• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "window_extension_session_impl.h"
17 
18 #include <bool_wrapper.h>
19 #include <float_wrapper.h>
20 #include <hitrace_meter.h>
21 #include <int_wrapper.h>
22 #include <ipc_types.h>
23 #include <parameters.h>
24 #include <string_wrapper.h>
25 #include <transaction/rs_interfaces.h>
26 #include <transaction/rs_transaction.h>
27 
28 #ifdef IMF_ENABLE
29 #include <input_method_controller.h>
30 #endif
31 
32 #include "display_info.h"
33 #include "input_transfer_station.h"
34 #include "perform_reporter.h"
35 #include "rs_adapter.h"
36 #include "session_permission.h"
37 #include "singleton_container.h"
38 #include "sys_cap_util.h"
39 #include "ui_extension/provider_data_handler.h"
40 #include "window_adapter.h"
41 #include "window_helper.h"
42 #include "window_manager_hilog.h"
43 #include "wm_common.h"
44 #include "session_helper.h"
45 
46 namespace OHOS {
47 namespace Rosen {
48 namespace {
49 constexpr HiviewDFX::HiLogLabel LABEL = {LOG_CORE, HILOG_DOMAIN_WINDOW, "WindowExtensionSessionImpl"};
50 #ifdef IMF_ENABLE
51 constexpr int64_t DISPATCH_KEY_EVENT_TIMEOUT_TIME_MS = 1000;
52 #endif // IMF_ENABLE
53 constexpr int32_t UIEXTENTION_ROTATION_ANIMATION_TIME = 400;
54 }
55 
56 #define CHECK_HOST_SESSION_RETURN_IF_NULL(hostSession)                         \
57     do {                                                                       \
58         if ((hostSession) == nullptr) {                                        \
59             TLOGE(WmsLogTag::DEFAULT, "hostSession is null");                  \
60             return;                                                            \
61         }                                                                      \
62     } while (false)
63 
64 #define CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, ret)              \
65     do {                                                                       \
66         if ((hostSession) == nullptr) {                                        \
67             TLOGE(WmsLogTag::DEFAULT, "hostSession is null");                  \
68             return ret;                                                        \
69         }                                                                      \
70     } while (false)
71 
WindowExtensionSessionImpl(const sptr<WindowOption> & option)72 WindowExtensionSessionImpl::WindowExtensionSessionImpl(const sptr<WindowOption>& option) : WindowSessionImpl(option)
73 {
74     if (property_->GetUIExtensionUsage() == UIExtensionUsage::MODAL ||
75         SessionHelper::IsSecureUIExtension(property_->GetUIExtensionUsage())) {
76         extensionWindowFlags_.hideNonSecureWindowsFlag = true;
77     }
78     if ((isDensityFollowHost_ = option->GetIsDensityFollowHost())) {
79         hostDensityValue_ = option->GetDensity();
80     }
81     TLOGNI(WmsLogTag::WMS_UIEXT, "Uiext usage=%{public}u", property_->GetUIExtensionUsage());
82     dataHandler_ = std::make_shared<Extension::ProviderDataHandler>();
83     RegisterDataConsumer();
84 }
85 
~WindowExtensionSessionImpl()86 WindowExtensionSessionImpl::~WindowExtensionSessionImpl()
87 {
88     WLOGFI("[WMSCom] %{public}d, %{public}s", GetPersistentId(), GetWindowName().c_str());
89 }
90 
GetFloatParam(const std::string & key,const AAFwk::WantParams & configParam,float defaultValue=1.0f)91 static float GetFloatParam(const std::string& key, const AAFwk::WantParams& configParam,
92     float defaultValue = 1.0f)
93 {
94     if (AAFwk::IFloat* so = AAFwk::IFloat::Query(configParam.GetParam(key))) {
95         defaultValue = AAFwk::Float::Unbox(so);
96     }
97     return defaultValue;
98 }
99 
GetExtensionDataHandler() const100 std::shared_ptr<IDataHandler> WindowExtensionSessionImpl::GetExtensionDataHandler() const
101 {
102     return dataHandler_;
103 }
104 
Create(const std::shared_ptr<AbilityRuntime::Context> & context,const sptr<Rosen::ISession> & iSession,const std::string & identityToken,bool isModuleAbilityHookEnd)105 WMError WindowExtensionSessionImpl::Create(const std::shared_ptr<AbilityRuntime::Context>& context,
106     const sptr<Rosen::ISession>& iSession, const std::string& identityToken, bool isModuleAbilityHookEnd)
107 {
108     TLOGD(WmsLogTag::WMS_LIFE, "Called.");
109     if (!context || !iSession) {
110         TLOGE(WmsLogTag::WMS_LIFE, "context is nullptr: %{public}u or sessionToken is nullptr: %{public}u",
111             context == nullptr, iSession == nullptr);
112         return WMError::WM_ERROR_NULLPTR;
113     }
114     if (vsyncStation_ == nullptr || !vsyncStation_->IsVsyncReceiverCreated()) {
115         return WMError::WM_ERROR_NULLPTR;
116     }
117     SetDefaultDisplayIdIfNeed();
118     // Since here is init of this window, no other threads will rw it.
119     hostSession_ = iSession;
120 
121     dataHandler_->SetEventHandler(handler_);
122     dataHandler_->SetRemoteProxyObject(iSession->AsObject());
123 
124     context_ = context;
125     if (context_) {
126         abilityToken_ = context_->GetToken();
127     }
128     // XTS log, please do not modify
129     TLOGI(WmsLogTag::WMS_UIEXT, "IsConstrainedModal: %{public}d", property_->IsConstrainedModal());
130     AddExtensionWindowStageToSCB(property_->IsConstrainedModal());
131     WMError ret = Connect();
132     if (ret != WMError::WM_OK) {
133         TLOGE(WmsLogTag::WMS_LIFE, "name:%{public}s %{public}d connect fail. ret:%{public}d",
134             property_->GetWindowName().c_str(), GetPersistentId(), ret);
135         return ret;
136     }
137     MakeSubOrDialogWindowDragableAndMoveble();
138     {
139         std::unique_lock<std::shared_mutex> lock(windowExtensionSessionMutex_);
140         GetWindowExtensionSessionSet().insert(this);
141     }
142 
143     auto usage = property_->GetUIExtensionUsage();
144     if ((usage == UIExtensionUsage::MODAL) || SessionHelper::IsSecureUIExtension(usage)) {
145         InputTransferStation::GetInstance().AddInputWindow(this);
146     }
147 
148     state_ = WindowState::STATE_CREATED;
149     isUIExtensionAbilityProcess_ = true;
150     property_->SetIsUIExtensionAbilityProcess(true);
151     TLOGI(WmsLogTag::WMS_LIFE, "Created name:%{public}s %{public}d",
152         property_->GetWindowName().c_str(), GetPersistentId());
153     AddSetUIContentTimeoutCheck();
154     return WMError::WM_OK;
155 }
156 
AddExtensionWindowStageToSCB(bool isConstrainedModal)157 void WindowExtensionSessionImpl::AddExtensionWindowStageToSCB(bool isConstrainedModal)
158 {
159     if (!abilityToken_) {
160         TLOGE(WmsLogTag::WMS_UIEXT, "token is nullptr");
161         return;
162     }
163     if (surfaceNode_ == nullptr) {
164         TLOGE(WmsLogTag::WMS_UIEXT, "surfaceNode_ is nullptr");
165         return;
166     }
167 
168     SingletonContainer::Get<WindowAdapter>().AddExtensionWindowStageToSCB(sptr<ISessionStage>(this), abilityToken_,
169         surfaceNode_->GetId(), isConstrainedModal);
170 }
171 
RemoveExtensionWindowStageFromSCB(bool isConstrainedModal)172 void WindowExtensionSessionImpl::RemoveExtensionWindowStageFromSCB(bool isConstrainedModal)
173 {
174     if (!abilityToken_) {
175         TLOGE(WmsLogTag::WMS_UIEXT, "token is nullptr");
176         return;
177     }
178 
179     SingletonContainer::Get<WindowAdapter>().RemoveExtensionWindowStageFromSCB(sptr<ISessionStage>(this),
180         abilityToken_, isConstrainedModal);
181 }
182 
UpdateConfiguration(const std::shared_ptr<AppExecFwk::Configuration> & configuration)183 void WindowExtensionSessionImpl::UpdateConfiguration(const std::shared_ptr<AppExecFwk::Configuration>& configuration)
184 {
185     if (auto uiContent = GetUIContentSharedPtr()) {
186         TLOGI(WmsLogTag::WMS_ATTRIBUTE, "notify ace extension win=%{public}u, display=%{public}" PRIu64,
187             GetWindowId(), GetDisplayId());
188         uiContent->UpdateConfiguration(configuration);
189     } else {
190         TLOGE(WmsLogTag::WMS_ATTRIBUTE, "uiContent null, ext win=%{public}u, display=%{public}" PRIu64,
191             GetWindowId(), GetDisplayId());
192     }
193 }
194 
UpdateConfigurationForSpecified(const std::shared_ptr<AppExecFwk::Configuration> & configuration,const std::shared_ptr<Global::Resource::ResourceManager> & resourceManager)195 void WindowExtensionSessionImpl::UpdateConfigurationForSpecified(
196     const std::shared_ptr<AppExecFwk::Configuration>& configuration,
197     const std::shared_ptr<Global::Resource::ResourceManager>& resourceManager)
198 {
199     if (auto uiContent = GetUIContentSharedPtr()) {
200         TLOGI(WmsLogTag::WMS_ATTRIBUTE, "notify ace extension win=%{public}u, display=%{public}" PRIu64,
201             GetWindowId(), GetDisplayId());
202         uiContent->UpdateConfiguration(configuration, resourceManager);
203     } else {
204         TLOGE(WmsLogTag::WMS_ATTRIBUTE, "uiContent null, ext win=%{public}u, display=%{public}" PRIu64,
205             GetWindowId(), GetDisplayId());
206     }
207 }
208 
UpdateConfigurationForAll(const std::shared_ptr<AppExecFwk::Configuration> & configuration,const std::vector<std::shared_ptr<AbilityRuntime::Context>> & ignoreWindowContexts)209 void WindowExtensionSessionImpl::UpdateConfigurationForAll(
210     const std::shared_ptr<AppExecFwk::Configuration>& configuration,
211     const std::vector<std::shared_ptr<AbilityRuntime::Context>>& ignoreWindowContexts)
212 {
213     std::unordered_set<std::shared_ptr<AbilityRuntime::Context>> ignoreWindowCtxSet(
214         ignoreWindowContexts.begin(), ignoreWindowContexts.end());
215     std::unique_lock<std::shared_mutex> lock(windowExtensionSessionMutex_);
216     TLOGD(WmsLogTag::WMS_ATTRIBUTE, "extension map size: %{public}u",
217         static_cast<uint32_t>(GetWindowExtensionSessionSet().size()));
218     for (const auto& window : GetWindowExtensionSessionSet()) {
219         if (window == nullptr) {
220             TLOGE(WmsLogTag::WMS_ATTRIBUTE, "extension window is null");
221             continue;
222         }
223         if (ignoreWindowCtxSet.count(window->GetContext()) == 0) {
224             TLOGD(WmsLogTag::WMS_ATTRIBUTE, "extension win=%{public}u, display=%{public}" PRIu64,
225                 window->GetWindowId(), window->GetDisplayId());
226             window->UpdateConfiguration(configuration);
227         } else {
228             TLOGI(WmsLogTag::WMS_ATTRIBUTE, "skip extension win=%{public}u, display=%{public}" PRIu64,
229                 window->GetWindowId(), window->GetDisplayId());
230         }
231     }
232 }
233 
UpdateConfigurationSync(const std::shared_ptr<AppExecFwk::Configuration> & configuration)234 void WindowExtensionSessionImpl::UpdateConfigurationSync(
235     const std::shared_ptr<AppExecFwk::Configuration>& configuration)
236 {
237     if (auto uiContent = GetUIContentSharedPtr()) {
238         TLOGI(WmsLogTag::WMS_ATTRIBUTE, "notify ace extension win=%{public}u, display=%{public}" PRIu64,
239             GetWindowId(), GetDisplayId());
240         uiContent->UpdateConfigurationSyncForAll(configuration);
241     } else {
242         TLOGE(WmsLogTag::WMS_ATTRIBUTE, "uiContent null, ext win=%{public}u, display=%{public}" PRIu64,
243             GetWindowId(), GetDisplayId());
244     }
245 }
246 
UpdateConfigurationSyncForAll(const std::shared_ptr<AppExecFwk::Configuration> & configuration)247 void WindowExtensionSessionImpl::UpdateConfigurationSyncForAll(
248     const std::shared_ptr<AppExecFwk::Configuration>& configuration)
249 {
250     std::unique_lock<std::shared_mutex> lock(windowExtensionSessionMutex_);
251     TLOGD(WmsLogTag::WMS_ATTRIBUTE, "extension map size: %{public}u",
252         static_cast<uint32_t>(GetWindowExtensionSessionSet().size()));
253     for (const auto& window : GetWindowExtensionSessionSet()) {
254         if (window == nullptr) {
255             TLOGE(WmsLogTag::WMS_ATTRIBUTE, "extension window is null");
256             continue;
257         }
258         TLOGD(WmsLogTag::WMS_ATTRIBUTE, "extension win=%{public}u, display=%{public}" PRIu64,
259             window->GetWindowId(), window->GetDisplayId());
260         window->UpdateConfigurationSync(configuration);
261     }
262 }
263 
Destroy(bool needNotifyServer,bool needClearListener,uint32_t reason)264 WMError WindowExtensionSessionImpl::Destroy(bool needNotifyServer, bool needClearListener, uint32_t reason)
265 {
266     TLOGI(WmsLogTag::WMS_LIFE, "id:%{public}d Destroy, state:%{public}u, needNotifyServer:%{public}d, "
267         "needClearListener:%{public}d", GetPersistentId(), state_, needNotifyServer, needClearListener);
268 
269     auto usage = property_->GetUIExtensionUsage();
270     if ((usage == UIExtensionUsage::MODAL) || SessionHelper::IsSecureUIExtension(usage)) {
271         InputTransferStation::GetInstance().RemoveInputWindow(GetPersistentId());
272     }
273 
274     if (IsWindowSessionInvalid()) {
275         TLOGE(WmsLogTag::WMS_LIFE, "session is invalid");
276         return WMError::WM_ERROR_INVALID_WINDOW;
277     }
278     if (auto hostSession = GetHostSession()) {
279         TLOGI(WmsLogTag::WMS_LIFE, "Disconnect with host session, id: %{public}d.", GetPersistentId());
280         hostSession->Disconnect();
281     }
282     NotifyBeforeDestroy(GetWindowName());
283     if (needClearListener) {
284         ClearListenersById(GetPersistentId());
285     }
286     {
287         std::lock_guard<std::recursive_mutex> lock(mutex_);
288         state_ = WindowState::STATE_DESTROYED;
289         requestState_ = WindowState::STATE_DESTROYED;
290     }
291     DestroySubWindow();
292     {
293         TLOGI(WmsLogTag::WMS_LIFE, "Reset state, id: %{public}d.", GetPersistentId());
294         std::lock_guard<std::mutex> lock(hostSessionMutex_);
295         hostSession_ = nullptr;
296     }
297     {
298         std::unique_lock<std::shared_mutex> lock(windowExtensionSessionMutex_);
299         GetWindowExtensionSessionSet().erase(this);
300     }
301     // Notify host window to remove rect change listeners
302     AAFwk::Want want;
303     auto ret = SendExtensionMessageToHost(
304         static_cast<uint32_t>(Extension::Businesscode::UNREGISTER_HOST_WINDOW_RECT_CHANGE_LISTENER), want);
305     if (ret != WMError::WM_OK) {
306         TLOGE(WmsLogTag::WMS_UIEXT, "Send unregister host window rect change listener message failed, errCode: "
307             "%{public}d", ret);
308     }
309     TLOGI(WmsLogTag::WMS_LIFE, "Erase in set, id: %{public}d.", GetPersistentId());
310     if (context_) {
311         context_.reset();
312     }
313     ClearVsyncStation();
314     SetUIContentComplete();
315     SetUIExtensionDestroyComplete();
316     RemoveExtensionWindowStageFromSCB(property_->IsConstrainedModal());
317     dataHandler_->SetRemoteProxyObject(nullptr);
318     TLOGI(WmsLogTag::WMS_LIFE, "Destroyed success, id: %{public}d.", GetPersistentId());
319     return WMError::WM_OK;
320 }
321 
MoveTo(int32_t x,int32_t y,bool isMoveToGlobal,MoveConfiguration moveConfiguration)322 WMError WindowExtensionSessionImpl::MoveTo(int32_t x, int32_t y,
323     bool isMoveToGlobal, MoveConfiguration moveConfiguration)
324 {
325     TLOGD(WmsLogTag::WMS_UIEXT, "Id:%{public}d xy %{public}d %{public}d isMoveToGlobal %{public}d "
326         "moveConfiguration %{public}s", property_->GetPersistentId(), x, y, isMoveToGlobal,
327         moveConfiguration.ToString().c_str());
328     if (IsWindowSessionInvalid()) {
329         WLOGFE("Window session invalid.");
330         return WMError::WM_ERROR_INVALID_WINDOW;
331     }
332     const auto& rect = property_->GetWindowRect();
333     WSRect wsRect = { x, y, rect.width_, rect.height_ };
334     WSError error = UpdateRect(wsRect, SizeChangeReason::MOVE);
335     return static_cast<WMError>(error);
336 }
337 
Resize(uint32_t width,uint32_t height,const RectAnimationConfig & rectAnimationConfig)338 WMError WindowExtensionSessionImpl::Resize(uint32_t width, uint32_t height,
339     const RectAnimationConfig& rectAnimationConfig)
340 {
341     WLOGFD("Id:%{public}d wh %{public}u %{public}u", property_->GetPersistentId(), width, height);
342     if (IsWindowSessionInvalid()) {
343         WLOGFE("Window session invalid.");
344         return WMError::WM_ERROR_INVALID_WINDOW;
345     }
346     const auto& rect = property_->GetWindowRect();
347     WSRect wsRect = { rect.posX_, rect.posY_, width, height };
348     WSError error = UpdateRect(wsRect, SizeChangeReason::RESIZE);
349     return static_cast<WMError>(error);
350 }
351 
TransferAbilityResult(uint32_t resultCode,const AAFwk::Want & want)352 WMError WindowExtensionSessionImpl::TransferAbilityResult(uint32_t resultCode, const AAFwk::Want& want)
353 {
354     TLOGI(WmsLogTag::WMS_UIEXT, "id: %{public}d", GetPersistentId());
355     if (IsWindowSessionInvalid()) {
356         WLOGFE("Window invalid.");
357         return WMError::WM_ERROR_REPEAT_OPERATION;
358     }
359     auto hostSession = GetHostSession();
360     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_INVALID_WINDOW);
361     return static_cast<WMError>(hostSession->TransferAbilityResult(resultCode, want));
362 }
363 
TransferExtensionData(const AAFwk::WantParams & wantParams)364 WMError WindowExtensionSessionImpl::TransferExtensionData(const AAFwk::WantParams& wantParams)
365 {
366     TLOGD(WmsLogTag::WMS_UIEXT, "id: %{public}d", GetPersistentId());
367     if (IsWindowSessionInvalid()) {
368         WLOGFE("Window invalid.");
369         return WMError::WM_ERROR_REPEAT_OPERATION;
370     }
371     auto hostSession = GetHostSession();
372     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_INVALID_WINDOW);
373     auto ret = hostSession->TransferExtensionData(wantParams);
374     if (ret == ERR_NONE) {
375         return WMError::WM_OK;
376     }
377     if (context_ != nullptr) {
378         std::ostringstream oss;
379         oss << "TransferExtensionData from provider to host failed" << ",";
380         oss << " provider bundleName: " << context_->GetBundleName() << ",";
381         oss << " provider windowName: " << property_->GetWindowName() << ",";
382         oss << " errorCode: " << static_cast<int32_t>(ret) << ";";
383         int32_t res = WindowInfoReporter::GetInstance().ReportUIExtensionException(
384             static_cast<int32_t>(WindowDFXHelperType::WINDOW_UIEXTENSION_TRANSFER_DATA_FAIL),
385             getpid(), GetPersistentId(), oss.str()
386         );
387         if (res != 0) {
388             TLOGE(WmsLogTag::WMS_UIEXT, "ReportUIExtensionException message failed, res: %{public}d", res);
389         }
390     }
391     return WMError::WM_ERROR_IPC_FAILED;
392 }
393 
RegisterTransferComponentDataListener(const NotifyTransferComponentDataFunc & func)394 void WindowExtensionSessionImpl::RegisterTransferComponentDataListener(const NotifyTransferComponentDataFunc& func)
395 {
396     if (IsWindowSessionInvalid()) {
397         WLOGFE("Window invalid.");
398         return;
399     }
400     notifyTransferComponentDataFunc_ = std::move(func);
401     auto hostSession = GetHostSession();
402     CHECK_HOST_SESSION_RETURN_IF_NULL(hostSession);
403     hostSession->NotifyAsyncOn();
404 }
405 
NotifyTransferComponentData(const AAFwk::WantParams & wantParams)406 WSError WindowExtensionSessionImpl::NotifyTransferComponentData(const AAFwk::WantParams& wantParams)
407 {
408     TLOGD(WmsLogTag::WMS_UIEXT, "id: %{public}d", GetPersistentId());
409     if (notifyTransferComponentDataFunc_) {
410         notifyTransferComponentDataFunc_(wantParams);
411     }
412     return WSError::WS_OK;
413 }
414 
NotifyTransferComponentDataSync(const AAFwk::WantParams & wantParams,AAFwk::WantParams & reWantParams)415 WSErrorCode WindowExtensionSessionImpl::NotifyTransferComponentDataSync(
416     const AAFwk::WantParams& wantParams, AAFwk::WantParams& reWantParams)
417 {
418     TLOGI(WmsLogTag::WMS_UIEXT, "id: %{public}d", GetPersistentId());
419     if (notifyTransferComponentDataForResultFunc_) {
420         reWantParams = notifyTransferComponentDataForResultFunc_(wantParams);
421         return WSErrorCode::WS_OK;
422     }
423     return WSErrorCode::WS_ERROR_NOT_REGISTER_SYNC_CALLBACK;
424 }
425 
RegisterTransferComponentDataForResultListener(const NotifyTransferComponentDataForResultFunc & func)426 void WindowExtensionSessionImpl::RegisterTransferComponentDataForResultListener(
427     const NotifyTransferComponentDataForResultFunc& func)
428 {
429     if (IsWindowSessionInvalid()) {
430         WLOGFE("session invalid.");
431         return;
432     }
433     notifyTransferComponentDataForResultFunc_ = std::move(func);
434     auto hostSession = GetHostSession();
435     CHECK_HOST_SESSION_RETURN_IF_NULL(hostSession);
436     hostSession->NotifySyncOn();
437 }
438 
RegisterHostWindowRectChangeListener(const sptr<IWindowRectChangeListener> & listener)439 WMError WindowExtensionSessionImpl::RegisterHostWindowRectChangeListener(
440     const sptr<IWindowRectChangeListener>& listener)
441 {
442     AAFwk::Want dataToSend;
443     auto ret = SendExtensionMessageToHost(
444         static_cast<uint32_t>(Extension::Businesscode::REGISTER_HOST_WINDOW_RECT_CHANGE_LISTENER), dataToSend);
445     if (ret != WMError::WM_OK) {
446         return ret;
447     }
448     {
449         std::lock_guard<std::mutex> lockListener(hostWindowRectChangeListenerMutex_);
450         ret = RegisterListener(hostWindowRectChangeListener_, listener);
451     }
452     return ret;
453 }
454 
UnregisterHostWindowRectChangeListener(const sptr<IWindowRectChangeListener> & listener)455 WMError WindowExtensionSessionImpl::UnregisterHostWindowRectChangeListener(
456     const sptr<IWindowRectChangeListener>& listener)
457 {
458     WMError ret = WMError::WM_OK;
459     bool isHostWindowRectChangeListenerEmpty = false;
460     size_t hostWindowRectChangeListenerSize = 0;
461     {
462         std::lock_guard<std::mutex> lockListener(hostWindowRectChangeListenerMutex_);
463         ret = UnregisterListener(hostWindowRectChangeListener_, listener);
464         if (ret != WMError::WM_OK) {
465             return ret;
466         }
467         isHostWindowRectChangeListenerEmpty = hostWindowRectChangeListener_.empty();
468         hostWindowRectChangeListenerSize = hostWindowRectChangeListener_.size();
469     }
470     if (!isHostWindowRectChangeListenerEmpty || !rectChangeUIExtListenerIds_.empty()) {
471         TLOGI(WmsLogTag::WMS_UIEXT, "No need to send message to host to unregister, size of "
472             "hostWindowRectChangeListener_: %{public}zu, size of rectChangeUIExtListenerIds_: %{public}zu",
473             hostWindowRectChangeListenerSize, rectChangeUIExtListenerIds_.size());
474         return ret;
475     }
476     AAFwk::Want dataToSend;
477     ret = SendExtensionMessageToHost(
478         static_cast<uint32_t>(Extension::Businesscode::UNREGISTER_HOST_WINDOW_RECT_CHANGE_LISTENER), dataToSend);
479     return ret;
480 }
481 
RegisterKeyboardDidShowListener(const sptr<IKeyboardDidShowListener> & listener)482 WMError WindowExtensionSessionImpl::RegisterKeyboardDidShowListener(const sptr<IKeyboardDidShowListener>& listener)
483 {
484     TLOGD(WmsLogTag::WMS_KEYBOARD, "in");
485     AAFwk::Want want;
486     auto ret = SendExtensionMessageToHost(
487         static_cast<uint32_t>(Extension::Businesscode::REGISTER_KEYBOARD_DID_SHOW_LISTENER), want);
488     if (ret != WMError::WM_OK) {
489         TLOGE(WmsLogTag::WMS_UIEXT, "Send register listener message failed, errCode: %{public}d", ret);
490         return ret;
491     }
492     std::lock_guard<std::mutex> lockListener(keyboardDidShowListenerMutex_);
493     ret = RegisterListener(keyboardDidShowListenerList_, listener);
494     return ret;
495 }
496 
UnregisterKeyboardDidShowListener(const sptr<IKeyboardDidShowListener> & listener)497 WMError WindowExtensionSessionImpl::UnregisterKeyboardDidShowListener(const sptr<IKeyboardDidShowListener>& listener)
498 {
499     TLOGD(WmsLogTag::WMS_KEYBOARD, "in");
500     WMError ret = WMError::WM_OK;
501     bool needNotifyHost = false;
502     {
503         std::lock_guard<std::mutex> lockListener(keyboardDidShowListenerMutex_);
504         ret = UnregisterListener(keyboardDidShowListenerList_, listener);
505         if (ret != WMError::WM_OK) {
506             return ret;
507         }
508         needNotifyHost = keyboardDidShowListenerList_.empty() && keyboardDidShowUIExtListeners_.empty();
509     }
510     if (needNotifyHost) {
511         AAFwk::Want want;
512         ret = SendExtensionMessageToHost(
513             static_cast<uint32_t>(Extension::Businesscode::UNREGISTER_KEYBOARD_DID_SHOW_LISTENER), want);
514     }
515     return ret;
516 }
517 
RegisterKeyboardDidHideListener(const sptr<IKeyboardDidHideListener> & listener)518 WMError WindowExtensionSessionImpl::RegisterKeyboardDidHideListener(const sptr<IKeyboardDidHideListener>& listener)
519 {
520     TLOGD(WmsLogTag::WMS_KEYBOARD, "in");
521     AAFwk::Want want;
522     auto ret = SendExtensionMessageToHost(
523         static_cast<uint32_t>(Extension::Businesscode::REGISTER_KEYBOARD_DID_HIDE_LISTENER), want);
524     if (ret != WMError::WM_OK) {
525         TLOGE(WmsLogTag::WMS_UIEXT, "Send register listener message failed, errCode: %{public}d", ret);
526         return ret;
527     }
528     std::lock_guard<std::mutex> lockListener(keyboardDidHideListenerMutex_);
529     ret = RegisterListener(keyboardDidHideListenerList_, listener);
530     return ret;
531 }
532 
UnregisterKeyboardDidHideListener(const sptr<IKeyboardDidHideListener> & listener)533 WMError WindowExtensionSessionImpl::UnregisterKeyboardDidHideListener(const sptr<IKeyboardDidHideListener>& listener)
534 {
535     TLOGD(WmsLogTag::WMS_KEYBOARD, "in");
536     WMError ret = WMError::WM_OK;
537     bool needNotifyHost = false;
538     {
539         std::lock_guard<std::mutex> lockListener(keyboardDidHideListenerMutex_);
540         ret = UnregisterListener(keyboardDidHideListenerList_, listener);
541         if (ret != WMError::WM_OK) {
542             return ret;
543         }
544         needNotifyHost = keyboardDidHideListenerList_.empty() && keyboardDidHideUIExtListeners_.empty();
545     }
546     if (needNotifyHost) {
547         AAFwk::Want want;
548         ret = SendExtensionMessageToHost(
549             static_cast<uint32_t>(Extension::Businesscode::UNREGISTER_KEYBOARD_DID_HIDE_LISTENER), want);
550     }
551     return ret;
552 }
553 
TriggerBindModalUIExtension()554 void WindowExtensionSessionImpl::TriggerBindModalUIExtension()
555 {
556     TLOGI(WmsLogTag::WMS_UIEXT, "id: %{public}d", GetPersistentId());
557     auto hostSession = GetHostSession();
558     CHECK_HOST_SESSION_RETURN_IF_NULL(hostSession);
559     hostSession->TriggerBindModalUIExtension();
560 }
561 
SetPrivacyMode(bool isPrivacyMode)562 WMError WindowExtensionSessionImpl::SetPrivacyMode(bool isPrivacyMode)
563 {
564     TLOGI(WmsLogTag::WMS_UIEXT, "Id: %{public}u, isPrivacyMode: %{public}u", GetPersistentId(),
565         isPrivacyMode);
566     if (surfaceNode_ == nullptr) {
567         TLOGE(WmsLogTag::WMS_UIEXT, "surfaceNode is nullptr");
568         return WMError::WM_ERROR_NULLPTR;
569     }
570     surfaceNode_->SetSecurityLayer(isPrivacyMode);
571     RSTransactionAdapter::FlushImplicitTransaction(surfaceNode_);
572 
573     if (state_ != WindowState::STATE_SHOWN) {
574         extensionWindowFlags_.privacyModeFlag = isPrivacyMode;
575         return WMError::WM_OK;
576     }
577     if (isPrivacyMode == extensionWindowFlags_.privacyModeFlag) {
578         return WMError::WM_OK;
579     }
580 
581     auto updateFlags = extensionWindowFlags_;
582     updateFlags.privacyModeFlag = isPrivacyMode;
583     ExtensionWindowFlags actions(0);
584     actions.privacyModeFlag = true;
585     auto ret = UpdateExtWindowFlags(updateFlags, actions);
586     if (ret == WMError::WM_OK) {
587         extensionWindowFlags_ = updateFlags;
588     }
589     return ret;
590 }
591 
HidePrivacyContentForHost(bool needHide)592 WMError WindowExtensionSessionImpl::HidePrivacyContentForHost(bool needHide)
593 {
594     auto persistentId = GetPersistentId();
595     std::stringstream ss;
596     ss << "ID: " << persistentId << ", needHide: " << needHide;
597 
598     if (surfaceNode_ == nullptr) {
599         TLOGI(WmsLogTag::WMS_UIEXT, "surfaceNode is null, %{public}s", ss.str().c_str());
600         return WMError::WM_ERROR_NULLPTR;
601     }
602 
603     // Let rs guarantee the security and permissions of the interface
604     auto errCode = surfaceNode_->SetHidePrivacyContent(needHide);
605     TLOGI(WmsLogTag::WMS_UIEXT, "Notify Render Service client finished, %{public}s, err: %{public}u", ss.str().c_str(),
606           errCode);
607     if (errCode == RSInterfaceErrorCode::NONSYSTEM_CALLING) { // not system app calling
608         return WMError::WM_ERROR_NOT_SYSTEM_APP;
609     } else if (errCode != RSInterfaceErrorCode::NO_ERROR) { // other error
610         return WMError::WM_ERROR_SYSTEM_ABNORMALLY;
611     }
612 
613     return WMError::WM_OK;
614 }
615 
IsComponentFocused() const616 bool WindowExtensionSessionImpl::IsComponentFocused() const
617 {
618     if (IsWindowSessionInvalid() || focusState_ == std::nullopt) {
619         TLOGE(WmsLogTag::WMS_FOCUS, "Session is invalid");
620         return false;
621     }
622     TLOGD(WmsLogTag::WMS_FOCUS, "window id=%{public}d, isFocused=%{public}d",
623         GetPersistentId(), static_cast<int32_t>(focusState_.value()));
624     return focusState_.value();
625 }
626 
NotifyFocusStateEvent(bool focusState)627 void WindowExtensionSessionImpl::NotifyFocusStateEvent(bool focusState)
628 {
629     if (auto uiContent = GetUIContentSharedPtr()) {
630         focusState ? uiContent->Focus() : uiContent->UnFocus();
631     }
632     if (focusState) {
633         NotifyWindowAfterFocused();
634     } else {
635         NotifyWindowAfterUnfocused();
636     }
637     focusState_ = focusState;
638     if (focusState_ != std::nullopt) {
639         TLOGI(WmsLogTag::WMS_FOCUS, "[%{public}d,%{public}d]",
640             GetPersistentId(), static_cast<int32_t>(focusState_.value()));
641     }
642 }
643 
NotifyFocusActiveEvent(bool isFocusActive)644 void WindowExtensionSessionImpl::NotifyFocusActiveEvent(bool isFocusActive)
645 {
646     if (auto uiContent = GetUIContentSharedPtr()) {
647         uiContent->SetIsFocusActive(isFocusActive);
648     }
649 }
650 
NotifyBackpressedEvent(bool & isConsumed)651 void WindowExtensionSessionImpl::NotifyBackpressedEvent(bool& isConsumed)
652 {
653     if (auto uiContent = GetUIContentSharedPtr()) {
654         WLOGFD("Transfer backpressed event to uiContent");
655         isConsumed = uiContent->ProcessBackPressed();
656     }
657     WLOGFD("Backpressed event is consumed %{public}d", isConsumed);
658 }
659 
InputMethodKeyEventResultCallback(const std::shared_ptr<MMI::KeyEvent> & keyEvent,bool consumed,std::shared_ptr<std::promise<bool>> isConsumedPromise,std::shared_ptr<bool> isTimeout)660 void WindowExtensionSessionImpl::InputMethodKeyEventResultCallback(const std::shared_ptr<MMI::KeyEvent>& keyEvent,
661     bool consumed, std::shared_ptr<std::promise<bool>> isConsumedPromise, std::shared_ptr<bool> isTimeout)
662 {
663     if (keyEvent == nullptr) {
664         WLOGFW("keyEvent is null, consumed:%{public}" PRId32, consumed);
665         if (isConsumedPromise != nullptr) {
666             isConsumedPromise->set_value(consumed);
667         }
668         return;
669     }
670 
671     auto id = keyEvent->GetId();
672     if (isConsumedPromise == nullptr || isTimeout == nullptr) {
673         WLOGFW("Shared point isConsumedPromise or isTimeout is null, id:%{public}" PRId32, id);
674         keyEvent->MarkProcessed();
675         return;
676     }
677 
678     if (*isTimeout) {
679         WLOGFW("DispatchKeyEvent timeout id:%{public}" PRId32, id);
680         keyEvent->MarkProcessed();
681         return;
682     }
683 
684     if (consumed) {
685         isConsumedPromise->set_value(consumed);
686         WLOGD("Input method has processed key event, id:%{public}" PRId32, id);
687         return;
688     }
689 
690     bool isConsumed = false;
691     DispatchKeyEventCallback(const_cast<std::shared_ptr<MMI::KeyEvent>&>(keyEvent), isConsumed);
692     isConsumedPromise->set_value(isConsumed);
693 }
694 
NotifyKeyEvent(const std::shared_ptr<MMI::KeyEvent> & keyEvent,bool & isConsumed,bool notifyInputMethod)695 void WindowExtensionSessionImpl::NotifyKeyEvent(const std::shared_ptr<MMI::KeyEvent>& keyEvent, bool& isConsumed,
696     bool notifyInputMethod)
697 {
698     if (keyEvent == nullptr) {
699         WLOGFE("keyEvent is nullptr");
700         return;
701     }
702     if (property_->GetUIExtensionUsage() == UIExtensionUsage::PREVIEW_EMBEDDED) {
703         TLOGD(WmsLogTag::WMS_EVENT, "Preview uiext does not handle event, eid:%{public}d", keyEvent->GetId());
704         return;
705     }
706 
707 #ifdef IMF_ENABLE
708     bool isKeyboardEvent = IsKeyboardEvent(keyEvent);
709     if (isKeyboardEvent && notifyInputMethod) {
710         WLOGD("Async dispatch keyEvent to input method, id:%{public}" PRId32, keyEvent->GetId());
711         auto isConsumedPromise = std::make_shared<std::promise<bool>>();
712         auto isConsumedFuture = isConsumedPromise->get_future().share();
713         auto isTimeout = std::make_shared<bool>(false);
714         auto ret = MiscServices::InputMethodController::GetInstance()->DispatchKeyEvent(keyEvent,
715             [weakThis = wptr(this), isConsumedPromise, isTimeout](const std::shared_ptr<MMI::KeyEvent>& keyEvent,
716                 bool consumed) {
717                 auto window = weakThis.promote();
718                 if (window == nullptr) {
719                     TLOGNE(WmsLogTag::WMS_UIEXT, "window is nullptr");
720                     return;
721                 }
722                 window->InputMethodKeyEventResultCallback(keyEvent, consumed, isConsumedPromise, isTimeout);
723             });
724         if (ret != 0) {
725             WLOGFW("DispatchKeyEvent failed, ret:%{public}" PRId32 ", id:%{public}" PRId32, ret, keyEvent->GetId());
726             DispatchKeyEventCallback(keyEvent, isConsumed);
727             return;
728         }
729         if (isConsumedFuture.wait_for(std::chrono::milliseconds(DISPATCH_KEY_EVENT_TIMEOUT_TIME_MS)) ==
730             std::future_status::timeout) {
731             *isTimeout = true;
732             isConsumed = true;
733             WLOGFE("DispatchKeyEvent timeout, id:%{public}" PRId32, keyEvent->GetId());
734         } else {
735             isConsumed = isConsumedFuture.get();
736         }
737         WLOGFD("Input Method DispatchKeyEvent isConsumed:%{public}" PRId32, isConsumed);
738         return;
739     }
740 #endif // IMF_ENABLE
741     DispatchKeyEventCallback(keyEvent, isConsumed);
742 }
743 
ArkUIFrameworkSupport()744 void WindowExtensionSessionImpl::ArkUIFrameworkSupport()
745 {
746     uint32_t version = 0;
747     if ((context_ != nullptr) && (context_->GetApplicationInfo() != nullptr)) {
748         version = context_->GetApplicationInfo()->apiCompatibleVersion;
749     }
750     // 10 ArkUI new framework support after API10
751     if (version < 10) {
752         SetLayoutFullScreenByApiVersion(isIgnoreSafeArea_);
753         if (!isSystembarPropertiesSet_) {
754             SetSystemBarProperty(WindowType::WINDOW_TYPE_STATUS_BAR, SystemBarProperty());
755         }
756     } else if (isIgnoreSafeAreaNeedNotify_) {
757         SetLayoutFullScreenByApiVersion(isIgnoreSafeArea_);
758     }
759 }
760 
UIContentCreate(AppExecFwk::Ability * ability,void * env,int isAni)761 std::unique_ptr<Ace::UIContent> WindowExtensionSessionImpl::UIContentCreate(AppExecFwk::Ability* ability, void* env,
762     int isAni)
763 {
764     if (isAni) {
765         return  ability != nullptr ? Ace::UIContent::Create(ability) :
766             Ace::UIContent::CreateWithAniEnv(context_.get(), reinterpret_cast<ani_env*>(env));
767     } else {
768         return  ability != nullptr ? Ace::UIContent::Create(ability) :
769             Ace::UIContent::Create(context_.get(), reinterpret_cast<NativeEngine*>(env));
770     }
771 }
772 
NapiSetUIContent(const std::string & contentInfo,ani_env * env,ani_object storage,BackupAndRestoreType type,sptr<IRemoteObject> token,AppExecFwk::Ability * ability)773 WMError WindowExtensionSessionImpl::NapiSetUIContent(const std::string& contentInfo, ani_env* env, ani_object storage,
774     BackupAndRestoreType type, sptr<IRemoteObject> token, AppExecFwk::Ability* ability)
775 {
776     return NapiSetUIContentInner(contentInfo, env, storage, type, token, ability, 1);
777 }
778 
NapiSetUIContent(const std::string & contentInfo,napi_env env,napi_value storage,BackupAndRestoreType type,sptr<IRemoteObject> token,AppExecFwk::Ability * ability)779 WMError WindowExtensionSessionImpl::NapiSetUIContent(const std::string& contentInfo, napi_env env, napi_value storage,
780     BackupAndRestoreType type, sptr<IRemoteObject> token, AppExecFwk::Ability* ability)
781 {
782     return NapiSetUIContentInner(contentInfo, env, storage, type, token, ability, 0);
783 }
784 
NapiSetUIContentInner(const std::string & contentInfo,void * env,void * storage,BackupAndRestoreType type,sptr<IRemoteObject> token,AppExecFwk::Ability * ability,int isAni)785 WMError WindowExtensionSessionImpl::NapiSetUIContentInner(const std::string& contentInfo, void* env, void* storage,
786     BackupAndRestoreType type, sptr<IRemoteObject> token, AppExecFwk::Ability* ability, int isAni)
787 {
788     return SetUIContentInner(contentInfo, env, storage, token, ability, false, isAni);
789 }
790 
NapiSetUIContentByName(const std::string & contentName,napi_env env,napi_value storage,BackupAndRestoreType type,sptr<IRemoteObject> token,AppExecFwk::Ability * ability)791 WMError WindowExtensionSessionImpl::NapiSetUIContentByName(const std::string& contentName, napi_env env,
792     napi_value storage, BackupAndRestoreType type, sptr<IRemoteObject> token, AppExecFwk::Ability* ability)
793 {
794     TLOGI(WmsLogTag::WMS_UIEXT, "name: %{public}s", contentName.c_str());
795     return SetUIContentInner(contentName, env, storage, token, ability, true);
796 }
797 
SetUIContentInner(const std::string & contentInfo,void * env,void * storage,sptr<IRemoteObject> token,AppExecFwk::Ability * ability,bool initByName,int isAni)798 WMError WindowExtensionSessionImpl::SetUIContentInner(const std::string& contentInfo, void* env, void* storage,
799     sptr<IRemoteObject> token, AppExecFwk::Ability* ability, bool initByName, int isAni)
800 {
801     WLOGFD("%{public}s state:%{public}u", contentInfo.c_str(), state_);
802     if (auto uiContent = GetUIContentSharedPtr()) {
803         uiContent->Destroy();
804     }
805     {
806         std::unique_ptr<Ace::UIContent> uiContent = UIContentCreate(ability, (void*)env, isAni);
807         if (uiContent == nullptr) {
808             WLOGFE("failed, id: %{public}d", GetPersistentId());
809             return WMError::WM_ERROR_NULLPTR;
810         }
811         uiContent->SetParentToken(token);
812         auto usage = property_->GetUIExtensionUsage();
813         if (usage == UIExtensionUsage::CONSTRAINED_EMBEDDED) {
814             uiContent->SetUIContentType(Ace::UIContentType::SECURITY_UI_EXTENSION);
815         } else if (usage == UIExtensionUsage::EMBEDDED) {
816             uiContent->SetUIContentType(Ace::UIContentType::UI_EXTENSION);
817         } else if (usage == UIExtensionUsage::MODAL) {
818             uiContent->SetUIContentType(Ace::UIContentType::MODAL_UI_EXTENSION);
819         } else if (usage == UIExtensionUsage::PREVIEW_EMBEDDED) {
820             uiContent->SetUIContentType(Ace::UIContentType::PREVIEW_UI_EXTENSION);
821         }
822         uiContent->SetHostParams(extensionConfig_);
823         if (initByName) {
824             if (isAni) {
825                 uiContent->InitializeByNameWithAniStorage(this, contentInfo, (ani_object)storage);
826             } else {
827                 uiContent->InitializeByName(this, contentInfo, (napi_value)storage, property_->GetParentId());
828             }
829         } else {
830             if (isAni) {
831                 uiContent->InitializeWithAniStorage(this, contentInfo, (ani_object)storage, property_->GetParentId());
832             } else {
833                 uiContent->Initialize(this, contentInfo, (napi_value)storage, property_->GetParentId());
834             }
835         }
836         // make uiContent available after Initialize/Restore
837         std::unique_lock<std::shared_mutex> lock(uiContentMutex_);
838         uiContent_ = std::move(uiContent);
839     }
840     SetUIContentComplete();
841     NotifyModalUIExtensionMayBeCovered(true);
842 
843     UpdateAccessibilityTreeInfo();
844     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
845     if (uiContent == nullptr) {
846         TLOGE(WmsLogTag::DEFAULT, "uiContent is nullptr.");
847         return WMError::WM_ERROR_NULLPTR;
848     }
849     if (focusState_ != std::nullopt) {
850         focusState_.value() ? uiContent->Focus() : uiContent->UnFocus();
851     }
852     ArkUIFrameworkSupport();
853     UpdateDecorEnable(true);
854     if (state_ == WindowState::STATE_SHOWN) {
855         // UIContent may be nullptr when show window, need to notify again when window is shown
856         uiContent->Foreground();
857         UpdateTitleButtonVisibility();
858     }
859     UpdateViewportConfig(GetRect(), WindowSizeChangeReason::UNDEFINED);
860     WLOGFD("notify uiContent window size change end");
861     return WMError::WM_OK;
862 }
863 
UpdateRect(const WSRect & rect,SizeChangeReason reason,const SceneAnimationConfig & config,const std::map<AvoidAreaType,AvoidArea> & avoidAreas)864 WSError WindowExtensionSessionImpl::UpdateRect(const WSRect& rect, SizeChangeReason reason,
865     const SceneAnimationConfig& config, const std::map<AvoidAreaType, AvoidArea>& avoidAreas)
866 {
867     auto wmReason = static_cast<WindowSizeChangeReason>(reason);
868     Rect wmRect = {rect.posX_, rect.posY_, rect.width_, rect.height_};
869     auto preRect = GetRect();
870     if (rect.width_ == static_cast<int>(preRect.width_) && rect.height_ == static_cast<int>(preRect.height_)) {
871         WLOGFD("EQ [%{public}d, %{public}d, reason: %{public}d]", rect.width_,
872             rect.height_, static_cast<int>(reason));
873     } else {
874         WLOGFI("[%{public}d, %{public}d, reason: %{public}d]", rect.width_,
875             rect.height_, static_cast<int>(reason));
876     }
877     property_->SetWindowRect(wmRect);
878 
879     if (property_->GetUIExtensionUsage() == UIExtensionUsage::MODAL) {
880         if (!abilityToken_) {
881             TLOGE(WmsLogTag::WMS_UIEXT, "token is nullptr");
882             return WSError::WS_ERROR_NULLPTR;
883         }
884         SingletonContainer::Get<WindowAdapter>().UpdateModalExtensionRect(abilityToken_, wmRect);
885     }
886 
887     if (wmReason == WindowSizeChangeReason::ROTATION || wmReason == WindowSizeChangeReason::SNAPSHOT_ROTATION) {
888         const std::shared_ptr<RSTransaction>& rsTransaction = config.rsTransaction_;
889         UpdateRectForRotation(wmRect, preRect, wmReason, rsTransaction, avoidAreas);
890     } else if (handler_ != nullptr) {
891         UpdateRectForOtherReason(wmRect, wmReason, avoidAreas);
892     } else {
893         NotifySizeChange(wmRect, wmReason);
894         UpdateViewportConfig(wmRect, wmReason, nullptr, nullptr, avoidAreas);
895     }
896     return WSError::WS_OK;
897 }
898 
UpdateRectForRotation(const Rect & wmRect,const Rect & preRect,WindowSizeChangeReason wmReason,const std::shared_ptr<RSTransaction> & rsTransaction,const std::map<AvoidAreaType,AvoidArea> & avoidAreas)899 void WindowExtensionSessionImpl::UpdateRectForRotation(const Rect& wmRect, const Rect& preRect,
900     WindowSizeChangeReason wmReason, const std::shared_ptr<RSTransaction>& rsTransaction,
901     const std::map<AvoidAreaType, AvoidArea>& avoidAreas)
902 {
903     if (!handler_) {
904         return;
905     }
906     auto task = [weak = wptr(this), wmReason, wmRect, preRect, rsTransaction, avoidAreas]() mutable {
907         HITRACE_METER_NAME(HITRACE_TAG_WINDOW_MANAGER, "WindowExtensionSessionImpl::UpdateRectForRotation");
908         auto window = weak.promote();
909         if (!window) {
910             return;
911         }
912         int32_t duration = UIEXTENTION_ROTATION_ANIMATION_TIME;
913         bool needSync = false;
914         if (rsTransaction && rsTransaction->GetSyncId() > 0) {
915             // extract high 32 bits of SyncId as pid
916             auto SyncTransactionPid = static_cast<int32_t>(rsTransaction->GetSyncId() >> 32);
917             if (rsTransaction->IsOpenSyncTransaction() || SyncTransactionPid != rsTransaction->GetParentPid()) {
918                 needSync = true;
919             }
920         }
921 
922         auto rsUIContext = window->GetRSUIContext();
923         if (needSync) {
924             window->UpdateRotateDuration(wmReason, duration, rsTransaction);
925             RSTransactionAdapter::FlushImplicitTransaction(rsUIContext);
926             rsTransaction->Begin();
927         }
928         window->rotationAnimationCount_++;
929         RSAnimationTimingProtocol protocol;
930         protocol.SetDuration(duration);
931         // animation curve: cubic [0.2, 0.0, 0.2, 1.0]
932         auto curve = RSAnimationTimingCurve::CreateCubicCurve(0.2, 0.0, 0.2, 1.0);
933         RSNode::OpenImplicitAnimation(rsUIContext, protocol, curve, [weak]() {
934             auto window = weak.promote();
935             if (!window) {
936                 return;
937             }
938             window->rotationAnimationCount_--;
939             if (window->rotationAnimationCount_ == 0) {
940                 window->NotifyRotationAnimationEnd();
941             }
942         });
943         if (wmRect != preRect) {
944             window->NotifySizeChange(wmRect, wmReason);
945         }
946         window->UpdateViewportConfig(wmRect, wmReason, rsTransaction, nullptr, avoidAreas);
947         RSNode::CloseImplicitAnimation(rsUIContext);
948         if (needSync) {
949             rsTransaction->Commit();
950         } else {
951             RSTransactionAdapter::FlushImplicitTransaction(rsUIContext);
952         }
953     };
954     handler_->PostTask(task, "WMS_WindowExtensionSessionImpl_UpdateRectForRotation");
955 }
956 
UpdateRotateDuration(WindowSizeChangeReason & reason,int32_t & duration,const std::shared_ptr<RSTransaction> & rsTransaction)957 void WindowExtensionSessionImpl::UpdateRotateDuration(WindowSizeChangeReason& reason, int32_t& duration,
958     const std::shared_ptr<RSTransaction>& rsTransaction)
959 {
960     if (reason == WindowSizeChangeReason::SNAPSHOT_ROTATION) {
961         duration = rsTransaction->GetDuration();
962         reason = WindowSizeChangeReason::ROTATION;
963     } else {
964         duration = rsTransaction->GetDuration() ? rsTransaction->GetDuration() : duration;
965     }
966 }
967 
UpdateRectForOtherReason(const Rect & wmRect,WindowSizeChangeReason wmReason,const std::map<AvoidAreaType,AvoidArea> & avoidAreas)968 void WindowExtensionSessionImpl::UpdateRectForOtherReason(const Rect& wmRect, WindowSizeChangeReason wmReason,
969     const std::map<AvoidAreaType, AvoidArea>& avoidAreas)
970 {
971     auto task = [weak = wptr(this), wmReason, wmRect, avoidAreas] {
972         auto window = weak.promote();
973         if (!window) {
974             TLOGE(WmsLogTag::WMS_LAYOUT, "window is null, updateViewPortConfig failed");
975             return;
976         }
977         window->NotifySizeChange(wmRect, wmReason);
978         window->UpdateViewportConfig(wmRect, wmReason, nullptr, nullptr, avoidAreas);
979     };
980     if (handler_) {
981         handler_->PostTask(task, "WMS_WindowExtensionSessionImpl_UpdateRectForOtherReason");
982     }
983 }
984 
GetSystemViewportConfig(SessionViewportConfig & config)985 WMError WindowExtensionSessionImpl::GetSystemViewportConfig(SessionViewportConfig& config)
986 {
987     config.displayId_ = property_->GetDisplayId();
988     auto display = SingletonContainer::Get<DisplayManager>().GetDisplayById(config.displayId_);
989     if (display == nullptr) {
990         TLOGE(WmsLogTag::WMS_UIEXT, "display is null!");
991         return WMError::WM_ERROR_NULLPTR;
992     }
993     auto displayInfo = display->GetDisplayInfo();
994     if (displayInfo == nullptr) {
995         TLOGE(WmsLogTag::WMS_UIEXT, "displayInfo is null");
996         return WMError::WM_ERROR_NULLPTR;
997     }
998     config.density_ = GetDefaultDensity(displayInfo);
999     auto rotation = ONE_FOURTH_FULL_CIRCLE_DEGREE * static_cast<uint32_t>(displayInfo->GetOriginRotation());
1000     auto deviceRotation = static_cast<uint32_t>(displayInfo->GetDefaultDeviceRotationOffset());
1001     config.transform_ = (rotation + deviceRotation) % FULL_CIRCLE_DEGREE;
1002     config.orientation_ = static_cast<int32_t>(displayInfo->GetDisplayOrientation());
1003     return WMError::WM_OK;
1004 }
1005 
UpdateSystemViewportConfig()1006 void WindowExtensionSessionImpl::UpdateSystemViewportConfig()
1007 {
1008     if (!handler_) {
1009         TLOGE(WmsLogTag::WMS_UIEXT, "handler_ is null");
1010         return;
1011     }
1012     auto task = [weak = wptr(this)]() {
1013         auto window = weak.promote();
1014         if (!window) {
1015             return;
1016         }
1017         if (window->isDensityFollowHost_) {
1018             TLOGNW(WmsLogTag::WMS_UIEXT, "UpdateSystemViewportConfig: Density is follow host");
1019             return;
1020         }
1021         SessionViewportConfig config;
1022         if (window->GetSystemViewportConfig(config) != WMError::WM_OK) {
1023             TLOGNE(WmsLogTag::WMS_UIEXT, "UpdateSystemViewportConfig: Get system viewportConfig failed");
1024             return;
1025         }
1026         if (!MathHelper::NearZero(window->lastDensity_ - config.density_)) {
1027             TLOGNI(WmsLogTag::WMS_UIEXT, "UpdateSystemViewportConfig: System density is changed");
1028             window->UpdateSessionViewportConfig(config);
1029         }
1030     };
1031     handler_->PostTask(task, "UpdateSystemViewportConfig");
1032 }
1033 
UpdateSessionViewportConfig(const SessionViewportConfig & config)1034 WSError WindowExtensionSessionImpl::UpdateSessionViewportConfig(const SessionViewportConfig& config)
1035 {
1036     if (config.isDensityFollowHost_ && std::islessequal(config.density_, 0.0f)) {
1037         TLOGE(WmsLogTag::WMS_UIEXT, "invalid density_: %{public}f", config.density_);
1038         return WSError::WS_ERROR_INVALID_PARAM;
1039     }
1040     if (!handler_) {
1041         TLOGE(WmsLogTag::WMS_UIEXT, "handler_ is null");
1042         return WSError::WS_ERROR_NULLPTR;
1043     }
1044     auto task = [weak = wptr(this), config]() {
1045         auto window = weak.promote();
1046         if (!window) {
1047             return;
1048         }
1049         auto viewportConfig = config;
1050         window->UpdateExtensionDensity(viewportConfig);
1051 
1052         TLOGNI(WmsLogTag::WMS_UIEXT, "UpdateSessionViewportConfig: Id:%{public}d, isDensityFollowHost_:%{public}d, "
1053             "displayId:%{public}" PRIu64", density:%{public}f, lastDensity:%{public}f, orientation:%{public}d, "
1054             "lastOrientation:%{public}d",
1055             window->GetPersistentId(), viewportConfig.isDensityFollowHost_, viewportConfig.displayId_,
1056             viewportConfig.density_, window->lastDensity_, viewportConfig.orientation_, window->lastOrientation_);
1057 
1058         window->NotifyDisplayInfoChange(viewportConfig);
1059         window->property_->SetDisplayId(viewportConfig.displayId_);
1060 
1061         auto ret = window->UpdateSessionViewportConfigInner(viewportConfig);
1062         if (ret == WSError::WS_OK) {
1063             window->lastDensity_ = viewportConfig.density_;
1064             window->lastOrientation_ = viewportConfig.orientation_;
1065             window->lastDisplayId_ = viewportConfig.displayId_;
1066         }
1067     };
1068     handler_->PostTask(task, "UpdateSessionViewportConfig");
1069     return WSError::WS_OK;
1070 }
1071 
UpdateExtensionDensity(SessionViewportConfig & config)1072 void WindowExtensionSessionImpl::UpdateExtensionDensity(SessionViewportConfig& config)
1073 {
1074     TLOGD(WmsLogTag::WMS_UIEXT, "isFollowHost:%{public}d, densityValue:%{public}f", config.isDensityFollowHost_,
1075         config.density_);
1076     isDensityFollowHost_ = config.isDensityFollowHost_;
1077     if (config.isDensityFollowHost_) {
1078         hostDensityValue_ = config.density_;
1079         return;
1080     }
1081     auto display = SingletonContainer::Get<DisplayManager>().GetDisplayById(config.displayId_);
1082     if (display == nullptr) {
1083         TLOGE(WmsLogTag::WMS_UIEXT, "display is null!");
1084         return;
1085     }
1086     auto displayInfo = display->GetDisplayInfo();
1087     if (displayInfo == nullptr) {
1088         TLOGE(WmsLogTag::WMS_UIEXT, "displayInfo is null");
1089         return;
1090     }
1091     config.density_ = GetDefaultDensity(displayInfo);
1092 }
1093 
NotifyDisplayInfoChange(const SessionViewportConfig & config)1094 void WindowExtensionSessionImpl::NotifyDisplayInfoChange(const SessionViewportConfig& config)
1095 {
1096     auto display = SingletonContainer::Get<DisplayManager>().GetDisplayById(config.displayId_);
1097     if (display != nullptr) {
1098         auto displayInfo = display->GetDisplayInfo();
1099         if (displayInfo != nullptr && !MathHelper::NearZero(lastSystemDensity_ - displayInfo->GetVirtualPixelRatio())) {
1100             auto density = displayInfo->GetVirtualPixelRatio();
1101             lastSystemDensity_ = density;
1102             NotifySystemDensityChange(density);
1103         }
1104     }
1105     if (context_ == nullptr) {
1106         TLOGE(WmsLogTag::WMS_UIEXT, "get token of window:%{public}d failed because of context is null.",
1107             GetPersistentId());
1108         return;
1109     }
1110     auto token = context_->GetToken();
1111     if (token == nullptr) {
1112         TLOGE(WmsLogTag::WMS_UIEXT, "get token of window:%{public}d failed.", GetPersistentId());
1113         return;
1114     }
1115     if (config.displayId_ != lastDisplayId_) {
1116         NotifyDisplayIdChange(config.displayId_);
1117     }
1118     SingletonContainer::Get<WindowManager>().NotifyDisplayInfoChange(
1119         token, config.displayId_, config.density_, static_cast<DisplayOrientation>(config.orientation_));
1120 }
1121 
UpdateSessionViewportConfigInner(const SessionViewportConfig & config)1122 WSError WindowExtensionSessionImpl::UpdateSessionViewportConfigInner(const SessionViewportConfig& config)
1123 {
1124     if (NearEqual(lastDensity_, config.density_) && lastOrientation_ == config.orientation_ &&
1125         lastDisplayId_ == config.displayId_) {
1126         TLOGI(WmsLogTag::WMS_UIEXT, "No parameters have changed, no need to update");
1127         return WSError::WS_DO_NOTHING;
1128     }
1129     Ace::ViewportConfig viewportConfig;
1130     auto rect = GetRect();
1131     viewportConfig.SetSize(rect.width_, rect.height_);
1132     viewportConfig.SetPosition(rect.posX_, rect.posY_);
1133     viewportConfig.SetDensity(config.density_);
1134     viewportConfig.SetOrientation(config.orientation_);
1135     viewportConfig.SetTransformHint(config.transform_);
1136     viewportConfig.SetDisplayId(config.displayId_);
1137 
1138     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
1139     if (uiContent == nullptr) {
1140         TLOGW(WmsLogTag::WMS_UIEXT, "uiContent is null!");
1141         return WSError::WS_ERROR_NULLPTR;
1142     }
1143     uiContent->UpdateViewportConfig(viewportConfig, WindowSizeChangeReason::UNDEFINED, nullptr, lastAvoidAreaMap_);
1144     return WSError::WS_OK;
1145 }
1146 
NotifyAccessibilityHoverEvent(float pointX,float pointY,int32_t sourceType,int32_t eventType,int64_t timeMs)1147 WSError WindowExtensionSessionImpl::NotifyAccessibilityHoverEvent(float pointX, float pointY, int32_t sourceType,
1148     int32_t eventType, int64_t timeMs)
1149 {
1150     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
1151     if (uiContent == nullptr) {
1152         WLOGFE("error, no uiContent");
1153         return WSError::WS_ERROR_NO_UI_CONTENT_ERROR;
1154     }
1155     uiContent->HandleAccessibilityHoverEvent(pointX, pointY, sourceType, eventType, timeMs);
1156     return WSError::WS_OK;
1157 }
1158 
TransferAccessibilityEvent(const Accessibility::AccessibilityEventInfo & info,int64_t uiExtensionIdLevel)1159 WMError WindowExtensionSessionImpl::TransferAccessibilityEvent(const Accessibility::AccessibilityEventInfo& info,
1160     int64_t uiExtensionIdLevel)
1161 {
1162     if (IsWindowSessionInvalid()) {
1163         WLOGFE("Window session invalid.");
1164         return WMError::WM_ERROR_INVALID_WINDOW;
1165     }
1166     auto hostSession = GetHostSession();
1167     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_INVALID_WINDOW);
1168     return static_cast<WMError>(hostSession->TransferAccessibilityEvent(info, uiExtensionIdLevel));
1169 }
1170 
NotifySessionForeground(uint32_t reason,bool withAnimation)1171 void WindowExtensionSessionImpl::NotifySessionForeground(uint32_t reason, bool withAnimation)
1172 {
1173 }
1174 
NotifySessionBackground(uint32_t reason,bool withAnimation,bool isFromInnerkits)1175 void WindowExtensionSessionImpl::NotifySessionBackground(uint32_t reason, bool withAnimation, bool isFromInnerkits)
1176 {
1177 }
1178 
NotifyOccupiedAreaChangeInfo(sptr<OccupiedAreaChangeInfo> info,const std::shared_ptr<RSTransaction> & rsTransaction,const Rect & callingSessionRect,const std::map<AvoidAreaType,AvoidArea> & avoidAreas)1179 void WindowExtensionSessionImpl::NotifyOccupiedAreaChangeInfo(sptr<OccupiedAreaChangeInfo> info,
1180     const std::shared_ptr<RSTransaction>& rsTransaction,
1181     const Rect& callingSessionRect, const std::map<AvoidAreaType, AvoidArea>& avoidAreas)
1182 {
1183     if (handler_ == nullptr) {
1184         TLOGE(WmsLogTag::WMS_KEYBOARD, "handler is nullptr");
1185         return;
1186     }
1187     auto task = [weak = wptr(this), info, rsTransaction, callingSessionRect, avoidAreas]() {
1188         if (info != nullptr) {
1189             TLOGNI(WmsLogTag::WMS_KEYBOARD, "TextFieldPosY: %{public}f, KeyBoardHeight: %{public}d",
1190                 info->textFieldPositionY_, info->rect_.height_);
1191         }
1192         auto window = weak.promote();
1193         if (window == nullptr) {
1194             TLOGNE(WmsLogTag::WMS_KEYBOARD, "window is nullptr, notify occupied area info failed");
1195             return;
1196         }
1197         window->NotifyOccupiedAreaChange(info);
1198         window->occupiedAreaInfo_ = info;
1199         window->UpdateViewportConfig(
1200             window->GetRect(), WindowSizeChangeReason::OCCUPIED_AREA_CHANGE, rsTransaction, nullptr, avoidAreas);
1201     };
1202     handler_->PostTask(task, "WMS_WindowExtensionSessionImpl_NotifyOccupiedAreaChangeInfo");
1203 }
1204 
RegisterOccupiedAreaChangeListener(const sptr<IOccupiedAreaChangeListener> & listener)1205 WMError WindowExtensionSessionImpl::RegisterOccupiedAreaChangeListener(
1206     const sptr<IOccupiedAreaChangeListener>& listener)
1207 {
1208     std::lock_guard<std::mutex> lockListener(occupiedAreaChangeListenerMutex_);
1209     return RegisterListener(occupiedAreaChangeListenerList_, listener);
1210 }
1211 
UnregisterOccupiedAreaChangeListener(const sptr<IOccupiedAreaChangeListener> & listener)1212 WMError WindowExtensionSessionImpl::UnregisterOccupiedAreaChangeListener(
1213     const sptr<IOccupiedAreaChangeListener>& listener)
1214 {
1215     std::lock_guard<std::mutex> lockListener(occupiedAreaChangeListenerMutex_);
1216     return UnregisterListener(occupiedAreaChangeListenerList_, listener);
1217 }
1218 
GetAvoidAreaByType(AvoidAreaType type,AvoidArea & avoidArea,const Rect & rect,int32_t apiVersion)1219 WMError WindowExtensionSessionImpl::GetAvoidAreaByType(AvoidAreaType type, AvoidArea& avoidArea,
1220     const Rect& rect, int32_t apiVersion)
1221 {
1222     uint32_t currentApiVersion = GetTargetAPIVersionByApplicationInfo();
1223     apiVersion = (apiVersion == API_VERSION_INVALID) ? static_cast<int32_t>(currentApiVersion) : apiVersion;
1224     auto hostSession = GetHostSession();
1225     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_NULLPTR);
1226     WSRect sessionRect = { rect.posX_, rect.posY_, rect.width_, rect.height_ };
1227     avoidArea = hostSession->GetAvoidAreaByType(type, sessionRect, apiVersion);
1228     TLOGI(WmsLogTag::WMS_IMMS, "win %{public}d type %{public}d api %{public}d area %{public}s",
1229         GetPersistentId(), type, apiVersion, avoidArea.ToString().c_str());
1230     return WMError::WM_OK;
1231 }
1232 
RegisterAvoidAreaChangeListener(const sptr<IAvoidAreaChangedListener> & listener)1233 WMError WindowExtensionSessionImpl::RegisterAvoidAreaChangeListener(const sptr<IAvoidAreaChangedListener>& listener)
1234 {
1235     return RegisterExtensionAvoidAreaChangeListener(listener);
1236 }
1237 
UnregisterAvoidAreaChangeListener(const sptr<IAvoidAreaChangedListener> & listener)1238 WMError WindowExtensionSessionImpl::UnregisterAvoidAreaChangeListener(const sptr<IAvoidAreaChangedListener>& listener)
1239 {
1240     return UnregisterExtensionAvoidAreaChangeListener(listener);
1241 }
1242 
Show(uint32_t reason,bool withAnimation,bool withFocus)1243 WMError WindowExtensionSessionImpl::Show(uint32_t reason, bool withAnimation, bool withFocus)
1244 {
1245     return Show(reason, withAnimation, withFocus, false);
1246 }
1247 
Show(uint32_t reason,bool withAnimation,bool withFocus,bool waitAttach)1248 WMError WindowExtensionSessionImpl::Show(uint32_t reason, bool withAnimation, bool withFocus, bool waitAttach)
1249 {
1250     CheckAndAddExtWindowFlags();
1251     UpdateSystemViewportConfig();
1252     return WindowSessionImpl::Show(reason, withAnimation, withFocus, waitAttach);
1253 }
1254 
Hide(uint32_t reason,bool withAnimation,bool isFromInnerkits)1255 WMError WindowExtensionSessionImpl::Hide(uint32_t reason, bool withAnimation, bool isFromInnerkits)
1256 {
1257     return Hide(reason, withAnimation, isFromInnerkits, false);
1258 }
1259 
Hide(uint32_t reason,bool withAnimation,bool isFromInnerkits,bool waitDetach)1260 WMError WindowExtensionSessionImpl::Hide(uint32_t reason, bool withAnimation, bool isFromInnerkits, bool waitDetach)
1261 {
1262     TLOGI(WmsLogTag::WMS_LIFE, "id:%{public}d Hide, reason:%{public}u, state:%{public}u",
1263         GetPersistentId(), reason, state_);
1264     if (IsWindowSessionInvalid()) {
1265         WLOGFE("session invalid");
1266         return WMError::WM_ERROR_INVALID_WINDOW;
1267     }
1268     auto hostSession = GetHostSession();
1269     CHECK_HOST_SESSION_RETURN_ERROR_IF_NULL(hostSession, WMError::WM_ERROR_INVALID_WINDOW);
1270     CheckAndRemoveExtWindowFlags();
1271     if (state_ == WindowState::STATE_HIDDEN || state_ == WindowState::STATE_CREATED) {
1272         TLOGD(WmsLogTag::WMS_LIFE, "already hidden [name:%{public}s, id:%{public}d, type: %{public}u]",
1273             property_->GetWindowName().c_str(), GetPersistentId(), property_->GetWindowType());
1274         NotifyBackgroundFailed(WMError::WM_DO_NOTHING);
1275         return WMError::WM_OK;
1276     }
1277     WSError ret = hostSession->Background();
1278     WMError res = static_cast<WMError>(ret);
1279     if (res == WMError::WM_OK) {
1280         UpdateSubWindowStateAndNotify(GetPersistentId(), WindowState::STATE_HIDDEN);
1281         state_ = WindowState::STATE_HIDDEN;
1282         requestState_ = WindowState::STATE_HIDDEN;
1283         NotifyAfterBackground();
1284     } else {
1285         TLOGD(WmsLogTag::WMS_LIFE, "window extension session Hide to Background error");
1286     }
1287     return WMError::WM_OK;
1288 }
1289 
NotifyDensityFollowHost(bool isFollowHost,float densityValue)1290 WSError WindowExtensionSessionImpl::NotifyDensityFollowHost(bool isFollowHost, float densityValue)
1291 {
1292     TLOGI(WmsLogTag::WMS_UIEXT, "isFollowHost:%{public}d densityValue:%{public}f", isFollowHost, densityValue);
1293 
1294     if (!isFollowHost && !isDensityFollowHost_) {
1295         TLOGI(WmsLogTag::WMS_UIEXT, "isFollowHost is false and not change");
1296         return WSError::WS_OK;
1297     }
1298 
1299     if (isFollowHost) {
1300         if (std::islessequal(densityValue, 0.0f)) {
1301             TLOGE(WmsLogTag::WMS_UIEXT, "densityValue is invalid");
1302             return WSError::WS_ERROR_INVALID_PARAM;
1303         }
1304         if (hostDensityValue_ != std::nullopt &&
1305             std::abs(hostDensityValue_->load() - densityValue) < std::numeric_limits<float>::epsilon()) {
1306             TLOGI(WmsLogTag::WMS_UIEXT, "densityValue not change");
1307             return WSError::WS_OK;
1308         }
1309         hostDensityValue_ = densityValue;
1310     }
1311 
1312     isDensityFollowHost_ = isFollowHost;
1313 
1314     UpdateViewportConfig(GetRect(), WindowSizeChangeReason::UNDEFINED);
1315     return WSError::WS_OK;
1316 }
1317 
GetVirtualPixelRatio(const sptr<DisplayInfo> & displayInfo)1318 float WindowExtensionSessionImpl::GetVirtualPixelRatio(const sptr<DisplayInfo>& displayInfo)
1319 {
1320     if (isDensityFollowHost_ && hostDensityValue_ != std::nullopt) {
1321         return hostDensityValue_->load();
1322     }
1323     return GetDefaultDensity(displayInfo);
1324 }
1325 
GetDefaultDensity(const sptr<DisplayInfo> & displayInfo)1326 float WindowExtensionSessionImpl::GetDefaultDensity(const sptr<DisplayInfo>& displayInfo)
1327 {
1328     if (IsAdaptToSimulationScale()) {
1329         TLOGD(WmsLogTag::WMS_COMPAT, "id:%{public}d scale mode", GetPersistentId());
1330         return COMPACT_SIMULATION_SCALE_DPI;
1331     }
1332     float vpr = 1.0f;
1333     if (displayInfo == nullptr) {
1334         TLOGE(WmsLogTag::WMS_UIEXT, "displayInfo is nullptr");
1335         return vpr;
1336     }
1337     return displayInfo->GetVirtualPixelRatio();
1338 }
1339 
CheckHideNonSecureWindowsPermission(bool shouldHide)1340 WMError WindowExtensionSessionImpl::CheckHideNonSecureWindowsPermission(bool shouldHide)
1341 {
1342     if ((property_->GetUIExtensionUsage() == UIExtensionUsage::MODAL ||
1343          SessionHelper::IsSecureUIExtension(property_->GetUIExtensionUsage())) && !shouldHide) {
1344         if (!SessionPermission::VerifyCallingPermission("ohos.permission.ALLOW_SHOW_NON_SECURE_WINDOWS")) {
1345             extensionWindowFlags_.hideNonSecureWindowsFlag = true;
1346             TLOGE(WmsLogTag::WMS_UIEXT, "Permission denied in %{public}s UIExtension.",
1347                 property_->GetUIExtensionUsage() == UIExtensionUsage::MODAL ? "modal" : "constrained embedded");
1348             return WMError::WM_ERROR_INVALID_OPERATION;
1349         }
1350         if (modalUIExtensionMayBeCovered_) {
1351             ReportModalUIExtensionMayBeCovered(modalUIExtensionSelfLoadContent_);
1352         }
1353     }
1354     return WMError::WM_OK;
1355 }
1356 
HideNonSecureWindows(bool shouldHide)1357 WMError WindowExtensionSessionImpl::HideNonSecureWindows(bool shouldHide)
1358 {
1359     TLOGI(WmsLogTag::WMS_UIEXT, "Id: %{public}u, shouldHide: %{public}u", GetPersistentId(), shouldHide);
1360     WMError checkRet = CheckHideNonSecureWindowsPermission(shouldHide);
1361     if (checkRet != WMError::WM_OK) {
1362         return checkRet;
1363     }
1364 
1365     if (state_ != WindowState::STATE_SHOWN) {
1366         extensionWindowFlags_.hideNonSecureWindowsFlag = shouldHide;
1367         return WMError::WM_OK;
1368     }
1369     if (shouldHide == extensionWindowFlags_.hideNonSecureWindowsFlag) {
1370         return WMError::WM_OK;
1371     }
1372 
1373     auto updateFlags = extensionWindowFlags_;
1374     updateFlags.hideNonSecureWindowsFlag = shouldHide;
1375     ExtensionWindowFlags actions(0);
1376     actions.hideNonSecureWindowsFlag = true;
1377     auto ret = UpdateExtWindowFlags(updateFlags, actions);
1378     if (ret == WMError::WM_OK) {
1379         extensionWindowFlags_ = updateFlags;
1380     }
1381     return ret;
1382 }
1383 
SetWaterMarkFlag(bool isEnable)1384 WMError WindowExtensionSessionImpl::SetWaterMarkFlag(bool isEnable)
1385 {
1386     TLOGI(WmsLogTag::WMS_UIEXT, "Id: %{public}u, isEnable: %{public}u", GetPersistentId(), isEnable);
1387     if (state_ != WindowState::STATE_SHOWN) {
1388         extensionWindowFlags_.waterMarkFlag = isEnable;
1389         return WMError::WM_OK;
1390     }
1391     if (isEnable == extensionWindowFlags_.waterMarkFlag) {
1392         return WMError::WM_OK;
1393     }
1394 
1395     auto updateFlags = extensionWindowFlags_;
1396     updateFlags.waterMarkFlag = isEnable;
1397     ExtensionWindowFlags actions(0);
1398     actions.waterMarkFlag = true;
1399     auto ret = UpdateExtWindowFlags(updateFlags, actions);
1400     if (ret == WMError::WM_OK) {
1401         extensionWindowFlags_ = updateFlags;
1402     }
1403     return ret;
1404 }
1405 
CheckAndAddExtWindowFlags()1406 void WindowExtensionSessionImpl::CheckAndAddExtWindowFlags()
1407 {
1408     if (extensionWindowFlags_.bitData != 0) {
1409         // If flag is true, make it active when foreground
1410         UpdateExtWindowFlags(extensionWindowFlags_, extensionWindowFlags_);
1411     }
1412 }
1413 
CheckAndRemoveExtWindowFlags()1414 void WindowExtensionSessionImpl::CheckAndRemoveExtWindowFlags()
1415 {
1416     if (extensionWindowFlags_.bitData != 0) {
1417         // If flag is true, make it inactive when background
1418         UpdateExtWindowFlags(ExtensionWindowFlags(), extensionWindowFlags_);
1419     }
1420 }
1421 
NotifyAccessibilityChildTreeRegister(uint32_t windowId,int32_t treeId,int64_t accessibilityId)1422 WSError WindowExtensionSessionImpl::NotifyAccessibilityChildTreeRegister(
1423     uint32_t windowId, int32_t treeId, int64_t accessibilityId)
1424 {
1425     if (!handler_) {
1426         return WSError::WS_ERROR_INTERNAL_ERROR;
1427     }
1428     auto uiContentSharedPtr = GetUIContentSharedPtr();
1429     if (uiContentSharedPtr == nullptr) {
1430         accessibilityChildTreeInfo_ = {
1431             .windowId = windowId,
1432             .treeId = treeId,
1433             .accessibilityId = accessibilityId
1434         };
1435         TLOGD(WmsLogTag::WMS_UIEXT, "uiContent is null, save the accessibility child tree info.");
1436         return WSError::WS_OK;
1437     }
1438     handler_->PostTask([uiContent = uiContentSharedPtr, windowId, treeId, accessibilityId]() {
1439         if (uiContent == nullptr) {
1440             TLOGNE(WmsLogTag::WMS_UIEXT, "NotifyAccessibilityChildTreeRegister error, no uiContent");
1441             return;
1442         }
1443         TLOGND(WmsLogTag::WMS_UIEXT,
1444             "NotifyAccessibilityChildTreeRegister: %{public}d %{public}" PRId64, treeId, accessibilityId);
1445         uiContent->RegisterAccessibilityChildTree(windowId, treeId, accessibilityId);
1446     });
1447     return WSError::WS_OK;
1448 }
1449 
NotifyAccessibilityChildTreeUnregister()1450 WSError WindowExtensionSessionImpl::NotifyAccessibilityChildTreeUnregister()
1451 {
1452     if (!handler_) {
1453         return WSError::WS_ERROR_INTERNAL_ERROR;
1454     }
1455     handler_->PostTask([uiContent = GetUIContentSharedPtr()]() {
1456         if (uiContent == nullptr) {
1457             TLOGNE(WmsLogTag::WMS_UIEXT, "NotifyAccessibilityChildTreeUnregister error, no uiContent");
1458             return;
1459         }
1460         uiContent->DeregisterAccessibilityChildTree();
1461     });
1462     return WSError::WS_OK;
1463 }
1464 
NotifyAccessibilityDumpChildInfo(const std::vector<std::string> & params,std::vector<std::string> & info)1465 WSError WindowExtensionSessionImpl::NotifyAccessibilityDumpChildInfo(
1466     const std::vector<std::string>& params, std::vector<std::string>& info)
1467 {
1468     if (!handler_) {
1469         return WSError::WS_ERROR_INTERNAL_ERROR;
1470     }
1471     handler_->PostSyncTask([uiContent = GetUIContentSharedPtr(), params, &info]() {
1472         if (uiContent == nullptr) {
1473             TLOGNE(WmsLogTag::WMS_UIEXT, "NotifyAccessibilityDumpChildInfo error, no uiContent");
1474             return;
1475         }
1476         uiContent->AccessibilityDumpChildInfo(params, info);
1477     });
1478     return WSError::WS_OK;
1479 }
1480 
UpdateAccessibilityTreeInfo()1481 void WindowExtensionSessionImpl::UpdateAccessibilityTreeInfo()
1482 {
1483     if (accessibilityChildTreeInfo_ == std::nullopt) {
1484         return;
1485     }
1486     std::shared_ptr<Ace::UIContent> uiContent = GetUIContentSharedPtr();
1487     if (uiContent == nullptr) {
1488         return;
1489     }
1490     uiContent->RegisterAccessibilityChildTree(accessibilityChildTreeInfo_->windowId,
1491         accessibilityChildTreeInfo_->treeId, accessibilityChildTreeInfo_->accessibilityId);
1492     accessibilityChildTreeInfo_.reset();
1493 }
1494 
UpdateExtWindowFlags(const ExtensionWindowFlags & flags,const ExtensionWindowFlags & actions)1495 WMError WindowExtensionSessionImpl::UpdateExtWindowFlags(const ExtensionWindowFlags& flags,
1496     const ExtensionWindowFlags& actions)
1497 {
1498     // action is true when the corresponding flag should be updated
1499     if (IsWindowSessionInvalid()) {
1500         TLOGI(WmsLogTag::WMS_UIEXT, "session is invalid");
1501         return WMError::WM_ERROR_INVALID_WINDOW;
1502     }
1503 
1504     if (!abilityToken_) {
1505         TLOGE(WmsLogTag::WMS_UIEXT, "token is nullptr");
1506         return WMError::WM_ERROR_NULLPTR;
1507     }
1508 
1509     return SingletonContainer::Get<WindowAdapter>().UpdateExtWindowFlags(abilityToken_, flags.bitData, actions.bitData);
1510 }
1511 
GetHostWindowRect(int32_t hostWindowId)1512 Rect WindowExtensionSessionImpl::GetHostWindowRect(int32_t hostWindowId)
1513 {
1514     Rect rect;
1515     if (hostWindowId != property_->GetParentId()) {
1516         TLOGE(WmsLogTag::WMS_UIEXT, "hostWindowId is invalid");
1517         return rect;
1518     }
1519     SingletonContainer::Get<WindowAdapter>().GetHostWindowRect(hostWindowId, rect);
1520     return rect;
1521 }
1522 
GetGlobalScaledRect(Rect & globalScaledRect)1523 WMError WindowExtensionSessionImpl::GetGlobalScaledRect(Rect& globalScaledRect)
1524 {
1525     return SingletonContainer::Get<WindowAdapter>().GetHostGlobalScaledRect(property_->GetParentId(), globalScaledRect);
1526 }
1527 
GetGestureBackEnabled(bool & enable) const1528 WMError WindowExtensionSessionImpl::GetGestureBackEnabled(bool& enable) const
1529 {
1530     enable = hostGestureBackEnabled_;
1531     return WMError::WM_OK;
1532 }
1533 
SetGestureBackEnabled(bool enable)1534 WMError WindowExtensionSessionImpl::SetGestureBackEnabled(bool enable)
1535 {
1536     AAFwk::WantParams want;
1537     want.SetParam(Extension::ATOMICSERVICE_KEY_FUNCTION, AAFwk::String::Box("setGestureBackEnabled"));
1538     want.SetParam(Extension::ATOMICSERVICE_KEY_PARAM_ENABLE, AAFwk::Boolean::Box(enable));
1539     if (TransferExtensionData(want) != WMError::WM_OK) {
1540         TLOGE(WmsLogTag::WMS_UIEXT, "send failed");
1541         return WMError::WM_ERROR_IPC_FAILED;
1542     }
1543     return WMError::WM_OK;
1544 }
1545 
SetLayoutFullScreen(bool status)1546 WMError WindowExtensionSessionImpl::SetLayoutFullScreen(bool status)
1547 {
1548     TLOGI(WmsLogTag::WMS_IMMS, "win [%{public}u %{public}s] status %{public}d",
1549         GetWindowId(), GetWindowName().c_str(), static_cast<int32_t>(status));
1550     if (IsWindowSessionInvalid()) {
1551         return WMError::WM_ERROR_INVALID_WINDOW;
1552     }
1553     if (auto hostSession = GetHostSession()) {
1554         hostSession->OnLayoutFullScreenChange(status);
1555     }
1556     property_->SetIsLayoutFullScreen(status);
1557     isIgnoreSafeArea_ = status;
1558     isIgnoreSafeAreaNeedNotify_ = true;
1559     if (auto uiContent = GetUIContentSharedPtr()) {
1560         uiContent->SetIgnoreViewSafeArea(status);
1561     }
1562     return WMError::WM_OK;
1563 }
1564 
UpdateSystemBarProperties(const std::unordered_map<WindowType,SystemBarProperty> & systemBarProperties,const std::unordered_map<WindowType,SystemBarPropertyFlag> & systemBarPropertyFlags)1565 WMError WindowExtensionSessionImpl::UpdateSystemBarProperties(
1566     const std::unordered_map<WindowType, SystemBarProperty>& systemBarProperties,
1567     const std::unordered_map<WindowType, SystemBarPropertyFlag>& systemBarPropertyFlags)
1568 {
1569     AAFwk::WantParams want;
1570     want.SetParam(Extension::ATOMICSERVICE_KEY_FUNCTION, AAFwk::String::Box("setWindowSystemBarEnable"));
1571     want.SetParam(Extension::ATOMICSERVICE_KEY_PARAM_STATUS,
1572         AAFwk::Boolean::Box(systemBarProperties.at(WindowType::WINDOW_TYPE_STATUS_BAR).enable_));
1573     want.SetParam(Extension::ATOMICSERVICE_KEY_PARAM_NAVIGATION,
1574         AAFwk::Boolean::Box(systemBarProperties.at(WindowType::WINDOW_TYPE_NAVIGATION_BAR).enable_));
1575     if (TransferExtensionData(want) != WMError::WM_OK) {
1576         TLOGE(WmsLogTag::WMS_UIEXT, "send failed");
1577         return WMError::WM_ERROR_IPC_FAILED;
1578     }
1579     return WMError::WM_OK;
1580 }
1581 
UpdateHostSpecificSystemBarEnabled(const std::string & name,bool enable,bool enableAnimation)1582 WMError WindowExtensionSessionImpl::UpdateHostSpecificSystemBarEnabled(const std::string& name, bool enable,
1583     bool enableAnimation)
1584 {
1585     AAFwk::WantParams want;
1586     want.SetParam(Extension::ATOMICSERVICE_KEY_FUNCTION, AAFwk::String::Box("setSpecificSystemBarEnabled"));
1587     want.SetParam(Extension::ATOMICSERVICE_KEY_PARAM_NAME, AAFwk::String::Box(name));
1588     want.SetParam(Extension::ATOMICSERVICE_KEY_PARAM_ENABLE, AAFwk::Boolean::Box(enable));
1589     want.SetParam(Extension::ATOMICSERVICE_KEY_PARAM_ENABLEANIMATION, AAFwk::Boolean::Box(enableAnimation));
1590     if (TransferExtensionData(want) != WMError::WM_OK) {
1591         TLOGE(WmsLogTag::WMS_UIEXT, "send failed");
1592         return WMError::WM_ERROR_IPC_FAILED;
1593     }
1594     return WMError::WM_OK;
1595 }
1596 
GetImmersiveModeEnabledState() const1597 bool WindowExtensionSessionImpl::GetImmersiveModeEnabledState() const
1598 {
1599     return hostImmersiveModeEnabled_;
1600 }
1601 
SetImmersiveModeEnabledState(bool enable)1602 WMError WindowExtensionSessionImpl::SetImmersiveModeEnabledState(bool enable)
1603 {
1604     AAFwk::WantParams want;
1605     want.SetParam(Extension::ATOMICSERVICE_KEY_FUNCTION, AAFwk::String::Box("setImmersiveModeEnabledState"));
1606     want.SetParam(Extension::ATOMICSERVICE_KEY_PARAM_ENABLE, AAFwk::Boolean::Box(enable));
1607     if (TransferExtensionData(want) != WMError::WM_OK) {
1608         TLOGE(WmsLogTag::WMS_UIEXT, "send failed");
1609         return WMError::WM_ERROR_IPC_FAILED;
1610     }
1611     return WMError::WM_OK;
1612 }
1613 
ExtensionSetKeepScreenOn(bool keepScreenOn)1614 WMError WindowExtensionSessionImpl::ExtensionSetKeepScreenOn(bool keepScreenOn)
1615 {
1616     AAFwk::WantParams want;
1617     want.SetParam(Extension::ATOMICSERVICE_KEY_FUNCTION, AAFwk::String::Box("setWindowKeepScreenOn"));
1618     want.SetParam(Extension::ATOMICSERVICE_KEY_PARAM_ISKEEPSCREENON, AAFwk::Boolean::Box(keepScreenOn));
1619     if (TransferExtensionData(want) != WMError::WM_OK) {
1620         TLOGE(WmsLogTag::WMS_UIEXT, "send failed");
1621         return WMError::WM_ERROR_IPC_FAILED;
1622     }
1623     return WMError::WM_OK;
1624 }
1625 
ExtensionSetBrightness(float brightness)1626 WMError WindowExtensionSessionImpl::ExtensionSetBrightness(float brightness)
1627 {
1628     AAFwk::WantParams want;
1629     want.SetParam(Extension::ATOMICSERVICE_KEY_FUNCTION, AAFwk::String::Box("setWindowBrightness"));
1630     want.SetParam(Extension::ATOMICSERVICE_KEY_PARAM_BRIGHTNESS, AAFwk::Float::Box(brightness));
1631     if (TransferExtensionData(want) != WMError::WM_OK) {
1632         TLOGE(WmsLogTag::WMS_UIEXT, "send failed");
1633         return WMError::WM_ERROR_IPC_FAILED;
1634     }
1635     return WMError::WM_OK;
1636 }
1637 
ConsumePointerEvent(const std::shared_ptr<MMI::PointerEvent> & pointerEvent)1638 void WindowExtensionSessionImpl::ConsumePointerEvent(const std::shared_ptr<MMI::PointerEvent>& pointerEvent)
1639 {
1640     if (pointerEvent == nullptr) {
1641         TLOGE(WmsLogTag::WMS_EVENT, "PointerEvent is nullptr, windowId: %{public}d", GetWindowId());
1642         return;
1643     }
1644     if (property_->GetUIExtensionUsage() == UIExtensionUsage::PREVIEW_EMBEDDED) {
1645         TLOGD(WmsLogTag::WMS_EVENT, "Preview uiext does not handle event, eid:%{public}d", pointerEvent->GetId());
1646         return;
1647     }
1648     if (hostSession_ == nullptr) {
1649         TLOGE(WmsLogTag::WMS_EVENT, "hostSession is nullptr, windowId: %{public}d", GetWindowId());
1650         pointerEvent->MarkProcessed();
1651         return;
1652     }
1653 
1654     MMI::PointerEvent::PointerItem pointerItem;
1655     if (!pointerEvent->GetPointerItem(pointerEvent->GetPointerId(), pointerItem)) {
1656         TLOGW(WmsLogTag::WMS_EVENT, "invalid pointerEvent, windowId: %{public}d", GetWindowId());
1657         pointerEvent->MarkProcessed();
1658         return;
1659     }
1660     auto action = pointerEvent->GetPointerAction();
1661     bool isPointDown = (action == MMI::PointerEvent::POINTER_ACTION_DOWN ||
1662         action == MMI::PointerEvent::POINTER_ACTION_BUTTON_DOWN);
1663     if ((property_->GetUIExtensionUsage() == UIExtensionUsage::MODAL) && isPointDown) {
1664         if (!abilityToken_) {
1665             TLOGE(WmsLogTag::WMS_UIEXT, "token is nullptr");
1666             return;
1667         }
1668         SingletonContainer::Get<WindowAdapter>().ProcessModalExtensionPointDown(abilityToken_,
1669             pointerItem.GetDisplayX(), pointerItem.GetDisplayY());
1670     }
1671     if (action != MMI::PointerEvent::POINTER_ACTION_MOVE) {
1672         TLOGI(WmsLogTag::WMS_EVENT, "eid:%{public}d,wid:%{public}u,"
1673             "pointId:%{public}d,sourceType:%{public}d", pointerEvent->GetId(), GetWindowId(),
1674             pointerEvent->GetPointerId(), pointerEvent->GetSourceType());
1675     }
1676     NotifyPointerEvent(pointerEvent);
1677 }
1678 
NotifyPointerEvent(const std::shared_ptr<MMI::PointerEvent> & pointerEvent)1679 void WindowExtensionSessionImpl::NotifyPointerEvent(const std::shared_ptr<MMI::PointerEvent>& pointerEvent)
1680 {
1681     if (pointerEvent == nullptr) {
1682         TLOGE(WmsLogTag::WMS_EVENT, "pointerEvent is nullptr, windowId: %{public}d", GetWindowId());
1683         return;
1684     }
1685     WindowSessionImpl::NotifyPointerEvent(pointerEvent);
1686     if (!IsWindowDelayRaiseEnabled()) {
1687         return;
1688     }
1689     std::shared_ptr<MMI::PointerEvent> pointerEventBackup;
1690     if (pointerEvent->GetPointerAction() == MMI::PointerEvent::POINTER_ACTION_BUTTON_DOWN) {
1691         pointerEventBackup = std::make_shared<MMI::PointerEvent>(*pointerEvent);
1692     } else {
1693         pointerEventBackup = pointerEvent;
1694     }
1695     auto uiContent = GetUIContentSharedPtr();
1696     if (uiContent == nullptr) {
1697         TLOGE(WmsLogTag::WMS_UIEXT, "uiContent is null!");
1698         return;
1699     }
1700     uiContent->ProcessPointerEvent(pointerEvent,
1701         [weakThis = wptr(this), pointerEventBackup](bool isHitTargetDraggable) mutable {
1702             auto window = weakThis.promote();
1703             if (window == nullptr) {
1704                 TLOGNE(WmsLogTag::WMS_UIEXT, "window is null!");
1705                 return;
1706             }
1707             window->ProcessPointerEventWithHostWindowDelayRaise(pointerEventBackup, isHitTargetDraggable);
1708         });
1709 }
1710 
ProcessPointerEventWithHostWindowDelayRaise(const std::shared_ptr<MMI::PointerEvent> & pointerEvent,bool isHitTargetDraggable) const1711 void WindowExtensionSessionImpl::ProcessPointerEventWithHostWindowDelayRaise(
1712     const std::shared_ptr<MMI::PointerEvent>& pointerEvent, bool isHitTargetDraggable) const
1713 {
1714     if (pointerEvent == nullptr) {
1715         TLOGE(WmsLogTag::WMS_EVENT, "pointerEvent is nullptr, windowId: %{public}d", GetWindowId());
1716         return;
1717     }
1718     const int32_t action = pointerEvent->GetPointerAction();
1719     bool isPointerButtonDown = (action == MMI::PointerEvent::POINTER_ACTION_BUTTON_DOWN);
1720     bool isPointerUp = (action == MMI::PointerEvent::POINTER_ACTION_BUTTON_UP ||
1721         action == MMI::PointerEvent::POINTER_ACTION_PULL_UP);
1722     if (!isPointerButtonDown && !isPointerUp) {
1723         return;
1724     }
1725     bool needNotifyHostWindowToRaise = isPointerUp || !isHitTargetDraggable;
1726     if (needNotifyHostWindowToRaise) {
1727         // Send message to host window to raise hierarchy
1728         auto businessCode = Extension::Businesscode::NOTIFY_HOST_WINDOW_TO_RAISE;
1729         AAFwk::Want dataToSend;
1730         if (SendExtensionMessageToHost(static_cast<uint32_t>(businessCode), dataToSend) != WMError::WM_OK) {
1731             return;
1732         }
1733         TLOGI(WmsLogTag::WMS_UIEXT, "Notify host window to raise, id: %{public}d, isHitTargetDraggable: %{public}d, "
1734             "isPointerUp: %{public}d", GetPersistentId(), isHitTargetDraggable, isPointerUp);
1735         return;
1736     }
1737     TLOGI(WmsLogTag::WMS_UIEXT, "No need to notify host window to raise, id: %{public}d, isHitTargetDraggable: "
1738         "%{public}d, isPointerUp: %{public}d", GetPersistentId(), isHitTargetDraggable, isPointerUp);
1739 }
1740 
PreNotifyKeyEvent(const std::shared_ptr<MMI::KeyEvent> & keyEvent)1741 bool WindowExtensionSessionImpl::PreNotifyKeyEvent(const std::shared_ptr<MMI::KeyEvent>& keyEvent)
1742 {
1743     if (keyEvent == nullptr) {
1744         TLOGE(WmsLogTag::WMS_EVENT, "keyEvent is nullptr");
1745         return false;
1746     }
1747     if (property_->GetUIExtensionUsage() == UIExtensionUsage::PREVIEW_EMBEDDED) {
1748         TLOGD(WmsLogTag::WMS_EVENT, "Preview uiext does not handle event, eid:%{public}d", keyEvent->GetId());
1749         return false;
1750     }
1751     RefreshNoInteractionTimeoutMonitor();
1752     if (property_->GetUIExtensionUsage() == UIExtensionUsage::CONSTRAINED_EMBEDDED) {
1753         if (focusState_ == std::nullopt) {
1754             TLOGW(WmsLogTag::WMS_EVENT, "focusState is null");
1755             keyEvent->MarkProcessed();
1756             return true;
1757         }
1758         if (!focusState_.value()) {
1759             keyEvent->MarkProcessed();
1760             return true;
1761         }
1762         TLOGI(WmsLogTag::WMS_EVENT, "eid:%{public}d wid:%{public}d",
1763             keyEvent->GetId(), keyEvent->GetAgentWindowId());
1764     }
1765     if (auto uiContent = GetUIContentSharedPtr()) {
1766         TLOGD(WmsLogTag::WMS_EVENT, "Start to process keyEvent, id: %{public}d", keyEvent->GetId());
1767         return uiContent->ProcessKeyEvent(keyEvent, true);
1768     }
1769     return false;
1770 }
1771 
GetFreeMultiWindowModeEnabledState()1772 bool WindowExtensionSessionImpl::GetFreeMultiWindowModeEnabledState()
1773 {
1774     bool enable = false;
1775     SingletonContainer::Get<WindowAdapter>().GetFreeMultiWindowEnableState(enable);
1776     TLOGI(WmsLogTag::WMS_MULTI_WINDOW, "enable=%{public}u", enable);
1777     return enable;
1778 }
1779 
NotifyExtensionTimeout(int32_t errorCode)1780 void WindowExtensionSessionImpl::NotifyExtensionTimeout(int32_t errorCode)
1781 {
1782     auto hostSession = GetHostSession();
1783     CHECK_HOST_SESSION_RETURN_IF_NULL(hostSession);
1784     hostSession->NotifyExtensionTimeout(errorCode);
1785 }
1786 
GetRealParentId() const1787 int32_t WindowExtensionSessionImpl::GetRealParentId() const
1788 {
1789     return property_->GetRealParentId();
1790 }
1791 
GetParentWindowType() const1792 WindowType WindowExtensionSessionImpl::GetParentWindowType() const
1793 {
1794     return property_->GetParentWindowType();
1795 }
1796 
NotifyModalUIExtensionMayBeCovered(bool byLoadContent)1797 void WindowExtensionSessionImpl::NotifyModalUIExtensionMayBeCovered(bool byLoadContent)
1798 {
1799     if (property_->GetUIExtensionUsage() != UIExtensionUsage::MODAL &&
1800         !SessionHelper::IsSecureUIExtension(property_->GetUIExtensionUsage())) {
1801         return;
1802     }
1803 
1804     modalUIExtensionMayBeCovered_ = true;
1805     if (byLoadContent) {
1806         modalUIExtensionSelfLoadContent_ = true;
1807     }
1808     if (extensionWindowFlags_.hideNonSecureWindowsFlag) {
1809         return;
1810     }
1811     ReportModalUIExtensionMayBeCovered(byLoadContent);
1812 }
1813 
ReportModalUIExtensionMayBeCovered(bool byLoadContent) const1814 void WindowExtensionSessionImpl::ReportModalUIExtensionMayBeCovered(bool byLoadContent) const
1815 {
1816     TLOGW(WmsLogTag::WMS_UIEXT, "Id=%{public}d", GetPersistentId());
1817     std::ostringstream oss;
1818     oss << "Modal UIExtension may be covered uid: " << getuid();
1819     oss << ", windowName: " << property_->GetWindowName();
1820     if (context_) {
1821         oss << ", bundleName: " << context_->GetBundleName();
1822     }
1823     auto type = byLoadContent ? WindowDFXHelperType::WINDOW_MODAL_UIEXTENSION_UICONTENT_CHECK :
1824         WindowDFXHelperType::WINDOW_MODAL_UIEXTENSION_SUBWINDOW_CHECK;
1825     SingletonContainer::Get<WindowInfoReporter>().ReportWindowException(static_cast<int32_t>(type), getpid(),
1826         oss.str());
1827 }
1828 
NotifyExtensionEventAsync(uint32_t notifyEvent)1829 void WindowExtensionSessionImpl::NotifyExtensionEventAsync(uint32_t notifyEvent)
1830 {
1831     TLOGD(WmsLogTag::WMS_UIEXT, "notifyEvent:%{public}d", notifyEvent);
1832     if (IsWindowSessionInvalid()) {
1833         TLOGE(WmsLogTag::WMS_UIEXT, "Window session invalid.");
1834         return;
1835     }
1836     auto hostSession = GetHostSession();
1837     CHECK_HOST_SESSION_RETURN_IF_NULL(hostSession);
1838     hostSession->NotifyExtensionEventAsync(notifyEvent);
1839 }
1840 
NotifyDumpInfo(const std::vector<std::string> & params,std::vector<std::string> & info)1841 WSError WindowExtensionSessionImpl::NotifyDumpInfo(const std::vector<std::string>& params,
1842     std::vector<std::string>& info)
1843 {
1844     TLOGI(WmsLogTag::WMS_UIEXT, "persistentId: %{public}d", GetPersistentId());
1845     auto uiContentSharedPtr = GetUIContentSharedPtr();
1846     if (uiContentSharedPtr == nullptr) {
1847         TLOGE(WmsLogTag::WMS_UIEXT, "uiContent is nullptr");
1848         return WSError::WS_ERROR_NULLPTR;
1849     }
1850     uiContentSharedPtr->DumpInfo(params, info);
1851     if (!SessionPermission::IsBetaVersion()) {
1852         TLOGW(WmsLogTag::WMS_UIEXT, "is not beta version, persistentId: %{public}d", GetPersistentId());
1853         info.clear();
1854     }
1855     return WSError::WS_OK;
1856 }
1857 
IsPcWindow() const1858 bool WindowExtensionSessionImpl::IsPcWindow() const
1859 {
1860     bool isPcWindow = false;
1861     WMError ret = SingletonContainer::Get<WindowAdapter>().IsPcWindow(isPcWindow);
1862     if (ret != WMError::WM_OK) {
1863         TLOGE(WmsLogTag::WMS_UIEXT, "can't find isPcWindow, err: %{public}u",
1864             static_cast<uint32_t>(ret));
1865     }
1866     return isPcWindow;
1867 }
1868 
IsPcOrPadFreeMultiWindowMode() const1869 bool WindowExtensionSessionImpl::IsPcOrPadFreeMultiWindowMode() const
1870 {
1871     bool isPcOrPadFreeMultiWindowMode = false;
1872     WMError ret = SingletonContainer::Get<WindowAdapter>().IsPcOrPadFreeMultiWindowMode(isPcOrPadFreeMultiWindowMode);
1873     if (ret != WMError::WM_OK) {
1874         TLOGE(WmsLogTag::WMS_UIEXT, "cant't find isPcOrPadFreeMultiWindowMode, err: %{public}u",
1875             static_cast<uint32_t>(ret));
1876     }
1877     return isPcOrPadFreeMultiWindowMode;
1878 }
1879 
SendExtensionData(MessageParcel & data,MessageParcel & reply,MessageOption & option)1880 WSError WindowExtensionSessionImpl::SendExtensionData(MessageParcel& data, MessageParcel& reply,
1881                                                       [[maybe_unused]] MessageOption& option)
1882 {
1883     TLOGD(WmsLogTag::WMS_UIEXT, "id=%{public}d", GetPersistentId());
1884     dataHandler_->NotifyDataConsumer(data, reply);
1885     return WSError::WS_OK;
1886 }
1887 
GetWindowMode() const1888 WindowMode WindowExtensionSessionImpl::GetWindowMode() const
1889 {
1890     return property_->GetWindowMode();
1891 }
1892 
UpdateExtensionConfig(const std::shared_ptr<AAFwk::Want> & want)1893 void WindowExtensionSessionImpl::UpdateExtensionConfig(const std::shared_ptr<AAFwk::Want>& want)
1894 {
1895     if (want == nullptr) {
1896         TLOGE(WmsLogTag::WMS_UIEXT, "null want ptr");
1897         return;
1898     }
1899 
1900     const auto& configParam = want->GetParams().GetWantParams(Extension::UIEXTENSION_CONFIG_FIELD);
1901     auto state = configParam.GetIntParam(Extension::CROSS_AXIS_FIELD, 0);
1902     if (IsValidCrossState(state)) {
1903         crossAxisState_ = static_cast<CrossAxisState>(state);
1904     }
1905     auto waterfallModeValue = configParam.GetIntParam(Extension::WATERFALL_MODE_FIELD, 0);
1906     isFullScreenWaterfallMode_.store(static_cast<bool>(waterfallModeValue));
1907     isValidWaterfallMode_.store(true);
1908     hostGestureBackEnabled_ = static_cast<bool>(configParam.GetIntParam(Extension::GESTURE_BACK_ENABLED, 1));
1909     hostImmersiveModeEnabled_ = static_cast<bool>(configParam.GetIntParam(Extension::IMMERSIVE_MODE_ENABLED, 0));
1910     auto isHostWindowDelayRaiseEnabled = configParam.GetIntParam(Extension::HOST_WINDOW_DELAY_RAISE_STATE_FIELD, 0);
1911     property_->SetWindowDelayRaiseEnabled(static_cast<bool>(isHostWindowDelayRaiseEnabled));
1912 
1913     extensionConfig_ = AAFwk::WantParams(configParam);
1914     if (auto uiContent = GetUIContentSharedPtr()) {
1915         uiContent->SetHostParams(extensionConfig_);
1916     }
1917     want->RemoveParam(Extension::UIEXTENSION_CONFIG_FIELD);
1918     auto rootHostWindowType =
1919         static_cast<WindowType>(configParam.GetIntParam(Extension::ROOT_HOST_WINDOW_TYPE_FIELD, 0));
1920     SetRootHostWindowType(rootHostWindowType);
1921     SetCompatInfo(configParam);
1922     TLOGI(WmsLogTag::WMS_ATTRIBUTE, "CrossAxisState: %{public}d, waterfall: %{public}d, "
1923         "rootHostWindowType: %{public}u, isHostWindowDelayRaiseEnabled: %{public}d, winId: %{public}u",
1924         state, isFullScreenWaterfallMode_.load(), rootHostWindowType, isHostWindowDelayRaiseEnabled, GetWindowId());
1925 }
1926 
SendExtensionMessageToHost(uint32_t code,const AAFwk::Want & data) const1927 WMError WindowExtensionSessionImpl::SendExtensionMessageToHost(uint32_t code, const AAFwk::Want& data) const
1928 {
1929     auto dataHandler = GetExtensionDataHandler();
1930     if (dataHandler == nullptr) {
1931         TLOGE(WmsLogTag::WMS_UIEXT, "dataHandler_ is nullptr!");
1932         return WMError::WM_ERROR_INVALID_PARAM;
1933     }
1934     auto sendResult = dataHandler->SendDataAsync(SubSystemId::ARKUI_UIEXT, code, data);
1935     if (sendResult == DataHandlerErr::OK) {
1936         return WMError::WM_OK;
1937     }
1938     TLOGE(WmsLogTag::WMS_UIEXT, "SendDataAsync failed, businessCode: %{public}u, errCode: %{public}u", code,
1939         sendResult);
1940     return WMError::WM_ERROR_IPC_FAILED;
1941 }
1942 
OnExtensionMessage(uint32_t code,int32_t persistentId,const AAFwk::Want & data)1943 WMError WindowExtensionSessionImpl::OnExtensionMessage(uint32_t code, int32_t persistentId, const AAFwk::Want& data)
1944 {
1945     switch (code) {
1946         case static_cast<uint32_t>(Extension::Businesscode::NOTIFY_HOST_WINDOW_TO_RAISE): {
1947             return HandleHostWindowRaise(code, persistentId, data);
1948             break;
1949         }
1950         case static_cast<uint32_t>(Extension::Businesscode::REGISTER_HOST_WINDOW_RECT_CHANGE_LISTENER): {
1951             return HandleRegisterHostWindowRectChangeListener(code, persistentId, data);
1952             break;
1953         }
1954         case static_cast<uint32_t>(Extension::Businesscode::UNREGISTER_HOST_WINDOW_RECT_CHANGE_LISTENER): {
1955             return HandleUnregisterHostWindowRectChangeListener(code, persistentId, data);
1956             break;
1957         }
1958         case static_cast<uint32_t>(Extension::Businesscode::REGISTER_KEYBOARD_DID_SHOW_LISTENER): {
1959             return HandleUIExtRegisterKeyboardDidShowListener(code, persistentId, data);
1960             break;
1961         }
1962         case static_cast<uint32_t>(Extension::Businesscode::UNREGISTER_KEYBOARD_DID_SHOW_LISTENER): {
1963             return HandleUIExtUnregisterKeyboardDidShowListener(code, persistentId, data);
1964             break;
1965         }
1966         case static_cast<uint32_t>(Extension::Businesscode::REGISTER_KEYBOARD_DID_HIDE_LISTENER): {
1967             return HandleUIExtRegisterKeyboardDidHideListener(code, persistentId, data);
1968             break;
1969         }
1970         case static_cast<uint32_t>(Extension::Businesscode::UNREGISTER_KEYBOARD_DID_HIDE_LISTENER): {
1971             return HandleUIExtUnregisterKeyboardDidHideListener(code, persistentId, data);
1972             break;
1973         }
1974         default: {
1975             TLOGI(WmsLogTag::WMS_UIEXT, "Message was not processed, businessCode: %{public}u", code);
1976             break;
1977         }
1978     }
1979     return WMError::WM_OK;
1980 }
1981 
HandleHostWindowRaise(uint32_t code,int32_t persistentId,const AAFwk::Want & data)1982 WMError WindowExtensionSessionImpl::HandleHostWindowRaise(uint32_t code, int32_t persistentId, const AAFwk::Want& data)
1983 {
1984     TLOGI(WmsLogTag::WMS_UIEXT, "businessCode: %{public}u", code);
1985     return SendExtensionMessageToHost(code, data);
1986 }
1987 
HandleRegisterHostWindowRectChangeListener(uint32_t code,int32_t persistentId,const AAFwk::Want & data)1988 WMError WindowExtensionSessionImpl::HandleRegisterHostWindowRectChangeListener(uint32_t code, int32_t persistentId,
1989     const AAFwk::Want& data)
1990 {
1991     TLOGD(WmsLogTag::WMS_UIEXT, "businessCode: %{public}u", code);
1992     auto ret = SendExtensionMessageToHost(code, data);
1993     if (ret != WMError::WM_OK) {
1994         return ret;
1995     }
1996     rectChangeUIExtListenerIds_.emplace(persistentId);
1997     return WMError::WM_OK;
1998 }
1999 
HandleUnregisterHostWindowRectChangeListener(uint32_t code,int32_t persistentId,const AAFwk::Want & data)2000 WMError WindowExtensionSessionImpl::HandleUnregisterHostWindowRectChangeListener(uint32_t code, int32_t persistentId,
2001     const AAFwk::Want& data)
2002 {
2003     TLOGD(WmsLogTag::WMS_UIEXT, "businessCode: %{public}u", code);
2004     bool isHostWindowRectChangeListenerEmpty = false;
2005     size_t hostWindowRectChangeListenerSize = 0;
2006     rectChangeUIExtListenerIds_.erase(persistentId);
2007     {
2008         std::lock_guard<std::mutex> lockListener(hostWindowRectChangeListenerMutex_);
2009         isHostWindowRectChangeListenerEmpty = hostWindowRectChangeListener_.empty();
2010         hostWindowRectChangeListenerSize = hostWindowRectChangeListener_.size();
2011     }
2012     if (!isHostWindowRectChangeListenerEmpty || !rectChangeUIExtListenerIds_.empty()) {
2013         TLOGI(WmsLogTag::WMS_UIEXT, "No need to send message to host to unregister, size of "
2014             "hostWindowRectChangeListener_: %{public}zu, size of rectChangeUIExtListenerIds_: %{public}zu",
2015             hostWindowRectChangeListenerSize, rectChangeUIExtListenerIds_.size());
2016         return WMError::WM_OK;
2017     }
2018     return SendExtensionMessageToHost(code, data);
2019 }
2020 
SetWindowMode(WindowMode mode)2021 WMError WindowExtensionSessionImpl::SetWindowMode(WindowMode mode)
2022 {
2023     property_->SetWindowMode(mode);
2024     if (auto uiContet = GetUIContentSharedPtr()) {
2025         uiContet->NotifyWindowMode(mode);
2026     }
2027     TLOGNI(WmsLogTag::WMS_UIEXT, "windowMode:%{public}u", GetWindowMode());
2028     return WMError::WM_OK;
2029 }
2030 
OnCrossAxisStateChange(AAFwk::Want && data,std::optional<AAFwk::Want> & reply)2031 WMError WindowExtensionSessionImpl::OnCrossAxisStateChange(AAFwk::Want&& data, std::optional<AAFwk::Want>& reply)
2032 {
2033     auto state = data.GetIntParam(Extension::CROSS_AXIS_FIELD, 0);
2034     if (state == static_cast<int32_t>(GetCrossAxisState())) {
2035         return WMError::WM_OK;
2036     }
2037     if (!IsValidCrossState(state)) {
2038         TLOGE(WmsLogTag::WMS_UIEXT, "invalid CrossAxisState:%{public}d", state);
2039         return WMError::WM_ERROR_INVALID_PARAM;
2040     }
2041     crossAxisState_ = static_cast<CrossAxisState>(state);
2042     if (auto uiContent = GetUIContentSharedPtr()) {
2043         uiContent->SendUIExtProprty(static_cast<uint32_t>(Extension::Businesscode::SYNC_CROSS_AXIS_STATE),
2044             data, static_cast<uint8_t>(SubSystemId::WM_UIEXT));
2045     }
2046     TLOGI(WmsLogTag::WMS_UIEXT, "CrossAxisState:%{public}d", state);
2047     auto windowCrossAxisListeners = GetListeners<IWindowCrossAxisListener>();
2048     for (const auto& listener : windowCrossAxisListeners) {
2049         if (listener != nullptr) {
2050             listener->OnCrossAxisChange(static_cast<CrossAxisState>(state));
2051         }
2052     }
2053     return WMError::WM_OK;
2054 }
2055 
GetCrossAxisState()2056 CrossAxisState WindowExtensionSessionImpl::GetCrossAxisState()
2057 {
2058     return crossAxisState_.load();
2059 }
2060 
OnWaterfallModeChange(AAFwk::Want && data,std::optional<AAFwk::Want> & reply)2061 WMError WindowExtensionSessionImpl::OnWaterfallModeChange(AAFwk::Want&& data, std::optional<AAFwk::Want>& reply)
2062 {
2063     bool isWaterfallMode = data.GetBoolParam(Extension::WATERFALL_MODE_FIELD, false);
2064     if (isWaterfallMode == isFullScreenWaterfallMode_) {
2065         return WMError::WM_OK;
2066     }
2067     TLOGI(WmsLogTag::WMS_ATTRIBUTE, "prev: %{public}d, curr: %{public}d, winId: %{public}u",
2068         isFullScreenWaterfallMode_.load(), isWaterfallMode, GetWindowId());
2069     isFullScreenWaterfallMode_.store(isWaterfallMode);
2070     isValidWaterfallMode_.store(true);
2071     if (auto uiContent = GetUIContentSharedPtr()) {
2072         TLOGI(WmsLogTag::WMS_ATTRIBUTE, "send uiext winId: %{public}u", GetWindowId());
2073         uiContent->SendUIExtProprty(static_cast<uint32_t>(Extension::Businesscode::SYNC_HOST_WATERFALL_MODE),
2074             data, static_cast<uint8_t>(SubSystemId::WM_UIEXT));
2075     }
2076     auto waterfallModeChangeListeners = GetWaterfallModeChangeListeners();
2077     for (const auto& listener : waterfallModeChangeListeners) {
2078         if (listener != nullptr) {
2079             listener->OnWaterfallModeChange(isWaterfallMode);
2080         }
2081     }
2082     return WMError::WM_OK;
2083 }
2084 
OnResyncExtensionConfig(AAFwk::Want && data,std::optional<AAFwk::Want> & reply)2085 WMError WindowExtensionSessionImpl::OnResyncExtensionConfig(AAFwk::Want&& data, std::optional<AAFwk::Want>& reply)
2086 {
2087     const auto& configParam = data.GetParams().GetWantParams(Extension::UIEXTENSION_CONFIG_FIELD);
2088     AAFwk::Want axisWant;
2089     axisWant.SetParam(Extension::CROSS_AXIS_FIELD,
2090         static_cast<int32_t>(configParam.GetIntParam(Extension::CROSS_AXIS_FIELD, 0)));
2091     OnCrossAxisStateChange(std::move(axisWant), reply);
2092     AAFwk::Want waterfallWant;
2093     waterfallWant.SetParam(Extension::WATERFALL_MODE_FIELD,
2094         static_cast<bool>(configParam.GetIntParam(Extension::WATERFALL_MODE_FIELD, 0)));
2095     OnWaterfallModeChange(std::move(waterfallWant), reply);
2096     AAFwk::Want windowDelayRaiseWant;
2097     windowDelayRaiseWant.SetParam(Extension::HOST_WINDOW_DELAY_RAISE_STATE_FIELD,
2098         static_cast<bool>(configParam.GetIntParam(Extension::HOST_WINDOW_DELAY_RAISE_STATE_FIELD, 0)));
2099     OnHostWindowDelayRaiseStateChange(std::move(windowDelayRaiseWant), reply);
2100     AAFwk::Want compatWant;
2101     compatWant.SetParam(Extension::COMPAT_IS_SIMULATION_SCALE_FIELD,
2102         static_cast<bool>(configParam.GetIntParam(Extension::COMPAT_IS_SIMULATION_SCALE_FIELD, 0)));
2103     compatWant.SetParam(Extension::COMPAT_IS_PROPORTION_SCALE_FIELD,
2104         static_cast<bool>(configParam.GetIntParam(Extension::COMPAT_IS_PROPORTION_SCALE_FIELD, 0)));
2105     compatWant.SetParam(Extension::COMPAT_SCALE_X_FIELD, GetFloatParam(Extension::COMPAT_SCALE_X_FIELD, configParam));
2106     compatWant.SetParam(Extension::COMPAT_SCALE_Y_FIELD, GetFloatParam(Extension::COMPAT_SCALE_Y_FIELD, configParam));
2107     OnHostWindowCompatInfoChange(std::move(compatWant), reply);
2108     return WMError::WM_OK;
2109 }
2110 
OnGestureBackEnabledChange(AAFwk::Want && data,std::optional<AAFwk::Want> & reply)2111 WMError WindowExtensionSessionImpl::OnGestureBackEnabledChange(AAFwk::Want&& data, std::optional<AAFwk::Want>& reply)
2112 {
2113     auto enable = data.GetBoolParam(Extension::GESTURE_BACK_ENABLED, true);
2114     if (enable == hostGestureBackEnabled_) {
2115         return WMError::WM_OK;
2116     }
2117     TLOGI(WmsLogTag::WMS_UIEXT, "gestureBackEnabled:%{public}d", enable);
2118     hostGestureBackEnabled_ = enable;
2119     if (auto uiContent = GetUIContentSharedPtr()) {
2120         uiContent->SendUIExtProprty(static_cast<uint32_t>(Extension::Businesscode::SYNC_HOST_GESTURE_BACK_ENABLED),
2121             data, static_cast<uint8_t>(SubSystemId::WM_UIEXT));
2122     }
2123     return WMError::WM_OK;
2124 }
2125 
OnImmersiveModeEnabledChange(AAFwk::Want && data,std::optional<AAFwk::Want> & reply)2126 WMError WindowExtensionSessionImpl::OnImmersiveModeEnabledChange(AAFwk::Want&& data, std::optional<AAFwk::Want>& reply)
2127 {
2128     auto enable = data.GetBoolParam(Extension::IMMERSIVE_MODE_ENABLED, false);
2129     if (enable == hostImmersiveModeEnabled_) {
2130         return WMError::WM_OK;
2131     }
2132     TLOGI(WmsLogTag::WMS_UIEXT, "immersiveModeEnabled:%{public}d", enable);
2133     hostImmersiveModeEnabled_ = enable;
2134     if (auto uiContent = GetUIContentSharedPtr()) {
2135         uiContent->SendUIExtProprty(static_cast<uint32_t>(Extension::Businesscode::SYNC_HOST_IMMERSIVE_MODE_ENABLED),
2136             data, static_cast<uint8_t>(SubSystemId::WM_UIEXT));
2137     }
2138     return WMError::WM_OK;
2139 }
2140 
OnHostWindowDelayRaiseStateChange(AAFwk::Want && data,std::optional<AAFwk::Want> & reply)2141 WMError WindowExtensionSessionImpl::OnHostWindowDelayRaiseStateChange(AAFwk::Want&& data,
2142     std::optional<AAFwk::Want>& reply)
2143 {
2144     bool isHostWindowDelayRaiseEnabled = data.GetBoolParam(Extension::HOST_WINDOW_DELAY_RAISE_STATE_FIELD, false);
2145     if (isHostWindowDelayRaiseEnabled == IsWindowDelayRaiseEnabled()) {
2146         return WMError::WM_OK;
2147     }
2148     property_->SetWindowDelayRaiseEnabled(isHostWindowDelayRaiseEnabled);
2149     if (auto uiContent = GetUIContentSharedPtr()) {
2150         uiContent->SendUIExtProprty(static_cast<uint32_t>(Extension::Businesscode::SYNC_HOST_WINDOW_DELAY_RAISE_STATE),
2151             data, static_cast<uint8_t>(SubSystemId::WM_UIEXT));
2152     }
2153     TLOGI(WmsLogTag::WMS_UIEXT, "isHostWindowDelayRaiseEnabled: %{public}d", isHostWindowDelayRaiseEnabled);
2154     return WMError::WM_OK;
2155 }
2156 
OnHostWindowRectChange(AAFwk::Want && data,std::optional<AAFwk::Want> & reply)2157 WMError WindowExtensionSessionImpl::OnHostWindowRectChange(AAFwk::Want&& data, std::optional<AAFwk::Want>& reply)
2158 {
2159     auto rectX = data.GetIntParam(Extension::RECT_X, 0);
2160     auto rectY = data.GetIntParam(Extension::RECT_Y, 0);
2161     auto rectWidth = data.GetIntParam(Extension::RECT_WIDTH, 0);
2162     auto rectHeight = data.GetIntParam(Extension::RECT_HEIGHT, 0);
2163     auto reason = static_cast<WindowSizeChangeReason>(data.GetIntParam(Extension::RECT_CHANGE_REASON, 0));
2164     Rect rect {rectX, rectY, rectWidth, rectHeight};
2165     TLOGI(WmsLogTag::WMS_UIEXT, "Host window rect change: %{public}s, reason: %{public}u",
2166         rect.ToString().c_str(), reason);
2167     {
2168         std::lock_guard<std::mutex> lockListener(hostWindowRectChangeListenerMutex_);
2169         for (const auto& listener : hostWindowRectChangeListener_) {
2170             if (listener != nullptr) {
2171                 listener->OnRectChange(rect, reason);
2172             }
2173         }
2174     }
2175     auto uiContent = GetUIContentSharedPtr();
2176     if (!rectChangeUIExtListenerIds_.empty() && uiContent != nullptr) {
2177         uiContent->SendUIExtProprtyByPersistentId(
2178             static_cast<uint32_t>(Extension::Businesscode::NOTIFY_HOST_WINDOW_RECT_CHANGE), data,
2179             rectChangeUIExtListenerIds_, static_cast<uint8_t>(SubSystemId::WM_UIEXT));
2180     }
2181     return WMError::WM_OK;
2182 }
2183 
OnScreenshot(AAFwk::Want && data,std::optional<AAFwk::Want> & reply)2184 WMError WindowExtensionSessionImpl::OnScreenshot(AAFwk::Want&& data, std::optional<AAFwk::Want>& reply)
2185 {
2186     TLOGD(WmsLogTag::WMS_UIEXT, "in");
2187     NotifyScreenshot();
2188     return WMError::WM_OK;
2189 }
2190 
OnExtensionSecureLimitChange(AAFwk::Want && data,std::optional<AAFwk::Want> & reply)2191 WMError WindowExtensionSessionImpl::OnExtensionSecureLimitChange(AAFwk::Want&& data, std::optional<AAFwk::Want>& reply)
2192 {
2193     bool limit = data.GetBoolParam(Extension::EXTENSION_SECURE_LIMIT_CHANGE, false);
2194     TLOGD(WmsLogTag::WMS_UIEXT, "limit: %{public}d", limit);
2195     NotifyExtensionSecureLimitChange(limit);
2196     return WMError::WM_OK;
2197 }
2198 
OnKeyboardDidShow(AAFwk::Want && data,std::optional<AAFwk::Want> & reply)2199 WMError WindowExtensionSessionImpl::OnKeyboardDidShow(AAFwk::Want&& data, std::optional<AAFwk::Want>& reply)
2200 {
2201     TLOGD(WmsLogTag::WMS_UIEXT, "in");
2202     KeyboardPanelInfo info;
2203     ReadKeyboardInfoFromWant(data, info);
2204     NotifyKeyboardDidShow(info);
2205     return WMError::WM_OK;
2206 }
2207 
OnKeyboardDidHide(AAFwk::Want && data,std::optional<AAFwk::Want> & reply)2208 WMError WindowExtensionSessionImpl::OnKeyboardDidHide(AAFwk::Want&& data, std::optional<AAFwk::Want>& reply)
2209 {
2210     TLOGD(WmsLogTag::WMS_UIEXT, "in");
2211     KeyboardPanelInfo info;
2212     ReadKeyboardInfoFromWant(data, info);
2213     NotifyKeyboardDidHide(info);
2214     return WMError::WM_OK;
2215 }
2216 
RegisterConsumer(Extension::Businesscode code,const std::function<WMError (AAFwk::Want && data,std::optional<AAFwk::Want> & reply)> & func)2217 void WindowExtensionSessionImpl::RegisterConsumer(Extension::Businesscode code,
2218     const std::function<WMError(AAFwk::Want&& data, std::optional<AAFwk::Want>& reply)>& func)
2219 {
2220     auto consumer = [func](SubSystemId id, uint32_t customId, AAFwk::Want&& data,
2221                                      std::optional<AAFwk::Want>& reply) {
2222         return static_cast<int32_t>(func(std::move(data), reply));
2223     };
2224     dataConsumers_.emplace(static_cast<uint32_t>(code), std::move(consumer));
2225 }
2226 
RegisterDataConsumer()2227 void WindowExtensionSessionImpl::RegisterDataConsumer()
2228 {
2229     auto windowModeConsumer = [this](SubSystemId id, uint32_t customId, AAFwk::Want&& data,
2230                                      std::optional<AAFwk::Want>& reply) -> int32_t {
2231         auto windowMode = data.GetIntParam(Extension::WINDOW_MODE_FIELD, 0);
2232         if (windowMode < static_cast<int32_t>(WindowMode::WINDOW_MODE_UNDEFINED) ||
2233             windowMode > static_cast<int32_t>(WindowMode::END)) {
2234             TLOGNE(WmsLogTag::WMS_UIEXT, "invalid window mode, windowMode:%{public}d", windowMode);
2235             return static_cast<int32_t>(DataHandlerErr::INVALID_PARAMETER);
2236         }
2237 
2238         static_cast<void>(SetWindowMode(static_cast<WindowMode>(windowMode)));
2239         return static_cast<int32_t>(DataHandlerErr::OK);
2240     };
2241     dataConsumers_.emplace(static_cast<uint32_t>(Extension::Businesscode::SYNC_HOST_WINDOW_MODE),
2242                            std::move(windowModeConsumer));
2243     RegisterConsumer(Extension::Businesscode::SYNC_CROSS_AXIS_STATE,
2244         std::bind(&WindowExtensionSessionImpl::OnCrossAxisStateChange,
2245         this, std::placeholders::_1, std::placeholders::_2));
2246     RegisterConsumer(Extension::Businesscode::SYNC_HOST_WATERFALL_MODE,
2247         std::bind(&WindowExtensionSessionImpl::OnWaterfallModeChange,
2248         this, std::placeholders::_1, std::placeholders::_2));
2249     RegisterConsumer(Extension::Businesscode::SYNC_WANT_PARAMS,
2250         std::bind(&WindowExtensionSessionImpl::OnResyncExtensionConfig,
2251         this, std::placeholders::_1, std::placeholders::_2));
2252     RegisterConsumer(Extension::Businesscode::SYNC_HOST_GESTURE_BACK_ENABLED,
2253         std::bind(&WindowExtensionSessionImpl::OnGestureBackEnabledChange,
2254         this, std::placeholders::_1, std::placeholders::_2));
2255     RegisterConsumer(Extension::Businesscode::SYNC_HOST_IMMERSIVE_MODE_ENABLED,
2256         std::bind(&WindowExtensionSessionImpl::OnImmersiveModeEnabledChange,
2257         this, std::placeholders::_1, std::placeholders::_2));
2258     RegisterConsumer(Extension::Businesscode::SYNC_COMPAT_INFO,
2259         std::bind(&WindowExtensionSessionImpl::OnHostWindowCompatInfoChange,
2260         this, std::placeholders::_1, std::placeholders::_2));
2261     RegisterConsumer(Extension::Businesscode::SYNC_HOST_WINDOW_DELAY_RAISE_STATE,
2262         std::bind(&WindowExtensionSessionImpl::OnHostWindowDelayRaiseStateChange,
2263         this, std::placeholders::_1, std::placeholders::_2));
2264     RegisterConsumer(Extension::Businesscode::NOTIFY_HOST_WINDOW_RECT_CHANGE,
2265         std::bind(&WindowExtensionSessionImpl::OnHostWindowRectChange,
2266         this, std::placeholders::_1, std::placeholders::_2));
2267     RegisterConsumer(Extension::Businesscode::NOTIFY_SCREENSHOT,
2268         std::bind(&WindowExtensionSessionImpl::OnScreenshot,
2269         this, std::placeholders::_1, std::placeholders::_2));
2270     RegisterConsumer(Extension::Businesscode::NOTIFY_EXTENSION_SECURE_LIMIT_CHANGE,
2271         std::bind(&WindowExtensionSessionImpl::OnExtensionSecureLimitChange,
2272         this, std::placeholders::_1, std::placeholders::_2));
2273     RegisterConsumer(Extension::Businesscode::NOTIFY_KEYBOARD_DID_SHOW,
2274         std::bind(&WindowExtensionSessionImpl::OnKeyboardDidShow,
2275         this, std::placeholders::_1, std::placeholders::_2));
2276     RegisterConsumer(Extension::Businesscode::NOTIFY_KEYBOARD_DID_HIDE,
2277         std::bind(&WindowExtensionSessionImpl::OnKeyboardDidHide,
2278             this, std::placeholders::_1, std::placeholders::_2));
2279     RegisterConsumer(Extension::Businesscode::SYNC_HOST_STATUS_BAR_CONTENT_COLOR,
2280         std::bind(&WindowExtensionSessionImpl::OnHostStatusBarContentColorChange,
2281         this, std::placeholders::_1, std::placeholders::_2));
2282 
2283     auto consumersEntry = [weakThis = wptr(this)](SubSystemId id, uint32_t customId, AAFwk::Want&& data,
2284                                                   std::optional<AAFwk::Want>& reply) -> int32_t {
2285         auto window = weakThis.promote();
2286         if (window == nullptr) {
2287             TLOGNE(WmsLogTag::WMS_UIEXT, "window is nullptr");
2288             return static_cast<int32_t>(DataHandlerErr::NULL_PTR);
2289         }
2290         auto itr = window->dataConsumers_.find(customId);
2291         if (itr == window->dataConsumers_.end()) {
2292             TLOGNE(WmsLogTag::WMS_UIEXT, "no consumer for %{public}u", customId);
2293             return static_cast<int32_t>(DataHandlerErr::NO_CONSUME_CALLBACK);
2294         }
2295 
2296         const auto& func = itr->second;
2297         if (!func) {
2298             TLOGNE(WmsLogTag::WMS_UIEXT, "not callable for %{public}u", customId);
2299             return static_cast<int32_t>(DataHandlerErr::INVALID_CALLBACK);
2300         }
2301 
2302         auto ret = func(id, customId, std::move(data), reply);
2303         TLOGND(WmsLogTag::WMS_UIEXT, "customId:%{public}u, ret:%{public}d", customId, ret);
2304         return static_cast<int32_t>(DataHandlerErr::OK);
2305     };
2306     dataHandler_->RegisterDataConsumer(SubSystemId::WM_UIEXT, std::move(consumersEntry));
2307 }
2308 
UseImplicitAnimation(bool useImplicit)2309 WMError WindowExtensionSessionImpl::UseImplicitAnimation(bool useImplicit)
2310 {
2311     TLOGI(WmsLogTag::WMS_UIEXT, "WindowId: %{public}u", GetWindowId());
2312     SingletonContainer::Get<WindowAdapter>().UseImplicitAnimation(property_->GetParentId(), useImplicit);
2313     return WMError::WM_OK;
2314 }
2315 
SetCompatInfo(const AAFwk::WantParams & configParam)2316 WMError WindowExtensionSessionImpl::SetCompatInfo(const AAFwk::WantParams& configParam)
2317 {
2318     bool isAdaptToSimulationScale =
2319         static_cast<bool>(configParam.GetIntParam(Extension::COMPAT_IS_SIMULATION_SCALE_FIELD, 0));
2320     bool isAdaptToProportionalScale =
2321         static_cast<bool>(configParam.GetIntParam(Extension::COMPAT_IS_PROPORTION_SCALE_FIELD, 0));
2322     auto compatibleModeProperty = property_->GetCompatibleModeProperty();
2323     if (compatibleModeProperty == nullptr) {
2324         if (!isAdaptToSimulationScale && !isAdaptToProportionalScale) {
2325             TLOGD(WmsLogTag::WMS_COMPAT, "id:%{public}d not scale mode", GetPersistentId());
2326             return WMError::WM_DO_NOTHING;
2327         }
2328         compatibleModeProperty = sptr<CompatibleModeProperty>::MakeSptr();
2329         property_->SetCompatibleModeProperty(compatibleModeProperty);
2330     }
2331     compatibleModeProperty->SetIsAdaptToSimulationScale(isAdaptToSimulationScale);
2332     compatibleModeProperty->SetIsAdaptToProportionalScale(isAdaptToProportionalScale);
2333     compatScaleX_ = GetFloatParam(Extension::COMPAT_SCALE_X_FIELD, configParam);
2334     compatScaleY_ = GetFloatParam(Extension::COMPAT_SCALE_Y_FIELD, configParam);
2335     TLOGI(WmsLogTag::WMS_COMPAT, "id:%{public}d compatScaleX:%{public}f compatScaleY:%{public}f",
2336         GetPersistentId(), compatScaleX_, compatScaleY_);
2337     return WMError::WM_OK;
2338 }
2339 
OnHostWindowCompatInfoChange(AAFwk::Want && data,std::optional<AAFwk::Want> & reply)2340 WMError WindowExtensionSessionImpl::OnHostWindowCompatInfoChange(AAFwk::Want&& data,
2341     std::optional<AAFwk::Want>& reply)
2342 {
2343     bool isAdaptToSimulationScale = data.GetBoolParam(Extension::COMPAT_IS_SIMULATION_SCALE_FIELD, false);
2344     bool isAdaptToProportionalScale = data.GetBoolParam(Extension::COMPAT_IS_PROPORTION_SCALE_FIELD, false);
2345     auto compatibleModeProperty = property_->GetCompatibleModeProperty();
2346     if (compatibleModeProperty == nullptr) {
2347         if (!isAdaptToSimulationScale && !isAdaptToProportionalScale) {
2348             TLOGD(WmsLogTag::WMS_COMPAT, "id:%{public}d not scale mode", GetPersistentId());
2349             return WMError::WM_DO_NOTHING;
2350         }
2351         compatibleModeProperty = sptr<CompatibleModeProperty>::MakeSptr();
2352         property_->SetCompatibleModeProperty(compatibleModeProperty);
2353     }
2354     compatibleModeProperty->SetIsAdaptToSimulationScale(isAdaptToSimulationScale);
2355     compatibleModeProperty->SetIsAdaptToProportionalScale(isAdaptToProportionalScale);
2356     compatScaleX_ = data.GetFloatParam(Extension::COMPAT_SCALE_X_FIELD, 1.0f);
2357     compatScaleY_ = data.GetFloatParam(Extension::COMPAT_SCALE_Y_FIELD, 1.0f);
2358     TLOGI(WmsLogTag::WMS_COMPAT, "id:%{public}d compatScaleX:%{public}f compatScaleY:%{public}f",
2359         GetPersistentId(), compatScaleX_, compatScaleY_);
2360     if (auto uiContent = GetUIContentSharedPtr()) {
2361         TLOGD(WmsLogTag::WMS_COMPAT, "send uiext winId: %{public}u", GetWindowId());
2362         uiContent->SendUIExtProprty(static_cast<uint32_t>(Extension::Businesscode::SYNC_COMPAT_INFO),
2363             data, static_cast<uint8_t>(SubSystemId::WM_UIEXT));
2364     }
2365     return WMError::WM_OK;
2366 }
2367 
NotifyKeyboardDidShow(const KeyboardPanelInfo & keyboardPanelInfo)2368 void WindowExtensionSessionImpl::NotifyKeyboardDidShow(const KeyboardPanelInfo& keyboardPanelInfo)
2369 {
2370     std::lock_guard<std::mutex> lockListener(keyboardDidShowListenerMutex_);
2371     for (const auto& listener : keyboardDidShowListenerList_) {
2372         if (listener != nullptr) {
2373             listener->OnKeyboardDidShow(keyboardPanelInfo);
2374         }
2375     }
2376     if (auto uiContent = GetUIContentSharedPtr()) {
2377         AAFwk::Want want;
2378         WriteKeyboardInfoToWant(want, keyboardPanelInfo);
2379         uiContent->SendUIExtProprtyByPersistentId(
2380             static_cast<uint32_t>(Extension::Businesscode::NOTIFY_KEYBOARD_DID_SHOW), want,
2381             keyboardDidShowUIExtListenerIds_, static_cast<uint8_t>(SubSystemId::WM_UIEXT));
2382     }
2383 }
2384 
NotifyKeyboardDidHide(const KeyboardPanelInfo & keyboardPanelInfo)2385 void WindowExtensionSessionImpl::NotifyKeyboardDidHide(const KeyboardPanelInfo& keyboardPanelInfo)
2386 {
2387     std::lock_guard<std::mutex> lockListener(keyboardDidHideListenerMutex_);
2388     for (const auto& listener : keyboardDidHideListenerList_) {
2389         if (listener != nullptr) {
2390             listener->OnKeyboardDidHide(keyboardPanelInfo);
2391         }
2392     }
2393     if (auto uiContent = GetUIContentSharedPtr()) {
2394         AAFwk::Want want;
2395         WriteKeyboardInfoToWant(want, keyboardPanelInfo);
2396         uiContent->SendUIExtProprtyByPersistentId(
2397             static_cast<uint32_t>(Extension::Businesscode::NOTIFY_KEYBOARD_DID_HIDE), want,
2398             keyboardDidHideUIExtListenerIds_, static_cast<uint8_t>(SubSystemId::WM_UIEXT));
2399     }
2400 }
2401 
OnHostStatusBarContentColorChange(AAFwk::Want && data,std::optional<AAFwk::Want> & reply)2402 WMError WindowExtensionSessionImpl::OnHostStatusBarContentColorChange(AAFwk::Want&& data,
2403     std::optional<AAFwk::Want>& reply)
2404 {
2405     auto contentColor = static_cast<uint32_t>(data.GetIntParam(Extension::HOST_STATUS_BAR_CONTENT_COLOR, 0));
2406     TLOGI(WmsLogTag::WMS_UIEXT, "contentColor: %{public}u", contentColor);
2407     hostStatusBarContentColor_ = contentColor;
2408     return WMError::WM_OK;
2409 }
2410 
GetHostStatusBarContentColor() const2411 uint32_t WindowExtensionSessionImpl::GetHostStatusBarContentColor() const
2412 {
2413     return hostStatusBarContentColor_;
2414 }
2415 
NotifyOccupiedAreaChange(sptr<OccupiedAreaChangeInfo> info)2416 void WindowExtensionSessionImpl::NotifyOccupiedAreaChange(sptr<OccupiedAreaChangeInfo> info)
2417 {
2418     std::lock_guard<std::mutex> lockListener(occupiedAreaChangeListenerMutex_);
2419     for (auto& listener : occupiedAreaChangeListenerList_) {
2420         if (listener != nullptr) {
2421             listener->OnSizeChange(info);
2422         }
2423     }
2424 }
2425 } // namespace Rosen
2426 } // namespace OHOS
2427