mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-28 13:02:21 +01:00
Steps 3 and 4 of the phone side, on the shared reader's latest (21cdab23). - Settings › Keyboard › Typing configs (beside Vocabulary, only while the experiment is on): Hex defaults first, then every kept config newest first with its status (In use, Best so far, applied or opened when), Use on each row (one tap, deletes nothing), and Delete all. A config's page shows its facts (based on, made from another iPhone's typing), Use or Use Hex defaults instead, Rename, Share (the kept file, unchanged) and Delete, and its parts with their switches (TypingConfigParts, shared with the review sheet), applied at once while it is the one in use. - History: never refuses a new config. At 20 the oldest that is neither active nor best so far goes, and the review names it before Apply (replaces the old refusal). Not now keeps the parts switched off. Records this phone's export ids. - Experiment off: the sheet's first action is Turn on typing configs, which shows the review at once; Open Experiments stays as the quieter second. - The review now reads the keyboards the Hex keyboard recorded (TypingConfigSettings .keyboards) instead of a keyboard the app built (TypingConfigKeyboard.swift removed), and each item's own list, position, evidence and cleaned text instead of indexing by path; the note is the review's cleaned one. With no keyboard recorded yet the sheet says so under For another keyboard. hiddenCharacters has its sentence. The active config is compiled again when Hex comes to the foreground and a keyboard was recorded since. - Delete what Hex learned also deletes every typing config and goes back to Hex defaults; its confirmation says so. - Export for your agent (Typing logs, experiment on): the warning sheet every time (design §5's wording, a variant for fewer days), the days to include, then one zip: the bundled package (ios/TypingConfig/package as a folder resource), the chosen logs and state/ (phone.json as state.md defines it, the recorded keyboards' layout; vocabulary.json with each word's model cost and spell-checker answer). Deleted once the share sheet closes. - Hex's own dictation (handed to Hex, Action Button) applies the active config's dictation fixes after Learn how I type's, never to a translated dictation (TypingConfigDictation). - Strings in English and Simplified Chinese. Verified on the Studio (iOS 27.2): TypingLogTests 15 of 15 (history at the limit, apply and go back, dictation fixes off for translation); every screen on iPhone 17 Pro and iPhone SE (3rd gen) in English and 简体中文; the export of two real days (6.6 MB of logs) is a 772 KB zip, built in about 2.5 s from Continue; its state/ read by the package's overview.py; the share sheet offers Copy, Save to Files and More (AirDrop and other apps don't show on the simulator). Through the real keyboard (Full Access granted in the simulator's TCC database, the keyboard's typing log and Full Access report confirming it), a tap 3.35 pt inside r types R with Hex defaults and E with a key-off config applied through the review sheet (e's right edge +0.2, word-rule evidence), the keyboard closed and opened in between.
188 lines
8.1 KiB
Swift
188 lines
8.1 KiB
Swift
import Foundation
|
||
import Observation
|
||
import SwiftUI
|
||
import UIKit
|
||
|
||
/// A file that arrived to be opened as a typing config: from Files, a share sheet's Open in
|
||
/// Hex, AirDrop or Mail. Untrusted until the shared reader has read it.
|
||
struct TypingConfigArrival: Identifiable, Equatable {
|
||
enum Content: Equatable {
|
||
case file(Data)
|
||
/// Over `TypingConfigLimits.maxBytes`: never read.
|
||
case tooLarge(bytes: Int)
|
||
case unreadable
|
||
}
|
||
|
||
let id = UUID()
|
||
/// The file's name without its extension, cleaned for display.
|
||
let name: String
|
||
let content: Content
|
||
|
||
var data: Data? {
|
||
if case .file(let data) = content { data } else { nil }
|
||
}
|
||
}
|
||
|
||
/// Typing configs arriving (`.onOpenURL` with a `.mhexconfig`): each file is read once, at most
|
||
/// 64 KB, and waits in line for its sheet. Nothing is applied or kept until the person chooses on
|
||
/// the sheet: opening a file never changes typing.
|
||
@MainActor
|
||
@Observable
|
||
final class TypingConfigInbox {
|
||
static let shared = TypingConfigInbox()
|
||
nonisolated static let fileExtension = "mhexconfig"
|
||
/// How much of a file's name the sheet and the history show.
|
||
nonisolated static let nameLimit = 60
|
||
|
||
/// The sheet shows the first; the rest wait their turn.
|
||
private(set) var queue: [TypingConfigArrival] = []
|
||
/// The sheet stepped aside for Settings › Experiments (Typing configs off): the files stay
|
||
/// in line and their sheet comes back when the switch turns on.
|
||
private(set) var isParked = false
|
||
/// Settings › Experiments, when the sheet's Open Experiments asked for it.
|
||
var opensExperiments = false
|
||
|
||
var current: TypingConfigArrival? { queue.first }
|
||
var waiting: Int { max(0, queue.count - 1) }
|
||
|
||
nonisolated static func handles(_ url: URL) -> Bool {
|
||
url.isFileURL && url.pathExtension.lowercased() == fileExtension
|
||
}
|
||
|
||
/// Reads `url` off the main thread and puts it in line. The same bytes already in line
|
||
/// aren't added twice.
|
||
func receive(_ url: URL) {
|
||
Task {
|
||
let arrival = await Task.detached(priority: .userInitiated) { Self.read(url) }.value
|
||
if let data = arrival.data, queue.contains(where: { $0.data == data }) { return }
|
||
queue.append(arrival)
|
||
isParked = false
|
||
TypingConfigSheetPresenter.update(for: self)
|
||
}
|
||
}
|
||
|
||
/// The sheet's file is done with (applied, kept for later or closed): the next one shows.
|
||
func finishCurrent() {
|
||
guard !queue.isEmpty else { return }
|
||
queue.removeFirst()
|
||
TypingConfigSheetPresenter.update(for: self)
|
||
}
|
||
|
||
/// Open Experiments: the sheet steps aside and Settings › Experiments opens at the switch.
|
||
func parkForExperiments() {
|
||
isParked = true
|
||
opensExperiments = true
|
||
TypingConfigSheetPresenter.update(for: self)
|
||
}
|
||
|
||
/// Experiments' switch turned on with files still in line: their sheet shows again.
|
||
func experimentTurnedOn() {
|
||
guard isParked else { return }
|
||
isParked = false
|
||
TypingConfigSheetPresenter.update(for: self)
|
||
}
|
||
|
||
func closeAll() {
|
||
queue.removeAll()
|
||
isParked = false
|
||
TypingConfigSheetPresenter.update(for: self)
|
||
}
|
||
|
||
/// The file's bytes, or why there are none, never reading more than the limit allows. A
|
||
/// copy iOS put in Documents/Inbox (Open in Hex, AirDrop, Mail) is deleted once read.
|
||
nonisolated static func read(_ url: URL, limit: Int = TypingConfigLimits.maxBytes) -> TypingConfigArrival {
|
||
let name = displayName(url.deletingPathExtension().lastPathComponent)
|
||
let scoped = url.startAccessingSecurityScopedResource()
|
||
defer {
|
||
if scoped { url.stopAccessingSecurityScopedResource() }
|
||
if url.path.contains("/Documents/Inbox/") { try? FileManager.default.removeItem(at: url) }
|
||
}
|
||
var content = TypingConfigArrival.Content.unreadable
|
||
var coordinationError: NSError?
|
||
NSFileCoordinator().coordinate(readingItemAt: url, options: .withoutChanges, error: &coordinationError) { readURL in
|
||
content = readContent(readURL, limit: limit)
|
||
}
|
||
return TypingConfigArrival(name: name, content: content)
|
||
}
|
||
|
||
nonisolated private static func readContent(_ url: URL, limit: Int) -> TypingConfigArrival.Content {
|
||
if let size = try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize, size > limit {
|
||
return .tooLarge(bytes: size)
|
||
}
|
||
guard let handle = try? FileHandle(forReadingFrom: url) else { return .unreadable }
|
||
defer { try? handle.close() }
|
||
// A size the file provider didn't report, or got wrong: read one byte past the limit.
|
||
guard let data = try? handle.read(upToCount: limit + 1) else { return .unreadable }
|
||
if data.count > limit {
|
||
let size = (try? handle.seekToEnd()).map(Int.init) ?? data.count
|
||
return .tooLarge(bytes: size)
|
||
}
|
||
return data.isEmpty ? .unreadable : .file(data)
|
||
}
|
||
|
||
nonisolated private static func safe(_ raw: String, keepsNewlines: Bool) -> String {
|
||
let scalars = raw.unicodeScalars.filter { scalar in
|
||
(keepsNewlines && scalar == "\n") || (!CharacterSet.controlCharacters.contains(scalar)
|
||
&& !(0x202A...0x202E).contains(scalar.value)
|
||
&& !(0x2066...0x2069).contains(scalar.value)
|
||
&& scalar.value != 0x200E && scalar.value != 0x200F)
|
||
}
|
||
return String(String.UnicodeScalarView(scalars)).trimmingCharacters(in: .whitespacesAndNewlines)
|
||
}
|
||
|
||
/// A name safe to show: no control or direction-changing characters, at most `nameLimit`.
|
||
nonisolated static func displayName(_ raw: String) -> String {
|
||
let cleaned = safe(raw, keepsNewlines: false)
|
||
return cleaned.count > nameLimit ? String(cleaned.prefix(nameLimit - 1)) + "…" : cleaned
|
||
}
|
||
}
|
||
|
||
/// Shows the typing config sheet over whatever is on screen (Home, a Settings page, the setup
|
||
/// sheet or Typing logs), so a file that arrives is never lost behind another sheet.
|
||
@MainActor
|
||
enum TypingConfigSheetPresenter {
|
||
private static weak var controller: UIViewController?
|
||
/// The sheet's content height, so a short message sits in a short sheet as the setup
|
||
/// sheet does; the review grows to the full height and scrolls.
|
||
private static var contentHeight: CGFloat = 320
|
||
|
||
static func contentHeightChanged(_ height: CGFloat) {
|
||
guard abs(height - contentHeight) > 0.5 else { return }
|
||
contentHeight = height
|
||
guard let sheet = controller?.sheetPresentationController else { return }
|
||
sheet.animateChanges { sheet.invalidateDetents() }
|
||
}
|
||
|
||
static func update(for inbox: TypingConfigInbox) {
|
||
if inbox.current == nil || inbox.isParked {
|
||
controller?.dismiss(animated: true)
|
||
controller = nil
|
||
return
|
||
}
|
||
guard controller == nil else { return }
|
||
let scene = UIApplication.shared.connectedScenes
|
||
.compactMap { $0 as? UIWindowScene }
|
||
.first { $0.activationState == .foregroundActive } ?? UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first
|
||
guard var top = scene?.keyWindow?.rootViewController else {
|
||
// Opened cold: the window comes a moment later.
|
||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { update(for: inbox) }
|
||
return
|
||
}
|
||
while let presented = top.presentedViewController, !presented.isBeingDismissed {
|
||
top = presented
|
||
}
|
||
let host = UIHostingController(rootView: TypingConfigSheet(inbox: inbox))
|
||
host.view.backgroundColor = UIColor(HexTheme.bgDeep)
|
||
host.overrideUserInterfaceStyle = .dark
|
||
// It stays until it's closed: a swipe down doesn't drop the file.
|
||
host.isModalInPresentation = true
|
||
if let sheet = host.sheetPresentationController {
|
||
sheet.detents = [.custom(identifier: .init("content")) { context in
|
||
min(contentHeight, context.maximumDetentValue)
|
||
}]
|
||
sheet.prefersGrabberVisible = false
|
||
}
|
||
controller = host
|
||
top.present(host, animated: true)
|
||
}
|
||
}
|