• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 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 "JsAppImpl.h"
17 
18 #include "CommandParser.h"
19 #include "FileSystem.h"
20 #include "JsonReader.h"
21 #include "PreviewerEngineLog.h"
22 #include "SharedData.h"
23 #include "TraceTool.h"
24 #include "VirtualScreenImpl.h"
25 #include "external/EventHandler.h"
26 #include "viewport_config.h"
27 #include "glfw_render_context.h"
28 #include "window_model.h"
29 #if defined(__APPLE__) || defined(_WIN32)
30 #include "options.h"
31 #include "simulator.h"
32 #endif
33 
34 using namespace std;
35 using namespace OHOS;
36 using namespace OHOS::Ace;
37 
JsAppImpl()38 JsAppImpl::JsAppImpl() noexcept : ability(nullptr), isStop(false)
39 {
40 #if defined(__APPLE__) || defined(_WIN32)
41     windowModel = std::make_shared<OHOS::Previewer::PreviewerWindowModel>();
42 #endif
43 }
44 
~JsAppImpl()45 JsAppImpl::~JsAppImpl()
46 {
47     if (glfwRenderContext != nullptr) {
48         glfwRenderContext->DestroyWindow();
49         glfwRenderContext->Terminate();
50     }
51 }
52 
GetInstance()53 JsAppImpl& JsAppImpl::GetInstance()
54 {
55     static JsAppImpl instance;
56     return instance;
57 }
58 
Start()59 void JsAppImpl::Start()
60 {
61     VirtualScreenImpl::GetInstance().InitVirtualScreen();
62     VirtualScreenImpl::GetInstance().InitAll(pipeName, pipePort);
63     isFinished = false;
64     ILOG("Start run js app");
65     OHOS::AppExecFwk::EventHandler::SetMainThreadId(std::this_thread::get_id());
66     RunJsApp();
67     ILOG("Js app run finished");
68     while (!isStop) {
69         // Execute all tasks in the main thread
70         OHOS::AppExecFwk::EventHandler::Run();
71         glfwRenderContext->PollEvents();
72         std::this_thread::sleep_for(std::chrono::milliseconds(1));
73     }
74     isFinished = true;
75 }
76 
Restart()77 void JsAppImpl::Restart()
78 {
79     if (isDebug && debugServerPort >= 0) {
80 #if defined(__APPLE__) || defined(_WIN32)
81         if (simulator) {
82             simulator->TerminateAbility(debugAbilityId);
83         }
84 #endif
85     } else {
86         ability = nullptr;
87     }
88 }
89 
GetJSONTree()90 std::string JsAppImpl::GetJSONTree()
91 {
92     std::string jsongTree = ability->GetJSONTree();
93     Json::Value jsonData = JsonReader::ParseJsonData(jsongTree);
94     Json::StreamWriterBuilder builder;
95     builder["indentation"] = "";
96     builder["emitUTF8"] = true;
97     return Json::writeString(builder, jsonData);
98 }
99 
GetDefaultJSONTree()100 std::string JsAppImpl::GetDefaultJSONTree()
101 {
102     ILOG("Start getDefaultJsontree.");
103     std::string jsongTree = ability->GetDefaultJSONTree();
104     Json::Value jsonData = JsonReader::ParseJsonData(jsongTree);
105     ILOG("GetDefaultJsontree finished.");
106     Json::StreamWriterBuilder builder;
107     builder["indentation"] = "";
108     builder["emitUTF8"] = true;
109     return Json::writeString(builder, jsonData);
110 }
111 
OrientationChanged(std::string commandOrientation)112 void JsAppImpl::OrientationChanged(std::string commandOrientation)
113 {
114     aceRunArgs.deviceWidth = height;
115     aceRunArgs.deviceHeight = width;
116     VirtualScreenImpl::GetInstance().WidthAndHeightReverse();
117 
118     AdaptDeviceType(aceRunArgs, CommandParser::GetInstance().GetDeviceType(),
119                     VirtualScreenImpl::GetInstance().GetOrignalWidth());
120     AssignValueForWidthAndHeight(VirtualScreenImpl::GetInstance().GetOrignalWidth(),
121                                  VirtualScreenImpl::GetInstance().GetOrignalHeight(),
122                                  VirtualScreenImpl::GetInstance().GetCompressionWidth(),
123                                  VirtualScreenImpl::GetInstance().GetCompressionHeight());
124     if (commandOrientation == "portrait") {
125         aceRunArgs.deviceConfig.orientation = DeviceOrientation::PORTRAIT;
126     } else {
127         aceRunArgs.deviceConfig.orientation = DeviceOrientation::LANDSCAPE;
128     }
129 
130     orientation = commandOrientation;
131     ILOG("OrientationChanged: %s %d %d %f", orientation.c_str(), aceRunArgs.deviceWidth,
132          aceRunArgs.deviceHeight, aceRunArgs.deviceConfig.density);
133     if (ability != nullptr) {
134         OHOS::AppExecFwk::EventHandler::PostTask([this]() {
135             glfwRenderContext->SetWindowSize(width, height);
136         });
137         ability->SurfaceChanged(aceRunArgs.deviceConfig.orientation, aceRunArgs.deviceConfig.density,
138                                 aceRunArgs.deviceWidth, aceRunArgs.deviceHeight);
139     }
140 }
141 
ColorModeChanged(const std::string commandColorMode)142 void JsAppImpl::ColorModeChanged(const std::string commandColorMode)
143 {
144     if (commandColorMode == "light") {
145         aceRunArgs.deviceConfig.colorMode = ColorMode::LIGHT;
146     } else {
147         aceRunArgs.deviceConfig.colorMode = ColorMode::DARK;
148     }
149 
150     if (ability != nullptr) {
151         ability->OnConfigurationChanged(aceRunArgs.deviceConfig);
152     }
153 }
154 
Interrupt()155 void JsAppImpl::Interrupt()
156 {
157     isStop = true;
158     if (isDebug && debugServerPort >= 0) {
159 #if defined(__APPLE__) || defined(_WIN32)
160         if (simulator) {
161             simulator->TerminateAbility(debugAbilityId);
162         }
163 #endif
164     } else {
165         ability = nullptr;
166     }
167 }
168 
SetJsAppArgs(OHOS::Ace::Platform::AceRunArgs & args)169 void JsAppImpl::SetJsAppArgs(OHOS::Ace::Platform::AceRunArgs& args)
170 {
171     SetAssetPath(args, jsAppPath);
172     SetProjectModel(args);
173     SetPageProfile(args, CommandParser::GetInstance().GetPages());
174     SetDeviceWidth(args, width);
175     SetDeviceHeight(args, height);
176     SetWindowTitle(args, "Ace");
177     SetUrl(args, urlPath);
178     SetConfigChanges(args, configChanges);
179     SetColorMode(args, colorMode);
180     SetOrientation(args, orientation);
181     SetAceVersionArgs(args, aceVersion);
182     SetDeviceScreenDensity(atoi(screenDensity.c_str()),
183                            CommandParser::GetInstance().GetDeviceType());
184     SetLanguage(args, SharedData<string>::GetData(SharedDataType::LAN));
185     SetRegion(args, SharedData<string>::GetData(SharedDataType::REGION));
186     SetScript(args, "");
187     SetSystemResourcesPath(args);
188     SetAppResourcesPath(args, CommandParser::GetInstance().GetAppResourcePath());
189     SetFormsEnabled(args, CommandParser::GetInstance().IsCardDisplay());
190     SetContainerSdkPath(args, CommandParser::GetInstance().GetContainerSdkPath());
191     AdaptDeviceType(args, CommandParser::GetInstance().GetDeviceType(),
192                     VirtualScreenImpl::GetInstance().GetOrignalWidth());
193     SetOnRender(args);
194     SetOnRouterChange(args);
195     SetOnError(args);
196     SetComponentModeEnabled(args, CommandParser::GetInstance().IsComponentMode());
197     ILOG("start abilit: %d %d %f", args.deviceWidth, args.deviceHeight, args.deviceConfig.density);
198 }
199 
RunJsApp()200 void JsAppImpl::RunJsApp()
201 {
202     ILOG("RunJsApp 1");
203     AssignValueForWidthAndHeight(VirtualScreenImpl::GetInstance().GetOrignalWidth(),
204                                  VirtualScreenImpl::GetInstance().GetOrignalHeight(),
205                                  VirtualScreenImpl::GetInstance().GetCompressionWidth(),
206                                  VirtualScreenImpl::GetInstance().GetCompressionHeight());
207     SetJsAppArgs(aceRunArgs);
208     InitGlfwEnv();
209     if (isDebug && debugServerPort >= 0) {
210         RunDebugAbility(); // for debug preview
211     } else {
212         RunNormalAbility(); // for normal preview
213     }
214 }
215 
RunNormalAbility()216 void JsAppImpl::RunNormalAbility()
217 {
218     if (ability != nullptr) {
219         ability.reset();
220     }
221     TraceTool::GetInstance().HandleTrace("Launch Js App");
222     ability = Platform::AceAbility::CreateInstance(aceRunArgs);
223     if (ability == nullptr) {
224         ELOG("JsApp::Run ability create failed.");
225         return;
226     }
227     OHOS::Rosen::WMError errCode;
228     OHOS::sptr<OHOS::Rosen::WindowOption> sp = nullptr;
229     auto window = OHOS::Rosen::Window::Create("previewer", sp, nullptr, errCode);
230     window->SetContentInfoCallback(std::move(VirtualScreenImpl::LoadContentCallBack));
231     window->CreateSurfaceNode("preview_surface", aceRunArgs.onRender);
232     ability->SetWindow(window);
233     ability->InitEnv();
234 }
235 
236 #if defined(__APPLE__) || defined(_WIN32)
RunDebugAbility()237 void JsAppImpl::RunDebugAbility()
238 {
239     // init window params
240     SetWindowParams();
241     OHOS::Previewer::PreviewerWindow::GetInstance().SetWindowParams(*windowModel);
242     // start ability
243     OHOS::AbilityRuntime::Options options;
244     SetSimulatorParams(options);
245     simulator = OHOS::AbilityRuntime::Simulator::Create(options);
246     if (!simulator) {
247         ELOG("JsApp::Run simulator create failed.");
248         return;
249     }
250     std::string abilitySrcPath = CommandParser::GetInstance().GetAbilityPath();
251     debugAbilityId = simulator->StartAbility(abilitySrcPath, [](int64_t abilityId) {});
252     if (debugAbilityId < 0) {
253         ELOG("JsApp::Run ability start failed. abilitySrcPath:%s", abilitySrcPath.c_str());
254         return;
255     }
256     // set onRender callback
257     OHOS::Rosen::Window* window = OHOS::Previewer::PreviewerWindow::GetInstance().GetWindowObject();
258     if (!window) {
259         ELOG("JsApp::Run get window failed.");
260         return;
261     }
262     window->SetContentInfoCallback(std::move(VirtualScreenImpl::LoadContentCallBack));
263     window->CreateSurfaceNode(options.moduleName, std::move(VirtualScreenImpl::CallBack));
264 }
265 
ConvertAbilityInfo(const Ide::AbilityInfo & info,AppExecFwk::AbilityInfo & abilityInfo)266 static void ConvertAbilityInfo(const Ide::AbilityInfo &info, AppExecFwk::AbilityInfo &abilityInfo)
267 {
268     abilityInfo.name = info.name;
269     abilityInfo.iconPath = info.icon;
270     abilityInfo.labelId = info.iconId;
271     abilityInfo.label = info.label;
272     abilityInfo.labelId = info.labelId;
273     abilityInfo.srcEntrance = info.srcEntrty;
274     abilityInfo.description = info.description;
275     abilityInfo.descriptionId = info.descriptionId;
276     abilityInfo.startWindowBackground = info.startWindowBackground;
277     abilityInfo.startWindowBackgroundId = info.startWindowBackgroundId;
278     abilityInfo.startWindowIconId = info.startWindowIconId;
279     abilityInfo.startWindowIcon = info.startWindowIcon;
280 }
281 
ConvertApplicationInfo(const Ide::AppInfo & info,AppExecFwk::ApplicationInfo & applicationInfo)282 static void ConvertApplicationInfo(const Ide::AppInfo &info, AppExecFwk::ApplicationInfo &applicationInfo)
283 {
284     applicationInfo.apiReleaseType = info.apiReleaseType;
285     applicationInfo.bundleName = info.bundleName;
286     applicationInfo.compileSdkType = info.compileSdkType;
287     applicationInfo.compileSdkVersion = info.compileSdkVersion;
288     applicationInfo.debug = info.debug;
289     applicationInfo.icon = info.icon;
290     applicationInfo.iconId = info.iconId;
291     applicationInfo.label = info.label;
292     applicationInfo.labelId = info.labelId;
293     applicationInfo.minCompatibleVersionCode = info.minAPIVersion;
294     applicationInfo.apiTargetVersion = info.targetAPIVersion;
295     applicationInfo.vendor = info.vendor;
296     applicationInfo.vendor = info.vendor;
297     applicationInfo.versionName = info.versionName;
298     applicationInfo.distributedNotificationEnabled = info.distributedNotificationEnabled;
299 }
300 
ConvertHapModuleInfo(const Ide::HapModuleInfo & info,AppExecFwk::HapModuleInfo & hapModuleInfo)301 static void ConvertHapModuleInfo(const Ide::HapModuleInfo &info, AppExecFwk::HapModuleInfo &hapModuleInfo)
302 {
303     hapModuleInfo.labelId = info.labelId;
304     hapModuleInfo.virtualMachine = info.virtualMachine;
305     hapModuleInfo.pages = info.pages;
306     hapModuleInfo.name = info.name;
307     hapModuleInfo.mainElementName = info.mainElement;
308     hapModuleInfo.installationFree = info.installationFree;
309     hapModuleInfo.descriptionId = info.descriptionId;
310     hapModuleInfo.description = info.description;
311     hapModuleInfo.deliveryWithInstall = info.deliveryWithInstall;
312     hapModuleInfo.compileMode = AppExecFwk::CompileMode::ES_MODULE;
313     hapModuleInfo.deviceTypes = info.deviceTypes;
314     hapModuleInfo.srcEntrance = info.srcEntry;
315     for (auto &ability : info.abilities) {
316         AppExecFwk::AbilityInfo aInfo;
317         ConvertAbilityInfo(ability, aInfo);
318         hapModuleInfo.abilityInfos.emplace_back(aInfo);
319     }
320 }
321 
SetSimulatorParams(OHOS::AbilityRuntime::Options & options)322 void JsAppImpl::SetSimulatorParams(OHOS::AbilityRuntime::Options& options)
323 {
324     const string path = CommandParser::GetInstance().GetAppResourcePath() +
325                         FileSystem::GetSeparator() + "module.json";
326     GetModuleJsonInfo(path);
327     SetSimulatorCommonParams(options);
328     SetSimulatorConfigParams(options);
329     ILOG("setted bundleName:%s moduleName:%s", options.bundleName.c_str(), options.moduleName.c_str());
330 }
331 
SetSimulatorCommonParams(OHOS::AbilityRuntime::Options & options)332 void JsAppImpl::SetSimulatorCommonParams(OHOS::AbilityRuntime::Options& options)
333 {
334     options.bundleName = OHOS::Ide::StageContext::GetInstance().GetAppInfo().bundleName;
335     options.moduleName = OHOS::Ide::StageContext::GetInstance().GetHapModuleInfo().name;
336     options.modulePath = aceRunArgs.assetPath + FileSystem::GetSeparator() + "modules.abc";
337     options.resourcePath = CommandParser::GetInstance().GetAppResourcePath() +
338                                 FileSystem::GetSeparator() + "resources.index";
339     options.debugPort = debugServerPort;
340     options.assetPath = aceRunArgs.assetPath;
341     options.systemResourcePath = aceRunArgs.systemResourcesPath;
342     options.appResourcePath = aceRunArgs.appResourcesPath;
343     options.containerSdkPath = aceRunArgs.containerSdkPath;
344     options.url = aceRunArgs.url;
345     options.language = aceRunArgs.language;
346     options.region = aceRunArgs.region;
347     options.script = aceRunArgs.script;
348     options.themeId = aceRunArgs.themeId;
349     options.deviceWidth = aceRunArgs.deviceWidth;
350     options.deviceHeight = aceRunArgs.deviceHeight;
351     options.isRound = aceRunArgs.isRound;
352     options.onRouterChange = aceRunArgs.onRouterChange;
353     OHOS::AbilityRuntime::DeviceConfig deviceCfg;
354     deviceCfg.deviceType = SetDevice<OHOS::AbilityRuntime::DeviceType>(aceRunArgs.deviceConfig.deviceType);
355     deviceCfg.orientation = SetOrientation<OHOS::AbilityRuntime::DeviceOrientation>(
356         aceRunArgs.deviceConfig.orientation);
357     deviceCfg.colorMode = SetColorMode<OHOS::AbilityRuntime::ColorMode>(aceRunArgs.deviceConfig.colorMode);
358     deviceCfg.density = aceRunArgs.deviceConfig.density;
359     options.deviceConfig = deviceCfg;
360     options.compatibleVersion = OHOS::Ide::StageContext::GetInstance().GetAppInfo().minAPIVersion;
361     options.installationFree =
362         OHOS::Ide::StageContext::GetInstance().GetAppInfo().bundleType == "atomicService" ? true : false;
363     options.labelId = OHOS::Ide::StageContext::GetInstance().GetAbilityInfo(
364         CommandParser::GetInstance().GetAbilityPath()).labelId;
365     options.compileMode = OHOS::Ide::StageContext::GetInstance().GetHapModuleInfo().compileMode;
366     options.pageProfile = OHOS::Ide::StageContext::GetInstance().GetHapModuleInfo().pages;
367     options.targetVersion = OHOS::Ide::StageContext::GetInstance().GetAppInfo().targetAPIVersion;
368     options.releaseType = OHOS::Ide::StageContext::GetInstance().GetAppInfo().apiReleaseType;
369     options.enablePartialUpdate = OHOS::Ide::StageContext::GetInstance().GetHapModuleInfo().isPartialUpdate;
370     string fPath = CommandParser::GetInstance().GetConfigPath();
371     std::size_t pos = fPath.find(".idea");
372     if (pos == std::string::npos) {
373         ELOG("previewPath error:%s", fPath.c_str());
374     } else {
375         options.previewPath = fPath.substr(0, pos) + ".idea" + FileSystem::GetSeparator() + "previewer";
376         ILOG("previewPath info:%s", options.previewPath.c_str());
377     }
378 }
379 
SetSimulatorConfigParams(OHOS::AbilityRuntime::Options & options)380 void JsAppImpl::SetSimulatorConfigParams(OHOS::AbilityRuntime::Options& options)
381 {
382     AppExecFwk::ApplicationInfo applicationInfo;
383     ConvertApplicationInfo(Ide::StageContext::GetInstance().GetAppInfo(), applicationInfo);
384     options.applicationInfo = applicationInfo;
385     AppExecFwk::HapModuleInfo hapModuleInfo;
386     ConvertHapModuleInfo(OHOS::Ide::StageContext::GetInstance().GetHapModuleInfo(), hapModuleInfo);
387     options.hapModuleInfo = hapModuleInfo;
388     AppExecFwk::AbilityInfo abilityInfo;
389     ConvertAbilityInfo(OHOS::Ide::StageContext::GetInstance().GetAbilityInfo(
390         CommandParser::GetInstance().GetAbilityPath()), abilityInfo);
391     options.abilityInfo = abilityInfo;
392     options.configuration = UpdateConfiguration(aceRunArgs);
393 }
394 
UpdateConfiguration(OHOS::Ace::Platform::AceRunArgs & args)395 std::shared_ptr<AppExecFwk::Configuration> JsAppImpl::UpdateConfiguration(OHOS::Ace::Platform::AceRunArgs& args)
396 {
397     std::shared_ptr<AppExecFwk::Configuration> configuration = make_shared<AppExecFwk::Configuration>();
398     configuration->AddItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE,
399         SharedData<string>::GetData(SharedDataType::LANGUAGE));
400     string colorMode = "light";
401     if (aceRunArgs.deviceConfig.colorMode == ColorMode::DARK) {
402         colorMode = "dark";
403     }
404     configuration->AddItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE, colorMode);
405     string direction = "portrait";
406     if (aceRunArgs.deviceConfig.orientation == DeviceOrientation::LANDSCAPE) {
407         orientation = "landscape";
408     }
409     configuration->AddItem(OHOS::AppExecFwk::ConfigurationInner::APPLICATION_DIRECTION, direction);
410     string density = std::to_string(aceRunArgs.deviceConfig.density);
411     configuration->AddItem(OHOS::AppExecFwk::ConfigurationInner::APPLICATION_DENSITYDPI, density);
412     return configuration;
413 }
414 
415 
SetWindowParams() const416 void JsAppImpl::SetWindowParams() const
417 {
418     windowModel->isRound = aceRunArgs.isRound;
419     windowModel->originWidth = aceRunArgs.deviceWidth;
420     windowModel->originHeight = aceRunArgs.deviceHeight;
421     windowModel->compressWidth = aceRunArgs.deviceWidth;
422     windowModel->compressHeight = aceRunArgs.deviceHeight;
423     windowModel->density = aceRunArgs.deviceConfig.density;
424     windowModel->deviceType = SetDevice<OHOS::Previewer::DeviceType>(aceRunArgs.deviceConfig.deviceType);
425     windowModel->orientation = SetOrientation<OHOS::Previewer::Orientation>(aceRunArgs.deviceConfig.orientation);
426     windowModel->colorMode = SetColorMode<OHOS::Previewer::ColorMode>(aceRunArgs.deviceConfig.colorMode);
427 }
428 #else
RunDebugAbility()429     void JsAppImpl::RunDebugAbility()
430     {
431         ELOG("JsApp::Run ability start failed.Linux is not supported.");
432         return;
433     }
434 #endif
435 
AdaptDeviceType(Platform::AceRunArgs & args,const std::string type,const int32_t realDeviceWidth,double screenDendity) const436 void JsAppImpl::AdaptDeviceType(Platform::AceRunArgs& args, const std::string type,
437                                 const int32_t realDeviceWidth, double screenDendity) const
438 {
439     if (type == "wearable") {
440         args.deviceConfig.deviceType = DeviceType::WATCH;
441         double density = screenDendity > 0 ? screenDendity : watchScreenDensity;
442         double adaptWidthWatch = realDeviceWidth * BASE_SCREEN_DENSITY / density;
443         args.deviceConfig.density = args.deviceWidth / adaptWidthWatch;
444         return;
445     }
446     if (type == "tv") {
447         args.deviceConfig.deviceType = DeviceType::TV;
448         double density = screenDendity > 0 ? screenDendity : tvScreenDensity;
449         double adaptWidthTv = realDeviceWidth * BASE_SCREEN_DENSITY / density;
450         args.deviceConfig.density = args.deviceWidth / adaptWidthTv;
451         return;
452     }
453     if (type == "phone" || type == "default") {
454         args.deviceConfig.deviceType = DeviceType::PHONE;
455         double density = screenDendity > 0 ? screenDendity : phoneScreenDensity;
456         double adaptWidthPhone = realDeviceWidth * BASE_SCREEN_DENSITY / density;
457         args.deviceConfig.density = args.deviceWidth / adaptWidthPhone;
458         return;
459     }
460     if (type == "2in1") {
461         args.deviceConfig.deviceType = DeviceType::TABLET;
462         double density = screenDendity > 0 ? screenDendity : twoInOneScreenDensity;
463         double adaptWidthPhone = realDeviceWidth * BASE_SCREEN_DENSITY / density;
464         args.deviceConfig.density = args.deviceWidth / adaptWidthPhone;
465         return;
466     }
467     if (type == "tablet") {
468         args.deviceConfig.deviceType = DeviceType::TABLET;
469         double density = screenDendity > 0 ? screenDendity : tabletScreenDensity;
470         double adaptWidthTablet = realDeviceWidth * BASE_SCREEN_DENSITY / density;
471         args.deviceConfig.density = args.deviceWidth / adaptWidthTablet;
472         return;
473     }
474     if (type == "car") {
475         args.deviceConfig.deviceType = DeviceType::CAR;
476         double density = screenDendity > 0 ? screenDendity : carScreenDensity;
477         double adaptWidthCar = realDeviceWidth * BASE_SCREEN_DENSITY / density;
478         args.deviceConfig.density = args.deviceWidth / adaptWidthCar;
479         return;
480     }
481     ELOG("DeviceType not supported : %s", type.c_str());
482     return;
483 }
484 
SetAssetPath(Platform::AceRunArgs & args,const std::string assetPath) const485 void JsAppImpl::SetAssetPath(Platform::AceRunArgs& args, const std::string assetPath) const
486 {
487     args.assetPath = assetPath;
488 }
489 
SetProjectModel(Platform::AceRunArgs & args) const490 void JsAppImpl::SetProjectModel(Platform::AceRunArgs& args) const
491 {
492     int idxVal = CommandParser::GetInstance().GetProjectModelEnumValue();
493     ILOG("ProjectModel: %s", CommandParser::GetInstance().GetProjectModelEnumName(idxVal).c_str());
494     args.projectModel = Platform::ProjectModel(idxVal);
495 }
496 
SetPageProfile(Platform::AceRunArgs & args,const std::string pageProfile) const497 void JsAppImpl::SetPageProfile(Platform::AceRunArgs& args, const std::string pageProfile) const
498 {
499     args.pageProfile = pageProfile;
500 }
501 
SetDeviceWidth(Platform::AceRunArgs & args,const int32_t deviceWidth) const502 void JsAppImpl::SetDeviceWidth(Platform::AceRunArgs& args, const int32_t deviceWidth) const
503 {
504     args.deviceWidth = deviceWidth;
505 }
506 
SetDeviceHeight(Platform::AceRunArgs & args,const int32_t deviceHeight) const507 void JsAppImpl::SetDeviceHeight(Platform::AceRunArgs& args, const int32_t deviceHeight) const
508 {
509     args.deviceHeight = deviceHeight;
510 }
511 
SetWindowTitle(Platform::AceRunArgs & args,const std::string windowTitle) const512 void JsAppImpl::SetWindowTitle(Platform::AceRunArgs& args, const std::string windowTitle) const
513 {
514     args.windowTitle = windowTitle;
515 }
516 
SetUrl(Platform::AceRunArgs & args,const std::string urlPath) const517 void JsAppImpl::SetUrl(Platform::AceRunArgs& args, const std::string urlPath) const
518 {
519     args.url = urlPath;
520 }
521 
SetConfigChanges(Platform::AceRunArgs & args,const std::string configChanges) const522 void JsAppImpl::SetConfigChanges(Platform::AceRunArgs& args, const std::string configChanges) const
523 {
524     args.configChanges = configChanges;
525 }
526 
SetColorMode(Platform::AceRunArgs & args,const std::string colorMode) const527 void JsAppImpl::SetColorMode(Platform::AceRunArgs& args, const std::string colorMode) const
528 {
529     ILOG("JsAppImpl::RunJsApp SetColorMode: %s", colorMode.c_str());
530     if (colorMode == "dark") {
531         args.deviceConfig.colorMode = ColorMode::DARK;
532     } else {
533         args.deviceConfig.colorMode = ColorMode::LIGHT;
534     }
535 }
536 
SetOrientation(Platform::AceRunArgs & args,const std::string orientation) const537 void JsAppImpl::SetOrientation(Platform::AceRunArgs& args, const std::string orientation) const
538 {
539     ILOG("JsAppImpl::RunJsApp SetOrientation: %s", orientation.c_str());
540     if (orientation == "landscape") {
541         args.deviceConfig.orientation = DeviceOrientation::LANDSCAPE;
542     } else {
543         args.deviceConfig.orientation = DeviceOrientation::PORTRAIT;
544     }
545 }
546 
SetAceVersionArgs(Platform::AceRunArgs & args,const std::string aceVersion) const547 void JsAppImpl::SetAceVersionArgs(Platform::AceRunArgs& args, const std::string aceVersion) const
548 {
549     ILOG("JsAppImpl::RunJsApp SetAceVersionArgs: %s", aceVersion.c_str());
550     if (aceVersion == "ACE_2_0") {
551         args.aceVersion = Platform::AceVersion::ACE_2_0;
552     } else {
553         args.aceVersion = Platform::AceVersion::ACE_1_0;
554     }
555 }
556 
SetLanguage(Platform::AceRunArgs & args,const std::string language) const557 void JsAppImpl::SetLanguage(Platform::AceRunArgs& args, const std::string language) const
558 {
559     args.language = language;
560 }
561 
SetRegion(Platform::AceRunArgs & args,const std::string region) const562 void JsAppImpl::SetRegion(Platform::AceRunArgs& args, const std::string region) const
563 {
564     args.region = region;
565 }
566 
SetScript(Platform::AceRunArgs & args,const std::string script) const567 void JsAppImpl::SetScript(Platform::AceRunArgs& args, const std::string script) const
568 {
569     args.script = script;
570 }
571 
SetSystemResourcesPath(Platform::AceRunArgs & args) const572 void JsAppImpl::SetSystemResourcesPath(Platform::AceRunArgs& args) const
573 {
574     string sep = FileSystem::GetSeparator();
575     string rPath = FileSystem::GetApplicationPath();
576     int idx = rPath.find_last_of(sep);
577     rPath = rPath.substr(0, idx + 1) + "resources";
578     args.systemResourcesPath = rPath;
579 }
580 
SetAppResourcesPath(Platform::AceRunArgs & args,const std::string appResourcesPath) const581 void JsAppImpl::SetAppResourcesPath(Platform::AceRunArgs& args, const std::string appResourcesPath) const
582 {
583     args.appResourcesPath = appResourcesPath;
584 }
585 
SetFormsEnabled(Platform::AceRunArgs & args,bool formsEnabled) const586 void JsAppImpl::SetFormsEnabled(Platform::AceRunArgs& args, bool formsEnabled) const
587 {
588     args.formsEnabled = formsEnabled;
589 }
590 
SetContainerSdkPath(Platform::AceRunArgs & args,const std::string containerSdkPath) const591 void JsAppImpl::SetContainerSdkPath(Platform::AceRunArgs& args, const std::string containerSdkPath) const
592 {
593     args.containerSdkPath = containerSdkPath;
594 }
595 
SetOnRender(Platform::AceRunArgs & args) const596 void JsAppImpl::SetOnRender(Platform::AceRunArgs& args) const
597 {
598     args.onRender = std::move(VirtualScreenImpl::CallBack);
599 }
600 
SetOnRouterChange(Platform::AceRunArgs & args) const601 void JsAppImpl::SetOnRouterChange(Platform::AceRunArgs& args) const
602 {
603     args.onRouterChange = std::move(VirtualScreenImpl::PageCallBack);
604 }
605 
SetOnError(Platform::AceRunArgs & args) const606 void JsAppImpl::SetOnError(Platform::AceRunArgs& args) const
607 {
608     args.onError = std::move(VirtualScreenImpl::FastPreviewCallBack);
609 }
610 
SetComponentModeEnabled(Platform::AceRunArgs & args,bool isComponentMode) const611 void JsAppImpl::SetComponentModeEnabled(Platform::AceRunArgs& args, bool isComponentMode) const
612 {
613     args.isComponentMode = isComponentMode;
614 }
615 
AssignValueForWidthAndHeight(const int32_t origWidth,const int32_t origHeight,const int32_t compWidth,const int32_t compHeight)616 void JsAppImpl::AssignValueForWidthAndHeight(const int32_t origWidth,
617                                              const int32_t origHeight,
618                                              const int32_t compWidth,
619                                              const int32_t compHeight)
620 {
621     orignalWidth = origWidth;
622     orignalHeight = origHeight;
623     width = compWidth;
624     height = compHeight;
625     ILOG("AssignValueForWidthAndHeight: %d %d %d %d", orignalWidth, orignalHeight, width, height);
626 }
627 
ResolutionChanged(int32_t changedOriginWidth,int32_t changedOriginHeight,int32_t changedWidth,int32_t changedHeight,int32_t screenDensity)628 void JsAppImpl::ResolutionChanged(int32_t changedOriginWidth, int32_t changedOriginHeight, int32_t changedWidth,
629                                   int32_t changedHeight, int32_t screenDensity)
630 {
631     SetResolutionParams(changedOriginWidth, changedOriginHeight, changedWidth, changedHeight, screenDensity);
632     if (isDebug && debugServerPort >= 0) {
633 #if defined(__APPLE__) || defined(_WIN32)
634         SetWindowParams();
635         OHOS::Ace::ViewportConfig config;
636         config.SetSize(windowModel->originWidth, windowModel->originHeight);
637         config.SetPosition(0, 0);
638         config.SetOrientation(static_cast<int32_t>(
639             OHOS::Previewer::PreviewerWindow::TransOrientation(windowModel->orientation)));
640         config.SetDensity(windowModel->density);
641         OHOS::Rosen::Window* window = OHOS::Previewer::PreviewerWindow::GetInstance().GetWindowObject();
642         if (!window) {
643             ELOG("JsApp::Run get window failed.");
644             return;
645         }
646         OHOS::AppExecFwk::EventHandler::PostTask([this]() {
647             glfwRenderContext->SetWindowSize(width, height);
648         });
649         simulator->UpdateConfiguration(*(UpdateConfiguration(aceRunArgs).get()));
650         window->SetViewportConfig(config);
651 #endif
652     } else {
653         if (ability != nullptr) {
654             OHOS::AppExecFwk::EventHandler::PostTask([this]() {
655                 glfwRenderContext->SetWindowSize(width, height);
656             });
657             ability->SurfaceChanged(aceRunArgs.deviceConfig.orientation, aceRunArgs.deviceConfig.density,
658                                     aceRunArgs.deviceWidth, aceRunArgs.deviceHeight);
659         }
660     }
661 }
662 
SetResolutionParams(int32_t changedOriginWidth,int32_t changedOriginHeight,int32_t changedWidth,int32_t changedHeight,int32_t screenDensity)663 void JsAppImpl::SetResolutionParams(int32_t changedOriginWidth, int32_t changedOriginHeight, int32_t changedWidth,
664     int32_t changedHeight, int32_t screenDensity)
665 {
666     SetDeviceWidth(aceRunArgs, changedWidth);
667     SetDeviceHeight(aceRunArgs, changedHeight);
668     orignalWidth = changedOriginWidth;
669     orignalHeight = changedOriginHeight;
670     VirtualScreenImpl::GetInstance().SetVirtualScreenWidthAndHeight(changedOriginWidth, changedOriginHeight,
671                                                                     changedWidth, changedHeight);
672     SetDeviceScreenDensity(screenDensity,
673                            CommandParser::GetInstance().GetDeviceType());
674     AdaptDeviceType(aceRunArgs, CommandParser::GetInstance().GetDeviceType(),
675                     VirtualScreenImpl::GetInstance().GetOrignalWidth());
676     AssignValueForWidthAndHeight(VirtualScreenImpl::GetInstance().GetOrignalWidth(),
677                                  VirtualScreenImpl::GetInstance().GetOrignalHeight(),
678                                  VirtualScreenImpl::GetInstance().GetCompressionWidth(),
679                                  VirtualScreenImpl::GetInstance().GetCompressionHeight());
680     if (changedWidth <= changedHeight) {
681         JsAppImpl::GetInstance().SetDeviceOrentation("portrait");
682     } else {
683         JsAppImpl::GetInstance().SetDeviceOrentation("landscape");
684     }
685     SetOrientation(aceRunArgs, orientation);
686     ILOG("ResolutionChanged: %s %d %d %f", orientation.c_str(), aceRunArgs.deviceWidth,
687          aceRunArgs.deviceHeight, aceRunArgs.deviceConfig.density);
688 }
689 
SetArgsColorMode(const string & value)690 void JsAppImpl::SetArgsColorMode(const string& value)
691 {
692     colorMode = value;
693 }
694 
SetArgsAceVersion(const string & value)695 void JsAppImpl::SetArgsAceVersion(const string& value)
696 {
697     aceVersion = value;
698 }
699 
SetDeviceOrentation(const string & value)700 void JsAppImpl::SetDeviceOrentation(const string& value)
701 {
702     orientation = value;
703 }
704 
GetOrientation() const705 std::string JsAppImpl::GetOrientation() const
706 {
707     return orientation;
708 }
709 
GetColorMode() const710 std::string JsAppImpl::GetColorMode() const
711 {
712     return colorMode;
713 }
714 
SetDeviceScreenDensity(const int32_t screenDensity,const std::string type)715 void JsAppImpl::SetDeviceScreenDensity(const int32_t screenDensity, const std::string type)
716 {
717     if (type == "wearable" && screenDensity != 0) {
718         watchScreenDensity = screenDensity;
719         return;
720     }
721     if (type == "tv" && screenDensity != 0) {
722         tvScreenDensity = screenDensity;
723         return;
724     }
725     if ((type == "phone" || type == "default") && screenDensity != 0) {
726         phoneScreenDensity = screenDensity;
727         return;
728     }
729     if (type == "2in1" && screenDensity != 0) {
730         twoInOneScreenDensity = screenDensity;
731         return;
732     }
733     if (type == "tablet" && screenDensity != 0) {
734         tabletScreenDensity = screenDensity;
735         return;
736     }
737     if (type == "car" && screenDensity != 0) {
738         carScreenDensity = screenDensity;
739         return;
740     }
741     ILOG("DeviceType not supported to SetDeviceScreenDensity: %s", type.c_str());
742     return;
743 }
744 
ReloadRuntimePage(const std::string currentPage)745 void JsAppImpl::ReloadRuntimePage(const std::string currentPage)
746 {
747     std::string params = "";
748     if (ability != nullptr) {
749         ability->ReplacePage(currentPage, params);
750     }
751 }
752 
SetScreenDensity(const std::string value)753 void JsAppImpl::SetScreenDensity(const std::string value)
754 {
755     screenDensity = value;
756 }
757 
SetConfigChanges(const std::string value)758 void JsAppImpl::SetConfigChanges(const std::string value)
759 {
760     configChanges = value;
761 }
762 
MemoryRefresh(const std::string memoryRefreshArgs) const763 bool JsAppImpl::MemoryRefresh(const std::string memoryRefreshArgs) const
764 {
765     ILOG("MemoryRefresh.");
766     if (ability != nullptr) {
767         return ability->OperateComponent(memoryRefreshArgs);
768     }
769     return false;
770 }
771 
ParseSystemParams(OHOS::Ace::Platform::AceRunArgs & args,Json::Value paramObj)772 void JsAppImpl::ParseSystemParams(OHOS::Ace::Platform::AceRunArgs& args, Json::Value paramObj)
773 {
774     if (paramObj == Json::nullValue) {
775         SetDeviceWidth(args, VirtualScreenImpl::GetInstance().GetCompressionWidth());
776         SetDeviceHeight(args, VirtualScreenImpl::GetInstance().GetCompressionHeight());
777         AssignValueForWidthAndHeight(args.deviceWidth, args.deviceHeight,
778                                      args.deviceWidth, args.deviceHeight);
779         SetColorMode(args, colorMode);
780         SetOrientation(args, orientation);
781         SetDeviceScreenDensity(atoi(screenDensity.c_str()),
782                                CommandParser::GetInstance().GetDeviceType());
783         AdaptDeviceType(args, CommandParser::GetInstance().GetDeviceType(),
784                         VirtualScreenImpl::GetInstance().GetOrignalWidth());
785         SetLanguage(args, SharedData<string>::GetData(SharedDataType::LAN));
786         SetRegion(args, SharedData<string>::GetData(SharedDataType::REGION));
787     } else {
788         SetDeviceWidth(args, paramObj["width"].asInt());
789         SetDeviceHeight(args, paramObj["height"].asInt());
790         AssignValueForWidthAndHeight(args.deviceWidth, args.deviceHeight,
791                                      args.deviceWidth, args.deviceHeight);
792         SetColorMode(args, paramObj["colorMode"].asString());
793         SetOrientation(args, paramObj["orientation"].asString());
794         string deviceType = paramObj["deviceType"].asString();
795         SetDeviceScreenDensity(atoi(screenDensity.c_str()), deviceType);
796         AdaptDeviceType(args, deviceType, args.deviceWidth, paramObj["dpi"].asDouble());
797         string lanInfo = paramObj["locale"].asString();
798         SetLanguage(args, lanInfo.substr(0, lanInfo.find("_")));
799         SetRegion(args, lanInfo.substr(lanInfo.find("_") + 1, lanInfo.length() - 1));
800     }
801 }
802 
SetSystemParams(OHOS::Ace::Platform::SystemParams & params,Json::Value paramObj)803 void JsAppImpl::SetSystemParams(OHOS::Ace::Platform::SystemParams& params, Json::Value paramObj)
804 {
805     ParseSystemParams(aceRunArgs, paramObj);
806     params.deviceWidth = aceRunArgs.deviceWidth;
807     params.deviceHeight = aceRunArgs.deviceHeight;
808     params.language = aceRunArgs.language;
809     params.region = aceRunArgs.region;
810     params.colorMode = aceRunArgs.deviceConfig.colorMode;
811     params.orientation = aceRunArgs.deviceConfig.orientation;
812     params.deviceType = aceRunArgs.deviceConfig.deviceType;
813     params.density = aceRunArgs.deviceConfig.density;
814     params.isRound = (paramObj == Json::nullValue) ?
815                      (CommandParser::GetInstance().GetScreenShape() == "circle") :
816                      paramObj["roundScreen"].asBool();
817 }
818 
LoadDocument(const std::string filePath,const std::string componentName,Json::Value previewContext)819 void JsAppImpl::LoadDocument(const std::string filePath,
820                              const std::string componentName,
821                              Json::Value previewContext)
822 {
823     ILOG("LoadDocument.");
824     if (ability != nullptr) {
825         OHOS::Ace::Platform::SystemParams params;
826         SetSystemParams(params, previewContext);
827         ILOG("LoadDocument params is density: %f region: %s language: %s deviceWidth: %d\
828              deviceHeight: %d isRound:%d colorMode:%s orientation: %s deviceType: %s",
829              params.density,
830              params.region.c_str(),
831              params.language.c_str(),
832              params.deviceWidth,
833              params.deviceHeight,
834              (params.isRound ? "true" : "false"),
835              ((params.colorMode == ColorMode::DARK) ? "dark" : "light"),
836              ((params.orientation == DeviceOrientation::LANDSCAPE) ? "landscape" : "portrait"),
837              GetDeviceTypeName(params.deviceType).c_str());
838         OHOS::AppExecFwk::EventHandler::PostTask([this]() {
839             glfwRenderContext->SetWindowSize(width, height);
840         });
841         ability->LoadDocument(filePath, componentName, params);
842     }
843 }
844 
DispatchBackPressedEvent() const845 void JsAppImpl::DispatchBackPressedEvent() const
846 {
847     ability->OnBackPressed();
848 }
DispatchKeyEvent(const std::shared_ptr<OHOS::MMI::KeyEvent> & keyEvent) const849 void JsAppImpl::DispatchKeyEvent(const std::shared_ptr<OHOS::MMI::KeyEvent>& keyEvent) const
850 {
851     if (isDebug && debugServerPort >= 0) {
852 #if defined(__APPLE__) || defined(_WIN32)
853         OHOS::Rosen::Window* window = OHOS::Previewer::PreviewerWindow::GetInstance().GetWindowObject();
854         if (!window) {
855             ELOG("JsApp::Run get window failed.");
856             return;
857         }
858         window->ConsumeKeyEvent(keyEvent);
859 #endif
860     } else {
861         ability->OnInputEvent(keyEvent);
862     }
863 }
DispatchPointerEvent(const std::shared_ptr<OHOS::MMI::PointerEvent> & pointerEvent) const864 void JsAppImpl::DispatchPointerEvent(const std::shared_ptr<OHOS::MMI::PointerEvent>& pointerEvent) const
865 {
866     if (isDebug && debugServerPort >= 0) {
867 #if defined(__APPLE__) || defined(_WIN32)
868         OHOS::Rosen::Window* window = OHOS::Previewer::PreviewerWindow::GetInstance().GetWindowObject();
869         if (!window) {
870             ELOG("JsApp::Run get window failed.");
871             return;
872         }
873         window->ConsumePointerEvent(pointerEvent);
874 #endif
875     } else {
876         ability->OnInputEvent(pointerEvent);
877     }
878 }
DispatchAxisEvent(const std::shared_ptr<OHOS::MMI::AxisEvent> & axisEvent) const879 void JsAppImpl::DispatchAxisEvent(const std::shared_ptr<OHOS::MMI::AxisEvent>& axisEvent) const
880 {
881     ability->OnInputEvent(axisEvent);
882 }
DispatchInputMethodEvent(const unsigned int code_point) const883 void JsAppImpl::DispatchInputMethodEvent(const unsigned int code_point) const
884 {
885     ability->OnInputMethodEvent(code_point);
886 }
887 
GetDeviceTypeName(const OHOS::Ace::DeviceType type) const888 string JsAppImpl::GetDeviceTypeName(const OHOS::Ace::DeviceType type) const
889 {
890     switch (type) {
891         case DeviceType::WATCH:
892             return "watch";
893         case DeviceType::TV:
894             return "tv";
895         case DeviceType::PHONE:
896             return "phone";
897         case DeviceType::TABLET:
898             return "tablet";
899         case DeviceType::CAR:
900             return "car";
901         default:
902             return "";
903     }
904 }
905 
InitGlfwEnv()906 void JsAppImpl::InitGlfwEnv()
907 {
908     glfwRenderContext = OHOS::Rosen::GlfwRenderContext::GetGlobal();
909     if (!glfwRenderContext->Init()) {
910         ELOG("Could not create window: InitGlfwEnv failed.");
911         return;
912     }
913     glfwRenderContext->CreateGlfwWindow(aceRunArgs.deviceWidth, aceRunArgs.deviceHeight, false);
914 }