• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-2023 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 #include "core/components_ng/pattern/web/web_pattern.h"
17 
18 #include <securec.h>
19 #include <algorithm>
20 
21 #include "display_manager.h"
22 #include "file_uri.h"
23 #include "image_source.h"
24 #include "parameters.h"
25 
26 #include "base/geometry/ng/offset_t.h"
27 #include "base/image/file_uri_helper.h"
28 #include "base/mousestyle/mouse_style.h"
29 #include "base/utils/date_util.h"
30 #include "base/utils/linear_map.h"
31 #include "base/utils/utils.h"
32 #include "core/components/dialog/dialog_theme.h"
33 #include "core/components/picker/picker_data.h"
34 #include "core/components/text_overlay/text_overlay_theme.h"
35 #include "core/components/web/resource/web_delegate.h"
36 #include "core/components/web/web_property.h"
37 #include "core/components_ng/base/view_stack_processor.h"
38 #include "core/components_ng/pattern/menu/menu_view.h"
39 #include "core/components_ng/pattern/menu/wrapper/menu_wrapper_pattern.h"
40 #include "core/components_ng/pattern/overlay/overlay_manager.h"
41 #include "core/components_ng/pattern/swiper/swiper_pattern.h"
42 #include "core/components_ng/pattern/web/web_event_hub.h"
43 #include "core/event/key_event.h"
44 #include "core/event/touch_event.h"
45 #include "core/pipeline_ng/pipeline_context.h"
46 #include "frameworks/base/utils/system_properties.h"
47 #include "frameworks/core/components_ng/base/ui_node.h"
48 
49 #include "base/geometry/rect.h"
50 #include "core/common/ace_engine_ext.h"
51 #include "core/common/udmf/udmf_client.h"
52 #include "core/common/udmf/unified_data.h"
53 
54 namespace OHOS::Ace::NG {
55 namespace {
56 const std::string IMAGE_POINTER_CONTEXT_MENU_PATH = "etc/webview/ohos_nweb/context-menu.svg";
57 const std::string IMAGE_POINTER_ALIAS_PATH = "etc/webview/ohos_nweb/alias.svg";
58 constexpr int32_t UPDATE_WEB_LAYOUT_DELAY_TIME = 20;
59 const LinearEnumMapNode<OHOS::NWeb::CursorType, MouseFormat> g_cursorTypeMap[] = {
60     { OHOS::NWeb::CursorType::CT_CROSS, MouseFormat::CROSS },
61     { OHOS::NWeb::CursorType::CT_HAND, MouseFormat::HAND_POINTING },
62     { OHOS::NWeb::CursorType::CT_IBEAM, MouseFormat::TEXT_CURSOR },
63     { OHOS::NWeb::CursorType::CT_WAIT, MouseFormat::LOADING },
64     { OHOS::NWeb::CursorType::CT_HELP, MouseFormat::HELP },
65     { OHOS::NWeb::CursorType::CT_EASTRESIZE, MouseFormat::WEST_EAST },
66     { OHOS::NWeb::CursorType::CT_NORTHRESIZE, MouseFormat::NORTH_SOUTH },
67     { OHOS::NWeb::CursorType::CT_NORTHEASTRESIZE, MouseFormat::NORTH_EAST_SOUTH_WEST },
68     { OHOS::NWeb::CursorType::CT_NORTHWESTRESIZE, MouseFormat::NORTH_WEST_SOUTH_EAST },
69     { OHOS::NWeb::CursorType::CT_SOUTHRESIZE, MouseFormat::NORTH_SOUTH },
70     { OHOS::NWeb::CursorType::CT_SOUTHEASTRESIZE, MouseFormat::NORTH_WEST_SOUTH_EAST },
71     { OHOS::NWeb::CursorType::CT_SOUTHWESTRESIZE, MouseFormat::NORTH_EAST_SOUTH_WEST },
72     { OHOS::NWeb::CursorType::CT_WESTRESIZE, MouseFormat::WEST_EAST },
73     { OHOS::NWeb::CursorType::CT_NORTHSOUTHRESIZE, MouseFormat::NORTH_SOUTH },
74     { OHOS::NWeb::CursorType::CT_EASTWESTRESIZE, MouseFormat::WEST_EAST },
75     { OHOS::NWeb::CursorType::CT_NORTHEASTSOUTHWESTRESIZE, MouseFormat::NORTH_EAST_SOUTH_WEST },
76     { OHOS::NWeb::CursorType::CT_NORTHWESTSOUTHEASTRESIZE, MouseFormat::NORTH_WEST_SOUTH_EAST },
77     { OHOS::NWeb::CursorType::CT_COLUMNRESIZE, MouseFormat::RESIZE_LEFT_RIGHT },
78     { OHOS::NWeb::CursorType::CT_ROWRESIZE, MouseFormat::RESIZE_UP_DOWN },
79     { OHOS::NWeb::CursorType::CT_MIDDLEPANNING, MouseFormat::MIDDLE_BTN_NORTH_SOUTH_WEST_EAST },
80     { OHOS::NWeb::CursorType::CT_EASTPANNING, MouseFormat::MIDDLE_BTN_EAST },
81     { OHOS::NWeb::CursorType::CT_NORTHPANNING, MouseFormat::MIDDLE_BTN_NORTH },
82     { OHOS::NWeb::CursorType::CT_NORTHEASTPANNING, MouseFormat::MIDDLE_BTN_NORTH_EAST },
83     { OHOS::NWeb::CursorType::CT_NORTHWESTPANNING, MouseFormat::MIDDLE_BTN_NORTH_WEST },
84     { OHOS::NWeb::CursorType::CT_SOUTHPANNING, MouseFormat::MIDDLE_BTN_SOUTH },
85     { OHOS::NWeb::CursorType::CT_SOUTHEASTPANNING, MouseFormat::MIDDLE_BTN_SOUTH_EAST },
86     { OHOS::NWeb::CursorType::CT_SOUTHWESTPANNING, MouseFormat::MIDDLE_BTN_SOUTH_WEST },
87     { OHOS::NWeb::CursorType::CT_WESTPANNING, MouseFormat::MIDDLE_BTN_WEST },
88     { OHOS::NWeb::CursorType::CT_MOVE, MouseFormat::CURSOR_MOVE },
89     { OHOS::NWeb::CursorType::CT_VERTICALTEXT, MouseFormat::HORIZONTAL_TEXT_CURSOR },
90     { OHOS::NWeb::CursorType::CT_CELL, MouseFormat::CURSOR_CROSS },
91     { OHOS::NWeb::CursorType::CT_PROGRESS, MouseFormat::RUNNING },
92     { OHOS::NWeb::CursorType::CT_NODROP, MouseFormat::CURSOR_FORBID },
93     { OHOS::NWeb::CursorType::CT_COPY, MouseFormat::CURSOR_COPY },
94     { OHOS::NWeb::CursorType::CT_NONE, MouseFormat::CURSOR_NONE },
95     { OHOS::NWeb::CursorType::CT_NOTALLOWED, MouseFormat::CURSOR_FORBID },
96     { OHOS::NWeb::CursorType::CT_ZOOMIN, MouseFormat::ZOOM_IN },
97     { OHOS::NWeb::CursorType::CT_ZOOMOUT, MouseFormat::ZOOM_OUT },
98     { OHOS::NWeb::CursorType::CT_GRAB, MouseFormat::HAND_OPEN },
99     { OHOS::NWeb::CursorType::CT_GRABBING, MouseFormat::HAND_GRABBING },
100     { OHOS::NWeb::CursorType::CT_MIDDLE_PANNING_VERTICAL, MouseFormat::MIDDLE_BTN_NORTH_SOUTH },
101     { OHOS::NWeb::CursorType::CT_MIDDLE_PANNING_HORIZONTAL, MouseFormat::MIDDLE_BTN_NORTH_SOUTH_WEST_EAST },
102 };
103 
ParseDateTimeJson(const std::string & timeJson,NWeb::DateTime & result)104 bool ParseDateTimeJson(const std::string& timeJson, NWeb::DateTime& result)
105 {
106     auto sourceJson = JsonUtil::ParseJsonString(timeJson);
107     if (!sourceJson || sourceJson->IsNull()) {
108         return false;
109     }
110 
111     auto year = sourceJson->GetValue("year");
112     if (year && year->IsNumber()) {
113         result.year = year->GetInt();
114     }
115     auto month = sourceJson->GetValue("month");
116     if (month && month->IsNumber()) {
117         result.month = month->GetInt();
118     }
119     auto day = sourceJson->GetValue("day");
120     if (day && day->IsNumber()) {
121         result.day = day->GetInt();
122     }
123     auto hour = sourceJson->GetValue("hour");
124     if (hour && hour->IsNumber()) {
125         result.hour = hour->GetInt();
126     }
127     auto minute = sourceJson->GetValue("minute");
128     if (minute && minute->IsNumber()) {
129         result.minute = minute->GetInt();
130     }
131     return true;
132 }
133 
ParseTextJsonValue(const std::string & textJson)134 std::string ParseTextJsonValue(const std::string& textJson)
135 {
136     auto sourceJson = JsonUtil::ParseJsonString(textJson);
137     if (!sourceJson || sourceJson->IsNull()) {
138         return "";
139     }
140     auto value = sourceJson->GetValue("value");
141     if (value && value->IsString()) {
142         return value->GetString();
143     }
144     return "";
145 }
146 } // namespace
147 
148 constexpr int32_t SINGLE_CLICK_NUM = 1;
149 constexpr int32_t DOUBLE_CLICK_NUM = 2;
150 constexpr double DEFAULT_DBCLICK_INTERVAL = 0.5;
151 constexpr double DEFAULT_DBCLICK_OFFSET = 2.0;
152 constexpr double DEFAULT_AXIS_RATIO = -0.06;
153 constexpr double DEFAULT_WEB_WIDTH = 100.0;
154 constexpr double DEFAULT_WEB_HEIGHT = 80.0;
155 constexpr uint32_t DEFAULT_WEB_DRAW_HEIGHT = 4000;
156 const std::string PATTERN_TYPE_WEB = "WEBPATTERN";
157 constexpr int32_t SURFACE_QUEUE_SIZE = 8;
158 constexpr uint32_t DEBUG_DRAGMOVEID_TIMER = 30;
159 // web feature params
160 constexpr char VISIBLE_ACTIVE_ENABLE[] = "persist.web.visible_active_enable";
161 constexpr char MEMORY_LEVEL_ENABEL[] = "persist.web.memory_level_enable";
162 const std::vector<int32_t> DEFAULT_HEIGHT_GEAR {7998, 7999, 8001, 8002, 8003};
163 const std::vector<int32_t> DEFAULT_ORIGN_GEAR {0, 2000, 4000, 6000, 8000};
164 
165 WebPattern::WebPattern() = default;
166 
WebPattern(const std::string & webSrc,const RefPtr<WebController> & webController,WebType type,bool incognitoMode)167 WebPattern::WebPattern(const std::string& webSrc,
168                        const RefPtr<WebController>& webController,
169                        WebType type,
170                        bool incognitoMode)
171     : webSrc_(std::move(webSrc)), webController_(webController), type_(type),
172       incognitoMode_(incognitoMode)
173 {}
174 
WebPattern(const std::string & webSrc,const SetWebIdCallback & setWebIdCallback,WebType type,bool incognitoMode)175 WebPattern::WebPattern(const std::string& webSrc,
176                        const SetWebIdCallback& setWebIdCallback,
177                        WebType type,
178                        bool incognitoMode)
179     : webSrc_(std::move(webSrc)), setWebIdCallback_(setWebIdCallback), type_(type),
180       incognitoMode_(incognitoMode) {}
181 
~WebPattern()182 WebPattern::~WebPattern()
183 {
184     TAG_LOGI(AceLogTag::ACE_WEB, "Web pattern destory");
185     if (delegate_) {
186         delegate_->SetAudioMuted(true);
187     }
188 
189     if (observer_) {
190         observer_->NotifyDestory();
191     }
192     if (isActive_) {
193         OnInActive();
194     }
195 }
196 
NeedSoftKeyboard() const197 bool WebPattern::NeedSoftKeyboard() const
198 {
199     if (delegate_) {
200         return delegate_->NeedSoftKeyboard();
201     }
202     return false;
203 }
204 
OnAttachToFrameNode()205 void WebPattern::OnAttachToFrameNode()
206 {
207     auto host = GetHost();
208     CHECK_NULL_VOID(host);
209     host->GetRenderContext()->SetClipToFrame(true);
210     host->GetRenderContext()->UpdateBackgroundColor(Color::WHITE);
211     host->GetLayoutProperty()->UpdateMeasureType(MeasureType::MATCH_PARENT);
212     auto pipeline = PipelineContext::GetCurrentContext();
213     CHECK_NULL_VOID(pipeline);
214     pipeline->AddNodesToNotifyMemoryLevel(host->GetId());
215 }
216 
OnDetachFromFrameNode(FrameNode * frameNode)217 void WebPattern::OnDetachFromFrameNode(FrameNode* frameNode)
218 {
219     CHECK_NULL_VOID(delegate_);
220     isFocus_ = false;
221     delegate_->OnBlur();
222     OnQuickMenuDismissed();
223 
224     auto id = frameNode->GetId();
225     auto pipeline = AceType::DynamicCast<PipelineContext>(PipelineBase::GetCurrentContext());
226     CHECK_NULL_VOID(pipeline);
227     pipeline->RemoveWindowStateChangedCallback(id);
228     pipeline->RemoveWindowSizeChangeCallback(id);
229     pipeline->RemoveNodesToNotifyMemoryLevel(id);
230 }
231 
InitEvent()232 void WebPattern::InitEvent()
233 {
234     auto host = GetHost();
235     CHECK_NULL_VOID(host);
236     auto eventHub = host->GetEventHub<WebEventHub>();
237     CHECK_NULL_VOID(eventHub);
238 
239     auto gestureHub = eventHub->GetOrCreateGestureEventHub();
240     CHECK_NULL_VOID(gestureHub);
241 
242     InitTouchEvent(gestureHub);
243     InitDragEvent(gestureHub);
244     InitPanEvent(gestureHub);
245 
246     auto inputHub = eventHub->GetOrCreateInputEventHub();
247     CHECK_NULL_VOID(inputHub);
248     InitMouseEvent(inputHub);
249     InitHoverEvent(inputHub);
250 
251     auto focusHub = eventHub->GetOrCreateFocusHub();
252     CHECK_NULL_VOID(focusHub);
253     InitFocusEvent(focusHub);
254 
255     auto context = PipelineContext::GetCurrentContext();
256     CHECK_NULL_VOID(context);
257     auto langTask = [weak = AceType::WeakClaim(this)]() {
258         auto WebPattern = weak.Upgrade();
259         CHECK_NULL_VOID(WebPattern);
260         WebPattern->UpdateLocale();
261     };
262     context->SetConfigChangedCallback(std::move(langTask));
263 }
264 
InitFeatureParam()265 void WebPattern::InitFeatureParam()
266 {
267     isVisibleActiveEnable_ = system::GetBoolParameter(VISIBLE_ACTIVE_ENABLE, true);
268     isMemoryLevelEnable_ = system::GetBoolParameter(MEMORY_LEVEL_ENABEL, true);
269 }
270 
InitPanEvent(const RefPtr<GestureEventHub> & gestureHub)271 void WebPattern::InitPanEvent(const RefPtr<GestureEventHub>& gestureHub)
272 {
273     if (panEvent_) {
274         return;
275     }
276     auto actionStartTask = [weak = WeakClaim(this)](const GestureEvent& event) {
277         auto pattern = weak.Upgrade();
278         CHECK_NULL_VOID(pattern);
279         pattern->OnScrollStartRecursive(pattern->GetParentAxis() == Axis::HORIZONTAL
280                                     ? event.GetGlobalLocation().GetX()
281                                     : event.GetGlobalLocation().GetY());
282     };
283     auto actionUpdateTask = [weak = WeakClaim(this)](const GestureEvent& event) {
284         auto pattern = weak.Upgrade();
285         CHECK_NULL_VOID(pattern);
286         pattern->HandleDragMove(event);
287     };
288     auto actionEndTask = [weak = WeakClaim(this)](const GestureEvent& info) { return; };
289     auto actionCancelTask = [weak = WeakClaim(this)]() { return; };
290     PanDirection panDirection;
291     panDirection.type = PanDirection::ALL;
292     panEvent_ = MakeRefPtr<PanEvent>(
293         std::move(actionStartTask), std::move(actionUpdateTask), std::move(actionEndTask), std::move(actionCancelTask));
294     gestureHub->AddPanEvent(panEvent_, panDirection, DEFAULT_PAN_FINGER, DEFAULT_PAN_DISTANCE);
295     gestureHub->SetPanEventType(GestureTypeName::WEBSCROLL);
296     gestureHub->SetOnGestureJudgeNativeBegin([](const RefPtr<NG::GestureInfo>& gestureInfo,
297                                                 const std::shared_ptr<BaseGestureEvent>& info) -> GestureJudgeResult {
298             if (!gestureInfo) {
299                 // info is null, default case to continue
300                 return GestureJudgeResult::CONTINUE;
301             }
302             if (gestureInfo->GetType() != GestureTypeName::WEBSCROLL) {
303                 // not web pan event type, continue
304                 return GestureJudgeResult::CONTINUE;
305             }
306 
307             auto inputEventType = gestureInfo->GetInputEventType();
308             if (inputEventType == InputEventType::AXIS) {
309                 // axis event type of web pan, dispatch to panEvent to process
310                 return GestureJudgeResult::CONTINUE;
311             } else if (inputEventType == InputEventType::MOUSE_BUTTON) {
312                 // mouse button event type of web pan, dispatch to DragEvent to process
313                 return GestureJudgeResult::REJECT;
314             }
315             // In other cases, the panEvent is used by default
316             return GestureJudgeResult::CONTINUE;
317         });
318 }
319 
HandleDragMove(const GestureEvent & event)320 void WebPattern::HandleDragMove(const GestureEvent& event)
321 {
322     if (event.GetInputEventType() == InputEventType::AXIS) {
323         CHECK_NULL_VOID(delegate_);
324         auto localLocation = event.GetLocalLocation();
325         delegate_->HandleAxisEvent(localLocation.GetX(), localLocation.GetY(),
326             event.GetDelta().GetX() * DEFAULT_AXIS_RATIO, event.GetDelta().GetY() * DEFAULT_AXIS_RATIO);
327     }
328 }
329 
InitTouchEvent(const RefPtr<GestureEventHub> & gestureHub)330 void WebPattern::InitTouchEvent(const RefPtr<GestureEventHub>& gestureHub)
331 {
332     if (touchEvent_) {
333         return;
334     }
335 
336     auto touchTask = [weak = WeakClaim(this)](const TouchEventInfo& info) {
337         auto pattern = weak.Upgrade();
338         CHECK_NULL_VOID(pattern);
339         if (info.GetChangedTouches().empty()) {
340             return;
341         }
342 
343         // only handle touch event
344         if (info.GetSourceDevice() != SourceType::TOUCH) {
345             return;
346         }
347         pattern->touchEventInfo_ = info;
348         pattern->isMouseEvent_ = false;
349         const auto& changedPoint = info.GetChangedTouches().front();
350         if (changedPoint.GetTouchType() == TouchType::DOWN) {
351             pattern->HandleTouchDown(info, false);
352             return;
353         }
354         if (changedPoint.GetTouchType() == TouchType::MOVE) {
355             pattern->HandleTouchMove(info, false);
356             return;
357         }
358         if (changedPoint.GetTouchType() == TouchType::UP) {
359             pattern->HandleTouchUp(info, false);
360             return;
361         }
362         if (changedPoint.GetTouchType() == TouchType::CANCEL) {
363             pattern->HandleTouchCancel(info);
364             return;
365         }
366     };
367     touchEvent_ = MakeRefPtr<TouchEventImpl>(std::move(touchTask));
368     gestureHub->AddTouchEvent(touchEvent_);
369 }
370 
InitMouseEvent(const RefPtr<InputEventHub> & inputHub)371 void WebPattern::InitMouseEvent(const RefPtr<InputEventHub>& inputHub)
372 {
373     if (mouseEvent_) {
374         return;
375     }
376 
377     auto mouseTask = [weak = WeakClaim(this)](MouseInfo& info) {
378         auto pattern = weak.Upgrade();
379         CHECK_NULL_VOID(pattern);
380         pattern->HandleMouseEvent(info);
381     };
382 
383     mouseEvent_ = MakeRefPtr<InputEvent>(std::move(mouseTask));
384     inputHub->AddOnMouseEvent(mouseEvent_);
385 }
386 
InitHoverEvent(const RefPtr<InputEventHub> & inputHub)387 void WebPattern::InitHoverEvent(const RefPtr<InputEventHub>& inputHub)
388 {
389     if (hoverEvent_) {
390         return;
391     }
392 
393     auto hoverTask = [weak = WeakClaim(this)](bool isHover) {
394         auto pattern = weak.Upgrade();
395         CHECK_NULL_VOID(pattern);
396         MouseInfo info;
397         info.SetAction(isHover ? MouseAction::HOVER : MouseAction::HOVER_EXIT);
398         pattern->WebOnMouseEvent(info);
399     };
400 
401     hoverEvent_ = MakeRefPtr<InputEvent>(std::move(hoverTask));
402     inputHub->AddOnHoverEvent(hoverEvent_);
403 }
404 
HandleMouseEvent(MouseInfo & info)405 void WebPattern::HandleMouseEvent(MouseInfo& info)
406 {
407     isMouseEvent_ = true;
408     WebOnMouseEvent(info);
409 
410     auto host = GetHost();
411     CHECK_NULL_VOID(host);
412     auto eventHub = host->GetEventHub<WebEventHub>();
413     CHECK_NULL_VOID(eventHub);
414     auto mouseEventCallback = eventHub->GetOnMouseEvent();
415     CHECK_NULL_VOID(mouseEventCallback);
416     mouseEventCallback(info);
417 }
418 
WebOnMouseEvent(const MouseInfo & info)419 void WebPattern::WebOnMouseEvent(const MouseInfo& info)
420 {
421     CHECK_NULL_VOID(delegate_);
422     if (info.GetAction() == MouseAction::PRESS) {
423         delegate_->OnContextMenuHide("");
424         WebRequestFocus();
425     }
426 
427     if (info.GetButton() == MouseButton::LEFT_BUTTON && info.GetAction() == MouseAction::RELEASE) {
428         ResetDragAction();
429     }
430 
431     auto localLocation = info.GetLocalLocation();
432     if (!HandleDoubleClickEvent(info)) {
433         delegate_->OnMouseEvent(
434             localLocation.GetX(), localLocation.GetY(), info.GetButton(), info.GetAction(), SINGLE_CLICK_NUM);
435     }
436 }
437 
ResetDragAction()438 void WebPattern::ResetDragAction()
439 {
440     auto frameNode = GetHost();
441     CHECK_NULL_VOID(frameNode);
442     frameNode->SetDraggable(false);
443     auto eventHub = frameNode->GetEventHub<WebEventHub>();
444     CHECK_NULL_VOID(eventHub);
445     auto gestureHub = eventHub->GetOrCreateGestureEventHub();
446     CHECK_NULL_VOID(gestureHub);
447     gestureHub->ResetDragActionForWeb();
448 
449     if (!isDragging_) {
450         return;
451     }
452 
453     isDragging_ = false;
454     // cancel drag action to avoid web kernel can't process other input event
455     CHECK_NULL_VOID(delegate_);
456     delegate_->HandleDragEvent(0, 0, DragAction::DRAG_CANCEL);
457     gestureHub->CancelDragForWeb();
458 }
459 
GetDragOffset() const460 Offset WebPattern::GetDragOffset() const
461 {
462     Offset webDragOffset;
463     int x = 0;
464     int y = 0;
465     if (delegate_ && delegate_->dragData_) {
466         delegate_->dragData_->GetDragStartPosition(x, y);
467     }
468 
469     webDragOffset.SetX(x);
470     webDragOffset.SetY(y);
471 
472     return webDragOffset;
473 }
474 
HandleDoubleClickEvent(const MouseInfo & info)475 bool WebPattern::HandleDoubleClickEvent(const MouseInfo& info)
476 {
477     if (info.GetButton() != MouseButton::LEFT_BUTTON || info.GetAction() != MouseAction::PRESS) {
478         return false;
479     }
480     auto localLocation = info.GetLocalLocation();
481     MouseClickInfo clickInfo;
482     clickInfo.x = localLocation.GetX();
483     clickInfo.y = localLocation.GetY();
484     clickInfo.start = info.GetTimeStamp();
485     if (doubleClickQueue_.empty()) {
486         doubleClickQueue_.push(clickInfo);
487         return false;
488     }
489     std::chrono::duration<float> timeout_ = clickInfo.start - doubleClickQueue_.back().start;
490     double offsetX = clickInfo.x - doubleClickQueue_.back().x;
491     double offsetY = clickInfo.y - doubleClickQueue_.back().y;
492     double offset = sqrt(offsetX * offsetX + offsetY * offsetY);
493     if (timeout_.count() < DEFAULT_DBCLICK_INTERVAL && offset < DEFAULT_DBCLICK_OFFSET) {
494         SendDoubleClickEvent(clickInfo);
495         std::queue<MouseClickInfo> empty;
496         swap(empty, doubleClickQueue_);
497         return true;
498     }
499     if (doubleClickQueue_.size() == 1) {
500         doubleClickQueue_.push(clickInfo);
501         return false;
502     }
503     doubleClickQueue_.pop();
504     doubleClickQueue_.push(clickInfo);
505     return false;
506 }
507 
SendDoubleClickEvent(const MouseClickInfo & info)508 void WebPattern::SendDoubleClickEvent(const MouseClickInfo& info)
509 {
510     CHECK_NULL_VOID(delegate_);
511     delegate_->OnMouseEvent(info.x, info.y, MouseButton::LEFT_BUTTON, MouseAction::PRESS, DOUBLE_CLICK_NUM);
512 }
513 
GenerateDragDropInfo(NG::DragDropInfo & dragDropInfo)514 bool WebPattern::GenerateDragDropInfo(NG::DragDropInfo& dragDropInfo)
515 {
516     if (delegate_) {
517         dragDropInfo.pixelMap = delegate_->GetDragPixelMap();
518     }
519 
520     if (dragDropInfo.pixelMap) {
521         isW3cDragEvent_ = true;
522         return true;
523     }
524 
525     return false;
526 }
527 
HandleOnDragStart(const RefPtr<OHOS::Ace::DragEvent> & info)528 NG::DragDropInfo WebPattern::HandleOnDragStart(const RefPtr<OHOS::Ace::DragEvent>& info)
529 {
530     isDragging_ = true;
531     NG::DragDropInfo dragDropInfo;
532     if (GenerateDragDropInfo(dragDropInfo)) {
533         auto frameNode = GetHost();
534         CHECK_NULL_RETURN(frameNode, dragDropInfo);
535         CHECK_NULL_RETURN(delegate_, dragDropInfo);
536         CHECK_NULL_RETURN(delegate_->dragData_, dragDropInfo);
537         // get drag pixel map successfully, disable next drag util received web kernel drag callback
538         frameNode->SetDraggable(false);
539         RefPtr<UnifiedData> aceUnifiedData = UdmfClient::GetInstance()->CreateUnifiedData();
540         std::string plainContent = delegate_->dragData_->GetFragmentText();
541         std::string htmlContent = delegate_->dragData_->GetFragmentHtml();
542         std::string linkUrl = delegate_->dragData_->GetLinkURL();
543         std::string linkTitle = delegate_->dragData_->GetLinkTitle();
544         if (!plainContent.empty()) {
545             UdmfClient::GetInstance()->AddPlainTextRecord(aceUnifiedData, plainContent);
546         }
547         if (!htmlContent.empty()) {
548             UdmfClient::GetInstance()->AddHtmlRecord(aceUnifiedData, htmlContent, "");
549         }
550         if (!linkUrl.empty()) {
551             UdmfClient::GetInstance()->AddLinkRecord(aceUnifiedData, linkUrl, linkTitle);
552             TAG_LOGI(AceLogTag::ACE_WEB,
553                 "DragDrop event WebEventHub HandleOnDragStart, linkUrl size:%{public}zu", linkUrl.size());
554         }
555         std::string fileName = delegate_->dragData_->GetImageFileName();
556         if (!fileName.empty()) {
557             std::string fullName;
558             if (delegate_->tempDir_.empty()) {
559                 fullName = "/data/storage/el2/base/haps/entry/temp/dragdrop/" + fileName;
560             } else {
561                 fullName = delegate_->tempDir_ + "/dragdrop/" + fileName;
562             }
563             AppFileService::ModuleFileUri::FileUri fileUri(fullName);
564             TAG_LOGI(AceLogTag::ACE_WEB,
565                 "DragDrop event WebEventHub HandleOnDragStart, FileUri:%{public}s, image path:%{public}s",
566                 fileUri.ToString().c_str(), fullName.c_str());
567             std::vector<std::string> urlVec;
568             std::string udmfUri = fileUri.ToString();
569             urlVec.emplace_back(udmfUri);
570             UdmfClient::GetInstance()->AddFileUriRecord(aceUnifiedData, urlVec);
571         } else {
572             TAG_LOGW(AceLogTag::ACE_WEB, "DragDrop event start, dragdata has no image file uri, just pass");
573         }
574         info->SetData(aceUnifiedData);
575         HandleOnDragEnter(info);
576         return dragDropInfo;
577     }
578     return dragDropInfo;
579 }
580 
HandleOnDropMove(const RefPtr<OHOS::Ace::DragEvent> & info)581 void WebPattern::HandleOnDropMove(const RefPtr<OHOS::Ace::DragEvent>& info)
582 {
583     if (!isDragging_) {
584         return;
585     }
586 
587     if (!isW3cDragEvent_) {
588         return;
589     }
590 
591     CHECK_NULL_VOID(delegate_);
592     delegate_->OnContextMenuHide("");
593     auto host = GetHost();
594     CHECK_NULL_VOID(host);
595     auto pipelineContext = host->GetContext();
596     CHECK_NULL_VOID(pipelineContext);
597     auto viewScale = pipelineContext->GetViewScale();
598     int32_t globalX = static_cast<int32_t>(info->GetX()) * viewScale;
599     int32_t globalY = static_cast<int32_t>(info->GetY()) * viewScale;
600     auto offset = GetCoordinatePoint();
601     globalX = static_cast<int32_t>(globalX - offset.value_or(OffsetF()).GetX());
602     globalY = static_cast<int32_t>(globalY - offset.value_or(OffsetF()).GetY());
603     delegate_->HandleDragEvent(globalX, globalY, DragAction::DRAG_OVER);
604 }
605 
InitCommonDragDropEvent(const RefPtr<GestureEventHub> & gestureHub)606 void WebPattern::InitCommonDragDropEvent(const RefPtr<GestureEventHub>& gestureHub)
607 {
608     auto frameNode = GetHost();
609     CHECK_NULL_VOID(frameNode);
610     auto eventHub = frameNode->GetEventHub<WebEventHub>();
611     CHECK_NULL_VOID(eventHub);
612 
613     isDisableDrag_ = false;
614     // disable drag
615     frameNode->SetDraggable(false);
616     // init common drag drop event
617     gestureHub->InitDragDropEvent();
618     InitWebEventHubDragDropStart(eventHub);
619     InitWebEventHubDragDropEnd(eventHub);
620 }
621 
InitWebEventHubDragDropStart(const RefPtr<WebEventHub> & eventHub)622 void WebPattern::InitWebEventHubDragDropStart(const RefPtr<WebEventHub>& eventHub)
623 {
624     auto onDragStartId = [weak = WeakClaim(this)](const RefPtr<OHOS::Ace::DragEvent>& info,
625                              const std::string& extraParams) -> NG::DragDropInfo {
626         NG::DragDropInfo dragDropInfo;
627         auto pattern = weak.Upgrade();
628         if (pattern) {
629             TAG_LOGI(AceLogTag::ACE_WEB,
630                 "DragDrop event WebEventHub onDragStartId, x:%{public}lf, y:%{public}lf, webId:%{public}d",
631                 info->GetX(), info->GetY(), pattern->GetWebId());
632             pattern->dropX_ = 0;
633             pattern->dropY_ = 0;
634             return pattern->HandleOnDragStart(info);
635         }
636         return dragDropInfo;
637     };
638 
639     auto onDragEnterId = [weak = WeakClaim(this)](const RefPtr<OHOS::Ace::DragEvent>& info,
640                              const std::string& extraParams) {
641         auto pattern = weak.Upgrade();
642         CHECK_NULL_VOID(pattern);
643         TAG_LOGI(AceLogTag::ACE_WEB,
644             "DragDrop event WebEventHub onDragEnterId, x:%{public}lf, y:%{public}lf, webId:%{public}d",
645             info->GetX(), info->GetY(), pattern->GetWebId());
646         pattern->isW3cDragEvent_ = true;
647         pattern->isDragging_ = true;
648         pattern->dropX_ = 0;
649         pattern->dropY_ = 0;
650         return pattern->HandleOnDragEnter(info);
651     };
652 
653     auto onDragMoveId = [weak = WeakClaim(this)](const RefPtr<OHOS::Ace::DragEvent>& info,
654                              const std::string& extraParams) {
655         auto pattern = weak.Upgrade();
656         CHECK_NULL_VOID(pattern);
657         static uint32_t dragMoveCnt = 0;
658         if ((dragMoveCnt++ % DEBUG_DRAGMOVEID_TIMER) == 0) {
659             TAG_LOGI(AceLogTag::ACE_WEB,
660                 "DragDrop event WebEventHub onDragMoveId, x:%{public}lf, y:%{public}lf, webId:%{public}d",
661                 info->GetX(), info->GetY(), pattern->GetWebId());
662         }
663         if (!pattern->isDragging_) {
664             return;
665         }
666         pattern->OnQuickMenuDismissed();
667 
668         // update drag status
669         info->SetResult(pattern->GetDragAcceptableStatus());
670 
671         pattern->HandleOnDropMove(info);
672     };
673     // set custom OnDragStart function
674     eventHub->SetOnDragStart(std::move(onDragStartId));
675     eventHub->SetOnDragEnter(std::move(onDragEnterId));
676     eventHub->SetOnDragMove(std::move(onDragMoveId));
677 }
678 
InitWebEventHubDragDropEnd(const RefPtr<WebEventHub> & eventHub)679 void WebPattern::InitWebEventHubDragDropEnd(const RefPtr<WebEventHub>& eventHub)
680 {
681     auto onDragDropId = [weak = WeakClaim(this)](const RefPtr<OHOS::Ace::DragEvent>& info,
682                              const std::string& extraParams) {
683         auto pattern = weak.Upgrade();
684         CHECK_NULL_VOID(pattern);
685         TAG_LOGI(AceLogTag::ACE_WEB,
686             "DragDrop event WebEventHub onDragDropId, x:%{public}lf, y:%{public}lf, webId:%{public}d",
687             info->GetX(), info->GetY(), pattern->GetWebId());
688         if (!pattern->isDragging_) {
689             return;
690         }
691         pattern->dropX_ = info->GetX();
692         pattern->dropY_ = info->GetY();
693         pattern->HandleOnDragDrop(info);
694     };
695 
696     auto onDragLeaveId = [weak = WeakClaim(this)](const RefPtr<OHOS::Ace::DragEvent>& info,
697                              const std::string& extraParams) {
698         auto pattern = weak.Upgrade();
699         CHECK_NULL_VOID(pattern);
700         TAG_LOGI(AceLogTag::ACE_WEB,
701             "DragDrop event WebEventHub onDragLeaveId, x:%{public}lf, y:%{public}lf, webId:%{public}d",
702             info->GetX(), info->GetY(), pattern->GetWebId());
703         pattern->HandleOnDragLeave(info->GetX(), info->GetY());
704     };
705 
706     auto onDragEndId = [weak = WeakClaim(this)](const RefPtr<OHOS::Ace::DragEvent>& info) {
707         auto pattern = weak.Upgrade();
708         CHECK_NULL_VOID(pattern);
709         TAG_LOGI(AceLogTag::ACE_WEB,
710             "DragDrop event WebEventHub onDragEndId, x:%{public}lf, y:%{public}lf, webId:%{public}d",
711             info->GetX(), info->GetY(), pattern->GetWebId());
712         pattern->HandleDragEnd(pattern->dropX_, pattern->dropY_);
713     };
714     // set custom OnDragStart function
715     eventHub->SetOnDragEnd(std::move(onDragEndId));
716     eventHub->SetOnDragLeave(std::move(onDragLeaveId));
717     eventHub->SetOnDrop(std::move(onDragDropId));
718 }
719 
IsImageDrag()720 bool WebPattern::IsImageDrag()
721 {
722     if (delegate_) {
723         return delegate_->IsImageDrag();
724     }
725     return false;
726 }
727 
GetDragAcceptableStatus()728 DragRet WebPattern::GetDragAcceptableStatus()
729 {
730     OHOS::NWeb::NWebDragData::DragOperation status = delegate_->GetDragAcceptableStatus();
731     if (status == OHOS::NWeb::NWebDragData::DragOperation::DRAG_OPERATION_MOVE ||
732         status == OHOS::NWeb::NWebDragData::DragOperation::DRAG_OPERATION_COPY ||
733         status == OHOS::NWeb::NWebDragData::DragOperation::DRAG_OPERATION_LINK) {
734         return DragRet::ENABLE_DROP;
735     }
736     return DragRet::DISABLE_DROP;
737 }
738 
NotifyStartDragTask()739 bool WebPattern::NotifyStartDragTask()
740 {
741     if (isDisableDrag_) {
742         return false;
743     }
744     isDragging_ = true;
745     auto frameNode = GetHost();
746     CHECK_NULL_RETURN(frameNode, false);
747     auto eventHub = frameNode->GetEventHub<WebEventHub>();
748     CHECK_NULL_RETURN(eventHub, false);
749     auto gestureHub = eventHub->GetOrCreateGestureEventHub();
750     CHECK_NULL_RETURN(gestureHub, false);
751     // received web kernel drag callback, enable drag
752     frameNode->SetDraggable(true);
753     gestureHub->SetPixelMap(delegate_->GetDragPixelMap());
754     if (!isMouseEvent_) {
755         // mouse drag does not need long press action
756         gestureHub->StartLongPressActionForWeb();
757     }
758     gestureHub->StartDragTaskForWeb();
759     return true;
760 }
761 
InitDragEvent(const RefPtr<GestureEventHub> & gestureHub)762 void WebPattern::InitDragEvent(const RefPtr<GestureEventHub>& gestureHub)
763 {
764     if (dragEvent_) {
765         return;
766     }
767 
768     auto host = GetHost();
769     CHECK_NULL_VOID(host);
770     auto eventHub = host->GetEventHub<WebEventHub>();
771     CHECK_NULL_VOID(eventHub);
772 
773     auto userOnDragStartFunc = eventHub->GetOnDragStart();
774     if (userOnDragStartFunc) {
775         isDisableDrag_ = true;
776         return;
777     }
778 
779     InitCommonDragDropEvent(gestureHub);
780 
781     auto actionStartTask = [weak = WeakClaim(this)](const GestureEvent& info) {
782         int32_t x = info.GetGlobalPoint().GetX();
783         int32_t y = info.GetGlobalPoint().GetY();
784         auto pattern = weak.Upgrade();
785         CHECK_NULL_VOID(pattern);
786         TAG_LOGI(AceLogTag::ACE_WEB,
787             "DragDrop event gestureHub actionStartTask x:%{public}d, y:%{public}d, webId:%{public}d",
788             x, y, pattern->GetWebId());
789         pattern->HandleDragStart(x, y);
790     };
791 
792     auto actionUpdateTask = [weak = WeakClaim(this)](const GestureEvent& info) {
793         return;
794     };
795 
796     auto actionEndTask = [weak = WeakClaim(this)](const GestureEvent& info) {
797         int32_t x = info.GetGlobalPoint().GetX();
798         int32_t y = info.GetGlobalPoint().GetY();
799         auto pattern = weak.Upgrade();
800         CHECK_NULL_VOID(pattern);
801         TAG_LOGI(AceLogTag::ACE_WEB,
802             "DragDrop event gestureHub actionEndTask x:%{public}d, y:%{public}d, webId:%{public}d",
803             x, y, pattern->GetWebId());
804         pattern->HandleDragEnd(x, y);
805     };
806 
807     auto actionCancelTask = [weak = WeakClaim(this)]() {
808     };
809 
810     dragEvent_ = MakeRefPtr<DragEvent>(
811         std::move(actionStartTask), std::move(actionUpdateTask), std::move(actionEndTask), std::move(actionCancelTask));
812     gestureHub->SetCustomDragEvent(dragEvent_, { PanDirection::ALL }, DEFAULT_PAN_FINGER, DEFAULT_PAN_DISTANCE);
813 }
814 
HandleDragStart(int32_t x,int32_t y)815 void WebPattern::HandleDragStart(int32_t x, int32_t y)
816 {
817     TAG_LOGI(AceLogTag::ACE_WEB,
818         "DragDrop event gestureHub actionStart, isW3cDragEvent_:%{public}d", (int)isW3cDragEvent_);
819 }
820 
HandleOnDragEnter(const RefPtr<OHOS::Ace::DragEvent> & info)821 void WebPattern::HandleOnDragEnter(const RefPtr<OHOS::Ace::DragEvent>& info)
822 {
823     if (!delegate_) {
824         return;
825     }
826 
827     auto host = GetHost();
828     CHECK_NULL_VOID(host);
829     auto pipelineContext = host->GetContext();
830     CHECK_NULL_VOID(pipelineContext);
831     int32_t globalX = static_cast<int32_t>(info->GetX());
832     int32_t globalY = static_cast<int32_t>(info->GetY());
833     auto viewScale = pipelineContext->GetViewScale();
834     auto offset = GetCoordinatePoint();
835     int32_t localX = static_cast<int32_t>(globalX - offset.value_or(OffsetF()).GetX()) * viewScale;
836     int32_t localY = static_cast<int32_t>(globalY - offset.value_or(OffsetF()).GetY()) * viewScale;
837 
838     // fake drag data when enter
839     delegate_->GetOrCreateDragData();
840     // use summary to set fake data
841     ClearDragData();
842     delegate_->HandleDragEvent(localX, localY, DragAction::DRAG_ENTER);
843     // RequestFocus to show the carret frame_caret
844     WebRequestFocus();
845 }
846 
HandleOnDragDropLink(RefPtr<UnifiedData> aceData)847 void WebPattern::HandleOnDragDropLink(RefPtr<UnifiedData> aceData)
848 {
849     CHECK_NULL_VOID(aceData);
850     CHECK_NULL_VOID(delegate_);
851     CHECK_NULL_VOID(delegate_->dragData_);
852     // hyperlink
853     std::string linkUrl;
854     std::string linkTitle;
855     UdmfClient::GetInstance()->GetLinkRecord(aceData, linkUrl, linkTitle);
856     if (!linkUrl.empty()) {
857         delegate_->dragData_->SetLinkURL(linkUrl);
858         delegate_->dragData_->SetLinkTitle(linkTitle);
859         TAG_LOGI(AceLogTag::ACE_WEB,
860             "DragDrop event WebEventHub onDragDropId, linkUrl size:%{public}zu", linkUrl.size());
861     } else {
862         TAG_LOGW(AceLogTag::ACE_WEB,
863             "DragDrop event WebEventHub onDragDropId, linkUrl is empty");
864     }
865 }
866 
HandleOnDragDropFile(RefPtr<UnifiedData> aceData)867 void WebPattern::HandleOnDragDropFile(RefPtr<UnifiedData> aceData)
868 {
869     CHECK_NULL_VOID(aceData);
870     CHECK_NULL_VOID(delegate_);
871     CHECK_NULL_VOID(delegate_->dragData_);
872     // file
873     std::vector<std::string> urlVec;
874     UdmfClient::GetInstance()->GetFileUriRecord(aceData, urlVec);
875     TAG_LOGI(AceLogTag::ACE_WEB, "DragDrop event WebEventHub onDragDropId,"
876         "url array size is:%{public}zu", urlVec.size());
877     delegate_->dragData_->ClearImageFileNames();
878     for (std::string url : urlVec) {
879         TAG_LOGI(AceLogTag::ACE_WEB, "DragDrop event WebEventHub onDragDropId,"
880             "url get from udmf:%{public}s", url.c_str());
881         AppFileService::ModuleFileUri::FileUri fileUri(url);
882         TAG_LOGI(AceLogTag::ACE_WEB, "DragDrop event WebEventHub onDragDropId,"
883             "fileUri ToString:%{public}s", fileUri.ToString().c_str());
884         std::string uriRealPath = FileUriHelper::GetRealPath(url);
885         if (!uriRealPath.empty() && access(uriRealPath.c_str(), F_OK) == 0) { // file exist
886             TAG_LOGI(AceLogTag::ACE_WEB, "DragDrop event WebEventHub onDragDropId,"
887             "url real path:%{public}s", uriRealPath.c_str());
888             delegate_->dragData_->SetFileUri(uriRealPath);
889         } else {
890             TAG_LOGW(AceLogTag::ACE_WEB, "DragDrop event WebEventHub onDragDropId,"
891                 "url is empty or not exist, uriRealPath:%{public}s", uriRealPath.c_str());
892         }
893     }
894 }
895 
HandleOnDragDrop(const RefPtr<OHOS::Ace::DragEvent> & info)896 void WebPattern::HandleOnDragDrop(const RefPtr<OHOS::Ace::DragEvent>& info)
897 {
898     isDragging_ = false;
899     isW3cDragEvent_ = false;
900     CHECK_NULL_VOID(delegate_);
901     auto host = GetHost();
902     CHECK_NULL_VOID(host);
903     auto pipelineContext = host->GetContext();
904     CHECK_NULL_VOID(pipelineContext);
905     auto viewScale = pipelineContext->GetViewScale();
906     auto offset = GetCoordinatePoint();
907     int32_t localX = static_cast<int32_t>(info->GetX() - offset.value_or(OffsetF()).GetX()) * viewScale;
908     int32_t localY = static_cast<int32_t>(info->GetY() - offset.value_or(OffsetF()).GetY()) * viewScale;
909 
910     RefPtr<UnifiedData> aceData = info->GetData();
911     // get data from ace(from udmf), and send it to chromium
912     if (aceData && aceData->GetSize() >= 1) {
913         TAG_LOGI(AceLogTag::ACE_WEB,
914             "DragDrop event WebEventHub onDragDropId, size:%{public}" PRId64 "", aceData->GetSize());
915         CHECK_NULL_VOID(delegate_->dragData_);
916         // plain text
917         std::string plain = UdmfClient::GetInstance()->GetSinglePlainTextRecord(aceData);
918         if (!plain.empty()) {
919             delegate_->dragData_->SetFragmentText(plain);
920             TAG_LOGI(AceLogTag::ACE_WEB,
921                 "DragDrop event WebEventHub onDragDropId, plain size:%{public}zu", plain.size());
922         }
923         // html
924         std::string htmlContent;
925         std::string plainContent;
926         UdmfClient::GetInstance()->GetHtmlRecord(aceData, htmlContent, plainContent);
927         if (!htmlContent.empty()) {
928             delegate_->dragData_->SetFragmentHtml(htmlContent);
929             TAG_LOGI(AceLogTag::ACE_WEB,
930                 "DragDrop event WebEventHub onDragDropId, htmlContent size:%{public}zu", htmlContent.size());
931         }
932         // link
933         HandleOnDragDropLink(aceData);
934         // file
935         HandleOnDragDropFile(aceData);
936     } else {
937         TAG_LOGW(AceLogTag::ACE_WEB, "DragDrop event WebEventHub onDragDropId get data failed");
938     }
939 
940     delegate_->HandleDragEvent(localX, localY, DragAction::DRAG_DROP);
941 }
942 
HandleOnDragLeave(int32_t x,int32_t y)943 void WebPattern::HandleOnDragLeave(int32_t x, int32_t y)
944 {
945     CHECK_NULL_VOID(delegate_);
946     isDragging_ = false;
947     isW3cDragEvent_ = false;
948     auto host = GetHost();
949     CHECK_NULL_VOID(host);
950     auto pipelineContext = host->GetContext();
951     CHECK_NULL_VOID(pipelineContext);
952     auto viewScale = pipelineContext->GetViewScale();
953     auto offset = GetCoordinatePoint();
954     int32_t localX = static_cast<int32_t>(x - offset.value_or(OffsetF()).GetX());
955     int32_t localY = static_cast<int32_t>(y - offset.value_or(OffsetF()).GetY());
956     delegate_->HandleDragEvent(localX * viewScale, localY * viewScale, DragAction::DRAG_LEAVE);
957 }
958 
HandleDragEnd(int32_t x,int32_t y)959 void WebPattern::HandleDragEnd(int32_t x, int32_t y)
960 {
961     CHECK_NULL_VOID(delegate_);
962 
963     isDragging_ = false;
964     isW3cDragEvent_ = false;
965     ClearDragData();
966 
967     auto host = GetHost();
968     CHECK_NULL_VOID(host);
969     auto pipelineContext = host->GetContext();
970     CHECK_NULL_VOID(pipelineContext);
971     auto viewScale = pipelineContext->GetViewScale();
972     auto offset = GetCoordinatePoint();
973     int32_t localX = static_cast<int32_t>(x - offset.value_or(OffsetF()).GetX()) * viewScale;
974     int32_t localY = static_cast<int32_t>(y - offset.value_or(OffsetF()).GetY()) * viewScale;
975     if (x == 0 && y == 0) {
976         delegate_->HandleDragEvent(0, 0, DragAction::DRAG_END);
977     } else {
978         delegate_->HandleDragEvent(localX, localY, DragAction::DRAG_END);
979     }
980 }
981 
HandleDragCancel()982 void WebPattern::HandleDragCancel()
983 {
984     auto frameNode = GetHost();
985     CHECK_NULL_VOID(frameNode);
986     // disable drag
987     frameNode->SetDraggable(false);
988     CHECK_NULL_VOID(delegate_);
989     isDragging_ = false;
990     isW3cDragEvent_ = false;
991     ClearDragData();
992     delegate_->HandleDragEvent(0, 0, DragAction::DRAG_CANCEL);
993 }
994 
ClearDragData()995 void WebPattern::ClearDragData()
996 {
997     CHECK_NULL_VOID(delegate_);
998     std::string plain = "";
999     std::string htmlContent = "";
1000     std::string linkUrl = "";
1001     std::string linkTitle = "";
1002     if (delegate_->dragData_) {
1003         delegate_->dragData_->SetFragmentText(plain);
1004         delegate_->dragData_->SetFragmentHtml(htmlContent);
1005         delegate_->dragData_->SetLinkURL(linkUrl);
1006         delegate_->dragData_->SetLinkTitle(linkTitle);
1007     }
1008 }
1009 
InitFocusEvent(const RefPtr<FocusHub> & focusHub)1010 void WebPattern::InitFocusEvent(const RefPtr<FocusHub>& focusHub)
1011 {
1012     auto focusTask = [weak = WeakClaim(this)]() {
1013         auto pattern = weak.Upgrade();
1014         CHECK_NULL_VOID(pattern);
1015         pattern->HandleFocusEvent();
1016     };
1017     focusHub->SetOnFocusInternal(focusTask);
1018 
1019     auto blurTask = [weak = WeakClaim(this)](const BlurReason& blurReason) {
1020         auto pattern = weak.Upgrade();
1021         CHECK_NULL_VOID(pattern);
1022         pattern->HandleBlurEvent(blurReason);
1023     };
1024     focusHub->SetOnBlurReasonInternal(blurTask);
1025 
1026     auto keyTask = [weak = WeakClaim(this)](const KeyEvent& keyEvent) -> bool {
1027         auto pattern = weak.Upgrade();
1028         CHECK_NULL_RETURN(pattern, false);
1029         return pattern->HandleKeyEvent(keyEvent);
1030     };
1031     focusHub->SetOnKeyEventInternal(keyTask);
1032 }
1033 
HandleFocusEvent()1034 void WebPattern::HandleFocusEvent()
1035 {
1036     CHECK_NULL_VOID(delegate_);
1037     isFocus_ = true;
1038     if (needOnFocus_) {
1039         delegate_->OnFocus();
1040     } else {
1041         needOnFocus_ = true;
1042     }
1043 }
1044 
HandleBlurEvent(const BlurReason & blurReason)1045 void WebPattern::HandleBlurEvent(const BlurReason& blurReason)
1046 {
1047     CHECK_NULL_VOID(delegate_);
1048     isFocus_ = false;
1049     if (!selectPopupMenuShowing_) {
1050         delegate_->SetBlurReason(static_cast<OHOS::NWeb::BlurReason>(blurReason));
1051         delegate_->OnBlur();
1052     }
1053     OnQuickMenuDismissed();
1054     for (auto keyCode : KeyCodeSet_) {
1055         delegate_->OnKeyEvent(static_cast<int32_t>(keyCode), static_cast<int32_t>(OHOS::Ace::KeyAction::UP));
1056     }
1057     KeyCodeSet_.clear();
1058 }
1059 
HandleKeyEvent(const KeyEvent & keyEvent)1060 bool WebPattern::HandleKeyEvent(const KeyEvent& keyEvent)
1061 {
1062     bool ret = false;
1063 
1064     auto host = GetHost();
1065     CHECK_NULL_RETURN(host, ret);
1066     auto eventHub = host->GetEventHub<WebEventHub>();
1067     CHECK_NULL_RETURN(eventHub, ret);
1068 
1069     KeyEventInfo info(keyEvent);
1070     auto keyEventCallback = eventHub->GetOnKeyEvent();
1071     if (keyEventCallback) {
1072         keyEventCallback(info);
1073     }
1074 
1075     auto preKeyEventCallback = eventHub->GetOnPreKeyEvent();
1076     if (preKeyEventCallback) {
1077         ret = preKeyEventCallback(info);
1078         if (ret) {
1079             return ret;
1080         }
1081     }
1082 
1083     ret = WebOnKeyEvent(keyEvent);
1084     return ret;
1085 }
1086 
WebOnKeyEvent(const KeyEvent & keyEvent)1087 bool WebPattern::WebOnKeyEvent(const KeyEvent& keyEvent)
1088 {
1089     CHECK_NULL_RETURN(delegate_, false);
1090     if (keyEvent.action == OHOS::Ace::KeyAction::DOWN) {
1091         KeyCodeSet_.insert(keyEvent.code);
1092     } else if (keyEvent.action == OHOS::Ace::KeyAction::UP) {
1093         KeyCodeSet_.erase(keyEvent.code);
1094     }
1095     return delegate_->OnKeyEvent(static_cast<int32_t>(keyEvent.code), static_cast<int32_t>(keyEvent.action));
1096 }
1097 
WebRequestFocus()1098 void WebPattern::WebRequestFocus()
1099 {
1100     auto host = GetHost();
1101     CHECK_NULL_VOID(host);
1102     auto eventHub = host->GetEventHub<WebEventHub>();
1103     CHECK_NULL_VOID(eventHub);
1104     auto focusHub = eventHub->GetOrCreateFocusHub();
1105     CHECK_NULL_VOID(focusHub);
1106 
1107     focusHub->RequestFocusImmediately();
1108 }
1109 
UpdateContentOffset(const RefPtr<LayoutWrapper> & dirty)1110 void WebPattern::UpdateContentOffset(const RefPtr<LayoutWrapper>& dirty)
1111 {
1112     CHECK_NULL_VOID(dirty);
1113     auto geometryNode = dirty->GetGeometryNode();
1114     CHECK_NULL_VOID(geometryNode);
1115     auto host = GetHost();
1116     CHECK_NULL_VOID(host);
1117     auto renderContext = host->GetRenderContext();
1118     CHECK_NULL_VOID(renderContext);
1119     auto paddingOffset = geometryNode->GetPaddingOffset();
1120     auto webContentSize = geometryNode->GetContentSize();
1121 
1122     auto positionProperty = renderContext->GetPropertyOfPosition();
1123     renderContext->SetBounds(
1124         paddingOffset.GetX() +  positionProperty.GetX(), paddingOffset.GetY() + positionProperty.GetY(),
1125         webContentSize.Width(), webContentSize.Height());
1126 }
1127 
OnDirtyLayoutWrapperSwap(const RefPtr<LayoutWrapper> & dirty,const DirtySwapConfig & config)1128 bool WebPattern::OnDirtyLayoutWrapperSwap(const RefPtr<LayoutWrapper>& dirty, const DirtySwapConfig& config)
1129 {
1130     if (!config.contentSizeChange || isInWindowDrag_) {
1131         return false;
1132     }
1133     CHECK_NULL_RETURN(delegate_, false);
1134     CHECK_NULL_RETURN(dirty, false);
1135     auto geometryNode = dirty->GetGeometryNode();
1136     auto drawSize = Size(geometryNode->GetContentSize().Width(), geometryNode->GetContentSize().Height());
1137     if (drawSize.IsInfinite() || drawSize.IsEmpty()) {
1138         return false;
1139     }
1140 
1141     if (GreatOrEqual(drawSize.Width(), Infinity<double>())) {
1142         drawSize.SetWidth(DEFAULT_WEB_WIDTH);
1143     }
1144     if (GreatOrEqual(drawSize.Height(), Infinity<double>())) {
1145         drawSize.SetHeight(DEFAULT_WEB_HEIGHT);
1146     }
1147 
1148     drawSize_ = drawSize;
1149     drawSizeCache_ = drawSize_;
1150     auto offset = Offset(GetCoordinatePoint()->GetX(), GetCoordinatePoint()->GetY());
1151     delegate_->SetBoundsOrResize(drawSize_, offset);
1152     if (isOfflineMode_) {
1153         isOfflineMode_ = false;
1154         OnWindowShow();
1155     }
1156 
1157     // first update size to load url.
1158     if (!isUrlLoaded_) {
1159         isUrlLoaded_ = true;
1160         if (webSrc_) {
1161             delegate_->LoadUrl();
1162         } else if (webData_) {
1163             delegate_->LoadDataWithRichText();
1164         }
1165     }
1166 
1167     return false;
1168 }
1169 
UpdateLayoutAfterKerboardShow(int32_t width,int32_t height,double keyboard,double oldWebHeight)1170 void WebPattern::UpdateLayoutAfterKerboardShow(int32_t width, int32_t height, double keyboard, double oldWebHeight)
1171 {
1172     if (isVirtualKeyBoardShow_ != VkState::VK_SHOW) {
1173         return;
1174     }
1175 
1176     TAG_LOGI(AceLogTag::ACE_WEB,
1177         "KerboardShow height:%{public}d, keyboard:%{public}f, offset:%{public}f, oldWebHeight:%{public}f",
1178         height, keyboard, GetCoordinatePoint()->GetY(), oldWebHeight);
1179 
1180     if (GreatOrEqual(height, keyboard + GetCoordinatePoint()->GetY())) {
1181         double newHeight = height - keyboard - GetCoordinatePoint()->GetY();
1182         if (GreatOrEqual(newHeight, oldWebHeight)) {
1183             newHeight = oldWebHeight;
1184         }
1185         if (NearEqual(newHeight, oldWebHeight)) {
1186             return;
1187         }
1188         drawSize_.SetHeight(newHeight);
1189         UpdateWebLayoutSize(width, height, true);
1190     }
1191 }
1192 
OnAreaChangedInner()1193 void WebPattern::OnAreaChangedInner()
1194 {
1195     auto offset = OffsetF(GetCoordinatePoint()->GetX(), GetCoordinatePoint()->GetY());
1196     if (webOffset_ == offset) {
1197         return;
1198     }
1199     webOffset_ = offset;
1200     UpdateTouchHandleForOverlay();
1201     if (isInWindowDrag_)
1202         return;
1203     auto resizeOffset = Offset(offset.GetX(), offset.GetY());
1204     delegate_->SetBoundsOrResize(drawSize_, resizeOffset);
1205 }
1206 
OnWebSrcUpdate()1207 void WebPattern::OnWebSrcUpdate()
1208 {
1209     if (delegate_ && isUrlLoaded_) {
1210         delegate_->LoadUrl();
1211     }
1212 }
1213 
OnWebDataUpdate()1214 void WebPattern::OnWebDataUpdate()
1215 {
1216     if (delegate_ && isUrlLoaded_) {
1217         delegate_->LoadDataWithRichText();
1218     }
1219 }
1220 
OnJsEnabledUpdate(bool value)1221 void WebPattern::OnJsEnabledUpdate(bool value)
1222 {
1223     if (delegate_) {
1224         delegate_->UpdateJavaScriptEnabled(value);
1225     }
1226 }
1227 
OnMediaPlayGestureAccessUpdate(bool value)1228 void WebPattern::OnMediaPlayGestureAccessUpdate(bool value)
1229 {
1230     if (delegate_) {
1231         delegate_->UpdateMediaPlayGestureAccess(value);
1232     }
1233 }
1234 
OnFileAccessEnabledUpdate(bool value)1235 void WebPattern::OnFileAccessEnabledUpdate(bool value)
1236 {
1237     if (delegate_) {
1238         delegate_->UpdateAllowFileAccess(value);
1239     }
1240 }
1241 
OnOnLineImageAccessEnabledUpdate(bool value)1242 void WebPattern::OnOnLineImageAccessEnabledUpdate(bool value)
1243 {
1244     if (delegate_) {
1245         delegate_->UpdateBlockNetworkImage(!value);
1246     }
1247 }
1248 
OnDomStorageAccessEnabledUpdate(bool value)1249 void WebPattern::OnDomStorageAccessEnabledUpdate(bool value)
1250 {
1251     if (delegate_) {
1252         delegate_->UpdateDomStorageEnabled(value);
1253     }
1254 }
1255 
OnImageAccessEnabledUpdate(bool value)1256 void WebPattern::OnImageAccessEnabledUpdate(bool value)
1257 {
1258     if (delegate_) {
1259         delegate_->UpdateLoadsImagesAutomatically(value);
1260     }
1261 }
1262 
OnMixedModeUpdate(MixedModeContent value)1263 void WebPattern::OnMixedModeUpdate(MixedModeContent value)
1264 {
1265     if (delegate_) {
1266         delegate_->UpdateMixedContentMode(value);
1267     }
1268 }
1269 
OnZoomAccessEnabledUpdate(bool value)1270 void WebPattern::OnZoomAccessEnabledUpdate(bool value)
1271 {
1272     if (delegate_) {
1273         delegate_->UpdateSupportZoom(value);
1274     }
1275 }
1276 
OnGeolocationAccessEnabledUpdate(bool value)1277 void WebPattern::OnGeolocationAccessEnabledUpdate(bool value)
1278 {
1279     if (delegate_) {
1280         delegate_->UpdateGeolocationEnabled(value);
1281     }
1282 }
1283 
OnUserAgentUpdate(const std::string & value)1284 void WebPattern::OnUserAgentUpdate(const std::string& value)
1285 {
1286     if (delegate_) {
1287         delegate_->UpdateUserAgent(value);
1288     }
1289 }
1290 
OnCacheModeUpdate(WebCacheMode value)1291 void WebPattern::OnCacheModeUpdate(WebCacheMode value)
1292 {
1293     if (delegate_) {
1294         delegate_->UpdateCacheMode(value);
1295     }
1296 }
1297 
OnDarkModeUpdate(WebDarkMode mode)1298 void WebPattern::OnDarkModeUpdate(WebDarkMode mode)
1299 {
1300     if (delegate_) {
1301         delegate_->UpdateDarkMode(mode);
1302     }
1303 }
1304 
OnOverScrollModeUpdate(int mode)1305 void WebPattern::OnOverScrollModeUpdate(int mode)
1306 {
1307     if (delegate_) {
1308         delegate_->UpdateOverScrollMode(mode);
1309     }
1310 }
1311 
OnCopyOptionModeUpdate(int32_t mode)1312 void WebPattern::OnCopyOptionModeUpdate(int32_t mode)
1313 {
1314     if (delegate_) {
1315         delegate_->UpdateCopyOptionMode(mode);
1316     }
1317 }
1318 
OnForceDarkAccessUpdate(bool access)1319 void WebPattern::OnForceDarkAccessUpdate(bool access)
1320 {
1321     if (delegate_) {
1322         delegate_->UpdateForceDarkAccess(access);
1323     }
1324 }
1325 
OnAudioResumeIntervalUpdate(int32_t resumeInterval)1326 void WebPattern::OnAudioResumeIntervalUpdate(int32_t resumeInterval)
1327 {
1328     if (delegate_) {
1329         delegate_->UpdateAudioResumeInterval(resumeInterval);
1330     }
1331 }
1332 
OnAudioExclusiveUpdate(bool audioExclusive)1333 void WebPattern::OnAudioExclusiveUpdate(bool audioExclusive)
1334 {
1335     if (delegate_) {
1336         delegate_->UpdateAudioExclusive(audioExclusive);
1337     }
1338 }
1339 
OnOverviewModeAccessEnabledUpdate(bool value)1340 void WebPattern::OnOverviewModeAccessEnabledUpdate(bool value)
1341 {
1342     if (delegate_) {
1343         delegate_->UpdateOverviewModeEnabled(value);
1344     }
1345 }
1346 
OnFileFromUrlAccessEnabledUpdate(bool value)1347 void WebPattern::OnFileFromUrlAccessEnabledUpdate(bool value)
1348 {
1349     if (delegate_) {
1350         delegate_->UpdateFileFromUrlEnabled(value);
1351     }
1352 }
1353 
OnDatabaseAccessEnabledUpdate(bool value)1354 void WebPattern::OnDatabaseAccessEnabledUpdate(bool value)
1355 {
1356     if (delegate_) {
1357         delegate_->UpdateDatabaseEnabled(value);
1358     }
1359 }
1360 
OnTextZoomRatioUpdate(int32_t value)1361 void WebPattern::OnTextZoomRatioUpdate(int32_t value)
1362 {
1363     if (delegate_) {
1364         delegate_->UpdateTextZoomRatio(value);
1365     }
1366 }
1367 
OnWebDebuggingAccessEnabledUpdate(bool value)1368 void WebPattern::OnWebDebuggingAccessEnabledUpdate(bool value)
1369 {
1370     if (delegate_) {
1371         delegate_->UpdateWebDebuggingAccess(value);
1372     }
1373 }
1374 
OnPinchSmoothModeEnabledUpdate(bool value)1375 void WebPattern::OnPinchSmoothModeEnabledUpdate(bool value)
1376 {
1377     if (delegate_) {
1378         delegate_->UpdatePinchSmoothModeEnabled(value);
1379     }
1380 }
1381 
OnBackgroundColorUpdate(int32_t value)1382 void WebPattern::OnBackgroundColorUpdate(int32_t value)
1383 {
1384     UpdateBackgroundColorRightNow(value);
1385     if (delegate_) {
1386         delegate_->UpdateBackgroundColor(value);
1387     }
1388 }
1389 
OnInitialScaleUpdate(float value)1390 void WebPattern::OnInitialScaleUpdate(float value)
1391 {
1392     if (delegate_) {
1393         delegate_->UpdateInitialScale(value);
1394     }
1395 }
1396 
OnMultiWindowAccessEnabledUpdate(bool value)1397 void WebPattern::OnMultiWindowAccessEnabledUpdate(bool value)
1398 {
1399     if (delegate_) {
1400         delegate_->UpdateMultiWindowAccess(value);
1401     }
1402 }
1403 
OnAllowWindowOpenMethodUpdate(bool value)1404 void WebPattern::OnAllowWindowOpenMethodUpdate(bool value)
1405 {
1406     if (delegate_) {
1407         delegate_->UpdateAllowWindowOpenMethod(value);
1408     }
1409 }
1410 
OnWebCursiveFontUpdate(const std::string & value)1411 void WebPattern::OnWebCursiveFontUpdate(const std::string& value)
1412 {
1413     if (delegate_) {
1414         delegate_->UpdateWebCursiveFont(value);
1415     }
1416 }
1417 
OnWebFantasyFontUpdate(const std::string & value)1418 void WebPattern::OnWebFantasyFontUpdate(const std::string& value)
1419 {
1420     if (delegate_) {
1421         delegate_->UpdateWebFantasyFont(value);
1422     }
1423 }
1424 
OnWebFixedFontUpdate(const std::string & value)1425 void WebPattern::OnWebFixedFontUpdate(const std::string& value)
1426 {
1427     if (delegate_) {
1428         delegate_->UpdateWebFixedFont(value);
1429     }
1430 }
1431 
OnWebSansSerifFontUpdate(const std::string & value)1432 void WebPattern::OnWebSansSerifFontUpdate(const std::string& value)
1433 {
1434     if (delegate_) {
1435         delegate_->UpdateWebSansSerifFont(value);
1436     }
1437 }
1438 
OnWebSerifFontUpdate(const std::string & value)1439 void WebPattern::OnWebSerifFontUpdate(const std::string& value)
1440 {
1441     if (delegate_) {
1442         delegate_->UpdateWebSerifFont(value);
1443     }
1444 }
1445 
OnWebStandardFontUpdate(const std::string & value)1446 void WebPattern::OnWebStandardFontUpdate(const std::string& value)
1447 {
1448     if (delegate_) {
1449         delegate_->UpdateWebStandardFont(value);
1450     }
1451 }
1452 
OnDefaultFixedFontSizeUpdate(int32_t value)1453 void WebPattern::OnDefaultFixedFontSizeUpdate(int32_t value)
1454 {
1455     if (delegate_) {
1456         delegate_->UpdateDefaultFixedFontSize(value);
1457     }
1458 }
1459 
OnDefaultFontSizeUpdate(int32_t value)1460 void WebPattern::OnDefaultFontSizeUpdate(int32_t value)
1461 {
1462     if (delegate_) {
1463         delegate_->UpdateDefaultFontSize(value);
1464     }
1465 }
1466 
OnMinFontSizeUpdate(int32_t value)1467 void WebPattern::OnMinFontSizeUpdate(int32_t value)
1468 {
1469     if (delegate_) {
1470         delegate_->UpdateMinFontSize(value);
1471     }
1472 }
1473 
OnMinLogicalFontSizeUpdate(int32_t value)1474 void WebPattern::OnMinLogicalFontSizeUpdate(int32_t value)
1475 {
1476     if (delegate_) {
1477         delegate_->UpdateMinLogicalFontSize(value);
1478     }
1479 }
1480 
OnBlockNetworkUpdate(bool value)1481 void WebPattern::OnBlockNetworkUpdate(bool value)
1482 {
1483     if (delegate_) {
1484         delegate_->UpdateBlockNetwork(value);
1485     }
1486 }
1487 
OnHorizontalScrollBarAccessEnabledUpdate(bool value)1488 void WebPattern::OnHorizontalScrollBarAccessEnabledUpdate(bool value)
1489 {
1490     if (delegate_) {
1491         delegate_->UpdateHorizontalScrollBarAccess(value);
1492     }
1493 }
1494 
OnVerticalScrollBarAccessEnabledUpdate(bool value)1495 void WebPattern::OnVerticalScrollBarAccessEnabledUpdate(bool value)
1496 {
1497     if (delegate_) {
1498         delegate_->UpdateVerticalScrollBarAccess(value);
1499     }
1500 }
1501 
OnNativeEmbedModeEnabledUpdate(bool value)1502 void WebPattern::OnNativeEmbedModeEnabledUpdate(bool value)
1503 {
1504     if (delegate_) {
1505         delegate_->UpdateNativeEmbedModeEnabled(value);
1506     }
1507 }
1508 
IsRootNeedExportTexture()1509 bool WebPattern::IsRootNeedExportTexture()
1510 {
1511     auto host = GetHost();
1512     CHECK_NULL_RETURN(host, false);
1513     bool isNeedExportTexture = false;
1514     for (auto parent = host->GetParent(); parent != nullptr; parent = parent->GetParent()) {
1515         RefPtr<FrameNode> frameNode = AceType::DynamicCast<FrameNode>(parent);
1516         if (!frameNode) {
1517             continue;
1518         }
1519         isNeedExportTexture = frameNode->IsNeedExportTexture();
1520         if (isNeedExportTexture) {
1521             return isNeedExportTexture;
1522         }
1523     }
1524     return isNeedExportTexture;
1525 }
1526 
OnScrollBarColorUpdate(const std::string & value)1527 void WebPattern::OnScrollBarColorUpdate(const std::string& value)
1528 {
1529     if (delegate_) {
1530         delegate_->UpdateScrollBarColor(value);
1531     }
1532 }
1533 
RegistVirtualKeyBoardListener()1534 void WebPattern::RegistVirtualKeyBoardListener()
1535 {
1536     if (!needUpdateWeb_) {
1537         return;
1538     }
1539     auto pipelineContext = PipelineContext::GetCurrentContext();
1540     CHECK_NULL_VOID(pipelineContext);
1541     pipelineContext->SetVirtualKeyBoardCallback(
1542         [weak = AceType::WeakClaim(this)](int32_t width, int32_t height, double keyboard) {
1543             auto webPattern = weak.Upgrade();
1544             CHECK_NULL_RETURN(webPattern, false);
1545             return webPattern->ProcessVirtualKeyBoard(width, height, keyboard);
1546         });
1547     needUpdateWeb_ = false;
1548 }
1549 
InitEnhanceSurfaceFlag()1550 void WebPattern::InitEnhanceSurfaceFlag()
1551 {
1552     if (SystemProperties::GetExtSurfaceEnabled()) {
1553         isEnhanceSurface_ = true;
1554     } else {
1555         isEnhanceSurface_ = false;
1556     }
1557 }
1558 
OnModifyDone()1559 void WebPattern::OnModifyDone()
1560 {
1561     Pattern::OnModifyDone();
1562     // called in each update function.
1563     auto host = GetHost();
1564     CHECK_NULL_VOID(host);
1565     auto renderContext = host->GetRenderContext();
1566     CHECK_NULL_VOID(renderContext);
1567     RegistVirtualKeyBoardListener();
1568     if (!delegate_) {
1569         // first create case,
1570         delegate_ = AceType::MakeRefPtr<WebDelegate>(PipelineContext::GetCurrentContext(), nullptr, "");
1571         CHECK_NULL_VOID(delegate_);
1572         observer_ = AceType::MakeRefPtr<WebDelegateObserver>(delegate_, PipelineContext::GetCurrentContext());
1573         CHECK_NULL_VOID(observer_);
1574         delegate_->SetObserver(observer_);
1575         delegate_->SetWebType(type_);
1576         InitEnhanceSurfaceFlag();
1577         delegate_->SetNGWebPattern(Claim(this));
1578         delegate_->SetEnhanceSurfaceFlag(isEnhanceSurface_);
1579         delegate_->SetPopup(isPopup_);
1580         delegate_->SetParentNWebId(parentNWebId_);
1581         delegate_->SetBackgroundColor(GetBackgroundColorValue(
1582             static_cast<int32_t>(renderContext->GetBackgroundColor().value_or(Color::WHITE).GetValue())));
1583         if (isEnhanceSurface_) {
1584             auto drawSize = Size(1, 1);
1585             delegate_->SetDrawSize(drawSize);
1586             delegate_->InitOHOSWeb(PipelineContext::GetCurrentContext());
1587         } else {
1588             auto drawSize = Size(1, 1);
1589             delegate_->SetDrawSize(drawSize);
1590             int32_t instanceId = Container::CurrentId();
1591             renderSurface_->SetInstanceId(instanceId);
1592             renderSurface_->SetRenderContext(host->GetRenderContext());
1593             if (type_ == WebType::TEXTURE) {
1594                 renderSurface_->SetIsTexture(true);
1595                 renderSurface_->SetPatternType(PATTERN_TYPE_WEB);
1596                 renderSurface_->SetSurfaceQueueSize(SURFACE_QUEUE_SIZE);
1597             } else {
1598                 renderSurface_->SetIsTexture(false);
1599             }
1600             renderSurface_->InitSurface();
1601             renderSurface_->UpdateXComponentConfig();
1602             delegate_->InitOHOSWeb(PipelineContext::GetCurrentContext(), renderSurface_);
1603         }
1604         UpdateJavaScriptOnDocumentStart();
1605         UpdateJavaScriptOnDocumentEnd();
1606         delegate_->UpdateBackgroundColor(GetBackgroundColorValue(
1607             static_cast<int32_t>(renderContext->GetBackgroundColor().value_or(Color::WHITE).GetValue())));
1608         delegate_->UpdateJavaScriptEnabled(GetJsEnabledValue(true));
1609         delegate_->UpdateBlockNetworkImage(!GetOnLineImageAccessEnabledValue(true));
1610         delegate_->UpdateAllowFileAccess(GetFileAccessEnabledValue(true));
1611         delegate_->UpdateLoadsImagesAutomatically(GetImageAccessEnabledValue(true));
1612         delegate_->UpdateMixedContentMode(GetMixedModeValue(MixedModeContent::MIXED_CONTENT_NEVER_ALLOW));
1613         delegate_->UpdateSupportZoom(GetZoomAccessEnabledValue(true));
1614         delegate_->UpdateDomStorageEnabled(GetDomStorageAccessEnabledValue(false));
1615         delegate_->UpdateGeolocationEnabled(GetGeolocationAccessEnabledValue(true));
1616         delegate_->UpdateCacheMode(GetCacheModeValue(WebCacheMode::DEFAULT));
1617         if (webData_) {
1618             // Created a richtext component
1619             delegate_->SetRichtextIdentifier(webData_);
1620             delegate_->UpdateDarkMode(GetDarkModeValue(WebDarkMode::Auto));
1621             delegate_->UpdateForceDarkAccess(GetForceDarkAccessValue(true));
1622             delegate_->UpdateOverviewModeEnabled(GetOverviewModeAccessEnabledValue(false));
1623         } else {
1624             delegate_->UpdateDarkMode(GetDarkModeValue(WebDarkMode::Off));
1625             delegate_->UpdateForceDarkAccess(GetForceDarkAccessValue(false));
1626             delegate_->UpdateOverviewModeEnabled(GetOverviewModeAccessEnabledValue(true));
1627         }
1628         delegate_->UpdateAudioResumeInterval(GetAudioResumeIntervalValue(-1));
1629         delegate_->UpdateAudioExclusive(GetAudioExclusiveValue(true));
1630         delegate_->UpdateFileFromUrlEnabled(GetFileFromUrlAccessEnabledValue(false));
1631         delegate_->UpdateDatabaseEnabled(GetDatabaseAccessEnabledValue(false));
1632         delegate_->UpdateTextZoomRatio(GetTextZoomRatioValue(DEFAULT_TEXT_ZOOM_RATIO));
1633         delegate_->UpdateWebDebuggingAccess(GetWebDebuggingAccessEnabledValue(false));
1634         delegate_->UpdateMediaPlayGestureAccess(GetMediaPlayGestureAccessValue(true));
1635         delegate_->UpdatePinchSmoothModeEnabled(GetPinchSmoothModeEnabledValue(false));
1636         delegate_->UpdateMultiWindowAccess(GetMultiWindowAccessEnabledValue(false));
1637         delegate_->UpdateWebCursiveFont(GetWebCursiveFontValue(DEFAULT_CURSIVE_FONT_FAMILY));
1638         delegate_->UpdateWebFantasyFont(GetWebFantasyFontValue(DEFAULT_FANTASY_FONT_FAMILY));
1639         delegate_->UpdateWebFixedFont(GetWebFixedFontValue(DEFAULT_FIXED_fONT_FAMILY));
1640         delegate_->UpdateWebSansSerifFont(GetWebSansSerifFontValue(DEFAULT_SANS_SERIF_FONT_FAMILY));
1641         delegate_->UpdateWebSerifFont(GetWebSerifFontValue(DEFAULT_SERIF_FONT_FAMILY));
1642         delegate_->UpdateWebStandardFont(GetWebStandardFontValue(DEFAULT_STANDARD_FONT_FAMILY));
1643         delegate_->UpdateDefaultFixedFontSize(GetDefaultFixedFontSizeValue(DEFAULT_FIXED_FONT_SIZE));
1644         delegate_->UpdateDefaultFontSize(GetDefaultFontSizeValue(DEFAULT_FONT_SIZE));
1645         delegate_->UpdateMinFontSize(GetMinFontSizeValue(DEFAULT_MINIMUM_FONT_SIZE));
1646         delegate_->UpdateMinLogicalFontSize(GetMinLogicalFontSizeValue(DEFAULT_MINIMUM_LOGICAL_FONT_SIZE));
1647         delegate_->UpdateHorizontalScrollBarAccess(GetHorizontalScrollBarAccessEnabledValue(true));
1648         delegate_->UpdateVerticalScrollBarAccess(GetVerticalScrollBarAccessEnabledValue(true));
1649         delegate_->UpdateScrollBarColor(GetScrollBarColorValue(DEFAULT_SCROLLBAR_COLOR));
1650         delegate_->UpdateOverScrollMode(GetOverScrollModeValue(OverScrollMode::NEVER));
1651         delegate_->UpdateCopyOptionMode(GetCopyOptionModeValue(static_cast<int32_t>(CopyOptions::Distributed)));
1652         if (GetBlockNetwork()) {
1653             delegate_->UpdateBlockNetwork(GetBlockNetwork().value());
1654         }
1655         if (GetUserAgent()) {
1656             delegate_->UpdateUserAgent(GetUserAgent().value());
1657         }
1658         if (GetInitialScale()) {
1659             delegate_->UpdateInitialScale(GetInitialScale().value());
1660         }
1661         isAllowWindowOpenMethod_ = SystemProperties::GetAllowWindowOpenMethodEnabled();
1662         delegate_->UpdateAllowWindowOpenMethod(GetAllowWindowOpenMethodValue(isAllowWindowOpenMethod_));
1663         if (!webAccessibilityNode_) {
1664             webAccessibilityNode_ = AceType::MakeRefPtr<WebAccessibilityNode>(host);
1665         }
1666         delegate_->UpdateNativeEmbedModeEnabled(GetNativeEmbedModeEnabledValue(false));
1667         accessibilityState_ = AceApplicationInfo::GetInstance().IsAccessibilityEnabled();
1668         if (accessibilityState_) {
1669             delegate_->SetAccessibilityState(true);
1670         }
1671     }
1672 
1673     // Initialize events such as keyboard, focus, etc.
1674     InitEvent();
1675     // Initialize web params.
1676     InitFeatureParam();
1677 
1678     // Initialize scrollupdate listener
1679     if (type_ == WebType::TEXTURE) {
1680         auto task = [this]() {
1681             InitScrollUpdateListener();
1682         };
1683         PostTaskToUI(std::move(task));
1684     }
1685 
1686     auto embedEnabledTask = [weak = AceType::WeakClaim(this)]() {
1687         auto webPattern = weak.Upgrade();
1688         CHECK_NULL_VOID(webPattern);
1689         if (webPattern->IsRootNeedExportTexture() && webPattern->delegate_) {
1690             webPattern->delegate_->UpdateNativeEmbedModeEnabled(false);
1691         }
1692     };
1693     PostTaskToUI(std::move(embedEnabledTask));
1694 
1695     auto pipelineContext = PipelineContext::GetCurrentContext();
1696     CHECK_NULL_VOID(pipelineContext);
1697     pipelineContext->AddOnAreaChangeNode(host->GetId());
1698 
1699     // offline mode
1700     if (host->GetNodeStatus() != NodeStatus::NORMAL_NODE) {
1701         TAG_LOGI(AceLogTag::ACE_WEB, "Web offline mode type");
1702         isOfflineMode_ = true;
1703         OfflineMode();
1704     }
1705 }
1706 
OfflineMode()1707 void WebPattern::OfflineMode()
1708 {
1709     auto host = GetHost();
1710     CHECK_NULL_VOID(host);
1711     int width = 0;
1712     int height = 0;
1713     auto layoutProperty = host->GetLayoutProperty();
1714     CHECK_NULL_VOID(layoutProperty);
1715     auto& calcLayout = layoutProperty->GetCalcLayoutConstraint();
1716     if (calcLayout) {
1717         width = calcLayout->selfIdealSize ?
1718             calcLayout->selfIdealSize->Width()->GetDimension().ConvertToPx() : 0;
1719         height = calcLayout->selfIdealSize ?
1720             calcLayout->selfIdealSize->Height()->GetDimension().ConvertToPx() : 0;
1721     }
1722     bool isUnSetSize = (width == 0) && (height == 0);
1723     auto defaultDisplay = OHOS::Rosen::DisplayManager::GetInstance().GetDefaultDisplay();
1724     if (isUnSetSize && defaultDisplay) {
1725         width = defaultDisplay->GetWidth();
1726         height = defaultDisplay->GetHeight();
1727     }
1728     Size drawSize = Size(width, height);
1729     Offset offset = Offset(0, 0);
1730     delegate_->SetBoundsOrResize(drawSize, offset);
1731     if (webSrc_) {
1732         delegate_->LoadUrl();
1733     } else if (webData_) {
1734         delegate_->LoadDataWithRichText();
1735     }
1736     isUrlLoaded_ = true;
1737     OnWindowHide();
1738 }
1739 
ProcessVirtualKeyBoard(int32_t width,int32_t height,double keyboard)1740 bool WebPattern::ProcessVirtualKeyBoard(int32_t width, int32_t height, double keyboard)
1741 {
1742     CHECK_NULL_RETURN(delegate_, false);
1743     delegate_->SetVirtualKeyBoardArg(width, height, keyboard);
1744     if (!isFocus_ || !isVisible_) {
1745         if (isVirtualKeyBoardShow_ == VkState::VK_SHOW) {
1746             drawSize_.SetSize(drawSizeCache_);
1747             UpdateWebLayoutSize(width, height, false);
1748             isVirtualKeyBoardShow_ = VkState::VK_HIDE;
1749         }
1750         return false;
1751     }
1752     if (NearZero(keyboard)) {
1753         if (isVirtualKeyBoardShow_ != VkState::VK_SHOW) {
1754             return false;
1755         }
1756         drawSize_.SetSize(drawSizeCache_);
1757         UpdateWebLayoutSize(width, height, false);
1758         isVirtualKeyBoardShow_ = VkState::VK_HIDE;
1759     } else if (isVirtualKeyBoardShow_ != VkState::VK_SHOW) {
1760         drawSizeCache_.SetSize(drawSize_);
1761         if (drawSize_.Height() <= (height - keyboard - GetCoordinatePoint()->GetY())) {
1762             isVirtualKeyBoardShow_ = VkState::VK_SHOW;
1763             return true;
1764         }
1765         if (height - GetCoordinatePoint()->GetY() < keyboard) {
1766             return true;
1767         }
1768         isVirtualKeyBoardShow_ = VkState::VK_SHOW;
1769         auto frameNode = GetHost();
1770         CHECK_NULL_RETURN(frameNode, false);
1771         frameNode->MarkDirtyNode(PROPERTY_UPDATE_MEASURE_SELF);
1772         auto context = PipelineContext::GetCurrentContext();
1773         CHECK_NULL_RETURN(context, false);
1774         context->SetRootRect(width, height, 0);
1775         auto taskExecutor = context->GetTaskExecutor();
1776         CHECK_NULL_RETURN(taskExecutor, false);
1777         taskExecutor->PostDelayedTask(
1778             [weak = WeakClaim(this), width, height, keyboard, oldWebHeight = drawSize_.Height()]() {
1779                 auto webPattern = weak.Upgrade();
1780                 CHECK_NULL_VOID(webPattern);
1781                 webPattern->UpdateLayoutAfterKerboardShow(width, height, keyboard, oldWebHeight);
1782             },
1783             TaskExecutor::TaskType::UI, UPDATE_WEB_LAYOUT_DELAY_TIME);
1784     }
1785     return true;
1786 }
1787 
UpdateWebLayoutSize(int32_t width,int32_t height,bool isKeyboard)1788 void WebPattern::UpdateWebLayoutSize(int32_t width, int32_t height, bool isKeyboard)
1789 {
1790     CHECK_NULL_VOID(delegate_);
1791     if (delegate_->ShouldVirtualKeyboardOverlay()) {
1792         TAG_LOGW(AceLogTag::ACE_WEB, "VirtualKeyboard Overlaycontent is true and does not require resizing");
1793         return;
1794     }
1795     auto frameNode = GetHost();
1796     CHECK_NULL_VOID(frameNode);
1797     auto rect = frameNode->GetGeometryNode()->GetFrameRect();
1798     auto offset = Offset(GetCoordinatePoint()->GetX(), GetCoordinatePoint()->GetY());
1799 
1800     // Scroll focused node into view when keyboard show.
1801     delegate_->SetBoundsOrResize(drawSize_, offset, isKeyboard);
1802 
1803     rect.SetSize(SizeF(drawSize_.Width(), drawSize_.Height()));
1804     frameNode->GetRenderContext()->SyncGeometryProperties(rect);
1805     frameNode->MarkDirtyNode(PROPERTY_UPDATE_MEASURE_SELF);
1806     auto context = PipelineContext::GetCurrentContext();
1807     CHECK_NULL_VOID(context);
1808     context->SetRootRect(width, height, 0);
1809 }
1810 
HandleTouchDown(const TouchEventInfo & info,bool fromOverlay)1811 void WebPattern::HandleTouchDown(const TouchEventInfo& info, bool fromOverlay)
1812 {
1813     CHECK_NULL_VOID(delegate_);
1814     Offset touchOffset = Offset(0, 0);
1815     std::list<TouchInfo> touchInfos;
1816     if (!ParseTouchInfo(info, touchInfos)) {
1817         return;
1818     }
1819     for (auto& touchPoint : touchInfos) {
1820         if (fromOverlay) {
1821             touchPoint.x -= webOffset_.GetX();
1822             touchPoint.y -= webOffset_.GetY();
1823         }
1824         delegate_->HandleTouchDown(touchPoint.id, touchPoint.x, touchPoint.y, fromOverlay);
1825     }
1826     if (!touchInfos.empty()) {
1827         WebRequestFocus();
1828     }
1829 }
1830 
HandleTouchUp(const TouchEventInfo & info,bool fromOverlay)1831 void WebPattern::HandleTouchUp(const TouchEventInfo& info, bool fromOverlay)
1832 {
1833     ResetDragAction();
1834     CHECK_NULL_VOID(delegate_);
1835     std::list<TouchInfo> touchInfos;
1836     if (!ParseTouchInfo(info, touchInfos)) {
1837         return;
1838     }
1839     for (auto& touchPoint : touchInfos) {
1840         if (fromOverlay) {
1841             touchPoint.x -= webOffset_.GetX();
1842             touchPoint.y -= webOffset_.GetY();
1843         }
1844         delegate_->HandleTouchUp(touchPoint.id, touchPoint.x, touchPoint.y, fromOverlay);
1845     }
1846 }
1847 
HandleTouchMove(const TouchEventInfo & info,bool fromOverlay)1848 void WebPattern::HandleTouchMove(const TouchEventInfo& info, bool fromOverlay)
1849 {
1850     if (isDragging_) {
1851         return;
1852     }
1853     auto pipeline = PipelineContext::GetCurrentContext();
1854     CHECK_NULL_VOID(pipeline);
1855     auto manager = pipeline->GetDragDropManager();
1856     CHECK_NULL_VOID(manager);
1857     if (manager->IsDragged()) {
1858         return;
1859     }
1860     CHECK_NULL_VOID(delegate_);
1861     std::list<TouchInfo> touchInfos;
1862 
1863     touchEventInfoList_.emplace_back(info);
1864     for (const auto& touchEventInfo : touchEventInfoList_) {
1865         ParseTouchInfo(touchEventInfo, touchInfos);
1866     }
1867 
1868     if (touchInfos.empty()) {
1869         return;
1870     }
1871     if (!info.GetTouchEventsEnd()) {
1872         return;
1873     }
1874     touchEventInfoList_.clear();
1875 
1876     std::list<OHOS::NWeb::TouchPointInfo> touchPointInfoList {};
1877     for (auto& touchPoint : touchInfos) {
1878         if (fromOverlay) {
1879             touchPoint.x -= webOffset_.GetX();
1880             touchPoint.y -= webOffset_.GetY();
1881         }
1882         touchPointInfoList.emplace_back(OHOS::NWeb::TouchPointInfo{touchPoint.id, touchPoint.x, touchPoint.y});
1883     }
1884     touchPointInfoList.sort([](const OHOS::NWeb::TouchPointInfo& point1, const OHOS::NWeb::TouchPointInfo& point2) {
1885         return point1.id_ < point2.id_;
1886     });
1887     delegate_->HandleTouchMove(touchPointInfoList, fromOverlay);
1888 }
1889 
HandleTouchCancel(const TouchEventInfo & info)1890 void WebPattern::HandleTouchCancel(const TouchEventInfo& info)
1891 {
1892     if (IsRootNeedExportTexture()) {
1893         HandleTouchUp(info, false);
1894     }
1895     CHECK_NULL_VOID(delegate_);
1896     delegate_->HandleTouchCancel();
1897 }
1898 
ParseTouchInfo(const TouchEventInfo & info,std::list<TouchInfo> & touchInfos)1899 bool WebPattern::ParseTouchInfo(const TouchEventInfo& info, std::list<TouchInfo>& touchInfos)
1900 {
1901     auto context = PipelineContext::GetCurrentContext();
1902     CHECK_NULL_RETURN(context, false);
1903     auto viewScale = context->GetViewScale();
1904     if (info.GetChangedTouches().empty()) {
1905         return false;
1906     }
1907     for (const auto& point : info.GetChangedTouches()) {
1908         TouchInfo touchInfo;
1909         touchInfo.id = point.GetFingerId();
1910         const Offset& location = point.GetLocalLocation();
1911         touchInfo.x = static_cast<float>(location.GetX() * viewScale);
1912         touchInfo.y = static_cast<float>(location.GetY() * viewScale);
1913         touchInfos.emplace_back(touchInfo);
1914     }
1915     return true;
1916 }
1917 
RequestFullScreen()1918 void WebPattern::RequestFullScreen()
1919 {
1920     isFullScreen_ = true;
1921 }
1922 
ExitFullScreen()1923 void WebPattern::ExitFullScreen()
1924 {
1925     isFullScreen_ = false;
1926 }
1927 
IsTouchHandleValid(std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> handle)1928 bool WebPattern::IsTouchHandleValid(std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> handle)
1929 {
1930     return (handle != nullptr) && (handle->IsEnable());
1931 }
1932 
IsTouchHandleShow(std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> handle)1933 bool WebPattern::IsTouchHandleShow(std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> handle)
1934 {
1935     CHECK_NULL_RETURN(handle, false);
1936     auto pipeline = PipelineBase::GetCurrentContext();
1937     CHECK_NULL_RETURN(pipeline, false);
1938     int y = static_cast<int32_t>(handle->GetY() / pipeline->GetDipScale());
1939     int edgeHeight = static_cast<int32_t>(handle->GetEdgeHeight() / pipeline->GetDipScale()) - 1;
1940     if (handle->GetAlpha() > 0 && y >= edgeHeight &&
1941         GreatNotEqual(GetHostFrameSize().value_or(SizeF()).Height(), handle->GetY())) {
1942         return true;
1943     }
1944     return false;
1945 }
1946 
GetTouchHandleOverlayType(std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> insertHandle,std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> startSelectionHandle,std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> endSelectionHandle)1947 WebOverlayType WebPattern::GetTouchHandleOverlayType(std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> insertHandle,
1948     std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> startSelectionHandle,
1949     std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> endSelectionHandle)
1950 {
1951     if (IsTouchHandleValid(insertHandle) && !IsTouchHandleValid(startSelectionHandle) &&
1952         !IsTouchHandleValid(endSelectionHandle)) {
1953         return INSERT_OVERLAY;
1954     }
1955 
1956     if (!IsTouchHandleValid(insertHandle) && IsTouchHandleValid(startSelectionHandle) &&
1957         IsTouchHandleValid(endSelectionHandle)) {
1958         return SELECTION_OVERLAY;
1959     }
1960 
1961     return INVALID_OVERLAY;
1962 }
1963 
GetCoordinatePoint()1964 std::optional<OffsetF> WebPattern::GetCoordinatePoint()
1965 {
1966     auto frameNode = GetHost();
1967     CHECK_NULL_RETURN(frameNode, std::nullopt);
1968     return frameNode->GetTransformRelativeOffset();
1969 }
1970 
ComputeTouchHandleRect(std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> touchHandle)1971 RectF WebPattern::ComputeTouchHandleRect(std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> touchHandle)
1972 {
1973     RectF paintRect;
1974     auto offset = GetCoordinatePoint().value_or(OffsetF());
1975     auto size = GetHostFrameSize().value_or(SizeF());
1976     float edgeHeight = touchHandle->GetEdgeHeight();
1977     float x = touchHandle->GetX();
1978     float y = touchHandle->GetY();
1979     if (x > size.Width()) {
1980         x = offset.GetX() + size.Width();
1981     } else {
1982         x = x + offset.GetX();
1983     }
1984 
1985     if (y < 0) {
1986         y = offset.GetY();
1987     } else if (y > size.Height()) {
1988         y = offset.GetY() + size.Height();
1989     } else {
1990         y = y + offset.GetY();
1991         y = y - edgeHeight;
1992     }
1993 
1994     x = x - SelectHandleInfo::GetDefaultLineWidth().ConvertToPx() / 2;
1995     paintRect.SetOffset({ x, y });
1996     paintRect.SetSize({ SelectHandleInfo::GetDefaultLineWidth().ConvertToPx(), edgeHeight });
1997     return paintRect;
1998 }
1999 
CloseSelectOverlay()2000 void WebPattern::CloseSelectOverlay()
2001 {
2002     auto pipeline = PipelineContext::GetCurrentContext();
2003     CHECK_NULL_VOID(pipeline);
2004     if (selectOverlayProxy_) {
2005         selectOverlayProxy_->Close();
2006         pipeline->GetSelectOverlayManager()->DestroySelectOverlay(selectOverlayProxy_);
2007         selectOverlayProxy_ = nullptr;
2008     }
2009 }
2010 
RegisterSelectOverlayCallback(SelectOverlayInfo & selectInfo,std::shared_ptr<OHOS::NWeb::NWebQuickMenuParams> params,std::shared_ptr<OHOS::NWeb::NWebQuickMenuCallback> callback)2011 void WebPattern::RegisterSelectOverlayCallback(SelectOverlayInfo& selectInfo,
2012     std::shared_ptr<OHOS::NWeb::NWebQuickMenuParams> params,
2013     std::shared_ptr<OHOS::NWeb::NWebQuickMenuCallback> callback)
2014 {
2015     CHECK_NULL_VOID(delegate_);
2016     auto copyOption = delegate_->GetCopyOptionMode();
2017     quickMenuCallback_ = callback;
2018     int32_t flags = params->GetEditStateFlags();
2019     if ((flags & OHOS::NWeb::NWebQuickMenuParams::QM_EF_CAN_CUT)
2020         && (copyOption != OHOS::NWeb::NWebPreference::CopyOptionMode::NONE)) {
2021         selectInfo.menuCallback.onCut = [weak = AceType::WeakClaim(this), callback]() {
2022             CHECK_NULL_VOID(callback);
2023             callback->Continue(
2024                 OHOS::NWeb::NWebQuickMenuParams::QM_EF_CAN_CUT, OHOS::NWeb::MenuEventFlags::EF_LEFT_MOUSE_BUTTON);
2025         };
2026     } else {
2027         selectInfo.menuInfo.showCut = false;
2028     }
2029     if ((flags & OHOS::NWeb::NWebQuickMenuParams::QM_EF_CAN_COPY)
2030         && (copyOption != OHOS::NWeb::NWebPreference::CopyOptionMode::NONE)) {
2031         selectInfo.menuCallback.onCopy = [weak = AceType::WeakClaim(this), callback]() {
2032             CHECK_NULL_VOID(callback);
2033             callback->Continue(
2034                 OHOS::NWeb::NWebQuickMenuParams::QM_EF_CAN_COPY, OHOS::NWeb::MenuEventFlags::EF_LEFT_MOUSE_BUTTON);
2035         };
2036     } else {
2037         selectInfo.menuInfo.showCopy = false;
2038     }
2039     if (flags & OHOS::NWeb::NWebQuickMenuParams::QM_EF_CAN_PASTE) {
2040         selectInfo.menuCallback.onPaste = [weak = AceType::WeakClaim(this), callback]() {
2041             CHECK_NULL_VOID(callback);
2042             callback->Continue(
2043                 OHOS::NWeb::NWebQuickMenuParams::QM_EF_CAN_PASTE, OHOS::NWeb::MenuEventFlags::EF_LEFT_MOUSE_BUTTON);
2044         };
2045     } else {
2046         selectInfo.menuInfo.showPaste = false;
2047     }
2048     if (flags & OHOS::NWeb::NWebQuickMenuParams::QM_EF_CAN_SELECT_ALL) {
2049         selectInfo.menuCallback.onSelectAll = [weak = AceType::WeakClaim(this), callback]() {
2050             CHECK_NULL_VOID(callback);
2051             callback->Continue(OHOS::NWeb::NWebQuickMenuParams::QM_EF_CAN_SELECT_ALL,
2052                 OHOS::NWeb::MenuEventFlags::EF_LEFT_MOUSE_BUTTON);
2053         };
2054     } else {
2055         selectInfo.menuInfo.showCopyAll = false;
2056     }
2057 }
2058 
RegisterSelectOverlayEvent(SelectOverlayInfo & selectInfo)2059 void WebPattern::RegisterSelectOverlayEvent(SelectOverlayInfo& selectInfo)
2060 {
2061     selectInfo.onHandleMoveDone = [weak = AceType::WeakClaim(this)](const RectF& rectF, bool isFirst) {
2062         auto webPattern = weak.Upgrade();
2063         CHECK_NULL_VOID(webPattern);
2064         webPattern->UpdateTouchHandleForOverlay();
2065         webPattern->SetSelectOverlayDragging(false);
2066     };
2067     selectInfo.onTouchDown = [weak = AceType::WeakClaim(this)](const TouchEventInfo& info) {
2068         auto webPattern = weak.Upgrade();
2069         CHECK_NULL_VOID(webPattern);
2070         webPattern->HandleTouchDown(info, true);
2071     };
2072     selectInfo.onTouchUp = [weak = AceType::WeakClaim(this)](const TouchEventInfo& info) {
2073         auto webPattern = weak.Upgrade();
2074         CHECK_NULL_VOID(webPattern);
2075         webPattern->HandleTouchUp(info, true);
2076     };
2077     selectInfo.onTouchMove = [weak = AceType::WeakClaim(this)](const TouchEventInfo& info) {
2078         auto webPattern = weak.Upgrade();
2079         CHECK_NULL_VOID(webPattern);
2080         if (webPattern->IsSelectOverlayDragging()) {
2081             webPattern->HandleTouchMove(info, true);
2082         }
2083     };
2084     selectInfo.onHandleMoveStart = [weak = AceType::WeakClaim(this)](bool isFirst) {
2085         auto webPattern = weak.Upgrade();
2086         CHECK_NULL_VOID(webPattern);
2087         webPattern->SetCurrentStartHandleDragging(isFirst);
2088         webPattern->SetSelectOverlayDragging(true);
2089     };
2090 }
2091 
RunQuickMenu(std::shared_ptr<OHOS::NWeb::NWebQuickMenuParams> params,std::shared_ptr<OHOS::NWeb::NWebQuickMenuCallback> callback)2092 bool WebPattern::RunQuickMenu(std::shared_ptr<OHOS::NWeb::NWebQuickMenuParams> params,
2093     std::shared_ptr<OHOS::NWeb::NWebQuickMenuCallback> callback)
2094 {
2095     std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> insertTouchHandle =
2096         params->GetTouchHandleState(OHOS::NWeb::NWebTouchHandleState::TouchHandleType::INSERT_HANDLE);
2097     std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> beginTouchHandle =
2098         params->GetTouchHandleState(OHOS::NWeb::NWebTouchHandleState::TouchHandleType::SELECTION_BEGIN_HANDLE);
2099     std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> endTouchHandle =
2100         params->GetTouchHandleState(OHOS::NWeb::NWebTouchHandleState::TouchHandleType::SELECTION_END_HANDLE);
2101     WebOverlayType overlayType = GetTouchHandleOverlayType(insertTouchHandle, beginTouchHandle, endTouchHandle);
2102     if (overlayType == INVALID_OVERLAY) {
2103         return false;
2104     }
2105     if (selectOverlayProxy_) {
2106         CloseSelectOverlay();
2107     }
2108     auto pipeline = PipelineContext::GetCurrentContext();
2109     CHECK_NULL_RETURN(pipeline, false);
2110     auto theme = pipeline->GetTheme<TextOverlayTheme>();
2111     CHECK_NULL_RETURN(theme, false);
2112     selectHotZone_ = theme->GetHandleHotZoneRadius().ConvertToPx();
2113     SelectOverlayInfo selectInfo;
2114     selectInfo.isSingleHandle = (overlayType == INSERT_OVERLAY);
2115     selectInfo.hitTestMode = HitTestMode::HTMDEFAULT;
2116     if (selectInfo.isSingleHandle) {
2117         selectInfo.firstHandle.isShow = IsTouchHandleShow(insertTouchHandle);
2118         selectInfo.firstHandle.paintRect = ComputeTouchHandleRect(insertTouchHandle);
2119         selectInfo.secondHandle.isShow = false;
2120     } else {
2121         selectInfo.firstHandle.isShow = IsTouchHandleShow(beginTouchHandle);
2122         selectInfo.firstHandle.paintRect = ComputeTouchHandleRect(beginTouchHandle);
2123         selectInfo.secondHandle.isShow = IsTouchHandleShow(endTouchHandle);
2124         selectInfo.secondHandle.paintRect = ComputeTouchHandleRect(endTouchHandle);
2125     }
2126     selectInfo.menuInfo.menuIsShow = true;
2127     RegisterSelectOverlayCallback(selectInfo, params, callback);
2128     RegisterSelectOverlayEvent(selectInfo);
2129     selectOverlayProxy_ = pipeline->GetSelectOverlayManager()->CreateAndShowSelectOverlay(selectInfo, WeakClaim(this));
2130     selectMenuInfo_ = selectInfo.menuInfo;
2131     insertHandle_ = insertTouchHandle;
2132     startSelectionHandle_ = beginTouchHandle;
2133     endSelectionHandle_ = endTouchHandle;
2134     return selectOverlayProxy_ ? true : false;
2135 }
2136 
OnQuickMenuDismissed()2137 void WebPattern::OnQuickMenuDismissed()
2138 {
2139     CloseSelectOverlay();
2140 }
2141 
UpdateSelectHandleInfo()2142 void WebPattern::UpdateSelectHandleInfo()
2143 {
2144     bool needReverse = IsSelectHandleReverse();
2145     SelectHandleInfo handleInfo;
2146     if (!needReverse) {
2147         if (!isCurrentStartHandleDragging_) {
2148             handleInfo.isShow = IsTouchHandleShow(startSelectionHandle_);
2149             handleInfo.paintRect = ComputeTouchHandleRect(startSelectionHandle_);
2150             selectOverlayProxy_->UpdateFirstSelectHandleInfo(handleInfo);
2151         } else {
2152             handleInfo.isShow = IsTouchHandleShow(endSelectionHandle_);
2153             handleInfo.paintRect = ComputeTouchHandleRect(endSelectionHandle_);
2154             selectOverlayProxy_->UpdateSecondSelectHandleInfo(handleInfo);
2155         }
2156     } else {
2157         if (!isCurrentStartHandleDragging_) {
2158             handleInfo.isShow = IsTouchHandleShow(endSelectionHandle_);
2159             handleInfo.paintRect = ComputeTouchHandleRect(endSelectionHandle_);
2160             selectOverlayProxy_->UpdateFirstSelectHandleInfo(handleInfo);
2161         } else {
2162             handleInfo.isShow = IsTouchHandleShow(startSelectionHandle_);
2163             handleInfo.paintRect = ComputeTouchHandleRect(startSelectionHandle_);
2164             selectOverlayProxy_->UpdateSecondSelectHandleInfo(handleInfo);
2165         }
2166     }
2167 }
2168 
IsSelectHandleReverse()2169 bool WebPattern::IsSelectHandleReverse()
2170 {
2171     if (startSelectionHandle_->GetTouchHandleType() ==
2172         OHOS::NWeb::NWebTouchHandleState::SELECTION_BEGIN_HANDLE &&
2173         endSelectionHandle_->GetTouchHandleType() ==
2174         OHOS::NWeb::NWebTouchHandleState::SELECTION_BEGIN_HANDLE) {
2175         return true;
2176     } else if (startSelectionHandle_->GetTouchHandleType() ==
2177         OHOS::NWeb::NWebTouchHandleState::SELECTION_END_HANDLE &&
2178         endSelectionHandle_->GetTouchHandleType() ==
2179         OHOS::NWeb::NWebTouchHandleState::SELECTION_END_HANDLE) {
2180         return true;
2181     }
2182     return false;
2183 }
2184 
OnTouchSelectionChanged(std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> insertHandle,std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> startSelectionHandle,std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> endSelectionHandle)2185 void WebPattern::OnTouchSelectionChanged(std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> insertHandle,
2186     std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> startSelectionHandle,
2187     std::shared_ptr<OHOS::NWeb::NWebTouchHandleState> endSelectionHandle)
2188 {
2189     WebOverlayType overlayType = GetTouchHandleOverlayType(insertHandle, startSelectionHandle, endSelectionHandle);
2190     if (overlayType == INVALID_OVERLAY) {
2191         CloseSelectOverlay();
2192         return;
2193     }
2194     auto pipeline = PipelineContext::GetCurrentContext();
2195     CHECK_NULL_VOID(pipeline);
2196     auto theme = pipeline->GetTheme<TextOverlayTheme>();
2197     CHECK_NULL_VOID(theme);
2198     selectHotZone_ = theme->GetHandleHotZoneRadius().ConvertToPx();
2199     insertHandle_ = insertHandle;
2200     startSelectionHandle_ = startSelectionHandle;
2201     endSelectionHandle_ = endSelectionHandle;
2202     if (!selectOverlayProxy_) {
2203         if (overlayType == INSERT_OVERLAY) {
2204             SelectOverlayInfo selectInfo;
2205             selectInfo.isSingleHandle = true;
2206             selectInfo.firstHandle.isShow = IsTouchHandleShow(insertHandle_);
2207             selectInfo.firstHandle.paintRect = ComputeTouchHandleRect(insertHandle_);
2208             selectInfo.secondHandle.isShow = false;
2209             selectInfo.menuInfo.menuDisable = true;
2210             selectInfo.menuInfo.menuIsShow = false;
2211             selectInfo.hitTestMode = HitTestMode::HTMDEFAULT;
2212             RegisterSelectOverlayEvent(selectInfo);
2213             selectOverlayProxy_ =
2214                 pipeline->GetSelectOverlayManager()->CreateAndShowSelectOverlay(selectInfo, WeakClaim(this));
2215         }
2216     } else {
2217         if (overlayType == INSERT_OVERLAY) {
2218             UpdateTouchHandleForOverlay();
2219         } else {
2220             UpdateSelectHandleInfo();
2221         }
2222     }
2223 }
2224 
OnCursorChange(const OHOS::NWeb::CursorType & type,const OHOS::NWeb::NWebCursorInfo & info)2225 bool WebPattern::OnCursorChange(const OHOS::NWeb::CursorType& type, const OHOS::NWeb::NWebCursorInfo& info)
2226 {
2227     (void)info;
2228     auto pipeline = PipelineContext::GetCurrentContext();
2229     CHECK_NULL_RETURN(pipeline, false);
2230     auto windowId = pipeline->GetWindowId();
2231     auto mouseStyle = MouseStyle::CreateMouseStyle();
2232     int32_t curPointerStyle = 0;
2233     if (mouseStyle->GetPointerStyle(windowId, curPointerStyle) == -1) {
2234         return false;
2235     }
2236     if ((type == OHOS::NWeb::CursorType::CT_CONTEXTMENU) || (type == OHOS::NWeb::CursorType::CT_ALIAS)) {
2237         UpdateLocalCursorStyle(windowId, type);
2238     } else {
2239         MouseFormat pointStyle = MouseFormat::DEFAULT;
2240         int64_t idx = BinarySearchFindIndex(g_cursorTypeMap, ArraySize(g_cursorTypeMap), type);
2241         if (idx >= 0) {
2242             pointStyle = g_cursorTypeMap[idx].value;
2243         }
2244         mouseStyle->SetPointerVisible(pointStyle);
2245         if (static_cast<int32_t>(pointStyle) != curPointerStyle) {
2246             mouseStyle->SetPointerStyle(windowId, pointStyle);
2247         }
2248     }
2249     return true;
2250 }
2251 
UpdateLocalCursorStyle(int32_t windowId,const OHOS::NWeb::CursorType & type)2252 void WebPattern::UpdateLocalCursorStyle(int32_t windowId, const OHOS::NWeb::CursorType& type)
2253 {
2254     std::shared_ptr<Media::PixelMap> pixelMap;
2255     auto mouseStyle = MouseStyle::CreateMouseStyle();
2256     if (type == NWeb::CursorType::CT_CONTEXTMENU) {
2257         MouseFormat pointStyle = MouseFormat::CONTEXT_MENU;
2258         pixelMap = CreatePixelMapFromString(IMAGE_POINTER_CONTEXT_MENU_PATH);
2259         mouseStyle->SetMouseIcon(windowId, pointStyle, pixelMap);
2260     } else if (type == NWeb::CursorType::CT_ALIAS) {
2261         MouseFormat pointStyle = MouseFormat::ALIAS;
2262         pixelMap = CreatePixelMapFromString(IMAGE_POINTER_ALIAS_PATH);
2263         mouseStyle->SetMouseIcon(windowId, pointStyle, pixelMap);
2264     }
2265 }
2266 
CreatePixelMapFromString(const std::string & filePath)2267 std::shared_ptr<OHOS::Media::PixelMap> WebPattern::CreatePixelMapFromString(const std::string& filePath)
2268 {
2269     OHOS::Media::SourceOptions opts;
2270     opts.formatHint = "image/svg+xml";
2271     uint32_t errCode = 0;
2272     auto imageSource = OHOS::Media::ImageSource::CreateImageSource(filePath, opts, errCode);
2273     CHECK_NULL_RETURN(imageSource, nullptr);
2274     std::set<std::string> formats;
2275     errCode = imageSource->GetSupportedFormats(formats);
2276     Media::DecodeOptions decodeOpts;
2277     std::shared_ptr<OHOS::Media::PixelMap> pixelMap = imageSource->CreatePixelMap(decodeOpts, errCode);
2278     CHECK_NULL_RETURN(pixelMap, nullptr);
2279 
2280     return pixelMap;
2281 }
2282 
OnSelectPopupMenu(std::shared_ptr<OHOS::NWeb::NWebSelectPopupMenuParam> params,std::shared_ptr<OHOS::NWeb::NWebSelectPopupMenuCallback> callback)2283 void WebPattern::OnSelectPopupMenu(std::shared_ptr<OHOS::NWeb::NWebSelectPopupMenuParam> params,
2284     std::shared_ptr<OHOS::NWeb::NWebSelectPopupMenuCallback> callback)
2285 {
2286     CHECK_NULL_VOID(params);
2287     CHECK_NULL_VOID(callback);
2288     auto host = GetHost();
2289     CHECK_NULL_VOID(host);
2290     auto id = host->GetId();
2291     std::vector<SelectParam> selectParam;
2292     for (auto& item : params->menuItems) {
2293         selectParam.push_back({
2294             item.label, ""
2295         });
2296     }
2297     auto menu = MenuView::Create(selectParam, id, host->GetTag());
2298     auto context = PipelineContext::GetCurrentContext();
2299     CHECK_NULL_VOID(context);
2300     auto eventHub = host->GetEventHub<WebEventHub>();
2301     auto destructor = [weak = WeakClaim(this), id]() {
2302         auto pattern = weak.Upgrade();
2303         CHECK_NULL_VOID(pattern);
2304         auto pipeline = NG::PipelineContext::GetCurrentContext();
2305         CHECK_NULL_VOID(pipeline);
2306         auto overlayManager = pipeline->GetOverlayManager();
2307         CHECK_NULL_VOID(overlayManager);
2308         pattern->SetSelectPopupMenuShowing(false);
2309         overlayManager->DeleteMenu(id);
2310     };
2311     CHECK_NULL_VOID(eventHub);
2312     eventHub->SetOnDisappear(destructor);
2313 
2314     WebPattern::RegisterSelectPopupCallback(menu, callback, params);
2315     auto overlayManager = context->GetOverlayManager();
2316     CHECK_NULL_VOID(overlayManager);
2317     auto menuWrapperPattern = menu->GetPattern<MenuWrapperPattern>();
2318     CHECK_NULL_VOID(menuWrapperPattern);
2319     menuWrapperPattern->RegisterMenuDisappearCallback([weak = WeakClaim(this), callback]() {
2320         auto pattern = weak.Upgrade();
2321         CHECK_NULL_VOID(pattern);
2322         callback->Cancel();
2323         pattern->SetSelectPopupMenuShowing(false);
2324     });
2325     auto offset = GetSelectPopupPostion(params->bounds);
2326     selectPopupMenuShowing_ = true;
2327     overlayManager->ShowMenu(id, offset, menu);
2328 }
2329 
OnDateTimeChooserPopup(const NWeb::DateTimeChooser & chooser,const std::vector<NWeb::DateTimeSuggestion> & suggestions,std::shared_ptr<NWeb::NWebDateTimeChooserCallback> callback)2330 void WebPattern::OnDateTimeChooserPopup(const NWeb::DateTimeChooser& chooser,
2331     const std::vector<NWeb::DateTimeSuggestion>& suggestions,
2332     std::shared_ptr<NWeb::NWebDateTimeChooserCallback> callback)
2333 {
2334     bool result = false;
2335     if (suggestions.size() != 0) {
2336         result = ShowDateTimeSuggestionDialog(chooser, suggestions, callback);
2337     } else if (chooser.type == NWeb::DTC_TIME) {
2338         result = ShowTimeDialog(chooser, suggestions, callback);
2339     } else {
2340         result = ShowDateTimeDialog(chooser, suggestions, callback);
2341     }
2342     if (!result) {
2343         callback->Continue(false, OHOS::NWeb::DateTime());
2344     }
2345 }
2346 
GetDialogProperties(const RefPtr<DialogTheme> & theme)2347 DialogProperties WebPattern::GetDialogProperties(const RefPtr<DialogTheme>& theme)
2348 {
2349     DialogProperties properties;
2350     if (SystemProperties::GetDeviceType() == DeviceType::PHONE) {
2351         properties.alignment = DialogAlignment::BOTTOM;
2352     } else {
2353         properties.alignment = DialogAlignment::CENTER;
2354     }
2355     properties.customStyle = false;
2356     properties.offset = DimensionOffset(Offset(0, -theme->GetMarginBottom().ConvertToPx()));
2357     return properties;
2358 }
2359 
ShowDateTimeDialog(const NWeb::DateTimeChooser & chooser,const std::vector<NWeb::DateTimeSuggestion> & suggestions,std::shared_ptr<NWeb::NWebDateTimeChooserCallback> callback)2360 bool WebPattern::ShowDateTimeDialog(const NWeb::DateTimeChooser& chooser,
2361     const std::vector<NWeb::DateTimeSuggestion>& suggestions,
2362     std::shared_ptr<NWeb::NWebDateTimeChooserCallback> callback)
2363 {
2364     auto container = Container::Current();
2365     CHECK_NULL_RETURN(container, false);
2366     auto pipelineContext = AccessibilityManager::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
2367     CHECK_NULL_RETURN(pipelineContext, false);
2368     auto executor = pipelineContext->GetTaskExecutor();
2369     CHECK_NULL_RETURN(executor, false);
2370     auto context = AccessibilityManager::DynamicCast<NG::PipelineContext>(pipelineContext);
2371     auto overlayManager = context ? context->GetOverlayManager() : nullptr;
2372     CHECK_NULL_RETURN(overlayManager, false);
2373     auto theme = pipelineContext->GetTheme<DialogTheme>();
2374     CHECK_NULL_RETURN(theme, false);
2375     NG::DatePickerSettingData settingData;
2376     settingData.isLunar = false;
2377     settingData.showTime = chooser.type == NWeb::DTC_DATETIME_LOCAL;
2378     settingData.useMilitary = true;
2379     DialogProperties properties = GetDialogProperties(theme);
2380     std::map<std::string, PickerDate> datePickerProperty;
2381     std::map<std::string, PickerTime> timePickerProperty;
2382     settingData.datePickerProperty["start"] = PickerDate(
2383         chooser.minimum.year, chooser.minimum.month + 1, chooser.minimum.day);
2384     settingData.datePickerProperty["end"] = PickerDate(
2385         chooser.maximum.year, chooser.maximum.month + 1, chooser.maximum.day);
2386     if (chooser.hasSelected) {
2387         int32_t day = (chooser.dialogValue.day == 0) ? 1 : chooser.dialogValue.day;
2388         settingData.datePickerProperty["selected"] =
2389             PickerDate(chooser.dialogValue.year, chooser.dialogValue.month + 1, day);
2390     }
2391     std::map<std::string, NG::DialogEvent> dialogEvent;
2392     std::map<std::string, NG::DialogGestureEvent> dialogCancelEvent;
2393     auto acceptId = [callback](const std::string& info) {
2394         OHOS::NWeb::DateTime result;
2395         bool success = ParseDateTimeJson(info, result);
2396         callback->Continue(success, result);
2397     };
2398     dialogEvent["acceptId"] = acceptId;
2399     auto cancelId = [callback](const GestureEvent&) { callback->Continue(false, OHOS::NWeb::DateTime()); };
2400     dialogCancelEvent["cancelId"] = cancelId;
2401     overlayManager->RegisterOnHideDialog([callback] { callback->Continue(false, OHOS::NWeb::DateTime()); });
2402     executor->PostTask(
2403         [properties, settingData, dialogEvent, dialogCancelEvent, weak = WeakPtr<NG::OverlayManager>(overlayManager)] {
2404             auto overlayManager = weak.Upgrade();
2405             CHECK_NULL_VOID(overlayManager);
2406             overlayManager->ShowDateDialog(properties, settingData, dialogEvent, dialogCancelEvent);
2407         },
2408         TaskExecutor::TaskType::UI);
2409     return true;
2410 }
2411 
ShowTimeDialog(const NWeb::DateTimeChooser & chooser,const std::vector<NWeb::DateTimeSuggestion> & suggestions,std::shared_ptr<NWeb::NWebDateTimeChooserCallback> callback)2412 bool WebPattern::ShowTimeDialog(const NWeb::DateTimeChooser& chooser,
2413     const std::vector<NWeb::DateTimeSuggestion>& suggestions,
2414     std::shared_ptr<NWeb::NWebDateTimeChooserCallback> callback)
2415 {
2416     auto container = Container::Current();
2417     CHECK_NULL_RETURN(container, false);
2418     auto pipelineContext = AccessibilityManager::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
2419     CHECK_NULL_RETURN(pipelineContext, false);
2420     auto executor = pipelineContext->GetTaskExecutor();
2421     CHECK_NULL_RETURN(executor, false);
2422     auto theme = pipelineContext->GetTheme<DialogTheme>();
2423     CHECK_NULL_RETURN(theme, false);
2424     auto context = AccessibilityManager::DynamicCast<NG::PipelineContext>(pipelineContext);
2425     auto overlayManager = context ? context->GetOverlayManager() : nullptr;
2426     CHECK_NULL_RETURN(overlayManager, false);
2427     NG::TimePickerSettingData settingData;
2428     settingData.isUseMilitaryTime = true;
2429     DialogProperties properties = GetDialogProperties(theme);
2430     std::map<std::string, PickerTime> timePickerProperty;
2431     timePickerProperty["start"] = PickerTime(chooser.minimum.hour, chooser.minimum.minute, chooser.minimum.second);
2432     timePickerProperty["selected"] = PickerTime(chooser.maximum.hour, chooser.maximum.minute, chooser.maximum.second);
2433     if (chooser.hasSelected) {
2434         timePickerProperty["selected"] =
2435             PickerTime(chooser.dialogValue.hour, chooser.dialogValue.minute, chooser.dialogValue.second);
2436     }
2437     std::map<std::string, NG::DialogEvent> dialogEvent;
2438     std::map<std::string, NG::DialogGestureEvent> dialogCancelEvent;
2439     auto acceptId = [callback](const std::string& info) {
2440         OHOS::NWeb::DateTime result;
2441         bool success = ParseDateTimeJson(info, result);
2442         callback->Continue(success, result);
2443     };
2444     dialogEvent["acceptId"] = acceptId;
2445     auto cancelId = [callback](const GestureEvent&) { callback->Continue(false, OHOS::NWeb::DateTime()); };
2446     dialogCancelEvent["cancelId"] = cancelId;
2447     overlayManager->RegisterOnHideDialog([callback] { callback->Continue(false, OHOS::NWeb::DateTime()); });
2448     executor->PostTask(
2449         [properties, settingData, timePickerProperty, dialogEvent, dialogCancelEvent,
2450             weak = WeakPtr<NG::OverlayManager>(overlayManager)] {
2451             auto overlayManager = weak.Upgrade();
2452             CHECK_NULL_VOID(overlayManager);
2453             overlayManager->ShowTimeDialog(properties, settingData, timePickerProperty, dialogEvent, dialogCancelEvent);
2454         },
2455         TaskExecutor::TaskType::UI);
2456     return true;
2457 }
2458 
ShowDateTimeSuggestionDialog(const NWeb::DateTimeChooser & chooser,const std::vector<NWeb::DateTimeSuggestion> & suggestions,std::shared_ptr<NWeb::NWebDateTimeChooserCallback> callback)2459 bool WebPattern::ShowDateTimeSuggestionDialog(const NWeb::DateTimeChooser& chooser,
2460     const std::vector<NWeb::DateTimeSuggestion>& suggestions,
2461     std::shared_ptr<NWeb::NWebDateTimeChooserCallback> callback)
2462 {
2463     auto container = Container::Current();
2464     CHECK_NULL_RETURN(container, false);
2465     auto pipelineContext = AccessibilityManager::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
2466     CHECK_NULL_RETURN(pipelineContext, false);
2467     auto executor = pipelineContext->GetTaskExecutor();
2468     CHECK_NULL_RETURN(executor, false);
2469     auto theme = pipelineContext->GetTheme<DialogTheme>();
2470     CHECK_NULL_RETURN(theme, false);
2471     auto context = AccessibilityManager::DynamicCast<NG::PipelineContext>(pipelineContext);
2472     auto overlayManager = context ? context->GetOverlayManager() : nullptr;
2473     CHECK_NULL_RETURN(overlayManager, false);
2474     NG::TextPickerSettingData settingData;
2475     if (memset_s(&settingData, sizeof(NG::TextPickerSettingData), 0, sizeof(NG::TextPickerSettingData)) != EOK) {
2476         return false;
2477     }
2478     std::map<std::string, OHOS::NWeb::DateTime> suggestionMap;
2479     for (size_t i = 0; i < suggestions.size(); i++) {
2480         settingData.rangeVector.push_back({ "", suggestions[i].localizedValue });
2481         settingData.values.push_back(suggestions[i].localizedValue);
2482         suggestionMap.emplace(std::make_pair(suggestions[i].localizedValue, suggestions[i].value));
2483     }
2484     settingData.columnKind = NG::TEXT;
2485     settingData.selected = chooser.suggestionIndex;
2486     DialogProperties properties = GetDialogProperties(theme);
2487     std::map<std::string, NG::DialogTextEvent> dialogEvent;
2488     std::map<std::string, NG::DialogGestureEvent> dialogCancelEvent;
2489     auto cancelId = [callback](const GestureEvent&) { callback->Continue(false, OHOS::NWeb::DateTime()); };
2490     auto acceptId = [suggestionMap, callback](const std::string& info) {
2491         std::string value = ParseTextJsonValue(info);
2492         if (suggestionMap.find(value) != suggestionMap.end()) {
2493             callback->Continue(true, suggestionMap.at(value));
2494         } else {
2495             callback->Continue(false, OHOS::NWeb::DateTime());
2496         }
2497     };
2498     dialogEvent["acceptId"] = acceptId;
2499     dialogCancelEvent["cancelId"] = cancelId;
2500     overlayManager->RegisterOnHideDialog([callback] { callback->Continue(false, OHOS::NWeb::DateTime()); });
2501     executor->PostTask(
2502         [properties, settingData, dialogEvent, dialogCancelEvent, weak = WeakPtr<NG::OverlayManager>(overlayManager)] {
2503             auto overlayManager = weak.Upgrade();
2504             CHECK_NULL_VOID(overlayManager);
2505             overlayManager->ShowTextDialog(properties, settingData, dialogEvent, dialogCancelEvent);
2506         },
2507         TaskExecutor::TaskType::UI);
2508     return true;
2509 }
2510 
OnDateTimeChooserClose()2511 void WebPattern::OnDateTimeChooserClose() {}
2512 
RegisterSelectPopupCallback(RefPtr<FrameNode> & menu,std::shared_ptr<OHOS::NWeb::NWebSelectPopupMenuCallback> callback,std::shared_ptr<OHOS::NWeb::NWebSelectPopupMenuParam> params)2513 void WebPattern::RegisterSelectPopupCallback(RefPtr<FrameNode>& menu,
2514     std::shared_ptr<OHOS::NWeb::NWebSelectPopupMenuCallback> callback,
2515     std::shared_ptr<OHOS::NWeb::NWebSelectPopupMenuParam> params)
2516 {
2517     auto pipeline = PipelineBase::GetCurrentContext();
2518     CHECK_NULL_VOID(pipeline);
2519     auto menuContainer = AceType::DynamicCast<FrameNode>(menu->GetChildAtIndex(0));
2520     CHECK_NULL_VOID(menuContainer);
2521     auto menuPattern = menuContainer->GetPattern<MenuPattern>();
2522     CHECK_NULL_VOID(menuPattern);
2523     auto options = menuPattern->GetOptions();
2524     for (auto&& option : options) {
2525         auto selectCallback = [callback](int32_t index) {
2526             std::vector<int32_t> indices { static_cast<int32_t>(index) };
2527             callback->Continue(indices);
2528         };
2529         auto optionNode = AceType::DynamicCast<FrameNode>(option);
2530         if (optionNode) {
2531             auto hub = optionNode->GetEventHub<OptionEventHub>();
2532             auto optionPattern = optionNode->GetPattern<OptionPattern>();
2533             if (!hub || !optionPattern) {
2534                 continue;
2535             }
2536             hub->SetOnSelect(std::move(selectCallback));
2537             optionPattern->SetFontSize(Dimension(params->itemFontSize * pipeline->GetDipScale()));
2538             optionNode->MarkModifyDone();
2539         }
2540     }
2541 }
2542 
GetSelectPopupPostion(const OHOS::NWeb::SelectMenuBound & bounds)2543 OffsetF WebPattern::GetSelectPopupPostion(const OHOS::NWeb::SelectMenuBound& bounds)
2544 {
2545     auto offset = GetCoordinatePoint().value_or(OffsetF());
2546     offset.AddX(bounds.x);
2547     offset.AddY(bounds.y + bounds.height);
2548     return offset;
2549 }
2550 
UpdateTouchHandleForOverlay()2551 void WebPattern::UpdateTouchHandleForOverlay()
2552 {
2553     WebOverlayType overlayType = GetTouchHandleOverlayType(insertHandle_, startSelectionHandle_, endSelectionHandle_);
2554     CHECK_NULL_VOID(selectOverlayProxy_);
2555     if (overlayType == INVALID_OVERLAY) {
2556         CloseSelectOverlay();
2557         return;
2558     }
2559     SelectHandleInfo firstHandleInfo;
2560     SelectHandleInfo secondHandleInfo;
2561     SelectMenuInfo menuInfo;
2562     if (overlayType == INSERT_OVERLAY) {
2563         firstHandleInfo.isShow = IsTouchHandleShow(insertHandle_);
2564         firstHandleInfo.paintRect = ComputeTouchHandleRect(insertHandle_);
2565         menuInfo.menuDisable = true;
2566         menuInfo.menuIsShow = false;
2567         selectOverlayProxy_->UpdateFirstSelectHandleInfo(firstHandleInfo);
2568         selectOverlayProxy_->UpdateSelectMenuInfo(menuInfo);
2569     } else {
2570         firstHandleInfo.isShow = IsTouchHandleShow(startSelectionHandle_);
2571         firstHandleInfo.paintRect = ComputeTouchHandleRect(startSelectionHandle_);
2572         secondHandleInfo.isShow = IsTouchHandleShow(endSelectionHandle_);
2573         secondHandleInfo.paintRect = ComputeTouchHandleRect(endSelectionHandle_);
2574         selectOverlayProxy_->UpdateFirstSelectHandleInfo(firstHandleInfo);
2575         selectOverlayProxy_->UpdateSecondSelectHandleInfo(secondHandleInfo);
2576         selectOverlayProxy_->UpdateSelectMenuInfo(selectMenuInfo_);
2577         selectOverlayProxy_->SetHandleReverse(false);
2578     }
2579 }
2580 
UpdateLocale()2581 void WebPattern::UpdateLocale()
2582 {
2583     CHECK_NULL_VOID(delegate_);
2584     delegate_->UpdateLocale();
2585 }
2586 
OnWindowShow()2587 void WebPattern::OnWindowShow()
2588 {
2589     if (isWindowShow_ || !isVisible_) {
2590         return;
2591     }
2592 
2593     CHECK_NULL_VOID(delegate_);
2594     delegate_->ShowWebView();
2595     isWindowShow_ = true;
2596 }
2597 
OnWindowHide()2598 void WebPattern::OnWindowHide()
2599 {
2600     if (!isWindowShow_ || !isVisible_) {
2601         return;
2602     }
2603 
2604     CHECK_NULL_VOID(delegate_);
2605     delegate_->HideWebView();
2606     needOnFocus_ = false;
2607     isWindowShow_ = false;
2608 }
2609 
OnWindowSizeChanged(int32_t width,int32_t height,WindowSizeChangeReason type)2610 void WebPattern::OnWindowSizeChanged(int32_t width, int32_t height, WindowSizeChangeReason type) {}
2611 
OnCompleteSwapWithNewSize()2612 void WebPattern::OnCompleteSwapWithNewSize()
2613 {
2614     if (!isInWindowDrag_ || !isWaiting_)
2615         return;
2616 
2617     ACE_SCOPED_TRACE("WebPattern::OnCompleteSwapWithNewSize");
2618     isWaiting_ = false;
2619 }
2620 
OnResizeNotWork()2621 void WebPattern::OnResizeNotWork()
2622 {
2623     if (!isInWindowDrag_ || !isWaiting_)
2624         return;
2625 
2626     ACE_SCOPED_TRACE("WebPattern::OnResizeNotWork");
2627     isWaiting_ = false;
2628 }
2629 
OnBackPressed() const2630 bool WebPattern::OnBackPressed() const
2631 {
2632     if (!isFullScreen_) {
2633         return false;
2634     }
2635 
2636     CHECK_NULL_RETURN(fullScreenExitHandler_, false);
2637     auto webFullScreenExitHandler = fullScreenExitHandler_->GetHandler();
2638     CHECK_NULL_RETURN(webFullScreenExitHandler, false);
2639     webFullScreenExitHandler->ExitFullScreen();
2640     return true;
2641 }
2642 
SetFullScreenExitHandler(const std::shared_ptr<FullScreenEnterEvent> & fullScreenExitHandler)2643 void WebPattern::SetFullScreenExitHandler(const std::shared_ptr<FullScreenEnterEvent>& fullScreenExitHandler)
2644 {
2645     fullScreenExitHandler_ = fullScreenExitHandler;
2646 }
2647 
OnInActive()2648 void WebPattern::OnInActive()
2649 {
2650     if (!isActive_) {
2651         return;
2652     }
2653 
2654     CHECK_NULL_VOID(delegate_);
2655     delegate_->OnInactive();
2656     isActive_ = false;
2657 }
2658 
OnActive()2659 void WebPattern::OnActive()
2660 {
2661     if (isActive_) {
2662         return;
2663     }
2664 
2665     CHECK_NULL_VOID(delegate_);
2666     delegate_->OnActive();
2667     isActive_ = true;
2668 }
2669 
OnVisibleChange(bool isVisible)2670 void WebPattern::OnVisibleChange(bool isVisible)
2671 {
2672     if (isVisible_ == isVisible) {
2673         return;
2674     }
2675 
2676     isVisible_ = isVisible;
2677     if (!isVisible_) {
2678         CloseSelectOverlay();
2679         if (isVisibleActiveEnable_) {
2680             OnInActive();
2681         }
2682     } else {
2683         if (isVisibleActiveEnable_) {
2684             OnActive();
2685         }
2686     }
2687 }
2688 
UpdateBackgroundColorRightNow(int32_t color)2689 void WebPattern::UpdateBackgroundColorRightNow(int32_t color)
2690 {
2691     auto host = GetHost();
2692     CHECK_NULL_VOID(host);
2693     auto renderContext = host->GetRenderContext();
2694     CHECK_NULL_VOID(renderContext);
2695     renderContext->UpdateBackgroundColor(Color(static_cast<uint32_t>(color)));
2696 }
2697 
OnNotifyMemoryLevel(int32_t level)2698 void WebPattern::OnNotifyMemoryLevel(int32_t level)
2699 {
2700     if (!isMemoryLevelEnable_) {
2701         return;
2702     }
2703     CHECK_NULL_VOID(delegate_);
2704     delegate_->NotifyMemoryLevel(level);
2705 }
2706 
GetWebId()2707 int WebPattern::GetWebId()
2708 {
2709     if (delegate_) {
2710         return delegate_->GetWebId();
2711     }
2712     return -1;
2713 }
2714 
HandleScroll(float offset,int32_t source,NestedState state)2715 ScrollResult WebPattern::HandleScroll(float offset, int32_t source, NestedState state)
2716 {
2717     auto parent = parent_.Upgrade();
2718     if (parent) {
2719         source = isMouseEvent_ ? SCROLL_FROM_AXIS : source;
2720         return parent->HandleScroll(offset, source, state);
2721     }
2722     return { 0.0f, false };
2723 }
2724 
HandleScrollVelocity(float velocity)2725 bool WebPattern::HandleScrollVelocity(float velocity)
2726 {
2727     auto parent = parent_.Upgrade();
2728     CHECK_NULL_RETURN(parent, false);
2729     if (InstanceOf<SwiperPattern>(parent)) {
2730         // When scrolling to the previous SwiperItem, that item needs to be visible. Update the offset slightly to make
2731         // it visible before calling HandleScrollVelocity.
2732         float tweak = (velocity > 0.0f) ? 1.0f : -1.0f;
2733         parent->HandleScroll(tweak, SCROLL_FROM_UPDATE, NestedState::CHILD_SCROLL);
2734     }
2735     if (parent->HandleScrollVelocity(velocity)) {
2736         return true;
2737     }
2738     return false;
2739 }
2740 
OnScrollStartRecursive(float position)2741 void WebPattern::OnScrollStartRecursive(float position)
2742 {
2743     TAG_LOGI(AceLogTag::ACE_WEB, "WebPattern::OnScrollStartRecursive");
2744     auto parent = parent_.Upgrade();
2745     if (parent) {
2746         parent->OnScrollStartRecursive(position);
2747     }
2748     isFirstFlingScrollVelocity_ = true;
2749 }
2750 
OnAttachToBuilderNode(NodeStatus nodeStatus)2751 void WebPattern::OnAttachToBuilderNode(NodeStatus nodeStatus)
2752 {
2753     if (nodeStatus != NodeStatus::NORMAL_NODE) {
2754         TAG_LOGI(AceLogTag::ACE_WEB, "Web offline mode type");
2755         isOfflineMode_ = true;
2756         OfflineMode();
2757     }
2758 }
2759 
OnScrollEndRecursive(const std::optional<float> & velocity)2760 void WebPattern::OnScrollEndRecursive(const std::optional<float>& velocity)
2761 {
2762     TAG_LOGI(AceLogTag::ACE_WEB, "WebPattern::OnScrollEndRecursive");
2763     auto parent = parent_.Upgrade();
2764     if (parent) {
2765         parent->OnScrollEndRecursive(std::nullopt);
2766     }
2767 }
2768 
OnOverScrollFlingVelocity(float xVelocity,float yVelocity,bool isFling)2769 void WebPattern::OnOverScrollFlingVelocity(float xVelocity, float yVelocity, bool isFling)
2770 {
2771     float velocity = GetAxis() == Axis::HORIZONTAL ? xVelocity : yVelocity;
2772     if (!isFling) {
2773         if (scrollState_ && ((velocity < 0 && nestedScrollBackwardMode_ == NestedScrollMode::SELF_FIRST) ||
2774                                 (velocity > 0 && nestedScrollForwardMode_ == NestedScrollMode::SELF_FIRST))) {
2775             HandleScroll(-velocity, SCROLL_FROM_UPDATE, NestedState::CHILD_SCROLL);
2776         }
2777     } else {
2778         if (((velocity > 0 && nestedScrollBackwardMode_ == NestedScrollMode::SELF_FIRST) ||
2779                 (velocity < 0 && nestedScrollForwardMode_ == NestedScrollMode::SELF_FIRST))) {
2780             if (isFirstFlingScrollVelocity_) {
2781                 HandleScrollVelocity(velocity);
2782                 isFirstFlingScrollVelocity_ = false;
2783             }
2784         }
2785     }
2786 }
2787 
OnScrollState(bool scrollState)2788 void WebPattern::OnScrollState(bool scrollState)
2789 {
2790     scrollState_ = scrollState;
2791     if (!scrollState) {
2792         OnScrollEndRecursive(std::nullopt);
2793     }
2794 }
2795 
GetParentAxis()2796 Axis WebPattern::GetParentAxis()
2797 {
2798     auto parent = WebSearchParent();
2799     parent_ = parent;
2800     CHECK_NULL_RETURN(parent, Axis::HORIZONTAL);
2801     axis_ = parent->GetAxis();
2802     return axis_;
2803 }
2804 
WebSearchParent()2805 RefPtr<NestableScrollContainer> WebPattern::WebSearchParent()
2806 {
2807     auto host = GetHost();
2808     CHECK_NULL_RETURN(host, nullptr);
2809     for (auto parent = host->GetParent(); parent != nullptr; parent = parent->GetParent()) {
2810         RefPtr<FrameNode> frameNode = AceType::DynamicCast<FrameNode>(parent);
2811         if (!frameNode) {
2812             continue;
2813         }
2814         auto pattern = frameNode->GetPattern<NestableScrollContainer>();
2815         if (!pattern) {
2816             continue;
2817         }
2818         return pattern;
2819     }
2820     return nullptr;
2821 }
2822 
OnRootLayerChanged(int width,int height)2823 void WebPattern::OnRootLayerChanged(int width, int height)
2824 {
2825     rootLayerWidth_ = width;
2826     rootLayerHeight_ = height;
2827     if (layoutMode_ == WebLayoutMode::FIT_CONTENT) {
2828         auto frameNode = GetHost();
2829         CHECK_NULL_VOID(frameNode);
2830         auto newRect = Size(width, height);
2831         drawSize_.SetSize(newRect);
2832         frameNode->MarkDirtyNode(PROPERTY_UPDATE_LAYOUT | PROPERTY_UPDATE_MEASURE_SELF_AND_PARENT);
2833         auto offset = Offset(GetCoordinatePoint()->GetX(), GetCoordinatePoint()->GetY());
2834         delegate_->SetBoundsOrResize(drawSize_, offset, false);
2835     }
2836 }
2837 
SetNestedScroll(const NestedScrollOptions & nestedOpt)2838 void WebPattern::SetNestedScroll(const NestedScrollOptions& nestedOpt)
2839 {
2840     nestedScrollForwardMode_ = nestedOpt.forward;
2841     nestedScrollBackwardMode_ = nestedOpt.backward;
2842 }
2843 
FilterScrollEvent(const float x,const float y,const float xVelocity,const float yVelocity)2844 bool WebPattern::FilterScrollEvent(const float x, const float y, const float xVelocity, const float yVelocity)
2845 {
2846     float offset = GetAxis() == Axis::HORIZONTAL ? x : y;
2847     float velocity = GetAxis() == Axis::HORIZONTAL ? xVelocity : yVelocity;
2848     if (((offset > 0 || velocity > 0) && nestedScrollBackwardMode_ == NestedScrollMode::PARENT_FIRST) ||
2849         ((offset < 0 || velocity < 0) && nestedScrollForwardMode_ == NestedScrollMode::PARENT_FIRST)) {
2850         if (offset != 0) {
2851             auto result = HandleScroll(offset, SCROLL_FROM_UPDATE, NestedState::CHILD_SCROLL);
2852             CHECK_NULL_RETURN(delegate_, false);
2853             GetAxis() == Axis::HORIZONTAL ? delegate_->ScrollBy(-result.remain, 0)
2854                                           : delegate_->ScrollBy(0, -result.remain);
2855             return true;
2856         } else {
2857             return HandleScrollVelocity(velocity);
2858         }
2859     } else if (((offset > 0 || velocity > 0) && nestedScrollBackwardMode_ == NestedScrollMode::PARALLEL) ||
2860                ((offset < 0 || velocity < 0) && nestedScrollForwardMode_ == NestedScrollMode::PARALLEL)) {
2861         if (offset != 0) {
2862             HandleScroll(offset, SCROLL_FROM_UPDATE, NestedState::CHILD_SCROLL);
2863         } else {
2864             HandleScrollVelocity(velocity);
2865         }
2866     }
2867     return false;
2868 }
2869 
SearchParent()2870 RefPtr<ScrollPattern> WebPattern::SearchParent()
2871 {
2872     auto host = GetHost();
2873     CHECK_NULL_RETURN(host, nullptr);
2874     if (isParentHasScroll_) {
2875         relativeOffsetOfScroll_.Reset();
2876     }
2877     relativeOffsetOfScroll_ += host->GetGeometryNode()->GetFrameOffset();
2878     for (auto parent = host->GetParent(); parent != nullptr; parent = parent->GetParent()) {
2879         RefPtr<FrameNode> frameNode = AceType::DynamicCast<FrameNode>(parent);
2880         if (!frameNode) {
2881             continue;
2882         }
2883         auto pattern = frameNode->GetPattern<ScrollPattern>();
2884         if (!pattern) {
2885             relativeOffsetOfScroll_ += frameNode->GetGeometryNode()->GetFrameOffset();
2886             continue;
2887         }
2888         isParentHasScroll_ = true;
2889         return pattern;
2890     }
2891     isParentHasScroll_ = false;
2892     return nullptr;
2893 }
2894 
InitScrollUpdateListener()2895 void WebPattern::InitScrollUpdateListener()
2896 {
2897     std::shared_ptr<ScrollUpdateListener> listener = std::make_shared<ScrollUpdateListener>();
2898     listener->SetPatternToListener(AceType::WeakClaim(this));
2899     auto pattern = SearchParent();
2900     CHECK_NULL_VOID(pattern);
2901     TAG_LOGI(AceLogTag::ACE_WEB, "WebPattern registerScrollUpdateListener");
2902     pattern->registerScrollUpdateListener(listener);
2903     axis_ = pattern->GetAxis();
2904 }
2905 
UpdateScrollOffset(SizeF frameSize)2906 void WebPattern::UpdateScrollOffset(SizeF frameSize)
2907 {
2908     if (isParentHasScroll_) {
2909         SearchParent();
2910         switch (axis_) {
2911             case Axis::HORIZONTAL:
2912                 CalculateHorizontalDrawRect(frameSize);
2913                 break;
2914             case Axis::VERTICAL:
2915                 CalculateVerticalDrawRect(frameSize);
2916                 break;
2917             default :
2918                 break;
2919         }
2920     }
2921 }
2922 
CalculateHorizontalDrawRect(SizeF frameSize)2923 void WebPattern::CalculateHorizontalDrawRect(SizeF frameSize) {}
2924 
CalculateVerticalDrawRect(SizeF frameSize)2925 void WebPattern::CalculateVerticalDrawRect(SizeF frameSize)
2926 {
2927     if (relativeOffsetOfScroll_.GetY() >= 0) {
2928         return;
2929     }
2930 
2931     int32_t stepGear = (-relativeOffsetOfScroll_.GetY()) / DEFAULT_WEB_DRAW_HEIGHT;
2932     if (stepGear >= static_cast<int32_t>(DEFAULT_HEIGHT_GEAR.size())) {
2933         TAG_LOGE(AceLogTag::ACE_WEB, "stepGear out of DEFAULT_HEIGHT_GEAR orign");
2934         return;
2935     }
2936     int32_t height = DEFAULT_HEIGHT_GEAR[stepGear];
2937     int32_t y = DEFAULT_ORIGN_GEAR[stepGear];
2938     CHECK_NULL_VOID(renderSurface_);
2939     renderSurface_->SetWebMessage({ 0, y });
2940 
2941     SetDrawRect(relativeOffsetOfScroll_.GetX(), -y, frameSize.Width(), height);
2942 }
2943 
PostTaskToUI(const std::function<void ()> && task) const2944 void WebPattern::PostTaskToUI(const std::function<void()>&& task) const
2945 {
2946     CHECK_NULL_VOID(task);
2947     auto container = Container::Current();
2948     CHECK_NULL_VOID(container);
2949     auto pipelineContext = AccessibilityManager::DynamicCast<NG::PipelineContext>(container->GetPipelineContext());
2950     CHECK_NULL_VOID(pipelineContext);
2951     auto taskExecutor = pipelineContext->GetTaskExecutor();
2952     CHECK_NULL_VOID(taskExecutor);
2953     taskExecutor->PostTask(task, TaskExecutor::TaskType::UI);
2954 }
2955 
SetDrawRect(int32_t x,int32_t y,int32_t width,int32_t height)2956 void WebPattern::SetDrawRect(int32_t x, int32_t y, int32_t width, int32_t height)
2957 {
2958     CHECK_NULL_VOID(delegate_);
2959     delegate_->SetDrawRect(x, -y, width, height);
2960 }
2961 
CreateNodePaintMethod()2962 RefPtr<NodePaintMethod> WebPattern::CreateNodePaintMethod()
2963 {
2964     auto paint = MakeRefPtr<WebPaintMethod>(renderSurface_);
2965     return paint;
2966 }
2967 
JavaScriptOnDocumentStart(const ScriptItems & scriptItems)2968 void WebPattern::JavaScriptOnDocumentStart(const ScriptItems& scriptItems)
2969 {
2970     onDocumentStartScriptItems_ = std::make_optional<ScriptItems>(scriptItems);
2971     if (delegate_) {
2972         UpdateJavaScriptOnDocumentStart();
2973         delegate_->JavaScriptOnDocumentStart();
2974     }
2975 }
2976 
JavaScriptOnDocumentEnd(const ScriptItems & scriptItems)2977 void WebPattern::JavaScriptOnDocumentEnd(const ScriptItems& scriptItems)
2978 {
2979     onDocumentEndScriptItems_ = std::make_optional<ScriptItems>(scriptItems);
2980     if (delegate_) {
2981         UpdateJavaScriptOnDocumentEnd();
2982         delegate_->JavaScriptOnDocumentEnd();
2983     }
2984 }
2985 
UpdateJavaScriptOnDocumentStart()2986 void WebPattern::UpdateJavaScriptOnDocumentStart()
2987 {
2988     if (delegate_ && onDocumentStartScriptItems_.has_value()) {
2989         delegate_->SetJavaScriptItems(onDocumentStartScriptItems_.value(), ScriptItemType::DOCUMENT_START);
2990         onDocumentStartScriptItems_ = std::nullopt;
2991     }
2992 }
2993 
UpdateJavaScriptOnDocumentEnd()2994 void WebPattern::UpdateJavaScriptOnDocumentEnd()
2995 {
2996     if (delegate_ && onDocumentEndScriptItems_.has_value()) {
2997         delegate_->SetJavaScriptItems(onDocumentEndScriptItems_.value(), ScriptItemType::DOCUMENT_END);
2998         onDocumentEndScriptItems_ = std::nullopt;
2999     }
3000 }
3001 
GetAccessibilityNodeById(int64_t accessibilityId)3002 RefPtr<WebAccessibilityNode> WebPattern::GetAccessibilityNodeById(int64_t accessibilityId)
3003 {
3004     CHECK_NULL_RETURN(delegate_, nullptr);
3005     CHECK_NULL_RETURN(webAccessibilityNode_, nullptr);
3006     auto& info = webAccessibilityNode_->GetAccessibilityNodeInfo();
3007     if (!delegate_->GetAccessibilityNodeInfoById(accessibilityId, info)) {
3008         return nullptr;
3009     }
3010     SetSelfAsParentOfWebCoreNode(info);
3011     return webAccessibilityNode_;
3012 }
3013 
GetFocusedAccessibilityNode(int64_t accessibilityId,bool isAccessibilityFocus)3014 RefPtr<WebAccessibilityNode> WebPattern::GetFocusedAccessibilityNode(int64_t accessibilityId, bool isAccessibilityFocus)
3015 {
3016     CHECK_NULL_RETURN(delegate_, nullptr);
3017     CHECK_NULL_RETURN(webAccessibilityNode_, nullptr);
3018     auto& info = webAccessibilityNode_->GetAccessibilityNodeInfo();
3019     if (!delegate_->GetFocusedAccessibilityNodeInfo(accessibilityId, isAccessibilityFocus, info)) {
3020         return nullptr;
3021     }
3022     SetSelfAsParentOfWebCoreNode(info);
3023     return webAccessibilityNode_;
3024 }
3025 
GetAccessibilityNodeByFocusMove(int64_t accessibilityId,int32_t direction)3026 RefPtr<WebAccessibilityNode> WebPattern::GetAccessibilityNodeByFocusMove(int64_t accessibilityId, int32_t direction)
3027 {
3028     CHECK_NULL_RETURN(delegate_, nullptr);
3029     CHECK_NULL_RETURN(webAccessibilityNode_, nullptr);
3030     auto& info = webAccessibilityNode_->GetAccessibilityNodeInfo();
3031     if (!delegate_->GetAccessibilityNodeInfoByFocusMove(accessibilityId, direction, info)) {
3032         return nullptr;
3033     }
3034     SetSelfAsParentOfWebCoreNode(info);
3035     return webAccessibilityNode_;
3036 }
3037 
3038 
ExecuteAction(int64_t accessibilityId,AceAction action) const3039 void WebPattern::ExecuteAction(int64_t accessibilityId, AceAction action) const
3040 {
3041     CHECK_NULL_VOID(delegate_);
3042     delegate_->ExecuteAction(accessibilityId, action);
3043 }
3044 
SetAccessibilityState(bool state)3045 void WebPattern::SetAccessibilityState(bool state)
3046 {
3047     CHECK_NULL_VOID(delegate_);
3048     if (accessibilityState_ != state) {
3049         accessibilityState_ = state;
3050         delegate_->SetAccessibilityState(state);
3051     }
3052 }
3053 
SetSelfAsParentOfWebCoreNode(NWeb::NWebAccessibilityNodeInfo & info) const3054 void WebPattern::SetSelfAsParentOfWebCoreNode(NWeb::NWebAccessibilityNodeInfo& info) const
3055 {
3056     auto host = GetHost();
3057     CHECK_NULL_VOID(host);
3058     if (info.parentId == -1) { // root node of web core
3059         info.parentId = host->GetAccessibilityId();
3060     }
3061 }
3062 
SetTouchEventInfo(const TouchEvent & touchEvent,TouchEventInfo & touchEventInfo)3063 void WebPattern::SetTouchEventInfo(const TouchEvent& touchEvent, TouchEventInfo& touchEventInfo)
3064 {
3065     auto host = GetHost();
3066     CHECK_NULL_VOID(host);
3067     auto offset = host->GetOffsetRelativeToWindow();
3068     touchEventInfo = touchEventInfo_;
3069     TouchLocationInfo changedInfo("onTouch", touchEvent.id);
3070     changedInfo.SetLocalLocation(Offset(touchEvent.x, touchEvent.y));
3071     changedInfo.SetGlobalLocation(Offset(touchEvent.x + offset.GetX(), touchEvent.y + offset.GetY()));
3072     changedInfo.SetScreenLocation(Offset(touchEvent.x + offset.GetX(), touchEvent.y + offset.GetY()));
3073     changedInfo.SetTouchType(touchEvent.type);
3074 
3075     touchEventInfo.AddChangedTouchLocationInfo(std::move(changedInfo));
3076 }
3077 } // namespace OHOS::Ace::NG
3078