Files
OSGKeyboard/OSGKeyboardExt/Typing/CandidateExpandGridView.swift
T
rockyandClaude Opus 5 0023741455 feat(app): add crash visibility, memory relief, and clipboard reply work
Squashes the working tree that had accumulated on cloud-agent. Two
strands of work, kept in one commit at the maintainer's request.

Crash and stability (this session):

- Subscribe to MetricKit so crash, hang, CPU, and disk-write diagnostics
  are recorded on device. Keyboard-extension memory kills are the most
  likely way a user loses the keyboard mid-sentence and iOS does not
  classify them as crashes, so they never reach App Store Connect.
- Upload those reports to POST /v1/analytics/diagnostics from internal
  builds only (local Debug and TestFlight), reusing the analytics
  installation identifier and skipping entirely when analytics are off.
  App Store builds keep everything on device.
- Shed the Chinese engine, English lexicon, and in-flight pipeline work
  at the 40 MiB and 48 MiB budget thresholds instead of waiting for a
  system memory warning that jetsam often preempts.
- Install audio taps with the input node's live format through one
  shared adaptive resampler, so an audio-route change mid-recording no
  longer raises an uncatchable format-mismatch exception. Covers the
  dictation preview and the Mac recorder, which still used the pattern
  the Flow capture path had already moved away from.
- Harden the librime bridge: never pass a nil string across a nonnull
  boundary when a user dictionary holds malformed UTF-8, null-check the
  engine API vector, and distrust a candidate count without its array.
- Guard the expanded candidate grid against a list that shrinks while
  the collection view is still laying out against the previous count.
- Resolve localized text without the App Group so the screen shown when
  that container is missing renders its message instead of crashing on
  launch, which is the one situation it exists to handle.
- Gate CI on the App Group and Keychain wiring that the keyboard
  extension hard-depends on, with a self-test proving the check fails.

Clipboard, reply, and semantics (pre-existing working tree):

- Unify the reply center, refresh keyboard AI features, and add native
  event and reminder exporters.
- Expand clipboard semantic routing with authored corpora and a
  product-blind holdout, plus the scripts that build and validate them.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-18 17:31:29 -07:00

202 lines
7.7 KiB
Swift

// CandidateExpandGridView.swift
// OSGKeyboard · Keyboard Extension
//
// UIKit grid for the expanded Chinese candidate panel. UILabel cells +
// UICollectionView recycling stay far cheaper than hundreds of SwiftUI Buttons.
import OSGKeyboardShared
import SwiftUI
import UIKit
struct CandidateExpandGridView: UIViewRepresentable {
var candidates: [TypingCandidate]
var textColor: UIColor
var dividerColor: UIColor
var onSelect: (TypingCandidate) -> Void
func makeCoordinator() -> Coordinator {
Coordinator(onSelect: onSelect)
}
func makeUIView(context: Context) -> UICollectionView {
let view = UICollectionView(frame: .zero, collectionViewLayout: Self.makeLayout())
view.backgroundColor = .clear
view.alwaysBounceVertical = true
view.showsVerticalScrollIndicator = true
view.delaysContentTouches = false
view.canCancelContentTouches = true
view.dataSource = context.coordinator
view.delegate = context.coordinator
view.register(Cell.self, forCellWithReuseIdentifier: Cell.reuseID)
context.coordinator.collectionView = view
return view
}
func updateUIView(_ uiView: UICollectionView, context: Context) {
let coordinator = context.coordinator
let idsChanged = coordinator.candidates.map(\.id) != candidates.map(\.id)
let styleChanged =
coordinator.textColor != textColor || coordinator.dividerColor != dividerColor
coordinator.onSelect = onSelect
coordinator.textColor = textColor
coordinator.dividerColor = dividerColor
coordinator.candidates = candidates
if idsChanged || styleChanged {
uiView.reloadData()
}
}
private static func makeLayout() -> UICollectionViewCompositionalLayout {
let columns = TypingLayoutMetrics.expandGridColumns
let itemSize = NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1.0 / CGFloat(columns)),
heightDimension: .absolute(TypingLayoutMetrics.expandCellHeight)
)
let item = NSCollectionLayoutItem(layoutSize: itemSize)
let groupSize = NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1.0),
heightDimension: .absolute(TypingLayoutMetrics.expandCellHeight)
)
let group = NSCollectionLayoutGroup.horizontal(
layoutSize: groupSize,
repeatingSubitem: item,
count: columns
)
let section = NSCollectionLayoutSection(group: group)
section.contentInsets = .zero
return UICollectionViewCompositionalLayout(section: section)
}
final class Coordinator: NSObject, UICollectionViewDataSource, UICollectionViewDelegate {
var candidates: [TypingCandidate] = []
var textColor: UIColor = .label
var dividerColor: UIColor = .separator
var onSelect: (TypingCandidate) -> Void
weak var collectionView: UICollectionView?
init(onSelect: @escaping (TypingCandidate) -> Void) {
self.onSelect = onSelect
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
candidates.count
}
func collectionView(
_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath
) -> UICollectionViewCell {
let dequeued = collectionView.dequeueReusableCell(
withReuseIdentifier: Cell.reuseID,
for: indexPath
)
guard let cell = dequeued as? Cell else { return dequeued }
// Rime refreshes the candidate list on every keystroke, so the
// collection view can still be laying out against the *previous*
// count when a new list lands. An out-of-range read here would
// crash the whole keyboard; render an empty cell instead — the
// pending `reloadData` repaints it a frame later.
guard candidates.indices.contains(indexPath.item) else {
cell.configure(
text: "",
emphasized: false,
textColor: textColor,
dividerColor: dividerColor,
showDivider: false
)
return cell
}
let index = indexPath.item
cell.configure(
text: candidates[index].text,
emphasized: index == 0,
textColor: textColor,
dividerColor: dividerColor,
showDivider: !isLastRow(index: index)
)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: false)
guard candidates.indices.contains(indexPath.item) else { return }
onSelect(candidates[indexPath.item])
}
private func isLastRow(index: Int) -> Bool {
let columns = TypingLayoutMetrics.expandGridColumns
guard !candidates.isEmpty else { return true }
let row = index / columns
let lastRow = (candidates.count - 1) / columns
return row == lastRow
}
}
private final class Cell: UICollectionViewCell {
static let reuseID = "CandidateExpandCell"
private let label = UILabel()
private let divider = UIView()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .clear
contentView.backgroundColor = .clear
isAccessibilityElement = true
accessibilityTraits = .button
label.textAlignment = .center
label.lineBreakMode = .byTruncatingTail
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.7
label.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(label)
divider.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(divider)
NSLayoutConstraint.activate([
label.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 2),
label.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -2),
label.topAnchor.constraint(equalTo: contentView.topAnchor),
label.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
divider.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
divider.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
divider.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
divider.heightAnchor.constraint(equalToConstant: 1.0 / 3.0)
])
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configure(
text: String,
emphasized: Bool,
textColor: UIColor,
dividerColor: UIColor,
showDivider: Bool
) {
label.text = text
label.textColor = textColor
label.font = .systemFont(
ofSize: emphasized ? 19 : 18,
weight: emphasized ? .medium : .regular
)
divider.backgroundColor = dividerColor
divider.isHidden = !showDivider
accessibilityLabel = text
}
override var isHighlighted: Bool {
didSet {
contentView.alpha = isHighlighted ? 0.45 : 1
}
}
}
}