mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-22 21:23:02 +01:00
What was wrong: iOS creates a new KeyboardViewController almost every time the keyboard comes up inside one HEXKeyboard process. Three things stayed behind after each presentation (~0.44 MB per empty show, ~0.82 MB once a word was typed) until iOS killed the keyboard over its memory limit and fell back to the system keyboard: 1. KeyboardLocalDictation built a new WKWebView (KeyboardWebCapture) for every controller and never detached it from KeyboardInputView when the keyboard hid or deallocated. WebKit's process-wide observers kept each WKWebView alive, and its Auto Layout engine kept the whole dismissed KeyboardInputView and FullKeyboardView alive with it. 2. On iOS 27, UIKit keeps every UIInputView shell alive in ObjC associated storage after its controller deallocates, so any subviews Hex left attached (FullKeyboardView, the bar, KeyboardBackdropView's UIVisualEffectView) stayed in memory too. In hosts with an autofocusing inputAccessoryView (#2302), iOS also keeps earlier controllers alive without calling viewWillDisappear, leaving their views and 4 Hz poll timers running. 3. EmojiLibrary.load built a new ~0.8 MB index per FullKeyboardView instead of sharing one copy per process like TypingDecoderModel and GermanCapitals. What changed (and what was replaced): - Replaced per-controller WKWebView creation with one shared KeyboardWebCapture per extension process, guarded by KeyboardCaptureOwnership so only the current owner (or any caller while parked with no owner) can detach, park, or evict it on a memory warning. A stale controller that hid or received a memory warning drops only its own pointer instead of stopping a newer keyboard's active recording. - Replaced eager KeyboardBackdropView allocation with a lazy backdrop created only while KeyboardsOnScreen.isOverAnother is true. KeyboardInputView records weak references to only the subviews Hex mounted (surface, backdrop, barEmojiPanel) and removes those exact views in viewDidDisappear and deinit without touching UIKit's own views. - Superseded controllers in the same named field (KeyboardsOnScreen.isSuperseded) stop their poll timer and unmount their surface; if the newer keyboard above leaves while the older one is still on screen, restoreRetiredKeyboard() rebuilds only its surface and poll timer without handing off number pads, auto-starting dictation, or resetting its cold-start job. Cleared handOffWaitsForPosture on appear, disappear, teardown, and retire. - Added EmojiLibrary.bundled(language:bundle:) and EmojiLibrary.evictCached() to share one index across presentations until a memory warning. Checked: - Release on iPhone Air iOS 27.2 simulator vs origin/dev: - 30 hide/shows + 20 Apple switches: 46.35 MB (peak 54.71 MB) -> 25.25 MB (peak 33.57 MB); FullKeyboardView 51 -> 1, WKWebView 51 -> 1, KeyboardBackdropView 51 -> 0. - 6 switches in autofocus inputAccessoryView host: 28.50 MB -> 24.96 MB (1 live FullKeyboardView, 1 WKWebView, 1 backdrop on the top keyboard). - First-frame commit time (20 shows): 1.19 ms median (new controller) vs 1.25 ms on dev; 15.66 ms when forcibly reusing one controller; keys present across Messages, Safari address bar and web fields, Spotlight, two-field focus, and rotation. - 48 kHz mock-mic dictation across first show, 10 hide/shows, keyboard switches, bar, auto-start, hide mid-recording/transcribing, active recording surviving an older controller's memory warning/hide/deinit, and number-pad restore without hand-off or auto-start. - xcodebuild test -scheme HEXMobile: 808 executed, 3 skipped, 0 failures; code-shape and hex-agent-policy clean.
262 lines
11 KiB
Swift
262 lines
11 KiB
Swift
import QuartzCore
|
||
import UIKit
|
||
|
||
/// Settings › Keyboard › Emoji in the full keyboard: the emoji key, its panel, the emoji search
|
||
/// (the letter keys type into it while the results sit above), and an emoji in the empty
|
||
/// strip for the word just finished ("pizza " offers 🍕).
|
||
///
|
||
/// The index (`EmojiLibrary`, a memory-mapped file and about 0.7 MB of offsets) loads on
|
||
/// the first emoji key press or finished word and stays while the keyboard runs, apart
|
||
/// from memory warnings; the panel, its grid and the search go when the panel closes.
|
||
extension FullKeyboardView {
|
||
var emojiEnabled: Bool {
|
||
emojiOverride ?? FullKeyboardSettings().emoji
|
||
}
|
||
|
||
/// Emoji in text fields that take any text: not web addresses, email addresses or
|
||
/// ASCII-only fields.
|
||
func refreshEmojiKey() {
|
||
let document = routedTarget.document
|
||
let takesEmoji: Bool = {
|
||
guard case .keys(.text, _) = KeyboardFieldRouting.route(for: document.keyboardType) else { return false }
|
||
return document.keyboardType != .asciiCapable
|
||
}()
|
||
let shows = emojiEnabled && takesEmoji
|
||
guard engine.showsEmoji != shows else { return }
|
||
engine.showsEmoji = shows
|
||
plane.setNeedsDisplay()
|
||
setNeedsLayout()
|
||
}
|
||
|
||
var isShowingEmoji: Bool { emojiPanel != nil }
|
||
|
||
func loadEmojiLibrary() -> EmojiLibrary? {
|
||
let language = engine.language.rawValue
|
||
if let library = emojiLibrary, library.language == language || !EmojiLibrary.languages.contains(language) {
|
||
return library
|
||
}
|
||
emojiLibrary = EmojiLibrary.bundled(language: language, bundle: Bundle(for: FullKeyboardView.self))
|
||
return emojiLibrary
|
||
}
|
||
|
||
// MARK: - Panel
|
||
|
||
func emojiKeyTapped() {
|
||
if routedTarget.isSearching {
|
||
endEmojiSearch()
|
||
} else {
|
||
openEmojiPanel()
|
||
}
|
||
}
|
||
|
||
func openEmojiPanel() {
|
||
guard emojiPanel == nil, !showsRecording else { return }
|
||
let started = CACurrentMediaTime()
|
||
guard let library = loadEmojiLibrary() else { return }
|
||
engine.commitHangulComposition()
|
||
typingLog?.ui("emoji_open")
|
||
dismissStyleMenu()
|
||
plane.cancelAllTouches()
|
||
let panel = EmojiPanelView(library: library, usage: makeEmojiUsage())
|
||
panel.palette = palette
|
||
panel.showsKeyPopups = engine.showsKeyPopups
|
||
panel.onKeyDown = { [weak self] in self?.keyFeedback() }
|
||
panel.onSelectionStep = { [weak self] in self?.selectionFeedback() }
|
||
panel.onInsert = { [weak self] text, entry, source in self?.insertEmoji(text, entry: entry, source: source) }
|
||
panel.onDelete = { [weak self] in self?.engine.deleteBackward(source: "emoji") }
|
||
panel.onDeleteRepeat = { [weak self] held in self?.engine.repeatDelete(heldFor: held) }
|
||
panel.onLetters = { [weak self] in
|
||
self?.typingLog?.ui("emoji_close")
|
||
self?.closeEmojiPanel()
|
||
}
|
||
panel.onSearch = { [weak self] in self?.beginEmojiSearch() }
|
||
insertSubview(panel, belowSubview: callout)
|
||
emojiPanel = panel
|
||
for view in [plane, stripView, hexKey, globeButton] as [UIView] { view.isHidden = true }
|
||
callout.show(nil, label: "")
|
||
accentCallout.isHidden = true
|
||
fillEmojiPanel()
|
||
setNeedsLayout()
|
||
layoutIfNeeded()
|
||
lastEmojiPanelLatency = CACurrentMediaTime() - started
|
||
}
|
||
|
||
/// The row's suggestions for the text before the cursor and your use, and the grid's
|
||
/// Frequently used.
|
||
func fillEmojiPanel() {
|
||
emojiPanel?.fill(before: routedTarget.document.documentContextBeforeInput)
|
||
}
|
||
|
||
func closeEmojiPanel() {
|
||
guard let panel = emojiPanel else { return }
|
||
if routedTarget.isSearching { endEmojiSearch() }
|
||
panel.tearDown()
|
||
panel.removeFromSuperview()
|
||
emojiPanel = nil
|
||
for view in [plane, stripView, hexKey] as [UIView] {
|
||
view.isHidden = false
|
||
view.alpha = 1
|
||
}
|
||
engine.textDidChange()
|
||
refreshReturnKey()
|
||
refreshStrip()
|
||
setNeedsLayout()
|
||
}
|
||
|
||
func insertEmoji(_ text: String, entry: Int, source: String) {
|
||
// An emoji ends a Hangul run, whether the keys search emoji first or not.
|
||
engine.commitHangulComposition()
|
||
if routedTarget.isSearching {
|
||
// The keys type into the search; the emoji goes into the field.
|
||
suspendedTypingLog?.edit("insert", [
|
||
TypingLogField("inserted", .string(text)),
|
||
TypingLogField("src", .string("emoji_\(source)")),
|
||
])
|
||
routedTarget.document.insertText(text)
|
||
onTextEdit?()
|
||
} else {
|
||
engine.insertEmoji(text, source: "emoji_\(source)")
|
||
}
|
||
if let library = emojiPanel?.library ?? emojiLibrary, entry < library.entries.count {
|
||
emojiPanel?.usage.record(library.entries[entry].emoji)
|
||
}
|
||
}
|
||
|
||
/// An emoji picked from the strip: counted like one from the panel.
|
||
func recordEmojiUse(_ emoji: String) {
|
||
guard let library = emojiLibrary, let entry = library.entryByEmoji[emoji] else { return }
|
||
makeEmojiUsage().record(library.entries[entry].emoji)
|
||
}
|
||
|
||
// MARK: - Search
|
||
|
||
func beginEmojiSearch() {
|
||
guard let panel = emojiPanel, !routedTarget.isSearching else { return }
|
||
typingLog?.ui("emoji_search")
|
||
suspendedTypingLog = engine.typingLog
|
||
engine.typingLog = nil
|
||
routedTarget.query = ""
|
||
panel.isHidden = true
|
||
|
||
let field = EmojiSearchField()
|
||
field.palette = palette
|
||
field.onClose = { [weak self] in self?.endEmojiSearch() }
|
||
addSubview(field)
|
||
emojiSearchField = field
|
||
let results = EmojiRowView()
|
||
results.renderer = panel.glyphs
|
||
results.palette = palette
|
||
results.fontSize = panel.rowFontSize
|
||
results.emptyText = "No emoji"
|
||
results.onPick = { [weak self] index in
|
||
guard let self, index < self.emojiResultEntries.count, let panel = self.emojiPanel else { return }
|
||
self.keyFeedback()
|
||
let entry = self.emojiResultEntries[index]
|
||
self.insertEmoji(panel.display(for: entry), entry: entry, source: "search")
|
||
}
|
||
addSubview(results)
|
||
emojiResults = results
|
||
|
||
plane.isHidden = false
|
||
emojiSearchLift = engine.layout.metrics.stripHeight
|
||
onPreferredHeightChange?()
|
||
engine.configureForField()
|
||
refreshReturnKey()
|
||
refreshEmojiSearch()
|
||
setNeedsLayout()
|
||
layoutIfNeeded()
|
||
}
|
||
|
||
/// Typing changed the query: the results follow, your suggestions while it's empty.
|
||
func refreshEmojiSearch() {
|
||
guard let panel = emojiPanel, let query = routedTarget.query else { return }
|
||
emojiSearchField?.query = query
|
||
let library = panel.library
|
||
let ranked = panel.usage.ranked(limit: 32)
|
||
var boost: [Int: Float] = [:]
|
||
for (emoji, score) in ranked {
|
||
if let entry = library.entryByEmoji[emoji] { boost[entry] = score }
|
||
}
|
||
emojiResultEntries = query.trimmingCharacters(in: .whitespaces).isEmpty
|
||
? panel.suggestions
|
||
: EmojiSuggester.search(query, library: library, usage: boost)
|
||
emojiResults?.setItems(emojiResultEntries.map { (panel.display(for: $0), library.name(of: $0)) })
|
||
}
|
||
|
||
func endEmojiSearch() {
|
||
guard routedTarget.isSearching else { return }
|
||
routedTarget.query = nil
|
||
plane.cancelAllTouches()
|
||
engine.typingLog = suspendedTypingLog
|
||
suspendedTypingLog = nil
|
||
emojiSearchField?.removeFromSuperview()
|
||
emojiSearchField = nil
|
||
emojiResults?.removeFromSuperview()
|
||
emojiResults = nil
|
||
emojiResultEntries = []
|
||
emojiSearchLift = 0
|
||
onPreferredHeightChange?()
|
||
engine.configureForField()
|
||
refreshReturnKey()
|
||
if let panel = emojiPanel {
|
||
plane.isHidden = true
|
||
panel.isHidden = false
|
||
fillEmojiPanel()
|
||
}
|
||
setNeedsLayout()
|
||
}
|
||
|
||
func layoutEmoji(content: CGRect, lift: CGFloat) {
|
||
let layout = engine.layout
|
||
let m = layout.metrics
|
||
if let panel = emojiPanel {
|
||
panel.frame = routedTarget.isSearching ? content : bounds
|
||
panel.metrics = m
|
||
panel.horizontalInset = layout.horizontalInset
|
||
// The panel covers the keyboard while it shows, so the emoji key's keycap sits in
|
||
// it at the plane's frame (the lift is zero then); the ABC experiment puts the
|
||
// panel's ABC under it. Searching lifts the panel and hides it, and shows ABC
|
||
// nowhere, so there is no key to sit under.
|
||
let underEmojiKey = emojiLettersUnderEmojiKeyOverride ?? FullKeyboardSettings().emojiLettersUnderEmojiKey
|
||
panel.emojiKeyFrame = underEmojiKey && !routedTarget.isSearching
|
||
? layout.key(.emoji)?.frame.offsetBy(dx: 0, dy: lift)
|
||
: nil
|
||
}
|
||
let inset = layout.horizontalInset
|
||
// Centred on the strip's words' line, as the emoji panel's top row.
|
||
let band = m.stripLineBand
|
||
emojiSearchField?.frame = CGRect(x: inset, y: m.stripTop + lift + band.top, width: bounds.width - 2 * inset, height: band.height)
|
||
emojiResults?.frame = CGRect(x: inset + m.side, y: 0, width: bounds.width - 2 * (inset + m.side), height: lift)
|
||
}
|
||
|
||
// MARK: - Strip
|
||
|
||
/// Up to three emoji for the word just finished, when the strip would be empty.
|
||
func emojiForFinishedWord() -> [KeyboardSuggestion] {
|
||
guard engine.showsEmoji, emojiPanel == nil, !routedTarget.isSearching,
|
||
engine.target.autocorrectionType != .no else { return [] }
|
||
let before = routedTarget.document.documentContextBeforeInput
|
||
guard let before, before.hasSuffix(" "), !before.hasSuffix(" ") else { return [] }
|
||
guard let library = loadEmojiLibrary() else { return [] }
|
||
let usage = makeEmojiUsage()
|
||
return EmojiSuggester.forFinishedWord(before, library: library).map { entry in
|
||
let item = library.entries[entry]
|
||
let tone = item.hasTones ? usage.tone(for: item.emoji) : 0
|
||
let emoji = tone > 0 ? item.tones[tone - 1] : item.emoji
|
||
return KeyboardSuggestion(displayText: emoji, replacement: emoji, kind: .emoji)
|
||
}
|
||
}
|
||
|
||
// MARK: - Fixtures
|
||
|
||
/// Fixtures: open the panel, optionally searching `query`.
|
||
func debugOpenEmoji(search query: String? = nil) {
|
||
openEmojiPanel()
|
||
guard let query else { return }
|
||
beginEmojiSearch()
|
||
for character in query {
|
||
routedTarget.insertText(String(character))
|
||
}
|
||
refreshEmojiSearch()
|
||
}
|
||
}
|