Compare commits

...
Author SHA1 Message Date
rustdeskandClaude Fable 5.2 fca07adfae feat(mobile): opt-in soft keyboard interpreters that know about composing text
Both are off by default. The old handlers stay in use on both platforms
until these have been run on devices. A new switch on the mobile
settings page, "Improved input method (IME) handling", selects them. The
choice takes effect the next time the keyboard is opened.

iOS. The old handler diffs the whole text and guards on the length of
the composing range. That lets the first letter of every composition
through (#16632), sends the rest of it on a partial commit, and never
sees a commit that leaves the text as it is. The interpreter diffs only
the text outside the composing range, with the same tail diff as before.
Without a composing range it sends exactly what the old handler sends; a
test compares the two on random editing sequences. Because it keeps that
tail diff it does not fix #16663, a deleted emoji, or a typed 1. The
helper in #17002 does, and is meant to take its place.

Text that is still being composed when the field loses focus is
dropped. If the keyboard itself commits it before that, it is sent like
any other commit.

Android. The interpreter mirrors the field instead of comparing lengths.
It handles replacements of equal length (#7727), text committed inside a
pair of quotes (#16535) and compositions that get shorter when
committed. It replays Backspace only through text this client typed, at
most 64 characters, never across a line break and never through a
character made of several code points. Anything else is sent at the
caret, cut off at the limit or dropped. Return that arrives in the same
edit as other text is still sent as the key. It does not know when the
remote caret has been moved.

Building with --dart-define=SOFT_KEYBOARD_TRACE=meta or =full logs the
editing values and what was derived from them. meta never contains text.
The log lines of a full trace can be saved under
test/fixtures/soft_keyboard as they are and are then replayed as a test.
The fixtures in this commit are written by hand and say so.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JAxkkkfvhEPKVg85ZHovfs
2026-11-14 10:27:44 +08:00
rustdeskandClaude Fable 5.2 624cd23a07 refactor(mobile): move soft keyboard input handling out of the remote page
The two handlers that turn changes of the hidden text field into key
events lived in the page widget and called the bridge directly, so they
could not be run in a test. They are moved, unchanged, into
lib/mobile/soft_keyboard/ and now return what should be sent instead of
sending it. Tests pin what they do, the known failures included (#16632,
#7727, #16535).

What changes around them:

- The page listens to the text controller instead of onChanged. The
  handlers still act only when the text changes, as before. A test runs
  them both ways behind a real text field and compares the results.
- When the field loses focus it is refilled and interpretation starts
  over. A change that reaches the controller while the field has no
  focus is ignored. The framework makes one when it clears the composing
  range of a field that lost focus.
- What the handlers return is sent through a queue. Text waits until the
  Backspaces in front of it have returned. The bridge runs calls on four
  worker threads, so a Backspace followed by text, which the iOS handler
  has always produced, was not guaranteed to reach the session in that
  order. InputModel.inputKey returns the future of its call for this.
  Keys sent from elsewhere, the toolbar for instance, do not go through
  the queue.

An interpreter can also ask for the field to be corrected, with
SoftKeyboardSetField. Neither old handler uses it. It is there for one
that has to put padding back or move the caret, as in #17002.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JAxkkkfvhEPKVg85ZHovfs
2026-11-14 10:27:44 +08:00
77 changed files with 2719 additions and 114 deletions

No files matched your search

+2
View File
@@ -192,6 +192,8 @@ const String kOptionAllowAskForNoteAtEndOfConnection = "allow-ask-for-note";
const String kOptionAllowMonitorSwitchMainToolbar = "allow-monitor-switch-main-toolbar";
const String kOptionAllowMonitorSwitchMinToolbar = "allow-monitor-switch-min-toolbar";
const String kOptionEnableShowTerminalExtraKeys = "enable-show-terminal-extra-keys";
// On only when it is "Y". `option2bool()` would read an unset value as true.
const String kOptionMobileImeInput = "mobile-ime-input";
const String kOptionShowTerminalCtrlKeys = "show-terminal-extra-ctrl-keys";
// network options
+37 -112
View File
@@ -23,10 +23,11 @@ import '../../models/model.dart';
import '../../models/platform_model.dart';
import '../../models/shortcut_model.dart';
import '../../utils/image.dart';
import '../soft_keyboard/soft_keyboard.dart';
import '../widgets/dialog.dart';
import '../widgets/custom_scale_widget.dart';
final initText = '1' * 1024;
final initText = kSoftKeyboardSentinelChar * 1024;
// Workaround for Android (default input method, Microsoft SwiftKey keyboard) when using physical keyboard.
// When connecting a physical keyboard, `KeyEvent.physicalKey.usbHidUsage` are wrong is using Microsoft SwiftKey keyboard.
@@ -91,7 +92,6 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
Timer? _timer;
bool _showBar = !isWebDesktop;
bool _showGestureHelp = false;
String _value = '';
Orientation? _currentOrientation;
final _uniqueKey = UniqueKey();
Timer? _iosKeyboardWorkaroundTimer;
@@ -113,6 +113,26 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
final TextEditingController _textController =
TextEditingController(text: initText);
// Soft keyboard input: the hidden field's editing values go through an
// interpreter, and what it derives from them is sent in order.
late final _softKeyboardInput = SoftKeyboardInput(
controller: _textController,
focusNode: _mobileFocusNode,
sentinel: initText,
createInterpreter: (initial) => createSoftKeyboardInterpreter(
isIOS: isIOS,
useReducer: bind.mainGetLocalOption(key: kOptionMobileImeInput) == 'Y',
initial: initial,
),
dispatcher: SoftKeyboardDispatcher(
sendBackspace: () => inputModel.inputKey('VK_BACK'),
sendText: _sendSoftKeyboardText,
),
isAllowed: () => inputModel.keyboardInputAllowed,
reopenKeyboard: _openKeyboardUnlocked,
platform: isIOS ? 'ios' : (isAndroid ? 'android' : 'other'),
);
_RemotePageState(String id) {
initSharedStates(id);
gFFI.chatModel.voiceCallStatus.value = VoiceCallStatus.notStarted;
@@ -138,6 +158,7 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
WakelockManager.enable(_uniqueKey);
_physicalFocusNode.requestFocus();
HardwareKeyboard.instance.addHandler(_handleLocalKeyEvent);
_softKeyboardInput.attach();
gFFI.inputModel.listenToMouse(true);
gFFI.qualityMonitorModel.checkShowQualityMonitor(sessionId);
keyboardSubscription =
@@ -187,6 +208,7 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
@override
Future<void> dispose() async {
HardwareKeyboard.instance.removeHandler(_handleLocalKeyEvent);
_softKeyboardInput.detach();
WidgetsBinding.instance.removeObserver(this);
// Close the session up-front. `gFFI.close()` below only calls `sessionClose`
// after several awaits (canvas save, image update, the `enable_soft_keyboard`
@@ -320,114 +342,16 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
setState(() {});
}
void _handleIOSSoftKeyboardInput(String newValue) {
var oldValue = _value;
_value = newValue;
var i = newValue.length - 1;
for (; i >= 0 && newValue[i] != '1'; --i) {}
var j = oldValue.length - 1;
for (; j >= 0 && oldValue[j] != '1'; --j) {}
if (i < j) j = i;
var subNewValue = newValue.substring(j + 1);
var subOldValue = oldValue.substring(j + 1);
// get common prefix of subNewValue and subOldValue
var common = 0;
for (;
common < subOldValue.length &&
common < subNewValue.length &&
subNewValue[common] == subOldValue[common];
++common) {}
// get newStr from subNewValue
var newStr = "";
if (subNewValue.length > common) {
newStr = subNewValue.substring(common);
}
// Set the value to the old value and early return if is still composing. (1 && 2)
// 1. The composing range is valid
// 2. The new string is shorter than the composing range.
if (_textController.value.isComposingRangeValid) {
final composingLength = _textController.value.composing.end -
_textController.value.composing.start;
if (composingLength > newStr.length) {
_value = oldValue;
return;
}
}
// Delete the different part in the old value.
for (i = 0; i < subOldValue.length - common; ++i) {
inputModel.inputKey('VK_BACK');
}
// Input the new string.
if (newStr.length > 1) {
bind.sessionInputString(sessionId: sessionId, value: newStr);
} else {
inputChar(newStr);
// Text from the mobile virtual keyboard: a single character goes out as a
// key, anything longer as a string.
Future<void> _sendSoftKeyboardText(String text) {
if (text.length > 1) {
return bind.sessionInputString(sessionId: sessionId, value: text);
}
return inputChar(text);
}
void _handleNonIOSSoftKeyboardInput(String newValue) {
var oldValue = _value;
_value = newValue;
if (oldValue.isNotEmpty &&
newValue.isNotEmpty &&
oldValue[0] == '1' &&
newValue[0] != '1') {
// clipboard
oldValue = '';
}
// This length-only diff assumes the IME appends at the end. If an IME
// leaves the caret inside paired punctuation, later insertions can replay
// the closing symbol: "()" -> "(a)" sends ")" instead of "a". This is a
// client text-diff issue, independent of the host keyboard layout.
if (newValue.length == oldValue.length) {
// ?
} else if (newValue.length < oldValue.length) {
final char = 'VK_BACK';
inputModel.inputKey(char);
} else {
final content = newValue.substring(oldValue.length);
if (content.length > 1) {
if (oldValue != '' &&
content.length == 2 &&
(content == '""' ||
content == '()' ||
content == '[]' ||
content == '<>' ||
content == "{}" ||
content == '”“' ||
content == '《》' ||
content == '()' ||
content == '【】')) {
// can not only input content[0], because when input ], [ are also auo insert, which cause ] never be input
bind.sessionInputString(sessionId: sessionId, value: content);
_openKeyboardUnlocked();
return;
}
bind.sessionInputString(sessionId: sessionId, value: content);
} else {
inputChar(content);
}
}
}
// handle mobile virtual keyboard
void handleSoftKeyboardInput(String newValue) {
if (!inputModel.keyboardInputAllowed) {
return;
}
if (isIOS) {
_handleIOSSoftKeyboardInput(newValue);
} else {
_handleNonIOSSoftKeyboardInput(newValue);
}
}
void inputChar(String char) {
Future<void> inputChar(String char) async {
if (!inputModel.keyboardInputAllowed) {
return;
}
@@ -436,7 +360,7 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
} else if (char == ' ') {
char = 'VK_SPACE';
}
inputModel.inputKey(char);
await inputModel.inputKey(char);
}
void openKeyboard() {
@@ -464,9 +388,8 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
void _openKeyboardUnlocked() {
inputModel.keyboardInputAllowed = true;
gFFI.invokeMethod("enable_soft_keyboard", true);
// destroy first, so that our _value trick can work
_value = initText;
_textController.text = _value;
// refill first, so that the sentinel trick can work
_softKeyboardInput.refill();
setState(() => _showEdit = false);
_timer?.cancel();
_timer = Timer(kMobileDelaySoftKeyboard, () {
@@ -752,7 +675,9 @@ class _RemotePageState extends State<RemotePage> with WidgetsBindingObserver {
// 2. The button will trigger `onKeyEvent` if the text field is empty.
// ko/zh/ja input method: the button will trigger `onKeyEvent`
// and the event will not popup if `KeyEventResult.handled` is returned.
onChanged: handleSoftKeyboardInput,
//
// The input is taken from `_textController`, see
// `_softKeyboardInput`.
).workaroundFreezeLinuxMint(),
),
];
@@ -75,6 +75,7 @@ class _SettingsState extends State<SettingsPage> with WidgetsBindingObserver {
var _enableStartOnBoot = false;
var _checkUpdateOnStartup = false;
var _showTerminalExtraKeys = false;
var _mobileImeInput = false;
var _floatingWindowDisabled = false;
var _keepScreenOn = KeepScreenOn.duringControlled; // relay on floating window
var _enableAbr = false;
@@ -155,6 +156,8 @@ class _SettingsState extends State<SettingsPage> with WidgetsBindingObserver {
mainGetLocalBoolOptionSync(kOptionKeepAwakeDuringOutgoingSessions);
_showTerminalExtraKeys =
mainGetLocalBoolOptionSync(kOptionEnableShowTerminalExtraKeys);
_mobileImeInput =
bind.mainGetLocalOption(key: kOptionMobileImeInput) == 'Y';
}
@override
@@ -933,6 +936,22 @@ class _SettingsState extends State<SettingsPage> with WidgetsBindingObserver {
});
},
),
if (!incomingOnly)
SettingsTile.switchTile(
title: Text(translate('Improved input method (IME) handling')),
initialValue: _mobileImeInput,
onToggle: isOptionFixed(kOptionMobileImeInput)
? null
: (v) async {
await mainSetLocalBoolOption(kOptionMobileImeInput, v);
final newValue =
bind.mainGetLocalOption(key: kOptionMobileImeInput) ==
'Y';
setState(() {
_mobileImeInput = newValue;
});
},
),
if (!bind.isDisableAccount())
SettingsTile.switchTile(
title: Text(translate('note-at-conn-end-tip')),
@@ -0,0 +1,156 @@
import 'package:flutter/services.dart';
import 'soft_keyboard_actions.dart';
/// The result of [legacyTailDiff].
class LegacyTailDiff {
const LegacyTailDiff(this.backspaces, this.inserted);
/// How many UTF-16 code units of the old tail have to be deleted.
final int backspaces;
/// What has to be typed after the deletion. May be empty.
final String inserted;
}
/// The tail diff the iOS handler has always used.
///
/// Both values are cut after their last sentinel character, then compared by
/// common prefix. Lengths are UTF-16 code units.
LegacyTailDiff legacyTailDiff(String oldValue, String newValue) {
var i = newValue.length - 1;
for (; i >= 0 && newValue[i] != kSoftKeyboardSentinelChar; --i) {}
var j = oldValue.length - 1;
for (; j >= 0 && oldValue[j] != kSoftKeyboardSentinelChar; --j) {}
if (i < j) j = i;
final subNewValue = newValue.substring(j + 1);
final subOldValue = oldValue.substring(j + 1);
// get common prefix of subNewValue and subOldValue
var common = 0;
for (;
common < subOldValue.length &&
common < subNewValue.length &&
subNewValue[common] == subOldValue[common];
++common) {}
return LegacyTailDiff(
subOldValue.length - common,
subNewValue.length > common ? subNewValue.substring(common) : '',
);
}
/// `_handleIOSSoftKeyboardInput` as it was in `remote_page.dart`, returning
/// actions instead of sending them.
///
/// Kept as the fallback and as the reference the new interpreter is compared
/// against in tests. Do not fix bugs here.
class LegacyIosSoftKeyboard implements SoftKeyboardInterpreter {
LegacyIosSoftKeyboard(TextEditingValue initial)
: _value = initial.text,
_lastText = initial.text;
String _value;
String _lastText;
@override
String get name => 'legacy-ios';
@override
String? get lastNote => null;
@override
List<SoftKeyboardAction> update(TextEditingValue value) {
final newValue = value.text;
// This used to be driven by `onChanged`, which is only called when the
// text changes.
if (newValue == _lastText) return const [];
_lastText = newValue;
final oldValue = _value;
_value = newValue;
final diff = legacyTailDiff(oldValue, newValue);
// Set the value to the old value and early return if is still composing. (1 && 2)
// 1. The composing range is valid
// 2. The new string is shorter than the composing range.
if (value.isComposingRangeValid) {
final composingLength = value.composing.end - value.composing.start;
if (composingLength > diff.inserted.length) {
_value = oldValue;
return const [];
}
}
return [
// Delete the different part in the old value.
if (diff.backspaces > 0) SoftKeyboardBackspace(diff.backspaces),
// Input the new string.
if (diff.inserted.isNotEmpty) SoftKeyboardText(diff.inserted),
];
}
}
/// `_handleNonIOSSoftKeyboardInput` as it was in `remote_page.dart`, returning
/// actions instead of sending them.
///
/// Kept as the default on Android and as the reference the new interpreter is
/// compared against in tests. Do not fix bugs here.
class LegacyAndroidSoftKeyboard implements SoftKeyboardInterpreter {
LegacyAndroidSoftKeyboard(TextEditingValue initial) : _value = initial.text;
String _value;
@override
String get name => 'legacy-android';
@override
String? get lastNote => null;
@override
List<SoftKeyboardAction> update(TextEditingValue value) {
final newValue = value.text;
// This used to be driven by `onChanged`, which is only called when the
// text changes.
if (newValue == _value) return const [];
var oldValue = _value;
_value = newValue;
if (oldValue.isNotEmpty &&
newValue.isNotEmpty &&
oldValue[0] == kSoftKeyboardSentinelChar &&
newValue[0] != kSoftKeyboardSentinelChar) {
// clipboard
oldValue = '';
}
// This length-only diff assumes the IME appends at the end. If an IME
// leaves the caret inside paired punctuation, later insertions can replay
// the closing symbol: "()" -> "(a)" sends ")" instead of "a". This is a
// client text-diff issue, independent of the host keyboard layout.
if (newValue.length == oldValue.length) {
// ?
return const [];
} else if (newValue.length < oldValue.length) {
return const [SoftKeyboardBackspace(1)];
} else {
final content = newValue.substring(oldValue.length);
if (content.length > 1) {
if (oldValue != '' &&
content.length == 2 &&
(content == '""' ||
content == '()' ||
content == '[]' ||
content == '<>' ||
content == "{}" ||
content == '”“' ||
content == '《》' ||
content == '()' ||
content == '【】')) {
// can not only input content[0], because when input ], [ are also auo insert, which cause ] never be input
return [SoftKeyboardText(content), const SoftKeyboardResetField()];
}
}
return [SoftKeyboardText(content)];
}
}
}
@@ -0,0 +1,40 @@
/// Interpretation of mobile soft keyboard input.
///
/// The remote page owns a hidden text field. Whatever the keyboard does to it
/// arrives as editing values, an interpreter turns those into actions, and the
/// dispatcher sends the actions in order. Nothing in here touches FFI or
/// widgets, so all of it runs in unit tests.
library;
import 'package:flutter/services.dart';
import 'legacy_soft_keyboard.dart';
import 'soft_keyboard_actions.dart';
import 'soft_keyboard_reducer.dart';
export 'legacy_soft_keyboard.dart';
export 'soft_keyboard_actions.dart';
export 'soft_keyboard_dispatcher.dart';
export 'soft_keyboard_input.dart';
export 'soft_keyboard_reducer.dart';
export 'soft_keyboard_trace.dart';
/// The interpreter for a platform: the old handler, or, when [useReducer] is
/// set, the one that knows about composing text.
///
/// The old handlers are the default on both platforms. The new ones have not
/// been run on a device.
SoftKeyboardInterpreter createSoftKeyboardInterpreter({
required bool isIOS,
required bool useReducer,
required TextEditingValue initial,
}) {
if (isIOS) {
return useReducer
? SoftKeyboardReducer.ios(initial)
: LegacyIosSoftKeyboard(initial);
}
return useReducer
? SoftKeyboardReducer.android(initial)
: LegacyAndroidSoftKeyboard(initial);
}
@@ -0,0 +1,129 @@
import 'package:flutter/services.dart';
/// The character the hidden soft keyboard field is pre-filled with.
///
/// An empty editable field cannot report a Backspace, so the field always
/// holds a run of these for the keyboard to delete.
const String kSoftKeyboardSentinelChar = '1';
/// What has to happen in response to a local editing change.
///
/// Interpreters only describe it. Sending is done by the dispatcher and the
/// field is written by its owner, so the interpretation logic stays free of
/// FFI and can be executed in unit tests.
sealed class SoftKeyboardAction {
const SoftKeyboardAction();
/// Whether this is sent to the remote side. The others act on the local
/// field only.
bool get isRemote;
}
/// Press Backspace [count] times.
class SoftKeyboardBackspace extends SoftKeyboardAction {
const SoftKeyboardBackspace(this.count) : assert(count > 0);
final int count;
@override
bool get isRemote => true;
@override
bool operator ==(Object other) =>
other is SoftKeyboardBackspace && other.count == count;
@override
int get hashCode => Object.hash(SoftKeyboardBackspace, count);
@override
String toString() => 'Backspace($count)';
}
/// Send [text] to the remote side.
///
/// Whether it goes out as a single key or as a text sequence is decided by the
/// dispatcher from the text length, the same way it always was.
class SoftKeyboardText extends SoftKeyboardAction {
const SoftKeyboardText(this.text) : assert(text != '');
final String text;
@override
bool get isRemote => true;
@override
bool operator ==(Object other) =>
other is SoftKeyboardText && other.text == text;
@override
int get hashCode => Object.hash(SoftKeyboardText, text);
@override
String toString() => 'Text(${_escape(text)})';
}
/// Re-create the hidden field. Only the legacy Android handler asks for this,
/// after it has sent a pair of brackets or quotes.
class SoftKeyboardResetField extends SoftKeyboardAction {
const SoftKeyboardResetField();
@override
bool get isRemote => false;
@override
bool operator ==(Object other) => other is SoftKeyboardResetField;
@override
int get hashCode => (SoftKeyboardResetField).hashCode;
@override
String toString() => 'ResetField';
}
/// Write [value] to the hidden field. Nothing is sent.
///
/// For an interpreter that has to correct the field itself, for instance to
/// put back padding the keyboard used up, or to move the caret to the end.
/// The interpreter is given the corrected value like any other and must not
/// answer it with remote operations.
class SoftKeyboardSetField extends SoftKeyboardAction {
const SoftKeyboardSetField(this.value);
final TextEditingValue value;
@override
bool get isRemote => false;
@override
bool operator ==(Object other) =>
other is SoftKeyboardSetField && other.value == value;
@override
int get hashCode => Object.hash(SoftKeyboardSetField, value);
// Without the value: it holds what was typed.
@override
String toString() => 'SetField';
}
/// Turns the editing values of the hidden field into remote operations.
///
/// An interpreter starts from the value the field has when it is created.
/// When the app changes the field, a new one is created.
abstract class SoftKeyboardInterpreter {
/// Short identifier, recorded in traces.
String get name;
/// Consumes one editing value and returns what has to be sent for it.
///
/// Must be called for every value the controller reports, including the
/// ones where only the selection or the composing range changed.
List<SoftKeyboardAction> update(TextEditingValue value);
/// Why the last [update] did not mirror the local edit, if it did not.
///
/// Diagnostic only; recorded in traces.
String? get lastNote;
}
String _escape(String s) => s.replaceAll('\n', r'\n');
@@ -0,0 +1,81 @@
import 'dart:async';
import 'dart:collection';
import 'package:flutter/foundation.dart';
import 'soft_keyboard_actions.dart';
/// Sends the remote operations among soft keyboard actions one at a time, in
/// order.
///
/// Each send is an asynchronous call that the bridge runs on a pool of worker
/// threads, so two calls made back to back are not guaranteed to reach the
/// connection in the order they were made. Text that follows a Backspace has
/// to arrive after it. Waiting for one call to return before making the next
/// is what guarantees that.
class SoftKeyboardDispatcher {
SoftKeyboardDispatcher({
required this.sendBackspace,
required this.sendText,
});
/// Presses Backspace once.
final Future<void> Function() sendBackspace;
/// Sends committed text.
final Future<void> Function(String text) sendText;
final Queue<SoftKeyboardAction> _pending = Queue();
bool _draining = false;
/// Queues [actions]. If nothing is in flight the first one is sent before
/// this returns.
///
/// Actions that are not remote operations are skipped. The owner of the
/// field acts on those.
void dispatch(List<SoftKeyboardAction> actions) {
_pending.addAll(actions.where((action) => action.isRemote));
if (_pending.isEmpty) return;
if (!_draining) unawaited(_drain());
}
/// Drops everything that has not been sent yet.
///
/// For when the session goes away. Input typed for one session must not be
/// delivered to whatever comes next.
void cancel() {
_pending.clear();
}
Future<void> _drain() async {
_draining = true;
try {
while (_pending.isNotEmpty) {
final action = _pending.removeFirst();
try {
await _send(action);
} catch (e) {
// Keep going. One failed send must not hold back later input. The
// action is not logged: it may hold what was typed.
debugPrint('soft keyboard: a send failed (${e.runtimeType})');
}
}
} finally {
_draining = false;
}
}
Future<void> _send(SoftKeyboardAction action) async {
switch (action) {
case SoftKeyboardBackspace(:final count):
// Backspaces cannot overtake each other in any way that matters, so
// they go out together. Only what follows has to wait for them.
await Future.wait([for (var i = 0; i < count; i++) sendBackspace()]);
case SoftKeyboardText(:final text):
await sendText(text);
case SoftKeyboardResetField():
case SoftKeyboardSetField():
break;
}
}
}
@@ -0,0 +1,129 @@
import 'package:flutter/widgets.dart';
import 'soft_keyboard_actions.dart';
import 'soft_keyboard_dispatcher.dart';
import 'soft_keyboard_trace.dart';
/// Connects the hidden text field to an interpreter and a dispatcher.
///
/// This is the one place that decides whether a change of the field is input
/// at all. It is not input when the app refills the field, and it is not
/// input when the field has no focus.
class SoftKeyboardInput {
SoftKeyboardInput({
required this.controller,
required this.focusNode,
required this.sentinel,
required this.createInterpreter,
required this.dispatcher,
required this.isAllowed,
required this.reopenKeyboard,
this.platform = 'other',
SoftKeyboardTrace? trace,
}) : _trace = trace ?? SoftKeyboardTrace();
final TextEditingController controller;
final FocusNode focusNode;
/// What the field holds when nothing has been typed.
final String sentinel;
/// Creates the interpreter to use from now on. Called on every [refill], so
/// a change of the setting never takes effect in the middle of typing.
final SoftKeyboardInterpreter Function(TextEditingValue initial)
createInterpreter;
final SoftKeyboardDispatcher dispatcher;
/// Whether soft keyboard input may be sent at the moment.
final bool Function() isAllowed;
/// Closes and opens the keyboard again. Only the legacy Android handler
/// asks for it.
final VoidCallback reopenKeyboard;
/// Recorded in traces.
final String platform;
final SoftKeyboardTrace _trace;
late SoftKeyboardInterpreter _interpreter;
/// Whether the field still is as the last [refill] left it.
bool _untouched = false;
/// Set while a correction asked for by the interpreter is being written.
bool _correcting = false;
void attach() {
refill();
controller.addListener(_handleValue);
focusNode.addListener(_handleFocus);
}
/// Stops listening and drops what has not been sent yet. Input typed for
/// one session must not be delivered to whatever comes next.
void detach() {
controller.removeListener(_handleValue);
focusNode.removeListener(_handleFocus);
dispatcher.cancel();
}
/// Fills the field with the sentinel again and starts interpreting from
/// scratch. Text that was still being composed is dropped.
void refill() {
// The interpreter starts from the refilled field, so that the refill is
// not taken for input.
final initial = TextEditingValue(text: sentinel);
_interpreter = createInterpreter(initial);
_trace.start(_interpreter, initial, platform: platform);
controller.value = initial;
_untouched = true;
}
// This listens to the controller instead of `onChanged`, because `onChanged`
// is only called when the text changes. An input method can finish a
// composition without changing the text, and that has to be seen too.
void _handleValue() {
// Without focus the field is not connected to a keyboard. What changes it
// then is the framework, which clears the composing range of a field
// that loses focus. That is not the keyboard committing the text.
if (!focusNode.hasFocus) return;
_untouched = false;
if (!isAllowed()) return;
final value = controller.value;
final actions = _interpreter.update(value);
_trace.record(value, actions, note: _interpreter.lastNote);
dispatcher.dispatch(actions);
for (final action in actions) {
switch (action) {
case SoftKeyboardSetField(:final value):
_correct(value);
case SoftKeyboardResetField():
reopenKeyboard();
case SoftKeyboardBackspace():
case SoftKeyboardText():
break;
}
}
}
// Writing the field comes straight back here, so that the interpreter sees
// the value it asked for. A correction asked for in answer to a correction
// is not written. That would never end.
void _correct(TextEditingValue value) {
if (_correcting) return;
_correcting = true;
try {
controller.value = value;
} finally {
_correcting = false;
}
}
// Leaving the field ends the input. However the keyboard is closed, a
// composition that was not committed is cancelled, and what was typed
// before can no longer be edited from here.
void _handleFocus() {
if (!focusNode.hasFocus && !_untouched) refill();
}
}
@@ -0,0 +1,350 @@
import 'dart:math' as math;
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart' show CharacterRange, StringCharacters;
import 'legacy_soft_keyboard.dart';
import 'soft_keyboard_actions.dart';
/// What to do with text the keyboard still marks as composing.
enum ComposingPolicy {
/// Keep composing text local and send only what has been committed.
///
/// Nothing provisional reaches the remote side. Right when the composing
/// range is only used for real compositions, as on iOS.
hold,
/// Ignore the composing range and mirror the field as it is typed.
///
/// Provisional text is sent and corrected afterwards. Needed where the
/// keyboard also marks ordinary words as composing, as Gboard does for
/// English.
forward,
}
/// Turns one change of the mirrored text into remote operations.
abstract class SoftKeyboardDiff {
/// Diagnostic identifier.
String get name;
/// Called once, with the text the interpretation starts from.
void start(String text);
List<SoftKeyboardAction> apply(String oldText, String newText);
/// Why the last [apply] did not mirror the edit, if it did not.
String? get lastNote;
}
/// The mobile soft keyboard interpreter.
///
/// It keeps a baseline, the text the remote side has been told about, and
/// derives a target from each editing value. The difference between the two
/// is handed to a [SoftKeyboardDiff]. With [ComposingPolicy.hold] the target
/// excludes the composing range, so a composition produces nothing until it is
/// committed, and a partial commit produces exactly the committed part.
class SoftKeyboardReducer implements SoftKeyboardInterpreter {
SoftKeyboardReducer({
required this.policy,
required SoftKeyboardDiff diff,
required TextEditingValue initial,
}) : _diff = diff,
_last = initial,
_baseline = initial.text {
_diff.start(initial.text);
}
/// iOS: hold composing text, and keep the tail diff the iOS handler has
/// always used so that everything typed without a composing range is
/// handled exactly as before.
factory SoftKeyboardReducer.ios(TextEditingValue initial) =>
SoftKeyboardReducer(
policy: ComposingPolicy.hold,
diff: LegacyTailSoftKeyboardDiff(),
initial: initial,
);
/// Android: mirror the field as it is typed, with a diff that also handles
/// replacements and edits that are not at the end.
factory SoftKeyboardReducer.android(TextEditingValue initial) =>
SoftKeyboardReducer(
policy: ComposingPolicy.forward,
diff: MirrorSoftKeyboardDiff(),
initial: initial,
);
final ComposingPolicy policy;
final SoftKeyboardDiff _diff;
String _baseline;
TextEditingValue _last;
String? _note;
@override
String get name => '${policy.name}+${_diff.name}';
@override
String? get lastNote => _note;
@override
List<SoftKeyboardAction> update(TextEditingValue value) {
_note = null;
if (value == _last) return const [];
_last = value;
var target = value.text;
String? note;
final composing = _activeComposing(value);
if (policy == ComposingPolicy.hold && composing != null) {
final committed =
value.text.replaceRange(composing.start, composing.end, '');
if (_composingCoversSentText(committed, composing.start)) {
// The keyboard marked text that is already on the remote side as
// composing. It cannot be held back any more, and deleting it now
// would only be undone by the commit, so follow it as it changes.
note = 'composing covers sent text';
} else {
target = committed;
}
}
_note = note;
if (target == _baseline) return const [];
final actions = _diff.apply(_baseline, target);
_baseline = target;
_note = _diff.lastNote ?? note;
return actions;
}
/// The composing range, if the keyboard is in the middle of a composition.
static TextRange? _activeComposing(TextEditingValue value) {
if (!value.isComposingRangeValid || value.composing.isCollapsed) {
return null;
}
return value.composing;
}
/// Whether [committed], the text without its composing range, is the
/// baseline with a piece cut out exactly where the composing range starts.
bool _composingCoversSentText(String committed, int composingStart) {
if (committed.length >= _baseline.length) return false;
return _baseline.startsWith(committed.substring(0, composingStart)) &&
_baseline.endsWith(committed.substring(composingStart));
}
}
/// [legacyTailDiff] as a [SoftKeyboardDiff].
class LegacyTailSoftKeyboardDiff implements SoftKeyboardDiff {
@override
String get name => 'tail';
@override
String? get lastNote => null;
@override
void start(String text) {}
@override
List<SoftKeyboardAction> apply(String oldText, String newText) {
final diff = legacyTailDiff(oldText, newText);
return [
if (diff.backspaces > 0) SoftKeyboardBackspace(diff.backspaces),
if (diff.inserted.isNotEmpty) SoftKeyboardText(diff.inserted),
];
}
}
/// A diff that keeps the remote text equal to what was typed since the
/// keyboard was opened.
///
/// The only thing the client can do to remote text is press Backspace at the
/// remote caret and type. So a local edit can be reproduced only if it lies in
/// text this client typed, which is assumed to still end at the remote caret:
/// delete back to where the edit starts, then type the rest again.
///
/// That replay is limited to [maxReplay] characters, to text in which one
/// Backspace is known to delete one character, and it never crosses a line
/// break. An edit outside those limits is not guessed: typing and Backspace
/// are applied at the caret, a replacement is dropped, and a deletion is cut
/// off at the limit. [lastNote] says which, and the text up to that point is
/// never replayed afterwards.
class MirrorSoftKeyboardDiff implements SoftKeyboardDiff {
MirrorSoftKeyboardDiff({this.maxReplay = 64});
/// The most Backspaces a single edit may produce.
final int maxReplay;
/// Number of leading sentinel characters. They were never sent, and
/// deleting any number of them at once is a single Backspace.
int _sentinel = 0;
/// Text before this index is not known to be on the remote side, so it is
/// never replayed. Starts at the end of the sentinel.
int _floor = 0;
String? _note;
@override
String get name => 'mirror';
@override
String? get lastNote => _note;
@override
void start(String text) {
var n = 0;
while (n < text.length && text[n] == kSoftKeyboardSentinelChar) {
n++;
}
_sentinel = n;
_floor = n;
}
@override
List<SoftKeyboardAction> apply(String oldText, String newText) {
_note = null;
if (oldText == newText) return const [];
final prefix = _commonPrefix(oldText, newText);
final suffix = _commonSuffix(oldText, newText, prefix);
final removedEnd = oldText.length - suffix;
final removed = oldText.substring(prefix, removedEnd);
final inserted = newText.substring(prefix, newText.length - suffix);
if (prefix >= _floor) {
if (suffix == 0 && removed.isEmpty) {
return _type(inserted);
}
if (suffix == 0 && inserted.isEmpty) {
// The end of the text was deleted: Backspace was pressed.
return [_backspace(removed.characters.length, newText.length)];
}
// A replacement, or an edit with text after it. Reproduce it by
// deleting back to where it starts and typing everything after that
// again.
final count = _replayCount(oldText, prefix);
if (count != null) {
return [
if (count > 0) SoftKeyboardBackspace(count),
..._type(inserted, oldText.substring(removedEnd)),
];
}
}
// From here on the edit touches text that cannot be replayed.
final inSentinel = prefix < _sentinel;
var backspaces = 0;
if (inSentinel) {
backspaces = 1;
if (removedEnd > _sentinel) {
backspaces +=
oldText.substring(_sentinel, removedEnd).characters.length;
}
} else if (removed.isNotEmpty) {
backspaces = removed.characters.length;
}
_sentinel = math.min(_sentinel, prefix);
if (suffix == 0 && inserted.isEmpty) {
// Backspace reached past what is mirrored. It is still just Backspace.
_floor = math.min(_floor, prefix);
return [_backspace(backspaces, newText.length)];
}
_floor = newText.length;
if (inSentinel && inserted.isNotEmpty) {
// The sentinel was replaced or typed into. Nothing on the remote side
// corresponds to it, so the new text is all that can be sent.
_note = 'at caret: edit inside the sentinel';
return _type(inserted);
}
if (removed.isNotEmpty && inserted.isNotEmpty) {
// Backspace cannot be trusted to remove exactly the replaced text, and
// typing the replacement next to it would only add to the damage.
_note = 'dropped: replacement cannot be replayed';
return const [];
}
// Typing or Backspace with text after the caret. They mean what they
// always mean, at the remote caret.
_note = 'at caret: text after the edit cannot be replayed';
return inserted.isEmpty
? [_backspace(backspaces, newText.length)]
: _type(inserted);
}
/// [inserted] and then [after], the text that follows it, as text to type.
///
/// A line break at the end of what was inserted is Return being pressed,
/// possibly in the same edit as a correction of the word before it. It is
/// sent on its own, so that it goes out as the key and not as a character
/// in a string.
static List<SoftKeyboardAction> _type(String inserted, [String after = '']) {
if (!inserted.endsWith('\n') || inserted.length + after.length == 1) {
return [SoftKeyboardText(inserted + after)];
}
final before = inserted.substring(0, inserted.length - 1);
return [
if (before.isNotEmpty) SoftKeyboardText(before),
const SoftKeyboardText('\n'),
if (after.isNotEmpty) SoftKeyboardText(after),
];
}
/// [count] Backspaces, or as many as are allowed.
///
/// When that is fewer, the remote text is left longer than the local text,
/// which has [newLength] characters now. Nothing up to there is replayed
/// afterwards.
SoftKeyboardBackspace _backspace(int count, int newLength) {
if (count <= maxReplay) return SoftKeyboardBackspace(count);
_floor = newLength;
_note = 'clamped: more Backspaces than the limit';
return SoftKeyboardBackspace(maxReplay);
}
/// How many Backspaces delete [text] from [from] to its end, or null if
/// that is not known well enough to replay.
int? _replayCount(String text, int from) {
// Every character has to be a single code point. For longer clusters,
// such as emoji sequences, applications disagree on what one Backspace
// deletes.
var count = 0;
for (final char in text.substring(from).characters) {
if (char.runes.length != 1) return null;
// Return is a key press, not text. Deleting a line break does not undo
// it, and typing it again would press Return again.
if (char.codeUnitAt(0) < 0x20) return null;
if (++count > maxReplay) return null;
}
// And the edit must not start inside a cluster.
if (CharacterRange.at(text, from).stringBeforeLength != from) return null;
return count;
}
static int _commonPrefix(String a, String b) {
final max = math.min(a.length, b.length);
var n = 0;
while (n < max && a.codeUnitAt(n) == b.codeUnitAt(n)) {
n++;
}
// Do not split a surrogate pair.
if (n > 0 && _isHighSurrogate(a.codeUnitAt(n - 1))) n--;
return n;
}
static int _commonSuffix(String a, String b, int prefix) {
final max = math.min(a.length, b.length) - prefix;
var n = 0;
while (n < max &&
a.codeUnitAt(a.length - 1 - n) == b.codeUnitAt(b.length - 1 - n)) {
n++;
}
// Do not split a surrogate pair.
if (n > 0 && _isLowSurrogate(a.codeUnitAt(a.length - n))) n--;
return n;
}
static bool _isHighSurrogate(int unit) => (unit & 0xFC00) == 0xD800;
static bool _isLowSurrogate(int unit) => (unit & 0xFC00) == 0xDC00;
}
@@ -0,0 +1,127 @@
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'soft_keyboard_actions.dart';
/// How much of the soft keyboard input is written to the log.
enum SoftKeyboardTraceLevel {
/// Nothing. The default.
off,
/// Structure only: lengths, ranges and action types. Never any text. It
/// can show where an input sequence went wrong but cannot be replayed.
meta,
/// Everything, including the text that was typed. For development with
/// made-up input only. A trace at this level can be replayed in a test.
full,
}
/// Build with `--dart-define=SOFT_KEYBOARD_TRACE=meta` (or `full`) to turn
/// tracing on. There is deliberately no runtime switch for it.
const String _traceFromEnvironment =
String.fromEnvironment('SOFT_KEYBOARD_TRACE');
SoftKeyboardTraceLevel parseSoftKeyboardTraceLevel(String value) {
for (final level in SoftKeyboardTraceLevel.values) {
if (level.name == value) return level;
}
return SoftKeyboardTraceLevel.off;
}
/// Writes one JSON object per line: a header whenever an interpreter starts,
/// then one line per editing value with the actions derived from it.
///
/// The log lines of a [SoftKeyboardTraceLevel.full] trace can be saved as a
/// fixture as they are. The replay test ignores whatever the log puts in
/// front of the JSON, and starts over at every header.
class SoftKeyboardTrace {
SoftKeyboardTrace(
{SoftKeyboardTraceLevel? level, void Function(String)? sink})
: level = level ?? parseSoftKeyboardTraceLevel(_traceFromEnvironment),
_sink = sink ?? _printLine;
static const String tag = '[soft-keyboard]';
final SoftKeyboardTraceLevel level;
final void Function(String line) _sink;
int _seq = 0;
bool get enabled => level != SoftKeyboardTraceLevel.off;
bool get _withText => level == SoftKeyboardTraceLevel.full;
/// Records that [interpreter] starts from [initial].
void start(SoftKeyboardInterpreter interpreter, TextEditingValue initial,
{required String platform}) {
if (!enabled) return;
_seq = 0;
_sink(jsonEncode({
'trace': 'soft-keyboard',
'v': 1,
'level': level.name,
'platform': platform,
'interpreter': interpreter.name,
'synthetic': false,
'initial': encodeSoftKeyboardValue(initial, withText: _withText),
}));
}
/// Records one editing value and what was derived from it.
void record(TextEditingValue value, List<SoftKeyboardAction> actions,
{String? note}) {
if (!enabled) return;
_sink(jsonEncode({
'n': ++_seq,
...encodeSoftKeyboardValue(value, withText: _withText),
'act': encodeSoftKeyboardActions(actions, withText: _withText),
if (note != null) 'note': note,
}));
}
static void _printLine(String line) => debugPrint('$tag $line');
}
/// Encodes an editing value.
///
/// With text, the sentinel is not spelled out: `lead` is the number of leading
/// sentinel characters and `rest` whatever follows them. Without text there
/// is only the length, because a typed sentinel character cannot be told from
/// the sentinel and splitting the two would give it away.
Map<String, Object?> encodeSoftKeyboardValue(TextEditingValue value,
{required bool withText}) {
final text = value.text;
var lead = 0;
while (lead < text.length && text[lead] == kSoftKeyboardSentinelChar) {
lead++;
}
return {
if (withText) ...{'lead': lead, 'rest': text.substring(lead)} else
'len': text.length,
'sel': [value.selection.baseOffset, value.selection.extentOffset],
'comp': [value.composing.start, value.composing.end],
};
}
/// Encodes actions as `["bs", count]`, `["text", text]`, `["reset"]` and
/// `["set", value]`. Without text, text is replaced by its length.
List<Object?> encodeSoftKeyboardActions(List<SoftKeyboardAction> actions,
{required bool withText}) {
return [
for (final action in actions)
switch (action) {
SoftKeyboardBackspace(:final count) => ['bs', count],
SoftKeyboardText(:final text) => [
'text',
withText ? text : text.length
],
SoftKeyboardResetField() => ['reset'],
SoftKeyboardSetField(:final value) => [
'set',
encodeSoftKeyboardValue(value, withText: withText)
],
}
];
}
+5 -2
View File
@@ -1339,10 +1339,13 @@ class InputModel {
/// Send key stroke event.
/// [down] indicates the key's state(down or up).
/// [press] indicates a click event(down and up).
void inputKey(String name, {bool? down, bool? press}) {
///
/// The returned future completes when the event has been handed to the
/// session. Await it when the next event must not overtake this one.
Future<void> inputKey(String name, {bool? down, bool? press}) async {
if (!keyboardPerm) return;
if (isViewCamera) return;
bind.sessionInputKey(
await bind.sessionInputKey(
sessionId: sessionId,
name: name,
down: down ?? false,
@@ -0,0 +1,7 @@
{"trace": "soft-keyboard", "v": 1, "level": "full", "platform": "android", "interpreter": "forward+mirror", "synthetic": true, "note": "Hand-written. Hangul: the syllable being typed is replaced in place, without a composing range.", "initial": {"lead": 1024, "rest": "", "sel": [1024, 1024], "comp": [-1, -1]}}
{"n": 1, "lead": 1024, "rest": "ㅇ", "sel": [1025, 1025], "comp": [-1, -1], "act": [["text", "ㅇ"]]}
{"n": 2, "lead": 1024, "rest": "아", "sel": [1025, 1025], "comp": [-1, -1], "act": [["bs", 1], ["text", "아"]]}
{"n": 3, "lead": 1024, "rest": "안", "sel": [1025, 1025], "comp": [-1, -1], "act": [["bs", 1], ["text", "안"]]}
{"n": 4, "lead": 1024, "rest": "안ㄴ", "sel": [1026, 1026], "comp": [-1, -1], "act": [["text", "ㄴ"]]}
{"n": 5, "lead": 1024, "rest": "안녀", "sel": [1026, 1026], "comp": [-1, -1], "act": [["bs", 1], ["text", "녀"]]}
{"n": 6, "lead": 1024, "rest": "안녕", "sel": [1026, 1026], "comp": [-1, -1], "act": [["bs", 1], ["text", "녕"]]}
@@ -0,0 +1,4 @@
{"trace": "soft-keyboard", "v": 1, "level": "full", "platform": "android", "interpreter": "forward+mirror", "synthetic": true, "note": "Hand-written. A pair of quotes is inserted with the caret between them, then text is committed there.", "initial": {"lead": 1024, "rest": "", "sel": [1024, 1024], "comp": [-1, -1]}}
{"n": 1, "lead": 1024, "rest": "“”", "sel": [1025, 1025], "comp": [-1, -1], "act": [["text", "“”"]]}
{"n": 2, "lead": 1024, "rest": "“你好”", "sel": [1027, 1027], "comp": [-1, -1], "act": [["bs", 1], ["text", "你好”"]]}
{"n": 3, "lead": 1024, "rest": "“你好”", "sel": [1028, 1028], "comp": [-1, -1], "act": []}
@@ -0,0 +1,5 @@
{"trace": "soft-keyboard", "v": 1, "level": "full", "platform": "ios", "interpreter": "hold+tail", "synthetic": true, "note": "Hand-written. English without a composing range; the last word is replaced.", "initial": {"lead": 1024, "rest": "", "sel": [1024, 1024], "comp": [-1, -1]}}
{"n": 1, "lead": 1024, "rest": "t", "sel": [1025, 1025], "comp": [-1, -1], "act": [["text", "t"]]}
{"n": 2, "lead": 1024, "rest": "te", "sel": [1026, 1026], "comp": [-1, -1], "act": [["text", "e"]]}
{"n": 3, "lead": 1024, "rest": "teh", "sel": [1027, 1027], "comp": [-1, -1], "act": [["text", "h"]]}
{"n": 4, "lead": 1024, "rest": "the ", "sel": [1028, 1028], "comp": [-1, -1], "act": [["bs", 2], ["text", "he "]]}
@@ -0,0 +1,7 @@
{"trace": "soft-keyboard", "v": 1, "level": "full", "platform": "ios", "interpreter": "hold+tail", "synthetic": true, "note": "Hand-written. Romaji: the kana are accepted as they are, so the commit only clears the composing range.", "initial": {"lead": 1024, "rest": "", "sel": [1024, 1024], "comp": [-1, -1]}}
{"n": 1, "lead": 1024, "rest": "あ", "sel": [1025, 1025], "comp": [1024, 1025], "act": []}
{"n": 2, "lead": 1024, "rest": "あり", "sel": [1026, 1026], "comp": [1024, 1026], "act": []}
{"n": 3, "lead": 1024, "rest": "ありが", "sel": [1027, 1027], "comp": [1024, 1027], "act": []}
{"n": 4, "lead": 1024, "rest": "ありがと", "sel": [1028, 1028], "comp": [1024, 1028], "act": []}
{"n": 5, "lead": 1024, "rest": "ありがとう", "sel": [1029, 1029], "comp": [1024, 1029], "act": []}
{"n": 6, "lead": 1024, "rest": "ありがとう", "sel": [1029, 1029], "comp": [-1, -1], "act": [["text", "ありがとう"]]}
@@ -0,0 +1,8 @@
{"trace": "soft-keyboard", "v": 1, "level": "full", "platform": "ios", "interpreter": "hold+tail", "synthetic": true, "note": "Hand-written. Pinyin: the first candidate is picked while the rest is still composing.", "initial": {"lead": 1024, "rest": "", "sel": [1024, 1024], "comp": [-1, -1]}}
{"n": 1, "lead": 1024, "rest": "n", "sel": [1025, 1025], "comp": [1024, 1025], "act": []}
{"n": 2, "lead": 1024, "rest": "ni", "sel": [1026, 1026], "comp": [1024, 1026], "act": []}
{"n": 3, "lead": 1024, "rest": "nih", "sel": [1027, 1027], "comp": [1024, 1027], "act": []}
{"n": 4, "lead": 1024, "rest": "niha", "sel": [1028, 1028], "comp": [1024, 1028], "act": []}
{"n": 5, "lead": 1024, "rest": "nihao", "sel": [1029, 1029], "comp": [1024, 1029], "act": []}
{"n": 6, "lead": 1024, "rest": "你hao", "sel": [1028, 1028], "comp": [1025, 1028], "act": [["text", "你"]]}
{"n": 7, "lead": 1024, "rest": "你好", "sel": [1026, 1026], "comp": [-1, -1], "act": [["text", "好"]]}
@@ -0,0 +1,4 @@
{"trace": "soft-keyboard", "v": 1, "level": "full", "platform": "android", "interpreter": "legacy-android", "synthetic": true, "note": "Hand-written. #7727 with the old handler: a replacement of equal length sends nothing.", "initial": {"lead": 1024, "rest": "", "sel": [1024, 1024], "comp": [-1, -1]}}
{"n": 1, "lead": 1024, "rest": "ㅇ", "sel": [1025, 1025], "comp": [-1, -1], "act": [["text", "ㅇ"]]}
{"n": 2, "lead": 1024, "rest": "아", "sel": [1025, 1025], "comp": [-1, -1], "act": []}
{"n": 3, "lead": 1024, "rest": "안", "sel": [1025, 1025], "comp": [-1, -1], "act": []}
@@ -0,0 +1,5 @@
{"trace": "soft-keyboard", "v": 1, "level": "full", "platform": "ios", "interpreter": "legacy-ios", "synthetic": true, "note": "Hand-written. #16632 with the old handler: the first letter is sent and taken back.", "initial": {"lead": 1024, "rest": "", "sel": [1024, 1024], "comp": [-1, -1]}}
{"n": 1, "lead": 1024, "rest": "n", "sel": [1025, 1025], "comp": [1024, 1025], "act": [["text", "n"]]}
{"n": 2, "lead": 1024, "rest": "ni", "sel": [1026, 1026], "comp": [1024, 1026], "act": []}
{"n": 3, "lead": 1024, "rest": "nihao", "sel": [1029, 1029], "comp": [1024, 1029], "act": []}
{"n": 4, "lead": 1024, "rest": "你好", "sel": [1026, 1026], "comp": [-1, -1], "act": [["bs", 1], ["text", "你好"]]}
@@ -0,0 +1,150 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter_hbb/mobile/soft_keyboard/soft_keyboard.dart';
import 'package:flutter_test/flutter_test.dart';
/// Stands in for the bridge: every send stays open until the test completes
/// it, the way a call stays open until a worker thread has run it.
class _Bridge {
final log = <String>[];
final _open = <Completer<void>>[];
int get inFlight => _open.length;
Future<void> backspace() => _send('<BS>');
Future<void> text(String text) => _send(text);
Future<void> _send(String what) {
log.add(what);
final completer = Completer<void>();
_open.add(completer);
return completer.future;
}
/// Lets the oldest open send return.
Future<void> finishOne({Object? error}) async {
final completer = _open.removeAt(0);
if (error != null) {
completer.completeError(error);
} else {
completer.complete();
}
await pumpEventQueue();
}
Future<void> finishAll() async {
while (_open.isNotEmpty) {
await finishOne();
}
}
}
void main() {
late _Bridge bridge;
late SoftKeyboardDispatcher dispatcher;
setUp(() {
bridge = _Bridge();
dispatcher = SoftKeyboardDispatcher(
sendBackspace: bridge.backspace,
sendText: bridge.text,
);
});
test('sends the first action before returning', () {
dispatcher.dispatch(const [SoftKeyboardText('a')]);
expect(bridge.log, ['a']);
});
test('does not send text before the Backspaces in front of it have returned',
() async {
dispatcher
.dispatch(const [SoftKeyboardBackspace(2), SoftKeyboardText('he ')]);
// The Backspaces go out together.
expect(bridge.log, ['<BS>', '<BS>']);
expect(bridge.inFlight, 2);
await bridge.finishOne();
expect(bridge.log, ['<BS>', '<BS>']);
await bridge.finishOne();
expect(bridge.log, ['<BS>', '<BS>', 'he ']);
await bridge.finishAll();
});
test('does not send an action before the text in front of it has returned',
() async {
dispatcher.dispatch(const [
SoftKeyboardText('a'),
SoftKeyboardBackspace(1),
SoftKeyboardText('b'),
]);
expect(bridge.log, ['a']);
await bridge.finishOne();
expect(bridge.log, ['a', '<BS>']);
await bridge.finishOne();
expect(bridge.log, ['a', '<BS>', 'b']);
await bridge.finishAll();
});
test('keeps the order across dispatches', () async {
dispatcher
.dispatch(const [SoftKeyboardBackspace(1), SoftKeyboardText('마')]);
dispatcher
.dispatch(const [SoftKeyboardBackspace(1), SoftKeyboardText('만')]);
expect(bridge.inFlight, 1);
await bridge.finishAll();
expect(bridge.log, ['<BS>', '마', '<BS>', '만']);
});
test('leaves what concerns the field to the owner of the field', () async {
dispatcher
.dispatch(const [SoftKeyboardText('()'), SoftKeyboardResetField()]);
dispatcher.dispatch(const [SoftKeyboardResetField()]);
dispatcher.dispatch(const [
SoftKeyboardSetField(TextEditingValue(text: 'padding')),
SoftKeyboardText('a'),
]);
await bridge.finishAll();
expect(bridge.log, ['()', 'a']);
});
test('carries on after a failed send, without logging what was typed',
() async {
final printed = <String>[];
final previous = debugPrint;
debugPrint = (String? message, {int? wrapWidth}) => printed.add('$message');
addTearDown(() => debugPrint = previous);
dispatcher
.dispatch(const [SoftKeyboardText('hunter2'), SoftKeyboardText('b')]);
await bridge.finishOne(error: StateError('session closed'));
expect(bridge.log, ['hunter2', 'b']);
await bridge.finishAll();
expect(printed, hasLength(1));
expect(printed.single.contains('hunter2'), isFalse);
dispatcher.dispatch(const [SoftKeyboardText('c')]);
expect(bridge.log, ['hunter2', 'b', 'c']);
});
test('cancel drops what has not been sent', () async {
dispatcher
.dispatch(const [SoftKeyboardBackspace(3), SoftKeyboardText('x')]);
expect(bridge.log, ['<BS>', '<BS>', '<BS>']);
dispatcher.cancel();
await bridge.finishAll();
expect(bridge.log, ['<BS>', '<BS>', '<BS>']);
// And it still works afterwards.
dispatcher.dispatch(const [SoftKeyboardText('y')]);
expect(bridge.log, ['<BS>', '<BS>', '<BS>', 'y']);
});
test('ignores an empty list', () {
dispatcher.dispatch(const []);
expect(bridge.log, isEmpty);
});
}
+104
View File
@@ -0,0 +1,104 @@
// Records what the handlers that used to live in `remote_page.dart` do, the
// failures included. These tests pin behavior; they do not endorse it.
//
// All sequences here are written by hand. They show what the code does with a
// given sequence, not that a keyboard produces that sequence.
import 'package:flutter_test/flutter_test.dart';
import 'soft_keyboard_test_support.dart';
void main() {
group('legacy iOS handler', () {
test('sends plain typing one key at a time', () {
expect(
typed(legacyIos(), ['a', 'ab', 'ab ', 'ab c']), ['a', 'b', ' ', 'c']);
});
test('replays a replaced tail', () {
expect(typed(legacyIos(), ['t', 'te', 'teh', 'the ']),
['t', 'e', 'h', '<BS*2>', 'he ']);
});
test('sends Backspace for deleted text and for a deleted sentinel', () {
final ios = legacyIos();
expect(typed(ios, ['ab', 'a', '']), ['ab', '<BS>', '<BS>']);
expect(sent(ios, [ev('', lead: 1023)]), ['<BS>']);
});
test('still sends the digit 1 after the sentinel got shorter', () {
final ios = legacyIos();
expect(
sent(ios, [ev('', lead: 1023), ev('', lead: 1024)]), ['<BS>', '1']);
});
test('leaks the first letter of a composition (#16632)', () {
expect(
typed(
legacyIos(), ['[n]', '[ni]', '[nih]', '[niha]', '[nihao]', '你好']),
['n', '<BS>', '你好']);
});
test('leaks the rest of a composition on a partial commit', () {
expect(typed(legacyIos(), ['[n]', '[nihao]', '你[hao]', '你好']),
['n', '<BS>', '你hao', '<BS*3>', '好']);
});
test('leaks and retracts the first letter of a cancelled composition', () {
expect(typed(legacyIos(), ['[n]', '[ni]', '']), ['n', '<BS>']);
});
test('misses a commit that does not change the text', () {
// Only the first kana ever arrives.
expect(typed(legacyIos(), ['[あ]', '[あり]', '[ありがとう]', 'ありがとう']), ['あ']);
});
test('sends two Backspaces for one deleted emoji', () {
expect(typed(legacyIos(), ['😀', '']), ['😀', '<BS*2>']);
});
});
group('legacy Android handler', () {
test('sends plain typing one key at a time', () {
expect(typed(legacyAndroid(), ['a', 'ab', 'ab ', 'ab c']),
['a', 'b', ' ', 'c']);
});
test('sends text committed at once as a string', () {
expect(typed(legacyAndroid(), ['你好']), ['你好']);
});
test('sends one Backspace for any deletion', () {
final android = legacyAndroid();
expect(typed(android, ['ab', 'a']), ['ab', '<BS>']);
expect(sent(android, [ev(''), ev('', lead: 1023)]), ['<BS>', '<BS>']);
});
test('ignores a replacement of equal length (#7727)', () {
// The syllable never arrives, only its first jamo.
expect(typed(legacyAndroid(), ['ㅁ', '마', '만']), ['ㅁ']);
});
test('sends one Backspace when a composition gets shorter on commit', () {
// The converted text never arrives.
expect(typed(legacyAndroid(), ['n', 'ni', 'nih', 'niha', 'nihao', '你好']),
['n', 'i', 'h', 'a', 'o', '<BS>']);
});
test('sends the wrong text for an insertion that is not at the end', () {
expect(typed(legacyAndroid(), ['“|”', '“你好|”']), ['“”', '好”']);
});
test('resets the field after a pair of brackets', () {
expect(sent(legacyAndroid(), [plain('a'), plain('a()', caret: 2)]),
['a', '()', '<RESET>']);
expect(sent(legacyAndroid(), [plain('[]', caret: 1)]), ['[]', '<RESET>']);
});
test('sends the whole text when the sentinel is replaced', () {
expect(
sent(legacyAndroid(), [const TextEditingValue(text: 'pasted text')]),
['pasted text']);
});
});
}
@@ -0,0 +1,537 @@
// All sequences here are written by hand. They show what the interpreter does
// with a given sequence, not that a keyboard produces that sequence.
import 'dart:math';
import 'package:flutter/services.dart';
import 'package:flutter_hbb/mobile/soft_keyboard/soft_keyboard.dart';
import 'package:flutter_test/flutter_test.dart';
import 'soft_keyboard_test_support.dart';
void main() {
group('iOS: composing text is held', () {
test('a composition sends only what is committed', () {
expect(
typed(newIos(), ['[n]', '[ni]', '[nih]', '[niha]', '[nihao]', '你好']),
['你好']);
});
test('a partial commit sends exactly the committed part', () {
expect(typed(newIos(), ['[n]', '[nihao]', '你[hao]', '你好']), ['你', '好']);
});
test('Backspace inside a composition sends nothing', () {
expect(typed(newIos(), ['[n]', '[ni]', '[nih]', '[ni]', '你']), ['你']);
});
test('a commit that does not change the text is sent', () {
expect(typed(newIos(), ['[你]', '你']), ['你']);
expect(typed(newIos(), ['[あ]', '[あり]', '[ありがとう]', 'ありがとう']), ['ありがとう']);
});
test('a cancelled composition sends nothing', () {
expect(typed(newIos(), ['[n]', '[ni]', '']), isEmpty);
});
test('a composition after committed text leaves that text alone', () {
expect(typed(newIos(), ['ab', 'ab[ni]', 'ab你']), ['ab', '你']);
});
test('committing the letters as they are sends them once', () {
// Return on the Pinyin keyboard commits the letters typed so far.
expect(typed(newIos(), ['[ni]', '[nihao]', 'nihao']), ['nihao']);
});
test('the same text committed twice is sent twice', () {
expect(typed(newIos(), ['[ni]', '你', '你[ni]', '你你']), ['你', '你']);
});
test('a change of selection alone sends nothing', () {
expect(typed(newIos(), ['ab', 'a|b', '|ab', 'ab']), ['ab']);
});
test('composing text that covers sent text is followed, not retracted', () {
final ios = newIos();
// The keyboard marks the committed character as composing again.
expect(typed(ios, ['你', '[你]']), ['你']);
expect(ios.lastNote, 'composing covers sent text');
// And then replaces it.
expect(typed(ios, ['尼']), ['<BS>', '尼']);
});
});
group('iOS: without a composing range nothing changes', () {
test('plain typing', () {
expect(typed(newIos(), ['a', 'ab', 'ab ', 'ab c']), ['a', 'b', ' ', 'c']);
});
test('a replaced tail', () {
expect(typed(newIos(), ['t', 'te', 'teh', 'the ']),
['t', 'e', 'h', '<BS*2>', 'he ']);
});
test('Backspace, also into the sentinel, and the digit 1 afterwards', () {
final ios = newIos();
expect(typed(ios, ['ab', 'a', '']), ['ab', '<BS>', '<BS>']);
expect(
sent(ios, [ev('', lead: 1023), ev('', lead: 1024)]), ['<BS>', '1']);
});
test('Return and Space', () {
expect(typed(newIos(), ['a', 'a\n', 'a\n ']), ['a', '\n', ' ']);
});
// The claim behind enabling this on iOS by default: fed the same editing
// values, none of which has a composing range, the new interpreter and
// the old handler send the same thing at every step.
test('matches the old handler on random editing sequences', () {
final random = Random(16632);
for (var run = 0; run < 400; run++) {
final oldHandler = legacyIos();
final newHandler = newIos();
var lead = 1024;
var rest = '';
for (var step = 0; step < 60; step++) {
final roll = random.nextInt(10);
var caret = rest.length;
if (roll < 5) {
rest += _randomText(random, 1 + random.nextInt(3));
} else if (roll < 7 && rest.isNotEmpty) {
rest = rest.substring(0, rest.length - 1);
} else if (roll == 7 && rest.isNotEmpty) {
// Something like an autocorrection: the tail is replaced.
final cut = 1 + random.nextInt(min(4, rest.length));
rest = rest.substring(0, rest.length - cut) +
_randomText(random, random.nextInt(4));
} else if (roll == 8 && rest.isEmpty && lead > 0) {
lead--;
} else {
// Only the caret moves.
caret = random.nextInt(rest.length + 1);
}
final value = plain(rest, lead: lead, caret: caret);
expect(tokens(newHandler.update(value)),
tokens(oldHandler.update(value)),
reason: 'run $run step $step: "$rest" with $lead sentinels');
}
}
});
// And with compositions mixed in: what has been sent is always exactly
// the committed text. Nothing provisional, nothing missing.
test('the remote text is always the committed text', () {
final random = Random(8471);
for (var run = 0; run < 400; run++) {
final ios = newIos();
final remote = RemoteText(backspaceDeletesCodePoint: false);
var committed = '';
var composing = '';
for (var step = 0; step < 60; step++) {
final roll = random.nextInt(10);
if (composing.isEmpty) {
if (roll < 4) {
composing = _randomLetters(random, 1);
} else if (roll < 7) {
committed += _randomBmpText(random, 1 + random.nextInt(2));
} else if (committed.isNotEmpty) {
committed = committed.substring(0, committed.length - 1);
}
} else {
if (roll < 4) {
composing += _randomLetters(random, 1);
} else if (roll < 5) {
composing = composing.substring(0, composing.length - 1);
} else if (roll < 7) {
// The whole composition is converted and committed.
committed += _randomCjk(random, 1 + random.nextInt(2));
composing = '';
} else if (roll < 9 && composing.length > 1) {
// The first part is committed, the rest keeps composing.
committed += _randomCjk(random, 1);
composing = composing.substring(1);
} else {
// Committed as typed. The text does not change.
committed += composing;
composing = '';
}
}
final value =
ev(composing.isEmpty ? committed : '$committed[$composing]');
remote.apply(ios.update(value));
expect(remote.text, committed, reason: 'run $run step $step');
expect(remote.overrun, 0, reason: 'run $run step $step');
}
}
});
});
group('Android: the field is mirrored', () {
test('plain typing and deleting', () {
expect(typed(newAndroid(), ['a', 'ab', 'ab ', 'ab c', 'ab ']),
['a', 'b', ' ', 'c', '<BS>']);
});
test('text committed at once is sent as a string', () {
expect(typed(newAndroid(), ['你好']), ['你好']);
});
test('a syllable edited in place is replaced (#7727)', () {
expect(typed(newAndroid(), ['ㅁ', '마', '만', '마나']),
['ㅁ', '<BS>', '마', '<BS>', '만', '<BS>', '마나']);
});
test('a syllable is replaced whether or not it is marked as composing', () {
expect(typed(newAndroid(), ['[ㅁ]', '[마]', '[만]', '만[ㄴ]']),
['ㅁ', '<BS>', '마', '<BS>', '만', 'ㄴ']);
});
test('composing letters are replaced by the committed text', () {
expect(
typed(newAndroid(),
['[n]', '[ni]', '[nih]', '[niha]', '[nihao]', '你好']),
['n', 'i', 'h', 'a', 'o', '<BS*5>', '你好']);
});
test('a word replaced by a suggestion', () {
expect(typed(newAndroid(), ['[teh]', 'the ']), ['teh', '<BS*2>', 'he ']);
});
test('text inserted inside a pair of quotes (#16535)', () {
// The keyboard leaves the caret between the quotes, so what comes next
// is not appended.
expect(typed(newAndroid(), ['“|”', '“你好|”', '“你好吗|”']),
['“”', '<BS>', '你好”', '<BS>', '吗”']);
});
test('a pair of brackets needs no field reset', () {
expect(
sent(newAndroid(),
[plain('a'), plain('a()', caret: 2), plain('a(b)', caret: 3)]),
['a', '()', '<BS>', 'b)']);
});
test('text deleted before the caret', () {
expect(typed(newAndroid(), ['(ab|)', '(a|)']), ['(ab)', '<BS*2>', ')']);
});
test('a deleted emoji is one Backspace', () {
expect(typed(newAndroid(), ['😀', '']), ['😀', '<BS>']);
expect(typed(newAndroid(), ['a👨‍👩‍👧', 'a']), ['a👨‍👩‍👧', '<BS>']);
});
test('several characters deleted at once are that many Backspaces', () {
expect(typed(newAndroid(), ['one two', 'one ']), ['one two', '<BS*3>']);
});
test('an emoji replaced by another one', () {
expect(typed(newAndroid(), ['😀', '😁']), ['😀', '<BS>', '😁']);
});
test('a change of selection or composing range alone sends nothing', () {
expect(typed(newAndroid(), ['ab', 'a|b', '[ab]', 'ab']), ['ab']);
});
group('the sentinel', () {
test('is deleted one Backspace at a time', () {
final android = newAndroid();
expect(sent(android, [ev('', lead: 1023), ev('', lead: 1022)]),
['<BS>', '<BS>']);
});
test('is one Backspace however much of it is deleted at once', () {
expect(sent(newAndroid(), [ev('', lead: 0)]), ['<BS>']);
expect(sent(newAndroid(), [ev('', lead: 1000)]), ['<BS>']);
});
test('is never typed back', () {
final android = newAndroid();
expect(sent(android, [ev('', lead: 1023), ev('가', lead: 1023)]),
['<BS>', '가']);
expect(sent(android, [ev('각', lead: 1023)]), ['<BS>', '각']);
});
test('does not swallow the digit 1', () {
final android = newAndroid();
expect(typed(android, ['1', '11', '1']), ['1', '1', '<BS>']);
// Also after the sentinel got shorter.
expect(sent(android, [ev(''), ev('', lead: 1023), ev('', lead: 1024)]),
['<BS>', '<BS>', '1']);
});
test('deleted together with typed text counts the typed text', () {
expect(sent(newAndroid(), [ev('ab'), ev('', lead: 1021)]),
['ab', '<BS*3>']);
});
test('replaced as a whole sends the new text only', () {
final android = newAndroid();
expect(sent(android, [const TextEditingValue(text: 'pasted text')]),
['pasted text']);
expect(android.lastNote, 'at caret: edit inside the sentinel');
});
test('typed into sends the text and is not replayed afterwards', () {
final android = newAndroid();
// The caret was moved into the sentinel.
TextEditingValue inSentinel(String typed) => TextEditingValue(
text: '${'1' * 1000}$typed${'1' * 24}',
selection: TextSelection.collapsed(offset: 1000 + typed.length));
expect(sent(android, [inSentinel('a')]), ['a']);
// No Backspaces through the 24 characters after the caret.
expect(sent(android, [inSentinel('ab')]), ['b']);
expect(sent(android, [inSentinel('a')]), ['<BS>']);
});
});
group('what cannot be replayed', () {
test('a replacement longer than the limit is dropped', () {
final android = SoftKeyboardReducer(
policy: ComposingPolicy.forward,
diff: MirrorSoftKeyboardDiff(maxReplay: 4),
initial: ev(''),
);
expect(typed(android, ['abcde', 'ABCDE']), ['abcde']);
expect(android.lastNote, 'dropped: replacement cannot be replayed');
});
test('a replacement inside a character cluster is dropped', () {
final android = newAndroid();
// The skin tone changes. Applications disagree on whether Backspace
// removes the modifier or the whole emoji.
expect(typed(android, ['👍🏽', '👍🏿']), ['👍🏽']);
expect(android.lastNote, 'dropped: replacement cannot be replayed');
});
test('only freezes the text up to that point', () {
final android = newAndroid();
expect(typed(android, ['👍🏽', '👍🏿']), ['👍🏽']);
// Typing goes on, and what is typed from here on is replayed again.
expect(typed(android, ['👍🏿ㅁ', '👍🏿마']), ['ㅁ', '<BS>', '마']);
// Backspace still is Backspace.
expect(typed(android, ['👍🏿', '']), ['<BS>', '<BS>']);
});
test('is not edited later either', () {
final android = SoftKeyboardReducer(
policy: ComposingPolicy.forward,
diff: MirrorSoftKeyboardDiff(maxReplay: 4),
initial: ev(''),
);
// The remote side keeps "abcde". From here on a position in the
// local text says nothing about a position in the remote text.
expect(typed(android, ['abcde', 'XY']), ['abcde']);
expect(typed(android, ['XZ']), isEmpty);
expect(android.lastNote, 'dropped: replacement cannot be replayed');
// What is typed after it is mirrored again.
expect(typed(android, ['XZw', 'XZv']), ['w', '<BS>', 'v']);
});
test('a line break is never deleted and typed again', () {
final android = newAndroid();
expect(typed(android, ['a\n', 'b\n']), ['a', '\n']);
expect(android.lastNote, 'dropped: replacement cannot be replayed');
// Typing in front of it goes to the caret instead.
expect(typed(android, ['bX|\n']), ['X']);
expect(android.lastNote,
'at caret: text after the edit cannot be replayed');
});
test('Return typed with other text is still sent on its own', () {
// On its own it goes out as the key. Inside a string it would only
// be a character.
expect(typed(newAndroid(), ['teh', 'the\n']),
['teh', '<BS*2>', 'he', '\n']);
expect(
typed(newAndroid(), ['(|)', '(\n|)']), ['()', '<BS>', '\n', ')']);
expect(typed(newAndroid(), ['a', 'ab\n']), ['a', 'b', '\n']);
});
test('a line break inside committed text stays text', () {
expect(typed(newAndroid(), ['one\ntwo']), ['one\ntwo']);
});
test('Backspace after Return is still one Backspace', () {
expect(typed(newAndroid(), ['a', 'a\n', 'a']), ['a', '\n', '<BS>']);
});
test('a replacement in front of too much text is dropped', () {
final android = SoftKeyboardReducer(
policy: ComposingPolicy.forward,
diff: MirrorSoftKeyboardDiff(maxReplay: 4),
initial: ev(''),
);
expect(typed(android, ['teh abcdef', 'the| abcdef']), ['teh abcdef']);
expect(android.lastNote, 'dropped: replacement cannot be replayed');
});
test('Backspace in front of too much text is still Backspace', () {
final android = SoftKeyboardReducer(
policy: ComposingPolicy.forward,
diff: MirrorSoftKeyboardDiff(maxReplay: 4),
initial: ev(''),
);
expect(typed(android, ['xabcdef', '|abcdef']), ['xabcdef', '<BS>']);
expect(android.lastNote,
'at caret: text after the edit cannot be replayed');
});
test('an insertion in front of too much text is sent on its own', () {
final android = SoftKeyboardReducer(
policy: ComposingPolicy.forward,
diff: MirrorSoftKeyboardDiff(maxReplay: 4),
initial: ev(''),
);
expect(typed(android, ['abcdef', 'X|abcdef']), ['abcdef', 'X']);
expect(android.lastNote,
'at caret: text after the edit cannot be replayed');
});
test('a deletion is never more Backspaces than the limit', () {
final android = SoftKeyboardReducer(
policy: ComposingPolicy.forward,
diff: MirrorSoftKeyboardDiff(maxReplay: 4),
initial: ev(''),
);
expect(typed(android, ['abcdefgh', 'ab']), ['abcdefgh', '<BS*4>']);
expect(android.lastNote, 'clamped: more Backspaces than the limit');
// The remote side still has "abgh". What is left of it is not edited.
expect(typed(android, ['ac']), isEmpty);
expect(android.lastNote, 'dropped: replacement cannot be replayed');
expect(typed(android, ['acd', 'ace']), ['d', '<BS>', 'e']);
});
});
// On sequences the old handler gets right, appending and deleting one
// character at the end, the new interpreter sends the same thing.
test('matches the old handler on appending and deleting', () {
final random = Random(9790);
for (var run = 0; run < 400; run++) {
final oldHandler = legacyAndroid();
final newHandler = newAndroid();
var lead = 1024;
var rest = '';
for (var step = 0; step < 60; step++) {
final roll = random.nextInt(10);
if (roll < 6) {
// No brackets: the old handler resets the field after a pair.
// And Return only on its own: typed together with other text,
// the old handler sends it as a character in a string.
var chunk = _randomBmpText(random, 1 + random.nextInt(3))
.replaceAll(RegExp(r'[()]'), 'x');
if (chunk.length > 1) chunk = chunk.replaceAll('\n', ' ');
rest += chunk;
} else if (rest.isNotEmpty) {
rest = rest.substring(0, rest.length - 1);
} else if (lead > 0) {
lead--;
}
final value = plain(rest, lead: lead);
expect(tokens(newHandler.update(value)),
tokens(oldHandler.update(value)),
reason: 'run $run step $step: "$rest" with $lead sentinels');
}
}
});
// Whatever is done to the typed text, at the end or in the middle, the
// remote text stays equal to it. Within one line, that is: Return is a
// key press and is never replayed.
test('the remote text always equals the typed text', () {
final random = Random(7727);
String oneLine(Random random, int length) =>
_randomBmpText(random, length).replaceAll('\n', ' ');
for (var run = 0; run < 400; run++) {
final android = newAndroid();
final remote = RemoteText(backspaceDeletesCodePoint: true);
var rest = '';
for (var step = 0; step < 60; step++) {
final roll = random.nextInt(10);
// Keep within what may be replayed.
final from = max(0, rest.length - 20);
final at = from + random.nextInt(rest.length - from + 1);
if (roll < 4 || rest.isEmpty) {
rest += oneLine(random, 1 + random.nextInt(3));
} else if (roll < 6) {
rest = rest.substring(0, rest.length - 1);
} else if (roll < 8) {
// Replace from somewhere to the end.
rest = rest.substring(0, at) + oneLine(random, random.nextInt(4));
} else if (roll < 9) {
// Insert somewhere.
rest = rest.substring(0, at) +
oneLine(random, 1 + random.nextInt(2)) +
rest.substring(at);
} else if (at < rest.length) {
// Delete somewhere.
rest = rest.substring(0, at) + rest.substring(at + 1);
}
remote.apply(android.update(plain(rest)));
expect(remote.text, rest, reason: 'run $run step $step');
expect(remote.overrun, 0, reason: 'run $run step $step');
expect(android.lastNote, isNull, reason: 'run $run step $step');
}
}
});
});
group('Android keyboards that only compose real compositions', () {
// Not used yet. Holding composing text on Android needs a way to tell
// such a keyboard from one that also composes plain words.
SoftKeyboardInterpreter holdAndMirror() =>
interpreterByName('hold+mirror', ev(''));
test('a composition sends only what is committed', () {
expect(typed(holdAndMirror(), ['[n]', '[nihao]', '你[hao]', '你好']),
['你', '好']);
});
test('a syllable is sent when it is complete', () {
expect(
typed(holdAndMirror(), ['[ㅁ]', '[마]', '[만]', '만[ㄴ]', '만[나]', '만나']),
['만', '나']);
});
});
group('choosing the interpreter', () {
test('by platform and option', () {
String name({required bool isIOS, required bool useReducer}) =>
createSoftKeyboardInterpreter(
isIOS: isIOS, useReducer: useReducer, initial: ev(''))
.name;
expect(name(isIOS: true, useReducer: true), 'hold+tail');
expect(name(isIOS: true, useReducer: false), 'legacy-ios');
expect(name(isIOS: false, useReducer: true), 'forward+mirror');
expect(name(isIOS: false, useReducer: false), 'legacy-android');
});
});
}
const _letters = 'abcdefghijklmnopqrstuvwxyz';
const _cjk = '你好中文日本語한국어가나다';
const _bmp = '${_letters}ABC 1.,\n()$_cjk';
const _emoji = ['😀', '🎉'];
String _randomLetters(Random random, int length) => String.fromCharCodes([
for (var i = 0; i < length; i++)
_letters.codeUnitAt(random.nextInt(_letters.length))
]);
String _randomCjk(Random random, int length) => String.fromCharCodes([
for (var i = 0; i < length; i++)
_cjk.codeUnitAt(random.nextInt(_cjk.length))
]);
/// Characters of one UTF-16 code unit each.
String _randomBmpText(Random random, int length) => String.fromCharCodes([
for (var i = 0; i < length; i++)
_bmp.codeUnitAt(random.nextInt(_bmp.length))
]);
/// Like [_randomBmpText], with the occasional emoji.
String _randomText(Random random, int length) => [
for (var i = 0; i < length; i++)
random.nextInt(12) == 0
? _emoji[random.nextInt(_emoji.length)]
: _randomBmpText(random, 1)
].join();
@@ -0,0 +1,167 @@
import 'package:flutter/services.dart';
import 'package:flutter_hbb/mobile/soft_keyboard/soft_keyboard.dart';
/// The hidden field as it is when the keyboard opens.
final String sentinel = kSoftKeyboardSentinelChar * 1024;
/// Builds an editing value from a compact description of what follows the
/// sentinel.
///
/// `[` and `]` enclose the composing range and `|` marks the caret, which is
/// at the end when not given. `ev('你[hao]')` is the committed `你` followed by
/// `hao` still being composed.
TextEditingValue ev(String spec, {int lead = 1024}) {
final text = StringBuffer(kSoftKeyboardSentinelChar * lead);
int? composingStart;
int? composingEnd;
int? caret;
for (final rune in spec.runes) {
final char = String.fromCharCode(rune);
if (char == '[') {
composingStart = text.length;
} else if (char == ']') {
composingEnd = text.length;
} else if (char == '|') {
caret = text.length;
} else {
text.write(char);
}
}
return TextEditingValue(
text: text.toString(),
selection: TextSelection.collapsed(offset: caret ?? text.length),
composing: composingStart == null
? TextRange.empty
: TextRange(start: composingStart, end: composingEnd!),
);
}
/// Like [ev], for text that contains `[`, `]` or `|` itself.
TextEditingValue plain(String rest, {int lead = 1024, int? caret}) {
final text = kSoftKeyboardSentinelChar * lead + rest;
return TextEditingValue(
text: text,
selection: TextSelection.collapsed(
offset: caret == null ? text.length : lead + caret),
);
}
/// Renders actions as short tokens: the text itself, `<BS>` for one Backspace
/// and `<BS*n>` for several, `<RESET>` for a field reset, `<SET>` for a
/// correction of the field.
List<String> tokens(List<SoftKeyboardAction> actions) => [
for (final action in actions)
switch (action) {
SoftKeyboardBackspace(:final count) =>
count == 1 ? '<BS>' : '<BS*$count>',
SoftKeyboardText(:final text) => text,
SoftKeyboardResetField() => '<RESET>',
SoftKeyboardSetField() => '<SET>',
}
];
/// Feeds [values] to [interpreter] and returns everything it sent, in order.
List<String> sent(
SoftKeyboardInterpreter interpreter, List<TextEditingValue> values) {
return [for (final value in values) ...tokens(interpreter.update(value))];
}
/// Like [sent], for values written as [ev] descriptions.
List<String> typed(SoftKeyboardInterpreter interpreter, List<String> specs) =>
sent(interpreter, [for (final spec in specs) ev(spec)]);
SoftKeyboardInterpreter legacyIos() => LegacyIosSoftKeyboard(ev(''));
SoftKeyboardInterpreter legacyAndroid() => LegacyAndroidSoftKeyboard(ev(''));
SoftKeyboardInterpreter newIos() => SoftKeyboardReducer.ios(ev(''));
SoftKeyboardInterpreter newAndroid() => SoftKeyboardReducer.android(ev(''));
/// Creates the interpreter a trace was recorded with, from the `interpreter`
/// field of its header.
SoftKeyboardInterpreter interpreterByName(
String name, TextEditingValue initial) {
switch (name) {
case 'legacy-ios':
return LegacyIosSoftKeyboard(initial);
case 'legacy-android':
return LegacyAndroidSoftKeyboard(initial);
case 'hold+tail':
return SoftKeyboardReducer.ios(initial);
case 'forward+mirror':
return SoftKeyboardReducer.android(initial);
case 'hold+mirror':
// Not used by the app. Holding composing text on Android needs a way
// to tell a keyboard that only composes real compositions from one
// that also composes plain words.
return SoftKeyboardReducer(
policy: ComposingPolicy.hold,
diff: MirrorSoftKeyboardDiff(),
initial: initial,
);
}
throw ArgumentError.value(name, 'name', 'unknown soft keyboard interpreter');
}
/// The inverse of [encodeSoftKeyboardValue] for values encoded with text.
TextEditingValue decodeValue(Map<String, Object?> json) {
final sel = (json['sel'] as List).cast<int>();
final comp = (json['comp'] as List).cast<int>();
return TextEditingValue(
text: kSoftKeyboardSentinelChar * (json['lead'] as int) +
(json['rest'] as String),
selection: TextSelection(baseOffset: sel[0], extentOffset: sel[1]),
composing: TextRange(start: comp[0], end: comp[1]),
);
}
/// The inverse of [encodeSoftKeyboardActions] for actions encoded with text.
List<SoftKeyboardAction> decodeActions(List<Object?> json) {
return [
for (final action in json.cast<List>())
switch (action[0]) {
'bs' => SoftKeyboardBackspace(action[1] as int),
'text' => SoftKeyboardText(action[1] as String),
'reset' => const SoftKeyboardResetField(),
'set' => SoftKeyboardSetField(
decodeValue((action[1] as Map).cast<String, Object?>())),
_ => throw FormatException('unknown soft keyboard action: $action'),
}
];
}
/// A stand-in for the remote text field: Backspace deletes before the caret,
/// which is at the end, and text is appended.
class RemoteText {
RemoteText({required this.backspaceDeletesCodePoint});
/// Whether Backspace deletes a whole code point, or one UTF-16 code unit.
/// The old iOS tail diff counts code units.
final bool backspaceDeletesCodePoint;
String text = '';
/// Backspaces that found nothing to delete: they went past what was typed.
int overrun = 0;
void apply(List<SoftKeyboardAction> actions) {
for (final action in actions) {
switch (action) {
case SoftKeyboardBackspace(:final count):
for (var i = 0; i < count; i++) {
if (text.isEmpty) {
overrun++;
} else if (backspaceDeletesCodePoint) {
final runes = text.runes.toList()..removeLast();
text = String.fromCharCodes(runes);
} else {
text = text.substring(0, text.length - 1);
}
}
case SoftKeyboardText(:final text):
this.text += text;
case SoftKeyboardResetField():
case SoftKeyboardSetField():
break;
}
}
}
}
@@ -0,0 +1,364 @@
// Runs the soft keyboard input behind a real text field, set up like the
// hidden one on the remote page, with editing values injected the way the
// engine delivers them. This checks how the field reports changes. It does
// not show what a keyboard sends.
import 'package:flutter/material.dart';
import 'package:flutter_hbb/mobile/soft_keyboard/soft_keyboard.dart';
import 'package:flutter_test/flutter_test.dart';
import 'soft_keyboard_test_support.dart';
typedef _Create = SoftKeyboardInterpreter Function(TextEditingValue initial);
void main() {
late TextEditingController controller;
late FocusNode focusNode;
late List<String> onChangedCalls;
/// Everything that was sent: the text, and `<BS>` once per Backspace.
late List<String> out;
late bool allowed;
late int reopened;
Future<SoftKeyboardInput> pumpField(WidgetTester tester, _Create create,
{bool attachBeforeField = true}) async {
controller = TextEditingController(text: sentinel);
addTearDown(controller.dispose);
focusNode = FocusNode();
addTearDown(focusNode.dispose);
onChangedCalls = [];
out = [];
allowed = true;
reopened = 0;
final input = SoftKeyboardInput(
controller: controller,
focusNode: focusNode,
sentinel: sentinel,
createInterpreter: create,
dispatcher: SoftKeyboardDispatcher(
sendBackspace: () async => out.add('<BS>'),
sendText: (text) async => out.add(text),
),
isAllowed: () => allowed,
reopenKeyboard: () => reopened++,
trace: SoftKeyboardTrace(level: SoftKeyboardTraceLevel.off),
);
// On the remote page the input is attached long before the field exists.
if (attachBeforeField) input.attach();
addTearDown(input.detach);
await tester.pumpWidget(MaterialApp(
home: Material(
child: TextFormField(
textInputAction: TextInputAction.newline,
autocorrect: false,
autofocus: true,
focusNode: focusNode,
maxLines: null,
controller: controller,
keyboardType: TextInputType.multiline,
onChanged: onChangedCalls.add,
),
),
));
if (!attachBeforeField) input.attach();
await tester.showKeyboard(find.byType(TextFormField));
return input;
}
/// Delivers [value] as the keyboard would, and lets the sends finish.
Future<void> type(WidgetTester tester, TextEditingValue value) async {
tester.testTextInput.updateEditingValue(value);
await tester.pump();
}
for (final (name, create) in <(String, _Create)>[
('iOS', LegacyIosSoftKeyboard.new),
('Android', LegacyAndroidSoftKeyboard.new),
]) {
testWidgets(
'the old $name handler sees through the controller what onChanged gave it',
(tester) async {
await pumpField(tester, create);
// The same handler, driven by onChanged as it used to be. Its own
// check for an unchanged text never triggers there.
final direct = create(ev(''));
final viaOnChanged = <String>[];
var seen = 0;
void drain() {
for (; seen < onChangedCalls.length; seen++) {
for (final action in direct.update(controller.value)) {
switch (action) {
case SoftKeyboardBackspace(:final count):
viaOnChanged.addAll(List.filled(count, '<BS>'));
case SoftKeyboardText(:final text):
viaOnChanged.add(text);
case SoftKeyboardResetField():
case SoftKeyboardSetField():
break;
}
}
}
}
for (final spec in [
'[n]', '[ni]', '你', '你|', '你a', '你ab', '你a', '你a[b]', '你ab', //
'', '(|)', '(x|)',
]) {
await type(tester, ev(spec));
drain();
}
expect(out, viaOnChanged);
expect(out, isNotEmpty);
});
}
testWidgets('the field starts over when it loses focus', (tester) async {
await pumpField(tester, LegacyIosSoftKeyboard.new);
await type(tester, ev('ab'));
focusNode.unfocus();
await tester.pump();
expect(controller.value, TextEditingValue(text: sentinel));
expect(out, ['ab']);
// What was typed before is gone from the field, so Backspace reaches the
// sentinel. It still is one Backspace.
await tester.showKeyboard(find.byType(TextFormField));
await type(tester, ev('', lead: 1023));
expect(out, ['ab', '<BS>']);
});
for (final (name, create) in <(String, _Create)>[
('old iOS handler', LegacyIosSoftKeyboard.new),
('old Android handler', LegacyAndroidSoftKeyboard.new),
]) {
testWidgets('refilling the field is not taken for input by the $name',
(tester) async {
final input = await pumpField(tester, create);
await type(tester, ev('abc'));
expect(out, ['abc']);
// What the page does when the keyboard is opened again.
input.refill();
await tester.pump();
expect(controller.text, sentinel);
expect(out, ['abc']);
await type(tester, ev('d'));
expect(out, ['abc', 'd']);
});
}
testWidgets('a field that was just refilled does not start over again',
(tester) async {
var created = 0;
final input = await pumpField(tester, (initial) {
created++;
return LegacyAndroidSoftKeyboard(initial);
});
await type(tester, ev('a'));
// Opening the keyboard refills the field and then takes it away, which
// also takes its focus.
input.refill();
final afterRefill = created;
focusNode.unfocus();
await tester.pump();
expect(created, afterRefill);
});
testWidgets(
'an interpreter can correct the field without anything being sent',
(tester) async {
late _Correcting interpreter;
await pumpField(tester, (initial) => interpreter = _Correcting());
// Getting focus already moved the caret, which the interpreter saw.
interpreter.seen.clear();
// Backspace takes one character of padding. The interpreter sends the
// Backspace and asks for the padding back.
await type(tester, ev('', lead: 1023));
expect(out, ['<BS>']);
expect(controller.value, ev(''));
// It was given the keyboard's value and then its own correction.
expect(interpreter.seen, [ev('', lead: 1023), ev('')]);
await type(tester, ev('a'));
expect(out, ['<BS>']);
expect(interpreter.seen.last, ev('a'));
});
testWidgets('a correction answered with another correction is written once',
(tester) async {
await pumpField(tester, (initial) => _NeverSatisfied());
await type(tester, ev('a'));
expect(controller.text, '${sentinel}a!');
expect(out, isEmpty);
});
testWidgets('nothing is sent while input is not allowed', (tester) async {
await pumpField(tester, LegacyAndroidSoftKeyboard.new);
allowed = false;
await type(tester, ev('a'));
await type(tester, ev('ab'));
expect(out, isEmpty);
});
testWidgets('the old Android handler has the keyboard reopened after a pair',
(tester) async {
await pumpField(tester, LegacyAndroidSoftKeyboard.new);
await type(tester, ev('a'));
expect(reopened, 0);
await type(tester, ev('a(|)'));
expect(out, ['a', '()']);
expect(reopened, 1);
});
testWidgets('nothing is sent after detaching', (tester) async {
final input = await pumpField(tester, LegacyAndroidSoftKeyboard.new);
await type(tester, ev('a'));
input.detach();
await type(tester, ev('ab'));
expect(out, ['a']);
});
// With the interpreters that know about composing text.
testWidgets(
'a commit that leaves the text as it is reaches the controller but not onChanged',
(tester) async {
await pumpField(tester, SoftKeyboardReducer.ios);
await type(tester, ev('[あり]'));
expect(onChangedCalls, hasLength(1));
expect(out, isEmpty);
await type(tester, ev('あり'));
// The text did not change, so onChanged stays silent ...
expect(onChangedCalls, hasLength(1));
// ... but the controller reports the change, and the text is sent.
expect(controller.value.composing, TextRange.empty);
expect(out, ['あり']);
});
testWidgets('a composition is sent once, when it is committed',
(tester) async {
await pumpField(tester, SoftKeyboardReducer.ios);
for (final spec in ['[n]', '[ni]', '[nihao]', '你[hao]', '你好', '你好\n']) {
await type(tester, ev(spec));
}
expect(out, ['你', '好', '\n']);
});
testWidgets('composing text is dropped when the field loses focus',
(tester) async {
await pumpField(tester, SoftKeyboardReducer.ios);
await type(tester, ev('ab'));
await type(tester, ev('ab[nihao]'));
expect(out, ['ab']);
// The framework clears the composing range of a field that loses focus
// and keeps the text. That is not the keyboard committing the letters.
focusNode.unfocus();
await tester.pump();
expect(out, ['ab']);
// The field starts over, so the letters cannot come back later either.
expect(controller.value, TextEditingValue(text: sentinel));
await tester.showKeyboard(find.byType(TextFormField));
await type(tester, ev('[ni]'));
await type(tester, ev('你'));
expect(out, ['ab', '你']);
// What was typed before the field lost focus is gone from it, so
// Backspace now reaches the sentinel. It still is one Backspace.
await type(tester, ev(''));
await type(tester, ev('', lead: 1023));
expect(out, ['ab', '你', '<BS>', '<BS>']);
});
testWidgets(
'composing text is dropped when the field hears of the focus loss first',
(tester) async {
// Listeners are told in the order they were added. Here the field clears
// its composing range before the input has refilled it.
await pumpField(tester, SoftKeyboardReducer.ios, attachBeforeField: false);
await type(tester, ev('[nihao]'));
focusNode.unfocus();
await tester.pump();
expect(out, isEmpty);
expect(controller.value, TextEditingValue(text: sentinel));
});
for (final (name, create) in <(String, _Create)>[
('iOS interpreter', SoftKeyboardReducer.ios),
('Android interpreter', SoftKeyboardReducer.android),
]) {
testWidgets('refilling the field is not taken for input by the $name',
(tester) async {
final input = await pumpField(tester, create);
await type(tester, ev('abc'));
expect(out, ['abc']);
// What the page does when the keyboard is opened again.
input.refill();
await tester.pump();
expect(controller.text, sentinel);
expect(out, ['abc']);
await type(tester, ev('d'));
expect(out, ['abc', 'd']);
});
}
}
/// Sends a Backspace for every character of padding that goes missing and
/// asks for the padding back.
class _Correcting implements SoftKeyboardInterpreter {
final seen = <TextEditingValue>[];
@override
String get name => 'correcting';
@override
String? get lastNote => null;
@override
List<SoftKeyboardAction> update(TextEditingValue value) {
seen.add(value);
if (value.text.length >= sentinel.length) return const [];
return [
SoftKeyboardBackspace(sentinel.length - value.text.length),
SoftKeyboardSetField(ev('')),
];
}
}
/// Answers every value by asking for a longer one.
class _NeverSatisfied implements SoftKeyboardInterpreter {
@override
String get name => 'never satisfied';
@override
String? get lastNote => null;
@override
List<SoftKeyboardAction> update(TextEditingValue value) => [
SoftKeyboardSetField(TextEditingValue(
text: '${value.text}!',
selection: TextSelection.collapsed(offset: value.text.length + 1),
)),
];
}
+229
View File
@@ -0,0 +1,229 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter_hbb/mobile/soft_keyboard/soft_keyboard.dart';
import 'package:flutter_test/flutter_test.dart';
import 'soft_keyboard_test_support.dart';
/// The JSON objects of a trace, one per line. Whatever a log put in front of
/// them is skipped, and so are lines without any.
List<Map<String, Object?>> readTrace(Iterable<String> lines) => [
for (final line in lines)
if (line.contains('{'))
jsonDecode(line.substring(line.indexOf('{'))) as Map<String, Object?>
];
/// Feeds the editing values of a trace to the interpreter named in the header
/// before them and checks that every value produces the recorded actions.
/// Returns how many values there were.
int replay(Iterable<String> lines, {String? reason}) {
SoftKeyboardInterpreter? interpreter;
var values = 0;
for (final entry in readTrace(lines)) {
if (entry['trace'] == 'soft-keyboard') {
expect(entry['level'], 'full',
reason: 'only a trace with text can be replayed');
interpreter = interpreterByName(
entry['interpreter'] as String,
decodeValue(entry['initial'] as Map<String, Object?>),
);
continue;
}
expect(interpreter, isNotNull, reason: 'a trace starts with a header');
final actions = interpreter!.update(decodeValue(entry));
expect(encodeSoftKeyboardActions(actions, withText: true), entry['act'],
reason: '${reason ?? ''} step ${entry['n']}');
values++;
}
return values;
}
void main() {
group('trace', () {
test('is off unless asked for', () {
final lines = <String>[];
final trace = SoftKeyboardTrace(sink: lines.add);
expect(trace.enabled, isFalse);
trace.start(newIos(), ev(''), platform: 'ios');
trace.record(ev('a'), const [SoftKeyboardText('a')]);
expect(lines, isEmpty);
});
test('parses its level, and anything unknown is off', () {
expect(parseSoftKeyboardTraceLevel('meta'), SoftKeyboardTraceLevel.meta);
expect(parseSoftKeyboardTraceLevel('full'), SoftKeyboardTraceLevel.full);
expect(parseSoftKeyboardTraceLevel(''), SoftKeyboardTraceLevel.off);
expect(parseSoftKeyboardTraceLevel('yes'), SoftKeyboardTraceLevel.off);
});
test('at meta level never contains what was typed', () {
final lines = <String>[];
final trace = SoftKeyboardTrace(
level: SoftKeyboardTraceLevel.meta, sink: lines.add);
final ios = newIos();
trace.start(ios, ev(''), platform: 'ios');
for (final spec in ['hunter', 'hunter[mima]', 'hunter密码']) {
final value = ev(spec);
trace.record(value, ios.update(value), note: ios.lastNote);
}
expect(lines, hasLength(4));
final all = lines.join('\n');
for (final secret in ['hunter', 'mima', '密码']) {
expect(all.contains(secret), isFalse);
}
// What is there: lengths, ranges and the kind of each action.
expect(jsonDecode(lines[1]), {
'n': 1,
'len': 1030,
'sel': [1030, 1030],
'comp': [-1, -1],
'act': [
['text', 6]
],
});
expect(jsonDecode(lines[2]), {
'n': 2,
'len': 1034,
'sel': [1034, 1034],
'comp': [1030, 1034],
'act': [],
});
});
test('at meta level does not tell a typed 1 from the sentinel', () {
String line(TextEditingValue value) {
final lines = <String>[];
SoftKeyboardTrace(level: SoftKeyboardTraceLevel.meta, sink: lines.add)
.record(value, const [SoftKeyboardText('x')]);
return lines.single;
}
// The same length, typed as digits and typed as letters.
expect(line(ev('1111')), line(ev('abcd')));
expect(line(ev('1q2w')), line(ev('abcd')));
});
test('at meta level does not contain a correction of the field either', () {
final lines = <String>[];
SoftKeyboardTrace(level: SoftKeyboardTraceLevel.meta, sink: lines.add)
.record(ev(''), [SoftKeyboardSetField(ev('hunter'))]);
expect(lines.single.contains('hunter'), isFalse);
expect((jsonDecode(lines.single) as Map)['act'], [
[
'set',
{
'len': 1030,
'sel': [1030, 1030],
'comp': [-1, -1],
}
]
]);
});
test('at full level can be replayed as it was written', () {
final lines = <String>[];
final trace = SoftKeyboardTrace(
level: SoftKeyboardTraceLevel.full, sink: lines.add);
final android = newAndroid();
trace.start(android, ev(''), platform: 'android');
for (final spec in ['ㅁ', '마', '만', '만 ', '만 “|”', '만 “나|”', '만 ']) {
final value = ev(spec);
trace.record(value, android.update(value), note: android.lastNote);
}
expect(lines, hasLength(8));
expect((jsonDecode(lines.first) as Map)['synthetic'], isFalse);
expect(replay(lines), 7);
});
test('can be replayed straight from a log', () {
// What ends up in a device log: a prefix on every line, and a new
// header every time the field is refilled.
final log = <String>[];
final previous = debugPrint;
debugPrint = (String? message, {int? wrapWidth}) =>
log.add('11-12 09:30:01.123 4242 4242 I flutter : $message');
addTearDown(() => debugPrint = previous);
final trace = SoftKeyboardTrace(level: SoftKeyboardTraceLevel.full);
for (final specs in [
['[n]', '[ni]', '你'],
<String>[],
['ab', 'a'],
]) {
final ios = newIos();
trace.start(ios, ev(''), platform: 'ios');
for (final spec in specs) {
final value = ev(spec);
trace.record(value, ios.update(value), note: ios.lastNote);
}
}
log.insert(
3, '11-12 09:30:01.200 4242 4242 I flutter : something else');
expect(log, hasLength(9));
expect(log.first, contains(SoftKeyboardTrace.tag));
expect(replay(log), 5);
});
test('values and actions survive encoding', () {
for (final value in [
ev(''),
ev('你[hao]'),
ev('a|b'),
ev('1', lead: 3),
const TextEditingValue(text: 'no sentinel'),
TextEditingValue.empty,
]) {
final json = jsonDecode(
jsonEncode(encodeSoftKeyboardValue(value, withText: true)))
as Map<String, Object?>;
expect(decodeValue(json), value);
}
final actions = [
const SoftKeyboardBackspace(3),
const SoftKeyboardText('he \n'),
const SoftKeyboardResetField(),
SoftKeyboardSetField(ev('ab[c]')),
];
final json = jsonDecode(
jsonEncode(encodeSoftKeyboardActions(actions, withText: true)))
as List<Object?>;
expect(decodeActions(json), actions);
});
});
group('recorded sequences', () {
final files = Directory('test/fixtures/soft_keyboard')
.listSync()
.whereType<File>()
.where((file) => file.path.endsWith('.jsonl'))
.toList()
..sort((a, b) => a.path.compareTo(b.path));
test('exist', () {
expect(files, isNotEmpty);
});
for (final file in files) {
final name = file.uri.pathSegments.last;
test(name, () {
final lines = file
.readAsLinesSync()
.where((line) => line.trim().isNotEmpty)
.toList();
final header = readTrace(lines).first;
// A sequence written by hand shows what the code does with it. Only
// one captured on a device shows what a keyboard does. Every fixture
// has to say which of the two it is.
expect(header['synthetic'], isA<bool>(),
reason: '$name must say whether it is synthetic');
expect(replay(lines, reason: name), greaterThan(0));
});
}
});
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "المجلد المحدد ليس فارغًا. قد يؤدي التثبيت إلى حذف البيانات الموجودة. يُنصح باختيار مجلد آخر."),
("Request approval", "طلب الموافقة"),
("Forever", "إلى الأبد"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Seçilmiş qovluq boş deyil. Quraşdırma mövcud məlumatları silə bilər. Başqa qovluq seçməyiniz tövsiyə olunur."),
("Request approval", "Təsdiq istə"),
("Forever", "Həmişəlik"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Выбраная папка не пустая. Усталёўванне можа выдаліць наяўныя даныя. Лепш выберыце іншую папку."),
("Request approval", "Запытаць дазвол"),
("Forever", "Назаўсёды"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Избраната папка не е празна. Инсталацията може да изтрие съществуващите данни. Препоръчително е да изберете друга папка."),
("Request approval", "Поискай одобрение"),
("Forever", "Завинаги"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "La carpeta seleccionada no és buida. La instal·lació pot suprimir les dades existents. Considereu triar una altra carpeta."),
("Request approval", "Sol·licita aprovació"),
("Forever", "Per sempre"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "所选文件夹不为空。安装可能删除现有数据。建议选择其他文件夹。"),
("Request approval", "请求批准"),
("Forever", "永久"),
("Improved input method (IME) handling", "改进的输入法处理"),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Vybraná složka není prázdná. Instalace může odstranit existující data. Zvažte výběr jiné složky."),
("Request approval", "Požádat o schválení"),
("Forever", "Navždy"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Den valgte mappe er ikke tom. Installationen kan slette eksisterende data. Overvej at vælge en anden mappe."),
("Request approval", "Anmod om godkendelse"),
("Forever", "For evigt"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Der ausgewählte Ordner ist nicht leer. Bei der Installation können vorhandene Daten gelöscht werden. Erwägen Sie, einen anderen Ordner auszuwählen."),
("Request approval", "Genehmigung anfordern"),
("Forever", "Für immer"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Ο επιλεγμένος φάκελος δεν είναι κενός. Η εγκατάσταση ενδέχεται να διαγράψει υπάρχοντα δεδομένα. Εξετάστε το ενδεχόμενο να επιλέξετε διαφορετικό φάκελο."),
("Request approval", "Αίτημα έγκρισης"),
("Forever", "Για πάντα"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "La elektita dosierujo ne estas malplena. La instalado povas forigi ekzistantajn datumojn. Konsideru elekti alian dosierujon."),
("Request approval", "Peti aprobon"),
("Forever", "Por ĉiam"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "La carpeta seleccionada no está vacía. La instalación puede eliminar los datos existentes. Considera elegir otra carpeta."),
("Request approval", "Solicitar aprobación"),
("Forever", "Para siempre"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Valitud kaust ei ole tühi. Paigaldamine võib olemasolevad andmed kustutada. Kaalu teise kausta valimist."),
("Request approval", "Küsi heakskiitu"),
("Forever", "Igavesti"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Hautatutako karpeta ez dago hutsik. Instalazioak lehendik dauden datuak ezaba ditzake. Beste karpeta bat aukeratzea gomendatzen da."),
("Request approval", "Eskatu onespena"),
("Forever", "Betiko"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "پوشه انتخاب‌شده خالی نیست. نصب ممکن است داده‌های موجود را حذف کند. بهتر است پوشه دیگری انتخاب کنید."),
("Request approval", "درخواست تأیید"),
("Forever", "برای همیشه"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Valittu kansio ei ole tyhjä. Asennus voi poistaa olemassa olevia tietoja. Harkitse toisen kansion valitsemista."),
("Request approval", "Pyydä hyväksyntää"),
("Forever", "Ikuisesti"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Le dossier sélectionné n’est pas vide. L’installation peut supprimer des données existantes. Envisagez de choisir un autre dossier."),
("Request approval", "Demander l'approbation"),
("Forever", "Pour toujours"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "არჩეული საქაღალდე ცარიელი არ არის. ინსტალაციამ შეიძლება წაშალოს არსებული მონაცემები. რეკომენდებულია სხვა საქაღალდის არჩევა."),
("Request approval", "დამტკიცების მოთხოვნა"),
("Forever", "სამუდამოდ"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "O cartafol seleccionado non está baleiro. A instalación pode eliminar os datos existentes. Considera escoller outro cartafol."),
("Request approval", "Solicitar aprobación"),
("Forever", "Para sempre"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "પસંદ કરેલ ફોલ્ડર ખાલી નથી. ઇન્સ્ટોલેશન હાલનો ડેટા કાઢી નાખી શકે છે. બીજું ફોલ્ડર પસંદ કરવાનું વિચારો."),
("Request approval", "મંજૂરીની વિનંતી કરો"),
("Forever", "કાયમ માટે"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "התיקייה שנבחרה אינה ריקה. ההתקנה עלולה למחוק נתונים קיימים. מומלץ לבחור תיקייה אחרת."),
("Request approval", "בקש אישור"),
("Forever", "לתמיד"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "चयनित फ़ोल्डर खाली नहीं है। इंस्टॉलेशन से मौजूदा डेटा हट सकता है। कोई दूसरा फ़ोल्डर चुनने पर विचार करें।"),
("Request approval", "स्वीकृति का अनुरोध करें"),
("Forever", "हमेशा के लिए"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Odabrana mapa nije prazna. Instalacija može izbrisati postojeće podatke. Razmislite o odabiru druge mape."),
("Request approval", "Zatraži odobrenje"),
("Forever", "Zauvijek"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "A kiválasztott mappa nem üres. A telepítés törölheti a meglévő adatokat. Fontolja meg egy másik mappa kiválasztását."),
("Request approval", "Jóváhagyás kérése"),
("Forever", "Örökre"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Folder yang dipilih tidak kosong. Instalasi dapat menghapus data yang ada. Pertimbangkan untuk memilih folder lain."),
("Request approval", "Minta persetujuan"),
("Forever", "Selamanya"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "La cartella selezionata non è vuota. L'installazione potrebbe eliminare i dati esistenti. Valuta la possibilità di scegliere una cartella diversa."),
("Request approval", "Richiedi approvazione"),
("Forever", "Per sempre"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "選択したフォルダーは空ではありません。インストールにより既存のデータが削除される可能性があります。別のフォルダーを選択することをおすすめします。"),
("Request approval", "承認を要求"),
("Forever", "無期限"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "선택한 폴더가 비어 있지 않습니다. 설치 시 기존 데이터가 삭제될 수 있습니다. 다른 폴더를 선택하는 것이 좋습니다."),
("Request approval", "승인 요청"),
("Forever", "영구"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Таңдалған бума бос емес. Орнату бар деректерді жоюы мүмкін. Басқа буманы таңдаған жөн."),
("Request approval", "Мақұлдауды сұрау"),
("Forever", "Мәңгі"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Pasirinktas aplankas nėra tuščias. Diegimas gali ištrinti esamus duomenis. Apsvarstykite galimybę pasirinkti kitą aplanką."),
("Request approval", "Prašyti patvirtinimo"),
("Forever", "Visam laikui"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Izvēlētā mape nav tukša. Instalēšana var izdzēst esošos datus. Apsveriet iespēju izvēlēties citu mapi."),
("Request approval", "Pieprasīt apstiprinājumu"),
("Forever", "Uz visiem laikiem"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "തിരഞ്ഞെടുത്ത ഫോൾഡർ ശൂന്യമല്ല. ഇൻസ്റ്റാളേഷൻ നിലവിലുള്ള ഡാറ്റ ഇല്ലാതാക്കിയേക്കാം. മറ്റൊരു ഫോൾഡർ തിരഞ്ഞെടുക്കുന്നത് പരിഗണിക്കുക."),
("Request approval", "അംഗീകാരം അഭ്യർത്ഥിക്കുക"),
("Forever", "എന്നേക്കും"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Den valgte mappen er ikke tom. Installasjonen kan slette eksisterende data. Vurder å velge en annen mappe."),
("Request approval", "Be om godkjenning"),
("Forever", "For alltid"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "De geselecteerde map is niet leeg. De installatie kan bestaande gegevens verwijderen. Overweeg een andere map te kiezen."),
("Request approval", "Goedkeuring aanvragen"),
("Forever", "Voor altijd"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Wybrany folder nie jest pusty. Instalacja może usunąć istniejące dane. Rozważ wybranie innego folderu."),
("Request approval", "Poproś o zatwierdzenie"),
("Forever", "Na zawsze"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "A pasta selecionada não está vazia. A instalação pode excluir dados existentes. Considere escolher outra pasta."),
("Request approval", "Solicitar aprovação"),
("Forever", "Para sempre"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "A pasta selecionada não está vazia. A instalação pode eliminar dados existentes. Considere escolher outra pasta."),
("Request approval", "Solicitar aprovação"),
("Forever", "Para sempre"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Folderul selectat nu este gol. Instalarea poate șterge datele existente. Ia în considerare alegerea altui folder."),
("Request approval", "Solicită aprobarea"),
("Forever", "Pentru totdeauna"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Выбранная папка не пуста. При установке существующие данные могут быть удалены. Рекомендуется выбрать другую папку."),
("Request approval", "Запросить одобрение"),
("Forever", "Навсегда"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Sa cartella seletzionada non est bòida. S'installatzione diat pòdere iscantzellare sos datos chi bi sunt. Ti cussigiamus de isseberare un'àtera cartella."),
("Request approval", "Pedi s'aprovatzione"),
("Forever", "Pro semper"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Vybraný priečinok nie je prázdny. Inštalácia môže odstrániť existujúce údaje. Zvážte výber iného priečinka."),
("Request approval", "Požiadať o schválenie"),
("Forever", "Navždy"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Izbrana mapa ni prazna. Namestitev lahko izbriše obstoječe podatke. Razmislite o izbiri druge mape."),
("Request approval", "Zahtevaj odobritev"),
("Forever", "Za vedno"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Dosja e zgjedhur nuk është bosh. Instalimi mund të fshijë të dhënat ekzistuese. Konsideroni të zgjidhni një dosje tjetër."),
("Request approval", "Kërko miratim"),
("Forever", "Përgjithmonë"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Izabrani direktorijum nije prazan. Instalacija može da obriše postojeće podatke. Razmislite o izboru drugog direktorijuma."),
("Request approval", "Zatraži odobrenje"),
("Forever", "Zauvek"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Den valda mappen är inte tom. Installationen kan radera befintliga data. Överväg att välja en annan mapp."),
("Request approval", "Begär godkännande"),
("Forever", "För alltid"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "தேர்ந்தெடுக்கப்பட்ட கோப்புறை காலியாக இல்லை. நிறுவல் ஏற்கனவே உள்ள தரவை நீக்கக்கூடும். வேறு கோப்புறையைத் தேர்ந்தெடுப்பது நல்லது."),
("Request approval", "ஒப்புதல் கோரவும்"),
("Forever", "என்றென்றும்"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", ""),
("Request approval", ""),
("Forever", ""),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "โฟลเดอร์ที่เลือกไม่ว่างเปล่า การติดตั้งอาจลบข้อมูลที่มีอยู่ ควรพิจารณาเลือกโฟลเดอร์อื่น"),
("Request approval", "ขออนุมัติ"),
("Forever", "ตลอดไป"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Seçilen klasör boş değil. Kurulum mevcut verileri silebilir. Farklı bir klasör seçmeyi düşünün."),
("Request approval", "Onay iste"),
("Forever", "Sonsuza dek"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "所選資料夾不是空的。安裝可能刪除現有資料。建議選擇其他資料夾。"),
("Request approval", "請求批准"),
("Forever", "永久"),
("Improved input method (IME) handling", "改良的輸入法處理"),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Вибрана тека не порожня. Встановлення може видалити наявні дані. Радимо вибрати іншу теку."),
("Request approval", "Запросити схвалення"),
("Forever", "Назавжди"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "منتخب فولڈر خالی نہیں ہے۔ انسٹالیشن موجودہ ڈیٹا کو حذف کر سکتی ہے۔ کوئی دوسرا فولڈر منتخب کرنے پر غور کریں۔"),
("Request approval", "منظوری کی درخواست کریں"),
("Forever", "ہمیشہ کے لیے"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}
+1
View File
@@ -826,5 +826,6 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
("install-directory-not-empty-tip", "Thư mục đã chọn không trống. Quá trình cài đặt có thể xóa dữ liệu hiện có. Hãy cân nhắc chọn một thư mục khác."),
("Request approval", "Yêu cầu phê duyệt"),
("Forever", "Vĩnh viễn"),
("Improved input method (IME) handling", ""),
].iter().cloned().collect();
}