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