mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-28 13:02:21 +01:00
* iOS keyboard: Adaptive touch learns personal key centres for the decoder (Experiments, off) Adds Adaptive touch, stages 1 and 2 of the adaptive-touch design: the keyboard learns where you land on each physical letter key, on this device, and Spatial autocorrect's decoder (TypingDecoder.Keys) and the suggestion strip read your taps with those personal centres. Hit rectangles, keycaps, key(at:) and Swipe typing are unchanged. - AdaptiveTouch.swift: fixed-size sums (4 rotating bins of 200 labelled taps) per physical key and context (letters, posture, orientation, split, Hex key side, width bin, plus one of two grip regimes); offsets in keycaps, hierarchically shrunk (key 20, row 50, keyboard 40), bounded to 0.3 keycap, 0.05 per promotion, fixed sigma. The decoder reads a context only after 400 labelled taps over 3 sessions, while the profile fits recent taps better than the stock centres; once it fits worse it falls back to stock at once and labels go to the other regime (a returning grip is taken back). The model serializes to 23,588 bytes: a protected file in the keyboard's own container, excluded from backup, never in the App Group, written off the main thread; without Full Access, memory only. Reset generation in the App Group drops RAM and file, and stale writes can't resurrect. - AdaptiveTouchLabels.swift: RAM-only spans. A tap teaches only with evidence of intent, and only once the next word shows its word stood: a word left as typed (only letters the key under the finger typed), a same-length picked suggestion, a word kept over an autocorrection (undo or tapping it), and an erased letter retyped as a neighbour. Never autocorrections left in place, swipes, slides, strip touches, accent picks, or secure, code, email, URL or no-autocorrect fields. - No new automatic rewrites: AutocorrectEngine.decoderStockKeys; space applies a personal reading only if the stock centres also clear it by the margin (TypingDecoder.replaces), else the stock decision. Experiment on replaces Learn how I type's per-letter offsets for decoding (its word-level learning stays). Off, the engine has no AdaptiveTouch and behaves exactly as before. - Hooks: FullKeyboardEngine (touch-down point, letter commit, delete, undo, word ends, picks, swipes, cursor, field), FullKeyboardView.syncSettings, the keyboard saving on hide. KeyboardTextTarget gains isSecureTextEntry. Verified: xcodebuild test on an iPhone 17 simulator (iOS 27.2), 440 tests, 0 failures (1 skipped, existing); new cases in FullKeyboardEngineTests and AutocorrectEngineTests cover label admission, excluded fields and swipes, no hit-rectangle change, contexts, grip fallback, evidence floor, untrained equals off, the file cap, backup exclusion, damage and reset, and the no-new-rewrite guard. * iOS: Settings › Experiments › Adaptive touch, with its status and Reset touch learning The switch (off by default, App Group key experiments.adaptiveTouch) reads "Learns where you land on the keys on this device. Stores averages, not what you type." While on, a status line says Session only (Full Access not confirmed: the keyboard keeps its averages in memory until it closes), Learning: n of 400 taps, or Active, from the counts the keyboard reports (adaptiveTouch.summary.*); and Reset touch learning, after a confirmation, bumps the reset generation every keyboard honours. Delete what Hex learned (Typing insights) resets it too. Strings have zh-Hans. The settings-experiments-on fixture shows it on, partway through learning. Verified: built and tested with the previous commit (440 tests, 0 failures). * iOS keyboard: Adaptive touch's guard follows the Experiment-off decoder, and its grip check reads each axis Three refinements found while replaying the public benchmark: - No new automatic rewrites now means none the keyboard wouldn't make with the Experiment off: AutocorrectEngine.decoderStockKeys becomes decoderBaselineKeys, the centres Spatial autocorrect reads without Adaptive touch (stock, or moved by Learn how I type's per-letter offsets). Those offsets still never move the centres the decoder reads while the Experiment is on (no stacking), so journal users keep its correction authority as the ceiling. Before, the baseline was always the stock centres, which let a journal user's rewrites change on enabling. - The fit monitor keeps separate x and y log-likelihood gains. A grip that shifts taps sideways while the learned up/down offsets still fit used to average out: in the right-to-left grip replay the profile flapped in and out ~80 times and kept breaking words. Now a profile falls back once either axis fits worse than the stock centres (-0.06 nats per tap over 32 labels) and is only taken back when neither axis misfits. - TypingDecoder.replaces first scores the reading letter for letter (or with one untyped letter), an alignment the search also tries, and skips the one-word search when that already clears the margin: the guard runs on most letters. Verified: xcodebuild test on the iPhone 17 simulator (iOS 27.2), 446 tests, 0 failures (1 skipped, existing), including a new case for the journal baseline. * iOS keyboard: Adaptive touch switches grip profiles only once one had the evidence to be used The public replay showed a false switch while learning the steady base typist: the early, thin profile (368 taps) misfit one axis by noise and labels moved to a fresh second profile, throwing that evidence away. Before the activation floor nothing is in use, so a new grip now just mixes into what is learned; the per-axis fallback and switching apply once the profile is eligible (400 taps, 3 sessions). Also skips the accent comparison in TypingDecoder.replaces when it can't lower the margin (it allocates), the guard's remaining per-letter cost on the simulator. Adds AutocorrectEngineTests.testPersonalCentresKeepNamesYourWordsAndWordsTypedRight: with every centre pushed to the bound, words typed right, lowercase names and days, Contacts-style terms and shorthand come out exactly as with the Experiment off. Verified: xcodebuild test on the iPhone 17 simulator (iOS 27.2), rebased ond65f5f76: 452 tests, 0 failures (1 skipped, existing). * iOS keyboard: test that Adaptive touch never joins words its own way Rebased onto the autocorrect fixes (#2144). Their new automatic rewrites go through finishWord, so Adaptive touch hooks in there: a word space or a closing mark autocorrects teaches nothing, a revised word before it ("well" to "we'll") teaches nothing either, and two words joined at the space bar's edge drop everything pending. AutocorrectEngine.merge reads the centres the keyboard reads without Adaptive touch, so personal centres never decide a join (folded into the first two commits while resolving the rebase). Adds AutocorrectEngineTests.testPersonalCentresNeverJoinWordsTheirOwnWay: with a strong personal profile in use, "the deli" + a space at the bar's edge + "ate" still becomes "the delicate", as with the Experiment off. Verified: xcodebuild test on the iPhone 17 simulator (iOS 27.2) on8c93f6f5: 461 tests, 0 failures (1 skipped, existing). * iOS keyboard: Adaptive touch's guard takes the next reading the baseline clears, not a second search When a personal reading doesn't clear the baseline margin, the guard used to run a whole second decode with the baseline centres to find their own decision. On the public benchmark that happened on ~5% of checked letters and cost ~0.13 ms each, pushing the simulator's English per-letter p95 up to +0.1-0.16 ms. Now it takes the next of the personal readings that the baseline centres also clear by the margin (TypingDecoder.replaces, mostly without a search), or none: still never a rewrite the keyboard wouldn't make with the Experiment off. Only a two-word reading, which replaces can't score, still asks the baseline decode. Verified: xcodebuild test on the iPhone 17 simulator (iOS 27.2) on8c93f6f5: 461 tests, 0 failures (1 skipped, existing). Held-out benchmark on the same simulator, profile learned on the 300 dev sentences: WER unchanged by this (EN 5.24% -> 5.16%, ES 8.34% -> 8.26%); per-letter engine p95 against Experiment off, two runs each: EN -0.09 / +0.02 ms, ES -0.01 / +0.04 ms; peak footprint -0.11 / +0.00 MB. * iOS: README documents Adaptive touch and what verified it Adds Settings › Experiments › Adaptive touch to the capabilities (what it learns from, what it keeps and where, when the decoder uses it, the no-new-rewrite guard) and to the Experiments page list, and a verification entry: the unit tests, the held-out benchmark on the simulator (Experiment off and on without evidence match the keyboard without it on all 2,000 items in English and Spanish; with a learned profile EN 5.24% -> 5.16%, ES 8.34% -> 8.26% WER, none typed right broken), the grip-change replay (38 broken words without the fallback, none with it), latency and footprint, and what remains unverified without a physical iPhone. Verified: the numbers are from this branch at17af3357on8c93f6f5(replay tables in the experiment folder, not committed).
305 lines
10 KiB
Swift
305 lines
10 KiB
Swift
import SwiftUI
|
||
|
||
/// The home screen's four settings pages.
|
||
enum SettingsPage: String, Hashable, CaseIterable {
|
||
case dictation
|
||
case keyboard
|
||
case privacy
|
||
case experiments
|
||
|
||
var title: String {
|
||
switch self {
|
||
case .dictation: String(localized: "Dictation")
|
||
case .keyboard: String(localized: "Keyboard")
|
||
case .privacy: String(localized: "Privacy")
|
||
case .experiments: String(localized: "Experiments")
|
||
}
|
||
}
|
||
|
||
var icon: String {
|
||
switch self {
|
||
case .dictation: "waveform"
|
||
case .keyboard: "keyboard"
|
||
case .privacy: "lock"
|
||
case .experiments: "testtube.2"
|
||
}
|
||
}
|
||
}
|
||
|
||
/// A settings page: a short scrolling column of cards under an inline title.
|
||
struct SettingsPageScaffold<Content: View>: View {
|
||
let title: LocalizedStringKey
|
||
@ViewBuilder var content: Content
|
||
|
||
var body: some View {
|
||
ScrollView {
|
||
VStack(alignment: .leading, spacing: 12) {
|
||
content
|
||
}
|
||
.frame(maxWidth: 500)
|
||
.padding(.horizontal, 20)
|
||
.padding(.top, 8)
|
||
.padding(.bottom, 28)
|
||
.frame(maxWidth: .infinity)
|
||
}
|
||
.scrollBounceBehavior(.basedOnSize)
|
||
.scrollDismissesKeyboard(.interactively)
|
||
.defaultScrollAnchor(SettingsSnapshotFixture.scrollsToEnd ? .bottom : .top)
|
||
.background(HexTheme.bgDeep.ignoresSafeArea())
|
||
.navigationTitle(title)
|
||
.navigationBarTitleDisplayMode(.inline)
|
||
.toolbarBackground(HexTheme.bgDeep, for: .navigationBar)
|
||
}
|
||
}
|
||
|
||
/// Rows on `bgBase` with the theme's corner radius.
|
||
struct SettingsCard<Content: View>: View {
|
||
@ViewBuilder var content: Content
|
||
|
||
var body: some View {
|
||
VStack(spacing: 0) {
|
||
content
|
||
}
|
||
.background(
|
||
HexTheme.bgBase,
|
||
in: RoundedRectangle(cornerRadius: HexTheme.cardRadius, style: .continuous)
|
||
)
|
||
}
|
||
}
|
||
|
||
/// A small label above a card, such as Privacy's "Advanced".
|
||
struct SettingsSectionHeader: View {
|
||
let title: LocalizedStringKey
|
||
|
||
var body: some View {
|
||
Text(title)
|
||
.font(.system(size: 13, weight: .medium))
|
||
.foregroundStyle(HexTheme.textMuted)
|
||
.padding(.leading, 16)
|
||
.padding(.top, 12)
|
||
}
|
||
}
|
||
|
||
struct SettingsDivider: View {
|
||
var leading: CGFloat = 16
|
||
|
||
var body: some View {
|
||
Rectangle()
|
||
.fill(HexTheme.borderWeak)
|
||
.frame(height: 0.5)
|
||
.padding(.leading, leading)
|
||
}
|
||
}
|
||
|
||
/// A row's title, and its one-line description when it has one.
|
||
struct SettingsRowLabel: View {
|
||
let title: String
|
||
var detail: String?
|
||
|
||
var body: some View {
|
||
VStack(alignment: .leading, spacing: 2) {
|
||
Text(title)
|
||
.font(.system(size: 15, weight: .regular))
|
||
.foregroundStyle(HexTheme.textBase)
|
||
if let detail {
|
||
Text(detail)
|
||
.font(.system(size: 12))
|
||
.foregroundStyle(HexTheme.textMuted)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// A switch with its one-line description.
|
||
struct SettingsToggleRow: View {
|
||
let title: String
|
||
var detail: String?
|
||
@Binding var isOn: Bool
|
||
|
||
var body: some View {
|
||
Toggle(isOn: $isOn) {
|
||
SettingsRowLabel(title: title, detail: detail)
|
||
}
|
||
.tint(HexTheme.success)
|
||
.padding(.horizontal, 16)
|
||
.padding(.vertical, 10)
|
||
.frame(minHeight: 50)
|
||
}
|
||
}
|
||
|
||
/// A row that opens something: a page (chevron) or another app (arrow).
|
||
struct SettingsLinkLabel: View {
|
||
let title: String
|
||
var icon: String?
|
||
var trailingIcon = "chevron.right"
|
||
|
||
var body: some View {
|
||
HStack(spacing: 12) {
|
||
if let icon {
|
||
Image(systemName: icon)
|
||
.font(.system(size: 15, weight: .regular))
|
||
.foregroundStyle(HexTheme.textMuted)
|
||
.frame(width: 22)
|
||
}
|
||
Text(title)
|
||
.font(.system(size: 15, weight: .regular))
|
||
.foregroundStyle(HexTheme.textBase)
|
||
Spacer(minLength: 8)
|
||
Image(systemName: trailingIcon)
|
||
.font(.system(size: 13, weight: .medium))
|
||
.foregroundStyle(HexTheme.textMuted)
|
||
}
|
||
.padding(.horizontal, 16)
|
||
.frame(minHeight: 50)
|
||
.contentShape(Rectangle())
|
||
}
|
||
}
|
||
|
||
/// A menu's current value with the up-down chevron.
|
||
struct SettingsMenuValue: View {
|
||
let value: String
|
||
|
||
var body: some View {
|
||
HStack(spacing: 5) {
|
||
Text(value)
|
||
.font(.system(size: 15, weight: .regular))
|
||
.foregroundStyle(HexTheme.textMuted)
|
||
.lineLimit(1)
|
||
Image(systemName: "chevron.up.chevron.down")
|
||
.font(.system(size: 11, weight: .medium))
|
||
.foregroundStyle(HexTheme.textMuted)
|
||
}
|
||
.padding(.vertical, 6)
|
||
.contentShape(Rectangle())
|
||
}
|
||
}
|
||
|
||
/// A small segmented control in the settings rows' style.
|
||
struct SettingsSegments<Item: Hashable>: View {
|
||
let items: [Item]
|
||
let selected: Item
|
||
let label: KeyPath<Item, String>
|
||
let onSelect: (Item) -> Void
|
||
|
||
var body: some View {
|
||
HStack(spacing: 2) {
|
||
ForEach(items, id: \.self) { item in
|
||
let isSelected = item == selected
|
||
Button {
|
||
onSelect(item)
|
||
} label: {
|
||
Text(item[keyPath: label])
|
||
.font(.system(size: 13, weight: .medium))
|
||
.lineLimit(1)
|
||
.fixedSize(horizontal: true, vertical: false)
|
||
.foregroundStyle(isSelected ? HexTheme.textBase : HexTheme.textMuted)
|
||
.padding(.horizontal, 10)
|
||
.frame(height: 28)
|
||
.background(
|
||
isSelected ? Color.white.opacity(0.14) : Color.clear,
|
||
in: RoundedRectangle(cornerRadius: 7, style: .continuous)
|
||
)
|
||
.contentShape(RoundedRectangle(cornerRadius: 7, style: .continuous))
|
||
}
|
||
.buttonStyle(.plain)
|
||
}
|
||
}
|
||
.fixedSize(horizontal: true, vertical: false)
|
||
.padding(2)
|
||
.background(
|
||
Color.white.opacity(0.055),
|
||
in: RoundedRectangle(cornerRadius: 9, style: .continuous)
|
||
)
|
||
}
|
||
}
|
||
|
||
/// Simulator scenes for the home screen and its pages (`--snap-state <name>`):
|
||
///
|
||
/// - `settings-home`: home, everything ready. `setup`: home, keyboard added but Full Access
|
||
/// not confirmed yet. `setup-sheet`: the same, with the setup sheet open;
|
||
/// `setup-sheet-microphone`: the sheet before iOS has asked for the microphone.
|
||
/// - `settings-<page>` opens a page (`dictation`, `keyboard`, `privacy`, `experiments`) with
|
||
/// every switch at its default; `-on` turns the switches on, `-end` starts scrolled to the end.
|
||
/// `settings-keyboard-languages[-on]` opens Keyboard › Languages.
|
||
/// `settings-privacy-confirm` opens Record typing logs' consent dialog.
|
||
///
|
||
/// `KeyboardSetupMonitor.refresh` and `DictationController` supply the matching state.
|
||
enum SettingsSnapshotFixture {
|
||
static let scene: String? = {
|
||
let args = ProcessInfo.processInfo.arguments
|
||
guard let idx = args.firstIndex(of: "--snap-state"), idx + 1 < args.count else { return nil }
|
||
let value = args[idx + 1]
|
||
return value.hasPrefix("settings-") || value.hasPrefix("setup-sheet") ? value : nil
|
||
}()
|
||
|
||
static var initialPath: [SettingsPage] {
|
||
guard let scene else { return [] }
|
||
let name = scene.dropFirst("settings-".count).split(separator: "-").first.map(String.init)
|
||
return name.flatMap(SettingsPage.init(rawValue:)).map { [$0] } ?? []
|
||
}
|
||
|
||
static var showsSetupSheet: Bool {
|
||
scene?.hasPrefix("setup-sheet") == true
|
||
}
|
||
|
||
/// `settings-privacy-confirm`: Record typing logs' consent dialog, open.
|
||
static var confirmsTypingLogs: Bool {
|
||
scene?.hasSuffix("-confirm") == true
|
||
}
|
||
|
||
static var scrollsToEnd: Bool {
|
||
scene?.hasSuffix("-end") == true
|
||
}
|
||
|
||
/// `settings-experiments-on`: Adaptive touch partway through learning, as a keyboard with
|
||
/// Full Access reports it.
|
||
static var adaptiveTouchStatus: AdaptiveTouchStatus? {
|
||
guard let scene, scene.hasPrefix("settings-experiments") else { return nil }
|
||
return scene.contains("-on") ? .learning(taps: 240) : nil
|
||
}
|
||
|
||
/// `settings-keyboard-languages[-on]`: Keyboard › Languages, open (Automatic, or with
|
||
/// `-on` English, Français and Русский with Switch dictation too).
|
||
static var opensKeyboardLanguages: Bool {
|
||
scene?.hasPrefix("settings-keyboard-languages") == true
|
||
}
|
||
|
||
/// Writes the page's switches to the App Group so every run renders the same.
|
||
@MainActor
|
||
static func applyDefaults() {
|
||
guard let scene, scene.hasPrefix("settings-") else { return }
|
||
let on = scene.contains("-on")
|
||
let keyboard = FullKeyboardSettings()
|
||
keyboard.isEnabled = on || opensKeyboardLanguages
|
||
keyboard.autoCapitalization = true
|
||
// `--hex-key left` renders the page with the Hex key on the left.
|
||
let args = ProcessInfo.processInfo.arguments
|
||
keyboard.hexKeyOnLeft = args.firstIndex(of: FullKeyboardSettings.hexKeyLaunchArgument)
|
||
.flatMap { $0 + 1 < args.count ? args[$0 + 1] : nil } == "left"
|
||
keyboard.autocorrect = true
|
||
keyboard.spatialAutocorrect = true
|
||
keyboard.suggestSwearWords = on
|
||
keyboard.keyPopups = true
|
||
keyboard.haptics = true
|
||
keyboard.emoji = true
|
||
keyboard.swipeTyping = true
|
||
let emojiUsage = EmojiUsageStore()
|
||
emojiUsage.clear()
|
||
if on {
|
||
emojiUsage.record("🎉")
|
||
}
|
||
LanguageSettings().keyboardLanguages = on ? [.english, .french, .russian] : []
|
||
LanguageSettings().currentKeyboardLanguage = nil
|
||
LanguageSettings().dictationFollowsKeyboard = on
|
||
CleanupTaggerSettings().isEnabled = on
|
||
AppleIntelligenceCleanupSettings().isEnabled = false
|
||
CustomVocabularySettings().isEnabled = on
|
||
CustomVocabularySettings().terms = on ? ["OpenCode", "SwiftUI", "TestFlight"] : []
|
||
DictationTranslationSettings().isEnabled = on
|
||
DictationTranslationSettings().targetLanguage = "ja"
|
||
TypingJournalSettings().isEnabled = on
|
||
TypingLogSettings().isEnabled = on
|
||
HinglishSettings().isEnabled = on
|
||
AdaptiveTouchSettings().isEnabled = on
|
||
}
|
||
}
|