• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "frameworks/bridge/declarative_frontend/ng/frontend_delegate_declarative_ng.h"
17 
18 #include "base/i18n/localization.h"
19 #include "base/log/ace_trace.h"
20 #include "base/log/event_report.h"
21 #include "base/resource/ace_res_config.h"
22 #include "base/subwindow/subwindow_manager.h"
23 #include "base/thread/background_task_executor.h"
24 #include "base/utils/measure_util.h"
25 #include "base/utils/utils.h"
26 #include "core/common/ace_application_info.h"
27 #include "core/common/container.h"
28 #include "core/common/thread_checker.h"
29 #include "core/components_ng/base/view_stack_model.h"
30 #include "core/components_ng/pattern/overlay/overlay_manager.h"
31 #include "core/components_ng/pattern/stage/page_pattern.h"
32 #include "core/components_ng/render/adapter/component_snapshot.h"
33 #include "core/pipeline_ng/pipeline_context.h"
34 #include "frameworks/bridge/common/utils/utils.h"
35 #include "frameworks/core/common/ace_engine.h"
36 
37 namespace OHOS::Ace::Framework {
38 
39 namespace {
40 
41 const char MANIFEST_JSON[] = "manifest.json";
42 const char PAGES_JSON[] = "main_pages.json";
43 constexpr int32_t TOAST_TIME_MAX = 10000;    // ms
44 constexpr int32_t TOAST_TIME_DEFAULT = 1500; // ms
45 constexpr int32_t CALLBACK_ERRORCODE_CANCEL = 1;
46 constexpr int32_t CALLBACK_DATACODE_ZERO = 0;
47 
48 // helper function to run OverlayManager task
49 // ensures that the task runs in subwindow instead of main Window
MainWindowOverlay(std::function<void (RefPtr<NG::OverlayManager>)> && task,const std::string & name)50 void MainWindowOverlay(std::function<void(RefPtr<NG::OverlayManager>)>&& task, const std::string& name)
51 {
52     auto currentId = Container::CurrentId();
53     ContainerScope scope(currentId);
54     auto context = NG::PipelineContext::GetCurrentContext();
55     CHECK_NULL_VOID(context);
56     auto overlayManager = context->GetOverlayManager();
57     context->GetTaskExecutor()->PostTask(
58         [task = std::move(task), weak = WeakPtr<NG::OverlayManager>(overlayManager)] {
59             auto overlayManager = weak.Upgrade();
60             task(overlayManager);
61         },
62         TaskExecutor::TaskType::UI, name);
63 }
64 } // namespace
65 
FrontendDelegateDeclarativeNG(const RefPtr<TaskExecutor> & taskExecutor)66 FrontendDelegateDeclarativeNG::FrontendDelegateDeclarativeNG(const RefPtr<TaskExecutor>& taskExecutor)
67     : taskExecutor_(taskExecutor), manifestParser_(AceType::MakeRefPtr<Framework::ManifestParser>()),
68       mediaQueryInfo_(AceType::MakeRefPtr<MediaQueryInfo>()),
69       jsAccessibilityManager_(AccessibilityNodeManager::Create())
70 {}
71 
SetMediaQueryCallback(MediaQueryCallback && mediaQueryCallback)72 void FrontendDelegateDeclarativeNG::SetMediaQueryCallback(MediaQueryCallback&& mediaQueryCallback)
73 {
74     mediaQueryCallback_ = mediaQueryCallback;
75 }
76 
SetLayoutInspectorCallback(const LayoutInspectorCallback & layoutInspectorCallback)77 void FrontendDelegateDeclarativeNG::SetLayoutInspectorCallback(const LayoutInspectorCallback& layoutInspectorCallback)
78 {
79     layoutInspectorCallback_ = layoutInspectorCallback;
80 }
81 
SetDrawInspectorCallback(const DrawInspectorCallback & drawInspectorCallback)82 void FrontendDelegateDeclarativeNG::SetDrawInspectorCallback(const DrawInspectorCallback& drawInspectorCallback)
83 {
84     drawInspectorCallback_ = drawInspectorCallback;
85 }
86 
SetOnStartContinuationCallBack(OnStartContinuationCallBack && onStartContinuationCallBack)87 void FrontendDelegateDeclarativeNG::SetOnStartContinuationCallBack(
88     OnStartContinuationCallBack&& onStartContinuationCallBack)
89 {
90     onStartContinuationCallBack_ = onStartContinuationCallBack;
91 }
92 
SetOnCompleteContinuationCallBack(OnCompleteContinuationCallBack && onCompleteContinuationCallBack)93 void FrontendDelegateDeclarativeNG::SetOnCompleteContinuationCallBack(
94     OnCompleteContinuationCallBack&& onCompleteContinuationCallBack)
95 {
96     onCompleteContinuationCallBack_ = onCompleteContinuationCallBack;
97 }
98 
SetOnSaveDataCallBack(OnSaveDataCallBack && onSaveDataCallBack)99 void FrontendDelegateDeclarativeNG::SetOnSaveDataCallBack(OnSaveDataCallBack&& onSaveDataCallBack)
100 {
101     onSaveDataCallBack_ = onSaveDataCallBack;
102 }
103 
SetOnRemoteTerminatedCallBack(OnRemoteTerminatedCallBack && onRemoteTerminatedCallBack)104 void FrontendDelegateDeclarativeNG::SetOnRemoteTerminatedCallBack(
105     OnRemoteTerminatedCallBack&& onRemoteTerminatedCallBack)
106 {
107     onRemoteTerminatedCallBack_ = onRemoteTerminatedCallBack;
108 }
109 
SetOnRestoreDataCallBack(OnRestoreDataCallBack && onRestoreDataCallBack)110 void FrontendDelegateDeclarativeNG::SetOnRestoreDataCallBack(OnRestoreDataCallBack&& onRestoreDataCallBack)
111 {
112     onRestoreDataCallBack_ = onRestoreDataCallBack;
113 }
114 
SetDestroyApplicationCallback(DestroyApplicationCallback && destroyApplicationCallback)115 void FrontendDelegateDeclarativeNG::SetDestroyApplicationCallback(
116     DestroyApplicationCallback&& destroyApplicationCallback)
117 {
118     destroyApplication_ = destroyApplicationCallback;
119 }
120 
SetUpdateApplicationStateCallback(UpdateApplicationStateCallback && updateApplicationStateCallback)121 void FrontendDelegateDeclarativeNG::SetUpdateApplicationStateCallback(
122     UpdateApplicationStateCallback&& updateApplicationStateCallback)
123 {
124     updateApplicationState_ = updateApplicationStateCallback;
125 }
126 
SetOnWindowDisplayModeChangedCallback(OnWindowDisplayModeChangedCallBack && onWindowDisplayModeChangedCallBack)127 void FrontendDelegateDeclarativeNG::SetOnWindowDisplayModeChangedCallback(
128     OnWindowDisplayModeChangedCallBack&& onWindowDisplayModeChangedCallBack)
129 {
130     onWindowDisplayModeChanged_ = onWindowDisplayModeChangedCallBack;
131 }
132 
SetExternalEventCallback(ExternalEventCallback && externalEventCallback)133 void FrontendDelegateDeclarativeNG::SetExternalEventCallback(ExternalEventCallback&& externalEventCallback)
134 {
135     externalEvent_ = externalEventCallback;
136 }
137 
SetTimerCallback(TimerCallback && timerCallback)138 void FrontendDelegateDeclarativeNG::SetTimerCallback(TimerCallback&& timerCallback)
139 {
140     timer_ = timerCallback;
141 }
142 
AttachPipelineContext(const RefPtr<PipelineBase> & context)143 void FrontendDelegateDeclarativeNG::AttachPipelineContext(const RefPtr<PipelineBase>& context)
144 {
145     if (!context) {
146         return;
147     }
148     context->SetOnPageShow([weak = AceType::WeakClaim(this)] {
149         auto delegate = weak.Upgrade();
150         if (delegate) {
151             delegate->OnPageShow();
152         }
153     });
154 
155     pipelineContextHolder_.Attach(context);
156     jsAccessibilityManager_->SetPipelineContext(context);
157     jsAccessibilityManager_->InitializeCallback();
158 }
159 
AttachSubPipelineContext(const RefPtr<PipelineBase> & context)160 void FrontendDelegateDeclarativeNG::AttachSubPipelineContext(const RefPtr<PipelineBase>& context)
161 {
162     if (!context) {
163         return;
164     }
165     jsAccessibilityManager_->AddSubPipelineContext(context);
166     jsAccessibilityManager_->RegisterSubWindowInteractionOperation(context->GetWindowId());
167 }
168 
RunPage(const std::string & url,const std::string & params,const std::string & profile)169 void FrontendDelegateDeclarativeNG::RunPage(
170     const std::string& url, const std::string& params, const std::string& profile)
171 {
172     ACE_SCOPED_TRACE("FrontendDelegateDeclarativeNG::RunPage");
173 
174     LOGI("Frontend delegate declarative run page, url=%{public}s", url.c_str());
175     std::string jsonContent;
176     if (GetAssetContent(MANIFEST_JSON, jsonContent)) {
177         manifestParser_->Parse(jsonContent);
178         manifestParser_->Printer();
179     } else if (!profile.empty() && GetAssetContent(profile, jsonContent)) {
180         manifestParser_->Parse(jsonContent);
181     } else if (GetAssetContent(PAGES_JSON, jsonContent)) {
182         manifestParser_->Parse(jsonContent);
183     }
184     std::string mainPagePath;
185     if (!url.empty()) {
186         mainPagePath = manifestParser_->GetRouter()->GetPagePath(url);
187     } else {
188         mainPagePath = manifestParser_->GetRouter()->GetEntry();
189     }
190     taskExecutor_->PostTask(
191         [manifestParser = manifestParser_, delegate = Claim(this),
192             weakPtr = WeakPtr<NG::PageRouterManager>(pageRouterManager_), url, params]() {
193             auto pageRouterManager = weakPtr.Upgrade();
194             CHECK_NULL_VOID(pageRouterManager);
195             pageRouterManager->SetManifestParser(manifestParser);
196             pageRouterManager->RunPage(url, params);
197             auto pipeline = delegate->GetPipelineContext();
198             // TODO: get platform version from context, and should stored in AceApplicationInfo.
199             if (manifestParser->GetMinPlatformVersion() > 0) {
200                 pipeline->SetMinPlatformVersion(manifestParser->GetMinPlatformVersion());
201             }
202         },
203         TaskExecutor::TaskType::JS, "ArkUIRunPageUrl");
204 }
205 
RunPage(const std::shared_ptr<std::vector<uint8_t>> & content,const std::string & params,const std::string & profile)206 void FrontendDelegateDeclarativeNG::RunPage(
207     const std::shared_ptr<std::vector<uint8_t>>& content, const std::string& params, const std::string& profile)
208 {
209     ACE_SCOPED_TRACE("FrontendDelegateDeclarativeNG::RunPage %zu", content->size());
210     taskExecutor_->PostTask(
211         [delegate = Claim(this), weakPtr = WeakPtr<NG::PageRouterManager>(pageRouterManager_), content, params]() {
212             auto pageRouterManager = weakPtr.Upgrade();
213             CHECK_NULL_VOID(pageRouterManager);
214             pageRouterManager->RunPage(content, params);
215             auto pipeline = delegate->GetPipelineContext();
216         },
217         TaskExecutor::TaskType::JS, "ArkUIRunPageContent");
218 }
219 
OnConfigurationUpdated(const std::string & data)220 void FrontendDelegateDeclarativeNG::OnConfigurationUpdated(const std::string& data)
221 {
222     // only support mediaQueryUpdate
223     OnMediaQueryUpdate();
224 }
225 
OnStartContinuation()226 bool FrontendDelegateDeclarativeNG::OnStartContinuation()
227 {
228     bool ret = false;
229     taskExecutor_->PostSyncTask(
230         [weak = AceType::WeakClaim(this), &ret] {
231             auto delegate = weak.Upgrade();
232             if (delegate && delegate->onStartContinuationCallBack_) {
233                 ret = delegate->onStartContinuationCallBack_();
234             }
235         },
236         TaskExecutor::TaskType::JS, "ArkUIStartContinuation");
237     return ret;
238 }
239 
OnCompleteContinuation(int32_t code)240 void FrontendDelegateDeclarativeNG::OnCompleteContinuation(int32_t code)
241 {
242     taskExecutor_->PostSyncTask(
243         [weak = AceType::WeakClaim(this), code] {
244             auto delegate = weak.Upgrade();
245             if (delegate && delegate->onCompleteContinuationCallBack_) {
246                 delegate->onCompleteContinuationCallBack_(code);
247             }
248         },
249         TaskExecutor::TaskType::JS, "ArkUICompleteContinuation");
250 }
251 
OnRemoteTerminated()252 void FrontendDelegateDeclarativeNG::OnRemoteTerminated()
253 {
254     taskExecutor_->PostSyncTask(
255         [weak = AceType::WeakClaim(this)] {
256             auto delegate = weak.Upgrade();
257             if (delegate && delegate->onRemoteTerminatedCallBack_) {
258                 delegate->onRemoteTerminatedCallBack_();
259             }
260         },
261         TaskExecutor::TaskType::JS, "ArkUIRemoteTerminated");
262 }
263 
OnSaveData(std::string & data)264 void FrontendDelegateDeclarativeNG::OnSaveData(std::string& data)
265 {
266     std::string savedData;
267     taskExecutor_->PostSyncTask(
268         [weak = AceType::WeakClaim(this), &savedData] {
269             auto delegate = weak.Upgrade();
270             if (delegate && delegate->onSaveDataCallBack_) {
271                 delegate->onSaveDataCallBack_(savedData);
272             }
273         },
274         TaskExecutor::TaskType::JS, "ArkUISaveData");
275     std::string pageUri = GetCurrentPageUrl();
276     data = std::string("{\"url\":\"").append(pageUri).append("\",\"__remoteData\":").append(savedData).append("}");
277 }
278 
OnRestoreData(const std::string & data)279 bool FrontendDelegateDeclarativeNG::OnRestoreData(const std::string& data)
280 {
281     bool ret = false;
282     taskExecutor_->PostSyncTask(
283         [weak = AceType::WeakClaim(this), &data, &ret] {
284             auto delegate = weak.Upgrade();
285             if (delegate && delegate->onRestoreDataCallBack_) {
286                 ret = delegate->onRestoreDataCallBack_(data);
287             }
288         },
289         TaskExecutor::TaskType::JS, "ArkUIRestoreData");
290     return ret;
291 }
292 
OnApplicationDestroy(const std::string & packageName)293 void FrontendDelegateDeclarativeNG::OnApplicationDestroy(const std::string& packageName)
294 {
295     taskExecutor_->PostSyncTask(
296         [destroyApplication = destroyApplication_, packageName] { destroyApplication(packageName); },
297         TaskExecutor::TaskType::JS, "ArkUIApplicationDestroy");
298 }
299 
UpdateApplicationState(const std::string & packageName,Frontend::State state)300 void FrontendDelegateDeclarativeNG::UpdateApplicationState(const std::string& packageName, Frontend::State state)
301 {
302     taskExecutor_->PostTask([updateApplicationState = updateApplicationState_, packageName,
303                                 state] { updateApplicationState(packageName, state); },
304         TaskExecutor::TaskType::JS, "ArkUIUpdateApplicationState");
305 }
306 
OnWindowDisplayModeChanged(bool isShownInMultiWindow,const std::string & data)307 void FrontendDelegateDeclarativeNG::OnWindowDisplayModeChanged(bool isShownInMultiWindow, const std::string& data)
308 {
309     taskExecutor_->PostTask([onWindowDisplayModeChanged = onWindowDisplayModeChanged_, isShownInMultiWindow,
310                                 data] { onWindowDisplayModeChanged(isShownInMultiWindow, data); },
311         TaskExecutor::TaskType::JS, "ArkUIWindowDisplayModeChanged");
312 }
313 
NotifyAppStorage(const WeakPtr<Framework::JsEngine> & jsEngineWeak,const std::string & key,const std::string & value)314 void FrontendDelegateDeclarativeNG::NotifyAppStorage(
315     const WeakPtr<Framework::JsEngine>& jsEngineWeak, const std::string& key, const std::string& value)
316 {
317     taskExecutor_->PostTask(
318         [jsEngineWeak, key, value] {
319             auto jsEngine = jsEngineWeak.Upgrade();
320             if (!jsEngine) {
321                 return;
322             }
323             jsEngine->NotifyAppStorage(key, value);
324         },
325         TaskExecutor::TaskType::JS, "ArkUINotifyAppStorage");
326 }
327 
FireAccessibilityEvent(const AccessibilityEvent & accessibilityEvent)328 void FrontendDelegateDeclarativeNG::FireAccessibilityEvent(const AccessibilityEvent& accessibilityEvent)
329 {
330     jsAccessibilityManager_->SendAccessibilityAsyncEvent(accessibilityEvent);
331 }
332 
InitializeAccessibilityCallback()333 void FrontendDelegateDeclarativeNG::InitializeAccessibilityCallback()
334 {
335     jsAccessibilityManager_->InitializeCallback();
336 }
337 
FireExternalEvent(const std::string &,const std::string & componentId,const uint32_t nodeId,const bool isDestroy)338 void FrontendDelegateDeclarativeNG::FireExternalEvent(
339     const std::string& /* eventId */, const std::string& componentId, const uint32_t nodeId, const bool isDestroy)
340 {
341     taskExecutor_->PostSyncTask(
342         [weak = AceType::WeakClaim(this), componentId, nodeId, isDestroy] {
343             auto delegate = weak.Upgrade();
344             if (delegate) {
345                 delegate->externalEvent_(componentId, nodeId, isDestroy);
346             }
347         },
348         TaskExecutor::TaskType::JS, "ArkUIFireExternalEvent");
349 }
350 
WaitTimer(const std::string & callbackId,const std::string & delay,bool isInterval,bool isFirst)351 void FrontendDelegateDeclarativeNG::WaitTimer(
352     const std::string& callbackId, const std::string& delay, bool isInterval, bool isFirst)
353 {
354     if (!isFirst) {
355         auto timeoutTaskIter = timeoutTaskMap_.find(callbackId);
356         // If not find the callbackId in map, means this timer already was removed,
357         // no need create a new cancelableTimer again.
358         if (timeoutTaskIter == timeoutTaskMap_.end()) {
359             return;
360         }
361     }
362 
363     int32_t delayTime = StringToInt(delay);
364     // CancelableCallback class can only be executed once.
365     CancelableCallback<void()> cancelableTimer;
366     cancelableTimer.Reset([callbackId, delay, isInterval, call = timer_] { call(callbackId, delay, isInterval); });
367     auto result = timeoutTaskMap_.try_emplace(callbackId, cancelableTimer);
368     if (!result.second) {
369         result.first->second = cancelableTimer;
370     }
371     taskExecutor_->PostDelayedTask(cancelableTimer, TaskExecutor::TaskType::JS, delayTime, "ArkUIWaitTimer");
372 }
373 
ClearTimer(const std::string & callbackId)374 void FrontendDelegateDeclarativeNG::ClearTimer(const std::string& callbackId)
375 {
376     auto timeoutTaskIter = timeoutTaskMap_.find(callbackId);
377     if (timeoutTaskIter != timeoutTaskMap_.end()) {
378         timeoutTaskIter->second.Cancel();
379         timeoutTaskMap_.erase(timeoutTaskIter);
380     }
381 }
382 
Push(const std::string & uri,const std::string & params)383 void FrontendDelegateDeclarativeNG::Push(const std::string& uri, const std::string& params)
384 {
385     CHECK_NULL_VOID(pageRouterManager_);
386     pageRouterManager_->Push(NG::RouterPageInfo({ uri, params }));
387     OnMediaQueryUpdate();
388 }
389 
PushWithMode(const std::string & uri,const std::string & params,uint32_t routerMode)390 void FrontendDelegateDeclarativeNG::PushWithMode(const std::string& uri, const std::string& params, uint32_t routerMode)
391 {
392     CHECK_NULL_VOID(pageRouterManager_);
393     pageRouterManager_->Push(NG::RouterPageInfo({ uri, params, static_cast<NG::RouterMode>(routerMode) }));
394     OnMediaQueryUpdate();
395 }
396 
PushWithCallback(const std::string & uri,const std::string & params,const std::function<void (const std::string &,int32_t)> & errorCallback,uint32_t routerMode)397 void FrontendDelegateDeclarativeNG::PushWithCallback(const std::string& uri, const std::string& params,
398     const std::function<void(const std::string&, int32_t)>& errorCallback, uint32_t routerMode)
399 {
400     CHECK_NULL_VOID(pageRouterManager_);
401     pageRouterManager_->Push(
402         NG::RouterPageInfo({ uri, params, static_cast<NG::RouterMode>(routerMode), errorCallback }));
403     OnMediaQueryUpdate();
404 }
405 
PushNamedRoute(const std::string & uri,const std::string & params,const std::function<void (const std::string &,int32_t)> & errorCallback,uint32_t routerMode)406 void FrontendDelegateDeclarativeNG::PushNamedRoute(const std::string& uri, const std::string& params,
407     const std::function<void(const std::string&, int32_t)>& errorCallback, uint32_t routerMode)
408 {
409     CHECK_NULL_VOID(pageRouterManager_);
410     pageRouterManager_->PushNamedRoute(
411         NG::RouterPageInfo({ uri, params, static_cast<NG::RouterMode>(routerMode), errorCallback }));
412     OnMediaQueryUpdate();
413 }
414 
Replace(const std::string & uri,const std::string & params)415 void FrontendDelegateDeclarativeNG::Replace(const std::string& uri, const std::string& params)
416 {
417     CHECK_NULL_VOID(pageRouterManager_);
418     pageRouterManager_->Replace(NG::RouterPageInfo({ uri, params }));
419 }
420 
ReplaceWithMode(const std::string & uri,const std::string & params,uint32_t routerMode)421 void FrontendDelegateDeclarativeNG::ReplaceWithMode(
422     const std::string& uri, const std::string& params, uint32_t routerMode)
423 {
424     CHECK_NULL_VOID(pageRouterManager_);
425     pageRouterManager_->Replace(NG::RouterPageInfo({ uri, params, static_cast<NG::RouterMode>(routerMode) }));
426     OnMediaQueryUpdate();
427 }
428 
ReplaceWithCallback(const std::string & uri,const std::string & params,const std::function<void (const std::string &,int32_t)> & errorCallback,uint32_t routerMode)429 void FrontendDelegateDeclarativeNG::ReplaceWithCallback(const std::string& uri, const std::string& params,
430     const std::function<void(const std::string&, int32_t)>& errorCallback, uint32_t routerMode)
431 {
432     CHECK_NULL_VOID(pageRouterManager_);
433     pageRouterManager_->Replace(
434         NG::RouterPageInfo({ uri, params, static_cast<NG::RouterMode>(routerMode), errorCallback }));
435     OnMediaQueryUpdate();
436 }
437 
ReplaceNamedRoute(const std::string & uri,const std::string & params,const std::function<void (const std::string &,int32_t)> & errorCallback,uint32_t routerMode)438 void FrontendDelegateDeclarativeNG::ReplaceNamedRoute(const std::string& uri, const std::string& params,
439     const std::function<void(const std::string&, int32_t)>& errorCallback, uint32_t routerMode)
440 {
441     CHECK_NULL_VOID(pageRouterManager_);
442     pageRouterManager_->ReplaceNamedRoute(
443         NG::RouterPageInfo({ uri, params, static_cast<NG::RouterMode>(routerMode), errorCallback }));
444     OnMediaQueryUpdate();
445 }
446 
Back(const std::string & uri,const std::string & params)447 void FrontendDelegateDeclarativeNG::Back(const std::string& uri, const std::string& params)
448 {
449     CHECK_NULL_VOID(pageRouterManager_);
450     pageRouterManager_->BackWithTarget(NG::RouterPageInfo({ uri, params }));
451 }
452 
BackToIndex(int32_t index,const std::string & params)453 void FrontendDelegateDeclarativeNG::BackToIndex(int32_t index, const std::string& params)
454 {
455     CHECK_NULL_VOID(pageRouterManager_);
456     pageRouterManager_->BackToIndexWithTarget(index, params);
457 }
458 
Clear()459 void FrontendDelegateDeclarativeNG::Clear()
460 {
461     CHECK_NULL_VOID(pageRouterManager_);
462     pageRouterManager_->Clear();
463 }
464 
GetStackSize() const465 int32_t FrontendDelegateDeclarativeNG::GetStackSize() const
466 {
467     CHECK_NULL_RETURN(pageRouterManager_, 0);
468     return pageRouterManager_->GetStackSize();
469 }
470 
GetState(int32_t & index,std::string & name,std::string & path)471 void FrontendDelegateDeclarativeNG::GetState(int32_t& index, std::string& name, std::string& path)
472 {
473     CHECK_NULL_VOID(pageRouterManager_);
474     pageRouterManager_->GetState(index, name, path);
475 }
476 
GetRouterStateByIndex(int32_t & index,std::string & name,std::string & path,std::string & params)477 void FrontendDelegateDeclarativeNG::GetRouterStateByIndex(int32_t& index, std::string& name,
478     std::string& path, std::string& params)
479 {
480     CHECK_NULL_VOID(pageRouterManager_);
481     pageRouterManager_->GetStateByIndex(index, name, path, params);
482 }
483 
GetRouterStateByUrl(std::string & url,std::vector<StateInfo> & stateArray)484 void FrontendDelegateDeclarativeNG::GetRouterStateByUrl(std::string& url, std::vector<StateInfo>& stateArray)
485 {
486     CHECK_NULL_VOID(pageRouterManager_);
487     pageRouterManager_->GetStateByUrl(url, stateArray);
488 }
489 
GetParams()490 std::string FrontendDelegateDeclarativeNG::GetParams()
491 {
492     CHECK_NULL_RETURN(pageRouterManager_, "");
493     return pageRouterManager_->GetParams();
494 }
495 
NavigatePage(uint8_t type,const PageTarget & target,const std::string & params)496 void FrontendDelegateDeclarativeNG::NavigatePage(uint8_t type, const PageTarget& target, const std::string& params)
497 {
498     switch (static_cast<NavigatorType>(type)) {
499         case NavigatorType::PUSH:
500             Push(target.url, params);
501             break;
502         case NavigatorType::REPLACE:
503             Replace(target.url, params);
504             break;
505         case NavigatorType::BACK:
506             Back(target.url, params);
507             break;
508         default:
509             Back(target.url, params);
510     }
511 }
512 
PostJsTask(std::function<void ()> && task,const std::string & name)513 void FrontendDelegateDeclarativeNG::PostJsTask(std::function<void()>&& task, const std::string& name)
514 {
515     taskExecutor_->PostTask(task, TaskExecutor::TaskType::JS, name);
516 }
517 
GetAppID() const518 const std::string& FrontendDelegateDeclarativeNG::GetAppID() const
519 {
520     return manifestParser_->GetAppInfo()->GetAppID();
521 }
522 
GetAppName() const523 const std::string& FrontendDelegateDeclarativeNG::GetAppName() const
524 {
525     return manifestParser_->GetAppInfo()->GetAppName();
526 }
527 
GetVersionName() const528 const std::string& FrontendDelegateDeclarativeNG::GetVersionName() const
529 {
530     return manifestParser_->GetAppInfo()->GetVersionName();
531 }
532 
GetVersionCode() const533 int32_t FrontendDelegateDeclarativeNG::GetVersionCode() const
534 {
535     return manifestParser_->GetAppInfo()->GetVersionCode();
536 }
537 
PostSyncTaskToPage(std::function<void ()> && task,const std::string & name)538 void FrontendDelegateDeclarativeNG::PostSyncTaskToPage(std::function<void()>&& task, const std::string& name)
539 {
540     pipelineContextHolder_.Get(); // Wait until Pipeline Context is attached.
541     taskExecutor_->PostSyncTask(task, TaskExecutor::TaskType::UI, name);
542 }
543 
GetAssetContent(const std::string & url,std::string & content)544 bool FrontendDelegateDeclarativeNG::GetAssetContent(const std::string& url, std::string& content)
545 {
546     return GetAssetContentImpl(assetManager_, url, content);
547 }
548 
GetAssetContent(const std::string & url,std::vector<uint8_t> & content)549 bool FrontendDelegateDeclarativeNG::GetAssetContent(const std::string& url, std::vector<uint8_t>& content)
550 {
551     return GetAssetContentImpl(assetManager_, url, content);
552 }
553 
GetAssetPath(const std::string & url)554 std::string FrontendDelegateDeclarativeNG::GetAssetPath(const std::string& url)
555 {
556     return GetAssetPathImpl(assetManager_, url);
557 }
558 
ChangeLocale(const std::string & language,const std::string & countryOrRegion)559 void FrontendDelegateDeclarativeNG::ChangeLocale(const std::string& language, const std::string& countryOrRegion)
560 {
561     taskExecutor_->PostTask(
562         [language, countryOrRegion]() { AceApplicationInfo::GetInstance().ChangeLocale(language, countryOrRegion); },
563         TaskExecutor::TaskType::PLATFORM, "ArkUIChangeLocale");
564 }
565 
RegisterFont(const std::string & familyName,const std::string & familySrc,const std::string & bundleName,const std::string & moduleName)566 void FrontendDelegateDeclarativeNG::RegisterFont(const std::string& familyName, const std::string& familySrc,
567     const std::string& bundleName, const std::string& moduleName)
568 {
569     pipelineContextHolder_.Get()->RegisterFont(familyName, familySrc, bundleName, moduleName);
570 }
571 
GetSystemFontList(std::vector<std::string> & fontList)572 void FrontendDelegateDeclarativeNG::GetSystemFontList(std::vector<std::string>& fontList)
573 {
574     pipelineContextHolder_.Get()->GetSystemFontList(fontList);
575 }
576 
GetSystemFont(const std::string & fontName,FontInfo & fontInfo)577 bool FrontendDelegateDeclarativeNG::GetSystemFont(const std::string& fontName, FontInfo& fontInfo)
578 {
579     return pipelineContextHolder_.Get()->GetSystemFont(fontName, fontInfo);
580 }
581 
GetUIFontConfig(FontConfigJsonInfo & fontConfigJsonInfo)582 void FrontendDelegateDeclarativeNG::GetUIFontConfig(FontConfigJsonInfo& fontConfigJsonInfo)
583 {
584     pipelineContextHolder_.Get()->GetUIFontConfig(fontConfigJsonInfo);
585 }
586 
MeasureText(MeasureContext context)587 double FrontendDelegateDeclarativeNG::MeasureText(MeasureContext context)
588 {
589     if (context.isFontSizeUseDefaultUnit && context.fontSize.has_value() &&
590         !AceApplicationInfo::GetInstance().GreatOrEqualTargetAPIVersion(PlatformVersion::VERSION_TWELVE)) {
591         context.fontSize = Dimension(context.fontSize->Value(), DimensionUnit::VP);
592     }
593     return MeasureUtil::MeasureText(context);
594 }
595 
MeasureTextSize(MeasureContext context)596 Size FrontendDelegateDeclarativeNG::MeasureTextSize(MeasureContext context)
597 {
598     if (context.isFontSizeUseDefaultUnit && context.fontSize.has_value() &&
599         !AceApplicationInfo::GetInstance().GreatOrEqualTargetAPIVersion(PlatformVersion::VERSION_TWELVE)) {
600         context.fontSize = Dimension(context.fontSize->Value(), DimensionUnit::VP);
601     }
602     return MeasureUtil::MeasureTextSize(context);
603 }
604 
GetAnimationJsTask()605 SingleTaskExecutor FrontendDelegateDeclarativeNG::GetAnimationJsTask()
606 {
607     return SingleTaskExecutor::Make(taskExecutor_, TaskExecutor::TaskType::JS);
608 }
609 
GetUiTask()610 SingleTaskExecutor FrontendDelegateDeclarativeNG::GetUiTask()
611 {
612     return SingleTaskExecutor::Make(taskExecutor_, TaskExecutor::TaskType::UI);
613 }
614 
GetPipelineContext()615 RefPtr<PipelineBase> FrontendDelegateDeclarativeNG::GetPipelineContext()
616 {
617     return pipelineContextHolder_.Get();
618 }
619 
OnPageBackPress()620 bool FrontendDelegateDeclarativeNG::OnPageBackPress()
621 {
622     CHECK_NULL_RETURN(pageRouterManager_, false);
623     auto pageNode = pageRouterManager_->GetCurrentPageNode();
624     CHECK_NULL_RETURN(pageNode, false);
625     auto pagePattern = pageNode->GetPattern<NG::PagePattern>();
626     CHECK_NULL_RETURN(pagePattern, false);
627     if (pagePattern->OnBackPressed()) {
628         return true;
629     }
630     return pageRouterManager_->Pop();
631 }
632 
OnSurfaceChanged()633 void FrontendDelegateDeclarativeNG::OnSurfaceChanged()
634 {
635     if (mediaQueryInfo_->GetIsInit()) {
636         mediaQueryInfo_->SetIsInit(false);
637     }
638     mediaQueryInfo_->EnsureListenerIdValid();
639     OnMediaQueryUpdate();
640 }
641 
ShowDialog(const std::string & title,const std::string & message,const std::vector<ButtonInfo> & buttons,bool autoCancel,std::function<void (int32_t,int32_t)> && callback,const std::set<std::string> & callbacks)642 void FrontendDelegateDeclarativeNG::ShowDialog(const std::string& title, const std::string& message,
643     const std::vector<ButtonInfo>& buttons, bool autoCancel, std::function<void(int32_t, int32_t)>&& callback,
644     const std::set<std::string>& callbacks)
645 {
646     TAG_LOGD(AceLogTag::ACE_OVERLAY, "show dialog enter");
647     DialogProperties dialogProperties = {
648         .type = DialogType::ALERT_DIALOG,
649         .title = title,
650         .content = message,
651         .autoCancel = autoCancel,
652         .buttons = buttons,
653     };
654     ShowDialogInner(dialogProperties, std::move(callback), callbacks);
655 }
656 
ShowDialog(const std::string & title,const std::string & message,const std::vector<ButtonInfo> & buttons,bool autoCancel,std::function<void (int32_t,int32_t)> && callback,const std::set<std::string> & callbacks,std::function<void (bool)> && onStatusChanged)657 void FrontendDelegateDeclarativeNG::ShowDialog(const std::string& title, const std::string& message,
658     const std::vector<ButtonInfo>& buttons, bool autoCancel, std::function<void(int32_t, int32_t)>&& callback,
659     const std::set<std::string>& callbacks, std::function<void(bool)>&& onStatusChanged)
660 {
661     TAG_LOGD(AceLogTag::ACE_OVERLAY, "show dialog enter");
662     DialogProperties dialogProperties = {
663         .type = DialogType::ALERT_DIALOG,
664         .title = title,
665         .content = message,
666         .autoCancel = autoCancel,
667         .buttons = buttons,
668         .onStatusChanged = std::move(onStatusChanged),
669     };
670     ShowDialogInner(dialogProperties, std::move(callback), callbacks);
671 }
672 
ShowDialog(const PromptDialogAttr & dialogAttr,const std::vector<ButtonInfo> & buttons,std::function<void (int32_t,int32_t)> && callback,const std::set<std::string> & callbacks)673 void FrontendDelegateDeclarativeNG::ShowDialog(const PromptDialogAttr& dialogAttr,
674     const std::vector<ButtonInfo>& buttons, std::function<void(int32_t, int32_t)>&& callback,
675     const std::set<std::string>& callbacks)
676 {
677     TAG_LOGD(AceLogTag::ACE_OVERLAY, "show dialog enter");
678     DialogProperties dialogProperties = {
679         .type = DialogType::ALERT_DIALOG,
680         .title = dialogAttr.title,
681         .content = dialogAttr.message,
682         .autoCancel = dialogAttr.autoCancel,
683         .buttons = buttons,
684         .isShowInSubWindow = dialogAttr.showInSubWindow,
685         .isModal = dialogAttr.isModal,
686         .maskRect = dialogAttr.maskRect,
687     };
688     if (dialogAttr.alignment.has_value()) {
689         dialogProperties.alignment = dialogAttr.alignment.value();
690     }
691     if (dialogAttr.offset.has_value()) {
692         dialogProperties.offset = dialogAttr.offset.value();
693     }
694     if (dialogAttr.shadow.has_value()) {
695         dialogProperties.shadow = dialogAttr.shadow.value();
696     }
697     if (dialogAttr.backgroundColor.has_value()) {
698         dialogProperties.backgroundColor = dialogAttr.backgroundColor.value();
699     }
700     if (dialogAttr.backgroundBlurStyle.has_value()) {
701         dialogProperties.backgroundBlurStyle = dialogAttr.backgroundBlurStyle.value();
702     }
703     ShowDialogInner(dialogProperties, std::move(callback), callbacks);
704 }
705 
ShowDialog(const PromptDialogAttr & dialogAttr,const std::vector<ButtonInfo> & buttons,std::function<void (int32_t,int32_t)> && callback,const std::set<std::string> & callbacks,std::function<void (bool)> && onStatusChanged)706 void FrontendDelegateDeclarativeNG::ShowDialog(const PromptDialogAttr& dialogAttr,
707     const std::vector<ButtonInfo>& buttons, std::function<void(int32_t, int32_t)>&& callback,
708     const std::set<std::string>& callbacks, std::function<void(bool)>&& onStatusChanged)
709 {
710     TAG_LOGD(AceLogTag::ACE_OVERLAY, "show dialog enter");
711     DialogProperties dialogProperties = {
712         .type = DialogType::ALERT_DIALOG,
713         .title = dialogAttr.title,
714         .content = dialogAttr.message,
715         .autoCancel = dialogAttr.autoCancel,
716         .buttons = buttons,
717         .isShowInSubWindow = dialogAttr.showInSubWindow,
718         .isModal = dialogAttr.isModal,
719         .onStatusChanged = std::move(onStatusChanged),
720         .maskRect = dialogAttr.maskRect,
721     };
722     if (dialogAttr.alignment.has_value()) {
723         dialogProperties.alignment = dialogAttr.alignment.value();
724     }
725     if (dialogAttr.offset.has_value()) {
726         dialogProperties.offset = dialogAttr.offset.value();
727     }
728     ShowDialogInner(dialogProperties, std::move(callback), callbacks);
729 }
730 
ParsePropertiesFromAttr(const PromptDialogAttr & dialogAttr)731 DialogProperties FrontendDelegateDeclarativeNG::ParsePropertiesFromAttr(const PromptDialogAttr &dialogAttr)
732 {
733     DialogProperties dialogProperties = { .autoCancel = dialogAttr.autoCancel,
734         .customStyle = dialogAttr.customStyle,
735         .onWillDismiss = dialogAttr.customOnWillDismiss,
736         .maskColor = dialogAttr.maskColor,
737         .backgroundColor = dialogAttr.backgroundColor,
738         .borderRadius = dialogAttr.borderRadius,
739         .isShowInSubWindow = dialogAttr.showInSubWindow,
740         .isModal = dialogAttr.isModal,
741         .customBuilder = dialogAttr.customBuilder,
742         .borderWidth = dialogAttr.borderWidth,
743         .borderColor = dialogAttr.borderColor,
744         .borderStyle = dialogAttr.borderStyle,
745         .shadow = dialogAttr.shadow,
746         .width = dialogAttr.width,
747         .height = dialogAttr.height,
748         .maskRect = dialogAttr.maskRect,
749         .transitionEffect = dialogAttr.transitionEffect,
750         .contentNode = dialogAttr.contentNode,
751         .onDidAppear = dialogAttr.onDidAppear,
752         .onDidDisappear = dialogAttr.onDidDisappear,
753         .onWillAppear = dialogAttr.onWillAppear,
754         .onWillDisappear = dialogAttr.onWillDisappear,
755         .keyboardAvoidMode = dialogAttr.keyboardAvoidMode };
756 #if defined(PREVIEW)
757     if (dialogProperties.isShowInSubWindow) {
758         LOGW("[Engine Log] Unable to use the SubWindow in the Previewer. Perform this operation on the "
759              "emulator or a real device instead.");
760         dialogProperties.isShowInSubWindow = false;
761     }
762 #endif
763     if (dialogAttr.alignment.has_value()) {
764         dialogProperties.alignment = dialogAttr.alignment.value();
765     }
766     if (dialogAttr.offset.has_value()) {
767         dialogProperties.offset = dialogAttr.offset.value();
768     }
769     if (Container::LessThanAPIVersion(PlatformVersion::VERSION_TWELVE)) {
770         dialogProperties.isSysBlurStyle = false;
771     } else {
772         if (dialogAttr.backgroundBlurStyle.has_value()) {
773             dialogProperties.backgroundBlurStyle = dialogAttr.backgroundBlurStyle.value();
774         }
775     }
776     return dialogProperties;
777 }
778 
OpenCustomDialog(const PromptDialogAttr & dialogAttr,std::function<void (int32_t)> && callback)779 void FrontendDelegateDeclarativeNG::OpenCustomDialog(const PromptDialogAttr &dialogAttr,
780     std::function<void(int32_t)> &&callback)
781 {
782     DialogProperties dialogProperties = ParsePropertiesFromAttr(dialogAttr);
783     if (Container::IsCurrentUseNewPipeline()) {
784         auto task = [dialogAttr, dialogProperties, callback](const RefPtr<NG::OverlayManager>& overlayManager) mutable {
785             CHECK_NULL_VOID(overlayManager);
786             TAG_LOGD(AceLogTag::ACE_OVERLAY, "Begin to open custom dialog ");
787             if (dialogProperties.isShowInSubWindow) {
788                 SubwindowManager::GetInstance()->OpenCustomDialogNG(dialogProperties, std::move(callback));
789                 if (dialogProperties.isModal) {
790                     TAG_LOGW(AceLogTag::ACE_OVERLAY, "temporary not support isShowInSubWindow and isModal");
791                 }
792             } else {
793                 overlayManager->OpenCustomDialog(dialogProperties, std::move(callback));
794             }
795         };
796         MainWindowOverlay(std::move(task), "ArkUIOverlayOpenCustomDialog");
797         return;
798     } else {
799         TAG_LOGW(AceLogTag::ACE_OVERLAY, "not support old pipeline");
800     }
801 }
802 
CloseCustomDialog(const int32_t dialogId)803 void FrontendDelegateDeclarativeNG::CloseCustomDialog(const int32_t dialogId)
804 {
805     auto task = [dialogId](const RefPtr<NG::OverlayManager>& overlayManager) {
806         CHECK_NULL_VOID(overlayManager);
807         TAG_LOGD(AceLogTag::ACE_OVERLAY, "begin to close custom dialog.");
808         overlayManager->CloseCustomDialog(dialogId);
809         SubwindowManager::GetInstance()->CloseCustomDialogNG(dialogId);
810     };
811     MainWindowOverlay(std::move(task), "ArkUIOverlayCloseCustomDialog");
812     return;
813 }
814 
CloseCustomDialog(const WeakPtr<NG::UINode> & node,std::function<void (int32_t)> && callback)815 void FrontendDelegateDeclarativeNG::CloseCustomDialog(const WeakPtr<NG::UINode>& node,
816     std::function<void(int32_t)> &&callback)
817 {
818     auto task = [node, callback](const RefPtr<NG::OverlayManager>& overlayManager) mutable {
819         CHECK_NULL_VOID(overlayManager);
820         TAG_LOGD(AceLogTag::ACE_OVERLAY, "begin to close custom dialog.");
821         overlayManager->CloseCustomDialog(node, std::move(callback));
822         SubwindowManager::GetInstance()->CloseCustomDialogNG(node, std::move(callback));
823     };
824     MainWindowOverlay(std::move(task), "ArkUIOverlayCloseCustomDialog");
825     return;
826 }
827 
UpdateCustomDialog(const WeakPtr<NG::UINode> & node,const PromptDialogAttr & dialogAttr,std::function<void (int32_t)> && callback)828 void FrontendDelegateDeclarativeNG::UpdateCustomDialog(
829     const WeakPtr<NG::UINode>& node, const PromptDialogAttr &dialogAttr, std::function<void(int32_t)> &&callback)
830 {
831     DialogProperties dialogProperties = {
832         .autoCancel = dialogAttr.autoCancel,
833         .maskColor = dialogAttr.maskColor,
834         .isSysBlurStyle = false
835     };
836     if (dialogAttr.alignment.has_value()) {
837         dialogProperties.alignment = dialogAttr.alignment.value();
838     }
839     if (dialogAttr.offset.has_value()) {
840         dialogProperties.offset = dialogAttr.offset.value();
841     }
842     auto task = [dialogAttr, dialogProperties, node, callback]
843         (const RefPtr<NG::OverlayManager>& overlayManager) mutable {
844         CHECK_NULL_VOID(overlayManager);
845         TAG_LOGD(AceLogTag::ACE_OVERLAY, "begin to update custom dialog.");
846         overlayManager->UpdateCustomDialog(node, dialogProperties, std::move(callback));
847         SubwindowManager::GetInstance()->UpdateCustomDialogNG(node, dialogAttr, std::move(callback));
848     };
849     MainWindowOverlay(std::move(task), "ArkUIOverlayUpdateCustomDialog");
850     return;
851 }
852 
ShowActionMenu(const std::string & title,const std::vector<ButtonInfo> & button,std::function<void (int32_t,int32_t)> && callback)853 void FrontendDelegateDeclarativeNG::ShowActionMenu(
854     const std::string& title, const std::vector<ButtonInfo>& button, std::function<void(int32_t, int32_t)>&& callback)
855 {
856     TAG_LOGD(AceLogTag::ACE_OVERLAY, "show action menu enter");
857     DialogProperties dialogProperties = {
858         .title = title,
859         .autoCancel = true,
860         .isMenu = true,
861         .buttons = button,
862     };
863     ShowActionMenuInner(dialogProperties, button, std::move(callback));
864 }
865 
ShowActionMenu(const std::string & title,const std::vector<ButtonInfo> & button,std::function<void (int32_t,int32_t)> && callback,std::function<void (bool)> && onStatusChanged)866 void FrontendDelegateDeclarativeNG::ShowActionMenu(const std::string& title, const std::vector<ButtonInfo>& button,
867     std::function<void(int32_t, int32_t)>&& callback, std::function<void(bool)>&& onStatusChanged)
868 {
869     TAG_LOGD(AceLogTag::ACE_OVERLAY, "show action menu enter");
870     DialogProperties dialogProperties = {
871         .title = title,
872         .autoCancel = true,
873         .isMenu = true,
874         .buttons = button,
875         .onStatusChanged = std::move(onStatusChanged),
876     };
877     ShowActionMenuInner(dialogProperties, button, std::move(callback));
878 }
879 
OnMediaQueryUpdate(bool isSynchronous)880 void FrontendDelegateDeclarativeNG::OnMediaQueryUpdate(bool isSynchronous)
881 {
882     auto containerId = Container::CurrentId();
883     if (containerId < 0) {
884         auto container = Container::GetActive();
885         if (container) {
886             containerId = container->GetInstanceId();
887         }
888     }
889     bool isInSubwindow = containerId >= 1000000;
890     if (isInSubwindow) {
891         return;
892     }
893     if (mediaQueryInfo_->GetIsInit()) {
894         return;
895     }
896 
897     taskExecutor_->PostTask(
898         [weak = AceType::WeakClaim(this)] {
899             auto delegate = weak.Upgrade();
900             if (!delegate) {
901                 return;
902             }
903             const auto& info = delegate->mediaQueryInfo_->GetMediaQueryInfo();
904 
905             // request js media query
906             const auto& listenerId = delegate->mediaQueryInfo_->GetListenerId();
907             delegate->mediaQueryCallback_(listenerId, info);
908             delegate->mediaQueryInfo_->ResetListenerId();
909         },
910         TaskExecutor::TaskType::JS, "ArkUIMediaQueryUpdate");
911 }
912 
OnLayoutCompleted(const std::string & componentId)913 void FrontendDelegateDeclarativeNG::OnLayoutCompleted(const std::string& componentId)
914 {
915     taskExecutor_->PostTask(
916         [weak = AceType::WeakClaim(this), componentId] {
917             auto delegate = weak.Upgrade();
918             if (!delegate) {
919                 return;
920             }
921             delegate->layoutInspectorCallback_(componentId);
922         },
923         TaskExecutor::TaskType::JS, "ArkUILayoutCompleted");
924 }
925 
OnDrawCompleted(const std::string & componentId)926 void FrontendDelegateDeclarativeNG::OnDrawCompleted(const std::string& componentId)
927 {
928     taskExecutor_->PostTask(
929         [weak = AceType::WeakClaim(this), componentId] {
930             auto delegate = weak.Upgrade();
931             if (!delegate) {
932                 return;
933             }
934             delegate->drawInspectorCallback_(componentId);
935         },
936         TaskExecutor::TaskType::JS, "ArkUIDrawCompleted");
937 }
938 
SetColorMode(ColorMode colorMode)939 void FrontendDelegateDeclarativeNG::SetColorMode(ColorMode colorMode)
940 {
941     OnMediaQueryUpdate();
942 }
943 
OnForeground()944 void FrontendDelegateDeclarativeNG::OnForeground()
945 {
946     if (!isFirstNotifyShow_) {
947         OnPageShow();
948     }
949     isFirstNotifyShow_ = false;
950 }
951 
GetCurrentPageUrl()952 std::string FrontendDelegateDeclarativeNG::GetCurrentPageUrl()
953 {
954     CHECK_NULL_RETURN(pageRouterManager_, "");
955     return pageRouterManager_->GetCurrentPageUrl();
956 }
957 
958 // Get the currently running JS page information in NG structure.
GetCurrentPageSourceMap()959 RefPtr<RevSourceMap> FrontendDelegateDeclarativeNG::GetCurrentPageSourceMap()
960 {
961     CHECK_NULL_RETURN(pageRouterManager_, nullptr);
962     return pageRouterManager_->GetCurrentPageSourceMap(assetManager_);
963 }
964 
965 // Get the currently running JS page information in NG structure.
GetFaAppSourceMap()966 RefPtr<RevSourceMap> FrontendDelegateDeclarativeNG::GetFaAppSourceMap()
967 {
968     if (appSourceMap_) {
969         return appSourceMap_;
970     }
971     std::string appMap;
972     if (GetAssetContent("app.js.map", appMap)) {
973         appSourceMap_ = AceType::MakeRefPtr<RevSourceMap>();
974         appSourceMap_->Init(appMap);
975     }
976     return appSourceMap_;
977 }
978 
GetStageSourceMap(std::unordered_map<std::string,RefPtr<Framework::RevSourceMap>> & sourceMaps)979 void FrontendDelegateDeclarativeNG::GetStageSourceMap(
980     std::unordered_map<std::string, RefPtr<Framework::RevSourceMap>>& sourceMaps)
981 {
982     std::string maps;
983     if (GetAssetContent(MERGE_SOURCEMAPS_PATH, maps)) {
984         auto SourceMap = AceType::MakeRefPtr<RevSourceMap>();
985         SourceMap->StageModeSourceMapSplit(maps, sourceMaps);
986     }
987 }
988 
CallPopPage()989 void FrontendDelegateDeclarativeNG::CallPopPage()
990 {
991     Back("", "");
992 }
993 
PostponePageTransition()994 void FrontendDelegateDeclarativeNG::PostponePageTransition()
995 {
996     taskExecutor_->PostTask(
997         [weak = AceType::WeakClaim(this)] {
998             auto delegate = weak.Upgrade();
999             if (!delegate) {
1000                 return;
1001             }
1002             auto pipelineContext = delegate->pipelineContextHolder_.Get();
1003             pipelineContext->PostponePageTransition();
1004         },
1005         TaskExecutor::TaskType::UI, "ArkUIPostponePageTransition");
1006 }
1007 
LaunchPageTransition()1008 void FrontendDelegateDeclarativeNG::LaunchPageTransition()
1009 {
1010     taskExecutor_->PostTask(
1011         [weak = AceType::WeakClaim(this)] {
1012             auto delegate = weak.Upgrade();
1013             if (!delegate) {
1014                 return;
1015             }
1016             auto pipelineContext = delegate->pipelineContextHolder_.Get();
1017             pipelineContext->LaunchPageTransition();
1018         },
1019         TaskExecutor::TaskType::UI, "ArkUILaunchPageTransition");
1020 }
1021 
GetComponentsCount()1022 size_t FrontendDelegateDeclarativeNG::GetComponentsCount()
1023 {
1024     CHECK_NULL_RETURN(pageRouterManager_, 0);
1025     auto pageNode = pageRouterManager_->GetCurrentPageNode();
1026     CHECK_NULL_RETURN(pageNode, 0);
1027     return pageNode->GetAllDepthChildrenCount();
1028 }
1029 
ShowToast(const NG::ToastInfo & toastInfo)1030 void FrontendDelegateDeclarativeNG::ShowToast(const NG::ToastInfo& toastInfo)
1031 {
1032     TAG_LOGD(AceLogTag::ACE_OVERLAY, "show toast enter");
1033     NG::ToastInfo updatedToastInfo = toastInfo;
1034     updatedToastInfo.duration = std::clamp(toastInfo.duration, TOAST_TIME_DEFAULT, TOAST_TIME_MAX);
1035     updatedToastInfo.isRightToLeft = AceApplicationInfo::GetInstance().IsRightToLeft();
1036     auto task = [updatedToastInfo, containerId = Container::CurrentId()](
1037                     const RefPtr<NG::OverlayManager>& overlayManager) {
1038         CHECK_NULL_VOID(overlayManager);
1039         ContainerScope scope(containerId);
1040         overlayManager->ShowToast(updatedToastInfo);
1041     };
1042     MainWindowOverlay(std::move(task), "ArkUIOverlayShowToast");
1043 }
1044 
ShowDialogInner(DialogProperties & dialogProperties,std::function<void (int32_t,int32_t)> && callback,const std::set<std::string> & callbacks)1045 void FrontendDelegateDeclarativeNG::ShowDialogInner(DialogProperties& dialogProperties,
1046     std::function<void(int32_t, int32_t)>&& callback, const std::set<std::string>& callbacks)
1047 {
1048     TAG_LOGD(AceLogTag::ACE_OVERLAY, "show dialog inner enter");
1049     dialogProperties.onSuccess = std::move(callback);
1050     dialogProperties.onCancel = [callback, taskExecutor = taskExecutor_] {
1051         taskExecutor->PostTask(
1052             [callback]() { callback(CALLBACK_ERRORCODE_CANCEL, CALLBACK_DATACODE_ZERO); },
1053             TaskExecutor::TaskType::JS, "ArkUIOverlayShowDialogCancel");
1054     };
1055     auto task = [dialogProperties](const RefPtr<NG::OverlayManager>& overlayManager) {
1056         LOGI("Begin to show dialog ");
1057         CHECK_NULL_VOID(overlayManager);
1058         auto container = Container::Current();
1059         CHECK_NULL_VOID(container);
1060         if (container->IsSubContainer()) {
1061             auto currentId = SubwindowManager::GetInstance()->GetParentContainerId(Container::CurrentId());
1062             container = AceEngine::Get().GetContainer(currentId);
1063             CHECK_NULL_VOID(container);
1064         }
1065         RefPtr<NG::FrameNode> dialog;
1066         if (dialogProperties.isShowInSubWindow) {
1067             dialog = SubwindowManager::GetInstance()->ShowDialogNG(dialogProperties, nullptr);
1068             CHECK_NULL_VOID(dialog);
1069             if (dialogProperties.isModal && !container->IsUIExtensionWindow()) {
1070                 DialogProperties Maskarg;
1071                 Maskarg.isMask = true;
1072                 Maskarg.autoCancel = dialogProperties.autoCancel;
1073                 auto mask = overlayManager->ShowDialog(Maskarg, nullptr, false);
1074                 CHECK_NULL_VOID(mask);
1075                 overlayManager->SetMaskNodeId(dialog->GetId(), mask->GetId());
1076             }
1077         } else {
1078             dialog = overlayManager->ShowDialog(
1079                 dialogProperties, nullptr, AceApplicationInfo::GetInstance().IsRightToLeft());
1080             CHECK_NULL_VOID(dialog);
1081         }
1082     };
1083     MainWindowOverlay(std::move(task), "ArkUIOverlayShowDialog");
1084     return;
1085 }
1086 
ShowActionMenuInner(DialogProperties & dialogProperties,const std::vector<ButtonInfo> & button,std::function<void (int32_t,int32_t)> && callback)1087 void FrontendDelegateDeclarativeNG::ShowActionMenuInner(DialogProperties& dialogProperties,
1088     const std::vector<ButtonInfo>& button, std::function<void(int32_t, int32_t)>&& callback)
1089 {
1090     TAG_LOGD(AceLogTag::ACE_OVERLAY, "show action menu inner enter");
1091     dialogProperties.onSuccess = std::move(callback);
1092     dialogProperties.onCancel = [callback, taskExecutor = taskExecutor_] {
1093         taskExecutor->PostTask(
1094             [callback]() { callback(CALLBACK_ERRORCODE_CANCEL, CALLBACK_DATACODE_ZERO); },
1095             TaskExecutor::TaskType::JS, "ArkUIOverlayShowActionMenuCancel");
1096     };
1097     auto context = DynamicCast<NG::PipelineContext>(pipelineContextHolder_.Get());
1098     auto overlayManager = context ? context->GetOverlayManager() : nullptr;
1099     taskExecutor_->PostTask(
1100         [dialogProperties, weak = WeakPtr<NG::OverlayManager>(overlayManager)] {
1101             auto overlayManager = weak.Upgrade();
1102             CHECK_NULL_VOID(overlayManager);
1103             overlayManager->ShowDialog(dialogProperties, nullptr, AceApplicationInfo::GetInstance().IsRightToLeft());
1104         },
1105         TaskExecutor::TaskType::UI, "ArkUIOverlayShowActionMenu");
1106     return;
1107 }
1108 
EnableAlertBeforeBackPage(const std::string & message,std::function<void (int32_t)> && callback)1109 void FrontendDelegateDeclarativeNG::EnableAlertBeforeBackPage(
1110     const std::string& message, std::function<void(int32_t)>&& callback)
1111 {
1112     CHECK_NULL_VOID(pageRouterManager_);
1113     pageRouterManager_->EnableAlertBeforeBackPage(message, std::move(callback));
1114     return;
1115 }
1116 
DisableAlertBeforeBackPage()1117 void FrontendDelegateDeclarativeNG::DisableAlertBeforeBackPage()
1118 {
1119     CHECK_NULL_VOID(pageRouterManager_);
1120     pageRouterManager_->DisableAlertBeforeBackPage();
1121     return;
1122 }
1123 
RebuildAllPages()1124 void FrontendDelegateDeclarativeNG::RebuildAllPages()
1125 {
1126     CHECK_NULL_VOID(pageRouterManager_);
1127     auto url = pageRouterManager_->GetCurrentPageUrl();
1128     pageRouterManager_->Clear();
1129     pageRouterManager_->RunPage(url, "");
1130     return;
1131 }
1132 
OnPageShow()1133 void FrontendDelegateDeclarativeNG::OnPageShow()
1134 {
1135     CHECK_NULL_VOID(pageRouterManager_);
1136     auto pageNode = pageRouterManager_->GetCurrentPageNode();
1137     CHECK_NULL_VOID(pageNode);
1138     auto pagePattern = pageNode->GetPattern<NG::PagePattern>();
1139     CHECK_NULL_VOID(pagePattern);
1140     pagePattern->OnShow();
1141 }
1142 
OnPageHide()1143 void FrontendDelegateDeclarativeNG::OnPageHide()
1144 {
1145     CHECK_NULL_VOID(pageRouterManager_);
1146     auto pageNode = pageRouterManager_->GetCurrentPageNode();
1147     CHECK_NULL_VOID(pageNode);
1148     auto pagePattern = pageNode->GetPattern<NG::PagePattern>();
1149     CHECK_NULL_VOID(pagePattern);
1150     pagePattern->OnHide();
1151 }
1152 
GetSnapshot(const std::string & componentId,NG::ComponentSnapshot::JsCallback && callback,const NG::SnapshotOptions & options)1153 void FrontendDelegateDeclarativeNG::GetSnapshot(
1154     const std::string& componentId, NG::ComponentSnapshot::JsCallback&& callback, const NG::SnapshotOptions& options)
1155 {
1156 #ifdef ENABLE_ROSEN_BACKEND
1157     NG::ComponentSnapshot::Get(componentId, std::move(callback), options);
1158 #endif
1159 }
1160 
GetSyncSnapshot(const std::string & componentId,const NG::SnapshotOptions & options)1161 std::pair<int32_t, std::shared_ptr<Media::PixelMap>> FrontendDelegateDeclarativeNG::GetSyncSnapshot(
1162     const std::string& componentId, const NG::SnapshotOptions& options)
1163 {
1164 #ifdef ENABLE_ROSEN_BACKEND
1165     return NG::ComponentSnapshot::GetSync(componentId, options);
1166 #endif
1167     return {ERROR_CODE_INTERNAL_ERROR, nullptr};
1168 }
1169 
GetContentInfo()1170 std::string FrontendDelegateDeclarativeNG::GetContentInfo()
1171 {
1172     auto jsonContentInfo = JsonUtil::Create(true);
1173 
1174     CHECK_NULL_RETURN(pageRouterManager_, "");
1175     jsonContentInfo->Put("stackInfo", pageRouterManager_->GetStackInfo());
1176 
1177     auto pipelineContext = pipelineContextHolder_.Get();
1178     CHECK_NULL_RETURN(pipelineContext, jsonContentInfo->ToString());
1179     jsonContentInfo->Put("nodeInfo", pipelineContext->GetStoredNodeInfo());
1180 
1181     return jsonContentInfo->ToString();
1182 }
1183 
CreateSnapshot(std::function<void ()> && customBuilder,NG::ComponentSnapshot::JsCallback && callback,bool enableInspector,const NG::SnapshotParam & param)1184 void FrontendDelegateDeclarativeNG::CreateSnapshot(
1185     std::function<void()>&& customBuilder, NG::ComponentSnapshot::JsCallback&& callback, bool enableInspector,
1186     const NG::SnapshotParam& param)
1187 {
1188 #ifdef ENABLE_ROSEN_BACKEND
1189     ViewStackModel::GetInstance()->NewScope();
1190     CHECK_NULL_VOID(customBuilder);
1191     customBuilder();
1192     auto customNode = ViewStackModel::GetInstance()->Finish();
1193 
1194     NG::ComponentSnapshot::Create(customNode, std::move(callback), enableInspector, param);
1195 #endif
1196 }
1197 
AddFrameNodeToOverlay(const RefPtr<NG::FrameNode> & node,std::optional<int32_t> index)1198 void FrontendDelegateDeclarativeNG::AddFrameNodeToOverlay(
1199     const RefPtr<NG::FrameNode>& node, std::optional<int32_t> index)
1200 {
1201     auto task = [node, index, containerId = Container::CurrentId()](const RefPtr<NG::OverlayManager>& overlayManager) {
1202         CHECK_NULL_VOID(overlayManager);
1203         ContainerScope scope(containerId);
1204         overlayManager->AddFrameNodeToOverlay(node, index);
1205     };
1206     MainWindowOverlay(std::move(task), "ArkUIOverlayAddFrameNode");
1207 }
1208 
RemoveFrameNodeOnOverlay(const RefPtr<NG::FrameNode> & node)1209 void FrontendDelegateDeclarativeNG::RemoveFrameNodeOnOverlay(const RefPtr<NG::FrameNode>& node)
1210 {
1211     auto task = [node, containerId = Container::CurrentId()](const RefPtr<NG::OverlayManager>& overlayManager) {
1212         CHECK_NULL_VOID(overlayManager);
1213         ContainerScope scope(containerId);
1214         overlayManager->RemoveFrameNodeOnOverlay(node);
1215     };
1216     MainWindowOverlay(std::move(task), "ArkUIOverlayRemoveFrameNode");
1217 }
1218 
ShowNodeOnOverlay(const RefPtr<NG::FrameNode> & node)1219 void FrontendDelegateDeclarativeNG::ShowNodeOnOverlay(const RefPtr<NG::FrameNode>& node)
1220 {
1221     auto task = [node, containerId = Container::CurrentId()](const RefPtr<NG::OverlayManager>& overlayManager) {
1222         CHECK_NULL_VOID(overlayManager);
1223         ContainerScope scope(containerId);
1224         overlayManager->ShowNodeOnOverlay(node);
1225     };
1226     MainWindowOverlay(std::move(task), "ArkUIOverlayShowNode");
1227 }
1228 
HideNodeOnOverlay(const RefPtr<NG::FrameNode> & node)1229 void FrontendDelegateDeclarativeNG::HideNodeOnOverlay(const RefPtr<NG::FrameNode>& node)
1230 {
1231     auto task = [node, containerId = Container::CurrentId()](const RefPtr<NG::OverlayManager>& overlayManager) {
1232         CHECK_NULL_VOID(overlayManager);
1233         ContainerScope scope(containerId);
1234         overlayManager->HideNodeOnOverlay(node);
1235     };
1236     MainWindowOverlay(std::move(task), "ArkUIOverlayHideNode");
1237 }
1238 
ShowAllNodesOnOverlay()1239 void FrontendDelegateDeclarativeNG::ShowAllNodesOnOverlay()
1240 {
1241     auto task = [containerId = Container::CurrentId()](const RefPtr<NG::OverlayManager>& overlayManager) {
1242         CHECK_NULL_VOID(overlayManager);
1243         ContainerScope scope(containerId);
1244         overlayManager->ShowAllNodesOnOverlay();
1245     };
1246     MainWindowOverlay(std::move(task), "ArkUIOverlayShowAllNodes");
1247 }
1248 
HideAllNodesOnOverlay()1249 void FrontendDelegateDeclarativeNG::HideAllNodesOnOverlay()
1250 {
1251     auto task = [containerId = Container::CurrentId()](const RefPtr<NG::OverlayManager>& overlayManager) {
1252         CHECK_NULL_VOID(overlayManager);
1253         ContainerScope scope(containerId);
1254         overlayManager->HideAllNodesOnOverlay();
1255     };
1256     MainWindowOverlay(std::move(task), "ArkUIOverlayHideAllNodes");
1257 }
1258 } // namespace OHOS::Ace::Framework
1259