1 /*
2  * Copyright (c) 2021-2022 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 "frameworks/bridge/plugin_frontend/plugin_frontend.h"
17 
18 #include "base/log/dump_log.h"
19 #include "base/log/event_report.h"
20 
21 namespace OHOS::Ace {
22 namespace {
23 /*
24  * NOTE:
25  * This function is needed to copy the values from BaseEventInfo
26  * It is observed, that the owner of BaseEventInfo will delete the pointer before it is ultimately
27  * processed by the EventMarker callback. In order to avoid this, a copy of all data needs to be made.
28  */
CopyEventInfo(const BaseEventInfo& info)29 std::shared_ptr<BaseEventInfo> CopyEventInfo(const BaseEventInfo& info)
30 {
31     const auto* touchInfo = TypeInfoHelper::DynamicCast<TouchEventInfo>(&info);
32     if (touchInfo != nullptr) {
33         return std::make_shared<TouchEventInfo>(*touchInfo);
34     }
35 
36     const auto* dragStartInfo = TypeInfoHelper::DynamicCast<DragStartInfo>(&info);
37     if (dragStartInfo != nullptr) {
38         return std::make_shared<DragStartInfo>(*dragStartInfo);
39     }
40 
41     const auto* dragUpdateInfo = TypeInfoHelper::DynamicCast<DragUpdateInfo>(&info);
42     if (dragUpdateInfo != nullptr) {
43         return std::make_shared<DragUpdateInfo>(*dragUpdateInfo);
44     }
45 
46     const auto* dragEndInfo = TypeInfoHelper::DynamicCast<DragEndInfo>(&info);
47     if (dragEndInfo != nullptr) {
48         return std::make_shared<DragEndInfo>(*dragEndInfo);
49     }
50 
51     const auto* clickInfo = TypeInfoHelper::DynamicCast<ClickInfo>(&info);
52     if (clickInfo != nullptr) {
53         return std::make_shared<ClickInfo>(*clickInfo);
54     }
55     return nullptr;
56 }
57 
TouchInfoToString(const BaseEventInfo& info, std::string& eventParam)58 void TouchInfoToString(const BaseEventInfo& info, std::string& eventParam)
59 {
60     eventParam.append("{\"touches\":[{");
61     const auto touchInfo = TypeInfoHelper::DynamicCast<TouchEventInfo>(&info);
62     if (touchInfo) {
63         auto touchList = touchInfo->GetTouches();
64         for (const auto& location : touchList) {
65             auto globalLocation = location.GetGlobalLocation();
66             eventParam.append("\"globalX\":")
67                 .append(std::to_string(globalLocation.GetX()))
68                 .append(",\"globalY\":")
69                 .append(std::to_string(globalLocation.GetY()))
70                 .append(",");
71             auto localLocation = location.GetLocalLocation();
72             eventParam.append("\"localX\":")
73                 .append(std::to_string(localLocation.GetX()))
74                 .append(",\"localY\":")
75                 .append(std::to_string(localLocation.GetY()))
76                 .append(",");
77             eventParam.append("\"size\":").append(std::to_string(location.GetSize())).append(",");
78         }
79         if (eventParam.back() == ',') {
80             eventParam.pop_back();
81         }
82         eventParam.append("}],\"changedTouches\":[{");
83         auto changeTouch = touchInfo->GetChangedTouches();
84         for (const auto& change : changeTouch) {
85             auto globalLocation = change.GetGlobalLocation();
86             eventParam.append("\"globalX\":")
87                 .append(std::to_string(globalLocation.GetX()))
88                 .append(",\"globalY\":")
89                 .append(std::to_string(globalLocation.GetY()))
90                 .append(",");
91             auto localLocation = change.GetLocalLocation();
92             eventParam.append("\"localX\":")
93                 .append(std::to_string(localLocation.GetX()))
94                 .append(",\"localY\":")
95                 .append(std::to_string(localLocation.GetY()))
96                 .append(",");
97             eventParam.append("\"size\":").append(std::to_string(change.GetSize())).append(",");
98         }
99         if (eventParam.back() == ',') {
100             eventParam.pop_back();
101         }
102     }
103     eventParam.append("}]}");
104 }
105 
MouseInfoToString(const BaseEventInfo& info, std::string& eventParam)106 void MouseInfoToString(const BaseEventInfo& info, std::string& eventParam)
107 {
108     const auto mouseInfo = TypeInfoHelper::DynamicCast<MouseEventInfo>(&info);
109     eventParam.append("{\"mouse\":{");
110     if (mouseInfo) {
111         auto globalMouse = mouseInfo->GetGlobalMouse();
112         eventParam.append("\"globalX\":")
113             .append(std::to_string(globalMouse.x))
114             .append(",\"globalY\":")
115             .append(std::to_string(globalMouse.y))
116             .append(",\"globalZ\":")
117             .append(std::to_string(globalMouse.z))
118             .append(",\"localX\":")
119             .append(std::to_string(globalMouse.x))
120             .append(",\"localY\":")
121             .append(std::to_string(globalMouse.y))
122             .append(",\"localZ\":")
123             .append(std::to_string(globalMouse.z))
124             .append(",\"deltaX\":")
125             .append(std::to_string(globalMouse.deltaX))
126             .append(",\"deltaY\":")
127             .append(std::to_string(globalMouse.deltaY))
128             .append(",\"deltaZ\":")
129             .append(std::to_string(globalMouse.deltaZ))
130             .append(",\"scrollX\":")
131             .append(std::to_string(globalMouse.scrollX))
132             .append(",\"scrollY\":")
133             .append(std::to_string(globalMouse.scrollY))
134             .append(",\"scrollZ\":")
135             .append(std::to_string(globalMouse.scrollZ))
136             .append(",\"action\":")
137             .append(std::to_string(static_cast<int32_t>(globalMouse.action)))
138             .append(",\"button\":")
139             .append(std::to_string(static_cast<int32_t>(globalMouse.button)))
140             .append(",\"pressedButtons\":")
141             .append(std::to_string(globalMouse.pressedButtons));
142     }
143     eventParam.append("}}");
144 }
145 
SwipeInfoToString(const BaseEventInfo& info, std::string& eventParam)146 void SwipeInfoToString(const BaseEventInfo& info, std::string& eventParam)
147 {
148     const auto& swipeInfo = TypeInfoHelper::DynamicCast<SwipeEventInfo>(&info);
149     CHECK_NULL_VOID(swipeInfo);
150     eventParam = swipeInfo->ToJsonParamInfo();
151 }
152 } // namespace
153 
154 PluginFrontend::~PluginFrontend() noexcept
155 {
156     Destroy();
157     TAG_LOGI(AceLogTag::ACE_PLUGIN_COMPONENT, "Plugin frontend destroyed");
158 }
159 
Destroy()160 void PluginFrontend::Destroy()
161 {
162     CHECK_RUN_ON(JS);
163     // To guarantee the jsEngine_ and delegate_ released in js thread
164     if (jsEngine_) {
165         jsEngine_->Destroy();
166         jsEngine_.Reset();
167     }
168     delegate_.Reset();
169     handler_.Reset();
170 }
171 
Initialize(FrontendType type, const RefPtr<TaskExecutor>& taskExecutor)172 bool PluginFrontend::Initialize(FrontendType type, const RefPtr<TaskExecutor>& taskExecutor)
173 {
174     type_ = type;
175     taskExecutor_ = taskExecutor;
176     ACE_DCHECK(type_ == FrontendType::JS_PLUGIN);
177     InitializeFrontendDelegate(taskExecutor);
178     taskExecutor->PostSyncTask(
179         [weakEngine = WeakPtr<Framework::JsEngine>(jsEngine_), delegate = delegate_] {
180             auto jsEngine = weakEngine.Upgrade();
181             CHECK_NULL_VOID(jsEngine);
182             jsEngine->Initialize(delegate);
183         },
184         TaskExecutor::TaskType::JS, "ArkUIPluginInitialize");
185 
186     return true;
187 }
188 
AttachPipelineContext(const RefPtr<PipelineBase>& context)189 void PluginFrontend::AttachPipelineContext(const RefPtr<PipelineBase>& context)
190 {
191     CHECK_NULL_VOID(delegate_);
192     handler_ = AceType::MakeRefPtr<PluginEventHandler>(delegate_);
193     auto pipelineContext = AceType::DynamicCast<PipelineContext>(context);
194     if (pipelineContext) {
195         pipelineContext->RegisterEventHandler(handler_);
196     }
197     delegate_->AttachPipelineContext(context);
198 }
199 
SetAssetManager(const RefPtr<AssetManager>& assetManager)200 void PluginFrontend::SetAssetManager(const RefPtr<AssetManager>& assetManager)
201 {
202     if (delegate_) {
203         delegate_->SetAssetManager(assetManager);
204     }
205 }
206 
InitializeFrontendDelegate(const RefPtr<TaskExecutor>& taskExecutor)207 void PluginFrontend::InitializeFrontendDelegate(const RefPtr<TaskExecutor>& taskExecutor)
208 {
209     const auto& loadCallback = [weakEngine = WeakPtr<Framework::JsEngine>(jsEngine_)](const std::string& url,
210                                    const RefPtr<Framework::JsAcePage>& jsPage, bool isMainPage) {
211         auto jsEngine = weakEngine.Upgrade();
212         CHECK_NULL_VOID(jsEngine);
213         jsEngine->LoadPluginComponent(url, jsPage, isMainPage);
214     };
215 
216     const auto& setPluginMessageTransferCallback = [weakEngine = WeakPtr<Framework::JsEngine>(jsEngine_)](
217                                                        const RefPtr<JsMessageDispatcher>& dispatcher) {
218         auto jsEngine = weakEngine.Upgrade();
219         CHECK_NULL_VOID(jsEngine);
220         jsEngine->SetJsMessageDispatcher(dispatcher);
221     };
222 
223     const auto& asyncEventCallback = [weakEngine = WeakPtr<Framework::JsEngine>(jsEngine_)](
224                                          const std::string& eventId, const std::string& param) {
225         auto jsEngine = weakEngine.Upgrade();
226         CHECK_NULL_VOID(jsEngine);
227         jsEngine->FireAsyncEvent(eventId, param);
228     };
229 
230     const auto& syncEventCallback = [weakEngine = WeakPtr<Framework::JsEngine>(jsEngine_)](
231                                         const std::string& eventId, const std::string& param) {
232         auto jsEngine = weakEngine.Upgrade();
233         CHECK_NULL_VOID(jsEngine);
234         jsEngine->FireSyncEvent(eventId, param);
235     };
236 
237     const auto& updatePageCallback = [weakEngine = WeakPtr<Framework::JsEngine>(jsEngine_)](
238                                          const RefPtr<Framework::JsAcePage>& jsPage) {
239         auto jsEngine = weakEngine.Upgrade();
240         CHECK_NULL_VOID(jsEngine);
241         jsEngine->UpdateRunningPage(jsPage);
242         jsEngine->UpdateStagingPage(jsPage);
243     };
244 
245     const auto& resetStagingPageCallback = [weakEngine = WeakPtr<Framework::JsEngine>(jsEngine_)]() {
246         auto jsEngine = weakEngine.Upgrade();
247         CHECK_NULL_VOID(jsEngine);
248         jsEngine->ResetStagingPage();
249     };
250 
251     const auto& destroyPageCallback = [weakEngine = WeakPtr<Framework::JsEngine>(jsEngine_)](int32_t pageId) {
252         auto jsEngine = weakEngine.Upgrade();
253         CHECK_NULL_VOID(jsEngine);
254         jsEngine->DestroyPageInstance(pageId);
255     };
256 
257     const auto& destroyApplicationCallback = [weakEngine = WeakPtr<Framework::JsEngine>(jsEngine_)](
258                                                  const std::string& packageName) {
259         auto jsEngine = weakEngine.Upgrade();
260         CHECK_NULL_VOID(jsEngine);
261         jsEngine->DestroyApplication(packageName);
262     };
263 
264     const auto& updateApplicationStateCallback = [weakEngine = WeakPtr<Framework::JsEngine>(jsEngine_)](
265                                                      const std::string& packageName, Frontend::State state) {
266         auto jsEngine = weakEngine.Upgrade();
267         CHECK_NULL_VOID(jsEngine);
268         jsEngine->UpdateApplicationState(packageName, state);
269     };
270 
271     const auto& onWindowDisplayModeChangedCallBack = [weakEngine = WeakPtr<Framework::JsEngine>(jsEngine_)](
272                                                          bool isShownInMultiWindow, const std::string& data) {
273         auto jsEngine = weakEngine.Upgrade();
274         CHECK_NULL_VOID(jsEngine);
275         jsEngine->OnWindowDisplayModeChanged(isShownInMultiWindow, data);
276     };
277 
278     const auto& onSaveAbilityStateCallBack = [weakEngine = WeakPtr<Framework::JsEngine>(jsEngine_)](std::string& data) {
279         auto jsEngine = weakEngine.Upgrade();
280         CHECK_NULL_VOID(jsEngine);
281         jsEngine->OnSaveAbilityState(data);
282     };
283     const auto& onRestoreAbilityStateCallBack = [weakEngine = WeakPtr<Framework::JsEngine>(jsEngine_)](
284                                                     const std::string& data) {
285         auto jsEngine = weakEngine.Upgrade();
286         CHECK_NULL_VOID(jsEngine);
287         jsEngine->OnRestoreAbilityState(data);
288     };
289 
290     const auto& onNewWantCallBack = [weakEngine = WeakPtr<Framework::JsEngine>(jsEngine_)](const std::string& data) {
291         auto jsEngine = weakEngine.Upgrade();
292         CHECK_NULL_VOID(jsEngine);
293         jsEngine->OnNewWant(data);
294     };
295     const auto& onActiveCallBack = [weakEngine = WeakPtr<Framework::JsEngine>(jsEngine_)]() {
296         auto jsEngine = weakEngine.Upgrade();
297         CHECK_NULL_VOID(jsEngine);
298         jsEngine->OnActive();
299     };
300 
301     const auto& onInactiveCallBack = [weakEngine = WeakPtr<Framework::JsEngine>(jsEngine_)]() {
302         auto jsEngine = weakEngine.Upgrade();
303         CHECK_NULL_VOID(jsEngine);
304         jsEngine->OnInactive();
305     };
306 
307     const auto& onConfigurationUpdatedCallBack = [weakEngine = WeakPtr<Framework::JsEngine>(jsEngine_)](
308                                                      const std::string& data) {
309         auto jsEngine = weakEngine.Upgrade();
310         CHECK_NULL_VOID(jsEngine);
311         jsEngine->OnConfigurationUpdated(data);
312     };
313 
314     const auto& timerCallback = [weakEngine = WeakPtr<Framework::JsEngine>(jsEngine_)](
315                                     const std::string& callbackId, const std::string& delay, bool isInterval) {
316         auto jsEngine = weakEngine.Upgrade();
317         CHECK_NULL_VOID(jsEngine);
318         jsEngine->TimerCallback(callbackId, delay, isInterval);
319     };
320 
321     const auto& mediaQueryCallback = [weakEngine = WeakPtr<Framework::JsEngine>(jsEngine_)](
322                                          const std::string& callbackId, const std::string& args) {
323         auto jsEngine = weakEngine.Upgrade();
324         CHECK_NULL_VOID(jsEngine);
325         jsEngine->MediaQueryCallback(callbackId, args);
326     };
327 
328     const auto& requestAnimationCallback = [weakEngine = WeakPtr<Framework::JsEngine>(jsEngine_)](
329                                                const std::string& callbackId, uint64_t timeStamp) {
330         auto jsEngine = weakEngine.Upgrade();
331         CHECK_NULL_VOID(jsEngine);
332         jsEngine->RequestAnimationCallback(callbackId, timeStamp);
333     };
334 
335     const auto& jsCallback = [weakEngine = WeakPtr<Framework::JsEngine>(jsEngine_)](
336                                  const std::string& callbackId, const std::string& args) {
337         auto jsEngine = weakEngine.Upgrade();
338         CHECK_NULL_VOID(jsEngine);
339         jsEngine->JsCallback(callbackId, args);
340     };
341 
342     const auto& onMemoryLevelCallBack = [weakEngine = WeakPtr<Framework::JsEngine>(jsEngine_)](const int32_t level) {
343         auto jsEngine = weakEngine.Upgrade();
344         CHECK_NULL_VOID(jsEngine);
345         jsEngine->OnMemoryLevel(level);
346     };
347 
348     const auto& onStartContinuationCallBack = [weakEngine = WeakPtr<Framework::JsEngine>(jsEngine_)]() -> bool {
349         auto jsEngine = weakEngine.Upgrade();
350         CHECK_NULL_RETURN(jsEngine, false);
351         return jsEngine->OnStartContinuation();
352     };
353     const auto& onCompleteContinuationCallBack = [weakEngine = WeakPtr<Framework::JsEngine>(jsEngine_)](int32_t code) {
354         auto jsEngine = weakEngine.Upgrade();
355         CHECK_NULL_VOID(jsEngine);
356         jsEngine->OnCompleteContinuation(code);
357     };
358     const auto& onRemoteTerminatedCallBack = [weakEngine = WeakPtr<Framework::JsEngine>(jsEngine_)]() {
359         auto jsEngine = weakEngine.Upgrade();
360         CHECK_NULL_VOID(jsEngine);
361         jsEngine->OnRemoteTerminated();
362     };
363     const auto& onSaveDataCallBack = [weakEngine = WeakPtr<Framework::JsEngine>(jsEngine_)](std::string& savedData) {
364         auto jsEngine = weakEngine.Upgrade();
365         CHECK_NULL_VOID(jsEngine);
366         jsEngine->OnSaveData(savedData);
367     };
368     const auto& onRestoreDataCallBack = [weakEngine = WeakPtr<Framework::JsEngine>(jsEngine_)](
369                                             const std::string& data) -> bool {
370         auto jsEngine = weakEngine.Upgrade();
371         CHECK_NULL_RETURN(jsEngine, false);
372         return jsEngine->OnRestoreData(data);
373     };
374     delegate_ = AceType::MakeRefPtr<Framework::PluginFrontendDelegate>(taskExecutor, loadCallback,
375         setPluginMessageTransferCallback, asyncEventCallback, syncEventCallback, updatePageCallback,
376         resetStagingPageCallback, destroyPageCallback, destroyApplicationCallback, updateApplicationStateCallback,
377         timerCallback, mediaQueryCallback, requestAnimationCallback, jsCallback, onWindowDisplayModeChangedCallBack,
378         onConfigurationUpdatedCallBack, onSaveAbilityStateCallBack, onRestoreAbilityStateCallBack, onNewWantCallBack,
379         onActiveCallBack, onInactiveCallBack, onMemoryLevelCallBack, onStartContinuationCallBack,
380         onCompleteContinuationCallBack, onRemoteTerminatedCallBack, onSaveDataCallBack, onRestoreDataCallBack);
381     if (disallowPopLastPage_) {
382         delegate_->DisallowPopLastPage();
383     }
384     if (jsEngine_) {
385         delegate_->SetGroupJsBridge(jsEngine_->GetGroupJsBridge());
386     } else {
387         LOGE("the js engine is nullptr");
388         EventReport::SendAppStartException(AppStartExcepType::JS_ENGINE_CREATE_ERR);
389     }
390 }
391 
RunPage(const std::string& url, const std::string& params)392 UIContentErrorCode PluginFrontend::RunPage(const std::string& url, const std::string& params)
393 {
394     // Not use this pageId from backend, manage it in PluginFrontendDelegate.
395     CHECK_NULL_RETURN(delegate_, UIContentErrorCode::NULL_POINTER);
396     return delegate_->RunPage(url, params);
397 }
398 
ReplacePage(const std::string& url, const std::string& params)399 void PluginFrontend::ReplacePage(const std::string& url, const std::string& params)
400 {
401     CHECK_NULL_VOID(delegate_);
402     delegate_->Replace(url, params);
403 }
404 
PushPage(const std::string& url, const std::string& params)405 void PluginFrontend::PushPage(const std::string& url, const std::string& params)
406 {
407     CHECK_NULL_VOID(delegate_);
408     delegate_->Push(url, params);
409 }
410 
411 // navigator component call router
NavigatePage(uint8_t type, const PageTarget& target, const std::string& params)412 void PluginFrontend::NavigatePage(uint8_t type, const PageTarget& target, const std::string& params)
413 {
414     CHECK_NULL_VOID(delegate_);
415     switch (static_cast<NavigatorType>(type)) {
416         case NavigatorType::PUSH:
417             delegate_->Push(target, params);
418             break;
419         case NavigatorType::REPLACE:
420             delegate_->Replace(target, params);
421             break;
422         case NavigatorType::BACK:
423             delegate_->BackWithTarget(target, params);
424             break;
425         default:
426             LOGE("Navigator type is invalid!");
427             delegate_->BackWithTarget(target, params);
428     }
429 }
430 
SendCallbackMessage(const std::string& callbackId, const std::string& data) const431 void PluginFrontend::SendCallbackMessage(const std::string& callbackId, const std::string& data) const
432 {
433     CHECK_NULL_VOID(delegate_);
434     delegate_->OnJSCallback(callbackId, data);
435 }
436 
SetJsMessageDispatcher(const RefPtr<JsMessageDispatcher>& dispatcher) const437 void PluginFrontend::SetJsMessageDispatcher(const RefPtr<JsMessageDispatcher>& dispatcher) const
438 {
439     CHECK_NULL_VOID(delegate_);
440     delegate_->SetJsMessageDispatcher(dispatcher);
441 }
442 
TransferComponentResponseData(int callbackId, int32_t code, std::vector<uint8_t>&& data) const443 void PluginFrontend::TransferComponentResponseData(int callbackId, int32_t code, std::vector<uint8_t>&& data) const
444 {
445     CHECK_NULL_VOID(delegate_);
446     delegate_->TransferComponentResponseData(callbackId, code, std::move(data));
447 }
448 
TransferJsResponseData(int callbackId, int32_t code, std::vector<uint8_t>&& data) const449 void PluginFrontend::TransferJsResponseData(int callbackId, int32_t code, std::vector<uint8_t>&& data) const
450 {
451     CHECK_NULL_VOID(delegate_);
452     delegate_->TransferJsResponseData(callbackId, code, std::move(data));
453 }
454 
455 #if defined(PREVIEW)
TransferJsResponseDataPreview(int callbackId, int32_t code, ResponseData responseData) const456 void PluginFrontend::TransferJsResponseDataPreview(int callbackId, int32_t code, ResponseData responseData) const
457 {
458     delegate_->TransferJsResponseDataPreview(callbackId, code, responseData);
459 }
460 #endif
461 
TransferJsPluginGetError(int callbackId, int32_t errorCode, std::string&& errorMessage) const462 void PluginFrontend::TransferJsPluginGetError(int callbackId, int32_t errorCode, std::string&& errorMessage) const
463 {
464     CHECK_NULL_VOID(delegate_);
465     delegate_->TransferJsPluginGetError(callbackId, errorCode, std::move(errorMessage));
466 }
467 
TransferJsEventData(int32_t callbackId, int32_t code, std::vector<uint8_t>&& data) const468 void PluginFrontend::TransferJsEventData(int32_t callbackId, int32_t code, std::vector<uint8_t>&& data) const
469 {
470     CHECK_NULL_VOID(delegate_);
471     delegate_->TransferJsEventData(callbackId, code, std::move(data));
472 }
473 
LoadPluginJsCode(std::string&& jsCode) const474 void PluginFrontend::LoadPluginJsCode(std::string&& jsCode) const
475 {
476     CHECK_NULL_VOID(delegate_);
477     delegate_->LoadPluginJsCode(std::move(jsCode));
478 }
479 
LoadPluginJsByteCode(std::vector<uint8_t>&& jsCode, std::vector<int32_t>&& jsCodeLen) const480 void PluginFrontend::LoadPluginJsByteCode(std::vector<uint8_t>&& jsCode, std::vector<int32_t>&& jsCodeLen) const
481 {
482     CHECK_NULL_VOID(delegate_);
483     delegate_->LoadPluginJsByteCode(std::move(jsCode), std::move(jsCodeLen));
484 }
485 
UpdateState(Frontend::State state)486 void PluginFrontend::UpdateState(Frontend::State state)
487 {
488     CHECK_NULL_VOID(delegate_);
489     switch (state) {
490         case Frontend::State::ON_CREATE:
491             break;
492         case Frontend::State::ON_SHOW:
493         case Frontend::State::ON_HIDE:
494             delegate_->UpdateApplicationState(delegate_->GetAppID(), state);
495             break;
496         case Frontend::State::ON_DESTROY:
497             delegate_->OnApplicationDestroy(delegate_->GetAppID());
498             break;
499         default:
500             LOGE("error State: %d", state);
501             break;
502     }
503 }
504 
OnWindowDisplayModeChanged(bool isShownInMultiWindow, const std::string& data)505 void PluginFrontend::OnWindowDisplayModeChanged(bool isShownInMultiWindow, const std::string& data)
506 {
507     CHECK_NULL_VOID(delegate_);
508     delegate_->OnWindowDisplayModeChanged(isShownInMultiWindow, data);
509 }
510 
OnSaveAbilityState(std::string& data)511 void PluginFrontend::OnSaveAbilityState(std::string& data)
512 {
513     CHECK_NULL_VOID(delegate_);
514     delegate_->OnSaveAbilityState(data);
515 }
516 
OnRestoreAbilityState(const std::string& data)517 void PluginFrontend::OnRestoreAbilityState(const std::string& data)
518 {
519     CHECK_NULL_VOID(delegate_);
520     delegate_->OnRestoreAbilityState(data);
521 }
522 
OnNewWant(const std::string& data)523 void PluginFrontend::OnNewWant(const std::string& data)
524 {
525     CHECK_NULL_VOID(delegate_);
526     delegate_->OnNewWant(data);
527 }
528 
GetAccessibilityManager() const529 RefPtr<AccessibilityManager> PluginFrontend::GetAccessibilityManager() const
530 {
531     CHECK_NULL_RETURN(delegate_, nullptr);
532     return delegate_->GetJSAccessibilityManager();
533 }
534 
GetWindowConfig()535 WindowConfig& PluginFrontend::GetWindowConfig()
536 {
537     if (!delegate_) {
538         static WindowConfig windowConfig;
539         LOGW("delegate is null, return default config");
540         return windowConfig;
541     }
542     return delegate_->GetWindowConfig();
543 }
544 
OnBackPressed()545 bool PluginFrontend::OnBackPressed()
546 {
547     CHECK_NULL_RETURN(delegate_, false);
548     return delegate_->OnPageBackPress();
549 }
550 
OnShow()551 void PluginFrontend::OnShow()
552 {
553     CHECK_NULL_VOID(delegate_);
554     delegate_->OnForeground();
555 }
556 
OnHide()557 void PluginFrontend::OnHide()
558 {
559     CHECK_NULL_VOID(delegate_);
560     delegate_->OnBackGround();
561     foregroundFrontend_ = false;
562 }
563 
OnConfigurationUpdated(const std::string& data)564 void PluginFrontend::OnConfigurationUpdated(const std::string& data)
565 {
566     CHECK_NULL_VOID(delegate_);
567     delegate_->OnConfigurationUpdated(data);
568 }
569 
OnActive()570 void PluginFrontend::OnActive()
571 {
572     CHECK_NULL_VOID(delegate_);
573     foregroundFrontend_ = true;
574     delegate_->OnActive();
575     delegate_->InitializeAccessibilityCallback();
576 }
577 
OnInactive()578 void PluginFrontend::OnInactive()
579 {
580     CHECK_NULL_VOID(delegate_);
581     delegate_->OnInactive();
582     delegate_->OnSuspended();
583 }
584 
OnStartContinuation()585 bool PluginFrontend::OnStartContinuation()
586 {
587     CHECK_NULL_RETURN(delegate_, false);
588     return delegate_->OnStartContinuation();
589 }
590 
OnCompleteContinuation(int32_t code)591 void PluginFrontend::OnCompleteContinuation(int32_t code)
592 {
593     CHECK_NULL_VOID(delegate_);
594     delegate_->OnCompleteContinuation(code);
595 }
596 
OnMemoryLevel(const int32_t level)597 void PluginFrontend::OnMemoryLevel(const int32_t level)
598 {
599     CHECK_NULL_VOID(delegate_);
600     delegate_->OnMemoryLevel(level);
601 }
602 
OnSaveData(std::string& data)603 void PluginFrontend::OnSaveData(std::string& data)
604 {
605     CHECK_NULL_VOID(delegate_);
606     delegate_->OnSaveData(data);
607 }
608 
GetPluginsUsed(std::string& data)609 void PluginFrontend::GetPluginsUsed(std::string& data)
610 {
611     CHECK_NULL_VOID(delegate_);
612     delegate_->GetPluginsUsed(data);
613 }
614 
OnRestoreData(const std::string& data)615 bool PluginFrontend::OnRestoreData(const std::string& data)
616 {
617     CHECK_NULL_RETURN(delegate_, false);
618     return delegate_->OnRestoreData(data);
619 }
620 
OnRemoteTerminated()621 void PluginFrontend::OnRemoteTerminated()
622 {
623     CHECK_NULL_VOID(delegate_);
624     delegate_->OnRemoteTerminated();
625 }
626 
OnNewRequest(const std::string& data)627 void PluginFrontend::OnNewRequest(const std::string& data)
628 {
629     CHECK_NULL_VOID(delegate_);
630     delegate_->OnNewRequest(data);
631 }
632 
CallRouterBack()633 void PluginFrontend::CallRouterBack()
634 {
635     CHECK_NULL_VOID(delegate_);
636     if (delegate_->GetStackSize() == 1 && isSubWindow_) {
637         LOGW("Can't back because this is the last page of sub window!");
638         return;
639     }
640     delegate_->CallPopPage();
641 }
642 
OnSurfaceChanged(int32_t width, int32_t height)643 void PluginFrontend::OnSurfaceChanged(int32_t width, int32_t height)
644 {
645     CHECK_NULL_VOID(delegate_);
646     delegate_->OnSurfaceChanged();
647 }
648 
OnLayoutCompleted(const std::string& componentId)649 void PluginFrontend::OnLayoutCompleted(const std::string& componentId)
650 {
651     CHECK_NULL_VOID(delegate_);
652 }
653 
OnDrawCompleted(const std::string& componentId)654 void PluginFrontend::OnDrawCompleted(const std::string& componentId)
655 {
656     CHECK_NULL_VOID(delegate_);
657 }
658 
DumpFrontend() const659 void PluginFrontend::DumpFrontend() const
660 {
661     CHECK_NULL_VOID(delegate_);
662     int32_t routerIndex = 0;
663     std::string routerName;
664     std::string routerPath;
665     delegate_->GetState(routerIndex, routerName, routerPath);
666 
667     if (DumpLog::GetInstance().GetDumpFile()) {
668         DumpLog::GetInstance().AddDesc("Components: " + std::to_string(delegate_->GetComponentsCount()));
669         DumpLog::GetInstance().AddDesc("Path: " + routerPath);
670         DumpLog::GetInstance().AddDesc("Length: " + std::to_string(routerIndex));
671         DumpLog::GetInstance().Print(0, routerName, 0);
672     }
673 }
674 
GetPagePath() const675 std::string PluginFrontend::GetPagePath() const
676 {
677     CHECK_NULL_RETURN(delegate_, "");
678     int32_t routerIndex = 0;
679     std::string routerName;
680     std::string routerPath;
681     delegate_->GetState(routerIndex, routerName, routerPath);
682     return routerPath + routerName;
683 }
684 
TriggerGarbageCollection()685 void PluginFrontend::TriggerGarbageCollection()
686 {
687     CHECK_NULL_VOID(delegate_);
688     jsEngine_->RunGarbageCollection();
689 }
690 
SetColorMode(ColorMode colorMode)691 void PluginFrontend::SetColorMode(ColorMode colorMode)
692 {
693     CHECK_NULL_VOID(delegate_);
694     delegate_->SetColorMode(colorMode);
695 }
696 
RebuildAllPages()697 void PluginFrontend::RebuildAllPages()
698 {
699     CHECK_NULL_VOID(delegate_);
700     delegate_->RebuildAllPages();
701 }
702 
NotifyAppStorage(const std::string& key, const std::string& value)703 void PluginFrontend::NotifyAppStorage(const std::string& key, const std::string& value)
704 {
705     CHECK_NULL_VOID(delegate_);
706     delegate_->NotifyAppStorage(jsEngine_, key, value);
707 }
708 
UpdatePlugin(const std::string& content)709 void PluginFrontend::UpdatePlugin(const std::string& content)
710 {
711     CHECK_NULL_VOID(delegate_);
712     delegate_->UpdatePlugin(content);
713 }
714 
HandleAsyncEvent(const EventMarker& eventMarker)715 void PluginEventHandler::HandleAsyncEvent(const EventMarker& eventMarker)
716 {
717     std::string param = eventMarker.GetData().GetEventParam();
718     if (eventMarker.GetData().isDeclarativeUi) {
719         if (delegate_) {
720             delegate_->GetUiTask().PostTask(
721                 [eventMarker] { eventMarker.CallUiFunction(); }, "ArkUIPluginCallUiFunction");
722         }
723     } else {
724         delegate_->FireAsyncEvent(eventMarker.GetData().eventId, param.append("null"), std::string(""));
725     }
726 
727     AccessibilityEvent accessibilityEvent;
728     accessibilityEvent.nodeId = StringUtils::StringToInt(eventMarker.GetData().eventId);
729     accessibilityEvent.eventType = eventMarker.GetData().eventType;
730     delegate_->FireAccessibilityEvent(accessibilityEvent);
731 }
732 
HandleAsyncEvent(const EventMarker& eventMarker, const BaseEventInfo& info)733 void PluginEventHandler::HandleAsyncEvent(const EventMarker& eventMarker, const BaseEventInfo& info)
734 {
735     std::string eventParam;
736     if (eventMarker.GetData().eventType.find("touch") != std::string::npos) {
737         TouchInfoToString(info, eventParam);
738     } else if (eventMarker.GetData().eventType.find("mouse") != std::string::npos) {
739         MouseInfoToString(info, eventParam);
740     } else if (eventMarker.GetData().eventType == "swipe") {
741         SwipeInfoToString(info, eventParam);
742     }
743 
744     std::string param = eventMarker.GetData().GetEventParam();
745     if (eventParam.empty()) {
746         param.append("null");
747     } else {
748         param.append(eventParam);
749     }
750 
751     if (eventMarker.GetData().isDeclarativeUi) {
752         if (delegate_) {
753             auto cinfo = CopyEventInfo(info);
754             delegate_->GetUiTask().PostTask(
755                 [eventMarker, cinfo] { eventMarker.CallUiArgFunction(cinfo.get()); }, "ArkUIPluginCallUiArgFunction");
756         }
757     } else {
758         delegate_->FireAsyncEvent(eventMarker.GetData().eventId, param, "");
759     }
760 
761     AccessibilityEvent accessibilityEvent;
762     accessibilityEvent.nodeId = StringUtils::StringToInt(eventMarker.GetData().eventId);
763     accessibilityEvent.eventType = eventMarker.GetData().eventType;
764     delegate_->FireAccessibilityEvent(accessibilityEvent);
765 }
766 
HandleAsyncEvent(const EventMarker& eventMarker, const std::shared_ptr<BaseEventInfo>& info)767 void PluginEventHandler::HandleAsyncEvent(const EventMarker& eventMarker, const std::shared_ptr<BaseEventInfo>& info)
768 {
769     if (eventMarker.GetData().isDeclarativeUi) {
770         if (delegate_) {
771             delegate_->GetUiTask().PostTask(
772                 [eventMarker, info] { eventMarker.CallUiArgFunction(info.get()); }, "ArkUIPluginCallUiArgFunction");
773         }
774     }
775 }
776 
HandleSyncEvent(const EventMarker& eventMarker, const KeyEvent& info, bool& result)777 void PluginEventHandler::HandleSyncEvent(const EventMarker& eventMarker, const KeyEvent& info, bool& result)
778 {
779     std::string param = std::string("\"")
780                             .append(eventMarker.GetData().eventType)
781                             .append("\",{\"code\":")
782                             .append(std::to_string(static_cast<int32_t>(info.code)))
783                             .append(",\"action\":")
784                             .append(std::to_string(static_cast<int32_t>(info.action)))
785                             .append(",\"repeatCount\":")
786                             .append(std::to_string(static_cast<int32_t>(info.repeatTime)))
787                             .append(",\"timestamp\":")
788                             .append(std::to_string(static_cast<int32_t>(info.timeStamp.time_since_epoch().count())))
789                             .append(",\"key\":\"")
790                             .append(info.key)
791                             .append("\"},");
792 
793     result = delegate_->FireSyncEvent(eventMarker.GetData().eventId, param, "");
794 
795     AccessibilityEvent accessibilityEvent;
796     accessibilityEvent.nodeId = StringUtils::StringToInt(eventMarker.GetData().eventId);
797     accessibilityEvent.eventType = std::to_string(static_cast<int32_t>(info.code));
798     delegate_->FireAccessibilityEvent(accessibilityEvent);
799 }
800 
HandleAsyncEvent(const EventMarker& eventMarker, int32_t param)801 void PluginEventHandler::HandleAsyncEvent(const EventMarker& eventMarker, int32_t param)
802 {
803     LOGW("js event handler does not support this event type!");
804     AccessibilityEvent accessibilityEvent;
805     accessibilityEvent.nodeId = StringUtils::StringToInt(eventMarker.GetData().eventId);
806     accessibilityEvent.eventType = eventMarker.GetData().eventType;
807     delegate_->FireAccessibilityEvent(accessibilityEvent);
808 }
809 
HandleAsyncEvent(const EventMarker& eventMarker, const KeyEvent& info)810 void PluginEventHandler::HandleAsyncEvent(const EventMarker& eventMarker, const KeyEvent& info)
811 {
812     LOGW("js event handler does not support this event type!");
813     AccessibilityEvent accessibilityEvent;
814     accessibilityEvent.nodeId = StringUtils::StringToInt(eventMarker.GetData().eventId);
815     accessibilityEvent.eventType = eventMarker.GetData().eventType;
816     delegate_->FireAccessibilityEvent(accessibilityEvent);
817 }
818 
HandleAsyncEvent(const EventMarker& eventMarker, const std::string& param)819 void PluginEventHandler::HandleAsyncEvent(const EventMarker& eventMarker, const std::string& param)
820 {
821     if (eventMarker.GetData().isDeclarativeUi) {
822         std::string fixParam(param);
823         std::string::size_type startPos = param.find_first_of("{");
824         std::string::size_type endPos = param.find_last_of("}");
825         if (startPos != std::string::npos && endPos != std::string::npos && startPos < endPos) {
826             fixParam = fixParam.substr(startPos, endPos - startPos + 1);
827         }
828         if (delegate_) {
829             delegate_->GetUiTask().PostTask(
830                 [eventMarker, fixParam] { eventMarker.CallUiStrFunction(fixParam); }, "ArkUIPluginCallUiStrFunction");
831         }
832     } else {
833         delegate_->FireAsyncEvent(eventMarker.GetData().eventId, param, "");
834     }
835 
836     AccessibilityEvent accessibilityEvent;
837     accessibilityEvent.nodeId = StringUtils::StringToInt(eventMarker.GetData().eventId);
838     accessibilityEvent.eventType = eventMarker.GetData().eventType;
839     delegate_->FireAccessibilityEvent(accessibilityEvent);
840 }
841 
HandleSyncEvent(const EventMarker& eventMarker, bool& result)842 void PluginEventHandler::HandleSyncEvent(const EventMarker& eventMarker, bool& result)
843 {
844     LOGW("js event handler does not support this event type!");
845     AccessibilityEvent accessibilityEvent;
846     accessibilityEvent.nodeId = StringUtils::StringToInt(eventMarker.GetData().eventId);
847     accessibilityEvent.eventType = eventMarker.GetData().eventType;
848     delegate_->FireAccessibilityEvent(accessibilityEvent);
849 }
850 
HandleSyncEvent(const EventMarker& eventMarker, const std::shared_ptr<BaseEventInfo>& info)851 void PluginEventHandler::HandleSyncEvent(const EventMarker& eventMarker, const std::shared_ptr<BaseEventInfo>& info)
852 {
853     CHECK_NULL_VOID(delegate_);
854     delegate_->GetUiTask().PostSyncTask(
855         [eventMarker, info] { eventMarker.CallUiArgFunction(info.get()); }, "ArkUIPluginCallUiArgFunction");
856 }
857 
HandleSyncEvent(const EventMarker& eventMarker, const BaseEventInfo& info, bool& result)858 void PluginEventHandler::HandleSyncEvent(const EventMarker& eventMarker, const BaseEventInfo& info, bool& result)
859 {
860     LOGW("js event handler does not support this event type!");
861     AccessibilityEvent accessibilityEvent;
862     accessibilityEvent.nodeId = StringUtils::StringToInt(eventMarker.GetData().eventId);
863     accessibilityEvent.eventType = eventMarker.GetData().eventType;
864     delegate_->FireAccessibilityEvent(accessibilityEvent);
865 }
866 
HandleSyncEvent(const EventMarker& eventMarker, const std::string& param, std::string& result)867 void PluginEventHandler::HandleSyncEvent(const EventMarker& eventMarker, const std::string& param, std::string& result)
868 {
869     LOGW("js event handler does not support this event type!");
870     AccessibilityEvent accessibilityEvent;
871     accessibilityEvent.nodeId = StringUtils::StringToInt(eventMarker.GetData().eventId);
872     accessibilityEvent.eventType = eventMarker.GetData().eventType;
873     delegate_->FireAccessibilityEvent(accessibilityEvent);
874     delegate_->FireSyncEvent(eventMarker.GetData().eventId, param, std::string(""), result);
875 }
876 
HandleSyncEvent( const EventMarker& eventMarker, const std::string& componentId, const int32_t nodeId, const bool isDestroy)877 void PluginEventHandler::HandleSyncEvent(
878     const EventMarker& eventMarker, const std::string& componentId, const int32_t nodeId, const bool isDestroy)
879 {
880     LOGW("js event handler does not support this event type!");
881 }
882 } // namespace OHOS::Ace
883