• 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 "external/StageContext.h"
27 #include "viewport_config.h"
28 #include "glfw_render_context.h"
29 #include "window_model.h"
30 #include "window_display.h"
31 #include "ace_preview_helper.h"
32 #include "ClipboardHelper.h"
33 #if defined(__APPLE__) || defined(_WIN32)
34 #include "options.h"
35 #include "simulator.h"
36 #endif
37 #include <fstream>
38 
39 using namespace std;
40 using namespace OHOS;
41 using namespace OHOS::Ace;
42 
JsAppImpl()43 JsAppImpl::JsAppImpl() noexcept : ability(nullptr), isStop(false)
44 {
45 #if defined(__APPLE__) || defined(_WIN32)
46     windowModel = std::make_shared<OHOS::Previewer::PreviewerWindowModel>();
47 #endif
48 }
49 
~JsAppImpl()50 JsAppImpl::~JsAppImpl()
51 {
52     if (glfwRenderContext != nullptr) {
53         glfwRenderContext->DestroyWindow();
54         glfwRenderContext->Terminate();
55     }
56 }
57 
GetInstance()58 JsAppImpl& JsAppImpl::GetInstance()
59 {
60     static JsAppImpl instance;
61     return instance;
62 }
63 
Start()64 void JsAppImpl::Start()
65 {
66     VirtualScreenImpl::GetInstance().InitVirtualScreen();
67     VirtualScreenImpl::GetInstance().InitAll(pipeName, pipePort);
68     isFinished = false;
69     ILOG("Start run js app");
70     OHOS::AppExecFwk::EventHandler::SetMainThreadId(std::this_thread::get_id());
71     RunJsApp();
72     ILOG("Js app run finished");
73     while (!isStop) {
74         // Execute all tasks in the main thread
75         OHOS::AppExecFwk::EventHandler::Run();
76         glfwRenderContext->PollEvents();
77         std::this_thread::sleep_for(std::chrono::milliseconds(1));
78     }
79     isFinished = true;
80 }
81 
Restart()82 void JsAppImpl::Restart()
83 {
84     if (isDebug && debugServerPort >= 0) {
85 #if defined(__APPLE__) || defined(_WIN32)
86         if (simulator) {
87             simulator->TerminateAbility(debugAbilityId);
88         }
89 #endif
90     } else {
91         ability = nullptr;
92     }
93     OHOS::Ide::StageContext::GetInstance().ReleaseHspBuffers();
94 }
95 
GetJSONTree()96 std::string JsAppImpl::GetJSONTree()
97 {
98     std::string jsongTree = ability->GetJSONTree();
99     Json::Value jsonData = JsonReader::ParseJsonData(jsongTree);
100     Json::StreamWriterBuilder builder;
101     builder["indentation"] = "";
102     builder["emitUTF8"] = true;
103     return Json::writeString(builder, jsonData);
104 }
105 
GetDefaultJSONTree()106 std::string JsAppImpl::GetDefaultJSONTree()
107 {
108     ILOG("Start getDefaultJsontree.");
109     std::string jsongTree = ability->GetDefaultJSONTree();
110     Json::Value jsonData = JsonReader::ParseJsonData(jsongTree);
111     ILOG("GetDefaultJsontree finished.");
112     Json::StreamWriterBuilder builder;
113     builder["indentation"] = "";
114     builder["emitUTF8"] = true;
115     return Json::writeString(builder, jsonData);
116 }
117 
OrientationChanged(std::string commandOrientation)118 void JsAppImpl::OrientationChanged(std::string commandOrientation)
119 {
120     aceRunArgs.deviceWidth = height;
121     aceRunArgs.deviceHeight = width;
122     VirtualScreenImpl::GetInstance().WidthAndHeightReverse();
123     AdaptDeviceType(aceRunArgs, CommandParser::GetInstance().GetDeviceType(), aceRunArgs.deviceWidth);
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     OHOS::Ide::StageContext::GetInstance().ReleaseHspBuffers();
168 }
169 
SetJsAppArgs(OHOS::Ace::Platform::AceRunArgs & args)170 void JsAppImpl::SetJsAppArgs(OHOS::Ace::Platform::AceRunArgs& args)
171 {
172     ILOG("foldStatus:%s foldWidth:%d foldHeight:%d",
173         VirtualScreenImpl::GetInstance().GetFoldStatus().c_str(), VirtualScreenImpl::GetInstance().GetFoldWidth(),
174         VirtualScreenImpl::GetInstance().GetFoldHeight());
175     SetAssetPath(args, jsAppPath);
176     SetProjectModel(args);
177     SetPageProfile(args, CommandParser::GetInstance().GetPages());
178     SetDeviceWidth(args, ConvertFoldStatus(VirtualScreenImpl::GetInstance().GetFoldStatus()) ==
179         OHOS::Rosen::FoldStatus::FOLDED ? VirtualScreenImpl::GetInstance().GetFoldWidth() :
180         VirtualScreenImpl::GetInstance().GetOrignalWidth());
181     SetDeviceHeight(args, ConvertFoldStatus(VirtualScreenImpl::GetInstance().GetFoldStatus()) ==
182         OHOS::Rosen::FoldStatus::FOLDED ? VirtualScreenImpl::GetInstance().GetFoldHeight() :
183         VirtualScreenImpl::GetInstance().GetOrignalHeight());
184     SetWindowTitle(args, "Ace");
185     SetUrl(args, urlPath);
186     SetConfigChanges(args, configChanges);
187     SetColorMode(args, colorMode);
188     SetOrientation(args, orientation);
189     SetAceVersionArgs(args, aceVersion);
190     SetDeviceScreenDensity(atoi(screenDensity.c_str()),
191                            CommandParser::GetInstance().GetDeviceType());
192     SetLanguage(args, SharedData<string>::GetData(SharedDataType::LAN));
193     SetRegion(args, SharedData<string>::GetData(SharedDataType::REGION));
194     SetScript(args, "");
195     SetSystemResourcesPath(args);
196     SetAppResourcesPath(args, CommandParser::GetInstance().GetAppResourcePath());
197     SetFormsEnabled(args, CommandParser::GetInstance().IsCardDisplay());
198     SetContainerSdkPath(args, CommandParser::GetInstance().GetContainerSdkPath());
199     AdaptDeviceType(args, CommandParser::GetInstance().GetDeviceType(),
200         ConvertFoldStatus(VirtualScreenImpl::GetInstance().GetFoldStatus()) ==
201         OHOS::Rosen::FoldStatus::FOLDED ? VirtualScreenImpl::GetInstance().GetFoldWidth() :
202         VirtualScreenImpl::GetInstance().GetOrignalWidth());
203     SetOnRender(args);
204     SetOnRouterChange(args);
205     SetOnError(args);
206     SetComponentModeEnabled(args, CommandParser::GetInstance().IsComponentMode());
207     ILOG("start ability: %d %d %f", args.deviceWidth, args.deviceHeight, args.deviceConfig.density);
208 }
209 
RunJsApp()210 void JsAppImpl::RunJsApp()
211 {
212     ILOG("RunJsApp 1");
213     AssignValueForWidthAndHeight(VirtualScreenImpl::GetInstance().GetOrignalWidth(),
214                                  VirtualScreenImpl::GetInstance().GetOrignalHeight(),
215                                  VirtualScreenImpl::GetInstance().GetCompressionWidth(),
216                                  VirtualScreenImpl::GetInstance().GetCompressionHeight());
217     SetJsAppArgs(aceRunArgs);
218     OHOS::Ide::StageContext::GetInstance().SetLoaderJsonPath(CommandParser::GetInstance().GetLoaderJsonPath());
219     OHOS::Ide::StageContext::GetInstance().GetModulePathMapFromLoaderJson();
220     OHOS::Previewer::PreviewerDisplay::GetInstance().SetFoldable(VirtualScreenImpl::GetInstance().GetFoldable());
221     OHOS::Previewer::PreviewerDisplay::GetInstance().SetFoldStatus(ConvertFoldStatus(
222         VirtualScreenImpl::GetInstance().GetFoldStatus()));
223     InitGlfwEnv();
224     Platform::AcePreviewHelper::GetInstance()->SetCallbackOfPostTask(AppExecFwk::EventHandler::PostTask);
225     Platform::AcePreviewHelper::GetInstance()->
226         SetCallbackOfIsCurrentRunnerThread(AppExecFwk::EventHandler::IsCurrentRunnerThread);
227     Platform::AcePreviewHelper::GetInstance()->SetCallbackOfSetClipboardData(ClipboardHelper::SetClipboardData);
228     Platform::AcePreviewHelper::GetInstance()->SetCallbackOfGetClipboardData(ClipboardHelper::GetClipboardData);
229     if (isDebug && debugServerPort >= 0) {
230         RunDebugAbility(); // for debug preview
231     } else {
232         RunNormalAbility(); // for normal preview
233     }
234 }
235 
RunNormalAbility()236 void JsAppImpl::RunNormalAbility()
237 {
238     Platform::AcePreviewHelper::GetInstance()->SetCallbackOfHspBufferTracker(
239         [](const std::string& inputPath, uint8_t** buff, size_t* buffSize) -> bool {
240             if (!buff || !buffSize || inputPath.empty()) {
241                 return false;
242             }
243             auto data = OHOS::Ide::StageContext::GetInstance().GetModuleBuffer(inputPath);
244             if (!data) {
245                 return false;
246             }
247             *buff = data->data();
248             *buffSize = data->size();
249             return true;
250         });
251     if (ability != nullptr) {
252         ability.reset();
253     }
254     TraceTool::GetInstance().HandleTrace("Launch Js App");
255     ability = Platform::AceAbility::CreateInstance(aceRunArgs);
256     if (ability == nullptr) {
257         ELOG("JsApp::Run ability create failed.");
258         return;
259     }
260     SetMockJsonInfo();
261     OHOS::Rosen::WMError errCode;
262     OHOS::sptr<OHOS::Rosen::WindowOption> sp = nullptr;
263     auto window = OHOS::Rosen::Window::Create("previewer", sp, nullptr, errCode);
264     window->SetContentInfoCallback(std::move(VirtualScreenImpl::LoadContentCallBack));
265     window->CreateSurfaceNode("preview_surface", aceRunArgs.onRender);
266     ability->SetWindow(window);
267     ability->InitEnv();
268 }
269 
270 #if defined(__APPLE__) || defined(_WIN32)
RunDebugAbility()271 void JsAppImpl::RunDebugAbility()
272 {
273     // init window params
274     SetWindowParams();
275     OHOS::Previewer::PreviewerWindow::GetInstance().SetWindowParams(*windowModel);
276     // start ability
277     OHOS::AbilityRuntime::Options options;
278     SetSimulatorParams(options);
279     simulator = OHOS::AbilityRuntime::Simulator::Create(options);
280     if (!simulator) {
281         ELOG("JsApp::Run simulator create failed.");
282         return;
283     }
284     simulator->SetHostResolveBufferTracker(
285         [](const std::string &inputPath, uint8_t **buff, size_t *buffSize) -> bool {
286             if (inputPath.empty() || buff == nullptr || buffSize == nullptr) {
287                 ELOG("Param invalid.");
288                 return false;
289             }
290 
291             DLOG("Get module buffer, input path: %{public}s.", inputPath.c_str());
292             auto data = Ide::StageContext::GetInstance().GetModuleBuffer(inputPath);
293             if (data == nullptr) {
294                 ELOG("Get module buffer failed, input path: %{public}s.", inputPath.c_str());
295                 return false;
296             }
297 
298             *buff = data->data();
299             *buffSize = data->size();
300             return true;
301         });
302     SetMockJsonInfo();
303     std::string abilitySrcPath = CommandParser::GetInstance().GetAbilityPath();
304     std::string abilityName = CommandParser::GetInstance().GetAbilityName();
305     debugAbilityId = simulator->StartAbility(abilitySrcPath, [](int64_t abilityId) {}, abilityName);
306     if (debugAbilityId < 0) {
307         ELOG("JsApp::Run ability start failed. abilitySrcPath:%s abilityName:%s", abilitySrcPath.c_str(),
308             abilityName.c_str());
309         return;
310     }
311     // set onRender callback
312     OHOS::Rosen::Window* window = OHOS::Previewer::PreviewerWindow::GetInstance().GetWindowObject();
313     if (!window) {
314         ELOG("JsApp::Run get window failed.");
315         return;
316     }
317     window->SetContentInfoCallback(std::move(VirtualScreenImpl::LoadContentCallBack));
318     window->CreateSurfaceNode(options.moduleName, std::move(VirtualScreenImpl::CallBack));
319 }
320 
SetSimulatorParams(OHOS::AbilityRuntime::Options & options)321 void JsAppImpl::SetSimulatorParams(OHOS::AbilityRuntime::Options& options)
322 {
323     const string path = CommandParser::GetInstance().GetAppResourcePath() +
324                         FileSystem::GetSeparator() + "module.json";
325     if (!FileSystem::IsFileExists(path)) {
326         ELOG("The module.json file is not exist.");
327         return;
328     }
329     std::optional<std::vector<uint8_t>> ctx = OHOS::Ide::StageContext::GetInstance().ReadFileContents(path);
330     if (ctx.has_value()) {
331         options.moduleJsonBuffer = ctx.value();
332     } else {
333         ELOG("get module.json content failed");
334     }
335     SetSimulatorCommonParams(options);
336     ILOG("setted bundleName:%s moduleName:%s", options.modulePath.c_str(), options.resourcePath.c_str());
337 }
338 
SetSimulatorCommonParams(OHOS::AbilityRuntime::Options & options)339 void JsAppImpl::SetSimulatorCommonParams(OHOS::AbilityRuntime::Options& options)
340 {
341     options.modulePath = aceRunArgs.assetPath + FileSystem::GetSeparator() + "modules.abc";
342     options.resourcePath = CommandParser::GetInstance().GetAppResourcePath() +
343                                 FileSystem::GetSeparator() + "resources.index";
344     options.debugPort = debugServerPort;
345     options.assetPath = aceRunArgs.assetPath;
346     options.systemResourcePath = aceRunArgs.systemResourcesPath;
347     options.appResourcePath = aceRunArgs.appResourcesPath;
348     options.containerSdkPath = aceRunArgs.containerSdkPath;
349     options.url = aceRunArgs.url;
350     options.language = aceRunArgs.language;
351     options.region = aceRunArgs.region;
352     options.script = aceRunArgs.script;
353     options.themeId = aceRunArgs.themeId;
354     options.deviceWidth = aceRunArgs.deviceWidth;
355     options.deviceHeight = aceRunArgs.deviceHeight;
356     options.isRound = aceRunArgs.isRound;
357     options.onRouterChange = aceRunArgs.onRouterChange;
358     OHOS::AbilityRuntime::DeviceConfig deviceCfg;
359     deviceCfg.deviceType = SetDevice<OHOS::AbilityRuntime::DeviceType>(aceRunArgs.deviceConfig.deviceType);
360     deviceCfg.orientation = SetOrientation<OHOS::AbilityRuntime::DeviceOrientation>(
361         aceRunArgs.deviceConfig.orientation);
362     deviceCfg.colorMode = SetColorMode<OHOS::AbilityRuntime::ColorMode>(aceRunArgs.deviceConfig.colorMode);
363     deviceCfg.density = aceRunArgs.deviceConfig.density;
364     options.deviceConfig = deviceCfg;
365     string fPath = CommandParser::GetInstance().GetConfigPath();
366     options.configuration = UpdateConfiguration(aceRunArgs);
367     std::size_t pos = fPath.find(".idea");
368     if (pos == std::string::npos) {
369         ELOG("previewPath error:%s", fPath.c_str());
370     } else {
371         options.previewPath = fPath.substr(0, pos) + ".idea" + FileSystem::GetSeparator() + "previewer";
372         ILOG("previewPath info:%s", options.previewPath.c_str());
373     }
374     options.postTask = AppExecFwk::EventHandler::PostTask;
375 }
376 
UpdateConfiguration(OHOS::Ace::Platform::AceRunArgs & args)377 std::shared_ptr<AppExecFwk::Configuration> JsAppImpl::UpdateConfiguration(OHOS::Ace::Platform::AceRunArgs& args)
378 {
379     std::shared_ptr<AppExecFwk::Configuration> configuration = make_shared<AppExecFwk::Configuration>();
380     configuration->AddItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE,
381         SharedData<string>::GetData(SharedDataType::LANGUAGE));
382     string colorMode = "light";
383     if (aceRunArgs.deviceConfig.colorMode == ColorMode::DARK) {
384         colorMode = "dark";
385     }
386     configuration->AddItem(OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE, colorMode);
387     string direction = "portrait";
388     if (aceRunArgs.deviceConfig.orientation == DeviceOrientation::LANDSCAPE) {
389         orientation = "landscape";
390     }
391     configuration->AddItem(OHOS::AppExecFwk::ConfigurationInner::APPLICATION_DIRECTION, direction);
392     string density = std::to_string(aceRunArgs.deviceConfig.density);
393     configuration->AddItem(OHOS::AppExecFwk::ConfigurationInner::APPLICATION_DENSITYDPI, density);
394     return configuration;
395 }
396 
397 
SetWindowParams() const398 void JsAppImpl::SetWindowParams() const
399 {
400     windowModel->isRound = aceRunArgs.isRound;
401     windowModel->originWidth = aceRunArgs.deviceWidth;
402     windowModel->originHeight = aceRunArgs.deviceHeight;
403     windowModel->compressWidth = aceRunArgs.deviceWidth;
404     windowModel->compressHeight = aceRunArgs.deviceHeight;
405     windowModel->density = aceRunArgs.deviceConfig.density;
406     windowModel->deviceType = SetDevice<OHOS::Previewer::DeviceType>(aceRunArgs.deviceConfig.deviceType);
407     windowModel->orientation = SetOrientation<OHOS::Previewer::Orientation>(aceRunArgs.deviceConfig.orientation);
408     windowModel->colorMode = SetColorMode<OHOS::Previewer::ColorMode>(aceRunArgs.deviceConfig.colorMode);
409 }
410 #else
RunDebugAbility()411     void JsAppImpl::RunDebugAbility()
412     {
413         ELOG("JsApp::Run ability start failed.Linux is not supported.");
414         return;
415     }
416 #endif
417 
AdaptDeviceType(Platform::AceRunArgs & args,const std::string type,const int32_t realDeviceWidth,double screenDendity) const418 void JsAppImpl::AdaptDeviceType(Platform::AceRunArgs& args, const std::string type,
419                                 const int32_t realDeviceWidth, double screenDendity) const
420 {
421     if (type == "wearable") {
422         args.deviceConfig.deviceType = DeviceType::WATCH;
423         double density = screenDendity > 0 ? screenDendity : watchScreenDensity;
424         double adaptWidthWatch = realDeviceWidth * BASE_SCREEN_DENSITY / density;
425         args.deviceConfig.density = args.deviceWidth / adaptWidthWatch;
426         return;
427     }
428     if (type == "tv") {
429         args.deviceConfig.deviceType = DeviceType::TV;
430         double density = screenDendity > 0 ? screenDendity : tvScreenDensity;
431         double adaptWidthTv = realDeviceWidth * BASE_SCREEN_DENSITY / density;
432         args.deviceConfig.density = args.deviceWidth / adaptWidthTv;
433         return;
434     }
435     if (type == "phone" || type == "default") {
436         args.deviceConfig.deviceType = DeviceType::PHONE;
437         double density = screenDendity > 0 ? screenDendity : phoneScreenDensity;
438         double adaptWidthPhone = realDeviceWidth * BASE_SCREEN_DENSITY / density;
439         args.deviceConfig.density = args.deviceWidth / adaptWidthPhone;
440         return;
441     }
442     if (type == "2in1") {
443         args.deviceConfig.deviceType = DeviceType::TWO_IN_ONE;
444         double density = screenDendity > 0 ? screenDendity : twoInOneScreenDensity;
445         double adaptWidthPhone = realDeviceWidth * BASE_SCREEN_DENSITY / density;
446         args.deviceConfig.density = args.deviceWidth / adaptWidthPhone;
447         return;
448     }
449     if (type == "tablet") {
450         args.deviceConfig.deviceType = DeviceType::TABLET;
451         double density = screenDendity > 0 ? screenDendity : tabletScreenDensity;
452         double adaptWidthTablet = realDeviceWidth * BASE_SCREEN_DENSITY / density;
453         args.deviceConfig.density = args.deviceWidth / adaptWidthTablet;
454         return;
455     }
456     if (type == "car") {
457         args.deviceConfig.deviceType = DeviceType::CAR;
458         double density = screenDendity > 0 ? screenDendity : carScreenDensity;
459         double adaptWidthCar = realDeviceWidth * BASE_SCREEN_DENSITY / density;
460         args.deviceConfig.density = args.deviceWidth / adaptWidthCar;
461         return;
462     }
463     ELOG("DeviceType not supported : %s", type.c_str());
464     return;
465 }
466 
SetAssetPath(Platform::AceRunArgs & args,const std::string assetPath) const467 void JsAppImpl::SetAssetPath(Platform::AceRunArgs& args, const std::string assetPath) const
468 {
469     args.assetPath = assetPath;
470 }
471 
SetProjectModel(Platform::AceRunArgs & args) const472 void JsAppImpl::SetProjectModel(Platform::AceRunArgs& args) const
473 {
474     int idxVal = CommandParser::GetInstance().GetProjectModelEnumValue();
475     ILOG("ProjectModel: %s", CommandParser::GetInstance().GetProjectModelEnumName(idxVal).c_str());
476     args.projectModel = Platform::ProjectModel(idxVal);
477 }
478 
SetPageProfile(Platform::AceRunArgs & args,const std::string pageProfile) const479 void JsAppImpl::SetPageProfile(Platform::AceRunArgs& args, const std::string pageProfile) const
480 {
481     args.pageProfile = pageProfile;
482 }
483 
SetDeviceWidth(Platform::AceRunArgs & args,const int32_t deviceWidth) const484 void JsAppImpl::SetDeviceWidth(Platform::AceRunArgs& args, const int32_t deviceWidth) const
485 {
486     args.deviceWidth = deviceWidth;
487 }
488 
SetDeviceHeight(Platform::AceRunArgs & args,const int32_t deviceHeight) const489 void JsAppImpl::SetDeviceHeight(Platform::AceRunArgs& args, const int32_t deviceHeight) const
490 {
491     args.deviceHeight = deviceHeight;
492 }
493 
SetWindowTitle(Platform::AceRunArgs & args,const std::string windowTitle) const494 void JsAppImpl::SetWindowTitle(Platform::AceRunArgs& args, const std::string windowTitle) const
495 {
496     args.windowTitle = windowTitle;
497 }
498 
SetUrl(Platform::AceRunArgs & args,const std::string urlPath) const499 void JsAppImpl::SetUrl(Platform::AceRunArgs& args, const std::string urlPath) const
500 {
501     args.url = urlPath;
502 }
503 
SetConfigChanges(Platform::AceRunArgs & args,const std::string configChanges) const504 void JsAppImpl::SetConfigChanges(Platform::AceRunArgs& args, const std::string configChanges) const
505 {
506     args.configChanges = configChanges;
507 }
508 
SetColorMode(Platform::AceRunArgs & args,const std::string colorMode) const509 void JsAppImpl::SetColorMode(Platform::AceRunArgs& args, const std::string colorMode) const
510 {
511     ILOG("JsAppImpl::RunJsApp SetColorMode: %s", colorMode.c_str());
512     if (colorMode == "dark") {
513         args.deviceConfig.colorMode = ColorMode::DARK;
514     } else {
515         args.deviceConfig.colorMode = ColorMode::LIGHT;
516     }
517 }
518 
SetOrientation(Platform::AceRunArgs & args,const std::string orientation) const519 void JsAppImpl::SetOrientation(Platform::AceRunArgs& args, const std::string orientation) const
520 {
521     ILOG("JsAppImpl::RunJsApp SetOrientation: %s", orientation.c_str());
522     if (orientation == "landscape") {
523         args.deviceConfig.orientation = DeviceOrientation::LANDSCAPE;
524     } else {
525         args.deviceConfig.orientation = DeviceOrientation::PORTRAIT;
526     }
527 }
528 
SetAceVersionArgs(Platform::AceRunArgs & args,const std::string aceVersion) const529 void JsAppImpl::SetAceVersionArgs(Platform::AceRunArgs& args, const std::string aceVersion) const
530 {
531     ILOG("JsAppImpl::RunJsApp SetAceVersionArgs: %s", aceVersion.c_str());
532     if (aceVersion == "ACE_2_0") {
533         args.aceVersion = Platform::AceVersion::ACE_2_0;
534     } else {
535         args.aceVersion = Platform::AceVersion::ACE_1_0;
536     }
537 }
538 
SetLanguage(Platform::AceRunArgs & args,const std::string language) const539 void JsAppImpl::SetLanguage(Platform::AceRunArgs& args, const std::string language) const
540 {
541     args.language = language;
542 }
543 
SetRegion(Platform::AceRunArgs & args,const std::string region) const544 void JsAppImpl::SetRegion(Platform::AceRunArgs& args, const std::string region) const
545 {
546     args.region = region;
547 }
548 
SetScript(Platform::AceRunArgs & args,const std::string script) const549 void JsAppImpl::SetScript(Platform::AceRunArgs& args, const std::string script) const
550 {
551     args.script = script;
552 }
553 
SetSystemResourcesPath(Platform::AceRunArgs & args) const554 void JsAppImpl::SetSystemResourcesPath(Platform::AceRunArgs& args) const
555 {
556     string sep = FileSystem::GetSeparator();
557     string rPath = FileSystem::GetApplicationPath();
558     int idx = rPath.find_last_of(sep);
559     rPath = rPath.substr(0, idx + 1) + "resources";
560     args.systemResourcesPath = rPath;
561 }
562 
SetAppResourcesPath(Platform::AceRunArgs & args,const std::string appResourcesPath) const563 void JsAppImpl::SetAppResourcesPath(Platform::AceRunArgs& args, const std::string appResourcesPath) const
564 {
565     args.appResourcesPath = appResourcesPath;
566 }
567 
SetFormsEnabled(Platform::AceRunArgs & args,bool formsEnabled) const568 void JsAppImpl::SetFormsEnabled(Platform::AceRunArgs& args, bool formsEnabled) const
569 {
570     args.formsEnabled = formsEnabled;
571 }
572 
SetContainerSdkPath(Platform::AceRunArgs & args,const std::string containerSdkPath) const573 void JsAppImpl::SetContainerSdkPath(Platform::AceRunArgs& args, const std::string containerSdkPath) const
574 {
575     args.containerSdkPath = containerSdkPath;
576 }
577 
SetOnRender(Platform::AceRunArgs & args) const578 void JsAppImpl::SetOnRender(Platform::AceRunArgs& args) const
579 {
580     args.onRender = std::move(VirtualScreenImpl::CallBack);
581 }
582 
SetOnRouterChange(Platform::AceRunArgs & args) const583 void JsAppImpl::SetOnRouterChange(Platform::AceRunArgs& args) const
584 {
585     args.onRouterChange = std::move(VirtualScreenImpl::PageCallBack);
586 }
587 
SetOnError(Platform::AceRunArgs & args) const588 void JsAppImpl::SetOnError(Platform::AceRunArgs& args) const
589 {
590     args.onError = std::move(VirtualScreenImpl::FastPreviewCallBack);
591 }
592 
SetComponentModeEnabled(Platform::AceRunArgs & args,bool isComponentMode) const593 void JsAppImpl::SetComponentModeEnabled(Platform::AceRunArgs& args, bool isComponentMode) const
594 {
595     args.isComponentMode = isComponentMode;
596 }
597 
AssignValueForWidthAndHeight(const int32_t origWidth,const int32_t origHeight,const int32_t compWidth,const int32_t compHeight)598 void JsAppImpl::AssignValueForWidthAndHeight(const int32_t origWidth,
599                                              const int32_t origHeight,
600                                              const int32_t compWidth,
601                                              const int32_t compHeight)
602 {
603     orignalWidth = origWidth;
604     orignalHeight = origHeight;
605     width = compWidth;
606     height = compHeight;
607     ILOG("AssignValueForWidthAndHeight: %d %d %d %d", orignalWidth, orignalHeight, width, height);
608 }
609 
ResolutionChanged(ResolutionParam & param,int32_t screenDensity,string reason)610 void JsAppImpl::ResolutionChanged(ResolutionParam& param, int32_t screenDensity, string reason)
611 {
612     SetResolutionParams(param.orignalWidth, param.orignalHeight, param.compressionWidth,
613         param.compressionHeight, screenDensity);
614     if (isDebug && debugServerPort >= 0) {
615 #if defined(__APPLE__) || defined(_WIN32)
616         SetWindowParams();
617         OHOS::Ace::ViewportConfig config;
618         config.SetSize(windowModel->originWidth, windowModel->originHeight);
619         config.SetPosition(0, 0);
620         config.SetOrientation(static_cast<int32_t>(
621             OHOS::Previewer::PreviewerWindow::TransOrientation(windowModel->orientation)));
622         config.SetDensity(windowModel->density);
623         OHOS::Rosen::Window* window = OHOS::Previewer::PreviewerWindow::GetInstance().GetWindowObject();
624         if (!window) {
625             ELOG("JsApp::Run get window failed.");
626             return;
627         }
628         OHOS::AppExecFwk::EventHandler::PostTask([this]() {
629             glfwRenderContext->SetWindowSize(aceRunArgs.deviceWidth, aceRunArgs.deviceHeight);
630         });
631         simulator->UpdateConfiguration(*(UpdateConfiguration(aceRunArgs).get()));
632         window->SetViewportConfig(config);
633 #endif
634     } else {
635         if (ability != nullptr) {
636             OHOS::AppExecFwk::EventHandler::PostTask([this]() {
637                 glfwRenderContext->SetWindowSize(aceRunArgs.deviceWidth, aceRunArgs.deviceHeight);
638             });
639             ability->SurfaceChanged(aceRunArgs.deviceConfig.orientation, aceRunArgs.deviceConfig.density,
640                 aceRunArgs.deviceWidth, aceRunArgs.deviceHeight, ConvertResizeReason(reason));
641         }
642     }
643 }
644 
ConvertResizeReason(std::string reason)645 WindowSizeChangeReason JsAppImpl::ConvertResizeReason(std::string reason)
646 {
647     if (reason == "undefined") {
648         return WindowSizeChangeReason::UNDEFINED;
649     } else if (reason == "rotation") {
650         return WindowSizeChangeReason::ROTATION;
651     } else {
652         return WindowSizeChangeReason::RESIZE;
653     }
654 }
655 
SetResolutionParams(int32_t changedOriginWidth,int32_t changedOriginHeight,int32_t changedWidth,int32_t changedHeight,int32_t screenDensity)656 void JsAppImpl::SetResolutionParams(int32_t changedOriginWidth, int32_t changedOriginHeight, int32_t changedWidth,
657     int32_t changedHeight, int32_t screenDensity)
658 {
659     SetDeviceWidth(aceRunArgs, changedWidth);
660     SetDeviceHeight(aceRunArgs, changedHeight);
661     orignalWidth = changedOriginWidth;
662     orignalHeight = changedOriginHeight;
663     SetDeviceScreenDensity(screenDensity, CommandParser::GetInstance().GetDeviceType());
664     AdaptDeviceType(aceRunArgs, CommandParser::GetInstance().GetDeviceType(), changedOriginWidth);
665     AssignValueForWidthAndHeight(changedOriginWidth, changedOriginHeight, changedWidth, changedHeight);
666     if (changedWidth <= changedHeight) {
667         JsAppImpl::GetInstance().SetDeviceOrentation("portrait");
668     } else {
669         JsAppImpl::GetInstance().SetDeviceOrentation("landscape");
670     }
671     SetOrientation(aceRunArgs, orientation);
672     VirtualScreenImpl::GetInstance().SetCurrentResolution(aceRunArgs.deviceWidth, aceRunArgs.deviceHeight);
673     ILOG("ResolutionChanged: %s %d %d %f", orientation.c_str(), aceRunArgs.deviceWidth,
674          aceRunArgs.deviceHeight, aceRunArgs.deviceConfig.density);
675 }
676 
SetArgsColorMode(const string & value)677 void JsAppImpl::SetArgsColorMode(const string& value)
678 {
679     colorMode = value;
680 }
681 
SetArgsAceVersion(const string & value)682 void JsAppImpl::SetArgsAceVersion(const string& value)
683 {
684     aceVersion = value;
685 }
686 
SetDeviceOrentation(const string & value)687 void JsAppImpl::SetDeviceOrentation(const string& value)
688 {
689     orientation = value;
690 }
691 
GetOrientation() const692 std::string JsAppImpl::GetOrientation() const
693 {
694     return orientation;
695 }
696 
GetColorMode() const697 std::string JsAppImpl::GetColorMode() const
698 {
699     return colorMode;
700 }
701 
SetDeviceScreenDensity(const int32_t screenDensity,const std::string type)702 void JsAppImpl::SetDeviceScreenDensity(const int32_t screenDensity, const std::string type)
703 {
704     if (type == "wearable" && screenDensity != 0) {
705         watchScreenDensity = screenDensity;
706         return;
707     }
708     if (type == "tv" && screenDensity != 0) {
709         tvScreenDensity = screenDensity;
710         return;
711     }
712     if ((type == "phone" || type == "default") && screenDensity != 0) {
713         phoneScreenDensity = screenDensity;
714         return;
715     }
716     if (type == "2in1" && screenDensity != 0) {
717         twoInOneScreenDensity = screenDensity;
718         return;
719     }
720     if (type == "tablet" && screenDensity != 0) {
721         tabletScreenDensity = screenDensity;
722         return;
723     }
724     if (type == "car" && screenDensity != 0) {
725         carScreenDensity = screenDensity;
726         return;
727     }
728     ILOG("DeviceType not supported to SetDeviceScreenDensity: %s", type.c_str());
729     return;
730 }
731 
ReloadRuntimePage(const std::string currentPage)732 void JsAppImpl::ReloadRuntimePage(const std::string currentPage)
733 {
734     std::string params = "";
735     if (ability != nullptr) {
736         ability->ReplacePage(currentPage, params);
737     }
738 }
739 
SetScreenDensity(const std::string value)740 void JsAppImpl::SetScreenDensity(const std::string value)
741 {
742     screenDensity = value;
743 }
744 
SetConfigChanges(const std::string value)745 void JsAppImpl::SetConfigChanges(const std::string value)
746 {
747     configChanges = value;
748 }
749 
MemoryRefresh(const std::string memoryRefreshArgs) const750 bool JsAppImpl::MemoryRefresh(const std::string memoryRefreshArgs) const
751 {
752     ILOG("MemoryRefresh.");
753     if (ability != nullptr) {
754         return ability->OperateComponent(memoryRefreshArgs);
755     }
756     return false;
757 }
758 
ParseSystemParams(OHOS::Ace::Platform::AceRunArgs & args,Json::Value paramObj)759 void JsAppImpl::ParseSystemParams(OHOS::Ace::Platform::AceRunArgs& args, Json::Value paramObj)
760 {
761     if (paramObj == Json::nullValue) {
762         SetDeviceWidth(args, VirtualScreenImpl::GetInstance().GetCompressionWidth());
763         SetDeviceHeight(args, VirtualScreenImpl::GetInstance().GetCompressionHeight());
764         AssignValueForWidthAndHeight(args.deviceWidth, args.deviceHeight,
765                                      args.deviceWidth, args.deviceHeight);
766         SetColorMode(args, colorMode);
767         SetOrientation(args, orientation);
768         SetDeviceScreenDensity(atoi(screenDensity.c_str()),
769                                CommandParser::GetInstance().GetDeviceType());
770         AdaptDeviceType(args, CommandParser::GetInstance().GetDeviceType(), aceRunArgs.deviceWidth);
771         SetLanguage(args, SharedData<string>::GetData(SharedDataType::LAN));
772         SetRegion(args, SharedData<string>::GetData(SharedDataType::REGION));
773     } else {
774         SetDeviceWidth(args, paramObj["width"].asInt());
775         SetDeviceHeight(args, paramObj["height"].asInt());
776         AssignValueForWidthAndHeight(args.deviceWidth, args.deviceHeight,
777                                      args.deviceWidth, args.deviceHeight);
778         SetColorMode(args, paramObj["colorMode"].asString());
779         SetOrientation(args, paramObj["orientation"].asString());
780         string deviceType = paramObj["deviceType"].asString();
781         SetDeviceScreenDensity(atoi(screenDensity.c_str()), deviceType);
782         AdaptDeviceType(args, deviceType, args.deviceWidth, paramObj["dpi"].asDouble());
783         string lanInfo = paramObj["locale"].asString();
784         SetLanguage(args, lanInfo.substr(0, lanInfo.find("_")));
785         SetRegion(args, lanInfo.substr(lanInfo.find("_") + 1, lanInfo.length() - 1));
786     }
787 }
788 
SetSystemParams(OHOS::Ace::Platform::SystemParams & params,Json::Value paramObj)789 void JsAppImpl::SetSystemParams(OHOS::Ace::Platform::SystemParams& params, Json::Value paramObj)
790 {
791     ParseSystemParams(aceRunArgs, paramObj);
792     params.deviceWidth = aceRunArgs.deviceWidth;
793     params.deviceHeight = aceRunArgs.deviceHeight;
794     params.language = aceRunArgs.language;
795     params.region = aceRunArgs.region;
796     params.colorMode = aceRunArgs.deviceConfig.colorMode;
797     params.orientation = aceRunArgs.deviceConfig.orientation;
798     params.deviceType = aceRunArgs.deviceConfig.deviceType;
799     params.density = aceRunArgs.deviceConfig.density;
800     params.isRound = (paramObj == Json::nullValue) ?
801                      (CommandParser::GetInstance().GetScreenShape() == "circle") :
802                      paramObj["roundScreen"].asBool();
803 }
804 
LoadDocument(const std::string filePath,const std::string componentName,Json::Value previewContext)805 void JsAppImpl::LoadDocument(const std::string filePath,
806                              const std::string componentName,
807                              Json::Value previewContext)
808 {
809     ILOG("LoadDocument.");
810     if (ability != nullptr) {
811         OHOS::Ace::Platform::SystemParams params;
812         SetSystemParams(params, previewContext);
813         ILOG("LoadDocument params is density: %f region: %s language: %s deviceWidth: %d\
814              deviceHeight: %d isRound:%d colorMode:%s orientation: %s deviceType: %s",
815              params.density,
816              params.region.c_str(),
817              params.language.c_str(),
818              params.deviceWidth,
819              params.deviceHeight,
820              (params.isRound ? "true" : "false"),
821              ((params.colorMode == ColorMode::DARK) ? "dark" : "light"),
822              ((params.orientation == DeviceOrientation::LANDSCAPE) ? "landscape" : "portrait"),
823              GetDeviceTypeName(params.deviceType).c_str());
824         OHOS::AppExecFwk::EventHandler::PostTask([this]() {
825             glfwRenderContext->SetWindowSize(aceRunArgs.deviceWidth, aceRunArgs.deviceHeight);
826         });
827         ability->LoadDocument(filePath, componentName, params);
828     }
829 }
830 
DispatchBackPressedEvent() const831 void JsAppImpl::DispatchBackPressedEvent() const
832 {
833     ability->OnBackPressed();
834 }
DispatchKeyEvent(const std::shared_ptr<OHOS::MMI::KeyEvent> & keyEvent) const835 void JsAppImpl::DispatchKeyEvent(const std::shared_ptr<OHOS::MMI::KeyEvent>& keyEvent) const
836 {
837     if (isDebug && debugServerPort >= 0) {
838 #if defined(__APPLE__) || defined(_WIN32)
839         OHOS::Rosen::Window* window = OHOS::Previewer::PreviewerWindow::GetInstance().GetWindowObject();
840         if (!window) {
841             ELOG("JsApp::Run get window failed.");
842             return;
843         }
844         window->ConsumeKeyEvent(keyEvent);
845 #endif
846     } else {
847         ability->OnInputEvent(keyEvent);
848     }
849 }
DispatchPointerEvent(const std::shared_ptr<OHOS::MMI::PointerEvent> & pointerEvent) const850 void JsAppImpl::DispatchPointerEvent(const std::shared_ptr<OHOS::MMI::PointerEvent>& pointerEvent) const
851 {
852     if (isDebug && debugServerPort >= 0) {
853 #if defined(__APPLE__) || defined(_WIN32)
854         OHOS::Rosen::Window* window = OHOS::Previewer::PreviewerWindow::GetInstance().GetWindowObject();
855         if (!window) {
856             ELOG("JsApp::Run get window failed.");
857             return;
858         }
859         window->ConsumePointerEvent(pointerEvent);
860 #endif
861     } else {
862         ability->OnInputEvent(pointerEvent);
863     }
864 }
DispatchAxisEvent(const std::shared_ptr<OHOS::MMI::AxisEvent> & axisEvent) const865 void JsAppImpl::DispatchAxisEvent(const std::shared_ptr<OHOS::MMI::AxisEvent>& axisEvent) const
866 {
867     ability->OnInputEvent(axisEvent);
868 }
DispatchInputMethodEvent(const unsigned int codePoint) const869 void JsAppImpl::DispatchInputMethodEvent(const unsigned int codePoint) const
870 {
871     ability->OnInputMethodEvent(codePoint);
872 }
873 
GetDeviceTypeName(const OHOS::Ace::DeviceType type) const874 string JsAppImpl::GetDeviceTypeName(const OHOS::Ace::DeviceType type) const
875 {
876     switch (type) {
877         case DeviceType::WATCH:
878             return "watch";
879         case DeviceType::TV:
880             return "tv";
881         case DeviceType::PHONE:
882             return "phone";
883         case DeviceType::TABLET:
884             return "tablet";
885         case DeviceType::CAR:
886             return "car";
887         default:
888             return "";
889     }
890 }
891 
InitGlfwEnv()892 void JsAppImpl::InitGlfwEnv()
893 {
894     ILOG("InitGlfwEnv started");
895     glfwRenderContext = OHOS::Rosen::GlfwRenderContext::GetGlobal();
896     if (!glfwRenderContext->Init()) {
897         ELOG("Could not create window: InitGlfwEnv failed.");
898         return;
899     }
900     glfwRenderContext->CreateGlfwWindow(aceRunArgs.deviceWidth, aceRunArgs.deviceHeight, false);
901     ILOG("InitGlfwEnv finished");
902 }
903 
SetMockJsonInfo()904 void JsAppImpl::SetMockJsonInfo()
905 {
906     string filePath = CommandParser::GetInstance().GetAppResourcePath() +
907         FileSystem::GetSeparator() + "mock-config.json";
908     if (isDebug && debugServerPort >= 0) {
909 #if defined(__APPLE__) || defined(_WIN32)
910         simulator->SetMockList(Ide::StageContext::GetInstance().ParseMockJsonFile(filePath));
911 #endif
912     } else {
913         ability->SetMockModuleList(Ide::StageContext::GetInstance().ParseMockJsonFile(filePath));
914     }
915 }
916 
FoldStatusChanged(const std::string commandFoldStatus,int32_t width,int32_t height)917 void JsAppImpl::FoldStatusChanged(const std::string commandFoldStatus, int32_t width, int32_t height)
918 {
919     string reason = "resize";
920     ILOG("FoldStatusChanged commandFoldStatus:%s", commandFoldStatus.c_str());
921     VirtualScreenImpl::GetInstance().SetFoldStatus(commandFoldStatus);
922     OHOS::Rosen::FoldStatus status = ConvertFoldStatus(commandFoldStatus);
923     // execute callback
924     OHOS::Previewer::PreviewerDisplay::GetInstance().SetFoldStatus(status);
925     OHOS::Previewer::PreviewerDisplay::GetInstance().ExecStatusChangedCallback();
926     if (status == OHOS::Rosen::FoldStatus::UNKNOWN) {
927         return; // unknown status do nothing
928     }
929     // change resolution
930     ResolutionParam param(width, height, width, height);
931     ResolutionChanged(param, atoi(screenDensity.c_str()), reason);
932 }
933 
ConvertFoldStatus(std::string value) const934 OHOS::Rosen::FoldStatus JsAppImpl::ConvertFoldStatus(std::string value) const
935 {
936     OHOS::Rosen::FoldStatus foldStatus = OHOS::Rosen::FoldStatus::EXPAND;
937     if (value == "fold") {
938         foldStatus = OHOS::Rosen::FoldStatus::FOLDED;
939     } else if (value == "unfold") {
940         foldStatus = OHOS::Rosen::FoldStatus::EXPAND;
941     } else if (value == "half_fold") {
942         foldStatus = OHOS::Rosen::FoldStatus::HALF_FOLD;
943     } else {
944         foldStatus = OHOS::Rosen::FoldStatus::UNKNOWN;
945     }
946     return foldStatus;
947 }