hex/ios/HEXMobile/SettingsComponents.swift
Ryan Vogel 33c2a4ed3a
iOS: choose QWERTY, QWERTZ, AZERTY or Dvorak per keyboard language (#2172)
* iOS: arrange each keyboard language's letters on another layout (engine)

TestFlight (build 56, iPhone 16 Pro, iOS 27.0.1): a German tester types on
the English keyboard but wants QWERTZ, which Apple's Settings offers and
Hex didn't. This adds KeyboardLetterLayout (own, QWERTY, QWERTZ, AZERTY,
Dvorak) and, per language, the layouts Apple's Keyboard Layout list offers
for it, observed black box in the iOS 27.0 simulator (Settings › General ›
Keyboard › Keyboards › Add New Keyboard, and each layout typed on in
Messages, read from screenshots and the accessibility tree only). Each
language's own (today's) layout stays first and is the default.

- KeyboardLanguage.letterRows(_:) builds the rows; the plain layouts are the
  same 26 letters in every language (as on Apple's). French's "– French"
  variants differ only by the ´ key Hex already leaves out, so French
  offers the plain three.
- letterHolds(on:) keeps the language's holds and, on a plain layout without
  the language's own letter keys, holds them right after their base, as
  Apple's German QWERTZ/QWERTY (A Ä…, O Ö…, U Ü…) and Spanish QWERTY (N Ñ Ń) do.
- KeyboardLayout takes letters:, with Apple's Dvorak geometry (delete ends
  row 1, row 2 from the edge, shift plus nine letters on narrower keys).
- Autocorrect's neighbouring-key cost reads the layout's arrangement
  (setKeys, partner included); the decoder, swipe typing, next-key growth
  and Adaptive touch already read the drawn keys, and Adaptive touch keys
  its contexts by the letters, so a new arrangement is a new context.
- LanguageSettings stores the choice per language in the App Group
  (settings.keyboardLanguages.layouts); unset or not offered is the
  language's own layout. Typing logs' layout lines name the letters.

Nothing changes for anyone who doesn't pick another layout: every language's
default rows equal today's (tested).

Verified: xcodebuild test, HEXMobile scheme, iPhone 17 simulator iOS 27.2:
498 tests, 0 failures (1 skipped, as before), with new KeyboardLayoutTests
for the offered layouts, plain rows, English QWERTZ (y/z swap, English's
holds, adjacency), plain-layout holds, Dvorak and per-language storage.

* iOS: Settings › Keyboard › Languages › Layout picks each language's layout

Each language the keys show (every chosen one, Automatic's while none is,
and only the first of English and Spanish together, whose keys both type on)
gets a Layout menu listing the layouts Apple offers for it, the current one
ticked, in the page's existing row and menu style, with zh-Hans strings.
The keyboard reads the choice for KeyboardLanguageList.layout's language, so
the bilingual English & Spanish keyboard uses the first language's layout;
without the App Group (no Full Access on an iPhone that keeps it from the
keyboard) every language types on its own layout, as before. Snapshot
fixtures take --keyboard-letters and the -on languages fixture shows English
on QWERTZ. README documents the observed layouts and behaviour.

Verified: xcodebuild test, HEXMobile scheme, iPhone 17 simulator iOS 27.2:
498 tests, 0 failures (1 skipped, as before), with new FullKeyboardEngineTests
for English QWERTZ typing (keys, decoder centres, swipe keys, holds), Spatial
autocorrect on QWERTZ, Adaptive touch contexts per layout and the shared
English & Spanish layout following the first language.
2026-11-21 10:41:12 +00:00

308 lines
11 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 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 on QWERTZ, 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.germanSpatialAutocorrect = on
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().setLetterLayout(on ? .qwertz : .qwerty, for: .english)
LanguageSettings().setLetterLayout(.azerty, for: .french)
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
}
}