• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023-2025 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 "core/components_ng/pattern/ui_extension/ui_extension_component/session_wrapper_impl.h"
17 
18 #include <cmath>
19 #include <memory>
20 
21 #include "accessibility_event_info.h"
22 #include "extension/extension_business_info.h"
23 #include "interfaces/include/ws_common.h"
24 #include "refbase.h"
25 #include "session_manager/include/extension_session_manager.h"
26 #include "transaction/rs_sync_transaction_controller.h"
27 #include "transaction/rs_transaction.h"
28 #include "ui/rs_surface_node.h"
29 #include "want_params.h"
30 #include "want_params_wrapper.h"
31 #include "wm/wm_common.h"
32 #include "wm/data_handler_interface.h"
33 
34 #include "adapter/ohos/entrance/ace_container.h"
35 #include "adapter/ohos/osal/want_wrap_ohos.h"
36 #include "base/error/error_code.h"
37 #include "base/utils/utils.h"
38 #include "core/common/container.h"
39 #include "core/common/container_scope.h"
40 #include "core/components_ng/pattern/ui_extension/session_wrapper.h"
41 #include "core/components_ng/pattern/window_scene/helper/window_scene_helper.h"
42 #include "core/components_ng/pattern/window_scene/scene/system_window_scene.h"
43 #include "core/pipeline_ng/pipeline_context.h"
44 
45 namespace OHOS::Ace::NG {
46 namespace {
47 // Defines all error names and messages.
48 constexpr char START_FAIL_NAME[] = "start_ability_fail";
49 constexpr char START_FAIL_MESSAGE[] = "Start ui extension ability failed, please check the want of UIextensionAbility.";
50 constexpr char BACKGROUND_FAIL_NAME[] = "background_fail";
51 constexpr char BACKGROUND_FAIL_MESSAGE[] = "background ui extension ability failed, please check AMS log.";
52 constexpr char TERMINATE_FAIL_NAME[] = "terminate_fail";
53 constexpr char TERMINATE_FAIL_MESSAGE[] = "terminate ui extension ability failed, please check AMS log.";
54 constexpr char PULL_FAIL_NAME[] = "extension_pulling_up_fail";
55 constexpr char PULL_FAIL_MESSAGE[] = "pulling another embedded component failed, not allowed to cascade.";
56 constexpr char EXIT_ABNORMALLY_NAME[] = "extension_exit_abnormally";
57 constexpr char EXIT_ABNORMALLY_MESSAGE[] = "the extension ability exited abnormally, please check AMS log.";
58 constexpr char EXTENSION_TRANSPARENT_NAME[] = "extension_node_transparent";
59 constexpr char EXTENSION_TRANSPARENT_MESSAGE[] = "the extension ability has transparent node.";
60 constexpr char LIFECYCLE_TIMEOUT_NAME[] = "extension_lifecycle_timeout";
61 constexpr char LIFECYCLE_TIMEOUT_MESSAGE[] = "the lifecycle of extension ability is timeout, please check AMS log.";
62 constexpr char EVENT_TIMEOUT_NAME[] = "handle_event_timeout";
63 constexpr char EVENT_TIMEOUT_MESSAGE[] = "the extension ability has timed out processing the key event.";
64 // Defines the want parameter to control the soft-keyboard area change of the provider.
65 constexpr char OCCUPIED_AREA_CHANGE_KEY[] = "ability.want.params.IsNotifyOccupiedAreaChange";
66 // Set the UIExtension type of the EmbeddedComponent.
67 constexpr char UI_EXTENSION_TYPE_KEY[] = "ability.want.params.uiExtensionType";
68 constexpr const char* const UIEXTENSION_CONFIG_FIELD = "ohos.system.window.uiextension.params";
69 const std::string EMBEDDED_UI("embeddedUI");
70 constexpr int32_t AVOID_DELAY_TIME = 30;
71 constexpr int32_t INVALID_WINDOW_ID = -1;
72 } // namespace
73 
74 class UIExtensionLifecycleListener : public Rosen::ILifecycleListener {
75 public:
UIExtensionLifecycleListener(const WeakPtr<SessionWrapper> & sessionWrapper)76     explicit UIExtensionLifecycleListener(const WeakPtr<SessionWrapper>& sessionWrapper)
77         : sessionWrapper_(sessionWrapper)
78     {}
79     virtual ~UIExtensionLifecycleListener() = default;
80 
OnActivation()81     void OnActivation() override {}
OnForeground()82     void OnForeground() override {}
OnBackground()83     void OnBackground() override {}
84 
OnConnect()85     void OnConnect() override
86     {
87         auto sessionWrapper = sessionWrapper_.Upgrade();
88         CHECK_NULL_VOID(sessionWrapper);
89         sessionWrapper->OnConnect();
90     }
91 
OnDisconnect()92     void OnDisconnect() override
93     {
94         auto sessionWrapper = sessionWrapper_.Upgrade();
95         CHECK_NULL_VOID(sessionWrapper);
96         sessionWrapper->OnDisconnect(false);
97     }
98 
OnExtensionDied()99     void OnExtensionDied() override
100     {
101         auto sessionWrapper = sessionWrapper_.Upgrade();
102         CHECK_NULL_VOID(sessionWrapper);
103         sessionWrapper->OnDisconnect(true);
104     }
105 
OnExtensionTimeout(int32_t errorCode)106     void OnExtensionTimeout(int32_t errorCode) override
107     {
108         auto sessionWrapper = sessionWrapper_.Upgrade();
109         CHECK_NULL_VOID(sessionWrapper);
110         sessionWrapper->OnExtensionTimeout(errorCode);
111     }
112 
OnExtensionDetachToDisplay()113     void OnExtensionDetachToDisplay() override
114     {
115         auto sessionWrapper = sessionWrapper_.Upgrade();
116         CHECK_NULL_VOID(sessionWrapper);
117         sessionWrapper->OnExtensionDetachToDisplay();
118     }
119 
OnAccessibilityEvent(const Accessibility::AccessibilityEventInfo & info,int64_t uiExtensionOffset)120     void OnAccessibilityEvent(const Accessibility::AccessibilityEventInfo& info, int64_t uiExtensionOffset) override
121     {
122         auto sessionWrapper = sessionWrapper_.Upgrade();
123         CHECK_NULL_VOID(sessionWrapper);
124         sessionWrapper->OnAccessibilityEvent(info, uiExtensionOffset);
125     }
126 
127 private:
128     WeakPtr<SessionWrapper> sessionWrapper_;
129 };
130 
131 /************************************************ Begin: Initialization ***********************************************/
SessionWrapperImpl(const WeakPtr<UIExtensionPattern> & hostPattern,int32_t instanceId,bool isTransferringCaller,SessionType sessionType)132 SessionWrapperImpl::SessionWrapperImpl(const WeakPtr<UIExtensionPattern>& hostPattern, int32_t instanceId,
133     bool isTransferringCaller, SessionType sessionType)
134     : hostPattern_(hostPattern), instanceId_(instanceId), isTransferringCaller_(isTransferringCaller),
135       sessionType_(sessionType)
136 {
137     auto pattern = hostPattern.Upgrade();
138     uiExtensionId_ = pattern ? pattern->GetUiExtensionId() : 0;
139     taskExecutor_ = Container::CurrentTaskExecutor();
140 }
141 
~SessionWrapperImpl()142 SessionWrapperImpl::~SessionWrapperImpl() {}
143 
InitForegroundCallback()144 void SessionWrapperImpl::InitForegroundCallback()
145 {
146     CHECK_NULL_VOID(session_);
147     CHECK_NULL_VOID(taskExecutor_);
148     int32_t callSessionId = GetSessionId();
149     foregroundCallback_ = [weakTaskExecutor = WeakClaim(RawPtr(taskExecutor_)),
150         weak = hostPattern_, callSessionId] (OHOS::Rosen::WSError errcode) {
151             if (errcode == OHOS::Rosen::WSError::WS_OK) {
152                 return;
153             }
154 
155             auto taskExecutor = weakTaskExecutor.Upgrade();
156             if (taskExecutor == nullptr) {
157                 TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
158                     "InitForegroundCallback: taskExecutor is nullptr");
159                     return;
160             }
161 
162             taskExecutor->PostTask(
163                 [weak, errcode, callSessionId] {
164                     auto pattern = weak.Upgrade();
165                     CHECK_NULL_VOID(pattern);
166                     if (callSessionId != pattern->GetSessionId()) {
167                         TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
168                             "foregroundCallback_: The callSessionId(%{public}d)"
169                                 " is inconsistent with the curSession(%{public}d)",
170                             callSessionId, pattern->GetSessionId());
171                             return;
172                     }
173 
174                     int32_t code = pattern->IsCompatibleOldVersion()
175                         ? static_cast<int32_t>(errcode) : ERROR_CODE_UIEXTENSION_FOREGROUND_FAILED;
176                     pattern->FireOnErrorCallback(code, START_FAIL_NAME, START_FAIL_MESSAGE);
177                 }, TaskExecutor::TaskType::UI, "ArkUIUIExtensionForegroundError");
178         };
179 }
180 
InitBackgroundCallback()181 void SessionWrapperImpl::InitBackgroundCallback()
182 {
183     CHECK_NULL_VOID(session_);
184     CHECK_NULL_VOID(taskExecutor_);
185     int32_t callSessionId = GetSessionId();
186     backgroundCallback_ = [weakTaskExecutor = WeakClaim(RawPtr(taskExecutor_)),
187         weak = hostPattern_, callSessionId] (OHOS::Rosen::WSError errcode) {
188             if (errcode == OHOS::Rosen::WSError::WS_OK) {
189                 return;
190             }
191 
192             auto taskExecutor = weakTaskExecutor.Upgrade();
193             if (taskExecutor == nullptr) {
194                 TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
195                     "InitBackgroundCallback: taskExecutor is nullptr");
196                     return;
197             }
198 
199             taskExecutor->PostTask(
200                 [weak, errcode, callSessionId] {
201                     auto pattern = weak.Upgrade();
202                     CHECK_NULL_VOID(pattern);
203                     if (callSessionId != pattern->GetSessionId()) {
204                         TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
205                             "backgroundCallback_: The callSessionId(%{public}d)"
206                                 " is inconsistent with the curSession(%{public}d)",
207                             callSessionId, pattern->GetSessionId());
208                             return;
209                     }
210 
211                     int32_t code = pattern->IsCompatibleOldVersion()
212                         ? static_cast<int32_t>(errcode) : ERROR_CODE_UIEXTENSION_BACKGROUND_FAILED;
213                     pattern->FireOnErrorCallback(
214                         code, BACKGROUND_FAIL_NAME, BACKGROUND_FAIL_MESSAGE);
215                 }, TaskExecutor::TaskType::UI, "ArkUIUIExtensionBackgroundError");
216         };
217 }
218 
InitDestructionCallback()219 void SessionWrapperImpl::InitDestructionCallback()
220 {
221     CHECK_NULL_VOID(session_);
222     CHECK_NULL_VOID(taskExecutor_);
223     int32_t callSessionId = GetSessionId();
224     destructionCallback_ = [weakTaskExecutor = WeakClaim(RawPtr(taskExecutor_)),
225         weak = hostPattern_, callSessionId] (OHOS::Rosen::WSError errcode) {
226             if (errcode == OHOS::Rosen::WSError::WS_OK) {
227                 return;
228             }
229 
230             auto taskExecutor = weakTaskExecutor.Upgrade();
231             if (taskExecutor == nullptr) {
232                 TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
233                     "InitDestructionCallback: taskExecutor is nullptr");
234                     return;
235             }
236 
237             taskExecutor->PostTask(
238                 [weak, errcode, callSessionId] {
239                     auto pattern = weak.Upgrade();
240                     CHECK_NULL_VOID(pattern);
241                     if (callSessionId != pattern->GetSessionId()) {
242                         TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
243                             "destructionCallback_: The callSessionId(%{public}d)"
244                                 " is inconsistent with the curSession(%{public}d)",
245                             callSessionId, pattern->GetSessionId());
246                             return;
247                     }
248 
249                     int32_t code = pattern->IsCompatibleOldVersion()
250                         ? static_cast<int32_t>(errcode) : ERROR_CODE_UIEXTENSION_DESTRUCTION_FAILED;
251                     pattern->FireOnErrorCallback(
252                         code, TERMINATE_FAIL_NAME, TERMINATE_FAIL_MESSAGE);
253                 }, TaskExecutor::TaskType::UI, "ArkUIUIExtensionDestructionError");
254         };
255 }
256 
InitTransferAbilityResultFunc()257 void SessionWrapperImpl::InitTransferAbilityResultFunc()
258 {
259     CHECK_NULL_VOID(session_);
260     CHECK_NULL_VOID(taskExecutor_);
261     auto sessionCallbacks = session_->GetExtensionSessionEventCallback();
262     if (sessionCallbacks == nullptr) {
263         TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
264             "InitTransferAbilityResultFunc: sessionCallbacks is nullptr");
265         return;
266     }
267 
268     int32_t callSessionId = GetSessionId();
269     sessionCallbacks->transferAbilityResultFunc_ = [weakTaskExecutor = WeakClaim(RawPtr(taskExecutor_)),
270         weak = hostPattern_, sessionType = sessionType_, callSessionId] (
271             int32_t code, const AAFwk::Want& want) {
272                 auto taskExecutor = weakTaskExecutor.Upgrade();
273                 if (taskExecutor == nullptr) {
274                     TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
275                         "InitTransferAbilityResultFunc: taskExecutor is nullptr");
276                         return;
277                 }
278 
279                 taskExecutor->PostTask(
280                     [weak, code, want, sessionType, callSessionId] () {
281                         auto pattern = weak.Upgrade();
282                         CHECK_NULL_VOID(pattern);
283                         if (callSessionId != pattern->GetSessionId()) {
284                             TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
285                                 "transferAbilityResultFunc_: The callSessionId(%{public}d)"
286                                     " is inconsistent with the curSession(%{public}d)",
287                                 callSessionId, pattern->GetSessionId());
288                                 return;
289                         }
290 
291                         if (sessionType == SessionType::UI_EXTENSION_ABILITY
292                             && pattern->IsCompatibleOldVersion()) {
293                             pattern->FireOnResultCallback(code, want);
294                         } else {
295                             pattern->FireOnTerminatedCallback(code, MakeRefPtr<WantWrapOhos>(want));
296                         }
297                     }, TaskExecutor::TaskType::UI, "ArkUIUIExtensionTransferAbilityResult");
298             };
299 }
300 
InitTransferExtensionDataFunc()301 void SessionWrapperImpl::InitTransferExtensionDataFunc()
302 {
303     CHECK_NULL_VOID(session_);
304     CHECK_NULL_VOID(taskExecutor_);
305     auto sessionCallbacks = session_->GetExtensionSessionEventCallback();
306     if (sessionCallbacks == nullptr) {
307         TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
308             "InitTransferExtensionDataFunc: sessionCallbacks is nullptr");
309         return;
310     }
311 
312     int32_t callSessionId = GetSessionId();
313     sessionCallbacks->transferExtensionDataFunc_ = [weakTaskExecutor = WeakClaim(RawPtr(taskExecutor_)),
314         weak = hostPattern_, callSessionId] (const AAFwk::WantParams& params) {
315             auto taskExecutor = weakTaskExecutor.Upgrade();
316             if (taskExecutor == nullptr) {
317                 TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
318                     "InitTransferExtensionDataFunc: taskExecutor is nullptr");
319                     return;
320             }
321 
322             taskExecutor->PostTask(
323                 [weak, params, callSessionId] () {
324                     auto pattern = weak.Upgrade();
325                     CHECK_NULL_VOID(pattern);
326                     if (callSessionId != pattern->GetSessionId()) {
327                         TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
328                             "transferExtensionDataFunc_: The callSessionId(%{public}d)"
329                                 " is inconsistent with the curSession(%{public}d)",
330                             callSessionId, pattern->GetSessionId());
331                             return;
332                     }
333 
334                     pattern->FireOnReceiveCallback(params);
335                 }, TaskExecutor::TaskType::UI, "ArkUIUIExtensionReceiveCallback");
336         };
337 }
338 
InitNotifyRemoteReadyFunc()339 void SessionWrapperImpl::InitNotifyRemoteReadyFunc()
340 {
341     CHECK_NULL_VOID(session_);
342     CHECK_NULL_VOID(taskExecutor_);
343     auto sessionCallbacks = session_->GetExtensionSessionEventCallback();
344     if (sessionCallbacks == nullptr) {
345         TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
346             "InitNotifyRemoteReadyFunc: sessionCallbacks is nullptr");
347         return;
348     }
349 
350     int32_t callSessionId = GetSessionId();
351     sessionCallbacks->notifyRemoteReadyFunc_ = [weakTaskExecutor = WeakClaim(RawPtr(taskExecutor_)),
352         weak = hostPattern_, callSessionId] () {
353             auto taskExecutor = weakTaskExecutor.Upgrade();
354             if (taskExecutor == nullptr) {
355                 TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
356                     "InitNotifyRemoteReadyFunc: taskExecutor is nullptr");
357                     return;
358             }
359 
360             taskExecutor->PostTask(
361                 [weak, callSessionId] () {
362                     auto pattern = weak.Upgrade();
363                     CHECK_NULL_VOID(pattern);
364                     if (callSessionId != pattern->GetSessionId()) {
365                         TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
366                             "notifyRemoteReadyFunc_: The callSessionId(%{public}d)"
367                                 " is inconsistent with the curSession(%{public}d)",
368                             callSessionId, pattern->GetSessionId());
369                             return;
370                     }
371 
372                     pattern->FireOnRemoteReadyCallback();
373                 }, TaskExecutor::TaskType::UI, "ArkUIUIExtensionRemoteReadyCallback");
374         };
375 }
376 
InitNotifySyncOnFunc()377 void SessionWrapperImpl::InitNotifySyncOnFunc()
378 {
379     CHECK_NULL_VOID(session_);
380     CHECK_NULL_VOID(taskExecutor_);
381     auto sessionCallbacks = session_->GetExtensionSessionEventCallback();
382     if (sessionCallbacks == nullptr) {
383         TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
384             "InitNotifySyncOnFunc: sessionCallbacks is nullptr");
385         return;
386     }
387 
388     int32_t callSessionId = GetSessionId();
389     sessionCallbacks->notifySyncOnFunc_ = [weakTaskExecutor = WeakClaim(RawPtr(taskExecutor_)),
390         weak = hostPattern_, callSessionId] () {
391             auto taskExecutor = weakTaskExecutor.Upgrade();
392             if (taskExecutor == nullptr) {
393                 TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
394                     "InitNotifySyncOnFunc: taskExecutor is nullptr");
395                     return;
396             }
397 
398             taskExecutor->PostTask(
399                 [weak, callSessionId] () {
400                     auto pattern = weak.Upgrade();
401                     CHECK_NULL_VOID(pattern);
402                     if (callSessionId != pattern->GetSessionId()) {
403                         TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
404                             "notifySyncOnFunc_: The callSessionId(%{public}d)"
405                                 " is inconsistent with the curSession(%{public}d)",
406                             callSessionId, pattern->GetSessionId());
407                             return;
408                     }
409 
410                     pattern->FireSyncCallbacks();
411                 }, TaskExecutor::TaskType::UI, "ArkUIUIExtensionSyncCallbacks");
412         };
413 }
414 
InitNotifyAsyncOnFunc()415 void SessionWrapperImpl::InitNotifyAsyncOnFunc()
416 {
417     CHECK_NULL_VOID(session_);
418     CHECK_NULL_VOID(taskExecutor_);
419     auto sessionCallbacks = session_->GetExtensionSessionEventCallback();
420     if (sessionCallbacks == nullptr) {
421         TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
422             "InitNotifyAsyncOnFunc: sessionCallbacks is nullptr");
423         return;
424     }
425 
426     int32_t callSessionId = GetSessionId();
427     sessionCallbacks->notifyAsyncOnFunc_ = [weakTaskExecutor = WeakClaim(RawPtr(taskExecutor_)),
428         weak = hostPattern_, callSessionId] () {
429             auto taskExecutor = weakTaskExecutor.Upgrade();
430             if (taskExecutor == nullptr) {
431                 TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
432                     "InitNotifyAsyncOnFunc: taskExecutor is nullptr");
433                     return;
434             }
435 
436             taskExecutor->PostTask(
437                 [weak, callSessionId] () {
438                     auto pattern = weak.Upgrade();
439                     CHECK_NULL_VOID(pattern);
440                     if (callSessionId != pattern->GetSessionId()) {
441                         TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
442                             "notifyAsyncOnFunc_: The callSessionId(%{public}d)"
443                                 " is inconsistent with the curSession(%{public}d)",
444                             callSessionId, pattern->GetSessionId());
445                             return;
446                     }
447                     pattern->FireAsyncCallbacks();
448                 }, TaskExecutor::TaskType::UI, "ArkUIUIExtensionAsyncCallbacks");
449         };
450 }
451 
InitNotifyBindModalFunc()452 void SessionWrapperImpl::InitNotifyBindModalFunc()
453 {
454     CHECK_NULL_VOID(session_);
455     CHECK_NULL_VOID(taskExecutor_);
456     auto sessionCallbacks = session_->GetExtensionSessionEventCallback();
457     if (sessionCallbacks == nullptr) {
458         TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
459             "InitNotifyBindModalFunc: sessionCallbacks is nullptr");
460         return;
461     }
462 
463     int32_t callSessionId = GetSessionId();
464     sessionCallbacks->notifyBindModalFunc_ = [weakTaskExecutor = WeakClaim(RawPtr(taskExecutor_)),
465         weak = hostPattern_, callSessionId] () {
466             auto taskExecutor = weakTaskExecutor.Upgrade();
467             if (taskExecutor == nullptr) {
468                 TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
469                     "InitNotifyBindModalFunc: taskExecutor is nullptr");
470                     return;
471             }
472 
473             taskExecutor->PostSyncTask(
474                 [weak, callSessionId] () {
475                     auto pattern = weak.Upgrade();
476                     CHECK_NULL_VOID(pattern);
477                     if (callSessionId != pattern->GetSessionId()) {
478                         TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
479                             "notifyBindModalFunc_: The callSessionId(%{public}d)"
480                                 " is inconsistent with the curSession(%{public}d)",
481                             callSessionId, pattern->GetSessionId());
482                             return;
483                     }
484 
485                     pattern->FireBindModalCallback();
486                 }, TaskExecutor::TaskType::UI, "ArkUIUIExtensionBindModalCallback");
487         };
488 }
489 
InitNotifyGetAvoidAreaByTypeFunc()490 void SessionWrapperImpl::InitNotifyGetAvoidAreaByTypeFunc()
491 {
492     CHECK_NULL_VOID(session_);
493     auto sessionCallbacks = session_->GetExtensionSessionEventCallback();
494     if (sessionCallbacks == nullptr) {
495         TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
496             "InitNotifyGetAvoidAreaByTypeFunc: sessionCallbacks is nullptr");
497         return;
498     }
499 
500     sessionCallbacks->notifyGetAvoidAreaByTypeFunc_ =
501         [instanceId = instanceId_] (Rosen::AvoidAreaType type, int32_t apiVersion) -> Rosen::AvoidArea {
502             Rosen::AvoidArea avoidArea;
503             auto container = Platform::AceContainer::GetContainer(instanceId);
504             CHECK_NULL_RETURN(container, avoidArea);
505             avoidArea = container->GetAvoidAreaByType(type, apiVersion);
506             return avoidArea;
507         };
508 }
509 
InitNotifyExtensionEventFunc()510 void SessionWrapperImpl::InitNotifyExtensionEventFunc()
511 {
512     CHECK_NULL_VOID(session_);
513     CHECK_NULL_VOID(taskExecutor_);
514     auto sessionCallbacks = session_->GetExtensionSessionEventCallback();
515     if (sessionCallbacks == nullptr) {
516         TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
517             "InitNotifyExtensionEventFunc: sessionCallbacks is nullptr");
518         return;
519     }
520 
521     int32_t callSessionId = GetSessionId();
522     sessionCallbacks->notifyExtensionEventFunc_ = [weakTaskExecutor = WeakClaim(RawPtr(taskExecutor_)),
523         weak = hostPattern_, callSessionId] (uint32_t eventId) {
524             auto taskExecutor = weakTaskExecutor.Upgrade();
525             if (taskExecutor == nullptr) {
526                 TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
527                     "InitNotifyExtensionEventFunc: taskExecutor is nullptr");
528                     return;
529             }
530 
531             taskExecutor->PostTask(
532                 [weak, callSessionId, eventId] () {
533                     auto pattern = weak.Upgrade();
534                     CHECK_NULL_VOID(pattern);
535                     if (callSessionId != pattern->GetSessionId()) {
536                         TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
537                             "notifyBindModalFunc_: The callSessionId(%{public}d)"
538                                 " is inconsistent with the curSession(%{public}d)",
539                             callSessionId, pattern->GetSessionId());
540                             return;
541                     }
542 
543                     pattern->OnExtensionEvent(static_cast<UIExtCallbackEventId>(eventId));
544                 }, TaskExecutor::TaskType::UI, "ArkUIUIExtensionEventCallback");
545         };
546 }
547 
InitGetStatusBarHeightFunc()548 void SessionWrapperImpl::InitGetStatusBarHeightFunc()
549 {
550     CHECK_NULL_VOID(session_);
551     auto sessionCallbacks = session_->GetExtensionSessionEventCallback();
552     if (sessionCallbacks == nullptr) {
553         TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
554             "InitGetStatusBarHeightFunc: sessionCallbacks is nullptr");
555         return;
556     }
557 
558     sessionCallbacks->getStatusBarHeightFunc_ = [instanceId = instanceId_]() -> uint32_t {
559         auto container = Platform::AceContainer::GetContainer(instanceId);
560         CHECK_NULL_RETURN(container, 0);
561         return container->GetStatusBarHeight();
562     };
563 }
564 
InitAllCallback()565 void SessionWrapperImpl::InitAllCallback()
566 {
567     CHECK_NULL_VOID(session_);
568     int32_t callSessionId = GetSessionId();
569     if (!taskExecutor_) {
570         LOGE("taskExecutor_ is nullptr, the sessionid = %{public}d", callSessionId);
571         return;
572     }
573 
574     InitForegroundCallback();
575     InitBackgroundCallback();
576     InitDestructionCallback();
577 
578     // Init SessionEventCallback
579     auto sessionCallbacks = session_->GetExtensionSessionEventCallback();
580     if (sessionCallbacks == nullptr) {
581         TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
582             "InitAllCallback: sessionCallbacks is nullptr");
583         return;
584     }
585 
586     InitTransferAbilityResultFunc();
587     InitTransferExtensionDataFunc();
588     InitNotifyRemoteReadyFunc();
589     InitNotifySyncOnFunc();
590     InitNotifyAsyncOnFunc();
591     InitNotifyBindModalFunc();
592     InitNotifyGetAvoidAreaByTypeFunc();
593     InitNotifyExtensionEventFunc();
594     InitGetStatusBarHeightFunc();
595 }
596 
UpdateInstanceId(int32_t instanceId)597 void SessionWrapperImpl::UpdateInstanceId(int32_t instanceId)
598 {
599     if (instanceId_ == instanceId) {
600         UIEXT_LOGW("InstanceId(%{public}d) has not changed when UpdateInstanceId.", instanceId);
601         return;
602     }
603 
604     UIEXT_LOGI("Update instanceId %{public}d to %{public}d.", instanceId_, instanceId);
605     auto container = Container::GetContainer(instanceId);
606     CHECK_NULL_VOID(container);
607     auto taskExecutor = container->GetTaskExecutor();
608     CHECK_NULL_VOID(taskExecutor);
609     instanceId_ = instanceId;
610     taskExecutor_ = taskExecutor;
611     InitAllCallback();
612     UIEXT_LOGI("Update instanceId success.");
613 }
614 /************************************************ End: Initialization *************************************************/
615 
616 /************************************************ Begin: About session ************************************************/
ConvertToRosenSessionViewportConfig(const SessionViewportConfig & config)617 Rosen::SessionViewportConfig ConvertToRosenSessionViewportConfig(const SessionViewportConfig& config)
618 {
619     Rosen::SessionViewportConfig config_ = {
620         .isDensityFollowHost_ = config.isDensityFollowHost_,
621         .density_ = config.density_,
622         .displayId_ = config.displayId_,
623         .orientation_ = config.orientation_,
624         .transform_ = config.transform_,
625     };
626     return config_;
627 }
628 
CreateSession(const AAFwk::Want & want,const SessionConfig & config)629 void SessionWrapperImpl::CreateSession(const AAFwk::Want& want, const SessionConfig& config)
630 {
631     ContainerScope scope(instanceId_);
632     UIEXT_LOGI("The session is created with bundle=%{public}s, ability=%{public}s, componentId=%{public}d.",
633         want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), GetFrameNodeId());
634     auto container = Platform::AceContainer::GetContainer(instanceId_);
635     CHECK_NULL_VOID(container);
636     auto pipeline = container->GetPipelineContext();
637     CHECK_NULL_VOID(pipeline);
638     auto realHostWindowId = pipeline->GetRealHostWindowId();
639     customWant_ = std::make_shared<Want>(want);
640     auto wantPtr = std::make_shared<Want>(want);
641     UpdateWantPtr(wantPtr);
642     if (sessionType_ == SessionType::UI_EXTENSION_ABILITY) {
643         if (wantPtr->GetStringParam(UI_EXTENSION_TYPE_KEY) == EMBEDDED_UI) {
644             UIEXT_LOGE("The UIExtensionComponent is not allowed to start the EmbeddedUIExtensionAbility.");
645             return;
646         }
647         if ((container->IsUIExtensionAbilityHost() && container->IsUIExtensionSubWindow())) {
648             UIEXT_LOGE("The UIExtensionComponent does not allow nested pulling of another.");
649             auto pattern = hostPattern_.Upgrade();
650             CHECK_NULL_VOID(pattern);
651             pattern->FireOnErrorCallback(ERROR_CODE_UIEXTENSION_FORBID_CASCADE, PULL_FAIL_NAME, PULL_FAIL_MESSAGE);
652             return;
653         }
654     }
655     if (sessionType_ == SessionType::EMBEDDED_UI_EXTENSION) {
656         if ((container->IsUIExtensionWindow()) ||
657             (container->IsUIExtensionAbilityProcess() && container->IsUIExtensionSubWindow())) {
658             UIEXT_LOGE("The EmbeddedComponent does not allow nested pulling of another.");
659             auto pattern = hostPattern_.Upgrade();
660             CHECK_NULL_VOID(pattern);
661             pattern->FireOnErrorCallback(ERROR_CODE_UIEXTENSION_FORBID_CASCADE, PULL_FAIL_NAME, PULL_FAIL_MESSAGE);
662             return;
663         }
664         WantParams wantParams;
665         wantPtr->SetParam(UI_EXTENSION_TYPE_KEY, EMBEDDED_UI);
666     }
667     isNotifyOccupiedAreaChange_ = want.GetBoolParam(OCCUPIED_AREA_CHANGE_KEY, true);
668     uint32_t parentWindowType = 0;
669     if (container->IsUIExtensionWindow()) {
670         parentWindowType = container->GetParentWindowType();
671     } else {
672         parentWindowType = container->GetWindowType();
673     }
674     UIEXT_LOGI("Want param isNotifyOccupiedAreaChange is %{public}d, realHostWindowId: %{public}u,"
675         " parentWindowType: %{public}u",
676         isNotifyOccupiedAreaChange_, realHostWindowId, parentWindowType);
677     auto callerToken = container->GetToken();
678     auto parentToken = container->GetParentToken();
679     auto context = PipelineContext::GetCurrentContext();
680     CHECK_NULL_VOID(context);
681     auto pattern = hostPattern_.Upgrade();
682     CHECK_NULL_VOID(pattern);
683     SessionViewportConfig sessionViewportConfig;
684     sessionViewportConfig.isDensityFollowHost_ = pattern->GetDensityDpi();
685     sessionViewportConfig.density_ = context->GetCurrentDensity();
686     sessionViewportConfig.displayId_ = container->GetCurrentDisplayId();
687     sessionViewportConfig.orientation_ = static_cast<int32_t>(SystemProperties::GetDeviceOrientation());
688     sessionViewportConfig.transform_ = context->GetTransformHint();
689     pattern->SetSessionViewportConfig(sessionViewportConfig);
690     Rosen::SessionInfo extensionSessionInfo;
691     extensionSessionInfo.bundleName_ = want.GetElement().GetBundleName();
692     extensionSessionInfo.abilityName_ = want.GetElement().GetAbilityName();
693     extensionSessionInfo.callerToken_ = callerToken;
694     extensionSessionInfo.rootToken_ = (isTransferringCaller_ && parentToken) ? parentToken : callerToken;
695     extensionSessionInfo.want = wantPtr;
696     extensionSessionInfo.parentWindowType_ = parentWindowType;
697     extensionSessionInfo.realParentId_ = static_cast<int32_t>(realHostWindowId);
698     extensionSessionInfo.uiExtensionUsage_ = static_cast<uint32_t>(config.uiExtensionUsage);
699     extensionSessionInfo.isAsyncModalBinding_ = config.isAsyncModalBinding;
700     extensionSessionInfo.config_ = ConvertToRosenSessionViewportConfig(sessionViewportConfig);
701     session_ = Rosen::ExtensionSessionManager::GetInstance().RequestExtensionSession(extensionSessionInfo);
702     CHECK_NULL_VOID(session_);
703     UpdateSessionConfig();
704     lifecycleListener_ = std::make_shared<UIExtensionLifecycleListener>(AceType::WeakClaim(this));
705     session_->RegisterLifecycleListener(lifecycleListener_);
706     InitAllCallback();
707     RegisterDataConsumer();
708 }
709 
UpdateSessionConfig()710 void SessionWrapperImpl::UpdateSessionConfig()
711 {
712     auto extConfig = session_->GetSystemConfig();
713     auto pipeline = PipelineBase::GetCurrentContext();
714     CHECK_NULL_VOID(pipeline);
715     auto hostConfig = pipeline->GetKeyboardAnimationConfig();
716     extConfig.animationIn_ = {
717         hostConfig.curveIn_.curveType_, hostConfig.curveIn_.curveParams_, hostConfig.curveIn_.duration_};
718     extConfig.animationOut_ = {
719         hostConfig.curveOut_.curveType_, hostConfig.curveOut_.curveParams_, hostConfig.curveOut_.duration_};
720     session_->SetSystemConfig(extConfig);
721 }
722 
DestroySession()723 void SessionWrapperImpl::DestroySession()
724 {
725     CHECK_NULL_VOID(session_);
726     UIEXT_LOGI("DestroySession, persistentid=%{public}d, componentId=%{public}d.",
727         session_->GetPersistentId(), GetFrameNodeId());
728     session_->UnregisterLifecycleListener(lifecycleListener_);
729     auto dataHandler = session_->GetExtensionDataHandler();
730     if (dataHandler) {
731         dataHandler->UnregisterDataConsumer(subSystemId_);
732     }
733     customWant_ = nullptr;
734     session_ = nullptr;
735 }
736 
UpdateWantPtr(std::shared_ptr<AAFwk::Want> & wantPtr)737 void SessionWrapperImpl::UpdateWantPtr(std::shared_ptr<AAFwk::Want>& wantPtr)
738 {
739     CHECK_NULL_VOID(wantPtr);
740     AAFwk::WantParams configParam;
741     auto container = Platform::AceContainer::GetContainer(GetInstanceIdFromHost());
742     CHECK_NULL_VOID(container);
743     container->GetExtensionConfig(configParam);
744     AAFwk::WantParams wantParam(wantPtr->GetParams());
745     wantParam.SetParam(UIEXTENSION_CONFIG_FIELD, AAFwk::WantParamWrapper::Box(configParam));
746     wantPtr->SetParams(wantParam);
747 }
748 
IsSessionValid()749 bool SessionWrapperImpl::IsSessionValid()
750 {
751     return session_ != nullptr;
752 }
753 
GetSessionId() const754 int32_t SessionWrapperImpl::GetSessionId() const
755 {
756     return session_ ? session_->GetPersistentId() : 0;
757 }
758 
GetInstanceIdFromHost() const759 int32_t SessionWrapperImpl::GetInstanceIdFromHost() const
760 {
761     auto pattern = hostPattern_.Upgrade();
762     if (pattern == nullptr) {
763         UIEXT_LOGW("UIExtension pattern is null, session wrapper get instanceId from host return fail.");
764         return INSTANCE_ID_UNDEFINED;
765     }
766     auto instanceId = pattern->GetInstanceIdFromHost();
767     if (instanceId != instanceId_) {
768         UIEXT_LOGW("SessionWrapper instanceId %{public}d not equal frame node instanceId %{public}d",
769             instanceId_, instanceId);
770     }
771     return instanceId;
772 }
773 
GetWant()774 const std::shared_ptr<AAFwk::Want> SessionWrapperImpl::GetWant()
775 {
776     return session_ ? customWant_ : nullptr;
777 }
778 /************************************************ End: About session **************************************************/
779 
780 /************************************************ Begin: Synchronous interface for event notify ***********************/
NotifyFocusEventSync(bool isFocus)781 bool SessionWrapperImpl::NotifyFocusEventSync(bool isFocus)
782 {
783     return false;
784 }
NotifyFocusStateSync(bool focusState)785 bool SessionWrapperImpl::NotifyFocusStateSync(bool focusState)
786 {
787     return false;
788 }
789 
NotifyBackPressedSync()790 bool SessionWrapperImpl::NotifyBackPressedSync()
791 {
792     CHECK_NULL_RETURN(session_, false);
793     bool isConsumed = false;
794     session_->TransferBackPressedEventForConsumed(isConsumed);
795     UIEXT_LOGI("Back event notified to uiextension, persistentid=%{public}d and %{public}s consumed,"
796         " componentId=%{public}d.", GetSessionId(), isConsumed ? "is" : "is not", GetFrameNodeId());
797     return isConsumed;
798 }
799 
NotifyPointerEventSync(const std::shared_ptr<OHOS::MMI::PointerEvent> & pointerEvent)800 bool SessionWrapperImpl::NotifyPointerEventSync(const std::shared_ptr<OHOS::MMI::PointerEvent>& pointerEvent)
801 {
802     return false;
803 }
804 
NotifyKeyEventSync(const std::shared_ptr<OHOS::MMI::KeyEvent> & keyEvent,bool isPreIme)805 bool SessionWrapperImpl::NotifyKeyEventSync(const std::shared_ptr<OHOS::MMI::KeyEvent>& keyEvent, bool isPreIme)
806 {
807     CHECK_NULL_RETURN(session_, false);
808     bool isConsumed = false;
809     bool isTimeout = false;
810     session_->TransferKeyEventForConsumed(keyEvent, isConsumed, isTimeout, isPreIme);
811     auto pattern = hostPattern_.Upgrade();
812     if (isTimeout && pattern) {
813         pattern->FireOnErrorCallback(ERROR_CODE_UIEXTENSION_EVENT_TIMEOUT, EVENT_TIMEOUT_NAME, EVENT_TIMEOUT_MESSAGE);
814         return false;
815     }
816     UIEXT_LOGI("Key event notified to uiextension, persistentid = %{public}d and %{public}s consumed,"
817         " componentId=%{public}d.", GetSessionId(), isConsumed ? "is" : "is not", GetFrameNodeId());
818     return isConsumed;
819 }
820 
NotifyKeyEventAsync(const std::shared_ptr<OHOS::MMI::KeyEvent> & keyEvent,bool isPreIme)821 bool SessionWrapperImpl::NotifyKeyEventAsync(const std::shared_ptr<OHOS::MMI::KeyEvent>& keyEvent, bool isPreIme)
822 {
823     CHECK_NULL_RETURN(session_, false);
824     session_->TransferKeyEventAsync(keyEvent, isPreIme);
825     return true;
826 }
827 
NotifyAxisEventSync(const std::shared_ptr<OHOS::MMI::AxisEvent> & axisEvent)828 bool SessionWrapperImpl::NotifyAxisEventSync(const std::shared_ptr<OHOS::MMI::AxisEvent>& axisEvent)
829 {
830     return false;
831 }
832 /************************************************ End: Synchronous interface for event notify *************************/
833 
834 /************************************************ Begin: Asynchronous interface for event notify **********************/
NotifyFocusEventAsync(bool isFocus)835 bool SessionWrapperImpl::NotifyFocusEventAsync(bool isFocus)
836 {
837     CHECK_NULL_RETURN(session_, false);
838     UIEXT_LOGI("Notify uiextension, persistentid = %{public}d to %{public}s the focus state,"
839         " componentId=%{public}d.", GetSessionId(), isFocus ? "paint" : "clear", GetFrameNodeId());
840     session_->TransferFocusActiveEvent(isFocus);
841     return true;
842 }
843 
NotifyFocusStateAsync(bool focusState)844 bool SessionWrapperImpl::NotifyFocusStateAsync(bool focusState)
845 {
846     CHECK_NULL_RETURN(session_, false);
847     UIEXT_LOGI("%{public}s state notified to uiextension, persistentid = %{public}d,"
848         " componentId=%{public}d.", focusState ? "focused" : "unfocused", GetSessionId(), GetFrameNodeId());
849     session_->TransferFocusStateEvent(focusState);
850     return true;
851 }
852 
NotifyBackPressedAsync()853 bool SessionWrapperImpl::NotifyBackPressedAsync()
854 {
855     return false;
856 }
NotifyPointerEventAsync(const std::shared_ptr<OHOS::MMI::PointerEvent> & pointerEvent)857 bool SessionWrapperImpl::NotifyPointerEventAsync(const std::shared_ptr<OHOS::MMI::PointerEvent>& pointerEvent)
858 {
859     if (session_ && pointerEvent) {
860         UIEXT_LOGI("Transfer pointer event with 'id = %{public}d' to uiextension, persistentid = %{public}d,"
861             " componentId=%{public}d.", pointerEvent->GetId(), GetSessionId(), GetFrameNodeId());
862         session_->TransferPointerEvent(pointerEvent);
863     }
864     return false;
865 }
NotifyKeyEventAsync(const std::shared_ptr<OHOS::MMI::KeyEvent> & keyEvent)866 bool SessionWrapperImpl::NotifyKeyEventAsync(const std::shared_ptr<OHOS::MMI::KeyEvent>& keyEvent)
867 {
868     if (session_ && keyEvent) {
869         UIEXT_LOGI("Transfer key event with 'id = %{public}d' to uiextension, persistentid = %{public}d,"
870             " componentId=%{public}d.", keyEvent->GetId(), GetSessionId(), GetFrameNodeId());
871         session_->TransferKeyEvent(keyEvent);
872     }
873     return false;
874 }
NotifyAxisEventAsync(const std::shared_ptr<OHOS::MMI::AxisEvent> & axisEvent)875 bool SessionWrapperImpl::NotifyAxisEventAsync(const std::shared_ptr<OHOS::MMI::AxisEvent>& axisEvent)
876 {
877     return false;
878 }
879 /************************************************ End: Asynchronous interface for event notify ************************/
880 
881 /************************************************ Begin: The lifecycle interface **************************************/
NotifyCreate()882 void SessionWrapperImpl::NotifyCreate() {}
883 
GetWindowScene()884 RefPtr<SystemWindowScene> SessionWrapperImpl::GetWindowScene()
885 {
886     RefPtr<SystemWindowScene> hostPattern = nullptr;
887     auto pattern = hostPattern_.Upgrade();
888     CHECK_NULL_RETURN(pattern, hostPattern);
889     auto hostWindowNode = WindowSceneHelper::FindWindowScene(pattern->GetHost());
890     CHECK_NULL_RETURN(hostWindowNode, hostPattern);
891     auto hostNode = AceType::DynamicCast<FrameNode>(hostWindowNode);
892     CHECK_NULL_RETURN(hostNode, hostPattern);
893     hostPattern = hostNode->GetPattern<SystemWindowScene>();
894     return hostPattern;
895 }
896 
GetWindowSceneId()897 int32_t SessionWrapperImpl::GetWindowSceneId()
898 {
899     auto pattern = hostPattern_.Upgrade();
900     CHECK_NULL_RETURN(pattern, INVALID_WINDOW_ID);
901     auto hostPattern = GetWindowScene();
902     CHECK_NULL_RETURN(hostPattern, INVALID_WINDOW_ID);
903     auto hostSession = hostPattern->GetSession();
904     CHECK_NULL_RETURN(hostSession, INVALID_WINDOW_ID);
905     int32_t windowSceneId = hostSession->GetPersistentId();
906     if (windowSceneId != INVALID_WINDOW_ID) {
907         pattern->RegisterWindowSceneVisibleChangeCallback(hostPattern);
908     }
909     return windowSceneId;
910 }
911 
GetWindowSceneRect()912 Rosen::WSRect SessionWrapperImpl::GetWindowSceneRect()
913 {
914     Rosen::WSRect rect = {0, 0, 0, 0};
915     auto hostPattern = GetWindowScene();
916     CHECK_NULL_RETURN(hostPattern, rect);
917     auto hostSession = hostPattern->GetSession();
918     CHECK_NULL_RETURN(hostSession, rect);
919     return hostSession->GetSessionRect();
920 }
921 
NotifyForeground()922 void SessionWrapperImpl::NotifyForeground()
923 {
924     ContainerScope scope(instanceId_);
925     CHECK_NULL_VOID(session_);
926     auto container = Platform::AceContainer::GetContainer(instanceId_);
927     CHECK_NULL_VOID(container);
928     auto pipeline = PipelineBase::GetCurrentContext();
929     CHECK_NULL_VOID(pipeline);
930     auto hostWindowId = pipeline->GetFocusWindowId();
931     int32_t windowSceneId = GetWindowSceneId();
932     UIEXT_LOGI("NotifyForeground, persistentid = %{public}d, hostWindowId = %{public}u,"
933         " windowSceneId = %{public}d, IsScenceBoardWindow: %{public}d, componentId=%{public}d.",
934         session_->GetPersistentId(), hostWindowId, windowSceneId, container->IsScenceBoardWindow(), GetFrameNodeId());
935     if (container->IsScenceBoardWindow() && windowSceneId != INVALID_WINDOW_ID) {
936         hostWindowId = static_cast<uint32_t>(windowSceneId);
937     }
938     auto pattern = hostPattern_.Upgrade();
939     CHECK_NULL_VOID(pattern);
940     if (pattern->IsViewportConfigChanged()) {
941         pattern->SetViewportConfigChanged(false);
942         UpdateSessionViewportConfig();
943     }
944     auto wantPtr = session_->EditSessionInfo().want;
945     UpdateWantPtr(wantPtr);
946     Rosen::ExtensionSessionManager::GetInstance().RequestExtensionSessionActivation(
947         session_, hostWindowId, std::move(foregroundCallback_));
948 }
949 
NotifyBackground(bool isHandleError)950 void SessionWrapperImpl::NotifyBackground(bool isHandleError)
951 {
952     CHECK_NULL_VOID(session_);
953     UIEXT_LOGI("NotifyBackground, persistentid = %{public}d, isHandleError = %{public}d, componentId=%{public}d.",
954         session_->GetPersistentId(), isHandleError, GetFrameNodeId());
955     if (isHandleError) {
956         Rosen::ExtensionSessionManager::GetInstance().RequestExtensionSessionBackground(
957             session_, std::move(backgroundCallback_));
958     } else {
959         Rosen::ExtensionSessionManager::GetInstance().RequestExtensionSessionBackground(
960             session_, nullptr);
961     }
962 }
963 
OnReleaseDone()964 void SessionWrapperImpl::OnReleaseDone()
965 {
966     CHECK_NULL_VOID(session_);
967     UIEXT_LOGI("OnReleaseDone, persistentid = %{public}d, componentId=%{public}d.",
968         session_->GetPersistentId(), GetFrameNodeId());
969     session_->UnregisterLifecycleListener(lifecycleListener_);
970     Rosen::ExtensionSessionManager::GetInstance().RequestExtensionSessionDestructionDone(session_);
971     session_ = nullptr;
972 }
973 
NotifyDestroy(bool isHandleError)974 void SessionWrapperImpl::NotifyDestroy(bool isHandleError)
975 {
976     CHECK_NULL_VOID(session_);
977     UIEXT_LOGI("NotifyDestroy, isHandleError = %{public}d, persistentid = %{public}d, componentId=%{public}d.",
978         isHandleError, session_->GetPersistentId(), GetFrameNodeId());
979     if (isHandleError) {
980         Rosen::ExtensionSessionManager::GetInstance().RequestExtensionSessionDestruction(
981             session_, std::move(destructionCallback_));
982     } else {
983         Rosen::ExtensionSessionManager::GetInstance().RequestExtensionSessionDestruction(
984             session_, nullptr);
985     }
986 }
987 
NotifyConfigurationUpdate()988 void SessionWrapperImpl::NotifyConfigurationUpdate() {}
989 /************************************************ End: The lifecycle interface ****************************************/
990 
991 /************************************************ Begin: The interface for responsing provider ************************/
OnConnect()992 void SessionWrapperImpl::OnConnect()
993 {
994     int32_t callSessionId = GetSessionId();
995     taskExecutor_->PostTask(
996         [weak = hostPattern_, wrapperWeak = WeakClaim(this), callSessionId]() {
997             auto pattern = weak.Upgrade();
998             CHECK_NULL_VOID(pattern);
999             if (callSessionId != pattern->GetSessionId()) {
1000                 TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT, "OnConnect: The callSessionId(%{public}d)"
1001                         " is inconsistent with the curSession(%{public}d)",
1002                     callSessionId, pattern->GetSessionId());
1003             }
1004             pattern->OnConnect();
1005             auto wrapper = wrapperWeak.Upgrade();
1006             CHECK_NULL_VOID(wrapper && wrapper->session_);
1007             ContainerScope scope(wrapper->instanceId_);
1008             if (auto hostWindowNode = WindowSceneHelper::FindWindowScene(pattern->GetHost())) {
1009                 auto hostNode = AceType::DynamicCast<FrameNode>(hostWindowNode);
1010                 CHECK_NULL_VOID(hostNode);
1011                 auto hostPattern = hostNode->GetPattern<SystemWindowScene>();
1012                 CHECK_NULL_VOID(hostPattern);
1013                 wrapper->session_->SetParentSession(hostPattern->GetSession());
1014             }
1015         },
1016         TaskExecutor::TaskType::UI, "ArkUIUIExtensionSessionConnect");
1017 }
1018 
OnDisconnect(bool isAbnormal)1019 void SessionWrapperImpl::OnDisconnect(bool isAbnormal)
1020 {
1021     int32_t callSessionId = GetSessionId();
1022     taskExecutor_->PostTask(
1023         [weak = hostPattern_, sessionType = sessionType_, isAbnormal, callSessionId]() {
1024             auto pattern = weak.Upgrade();
1025             CHECK_NULL_VOID(pattern);
1026             if (callSessionId != pattern->GetSessionId()) {
1027                 TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT, "OnDisconnect: The callSessionId(%{public}d)"
1028                         " is inconsistent with the curSession(%{public}d)",
1029                     callSessionId, pattern->GetSessionId());
1030                 return;
1031             }
1032             pattern->OnDisconnect(isAbnormal);
1033             if (sessionType == SessionType::UI_EXTENSION_ABILITY && pattern->IsCompatibleOldVersion()) {
1034                 pattern->FireOnReleaseCallback(static_cast<int32_t>(isAbnormal));
1035                 return;
1036             }
1037             if (isAbnormal) {
1038                 pattern->FireOnErrorCallback(
1039                     ERROR_CODE_UIEXTENSION_EXITED_ABNORMALLY, EXIT_ABNORMALLY_NAME, EXIT_ABNORMALLY_MESSAGE);
1040             } else {
1041                 pattern->FireOnTerminatedCallback(0, nullptr);
1042             }
1043         },
1044         TaskExecutor::TaskType::UI, "ArkUIUIExtensionSessionDisconnect");
1045 }
1046 
OnExtensionTimeout(int32_t errorCode)1047 void SessionWrapperImpl::OnExtensionTimeout(int32_t errorCode)
1048 {
1049     int32_t callSessionId = GetSessionId();
1050     taskExecutor_->PostTask(
1051         [weak = hostPattern_, callSessionId, errorCode]() {
1052             auto pattern = weak.Upgrade();
1053             CHECK_NULL_VOID(pattern);
1054             if (callSessionId != pattern->GetSessionId()) {
1055                 TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT, "OnExtensionTimeout: The callSessionId(%{public}d)"
1056                         " is inconsistent with the curSession(%{public}d)",
1057                     callSessionId, pattern->GetSessionId());
1058             }
1059             bool isTransparent = errorCode == ERROR_CODE_UIEXTENSION_TRANSPARENT;
1060             pattern->FireOnErrorCallback(
1061                 isTransparent ? errorCode : ERROR_CODE_UIEXTENSION_LIFECYCLE_TIMEOUT,
1062                 isTransparent ? EXTENSION_TRANSPARENT_NAME : LIFECYCLE_TIMEOUT_NAME,
1063                 isTransparent ? EXTENSION_TRANSPARENT_MESSAGE : LIFECYCLE_TIMEOUT_MESSAGE);
1064         },
1065         TaskExecutor::TaskType::UI, "ArkUIUIExtensionTimeout");
1066 }
1067 
OnExtensionDetachToDisplay()1068 void SessionWrapperImpl::OnExtensionDetachToDisplay()
1069 {
1070     UIEXT_LOGI("OnExtensionDetachToDisplay");
1071     int32_t callSessionId = GetSessionId();
1072     taskExecutor_->PostTask(
1073         [weak = hostPattern_, callSessionId]() {
1074             auto pattern = weak.Upgrade();
1075             CHECK_NULL_VOID(pattern);
1076             if (callSessionId != pattern->GetSessionId()) {
1077                 TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
1078                     "OnExtensionDetachToDisplay: The callSessionId(%{public}d)"
1079                     " is inconsistent with the curSession(%{public}d)",
1080                     callSessionId, pattern->GetSessionId());
1081                 return;
1082             }
1083 
1084             pattern->OnExtensionDetachToDisplay();
1085         },
1086         TaskExecutor::TaskType::UI, "ArkUIUIExtensionOnExtensionDetachToDisplay");
1087 }
1088 
OnAccessibilityEvent(const Accessibility::AccessibilityEventInfo & info,int64_t offset)1089 void SessionWrapperImpl::OnAccessibilityEvent(const Accessibility::AccessibilityEventInfo& info, int64_t offset)
1090 {
1091     int32_t callSessionId = GetSessionId();
1092     taskExecutor_->PostTask(
1093         [weak = hostPattern_, info, offset, callSessionId]() {
1094             auto pattern = weak.Upgrade();
1095             CHECK_NULL_VOID(pattern);
1096             if (callSessionId != pattern->GetSessionId()) {
1097                 TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT, "OnAccessibilityEvent: The callSessionId(%{public}d)"
1098                         " is inconsistent with the curSession(%{public}d)",
1099                     callSessionId, pattern->GetSessionId());
1100             }
1101             pattern->OnAccessibilityEvent(info, offset);
1102         },
1103         TaskExecutor::TaskType::UI, "ArkUIUIExtensionAccessibilityEvent");
1104 }
1105 /************************************************** End: The interface for responsing provider ************************/
1106 
1107 /************************************************ Begin: The interface about the accessibility ************************/
TransferAccessibilityHoverEvent(float pointX,float pointY,int32_t sourceType,int32_t eventType,int64_t timeMs)1108 void SessionWrapperImpl::TransferAccessibilityHoverEvent(float pointX, float pointY, int32_t sourceType,
1109     int32_t eventType, int64_t timeMs)
1110 {
1111     CHECK_NULL_VOID(session_);
1112     session_->TransferAccessibilityHoverEvent(pointX, pointY, sourceType, eventType, timeMs);
1113 }
1114 
TransferAccessibilityChildTreeRegister(uint32_t windowId,int32_t treeId,int64_t accessibilityId)1115 void SessionWrapperImpl::TransferAccessibilityChildTreeRegister(
1116     uint32_t windowId, int32_t treeId, int64_t accessibilityId)
1117 {
1118     CHECK_NULL_VOID(session_);
1119     session_->TransferAccessibilityChildTreeRegister(windowId, treeId, accessibilityId);
1120 }
1121 
TransferAccessibilityChildTreeDeregister()1122 void SessionWrapperImpl::TransferAccessibilityChildTreeDeregister()
1123 {
1124     CHECK_NULL_VOID(session_);
1125     session_->TransferAccessibilityChildTreeUnregister();
1126 }
1127 
TransferAccessibilityDumpChildInfo(const std::vector<std::string> & params,std::vector<std::string> & info)1128 void SessionWrapperImpl::TransferAccessibilityDumpChildInfo(
1129     const std::vector<std::string>& params, std::vector<std::string>& info)
1130 {
1131     CHECK_NULL_VOID(session_);
1132     session_->TransferAccessibilityDumpChildInfo(params, info);
1133 }
1134 /************************************************ End: The interface about the accessibility **************************/
1135 
1136 /***************************** Begin: The interface to control the display area and the avoid area ********************/
GetSurfaceNode() const1137 std::shared_ptr<Rosen::RSSurfaceNode> SessionWrapperImpl::GetSurfaceNode() const
1138 {
1139     return session_ ? session_->GetSurfaceNode() : nullptr;
1140 }
1141 
NotifyDisplayArea(const RectF & displayArea)1142 void SessionWrapperImpl::NotifyDisplayArea(const RectF& displayArea)
1143 {
1144     CHECK_NULL_VOID(session_);
1145     auto instanceId = GetInstanceIdFromHost();
1146     ContainerScope scope(instanceId);
1147     auto pipeline = PipelineBase::GetCurrentContext();
1148     CHECK_NULL_VOID(pipeline);
1149     displayAreaWindow_ = pipeline->GetCurrentWindowRect();
1150     displayArea_ = displayArea + OffsetF(displayAreaWindow_.Left(), displayAreaWindow_.Top());
1151     std::shared_ptr<Rosen::RSTransaction> transaction;
1152     auto parentSession = session_->GetParentSession();
1153     auto reason = parentSession ? parentSession->GetSizeChangeReason() : session_->GetSizeChangeReason();
1154     reason_ = (uint32_t)reason;
1155     auto persistentId = parentSession ? parentSession->GetPersistentId() : session_->GetPersistentId();
1156     int32_t duration = 0;
1157     if (reason == Rosen::SizeChangeReason::ROTATION) {
1158         if (transaction_.lock()) {
1159             transaction = transaction_.lock();
1160             transaction_.reset();
1161         } else if (auto transactionController = Rosen::RSSyncTransactionController::GetInstance()) {
1162             transaction = transactionController->GetRSTransaction();
1163         }
1164         if (transaction && parentSession) {
1165             duration = pipeline->GetSyncAnimationOption().GetDuration();
1166             transaction->SetDuration(duration);
1167         }
1168     }
1169     ACE_SCOPED_TRACE("NotifyDisplayArea displayArea[%s], curWindow[%s], reason[%d], duration[%d], componentId[%d]",
1170         displayArea_.ToString().c_str(), displayAreaWindow_.ToString().c_str(), reason, duration, GetFrameNodeId());
1171     UIEXT_LOGI("NotifyDisplayArea displayArea=%{public}s, curWindow=%{public}s, "
1172         "reason=%{public}d, duration=%{public}d, persistentId=%{public}d, componentId=%{public}d.",
1173         displayArea_.ToString().c_str(), displayAreaWindow_.ToString().c_str(),
1174         reason, duration, persistentId, GetFrameNodeId());
1175     session_->UpdateRect({ std::round(displayArea_.Left()), std::round(displayArea_.Top()),
1176         std::round(displayArea_.Width()), std::round(displayArea_.Height()) }, reason, "NotifyDisplayArea",
1177         transaction);
1178 }
1179 
NotifySizeChangeReason(WindowSizeChangeReason type,const std::shared_ptr<Rosen::RSTransaction> & rsTransaction)1180 void SessionWrapperImpl::NotifySizeChangeReason(
1181     WindowSizeChangeReason type, const std::shared_ptr<Rosen::RSTransaction>& rsTransaction)
1182 {
1183     CHECK_NULL_VOID(session_);
1184     auto reason = static_cast<Rosen::SizeChangeReason>(type);
1185     session_->UpdateSizeChangeReason(reason);
1186     if (rsTransaction && (type == WindowSizeChangeReason::ROTATION)) {
1187         transaction_ = rsTransaction;
1188     }
1189 }
1190 
NotifyOriginAvoidArea(const Rosen::AvoidArea & avoidArea,uint32_t type) const1191 void SessionWrapperImpl::NotifyOriginAvoidArea(const Rosen::AvoidArea& avoidArea, uint32_t type) const
1192 {
1193     CHECK_NULL_VOID(session_);
1194     UIEXT_LOGI("NotifyAvoidArea, type: %{public}d, topRect=(%{public}d, %{public}d)-[%{public}d, %{public}d], "
1195         "bottomRect=(%{public}d,%{public}d)-[%{public}d,%{public}d],persistentId=%{public}d,componentId=%{public}d.",
1196         type, avoidArea.topRect_.posX_, avoidArea.topRect_.posY_, (int32_t)avoidArea.topRect_.width_,
1197         (int32_t)avoidArea.topRect_.height_, avoidArea.bottomRect_.posX_, avoidArea.bottomRect_.posY_,
1198         (int32_t)avoidArea.bottomRect_.width_, (int32_t)avoidArea.bottomRect_.height_, GetSessionId(),
1199         GetFrameNodeId());
1200     ACE_SCOPED_TRACE("NotifyAvoidArea, type: %d, topRect: (%d, %d) - [%d, %d], bottomRect: (%d, %d) - [%d, %d]",
1201         type, avoidArea.topRect_.posX_, avoidArea.topRect_.posY_, (int32_t)avoidArea.topRect_.width_,
1202         (int32_t)avoidArea.topRect_.height_, avoidArea.bottomRect_.posX_, avoidArea.bottomRect_.posY_,
1203         (int32_t)avoidArea.bottomRect_.width_, (int32_t)avoidArea.bottomRect_.height_);
1204     session_->UpdateAvoidArea(sptr<Rosen::AvoidArea>::MakeSptr(avoidArea), static_cast<Rosen::AvoidAreaType>(type));
1205 }
1206 
NotifyOccupiedAreaChangeInfo(sptr<Rosen::OccupiedAreaChangeInfo> info,bool needWaitLayout)1207 bool SessionWrapperImpl::NotifyOccupiedAreaChangeInfo(
1208     sptr<Rosen::OccupiedAreaChangeInfo> info, bool needWaitLayout)
1209 {
1210     CHECK_NULL_RETURN(session_, false);
1211     CHECK_NULL_RETURN(info, false);
1212     CHECK_NULL_RETURN(isNotifyOccupiedAreaChange_, false);
1213     CHECK_NULL_RETURN(taskExecutor_, false);
1214     ContainerScope scope(instanceId_);
1215     auto pipeline = PipelineBase::GetCurrentContext();
1216     CHECK_NULL_RETURN(pipeline, false);
1217     auto curWindow = pipeline->GetCurrentWindowRect();
1218     int64_t curTime = GetCurrentTimestamp();
1219     if (displayAreaWindow_ != curWindow && needWaitLayout) {
1220         UIEXT_LOGI("OccupiedArea wait layout, displayAreaWindow: %{public}s,"
1221             " curWindow=%{public}s, componentId=%{public}d.",
1222             displayAreaWindow_.ToString().c_str(), curWindow.ToString().c_str(), GetFrameNodeId());
1223         taskExecutor_->PostDelayedTask(
1224             [info, weak = AceType::WeakClaim(this), curTime] {
1225                 auto session = weak.Upgrade();
1226                 if (session) {
1227                     session->InnerNotifyOccupiedAreaChangeInfo(info, true, curTime);
1228                 }
1229             },
1230             TaskExecutor::TaskType::UI, AVOID_DELAY_TIME, "ArkUIVirtualKeyboardAreaChangeDelay");
1231     }
1232 
1233     taskExecutor_->PostTask(
1234         [info, weak = AceType::WeakClaim(this), curTime] {
1235             auto session = weak.Upgrade();
1236             if (session) {
1237                 session->InnerNotifyOccupiedAreaChangeInfo(info, false, curTime);
1238             }
1239         },
1240         TaskExecutor::TaskType::UI, "ArkUIUecAreaChange",
1241         TaskExecutor::GetPriorityTypeWithCheck(PriorityType::VIP));
1242     return true;
1243 }
1244 
InnerNotifyOccupiedAreaChangeInfo(sptr<Rosen::OccupiedAreaChangeInfo> info,bool isWaitTask,int64_t occupiedAreaTime)1245 bool SessionWrapperImpl::InnerNotifyOccupiedAreaChangeInfo(
1246     sptr<Rosen::OccupiedAreaChangeInfo> info, bool isWaitTask, int64_t occupiedAreaTime)
1247 {
1248     if (isWaitTask && occupiedAreaTime < lastOccupiedAreaTime_) {
1249         UIEXT_LOGW("OccupiedArea has been executed last time, persistentid = %{public}d.",
1250             GetSessionId());
1251         return false;
1252     }
1253 
1254     lastOccupiedAreaTime_ = occupiedAreaTime;
1255     CHECK_NULL_RETURN(session_, false);
1256     CHECK_NULL_RETURN(info, false);
1257     CHECK_NULL_RETURN(isNotifyOccupiedAreaChange_, false);
1258     int32_t keyboardHeight = static_cast<int32_t>(info->rect_.height_);
1259     ContainerScope scope(instanceId_);
1260     auto pipeline = PipelineBase::GetCurrentContext();
1261     CHECK_NULL_RETURN(pipeline, false);
1262     auto curWindow = pipeline->GetCurrentWindowRect();
1263     auto container = Platform::AceContainer::GetContainer(GetInstanceIdFromHost());
1264     CHECK_NULL_RETURN(container, false);
1265     if (container->IsScenceBoardWindow()) {
1266         Rosen::WSRect rect = GetWindowSceneRect();
1267         curWindow.SetRect(rect.posX_, rect.posY_, rect.width_, rect.height_);
1268     }
1269     if (keyboardHeight > 0) {
1270         if (curWindow.Bottom() >= displayArea_.Bottom()) {
1271             int32_t spaceWindow = std::max(curWindow.Bottom() - displayArea_.Bottom(), 0.0);
1272             keyboardHeight = static_cast<int32_t>(std::max(keyboardHeight - spaceWindow, 0));
1273         } else {
1274             keyboardHeight = keyboardHeight + (displayArea_.Bottom() - curWindow.Bottom());
1275         }
1276     }
1277     sptr<Rosen::OccupiedAreaChangeInfo> newInfo = new Rosen::OccupiedAreaChangeInfo(
1278         info->type_, info->rect_, info->safeHeight_, info->textFieldPositionY_, info->textFieldHeight_);
1279     newInfo->rect_.height_ = static_cast<uint32_t>(keyboardHeight);
1280     UIEXT_LOGI("OccupiedArea keyboardHeight = %{public}d, displayArea = %{public}s, "
1281         "curWindow = %{public}s, persistentid = %{public}d, componentId=%{public}d.",
1282         keyboardHeight, displayArea_.ToString().c_str(), curWindow.ToString().c_str(), GetSessionId(),
1283         GetFrameNodeId());
1284     session_->NotifyOccupiedAreaChangeInfo(newInfo);
1285     return true;
1286 }
1287 
UpdateSessionViewportConfig()1288 void SessionWrapperImpl::UpdateSessionViewportConfig()
1289 {
1290     CHECK_NULL_VOID(session_);
1291     auto pattern = hostPattern_.Upgrade();
1292     CHECK_NULL_VOID(pattern);
1293     auto config = pattern->GetSessionViewportConfig();
1294     UIEXT_LOGI("SessionViewportConfig: isDensityFollowHost=%{public}d, density=%{public}f, "
1295         "displayId=%{public}" PRIu64", orientation=%{public}d, transform=%{public}d, componentId=%{public}d.",
1296         config.isDensityFollowHost_, config.density_, config.displayId_, config.orientation_, config.transform_,
1297         GetFrameNodeId());
1298     session_->UpdateSessionViewportConfig(ConvertToRosenSessionViewportConfig(config));
1299 }
1300 
1301 /***************************** End: The interface to control the display area and the avoid area **********************/
1302 
1303 /************************************************ Begin: The interface to send the data for ArkTS *********************/
SendDataAsync(const AAFwk::WantParams & params) const1304 void SessionWrapperImpl::SendDataAsync(const AAFwk::WantParams& params) const
1305 {
1306     UIEXT_LOGI("The data is asynchronously send and the session is %{public}s, componentId=%{public}d.",
1307         session_ ? "valid" : "invalid", GetFrameNodeId());
1308     CHECK_NULL_VOID(session_);
1309     session_->TransferComponentData(params);
1310 }
1311 
SendDataSync(const AAFwk::WantParams & wantParams,AAFwk::WantParams & reWantParams) const1312 int32_t SessionWrapperImpl::SendDataSync(const AAFwk::WantParams& wantParams, AAFwk::WantParams& reWantParams) const
1313 {
1314     Rosen::WSErrorCode transferCode = Rosen::WSErrorCode::WS_ERROR_TRANSFER_DATA_FAILED;
1315     UIEXT_LOGI("The data is synchronously send and the session is %{public}s, componentId=%{public}d.",
1316         session_ ? "valid" : "invalid", GetFrameNodeId());
1317     if (session_) {
1318         transferCode = session_->TransferComponentDataSync(wantParams, reWantParams);
1319     }
1320     return static_cast<int32_t>(transferCode);
1321 }
1322 /************************************************ End: The interface to send the data for ArkTS ***********************/
1323 
1324 /************************************************ Begin: The interface for UEC dump **********************************/
GetReasonDump() const1325 uint32_t SessionWrapperImpl::GetReasonDump() const
1326 {
1327     return reason_;
1328 }
1329 
NotifyUieDump(const std::vector<std::string> & params,std::vector<std::string> & info)1330 void SessionWrapperImpl::NotifyUieDump(const std::vector<std::string>& params, std::vector<std::string>& info)
1331 {
1332     CHECK_NULL_VOID(session_);
1333     session_->NotifyDumpInfo(params, info);
1334 }
1335 
GetFrameNodeId() const1336 int32_t SessionWrapperImpl::GetFrameNodeId() const
1337 {
1338     auto pattern = hostPattern_.Upgrade();
1339     CHECK_NULL_RETURN(pattern, -1);
1340     auto frameNode =  pattern->GetHost();
1341     CHECK_NULL_RETURN(frameNode, -1);
1342     return frameNode->GetId();
1343 }
1344 
SendBusinessDataSyncReply(UIContentBusinessCode code,const AAFwk::Want & data,AAFwk::Want & reply,RSSubsystemId subSystemId)1345 bool SessionWrapperImpl::SendBusinessDataSyncReply(
1346     UIContentBusinessCode code, const AAFwk::Want& data, AAFwk::Want& reply, RSSubsystemId subSystemId)
1347 {
1348     if (code == UIContentBusinessCode::UNDEFINED) {
1349         return false;
1350     }
1351     CHECK_NULL_RETURN(session_, false);
1352     auto dataHandler = session_->GetExtensionDataHandler();
1353     CHECK_NULL_RETURN(dataHandler, false);
1354     auto result = dataHandler->SendDataSync(static_cast<OHOS::Rosen::SubSystemId>(subSystemId),
1355         static_cast<uint32_t>(code), data, reply);
1356     if (result != Rosen::DataHandlerErr::OK) {
1357         UIEXT_LOGW("SendBusinessDataSyncReply Fail, businesCode=%{public}u, result=%{public}u, compontId=%{public}d.",
1358             code, result, GetFrameNodeId());
1359         return false;
1360     }
1361     UIEXT_LOGI("SendBusinessDataSyncReply Success, businessCode=%{public}u, compontId=%{public}d.",
1362         code, GetFrameNodeId());
1363     return true;
1364 }
1365 
SendBusinessData(UIContentBusinessCode code,const AAFwk::Want & data,BusinessDataSendType type,RSSubsystemId subSystemId)1366 bool SessionWrapperImpl::SendBusinessData(
1367     UIContentBusinessCode code, const AAFwk::Want& data, BusinessDataSendType type, RSSubsystemId subSystemId)
1368 {
1369     if (code == UIContentBusinessCode::UNDEFINED) {
1370         return false;
1371     }
1372     CHECK_NULL_RETURN(session_, false);
1373     auto dataHandler = session_->GetExtensionDataHandler();
1374     CHECK_NULL_RETURN(dataHandler, false);
1375     if (type == BusinessDataSendType::ASYNC) {
1376         dataHandler->SendDataAsync(static_cast<OHOS::Rosen::SubSystemId>(subSystemId),
1377             static_cast<uint32_t>(code), data);
1378         UIEXT_LOGI("SendBusinessData ASYNC Success, businessCode=%{public}u, compontId=%{public}d.",
1379             code, GetFrameNodeId());
1380         return true;
1381     }
1382     auto result = dataHandler->SendDataSync(static_cast<OHOS::Rosen::SubSystemId>(subSystemId),
1383         static_cast<uint32_t>(code), data);
1384     if (result != Rosen::DataHandlerErr::OK) {
1385         UIEXT_LOGW("SendBusinessData Sync Fail, businesCode=%{public}u, result=%{public}u, compontId=%{public}d.",
1386             code, result, GetFrameNodeId());
1387         return false;
1388     }
1389     UIEXT_LOGI("SendBusinessData SYNC Success, businessCode=%{public}u, componentId=%{public}d.",
1390         code, GetFrameNodeId());
1391     return true;
1392 }
1393 
PostBusinessDataConsumeAsync(uint32_t customId,AAFwk::Want && data)1394 void SessionWrapperImpl::PostBusinessDataConsumeAsync(uint32_t customId, AAFwk::Want&& data)
1395 {
1396     UIEXT_LOGI("PostBusinessDataConsumeAsync, businessCode=%{public}u.", customId);
1397     int32_t callSessionId = GetSessionId();
1398     CHECK_NULL_VOID(taskExecutor_);
1399     auto instanceId = GetInstanceIdFromHost();
1400     AAFwk::Want businessData = data;
1401     taskExecutor_->PostTask(
1402         [instanceId, weak = hostPattern_, customId, businessData, callSessionId]() {
1403             ContainerScope scope(instanceId);
1404             auto pattern = weak.Upgrade();
1405             CHECK_NULL_VOID(pattern);
1406             if (callSessionId != pattern->GetSessionId()) {
1407                 TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
1408                     "BusinessDataConsumeAsync: The callSessionId(%{public}d)"
1409                         " is inconsistent with the curSession(%{public}d)",
1410                     callSessionId, pattern->GetSessionId());
1411                 return;
1412             }
1413             pattern->OnUIExtBusinessReceive(static_cast<UIContentBusinessCode>(customId), businessData);
1414         },
1415         TaskExecutor::TaskType::UI, "ArkUIUIExtensionBusinessDataConsumeAsync");
1416 }
PostBusinessDataConsumeSyncReply(uint32_t customId,AAFwk::Want && data,std::optional<AAFwk::Want> & reply)1417 void SessionWrapperImpl::PostBusinessDataConsumeSyncReply(
1418     uint32_t customId, AAFwk::Want&& data, std::optional<AAFwk::Want>& reply)
1419 {
1420     UIEXT_LOGI("PostBusinessDataConsumeSyncReply, businessCode=%{public}u.", customId);
1421     int32_t callSessionId = GetSessionId();
1422     CHECK_NULL_VOID(taskExecutor_);
1423     auto instanceId = GetInstanceIdFromHost();
1424     AAFwk::Want businessData = data;
1425     taskExecutor_->PostSyncTask(
1426         [instanceId, weak = hostPattern_, customId, businessData, &reply, callSessionId]() {
1427             ContainerScope scope(instanceId);
1428             auto pattern = weak.Upgrade();
1429             CHECK_NULL_VOID(pattern);
1430             if (callSessionId != pattern->GetSessionId()) {
1431                 TAG_LOGW(AceLogTag::ACE_UIEXTENSIONCOMPONENT,
1432                     "BusinessDataConsumeSyncReply: The callSessionId(%{public}d)"
1433                         " is inconsistent with the curSession(%{public}d)",
1434                     callSessionId, pattern->GetSessionId());
1435                 return;
1436             }
1437             pattern->OnUIExtBusinessReceiveReply(
1438                 static_cast<UIContentBusinessCode>(customId), businessData, reply);
1439         },
1440         TaskExecutor::TaskType::UI, "ArkUIUIExtensionBusinessDataConsumeSyncReply");
1441 }
1442 
RegisterDataConsumer()1443 bool SessionWrapperImpl::RegisterDataConsumer()
1444 {
1445     CHECK_NULL_RETURN(session_, false);
1446     auto dataHandler = session_->GetExtensionDataHandler();
1447     CHECK_NULL_RETURN(dataHandler, false);
1448     auto subSystemId = subSystemId_;
1449     auto callback = [wrapperWeak = WeakClaim(this), subSystemId]
1450         (Rosen::SubSystemId id, uint32_t customId, AAFwk::Want&& data, std::optional<AAFwk::Want>& reply) ->int32_t {
1451         auto sessionWrapper = wrapperWeak.Upgrade();
1452         CHECK_NULL_RETURN(sessionWrapper, false);
1453         auto instanceId = sessionWrapper->GetInstanceIdFromHost();
1454         ContainerScope scope(instanceId);
1455         if (id != subSystemId) {
1456             return 0;
1457         }
1458         if (reply.has_value()) {
1459             sessionWrapper->PostBusinessDataConsumeSyncReply(customId, std::move(data), reply);
1460         } else {
1461             sessionWrapper->PostBusinessDataConsumeAsync(customId, std::move(data));
1462         }
1463         return 0;
1464     };
1465     auto result = dataHandler->RegisterDataConsumer(subSystemId, std::move(callback));
1466     if (result != Rosen::DataHandlerErr::OK) {
1467         UIEXT_LOGW("RegisterDataConsumer Fail, result=%{public}u", result);
1468         return false;
1469     }
1470     return true;
1471 }
1472 /************************************************ End: The interface for UEC dump **********************************/
1473 
NotifyHostWindowMode(int32_t mode)1474 void SessionWrapperImpl::NotifyHostWindowMode(int32_t mode)
1475 {
1476     UIEXT_LOGI("SendWindowModeToProvider: mode = %{public}d", mode);
1477     CHECK_NULL_VOID(session_);
1478     auto dataHandler = session_->GetExtensionDataHandler();
1479     CHECK_NULL_VOID(dataHandler);
1480     AAFwk::Want dataToSend;
1481     dataToSend.SetParam(OHOS::Rosen::Extension::WINDOW_MODE_FIELD, mode);
1482     dataHandler->SendDataAsync(Rosen::SubSystemId::WM_UIEXT,
1483         static_cast<uint32_t>(OHOS::Rosen::Extension::Businesscode::SYNC_HOST_WINDOW_MODE), dataToSend);
1484 }
1485 } // namespace OHOS::Ace::NG
1486