-
Notifications
You must be signed in to change notification settings - Fork 26.7k
/
editable.dart
565 lines (487 loc) · 17.7 KB
/
editable.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/rendering.dart' show RenderEditableLine, SelectionChangedHandler, RenderEditableLinePaintOffsetNeededCallback;
import 'package:flutter/services.dart';
import 'package:meta/meta.dart';
import 'package:flutter_services/editing.dart' as mojom;
import 'basic.dart';
import 'focus.dart';
import 'framework.dart';
import 'media_query.dart';
import 'scroll_behavior.dart';
import 'scrollable.dart';
import 'text_selection.dart';
export 'package:flutter/painting.dart' show TextSelection;
export 'package:flutter_services/editing.dart' show KeyboardType;
const Duration _kCursorBlinkHalfPeriod = const Duration(milliseconds: 500);
TextSelection _getTextSelectionFromEditingState(mojom.EditingState state) {
return new TextSelection(
baseOffset: state.selectionBase,
extentOffset: state.selectionExtent,
affinity: TextAffinity.values[state.selectionAffinity.mojoEnumValue],
isDirectional: state.selectionIsDirectional
);
}
class _KeyboardClientImpl implements mojom.KeyboardClient {
_KeyboardClientImpl({
this.inputValue,
this.onUpdated,
this.onSubmitted
}) {
assert(inputValue != null);
assert(onUpdated != null);
assert(onSubmitted != null);
}
InputValue inputValue;
/// Called whenever the text changes.
final VoidCallback onUpdated;
/// Called whenever the user indicates they are done editing the string.
final VoidCallback onSubmitted;
/// A keyboard client stub that can be attached to a keyboard service.
mojom.KeyboardClientStub createStub() {
return new mojom.KeyboardClientStub.unbound()..impl = this;
}
mojom.EditingState get editingState {
return new mojom.EditingState()
..text = inputValue.text
..selectionBase = inputValue.selection.baseOffset
..selectionExtent = inputValue.selection.extentOffset
..selectionAffinity = mojom.TextAffinity.values[inputValue.selection.affinity.index]
..selectionIsDirectional = inputValue.selection.isDirectional
..composingBase = inputValue.composing.start
..composingExtent = inputValue.composing.end;
}
@override
void updateEditingState(mojom.EditingState state) {
inputValue = new InputValue(
text: state.text,
selection: _getTextSelectionFromEditingState(state),
composing: new TextRange(start: state.composingBase, end: state.composingExtent)
);
onUpdated();
}
void clearComposing() {
inputValue = inputValue.copyWith(composing: TextRange.empty);
}
@override
void submit(mojom.SubmitAction action) {
clearComposing();
onSubmitted();
}
}
/// Configuration information for an input field.
///
/// An [InputValue] contains the text for the input field as well as the
/// selection extent and the composing range.
class InputValue {
/// Creates configuration information for an input field
///
/// The selection and composing range must be within the text.
///
/// The [text], [selection], and [composing] arguments must not be null but
/// each have default values.
const InputValue({
this.text: '',
this.selection: const TextSelection.collapsed(offset: -1),
this.composing: TextRange.empty
});
/// The current text being edited.
final String text;
/// The range of text that is currently selected.
final TextSelection selection;
/// The range of text that is still being composed.
final TextRange composing;
/// An input value that corresponds to the empty string with no selection and no composing range.
static const InputValue empty = const InputValue();
@override
String toString() => '$runtimeType(text: \u2524$text\u251C, selection: $selection, composing: $composing)';
@override
bool operator ==(dynamic other) {
if (identical(this, other))
return true;
if (other is! InputValue)
return false;
InputValue typedOther = other;
return typedOther.text == text
&& typedOther.selection == selection
&& typedOther.composing == composing;
}
@override
int get hashCode => hashValues(
text.hashCode,
selection.hashCode,
composing.hashCode
);
/// Creates a copy of this input value but with the given fields replaced with the new values.
InputValue copyWith({
String text,
TextSelection selection,
TextRange composing
}) {
return new InputValue (
text: text ?? this.text,
selection: selection ?? this.selection,
composing: composing ?? this.composing
);
}
}
/// A basic single-line input control.
///
/// This control is not intended to be used directly. Instead, consider using
/// [Input], which provides focus management and material design.
//
// TODO(mpcomplete): rename RawInput since it can span multiple lines.
class RawInputLine extends Scrollable {
/// Creates a basic single-line input control.
///
/// The [value] argument must not be null.
RawInputLine({
Key key,
@required this.value,
this.focusKey,
this.hideText: false,
this.style,
this.cursorColor,
this.textScaleFactor,
int maxLines: 1,
this.selectionColor,
this.selectionControls,
@required this.platform,
this.keyboardType,
this.onChanged,
this.onSubmitted
}) : maxLines = maxLines, super(
key: key,
initialScrollOffset: 0.0,
scrollDirection: maxLines > 1 ? Axis.vertical : Axis.horizontal
) {
assert(value != null);
}
/// The string being displayed in this widget.
final InputValue value;
/// Key of the enclosing widget that holds the focus.
final GlobalKey focusKey;
/// Whether to hide the text being edited (e.g., for passwords).
final bool hideText;
/// The text style to use for the editable text.
final TextStyle style;
/// The number of font pixels for each logical pixel.
///
/// For example, if the text scale factor is 1.5, text will be 50% larger than
/// the specified font size.
///
/// Defaults to [MediaQuery.textScaleFactor].
final double textScaleFactor;
/// The color to use when painting the cursor.
final Color cursorColor;
/// The maximum number of lines for the text to span, wrapping if necessary.
/// If this is 1 (the default), the text will not wrap, but will scroll
/// horizontally instead.
final int maxLines;
/// The color to use when painting the selection.
final Color selectionColor;
/// Optional delegate for building the text selection handles and toolbar.
final TextSelectionControls selectionControls;
/// The platform whose behavior should be approximated, in particular
/// for scroll physics. (See [ScrollBehavior.platform].)
///
/// Must not be null.
final TargetPlatform platform;
/// The type of keyboard to use for editing the text.
final KeyboardType keyboardType;
/// Called when the text being edited changes.
final ValueChanged<InputValue> onChanged;
/// Called when the user indicates that they are done editing the text in the field.
final ValueChanged<InputValue> onSubmitted;
@override
RawInputLineState createState() => new RawInputLineState();
}
/// State for a [RawInputLine].
class RawInputLineState extends ScrollableState<RawInputLine> {
Timer _cursorTimer;
bool _showCursor = false;
_KeyboardClientImpl _keyboardClient;
KeyboardHandle _keyboardHandle;
TextSelectionOverlay _selectionOverlay;
@override
ExtentScrollBehavior createScrollBehavior() => new BoundedBehavior(platform: config.platform);
@override
BoundedBehavior get scrollBehavior => super.scrollBehavior;
@override
void initState() {
super.initState();
_keyboardClient = new _KeyboardClientImpl(
inputValue: config.value,
onUpdated: _handleTextUpdated,
onSubmitted: _handleTextSubmitted
);
}
@override
void didUpdateConfig(RawInputLine oldConfig) {
if (_keyboardClient.inputValue != config.value) {
_keyboardClient.inputValue = config.value;
if (_isAttachedToKeyboard)
_keyboardHandle.setEditingState(_keyboardClient.editingState);
}
}
bool get _isAttachedToKeyboard => _keyboardHandle != null && _keyboardHandle.attached;
bool get _isMultiline => config.maxLines > 1;
double _contentExtent = 0.0;
double _containerExtent = 0.0;
Offset _handlePaintOffsetUpdateNeeded(ViewportDimensions dimensions, Rect caretRect) {
// We make various state changes here but don't have to do so in a
// setState() callback because we are called during layout and all
// we're updating is the new offset, which we are providing to the
// render object via our return value.
_contentExtent = _isMultiline ?
dimensions.contentSize.height :
dimensions.contentSize.width;
_containerExtent = _isMultiline ?
dimensions.containerSize.height :
dimensions.containerSize.width;
didUpdateScrollBehavior(scrollBehavior.updateExtents(
contentExtent: _contentExtent,
containerExtent: _containerExtent,
// TODO(ianh): We should really only do this when text is added,
// not generally any time the size changes.
scrollOffset: _getScrollOffsetForCaret(caretRect, _containerExtent)
));
updateGestureDetector();
return scrollOffsetToPixelDelta(scrollOffset);
}
// Calculate the new scroll offset so the cursor remains visible.
double _getScrollOffsetForCaret(Rect caretRect, double containerExtent) {
double caretStart = _isMultiline ? caretRect.top : caretRect.left;
double caretEnd = _isMultiline ? caretRect.bottom : caretRect.right;
double newScrollOffset = scrollOffset;
if (caretStart < 0.0) // cursor before start of bounds
newScrollOffset += pixelOffsetToScrollOffset(-caretStart);
else if (caretEnd >= containerExtent) // cursor after end of bounds
newScrollOffset += pixelOffsetToScrollOffset(-(caretEnd - containerExtent));
return newScrollOffset;
}
void _attachOrDetachKeyboard(bool focused) {
if (focused && !_isAttachedToKeyboard) {
_keyboardHandle = keyboard.attach(_keyboardClient.createStub(),
new mojom.KeyboardConfiguration()
..type = config.keyboardType);
_keyboardHandle.setEditingState(_keyboardClient.editingState);
_keyboardHandle.show();
} else if (!focused) {
if (_isAttachedToKeyboard) {
_keyboardHandle.release();
_keyboardHandle = null;
}
_keyboardClient.clearComposing();
}
}
/// Express interest in interacting with the keyboard.
///
/// If this control is already attached to the keyboard, this function will
/// request that the keyboard become visible. Otherwise, this function will
/// ask the focus system that it become focused. If successful in acquiring
/// focus, the control will then attach to the keyboard and request that the
/// keyboard become visible.
void requestKeyboard() {
if (_isAttachedToKeyboard) {
_keyboardHandle.show();
} else {
Focus.moveTo(config.focusKey);
}
}
void _handleTextUpdated() {
if (config.onChanged != null)
config.onChanged(_keyboardClient.inputValue);
if (_keyboardClient.inputValue.text != config.value.text) {
_selectionOverlay?.hide();
_selectionOverlay = null;
}
}
void _handleTextSubmitted() {
Focus.clear(context);
if (config.onSubmitted != null)
config.onSubmitted(_keyboardClient.inputValue);
}
void _handleSelectionChanged(TextSelection selection, RenderEditableLine renderObject, bool longPress) {
// Note that this will show the keyboard for all selection changes on the
// EditableLineWidget, not just changes triggered by user gestures.
requestKeyboard();
InputValue newInput = new InputValue(text: _keyboardClient.inputValue.text, selection: selection);
if (config.onChanged != null)
config.onChanged(newInput);
if (_selectionOverlay != null) {
_selectionOverlay.hide();
_selectionOverlay = null;
}
if (config.selectionControls != null) {
_selectionOverlay = new TextSelectionOverlay(
input: newInput,
context: context,
debugRequiredFor: config,
renderObject: renderObject,
onSelectionOverlayChanged: _handleSelectionOverlayChanged,
selectionControls: config.selectionControls,
);
if (newInput.text.isNotEmpty || longPress)
_selectionOverlay.showHandles();
if (longPress)
_selectionOverlay.showToolbar();
}
}
void _handleSelectionOverlayChanged(InputValue newInput, Rect caretRect) {
assert(!newInput.composing.isValid); // composing range must be empty while selecting
if (config.onChanged != null)
config.onChanged(newInput);
didUpdateScrollBehavior(scrollBehavior.updateExtents(
// TODO(mpcomplete): should just be able to pass
// scrollBehavior.containerExtent here (and remove the member var), but
// scrollBehavior gets re-created too often, and is sometimes
// uninitialized here. Investigate if this is a bug.
scrollOffset: _getScrollOffsetForCaret(caretRect, _containerExtent)
));
}
/// Whether the blinking cursor is actually visible at this precise moment
/// (it's hidden half the time, since it blinks).
bool get cursorCurrentlyVisible => _showCursor;
/// The cursor blink interval (the amount of time the cursor is in the "on"
/// state or the "off" state). A complete cursor blink period is twice this
/// value (half on, half off).
Duration get cursorBlinkInterval => _kCursorBlinkHalfPeriod;
void _cursorTick(Timer timer) {
setState(() {
_showCursor = !_showCursor;
});
}
void _startCursorTimer() {
_showCursor = true;
_cursorTimer = new Timer.periodic(_kCursorBlinkHalfPeriod, _cursorTick);
}
@override
void dispose() {
if (_isAttachedToKeyboard)
_keyboardHandle.release();
if (_cursorTimer != null)
_stopCursorTimer();
_selectionOverlay?.dispose();
super.dispose();
}
void _stopCursorTimer() {
_cursorTimer.cancel();
_cursorTimer = null;
_showCursor = false;
}
@override
Widget buildContent(BuildContext context) {
assert(config.style != null);
assert(config.focusKey != null);
assert(config.cursorColor != null);
bool focused = Focus.at(config.focusKey.currentContext);
_attachOrDetachKeyboard(focused);
if (_cursorTimer == null && focused && config.value.selection.isCollapsed)
_startCursorTimer();
else if (_cursorTimer != null && (!focused || !config.value.selection.isCollapsed))
_stopCursorTimer();
if (_selectionOverlay != null) {
if (focused) {
_selectionOverlay.update(config.value);
} else {
_selectionOverlay?.dispose();
_selectionOverlay = null;
}
}
return new ClipRect(
child: new _EditableLineWidget(
value: _keyboardClient.inputValue,
style: config.style,
cursorColor: config.cursorColor,
showCursor: _showCursor,
maxLines: config.maxLines,
selectionColor: config.selectionColor,
textScaleFactor: config.textScaleFactor ?? MediaQuery.of(context).textScaleFactor,
hideText: config.hideText,
onSelectionChanged: _handleSelectionChanged,
paintOffset: scrollOffsetToPixelDelta(scrollOffset),
onPaintOffsetUpdateNeeded: _handlePaintOffsetUpdateNeeded
)
);
}
}
class _EditableLineWidget extends LeafRenderObjectWidget {
_EditableLineWidget({
Key key,
this.value,
this.style,
this.cursorColor,
this.showCursor,
this.maxLines,
this.selectionColor,
this.textScaleFactor,
this.hideText,
this.onSelectionChanged,
this.paintOffset,
this.onPaintOffsetUpdateNeeded
}) : super(key: key);
final InputValue value;
final TextStyle style;
final Color cursorColor;
final bool showCursor;
final int maxLines;
final Color selectionColor;
final double textScaleFactor;
final bool hideText;
final SelectionChangedHandler onSelectionChanged;
final Offset paintOffset;
final RenderEditableLinePaintOffsetNeededCallback onPaintOffsetUpdateNeeded;
@override
RenderEditableLine createRenderObject(BuildContext context) {
return new RenderEditableLine(
text: _styledTextSpan,
cursorColor: cursorColor,
showCursor: showCursor,
maxLines: maxLines,
selectionColor: selectionColor,
textScaleFactor: textScaleFactor,
selection: value.selection,
onSelectionChanged: onSelectionChanged,
paintOffset: paintOffset,
onPaintOffsetUpdateNeeded: onPaintOffsetUpdateNeeded
);
}
@override
void updateRenderObject(BuildContext context, RenderEditableLine renderObject) {
renderObject
..text = _styledTextSpan
..cursorColor = cursorColor
..showCursor = showCursor
..maxLines = maxLines
..selectionColor = selectionColor
..textScaleFactor = textScaleFactor
..selection = value.selection
..onSelectionChanged = onSelectionChanged
..paintOffset = paintOffset
..onPaintOffsetUpdateNeeded = onPaintOffsetUpdateNeeded;
}
TextSpan get _styledTextSpan {
if (!hideText && value.composing.isValid) {
TextStyle composingStyle = style.merge(
const TextStyle(decoration: TextDecoration.underline)
);
return new TextSpan(
style: style,
children: <TextSpan>[
new TextSpan(text: value.composing.textBefore(value.text)),
new TextSpan(
style: composingStyle,
text: value.composing.textInside(value.text)
),
new TextSpan(text: value.composing.textAfter(value.text))
]);
}
String text = value.text;
if (hideText)
text = new String.fromCharCodes(new List<int>.filled(text.length, 0x2022));
return new TextSpan(style: style, text: text);
}
}