hex/ios/HEXShared/TypingLog/TypingLogSession.swift
Ryan Vogel 0e7a1030a9
iOS: hold the bar to dictate, Learn how I type on, a plain centred Paste, and typing logs off (#2210)
* iOS: hold an empty part of the top bar to dictate

A tester found the Hex key (44 pt, in the strip) too small to hit quickly.
A still hold of 0.4 s (Apple's long press) anywhere on the bar with no word
under it now dictates exactly as holding the Hex key does: hold to talk,
release to finish. It reuses the Hex key's own path: a HexKeyGesture fed by
FullKeyboardView's touches, then the key's press (in-keyboard dictation arms)
and hexKeyHeld / hexKeyReleased, so without Full Access it shows the Full
Access hint, and a hold that can only open Hex opens Hex, as the key does.

The empty space is every touch nothing else takes in the bar: empty slots
(their buttons take no touches), the strip around Paste, Undo or a status,
the gaps beside the Hex key, and a bar with no suggestions. A word's slot
keeps its tap and its hold (Add to vocabulary, #2205). A tap on empty space
does nothing, and a slide past 10 pt cancels the hold. No hold while the bar
shows the Full Access hint or a notice, while a dictation records or
transcribes, or with the emoji panel or style menu up. Typing logs name the
source (bar_hold / bar_release).

Verified in the iOS 27.2 simulator (iPhone 17 Pro, a UIKit host app, Hex
keyboard with Full Access): holding an empty slot showed the recording panel
and releasing finished it; holding a suggestion ("The") and tapping empty
space did nothing; holds in the 2 pt gap left of the Hex key and past its
right edge took the Hex key's path (opened Hex, as the key does once
in-keyboard dictation is unavailable). On origin/dev the same hold did
nothing.

* iOS: Learn how I type is on by default

Settings › Privacy › Learn how I type now reads on when the switch was never
set (no key in the App Group: true). The toggle saves an explicit false when
turned off (UserDefaults.set on change), so "off" and "never set" are
distinct and nobody who turned it off is switched back on; no migration is
needed. Without an App Group (no Full Access) it stays off, as there is
nowhere to learn.

Every reader goes through TypingJournalSettings.isEnabled, so both sides
follow it: typing (TypingJournal.sharedIfEnabled in the full keyboard) and
dictation (the keyboard's DictationEditInference tracking in
learnsFromDictation, its learned fixes for in-keyboard dictation, and the
app's DictationPipeline fixes and raw-transcript sharing in
DictationController).

The switch's line now says what it does: "Learns on this iPhone from your
taps and the words you fix with Hex, never from what you write elsewhere"
(zh-Hans added; the old line is removed from the catalog).

Verified: TypingJournalLearningTests.testLearnHowITypeIsOnUntilTurnedOff
(an unset switch learns, one turned off stays off and stores nothing) in the
full xcodebuild test run.

* iOS: the bar's Paste is plain text, centred on the keyboard

The clipboard offer drew Paste as a chip (a filled background with a 15 pt
corner radius, 12.5 pt medium type) and centred it in the strip's bounds,
which leave out the Hex key, so it sat visibly left of the middle. Ryan
wanted no chip: plain text in the bar like a suggestion word.

- Paste (and Paste dictation) is now SF 17 pt regular in the bar words' ink
  (palette.stripText), with no background. The clipboard glyph stays, sized
  to the text's font (small scale), since it sits on the line beside the word.
- Paste and the Next keyboard chip (or the pair in a code field) centre on
  the keyboard's middle, where the middle slot's word centres
  (KeyboardStripView.barMidX = stripBarFrame.midX in the strip's
  coordinates), clamped inside the strip.
- Their line stays the bar's word line (textCenterY,
  KeyboardMetrics.stripTextCenter from #2207); the chip and line geometry
  of #2207 is unchanged.

Verified in the iOS 27.2 simulator (iPhone 17 Pro, a copied string through
simctl pbcopy): before, the chip spanned x 126-219 pt of a 402 pt keyboard
(centre 172); after, glyph and word span 169-232 (centre 201, the keyboard's
middle), on the same line as "The" in the middle slot.

* iOS: turn Record typing logs off once for everyone

The bar's "● Logging" mark shows while Settings › Privacy › Advanced ›
Record typing logs is on, and Ryan wants it gone. A one-time migration,
TypingLogSettings.turnOffOnce, switches the setting off for anyone who has it
on and records migrations.typingLogsOff.v1 in the App Group so it never runs
again: turning it back on afterwards keeps it on. It runs where either
process starts, the app's launch (before the simulator scenes' launch
argument) and the keyboard's viewDidLoad (before any typing log session), so
a keyboard updated before Hex is opened drops the mark too. The logs already
recorded stay, and so does the switch in Settings.

Nothing in a build turns it on: the key is set to true only by the switch's
consent dialog, the simulator-only --experiment-typing-logs launch argument,
and the Settings snapshot fixtures (settings-*-on scenes); no scheme,
ci_scripts or Xcode Cloud step passes either, so there was no build or
TestFlight default to remove.

Verified: TypingLogTests.testTypingLogsTurnOffOnceAndKeepWhatTheyRecorded
in the full xcodebuild test run, and in the iOS 27.2 simulator: with
experiments.typingLogs set to true and the flag removed from the keyboard's
defaults, showing the keyboard left it false and the flag true.
2026-11-21 12:11:58 -05:00

364 lines
14 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import CoreGraphics
import Foundation
import UIKit
/// Experiment (Record typing logs): every tap Hex's keyboard sees, where it landed, the key
/// it typed and the text that resulted, plus dictations, written to day files in the App
/// Group for 14 days so they can be exported from the app. Off by default; nothing is sent.
/// Separate from Learn how I type, which keeps only word pairs.
nonisolated struct TypingLogSettings {
static let enabledKey = "experiments.typingLogs"
private let defaults: UserDefaults?
init(defaults: UserDefaults? = UserDefaults(suiteName: KeyboardBridge.appGroup)) {
self.defaults = defaults
}
var isEnabled: Bool {
get { defaults?.bool(forKey: Self.enabledKey) ?? false }
nonmutating set { defaults?.set(newValue, forKey: Self.enabledKey) }
}
/// Set once `turnOffOnce()` has run; a later version turns it off again under a new key.
static let turnedOffKey = "migrations.typingLogsOff.v1"
/// Once per App Group (Nov 2026): Record typing logs goes off for everyone who had it on,
/// so the bar's Logging mark goes. The logs already recorded stay, and so does the switch
/// in Settings › Privacy › Advanced, which turns it back on for good.
func turnOffOnce() {
guard let defaults, !defaults.bool(forKey: Self.turnedOffKey) else { return }
if isEnabled { isEnabled = false }
defaults.set(true, forKey: Self.turnedOffKey)
}
static let launchArgument = "--experiment-typing-logs"
/// Simulator scenes pass `--experiment-typing-logs` to turn the experiment on.
func applyLaunchArguments(_ arguments: [String] = ProcessInfo.processInfo.arguments) {
if arguments.contains(Self.launchArgument) {
isEnabled = true
}
}
}
/// The field's text input traits, as names, for `session_start` and the skip rule.
nonisolated struct TypingLogTraits: Equatable, Sendable {
var keyboardType = "default"
var returnKeyType = "default"
var autocapitalization = "sentences"
var autocorrection = "default"
var spellChecking = "default"
var smartQuotes = "default"
var smartDashes = "default"
var smartInsertDelete = "default"
var inlinePrediction = "default"
var keyboardAppearance = "default"
var textContentType: String?
var isSecure = false
var enablesReturnKeyAutomatically = false
/// `UITextDocumentProxy.documentIdentifier`: changes with the field, not the app.
var document: String?
/// Why nothing is logged in this field, or nil to log it.
var skipReason: String? {
TypingLogPrivacy.skipReason(isSecure: isSecure, textContentType: textContentType.map(UITextContentType.init(rawValue:)))
}
/// Changes when the keyboard moves to another field or the field's traits change.
var signature: String {
[
keyboardType, returnKeyType, autocapitalization, autocorrection, spellChecking, smartQuotes,
smartDashes, smartInsertDelete, inlinePrediction, keyboardAppearance, textContentType ?? "",
isSecure ? "secure" : "", enablesReturnKeyAutomatically ? "auto-return" : "", document ?? "",
].joined(separator: "|")
}
var fields: [TypingLogField] {
[
TypingLogField("keyboardType", .string(keyboardType)),
TypingLogField("returnKeyType", .string(returnKeyType)),
TypingLogField("autocapitalization", .string(autocapitalization)),
TypingLogField("autocorrection", .string(autocorrection)),
TypingLogField("spellChecking", .string(spellChecking)),
TypingLogField("smartQuotes", .string(smartQuotes)),
TypingLogField("smartDashes", .string(smartDashes)),
TypingLogField("smartInsertDelete", .string(smartInsertDelete)),
TypingLogField("inlinePrediction", .string(inlinePrediction)),
TypingLogField("keyboardAppearance", .string(keyboardAppearance)),
TypingLogField("textContentType", .text(textContentType)),
TypingLogField("secure", .bool(isSecure)),
TypingLogField("enablesReturnKeyAutomatically", .bool(enablesReturnKeyAutomatically)),
]
}
}
extension TypingLogTraits {
@MainActor
init(_ traits: UITextInputTraits, document: UUID? = nil) {
keyboardType = Self.name(traits.keyboardType ?? .default)
returnKeyType = Self.name(traits.returnKeyType ?? .default)
autocapitalization = Self.name(traits.autocapitalizationType ?? .sentences)
autocorrection = Self.name(traits.autocorrectionType ?? .default)
spellChecking = Self.name(traits.spellCheckingType ?? .default)
smartQuotes = Self.name(traits.smartQuotesType ?? .default)
smartDashes = Self.name(traits.smartDashesType ?? .default)
smartInsertDelete = Self.name(traits.smartInsertDeleteType ?? .default)
inlinePrediction = Self.name(traits.inlinePredictionType ?? .default)
keyboardAppearance = Self.name(traits.keyboardAppearance ?? .default)
textContentType = traits.textContentType??.rawValue
isSecure = traits.isSecureTextEntry ?? false
enablesReturnKeyAutomatically = traits.enablesReturnKeyAutomatically ?? false
self.document = document?.uuidString
}
/// `UITextDocumentProxy.documentIdentifier`, or nil while UIKit has none. UIKit declares it
/// non-optional, but the keyboard's proxy returns nil early on (in `viewDidLoad`, and at
/// times later), and reading that nil as Swift's `UUID` traps (Debug keyboard crashes in
/// `viewDidLoad` and on a field change). Read through key-value coding instead.
static func documentIdentifier(of proxy: AnyObject) -> UUID? {
guard let object = proxy as? NSObject,
object.responds(to: NSSelectorFromString("documentIdentifier")) else { return nil }
return object.value(forKey: "documentIdentifier") as? UUID
}
/// Whether `next` is another field, or this field with other traits. A document UIKit
/// couldn't name yet (nil) matches any, so a field isn't split in two when it's named.
func isOtherField(than next: TypingLogTraits) -> Bool {
var current = self
var next = next
if current.document == nil || next.document == nil {
current.document = nil
next.document = nil
}
return current.signature != next.signature
}
static func name(_ type: UIKeyboardType) -> String {
switch type {
case .default: "default"
case .asciiCapable: "asciiCapable"
case .numbersAndPunctuation: "numbersAndPunctuation"
case .URL: "URL"
case .numberPad: "numberPad"
case .phonePad: "phonePad"
case .namePhonePad: "namePhonePad"
case .emailAddress: "emailAddress"
case .decimalPad: "decimalPad"
case .twitter: "twitter"
case .webSearch: "webSearch"
case .asciiCapableNumberPad: "asciiCapableNumberPad"
@unknown default: "raw:\(type.rawValue)"
}
}
static func name(_ type: UIReturnKeyType) -> String {
switch type {
case .default: "default"
case .go: "go"
case .google: "google"
case .join: "join"
case .next: "next"
case .route: "route"
case .search: "search"
case .send: "send"
case .yahoo: "yahoo"
case .done: "done"
case .emergencyCall: "emergencyCall"
case .continue: "continue"
@unknown default: "raw:\(type.rawValue)"
}
}
static func name(_ type: UITextAutocapitalizationType) -> String {
switch type {
case .none: "none"
case .words: "words"
case .sentences: "sentences"
case .allCharacters: "allCharacters"
@unknown default: "raw:\(type.rawValue)"
}
}
static func name(_ type: UITextAutocorrectionType) -> String {
switch type {
case .default: "default"
case .no: "no"
case .yes: "yes"
@unknown default: "raw:\(type.rawValue)"
}
}
static func name(_ type: UITextSpellCheckingType) -> String {
switch type {
case .default: "default"
case .no: "no"
case .yes: "yes"
@unknown default: "raw:\(type.rawValue)"
}
}
static func name(_ type: UITextSmartQuotesType) -> String {
switch type {
case .default: "default"
case .no: "no"
case .yes: "yes"
@unknown default: "raw:\(type.rawValue)"
}
}
static func name(_ type: UITextSmartDashesType) -> String {
switch type {
case .default: "default"
case .no: "no"
case .yes: "yes"
@unknown default: "raw:\(type.rawValue)"
}
}
static func name(_ type: UITextSmartInsertDeleteType) -> String {
switch type {
case .default: "default"
case .no: "no"
case .yes: "yes"
@unknown default: "raw:\(type.rawValue)"
}
}
static func name(_ type: UITextInlinePredictionType) -> String {
switch type {
case .default: "default"
case .no: "no"
case .yes: "yes"
@unknown default: "raw:\(type.rawValue)"
}
}
static func name(_ type: UIKeyboardAppearance) -> String {
switch type {
case .default: "default"
case .dark: "dark"
case .light: "light"
@unknown default: "raw:\(type.rawValue)"
}
}
}
/// Fields nothing is logged in. iOS never shows a third-party keyboard in a secure field,
/// but a field can still ask for a password, a code, or a card number without being secure.
nonisolated enum TypingLogPrivacy {
static let skippedContentTypes: Set<UITextContentType> = [
.password, .newPassword, .oneTimeCode,
.creditCardNumber, .creditCardSecurityCode, .creditCardType,
.creditCardExpiration, .creditCardExpirationMonth, .creditCardExpirationYear,
.creditCardName, .creditCardGivenName, .creditCardMiddleName, .creditCardFamilyName,
]
static func skipReason(isSecure: Bool, textContentType: UITextContentType?) -> String? {
if isSecure { return "secureTextEntry" }
if let type = textContentType, skippedContentTypes.contains(type) {
return "textContentType:\(type.rawValue)"
}
return nil
}
}
/// What a session line says about the keyboard and the iPhone. The host app can't be
/// known from a keyboard extension, so it is never guessed.
nonisolated struct TypingLogSessionInfo: Sendable {
/// `appear`, `field` (another field or new traits), or `enabled` (turned on while shown).
var trigger: String
/// `full` (Hex's keys) or `bar` (the dictation bar).
var surface: String
var traits: TypingLogTraits
var bounds: CGSize
var safeArea: UIEdgeInsets
var orientation: String
var appearance: String
var device: String
var system: String
var version: String
var build: String
var locale: String
var languages: [String]
/// The keyboard's own language (`primaryLanguage`) and the field's input mode.
var keyboardLanguage: String?
var inputMode: String?
var fullAccess: Bool
/// Other switches that change what the keys do.
var settings: [TypingLogField]
var fields: [TypingLogField] {
[
TypingLogField("trigger", .string(trigger)),
TypingLogField("surface", .string(surface)),
TypingLogField("document", .text(traits.document)),
TypingLogField("traits", .object(traits.fields)),
TypingLogField("bounds", .array([.pt(bounds.width), .pt(bounds.height)])),
TypingLogField("safeArea", Self.insets(safeArea)),
TypingLogField("orientation", .string(orientation)),
TypingLogField("appearance", .string(appearance)),
TypingLogField("device", .string(device)),
TypingLogField("system", .string(system)),
TypingLogField("version", .string(version)),
TypingLogField("build", .string(build)),
TypingLogField("locale", .string(locale)),
TypingLogField("languages", .strings(languages)),
TypingLogField("keyboardLanguage", .text(keyboardLanguage)),
TypingLogField("inputMode", .text(inputMode)),
TypingLogField("fullAccess", .bool(fullAccess)),
TypingLogField("settings", .object(settings)),
]
}
/// `[top, left, bottom, right]` in points.
static func insets(_ insets: UIEdgeInsets) -> TypingLogValue {
.array([.pt(insets.top), .pt(insets.left), .pt(insets.bottom), .pt(insets.right)])
}
/// The hardware model (`iPhone17,1`); the simulated one in the simulator.
static var deviceModel: String {
if let simulated = ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"] {
return "Simulator:\(simulated)"
}
var system = utsname()
uname(&system)
return withUnsafeBytes(of: &system.machine) { raw in
String(decoding: raw.prefix { $0 != 0 }, as: UTF8.self)
}
}
}
/// One `UITouch` sample, copied so tests can feed the same path.
nonisolated struct TypingLogTouchSample: Equatable, Sendable {
var point: CGPoint
/// `UITouch.timestamp`, seconds on the `CACurrentMediaTime` clock.
var timestamp: TimeInterval
var majorRadius: CGFloat = 0
var majorRadiusTolerance: CGFloat = 0
var force: CGFloat = 0
var maximumPossibleForce: CGFloat = 0
}
extension TypingLogTouchSample {
@MainActor
init(_ touch: UITouch, in view: UIView) {
point = touch.location(in: view)
timestamp = touch.timestamp
majorRadius = touch.majorRadius
majorRadiusTolerance = touch.majorRadiusTolerance
force = touch.force
maximumPossibleForce = touch.maximumPossibleForce
}
}
nonisolated enum TypingLogTouchPhase: String, Sendable {
case began, moved, ended, cancelled
}
/// The text around the cursor, as the host shows it.
nonisolated struct TypingLogContext: Equatable, Sendable {
var before: String?
var after: String?
var hasText: Bool
}