2
This commit is contained in:
1 parent
9fbb414ee6
commit
4554f22c87
233 files changed
+147430
-605
No files matched your search
@@ -0,0 +1,323 @@
|
||||
part of re_editor;
|
||||
|
||||
class _DefaultCodeAutocompletePromptsBuilder implements DefaultCodeAutocompletePromptsBuilder {
|
||||
|
||||
final Mode? language;
|
||||
final List<CodeKeywordPrompt> keywordPrompts;
|
||||
final List<CodePrompt> directPrompts;
|
||||
final Map<String, List<CodePrompt>> relatedPrompts;
|
||||
|
||||
final Set<CodePrompt> _allKeywordPrompts = {};
|
||||
|
||||
_DefaultCodeAutocompletePromptsBuilder({
|
||||
this.language,
|
||||
required this.keywordPrompts,
|
||||
required this.directPrompts,
|
||||
required this.relatedPrompts
|
||||
}) {
|
||||
_allKeywordPrompts.addAll(keywordPrompts);
|
||||
_allKeywordPrompts.addAll(directPrompts);
|
||||
final dynamic keywords = language?.keywords;
|
||||
if (keywords is Map) {
|
||||
final dynamic keywordList = keywords['keyword'];
|
||||
if (keywordList is List) {
|
||||
_allKeywordPrompts.addAll(keywordList.map(
|
||||
(keyword) => CodeKeywordPrompt(word: keyword))
|
||||
);
|
||||
}
|
||||
final dynamic builtInList = keywords['built_in'];
|
||||
if (builtInList is List) {
|
||||
_allKeywordPrompts.addAll(builtInList.map(
|
||||
(keyword) => CodeKeywordPrompt(word: keyword))
|
||||
);
|
||||
}
|
||||
final dynamic literalList = keywords['literal'];
|
||||
if (literalList is List) {
|
||||
_allKeywordPrompts.addAll(literalList.map(
|
||||
(keyword) => CodeKeywordPrompt(word: keyword))
|
||||
);
|
||||
}
|
||||
final dynamic typeList = keywords['type'];
|
||||
if (typeList is List) {
|
||||
_allKeywordPrompts.addAll(typeList.map(
|
||||
(keyword) => CodeKeywordPrompt(word: keyword))
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
CodeAutocompleteEditingValue? build(BuildContext context, CodeLine codeLine, CodeLineSelection selection) {
|
||||
final String text = codeLine.text;
|
||||
final Characters charactersBefore = text.substring(0, selection.extentOffset).characters;
|
||||
if (charactersBefore.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
final Characters charactersAfter = text.substring(selection.extentOffset).characters;
|
||||
// FIXME:Check whether the position is inside a string
|
||||
if (charactersBefore.containsSymbols(const ['\'', '"']) && charactersAfter.containsSymbols(const ['\'', '"'])) {
|
||||
return null;
|
||||
}
|
||||
// TODO Should check operator `->` for some languages like c/c++
|
||||
final Iterable<CodePrompt> prompts;
|
||||
final String input;
|
||||
if (charactersBefore.takeLast(1).string == '.') {
|
||||
input = '';
|
||||
int start = charactersBefore.length - 2;
|
||||
for (; start >= 0; start--) {
|
||||
if (!charactersBefore.elementAt(start).isValidVariablePart) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
final String target = charactersBefore.getRange(start + 1, charactersBefore.length - 1).string;
|
||||
prompts = relatedPrompts[target] ?? const [];
|
||||
} else {
|
||||
int start = charactersBefore.length - 1;
|
||||
for (; start >= 0; start--) {
|
||||
if (!charactersBefore.elementAt(start).isValidVariablePart) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
input = charactersBefore.getRange(start + 1, charactersBefore.length).string;
|
||||
if (input.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
if (start > 0 && charactersBefore.elementAt(start) == '.') {
|
||||
final int mark = start;
|
||||
for (start = start - 1; start >= 0; start--) {
|
||||
if (!charactersBefore.elementAt(start).isValidVariablePart) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
final String target = charactersBefore.getRange(start + 1, mark).string;
|
||||
prompts = relatedPrompts[target]?.where(
|
||||
(prompt) => prompt.match(input)
|
||||
) ?? const [];
|
||||
} else {
|
||||
prompts = _allKeywordPrompts.where(
|
||||
(prompt) => prompt.match(input)
|
||||
);
|
||||
}
|
||||
}
|
||||
if (prompts.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
return CodeAutocompleteEditingValue(
|
||||
input: input,
|
||||
prompts: prompts.toList(),
|
||||
index: 0
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class _CodeAutocomplete extends StatefulWidget {
|
||||
|
||||
const _CodeAutocomplete({
|
||||
required this.viewBuilder,
|
||||
required this.promptsBuilder,
|
||||
required this.child,
|
||||
});
|
||||
|
||||
final CodeAutocompleteWidgetBuilder viewBuilder;
|
||||
final CodeAutocompletePromptsBuilder promptsBuilder;
|
||||
final Widget child;
|
||||
|
||||
@override
|
||||
State<StatefulWidget> createState() => _CodeAutocompleteState();
|
||||
|
||||
}
|
||||
|
||||
class _CodeAutocompleteState extends State<_CodeAutocomplete> {
|
||||
|
||||
late final _CodeAutocompleteNavigateAction _navigateAction;
|
||||
late final _CodeAutocompleteAction _selectAction;
|
||||
|
||||
ValueChanged<CodeAutocompleteResult>? _onAutocomplete;
|
||||
OverlayEntry? _overlayEntry;
|
||||
ValueNotifier<CodeAutocompleteEditingValue>? _notifier;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_navigateAction = _CodeAutocompleteNavigateAction(
|
||||
onInvoke: (intent) {
|
||||
final CodeAutocompleteEditingValue? value = _notifier?.value;
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
int newIndex = value.index;
|
||||
if (intent.direction == AxisDirection.up) {
|
||||
newIndex--;
|
||||
} else {
|
||||
newIndex++;
|
||||
}
|
||||
if (newIndex < 0) {
|
||||
newIndex = value.prompts.length - 1;
|
||||
} else if (newIndex >= value.prompts.length) {
|
||||
newIndex = 0;
|
||||
}
|
||||
_notifier?.value = value.copyWith(
|
||||
index: newIndex,
|
||||
);
|
||||
return intent;
|
||||
},
|
||||
);
|
||||
_selectAction = _CodeAutocompleteAction<CodeShortcutNewLineIntent>(
|
||||
onInvoke: (intent) {
|
||||
final CodeAutocompleteEditingValue? value = _notifier?.value;
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
_onAutocomplete?.call(value.autocomplete);
|
||||
return intent;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant _CodeAutocomplete oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Actions(
|
||||
actions: {
|
||||
CodeShortcutCursorMoveIntent: _navigateAction,
|
||||
CodeShortcutNewLineIntent: _selectAction,
|
||||
},
|
||||
child: widget.child
|
||||
);
|
||||
}
|
||||
|
||||
void show({
|
||||
required LayerLink layerLink,
|
||||
required Offset position,
|
||||
required double lineHeight,
|
||||
required CodeLineEditingValue value,
|
||||
required ValueChanged<CodeAutocompleteResult> onAutocomplete,
|
||||
}) {
|
||||
dismiss();
|
||||
final CodeAutocompleteEditingValue? autocompleteEditingValue = widget.promptsBuilder.build(
|
||||
context,
|
||||
value.codeLines[value.selection.extentIndex],
|
||||
value.selection,
|
||||
);
|
||||
if (autocompleteEditingValue == null) {
|
||||
return;
|
||||
}
|
||||
_notifier = ValueNotifier(autocompleteEditingValue);
|
||||
_onAutocomplete = onAutocomplete;
|
||||
_overlayEntry = OverlayEntry(
|
||||
builder:(context) {
|
||||
return _buildWidget(context, layerLink, position, lineHeight);
|
||||
},
|
||||
);
|
||||
Overlay.of(context, rootOverlay: true).insert(_overlayEntry!);
|
||||
_navigateAction.setEnabled(true);
|
||||
_selectAction.setEnabled(true);
|
||||
}
|
||||
|
||||
void dismiss() {
|
||||
_notifier = null;
|
||||
_onAutocomplete = null;
|
||||
_overlayEntry?.remove();
|
||||
_overlayEntry = null;
|
||||
_navigateAction.setEnabled(false);
|
||||
_selectAction.setEnabled(false);
|
||||
}
|
||||
|
||||
Widget _buildWidget(BuildContext context, LayerLink layerLink, Offset position, double lineHeight) {
|
||||
final PreferredSizeWidget child = widget.viewBuilder(context, _notifier!, (result) {
|
||||
_onAutocomplete?.call(result);
|
||||
});
|
||||
final Size screenSize = MediaQuery.of(context).size;
|
||||
final double offsetX;
|
||||
if (position.dx + child.preferredSize.width > screenSize.width) {
|
||||
offsetX = screenSize.width - (position.dx + child.preferredSize.width);
|
||||
} else {
|
||||
offsetX = 0;
|
||||
}
|
||||
final double offsetY;
|
||||
if (position.dy + child.preferredSize.height > screenSize.height) {
|
||||
offsetY = -child.preferredSize.height - lineHeight;
|
||||
} else {
|
||||
offsetY = 0;
|
||||
}
|
||||
return CompositedTransformFollower(
|
||||
link: layerLink,
|
||||
showWhenUnlinked: false,
|
||||
offset: Offset(offsetX, offsetY),
|
||||
child: Align(
|
||||
alignment: Alignment.topLeft,
|
||||
child: Material(
|
||||
color: Colors.transparent,
|
||||
child: TapRegion(
|
||||
onTapOutside: (event) {
|
||||
dismiss();
|
||||
},
|
||||
child: CodeEditorTapRegion(
|
||||
child: ExcludeSemantics(
|
||||
child: child,
|
||||
)
|
||||
)
|
||||
),
|
||||
)
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class _CodeAutocompleteAction<T extends Intent> extends CallbackAction<T> {
|
||||
|
||||
bool _isEnabled = false;
|
||||
|
||||
_CodeAutocompleteAction({
|
||||
required super.onInvoke
|
||||
});
|
||||
|
||||
void setEnabled(bool enabled) {
|
||||
_isEnabled = enabled;
|
||||
}
|
||||
|
||||
@override
|
||||
bool get isActionEnabled => _isEnabled;
|
||||
|
||||
}
|
||||
|
||||
class _CodeAutocompleteNavigateAction extends _CodeAutocompleteAction<CodeShortcutCursorMoveIntent> {
|
||||
|
||||
_CodeAutocompleteNavigateAction({
|
||||
required super.onInvoke
|
||||
});
|
||||
|
||||
@override
|
||||
bool consumesKey(CodeShortcutCursorMoveIntent intent) {
|
||||
return intent.direction == AxisDirection.up || intent.direction == AxisDirection.down;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension _CodeAutocompleteStringExtension on String {
|
||||
|
||||
bool get isValidVariablePart {
|
||||
final int char = codeUnits.first;
|
||||
return (char >= 65 && char <= 90) || (char >= 97 && char <= 122) || char == 95;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension _CodeAutocompleteCharactersExtension on Characters {
|
||||
|
||||
bool containsSymbols(List<String> symbols) {
|
||||
for (int i = length - 1; i >= 0; i--) {
|
||||
if (symbols.contains(elementAt(i))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,489 @@
|
||||
part of re_editor;
|
||||
|
||||
const double _kDefaultTextSize = 13.0;
|
||||
const double _kDefaultFontHeight = 1.4;
|
||||
const double _kDefaultCaretWidth = 2;
|
||||
const EdgeInsetsGeometry _kDefaultPadding = EdgeInsets.all(5);
|
||||
const Duration _kCursorBlinkHalfPeriod = Duration(milliseconds: 500);
|
||||
|
||||
class _CodeEditable extends StatefulWidget {
|
||||
|
||||
final GlobalKey editorKey;
|
||||
final String? hint;
|
||||
final CodeIndicatorBuilder? indicatorBuilder;
|
||||
final CodeScrollbarBuilder? scrollbarBuilder;
|
||||
final double? verticalScrollbarWidth;
|
||||
final double? horizontalScrollbarHeight;
|
||||
final TextStyle textStyle;
|
||||
final Color? hintTextColor;
|
||||
final Color? backgroundColor;
|
||||
final Color selectionColor;
|
||||
final Color highlightColor;
|
||||
final Color cursorColor;
|
||||
final Color? cursorLineColor;
|
||||
final Color? chunkIndicatorColor;
|
||||
final double cursorWidth;
|
||||
final bool showCursorWhenReadOnly;
|
||||
final EdgeInsetsGeometry padding;
|
||||
final EdgeInsetsGeometry margin;
|
||||
final Widget? leadingDivider;
|
||||
final Border? border;
|
||||
final BorderRadius? borderRadius;
|
||||
final Clip clipBehavior;
|
||||
final ValueChanged<CodeLineEditingValue>? onChanged;
|
||||
final FocusNode focusNode;
|
||||
final CodeLineEditingController controller;
|
||||
final _CodeInputController inputController;
|
||||
final _CodeFloatingCursorController floatingCursorController;
|
||||
final CodeHighlightTheme? codeTheme;
|
||||
final bool readOnly;
|
||||
final bool autofocus;
|
||||
final bool wordWrap;
|
||||
final int? maxLengthSingleLineRendering;
|
||||
final CodeFindController findController;
|
||||
final CodeScrollController scrollController;
|
||||
final CodeChunkController chunkController;
|
||||
final LayerLink startHandleLayerLink;
|
||||
final LayerLink endHandleLayerLink;
|
||||
final LayerLink toolbarLayerLink;
|
||||
final _SelectionOverlayController selectionOverlayController;
|
||||
|
||||
const _CodeEditable({
|
||||
required this.editorKey,
|
||||
this.hint,
|
||||
this.indicatorBuilder,
|
||||
this.scrollbarBuilder,
|
||||
this.verticalScrollbarWidth,
|
||||
this.horizontalScrollbarHeight,
|
||||
required this.textStyle,
|
||||
this.hintTextColor,
|
||||
this.backgroundColor,
|
||||
required this.selectionColor,
|
||||
required this.highlightColor,
|
||||
required this.cursorColor,
|
||||
this.cursorLineColor,
|
||||
this.chunkIndicatorColor,
|
||||
required this.cursorWidth,
|
||||
required this.showCursorWhenReadOnly,
|
||||
required this.padding,
|
||||
required this.margin,
|
||||
required this.leadingDivider,
|
||||
this.border,
|
||||
this.borderRadius,
|
||||
this.clipBehavior = Clip.none,
|
||||
this.onChanged,
|
||||
required this.focusNode,
|
||||
required this.controller,
|
||||
required this.inputController,
|
||||
required this.floatingCursorController,
|
||||
required this.codeTheme,
|
||||
required this.readOnly,
|
||||
required this.autofocus,
|
||||
required this.wordWrap,
|
||||
this.maxLengthSingleLineRendering,
|
||||
required this.findController,
|
||||
required this.scrollController,
|
||||
required this.chunkController,
|
||||
required this.startHandleLayerLink,
|
||||
required this.endHandleLayerLink,
|
||||
required this.toolbarLayerLink,
|
||||
required this.selectionOverlayController,
|
||||
});
|
||||
|
||||
@override
|
||||
State<StatefulWidget> createState() => _CodeEditableState();
|
||||
|
||||
}
|
||||
|
||||
class _CodeEditableState extends State<_CodeEditable> with AutomaticKeepAliveClientMixin<_CodeEditable>, SingleTickerProviderStateMixin {
|
||||
|
||||
late bool _didAutoFocus;
|
||||
late final _CodeCursorBlinkController _cursorController;
|
||||
|
||||
late AnimationController _floatingCursorAnimationController;
|
||||
|
||||
late _CodeHighlighter _highlighter;
|
||||
late CodeIndicatorValueNotifier _codeIndicatorValueNotifier;
|
||||
|
||||
@override
|
||||
bool get wantKeepAlive => widget.focusNode.hasFocus;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_didAutoFocus = false;
|
||||
|
||||
widget.controller.addListener(_onCodeInputChanged);
|
||||
widget.inputController.addListener(_onCodeUserInputChanged);
|
||||
|
||||
_highlighter = _CodeHighlighter(
|
||||
context: context,
|
||||
controller: widget.controller,
|
||||
theme: widget.codeTheme,
|
||||
);
|
||||
|
||||
_codeIndicatorValueNotifier = CodeIndicatorValueNotifier(null);
|
||||
|
||||
_cursorController = _CodeCursorBlinkController();
|
||||
_floatingCursorAnimationController = AnimationController(vsync: this);
|
||||
|
||||
widget.floatingCursorController
|
||||
..blinkController = _cursorController
|
||||
..animationController = _floatingCursorAnimationController;
|
||||
|
||||
widget.focusNode.addListener(_onFocusChanged);
|
||||
widget.findController.addListener(_onCodeFindChanged);
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant _CodeEditable oldWidget) {
|
||||
if (oldWidget.controller != widget.controller) {
|
||||
_highlighter.controller = widget.controller;
|
||||
oldWidget.controller.removeListener(_onCodeInputChanged);
|
||||
widget.controller.addListener(_onCodeInputChanged);
|
||||
}
|
||||
if (oldWidget.inputController != widget.inputController) {
|
||||
oldWidget.inputController.removeListener(_onCodeUserInputChanged);
|
||||
widget.inputController.addListener(_onCodeUserInputChanged);
|
||||
}
|
||||
if (oldWidget.focusNode != widget.focusNode) {
|
||||
oldWidget.focusNode.removeListener(_onFocusChanged);
|
||||
widget.focusNode.addListener(_onFocusChanged);
|
||||
}
|
||||
if (oldWidget.findController != widget.findController) {
|
||||
oldWidget.findController.removeListener(_onCodeFindChanged);
|
||||
widget.findController.addListener(_onCodeFindChanged);
|
||||
}
|
||||
if (oldWidget.codeTheme != widget.codeTheme) {
|
||||
_highlighter.theme = widget.codeTheme;
|
||||
}
|
||||
super.didUpdateWidget(oldWidget);
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeDependencies() {
|
||||
super.didChangeDependencies();
|
||||
if (!_didAutoFocus && widget.autofocus) {
|
||||
_didAutoFocus = true;
|
||||
SchedulerBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted) {
|
||||
FocusScope.of(context).autofocus(widget.focusNode);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
widget.controller.removeListener(_onCodeInputChanged);
|
||||
widget.inputController.removeListener(_onCodeUserInputChanged);
|
||||
_highlighter.dispose();
|
||||
_codeIndicatorValueNotifier.dispose();
|
||||
_cursorController.dispose();
|
||||
_floatingCursorAnimationController.dispose();
|
||||
widget.focusNode.removeListener(_onFocusChanged);
|
||||
widget.findController.removeListener(_onCodeFindChanged);
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
super.build(context);
|
||||
final Widget child = _CodeScrollable(
|
||||
axisDirection: AxisDirection.down,
|
||||
controller: widget.scrollController.verticalScroller,
|
||||
viewportBuilder: (context, ViewportOffset vertical) {
|
||||
Widget codeField;
|
||||
if (widget.wordWrap) {
|
||||
codeField = _buildCodeField(vertical, null);
|
||||
} else {
|
||||
codeField = _CodeScrollable(
|
||||
axisDirection: AxisDirection.right,
|
||||
controller: widget.scrollController.horizontalScroller,
|
||||
viewportBuilder: (context, ViewportOffset horizontal) {
|
||||
return _buildCodeField(vertical, horizontal);
|
||||
},
|
||||
scrollbarBuilder: widget.scrollbarBuilder
|
||||
);
|
||||
}
|
||||
if (widget.controller.value.isInitial) {
|
||||
final String? hint = widget.hint;
|
||||
if (hint != null && hint.isNotEmpty) {
|
||||
codeField = Stack(
|
||||
children: [
|
||||
codeField,
|
||||
IgnorePointer(
|
||||
ignoring: true,
|
||||
child: Padding(
|
||||
padding: widget.padding,
|
||||
child: Text(
|
||||
hint,
|
||||
style: widget.textStyle.copyWith(
|
||||
color: widget.hintTextColor
|
||||
),
|
||||
),
|
||||
)
|
||||
)
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
final Widget? indicator = widget.indicatorBuilder?.call(
|
||||
context,
|
||||
widget.controller,
|
||||
widget.chunkController,
|
||||
_codeIndicatorValueNotifier
|
||||
);
|
||||
return Container(
|
||||
decoration: BoxDecoration(
|
||||
border: widget.border,
|
||||
color: widget.backgroundColor,
|
||||
borderRadius: widget.borderRadius,
|
||||
),
|
||||
clipBehavior: widget.clipBehavior,
|
||||
margin: widget.margin,
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
if (indicator != null)
|
||||
indicator,
|
||||
if (widget.leadingDivider != null)
|
||||
widget.leadingDivider!,
|
||||
Expanded(
|
||||
child: RepaintBoundary(
|
||||
child: CompositedTransformTarget(
|
||||
link: widget.toolbarLayerLink,
|
||||
child: codeField
|
||||
),
|
||||
),
|
||||
)
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
scrollbarBuilder: widget.scrollbarBuilder
|
||||
);
|
||||
return CodeEditorTapRegion(
|
||||
onTapOutside: (_) {
|
||||
widget.focusNode.unfocus();
|
||||
},
|
||||
child: NotificationListener(
|
||||
onNotification: (notification) {
|
||||
if (notification is ScrollStartNotification) {
|
||||
widget.selectionOverlayController.hideToolbar();
|
||||
}
|
||||
return false;
|
||||
},
|
||||
child: child
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildCodeField(ViewportOffset vertical, ViewportOffset? horizontal) {
|
||||
return _CodeField(
|
||||
key: widget.editorKey,
|
||||
verticalViewport: vertical,
|
||||
horizontalViewport: horizontal,
|
||||
verticalScrollbarWidth: widget.verticalScrollbarWidth ?? _kScrollbarThickness,
|
||||
horizontalScrollbarHeight: widget.horizontalScrollbarHeight ?? _kScrollbarThickness,
|
||||
selection: widget.controller.selection,
|
||||
highlightSelections: widget.findController.allMatchSelections,
|
||||
codes: widget.controller.codeLines,
|
||||
textStyle: widget.textStyle,
|
||||
hasFocus: widget.focusNode.hasFocus,
|
||||
highlighter: _highlighter,
|
||||
showCursorNotifier: _cursorController,
|
||||
floatingCursorNotifier: widget.floatingCursorController,
|
||||
onRenderParagraphsChanged: (paragraphs) {
|
||||
_codeIndicatorValueNotifier.value = CodeIndicatorValue(
|
||||
paragraphs: paragraphs,
|
||||
focusedIndex: widget.controller.selection.extentIndex
|
||||
);
|
||||
},
|
||||
selectionColor: widget.selectionColor,
|
||||
highlightColor: widget.highlightColor,
|
||||
cursorColor: widget.cursorColor,
|
||||
cursorLineColor: widget.cursorLineColor,
|
||||
chunkIndicatorColor: widget.chunkIndicatorColor,
|
||||
cursorWidth: widget.cursorWidth,
|
||||
padding: widget.padding,
|
||||
readOnly: widget.readOnly,
|
||||
// Enable long text rendering when the find is on.
|
||||
maxLengthSingleLineRendering: widget.findController.value != null ? null : widget.maxLengthSingleLineRendering,
|
||||
startHandleLayerLink: widget.startHandleLayerLink,
|
||||
endHandleLayerLink: widget.endHandleLayerLink,
|
||||
);
|
||||
}
|
||||
|
||||
void _onFocusChanged() {
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
_updateCursorState();
|
||||
_updateAutoCompleteState(false);
|
||||
updateKeepAlive();
|
||||
if (!widget.focusNode.hasFocus) {
|
||||
if (kIsAndroid || kIsIOS) {
|
||||
widget.controller.cancelSelection();
|
||||
}
|
||||
widget.selectionOverlayController.hideHandle();
|
||||
widget.selectionOverlayController.hideToolbar();
|
||||
}
|
||||
}
|
||||
|
||||
void _onCodeInputChanged() {
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
widget.onChanged?.call(widget.controller.value);
|
||||
if (widget.controller.codeLines != widget.controller.preValue?.codeLines &&
|
||||
widget.controller.preValue != null) {
|
||||
widget.selectionOverlayController.hideHandle();
|
||||
widget.selectionOverlayController.hideToolbar();
|
||||
} else {
|
||||
_updateAutoCompleteState(false);
|
||||
}
|
||||
_updateCursorState();
|
||||
setState(() {
|
||||
});
|
||||
}
|
||||
|
||||
void _onCodeUserInputChanged() {
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
// Delay 50ms to update the auto-complate prompt words.
|
||||
Future.delayed(const Duration(milliseconds: 50), () {
|
||||
_updateAutoCompleteState(true);
|
||||
});
|
||||
}
|
||||
|
||||
void _onCodeFindChanged() {
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
final CodeFindValue? value = widget.findController.value;
|
||||
if (value == null) {
|
||||
widget.focusNode.requestFocus();
|
||||
return;
|
||||
}
|
||||
if (widget.focusNode.hasFocus) {
|
||||
return;
|
||||
}
|
||||
final CodeLineSelection? currentMatch = widget.findController.currentMatchSelection;
|
||||
if (currentMatch == null) {
|
||||
return;
|
||||
}
|
||||
widget.controller.selection = currentMatch;
|
||||
if (currentMatch.isSameLine) {
|
||||
widget.controller.makePositionCenterIfInvisible(CodeLinePosition(
|
||||
index: currentMatch.start.index,
|
||||
offset: (currentMatch.startOffset + currentMatch.endOffset) >> 1
|
||||
));
|
||||
} else {
|
||||
widget.controller.makePositionCenterIfInvisible(currentMatch.start);
|
||||
}
|
||||
}
|
||||
|
||||
void _updateCursorState() {
|
||||
if (widget.focusNode.hasFocus && (!widget.readOnly || widget.showCursorWhenReadOnly)) {
|
||||
_cursorController.startBlink();
|
||||
} else {
|
||||
_cursorController.stopBlink();
|
||||
}
|
||||
}
|
||||
|
||||
void _updateAutoCompleteState(bool isCodeLineChanged) {
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
final _CodeAutocompleteState? autocompleteState;
|
||||
try {
|
||||
autocompleteState = context.findAncestorStateOfType<_CodeAutocompleteState>();
|
||||
} catch (e) {
|
||||
// Ignore the error when the widget is disposed.
|
||||
return;
|
||||
}
|
||||
if (autocompleteState == null) {
|
||||
return;
|
||||
}
|
||||
if (!isCodeLineChanged) {
|
||||
autocompleteState.dismiss();
|
||||
return;
|
||||
}
|
||||
if (widget.controller.isComposing || !widget.controller.selection.isCollapsed) {
|
||||
autocompleteState.dismiss();
|
||||
return;
|
||||
}
|
||||
final _CodeFieldRender? render = widget.editorKey.currentContext?.findRenderObject() as _CodeFieldRender?;
|
||||
if (render == null) {
|
||||
autocompleteState.dismiss();
|
||||
return;
|
||||
}
|
||||
final Offset? position = render.calculateTextPositionScreenOffset(widget.controller.selection.extent, true);
|
||||
if (position == null) {
|
||||
autocompleteState.dismiss();
|
||||
return;
|
||||
}
|
||||
autocompleteState.show(
|
||||
layerLink: widget.startHandleLayerLink,
|
||||
position: position,
|
||||
lineHeight: render.lineHeight,
|
||||
value: widget.controller.value,
|
||||
onAutocomplete: (value) {
|
||||
autocompleteState?.dismiss();
|
||||
final CodeLineSelection selection = widget.controller.selection;
|
||||
widget.controller.replaceSelection(value.word, selection.copyWith(
|
||||
baseOffset: selection.baseOffset - value.input.length,
|
||||
));
|
||||
widget.controller.selection = selection.copyWith(
|
||||
baseOffset: selection.baseOffset + value.selection.baseOffset,
|
||||
extentOffset: selection.extentOffset + value.selection.extentOffset,
|
||||
);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class _CodeCursorBlinkController extends ValueNotifier<bool> {
|
||||
|
||||
Timer? _timer;
|
||||
|
||||
_CodeCursorBlinkController() : super(false);
|
||||
|
||||
void startBlink() {
|
||||
if (_timer != null) {
|
||||
_timer!.cancel();
|
||||
}
|
||||
_timer = Timer.periodic(_kCursorBlinkHalfPeriod, _cursorTick);
|
||||
if (kIsAndroid || kIsIOS) {
|
||||
// Wait selection position to update
|
||||
Future.delayed(const Duration(milliseconds: 100), () {
|
||||
value = true;
|
||||
});
|
||||
} else {
|
||||
value = true;
|
||||
}
|
||||
}
|
||||
|
||||
void stopBlink() {
|
||||
if (_timer == null) {
|
||||
return;
|
||||
}
|
||||
_timer?.cancel();
|
||||
_timer = null;
|
||||
value = false;
|
||||
}
|
||||
|
||||
void _cursorTick(Timer timer) {
|
||||
value = !value;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
stopBlink();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
part of re_editor;
|
||||
|
||||
extension _InlineSpanExtension on InlineSpan {
|
||||
|
||||
int get length => _computeLength();
|
||||
|
||||
int _computeLength() {
|
||||
int len = 0;
|
||||
if (this is TextSpan) {
|
||||
len += (this as TextSpan).length;
|
||||
} else {
|
||||
len += toPlainText(includePlaceholders: false).length;
|
||||
}
|
||||
return len;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension _TextSpanExtension on TextSpan {
|
||||
|
||||
int get length => _computeLength();
|
||||
|
||||
int _computeLength() {
|
||||
int len = 0;
|
||||
if (text != null) {
|
||||
len += text!.length;
|
||||
}
|
||||
if (children != null) {
|
||||
for (final InlineSpan span in children!) {
|
||||
len += span.length;
|
||||
}
|
||||
}
|
||||
return len;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension _OffsetExtension on Offset {
|
||||
|
||||
bool isSamePosition(Offset offset) {
|
||||
return (this - offset).distance < 10;
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,525 @@
|
||||
part of re_editor;
|
||||
|
||||
class _CodeFindControllerImpl extends ValueNotifier<CodeFindValue?> implements CodeFindController {
|
||||
|
||||
late final CodeLineEditingController _controller;
|
||||
late final _IsolateTasker<_CodeFindPayload, CodeFindResult?> _tasker;
|
||||
late final TextEditingController _findInputController;
|
||||
late final FocusNode _findInputFocusNode;
|
||||
late final TextEditingController _replaceInputController;
|
||||
late final FocusNode _replaceInputFocusNode;
|
||||
late bool _shouldNotUpdateResults;
|
||||
late bool _replacingMatch;
|
||||
|
||||
_CodeFindControllerImpl(CodeLineEditingController controller, [CodeFindValue? value]) : super(value) {
|
||||
_controller = controller is _CodeLineEditingControllerDelegate ? controller.delegate : controller;
|
||||
_controller.addListener(_updateResult);
|
||||
_tasker = _IsolateTasker<_CodeFindPayload, CodeFindResult?>('CodeFind', _run);
|
||||
_findInputController = TextEditingController();
|
||||
_findInputController.addListener(_onFindPatternChanged);
|
||||
_findInputFocusNode = FocusNode();
|
||||
_replaceInputController = TextEditingController();
|
||||
_replaceInputFocusNode = FocusNode();
|
||||
_shouldNotUpdateResults = false;
|
||||
_replacingMatch = false;
|
||||
_updateResult();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
super.dispose();
|
||||
_controller.removeListener(_updateResult);
|
||||
_findInputController.removeListener(_onFindPatternChanged);
|
||||
_findInputController.dispose();
|
||||
_findInputFocusNode.dispose();
|
||||
_replaceInputController.dispose();
|
||||
_replaceInputFocusNode.dispose();
|
||||
_tasker.close();
|
||||
}
|
||||
|
||||
@override
|
||||
TextEditingController get findInputController => _findInputController;
|
||||
|
||||
@override
|
||||
TextEditingController get replaceInputController => _replaceInputController;
|
||||
|
||||
@override
|
||||
FocusNode get findInputFocusNode => _findInputFocusNode;
|
||||
|
||||
@override
|
||||
FocusNode get replaceInputFocusNode => _replaceInputFocusNode;
|
||||
|
||||
@override
|
||||
List<CodeLineSelection>? get allMatchSelections {
|
||||
final List<CodeLineSelection>? matches = value?.result?.matches;
|
||||
if (matches == null) {
|
||||
return null;
|
||||
}
|
||||
if (value!.result!.dirty) {
|
||||
return null;
|
||||
}
|
||||
final List<CodeLineSelection> selections = [];
|
||||
for (final CodeLineSelection match in matches) {
|
||||
final CodeLineSelection? selection = convertMatchToSelection(match);
|
||||
if (selection == null) {
|
||||
continue;
|
||||
}
|
||||
selections.add(selection);
|
||||
}
|
||||
return selections;
|
||||
}
|
||||
|
||||
@override
|
||||
CodeLineSelection? get currentMatchSelection {
|
||||
final CodeLineSelection? currentMatch = value?.result?.currentMatch;
|
||||
if (currentMatch == null) {
|
||||
return null;
|
||||
}
|
||||
if (value!.result!.dirty) {
|
||||
return null;
|
||||
}
|
||||
return convertMatchToSelection(currentMatch);
|
||||
}
|
||||
|
||||
@override
|
||||
void findMode() {
|
||||
_findInputFocusNode.requestFocus();
|
||||
final String? autoFilled = _autoFilledPattern();
|
||||
_findInputController.removeListener(_onFindPatternChanged);
|
||||
if (autoFilled != null) {
|
||||
_findInputController.value = TextEditingValue(
|
||||
text: autoFilled,
|
||||
selection: TextSelection(
|
||||
baseOffset: 0,
|
||||
extentOffset: autoFilled.length
|
||||
)
|
||||
);
|
||||
} else {
|
||||
_findInputController.selection = TextSelection(
|
||||
baseOffset: 0,
|
||||
extentOffset: _findInputController.text.length
|
||||
);
|
||||
}
|
||||
_findInputController.addListener(_onFindPatternChanged);
|
||||
final CodeFindValue preValue = value ?? const CodeFindValue.empty();
|
||||
value = preValue.copyWith(
|
||||
option: preValue.option.copyWith(
|
||||
pattern: _findInputController.text
|
||||
),
|
||||
result: null,
|
||||
searching: true
|
||||
);
|
||||
_updateResult();
|
||||
}
|
||||
|
||||
@override
|
||||
void replaceMode() {
|
||||
_replaceInputFocusNode.requestFocus();
|
||||
final String? autoFilled = _autoFilledPattern();
|
||||
_findInputController.removeListener(_onFindPatternChanged);
|
||||
if (autoFilled != null) {
|
||||
_findInputController.value = TextEditingValue(
|
||||
text: autoFilled,
|
||||
selection: TextSelection(
|
||||
baseOffset: 0,
|
||||
extentOffset: autoFilled.length
|
||||
)
|
||||
);
|
||||
} else {
|
||||
_findInputController.selection = TextSelection(
|
||||
baseOffset: 0,
|
||||
extentOffset: _findInputController.text.length
|
||||
);
|
||||
}
|
||||
_findInputController.addListener(_onFindPatternChanged);
|
||||
final CodeFindValue preValue = value ?? const CodeFindValue.empty();
|
||||
value = preValue.copyWith(
|
||||
option: preValue.option.copyWith(
|
||||
pattern: _findInputController.text,
|
||||
),
|
||||
replaceMode: true,
|
||||
result: null,
|
||||
searching: true
|
||||
);
|
||||
_updateResult();
|
||||
}
|
||||
|
||||
@override
|
||||
void focusOnFindInput() {
|
||||
_findInputFocusNode.requestFocus();
|
||||
_findInputController.selection = TextSelection(
|
||||
baseOffset: 0,
|
||||
extentOffset: _findInputController.text.length
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void focusOnReplaceInput() {
|
||||
_replaceInputFocusNode.requestFocus();
|
||||
_replaceInputController.selection = TextSelection(
|
||||
baseOffset: 0,
|
||||
extentOffset: _replaceInputController.text.length
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void toggleMode() {
|
||||
final CodeFindValue? preValue = value;
|
||||
if (preValue == null) {
|
||||
return;
|
||||
}
|
||||
value = preValue.copyWith(
|
||||
replaceMode: !preValue.replaceMode,
|
||||
result: preValue.result
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void close() {
|
||||
value = null;
|
||||
}
|
||||
|
||||
@override
|
||||
void toggleRegex() {
|
||||
final CodeFindOption? option = value?.option;
|
||||
if (option == null) {
|
||||
return;
|
||||
}
|
||||
value = value?.copyWith(
|
||||
option: option.copyWith(
|
||||
regex: !option.regex,
|
||||
),
|
||||
result: null,
|
||||
searching: true
|
||||
);
|
||||
_updateResult();
|
||||
}
|
||||
|
||||
@override
|
||||
void toggleCaseSensitive() {
|
||||
final CodeFindOption? option = value?.option;
|
||||
if (option == null) {
|
||||
return;
|
||||
}
|
||||
value = value?.copyWith(
|
||||
option: option.copyWith(
|
||||
caseSensitive: !option.caseSensitive,
|
||||
),
|
||||
result: null,
|
||||
searching: true
|
||||
);
|
||||
_updateResult();
|
||||
}
|
||||
|
||||
@override
|
||||
void previousMatch() {
|
||||
final CodeFindResult? result = value?.result;
|
||||
if (result == null || result.dirty) {
|
||||
return;
|
||||
}
|
||||
final CodeFindValue newValue = value!.copyWith(
|
||||
result: result.previous
|
||||
);
|
||||
_expandChunkIfNeeded(newValue);
|
||||
value = newValue;
|
||||
if (result.matches.length == 1) {
|
||||
final CodeLineSelection? selection = currentMatchSelection;
|
||||
if (selection != null) {
|
||||
_controller.makePositionCenterIfInvisible(selection.start);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void nextMatch() {
|
||||
final CodeFindResult? result = value?.result;
|
||||
if (result == null || result.dirty) {
|
||||
return;
|
||||
}
|
||||
final CodeFindValue newValue = value!.copyWith(
|
||||
result: result.next
|
||||
);
|
||||
_expandChunkIfNeeded(newValue);
|
||||
value = newValue;
|
||||
if (result.matches.length == 1) {
|
||||
final CodeLineSelection? selection = currentMatchSelection;
|
||||
if (selection != null) {
|
||||
_controller.makePositionCenterIfInvisible(selection.start);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void replaceMatch() {
|
||||
final CodeFindResult? result = value?.result;
|
||||
if (result == null || result.dirty) {
|
||||
return;
|
||||
}
|
||||
if (currentMatchSelection == null) {
|
||||
_expandChunkIfNeeded(value!);
|
||||
}
|
||||
final CodeLineSelection? selection = currentMatchSelection;
|
||||
if (selection == null) {
|
||||
return;
|
||||
}
|
||||
_replacingMatch = true;
|
||||
final CodeLines preCodeLines = _controller.codeLines;
|
||||
_controller.replaceSelection(_replaceInputController.text, selection);
|
||||
final CodeFindValue newValue = value!.copyWith(
|
||||
result: result.next.copyWith(
|
||||
dirty: !preCodeLines.equals(_controller.codeLines)
|
||||
)
|
||||
);
|
||||
_expandChunkIfNeeded(newValue);
|
||||
value = newValue;
|
||||
_replacingMatch = false;
|
||||
}
|
||||
|
||||
@override
|
||||
void replaceAllMatches() {
|
||||
final CodeFindResult? result = value?.result;
|
||||
if (result == null || result.matches.isEmpty || result.dirty) {
|
||||
return;
|
||||
}
|
||||
final CodeFindOption? option = value?.option;
|
||||
if (option == null) {
|
||||
return;
|
||||
}
|
||||
final RegExp? regExp = option.regExp;
|
||||
if (regExp == null) {
|
||||
return;
|
||||
}
|
||||
_replacingMatch = true;
|
||||
final CodeLines preCodeLine = _controller.codeLines;
|
||||
_controller.replaceAll(regExp, _replaceInputController.text);
|
||||
value = value?.copyWith(
|
||||
result: result.copyWith(
|
||||
dirty: !preCodeLine.equals(_controller.codeLines)
|
||||
)
|
||||
);
|
||||
_replacingMatch = false;
|
||||
}
|
||||
|
||||
@override
|
||||
CodeLineSelection? convertMatchToSelection(CodeLineSelection match) {
|
||||
final CodeLineIndex baseIndex = _controller.lineIndex2Index(match.baseIndex);
|
||||
if (baseIndex.chunkIndex >= 0) {
|
||||
// This match is in a collapsed chunk, invisble
|
||||
return null;
|
||||
}
|
||||
final CodeLineIndex extentIndex;
|
||||
if (match.isSameLine) {
|
||||
extentIndex = baseIndex;
|
||||
} else {
|
||||
extentIndex = _controller.lineIndex2Index(match.extentIndex);
|
||||
}
|
||||
if (extentIndex.chunkIndex >= 0) {
|
||||
// This match is in a collapsed chunk, invisble
|
||||
return null;
|
||||
}
|
||||
return match.copyWith(
|
||||
baseIndex: baseIndex.index,
|
||||
extentIndex: extentIndex.index
|
||||
);
|
||||
}
|
||||
|
||||
void _onFindPatternChanged() {
|
||||
final CodeFindOption? option = value?.option;
|
||||
if (option == null) {
|
||||
return;
|
||||
}
|
||||
if (_findInputController.text == option.pattern) {
|
||||
return;
|
||||
}
|
||||
value = value?.copyWith(
|
||||
option: option.copyWith(
|
||||
pattern: _findInputController.text,
|
||||
),
|
||||
result: null,
|
||||
searching: true
|
||||
);
|
||||
_updateResult();
|
||||
}
|
||||
|
||||
String? _autoFilledPattern() {
|
||||
final CodeLineSelection selection = _controller.selection;
|
||||
if (selection.isCollapsed || !selection.isSameLine) {
|
||||
return null;
|
||||
}
|
||||
return _controller.selectedText;
|
||||
}
|
||||
|
||||
void _updateResult() {
|
||||
if (_shouldNotUpdateResults) {
|
||||
return;
|
||||
}
|
||||
final CodeFindOption? option = value?.option;
|
||||
if (option == null || option.pattern.isEmpty) {
|
||||
value = value?.copyWith(
|
||||
result: null,
|
||||
searching: false
|
||||
);
|
||||
return;
|
||||
}
|
||||
final bool optionChanged = value?.result?.option != option;
|
||||
if (!optionChanged && _controller.codeLines.equals(value?.result?.codeLines)) {
|
||||
value = value?.copyWith(
|
||||
result: value?.result,
|
||||
searching: false
|
||||
);
|
||||
return;
|
||||
}
|
||||
final _CodeFindPayload payload = _CodeFindPayload(
|
||||
codeLines: _controller.codeLines,
|
||||
selection: _controller.unfoldLineSelection,
|
||||
option: option,
|
||||
forwardMatch: !_replacingMatch
|
||||
);
|
||||
_tasker.run(payload, (result) {
|
||||
if (option == value?.option) {
|
||||
final CodeFindValue newValue = value!.copyWith(
|
||||
result: result,
|
||||
searching: false
|
||||
);
|
||||
if (optionChanged) {
|
||||
_expandChunkIfNeeded(newValue);
|
||||
}
|
||||
value = newValue;
|
||||
} else {
|
||||
value = value?.copyWith(
|
||||
result: null,
|
||||
searching: false
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void _expandChunkIfNeeded(CodeFindValue value) {
|
||||
_shouldNotUpdateResults = true;
|
||||
final CodeLineSelection? match = value.result?.currentMatch;
|
||||
if (match != null) {
|
||||
_expandChunkIfSelectionInvisible(match);
|
||||
}
|
||||
_shouldNotUpdateResults = false;
|
||||
}
|
||||
|
||||
void _expandChunkIfSelectionInvisible(CodeLineSelection match) {
|
||||
if (match.isSameLine) {
|
||||
final CodeLineIndex start = _controller.lineIndex2Index(match.startIndex);
|
||||
if (start.chunkIndex < 0) {
|
||||
return;
|
||||
}
|
||||
_controller.expandChunk(start.index);
|
||||
} else {
|
||||
final CodeLineIndex start = _controller.lineIndex2Index(match.startIndex);
|
||||
final CodeLineIndex end = _controller.lineIndex2Index(match.endIndex);
|
||||
if (start.chunkIndex >= 0) {
|
||||
_controller.expandChunk(start.index);
|
||||
} else if (end.chunkIndex >= 0) {
|
||||
_controller.expandChunk(end.index);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
// If the selection is in a nested chunk, we should expand the chunk from outside one by one
|
||||
_expandChunkIfSelectionInvisible(match);
|
||||
}
|
||||
|
||||
@pragma('vm:entry-point')
|
||||
static CodeFindResult? _run(_CodeFindPayload payload) {
|
||||
final RegExp? regExp = payload.option.regExp;
|
||||
if (regExp == null) {
|
||||
return null;
|
||||
}
|
||||
final List<String> rawCodeLines = payload.codeLines.toList().fold([], (previousValue, element) {
|
||||
previousValue.addAll(element.flat());
|
||||
return previousValue;
|
||||
});
|
||||
final Iterable<Match> matches = regExp.allMatches(rawCodeLines.join(TextLineBreak.lf.value));
|
||||
if (matches.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
final List<CodeLineSelection> selections = [];
|
||||
for (final Match match in matches) {
|
||||
final CodeLinePosition start = _findPosition(rawCodeLines, match.start);
|
||||
final CodeLinePosition end = _findPosition(rawCodeLines, match.end);
|
||||
selections.add(CodeLineSelection(
|
||||
baseIndex: start.index,
|
||||
baseOffset: start.offset,
|
||||
extentIndex: end.index,
|
||||
extentOffset: end.offset
|
||||
));
|
||||
}
|
||||
int index;
|
||||
if (payload.forwardMatch) {
|
||||
index = selections.length - 1;
|
||||
for (; index > 0; index--) {
|
||||
if (selections[index].contains(payload.selection)) {
|
||||
break;
|
||||
}
|
||||
if (selections[index].endIndex < payload.selection.startIndex) {
|
||||
break;
|
||||
}
|
||||
if (selections[index].endIndex == payload.selection.startIndex &&
|
||||
selections[index].endOffset <= payload.selection.startOffset) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
index = 0;
|
||||
for (; index < selections.length; index++) {
|
||||
if (selections[index].contains(payload.selection)) {
|
||||
break;
|
||||
}
|
||||
if (selections[index].startIndex > payload.selection.endIndex) {
|
||||
break;
|
||||
}
|
||||
if (selections[index].startIndex == payload.selection.endIndex &&
|
||||
selections[index].startOffset >= payload.selection.endOffset) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return CodeFindResult(
|
||||
index: max(min(index, selections.length - 1), 0),
|
||||
matches: selections,
|
||||
option: payload.option,
|
||||
codeLines: payload.codeLines,
|
||||
dirty: false
|
||||
);
|
||||
}
|
||||
|
||||
static CodeLinePosition _findPosition(List<String> codeLines, int index) {
|
||||
int start = 0;
|
||||
int line = 0;
|
||||
int offset = -1;
|
||||
for (; line < codeLines.length; line++) {
|
||||
if (index <= start + codeLines[line].length) {
|
||||
offset = index - start;
|
||||
break;
|
||||
}
|
||||
start += codeLines[line].length + 1;
|
||||
}
|
||||
return CodeLinePosition(
|
||||
index: line,
|
||||
offset: offset
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class _CodeFindPayload {
|
||||
|
||||
final CodeLines codeLines;
|
||||
final CodeLineSelection selection;
|
||||
final CodeFindOption option;
|
||||
final bool forwardMatch;
|
||||
|
||||
const _CodeFindPayload({
|
||||
required this.codeLines,
|
||||
required this.selection,
|
||||
required this.option,
|
||||
required this.forwardMatch,
|
||||
});
|
||||
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
part of re_editor;
|
||||
|
||||
// The time the animation of the floating cursor snapping to the final cursor position will take.
|
||||
const Duration floatingCursorSnapDuration = Duration(milliseconds: 300);
|
||||
|
||||
// Class containing the floating cursor control logic.
|
||||
class _CodeFloatingCursorController
|
||||
extends ValueNotifier<_FloatingCursorState> {
|
||||
late final _CodeCursorBlinkController _blinkController;
|
||||
late final AnimationController _animationController;
|
||||
|
||||
_CodeFloatingCursorController() : super(const _FloatingCursorState());
|
||||
|
||||
/// Sets the [Offset] and [CodeLineSelection] of the cursors. Setting either one of these offsets
|
||||
/// to null is equivalent to turning off the corresponding cursor.
|
||||
void setFloatingCursorPositions(
|
||||
{Offset? floatingCursorOffset,
|
||||
Offset? previewCursorOffset,
|
||||
Offset? finalCursorOffset,
|
||||
CodeLineSelection? finalCursorSelection}) {
|
||||
if (value.floatingCursorOffset != null && floatingCursorOffset == null) {
|
||||
// Starting the floating cursor, stop blinking of the normal cursor
|
||||
_blinkController.startBlink();
|
||||
} else if (value.floatingCursorOffset == null &&
|
||||
floatingCursorOffset != null) {
|
||||
// Stopping the floating cursor, resume blinking of the normal cursor
|
||||
_blinkController.stopBlink();
|
||||
}
|
||||
|
||||
value = _FloatingCursorState(
|
||||
floatingCursorOffset: floatingCursorOffset,
|
||||
previewCursorOffset: previewCursorOffset,
|
||||
finalCursorOffset: finalCursorOffset,
|
||||
finalCursorSelection: finalCursorSelection,
|
||||
);
|
||||
}
|
||||
|
||||
/// Turns off the floating cursor by setting all the offsets to null.
|
||||
void disableFloatingCursor() {
|
||||
setFloatingCursorPositions();
|
||||
}
|
||||
|
||||
/// Update the [Offset] value of preview cursor.
|
||||
void updatePreviewCursorOffset(Offset? previewCursorOffset) {
|
||||
value = value.copyWith(previewCursorOffset: previewCursorOffset);
|
||||
}
|
||||
|
||||
void _onFloatingCursorResetAnimationTick() {
|
||||
if (_animationController.isCompleted) {
|
||||
// Once animation is complete, turn off the floating cursor off
|
||||
disableFloatingCursor();
|
||||
} else {
|
||||
final double lerpValue = _animationController.value;
|
||||
final double lerpX = ui.lerpDouble(value.floatingCursorOffset!.dx,
|
||||
value.finalCursorOffset!.dx, lerpValue)!;
|
||||
final double lerpY = ui.lerpDouble(value.floatingCursorOffset!.dy,
|
||||
value.finalCursorOffset!.dy, lerpValue)!;
|
||||
|
||||
setFloatingCursorPositions(
|
||||
floatingCursorOffset: Offset(lerpX, lerpY),
|
||||
previewCursorOffset: value.previewCursorOffset,
|
||||
finalCursorOffset: value.finalCursorOffset,
|
||||
finalCursorSelection: value.finalCursorSelection);
|
||||
}
|
||||
}
|
||||
|
||||
/// Performs the "snapping" animation and turns of the floating cursor.
|
||||
void animateDisableFloatingCursor() {
|
||||
_animationController.value = 0.0;
|
||||
_animationController.animateTo(1,
|
||||
duration: floatingCursorSnapDuration, curve: Curves.decelerate);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
disableFloatingCursor();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
/// The two methods below are meant to only be used for property injection. Both [_blinkController] and [_animationController]
|
||||
/// have to be set before calling any of the other methods for the [_CodeFloatingCursorController] to work properly.
|
||||
|
||||
set blinkController(_CodeCursorBlinkController value) {
|
||||
_blinkController = value;
|
||||
}
|
||||
|
||||
set animationController(AnimationController value) {
|
||||
value.addListener(_onFloatingCursorResetAnimationTick);
|
||||
_animationController = value;
|
||||
}
|
||||
|
||||
Offset? get previewCursorOffset => value.previewCursorOffset;
|
||||
|
||||
Offset? get floatingCursorOffset => value.floatingCursorOffset;
|
||||
}
|
||||
|
||||
class _FloatingCursorState {
|
||||
/// The offset of the floating cursor.
|
||||
final Offset? floatingCursorOffset;
|
||||
|
||||
/// The offset of the preview cursor. The preview cursor is only visible when the floating cursor is hovering to the right of
|
||||
/// the end of the line, where no text is present. It shows where the actual cursor would end up if the floating cursor would
|
||||
/// be stoped in that moment.
|
||||
final Offset? previewCursorOffset;
|
||||
|
||||
/// The offset where the actual cursor would be placed if floating cursor would be stopped.
|
||||
final Offset? finalCursorOffset;
|
||||
|
||||
final CodeLineSelection? finalCursorSelection;
|
||||
|
||||
const _FloatingCursorState(
|
||||
{this.floatingCursorOffset,
|
||||
this.previewCursorOffset,
|
||||
this.finalCursorOffset,
|
||||
this.finalCursorSelection});
|
||||
|
||||
/// Creates a copy of this instance with the specified values overridden.
|
||||
_FloatingCursorState copyWith({
|
||||
Offset? floatingCursorOffset,
|
||||
Offset? previewCursorOffset,
|
||||
Offset? finalCursorOffset,
|
||||
CodeLineSelection? finalCursorSelection,
|
||||
}) {
|
||||
return _FloatingCursorState(
|
||||
floatingCursorOffset: floatingCursorOffset ?? this.floatingCursorOffset,
|
||||
previewCursorOffset: previewCursorOffset ?? this.previewCursorOffset,
|
||||
finalCursorOffset: finalCursorOffset ?? this.finalCursorOffset,
|
||||
finalCursorSelection: finalCursorSelection ?? this.finalCursorSelection,
|
||||
);
|
||||
}
|
||||
|
||||
bool isActive() {
|
||||
// Floating cursor is active only if its offset is not null.
|
||||
return floatingCursorOffset != null;
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
identical(this, other) ||
|
||||
(other is _FloatingCursorState &&
|
||||
floatingCursorOffset == other.floatingCursorOffset &&
|
||||
previewCursorOffset == other.previewCursorOffset &&
|
||||
finalCursorOffset == other.finalCursorOffset &&
|
||||
finalCursorSelection == other.finalCursorSelection);
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(floatingCursorOffset, previewCursorOffset,
|
||||
finalCursorOffset, finalCursorSelection);
|
||||
}
|
||||
@@ -0,0 +1,795 @@
|
||||
part of re_editor;
|
||||
|
||||
class _DefaultCodeCommentFormatter implements DefaultCodeCommentFormatter {
|
||||
|
||||
final String? singleLinePrefix;
|
||||
final String? multiLinePrefix;
|
||||
final String? multiLineSuffix;
|
||||
|
||||
const _DefaultCodeCommentFormatter({
|
||||
this.singleLinePrefix,
|
||||
this.multiLinePrefix,
|
||||
this.multiLineSuffix
|
||||
});
|
||||
|
||||
@override
|
||||
CodeLineEditingValue format(CodeLineEditingValue value, String indent, bool single) {
|
||||
if (single && (singleLinePrefix == null || singleLinePrefix!.isEmpty)) {
|
||||
return value;
|
||||
}
|
||||
if (!single && (multiLinePrefix == null || multiLinePrefix!.isEmpty) && (multiLineSuffix == null || multiLineSuffix!.isEmpty)) {
|
||||
return value;
|
||||
}
|
||||
final _DefaultCommentFormatter formatter;
|
||||
if (single) {
|
||||
formatter = _DefaultSingleLineCommentFormatter(singleLinePrefix!);
|
||||
} else {
|
||||
formatter = _DefaultMultiLineCommentFormatter(multiLinePrefix!, multiLineSuffix!);
|
||||
}
|
||||
return formatter.format(value, indent);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
abstract class _DefaultCommentFormatter {
|
||||
|
||||
final String symbol;
|
||||
|
||||
const _DefaultCommentFormatter(this.symbol);
|
||||
|
||||
CodeLineEditingValue format(CodeLineEditingValue value, String indent);
|
||||
|
||||
}
|
||||
|
||||
class _DefaultSingleLineCommentFormatter extends _DefaultCommentFormatter {
|
||||
const _DefaultSingleLineCommentFormatter(super.symbol);
|
||||
|
||||
@override
|
||||
CodeLineEditingValue format(CodeLineEditingValue value, String indent) {
|
||||
final CodeLineSelection selection = value.selection;
|
||||
if (selection.isSameLine) {
|
||||
return _formatSelectedCodeLine(value, indent);
|
||||
} else {
|
||||
return _formatSelectedCodeLines(value, indent);
|
||||
}
|
||||
}
|
||||
|
||||
CodeLineEditingValue _formatSelectedCodeLine(CodeLineEditingValue value, String indent) {
|
||||
final String trimCode = value.codeLines[value.selection.baseIndex].text.trimLeft();
|
||||
if (trimCode.startsWith('$symbol ')) {
|
||||
return _uncommentSelectedCodeLine(value, '$symbol ');
|
||||
} else if (trimCode.startsWith(symbol)) {
|
||||
return _uncommentSelectedCodeLine(value, symbol);
|
||||
} else {
|
||||
return _commentSelectedCodeLine(value, indent, '$symbol ');
|
||||
}
|
||||
}
|
||||
|
||||
CodeLineEditingValue _uncommentSelectedCodeLine(CodeLineEditingValue value, String prefix) {
|
||||
final CodeLineSelection selection = value.selection;
|
||||
final CodeLines codeLines = value.codeLines;
|
||||
final int lineIndex = selection.baseIndex;
|
||||
final CodeLine codeLine = codeLines[lineIndex];
|
||||
final int index = codeLine.text.indexOf(prefix);
|
||||
final CodeLines newCodeLines = CodeLines.from(codeLines);
|
||||
newCodeLines[lineIndex] = codeLine.copyWith(
|
||||
text: codeLine.text.substring(0, index) + codeLine.text.substring(index + prefix.length)
|
||||
);
|
||||
int relocation(int offset) {
|
||||
if (offset <= index) {
|
||||
return offset;
|
||||
} else {
|
||||
return max(index, offset - prefix.length);
|
||||
}
|
||||
}
|
||||
return value.copyWith(
|
||||
codeLines: newCodeLines,
|
||||
selection: selection.copyWith(
|
||||
baseOffset: relocation(selection.baseOffset),
|
||||
extentOffset: relocation(selection.extentOffset),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
CodeLineEditingValue _commentSelectedCodeLine(CodeLineEditingValue value, String indent, String prefix) {
|
||||
final CodeLineSelection selection = value.selection;
|
||||
final CodeLines codeLines = value.codeLines;
|
||||
final int lineIndex = selection.baseIndex;
|
||||
final CodeLine codeLine = codeLines[lineIndex];
|
||||
final int index = codeLine.text.getOffsetWithoutIndent(indent);
|
||||
final CodeLines newCodeLines = CodeLines.from(codeLines);
|
||||
newCodeLines[lineIndex] = codeLine.copyWith(
|
||||
text: codeLine.text.insert(prefix, index)
|
||||
);
|
||||
final int baseOffset;
|
||||
final int extentOffset;
|
||||
if (selection.isCollapsed) {
|
||||
if (selection.baseOffset < index) {
|
||||
baseOffset = extentOffset = selection.baseOffset;
|
||||
} else {
|
||||
baseOffset = extentOffset = selection.baseOffset + prefix.length;
|
||||
}
|
||||
} else {
|
||||
if (selection.startOffset < index && selection.endOffset > index) {
|
||||
if (selection.baseOffset < index) {
|
||||
baseOffset = selection.baseOffset;
|
||||
extentOffset = selection.extentOffset + prefix.length;
|
||||
} else {
|
||||
extentOffset = selection.extentOffset;
|
||||
baseOffset = selection.baseOffset + prefix.length;
|
||||
}
|
||||
} else if (selection.startOffset >= index) {
|
||||
baseOffset = selection.baseOffset + prefix.length;
|
||||
extentOffset = selection.extentOffset + prefix.length;
|
||||
} else {
|
||||
baseOffset = selection.baseOffset;
|
||||
extentOffset = selection.extentOffset;
|
||||
}
|
||||
}
|
||||
return value.copyWith(
|
||||
codeLines: newCodeLines,
|
||||
selection: selection.copyWith(
|
||||
baseOffset: baseOffset,
|
||||
extentOffset: extentOffset,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
CodeLineEditingValue _formatSelectedCodeLines(CodeLineEditingValue value, String indent) {
|
||||
final CodeLineSelection selection = value.selection;
|
||||
final CodeLines codeLines = value.codeLines;
|
||||
final List<String> texts = [];
|
||||
for (int i = selection.startIndex; i <= selection.endIndex; i++) {
|
||||
texts.add(codeLines[i].text);
|
||||
}
|
||||
final bool willComment;
|
||||
texts.removeWhere((text) => text.isEmpty);
|
||||
if (texts.isEmpty) {
|
||||
willComment = true;
|
||||
} else {
|
||||
willComment = texts.any((text) => !text.trimLeft().startsWith(symbol));
|
||||
}
|
||||
if (willComment) {
|
||||
return _commentSelectedCodeLines(value, indent, '$symbol ');
|
||||
} else {
|
||||
return _uncommentSelectedCodeLines(value, indent, symbol);
|
||||
}
|
||||
}
|
||||
|
||||
CodeLineEditingValue _commentSelectedCodeLines(CodeLineEditingValue value, String indent, String prefix) {
|
||||
final CodeLineSelection selection = value.selection;
|
||||
final CodeLines codeLines = value.codeLines;
|
||||
int? index;
|
||||
for (int i = selection.startIndex; i <= selection.endIndex; i++) {
|
||||
final CodeLine codeLine = codeLines[i];
|
||||
if (codeLine.text.isEmpty) {
|
||||
continue;
|
||||
}
|
||||
final int offset = codeLine.text.getOffsetWithoutIndent(indent);
|
||||
if (index == null) {
|
||||
index = offset;
|
||||
} else {
|
||||
index = min(index, offset);
|
||||
}
|
||||
}
|
||||
if (index == null) {
|
||||
return value;
|
||||
}
|
||||
final CodeLines newCodeLines = CodeLines.from(codeLines);
|
||||
for (int i = selection.startIndex; i <= selection.endIndex; i++) {
|
||||
final CodeLine codeLine = newCodeLines[i];
|
||||
if (codeLine.text.isEmpty) {
|
||||
continue;
|
||||
}
|
||||
final newChunks = _commentChunks(codeLine, prefix, index);
|
||||
newCodeLines[i] = codeLine.copyWith(
|
||||
text: codeLine.text.insert(prefix, index),
|
||||
chunks: newChunks
|
||||
);
|
||||
}
|
||||
final int baseOffset;
|
||||
final int extentOffset;
|
||||
if (selection.baseIndex < selection.extentIndex) {
|
||||
if (selection.baseOffset < index || newCodeLines[selection.baseIndex].text.isEmpty) {
|
||||
baseOffset = selection.baseOffset;
|
||||
} else {
|
||||
baseOffset = selection.baseOffset + prefix.length;
|
||||
}
|
||||
if (selection.extentOffset <= index) {
|
||||
extentOffset = selection.extentOffset;
|
||||
} else {
|
||||
extentOffset = selection.extentOffset + prefix.length;
|
||||
}
|
||||
} else {
|
||||
if (selection.baseOffset <= index) {
|
||||
baseOffset = selection.baseOffset;
|
||||
} else {
|
||||
baseOffset = selection.baseOffset + prefix.length;
|
||||
}
|
||||
if (selection.extentOffset < index || newCodeLines[selection.extentIndex].text.isEmpty) {
|
||||
extentOffset = selection.extentOffset;
|
||||
} else {
|
||||
extentOffset = selection.extentOffset + prefix.length;
|
||||
}
|
||||
}
|
||||
return value.copyWith(
|
||||
codeLines: newCodeLines,
|
||||
selection: selection.copyWith(
|
||||
baseOffset: baseOffset,
|
||||
extentOffset: extentOffset,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
List<CodeLine> _commentChunks(CodeLine codeLine, String prefix, int index) {
|
||||
final List<CodeLine> newCodeChunks = List.from(codeLine.chunks);
|
||||
for (int j = 0; j < newCodeChunks.length; j++) {
|
||||
final CodeLine codeLineChunk = newCodeChunks[j];
|
||||
if (codeLineChunk.text.isEmpty) {
|
||||
continue;
|
||||
}
|
||||
final newCodeLineChunks = _commentChunks(codeLineChunk, prefix, index);
|
||||
newCodeChunks[j] = codeLineChunk.copyWith(
|
||||
text: codeLineChunk.text.insert(prefix, index),
|
||||
chunks: newCodeLineChunks);
|
||||
}
|
||||
return newCodeChunks;
|
||||
}
|
||||
|
||||
CodeLineEditingValue _uncommentSelectedCodeLines(CodeLineEditingValue value, String indent, String prefix) {
|
||||
final CodeLineSelection selection = value.selection;
|
||||
final CodeLines newCodeLines = CodeLines.from(value.codeLines);
|
||||
int? baseOffset;
|
||||
int? extentOffset;
|
||||
for (int i = selection.startIndex; i <= selection.endIndex; i++) {
|
||||
final CodeLine codeLine = newCodeLines[i];
|
||||
if (codeLine.text.isEmpty) {
|
||||
continue;
|
||||
}
|
||||
final String trimCode = codeLine.text.trimLeft();
|
||||
final String deletion;
|
||||
if (trimCode.startsWith('$prefix ')) {
|
||||
deletion = '$prefix ';
|
||||
} else {
|
||||
deletion = prefix;
|
||||
}
|
||||
final int index = codeLine.text.indexOf(deletion);
|
||||
final codeChunks = _uncommentChunks(codeLine, deletion, index);
|
||||
newCodeLines[i] = codeLine.copyWith(
|
||||
text: codeLine.text.substring(0, index) + codeLine.text.substring(index + deletion.length),
|
||||
chunks: codeChunks
|
||||
);
|
||||
if (i == selection.baseIndex) {
|
||||
if (selection.baseOffset > index) {
|
||||
baseOffset = max(index, selection.baseOffset - deletion.length);
|
||||
}
|
||||
}
|
||||
if (i == selection.extentIndex) {
|
||||
if (selection.extentOffset > index) {
|
||||
extentOffset = max(index, selection.extentOffset - deletion.length);
|
||||
}
|
||||
}
|
||||
}
|
||||
return value.copyWith(
|
||||
codeLines: newCodeLines,
|
||||
selection: selection.copyWith(
|
||||
baseOffset: baseOffset,
|
||||
extentOffset: extentOffset,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
List<CodeLine> _uncommentChunks(
|
||||
CodeLine codeLine, String deletion, int index) {
|
||||
final List<CodeLine> newCodeChunks = List.from(codeLine.chunks);
|
||||
for (int j = 0; j < newCodeChunks.length; j++) {
|
||||
final CodeLine codeLineChunk = newCodeChunks[j];
|
||||
if (codeLineChunk.text.isEmpty) {
|
||||
continue;
|
||||
}
|
||||
final newCodeLineChunks =
|
||||
_uncommentChunks(codeLineChunk, deletion, index);
|
||||
newCodeChunks[j] = codeLineChunk.copyWith(
|
||||
text: codeLineChunk.text.substring(0, index) +
|
||||
codeLineChunk.text.substring(index + deletion.length),
|
||||
chunks: newCodeLineChunks);
|
||||
}
|
||||
return newCodeChunks;
|
||||
}
|
||||
}
|
||||
|
||||
class _DefaultMultiLineCommentFormatter extends _DefaultCommentFormatter {
|
||||
|
||||
final String prefix;
|
||||
final String suffix;
|
||||
|
||||
_DefaultMultiLineCommentFormatter(this.prefix, this.suffix) : super(prefix + suffix);
|
||||
|
||||
@override
|
||||
CodeLineEditingValue format(CodeLineEditingValue value, String indent) {
|
||||
final CodeLineSelection selection = value.selection;
|
||||
if (selection.isSameLine) {
|
||||
return _formatSelectedCodeLine(value, indent);
|
||||
} else {
|
||||
return _formatSelectedCodeLines(value, indent);
|
||||
}
|
||||
}
|
||||
|
||||
CodeLineEditingValue _formatSelectedCodeLine(
|
||||
CodeLineEditingValue value,
|
||||
String indent,
|
||||
) {
|
||||
final CodeLineSelection selection = value.selection;
|
||||
final String codeLine = value.codeLines[selection.baseIndex].text;
|
||||
|
||||
final int baseOffset = selection.baseOffset;
|
||||
final int extentOffset = selection.extentOffset;
|
||||
|
||||
final int base;
|
||||
final int extent;
|
||||
|
||||
if (extentOffset >= baseOffset) {
|
||||
base = baseOffset;
|
||||
extent = extentOffset;
|
||||
} else {
|
||||
base = extentOffset;
|
||||
extent = baseOffset;
|
||||
}
|
||||
|
||||
final int prefixIndex;
|
||||
final int suffixIndex = codeLine.indexOf(suffix, extent);
|
||||
|
||||
prefixIndex = _getIndexOfPrefix(
|
||||
codeLine,
|
||||
base,
|
||||
);
|
||||
|
||||
if (prefixIndex == -1 || suffixIndex == -1 || base < prefixIndex) {
|
||||
return _commentSelectedCodeLine(
|
||||
value,
|
||||
indent,
|
||||
'$prefix ',
|
||||
' $suffix',
|
||||
);
|
||||
}
|
||||
|
||||
if (codeLine.startsWith('$prefix ', prefixIndex) &&
|
||||
codeLine.startsWith(' $suffix', suffixIndex - 1)) {
|
||||
return _uncommentSelectedCodeLine(
|
||||
value,
|
||||
'$prefix ',
|
||||
' $suffix',
|
||||
prefixIndex,
|
||||
suffixIndex - 1,
|
||||
);
|
||||
} else if (codeLine.startsWith('$prefix ', prefixIndex) &&
|
||||
codeLine.startsWith(suffix, suffixIndex)) {
|
||||
return _uncommentSelectedCodeLine(
|
||||
value,
|
||||
'$prefix ',
|
||||
suffix,
|
||||
prefixIndex,
|
||||
suffixIndex,
|
||||
);
|
||||
}
|
||||
if (codeLine.startsWith(prefix, prefixIndex) &&
|
||||
codeLine.startsWith(' $suffix', suffixIndex - 1)) {
|
||||
return _uncommentSelectedCodeLine(
|
||||
value,
|
||||
prefix,
|
||||
' $suffix',
|
||||
prefixIndex,
|
||||
suffixIndex - 1,
|
||||
);
|
||||
}
|
||||
if (codeLine.startsWith(prefix, prefixIndex) &&
|
||||
codeLine.startsWith(suffix, suffixIndex)) {
|
||||
return _uncommentSelectedCodeLine(
|
||||
value,
|
||||
prefix,
|
||||
suffix,
|
||||
prefixIndex,
|
||||
suffixIndex,
|
||||
);
|
||||
} else {
|
||||
return _commentSelectedCodeLine(
|
||||
value,
|
||||
indent,
|
||||
'$prefix ',
|
||||
' $suffix',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
CodeLineEditingValue _uncommentSelectedCodeLine(
|
||||
CodeLineEditingValue value,
|
||||
String prefix,
|
||||
String suffix,
|
||||
int prefixIndex,
|
||||
int suffixIndex,
|
||||
) {
|
||||
final CodeLineSelection selection = value.selection;
|
||||
final CodeLines codeLines = value.codeLines;
|
||||
final int lineIndex = selection.baseIndex;
|
||||
final CodeLine codeLine = codeLines[lineIndex];
|
||||
|
||||
final CodeLines newCodeLines = CodeLines.from(codeLines);
|
||||
|
||||
newCodeLines[lineIndex] = codeLine.copyWith(
|
||||
text: codeLine.text.substring(0, prefixIndex) +
|
||||
codeLine.text.substring(prefixIndex + prefix.length, suffixIndex) +
|
||||
codeLine.text.substring(suffixIndex + suffix.length),
|
||||
);
|
||||
|
||||
int relocationPrefix(int offset, int deletion) {
|
||||
if (offset <= prefixIndex) {
|
||||
return offset;
|
||||
} else {
|
||||
return max(prefixIndex, offset - deletion);
|
||||
}
|
||||
}
|
||||
|
||||
int relocationSuffix(int offset, int deletion) {
|
||||
return min(offset - deletion, newCodeLines[lineIndex].text.length);
|
||||
}
|
||||
|
||||
final int deletion;
|
||||
|
||||
if (prefixIndex + this.prefix.length >= selection.baseOffset) {
|
||||
deletion = this.prefix.length;
|
||||
} else {
|
||||
deletion = prefix.length;
|
||||
}
|
||||
|
||||
final int baseOffset;
|
||||
final int extentOffset;
|
||||
|
||||
if (selection.extentOffset >= selection.baseOffset) {
|
||||
baseOffset = relocationPrefix(selection.baseOffset, deletion);
|
||||
extentOffset = relocationSuffix(selection.extentOffset, deletion);
|
||||
} else {
|
||||
baseOffset = relocationSuffix(selection.baseOffset, deletion);
|
||||
extentOffset = relocationPrefix(selection.extentOffset, deletion);
|
||||
}
|
||||
|
||||
return value.copyWith(
|
||||
codeLines: newCodeLines,
|
||||
selection: selection.copyWith(
|
||||
baseOffset: baseOffset,
|
||||
extentOffset: extentOffset,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
CodeLineEditingValue _commentSelectedCodeLine(
|
||||
CodeLineEditingValue value,
|
||||
String indent,
|
||||
String prefix,
|
||||
String suffix,
|
||||
) {
|
||||
final CodeLineSelection selection = value.selection;
|
||||
final CodeLines codeLines = value.codeLines;
|
||||
final int lineIndex = selection.baseIndex;
|
||||
final CodeLine codeLine = codeLines[lineIndex];
|
||||
final int index = codeLine.text.getOffsetWithoutIndent(indent);
|
||||
final CodeLines newCodeLines = CodeLines.from(codeLines);
|
||||
|
||||
if (selection.extentOffset >= selection.baseOffset) {
|
||||
newCodeLines[lineIndex] = codeLine.copyWith(
|
||||
text: codeLine.text
|
||||
.insert(suffix, selection.extentOffset)
|
||||
.insert(prefix, selection.baseOffset),
|
||||
);
|
||||
} else {
|
||||
newCodeLines[lineIndex] = codeLine.copyWith(
|
||||
text: codeLine.text
|
||||
.insert(suffix, selection.baseOffset)
|
||||
.insert(prefix, selection.extentOffset),
|
||||
);
|
||||
}
|
||||
|
||||
final int baseOffset;
|
||||
final int extentOffset;
|
||||
|
||||
if (selection.isCollapsed) {
|
||||
if (selection.baseOffset < index) {
|
||||
baseOffset = extentOffset = selection.baseOffset;
|
||||
} else {
|
||||
baseOffset = extentOffset = selection.baseOffset + prefix.length;
|
||||
}
|
||||
} else {
|
||||
if (selection.startOffset < index && selection.endOffset > index) {
|
||||
if (selection.baseOffset < index) {
|
||||
baseOffset = selection.baseOffset;
|
||||
extentOffset = selection.extentOffset + prefix.length;
|
||||
} else {
|
||||
extentOffset = selection.extentOffset;
|
||||
baseOffset = selection.baseOffset + prefix.length;
|
||||
}
|
||||
} else if (selection.startOffset >= index) {
|
||||
baseOffset = selection.baseOffset + prefix.length;
|
||||
extentOffset = selection.extentOffset + prefix.length;
|
||||
} else {
|
||||
baseOffset = selection.baseOffset;
|
||||
extentOffset = selection.extentOffset;
|
||||
}
|
||||
}
|
||||
|
||||
return value.copyWith(
|
||||
codeLines: newCodeLines,
|
||||
selection: selection.copyWith(
|
||||
baseOffset: baseOffset,
|
||||
extentOffset: extentOffset,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
CodeLineEditingValue _formatSelectedCodeLines(
|
||||
CodeLineEditingValue value,
|
||||
String indent,
|
||||
) {
|
||||
final CodeLineSelection selection = value.selection;
|
||||
final int baseIndex = selection.baseIndex;
|
||||
final int extentIndex = selection.extentIndex;
|
||||
|
||||
String codeFirstLine;
|
||||
String codeLastLine;
|
||||
|
||||
final int base;
|
||||
final int extent;
|
||||
|
||||
if (extentIndex >= baseIndex) {
|
||||
codeFirstLine = value.codeLines[baseIndex].text;
|
||||
codeLastLine = value.codeLines[extentIndex].text;
|
||||
|
||||
base = selection.baseOffset;
|
||||
extent = selection.extentOffset;
|
||||
} else {
|
||||
codeFirstLine = value.codeLines[extentIndex].text;
|
||||
codeLastLine = value.codeLines[baseIndex].text;
|
||||
|
||||
base = selection.extentOffset;
|
||||
extent = selection.baseOffset;
|
||||
}
|
||||
|
||||
final int prefixIndex;
|
||||
final int suffixIndex = codeLastLine.indexOf(suffix, extent);
|
||||
|
||||
prefixIndex = _getIndexOfPrefix(
|
||||
codeFirstLine,
|
||||
base,
|
||||
);
|
||||
|
||||
if (prefixIndex == -1 || suffixIndex == -1 || base < prefixIndex) {
|
||||
return _commentSelectedCodeLines(
|
||||
value,
|
||||
indent,
|
||||
'$prefix ',
|
||||
' $suffix',
|
||||
);
|
||||
}
|
||||
|
||||
if (codeFirstLine.startsWith('$prefix ', prefixIndex) &&
|
||||
codeLastLine.startsWith(' $suffix', suffixIndex - 1)) {
|
||||
return _uncommentSelectedCodeLines(
|
||||
value,
|
||||
'$prefix ',
|
||||
' $suffix',
|
||||
prefixIndex,
|
||||
suffixIndex - 1,
|
||||
);
|
||||
} else if (codeFirstLine.startsWith('$prefix ', prefixIndex) &&
|
||||
codeLastLine.startsWith(suffix, suffixIndex)) {
|
||||
return _uncommentSelectedCodeLines(
|
||||
value,
|
||||
'$prefix ',
|
||||
suffix,
|
||||
prefixIndex,
|
||||
suffixIndex,
|
||||
);
|
||||
}
|
||||
if (codeFirstLine.startsWith(prefix, prefixIndex) &&
|
||||
codeLastLine.startsWith(' $suffix', suffixIndex - 1)) {
|
||||
return _uncommentSelectedCodeLines(
|
||||
value,
|
||||
prefix,
|
||||
' $suffix',
|
||||
prefixIndex,
|
||||
suffixIndex - 1,
|
||||
);
|
||||
}
|
||||
if (codeFirstLine.startsWith(prefix, prefixIndex) &&
|
||||
codeLastLine.startsWith(suffix, suffixIndex)) {
|
||||
return _uncommentSelectedCodeLines(
|
||||
value,
|
||||
prefix,
|
||||
suffix,
|
||||
prefixIndex,
|
||||
suffixIndex,
|
||||
);
|
||||
} else {
|
||||
return _commentSelectedCodeLines(
|
||||
value,
|
||||
indent,
|
||||
'$prefix ',
|
||||
' $suffix',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
CodeLineEditingValue _uncommentSelectedCodeLines(
|
||||
CodeLineEditingValue value,
|
||||
String prefix,
|
||||
String suffix,
|
||||
int prefixIndex,
|
||||
int suffixIndex,
|
||||
) {
|
||||
final CodeLineSelection selection = value.selection;
|
||||
final CodeLines codeLines = value.codeLines;
|
||||
final CodeLines newCodeLines = CodeLines.from(codeLines);
|
||||
|
||||
final int baseIndex = selection.baseIndex;
|
||||
final int extentIndex = selection.extentIndex;
|
||||
|
||||
final CodeLine codeFirstLine;
|
||||
final CodeLine codeLastLine;
|
||||
|
||||
final int baseOffset;
|
||||
final int extentOffset;
|
||||
|
||||
if (extentIndex >= baseIndex) {
|
||||
codeFirstLine = codeLines[baseIndex];
|
||||
codeLastLine = codeLines[extentIndex];
|
||||
|
||||
newCodeLines[baseIndex] = codeFirstLine.copyWith(
|
||||
text: codeFirstLine.text.substring(0, prefixIndex) +
|
||||
codeFirstLine.text.substring(prefixIndex + prefix.length),
|
||||
);
|
||||
|
||||
newCodeLines[extentIndex] = codeLastLine.copyWith(
|
||||
text: codeLastLine.text.substring(0, suffixIndex) +
|
||||
codeLastLine.text.substring(suffixIndex + suffix.length),
|
||||
);
|
||||
|
||||
final int deletion;
|
||||
|
||||
if (prefixIndex + this.prefix.length >= selection.baseOffset) {
|
||||
deletion = this.prefix.length;
|
||||
} else {
|
||||
deletion = prefix.length;
|
||||
}
|
||||
|
||||
baseOffset = selection.baseOffset - deletion;
|
||||
extentOffset = min(
|
||||
selection.extentOffset,
|
||||
newCodeLines[extentIndex].text.length,
|
||||
);
|
||||
} else {
|
||||
codeFirstLine = codeLines[extentIndex];
|
||||
codeLastLine = codeLines[baseIndex];
|
||||
|
||||
newCodeLines[extentIndex] = codeFirstLine.copyWith(
|
||||
text: codeFirstLine.text.substring(0, prefixIndex) +
|
||||
codeFirstLine.text.substring(prefixIndex + prefix.length),
|
||||
);
|
||||
|
||||
newCodeLines[baseIndex] = codeLastLine.copyWith(
|
||||
text: codeLastLine.text.substring(0, suffixIndex) +
|
||||
codeLastLine.text.substring(suffixIndex + suffix.length),
|
||||
);
|
||||
|
||||
final int deletion;
|
||||
|
||||
if (prefixIndex + this.prefix.length >= selection.extentOffset) {
|
||||
deletion = this.prefix.length;
|
||||
} else {
|
||||
deletion = prefix.length;
|
||||
}
|
||||
|
||||
baseOffset = min(
|
||||
selection.baseOffset,
|
||||
newCodeLines[baseIndex].text.length,
|
||||
);
|
||||
extentOffset = selection.extentOffset - deletion;
|
||||
}
|
||||
|
||||
return value.copyWith(
|
||||
codeLines: newCodeLines,
|
||||
selection: selection.copyWith(
|
||||
baseOffset: baseOffset,
|
||||
extentOffset: extentOffset,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
CodeLineEditingValue _commentSelectedCodeLines(
|
||||
CodeLineEditingValue value,
|
||||
String indent,
|
||||
String prefix,
|
||||
String suffix,
|
||||
) {
|
||||
final CodeLineSelection selection = value.selection;
|
||||
final CodeLines codeLines = value.codeLines;
|
||||
final CodeLines newCodeLines = CodeLines.from(codeLines);
|
||||
|
||||
final int baseIndex = selection.baseIndex;
|
||||
final int extentIndex = selection.extentIndex;
|
||||
|
||||
final CodeLine codeFirstLine;
|
||||
final CodeLine codeLastLine;
|
||||
|
||||
if (extentIndex >= baseIndex) {
|
||||
codeFirstLine = codeLines[baseIndex];
|
||||
codeLastLine = codeLines[extentIndex];
|
||||
|
||||
newCodeLines[baseIndex] = codeFirstLine.copyWith(
|
||||
text: codeFirstLine.text.insert(prefix, selection.baseOffset),
|
||||
);
|
||||
|
||||
newCodeLines[extentIndex] = codeLastLine.copyWith(
|
||||
text: codeLastLine.text.insert(suffix, selection.extentOffset),
|
||||
);
|
||||
} else {
|
||||
codeFirstLine = codeLines[extentIndex];
|
||||
codeLastLine = codeLines[baseIndex];
|
||||
|
||||
newCodeLines[extentIndex] = codeFirstLine.copyWith(
|
||||
text: codeFirstLine.text.insert(prefix, selection.extentOffset),
|
||||
);
|
||||
|
||||
newCodeLines[baseIndex] = codeLastLine.copyWith(
|
||||
text: codeLastLine.text.insert(suffix, selection.baseOffset),
|
||||
);
|
||||
}
|
||||
|
||||
final int baseOffset;
|
||||
final int extentOffset;
|
||||
|
||||
if (extentIndex >= baseIndex) {
|
||||
baseOffset = selection.baseOffset + prefix.length;
|
||||
extentOffset = selection.extentOffset;
|
||||
} else {
|
||||
baseOffset = selection.baseOffset;
|
||||
extentOffset = selection.extentOffset + suffix.length;
|
||||
}
|
||||
|
||||
return value.copyWith(
|
||||
codeLines: newCodeLines,
|
||||
selection: selection.copyWith(
|
||||
baseOffset: baseOffset,
|
||||
extentOffset: extentOffset,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
int _getIndexOfPrefix(
|
||||
String text,
|
||||
int baseIndex,
|
||||
) {
|
||||
int index = -1;
|
||||
int prefixLength = prefix.length - 1;
|
||||
int suffixLength = suffix.length - 1;
|
||||
|
||||
if (baseIndex >= text.length - 1) {
|
||||
return index;
|
||||
}
|
||||
|
||||
for (int i = baseIndex; i > 0; i--) {
|
||||
if (text[i] == suffix[suffixLength]) {
|
||||
if (text.substring(i - suffixLength, i + 1) == suffix) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (text[i] == prefix[prefixLength]) {
|
||||
if (text.substring(i - prefixLength, i + 1) == prefix) {
|
||||
index = i - 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return index;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
part of re_editor;
|
||||
|
||||
class _CodeHighlighter extends ValueNotifier<List<_HighlightResult>> {
|
||||
|
||||
final BuildContext _context;
|
||||
final _CodeParagraphProvider _provider;
|
||||
final _CodeHighlightEngine _engine;
|
||||
|
||||
CodeLineEditingController _controller;
|
||||
CodeHighlightTheme? _theme;
|
||||
|
||||
_CodeHighlighter({
|
||||
required BuildContext context,
|
||||
required CodeLineEditingController controller,
|
||||
CodeHighlightTheme? theme,
|
||||
}) : _context = context,
|
||||
_provider = _CodeParagraphProvider(),
|
||||
_controller = controller,
|
||||
_theme = theme,
|
||||
_engine = _CodeHighlightEngine(theme),
|
||||
super(const []) {
|
||||
_controller.addListener(_onCodesChanged);
|
||||
_processHighlight();
|
||||
}
|
||||
|
||||
set controller(CodeLineEditingController value) {
|
||||
if (_controller == value) {
|
||||
return;
|
||||
}
|
||||
_controller.removeListener(_onCodesChanged);
|
||||
_controller = value;
|
||||
_controller.addListener(_onCodesChanged);
|
||||
_processHighlight();
|
||||
}
|
||||
|
||||
set theme(CodeHighlightTheme? value) {
|
||||
if (_theme == value) {
|
||||
return;
|
||||
}
|
||||
_theme = value;
|
||||
_engine.theme = value;
|
||||
_processHighlight();
|
||||
}
|
||||
|
||||
IParagraph build({
|
||||
required int index,
|
||||
required TextStyle style,
|
||||
required double maxWidth,
|
||||
int? maxLengthSingleLineRendering,
|
||||
}) {
|
||||
_provider.updateBaseStyle(style);
|
||||
_provider.updateMaxLengthSingleLineRendering(maxLengthSingleLineRendering);
|
||||
return _provider.build(_controller.buildTextSpan(
|
||||
context: _context,
|
||||
index: index,
|
||||
textSpan: _buildSpan(index, style),
|
||||
style: style
|
||||
), maxWidth);
|
||||
}
|
||||
|
||||
void clearCache() {
|
||||
_provider.clearCache();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.removeListener(_onCodesChanged);
|
||||
_engine.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
TextSpan _buildSpan(int index, TextStyle style) {
|
||||
final String text = _controller.codeLines[index].text;
|
||||
if (index >= value.length) {
|
||||
return TextSpan(
|
||||
text: text,
|
||||
style: style
|
||||
);
|
||||
}
|
||||
final _HighlightResult result = value[index];
|
||||
if (result.nodes.isEmpty) {
|
||||
return TextSpan(
|
||||
text: text,
|
||||
style: style
|
||||
);
|
||||
}
|
||||
if (result.source == text) {
|
||||
return _buildSpanFromNodes(result.nodes, style);
|
||||
}
|
||||
// Diff the changes and reuse node to avoid style blink.
|
||||
final List<_HighlightNode> startNodes = [];
|
||||
int start = 0;
|
||||
int end = text.length;
|
||||
for (int i = 0; i < result.nodes.length && start < end; i++) {
|
||||
final String value = result.nodes[i].value;
|
||||
if (text.startsWith(value, start)) {
|
||||
startNodes.add(result.nodes[i]);
|
||||
start += value.length;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
final List<_HighlightNode> endNodes = [];
|
||||
for (int i = result.nodes.length - 1; i >= 0 && start < end; i--) {
|
||||
final String value = result.nodes[i].value;
|
||||
if (text.substring(start, end).endsWith(value)) {
|
||||
endNodes.insert(0, result.nodes[i]);
|
||||
end -= value.length;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
final _HighlightNode? midNode;
|
||||
if (startNodes.isEmpty) {
|
||||
midNode = _HighlightNode(text.substring(start, end), result.nodes[0].className);
|
||||
} else if (startNodes.length < result.nodes.length) {
|
||||
midNode = _HighlightNode(text.substring(start, end), result.nodes[startNodes.length].className);
|
||||
} else if (end > start){
|
||||
midNode = _HighlightNode(text.substring(start, end), result.nodes.last.className);
|
||||
} else {
|
||||
midNode = null;
|
||||
}
|
||||
return _buildSpanFromNodes([
|
||||
...startNodes,
|
||||
if (midNode != null)
|
||||
midNode,
|
||||
...endNodes
|
||||
], style);
|
||||
}
|
||||
|
||||
TextSpan _buildSpanFromNodes(List<_HighlightNode> nodes, TextStyle baseStyle) {
|
||||
return TextSpan(
|
||||
children: nodes.map((e) => TextSpan(
|
||||
text: e.value,
|
||||
style: _findStyle(e.className)
|
||||
)).toList(),
|
||||
style: baseStyle
|
||||
);
|
||||
}
|
||||
|
||||
TextStyle? _findStyle(String? className) {
|
||||
if (className == null) {
|
||||
return null;
|
||||
}
|
||||
while(true) {
|
||||
final TextStyle? style = _theme?.theme[className];
|
||||
if (style != null) {
|
||||
return style;
|
||||
}
|
||||
final int pieceIndex = className!.indexOf('-');
|
||||
if (pieceIndex < 0) {
|
||||
break;
|
||||
}
|
||||
className = className.substring(pieceIndex + 1);
|
||||
if (className.isEmpty) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
void _onCodesChanged() {
|
||||
if (_controller.preValue?.codeLines == _controller.codeLines) {
|
||||
return;
|
||||
}
|
||||
_processHighlight();
|
||||
}
|
||||
|
||||
void _processHighlight() {
|
||||
_engine.run(_controller.codeLines, (result) => value = result);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class _CodeHighlightEngine {
|
||||
|
||||
late final _IsolateTasker<_HighlightPayload, List<_HighlightResult>> _tasker;
|
||||
|
||||
Highlight? _highlight;
|
||||
CodeHighlightTheme? _theme;
|
||||
|
||||
_CodeHighlightEngine(final CodeHighlightTheme? theme) {
|
||||
this.theme = theme;
|
||||
_tasker = _IsolateTasker<_HighlightPayload, List<_HighlightResult>>('CodeHighlightEngine', _run);
|
||||
}
|
||||
|
||||
set theme(CodeHighlightTheme? value) {
|
||||
if (_theme == value) {
|
||||
return;
|
||||
}
|
||||
_theme = value;
|
||||
final Map<String, CodeHighlightThemeMode>? modes = _theme?.languages;
|
||||
if (modes == null) {
|
||||
_highlight = null;
|
||||
} else {
|
||||
final Highlight highlight = Highlight();
|
||||
highlight.registerLanguages(modes.map((key, value) => MapEntry(key, value.mode)));
|
||||
for (final HLPlugin plugin in _theme!.plugins) {
|
||||
highlight.addPlugin(plugin);
|
||||
}
|
||||
_highlight = highlight;
|
||||
}
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
_tasker.close();
|
||||
}
|
||||
|
||||
void run(CodeLines codes, IsolateCallback<List<_HighlightResult>> callback) {
|
||||
final Highlight? highlight = _highlight;
|
||||
if (highlight == null) {
|
||||
callback(const []);
|
||||
return;
|
||||
}
|
||||
final Map<String, CodeHighlightThemeMode>? modes = _theme?.languages;
|
||||
if (modes == null) {
|
||||
callback(const []);
|
||||
return;
|
||||
}
|
||||
_tasker.run(_HighlightPayload(
|
||||
highlight: highlight,
|
||||
codes: codes,
|
||||
languages: modes.keys.toList(),
|
||||
maxSizes: modes.values.map((e) => e.maxSize).toList(),
|
||||
maxLineLengths: modes.values.map((e) => e.maxLineLength).toList(),
|
||||
), callback);
|
||||
}
|
||||
|
||||
@pragma('vm:entry-point')
|
||||
static List<_HighlightResult> _run(_HighlightPayload payload) {
|
||||
final CodeLines codeLines = payload.codes;
|
||||
final int maxSize = payload.maxSizes.reduce(min);
|
||||
final int maxLineLength = payload.maxLineLengths.reduce(min);
|
||||
// Evalaute performance
|
||||
bool canHighlight = true;
|
||||
int total = 0;
|
||||
for (int i = 0; i < codeLines.length; i++) {
|
||||
final int length = codeLines[i].length;
|
||||
if (length > maxLineLength || total > maxSize) {
|
||||
canHighlight = false;
|
||||
break;
|
||||
}
|
||||
total += length;
|
||||
}
|
||||
final String code = payload.codes.asString(TextLineBreak.lf, false);
|
||||
final HighlightResult result;
|
||||
if (!canHighlight) {
|
||||
result = payload.highlight.justTextHighlightResult(code);
|
||||
} else if (payload.languages.length == 1) {
|
||||
result = payload.highlight.highlight(code: code, language: payload.languages.first);
|
||||
} else {
|
||||
result = payload.highlight.highlightAuto(code, payload.languages);
|
||||
}
|
||||
final _HighlightLineRenderer renderer = _HighlightLineRenderer();
|
||||
result.render(renderer);
|
||||
return renderer.lineResults;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class _HighlightPayload {
|
||||
|
||||
final Highlight highlight;
|
||||
final CodeLines codes;
|
||||
final List<String> languages;
|
||||
final List<int> maxSizes;
|
||||
final List<int> maxLineLengths;
|
||||
|
||||
const _HighlightPayload({
|
||||
required this.highlight,
|
||||
required this.codes,
|
||||
required this.languages,
|
||||
required this.maxSizes,
|
||||
required this.maxLineLengths,
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
class _HighlightResult {
|
||||
final List<_HighlightNode> nodes;
|
||||
|
||||
_HighlightResult(this.nodes);
|
||||
|
||||
String get source => nodes.map((e) => e.value).join();
|
||||
}
|
||||
|
||||
class _HighlightNode {
|
||||
|
||||
final String? className;
|
||||
final String value;
|
||||
|
||||
const _HighlightNode(this.value, [this.className]);
|
||||
}
|
||||
|
||||
class _HighlightLineRenderer implements HighlightRenderer {
|
||||
|
||||
final List<_HighlightResult> lineResults;
|
||||
final List<String?> classNames;
|
||||
_HighlightLineRenderer(): lineResults = [
|
||||
_HighlightResult([])
|
||||
], classNames = [];
|
||||
|
||||
@override
|
||||
void addText(String text) {
|
||||
final String? className = classNames.isEmpty ? null : classNames.last;
|
||||
final List<String> lines = text.split(TextLineBreak.lf.value);
|
||||
lineResults.last.nodes.add(_HighlightNode(lines.first, className));
|
||||
if (lines.length > 1) {
|
||||
for (int i = 1; i < lines.length; i++) {
|
||||
lineResults.add(_HighlightResult([_HighlightNode(lines[i], className)]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void openNode(DataNode node) {
|
||||
final String? className = classNames.isEmpty ? null : classNames.last;
|
||||
String? newClassName;
|
||||
if (className == null || node.scope == null) {
|
||||
newClassName = node.scope;
|
||||
} else {
|
||||
newClassName = '$className-${node.scope!}';
|
||||
}
|
||||
newClassName = newClassName?.split('.')[0];
|
||||
classNames.add(newClassName);
|
||||
}
|
||||
|
||||
|
||||
@override
|
||||
void closeNode(DataNode node) {
|
||||
if (classNames.isNotEmpty) {
|
||||
classNames.removeLast();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,373 @@
|
||||
part of re_editor;
|
||||
|
||||
class CodeLineNumberRenderObject extends RenderBox {
|
||||
|
||||
CodeLineEditingController _controller;
|
||||
CodeIndicatorValueNotifier _notifier;
|
||||
TextStyle _textStyle;
|
||||
TextStyle _focusedTextStyle;
|
||||
int _minNumberCount;
|
||||
int _allLineCount;
|
||||
|
||||
final String Function(int lineIndex)? _customLineIndex2Text;
|
||||
final TextPainter _textPainter;
|
||||
|
||||
CodeLineNumberRenderObject({
|
||||
required CodeLineEditingController controller,
|
||||
required CodeIndicatorValueNotifier notifier,
|
||||
required TextStyle textStyle,
|
||||
required TextStyle focusedTextStyle,
|
||||
required int minNumberCount,
|
||||
String Function(int lineIndex)? custonLineIndex2Text,
|
||||
}) : _controller = controller,
|
||||
_notifier = notifier,
|
||||
_textStyle = textStyle,
|
||||
_focusedTextStyle = focusedTextStyle,
|
||||
_minNumberCount = minNumberCount,
|
||||
_allLineCount = controller.lineCount,
|
||||
_customLineIndex2Text = custonLineIndex2Text,
|
||||
_textPainter = TextPainter(
|
||||
textDirection: TextDirection.ltr,
|
||||
);
|
||||
|
||||
set controller(CodeLineEditingController value) {
|
||||
if (_controller == value) {
|
||||
return;
|
||||
}
|
||||
if (attached) {
|
||||
_controller.removeListener(_onCodeLineChanged);
|
||||
}
|
||||
_controller = value;
|
||||
if (attached) {
|
||||
_controller.addListener(_onCodeLineChanged);
|
||||
}
|
||||
_onCodeLineChanged();
|
||||
}
|
||||
|
||||
set notifier(CodeIndicatorValueNotifier value) {
|
||||
if (_notifier == value) {
|
||||
return;
|
||||
}
|
||||
if (attached) {
|
||||
_notifier.removeListener(markNeedsPaint);
|
||||
}
|
||||
_notifier = value;
|
||||
if (attached) {
|
||||
_notifier.addListener(markNeedsPaint);
|
||||
}
|
||||
markNeedsPaint();
|
||||
}
|
||||
|
||||
set textStyle(TextStyle value) {
|
||||
if (_textStyle == value) {
|
||||
return;
|
||||
}
|
||||
_textStyle = value;
|
||||
markNeedsLayout();
|
||||
}
|
||||
|
||||
set focusedTextStyle(TextStyle value) {
|
||||
if (_focusedTextStyle == value) {
|
||||
return;
|
||||
}
|
||||
_focusedTextStyle = value;
|
||||
markNeedsLayout();
|
||||
}
|
||||
|
||||
set minNumberCount(int value) {
|
||||
if (_minNumberCount == value) {
|
||||
return;
|
||||
}
|
||||
_minNumberCount = value;
|
||||
markNeedsLayout();
|
||||
}
|
||||
|
||||
@override
|
||||
bool hitTestSelf(Offset position) => true;
|
||||
|
||||
@override
|
||||
void handleEvent(PointerEvent event, BoxHitTestEntry entry) {
|
||||
if (event is PointerDownEvent) {
|
||||
final Offset position = globalToLocal(event.position);
|
||||
final CodeLineRenderParagraph? paragraph = _findParagraphByPosition(position);
|
||||
if (paragraph != null) {
|
||||
_controller.selectLine(paragraph.index);
|
||||
}
|
||||
}
|
||||
super.handleEvent(event, entry);
|
||||
}
|
||||
|
||||
@override
|
||||
void attach(covariant PipelineOwner owner) {
|
||||
_controller.addListener(_onCodeLineChanged);
|
||||
_notifier.addListener(markNeedsPaint);
|
||||
super.attach(owner);
|
||||
}
|
||||
|
||||
@override
|
||||
void detach() {
|
||||
_controller.removeListener(_onCodeLineChanged);
|
||||
_notifier.removeListener(markNeedsPaint);
|
||||
super.detach();
|
||||
}
|
||||
|
||||
@override
|
||||
void performLayout() {
|
||||
assert(constraints.maxHeight > 0 && constraints.maxHeight != double.infinity,
|
||||
'CodeLineNumber should have an explicit height.');
|
||||
_textPainter.text = TextSpan(
|
||||
text: '0' * max(_minNumberCount, _allLineCount.toString().length),
|
||||
style: _textStyle,
|
||||
);
|
||||
_textPainter.layout();
|
||||
size = Size(_textPainter.width, constraints.maxHeight);
|
||||
}
|
||||
|
||||
@override
|
||||
void paint(PaintingContext context, Offset offset) {
|
||||
final Canvas canvas = context.canvas;
|
||||
final CodeIndicatorValue? value = _notifier.value;
|
||||
if (value == null || value.paragraphs.isEmpty) {
|
||||
// line offsets are not determined.
|
||||
return;
|
||||
}
|
||||
canvas.save();
|
||||
canvas.clipRect(Rect.fromLTWH(offset.dx, offset.dy, size.width, size.height));
|
||||
int firstLineIndex = _controller.index2lineIndex(value.paragraphs.first.index);
|
||||
for (final CodeLineRenderParagraph paragraph in value.paragraphs) {
|
||||
final lineIndexText = _customLineIndex2Text?.call(firstLineIndex) ?? (firstLineIndex + 1).toString();
|
||||
_textPainter.text = TextSpan(
|
||||
text: lineIndexText,
|
||||
style: paragraph.index == value.focusedIndex ? _focusedTextStyle : _textStyle
|
||||
);
|
||||
_textPainter.layout();
|
||||
_textPainter.paint(canvas, Offset(offset.dx + size.width - _textPainter.width, offset.dy + paragraph.offset.dy));
|
||||
firstLineIndex += _controller.codeLines[paragraph.index].lineCount;
|
||||
}
|
||||
canvas.restore();
|
||||
}
|
||||
|
||||
void _onCodeLineChanged() {
|
||||
if (!attached) {
|
||||
return;
|
||||
}
|
||||
final int newAllLineCount = _controller.lineCount;
|
||||
if (max(_minNumberCount, newAllLineCount.toString().length) !=
|
||||
max(_minNumberCount, _allLineCount.toString().length)) {
|
||||
_allLineCount = newAllLineCount;
|
||||
markNeedsLayout();
|
||||
} else {
|
||||
_allLineCount = newAllLineCount;
|
||||
markNeedsPaint();
|
||||
}
|
||||
}
|
||||
|
||||
CodeLineRenderParagraph? _findParagraphByPosition(Offset position) {
|
||||
final int? index = _notifier.value?.paragraphs.indexWhere((e) => position.dy > e.top
|
||||
&& position.dy < e.bottom);
|
||||
if (index == null || index < 0) {
|
||||
return null;
|
||||
}
|
||||
return _notifier.value?.paragraphs[index];
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class CodeChunkIndicatorRenderObject extends RenderBox implements MouseTrackerAnnotation {
|
||||
|
||||
double _width;
|
||||
CodeChunkController _controller;
|
||||
CodeIndicatorValueNotifier _notifier;
|
||||
CodeChunkIndicatorPainter _painter;
|
||||
bool _collapseIndicatorVisible;
|
||||
bool _expandIndicatorVisible;
|
||||
MouseCursor _cursor;
|
||||
|
||||
CodeChunkIndicatorRenderObject({
|
||||
required double width,
|
||||
required CodeChunkController controller,
|
||||
required CodeIndicatorValueNotifier notifier,
|
||||
required CodeChunkIndicatorPainter painter,
|
||||
required bool collapseIndicatorVisible,
|
||||
required bool expandIndicatorVisible,
|
||||
}) : _width = width,
|
||||
_controller = controller,
|
||||
_notifier = notifier,
|
||||
_painter = painter,
|
||||
_collapseIndicatorVisible = collapseIndicatorVisible,
|
||||
_expandIndicatorVisible = expandIndicatorVisible,
|
||||
_cursor = MouseCursor.defer;
|
||||
|
||||
set width(double value) {
|
||||
if (_width == value) {
|
||||
return;
|
||||
}
|
||||
_width = value;
|
||||
markNeedsLayout();
|
||||
}
|
||||
|
||||
set controller(CodeChunkController value) {
|
||||
if (_controller == value) {
|
||||
return;
|
||||
}
|
||||
if (attached) {
|
||||
_controller.removeListener(markNeedsPaint);
|
||||
}
|
||||
_controller = value;
|
||||
if (attached) {
|
||||
_controller.addListener(markNeedsPaint);
|
||||
}
|
||||
markNeedsPaint();
|
||||
}
|
||||
|
||||
set notifier(CodeIndicatorValueNotifier value) {
|
||||
if (_notifier == value) {
|
||||
return;
|
||||
}
|
||||
if (attached) {
|
||||
_notifier.removeListener(markNeedsPaint);
|
||||
}
|
||||
_notifier = value;
|
||||
if (attached) {
|
||||
_notifier.addListener(markNeedsPaint);
|
||||
}
|
||||
markNeedsPaint();
|
||||
}
|
||||
|
||||
set painter(CodeChunkIndicatorPainter value) {
|
||||
if (_painter == value) {
|
||||
return;
|
||||
}
|
||||
_painter = value;
|
||||
markNeedsPaint();
|
||||
}
|
||||
|
||||
set collapseIndicatorVisible(bool value) {
|
||||
if (_collapseIndicatorVisible == value) {
|
||||
return;
|
||||
}
|
||||
_collapseIndicatorVisible = value;
|
||||
markNeedsPaint();
|
||||
}
|
||||
|
||||
set expandIndicatorVisible(bool value) {
|
||||
if (_expandIndicatorVisible == value) {
|
||||
return;
|
||||
}
|
||||
_expandIndicatorVisible = value;
|
||||
markNeedsPaint();
|
||||
}
|
||||
|
||||
@override
|
||||
MouseCursor get cursor => _cursor;
|
||||
|
||||
@override
|
||||
PointerEnterEventListener? get onEnter => null;
|
||||
|
||||
@override
|
||||
PointerExitEventListener? get onExit => null;
|
||||
|
||||
@override
|
||||
bool get validForMouseTracker => true;
|
||||
|
||||
@override
|
||||
bool hitTest(BoxHitTestResult result, {required ui.Offset position}) {
|
||||
bool hitTarget = false;
|
||||
if (size.contains(position)) {
|
||||
result.add(BoxHitTestEntry(this, position));
|
||||
if (_findParagraphByPosition(position) != null) {
|
||||
_cursor = SystemMouseCursors.click;
|
||||
} else {
|
||||
_cursor = MouseCursor.defer;
|
||||
}
|
||||
hitTarget = true;
|
||||
}
|
||||
return hitTarget;
|
||||
}
|
||||
|
||||
@override
|
||||
void handleEvent(PointerEvent event, BoxHitTestEntry entry) {
|
||||
if (event is PointerDownEvent) {
|
||||
final Offset position = globalToLocal(event.position);
|
||||
final CodeLineRenderParagraph? paragraph = _findParagraphByPosition(position);
|
||||
if (paragraph != null) {
|
||||
_controller.toggle(paragraph.index);
|
||||
}
|
||||
}
|
||||
super.handleEvent(event, entry);
|
||||
}
|
||||
|
||||
@override
|
||||
void attach(covariant PipelineOwner owner) {
|
||||
_controller.addListener(markNeedsPaint);
|
||||
_notifier.addListener(markNeedsPaint);
|
||||
super.attach(owner);
|
||||
}
|
||||
|
||||
@override
|
||||
void detach() {
|
||||
_controller.removeListener(markNeedsPaint);
|
||||
_notifier.removeListener(markNeedsPaint);
|
||||
super.detach();
|
||||
}
|
||||
|
||||
@override
|
||||
void performLayout() {
|
||||
assert(_width > 0 && _width != double.infinity &&
|
||||
constraints.maxHeight > 0 && constraints.maxHeight != double.infinity,
|
||||
'CodeChunkIndicator should have an explicit width and height.');
|
||||
size = Size(_width, constraints.maxHeight);
|
||||
}
|
||||
|
||||
@override
|
||||
void paint(PaintingContext context, Offset offset) {
|
||||
final Canvas canvas = context.canvas;
|
||||
final CodeIndicatorValue? value = _notifier.value;
|
||||
if (value == null) {
|
||||
// line offsets are not determined.
|
||||
return;
|
||||
}
|
||||
if (!_expandIndicatorVisible && !_collapseIndicatorVisible) {
|
||||
return;
|
||||
}
|
||||
canvas.save();
|
||||
canvas.clipRect(Rect.fromLTWH(offset.dx, offset.dy, size.width, size.height));
|
||||
for (final CodeLineRenderParagraph paragraph in value.paragraphs) {
|
||||
final Offset newOffset = offset + Offset(0, paragraph.offset.dy);
|
||||
final Size container = Size(_width, paragraph.preferredLineHeight);
|
||||
if (paragraph.chunkParent) {
|
||||
if (_expandIndicatorVisible) {
|
||||
canvas.save();
|
||||
canvas.translate(newOffset.dx, newOffset.dy);
|
||||
_painter.paintExpandIndicator(canvas, container);
|
||||
canvas.restore();
|
||||
}
|
||||
} else if (_controller.canCollapse(paragraph.index)) {
|
||||
if (_collapseIndicatorVisible) {
|
||||
canvas.save();
|
||||
canvas.translate(newOffset.dx, newOffset.dy);
|
||||
_painter.paintCollapseIndicator(canvas, container);
|
||||
canvas.restore();
|
||||
}
|
||||
}
|
||||
}
|
||||
canvas.restore();
|
||||
}
|
||||
|
||||
CodeLineRenderParagraph? _findParagraphByPosition(Offset position) {
|
||||
final int? index = _notifier.value?.paragraphs.indexWhere((e) => position.dy > e.top
|
||||
&& position.dy < e.top + e.preferredLineHeight);
|
||||
if (index == null || index < 0) {
|
||||
return null;
|
||||
}
|
||||
final CodeLineRenderParagraph? paragraph = _notifier.value?.paragraphs[index];
|
||||
if (paragraph == null) {
|
||||
return null;
|
||||
}
|
||||
if (paragraph.chunkParent || _controller.findByIndex(paragraph.index) != null) {
|
||||
return paragraph;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,756 @@
|
||||
part of re_editor;
|
||||
|
||||
class _CodeInputController extends ChangeNotifier implements DeltaTextInputClient {
|
||||
|
||||
CodeLineEditingController _controller;
|
||||
FocusNode _focusNode;
|
||||
bool _readOnly;
|
||||
bool _autocompleteSymbols;
|
||||
bool _updateCausedByFloatingCursor;
|
||||
late Offset _floatingCursorStartingOffset;
|
||||
|
||||
TextInputConnection? _textInputConnection;
|
||||
TextEditingValue? _remoteEditingValue;
|
||||
|
||||
final _CodeFloatingCursorController _floatingCursorController;
|
||||
Timer? _floatingCursorScrollTimer;
|
||||
|
||||
GlobalKey? _editorKey;
|
||||
|
||||
_CodeInputController({
|
||||
required CodeLineEditingController controller,
|
||||
required _CodeFloatingCursorController floatingCursorController,
|
||||
required FocusNode focusNode,
|
||||
required bool readOnly,
|
||||
required bool autocompleteSymbols,
|
||||
}) : _controller = controller,
|
||||
_floatingCursorController = floatingCursorController,
|
||||
_focusNode = focusNode,
|
||||
_readOnly = readOnly,
|
||||
_updateCausedByFloatingCursor = false,
|
||||
_autocompleteSymbols = autocompleteSymbols {
|
||||
_controller.addListener(_onCodeEditingChanged);
|
||||
_focusNode.addListener(_onFocusChanged);
|
||||
}
|
||||
|
||||
void bindEditor(GlobalKey key) {
|
||||
_editorKey = key;
|
||||
}
|
||||
|
||||
set controller(CodeLineEditingController value) {
|
||||
if (_controller == value) {
|
||||
return;
|
||||
}
|
||||
_controller.removeListener(_onCodeEditingChanged);
|
||||
_controller = value;
|
||||
_controller.addListener(_onCodeEditingChanged);
|
||||
_onCodeEditingChanged();
|
||||
}
|
||||
|
||||
set focusNode(FocusNode value) {
|
||||
if (_focusNode == value) {
|
||||
return;
|
||||
}
|
||||
_focusNode.removeListener(_onFocusChanged);
|
||||
_focusNode = value;
|
||||
_focusNode.addListener(_onFocusChanged);
|
||||
}
|
||||
|
||||
set readOnly(bool value) {
|
||||
if (_readOnly == value) {
|
||||
return;
|
||||
}
|
||||
_readOnly = value;
|
||||
}
|
||||
|
||||
set autocompleteSymbols(bool value) {
|
||||
if (_autocompleteSymbols == value) {
|
||||
return;
|
||||
}
|
||||
_autocompleteSymbols = value;
|
||||
}
|
||||
|
||||
set value(CodeLineEditingValue value) {
|
||||
_controller.value = value;
|
||||
}
|
||||
|
||||
CodeLineEditingValue get value => _controller.value;
|
||||
|
||||
set codeLines(CodeLines value) {
|
||||
_controller.codeLines = value.isEmpty ? _kInitialCodeLines : value;
|
||||
}
|
||||
|
||||
CodeLines get codeLines => _controller.codeLines;
|
||||
|
||||
set selection(CodeLineSelection value) => _controller.selection = value;
|
||||
|
||||
CodeLineSelection get selection => _controller.selection;
|
||||
|
||||
set composing(TextRange value) => _controller.composing = value;
|
||||
|
||||
TextRange get composing => _controller.composing;
|
||||
|
||||
@override
|
||||
void connectionClosed() {
|
||||
}
|
||||
|
||||
@override
|
||||
AutofillScope? get currentAutofillScope => null;
|
||||
|
||||
@override
|
||||
TextEditingValue? get currentTextEditingValue => _buildTextEditingValue();
|
||||
|
||||
@override
|
||||
void performAction(TextInputAction action) {
|
||||
if (action == TextInputAction.newline) {
|
||||
// Fix issue #42, iOS will insert duplicate new lines.
|
||||
// We only do this on Android.
|
||||
if (kIsAndroid) {
|
||||
_controller.applyNewLine();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void performPrivateCommand(String action, Map<String, dynamic> data) {
|
||||
}
|
||||
|
||||
@override
|
||||
void showAutocorrectionPromptRect(int start, int end) {
|
||||
}
|
||||
|
||||
@override
|
||||
void showToolbar() {
|
||||
}
|
||||
|
||||
@override
|
||||
void insertTextPlaceholder(Size size) {
|
||||
}
|
||||
|
||||
@override
|
||||
void removeTextPlaceholder() {
|
||||
}
|
||||
|
||||
@override
|
||||
void updateEditingValueWithDeltas(List<TextEditingDelta> textEditingDeltas) {
|
||||
if (_updateCausedByFloatingCursor) {
|
||||
// This is necessary because otherwise the content of the line where the floating cursor was started
|
||||
// will be pasted over to the line where the floating cursor was stopped.
|
||||
_updateCausedByFloatingCursor = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (textEditingDeltas.any((delta) => delta is TextEditingDeltaInsertion && delta.textInserted == '\n')) {
|
||||
TextEditingValue newValue = _remoteEditingValue!;
|
||||
for (final TextEditingDelta delta in textEditingDeltas) {
|
||||
newValue = delta.apply(newValue);
|
||||
}
|
||||
_remoteEditingValue = newValue;
|
||||
_controller.applyNewLine();
|
||||
return;
|
||||
}
|
||||
|
||||
// _Trace.begin('updateEditingValue all');
|
||||
TextEditingValue newValue = _remoteEditingValue!;
|
||||
bool smartChange = false;
|
||||
for (final TextEditingDelta delta in textEditingDeltas) {
|
||||
if (_autocompleteSymbols) {
|
||||
TextEditingDelta newDelta = _SmartTextEditingDelta(delta).apply(selection);
|
||||
if (newDelta != delta) {
|
||||
smartChange = true;
|
||||
}
|
||||
newValue = newDelta.apply(newValue);
|
||||
} else {
|
||||
newValue = delta.apply(newValue);
|
||||
}
|
||||
}
|
||||
if (newValue == _remoteEditingValue) {
|
||||
return;
|
||||
}
|
||||
if (!smartChange) {
|
||||
_remoteEditingValue = newValue;
|
||||
}
|
||||
// print('update text ${newValue.text}');
|
||||
// print('update selection ${newValue.selection}');
|
||||
// print('update composing ${newValue.composing}');
|
||||
if (newValue.usePrefix) {
|
||||
if (newValue.selection.isCollapsed && newValue.selection.start == 0) {
|
||||
_controller.deleteBackward();
|
||||
} else {
|
||||
_controller.edit(newValue.removePrefixIfNecessary());
|
||||
}
|
||||
} else {
|
||||
_controller.edit(newValue);
|
||||
}
|
||||
notifyListeners();
|
||||
// _Trace.end('updateEditingValue all');
|
||||
}
|
||||
|
||||
@override
|
||||
void updateEditingValue(TextEditingValue textEditingValue) {
|
||||
}
|
||||
|
||||
@override
|
||||
void updateFloatingCursor(RawFloatingCursorPoint point) {
|
||||
_updateCausedByFloatingCursor = true;
|
||||
final _CodeFieldRender? render = _editorKey?.currentContext?.findRenderObject() as _CodeFieldRender?;
|
||||
if (render == null) {
|
||||
return;
|
||||
}
|
||||
switch(point.state) {
|
||||
case FloatingCursorDragState.Start:
|
||||
_floatingCursorStartingOffset = render.calculateTextPositionViewportOffset(selection.base)!;
|
||||
_floatingCursorController.setFloatingCursorPositions(
|
||||
floatingCursorOffset: _floatingCursorStartingOffset,
|
||||
finalCursorSelection: selection,
|
||||
);
|
||||
break;
|
||||
case FloatingCursorDragState.Update:
|
||||
final Offset updatedOffset = _floatingCursorStartingOffset + point.offset!;
|
||||
|
||||
final double topBound = render.paintBounds.top + render.paddingTop;
|
||||
final double leftBound = render.paintBounds.left + render.paddingLeft;
|
||||
final double bottomBound = render.paintBounds.bottom - render.paddingBottom - render.floatingCursorHeight;
|
||||
final double rightBound = render.paintBounds.right - render.paddingRight;
|
||||
|
||||
// Clamp the offset coordinates to the paint bounds
|
||||
Offset clampedUpdatedOffset = Offset(
|
||||
updatedOffset.dx.clamp(leftBound, rightBound),
|
||||
updatedOffset.dy.clamp(topBound, bottomBound),
|
||||
);
|
||||
|
||||
// An adjustment is made on the y-axis so that whenever it is in between lines, the line where the center
|
||||
// of the floating cursor is will be selected.
|
||||
Offset adjustedClampedUpdatedOffset = clampedUpdatedOffset + Offset(0, render.floatingCursorHeight / 2);
|
||||
final CodeLinePosition newPosition = render.calculateTextPosition(adjustedClampedUpdatedOffset)!;
|
||||
|
||||
// The offset at which the actual cursor would end up if floating cursor was terminated now.
|
||||
final Offset? snappedNewOffset = render.calculateTextPositionViewportOffset(newPosition);
|
||||
|
||||
CodeLineSelection newSelection = CodeLineSelection.fromPosition(position: newPosition);
|
||||
|
||||
|
||||
if (clampedUpdatedOffset != updatedOffset) {
|
||||
// When the cursor is at one of the edges, adjust the starting offset so that the floating cursor
|
||||
// does not get "loose" when starting to move in the opposite direction.
|
||||
_floatingCursorStartingOffset += clampedUpdatedOffset - updatedOffset;
|
||||
}
|
||||
|
||||
if (clampedUpdatedOffset.dy == topBound || clampedUpdatedOffset.dy == bottomBound || clampedUpdatedOffset.dx == rightBound || clampedUpdatedOffset.dx == leftBound) {
|
||||
_floatingCursorScrollTimer ??= Timer.periodic(const Duration(milliseconds: 50), (timer) {
|
||||
render.autoScrollWhenDraggingFloatingCursor(clampedUpdatedOffset);
|
||||
final CodeLinePosition newPos = render.calculateTextPosition(adjustedClampedUpdatedOffset)!;
|
||||
final Offset? snappedNewOffset = render.calculateTextPositionViewportOffset(newPos);
|
||||
|
||||
// This step ensures that the preview cursor will keep updating when scrolling
|
||||
if (adjustedClampedUpdatedOffset.dx > snappedNewOffset!.dx + render.textStyle.fontSize!) {
|
||||
_floatingCursorController.updatePreviewCursorOffset(snappedNewOffset);
|
||||
}
|
||||
else {
|
||||
_floatingCursorController.updatePreviewCursorOffset(null);
|
||||
}
|
||||
});
|
||||
}
|
||||
else {
|
||||
if (_floatingCursorScrollTimer != null) {
|
||||
_floatingCursorScrollTimer!.cancel();
|
||||
_floatingCursorScrollTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Only turn on the preview cursor if we are away from the end of the line (relatively to the font size)
|
||||
if (adjustedClampedUpdatedOffset.dx > snappedNewOffset!.dx + render.textStyle.fontSize!) {
|
||||
_floatingCursorController.setFloatingCursorPositions(
|
||||
floatingCursorOffset: clampedUpdatedOffset,
|
||||
previewCursorOffset: snappedNewOffset,
|
||||
finalCursorOffset: snappedNewOffset,
|
||||
finalCursorSelection:newSelection
|
||||
);
|
||||
}
|
||||
else {
|
||||
_floatingCursorController.setFloatingCursorPositions(
|
||||
floatingCursorOffset: clampedUpdatedOffset,
|
||||
finalCursorOffset: snappedNewOffset,
|
||||
finalCursorSelection: newSelection
|
||||
);
|
||||
}
|
||||
|
||||
break;
|
||||
case FloatingCursorDragState.End:
|
||||
if (_floatingCursorScrollTimer != null) {
|
||||
_floatingCursorScrollTimer!.cancel();
|
||||
_floatingCursorScrollTimer = null;
|
||||
}
|
||||
selection = _floatingCursorController.value.finalCursorSelection!;
|
||||
final CodeLinePosition finalPosition = CodeLinePosition(
|
||||
index: selection.baseIndex,
|
||||
offset: selection.baseOffset,
|
||||
affinity: selection.baseAffinity);
|
||||
|
||||
final Offset? finalOffset = render.calculateTextPositionViewportOffset(finalPosition);
|
||||
|
||||
// If the final selection is in not the viewport, make it visible without animating the floating cursor.
|
||||
// Otherwise, play the floating cursor reset animation.
|
||||
if (finalOffset != null && (finalOffset.dx < 0 || finalOffset.dy < 0)) {
|
||||
render.makePositionCenterIfInvisible(
|
||||
CodeLinePosition(
|
||||
index: selection.baseIndex,
|
||||
offset: selection.baseOffset,
|
||||
affinity: selection.baseAffinity),
|
||||
animated: true);
|
||||
_floatingCursorController.disableFloatingCursor();
|
||||
}
|
||||
else {
|
||||
_floatingCursorController.animateDisableFloatingCursor();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeInputControl(TextInputControl? oldControl, TextInputControl? newControl) {
|
||||
}
|
||||
|
||||
@override
|
||||
void performSelector(String selectorName) {
|
||||
}
|
||||
|
||||
@override
|
||||
void insertContent(KeyboardInsertedContent content) {
|
||||
}
|
||||
|
||||
bool onFocusReceived() => false;
|
||||
|
||||
void ensureInput() {
|
||||
if (_focusNode.hasFocus) {
|
||||
if (!_readOnly) {
|
||||
_openInputConnection();
|
||||
}
|
||||
} else {
|
||||
_focusNode.requestFocus();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void notifyListeners() {
|
||||
// Do nothing here.
|
||||
super.notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
super.dispose();
|
||||
_closeInputConnectionIfNeeded();
|
||||
_controller.removeListener(_onCodeEditingChanged);
|
||||
_focusNode.removeListener(_onFocusChanged);
|
||||
}
|
||||
|
||||
bool get _hasInputConnection => _textInputConnection?.attached ?? false;
|
||||
|
||||
void _onCodeEditingChanged() {
|
||||
_updateRemoteEditingValueIfNeeded();
|
||||
_updateRemoteComposingIfNeeded();
|
||||
}
|
||||
|
||||
void _updateRemoteEditingValueIfNeeded() {
|
||||
if (!_hasInputConnection) {
|
||||
return;
|
||||
}
|
||||
TextEditingValue localValue = _buildTextEditingValue();
|
||||
if (localValue == _remoteEditingValue) {
|
||||
return;
|
||||
}
|
||||
if (localValue.composing.isValid && max(localValue.composing.start, localValue.composing.end) > localValue.text.length) {
|
||||
localValue = localValue.copyWith(
|
||||
composing: TextRange.empty
|
||||
);
|
||||
}
|
||||
// print('post text ${localValue.text}');
|
||||
// print('post selection ${localValue.selection}');
|
||||
// print('post composing ${localValue.composing}');
|
||||
_remoteEditingValue = localValue;
|
||||
|
||||
_textInputConnection!.setEditingState(localValue);
|
||||
}
|
||||
|
||||
void _updateRemoteComposingIfNeeded({
|
||||
bool retry = false
|
||||
}) {
|
||||
if (!_hasInputConnection) {
|
||||
return;
|
||||
}
|
||||
final _CodeFieldRender? render = _editorKey?.currentContext?.findRenderObject() as _CodeFieldRender?;
|
||||
if (render == null) {
|
||||
return;
|
||||
}
|
||||
final Offset? composingStart = render.calculateTextPositionViewportOffset(selection.base.copyWith(
|
||||
offset: _remoteEditingValue?.composing.start
|
||||
));
|
||||
final Offset? composingEnd = render.calculateTextPositionViewportOffset(selection.extent.copyWith(
|
||||
offset: _remoteEditingValue?.composing.end
|
||||
));
|
||||
if (composingStart != null && composingEnd != null) {
|
||||
_textInputConnection!.setComposingRect(Rect.fromPoints(composingStart, composingEnd + Offset(0, render.lineHeight)));
|
||||
}
|
||||
final Offset? caret = render.calculateTextPositionViewportOffset(selection.base) ?? composingStart;
|
||||
if (caret != null) {
|
||||
_textInputConnection!.setCaretRect(Rect.fromLTWH(caret.dx, caret.dy, render.cursorWidth, render.lineHeight));
|
||||
} else if (!retry) {
|
||||
Future.delayed(const Duration(milliseconds: 10), () {
|
||||
_updateRemoteComposingIfNeeded(
|
||||
retry: true
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void _updateRemoteEditableSizeAndTransform() {
|
||||
if (!_hasInputConnection) {
|
||||
return;
|
||||
}
|
||||
final _CodeFieldRender? render = _editorKey?.currentContext?.findRenderObject() as _CodeFieldRender?;
|
||||
if (render == null || !render.hasSize) {
|
||||
return;
|
||||
}
|
||||
_textInputConnection!.setEditableSizeAndTransform(render.size, render.getTransformTo(null));
|
||||
}
|
||||
|
||||
void _onFocusChanged() {
|
||||
_openOrCloseInputConnectionIfNeeded();
|
||||
}
|
||||
|
||||
void _openOrCloseInputConnectionIfNeeded() {
|
||||
if (_focusNode.hasFocus && !_readOnly) {
|
||||
if (_focusNode.consumeKeyboardToken()) {
|
||||
_openInputConnection();
|
||||
}
|
||||
} else {
|
||||
_closeInputConnectionIfNeeded();
|
||||
_controller.clearComposing();
|
||||
}
|
||||
}
|
||||
|
||||
void _openInputConnection() {
|
||||
final BuildContext? context = _editorKey?.currentContext;
|
||||
if (context == null) {
|
||||
return;
|
||||
}
|
||||
if (!_hasInputConnection) {
|
||||
// Fix PlatformException issue on new flutter version.
|
||||
// See https://github.com/reqable/re-editor/issues/83
|
||||
final TextInputConnection connection = TextInput.attach(this,
|
||||
_TextInputConfiguration(
|
||||
flutterViewId: View.maybeOf(context)?.viewId ?? 0,
|
||||
enableDeltaModel: true,
|
||||
inputAction: TextInputAction.newline,
|
||||
autocorrect: false,
|
||||
smartDashesType: SmartDashesType.disabled,
|
||||
smartQuotesType: SmartQuotesType.disabled,
|
||||
textCapitalization: TextCapitalization.none,
|
||||
keyboardAppearance: Theme.of(context).brightness,
|
||||
),
|
||||
);
|
||||
_remoteEditingValue = _buildTextEditingValue();
|
||||
connection.setEditingState(_remoteEditingValue!);
|
||||
connection.show();
|
||||
_textInputConnection = connection;
|
||||
} else {
|
||||
_textInputConnection?.show();
|
||||
}
|
||||
_updateRemoteComposingIfNeeded();
|
||||
_updateRemoteEditableSizeAndTransform();
|
||||
}
|
||||
|
||||
void _closeInputConnectionIfNeeded() {
|
||||
if (_hasInputConnection) {
|
||||
_textInputConnection!.close();
|
||||
}
|
||||
_textInputConnection = null;
|
||||
}
|
||||
|
||||
TextEditingValue _buildTextEditingValue() {
|
||||
final TextSelection textSelection;
|
||||
if (selection.isSameLine) {
|
||||
textSelection = TextSelection(
|
||||
baseOffset: selection.baseOffset,
|
||||
extentOffset: selection.extentOffset
|
||||
);
|
||||
} else {
|
||||
if (selection.baseIndex < selection.extentIndex) {
|
||||
textSelection = TextSelection(
|
||||
baseOffset: selection.baseOffset,
|
||||
extentOffset: codeLines[selection.baseIndex].length
|
||||
);
|
||||
} else {
|
||||
textSelection = TextSelection(
|
||||
baseOffset: 0,
|
||||
extentOffset: selection.baseOffset
|
||||
);
|
||||
}
|
||||
}
|
||||
return TextEditingValue(
|
||||
text: codeLines[selection.baseIndex].text,
|
||||
selection: textSelection,
|
||||
composing: composing
|
||||
).appendPrefixIfNecessary();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class _SmartTextEditingDelta {
|
||||
|
||||
static const List<_ClosureSymbol> _closureSymbols = [
|
||||
_ClosureSymbol('{', '}'),
|
||||
_ClosureSymbol('[', ']'),
|
||||
_ClosureSymbol('(', ')'),
|
||||
];
|
||||
|
||||
static const List<String> _quoteSymbols = [
|
||||
'\'', '"', '`'
|
||||
];
|
||||
|
||||
static const List<_ClosureSymbol> _wrapSymbols = [
|
||||
_ClosureSymbol('{', '}'),
|
||||
_ClosureSymbol('[', ']'),
|
||||
_ClosureSymbol('(', ')'),
|
||||
_ClosureSymbol('\'', '\''),
|
||||
_ClosureSymbol('"', '"'),
|
||||
_ClosureSymbol('`', '`'),
|
||||
];
|
||||
|
||||
final TextEditingDelta _delta;
|
||||
|
||||
_SmartTextEditingDelta(this._delta);
|
||||
|
||||
TextEditingDelta apply(CodeLineSelection selection) {
|
||||
TextEditingDelta delta = _delta;
|
||||
if (delta is TextEditingDeltaInsertion) {
|
||||
delta = _smartInsertion(delta);
|
||||
} else if (delta is TextEditingDeltaReplacement) {
|
||||
delta = _smartReplacement(delta, selection);
|
||||
}
|
||||
return delta;
|
||||
}
|
||||
|
||||
TextEditingDelta _smartInsertion(TextEditingDeltaInsertion delta) {
|
||||
for (final _ClosureSymbol symbol in _closureSymbols) {
|
||||
if (delta.textInserted == symbol.left) {
|
||||
if (!_shouldAutoClosed(delta.oldText, delta.insertionOffset, symbol)) {
|
||||
break;
|
||||
}
|
||||
return TextEditingDeltaInsertion(
|
||||
oldText: delta.oldText,
|
||||
textInserted: symbol.toString(),
|
||||
insertionOffset: delta.insertionOffset,
|
||||
selection: delta.selection,
|
||||
composing: delta.composing,
|
||||
);
|
||||
} else if (delta.textInserted == symbol.right) {
|
||||
if (!_shouldSkipClosed(delta.oldText, delta.insertionOffset, symbol)) {
|
||||
break;
|
||||
}
|
||||
return TextEditingDeltaNonTextUpdate(
|
||||
oldText: delta.oldText,
|
||||
selection: TextSelection.collapsed(
|
||||
offset: delta.insertionOffset + 1
|
||||
),
|
||||
composing: delta.composing
|
||||
);
|
||||
}
|
||||
}
|
||||
for (final String symbol in _quoteSymbols) {
|
||||
if (delta.textInserted != symbol) {
|
||||
continue;
|
||||
}
|
||||
if (!_shouldAutoQuoted(delta.oldText, symbol, delta.insertionOffset)) {
|
||||
break;
|
||||
}
|
||||
return TextEditingDeltaInsertion(
|
||||
oldText: delta.oldText,
|
||||
textInserted: symbol * 2,
|
||||
insertionOffset: delta.insertionOffset,
|
||||
selection: delta.selection,
|
||||
composing: delta.composing,
|
||||
);
|
||||
}
|
||||
return delta;
|
||||
}
|
||||
|
||||
TextEditingDelta _smartReplacement(TextEditingDeltaReplacement delta, CodeLineSelection selection) {
|
||||
if (!selection.isSameLine) {
|
||||
return delta;
|
||||
}
|
||||
if (delta.replacementText.length > 1) {
|
||||
return delta;
|
||||
}
|
||||
final int index = _wrapSymbols.indexWhere((element) => element.left == delta.replacementText);
|
||||
if (index < 0) {
|
||||
return delta;
|
||||
}
|
||||
final _ClosureSymbol symbol = _wrapSymbols[index];
|
||||
return TextEditingDeltaReplacement(
|
||||
oldText: delta.oldText,
|
||||
replacementText: symbol.left + delta.textReplaced + symbol.right,
|
||||
replacedRange: delta.replacedRange,
|
||||
selection: TextSelection(
|
||||
baseOffset: selection.startOffset + 1,
|
||||
extentOffset: selection.endOffset + 1
|
||||
),
|
||||
composing: delta.composing
|
||||
);
|
||||
}
|
||||
|
||||
bool _shouldAutoClosed(String text, int offset, _ClosureSymbol symbol) {
|
||||
final Characters characters = text.characters;
|
||||
if (characters.isEmpty) {
|
||||
return true;
|
||||
}
|
||||
int leftSymbolCount = 0;
|
||||
int rightSymbolCount = 0;
|
||||
for (int i = 0; i < characters.length; i++) {
|
||||
final String character = characters.elementAt(i);
|
||||
if (i <= offset) {
|
||||
if (character == symbol.left) {
|
||||
leftSymbolCount++;
|
||||
} else if (character == symbol.right) {
|
||||
leftSymbolCount--;
|
||||
}
|
||||
} else {
|
||||
if (character == symbol.left) {
|
||||
rightSymbolCount--;
|
||||
} else if (character == symbol.right) {
|
||||
rightSymbolCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
return max(0, leftSymbolCount) >= rightSymbolCount;
|
||||
}
|
||||
|
||||
bool _shouldSkipClosed(String text, int offset, _ClosureSymbol symbol) {
|
||||
if (text.isEmpty) {
|
||||
return false;
|
||||
}
|
||||
if (offset == text.length) {
|
||||
return false;
|
||||
}
|
||||
return text.substring(offset, offset + 1) == symbol.right;
|
||||
}
|
||||
|
||||
bool _shouldAutoQuoted(String text, String symbol, int offset) {
|
||||
final Characters characters = text.characters;
|
||||
if (characters.isEmpty) {
|
||||
return true;
|
||||
}
|
||||
int leftSymbolCount = 0;
|
||||
int rightSymbolCount = 0;
|
||||
for (int i = 0; i < characters.length; i++) {
|
||||
final String character = characters.elementAt(i);
|
||||
if (i < offset) {
|
||||
if (character == symbol) {
|
||||
leftSymbolCount++;
|
||||
}
|
||||
} else {
|
||||
if (character == symbol) {
|
||||
rightSymbolCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (leftSymbolCount == 0 && rightSymbolCount == 0) {
|
||||
return true;
|
||||
}
|
||||
if (rightSymbolCount == 0) {
|
||||
return leftSymbolCount % 2 == 0;
|
||||
}
|
||||
if (leftSymbolCount == 0) {
|
||||
return rightSymbolCount % 2 == 0;
|
||||
}
|
||||
return leftSymbolCount % 2 == rightSymbolCount % 2;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class _ClosureSymbol {
|
||||
final String left;
|
||||
final String right;
|
||||
|
||||
const _ClosureSymbol(this.left, this.right);
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return left + right;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
const String _kPrefix = '\u200b';
|
||||
|
||||
extension _TextEditingValueExtension on TextEditingValue {
|
||||
|
||||
bool get startWithPrefix => text.startsWith(_kPrefix);
|
||||
|
||||
bool get usePrefix => kIsIOS || kIsAndroid;
|
||||
|
||||
TextEditingValue appendPrefixIfNecessary() {
|
||||
if (!usePrefix) {
|
||||
return this;
|
||||
}
|
||||
return copyWith(
|
||||
text: '$_kPrefix$text',
|
||||
selection: selection.copyWith(
|
||||
baseOffset: selection.baseOffset + 1,
|
||||
extentOffset: selection.extentOffset + 1,
|
||||
),
|
||||
composing: composing.isValid ? TextRange(
|
||||
start: composing.start + 1,
|
||||
end: composing.end + 1
|
||||
) : composing
|
||||
);
|
||||
}
|
||||
|
||||
TextEditingValue removePrefixIfNecessary() {
|
||||
if (!usePrefix) {
|
||||
return this;
|
||||
}
|
||||
if (!startWithPrefix) {
|
||||
return this;
|
||||
}
|
||||
return copyWith(
|
||||
text: text.substring(1),
|
||||
selection: selection.copyWith(
|
||||
baseOffset: max(0, selection.baseOffset - 1),
|
||||
extentOffset: max(0, selection.extentOffset - 1),
|
||||
),
|
||||
composing: composing.isValid ? TextRange(
|
||||
start: max(0, composing.start - 1),
|
||||
end: max(0, composing.end - 1)
|
||||
) : null
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class _TextInputConfiguration extends TextInputConfiguration {
|
||||
|
||||
final int flutterViewId;
|
||||
|
||||
const _TextInputConfiguration({
|
||||
required this.flutterViewId,
|
||||
required super.enableDeltaModel,
|
||||
required super.inputAction,
|
||||
super.autocorrect = false,
|
||||
super.smartDashesType = SmartDashesType.disabled,
|
||||
super.smartQuotesType = SmartQuotesType.disabled,
|
||||
super.textCapitalization = TextCapitalization.none,
|
||||
super.keyboardAppearance,
|
||||
});
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
...super.toJson(),
|
||||
'viewId': flutterViewId,
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,36 @@
|
||||
part of re_editor;
|
||||
|
||||
class _CodeLineSegmentQuckLineCount extends CodeLineSegment {
|
||||
|
||||
late int _lineCount;
|
||||
|
||||
_CodeLineSegmentQuckLineCount({
|
||||
required super.codeLines,
|
||||
required super.dirty,
|
||||
}) {
|
||||
_lineCount = super.lineCount;
|
||||
}
|
||||
|
||||
@override
|
||||
int get lineCount => _lineCount;
|
||||
|
||||
@override
|
||||
set length(int newLength) {
|
||||
super.length = newLength;
|
||||
_lineCount = super.lineCount;
|
||||
}
|
||||
|
||||
@override
|
||||
void add(CodeLine element) {
|
||||
super.add(element);
|
||||
_lineCount = super.lineCount;
|
||||
}
|
||||
|
||||
@override
|
||||
void operator []=(int index, CodeLine value) {
|
||||
super[index] = value;
|
||||
_lineCount = super.lineCount;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
part of re_editor;
|
||||
|
||||
class _ParagraphImpl extends IParagraph {
|
||||
|
||||
// Unicode value for a zero width joiner character.
|
||||
static const int _zwjUtf16 = 0x200d;
|
||||
|
||||
final String text;
|
||||
final TextSpan span;
|
||||
final ui.Paragraph paragraph;
|
||||
final bool _trucated;
|
||||
final double _preferredLineHeight;
|
||||
final int _lineCount;
|
||||
|
||||
// For performance, do not init here
|
||||
Map<TextPosition, Offset?>? _offsets;
|
||||
|
||||
_ParagraphImpl({
|
||||
required this.text,
|
||||
required this.span,
|
||||
required this.paragraph,
|
||||
required bool trucated,
|
||||
required double preferredLineHeight,
|
||||
}) : _trucated = trucated,
|
||||
_preferredLineHeight = preferredLineHeight,
|
||||
_lineCount = (paragraph.height / preferredLineHeight).ceil();
|
||||
|
||||
int get runeLength => text.runes.length;
|
||||
|
||||
int? codeUnitAt(int index) {
|
||||
if (index < 0 || index >= length) {
|
||||
return null;
|
||||
}
|
||||
return text.codeUnitAt(index);
|
||||
}
|
||||
|
||||
@override
|
||||
double get width => _applyFloatingPointHack(max(0, paragraph.longestLine));
|
||||
|
||||
@override
|
||||
double get height => lineCount * preferredLineHeight;
|
||||
|
||||
@override
|
||||
double get preferredLineHeight => _preferredLineHeight;
|
||||
|
||||
@override
|
||||
int get length => text.length;
|
||||
|
||||
@override
|
||||
int get lineCount => _lineCount;
|
||||
|
||||
@override
|
||||
bool get trucated => _trucated;
|
||||
|
||||
@override
|
||||
void draw(Canvas canvas, Offset offset) {
|
||||
canvas.drawParagraph(paragraph, offset);
|
||||
}
|
||||
|
||||
@override
|
||||
TextPosition getPosition(Offset offset) {
|
||||
final TextPosition position = paragraph.getPositionForOffset(offset);
|
||||
return position;
|
||||
}
|
||||
|
||||
@override
|
||||
InlineSpan? getSpanForPosition(TextPosition position) {
|
||||
if (position.offset >= length - 1) {
|
||||
return null;
|
||||
}
|
||||
return span.getSpanForPosition(position);
|
||||
}
|
||||
|
||||
@override
|
||||
TextRange getRangeForSpan(InlineSpan span) {
|
||||
int offset = 0;
|
||||
this.span.visitChildren((child) {
|
||||
if (identical(child, span)) {
|
||||
return false;
|
||||
}
|
||||
offset += child.length;
|
||||
return true;
|
||||
});
|
||||
return TextRange(
|
||||
start: offset,
|
||||
end: offset + span.length
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
TextRange getWord(Offset offset) {
|
||||
return paragraph.getWordBoundary(getPosition(offset));
|
||||
}
|
||||
|
||||
@override
|
||||
TextRange getLineBoundary(TextPosition position) {
|
||||
return paragraph.getLineBoundary(position);
|
||||
}
|
||||
|
||||
@override
|
||||
Offset? getOffset(TextPosition position) {
|
||||
Offset? offset = _offsets?[position];
|
||||
if (offset != null) {
|
||||
return offset;
|
||||
}
|
||||
if (text.isEmpty) {
|
||||
return Offset.zero;
|
||||
}
|
||||
if (position.offset == 0) {
|
||||
return Offset.zero;
|
||||
}
|
||||
if (position.affinity == TextAffinity.downstream) {
|
||||
offset = _getOffsetDownstream(position.offset) ?? _getOffsetUpstream(position.offset);
|
||||
} else {
|
||||
offset = _getOffsetUpstream(position.offset) ?? _getOffsetDownstream(position.offset);
|
||||
}
|
||||
(_offsets ??= {})[position] = offset;
|
||||
return offset;
|
||||
}
|
||||
|
||||
@override
|
||||
List<Rect> getRangeRects(TextRange range) {
|
||||
if (text.isEmpty) {
|
||||
return [
|
||||
Rect.fromLTWH(0, 0, 0, _preferredLineHeight)
|
||||
];
|
||||
}
|
||||
if (range.isCollapsed) {
|
||||
return const [];
|
||||
}
|
||||
return paragraph.getBoxesForRange(range.start, range.end, boxHeightStyle: ui.BoxHeightStyle.max).map((e) => e.toRect()).toList();
|
||||
}
|
||||
|
||||
Offset? _getOffsetDownstream(int position) {
|
||||
final int? nextCodeUnit = codeUnitAt(min(position, text.length - 1));
|
||||
if (nextCodeUnit == null) {
|
||||
return null;
|
||||
}
|
||||
// Check for multi-code-unit glyphs such as emojis or zero width joiner.
|
||||
final int graphemeClusterLength = _isUtf16Surrogate(nextCodeUnit) ||
|
||||
_isUnicodeDirectionality(nextCodeUnit) || codeUnitAt(position) == _zwjUtf16 ? 2 : 1;
|
||||
final List<TextBox> boxes = paragraph.getBoxesForRange(position,
|
||||
position + graphemeClusterLength, boxHeightStyle: ui.BoxHeightStyle.strut);
|
||||
if (boxes.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
return Offset(boxes.first.left, boxes.first.top);
|
||||
}
|
||||
|
||||
Offset? _getOffsetUpstream(int position) {
|
||||
final int? prevCodeUnit = codeUnitAt(max(0, position - 1));
|
||||
if (prevCodeUnit == null) {
|
||||
return null;
|
||||
}
|
||||
// Check for multi-code-unit glyphs such as emojis or zero width joiner.
|
||||
final int graphemeClusterLength = _isUtf16Surrogate(prevCodeUnit) ||
|
||||
_isUnicodeDirectionality(prevCodeUnit) || codeUnitAt(position) == _zwjUtf16 ? 2 : 1;
|
||||
final List<TextBox> boxes = paragraph.getBoxesForRange(position - graphemeClusterLength,
|
||||
position, boxHeightStyle: ui.BoxHeightStyle.strut);
|
||||
if (boxes.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
return Offset(boxes.first.right, boxes.first.top);
|
||||
}
|
||||
|
||||
// Returns true if the given value is a valid UTF-16 surrogate. The value
|
||||
// must be a UTF-16 code unit, meaning it must be in the range 0x0000-0xFFFF.
|
||||
//
|
||||
// See also:
|
||||
// * https://en.wikipedia.org/wiki/UTF-16#Code_points_from_U+010000_to_U+10FFFF
|
||||
bool _isUtf16Surrogate(int value) {
|
||||
return value & 0xF800 == 0xD800;
|
||||
}
|
||||
|
||||
// Checks if the glyph is either [Unicode.RLM] or [Unicode.LRM]. These values take
|
||||
// up zero space and do not have valid bounding boxes around them.
|
||||
//
|
||||
// We do not directly use the [Unicode] constants since they are strings.
|
||||
bool _isUnicodeDirectionality(int value) {
|
||||
return value == 0x200F || value == 0x200E;
|
||||
}
|
||||
|
||||
// Unfortunately, using full precision floating point here causes bad layouts
|
||||
// because floating point math isn't associative. If we add and subtract
|
||||
// padding, for example, we'll get different values when we estimate sizes and
|
||||
// when we actually compute layout because the operations will end up associated
|
||||
// differently. To work around this problem for now, we round fractional pixel
|
||||
// values up to the nearest whole pixel value. The right long-term fix is to do
|
||||
// layout using fixed precision arithmetic.
|
||||
double _applyFloatingPointHack(double layoutValue) {
|
||||
return layoutValue.ceilToDouble();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class _CodeParagraphProvider {
|
||||
|
||||
final Map<TextSpan, _ParagraphImpl> _cachedParagraphs;
|
||||
|
||||
ui.TextStyle? _style;
|
||||
ui.ParagraphConstraints? _constraints;
|
||||
ui.ParagraphStyle? _paragraphStyle;
|
||||
double? _preferredLineHeight;
|
||||
int? _maxLengthSingleLineRendering;
|
||||
|
||||
_CodeParagraphProvider() : _cachedParagraphs = {};
|
||||
|
||||
void updateBaseStyle(TextStyle style) {
|
||||
final ui.TextStyle uiStyle = style.getTextStyle();
|
||||
if (uiStyle == _style) {
|
||||
return;
|
||||
}
|
||||
_paragraphStyle = style.getParagraphStyle(
|
||||
textAlign: TextAlign.left,
|
||||
textDirection: TextDirection.ltr,
|
||||
strutStyle: StrutStyle(
|
||||
fontSize: style.fontSize,
|
||||
fontFamily: style.fontFamily,
|
||||
height: style.height,
|
||||
forceStrutHeight: true,
|
||||
)
|
||||
);
|
||||
_style = uiStyle;
|
||||
final TextPainter painter = TextPainter(
|
||||
textDirection: TextDirection.ltr,
|
||||
);
|
||||
painter.text = TextSpan(
|
||||
text: '0',
|
||||
style: style
|
||||
);
|
||||
_preferredLineHeight = painter.preferredLineHeight;
|
||||
clearCache();
|
||||
}
|
||||
|
||||
void updateMaxLengthSingleLineRendering(int? maxLengthSingleLineRendering) {
|
||||
if (_maxLengthSingleLineRendering == maxLengthSingleLineRendering) {
|
||||
return;
|
||||
}
|
||||
_maxLengthSingleLineRendering = maxLengthSingleLineRendering;
|
||||
clearCache();
|
||||
}
|
||||
|
||||
IParagraph build(TextSpan span, double maxWidth) {
|
||||
if (maxWidth != _constraints?.width) {
|
||||
_constraints = ui.ParagraphConstraints(
|
||||
width: maxWidth
|
||||
);
|
||||
clearCache();
|
||||
}
|
||||
final _ParagraphImpl? cache = _cachedParagraphs[span];
|
||||
if (cache != null) {
|
||||
return cache;
|
||||
}
|
||||
final _ParagraphImpl impl;
|
||||
// Trucate the span if it's too long.
|
||||
final String plainText = span.toPlainText();
|
||||
final int? renderingLength = _maxLengthSingleLineRendering;
|
||||
if (renderingLength != null && plainText.length > renderingLength) {
|
||||
impl = _build(trucate(span, renderingLength), plainText.substring(0, renderingLength), true);
|
||||
} else {
|
||||
impl = _build(span, plainText, false);
|
||||
}
|
||||
_cachedParagraphs[span] = impl;
|
||||
return impl;
|
||||
}
|
||||
|
||||
TextSpan trucate(TextSpan span, int maxLength) {
|
||||
int currentLength = 0;
|
||||
TextSpan truncateSpan(TextSpan span) {
|
||||
if (currentLength >= maxLength) {
|
||||
return const TextSpan(text: '');
|
||||
}
|
||||
String? text = span.text;
|
||||
if (text != null) {
|
||||
int remainingLength = maxLength - currentLength;
|
||||
if (text.length > remainingLength) {
|
||||
text = text.substring(0, remainingLength);
|
||||
}
|
||||
currentLength += text.length;
|
||||
return TextSpan(
|
||||
text: text,
|
||||
style: span.style
|
||||
);
|
||||
}
|
||||
final List<InlineSpan> children = [];
|
||||
for (InlineSpan child in span.children ?? const []) {
|
||||
if (currentLength >= maxLength) {
|
||||
break;
|
||||
}
|
||||
if (child is TextSpan) {
|
||||
children.add(truncateSpan(child));
|
||||
} else {
|
||||
children.add(child);
|
||||
}
|
||||
}
|
||||
return TextSpan(
|
||||
children: children,
|
||||
style: span.style
|
||||
);
|
||||
}
|
||||
return truncateSpan(span);
|
||||
}
|
||||
|
||||
void clearCache() {
|
||||
_cachedParagraphs.clear();
|
||||
}
|
||||
|
||||
_ParagraphImpl _build(TextSpan span, String plainText, bool trucated) {
|
||||
final ui.ParagraphStyle? style = _paragraphStyle;
|
||||
if (style == null) {
|
||||
throw AssertionError('Must call updateBaseStyle before build Paragraph.');
|
||||
}
|
||||
final ui.ParagraphBuilder builder = ui.ParagraphBuilder(style);
|
||||
span.build(builder);
|
||||
final ui.Paragraph paragraph = builder.build();
|
||||
paragraph.layout(_constraints!);
|
||||
return _ParagraphImpl(
|
||||
text: plainText,
|
||||
span: span,
|
||||
paragraph: paragraph,
|
||||
trucated: trucated,
|
||||
preferredLineHeight: _preferredLineHeight!,
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
part of re_editor;
|
||||
|
||||
const double _kScrollbarThickness = 8.0;
|
||||
|
||||
class _CodeScrollable extends StatelessWidget {
|
||||
|
||||
final AxisDirection axisDirection;
|
||||
final ScrollController? controller;
|
||||
final ViewportBuilder viewportBuilder;
|
||||
final CodeScrollbarBuilder? scrollbarBuilder;
|
||||
|
||||
const _CodeScrollable({
|
||||
required this.axisDirection,
|
||||
this.controller,
|
||||
required this.viewportBuilder,
|
||||
this.scrollbarBuilder
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scrollable(
|
||||
excludeFromSemantics: true,
|
||||
controller: controller,
|
||||
scrollBehavior: _ScrollBehavior(scrollbarBuilder),
|
||||
viewportBuilder: viewportBuilder,
|
||||
axisDirection: axisDirection,
|
||||
physics: const ClampingScrollPhysics(),
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class _ScrollBehavior extends MaterialScrollBehavior {
|
||||
|
||||
final _ScrollPhysics physics;
|
||||
final CodeScrollbarBuilder? scrollbarBuilder;
|
||||
|
||||
_ScrollBehavior(this.scrollbarBuilder) : physics = _ScrollPhysics();
|
||||
|
||||
@override
|
||||
Widget buildScrollbar(BuildContext context, Widget child, ScrollableDetails details) {
|
||||
final Widget? scrollbar = scrollbarBuilder?.call(context, child, details);
|
||||
if (scrollbar != null) {
|
||||
return scrollbar;
|
||||
}
|
||||
final ScrollbarOrientation? orientation;
|
||||
if (details.direction == AxisDirection.down) {
|
||||
orientation = ScrollbarOrientation.right;
|
||||
} else if (details.direction == AxisDirection.right) {
|
||||
orientation = ScrollbarOrientation.bottom;
|
||||
} else {
|
||||
orientation = null;
|
||||
}
|
||||
if (kIsAndroid || kIsIOS) {
|
||||
return Scrollbar(
|
||||
controller: details.controller,
|
||||
scrollbarOrientation: orientation,
|
||||
thumbVisibility: details.direction == AxisDirection.down,
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
return _RawScrollbar(
|
||||
physics: physics,
|
||||
controller: details.controller ?? ScrollController(),
|
||||
scrollbarOrientation: orientation,
|
||||
thumbVisibility: details.direction == AxisDirection.down,
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
ScrollPhysics getScrollPhysics(BuildContext context) {
|
||||
return physics;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class _RawScrollbar extends RawScrollbar {
|
||||
|
||||
final _ScrollPhysics physics;
|
||||
|
||||
const _RawScrollbar({
|
||||
required this.physics,
|
||||
required Widget child,
|
||||
required ScrollController controller,
|
||||
ScrollbarOrientation? scrollbarOrientation,
|
||||
required bool thumbVisibility,
|
||||
}) : super(
|
||||
controller: controller,
|
||||
scrollbarOrientation: scrollbarOrientation,
|
||||
thumbVisibility: thumbVisibility,
|
||||
thickness: _kScrollbarThickness,
|
||||
radius: const Radius.circular(10),
|
||||
crossAxisMargin: 2,
|
||||
child: child,
|
||||
);
|
||||
|
||||
@override
|
||||
RawScrollbarState<_RawScrollbar> createState() => _RawScrollbarState();
|
||||
|
||||
}
|
||||
|
||||
class _RawScrollbarState extends RawScrollbarState<_RawScrollbar> {
|
||||
|
||||
Offset? downPosition;
|
||||
double? downOffset;
|
||||
|
||||
@override
|
||||
void handleThumbPressStart(ui.Offset localPosition) {
|
||||
downPosition = localPosition;
|
||||
downOffset = widget.controller!.offset;
|
||||
super.handleThumbPressStart(localPosition);
|
||||
}
|
||||
|
||||
@override
|
||||
void handleThumbPressUpdate(Offset localPosition) {
|
||||
if (getScrollbarDirection() == Axis.vertical) {
|
||||
widget.physics.setScrollPosition(downOffset! + scrollbarPainter.getTrackToScroll(localPosition.dy - downPosition!.dy));
|
||||
}
|
||||
super.handleThumbPressUpdate(localPosition);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// ignore: must_be_immutable
|
||||
class _ScrollPhysics extends ScrollPhysics {
|
||||
|
||||
double? _position;
|
||||
|
||||
void setScrollPosition(double position) {
|
||||
_position = position;
|
||||
}
|
||||
|
||||
@override
|
||||
double applyBoundaryConditions(ScrollMetrics position, double value) {
|
||||
if (_position == null) {
|
||||
return super.applyBoundaryConditions(position, value);
|
||||
}
|
||||
return value - _position!;
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,334 @@
|
||||
part of re_editor;
|
||||
|
||||
class _CodeShortcuts extends StatefulWidget {
|
||||
final CodeShortcutsActivatorsBuilder builder;
|
||||
final Widget child;
|
||||
|
||||
const _CodeShortcuts({required this.builder, required this.child});
|
||||
|
||||
@override
|
||||
State<StatefulWidget> createState() => _CodeShortcutsState();
|
||||
}
|
||||
|
||||
class _CodeShortcutsState extends State<_CodeShortcuts> {
|
||||
late final Map<ShortcutActivator, Intent> _shortcuts;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_shortcuts = {};
|
||||
_buildShortcuts();
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(_CodeShortcuts oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.builder != widget.builder) {
|
||||
_buildShortcuts();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Shortcuts(shortcuts: _shortcuts, child: widget.child);
|
||||
}
|
||||
|
||||
void _buildShortcuts() {
|
||||
_shortcuts.clear();
|
||||
for (final CodeShortcutType type in CodeShortcutType.values) {
|
||||
if (type == CodeShortcutType.backspace) {
|
||||
if (kIsAndroid || kIsIOS) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
final List<ShortcutActivator>? activators = widget.builder.build(type);
|
||||
if (activators == null || activators.isEmpty) {
|
||||
continue;
|
||||
}
|
||||
for (final ShortcutActivator activator in activators) {
|
||||
_shortcuts[activator] = kCodeShortcutIntents[type]!;
|
||||
}
|
||||
}
|
||||
// Protect space key go to the IME.
|
||||
_shortcuts.addAll({
|
||||
const SingleActivator(LogicalKeyboardKey.space):
|
||||
const DoNothingAndStopPropagationTextIntent(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class _CodeShortcutActions extends StatelessWidget {
|
||||
final CodeLineEditingController editingController;
|
||||
final _CodeInputController inputController;
|
||||
final CodeFindController? findController;
|
||||
final CodeCommentFormatter? commentFormatter;
|
||||
final Map<Type, Action<Intent>>? overrideActions;
|
||||
final bool readOnly;
|
||||
final Widget child;
|
||||
|
||||
const _CodeShortcutActions({
|
||||
required this.editingController,
|
||||
required this.inputController,
|
||||
this.findController,
|
||||
this.commentFormatter,
|
||||
required this.overrideActions,
|
||||
required this.readOnly,
|
||||
required this.child,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final Map<Type, Action<Intent>> actions = {};
|
||||
for (final Intent intent in kCodeShortcutIntents.values) {
|
||||
// Do not add editable actions when read only.
|
||||
if (intent is CodeShortcutEditableIntent && readOnly) {
|
||||
continue;
|
||||
}
|
||||
if (intent is CodeShortcutEscIntent) {
|
||||
// Do not enable ESC key when nothing the eidtor can do.
|
||||
actions[intent.runtimeType] = _EscCallbackAction(
|
||||
controller: editingController,
|
||||
findController: findController,
|
||||
onInvoke: (intent) {
|
||||
return _onAction(context, intent);
|
||||
},
|
||||
);
|
||||
continue;
|
||||
}
|
||||
actions[intent.runtimeType] = _CompoDoNothingCallbackAction(
|
||||
controller: editingController,
|
||||
onInvoke: (intent) {
|
||||
return _onAction(context, intent);
|
||||
},
|
||||
);
|
||||
}
|
||||
return Actions(actions: {
|
||||
...actions,
|
||||
...{
|
||||
DoNothingAndStopPropagationTextIntent:
|
||||
DoNothingAction(consumesKey: false),
|
||||
},
|
||||
if (overrideActions != null) ...overrideActions!
|
||||
}, child: child);
|
||||
}
|
||||
|
||||
static final Map<Type,
|
||||
void Function(Intent intent, _CodeShortcutActions actions)> actions = {
|
||||
CodeShortcutSelectAllIntent: (intent, actions) {
|
||||
actions.editingController.selectAll();
|
||||
},
|
||||
CodeShortcutLineSelectIntent: (intent, actions) {
|
||||
actions.editingController.selectLines(
|
||||
actions.editingController.selection.baseIndex,
|
||||
actions.editingController.selection.extentIndex);
|
||||
},
|
||||
CodeShortcutCutIntent: (intent, actions) {
|
||||
actions.editingController.cut();
|
||||
},
|
||||
CodeShortcutCopyIntent: (intent, actions) {
|
||||
actions.editingController.copy();
|
||||
},
|
||||
CodeShortcutPasteIntent: (intent, actions) {
|
||||
actions.editingController.paste();
|
||||
},
|
||||
CodeShortcutUndoIntent: (intent, actions) {
|
||||
actions.editingController.undo();
|
||||
},
|
||||
CodeShortcutRedoIntent: (intent, actions) {
|
||||
actions.editingController.redo();
|
||||
},
|
||||
ShortcutLineDeleteIntent: (intent, actions) {
|
||||
actions.editingController.deleteSelectionLines(true);
|
||||
},
|
||||
ShortcutLineDeleteDirectionIntent: (intent, actions) {
|
||||
if ((intent as ShortcutLineDeleteDirectionIntent).forward) {
|
||||
actions.editingController.deleteLineForward();
|
||||
} else {
|
||||
actions.editingController.deleteLineBackward();
|
||||
}
|
||||
},
|
||||
ShortcutLineMoveIntent: (intent, actions) {
|
||||
if ((intent as ShortcutLineMoveIntent).direction ==
|
||||
VerticalDirection.up) {
|
||||
actions.editingController.moveSelectionLinesUp();
|
||||
} else {
|
||||
actions.editingController.moveSelectionLinesDown();
|
||||
}
|
||||
},
|
||||
CodeShortcutIndentIntent: (intent, actions) {
|
||||
actions.editingController.applyIndent();
|
||||
},
|
||||
CodeShortcutOutdentIntent: (intent, actions) {
|
||||
actions.editingController.applyOutdent();
|
||||
},
|
||||
CodeShortcutCommentIntent: (intent, actions) {
|
||||
final CodeLineEditingValue? value = actions.commentFormatter?.format(
|
||||
actions.editingController.value,
|
||||
actions.editingController.options.indent,
|
||||
(intent as CodeShortcutCommentIntent).single);
|
||||
if (value != null) {
|
||||
actions.editingController.runRevocableOp(() {
|
||||
actions.editingController.value = value;
|
||||
});
|
||||
}
|
||||
},
|
||||
CodeShortcutCursorMoveIntent: (intent, actions) {
|
||||
actions.editingController
|
||||
.moveCursor((intent as CodeShortcutCursorMoveIntent).direction);
|
||||
},
|
||||
CodeShortcutCursorMoveLineEdgeIntent: (intent, actions) {
|
||||
if ((intent as CodeShortcutCursorMoveLineEdgeIntent).forward) {
|
||||
actions.editingController.moveCursorToLineEnd();
|
||||
} else {
|
||||
actions.editingController.moveCursorToLineStart();
|
||||
}
|
||||
},
|
||||
CodeShortcutCursorMoveDocEdgeIntent: (intent, actions) {
|
||||
if ((intent as CodeShortcutCursorMoveDocEdgeIntent).forward) {
|
||||
actions.editingController.moveCursorToPageEnd();
|
||||
} else {
|
||||
actions.editingController.moveCursorToPageStart();
|
||||
}
|
||||
},
|
||||
CodeShortcutCursorMovePageIntent: (intent, actions) {
|
||||
if ((intent as CodeShortcutCursorMovePageIntent).forward) {
|
||||
actions.editingController.moveCursorToPageDown();
|
||||
} else {
|
||||
actions.editingController.moveCursorToPageUp();
|
||||
}
|
||||
},
|
||||
CodeShortcutCursorMoveWordBoundaryIntent: (intent, actions) {
|
||||
if ((intent as CodeShortcutCursorMoveWordBoundaryIntent).forward) {
|
||||
actions.editingController.moveCursorToWordBoundaryForward();
|
||||
} else {
|
||||
actions.editingController.moveCursorToWordBoundaryBackward();
|
||||
}
|
||||
},
|
||||
CodeShortcutSelectionExtendIntent: (intent, actions) {
|
||||
actions.editingController.extendSelection(
|
||||
(intent as CodeShortcutSelectionExtendIntent).direction);
|
||||
},
|
||||
CodeShortcutSelectionExtendLineEdgeIntent: (intent, actions) {
|
||||
if ((intent as CodeShortcutSelectionExtendLineEdgeIntent).forward) {
|
||||
actions.editingController.extendSelectionToLineEnd();
|
||||
} else {
|
||||
actions.editingController.extendSelectionToLineStart();
|
||||
}
|
||||
},
|
||||
CodeShortcutSelectionExtendPageEdgeIntent: (intent, actions) {
|
||||
if ((intent as CodeShortcutSelectionExtendPageEdgeIntent).forward) {
|
||||
actions.editingController.extendSelectionToPageEnd();
|
||||
} else {
|
||||
actions.editingController.extendSelectionToPageStart();
|
||||
}
|
||||
},
|
||||
CodeShortcutSelectionExtendWordBoundaryIntent: (intent, actions) {
|
||||
if ((intent as CodeShortcutSelectionExtendWordBoundaryIntent).forward) {
|
||||
actions.editingController.extendSelectionToWordBoundaryForward();
|
||||
} else {
|
||||
actions.editingController.extendSelectionToWordBoundaryBackward();
|
||||
}
|
||||
},
|
||||
ShortcutWordDeleteDirectionIntent: (intent, actions) {
|
||||
if ((intent as ShortcutWordDeleteDirectionIntent).forward) {
|
||||
actions.editingController.deleteWordForward();
|
||||
} else {
|
||||
actions.editingController.deleteWordBackward();
|
||||
}
|
||||
},
|
||||
CodeShortcutDeleteIntent: (intent, actions) {
|
||||
if ((intent as CodeShortcutDeleteIntent).forward) {
|
||||
actions.editingController.deleteForward();
|
||||
} else {
|
||||
actions.editingController.deleteBackward();
|
||||
}
|
||||
actions.inputController.notifyListeners();
|
||||
},
|
||||
CodeShortcutNewLineIntent: (intent, actions) {
|
||||
actions.editingController.applyNewLine();
|
||||
},
|
||||
CodeShortcutTransposeCharactersIntent: (intent, actions) {
|
||||
actions.editingController.transposeCharacters();
|
||||
},
|
||||
CodeShortcutFindIntent: (intent, actions) {
|
||||
actions.findController?.findMode();
|
||||
},
|
||||
CodeShortcutFindToggleMatchCaseIntent: (intent, actions) {
|
||||
actions.findController?.toggleCaseSensitive();
|
||||
},
|
||||
CodeShortcutFindToggleRegexIntent: (intent, actions) {
|
||||
actions.findController?.toggleRegex();
|
||||
},
|
||||
CodeShortcutReplaceIntent: (intent, actions) {
|
||||
actions.findController?.replaceMode();
|
||||
},
|
||||
CodeShortcutEscIntent: (intent, actions) {
|
||||
if (actions.findController?.value != null) {
|
||||
actions.findController?.close();
|
||||
} else {
|
||||
actions.editingController.cancelSelection();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Object? _onAction(BuildContext context, Intent intent) {
|
||||
final Action<Intent>? action = Actions.maybeFind(context, intent: intent);
|
||||
if (action != null &&
|
||||
action.isActionEnabled &&
|
||||
action.consumesKey(intent)) {
|
||||
if (action is CallbackAction) {
|
||||
action.invoke(intent);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (intent is CodeShortcutEditableIntent && readOnly) {
|
||||
return null;
|
||||
}
|
||||
if (editingController.isComposing) {
|
||||
return null;
|
||||
}
|
||||
bool keepAutoCompleteState = intent is CodeShortcutDeleteIntent;
|
||||
final handler = actions[intent.runtimeType];
|
||||
if (handler != null) {
|
||||
handler(intent, this);
|
||||
}
|
||||
if (!keepAutoCompleteState) {
|
||||
final _CodeAutocompleteState? autocompleteState =
|
||||
context.findAncestorStateOfType<_CodeAutocompleteState>();
|
||||
autocompleteState?.dismiss();
|
||||
}
|
||||
return intent;
|
||||
}
|
||||
}
|
||||
|
||||
class _CompoDoNothingCallbackAction<T extends Intent>
|
||||
extends CallbackAction<T> {
|
||||
final CodeLineEditingController controller;
|
||||
|
||||
_CompoDoNothingCallbackAction({
|
||||
required this.controller,
|
||||
required super.onInvoke,
|
||||
});
|
||||
|
||||
@override
|
||||
bool consumesKey(T intent) {
|
||||
return !controller.isComposing;
|
||||
}
|
||||
}
|
||||
|
||||
class _EscCallbackAction<T extends Intent> extends CallbackAction<T> {
|
||||
final CodeLineEditingController controller;
|
||||
final CodeFindController? findController;
|
||||
|
||||
_EscCallbackAction({
|
||||
required this.controller,
|
||||
required this.findController,
|
||||
required super.onInvoke,
|
||||
});
|
||||
|
||||
@override
|
||||
bool isEnabled(T intent) {
|
||||
return !controller.isComposing &&
|
||||
(findController?.value != null || !controller.selection.isCollapsed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
part of re_editor;
|
||||
|
||||
@immutable
|
||||
class _MouseTrackerAnnotationTextSpan extends TextSpan {
|
||||
|
||||
final int id;
|
||||
final MouseTrackerAnnotationTextSpan span;
|
||||
final List<Rect> rects;
|
||||
|
||||
const _MouseTrackerAnnotationTextSpan({
|
||||
required this.id,
|
||||
required this.rects,
|
||||
required this.span,
|
||||
});
|
||||
|
||||
@override
|
||||
PointerEnterEventListener? get onEnter => (event) {
|
||||
span.onEnterWithRect(event, id, rects);
|
||||
};
|
||||
|
||||
@override
|
||||
PointerExitEventListener? get onExit => (event) {
|
||||
span.onExitWithRect(event, id, rects);
|
||||
};
|
||||
|
||||
@override
|
||||
int get hashCode => span.hashCode;
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
if (identical(this, other)) {
|
||||
return true;
|
||||
}
|
||||
return other is _MouseTrackerAnnotationTextSpan && span == other.span &&
|
||||
id == other.id;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
part of re_editor;
|
||||
|
||||
final kIsMacOS = defaultTargetPlatform == TargetPlatform.macOS;
|
||||
final kIsAndroid = defaultTargetPlatform == TargetPlatform.android;
|
||||
final kIsIOS = defaultTargetPlatform == TargetPlatform.iOS;
|
||||
@@ -0,0 +1,38 @@
|
||||
part of re_editor;
|
||||
|
||||
typedef IsolateRunnable<Req, Res> = Res Function(Req req);
|
||||
typedef IsolateCallback<Res> = void Function(Res res);
|
||||
|
||||
class _IsolateTasker<Req, Res> {
|
||||
final String name;
|
||||
late bool _closed;
|
||||
|
||||
late IsolateManager<Res, Req>? _isolateManager;
|
||||
|
||||
_IsolateTasker(this.name, IsolateRunnable<Req, Res> runnable) {
|
||||
_closed = false;
|
||||
_isolateManager = IsolateManager.create(
|
||||
runnable,
|
||||
concurrent: 1, // one is enough
|
||||
);
|
||||
}
|
||||
|
||||
void run(Req req, IsolateCallback<Res> callback) async {
|
||||
if (_closed) {
|
||||
return;
|
||||
}
|
||||
_isolateManager?.compute(req, callback: (message) async {
|
||||
if (_closed) {
|
||||
return false;
|
||||
}
|
||||
callback(message);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
void close() {
|
||||
_closed = true;
|
||||
_isolateManager?.stop();
|
||||
_isolateManager = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
part of re_editor;
|
||||
|
||||
/// Define code autocomplate prompt information.
|
||||
///
|
||||
/// See also [CodeKeywordPrompt], [CodeFieldPrompt] and [CodeFunctionPrompt].
|
||||
abstract class CodePrompt {
|
||||
|
||||
const CodePrompt({
|
||||
required this.word
|
||||
});
|
||||
|
||||
/// Content associated with user input.
|
||||
///
|
||||
/// e.g. User input is 're', the prompt word 'return' will be displayed to user.
|
||||
final String word;
|
||||
|
||||
/// Get the final auto completion content. In most cases it is equal to [word], but there are some exceptions.
|
||||
/// For example, for functions, auto completion of parameters may be required.
|
||||
///
|
||||
/// e.g. User input is 'he', 'hello(String name)' will be auto completed.
|
||||
CodeAutocompleteResult get autocomplete;
|
||||
|
||||
/// Check whether the input meets this prompt condition.
|
||||
bool match(String input);
|
||||
|
||||
}
|
||||
|
||||
/// The keyword autocomplate prompt. such as 'return', 'class', 'new' and so on.
|
||||
class CodeKeywordPrompt extends CodePrompt {
|
||||
|
||||
const CodeKeywordPrompt({
|
||||
required super.word
|
||||
});
|
||||
|
||||
@override
|
||||
CodeAutocompleteResult get autocomplete => CodeAutocompleteResult.fromWord(word);
|
||||
|
||||
@override
|
||||
bool match(String input) {
|
||||
return word != input && word.startsWith(input);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
if (identical(this, other)) {
|
||||
return true;
|
||||
}
|
||||
return other is CodeKeywordPrompt && other.word == word;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode => word.hashCode;
|
||||
|
||||
}
|
||||
|
||||
/// The field autocomplate prompt. Compared to [CodeKeywordPrompt],
|
||||
/// type definitions also need to be provided.
|
||||
///
|
||||
/// If a line of code is 'String foo;', 'foo' is the word and 'String' is the type.
|
||||
class CodeFieldPrompt extends CodePrompt {
|
||||
|
||||
const CodeFieldPrompt({
|
||||
required super.word,
|
||||
required this.type,
|
||||
this.customAutocomplete,
|
||||
});
|
||||
|
||||
/// The field type name.
|
||||
final String type;
|
||||
|
||||
/// Will use custom autocomplete rather than word if this is not null.
|
||||
final CodeAutocompleteResult? customAutocomplete;
|
||||
|
||||
@override
|
||||
CodeAutocompleteResult get autocomplete => customAutocomplete ?? CodeAutocompleteResult.fromWord(word);
|
||||
|
||||
@override
|
||||
bool match(String input) {
|
||||
return word != input && word.startsWith(input);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
if (identical(this, other)) {
|
||||
return true;
|
||||
}
|
||||
return other is CodeFieldPrompt && other.word == word && other.type == type
|
||||
&& other.customAutocomplete == customAutocomplete;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(word, type, customAutocomplete);
|
||||
|
||||
}
|
||||
|
||||
/// The function autocomplate prompt.
|
||||
class CodeFunctionPrompt extends CodePrompt {
|
||||
|
||||
const CodeFunctionPrompt({
|
||||
required super.word,
|
||||
required this.type,
|
||||
this.parameters = const {},
|
||||
this.optionalParameters = const {},
|
||||
this.customAutocomplete,
|
||||
});
|
||||
|
||||
/// The function return type.
|
||||
final String type;
|
||||
|
||||
/// The function required parameters.
|
||||
final Map<String, String> parameters;
|
||||
|
||||
/// The function optional parameters.
|
||||
final Map<String, String> optionalParameters;
|
||||
|
||||
/// Will use custom autocomplete rather than word if this is not null.
|
||||
final CodeAutocompleteResult? customAutocomplete;
|
||||
|
||||
@override
|
||||
CodeAutocompleteResult get autocomplete => customAutocomplete ?? CodeAutocompleteResult.fromWord('$word(${parameters.keys.join(', ')})');
|
||||
|
||||
@override
|
||||
bool match(String input) {
|
||||
return word != input && word.startsWith(input);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
if (identical(this, other)) {
|
||||
return true;
|
||||
}
|
||||
return other is CodeFunctionPrompt && other.word == word && other.type == type &&
|
||||
mapEquals(other.parameters, parameters) && mapEquals(other.optionalParameters, optionalParameters)
|
||||
&& other.customAutocomplete == customAutocomplete;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(word, type, parameters, optionalParameters, customAutocomplete);
|
||||
|
||||
}
|
||||
|
||||
/// The autocomplete result selected by user, the editor will apply this
|
||||
/// to code content.
|
||||
class CodeAutocompleteResult {
|
||||
|
||||
const CodeAutocompleteResult({
|
||||
required this.input,
|
||||
required this.word,
|
||||
required this.selection
|
||||
});
|
||||
|
||||
factory CodeAutocompleteResult.fromWord(String word) {
|
||||
return CodeAutocompleteResult(
|
||||
input: '',
|
||||
word: word,
|
||||
selection: TextSelection.collapsed(
|
||||
offset: word.length
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/// The autocomplete text.
|
||||
/// e.g.
|
||||
/// If user inputs `go` and the word is `good`, we will replace `go` with `good`.
|
||||
final String input;
|
||||
final String word;
|
||||
|
||||
/// The new selection after the autocompletion.
|
||||
final TextSelection selection;
|
||||
|
||||
}
|
||||
|
||||
/// The current user input and prompts for editing a run of text.
|
||||
class CodeAutocompleteEditingValue {
|
||||
|
||||
const CodeAutocompleteEditingValue({
|
||||
required this.input,
|
||||
required this.prompts,
|
||||
required this.index,
|
||||
});
|
||||
|
||||
/// User input content.
|
||||
final String input;
|
||||
|
||||
/// Matched code prompts.
|
||||
final List<CodePrompt> prompts;
|
||||
|
||||
/// Current selected code prompt.
|
||||
final int index;
|
||||
|
||||
CodeAutocompleteEditingValue copyWith({
|
||||
String? input,
|
||||
List<CodePrompt>? prompts,
|
||||
int? index,
|
||||
}) {
|
||||
return CodeAutocompleteEditingValue(
|
||||
input: input ?? this.input,
|
||||
prompts: prompts ?? this.prompts,
|
||||
index: index ?? this.index,
|
||||
);
|
||||
}
|
||||
|
||||
CodeAutocompleteResult get autocomplete {
|
||||
final CodeAutocompleteResult result = prompts[index].autocomplete;
|
||||
if (result.word.isEmpty) {
|
||||
return result;
|
||||
}
|
||||
final TextSelection finalSelection = result.selection.copyWith(
|
||||
baseOffset: result.selection.baseOffset - input.length,
|
||||
extentOffset: result.selection.extentOffset - input.length,
|
||||
);
|
||||
return CodeAutocompleteResult(
|
||||
input: input,
|
||||
word: result.word,
|
||||
selection: finalSelection,
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// Builds the overlay autocomplete prompts view.
|
||||
typedef CodeAutocompleteWidgetBuilder = PreferredSizeWidget Function(
|
||||
BuildContext context,
|
||||
ValueNotifier<CodeAutocompleteEditingValue> notifier,
|
||||
ValueChanged<CodeAutocompleteResult> onSelected
|
||||
);
|
||||
|
||||
/// The autocomplete prompts builder.
|
||||
abstract class CodeAutocompletePromptsBuilder {
|
||||
|
||||
/// Build the prompts with the current code.
|
||||
CodeAutocompleteEditingValue? build(
|
||||
BuildContext context,
|
||||
CodeLine codeLine,
|
||||
CodeLineSelection selection,
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
/// The default autocomplete prompts builder.
|
||||
abstract class DefaultCodeAutocompletePromptsBuilder implements CodeAutocompletePromptsBuilder {
|
||||
|
||||
/// Constructs the builder with defined prompts.
|
||||
factory DefaultCodeAutocompletePromptsBuilder({
|
||||
Mode? language,
|
||||
List<CodeKeywordPrompt> keywordPrompts = const [],
|
||||
List<CodePrompt> directPrompts = const [],
|
||||
Map<String, List<CodePrompt>> relatedPrompts = const {},
|
||||
}) => _DefaultCodeAutocompletePromptsBuilder(
|
||||
language: language,
|
||||
keywordPrompts: keywordPrompts,
|
||||
directPrompts: directPrompts,
|
||||
relatedPrompts: relatedPrompts,
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
/// A widget enables code autocomplete for [CodeEditor].
|
||||
///
|
||||
/// Developers can customize the view styles and prompt logic they need.
|
||||
///
|
||||
/// The following is a common usage.
|
||||
///
|
||||
/// ```
|
||||
/// CodeAutocomplete(
|
||||
/// viewBuilder: (context, notifier, onSelected) {
|
||||
/// // TODO build the options list widget.
|
||||
/// },
|
||||
/// promptsBuilder: DefaultCodeAutocompletePromptsBuilder(
|
||||
/// language: langDart,
|
||||
/// directPrompts: [
|
||||
/// CodeFieldPrompt(
|
||||
/// word: 'foo',
|
||||
/// type: 'String'
|
||||
/// ),
|
||||
/// CodeFunctionPrompt(
|
||||
/// word: 'hello',
|
||||
/// type: 'void',
|
||||
/// parameters: {
|
||||
/// 'value': 'String',
|
||||
/// }
|
||||
/// )
|
||||
/// ],
|
||||
/// ),
|
||||
/// child: CodeEditor()
|
||||
/// )
|
||||
/// ```
|
||||
class CodeAutocomplete extends StatelessWidget {
|
||||
|
||||
const CodeAutocomplete({
|
||||
super.key,
|
||||
required this.viewBuilder,
|
||||
required this.promptsBuilder,
|
||||
required this.child,
|
||||
});
|
||||
|
||||
final CodeAutocompleteWidgetBuilder viewBuilder;
|
||||
final CodeAutocompletePromptsBuilder promptsBuilder;
|
||||
final Widget child;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return _CodeAutocomplete(
|
||||
viewBuilder: viewBuilder,
|
||||
promptsBuilder: promptsBuilder,
|
||||
child: child
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
part of re_editor;
|
||||
|
||||
class CodeChunkController extends ValueNotifier<List<CodeChunk>> {
|
||||
|
||||
late final CodeLineEditingController _controller;
|
||||
final CodeChunkAnalyzer _analyzer;
|
||||
|
||||
late final _IsolateTasker<_CodeChunkAnalyzePayload, _CodeChunkAnalyzeResult> _tasker;
|
||||
|
||||
late bool _shouldNotUpdateChunks;
|
||||
|
||||
CodeChunkController(CodeLineEditingController controller, this._analyzer) : super(const []) {
|
||||
_controller = controller is _CodeLineEditingControllerDelegate ? controller.delegate : controller;
|
||||
_controller.addListener(_onCodeChanged);
|
||||
_tasker = _IsolateTasker<_CodeChunkAnalyzePayload, _CodeChunkAnalyzeResult>('CodeChunk', _run);
|
||||
_shouldNotUpdateChunks = false;
|
||||
_runChunkAnalyzeTask();
|
||||
}
|
||||
|
||||
void collapse(int index) {
|
||||
final CodeChunk? chunk = findByIndex(index);
|
||||
if (chunk == null) {
|
||||
// Not support to collapse
|
||||
return;
|
||||
}
|
||||
if (!chunk.canCollapse) {
|
||||
// Has collapsed or nothing to collapse
|
||||
return;
|
||||
}
|
||||
final List<CodeChunk> codeChunks = List.of(value);
|
||||
// Remove sub chunks
|
||||
codeChunks.removeWhere((e) => e.index > chunk.index && e.end < chunk.end);
|
||||
// Chunks after the collapsed should adjust the offset
|
||||
for (int i = 0; i < codeChunks.length; i++) {
|
||||
final CodeChunk e = codeChunks[i];
|
||||
if (e.index >= index || e.end >= index) {
|
||||
codeChunks[i] = CodeChunk(e.index > index ? e.index - chunk.collapseSize : e.index,
|
||||
e.end > index ? e.end - chunk.collapseSize : e.end
|
||||
);
|
||||
}
|
||||
}
|
||||
value = codeChunks;
|
||||
_shouldNotUpdateChunks = true;
|
||||
_controller.collapseChunk(chunk.index, chunk.end);
|
||||
_shouldNotUpdateChunks = false;
|
||||
}
|
||||
|
||||
void expand(int index) {
|
||||
final CodeLine codeLine = _controller.codeLines[index];
|
||||
if (!codeLine.chunkParent) {
|
||||
// Nothing to expand, this should not happen.
|
||||
return;
|
||||
}
|
||||
final List<CodeChunk> codeChunks = List.of(value);
|
||||
bool exists = false;
|
||||
for (int i = 0; i < codeChunks.length; i++) {
|
||||
final CodeChunk e = codeChunks[i];
|
||||
if (e.index >= index || e.end >= index) {
|
||||
codeChunks[i] = CodeChunk(e.index > index ? e.index + codeLine.chunks.length : e.index,
|
||||
e.end > index ? e.end + codeLine.chunks.length : e.end
|
||||
);
|
||||
}
|
||||
if (e.index == index) {
|
||||
exists = true;
|
||||
}
|
||||
}
|
||||
// Add self into the chunks if not exists
|
||||
if (!exists) {
|
||||
codeChunks.add(CodeChunk(index, index + codeLine.chunks.length + 1));
|
||||
// sort by index
|
||||
codeChunks.sort((a, b) => a.index - b.index);
|
||||
}
|
||||
value = codeChunks;
|
||||
_controller.expandChunk(index);
|
||||
}
|
||||
|
||||
void toggle(int index) {
|
||||
if (_controller.codeLines[index].chunkParent) {
|
||||
expand(index);
|
||||
} else {
|
||||
collapse(index);
|
||||
}
|
||||
}
|
||||
|
||||
CodeChunk? findByIndex(int index) {
|
||||
for (final CodeChunk chunk in value) {
|
||||
if (chunk.index == index) {
|
||||
return chunk;
|
||||
} else if (chunk.index > index) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
bool canCollapse(int index) {
|
||||
return findByIndex(index)?.canCollapse ?? false;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.removeListener(_onCodeChanged);
|
||||
_tasker.close();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _onCodeChanged() {
|
||||
if (_shouldNotUpdateChunks) {
|
||||
return;
|
||||
}
|
||||
if (_controller.codeLines.length < 3 && value.isEmpty) {
|
||||
value = [];
|
||||
return;
|
||||
}
|
||||
if (_controller.codeLines.equals(_controller.preValue?.codeLines)) {
|
||||
return;
|
||||
}
|
||||
_runChunkAnalyzeTask();
|
||||
}
|
||||
|
||||
void _runChunkAnalyzeTask() {
|
||||
final CodeLines codeLines = _controller.codeLines;
|
||||
_tasker.run(_CodeChunkAnalyzePayload(_analyzer, codeLines), (result) {
|
||||
if (_controller.codeLines.equals(codeLines)) {
|
||||
value = result.chunks;
|
||||
_expandInvalidCollapsedChunks(result.invalidCollapsedChunkIndexes);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void _expandInvalidCollapsedChunks(List<int> indexes) {
|
||||
// Expand invalid chunks from bottom to top
|
||||
for (int i = indexes.length - 1; i >=0; i--) {
|
||||
expand(indexes[i]);
|
||||
}
|
||||
}
|
||||
|
||||
@pragma('vm:entry-point')
|
||||
static _CodeChunkAnalyzeResult _run(_CodeChunkAnalyzePayload payload) {
|
||||
final List<CodeChunk> chunks = payload.analyzer.run(payload.codeLines);
|
||||
final List<int> invalidCollapsedChunkIndexes = [];
|
||||
for (int i = 0; i < payload.codeLines.length; i++) {
|
||||
if (!payload.codeLines[i].chunkParent) {
|
||||
continue;
|
||||
}
|
||||
final int index = chunks.indexWhere((e) => e.index == i);
|
||||
if (index < 0 || chunks[index].canCollapse) {
|
||||
invalidCollapsedChunkIndexes.add(i);
|
||||
}
|
||||
}
|
||||
return _CodeChunkAnalyzeResult(chunks, invalidCollapsedChunkIndexes);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class CodeChunk {
|
||||
|
||||
final int index;
|
||||
final int end;
|
||||
|
||||
const CodeChunk(this.index, this.end);
|
||||
|
||||
bool get canCollapse => collapseSize > 0;
|
||||
|
||||
int get collapseSize => end - index - 1;
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
if (identical(this, other)) {
|
||||
return true;
|
||||
}
|
||||
return other is CodeChunk
|
||||
&& other.index == index
|
||||
&& other.end == end;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(index, end);
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return '[$index, $end]';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
abstract class CodeChunkAnalyzer {
|
||||
|
||||
List<CodeChunk> run(CodeLines codeLines);
|
||||
|
||||
}
|
||||
|
||||
class NonCodeChunkAnalyzer implements CodeChunkAnalyzer {
|
||||
|
||||
const NonCodeChunkAnalyzer();
|
||||
|
||||
@override
|
||||
List<CodeChunk> run(CodeLines codeLines) => const [];
|
||||
|
||||
}
|
||||
|
||||
class DefaultCodeChunkAnalyzer implements CodeChunkAnalyzer {
|
||||
|
||||
static const Map<String, String> _chunkSymbols = {
|
||||
'(': ')',
|
||||
'[': ']',
|
||||
'{': '}'
|
||||
};
|
||||
static final List<int> _tokens = '"\'()[]{}'.codeUnits;
|
||||
|
||||
const DefaultCodeChunkAnalyzer();
|
||||
|
||||
@override
|
||||
List<CodeChunk> run(CodeLines codeLines) {
|
||||
final List<CodeChunk> chunks = [];
|
||||
final List<CodeChunkSymbol> stack = [];
|
||||
final List<CodeChunkSymbol> chunkSymbols = parse(codeLines);
|
||||
for (final CodeChunkSymbol symbol in chunkSymbols) {
|
||||
if (_chunkSymbols.keys.contains(symbol.value)) {
|
||||
stack.add(symbol);
|
||||
continue;
|
||||
}
|
||||
while(stack.isNotEmpty) {
|
||||
final CodeChunkSymbol pop = stack.removeLast();
|
||||
if (_chunkSymbols[pop.value] == symbol.value) {
|
||||
if (symbol.index - pop.index >= 1 && chunks.where((e) => e.index == pop.index).isEmpty) {
|
||||
chunks.add(CodeChunk(pop.index, symbol.index));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// sort by index
|
||||
chunks.sort((a, b) => a.index - b.index);
|
||||
return chunks;
|
||||
}
|
||||
|
||||
@visibleForTesting
|
||||
List<CodeChunkSymbol> parse(CodeLines codeLines) {
|
||||
final List<CodeChunkSymbol> symbols = [];
|
||||
for (int i = 0; i < codeLines.length; i++) {
|
||||
final String text = codeLines[i].text.trim();
|
||||
if (text.isEmpty) {
|
||||
continue;
|
||||
}
|
||||
symbols.addAll(_parseLine(text, i));
|
||||
}
|
||||
return symbols;
|
||||
}
|
||||
|
||||
List<CodeChunkSymbol> _parseLine(String text, int index) {
|
||||
final List<CodeChunkSymbol> symbols = [];
|
||||
const int normal = 0;
|
||||
const int inQuote = 1;
|
||||
const int inDoubleQuote = 2;
|
||||
bool inEscapeQuote = false;
|
||||
bool inEscapeDoubleQuote = false;
|
||||
int state = normal;
|
||||
final List<int> codeUnits = text.codeUnits;
|
||||
for (int i = 0; i < codeUnits.length; i++) {
|
||||
if (!_tokens.contains(codeUnits[i])) {
|
||||
continue;
|
||||
}
|
||||
final String character = String.fromCharCode(codeUnits[i]);
|
||||
if (state == inQuote) {
|
||||
if (character == '\'' && !isPreEscapeChar(codeUnits, i)) {
|
||||
state = normal;
|
||||
}
|
||||
} else if (state == inDoubleQuote) {
|
||||
if (character == '"' && !isPreEscapeChar(codeUnits, i)) {
|
||||
state = normal;
|
||||
}
|
||||
} else {
|
||||
if (character == '\'') {
|
||||
if (inEscapeQuote) {
|
||||
if (isPreEscapeChar(codeUnits, i)) {
|
||||
inEscapeQuote = false;
|
||||
} else {
|
||||
// Unbalanced escape quotes
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
if (isPreEscapeChar(codeUnits, i)) {
|
||||
inEscapeQuote = true;
|
||||
} else {
|
||||
state = inQuote;
|
||||
}
|
||||
}
|
||||
} else if (character == '"') {
|
||||
if (inEscapeDoubleQuote) {
|
||||
if (isPreEscapeChar(codeUnits, i)) {
|
||||
inEscapeDoubleQuote = false;
|
||||
} else {
|
||||
// Unbalanced escape double quotes
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
if (isPreEscapeChar(codeUnits, i)) {
|
||||
inEscapeDoubleQuote = true;
|
||||
} else {
|
||||
state = inDoubleQuote;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (!inEscapeQuote && !inEscapeDoubleQuote) {
|
||||
symbols.add(CodeChunkSymbol(character, index));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return symbols;
|
||||
}
|
||||
|
||||
bool isPreEscapeChar(List<int> codeUnits, int index) {
|
||||
return index > 0 && codeUnits[index - 1] == '\\'.codeUnits.first;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class CodeChunkSymbol {
|
||||
|
||||
final String value;
|
||||
final int index;
|
||||
|
||||
const CodeChunkSymbol(this.value, this.index);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
if (identical(this, other)) {
|
||||
return true;
|
||||
}
|
||||
return other is CodeChunkSymbol
|
||||
&& other.value == value
|
||||
&& other.index == index;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(value, index);
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return '$value@$index';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class _CodeChunkAnalyzePayload {
|
||||
|
||||
final CodeChunkAnalyzer analyzer;
|
||||
final CodeLines codeLines;
|
||||
|
||||
const _CodeChunkAnalyzePayload(this.analyzer, this.codeLines);
|
||||
|
||||
}
|
||||
|
||||
class _CodeChunkAnalyzeResult {
|
||||
|
||||
final List<CodeChunk> chunks;
|
||||
final List<int> invalidCollapsedChunkIndexes;
|
||||
|
||||
const _CodeChunkAnalyzeResult(this.chunks, this.invalidCollapsedChunkIndexes);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,641 @@
|
||||
part of re_editor;
|
||||
|
||||
/// An immutable style describing how to format and paint editor content.
|
||||
class CodeEditorStyle {
|
||||
|
||||
/// Creates a code editor style.
|
||||
const CodeEditorStyle({
|
||||
this.fontSize,
|
||||
this.fontFamily,
|
||||
this.fontFamilyFallback,
|
||||
this.fontHeight,
|
||||
this.textColor,
|
||||
this.hintTextColor,
|
||||
this.backgroundColor,
|
||||
this.selectionColor,
|
||||
this.highlightColor,
|
||||
this.cursorColor,
|
||||
this.cursorWidth,
|
||||
this.cursorLineColor,
|
||||
this.chunkIndicatorColor,
|
||||
this.codeTheme,
|
||||
}) : assert(fontSize == null || fontSize > 0),
|
||||
assert(fontHeight == null || fontHeight >= 1.0),
|
||||
assert(cursorWidth == null || cursorWidth > 0);
|
||||
|
||||
/// The size of fonts (in logical pixels) to use when painting the text.
|
||||
///
|
||||
/// The value specified matches the dimension of the
|
||||
/// [em square](https://fonts.google.com/knowledge/glossary/em) of the
|
||||
/// underlying font, and more often then not isn't exactly the height or the
|
||||
/// width of glyphs in the font.
|
||||
///
|
||||
/// Default value is 13.0 pixels.
|
||||
final double? fontSize;
|
||||
|
||||
/// The name of the font to use when painting the text (e.g., Roboto).
|
||||
///
|
||||
/// If the font is defined in a package, this will be prefixed with
|
||||
/// 'packages/package_name/' (e.g. 'packages/cool_fonts/Roboto'). The
|
||||
/// prefixing is done by the constructor when the `package` argument is
|
||||
/// provided.
|
||||
///
|
||||
/// The value provided in [fontFamily] will act as the preferred/first font
|
||||
/// family that glyphs are looked for in, followed in order by the font families
|
||||
/// in [fontFamilyFallback]. When [fontFamily] is null or not provided, the
|
||||
/// first value in [fontFamilyFallback] acts as the preferred/first font
|
||||
/// family. When neither is provided, then the default platform font will
|
||||
/// be used.
|
||||
final String? fontFamily;
|
||||
|
||||
/// The ordered list of font families to fall back on when a glyph cannot be
|
||||
/// found in a higher priority font family.
|
||||
///
|
||||
/// The value provided in [fontFamily] will act as the preferred/first font
|
||||
/// family that glyphs are looked for in, followed in order by the font families
|
||||
/// in [fontFamilyFallback]. If all font families are exhausted and no match
|
||||
/// was found, the default platform font family will be used instead.
|
||||
///
|
||||
/// When [fontFamily] is null or not provided, the first value in [fontFamilyFallback]
|
||||
/// acts as the preferred/first font family. When neither is provided, then
|
||||
/// the default platform font will be used. Providing an empty list or null
|
||||
/// for this property is the same as omitting it.
|
||||
///
|
||||
/// For example, if a glyph is not found in [fontFamily], then each font family
|
||||
/// in [fontFamilyFallback] will be searched in order until it is found. If it
|
||||
/// is not found, then a box will be drawn in its place.
|
||||
///
|
||||
/// If the font is defined in a package, each font family in the list will be
|
||||
/// prefixed with 'packages/package_name/' (e.g. 'packages/cool_fonts/Roboto').
|
||||
/// The package name should be provided by the `package` argument in the
|
||||
/// constructor.
|
||||
final List<String>? fontFamilyFallback;
|
||||
|
||||
/// The height of this text span, as a multiple of the font size.
|
||||
///
|
||||
/// When [fontHeight] is null or omitted, the line height will be determined
|
||||
/// by the font's metrics directly, which may differ from the fontSize.
|
||||
/// When [fontHeight] is non-null, the line height of the span of text will be a
|
||||
/// multiple of [fontSize] and be exactly `fontSize * height` logical pixels
|
||||
/// tall.
|
||||
///
|
||||
/// For most fonts, setting [fontHeight] to 1.0 is not the same as omitting or
|
||||
/// setting height to null because the [fontSize] sets the height of the EM-square,
|
||||
/// which is different than the font provided metrics for line height. The
|
||||
/// following diagram illustrates the difference between the font-metrics
|
||||
/// defined line height and the line height produced with `height: 1.0`
|
||||
/// (which forms the upper and lower edges of the EM-square):
|
||||
///
|
||||
/// See [StrutStyle] and [TextHeightBehavior] for further control of line
|
||||
/// height at the paragraph level.
|
||||
final double? fontHeight;
|
||||
|
||||
/// The color to use when painting the text.
|
||||
///
|
||||
/// The [textColor] property is shorthand for `Paint()..color = color`.
|
||||
final Color? textColor;
|
||||
|
||||
/// The color to use when painting the hint text.
|
||||
///
|
||||
/// The [hintTextColor] property is shorthand for `Paint()..color = color`.
|
||||
final Color? hintTextColor;
|
||||
|
||||
/// The color to use as the background for the editor.
|
||||
///
|
||||
/// Note, this is not the text background color.
|
||||
final Color? backgroundColor;
|
||||
|
||||
/// The color to use as the background for the selected text.
|
||||
///
|
||||
/// The paint layer is under [highlightColor].
|
||||
final Color? selectionColor;
|
||||
|
||||
/// The color to use as the background for the highlighted text, such as
|
||||
/// the search matched text.
|
||||
///
|
||||
/// The paint layer is above [selectionColor].
|
||||
final Color? highlightColor;
|
||||
|
||||
/// The color of the cursor.
|
||||
///
|
||||
/// The cursor indicates the current location of text insertion point in
|
||||
/// the field.
|
||||
///
|
||||
/// If this is null it will default to the ambient
|
||||
/// [DefaultSelectionStyle.cursorColor]. If that is null, and the
|
||||
/// [ThemeData.platform] is [TargetPlatform.iOS] or [TargetPlatform.macOS]
|
||||
/// it will use [CupertinoThemeData.primaryColor]. Otherwise it will use
|
||||
/// the value of [ColorScheme.primary] of [ThemeData.colorScheme].
|
||||
final Color? cursorColor;
|
||||
|
||||
/// How thick the cursor will be.
|
||||
///
|
||||
/// Defaults to 2.0.
|
||||
///
|
||||
/// The cursor will draw under the text. The cursor width will extend
|
||||
/// to the right of the boundary between characters for left-to-right text
|
||||
/// and to the left for right-to-left text. This corresponds to extending
|
||||
/// downstream relative to the selected position. Negative values may be used
|
||||
/// to reverse this behavior.
|
||||
final double? cursorWidth;
|
||||
|
||||
/// The color to use as the border for the focused line.
|
||||
final Color? cursorLineColor;
|
||||
|
||||
/// The color of the chunked indicator at the end of the line.
|
||||
final Color? chunkIndicatorColor;
|
||||
|
||||
/// The code syntax highlighting rules and styles.
|
||||
final CodeHighlightTheme? codeTheme;
|
||||
|
||||
}
|
||||
|
||||
/// Creates a code editor.
|
||||
///
|
||||
/// You can freely define the styles of the editor, such as text style,
|
||||
/// line number view, search view, scroll bar, etc.
|
||||
///
|
||||
/// Similar to [TextField], editor uses [CodeLineEditingController] as the content controller.
|
||||
/// You can create a controller using the following code.
|
||||
///
|
||||
/// ```dart
|
||||
/// final controller = CodeLineEditingController.fromText('Hello World');
|
||||
/// ```
|
||||
/// or
|
||||
/// ```dart
|
||||
/// final controller = CodeLineEditingController.fromFile('/Users/megatronking/hello.py');
|
||||
/// ```
|
||||
///
|
||||
/// If [wordWrap] mode is turned off, the editor will support both horizontal and vertical scrolling,
|
||||
/// and you can use [CodeScrollController] to control the scrolling.
|
||||
///
|
||||
/// You can use [CodeFindBuilder] to create search widget and use [CodeFindController] to control the widget and
|
||||
/// search actions.
|
||||
///
|
||||
/// The editor has many built-in shortcut key actions. If you need to customize shortcut keys, you can use
|
||||
/// [shortcutsActivatorsBuilder] or [shortcutOverrideActions]. By default, the editor will use [DefaultCodeShortcutsActivatorsBuilder].
|
||||
///
|
||||
/// Regarding code folding, you can write a custom code folding analyzer with [chunkAnalyzer].
|
||||
/// By default, the editor will use [DefaultCodeChunkAnalyzer]. This works for some commonly used languages,
|
||||
/// but may not work for some languages (such as python).
|
||||
class CodeEditor extends StatefulWidget {
|
||||
|
||||
const CodeEditor({
|
||||
super.key,
|
||||
this.controller,
|
||||
this.scrollController,
|
||||
this.findController,
|
||||
this.toolbarController,
|
||||
this.onChanged,
|
||||
this.style,
|
||||
this.hint,
|
||||
this.padding,
|
||||
this.margin,
|
||||
this.indicatorBuilder,
|
||||
this.scrollbarBuilder,
|
||||
this.verticalScrollbarWidth,
|
||||
this.horizontalScrollbarHeight,
|
||||
this.findBuilder,
|
||||
this.shortcutsActivatorsBuilder,
|
||||
this.shortcutOverrideActions,
|
||||
this.leadingDivider,
|
||||
this.border,
|
||||
this.borderRadius,
|
||||
this.clipBehavior = Clip.none,
|
||||
this.readOnly,
|
||||
this.showCursorWhenReadOnly,
|
||||
this.wordWrap,
|
||||
this.autocompleteSymbols,
|
||||
this.autofocus,
|
||||
this.focusNode,
|
||||
this.maxLengthSingleLineRendering,
|
||||
this.chunkAnalyzer,
|
||||
this.commentFormatter,
|
||||
}) : assert(indicatorBuilder != null || (indicatorBuilder == null && leadingDivider == null));
|
||||
|
||||
/// Similar to [TextField], editor uses [CodeLineEditingController] as the content controller.
|
||||
final CodeLineEditingController? controller;
|
||||
|
||||
/// Controls horizontal and vertical scrolling.
|
||||
final CodeScrollController? scrollController;
|
||||
|
||||
/// Controls the search widget and actions.
|
||||
final CodeFindController? findController;
|
||||
|
||||
/// Controls the selection toolbar.
|
||||
final SelectionToolbarController? toolbarController;
|
||||
|
||||
/// Called when the user initiates a change to the editor's
|
||||
/// value was changed, such as insertion or deletion.
|
||||
///
|
||||
/// Same as [CodeLineEditingController.addListener].
|
||||
final ValueChanged<CodeLineEditingValue>? onChanged;
|
||||
|
||||
/// The style to use for the editor.
|
||||
final CodeEditorStyle? style;
|
||||
|
||||
/// Text that suggests what sort of input the field accepts.
|
||||
final String? hint;
|
||||
|
||||
/// The padding of the editor field, excludes the addtional wdigets like line number widget.
|
||||
final EdgeInsetsGeometry? padding;
|
||||
|
||||
/// The margin value of the whole editor, includes the addtional wdigets like line number widget.
|
||||
final EdgeInsetsGeometry? margin;
|
||||
|
||||
/// Use this to build your own indicator widget like line number widget.
|
||||
/// See [DefaultCodeLineNumber] and [DefaultCodeChunkIndicator].
|
||||
final CodeIndicatorBuilder? indicatorBuilder;
|
||||
|
||||
/// Use this to build your own scroll bar widget.
|
||||
final CodeScrollbarBuilder? scrollbarBuilder;
|
||||
|
||||
/// The width of the vertical scrollbar.
|
||||
final double? verticalScrollbarWidth;
|
||||
|
||||
/// The height of the horizontal scrollbar.
|
||||
final double? horizontalScrollbarHeight;
|
||||
|
||||
/// Use this to build your own search widget.
|
||||
/// The search widget will appear on the top of editor field.
|
||||
final CodeFindBuilder? findBuilder;
|
||||
|
||||
/// Customize your shortcut keys.
|
||||
final CodeShortcutsActivatorsBuilder? shortcutsActivatorsBuilder;
|
||||
|
||||
/// Override built-in shortcut key actions.
|
||||
final Map<Type, Action<Intent>>? shortcutOverrideActions;
|
||||
|
||||
/// A leadingDivider widget between indicator and editor field.
|
||||
final Widget? leadingDivider;
|
||||
|
||||
/// The border of the editor.
|
||||
final Border? border;
|
||||
|
||||
/// The radius of the editor's border corners.
|
||||
///
|
||||
/// This defines how rounded the corners of the editor's border will appear.
|
||||
///
|
||||
/// If null, the corners will not be rounded.
|
||||
final BorderRadius? borderRadius;
|
||||
|
||||
|
||||
/// How the content should be clipped if it overflows the editor's bounds.
|
||||
final Clip clipBehavior;
|
||||
|
||||
/// Whether the text can be changed.
|
||||
///
|
||||
/// When this is set to true, the text cannot be modified
|
||||
/// by any shortcut or keyboard operation. The text is still selectable.
|
||||
///
|
||||
/// Defaults to false.
|
||||
final bool? readOnly;
|
||||
|
||||
/// Whether to show cursor when in readonly mode.
|
||||
///
|
||||
/// The cursor refers to the blinking caret when the editor is focused.
|
||||
final bool? showCursorWhenReadOnly;
|
||||
|
||||
/// Should wrap the word.
|
||||
final bool? wordWrap;
|
||||
|
||||
/// When entering a closed symbol, should the other half be automatically completed.
|
||||
/// For example, when entering a double quote, the other half will be automatically added.
|
||||
/// Defaults to true.
|
||||
final bool? autocompleteSymbols;
|
||||
|
||||
/// Whether this editor field should focus itself if nothing else is already
|
||||
/// focused.
|
||||
///
|
||||
/// If true, the keyboard will open as soon as this text field obtains focus.
|
||||
/// Otherwise, the keyboard is only shown after the user taps the editor field.
|
||||
///
|
||||
/// Defaults to false.
|
||||
final bool? autofocus;
|
||||
|
||||
/// Controls whether this widget has keyboard focus.
|
||||
final FocusNode? focusNode;
|
||||
|
||||
/// The maximum number of characters per line to render.
|
||||
///
|
||||
/// Due to the performance limitations of the Skia text engine,
|
||||
/// setting a reasonable length can improve the performance of the editor.
|
||||
///
|
||||
/// If null, there is no limit.
|
||||
final int? maxLengthSingleLineRendering;
|
||||
|
||||
/// Decide which parts of code can be folded.
|
||||
///
|
||||
/// Defaults to [DefaultCodeChunkAnalyzer].
|
||||
///
|
||||
/// If you wish to turn off code folding, you can use [NonCodeChunkAnalyzer].
|
||||
final CodeChunkAnalyzer? chunkAnalyzer;
|
||||
|
||||
/// Control how one or more lines of code are commented.
|
||||
final CodeCommentFormatter? commentFormatter;
|
||||
|
||||
@override
|
||||
State<StatefulWidget> createState() => _CodeEditorState();
|
||||
|
||||
}
|
||||
|
||||
class _CodeEditorState extends State<CodeEditor> {
|
||||
|
||||
late final GlobalKey _editorKey;
|
||||
late FocusNode _focusNode;
|
||||
late _CodeLineEditingControllerDelegate _editingController;
|
||||
late final _CodeInputController _inputController;
|
||||
late final _CodeFloatingCursorController _floatingCursorController;
|
||||
late CodeScrollController _scrollController;
|
||||
late CodeFindController _findController;
|
||||
late CodeChunkController _chunkController;
|
||||
|
||||
final LayerLink _startHandleLayerLink = LayerLink();
|
||||
final LayerLink _endHandleLayerLink = LayerLink();
|
||||
final LayerLink _toolbarLayerLink = LayerLink();
|
||||
final ValueNotifier<bool> _effectiveToolbarVisibility = ValueNotifier<bool>(true);
|
||||
|
||||
late _SelectionOverlayController _selectionOverlayController;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_editorKey = GlobalKey();
|
||||
_focusNode = widget.focusNode ?? FocusNode();
|
||||
_editingController = _CodeLineEditingControllerDelegate();
|
||||
_editingController.delegate = widget.controller ?? CodeLineEditingController();
|
||||
_editingController.bindEditor(_editorKey);
|
||||
|
||||
_floatingCursorController = _CodeFloatingCursorController();
|
||||
|
||||
_inputController = _CodeInputController(
|
||||
controller: _editingController,
|
||||
floatingCursorController: _floatingCursorController,
|
||||
focusNode: _focusNode,
|
||||
readOnly: widget.readOnly ?? false,
|
||||
autocompleteSymbols: widget.autocompleteSymbols ?? true,
|
||||
);
|
||||
_inputController.bindEditor(_editorKey);
|
||||
|
||||
_findController = widget.findController ?? CodeFindController(_editingController);
|
||||
_findController.addListener(_updateWidget);
|
||||
_scrollController = widget.scrollController ?? CodeScrollController();
|
||||
_scrollController.bindEditor(_editorKey);
|
||||
_chunkController = CodeChunkController(_editingController, widget.chunkAnalyzer ?? const DefaultCodeChunkAnalyzer());
|
||||
|
||||
_selectionOverlayController = kIsAndroid || kIsIOS ? _MobileSelectionOverlayController(
|
||||
context: context,
|
||||
controller: _editingController,
|
||||
editorKey: _editorKey,
|
||||
startHandleLayerLink: _startHandleLayerLink,
|
||||
endHandleLayerLink: _endHandleLayerLink,
|
||||
toolbarVisibility: _effectiveToolbarVisibility,
|
||||
focusNode: _focusNode,
|
||||
onShowToolbar: (context, anchors, renderRect) {
|
||||
widget.toolbarController?.show(
|
||||
context: _editorKey.currentContext ?? context,
|
||||
controller: _editingController,
|
||||
anchors: anchors,
|
||||
renderRect: renderRect,
|
||||
layerLink: _toolbarLayerLink,
|
||||
visibility: _effectiveToolbarVisibility,
|
||||
);
|
||||
},
|
||||
onHideToolbar: () {
|
||||
widget.toolbarController?.hide(context);
|
||||
},
|
||||
) : _DesktopSelectionOverlayController(
|
||||
onShowToolbar: (context, anchors, renderRect) {
|
||||
widget.toolbarController?.show(
|
||||
context: context,
|
||||
controller: _editingController,
|
||||
anchors: anchors,
|
||||
renderRect: renderRect,
|
||||
layerLink: _toolbarLayerLink,
|
||||
visibility: _effectiveToolbarVisibility,
|
||||
);
|
||||
},
|
||||
onHideToolbar: () {
|
||||
widget.toolbarController?.hide(context);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_findController.removeListener(_updateWidget);
|
||||
if (widget.focusNode == null) {
|
||||
_focusNode.dispose();
|
||||
}
|
||||
if (widget.controller == null) {
|
||||
_editingController.dispose();
|
||||
}
|
||||
_inputController.dispose();
|
||||
if (widget.findController == null) {
|
||||
_findController.dispose();
|
||||
}
|
||||
if (widget.scrollController== null) {
|
||||
_scrollController.dispose();
|
||||
}
|
||||
_chunkController.dispose();
|
||||
_selectionOverlayController.dispose();
|
||||
_floatingCursorController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant CodeEditor oldWidget) {
|
||||
if (oldWidget.focusNode != widget.focusNode) {
|
||||
if (oldWidget.focusNode == null) {
|
||||
_focusNode.dispose();
|
||||
}
|
||||
_focusNode = widget.focusNode ?? FocusNode();
|
||||
_inputController.focusNode = _focusNode;
|
||||
}
|
||||
if (oldWidget.controller != widget.controller) {
|
||||
if (oldWidget.controller == null) {
|
||||
_editingController.dispose();
|
||||
}
|
||||
_editingController.delegate = widget.controller ?? CodeLineEditingController();
|
||||
_editingController.bindEditor(_editorKey);
|
||||
}
|
||||
if (oldWidget.findController != widget.findController || oldWidget.controller != widget.controller) {
|
||||
final CodeFindController oldFindController = _findController;
|
||||
if (oldWidget.findController == null) {
|
||||
oldFindController.dispose();
|
||||
} else {
|
||||
oldFindController.removeListener(_updateWidget);
|
||||
}
|
||||
_findController = widget.findController ?? CodeFindController(_editingController);
|
||||
_findController.addListener(_updateWidget);
|
||||
}
|
||||
if (oldWidget.scrollController != widget.scrollController) {
|
||||
if (oldWidget.scrollController == null) {
|
||||
_scrollController.dispose();
|
||||
}
|
||||
_scrollController = widget.scrollController ?? CodeScrollController();
|
||||
_scrollController.bindEditor(_editorKey);
|
||||
}
|
||||
if (oldWidget.chunkAnalyzer != widget.chunkAnalyzer || oldWidget.controller != widget.controller) {
|
||||
_chunkController.dispose();
|
||||
_chunkController = CodeChunkController(_editingController, widget.chunkAnalyzer ?? const DefaultCodeChunkAnalyzer());
|
||||
}
|
||||
if (oldWidget.readOnly != widget.readOnly) {
|
||||
_inputController.readOnly = widget.readOnly ?? false;
|
||||
}
|
||||
if (oldWidget.autocompleteSymbols != widget.autocompleteSymbols) {
|
||||
_inputController.autocompleteSymbols = widget.autocompleteSymbols ?? true;
|
||||
}
|
||||
super.didUpdateWidget(oldWidget);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final ThemeData theme = Theme.of(context);
|
||||
final TextSelectionThemeData selectionTheme = TextSelectionTheme.of(context);
|
||||
final TextStyle baseStyle = TextStyle(
|
||||
fontSize: widget.style?.fontSize ?? _kDefaultTextSize,
|
||||
fontFamily: widget.style?.fontFamily,
|
||||
fontFamilyFallback: widget.style?.fontFamilyFallback,
|
||||
height: widget.style?.fontHeight ?? _kDefaultFontHeight,
|
||||
);
|
||||
final bool readOnly = widget.readOnly ?? false;
|
||||
final bool autofocus = widget.autofocus ?? true;
|
||||
final bool wordWrap = widget.wordWrap ?? true;
|
||||
final PreferredSizeWidget? find = widget.findBuilder?.call(context, _findController, readOnly);
|
||||
final Widget editable = _CodeEditable(
|
||||
editorKey: _editorKey,
|
||||
hint: widget.hint,
|
||||
indicatorBuilder: widget.indicatorBuilder,
|
||||
scrollbarBuilder: widget.scrollbarBuilder,
|
||||
verticalScrollbarWidth: widget.verticalScrollbarWidth,
|
||||
horizontalScrollbarHeight: widget.horizontalScrollbarHeight,
|
||||
textStyle: baseStyle.copyWith(
|
||||
color: widget.style?.textColor ?? theme.textTheme.bodyLarge?.color,
|
||||
),
|
||||
hintTextColor: widget.style?.hintTextColor,
|
||||
backgroundColor: widget.style?.backgroundColor,
|
||||
selectionColor: widget.style?.selectionColor ?? selectionTheme.selectionColor ?? theme.colorScheme.primary.withOpacity(0.4),
|
||||
highlightColor: widget.style?.highlightColor ?? selectionTheme.selectionColor ?? theme.colorScheme.primary.withOpacity(0.4),
|
||||
cursorColor: widget.style?.cursorColor ?? selectionTheme.cursorColor ?? theme.colorScheme.primary,
|
||||
cursorLineColor: widget.style?.cursorLineColor,
|
||||
chunkIndicatorColor: widget.style?.chunkIndicatorColor,
|
||||
cursorWidth: widget.style?.cursorWidth ?? _kDefaultCaretWidth,
|
||||
showCursorWhenReadOnly: widget.showCursorWhenReadOnly ?? true,
|
||||
leadingDivider: widget.leadingDivider,
|
||||
border: widget.border,
|
||||
borderRadius: widget.borderRadius,
|
||||
clipBehavior: widget.clipBehavior,
|
||||
onChanged: widget.onChanged,
|
||||
focusNode: _focusNode,
|
||||
padding: (widget.padding ?? _kDefaultPadding).add(EdgeInsets.only(
|
||||
top: find == null ? 0 : find.preferredSize.height
|
||||
)),
|
||||
margin: widget.margin ?? EdgeInsets.zero,
|
||||
controller: _editingController,
|
||||
inputController: _inputController,
|
||||
codeTheme: widget.style?.codeTheme,
|
||||
readOnly: readOnly,
|
||||
autofocus: autofocus,
|
||||
wordWrap: wordWrap,
|
||||
maxLengthSingleLineRendering: widget.maxLengthSingleLineRendering,
|
||||
findController: _findController,
|
||||
scrollController: _scrollController,
|
||||
chunkController: _chunkController,
|
||||
floatingCursorController: _floatingCursorController,
|
||||
startHandleLayerLink: _startHandleLayerLink,
|
||||
endHandleLayerLink: _endHandleLayerLink,
|
||||
toolbarLayerLink: _toolbarLayerLink,
|
||||
selectionOverlayController: _selectionOverlayController,
|
||||
);
|
||||
final Widget detector = _CodeSelectionGestureDetector(
|
||||
controller: _editingController,
|
||||
inputController: _inputController,
|
||||
chunkController: _chunkController,
|
||||
selectionOverlayController: _selectionOverlayController,
|
||||
behavior: HitTestBehavior.translucent,
|
||||
editorKey: _editorKey,
|
||||
child: editable
|
||||
);
|
||||
final Widget child;
|
||||
if (kIsAndroid || kIsIOS) {
|
||||
child = Focus(
|
||||
autofocus: autofocus,
|
||||
focusNode: _focusNode,
|
||||
onKey: (node, event) {
|
||||
if (event.isKeyPressed(LogicalKeyboardKey.backspace)) {
|
||||
_editingController.deleteBackward();
|
||||
return KeyEventResult.handled;
|
||||
} else if (event.isKeyPressed(LogicalKeyboardKey.enter)) {
|
||||
_editingController.applyNewLine();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
return KeyEventResult.ignored;
|
||||
},
|
||||
includeSemantics: false,
|
||||
debugLabel: 'CodeEditor',
|
||||
child: detector
|
||||
);
|
||||
} else {
|
||||
child = _CodeShortcuts(
|
||||
builder: widget.shortcutsActivatorsBuilder ?? const DefaultCodeShortcutsActivatorsBuilder(),
|
||||
child: _CodeShortcutActions(
|
||||
editingController: _editingController,
|
||||
inputController: _inputController,
|
||||
findController: find != null ? _findController : null,
|
||||
commentFormatter: widget.commentFormatter,
|
||||
overrideActions: widget.shortcutOverrideActions,
|
||||
readOnly: readOnly,
|
||||
child: Focus(
|
||||
autofocus: autofocus,
|
||||
focusNode: _focusNode,
|
||||
includeSemantics: false,
|
||||
debugLabel: 'CodeEditor',
|
||||
child: detector
|
||||
)
|
||||
),
|
||||
);
|
||||
}
|
||||
return Stack(
|
||||
children: [
|
||||
child,
|
||||
if (find != null)
|
||||
find,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
void _updateWidget() {
|
||||
setState(() {
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// A [TapRegion] that adds its children to the tap region group for widgets
|
||||
/// based on the [CodeEditor] widget.
|
||||
///
|
||||
/// Widgets that are wrapped with a [CodeEditorTapRegion] are considered to be
|
||||
/// part of the editor for purposes of unfocus behavior. So, when the user
|
||||
/// taps on them, the currently focused editor won't be unfocused by
|
||||
/// default.
|
||||
///
|
||||
/// See also:
|
||||
///
|
||||
/// * [TapRegion], the widget that this widget uses to add widgets to the group
|
||||
/// of text fields.
|
||||
class CodeEditorTapRegion extends TapRegion {
|
||||
|
||||
/// Creates a const [CodeEditorTapRegion].
|
||||
///
|
||||
/// The [child] field is required.
|
||||
const CodeEditorTapRegion({
|
||||
super.key,
|
||||
required super.child,
|
||||
super.enabled = true,
|
||||
super.behavior = HitTestBehavior.deferToChild,
|
||||
super.onTapOutside,
|
||||
super.onTapInside,
|
||||
}) : super(groupId: CodeEditor);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
part of re_editor;
|
||||
|
||||
typedef CodeFindBuilder = PreferredSizeWidget Function(BuildContext context, CodeFindController controller, bool readonly);
|
||||
|
||||
class CodeFindValue {
|
||||
|
||||
final CodeFindOption option;
|
||||
final bool replaceMode;
|
||||
final CodeFindResult? result;
|
||||
final bool searching;
|
||||
|
||||
const CodeFindValue({
|
||||
required this.option,
|
||||
required this.replaceMode,
|
||||
this.result,
|
||||
this.searching = false,
|
||||
});
|
||||
|
||||
const CodeFindValue.empty() : this(
|
||||
option: const CodeFindOption(
|
||||
pattern: '',
|
||||
caseSensitive: false,
|
||||
regex: false,
|
||||
),
|
||||
replaceMode: false,
|
||||
);
|
||||
|
||||
CodeFindValue copyWith({
|
||||
CodeFindOption? option,
|
||||
bool? replaceMode,
|
||||
required CodeFindResult? result,
|
||||
bool? searching,
|
||||
}) {
|
||||
return CodeFindValue(
|
||||
option: option ?? this.option,
|
||||
replaceMode: replaceMode ?? this.replaceMode,
|
||||
result: result,
|
||||
searching: searching ?? this.searching,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
if (identical(this, other)) {
|
||||
return true;
|
||||
}
|
||||
return other is CodeFindValue
|
||||
&& other.option == option
|
||||
&& other.replaceMode == replaceMode
|
||||
&& other.result == result
|
||||
&& other.searching == searching;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(option, replaceMode, result, searching);
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return '{option: $option replaceMode: $replaceMode result: $result searching:$searching}';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class CodeFindOption {
|
||||
|
||||
final String pattern;
|
||||
final bool caseSensitive;
|
||||
final bool regex;
|
||||
|
||||
const CodeFindOption({
|
||||
required this.pattern,
|
||||
required this.caseSensitive,
|
||||
required this.regex,
|
||||
});
|
||||
|
||||
CodeFindOption copyWith({
|
||||
String? pattern,
|
||||
bool? caseSensitive,
|
||||
bool? regex,
|
||||
}) {
|
||||
return CodeFindOption(
|
||||
pattern: pattern ?? this.pattern,
|
||||
caseSensitive: caseSensitive ?? this.caseSensitive,
|
||||
regex: regex ?? this.regex,
|
||||
);
|
||||
}
|
||||
|
||||
RegExp? get regExp {
|
||||
if (regex) {
|
||||
try {
|
||||
return RegExp(pattern, caseSensitive: caseSensitive);
|
||||
} on FormatException {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
return RegExp(RegExp.escape(pattern), caseSensitive: caseSensitive);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
if (identical(this, other)) {
|
||||
return true;
|
||||
}
|
||||
return other is CodeFindOption
|
||||
&& other.pattern == pattern
|
||||
&& other.caseSensitive == caseSensitive
|
||||
&& other.regex == regex;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(pattern, caseSensitive, regex);
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return '{pattern: $pattern caseSensitive: $caseSensitive regex: $regex}';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class CodeFindResult {
|
||||
|
||||
final int index;
|
||||
final List<CodeLineSelection> matches;
|
||||
final CodeFindOption option;
|
||||
final CodeLines codeLines;
|
||||
final bool dirty;
|
||||
|
||||
const CodeFindResult({
|
||||
required this.index,
|
||||
required this.matches,
|
||||
required this.option,
|
||||
required this.codeLines,
|
||||
required this.dirty,
|
||||
});
|
||||
|
||||
CodeFindResult get previous => copyWith(
|
||||
index: index == 0 ? matches.length - 1 : index - 1
|
||||
);
|
||||
|
||||
CodeFindResult get next => copyWith(
|
||||
index: index == matches.length - 1 ? 0 : index + 1
|
||||
);
|
||||
|
||||
CodeLineSelection? get currentMatch => index == -1 ? null : matches[index];
|
||||
|
||||
CodeFindResult copyWith({
|
||||
int? index,
|
||||
List<CodeLineSelection>? matches,
|
||||
CodeFindOption? option,
|
||||
CodeLines? codeLines,
|
||||
bool? dirty,
|
||||
}) {
|
||||
return CodeFindResult(
|
||||
index: index ?? this.index,
|
||||
matches: matches ?? this.matches,
|
||||
option: option ?? this.option,
|
||||
codeLines: codeLines ?? this.codeLines,
|
||||
dirty: dirty ?? this.dirty,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
if (identical(this, other)) {
|
||||
return true;
|
||||
}
|
||||
return other is CodeFindResult
|
||||
&& other.index == index
|
||||
&& listEquals(other.matches, matches)
|
||||
&& other.option == option
|
||||
&& other.codeLines.equals(codeLines)
|
||||
&& other.dirty == dirty;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(index, matches, option, codeLines, dirty);
|
||||
|
||||
}
|
||||
|
||||
abstract class CodeFindController extends ValueNotifier<CodeFindValue?> {
|
||||
|
||||
factory CodeFindController(CodeLineEditingController controller, [CodeFindValue? value])
|
||||
=> _CodeFindControllerImpl(controller, value);
|
||||
|
||||
TextEditingController get findInputController;
|
||||
|
||||
TextEditingController get replaceInputController;
|
||||
|
||||
FocusNode get findInputFocusNode;
|
||||
|
||||
FocusNode get replaceInputFocusNode;
|
||||
|
||||
List<CodeLineSelection>? get allMatchSelections;
|
||||
|
||||
CodeLineSelection? get currentMatchSelection;
|
||||
|
||||
void findMode();
|
||||
|
||||
void replaceMode();
|
||||
|
||||
void focusOnFindInput();
|
||||
|
||||
void focusOnReplaceInput();
|
||||
|
||||
void toggleMode();
|
||||
|
||||
void close();
|
||||
|
||||
void toggleRegex();
|
||||
|
||||
void toggleCaseSensitive();
|
||||
|
||||
void previousMatch();
|
||||
|
||||
void nextMatch();
|
||||
|
||||
void replaceMatch();
|
||||
|
||||
void replaceAllMatches();
|
||||
|
||||
CodeLineSelection? convertMatchToSelection(CodeLineSelection match);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
part of re_editor;
|
||||
|
||||
abstract class CodeCommentFormatter {
|
||||
|
||||
CodeLineEditingValue format(CodeLineEditingValue value, String indent, bool single);
|
||||
|
||||
}
|
||||
|
||||
abstract class DefaultCodeCommentFormatter implements CodeCommentFormatter {
|
||||
|
||||
factory DefaultCodeCommentFormatter({
|
||||
String? singleLinePrefix,
|
||||
String? multiLinePrefix,
|
||||
String? multiLineSuffix
|
||||
}) => _DefaultCodeCommentFormatter(
|
||||
singleLinePrefix: singleLinePrefix,
|
||||
multiLinePrefix: multiLinePrefix,
|
||||
multiLineSuffix: multiLineSuffix
|
||||
);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
part of re_editor;
|
||||
|
||||
const int _kDefaultMinNumberCount = 3;
|
||||
const Size _kDefaultChunkIndicatorSize = Size(7, 7);
|
||||
|
||||
typedef CodeIndicatorValueNotifier = ValueNotifier<CodeIndicatorValue?>;
|
||||
typedef CodeIndicatorBuilder = Widget Function(
|
||||
BuildContext context,
|
||||
CodeLineEditingController editingController,
|
||||
CodeChunkController chunkController,
|
||||
CodeIndicatorValueNotifier notifier,
|
||||
);
|
||||
|
||||
class CodeIndicatorValue {
|
||||
|
||||
final List<CodeLineRenderParagraph> paragraphs;
|
||||
final int focusedIndex;
|
||||
|
||||
CodeIndicatorValue({
|
||||
required this.paragraphs,
|
||||
this.focusedIndex = -1,
|
||||
});
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hashAll([paragraphs, focusedIndex]);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
if (other is! CodeIndicatorValue) {
|
||||
return false;
|
||||
}
|
||||
return listEquals(other.paragraphs, paragraphs) &&
|
||||
other.focusedIndex == focusedIndex;
|
||||
}
|
||||
|
||||
CodeIndicatorValue copyWith({
|
||||
List<CodeLineRenderParagraph>? paragraphs,
|
||||
int? focusedIndex,
|
||||
}) {
|
||||
return CodeIndicatorValue(
|
||||
paragraphs: paragraphs ?? this.paragraphs,
|
||||
focusedIndex: focusedIndex ?? this.focusedIndex,
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class DefaultCodeLineNumber extends LeafRenderObjectWidget {
|
||||
|
||||
final CodeLineEditingController controller;
|
||||
final CodeIndicatorValueNotifier notifier;
|
||||
final TextStyle? textStyle;
|
||||
final TextStyle? focusedTextStyle;
|
||||
final int? minNumberCount;
|
||||
final String Function(int lineIndex)? customLineIndex2Text;
|
||||
|
||||
const DefaultCodeLineNumber({
|
||||
super.key,
|
||||
required this.notifier,
|
||||
required this.controller,
|
||||
this.textStyle,
|
||||
this.focusedTextStyle,
|
||||
this.minNumberCount,
|
||||
this.customLineIndex2Text,
|
||||
});
|
||||
|
||||
@override
|
||||
RenderObject createRenderObject(BuildContext context) => CodeLineNumberRenderObject(
|
||||
controller: controller,
|
||||
notifier: notifier,
|
||||
textStyle: textStyle ?? _useCodeTextStyle(context, false),
|
||||
focusedTextStyle: focusedTextStyle ?? _useCodeTextStyle(context, true),
|
||||
minNumberCount: minNumberCount ?? _kDefaultMinNumberCount,
|
||||
custonLineIndex2Text: customLineIndex2Text,
|
||||
);
|
||||
|
||||
@override
|
||||
void updateRenderObject(BuildContext context, covariant CodeLineNumberRenderObject renderObject) {
|
||||
renderObject
|
||||
..controller = controller
|
||||
..notifier = notifier
|
||||
..textStyle = textStyle ?? _useCodeTextStyle(context, false)
|
||||
..focusedTextStyle = focusedTextStyle ?? _useCodeTextStyle(context, true)
|
||||
..minNumberCount = minNumberCount ?? _kDefaultMinNumberCount;
|
||||
super.updateRenderObject(context, renderObject);
|
||||
}
|
||||
|
||||
TextStyle _useCodeTextStyle(BuildContext context, bool focused) {
|
||||
final _CodeEditable? editor = context.findAncestorWidgetOfExactType<_CodeEditable>();
|
||||
assert(editor != null);
|
||||
return editor!.textStyle.copyWith(
|
||||
color: focused ? null : editor.textStyle.color?.withAlpha(128)
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class DefaultCodeChunkIndicator extends LeafRenderObjectWidget {
|
||||
|
||||
final double width;
|
||||
final CodeChunkController controller;
|
||||
final CodeIndicatorValueNotifier notifier;
|
||||
final CodeChunkIndicatorPainter? painter;
|
||||
final bool collapseIndicatorVisible;
|
||||
final bool expandIndicatorVisible;
|
||||
|
||||
const DefaultCodeChunkIndicator({
|
||||
super.key,
|
||||
required this.width,
|
||||
required this.controller,
|
||||
required this.notifier,
|
||||
this.painter,
|
||||
this.collapseIndicatorVisible = true,
|
||||
this.expandIndicatorVisible = true,
|
||||
});
|
||||
|
||||
@override
|
||||
RenderObject createRenderObject(BuildContext context) => CodeChunkIndicatorRenderObject(
|
||||
width: width,
|
||||
controller: controller,
|
||||
notifier: notifier,
|
||||
painter: painter ?? DefaultCodeChunkIndicatorPainter(
|
||||
color: _useCodeTextColor(context),
|
||||
),
|
||||
collapseIndicatorVisible: collapseIndicatorVisible,
|
||||
expandIndicatorVisible: expandIndicatorVisible,
|
||||
);
|
||||
|
||||
@override
|
||||
void updateRenderObject(BuildContext context, covariant CodeChunkIndicatorRenderObject renderObject) {
|
||||
renderObject
|
||||
..width = width
|
||||
..controller = controller
|
||||
..notifier = notifier
|
||||
..painter = painter ?? DefaultCodeChunkIndicatorPainter(
|
||||
color: _useCodeTextColor(context),
|
||||
)
|
||||
..collapseIndicatorVisible = collapseIndicatorVisible
|
||||
..expandIndicatorVisible = expandIndicatorVisible;
|
||||
super.updateRenderObject(context, renderObject);
|
||||
}
|
||||
|
||||
Color? _useCodeTextColor(BuildContext context) {
|
||||
final _CodeEditable? editor = context.findAncestorWidgetOfExactType<_CodeEditable>();
|
||||
assert(editor != null);
|
||||
return editor!.textStyle.color?.withAlpha(128);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
abstract class CodeChunkIndicatorPainter {
|
||||
|
||||
void paintCollapseIndicator(Canvas canvas, Size container);
|
||||
|
||||
void paintExpandIndicator(Canvas canvas, Size container);
|
||||
|
||||
}
|
||||
|
||||
class DefaultCodeChunkIndicatorPainter implements CodeChunkIndicatorPainter {
|
||||
|
||||
final Color? color;
|
||||
final Size size;
|
||||
|
||||
late final Paint _paint;
|
||||
|
||||
DefaultCodeChunkIndicatorPainter({
|
||||
this.color,
|
||||
this.size = _kDefaultChunkIndicatorSize
|
||||
}) {
|
||||
_paint = Paint();
|
||||
if (color != null) {
|
||||
_paint.color = color!;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void paintCollapseIndicator(Canvas canvas, Size container) {
|
||||
if (color == null || color == Colors.transparent || container.isEmpty) {
|
||||
return;
|
||||
}
|
||||
final Path path = Path();
|
||||
path.moveTo((container.width - size.width) / 2, (container.height - size.height) / 2);
|
||||
path.lineTo((container.width + size.width) / 2, (container.height - size.height) / 2);
|
||||
path.lineTo(container.width / 2, (container.height + size.height) / 2);
|
||||
path.lineTo((container.width - size.width) / 2, (container.height - size.height) / 2);
|
||||
canvas.drawPath(path, _paint);
|
||||
}
|
||||
|
||||
@override
|
||||
void paintExpandIndicator(Canvas canvas, Size container) {
|
||||
if (color == null || color == Colors.transparent || container.isEmpty) {
|
||||
return;
|
||||
}
|
||||
final Path path = Path();
|
||||
path.moveTo((container.width - size.width) / 2, (container.height - size.height) / 2);
|
||||
path.lineTo((container.width + size.width) / 2, container.height / 2);
|
||||
path.lineTo((container.width - size.width) / 2, (container.height + size.height) / 2);
|
||||
path.lineTo((container.width - size.width) / 2, (container.height - size.height) / 2);
|
||||
canvas.drawPath(path, _paint);
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,461 @@
|
||||
part of re_editor;
|
||||
|
||||
const int _kCodeLineSegamentDefaultSize = 256;
|
||||
|
||||
class CodeLines {
|
||||
|
||||
final List<CodeLineSegment> segments;
|
||||
|
||||
const CodeLines(this.segments);
|
||||
|
||||
factory CodeLines.empty() {
|
||||
return CodeLines.of([]);
|
||||
}
|
||||
|
||||
factory CodeLines.fromText(String text) {
|
||||
return text.codeLines;
|
||||
}
|
||||
|
||||
factory CodeLines.from(CodeLines codeLines) {
|
||||
final List<CodeLineSegment> segments = [];
|
||||
for (final CodeLineSegment segment in codeLines.segments) {
|
||||
if (segment.isEmpty) {
|
||||
continue;
|
||||
}
|
||||
segments.add(segment.copyWith(
|
||||
dirty: true
|
||||
));
|
||||
}
|
||||
return CodeLines(segments);
|
||||
}
|
||||
|
||||
factory CodeLines.of(Iterable<CodeLine> elements) {
|
||||
final List<CodeLineSegment> segments = [];
|
||||
int count = 0;
|
||||
for (int i = 0; i < elements.length; i++) {
|
||||
if (count == 0) {
|
||||
segments.add(CodeLineSegment.of(codeLines: []));
|
||||
}
|
||||
segments.last.add(elements.elementAt(i));
|
||||
count++;
|
||||
if (count >= _kCodeLineSegamentDefaultSize) {
|
||||
count = 0;
|
||||
}
|
||||
}
|
||||
return CodeLines(segments);
|
||||
}
|
||||
|
||||
CodeLine get first => segments.first.first;
|
||||
|
||||
CodeLine get last => segments.last.last;
|
||||
|
||||
int get length => segments.fold(0, (previousValue, element) => previousValue += element.length);
|
||||
|
||||
bool get isEmpty => segments.isEmpty || length == 0;
|
||||
|
||||
bool get isNotEmpty => !isEmpty;
|
||||
|
||||
int get lineCount => segments.fold(0, (previousValue, element) => previousValue += element.lineCount);
|
||||
|
||||
CodeLine operator [](int index) {
|
||||
int offset = 0;
|
||||
for (final CodeLineSegment segment in segments) {
|
||||
if (index - offset >= segment.length) {
|
||||
offset += segment.length;
|
||||
} else {
|
||||
return segment[index - offset];
|
||||
}
|
||||
}
|
||||
throw RangeError.range(index, 0, length - 1);
|
||||
}
|
||||
|
||||
void operator []=(int index, CodeLine value) {
|
||||
int offset = 0;
|
||||
for (int i = 0; i < segments.length; i++) {
|
||||
CodeLineSegment segment = segments[i];
|
||||
if (index - offset >= segment.length) {
|
||||
offset += segment.length;
|
||||
} else {
|
||||
if (segment.dirty) {
|
||||
segment = segment.clone();
|
||||
segments[i] = segment;
|
||||
}
|
||||
segment[index - offset] = value;
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw RangeError.range(index, 0, length - 1);
|
||||
}
|
||||
|
||||
void add(CodeLine value) {
|
||||
if (isEmpty || segments.last.length >= _kCodeLineSegamentDefaultSize) {
|
||||
segments.add(CodeLineSegment.of(
|
||||
codeLines: [
|
||||
value
|
||||
]
|
||||
));
|
||||
} else {
|
||||
CodeLineSegment segment = segments.last;
|
||||
if (segment.dirty) {
|
||||
segment = segment.clone();
|
||||
segments.last = segment;
|
||||
}
|
||||
segment.add(value);
|
||||
}
|
||||
}
|
||||
|
||||
void addAll(Iterable<CodeLine> iterable) {
|
||||
if (isEmpty) {
|
||||
segments.addAll(CodeLines.of(iterable).segments);
|
||||
return;
|
||||
}
|
||||
final CodeLineSegment segment = segments.last;
|
||||
int count;
|
||||
if (segment.length >= _kCodeLineSegamentDefaultSize) {
|
||||
count = 0;
|
||||
} else {
|
||||
count = segment.length;
|
||||
if (segment.dirty) {
|
||||
segments.last = segment.clone();
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < iterable.length; i++) {
|
||||
if (count == 0) {
|
||||
segments.add(CodeLineSegment.of(codeLines: []));
|
||||
}
|
||||
segments.last.add(iterable.elementAt(i));
|
||||
count++;
|
||||
if (count >= _kCodeLineSegamentDefaultSize) {
|
||||
count = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void addFrom(CodeLines codeLines, int start, [int? end]) {
|
||||
final CodeLines sub = codeLines.sublines(start, end);
|
||||
if (sub.isEmpty) {
|
||||
return;
|
||||
}
|
||||
if (isEmpty) {
|
||||
segments.addAll(sub.segments);
|
||||
return;
|
||||
}
|
||||
final List<CodeLineSegment> appendSegments = sub.segments;
|
||||
for (int i = 0; i < appendSegments.length; i++) {
|
||||
CodeLineSegment tail = segments.last;
|
||||
final CodeLineSegment appendSegment = appendSegments[i];
|
||||
if (tail.length + appendSegment.length <= _kCodeLineSegamentDefaultSize) {
|
||||
if (tail.dirty) {
|
||||
tail = tail.clone();
|
||||
segments.last = tail;
|
||||
}
|
||||
tail.addAll(appendSegment);
|
||||
} else {
|
||||
segments.add(appendSegment);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool equals(CodeLines? codeLines) {
|
||||
if (codeLines == null) {
|
||||
return false;
|
||||
}
|
||||
// Quick comparation
|
||||
if (isEmpty && codeLines.isEmpty) {
|
||||
return true;
|
||||
}
|
||||
if (isEmpty && codeLines.isNotEmpty) {
|
||||
return false;
|
||||
}
|
||||
if (isNotEmpty && codeLines.isEmpty) {
|
||||
return false;
|
||||
}
|
||||
if (first != codeLines.first) {
|
||||
return false;
|
||||
}
|
||||
if (last != codeLines.last) {
|
||||
return false;
|
||||
}
|
||||
final int length1 = length;
|
||||
final int length2 = codeLines.length;
|
||||
if (length1 != length2) {
|
||||
return false;
|
||||
}
|
||||
final int minSegmentLength = min(segments.length, codeLines.segments.length);
|
||||
int offset = 0;
|
||||
for (int i = 0; i < minSegmentLength; i++) {
|
||||
if (segments[i].length != codeLines.segments[i].length) {
|
||||
break;
|
||||
}
|
||||
if (!listEquals(segments[i].codeLines, codeLines.segments[i].codeLines)) {
|
||||
return false;
|
||||
}
|
||||
offset += segments[i].length;
|
||||
}
|
||||
// The worst is the distributions are different, we should compare them one by one
|
||||
for (int i = offset; i < length1; i++) {
|
||||
if (this[i] != codeLines[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
CodeLines sublines(int start, [int? end]) {
|
||||
end ??= length;
|
||||
if (end > length) {
|
||||
throw RangeError.range(end, 0, length - 1);
|
||||
}
|
||||
if (start > end) {
|
||||
throw RangeError('start $start should be less than end $end');
|
||||
}
|
||||
if (start == end) {
|
||||
return CodeLines.empty();
|
||||
}
|
||||
final List<CodeLineSegment> newSegments = [];
|
||||
int offset = 0;
|
||||
for (final CodeLineSegment segment in segments) {
|
||||
if (start - offset >= segment.length) {
|
||||
offset += segment.length;
|
||||
continue;
|
||||
}
|
||||
if (start <= offset) {
|
||||
if (end - offset >= segment.length) {
|
||||
newSegments.add(segment.copyWith(
|
||||
dirty: true
|
||||
));
|
||||
offset += segment.length;
|
||||
continue;
|
||||
} else {
|
||||
if (end > offset) {
|
||||
newSegments.add(segment.clone(0, end - offset));
|
||||
}
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
if (end - offset >= segment.length) {
|
||||
newSegments.add(segment.clone(start - offset, segment.length));
|
||||
offset += segment.length;
|
||||
continue;
|
||||
} else {
|
||||
newSegments.add(segment.clone(start - offset, end - offset));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return CodeLines(newSegments);
|
||||
}
|
||||
|
||||
void clear() {
|
||||
segments.clear();
|
||||
}
|
||||
|
||||
String asString(TextLineBreak lineBreak, [bool expandChunks = true]) {
|
||||
final StringBuffer sb = StringBuffer();
|
||||
final int length = this.length;
|
||||
int count = 0;
|
||||
for (final CodeLineSegment segment in segments) {
|
||||
for (final CodeLine codeLine in segment.codeLines) {
|
||||
count++;
|
||||
if (expandChunks) {
|
||||
sb.write(codeLine.asString(0, lineBreak));
|
||||
} else {
|
||||
sb.write(codeLine.text);
|
||||
}
|
||||
if (count != length) {
|
||||
sb.write(lineBreak.value);
|
||||
}
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
int index2lineIndex(int index) {
|
||||
if (index < 0 || index >= length) {
|
||||
return -1;
|
||||
}
|
||||
int lineIndex = 0;
|
||||
int offset = 0;
|
||||
for (final CodeLineSegment segment in segments) {
|
||||
if (index - offset >= segment.length) {
|
||||
offset += segment.length;
|
||||
lineIndex += segment.lineCount;
|
||||
} else {
|
||||
for (int j = 0; j < index - offset; j++) {
|
||||
lineIndex += segment[j].lineCount;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
return lineIndex;
|
||||
}
|
||||
|
||||
CodeLineIndex lineIndex2Index(int lineIndex) {
|
||||
if (lineIndex < 0) {
|
||||
return const CodeLineIndex(-1, -1);
|
||||
}
|
||||
// Find the segment first
|
||||
int segmentIndex = -1;
|
||||
int lineCount = 0;
|
||||
for (int i = 0, start = 0; i < segments.length; i++) {
|
||||
final int end = start + segments[i].lineCount;
|
||||
if (lineIndex >= start && lineIndex < end) {
|
||||
segmentIndex = i;
|
||||
lineIndex -= start;
|
||||
break;
|
||||
}
|
||||
start = end;
|
||||
lineCount += segments[i].length;
|
||||
}
|
||||
if (segmentIndex < 0) {
|
||||
return const CodeLineIndex(-1, -1);
|
||||
}
|
||||
// Find the index in the segment
|
||||
final List<CodeLine> codeLines = segments[segmentIndex].codeLines;
|
||||
int index = -1;
|
||||
int start = 0;
|
||||
for (int i = 0; i < codeLines.length; i++) {
|
||||
final int end = start + codeLines[i].lineCount;
|
||||
if (lineIndex >= start && lineIndex < end) {
|
||||
index = i;
|
||||
start++;
|
||||
break;
|
||||
}
|
||||
start = end;
|
||||
}
|
||||
if (index == -1) {
|
||||
return const CodeLineIndex(-1, -1);
|
||||
}
|
||||
// Find the index in the chunk
|
||||
int chunkIndex = -1;
|
||||
final List<CodeLine> chunks = codeLines[index].chunks;
|
||||
for (int i = 0; i < chunks.length; i++) {
|
||||
final int end = start + chunks[i].lineCount;
|
||||
if (lineIndex >= start && lineIndex < end) {
|
||||
chunkIndex = i;
|
||||
break;
|
||||
}
|
||||
start = end;
|
||||
}
|
||||
return CodeLineIndex(index + lineCount, chunkIndex);
|
||||
}
|
||||
|
||||
List<CodeLine> toList() {
|
||||
final List<CodeLine> codeLines = [];
|
||||
for (final CodeLineSegment segment in segments) {
|
||||
codeLines.addAll(segment.codeLines);
|
||||
}
|
||||
return codeLines;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode => segments.hashCode;
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
if (identical(this, other)) {
|
||||
return true;
|
||||
}
|
||||
return other is CodeLines
|
||||
&& listEquals(other.segments, segments);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return '[ ${segments.join(',')} ]';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class CodeLineSegment with ListMixin<CodeLine> {
|
||||
|
||||
final List<CodeLine> codeLines;
|
||||
final bool dirty;
|
||||
|
||||
const CodeLineSegment({
|
||||
required this.codeLines,
|
||||
this.dirty = false
|
||||
});
|
||||
|
||||
factory CodeLineSegment.of({
|
||||
required List<CodeLine> codeLines,
|
||||
bool dirty = false
|
||||
}) => _CodeLineSegmentQuckLineCount(
|
||||
codeLines: codeLines,
|
||||
dirty: dirty
|
||||
);
|
||||
|
||||
@override
|
||||
int get length => codeLines.length;
|
||||
|
||||
int get lineCount => codeLines.fold(0, (previousValue, element) => previousValue += element.lineCount);
|
||||
|
||||
@override
|
||||
CodeLine operator [](int index) {
|
||||
return codeLines[index];
|
||||
}
|
||||
|
||||
@override
|
||||
void operator []=(int index, CodeLine value) {
|
||||
if (dirty) {
|
||||
// Not support write operation
|
||||
throw UnimplementedError();
|
||||
} else {
|
||||
codeLines[index] = value;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
set length(int newLength) {
|
||||
if (dirty) {
|
||||
// Not support write operation
|
||||
throw UnimplementedError();
|
||||
} else {
|
||||
codeLines.length = newLength;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void add(CodeLine element) {
|
||||
if (dirty) {
|
||||
// Not support write operation
|
||||
throw UnimplementedError();
|
||||
} else {
|
||||
codeLines.add(element);
|
||||
}
|
||||
}
|
||||
|
||||
CodeLineSegment clone([int start = 0, int? end]) => CodeLineSegment.of(
|
||||
codeLines: codeLines.sublist(start, end)
|
||||
);
|
||||
|
||||
CodeLineSegment copyWith({
|
||||
List<CodeLine>? codeLines,
|
||||
bool? dirty,
|
||||
}) {
|
||||
return CodeLineSegment.of(
|
||||
codeLines: codeLines ?? this.codeLines,
|
||||
dirty: dirty ?? this.dirty
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(codeLines, lineCount, dirty);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
if (identical(this, other)) {
|
||||
return true;
|
||||
}
|
||||
return other is CodeLineSegment
|
||||
&& listEquals(other.codeLines, codeLines)
|
||||
&& other.lineCount == lineCount
|
||||
&& other.dirty == dirty;
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return '[ ${join(',')} ]';
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
part of re_editor;
|
||||
|
||||
abstract class IParagraph {
|
||||
|
||||
double get width;
|
||||
double get height;
|
||||
double get preferredLineHeight;
|
||||
bool get trucated;
|
||||
int get length;
|
||||
int get lineCount;
|
||||
|
||||
void draw(Canvas canvas, Offset offset);
|
||||
|
||||
TextPosition getPosition(Offset offset);
|
||||
|
||||
TextRange getWord(Offset offset);
|
||||
|
||||
InlineSpan? getSpanForPosition(TextPosition position);
|
||||
|
||||
TextRange getRangeForSpan(InlineSpan span);
|
||||
|
||||
TextRange getLineBoundary(TextPosition position);
|
||||
|
||||
Offset? getOffset(TextPosition position);
|
||||
|
||||
List<Rect> getRangeRects(TextRange range);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
part of re_editor;
|
||||
|
||||
typedef CodeScrollbarBuilder = Widget Function(BuildContext context, Widget child, ScrollableDetails details);
|
||||
|
||||
class CodeScrollController {
|
||||
|
||||
final ScrollController verticalScroller;
|
||||
final ScrollController horizontalScroller;
|
||||
|
||||
GlobalKey? _editorKey;
|
||||
|
||||
CodeScrollController({
|
||||
ScrollController? verticalScroller,
|
||||
ScrollController? horizontalScroller,
|
||||
}) : verticalScroller = verticalScroller ?? ScrollController(),
|
||||
horizontalScroller = horizontalScroller ?? ScrollController();
|
||||
|
||||
void makeCenterIfInvisible(CodeLinePosition position) {
|
||||
_render?.makePositionCenterIfInvisible(position);
|
||||
}
|
||||
|
||||
void makeVisible(CodeLinePosition position) {
|
||||
_render?.makePositionVisible(position);
|
||||
}
|
||||
|
||||
void bindEditor(GlobalKey key) {
|
||||
_editorKey = key;
|
||||
}
|
||||
|
||||
_CodeFieldRender? get _render => _editorKey?.currentContext?.findRenderObject() as _CodeFieldRender?;
|
||||
|
||||
void dispose() {
|
||||
_editorKey = null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,605 @@
|
||||
part of re_editor;
|
||||
|
||||
enum CodeShortcutType {
|
||||
selectAll,
|
||||
cut,
|
||||
copy,
|
||||
paste,
|
||||
delete,
|
||||
backspace,
|
||||
undo,
|
||||
redo,
|
||||
lineSelect,
|
||||
lineDelete,
|
||||
lineDeleteForward,
|
||||
lineDeleteBackward,
|
||||
lineMoveUp,
|
||||
lineMoveDown,
|
||||
cursorMoveUp,
|
||||
cursorMoveDown,
|
||||
cursorMoveForward,
|
||||
cursorMoveBackward,
|
||||
cursorMoveLineStart,
|
||||
cursorMoveLineEnd,
|
||||
cursorMovePageStart,
|
||||
cursorMovePageEnd,
|
||||
cursorMovePageUp,
|
||||
cursorMovePageDown,
|
||||
cursorMoveWordBoundaryForward,
|
||||
cursorMoveWordBoundaryBackward,
|
||||
selectionExtendUp,
|
||||
selectionExtendDown,
|
||||
selectionExtendForward,
|
||||
selectionExtendBackward,
|
||||
selectionExtendLineStart,
|
||||
selectionExtendLineEnd,
|
||||
selectionExtendPageStart,
|
||||
selectionExtendPageEnd,
|
||||
selectionExtendWordBoundaryForward,
|
||||
selectionExtendWordBoundaryBackward,
|
||||
wordDeleteForward,
|
||||
wordDeleteBackward,
|
||||
indent,
|
||||
outdent,
|
||||
newLine,
|
||||
transposeCharacters,
|
||||
singleLineComment,
|
||||
multiLineComment,
|
||||
find,
|
||||
findToggleMatchCase,
|
||||
findToggleRegex,
|
||||
replace,
|
||||
save,
|
||||
esc,
|
||||
}
|
||||
|
||||
abstract class CodeShortcutsActivatorsBuilder {
|
||||
|
||||
const CodeShortcutsActivatorsBuilder();
|
||||
|
||||
List<ShortcutActivator>? build(CodeShortcutType type);
|
||||
|
||||
}
|
||||
|
||||
class DefaultCodeShortcutsActivatorsBuilder extends CodeShortcutsActivatorsBuilder {
|
||||
|
||||
const DefaultCodeShortcutsActivatorsBuilder();
|
||||
|
||||
@override
|
||||
List<ShortcutActivator>? build(CodeShortcutType type) {
|
||||
return kIsMacOS ? _kDefaultMacCodeShortcutsActivators[type] :
|
||||
_kDefaultCommonCodeShortcutsActivators[type];
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
abstract class CodeShortcutEditableIntent extends Intent {
|
||||
const CodeShortcutEditableIntent();
|
||||
}
|
||||
|
||||
class CodeShortcutSelectAllIntent extends Intent {
|
||||
const CodeShortcutSelectAllIntent();
|
||||
}
|
||||
|
||||
class CodeShortcutCopyIntent extends Intent {
|
||||
const CodeShortcutCopyIntent();
|
||||
}
|
||||
|
||||
class CodeShortcutCutIntent extends CodeShortcutEditableIntent {
|
||||
const CodeShortcutCutIntent();
|
||||
}
|
||||
|
||||
class CodeShortcutPasteIntent extends CodeShortcutEditableIntent {
|
||||
const CodeShortcutPasteIntent();
|
||||
}
|
||||
|
||||
class CodeShortcutUndoIntent extends CodeShortcutEditableIntent {
|
||||
const CodeShortcutUndoIntent();
|
||||
}
|
||||
|
||||
class CodeShortcutRedoIntent extends CodeShortcutEditableIntent {
|
||||
const CodeShortcutRedoIntent();
|
||||
}
|
||||
|
||||
class CodeShortcutLineSelectIntent extends Intent {
|
||||
const CodeShortcutLineSelectIntent();
|
||||
}
|
||||
|
||||
class ShortcutLineDeleteIntent extends CodeShortcutEditableIntent {
|
||||
const ShortcutLineDeleteIntent();
|
||||
}
|
||||
|
||||
class ShortcutLineMoveIntent extends CodeShortcutEditableIntent {
|
||||
final VerticalDirection direction;
|
||||
const ShortcutLineMoveIntent(this.direction);
|
||||
}
|
||||
|
||||
class ShortcutLineDeleteDirectionIntent extends CodeShortcutEditableIntent {
|
||||
final bool forward;
|
||||
const ShortcutLineDeleteDirectionIntent(this.forward);
|
||||
}
|
||||
|
||||
class CodeShortcutIndentIntent extends CodeShortcutEditableIntent {
|
||||
const CodeShortcutIndentIntent();
|
||||
}
|
||||
|
||||
class CodeShortcutOutdentIntent extends CodeShortcutEditableIntent {
|
||||
const CodeShortcutOutdentIntent();
|
||||
}
|
||||
|
||||
class CodeShortcutCommentIntent extends CodeShortcutEditableIntent {
|
||||
final bool single;
|
||||
const CodeShortcutCommentIntent(this.single);
|
||||
}
|
||||
|
||||
class CodeShortcutCursorMoveIntent extends Intent {
|
||||
final AxisDirection direction;
|
||||
const CodeShortcutCursorMoveIntent(this.direction);
|
||||
}
|
||||
|
||||
class CodeShortcutCursorMoveLineEdgeIntent extends Intent {
|
||||
final bool forward;
|
||||
const CodeShortcutCursorMoveLineEdgeIntent(this.forward);
|
||||
}
|
||||
|
||||
class CodeShortcutCursorMoveDocEdgeIntent extends Intent {
|
||||
final bool forward;
|
||||
const CodeShortcutCursorMoveDocEdgeIntent(this.forward);
|
||||
}
|
||||
|
||||
class CodeShortcutCursorMovePageIntent extends Intent {
|
||||
final bool forward;
|
||||
const CodeShortcutCursorMovePageIntent(this.forward);
|
||||
}
|
||||
|
||||
class CodeShortcutCursorMoveWordBoundaryIntent extends Intent {
|
||||
final bool forward;
|
||||
const CodeShortcutCursorMoveWordBoundaryIntent(this.forward);
|
||||
}
|
||||
|
||||
class CodeShortcutSelectionExtendIntent extends Intent {
|
||||
final AxisDirection direction;
|
||||
const CodeShortcutSelectionExtendIntent(this.direction);
|
||||
}
|
||||
|
||||
class CodeShortcutSelectionExtendLineEdgeIntent extends Intent {
|
||||
final bool forward;
|
||||
const CodeShortcutSelectionExtendLineEdgeIntent(this.forward);
|
||||
}
|
||||
|
||||
class CodeShortcutSelectionExtendPageEdgeIntent extends Intent {
|
||||
final bool forward;
|
||||
const CodeShortcutSelectionExtendPageEdgeIntent(this.forward);
|
||||
}
|
||||
|
||||
class CodeShortcutSelectionExtendWordBoundaryIntent extends Intent {
|
||||
final bool forward;
|
||||
const CodeShortcutSelectionExtendWordBoundaryIntent(this.forward);
|
||||
}
|
||||
|
||||
class ShortcutWordDeleteDirectionIntent extends CodeShortcutEditableIntent {
|
||||
final bool forward;
|
||||
const ShortcutWordDeleteDirectionIntent(this.forward);
|
||||
}
|
||||
|
||||
class CodeShortcutDeleteIntent extends CodeShortcutEditableIntent {
|
||||
final bool forward;
|
||||
const CodeShortcutDeleteIntent(this.forward);
|
||||
}
|
||||
|
||||
class CodeShortcutNewLineIntent extends CodeShortcutEditableIntent {
|
||||
const CodeShortcutNewLineIntent();
|
||||
}
|
||||
|
||||
class CodeShortcutTransposeCharactersIntent extends CodeShortcutEditableIntent {
|
||||
const CodeShortcutTransposeCharactersIntent();
|
||||
}
|
||||
|
||||
class CodeShortcutFindIntent extends Intent {
|
||||
const CodeShortcutFindIntent();
|
||||
}
|
||||
|
||||
class CodeShortcutFindToggleMatchCaseIntent extends Intent {
|
||||
const CodeShortcutFindToggleMatchCaseIntent();
|
||||
}
|
||||
|
||||
class CodeShortcutFindToggleRegexIntent extends Intent {
|
||||
const CodeShortcutFindToggleRegexIntent();
|
||||
}
|
||||
|
||||
class CodeShortcutReplaceIntent extends CodeShortcutEditableIntent {
|
||||
const CodeShortcutReplaceIntent();
|
||||
}
|
||||
|
||||
class CodeShortcutSaveIntent extends Intent {
|
||||
const CodeShortcutSaveIntent();
|
||||
}
|
||||
|
||||
class CodeShortcutEscIntent extends Intent {
|
||||
const CodeShortcutEscIntent();
|
||||
}
|
||||
|
||||
const Map<CodeShortcutType, Intent> kCodeShortcutIntents = {
|
||||
CodeShortcutType.selectAll: CodeShortcutSelectAllIntent(),
|
||||
CodeShortcutType.cut: CodeShortcutCutIntent(),
|
||||
CodeShortcutType.copy: CodeShortcutCopyIntent(),
|
||||
CodeShortcutType.paste: CodeShortcutPasteIntent(),
|
||||
CodeShortcutType.delete: CodeShortcutDeleteIntent(true),
|
||||
CodeShortcutType.backspace: CodeShortcutDeleteIntent(false),
|
||||
CodeShortcutType.undo: CodeShortcutUndoIntent(),
|
||||
CodeShortcutType.redo: CodeShortcutRedoIntent(),
|
||||
CodeShortcutType.lineSelect: CodeShortcutLineSelectIntent(),
|
||||
CodeShortcutType.lineDelete: ShortcutLineDeleteIntent(),
|
||||
CodeShortcutType.lineDeleteForward: ShortcutLineDeleteDirectionIntent(true),
|
||||
CodeShortcutType.lineDeleteBackward: ShortcutLineDeleteDirectionIntent(false),
|
||||
CodeShortcutType.lineMoveUp: ShortcutLineMoveIntent(VerticalDirection.up),
|
||||
CodeShortcutType.lineMoveDown: ShortcutLineMoveIntent(VerticalDirection.down),
|
||||
CodeShortcutType.cursorMoveUp: CodeShortcutCursorMoveIntent(AxisDirection.up),
|
||||
CodeShortcutType.cursorMoveDown: CodeShortcutCursorMoveIntent(AxisDirection.down),
|
||||
CodeShortcutType.cursorMoveForward: CodeShortcutCursorMoveIntent(AxisDirection.right),
|
||||
CodeShortcutType.cursorMoveBackward: CodeShortcutCursorMoveIntent(AxisDirection.left),
|
||||
CodeShortcutType.cursorMoveLineStart: CodeShortcutCursorMoveLineEdgeIntent(false),
|
||||
CodeShortcutType.cursorMoveLineEnd: CodeShortcutCursorMoveLineEdgeIntent(true),
|
||||
CodeShortcutType.cursorMovePageStart: CodeShortcutCursorMoveDocEdgeIntent(false),
|
||||
CodeShortcutType.cursorMovePageEnd: CodeShortcutCursorMoveDocEdgeIntent(true),
|
||||
CodeShortcutType.cursorMovePageUp: CodeShortcutCursorMovePageIntent(false),
|
||||
CodeShortcutType.cursorMovePageDown: CodeShortcutCursorMovePageIntent(true),
|
||||
CodeShortcutType.cursorMoveWordBoundaryForward: CodeShortcutCursorMoveWordBoundaryIntent(true),
|
||||
CodeShortcutType.cursorMoveWordBoundaryBackward: CodeShortcutCursorMoveWordBoundaryIntent(false),
|
||||
CodeShortcutType.selectionExtendUp: CodeShortcutSelectionExtendIntent(AxisDirection.up),
|
||||
CodeShortcutType.selectionExtendDown: CodeShortcutSelectionExtendIntent(AxisDirection.down),
|
||||
CodeShortcutType.selectionExtendForward: CodeShortcutSelectionExtendIntent(AxisDirection.right),
|
||||
CodeShortcutType.selectionExtendBackward: CodeShortcutSelectionExtendIntent(AxisDirection.left),
|
||||
CodeShortcutType.selectionExtendLineStart: CodeShortcutSelectionExtendLineEdgeIntent(false),
|
||||
CodeShortcutType.selectionExtendLineEnd: CodeShortcutSelectionExtendLineEdgeIntent(true),
|
||||
CodeShortcutType.selectionExtendPageStart: CodeShortcutSelectionExtendPageEdgeIntent(false),
|
||||
CodeShortcutType.selectionExtendPageEnd: CodeShortcutSelectionExtendPageEdgeIntent(true),
|
||||
CodeShortcutType.selectionExtendWordBoundaryForward: CodeShortcutSelectionExtendWordBoundaryIntent(true),
|
||||
CodeShortcutType.selectionExtendWordBoundaryBackward: CodeShortcutSelectionExtendWordBoundaryIntent(false),
|
||||
CodeShortcutType.wordDeleteForward: ShortcutWordDeleteDirectionIntent(true),
|
||||
CodeShortcutType.wordDeleteBackward: ShortcutWordDeleteDirectionIntent(false),
|
||||
CodeShortcutType.indent: CodeShortcutIndentIntent(),
|
||||
CodeShortcutType.outdent: CodeShortcutOutdentIntent(),
|
||||
CodeShortcutType.newLine: CodeShortcutNewLineIntent(),
|
||||
CodeShortcutType.transposeCharacters: CodeShortcutTransposeCharactersIntent(),
|
||||
CodeShortcutType.singleLineComment: CodeShortcutCommentIntent(true),
|
||||
CodeShortcutType.multiLineComment: CodeShortcutCommentIntent(false),
|
||||
CodeShortcutType.find: CodeShortcutFindIntent(),
|
||||
CodeShortcutType.findToggleMatchCase: CodeShortcutFindToggleMatchCaseIntent(),
|
||||
CodeShortcutType.findToggleRegex: CodeShortcutFindToggleRegexIntent(),
|
||||
CodeShortcutType.replace: CodeShortcutReplaceIntent(),
|
||||
CodeShortcutType.save: CodeShortcutSaveIntent(),
|
||||
CodeShortcutType.esc: CodeShortcutEscIntent(),
|
||||
};
|
||||
|
||||
const Map<CodeShortcutType, List<ShortcutActivator>> _kDefaultMacCodeShortcutsActivators = {
|
||||
CodeShortcutType.selectAll: [
|
||||
SingleActivator(LogicalKeyboardKey.keyA, meta: true)
|
||||
],
|
||||
CodeShortcutType.cut: [
|
||||
SingleActivator(LogicalKeyboardKey.keyX, meta: true)
|
||||
],
|
||||
CodeShortcutType.copy: [
|
||||
SingleActivator(LogicalKeyboardKey.keyC, meta: true)
|
||||
],
|
||||
CodeShortcutType.paste: [
|
||||
SingleActivator(LogicalKeyboardKey.keyV, meta: true)
|
||||
],
|
||||
CodeShortcutType.delete: [
|
||||
SingleActivator(LogicalKeyboardKey.delete,),
|
||||
SingleActivator(LogicalKeyboardKey.delete, shift: true),
|
||||
],
|
||||
CodeShortcutType.backspace: [
|
||||
SingleActivator(LogicalKeyboardKey.backspace,),
|
||||
SingleActivator(LogicalKeyboardKey.backspace, shift: true),
|
||||
],
|
||||
CodeShortcutType.undo: [
|
||||
SingleActivator(LogicalKeyboardKey.keyZ, meta: true)
|
||||
],
|
||||
CodeShortcutType.redo: [
|
||||
SingleActivator(LogicalKeyboardKey.keyZ, meta: true, shift: true)
|
||||
],
|
||||
CodeShortcutType.lineSelect: [
|
||||
SingleActivator(LogicalKeyboardKey.keyL, meta: true)
|
||||
],
|
||||
CodeShortcutType.lineDelete: [
|
||||
SingleActivator(LogicalKeyboardKey.keyD, meta: true)
|
||||
],
|
||||
CodeShortcutType.lineDeleteForward: [
|
||||
SingleActivator(LogicalKeyboardKey.delete, meta: true)
|
||||
],
|
||||
CodeShortcutType.lineDeleteBackward: [
|
||||
SingleActivator(LogicalKeyboardKey.backspace, meta: true)
|
||||
],
|
||||
CodeShortcutType.lineMoveUp: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowUp, alt: true)
|
||||
],
|
||||
CodeShortcutType.lineMoveDown: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowDown, alt: true)
|
||||
],
|
||||
CodeShortcutType.cursorMoveUp: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowUp)
|
||||
],
|
||||
CodeShortcutType.cursorMoveDown: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowDown)
|
||||
],
|
||||
CodeShortcutType.cursorMoveForward: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowRight)
|
||||
],
|
||||
CodeShortcutType.cursorMoveBackward: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowLeft)
|
||||
],
|
||||
CodeShortcutType.cursorMoveLineStart: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true),
|
||||
SingleActivator(LogicalKeyboardKey.home)
|
||||
],
|
||||
CodeShortcutType.cursorMoveLineEnd: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowRight, meta: true),
|
||||
SingleActivator(LogicalKeyboardKey.end),
|
||||
],
|
||||
CodeShortcutType.cursorMovePageStart: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowUp, meta: true),
|
||||
SingleActivator(LogicalKeyboardKey.home, control: true)
|
||||
],
|
||||
CodeShortcutType.cursorMovePageEnd: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowDown, meta: true),
|
||||
SingleActivator(LogicalKeyboardKey.end, control: true)
|
||||
],
|
||||
CodeShortcutType.cursorMoveWordBoundaryBackward: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true)
|
||||
],
|
||||
CodeShortcutType.cursorMoveWordBoundaryForward: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowRight, alt: true)
|
||||
],
|
||||
CodeShortcutType.selectionExtendUp: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowUp, shift: true)
|
||||
],
|
||||
CodeShortcutType.selectionExtendDown: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowDown, shift: true)
|
||||
],
|
||||
CodeShortcutType.selectionExtendForward: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowRight, shift: true)
|
||||
],
|
||||
CodeShortcutType.selectionExtendBackward: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true)
|
||||
],
|
||||
CodeShortcutType.selectionExtendPageStart: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowUp, shift: true, meta: true),
|
||||
SingleActivator(LogicalKeyboardKey.home, shift: true, meta: true)
|
||||
],
|
||||
CodeShortcutType.selectionExtendPageEnd: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowDown, shift: true, meta: true),
|
||||
SingleActivator(LogicalKeyboardKey.end, shift: true, meta: true)
|
||||
],
|
||||
CodeShortcutType.selectionExtendLineStart: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, meta: true),
|
||||
SingleActivator(LogicalKeyboardKey.home, shift: true)
|
||||
],
|
||||
CodeShortcutType.selectionExtendLineEnd: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, meta: true),
|
||||
SingleActivator(LogicalKeyboardKey.end, shift: true)
|
||||
],
|
||||
CodeShortcutType.selectionExtendWordBoundaryForward: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: true)
|
||||
],
|
||||
CodeShortcutType.selectionExtendWordBoundaryBackward: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: true)
|
||||
],
|
||||
CodeShortcutType.wordDeleteForward: [
|
||||
SingleActivator(LogicalKeyboardKey.delete, alt: true),
|
||||
SingleActivator(LogicalKeyboardKey.delete, alt: true, shift: true),
|
||||
SingleActivator(LogicalKeyboardKey.delete, meta: true, shift: true)
|
||||
],
|
||||
CodeShortcutType.wordDeleteBackward: [
|
||||
SingleActivator(LogicalKeyboardKey.backspace, alt: true),
|
||||
SingleActivator(LogicalKeyboardKey.backspace, alt: true, shift: true),
|
||||
SingleActivator(LogicalKeyboardKey.backspace, meta: true, shift: true)
|
||||
],
|
||||
CodeShortcutType.indent: [
|
||||
SingleActivator(LogicalKeyboardKey.tab)
|
||||
],
|
||||
CodeShortcutType.outdent: [
|
||||
SingleActivator(LogicalKeyboardKey.tab, shift: true)
|
||||
],
|
||||
CodeShortcutType.newLine: [
|
||||
SingleActivator(LogicalKeyboardKey.enter),
|
||||
SingleActivator(LogicalKeyboardKey.enter, shift: true),
|
||||
SingleActivator(LogicalKeyboardKey.enter, meta: true),
|
||||
SingleActivator(LogicalKeyboardKey.enter, meta: true, shift: true),
|
||||
SingleActivator(LogicalKeyboardKey.numpadEnter),
|
||||
SingleActivator(LogicalKeyboardKey.numpadEnter, shift: true),
|
||||
SingleActivator(LogicalKeyboardKey.numpadEnter, meta: true),
|
||||
SingleActivator(LogicalKeyboardKey.numpadEnter, meta: true, shift: true)
|
||||
],
|
||||
CodeShortcutType.transposeCharacters: [
|
||||
SingleActivator(LogicalKeyboardKey.keyT, control: true)
|
||||
],
|
||||
CodeShortcutType.singleLineComment: [
|
||||
SingleActivator(LogicalKeyboardKey.slash, meta: true)
|
||||
],
|
||||
CodeShortcutType.multiLineComment: [
|
||||
SingleActivator(LogicalKeyboardKey.slash, meta: true, shift: true)
|
||||
],
|
||||
CodeShortcutType.find: [
|
||||
SingleActivator(LogicalKeyboardKey.keyF, meta: true)
|
||||
],
|
||||
CodeShortcutType.findToggleMatchCase: [
|
||||
SingleActivator(LogicalKeyboardKey.keyC, meta: true, alt: true)
|
||||
],
|
||||
CodeShortcutType.findToggleRegex: [
|
||||
SingleActivator(LogicalKeyboardKey.keyR, meta: true, alt: true)
|
||||
],
|
||||
CodeShortcutType.replace: [
|
||||
SingleActivator(LogicalKeyboardKey.keyF, meta: true, alt: true)
|
||||
],
|
||||
CodeShortcutType.save: [
|
||||
SingleActivator(LogicalKeyboardKey.keyS, meta: true)
|
||||
],
|
||||
CodeShortcutType.esc: [
|
||||
SingleActivator(LogicalKeyboardKey.escape)
|
||||
],
|
||||
};
|
||||
|
||||
const Map<CodeShortcutType, List<ShortcutActivator>> _kDefaultCommonCodeShortcutsActivators = {
|
||||
CodeShortcutType.selectAll: [
|
||||
SingleActivator(LogicalKeyboardKey.keyA, control: true)
|
||||
],
|
||||
CodeShortcutType.cut: [
|
||||
SingleActivator(LogicalKeyboardKey.keyX, control: true)
|
||||
],
|
||||
CodeShortcutType.copy: [
|
||||
SingleActivator(LogicalKeyboardKey.keyC, control: true)
|
||||
],
|
||||
CodeShortcutType.paste: [
|
||||
SingleActivator(LogicalKeyboardKey.keyV, control: true)
|
||||
],
|
||||
CodeShortcutType.delete: [
|
||||
SingleActivator(LogicalKeyboardKey.delete,),
|
||||
SingleActivator(LogicalKeyboardKey.delete, shift: true),
|
||||
],
|
||||
CodeShortcutType.backspace: [
|
||||
SingleActivator(LogicalKeyboardKey.backspace,),
|
||||
SingleActivator(LogicalKeyboardKey.backspace, shift: true),
|
||||
],
|
||||
CodeShortcutType.undo: [
|
||||
SingleActivator(LogicalKeyboardKey.keyZ, control: true)
|
||||
],
|
||||
CodeShortcutType.redo: [
|
||||
SingleActivator(LogicalKeyboardKey.keyZ, control: true, shift: true)
|
||||
],
|
||||
CodeShortcutType.lineSelect: [
|
||||
SingleActivator(LogicalKeyboardKey.keyL, control: true)
|
||||
],
|
||||
CodeShortcutType.lineDelete: [
|
||||
SingleActivator(LogicalKeyboardKey.keyD, control: true)
|
||||
],
|
||||
CodeShortcutType.lineDeleteForward: [
|
||||
SingleActivator(LogicalKeyboardKey.delete, control: true)
|
||||
],
|
||||
CodeShortcutType.lineDeleteBackward: [
|
||||
SingleActivator(LogicalKeyboardKey.backspace, control: true)
|
||||
],
|
||||
CodeShortcutType.lineMoveUp: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowUp, alt: true)
|
||||
],
|
||||
CodeShortcutType.lineMoveDown: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowDown, alt: true)
|
||||
],
|
||||
CodeShortcutType.cursorMoveUp: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowUp)
|
||||
],
|
||||
CodeShortcutType.cursorMoveDown: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowDown)
|
||||
],
|
||||
CodeShortcutType.cursorMoveForward: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowRight)
|
||||
],
|
||||
CodeShortcutType.cursorMoveBackward: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowLeft)
|
||||
],
|
||||
CodeShortcutType.cursorMoveLineStart: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowLeft, control: true),
|
||||
SingleActivator(LogicalKeyboardKey.home)
|
||||
],
|
||||
CodeShortcutType.cursorMoveLineEnd: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowRight, control: true),
|
||||
SingleActivator(LogicalKeyboardKey.end)
|
||||
],
|
||||
CodeShortcutType.cursorMovePageStart: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowUp, control: true),
|
||||
SingleActivator(LogicalKeyboardKey.home, control: true)
|
||||
],
|
||||
CodeShortcutType.cursorMovePageEnd: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowDown, control: true),
|
||||
SingleActivator(LogicalKeyboardKey.end, control: true)
|
||||
],
|
||||
CodeShortcutType.cursorMoveWordBoundaryBackward: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true)
|
||||
],
|
||||
CodeShortcutType.cursorMoveWordBoundaryForward: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowRight, alt: true)
|
||||
],
|
||||
CodeShortcutType.selectionExtendUp: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowUp, shift: true)
|
||||
],
|
||||
CodeShortcutType.selectionExtendDown: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowDown, shift: true)
|
||||
],
|
||||
CodeShortcutType.selectionExtendForward: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowRight, shift: true)
|
||||
],
|
||||
CodeShortcutType.selectionExtendBackward: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true)
|
||||
],
|
||||
CodeShortcutType.selectionExtendPageStart: [
|
||||
SingleActivator(LogicalKeyboardKey.home, shift: true, control: true)
|
||||
],
|
||||
CodeShortcutType.selectionExtendPageEnd: [
|
||||
SingleActivator(LogicalKeyboardKey.end, shift: true, control: true)
|
||||
],
|
||||
CodeShortcutType.selectionExtendLineStart: [
|
||||
SingleActivator(LogicalKeyboardKey.home, shift: true)
|
||||
],
|
||||
CodeShortcutType.selectionExtendLineEnd: [
|
||||
SingleActivator(LogicalKeyboardKey.end, shift: true)
|
||||
],
|
||||
CodeShortcutType.selectionExtendWordBoundaryForward: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: true)
|
||||
],
|
||||
CodeShortcutType.selectionExtendWordBoundaryBackward: [
|
||||
SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: true)
|
||||
],
|
||||
CodeShortcutType.wordDeleteForward: [
|
||||
SingleActivator(LogicalKeyboardKey.delete, alt: true),
|
||||
SingleActivator(LogicalKeyboardKey.delete, alt: true, shift: true),
|
||||
SingleActivator(LogicalKeyboardKey.delete, control: true),
|
||||
],
|
||||
CodeShortcutType.wordDeleteBackward: [
|
||||
SingleActivator(LogicalKeyboardKey.backspace, alt: true),
|
||||
SingleActivator(LogicalKeyboardKey.backspace, alt: true, shift: true),
|
||||
SingleActivator(LogicalKeyboardKey.backspace, control: true),
|
||||
],
|
||||
CodeShortcutType.indent: [
|
||||
SingleActivator(LogicalKeyboardKey.tab)
|
||||
],
|
||||
CodeShortcutType.outdent: [
|
||||
SingleActivator(LogicalKeyboardKey.tab, shift: true)
|
||||
],
|
||||
CodeShortcutType.newLine: [
|
||||
SingleActivator(LogicalKeyboardKey.enter),
|
||||
SingleActivator(LogicalKeyboardKey.enter, shift: true),
|
||||
SingleActivator(LogicalKeyboardKey.enter, control: true),
|
||||
SingleActivator(LogicalKeyboardKey.enter, control: true, shift: true),
|
||||
SingleActivator(LogicalKeyboardKey.numpadEnter),
|
||||
SingleActivator(LogicalKeyboardKey.numpadEnter, shift: true),
|
||||
SingleActivator(LogicalKeyboardKey.numpadEnter, control: true),
|
||||
SingleActivator(LogicalKeyboardKey.numpadEnter, control: true, shift: true)
|
||||
],
|
||||
CodeShortcutType.transposeCharacters: [
|
||||
SingleActivator(LogicalKeyboardKey.keyT, control: true)
|
||||
],
|
||||
CodeShortcutType.singleLineComment: [
|
||||
SingleActivator(LogicalKeyboardKey.slash, control: true)
|
||||
],
|
||||
CodeShortcutType.multiLineComment: [
|
||||
SingleActivator(LogicalKeyboardKey.slash, control: true, shift: true)
|
||||
],
|
||||
CodeShortcutType.find: [
|
||||
SingleActivator(LogicalKeyboardKey.keyF, control: true)
|
||||
],
|
||||
CodeShortcutType.findToggleMatchCase: [
|
||||
SingleActivator(LogicalKeyboardKey.keyC, control: true, alt: true)
|
||||
],
|
||||
CodeShortcutType.findToggleRegex: [
|
||||
SingleActivator(LogicalKeyboardKey.keyR, control: true, alt: true)
|
||||
],
|
||||
CodeShortcutType.replace: [
|
||||
SingleActivator(LogicalKeyboardKey.keyF, control: true, alt: true)
|
||||
],
|
||||
CodeShortcutType.save: [
|
||||
SingleActivator(LogicalKeyboardKey.keyS, control: true)
|
||||
],
|
||||
CodeShortcutType.esc: [
|
||||
SingleActivator(LogicalKeyboardKey.escape)
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
part of re_editor;
|
||||
|
||||
typedef PointerEnterEventWithRectListener = void Function(PointerEnterEvent event, int id, List<Rect> rects);
|
||||
|
||||
typedef PointerExitEventWithRectListener = void Function(PointerExitEvent event, int id, List<Rect> rects);
|
||||
|
||||
@immutable
|
||||
class MouseTrackerAnnotationTextSpan extends TextSpan {
|
||||
|
||||
final PointerEnterEventWithRectListener onEnterWithRect;
|
||||
final PointerExitEventWithRectListener onExitWithRect;
|
||||
|
||||
const MouseTrackerAnnotationTextSpan({
|
||||
super.text,
|
||||
super.children,
|
||||
super.style,
|
||||
super.recognizer,
|
||||
super.mouseCursor,
|
||||
super.semanticsLabel,
|
||||
super.locale,
|
||||
super.spellOut,
|
||||
required this.onEnterWithRect,
|
||||
required this.onExitWithRect,
|
||||
});
|
||||
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
part of re_editor;
|
||||
|
||||
/// The code syntax highlighting theme. We use Re-Highlight as the syntax highlighting rule.
|
||||
/// Re-Highlight provides some built-in syntax highlighting rules for dozens of programming languages,
|
||||
/// and many theme styles.
|
||||
///
|
||||
/// Please see [Re-Highlight](https://reqable/re-highlight).
|
||||
class CodeHighlightTheme {
|
||||
|
||||
const CodeHighlightTheme({
|
||||
required this.languages,
|
||||
required this.theme,
|
||||
this.plugins = const [],
|
||||
});
|
||||
|
||||
/// Supported syntax highlighting language rules.
|
||||
final Map<String, CodeHighlightThemeMode> languages;
|
||||
|
||||
/// The syntax highlighting style theme.
|
||||
final Map<String, TextStyle> theme;
|
||||
|
||||
/// The plugins for syntax highlighting.
|
||||
final List<HLPlugin> plugins;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(languages, theme, plugins);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
if (identical(this, other)) {
|
||||
return true;
|
||||
}
|
||||
return other is CodeHighlightTheme
|
||||
&& mapEquals(other.languages, languages)
|
||||
&& mapEquals(other.theme, theme)
|
||||
&& listEquals(other.plugins, plugins);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// Define language rules and restrictions for highlighting.
|
||||
///
|
||||
/// Since the dart stack capacity is relatively small, stack overflow may occur
|
||||
/// when executing syntax highlighting, so we added some restrictions to disable
|
||||
/// syntax highlighting.
|
||||
///
|
||||
/// The issue see https://github.com/dart-lang/sdk/issues/48425
|
||||
class CodeHighlightThemeMode {
|
||||
|
||||
const CodeHighlightThemeMode({
|
||||
required this.mode,
|
||||
this.maxSize = 4 * 1024 * 1024,
|
||||
this.maxLineLength = 1 * 1024 * 1024,
|
||||
});
|
||||
|
||||
/// Syntax highlighting language rule.
|
||||
final Mode mode;
|
||||
|
||||
/// If the total text length is higher than this value, syntax highlighting
|
||||
/// will not be performed.
|
||||
///
|
||||
/// The default value is 4MB.
|
||||
final int maxSize;
|
||||
|
||||
/// If the text length of a line is higher than this value, syntax highlighting
|
||||
/// will not be performed.
|
||||
///
|
||||
/// The default value is 1MB.
|
||||
final int maxLineLength;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(mode, maxSize, maxLineLength);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
if (identical(this, other)) {
|
||||
return true;
|
||||
}
|
||||
return other is CodeHighlightThemeMode
|
||||
&& mode == other.mode && maxSize == other.maxSize
|
||||
&& maxLineLength == other.maxLineLength;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension CodeHighlightThemeModeExtension on Mode {
|
||||
|
||||
CodeHighlightThemeMode get themeMode => CodeHighlightThemeMode(mode: this);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
part of re_editor;
|
||||
|
||||
typedef ToolbarMenuBuilder = Widget Function({
|
||||
required BuildContext context,
|
||||
required TextSelectionToolbarAnchors anchors,
|
||||
required CodeLineEditingController controller,
|
||||
required VoidCallback onDismiss,
|
||||
required VoidCallback onRefresh,
|
||||
});
|
||||
|
||||
abstract class SelectionToolbarController {
|
||||
|
||||
void show({
|
||||
required BuildContext context,
|
||||
required CodeLineEditingController controller,
|
||||
required TextSelectionToolbarAnchors anchors,
|
||||
Rect? renderRect,
|
||||
required LayerLink layerLink,
|
||||
required ValueNotifier<bool> visibility,
|
||||
});
|
||||
|
||||
void hide(BuildContext context);
|
||||
|
||||
}
|
||||
|
||||
abstract class MobileSelectionToolbarController implements SelectionToolbarController {
|
||||
|
||||
factory MobileSelectionToolbarController({
|
||||
required ToolbarMenuBuilder builder
|
||||
}) => _MobileSelectionToolbarController(
|
||||
builder: builder
|
||||
);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
part of re_editor;
|
||||
|
||||
class _Trace {
|
||||
|
||||
static final Map<String, DateTime> _timestamps = {};
|
||||
|
||||
static void begin(String name) {
|
||||
_timestamps[name] = DateTime.now();
|
||||
}
|
||||
|
||||
static void end(String name, [bool microsecond = false]) {
|
||||
final DateTime? time = _timestamps.remove(name);
|
||||
if (time != null) {
|
||||
if (microsecond) {
|
||||
print('[${DateTime.now()}] $name costs ${DateTime.now().microsecondsSinceEpoch - time.microsecondsSinceEpoch} us');
|
||||
} else {
|
||||
print('[${DateTime.now()}] $name costs ${DateTime.now().millisecondsSinceEpoch - time.millisecondsSinceEpoch} ms');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
library re_editor;
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:math';
|
||||
import 'dart:ui' as ui;
|
||||
import 'dart:collection';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:flutter/scheduler.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import 'package:re_highlight/re_highlight.dart';
|
||||
import 'package:isolate_manager/isolate_manager.dart';
|
||||
|
||||
part '_code_floating_cursor.dart';
|
||||
part '_code_autocomplete.dart';
|
||||
part '_code_editable.dart';
|
||||
part '_code_extensions.dart';
|
||||
part '_code_field.dart';
|
||||
part '_code_find.dart';
|
||||
part '_code_formatter.dart';
|
||||
part '_code_highlight.dart';
|
||||
part '_code_indicator.dart';
|
||||
part '_code_input.dart';
|
||||
part '_code_line.dart';
|
||||
part '_code_lines.dart';
|
||||
part '_code_paragraph.dart';
|
||||
part '_code_scroll.dart';
|
||||
part '_code_selection.dart';
|
||||
part '_code_shortcuts.dart';
|
||||
part '_code_span.dart';
|
||||
part '_consts.dart';
|
||||
part '_isolate.dart';
|
||||
part 'code_autocomplete.dart';
|
||||
part 'code_chunk.dart';
|
||||
part 'code_editor.dart';
|
||||
part 'code_find.dart';
|
||||
part 'code_formatter.dart';
|
||||
part 'code_indicator.dart';
|
||||
part 'code_line.dart';
|
||||
part 'code_lines.dart';
|
||||
part 'code_paragraph.dart';
|
||||
part 'code_shortcuts.dart';
|
||||
part 'code_scroll.dart';
|
||||
part 'code_span.dart';
|
||||
part 'code_theme.dart';
|
||||
part 'code_toolbar.dart';
|
||||
part 'debug/_trace.dart';
|
||||
Reference in new issue
Block a user