• 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 "adapter/preview/entrance/ace_container.h"
17 
18 #include <functional>
19 
20 #include "base/log/log.h"
21 
22 #ifndef ENABLE_ROSEN_BACKEND
23 #include "flutter/lib/ui/ui_dart_state.h"
24 #include "adapter/ohos/entrance/file_asset_provider_impl.h"
25 #include "core/common/asset_manager_impl.h"
26 #else // ENABLE_ROSEN_BACKEND == true
27 #include "adapter/preview/entrance/rs_dir_asset_provider.h"
28 #include "core/common/rosen/rosen_asset_manager.h"
29 #endif
30 
31 #include "native_engine/native_engine.h"
32 #include "previewer/include/window.h"
33 
34 #include "adapter/preview/entrance/ace_application_info.h"
35 #include "adapter/preview/entrance/ace_preview_helper.h"
36 #include "adapter/preview/osal/stage_card_parser.h"
37 #include "base/log/ace_trace.h"
38 #include "base/log/event_report.h"
39 #include "base/log/log.h"
40 #include "base/utils/system_properties.h"
41 #include "base/utils/utils.h"
42 #include "bridge/card_frontend/card_frontend.h"
43 #include "bridge/card_frontend/card_frontend_declarative.h"
44 #include "bridge/card_frontend/form_frontend_declarative.h"
45 #include "bridge/common/utils/engine_helper.h"
46 #include "bridge/declarative_frontend/declarative_frontend.h"
47 #include "bridge/declarative_frontend/engine/jsi/jsi_declarative_engine.h"
48 #include "bridge/js_frontend/engine/common/js_engine_loader.h"
49 #include "bridge/js_frontend/js_frontend.h"
50 #include "core/common/ace_engine.h"
51 #include "core/common/ace_view.h"
52 #include "core/common/container_scope.h"
53 #include "core/common/platform_bridge.h"
54 #include "core/common/platform_window.h"
55 #include "core/common/resource/resource_manager.h"
56 #include "core/common/task_executor_impl.h"
57 #include "core/common/text_field_manager.h"
58 #include "core/common/window.h"
59 #include "core/components/theme/app_theme.h"
60 #include "core/components/theme/theme_constants.h"
61 #include "core/components/theme/theme_manager_impl.h"
62 #include "core/components_ng/pattern/text_field/text_field_manager.h"
63 #include "core/components_ng/render/adapter/rosen_window.h"
64 #include "core/pipeline/base/element.h"
65 #include "core/pipeline/pipeline_context.h"
66 #include "core/pipeline_ng/pipeline_context.h"
67 
68 namespace OHOS::Ace::Platform {
69 namespace {
70 const char LANGUAGE_TAG[] = "language";
71 const char COUNTRY_TAG[] = "countryOrRegion";
72 const char DIRECTION_TAG[] = "dir";
73 const char UNICODE_SETTING_TAG[] = "unicodeSetting";
74 const char LOCALE_DIR_LTR[] = "ltr";
75 const char LOCALE_DIR_RTL[] = "rtl";
76 const char LOCALE_KEY[] = "locale";
77 
SaveResourceAdapter(const std::string & bundleName,const std::string & moduleName,int32_t instanceId,RefPtr<ResourceAdapter> & resourceAdapter)78 void SaveResourceAdapter(const std::string& bundleName, const std::string& moduleName, int32_t instanceId,
79     RefPtr<ResourceAdapter>& resourceAdapter)
80 {
81     auto defaultBundleName = "";
82     auto defaultModuleName = "";
83     ResourceManager::GetInstance().AddResourceAdapter(
84         defaultBundleName, defaultModuleName, instanceId, resourceAdapter);
85     LOGI("Save default adapter");
86 
87     if (!bundleName.empty() && !moduleName.empty()) {
88         LOGI("Save resource adapter bundle: %{public}s, module: %{public}s", bundleName.c_str(), moduleName.c_str());
89         ResourceManager::GetInstance().AddResourceAdapter(bundleName, moduleName, instanceId, resourceAdapter);
90     }
91 }
92 } // namespace
93 
94 std::once_flag AceContainer::onceFlag_;
95 bool AceContainer::isComponentMode_ = false;
AceContainer(int32_t instanceId,FrontendType type,bool useNewPipeline,bool useCurrentEventRunner)96 AceContainer::AceContainer(int32_t instanceId, FrontendType type, bool useNewPipeline, bool useCurrentEventRunner)
97     : instanceId_(instanceId), messageBridge_(AceType::MakeRefPtr<PlatformBridge>()), type_(type)
98 {
99     LOGI("Using %{public}s pipeline context ...", (useNewPipeline ? "new" : "old"));
100     if (useNewPipeline) {
101         SetUseNewPipeline();
102     }
103     ThemeConstants::InitDeviceType();
104     auto taskExecutorImpl = Referenced::MakeRefPtr<TaskExecutorImpl>();
105     taskExecutorImpl->InitPlatformThread(useCurrentEventRunner);
106     if (type_ != FrontendType::DECLARATIVE_JS && type_ != FrontendType::ETS_CARD) {
107         taskExecutorImpl->InitJsThread();
108     } else {
109         GetSettings().useUIAsJSThread = true;
110     }
111     taskExecutor_ = taskExecutorImpl;
112 }
113 
Initialize()114 void AceContainer::Initialize()
115 {
116     ContainerScope scope(instanceId_);
117     if (type_ != FrontendType::DECLARATIVE_JS && type_ != FrontendType::ETS_CARD) {
118         InitializeFrontend();
119     }
120 }
121 
Destroy()122 void AceContainer::Destroy()
123 {
124     ContainerScope scope(instanceId_);
125     if (!pipelineContext_) {
126         return;
127     }
128     if (!taskExecutor_) {
129         return;
130     }
131     auto weak = AceType::WeakClaim(AceType::RawPtr(pipelineContext_));
132     taskExecutor_->PostTask(
133         [weak]() {
134             auto context = weak.Upgrade();
135             if (context == nullptr) {
136                 return;
137             }
138             context->Destroy();
139         },
140         TaskExecutor::TaskType::UI, "ArkUIPipelineDestroy");
141 
142     RefPtr<Frontend> frontend;
143     frontend_.Swap(frontend);
144     if (frontend && taskExecutor_) {
145         taskExecutor_->PostTask(
146             [frontend]() {
147                 frontend->UpdateState(Frontend::State::ON_DESTROY);
148                 frontend->Destroy();
149             },
150             TaskExecutor::TaskType::JS, "ArkUIFrontendDestroy");
151     }
152 
153     messageBridge_.Reset();
154     resRegister_.Reset();
155     assetManager_.Reset();
156     pipelineContext_.Reset();
157     aceView_ = nullptr;
158 }
159 
DestroyView()160 void AceContainer::DestroyView()
161 {
162     if (aceView_ != nullptr) {
163         aceView_ = nullptr;
164     }
165 }
166 
InitializeFrontend()167 void AceContainer::InitializeFrontend()
168 {
169     if (type_ == FrontendType::JS) {
170         frontend_ = Frontend::Create();
171         auto jsFrontend = AceType::DynamicCast<JsFrontend>(frontend_);
172         auto jsEngine = Framework::JsEngineLoader::Get().CreateJsEngine(GetInstanceId());
173         EngineHelper::AddEngine(instanceId_, jsEngine);
174         jsFrontend->SetJsEngine(jsEngine);
175         jsFrontend->SetNeedDebugBreakPoint(AceApplicationInfo::GetInstance().IsNeedDebugBreakPoint());
176         jsFrontend->SetDebugVersion(AceApplicationInfo::GetInstance().IsDebugVersion());
177     } else if (type_ == FrontendType::DECLARATIVE_JS) {
178         frontend_ = AceType::MakeRefPtr<DeclarativeFrontend>();
179         auto declarativeFrontend = AceType::DynamicCast<DeclarativeFrontend>(frontend_);
180         auto& loader = Framework::JsEngineLoader::GetDeclarative();
181         RefPtr<Framework::JsEngine> jsEngine;
182         if (GetSettings().usingSharedRuntime) {
183             jsEngine = loader.CreateJsEngineUsingSharedRuntime(instanceId_, sharedRuntime_);
184         } else {
185             jsEngine = loader.CreateJsEngine(instanceId_);
186         }
187         EngineHelper::AddEngine(instanceId_, jsEngine);
188         declarativeFrontend->SetJsEngine(jsEngine);
189         declarativeFrontend->SetPageProfile(pageProfile_);
190         if (PkgContextInfo_) {
191             declarativeFrontend->SetPkgNameList(PkgContextInfo_->GetPkgNameMap());
192             declarativeFrontend->SetPkgAliasList(PkgContextInfo_->GetPkgAliasMap());
193             declarativeFrontend->SetpkgContextInfoList(PkgContextInfo_->GetPkgContextInfoMap());
194         }
195     } else if (type_ == FrontendType::JS_CARD) {
196         AceApplicationInfo::GetInstance().SetCardType();
197         frontend_ = AceType::MakeRefPtr<CardFrontend>();
198     } else if (type_ == FrontendType::ETS_CARD) {
199         frontend_ = AceType::MakeRefPtr<FormFrontendDeclarative>();
200         auto cardFrontend = AceType::DynamicCast<FormFrontendDeclarative>(frontend_);
201         auto jsEngine = Framework::JsEngineLoader::GetDeclarative().CreateJsEngine(instanceId_);
202         EngineHelper::AddEngine(instanceId_, jsEngine);
203         cardFrontend->SetJsEngine(jsEngine);
204         cardFrontend->SetPageProfile(pageProfile_);
205         cardFrontend->SetRunningCardId(0);
206         cardFrontend->SetIsFormRender(true);
207         cardFrontend->SetTaskExecutor(taskExecutor_);
208         if (PkgContextInfo_) {
209             cardFrontend->SetPkgNameList(PkgContextInfo_->GetPkgNameMap());
210             cardFrontend->SetPkgAliasList(PkgContextInfo_->GetPkgAliasMap());
211             cardFrontend->SetpkgContextInfoList(PkgContextInfo_->GetPkgContextInfoMap());
212         }
213         SetIsFRSCardContainer(true);
214     }
215     ACE_DCHECK(frontend_);
216     frontend_->DisallowPopLastPage();
217     frontend_->Initialize(type_, taskExecutor_);
218     if (assetManager_) {
219         frontend_->SetAssetManager(assetManager_);
220     }
221 }
222 
RunNativeEngineLoop()223 void AceContainer::RunNativeEngineLoop()
224 {
225     taskExecutor_->PostTask([frontend = frontend_]() { frontend->RunNativeEngineLoop(); }, TaskExecutor::TaskType::JS,
226         "ArkUIRunNativeEngineLoop");
227     // After the JS thread executes frontend ->RunNativeEngineLoop(),
228     // it is thrown back into the Platform thread queue to form a loop.
229     taskExecutor_->PostTask([this]() { RunNativeEngineLoop(); },
230         TaskExecutor::TaskType::PLATFORM, "ArkUIRunNativeEngineLoop");
231 }
232 
InitializeAppConfig(const std::string & assetPath,const std::string & bundleName,const std::string & moduleName,const std::string & compileMode)233 void AceContainer::InitializeAppConfig(const std::string& assetPath, const std::string& bundleName,
234     const std::string& moduleName, const std::string& compileMode)
235 {
236     bool isBundle = (compileMode != "esmodule");
237     auto declarativeFrontend = AceType::DynamicCast<DeclarativeFrontend>(frontend_);
238     CHECK_NULL_VOID(declarativeFrontend);
239     declarativeFrontend->InitializeModuleSearcher(bundleName, moduleName, assetPath, isBundle);
240 
241     auto formFrontend = AceType::DynamicCast<FormFrontendDeclarative>(frontend_);
242     CHECK_NULL_VOID(formFrontend);
243     formFrontend->SetBundleName(bundleName);
244     formFrontend->SetModuleName(moduleName);
245     formFrontend->SetIsBundle(isBundle);
246 }
247 
SetHspBufferTrackerCallback()248 void AceContainer::SetHspBufferTrackerCallback()
249 {
250     if (GetSettings().usingSharedRuntime) {
251         LOGI("The callback has been set by ability in the light simulator.");
252         return;
253     }
254     auto frontend = AceType::DynamicCast<DeclarativeFrontend>(frontend_);
255     CHECK_NULL_VOID(frontend);
256     auto weak = WeakPtr(frontend->GetJsEngine());
257     taskExecutor_->PostTask(
258         [weak, instanceId = instanceId_]() {
259             ContainerScope scope(instanceId);
260             auto jsEngine = AceType::DynamicCast<Framework::JsiDeclarativeEngine>(weak.Upgrade());
261             CHECK_NULL_VOID(jsEngine);
262             jsEngine->SetHspBufferTrackerCallback(AcePreviewHelper::GetInstance()->GetCallbackOfHspBufferTracker());
263         },
264         TaskExecutor::TaskType::JS, "ArkUISetHspBufferTracker");
265 }
266 
SetMockModuleListToJsEngine()267 void AceContainer::SetMockModuleListToJsEngine()
268 {
269     if (GetSettings().usingSharedRuntime) {
270         LOGI("The callback has been set by ability in the light simulator.");
271         return;
272     }
273     auto frontend = AceType::DynamicCast<DeclarativeFrontend>(frontend_);
274     CHECK_NULL_VOID(frontend);
275     auto weak = WeakPtr(frontend->GetJsEngine());
276     taskExecutor_->PostTask(
277         [weak, instanceId = instanceId_, mockJsonInfo = mockJsonInfo_]() {
278             ContainerScope scope(instanceId);
279             auto jsEngine = AceType::DynamicCast<Framework::JsiDeclarativeEngine>(weak.Upgrade());
280             CHECK_NULL_VOID(jsEngine);
281             jsEngine->SetMockModuleList(mockJsonInfo);
282         },
283         TaskExecutor::TaskType::JS, "ArkUISetMockModuleList");
284 }
285 
SetStageCardConfig(const std::string & pageProfile,const std::string & selectUrl)286 void AceContainer::SetStageCardConfig(const std::string& pageProfile, const std::string& selectUrl)
287 {
288     std::string fullPageProfile = pageProfile + ".json";
289     std::string formConfigs;
290     RefPtr<StageCardParser> stageCardParser = AceType::MakeRefPtr<StageCardParser>();
291     if (!Framework::GetAssetContentImpl(assetManager_, fullPageProfile, formConfigs)) {
292         LOGW("Can not load the form config, formConfigs is %{public}s", formConfigs.c_str());
293         return;
294     }
295     const std::string prefix("./js/");
296     stageCardParser->Parse(formConfigs, prefix + selectUrl);
297     auto cardFront = static_cast<CardFrontend*>(RawPtr(frontend_));
298     if (cardFront) {
299         cardFront->SetFormSrc(selectUrl);
300         cardFront->SetCardWindowConfig(stageCardParser->GetWindowConfig());
301     }
302 }
303 
SetPkgContextInfo(const RefPtr<StagePkgContextInfo> & PkgContextInfo)304 void AceContainer::SetPkgContextInfo(const RefPtr<StagePkgContextInfo>& PkgContextInfo)
305 {
306     PkgContextInfo_ = PkgContextInfo;
307 }
308 
InitializeCallback()309 void AceContainer::InitializeCallback()
310 {
311     ACE_FUNCTION_TRACE();
312 
313     ACE_DCHECK(aceView_ && taskExecutor_ && pipelineContext_);
314 
315     auto weak = AceType::WeakClaim(AceType::RawPtr(pipelineContext_));
316     auto&& touchEventCallback = [weak, id = instanceId_](
317                                     const TouchEvent& event, const std::function<void()>& ignoreMark,
318                                     const RefPtr<OHOS::Ace::NG::FrameNode>& node) {
319         ContainerScope scope(id);
320         auto context = weak.Upgrade();
321         if (context == nullptr) {
322             return;
323         }
324         context->GetTaskExecutor()->PostTask(
325             [context, event]() { context->OnTouchEvent(event); },
326             TaskExecutor::TaskType::UI, "ArkUIAceContainerTouchEvent");
327     };
328     aceView_->RegisterTouchEventCallback(touchEventCallback);
329 
330     auto&& keyEventCallback = [weak, id = instanceId_](const KeyEvent& event) {
331         ContainerScope scope(id);
332         auto context = weak.Upgrade();
333         if (context == nullptr) {
334             return false;
335         }
336         bool result = false;
337         context->GetTaskExecutor()->PostSyncTask(
338             [context, event, &result]() { result = context->OnNonPointerEvent(event); },
339             TaskExecutor::TaskType::UI, "ArkUIAceContainerKeyEvent");
340         return result;
341     };
342     aceView_->RegisterKeyEventCallback(keyEventCallback);
343 
344     auto&& mouseEventCallback = [weak, id = instanceId_](
345                                     const MouseEvent& event, const std::function<void()>& ignoreMark,
346                                     const RefPtr<OHOS::Ace::NG::FrameNode>& node) {
347         ContainerScope scope(id);
348         auto context = weak.Upgrade();
349         if (context == nullptr) {
350             return;
351         }
352         context->GetTaskExecutor()->PostTask(
353             [context, event]() { context->OnMouseEvent(event); },
354             TaskExecutor::TaskType::UI, "ArkUIAceContainerMouseEvent");
355     };
356     aceView_->RegisterMouseEventCallback(mouseEventCallback);
357 
358     auto&& axisEventCallback = [weak, id = instanceId_](
359                                    const AxisEvent& event, const std::function<void()>& ignoreMark,
360                                    const RefPtr<OHOS::Ace::NG::FrameNode>& node) {
361         ContainerScope scope(id);
362         auto context = weak.Upgrade();
363         if (context == nullptr) {
364             return;
365         }
366         context->GetTaskExecutor()->PostTask(
367             [context, event]() { context->OnAxisEvent(event); },
368             TaskExecutor::TaskType::UI, "ArkUIAceContainerAxisEvent");
369     };
370     aceView_->RegisterAxisEventCallback(axisEventCallback);
371 
372     auto&& crownEventCallback = [weak, id = instanceId_](
373         const CrownEvent& event, const std::function<void()>& ignoreMark) {
374         ContainerScope scope(id);
375         auto context = weak.Upgrade();
376         if (context == nullptr) {
377             return false;
378         }
379         context->GetTaskExecutor()->PostTask(
380             [context, event, id]() {
381                 ContainerScope scope(id);
382                 context->OnNonPointerEvent(event);
383             },
384             TaskExecutor::TaskType::UI, "ArkUIAceContainerCrownEvent");
385         return true;
386     };
387     aceView_->RegisterCrownEventCallback(crownEventCallback);
388 
389     auto&& rotationEventCallback = [weak, id = instanceId_](const RotationEvent& event) {
390         ContainerScope scope(id);
391         auto context = weak.Upgrade();
392         if (context == nullptr) {
393             return false;
394         }
395         bool result = false;
396         context->GetTaskExecutor()->PostSyncTask(
397             [context, event, &result]() { result = context->OnRotationEvent(event); },
398             TaskExecutor::TaskType::UI, "ArkUIAceContainerRotationEvent");
399         return result;
400     };
401     aceView_->RegisterRotationEventCallback(rotationEventCallback);
402 
403     auto&& cardViewPositionCallback = [weak, instanceId = instanceId_](int id, float offsetX, float offsetY) {
404         ContainerScope scope(instanceId);
405         auto context = AceType::DynamicCast<PipelineContext>(weak.Upgrade());
406         if (context == nullptr) {
407             return;
408         }
409         context->GetTaskExecutor()->PostSyncTask(
410             [context, id, offsetX, offsetY]() { context->SetCardViewPosition(id, offsetX, offsetY); },
411             TaskExecutor::TaskType::UI, "ArkUISetCardViewPosition");
412     };
413     aceView_->RegisterCardViewPositionCallback(cardViewPositionCallback);
414 
415     auto&& cardViewParamsCallback = [weak, id = instanceId_](const std::string& key, bool focus) {
416         ContainerScope scope(id);
417         auto context = AceType::DynamicCast<PipelineContext>(weak.Upgrade());
418         if (context == nullptr) {
419             return;
420         }
421         context->GetTaskExecutor()->PostSyncTask(
422             [context, key, focus]() { context->SetCardViewAccessibilityParams(key, focus); },
423             TaskExecutor::TaskType::UI, "ArkUISetCardViewAccessibilityParams");
424     };
425     aceView_->RegisterCardViewAccessibilityParamsCallback(cardViewParamsCallback);
426 
427     auto&& viewChangeCallback = [weak, id = instanceId_](int32_t width, int32_t height, WindowSizeChangeReason type,
428                                     const std::shared_ptr<Rosen::RSTransaction>& rsTransaction) {
429         ContainerScope scope(id);
430         auto context = weak.Upgrade();
431         if (context == nullptr) {
432             return;
433         }
434         ACE_SCOPED_TRACE("ViewChangeCallback(%d, %d)", width, height);
435         context->GetTaskExecutor()->PostTask(
436             [context, width, height, type, rsTransaction]() {
437                 context->OnSurfaceChanged(width, height, type, rsTransaction);
438             },
439             TaskExecutor::TaskType::UI, "ArkUISurfaceChanged");
440     };
441     aceView_->RegisterViewChangeCallback(viewChangeCallback);
442 
443     auto&& densityChangeCallback = [weak, id = instanceId_](double density) {
444         ContainerScope scope(id);
445         auto context = weak.Upgrade();
446         if (context == nullptr) {
447             return;
448         }
449         ACE_SCOPED_TRACE("DensityChangeCallback(%lf)", density);
450         context->GetTaskExecutor()->PostTask(
451             [context, density]() { context->OnSurfaceDensityChanged(density); },
452             TaskExecutor::TaskType::UI, "ArkUIDensityChanged");
453     };
454     aceView_->RegisterDensityChangeCallback(densityChangeCallback);
455 
456     auto&& systemBarHeightChangeCallback = [weak, id = instanceId_](double statusBar, double navigationBar) {
457         ContainerScope scope(id);
458         auto context = weak.Upgrade();
459         if (context == nullptr) {
460             return;
461         }
462         ACE_SCOPED_TRACE("SystemBarHeightChangeCallback(%lf, %lf)", statusBar, navigationBar);
463         context->GetTaskExecutor()->PostTask(
464             [context, statusBar, navigationBar]() { context->OnSystemBarHeightChanged(statusBar, navigationBar); },
465             TaskExecutor::TaskType::UI, "ArkUISystemBarHeightChanged");
466     };
467     aceView_->RegisterSystemBarHeightChangeCallback(systemBarHeightChangeCallback);
468 
469     auto&& surfaceDestroyCallback = [weak, id = instanceId_]() {
470         ContainerScope scope(id);
471         auto context = weak.Upgrade();
472         if (context == nullptr) {
473             return;
474         }
475         context->GetTaskExecutor()->PostTask(
476             [context]() { context->OnSurfaceDestroyed(); },
477             TaskExecutor::TaskType::UI, "ArkUISurfaceDestroyed");
478     };
479     aceView_->RegisterSurfaceDestroyCallback(surfaceDestroyCallback);
480 
481     auto&& idleCallback = [weak, id = instanceId_](int64_t deadline) {
482         ContainerScope scope(id);
483         auto context = weak.Upgrade();
484         if (context == nullptr) {
485             return;
486         }
487         context->GetTaskExecutor()->PostTask(
488             [context, deadline]() { context->OnIdle(deadline); }, TaskExecutor::TaskType::UI, "ArkUIIdleTask");
489     };
490     aceView_->RegisterIdleCallback(idleCallback);
491 }
492 
CreateContainer(int32_t instanceId,FrontendType type,bool useNewPipeline,bool useCurrentEventRunner)493 void AceContainer::CreateContainer(
494     int32_t instanceId, FrontendType type, bool useNewPipeline, bool useCurrentEventRunner)
495 {
496     auto aceContainer = AceType::MakeRefPtr<AceContainer>(instanceId, type, useNewPipeline, useCurrentEventRunner);
497     AceEngine::Get().AddContainer(aceContainer->GetInstanceId(), aceContainer);
498     aceContainer->Initialize();
499     ContainerScope scope(instanceId);
500     auto front = aceContainer->GetFrontend();
501     if (front) {
502         front->UpdateState(Frontend::State::ON_CREATE);
503         front->SetJsMessageDispatcher(aceContainer);
504     }
505     auto platMessageBridge = aceContainer->GetMessageBridge();
506     platMessageBridge->SetJsMessageDispatcher(aceContainer);
507 }
508 
DestroyContainer(int32_t instanceId)509 void AceContainer::DestroyContainer(int32_t instanceId)
510 {
511     auto container = AceEngine::Get().GetContainer(instanceId);
512     if (!container) {
513         return;
514     }
515     container->Destroy();
516     // unregister watchdog before stop thread to avoid UI_BLOCK report
517     AceEngine::Get().UnRegisterFromWatchDog(instanceId);
518     auto taskExecutor = container->GetTaskExecutor();
519     if (taskExecutor) {
520         taskExecutor->PostSyncTask([] { LOGI("Wait UI thread..."); }, TaskExecutor::TaskType::UI, "ArkUIWaitLog");
521         taskExecutor->PostSyncTask([] { LOGI("Wait JS thread..."); }, TaskExecutor::TaskType::JS, "ArkUIWaitLog");
522     }
523     container->DestroyView(); // Stop all threads(ui,gpu,io) for current ability.
524     EngineHelper::RemoveEngine(instanceId);
525     AceEngine::Get().RemoveContainer(instanceId);
526 }
527 
RunPage(int32_t instanceId,const std::string & url,const std::string & params,bool isNamedRouter)528 UIContentErrorCode AceContainer::RunPage(
529     int32_t instanceId, const std::string& url, const std::string& params, bool isNamedRouter)
530 {
531     ACE_FUNCTION_TRACE();
532     auto container = AceEngine::Get().GetContainer(instanceId);
533     if (!container) {
534         return UIContentErrorCode::NULL_POINTER;
535     }
536 
537     ContainerScope scope(instanceId);
538     auto front = container->GetFrontend();
539     CHECK_NULL_RETURN(front, UIContentErrorCode::NULL_POINTER);
540     auto type = front->GetType();
541     if ((type == FrontendType::JS) || (type == FrontendType::DECLARATIVE_JS) || (type == FrontendType::JS_CARD) ||
542         (type == FrontendType::ETS_CARD)) {
543         if (isNamedRouter) {
544             return front->RunPageByNamedRouter(url, params);
545         }
546         return front->RunPage(url, params);
547     } else {
548         LOGE("Frontend type not supported when runpage");
549     }
550     return UIContentErrorCode::NULL_POINTER;
551 }
552 
UpdateResourceConfiguration(const std::string & jsonStr)553 void AceContainer::UpdateResourceConfiguration(const std::string& jsonStr)
554 {
555     ContainerScope scope(instanceId_);
556     uint32_t updateFlags = 0;
557     auto resConfig = resourceInfo_.GetResourceConfiguration();
558     if (!resConfig.UpdateFromJsonString(jsonStr, updateFlags) || !updateFlags) {
559         return;
560     }
561     resourceInfo_.SetResourceConfiguration(resConfig);
562     if (ResourceConfiguration::TestFlag(updateFlags, ResourceConfiguration::COLOR_MODE_UPDATED_FLAG)) {
563         SetColorMode(resConfig.GetColorMode());
564         if (frontend_) {
565             frontend_->SetColorMode(resConfig.GetColorMode());
566         }
567     }
568     if (!pipelineContext_) {
569         return;
570     }
571     auto themeManager = pipelineContext_->GetThemeManager();
572     if (!themeManager) {
573         return;
574     }
575     themeManager->UpdateConfig(resConfig);
576     if (SystemProperties::GetResourceDecoupling()) {
577         ResourceManager::GetInstance().UpdateResourceConfig(resConfig);
578     }
579     taskExecutor_->PostTask(
580         [weakThemeManager = WeakPtr<ThemeManager>(themeManager), colorScheme = colorScheme_, config = resConfig,
581             weakContext = WeakPtr<PipelineBase>(pipelineContext_)]() {
582             auto themeManager = weakThemeManager.Upgrade();
583             auto context = weakContext.Upgrade();
584             if (!themeManager || !context) {
585                 return;
586             }
587             themeManager->LoadResourceThemes();
588             themeManager->ParseSystemTheme();
589             themeManager->SetColorScheme(colorScheme);
590             context->RefreshRootBgColor();
591             context->UpdateFontWeightScale();
592             context->SetFontScale(config.GetFontRatio());
593         },
594         TaskExecutor::TaskType::UI, "ArkUIUpdateResourceConfig");
595     if (frontend_) {
596         frontend_->RebuildAllPages();
597     }
598 }
599 
NativeOnConfigurationUpdated(int32_t instanceId)600 void AceContainer::NativeOnConfigurationUpdated(int32_t instanceId)
601 {
602     auto container = GetContainerInstance(instanceId);
603     if (!container) {
604         return;
605     }
606     ContainerScope scope(instanceId);
607     auto front = container->GetFrontend();
608     if (!front) {
609         return;
610     }
611 
612     std::unique_ptr<JsonValue> value = JsonUtil::Create(true);
613     value->Put("fontScale", container->GetResourceConfiguration().GetFontRatio());
614     value->Put("colorMode", container->GetColorMode() == ColorMode::LIGHT ? "light" : "dark");
615     auto declarativeFrontend = AceType::DynamicCast<DeclarativeFrontend>(front);
616     if (declarativeFrontend) {
617         container->UpdateResourceConfiguration(value->ToString());
618         declarativeFrontend->OnConfigurationUpdated(value->ToString());
619         return;
620     }
621 
622     std::unique_ptr<JsonValue> localeValue = JsonUtil::Create(true);
623     localeValue->Put(LANGUAGE_TAG, AceApplicationInfo::GetInstance().GetLanguage().c_str());
624     localeValue->Put(COUNTRY_TAG, AceApplicationInfo::GetInstance().GetCountryOrRegion().c_str());
625     localeValue->Put(
626         DIRECTION_TAG, AceApplicationInfo::GetInstance().IsRightToLeft() ? LOCALE_DIR_RTL : LOCALE_DIR_LTR);
627     localeValue->Put(UNICODE_SETTING_TAG, AceApplicationInfo::GetInstance().GetUnicodeSetting().c_str());
628     value->Put(LOCALE_KEY, localeValue);
629     front->OnConfigurationUpdated(value->ToString());
630 }
631 
Dispatch(const std::string & group,std::vector<uint8_t> && data,int32_t id,bool replyToComponent) const632 void AceContainer::Dispatch(
633     const std::string& group, std::vector<uint8_t>&& data, int32_t id, bool replyToComponent) const
634 {}
635 
FetchResponse(const ResponseData responseData,const int32_t callbackId) const636 void AceContainer::FetchResponse(const ResponseData responseData, const int32_t callbackId) const
637 {
638     auto container = AceType::DynamicCast<AceContainer>(AceEngine::Get().GetContainer(0));
639     if (!container) {
640         return;
641     }
642     ContainerScope scope(instanceId_);
643     auto front = container->GetFrontend();
644     auto type = container->GetType();
645     if (type == FrontendType::JS) {
646         auto jsFrontend = AceType::DynamicCast<JsFrontend>(front);
647         if (jsFrontend) {
648             jsFrontend->TransferJsResponseDataPreview(callbackId, ACTION_SUCCESS, responseData);
649         }
650     } else if (type == FrontendType::DECLARATIVE_JS) {
651         auto declarativeFrontend = AceType::DynamicCast<DeclarativeFrontend>(front);
652         if (declarativeFrontend) {
653             declarativeFrontend->TransferJsResponseDataPreview(callbackId, ACTION_SUCCESS, responseData);
654         }
655     } else {
656         return;
657     }
658 }
659 
CallCurlFunction(const RequestData requestData,const int32_t callbackId) const660 void AceContainer::CallCurlFunction(const RequestData requestData, const int32_t callbackId) const
661 {
662     auto container = AceType::DynamicCast<AceContainer>(AceEngine::Get().GetContainer(ACE_INSTANCE_ID));
663     if (!container) {
664         return;
665     }
666 
667     ContainerScope scope(instanceId_);
668     taskExecutor_->PostTask(
669         [container, requestData, callbackId]() mutable {
670             ResponseData responseData;
671             if (FetchManager::GetInstance().Fetch(requestData, callbackId, responseData)) {
672                 container->FetchResponse(responseData, callbackId);
673             }
674         },
675         TaskExecutor::TaskType::BACKGROUND, "ArkUICallCurlFunction");
676 }
677 
DispatchPluginError(int32_t callbackId,int32_t errorCode,std::string && errorMessage) const678 void AceContainer::DispatchPluginError(int32_t callbackId, int32_t errorCode, std::string&& errorMessage) const
679 {
680     auto front = GetFrontend();
681     if (!front) {
682         return;
683     }
684 
685     ContainerScope scope(instanceId_);
686     taskExecutor_->PostTask(
687         [front, callbackId, errorCode, errorMessage = std::move(errorMessage)]() mutable {
688             front->TransferJsPluginGetError(callbackId, errorCode, std::move(errorMessage));
689         },
690         TaskExecutor::TaskType::BACKGROUND, "ArkUIDispatchPluginError");
691 }
692 
AddRouterChangeCallback(int32_t instanceId,const OnRouterChangeCallback & onRouterChangeCallback)693 void AceContainer::AddRouterChangeCallback(int32_t instanceId, const OnRouterChangeCallback& onRouterChangeCallback)
694 {
695     auto container = GetContainerInstance(instanceId);
696     if (!container) {
697         return;
698     }
699     ContainerScope scope(instanceId);
700     if (!container->pipelineContext_) {
701         LOGW("container pipelineContext not init");
702         return;
703     }
704     container->pipelineContext_->AddRouterChangeCallback(onRouterChangeCallback);
705 }
706 
707 #ifndef ENABLE_ROSEN_BACKEND
AddAssetPath(int32_t instanceId,const std::string & packagePath,const std::vector<std::string> & paths)708 void AceContainer::AddAssetPath(
709     int32_t instanceId, const std::string& packagePath, const std::vector<std::string>& paths)
710 {
711     auto container = GetContainerInstance(instanceId);
712     CHECK_NULL_VOID(container);
713     if (!container->assetManager_) {
714         RefPtr<AssetManagerImpl> assetManagerImpl = Referenced::MakeRefPtr<AssetManagerImpl>();
715         container->assetManager_ = assetManagerImpl;
716         if (container->frontend_) {
717             container->frontend_->SetAssetManager(assetManagerImpl);
718         }
719     }
720     auto fileAssetProvider = AceType::MakeRefPtr<FileAssetProviderImpl>();
721     if (fileAssetProvider->Initialize("", paths)) {
722         LOGI("Push AssetProvider to queue.");
723         container->assetManager_->PushBack(std::move(fileAssetProvider));
724     }
725 }
726 #else
AddAssetPath(int32_t instanceId,const std::string & packagePath,const std::vector<std::string> & paths)727 void AceContainer::AddAssetPath(
728     int32_t instanceId, const std::string& packagePath, const std::vector<std::string>& paths)
729 {
730     auto container = GetContainerInstance(instanceId);
731     CHECK_NULL_VOID(container);
732 
733     if (!container->assetManager_) {
734         RefPtr<RSAssetManager> rsAssetManager = Referenced::MakeRefPtr<RSAssetManager>();
735         container->assetManager_ = rsAssetManager;
736         if (container->frontend_) {
737             container->frontend_->SetAssetManager(rsAssetManager);
738         }
739     }
740 
741     for (const auto& path : paths) {
742         auto dirAssetProvider = AceType::MakeRefPtr<RSDirAssetProvider>(path);
743         container->assetManager_->PushBack(std::move(dirAssetProvider));
744     }
745 }
746 #endif
747 
SetResourcesPathAndThemeStyle(int32_t instanceId,const std::string & systemResourcesPath,const std::string & hmsResourcesPath,const std::string & appResourcesPath,const int32_t & themeId,const ColorMode & colorMode)748 void AceContainer::SetResourcesPathAndThemeStyle(int32_t instanceId, const std::string& systemResourcesPath,
749     const std::string& hmsResourcesPath, const std::string& appResourcesPath, const int32_t& themeId,
750     const ColorMode& colorMode)
751 {
752     auto container = GetContainerInstance(instanceId);
753     if (!container) {
754         return;
755     }
756     ContainerScope scope(instanceId);
757     auto resConfig = container->resourceInfo_.GetResourceConfiguration();
758     resConfig.SetColorMode(static_cast<OHOS::Ace::ColorMode>(colorMode));
759     container->resourceInfo_.SetResourceConfiguration(resConfig);
760     container->resourceInfo_.SetPackagePath(appResourcesPath);
761     container->resourceInfo_.SetSystemPackagePath(systemResourcesPath);
762     if (!hmsResourcesPath.empty()) {
763         container->resourceInfo_.SetHmsPackagePath(hmsResourcesPath);
764     }
765     container->resourceInfo_.SetThemeId(themeId);
766 }
767 
UpdateDeviceConfig(const DeviceConfig & deviceConfig)768 void AceContainer::UpdateDeviceConfig(const DeviceConfig& deviceConfig)
769 {
770     ContainerScope scope(instanceId_);
771     SystemProperties::InitDeviceType(deviceConfig.deviceType);
772     SystemProperties::SetDeviceOrientation(deviceConfig.orientation == DeviceOrientation::PORTRAIT ? 0 : 1);
773     SystemProperties::SetResolution(deviceConfig.density);
774     SetColorMode(deviceConfig.colorMode);
775     auto resConfig = resourceInfo_.GetResourceConfiguration();
776     if (resConfig.GetDeviceType() == deviceConfig.deviceType &&
777         resConfig.GetOrientation() == deviceConfig.orientation && resConfig.GetDensity() == deviceConfig.density &&
778         resConfig.GetColorMode() == deviceConfig.colorMode && resConfig.GetFontRatio() == deviceConfig.fontRatio) {
779         return;
780     } else {
781         resConfig.SetDeviceType(deviceConfig.deviceType);
782         resConfig.SetOrientation(deviceConfig.orientation);
783         resConfig.SetDensity(deviceConfig.density);
784         resConfig.SetColorMode(deviceConfig.colorMode);
785         resConfig.SetFontRatio(deviceConfig.fontRatio);
786         if (frontend_) {
787             frontend_->SetColorMode(deviceConfig.colorMode);
788         }
789     }
790     resourceInfo_.SetResourceConfiguration(resConfig);
791     if (!pipelineContext_) {
792         return;
793     }
794     auto themeManager = pipelineContext_->GetThemeManager();
795     if (!themeManager) {
796         return;
797     }
798     themeManager->UpdateConfig(resConfig);
799     if (SystemProperties::GetResourceDecoupling()) {
800         ResourceManager::GetInstance().UpdateResourceConfig(resConfig);
801     }
802     taskExecutor_->PostTask(
803         [weakThemeManager = WeakPtr<ThemeManager>(themeManager), colorScheme = colorScheme_,
804             weakContext = WeakPtr<PipelineBase>(pipelineContext_)]() {
805             auto themeManager = weakThemeManager.Upgrade();
806             auto context = weakContext.Upgrade();
807             if (!themeManager || !context) {
808                 return;
809             }
810             themeManager->LoadResourceThemes();
811             themeManager->ParseSystemTheme();
812             themeManager->SetColorScheme(colorScheme);
813             context->RefreshRootBgColor();
814         },
815         TaskExecutor::TaskType::UI, "ArkUILoadTheme");
816 }
817 
818 #ifndef ENABLE_ROSEN_BACKEND
SetView(AceViewPreview * view,double density,int32_t width,int32_t height)819 void AceContainer::SetView(AceViewPreview* view, double density, int32_t width, int32_t height)
820 {
821     if (view == nullptr) {
822         return;
823     }
824 
825     auto container = AceType::DynamicCast<AceContainer>(AceEngine::Get().GetContainer(view->GetInstanceId()));
826     if (!container) {
827         return;
828     }
829     auto platformWindow = PlatformWindow::Create(view);
830     if (!platformWindow) {
831         LOGE("Create PlatformWindow failed!");
832         return;
833     }
834 
835     auto window = std::make_shared<Window>(std::move(platformWindow));
836     container->AttachView(std::move(window), view, density, width, height);
837 }
838 #else
SetView(AceViewPreview * view,sptr<Rosen::Window> rsWindow,double density,int32_t width,int32_t height,UIEnvCallback callback)839 void AceContainer::SetView(AceViewPreview* view, sptr<Rosen::Window> rsWindow, double density, int32_t width,
840     int32_t height, UIEnvCallback callback)
841 {
842     CHECK_NULL_VOID(view);
843     auto container = AceType::DynamicCast<AceContainer>(AceEngine::Get().GetContainer(view->GetInstanceId()));
844     CHECK_NULL_VOID(container);
845     auto taskExecutor = container->GetTaskExecutor();
846     CHECK_NULL_VOID(taskExecutor);
847     auto window = std::make_shared<NG::RosenWindow>(rsWindow, taskExecutor, view->GetInstanceId());
848     window->Init();
849     auto rsUIDirector = window->GetRSUIDirector();
850     CHECK_NULL_VOID(rsUIDirector);
851     rsUIDirector->SetFlushEmptyCallback(AcePreviewHelper::GetInstance()->GetCallbackFlushEmpty());
852     container->AttachView(std::move(window), view, density, width, height, callback);
853 }
854 #endif
855 
856 #ifndef ENABLE_ROSEN_BACKEND
AttachView(std::shared_ptr<Window> window,AceViewPreview * view,double density,int32_t width,int32_t height)857 void AceContainer::AttachView(
858     std::shared_ptr<Window> window, AceViewPreview* view, double density, int32_t width, int32_t height)
859 {
860     ContainerScope scope(instanceId_);
861     aceView_ = view;
862     auto instanceId = aceView_->GetInstanceId();
863 
864     auto state = flutter::UIDartState::Current()->GetStateById(instanceId);
865     ACE_DCHECK(state != nullptr);
866     auto taskExecutorImpl = AceType::DynamicCast<TaskExecutorImpl>(taskExecutorImpl_);
867     taskExecutorImpl->InitOtherThreads(state->GetTaskRunners());
868     if (type_ == FrontendType::DECLARATIVE_JS) {
869         // For DECLARATIVE_JS frontend display UI in JS thread temporarily.
870         taskExecutorImpl->InitJsThread(false);
871     }
872     if (type_ == FrontendType::DECLARATIVE_JS) {
873         InitializeFrontend();
874         auto front = GetFrontend();
875         if (front) {
876             front->UpdateState(Frontend::State::ON_CREATE);
877             front->SetJsMessageDispatcher(AceType::Claim(this));
878         }
879     }
880     resRegister_ = aceView_->GetPlatformResRegister();
881     auto pipelineContext = AceType::MakeRefPtr<PipelineContext>(
882         std::move(window), taskExecutor_, assetManager_, resRegister_, frontend_, instanceId);
883     pipelineContext->SetRootSize(density, width, height);
884     pipelineContext->SetTextFieldManager(AceType::MakeRefPtr<TextFieldManager>());
885     pipelineContext->SetIsRightToLeft(AceApplicationInfo::GetInstance().IsRightToLeft());
886     pipelineContext->SetMessageBridge(messageBridge_);
887     pipelineContext->SetWindowModal(windowModal_);
888     pipelineContext->SetDrawDelegate(aceView_->GetDrawDelegate());
889     pipelineContext->SetIsJsCard(type_ == FrontendType::JS_CARD);
890     pipelineContext_ = pipelineContext;
891     InitializeCallback();
892 
893     ThemeConstants::InitDeviceType();
894     // Only init global resource here, construct theme in UI thread
895     auto themeManager = AceType::MakeRefPtr<ThemeManagerImpl>();
896 
897     if (SystemProperties::GetResourceDecoupling()) {
898         auto resourceAdapter = ResourceAdapter::Create();
899         resourceAdapter->Init(resourceInfo);
900         SaveResourceAdapter(bundleName_, moduleName_, instanceId_, resourceAdapter);
901         themeManager = AceType::MakeRefPtr<ThemeManagerImpl>(resourceAdapter);
902     }
903     if (themeManager) {
904         pipelineContext_->SetThemeManager(themeManager);
905         // Init resource, load theme map.
906         if (!SystemProperties::GetResourceDecoupling()) {
907             themeManager->InitResource(resourceInfo_);
908         }
909         themeManager->LoadSystemTheme(resourceInfo_.GetThemeId());
910         taskExecutor_->PostTask(
911             [themeManager, assetManager = assetManager_, colorScheme = colorScheme_,
912                 pipelineContext = pipelineContext_]() {
913                 themeManager->ParseSystemTheme();
914                 themeManager->SetColorScheme(colorScheme);
915                 themeManager->LoadCustomTheme(assetManager);
916                 // get background color from theme
917                 pipelineContext->SetAppBgColor(themeManager->GetBackgroundColor());
918             },
919             TaskExecutor::TaskType::UI, "ArkUISetBackgroundColor");
920     }
921 
922     auto weak = AceType::WeakClaim(AceType::RawPtr(pipelineContext_));
923     taskExecutor_->PostTask(
924         [weak]() {
925             auto context = weak.Upgrade();
926             if (context == nullptr) {
927                 return;
928             }
929             context->SetupRootElement();
930         },
931         TaskExecutor::TaskType::UI, "ArkUISetupRootElement");
932     aceView_->Launch();
933 
934     frontend_->AttachPipelineContext(pipelineContext_);
935     auto cardFronted = AceType::DynamicCast<CardFrontend>(frontend_);
936     if (cardFronted) {
937         cardFronted->SetDensity(static_cast<double>(density));
938         taskExecutor_->PostTask(
939             [weak, width, height]() {
940                 auto context = weak.Upgrade();
941                 if (context == nullptr) {
942                     return;
943                 }
944                 context->OnSurfaceChanged(width, height);
945             },
946             TaskExecutor::TaskType::UI, "ArkUISurfaceChanged");
947     }
948 
949     AceEngine::Get().RegisterToWatchDog(instanceId, taskExecutor_, GetSettings().useUIAsJSThread);
950 }
951 #else
AttachView(std::shared_ptr<Window> window,AceViewPreview * view,double density,int32_t width,int32_t height,UIEnvCallback callback)952 void AceContainer::AttachView(std::shared_ptr<Window> window, AceViewPreview* view, double density, int32_t width,
953     int32_t height, UIEnvCallback callback)
954 {
955     ContainerScope scope(instanceId_);
956     aceView_ = view;
957     auto instanceId = aceView_->GetInstanceId();
958 
959     auto taskExecutorImpl = AceType::DynamicCast<TaskExecutorImpl>(taskExecutor_);
960     CHECK_NULL_VOID(taskExecutorImpl);
961     taskExecutorImpl->InitOtherThreads(aceView_->GetThreadModelImpl());
962     if (type_ == FrontendType::DECLARATIVE_JS || type_ == FrontendType::ETS_CARD) {
963         // For DECLARATIVE_JS frontend display UI in JS thread temporarily.
964         taskExecutorImpl->InitJsThread(false);
965     }
966     if (type_ == FrontendType::DECLARATIVE_JS || type_ == FrontendType::ETS_CARD) {
967         InitializeFrontend();
968         SetHspBufferTrackerCallback();
969         SetMockModuleListToJsEngine();
970         auto front = AceType::DynamicCast<DeclarativeFrontend>(GetFrontend());
971         if (front) {
972             front->UpdateState(Frontend::State::ON_CREATE);
973             front->SetJsMessageDispatcher(AceType::Claim(this));
974             auto weak = WeakPtr(front->GetJsEngine());
975             taskExecutor_->PostTask(
976                 [weak, containerSdkPath = containerSdkPath_]() {
977                     auto jsEngine = weak.Upgrade();
978                     CHECK_NULL_VOID(jsEngine);
979                     auto* nativeEngine = jsEngine->GetNativeEngine();
980                     CHECK_NULL_VOID(nativeEngine);
981                     auto* moduleManager = nativeEngine->GetModuleManager();
982                     CHECK_NULL_VOID(moduleManager);
983                     moduleManager->SetPreviewSearchPath(containerSdkPath);
984                 },
985                 TaskExecutor::TaskType::JS, "ArkUISetPreviewSearchPath");
986         }
987     }
988     resRegister_ = aceView_->GetPlatformResRegister();
989     if (useNewPipeline_) {
990         pipelineContext_ = AceType::MakeRefPtr<NG::PipelineContext>(
991             std::move(window), taskExecutor_, assetManager_, resRegister_, frontend_, instanceId);
992         pipelineContext_->SetTextFieldManager(AceType::MakeRefPtr<NG::TextFieldManagerNG>());
993     } else {
994         pipelineContext_ = AceType::MakeRefPtr<PipelineContext>(
995             std::move(window), taskExecutor_, assetManager_, resRegister_, frontend_, instanceId);
996         pipelineContext_->SetTextFieldManager(AceType::MakeRefPtr<TextFieldManager>());
997     }
998     pipelineContext_->SetRootSize(density, width, height);
999     pipelineContext_->SetIsRightToLeft(AceApplicationInfo::GetInstance().IsRightToLeft());
1000     pipelineContext_->SetMessageBridge(messageBridge_);
1001     pipelineContext_->SetWindowModal(windowModal_);
1002     pipelineContext_->SetDrawDelegate(aceView_->GetDrawDelegate());
1003     pipelineContext_->SetIsJsCard(type_ == FrontendType::JS_CARD);
1004     if (installationFree_ && !isComponentMode_) {
1005         pipelineContext_->SetInstallationFree(installationFree_);
1006         pipelineContext_->SetAppLabelId(labelId_);
1007     }
1008     pipelineContext_->OnShow();
1009     pipelineContext_->WindowFocus(true);
1010     InitializeCallback();
1011 
1012     auto cardFrontend = AceType::DynamicCast<FormFrontendDeclarative>(frontend_);
1013     if (cardFrontend) {
1014         pipelineContext_->SetIsFormRender(true);
1015         cardFrontend->SetLoadCardCallBack(WeakPtr<PipelineBase>(pipelineContext_));
1016     }
1017 
1018     ThemeConstants::InitDeviceType();
1019     // Only init global resource here, construct theme in UI thread
1020     auto themeManager = AceType::MakeRefPtr<ThemeManagerImpl>();
1021 
1022     if (SystemProperties::GetResourceDecoupling()) {
1023         auto resourceAdapter = ResourceAdapter::Create();
1024         resourceAdapter->Init(resourceInfo_);
1025         SaveResourceAdapter(bundleName_, moduleName_, instanceId_, resourceAdapter);
1026         themeManager = AceType::MakeRefPtr<ThemeManagerImpl>(resourceAdapter);
1027     }
1028 
1029     if (themeManager) {
1030         pipelineContext_->SetThemeManager(themeManager);
1031         // Init resource, load theme map.
1032         if (!SystemProperties::GetResourceDecoupling()) {
1033             themeManager->InitResource(resourceInfo_);
1034         }
1035         themeManager->LoadSystemTheme(resourceInfo_.GetThemeId());
1036         taskExecutor_->PostTask(
1037             [themeManager, assetManager = assetManager_, colorScheme = colorScheme_,
1038                 pipelineContext = pipelineContext_]() {
1039                 themeManager->ParseSystemTheme();
1040                 themeManager->SetColorScheme(colorScheme);
1041                 themeManager->LoadCustomTheme(assetManager);
1042                 // get background color from theme
1043                 pipelineContext->SetAppBgColor(themeManager->GetBackgroundColor());
1044             },
1045             TaskExecutor::TaskType::UI, "ArkUISetBackgroundColor");
1046     }
1047     if (!useNewPipeline_) {
1048         taskExecutor_->PostTask(
1049             [context = pipelineContext_, callback]() {
1050                 CHECK_NULL_VOID(callback);
1051                 callback(AceType::DynamicCast<PipelineContext>(context));
1052             },
1053             TaskExecutor::TaskType::UI, "ArkUIEnvCallback");
1054     }
1055 
1056     auto weak = AceType::WeakClaim(AceType::RawPtr(pipelineContext_));
1057     taskExecutor_->PostTask(
1058         [weak]() {
1059             auto context = weak.Upgrade();
1060             if (context == nullptr) {
1061                 return;
1062             }
1063             context->SetupRootElement();
1064         },
1065         TaskExecutor::TaskType::UI, "ArkUISetupRootElement");
1066     aceView_->Launch();
1067 
1068     frontend_->AttachPipelineContext(pipelineContext_);
1069     auto cardFronted = AceType::DynamicCast<CardFrontend>(frontend_);
1070     if (cardFronted) {
1071         cardFronted->SetDensity(static_cast<double>(density));
1072         taskExecutor_->PostTask(
1073             [weak, width, height]() {
1074                 auto context = weak.Upgrade();
1075                 if (context == nullptr) {
1076                     return;
1077                 }
1078                 context->OnSurfaceChanged(width, height);
1079             },
1080             TaskExecutor::TaskType::UI, "ArkUISurfaceChanged");
1081     }
1082 
1083     AceEngine::Get().RegisterToWatchDog(instanceId, taskExecutor_, GetSettings().useUIAsJSThread);
1084 }
1085 #endif
1086 
GetContainerInstance(int32_t instanceId)1087 RefPtr<AceContainer> AceContainer::GetContainerInstance(int32_t instanceId)
1088 {
1089     auto container = AceType::DynamicCast<AceContainer>(AceEngine::Get().GetContainer(instanceId));
1090     return container;
1091 }
1092 
GetContentInfo(int32_t instanceId,ContentInfoType type)1093 std::string AceContainer::GetContentInfo(int32_t instanceId, ContentInfoType type)
1094 {
1095     auto container = AceEngine::Get().GetContainer(instanceId);
1096     CHECK_NULL_RETURN(container, "");
1097     ContainerScope scope(instanceId);
1098     auto front = container->GetFrontend();
1099     CHECK_NULL_RETURN(front, "");
1100     return front->GetContentInfo(type);
1101 }
1102 
LoadDocument(const std::string & url,const std::string & componentName)1103 void AceContainer::LoadDocument(const std::string& url, const std::string& componentName)
1104 {
1105     ContainerScope scope(instanceId_);
1106     if (type_ != FrontendType::DECLARATIVE_JS) {
1107         LOGE("Component Preview failed: 1.0 not support");
1108         return;
1109     }
1110     auto frontend = AceType::DynamicCast<OHOS::Ace::DeclarativeFrontend>(frontend_);
1111     if (!frontend) {
1112         LOGE("Component Preview failed: the frontend is nullptr");
1113         return;
1114     }
1115     auto jsEngine = frontend->GetJsEngine();
1116     if (!jsEngine) {
1117         LOGE("Component Preview failed: the jsEngine is nullptr");
1118         return;
1119     }
1120     taskExecutor_->PostTask(
1121         [front = frontend, componentName, url, jsEngine]() {
1122             front->SetPagePath(url);
1123             jsEngine->ReplaceJSContent(url, componentName);
1124         },
1125         TaskExecutor::TaskType::JS, "ArkUIReplaceJsContent");
1126 }
1127 
NotifyConfigurationChange(bool,const ConfigurationChange & configurationChange)1128 void AceContainer::NotifyConfigurationChange(bool, const ConfigurationChange& configurationChange)
1129 {
1130     taskExecutor_->PostTask(
1131         [weakContext = WeakPtr<PipelineBase>(pipelineContext_), configurationChange]() {
1132             auto pipeline = weakContext.Upgrade();
1133             CHECK_NULL_VOID(pipeline);
1134             pipeline->NotifyConfigurationChange();
1135             pipeline->FlushReload(configurationChange);
1136         },
1137         TaskExecutor::TaskType::UI, "ArkUINotifyConfigurationChange");
1138 }
1139 } // namespace OHOS::Ace::Platform
1140