• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef FOUNDATION_ACE_FRAMEWORKS_BRIDGE_DECLARATIVE_FRONTEND_FRONTEND_DELEGATE_DECLARATIVE_H
17 #define FOUNDATION_ACE_FRAMEWORKS_BRIDGE_DECLARATIVE_FRONTEND_FRONTEND_DELEGATE_DECLARATIVE_H
18 
19 #include <future>
20 #include <mutex>
21 #include <unordered_map>
22 
23 #include "base/memory/ace_type.h"
24 #include "base/memory/referenced.h"
25 #include "base/thread/cancelable_callback.h"
26 #include "base/utils/measure_util.h"
27 #include "bridge/declarative_frontend/ng/page_router_manager.h"
28 #include "core/common/js_message_dispatcher.h"
29 #include "core/pipeline/pipeline_context.h"
30 #include "frameworks/bridge/common/accessibility/accessibility_node_manager.h"
31 #include "frameworks/bridge/common/manifest/manifest_parser.h"
32 #include "frameworks/bridge/js_frontend/engine/common/group_js_bridge.h"
33 #include "frameworks/bridge/js_frontend/engine/common/js_engine.h"
34 #include "frameworks/bridge/js_frontend/frontend_delegate.h"
35 #include "frameworks/bridge/js_frontend/frontend_delegate_impl.h"
36 #include "frameworks/bridge/js_frontend/js_ace_page.h"
37 
38 namespace OHOS::Ace::Framework {
39 
40 using ExternalEventCallback = std::function<void(const std::string&, const uint32_t&, const bool&)>;
41 
42 enum class RouterAction {
43     PUSH = 0,
44     REPLACE,
45     BACK,
46     CLEAR,
47 };
48 
49 struct RouterTask {
50     RouterAction action = RouterAction::PUSH;
51     PageTarget target = PageTarget("");
52     std::string params;
53     std::function<void(const std::string&, int32_t)> errorCallback;
54 };
55 
56 class FrontendDelegateDeclarative : public FrontendDelegate {
57     DECLARE_ACE_TYPE(FrontendDelegateDeclarative, FrontendDelegate);
58 
59 public:
60     FrontendDelegateDeclarative(const RefPtr<TaskExecutor>& taskExecutor, const LoadJsCallback& loadCallback,
61         const JsMessageDispatcherSetterCallback& transferCallback, const EventCallback& asyncEventCallback,
62         const EventCallback& syncEventCallback, const UpdatePageCallback& updatePageCallback,
63         const ResetStagingPageCallback& resetLoadingPageCallback, const DestroyPageCallback& destroyPageCallback,
64         const DestroyApplicationCallback& destroyApplicationCallback,
65         const UpdateApplicationStateCallback& updateApplicationStateCallback, const TimerCallback& timerCallback,
66         const MediaQueryCallback& mediaQueryCallback, const LayoutInspectorCallback& layoutInpsectorCallback,
67         const DrawInspectorCallback& drawInpsectorCallback, const RequestAnimationCallback& requestAnimationCallback,
68         const JsCallback& jsCallback, const OnWindowDisplayModeChangedCallBack& onWindowDisplayModeChangedCallBack,
69         const OnConfigurationUpdatedCallBack& onConfigurationUpdatedCallBack,
70         const OnSaveAbilityStateCallBack& onSaveAbilityStateCallBack,
71         const OnRestoreAbilityStateCallBack& onRestoreAbilityStateCallBack, const OnNewWantCallBack& onNewWantCallBack,
72         const OnMemoryLevelCallBack& onMemoryLevelCallBack,
73         const OnStartContinuationCallBack& onStartContinuationCallBack,
74         const OnCompleteContinuationCallBack& onCompleteContinuationCallBack,
75         const OnRemoteTerminatedCallBack& onRemoteTerminatedCallBack, const OnSaveDataCallBack& onSaveDataCallBack,
76         const OnRestoreDataCallBack& onRestoreDataCallBack, const ExternalEventCallback& externalEventCallback);
77     ~FrontendDelegateDeclarative() override;
78 
79     void AttachPipelineContext(const RefPtr<PipelineBase>& context) override;
80     void AttachSubPipelineContext(const RefPtr<PipelineBase>& context);
81 
82     // JSFrontend delegate functions.
83     void RunPage(const std::string& url, const std::string& params, const std::string& profile);
84     void SetJsMessageDispatcher(const RefPtr<JsMessageDispatcher>& dispatcher) const;
85     void TransferComponentResponseData(int32_t callbackId, int32_t code, std::vector<uint8_t>&& data);
86     void TransferJsResponseData(int32_t callbackId, int32_t code, std::vector<uint8_t>&& data) const;
87 #if defined(PREVIEW)
88     void TransferJsResponseDataPreview(int32_t callbackId, int32_t code, ResponseData responseData) const;
89 #endif
90     void TransferJsPluginGetError(int32_t callbackId, int32_t errorCode, std::string&& errorMessage) const;
91     void TransferJsEventData(int32_t callbackId, int32_t code, std::vector<uint8_t>&& data) const;
92     void LoadPluginJsCode(std::string&& jsCode) const;
93     void LoadPluginJsByteCode(std::vector<uint8_t>&& jsCode, std::vector<int32_t>&& jsCodeLen) const;
94     void OnJSCallback(const std::string& callbackId, const std::string& data);
95     bool OnPageBackPress();
96     void OnBackGround();
97     void OnForeground();
98     void OnConfigurationUpdated(const std::string& data);
99     void OnSaveAbilityState(std::string& data);
100     void OnRestoreAbilityState(const std::string& data);
101     void OnNewWant(const std::string& data);
102     bool OnStartContinuation();
103     void OnCompleteContinuation(int32_t code);
104     void OnMemoryLevel(int32_t level);
105     void OnSaveData(std::string& data);
106     void GetPluginsUsed(std::string& data);
107     bool OnRestoreData(const std::string& data);
108     void OnRemoteTerminated();
109     void OnNewRequest(const std::string& data);
110     void SetColorMode(ColorMode colorMode);
111     void CallPopPage();
112     void OnApplicationDestroy(const std::string& packageName);
113     void UpdateApplicationState(const std::string& packageName, Frontend::State state);
114     void OnWindowDisplayModeChanged(bool isShownInMultiWindow, const std::string& data);
115     void NotifyAppStorage(
116         const WeakPtr<Framework::JsEngine>& jsEngineWeak, const std::string& key, const std::string& value);
117 
118     // distribute
119     std::string RestoreRouterStack(const std::string& contentInfo) override;
120     std::string GetContentInfo() override;
121 
122     // Accessibility delegate functions.
GetJSAccessibilityManager()123     RefPtr<Framework::AccessibilityNodeManager> GetJSAccessibilityManager() const
124     {
125         return jsAccessibilityManager_;
126     }
127     void FireAccessibilityEvent(const AccessibilityEvent& accessibilityEvent);
128     void InitializeAccessibilityCallback();
129 
130     void OnMediaQueryUpdate(bool isSynchronous = false) override;
131     void OnSurfaceChanged();
132     void OnLayoutCompleted(const std::string& componentId);
133     void OnDrawCompleted(const std::string& componentId);
134     // JSEventHandler delegate functions.
135     void FireAsyncEvent(const std::string& eventId, const std::string& param, const std::string& jsonArgs);
136     bool FireSyncEvent(const std::string& eventId, const std::string& param, const std::string& jsonArgs);
137     void FireSyncEvent(
138         const std::string& eventId, const std::string& param, const std::string& jsonArgs, std::string& result);
139     void FireExternalEvent(const std::string& eventId, const std::string& componentId, uint32_t nodeId, bool isDestroy);
140 
141     // FrontendDelegate overrides.
142     void Push(const PageTarget& target, const std::string& params,
143         const std::function<void(const std::string&, int32_t)>& errorCallback = nullptr);
144     void Replace(const PageTarget& target, const std::string& params,
145         const std::function<void(const std::string&, int32_t)>& errorCallback = nullptr);
146     void BackWithTarget(const PageTarget& target, const std::string& params);
147 
148     void Push(const std::string& uri, const std::string& params) override;
149     void PushWithMode(const std::string& uri, const std::string& params, uint32_t routerMode) override;
150     void PushWithCallback(const std::string& uri, const std::string& params,
151         const std::function<void(const std::string&, int32_t)>& errorCallback, uint32_t routerMode = 0) override;
152     void PushNamedRoute(const std::string& uri, const std::string& params,
153         const std::function<void(const std::string&, int32_t)>& errorCallback, uint32_t routerMode = 0) override;
154     void Replace(const std::string& uri, const std::string& params) override;
155     void ReplaceWithMode(const std::string& uri, const std::string& params, uint32_t routerMode) override;
156     void ReplaceWithCallback(const std::string& uri, const std::string& params,
157         const std::function<void(const std::string&, int32_t)>& errorCallback, uint32_t routerMode = 0) override;
158     void ReplaceNamedRoute(const std::string& uri, const std::string& params,
159         const std::function<void(const std::string&, int32_t)>& errorCallback, uint32_t routerMode = 0) override;
160     void Back(const std::string& uri, const std::string& params) override;
161     void Clear() override;
162     int32_t GetStackSize() const override;
163     void GetState(int32_t& index, std::string& name, std::string& path) override;
164     std::string GetParams() override;
165 
166     void PostponePageTransition() override;
167     void LaunchPageTransition() override;
168     size_t GetComponentsCount() override;
169     void TriggerPageUpdate(int32_t pageId, bool directExecute = false) override;
170 
171     void PostJsTask(std::function<void()>&& task) override;
172 
173     const std::string& GetAppID() const override;
174     const std::string& GetAppName() const override;
175     const std::string& GetVersionName() const override;
176     int32_t GetVersionCode() const override;
GetWindowConfig()177     WindowConfig& GetWindowConfig()
178     {
179         return manifestParser_->GetWindowConfig();
180     }
181 
182     double MeasureText(const MeasureContext& context) override;
183     Size MeasureTextSize(const MeasureContext& context) override;
184 
185     void ShowToast(const std::string& message, int32_t duration, const std::string& bottom) override;
186     void SetToastStopListenerCallback(std::function<void()>&& stopCallback) override;
187     void ShowDialog(const std::string& title, const std::string& message, const std::vector<ButtonInfo>& buttons,
188         bool autoCancel, std::function<void(int32_t, int32_t)>&& callback,
189         const std::set<std::string>& callbacks) override;
190     void ShowDialog(const std::string& title, const std::string& message, const std::vector<ButtonInfo>& buttons,
191         bool autoCancel, std::function<void(int32_t, int32_t)>&& callback,
192         const std::set<std::string>& callbacks, std::function<void(bool)>&& onStatusChanged) override;
193     void ShowDialog(const PromptDialogAttr &dialogAttr, const std::vector<ButtonInfo> &buttons,
194         std::function<void(int32_t, int32_t)> &&callback, const std::set<std::string> &callbacks) override;
195     void ShowDialog(const PromptDialogAttr &dialogAttr, const std::vector<ButtonInfo> &buttons,
196         std::function<void(int32_t, int32_t)> &&callback, const std::set<std::string> &callbacks,
197         std::function<void(bool)>&& onStatusChanged) override;
198     void ShowDialogInner(DialogProperties& dialogProperties, std::function<void(int32_t, int32_t)>&& callback,
199         const std::set<std::string>& callbacks);
200 
201     void EnableAlertBeforeBackPage(const std::string& message, std::function<void(int32_t)>&& callback) override;
202 
203     void DisableAlertBeforeBackPage() override;
204 
205     void ShowActionMenu(const std::string& title, const std::vector<ButtonInfo>& button,
206         std::function<void(int32_t, int32_t)>&& callback) override;
207     void ShowActionMenu(const std::string& title, const std::vector<ButtonInfo>& button,
208         std::function<void(int32_t, int32_t)>&& callback, std::function<void(bool)>&& onStatusChanged) override;
209     void ShowActionMenuInner(DialogProperties& dialogProperties, const std::vector<ButtonInfo>& button,
210         std::function<void(int32_t, int32_t)>&& callback);
211 
212     Rect GetBoundingRectData(NodeId nodeId) override;
213 
214     std::string GetInspector(NodeId nodeId) override;
215 
216     void PushJsCallbackToRenderNode(NodeId id, double ratio, std::function<void(bool, double)>&& callback) override;
217     // For async event.
218     void SetCallBackResult(const std::string& callBackId, const std::string& result) override;
219 
220     void WaitTimer(const std::string& callbackId, const std::string& delay, bool isInterval, bool isFirst) override;
221     void ClearTimer(const std::string& callbackId) override;
222 
223     void PostSyncTaskToPage(std::function<void()>&& task) override;
224     void AddTaskObserver(std::function<void()>&& task) override;
225     void RemoveTaskObserver() override;
226 
227     bool GetAssetContent(const std::string& url, std::string& content) override;
228     bool GetAssetContent(const std::string& url, std::vector<uint8_t>& content) override;
229     std::string GetAssetPath(const std::string& url) override;
230 
231     // i18n
232     void GetI18nData(std::unique_ptr<JsonValue>& json) override;
233 
234     void GetResourceConfiguration(std::unique_ptr<JsonValue>& json) override;
235 
236     void GetConfigurationCommon(const std::string& filePath, std::unique_ptr<JsonValue>& data) override;
237 
238     int32_t GetMinPlatformVersion() override;
239 
240     void LoadResourceConfiguration(std::map<std::string, std::string>& mediaResourceFileMap,
241         std::unique_ptr<JsonValue>& currentResourceData) override;
242 
243     void ChangeLocale(const std::string& language, const std::string& countryOrRegion) override;
244 
245     void RegisterFont(const std::string& familyName, const std::string& familySrc) override;
246 
247     void GetSystemFontList(std::vector<std::string>& fontList) override;
248 
249     bool GetSystemFont(const std::string& fontName, FontInfo& fontInfo) override;
250 
251     void HandleImage(const std::string& src, std::function<void(bool, int32_t, int32_t)>&& callback) override;
252 
253     void GetSnapshot(const std::string& componentId,
254         std::function<void(std::shared_ptr<Media::PixelMap>, int32_t)>&& callback) override;
255     void CreateSnapshot(std::function<void()>&& customBuilder,
256         std::function<void(std::shared_ptr<Media::PixelMap>, int32_t)>&& callback) override;
257 
258     void RequestAnimationFrame(const std::string& callbackId) override;
259 
260     void CancelAnimationFrame(const std::string& callbackId) override;
261 
262     SingleTaskExecutor GetAnimationJsTask() override;
263 
264     SingleTaskExecutor GetUiTask() override;
265 
GetMediaQueryInfoInstance()266     const RefPtr<MediaQueryInfo>& GetMediaQueryInfoInstance() override
267     {
268         return mediaQueryInfo_;
269     }
270 
GetGroupJsBridge()271     const RefPtr<GroupJsBridge>& GetGroupJsBridge() override
272     {
273         return groupJsBridge_;
274     }
275 
276 #if defined(PREVIEW)
SetPagePath(const std::string & pagePath)277     void SetPagePath(const std::string& pagePath)
278     {
279         if (manifestParser_) {
280             manifestParser_->SetPagePath(pagePath);
281         }
282     }
283 #endif
284 
285     RefPtr<PipelineBase> GetPipelineContext() override;
286 
SetGroupJsBridge(const RefPtr<GroupJsBridge> & groupJsBridge)287     void SetGroupJsBridge(const RefPtr<GroupJsBridge>& groupJsBridge)
288     {
289         groupJsBridge_ = groupJsBridge;
290     }
291 
292     RefPtr<JsAcePage> GetPage(int32_t pageId) const override;
293 
294     void RebuildAllPages();
295 
296     std::string GetCurrentPageUrl();
297 
298     // Get the currently running JS page information in NG structure.
299     RefPtr<RevSourceMap> GetCurrentPageSourceMap();
300 
301     // Get the currently running JS page information in NG structure.
302     RefPtr<RevSourceMap> GetFaAppSourceMap();
303 
304     void GetStageSourceMap(
305         std::unordered_map<std::string, RefPtr<Framework::RevSourceMap>>& sourceMap);
306 
307     void InitializeRouterManager(
308         NG::LoadPageCallback&& loadPageCallback, NG::LoadNamedRouterCallback&& loadNamedRouterCallback);
309 
GetPageRouterManager()310     const RefPtr<NG::PageRouterManager>& GetPageRouterManager() const
311     {
312         return pageRouterManager_;
313     }
314 
GetTaskExecutor()315     const RefPtr<TaskExecutor>& GetTaskExecutor() const
316     {
317         return taskExecutor_;
318     }
319 
GetManifestParser()320     const RefPtr<Framework::ManifestParser>& GetManifestParser() const
321     {
322         return manifestParser_;
323     }
324 
325 protected:
326     bool isCardDelegate_ = false;
327 
328 private:
329     int32_t GenerateNextPageId();
330     void RecyclePageId(int32_t pageId);
331 
332     void LoadPage(
333         int32_t pageId, const PageTarget& target, bool isMainPage, const std::string& params, bool isRestore = false);
334     void OnPageReady(const RefPtr<Framework::JsAcePage>& page, const std::string& url, bool isMainPage, bool isRestore);
335     void FlushPageCommand(
336         const RefPtr<Framework::JsAcePage>& page, const std::string& url, bool isMainPage, bool isRestore);
337     void AddPageLocked(const RefPtr<JsAcePage>& page);
338     void OnPrePageChange(const RefPtr<JsAcePage>& page);
339     void SetCurrentPage(int32_t pageId);
340 
341     void OnPushPageSuccess(const RefPtr<JsAcePage>& page, const std::string& url);
342     void OnPopToPageSuccess(const std::string& url);
343     void PopToPage(const std::string& url);
344     int32_t OnPopPageSuccess();
345     void PopPage();
346     void RestorePopPage(const RefPtr<JsAcePage>& page, const std::string& url);
347 
348     void PushPageTransitionListener(const TransitionEvent& event, const RefPtr<JsAcePage>& page);
349 
350     void PopPageTransitionListener(const TransitionEvent& event, int32_t destroyPageId);
351 
352     void PopToPageTransitionListener(const TransitionEvent& event, const std::string& url, int32_t pageId);
353 
354     void RestorePageTransitionListener(
355         const TransitionEvent& event, const std::string& url, const RefPtr<JsAcePage>& page);
356 
357     int32_t OnClearInvisiblePagesSuccess();
358     void ClearInvisiblePages();
359 
360     void OnReplacePageSuccess(const RefPtr<JsAcePage>& page, const std::string& url);
361     void ReplacePage(const RefPtr<JsAcePage>& page, const std::string& url);
362     void LoadReplacePage(int32_t pageId, const PageTarget& url, const std::string& params);
363 
364     void ReplacePageInSubStage(const RefPtr<JsAcePage>& page, const std::string& url);
365 
366     uint64_t GetSystemRealTime();
367 
368     // Page lifecycle
369     void OnPageShow();
370     void OnPageHide();
371     void OnPageDestroy(int32_t pageId);
372 
373     int32_t GetRunningPageId() const;
374     std::string GetRunningPageUrl() const;
375     int32_t GetPageIdByUrl(const std::string& url, bool& isRestore);
GetPageIdByUrl(const std::string & url)376     int32_t GetPageIdByUrl(const std::string& url)
377     {
378         bool tmp = false;
379         return GetPageIdByUrl(url, tmp);
380     }
381 
382     void ResetStagingPage();
383     void FlushAnimationTasks();
384 
385     void StartPush(const PageTarget& target, const std::string& params,
386         const std::function<void(const std::string&, int32_t)>& errorCallback);
387     void StartReplace(const PageTarget& target, const std::string& params,
388         const std::function<void(const std::string&, int32_t)>& errorCallback);
389     void StartBack(const PageTarget& target, const std::string& params);
390     void BackCheckAlert(const PageTarget& target, const std::string& params);
391     void ProcessRouterTask();
392     void AddRouterTask(const RouterTask& task);
393     bool IsNavigationStage(const PageTarget& target);
394     void RecycleSinglePage();
395     void ClearAlertCallback(PageInfo pageInfo);
396 
397     std::atomic<uint64_t> pageIdPool_ = 0;
398     int32_t callbackCnt_ = 0;
399     int32_t pageId_ = -1;
400     bool isRouteStackFull_ = false;
401     bool isStagingPageExist_ = false;
402     int32_t singlePageId_ = -1;
403     std::string mainPagePath_;
404     PageTarget backUri_ = PageTarget("");
405     std::string backParam_;
406     std::vector<PageInfo> pageRouteStack_;
407     std::unordered_map<int32_t, RefPtr<JsAcePage>> pageMap_;
408     std::unordered_map<int32_t, std::string> pageParamMap_;
409     std::unordered_map<int32_t, std::string> jsCallBackResult_;
410 
411     LoadJsCallback loadJs_;
412     ExternalEventCallback externalEvent_;
413     JsMessageDispatcherSetterCallback dispatcherCallback_;
414     EventCallback asyncEvent_;
415     EventCallback syncEvent_;
416     UpdatePageCallback updatePage_;
417     ResetStagingPageCallback resetStagingPage_;
418     DestroyPageCallback destroyPage_;
419     DestroyApplicationCallback destroyApplication_;
420     UpdateApplicationStateCallback updateApplicationState_;
421     TimerCallback timer_;
422     std::unordered_map<std::string, CancelableCallback<void()>> timeoutTaskMap_;
423     MediaQueryCallback mediaQueryCallback_;
424     LayoutInspectorCallback layoutInspectorCallback_;
425     DrawInspectorCallback drawInspectorCallback_;
426     RequestAnimationCallback requestAnimationCallback_;
427     JsCallback jsCallback_;
428     OnWindowDisplayModeChangedCallBack onWindowDisplayModeChanged_;
429     OnConfigurationUpdatedCallBack onConfigurationUpdated_;
430     OnSaveAbilityStateCallBack onSaveAbilityState_;
431     OnRestoreAbilityStateCallBack onRestoreAbilityState_;
432     OnNewWantCallBack onNewWant_;
433     OnMemoryLevelCallBack onMemoryLevel_;
434     OnStartContinuationCallBack onStartContinuationCallBack_;
435     OnCompleteContinuationCallBack onCompleteContinuationCallBack_;
436     OnRemoteTerminatedCallBack onRemoteTerminatedCallBack_;
437     OnSaveDataCallBack onSaveDataCallBack_;
438     OnRestoreDataCallBack onRestoreDataCallBack_;
439     RefPtr<Framework::ManifestParser> manifestParser_;
440     RefPtr<Framework::AccessibilityNodeManager> jsAccessibilityManager_;
441     RefPtr<MediaQueryInfo> mediaQueryInfo_;
442     RefPtr<GroupJsBridge> groupJsBridge_;
443 
444     RefPtr<TaskExecutor> taskExecutor_;
445 
446     PipelineContextHolder pipelineContextHolder_;
447 
448     BaseId::IdType pageTransitionListenerId_ = 0L;
449     std::queue<std::string> animationFrameTaskIds_;
450     std::unordered_map<std::string, CancelableCallback<void()>> animationFrameTaskMap_;
451 
452     mutable std::mutex mutex_;
453 
454     std::queue<RouterTask> routerQueue_;
455     mutable std::mutex routerQueueMutex_;
456 
457     RefPtr<RevSourceMap> appSourceMap_;
458     RefPtr<NG::PageRouterManager> pageRouterManager_;
459 };
460 
461 } // namespace OHOS::Ace::Framework
462 
463 #endif // FOUNDATION_ACE_FRAMEWORKS_BRIDGE_DECLARATIVE_FRONTEND_FRONTEND_DELEGATE_DECLARATIVE_H
464