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