hex/ios/HEXShared/FullKeyboard/FullKeyboardView+Emoji.swift
Ryan Vogel 82f5df56c9
iOS: Emoji and Swipe typing are on by default, under Settings › Keyboard (#2129)
Ryan approved graduating both full-keyboard experiments. Swipe typing
(#2106) and the emoji key and panel (#2051) are on for new users and
move out of Experiments.

- Defaults: FullKeyboardSettings.emoji and .swipeTyping read
  experiments.emoji and experiments.swipeTyping as object-or-true (was
  bool(forKey:), unset meaning off), as spatialAutocorrect did in #2097.
  Only their Experiments switches ever wrote those keys, and only on a
  change, so unset means never touched: fresh installs and testers who
  never touched them get them on, a stored false stays off, a stored
  true stays on. The keys keep their names; no migration. Without the
  App Group (no Full Access on an iPhone) both read as on, like the
  keyboard's other on-by-default switches. --experiment-emoji and
  --experiment-swipe still turn them on.
- Settings › Keyboard: a card under the main one with Swipe typing and
  Emoji, plus Clear emoji history while Emoji is on. Both keep "Needs the
  full keyboard" while the Dictation bar is chosen (now from the page's
  own Full/Dictation bar choice). Settings › Experiments keeps Hinglish
  and Clean up with Apple Intelligence. No new strings; every string
  already had zh-Hans.
- Record typing logs' session line adds swipeTyping and emoji, beside
  spatialAutocorrect and cleanupTagger.
- settings-<page> scenes write both switches on, as for
  spatialAutocorrect. Doc comments and README point at Settings ›
  Keyboard.
- Test: KeyboardLayoutTests.testSwipeTypingAndEmojiAreOnByDefaultAnd-
  AStoredOffStaysOff (unset, no App Group, stored off, launch arguments).

Held back: Clean up what I say stays off by default. On the held-out
generated set its false deletes match the reference (0.5% of words; 3.9%
of clean and 2.7% of literal sentences lose a word; 1/43 hand-written
clean sentences), and "late" was never deleted (0/247). But it deletes
every hyphenated name tried: "Tell Hye-jin I said thanks." became "Tell
thanks.", and Jean-Luc, Anne-Marie, Mary-Kate, Ji-woo, Marie-Claire,
Smith-Jones and Zeta-Jones all went (P(DELETE) 0.996-1.0), with
"follow-up" and "re-entry". It also drops a literal "maybe" ("Call me
later, maybe after dinner").

Verified on iPhone 17 simulators (iOS 27.2) on the Mac Studio:
- xcodebuild test: 383 tests, 1 skipped (needs HEX_SPEECH_CLIPS), 0
  failures.
- Swipe on vs off, taps unchanged: the hex-vs-apple held-out sets (2,000
  English and 2,000 Spanish sentences) typed through a real
  KeyboardKeyPlaneView with a temporary, uncommitted harness gave
  identical output in every sentence and 0 swipes from 116,253 letter
  touches, for still taps, motion drawn from Record typing logs, every
  letter dragged 30-95% of a key's pitch, and overlapping (rollover) taps.
  English WER 5.94%, 79/9,203 correct words broken (still) both ways;
  Spanish 8.61%, 23/7,978. A control dragging 1.05-1.5 pitches made
  7,000/7,000 swipes with it on, 0 off. In the typing logs, 1 of about
  1,000 letter touches moved more than a pitch.
- Live keyboard in Messages: with no stored keys the emoji key shows
  and a drag from h to e swipes "He" (strip: Here, Her, He's); with both
  stored false (an upgrade that turned them off) there's no emoji key
  and the same drag slides and types "E".
- Keyboard memory (Release, Full Access, mock mic, probe transcript,
  vmmap physical footprint, resident/peak MB, 2 runs each; a temporary,
  uncommitted probe faked the transcript and headroom):
    typing, emoji and swipe off            34.0 / 46.1
    typing, both on                        35.0-39.9 / 47.0-51.8
    + in-keyboard dictation, Clean up off  35.0 / 46.6
    + dictation, Clean up on               37.6-43.6 / 46.5-51.9
    + emoji panel, a few picks             38.3-38.8 / 51.4-52.2
    + every emoji category browsed         58.8-59.3 / 68.2-68.3
    + all that, then dictation, Clean up   69.2 / 73.7
  Typing sets the peak, not the tagger (loaded after recording stops,
  about 2.6 MB). With a faked 60 MB headroom the 80 MB cleanup guard
  skipped the tagger and the transcript went in as heard (2/2). The
  simulator reports no headroom, so #2045's 32 MB start guard can't fire
  there. On a 4 GB iPhone (reported limits 60-77 MB), browsing every
  emoji category approaches the limit, and a dictation after it would
  open Hex instead. Unverified on a device.
2026-11-21 02:41:15 +00:00

262 lines
10 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 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.load(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 }
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() {
guard let panel = emojiPanel else { return }
let library = panel.library
var usage: [Int: Float] = [:]
var frequent: [Int] = []
for (emoji, score) in panel.usage.ranked(limit: 32) {
guard let entry = library.entryByEmoji[emoji], usage[entry] == nil else { continue }
usage[entry] = score
frequent.append(entry)
}
for emoji in EmojiSuggester.defaults where frequent.count < 16 {
if let entry = library.entryByEmoji[emoji], !frequent.contains(entry) { frequent.append(entry) }
}
let context = EmojiContext(before: routedTarget.document.documentContextBeforeInput, stopwords: library.stopwords)
let suggestions = EmojiSuggester.suggestions(context: context, library: library, usage: usage, limit: 10)
panel.show(suggestions: suggestions, frequent: frequent)
}
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) {
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.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
}
let inset = layout.horizontalInset
emojiSearchField?.frame = CGRect(x: inset, y: m.stripTop + lift, width: bounds.width - 2 * inset, height: m.stripHeight)
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()
}
}