One Flutter client for network-computer: drive a remote Linux/Mac desktop from Android, iPhone, iPad, or desktop over WebRTC.

0 downloads

network-computer-flutter/lib/soft_keyboard.dart
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/network-computer-flutter.git
HTTPS
https://gitstable.com/git/askrobots/network-computer-flutter.git
SSH
ssh://git@gitstable.com:2222/askrobots/network-computer-flutter.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Dan Quellhorst No colour (compare) in ⋯: the desk's picture in grey on this device c74471a 1 month, 3 weeks ago History
soft_keyboard.dart · 9.6 KB · 286 lines
1import 'package:flutter/material.dart';
2import 'package:flutter/services.dart';
3import 'protocol.dart';
4
5/// The US key that types [ch] on the desk, and whether it needs Shift.
6/// The desk keeps a US layout, so any character a US keyboard can type works;
7/// anything else (é, emoji) returns null.
8(String, bool)? usKey(String ch) {
9 if (ch.length != 1) return null;
10 final c = ch.codeUnitAt(0);
11 if (c >= 97 && c <= 122) return ('Key${ch.toUpperCase()}', false);
12 if (c >= 65 && c <= 90) return ('Key$ch', true);
13 if (c >= 48 && c <= 57) return ('Digit$ch', false);
14 if (ch == '\n') return ('Enter', false);
15 if (ch == '\t') return ('Tab', false);
16 return _us[ch];
17}
18
19const _us = {
20 ' ': ('Space', false),
21 '!': ('Digit1', true), '@': ('Digit2', true), '#': ('Digit3', true),
22 r'$': ('Digit4', true), '%': ('Digit5', true), '^': ('Digit6', true),
23 '&': ('Digit7', true), '*': ('Digit8', true), '(': ('Digit9', true),
24 ')': ('Digit0', true), '`': ('Backquote', false), '~': ('Backquote', true),
25 '-': ('Minus', false), '_': ('Minus', true), '=': ('Equal', false),
26 '+': ('Equal', true), '[': ('BracketLeft', false), '{': ('BracketLeft', true),
27 ']': ('BracketRight', false), '}': ('BracketRight', true),
28 '\\': ('Backslash', false), '|': ('Backslash', true),
29 ';': ('Semicolon', false), ':': ('Semicolon', true),
30 "'": ('Quote', false), '"': ('Quote', true), ',': ('Comma', false),
31 '<': ('Comma', true), '.': ('Period', false), '>': ('Period', true),
32 '/': ('Slash', false), '?': ('Slash', true),
33 // what a phone keyboard may type instead of the plain ones
34 '‘': ('Quote', false), '’': ('Quote', false),
35 '“': ('Quote', true), '”': ('Quote', true),
36};
37
38/// Typing on a touch device: the device's own keyboard for text, and a bar
39/// with the keys it lacks (esc, tab, ctrl, alt, super, arrows, F1–F12).
40///
41/// The device keyboard types into a hidden field that always holds a few
42/// invisible characters, so Backspace has something to delete; every change
43/// is turned into key presses on the desk and the field is reset.
44///
45/// ctrl, alt, super and shift on the bar apply to the next key and then let
46/// go (tap ctrl, then c: copy); hold one down on the bar to keep it on.
47class SoftKeyboard extends StatefulWidget {
48 const SoftKeyboard({super.key, required this.onEvent, this.autofocus = true});
49 final void Function(InputEvent) onEvent;
50 final bool autofocus;
51
52 @override
53 State<SoftKeyboard> createState() => _SoftKeyboardState();
54}
55
56class _SoftKeyboardState extends State<SoftKeyboard> {
57 static const _sentinel = '\u200B\u200B\u200B\u200B';
58
59 final _focus = FocusNode();
60 final _field = TextEditingController(text: _sentinel);
61 final Set<String> _mods = {}; // down on the desk, until the next key
62 final Set<String> _locked = {}; // down until tapped again
63 bool _fn = false;
64
65 @override
66 void initState() {
67 super.initState();
68 _reset();
69 HardwareKeyboard.instance.addHandler(_afterHardwareKey);
70 if (widget.autofocus) {
71 WidgetsBinding.instance.addPostFrameCallback((_) {
72 if (mounted) _focus.requestFocus();
73 });
74 }
75 }
76
77 @override
78 void dispose() {
79 HardwareKeyboard.instance.removeHandler(_afterHardwareKey);
80 for (final m in {..._mods, ..._locked}) {
81 widget.onEvent(InputEvent('ku', code: m));
82 }
83 _focus.dispose();
84 _field.dispose();
85 super.dispose();
86 }
87
88 void _reset() => _field.value = const TextEditingValue(
89 text: _sentinel,
90 selection: TextSelection.collapsed(offset: _sentinel.length),
91 );
92
93 void _changed(String text) {
94 // wait while an input method is still composing (dictation, accents)
95 final composing = _field.value.composing;
96 if (composing.isValid && !composing.isCollapsed) return;
97 final kept = '\u200B'.allMatches(text).length;
98 for (var i = kept; i < _sentinel.length; i++) {
99 _press('Backspace');
100 }
101 for (final ch in text.replaceAll('\u200B', '').split('')) {
102 final k = usKey(ch);
103 if (k != null) _press(k.$1, shift: k.$2);
104 }
105 _reset();
106 }
107
108 void _press(String code, {bool shift = false}) {
109 final addShift =
110 shift && !_mods.contains('ShiftLeft') && !_locked.contains('ShiftLeft');
111 if (addShift) widget.onEvent(InputEvent('kd', code: 'ShiftLeft'));
112 widget.onEvent(InputEvent('kd', code: code));
113 widget.onEvent(InputEvent('ku', code: code));
114 if (addShift) widget.onEvent(InputEvent('ku', code: 'ShiftLeft'));
115 if (_mods.isNotEmpty) {
116 for (final m in _mods) {
117 widget.onEvent(InputEvent('ku', code: m));
118 }
119 setState(_mods.clear);
120 }
121 }
122
123 // a key on a real keyboard is "the next key" too: let the bar's one-shot
124 // modifiers go once it is up (the session sends the key itself)
125 bool _afterHardwareKey(KeyEvent e) {
126 if (e is KeyUpEvent &&
127 _mods.isNotEmpty &&
128 !_modifierKeys.contains(e.logicalKey)) {
129 for (final m in _mods) {
130 widget.onEvent(InputEvent('ku', code: m));
131 }
132 setState(_mods.clear);
133 }
134 return false;
135 }
136
137 static final _modifierKeys = {
138 LogicalKeyboardKey.shiftLeft,
139 LogicalKeyboardKey.shiftRight,
140 LogicalKeyboardKey.controlLeft,
141 LogicalKeyboardKey.controlRight,
142 LogicalKeyboardKey.altLeft,
143 LogicalKeyboardKey.altRight,
144 LogicalKeyboardKey.metaLeft,
145 LogicalKeyboardKey.metaRight,
146 LogicalKeyboardKey.capsLock,
147 LogicalKeyboardKey.fn,
148 };
149
150 void _toggle(String code, {bool lock = false}) {
151 setState(() {
152 if (_mods.contains(code) || _locked.contains(code)) {
153 _mods.remove(code);
154 _locked.remove(code);
155 widget.onEvent(InputEvent('ku', code: code));
156 } else {
157 (lock ? _locked : _mods).add(code);
158 widget.onEvent(InputEvent('kd', code: code));
159 }
160 });
161 }
162
163 void _showKeyboard() {
164 if (_focus.hasFocus) {
165 SystemChannels.textInput.invokeMethod('TextInput.show');
166 } else {
167 _focus.requestFocus();
168 }
169 }
170
171 @override
172 Widget build(BuildContext context) {
173 return Container(
174 color: const Color(0xCC000000),
175 padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 6),
176 child: Column(
177 mainAxisSize: MainAxisSize.min,
178 crossAxisAlignment: CrossAxisAlignment.start,
179 children: [
180 // the hidden field the device keyboard types into
181 SizedBox(
182 height: 1,
183 child: Opacity(
184 opacity: 0,
185 child: TextField(
186 key: const Key('soft-keyboard-field'),
187 controller: _field,
188 focusNode: _focus,
189 onChanged: _changed,
190 // taps on the desk picture are clicks there: keep typing here
191 onTapOutside: (_) {},
192 keyboardType:
193 TextInputType.multiline, // Return types a newline: Enter
194 maxLines: null,
195 autocorrect: false,
196 enableSuggestions: false,
197 enableIMEPersonalizedLearning: false,
198 smartDashesType: SmartDashesType.disabled,
199 smartQuotesType: SmartQuotesType.disabled,
200 textCapitalization: TextCapitalization.none,
201 showCursor: false,
202 enableInteractiveSelection: false,
203 decoration: const InputDecoration.collapsed(hintText: null),
204 ),
205 ),
206 ),
207 if (_fn)
208 _row([
209 for (var i = 1; i <= 12; i++) _key('F$i', 'F$i'),
210 _key('ins', 'Insert'),
211 _key('prt sc', 'PrintScreen'),
212 ]),
213 _row([
214 _button('abc', _showKeyboard, tip: 'show the keyboard'),
215 _button('fn', () => setState(() => _fn = !_fn), on: _fn),
216 _key('esc', 'Escape'),
217 _key('tab', 'Tab'),
218 _mod('ctrl', 'ControlLeft'),
219 _mod('alt', 'AltLeft'),
220 _mod('super', 'MetaLeft'),
221 _mod('shift', 'ShiftLeft'),
222 _key('←', 'ArrowLeft'),
223 _key('↑', 'ArrowUp'),
224 _key('↓', 'ArrowDown'),
225 _key('→', 'ArrowRight'),
226 _key('home', 'Home'),
227 _key('end', 'End'),
228 _key('pg up', 'PageUp'),
229 _key('pg dn', 'PageDown'),
230 _key('del', 'Delete'),
231 ]),
232 ],
233 ),
234 );
235 }
236
237 Widget _row(List<Widget> keys) => SingleChildScrollView(
238 scrollDirection: Axis.horizontal,
239 child: Row(children: keys),
240 );
241
242 Widget _key(String label, String code) => _button(label, () => _press(code));
243
244 Widget _mod(String label, String code) => _button(
245 label,
246 () => _toggle(code),
247 onLong: () => _toggle(code, lock: true),
248 on: _mods.contains(code) || _locked.contains(code),
249 locked: _locked.contains(code),
250 );
251
252 Widget _button(
253 String label,
254 VoidCallback tap, {
255 VoidCallback? onLong,
256 bool on = false,
257 bool locked = false,
258 String? tip,
259 }) => Padding(
260 padding: const EdgeInsets.symmetric(horizontal: 2.5, vertical: 2),
261 child: Tooltip(
262 message: tip ?? '',
263 triggerMode: tip == null
264 ? TooltipTriggerMode.manual
265 : TooltipTriggerMode.longPress,
266 child: TextButton(
267 style: TextButton.styleFrom(
268 minimumSize: const Size(44, 40),
269 padding: const EdgeInsets.symmetric(horizontal: 10),
270 backgroundColor: locked
271 ? const Color(0xFF2E6BE0)
272 : on
273 ? const Color(0xFF4C8DFF)
274 : const Color(0xE61C2129),
275 foregroundColor: Colors.white,
276 side: locked
277 ? const BorderSide(color: Colors.white, width: 1.5)
278 : null,
279 ),
280 onPressed: tap,
281 onLongPress: onLong,
282 child: Text(label, style: const TextStyle(fontFamily: 'monospace')),
283 ),
284 ),
285 );
286}