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_PLUGIN_FRONTEND_PLUGIN_FRONTEND_DELEGATE_H
17 #define FOUNDATION_ACE_FRAMEWORKS_BRIDGE_PLUGIN_FRONTEND_PLUGIN_FRONTEND_DELEGATE_H
18 
19 #include <future>
20 #include <mutex>
21 #include <unordered_map>
22 
23 #include "base/memory/ace_type.h"
24 #include "base/thread/cancelable_callback.h"
25 #include "base/utils/measure_util.h"
26 #include "core/common/js_message_dispatcher.h"
27 #include "core/pipeline/pipeline_context.h"
28 #include "frameworks/bridge/common/accessibility/accessibility_node_manager.h"
29 #include "frameworks/bridge/common/manifest/manifest_parser.h"
30 #include "frameworks/bridge/js_frontend/engine/common/group_js_bridge.h"
31 #include "frameworks/bridge/js_frontend/engine/common/js_engine.h"
32 #include "frameworks/bridge/js_frontend/frontend_delegate.h"
33 #include "frameworks/bridge/js_frontend/frontend_delegate_impl.h"
34 #include "frameworks/bridge/js_frontend/js_ace_page.h"
35 
36 namespace OHOS::Ace::Framework {
37 class PluginFrontendDelegate : public FrontendDelegate {
38     DECLARE_ACE_TYPE(PluginFrontendDelegate, FrontendDelegate);
39 
40 public:
41     using onPluginUpdateWithValueParams = std::function<void(const std::string&)>;
42 
43     PluginFrontendDelegate(const RefPtr<TaskExecutor>& taskExecutor, const LoadJsCallback& loadCallback,
44         const JsMessageDispatcherSetterCallback& transferCallback, const EventCallback& asyncEventCallback,
45         const EventCallback& syncEventCallback, const UpdatePageCallback& updatePageCallback,
46         const ResetStagingPageCallback& resetLoadingPageCallback, const DestroyPageCallback& destroyPageCallback,
47         const DestroyApplicationCallback& destroyApplicationCallback,
48         const UpdateApplicationStateCallback& updateApplicationStateCallback, const TimerCallback& timerCallback,
49         const MediaQueryCallback& mediaQueryCallback, const RequestAnimationCallback& requestAnimationCallback,
50         const JsCallback& jsCallback, const OnWindowDisplayModeChangedCallBack& onWindowDisplayModeChangedCallBack,
51         const OnConfigurationUpdatedCallBack& onConfigurationUpdatedCallBack,
52         const OnSaveAbilityStateCallBack& onSaveAbilityStateCallBack,
53         const OnRestoreAbilityStateCallBack& onRestoreAbilityStateCallBack,
54         const OnNewWantCallBack& onNewWantCallBack,
55         const OnActiveCallBack& onActiveCallBack, const OnInactiveCallBack& onInactiveCallBack,
56         const OnMemoryLevelCallBack& onMemoryLevelCallBack,
57         const OnStartContinuationCallBack& onStartContinuationCallBack,
58         const OnCompleteContinuationCallBack& onCompleteContinuationCallBack,
59         const OnRemoteTerminatedCallBack& onRemoteTerminatedCallBack,
60         const OnSaveDataCallBack& onSaveDataCallBack,
61         const OnRestoreDataCallBack& onRestoreDataCallBack);
62     ~PluginFrontendDelegate() override;
63 
64     void AttachPipelineContext(const RefPtr<PipelineBase>& context) override;
65 
66     // JSFrontend delegate functions.
67     UIContentErrorCode RunPage(const std::string& url, const std::string& params);
68     void SetJsMessageDispatcher(const RefPtr<JsMessageDispatcher>& dispatcher) const;
69     void TransferComponentResponseData(int32_t callbackId, int32_t code, std::vector<uint8_t>&& data);
70     void TransferJsResponseData(int32_t callbackId, int32_t code, std::vector<uint8_t>&& data) const;
71 #if defined(PREVIEW)
72     void TransferJsResponseDataPreview(int32_t callbackId, int32_t code, ResponseData responseData) const;
73 #endif
74     void TransferJsPluginGetError(int32_t callbackId, int32_t errorCode, std::string&& errorMessage) const;
75     void TransferJsEventData(int32_t callbackId, int32_t code, std::vector<uint8_t>&& data) const;
76     void LoadPluginJsCode(std::string&& jsCode) const;
77     void LoadPluginJsByteCode(std::vector<uint8_t>&& jsCode, std::vector<int32_t>&& jsCodeLen) const;
78     void OnJSCallback(const std::string& callbackId, const std::string& data);
79     bool OnPageBackPress();
80     void OnBackGround();
81     void OnForeground();
82     void OnConfigurationUpdated(const std::string& data);
83     void OnSaveAbilityState(std::string& data);
84     void OnRestoreAbilityState(const std::string& data);
85     void OnNewWant(const std::string& data);
86     void OnSuspended();
87     bool OnStartContinuation();
88     void OnCompleteContinuation(int32_t code);
89     void OnMemoryLevel(const int32_t level);
90     void OnSaveData(std::string& data);
91     void GetPluginsUsed(std::string& data);
92     bool OnRestoreData(const std::string& data);
93     void OnRemoteTerminated();
94     void OnActive();
95     void OnInactive();
96     void OnNewRequest(const std::string& data);
97     void SetColorMode(ColorMode colorMode);
98     void CallPopPage();
99     void OnApplicationDestroy(const std::string& packageName);
100     void UpdateApplicationState(const std::string& packageName, Frontend::State state);
101     void OnWindowDisplayModeChanged(bool isShownInMultiWindow, const std::string& data);
102     void NotifyAppStorage(const WeakPtr<Framework::JsEngine>& jsEngineWeak,
103         const std::string& key, const std::string& value);
104 
105     // Accessibility delegate functions.
GetJSAccessibilityManager()106     RefPtr<Framework::AccessibilityNodeManager> GetJSAccessibilityManager() const
107     {
108         return jsAccessibilityManager_;
109     }
110     void FireAccessibilityEvent(const AccessibilityEvent& accessibilityEvent);
111     void InitializeAccessibilityCallback();
112 
113     void OnMediaQueryUpdate(bool isSynchronous = false) override;
114     void OnSurfaceChanged();
115     // JSEventHandler delegate functions.
116     void FireAsyncEvent(const std::string& eventId, const std::string& param, const std::string& jsonArgs);
117     bool FireSyncEvent(const std::string& eventId, const std::string& param, const std::string& jsonArgs);
118     void FireSyncEvent(
119         const std::string& eventId, const std::string& param, const std::string& jsonArgs, std::string& result);
120 
121     // FrontendDelegate overrides.
122     void Push(const PageTarget& target, const std::string& params);
123     void Replace(const PageTarget& target, const std::string& params);
124     void BackWithTarget(const PageTarget& target, const std::string& params);
125     void Push(const std::string& uri, const std::string& params) override;
126     void Replace(const std::string& uri, const std::string& params) override;
127     void Back(const std::string& uri, const std::string& params) override;
128     void PostponePageTransition() override;
129     void LaunchPageTransition() override;
130     void Clear() override;
131     int32_t GetStackSize() const override;
132     void GetState(int32_t& index, std::string& name, std::string& path) override;
133     size_t GetComponentsCount() override;
134     std::string GetParams() override;
135     void TriggerPageUpdate(int32_t pageId, bool directExecute = false) override;
136 
137     void PostJsTask(std::function<void()>&& task, const std::string& name) override;
138 
139     const std::string& GetAppID() const override;
140     const std::string& GetAppName() const override;
141     const std::string& GetVersionName() const override;
142     int32_t GetVersionCode() const override;
GetWindowConfig()143     WindowConfig& GetWindowConfig()
144     {
145         return manifestParser_->GetWindowConfig();
146     }
147 
148     double MeasureText(MeasureContext context) override;
149     Size MeasureTextSize(MeasureContext context) override;
150 
151     void ShowToast(const NG::ToastInfo& toastInfo) override;
152     void ShowDialog(const std::string& title, const std::string& message,
153         const std::vector<ButtonInfo>& buttons, bool autoCancel, std::function<void(int32_t, int32_t)>&& callback,
154         const std::set<std::string>& callbacks) override;
155 
EnableAlertBeforeBackPage(const std::string & message,std::function<void (int32_t)> && callback)156     void EnableAlertBeforeBackPage(const std::string& message, std::function<void(int32_t)>&& callback) override {}
157 
DisableAlertBeforeBackPage()158     void DisableAlertBeforeBackPage() override {}
159 
ShowActionMenu(const std::string & title,const std::vector<ButtonInfo> & button,std::function<void (int32_t,int32_t)> && callback)160     void ShowActionMenu(const std::string& title, const std::vector<ButtonInfo>& button,
161         std::function<void(int32_t, int32_t)>&& callback) override {}
162 
163     Rect GetBoundingRectData(NodeId nodeId) override;
164 
165     std::string GetInspector(NodeId nodeId) override;
166 
167     void PushJsCallbackToRenderNode(NodeId id, double ratio, std::function<void(bool, double)>&& callback) override;
168     // For async event.
169     void SetCallBackResult(const std::string& callBackId, const std::string& result) override;
170 
171     void WaitTimer(const std::string& callbackId, const std::string& delay, bool isInterval, bool isFirst) override;
172     void ClearTimer(const std::string& callbackId) override;
173 
174     void PostSyncTaskToPage(std::function<void()>&& task, const std::string& name) override;
175     void AddTaskObserver(std::function<void()>&& task) override;
176     void RemoveTaskObserver() override;
177 
178     bool GetAssetContent(const std::string& url, std::string& content) override;
179     bool GetAssetContent(const std::string& url, std::vector<uint8_t>& content) override;
180     std::string GetAssetPath(const std::string& url) override;
181 
182     // i18n
183     void GetI18nData(std::unique_ptr<JsonValue>& json) override;
184 
185     void GetResourceConfiguration(std::unique_ptr<JsonValue>& json) override;
186 
187     void GetConfigurationCommon(const std::string& filePath, std::unique_ptr<JsonValue>& data) override;
188 
189     int32_t GetMinPlatformVersion() override;
190 
191     void LoadResourceConfiguration(std::map<std::string, std::string>& mediaResourceFileMap,
192         std::unique_ptr<JsonValue>& currentResourceData) override;
193 
194     void ChangeLocale(const std::string& language, const std::string& countryOrRegion) override;
195 
196     void RegisterFont(const std::string& familyName, const std::string& familySrc, const std::string& bundleName = "",
197         const std::string& moduleName = "") override;
198 
199     void GetSystemFontList(std::vector<std::string>& fontList) override;
200 
201     bool GetSystemFont(const std::string& fontName, FontInfo& fontInfo) override;
202 
203     void HandleImage(const std::string& src, std::function<void(bool, int32_t, int32_t)>&& callback) override;
204 
205     void RequestAnimationFrame(const std::string& callbackId) override;
206 
207     void CancelAnimationFrame(const std::string& callbackId) override;
208 
209     SingleTaskExecutor GetAnimationJsTask() override;
210 
211     SingleTaskExecutor GetUiTask() override;
212 
GetMediaQueryInfoInstance()213     const RefPtr<MediaQueryInfo>& GetMediaQueryInfoInstance() override
214     {
215         return mediaQueryInfo_;
216     }
217 
GetGroupJsBridge()218     const RefPtr<GroupJsBridge>& GetGroupJsBridge() override
219     {
220         return groupJsBridge_;
221     }
222 
223     RefPtr<PipelineBase> GetPipelineContext() override;
224 
SetGroupJsBridge(const RefPtr<GroupJsBridge> & groupJsBridge)225     void SetGroupJsBridge(const RefPtr<GroupJsBridge>& groupJsBridge)
226     {
227         groupJsBridge_ = groupJsBridge;
228     }
229 
230     RefPtr<JsAcePage> GetPage(int32_t pageId) const override;
231 
232     void RebuildAllPages();
233 
234     void UpdatePlugin(const std::string& content);
235 
SetDeclarativeOnUpdateWithValueParamsCallback(onPluginUpdateWithValueParams && callback)236     void SetDeclarativeOnUpdateWithValueParamsCallback(onPluginUpdateWithValueParams&& callback)
237     {
238         if (callback) {
239             onPluginUpdateWithValueParams_ = callback;
240         }
241     }
242 
FireDeclarativeOnUpdateWithValueParamsCallback(const std::string & params)243     void FireDeclarativeOnUpdateWithValueParamsCallback(const std::string& params) const
244     {
245         if (onPluginUpdateWithValueParams_) {
246             onPluginUpdateWithValueParams_(params);
247         }
248     }
249 
250 private:
251     int32_t GenerateNextPageId();
252     void RecyclePageId(int32_t pageId);
253 
254     UIContentErrorCode LoadPage(int32_t pageId, const PageTarget& target, bool isMainPage, const std::string& params);
255     void LoadJS(const RefPtr<Framework::JsAcePage>& page, const std::string& url, bool isMainPage);
256     void OnPageReady(
257         const RefPtr<Framework::JsAcePage>& page, const std::string& url, bool isMainPage);
258     void FlushPageCommand(
259         const RefPtr<Framework::JsAcePage>& page, const std::string& url, bool isMainPage);
260     void AddPageLocked(const RefPtr<JsAcePage>& page);
261     void OnPrePageChange(const RefPtr<JsAcePage>& page);
262     void SetCurrentPage(int32_t pageId);
263 
264     void OnPushPageSuccess(const RefPtr<JsAcePage>& page, const std::string& url);
265     void OnPopToPageSuccess(const std::string& url);
266     void PopToPage(const std::string& url);
267     int32_t OnPopPageSuccess();
268     void PopPage();
269 
270     void PopPageTransitionListener(const TransitionEvent& event, int32_t destroyPageId);
271 
272     void PopToPageTransitionListener(
273         const TransitionEvent& event, const std::string& url, int32_t pageId);
274 
275     int32_t OnClearInvisiblePagesSuccess();
276     void ClearInvisiblePages();
277 
278     void OnReplacePageSuccess(const RefPtr<JsAcePage>& page, const std::string& url);
279     void ReplacePage(const RefPtr<JsAcePage>& page, const std::string& url);
280     void LoadReplacePage(int32_t pageId, const PageTarget& url, const std::string& params);
281 
282     uint64_t GetSystemRealTime();
283 
284     // Page lifecycle
285     void OnPageShow();
286     void OnPageHide();
287     void OnPageDestroy(int32_t pageId);
288 
289     int32_t GetRunningPageId() const;
290     std::string GetRunningPageUrl() const;
291     int32_t GetPageIdByUrl(const std::string& url);
292 
293     void ResetStagingPage();
294     void FlushAnimationTasks();
295 
296     std::atomic<uint64_t> pageIdPool_ = 0;
297     int32_t callbackCnt_ = 0;
298     int32_t pageId_ = -1;
299     bool isRouteStackFull_ = false;
300     bool isStagingPageExist_ = false;
301     std::string mainPagePath_;
302     std::vector<PageInfo> pageRouteStack_;
303     std::unordered_map<int32_t, RefPtr<JsAcePage>> pageMap_;
304     std::unordered_map<int32_t, std::string> pageParamMap_;
305     std::unordered_map<int32_t, std::string> jsCallBackResult_;
306 
307     LoadJsCallback loadJs_;
308     JsMessageDispatcherSetterCallback dispatcherCallback_;
309     EventCallback asyncEvent_;
310     EventCallback syncEvent_;
311     UpdatePageCallback updatePage_;
312     ResetStagingPageCallback resetStagingPage_;
313     DestroyPageCallback destroyPage_;
314     DestroyApplicationCallback destroyApplication_;
315     UpdateApplicationStateCallback updateApplicationState_;
316     TimerCallback timer_;
317     std::unordered_map<std::string, CancelableCallback<void()>> timeoutTaskMap_;
318     MediaQueryCallback mediaQueryCallback_;
319     RequestAnimationCallback requestAnimationCallback_;
320     JsCallback jsCallback_;
321     OnWindowDisplayModeChangedCallBack onWindowDisplayModeChanged_;
322     OnConfigurationUpdatedCallBack onConfigurationUpdated_;
323     OnSaveAbilityStateCallBack onSaveAbilityState_;
324     OnRestoreAbilityStateCallBack onRestoreAbilityState_;
325     OnNewWantCallBack onNewWant_;
326     OnActiveCallBack onActive_;
327     OnInactiveCallBack onInactive_;
328     OnMemoryLevelCallBack onMemoryLevel_;
329     onPluginUpdateWithValueParams onPluginUpdateWithValueParams_;
330     OnStartContinuationCallBack onStartContinuationCallBack_;
331     OnCompleteContinuationCallBack onCompleteContinuationCallBack_;
332     OnRemoteTerminatedCallBack onRemoteTerminatedCallBack_;
333     OnSaveDataCallBack onSaveDataCallBack_;
334     OnRestoreDataCallBack onRestoreDataCallBack_;
335     RefPtr<Framework::ManifestParser> manifestParser_;
336     RefPtr<Framework::AccessibilityNodeManager> jsAccessibilityManager_;
337     RefPtr<MediaQueryInfo> mediaQueryInfo_;
338     RefPtr<GroupJsBridge> groupJsBridge_;
339 
340     RefPtr<TaskExecutor> taskExecutor_;
341 
342     PipelineContextHolder pipelineContextHolder_;
343 
344     BaseId::IdType pageTransitionListenerId_ = 0L;
345     std::queue<std::string> animationFrameTaskIds_;
346     std::unordered_map<std::string, CancelableCallback<void()>> animationFrameTaskMap_;
347 
348     mutable std::mutex mutex_;
349 };
350 } // namespace OHOS::Ace::Framework
351 #endif // FOUNDATION_ACE_FRAMEWORKS_BRIDGE_PLUGIN_FRONTEND_PLUGIN_FRONTEND_DELEGATE_H
352