• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_NG_PATTERNS_RICH_EDITOR_RICH_EDITOR_PATTERN_H
17 #define FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_NG_PATTERNS_RICH_EDITOR_RICH_EDITOR_PATTERN_H
18 
19 #include <cstdint>
20 #include <map>
21 #include <optional>
22 #include <set>
23 #include <string>
24 
25 #include "base/log/event_report.h"
26 #include "base/utils/device_config.h"
27 #include "core/common/ai/ai_write_adapter.h"
28 #include "core/common/ime/text_edit_controller.h"
29 #include "core/common/ime/text_input_action.h"
30 #include "core/common/ime/text_input_client.h"
31 #include "core/common/ime/text_input_configuration.h"
32 #include "core/common/ime/text_input_connection.h"
33 #include "core/common/ime/text_input_formatter.h"
34 #include "core/common/ime/text_input_proxy.h"
35 #include "core/common/ime/text_input_type.h"
36 #include "core/common/ime/text_selection.h"
37 #include "core/components/common/properties/text_layout_info.h"
38 #include "core/components_ng/pattern/rich_editor/paragraph_manager.h"
39 #include "core/components_ng/pattern/rich_editor/rich_editor_accessibility_property.h"
40 #include "core/components_ng/pattern/rich_editor/rich_editor_content_modifier.h"
41 #include "core/components_ng/pattern/rich_editor/rich_editor_controller.h"
42 #include "core/components_ng/pattern/rich_editor/rich_editor_event_hub.h"
43 #include "core/components_ng/pattern/rich_editor/rich_editor_layout_algorithm.h"
44 #include "core/components_ng/pattern/rich_editor/rich_editor_layout_property.h"
45 #include "core/components_ng/pattern/rich_editor/rich_editor_overlay_modifier.h"
46 #include "core/components_ng/pattern/rich_editor/rich_editor_paint_method.h"
47 #include "core/components_ng/pattern/rich_editor/rich_editor_select_overlay.h"
48 #include "core/components_ng/pattern/rich_editor/rich_editor_styled_string_controller.h"
49 #include "core/components_ng/pattern/rich_editor/selection_info.h"
50 #include "core/components_ng/pattern/scrollable/scrollable_pattern.h"
51 #include "core/components_ng/pattern/select_overlay/magnifier.h"
52 #include "core/components_ng/pattern/select_overlay/magnifier_controller.h"
53 #include "core/components_ng/pattern/text/layout_info_interface.h"
54 #include "core/components_ng/pattern/text/span_node.h"
55 #include "core/components_ng/pattern/text/text_base.h"
56 #include "core/components_ng/pattern/text/text_pattern.h"
57 #include "core/components_ng/pattern/text_field/text_field_model.h"
58 #include "core/text/text_emoji_processor.h"
59 
60 #ifndef ACE_UNITTEST
61 #ifdef ENABLE_STANDARD_INPUT
62 #include "refbase.h"
63 
64 namespace OHOS::MiscServices {
65 class OnTextChangedListener;
66 struct TextConfig;
67 } // namespace OHOS::MiscServices
68 #endif
69 #endif
70 
71 #define COPY_SPAN_STYLE_IF_PRESENT(sourceNode, targetNode, styleType) \
72     do {                                                                            \
73         if ((sourceNode)->Has##styleType()) {                                       \
74             (targetNode)->Update##styleType(*((sourceNode)->Get##styleType()));     \
75         }                                                                           \
76     } while (false)
77 #define CONTENT_MODIFY_LOCK(patternPtr) ContentModifyLock contentModifyLock(patternPtr)
78 
79 #define IF_TRUE(cond, func) \
80     do {                    \
81         if (cond) {         \
82             func;           \
83         }                   \
84     } while (false)
85 
86 #define IF_PRESENT(opt, func) \
87     do {                      \
88         if (opt) {            \
89             opt->func;        \
90         }                     \
91     } while (false)
92 
93 namespace OHOS::Ace::NG {
94 class InspectorFilter;
95 class OneStepDragController;
96 
97 // TextPattern is the base class for text render node to perform paint text.
98 enum class MoveDirection { FORWARD, BACKWARD };
99 
100 enum class AutoScrollEvent { HANDLE, DRAG, MOUSE, NONE, CARET };
101 enum class EdgeDetectionStrategy { OUT_BOUNDARY, IN_BOUNDARY, DISABLE };
102 struct AutoScrollParam {
103     AutoScrollEvent autoScrollEvent = AutoScrollEvent::NONE;
104     RectF handleRect;
105     bool isFirstHandle = false;
106     float offset = 0.0f;
107     bool showScrollbar = false;
108     Offset eventOffset;
109     bool isFirstRun_ = true;
110 };
111 enum class RecordType { DEL_FORWARD = 0, DEL_BACKWARD = 1, INSERT = 2, UNDO = 3, REDO = 4, DRAG = 5 };
112 enum class SelectorAdjustPolicy { INCLUDE = 0, EXCLUDE };
113 enum class HandleType { FIRST = 0, SECOND };
114 enum class SelectType { SELECT_FORWARD = 0, SELECT_BACKWARD, SELECT_NOTHING };
115 enum class CaretAffinityPolicy { DEFAULT = 0, UPSTREAM_FIRST, DOWNSTREAM_FIRST };
116 enum class OperationType { DEFAULT = 0, DRAG, IME };
117 const std::map<std::pair<HandleType, SelectorAdjustPolicy>, MoveDirection> SELECTOR_ADJUST_DIR_MAP = {
118     {{ HandleType::FIRST, SelectorAdjustPolicy::INCLUDE }, MoveDirection::BACKWARD },
119     {{ HandleType::FIRST, SelectorAdjustPolicy::EXCLUDE }, MoveDirection::FORWARD },
120     {{ HandleType::SECOND, SelectorAdjustPolicy::INCLUDE }, MoveDirection::FORWARD },
121     {{ HandleType::SECOND, SelectorAdjustPolicy::EXCLUDE }, MoveDirection::BACKWARD }
122 };
123 struct CaretOffsetInfo {
124     // caret front offset info
125     OffsetF caretOffsetUp;
126     // caret end offset info
127     OffsetF caretOffsetDown;
128     // caret position offset info
129     OffsetF caretOffsetLine;
130     float caretHeightUp = 0.0f;
131     float caretHeightDown = 0.0f;
132     float caretHeightLine = 0.0f;
133 };
134 enum class PositionType { DEFAULT, PARAGRAPH_START, PARAGRAPH_END, LINE_START, LINE_END };
135 struct SysScale {
136     double dipScale = 1.0;
137     double logicScale = 1.0;
138     double fontScale = 1.0;
139     double fontWeightScale = 1.0;
140     bool operator==(const SysScale& rhs) const
141     {
142         return NearEqual(dipScale, rhs.dipScale)
143             && NearEqual(logicScale, rhs.logicScale)
144             && NearEqual(fontScale, rhs.fontScale)
145             && NearEqual(fontWeightScale, rhs.fontWeightScale);
146     }
147     bool operator!=(const SysScale& rhs) const
148     {
149         return !operator==(rhs);
150     }
ToStringSysScale151     std::string ToString()
152     {
153         std::stringstream ss;
154         ss << dipScale << ", " << logicScale << ", " << fontScale << ", " << fontWeightScale;
155         return ss.str();
156     }
157 };
158 
159 class RichEditorPattern
160     : public TextPattern, public ScrollablePattern, public TextInputClient, public SpanWatcher {
161     DECLARE_ACE_TYPE(RichEditorPattern, TextPattern, ScrollablePattern, TextInputClient, SpanWatcher);
162 
163 public:
164     RichEditorPattern();
165     ~RichEditorPattern() override;
166 
167     struct OperationRecord {
OperationRecordOperationRecord168         OperationRecord() : beforeCaretPosition(-1), afterCaretPosition(-1), deleteCaretPostion(-1) {}
169         std::optional<std::u16string> addText;
170         std::optional<std::u16string> deleteText;
171         int32_t beforeCaretPosition;
172         int32_t afterCaretPosition;
173         int32_t deleteCaretPostion;
174     };
175 
176     struct PreviewTextRecord {
177         int32_t startOffset = INVALID_VALUE;
178         int32_t endOffset = INVALID_VALUE;
179         bool previewTextHasStarted = false;
180         std::u16string previewContent;
181         std::u16string newPreviewContent;
182         bool needReplacePreviewText = false;
183         bool needReplaceText = false;
184         PreviewRange replacedRange;
185         bool isSpanSplit = false;
186         bool needUpdateCaret = true;
187         bool previewTextExiting = false;
188 
ToStringPreviewTextRecord189         std::string ToString() const
190         {
191             auto jsonValue = JsonUtil::Create(true);
192             JSON_STRING_PUT_STRING(jsonValue, previewContent);
193             JSON_STRING_PUT_BOOL(jsonValue, previewTextHasStarted);
194             JSON_STRING_PUT_INT(jsonValue, startOffset);
195             JSON_STRING_PUT_INT(jsonValue, endOffset);
196             JSON_STRING_PUT_BOOL(jsonValue, isSpanSplit);
197             JSON_STRING_PUT_BOOL(jsonValue, needUpdateCaret);
198             JSON_STRING_PUT_BOOL(jsonValue, previewTextExiting);
199 
200             return jsonValue->ToString();
201         }
202 
ResetPreviewTextRecord203         void Reset()
204         {
205             startOffset = INVALID_VALUE;
206             endOffset = INVALID_VALUE;
207             previewContent.clear();
208             previewTextHasStarted = false;
209             needReplacePreviewText = false;
210             needReplaceText = false;
211             replacedRange.Set(INVALID_VALUE, INVALID_VALUE);
212             isSpanSplit = false;
213             previewTextExiting = false;
214         }
215 
IsValidPreviewTextRecord216         bool IsValid() const
217         {
218             return !previewContent.empty() && previewTextHasStarted && startOffset >= 0 && endOffset >= startOffset;
219         }
220     };
221 
222     struct TouchAndMoveCaretState {
223         bool isTouchCaret = false;
224         bool isMoveCaret = false;
225         Offset touchDownOffset;
226         const Dimension minDistance = 5.0_vp;
227         std::optional<int32_t> touchFingerId = std::nullopt;
228 
ResetTouchAndMoveCaretState229         void Reset()
230         {
231             isTouchCaret = false;
232             isMoveCaret = false;
233             touchDownOffset.Reset();
234             touchFingerId.reset();
235         }
236     };
237 
238     struct FloatingCaretState {
239         bool isFloatingCaretVisible = false;
240         bool isOriginCaretVisible = false;
241         std::optional<Offset> touchMoveOffset = std::nullopt;
242         Color originCaretColor = Color(0x4D000000);
243         const Dimension showFloatingCaretDistance = 10.0_vp;
244 
ResetFloatingCaretState245         void Reset()
246         {
247             isFloatingCaretVisible = false;
248             isOriginCaretVisible = false;
249             touchMoveOffset.reset();
250         }
251 
UpdateOriginCaretColorFloatingCaretState252         void UpdateOriginCaretColor(ColorMode colorMode)
253         {
254             originCaretColor = colorMode == ColorMode::DARK ? Color(0x4DFFFFFF) : Color(0x4D000000);
255         }
256 
UpdateByTouchMoveFloatingCaretState257         void UpdateByTouchMove(const Offset& offset, double distance, const RectF& boundaryRect)
258         {
259             isFloatingCaretVisible = true;
260             touchMoveOffset = offset;
261             bool isCaretAtBoundaryLeft = LessOrEqual(touchMoveOffset->GetX(), boundaryRect.Left());
262             bool isCaretAtBoundaryRight = GreatOrEqual(touchMoveOffset->GetX(), boundaryRect.Right());
263             if (!isCaretAtBoundaryLeft && !isCaretAtBoundaryRight) {
264                 isOriginCaretVisible = GreatNotEqual(distance, showFloatingCaretDistance.ConvertToPx());
265             } else {
266                 touchMoveOffset->SetX(isCaretAtBoundaryLeft ? boundaryRect.Left() : boundaryRect.Right());
267                 isOriginCaretVisible = true;
268             }
269         }
270     };
271 
GetFloatingCaretState()272     const FloatingCaretState& GetFloatingCaretState() const
273     {
274         return floatingCaretState_;
275     }
276 
ResetFloatingCaretState()277     void ResetFloatingCaretState()
278     {
279         floatingCaretState_.Reset();
280     }
281 
282     class ContentModifyLock {
283     public:
284         ContentModifyLock();
ContentModifyLock(RichEditorPattern * pattern)285         ContentModifyLock(RichEditorPattern* pattern)
286         {
287             pattern->isModifyingContent_ = true;
288             pattern_ = WeakClaim(pattern);
289         }
~ContentModifyLock()290         ~ContentModifyLock()
291         {
292             auto pattern = pattern_.Upgrade();
293             if (!pattern) {
294                 TAG_LOGE(AceLogTag::ACE_RICH_TEXT, "pattern is null, unlock failed");
295                 return;
296             }
297             pattern->isModifyingContent_ = false;
298             auto host = pattern->GetHost();
299             CHECK_NULL_VOID(host);
300             host->MarkDirtyNode(PROPERTY_UPDATE_MEASURE);
301         }
302     private:
303         WeakPtr<RichEditorPattern> pattern_;
304     };
305 
306     int32_t SetPreviewText(const std::u16string& previewTextValue, const PreviewRange range) override;
307 
308     const PreviewTextInfo GetPreviewTextInfo() const;
309 
310     void FinishTextPreview() override;
311 
ReceivePreviewTextStyle(const std::string & style)312     void ReceivePreviewTextStyle(const std::string& style) override
313     {
314         TAG_LOGI(AceLogTag::ACE_RICH_TEXT, "previewTextStyle: [%{public}s]", style.c_str());
315         auto property = GetLayoutProperty<RichEditorLayoutProperty>();
316         CHECK_NULL_VOID(property && !style.empty());
317         property->UpdatePreviewTextStyle(style);
318     }
319 
320     int32_t CheckPreviewTextValidate(const std::string& previewTextValue, const PreviewRange range) override;
321 
322     int32_t CheckPreviewTextValidate(const std::u16string& previewTextValue, const PreviewRange range) override;
323 
324     const Color& GetPreviewTextDecorationColor() const;
325 
IsPreviewTextInputting()326     bool IsPreviewTextInputting()
327     {
328         return previewTextRecord_.IsValid();
329     }
330 
331     std::vector<RectF> GetPreviewTextRects();
332 
333     float GetPreviewTextUnderlineWidth() const;
334 
335     PreviewTextStyle GetPreviewTextStyle() const;
336 
SetSupportPreviewText(bool isTextPreviewSupported)337     void SetSupportPreviewText(bool isTextPreviewSupported)
338     {
339         TAG_LOGI(AceLogTag::ACE_RICH_TEXT, "enablePreviewText=%{public}d", isTextPreviewSupported);
340         isTextPreviewSupported_ = isTextPreviewSupported;
341     }
342 
343     ACE_DEFINE_PROPERTY_ITEM_FUNC_WITHOUT_GROUP(TextInputAction, TextInputAction)
344     TextInputAction GetDefaultTextInputAction() const;
345 
346     // RichEditor needs softkeyboard, override function.
NeedSoftKeyboard()347     bool NeedSoftKeyboard() const override
348     {
349         return true;
350     }
351 
352     BlurReason GetBlurReason();
353 
354     uint32_t GetSCBSystemWindowId();
355 
CreateEventHub()356     RefPtr<EventHub> CreateEventHub() override
357     {
358         return MakeRefPtr<RichEditorEventHub>();
359     }
360 
CreateLayoutProperty()361     RefPtr<LayoutProperty> CreateLayoutProperty() override
362     {
363         return MakeRefPtr<RichEditorLayoutProperty>();
364     }
365 
CreateLayoutAlgorithm()366     RefPtr<LayoutAlgorithm> CreateLayoutAlgorithm() override
367     {
368         HandleSysScaleChanged();
369         return MakeRefPtr<RichEditorLayoutAlgorithm>(spans_, &paragraphs_, typingTextStyle_, &paragraphCache_);
370     }
371 
HandleSysScaleChanged()372     void HandleSysScaleChanged()
373     {
374         auto ctx = GetContext();
375         if (!ctx) {
376             TAG_LOGW(AceLogTag::ACE_RICH_TEXT, "context is nullptr, handle scale failed");
377             return;
378         }
379         SysScale sysScale{ ctx->GetDipScale(), ctx->GetLogicScale(), ctx->GetFontScale(), ctx->GetFontWeightScale() };
380         if (sysScale != lastSysScale_) {
381             TAG_LOGI(AceLogTag::ACE_RICH_TEXT, "sys scale changed, %{public}s -> %{public}s",
382                 lastSysScale_.ToString().c_str(), sysScale.ToString().c_str());
383             lastSysScale_ = sysScale;
384             paragraphCache_.Clear();
385         }
386     }
387 
GetFocusPattern()388     FocusPattern GetFocusPattern() const override
389     {
390         FocusPattern focusPattern = { FocusType::NODE, true, FocusStyleType::INNER_BORDER };
391         focusPattern.SetIsFocusActiveWhenFocused(true);
392         return focusPattern;
393     }
394 
395     RefPtr<NodePaintMethod> CreateNodePaintMethod() override;
396 
GetRichEditorController()397     const RefPtr<RichEditorController>& GetRichEditorController()
398     {
399         return richEditorController_;
400     }
401 
SetRichEditorController(const RefPtr<RichEditorController> & controller)402     void SetRichEditorController(const RefPtr<RichEditorController>& controller)
403     {
404         richEditorController_ = controller;
405     }
406 
GetRichEditorStyledStringController()407     const RefPtr<RichEditorStyledStringController>& GetRichEditorStyledStringController()
408     {
409         return richEditorStyledStringController_;
410     }
411 
SetRichEditorStyledStringController(const RefPtr<RichEditorStyledStringController> & controller)412     void SetRichEditorStyledStringController(const RefPtr<RichEditorStyledStringController>& controller)
413     {
414         richEditorStyledStringController_ = controller;
415     }
416 
GetTimestamp()417     long long GetTimestamp() const
418     {
419         return timestamp_;
420     }
421 
SetMaxLength(std::optional<int32_t> maxLength)422     void SetMaxLength(std::optional<int32_t> maxLength)
423     {
424         if (maxLength != INT_MAX) {
425             DeleteToMaxLength(maxLength);
426         }
427         maxLength_ = maxLength;
428         TAG_LOGI(AceLogTag::ACE_RICH_TEXT, "maxLength: [%{public}d]", maxLength_.value_or(INT_MAX));
429     }
430 
GetMaxLength()431     int32_t GetMaxLength()
432     {
433         return maxLength_.value_or(INT_MAX);
434     }
435 
SetMaxLines(int32_t maxLines)436     void SetMaxLines(int32_t maxLines)
437     {
438         maxLines_ = maxLines;
439     }
440 
GetMaxLines()441     int32_t GetMaxLines()
442     {
443         return maxLines_;
444     }
445 
SetMaxLinesHeight(float maxLinesHeight)446     void SetMaxLinesHeight(float maxLinesHeight)
447     {
448         maxLinesHeight_ = maxLinesHeight;
449     }
450 
GetMaxLinesHeight()451     float GetMaxLinesHeight()
452     {
453         return maxLinesHeight_;
454     }
455 
UpdateSpanPosition()456     void UpdateSpanPosition()
457     {
458         uint32_t spanTextLength = 0;
459         for (auto& span : spans_) {
460             span->rangeStart = static_cast<int32_t>(spanTextLength);
461             spanTextLength += span->content.length();
462             span->position = static_cast<int32_t>(spanTextLength);
463         }
464     }
465 
OnAttachToMainTree()466     void OnAttachToMainTree() override
467     {
468         TextPattern::OnAttachToMainTree();
469     }
470 
RegisterCaretChangeListener(std::function<void (int32_t)> && listener)471     void RegisterCaretChangeListener(std::function<void(int32_t)>&& listener)
472     {
473         caretChangeListener_ = listener;
474     }
475 
476     void SetStyledString(const RefPtr<SpanString>& value);
477 
GetStyledString()478     RefPtr<MutableSpanString> GetStyledString() const
479     {
480         return styledString_;
481     }
482 
483     void UpdateSpanItems(const std::list<RefPtr<NG::SpanItem>>& spanItems) override;
484     void ProcessStyledString();
485     void MountImageNode(const RefPtr<ImageSpanItem>& imageItem);
486     void SetImageLayoutProperty(RefPtr<ImageSpanNode> imageNode, const ImageSpanOptions& options);
487     void InsertValueInStyledStringMore(RefPtr<SpanString> insertStyledString, int32_t changeStart, int32_t changeLength,
488         std::u16string& insertValue, bool needReplaceInTextPreview);
489     void InsertValueInStyledString(const std::u16string& insertValue, bool calledByImf = false);
490     RefPtr<SpanString> CreateStyledStringByTextStyle(
491         const std::u16string& insertValue, const struct UpdateSpanStyle& updateSpanStyle, const TextStyle& textStyle);
492     RefPtr<FontSpan> CreateFontSpanByTextStyle(
493         const struct UpdateSpanStyle& updateSpanStyle, const TextStyle& textStyle, int32_t length);
494     RefPtr<DecorationSpan> CreateDecorationSpanByTextStyle(
495         const struct UpdateSpanStyle& updateSpanStyle, const TextStyle& textStyle, int32_t length);
496     void DeleteBackwardInStyledString(int32_t length);
497     void DeleteForwardInStyledString(int32_t length, bool isIME = true);
498     void DeleteValueInStyledString(int32_t start, int32_t length, bool isIME = true, bool isUpdateCaret = true);
499 
500     bool BeforeStyledStringChange(int32_t start, int32_t length, const std::u16string& string);
501     bool BeforeStyledStringChange(int32_t start, int32_t length, const RefPtr<SpanString>& styledString);
502     void AfterStyledStringChange(int32_t start, int32_t length, const std::u16string& string);
503 
504     void ResetBeforePaste();
505     void ResetAfterPaste();
506 
507     void OnVisibleChange(bool isVisible) override;
508     void OnModifyDone() override;
509     void BeforeCreateLayoutWrapper() override;
510     bool OnDirtyLayoutWrapperSwap(const RefPtr<LayoutWrapper>& dirty, const DirtySwapConfig& config) override;
511     void HandleSelectOverlayOnLayoutSwap();
512     void FireOnReady();
513     void MoveCaretOnLayoutSwap();
514 
515     void UpdateEditingValue(const std::shared_ptr<TextEditingValue>& value, bool needFireChangeEvent = true) override;
516     void PerformAction(TextInputAction action, bool forceCloseKeyboard = true) override;
517     bool IsIMEOperation(OperationType operationType);
518     void InsertValue(const std::string& insertValue, bool isIME = false) override;
519     void InsertValue(const std::u16string& insertValue, bool isIME = false) override;
520     void InsertValueByOperationType(const std::u16string& insertValue,
521         OperationType operationType = OperationType::DEFAULT);
522     void InsertValueOperation(const std::u16string& insertValue, OperationRecord* const record = nullptr,
523         OperationType operationType = OperationType::IME);
524     void DeleteSelectOperation(OperationRecord* const record);
525     void DeleteByRange(OperationRecord* const record, int32_t start, int32_t end);
526     void InsertDiffStyleValueInSpan(RefPtr<SpanNode>& spanNode, const TextInsertValueInfo& info,
527         const std::u16string& insertValue, bool isIME = true);
528     void InsertValueByPaste(const std::u16string& insertValue);
529     bool IsLineSeparatorInLast(RefPtr<SpanNode>& spanNode);
530     void InsertValueToSpanNode(
531         RefPtr<SpanNode>& spanNode, const std::u16string& insertValue, const TextInsertValueInfo& info);
532     void SpanNodeFission(RefPtr<SpanNode>& spanNode);
533     void CreateTextSpanNode(RefPtr<SpanNode>& spanNode, const TextInsertValueInfo& info,
534         const std::u16string& insertValue, bool isIME = true);
535     void SetDefaultColor(RefPtr<SpanNode>& spanNode);
536     void HandleOnDelete(bool backward) override;
537     std::pair<bool, bool> IsEmojiOnCaretPosition(int32_t& emojiLength, bool isBackward, int32_t length);
538     int32_t CalculateDeleteLength(int32_t length, bool isBackward);
539     void DeleteBackward(int32_t length = 1) override;
540     std::u16string DeleteBackwardOperation(int32_t length);
541     void DeleteForward(int32_t length = 1) override;
542     std::u16string DeleteForwardOperation(int32_t length);
543     void SetInputMethodStatus(bool keyboardShown) override;
544     bool ClickAISpan(const PointF& textOffset, const AISpan& aiSpan) override;
545     WindowMode GetWindowMode();
546     bool GetIsMidScene();
NotifyKeyboardClosedByUser()547     void NotifyKeyboardClosedByUser() override
548     {
549         TAG_LOGI(AceLogTag::ACE_RICH_TEXT, "KeyboardClosedByUser");
550         FocusHub::LostFocusToViewRoot();
551     }
NotifyKeyboardClosed()552     void NotifyKeyboardClosed() override
553     {
554         TAG_LOGI(AceLogTag::ACE_RICH_TEXT, "KeyboardClosed");
555         CHECK_NULL_VOID(HasFocus());
556         CHECK_NULL_VOID(!customKeyboardBuilder_ || !isCustomKeyboardAttached_);
557 
558         // lost focus in floating window mode
559         auto windowMode = GetWindowMode();
560         TAG_LOGD(AceLogTag::ACE_RICH_TEXT, "KeyboardClosed windowMode = %{public}d", windowMode);
561         if (windowMode == WindowMode::WINDOW_MODE_FLOATING || windowMode == WindowMode::WINDOW_MODE_SPLIT_PRIMARY ||
562             windowMode == WindowMode::WINDOW_MODE_SPLIT_SECONDARY) {
563             FocusHub::LostFocusToViewRoot();
564         }
565     }
566     void ClearOperationRecords();
567     void ClearRedoOperationRecords();
568     void AddOperationRecord(const OperationRecord& record);
569     void UpdateShiftFlag(const KeyEvent& keyEvent)override;
570     bool HandleOnEscape() override;
571     void HandleOnUndoAction() override;
572     void HandleOnRedoAction() override;
573     void CursorMove(CaretMoveIntent direction) override;
574     void HandleExtendAction(int32_t action) override;
575     bool BeforeStatusCursorMove(bool isLeft);
576     bool CursorMoveLeft();
577     bool CursorMoveRight();
578     bool CursorMoveUp();
579     bool CursorMoveDown();
580     void CursorMoveToNextWord(CaretMoveIntent direction);
581     int32_t GetLeftWordIndex(int32_t index);
582     int32_t GetRightWordIndex(int32_t index);
583     bool CursorMoveToParagraphBegin();
584     bool CursorMoveToParagraphEnd();
585     bool CursorMoveHome();
586     bool CursorMoveEnd();
587     void CalcLineSidesIndexByPosition(int32_t& startIndex, int32_t& endIndex);
588     RectF CalcLineInfoByPosition();
589     CaretOffsetInfo GetCaretOffsetInfoByPosition(int32_t position = -1);
590     int32_t CalcMoveUpPos(float& leadingMarginOffset);
591     int32_t CalcMoveDownPos(float& leadingMarginOffset);
592     int32_t CalcLineBeginPosition();
593     float GetTextThemeFontSize();
594     int32_t CalcLineEndPosition(int32_t index = -1);
595     int32_t CalcSingleLineBeginPosition(int32_t fixedPos);
596     int32_t CalcSingleLineEndPosition(int32_t fixedPos);
597     bool CursorMoveLineBegin();
598     bool CursorMoveLineEnd();
599     void HandleSelectFontStyle(KeyCode code) override;
600     void HandleSelectFontStyleWrapper(KeyCode code, TextStyle& spanStyle);
601     void HandleOnShowMenu() override;
602     int32_t HandleKbVerticalSelection(bool isUp);
603     int32_t HandleSelectParagraghPos(bool direction);
604     PositionType GetPositionTypeFromLine();
605     int32_t HandleSelectWrapper(CaretMoveIntent direction, int32_t fixedPos);
606     void AIDeleteComb(int32_t start, int32_t end, int32_t& aiPosition, bool direction);
607     bool HandleOnDeleteComb(bool backward) override;
608     void DeleteBackwardWord();
609     void DeleteForwardWord();
610     int32_t GetLeftWordPosition(int32_t caretPosition);
611     int32_t GetRightWordPosition(int32_t caretPosition);
612     int32_t GetParagraphBeginPosition(int32_t caretPosition);
613     int32_t GetParagraphEndPosition(int32_t caretPosition);
614     int32_t CaretPositionSelectEmoji(CaretMoveIntent direction);
615     void HandleSelect(CaretMoveIntent direction) override;
616     void SetCaretPositionWithAffinity(PositionWithAffinity positionWithAffinity);
617     bool SetCaretPosition(int32_t pos, bool needNotifyImf = true);
618     int32_t GetCaretPosition();
619     int32_t GetTextContentLength() override;
620     bool GetCaretVisible() const;
621     OffsetF CalcCursorOffsetByPosition(int32_t position, float& selectLineHeight,
622         bool downStreamFirst = false, bool needLineHighest = true);
623     void HandleCurrentPositionParagraphInfo(float& lastLineTop, float& paragraphSpacing);
624     bool IsCustomSpanInCaretPos(int32_t position, bool downStreamFirst);
625     void CopyTextSpanStyle(RefPtr<SpanNode>& source, RefPtr<SpanNode>& target, bool needLeadingMargin = false);
626     void CopyTextSpanFontStyle(RefPtr<SpanNode>& source, RefPtr<SpanNode>& target);
627     void CopyTextSpanLineStyle(RefPtr<SpanNode>& source, RefPtr<SpanNode>& target, bool needLeadingMargin = false);
628     void CopyTextSpanUrlStyle(RefPtr<SpanNode>& source, RefPtr<SpanNode>& target);
629     void CopyGestureOption(const RefPtr<SpanNode>& source, RefPtr<SpanNode>& target);
630     int32_t TextSpanSplit(int32_t position, bool needLeadingMargin = false);
631     SpanPositionInfo GetSpanPositionInfo(int32_t position);
632     std::function<ImageSourceInfo()> CreateImageSourceInfo(const ImageSpanOptions& options);
633     void DeleteSpans(const RangeOptions& options);
634     void DeleteSpansOperation(int32_t start, int32_t end);
635     void DeleteSpanByRange(int32_t start, int32_t end, SpanPositionInfo info);
636     void DeleteSpansByRange(int32_t start, int32_t end, SpanPositionInfo startInfo, SpanPositionInfo endInfo);
637     void ClearContent(const RefPtr<UINode>& child);
638     void CloseSelectionMenu();
639     bool SetCaretOffset(int32_t caretPosition) override;
640     bool DoDeleteActions(int32_t currentPosition, int32_t length, RichEditorDeleteValue& info);
641 
642     void UpdateSpanStyle(int32_t start, int32_t end, const TextStyle& textStyle, const ImageSpanAttribute& imageStyle);
643     void GetContentBySpans(std::u16string& u16Str);
644     void SetSelectSpanStyle(int32_t start, int32_t end, KeyCode code, bool isStart);
645     void GetSelectSpansPositionInfo(
646         int32_t& start, int32_t& end, SpanPositionInfo& startPositionSpanInfo, SpanPositionInfo& endPositionSpanInfo);
647     std::list<RefPtr<UINode>>::const_iterator GetSpanNodeIter(int32_t index);
648     std::list<SpanPosition> GetSelectSpanSplit(
649         SpanPositionInfo& startPositionSpanInfo, SpanPositionInfo& endPositionSpanInfo);
650     std::list<SpanPosition> GetSelectSpanInfo(int32_t start, int32_t end);
651     SelectionInfo GetSpansInfoByRange(int32_t start, int32_t end);
652     void UpdateSelectSpanStyle(int32_t start, int32_t end, KeyCode code);
653     bool CheckStyledStringRangeValid(int32_t start, int32_t length);
654     void UpdateSelectStyledStringStyle(int32_t start, int32_t end, KeyCode code);
655     template<typename T>
656     void UpdateSpansStyleInRange(int32_t start, int32_t end, const RefPtr<SpanBase>& baseSpan,
657         std::function<RefPtr<T>(const RefPtr<T>&)>&& updateSpanFunc);
658     void UpdateStyledStringFontStyle(int32_t start, int32_t end, const Font& font);
659     void UpdateStyledStringDecorationType(int32_t start, int32_t end, const TextDecoration& type);
660     bool SymbolSpanUpdateStyle(RefPtr<SpanNode>& spanNode, struct UpdateSpanStyle updateSpanStyle, TextStyle textStyle);
661     void SetUpdateSpanStyle(struct UpdateSpanStyle updateSpanStyle);
662     struct UpdateSpanStyle GetUpdateSpanStyle();
663     void UpdateParagraphStyle(int32_t start, int32_t end, const struct UpdateParagraphStyle& style);
664     void UpdateParagraphStyle(RefPtr<SpanNode> spanNode, const struct UpdateParagraphStyle& style);
665     std::vector<ParagraphInfo> GetParagraphInfo(int32_t start, int32_t end);
666     void SetTypingStyle(std::optional<struct UpdateSpanStyle> typingStyle, std::optional<TextStyle> textStyle);
667     std::optional<struct UpdateSpanStyle> GetTypingStyle();
668     int32_t AddImageSpan(const ImageSpanOptions& options, bool isPaste = false, int32_t index = -1,
669         bool updateCaret = true);
670     int32_t AddTextSpan(TextSpanOptions options, bool isPaste = false, int32_t index = -1);
671     int32_t AddTextSpanOperation(const TextSpanOptions& options, bool isPaste = false, int32_t index = -1,
672         bool needLeadingMargin = false, bool updateCaretPosition = true);
673     void AdjustAddPosition(TextSpanOptions& options);
674     int32_t AddSymbolSpan(const SymbolSpanOptions& options, bool isPaste = false, int32_t index = -1);
675     int32_t AddSymbolSpanOperation(const SymbolSpanOptions& options, bool isPaste = false, int32_t index = -1);
676     void AddSpanItem(const RefPtr<SpanItem>& item, int32_t offset);
677     int32_t AddPlaceholderSpan(const RefPtr<UINode>& customNode, const SpanOptionBase& options);
678     void AddOnPlaceholderHoverEvent(const RefPtr<PlaceholderSpanNode>& placeholderSpanNode);
679     void OnPlaceholderHover(bool isHover);
680     void SetSelection(int32_t start, int32_t end, const std::optional<SelectionOptions>& options = std::nullopt,
681         bool isForward = false) override;
682     bool ResetOnInvalidSelection(int32_t start, int32_t end);
683     bool IsShowHandle();
684     void UpdateSelectionInfo(int32_t start, int32_t end);
685     bool IsEditing();
686     std::u16string GetLeftTextOfCursor(int32_t number) override;
687     std::u16string GetRightTextOfCursor(int32_t number) override;
688     int32_t GetTextIndexAtCursor() override;
689     void ShowSelectOverlay(const RectF& firstHandle, const RectF& secondHandle, bool isCopyAll = false,
690         TextResponseType responseType = TextResponseType::LONG_PRESS, bool handlReverse = false);
691     void CheckEditorTypeChange();
692     int32_t GetHandleIndex(const Offset& offset) const override;
693     void OnAreaChangedInner() override;
694     void UpdateParentOffsetAndOverlay();
695     void OnParentOffsetChange();
696     void CreateHandles() override;
697     void ShowHandles(const bool isNeedShowHandles) override;
698     void ShowHandles() override;
699     void HandleMenuCallbackOnSelectAll(bool isShowMenu = true);
700     void HandleOnSelectAll() override;
701     void OnCopyOperation(bool isUsingExternalKeyboard = false);
702     void HandleOnCopy(bool isUsingExternalKeyboard = false) override;
703     void HandleOnShare();
704     void HandleDraggableFlag(bool isTouchSelectArea);
705     void SetIsTextDraggable(bool isTextDraggable = true) override;
706     bool JudgeContentDraggable();
707     std::pair<OffsetF, float> CalculateCaretOffsetAndHeight();
708     std::pair<OffsetF, float> CalculateEmptyValueCaretRect();
709     void UpdateModifierCaretOffsetAndHeight();
710     void NotifyCaretChange();
711     TextAlign GetTextAlignByDirection();
712     void RemoveEmptySpan(std::set<int32_t, std::greater<int32_t>>& deleteSpanIndexs);
713     void RemoveEmptySpanItems();
714     void RemoveEmptySpanNodes();
715     void RemoveEmptySpans();
716     RefPtr<GestureEventHub> GetGestureEventHub();
717     void OnWindowHide() override;
718     bool BeforeAddImage(RichEditorChangeValue& changeValue, const ImageSpanOptions& options, int32_t insertIndex);
719     RefPtr<SpanString> ToStyledString(int32_t start, int32_t end);
720     SelectionInfo FromStyledString(const RefPtr<SpanString>& spanString);
721     bool BeforeAddSymbol(RichEditorChangeValue& changeValue, const SymbolSpanOptions& options);
722     void AfterContentChange(RichEditorChangeValue& changeValue);
723     void DeleteToMaxLength(std::optional<int32_t> length);
724     void DeleteContent(int32_t length);
725 
ResetIsMousePressed()726     void ResetIsMousePressed()
727     {
728         isMousePressed_ = false;
729     }
730 
GetSelectionMenuOffset()731     OffsetF GetSelectionMenuOffset() const
732     {
733         return selectionMenuOffsetByMouse_;
734     }
735 
SetLastClickOffset(const OffsetF & lastClickOffset)736     void SetLastClickOffset(const OffsetF& lastClickOffset)
737     {
738         lastClickOffset_ = lastClickOffset;
739     }
740 
ResetLastClickOffset()741     void ResetLastClickOffset()
742     {
743         lastClickOffset_.SetX(-1);
744         lastClickOffset_.SetY(-1);
745     }
746 
GetCaretSpanIndex()747     int32_t GetCaretSpanIndex()
748     {
749         return caretSpanIndex_;
750     }
751 
GetParagraphs()752     std::vector<ParagraphManager::ParagraphInfo> GetParagraphs() const override
753     {
754         return paragraphs_.GetParagraphs();
755     }
756 
GetFirstHandleInfo()757     std::optional<SelectHandleInfo> GetFirstHandleInfo() const
758     {
759         return selectOverlay_->GetFirstHandleInfo();
760     }
761 
GetSecondHandleInfo()762     std::optional<SelectHandleInfo> GetSecondHandleInfo() const
763     {
764         return selectOverlay_->GetSecondHandleInfo();
765     }
766 
767     RectF GetCaretRect() const override;
768     void OnDragNodeFloating() override;
769     void CloseSelectOverlay() override;
770     void CloseHandleAndSelect() override;
771     void CalculateHandleOffsetAndShowOverlay(bool isUsingMouse = false);
772     void CalculateDefaultHandleHeight(float& height) override;
773     bool IsSingleHandle();
774     bool IsHandlesShow() override;
775     void CopySelectionMenuParams(SelectOverlayInfo& selectInfo, TextResponseType responseType);
776     std::function<void(Offset)> GetThumbnailCallback() override;
777     void CreateDragNode();
778     float GetMaxSelectedWidth();
779     void InitDragShadow(const RefPtr<FrameNode>& host, const RefPtr<FrameNode>& dragNode, bool isDragShadowNeeded,
780         bool hasDragBackgroundColor);
781     void HandleOnDragStatusCallback(
782         const DragEventType& dragEventType, const RefPtr<NotifyDragEvent>& notifyDragEvent) override;
783     void ResetSelection();
784     bool BetweenSelection(const Offset& globalOffset);
785     bool InRangeRect(const Offset& globalOffset, const std::pair<int32_t, int32_t>& range);
786     bool BetweenSelectedPosition(const Offset& globalOffset) override;
787     void HandleSurfaceChanged(int32_t newWidth, int32_t newHeight, int32_t prevWidth, int32_t prevHeight,
788         WindowSizeChangeReason type) override;
789     void HandleSurfacePositionChanged(int32_t posX, int32_t posY) override;
790     bool RequestCustomKeyboard();
791     bool CloseCustomKeyboard();
792     void UpdateUrlStyle(RefPtr<SpanNode>& spanNode, const std::optional<std::u16string>& urlAddressOpt);
GetPasteStr()793     const std::u16string& GetPasteStr() const
794     {
795         return pasteStr_;
796     }
AddPasteStr(const std::string & addedStr)797     void AddPasteStr(const std::string& addedStr)
798     {
799         pasteStr_.append(UtfUtils::Str8ToStr16(addedStr));
800     }
ClearPasteStr()801     void ClearPasteStr()
802     {
803         pasteStr_.clear();
804     }
SetCustomKeyboard(const std::function<void ()> && keyboardBuilder)805     void SetCustomKeyboard(const std::function<void()>&& keyboardBuilder)
806     {
807         if (customKeyboardBuilder_ && isCustomKeyboardAttached_ && !keyboardBuilder) {
808             // close customKeyboard and request system keyboard
809             CloseCustomKeyboard();
810             customKeyboardBuilder_ = keyboardBuilder; // refresh current keyboard
811             RequestKeyboard(false, true, true);
812             return;
813         }
814         if (!customKeyboardBuilder_ && keyboardBuilder) {
815             // close system keyboard and request custom keyboard
816 #if defined(OHOS_STANDARD_SYSTEM) && !defined(PREVIEW)
817             if (imeShown_) {
818                 CloseKeyboard(true);
819                 customKeyboardBuilder_ = keyboardBuilder; // refresh current keyboard
820                 RequestKeyboard(false, true, true);
821                 return;
822             }
823 #endif
824         }
825         customKeyboardBuilder_ = keyboardBuilder;
826     }
827     void BindSelectionMenu(TextResponseType type, TextSpanType richEditorType, std::function<void()>& menuBuilder,
828         const SelectMenuParam& menuParam);
ClearSelectionMenu()829     void ClearSelectionMenu()
830     {
831         selectionMenuMap_.clear();
832     }
833     void DumpInfo() override;
834     void DumpInfo(std::unique_ptr<JsonValue>& json) override;
DumpSimplifyInfo(std::unique_ptr<JsonValue> & json)835     void DumpSimplifyInfo(std::unique_ptr<JsonValue>& json) override {}
836     void RichEditorErrorReport(RichEditorInfo& info);
837     void MouseDoubleClickParagraphEnd(int32_t& index);
838     void AdjustSelectionExcludeSymbol(int32_t& start, int32_t& end);
839     void InitSelection(const Offset& pos);
840     bool HasFocus() const;
841     void OnColorConfigurationUpdate() override;
842     bool OnThemeScopeUpdate(int32_t themeScopeId) override;
843     void OnCommonColorChange();
844     bool IsDisabled() const;
845     float GetLineHeight() const override;
846     size_t GetLineCount() const override;
847     std::vector<ParagraphManager::TextBox> GetRectsForRange(int32_t start, int32_t end,
848         RectHeightStyle heightStyle, RectWidthStyle widthStyle) override;
849     TextLineMetrics GetLineMetrics(int32_t lineNumber) override;
850     float GetLetterSpacing() const;
851     std::vector<RectF> GetTextBoxes() override;
852     bool OnBackPressed() override;
853 
854     RectF GetCaretRelativeRect();
855     // Add for Scroll
856 
857     void OnAttachToFrameNode() override;
858 
859     void OnDetachFromFrameNode(FrameNode* node) override;
860 
IsAtBottom()861     bool IsAtBottom() const override
862     {
863         return true;
864     }
865 
IsAtTop()866     bool IsAtTop() const override
867     {
868         return true;
869     }
870 
UpdateCurrentOffset(float offset,int32_t source)871     bool UpdateCurrentOffset(float offset, int32_t source) override
872     {
873         return true;
874     }
875 
GetTextRect()876     const RectF& GetTextRect() override
877     {
878         return richTextRect_;
879     }
880 
GetScrollOffset()881     float GetScrollOffset() const
882     {
883         return scrollOffset_;
884     }
885 
GetScrollControllerBar()886     RefPtr<ScrollBar> GetScrollControllerBar()
887     {
888         return GetScrollBar();
889     }
890 
891     bool OnScrollCallback(float offset, int32_t source) override;
892     void OnScrollEndCallback() override;
IsScrollable()893     bool IsScrollable() const override
894     {
895         return scrollable_;
896     }
897 
IsAtomicNode()898     bool IsAtomicNode() const override
899     {
900         return true;
901     }
902 
903     bool IsShowSelectMenuUsingMouse();
904 
IsShowPlaceholder()905     bool IsShowPlaceholder() const
906     {
907         return isShowPlaceholder_;
908     }
909 
910     bool IsSelectAreaVisible();
911 
912     bool SetPlaceholder(std::vector<std::list<RefPtr<SpanItem>>>& spanItemList);
913 
914     std::string GetPlaceHolder() const;
915 
916     void HandleOnCameraInput() override;
917     void HandleOnAIWrite();
918     void GetAIWriteInfo(AIWriteInfo& info);
919     void HandleAIWriteResult(int32_t start, int32_t end, std::vector<uint8_t>& buffer);
920     void InsertSpanByBackData(RefPtr<SpanString>& spanString);
921     void AddSpansAndReplacePlaceholder(RefPtr<SpanString>& spanString);
922     void ReplacePlaceholderWithRawSpans(const RefPtr<SpanItem>& spanItem, size_t& index, size_t& textIndex);
923     void SetSubSpansWithAIWrite(RefPtr<SpanString>& spanString, int32_t start, int32_t end);
924     SymbolSpanOptions GetSymbolSpanOptions(const RefPtr<SpanItem>& spanItem);
925     bool IsShowTranslate();
926     bool IsShowSearch();
927     bool IsShowAIWrite();
928     RefPtr<FocusHub> GetFocusHub() const;
929     void ResetDragOption() override;
930     bool NeedShowAIDetect() override;
931 
GetEditorType()932     TextSpanType GetEditorType() const
933     {
934         return selectedType_.value_or(TextSpanType::NONE);
935     }
936     void GetCaretMetrics(CaretMetricsF& caretCaretMetric) override;
937 
SetShowSelect(bool isShowSelect)938     void SetShowSelect(bool isShowSelect)
939     {
940         showSelect_ = isShowSelect;
941     }
942 
943     const std::list<RefPtr<UINode>>& GetAllChildren() const override;
944 
945     void OnVirtualKeyboardAreaChanged() override;
946 
SetCaretColor(const Color & caretColor)947     void SetCaretColor(const Color& caretColor)
948     {
949         TAG_LOGI(AceLogTag::ACE_RICH_TEXT, "setCaretColor=%{public}s", caretColor.ToString().c_str());
950         caretColor_ = caretColor;
951         IF_TRUE(SelectOverlayIsOn(), selectOverlay_->UpdateHandleColor());
952     }
953 
954     Color GetCaretColor();
955 
SetSelectedBackgroundColor(const Color & selectedBackgroundColor)956     void SetSelectedBackgroundColor(const Color& selectedBackgroundColor)
957     {
958         TAG_LOGI(AceLogTag::ACE_RICH_TEXT, "SetSelectedBackgroundColor=%{public}s",
959             selectedBackgroundColor.ToString().c_str());
960         selectedBackgroundColor_ = selectedBackgroundColor;
961     }
962 
963     Color GetSelectedBackgroundColor();
964 
965     void SetCustomKeyboardOption(bool supportAvoidance);
966     void StopEditing();
967     void ResetKeyboardIfNeed();
968 
HandleOnEnter()969     void HandleOnEnter() override
970     {
971         PerformAction(GetTextInputActionValue(GetDefaultTextInputAction()), false);
972     }
973 
GetClipboard()974     RefPtr<Clipboard> GetClipboard() override
975     {
976         return clipboard_;
977     }
978 
GetCaretIndex()979     int32_t GetCaretIndex() const override
980     {
981         return caretPosition_;
982     }
983 
GetContentWideTextLength()984     int32_t GetContentWideTextLength() override
985     {
986         return GetTextContentLength();
987     }
988 
GetParentGlobalOffset()989     OffsetF GetParentGlobalOffset() const override
990     {
991         return parentGlobalOffset_;
992     }
993 
GetFirstHandleOffset()994     OffsetF GetFirstHandleOffset() const override
995     {
996         return textSelector_.firstHandle.GetOffset();
997     }
998 
GetSecondHandleOffset()999     OffsetF GetSecondHandleOffset() const override
1000     {
1001         return textSelector_.secondHandle.GetOffset();
1002     }
1003 
1004     OffsetF GetTextPaintOffset() const override;
1005     OffsetF GetPaintRectGlobalOffset() const;
1006     // original local point to transformed global point.
1007     void HandlePointWithTransform(OffsetF& point);
1008 
1009     float GetCrossOverHeight() const;
1010 
CreateAccessibilityProperty()1011     RefPtr<AccessibilityProperty> CreateAccessibilityProperty() override
1012     {
1013         return MakeRefPtr<RichEditorAccessibilityProperty>();
1014     }
1015 
1016     void AdjustSelector(int32_t& index, HandleType handleType,
1017         SelectorAdjustPolicy policy = SelectorAdjustPolicy::INCLUDE);
1018     void AdjustSelector(int32_t& start, int32_t& end, SelectorAdjustPolicy policy = SelectorAdjustPolicy::INCLUDE);
1019     bool AdjustSelectorForSymbol(int32_t& index, HandleType handleType, SelectorAdjustPolicy policy);
1020     bool AdjustSelectorForEmoji(int32_t& index, HandleType handleType, SelectorAdjustPolicy policy);
1021     EmojiRelation GetEmojiRelation(int index);
1022     void UpdateSelector(int32_t start, int32_t end);
1023     void UpdateSelectionType(const SelectionInfo& textSelectInfo);
1024     std::list<RefPtr<SpanItem>>::iterator GetSpanIter(int32_t index);
1025     SpanItemType GetSpanType(int32_t index);
1026 
DumpAdvanceInfo()1027     void DumpAdvanceInfo() override {}
DumpAdvanceInfo(std::unique_ptr<JsonValue> & json)1028     void DumpAdvanceInfo(std::unique_ptr<JsonValue>& json) override  {}
1029 
SetContentChange(bool onChange)1030     void SetContentChange(bool onChange)
1031     {
1032         contentChange_ = onChange;
1033     }
1034 
1035     void HideMenu();
1036     PositionWithAffinity GetGlyphPositionAtCoordinate(int32_t x, int32_t y) override;
1037     void OnSelectionMenuOptionsUpdate(
1038         const NG::OnCreateMenuCallback&& onCreateMenuCallback, const NG::OnMenuItemClickCallback&& onMenuItemClick);
1039     RectF GetTextContentRect(bool isActualText = false) const override
1040     {
1041         return contentRect_;
1042     }
1043 
1044     void PreferredParagraph();
1045 
GetPresetParagraph()1046     const RefPtr<Paragraph>& GetPresetParagraph()
1047     {
1048         return presetParagraph_;
1049     }
1050 
OnFrameNodeChanged(FrameNodeChangeInfoFlag flag)1051     void OnFrameNodeChanged(FrameNodeChangeInfoFlag flag) override
1052     {
1053         selectOverlay_->OnAncestorNodeChanged(flag);
1054     }
1055 
1056     bool IsResponseRegionExpandingNeededForStylus(const TouchEvent& touchEvent) const override;
1057 
1058     RectF ExpandDefaultResponseRegion(RectF& rect) override;
ConsumeChildrenAdjustment(const OffsetF &)1059     bool ConsumeChildrenAdjustment(const OffsetF& /* offset */) override
1060     {
1061         return true;
1062     }
1063 
1064     TextStyle GetDefaultTextStyle();
SetEnableHapticFeedback(bool isEnabled)1065     void SetEnableHapticFeedback(bool isEnabled)
1066     {
1067         TAG_LOGI(AceLogTag::ACE_RICH_TEXT, "setEnableHapticFeedback=%{public}d", isEnabled);
1068         isEnableHapticFeedback_ = isEnabled;
1069     }
1070 
1071     bool InsertOrDeleteSpace(int32_t index) override;
1072 
1073     void DeleteRange(int32_t start, int32_t end, bool isIME = true) override;
1074     void HandleOnPageUp() override;
1075     void HandleOnPageDown() override;
1076     void HandlePageScroll(bool isPageUp);
1077 
SetRequestKeyboardOnFocus(bool needToRequest)1078     void SetRequestKeyboardOnFocus(bool needToRequest)
1079     {
1080         TAG_LOGI(AceLogTag::ACE_RICH_TEXT, "SetRequestKeyboardOnFocus=%{public}d", needToRequest);
1081         needToRequestKeyboardOnFocus_ = needToRequest;
1082     }
1083 
1084     bool IsTextEditableForStylus() const override;
1085 
1086     NG::DragDropInfo HandleDragStart(const RefPtr<Ace::DragEvent>& event, const std::string& extraParams);
1087 
1088     void SetPreviewMenuParam(TextSpanType spanType, std::function<void()>& builder, const SelectMenuParam& menuParam);
1089 
RequestFocusWhenSelected()1090     void RequestFocusWhenSelected()
1091     {
1092         CHECK_NULL_VOID(!HasFocus());
1093         CHECK_NULL_VOID(IsSelected());
1094         auto focusHub = GetFocusHub();
1095         CHECK_NULL_VOID(focusHub);
1096         isOnlyRequestFocus_ = true;
1097         IF_TRUE(!focusHub->RequestFocusImmediately(), isOnlyRequestFocus_ = false);
1098     }
1099 
GetBarDisplayMode()1100     DisplayMode GetBarDisplayMode() const
1101     {
1102         return barDisplayMode_.value_or(DisplayMode::AUTO);
1103     }
1104 
1105     Color GetUrlSpanColor() override;
1106 
1107     void TriggerAvoidOnCaretChange();
1108 
1109     void ForceTriggerAvoidOnCaretChange(bool isMoveContent = false)
1110     {
1111         auto pipeline = GetContext();
1112         CHECK_NULL_VOID(pipeline && pipeline->UsingCaretAvoidMode());
1113         IF_TRUE(isMoveContent, MoveCaretToContentRect());
1114         isTriggerAvoidOnCaretAvoidMode_ = true;
1115     }
1116 
TriggerAvoidOnCaretChangeNextFrame()1117     void TriggerAvoidOnCaretChangeNextFrame()
1118     {
1119         ForceTriggerAvoidOnCaretChange(true);
1120         isTriggerAvoidOnCaretAvoidMode_ = false;
1121         UpdateModifierCaretOffsetAndHeight();
1122         TriggerAvoidOnCaretChange();
1123     }
1124 
ResetTriggerAvoidFlagOnCaretChange()1125     void ResetTriggerAvoidFlagOnCaretChange()
1126     {
1127         isTriggerAvoidOnCaretAvoidMode_ = false;
1128     }
1129 
1130     void OnWindowSizeChanged(int32_t width, int32_t height, WindowSizeChangeReason type) override;
1131 
IsTriggerAvoidOnCaretAvoidMode()1132     bool IsTriggerAvoidOnCaretAvoidMode()
1133     {
1134         return isTriggerAvoidOnCaretAvoidMode_;
1135     }
1136 
SetAvoidFlagOnCaretAvoidMode(bool isTriggerAvoidOnCaretAvoidMode)1137     void SetAvoidFlagOnCaretAvoidMode(bool isTriggerAvoidOnCaretAvoidMode)
1138     {
1139         auto pipeline = GetContext();
1140         CHECK_NULL_VOID(pipeline && pipeline->UsingCaretAvoidMode());
1141         isTriggerAvoidOnCaretAvoidMode_ = isTriggerAvoidOnCaretAvoidMode;
1142     }
1143 
ChangeLastRichTextRect()1144     void ChangeLastRichTextRect()
1145     {
1146         lastRichTextRect_ = richTextRect_;
1147     }
1148 
GetLastTextRect()1149     const RectF& GetLastTextRect()
1150     {
1151         return lastRichTextRect_;
1152     }
1153     HoverInfo CreateHoverInfo(const MouseInfo& info);
1154     std::pair<int32_t, int32_t> GetSpanRangeByLocalOffset(Offset localOffset);
SetStopBackPress(bool isStopBackPress)1155     void SetStopBackPress(bool isStopBackPress)
1156     {
1157         isStopBackPress_ = isStopBackPress;
1158     }
1159 
IsStopBackPress()1160     bool IsStopBackPress() const override
1161     {
1162         return isStopBackPress_;
1163     }
1164 
SetKeyboardAppearance(KeyboardAppearance value)1165     void SetKeyboardAppearance(KeyboardAppearance value)
1166     {
1167         TAG_LOGI(AceLogTag::ACE_RICH_TEXT, "SetKeyboardAppearance=%{public}d", value);
1168         keyboardAppearance_ = value;
1169     }
1170 
GetKeyboardAppearance()1171     KeyboardAppearance GetKeyboardAppearance() const
1172     {
1173         return keyboardAppearance_;
1174     }
1175 
IsDragging()1176     bool IsDragging() const override
1177     {
1178         return status_ == Status::DRAGGING || status_ == Status::FLOATING;
1179     }
1180 
GetSpanItemByPosition(int32_t position)1181     const RefPtr<SpanItem> GetSpanItemByPosition(int32_t position)
1182     {
1183         CHECK_NULL_RETURN(position >= 0, nullptr);
1184         auto it = GetSpanIter(position);
1185         CHECK_NULL_RETURN(it != spans_.end(), nullptr);
1186         return *it;
1187     }
1188 
GetColorMode()1189     ColorMode GetColorMode()
1190     {
1191         auto host = GetHost();
1192         CHECK_NULL_RETURN(!host, host->GetLocalColorMode());
1193         auto context = GetContext();
1194         CHECK_NULL_RETURN(context, ColorMode::COLOR_MODE_UNDEFINED);
1195         return context->GetLocalColorMode();
1196     }
1197 
GetDisplayColorMode()1198     ColorMode GetDisplayColorMode()
1199     {
1200         auto colorMode = GetColorMode();
1201         return colorMode == ColorMode::COLOR_MODE_UNDEFINED ? Container::CurrentColorMode() : colorMode;
1202     }
1203 
1204     template<typename T>
GetTheme()1205     RefPtr<T> GetTheme()
1206     {
1207         auto pipelineContext = GetContext();
1208         CHECK_NULL_RETURN(pipelineContext, {});
1209         if (isAPI20Plus) {
1210             return pipelineContext->GetTheme<T>(GetThemeScopeId());
1211         }
1212         return pipelineContext->GetTheme<T>();
1213     }
1214 
GetAISpanMap()1215     const std::map<int32_t, AISpan>& GetAISpanMap() override
1216     {
1217         auto& aiSpanMap = dataDetectorAdapter_->aiSpanMap_;
1218         if (aiSpanMap != lastAISpanMap_) {
1219             paragraphCache_.Clear();
1220             lastAISpanMap_ = aiSpanMap;
1221         }
1222         return aiSpanMap;
1223     }
1224 
1225 protected:
1226     bool CanStartAITask() override;
1227     std::vector<RectF> GetSelectedRects(int32_t start, int32_t end) override;
1228     PointF GetTextOffset(const Offset& localLocation, const RectF& contentRect) override;
1229     std::pair<int32_t, int32_t> GetStartAndEnd(int32_t start, const RefPtr<SpanItem>& spanItem) override;
1230 
1231 private:
1232     friend class RichEditorSelectOverlay;
1233     friend class OneStepDragController;
1234     bool HandleUrlSpanClickEvent(const GestureEvent& info);
1235     void HandleUrlSpanForegroundClear();
1236     bool HandleUrlSpanShowShadow(const Offset& localLocation, const Offset& globalOffset, const Color& color);
1237     Color GetUrlHoverColor();
1238     Color GetUrlPressColor();
1239     RefPtr<RichEditorSelectOverlay> selectOverlay_;
1240     Offset ConvertGlobalToLocalOffset(const Offset& globalOffset);
1241     void UpdateSelectMenuInfo(SelectMenuInfo& selectInfo);
1242     void HandleOnPaste() override;
1243     void PasteStr(const std::string& text);
1244     void HandleOnCut() override;
1245     void InitClickEvent(const RefPtr<GestureEventHub>& gestureHub) override;
1246     void InitFocusEvent(const RefPtr<FocusHub>& focusHub);
1247     void HandleBlurEvent();
1248     void HandleFocusEvent();
1249     void OnFocusNodeChange(FocusReason focusReason) override;
1250     void HandleClickEvent(GestureEvent& info);
1251     void HandleSingleClickEvent(GestureEvent& info);
1252     bool HandleClickSelection(const OHOS::Ace::GestureEvent& info);
1253     bool IsClickEventOnlyForMenuToggle(const OHOS::Ace::GestureEvent& info);
1254     Offset ConvertTouchOffsetToTextOffset(const Offset& touchOffset);
1255     bool IsShowSingleHandleByClick(const OHOS::Ace::GestureEvent& info, int32_t lastCaretPosition,
1256         const RectF& lastCaretRect, bool isCaretTwinkling);
1257     bool RepeatClickCaret(const Offset& offset, const RectF& lastCaretRect);
1258     void CreateAndShowSingleHandle();
1259     void MoveCaretAndStartFocus(const Offset& offset);
1260     void HandleDoubleClickEvent(GestureEvent& info);
1261     bool HandleUserClickEvent(GestureEvent& info);
1262     bool HandleUserLongPressEvent(GestureEvent& info);
1263     bool HandleUserDoubleClickEvent(GestureEvent& info);
1264     bool HandleUserGestureEvent(
1265         GestureEvent& info, std::function<bool(RefPtr<SpanItem> item, GestureEvent& info)>&& gestureFunc);
1266     void CalcCaretInfoByClick(const Offset& touchOffset);
1267     std::pair<OffsetF, float> CalcAndRecordLastClickCaretInfo(const Offset& textOffset);
1268     void HandleEnabled();
1269     void HandleAISpanHoverEvent(const MouseInfo& info) override;
1270     void InitMouseEvent();
1271     void ScheduleCaretTwinkling();
1272     void OnCaretTwinkling();
1273     void StartTwinkling();
1274     void ShowCaretWithoutTwinkling();
1275     void StopTwinkling();
1276     void UpdateFontFeatureTextStyle(
1277         RefPtr<SpanNode>& spanNode, struct UpdateSpanStyle& updateSpanStyle, TextStyle& textStyle);
1278     void UpdateDecoration(RefPtr<SpanNode>& spanNode, struct UpdateSpanStyle& updateSpanStyle, TextStyle& textStyle);
1279     void UpdateTextStyle(RefPtr<SpanNode>& spanNode, struct UpdateSpanStyle updateSpanStyle, TextStyle textStyle);
1280     void UpdateSymbolStyle(RefPtr<SpanNode>& spanNode, struct UpdateSpanStyle updateSpanStyle, TextStyle textStyle);
1281     void UpdateImageStyle(RefPtr<FrameNode>& imageNode, const ImageSpanAttribute& imageStyle);
1282     void UpdateImageAttribute(RefPtr<FrameNode>& imageNode, const ImageSpanAttribute& imageStyle);
1283     TextStyle CreateTextStyleByTypingStyle();
1284     void InitTouchEvent();
1285     void InitPanEvent();
1286     bool SelectOverlayIsOn();
1287     void HandleLongPress(GestureEvent& info);
1288     void HandleDoubleClickOrLongPress(GestureEvent& info);
1289     void HandleDoubleClickOrLongPress(GestureEvent& info, RefPtr<FrameNode> host);
1290     void StartVibratorByLongPress();
1291     std::string GetPositionSpansText(int32_t position, int32_t& startSpan);
1292     void FireOnSelect(int32_t selectStart, int32_t selectEnd);
1293     void FireOnSelectionChange(const int32_t caretPosition);
1294     void FireOnSelectionChange(const TextSelector& selector);
1295     void FireOnSelectionChange(int32_t selectStart, int32_t selectEnd, bool isForced = false);
1296     void MouseRightFocus(const MouseInfo& info);
1297     bool IsScrollBarPressed(const MouseInfo& info);
1298     void HandleMouseLeftButtonMove(const MouseInfo& info);
1299     void HandleMouseSelect(const Offset& localOffset);
1300     void HandleMouseLeftButtonPress(const MouseInfo& info);
1301     void HandleShiftSelect(int32_t position);
1302     void HandleMouseLeftButtonRelease(const MouseInfo& info);
1303     void HandleMouseLeftButton(const MouseInfo& info);
1304     void HandleMouseRightButton(const MouseInfo& info);
1305     void HandleMouseEvent(const MouseInfo& info);
1306     void HandleImageHoverEvent(const MouseInfo& info);
1307     void HandleTouchEvent(const TouchEventInfo& info);
1308     std::optional<TouchLocationInfo> GetAcceptedTouchLocationInfo(const TouchEventInfo& info);
1309     void HandleTouchDown(const TouchLocationInfo& info);
1310     void HandleTouchUp();
1311     void StartFloatingCaretLand();
1312     void ResetTouchAndMoveCaretState();
1313     void ResetTouchSelectState();
1314     void HandleTouchUpAfterLongPress();
1315     void HandleTouchCancelAfterLongPress();
1316     void HandleTouchMove(const TouchLocationInfo& info);
1317     void OnMoveCaretStart(int32_t fingerId);
1318     void UpdateCaretByTouchMove(const Offset& offset);
1319     void SetCaretTouchMoveOffset(const Offset& localOffset);
1320     RectF GetCaretBoundaryRect();
1321     Offset AdjustLocalOffsetOnMoveEvent(const Offset& originalOffset);
1322     void StartVibratorByIndexChange(int32_t currentIndex, int32_t preIndex);
1323     void InitLongPressEvent(const RefPtr<GestureEventHub>& gestureHub);
1324     void UseHostToUpdateTextFieldManager();
1325     void UpdateTextFieldManager(const Offset& offset, float height);
1326     void ScrollToSafeArea() const override;
1327     void InitDragDropEvent();
1328     void OnDragStartAndEnd();
1329     void onDragDropAndLeave();
1330     void ClearDragDropEvent();
1331     void OnDragMove(const RefPtr<OHOS::Ace::DragEvent>& event);
1332     void OnDragEnd(const RefPtr<Ace::DragEvent>& event);
1333     void ResetDragSpanItems();
1334     void ToJsonValue(std::unique_ptr<JsonValue>& json, const InspectorFilter& filter) const override;
1335     std::string GetPlaceHolderInJson() const;
1336     std::string GetTextColorInJson(const std::optional<Color>& value) const;
1337     void FillPreviewMenuInJson(const std::unique_ptr<JsonValue>& jsonValue) const override;
1338     void ResetSelectionAfterAddSpan(bool isPaste);
1339     RefPtr<UINode> GetChildByIndex(int32_t index) const override;
1340     void SetResultObjectText(ResultObject& resultObject, const RefPtr<SpanItem>& spanItem) override;
1341     SelectionInfo GetAdjustedSelectionInfo(const SelectionInfo& textSelectInfo);
ResetAfterTextChange()1342     void ResetAfterTextChange() override {};
1343     void AddOprationWhenAddImage(int32_t beforeCaretPos);
1344     void UpdateSpanNode(RefPtr<SpanNode> spanNode, const TextSpanOptions& options);
1345     void UpdateTextBackgroundStyle(RefPtr<SpanNode>& spanNode, const std::optional<TextBackgroundStyle>& style);
1346     void InitPlaceholderSpansMap(
1347         RefPtr<SpanItem>& newSpanItem, const RefPtr<SpanItem>& spanItem, size_t& index, size_t& placeholderGains);
1348     void ReplacePlaceholderWithCustomSpan(const RefPtr<SpanItem>& spanItem, size_t& index, size_t& textIndex);
1349     void ReplacePlaceholderWithSymbolSpan(const RefPtr<SpanItem>& spanItem, size_t& index, size_t& textIndex);
1350     void ReplacePlaceholderWithImageSpan(const RefPtr<SpanItem>& spanItem, size_t& index, size_t& textIndex);
AddDragFrameNodeToManager(const RefPtr<FrameNode> & frameNode)1351     void AddDragFrameNodeToManager(const RefPtr<FrameNode>& frameNode)
1352     {
1353         auto host = GetHost();
1354         CHECK_NULL_VOID(host);
1355         auto context = host->GetContext();
1356         CHECK_NULL_VOID(context);
1357         auto dragDropManager = context->GetDragDropManager();
1358         CHECK_NULL_VOID(dragDropManager);
1359         dragDropManager->AddDragFrameNode(frameNode->GetId(), AceType::WeakClaim(AceType::RawPtr(frameNode)));
1360     }
1361 
RemoveDragFrameNodeFromManager(const RefPtr<FrameNode> & frameNode)1362     void RemoveDragFrameNodeFromManager(const RefPtr<FrameNode>& frameNode)
1363     {
1364         auto host = GetHost();
1365         CHECK_NULL_VOID(host);
1366         auto context = host->GetContext();
1367         CHECK_NULL_VOID(context);
1368         auto dragDropManager = context->GetDragDropManager();
1369         CHECK_NULL_VOID(dragDropManager);
1370         dragDropManager->RemoveDragFrameNode(frameNode->GetId());
1371     }
1372 
1373     void HandleCursorOnDragMoved(const RefPtr<NotifyDragEvent>& notifyDragEvent);
1374     void HandleCursorOnDragLeaved(const RefPtr<NotifyDragEvent>& notifyDragEvent);
1375     void HandleCursorOnDragEnded(const RefPtr<NotifyDragEvent>& notifyDragEvent);
1376 
1377     int32_t GetParagraphLength(const std::list<RefPtr<UINode>>& spans) const;
1378     // REQUIRES: 0 <= start < end
1379     std::vector<RefPtr<SpanNode>> GetParagraphNodes(int32_t start, int32_t end) const;
1380     void OnHover(bool isHover);
1381     void ChangeMouseStyle(MouseFormat format, bool freeMouseHoldNode = false);
1382     bool RequestKeyboard(bool isFocusViewChanged, bool needStartTwinkling, bool needShowSoftKeyboard,
1383         SourceType sourceType = SourceType::NONE);
1384     void UpdateCaretInfoToController();
1385 #if defined(ENABLE_STANDARD_INPUT)
1386     bool EnableStandardInput(bool needShowSoftKeyboard, SourceType sourceType = SourceType::NONE);
1387     std::optional<MiscServices::TextConfig> GetMiscTextConfig();
1388 #else
1389     bool UnableStandardInput(bool isFocusViewChanged);
1390 #endif
1391 
1392     bool HasConnection() const;
1393     bool CloseKeyboard(bool forceClose) override;
1394     void CalcInsertValueObj(TextInsertValueInfo& info);
1395     void CalcDeleteValueObj(int32_t currentPosition, int32_t length, RichEditorDeleteValue& info);
1396     RefPtr<SpanNode> GetSpanNodeBySpanItem(const RefPtr<SpanItem> spanItem);
1397     int32_t DeleteValueSetBuilderSpan(const RefPtr<SpanItem>& spanItem, RichEditorAbstractSpanResult& spanResult);
1398     int32_t DeleteValueSetImageSpan(const RefPtr<SpanItem>& spanItem, RichEditorAbstractSpanResult& spanResult);
1399     int32_t DeleteValueSetSymbolSpan(const RefPtr<SpanItem>& spanItem, RichEditorAbstractSpanResult& spanResult);
1400     int32_t DeleteValueSetTextSpan(const RefPtr<SpanItem>& spanItem, int32_t currentPosition, int32_t length,
1401         RichEditorAbstractSpanResult& spanResult);
1402     void DeleteByDeleteValueInfo(const RichEditorDeleteValue& info);
1403     int32_t ProcessDeleteNodes(std::list<RichEditorAbstractSpanResult>& deleteSpans);
1404     bool OnKeyEvent(const KeyEvent& keyEvent);
1405     void MoveCaretAfterTextChange();
1406     bool BeforeIMEInsertValue(const std::u16string& insertValue);
1407     void AfterInsertValue(
1408         const RefPtr<SpanNode>& spanNode, int32_t insertValueLength, bool isCreate, bool isIme = true);
1409     bool AfterIMEInsertValue(const RefPtr<SpanNode>& spanNode, int32_t moveLength, bool isCreate);
1410     RefPtr<SpanNode> InsertValueToBeforeSpan(RefPtr<SpanNode>& spanNodeBefore, const std::u16string& insertValue);
1411     void SetCaretSpanIndex(int32_t index);
1412     bool HasSameTypingStyle(const RefPtr<SpanNode>& spanNode);
1413 
1414     void GetChangeSpanStyle(RichEditorChangeValue& changeValue, std::optional<TextStyle>& spanTextStyle,
1415         std::optional<struct UpdateParagraphStyle>& spanParaStyle, std::optional<std::u16string>& urlAddress,
1416         const RefPtr<SpanNode>& spanNode, int32_t spanIndex);
1417     void GetReplacedSpan(RichEditorChangeValue& changeValue, int32_t& innerPosition, const std::u16string& insertValue,
1418         int32_t textIndex, std::optional<TextStyle> textStyle, std::optional<struct UpdateParagraphStyle> paraStyle,
1419         std::optional<std::u16string> urlAddress = std::nullopt, bool isCreate = false, bool fixDel = true);
1420     void GetReplacedSpanFission(RichEditorChangeValue& changeValue, int32_t& innerPosition, std::u16string& content,
1421         int32_t startSpanIndex, int32_t offsetInSpan, std::optional<TextStyle> textStyle,
1422         std::optional<struct UpdateParagraphStyle> paraStyle, const std::optional<std::u16string>& urlAddress);
1423     void CreateSpanResult(RichEditorChangeValue& changeValue, int32_t& innerPosition, int32_t spanIndex,
1424         int32_t offsetInSpan, int32_t endInSpan, std::u16string content, std::optional<TextStyle> textStyle,
1425         std::optional<struct UpdateParagraphStyle> paraStyle, const std::optional<std::u16string>& urlAddress);
1426     void SetTextStyleToRet(RichEditorAbstractSpanResult& retInfo, const TextStyle& textStyle);
1427     void CalcInsertValueObj(TextInsertValueInfo& info, int textIndex, bool isCreate = false);
1428     void GetDeletedSpan(RichEditorChangeValue& changeValue, int32_t& innerPosition, int32_t length,
1429         RichEditorDeleteDirection direction = RichEditorDeleteDirection::FORWARD);
1430     RefPtr<SpanItem> GetDelPartiallySpanItem(
1431         RichEditorChangeValue& changeValue, std::u16string& originalStr, int32_t& originalPos);
1432     void FixMoveDownChange(RichEditorChangeValue& changeValue, int32_t delLength);
1433     bool BeforeChangeText(
1434         RichEditorChangeValue& changeValue, const OperationRecord& record, RecordType type, int32_t delLength = 0);
1435     void BeforeUndo(RichEditorChangeValue& changeValue, int32_t& innerPosition, const OperationRecord& record);
1436     void BeforeRedo(RichEditorChangeValue& changeValue, int32_t& innerPosition, const OperationRecord& record);
1437     void BeforeDrag(RichEditorChangeValue& changeValue, int32_t& innerPosition, const OperationRecord& record);
1438     bool BeforeChangeText(RichEditorChangeValue& changeValue, const TextSpanOptions& options);
1439 
1440     // add for scroll.
1441     void UpdateChildrenOffset();
1442     void MoveFirstHandle(float offset);
1443     void MoveSecondHandle(float offset);
1444     void InitScrollablePattern();
1445     bool IsReachedBoundary(float offset);
1446     void UpdateScrollBarOffset() override;
1447     void CheckScrollable();
1448     void UpdateMagnifierStateAfterLayout(bool frameSizeChange);
1449     void UpdateScrollStateAfterLayout(bool shouldDisappear);
1450     void ScheduleAutoScroll(AutoScrollParam param);
1451     void OnAutoScroll(AutoScrollParam param);
1452     void StopAutoScroll();
1453     void AutoScrollByEdgeDetection(AutoScrollParam param, OffsetF offset, EdgeDetectionStrategy strategy);
1454     float CalcDragSpeed(float hotAreaStart, float hotAreaEnd, float point);
1455     float MoveTextRect(float offset);
1456     void SetNeedMoveCaretToContentRect();
1457     void MoveCaretToContentRect();
1458     void MoveCaretToContentRect(const OffsetF& caretOffset, float caretHeight);
1459     void MoveCaretToContentRect(float offset, int32_t source);
1460     bool IsCaretInContentArea();
IsTextArea()1461     bool IsTextArea() const override
1462     {
1463         return true;
1464     }
1465     void ProcessInnerPadding();
IsReachTop()1466     bool IsReachTop()
1467     {
1468         return NearEqual(richTextRect_.GetY(), contentRect_.GetY());
1469     }
1470 
IsReachBottom()1471     bool IsReachBottom()
1472     {
1473         return NearEqual(richTextRect_.Bottom(), contentRect_.Bottom());
1474     }
1475     // ai analysis fun
1476     bool NeedAiAnalysis(
1477         const CaretUpdateType targeType, const int32_t pos, const int32_t& spanStart, const std::string& content);
1478     bool IsIndexAfterOrInSymbolOrEmoji(int32_t index);
1479     void AdjustCursorPosition(int32_t& pos);
1480     void AdjustPlaceholderSelection(int32_t& start, int32_t& end, const Offset& pos);
1481     bool AdjustWordSelection(int32_t& start, int32_t& end);
1482     bool IsTouchAtLineEnd(int32_t caretPos, const Offset& textOffset);
1483     bool IsTouchBeforeCaret(int32_t caretPos, const Offset& textOffset);
1484     bool IsClickBoundary(const int32_t position);
1485     void SetSelfAndChildDraggableFalse(const RefPtr<UINode>& customNode);
1486     RefPtr<SpanItem> GetSameSpanItem(const RefPtr<SpanItem>& spanItem);
1487     RefPtr<ImageSpanNode> GetImageSpanNodeBySpanItem(const RefPtr<ImageSpanItem>& spanItem);
1488 
1489     void AdjustSelectRects(SelectRectsType pos, std::vector<RectF>& selectRects);
1490     RectF GetSelectArea(SelectRectsType pos);
1491     void AppendSelectRect(std::vector<RectF>& selectRects);
1492     bool IsTouchInFrameArea(const PointF& touchPoint);
1493     void HandleOnDragDrop(const RefPtr<OHOS::Ace::DragEvent>& event, bool isCopy = false);
1494     void DeleteForward(int32_t currentPosition, int32_t length);
1495     int32_t HandleOnDragDeleteForward();
1496     void HandleOnDragDropTextOperation(const std::u16string& insertValue, bool isDeleteSelect, bool isCopy = false);
1497     void UndoDrag(const OperationRecord& record);
1498     void RedoDrag(const OperationRecord& record);
1499     void HandleOnDragInsertValueOperation(const std::u16string& insertValue);
1500     void HandleOnDragInsertValue(const std::u16string& str);
1501     void HandleOnEditChanged(bool isEditing);
1502     void OnTextInputActionUpdate(TextInputAction value);
1503     void CloseSystemMenu();
1504     void SetAccessibilityAction() override;
1505     void SetAccessibilityEditAction();
1506     bool IsAccessibilityClick();
1507     void HandleTripleClickEvent(OHOS::Ace::GestureEvent& info);
1508     void UpdateSelectionByTouchMove(const Offset& offset);
1509     bool CheckTripClickEvent(GestureEvent& info);
1510     void HandleSelect(GestureEvent& info, int32_t selectStart, int32_t selectEnd);
1511     TextStyleResult GetTextStyleBySpanItem(const RefPtr<SpanItem>& spanItem);
1512     ImageStyleResult GetImageStyleBySpanItem(const RefPtr<SpanItem>& spanItem);
1513     void SetSubSpans(RefPtr<SpanString>& spanString, int32_t start, int32_t end);
1514     void SetSubMap(RefPtr<SpanString>& spanString);
1515     void OnCopyOperationExt(RefPtr<PasteDataMix>& pasteData);
1516     void AddSpanByPasteData(const RefPtr<SpanString>& spanString);
1517     void CompleteStyledString(RefPtr<SpanString>& spanString);
1518     void InsertStyledStringByPaste(const RefPtr<SpanString>& spanString);
1519     void HandleOnDragInsertStyledString(const RefPtr<SpanString>& spanString, bool isCopy = false);
1520     void AddSpansByPaste(const std::list<RefPtr<NG::SpanItem>>& spans);
1521     TextSpanOptions GetTextSpanOptions(const RefPtr<SpanItem>& spanItem);
1522     void HandleOnCopyStyledString();
1523     void HandleOnDragDropStyledString(const RefPtr<OHOS::Ace::DragEvent>& event, bool isCopy = false);
1524     void NotifyExitTextPreview(bool deletePreviewText = true);
1525     void NotifyImfFinishTextPreview();
1526     int32_t CalculateTruncationLength(const std::u16string& insertValue, int32_t start);
1527     bool ProcessTextTruncationOperation(std::u16string& text, bool calledByImf);
1528     void ProcessInsertValueMore(const std::u16string& text, OperationRecord record, OperationType operationType,
1529         RichEditorChangeValue changeValue, PreviewTextRecord preRecord);
1530     void ProcessInsertValue(const std::u16string& insertValue, OperationType operationType = OperationType::DEFAULT,
1531         bool calledbyImf = false);
1532     void FinishTextPreviewInner(bool deletePreviewText = true);
1533     void TripleClickSection(GestureEvent& info, int32_t start, int32_t end, int32_t pos);
1534     void ProcessOverlayOnSetSelection(const std::optional<SelectionOptions>& options);
1535     std::pair<int32_t, SelectType> JudgeSelectType(const Offset& pos);
1536     bool IsSelectEmpty(int32_t start, int32_t end);
1537     bool AdjustIndexSkipLineSeparator(int32_t& currentPosition);
1538     bool AdjustIndexSkipSpace(int32_t& currentPosition, const MoveDirection direction);
1539     void RequestKeyboardToEdit();
HandleTasksOnLayoutSwap()1540     void HandleTasksOnLayoutSwap()
1541     {
1542         while (!tasks_.empty()) {
1543             const auto& task = tasks_.front();
1544             if (task) {
1545                 task();
1546             }
1547             tasks_.pop();
1548         }
1549     }
PostTaskToLayutSwap(std::function<void ()> && task)1550     void PostTaskToLayutSwap(std::function<void()>&& task)
1551     {
1552         tasks_.emplace(std::forward<std::function<void()>>(task));
1553     }
1554 
1555     OffsetF GetGlobalOffset() const;
1556     void MergeAdjacentSpans(int32_t caretPosition);
1557     void HandleImageDrag(const RefPtr<ImageSpanNode>& imageNode);
1558     void DisableDrag(const RefPtr<ImageSpanNode>& imageNode);
1559     void SetGestureOptions(UserGestureOptions userGestureOptions, RefPtr<SpanItem> spanItem);
1560     void AddSpanHoverEvent(
1561         RefPtr<SpanItem> spanItem, const RefPtr<FrameNode>& frameNode, const SpanOptionBase& options);
1562     void UpdateGestureHotZone(const RefPtr<LayoutWrapper>& dirty);
1563     void ClearOnFocusTextField(FrameNode* node);
1564     void ProcessResultObject(RefPtr<PasteDataMix> pasteData, const ResultObject& result);
1565     void EncodeTlvDataByResultObject(const ResultObject& result, std::vector<uint8_t>& tlvData);
1566     bool InitPreviewText(const std::u16string& previewTextValue, const PreviewRange& range);
1567     bool ReplaceText(const std::u16string& previewTextValue, const PreviewRange& range);
1568     bool UpdatePreviewText(const std::u16string& previewTextValue, const PreviewRange& range);
1569     bool IsEnPreview();
1570     void SetMagnifierLocalOffset(Offset localOffset);
1571     void SetMagnifierOffsetWithAnimation(Offset offset);
1572     void UpdateSelectionAndHandleVisibility();
1573     void SetIsEnableSubWindowMenu();
1574 
1575 #if defined(ENABLE_STANDARD_INPUT)
1576     sptr<OHOS::MiscServices::OnTextChangedListener> richEditTextChangeListener_;
1577 #else
1578     RefPtr<TextInputConnection> connection_ = nullptr;
1579 #endif
1580     const bool isAPI14Plus;
1581     const bool isAPI16Plus;
1582     const bool isAPI18Plus;
1583     const bool isAPI20Plus;
1584     bool shiftFlag_ = false;
1585     bool isMouseSelect_ = false;
1586     bool isMousePressed_ = false;
1587     bool isFirstMouseSelect_ = true;
1588     bool leftMousePress_ = false;
1589     bool isLongPress_ = false;
1590 #if defined(OHOS_STANDARD_SYSTEM) && !defined(PREVIEW)
1591     bool imeAttached_ = false;
1592     bool imeShown_ = false;
1593 #endif
1594     bool isTextChange_ = false;
1595     bool caretVisible_ = false;
1596     bool caretTwinkling_ = false;
1597     bool isRichEditorInit_ = false;
1598     bool clickEventInitialized_ = false;
1599     bool focusEventInitialized_ = false;
1600     bool blockPress_ = false;
1601     bool isCustomKeyboardAttached_ = false;
1602     bool usingMouseRightButton_ = false;
1603     bool isCursorAlwaysDisplayed_ = false;
1604     bool isClickOnAISpan_ = false;
1605     bool isOnlyRequestFocus_ = false;
1606 
1607     int32_t moveLength_ = 0;
1608     int32_t insertValueLength_ = 0;
1609     int32_t lastCaretPosition_ = 0;
1610     int32_t caretPosition_ = 0;
1611     int32_t caretSpanIndex_ = -1;
1612     long long timestamp_ = 0;
1613     CaretAffinityPolicy caretAffinityPolicy_ = CaretAffinityPolicy::DEFAULT;
1614     OffsetF selectionMenuOffsetByMouse_;
1615     OffsetF selectionMenuOffsetClick_;
1616     OffsetF lastClickOffset_;
1617     std::u16string pasteStr_;
1618 
1619     // still in progress
1620     RichEditorParagraphManager paragraphs_;
1621     RefPtr<Paragraph> presetParagraph_;
1622     std::vector<OperationRecord> operationRecords_;
1623     std::vector<OperationRecord> redoOperationRecords_;
1624     std::list<WeakPtr<ImageSpanNode>> hoverableNodes;
1625     RefPtr<ImageSpanItem> lastHoverSpanItem_ = nullptr;
1626     HoverInfo lastHoverInfo_;
1627 
1628     RefPtr<TouchEventImpl> touchListener_;
1629     RefPtr<PanEvent> panEvent_;
1630     struct UpdateSpanStyle updateSpanStyle_;
1631     CancelableCallback<void()> caretTwinklingTask_;
1632     RefPtr<RichEditorController> richEditorController_;
1633     RefPtr<RichEditorStyledStringController> richEditorStyledStringController_;
1634     MoveDirection moveDirection_ = MoveDirection::FORWARD;
1635     RectF frameRect_;
1636     std::optional<struct UpdateSpanStyle> typingStyle_;
1637     std::optional<TextStyle> typingTextStyle_;
1638     std::list<ResultObject> dragResultObjects_;
1639     std::optional<Color> caretColor_;
1640     std::optional<Color> selectedBackgroundColor_;
1641     std::function<void()> customKeyboardBuilder_;
1642     std::function<void(int32_t)> caretChangeListener_;
1643     RefPtr<OverlayManager> keyboardOverlay_;
1644     RefPtr<AIWriteAdapter> aiWriteAdapter_ = MakeRefPtr<AIWriteAdapter>();
1645     Offset selectionMenuOffset_;
1646     // add for scroll
1647     RectF richTextRect_;
1648     float scrollOffset_ = 0.0f;
1649     bool isFirstCallOnReady_ = false;
1650     bool scrollable_ = true;
1651     CancelableCallback<void()> autoScrollTask_;
1652     OffsetF prevAutoScrollOffset_;
1653     AutoScrollParam currentScrollParam_;
1654     bool isAutoScrollRunning_ = false;
1655     // add for ai input analysis
1656     bool hasClicked_ = false;
1657     CaretUpdateType caretUpdateType_ = CaretUpdateType::NONE;
1658     TimeStamp lastClickTimeStamp_;
1659     TimeStamp lastAiPosTimeStamp_;
1660     bool adjusted_ = false;
1661     bool isShowMenu_ = true;
1662     bool isShowPlaceholder_ = false;
1663     bool isSingleHandle_ = false;
1664     TouchAndMoveCaretState moveCaretState_;
1665     FloatingCaretState floatingCaretState_;
1666     std::shared_ptr<AnimationUtils::Animation> magnifierAnimation_;
1667     // Recorded when touch down or mouse left button press.
1668     OffsetF globalOffsetOnMoveStart_;
1669     SelectionRangeInfo lastSelectionRange_{-1, -1};
1670     bool isDragSponsor_ = false;
1671     std::pair<int32_t, int32_t> dragRange_ { 0, 0 };
1672     bool isEditing_ = false;
1673     int32_t dragPosition_ = 0;
1674     // Action when "enter" pressed.
1675     TextInputAction action_ = TextInputAction::NEW_LINE;
1676     // What the keyboard appears.
1677     TextInputType keyboard_ = TextInputType::UNSPECIFIED;
1678     ACE_DISALLOW_COPY_AND_MOVE(RichEditorPattern);
1679     bool keyboardAvoidance_ = false;
1680     int32_t richEditorInstanceId_ = -1;
1681     int32_t frameId_ = -1;
1682     bool contentChange_ = false;
1683     PreviewTextRecord previewTextRecord_;
1684     bool isTextPreviewSupported_ = true;
1685     OffsetF movingHandleOffset_;
1686     std::pair<int32_t, int32_t> initSelector_ = { 0, 0 };
1687     std::vector<TimeStamp> clickInfo_;
1688     int32_t selectingFingerId_ = -1;
1689     bool isTouchSelecting_ = false;
1690     bool previewLongPress_ = false;
1691     bool editingLongPress_ = false;
1692     bool needMoveCaretToContentRect_ = false;
1693     std::queue<std::function<void()>> tasks_;
1694     bool isModifyingContent_ = false;
1695     bool needToRequestKeyboardOnFocus_ = true;
1696     bool isEnableHapticFeedback_ = true;
1697     float maxLinesHeight_ = FLT_MAX;
1698     int32_t maxLines_ = INT32_MAX;
1699     std::unordered_map<std::u16string, RefPtr<SpanItem>> placeholderSpansMap_;
1700     std::optional<DisplayMode> barDisplayMode_ = std::nullopt;
1701     uint32_t twinklingInterval_ = 0;
1702     bool isTriggerAvoidOnCaretAvoidMode_ = false;
1703     RectF lastRichTextRect_;
1704     std::optional<int32_t> maxLength_ = std::nullopt;
1705     std::unique_ptr<OneStepDragController> oneStepDragController_;
1706     std::list<WeakPtr<ImageSpanNode>> imageNodes;
1707     std::list<WeakPtr<PlaceholderSpanNode>> builderNodes;
1708     bool isStopBackPress_ = true;
1709     bool blockKbInFloatingWindow_ = false;
1710     KeyboardAppearance keyboardAppearance_ = KeyboardAppearance::NONE_IMMERSIVE;
1711     LRUMap<std::uintptr_t, RefPtr<Paragraph>> paragraphCache_;
1712     SysScale lastSysScale_;
1713     std::map<int32_t, AISpan> lastAISpanMap_;
1714 };
1715 } // namespace OHOS::Ace::NG
1716 
1717 #endif // FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_NG_PATTERNS_RICH_EDITOR_RICH_EDITOR_PATTERN_H
1718