• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "frameworks/bridge/js_frontend/frontend_delegate_impl.h"
17 
18 #include <atomic>
19 #include <regex>
20 #include <string>
21 
22 #include "base/i18n/localization.h"
23 #include "base/log/ace_trace.h"
24 #include "base/log/event_report.h"
25 #include "base/resource/ace_res_config.h"
26 #include "base/thread/background_task_executor.h"
27 #include "base/utils/utils.h"
28 #include "base/utils/measure_util.h"
29 #include "core/common/ace_application_info.h"
30 #include "core/common/platform_bridge.h"
31 #include "core/common/thread_checker.h"
32 #include "core/components/toast/toast_component.h"
33 #include "frameworks/bridge/common/manifest/manifest_parser.h"
34 #include "frameworks/bridge/common/utils/utils.h"
35 #include "frameworks/bridge/js_frontend/js_ace_page.h"
36 
37 namespace OHOS::Ace::Framework {
38 namespace {
39 
40 constexpr int32_t INVALID_PAGE_ID = -1;
41 constexpr int32_t MAX_ROUTER_STACK = 32;
42 constexpr int32_t TOAST_TIME_MAX = 10000;    // ms
43 constexpr int32_t TOAST_TIME_DEFAULT = 1500; // ms
44 constexpr int32_t MAX_PAGE_ID_SIZE = sizeof(uint64_t) * 8;
45 constexpr int32_t NANO_TO_MILLI = 1000000; // nanosecond to millisecond
46 constexpr int32_t TO_MILLI = 1000;         // second to millisecond
47 constexpr int32_t COMPATIBLE_VERSION = 7;
48 constexpr int32_t WEB_FEATURE_VERSION = 6;
49 
50 const char MANIFEST_JSON[] = "manifest.json";
51 const char FILE_TYPE_JSON[] = ".json";
52 const char I18N_FOLDER[] = "i18n/";
53 const char RESOURCES_FOLDER[] = "resources/";
54 const char STYLES_FOLDER[] = "styles/";
55 const char I18N_FILE_SUFFIX[] = "/properties/i18n.json";
56 
57 } // namespace
58 
GenerateNextPageId()59 int32_t FrontendDelegateImpl::GenerateNextPageId()
60 {
61     for (int32_t idx = 0; idx < MAX_PAGE_ID_SIZE; ++idx) {
62         uint64_t bitMask = (1ULL << idx);
63         if ((bitMask & pageIdPool_.fetch_or(bitMask, std::memory_order_relaxed)) == 0) {
64             return idx;
65         }
66     }
67     return INVALID_PAGE_ID;
68 }
69 
RecyclePageId(int32_t pageId)70 void FrontendDelegateImpl::RecyclePageId(int32_t pageId)
71 {
72     if (pageId < 0 && pageId >= MAX_PAGE_ID_SIZE) {
73         return;
74     }
75     uint64_t bitMask = (1ULL << pageId);
76     pageIdPool_.fetch_and(~bitMask, std::memory_order_relaxed);
77 }
78 
FrontendDelegateImpl(const FrontendDelegateImplBuilder & builder)79 FrontendDelegateImpl::FrontendDelegateImpl(const FrontendDelegateImplBuilder& builder)
80     : loadJs_(builder.loadCallback), dispatcherCallback_(builder.transferCallback),
81       asyncEvent_(builder.asyncEventCallback), syncEvent_(builder.syncEventCallback),
82       externalEvent_(builder.externalEventCallback),
83       updatePage_(builder.updatePageCallback), resetStagingPage_(builder.resetStagingPageCallback),
84       destroyPage_(builder.destroyPageCallback), destroyApplication_(builder.destroyApplicationCallback),
85       updateApplicationState_(builder.updateApplicationStateCallback),
86       onStartContinuationCallBack_(builder.onStartContinuationCallBack),
87       onCompleteContinuationCallBack_(builder.onCompleteContinuationCallBack),
88       onRemoteTerminatedCallBack_(builder.onRemoteTerminatedCallBack),
89       onSaveDataCallBack_(builder.onSaveDataCallBack),
90       onRestoreDataCallBack_(builder.onRestoreDataCallBack),
91       timer_(builder.timerCallback), mediaQueryCallback_(builder.mediaQueryCallback),
92       requestAnimationCallback_(builder.requestAnimationCallback), jsCallback_(builder.jsCallback),
93       manifestParser_(AceType::MakeRefPtr<ManifestParser>()),
94       jsAccessibilityManager_(AccessibilityNodeManager::Create()),
95       mediaQueryInfo_(AceType::MakeRefPtr<MediaQueryInfo>()), taskExecutor_(builder.taskExecutor),
96       callNativeHandler_(builder.callNativeHandler)
97 {}
98 
~FrontendDelegateImpl()99 FrontendDelegateImpl::~FrontendDelegateImpl()
100 {
101     CHECK_RUN_ON(JS);
102     LOG_DESTROY();
103 }
104 
ParseManifest()105 void FrontendDelegateImpl::ParseManifest()
106 {
107     std::call_once(onceFlag_, [weak = AceType::WeakClaim(this)]() {
108         std::string jsonContent;
109         auto delegate = weak.Upgrade();
110         if (delegate) {
111             if (!delegate->GetAssetContent(MANIFEST_JSON, jsonContent)) {
112                 LOGE("RunPage parse manifest.json failed");
113                 EventReport::SendFormException(FormExcepType::RUN_PAGE_ERR);
114                 return;
115             }
116             delegate->manifestParser_->Parse(jsonContent);
117             auto task = [delegate]() {
118                 delegate->pipelineContextHolder_.Get(); // Wait until Pipeline Context is attached.
119                 delegate->manifestParser_->GetAppInfo()->ParseI18nJsonInfo();
120             };
121             delegate->taskExecutor_->PostTask(task, TaskExecutor::TaskType::JS);
122         }
123     });
124 }
125 
RunPage(const std::string & url,const std::string & params)126 void FrontendDelegateImpl::RunPage(const std::string& url, const std::string& params)
127 {
128     ACE_SCOPED_TRACE("FrontendDelegateImpl::RunPage");
129 
130     auto routerBackCallback = [weak = WeakClaim(this)](const std::string& urlPath) {
131         auto delegate = weak.Upgrade();
132         if (!delegate) {
133             return false;
134         }
135         delegate->Push(urlPath, "");
136         return true;
137     };
138     DelegateClient::GetInstance().RegisterRouterPushCallback(routerBackCallback);
139 
140     auto getWebPageUrlCallback = [weak = WeakClaim(this)](std::string& pageUrl, int32_t& pageId) {
141         auto delegate = weak.Upgrade();
142         if (!delegate) {
143             return false;
144         }
145         pageUrl = delegate->GetRunningPageUrl();
146         pageId = delegate->GetRunningPageId();
147         return true;
148     };
149     DelegateClient::GetInstance().RegisterGetWebPageUrlCallback(getWebPageUrlCallback);
150 
151     auto isPagePathInvalidCallback = [weak = WeakClaim(this)](bool& isPageEmpty) {
152         auto delegate = weak.Upgrade();
153         if (!delegate) {
154             return false;
155         }
156         isPageEmpty = delegate->GetPagePathInvalidFlag();
157         return true;
158     };
159     DelegateClient::GetInstance().RegisterIsPagePathInvalidCallback(isPagePathInvalidCallback);
160 
161     LOGD("FrontendDelegateImpl RunPage url=%{private}s", url.c_str());
162     ParseManifest();
163     if (!url.empty()) {
164         mainPagePath_ = manifestParser_->GetRouter()->GetPagePath(url);
165         if (mainPagePath_.empty()) {
166             mainPagePath_ = manifestParser_->GetRouter()->GetEntry();
167         }
168     } else {
169         mainPagePath_ = manifestParser_->GetRouter()->GetEntry();
170     }
171     LoadPage(GenerateNextPageId(), mainPagePath_, true, params);
172 }
173 
ChangeLocale(const std::string & language,const std::string & countryOrRegion)174 void FrontendDelegateImpl::ChangeLocale(const std::string& language, const std::string& countryOrRegion)
175 {
176     LOGD("JsFrontend ChangeLocale");
177     taskExecutor_->PostTask(
178         [language, countryOrRegion]() { AceApplicationInfo::GetInstance().ChangeLocale(language, countryOrRegion); },
179         TaskExecutor::TaskType::PLATFORM);
180 }
181 
GetI18nData(std::unique_ptr<JsonValue> & json)182 void FrontendDelegateImpl::GetI18nData(std::unique_ptr<JsonValue>& json)
183 {
184     auto data = JsonUtil::CreateArray(true);
185     GetConfigurationCommon(I18N_FOLDER, data);
186     auto i18nData = JsonUtil::Create(true);
187     i18nData->Put("resources", data);
188     json->Put("i18n", i18nData);
189 }
190 
GetResourceConfiguration(std::unique_ptr<JsonValue> & json)191 void FrontendDelegateImpl::GetResourceConfiguration(std::unique_ptr<JsonValue>& json)
192 {
193     auto data = JsonUtil::CreateArray(true);
194     GetConfigurationCommon(RESOURCES_FOLDER, data);
195     json->Put("resourcesConfiguration", data);
196 }
197 
GetConfigurationCommon(const std::string & filePath,std::unique_ptr<JsonValue> & data)198 void FrontendDelegateImpl::GetConfigurationCommon(const std::string& filePath, std::unique_ptr<JsonValue>& data)
199 {
200     std::vector<std::string> files;
201     if (assetManager_) {
202         assetManager_->GetAssetList(filePath, files);
203     }
204 
205     std::vector<std::string> fileNameList;
206     for (const auto& file : files) {
207         if (EndWith(file, FILE_TYPE_JSON) && !StartWith(file, STYLES_FOLDER)) {
208             fileNameList.emplace_back(file.substr(0, file.size() - (sizeof(FILE_TYPE_JSON) - 1)));
209         }
210     }
211 
212     std::vector<std::string> priorityFileName;
213     if (filePath.compare(I18N_FOLDER) == 0) {
214         auto localeTag = AceApplicationInfo::GetInstance().GetLocaleTag();
215         priorityFileName = AceResConfig::GetLocaleFallback(localeTag, fileNameList);
216     } else {
217         priorityFileName = AceResConfig::GetResourceFallback(fileNameList);
218     }
219 
220     for (const auto& fileName : priorityFileName) {
221         auto fileFullPath = filePath + fileName + std::string(FILE_TYPE_JSON);
222         std::string content;
223         if (GetAssetContent(fileFullPath, content)) {
224             auto fileData = ParseFileData(content);
225             if (fileData == nullptr) {
226                 LOGW("parse %{private}s.json i18n content failed", filePath.c_str());
227             } else {
228                 data->Put(fileData);
229             }
230         }
231     }
232 }
233 
OnJsCallback(const std::string & callbackId,const std::string & data)234 void FrontendDelegateImpl::OnJsCallback(const std::string& callbackId, const std::string& data)
235 {
236     taskExecutor_->PostTask(
237         [weak = AceType::WeakClaim(this), callbackId, args = std::move(data)] {
238             auto delegate = weak.Upgrade();
239             if (delegate) {
240                 delegate->jsCallback_(callbackId, args);
241             }
242         },
243         TaskExecutor::TaskType::JS);
244 }
245 
SetJsMessageDispatcher(const RefPtr<JsMessageDispatcher> & dispatcher) const246 void FrontendDelegateImpl::SetJsMessageDispatcher(const RefPtr<JsMessageDispatcher>& dispatcher) const
247 {
248     LOGD("JsFrontend SetJsMessageDispatcher");
249     taskExecutor_->PostTask([dispatcherCallback = dispatcherCallback_, dispatcher] { dispatcherCallback(dispatcher); },
250         TaskExecutor::TaskType::JS);
251 }
252 
TransferComponentResponseData(int32_t callbackId,int32_t code,std::vector<uint8_t> && data)253 void FrontendDelegateImpl::TransferComponentResponseData(int32_t callbackId, int32_t code, std::vector<uint8_t>&& data)
254 {
255     LOGD("JsFrontend TransferComponentResponseData");
256     WeakPtr<PipelineBase> contextWeak(pipelineContextHolder_.Get());
257     taskExecutor_->PostTask(
258         [callbackId, data = std::move(data), contextWeak]() mutable {
259             auto context = contextWeak.Upgrade();
260             if (!context) {
261                 LOGE("context is null");
262             } else if (!context->GetMessageBridge()) {
263                 LOGE("messageBridge is null");
264             } else {
265                 context->GetMessageBridge()->HandleCallback(callbackId, std::move(data));
266             }
267         },
268         TaskExecutor::TaskType::UI);
269 }
270 
TransferJsResponseData(int32_t callbackId,int32_t code,std::vector<uint8_t> && data) const271 void FrontendDelegateImpl::TransferJsResponseData(int32_t callbackId, int32_t code, std::vector<uint8_t>&& data) const
272 {
273     LOGD("JsFrontend TransferJsResponseData");
274     auto weak = AceType::WeakClaim(AceType::RawPtr(groupJsBridge_));
275     taskExecutor_->PostTask([callbackId, code, data = std::move(data), weak]() mutable {
276         auto groupJsBridge = weak.Upgrade();
277         if (groupJsBridge) {
278             groupJsBridge->TriggerModuleJsCallback(callbackId, code, std::move(data));
279         }
280     }, TaskExecutor::TaskType::JS);
281 }
282 
283 #if defined(PREVIEW)
TransferJsResponseDataPreview(int32_t callbackId,int32_t code,ResponseData responseData) const284 void FrontendDelegateImpl::TransferJsResponseDataPreview(
285     int32_t callbackId, int32_t code, ResponseData responseData) const
286 {
287     LOGI("JsFrontend TransferJsResponseDataPreview");
288     auto weak = AceType::WeakClaim(AceType::RawPtr(groupJsBridge_));
289     taskExecutor_->PostTask([callbackId, code, responseData, weak]() mutable {
290         auto groupJsBridge = weak.Upgrade();
291         if (groupJsBridge) {
292             groupJsBridge->TriggerModuleJsCallbackPreview(callbackId, code, responseData);
293         }
294     }, TaskExecutor::TaskType::JS);
295 }
296 #endif
297 
TransferJsPluginGetError(int32_t callbackId,int32_t errorCode,std::string && errorMessage) const298 void FrontendDelegateImpl::TransferJsPluginGetError(
299     int32_t callbackId, int32_t errorCode, std::string&& errorMessage) const
300 {
301     LOGD("JsFrontend TransferJsPluginGetError");
302     auto weak = AceType::WeakClaim(AceType::RawPtr(groupJsBridge_));
303     taskExecutor_->PostTask([callbackId, errorCode, errorMessage = std::move(errorMessage), weak]() mutable {
304         auto groupJsBridge = weak.Upgrade();
305         if (groupJsBridge) {
306             groupJsBridge->TriggerModulePluginGetErrorCallback(callbackId, errorCode, std::move(errorMessage));
307         }
308     }, TaskExecutor::TaskType::JS);
309 }
310 
TransferJsEventData(int32_t callbackId,int32_t code,std::vector<uint8_t> && data) const311 void FrontendDelegateImpl::TransferJsEventData(int32_t callbackId, int32_t code, std::vector<uint8_t>&& data) const
312 {
313     auto weak = AceType::WeakClaim(AceType::RawPtr(groupJsBridge_));
314     taskExecutor_->PostTask([callbackId, code, data = std::move(data), weak]() mutable {
315         auto groupJsBridge = weak.Upgrade();
316         if (groupJsBridge) {
317             groupJsBridge->TriggerEventJsCallback(callbackId, code, std::move(data));
318         }
319     }, TaskExecutor::TaskType::JS);
320 }
321 
LoadPluginJsCode(std::string && jsCode) const322 void FrontendDelegateImpl::LoadPluginJsCode(std::string&& jsCode) const
323 {
324     auto weak = AceType::WeakClaim(AceType::RawPtr(groupJsBridge_));
325     taskExecutor_->PostTask([jsCode = std::move(jsCode), weak]() mutable {
326         auto groupJsBridge = weak.Upgrade();
327         if (groupJsBridge) {
328             groupJsBridge->LoadPluginJsCode(std::move(jsCode));
329         }
330     }, TaskExecutor::TaskType::JS);
331 }
332 
LoadPluginJsByteCode(std::vector<uint8_t> && jsCode,std::vector<int32_t> && jsCodeLen) const333 void FrontendDelegateImpl::LoadPluginJsByteCode(std::vector<uint8_t>&& jsCode, std::vector<int32_t>&& jsCodeLen) const
334 {
335     LOGD("JsFrontend LoadPluginJsByteCode");
336     auto weak = AceType::WeakClaim(AceType::RawPtr(groupJsBridge_));
337     taskExecutor_->PostTask([jsCode = std::move(jsCode), jsCodeLen = std::move(jsCodeLen), weak]() mutable {
338         auto groupJsBridge = weak.Upgrade();
339         if (groupJsBridge) {
340             groupJsBridge->LoadPluginJsByteCode(std::move(jsCode), std::move(jsCodeLen));
341         }
342     }, TaskExecutor::TaskType::JS);
343 }
344 
OnPageBackPress()345 bool FrontendDelegateImpl::OnPageBackPress()
346 {
347     bool result = FireSyncEvent("_root", std::string("\"clickbackitem\","), std::string(""));
348     LOGD("OnPageBackPress: jsframework callback result: %{public}d", result);
349     return result;
350 }
351 
OnActive()352 void FrontendDelegateImpl::OnActive()
353 {
354     LOGD("JsFrontend onActive");
355     FireAsyncEvent("_root", std::string("\"viewactive\",null,null"), std::string(""));
356 }
357 
OnInactive()358 void FrontendDelegateImpl::OnInactive()
359 {
360     LOGD("JsFrontend OnInactive");
361     FireAsyncEvent("_root", std::string("\"viewinactive\",null,null"), std::string(""));
362     FireAsyncEvent("_root", std::string("\"viewsuspended\",null,null"), std::string(""));
363 }
364 
OnBackGround()365 void FrontendDelegateImpl::OnBackGround()
366 {
367     OnPageHide();
368 }
369 
OnForeground()370 void FrontendDelegateImpl::OnForeground()
371 {
372     // first page show will be called by push page successfully
373     if (!isFirstNotifyShow_) {
374         OnPageShow();
375     }
376     isFirstNotifyShow_ = false;
377 }
378 
OnStartContinuation()379 bool FrontendDelegateImpl::OnStartContinuation()
380 {
381     bool ret = false;
382     taskExecutor_->PostSyncTask([weak = AceType::WeakClaim(this), &ret] {
383         auto delegate = weak.Upgrade();
384         if (delegate && delegate->onStartContinuationCallBack_) {
385             ret = delegate->onStartContinuationCallBack_();
386         }
387     }, TaskExecutor::TaskType::JS);
388     if (!ret) {
389         ret = FireSyncEvent("_root", std::string("\"onStartContinuation\","), std::string(""));
390     }
391     return ret;
392 }
393 
OnCompleteContinuation(int32_t code)394 void FrontendDelegateImpl::OnCompleteContinuation(int32_t code)
395 {
396     taskExecutor_->PostSyncTask([weak = AceType::WeakClaim(this), code] {
397         auto delegate = weak.Upgrade();
398         if (delegate && delegate->onCompleteContinuationCallBack_) {
399             delegate->onCompleteContinuationCallBack_(code);
400         }
401     }, TaskExecutor::TaskType::JS);
402     FireSyncEvent("_root", std::string("\"onCompleteContinuation\","), std::to_string(code));
403 }
404 
OnRemoteTerminated()405 void FrontendDelegateImpl::OnRemoteTerminated()
406 {
407     taskExecutor_->PostSyncTask([weak = AceType::WeakClaim(this)] {
408         auto delegate = weak.Upgrade();
409         if (delegate && delegate->onRemoteTerminatedCallBack_) {
410             delegate->onRemoteTerminatedCallBack_();
411         }
412     }, TaskExecutor::TaskType::JS);
413 }
414 
OnSaveData(std::string & data)415 void FrontendDelegateImpl::OnSaveData(std::string& data)
416 {
417     std::string savedData;
418     taskExecutor_->PostSyncTask([weak = AceType::WeakClaim(this), &savedData] {
419         auto delegate = weak.Upgrade();
420         if (delegate && delegate->onSaveDataCallBack_) {
421             delegate->onSaveDataCallBack_(savedData);
422         }
423     }, TaskExecutor::TaskType::JS);
424     if (savedData.empty()) {
425         FireSyncEvent("_root", std::string("\"onSaveData\","), std::string(""), savedData);
426     }
427     std::string pageUri = GetRunningPageUrl();
428     data = std::string("{\"url\":\"").append(pageUri).append("\",\"__remoteData\":").append(savedData).append("}");
429 }
430 
OnRestoreData(const std::string & data)431 bool FrontendDelegateImpl::OnRestoreData(const std::string& data)
432 {
433     bool ret = false;
434     taskExecutor_->PostSyncTask([weak = AceType::WeakClaim(this), &data, &ret] {
435         auto delegate = weak.Upgrade();
436         if (delegate && delegate->onRestoreDataCallBack_) {
437             ret = delegate->onRestoreDataCallBack_(data);
438         }
439     }, TaskExecutor::TaskType::JS);
440     FireSyncEvent("_root", std::string("\"onSaveData\","), data);
441     return ret;
442 }
443 
OnNewRequest(const std::string & data)444 void FrontendDelegateImpl::OnNewRequest(const std::string& data)
445 {
446     FireSyncEvent("_root", std::string("\"onNewRequest\","), data);
447 }
448 
CallPopPage()449 void FrontendDelegateImpl::CallPopPage()
450 {
451     std::lock_guard<std::mutex> lock(mutex_);
452     auto& currentPage = pageRouteStack_.back();
453     if (!pageRouteStack_.empty() && currentPage.alertCallback) {
454         backUri_ = "";
455         taskExecutor_->PostTask(
456             [context = AceType::DynamicCast<PipelineContext>(pipelineContextHolder_.Get()),
457                 dialogProperties = pageRouteStack_.back().dialogProperties,
458                 isRightToLeft = AceApplicationInfo::GetInstance().IsRightToLeft()]() {
459                 if (context) {
460                     context->ShowDialog(dialogProperties, isRightToLeft);
461                 }
462             },
463             TaskExecutor::TaskType::UI);
464     } else {
465         PopPage();
466     }
467 }
468 
ResetStagingPage()469 void FrontendDelegateImpl::ResetStagingPage()
470 {
471     taskExecutor_->PostTask([resetStagingPage = resetStagingPage_] { resetStagingPage(); }, TaskExecutor::TaskType::JS);
472 }
473 
OnApplicationDestroy(const std::string & packageName)474 void FrontendDelegateImpl::OnApplicationDestroy(const std::string& packageName)
475 {
476     taskExecutor_->PostSyncTask(
477         [destroyApplication = destroyApplication_, packageName] { destroyApplication(packageName); },
478         TaskExecutor::TaskType::JS);
479 }
480 
OnApplicationUpdateState(const std::string & packageName,Frontend::State state)481 void FrontendDelegateImpl::OnApplicationUpdateState(const std::string& packageName, Frontend::State state)
482 {
483     taskExecutor_->PostSyncTask(
484         [updateApplication = updateApplicationState_, packageName, state] { updateApplication(packageName, state); },
485         TaskExecutor::TaskType::JS);
486 }
487 
FireAsyncEvent(const std::string & eventId,const std::string & param,const std::string & jsonArgs)488 void FrontendDelegateImpl::FireAsyncEvent(
489     const std::string& eventId, const std::string& param, const std::string& jsonArgs)
490 {
491     LOGD("FireAsyncEvent eventId: %{public}s", eventId.c_str());
492     std::string args = param;
493     args.append(",null").append(",null"); // callback and dom changes
494     if (!jsonArgs.empty()) {
495         args.append(",").append(jsonArgs); // method args
496     }
497     taskExecutor_->PostTask(
498         [weak = AceType::WeakClaim(this), eventId, args = std::move(args)] {
499             auto delegate = weak.Upgrade();
500             if (delegate) {
501                 delegate->asyncEvent_(eventId, args);
502             }
503         },
504         TaskExecutor::TaskType::JS);
505 }
506 
FireSyncEvent(const std::string & eventId,const std::string & param,const std::string & jsonArgs)507 bool FrontendDelegateImpl::FireSyncEvent(
508     const std::string& eventId, const std::string& param, const std::string& jsonArgs)
509 {
510     std::string resultStr;
511     FireSyncEvent(eventId, param, jsonArgs, resultStr);
512     return (resultStr == "true");
513 }
514 
FireSyncEvent(const std::string & eventId,const std::string & param,const std::string & jsonArgs,std::string & result)515 void FrontendDelegateImpl::FireSyncEvent(
516     const std::string& eventId, const std::string& param, const std::string& jsonArgs, std::string& result)
517 {
518     int32_t callbackId = callbackCnt_++;
519     std::string args = param;
520     args.append("{\"_callbackId\":\"").append(std::to_string(callbackId)).append("\"}").append(",null");
521     if (!jsonArgs.empty()) {
522         args.append(",").append(jsonArgs); // method args
523     }
524     taskExecutor_->PostSyncTask(
525         [weak = AceType::WeakClaim(this), eventId, args = std::move(args)] {
526             auto delegate = weak.Upgrade();
527             if (delegate) {
528                 delegate->syncEvent_(eventId, args);
529             }
530         },
531         TaskExecutor::TaskType::JS);
532 
533     result = jsCallBackResult_[callbackId];
534     LOGD("FireSyncEvent eventId: %{public}s, callbackId: %{public}d", eventId.c_str(), callbackId);
535     jsCallBackResult_.erase(callbackId);
536 }
537 
FireExternalEvent(const std::string & eventId,const std::string & componentId,const uint32_t nodeId,const bool isDestroy)538 void FrontendDelegateImpl::FireExternalEvent(
539     const std::string& eventId, const std::string& componentId, const uint32_t nodeId, const bool isDestroy)
540 {
541     taskExecutor_->PostSyncTask(
542         [weak = AceType::WeakClaim(this), componentId, nodeId, isDestroy] {
543             auto delegate = weak.Upgrade();
544             if (delegate) {
545                 delegate->externalEvent_(componentId, nodeId, isDestroy);
546             }
547         },
548         TaskExecutor::TaskType::JS);
549 }
550 
FireAccessibilityEvent(const AccessibilityEvent & accessibilityEvent)551 void FrontendDelegateImpl::FireAccessibilityEvent(const AccessibilityEvent& accessibilityEvent)
552 {
553     jsAccessibilityManager_->SendAccessibilityAsyncEvent(accessibilityEvent);
554 }
555 
InitializeAccessibilityCallback()556 void FrontendDelegateImpl::InitializeAccessibilityCallback()
557 {
558     jsAccessibilityManager_->InitializeCallback();
559 }
560 
561 // Start FrontendDelegate overrides.
Push(const std::string & uri,const std::string & params)562 void FrontendDelegateImpl::Push(const std::string& uri, const std::string& params)
563 {
564     if (uri.empty()) {
565         LOGE("router.Push uri is empty");
566         return;
567     }
568     if (isRouteStackFull_) {
569         LOGE("the router stack has reached its max size, you can't push any more pages.");
570         EventReport::SendPageRouterException(PageRouterExcepType::PAGE_STACK_OVERFLOW_ERR, uri);
571         return;
572     }
573     std::string pagePath = manifestParser_->GetRouter()->GetPagePath(uri);
574     LOGD("router.Push pagePath = %{private}s", pagePath.c_str());
575     if (!pagePath.empty()) {
576         isPagePathInvalid_ = true;
577         LoadPage(GenerateNextPageId(), pagePath, false, params);
578     } else {
579         isPagePathInvalid_ = false;
580         LOGW("[Engine Log] this uri not support in route push.");
581     }
582 
583     if (taskExecutor_) {
584         taskExecutor_->PostTask(
585             [context = pipelineContextHolder_.Get(), isPagePathInvalid = isPagePathInvalid_]() {
586                 if (context) {
587                     context->NotifyIsPagePathInvalidDismiss(isPagePathInvalid);
588                 }
589             },
590             TaskExecutor::TaskType::UI);
591     }
592 }
593 
Replace(const std::string & uri,const std::string & params)594 void FrontendDelegateImpl::Replace(const std::string& uri, const std::string& params)
595 {
596     if (uri.empty()) {
597         LOGE("router.Replace uri is empty");
598         return;
599     }
600 
601     std::string pagePath = manifestParser_->GetRouter()->GetPagePath(uri);
602     LOGD("router.Replace pagePath = %{private}s", pagePath.c_str());
603     if (!pagePath.empty()) {
604         LoadReplacePage(GenerateNextPageId(), pagePath, params);
605     } else {
606         LOGW("[Engine Log] this uri not support in route replace.");
607     }
608 }
609 
Back(const std::string & uri,const std::string & params)610 void FrontendDelegateImpl::Back(const std::string& uri, const std::string& params)
611 {
612     auto pipelineContext = pipelineContextHolder_.Get();
613     {
614         std::lock_guard<std::mutex> lock(mutex_);
615         auto& currentPage = pageRouteStack_.back();
616         if (!pageRouteStack_.empty() && currentPage.alertCallback) {
617             backUri_ = uri;
618             backParam_ = params;
619             taskExecutor_->PostTask(
620                 [context = AceType::DynamicCast<PipelineContext>(pipelineContextHolder_.Get()),
621                     dialogProperties = pageRouteStack_.back().dialogProperties,
622                     isRightToLeft = AceApplicationInfo::GetInstance().IsRightToLeft()]() {
623                     if (context) {
624                         context->ShowDialog(dialogProperties, isRightToLeft);
625                     }
626                 },
627                 TaskExecutor::TaskType::UI);
628             return;
629         }
630     }
631     BackImplement(uri, params);
632 }
633 
BackImplement(const std::string & uri,const std::string & params)634 void FrontendDelegateImpl::BackImplement(const std::string& uri, const std::string& params)
635 {
636     LOGD("router.Back path = %{private}s", uri.c_str());
637     if (uri.empty()) {
638         PopPage();
639     } else {
640         std::string pagePath = manifestParser_->GetRouter()->GetPagePath(uri);
641         pageId_ = GetPageIdByUrl(pagePath);
642         LOGD("router.Back pagePath = %{private}s", pagePath.c_str());
643         if (!pagePath.empty()) {
644             if (!params.empty()) {
645                 std::lock_guard<std::mutex> lock(mutex_);
646                 pageParamMap_[pageId_] = params;
647             }
648             PopToPage(pagePath);
649         } else {
650             LOGW("[Engine Log] this uri not support in route Back.");
651         }
652     }
653 
654     taskExecutor_->PostTask(
655         [context = pipelineContextHolder_.Get()]() {
656             if (context) {
657                 context->NotifyRouterBackDismiss();
658             }
659         },
660         TaskExecutor::TaskType::UI);
661 }
662 
PostponePageTransition()663 void FrontendDelegateImpl::PostponePageTransition()
664 {
665     std::lock_guard<std::mutex> lock(mutex_);
666     taskExecutor_->PostTask(
667         [context = pipelineContextHolder_.Get()]() {
668             if (context) {
669                 context->PostponePageTransition();
670             }
671         },
672         TaskExecutor::TaskType::UI);
673 }
674 
LaunchPageTransition()675 void FrontendDelegateImpl::LaunchPageTransition()
676 {
677     std::lock_guard<std::mutex> lock(mutex_);
678     taskExecutor_->PostTask(
679         [context = pipelineContextHolder_.Get()]() {
680             if (context) {
681                 context->LaunchPageTransition();
682             }
683         },
684         TaskExecutor::TaskType::UI);
685 }
686 
Clear()687 void FrontendDelegateImpl::Clear()
688 {
689     ClearInvisiblePages();
690 }
691 
GetStackSize() const692 int32_t FrontendDelegateImpl::GetStackSize() const
693 {
694     std::lock_guard<std::mutex> lock(mutex_);
695     return static_cast<int32_t>(pageRouteStack_.size());
696 }
697 
GetState(int32_t & index,std::string & name,std::string & path)698 void FrontendDelegateImpl::GetState(int32_t& index, std::string& name, std::string& path)
699 {
700     std::string url;
701     {
702         std::lock_guard<std::mutex> lock(mutex_);
703         if (pageRouteStack_.empty()) {
704             return;
705         }
706         index = static_cast<int32_t>(pageRouteStack_.size());
707         url = pageRouteStack_.back().url;
708     }
709     auto pos = url.rfind(".js");
710     if (pos == url.length() - 3) {
711         url = url.substr(0, pos);
712     }
713     pos = url.rfind("/");
714     if (pos != std::string::npos) {
715         name = url.substr(pos + 1);
716         path = url.substr(0, pos + 1);
717     }
718 }
719 
GetComponentsCount()720 size_t FrontendDelegateImpl::GetComponentsCount()
721 {
722     std::lock_guard<std::mutex> lock(mutex_);
723     if (pageRouteStack_.empty()) {
724         return 0;
725     }
726     auto itPage = pageMap_.find(pageRouteStack_.back().pageId);
727     if (itPage == pageMap_.end()) {
728         return 0;
729     }
730     auto domDoc = itPage->second->GetDomDocument();
731     if (!domDoc) {
732         return 0;
733     }
734     return domDoc->GetComponentsCount();
735 }
736 
GetParams()737 std::string FrontendDelegateImpl::GetParams()
738 {
739     if (pageParamMap_.find(pageId_) != pageParamMap_.end()) {
740         return pageParamMap_.find(pageId_)->second;
741     } else {
742         return "";
743     }
744 }
745 
TriggerPageUpdate(int32_t pageId,bool directExecute)746 void FrontendDelegateImpl::TriggerPageUpdate(int32_t pageId, bool directExecute)
747 {
748     auto page = GetPage(pageId);
749     if (!page) {
750         return;
751     }
752 
753     auto jsPage = AceType::DynamicCast<Framework::JsAcePage>(page);
754     ACE_DCHECK(jsPage);
755 
756     // Pop all JS command and execute them in UI thread.
757     auto jsCommands = std::make_shared<std::vector<RefPtr<JsCommand>>>();
758     jsPage->PopAllCommands(*jsCommands);
759 
760     auto pipelineContext = AceType::DynamicCast<PipelineContext>(pipelineContextHolder_.Get());
761     WeakPtr<Framework::JsAcePage> jsPageWeak(jsPage);
762     WeakPtr<PipelineContext> contextWeak(pipelineContext);
763     auto updateTask = [weak = AceType::WeakClaim(this), jsPageWeak, contextWeak, jsCommands] {
764         ACE_SCOPED_TRACE("FlushUpdateCommands");
765         auto delegate = weak.Upgrade();
766         auto jsPage = jsPageWeak.Upgrade();
767         auto context = contextWeak.Upgrade();
768         if (!delegate || !jsPage || !context) {
769             LOGE("Page update failed. page or context is null.");
770             EventReport::SendPageRouterException(PageRouterExcepType::UPDATE_PAGE_ERR);
771             return;
772         }
773         bool useLiteStyle = delegate->GetMinPlatformVersion() < COMPATIBLE_VERSION && delegate->IsUseLiteStyle();
774         context->SetUseLiteStyle(useLiteStyle);
775         jsPage->SetUseLiteStyle(useLiteStyle);
776         jsPage->SetUseBoxWrap(delegate->GetMinPlatformVersion() >= WEB_FEATURE_VERSION);
777         // Flush all JS commands.
778         for (const auto& command : *jsCommands) {
779             command->Execute(jsPage);
780         }
781         if (jsPage->GetDomDocument()) {
782             jsPage->GetDomDocument()->HandleComponentPostBinding();
783         }
784         auto accessibilityManager = context->GetAccessibilityManager();
785         if (accessibilityManager) {
786             accessibilityManager->HandleComponentPostBinding();
787         }
788 
789         jsPage->ClearShowCommand();
790         std::vector<NodeId> dirtyNodes;
791         jsPage->PopAllDirtyNodes(dirtyNodes);
792         for (auto nodeId : dirtyNodes) {
793             auto patchComponent = jsPage->BuildPagePatch(nodeId);
794             if (patchComponent) {
795                 context->ScheduleUpdate(patchComponent);
796             }
797         }
798     };
799     auto weakContext = AceType::WeakClaim(AceType::RawPtr(pipelineContext));
800     taskExecutor_->PostTask([updateTask, weakContext, directExecute]() {
801         auto pipelineContext = weakContext.Upgrade();
802         if (pipelineContext) {
803             pipelineContext->AddPageUpdateTask(std::move(updateTask), directExecute);
804         }
805     }, TaskExecutor::TaskType::UI);
806 }
807 
PostJsTask(std::function<void ()> && task)808 void FrontendDelegateImpl::PostJsTask(std::function<void()>&& task)
809 {
810     taskExecutor_->PostTask(task, TaskExecutor::TaskType::JS);
811 }
812 
RemoveVisibleChangeNode(NodeId id)813 void FrontendDelegateImpl::RemoveVisibleChangeNode(NodeId id)
814 {
815     auto task = [nodeId = id, pipeline = AceType::DynamicCast<PipelineContext>(pipelineContextHolder_.Get())]() {
816         if (pipeline) {
817             pipeline->RemoveVisibleChangeNode(nodeId);
818         }
819     };
820     taskExecutor_->PostTask(task, TaskExecutor::TaskType::UI);
821 }
822 
GetAppID() const823 const std::string& FrontendDelegateImpl::GetAppID() const
824 {
825     return manifestParser_->GetAppInfo()->GetAppID();
826 }
827 
GetAppName() const828 const std::string& FrontendDelegateImpl::GetAppName() const
829 {
830     return manifestParser_->GetAppInfo()->GetAppName();
831 }
832 
GetVersionName() const833 const std::string& FrontendDelegateImpl::GetVersionName() const
834 {
835     return manifestParser_->GetAppInfo()->GetVersionName();
836 }
837 
GetVersionCode() const838 int32_t FrontendDelegateImpl::GetVersionCode() const
839 {
840     return manifestParser_->GetAppInfo()->GetVersionCode();
841 }
842 
GetWindowConfig()843 WindowConfig& FrontendDelegateImpl::GetWindowConfig()
844 {
845     ParseManifest();
846     return manifestParser_->GetWindowConfig();
847 }
848 
GetMinPlatformVersion()849 int32_t FrontendDelegateImpl::GetMinPlatformVersion()
850 {
851     ParseManifest();
852     return manifestParser_->GetMinPlatformVersion();
853 }
854 
IsUseLiteStyle()855 bool FrontendDelegateImpl::IsUseLiteStyle()
856 {
857     ParseManifest();
858     return manifestParser_->IsUseLiteStyle();
859 }
860 
IsWebFeature()861 bool FrontendDelegateImpl::IsWebFeature()
862 {
863     ParseManifest();
864     return manifestParser_->IsWebFeature();
865 }
866 
MeasureText(const MeasureContext & context)867 double FrontendDelegateImpl::MeasureText(const MeasureContext& context)
868 {
869     LOGD("FrontendDelegateImpl MeasureTxt.");
870     return MeasureUtil::MeasureText(context);
871 }
872 
MeasureTextSize(const MeasureContext & context)873 Size FrontendDelegateImpl::MeasureTextSize(const MeasureContext& context)
874 {
875     LOGD("FrontendDelegateImpl MeasureTxtSize.");
876     return MeasureUtil::MeasureTextSize(context);
877 }
878 
879 
ShowToast(const std::string & message,int32_t duration,const std::string & bottom)880 void FrontendDelegateImpl::ShowToast(const std::string& message, int32_t duration, const std::string& bottom)
881 {
882     LOGD("FrontendDelegateImpl ShowToast.");
883     int32_t durationTime = std::clamp(duration, TOAST_TIME_DEFAULT, TOAST_TIME_MAX);
884     auto pipelineContext = AceType::DynamicCast<PipelineContext>(pipelineContextHolder_.Get());
885     bool isRightToLeft = AceApplicationInfo::GetInstance().IsRightToLeft();
886     auto weak = AceType::WeakClaim(AceType::RawPtr(pipelineContext));
887     taskExecutor_->PostTask([durationTime, message, bottom, isRightToLeft, weak] {
888         ToastComponent::GetInstance().Show(weak.Upgrade(), message, durationTime, bottom, isRightToLeft);
889     }, TaskExecutor::TaskType::UI);
890 }
891 
GetBoundingRectData(NodeId nodeId)892 Rect FrontendDelegateImpl::GetBoundingRectData(NodeId nodeId)
893 {
894     Rect rect;
895     auto task = [context = pipelineContextHolder_.Get(), nodeId, &rect]() {
896         context->GetBoundingRectData(nodeId, rect);
897     };
898     PostSyncTaskToPage(task);
899     return rect;
900 }
901 
GetInspector(NodeId nodeId)902 std::string FrontendDelegateImpl::GetInspector(NodeId nodeId)
903 {
904     std::string attrs;
905     auto task = [weak = WeakClaim(AceType::RawPtr(jsAccessibilityManager_)), nodeId, &attrs]() {
906         auto accessibilityNodeManager = weak.Upgrade();
907         if (accessibilityNodeManager) {
908             attrs = accessibilityNodeManager->GetInspectorNodeById(nodeId);
909         }
910     };
911     PostSyncTaskToPage(task);
912     return attrs;
913 }
914 
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)915 void FrontendDelegateImpl::ShowDialog(const std::string& title, const std::string& message,
916     const std::vector<ButtonInfo>& buttons, bool autoCancel, std::function<void(int32_t, int32_t)>&& callback,
917     const std::set<std::string>& callbacks)
918 {
919     if (!taskExecutor_) {
920         LOGE("task executor is null.");
921         return;
922     }
923 
924     std::unordered_map<std::string, EventMarker> callbackMarkers;
925     if (callbacks.find(COMMON_SUCCESS) != callbacks.end()) {
926         auto successEventMarker = BackEndEventManager<void(int32_t)>::GetInstance().GetAvailableMarker();
927         BackEndEventManager<void(int32_t)>::GetInstance().BindBackendEvent(
928             successEventMarker, [callback, taskExecutor = taskExecutor_](int32_t successType) {
929                 taskExecutor->PostTask(
930                     [callback, successType]() { callback(0, successType); }, TaskExecutor::TaskType::JS);
931             });
932         callbackMarkers.emplace(COMMON_SUCCESS, successEventMarker);
933     }
934 
935     if (callbacks.find(COMMON_CANCEL) != callbacks.end()) {
936         auto cancelEventMarker = BackEndEventManager<void()>::GetInstance().GetAvailableMarker();
937         BackEndEventManager<void()>::GetInstance().BindBackendEvent(
938             cancelEventMarker, [callback, taskExecutor = taskExecutor_] {
939                 taskExecutor->PostTask([callback]() { callback(1, 0); }, TaskExecutor::TaskType::JS);
940             });
941         callbackMarkers.emplace(COMMON_CANCEL, cancelEventMarker);
942     }
943 
944     if (callbacks.find(COMMON_COMPLETE) != callbacks.end()) {
945         auto completeEventMarker = BackEndEventManager<void()>::GetInstance().GetAvailableMarker();
946         BackEndEventManager<void()>::GetInstance().BindBackendEvent(
947             completeEventMarker, [callback, taskExecutor = taskExecutor_] {
948                 taskExecutor->PostTask([callback]() { callback(2, 0); }, TaskExecutor::TaskType::JS);
949             });
950         callbackMarkers.emplace(COMMON_COMPLETE, completeEventMarker);
951     }
952 
953     DialogProperties dialogProperties = {
954         .title = title,
955         .content = message,
956         .autoCancel = autoCancel,
957         .buttons = buttons,
958         .callbacks = std::move(callbackMarkers),
959     };
960     WeakPtr<PipelineContext> weak = AceType::DynamicCast<PipelineContext>(pipelineContextHolder_.Get());
961     taskExecutor_->PostTask(
962         [weak, dialogProperties, isRightToLeft = AceApplicationInfo::GetInstance().IsRightToLeft()]() {
963             auto context = weak.Upgrade();
964             if (context) {
965                 context->ShowDialog(dialogProperties, isRightToLeft);
966             }
967         },
968         TaskExecutor::TaskType::UI);
969 }
970 
ShowActionMenu(const std::string & title,const std::vector<ButtonInfo> & button,std::function<void (int32_t,int32_t)> && callback)971 void FrontendDelegateImpl::ShowActionMenu(const std::string& title,
972     const std::vector<ButtonInfo>& button, std::function<void(int32_t, int32_t)>&& callback)
973 {
974     if (!taskExecutor_) {
975         LOGE("task executor is null.");
976         return;
977     }
978 
979     std::unordered_map<std::string, EventMarker> callbackMarkers;
980 
981     auto successEventMarker = BackEndEventManager<void(int32_t)>::GetInstance().GetAvailableMarker();
982     BackEndEventManager<void(int32_t)>::GetInstance().BindBackendEvent(
983         successEventMarker, [callback, number = button.size(), taskExecutor = taskExecutor_](int32_t successType) {
984             taskExecutor->PostTask(
985                 [callback, number, successType]() {
986                     // if callback index is larger than button's number, cancel button is selected
987                     if (static_cast<size_t>(successType) == number) {
988                         callback(1, 0);
989                     } else {
990                         callback(0, successType);
991                     }
992                 },
993                 TaskExecutor::TaskType::JS);
994         });
995     callbackMarkers.emplace(COMMON_SUCCESS, successEventMarker);
996 
997     auto cancelEventMarker = BackEndEventManager<void()>::GetInstance().GetAvailableMarker();
998     BackEndEventManager<void()>::GetInstance().BindBackendEvent(
999         cancelEventMarker, [callback, taskExecutor = taskExecutor_] {
1000             taskExecutor->PostTask([callback]() { callback(1, 0); }, TaskExecutor::TaskType::JS);
1001         });
1002     callbackMarkers.emplace(COMMON_CANCEL, cancelEventMarker);
1003 
1004     DialogProperties dialogProperties = {
1005         .title = title,
1006         .autoCancel = true,
1007         .isMenu = true,
1008         .buttons = button,
1009         .callbacks = std::move(callbackMarkers),
1010     };
1011     ButtonInfo buttonInfo = {
1012         .text = Localization::GetInstance()->GetEntryLetters("common.cancel"),
1013         .textColor = "#000000"
1014     };
1015     dialogProperties.buttons.emplace_back(buttonInfo);
1016     WeakPtr<PipelineContext> weak = AceType::DynamicCast<PipelineContext>(pipelineContextHolder_.Get());
1017     taskExecutor_->PostTask(
1018         [weak, dialogProperties, isRightToLeft = AceApplicationInfo::GetInstance().IsRightToLeft()]() {
1019             auto context = weak.Upgrade();
1020             if (context) {
1021                 context->ShowDialog(dialogProperties, isRightToLeft);
1022             }
1023         },
1024         TaskExecutor::TaskType::UI);
1025 }
1026 
EnableAlertBeforeBackPage(const std::string & message,std::function<void (int32_t)> && callback)1027 void FrontendDelegateImpl::EnableAlertBeforeBackPage(
1028     const std::string& message, std::function<void(int32_t)>&& callback)
1029 {
1030     if (!taskExecutor_) {
1031         LOGE("task executor is null.");
1032         return;
1033     }
1034 
1035     std::unordered_map<std::string, EventMarker> callbackMarkers;
1036     auto pipelineContext = pipelineContextHolder_.Get();
1037     auto successEventMarker = BackEndEventManager<void(int32_t)>::GetInstance().GetAvailableMarker();
1038     BackEndEventManager<void(int32_t)>::GetInstance().BindBackendEvent(successEventMarker,
1039         [weak = AceType::WeakClaim(this), callback, taskExecutor = taskExecutor_](int32_t successType) {
1040             taskExecutor->PostTask(
1041                 [weak, callback, successType]() {
1042                     callback(successType);
1043                     if (!successType) {
1044                         LOGI("dialog choose cancel button, can not back");
1045                         return;
1046                     }
1047                     auto delegate = weak.Upgrade();
1048                     if (!delegate) {
1049                         return;
1050                     }
1051                     delegate->BackImplement(delegate->backUri_, delegate->backParam_);
1052                 },
1053                 TaskExecutor::TaskType::JS);
1054         });
1055     callbackMarkers.emplace(COMMON_SUCCESS, successEventMarker);
1056 
1057     std::lock_guard<std::mutex> lock(mutex_);
1058     if (pageRouteStack_.empty()) {
1059         LOGE("page stack is null.");
1060         return;
1061     }
1062 
1063     auto& currentPage = pageRouteStack_.back();
1064     ClearAlertCallback(currentPage);
1065     currentPage.dialogProperties = {
1066         .content = message,
1067         .autoCancel = false,
1068         .buttons = { { .text = Localization::GetInstance()->GetEntryLetters("common.cancel"), .textColor = "" },
1069             { .text = Localization::GetInstance()->GetEntryLetters("common.ok"), .textColor = "" } },
1070         .callbacks = std::move(callbackMarkers),
1071     };
1072 }
1073 
DisableAlertBeforeBackPage()1074 void FrontendDelegateImpl::DisableAlertBeforeBackPage()
1075 {
1076     std::lock_guard<std::mutex> lock(mutex_);
1077     if (pageRouteStack_.empty()) {
1078         LOGE("page stack is null.");
1079         return;
1080     }
1081     auto& currentPage = pageRouteStack_.back();
1082     ClearAlertCallback(currentPage);
1083 }
1084 
SetCallBackResult(const std::string & callBackId,const std::string & result)1085 void FrontendDelegateImpl::SetCallBackResult(const std::string& callBackId, const std::string& result)
1086 {
1087     jsCallBackResult_.try_emplace(StringToInt(callBackId), result);
1088 }
1089 
WaitTimer(const std::string & callbackId,const std::string & delay,bool isInterval,bool isFirst)1090 void FrontendDelegateImpl::WaitTimer(
1091     const std::string& callbackId, const std::string& delay, bool isInterval, bool isFirst)
1092 {
1093     if (!isFirst) {
1094         auto timeoutTaskIter = timeoutTaskMap_.find(callbackId);
1095         // If not find the callbackId in map, means this timer already was removed,
1096         // no need create a new cancelableTimer again.
1097         if (timeoutTaskIter == timeoutTaskMap_.end()) {
1098             return;
1099         }
1100     }
1101 
1102     int32_t delayTime = StringToInt(delay);
1103     // CancelableCallback class can only be executed once.
1104     CancelableCallback<void()> cancelableTimer;
1105     cancelableTimer.Reset([callbackId, delay, isInterval, call = timer_] { call(callbackId, delay, isInterval); });
1106     auto result = timeoutTaskMap_.try_emplace(callbackId, cancelableTimer);
1107     if (!result.second) {
1108         result.first->second = cancelableTimer;
1109     }
1110     taskExecutor_->PostDelayedTask(cancelableTimer, TaskExecutor::TaskType::JS, delayTime);
1111 }
1112 
ClearTimer(const std::string & callbackId)1113 void FrontendDelegateImpl::ClearTimer(const std::string& callbackId)
1114 {
1115     auto timeoutTaskIter = timeoutTaskMap_.find(callbackId);
1116     if (timeoutTaskIter != timeoutTaskMap_.end()) {
1117         timeoutTaskIter->second.Cancel();
1118         timeoutTaskMap_.erase(timeoutTaskIter);
1119     } else {
1120         LOGW("ClearTimer callbackId not found");
1121     }
1122 }
1123 
PostSyncTaskToPage(std::function<void ()> && task)1124 void FrontendDelegateImpl::PostSyncTaskToPage(std::function<void()>&& task)
1125 {
1126     pipelineContextHolder_.Get(); // Wait until Pipeline Context is attached.
1127     TriggerPageUpdate(GetRunningPageId(), true);
1128     taskExecutor_->PostSyncTask(task, TaskExecutor::TaskType::UI);
1129 }
1130 
AddTaskObserver(std::function<void ()> && task)1131 void FrontendDelegateImpl::AddTaskObserver(std::function<void()>&& task)
1132 {
1133     taskExecutor_->AddTaskObserver(std::move(task));
1134 }
1135 
RemoveTaskObserver()1136 void FrontendDelegateImpl::RemoveTaskObserver()
1137 {
1138     taskExecutor_->RemoveTaskObserver();
1139 }
1140 
GetAssetContent(const std::string & url,std::string & content)1141 bool FrontendDelegateImpl::GetAssetContent(const std::string& url, std::string& content)
1142 {
1143     return GetAssetContentImpl(assetManager_, url, content);
1144 }
1145 
GetAssetContent(const std::string & url,std::vector<uint8_t> & content)1146 bool FrontendDelegateImpl::GetAssetContent(const std::string& url, std::vector<uint8_t>& content)
1147 {
1148     return GetAssetContentImpl(assetManager_, url, content);
1149 }
1150 
GetAssetPath(const std::string & url)1151 std::string FrontendDelegateImpl::GetAssetPath(const std::string& url)
1152 {
1153     return GetAssetPathImpl(assetManager_, url);
1154 }
1155 
LoadPage(int32_t pageId,const std::string & url,bool isMainPage,const std::string & params)1156 void FrontendDelegateImpl::LoadPage(int32_t pageId, const std::string& url, bool isMainPage, const std::string& params)
1157 {
1158     LOGD("FrontendDelegateImpl LoadPage[%{private}d]: %{private}s.", pageId, url.c_str());
1159     {
1160         std::lock_guard<std::mutex> lock(mutex_);
1161         pageId_ = pageId;
1162         pageParamMap_[pageId] = params;
1163     }
1164     if (pageId == INVALID_PAGE_ID) {
1165         LOGE("FrontendDelegateImpl, invalid page id");
1166         EventReport::SendPageRouterException(PageRouterExcepType::LOAD_PAGE_ERR, url);
1167         return;
1168     }
1169     if (isStagingPageExist_) {
1170         LOGE("FrontendDelegateImpl, load page failed, waiting for current page loading finish.");
1171         RecyclePageId(pageId);
1172         return;
1173     }
1174     isStagingPageExist_ = true;
1175     auto document = AceType::MakeRefPtr<DOMDocument>(pageId);
1176     auto page = AceType::MakeRefPtr<JsAcePage>(pageId, document, url);
1177     page->SetPageParams(params);
1178     page->SetFlushCallback([weak = AceType::WeakClaim(this), isMainPage](const RefPtr<JsAcePage>& acePage) {
1179         auto delegate = weak.Upgrade();
1180         if (delegate && acePage) {
1181             delegate->FlushPageCommand(acePage, acePage->GetUrl(), isMainPage);
1182         }
1183     });
1184     taskExecutor_->PostTask(
1185         [weak = AceType::WeakClaim(this), page, url, isMainPage] {
1186             auto delegate = weak.Upgrade();
1187             if (!delegate) {
1188                 LOGE("the delegate context is nullptr");
1189                 return;
1190             }
1191             delegate->loadJs_(url, page, isMainPage);
1192             page->FlushCommands();
1193             // just make sure the pipelineContext is created.
1194             auto pipelineContext = delegate->pipelineContextHolder_.Get();
1195             if (!pipelineContext) {
1196                 LOGE("the pipeline context is nullptr");
1197                 return;
1198             }
1199             if (delegate->GetMinPlatformVersion() > 0) {
1200                 pipelineContext->SetMinPlatformVersion(delegate->GetMinPlatformVersion());
1201             }
1202             delegate->taskExecutor_->PostTask(
1203                 [weak, page] {
1204                     auto delegate = weak.Upgrade();
1205                     if (delegate && delegate->pipelineContextHolder_.Get()) {
1206                         auto context = AceType::DynamicCast<PipelineContext>(delegate->pipelineContextHolder_.Get());
1207                         if (context) {
1208                             context->FlushFocus();
1209                         }
1210                     }
1211                     if (page->GetDomDocument()) {
1212                         page->GetDomDocument()->HandlePageLoadFinish();
1213                     }
1214                 },
1215                 TaskExecutor::TaskType::UI);
1216         },
1217         TaskExecutor::TaskType::JS);
1218 }
1219 
OnSurfaceChanged()1220 void FrontendDelegateImpl::OnSurfaceChanged()
1221 {
1222     if (mediaQueryInfo_->GetIsInit()) {
1223         mediaQueryInfo_->SetIsInit(false);
1224     }
1225     mediaQueryInfo_->EnsureListenerIdValid();
1226     OnMediaQueryUpdate();
1227 }
1228 
OnMediaQueryUpdate()1229 void FrontendDelegateImpl::OnMediaQueryUpdate()
1230 {
1231     if (mediaQueryInfo_->GetIsInit()) {
1232         return;
1233     }
1234 
1235     taskExecutor_->PostTask(
1236         [weak = AceType::WeakClaim(this)] {
1237             auto delegate = weak.Upgrade();
1238             if (!delegate) {
1239                 return;
1240             }
1241             const auto& info = delegate->mediaQueryInfo_->GetMediaQueryInfo();
1242             // request css mediaquery
1243             std::string param("\"viewsizechanged\",");
1244             param.append(info);
1245             delegate->asyncEvent_("_root", param);
1246 
1247             // request js mediaquery
1248             const auto& listenerId = delegate->mediaQueryInfo_->GetListenerId();
1249             delegate->mediaQueryCallback_(listenerId, info);
1250             delegate->mediaQueryInfo_->ResetListenerId();
1251         },
1252         TaskExecutor::TaskType::JS);
1253 }
1254 
OnPageReady(const RefPtr<JsAcePage> & page,const std::string & url,bool isMainPage)1255 void FrontendDelegateImpl::OnPageReady(const RefPtr<JsAcePage>& page, const std::string& url, bool isMainPage)
1256 {
1257     LOGI("OnPageReady url = %{private}s", url.c_str());
1258     // Pop all JS command and execute them in UI thread.
1259     auto jsCommands = std::make_shared<std::vector<RefPtr<JsCommand>>>();
1260     page->PopAllCommands(*jsCommands);
1261 
1262     auto pipelineContext = pipelineContextHolder_.Get();
1263     page->SetPipelineContext(pipelineContext);
1264     taskExecutor_->PostTask(
1265         [weak = AceType::WeakClaim(this), page, url, jsCommands, isMainPage] {
1266             auto delegate = weak.Upgrade();
1267             if (!delegate) {
1268                 return;
1269             }
1270             delegate->SetCurrentReadyPage(page);
1271             auto pipelineContext = AceType::DynamicCast<PipelineContext>(delegate->pipelineContextHolder_.Get());
1272             CHECK_NULL_VOID(pipelineContext);
1273             bool useLiteStyle = delegate->GetMinPlatformVersion() < COMPATIBLE_VERSION && delegate->IsUseLiteStyle();
1274             pipelineContext->SetUseLiteStyle(useLiteStyle);
1275             page->SetUseLiteStyle(useLiteStyle);
1276             page->SetUseBoxWrap(delegate->GetMinPlatformVersion() >= WEB_FEATURE_VERSION);
1277             // Flush all JS commands.
1278             for (const auto& command : *jsCommands) {
1279                 command->Execute(page);
1280             }
1281             // Just clear all dirty nodes.
1282             page->ClearAllDirtyNodes();
1283             if (page->GetDomDocument()) {
1284                 page->GetDomDocument()->HandleComponentPostBinding();
1285             }
1286             if (pipelineContext->GetAccessibilityManager()) {
1287                 pipelineContext->GetAccessibilityManager()->HandleComponentPostBinding();
1288             }
1289             if (pipelineContext->CanPushPage()) {
1290                 if (!isMainPage) {
1291                     delegate->OnPageHide();
1292                 }
1293                 pipelineContext->RemovePageTransitionListener(delegate->pageTransitionListenerId_);
1294                 delegate->pageTransitionListenerId_ = pipelineContext->AddPageTransitionListener(
1295                     [weak, page](
1296                         const TransitionEvent& event, const WeakPtr<PageElement>& in, const WeakPtr<PageElement>& out) {
1297                         auto delegate = weak.Upgrade();
1298                         if (delegate) {
1299                             delegate->PushPageTransitionListener(event, page);
1300                         }
1301                     });
1302                 pipelineContext->PushPage(page->BuildPage(url));
1303                 delegate->OnPushPageSuccess(page, url);
1304                 delegate->SetCurrentPage(page->GetPageId());
1305                 delegate->OnMediaQueryUpdate();
1306             } else {
1307                 // This page has been loaded but become useless now, the corresponding js instance
1308                 // must be destroyed to avoid memory leak.
1309                 delegate->OnPageDestroy(page->GetPageId());
1310                 delegate->ResetStagingPage();
1311             }
1312             delegate->isStagingPageExist_ = false;
1313         },
1314         TaskExecutor::TaskType::UI);
1315 }
1316 
PushPageTransitionListener(const TransitionEvent & event,const RefPtr<JsAcePage> & page)1317 void FrontendDelegateImpl::PushPageTransitionListener(
1318     const TransitionEvent& event, const RefPtr<JsAcePage>& page)
1319 {
1320     if (event == TransitionEvent::PUSH_END) {
1321         OnPageShow();
1322     }
1323 }
1324 
FlushPageCommand(const RefPtr<JsAcePage> & page,const std::string & url,bool isMainPage)1325 void FrontendDelegateImpl::FlushPageCommand(const RefPtr<JsAcePage>& page, const std::string& url, bool isMainPage)
1326 {
1327     if (!page) {
1328         return;
1329     }
1330     LOGI("FlushPageCommand FragmentCount(%{public}d)", page->FragmentCount());
1331     if (page->FragmentCount() == 1) {
1332         OnPageReady(page, url, isMainPage);
1333     } else {
1334         TriggerPageUpdate(page->GetPageId());
1335     }
1336 }
1337 
AddPageLocked(const RefPtr<JsAcePage> & page)1338 void FrontendDelegateImpl::AddPageLocked(const RefPtr<JsAcePage>& page)
1339 {
1340     auto result = pageMap_.try_emplace(page->GetPageId(), page);
1341     if (!result.second) {
1342         LOGW("the page has already in the map");
1343     }
1344 }
1345 
SetCurrentPage(int32_t pageId)1346 void FrontendDelegateImpl::SetCurrentPage(int32_t pageId)
1347 {
1348     LOGD("FrontendDelegateImpl SetCurrentPage pageId=%{private}d", pageId);
1349     auto page = GetPage(pageId);
1350     if (page != nullptr) {
1351         jsAccessibilityManager_->SetRunningPage(page);
1352         taskExecutor_->PostTask([updatePage = updatePage_, page] { updatePage(page); }, TaskExecutor::TaskType::JS);
1353     } else {
1354         LOGE("FrontendDelegateImpl SetCurrentPage page is null.");
1355     }
1356 }
1357 
OnPushPageSuccess(const RefPtr<JsAcePage> & page,const std::string & url)1358 void FrontendDelegateImpl::OnPushPageSuccess(const RefPtr<JsAcePage>& page, const std::string& url)
1359 {
1360     std::lock_guard<std::mutex> lock(mutex_);
1361     AddPageLocked(page);
1362     pageRouteStack_.emplace_back(PageInfo { page->GetPageId(), url });
1363     if (pageRouteStack_.size() >= MAX_ROUTER_STACK) {
1364         isRouteStackFull_ = true;
1365         EventReport::SendPageRouterException(PageRouterExcepType::PAGE_STACK_OVERFLOW_ERR, page->GetUrl());
1366     }
1367     auto pipelineContext = pipelineContextHolder_.Get();
1368     if (pipelineContext) {
1369         pipelineContext->onRouterChange(url);
1370         pipelineContext->NotifyPopPageSuccessDismiss(url, pageRouteStack_.back().pageId);
1371     }
1372     LOGI("OnPushPageSuccess size=%{private}zu,pageId=%{private}d,url=%{private}s", pageRouteStack_.size(),
1373         pageRouteStack_.back().pageId, pageRouteStack_.back().url.c_str());
1374 }
1375 
OnPopToPageSuccess(const std::string & url)1376 void FrontendDelegateImpl::OnPopToPageSuccess(const std::string& url)
1377 {
1378     std::lock_guard<std::mutex> lock(mutex_);
1379     while (!pageRouteStack_.empty()) {
1380         if (pageRouteStack_.back().url == url) {
1381             break;
1382         }
1383         OnPageDestroy(pageRouteStack_.back().pageId);
1384         pageMap_.erase(pageRouteStack_.back().pageId);
1385         pageParamMap_.erase(pageRouteStack_.back().pageId);
1386         ClearAlertCallback(pageRouteStack_.back());
1387         pageRouteStack_.pop_back();
1388     }
1389     if (isRouteStackFull_) {
1390         isRouteStackFull_ = false;
1391     }
1392     auto pipelineContext = pipelineContextHolder_.Get();
1393     if (pipelineContext) {
1394         pipelineContext->onRouterChange(url);
1395         pipelineContext->NotifyPopPageSuccessDismiss(url, pageRouteStack_.back().pageId);
1396     }
1397 }
1398 
PopToPage(const std::string & url)1399 void FrontendDelegateImpl::PopToPage(const std::string& url)
1400 {
1401     LOGD("FrontendDelegateImpl PopToPage url = %{private}s", url.c_str());
1402     taskExecutor_->PostTask(
1403         [weak = AceType::WeakClaim(this), url] {
1404             auto delegate = weak.Upgrade();
1405             if (!delegate) {
1406                 return;
1407             }
1408             auto pageId = delegate->GetPageIdByUrl(url);
1409             if (pageId == INVALID_PAGE_ID) {
1410                 return;
1411             }
1412             auto pipelineContext = AceType::DynamicCast<PipelineContext>(delegate->pipelineContextHolder_.Get());
1413             CHECK_NULL_VOID(pipelineContext);
1414             if (!pipelineContext->CanPopPage()) {
1415                 delegate->ResetStagingPage();
1416                 return;
1417             }
1418             delegate->OnPageHide();
1419             pipelineContext->RemovePageTransitionListener(delegate->pageTransitionListenerId_);
1420             delegate->pageTransitionListenerId_ = pipelineContext->AddPageTransitionListener(
1421                 [weak, url, pageId](
1422                     const TransitionEvent& event, const WeakPtr<PageElement>& in, const WeakPtr<PageElement>& out) {
1423                     auto delegate = weak.Upgrade();
1424                     if (delegate) {
1425                         delegate->PopToPageTransitionListener(event, url, pageId);
1426                     }
1427                 });
1428             pipelineContext->PopToPage(pageId);
1429         },
1430         TaskExecutor::TaskType::UI);
1431 }
1432 
PopToPageTransitionListener(const TransitionEvent & event,const std::string & url,int32_t pageId)1433 void FrontendDelegateImpl::PopToPageTransitionListener(
1434     const TransitionEvent& event, const std::string& url, int32_t pageId)
1435 {
1436     if (event == TransitionEvent::POP_END) {
1437         OnPopToPageSuccess(url);
1438         SetCurrentPage(pageId);
1439         OnPageShow();
1440         OnMediaQueryUpdate();
1441     }
1442 }
1443 
OnPopPageSuccess()1444 int32_t FrontendDelegateImpl::OnPopPageSuccess()
1445 {
1446     std::lock_guard<std::mutex> lock(mutex_);
1447     pageMap_.erase(pageRouteStack_.back().pageId);
1448     pageParamMap_.erase(pageRouteStack_.back().pageId);
1449     ClearAlertCallback(pageRouteStack_.back());
1450     pageRouteStack_.pop_back();
1451     if (isRouteStackFull_) {
1452         isRouteStackFull_ = false;
1453     }
1454     if (!pageRouteStack_.empty()) {
1455         auto context = pipelineContextHolder_.Get();
1456         if (context) {
1457             context->NotifyPopPageSuccessDismiss(pageRouteStack_.back().url, pageRouteStack_.back().pageId);
1458             context->onRouterChange(pageRouteStack_.back().url);
1459         }
1460 
1461         return pageRouteStack_.back().pageId;
1462     }
1463     return INVALID_PAGE_ID;
1464 }
1465 
PopPage()1466 void FrontendDelegateImpl::PopPage()
1467 {
1468     taskExecutor_->PostTask(
1469         [weak = AceType::WeakClaim(this)] {
1470             auto delegate = weak.Upgrade();
1471             if (!delegate) {
1472                 return;
1473             }
1474             auto pipelineContext = AceType::DynamicCast<PipelineContext>(delegate->pipelineContextHolder_.Get());
1475             CHECK_NULL_VOID(pipelineContext);
1476             if (delegate->GetStackSize() == 1) {
1477                 if (delegate->disallowPopLastPage_) {
1478                     LOGW("Not allow back because this is the last page!");
1479                     return;
1480                 }
1481                 delegate->OnPageHide();
1482                 delegate->OnPageDestroy(delegate->GetRunningPageId());
1483                 delegate->OnPopPageSuccess();
1484                 pipelineContext->Finish();
1485                 return;
1486             }
1487             if (!pipelineContext->CanPopPage()) {
1488                 delegate->ResetStagingPage();
1489                 return;
1490             }
1491             delegate->OnPageHide();
1492             pipelineContext->RemovePageTransitionListener(delegate->pageTransitionListenerId_);
1493             delegate->pageTransitionListenerId_ = pipelineContext->AddPageTransitionListener(
1494                 [weak, destroyPageId = delegate->GetRunningPageId()](
1495                     const TransitionEvent& event, const WeakPtr<PageElement>& in, const WeakPtr<PageElement>& out) {
1496                     auto delegate = weak.Upgrade();
1497                     if (delegate) {
1498                         delegate->PopPageTransitionListener(event, destroyPageId);
1499                     }
1500                 });
1501             pipelineContext->PopPage();
1502         },
1503         TaskExecutor::TaskType::UI);
1504 }
1505 
PopPageTransitionListener(const TransitionEvent & event,int32_t destroyPageId)1506 void FrontendDelegateImpl::PopPageTransitionListener(const TransitionEvent& event, int32_t destroyPageId)
1507 {
1508     if (event == TransitionEvent::POP_END) {
1509         OnPageDestroy(destroyPageId);
1510         auto pageId = OnPopPageSuccess();
1511         SetCurrentPage(pageId);
1512         OnPageShow();
1513         OnMediaQueryUpdate();
1514     }
1515 }
1516 
OnClearInvisiblePagesSuccess()1517 int32_t FrontendDelegateImpl::OnClearInvisiblePagesSuccess()
1518 {
1519     std::lock_guard<std::mutex> lock(mutex_);
1520     PageInfo pageInfo = std::move(pageRouteStack_.back());
1521     pageRouteStack_.pop_back();
1522     for (const auto& info : pageRouteStack_) {
1523         ClearAlertCallback(info);
1524         OnPageDestroy(info.pageId);
1525         pageMap_.erase(info.pageId);
1526         pageParamMap_.erase(info.pageId);
1527     }
1528     pageRouteStack_.clear();
1529     int32_t resPageId = pageInfo.pageId;
1530     pageRouteStack_.emplace_back(std::move(pageInfo));
1531     if (isRouteStackFull_) {
1532         isRouteStackFull_ = false;
1533     }
1534     return resPageId;
1535 }
1536 
ClearInvisiblePages()1537 void FrontendDelegateImpl::ClearInvisiblePages()
1538 {
1539     std::lock_guard<std::mutex> lock(mutex_);
1540     // Execute invisible pages' OnJsEngineDestroy to release JsValue
1541     for (auto pageRouteIter = pageRouteStack_.cbegin(); pageRouteIter != pageRouteStack_.cend() - 1; ++pageRouteIter) {
1542         const auto& info = *pageRouteIter;
1543         auto iter = pageMap_.find(info.pageId);
1544         if (iter != pageMap_.end()) {
1545             auto page = iter->second;
1546             if (page) {
1547                 page->OnJsEngineDestroy();
1548             }
1549         }
1550     }
1551 
1552     taskExecutor_->PostTask(
1553         [weak = AceType::WeakClaim(this)] {
1554             auto delegate = weak.Upgrade();
1555             if (!delegate) {
1556                 return;
1557             }
1558             auto pipelineContext = AceType::DynamicCast<PipelineContext>(delegate->pipelineContextHolder_.Get());
1559             CHECK_NULL_VOID(pipelineContext);
1560             if (pipelineContext->ClearInvisiblePages()) {
1561                 auto pageId = delegate->OnClearInvisiblePagesSuccess();
1562                 delegate->SetCurrentPage(pageId);
1563             }
1564         },
1565         TaskExecutor::TaskType::UI);
1566 }
1567 
OnReplacePageSuccess(const RefPtr<JsAcePage> & page,const std::string & url)1568 void FrontendDelegateImpl::OnReplacePageSuccess(const RefPtr<JsAcePage>& page, const std::string& url)
1569 {
1570     if (!page) {
1571         return;
1572     }
1573     std::lock_guard<std::mutex> lock(mutex_);
1574     AddPageLocked(page);
1575     if (!pageRouteStack_.empty()) {
1576         pageMap_.erase(pageRouteStack_.back().pageId);
1577         pageParamMap_.erase(pageRouteStack_.back().pageId);
1578         ClearAlertCallback(pageRouteStack_.back());
1579         pageRouteStack_.pop_back();
1580     }
1581     pageRouteStack_.emplace_back(PageInfo { page->GetPageId(), url });
1582     auto pipelineContext = pipelineContextHolder_.Get();
1583     if (pipelineContext) {
1584         pipelineContext->onRouterChange(url);
1585         pipelineContext->NotifyPopPageSuccessDismiss(url, pageRouteStack_.back().pageId);
1586     }
1587 }
1588 
ReplacePage(const RefPtr<JsAcePage> & page,const std::string & url)1589 void FrontendDelegateImpl::ReplacePage(const RefPtr<JsAcePage>& page, const std::string& url)
1590 {
1591     LOGI("ReplacePage url = %{private}s", url.c_str());
1592     // Pop all JS command and execute them in UI thread.
1593     auto jsCommands = std::make_shared<std::vector<RefPtr<JsCommand>>>();
1594     page->PopAllCommands(*jsCommands);
1595 
1596     auto pipelineContext = pipelineContextHolder_.Get();
1597     page->SetPipelineContext(pipelineContext);
1598     taskExecutor_->PostTask(
1599         [weak = AceType::WeakClaim(this), page, url, jsCommands] {
1600             auto delegate = weak.Upgrade();
1601             if (!delegate) {
1602                 return;
1603             }
1604             delegate->SetCurrentReadyPage(page);
1605             auto pipelineContext = AceType::DynamicCast<PipelineContext>(delegate->pipelineContextHolder_.Get());
1606             CHECK_NULL_VOID(pipelineContext);
1607             bool useLiteStyle = delegate->GetMinPlatformVersion() < COMPATIBLE_VERSION && delegate->IsUseLiteStyle();
1608             pipelineContext->SetUseLiteStyle(useLiteStyle);
1609             page->SetUseLiteStyle(useLiteStyle);
1610             page->SetUseBoxWrap(delegate->GetMinPlatformVersion() >= WEB_FEATURE_VERSION);
1611             // Flush all JS commands.
1612             for (const auto& command : *jsCommands) {
1613                 command->Execute(page);
1614             }
1615             // Just clear all dirty nodes.
1616             page->ClearAllDirtyNodes();
1617             page->GetDomDocument()->HandleComponentPostBinding();
1618             if (pipelineContext->GetAccessibilityManager()) {
1619                 pipelineContext->GetAccessibilityManager()->HandleComponentPostBinding();
1620             }
1621             if (pipelineContext->CanReplacePage()) {
1622                 delegate->OnPageHide();
1623                 delegate->OnPageDestroy(delegate->GetRunningPageId());
1624                 pipelineContext->ReplacePage(page->BuildPage(url));
1625                 delegate->OnReplacePageSuccess(page, url);
1626                 delegate->SetCurrentPage(page->GetPageId());
1627                 delegate->OnPageShow();
1628                 delegate->OnMediaQueryUpdate();
1629             } else {
1630                 // This page has been loaded but become useless now, the corresponding js instance
1631                 // must be destroyed to avoid memory leak.
1632                 delegate->OnPageDestroy(page->GetPageId());
1633                 delegate->ResetStagingPage();
1634             }
1635             delegate->isStagingPageExist_ = false;
1636         },
1637         TaskExecutor::TaskType::UI);
1638 }
1639 
LoadReplacePage(int32_t pageId,const std::string & url,const std::string & params)1640 void FrontendDelegateImpl::LoadReplacePage(int32_t pageId, const std::string& url, const std::string& params)
1641 {
1642     LOGD("FrontendDelegateImpl LoadReplacePage[%{private}d]: %{private}s.", pageId, url.c_str());
1643     {
1644         std::lock_guard<std::mutex> lock(mutex_);
1645         pageId_ = pageId;
1646         pageParamMap_[pageId] = params;
1647     }
1648     if (pageId == INVALID_PAGE_ID) {
1649         LOGE("FrontendDelegateImpl, invalid page id");
1650         EventReport::SendPageRouterException(PageRouterExcepType::REPLACE_PAGE_ERR, url);
1651         return;
1652     }
1653     if (isStagingPageExist_) {
1654         LOGE("FrontendDelegateImpl, replace page failed, waiting for current page loading finish.");
1655         EventReport::SendPageRouterException(PageRouterExcepType::REPLACE_PAGE_ERR, url);
1656         return;
1657     }
1658     isStagingPageExist_ = true;
1659     auto document = AceType::MakeRefPtr<DOMDocument>(pageId);
1660     auto page = AceType::MakeRefPtr<JsAcePage>(pageId, document, url);
1661     page->SetPageParams(params);
1662     taskExecutor_->PostTask(
1663         [page, url, weak = AceType::WeakClaim(this)] {
1664             auto delegate = weak.Upgrade();
1665             if (delegate) {
1666                 delegate->loadJs_(url, page, false);
1667                 delegate->ReplacePage(page, url);
1668             }
1669         },
1670         TaskExecutor::TaskType::JS);
1671 }
1672 
RebuildAllPages()1673 void FrontendDelegateImpl::RebuildAllPages()
1674 {
1675     std::unordered_map<int32_t, RefPtr<JsAcePage>> pages;
1676     {
1677         std::lock_guard<std::mutex> lock(mutex_);
1678         pages.insert(pageMap_.begin(), pageMap_.end());
1679     }
1680     for (const auto& [pageId, page] : pages) {
1681         taskExecutor_->PostTask(
1682             [weakPage = WeakPtr<JsAcePage>(page)] {
1683                 auto page = weakPage.Upgrade();
1684                 if (!page) {
1685                     return;
1686                 }
1687                 auto domDoc = page->GetDomDocument();
1688                 if (!domDoc) {
1689                     return;
1690                 }
1691                 auto rootNode = domDoc->GetDOMNodeById(domDoc->GetRootNodeId());
1692                 if (!rootNode) {
1693                     return;
1694                 }
1695                 rootNode->UpdateStyleWithChildren();
1696             },
1697             TaskExecutor::TaskType::UI);
1698     }
1699 }
1700 
OnPageShow()1701 void FrontendDelegateImpl::OnPageShow()
1702 {
1703     FireAsyncEvent("_root", std::string("\"viewappear\",null,null"), std::string(""));
1704 }
1705 
OnPageHide()1706 void FrontendDelegateImpl::OnPageHide()
1707 {
1708     FireAsyncEvent("_root", std::string("\"viewdisappear\",null,null"), std::string(""));
1709 }
1710 
OnConfigurationUpdated(const std::string & configurationData)1711 void FrontendDelegateImpl::OnConfigurationUpdated(const std::string& configurationData)
1712 {
1713     FireSyncEvent("_root", std::string("\"onConfigurationUpdated\","), configurationData);
1714 }
1715 
ClearAlertCallback(PageInfo pageInfo)1716 void FrontendDelegateImpl::ClearAlertCallback(PageInfo pageInfo)
1717 {
1718     if (pageInfo.alertCallback) {
1719         // notify to clear js reference
1720         pageInfo.alertCallback(static_cast<int32_t>(AlertState::RECOVERY));
1721         pageInfo.alertCallback = nullptr;
1722     }
1723 }
1724 
OnPageDestroy(int32_t pageId)1725 void FrontendDelegateImpl::OnPageDestroy(int32_t pageId)
1726 {
1727     taskExecutor_->PostTask(
1728         [weak = AceType::WeakClaim(this), pageId] {
1729             auto delegate = weak.Upgrade();
1730             if (delegate) {
1731                 auto iter = delegate->pageMap_.find(pageId);
1732                 if (iter != delegate->pageMap_.end()) {
1733                     auto page = iter->second;
1734                     if (page) {
1735                         page->OnJsEngineDestroy();
1736                     }
1737                 }
1738                 delegate->destroyPage_(pageId);
1739                 delegate->RecyclePageId(pageId);
1740             }
1741         },
1742         TaskExecutor::TaskType::JS);
1743 }
1744 
GetRunningPageId() const1745 int32_t FrontendDelegateImpl::GetRunningPageId() const
1746 {
1747     std::lock_guard<std::mutex> lock(mutex_);
1748     if (pageRouteStack_.empty()) {
1749         return INVALID_PAGE_ID;
1750     }
1751     return pageRouteStack_.back().pageId;
1752 }
1753 
GetRunningPageUrl() const1754 std::string FrontendDelegateImpl::GetRunningPageUrl() const
1755 {
1756     std::lock_guard<std::mutex> lock(mutex_);
1757     if (pageRouteStack_.empty()) {
1758         return std::string();
1759     }
1760     const auto& pageUrl = pageRouteStack_.back().url;
1761     auto pos = pageUrl.rfind(".js");
1762     if (pos == pageUrl.length() - 3) {
1763         return pageUrl.substr(0, pos);
1764     }
1765     return pageUrl;
1766 }
1767 
GetPageIdByUrl(const std::string & url)1768 int32_t FrontendDelegateImpl::GetPageIdByUrl(const std::string& url)
1769 {
1770     std::lock_guard<std::mutex> lock(mutex_);
1771     auto pageIter = std::find_if(std::rbegin(pageRouteStack_), std::rend(pageRouteStack_),
1772         [&url](const PageInfo& pageRoute) { return url == pageRoute.url; });
1773     if (pageIter != std::rend(pageRouteStack_)) {
1774         LOGD("GetPageIdByUrl pageId=%{private}d url=%{private}s", pageIter->pageId, url.c_str());
1775         return pageIter->pageId;
1776     }
1777     return INVALID_PAGE_ID;
1778 }
1779 
GetPage(int32_t pageId) const1780 RefPtr<JsAcePage> FrontendDelegateImpl::GetPage(int32_t pageId) const
1781 {
1782     std::lock_guard<std::mutex> lock(mutex_);
1783     auto itPage = pageMap_.find(pageId);
1784     if (itPage == pageMap_.end()) {
1785         LOGE("the page is not in the map");
1786         return nullptr;
1787     }
1788     return itPage->second;
1789 }
1790 
RegisterFont(const std::string & familyName,const std::string & familySrc)1791 void FrontendDelegateImpl::RegisterFont(const std::string& familyName, const std::string& familySrc)
1792 {
1793     pipelineContextHolder_.Get()->RegisterFont(familyName, familySrc);
1794 }
1795 
HandleImage(const std::string & src,std::function<void (bool,int32_t,int32_t)> && callback)1796 void FrontendDelegateImpl::HandleImage(const std::string& src, std::function<void(bool, int32_t, int32_t)>&& callback)
1797 {
1798     if (src.empty() || !callback) {
1799         return;
1800     }
1801     auto loadCallback = [jsCallback = std::move(callback), taskExecutor = taskExecutor_](
1802                             bool success, int32_t width, int32_t height) {
1803         taskExecutor->PostTask(
1804             [callback = std::move(jsCallback), success, width, height] { callback(success, width, height); },
1805             TaskExecutor::TaskType::JS);
1806     };
1807     pipelineContextHolder_.Get()->TryLoadImageInfo(src, std::move(loadCallback));
1808 }
1809 
RequestAnimationFrame(const std::string & callbackId)1810 void FrontendDelegateImpl::RequestAnimationFrame(const std::string& callbackId)
1811 {
1812     CancelableCallback<void()> cancelableTask;
1813     cancelableTask.Reset([callbackId, call = requestAnimationCallback_, weak = AceType::WeakClaim(this)] {
1814         auto delegate = weak.Upgrade();
1815         if (delegate && call) {
1816             call(callbackId, delegate->GetSystemRealTime());
1817         }
1818     });
1819     animationFrameTaskMap_.try_emplace(callbackId, cancelableTask);
1820     animationFrameTaskIds_.emplace(callbackId);
1821 }
1822 
GetSystemRealTime()1823 uint64_t FrontendDelegateImpl::GetSystemRealTime()
1824 {
1825     struct timespec ts;
1826     clock_gettime(CLOCK_REALTIME, &ts);
1827     return ts.tv_sec * TO_MILLI + ts.tv_nsec / NANO_TO_MILLI;
1828 }
1829 
CancelAnimationFrame(const std::string & callbackId)1830 void FrontendDelegateImpl::CancelAnimationFrame(const std::string& callbackId)
1831 {
1832     auto animationTaskIter = animationFrameTaskMap_.find(callbackId);
1833     if (animationTaskIter != animationFrameTaskMap_.end()) {
1834         animationTaskIter->second.Cancel();
1835         animationFrameTaskMap_.erase(animationTaskIter);
1836     } else {
1837         LOGW("cancelAnimationFrame callbackId not found");
1838     }
1839 }
1840 
FlushAnimationTasks()1841 void FrontendDelegateImpl::FlushAnimationTasks()
1842 {
1843     while (!animationFrameTaskIds_.empty()) {
1844         const auto& callbackId = animationFrameTaskIds_.front();
1845         if (!callbackId.empty()) {
1846             auto taskIter = animationFrameTaskMap_.find(callbackId);
1847             if (taskIter != animationFrameTaskMap_.end()) {
1848                 taskExecutor_->PostTask(taskIter->second, TaskExecutor::TaskType::JS);
1849             }
1850         }
1851         animationFrameTaskIds_.pop();
1852     }
1853 
1854     auto pageId = GetRunningPageId();
1855     auto page = GetPage(pageId);
1856     if (!page) {
1857         return;
1858     }
1859     auto jsPage = AceType::DynamicCast<Framework::JsAcePage>(page);
1860     if (jsPage && jsPage->GetCommandSize() > 0) {
1861         TriggerPageUpdate(pageId);
1862     }
1863 }
1864 
GetAnimationJsTask()1865 SingleTaskExecutor FrontendDelegateImpl::GetAnimationJsTask()
1866 {
1867     return SingleTaskExecutor::Make(taskExecutor_, TaskExecutor::TaskType::JS);
1868 }
1869 
GetUiTask()1870 SingleTaskExecutor FrontendDelegateImpl::GetUiTask()
1871 {
1872     return SingleTaskExecutor::Make(taskExecutor_, TaskExecutor::TaskType::UI);
1873 }
1874 
AttachPipelineContext(const RefPtr<PipelineBase> & context)1875 void FrontendDelegateImpl::AttachPipelineContext(const RefPtr<PipelineBase>& context)
1876 {
1877     context->SetOnPageShow([weak = AceType::WeakClaim(this)] {
1878         auto delegate = weak.Upgrade();
1879         if (delegate) {
1880             delegate->OnPageShow();
1881         }
1882     });
1883     context->SetAnimationCallback([weak = AceType::WeakClaim(this)] {
1884         auto delegate = weak.Upgrade();
1885         if (delegate) {
1886             delegate->FlushAnimationTasks();
1887         }
1888     });
1889     pipelineContextHolder_.Attach(context);
1890     jsAccessibilityManager_->SetPipelineContext(context);
1891     jsAccessibilityManager_->InitializeCallback();
1892 }
1893 
GetPipelineContext()1894 RefPtr<PipelineBase> FrontendDelegateImpl::GetPipelineContext()
1895 {
1896     return pipelineContextHolder_.Get();
1897 }
1898 
SetColorMode(ColorMode colorMode)1899 void FrontendDelegateImpl::SetColorMode(ColorMode colorMode)
1900 {
1901     mediaQueryInfo_->EnsureListenerIdValid();
1902     OnMediaQueryUpdate();
1903 }
1904 
LoadResourceConfiguration(std::map<std::string,std::string> & mediaResourceFileMap,std::unique_ptr<JsonValue> & currentResourceData)1905 void FrontendDelegateImpl::LoadResourceConfiguration(std::map<std::string, std::string>& mediaResourceFileMap,
1906     std::unique_ptr<JsonValue>& currentResourceData)
1907 {
1908     std::vector<std::string> files;
1909     if (assetManager_) {
1910         assetManager_->GetAssetList(RESOURCES_FOLDER, files);
1911     }
1912 
1913     std::set<std::string> resourceFolderName;
1914     for (const auto& file : files) {
1915         resourceFolderName.insert(file.substr(0, file.find_first_of("/")));
1916     }
1917 
1918     std::vector<std::string> sortedResourceFolderPath =
1919         AceResConfig::GetDeclarativeResourceFallback(resourceFolderName);
1920     for (const auto& folderName : sortedResourceFolderPath) {
1921         auto fileFullPath = std::string(RESOURCES_FOLDER) + folderName + std::string(I18N_FILE_SUFFIX);
1922         std::string content;
1923         if (GetAssetContent(fileFullPath, content)) {
1924             auto fileData = ParseFileData(content);
1925             if (fileData == nullptr) {
1926                 LOGW("parse %{private}s i18n content failed", fileFullPath.c_str());
1927             } else {
1928                 currentResourceData->Put(fileData);
1929             }
1930         }
1931     }
1932 
1933     std::set<std::string> mediaFileName;
1934     for (const auto& file : files) {
1935         auto mediaPathName = file.substr(file.find_first_of("/"));
1936         std::regex mediaPattern("^\\/media\\/\\w*(\\.jpg|\\.png|\\.gif|\\.svg|\\.webp|\\.bmp)$");
1937         std::smatch result;
1938         if (std::regex_match(mediaPathName, result, mediaPattern)) {
1939             mediaFileName.insert(mediaPathName.substr(mediaPathName.find_first_of("/")));
1940         }
1941     }
1942 
1943     auto currentResTag = AceResConfig::GetCurrentDeviceResTag();
1944     auto currentResolutionTag = currentResTag.substr(currentResTag.find_last_of("-") + 1);
1945     for (auto folderName : sortedResourceFolderPath) {
1946         for (auto fileName : mediaFileName) {
1947             if (mediaResourceFileMap.find(fileName) != mediaResourceFileMap.end()) {
1948                 continue;
1949             }
1950             auto fullFileName = folderName + fileName;
1951             if (std::find(files.begin(), files.end(), fullFileName) != files.end()) {
1952                 mediaResourceFileMap.emplace(fileName.substr(fileName.find_last_of("/") + 1),
1953                     std::string(RESOURCES_FOLDER).append(fullFileName));
1954             }
1955         }
1956         if (mediaResourceFileMap.size() == mediaFileName.size()) {
1957             break;
1958         }
1959     }
1960 }
1961 
PushJsCallbackToRenderNode(NodeId id,double ratio,std::function<void (bool,double)> && callback)1962 void FrontendDelegateImpl::PushJsCallbackToRenderNode(NodeId id, double ratio,
1963     std::function<void(bool, double)>&& callback)
1964 {
1965     auto visibleCallback = [jsCallback = std::move(callback), executor = taskExecutor_] (bool visible, double ratio) {
1966         executor->PostTask([task = std::move(jsCallback), visible, ratio] {
1967             if (task) {
1968                 task(visible, ratio);
1969             }
1970         }, TaskExecutor::TaskType::JS);
1971     };
1972     auto uiPushTask = [id, ratio, visibleCallback,
1973                           pipeline = AceType::DynamicCast<PipelineContext>(pipelineContextHolder_.Get())]() {
1974         if (pipeline) {
1975             pipeline->PushVisibleCallback(id, ratio, visibleCallback);
1976         }
1977     };
1978     taskExecutor_->PostTask(uiPushTask, TaskExecutor::TaskType::UI);
1979 }
1980 
CallNativeHandler(const std::string & event,const std::string & params)1981 void FrontendDelegateImpl::CallNativeHandler(const std::string& event, const std::string& params)
1982 {
1983     if (callNativeHandler_ != nullptr) {
1984         callNativeHandler_(event, params);
1985     }
1986 }
1987 
1988 } // namespace OHOS::Ace::Framework
1989