diff --git a/.gitee/CODEOWNERS b/.gitee/CODEOWNERS index 0f22ecb918a..2e1b7fcbbd0 100644 --- a/.gitee/CODEOWNERS +++ b/.gitee/CODEOWNERS @@ -93,7 +93,7 @@ frameworks/core/components_ng/pattern/refresh/ @aryawang frameworks/core/components_ng/pattern/relative_container/ @nickyjd frameworks/core/components_ng/pattern/remote_window/ @liuchao92 frameworks/core/components_ng/pattern/rendering_context/ @zhangbingce -frameworks/core/components_ng/pattern/rich_editor/ @cc520bf +frameworks/core/components_ng/pattern/rich_editor/ @jyj-0306 frameworks/core/components_ng/pattern/root/ @zhoutianer frameworks/core/components_ng/pattern/scroll/ @rongShao-Z frameworks/core/components_ng/pattern/scroll_bar/ @rongShao-Z @@ -159,7 +159,7 @@ frameworks/core/components/flex/ @yangfan229 frameworks/core/components/focus_animation/ @catpoison frameworks/core/components/focus_collaboration/ @catpoison frameworks/core/components/focusable/ @catpoison -frameworks/core/components/font/ @cc520bf +frameworks/core/components/font/ @jyj-0306 frameworks/core/components/foreach/ @yan-shuifeng frameworks/core/components/form/ @wangchensu1 frameworks/core/components/gesture_listener/ @zheng-qiyi @@ -367,7 +367,7 @@ frameworks/core/components_ng/test/pattern/refresh/ @suiwuyue frameworks/core/components_ng/test/pattern/relative_container/ @nickyjd frameworks/core/components_ng/test/pattern/remote_window/ @liuchao92 frameworks/core/components_ng/test/pattern/rendering_context/ @zhangbingce -frameworks/core/components_ng/test/pattern/rich_editor/ @cc520bf +frameworks/core/components_ng/test/pattern/rich_editor/ @jyj-0306 frameworks/core/components_ng/test/pattern/root/ @yan-shuifeng frameworks/core/components_ng/test/pattern/scroll/ @suiwuyue frameworks/core/components_ng/test/pattern/scroll_bar/ @suiwuyue diff --git a/adapter/ohos/capability/udmf/udmf_impl.cpp b/adapter/ohos/capability/udmf/udmf_impl.cpp index 46c6b4a72b9..fe97c1ecea6 100644 --- a/adapter/ohos/capability/udmf/udmf_impl.cpp +++ b/adapter/ohos/capability/udmf/udmf_impl.cpp @@ -25,6 +25,7 @@ #include "system_defined_form.h" #include "system_defined_pixelmap.h" #include "text.h" +#include "plain_text.h" #include "udmf_client.h" #include "unified_data.h" #include "unified_data_napi.h" @@ -240,30 +241,24 @@ void UdmfClientImpl::AddImageRecord(const RefPtr& unifiedData, cons udData->GetUnifiedData()->AddRecord(record); } -void UdmfClientImpl::AddTextRecord(const RefPtr& unifiedData, const std::string& selectedStr) +void UdmfClientImpl::AddPlainTextRecord(const RefPtr& unifiedData, const std::string& selectedStr) { - UDMF::UDVariant udmfValue(selectedStr); - UDMF::UDDetails udmfDetails = { { "value", udmfValue } }; - auto record = std::make_shared(udmfDetails); + auto record = std::make_shared(selectedStr, ""); auto udData = AceType::DynamicCast(unifiedData); CHECK_NULL_VOID(udData); udData->GetUnifiedData()->AddRecord(record); } -std::string UdmfClientImpl::GetSingleTextRecord(const RefPtr& unifiedData) +std::string UdmfClientImpl::GetSinglePlainTextRecord(const RefPtr& unifiedData) { std::string str = ""; auto udData = AceType::DynamicCast(unifiedData); CHECK_NULL_RETURN(udData, str); auto records = udData->GetUnifiedData()->GetRecords(); - if (records.size() >= 1 && records[0]->GetType() == UDMF::UDType::TEXT) { - UDMF::Text* text = reinterpret_cast(records[0].get()); - UDMF::UDDetails udmfDetails = text->GetDetails(); - auto value = udmfDetails.find("value"); - if (value != udmfDetails.end()) { - str = std::get(value->second); - } + if (records.size() >= 1 && records[0]->GetType() == UDMF::UDType::PLAIN_TEXT) { + UDMF::PlainText* plainText = reinterpret_cast(records[0].get()); + str = plainText->GetContent(); } return str; } diff --git a/adapter/ohos/capability/udmf/udmf_impl.h b/adapter/ohos/capability/udmf/udmf_impl.h index 3a7a267c458..6adfb5fc682 100644 --- a/adapter/ohos/capability/udmf/udmf_impl.h +++ b/adapter/ohos/capability/udmf/udmf_impl.h @@ -48,8 +48,8 @@ public: const RefPtr& unifiedData, std::string& htmlContent, std::string& plainContent) override; void AddPixelMapRecord(const RefPtr& unifiedData, std::vector& data) override; void AddImageRecord(const RefPtr& unifiedData, const std::string& uri) override; - void AddTextRecord(const RefPtr& unifiedData, const std::string& selectedStr) override; - std::string GetSingleTextRecord(const RefPtr& unifiedData) override; + void AddPlainTextRecord(const RefPtr& unifiedData, const std::string& selectedStr) override; + std::string GetSinglePlainTextRecord(const RefPtr& unifiedData) override; int32_t GetVideoRecordUri(const RefPtr& unifiedData, std::string& uri) override; }; diff --git a/adapter/ohos/entrance/data_ability_helper_standard.cpp b/adapter/ohos/entrance/data_ability_helper_standard.cpp index 0c8ab1c52ac..065c5a39f76 100644 --- a/adapter/ohos/entrance/data_ability_helper_standard.cpp +++ b/adapter/ohos/entrance/data_ability_helper_standard.cpp @@ -28,41 +28,59 @@ namespace OHOS::Ace { namespace { const std::string MEDIA_PLUGIN = "multimedia/libmedialibrary.z.so"; const std::string FILE_PLUGIN = "filemanagement/libuserfilemanager.z.so"; -const std::string PHOTO_HEAD = "file://media/Photo"; -const std::string AUDIO_HEAD = "file://media/Audio"; +const std::string PAH_PLUGIN = "file/libphotoaccesshelper.z.so"; const std::string MEDIA_SERVER_HEAD = "datashare:///media"; #if !defined(PREVIEW) -bool UseFilePlugin(const std::string& uri) -{ - return StringUtils::StartWith(uri, PHOTO_HEAD) || StringUtils::StartWith(uri, AUDIO_HEAD); -} - using ThumbnailNapiEntry = void* (*)(const char*, void*); -ThumbnailNapiEntry GetThumbnailNapiEntry(const std::string& uri) +static void* GetThumbnailFromNapi(const std::string& uri, const std::weak_ptr &context) { + ACE_SCOPED_TRACE("GetThumbnailFromNapi"); +#if defined(_ARM64_) || defined(SIMULATOR_64) + static const std::string PREFIX = "/system/lib64/module/"; +#else + static const std::string PREFIX = "/system/lib/module/"; +#endif + static const std::vector THUMB_PLUGINS = { + PAH_PLUGIN, + FILE_PLUGIN, + MEDIA_PLUGIN, + }; + void* outThumbnail = nullptr; + auto runtimeContext = context.lock(); + CHECK_NULL_RETURN(runtimeContext, nullptr); static ThumbnailNapiEntry thumbnailNapiEntry = nullptr; if (!thumbnailNapiEntry) { -#if defined(_ARM64_) || defined(SIMULATOR_64) - std::string prefix = "/system/lib64/module/"; -#else - std::string prefix = "/system/lib/module/"; -#endif - - auto napiPluginPath = prefix.append(UseFilePlugin(uri) ? FILE_PLUGIN : MEDIA_PLUGIN); - void* handle = dlopen(napiPluginPath.c_str(), RTLD_LAZY); - CHECK_NULL_RETURN(handle, nullptr); - thumbnailNapiEntry = reinterpret_cast(dlsym(handle, "OHOS_MEDIA_NativeGetThumbnail")); - if (thumbnailNapiEntry == nullptr) { - dlclose(handle); - LOGE("Failed to get symbol OHOS_MEDIA_NativeGetThumbnail in %{public}s", napiPluginPath.c_str()); - return nullptr; + for (const auto& plug : THUMB_PLUGINS) { + auto napiPlug = PREFIX + plug; + void* handle = dlopen(napiPlug.c_str(), RTLD_LAZY); + CHECK_NULL_RETURN(handle, nullptr); + thumbnailNapiEntry = reinterpret_cast(dlsym(handle, "OHOS_MEDIA_NativeGetThumbnail")); + if (thumbnailNapiEntry == nullptr) { + dlclose(handle); + LOGE("Failed to get symbol OHOS_MEDIA_NativeGetThumbnail in %{public}s, try next plugin", + napiPlug.c_str()); + continue; + } + outThumbnail = thumbnailNapiEntry(uri.c_str(), &runtimeContext); + if (outThumbnail == nullptr) { + dlclose(handle); + thumbnailNapiEntry = nullptr; + LOGE("Failed to get thumbnail from %{private}s, try next plugin", napiPlug.c_str()); + continue; + } + return outThumbnail; + } + } else { + outThumbnail = thumbnailNapiEntry(uri.c_str(), &runtimeContext); + if (outThumbnail == nullptr) { + thumbnailNapiEntry = nullptr; + LOGE("Failed to get thumbnail!"); } } - return thumbnailNapiEntry; + return outThumbnail; } #endif - } // namespace DataAbilityHelperStandard::DataAbilityHelperStandard(const std::shared_ptr& context, @@ -81,11 +99,7 @@ void* DataAbilityHelperStandard::QueryThumbnailResFromDataAbility(const std::str #ifdef PREVIEW return nullptr; #else - ThumbnailNapiEntry thumbnailNapiEntry = GetThumbnailNapiEntry(uri); - CHECK_NULL_RETURN(thumbnailNapiEntry, nullptr); - auto runtimeContextSptr = runtimeContext_.lock(); - CHECK_NULL_RETURN(runtimeContextSptr, nullptr); - return thumbnailNapiEntry(uri.c_str(), &runtimeContextSptr); + return GetThumbnailFromNapi(uri, runtimeContext_); #endif } diff --git a/adapter/ohos/entrance/subwindow/subwindow_ohos.cpp b/adapter/ohos/entrance/subwindow/subwindow_ohos.cpp index fbf5094518c..3463bd59059 100644 --- a/adapter/ohos/entrance/subwindow/subwindow_ohos.cpp +++ b/adapter/ohos/entrance/subwindow/subwindow_ohos.cpp @@ -24,6 +24,7 @@ #include "base/geometry/rect.h" #include "core/components/root/root_element.h" #include "core/components_ng/base/ui_node.h" +#include "core/pipeline_ng/pipeline_context.h" #if defined(ENABLE_ROSEN_BACKEND) and !defined(UPLOAD_GPU_DISABLED) #include "adapter/ohos/entrance/ace_rosen_sync_task.h" #endif @@ -238,6 +239,7 @@ void SubwindowOhos::ShowPopupNG(int32_t targetId, const NG::PopupInfo& popupInfo CHECK_NULL_VOID(overlayManager); ShowWindow(); ResizeWindow(); + ContainerScope scope(childContainerId_); overlayManager->UpdatePopupNode(targetId, popupInfo); } @@ -249,31 +251,11 @@ void SubwindowOhos::HidePopupNG(int32_t targetId) CHECK_NULL_VOID(context); auto overlayManager = context->GetOverlayManager(); CHECK_NULL_VOID(overlayManager); - auto popupInfo = overlayManager->GetPopupInfo(targetId); + auto popupInfo = overlayManager->GetPopupInfo(targetId == -1 ? popupTargetId_ : targetId); popupInfo.popupId = -1; popupInfo.markNeedUpdate = true; - overlayManager->HidePopup(targetId, popupInfo); - context->FlushPipelineImmediately(); - HideWindow(); -#ifdef ENABLE_DRAG_FRAMEWORK - HideEventColumn(); - HidePixelMap(); - HideFilter(); -#endif // ENABLE_DRAG_FRAMEWORK -} - -void SubwindowOhos::HidePopupNG() -{ - auto aceContainer = Platform::AceContainer::GetContainer(childContainerId_); - CHECK_NULL_VOID(aceContainer); - auto context = DynamicCast(aceContainer->GetPipelineContext()); - CHECK_NULL_VOID(context); - auto overlayManager = context->GetOverlayManager(); - CHECK_NULL_VOID(overlayManager); - auto popupInfo = overlayManager->GetPopupInfo(popupTargetId_); - popupInfo.popupId = -1; - popupInfo.markNeedUpdate = true; - overlayManager->HidePopup(popupTargetId_, popupInfo); + ContainerScope scope(childContainerId_); + overlayManager->HidePopup(targetId == -1 ? popupTargetId_ : targetId, popupInfo); context->FlushPipelineImmediately(); HideWindow(); #ifdef ENABLE_DRAG_FRAMEWORK @@ -383,6 +365,11 @@ void SubwindowOhos::HideWindow() } OHOS::Rosen::WMError ret = window_->Hide(); + auto parentContainer = Platform::AceContainer::GetContainer(parentContainerId_); + CHECK_NULL_VOID(parentContainer); + if (parentContainer->IsScenceBoardWindow()) { + window_->SetTouchable(true); + } if (ret != OHOS::Rosen::WMError::WM_OK) { LOGE("Hide window failed with errCode: %{public}d", static_cast(ret)); @@ -455,6 +442,7 @@ void SubwindowOhos::HideMenuNG() CHECK_NULL_VOID(context); auto overlay = context->GetOverlayManager(); CHECK_NULL_VOID(overlay); + ContainerScope scope(childContainerId_); overlay->HideMenuInSubWindow(); } @@ -562,7 +550,7 @@ void SubwindowOhos::RectConverter(const Rect& rect, Rosen::Rect& rosenRect) } RefPtr SubwindowOhos::ShowDialogNG( - const DialogProperties& dialogProps, const RefPtr& customNode) + const DialogProperties& dialogProps, std::function&& buildFunc) { LOGI("SubwindowOhos::ShowDialogNG"); auto aceContainer = Platform::AceContainer::GetContainer(childContainerId_); @@ -572,9 +560,10 @@ RefPtr SubwindowOhos::ShowDialogNG( auto overlay = context->GetOverlayManager(); CHECK_NULL_RETURN(overlay, nullptr); ShowWindow(); + window_->SetFullScreen(true); ResizeWindow(); ContainerScope scope(childContainerId_); - return overlay->ShowDialog(dialogProps, customNode); + return overlay->ShowDialog(dialogProps, std::move(buildFunc)); } void SubwindowOhos::HideSubWindowNG() @@ -700,7 +689,7 @@ void SubwindowOhos::ShowToastForAbility(const std::string& message, int32_t dura LOGE("can not get delegate."); return; } - ContainerScope scope(aceContainer->GetInstanceId()); + ContainerScope scope(childContainerId_); auto parentContainer = Platform::AceContainer::GetContainer(parentContainerId_); CHECK_NULL_VOID(parentContainer); if (parentContainer->IsScenceBoardWindow()) { diff --git a/adapter/ohos/entrance/subwindow/subwindow_ohos.h b/adapter/ohos/entrance/subwindow/subwindow_ohos.h index 183cf9acfaa..53017b3dd93 100644 --- a/adapter/ohos/entrance/subwindow/subwindow_ohos.h +++ b/adapter/ohos/entrance/subwindow/subwindow_ohos.h @@ -64,14 +64,12 @@ public: void ShowPopup(const RefPtr& newComponent, bool disableTouchEvent = true) override; void ShowPopupNG(int32_t targetId, const NG::PopupInfo& popupInfo) override; void HidePopupNG(int32_t targetId) override; - void HidePopupNG() override; void GetPopupInfoNG(int32_t targetId, NG::PopupInfo& popupInfo) override; bool CancelPopup(const std::string& id) override; void CloseMenu() override; void ClearMenu() override; void ClearMenuNG() override; - RefPtr ShowDialogNG( - const DialogProperties& dialogProps, const RefPtr& customNode) override; + RefPtr ShowDialogNG(const DialogProperties& dialogProps, std::function&& buildFunc) override; void HideSubWindowNG() override; bool GetShown() override { diff --git a/adapter/ohos/entrance/ui_content_impl.cpp b/adapter/ohos/entrance/ui_content_impl.cpp index 67028aa3788..f3d8376f0c3 100644 --- a/adapter/ohos/entrance/ui_content_impl.cpp +++ b/adapter/ohos/entrance/ui_content_impl.cpp @@ -255,10 +255,10 @@ public: CHECK_NULL_VOID(taskExecutor); ContainerScope scope(instanceId_); taskExecutor->PostTask( - [] { + [instanceId = instanceId_] { SubwindowManager::GetInstance()->ClearMenu(); - SubwindowManager::GetInstance()->ClearMenuNG(); - SubwindowManager::GetInstance()->HidePopupNG(); + SubwindowManager::GetInstance()->ClearMenuNG(instanceId); + SubwindowManager::GetInstance()->HidePopupNG(-1, instanceId); }, TaskExecutor::TaskType::UI); } diff --git a/adapter/ohos/osal/BUILD.gn b/adapter/ohos/osal/BUILD.gn index 99c692174df..d2db5f6cf27 100644 --- a/adapter/ohos/osal/BUILD.gn +++ b/adapter/ohos/osal/BUILD.gn @@ -56,6 +56,7 @@ template("ace_osal_ohos_source_set") { "ace_engine_ext.cpp", "ace_trace.cpp", "anr_thread.cpp", + "app_bar_helper_impl.cpp", "event_report.cpp", "exception_handler.cpp", "frame_report.cpp", @@ -65,14 +66,10 @@ template("ace_osal_ohos_source_set") { "socperf_client_impl.cpp", "system_properties.cpp", "trace_id_impl.cpp", - "ui_extension_helper_impl.cpp", "want_wrap_ohos.cpp", ] - external_deps += [ - "init:libbegetutil", - "window_manager:libwsutils", - ] + external_deps += [ "init:libbegetutil" ] if (is_ohos_standard_system) { sources += [ @@ -133,12 +130,15 @@ template("ace_osal_ohos_source_set") { external_deps += [ "ability_runtime:abilitykit_native", "ability_runtime:runtime", + "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "graphic_2d:librender_service_client", "hichecker:libhichecker", "hicollie:libhicollie", "hisysevent:libhisysevent", "hitrace:libhitracechain", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", ] deps += [ "$ace_root/interfaces/inner_api/drawable_descriptor:drawable_descriptor", diff --git a/adapter/ohos/osal/ui_extension_helper_impl.cpp b/adapter/ohos/osal/app_bar_helper_impl.cpp similarity index 51% rename from adapter/ohos/osal/ui_extension_helper_impl.cpp rename to adapter/ohos/osal/app_bar_helper_impl.cpp index 750c5558291..68ae3c82638 100644 --- a/adapter/ohos/osal/ui_extension_helper_impl.cpp +++ b/adapter/ohos/osal/app_bar_helper_impl.cpp @@ -13,13 +13,17 @@ * limitations under the License. */ -#include "core/common/ui_extension_helper.h" +#include "core/common/app_bar_helper.h" + +#include "bundlemgr/bundle_mgr_interface.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" #include "core/components_ng/pattern/ui_extension/ui_extension_model_ng.h" namespace OHOS::Ace { -RefPtr UIExtensionHelper::CreateUIExtensionNode(const std::string& bundleName, +RefPtr AppBarHelper::CreateUIExtensionNode(const std::string& bundleName, const std::string& abilityName, const std::map& params, std::function&& onRelease, std::function&& onError) @@ -27,4 +31,25 @@ RefPtr UIExtensionHelper::CreateUIExtensionNode(const std::string return NG::UIExtensionModelNG::Create(bundleName, abilityName, params, std::move(onRelease), std::move(onError)); } +std::string AppBarHelper::QueryAppGalleryBundleName() +{ + auto systemAbilityMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + CHECK_NULL_RETURN(systemAbilityMgr, ""); + + auto bundleObj = systemAbilityMgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + CHECK_NULL_RETURN(bundleObj, ""); + + auto bundleMgr = iface_cast(bundleObj); + CHECK_NULL_RETURN(bundleMgr, ""); + + std::string bundleName = ""; + auto result = bundleMgr->QueryAppGalleryBundleName(bundleName); + if (!result) { + LOGE("Query BundleName fail!"); + } else { + LOGI("BundleName: %{public}s", bundleName.c_str()); + } + return bundleName; +} + } // namespace OHOS::Ace \ No newline at end of file diff --git a/adapter/ohos/osal/js_accessibility_manager.cpp b/adapter/ohos/osal/js_accessibility_manager.cpp index ed447dfa85a..9ac26b6e7a3 100644 --- a/adapter/ohos/osal/js_accessibility_manager.cpp +++ b/adapter/ohos/osal/js_accessibility_manager.cpp @@ -647,6 +647,7 @@ void GetFrameNodeChildren(const RefPtr& uiNode, std::vector { auto frameNode = AceType::DynamicCast(uiNode); if (AceType::InstanceOf(uiNode)) { + CHECK_NULL_VOID_NOLOG(frameNode->IsActive()); if (uiNode->GetTag() == "stage") { } else if (uiNode->GetTag() == "page") { if (uiNode->GetPageId() != pageId) { @@ -830,10 +831,6 @@ void UpdateAccessibilityElementInfo(const RefPtr& node, const Com AccessibilityElementInfo& nodeInfo, const RefPtr& ngPipeline) { CHECK_NULL_VOID_NOLOG(node); - NG::RectF rect; - if (node->IsActive()) { - rect = node->GetTransformRectRelativeToWindow(); - } nodeInfo.SetParent(GetParentId(node)); std::vector children; for (const auto& item : node->GetChildren()) { @@ -852,6 +849,7 @@ void UpdateAccessibilityElementInfo(const RefPtr& node, const Com nodeInfo.SetInspectorKey(node->GetInspectorId().value_or("")); nodeInfo.SetVisible(node->IsVisible()); if (node->IsVisible()) { + auto rect = node->GetTransformRectRelativeToWindow(); auto left = rect.Left() + commonProperty.windowLeft; auto top = rect.Top() + commonProperty.windowTop; auto right = rect.Right() + commonProperty.windowLeft; diff --git a/adapter/ohos/osal/resource_theme_style.cpp b/adapter/ohos/osal/resource_theme_style.cpp index f31dda99302..96142a1dc36 100644 --- a/adapter/ohos/osal/resource_theme_style.cpp +++ b/adapter/ohos/osal/resource_theme_style.cpp @@ -52,13 +52,14 @@ static const std::set stringAttrs = { "description_current_position", "description_paste", "description_download", - "description_download_files", + "description_download_file", "description_save", - "description_save_images", - "description_save_files", + "description_save_image", + "description_save_file", "description_download_and_share", "description_receive", "description_continue_to_receive", + "draggable", }; double ParseDoubleUnit(const std::string& value, std::string& unit) diff --git a/adapter/ohos/osal/system_properties.cpp b/adapter/ohos/osal/system_properties.cpp index 0ce053384c0..adffe55a18a 100644 --- a/adapter/ohos/osal/system_properties.cpp +++ b/adapter/ohos/osal/system_properties.cpp @@ -23,7 +23,6 @@ #include "parameter.h" #include "parameters.h" -#include "scene_board_judgement.h" #include "base/log/log.h" #include "base/utils/utils.h" @@ -441,15 +440,4 @@ bool SystemProperties::IsFormAnimationLimited() return system::GetBoolParameter("persist.sys.arkui.formAnimationLimit", true); } -bool SystemProperties::IsSceneBoardEnabled() -{ - return Rosen::SceneBoardJudgement::IsSceneBoardEnabled(); -} - -void SystemProperties::GetAppBarInfo(std::string& bundleName, std::string& abilityName) -{ - bundleName = system::GetParameter("persist.ace.appbar.bundlename", ""); - abilityName = system::GetParameter("persist.ace.appbar.abilityname", ""); -} - } // namespace OHOS::Ace diff --git a/adapter/preview/osal/BUILD.gn b/adapter/preview/osal/BUILD.gn index 88a0cf043e8..a433ace2e35 100644 --- a/adapter/preview/osal/BUILD.gn +++ b/adapter/preview/osal/BUILD.gn @@ -62,6 +62,7 @@ ohos_source_set("preview_osal_source") { "ace_checker.cpp", "ace_engine_ext.cpp", "ace_trace.cpp", + "app_bar_helper_impl.cpp", "event_report.cpp", "exception_handler.cpp", "fetch_manager.cpp", @@ -75,7 +76,6 @@ ohos_source_set("preview_osal_source") { "stage_card_parser.cpp", "system_properties.cpp", "trace_id_impl.cpp", - "ui_extension_helper_impl.cpp", ] cflags_cc = [ diff --git a/adapter/preview/osal/ui_extension_helper_impl.cpp b/adapter/preview/osal/app_bar_helper_impl.cpp similarity index 80% rename from adapter/preview/osal/ui_extension_helper_impl.cpp rename to adapter/preview/osal/app_bar_helper_impl.cpp index 72e6866865d..afff65eb9c0 100644 --- a/adapter/preview/osal/ui_extension_helper_impl.cpp +++ b/adapter/preview/osal/app_bar_helper_impl.cpp @@ -13,13 +13,13 @@ * limitations under the License. */ -#include "core/common/ui_extension_helper.h" +#include "core/common/app_bar_helper.h" #include "core/components_ng/pattern/ui_extension/ui_extension_model_ng.h" namespace OHOS::Ace { -RefPtr UIExtensionHelper::CreateUIExtensionNode(const std::string& bundleName, +RefPtr AppBarHelper::CreateUIExtensionNode(const std::string& bundleName, const std::string& abilityName, const std::map& params, std::function&& onRelease, std::function&& onError) @@ -27,4 +27,9 @@ RefPtr UIExtensionHelper::CreateUIExtensionNode(const std::string return nullptr; } +std::string AppBarHelper::QueryAppGalleryBundleName() +{ + return ""; +} + } // namespace OHOS::Ace \ No newline at end of file diff --git a/adapter/preview/osal/system_properties.cpp b/adapter/preview/osal/system_properties.cpp index 1bc6af1c591..7981fcbfdb6 100644 --- a/adapter/preview/osal/system_properties.cpp +++ b/adapter/preview/osal/system_properties.cpp @@ -213,12 +213,4 @@ bool SystemProperties::GetImageFrameworkEnabled() { return false; } - -bool SystemProperties::IsSceneBoardEnabled() -{ - return false; -} - -void SystemProperties::GetAppBarInfo(std::string& bundleName, std::string& abilityName) {} - } // namespace OHOS::Ace diff --git a/frameworks/base/BUILD.gn b/frameworks/base/BUILD.gn index 934ae2f3fac..ca04900edae 100644 --- a/frameworks/base/BUILD.gn +++ b/frameworks/base/BUILD.gn @@ -173,7 +173,6 @@ foreach(item, ace_platforms) { "hichecker:libhichecker", "init:libbeget_proxy", "init:libbegetutil", - "window_manager:libwsutils", ] } } diff --git a/frameworks/base/subwindow/subwindow.h b/frameworks/base/subwindow/subwindow.h index a2d656ecfc4..c903d4517ed 100644 --- a/frameworks/base/subwindow/subwindow.h +++ b/frameworks/base/subwindow/subwindow.h @@ -44,14 +44,13 @@ public: virtual void ShowPopup(const RefPtr& newComponent, bool disableTouchEvent = true) = 0; virtual void ShowPopupNG(int32_t targetId, const NG::PopupInfo& popupInfo) = 0; virtual void HidePopupNG(int32_t targetId) = 0; - virtual void HidePopupNG() = 0; virtual void GetPopupInfoNG(int32_t targetId, NG::PopupInfo& popupInfo) = 0; virtual bool CancelPopup(const std::string& id) = 0; virtual void CloseMenu() = 0; virtual void ClearMenu() {}; virtual void ClearMenuNG() = 0; virtual RefPtr ShowDialogNG( - const DialogProperties& dialogProps, const RefPtr& customNode) = 0; + const DialogProperties& dialogProps, std::function&& buildFunc) = 0; virtual void HideSubWindowNG() = 0; virtual int32_t GetChildContainerId() const = 0; virtual bool GetShown() = 0; diff --git a/frameworks/base/subwindow/subwindow_manager.cpp b/frameworks/base/subwindow/subwindow_manager.cpp index 6afaf5939c2..0885b7ada2e 100644 --- a/frameworks/base/subwindow/subwindow_manager.cpp +++ b/frameworks/base/subwindow/subwindow_manager.cpp @@ -243,22 +243,21 @@ void SubwindowManager::ShowPopupNG(int32_t targetId, const NG::PopupInfo& popupI TaskExecutor::TaskType::PLATFORM); } -void SubwindowManager::HidePopupNG(int32_t targetId) +void SubwindowManager::HidePopupNG(int32_t targetId, int32_t instanceId) { - auto subwindow = GetCurrentWindow(); + RefPtr subwindow; + if (instanceId != -1) { + // get the subwindow which overlay node in, not current + subwindow = GetSubwindow(instanceId >= MIN_SUBCONTAINER_ID ? GetParentContainerId(instanceId) : instanceId); + } else { + subwindow = GetCurrentWindow(); + } + if (subwindow) { subwindow->HidePopupNG(targetId); } } -void SubwindowManager::HidePopupNG() -{ - auto subwindow = GetCurrentWindow(); - if (subwindow) { - subwindow->HidePopupNG(); - } -} - void SubwindowManager::ShowPopup(const RefPtr& newComponent, bool disableTouchEvent) { auto containerId = Container::CurrentId(); @@ -326,16 +325,23 @@ void SubwindowManager::ClearMenu() } } -void SubwindowManager::SetHotAreas(const std::vector& rects, int32_t overlayId) +void SubwindowManager::SetHotAreas(const std::vector& rects, int32_t overlayId, int32_t instanceId) { - auto subwindow = GetCurrentWindow(); + RefPtr subwindow; + if (instanceId != -1) { + // get the subwindow which overlay node in, not current + subwindow = GetSubwindow(instanceId >= MIN_SUBCONTAINER_ID ? GetParentContainerId(instanceId) : instanceId); + } else { + subwindow = GetCurrentWindow(); + } + if (subwindow) { subwindow->SetHotAreas(rects, overlayId); } } RefPtr SubwindowManager::ShowDialogNG( - const DialogProperties& dialogProps, const RefPtr& customNode) + const DialogProperties& dialogProps, std::function&& buildFunc) { auto containerId = Container::CurrentId(); auto subwindow = GetSubwindow(containerId); @@ -345,7 +351,7 @@ RefPtr SubwindowManager::ShowDialogNG( subwindow->InitContainer(); AddSubwindow(containerId, subwindow); } - return subwindow->ShowDialogNG(dialogProps, customNode); + return subwindow->ShowDialogNG(dialogProps, std::move(buildFunc)); } void SubwindowManager::AddDialogSubwindow(int32_t instanceId, const RefPtr& subwindow) diff --git a/frameworks/base/subwindow/subwindow_manager.h b/frameworks/base/subwindow/subwindow_manager.h index b41b257aee2..9a6176246eb 100644 --- a/frameworks/base/subwindow/subwindow_manager.h +++ b/frameworks/base/subwindow/subwindow_manager.h @@ -70,16 +70,15 @@ public: void HideMenuNG(); void ShowPopup(const RefPtr& newComponent, bool disableTouchEvent = true); void ShowPopupNG(int32_t targetId, const NG::PopupInfo& popupInfo); - void HidePopupNG(int32_t targetId); - void HidePopupNG(); + void HidePopupNG(int32_t targetId, int32_t instanceId = -1); bool CancelPopup(const std::string& id); void CloseMenu(); void ClearMenu(); void ClearMenuNG(int32_t instanceId = -1); - RefPtr ShowDialogNG(const DialogProperties& dialogProps, const RefPtr& customNode); + RefPtr ShowDialogNG(const DialogProperties& dialogProps, std::function&& buildFunc); void HideSubWindowNG(); - void SetHotAreas(const std::vector& rects, int32_t overlayId = -1); + void SetHotAreas(const std::vector& rects, int32_t overlayId = -1, int32_t instanceId = -1); void AddDialogSubwindow(int32_t instanceId, const RefPtr& subwindow); // Get the dialog subwindow of instance, return the window or nullptr. diff --git a/frameworks/base/test/mock/mock_subwindow_manager.cpp b/frameworks/base/test/mock/mock_subwindow_manager.cpp index c143da9bac2..02aae540e7b 100644 --- a/frameworks/base/test/mock/mock_subwindow_manager.cpp +++ b/frameworks/base/test/mock/mock_subwindow_manager.cpp @@ -30,7 +30,7 @@ std::shared_ptr SubwindowManager::GetInstance() return instance_; } -void SubwindowManager::HidePopupNG(int32_t targetId) +void SubwindowManager::HidePopupNG(int32_t targetId, int32_t instanceId) { LOGI("SubwindowManager::HidePopupNG MOCK"); } @@ -41,7 +41,7 @@ void SubwindowManager::HideMenuNG(int32_t targetId) {} void SubwindowManager::HideMenuNG() {} -void SubwindowManager::SetHotAreas(const std::vector& rects, int32_t overlayId) {} +void SubwindowManager::SetHotAreas(const std::vector& rects, int32_t overlayId, int32_t instanceId) {} const RefPtr& SubwindowManager::GetCurrentWindow() { diff --git a/frameworks/base/utils/system_properties.h b/frameworks/base/utils/system_properties.h index ce4b0bf1c8d..8be6e2eac15 100644 --- a/frameworks/base/utils/system_properties.h +++ b/frameworks/base/utils/system_properties.h @@ -348,10 +348,6 @@ public: static bool IsFormAnimationLimited(); - static bool IsSceneBoardEnabled(); - - static void GetAppBarInfo(std::string& bundleName, std::string& abilityName); - private: static bool traceEnabled_; static bool svgTraceEnable_; diff --git a/frameworks/bridge/card_frontend/card_frontend.h b/frameworks/bridge/card_frontend/card_frontend.h index ec223d81fdb..c6ff09cf267 100644 --- a/frameworks/bridge/card_frontend/card_frontend.h +++ b/frameworks/bridge/card_frontend/card_frontend.h @@ -127,11 +127,6 @@ public: return eventHandler_; } - FrontendType GetType() override - { - return type_; - } - // judge frontend is foreground frontend. bool IsForeground() override { @@ -205,7 +200,6 @@ protected: void ParseManifest() const; ColorMode colorMode_ = ColorMode::LIGHT; - FrontendType type_ = FrontendType::JS_CARD; bool foregroundFrontend_ = false; bool pageLoaded_ = false; double density_ = 1.0; @@ -217,7 +211,6 @@ protected: OnFormVisibleCallback onFormVisibleCallback_; mutable std::once_flag onceFlag_; - RefPtr taskExecutor_; RefPtr eventHandler_; Framework::PageIdPool pageIdPool_; std::string formSrc_; diff --git a/frameworks/bridge/declarative_frontend/BUILD.gn b/frameworks/bridge/declarative_frontend/BUILD.gn index a7776c94c1c..ae00cef415f 100644 --- a/frameworks/bridge/declarative_frontend/BUILD.gn +++ b/frameworks/bridge/declarative_frontend/BUILD.gn @@ -210,6 +210,7 @@ template("declarative_js_engine") { "jsview/js_list_item_group.cpp", "jsview/js_loading_progress.cpp", "jsview/js_local_storage.cpp", + "jsview/js_location_button.cpp", "jsview/js_marquee.cpp", "jsview/js_matrix2d.cpp", "jsview/js_menu.cpp", @@ -224,6 +225,7 @@ template("declarative_js_engine") { "jsview/js_offscreen_rendering_context.cpp", "jsview/js_page_transition.cpp", "jsview/js_pan_handler.cpp", + "jsview/js_paste_button.cpp", "jsview/js_path.cpp", "jsview/js_path2d.cpp", "jsview/js_pattern_lock.cpp", @@ -243,14 +245,12 @@ template("declarative_js_engine") { "jsview/js_richeditor.cpp", "jsview/js_row.cpp", "jsview/js_row_split.cpp", + "jsview/js_save_button.cpp", "jsview/js_scope_util.cpp", "jsview/js_scroll.cpp", "jsview/js_scroller.cpp", "jsview/js_search.cpp", "jsview/js_sec_button_base.cpp", - "jsview/js_sec_location_button.cpp", - "jsview/js_sec_paste_button.cpp", - "jsview/js_sec_save_button.cpp", "jsview/js_select.cpp", "jsview/js_shape.cpp", "jsview/js_shape_abstract.cpp", diff --git a/frameworks/bridge/declarative_frontend/declarative_frontend.cpp b/frameworks/bridge/declarative_frontend/declarative_frontend.cpp index 8a1ed7780ff..18641fda953 100644 --- a/frameworks/bridge/declarative_frontend/declarative_frontend.cpp +++ b/frameworks/bridge/declarative_frontend/declarative_frontend.cpp @@ -182,6 +182,7 @@ bool DeclarativeFrontend::Initialize(FrontendType type, const RefPtr& page) override {}; + void AddPage(const RefPtr& page) override {} RefPtr GetPage(int32_t /*pageId*/) const override { return nullptr; - }; + } std::string GetCurrentPageUrl() const override; @@ -153,11 +153,6 @@ public: RefPtr GetEventHandler() override { return handler_; - }; - - FrontendType GetType() override - { - return type_; } // judge frontend is foreground frontend. @@ -237,7 +232,6 @@ protected: private: void InitializeFrontendDelegate(const RefPtr& taskExecutor); - FrontendType type_ = FrontendType::DECLARATIVE_JS; RefPtr handler_; RefPtr jsEngine_; RefPtr accessibilityManager_; diff --git a/frameworks/bridge/declarative_frontend/engine/jsEnumStyle.js b/frameworks/bridge/declarative_frontend/engine/jsEnumStyle.js index a219fbc58c8..6dd6d66ccf5 100644 --- a/frameworks/bridge/declarative_frontend/engine/jsEnumStyle.js +++ b/frameworks/bridge/declarative_frontend/engine/jsEnumStyle.js @@ -1569,31 +1569,6 @@ var SecurityComponentLayoutDirection; SecurityComponentLayoutDirection[SecurityComponentLayoutDirection["VERTICAL"] = 1] = "VERTICAL"; })(SecurityComponentLayoutDirection || (SecurityComponentLayoutDirection = {})); -var SecurityComponentLayoutOrder; -(function (SecurityComponentLayoutOrder) { - SecurityComponentLayoutOrder[SecurityComponentLayoutOrder["ICON_FIRST"] = 0] = "ICON_FIRST"; - SecurityComponentLayoutOrder[SecurityComponentLayoutOrder["TEXT_FIRST"] = 1] = "TEXT_FIRST "; -})(SecurityComponentLayoutOrder || (SecurityComponentLayoutOrder = {})); - -var SecLocationButtonLayoutDirection; -(function (SecLocationButtonLayoutDirection) { - SecLocationButtonLayoutDirection[SecLocationButtonLayoutDirection["HORIZONTAL"] = 0] = "HORIZONTAL"; - SecLocationButtonLayoutDirection[SecLocationButtonLayoutDirection["VERTICAL"] = 1] = "VERTICAL"; -})(SecLocationButtonLayoutDirection || (SecLocationButtonLayoutDirection = {})); - -var SecLocationButtonLayoutOrder; -(function (SecLocationButtonLayoutOrder) { - SecLocationButtonLayoutOrder[SecLocationButtonLayoutOrder["ICON_FIRST"] = 0] = "ICON_FIRST"; - SecLocationButtonLayoutOrder[SecLocationButtonLayoutOrder["TEXT_FIRST"] = 1] = "TEXT_FIRST "; -})(SecLocationButtonLayoutOrder || (SecLocationButtonLayoutOrder = {})); - -var BackgroundButtonType; -(function (BackgroundButtonType) { - BackgroundButtonType[BackgroundButtonType["CAPSULE_BACKGROUND"] = 0] = "CAPSULE_BACKGROUND"; - BackgroundButtonType[BackgroundButtonType["CIRCLE_BACKGROUND"] = 1] = "CIRCLE_BACKGROUND"; - BackgroundButtonType[BackgroundButtonType["NORMAL_BACKGROUND"] = 2] = "NORMAL_BACKGROUND"; -})(BackgroundButtonType || (BackgroundButtonType = {})); - var LocationIconStyle; (function (LocationIconStyle) { LocationIconStyle[LocationIconStyle["FULL_FILLED"] = 0] = "FULL_FILLED"; @@ -1615,13 +1590,13 @@ var LocationDescription; LocationDescription[LocationDescription["CURRENT_POSITION"] = 10] = "CURRENT_POSITION"; })(LocationDescription || (LocationDescription = {})); -var SecLocationButtonOnClickResult; -(function (SecLocationButtonOnClickResult) { - SecLocationButtonOnClickResult[SecLocationButtonOnClickResult["LOCATION_BUTTON_CLICK_SUCCESS"] = 0] = - "LOCATION_BUTTON_CLICK_SUCCESS"; - SecLocationButtonOnClickResult[SecLocationButtonOnClickResult["LOCATION_BUTTON_CLICK_GRANT_FAILED"] = 1] = - "LOCATION_BUTTON_CLICK_GRANT_FAILED "; -})(SecLocationButtonOnClickResult || (SecLocationButtonOnClickResult = {})); +var LocationButtonOnClickResult; +(function (LocationButtonOnClickResult) { + LocationButtonOnClickResult[LocationButtonOnClickResult["SUCCESS"] = 0] = + "SUCCESS"; + LocationButtonOnClickResult[LocationButtonOnClickResult["TEMPORARY_AUTHORIZATION_FAILED"] = 1] = + "TEMPORARY_AUTHORIZATION_FAILED "; +})(LocationButtonOnClickResult || (LocationButtonOnClickResult = {})); var PasteIconStyle; (function (PasteIconStyle) { @@ -1633,13 +1608,13 @@ var PasteDescription; PasteDescription[PasteDescription["PASTE"] = 0] = "PASTE"; })(PasteDescription || (PasteDescription = {})); -var SecPasteButtonOnClickResult; -(function (SecPasteButtonOnClickResult) { - SecPasteButtonOnClickResult[SecPasteButtonOnClickResult["SUCCESS"] = 0] = +var PasteButtonOnClickResult; +(function (PasteButtonOnClickResult) { + PasteButtonOnClickResult[PasteButtonOnClickResult["SUCCESS"] = 0] = "SUCCESS"; - SecPasteButtonOnClickResult[SecPasteButtonOnClickResult["TEMPORARY_AUTHORIZATION_FAILED"] = 1] = + PasteButtonOnClickResult[PasteButtonOnClickResult["TEMPORARY_AUTHORIZATION_FAILED"] = 1] = "TEMPORARY_AUTHORIZATION_FAILED "; -})(SecPasteButtonOnClickResult || (SecPasteButtonOnClickResult = {})); +})(PasteButtonOnClickResult || (PasteButtonOnClickResult = {})); var SaveIconStyle; (function (SaveIconStyle) { @@ -1650,22 +1625,22 @@ var SaveIconStyle; var SaveDescription; (function (SaveDescription) { SaveDescription[SaveDescription["DOWNLOAD"] = 0] = "DOWNLOAD"; - SaveDescription[SaveDescription["DOWNLOAD_FILES"] = 1] = "DOWNLOAD_FILES"; + SaveDescription[SaveDescription["DOWNLOAD_FILE"] = 1] = "DOWNLOAD_FILE"; SaveDescription[SaveDescription["SAVE"] = 2] = "SAVE"; - SaveDescription[SaveDescription["SAVE_IMAGES"] = 3] = "SAVE_IMAGES"; - SaveDescription[SaveDescription["SAVE_FILES"] = 4] = "SAVE_FILES"; + SaveDescription[SaveDescription["SAVE_IMAGE"] = 3] = "SAVE_IMAGE"; + SaveDescription[SaveDescription["SAVE_FILE"] = 4] = "SAVE_FILE"; SaveDescription[SaveDescription["DOWNLOAD_AND_SHARE"] = 5] = "DOWNLOAD_AND_SHARE"; SaveDescription[SaveDescription["RECEIVE"] = 6] = "RECEIVE"; SaveDescription[SaveDescription["CONTINUE_TO_RECEIVE"] = 7] = "CONTINUE_TO_RECEIVE"; })(SaveDescription || (SaveDescription = {})); -var SecSaveButtonOnClickResult; -(function (SecSaveButtonOnClickResult) { - SecSaveButtonOnClickResult[SecSaveButtonOnClickResult["SUCCESS"] = 0] = +var SaveButtonOnClickResult; +(function (SaveButtonOnClickResult) { + SaveButtonOnClickResult[SaveButtonOnClickResult["SUCCESS"] = 0] = "SUCCESS"; - SecSaveButtonOnClickResult[SecSaveButtonOnClickResult["TEMPORARY_AUTHORIZATION_FAILED"] = 1] = + SaveButtonOnClickResult[SaveButtonOnClickResult["TEMPORARY_AUTHORIZATION_FAILED"] = 1] = "TEMPORARY_AUTHORIZATION_FAILED "; -})(SecSaveButtonOnClickResult || (SecSaveButtonOnClickResult = {})); +})(SaveButtonOnClickResult || (SaveButtonOnClickResult = {})); var ObscuredReasons; (function (ObscuredReasons) { diff --git a/frameworks/bridge/declarative_frontend/engine/jsi/jsi_view_register_impl.cpp b/frameworks/bridge/declarative_frontend/engine/jsi/jsi_view_register_impl.cpp index 9e1f5b3244e..f5fdd2545ee 100644 --- a/frameworks/bridge/declarative_frontend/engine/jsi/jsi_view_register_impl.cpp +++ b/frameworks/bridge/declarative_frontend/engine/jsi/jsi_view_register_impl.cpp @@ -80,6 +80,7 @@ #include "bridge/declarative_frontend/jsview/js_list_item_group.h" #include "bridge/declarative_frontend/jsview/js_loading_progress.h" #include "bridge/declarative_frontend/jsview/js_local_storage.h" +#include "bridge/declarative_frontend/jsview/js_location_button.h" #include "bridge/declarative_frontend/jsview/js_marquee.h" #include "bridge/declarative_frontend/jsview/js_matrix2d.h" #include "bridge/declarative_frontend/jsview/js_menu.h" @@ -93,6 +94,7 @@ #include "bridge/declarative_frontend/jsview/js_offscreen_rendering_context.h" #include "bridge/declarative_frontend/jsview/js_page_transition.h" #include "bridge/declarative_frontend/jsview/js_pan_handler.h" +#include "bridge/declarative_frontend/jsview/js_paste_button.h" #include "bridge/declarative_frontend/jsview/js_path.h" #include "bridge/declarative_frontend/jsview/js_path2d.h" #include "bridge/declarative_frontend/jsview/js_pattern_lock.h" @@ -112,13 +114,11 @@ #include "bridge/declarative_frontend/jsview/js_richeditor.h" #include "bridge/declarative_frontend/jsview/js_row.h" #include "bridge/declarative_frontend/jsview/js_row_split.h" +#include "bridge/declarative_frontend/jsview/js_save_button.h" #include "bridge/declarative_frontend/jsview/js_scope_util.h" #include "bridge/declarative_frontend/jsview/js_scroll.h" #include "bridge/declarative_frontend/jsview/js_scroller.h" #include "bridge/declarative_frontend/jsview/js_search.h" -#include "bridge/declarative_frontend/jsview/js_sec_location_button.h" -#include "bridge/declarative_frontend/jsview/js_sec_paste_button.h" -#include "bridge/declarative_frontend/jsview/js_sec_save_button.h" #include "bridge/declarative_frontend/jsview/js_select.h" #include "bridge/declarative_frontend/jsview/js_shape.h" #include "bridge/declarative_frontend/jsview/js_shape_abstract.h" @@ -528,9 +528,9 @@ static const std::unordered_map> { "AlertDialog", JSAlertDialog::JSBind }, { "ContextMenu", JSContextMenu::JSBind }, { "FormLink", JSFormLink::JSBind }, - { "SecLocationButton", JSSecLocationButton::JSBind }, - { "SecPasteButton", JSSecPasteButton::JSBind }, - { "SecSaveButton", JSSecSaveButton::JSBind }, + { "LocationButton", JSLocationButton::JSBind }, + { "PasteButton", JSPasteButton::JSBind }, + { "SaveButton", JSSaveButton::JSBind }, #ifdef ABILITY_COMPONENT_SUPPORTED { "AbilityComponent", JSAbilityComponent::JSBind }, #endif diff --git a/frameworks/bridge/declarative_frontend/engine/stateMgmt.js b/frameworks/bridge/declarative_frontend/engine/stateMgmt.js index 79874cd6d4e..1ec09cdb781 100644 --- a/frameworks/bridge/declarative_frontend/engine/stateMgmt.js +++ b/frameworks/bridge/declarative_frontend/engine/stateMgmt.js @@ -1782,6 +1782,30 @@ class stateMgmtTrace { return result; } } +class errorReport { + static varValueCheckFailed(params) { + let msg = `@Component '${params.customComponent}': Illegal variable value error with decorated variable ${params.variableDeco} '${params.variableName}': `; + msg += `failed validation: '${params.expectedType}`; + try { + msg += `, attempt to assign value type: '${typeof params.value}'`; + msg += `, value: '${JSON.stringify(params.value, null, 4)}'`; + } + catch (e) { } + msg += "!"; + throw new TypeError(msg); + } + static varObservationFailed(params) { + let msg = `@Component '${params.customComponent}': decorated variable ${params.variableDeco} '${params.variableName}': `; + msg += `its class is neither decorated with '@Observed' nor it is an instance of 'SubscribableAbstract'`; + try { + msg += `, attempt to assign value type: '${typeof params.value}'`; + msg += `, value: '${JSON.stringify(params.value, null, 4)}'`; + } + catch (e) { } + msg += "!"; + throw new TypeError(msg); + } +} /* * Copyright (c) 2022-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); @@ -3472,6 +3496,50 @@ class ObservedPropertyAbstractPU extends ObservedPropertyAbstract { numberOfSubscrbers() { return this.subscriberRefs_.size + (this.owningView_ ? 1 : 0); } + /* + type checking for any supported type, as required for union type support + see 1st parameter for explanation what is allowed + + FIXME this expects the Map, Set patch to go in + */ + checkIsSupportedValue(value) { + return this.checkNewValue(`undefined, null, number, boolean, string, or Object but not function`, value, () => ((typeof value == "object" && typeof value != "function") + || typeof value == "number" || typeof value == "string" || typeof value == "boolean") + || (value == undefined || value == null)); + } + /* + type checking for allowed Object type value + see 1st parameter for explanation what is allowed + + FIXME this expects the Map, Set patch to go in + */ + checkIsObject(value) { + return this.checkNewValue(`undefined, null, Object including Array and instance of SubscribableAbstract and excluding function, Set, and Map`, value, () => (value == undefined || value == null || (typeof value == "object"))); + } + /* + type checking for allowed simple types value + see 1st parameter for explanation what is allowed + */ + checkIsSimple(value) { + return this.checkNewValue(`undefined, number, boolean, string`, value, () => (value == undefined || typeof value == "number" || typeof value == "string" || typeof value == "boolean")); + } + checkNewValue(isAllowedComment, newValue, validator) { + if (validator(newValue)) { + return true; + } + // report error + // current implementation throws an Exception + errorReport.varValueCheckFailed({ + customComponent: this.owningView_ ? this.owningView_.constructor.name : "unknown owningView / internal error", + variableDeco: ObservedPropertyAbstractPU.mapDeco.get(this.constructor.name), + variableName: this.info(), + expectedType: isAllowedComment, + value: newValue + }); + // never gets here if errorReport.varValueCheckFailed throws an exception + // but should nto depend on its implementation + return false; + } /** * factory function for concrete 'object' or 'simple' ObservedProperty object * depending if value is Class object @@ -3542,58 +3610,16 @@ ObservedPropertyAbstractPU.DelayedNotifyChangesEnum = (_a = class { _a.delay_none_pending = 1, _a.delay_notification_pending = 2, _a); -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * ObservedPropertyObjectAbstractPU - * - * common bbase class of ObservedPropertyObjectPU and - * SyncedObjectPropertyTwoWayPU - * adds the createObjectLink to the ObservedPropertyAbstract base - * - * all definitions in this file are framework internal - */ -class ObservedPropertyObjectAbstractPU extends ObservedPropertyAbstractPU { - constructor(owningView, thisPropertyName) { - super(owningView, thisPropertyName); - } -} -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * ObservedPropertySimpleAbstractPU - * - * all definitions in this file are framework internal - */ -class ObservedPropertySimpleAbstractPU extends ObservedPropertyAbstractPU { - constructor(owningView, propertyName) { - super(owningView, propertyName); - } -} +ObservedPropertyAbstractPU.mapDeco = new Map([ + ["ObservedPropertyObjectPU", "@State/@Provide"], + ["ObservedPropertySimplePU", "@State/@Provide (error, should not be used)"], + ["SynchedPropertyObjectOneWayPU", "@Prop"], + ["SynchedPropertySimpleOneWayPU", "@Prop (error, should not be used)"], + ["SynchedPropertyObjectTwoWayPU", "@Link/@Consume"], + ["SynchedPropertySimpleTwoWayPU", "@Link/@Consume (error, should not be used)"], + ["SynchedPropertyNestedObjectPU", "@ObjectLink (only class-objects supported"], + ["SynchedPropertyNesedObjectPU", "@ObjectLink (only class-objects supported"] +]); /* * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); @@ -3618,7 +3644,7 @@ class ObservedPropertySimpleAbstractPU extends ObservedPropertyAbstractPU { * uses its base class to manage subscribers to this * property. */ -class ObservedPropertyObjectPU extends ObservedPropertyObjectAbstractPU { +class ObservedPropertyPU extends ObservedPropertyAbstractPU { constructor(localInitValue, owningView, propertyName) { super(owningView, propertyName); this.setValueInternal(localInitValue); @@ -3665,21 +3691,20 @@ class ObservedPropertyObjectPU extends ObservedPropertyObjectAbstractPU { and also notify with this.aboutToChange(); */ setValueInternal(newValue) { - if (newValue == undefined || newValue == null) { - stateMgmtConsole.error(`ObservedPropertyObjectPU[${this.id__()}, '${this.info() || "unknown"}']: constructor @State/@Provide value must not be undefined or null. Application error!`); - // TODO enable support for undefined and null - // unsubscribe old value, set wrappedValue_ to null/undefined - } - if (typeof newValue !== 'object') { - - return false; - } if (newValue == this.wrappedValue_) { return false; } + if (!this.checkIsSupportedValue(newValue)) { + return false; + } this.unsubscribeWrappedObject(); - if (newValue instanceof SubscribableAbstract) { + if (!newValue || typeof newValue !== 'object') { + // undefined, null, simple type: + // nothing to subscribe to in case of new value undefined || null || simple type + this.wrappedValue_ = newValue; + } + else if (newValue instanceof SubscribableAbstract) { this.wrappedValue_ = newValue; this.wrappedValue_.addOwningProperty(this); @@ -3716,84 +3741,10 @@ class ObservedPropertyObjectPU extends ObservedPropertyObjectAbstractPU { } } } -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * ObservedPropertySimplePU - * implementation of @State and @Provide decorated variables of types (T=) boolean | number | string | enum - * - * Holds an actual property value of type T - * uses its base class to manage subscribers to this - * property. - * - * all definitions in this file are framework internal -*/ -class ObservedPropertySimplePU extends ObservedPropertySimpleAbstractPU { - constructor(localInitValue, owningView, propertyName) { - super(owningView, propertyName); - // TODO undefined and null support remove this if statement - if (typeof localInitValue === "object") { - throw new SyntaxError("ObservedPropertySimple constructor: @State/@Provide value must not be an object"); - } - this.setValueInternal(localInitValue); - } - aboutToBeDeleted(unsubscribeMe) { - this.removeSubscriber(unsubscribeMe); - super.aboutToBeDeleted(); - } - /** - * Called by a @Link - SynchedPropertySimpleTwoWay that uses this as sync peer when it has changed - * @param eventSource - */ - syncPeerHasChanged(eventSource) { - - this.notifyPropertyHasChangedPU(); - } - /* - actually update this.wrappedValue_ - called needs to do value change check - and also notify with this.aboutToChange(); - */ - setValueInternal(newValue) { - - if (this.wrappedValue_ != newValue) { - this.wrappedValue_ = newValue; - return true; - } - return false; - } - getUnmonitored() { - - // unmonitored get access , no call to notifyPropertyRead ! - return this.wrappedValue_; - } - get() { - - this.notifyPropertyHasBeenReadPU(); - return this.wrappedValue_; - } - set(newValue) { - if (this.wrappedValue_ == newValue) { - - return; - } - - if (this.setValueInternal(newValue)) { - this.notifyPropertyHasChangedPU(); - } - } +// class definitions for backward compatibility +class ObservedPropertyObjectPU extends ObservedPropertyPU { +} +class ObservedPropertySimplePU extends ObservedPropertyPU { } /* * Copyright (c) 2022 Huawei Device Co., Ltd. @@ -3840,22 +3791,22 @@ class ObservedPropertySimplePU extends ObservedPropertySimpleAbstractPU { * * 1- assignment of a new Object value: this.aProp = new ClassA() * rhs can be ObservedObject because of @Observed decoration or now - * notifyPropertryHasChangedPU + * notifyPropertyHasChangedPU * * 2- local ObservedObject member property change * objectPropertyHasChangedPU called, eventSource is the ObservedObject stored in localCopyObservedObject_ - * no need to copy, notifyPropertryHasChangedPU + * no need to copy, notifyPropertyHasChangedPU * * 3- Rerender of the custom component triggered from the parent * reset() is called (code generated by the transpiler), set the value of source_ , if that causes a change will call syncPeerHasChanged * syncPeerHasChanged need to deep copy the ObservedObject from source to localCopyObservedObject_ - * notifyPropertryHasChangedPU + * notifyPropertyHasChangedPU * * 4- source_ ObservedObject member property change * objectPropertyHasChangedPU called, eventSource is the ObservedObject stored source_.getUnmonitored - * notifyPropertryHasChangedPU + * notifyPropertyHasChangedPU */ -class SynchedPropertyObjectOneWayPU extends ObservedPropertyObjectAbstractPU { +class SynchedPropertyOneWayPU extends ObservedPropertyAbstractPU { constructor(source, owningChildView, thisPropertyName) { super(owningChildView, thisPropertyName); if (source && (typeof (source) === "object") && ("subscribeMe" in source)) { @@ -3866,16 +3817,19 @@ class SynchedPropertyObjectOneWayPU extends ObservedPropertyObjectAbstractPU { this.source_.addSubscriber(this); } else { - // code path for - // 1- source is of same type C in parent, source is its value, not the backing store ObservedPropertyObject - // 2- nested Object/Array inside observed another object/array in parent, source is its value - if (!((source instanceof SubscribableAbstract) || ObservedObject.IsObservedObject(source))) { - stateMgmtConsole.warn(`@Prop ${this.info()} Provided source object's class - lacks @Observed class decorator. Object property changes will not be observed.`); + const sourceValue = source; + if (this.checkIsSupportedValue(sourceValue)) { + // code path for + // 1- source is of same type C in parent, source is its value, not the backing store ObservedPropertyObject + // 2- nested Object/Array inside observed another object/array in parent, source is its value + if (!((sourceValue instanceof SubscribableAbstract) || ObservedObject.IsObservedObject(sourceValue))) { + stateMgmtConsole.warn(`@Prop ${this.info()} Provided source object's class is not instance of SubscribableAbstract, + it also lacks @Observed class decorator. Object property changes will not be observed.`); + } + + this.source_ = new ObservedPropertyObjectPU(sourceValue, this, this.getSourceObservedPropertyFakeName()); + this.sourceIsOwnObject = true; } - - this.source_ = new ObservedPropertyObjectPU(source, this, this.getSourceObservedPropertyFakeName()); - this.sourceIsOwnObject = true; } if (this.source_ != undefined) { this.resetLocalValue(this.source_.get(), /* needCopyObject */ true); @@ -3901,11 +3855,16 @@ class SynchedPropertyObjectOneWayPU extends ObservedPropertyObjectAbstractPU { return `${this.info()}_source`; } syncPeerHasChanged(eventSource) { + if (this.source_ == undefined) { + stateMgmtConsole.error(`SynchedPropertyObjectOneWayPU[${this.id__()}, '${this.info() || "unknown"}']: \ + @Prop syncPeerHasChanged peer '${eventSource ? eventSource.info() : "no eventSource info"}' but source_ undefned. Internal error.`); + return; + } if (eventSource && this.source_ == eventSource) { // defensive programming: should always be the case! const newValue = this.source_.getUnmonitored(); - if (typeof newValue == "object") { + if (this.checkIsSupportedValue(newValue)) { if (this.resetLocalValue(newValue, /* needCopyObject */ true)) { this.notifyPropertyHasChangedPU(); @@ -3913,7 +3872,7 @@ class SynchedPropertyObjectOneWayPU extends ObservedPropertyObjectAbstractPU { } } else { - stateMgmtConsole.warn(`SynchedPropertyObjectOneWayPU[${this.id__()}]: syncPeerHasChanged Unexpected situation. Ignoring event.`); + stateMgmtConsole.warn(`SynchedPropertyObjectOneWayPU[${this.id__()}]: syncPeerHasChanged Unexpected situation. syncPeerHasChanged from different sender than source_. Ignoring event.`); } } /** @@ -3947,10 +3906,6 @@ class SynchedPropertyObjectOneWayPU extends ObservedPropertyObjectAbstractPU { return; } - if (!ObservedObject.IsObservedObject(newValue)) { - stateMgmtConsole.warn(`@Prop ${this.info()} Set: Provided new object's class - lacks '@Observed' class decorator. Object property changes will not be observed.`); - } if (this.resetLocalValue(newValue, /* needCopyObject */ false)) { this.notifyPropertyHasChangedPU(); } @@ -3958,13 +3913,10 @@ class SynchedPropertyObjectOneWayPU extends ObservedPropertyObjectAbstractPU { // called when updated from parent reset(sourceChangedValue) { - if (this.source_ !== undefined) { + if (this.source_ !== undefined && this.checkIsSupportedValue(sourceChangedValue)) { // if this.source_.set causes an actual change, then, ObservedPropertyObject source_ will call syncPeerHasChanged method this.source_.set(sourceChangedValue); } - else { - stateMgmtConsole.error(`SynchedPropertyObjectOneWayPU[${this.id__()}, '${this.info() || "unknown"}']: reset @Prop --- No source_. Internal error!`); - } } /* unsubscribe from previous wrapped ObjectObject @@ -3976,9 +3928,8 @@ class SynchedPropertyObjectOneWayPU extends ObservedPropertyObjectAbstractPU { resetLocalValue(newObservedObjectValue, needCopyObject) { // note: We can not test for newObservedObjectValue == this.localCopyObservedObject_ // here because the object might still be the same, but some property of it has changed - if (typeof newObservedObjectValue !== "object") { - // if not undefined or null, then the provided newObservedObjectValue must be an Object - stateMgmtConsole.error(`SynchedPropertyOneWayObjectPU[${this.id__()}]: setLocalValue new value must be an Object.`); + if (!this.checkIsSupportedValue(newObservedObjectValue)) { + return; } // unsubscribe from old local copy if (this.localCopyObservedObject_ instanceof SubscribableAbstract) { @@ -3990,24 +3941,24 @@ class SynchedPropertyObjectOneWayPU extends ObservedPropertyObjectAbstractPU { // shallow/deep copy value // needed whenever newObservedObjectValue comes from source // not needed on a local set (aka when called from set() method) - let copy = needCopyObject ? this.copyObject(newObservedObjectValue, this.info_) : newObservedObjectValue; - if (copy instanceof SubscribableAbstract) { - this.localCopyObservedObject_ = copy; - // deep copy will copy Set of subscribers as well. But local copy only has its own subscribers - // not those of its parent value. - this.localCopyObservedObject_.clearOwningProperties(); - this.localCopyObservedObject_.addOwningProperty(this); - } - else if (ObservedObject.IsObservedObject(copy)) { - // case: new ObservedObject - this.localCopyObservedObject_ = copy; - ObservedObject.addOwningProperty(this.localCopyObservedObject_, this); - } - else { - // wrap newObservedObjectValue raw object as ObservedObject and subscribe to it - stateMgmtConsole.warn(`@Prop ${this.info()} Provided source object's class \ + this.localCopyObservedObject_ = needCopyObject ? this.copyObject(newObservedObjectValue, this.info_) : newObservedObjectValue; + if (typeof this.localCopyObservedObject_ == "object") { + if (this.localCopyObservedObject_ instanceof SubscribableAbstract) { + // deep copy will copy Set of subscribers as well. But local copy only has its own subscribers + // not those of its parent value. + this.localCopyObservedObject_.clearOwningProperties(); + this.localCopyObservedObject_.addOwningProperty(this); + } + else if (ObservedObject.IsObservedObject(this.localCopyObservedObject_)) { + // case: new ObservedObject + ObservedObject.addOwningProperty(this.localCopyObservedObject_, this); + } + else { + // wrap newObservedObjectValue raw object as ObservedObject and subscribe to it + stateMgmtConsole.error(`@Prop ${this.info()} Provided source object's class \ lacks @Observed class decorator. Object property changes will not be observed.`); - this.localCopyObservedObject_ = ObservedObject.createNew(copy, this); + this.localCopyObservedObject_ = ObservedObject.createNew(this.localCopyObservedObject_, this); + } } return true; } @@ -4025,11 +3976,11 @@ class SynchedPropertyObjectOneWayPU extends ObservedPropertyObjectAbstractPU { shallowCopyObject(value, propName) { let rawValue = ObservedObject.GetRawObject(value); let copy; - if (rawValue == undefined || rawValue == null) { + if (!rawValue || typeof rawValue !== 'object') { copy = rawValue; } else if (typeof rawValue != "object") { - // TODO would it be better to crash the app here? + // FIXME would it be better to throw Exception here? stateMgmtConsole.error(`@Prop ${this.info()} shallowCopyObject: request to copy non-object but defined value of type '${typeof rawValue}'. Internal error! Setting copy=original value.`); copy = rawValue; } @@ -4137,6 +4088,11 @@ class SynchedPropertyObjectOneWayPU extends ObservedPropertyObjectAbstractPU { } } } +// class definitions for backward compatibility +class SynchedPropertySimpleOneWayPU extends SynchedPropertyOneWayPU { +} +class SynchedPropertyObjectOneWayPU extends SynchedPropertyOneWayPU { +} /* * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); @@ -4156,8 +4112,8 @@ class SynchedPropertyObjectOneWayPU extends ObservedPropertyObjectAbstractPU { * implementation of @Link and @Consume decorated variables of type class object * * all definitions in this file are framework internal - */ -class SynchedPropertyObjectTwoWayPU extends ObservedPropertyObjectAbstractPU { +*/ +class SynchedPropertyTwoWayPU extends ObservedPropertyAbstractPU { constructor(source, owningChildView, thisPropertyName) { super(owningChildView, thisPropertyName); this.changeNotificationIsOngoing_ = false; @@ -4169,7 +4125,7 @@ class SynchedPropertyObjectTwoWayPU extends ObservedPropertyObjectAbstractPU { ObservedObject.addOwningProperty(this.source_.get(), this); } else { - stateMgmtConsole.error(`SynchedPropertyObjectTwoWayPU[${this.id__()}, '${this.info() || "unknown"}']: constructor @Link/@Consume source must not be undefined. Application error!`); + throw new SyntaxError(`SynchedPropertyObjectTwoWayPU[${this.id__()}, '${this.info() || "unknown"}']: constructor @Link/@Consume source variable in parent/ancestor @ Component must be defined. Application error!`); } } /* @@ -4190,20 +4146,23 @@ class SynchedPropertyObjectTwoWayPU extends ObservedPropertyObjectAbstractPU { } setObject(newValue) { if (!this.source_) { - stateMgmtConsole.warn(`SynchedPropertyObjectTwoWayPU[${this.id__()}, '${this.info() || "unknown"}']: setObject (assign a new value), @Link/@Consume: no linked parent property. Likely a consequence of earlier application error.`); + throw new SyntaxError(`SynchedPropertyObjectTwoWayPU[${this.id__()}, '${this.info() || "unknown"}']: setObject (assign a new value), \ + @Link/@Consume: no source variable in parent/ancestor @Component. Application error.`); + } + if (this.getUnmonitored() == newValue) { + return; } - let oldValueObject = this.getUnmonitored(); - if (oldValueObject != undefined && oldValueObject != null) { - ObservedObject.removeOwningProperty(oldValueObject, this); + + if (this.checkIsSupportedValue(newValue)) { + // the source_ ObservedProperty will call: this.syncPeerHasChanged(newValue); + this.source_.set(newValue); } - this.source_.set(newValue); - ObservedObject.addOwningProperty(this.getUnmonitored(), this); } /** - * Called when sync peer ObservedPropertyObject or SynchedPropertyObjectTwoWay has chnaged value + * Called when sync peer ObservedPropertyObject or SynchedPropertyObjectTwoWay has changed value * that peer can be in either parent or child component if 'this' is used for a @Link - * that peer can be in either acestor or descendant component if 'this' is used for a @Consume + * that peer can be in either ancestor or descendant component if 'this' is used for a @Consume * @param eventSource */ syncPeerHasChanged(eventSource) { @@ -4217,11 +4176,11 @@ class SynchedPropertyObjectTwoWayPU extends ObservedPropertyObjectAbstractPU { * @param souceObject * @param changedPropertyName */ - objectPropertyHasChangedPU(souceObject, changedPropertyName) { + objectPropertyHasChangedPU(sourceObject, changedPropertyName) { this.notifyPropertyHasChangedPU(); } - objectPropertyHasBeenReadPU(souceObject, changedPropertyName) { + objectPropertyHasBeenReadPU(sourceObject, changedPropertyName) { this.notifyPropertyHasBeenReadPU(); } @@ -4250,185 +4209,10 @@ class SynchedPropertyObjectTwoWayPU extends ObservedPropertyObjectAbstractPU { this.changeNotificationIsOngoing_ = false; } } -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * SynchedPropertySimpleOneWayPU - * implementation of @Prop decorated variable of types boolean | number | string | enum - * - * all definitions in this file are framework internal - */ -class SynchedPropertySimpleOneWayPU extends ObservedPropertySimpleAbstractPU { - constructor(source, subscribeMe, thisPropertyName) { - super(subscribeMe, thisPropertyName); - // Check that source is ObservedPropertyAbstruct - if (source && (typeof (source) === "object") && ("notifyHasChanged" in source) && ("subscribeMe" in source)) { - // code path for @(Local)StorageProp - this.source_ = source; - this.sourceIsOwnObject = false; - this.source_.addSubscriber(this); - // subscribe to receive value change updates from LocalStorage source property - } - else { - // code path for @Prop - this.source_ = new ObservedPropertySimplePU(source, this, thisPropertyName); - this.sourceIsOwnObject = true; - } - // use own backing store for value to avoid - // value changes to be propagated back to source - this.wrappedValue_ = this.source_.getUnmonitored(); - } - /* - like a destructor, need to call this before deleting - the property. - */ - aboutToBeDeleted() { - if (this.source_) { - this.source_.removeSubscriber(this); - if (this.sourceIsOwnObject == true && this.source_.numberOfSubscrbers() == 0) { - - this.source_.aboutToBeDeleted(); - } - this.source_ = undefined; - this.sourceIsOwnObject = false; - } - super.aboutToBeDeleted(); - } - syncPeerHasChanged(eventSource) { - if (eventSource && (eventSource == this.source_)) { - // defensive, should always be the case - - this.setWrappedValue(eventSource.getUnmonitored()); - this.notifyPropertyHasChangedPU(); - } - } - getUnmonitored() { - - // unmonitored get access, no call to notifyPropertyRead ! - return this.wrappedValue_; - } - // get 'read through` from the ObservedProperty - get() { - - this.notifyPropertyHasBeenReadPU(); - return this.wrappedValue_; - } - set(newValue) { - if (this.wrappedValue_ == newValue) { - - return; - } - - this.setWrappedValue(newValue); - this.notifyPropertyHasChangedPU(); - } - reset(sourceChangedValue) { - - // if set causes an actual change, then, ObservedPropertySimple source_ will call hasChanged - if (this.source_ !== undefined) { - // if set causes an actual change, then, ObservedPropertySimple source_ will call hasChanged - this.source_.set(sourceChangedValue); - } - } - setWrappedValue(newValue) { - this.wrappedValue_ = newValue; - } +// class definitions for backward compatibility +class SynchedPropertyObjectTwoWayPU extends SynchedPropertyTwoWayPU { } -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * SynchedPropertySimpleTwoWayPU - * implementation of @Link and @Consume decorated variables of types boolean | number | string | enum - * - * all definitions in this file are framework internal - */ -class SynchedPropertySimpleTwoWayPU extends ObservedPropertySimpleAbstractPU { - constructor(source, owningView, owningViewPropNme) { - super(owningView, owningViewPropNme); - this.changeNotificationIsOngoing_ = false; - this.source_ = source; - if (this.source_) { - this.source_.addSubscriber(this); - } - else { - stateMgmtConsole.error(`SynchedPropertySimpleTwoWayPU[${this.id__()}, '${this.info() || "unknown"}']: constructor @Link/@Consume source must not be undefined. Application error!`); - } - } - /* - like a destructor, need to call this before deleting - the property. - */ - aboutToBeDeleted() { - if (this.source_) { - this.source_.removeSubscriber(this); - this.source_ = undefined; - } - super.aboutToBeDeleted(); - } - /** - * Called when sync peer ObservedPropertySimple or SynchedPropertySimpletTwoWay has chnaged value - * that peer can be in either parent or child component if 'this' is used for a @Link - * that peer can be in either acestor or descendant component if 'this' is used for a @Consume - * @param eventSource - */ - syncPeerHasChanged(eventSource) { - if (!this.changeNotificationIsOngoing_) { - - this.notifyPropertyHasChangedPU(); - } - } - getUnmonitored() { - - return (this.source_ ? this.source_.getUnmonitored() : undefined); - } - // get 'read through` from the ObservedProperty - get() { - - this.notifyPropertyHasBeenReadPU(); - return this.getUnmonitored(); - } - // set 'writes through` to the ObservedProperty - set(newValue) { - if (!this.source_) { - - return; - } - if (this.source_.get() == newValue) { - - return; - } - - // avoid circular notifications @Link -> source @State -> other but also to same @Link - this.changeNotificationIsOngoing_ = true; - // the source_ ObservedProeprty will call: this.hasChanged(newValue); - this.source_.set(newValue); - this.notifyPropertyHasChangedPU(); - this.changeNotificationIsOngoing_ = false; - } +class SynchedPropertySimpleTwoWayPU extends SynchedPropertyTwoWayPU { } /* * Copyright (c) 2022 Huawei Device Co., Ltd. @@ -4451,7 +4235,7 @@ class SynchedPropertySimpleTwoWayPU extends ObservedPropertySimpleAbstractPU { * all definitions in this file are framework internal * */ -class SynchedPropertyNestedObjectPU extends ObservedPropertyObjectAbstractPU { +class SynchedPropertyNestedObjectPU extends ObservedPropertyAbstractPU { /** * Construct a Property of a su component that links to a variable of parent view that holds an ObservedObject * example @@ -4501,11 +4285,15 @@ class SynchedPropertyNestedObjectPU extends ObservedPropertyObjectAbstractPU { return; } - this.setValueInternal(newValue); - // notify value change to subscribing View - this.notifyPropertyHasChangedPU(); + if (this.setValueInternal(newValue)) { + // notify value change to subscribing View + this.notifyPropertyHasChangedPU(); + } } setValueInternal(newValue) { + if (!this.checkIsObject(newValue)) { + return false; + } if (this.obsObject_ != undefined) { if (this.obsObject_ instanceof SubscribableAbstract) { // unregister from SubscribableAbstract object @@ -4531,6 +4319,7 @@ class SynchedPropertyNestedObjectPU extends ObservedPropertyObjectAbstractPU { value changes will bot be observed and UI will not update. forgot @Observed class decorator? Application error.`); } } + return true; } } /** backward compatibility after typo in classname fix */ @@ -4938,26 +4727,31 @@ class ViewPU extends NativeViewPartialUpdate { /** * Method for the sub-class to call from its constructor for resolving * a @Consume variable and initializing its backing store - * with the yncedPropertyTwoWay object created from the + * with the SyncedPropertyTwoWay object created from the * @Provide variable's backing store. * @param providedPropName the name of the @Provide'd variable. - * This is either the @Consume decortor parameter, or variable name. + * This is either the @Consume decorator parameter, or variable name. * @param consumeVarName the @Consume variable name (not the - * @Consume decortor parameter) - * @returns initiaizing value of the @Consume backing store + * @Consume decorator parameter) + * @returns initializing value of the @Consume backing store */ initializeConsume(providedPropName, consumeVarName) { let providedVarStore = this.providedVars_.get(providedPropName); if (providedVarStore === undefined) { throw new ReferenceError(`${this.constructor.name}: missing @Provide property with name ${providedPropName}. - Fail to resolve @Consume(${providedPropName}).`); + Fail to resolve @Consume(${providedPropName}).`); } - return providedVarStore.createSync((source) => (source instanceof ObservedPropertySimple) - ? new SynchedPropertySimpleTwoWayPU(source, this, consumeVarName) - : new SynchedPropertyObjectTwoWayPU(source, this, consumeVarName)); + const factory = (source) => { + const result = ((source instanceof ObservedPropertySimple) || (source instanceof ObservedPropertySimplePU)) + ? new SynchedPropertyObjectTwoWayPU(source, this, consumeVarName) + : new SynchedPropertyObjectTwoWayPU(source, this, consumeVarName); + stateMgmtConsole.error(`The @Consume is instance of ${result.constructor.name}`); + return result; + }; + return providedVarStore.createSync(factory); } /** - * given the elmtid of a child or child of child within this custom component + * given the elmtId of a child or child of child within this custom component * remember this component needs a partial update * @param elmtId */ @@ -5186,7 +4980,7 @@ class ViewPU extends NativeViewPartialUpdate { const appStorageLink = AppStorage.__createSync(storagePropName, defaultValue, (source) => (source === undefined) ? undefined : (source instanceof ObservedPropertySimple) - ? new SynchedPropertySimpleTwoWayPU(source, this, viewVariableName) + ? new SynchedPropertyObjectTwoWayPU(source, this, viewVariableName) : new SynchedPropertyObjectTwoWayPU(source, this, viewVariableName)); this.ownStorageLinksProps_.add(appStorageLink); return appStorageLink; @@ -5195,7 +4989,7 @@ class ViewPU extends NativeViewPartialUpdate { const appStorageProp = AppStorage.__createSync(storagePropName, defaultValue, (source) => (source === undefined) ? undefined : (source instanceof ObservedPropertySimple) - ? new SynchedPropertySimpleOneWayPU(source, this, viewVariableName) + ? new SynchedPropertyObjectOneWayPU(source, this, viewVariableName) : new SynchedPropertyObjectOneWayPU(source, this, viewVariableName)); this.ownStorageLinksProps_.add(appStorageProp); return appStorageProp; @@ -5204,7 +4998,7 @@ class ViewPU extends NativeViewPartialUpdate { const localStorageLink = this.localStorage_.__createSync(storagePropName, defaultValue, (source) => (source === undefined) ? undefined : (source instanceof ObservedPropertySimple) - ? new SynchedPropertySimpleTwoWayPU(source, this, viewVariableName) + ? new SynchedPropertyObjectTwoWayPU(source, this, viewVariableName) : new SynchedPropertyObjectTwoWayPU(source, this, viewVariableName)); this.ownStorageLinksProps_.add(localStorageLink); return localStorageLink; @@ -5213,7 +5007,7 @@ class ViewPU extends NativeViewPartialUpdate { const localStorageProp = this.localStorage_.__createSync(storagePropName, defaultValue, (source) => (source === undefined) ? undefined : (source instanceof ObservedPropertySimple) - ? new SynchedPropertySimpleOneWayPU(source, this, viewVariableName) + ? new SynchedPropertyObjectOneWayPU(source, this, viewVariableName) : new SynchedPropertyObjectOneWayPU(source, this, viewVariableName)); this.ownStorageLinksProps_.add(localStorageProp); return localStorageProp; diff --git a/frameworks/bridge/declarative_frontend/jsview/dialog/js_custom_dialog_controller.cpp b/frameworks/bridge/declarative_frontend/jsview/dialog/js_custom_dialog_controller.cpp index d9338be9af1..9a6700e9c57 100644 --- a/frameworks/bridge/declarative_frontend/jsview/dialog/js_custom_dialog_controller.cpp +++ b/frameworks/bridge/declarative_frontend/jsview/dialog/js_custom_dialog_controller.cpp @@ -68,14 +68,14 @@ void JSCustomDialogController::ConstructorCallback(const JSCallbackInfo& info) // check if owner object is set JSView* ownerView = ownerObj->Unwrap(); + auto instance = new JSCustomDialogController(ownerView); if (ownerView == nullptr) { + info.SetReturnValue(instance); + instance = nullptr; LOGE("JSCustomDialogController creation with invalid arguments. Missing \'ownerView\'"); return; } - auto instance = new JSCustomDialogController(ownerView); - instance->ownerView_ = ownerView; - // Process builder function. JSRef builderCallback = constructorArg->GetProperty("builder"); if (!builderCallback->IsUndefined() && builderCallback->IsFunction()) { @@ -176,10 +176,6 @@ void JSCustomDialogController::ConstructorCallback(const JSCallbackInfo& info) instance->dialogProperties_.isShowInSubWindow = showInSubWindowValue->ToBoolean(); #endif } - auto container = Container::Current(); - if (container && container->IsScenceBoardWindow()) { - instance->dialogProperties_.isShowInSubWindow = false; - } info.SetReturnValue(instance); } else { @@ -203,6 +199,10 @@ void JSCustomDialogController::JsOpenDialog(const JSCallbackInfo& info) return; } + if (this->ownerView_ == nullptr) { + LOGE("JSCustomDialogController(JsOpenDialog) Missing \'ownerView\'"); + return; + } auto containerId = this->ownerView_->GetInstanceId(); ContainerScope containerScope(containerId); @@ -251,6 +251,10 @@ void JSCustomDialogController::JsCloseDialog(const JSCallbackInfo& info) { LOGI("JSCustomDialogController(JsCloseDialog)"); + if (this->ownerView_ == nullptr) { + LOGE("JSCustomDialogController(JsCloseDialog) Missing \'ownerView\'"); + return; + } auto containerId = this->ownerView_->GetInstanceId(); ContainerScope containerScope(containerId); diff --git a/frameworks/bridge/declarative_frontend/jsview/js_datepicker.cpp b/frameworks/bridge/declarative_frontend/jsview/js_datepicker.cpp index a984989a5b5..2ece163ef78 100644 --- a/frameworks/bridge/declarative_frontend/jsview/js_datepicker.cpp +++ b/frameworks/bridge/declarative_frontend/jsview/js_datepicker.cpp @@ -147,6 +147,41 @@ JSRef DatePickerChangeEventToJSValue(const DatePickerChangeEvent& eventIn } return JSRef::Cast(obj); } + +JSRef DatePickerDateChangeEventToJSValue(const DatePickerChangeEvent& eventInfo) +{ + JSRef obj = JSRef::New(); + std::unique_ptr argsPtr = JsonUtil::ParseJsonString(eventInfo.GetSelectedStr()); + if (!argsPtr) { + LOGW("selectedStr is not exist."); + return JSRef::Cast(obj); + } + std::tm dateTime = { 0 }; + auto year = argsPtr->GetValue("year"); + if (year && year->IsNumber()) { + dateTime.tm_year = year->GetInt() - 1900; // local date start from 1900 + } + auto month = argsPtr->GetValue("month"); + if (month && month->IsNumber()) { + dateTime.tm_mon = month->GetInt(); + } + auto day = argsPtr->GetValue("day"); + if (day && day->IsNumber()) { + dateTime.tm_mday = day->GetInt(); + } + auto hour = argsPtr->GetValue("hour"); + if (hour && hour->IsNumber()) { + dateTime.tm_hour = hour->GetInt(); + } + auto minute = argsPtr->GetValue("minute"); + if (minute && minute->IsNumber()) { + dateTime.tm_min = minute->GetInt(); + } + + auto milliseconds = Date::GetMilliSecondsByDateTime(dateTime); + auto dateObj = JSDate::New(milliseconds); + return JSRef::Cast(dateObj); +} } // namespace void JSDatePicker::JSBind(BindingTarget globalObj) @@ -156,6 +191,7 @@ void JSDatePicker::JSBind(BindingTarget globalObj) JSClass::StaticMethod("create", &JSDatePicker::Create, opt); JSClass::StaticMethod("lunar", &JSDatePicker::SetLunar); JSClass::StaticMethod("onChange", &JSDatePicker::OnChange); + JSClass::StaticMethod("onDateChange", &JSDatePicker::OnDateChange); JSClass::StaticMethod("backgroundColor", &JSDatePicker::PickerBackgroundColor); // keep compatible, need remove after JSClass::StaticMethod("useMilitaryTime", &JSDatePicker::UseMilitaryTime); @@ -233,19 +269,21 @@ void JSDatePicker::ParseTextProperties(const JSRef& paramObj, NG::Pick void JSDatePicker::ParseTextStyle(const JSRef& paramObj, NG::PickerTextStyle& textStyle) { auto fontColor = paramObj->GetProperty("color"); - auto fontStyle = paramObj->GetProperty("font"); + auto fontOptions = paramObj->GetProperty("font"); Color textColor; if (JSViewAbstract::ParseJsColor(fontColor, textColor)) { textStyle.textColor = textColor; } - if (!fontStyle->IsObject()) { + if (!fontOptions->IsObject()) { return; } - JSRef fontObj = JSRef::Cast(fontStyle); + JSRef fontObj = JSRef::Cast(fontOptions); auto fontSize = fontObj->GetProperty("size"); auto fontWeight = fontObj->GetProperty("weight"); + auto fontFamily = fontObj->GetProperty("family"); + auto fontStyle = fontObj->GetProperty("style"); if (fontSize->IsNull() || fontSize->IsUndefined()) { textStyle.fontSize = Dimension(-1); } else { @@ -267,6 +305,22 @@ void JSDatePicker::ParseTextStyle(const JSRef& paramObj, NG::PickerTex } textStyle.fontWeight = ConvertStrToFontWeight(weight); } + + if (!fontFamily->IsNull() && !fontFamily->IsUndefined()) { + std::vector families; + if (ParseJsFontFamilies(fontFamily, families)) { + textStyle.fontFamily = families; + } + } + + if (fontStyle->IsNumber()) { + auto style = fontStyle->ToNumber(); + if (style < 0 || style > 1) { + LOGE("Text fontStyle(%d) is invalid value", style); + return; + } + textStyle.fontStyle = static_cast(style); + } } void JSDatePicker::SetDisappearTextStyle(const JSCallbackInfo& info) @@ -335,6 +389,23 @@ void JSDatePicker::OnChange(const JSCallbackInfo& info) DatePickerModel::GetInstance()->SetOnChange(std::move(onChange)); } +void JSDatePicker::OnDateChange(const JSCallbackInfo& info) +{ + if (info.Length() < 1 || !info[0]->IsFunction()) { + LOGI("info not function"); + return; + } + auto jsFunc = AceType::MakeRefPtr>( + JSRef::Cast(info[0]), DatePickerDateChangeEventToJSValue); + auto onDateChange = [execCtx = info.GetExecutionContext(), func = std::move(jsFunc)](const BaseEventInfo* info) { + JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx); + ACE_SCORING_EVENT("datePicker.onDateChange"); + const auto* eventInfo = TypeInfoHelper::DynamicCast(info); + func->Execute(*eventInfo); + }; + DatePickerModel::GetInstance()->SetOnDateChange(std::move(onDateChange)); +} + void JSTimePicker::OnChange(const JSCallbackInfo& info) { if (info.Length() < 1 || !info[0]->IsFunction()) { @@ -602,6 +673,8 @@ void JSDatePickerDialog::Show(const JSCallbackInfo& info) std::function cancelEvent; std::function acceptEvent; std::function changeEvent; + std::function dateChangeEvent; + std::function dateAcceptEvent; auto onChange = paramObject->GetProperty("onChange"); if (!onChange->IsUndefined() && onChange->IsFunction()) { auto jsFunc = AceType::MakeRefPtr(JSRef(), JSRef::Cast(onChange)); @@ -633,6 +706,82 @@ void JSDatePickerDialog::Show(const JSCallbackInfo& info) func->Execute(); }; } + auto onDateChange = paramObject->GetProperty("onDateChange"); + if (!onDateChange->IsUndefined() && onDateChange->IsFunction()) { + auto jsFunc = AceType::MakeRefPtr(JSRef(), JSRef::Cast(onDateChange)); + dateChangeEvent = [execCtx = info.GetExecutionContext(), type = pickerType, func = std::move(jsFunc)]( + const std::string& info) { + JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx); + ACE_SCORING_EVENT("DatePickerDialog.onDateChange"); + auto selectedJson = JsonUtil::ParseJsonString(info); + if (!selectedJson || selectedJson->IsNull()) { + return; + } + std::tm dateTime = { 0 }; + auto year = selectedJson->GetValue("year"); + if (year && year->IsNumber()) { + dateTime.tm_year = year->GetInt() - 1900; // local date start from 1900 + } + auto month = selectedJson->GetValue("month"); + if (month && month->IsNumber()) { + dateTime.tm_mon = month->GetInt(); + } + auto day = selectedJson->GetValue("day"); + if (day && day->IsNumber()) { + dateTime.tm_mday = day->GetInt(); + } + auto hour = selectedJson->GetValue("hour"); + if (hour && hour->IsNumber()) { + dateTime.tm_hour = hour->GetInt(); + } + auto minute = selectedJson->GetValue("minute"); + if (minute && minute->IsNumber()) { + dateTime.tm_min = minute->GetInt(); + } + + auto milliseconds = Date::GetMilliSecondsByDateTime(dateTime); + auto dateObj = JSDate::New(milliseconds); + func->ExecuteJS(1, &dateObj); + }; + } + auto onDateAccept = paramObject->GetProperty("onDateAccept"); + if (!onDateAccept->IsUndefined() && onDateAccept->IsFunction()) { + auto jsFunc = AceType::MakeRefPtr(JSRef(), JSRef::Cast(onDateAccept)); + dateAcceptEvent = [execCtx = info.GetExecutionContext(), type = pickerType, func = std::move(jsFunc)]( + const std::string& info) { + JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx); + ACE_SCORING_EVENT("DatePickerDialog.onDateAccept"); + auto selectedJson = JsonUtil::ParseJsonString(info); + if (!selectedJson || selectedJson->IsNull()) { + return; + } + std::tm dateTime = { 0 }; + auto year = selectedJson->GetValue("year"); + if (year && year->IsNumber()) { + dateTime.tm_year = year->GetInt() - 1900; // local date start from 1900 + } + auto month = selectedJson->GetValue("month"); + if (month && month->IsNumber()) { + dateTime.tm_mon = month->GetInt(); + } + auto day = selectedJson->GetValue("day"); + if (day && day->IsNumber()) { + dateTime.tm_mday = day->GetInt(); + } + auto hour = selectedJson->GetValue("hour"); + if (hour && hour->IsNumber()) { + dateTime.tm_hour = hour->GetInt(); + } + auto minute = selectedJson->GetValue("minute"); + if (minute && minute->IsNumber()) { + dateTime.tm_min = minute->GetInt(); + } + + auto milliseconds = Date::GetMilliSecondsByDateTime(dateTime); + auto dateObj = JSDate::New(milliseconds); + func->ExecuteJS(1, &dateObj); + }; + } NG::DatePickerSettingData settingData; PickerDialogInfo pickerDialog; auto startDate = paramObject->GetProperty("start"); @@ -661,7 +810,8 @@ void JSDatePickerDialog::Show(const JSCallbackInfo& info) pickerDialog.pickerTime = ParseTime(selectedDate); JSDatePicker::ParseTextProperties(paramObject, settingData.properties); DatePickerDialogModel::GetInstance()->SetDatePickerDialogShow( - pickerDialog, settingData, std::move(cancelEvent), std::move(acceptEvent), std::move(changeEvent), pickerType); + pickerDialog, settingData, std::move(cancelEvent), std::move(acceptEvent), std::move(changeEvent), + std::move(dateAcceptEvent), std::move(dateChangeEvent), pickerType); } void JSDatePickerDialog::DatePickerDialogShow(const JSRef& paramObj, @@ -1070,11 +1220,14 @@ void JSTimePickerDialog::Show(const JSCallbackInfo& info) NG::TimePickerSettingData settingData; PickerDialogInfo pickerDialog; settingData.isUseMilitaryTime = useMilitaryTime->ToBoolean(); - pickerDialog.pickerTime = ParseTime(selectedTime); pickerDialog.isUseMilitaryTime = useMilitaryTime->ToBoolean(); if (selectedTime->IsObject()) { - settingData.dialogTitleDate = ParseDate(selectedTime); - pickerDialog.isSelectedTime = true; + PickerDate dialogTitleDate = ParseDate(selectedTime); + if (dialogTitleDate.GetYear() != 0) { + settingData.dialogTitleDate = dialogTitleDate; + pickerDialog.isSelectedTime = true; + pickerDialog.pickerTime = ParseTime(selectedTime); + } } JSDatePicker::ParseTextProperties(paramObject, settingData.properties); TimePickerDialogModel::GetInstance()->SetTimePickerDialogShow( diff --git a/frameworks/bridge/declarative_frontend/jsview/js_datepicker.h b/frameworks/bridge/declarative_frontend/jsview/js_datepicker.h index b731919326d..f8db3ca017c 100644 --- a/frameworks/bridge/declarative_frontend/jsview/js_datepicker.h +++ b/frameworks/bridge/declarative_frontend/jsview/js_datepicker.h @@ -31,6 +31,7 @@ public: static void JSBind(BindingTarget globalObj); static void SetLunar(bool isLunar); static void OnChange(const JSCallbackInfo& info); + static void OnDateChange(const JSCallbackInfo& info); static void PickerBackgroundColor(const JSCallbackInfo& info); static void SetDisappearTextStyle(const JSCallbackInfo& info); static void SetTextStyle(const JSCallbackInfo& info); diff --git a/frameworks/bridge/declarative_frontend/jsview/js_grid.cpp b/frameworks/bridge/declarative_frontend/jsview/js_grid.cpp index 69feeb114b5..cf1fbdfb2a3 100644 --- a/frameworks/bridge/declarative_frontend/jsview/js_grid.cpp +++ b/frameworks/bridge/declarative_frontend/jsview/js_grid.cpp @@ -270,7 +270,7 @@ void JSGrid::SetScrollBar(int32_t displayMode) void JSGrid::SetScrollBarColor(const std::string& color) { - if (!color.empty()) { + if (!color.empty() && color != "undefined") { GridModel::GetInstance()->SetScrollBarColor(color); return; } diff --git a/frameworks/bridge/declarative_frontend/jsview/js_list.cpp b/frameworks/bridge/declarative_frontend/jsview/js_list.cpp index a49ac723288..83f04d76bc4 100644 --- a/frameworks/bridge/declarative_frontend/jsview/js_list.cpp +++ b/frameworks/bridge/declarative_frontend/jsview/js_list.cpp @@ -194,8 +194,10 @@ void JSList::SetLanes(const JSCallbackInfo& info) if (info.Length() >= 2 && !(info[1]->IsNull())) { /* 2: parameter count */ CalcDimension laneGutter; - if (!JSViewAbstract::ParseJsDimensionVp(info[1], laneGutter)) { - ListModel::GetInstance()->SetLaneGutter(0.0_vp); + if (JSViewAbstract::ParseJsDimensionVp(info[1], laneGutter)) { + if (laneGutter.IsNegative()) { + laneGutter.Reset(); + } } ListModel::GetInstance()->SetLaneGutter(laneGutter); } diff --git a/frameworks/bridge/declarative_frontend/jsview/js_list_item.cpp b/frameworks/bridge/declarative_frontend/jsview/js_list_item.cpp index 5c36a6be93c..ef87b9f607c 100644 --- a/frameworks/bridge/declarative_frontend/jsview/js_list_item.cpp +++ b/frameworks/bridge/declarative_frontend/jsview/js_list_item.cpp @@ -184,40 +184,52 @@ void JSListItem::JsParseDeleteArea(const JSCallbackInfo& args, const JSRefIsBoolean()) { useDefaultDeleteAnimation = defaultDeleteAnimation->ToBoolean(); } - auto onDelete = deleteAreaObj->GetProperty("onDelete"); - std::function onDeleteCallback; - if (onDelete->IsFunction()) { - onDeleteCallback = [execCtx = args.GetExecutionContext(), func = JSRef::Cast(onDelete)]() { + auto onAction = deleteAreaObj->GetProperty("onAction"); + if (!onAction->IsFunction()) { + onAction = deleteAreaObj->GetProperty("onDelete"); + } + std::function onActionCallback; + if (onAction->IsFunction()) { + onActionCallback = [execCtx = args.GetExecutionContext(), func = JSRef::Cast(onAction)]() { func->Call(JSRef()); return; }; } - auto onEnterDeleteArea = deleteAreaObj->GetProperty("onEnterDeleteArea"); - std::function onEnterDeleteAreaCallback; - if (onEnterDeleteArea->IsFunction()) { - onEnterDeleteAreaCallback = [execCtx = args.GetExecutionContext(), - func = JSRef::Cast(onEnterDeleteArea)]() { + auto onEnterActionArea = deleteAreaObj->GetProperty("onEnterActionArea"); + if (!onEnterActionArea->IsFunction()) { + onEnterActionArea = deleteAreaObj->GetProperty("onEnterDeleteArea"); + } + std::function onEnterActionAreaCallback; + if (onEnterActionArea->IsFunction()) { + onEnterActionAreaCallback = [execCtx = args.GetExecutionContext(), + func = JSRef::Cast(onEnterActionArea)]() { func->Call(JSRef()); return; }; } - auto onExitDeleteArea = deleteAreaObj->GetProperty("onExitDeleteArea"); - std::function onExitDeleteAreaCallback; - if (onExitDeleteArea->IsFunction()) { - onExitDeleteAreaCallback = [execCtx = args.GetExecutionContext(), - func = JSRef::Cast(onExitDeleteArea)]() { + auto onExitActionArea = deleteAreaObj->GetProperty("onExitActionArea"); + if (!onExitActionArea->IsFunction()) { + onExitActionArea = deleteAreaObj->GetProperty("onExitDeleteArea"); + } + std::function onExitActionAreaCallback; + if (onExitActionArea->IsFunction()) { + onExitActionAreaCallback = [execCtx = args.GetExecutionContext(), + func = JSRef::Cast(onExitActionArea)]() { func->Call(JSRef()); return; }; } - auto deleteAreaDistance = deleteAreaObj->GetProperty("deleteAreaDistance"); + auto actionAreaDistance = deleteAreaObj->GetProperty("actionAreaDistance"); CalcDimension length; - if (!ParseJsDimensionVp(deleteAreaDistance, length)) { - length = listItemTheme->GetDeleteDistance(); + if (!ParseJsDimensionVp(actionAreaDistance, length)) { + actionAreaDistance = deleteAreaObj->GetProperty("deleteAreaDistance"); + if (!ParseJsDimensionVp(actionAreaDistance, length)) { + length = listItemTheme->GetDeleteDistance(); + } } ListItemModel::GetInstance()->SetDeleteArea(std::move(builderAction), useDefaultDeleteAnimation, - std::move(onDeleteCallback), std::move(onEnterDeleteAreaCallback), std::move(onExitDeleteAreaCallback), length, + std::move(onActionCallback), std::move(onEnterActionAreaCallback), std::move(onExitActionAreaCallback), length, isStartArea); } diff --git a/frameworks/bridge/declarative_frontend/jsview/js_loading_progress.cpp b/frameworks/bridge/declarative_frontend/jsview/js_loading_progress.cpp index 0d38584bfce..1bc6ed92aa7 100644 --- a/frameworks/bridge/declarative_frontend/jsview/js_loading_progress.cpp +++ b/frameworks/bridge/declarative_frontend/jsview/js_loading_progress.cpp @@ -107,9 +107,10 @@ void JSLoadingProgress::SetForegroundColor(const JSCallbackInfo& info) void JSLoadingProgress::SetEnableLoading(const JSCallbackInfo& info) { - if (!info[0]->IsBoolean()) { - return; + bool enable = true; + if (info[0]->IsBoolean()) { + enable = info[0]->ToBoolean(); } - LoadingProgressModel::GetInstance()->SetEnableLoading(info[0]->ToBoolean()); + LoadingProgressModel::GetInstance()->SetEnableLoading(enable); } }; // namespace OHOS::Ace::Framework diff --git a/frameworks/bridge/declarative_frontend/jsview/js_sec_location_button.cpp b/frameworks/bridge/declarative_frontend/jsview/js_location_button.cpp similarity index 51% rename from frameworks/bridge/declarative_frontend/jsview/js_sec_location_button.cpp rename to frameworks/bridge/declarative_frontend/jsview/js_location_button.cpp index cf2181b422d..189a722e3dc 100644 --- a/frameworks/bridge/declarative_frontend/jsview/js_sec_location_button.cpp +++ b/frameworks/bridge/declarative_frontend/jsview/js_location_button.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "frameworks/bridge/declarative_frontend/jsview/js_sec_location_button.h" +#include "frameworks/bridge/declarative_frontend/jsview/js_location_button.h" #include "bridge/common/utils/utils.h" #include "core/common/container.h" @@ -26,27 +26,8 @@ using OHOS::Ace::NG::LocationButtonModelNG; using OHOS::Ace::NG::SecurityComponentTheme; namespace OHOS::Ace::Framework { -static ButtonType TransformSecCompBgType(SecurityComponentBackgroundType type) -{ - ButtonType buttonType = ButtonType::CAPSULE; - switch (type) { - case SecurityComponentBackgroundType::CAPSULE: - buttonType = ButtonType::CAPSULE; - break; - case SecurityComponentBackgroundType::CIRCLE: - buttonType = ButtonType::CIRCLE; - break; - case SecurityComponentBackgroundType::NORMAL: - buttonType = ButtonType::NORMAL; - break; - default: - break; - } - return buttonType; -} - -bool JSSecLocationButton::ParseComponentStyle(const JSCallbackInfo& info, - LocationButtonLocationDescription& text, LocationButtonIconStyle& icon, SecurityComponentBackgroundType& bg) +bool JSLocationButton::ParseComponentStyle(const JSCallbackInfo& info, + LocationButtonLocationDescription& text, LocationButtonIconStyle& icon, int32_t& bg) { if (!info[0]->IsObject()) { return false; @@ -80,41 +61,36 @@ bool JSSecLocationButton::ParseComponentStyle(const JSCallbackInfo& info, return false; } - value = paramObject->GetProperty("background"); + value = paramObject->GetProperty("buttonType"); if (value->IsNumber()) { - bg = static_cast(value->ToNumber()); - if ((bg < SecurityComponentBackgroundType::CAPSULE) || - (bg > SecurityComponentBackgroundType::NORMAL)) { + bg = value->ToNumber(); + if ((bg < static_cast(ButtonType::NORMAL)) || + (bg > static_cast(ButtonType::CIRCLE))) { return false; } } else { - bg = SecurityComponentBackgroundType::BACKGROUND_NULL; + bg = BUTTON_TYPE_NULL; } return true; } -void JSSecLocationButton::Create(const JSCallbackInfo& info) +void JSLocationButton::Create(const JSCallbackInfo& info) { LocationButtonLocationDescription textDesc; LocationButtonIconStyle iconType; - SecurityComponentBackgroundType backgroundType; + int32_t backgroundType = 0; if (!ParseComponentStyle(info, textDesc, iconType, backgroundType)) { LocationButtonModelNG::GetInstance()->Create( static_cast(LocationButtonLocationDescription::CURRENT_LOCATION), - static_cast(LocationButtonIconStyle::ICON_FULL_FILLED), + static_cast(LocationButtonIconStyle::ICON_LINE), static_cast(ButtonType::CAPSULE)); } else { - if (backgroundType == SecurityComponentBackgroundType::BACKGROUND_NULL) { - LocationButtonModelNG::GetInstance()->Create(static_cast(textDesc), - static_cast(iconType), static_cast(backgroundType)); - } else { - LocationButtonModelNG::GetInstance()->Create(static_cast(textDesc), - static_cast(iconType), static_cast(TransformSecCompBgType(backgroundType))); - } + LocationButtonModelNG::GetInstance()->Create(static_cast(textDesc), + static_cast(iconType), backgroundType); } } -void JsSecLocationButtonClickFunction::Execute(GestureEvent& info) +void JsLocationButtonClickFunction::Execute(GestureEvent& info) { JSRef clickEventParam = JSRef::New(); Offset globalOffset = info.GetGlobalLocation(); @@ -145,16 +121,16 @@ void JsSecLocationButtonClickFunction::Execute(GestureEvent& info) } #endif JSRef errorParam = JSRef::Make(ToJSValue(res)); - JSRef params[] = { errorParam, clickEventParam }; + JSRef params[] = { clickEventParam, errorParam }; JsFunction::ExecuteJS(2, params); } -void JSSecLocationButton::JsOnClick(const JSCallbackInfo& info) +void JSLocationButton::JsOnClick(const JSCallbackInfo& info) { if (!info[0]->IsFunction()) { return; } - auto jsOnClickFunc = AceType::MakeRefPtr(JSRef::Cast(info[0])); + auto jsOnClickFunc = AceType::MakeRefPtr(JSRef::Cast(info[0])); auto onTap = [execCtx = info.GetExecutionContext(), func = jsOnClickFunc](GestureEvent& info) { JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx); ACE_SCORING_EVENT("onClick"); @@ -164,36 +140,35 @@ void JSSecLocationButton::JsOnClick(const JSCallbackInfo& info) NG::ViewAbstract::SetOnClick(std::move(onTap)); } -void JSSecLocationButton::JSBind(BindingTarget globalObj) +void JSLocationButton::JSBind(BindingTarget globalObj) { - JSClass::Declare("SecLocationButton"); + JSClass::Declare("LocationButton"); MethodOptions opt = MethodOptions::NONE; - JSClass::StaticMethod("create", &JSSecLocationButton::Create, opt); - JSClass::StaticMethod("iconSize", &JSSecButtonBase::SetIconSize); - JSClass::StaticMethod("layoutDirection", &JSSecButtonBase::SetLayoutDirection); - JSClass::StaticMethod("layoutOrder", &JSSecButtonBase::SetlayoutOrder); - JSClass::StaticMethod("fontSize", &JSSecButtonBase::SetFontSize); - JSClass::StaticMethod("fontStyle", &JSSecButtonBase::SetFontStyle); - JSClass::StaticMethod("iconColor", &JSSecButtonBase::SetIconColor); - JSClass::StaticMethod("fontWeight", &JSSecButtonBase::SetFontWeight); - JSClass::StaticMethod("fontFamily", &JSSecButtonBase::SetFontFamily); - JSClass::StaticMethod("fontColor", &JSSecButtonBase::SetFontColor); - JSClass::StaticMethod("backgroundColor", &JSSecButtonBase::SetBackgroundColor); - JSClass::StaticMethod("borderStyle", &JSSecButtonBase::SetBackgroundBorderStyle); - JSClass::StaticMethod("borderWidth", &JSSecButtonBase::SetBackgroundBorderWidth); - JSClass::StaticMethod("borderColor", &JSSecButtonBase::SetBackgroundBorderColor); - JSClass::StaticMethod("borderRadius", &JSSecButtonBase::SetBackgroundBorderRadius); - JSClass::StaticMethod("backgroundPadding", &JSSecButtonBase::SetBackgroundPadding); - JSClass::StaticMethod("textIconPadding", &JSSecButtonBase::SetTextIconSpace); - JSClass::StaticMethod("onClick", &JSSecLocationButton::JsOnClick); - JSClass::StaticMethod("key", &JSViewAbstract::JsKey); - JSClass::StaticMethod("position", &JSViewAbstract::JsPosition); - JSClass::StaticMethod("markAnchor", &JSViewAbstract::JsMarkAnchor); - JSClass::StaticMethod("offset", &JSViewAbstract::JsOffset); - JSClass::StaticMethod("pop", &JSViewAbstract::Pop, opt); + JSClass::StaticMethod("create", &JSLocationButton::Create, opt); + JSClass::StaticMethod("iconSize", &JSSecButtonBase::SetIconSize); + JSClass::StaticMethod("layoutDirection", &JSSecButtonBase::SetLayoutDirection); + JSClass::StaticMethod("fontSize", &JSSecButtonBase::SetFontSize); + JSClass::StaticMethod("fontStyle", &JSSecButtonBase::SetFontStyle); + JSClass::StaticMethod("iconColor", &JSSecButtonBase::SetIconColor); + JSClass::StaticMethod("fontWeight", &JSSecButtonBase::SetFontWeight); + JSClass::StaticMethod("fontFamily", &JSSecButtonBase::SetFontFamily); + JSClass::StaticMethod("fontColor", &JSSecButtonBase::SetFontColor); + JSClass::StaticMethod("backgroundColor", &JSSecButtonBase::SetBackgroundColor); + JSClass::StaticMethod("borderStyle", &JSSecButtonBase::SetBackgroundBorderStyle); + JSClass::StaticMethod("borderWidth", &JSSecButtonBase::SetBackgroundBorderWidth); + JSClass::StaticMethod("borderColor", &JSSecButtonBase::SetBackgroundBorderColor); + JSClass::StaticMethod("borderRadius", &JSSecButtonBase::SetBackgroundBorderRadius); + JSClass::StaticMethod("padding", &JSSecButtonBase::SetBackgroundPadding); + JSClass::StaticMethod("textIconSpace", &JSSecButtonBase::SetTextIconSpace); + JSClass::StaticMethod("onClick", &JSLocationButton::JsOnClick); + JSClass::StaticMethod("key", &JSViewAbstract::JsKey); + JSClass::StaticMethod("position", &JSViewAbstract::JsPosition); + JSClass::StaticMethod("markAnchor", &JSViewAbstract::JsMarkAnchor); + JSClass::StaticMethod("offset", &JSViewAbstract::JsOffset); + JSClass::StaticMethod("pop", &JSViewAbstract::Pop, opt); #if defined(PREVIEW) - JSClass::StaticMethod("debugLine", &JSViewAbstract::JsDebugLine); + JSClass::StaticMethod("debugLine", &JSViewAbstract::JsDebugLine); #endif - JSClass::Bind<>(globalObj); + JSClass::Bind<>(globalObj); } } // namespace OHOS::Ace::Framework diff --git a/frameworks/bridge/declarative_frontend/jsview/js_sec_location_button.h b/frameworks/bridge/declarative_frontend/jsview/js_location_button.h similarity index 71% rename from frameworks/bridge/declarative_frontend/jsview/js_sec_location_button.h rename to frameworks/bridge/declarative_frontend/jsview/js_location_button.h index 813c1392690..7b61a94ef34 100644 --- a/frameworks/bridge/declarative_frontend/jsview/js_sec_location_button.h +++ b/frameworks/bridge/declarative_frontend/jsview/js_location_button.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef FRAMEWORKS_BRIDGE_DECLARATIVE_FRONTEND_JS_VIEW_JS_SEC_LOCATION_BUTTON_H -#define FRAMEWORKS_BRIDGE_DECLARATIVE_FRONTEND_JS_VIEW_JS_SEC_LOCATION_BUTTON_H +#ifndef FRAMEWORKS_BRIDGE_DECLARATIVE_FRONTEND_JS_VIEW_JS_LOCATION_BUTTON_H +#define FRAMEWORKS_BRIDGE_DECLARATIVE_FRONTEND_JS_VIEW_JS_LOCATION_BUTTON_H #include "bridge/declarative_frontend/engine/bindings.h" #include "bridge/declarative_frontend/engine/functions/js_function.h" @@ -26,13 +26,13 @@ #include "core/gestures/click_recognizer.h" namespace OHOS::Ace::Framework { -class JsSecLocationButtonClickFunction : public JsFunction { - DECLARE_ACE_TYPE(JsSecLocationButtonClickFunction, JsFunction) +class JsLocationButtonClickFunction : public JsFunction { + DECLARE_ACE_TYPE(JsLocationButtonClickFunction, JsFunction) public: - explicit JsSecLocationButtonClickFunction(const JSRef& jsFunction) : + explicit JsLocationButtonClickFunction(const JSRef& jsFunction) : JsFunction(JSRef(), jsFunction) {} - ~JsSecLocationButtonClickFunction() override {}; + ~JsLocationButtonClickFunction() override {}; void Execute() override { JsFunction::ExecuteJS(); @@ -41,13 +41,13 @@ public: void Execute(GestureEvent& info); }; -class JSSecLocationButton : public JSViewAbstract, public JSInteractableView { +class JSLocationButton : public JSViewAbstract, public JSInteractableView { public: static void JSBind(BindingTarget globalObj); static bool ParseComponentStyle(const JSCallbackInfo& info, LocationButtonLocationDescription& text, - LocationButtonIconStyle& icon, SecurityComponentBackgroundType& bg); + LocationButtonIconStyle& icon, int32_t& bg); static void Create(const JSCallbackInfo& info); static void JsOnClick(const JSCallbackInfo& info); }; } // namespace OHOS::Ace::Framework -#endif // FRAMEWORKS_BRIDGE_DECLARATIVE_FRONTEND_JS_VIEW_JS_SEC_LOCATION_BUTTON_H +#endif // FRAMEWORKS_BRIDGE_DECLARATIVE_FRONTEND_JS_VIEW_JS_LOCATION_BUTTON_H diff --git a/frameworks/bridge/declarative_frontend/jsview/js_navigation.cpp b/frameworks/bridge/declarative_frontend/jsview/js_navigation.cpp index 90132e414f2..fbdb1640fdf 100644 --- a/frameworks/bridge/declarative_frontend/jsview/js_navigation.cpp +++ b/frameworks/bridge/declarative_frontend/jsview/js_navigation.cpp @@ -27,9 +27,9 @@ #include "bridge/declarative_frontend/jsview/js_view_abstract.h" #include "bridge/declarative_frontend/jsview/models/navigation_model_impl.h" #include "core/components_ng/base/view_stack_model.h" -#include "core/components_ng/pattern/navigation/navigation_declaration.h" #include "core/components_ng/pattern/navigation/navigation_model_data.h" #include "core/components_ng/pattern/navigation/navigation_model_ng.h" +#include "core/components_ng/pattern/navigation/navigation_declaration.h" namespace OHOS::Ace { std::unique_ptr NavigationModel::instance_ = nullptr; @@ -60,7 +60,9 @@ namespace { constexpr int32_t TITLE_MODE_RANGE = 2; constexpr int32_t NAVIGATION_MODE_RANGE = 2; constexpr int32_t NAV_BAR_POSITION_RANGE = 1; -constexpr int32_t DEFAULT_NAV_BAR_WIDTH = 240; +constexpr int32_t DEFAULT_NAV_BAR_WIDTH = 200; +constexpr Dimension DEFAULT_MIN_NAV_BAR_WIDTH = 240.0_vp; +constexpr Dimension DEFAULT_MAX_NAV_BAR_WIDTH = 280.0_vp; constexpr Dimension DEFAULT_MIN_CONTENT_WIDTH = 360.0_vp; JSRef TitleModeChangeEventToJSValue(const NavigationTitleModeChangeEvent& eventInfo) @@ -210,7 +212,8 @@ bool JSNavigation::ParseCommonTitle(const JSRef& jsValue) bool sub = subtitle->IsString(); bool main = title->IsString(); if (subtitle->IsString() || title->IsString()) { - NavigationModel::GetInstance()->ParseCommonTitle(sub, main, subtitle->ToString(), title->ToString()); + NavigationModel::GetInstance()->ParseCommonTitle( + sub, main, subtitle->ToString(), title->ToString()); } return isCommonTitle; } @@ -494,7 +497,7 @@ void JSNavigation::SetOnTitleModeChanged(const JSCallbackInfo& info) auto onTitleModeChangeCallback = AceType::MakeRefPtr(JSRef(), JSRef::Cast(info[0])); auto onTitleModeChange = [execCtx = info.GetExecutionContext(), func = std::move(onTitleModeChangeCallback)]( - NG::NavigationTitleMode mode) { + NG::NavigationTitleMode mode) { JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx); ACE_SCORING_EVENT("OnTitleModeChange"); JSRef param = JSRef::Make(ToJSValue(mode)); @@ -503,7 +506,7 @@ void JSNavigation::SetOnTitleModeChanged(const JSCallbackInfo& info) auto changeHandler = AceType::MakeRefPtr>( JSRef::Cast(info[0]), TitleModeChangeEventToJSValue); auto eventInfo = [executionContext = info.GetExecutionContext(), func = std::move(changeHandler)]( - const BaseEventInfo* baseInfo) { + const BaseEventInfo* baseInfo) { JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(executionContext); auto eventInfo = TypeInfoHelper::DynamicCast(baseInfo); if (!eventInfo) { @@ -577,6 +580,7 @@ void JSNavigation::SetMinContentWidth(const JSCallbackInfo& info) void JSNavigation::SetNavBarWidthRange(const JSCallbackInfo& info) { + if (info.Length() < 1) { LOGE("The arg is wrong, it is supposed to have at least 1 argument"); return; @@ -587,19 +591,26 @@ void JSNavigation::SetNavBarWidthRange(const JSCallbackInfo& info) JSRef max = rangeArray->GetValueAt(1); CalcDimension minNavBarWidth; + if (!ParseJsDimensionVp(min, minNavBarWidth)) { + minNavBarWidth = DEFAULT_MIN_NAV_BAR_WIDTH; + } + CalcDimension maxNavBarWidth; - ParseJsDimensionVp(min, minNavBarWidth); - ParseJsDimensionVp(max, maxNavBarWidth); + if (!ParseJsDimensionVp(max, maxNavBarWidth)) { + maxNavBarWidth = DEFAULT_MAX_NAV_BAR_WIDTH; + } if (LessNotEqual(minNavBarWidth.Value(), 0.0)) { - minNavBarWidth.SetValue(0); + minNavBarWidth = DEFAULT_MIN_NAV_BAR_WIDTH; } - NavigationModel::GetInstance()->SetMinNavBarWidth(minNavBarWidth); if (LessNotEqual(maxNavBarWidth.Value(), 0.0)) { - maxNavBarWidth.SetValue(0); + maxNavBarWidth = DEFAULT_MAX_NAV_BAR_WIDTH; } + + NavigationModel::GetInstance()->SetMinNavBarWidth(minNavBarWidth); NavigationModel::GetInstance()->SetMaxNavBarWidth(maxNavBarWidth); + } void JSNavigation::SetOnNavBarStateChange(const JSCallbackInfo& info) @@ -613,7 +624,7 @@ void JSNavigation::SetOnNavBarStateChange(const JSCallbackInfo& info) auto onNavBarStateChangeCallback = AceType::MakeRefPtr(JSRef(), JSRef::Cast(info[0])); auto onNavBarStateChange = [execCtx = info.GetExecutionContext(), - func = std::move(onNavBarStateChangeCallback)](bool isVisible) { + func = std::move(onNavBarStateChangeCallback)](bool isVisible) { JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx); ACE_SCORING_EVENT("OnNavBarStateChange"); JSRef param = JSRef::Make(ToJSValue(isVisible)); diff --git a/frameworks/bridge/declarative_frontend/jsview/js_sec_paste_button.cpp b/frameworks/bridge/declarative_frontend/jsview/js_paste_button.cpp similarity index 65% rename from frameworks/bridge/declarative_frontend/jsview/js_sec_paste_button.cpp rename to frameworks/bridge/declarative_frontend/jsview/js_paste_button.cpp index 28f4bf978c3..4232cbff6fd 100644 --- a/frameworks/bridge/declarative_frontend/jsview/js_sec_paste_button.cpp +++ b/frameworks/bridge/declarative_frontend/jsview/js_paste_button.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "frameworks/bridge/declarative_frontend/jsview/js_sec_paste_button.h" +#include "frameworks/bridge/declarative_frontend/jsview/js_paste_button.h" #include "bridge/common/utils/utils.h" #include "core/common/container.h" @@ -26,7 +26,7 @@ using OHOS::Ace::NG::PasteButtonModelNG; using OHOS::Ace::NG::SecurityComponentTheme; namespace OHOS::Ace::Framework { -bool JSSecPasteButton::ParseComponentStyle(const JSCallbackInfo& info, +bool JSPasteButton::ParseComponentStyle(const JSCallbackInfo& info, PasteButtonPasteDescription& text, PasteButtonIconStyle& icon, int32_t& bg) { if (!info[0]->IsObject()) { @@ -73,7 +73,7 @@ bool JSSecPasteButton::ParseComponentStyle(const JSCallbackInfo& info, return true; } -void JSSecPasteButton::Create(const JSCallbackInfo& info) +void JSPasteButton::Create(const JSCallbackInfo& info) { PasteButtonPasteDescription textDesc; PasteButtonIconStyle iconType; @@ -89,7 +89,7 @@ void JSSecPasteButton::Create(const JSCallbackInfo& info) } } -void JsSecPasteButtonClickFunction::Execute(GestureEvent& info) +void JsPasteButtonClickFunction::Execute(GestureEvent& info) { JSRef clickEventParam = JSRef::New(); Offset globalOffset = info.GetGlobalLocation(); @@ -124,12 +124,12 @@ void JsSecPasteButtonClickFunction::Execute(GestureEvent& info) JsFunction::ExecuteJS(2, params); } -void JSSecPasteButton::JsOnClick(const JSCallbackInfo& info) +void JSPasteButton::JsOnClick(const JSCallbackInfo& info) { if (!info[0]->IsFunction()) { return; } - auto jsOnClickFunc = AceType::MakeRefPtr(JSRef::Cast(info[0])); + auto jsOnClickFunc = AceType::MakeRefPtr(JSRef::Cast(info[0])); auto onTap = [execCtx = info.GetExecutionContext(), func = jsOnClickFunc](GestureEvent& info) { JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx); ACE_SCORING_EVENT("onClick"); @@ -139,36 +139,35 @@ void JSSecPasteButton::JsOnClick(const JSCallbackInfo& info) NG::ViewAbstract::SetOnClick(std::move(onTap)); } -void JSSecPasteButton::JSBind(BindingTarget globalObj) +void JSPasteButton::JSBind(BindingTarget globalObj) { - JSClass::Declare("SecPasteButton"); + JSClass::Declare("PasteButton"); MethodOptions opt = MethodOptions::NONE; - JSClass::StaticMethod("create", &JSSecPasteButton::Create, opt); - JSClass::StaticMethod("iconSize", &JSSecButtonBase::SetIconSize); - JSClass::StaticMethod("layoutDirection", &JSSecButtonBase::SetLayoutDirection); - JSClass::StaticMethod("layoutOrder", &JSSecButtonBase::SetlayoutOrder); - JSClass::StaticMethod("fontSize", &JSSecButtonBase::SetFontSize); - JSClass::StaticMethod("fontStyle", &JSSecButtonBase::SetFontStyle); - JSClass::StaticMethod("iconColor", &JSSecButtonBase::SetIconColor); - JSClass::StaticMethod("fontWeight", &JSSecButtonBase::SetFontWeight); - JSClass::StaticMethod("fontFamily", &JSSecButtonBase::SetFontFamily); - JSClass::StaticMethod("fontColor", &JSSecButtonBase::SetFontColor); - JSClass::StaticMethod("backgroundColor", &JSSecButtonBase::SetBackgroundColor); - JSClass::StaticMethod("borderStyle", &JSSecButtonBase::SetBackgroundBorderStyle); - JSClass::StaticMethod("borderWidth", &JSSecButtonBase::SetBackgroundBorderWidth); - JSClass::StaticMethod("borderColor", &JSSecButtonBase::SetBackgroundBorderColor); - JSClass::StaticMethod("borderRadius", &JSSecButtonBase::SetBackgroundBorderRadius); - JSClass::StaticMethod("padding", &JSSecButtonBase::SetBackgroundPadding); - JSClass::StaticMethod("textIconSpace", &JSSecButtonBase::SetTextIconSpace); - JSClass::StaticMethod("onClick", &JSSecPasteButton::JsOnClick); - JSClass::StaticMethod("key", &JSViewAbstract::JsKey); - JSClass::StaticMethod("position", &JSViewAbstract::JsPosition); - JSClass::StaticMethod("markAnchor", &JSViewAbstract::JsMarkAnchor); - JSClass::StaticMethod("offset", &JSViewAbstract::JsOffset); - JSClass::StaticMethod("pop", &JSViewAbstract::Pop, opt); + JSClass::StaticMethod("create", &JSPasteButton::Create, opt); + JSClass::StaticMethod("iconSize", &JSSecButtonBase::SetIconSize); + JSClass::StaticMethod("layoutDirection", &JSSecButtonBase::SetLayoutDirection); + JSClass::StaticMethod("fontSize", &JSSecButtonBase::SetFontSize); + JSClass::StaticMethod("fontStyle", &JSSecButtonBase::SetFontStyle); + JSClass::StaticMethod("iconColor", &JSSecButtonBase::SetIconColor); + JSClass::StaticMethod("fontWeight", &JSSecButtonBase::SetFontWeight); + JSClass::StaticMethod("fontFamily", &JSSecButtonBase::SetFontFamily); + JSClass::StaticMethod("fontColor", &JSSecButtonBase::SetFontColor); + JSClass::StaticMethod("backgroundColor", &JSSecButtonBase::SetBackgroundColor); + JSClass::StaticMethod("borderStyle", &JSSecButtonBase::SetBackgroundBorderStyle); + JSClass::StaticMethod("borderWidth", &JSSecButtonBase::SetBackgroundBorderWidth); + JSClass::StaticMethod("borderColor", &JSSecButtonBase::SetBackgroundBorderColor); + JSClass::StaticMethod("borderRadius", &JSSecButtonBase::SetBackgroundBorderRadius); + JSClass::StaticMethod("padding", &JSSecButtonBase::SetBackgroundPadding); + JSClass::StaticMethod("textIconSpace", &JSSecButtonBase::SetTextIconSpace); + JSClass::StaticMethod("onClick", &JSPasteButton::JsOnClick); + JSClass::StaticMethod("key", &JSViewAbstract::JsKey); + JSClass::StaticMethod("position", &JSViewAbstract::JsPosition); + JSClass::StaticMethod("markAnchor", &JSViewAbstract::JsMarkAnchor); + JSClass::StaticMethod("offset", &JSViewAbstract::JsOffset); + JSClass::StaticMethod("pop", &JSViewAbstract::Pop, opt); #if defined(PREVIEW) - JSClass::StaticMethod("debugLine", &JSViewAbstract::JsDebugLine); + JSClass::StaticMethod("debugLine", &JSViewAbstract::JsDebugLine); #endif - JSClass::Bind<>(globalObj); + JSClass::Bind<>(globalObj); } } // namespace OHOS::Ace::Framework diff --git a/frameworks/bridge/declarative_frontend/jsview/js_sec_paste_button.h b/frameworks/bridge/declarative_frontend/jsview/js_paste_button.h similarity index 74% rename from frameworks/bridge/declarative_frontend/jsview/js_sec_paste_button.h rename to frameworks/bridge/declarative_frontend/jsview/js_paste_button.h index 04302b0a1aa..fafff9c9c88 100644 --- a/frameworks/bridge/declarative_frontend/jsview/js_sec_paste_button.h +++ b/frameworks/bridge/declarative_frontend/jsview/js_paste_button.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef FRAMEWORKS_BRIDGE_DECLARATIVE_FRONTEND_JS_VIEW_JS_SEC_PASTE_BUTTON_H -#define FRAMEWORKS_BRIDGE_DECLARATIVE_FRONTEND_JS_VIEW_JS_SEC_PASTE_BUTTON_H +#ifndef FRAMEWORKS_BRIDGE_DECLARATIVE_FRONTEND_JS_VIEW_JS_PASTE_BUTTON_H +#define FRAMEWORKS_BRIDGE_DECLARATIVE_FRONTEND_JS_VIEW_JS_PASTE_BUTTON_H #include "bridge/declarative_frontend/engine/bindings.h" #include "bridge/declarative_frontend/engine/functions/js_function.h" @@ -26,13 +26,13 @@ #include "core/gestures/click_recognizer.h" namespace OHOS::Ace::Framework { -class JsSecPasteButtonClickFunction : public JsFunction { - DECLARE_ACE_TYPE(JsSecPasteButtonClickFunction, JsFunction) +class JsPasteButtonClickFunction : public JsFunction { + DECLARE_ACE_TYPE(JsPasteButtonClickFunction, JsFunction) public: - explicit JsSecPasteButtonClickFunction(const JSRef& jsFunction) : + explicit JsPasteButtonClickFunction(const JSRef& jsFunction) : JsFunction(JSRef(), jsFunction) {} - ~JsSecPasteButtonClickFunction() override {}; + ~JsPasteButtonClickFunction() override {}; void Execute() override { JsFunction::ExecuteJS(); @@ -41,7 +41,7 @@ public: void Execute(GestureEvent& info); }; -class JSSecPasteButton : public JSViewAbstract, public JSInteractableView { +class JSPasteButton : public JSViewAbstract, public JSInteractableView { public: static void JSBind(BindingTarget globalObj); static bool ParseComponentStyle(const JSCallbackInfo& info, PasteButtonPasteDescription& text, @@ -50,4 +50,4 @@ public: static void JsOnClick(const JSCallbackInfo& info); }; } // namespace OHOS::Ace::Framework -#endif // FRAMEWORKS_BRIDGE_DECLARATIVE_FRONTEND_JS_VIEW_JS_SEC_PASTE_BUTTON_H +#endif // FRAMEWORKS_BRIDGE_DECLARATIVE_FRONTEND_JS_VIEW_JS_PASTE_BUTTON_H diff --git a/frameworks/bridge/declarative_frontend/jsview/js_richeditor.cpp b/frameworks/bridge/declarative_frontend/jsview/js_richeditor.cpp index f3b14bdde38..d04148dbc1e 100644 --- a/frameworks/bridge/declarative_frontend/jsview/js_richeditor.cpp +++ b/frameworks/bridge/declarative_frontend/jsview/js_richeditor.cpp @@ -409,17 +409,13 @@ ImageSpanAttribute JSRichEditorController::ParseJsImageSpanAttribute(JSRef size = JSRef::Cast(sizeObj); JSRef width = size->GetValueAt(0); CalcDimension imageSpanWidth; - if (!width->IsNull() && (JSContainerBase::ParseJsDimensionVp(width, imageSpanWidth) || - JSContainerBase::ParseJsDimensionFp(width, imageSpanWidth) || - JSContainerBase::ParseJsDimensionPx(width, imageSpanWidth))) { + if (!width->IsNull() && JSContainerBase::ParseJsDimensionVp(width, imageSpanWidth)) { imageSize.width = imageSpanWidth; updateSpanStyle_.updateImageWidth = imageSpanWidth; } JSRef height = size->GetValueAt(1); CalcDimension imageSpanHeight; - if (!height->IsNull() && (JSContainerBase::ParseJsDimensionVp(height, imageSpanHeight) || - JSContainerBase::ParseJsDimensionFp(height, imageSpanHeight) || - JSContainerBase::ParseJsDimensionPx(height, imageSpanHeight))) { + if (!height->IsNull() && JSContainerBase::ParseJsDimensionVp(height, imageSpanHeight)) { imageSize.height = imageSpanHeight; updateSpanStyle_.updateImageHeight = imageSpanHeight; } @@ -511,13 +507,19 @@ void JSRichEditorController::AddImageSpan(const JSCallbackInfo& args) return; } if (options.image.has_value()) { - SrcType srcType = ImageSourceInfo::ResolveURIType(options.image.value()); + std::string assetSrc = options.image.value(); + SrcType srcType = ImageSourceInfo::ResolveURIType(assetSrc); + if (assetSrc[0] == '/') { + assetSrc = assetSrc.substr(1); // get the asset src without '/'. + } else if (assetSrc[0] == '.' && assetSrc.size() > 2 && assetSrc[1] == '/') { + assetSrc = assetSrc.substr(2); // get the asset src without './'. + } if (srcType == SrcType::ASSET) { auto pipelineContext = PipelineBase::GetCurrentContext(); CHECK_NULL_VOID(pipelineContext); auto assetManager = pipelineContext->GetAssetManager(); CHECK_NULL_VOID(assetManager); - auto assetData = assetManager->GetAsset(options.image.value()); + auto assetData = assetManager->GetAsset(assetSrc); if (!assetData) { args.SetReturnValue(JSRef::Make(ToJSValue(-1))); return; diff --git a/frameworks/bridge/declarative_frontend/jsview/js_sec_save_button.cpp b/frameworks/bridge/declarative_frontend/jsview/js_save_button.cpp similarity index 65% rename from frameworks/bridge/declarative_frontend/jsview/js_sec_save_button.cpp rename to frameworks/bridge/declarative_frontend/jsview/js_save_button.cpp index 2d97c97d21b..43d6edcf31b 100644 --- a/frameworks/bridge/declarative_frontend/jsview/js_sec_save_button.cpp +++ b/frameworks/bridge/declarative_frontend/jsview/js_save_button.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "frameworks/bridge/declarative_frontend/jsview/js_sec_save_button.h" +#include "frameworks/bridge/declarative_frontend/jsview/js_save_button.h" #include "bridge/common/utils/utils.h" #include "core/common/container.h" @@ -26,7 +26,7 @@ using OHOS::Ace::NG::SaveButtonModelNG; using OHOS::Ace::NG::SecurityComponentTheme; namespace OHOS::Ace::Framework { -bool JSSecSaveButton::ParseComponentStyle(const JSCallbackInfo& info, +bool JSSaveButton::ParseComponentStyle(const JSCallbackInfo& info, SaveButtonSaveDescription& text, SaveButtonIconStyle& icon, int32_t& bg) { if (!info[0]->IsObject()) { @@ -74,7 +74,7 @@ bool JSSecSaveButton::ParseComponentStyle(const JSCallbackInfo& info, return true; } -void JSSecSaveButton::Create(const JSCallbackInfo& info) +void JSSaveButton::Create(const JSCallbackInfo& info) { SaveButtonSaveDescription textDesc; SaveButtonIconStyle iconType; @@ -90,7 +90,7 @@ void JSSecSaveButton::Create(const JSCallbackInfo& info) } } -void JsSecSaveButtonClickFunction::Execute(GestureEvent& info) +void JsSaveButtonClickFunction::Execute(GestureEvent& info) { JSRef clickEventParam = JSRef::New(); Offset globalOffset = info.GetGlobalLocation(); @@ -125,12 +125,12 @@ void JsSecSaveButtonClickFunction::Execute(GestureEvent& info) JsFunction::ExecuteJS(2, params); } -void JSSecSaveButton::JsOnClick(const JSCallbackInfo& info) +void JSSaveButton::JsOnClick(const JSCallbackInfo& info) { if (!info[0]->IsFunction()) { return; } - auto jsOnClickFunc = AceType::MakeRefPtr(JSRef::Cast(info[0])); + auto jsOnClickFunc = AceType::MakeRefPtr(JSRef::Cast(info[0])); auto onTap = [execCtx = info.GetExecutionContext(), func = jsOnClickFunc](GestureEvent& info) { JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx); ACE_SCORING_EVENT("onClick"); @@ -140,36 +140,35 @@ void JSSecSaveButton::JsOnClick(const JSCallbackInfo& info) NG::ViewAbstract::SetOnClick(std::move(onTap)); } -void JSSecSaveButton::JSBind(BindingTarget globalObj) +void JSSaveButton::JSBind(BindingTarget globalObj) { - JSClass::Declare("SecSaveButton"); + JSClass::Declare("SaveButton"); MethodOptions opt = MethodOptions::NONE; - JSClass::StaticMethod("create", &JSSecSaveButton::Create, opt); - JSClass::StaticMethod("iconSize", &JSSecButtonBase::SetIconSize); - JSClass::StaticMethod("layoutDirection", &JSSecButtonBase::SetLayoutDirection); - JSClass::StaticMethod("layoutOrder", &JSSecButtonBase::SetlayoutOrder); - JSClass::StaticMethod("fontSize", &JSSecButtonBase::SetFontSize); - JSClass::StaticMethod("fontStyle", &JSSecButtonBase::SetFontStyle); - JSClass::StaticMethod("iconColor", &JSSecButtonBase::SetIconColor); - JSClass::StaticMethod("fontWeight", &JSSecButtonBase::SetFontWeight); - JSClass::StaticMethod("fontFamily", &JSSecButtonBase::SetFontFamily); - JSClass::StaticMethod("fontColor", &JSSecButtonBase::SetFontColor); - JSClass::StaticMethod("backgroundColor", &JSSecButtonBase::SetBackgroundColor); - JSClass::StaticMethod("borderStyle", &JSSecButtonBase::SetBackgroundBorderStyle); - JSClass::StaticMethod("borderWidth", &JSSecButtonBase::SetBackgroundBorderWidth); - JSClass::StaticMethod("borderColor", &JSSecButtonBase::SetBackgroundBorderColor); - JSClass::StaticMethod("borderRadius", &JSSecButtonBase::SetBackgroundBorderRadius); - JSClass::StaticMethod("padding", &JSSecButtonBase::SetBackgroundPadding); - JSClass::StaticMethod("textIconSpace", &JSSecButtonBase::SetTextIconSpace); - JSClass::StaticMethod("onClick", &JSSecSaveButton::JsOnClick); - JSClass::StaticMethod("key", &JSViewAbstract::JsKey); - JSClass::StaticMethod("position", &JSViewAbstract::JsPosition); - JSClass::StaticMethod("markAnchor", &JSViewAbstract::JsMarkAnchor); - JSClass::StaticMethod("offset", &JSViewAbstract::JsOffset); - JSClass::StaticMethod("pop", &JSViewAbstract::Pop, opt); + JSClass::StaticMethod("create", &JSSaveButton::Create, opt); + JSClass::StaticMethod("iconSize", &JSSecButtonBase::SetIconSize); + JSClass::StaticMethod("layoutDirection", &JSSecButtonBase::SetLayoutDirection); + JSClass::StaticMethod("fontSize", &JSSecButtonBase::SetFontSize); + JSClass::StaticMethod("fontStyle", &JSSecButtonBase::SetFontStyle); + JSClass::StaticMethod("iconColor", &JSSecButtonBase::SetIconColor); + JSClass::StaticMethod("fontWeight", &JSSecButtonBase::SetFontWeight); + JSClass::StaticMethod("fontFamily", &JSSecButtonBase::SetFontFamily); + JSClass::StaticMethod("fontColor", &JSSecButtonBase::SetFontColor); + JSClass::StaticMethod("backgroundColor", &JSSecButtonBase::SetBackgroundColor); + JSClass::StaticMethod("borderStyle", &JSSecButtonBase::SetBackgroundBorderStyle); + JSClass::StaticMethod("borderWidth", &JSSecButtonBase::SetBackgroundBorderWidth); + JSClass::StaticMethod("borderColor", &JSSecButtonBase::SetBackgroundBorderColor); + JSClass::StaticMethod("borderRadius", &JSSecButtonBase::SetBackgroundBorderRadius); + JSClass::StaticMethod("padding", &JSSecButtonBase::SetBackgroundPadding); + JSClass::StaticMethod("textIconSpace", &JSSecButtonBase::SetTextIconSpace); + JSClass::StaticMethod("onClick", &JSSaveButton::JsOnClick); + JSClass::StaticMethod("key", &JSViewAbstract::JsKey); + JSClass::StaticMethod("position", &JSViewAbstract::JsPosition); + JSClass::StaticMethod("markAnchor", &JSViewAbstract::JsMarkAnchor); + JSClass::StaticMethod("offset", &JSViewAbstract::JsOffset); + JSClass::StaticMethod("pop", &JSViewAbstract::Pop, opt); #if defined(PREVIEW) - JSClass::StaticMethod("debugLine", &JSViewAbstract::JsDebugLine); + JSClass::StaticMethod("debugLine", &JSViewAbstract::JsDebugLine); #endif - JSClass::Bind<>(globalObj); + JSClass::Bind<>(globalObj); } } // namespace OHOS::Ace::Framework diff --git a/frameworks/bridge/declarative_frontend/jsview/js_sec_save_button.h b/frameworks/bridge/declarative_frontend/jsview/js_save_button.h similarity index 75% rename from frameworks/bridge/declarative_frontend/jsview/js_sec_save_button.h rename to frameworks/bridge/declarative_frontend/jsview/js_save_button.h index 21c92a4f8b3..9c3024c1544 100644 --- a/frameworks/bridge/declarative_frontend/jsview/js_sec_save_button.h +++ b/frameworks/bridge/declarative_frontend/jsview/js_save_button.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef FRAMEWORKS_BRIDGE_DECLARATIVE_FRONTEND_JS_VIEW_JS_SEC_SAVE_BUTTON_H -#define FRAMEWORKS_BRIDGE_DECLARATIVE_FRONTEND_JS_VIEW_JS_SEC_SAVE_BUTTON_H +#ifndef FRAMEWORKS_BRIDGE_DECLARATIVE_FRONTEND_JS_VIEW_JS_SAVE_BUTTON_H +#define FRAMEWORKS_BRIDGE_DECLARATIVE_FRONTEND_JS_VIEW_JS_SAVE_BUTTON_H #include "bridge/declarative_frontend/engine/bindings.h" #include "bridge/declarative_frontend/engine/functions/js_function.h" @@ -26,13 +26,13 @@ #include "core/gestures/click_recognizer.h" namespace OHOS::Ace::Framework { -class JsSecSaveButtonClickFunction : public JsFunction { - DECLARE_ACE_TYPE(JsSecSaveButtonClickFunction, JsFunction) +class JsSaveButtonClickFunction : public JsFunction { + DECLARE_ACE_TYPE(JsSaveButtonClickFunction, JsFunction) public: - explicit JsSecSaveButtonClickFunction(const JSRef& jsFunction) : + explicit JsSaveButtonClickFunction(const JSRef& jsFunction) : JsFunction(JSRef(), jsFunction) {} - ~JsSecSaveButtonClickFunction() override {}; + ~JsSaveButtonClickFunction() override {}; void Execute() override { JsFunction::ExecuteJS(); @@ -41,7 +41,7 @@ public: void Execute(GestureEvent& info); }; -class JSSecSaveButton : public JSViewAbstract, public JSInteractableView { +class JSSaveButton : public JSViewAbstract, public JSInteractableView { public: static void JSBind(BindingTarget globalObj); static bool ParseComponentStyle(const JSCallbackInfo& info, SaveButtonSaveDescription& text, @@ -50,4 +50,4 @@ public: static void JsOnClick(const JSCallbackInfo& info); }; } // namespace OHOS::Ace::Framework -#endif // FRAMEWORKS_BRIDGE_DECLARATIVE_FRONTEND_JS_VIEW_JS_SEC_LOCATION_BUTTON_H +#endif // FRAMEWORKS_BRIDGE_DECLARATIVE_FRONTEND_JS_VIEW_JS_SAVE_BUTTON_H diff --git a/frameworks/bridge/declarative_frontend/jsview/js_scroller.cpp b/frameworks/bridge/declarative_frontend/jsview/js_scroller.cpp index bd8c763d551..e87cc8e34c2 100644 --- a/frameworks/bridge/declarative_frontend/jsview/js_scroller.cpp +++ b/frameworks/bridge/declarative_frontend/jsview/js_scroller.cpp @@ -61,6 +61,8 @@ constexpr ScrollAlign ALIGN_TABLE[] = { ScrollAlign::AUTO, }; +const std::regex DIMENSION_REGEX(R"(^[-+]?\d+(?:\.\d+)?(?:px|vp|fp|lpx)?$)", std::regex::icase); + } // namespace void JSScroller::JSBind(BindingTarget globalObj) @@ -100,8 +102,11 @@ void JSScroller::ScrollTo(const JSCallbackInfo& args) JSRef obj = JSRef::Cast(args[0]); Dimension xOffset; Dimension yOffset; - if (!ConvertFromJSValue(obj->GetProperty("xOffset"), xOffset) || - !ConvertFromJSValue(obj->GetProperty("yOffset"), yOffset)) { + auto xOffsetStr = obj->GetProperty("xOffset"); + auto yOffsetStr = obj->GetProperty("yOffset"); + if (!std::regex_match(xOffsetStr->ToString(), DIMENSION_REGEX) || + !std::regex_match(yOffsetStr->ToString(), DIMENSION_REGEX) || !ConvertFromJSValue(xOffsetStr, xOffset) || + !ConvertFromJSValue(yOffsetStr, yOffset)) { LOGW("Failed to parse param 'xOffset' or 'yOffset'"); return; } diff --git a/frameworks/bridge/declarative_frontend/jsview/js_sec_button_base.cpp b/frameworks/bridge/declarative_frontend/jsview/js_sec_button_base.cpp index bd4ce8c19c1..bcc33dee156 100644 --- a/frameworks/bridge/declarative_frontend/jsview/js_sec_button_base.cpp +++ b/frameworks/bridge/declarative_frontend/jsview/js_sec_button_base.cpp @@ -128,23 +128,6 @@ void JSSecButtonBase::SetLayoutDirection(const JSCallbackInfo& info) static_cast(value)); } -void JSSecButtonBase::SetlayoutOrder(const JSCallbackInfo& info) -{ - if (!info[0]->IsNumber()) { - SecurityComponentModelNG::SetlayoutOrder( - SecSecurityComponentLayoutOrder::ICON_FIRST); - return; - } - int32_t value = info[0]->ToNumber(); - if ((value < static_cast(SecSecurityComponentLayoutOrder::ICON_FIRST)) || - (value > static_cast(SecSecurityComponentLayoutOrder::TEXT_FIRST))) { - SecurityComponentModelNG::SetlayoutOrder( - SecSecurityComponentLayoutOrder::ICON_FIRST); - return; - } - SecurityComponentModelNG::SetlayoutOrder(static_cast(value)); -} - void JSSecButtonBase::SetBackgroundColor(const JSCallbackInfo& info) { auto theme = GetTheme(); diff --git a/frameworks/bridge/declarative_frontend/jsview/js_sec_button_base.h b/frameworks/bridge/declarative_frontend/jsview/js_sec_button_base.h index 88256cb7704..148aacc19f6 100644 --- a/frameworks/bridge/declarative_frontend/jsview/js_sec_button_base.h +++ b/frameworks/bridge/declarative_frontend/jsview/js_sec_button_base.h @@ -35,7 +35,6 @@ public: static void SetFontFamily(const JSCallbackInfo& info); static void SetFontColor(const JSCallbackInfo& info); static void SetLayoutDirection(const JSCallbackInfo& info); - static void SetlayoutOrder(const JSCallbackInfo& info); static void SetBackgroundColor(const JSCallbackInfo& info); static void SetBackgroundPadding(const JSCallbackInfo& info); static void SetTextIconSpace(const JSCallbackInfo& info); diff --git a/frameworks/bridge/declarative_frontend/jsview/js_swiper.cpp b/frameworks/bridge/declarative_frontend/jsview/js_swiper.cpp index e38ee9686d6..c811526bca8 100644 --- a/frameworks/bridge/declarative_frontend/jsview/js_swiper.cpp +++ b/frameworks/bridge/declarative_frontend/jsview/js_swiper.cpp @@ -427,7 +427,7 @@ SwiperParameters JSSwiper::GetDotIndicatorInfo(const JSRef& obj) bool parseOk = false; SwiperParameters swiperParameters; CalcDimension dimPosition; - parseOk = ParseJsDimensionPx(leftValue, dimPosition); + parseOk = ParseJsDimensionVp(leftValue, dimPosition); if (parseOk) { if (dimPosition.ConvertToPx() < 0.0f) { dimPosition = 0.0_vp; @@ -436,20 +436,20 @@ SwiperParameters JSSwiper::GetDotIndicatorInfo(const JSRef& obj) dimPosition = 0.0_vp; } swiperParameters.dimLeft = dimPosition; - parseOk = ParseJsDimensionPx(topValue, dimPosition); + parseOk = ParseJsDimensionVp(topValue, dimPosition); swiperParameters.dimTop = parseOk ? dimPosition : 0.0_vp; - parseOk = ParseJsDimensionPx(rightValue, dimPosition); + parseOk = ParseJsDimensionVp(rightValue, dimPosition); swiperParameters.dimRight = parseOk ? dimPosition : 0.0_vp; - parseOk = ParseJsDimensionPx(bottomValue, dimPosition); + parseOk = ParseJsDimensionVp(bottomValue, dimPosition); swiperParameters.dimBottom = parseOk ? dimPosition : 0.0_vp; - parseOk = ParseJsDimensionPx(itemWidthValue, dimPosition); + parseOk = ParseJsDimensionVp(itemWidthValue, dimPosition); auto defaultSize = swiperIndicatorTheme->GetSize(); swiperParameters.itemWidth = parseOk && dimPosition > 0.0_vp ? dimPosition : defaultSize; - parseOk = ParseJsDimensionPx(itemHeightValue, dimPosition); + parseOk = ParseJsDimensionVp(itemHeightValue, dimPosition); swiperParameters.itemHeight = parseOk && dimPosition > 0.0_vp ? dimPosition : defaultSize; - parseOk = ParseJsDimensionPx(selectedItemWidthValue, dimPosition); + parseOk = ParseJsDimensionVp(selectedItemWidthValue, dimPosition); swiperParameters.selectedItemWidth = parseOk && dimPosition > 0.0_vp ? dimPosition : defaultSize; - parseOk = ParseJsDimensionPx(selectedItemHeightValue, dimPosition); + parseOk = ParseJsDimensionVp(selectedItemHeightValue, dimPosition); swiperParameters.selectedItemHeight = parseOk && dimPosition > 0.0_vp ? dimPosition : defaultSize; if (maskValue->IsBoolean()) { auto mask = maskValue->ToBoolean(); @@ -684,15 +684,15 @@ void JSSwiper::SetIndicatorStyle(const JSCallbackInfo& info) auto swiperIndicatorTheme = pipelineContext->GetTheme(); CHECK_NULL_VOID(swiperIndicatorTheme); CalcDimension dimPosition; - bool parseOk = ParseJsDimensionPx(leftValue, dimPosition); + bool parseOk = ParseJsDimensionVp(leftValue, dimPosition); swiperParameters.dimLeft = parseOk ? dimPosition : 0.0_vp; - parseOk = ParseJsDimensionPx(topValue, dimPosition); + parseOk = ParseJsDimensionVp(topValue, dimPosition); swiperParameters.dimTop = parseOk ? dimPosition : 0.0_vp; - parseOk = ParseJsDimensionPx(rightValue, dimPosition); + parseOk = ParseJsDimensionVp(rightValue, dimPosition); swiperParameters.dimRight = parseOk ? dimPosition : 0.0_vp; - parseOk = ParseJsDimensionPx(bottomValue, dimPosition); + parseOk = ParseJsDimensionVp(bottomValue, dimPosition); swiperParameters.dimBottom = parseOk ? dimPosition : 0.0_vp; - parseOk = ParseJsDimensionPx(sizeValue, dimPosition); + parseOk = ParseJsDimensionVp(sizeValue, dimPosition); SwiperModel::GetInstance()->SetIsIndicatorCustomSize(false); swiperParameters.itemWidth = parseOk && dimPosition > 0.0_vp ? dimPosition : swiperIndicatorTheme->GetSize(); swiperParameters.itemHeight = parseOk && dimPosition > 0.0_vp ? dimPosition : swiperIndicatorTheme->GetSize(); diff --git a/frameworks/bridge/declarative_frontend/jsview/js_text.cpp b/frameworks/bridge/declarative_frontend/jsview/js_text.cpp index 2bcb1ee1fad..fac368f8a40 100644 --- a/frameworks/bridge/declarative_frontend/jsview/js_text.cpp +++ b/frameworks/bridge/declarative_frontend/jsview/js_text.cpp @@ -38,6 +38,7 @@ #include "core/components_ng/pattern/text/text_model.h" #include "core/components_ng/pattern/text/text_model_ng.h" #include "core/event/ace_event_handler.h" +#include "core/pipeline/pipeline_base.h" namespace OHOS::Ace { @@ -147,17 +148,14 @@ void JSText::SetFontSize(const JSCallbackInfo& info) LOGI("The argv is wrong, it is supposed to have at least 1 argument"); return; } - CalcDimension fontSize; - if (!ParseJsDimensionFp(info[0], fontSize)) { - return; - } + auto pipelineContext = PipelineBase::GetCurrentContext(); + CHECK_NULL_VOID_NOLOG(pipelineContext); + auto theme = pipelineContext->GetTheme(); + CHECK_NULL_VOID_NOLOG(theme); + CalcDimension fontSize = theme->GetTextStyle().GetFontSize(); + ParseJsDimensionFp(info[0], fontSize); if (fontSize.IsNegative() || fontSize.Unit() == DimensionUnit::PERCENT) { - auto pipelineContext = PipelineContext::GetCurrentContext(); - CHECK_NULL_VOID_NOLOG(pipelineContext); - auto theme = pipelineContext->GetTheme(); - CHECK_NULL_VOID_NOLOG(theme); - TextModel::GetInstance()->SetFontSize(theme->GetTextStyle().GetFontSize()); - return; + fontSize = theme->GetTextStyle().GetFontSize(); } TextModel::GetInstance()->SetFontSize(fontSize); } @@ -248,14 +246,8 @@ void JSText::SetTextOverflow(const JSCallbackInfo& info) void JSText::SetMaxLines(const JSCallbackInfo& info) { - int32_t value; - if (info[0]->ToString() == "Infinity") { - value = Infinity(); - } else if (!info[0]->IsNumber()) { - return; - } else { - ParseJsInt32(info[0], value); - } + int32_t value = Infinity(); + ParseJsInt32(info[0], value); TextModel::GetInstance()->SetMaxLines(value); } @@ -335,9 +327,7 @@ void JSText::SetMinFontSize(const JSCallbackInfo& info) return; } CalcDimension fontSize; - if (!ParseJsDimensionFp(info[0], fontSize)) { - return; - } + ParseJsDimensionFp(info[0], fontSize); TextModel::GetInstance()->SetAdaptMinFontSize(fontSize); } @@ -348,9 +338,7 @@ void JSText::SetMaxFontSize(const JSCallbackInfo& info) return; } CalcDimension fontSize; - if (!ParseJsDimensionFp(info[0], fontSize)) { - return; - } + ParseJsDimensionFp(info[0], fontSize); TextModel::GetInstance()->SetAdaptMaxFontSize(fontSize); } @@ -399,23 +387,18 @@ void JSText::SetDecoration(const JSCallbackInfo& info) JSRef obj = JSRef::Cast(info[0]); JSRef typeValue = obj->GetProperty("type"); JSRef colorValue = obj->GetProperty("color"); - - std::optional textDecoration; + auto pipelineContext = PipelineBase::GetCurrentContext(); + CHECK_NULL_VOID_NOLOG(pipelineContext); + auto theme = pipelineContext->GetTheme(); + CHECK_NULL_VOID_NOLOG(theme); + TextDecoration textDecoration = theme->GetTextStyle().GetTextDecoration(); if (typeValue->IsNumber()) { textDecoration = static_cast(typeValue->ToNumber()); } - std::optional colorVal; - Color result; - if (ParseJsColor(colorValue, result)) { - colorVal = result; - } - - if (textDecoration) { - TextModel::GetInstance()->SetTextDecoration(textDecoration.value()); - } - if (colorVal) { - TextModel::GetInstance()->SetTextDecorationColor(colorVal.value()); - } + Color result = theme->GetTextStyle().GetTextDecorationColor(); + ParseJsColor(colorValue, result); + TextModel::GetInstance()->SetTextDecoration(textDecoration); + TextModel::GetInstance()->SetTextDecorationColor(result); } while (false); info.SetReturnValue(info.This()); } diff --git a/frameworks/bridge/declarative_frontend/jsview/js_textfield.cpp b/frameworks/bridge/declarative_frontend/jsview/js_textfield.cpp index a4ba6a13a10..0899bcbeebb 100644 --- a/frameworks/bridge/declarative_frontend/jsview/js_textfield.cpp +++ b/frameworks/bridge/declarative_frontend/jsview/js_textfield.cpp @@ -194,13 +194,10 @@ void JSTextField::SetPlaceholderColor(const JSCallbackInfo& info) return; } - Color color; - if (!CheckColor(info[0], color, V2::TEXTINPUT_ETS_TAG, "PlaceholderColor")) { - auto theme = GetTheme(); - if (info[0]->IsUndefined() && theme) { - color = theme->GetPlaceholderColor(); - } - } + auto theme = GetTheme(); + CHECK_NULL_VOID(theme); + Color color = theme->GetPlaceholderColor(); + CheckColor(info[0], color, V2::TEXTINPUT_ETS_TAG, "PlaceholderColor"); TextFieldModel::GetInstance()->SetPlaceholderColor(color); } @@ -1008,6 +1005,10 @@ void JSTextField::SetMaxLines(const JSCallbackInfo& info) TextFieldModel::GetInstance()->SetMaxViewLines(MAX_LINES); return; } + if (info[0]->ToNumber() <= 0) { + TextFieldModel::GetInstance()->SetMaxViewLines(MAX_LINES); + return; + } TextFieldModel::GetInstance()->SetMaxViewLines(info[0]->ToNumber()); } diff --git a/frameworks/bridge/declarative_frontend/jsview/js_textpicker.cpp b/frameworks/bridge/declarative_frontend/jsview/js_textpicker.cpp index b63c6c860cf..5683961fd95 100644 --- a/frameworks/bridge/declarative_frontend/jsview/js_textpicker.cpp +++ b/frameworks/bridge/declarative_frontend/jsview/js_textpicker.cpp @@ -722,20 +722,22 @@ bool JSTextPickerParser::ParseIconTextArray( void JSTextPickerParser::ParseTextStyle(const JSRef& paramObj, NG::PickerTextStyle& textStyle) { auto fontColor = paramObj->GetProperty("color"); - auto fontStyle = paramObj->GetProperty("font"); + auto fontOptions = paramObj->GetProperty("font"); Color textColor; if (ParseJsColor(fontColor, textColor)) { textStyle.textColor = textColor; } - if (!fontStyle->IsObject()) { + if (!fontOptions->IsObject()) { LOGE("fontStyle is not obj."); return; } - JSRef fontObj = JSRef::Cast(fontStyle); + JSRef fontObj = JSRef::Cast(fontOptions); auto fontSize = fontObj->GetProperty("size"); auto fontWeight = fontObj->GetProperty("weight"); + auto fontFamily = fontObj->GetProperty("family"); + auto fontStyle = fontObj->GetProperty("style"); if (fontSize->IsNull() || fontSize->IsUndefined()) { textStyle.fontSize = Dimension(-1); } else { @@ -757,6 +759,22 @@ void JSTextPickerParser::ParseTextStyle(const JSRef& paramObj, NG::Pic } textStyle.fontWeight = ConvertStrToFontWeight(weight); } + + if (!fontFamily->IsNull() && !fontFamily->IsUndefined()) { + std::vector families; + if (ParseJsFontFamilies(fontFamily, families)) { + textStyle.fontFamily = families; + } + } + + if (fontStyle->IsNumber()) { + auto style = fontStyle->ToNumber(); + if (style < 0 || style > 1) { + LOGE("Text fontStyle(%d) is invalid value", style); + return; + } + textStyle.fontStyle = static_cast(style); + } } void JSTextPicker::SetDefaultPickerItemHeight(const JSCallbackInfo& info) @@ -1216,7 +1234,6 @@ bool JSTextPickerDialog::ParseShowDataAttribute( const JSRef& paramObject, NG::TextPickerSettingData& settingData) { CalcDimension height; - NG::PickerTextProperties textProperties; auto defaultHeight = paramObject->GetProperty("defaultPickerItemHeight"); if (defaultHeight->IsNumber() || defaultHeight->IsString()) { if (!JSViewAbstract::ParseJsDimensionFp(defaultHeight, height)) { @@ -1224,12 +1241,7 @@ bool JSTextPickerDialog::ParseShowDataAttribute( } } settingData.height = height; - ParseTextProperties(paramObject, textProperties); - if (memcpy_s(&settingData.properties, sizeof(NG::PickerTextProperties), &textProperties, - sizeof(NG::PickerTextProperties)) != EOK) { - LOGE("memcpy properties error."); - return false; - } + ParseTextProperties(paramObject, settingData.properties); return true; } bool JSTextPickerDialog::ParseCanLoop(const JSRef& paramObject, bool& canLoop) diff --git a/frameworks/bridge/declarative_frontend/jsview/js_view_abstract.cpp b/frameworks/bridge/declarative_frontend/jsview/js_view_abstract.cpp index 612828d87da..1bbea791ff7 100755 --- a/frameworks/bridge/declarative_frontend/jsview/js_view_abstract.cpp +++ b/frameworks/bridge/declarative_frontend/jsview/js_view_abstract.cpp @@ -1993,6 +1993,39 @@ void JSViewAbstract::JsBackgroundBlurStyle(const JSCallbackInfo& info) ViewAbstractModel::GetInstance()->SetBackgroundBlurStyle(styleOption); } +void JSViewAbstract::JsBackgroundEffect(const JSCallbackInfo& info) +{ + if (info.Length() == 0) { + LOGW("The arg of backgroundBlurStyle is wrong, it is supposed to have 1 argument"); + return; + } + if (!info[0]->IsObject()) { + LOGW("failed to set background effect."); + return; + } + JSRef jsOption = JSRef::Cast(info[0]); + CalcDimension radius; + if (!ParseJsDimensionVp(jsOption->GetProperty("radius"), radius) || LessNotEqual(radius.Value(), 0.0f)) { + radius.SetValue(0.0f); + } + double saturation = 1.0f; + if (jsOption->GetProperty("saturation")->IsNumber()) { + saturation = jsOption->GetProperty("saturation")->ToNumber(); + saturation = saturation > 0.0f ? saturation : 1.0f; + } + double brightness = 1.0f; + if (jsOption->GetProperty("brightness")->IsNumber()) { + brightness = jsOption->GetProperty("brightness")->ToNumber(); + brightness = brightness > 0.0f ? brightness : 1.0f; + } + Color color = Color::TRANSPARENT; + if (!ParseJsColor(jsOption->GetProperty("color"), color)) { + color.SetValue(Color::TRANSPARENT.GetValue()); + } + EffectOption option = {radius, saturation, brightness, color}; + ViewAbstractModel::GetInstance()->SetBackgroundEffect(option); +} + void JSViewAbstract::JsForegroundBlurStyle(const JSCallbackInfo& info) { if (info.Length() == 0) { @@ -5355,6 +5388,7 @@ void JSViewAbstract::JSBind(BindingTarget globalObj) JSClass::StaticMethod("backgroundImageSize", &JSViewAbstract::JsBackgroundImageSize); JSClass::StaticMethod("backgroundImagePosition", &JSViewAbstract::JsBackgroundImagePosition); JSClass::StaticMethod("backgroundBlurStyle", &JSViewAbstract::JsBackgroundBlurStyle); + JSClass::StaticMethod("backgroundEffect", &JSViewAbstract::JsBackgroundEffect); JSClass::StaticMethod("foregroundBlurStyle", &JSViewAbstract::JsForegroundBlurStyle); JSClass::StaticMethod("lightUpEffect", &JSViewAbstract::JsLightUpEffect); JSClass::StaticMethod("sphericalEffect", &JSViewAbstract::JsSphericalEffect); diff --git a/frameworks/bridge/declarative_frontend/jsview/js_view_abstract.h b/frameworks/bridge/declarative_frontend/jsview/js_view_abstract.h index 2b17c93cb24..bb72674ef64 100644 --- a/frameworks/bridge/declarative_frontend/jsview/js_view_abstract.h +++ b/frameworks/bridge/declarative_frontend/jsview/js_view_abstract.h @@ -87,6 +87,7 @@ public: static void JsBackgroundImageSize(const JSCallbackInfo& info); static void JsBackgroundImagePosition(const JSCallbackInfo& info); static void JsBackgroundBlurStyle(const JSCallbackInfo& info); + static void JsBackgroundEffect(const JSCallbackInfo& info); static void JsForegroundBlurStyle(const JSCallbackInfo& info); static void JsSphericalEffect(const JSCallbackInfo& info); static void JsPixelStretchEffect(const JSCallbackInfo& info); diff --git a/frameworks/bridge/declarative_frontend/jsview/models/picker_model_impl.cpp b/frameworks/bridge/declarative_frontend/jsview/models/picker_model_impl.cpp index e32b0ebacb1..aaed1686481 100644 --- a/frameworks/bridge/declarative_frontend/jsview/models/picker_model_impl.cpp +++ b/frameworks/bridge/declarative_frontend/jsview/models/picker_model_impl.cpp @@ -92,7 +92,8 @@ void DatePickerModelImpl::SetBackgroundColor(const Color& color) void DatePickerDialogModelImpl::SetDatePickerDialogShow(PickerDialogInfo& pickerDialog, NG::DatePickerSettingData& settingData, std::function&& onCancel, - std::function&& onAccept, std::function&& onChange, + std::function&& onAccept, std::function&& onDateAccept, + std::function&& onDateChange, std::function&& onChange, DatePickerType pickerType) { std::string name; diff --git a/frameworks/bridge/declarative_frontend/jsview/models/picker_model_impl.h b/frameworks/bridge/declarative_frontend/jsview/models/picker_model_impl.h index e97ec5e6960..606f07f620b 100644 --- a/frameworks/bridge/declarative_frontend/jsview/models/picker_model_impl.h +++ b/frameworks/bridge/declarative_frontend/jsview/models/picker_model_impl.h @@ -33,6 +33,7 @@ public: void SetSelectedTime(const PickerTime& selectedTime) override; void SetHour24(bool value) override; void SetOnChange(DateChangeEvent&& onChange) override; + void SetOnDateChange(DateChangeEvent&& onChange) override {} void SetDisappearTextStyle(const RefPtr& theme, const NG::PickerTextStyle& value) override {}; void SetNormalTextStyle(const RefPtr& theme, const NG::PickerTextStyle& value) override {}; void SetSelectedTextStyle(const RefPtr& theme, const NG::PickerTextStyle& value) override {}; @@ -44,7 +45,8 @@ class DatePickerDialogModelImpl : public DatePickerDialogModel { public: void SetDatePickerDialogShow(PickerDialogInfo& pickerDialog, NG::DatePickerSettingData& settingData, std::function&& onCancel, std::function&& onAccept, - std::function&& onChange, DatePickerType pickerType) override; + std::function&& onChange, std::function&& onDateAccept, + std::function&& onDateChange, DatePickerType pickerType) override; }; } // namespace OHOS::Ace::Framework #endif // FRAMEWORKS_BRIDGE_DECLARATIVE_FRONTEND_JS_VIEW_MODELS_PICKER_MODEL_IMPL_H diff --git a/frameworks/bridge/declarative_frontend/jsview/window_scene/js_window_scene.cpp b/frameworks/bridge/declarative_frontend/jsview/window_scene/js_window_scene.cpp index 6ddf830346a..843f2df9bca 100644 --- a/frameworks/bridge/declarative_frontend/jsview/window_scene/js_window_scene.cpp +++ b/frameworks/bridge/declarative_frontend/jsview/window_scene/js_window_scene.cpp @@ -44,7 +44,12 @@ void JSWindowScene::Create(const JSCallbackInfo& info) return; } - auto persistentId = static_cast(info[0]->ToNumber()); + double value = info[0]->ToNumber(); + if (value < 0 || value > std::numeric_limits::max()) { + LOGE("input info[0] is beyond the int32_t limit"); + value = 0; + } + auto persistentId = static_cast(value); NG::WindowSceneModel::Create(persistentId); } } // namespace OHOS::Ace::Framework diff --git a/frameworks/bridge/declarative_frontend/ng/declarative_frontend_ng.cpp b/frameworks/bridge/declarative_frontend/ng/declarative_frontend_ng.cpp index 681bca65531..69e8aec7f79 100644 --- a/frameworks/bridge/declarative_frontend/ng/declarative_frontend_ng.cpp +++ b/frameworks/bridge/declarative_frontend/ng/declarative_frontend_ng.cpp @@ -41,6 +41,7 @@ bool DeclarativeFrontendNG::Initialize(FrontendType type, const RefPtr GetEventHandler() override { return nullptr; - }; - - FrontendType GetType() override - { - return type_; } // judge frontend is foreground frontend. @@ -192,11 +187,9 @@ public: private: void InitializeDelegate(const RefPtr& taskExecutor); - FrontendType type_ = FrontendType::DECLARATIVE_JS; RefPtr jsEngine_; RefPtr delegate_; RefPtr accessibilityManager_; - RefPtr taskExecutor_; std::string pageProfile_; bool foregroundFrontend_ = false; diff --git a/frameworks/bridge/declarative_frontend/ng/page_router_manager.cpp b/frameworks/bridge/declarative_frontend/ng/page_router_manager.cpp index 7bf462a596b..45de4eb72f7 100644 --- a/frameworks/bridge/declarative_frontend/ng/page_router_manager.cpp +++ b/frameworks/bridge/declarative_frontend/ng/page_router_manager.cpp @@ -250,7 +250,7 @@ void PageRouterManager::ReplaceNamedRoute(const RouterPageInfo& target) void PageRouterManager::BackWithTarget(const RouterPageInfo& target) { CHECK_RUN_ON(JS); - LOGD("router.Back path = %{private}s", target.url.c_str()); + LOGI("router.Back path = %{private}s", target.url.c_str()); if (inRouterOpt_) { LOGI("in router opt, post back router task"); auto context = PipelineContext::GetCurrentContext(); @@ -351,6 +351,7 @@ void PageRouterManager::StartClean() bool PageRouterManager::Pop() { CHECK_RUN_ON(JS); + LOGI("router pop be called"); if (inRouterOpt_) { LOGE("in router opt, post Pop router task failed"); return false; @@ -646,8 +647,8 @@ void PageRouterManager::PushOhmUrl(const RouterPageInfo& target) CHECK_NULL_VOID(pageUrlChecker); auto taskExecutor = container->GetTaskExecutor(); CHECK_NULL_VOID(taskExecutor); - taskExecutor->PostTask( - [pageUrlChecker, target]() { pageUrlChecker->CheckPreload(target.url); }, TaskExecutor::TaskType::BACKGROUND); + taskExecutor->PostTask([pageUrlChecker, url = target.url]() { pageUrlChecker->CheckPreload(url); }, + TaskExecutor::TaskType::BACKGROUND); } void PageRouterManager::StartPush(const RouterPageInfo& target) @@ -747,8 +748,8 @@ void PageRouterManager::ReplaceOhmUrl(const RouterPageInfo& target) CHECK_NULL_VOID(pageUrlChecker); auto taskExecutor = container->GetTaskExecutor(); CHECK_NULL_VOID(taskExecutor); - taskExecutor->PostTask( - [pageUrlChecker, target]() { pageUrlChecker->CheckPreload(target.url); }, TaskExecutor::TaskType::BACKGROUND); + taskExecutor->PostTask([pageUrlChecker, url = target.url]() { pageUrlChecker->CheckPreload(url); }, + TaskExecutor::TaskType::BACKGROUND); } void PageRouterManager::StartReplace(const RouterPageInfo& target) diff --git a/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/common/state_mgmt_console_trace.ts b/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/common/state_mgmt_console_trace.ts index c8ca55547ac..ae15776bef1 100644 --- a/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/common/state_mgmt_console_trace.ts +++ b/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/common/state_mgmt_console_trace.ts @@ -49,3 +49,31 @@ class stateMgmtTrace { return result; } } + +class errorReport { + public static varValueCheckFailed(params : { customComponent : string, variableDeco: string, variableName: string, expectedType: string, value : T }) : void { + let msg = `@Component '${params.customComponent}': Illegal variable value error with decorated variable ${params.variableDeco} '${params.variableName}': `; + msg += `failed validation: '${params.expectedType}`; + try { + msg += `, attempt to assign value type: '${typeof params.value}'`; + msg += `, value: '${JSON.stringify(params.value, null, 4)}'`; + } catch(e) {} + + msg += "!"; + throw new TypeError(msg); + } + + public static varObservationFailed(params : { customComponent : string, variableDeco: string, variableName: string, value: T }) : void { + let msg = `@Component '${params.customComponent}': decorated variable ${params.variableDeco} '${params.variableName}': `; + msg += `its class is neither decorated with '@Observed' nor it is an instance of 'SubscribableAbstract'`; + + try { + msg += `, attempt to assign value type: '${typeof params.value}'`; + msg += `, value: '${JSON.stringify(params.value, null, 4)}'`; + } catch(e) {} + + msg += "!"; + + throw new TypeError(msg); + } +} \ No newline at end of file diff --git a/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_observed_property_object.ts b/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_observed_property.ts similarity index 86% rename from frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_observed_property_object.ts rename to frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_observed_property.ts index 17668dcb27b..9c79c69386e 100644 --- a/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_observed_property_object.ts +++ b/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_observed_property.ts @@ -24,9 +24,8 @@ * property. */ -class ObservedPropertyObjectPU extends ObservedPropertyObjectAbstractPU - implements PeerChangeEventReceiverPU, - ObservedObjectEventsPUReceiver { +class ObservedPropertyPU extends ObservedPropertyAbstractPU + implements PeerChangeEventReceiverPU, ObservedObjectEventsPUReceiver { private wrappedValue_: T; @@ -42,6 +41,7 @@ class ObservedPropertyObjectPU extends ObservedPropertyObjectA super.aboutToBeDeleted(); } + /** * Called by a SynchedPropertyObjectTwoWayPU (@Link, @Consume) that uses this as sync peer when it has changed * @param eventSource @@ -77,31 +77,28 @@ class ObservedPropertyObjectPU extends ObservedPropertyObjectA } } } - + /* actually update this.wrappedValue_ called needs to do value change check and also notify with this.aboutToChange(); */ private setValueInternal(newValue: T): boolean { - if (newValue == undefined || newValue == null) { - stateMgmtConsole.error(`ObservedPropertyObjectPU[${this.id__()}, '${this.info() || "unknown"}']: constructor @State/@Provide value must not be undefined or null. Application error!`); - // TODO enable support for undefined and null - // unsubscribe old value, set wrappedValue_ to null/undefined - } - if (typeof newValue !== 'object') { - stateMgmtConsole.debug(`ObservedPropertyObject[${this.id__()}, '${this.info() || "unknown"}'] new value is NOT an object. Application error. Ignoring set.`); - return false; - } - if (newValue == this.wrappedValue_) { stateMgmtConsole.debug(`ObservedPropertyObjectPU[${this.id__()}, '${this.info() || "unknown"}'] newValue unchanged`); return false; } - this.unsubscribeWrappedObject(); + if (!this.checkIsSupportedValue(newValue)) { + return false; + } - if (newValue instanceof SubscribableAbstract) { + this.unsubscribeWrappedObject(); + if (!newValue || typeof newValue !== 'object') { + // undefined, null, simple type: + // nothing to subscribe to in case of new value undefined || null || simple type + this.wrappedValue_ = newValue; + } else if (newValue instanceof SubscribableAbstract) { stateMgmtConsole.debug(`ObservedPropertyObjectPU[${this.id__()}, '${this.info() || "unknown"}'] new value is an SubscribableAbstract, subscribiung to it.`); this.wrappedValue_ = newValue; (this.wrappedValue_ as unknown as SubscribableAbstract).addOwningProperty(this); @@ -139,3 +136,12 @@ class ObservedPropertyObjectPU extends ObservedPropertyObjectA } } } + +// class definitions for backward compatibility +class ObservedPropertyObjectPU extends ObservedPropertyPU { + +} + +class ObservedPropertySimplePU extends ObservedPropertyPU { + +} diff --git a/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_observed_property_abstract.ts b/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_observed_property_abstract.ts index 1a70b7aa63d..b13797864ee 100644 --- a/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_observed_property_abstract.ts +++ b/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_observed_property_abstract.ts @@ -174,6 +174,81 @@ implements ISinglePropertyChangeSubscriber, IMultiPropertiesChangeSubscriber, return this.subscriberRefs_.size + (this.owningView_ ? 1 : 0); } + /* + type checking for any supported type, as required for union type support + see 1st parameter for explanation what is allowed + + FIXME this expects the Map, Set patch to go in + */ + + protected checkIsSupportedValue(value: T): boolean { + return this.checkNewValue( + `undefined, null, number, boolean, string, or Object but not function`, + value, + () => ((typeof value == "object" && typeof value != "function") + || typeof value == "number" || typeof value == "string" || typeof value == "boolean") + || (value == undefined || value == null) + ); + } + + /* + type checking for allowed Object type value + see 1st parameter for explanation what is allowed + + FIXME this expects the Map, Set patch to go in + */ + protected checkIsObject(value: T): boolean { + return this.checkNewValue( + `undefined, null, Object including Array and instance of SubscribableAbstract and excluding function, Set, and Map`, + value, + () => (value == undefined || value == null || (typeof value == "object")) + ); + } + + /* + type checking for allowed simple types value + see 1st parameter for explanation what is allowed + */ + protected checkIsSimple(value: T): boolean { + return this.checkNewValue( + `undefined, number, boolean, string`, + value, + () => (value == undefined || typeof value == "number" || typeof value == "string" || typeof value == "boolean") + ); + } + + private static readonly mapDeco = new Map([ + ["ObservedPropertyObjectPU", "@State/@Provide"], + ["ObservedPropertySimplePU", "@State/@Provide (error, should not be used)"], + ["SynchedPropertyObjectOneWayPU", "@Prop"], + ["SynchedPropertySimpleOneWayPU", "@Prop (error, should not be used)"], + ["SynchedPropertyObjectTwoWayPU", "@Link/@Consume"], + ["SynchedPropertySimpleTwoWayPU", "@Link/@Consume (error, should not be used)"], + ["SynchedPropertyNestedObjectPU", "@ObjectLink (only class-objects supported"], + ["SynchedPropertyNesedObjectPU", "@ObjectLink (only class-objects supported"] + ]); + + protected checkNewValue(isAllowedComment : string, newValue: T, validator: (value: T) => boolean) : boolean { + if (validator(newValue)) { + return true; + } + + // report error + // current implementation throws an Exception + errorReport.varValueCheckFailed({ + customComponent: this.owningView_? this.owningView_.constructor.name : "unknown owningView / internal error", + variableDeco: ObservedPropertyAbstractPU.mapDeco.get(this.constructor.name), + variableName: this.info(), + expectedType: isAllowedComment, + value: newValue + }); + + // never gets here if errorReport.varValueCheckFailed throws an exception + // but should nto depend on its implementation + return false; + } + + /** * factory function for concrete 'object' or 'simple' ObservedProperty object * depending if value is Class object diff --git a/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_observed_property_object_abstract.ts b/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_observed_property_object_abstract.ts deleted file mode 100644 index 0c6a253c910..00000000000 --- a/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_observed_property_object_abstract.ts +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * ObservedPropertyObjectAbstractPU - * - * common bbase class of ObservedPropertyObjectPU and - * SyncedObjectPropertyTwoWayPU - * adds the createObjectLink to the ObservedPropertyAbstract base - * - * all definitions in this file are framework internal - */ - -abstract class ObservedPropertyObjectAbstractPU - extends ObservedPropertyAbstractPU { - - constructor(owningView: IPropertySubscriber, thisPropertyName: PropertyInfo) { - super(owningView, thisPropertyName) - } -} diff --git a/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_observed_property_simple.ts b/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_observed_property_simple.ts deleted file mode 100644 index 8116b74cbc3..00000000000 --- a/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_observed_property_simple.ts +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * ObservedPropertySimplePU - * implementation of @State and @Provide decorated variables of types (T=) boolean | number | string | enum - * - * Holds an actual property value of type T - * uses its base class to manage subscribers to this - * property. - * - * all definitions in this file are framework internal -*/ -class ObservedPropertySimplePU extends ObservedPropertySimpleAbstractPU - implements ISinglePropertyChangeSubscriber, PeerChangeEventReceiverPU { - - private wrappedValue_: T; - - constructor(localInitValue: T, owningView: IPropertySubscriber, propertyName: PropertyInfo) { - super(owningView, propertyName); - - // TODO undefined and null support remove this if statement - if (typeof localInitValue === "object") { - throw new SyntaxError("ObservedPropertySimple constructor: @State/@Provide value must not be an object")! - } - - this.setValueInternal(localInitValue); - } - - aboutToBeDeleted(unsubscribeMe?: IPropertySubscriber) { - this.removeSubscriber(unsubscribeMe); - super.aboutToBeDeleted(); - } - - /** - * Called by a @Link - SynchedPropertySimpleTwoWay that uses this as sync peer when it has changed - * @param eventSource - */ - syncPeerHasChanged(eventSource: ObservedPropertyAbstractPU) { - stateMgmtConsole.debug(`ObservedPropertySimple[${this.id__()}, '${this.info() || "unknown"}']: syncPeerHasChanged peer '${eventSource.info()}'.`); - this.notifyPropertyHasChangedPU(); - } - - /* - actually update this.wrappedValue_ - called needs to do value change check - and also notify with this.aboutToChange(); - */ - private setValueInternal(newValue: T): boolean { - stateMgmtConsole.debug(`ObservedPropertySimplePU[${this.id__()}, '${this.info() || "unknown"}'] set new value`); - if (this.wrappedValue_ != newValue) { - this.wrappedValue_ = newValue; - return true; - } - return false; - } - - public getUnmonitored(): T { - stateMgmtConsole.debug(`ObservedPropertySimple[${this.id__()}, '${this.info() || "unknown"}']: getUnmonitored.`); - // unmonitored get access , no call to notifyPropertyRead ! - return this.wrappedValue_; - } - - public get(): T { - stateMgmtConsole.debug(`ObservedPropertySimple[${this.id__()}, '${this.info() || "unknown"}']: get.`); - this.notifyPropertyHasBeenReadPU() - return this.wrappedValue_; - } - - public set(newValue: T): void { - if (this.wrappedValue_ == newValue) { - stateMgmtConsole.debug(`ObservedPropertySimple[${this.id__()}, '${this.info() || "unknown"}']: set with unchanged value - ignoring.`); - return; - } - stateMgmtConsole.debug(`ObservedPropertySimple[${this.id__()}, '${this.info() || "unknown"}']: set changed value.`); - if (this.setValueInternal(newValue)) { - this.notifyPropertyHasChangedPU(); - } - } -} diff --git a/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_synced_property_object_nested.ts b/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_synced_property_object_nested.ts index 6dc8626a3b6..761844d53a2 100644 --- a/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_synced_property_object_nested.ts +++ b/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_synced_property_object_nested.ts @@ -21,7 +21,7 @@ * */ class SynchedPropertyNestedObjectPU - extends ObservedPropertyObjectAbstractPU + extends ObservedPropertyAbstractPU implements ObservedObjectEventsPUReceiver { private obsObject_: C; @@ -39,7 +39,6 @@ class SynchedPropertyNestedObjectPU owningChildView: IPropertySubscriber, propertyName: PropertyInfo) { super(owningChildView, propertyName); this.obsObject_ = obsObject; - this.setValueInternal(obsObject); } @@ -87,14 +86,19 @@ class SynchedPropertyNestedObjectPU } stateMgmtConsole.debug(`SynchedPropertyNestedObjectPU[${this.id__()}, '${this.info() || "unknown"}']: set: @ObjectLink set to new value: .`); - this.setValueInternal(newValue); - // notify value change to subscribing View - this.notifyPropertyHasChangedPU(); + if (this.setValueInternal(newValue)) { + // notify value change to subscribing View + this.notifyPropertyHasChangedPU(); + } } - private setValueInternal(newValue: C): void { + private setValueInternal(newValue: C): boolean { + if (!this.checkIsObject(newValue)) { + return false; + } + if (this.obsObject_ != undefined) { if (this.obsObject_ instanceof SubscribableAbstract) { // unregister from SubscribableAbstract object @@ -119,6 +123,7 @@ class SynchedPropertyNestedObjectPU value changes will bot be observed and UI will not update. forgot @Observed class decorator? Application error.`); } } + return true; } } diff --git a/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_synced_property_object_one_way.ts b/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_synced_property_one_way.ts similarity index 80% rename from frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_synced_property_object_one_way.ts rename to frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_synced_property_one_way.ts index f78727c72f7..1205aaa59cb 100644 --- a/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_synced_property_object_one_way.ts +++ b/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_synced_property_one_way.ts @@ -45,32 +45,31 @@ * * 1- assignment of a new Object value: this.aProp = new ClassA() * rhs can be ObservedObject because of @Observed decoration or now - * notifyPropertryHasChangedPU + * notifyPropertyHasChangedPU * * 2- local ObservedObject member property change * objectPropertyHasChangedPU called, eventSource is the ObservedObject stored in localCopyObservedObject_ - * no need to copy, notifyPropertryHasChangedPU + * no need to copy, notifyPropertyHasChangedPU * * 3- Rerender of the custom component triggered from the parent * reset() is called (code generated by the transpiler), set the value of source_ , if that causes a change will call syncPeerHasChanged * syncPeerHasChanged need to deep copy the ObservedObject from source to localCopyObservedObject_ - * notifyPropertryHasChangedPU + * notifyPropertyHasChangedPU * * 4- source_ ObservedObject member property change * objectPropertyHasChangedPU called, eventSource is the ObservedObject stored source_.getUnmonitored - * notifyPropertryHasChangedPU + * notifyPropertyHasChangedPU */ -class SynchedPropertyObjectOneWayPU - extends ObservedPropertyObjectAbstractPU - implements PeerChangeEventReceiverPU, - ObservedObjectEventsPUReceiver { + + +class SynchedPropertyOneWayPU extends ObservedPropertyAbstractPU + implements PeerChangeEventReceiverPU, ObservedObjectEventsPUReceiver { // the locally modified ObservedObject private localCopyObservedObject_: C; // reference to the source variable in parent component private source_: ObservedPropertyAbstract; - // true for @Prop code path, // false for @(Local)StorageProp private sourceIsOwnObject : boolean; @@ -88,16 +87,19 @@ class SynchedPropertyObjectOneWayPU // subscribe to receive value change updates from LocalStorage source property this.source_.addSubscriber(this); } else { - // code path for - // 1- source is of same type C in parent, source is its value, not the backing store ObservedPropertyObject - // 2- nested Object/Array inside observed another object/array in parent, source is its value - if (!((source instanceof SubscribableAbstract) || ObservedObject.IsObservedObject(source))) { - stateMgmtConsole.warn(`@Prop ${this.info()} Provided source object's class - lacks @Observed class decorator. Object property changes will not be observed.`); + const sourceValue = source as C; + if (this.checkIsSupportedValue(sourceValue)) { + // code path for + // 1- source is of same type C in parent, source is its value, not the backing store ObservedPropertyObject + // 2- nested Object/Array inside observed another object/array in parent, source is its value + if (!((sourceValue instanceof SubscribableAbstract) || ObservedObject.IsObservedObject(sourceValue))) { + stateMgmtConsole.warn(`@Prop ${this.info()} Provided source object's class is not instance of SubscribableAbstract, + it also lacks @Observed class decorator. Object property changes will not be observed.`); + } + stateMgmtConsole.debug(`SynchedPropertyObjectOneWayPU[${this.id__()}, '${this.info() || "unknown"}']: constructor @Prop wrapping source in a new ObservedPropertyObjectPU`); + this.source_ = new ObservedPropertyObjectPU(sourceValue, this, this.getSourceObservedPropertyFakeName()); + this.sourceIsOwnObject = true; } - stateMgmtConsole.debug(`SynchedPropertyObjectOneWayPU[${this.id__()}, '${this.info() || "unknown"}']: constructor @Prop wrapping source in a new ObservedPropertyObjectPU`); - this.source_ = new ObservedPropertyObjectPU(source as C, this, this.getSourceObservedPropertyFakeName()); - this.sourceIsOwnObject = true; } if (this.source_ != undefined) { @@ -106,6 +108,7 @@ class SynchedPropertyObjectOneWayPU stateMgmtConsole.debug(`SynchedPropertyObjectOneWayPU[${this.id__()}, '${this.info() || "unknown"}']: constructor ready with local copy.`); } + /* like a destructor, need to call this before deleting the property. @@ -128,18 +131,25 @@ class SynchedPropertyObjectOneWayPU } public syncPeerHasChanged(eventSource: ObservedPropertyAbstractPU) { + + if (this.source_ == undefined) { + stateMgmtConsole.error(`SynchedPropertyObjectOneWayPU[${this.id__()}, '${this.info() || "unknown"}']: \ + @Prop syncPeerHasChanged peer '${eventSource ? eventSource.info() : "no eventSource info"}' but source_ undefned. Internal error.`); + return; + } + if (eventSource && this.source_ == eventSource) { // defensive programming: should always be the case! stateMgmtConsole.debug(`SynchedPropertyObjectOneWayPU[${this.id__()}]: syncPeerHasChanged(): Source '${eventSource.info()}' has changed'.`) const newValue = this.source_.getUnmonitored(); - if (typeof newValue == "object") { + if (this.checkIsSupportedValue(newValue)) { stateMgmtConsole.debug(`SynchedPropertyObjectOneWayPU[${this.id__()}, '${this.info() || "unknown"}']: hasChanged: newValue '${JSON.stringify(newValue)}'.`); if (this.resetLocalValue(newValue, /* needCopyObject */ true)) { this.notifyPropertyHasChangedPU(); } } } else { - stateMgmtConsole.warn(`SynchedPropertyObjectOneWayPU[${this.id__()}]: syncPeerHasChanged Unexpected situation. Ignoring event.`) + stateMgmtConsole.warn(`SynchedPropertyObjectOneWayPU[${this.id__()}]: syncPeerHasChanged Unexpected situation. syncPeerHasChanged from different sender than source_. Ignoring event.`) } } @@ -180,11 +190,6 @@ class SynchedPropertyObjectOneWayPU } stateMgmtConsole.debug(`SynchedPropertyObjectOneWayPU[${this.id__()}, '${this.info() || "unknown"}']: set to newV value.`); - if (!ObservedObject.IsObservedObject(newValue)) { - stateMgmtConsole.warn(`@Prop ${this.info()} Set: Provided new object's class - lacks '@Observed' class decorator. Object property changes will not be observed.`); - } - if (this.resetLocalValue(newValue, /* needCopyObject */ false)) { this.notifyPropertyHasChangedPU(); } @@ -193,11 +198,9 @@ class SynchedPropertyObjectOneWayPU // called when updated from parent public reset(sourceChangedValue: C): void { stateMgmtConsole.debug(`SynchedPropertyObjectOneWayPU[${this.id__()}, '${this.info() || "unknown"}']: reset.`); - if (this.source_ !== undefined) { + if (this.source_ !== undefined && this.checkIsSupportedValue(sourceChangedValue)) { // if this.source_.set causes an actual change, then, ObservedPropertyObject source_ will call syncPeerHasChanged method this.source_.set(sourceChangedValue); - } else { - stateMgmtConsole.error(`SynchedPropertyObjectOneWayPU[${this.id__()}, '${this.info() || "unknown"}']: reset @Prop --- No source_. Internal error!`); } } @@ -212,11 +215,9 @@ class SynchedPropertyObjectOneWayPU // note: We can not test for newObservedObjectValue == this.localCopyObservedObject_ // here because the object might still be the same, but some property of it has changed - if (typeof newObservedObjectValue !== "object") { - // if not undefined or null, then the provided newObservedObjectValue must be an Object - stateMgmtConsole.error(`SynchedPropertyOneWayObjectPU[${this.id__()}]: setLocalValue new value must be an Object.`) + if(!this.checkIsSupportedValue(newObservedObjectValue)) { + return; } - // unsubscribe from old local copy if (this.localCopyObservedObject_ instanceof SubscribableAbstract) { (this.localCopyObservedObject_ as SubscribableAbstract).removeOwningProperty(this); @@ -227,23 +228,23 @@ class SynchedPropertyObjectOneWayPU // shallow/deep copy value // needed whenever newObservedObjectValue comes from source // not needed on a local set (aka when called from set() method) - let copy = needCopyObject ? this.copyObject(newObservedObjectValue, this.info_) : newObservedObjectValue; + this.localCopyObservedObject_ = needCopyObject ? this.copyObject(newObservedObjectValue, this.info_) : newObservedObjectValue; - if (copy instanceof SubscribableAbstract) { - this.localCopyObservedObject_ = copy; - // deep copy will copy Set of subscribers as well. But local copy only has its own subscribers - // not those of its parent value. - (this.localCopyObservedObject_ as unknown as SubscribableAbstract).clearOwningProperties(); - (this.localCopyObservedObject_ as unknown as SubscribableAbstract).addOwningProperty(this); - } else if (ObservedObject.IsObservedObject(copy)) { - // case: new ObservedObject - this.localCopyObservedObject_ = copy; - ObservedObject.addOwningProperty(this.localCopyObservedObject_, this); - } else { - // wrap newObservedObjectValue raw object as ObservedObject and subscribe to it - stateMgmtConsole.warn(`@Prop ${this.info()} Provided source object's class \ + if (typeof this.localCopyObservedObject_ == "object") { + if (this.localCopyObservedObject_ instanceof SubscribableAbstract) { + // deep copy will copy Set of subscribers as well. But local copy only has its own subscribers + // not those of its parent value. + (this.localCopyObservedObject_ as unknown as SubscribableAbstract).clearOwningProperties(); + (this.localCopyObservedObject_ as unknown as SubscribableAbstract).addOwningProperty(this); + } else if (ObservedObject.IsObservedObject(this.localCopyObservedObject_)) { + // case: new ObservedObject + ObservedObject.addOwningProperty(this.localCopyObservedObject_, this); + } else { + // wrap newObservedObjectValue raw object as ObservedObject and subscribe to it + stateMgmtConsole.error(`@Prop ${this.info()} Provided source object's class \ lacks @Observed class decorator. Object property changes will not be observed.`); - this.localCopyObservedObject_ = ObservedObject.createNew(copy, this); + this.localCopyObservedObject_ = ObservedObject.createNew(this.localCopyObservedObject_, this); + } } return true; } @@ -263,14 +264,14 @@ class SynchedPropertyObjectOneWayPU } // API 9 code path - private shallowCopyObject(value: C, propName: string) : C { + private shallowCopyObject(value: C, propName: string): C { let rawValue = ObservedObject.GetRawObject(value); let copy: C; - if (rawValue == undefined || rawValue == null) { + if (!rawValue || typeof rawValue !== 'object') { copy = rawValue; } else if (typeof rawValue != "object") { - // TODO would it be better to crash the app here? + // FIXME would it be better to throw Exception here? stateMgmtConsole.error(`@Prop ${this.info()} shallowCopyObject: request to copy non-object but defined value of type '${typeof rawValue}'. Internal error! Setting copy=original value.`); copy = rawValue; } else if (rawValue instanceof Array) { @@ -379,3 +380,12 @@ class SynchedPropertyObjectOneWayPU } } } + +// class definitions for backward compatibility +class SynchedPropertySimpleOneWayPU extends SynchedPropertyOneWayPU { + +} + +class SynchedPropertyObjectOneWayPU extends SynchedPropertyOneWayPU { + +} diff --git a/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_synced_property_simple_one_way.ts b/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_synced_property_simple_one_way.ts deleted file mode 100644 index 5ddab9a2162..00000000000 --- a/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_synced_property_simple_one_way.ts +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * SynchedPropertySimpleOneWayPU - * implementation of @Prop decorated variable of types boolean | number | string | enum - * - * all definitions in this file are framework internal - */ - -class SynchedPropertySimpleOneWayPU extends ObservedPropertySimpleAbstractPU - implements PeerChangeEventReceiverPU { - - private wrappedValue_: T; - private source_: ObservedPropertyAbstract; - - // true for @Prop code path, - // false for @(Local)StorageProp - private sourceIsOwnObject: boolean; - - constructor(source: ObservedPropertyAbstract | T, subscribeMe?: IPropertySubscriber, thisPropertyName?: PropertyInfo) { - super(subscribeMe, thisPropertyName); - - // Check that source is ObservedPropertyAbstruct - if (source && (typeof (source) === "object") && ("notifyHasChanged" in source) && ("subscribeMe" in source)) { - // code path for @(Local)StorageProp - this.source_ = source; - this.sourceIsOwnObject = false; - this.source_.addSubscriber(this); - // subscribe to receive value change updates from LocalStorage source property - } else { - // code path for @Prop - this.source_ = new ObservedPropertySimplePU(source as T, this, thisPropertyName); - this.sourceIsOwnObject = true; - } - - // use own backing store for value to avoid - // value changes to be propagated back to source - this.wrappedValue_ = this.source_.getUnmonitored(); - } - - /* - like a destructor, need to call this before deleting - the property. - */ - aboutToBeDeleted() { - if (this.source_) { - this.source_.removeSubscriber(this); - if (this.sourceIsOwnObject == true && this.source_.numberOfSubscrbers()==0){ - stateMgmtConsole.debug(`SynchedPropertySimpleOneWayPU[${this.id__()}, '${this.info() || "unknown"}']: aboutToBeDeleted. owning source_ ObservedPropertySimplePU, calling its aboutToBeDeleted`); - this.source_.aboutToBeDeleted(); - } - this.source_ = undefined; - this.sourceIsOwnObject= false; - } - super.aboutToBeDeleted(); - } - - public syncPeerHasChanged(eventSource: ObservedPropertyAbstractPU) { - if (eventSource && (eventSource == this.source_)) { - // defensive, should always be the case - stateMgmtConsole.debug(`SynchedPropertySimpleOneWayPU[${this.id__()}, '${this.info() || "unknown"}']: \ - syncPeerHasChanged peer '${eventSource.info()}'.`); - this.setWrappedValue(eventSource.getUnmonitored()); - this.notifyPropertyHasChangedPU(); - } - } - - public getUnmonitored(): T { - stateMgmtConsole.debug(`SynchedPropertySimpleOneWayPU[${this.id__()}, '${this.info() || "unknown"}']: getUnmonitored.`); - // unmonitored get access, no call to notifyPropertyRead ! - return this.wrappedValue_; - } - - // get 'read through` from the ObservedProperty - public get(): T { - stateMgmtConsole.debug(`SynchedPropertySimpleOneWayPU[${this.id__()}, '${this.info() || "unknown"}']: get returns '${this.wrappedValue_}'`); - this.notifyPropertyHasBeenReadPU() - return this.wrappedValue_; - } - - public set(newValue: T): void { - if (this.wrappedValue_ == newValue) { - stateMgmtConsole.debug(`SynchedPropertySimpleOneWayPU[${this.id__()}, '${this.info() || "unknown"}']: set with unchanged value '${this.wrappedValue_}'- ignoring.`); - return; - } - - stateMgmtConsole.debug(`SynchedPropertySimpleOneWayPU[${this.id__()}, '${this.info() || "unknown"}']: set from '${this.wrappedValue_} to '${newValue}'.`); - this.setWrappedValue(newValue); - this.notifyPropertyHasChangedPU(); - } - - public reset(sourceChangedValue: T): void { - stateMgmtConsole.debug(`SynchedPropertySimpleOneWayPU[${this.id__()}, '${this.info() || "unknown"}']: reset from '${this.wrappedValue_} to '${sourceChangedValue}'.`); - // if set causes an actual change, then, ObservedPropertySimple source_ will call hasChanged - if (this.source_ !== undefined) { - // if set causes an actual change, then, ObservedPropertySimple source_ will call hasChanged - this.source_.set(sourceChangedValue); - } - } - - private setWrappedValue(newValue: T): void { - this.wrappedValue_ = newValue; - } -} - diff --git a/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_synced_property_simple_two_way.ts b/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_synced_property_simple_two_way.ts deleted file mode 100644 index 0c284019dea..00000000000 --- a/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_synced_property_simple_two_way.ts +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * SynchedPropertySimpleTwoWayPU - * implementation of @Link and @Consume decorated variables of types boolean | number | string | enum - * - * all definitions in this file are framework internal - */ - -class SynchedPropertySimpleTwoWayPU extends ObservedPropertySimpleAbstractPU - implements PeerChangeEventReceiverPU { - - private source_: ObservedPropertyAbstract; - private changeNotificationIsOngoing_: boolean = false; - - constructor(source: ObservedPropertyAbstract, owningView: IPropertySubscriber, owningViewPropNme: PropertyInfo) { - super(owningView, owningViewPropNme); - this.source_ = source; - if (this.source_) { - this.source_.addSubscriber(this); - } else { - stateMgmtConsole.error(`SynchedPropertySimpleTwoWayPU[${this.id__()}, '${this.info() || "unknown"}']: constructor @Link/@Consume source must not be undefined. Application error!`); - } - } - - /* - like a destructor, need to call this before deleting - the property. -*/ - aboutToBeDeleted() { - if (this.source_) { - this.source_.removeSubscriber(this); - this.source_ = undefined; - } - super.aboutToBeDeleted(); - } - - /** - * Called when sync peer ObservedPropertySimple or SynchedPropertySimpletTwoWay has chnaged value - * that peer can be in either parent or child component if 'this' is used for a @Link - * that peer can be in either acestor or descendant component if 'this' is used for a @Consume - * @param eventSource - */ - syncPeerHasChanged(eventSource : ObservedPropertyAbstractPU) { - if (!this.changeNotificationIsOngoing_) { - stateMgmtConsole.debug(`SynchedPropertySimpleTwoWayPU[${this.id__()}, '${this.info() || "unknown"}']: propertyHasChangedPU, property ${eventSource.info()}`); - this.notifyPropertyHasChangedPU(); - } - } - - public getUnmonitored(): T { - stateMgmtConsole.debug(`SynchedPropertySimpleTwoWayPU[${this.id__()}, '${this.info() || "unknown"}']: getUnmonitored`); - return (this.source_ ? this.source_.getUnmonitored() : undefined); - } - - // get 'read through` from the ObservedProperty - public get(): T { - stateMgmtConsole.debug(`SynchedPropertySimpleTwoWayPU[${this.id__()}, '${this.info() || "unknown"}']: get`); - this.notifyPropertyHasBeenReadPU() - return this.getUnmonitored(); - } - - // set 'writes through` to the ObservedProperty - public set(newValue: T): void { - if (!this.source_) { - stateMgmtConsole.debug(`SynchedPropertySimpleTwoWayPU[${this.id__()}IP, '${this.info() || "unknown"}']: set, no source, returning.`); - return; - } - - if (this.source_.get() == newValue) { - stateMgmtConsole.debug(`SynchedPropertySimpleTwoWayPU[${this.id__()}IP, '${this.info() || "unknown"}']: set with unchanged value '${newValue}'- ignoring.`); - return; - } - - stateMgmtConsole.debug(`SynchedPropertySimpleTwoWayPU[${this.id__()}IP, '${this.info() || "unknown"}']: set to newValue: '${newValue}'.`); - - // avoid circular notifications @Link -> source @State -> other but also to same @Link - this.changeNotificationIsOngoing_ = true; - - // the source_ ObservedProeprty will call: this.hasChanged(newValue); - this.source_.set(newValue); - this.notifyPropertyHasChangedPU(); - - this.changeNotificationIsOngoing_ = false; - } -} diff --git a/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_synced_property_object_two_way.ts b/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_synced_property_two_way.ts similarity index 73% rename from frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_synced_property_object_two_way.ts rename to frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_synced_property_two_way.ts index 46eb1b0fafe..810b0629628 100644 --- a/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_synced_property_object_two_way.ts +++ b/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_synced_property_two_way.ts @@ -18,11 +18,10 @@ * implementation of @Link and @Consume decorated variables of type class object * * all definitions in this file are framework internal - */ -class SynchedPropertyObjectTwoWayPU - extends ObservedPropertyObjectAbstractPU - implements PeerChangeEventReceiverPU, - ObservedObjectEventsPUReceiver { +*/ + +class SynchedPropertyTwoWayPU extends ObservedPropertyAbstractPU + implements PeerChangeEventReceiverPU, ObservedObjectEventsPUReceiver { private source_: ObservedPropertyObjectAbstract; private changeNotificationIsOngoing_: boolean = false; @@ -38,7 +37,7 @@ class SynchedPropertyObjectTwoWayPU // register to the ObservedObject ObservedObject.addOwningProperty(this.source_.get(), this); } else { - stateMgmtConsole.error(`SynchedPropertyObjectTwoWayPU[${this.id__()}, '${this.info() || "unknown"}']: constructor @Link/@Consume source must not be undefined. Application error!`); + throw new SyntaxError(`SynchedPropertyObjectTwoWayPU[${this.id__()}, '${this.info() || "unknown"}']: constructor @Link/@Consume source variable in parent/ancestor @ Component must be defined. Application error!`); } } @@ -63,25 +62,31 @@ class SynchedPropertyObjectTwoWayPU private setObject(newValue: C): void { if (!this.source_) { - stateMgmtConsole.warn(`SynchedPropertyObjectTwoWayPU[${this.id__()}, '${this.info() || "unknown"}']: setObject (assign a new value), @Link/@Consume: no linked parent property. Likely a consequence of earlier application error.`); - return; + throw new SyntaxError(`SynchedPropertyObjectTwoWayPU[${this.id__()}, '${this.info() || "unknown"}']: setObject (assign a new value), \ + @Link/@Consume: no source variable in parent/ancestor @Component. Application error.`); } - let oldValueObject = this.getUnmonitored(); - if (oldValueObject != undefined && oldValueObject != null) { - ObservedObject.removeOwningProperty(oldValueObject, this); + if (this.getUnmonitored() == newValue) { + stateMgmtConsole.debug(`SynchedPropertyObjectTwoWayPU[${this.id__()}IP, '${this.info() || "unknown"}']: set with unchanged value - ignoring.`); + return; } + + stateMgmtConsole.debug(`SynchedPropertyObjectTwoWayPU[${this.id__()}IP, '${this.info() || "unknown"}']: set.`); + + if (this.checkIsSupportedValue(newValue)) { + // the source_ ObservedProperty will call: this.syncPeerHasChanged(newValue); this.source_.set(newValue) - ObservedObject.addOwningProperty(this.getUnmonitored(), this); + } } + /** - * Called when sync peer ObservedPropertyObject or SynchedPropertyObjectTwoWay has chnaged value + * Called when sync peer ObservedPropertyObject or SynchedPropertyObjectTwoWay has changed value * that peer can be in either parent or child component if 'this' is used for a @Link - * that peer can be in either acestor or descendant component if 'this' is used for a @Consume + * that peer can be in either ancestor or descendant component if 'this' is used for a @Consume * @param eventSource */ - syncPeerHasChanged(eventSource : ObservedPropertyAbstractPU) { + syncPeerHasChanged(eventSource: ObservedPropertyAbstractPU) { if (!this.changeNotificationIsOngoing_) { stateMgmtConsole.debug(`SynchedPropertyObjectTwoWayPU[${this.id__()}, '${this.info() || "unknown"}']: propertyHasChangedPU: contained ObservedObject '${eventSource.info()}' hasChanged'.`) this.notifyPropertyHasChangedPU(); @@ -93,13 +98,13 @@ class SynchedPropertyObjectTwoWayPU * @param souceObject * @param changedPropertyName */ - public objectPropertyHasChangedPU(souceObject: ObservedObject, changedPropertyName : string) { + public objectPropertyHasChangedPU(sourceObject: ObservedObject, changedPropertyName : string) { stateMgmtConsole.debug(`SynchedPropertyObjectTwoWayPU[${this.id__()}, '${this.info() || "unknown"}']: \ objectPropertyHasChangedPU: contained ObservedObject property '${changedPropertyName}' has changed.`) this.notifyPropertyHasChangedPU(); } - public objectPropertyHasBeenReadPU(souceObject: ObservedObject, changedPropertyName : string) { + public objectPropertyHasBeenReadPU(sourceObject: ObservedObject, changedPropertyName : string) { stateMgmtConsole.debug(`SynchedPropertyObjectTwoWayPU[${this.id__()}, '${this.info() || "unknown"}']: \ objectPropertyHasBeenReadPU: contained ObservedObject property '${changedPropertyName}' has been read.`); this.notifyPropertyHasBeenReadPU(); @@ -134,3 +139,13 @@ class SynchedPropertyObjectTwoWayPU this.changeNotificationIsOngoing_ = false; } } + +// class definitions for backward compatibility +class SynchedPropertyObjectTwoWayPU extends SynchedPropertyTwoWayPU { + +} + +class SynchedPropertySimpleTwoWayPU extends SynchedPropertyTwoWayPU { + +} + diff --git a/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_view.ts b/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_view.ts index 3f7e1744996..61a31c0064e 100644 --- a/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_view.ts +++ b/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_view.ts @@ -500,31 +500,35 @@ abstract class ViewPU extends NativeViewPartialUpdate /** * Method for the sub-class to call from its constructor for resolving * a @Consume variable and initializing its backing store - * with the yncedPropertyTwoWay object created from the + * with the SyncedPropertyTwoWay object created from the * @Provide variable's backing store. * @param providedPropName the name of the @Provide'd variable. - * This is either the @Consume decortor parameter, or variable name. + * This is either the @Consume decorator parameter, or variable name. * @param consumeVarName the @Consume variable name (not the - * @Consume decortor parameter) - * @returns initiaizing value of the @Consume backing store + * @Consume decorator parameter) + * @returns initializing value of the @Consume backing store */ protected initializeConsume(providedPropName: string, consumeVarName: string): ObservedPropertyAbstractPU { - let providedVarStore = this.providedVars_.get(providedPropName); + let providedVarStore : ObservedPropertyAbstractPU = this.providedVars_.get(providedPropName); if (providedVarStore === undefined) { throw new ReferenceError(`${this.constructor.name}: missing @Provide property with name ${providedPropName}. - Fail to resolve @Consume(${providedPropName}).`); + Fail to resolve @Consume(${providedPropName}).`); } - return providedVarStore.createSync( - (source: ObservedPropertyAbstract) => (source instanceof ObservedPropertySimple) - ? new SynchedPropertySimpleTwoWayPU(source, this, consumeVarName) - : new SynchedPropertyObjectTwoWayPU(source, this, consumeVarName)) as ObservedPropertyAbstractPU; + const factory = (source: ObservedPropertyAbstract) => { + const result : ObservedPropertyAbstractPU = ((source instanceof ObservedPropertySimple) || (source instanceof ObservedPropertySimplePU)) + ? new SynchedPropertyObjectTwoWayPU(source, this, consumeVarName) + : new SynchedPropertyObjectTwoWayPU(source, this, consumeVarName); + stateMgmtConsole.error(`The @Consume is instance of ${result.constructor.name}`); + return result; + }; + return providedVarStore.createSync(factory) as ObservedPropertyAbstractPU; } /** - * given the elmtid of a child or child of child within this custom component + * given the elmtId of a child or child of child within this custom component * remember this component needs a partial update * @param elmtId */ @@ -793,7 +797,7 @@ abstract class ViewPU extends NativeViewPartialUpdate (source: ObservedPropertyAbstract) => (source === undefined) ? undefined : (source instanceof ObservedPropertySimple) - ? new SynchedPropertySimpleTwoWayPU(source, this, viewVariableName) + ? new SynchedPropertyObjectTwoWayPU(source, this, viewVariableName) : new SynchedPropertyObjectTwoWayPU(source, this, viewVariableName) ) as ObservedPropertyAbstractPU; this.ownStorageLinksProps_.add(appStorageLink); @@ -805,7 +809,7 @@ abstract class ViewPU extends NativeViewPartialUpdate (source: ObservedPropertyAbstract) => (source === undefined) ? undefined : (source instanceof ObservedPropertySimple) - ? new SynchedPropertySimpleOneWayPU(source, this, viewVariableName) + ? new SynchedPropertyObjectOneWayPU(source, this, viewVariableName) : new SynchedPropertyObjectOneWayPU(source, this, viewVariableName) ) as ObservedPropertyAbstractPU; this.ownStorageLinksProps_.add(appStorageProp); @@ -818,7 +822,7 @@ abstract class ViewPU extends NativeViewPartialUpdate (source: ObservedPropertyAbstract) => (source === undefined) ? undefined : (source instanceof ObservedPropertySimple) - ? new SynchedPropertySimpleTwoWayPU(source, this, viewVariableName) + ? new SynchedPropertyObjectTwoWayPU(source, this, viewVariableName) : new SynchedPropertyObjectTwoWayPU(source, this, viewVariableName) ) as ObservedPropertyAbstractPU; this.ownStorageLinksProps_.add(localStorageLink); @@ -831,7 +835,7 @@ abstract class ViewPU extends NativeViewPartialUpdate (source: ObservedPropertyAbstract) => (source === undefined) ? undefined : (source instanceof ObservedPropertySimple) - ? new SynchedPropertySimpleOneWayPU(source, this, viewVariableName) + ? new SynchedPropertyObjectOneWayPU(source, this, viewVariableName) : new SynchedPropertyObjectOneWayPU(source, this, viewVariableName) ) as ObservedPropertyAbstractPU; this.ownStorageLinksProps_.add(localStorageProp); diff --git a/frameworks/bridge/declarative_frontend/state_mgmt/tsconfig.json b/frameworks/bridge/declarative_frontend/state_mgmt/tsconfig.json index b89771ee59b..4c64a5b9851 100644 --- a/frameworks/bridge/declarative_frontend/state_mgmt/tsconfig.json +++ b/frameworks/bridge/declarative_frontend/state_mgmt/tsconfig.json @@ -50,14 +50,9 @@ "src/lib/partial_update/pu_foreach.d.ts", "src/lib/partial_update/pu_view_native.d.ts", "src/lib/partial_update/pu_observed_property_abstract.ts", - "src/lib/partial_update/pu_observed_property_object_abstract.ts", - "src/lib/partial_update/pu_observed_property_simple_abstract.ts", - "src/lib/partial_update/pu_observed_property_object.ts", - "src/lib/partial_update/pu_observed_property_simple.ts", - "src/lib/partial_update/pu_synced_property_object_one_way.ts", - "src/lib/partial_update/pu_synced_property_object_two_way.ts", - "src/lib/partial_update/pu_synced_property_simple_one_way.ts", - "src/lib/partial_update/pu_synced_property_simple_two_way.ts", + "src/lib/partial_update/pu_observed_property.ts", + "src/lib/partial_update/pu_synced_property_one_way.ts", + "src/lib/partial_update/pu_synced_property_two_way.ts", "src/lib/partial_update/pu_synced_property_object_nested.ts", "src/lib/partial_update/pu_view.ts", "src/lib/partial_update/pu_recycle_manager.ts", diff --git a/frameworks/bridge/declarative_frontend/state_mgmt/tsconfig.release.json b/frameworks/bridge/declarative_frontend/state_mgmt/tsconfig.release.json index 6be7085b55b..861d3f8d9a9 100644 --- a/frameworks/bridge/declarative_frontend/state_mgmt/tsconfig.release.json +++ b/frameworks/bridge/declarative_frontend/state_mgmt/tsconfig.release.json @@ -50,14 +50,9 @@ "src/lib/partial_update/pu_foreach.d.ts", "src/lib/partial_update/pu_view_native.d.ts", "src/lib/partial_update/pu_observed_property_abstract.ts", - "src/lib/partial_update/pu_observed_property_object_abstract.ts", - "src/lib/partial_update/pu_observed_property_simple_abstract.ts", - "src/lib/partial_update/pu_observed_property_object.ts", - "src/lib/partial_update/pu_observed_property_simple.ts", - "src/lib/partial_update/pu_synced_property_object_one_way.ts", - "src/lib/partial_update/pu_synced_property_object_two_way.ts", - "src/lib/partial_update/pu_synced_property_simple_one_way.ts", - "src/lib/partial_update/pu_synced_property_simple_two_way.ts", + "src/lib/partial_update/pu_observed_property.ts", + "src/lib/partial_update/pu_synced_property_one_way.ts", + "src/lib/partial_update/pu_synced_property_two_way.ts", "src/lib/partial_update/pu_synced_property_object_nested.ts", "src/lib/partial_update/pu_view.ts", "src/lib/partial_update/pu_recycle_manager.ts", diff --git a/frameworks/bridge/declarative_frontend/state_mgmt/tsconfig.test.json b/frameworks/bridge/declarative_frontend/state_mgmt/tsconfig.test.json index 30864dcd376..64ffe9ce605 100644 --- a/frameworks/bridge/declarative_frontend/state_mgmt/tsconfig.test.json +++ b/frameworks/bridge/declarative_frontend/state_mgmt/tsconfig.test.json @@ -38,14 +38,9 @@ "src/lib/common/observed_property_abstract.ts", // full_update specific - "src/lib/full_update/fu_observed_property_object_abstract.ts", - "src/lib/full_update/fu_observed_property_simple_abstract.ts", - "src/lib/full_update/fu_observed_property_object.ts", - "src/lib/full_update/fu_observed_property_simple.ts", - "src/lib/full_update/fu_synced_property_object_two_way.ts", - "src/lib/full_update/fu_synced_property_simple_one_way.ts", - "src/lib/full_update/fu_synced_property_simple_two_way.ts", - "src/lib/full_update/fu_synced_property_object_nested.ts", + "src/lib/full_update/fu_observed_property.ts", + "src/lib/full_update/fu_synced_property_two_way.ts", + "src/lib/full_update/fu_synced_property_one_way.ts", "src/lib/full_update/fu_view.ts", // partial update specific diff --git a/frameworks/bridge/js_frontend/js_frontend.cpp b/frameworks/bridge/js_frontend/js_frontend.cpp index e7b80aabb07..837beb5d552 100644 --- a/frameworks/bridge/js_frontend/js_frontend.cpp +++ b/frameworks/bridge/js_frontend/js_frontend.cpp @@ -235,6 +235,19 @@ RefPtr Frontend::Create() return AceType::MakeRefPtr(); } +bool Frontend::MaybeRelease() +{ + CHECK_RUN_ON(JS); + CHECK_NULL_RETURN(taskExecutor_, true); + if (taskExecutor_->WillRunOnCurrentThread(TaskExecutor::TaskType::JS)) { + LOGI("Destroy Frontend on JS thread."); + return true; + } else { + LOGI("Post Destroy Frontend Task to JS thread."); + return !taskExecutor_->PostTask([this] { delete this; }, TaskExecutor::TaskType::JS); + } +} + JsFrontend::~JsFrontend() noexcept { LOG_DESTROY(); @@ -255,6 +268,7 @@ bool JsFrontend::Initialize(FrontendType type, const RefPtr& taskE { LOGI("JsFrontend initialize begin."); type_ = type; + taskExecutor_ = taskExecutor; ACE_DCHECK(type_ == FrontendType::JS); InitializeFrontendDelegate(taskExecutor); auto weakEngine = AceType::WeakClaim(AceType::RawPtr(jsEngine_)); diff --git a/frameworks/bridge/js_frontend/js_frontend.h b/frameworks/bridge/js_frontend/js_frontend.h index 0153056a556..0a6f493d9d3 100644 --- a/frameworks/bridge/js_frontend/js_frontend.h +++ b/frameworks/bridge/js_frontend/js_frontend.h @@ -60,12 +60,12 @@ public: void PushPage(const std::string& url, const std::string& params) override; // Js frontend manages all pages self. - void AddPage(const RefPtr& page) override {}; + void AddPage(const RefPtr& page) override {} RefPtr GetPage(int32_t pageId) const override { return delegate_->GetPage(pageId); - }; + } WeakPtr GetCurrentReadyPage() const { @@ -130,11 +130,6 @@ public: RefPtr GetEventHandler() override { return handler_; - }; - - FrontendType GetType() override - { - return type_; } // judge frontend is foreground frontend. @@ -179,7 +174,6 @@ public: private: void InitializeFrontendDelegate(const RefPtr& taskExecutor); - FrontendType type_ = FrontendType::JS; RefPtr delegate_; RefPtr handler_; RefPtr jsEngine_; diff --git a/frameworks/bridge/plugin_frontend/plugin_frontend.cpp b/frameworks/bridge/plugin_frontend/plugin_frontend.cpp index f973afb8fda..18695190ff3 100644 --- a/frameworks/bridge/plugin_frontend/plugin_frontend.cpp +++ b/frameworks/bridge/plugin_frontend/plugin_frontend.cpp @@ -176,6 +176,7 @@ void PluginFrontend::Destroy() bool PluginFrontend::Initialize(FrontendType type, const RefPtr& taskExecutor) { type_ = type; + taskExecutor_ = taskExecutor; ACE_DCHECK(type_ == FrontendType::JS_PLUGIN); InitializeFrontendDelegate(taskExecutor); taskExecutor->PostSyncTask( diff --git a/frameworks/bridge/plugin_frontend/plugin_frontend.h b/frameworks/bridge/plugin_frontend/plugin_frontend.h index ec5ce9dc239..e7a79f19e60 100644 --- a/frameworks/bridge/plugin_frontend/plugin_frontend.h +++ b/frameworks/bridge/plugin_frontend/plugin_frontend.h @@ -60,12 +60,12 @@ public: void PushPage(const std::string& url, const std::string& params) override; // Js frontend manages all pages self. - void AddPage(const RefPtr& page) override {}; + void AddPage(const RefPtr& page) override {} RefPtr GetPage(int32_t pageId) const override { return nullptr; - }; + } void TriggerGarbageCollection() override; @@ -119,11 +119,6 @@ public: RefPtr GetEventHandler() override { return handler_; - }; - - FrontendType GetType() override - { - return type_; } // judge frontend is foreground frontend. @@ -216,7 +211,6 @@ public: private: void InitializeFrontendDelegate(const RefPtr& taskExecutor); - FrontendType type_ = FrontendType::DECLARATIVE_JS; RefPtr delegate_; RefPtr handler_; RefPtr jsEngine_; diff --git a/frameworks/bridge/test/unittest/jsfrontend/dom_mock.h b/frameworks/bridge/test/unittest/jsfrontend/dom_mock.h index cc90de2a0a6..eb323d71135 100644 --- a/frameworks/bridge/test/unittest/jsfrontend/dom_mock.h +++ b/frameworks/bridge/test/unittest/jsfrontend/dom_mock.h @@ -30,13 +30,13 @@ public: ~MockPlatformWindow() override = default; // Request next vsync. - void RequestFrame() override {}; + void RequestFrame() override {} // Register Vsync callback. - void RegisterVsyncCallback(AceVsyncCallback&& callback) override {}; + void RegisterVsyncCallback(AceVsyncCallback&& callback) override {} // Attach root render node to container - void SetRootRenderNode(const RefPtr& root) override {}; + void SetRootRenderNode(const RefPtr& root) override {} }; class MockFrontend : public Frontend { @@ -66,11 +66,6 @@ public: return windowConfig_; } - FrontendType GetType() override - { - return FrontendType::JS; - } - bool OnBackPressed() override { return false; diff --git a/frameworks/core/animation/svg_animate.cpp b/frameworks/core/animation/svg_animate.cpp index 9280d2bb98d..7780d537cb4 100644 --- a/frameworks/core/animation/svg_animate.cpp +++ b/frameworks/core/animation/svg_animate.cpp @@ -286,7 +286,7 @@ bool SvgAnimate::CreateLinearAnimate( animation->AddListener(std::move(callback)); animator->AddInterpolator(animation); } else { - if (!LinearAnimate(std::move(callback), originalValue, animator)) { + if (!LinearAnimateFromTo(std::move(callback), originalValue, animator)) { LOGW("create linear animate failed"); return false; } @@ -300,7 +300,7 @@ bool SvgAnimate::CreateLinearAnimate( } template -bool SvgAnimate::LinearAnimate( +bool SvgAnimate::LinearAnimateFromTo( std::function&& callback, const T& originalValue, const RefPtr& animator) { if (!animator) { @@ -416,7 +416,7 @@ bool SvgAnimate::CreatePacedAnimate( animation->AddListener(std::move(callback)); animator->AddInterpolator(animation); } else { - if (!LinearAnimate(std::move(callback), originalValue, animator)) { + if (!LinearAnimateFromTo(std::move(callback), originalValue, animator)) { LOGW("create linear animate failed"); return false; } diff --git a/frameworks/core/animation/svg_animate.h b/frameworks/core/animation/svg_animate.h index 739cf5c92a8..258fc9a5565 100644 --- a/frameworks/core/animation/svg_animate.h +++ b/frameworks/core/animation/svg_animate.h @@ -453,7 +453,8 @@ private: bool CreateLinearAnimate( std::function&& callback, const T& originalValue, const RefPtr& animator); template - bool LinearAnimate(std::function&& callback, const T& originalValue, const RefPtr& animator); + bool LinearAnimateFromTo( + std::function&& callback, const T& originalValue, const RefPtr& animator); template bool LinearAnimate(const RefPtr>& animation); template diff --git a/frameworks/core/common/ui_extension_helper.h b/frameworks/core/common/app_bar_helper.h similarity index 79% rename from frameworks/core/common/ui_extension_helper.h rename to frameworks/core/common/app_bar_helper.h index 935cb26659d..87ae05ddf64 100644 --- a/frameworks/core/common/ui_extension_helper.h +++ b/frameworks/core/common/app_bar_helper.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef FOUNDATION_ACE_FRAMEWORKS_CORE_COMMON_UI_EXTENSION_HELPER_H -#define FOUNDATION_ACE_FRAMEWORKS_CORE_COMMON_UI_EXTENSION_HELPER_H +#ifndef FOUNDATION_ACE_FRAMEWORKS_CORE_COMMON_APP_BAR_HELPER_H +#define FOUNDATION_ACE_FRAMEWORKS_CORE_COMMON_APP_BAR_HELPER_H #include #include @@ -23,13 +23,15 @@ namespace OHOS::Ace { -class ACE_EXPORT UIExtensionHelper final { +class ACE_EXPORT AppBarHelper final { public: static RefPtr CreateUIExtensionNode(const std::string& bundleName, const std::string& abilityName, const std::map& params, std::function&& onRelease, std::function&& onError); + + static std::string QueryAppGalleryBundleName(); }; } // namespace OHOS::Ace -#endif // FOUNDATION_ACE_FRAMEWORKS_CORE_COMMON_UI_EXTENSION_HELPER_H +#endif // FOUNDATION_ACE_FRAMEWORKS_CORE_COMMON_APP_BAR_HELPER_H diff --git a/frameworks/core/common/frontend.h b/frameworks/core/common/frontend.h index 84ee7a1ad97..af23e64b296 100644 --- a/frameworks/core/common/frontend.h +++ b/frameworks/core/common/frontend.h @@ -110,7 +110,7 @@ public: // Get the stage mode sourceMap. virtual void GetStageSourceMap( - std::unordered_map>& sourceMap) const {}; + std::unordered_map>& sourceMap) const {} virtual void RunPage(int32_t pageId, const std::string& content, const std::string& params) = 0; @@ -124,7 +124,15 @@ public: // Get window config of front end, which is used to calculate the pixel ratio of the real device. virtual WindowConfig& GetWindowConfig() = 0; - virtual FrontendType GetType() = 0; + FrontendType GetType() const + { + return type_; + } + + RefPtr GetTaskExecutor() const + { + return taskExecutor_; + } // inform the frontend that onCreate or onDestroy virtual void UpdateState(State) = 0; @@ -268,7 +276,7 @@ public: virtual void FlushReload() {} // flush frontend for HotReload feature in NG - virtual void HotReload() {}; + virtual void HotReload() {} State GetState() const { @@ -278,6 +286,9 @@ public: virtual void SetErrorEventHandler(std::function&& errorCallback) {} protected: + virtual bool MaybeRelease() override; + FrontendType type_ = FrontendType::JS; + RefPtr taskExecutor_; bool disallowPopLastPage_ = false; FrontendDialogCallback dialogCallback_ = nullptr; State state_ = State::UNDEFINE; diff --git a/frameworks/core/common/udmf/udmf_client.h b/frameworks/core/common/udmf/udmf_client.h index e274696b801..60fa2a08242 100644 --- a/frameworks/core/common/udmf/udmf_client.h +++ b/frameworks/core/common/udmf/udmf_client.h @@ -49,8 +49,8 @@ public: const RefPtr& unifiedData, std::string& htmlContent, std::string& plainContent) = 0; virtual void AddPixelMapRecord(const RefPtr& unifiedData, std::vector& data) = 0; virtual void AddImageRecord(const RefPtr& unifiedData, const std::string& uri) = 0; - virtual void AddTextRecord(const RefPtr& unifiedData, const std::string& selectedStr) = 0; - virtual std::string GetSingleTextRecord(const RefPtr& unifiedData) = 0; + virtual void AddPlainTextRecord(const RefPtr& unifiedData, const std::string& selectedStr) = 0; + virtual std::string GetSinglePlainTextRecord(const RefPtr& unifiedData) = 0; virtual int32_t GetVideoRecordUri(const RefPtr& unifiedData, std::string& uri) = 0; }; } // namespace OHOS::Ace diff --git a/frameworks/core/components/common/layout/constants.h b/frameworks/core/components/common/layout/constants.h index e2646e16770..28d12719e96 100644 --- a/frameworks/core/components/common/layout/constants.h +++ b/frameworks/core/components/common/layout/constants.h @@ -363,6 +363,7 @@ enum class WindowType : uint32_t { WINDOW_TYPE_UNDEFINED = 0, WINDOW_TYPE_APP_BASE = 1, WINDOW_TYPE_APP_END = 1003, + WINDOW_TYPE_FLOAT = 2106, }; enum class PanelType { diff --git a/frameworks/core/components/common/properties/decoration.h b/frameworks/core/components/common/properties/decoration.h index cdc60246f49..cbe4675d4b3 100644 --- a/frameworks/core/components/common/properties/decoration.h +++ b/frameworks/core/components/common/properties/decoration.h @@ -135,6 +135,18 @@ struct BlurStyleOption { } }; +struct EffectOption { + Dimension radius; + double saturation { 1.0f }; + double brightness { 1.0f }; + Color color { Color::TRANSPARENT }; + bool operator == (const EffectOption& other) const + { + return radius == other.radius && NearEqual(saturation, other.saturation) && + NearEqual(brightness, other.brightness) && color == other.color; + } +}; + struct PixStretchEffectOption { Dimension left; Dimension top; diff --git a/frameworks/core/components/container_modal/container_modal_component.cpp b/frameworks/core/components/container_modal/container_modal_component.cpp index 5ace3746620..726234a6890 100644 --- a/frameworks/core/components/container_modal/container_modal_component.cpp +++ b/frameworks/core/components/container_modal/container_modal_component.cpp @@ -42,7 +42,12 @@ constexpr int32_t WINDOW_MAX_RECOVER_BUTTON = ROOT_DECOR_BASE + 6; constexpr int32_t WINDOW_MINIMIZE_BUTTON = ROOT_DECOR_BASE + 8; constexpr int32_t WINDOW_CLOSE_BUTTON = ROOT_DECOR_BASE + 10; constexpr int32_t WINDOW_BUTTON_INVALID = ROOT_DECOR_BASE + 12; -} + +const std::string SPLIT_LEFT_KEY = "container_modal_split_left_button"; +const std::string MAXIMIZE_KEY = "container_modal_maximize_button"; +const std::string MINIMIZE_KEY = "container_modal_minimize_button"; +const std::string CLOSE_KEY = "container_modal_close_button"; +} // namespace RefPtr ContainerModalComponent::Create( const WeakPtr& context, const RefPtr& child) @@ -143,17 +148,21 @@ RefPtr ContainerModalComponent::BuildContent() RefPtr ContainerModalComponent::BuildControlButton( InternalResource::ResourceId icon, std::function&& clickCallback, bool isFocus, bool isFloating) { - static std::map controlButtonIdMap = { - { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_SPLIT_LEFT, WINDOW_SPLIT_BUTTON }, - { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_DEFOCUS_SPLIT_LEFT, WINDOW_SPLIT_BUTTON }, - { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_RECOVER, WINDOW_MAX_RECOVER_BUTTON }, - { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_MAXIMIZE, WINDOW_MAX_RECOVER_BUTTON }, - { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_DEFOCUS_RECOVER, WINDOW_MAX_RECOVER_BUTTON }, - { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_DEFOCUS_MAXIMIZE, WINDOW_MAX_RECOVER_BUTTON }, - { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_MINIMIZE, WINDOW_MINIMIZE_BUTTON }, - { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_DEFOCUS_MINIMIZE, WINDOW_MINIMIZE_BUTTON }, - { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_CLOSE, WINDOW_CLOSE_BUTTON }, - { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_DEFOCUS_CLOSE, WINDOW_CLOSE_BUTTON }, + static std::unordered_map> controlButtonIdMap = { + { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_SPLIT_LEFT, { WINDOW_SPLIT_BUTTON, SPLIT_LEFT_KEY } }, + { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_DEFOCUS_SPLIT_LEFT, + { WINDOW_SPLIT_BUTTON, SPLIT_LEFT_KEY } }, + { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_RECOVER, { WINDOW_MAX_RECOVER_BUTTON, MAXIMIZE_KEY } }, + { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_MAXIMIZE, { WINDOW_MAX_RECOVER_BUTTON, MAXIMIZE_KEY } }, + { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_DEFOCUS_RECOVER, + { WINDOW_MAX_RECOVER_BUTTON, MAXIMIZE_KEY } }, + { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_DEFOCUS_MAXIMIZE, + { WINDOW_MAX_RECOVER_BUTTON, MAXIMIZE_KEY } }, + { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_MINIMIZE, { WINDOW_MINIMIZE_BUTTON, MINIMIZE_KEY } }, + { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_DEFOCUS_MINIMIZE, + { WINDOW_MINIMIZE_BUTTON, MINIMIZE_KEY } }, + { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_CLOSE, { WINDOW_CLOSE_BUTTON, CLOSE_KEY } }, + { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_DEFOCUS_CLOSE, { WINDOW_CLOSE_BUTTON, CLOSE_KEY } }, }; auto image = AceType::MakeRefPtr(icon); @@ -171,12 +180,17 @@ RefPtr ContainerModalComponent::BuildControlButton( button->SetClickedColor(TITLE_BUTTON_CLICKED_COLOR); button->SetClickFunction(std::move(clickCallback)); button->SetFocusable(false); - + std::string buttonKey = ""; + auto iter = controlButtonIdMap.find(icon); + if (iter != controlButtonIdMap.end()) { + buttonKey = (iter->second).second; + } + button->SetInspectorKey(buttonKey.c_str()); if (!isDeclarative_) { auto buttonId = WINDOW_BUTTON_INVALID; auto iter = controlButtonIdMap.find(icon); if (iter != controlButtonIdMap.end()) { - buttonId = isFloating ? iter->second + 1 : iter->second; + buttonId = isFloating ? (iter->second).first + 1 : (iter->second).first; } CreateAccessibilityNode(DOM_NODE_TAG_BUTTON, buttonId, isFloating ? FLOATING_TITLE_ROW : TITLE_ROW); return AceType::MakeRefPtr(std::to_string(buttonId), DOM_NODE_TAG_BUTTON, button); diff --git a/frameworks/core/components/image/rosen_render_image.cpp b/frameworks/core/components/image/rosen_render_image.cpp index c05ee146d5a..c2f33da90bf 100644 --- a/frameworks/core/components/image/rosen_render_image.cpp +++ b/frameworks/core/components/image/rosen_render_image.cpp @@ -451,17 +451,11 @@ void RosenRenderImage::UpdateSharedMemoryImage(const RefPtr& co return; } auto nameOfSharedImage = ImageLoader::RemovePathHead(sourceInfo_.GetSrc()); - if (sharedImageManager->RegisterLoader(nameOfSharedImage, AceType::WeakClaim(this))) { - // This case means that the image to load is a memory image and its data is not ready. - // Add [this] to [providerMapToReload_] so that it will be notified to start loading image. - // When the data is ready, [SharedImageManager] will call [UpdateData] in [AddImageData]. - return; - } - // this is when current picName is not found in [ProviderMapToReload], indicating that image data of this - // image may have been written to [SharedImageMap], so start loading - if (sharedImageManager->FindImageInSharedImageMap(nameOfSharedImage, AceType::WeakClaim(this))) { - return; - } + sharedImageManager->RegisterLoader(nameOfSharedImage, AceType::WeakClaim(this)); + // This case means that the image to load is a memory image. + // Add [this] to [providerMapToReload_] so that it will be notified to start loading image. + // When the data is ready, [SharedImageManager] will call [UpdateData] in [AddImageData]. + sharedImageManager->FindImageInSharedImageMap(nameOfSharedImage, AceType::WeakClaim(this)); } void RosenRenderImage::PerformLayoutPixmap() diff --git a/frameworks/core/components/scroll/scrollable.cpp b/frameworks/core/components/scroll/scrollable.cpp index 2e51853bd5f..5b514ce81fb 100644 --- a/frameworks/core/components/scroll/scrollable.cpp +++ b/frameworks/core/components/scroll/scrollable.cpp @@ -988,7 +988,7 @@ void Scrollable::StartSpringMotion( void Scrollable::ProcessScrollMotionStop() { - if (needScrollSnapChange_ && calePredictSnapOffsetCallback_) { + if (needScrollSnapChange_ && calePredictSnapOffsetCallback_ && motion_) { needScrollSnapChange_ = false; auto predictSnapOffset = calePredictSnapOffsetCallback_(motion_->GetFinalPosition() - currentPos_); if (predictSnapOffset.has_value() && !NearZero(predictSnapOffset.value())) { @@ -1107,7 +1107,7 @@ bool Scrollable::HandleOverScroll(double velocity) { auto parent = parent_.Upgrade(); if (!parent || !nestedOpt_.NeedParent()) { - if (edgeEffect_ != EdgeEffect::NONE) { + if (edgeEffect_ == EdgeEffect::SPRING) { ProcessScrollOverCallback(velocity); return true; } @@ -1125,14 +1125,14 @@ bool Scrollable::HandleOverScroll(double velocity) } return true; } - if (edgeEffect_ != EdgeEffect::NONE) { + if (edgeEffect_ == EdgeEffect::SPRING) { ProcessScrollOverCallback(velocity); return true; } } // self handle over scroll first - if (edgeEffect_ != EdgeEffect::NONE) { + if (edgeEffect_ == EdgeEffect::SPRING) { ProcessScrollOverCallback(velocity); return true; } diff --git a/frameworks/core/components/select/select_theme.h b/frameworks/core/components/select/select_theme.h index fcd25669ea2..a0934cb4a9e 100644 --- a/frameworks/core/components/select/select_theme.h +++ b/frameworks/core/components/select/select_theme.h @@ -32,6 +32,8 @@ constexpr double SELECT_OPTION_TOP_LENGTH = 15.0; constexpr double SELECT_OPTION_RIGHT_LENGTH = 16.0; constexpr double SELECT_OPTION_BOTTOM_LENGTH = 15.0; constexpr Dimension VERTICAL_INTERVAL = 14.4_vp; +constexpr Dimension MENU_END_ICON_WIDTH = 12.0_vp; +constexpr Dimension MENU_END_ICON_HEIGHT = 24.0_vp; /** * SelectTheme defines color and styles of SelectComponent. SelectTheme should be build @@ -188,6 +190,8 @@ public: theme->selectMinWidth_ = pattern->GetAttr("select_min_width", theme->selectMinWidth_); theme->selectDefaultHeight_ = pattern->GetAttr("select_min_height", theme->selectDefaultHeight_); theme->iconSideLength_ = pattern->GetAttr("icon_side_length", theme->iconSideLength_); + theme->endIconWidth_ = MENU_END_ICON_WIDTH; + theme->endIconHeight_ = MENU_END_ICON_HEIGHT; theme->contentMargin_ = pattern->GetAttr("content_margin", theme->contentMargin_); } }; @@ -276,6 +280,8 @@ public: theme->selectMinWidth_ = selectMinWidth_; theme->selectDefaultHeight_ = selectDefaultHeight_; theme->iconSideLength_ = iconSideLength_; + theme->endIconWidth_ = endIconWidth_; + theme->endIconHeight_ = endIconHeight_; theme->contentMargin_ = contentMargin_; return theme; } @@ -789,6 +795,16 @@ public: return iconSideLength_; } + const Dimension& GetEndIconWidth() const + { + return endIconWidth_; + } + + const Dimension& GetEndIconHeight() const + { + return endIconHeight_; + } + const Dimension& GetContentMargin() const { return contentMargin_; @@ -865,6 +881,8 @@ private: Dimension selectMinWidth_; Dimension selectDefaultHeight_; Dimension iconSideLength_; + Dimension endIconWidth_; + Dimension endIconHeight_; Dimension contentMargin_; Color tvFocusTextColor_; diff --git a/frameworks/core/components/slider/slider_theme.h b/frameworks/core/components/slider/slider_theme.h index 99bd684066a..5581e00a76e 100644 --- a/frameworks/core/components/slider/slider_theme.h +++ b/frameworks/core/components/slider/slider_theme.h @@ -39,6 +39,7 @@ public: static constexpr Color BLOCK_COLOR_PRESSED = Color(0x19182431); static constexpr Color BLOCK_OUTER_EDGE_COLOR = Color(0x0A000000); + static constexpr Color BLOCK_SHADOW_COLOR = Color(0x26000000); static constexpr Dimension BUBBLE_TO_CIRCLE_CENTER_DISTANCE = 20.0_vp; static constexpr Dimension MEASURE_CONTENT_DEFAULT_WIDTH = 40.0_vp; static constexpr Dimension OUTSET_HOT_BLOCK_SHADOW_WIDTH = 4.0_vp; @@ -68,6 +69,7 @@ public: theme->tipFontSize_ = themeConstants->GetDimension(THEME_SLIDER_TIP_FONT_SIZE); theme->tipTextPadding_ = themeConstants->GetDimension(THEME_SLIDER_TIP_TEXT_PADDING_SIZE); theme->blockHoverColor_ = themeConstants->GetColor(THEME_SLIDER_BLOCK_HOVER_COLOR); + theme->blockShadowColor_ = BLOCK_SHADOW_COLOR; ParsePattern(themeConstants->GetThemeStyle(), theme); return theme; } @@ -223,6 +225,11 @@ public: return trackSelectedColor_; } + Color GetBlockShadowColor() const + { + return blockShadowColor_; + } + Dimension GetFocusSideDistance() const { return focusSideDistance_; @@ -279,6 +286,7 @@ private: Color markerColor_; Color trackBgColor_; Color trackSelectedColor_; + Color blockShadowColor_; // others Dimension focusSideDistance_; diff --git a/frameworks/core/components/test/json/json_frontend.cpp b/frameworks/core/components/test/json/json_frontend.cpp index 2949c616461..29353145e0b 100644 --- a/frameworks/core/components/test/json/json_frontend.cpp +++ b/frameworks/core/components/test/json/json_frontend.cpp @@ -26,10 +26,10 @@ RefPtr Frontend::CreateDefault() return AceType::MakeRefPtr(); } -bool JsonFrontend::Initialize(FrontendType type, const RefPtr&) +bool JsonFrontend::Initialize(FrontendType type, const RefPtr& taskExecutor) { - // This interface is inherited from base class 'Frontend', but we never use 'TaskExecutor'. type_ = type; + taskExecutor_ = taskExecutor; return true; } diff --git a/frameworks/core/components/test/json/json_frontend.h b/frameworks/core/components/test/json/json_frontend.h index 26bd185fe08..36f6f35c1f7 100644 --- a/frameworks/core/components/test/json/json_frontend.h +++ b/frameworks/core/components/test/json/json_frontend.h @@ -120,11 +120,6 @@ public: return windowConfig_; } - FrontendType GetType() override - { - return type_; - } - void SendCallbackMessage(const std::string& callbackId, const std::string& data) const override { // maybe will implement later @@ -172,7 +167,6 @@ public: } private: - FrontendType type_ { FrontendType::JSON }; static constexpr int32_t JSON_DESIGN_WIDTH = 1080; std::unordered_map> pageMap_; RefPtr pipelineContext_; diff --git a/frameworks/core/components/web/resource/web_delegate.cpp b/frameworks/core/components/web/resource/web_delegate.cpp index 2f73636faa9..288ba7e9dea 100644 --- a/frameworks/core/components/web/resource/web_delegate.cpp +++ b/frameworks/core/components/web/resource/web_delegate.cpp @@ -4482,6 +4482,10 @@ bool WebDelegate::IsImageDrag() std::shared_ptr WebDelegate::GetOrCreateDragData() { + if (dragData_) { + return dragData_; + } + if (nweb_) { dragData_ = nweb_->GetOrCreateDragData(); return dragData_; diff --git a/frameworks/core/components_ng/base/frame_node.cpp b/frameworks/core/components_ng/base/frame_node.cpp index 9188da1a137..57498a282dc 100644 --- a/frameworks/core/components_ng/base/frame_node.cpp +++ b/frameworks/core/components_ng/base/frame_node.cpp @@ -202,6 +202,7 @@ public: { SetAllChildrenInActive(); ResetChildren(); + Build(); for (const auto& child : children_) { child.node->DoRemoveChildInRenderTree(0, true); } @@ -727,6 +728,7 @@ void FrameNode::SwapDirtyLayoutWrapperOnMainThread(const RefPtr& SetBackgroundLayoutConstraint(columnNode); renderContext_->CreateBackgroundPixelMap(columnNode); builderFunc_ = nullptr; + backgroundNode_ = columnNode; } // update focus state @@ -963,11 +965,6 @@ std::optional FrameNode::CreateLayoutTask(bool forceUseMainThread) ACE_SCOPED_TRACE("Layout"); Layout(); } - { - LayoutWrapper::SaveGeoState(); - LayoutWrapper::AvoidKeyboard(); - LayoutWrapper::ExpandSafeArea(); - } SetRootMeasureNode(false); return std::nullopt; } @@ -1835,12 +1832,7 @@ OffsetF FrameNode::GetParentGlobalOffsetDuringLayout() const OffsetF offset {}; auto parent = GetAncestorNodeOfFrame(); while (parent) { - auto wrapper = parent->layoutWrapper_.Upgrade(); - if (wrapper) { - offset += wrapper->GetGeometryNode()->GetFrameOffset(); - } else { - offset += parent->geometryNode_->GetFrameOffset(); - } + offset += parent->geometryNode_->GetFrameOffset(); parent = parent->GetAncestorNodeOfFrame(); } return offset; @@ -2149,8 +2141,8 @@ bool FrameNode::HaveSecurityComponent() bool FrameNode::IsSecurityComponent() { - return GetTag() == V2::SEC_LOCATION_BUTTON_ETS_TAG || GetTag() == V2::SEC_PASTE_BUTTON_ETS_TAG || - GetTag() == V2::SEC_SAVE_BUTTON_ETS_TAG; + return GetTag() == V2::LOCATION_BUTTON_ETS_TAG || GetTag() == V2::PASTE_BUTTON_ETS_TAG || + GetTag() == V2::SAVE_BUTTON_ETS_TAG; } void FrameNode::OnSetDepth(const int32_t depth) @@ -2164,6 +2156,9 @@ void FrameNode::OnSetDepth(const int32_t depth) // This will call child and self measure process. void FrameNode::Measure(const std::optional& parentConstraint) { + if (!oldGeometryNode_) { + oldGeometryNode_ = geometryNode_->Clone(); + } RestoreGeoState(); pattern_->BeforeCreateLayoutWrapper(); GetLayoutAlgorithm(true); @@ -2257,14 +2252,6 @@ void FrameNode::Measure(const std::optional& parentConstraint void FrameNode::Layout() { int64_t time = GetSysTimestamp(); - auto&& expandOpts = layoutProperty_->GetSafeAreaExpandOpts(); - if ((expandOpts && expandOpts->Expansive()) || GetTag() == V2::PAGE_ETS_TAG) { - // record expansive wrappers during Layout traversal to speed up SafeArea expansion - // Page node needs to avoid keyboard, record it too. - auto pipeline = PipelineContext::GetCurrentContext(); - CHECK_NULL_VOID(pipeline); - pipeline->GetSafeAreaManager()->AddWrapper(WeakClaim(this)); - } OffsetNodeToSafeArea(); if (CheckNeedLayout(layoutProperty_->GetPropertyChangeFlag())) { if (!layoutProperty_->GetLayoutConstraint()) { @@ -2290,6 +2277,10 @@ void FrameNode::Layout() GetLayoutAlgorithm()->SetSkipLayout(); } + SaveGeoState(); + AvoidKeyboard(); + ExpandSafeArea(); + LOGD("On Layout Done: type: %{public}s, depth: %{public}d, Offset: %{public}s", GetTag().c_str(), GetDepth(), geometryNode_->GetFrameOffset().ToString().c_str()); SyncGeometryNode(); diff --git a/frameworks/core/components_ng/base/frame_node.h b/frameworks/core/components_ng/base/frame_node.h index 83606d3647d..285b75d4e45 100644 --- a/frameworks/core/components_ng/base/frame_node.h +++ b/frameworks/core/components_ng/base/frame_node.h @@ -357,6 +357,7 @@ public: void SetBackgroundFunction(std::function()>&& buildFunc) { builderFunc_ = buildFunc; + backgroundNode_ = nullptr; } bool IsDraggable() const @@ -405,16 +406,6 @@ public: static std::vector> GetNodesById(const std::unordered_set& set); - // called during LayoutWrapper creation, used for finding corresponding LayoutWrapper during RestoreGeoState - void RecordLayoutWrapper(WeakPtr layoutWrapper) - { - layoutWrapper_ = std::move(layoutWrapper); - } - const WeakPtr& GetLayoutWrapper() const - { - return layoutWrapper_; - } - void SetViewPort(RectF viewPort) { viewPort_ = viewPort; @@ -568,9 +559,8 @@ private: RefPtr renderContext_ = RenderContext::Create(); RefPtr eventHub_; RefPtr pattern_; - // only valid during layout task - WeakPtr layoutWrapper_; + RefPtr backgroundNode_; std::function()> builderFunc_; std::unique_ptr lastFrameRect_; std::unique_ptr lastParentOffsetToWindow_; diff --git a/frameworks/core/components_ng/base/ui_node.cpp b/frameworks/core/components_ng/base/ui_node.cpp index df8166b349a..96e8c3aec68 100644 --- a/frameworks/core/components_ng/base/ui_node.cpp +++ b/frameworks/core/components_ng/base/ui_node.cpp @@ -451,7 +451,9 @@ void UINode::DumpTree(int32_t depth) void UINode::AdjustLayoutWrapperTree(const RefPtr& parent, bool forceMeasure, bool forceLayout) { for (const auto& child : children_) { - child->AdjustLayoutWrapperTree(parent, forceMeasure, forceLayout); + if (!child->IsInDestroying()) { + child->AdjustLayoutWrapperTree(parent, forceMeasure, forceLayout); + } } } diff --git a/frameworks/core/components_ng/base/view_abstract.cpp b/frameworks/core/components_ng/base/view_abstract.cpp index dc164e82120..b455257e7d8 100644 --- a/frameworks/core/components_ng/base/view_abstract.cpp +++ b/frameworks/core/components_ng/base/view_abstract.cpp @@ -257,6 +257,20 @@ void ViewAbstract::SetBackgroundBlurStyle(const BlurStyleOption& bgBlurStyle) } } +void ViewAbstract::SetBackgroundEffect(const EffectOption& effectOption) +{ + if (!ViewStackProcessor::GetInstance()->IsCurrentVisualStateProcess()) { + LOGD("current state is not processed, return"); + return; + } + auto frameNode = ViewStackProcessor::GetInstance()->GetMainFrameNode(); + CHECK_NULL_VOID(frameNode); + auto target = frameNode->GetRenderContext(); + if (target) { + target->UpdateBackgroundEffect(effectOption); + } +} + void ViewAbstract::SetForegroundBlurStyle(const BlurStyleOption& fgBlurStyle) { if (!ViewStackProcessor::GetInstance()->IsCurrentVisualStateProcess()) { @@ -1091,6 +1105,7 @@ void ViewAbstract::BindPopup( LOGI("Popup now show in subwindow."); SubwindowManager::GetInstance()->ShowPopupNG(targetId, popupInfo); if (popupPattern) { + popupPattern->SetContainerId(Container::CurrentId()); popupPattern->StartEnteringAnimation(nullptr); } } else { @@ -1156,11 +1171,6 @@ void ViewAbstract::BindMenuWithCustomNode(const RefPtr& customNode, cons // unable to use the subWindow in the Previewer. isContextMenu = false; #endif - // windowScene will not use subwindow - auto container = Container::Current(); - if (container && container->IsScenceBoardWindow()) { - isContextMenu = false; - } auto type = isContextMenu ? MenuType::CONTEXT_MENU : MenuType::MENU; auto menuNode = MenuView::Create(customNode, targetNode->GetId(), targetNode->GetTag(), type, menuParam); if (isContextMenu) { diff --git a/frameworks/core/components_ng/base/view_abstract.h b/frameworks/core/components_ng/base/view_abstract.h index bc783261faa..6c34521fb8b 100644 --- a/frameworks/core/components_ng/base/view_abstract.h +++ b/frameworks/core/components_ng/base/view_abstract.h @@ -96,6 +96,7 @@ public: static void SetBackgroundImageSize(const BackgroundImageSize& bgImgSize); static void SetBackgroundImagePosition(const BackgroundImagePosition& bgImgPosition); static void SetBackgroundBlurStyle(const BlurStyleOption& bgBlurStyle); + static void SetBackgroundEffect(const EffectOption& effectOption); static void SetForegroundBlurStyle(const BlurStyleOption& fgBlurStyle); static void SetSphericalEffect(double radio); static void SetPixelStretchEffect(PixStretchEffectOption& option); diff --git a/frameworks/core/components_ng/base/view_abstract_model.h b/frameworks/core/components_ng/base/view_abstract_model.h index f08f1e2aa21..05d47a8fa49 100644 --- a/frameworks/core/components_ng/base/view_abstract_model.h +++ b/frameworks/core/components_ng/base/view_abstract_model.h @@ -75,6 +75,7 @@ public: virtual void SetBackgroundImageSize(const BackgroundImageSize& bgImgSize) = 0; virtual void SetBackgroundImagePosition(const BackgroundImagePosition& bgImgPosition) = 0; virtual void SetBackgroundBlurStyle(const BlurStyleOption& bgBlurStyle) = 0; + virtual void SetBackgroundEffect(const EffectOption& effectOption) {} virtual void SetForegroundBlurStyle(const BlurStyleOption& fgBlurStyle) {} virtual void SetSphericalEffect(double radio) {} virtual void SetPixelStretchEffect(PixStretchEffectOption& option) {} diff --git a/frameworks/core/components_ng/base/view_abstract_model_ng.h b/frameworks/core/components_ng/base/view_abstract_model_ng.h index a95904747a4..0fe5f94f262 100644 --- a/frameworks/core/components_ng/base/view_abstract_model_ng.h +++ b/frameworks/core/components_ng/base/view_abstract_model_ng.h @@ -134,6 +134,11 @@ public: ViewAbstract::SetBackgroundBlurStyle(bgBlurStyle); } + void SetBackgroundEffect(const EffectOption& effectOption) override + { + ViewAbstract::SetBackgroundEffect(effectOption); + } + void SetForegroundBlurStyle(const BlurStyleOption& fgBlurStyle) override { ViewAbstract::SetForegroundBlurStyle(fgBlurStyle); diff --git a/frameworks/core/components_ng/event/drag_event.cpp b/frameworks/core/components_ng/event/drag_event.cpp index c46e48d8792..f8af40fb7ab 100644 --- a/frameworks/core/components_ng/event/drag_event.cpp +++ b/frameworks/core/components_ng/event/drag_event.cpp @@ -136,6 +136,7 @@ void DragEventActuator::OnCollectTouchTarget(const OffsetF& coordinateOffset, co HideEventColumn(); HidePixelMap(true, info.GetGlobalLocation().GetX(), info.GetGlobalLocation().GetY()); HideFilter(); + SubwindowManager::GetInstance()->HideMenuNG(); AnimationOption option; option.SetDuration(PIXELMAP_ANIMATION_DURATION); option.SetCurve(Curves::SHARP); @@ -144,15 +145,6 @@ void DragEventActuator::OnCollectTouchTarget(const OffsetF& coordinateOffset, co [renderContext]() { renderContext->UpdateOpacity(SCALE_NUMBER); }, option.GetOnFinishEvent()); - auto container = Container::Current(); - if (container && container->IsScenceBoardWindow()) { - auto pipelineContext = PipelineContext::GetCurrentContext(); - CHECK_NULL_VOID(pipelineContext); - auto manager = pipelineContext->GetOverlayManager(); - manager->HideAllMenus(); - } else { - SubwindowManager::GetInstance()->HideMenuNG(); - } } } @@ -216,6 +208,7 @@ void DragEventActuator::OnCollectTouchTarget(const OffsetF& coordinateOffset, co LOGE("InteractionManager: UpdateShadowPic error"); return; } + LOGD("Drag window start for Mouse with default pixelMap"); Msdp::DeviceStatus::InteractionManager::GetInstance()->SetDragWindowVisible(true); }; auto gestureHub = gestureEventHub_.Upgrade(); @@ -467,6 +460,23 @@ void DragEventActuator::SetFilter(const RefPtr& actuator) } } +OffsetF DragEventActuator::GetFloatImageOffset(const RefPtr& frameNode) +{ + auto offsetToWindow = frameNode->GetPaintRectOffset(); + auto offsetX = offsetToWindow.GetX(); + auto offsetY = offsetToWindow.GetY(); +#ifdef WEB_SUPPORTED + if (frameNode->GetTag() == V2::WEB_ETS_TAG) { + auto webPattern = frameNode->GetPattern(); + if (webPattern) { + offsetX += webPattern->GetDragOffset().GetX(); + offsetY += webPattern->GetDragOffset().GetY(); + } + } +#endif + return OffsetF(offsetX, offsetY); +} + void DragEventActuator::SetPixelMap(const RefPtr& actuator) { auto pipelineContext = PipelineContext::GetCurrentContext(); @@ -484,13 +494,8 @@ void DragEventActuator::SetPixelMap(const RefPtr& actuator) CHECK_NULL_VOID(pixelMap); auto width = pixelMap->GetWidth(); auto height = pixelMap->GetHeight(); - auto offsetToWindow = frameNode->GetPaintRectOffset(); - auto offsetX = offsetToWindow.GetX(); - auto offsetY = offsetToWindow.GetY(); - if (frameNode->GetTag() == V2::WEB_ETS_TAG) { - offsetX = longPressInfo_.GetGlobalPoint().GetX() - (width / 2); - offsetY = longPressInfo_.GetGlobalPoint().GetY() - (height / 2); - } + auto offsetX = GetFloatImageOffset(frameNode).GetX(); + auto offsetY = GetFloatImageOffset(frameNode).GetY(); // create imageNode auto imageNode = FrameNode::GetOrCreateFrameNode(V2::IMAGE_ETS_TAG, ElementRegister::GetInstance()->MakeUniqueId(), []() { return AceType::MakeRefPtr(); }); @@ -679,6 +684,7 @@ void DragEventActuator::GetTextPixelMap(bool startDrag) LOGE("InteractionManager: UpdateShadowPic error"); return; } + LOGD("Drag window start for Mouse with Text"); Msdp::DeviceStatus::InteractionManager::GetInstance()->SetDragWindowVisible(true); gestureHub->SetPixelMap(nullptr); } @@ -741,6 +747,7 @@ void DragEventActuator::HideTextAnimation(bool startDrag, double globalX, double CHECK_NULL_VOID(pattern); pattern->CreateHandles(); } + LOGD("Drag window start for Text"); Msdp::DeviceStatus::InteractionManager::GetInstance()->SetDragWindowVisible(true); auto gestureHub = weakEvent.Upgrade(); CHECK_NULL_VOID(gestureHub); diff --git a/frameworks/core/components_ng/event/drag_event.h b/frameworks/core/components_ng/event/drag_event.h index 2f7695b10fe..91b8f556a97 100644 --- a/frameworks/core/components_ng/event/drag_event.h +++ b/frameworks/core/components_ng/event/drag_event.h @@ -108,6 +108,7 @@ public: bool GetIsBindOverlayValue(const RefPtr& actuator); bool IsAllowedDrag(); void GetTextPixelMap(bool startDrag); + OffsetF GetFloatImageOffset(const RefPtr& frameNode); #endif // ENABLE_DRAG_FRAMEWORK PanDirection GetDirection() const { diff --git a/frameworks/core/components_ng/event/gesture_event_hub.cpp b/frameworks/core/components_ng/event/gesture_event_hub.cpp index 976a64b3212..556f2cbf8c4 100644 --- a/frameworks/core/components_ng/event/gesture_event_hub.cpp +++ b/frameworks/core/components_ng/event/gesture_event_hub.cpp @@ -20,6 +20,7 @@ #include "base/memory/ace_type.h" #include "base/utils/time_util.h" +#include "core/common/container.h" #include "core/components_ng/base/frame_node.h" #include "core/components_ng/event/click_event.h" #include "core/components_ng/event/event_hub.h" @@ -433,21 +434,19 @@ void GestureEventHub::CancelDragForWeb() void GestureEventHub::ResetDragActionForWeb() { + isReceivedDragGestureInfo_ = false; CHECK_NULL_VOID_NOLOG(dragEventActuator_); dragEventActuator_->ResetDragActionForWeb(); } void GestureEventHub::StartDragTaskForWeb() { - auto startTime = std::chrono::high_resolution_clock::now(); - auto timeElapsed = startTime - gestureInfoForWeb_.GetTimeStamp(); - auto timeElapsedMs = std::chrono::duration_cast(timeElapsed); - // 100 : 100ms - if (timeElapsedMs.count() > 100) { - LOGW("start drag task for web failed, not received this drag action gesture info"); + if (!isReceivedDragGestureInfo_) { + LOGI("not received drag info, wait ark drag start"); return; } + isReceivedDragGestureInfo_ = false; auto pipeline = PipelineContext::GetCurrentContext(); CHECK_NULL_VOID(pipeline); auto taskScheduler = pipeline->GetTaskExecutor(); @@ -480,7 +479,7 @@ std::shared_ptr CreatePixelMapFromString(const std::string& fil OffsetF GestureEventHub::GetPixelMapOffset(const GestureEvent& info, const SizeF& size, const float scale) const { - OffsetF result = OffsetF(-1.0f, -1.0f); + OffsetF result = OffsetF(size.Width() * PIXELMAP_WIDTH_RATE, size.Height() * PIXELMAP_HEIGHT_RATE); if (info.GetInputEventType() == InputEventType::MOUSE_BUTTON) { return result; } @@ -512,12 +511,23 @@ OffsetF GestureEventHub::GetPixelMapOffset(const GestureEvent& info, const SizeF } #endif +void GestureEventHub::HandleNotallowDrag(const GestureEvent& info) +{ + auto frameNode = GetFrameNode(); + CHECK_NULL_VOID(frameNode); + if (frameNode->GetTag() == V2::WEB_ETS_TAG) { + LOGI("web component receive drag start, need to let web kernel start drag action"); + gestureInfoForWeb_ = info; + isReceivedDragGestureInfo_ = true; + } +} + void GestureEventHub::HandleOnDragStart(const GestureEvent& info) { auto eventHub = eventHub_.Upgrade(); CHECK_NULL_VOID(eventHub); if (!IsAllowedDrag(eventHub)) { - gestureInfoForWeb_ = info; + HandleNotallowDrag(info); return; } auto pipeline = PipelineContext::GetCurrentContext(); @@ -613,9 +623,10 @@ void GestureEventHub::HandleOnDragStart(const GestureEvent& info) return; } if (dragEventActuator_->GetIsNotInPreviewState()) { + LOGD("Drag window start for not in previewState"); Msdp::DeviceStatus::InteractionManager::GetInstance()->SetDragWindowVisible(true); - } - if (info.GetInputEventType() == InputEventType::MOUSE_BUTTON && dragDropInfo.pixelMap) { + } else if (info.GetInputEventType() == InputEventType::MOUSE_BUTTON && dragDropInfo.pixelMap) { + LOGD("Drag window start for Mouse with custom pixelMap"); Msdp::DeviceStatus::InteractionManager::GetInstance()->SetDragWindowVisible(true); } dragDropProxy_ = dragDropManager->CreateFrameworkDragDropProxy(); @@ -892,8 +903,9 @@ OnDragCallback GestureEventHub::GetDragCallback() CHECK_NULL_RETURN(dragDropManager, ret); auto eventManager = pipeline->GetEventManager(); RefPtr dragEvent = AceType::MakeRefPtr(); - auto callback = [eventHub, dragEvent, taskScheduler, dragDropManager, eventManager]( + auto callback = [id = Container::CurrentId(), eventHub, dragEvent, taskScheduler, dragDropManager, eventManager]( const DragNotifyMsg& notifyMessage) { + ContainerScope scope(id); DragRet result = DragRet::DRAG_FAIL; switch (notifyMessage.result) { case DragResult::DRAG_SUCCESS: diff --git a/frameworks/core/components_ng/event/gesture_event_hub.h b/frameworks/core/components_ng/event/gesture_event_hub.h index 30366955df6..85ece3c1c94 100644 --- a/frameworks/core/components_ng/event/gesture_event_hub.h +++ b/frameworks/core/components_ng/event/gesture_event_hub.h @@ -434,6 +434,7 @@ public: void OnModifyDone(); bool KeyBoardShortCutClick(const KeyEvent& event, const WeakPtr& node); bool IsAllowedDrag(RefPtr eventHub); + void HandleNotallowDrag(const GestureEvent& info); private: void ProcessTouchTestHierarchy(const OffsetF& coordinateOffset, const TouchRestrict& touchRestrict, @@ -475,6 +476,7 @@ private: bool touchable_ = true; RefPtr pixelMap_; GestureEvent gestureInfoForWeb_; + bool isReceivedDragGestureInfo_ = false; #ifdef ENABLE_DRAG_FRAMEWORK bool textDraggable_ = false; diff --git a/frameworks/core/components_ng/event/scrollable_event.cpp b/frameworks/core/components_ng/event/scrollable_event.cpp index f544cd73561..ff70c491889 100644 --- a/frameworks/core/components_ng/event/scrollable_event.cpp +++ b/frameworks/core/components_ng/event/scrollable_event.cpp @@ -27,25 +27,6 @@ ScrollableActuator::ScrollableActuator(const WeakPtr& gestureEv : gestureEventHub_(gestureEventHub) {} -void ScrollableActuator::CollectTouchTarget(const OffsetF& coordinateOffset, const PointF& localPoint, - const GetEventTargetImpl& getEventTargetImpl, TouchTestResult& result) -{ - for (const auto& [axis, event] : scrollableEvents_) { - if (!event || !event->GetEnable()) { - continue; - } - auto scrollBar = event->GetScrollBar(); - if (scrollBar && scrollBar->InBarTouchRegion(Point(localPoint.GetX(), localPoint.GetY()))) { - scrollBar->OnCollectTouchTarget(coordinateOffset, getEventTargetImpl, result); - } else { - const auto& scrollable = event->GetScrollable(); - scrollable->SetGetEventTargetImpl(getEventTargetImpl); - scrollable->SetCoordinateOffset(Offset(coordinateOffset.GetX(), coordinateOffset.GetY())); - scrollable->OnCollectTouchTarget(result); - } - } -} - void ScrollableActuator::InitializeScrollable(RefPtr event) { auto gestureEventHub = gestureEventHub_.Upgrade(); diff --git a/frameworks/core/components_ng/event/scrollable_event.h b/frameworks/core/components_ng/event/scrollable_event.h index 32ec68b2b93..ed9ff888e3d 100644 --- a/frameworks/core/components_ng/event/scrollable_event.h +++ b/frameworks/core/components_ng/event/scrollable_event.h @@ -24,12 +24,14 @@ #include "core/components/scroll/scrollable.h" #include "core/components_ng/event/gesture_event_actuator.h" #include "core/components_ng/pattern/scroll/scroll_edge_effect.h" -#include "core/components_ng/pattern/scroll/inner/scroll_bar.h" namespace OHOS::Ace::NG { class GestureEventHub; +using BarCollectTouchTargetCallback = std::function; +using InBarRegionCallback = std::function; + class ScrollableEvent : public AceType { DECLARE_ACE_TYPE(ScrollableEvent, AceType) public: @@ -155,14 +157,27 @@ public: return friction_; } - RefPtr GetScrollBar(void) const + void SetBarCollectTouchTargetCallback(const BarCollectTouchTargetCallback&& barCollectTouchTarget) { - return scrollBar_.Upgrade(); + barCollectTouchTarget_ = std::move(barCollectTouchTarget); } - void SetScrollBar(const RefPtr& scrollBar) + void SetInBarRegionCallback(const InBarRegionCallback&& inBarRegionCallback) { - scrollBar_ = AceType::WeakClaim(AceType::RawPtr(scrollBar)); + inBarRegionCallback_ = std::move(inBarRegionCallback); + } + + bool InBarRegion(const PointF& localPoint) const + { + return inBarRegionCallback_ && barCollectTouchTarget_ && inBarRegionCallback_(localPoint); + } + + void BarCollectTouchTarget(const OffsetF& coordinateOffset, + const GetEventTargetImpl& getEventTargetImpl, TouchTestResult& result) + { + if (barCollectTouchTarget_) { + barCollectTouchTarget_(coordinateOffset, getEventTargetImpl, result); + } } private: @@ -175,7 +190,8 @@ private: Axis axis_ = Axis::VERTICAL; bool enable_ = true; RefPtr scrollable_; - WeakPtr scrollBar_; + BarCollectTouchTargetCallback barCollectTouchTarget_; + InBarRegionCallback inBarRegionCallback_; double friction_ = -1.0; }; @@ -188,7 +204,9 @@ public: void AddScrollableEvent(const RefPtr& scrollableEvent) { scrollableEvents_[scrollableEvent->GetAxis()] = scrollableEvent; - InitializeScrollable(scrollableEvent); + if (scrollableEvent && !scrollableEvent->GetScrollable()) { + InitializeScrollable(scrollableEvent); + } } void RemoveScrollableEvent(const RefPtr& scrollableEvent) @@ -200,7 +218,22 @@ public: bool RemoveScrollEdgeEffect(const RefPtr& effect); void CollectTouchTarget(const OffsetF& coordinateOffset, const PointF& localPoint, - const GetEventTargetImpl& getEventTargetImpl, TouchTestResult& result); + const GetEventTargetImpl& getEventTargetImpl, TouchTestResult& result) + { + for (const auto& [axis, event] : scrollableEvents_) { + if (!event || !event->GetEnable()) { + continue; + } + if (event->InBarRegion(localPoint)) { + event->BarCollectTouchTarget(coordinateOffset, getEventTargetImpl, result); + } else { + const auto& scrollable = event->GetScrollable(); + scrollable->SetGetEventTargetImpl(getEventTargetImpl); + scrollable->SetCoordinateOffset(Offset(coordinateOffset.GetX(), coordinateOffset.GetY())); + scrollable->OnCollectTouchTarget(result); + } + } + } private: void InitializeScrollable(RefPtr event); diff --git a/frameworks/core/components_ng/image_provider/svg_image_object.cpp b/frameworks/core/components_ng/image_provider/svg_image_object.cpp index a9a9f5d968f..673587183c1 100644 --- a/frameworks/core/components_ng/image_provider/svg_image_object.cpp +++ b/frameworks/core/components_ng/image_provider/svg_image_object.cpp @@ -61,8 +61,12 @@ bool SvgImageObject::MakeSvgDom(const RefPtr& data, const std::option svgDomBase_ = rosenImageData->MakeSvgDom(svgFillColor); #endif CHECK_NULL_RETURN(svgDomBase_, false); - // get ImageSize - SetImageSize(svgDomBase_->GetContainerSize()); + imageSize_ = svgDomBase_->GetContainerSize(); + + if (imageSize_.IsNonPositive()) { + LOGI("[Engine Log] [Image] %{public}s doesn't have an intrinsic size. The developer must set a size for it.", + GetSourceInfo().ToString().c_str()); + } return true; } } // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/layout/layout_wrapper.cpp b/frameworks/core/components_ng/layout/layout_wrapper.cpp index 0fceb9cdba3..c10e8019819 100644 --- a/frameworks/core/components_ng/layout/layout_wrapper.cpp +++ b/frameworks/core/components_ng/layout/layout_wrapper.cpp @@ -17,10 +17,7 @@ #include -#include "base/geometry/dimension.h" #include "base/log/ace_checker.h" -#include "base/log/ace_trace.h" -#include "base/utils/time_util.h" #include "base/utils/utils.h" #include "core/components/common/properties/alignment.h" #include "core/components_ng/base/frame_node.h" @@ -45,16 +42,9 @@ void LayoutWrapper::ApplySafeArea(const SafeAreaInsets& insets, LayoutConstraint { SizeF safeSize { PipelineContext::GetCurrentRootWidth(), PipelineContext::GetCurrentRootHeight() }; safeSize.MinusPadding(insets.left_.Length(), insets.right_.Length(), insets.top_.Length(), insets.bottom_.Length()); - if (safeSize.Width() < constraint.maxSize.Width() || safeSize.Height() < constraint.maxSize.Height()) { - safeSize.SetWidth(std::min(safeSize.Width(), constraint.maxSize.Width())); - safeSize.SetHeight(std::min(safeSize.Height(), constraint.maxSize.Height())); - constraint.maxSize = safeSize; - constraint.parentIdealSize = OptionalSizeF(safeSize); - constraint.percentReference = safeSize; - } - if (safeSize < constraint.minSize) { - constraint.minSize = safeSize; - } + constraint.maxSize = safeSize; + constraint.parentIdealSize = OptionalSizeF(safeSize); + constraint.percentReference = safeSize; } void LayoutWrapper::OffsetNodeToSafeArea() @@ -95,61 +85,35 @@ void LayoutWrapper::RestoreGeoState() void LayoutWrapper::AvoidKeyboard() { - auto pipeline = PipelineContext::GetCurrentContext(); - CHECK_NULL_VOID(pipeline); - auto manager = pipeline->GetSafeAreaManager(); + // apply keyboard avoidance on Page + if (GetHostTag() == V2::PAGE_ETS_TAG) { + auto pipeline = PipelineContext::GetCurrentContext(); + CHECK_NULL_VOID(pipeline); + auto manager = pipeline->GetSafeAreaManager(); + GetGeometryNode()->SetFrameOffset( + GetGeometryNode()->GetFrameOffset() + OffsetF(0, manager->GetKeyboardOffset())); + } +} - for (auto&& wrapperWk : manager->GetWrappers()) { - auto wrapper = wrapperWk.Upgrade(); - if (!wrapper) { - continue; - } - auto host = wrapper->GetHostNode(); - // apply keyboard avoidance on Page - if (host && host->GetTag() == V2::PAGE_ETS_TAG) { - wrapper->GetGeometryNode()->SetFrameOffset( - wrapper->GetGeometryNode()->GetFrameOffset() + OffsetF(0, manager->GetKeyboardOffset())); - } +void LayoutWrapper::SaveGeoState() +{ + auto&& expandOpts = GetLayoutProperty()->GetSafeAreaExpandOpts(); + if ((expandOpts && expandOpts->Expansive()) || GetHostTag() == V2::PAGE_ETS_TAG) { + // save geometry state before SafeArea expansion / keyboard avoidance. + GetGeometryNode()->Save(); + // record nodes whose geometry states need to be restored, to speed up RestoreGeoState + auto pipeline = PipelineContext::GetCurrentContext(); + CHECK_NULL_VOID(pipeline); + auto manager = pipeline->GetSafeAreaManager(); + manager->AddGeoRestoreNode(GetHostNode()); } } void LayoutWrapper::ExpandSafeArea() { - auto pipeline = PipelineContext::GetCurrentContext(); - CHECK_NULL_VOID(pipeline); - auto manager = pipeline->GetSafeAreaManager(); + auto&& opts = GetLayoutProperty()->GetSafeAreaExpandOpts(); + CHECK_NULL_VOID_NOLOG(opts && opts->Expansive()); - for (auto&& wrapperWk : manager->GetWrappers()) { - auto wrapper = wrapperWk.Upgrade(); - if (wrapper && wrapper->GetLayoutProperty()->GetSafeAreaExpandOpts()) { - wrapper->ExpandSafeAreaInner(); - } - } - - manager->ResetWrappers(); -} - -void LayoutWrapper::SaveGeoState() -{ - auto pipeline = PipelineContext::GetCurrentContext(); - CHECK_NULL_VOID(pipeline); - auto manager = pipeline->GetSafeAreaManager(); - // save geometry state before SafeArea expansion / keyboard avoidance. - for (auto&& wrapperWk : manager->GetWrappers()) { - auto wrapper = wrapperWk.Upgrade(); - if (wrapper) { - wrapper->GetGeometryNode()->Save(); - - // record nodes whose geometry states need to be restored, to speed up RestoreGeoState - auto pipeline = PipelineContext::GetCurrentContext(); - CHECK_NULL_VOID(pipeline); - manager->AddGeoRestoreNode(wrapper->hostNode_); - } - } -} - -void LayoutWrapper::ExpandSafeAreaInner() -{ // children of Scrollable nodes don't support expandSafeArea auto host = GetHostNode(); CHECK_NULL_VOID(host); @@ -158,9 +122,6 @@ void LayoutWrapper::ExpandSafeAreaInner() return; } - auto&& opts = GetLayoutProperty()->GetSafeAreaExpandOpts(); - CHECK_NULL_VOID_NOLOG(opts->Expansive()); - if ((opts->edges & SAFE_AREA_EDGE_BOTTOM) && (opts->type & SAFE_AREA_TYPE_KEYBOARD)) { ExpandIntoKeyboard(); } @@ -203,7 +164,6 @@ void LayoutWrapper::ExpandSafeAreaInner() if (layoutProperty->HasAspectRatio()) { frame.SetHeight(frame.Width() / layoutProperty->GetAspectRatio()); } - // restore to local offset frame -= parentGlobalOffset; geometryNode->SetFrameOffset(frame.GetOffset()); @@ -212,6 +172,16 @@ void LayoutWrapper::ExpandSafeAreaInner() void LayoutWrapper::ExpandIntoKeyboard() { + // if parent already expanded into keyboard, offset shouldn't be applied again + auto parent = GetHostNode()->GetAncestorNodeOfFrame(); + while (parent) { + auto&& opts = parent->GetLayoutProperty()->GetSafeAreaExpandOpts(); + if (opts && (opts->edges & SAFE_AREA_EDGE_BOTTOM) && opts->type & SAFE_AREA_TYPE_KEYBOARD) { + return; + } + parent = parent->GetAncestorNodeOfFrame(); + } + auto pipeline = PipelineContext::GetCurrentContext(); CHECK_NULL_VOID(pipeline); auto geometryNode = GetGeometryNode(); diff --git a/frameworks/core/components_ng/layout/layout_wrapper.h b/frameworks/core/components_ng/layout/layout_wrapper.h index 5d5e4dc64a2..fe47dde165e 100644 --- a/frameworks/core/components_ng/layout/layout_wrapper.h +++ b/frameworks/core/components_ng/layout/layout_wrapper.h @@ -117,12 +117,12 @@ public: static void ApplySafeArea(const SafeAreaInsets& insets, LayoutConstraintF& constraint); // apply keyboard avoidance on content rootNodes - static void AvoidKeyboard(); + void AvoidKeyboard(); // expand the SafeArea of expansive nodes, which are previously recorded during Layout traversal - static void ExpandSafeArea(); + void ExpandSafeArea(); // save geometry states before SafeArea expansion / keyboard avoidance - static void SaveGeoState(); + void SaveGeoState(); // restore to the geometry state after last Layout and before SafeArea expansion and keyboard avoidance void RestoreGeoState(); @@ -131,7 +131,6 @@ protected: void ApplyConstraint(LayoutConstraintF constraint); void OffsetNodeToSafeArea(); - void ExpandSafeAreaInner(); // keyboard avoidance is done by offsetting, to expand into keyboard area, reverse the offset. void ExpandIntoKeyboard(); diff --git a/frameworks/core/components_ng/layout/layout_wrapper_node.cpp b/frameworks/core/components_ng/layout/layout_wrapper_node.cpp index 8fd556785c3..f39122527f1 100644 --- a/frameworks/core/components_ng/layout/layout_wrapper_node.cpp +++ b/frameworks/core/components_ng/layout/layout_wrapper_node.cpp @@ -38,20 +38,13 @@ void LayoutWrapperNode::Update( hostNode_ = std::move(hostNode); geometryNode_ = std::move(geometryNode); layoutProperty_ = std::move(layoutProperty); - auto host = hostNode_.Upgrade(); - CHECK_NULL_VOID(host); - host->RecordLayoutWrapper(WeakClaim(this)); } LayoutWrapperNode::LayoutWrapperNode( WeakPtr hostNode, RefPtr geometryNode, RefPtr layoutProperty) : LayoutWrapper(std::move(hostNode)), geometryNode_(std::move(geometryNode)), layoutProperty_(std::move(layoutProperty)) -{ - auto host = hostNode_.Upgrade(); - CHECK_NULL_VOID(host); - host->RecordLayoutWrapper(WeakClaim(this)); -} +{} void LayoutWrapperNode::AppendChild(const RefPtr& child, bool isOverlayNode) { @@ -170,8 +163,6 @@ void LayoutWrapperNode::Measure(const std::optional& parentCo CHECK_NULL_VOID(layoutProperty_); CHECK_NULL_VOID(geometryNode_); CHECK_NULL_VOID(host); - // restore to the geometry state after last Layout and before SafeArea expansion and keyboard avoidance - RestoreGeoState(); CHECK_NULL_VOID(layoutAlgorithm_); if (layoutAlgorithm_->SkipMeasure()) { @@ -255,14 +246,6 @@ void LayoutWrapperNode::Layout() CHECK_NULL_VOID(host); CHECK_NULL_VOID(layoutAlgorithm_); - auto&& expandOpts = layoutProperty_->GetSafeAreaExpandOpts(); - if ((expandOpts && expandOpts->Expansive()) || host->GetTag() == V2::PAGE_ETS_TAG) { - // record expansive wrappers during Layout traversal to speed up SafeArea expansion - // Page node needs to avoid keyboard, record it too. - auto pipeline = PipelineContext::GetCurrentContext(); - CHECK_NULL_VOID(pipeline); - pipeline->GetSafeAreaManager()->AddWrapper(WeakClaim(this)); - } OffsetNodeToSafeArea(); if (layoutAlgorithm_->SkipLayout()) { @@ -415,7 +398,7 @@ void LayoutWrapperNode::LayoutOverlay() return; } overlayChild_->Layout(); - auto size = GetGeometryNode()->GetMarginFrameSize(); + auto size = GetGeometryNode()->GetFrameSize(); auto align = Alignment::TOP_LEFT; Dimension offsetX, offsetY; auto childLayoutProperty = overlayChild_->GetLayoutProperty(); diff --git a/frameworks/core/components_ng/manager/drag_drop/drag_drop_manager.cpp b/frameworks/core/components_ng/manager/drag_drop/drag_drop_manager.cpp index 2916b477bc9..44e901fc6b8 100644 --- a/frameworks/core/components_ng/manager/drag_drop/drag_drop_manager.cpp +++ b/frameworks/core/components_ng/manager/drag_drop/drag_drop_manager.cpp @@ -173,7 +173,7 @@ void DragDropManager::UpdatePixelMapPosition(int32_t globalX, int32_t globalY) } RefPtr pixelMap = hub->GetPixelMap(); CHECK_NULL_VOID(pixelMap); - float scale = pixelMap->GetWidth() / (NearZero(width) ? 1.0f : width); + float scale = NearZero(width) ? 1.0f : pixelMap->GetWidth() / width; imageContext->UpdatePosition(NG::OffsetT( Dimension(globalX - width * PIXELMAP_POSITION_WIDTH * scale - width / 2.0f + width * scale / 2.0f), Dimension(globalY - height * PIXELMAP_POSITION_HEIGHT * scale - height / 2.0f + height * scale / 2.0f))); diff --git a/frameworks/core/components_ng/manager/safe_area/safe_area_manager.h b/frameworks/core/components_ng/manager/safe_area/safe_area_manager.h index 0f2bfc42f97..ca49a4600d4 100644 --- a/frameworks/core/components_ng/manager/safe_area/safe_area_manager.h +++ b/frameworks/core/components_ng/manager/safe_area/safe_area_manager.h @@ -63,23 +63,6 @@ public: SafeAreaInsets GetCombinedSafeArea(const SafeAreaExpandOpts& opts) const; - // Add during Layout traversal - void AddWrapper(const WeakPtr& wrapper) - { - wrappersToAdjust_.emplace_back(wrapper); - } - - // Reset after ExpandSafeArea and AvoidKeyboard - void ResetWrappers() - { - wrappersToAdjust_.clear(); - } - - const std::vector>& GetWrappers() const - { - return wrappersToAdjust_; - } - const std::set>& GetGeoRestoreNodes() const { return geoRestoreNodes_; @@ -106,7 +89,6 @@ private: // bottom direction only SafeAreaInsets::Inset keyboardInset_; std::set> geoRestoreNodes_; - std::vector> wrappersToAdjust_; // amount of offset to apply to Page when keyboard is up float keyboardOffset_ = 0.0f; static constexpr float SAFE_AREA_VELOCITY = 0.0f; diff --git a/frameworks/core/components_ng/pattern/BUILD.gn b/frameworks/core/components_ng/pattern/BUILD.gn index d7010fcf721..14edc5100c7 100644 --- a/frameworks/core/components_ng/pattern/BUILD.gn +++ b/frameworks/core/components_ng/pattern/BUILD.gn @@ -415,6 +415,7 @@ build_component_ng("pattern_ng") { "text/text_pattern.cpp", "text/text_styles.cpp", "text_clock/text_clock_accessibility_property.cpp", + "text_clock/text_clock_layout_algorithm.cpp", "text_clock/text_clock_layout_property.cpp", "text_clock/text_clock_model_ng.cpp", "text_clock/text_clock_pattern.cpp", diff --git a/frameworks/core/components_ng/pattern/ability_component/ability_component_pattern.cpp b/frameworks/core/components_ng/pattern/ability_component/ability_component_pattern.cpp index 8b40a63aacd..9cf0ab5c1c4 100644 --- a/frameworks/core/components_ng/pattern/ability_component/ability_component_pattern.cpp +++ b/frameworks/core/components_ng/pattern/ability_component/ability_component_pattern.cpp @@ -28,9 +28,8 @@ namespace OHOS::Ace::NG { AbilityComponentPattern::AbilityComponentPattern(const std::string& bundleName, const std::string& abilityName) { - if (SystemProperties::IsSceneBoardEnabled()) { - auto container = AceType::DynamicCast(Container::Current()); - CHECK_NULL_VOID_NOLOG(container); + auto container = AceType::DynamicCast(Container::Current()); + if (container && container->IsScenceBoardWindow()) { auto wantWrap = Ace::WantWrap::CreateWantWrap(bundleName, abilityName); auto want = AceType::DynamicCast(wantWrap)->GetWant(); Rosen::SessionInfo extensionSessionInfo = { @@ -72,7 +71,7 @@ void AbilityComponentPattern::OnModifyDone() CHECK_NULL_VOID(host); adapter_ = WindowExtensionConnectionProxyNG::CreateAdapter(); CHECK_NULL_VOID(adapter_); - if (SystemProperties::IsSceneBoardEnabled()) { + if (container && container->IsScenceBoardWindow()) { CHECK_NULL_VOID(session_); sptr extensionSession(static_cast(session_.GetRefPtr())); CHECK_NULL_VOID(extensionSession); diff --git a/frameworks/core/components_ng/pattern/app_bar/app_bar_theme.h b/frameworks/core/components_ng/pattern/app_bar/app_bar_theme.h index 1263cf113c3..6601442a9b3 100644 --- a/frameworks/core/components_ng/pattern/app_bar/app_bar_theme.h +++ b/frameworks/core/components_ng/pattern/app_bar/app_bar_theme.h @@ -94,6 +94,11 @@ public: return abilityName_; } + const std::string& GetStageAbilityName() const + { + return stageAbilityName_; + } + private: AppBarTheme() = default; static void ParsePattern(const RefPtr& themeStyle, const RefPtr& theme) @@ -115,6 +120,7 @@ private: theme->appBarBgColor_ = appBarPattern->GetAttr("app_bar_bg_color", Color()); theme->bundleName_ = appBarPattern->GetAttr("app_bar_bundle_name", "com.ohos.hag.famanager"); theme->abilityName_ = appBarPattern->GetAttr("app_bar_ability_name", "FaPanelAbility"); + theme->stageAbilityName_ = appBarPattern->GetAttr("app_bar_stage_ability_name", "PanelAbility"); } Dimension appBarHeight_; @@ -126,6 +132,7 @@ private: Color appBarBgColor_; std::string bundleName_; std::string abilityName_; + std::string stageAbilityName_; }; } // namespace OHOS::Ace::NG #endif // FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_NG_APP_BAR_THEME_H \ No newline at end of file diff --git a/frameworks/core/components_ng/pattern/app_bar/app_bar_view.cpp b/frameworks/core/components_ng/pattern/app_bar/app_bar_view.cpp index 7a8e4f15486..74cf6a38791 100644 --- a/frameworks/core/components_ng/pattern/app_bar/app_bar_view.cpp +++ b/frameworks/core/components_ng/pattern/app_bar/app_bar_view.cpp @@ -18,8 +18,8 @@ #include #include "base/want/want_wrap.h" +#include "core/common/app_bar_helper.h" #include "core/common/container.h" -#include "core/common/ui_extension_helper.h" #include "core/components_ng/pattern/app_bar/app_bar_theme.h" #include "core/components_ng/pattern/app_bar/atomic_service_pattern.h" #include "core/components_ng/pattern/button/button_layout_property.h" @@ -217,16 +217,15 @@ void AppBarView::BindContentCover(int32_t targetId) CHECK_NULL_VOID(pipeline); auto overlayManager = pipeline->GetOverlayManager(); CHECK_NULL_VOID(overlayManager); + + std::string stageAbilityName = ""; + auto appBarTheme = pipeline->GetTheme(); + if (appBarTheme) { + stageAbilityName = appBarTheme->GetStageAbilityName(); + } NG::ModalStyle modalStyle; modalStyle.modalTransition = NG::ModalTransition::NONE; - auto buildNodeFunc = [targetId, overlayManager, &modalStyle]() -> RefPtr { - std::string bundleName = ""; - std::string abilityName = ""; - SystemProperties::GetAppBarInfo(bundleName, abilityName); - if (bundleName.empty() || abilityName.empty()) { - return nullptr; - } - + auto buildNodeFunc = [targetId, overlayManager, &modalStyle, &stageAbilityName]() -> RefPtr { auto onRelease = [overlayManager, &modalStyle, targetId](int32_t releaseCode) { overlayManager->BindContentCover(false, nullptr, nullptr, modalStyle, nullptr, nullptr, targetId); }; @@ -234,6 +233,8 @@ void AppBarView::BindContentCover(int32_t targetId) [overlayManager, &modalStyle, targetId](int32_t code, const std::string& name, const std::string& message) { overlayManager->BindContentCover(false, nullptr, nullptr, modalStyle, nullptr, nullptr, targetId); }; + + // Create parameters of UIExtension. auto missionId = AceApplicationInfo::GetInstance().GetMissionId(); std::map params; params.try_emplace("bundleName", AceApplicationInfo::GetInstance().GetProcessName()); @@ -242,8 +243,14 @@ void AppBarView::BindContentCover(int32_t targetId) if (missionId != -1) { params.try_emplace("missionId", std::to_string(missionId)); } - auto uiExtNode = OHOS::Ace::UIExtensionHelper::CreateUIExtensionNode( - bundleName, abilityName, params, std::move(onRelease), std::move(onError)); + + // Create UIExtension node. + auto appGalleryBundleName = OHOS::Ace::AppBarHelper::QueryAppGalleryBundleName(); + auto uiExtNode = OHOS::Ace::AppBarHelper::CreateUIExtensionNode(appGalleryBundleName, stageAbilityName, + params, std::move(onRelease), std::move(onError)); + LOGI("BundleName: %{public}s, abilityName: %{public}s", appGalleryBundleName.c_str(), stageAbilityName.c_str()); + + // Update ideal size of UIExtension. auto layoutProperty = uiExtNode->GetLayoutProperty(); CHECK_NULL_RETURN(layoutProperty, uiExtNode); layoutProperty->UpdateUserDefinedIdealSize(CalcSize(CalcLength(Dimension(1.0, DimensionUnit::PERCENT)), diff --git a/frameworks/core/components_ng/pattern/bubble/bubble_layout_algorithm.cpp b/frameworks/core/components_ng/pattern/bubble/bubble_layout_algorithm.cpp index bff8b9dcee6..6508a9def97 100644 --- a/frameworks/core/components_ng/pattern/bubble/bubble_layout_algorithm.cpp +++ b/frameworks/core/components_ng/pattern/bubble/bubble_layout_algorithm.cpp @@ -26,6 +26,8 @@ #include "base/utils/device_config.h" #include "base/utils/system_properties.h" #include "base/utils/utils.h" +#include "core/common/ace_engine.h" +#include "core/common/container.h" #include "core/components/common/properties/placement.h" #include "core/components/popup/popup_theme.h" #include "core/components_ng/base/frame_node.h" @@ -33,17 +35,29 @@ #include "core/components_ng/pattern/bubble/bubble_pattern.h" #include "core/pipeline/pipeline_base.h" #include "core/pipeline_ng/pipeline_context.h" -#include "core/pipeline_ng/ui_task_scheduler.h" namespace OHOS::Ace::NG { - namespace { - constexpr Dimension ARROW_WIDTH = 32.0_vp; constexpr Dimension ARROW_HEIGHT = 8.0_vp; constexpr Dimension HORIZON_SPACING_WITH_SCREEN = 6.0_vp; constexpr Dimension BEZIER_WIDTH_HALF = 16.0_vp; +// get main window's pipeline +RefPtr GetMainPipelineContext() +{ + auto containerId = Container::CurrentId(); + RefPtr context; + if (containerId >= MIN_SUBCONTAINER_ID) { + auto parentContainerId = SubwindowManager::GetInstance()->GetParentContainerId(containerId); + auto parentContainer = AceEngine::Get().GetContainer(parentContainerId); + CHECK_NULL_RETURN(parentContainer, nullptr); + context = AceType::DynamicCast(parentContainer->GetPipelineContext()); + } else { + context = PipelineContext::GetCurrentContext(); + } + return context; +} } // namespace void BubbleLayoutAlgorithm::Measure(LayoutWrapper* layoutWrapper) @@ -171,7 +185,7 @@ OffsetT BubbleLayoutAlgorithm::GetChildOffsetAfterLayout(const RefPtr rects.emplace_back(parentWindowRect); rects.emplace_back(rect); } - SubwindowManager::GetInstance()->SetHotAreas(rects, frameNode->GetId()); + SubwindowManager::GetInstance()->SetHotAreas(rects, frameNode->GetId(), bubblePattern->GetContainerId()); } Dimension childOffsetX(childOffset_.GetX()); @@ -499,13 +513,11 @@ void BubbleLayoutAlgorithm::InitTargetSizeAndPosition(bool showInSubWindow) auto geometryNode = targetNode->GetGeometryNode(); CHECK_NULL_VOID(geometryNode); targetSize_ = geometryNode->GetFrameSize(); - auto pipelineContext = PipelineContext::GetCurrentContext(); + auto pipelineContext = GetMainPipelineContext(); CHECK_NULL_VOID(pipelineContext); targetOffset_ = targetNode->GetPaintRectOffset(); // Show in SubWindow if (showInSubWindow) { - auto overlayManager = pipelineContext->GetOverlayManager(); - CHECK_NULL_VOID(overlayManager); auto displayWindowOffset = OffsetF(pipelineContext->GetDisplayWindowRectInfo().GetOffset().GetX(), pipelineContext->GetDisplayWindowRectInfo().GetOffset().GetY()); targetOffset_ += displayWindowOffset; @@ -516,5 +528,4 @@ void BubbleLayoutAlgorithm::InitTargetSizeAndPosition(bool showInSubWindow) } } } - } // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/pattern/container_modal/container_modal_view.cpp b/frameworks/core/components_ng/pattern/container_modal/container_modal_view.cpp index 0b2d9851f82..1b7118544be 100644 --- a/frameworks/core/components_ng/pattern/container_modal/container_modal_view.cpp +++ b/frameworks/core/components_ng/pattern/container_modal/container_modal_view.cpp @@ -38,6 +38,12 @@ namespace OHOS::Ace::NG { +namespace { +constexpr char SPLIT_LEFT_KEY[] = "container_modal_split_left_button"; +constexpr char MAXIMIZE_KEY[] = "container_modal_maximize_button"; +constexpr char MINIMIZE_KEY[] = "container_modal_minimize_button"; +constexpr char CLOSE_KEY[] = "container_modal_close_button"; +} // namespace /** * The structure of container_modal is designed as follows : @@ -236,6 +242,18 @@ RefPtr ContainerModalView::AddControlButtons(RefPtr& conta RefPtr ContainerModalView::BuildControlButton( InternalResource::ResourceId icon, GestureEventFunc&& clickCallback, bool isCloseButton, bool canDrag) { + static std::unordered_map controlButtonKeyMap = { + { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_SPLIT_LEFT, SPLIT_LEFT_KEY }, + { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_DEFOCUS_SPLIT_LEFT, SPLIT_LEFT_KEY }, + { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_RECOVER, MAXIMIZE_KEY }, + { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_MAXIMIZE, MAXIMIZE_KEY }, + { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_DEFOCUS_RECOVER, MAXIMIZE_KEY }, + { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_DEFOCUS_MAXIMIZE, MAXIMIZE_KEY }, + { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_MINIMIZE, MINIMIZE_KEY }, + { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_DEFOCUS_MINIMIZE, MINIMIZE_KEY }, + { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_CLOSE, CLOSE_KEY }, + { InternalResource::ResourceId::CONTAINER_MODAL_WINDOW_DEFOCUS_CLOSE, CLOSE_KEY }, + }; // button image icon ImageSourceInfo imageSourceInfo; auto imageIcon = FrameNode::CreateFrameNode( @@ -260,6 +278,12 @@ RefPtr ContainerModalView::BuildControlButton( if (buttonFocus) { buttonFocus->SetFocusable(false); } + std::string buttonKey = ""; + auto iter = controlButtonKeyMap.find(icon); + if (iter != controlButtonKeyMap.end()) { + buttonKey = iter->second; + } + buttonNode->UpdateInspectorId(buttonKey); AddButtonHover(buttonNode, imageIcon); AddButtonMouse(buttonNode, imageIcon); diff --git a/frameworks/core/components_ng/pattern/data_panel/data_panel_modifier.cpp b/frameworks/core/components_ng/pattern/data_panel/data_panel_modifier.cpp index 2fe92e167f9..b847fbcd4bb 100755 --- a/frameworks/core/components_ng/pattern/data_panel/data_panel_modifier.cpp +++ b/frameworks/core/components_ng/pattern/data_panel/data_panel_modifier.cpp @@ -41,6 +41,7 @@ constexpr float PERCENT_HALF = 0.5f; constexpr float DIAMETER_TO_THICKNESS_RATIO = 0.12f; constexpr float FIXED_ANGLE = 2.0f; constexpr float FIXED_DRAW_ANGLE = 4.0f; +constexpr uint32_t SHADOW_ALPHA = 0.6 * 255; } // namespace DataPanelModifier::DataPanelModifier() @@ -159,6 +160,7 @@ void DataPanelModifier::PaintRainbowFilterMask(RSCanvas& canvas, double factor, RSPen gradientPaint; gradientPaint.SetWidth(thickness); gradientPaint.SetAntiAlias(true); + gradientPaint.SetAlpha(SHADOW_ALPHA); RSFilter filter; filter.SetMaskFilter(RSMaskFilter::CreateBlurMaskFilter(RSBlurType::NORMAL, shadowRadiusFloat_->Get())); gradientPaint.SetFilter(filter); @@ -170,11 +172,13 @@ void DataPanelModifier::PaintRainbowFilterMask(RSCanvas& canvas, double factor, RSBrush startCirclePaint; startCirclePaint.SetAntiAlias(true); startCirclePaint.SetColor(arcData.shadowColor.GetColors().begin()->GetLinearColor().GetValue()); + startCirclePaint.SetAlpha(SHADOW_ALPHA); startCirclePaint.SetFilter(filter); RSBrush endCirclePaint; endCirclePaint.SetAntiAlias(true); endCirclePaint.SetColor(arcData.shadowColor.GetColors().rbegin()->GetLinearColor().GetValue()); + endCirclePaint.SetAlpha(SHADOW_ALPHA); endCirclePaint.SetFilter(filter); gradientPaint.SetShaderEffect(RSShaderEffect::CreateSweepGradient( @@ -247,6 +251,22 @@ void DataPanelModifier::PaintCircle(DrawingContext& context, OffsetF offset, flo proportions = maxValue == 0 ? 1.0 : DEFAULT_MAX_VALUE / maxValue; } totalValue = totalValue * proportions; + double shadowValue = totalValue; + for (int32_t i = static_cast(tempSize) - 1; i >= 0; i--) { + float totalValuePre = shadowValue * 1.0f; + if (isEffect_->Get() && GreatNotEqual(totalValue, 0.0)) { + arcData.progress = shadowValue * date; + } else { + arcData.progress = shadowValue; + } + shadowValue -= values_[i]->Get() * proportions; + arcData.gradientPointBase = (shadowValue * 1.0f) / totalValuePre; + if ((isShadowVisible_ && (isHasShadowValue_ || isEffect_->Get())) && (i < shadowColorsLastLength_)) { + arcData.shadowColor = SortGradientColorsOffset(shadowColors_[i]->Get().GetGradient()); + PaintRainbowFilterMask(canvas, factor * date, arcData); + } + } + for (int32_t i = static_cast(tempSize) - 1; i >= 0; i--) { arcData.progressColors = SortGradientColorsOffset(valueColors_[i]->Get().GetGradient()); float totalValuePre = totalValue * 1.0f; @@ -257,13 +277,8 @@ void DataPanelModifier::PaintCircle(DrawingContext& context, OffsetF offset, flo } totalValue -= values_[i]->Get() * proportions; arcData.gradientPointBase = (totalValue * 1.0f) / totalValuePre; - if ((isShadowVisible_ && (isHasShadowValue_ || isEffect_->Get())) && (i < shadowColorsLastLength_)) { - arcData.shadowColor = SortGradientColorsOffset(shadowColors_[i]->Get().GetGradient()); - PaintRainbowFilterMask(canvas, factor * date, arcData); - } PaintProgress(canvas, arcData, isEffect_->Get(), false, 0.0); } - canvas.Restore(); } @@ -292,7 +307,8 @@ void DataPanelModifier::PaintLinearProgress(DrawingContext& context, OffsetF off } auto widthSegment = offset.GetX(); - PaintBackground(canvas, offset, totalWidth, context.height); + auto firstSegmentWidth = values_[0]->Get() * scaleMaxValue; + PaintBackground(canvas, offset, totalWidth, context.height, firstSegmentWidth); bool isStopPaint = false; float totalPaintWidth = 0.0f; float preWidthSegment = 0.0f; @@ -336,14 +352,20 @@ void DataPanelModifier::PaintLinearProgress(DrawingContext& context, OffsetF off } } -void DataPanelModifier::PaintBackground(RSCanvas& canvas, OffsetF offset, float totalWidth, float height) const +void DataPanelModifier::PaintBackground( + RSCanvas& canvas, OffsetF offset, float totalWidth, float height, float segmentWidth) const { RSBrush brush; brush.SetColor(ToRSColor(trackBackgroundColor_->Get())); brush.SetAntiAlias(true); canvas.AttachBrush(brush); RSRect rRect(offset.GetX(), offset.GetY(), totalWidth + offset.GetX(), height + offset.GetY()); - RSRoundRect rrRect(rRect, height, height); + RSRoundRect rrRect; + if (height <= segmentWidth) { + rrRect = RSRoundRect(rRect, height, height); + } else { + rrRect = RSRoundRect(rRect, segmentWidth, segmentWidth); + } canvas.DrawRoundRect(rrRect); canvas.DetachBrush(); } @@ -431,6 +453,7 @@ void DataPanelModifier::PaintColorSegmentFilterMask(RSCanvas& canvas, const Line RSFilter filter; filter.SetMaskFilter(RSMaskFilter::CreateBlurMaskFilter(RSBlurType::NORMAL, shadowRadiusFloat_->Get())); brush.SetFilter(filter); + brush.SetAlpha(SHADOW_ALPHA); brush.SetShaderEffect( RSShaderEffect::CreateLinearGradient(segmentStartPoint, segmentEndPoint, colors, pos, RSTileMode::CLAMP)); canvas.AttachBrush(brush); diff --git a/frameworks/core/components_ng/pattern/data_panel/data_panel_modifier.h b/frameworks/core/components_ng/pattern/data_panel/data_panel_modifier.h index f8431f767ea..3d5f86ee17d 100644 --- a/frameworks/core/components_ng/pattern/data_panel/data_panel_modifier.h +++ b/frameworks/core/components_ng/pattern/data_panel/data_panel_modifier.h @@ -78,7 +78,7 @@ public: void PaintCircle(DrawingContext& context, OffsetF offset, float date) const; void PaintLinearProgress(DrawingContext& context, OffsetF offset) const; - void PaintBackground(RSCanvas& canvas, OffsetF offset, float totalWidth, float height) const; + void PaintBackground(RSCanvas& canvas, OffsetF offset, float totalWidth, float height, float segmentWidth) const; void PaintColorSegment(RSCanvas& canvas, const LinearData& segmentLinearData) const; void PaintSpace(RSCanvas& canvas, OffsetF offset, float spaceWidth, float xSpace, float height) const; void PaintTrackBackground(RSCanvas& canvas, ArcData arcData, const Color color) const; @@ -219,4 +219,4 @@ private: ACE_DISALLOW_COPY_AND_MOVE(DataPanelModifier); }; } // namespace OHOS::Ace::NG -#endif // FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_NG_PATTERNS_DATA_PANEL_DATA_PANEL_MODIFIER_H \ No newline at end of file +#endif // FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_NG_PATTERNS_DATA_PANEL_DATA_PANEL_MODIFIER_H diff --git a/frameworks/core/components_ng/pattern/dialog/custom_dialog_controller_model_ng.cpp b/frameworks/core/components_ng/pattern/dialog/custom_dialog_controller_model_ng.cpp index ef6cdc651dc..7ab2ec6546b 100644 --- a/frameworks/core/components_ng/pattern/dialog/custom_dialog_controller_model_ng.cpp +++ b/frameworks/core/components_ng/pattern/dialog/custom_dialog_controller_model_ng.cpp @@ -16,8 +16,7 @@ #include "core/components_ng/pattern/dialog/custom_dialog_controller_model_ng.h" #include "base/subwindow/subwindow_manager.h" -#include "frameworks/bridge/common/utils/engine_helper.h" -#include "frameworks/core/components_ng/base/view_stack_processor.h" + namespace OHOS::Ace::NG { void CustomDialogControllerModelNG::SetOpenDialog(DialogProperties& dialogProperties, std::vector>& dialogs, bool& pending, bool& isShown, std::function&& cancelTask, @@ -39,11 +38,6 @@ void CustomDialogControllerModelNG::SetOpenDialog(DialogProperties& dialogProper auto overlayManager = context->GetOverlayManager(); CHECK_NULL_VOID(overlayManager); - NG::ScopedViewStackProcessor builderViewStackProcessor; - buildFunc(); - auto customNode = NG::ViewStackProcessor::GetInstance()->Finish(); - CHECK_NULL_VOID(customNode); - dialogProperties.onStatusChanged = [&isShown](bool isShownStatus) { if (!isShownStatus) { isShown = isShownStatus; @@ -52,9 +46,9 @@ void CustomDialogControllerModelNG::SetOpenDialog(DialogProperties& dialogProper WeakPtr dialog; if (dialogProperties.isShowInSubWindow) { - dialog = SubwindowManager::GetInstance()->ShowDialogNG(dialogProperties, customNode); + dialog = SubwindowManager::GetInstance()->ShowDialogNG(dialogProperties, std::move(buildFunc)); } else { - dialog = overlayManager->ShowDialog(dialogProperties, customNode, false); + dialog = overlayManager->ShowDialog(dialogProperties, std::move(buildFunc), false); } dialogs.emplace_back(dialog); } diff --git a/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp b/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp index 66443f4a540..be30dd41499 100644 --- a/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp +++ b/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp @@ -736,7 +736,7 @@ void FlexLayoutAlgorithm::Measure(LayoutWrapper* layoutWrapper) bool mainAxisInf = GreaterOrEqualToInfinity(direction_ == FlexDirection::ROW || direction_ == FlexDirection::ROW_REVERSE ? layoutConstraint->maxSize.Width() - : layoutConstraint->maxSize.Height()); + : layoutConstraint->maxSize.Height()) && NearEqual(mainAxisSize_, -1.0f); if (NearEqual(mainAxisSize_, -1.0f)) { if (PipelineBase::GetCurrentContext() && PipelineBase::GetCurrentContext()->GetMinPlatformVersion() <= 9) { mainAxisSize_ = direction_ == FlexDirection::ROW || direction_ == FlexDirection::ROW_REVERSE diff --git a/frameworks/core/components_ng/pattern/flex/flex_layout_pattern.h b/frameworks/core/components_ng/pattern/flex/flex_layout_pattern.h index ac4b77e7835..20a470ec69b 100644 --- a/frameworks/core/components_ng/pattern/flex/flex_layout_pattern.h +++ b/frameworks/core/components_ng/pattern/flex/flex_layout_pattern.h @@ -56,22 +56,6 @@ public: return { FocusType::SCOPE, true }; } - bool IsMeasureBoundary() const override - { - // May be optimized later by not using DynamicCast. - auto property = GetLayoutProperty(); - CHECK_NULL_RETURN(property, false); - bool isVertical = false; - if (property->GetFlexDirection().has_value()) { - isVertical = property->GetFlexDirection().value() == FlexDirection::COLUMN || - property->GetFlexDirection().value() == FlexDirection::COLUMN_REVERSE; - } - if (isVertical) { - return property->HasFixedWidth(); - } - return property->HasFixedHeight(); - } - ScopeFocusAlgorithm GetScopeFocusAlgorithm() override { auto property = GetLayoutProperty(); diff --git a/frameworks/core/components_ng/pattern/form/form_pattern.cpp b/frameworks/core/components_ng/pattern/form/form_pattern.cpp index c0bbbd2598b..cc9176e3a65 100644 --- a/frameworks/core/components_ng/pattern/form/form_pattern.cpp +++ b/frameworks/core/components_ng/pattern/form/form_pattern.cpp @@ -99,6 +99,17 @@ void FormPattern::OnAttachToFrameNode() }, DELAY_TIME_FOR_FORM_SUBCONTAINER_CACHE); }); + + // Init click event for static form. + auto gestureEventHub = host->GetOrCreateGestureEventHub(); + auto clickCallback = [weak = WeakClaim(this)](GestureEvent& info) { + auto formPattern = weak.Upgrade(); + CHECK_NULL_VOID(formPattern); + formPattern->HandleStaticFormEvent( + { static_cast(info.GetLocalLocation().GetX()), static_cast(info.GetLocalLocation().GetY()) }); + }; + auto clickEvent = AceType::MakeRefPtr(std::move(clickCallback)); + gestureEventHub->AddClickEvent(clickEvent); scopeId_ = Container::CurrentId(); } @@ -161,24 +172,11 @@ void FormPattern::HandleSnapshot() form->TakeSurfaceCaptureForUI(); }, TaskExecutor::TaskType::UI, DELAY_TIME_FOR_FORM_SNAPSHOT); - - // Init click event for static form. - auto host = GetHost(); - CHECK_NULL_VOID(host); - auto gestureEventHub = host->GetOrCreateGestureEventHub(); - auto clickCallback = [weak = WeakClaim(this)](GestureEvent& info) { - auto formPattern = weak.Upgrade(); - CHECK_NULL_VOID(formPattern); - formPattern->HandleStaticFormEvent( - { static_cast(info.GetLocalLocation().GetX()), static_cast(info.GetLocalLocation().GetY()) }); - }; - auto clickEvent = AceType::MakeRefPtr(std::move(clickCallback)); - gestureEventHub->AddClickEvent(clickEvent); } void FormPattern::HandleStaticFormEvent(const PointF& touchPoint) { - if (formLinkInfos_.empty()) { + if (formLinkInfos_.empty() || isDynamic_) { LOGE("formLinkInfos is empty, do not handle event."); return; } diff --git a/frameworks/core/components_ng/pattern/form/form_pattern.h b/frameworks/core/components_ng/pattern/form/form_pattern.h index 412b48099f4..e364024dbe3 100644 --- a/frameworks/core/components_ng/pattern/form/form_pattern.h +++ b/frameworks/core/components_ng/pattern/form/form_pattern.h @@ -87,6 +87,7 @@ public: void SetFormLinkInfos(const std::vector& infos) { + formLinkInfos_.clear(); formLinkInfos_ = infos; } diff --git a/frameworks/core/components_ng/pattern/form_link/form_link_pattern.cpp b/frameworks/core/components_ng/pattern/form_link/form_link_pattern.cpp index d35fa7300a6..0fa517ac655 100644 --- a/frameworks/core/components_ng/pattern/form_link/form_link_pattern.cpp +++ b/frameworks/core/components_ng/pattern/form_link/form_link_pattern.cpp @@ -24,18 +24,24 @@ void FormLinkPattern::OnAttachToFrameNode() auto host = GetHost(); CHECK_NULL_VOID(host); host->GetLayoutProperty()->UpdateMeasureType(MeasureType::MATCH_CONTENT); + auto pipeline = PipelineContext::GetCurrentContext(); + CHECK_NULL_VOID(pipeline); + pipeline->AddOnAreaChangeNode(GetHost()->GetId()); } -bool FormLinkPattern::OnDirtyLayoutWrapperSwap(const RefPtr& dirty, const DirtySwapConfig& config) +void FormLinkPattern::OnAreaChangedInner() { - CHECK_NULL_RETURN(dirty, false); - auto geometryNode = dirty->GetGeometryNode(); - CHECK_NULL_RETURN(geometryNode, false); - formLinkInfo_.SetFomLinkRect(geometryNode->GetFrameRect()); + auto host = GetHost(); + CHECK_NULL_VOID(host); + auto geometryNode = host->GetGeometryNode(); + CHECK_NULL_VOID(geometryNode); + auto linkRect = geometryNode->GetFrameRect(); + linkRect.SetOffset(GetHost()->GetTransformRelativeOffset()); + formLinkInfo_.SetFomLinkRect(linkRect); auto pipeline = PipelineContext::GetCurrentContext(); - CHECK_NULL_RETURN(pipeline, false); - pipeline->AddFormLinkInfo(formLinkInfo_.ToString()); - return false; + CHECK_NULL_VOID(pipeline); + pipeline->AddFormLinkInfo(host->GetId(), formLinkInfo_.ToString()); + } } // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/pattern/form_link/form_link_pattern.h b/frameworks/core/components_ng/pattern/form_link/form_link_pattern.h index 27d3bbbb31f..b50e78d1e97 100644 --- a/frameworks/core/components_ng/pattern/form_link/form_link_pattern.h +++ b/frameworks/core/components_ng/pattern/form_link/form_link_pattern.h @@ -45,7 +45,7 @@ public: private: void OnAttachToFrameNode() override; - bool OnDirtyLayoutWrapperSwap(const RefPtr& dirty, const DirtySwapConfig& config) override; + void OnAreaChangedInner() override; FormLinkInfo formLinkInfo_; }; diff --git a/frameworks/core/components_ng/pattern/gauge/gauge_layout_algorithm.cpp b/frameworks/core/components_ng/pattern/gauge/gauge_layout_algorithm.cpp index aefe2d05095..7f98e10350c 100644 --- a/frameworks/core/components_ng/pattern/gauge/gauge_layout_algorithm.cpp +++ b/frameworks/core/components_ng/pattern/gauge/gauge_layout_algorithm.cpp @@ -28,18 +28,10 @@ void GaugeLayoutAlgorithm::OnReset() {} std::optional GaugeLayoutAlgorithm::MeasureContent( const LayoutConstraintF& contentConstraint, LayoutWrapper* layoutWrapper) { - auto frameNode = layoutWrapper->GetHostNode(); - CHECK_NULL_RETURN(frameNode, std::nullopt); - auto pipeline = PipelineBase::GetCurrentContext(); - CHECK_NULL_RETURN(pipeline, std::nullopt); - auto gaugeTheme = pipeline->GetTheme(); - CHECK_NULL_RETURN(gaugeTheme, std::nullopt); - auto defaultThickness = gaugeTheme->GetTrackWidth().ConvertToPx(); - if ((NearEqual(contentConstraint.maxSize.Width(), Size::INFINITE_SIZE))) { - return SizeF(defaultThickness, defaultThickness); - } if (contentConstraint.selfIdealSize.IsValid()) { - return contentConstraint.selfIdealSize.ConvertToSizeT(); + auto len = + std::min(contentConstraint.selfIdealSize.Height().value(), contentConstraint.selfIdealSize.Width().value()); + return SizeF(len, len); } if (contentConstraint.selfIdealSize.Width().has_value() && NonNegative(contentConstraint.selfIdealSize.Width().value())) { @@ -51,8 +43,21 @@ std::optional GaugeLayoutAlgorithm::MeasureContent( auto height = contentConstraint.selfIdealSize.Height().value(); return SizeF(height, height); } - auto len = std::min(contentConstraint.maxSize.Height(), contentConstraint.maxSize.Width()); - return SizeF(len, len); + auto pipeline = PipelineBase::GetCurrentContext(); + CHECK_NULL_RETURN(pipeline, std::nullopt); + auto gaugeTheme = pipeline->GetTheme(); + CHECK_NULL_RETURN(gaugeTheme, std::nullopt); + auto defaultThickness = gaugeTheme->GetTrackWidth().ConvertToPx(); + auto size = SizeF(defaultThickness, defaultThickness); + size.Constrain(contentConstraint.minSize, contentConstraint.maxSize); + auto padding = layoutWrapper->GetLayoutProperty()->CreatePaddingAndBorder(); + MinusPaddingToSize(padding, size); + if (!NearEqual(size.Width(), size.Height())) { + auto length = std::min(size.Width(), size.Height()); + size.SetWidth(length); + size.SetHeight(length); + } + return size; } -} // namespace OHOS::Ace::NG \ No newline at end of file +} // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/pattern/gauge/gauge_paint_method.cpp b/frameworks/core/components_ng/pattern/gauge/gauge_paint_method.cpp index fa66901d2d0..d2f0da64c4d 100644 --- a/frameworks/core/components_ng/pattern/gauge/gauge_paint_method.cpp +++ b/frameworks/core/components_ng/pattern/gauge/gauge_paint_method.cpp @@ -46,10 +46,10 @@ void GaugePaintMethod::Paint(RSCanvas& canvas, PaintWrapper* paintWrapper) const auto pipelineContext = PipelineBase::GetCurrentContext(); CHECK_NULL_VOID(pipelineContext); auto offset = paintWrapper->GetContentOffset(); - auto frameSize = paintWrapper->GetGeometryNode()->GetFrameSize(); + auto contentSize = paintWrapper->GetContentSize(); RenderRingInfo data; - data.radius = std::min(frameSize.Width(), frameSize.Height()) / 2.0f; - data.center = Offset(frameSize.Width() / 2.0f + offset.GetX(), frameSize.Height() / 2.0f + offset.GetY()); + data.radius = std::min(contentSize.Width(), contentSize.Height()) / 2.0f; + data.center = Offset(contentSize.Width() / 2.0f + offset.GetX(), contentSize.Height() / 2.0f + offset.GetY()); float startAngle = DEFAULT_START_DEGREE; float endAngle = DEFAULT_END_DEGREE; if (paintProperty->GetStartAngle().has_value() && !std::isnan(paintProperty->GetStartAngle().value())) { diff --git a/frameworks/core/components_ng/pattern/grid/grid_pattern.cpp b/frameworks/core/components_ng/pattern/grid/grid_pattern.cpp index ec80ddff889..79f3eb7e0c3 100644 --- a/frameworks/core/components_ng/pattern/grid/grid_pattern.cpp +++ b/frameworks/core/components_ng/pattern/grid/grid_pattern.cpp @@ -426,7 +426,7 @@ void GridPattern::ProcessEvent(bool indexChanged, float finalOffset, float curre onScroll(offsetVP, ScrollState::SCROLL); onScroll(0.0_vp, ScrollState::IDLE); } else if (source == SCROLL_FROM_ANIMATION || source == SCROLL_FROM_ANIMATION_SPRING || - source == SCROLL_FROM_ANIMATION_CONTROLLER) { + source == SCROLL_FROM_ANIMATION_CONTROLLER || source == SCROLL_FROM_BAR_FLING) { onScroll(offsetVP, ScrollState::FLING); onScroll(0.0_vp, ScrollState::IDLE); } else { @@ -440,7 +440,7 @@ void GridPattern::ProcessEvent(bool indexChanged, float finalOffset, float curre if (source == SCROLL_FROM_UPDATE || source == SCROLL_FROM_AXIS || source == SCROLL_FROM_BAR) { onScroll(offsetVP, ScrollState::SCROLL); } else if (source == SCROLL_FROM_ANIMATION || source == SCROLL_FROM_ANIMATION_SPRING || - source == SCROLL_FROM_ANIMATION_CONTROLLER) { + source == SCROLL_FROM_ANIMATION_CONTROLLER || source == SCROLL_FROM_BAR_FLING) { onScroll(offsetVP, ScrollState::FLING); } else { onScroll(offsetVP, ScrollState::IDLE); @@ -455,24 +455,41 @@ void GridPattern::ProcessEvent(bool indexChanged, float finalOffset, float curre } auto onReachStart = gridEventHub->GetOnReachStart(); - // want to call onReachStart(), must be: - // onReachStart function pointer existing, - // first time to reach top: currentOffset equal to 0, - // Or Spring end to reach top again: reachStart_ is true and last time reachStart_ is false. - if (onReachStart && gridLayoutInfo_.startIndex_ == 0 && - (NearZero(gridLayoutInfo_.currentOffset_) || (gridLayoutInfo_.reachStart_ && !reachStart))) { + if (onReachStart && gridLayoutInfo_.startIndex_ == 0) { + if ((scrollState_ == SCROLL_FROM_UPDATE || scrollState_ == SCROLL_FROM_ANIMATION_SPRING || + scrollState_ == SCROLL_FROM_ANIMATION) && + gridLayoutInfo_.reachStart_ && !reachStart && !NearZero(gridLayoutInfo_.currentOffset_)) { + onReachStart(); + initialIndex_ = true; + } + if (scrollState_ == SCROLL_FROM_ANIMATION_SPRING && NearZero(gridLayoutInfo_.currentOffset_)) { + onReachStart(); + initialIndex_ = true; + } + if (!NearZero(gridLayoutInfo_.currentOffset_)) { + offsetCount_++; + } + if (scrollState_ == SCROLL_FROM_NONE && reachStart && NearZero(gridLayoutInfo_.currentOffset_) && + offsetCount_ > 1) { + onReachStart(); + initialIndex_ = true; + offsetCount_ = 0; + } + } + if (onReachStart && !initialIndex_ && gridLayoutInfo_.startIndex_ == 0) { onReachStart(); + initialIndex_ = true; } auto onReachEnd = gridEventHub->GetOnReachEnd(); - // want to call onReachEnd(), must be: - // onReachEnd function pointer existing and endIndex_ equal to sub windows count, - // first time to reach bottom: reachEnd_ is true and offsetEnd_ is different from last time, - // Or spring end to reach bottom again: reachEnd_ is false and offsetEnd_ is false. - if (onReachEnd && gridLayoutInfo_.endIndex_ == (gridLayoutInfo_.childrenCount_ - 1) && - ((gridLayoutInfo_.reachEnd_ && gridLayoutInfo_.offsetEnd_ != offsetEnd) || - (!gridLayoutInfo_.reachEnd_ && !gridLayoutInfo_.offsetEnd_))) { - onReachEnd(); + if (onReachEnd && gridLayoutInfo_.endIndex_ == (gridLayoutInfo_.childrenCount_ - 1)) { + if (gridLayoutInfo_.reachEnd_ && gridLayoutInfo_.offsetEnd_ != offsetEnd) { + onReachEnd(); + } + if (scrollState_ == SCROLL_FROM_ANIMATION_SPRING && !gridLayoutInfo_.reachEnd_ && + !gridLayoutInfo_.offsetEnd_) { + onReachEnd(); + } } if (scrollStop_) { @@ -527,7 +544,7 @@ void GridPattern::FlushCurrentFocus() } } if (gridLayoutInfo_.gridMatrix_.find(lastFocusItemMainIndex_) == gridLayoutInfo_.gridMatrix_.end()) { - LOGE("Can not find last focus item main index: %{public}d", lastFocusItemMainIndex_); + LOGD("Can not find last focus item main index: %{public}d", lastFocusItemMainIndex_); return; } auto curCrossNum = GetCrossCount(); @@ -842,7 +859,7 @@ WeakPtr GridPattern::GetChildFocusNodeByIndex(int32_t tarMainIndex, in } } } - LOGW("Item at location(%{public}d,%{public}d / %{public}d) can not found.", tarMainIndex, tarCrossIndex, tarIndex); + LOGD("Item at location(%{public}d,%{public}d / %{public}d) can not found.", tarMainIndex, tarCrossIndex, tarIndex); return nullptr; } @@ -1119,6 +1136,44 @@ float GridPattern::EstimateHeight() const return height; } +float GridPattern::GetTotalHeight() const +{ + auto host = GetHost(); + CHECK_NULL_RETURN_NOLOG(host, 0.0f); + auto geometryNode = host->GetGeometryNode(); + CHECK_NULL_RETURN_NOLOG(geometryNode, 0.0f); + auto viewScopeSize = geometryNode->GetPaddingSize(); + auto layoutProperty = host->GetLayoutProperty(); + float heightSum = 0; + int32_t itemCount = 0; + float estimatedHeight = 0.f; + if (scrollbarInfo_.first.has_value() && scrollbarInfo_.second.has_value()) { + estimatedHeight = scrollbarInfo_.second.value(); + } else { + auto mainGap = GridUtils::GetMainGap(layoutProperty, viewScopeSize, gridLayoutInfo_.axis_); + for (const auto& item : gridLayoutInfo_.lineHeightMap_) { + auto line = gridLayoutInfo_.gridMatrix_.find(item.first); + if (line == gridLayoutInfo_.gridMatrix_.end()) { + continue; + } + if (line->second.empty()) { + continue; + } + auto lineStart = line->second.begin()->second; + auto lineEnd = line->second.rbegin()->second; + itemCount += (lineEnd - lineStart + 1); + heightSum += item.second + mainGap; + } + auto averageHeight = heightSum / itemCount; + if (itemCount >= (gridLayoutInfo_.childrenCount_ - 1)) { + estimatedHeight = heightSum - mainGap; + } else { + estimatedHeight = heightSum + (gridLayoutInfo_.childrenCount_ - itemCount) * averageHeight; + } + } + return estimatedHeight; +} + void GridPattern::UpdateScrollBarOffset() { if (!GetScrollBar() && !GetScrollBarProxy()) { diff --git a/frameworks/core/components_ng/pattern/grid/grid_pattern.h b/frameworks/core/components_ng/pattern/grid/grid_pattern.h index 301ce267d3c..580b9be9e67 100644 --- a/frameworks/core/components_ng/pattern/grid/grid_pattern.h +++ b/frameworks/core/components_ng/pattern/grid/grid_pattern.h @@ -166,6 +166,8 @@ public: return EstimateHeight(); } + float GetTotalHeight() const override; + void OnAnimateStop() override; void AnimateTo(float position, float duration, const RefPtr& curve, bool smooth) override; @@ -227,6 +229,8 @@ private: RefPtr positionController_; float animatorOffset_ = 0.0f; bool scrollStop_ = false; + bool initialIndex_ = false; + int32_t offsetCount_ = 0; bool supportAnimation_ = false; bool isConfigScrollable_ = false; diff --git a/frameworks/core/components_ng/pattern/grid/grid_position_controller.cpp b/frameworks/core/components_ng/pattern/grid/grid_position_controller.cpp index b4ef8106b7f..6aab4bbdbc9 100644 --- a/frameworks/core/components_ng/pattern/grid/grid_position_controller.cpp +++ b/frameworks/core/components_ng/pattern/grid/grid_position_controller.cpp @@ -51,13 +51,9 @@ void GridPositionController::ScrollToEdge(ScrollEdgeType scrollEdgeType, bool /* CHECK_NULL_VOID(pattern); auto gridPattern = AceType::DynamicCast(pattern); gridPattern->StopAnimate(); - if ((gridPattern->GetGridLayoutInfo().axis_ == Axis::VERTICAL && scrollEdgeType == ScrollEdgeType::SCROLL_TOP) || - (gridPattern->GetGridLayoutInfo().axis_ == Axis::HORIZONTAL && scrollEdgeType == ScrollEdgeType::SCROLL_LEFT)) { + if (scrollEdgeType == ScrollEdgeType::SCROLL_TOP) { gridPattern->UpdateStartIndex(0); - } else if ((gridPattern->GetGridLayoutInfo().axis_ == Axis::VERTICAL && - scrollEdgeType == ScrollEdgeType::SCROLL_BOTTOM) || - (gridPattern->GetGridLayoutInfo().axis_ == Axis::HORIZONTAL && - scrollEdgeType == ScrollEdgeType::SCROLL_RIGHT)) { + } else if (scrollEdgeType == ScrollEdgeType::SCROLL_BOTTOM) { gridPattern->UpdateStartIndex(gridPattern->GetGridLayoutInfo().childrenCount_ - 1); } } diff --git a/frameworks/core/components_ng/pattern/grid/grid_scroll/grid_scroll_layout_algorithm.cpp b/frameworks/core/components_ng/pattern/grid/grid_scroll/grid_scroll_layout_algorithm.cpp index e7bae5e200d..01ecbe3f3b3 100644 --- a/frameworks/core/components_ng/pattern/grid/grid_scroll/grid_scroll_layout_algorithm.cpp +++ b/frameworks/core/components_ng/pattern/grid/grid_scroll/grid_scroll_layout_algorithm.cpp @@ -83,21 +83,21 @@ void GridScrollLayoutAlgorithm::UpdateOffsetOnVirtualKeyboardHeightChange(Layout } auto grid = layoutWrapper->GetHostNode(); - CHECK_NULL_VOID(grid); + CHECK_NULL_VOID_NOLOG(grid); auto focusHub = grid->GetFocusHub(); - CHECK_NULL_VOID(focusHub); + CHECK_NULL_VOID_NOLOG(focusHub); // textField not in Grid if (!focusHub->IsCurrentFocus()) { return; } auto context = PipelineContext::GetCurrentContext(); - CHECK_NULL_VOID(context); + CHECK_NULL_VOID_NOLOG(context); auto textFieldManager = AceType::DynamicCast(context->GetTextFieldManager()); - CHECK_NULL_VOID(textFieldManager); + CHECK_NULL_VOID_NOLOG(textFieldManager); // only when textField is onFocus auto focused = textFieldManager->GetOnFocusTextField().Upgrade(); - CHECK_NULL_VOID(focused); + CHECK_NULL_VOID_NOLOG(focused); auto position = textFieldManager->GetClickPosition().GetY(); auto gridOffset = grid->GetTransformRelativeOffset(); auto offset = mainSize + gridOffset.GetY() - position; @@ -202,8 +202,15 @@ void GridScrollLayoutAlgorithm::Layout(LayoutWrapper* layoutWrapper) } auto frSize = itemsCrossSize_.at(iter->first); SizeF blockSize = gridLayoutProperty->IsVertical() ? SizeF(frSize, lineHeight) : SizeF(lineHeight, frSize); - auto translate = Alignment::GetAlignPosition( - blockSize, wrapper->GetGeometryNode()->GetMarginFrameSize(), Alignment::TOP_CENTER); + auto translate = OffsetF(0.0f, 0.0f); + if (axis_ == Axis::VERTICAL) { + translate = Alignment::GetAlignPosition( + blockSize, wrapper->GetGeometryNode()->GetMarginFrameSize(), Alignment::TOP_CENTER); + } else { + translate = Alignment::GetAlignPosition( + blockSize, wrapper->GetGeometryNode()->GetMarginFrameSize(), Alignment::CENTER_LEFT); + } + wrapper->GetGeometryNode()->SetMarginFrameOffset(offset + translate); wrapper->Layout(); auto layoutProperty = wrapper->GetLayoutProperty(); @@ -394,6 +401,8 @@ void GridScrollLayoutAlgorithm::ModifyCurrentOffsetWhenReachEnd(float mainSize) gridLayoutInfo_.currentOffset_ = 0; gridLayoutInfo_.prevOffset_ = 0; } + gridLayoutInfo_.reachStart_ = true; + gridLayoutInfo_.offsetEnd_ = true; return; } @@ -460,27 +469,29 @@ OffsetF GridScrollLayoutAlgorithm::CalculateLargeItemOffset( bool GridScrollLayoutAlgorithm::NeedAdjust(const RefPtr& itemLayoutProperty) { bool needAdjust = false; + auto main = axis_ == Axis::VERTICAL ? mainCount_: crossCount_; + auto cross = axis_ == Axis::VERTICAL ? crossCount_: mainCount_; if (itemLayoutProperty->GetRowStart().has_value()) { currentItemRowStart_ = itemLayoutProperty->GetRowStart().value_or(-1); - if ((currentItemRowStart_ < 0) || (currentItemRowStart_ >= static_cast(mainCount_))) { + if ((currentItemRowStart_ < 0) || (currentItemRowStart_ >= static_cast(main))) { needAdjust = true; } } if (itemLayoutProperty->GetRowEnd().has_value()) { currentItemRowEnd_ = itemLayoutProperty->GetRowEnd().value_or(-1); - if ((currentItemRowEnd_ < 0) || (currentItemRowEnd_ >= static_cast(mainCount_))) { + if ((currentItemRowEnd_ < 0) || (currentItemRowEnd_ >= static_cast(main))) { needAdjust = true; } } if (itemLayoutProperty->GetColumnStart().has_value()) { currentItemColStart_ = itemLayoutProperty->GetColumnStart().value_or(-1); - if ((currentItemColStart_ < 0) || (currentItemColStart_ >= static_cast(crossCount_))) { + if ((currentItemColStart_ < 0) || (currentItemColStart_ >= static_cast(cross))) { needAdjust = true; } } if (itemLayoutProperty->GetColumnEnd().has_value()) { currentItemColEnd_ = itemLayoutProperty->GetColumnEnd().value_or(-1); - if ((currentItemColEnd_ < 0) || (currentItemColEnd_ >= static_cast(crossCount_))) { + if ((currentItemColEnd_ < 0) || (currentItemColEnd_ >= static_cast(cross))) { needAdjust = true; } } @@ -1388,7 +1399,9 @@ int32_t GridScrollLayoutAlgorithm::GetStartingItem(LayoutWrapper* layoutWrapper, } auto childLayoutProperty = DynamicCast(childLayoutWrapper->GetLayoutProperty()); CHECK_NULL_RETURN(childLayoutProperty, 0); - auto crossIndex = childLayoutProperty->GetCustomCrossIndex(axis_); + + AdjustRowColSpan(childLayoutWrapper); + auto crossIndex = axis_ == Axis::VERTICAL ? currentItemColStart_ : currentItemRowStart_; if (crossIndex == 0) { firstIndex = index; break; @@ -1405,7 +1418,8 @@ int32_t GridScrollLayoutAlgorithm::GetStartingItem(LayoutWrapper* layoutWrapper, } auto childLayoutProperty = DynamicCast(childLayoutWrapper->GetLayoutProperty()); CHECK_NULL_RETURN(childLayoutProperty, 0); - auto crossIndex = childLayoutProperty->GetCustomCrossIndex(axis_); + AdjustRowColSpan(childLayoutWrapper); + auto crossIndex = axis_ == Axis::VERTICAL ? currentItemColStart_ : currentItemRowStart_; // Grid may change from no big item to has big item if (crossIndex >= 0) { gridLayoutInfo_.hasBigItem_ = true; diff --git a/frameworks/core/components_ng/pattern/grid_row/grid_row_layout_algorithm.cpp b/frameworks/core/components_ng/pattern/grid_row/grid_row_layout_algorithm.cpp index a4d90e40977..21f44a5e628 100644 --- a/frameworks/core/components_ng/pattern/grid_row/grid_row_layout_algorithm.cpp +++ b/frameworks/core/components_ng/pattern/grid_row/grid_row_layout_algorithm.cpp @@ -91,11 +91,7 @@ void GridRowLayoutAlgorithm::MeasureSelf(LayoutWrapper* layoutWrapper, float chi auto padding = layoutProperty->CreatePaddingAndBorder(); auto idealSize = CreateIdealSize(layoutConstraint.value(), Axis::HORIZONTAL, MeasureType::MATCH_PARENT); - const auto& calcLayoutConstraint = layoutWrapper->GetLayoutProperty()->GetCalcLayoutConstraint(); - if (!(calcLayoutConstraint && calcLayoutConstraint->selfIdealSize.has_value() && - calcLayoutConstraint->selfIdealSize->Height().has_value())) { - idealSize.SetHeight(childHeight + padding.Height()); - } + idealSize.SetHeight(childHeight + padding.Height()); if (PipelineBase::GetCurrentContext() && PipelineBase::GetCurrentContext()->GetMinPlatformVersion() <= 9) { idealSize.Constrain(layoutConstraint->minSize, layoutConstraint->maxSize); @@ -151,6 +147,8 @@ float GridRowLayoutAlgorithm::MeasureChildren(LayoutWrapper* layoutWrapper, doub ideaSize.SetWidth(columnUnitWidth * span + (span - 1) * gutter.first); LayoutConstraintF parentConstraint = layoutWrapper->GetLayoutProperty()->CreateChildConstraint(); parentConstraint.UpdateSelfMarginSizeWithCheck(ideaSize); + // the max size need to minus the already allocated height. + parentConstraint.maxSize.MinusHeight(totalHeight); child->Measure(parentConstraint); if (newLineOffset.newLineCount > 0) { diff --git a/frameworks/core/components_ng/pattern/image/image_pattern.cpp b/frameworks/core/components_ng/pattern/image/image_pattern.cpp index 3808a5b511d..c1abc033c10 100644 --- a/frameworks/core/components_ng/pattern/image/image_pattern.cpp +++ b/frameworks/core/components_ng/pattern/image/image_pattern.cpp @@ -159,22 +159,22 @@ void ImagePattern::OnImageLoadSuccess() { auto host = GetHost(); CHECK_NULL_VOID(host); - const auto& layoutWrapper = host->GetLayoutWrapper().Upgrade(); - const auto& geometryNode = layoutWrapper == nullptr ? host->GetGeometryNode() : layoutWrapper->GetGeometryNode(); + const auto& geometryNode = host->GetGeometryNode(); CHECK_NULL_VOID(geometryNode); - // update src data + image_ = loadingCtx_->MoveCanvasImage(); srcRect_ = loadingCtx_->GetSrcRect(); dstRect_ = loadingCtx_->GetDstRect(); RectF paintRect = CalcImageContentPaintSize(geometryNode); - LoadImageSuccessEvent loadImageSuccessEvent_(loadingCtx_->GetImageSize().Width(), + LoadImageSuccessEvent event(loadingCtx_->GetImageSize().Width(), loadingCtx_->GetImageSize().Height(), geometryNode->GetFrameSize().Width(), geometryNode->GetFrameSize().Height(), 1, paintRect.Width(), paintRect.Height(), paintRect.GetX(), paintRect.GetY()); - auto imageEventHub = GetEventHub(); - CHECK_NULL_VOID(imageEventHub); - imageEventHub->FireCompleteEvent(loadImageSuccessEvent_); + auto eventHub = GetEventHub(); + if (eventHub) { + eventHub->FireCompleteEvent(event); + } SetImagePaintConfig(image_, srcRect_, dstRect_, loadingCtx_->GetSourceInfo().IsSvg()); PrepareAnimation(image_); @@ -198,12 +198,12 @@ void ImagePattern::OnImageDataReady() CHECK_NULL_VOID(geometryNode); auto imageEventHub = GetEventHub(); CHECK_NULL_VOID(imageEventHub); - LoadImageSuccessEvent loadImageSuccessEvent_(loadingCtx_->GetImageSize().Width(), + LoadImageSuccessEvent event(loadingCtx_->GetImageSize().Width(), loadingCtx_->GetImageSize().Height(), geometryNode->GetFrameSize().Width(), geometryNode->GetFrameSize().Height(), 0, geometryNode->GetContentSize().Width(), geometryNode->GetContentSize().Height(), geometryNode->GetContentOffset().GetX(), geometryNode->GetContentOffset().GetY()); - imageEventHub->FireCompleteEvent(loadImageSuccessEvent_); + imageEventHub->FireCompleteEvent(event); if (!geometryNode->GetContent() || (geometryNode->GetContent() && altLoadingCtx_)) { host->MarkDirtyNode(PROPERTY_UPDATE_MEASURE); diff --git a/frameworks/core/components_ng/pattern/image/image_pattern.h b/frameworks/core/components_ng/pattern/image/image_pattern.h index 72ddb0a4ce3..5bd70ca8ccc 100644 --- a/frameworks/core/components_ng/pattern/image/image_pattern.h +++ b/frameworks/core/components_ng/pattern/image/image_pattern.h @@ -40,6 +40,11 @@ public: ImagePattern() = default; ~ImagePattern() override = default; + std::optional GetContextParam() const override + { + return RenderContext::ContextParam { RenderContext::ContextType::CANVAS }; + } + RefPtr CreateNodePaintMethod() override; RefPtr CreateLayoutProperty() override diff --git a/frameworks/core/components_ng/pattern/indexer/indexer_layout_property.h b/frameworks/core/components_ng/pattern/indexer/indexer_layout_property.h index 36d0f4eac75..170fe747d8f 100644 --- a/frameworks/core/components_ng/pattern/indexer/indexer_layout_property.h +++ b/frameworks/core/components_ng/pattern/indexer/indexer_layout_property.h @@ -79,10 +79,10 @@ public: void ToJsonValue(std::unique_ptr& json) const override; ACE_DEFINE_PROPERTY_ITEM_WITHOUT_GROUP(ArrayValue, std::vector, PROPERTY_UPDATE_MEASURE); - ACE_DEFINE_PROPERTY_ITEM_WITHOUT_GROUP(Selected, int32_t, PROPERTY_UPDATE_MEASURE); - ACE_DEFINE_PROPERTY_ITEM_WITHOUT_GROUP(Color, Color, PROPERTY_UPDATE_MEASURE); - ACE_DEFINE_PROPERTY_ITEM_WITHOUT_GROUP(SelectedColor, Color, PROPERTY_UPDATE_MEASURE); - ACE_DEFINE_PROPERTY_ITEM_WITHOUT_GROUP(PopupColor, Color, PROPERTY_UPDATE_MEASURE); + ACE_DEFINE_PROPERTY_ITEM_WITHOUT_GROUP(Selected, int32_t, PROPERTY_UPDATE_MEASURE_SELF); + ACE_DEFINE_PROPERTY_ITEM_WITHOUT_GROUP(Color, Color, PROPERTY_UPDATE_MEASURE_SELF); + ACE_DEFINE_PROPERTY_ITEM_WITHOUT_GROUP(SelectedColor, Color, PROPERTY_UPDATE_MEASURE_SELF); + ACE_DEFINE_PROPERTY_ITEM_WITHOUT_GROUP(PopupColor, Color, PROPERTY_UPDATE_MEASURE_SELF); ACE_DEFINE_PROPERTY_ITEM_WITHOUT_GROUP(UsingPopup, bool, PROPERTY_UPDATE_MEASURE); ACE_DEFINE_PROPERTY_ITEM_WITHOUT_GROUP(SelectedFont, TextStyle, PROPERTY_UPDATE_MEASURE); ACE_DEFINE_PROPERTY_ITEM_WITHOUT_GROUP(PopupFont, TextStyle, PROPERTY_UPDATE_MEASURE); diff --git a/frameworks/core/components_ng/pattern/indexer/indexer_model_ng.cpp b/frameworks/core/components_ng/pattern/indexer/indexer_model_ng.cpp index 6cf4b95faa1..ac99b36595d 100644 --- a/frameworks/core/components_ng/pattern/indexer/indexer_model_ng.cpp +++ b/frameworks/core/components_ng/pattern/indexer/indexer_model_ng.cpp @@ -16,6 +16,7 @@ #include "core/components_ng/pattern/indexer/indexer_model_ng.h" #include "base/geometry/dimension.h" +#include "core/components/indexer/indexer_theme.h" #include "core/components_ng/base/view_abstract.h" #include "core/components_ng/base/view_stack_processor.h" #include "core/components_ng/pattern/indexer/indexer_pattern.h" @@ -34,6 +35,10 @@ void IndexerModelNG::Create(std::vector& arrayValue, int32_t select frameNode->Clean(); int32_t indexerSize = arrayValue.size(); + auto pipeline = PipelineContext::GetCurrentContext(); + CHECK_NULL_VOID(pipeline); + auto indexerTheme = pipeline->GetTheme(); + CHECK_NULL_VOID(indexerTheme); for (int32_t index = 0; index < indexerSize; index++) { auto indexerChildNode = FrameNode::CreateFrameNode( V2::TEXT_ETS_TAG, ElementRegister::GetInstance()->MakeUniqueId(), AceType::MakeRefPtr()); @@ -41,6 +46,20 @@ void IndexerModelNG::Create(std::vector& arrayValue, int32_t select auto textLayoutProperty = indexerChildNode->GetLayoutProperty(); CHECK_NULL_VOID(textLayoutProperty); textLayoutProperty->UpdateContent(arrayValue[index]); + Dimension borderWidth; + textLayoutProperty->UpdateBorderWidth({ borderWidth, borderWidth, borderWidth, borderWidth }); + auto defaultFont = indexerTheme->GetDefaultTextStyle(); + textLayoutProperty->UpdateFontSize(defaultFont.GetFontSize()); + textLayoutProperty->UpdateFontWeight(defaultFont.GetFontWeight()); + textLayoutProperty->UpdateFontFamily(defaultFont.GetFontFamilies()); + textLayoutProperty->UpdateItalicFontStyle(defaultFont.GetFontStyle()); + textLayoutProperty->UpdateTextColor(indexerTheme->GetDefaultTextColor()); + auto childRenderContext = indexerChildNode->GetRenderContext(); + CHECK_NULL_VOID(childRenderContext); + childRenderContext->ResetBlendBorderColor(); + childRenderContext->UpdateBackgroundColor(Color::TRANSPARENT); + Dimension radiusZeroSize; + childRenderContext->UpdateBorderRadius({ radiusZeroSize, radiusZeroSize, radiusZeroSize, radiusZeroSize }); frameNode->AddChild(indexerChildNode); } stack->Push(frameNode); diff --git a/frameworks/core/components_ng/pattern/indexer/indexer_pattern.cpp b/frameworks/core/components_ng/pattern/indexer/indexer_pattern.cpp index ce60bc6dd09..3878c1ff8b7 100644 --- a/frameworks/core/components_ng/pattern/indexer/indexer_pattern.cpp +++ b/frameworks/core/components_ng/pattern/indexer/indexer_pattern.cpp @@ -432,8 +432,6 @@ void IndexerPattern::ApplyIndexChanged(bool selectChanged, bool fromTouchUp) CHECK_NULL_VOID(host); auto layoutProperty = host->GetLayoutProperty(); CHECK_NULL_VOID(layoutProperty); - auto indexerEventHub = host->GetEventHub(); - CHECK_NULL_VOID(indexerEventHub); auto paintProperty = host->GetPaintProperty(); CHECK_NULL_VOID(paintProperty); @@ -516,7 +514,7 @@ void IndexerPattern::ApplyIndexChanged(bool selectChanged, bool fromTouchUp) if (selectChanged || NeedShowPopupView()) { ShowBubble(); } - host->MarkDirtyNode(PROPERTY_UPDATE_MEASURE); + host->MarkDirtyNode(); } void IndexerPattern::ShowBubble() @@ -738,6 +736,7 @@ void IndexerPattern::CreateBubbleListView(std::vector& currentListD auto textNode = FrameNode::CreateFrameNode( V2::TEXT_ETS_TAG, ElementRegister::GetInstance()->MakeUniqueId(), AceType::MakeRefPtr()); listItemNode->AddChild(textNode); + AddListItemClickListener(listItemNode, i); listNode->AddChild(listItemNode); } } @@ -770,7 +769,6 @@ void IndexerPattern::UpdateBubbleListItem( listItemProperty->UpdateAlignment(Alignment::CENTER); auto listItemContext = listItemNode->GetRenderContext(); CHECK_NULL_VOID(listItemContext); - AddListItemClickListener(listItemNode, i); auto textNode = DynamicCast(listItemNode->GetFirstChild()); CHECK_NULL_VOID(textNode); auto textLayoutProperty = textNode->GetLayoutProperty(); diff --git a/frameworks/core/components_ng/pattern/list/list_item_group_layout_algorithm.cpp b/frameworks/core/components_ng/pattern/list/list_item_group_layout_algorithm.cpp index 26bd9b30bd0..35fdc3c4099 100644 --- a/frameworks/core/components_ng/pattern/list/list_item_group_layout_algorithm.cpp +++ b/frameworks/core/components_ng/pattern/list/list_item_group_layout_algorithm.cpp @@ -164,6 +164,7 @@ void ListItemGroupLayoutAlgorithm::UpdateListItemConstraint(const OptionalSizeF& float crossSize = crossSizeOptional.value(); if (lanes_ > 1) { crossSize = (crossSize + laneGutter_) / lanes_ - laneGutter_; + crossSize = crossSize <= 0 ? 1 : crossSize; } if (maxLaneLength_.has_value() && maxLaneLength_.value() < crossSize) { crossSize = maxLaneLength_.value(); @@ -293,7 +294,7 @@ void ListItemGroupLayoutAlgorithm::MeasureListItem( layoutWrapper->RemoveAllChildInRenderTree(); jumpIndex_.reset(); } else if (!itemPosition_.empty()) { - if (itemPosition_.begin()->first > 0) { + if (itemPosition_.begin()->first > 0 || (forwardLayout_ && Negative(referencePos_))) { startPos = itemPosition_.begin()->second.first; } endPos = itemPosition_.rbegin()->second.second; diff --git a/frameworks/core/components_ng/pattern/list/list_lanes_layout_algorithm.cpp b/frameworks/core/components_ng/pattern/list/list_lanes_layout_algorithm.cpp index a0adf3025bd..d0330f7d7c6 100644 --- a/frameworks/core/components_ng/pattern/list/list_lanes_layout_algorithm.cpp +++ b/frameworks/core/components_ng/pattern/list/list_lanes_layout_algorithm.cpp @@ -33,6 +33,7 @@ void ListLanesLayoutAlgorithm::UpdateListItemConstraint( if (lanes_ > 1) { float laneGutter = GetLaneGutter(); crossSize = (crossSize + laneGutter) / lanes_ - laneGutter; + crossSize = crossSize <= 0 ? 1 : crossSize; } if (maxLaneLength_.has_value() && maxLaneLength_.value() < crossSize) { crossSize = maxLaneLength_.value(); diff --git a/frameworks/core/components_ng/pattern/list/list_pattern.cpp b/frameworks/core/components_ng/pattern/list/list_pattern.cpp index c6416bc595b..9087d24dd0f 100644 --- a/frameworks/core/components_ng/pattern/list/list_pattern.cpp +++ b/frameworks/core/components_ng/pattern/list/list_pattern.cpp @@ -50,6 +50,9 @@ void ListPattern::OnModifyDone() { if (!isInitialized_) { jumpIndex_ = GetLayoutProperty()->GetInitialIndex().value_or(0); + if (NeedScrollSnapAlignEffect()) { + scrollAlign_ = GetScrollAlignByScrollSnapAlign(); + } } auto host = GetHost(); CHECK_NULL_VOID(host); @@ -83,10 +86,6 @@ void ListPattern::OnModifyDone() CHECK_NULL_VOID_NOLOG(focusHub); InitOnKeyEvent(focusHub); SetAccessibilityAction(); - RegistOritationListener(); - if (NeedScrollSnapAlignEffect()) { - UpdateScrollSnap(); - } } bool ListPattern::OnDirtyLayoutWrapperSwap(const RefPtr& dirty, const DirtySwapConfig& config) @@ -204,6 +203,20 @@ bool ListPattern::OnDirtyLayoutWrapperSwap(const RefPtr& dirty, c return true; } +ScrollAlign ListPattern::GetScrollAlignByScrollSnapAlign() const +{ + auto scrollAlign = ScrollAlign::START; + auto host = GetHost(); + CHECK_NULL_RETURN(host, scrollAlign); + auto listProperty = host->GetLayoutProperty(); + CHECK_NULL_RETURN(listProperty, scrollAlign); + auto scrollSnapAlign = listProperty->GetScrollSnapAlign().value_or(V2::ScrollSnapAlign::NONE); + if (scrollSnapAlign == V2::ScrollSnapAlign::CENTER) { + scrollAlign = ScrollAlign::CENTER; + } + return scrollAlign; +} + float ListPattern::CalculateTargetPos(float startPos, float endPos, ScrollAutoType scrollAutoType) { float targetPos = 0.0f; @@ -702,8 +715,10 @@ bool ListPattern::IsOutOfBoundary(bool useCurrentDelta) bool outOfStart = (startIndex_ == 0) && Positive(startPos) && GreatNotEqual(endPos, contentMainSize_); bool outOfEnd = (endIndex_ == maxListItemIndex_) && LessNotEqual(endPos, contentMainSize_) && Negative(startPos); if (IsScrollSnapAlignCenter()) { - outOfStart = outOfStart && Positive(startPos - contentMainSize_ / 2.0f); - outOfEnd = outOfEnd && LessNotEqual(endPos, contentMainSize_ / 2.0f); + auto itemHeight = itemPosition_.begin()->second.endPos - itemPosition_.begin()->second.startPos; + outOfStart = (startIndex_ == 0) && Positive(startPos + itemHeight / 2.0f - contentMainSize_ / 2.0f); + outOfEnd = (endIndex_ == maxListItemIndex_) && + LessNotEqual(endPos - itemHeight / 2.0f, contentMainSize_ / 2.0f); } return outOfStart || outOfEnd; } @@ -776,31 +791,6 @@ bool ListPattern::OnScrollSnapCallback(double targetOffset, double velocity) return true; } -void ListPattern::OnWindowSizeChanged(int32_t width, int32_t height, WindowSizeChangeReason type) -{ - if (!NeedScrollSnapAlignEffect() || type != WindowSizeChangeReason::ROTATION) { - return; - } - auto host = GetHost(); - CHECK_NULL_VOID(host); - jumpIndex_ = GetLayoutProperty()->GetInitialIndex().value_or(0); - UpdateScrollSnap(); - host->MarkDirtyNode(PROPERTY_UPDATE_MEASURE); -} - -void ListPattern::RegistOritationListener() -{ - if (isOritationListenerRegisted_) { - return; - } - isOritationListenerRegisted_ = true; - auto host = GetHost(); - CHECK_NULL_VOID(host); - auto pipeline = PipelineContext::GetCurrentContext(); - CHECK_NULL_VOID(pipeline); - pipeline->AddWindowSizeChangeCallback(host->GetId()); -} - void ListPattern::SetEdgeEffectCallback(const RefPtr& scrollEffect) { scrollEffect->SetCurrentPositionCallback([weak = AceType::WeakClaim(this)]() -> double { @@ -983,8 +973,7 @@ WeakPtr ListPattern::GetNextFocusNode(FocusStep step, const WeakPtr ListPattern::GetNextFocusNode(FocusStep step, const WeakPtr ListPattern::GetNextFocusNode(FocusStep step, const WeakPtr= curListItemGroupPara.itemEndIndex)) { + nextIndex = curIndex + moveStep; + nextIndexInGroup = -1; + } else { + nextIndexInGroup = curIndexInGroup + moveStep; + } + } else if (step == FocusStep::SHIFT_TAB) { + moveStep = -1; + if ((curIndexInGroup == -1) || (curIndexInGroup <= 0)) { + nextIndex = curIndex + moveStep; + nextIndexInGroup = -1; + } else { + nextIndexInGroup = curIndexInGroup + moveStep; + } } } while (nextIndex >= 0 && nextIndex <= maxListItemIndex_) { @@ -1273,6 +1277,16 @@ void ListPattern::UpdateScrollBarOffset() UpdateScrollBarRegion(currentOffset, estimatedHeight, size, viewOffset); } +float ListPattern::GetTotalHeight() const +{ + if (itemPosition_.empty()) { + return 0.0f; + } + + float itemsSize = itemPosition_.rbegin()->second.endPos - itemPosition_.begin()->second.startPos + spaceWidth_; + return itemsSize / itemPosition_.size() * (maxListItemIndex_ + 1); +} + void ListPattern::SetChainAnimation() { auto listLayoutProperty = GetLayoutProperty(); diff --git a/frameworks/core/components_ng/pattern/list/list_pattern.h b/frameworks/core/components_ng/pattern/list/list_pattern.h index 8b502ed4762..8317919d6aa 100644 --- a/frameworks/core/components_ng/pattern/list/list_pattern.h +++ b/frameworks/core/components_ng/pattern/list/list_pattern.h @@ -166,6 +166,8 @@ public: return currentOffset_; } + float GetTotalHeight() const override; + // scroller void AnimateTo(float position, float duration, const RefPtr& curve, bool smooth) override { @@ -241,8 +243,7 @@ private: void SetChainAnimationLayoutAlgorithm( RefPtr listLayoutAlgorithm, RefPtr listLayoutProperty); bool NeedScrollSnapAlignEffect() const; - void OnWindowSizeChanged(int32_t width, int32_t height, WindowSizeChangeReason type) override; - void RegistOritationListener(); + ScrollAlign GetScrollAlignByScrollSnapAlign() const; // multiSelectable void ClearMultiSelect() override; diff --git a/frameworks/core/components_ng/pattern/loading_progress/loading_progress_layout_algorithm.cpp b/frameworks/core/components_ng/pattern/loading_progress/loading_progress_layout_algorithm.cpp index 32cfe90373f..2d1320d7582 100644 --- a/frameworks/core/components_ng/pattern/loading_progress/loading_progress_layout_algorithm.cpp +++ b/frameworks/core/components_ng/pattern/loading_progress/loading_progress_layout_algorithm.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -25,13 +25,16 @@ std::optional LoadingProgressLayoutAlgorithm::MeasureContent( const LayoutConstraintF& contentConstraint, LayoutWrapper* layoutWrapper) { float height_ = (contentConstraint.selfIdealSize.Height()) ? contentConstraint.selfIdealSize.Height().value() - : contentConstraint.maxSize.Height(); + : contentConstraint.percentReference.Height(); float width_ = (contentConstraint.selfIdealSize.Width()) ? contentConstraint.selfIdealSize.Width().value() - : contentConstraint.maxSize.Width(); - height_ = std::min(height_, contentConstraint.maxSize.Height()); - width_ = std::min(width_, contentConstraint.maxSize.Width()); - LOGD("LoadingProgressLayoutAlgorithm::MeasureContent: width_: %{public}fl ,height_: %{public}fl", width_, height_); - return SizeF(width_, height_); + : contentConstraint.percentReference.Width(); + height_ = std::min(height_, contentConstraint.percentReference.Height()); + width_ = std::min(width_, contentConstraint.percentReference.Width()); + auto diameter = std::min(width_, height_); + LOGD("LoadingProgressLayoutAlgorithm::MeasureContent: width_: %{public}fl, height_: %{public}fl, diameter: " + "%{public}fl", + width_, height_, diameter); + return SizeF(diameter, diameter); } -} // namespace OHOS::Ace::NG \ No newline at end of file +} // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/pattern/loading_progress/loading_progress_modifier.cpp b/frameworks/core/components_ng/pattern/loading_progress/loading_progress_modifier.cpp index 8a4b83a7f1f..0a71557f182 100644 --- a/frameworks/core/components_ng/pattern/loading_progress/loading_progress_modifier.cpp +++ b/frameworks/core/components_ng/pattern/loading_progress/loading_progress_modifier.cpp @@ -70,6 +70,8 @@ constexpr float TWO = 2.0f; } // namespace LoadingProgressModifier::LoadingProgressModifier(LoadingProgressOwner loadingProgressOwner) : enableLoading_(AceType::MakeRefPtr(true)), + offset_(AceType::MakeRefPtr(OffsetF())), + contentSize_(AceType::MakeRefPtr(SizeF())), date_(AceType::MakeRefPtr(0.0f)), color_(AceType::MakeRefPtr(LinearColor::BLUE)), centerDeviation_(AceType::MakeRefPtr(0.0f)), @@ -79,6 +81,8 @@ LoadingProgressModifier::LoadingProgressModifier(LoadingProgressOwner loadingPro sizeScale_(AceType::MakeRefPtr(1.0f)), loadingProgressOwner_(loadingProgressOwner) { AttachProperty(enableLoading_); + AttachProperty(offset_); + AttachProperty(contentSize_); AttachProperty(date_); AttachProperty(color_); AttachProperty(centerDeviation_); @@ -94,7 +98,7 @@ void LoadingProgressModifier::onDraw(DrawingContext& context) return; } float date = date_->Get(); - auto diameter = std::min(context.width, context.height); + auto diameter = std::min(contentSize_->Get().Width(), contentSize_->Get().Height()); RingParam ringParam; ringParam.strokeWidth = LoadingProgressUtill::GetRingStrokeWidth(diameter) * sizeScale_->Get(); ringParam.radius = LoadingProgressUtill::GetRingRadius(diameter) * sizeScale_->Get(); @@ -138,7 +142,10 @@ void LoadingProgressModifier::DrawRing(DrawingContext& context, const RingParam& pen.SetWidth(ringParam.strokeWidth); pen.SetAntiAlias(true); canvas.AttachPen(pen); - canvas.DrawCircle({ context.width * HALF, context.height * HALF + ringParam.movement }, ringParam.radius); + canvas.DrawCircle( + { offset_->Get().GetX() + contentSize_->Get().Width() * HALF, + offset_->Get().GetY() + contentSize_->Get().Height() * HALF + ringParam.movement }, + ringParam.radius); canvas.DetachPen(); canvas.Restore(); } @@ -148,8 +155,8 @@ void LoadingProgressModifier::DrawOrbit( { auto pointCounts = cometParam.pointCount; auto& canvas = context.canvas; - float width = context.width; - float height = context.height; + float width = contentSize_->Get().Width(); + float height = contentSize_->Get().Height(); double angle = TOTAL_ANGLE * date / FULL_COUNT; RSCamera3D camera; camera.Save(); @@ -159,7 +166,7 @@ void LoadingProgressModifier::DrawOrbit( RSMatrix matrix; camera.ApplyToMatrix(matrix); camera.Restore(); - auto center = RSPoint(width / 2, height / 2); + auto center = RSPoint(offset_->Get().GetX() + width / 2, offset_->Get().GetY() + height / 2); RSBrush brush; brush.SetAntiAlias(true); canvas.Save(); diff --git a/frameworks/core/components_ng/pattern/loading_progress/loading_progress_modifier.h b/frameworks/core/components_ng/pattern/loading_progress/loading_progress_modifier.h index b679e3a7566..1eab716a182 100644 --- a/frameworks/core/components_ng/pattern/loading_progress/loading_progress_modifier.h +++ b/frameworks/core/components_ng/pattern/loading_progress/loading_progress_modifier.h @@ -68,16 +68,31 @@ public: void SetEnableLoading(bool enable) { - if (enableLoading_) { - enableLoading_->Set(enable); - } + CHECK_NULL_VOID(enableLoading_); + enableLoading_->Set(enable); + } + + void SetContentOffset(const OffsetF& offset) + { + CHECK_NULL_VOID(offset_); + offset_->Set(offset); + } + + void SetContentSize(const SizeF& contentSize) + { + CHECK_NULL_VOID(contentSize_); + contentSize_->Set(contentSize); } private: float GetCurentCometOpacity(float baseOpacity, uint32_t index, uint32_t totalNumber); float GetCurentCometAngle(float baseAngle, uint32_t index, uint32_t totalNumber); uint32_t GetCometNumber(); + // no Animatable RefPtr enableLoading_; + RefPtr offset_; + RefPtr contentSize_; + // Animatable RefPtr date_; RefPtr color_; RefPtr centerDeviation_; diff --git a/frameworks/core/components_ng/pattern/loading_progress/loading_progress_paint_method.h b/frameworks/core/components_ng/pattern/loading_progress/loading_progress_paint_method.h index 4f996c9abee..fd0ed0db590 100644 --- a/frameworks/core/components_ng/pattern/loading_progress/loading_progress_paint_method.h +++ b/frameworks/core/components_ng/pattern/loading_progress/loading_progress_paint_method.h @@ -56,6 +56,8 @@ public: auto paintProperty = DynamicCast(paintWrapper->GetPaintProperty()); CHECK_NULL_VOID(paintProperty); loadingProgressModifier_->SetEnableLoading(paintProperty->GetEnableLoadingValue(true)); + loadingProgressModifier_->SetContentOffset(paintWrapper->GetContentOffset()); + loadingProgressModifier_->SetContentSize(paintWrapper->GetContentSize()); auto renderContext = paintWrapper->GetRenderContext(); CHECK_NULL_VOID(renderContext); if (renderContext->HasForegroundColorStrategy()) { diff --git a/frameworks/core/components_ng/pattern/menu/menu_item/menu_item_pattern.cpp b/frameworks/core/components_ng/pattern/menu/menu_item/menu_item_pattern.cpp index 75bd46f1e31..adcee9d4e54 100644 --- a/frameworks/core/components_ng/pattern/menu/menu_item/menu_item_pattern.cpp +++ b/frameworks/core/components_ng/pattern/menu/menu_item/menu_item_pattern.cpp @@ -83,7 +83,8 @@ void UpdateFontColor(RefPtr& textProperty, RefPtr& node, const std::string& src, const Dimension& size, const Color& color) +void UpdateIconSrc(RefPtr& node, const std::string& src, const Dimension& horizontalSize, + const Dimension& verticalSize, const Color& color) { ImageSourceInfo imageSourceInfo; imageSourceInfo.SetSrc(src); @@ -93,7 +94,7 @@ void UpdateIconSrc(RefPtr& node, const std::string& src, const Dimens CHECK_NULL_VOID(props); props->UpdateImageSourceInfo(imageSourceInfo); props->UpdateAlignment(Alignment::CENTER); - CalcSize idealSize = { CalcLength(size), CalcLength(size) }; + CalcSize idealSize = { CalcLength(horizontalSize), CalcLength(verticalSize) }; MeasureProperty layoutConstraint; layoutConstraint.selfIdealSize = idealSize; props->UpdateCalcLayoutProperty(layoutConstraint); @@ -527,7 +528,8 @@ void MenuItemPattern::AddSelectIcon(RefPtr& row) auto iconPath = userIcon.empty() ? iconTheme->GetIconPath(InternalResource::ResourceId::MENU_OK_SVG) : userIcon; auto selectTheme = pipeline->GetTheme(); CHECK_NULL_VOID(selectTheme); - UpdateIconSrc(selectIcon_, iconPath, selectTheme->GetIconSideLength(), selectTheme->GetMenuIconColor()); + UpdateIconSrc(selectIcon_, iconPath, selectTheme->GetIconSideLength(), selectTheme->GetIconSideLength(), + selectTheme->GetMenuIconColor()); auto renderContext = selectIcon_->GetRenderContext(); CHECK_NULL_VOID(renderContext); @@ -561,7 +563,9 @@ void MenuItemPattern::UpdateIcon(RefPtr& row, bool isStart) CHECK_NULL_VOID(pipeline); auto selectTheme = pipeline->GetTheme(); CHECK_NULL_VOID(selectTheme); - UpdateIconSrc(iconNode, iconSrc, selectTheme->GetIconSideLength(), selectTheme->GetMenuIconColor()); + auto iconWidth = isStart ? selectTheme->GetIconSideLength() : selectTheme->GetEndIconWidth(); + auto iconHeight = isStart ? selectTheme->GetIconSideLength() : selectTheme->GetEndIconHeight(); + UpdateIconSrc(iconNode, iconSrc, iconWidth, iconHeight, selectTheme->GetMenuIconColor()); iconNode->MountToParent(row, ((isStart && selectIcon_) || (!isStart && label_)) ? 1 : 0); iconNode->MarkModifyDone(); diff --git a/frameworks/core/components_ng/pattern/menu/menu_pattern.cpp b/frameworks/core/components_ng/pattern/menu/menu_pattern.cpp index 75a34f3f216..056a5774fdd 100644 --- a/frameworks/core/components_ng/pattern/menu/menu_pattern.cpp +++ b/frameworks/core/components_ng/pattern/menu/menu_pattern.cpp @@ -202,7 +202,7 @@ void MenuPattern::OnTouchEvent(const TouchEventInfo& info) auto touchUpOffset = info.GetTouches().front().GetLocalLocation(); if (lastTouchOffset_.has_value() && (touchUpOffset - lastTouchOffset_.value()).GetDistance() <= DEFAULT_CLICK_DISTANCE) { - HideMenu(); + HideMenu(true); } lastTouchOffset_.reset(); } @@ -321,7 +321,7 @@ void MenuPattern::UpdateSelectParam(const std::vector& params) host->MarkDirtyNode(PROPERTY_UPDATE_MEASURE); } -void MenuPattern::HideMenu() const +void MenuPattern::HideMenu(bool isMenuOnTouch) const { if (IsContextMenu()) { SubwindowManager::GetInstance()->HideMenuNG(targetId_); @@ -331,7 +331,7 @@ void MenuPattern::HideMenu() const CHECK_NULL_VOID(pipeline); auto overlayManager = pipeline->GetOverlayManager(); CHECK_NULL_VOID(overlayManager); - overlayManager->HideMenu(targetId_); + overlayManager->HideMenu(targetId_, isMenuOnTouch); LOGI("MenuPattern closing menu %{public}d", targetId_); } diff --git a/frameworks/core/components_ng/pattern/menu/menu_pattern.h b/frameworks/core/components_ng/pattern/menu/menu_pattern.h index b2b6dde4827..8a002c3da54 100644 --- a/frameworks/core/components_ng/pattern/menu/menu_pattern.h +++ b/frameworks/core/components_ng/pattern/menu/menu_pattern.h @@ -177,7 +177,7 @@ public: void UpdateSelectParam(const std::vector& params); - void HideMenu() const; + void HideMenu(bool isMenuOnTouch = false) const; void MountOption(const RefPtr& option); diff --git a/frameworks/core/components_ng/pattern/menu/wrapper/menu_wrapper_pattern.cpp b/frameworks/core/components_ng/pattern/menu/wrapper/menu_wrapper_pattern.cpp index b184b3a06b0..6bec908f2a2 100644 --- a/frameworks/core/components_ng/pattern/menu/wrapper/menu_wrapper_pattern.cpp +++ b/frameworks/core/components_ng/pattern/menu/wrapper/menu_wrapper_pattern.cpp @@ -204,7 +204,7 @@ void MenuWrapperPattern::SetHotAreas(const RefPtr& layoutWrapper) rects.emplace_back(rect); } - SubwindowManager::GetInstance()->SetHotAreas(rects, GetHost()->GetId()); + SubwindowManager::GetInstance()->SetHotAreas(rects, GetHost()->GetId(), GetContainerId()); } void MenuWrapperPattern::StartShowAnimation() diff --git a/frameworks/core/components_ng/pattern/navigation/nav_bar_layout_algorithm.cpp b/frameworks/core/components_ng/pattern/navigation/nav_bar_layout_algorithm.cpp index 8d49a8fe8ef..384edbf4b18 100644 --- a/frameworks/core/components_ng/pattern/navigation/nav_bar_layout_algorithm.cpp +++ b/frameworks/core/components_ng/pattern/navigation/nav_bar_layout_algorithm.cpp @@ -92,7 +92,7 @@ float MeasureTitleBar(LayoutWrapper* layoutWrapper, const RefPtr& ho if (NearZero(titleBarHeight)) { titleBarHeight = static_cast(FULL_DOUBLE_LINE_TITLEBAR_HEIGHT.ConvertToPx()); } - auto doubleTitleBarHeight = overDragOffset / 6.0f + titleBarHeight; + auto doubleTitleBarHeight = overDragOffset / 6.0f + titleBarHeight; constraint.selfIdealSize = OptionalSizeF(navigationSize.Width(), doubleTitleBarHeight); titleBarWrapper->Measure(constraint); return titleBarHeight; @@ -241,7 +241,7 @@ void LayoutContent(LayoutWrapper* layoutWrapper, const RefPtr& hostN CHECK_NULL_VOID(contentWrapper); auto geometryNode = contentWrapper->GetGeometryNode(); if (!navBarLayoutProperty->GetHideTitleBar().value_or(false)) { - auto contentOffset = OffsetF(geometryNode->GetFrameOffset().GetX(), overDragOffset + titlebarHeight); + auto contentOffset = OffsetF(geometryNode->GetFrameOffset().GetX(), overDragOffset + titlebarHeight); geometryNode->SetMarginFrameOffset(contentOffset); contentWrapper->Layout(); return; diff --git a/frameworks/core/components_ng/pattern/navigation/nav_bar_pattern.cpp b/frameworks/core/components_ng/pattern/navigation/nav_bar_pattern.cpp index 633f347c137..d0a95565bb8 100644 --- a/frameworks/core/components_ng/pattern/navigation/nav_bar_pattern.cpp +++ b/frameworks/core/components_ng/pattern/navigation/nav_bar_pattern.cpp @@ -260,6 +260,8 @@ RefPtr CreateMenuItems(const int32_t menuNodeId, const std::vector(false); }); + CHECK_NULL_RETURN(menuNode, nullptr); + menuNode->Clean(); auto rowProperty = menuNode->GetLayoutProperty(); CHECK_NULL_RETURN(rowProperty, nullptr); rowProperty->UpdateMainAxisAlign(FlexAlign::SPACE_BETWEEN); @@ -423,18 +425,16 @@ void BuildMenu(const RefPtr& navBarNode, const RefPtr& CHECK_NULL_VOID(navBarPattern); auto titleBarMenuItems = navBarPattern->GetTitleBarMenuItems(); auto toolBarMenuItems = navBarPattern->GetToolBarMenuItems(); - if (!navBarPattern->HasMenuNode()) { - auto menuNode = CreateMenuItems(navBarPattern->GetMenuNodeId(), titleBarMenuItems, navBarNode, false); - CHECK_NULL_VOID(menuNode); - navBarNode->SetMenu(menuNode); - } - if (!navBarPattern->HasLandscapeMenuNode()) { - titleBarMenuItems.insert(titleBarMenuItems.end(), toolBarMenuItems.begin(), toolBarMenuItems.end()); - auto landscapeMenuNode = - CreateMenuItems(navBarPattern->GetLandscapeMenuNodeId(), titleBarMenuItems, navBarNode, true); - CHECK_NULL_VOID(landscapeMenuNode); - navBarNode->SetLandscapeMenu(landscapeMenuNode); - } + + auto menuNode = CreateMenuItems(navBarPattern->GetMenuNodeId(), titleBarMenuItems, navBarNode, false); + CHECK_NULL_VOID(menuNode); + navBarNode->SetMenu(menuNode); + + titleBarMenuItems.insert(titleBarMenuItems.end(), toolBarMenuItems.begin(), toolBarMenuItems.end()); + auto landscapeMenuNode = + CreateMenuItems(navBarPattern->GetLandscapeMenuNodeId(), titleBarMenuItems, navBarNode, true); + CHECK_NULL_VOID(landscapeMenuNode); + navBarNode->SetLandscapeMenu(landscapeMenuNode); auto navigationGroupNode = AceType::DynamicCast(navBarNode->GetParent()); CHECK_NULL_VOID(navigationGroupNode); diff --git a/frameworks/core/components_ng/pattern/navigation/nav_bar_pattern.h b/frameworks/core/components_ng/pattern/navigation/nav_bar_pattern.h index 3ff6aa169d0..a22313b876c 100755 --- a/frameworks/core/components_ng/pattern/navigation/nav_bar_pattern.h +++ b/frameworks/core/components_ng/pattern/navigation/nav_bar_pattern.h @@ -75,30 +75,24 @@ public: return toolBarMenuItems_; } - int32_t GetMenuNodeId() + int32_t GetMenuNodeId() const { - if (!menuNodeId_.has_value()) { - menuNodeId_ = ElementRegister::GetInstance()->MakeUniqueId(); - } return menuNodeId_.value(); } - int32_t GetLandscapeMenuNodeId() + int32_t GetLandscapeMenuNodeId() const { - if (!landscapeMenuNodeId_.has_value()) { - landscapeMenuNodeId_ = ElementRegister::GetInstance()->MakeUniqueId(); - } return landscapeMenuNodeId_.value(); } - bool HasMenuNode() const + void SetMenuNodeId(const int32_t menuNodeId) { - return menuNodeId_.has_value(); + menuNodeId_ = menuNodeId; } - bool HasLandscapeMenuNode() const + void SetLandscapeMenuNodeId(const int32_t landscapeMenuNodeId) { - return landscapeMenuNodeId_.has_value(); + landscapeMenuNodeId_ = landscapeMenuNodeId; } protected: diff --git a/frameworks/core/components_ng/pattern/navigation/navigation_declaration.h b/frameworks/core/components_ng/pattern/navigation/navigation_declaration.h index 0ffa37d0335..d2fe6894e98 100644 --- a/frameworks/core/components_ng/pattern/navigation/navigation_declaration.h +++ b/frameworks/core/components_ng/pattern/navigation/navigation_declaration.h @@ -89,14 +89,13 @@ constexpr Dimension DEFAULT_MIN_CONTENT_WIDTH = 360.0_vp; constexpr Dimension FULL_SINGLE_LINE_TITLEBAR_HEIGHT = 112.0_vp; constexpr Dimension FULL_DOUBLE_LINE_TITLEBAR_HEIGHT = 138.0_vp; constexpr Dimension NAV_HORIZONTAL_MARGIN_L = 16.0_vp; // ohos_id_elements_margin_horizontal_l -constexpr Dimension NAV_HORIZONTAL_MARGIN_M = 8.0_vp; // ohos_id_elements_margin_horizontal_m +constexpr Dimension NAV_HORIZONTAL_MARGIN_M = 8.0_vp; // ohos_id_elements_margin_horizontal_m constexpr Dimension MENU_ITEM_PADDING = 24.0_vp; constexpr Dimension BUTTON_PADDING = 12.0_vp; constexpr Dimension BUTTON_RADIUS = 5.0_vp; constexpr Dimension MAX_OVER_DRAG_OFFSET = 180.0_vp; constexpr Dimension DEFAULT_MIN_NAV_BAR_WIDTH = 240.0_vp; -constexpr Dimension DEFAULT_MAX_NAV_BAR_WIDTH = 432.0_vp; -constexpr float MAX_NAV_BAR_WIDTH_SCALE = 0.4f; +constexpr Dimension DEFAULT_MAX_NAV_BAR_WIDTH = 280.0_vp; // more button constexpr Dimension MORE_BUTTON_CORNER_RADIUS = 8.0_vp; @@ -165,15 +164,9 @@ enum class ChildNodeOperation { NONE }; -enum class TitleHeight { - MAIN_ONLY, - MAIN_WITH_SUB -}; +enum class TitleHeight { MAIN_ONLY, MAIN_WITH_SUB }; -enum class TitleBarParentType { - NAVBAR, - NAV_DESTINATION -}; +enum class TitleBarParentType { NAVBAR, NAV_DESTINATION }; enum class NavRouteMode { PUSH_WITH_RECREATE = 0, diff --git a/frameworks/core/components_ng/pattern/navigation/navigation_layout_algorithm.cpp b/frameworks/core/components_ng/pattern/navigation/navigation_layout_algorithm.cpp index d044fe755e4..71364fac996 100644 --- a/frameworks/core/components_ng/pattern/navigation/navigation_layout_algorithm.cpp +++ b/frameworks/core/components_ng/pattern/navigation/navigation_layout_algorithm.cpp @@ -46,7 +46,7 @@ constexpr Dimension WINDOW_WIDTH = 520.0_vp; namespace { void MeasureDivider(LayoutWrapper* layoutWrapper, const RefPtr& hostNode, - const RefPtr& navigationLayoutProperty, const SizeF& dividerSize_) + const RefPtr& navigationLayoutProperty, const SizeF& dividerSize) { auto dividerNode = hostNode->GetDividerNode(); CHECK_NULL_VOID(dividerNode); @@ -54,12 +54,12 @@ void MeasureDivider(LayoutWrapper* layoutWrapper, const RefPtrGetOrCreateChildByIndex(index); CHECK_NULL_VOID(dividerWrapper); auto constraint = navigationLayoutProperty->CreateChildConstraint(); - constraint.selfIdealSize = OptionalSizeF(dividerSize_.Width(), dividerSize_.Height()); + constraint.selfIdealSize = OptionalSizeF(dividerSize.Width(), dividerSize.Height()); dividerWrapper->Measure(constraint); } void MeasureContentChild(LayoutWrapper* layoutWrapper, const RefPtr& hostNode, - const RefPtr& navigationLayoutProperty, const SizeF& contentSize_) + const RefPtr& navigationLayoutProperty, const SizeF& contentSize) { auto contentNode = hostNode->GetContentNode(); CHECK_NULL_VOID(contentNode); @@ -67,7 +67,7 @@ void MeasureContentChild(LayoutWrapper* layoutWrapper, const RefPtrGetOrCreateChildByIndex(index); CHECK_NULL_VOID(contentWrapper); auto constraint = navigationLayoutProperty->CreateChildConstraint(); - constraint.selfIdealSize = OptionalSizeF(contentSize_.Width(), contentSize_.Height()); + constraint.selfIdealSize = OptionalSizeF(contentSize.Width(), contentSize.Height()); contentWrapper->Measure(constraint); } @@ -187,40 +187,58 @@ void FitScrollFullWindow(SizeF& frameSize) } // namespace -void NavigationLayoutAlgorithm::GetRange(const RefPtr& hostNode) +void NavigationLayoutAlgorithm::MeasureNavBar(LayoutWrapper* layoutWrapper, const RefPtr& hostNode, + const RefPtr& navigationLayoutProperty, const SizeF& navBarSize) { - auto navigationPattern = AceType::DynamicCast(hostNode->GetPattern()); - CHECK_NULL_VOID(navigationPattern); - minNavBarWidthValue_ = navigationPattern->GetMinNavBarWidthValue(); - maxNavBarWidthValue_ = navigationPattern->GetMaxNavBarWidthValue(); - minContentWidthValue_ = navigationPattern->GetMinContentWidthValue(); - userSetNavBarRangeFlag_ = navigationPattern->GetUserSetNavBarRangeFlag(); - userSetMinContentFlag_ = navigationPattern->GetUserSetMinContentFlag(); + auto navBarNode = hostNode->GetNavBarNode(); + CHECK_NULL_VOID(navBarNode); + auto index = hostNode->GetChildIndexById(navBarNode->GetId()); + auto navBarWrapper = layoutWrapper->GetOrCreateChildByIndex(index); + CHECK_NULL_VOID(navBarWrapper); + auto constraint = navigationLayoutProperty->CreateChildConstraint(); + constraint.selfIdealSize = OptionalSizeF(navBarSize.Width(), navBarSize.Height()); + navBarWrapper->Measure(constraint); + realNavBarHeight_ = navBarWrapper->GetGeometryNode()->GetFrameSize().Height(); } -void NavigationLayoutAlgorithm::UpdateNavigationMode(LayoutWrapper* layoutWrapper, - const RefPtr& hostNode, const RefPtr& navigationLayoutProperty, - const SizeF& frameSize) +void NavigationLayoutAlgorithm::Measure(LayoutWrapper* layoutWrapper) { - auto lastNavMode = navigationLayoutProperty->GetNavigationModeValue(NavigationMode::AUTO); + auto hostNode = AceType::DynamicCast(layoutWrapper->GetHostNode()); + CHECK_NULL_VOID(hostNode); + auto contentNode = hostNode->GetContentNode(); + CHECK_NULL_VOID(contentNode); + auto navigationLayoutProperty = AceType::DynamicCast(layoutWrapper->GetLayoutProperty()); + CHECK_NULL_VOID(navigationLayoutProperty); + const auto& constraint = navigationLayoutProperty->GetLayoutConstraint(); + CHECK_NULL_VOID(constraint); + auto geometryNode = layoutWrapper->GetGeometryNode(); + auto size = CreateIdealSize(constraint.value(), Axis::HORIZONTAL, MeasureType::MATCH_PARENT, true); + auto parentSize = CreateIdealSize(constraint.value(), Axis::HORIZONTAL, MeasureType::MATCH_PARENT); + FitScrollFullWindow(size); + const auto& padding = layoutWrapper->GetLayoutProperty()->CreatePaddingAndBorder(); + MinusPaddingToSize(padding, size); + + auto navBarWidthValue = navigationLayoutProperty->GetNavBarWidthValue(DEFAULT_NAV_BAR_WIDTH); + auto minNavBarWidthValue = navigationLayoutProperty->GetMinNavBarWidthValue(DEFAULT_MIN_NAV_BAR_WIDTH); + auto maxNavBarWidthValue = navigationLayoutProperty->GetMaxNavBarWidthValue(DEFAULT_MAX_NAV_BAR_WIDTH); + auto minContentWidthValue = navigationLayoutProperty->GetMinContentWidthValue(DEFAULT_MIN_CONTENT_WIDTH); + usrNavigationMode_ = navigationLayoutProperty->GetUsrNavigationModeValue(NavigationMode::AUTO); navigationMode_ = usrNavigationMode_; auto navigationPattern = AceType::DynamicCast(hostNode->GetPattern()); - CHECK_NULL_VOID(navigationPattern); auto pipeline = PipelineContext::GetCurrentContext(); CHECK_NULL_VOID(pipeline); auto currentPlatformVersion = pipeline->GetMinPlatformVersion(); auto navigationWidth = 0.0f; - if (currentPlatformVersion >= PLATFORM_VERSION_TEN) { - navigationWidth = static_cast(minNavBarWidthValue_.ConvertToPx() + minContentWidthValue_.ConvertToPx()); + navigationWidth = static_cast(minNavBarWidthValue.ConvertToPx() + minContentWidthValue.ConvertToPx()); } else { navigationWidth = static_cast(WINDOW_WIDTH.ConvertToPx()); } if (navigationMode_ == NavigationMode::AUTO) { - if (frameSize.Width() >= navigationWidth) { + if (size.Width() >= navigationWidth) { navigationMode_ = NavigationMode::SPLIT; navigationLayoutProperty->UpdateNavigationMode(navigationMode_); navigationPattern->SetNavigationMode(navigationMode_); @@ -229,7 +247,6 @@ void NavigationLayoutAlgorithm::UpdateNavigationMode(LayoutWrapper* layoutWrappe navigationLayoutProperty->UpdateNavigationMode(navigationMode_); navigationPattern->SetNavigationMode(navigationMode_); } - } else { auto layoutAlgorithmWrapper = DynamicCast(layoutWrapper->GetLayoutAlgorithm()); CHECK_NULL_VOID(layoutAlgorithmWrapper); @@ -239,159 +256,71 @@ void NavigationLayoutAlgorithm::UpdateNavigationMode(LayoutWrapper* layoutWrappe navigationLayoutAlgorithm->SetNavigationMode(navigationMode_); navigationPattern->SetNavigationMode(navigationMode_); } - if (lastNavMode == NavigationMode::AUTO) { - navigationPattern->SetNavModeChange(navigationMode_ == NavigationMode::SPLIT); - } else { - navigationPattern->SetNavModeChange(navigationMode_ != lastNavMode); - } -} - -void NavigationLayoutAlgorithm::SizeCalculation(const RefPtr& hostNode, - const RefPtr& navigationLayoutProperty, const SizeF& frameSize) -{ - auto pipeline = PipelineContext::GetCurrentContext(); - CHECK_NULL_VOID(pipeline); - auto currentPlatformVersion = pipeline->GetMinPlatformVersion(); - auto constraint = navigationLayoutProperty->GetLayoutConstraint(); - auto parentSize = CreateIdealSize(constraint.value(), Axis::HORIZONTAL, MeasureType::MATCH_PARENT); - + auto navBarWidth = navBarWidthValue.ConvertToPxWithSize(parentSize.Width().value_or(0.0f)); if (currentPlatformVersion >= PLATFORM_VERSION_TEN) { - auto minNavBarWidth = minNavBarWidthValue_.ConvertToPxWithSize(parentSize.Width().value_or(0.0f)); - auto maxNavBarWidth = maxNavBarWidthValue_.ConvertToPxWithSize(parentSize.Width().value_or(0.0f)); - realNavBarWidth_ = std::max(realNavBarWidth_, static_cast(minNavBarWidth)); - realNavBarWidth_ = std::min(realNavBarWidth_, static_cast(maxNavBarWidth)); - } else { - auto navBarWidthValue = navigationLayoutProperty->GetNavBarWidthValue(DEFAULT_NAV_BAR_WIDTH); - auto navBarWidth = navBarWidthValue.ConvertToPxWithSize(parentSize.Width().value_or(0.0f)); - realNavBarWidth_ = navBarWidth; - } - navBarSize_ = frameSize; - contentSize_ = frameSize; - dividerSize_ = SizeF(0.0f, frameSize.Height()); + auto minNavBarWidth = minNavBarWidthValue.ConvertToPxWithSize(parentSize.Width().value_or(0.0f)); + auto maxNavBarWidth = maxNavBarWidthValue.ConvertToPxWithSize(parentSize.Width().value_or(0.0f)); + auto minContentWidth = minContentWidthValue.ConvertToPxWithSize(parentSize.Width().value_or(0.0f)); - if (navigationLayoutProperty->GetNavigationModeValue(navigationMode_) == NavigationMode::SPLIT) { - SizeCalculationSplit(navigationLayoutProperty, frameSize); - } else { - SizeCalculationStack(hostNode, navigationLayoutProperty, frameSize); - } - - navBarSize_.SetWidth(realNavBarWidth_); - dividerSize_.SetWidth(realDividerWidth_); - contentSize_.SetWidth(realContentWidth_); -} - -void NavigationLayoutAlgorithm::SizeCalculationSplit( - const RefPtr& navigationLayoutProperty, const SizeF& frameSize) -{ - float frameWidth = frameSize.Width(); - auto constraint = navigationLayoutProperty->GetLayoutConstraint(); - auto parentSize = CreateIdealSize(constraint.value(), Axis::HORIZONTAL, MeasureType::MATCH_PARENT); - auto dividerWidth = static_cast(DIVIDER_WIDTH.ConvertToPx()); - auto minContentWidth = minContentWidthValue_.ConvertToPxWithSize(parentSize.Width().value_or(0.0f)); - realContentWidth_ = minContentWidth; - - if (navigationLayoutProperty->GetHideNavBar().value_or(false)) { - navBarSize_ = SizeF(0.0f, 0.0f); - dividerSize_ = SizeF(0.0f, 0.0f); - realNavBarWidth_ = 0.0f; - realContentWidth_ = frameWidth; - } else { - if (userSetMinContentFlag_ && !userSetNavBarRangeFlag_) { - if (minContentWidth >= frameWidth) { - realContentWidth_ = frameWidth; - realNavBarWidth_ = 0.0f; - } else if (realNavBarWidth_ + dividerWidth + minContentWidth <= frameWidth) { - realContentWidth_ = frameWidth - realNavBarWidth_ - dividerWidth; - } else { - realContentWidth_ = minContentWidth; - realNavBarWidth_ = frameWidth - realContentWidth_ - dividerWidth; + if (ifNeedInit_) { + if (navBarWidth <= minNavBarWidth) { + navBarWidth = minNavBarWidth; + } else if (navBarWidth >= maxNavBarWidth) { + navBarWidth = maxNavBarWidth; } - } else { - float remainingSpace = frameWidth - realNavBarWidth_ - dividerWidth; - auto minNavBarWidth = minNavBarWidthValue_.ConvertToPxWithSize(parentSize.Width().value_or(0.0f)); - if (remainingSpace >= minContentWidth) { - realContentWidth_ = remainingSpace; - } else if (remainingSpace < minContentWidth && realNavBarWidth_ > minNavBarWidth) { - realContentWidth_ = minContentWidth; - realNavBarWidth_ = frameWidth - minContentWidth - dividerWidth; - } else { + realNavBarWidth_ = navBarWidth; + } + if (realNavBarWidth_ + static_cast(DIVIDER_WIDTH.ConvertToPx()) + minContentWidth > size.Width()) { + realNavBarWidth_ = size.Width() - minContentWidth - static_cast(DIVIDER_WIDTH.ConvertToPx()); + if (realNavBarWidth_ <= minNavBarWidth) { realNavBarWidth_ = minNavBarWidth; - realContentWidth_ = frameWidth - minNavBarWidth - dividerWidth; } } + if (navBarWidth != realNavBarWidth_) { + navBarWidth = realNavBarWidth_; + } } - - realDividerWidth_ = std::max(realDividerWidth_, 0.0f); - realContentWidth_ = std::max(realContentWidth_, 0.0f); - realNavBarWidth_ = std::min(realNavBarWidth_, frameWidth); - realContentWidth_ = std::min(realContentWidth_, frameWidth); - if (realNavBarWidth_ == 0.0f || realContentWidth_ == 0.0f) { - realDividerWidth_ = 0.0f; + auto navBarSize = size; + auto contentSize = size; + auto dividerSize = SizeF(0.0f, 0.0f); + float contentWidth = 0.0f; + float dividerWidth = 0.0f; + if (navigationLayoutProperty->GetNavigationModeValue(navigationMode_) == NavigationMode::SPLIT) { + if (navigationLayoutProperty->GetHideNavBar().value_or(false)) { + contentWidth = size.Width(); + navBarSize.SetWidth(0.0f); + navBarSize.SetHeight(0.0f); + contentSize.SetWidth(contentWidth); + MeasureNavBar(layoutWrapper, hostNode, navigationLayoutProperty, navBarSize); + MeasureContentChild(layoutWrapper, hostNode, navigationLayoutProperty, contentSize); + MeasureDivider(layoutWrapper, hostNode, navigationLayoutProperty, dividerSize); + layoutWrapper->GetGeometryNode()->SetFrameSize(size); + return; + } + contentWidth = std::floor(size.Width() - static_cast(DIVIDER_WIDTH.ConvertToPx()) - navBarWidth); + dividerWidth = size.Width() - navBarWidth - contentWidth; + navBarSize.SetWidth(navBarWidth); + contentSize.SetWidth(contentWidth); + dividerSize.SetWidth(dividerWidth); + dividerSize.SetHeight(size.Height()); + } else if (hostNode->GetIsModeChange()) { + if (navigationLayoutProperty->GetDestinationChange().value_or(false) || + contentNode->FindChildNodeOfClass()) { + navigationLayoutProperty->GetNavBarPositionValue(NavBarPosition::START) == NavBarPosition::END + ? navBarSize.SetWidth(0.0f) + : navBarSize.SetWidth(navBarWidth); + } else { + if (navigationLayoutProperty->GetNavBarPositionValue(NavBarPosition::START) == NavBarPosition::END) { + contentWidth = std::floor(size.Width() - static_cast(DIVIDER_WIDTH.ConvertToPx()) - navBarWidth); + } + contentSize.SetWidth(contentWidth); + } } else { - realDividerWidth_ = dividerWidth; + navBarWidth = 0.0f; } -} - -void NavigationLayoutAlgorithm::SizeCalculationStack(const RefPtr& hostNode, - const RefPtr& navigationLayoutProperty, const SizeF& frameSize) -{ - auto contentNode = hostNode->GetContentNode(); - CHECK_NULL_VOID(contentNode); - realDividerWidth_ = 0.0f; - float frameWidth = frameSize.Width(); - if (navigationLayoutProperty->GetDestinationChange().value_or(false) || - contentNode->FindChildNodeOfClass()) { - realContentWidth_ = frameWidth; - realNavBarWidth_ = 0.0f; - } else { - realContentWidth_ = 0.0f; - realNavBarWidth_ = frameWidth; - } - auto usrNavigationMode_ = navigationLayoutProperty->GetUsrNavigationModeValue(NavigationMode::AUTO); - if (usrNavigationMode_ == NavigationMode::AUTO && hostNode->GetIsModeChange() && - navigationLayoutProperty->GetNavigationMode() == NavigationMode::STACK) { - realContentWidth_ = 0.0f; - realNavBarWidth_ = frameWidth; - } -} - -void NavigationLayoutAlgorithm::MeasureNavBar(LayoutWrapper* layoutWrapper, const RefPtr& hostNode, - const RefPtr& navigationLayoutProperty, const SizeF& navBarSize_) -{ - auto navBarNode = hostNode->GetNavBarNode(); - CHECK_NULL_VOID(navBarNode); - auto index = hostNode->GetChildIndexById(navBarNode->GetId()); - auto navBarWrapper = layoutWrapper->GetOrCreateChildByIndex(index); - CHECK_NULL_VOID(navBarWrapper); - auto constraint = navigationLayoutProperty->CreateChildConstraint(); - constraint.selfIdealSize = OptionalSizeF(navBarSize_.Width(), navBarSize_.Height()); - navBarWrapper->Measure(constraint); - realNavBarHeight_ = navBarWrapper->GetGeometryNode()->GetFrameSize().Height(); -} - -void NavigationLayoutAlgorithm::Measure(LayoutWrapper* layoutWrapper) -{ - auto hostNode = AceType::DynamicCast(layoutWrapper->GetHostNode()); - CHECK_NULL_VOID(hostNode); - auto navigationLayoutProperty = AceType::DynamicCast(layoutWrapper->GetLayoutProperty()); - CHECK_NULL_VOID(navigationLayoutProperty); - const auto& constraint = navigationLayoutProperty->GetLayoutConstraint(); - CHECK_NULL_VOID(constraint); - auto geometryNode = layoutWrapper->GetGeometryNode(); - auto size = CreateIdealSize(constraint.value(), Axis::HORIZONTAL, MeasureType::MATCH_PARENT, true); - FitScrollFullWindow(size); - const auto& padding = layoutWrapper->GetLayoutProperty()->CreatePaddingAndBorder(); - MinusPaddingToSize(padding, size); - if (size.Width() == 0.0f) { - return; - } - GetRange(hostNode); - UpdateNavigationMode(layoutWrapper, hostNode, navigationLayoutProperty, size); - SizeCalculation(hostNode, navigationLayoutProperty, size); - - MeasureNavBar(layoutWrapper, hostNode, navigationLayoutProperty, navBarSize_); - MeasureContentChild(layoutWrapper, hostNode, navigationLayoutProperty, contentSize_); - MeasureDivider(layoutWrapper, hostNode, navigationLayoutProperty, dividerSize_); + MeasureNavBar(layoutWrapper, hostNode, navigationLayoutProperty, navBarSize); + MeasureContentChild(layoutWrapper, hostNode, navigationLayoutProperty, contentSize); + MeasureDivider(layoutWrapper, hostNode, navigationLayoutProperty, dividerSize); layoutWrapper->GetGeometryNode()->SetFrameSize(size); } diff --git a/frameworks/core/components_ng/pattern/navigation/navigation_layout_algorithm.h b/frameworks/core/components_ng/pattern/navigation/navigation_layout_algorithm.h index 1c1db085d84..26d8fff5071 100644 --- a/frameworks/core/components_ng/pattern/navigation/navigation_layout_algorithm.h +++ b/frameworks/core/components_ng/pattern/navigation/navigation_layout_algorithm.h @@ -81,38 +81,12 @@ private: NavigationMode navigationMode_ = NavigationMode::AUTO; ACE_DISALLOW_COPY_AND_MOVE(NavigationLayoutAlgorithm); void MeasureNavBar(LayoutWrapper* layoutWrapper, const RefPtr& hostNode, - const RefPtr& navigationLayoutProperty, const SizeF& navBarSize_); - - void GetRange(const RefPtr& hostNode); - - void UpdateNavigationMode(LayoutWrapper* layoutWrapper, const RefPtr& hostNode, - const RefPtr& navigationLayoutProperty, const SizeF& frameSize); - - void SizeCalculation(const RefPtr& hostNode, - const RefPtr& navigationLayoutProperty, const SizeF& frameSize); - - void SizeCalculationSplit(const RefPtr& navigationLayoutProperty, const SizeF& frameSize); - - void SizeCalculationStack(const RefPtr& hostNode, - const RefPtr& navigationLayoutProperty, const SizeF& frameSize); - - bool ifNeedInit_ = true; - OffsetF navBarOffset_; - - bool userSetNavBarRangeFlag_ = false; - bool userSetMinContentFlag_ = false; - Dimension minNavBarWidthValue_ = 0.0_vp; - Dimension maxNavBarWidthValue_ = 0.0_vp; - Dimension minContentWidthValue_ = 0.0_vp; - + const RefPtr& navigationLayoutProperty, const SizeF& navBarSize); float realNavBarWidth_ = 0.0f; float realDividerWidth_ = 0.0f; float realNavBarHeight_ = 0.0f; - float realContentWidth_ = 0.0f; - - SizeF navBarSize_ = SizeF(0.0f, 0.0f); - SizeF contentSize_ = SizeF(0.0f, 0.0f); - SizeF dividerSize_ = SizeF(0.0f, 0.0f); + bool ifNeedInit_ = true; + OffsetF navBarOffset_; }; } // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/pattern/navigation/navigation_layout_property.h b/frameworks/core/components_ng/pattern/navigation/navigation_layout_property.h index abbe0315f65..79d58ca5f7a 100644 --- a/frameworks/core/components_ng/pattern/navigation/navigation_layout_property.h +++ b/frameworks/core/components_ng/pattern/navigation/navigation_layout_property.h @@ -26,7 +26,7 @@ namespace OHOS::Ace::NG { -constexpr Dimension DEFAULT_NAV_BAR_WIDTH = 240.0_vp; +constexpr Dimension DEFAULT_NAV_BAR_WIDTH = 200.0_vp; class ACE_EXPORT NavigationLayoutProperty : public LayoutProperty { DECLARE_ACE_TYPE(NavigationLayoutProperty, LayoutProperty); @@ -75,14 +75,13 @@ public: void ToJsonValue(std::unique_ptr& json) const override { LayoutProperty::ToJsonValue(json); - std::string navBarWidthRange = GetMinNavBarWidthValue(DEFAULT_MIN_NAV_BAR_WIDTH).ToString() + ", " + - GetMaxNavBarWidthValue(DEFAULT_MAX_NAV_BAR_WIDTH).ToString(); + std::string navBarWidthRange = GetMinNavBarWidthValue(DEFAULT_MIN_NAV_BAR_WIDTH).ToString() + ", " + + GetMaxNavBarWidthValue(DEFAULT_MAX_NAV_BAR_WIDTH).ToString(); json->Put("navBarWidth", GetNavBarWidthValue(DEFAULT_NAV_BAR_WIDTH).ToString().c_str()); json->Put("navBarWidthRange", navBarWidthRange.c_str()); json->Put("minContentWidth", GetMinContentWidthValue(DEFAULT_MIN_CONTENT_WIDTH).ToString().c_str()); - json->Put("navBarPosition", GetNavBarPosition().value_or(NavBarPosition::START) == NavBarPosition::START - ? "NavBarPosition.Start" - : "NavBarPosition.End"); + json->Put("navBarPosition", GetNavBarPosition().value_or(NavBarPosition::START) == + NavBarPosition::START ? "NavBarPosition.Start" : "NavBarPosition.End"); static const std::array NAVIGATION_MODE_TO_STRING = { "NavigationMode.STACK", "NavigationMode.SPLIT", diff --git a/frameworks/core/components_ng/pattern/navigation/navigation_model_ng.cpp b/frameworks/core/components_ng/pattern/navigation/navigation_model_ng.cpp index c60713b7dfc..5d5b5660d81 100644 --- a/frameworks/core/components_ng/pattern/navigation/navigation_model_ng.cpp +++ b/frameworks/core/components_ng/pattern/navigation/navigation_model_ng.cpp @@ -1191,6 +1191,8 @@ void NavigationModelNG::SetMenuItems(std::vector&& menuItems) auto navBarPattern = navBarNode->GetPattern(); CHECK_NULL_VOID(navBarPattern); navBarPattern->SetTitleBarMenuItems(menuItems); + navBarPattern->SetMenuNodeId(ElementRegister::GetInstance()->MakeUniqueId()); + navBarPattern->SetLandscapeMenuNodeId(ElementRegister::GetInstance()->MakeUniqueId()); navBarNode->UpdatePrevMenuIsCustom(false); } diff --git a/frameworks/core/components_ng/pattern/navigation/navigation_pattern.cpp b/frameworks/core/components_ng/pattern/navigation/navigation_pattern.cpp index 9730899c98f..7f979cf3af8 100644 --- a/frameworks/core/components_ng/pattern/navigation/navigation_pattern.cpp +++ b/frameworks/core/components_ng/pattern/navigation/navigation_pattern.cpp @@ -347,22 +347,15 @@ bool NavigationPattern::OnDirtyLayoutWrapperSwap(const RefPtr& di if (config.skipMeasure && config.skipLayout) { return false; } - - auto hostNode = AceType::DynamicCast(GetHost()); - CHECK_NULL_RETURN(hostNode, false); - auto navigationLayoutProperty = AceType::DynamicCast(hostNode->GetLayoutProperty()); - CHECK_NULL_RETURN(navigationLayoutProperty, false); - - if (ifNeedInit_) { - RangeCalculation(hostNode, navigationLayoutProperty); - } - auto layoutAlgorithmWrapper = DynamicCast(dirty->GetLayoutAlgorithm()); CHECK_NULL_RETURN(layoutAlgorithmWrapper, false); auto navigationLayoutAlgorithm = DynamicCast(layoutAlgorithmWrapper->GetLayoutAlgorithm()); CHECK_NULL_RETURN(navigationLayoutAlgorithm, false); - + auto hostNode = AceType::DynamicCast(GetHost()); + CHECK_NULL_RETURN(hostNode, false); + auto navigationLayoutProperty = AceType::DynamicCast(hostNode->GetLayoutProperty()); + CHECK_NULL_RETURN(navigationLayoutProperty, false); if (config.frameSizeChange) { if (navigationLayoutProperty->GetUsrNavigationModeValue(NavigationMode::AUTO) == NavigationMode::AUTO) { auto currentMode = navigationLayoutAlgorithm->GetNavigationMode(); @@ -457,56 +450,52 @@ void NavigationPattern::HandleDragUpdate(float xOffset) { auto navigationLayoutProperty = GetLayoutProperty(); CHECK_NULL_VOID(navigationLayoutProperty); + auto minNavBarWidth = navigationLayoutProperty->GetMinNavBarWidthValue(DEFAULT_MIN_NAV_BAR_WIDTH); + auto maxNavBarWidth = navigationLayoutProperty->GetMaxNavBarWidthValue(DEFAULT_MAX_NAV_BAR_WIDTH); + auto minContentWidth = navigationLayoutProperty->GetMinContentWidthValue(DEFAULT_MIN_CONTENT_WIDTH); auto host = GetHost(); CHECK_NULL_VOID(host); auto geometryNode = host->GetGeometryNode(); CHECK_NULL_VOID(geometryNode); auto frameSize = geometryNode->GetFrameSize(); - auto frameWidth = frameSize.Width(); + auto parentWidth = frameSize.Width(); auto constraint = navigationLayoutProperty->GetLayoutConstraint(); auto parentSize = CreateIdealSize(constraint.value(), Axis::HORIZONTAL, MeasureType::MATCH_PARENT); - float minNavBarWidthPx = minNavBarWidthValue_.ConvertToPxWithSize(parentSize.Width().value_or(0.0f)); - float maxNavBarWidthPx = maxNavBarWidthValue_.ConvertToPxWithSize(parentSize.Width().value_or(0.0f)); - float minContentWidthPx = minContentWidthValue_.ConvertToPxWithSize(parentSize.Width().value_or(0.0f)); - auto dividerWidth = static_cast(DIVIDER_WIDTH.ConvertToPx()); - + auto minNavBarWidthPx = minNavBarWidth.ConvertToPxWithSize(parentSize.Width().value_or(0.0f)); + auto maxNavBarWidthPx = maxNavBarWidth.ConvertToPxWithSize(parentSize.Width().value_or(0.0f)); + auto minContentWidthPx = minContentWidth.ConvertToPxWithSize(parentSize.Width().value_or(0.0f)); auto navigationPosition = navigationLayoutProperty->GetNavBarPosition().value_or(NavBarPosition::START); bool isNavBarStart = navigationPosition == NavBarPosition::START; - float navBarLine = preNavBarWidth_ + (isNavBarStart ? xOffset : -xOffset); + auto navBarLine = preNavBarWidth_ + (isNavBarStart ? xOffset : -xOffset); float currentNavBarWidth = realNavBarWidth_; - - if (maxNavBarWidthPx + dividerWidth + minContentWidthPx > frameWidth) { - maxNavBarWidthPx = frameWidth - minContentWidthPx - dividerWidth; - } - navBarLine = std::min(navBarLine, maxNavBarWidthPx); - - if (userSetMinContentFlag_ && !userSetNavBarRangeFlag_) { - if (minContentWidthPx >= frameWidth) { - realNavBarWidth_ = 0.0f; - } else if (navBarLine + dividerWidth + minContentWidthPx <= frameWidth) { - realNavBarWidth_ = navBarLine; - + if (navBarLine > minNavBarWidthPx && navBarLine < maxNavBarWidthPx) { + if (navBarLine + static_cast(DIVIDER_WIDTH.ConvertToPx()) + minContentWidthPx > parentWidth) { + realNavBarWidth_ = parentWidth - minContentWidthPx - static_cast(DIVIDER_WIDTH.ConvertToPx()); } else { - realNavBarWidth_ = frameWidth - minContentWidthPx - dividerWidth; - } - } else { - realDividerWidth_ = dividerWidth; - float remainingSpace = frameWidth - navBarLine - dividerWidth; - if (remainingSpace >= minContentWidthPx) { realNavBarWidth_ = navBarLine; - } else if (remainingSpace < minContentWidthPx && navBarLine > minNavBarWidthPx) { - realNavBarWidth_ = frameWidth - minContentWidthPx - dividerWidth; - } else { - realNavBarWidth_ = minNavBarWidthPx; } + if (realNavBarWidth_ != currentNavBarWidth) { + host->MarkDirtyNode(PROPERTY_UPDATE_MEASURE_SELF_AND_CHILD); + } + return; } - - realNavBarWidth_ = std::min(realNavBarWidth_, frameWidth); - realNavBarWidth_ = std::min(realNavBarWidth_, maxNavBarWidthPx); - realNavBarWidth_ = std::max(realNavBarWidth_, minNavBarWidthPx); - - // MEASURE + if (navBarLine >= maxNavBarWidthPx) { + realNavBarWidth_ = maxNavBarWidthPx; + if (realNavBarWidth_ != currentNavBarWidth) { + host->MarkDirtyNode(PROPERTY_UPDATE_MEASURE_SELF_AND_CHILD); + } + return; + } + auto halfDragRegionWidth = dragRect_.Width() / 2; + if (navBarLine > minNavBarWidthPx - halfDragRegionWidth) { + realNavBarWidth_ = minNavBarWidthPx; + if (realNavBarWidth_ != currentNavBarWidth) { + host->MarkDirtyNode(PROPERTY_UPDATE_MEASURE_SELF_AND_CHILD); + } + return; + } + realNavBarWidth_ = minNavBarWidthPx; if (realNavBarWidth_ != currentNavBarWidth) { host->MarkDirtyNode(PROPERTY_UPDATE_MEASURE_SELF_AND_CHILD); } @@ -560,8 +549,8 @@ void NavigationPattern::OnHover(bool isHover) } } -void NavigationPattern::UpdateResponseRegion( - float realDividerWidth, float realNavBarWidth, float dragRegionHeight, OffsetF dragRectOffset) +void NavigationPattern::UpdateResponseRegion(float realDividerWidth, float realNavBarWidth, + float dragRegionHeight, OffsetF dragRectOffset) { auto layoutProperty = GetLayoutProperty(); CHECK_NULL_VOID(layoutProperty); @@ -608,12 +597,12 @@ void NavigationPattern::AddDividerHotZoneRect(const RefPtrGetRealNavBarWidth() - DEFAULT_DIVIDER_HOT_ZONE_HORIZONTAL_PADDING.ConvertToPx()); + hotZoneOffset.SetX(layoutAlgorithm->GetRealNavBarWidth() - + DEFAULT_DIVIDER_HOT_ZONE_HORIZONTAL_PADDING.ConvertToPx()); hotZoneOffset.SetY(DEFAULT_DIVIDER_START_MARGIN.ConvertToPx()); SizeF hotZoneSize; - hotZoneSize.SetWidth(realDividerWidth_ + DIVIDER_HOT_ZONE_HORIZONTAL_PADDING_NUM * - DEFAULT_DIVIDER_HOT_ZONE_HORIZONTAL_PADDING.ConvertToPx()); + hotZoneSize.SetWidth(realDividerWidth_ + + DIVIDER_HOT_ZONE_HORIZONTAL_PADDING_NUM * DEFAULT_DIVIDER_HOT_ZONE_HORIZONTAL_PADDING.ConvertToPx()); hotZoneSize.SetHeight(layoutAlgorithm->GetRealNavBarHeight()); DimensionRect hotZoneRegion; hotZoneRegion.SetSize(DimensionSize(Dimension(hotZoneSize.Width()), Dimension(hotZoneSize.Height()))); @@ -660,54 +649,4 @@ void NavigationPattern::OnWindowShow() eventHub->FireOnShownEvent(); navDestinationPattern->SetIsOnShow(true); } - -void NavigationPattern::RangeCalculation( - const RefPtr& hostNode, const RefPtr& navigationLayoutProperty) -{ - const auto& constraint = navigationLayoutProperty->GetLayoutConstraint(); - CHECK_NULL_VOID(constraint); - auto parentSize = CreateIdealSize(constraint.value(), Axis::HORIZONTAL, MeasureType::MATCH_PARENT); - auto frameSize = CreateIdealSize(constraint.value(), Axis::HORIZONTAL, MeasureType::MATCH_PARENT, true); - float frameSizeWidth = frameSize.Width(); - Dimension defaultValue = Dimension(-1.0); - auto pipeline = PipelineContext::GetCurrentContext(); - CHECK_NULL_VOID(pipeline); - auto currentPlatformVersion = pipeline->GetMinPlatformVersion(); - - minContentWidthValue_ = navigationLayoutProperty->GetMinContentWidthValue(defaultValue); - if (minContentWidthValue_ == defaultValue) { - userSetMinContentFlag_ = false; - minContentWidthValue_ = DEFAULT_MIN_CONTENT_WIDTH; - } else { - userSetMinContentFlag_ = true; - } - - minNavBarWidthValue_ = navigationLayoutProperty->GetMinNavBarWidthValue(DEFAULT_MIN_NAV_BAR_WIDTH); - auto userSetMaxNavBarWidthValue = navigationLayoutProperty->GetMaxNavBarWidthValue(defaultValue); - - float minNavBarWidth = std::min(static_cast(minNavBarWidthValue_.ConvertToPx()), frameSizeWidth); - float maxNavBarWidth = 0.0f; - - if (userSetMaxNavBarWidthValue == defaultValue) { - userSetNavBarRangeFlag_ = false; - maxNavBarWidth = std::min( - static_cast(DEFAULT_MAX_NAV_BAR_WIDTH.ConvertToPx()), frameSizeWidth * MAX_NAV_BAR_WIDTH_SCALE); - } else { - userSetNavBarRangeFlag_ = true; - maxNavBarWidth = static_cast(userSetMaxNavBarWidthValue.ConvertToPx()); - } - - maxNavBarWidthValue_ = Dimension(std::max(maxNavBarWidth, minNavBarWidth), DimensionUnit::PX); - - auto navBarWidthValue = navigationLayoutProperty->GetNavBarWidthValue(DEFAULT_NAV_BAR_WIDTH); - auto navBarWidth = navBarWidthValue.ConvertToPxWithSize(parentSize.Width().value_or(0.0f)); - realNavBarWidth_ = navBarWidth; - if (currentPlatformVersion >= PLATFORM_VERSION_TEN) { - auto minNavBarWidth = minNavBarWidthValue_.ConvertToPxWithSize(parentSize.Width().value_or(0.0f)); - auto maxNavBarWidth = maxNavBarWidthValue_.ConvertToPxWithSize(parentSize.Width().value_or(0.0f)); - realNavBarWidth_ = std::max(realNavBarWidth_, static_cast(minNavBarWidth)); - realNavBarWidth_ = std::min(realNavBarWidth_, static_cast(maxNavBarWidth)); - } -} - } // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/pattern/navigation/navigation_pattern.h b/frameworks/core/components_ng/pattern/navigation/navigation_pattern.h index c7e9c22c281..4b55061641b 100644 --- a/frameworks/core/components_ng/pattern/navigation/navigation_pattern.h +++ b/frameworks/core/components_ng/pattern/navigation/navigation_pattern.h @@ -177,31 +177,6 @@ public: return navigationStackProvided_; } - Dimension GetMinNavBarWidthValue() const - { - return minNavBarWidthValue_; - } - - Dimension GetMaxNavBarWidthValue() const - { - return maxNavBarWidthValue_; - } - - Dimension GetMinContentWidthValue() const - { - return minContentWidthValue_; - } - - bool GetUserSetNavBarRangeFlag() const - { - return userSetNavBarRangeFlag_; - } - - bool GetUserSetMinContentFlag() const - { - return userSetMinContentFlag_; - } - void OnWindowHide() override; void OnWindowShow() override; @@ -236,8 +211,8 @@ private: void HandleDragUpdate(float xOffset); void HandleDragEnd(); void OnHover(bool isHover); - void UpdateResponseRegion( - float realDividerWidth, float realNavBarWidth, float dragRegionHeight, OffsetF dragRectOffset); + void UpdateResponseRegion(float realDividerWidth, float realNavBarWidth, + float dragRegionHeight, OffsetF dragRectOffset); void AddDividerHotZoneRect(const RefPtr& layoutAlgorithm); void RangeCalculation( const RefPtr& hostNode, const RefPtr& navigationLayoutProperty); diff --git a/frameworks/core/components_ng/pattern/navigation/title_bar_layout_algorithm.cpp b/frameworks/core/components_ng/pattern/navigation/title_bar_layout_algorithm.cpp index 4845697f158..7c10740a63d 100644 --- a/frameworks/core/components_ng/pattern/navigation/title_bar_layout_algorithm.cpp +++ b/frameworks/core/components_ng/pattern/navigation/title_bar_layout_algorithm.cpp @@ -38,8 +38,8 @@ namespace OHOS::Ace::NG { namespace { constexpr int32_t MAX_MENU_ITEMS_NUM = 3; constexpr int32_t MENU_OFFSET_RATIO = 9; - -} // namespace +constexpr int32_t PLATFORM_VERSION_TEN = 10; +} void TitleBarLayoutAlgorithm::MeasureBackButton(LayoutWrapper* layoutWrapper, const RefPtr& titleBarNode, const RefPtr& titleBarLayoutProperty) @@ -327,6 +327,12 @@ void TitleBarLayoutAlgorithm::LayoutTitle(LayoutWrapper* layoutWrapper, const Re titleWrapper->Layout(); return; } + OffsetF titleOffset; + if (PipelineContext::GetCurrentContext()->GetMinPlatformVersion() >= PLATFORM_VERSION_TEN) { + titleOffset = OffsetF(static_cast(maxPaddingStart_.ConvertToPx()), + static_cast(menuHeight_.ConvertToPx()) + offsetY); + geometryNode->SetMarginFrameOffset(titleOffset); + } if (isInitialTitle_) { auto title = AceType::DynamicCast(titleNode); CHECK_NULL_VOID(title); @@ -346,7 +352,7 @@ void TitleBarLayoutAlgorithm::LayoutTitle(LayoutWrapper* layoutWrapper, const Re #endif initialTitleOffsetY_ = static_cast(menuHeight_.ConvertToPx()) + offsetY; isInitialTitle_ = false; - OffsetF titleOffset = OffsetF(static_cast(maxPaddingStart_.ConvertToPx()), initialTitleOffsetY_); + titleOffset = OffsetF(static_cast(maxPaddingStart_.ConvertToPx()), initialTitleOffsetY_); geometryNode->SetMarginFrameOffset(titleOffset); titleWrapper->Layout(); return; @@ -356,13 +362,13 @@ void TitleBarLayoutAlgorithm::LayoutTitle(LayoutWrapper* layoutWrapper, const Re CHECK_NULL_VOID(titlePattern); if (NearZero(titlePattern->GetTempTitleOffsetY())) { initialTitleOffsetY_ = static_cast(menuHeight_.ConvertToPx()) + offsetY; - OffsetF titleOffset = OffsetF(static_cast(maxPaddingStart_.ConvertToPx()), initialTitleOffsetY_); + titleOffset = OffsetF(static_cast(maxPaddingStart_.ConvertToPx()), initialTitleOffsetY_); geometryNode->SetMarginFrameOffset(titleOffset); titleWrapper->Layout(); return; } auto overDragOffset = titlePattern->GetOverDragOffset(); - OffsetF titleOffset = OffsetF(static_cast(maxPaddingStart_.ConvertToPx()), + titleOffset = OffsetF(static_cast(maxPaddingStart_.ConvertToPx()), titlePattern->GetTempTitleOffsetY() + overDragOffset / 6.0f); geometryNode->SetMarginFrameOffset(titleOffset); titleWrapper->Layout(); diff --git a/frameworks/core/components_ng/pattern/overlay/overlay_manager.cpp b/frameworks/core/components_ng/pattern/overlay/overlay_manager.cpp index 81c808300e2..e6288bf4006 100644 --- a/frameworks/core/components_ng/pattern/overlay/overlay_manager.cpp +++ b/frameworks/core/components_ng/pattern/overlay/overlay_manager.cpp @@ -33,6 +33,7 @@ #include "core/components/toast/toast_theme.h" #include "core/components_ng/base/frame_node.h" #include "core/components_ng/base/ui_node.h" +#include "core/components_ng/base/view_stack_processor.h" #include "core/components_ng/pattern/bubble/bubble_event_hub.h" #include "core/components_ng/pattern/bubble/bubble_pattern.h" #include "core/components_ng/pattern/calendar_picker/calendar_dialog_view.h" @@ -42,6 +43,7 @@ #include "core/components_ng/pattern/menu/menu_pattern.h" #include "core/components_ng/pattern/menu/wrapper/menu_wrapper_pattern.h" #include "core/components_ng/pattern/overlay/modal_presentation_pattern.h" +#include "core/components_ng/pattern/overlay/popup_base_pattern.h" #include "core/components_ng/pattern/overlay/sheet_drag_bar_pattern.h" #include "core/components_ng/pattern/overlay/sheet_presentation_pattern.h" #include "core/components_ng/pattern/overlay/sheet_presentation_property.h" @@ -572,7 +574,7 @@ void OverlayManager::HidePopup(int32_t targetId, const PopupInfo& popupInfo) auto rootNode = rootNodeWeak_.Upgrade(); auto container = Container::Current(); if (container && container->IsScenceBoardWindow()) { - rootNode = FindWindowScene(popupInfo.target.Upgrade()); + rootNode = FindWindowScene(popupMap_[targetId].popupNode); } CHECK_NULL_VOID(rootNode); auto rootChildren = rootNode->GetChildren(); @@ -737,6 +739,11 @@ void OverlayManager::ShowMenuInSubWindow(int32_t targetId, const NG::OffsetF& of SetShowMenuAnimation(menu, true); menu->MarkModifyDone(); rootNode->MarkDirtyNode(PROPERTY_UPDATE_MEASURE_SELF); + + // set subwindow container id in menu. + auto menuPattern = menu->GetPattern(); + CHECK_NULL_VOID(menuPattern); + menuPattern->SetContainerId(Container::CurrentId()); LOGI("menuNode mounted in subwindow"); } @@ -767,7 +774,7 @@ void OverlayManager::HideMenuInSubWindow() } } -void OverlayManager::HideMenu(int32_t targetId) +void OverlayManager::HideMenu(int32_t targetId, bool isMenuOnTouch) { LOGI("OverlayManager::HideMenuNode menu targetId is %{public}d", targetId); if (menuMap_.find(targetId) == menuMap_.end()) { @@ -779,9 +786,13 @@ void OverlayManager::HideMenu(int32_t targetId) menuMap_[targetId]->OnAccessibilityEvent( AccessibilityEventType::CHANGE, WindowsContentChangeTypes::CONTENT_CHANGE_TYPE_SUBTREE); #ifdef ENABLE_DRAG_FRAMEWORK - RemoveEventColumn(); + RemoveEventColumn(); + if (isMenuOnTouch) { + RemovePixelMap(); + } else { RemovePixelMapAnimation(false, 0, 0); - RemoveFilter(); + } + RemoveFilter(); #endif // ENABLE_DRAG_FRAMEWORK } @@ -853,9 +864,18 @@ void OverlayManager::BeforeShowDialog(const RefPtr& node) } RefPtr OverlayManager::ShowDialog( - const DialogProperties& dialogProps, const RefPtr& customNode, bool isRightToLeft) + const DialogProperties& dialogProps, std::function&& buildFunc, bool isRightToLeft) { LOGI("OverlayManager::ShowDialog"); + RefPtr customNode; + // create custom builder content + if (buildFunc) { + NG::ScopedViewStackProcessor builderViewStackProcessor; + buildFunc(); + customNode = NG::ViewStackProcessor::GetInstance()->Finish(); + CHECK_NULL_RETURN(customNode, nullptr); + } + auto dialog = DialogView::CreateDialogNode(dialogProps, customNode); BeforeShowDialog(dialog); OpenDialogAnimation(dialog); @@ -902,8 +922,7 @@ void OverlayManager::ShowTextDialog(const DialogProperties& dialogProps, const T } void OverlayManager::ShowCalendarDialog(const DialogProperties& dialogProps, const CalendarSettingData& settingData, - std::map dialogEvent, - std::map dialogCancelEvent) + std::map dialogEvent, std::map dialogCancelEvent) { auto dialogNode = CalendarDialogView::Show(dialogProps, settingData, std::move(dialogEvent), std::move(dialogCancelEvent)); @@ -1027,7 +1046,7 @@ bool OverlayManager::RemoveModalInOverlay() rootNode->RemoveChild(topModalNode); rootNode->MarkDirtyNode(PROPERTY_UPDATE_BY_CHILD_REQUEST); } - } else if (topModalNode->GetTag() == "SheetPage") { + } else if (topModalNode->GetTag() == V2::SHEET_PAGE_TAG) { topModalNode->GetPattern()->FireCallback("false"); auto builder = AceType::DynamicCast(topModalNode->GetLastChild()); CHECK_NULL_RETURN(topModalNode, false); @@ -1196,7 +1215,7 @@ void OverlayManager::BindContentCover(bool isShow, std::functionGetTag() == "ModalPage") { - if (topModalNode->GetPattern()->GetTargetId() == targetId) { + if (topModalNode->GetPattern()->GetTargetId() == targetId) { if (modalStyle.backgroundColor.has_value()) { topModalNode->GetRenderContext()->UpdateBackgroundColor(modalStyle.backgroundColor.value()); } @@ -1423,7 +1442,7 @@ void OverlayManager::BindSheet(bool isShow, std::functionGetTag() == "SheetPage") { + if (topModalNode->GetTag() == V2::SHEET_PAGE_TAG) { if (topModalNode->GetPattern()->GetTargetId() == targetId) { if (sheetStyle.backgroundColor.has_value()) { topModalNode->GetRenderContext()->UpdateBackgroundColor(sheetStyle.backgroundColor.value()); @@ -1473,7 +1492,7 @@ void OverlayManager::BindSheet(bool isShow, std::functionGetTag() != "SheetPage") { + if (topSheetNode->GetTag() != V2::SHEET_PAGE_TAG) { return; } if (topSheetNode->GetPattern()->GetTargetId() != targetId) { @@ -1594,25 +1613,26 @@ void OverlayManager::ComputeSheetOffset(NG::SheetStyle& sheetStyle) void OverlayManager::DestroySheet(const RefPtr& sheetNode, int32_t targetId) { - auto topSheetNode = modalStack_.top().Upgrade(); - CHECK_NULL_VOID(topSheetNode); - if (topSheetNode->GetTag() != "SheetPage") { - return; + if (!modalStack_.empty()) { + auto topSheetNode = modalStack_.top().Upgrade(); + CHECK_NULL_VOID(topSheetNode); + if (topSheetNode->GetTag() != V2::SHEET_PAGE_TAG) { + return; + } + if (topSheetNode->GetPattern()->GetTargetId() != targetId) { + return; + } + auto rootNode = rootNodeWeak_.Upgrade(); + CHECK_NULL_VOID(rootNode); + auto root = DynamicCast(rootNode); + OverlayManager::DestroySheetMask(sheetNode); + root->RemoveChild(sheetNode); + root->MarkDirtyNode(PROPERTY_UPDATE_MEASURE_SELF); + modalStack_.pop(); + modalList_.pop_back(); + FireModalPageHide(); + SaveLastModalNode(); } - if (topSheetNode->GetPattern()->GetTargetId() != targetId) { - return; - } - topSheetNode->GetPattern()->FireCallback("false"); - auto rootNode = rootNodeWeak_.Upgrade(); - CHECK_NULL_VOID(rootNode); - auto root = DynamicCast(rootNode); - OverlayManager::DestroySheetMask(sheetNode); - root->RemoveChild(sheetNode); - root->MarkDirtyNode(PROPERTY_UPDATE_MEASURE_SELF); - modalStack_.pop(); - modalList_.pop_back(); - FireModalPageHide(); - SaveLastModalNode(); } void OverlayManager::DestroySheetMask(const RefPtr& sheetNode) @@ -1751,6 +1771,7 @@ void OverlayManager::RemovePixelMapAnimation(bool startDrag, double x, double y) option.SetCurve(motion); option.SetOnFinishEvent([this, id = Container::CurrentId()] { ContainerScope scope(id); + LOGD("Drag window start with default pixelMap"); Msdp::DeviceStatus::InteractionManager::GetInstance()->SetDragWindowVisible(true); RemovePixelMap(); }); @@ -1760,10 +1781,8 @@ void OverlayManager::RemovePixelMapAnimation(bool startDrag, double x, double y) } imageContext->UpdateBackShadow(shadow.value()); - auto coordinateX = - imageNode->GetOffsetRelativeToWindow().GetX() - frameNode->GetOffsetRelativeToWindow().GetX(); - auto coordinateY = - imageNode->GetOffsetRelativeToWindow().GetY() - frameNode->GetOffsetRelativeToWindow().GetY(); + auto coordinateX = imageNode->GetOffsetRelativeToWindow().GetX() - frameNode->GetOffsetRelativeToWindow().GetX(); + auto coordinateY = imageNode->GetOffsetRelativeToWindow().GetY() - frameNode->GetOffsetRelativeToWindow().GetY(); AnimationUtils::Animate( option, [imageContext, shadow, startDrag, x, y, width, height, scale, coordinateX, coordinateY]() mutable { diff --git a/frameworks/core/components_ng/pattern/overlay/overlay_manager.h b/frameworks/core/components_ng/pattern/overlay/overlay_manager.h index e9641c8d016..2b1def9fa37 100644 --- a/frameworks/core/components_ng/pattern/overlay/overlay_manager.h +++ b/frameworks/core/components_ng/pattern/overlay/overlay_manager.h @@ -86,7 +86,7 @@ public: } void ShowMenu(int32_t targetId, const NG::OffsetF& offset, RefPtr menu = nullptr); - void HideMenu(int32_t targetId); + void HideMenu(int32_t targetId, bool isMenuOnTouch = false); void DeleteMenu(int32_t targetId); void ShowMenuInSubWindow(int32_t targetId, const NG::OffsetF& offset, RefPtr menu = nullptr); void HideMenuInSubWindow(int32_t targetId); @@ -98,7 +98,7 @@ public: // customNode only used by customDialog, pass in nullptr if not customDialog RefPtr ShowDialog( - const DialogProperties& dialogProps, const RefPtr& customNode, bool isRightToLeft = false); + const DialogProperties& dialogProps, std::function&& buildFunc, bool isRightToLeft = false); void ShowCustomDialog(const RefPtr& customNode); void ShowDateDialog(const DialogProperties& dialogProps, const DatePickerSettingData& settingData, std::map dialogEvent, diff --git a/frameworks/core/components_ng/pattern/overlay/popup_base_pattern.cpp b/frameworks/core/components_ng/pattern/overlay/popup_base_pattern.cpp index f651876a57d..78c2556834c 100644 --- a/frameworks/core/components_ng/pattern/overlay/popup_base_pattern.cpp +++ b/frameworks/core/components_ng/pattern/overlay/popup_base_pattern.cpp @@ -23,6 +23,9 @@ void PopupBasePattern::BeforeCreateLayoutWrapper() CHECK_NULL_VOID(pipeline); auto inset = pipeline->GetSafeArea(); + // popup shouldn't avoid status bar + inset.top_ = { 0, 0 }; + auto manager = pipeline->GetSafeAreaManager(); inset.bottom_ = inset.bottom_.Combine(manager->GetKeyboardInset()); auto host = GetHost(); diff --git a/frameworks/core/components_ng/pattern/overlay/popup_base_pattern.h b/frameworks/core/components_ng/pattern/overlay/popup_base_pattern.h index c7ad5fbef10..d274348ebc5 100644 --- a/frameworks/core/components_ng/pattern/overlay/popup_base_pattern.h +++ b/frameworks/core/components_ng/pattern/overlay/popup_base_pattern.h @@ -28,6 +28,20 @@ public: void BeforeCreateLayoutWrapper() override; + void SetContainerId(int32_t containerId) + { + containerId_ = containerId; + } + + int32_t GetContainerId() const + { + return containerId_; + } + +private: + // record node in which container. + int32_t containerId_ = -1; + ACE_DISALLOW_COPY_AND_MOVE(PopupBasePattern); }; } // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/pattern/overlay/sheet_presentation_pattern.cpp b/frameworks/core/components_ng/pattern/overlay/sheet_presentation_pattern.cpp index 4ffdeb0a076..0990bf2f0da 100644 --- a/frameworks/core/components_ng/pattern/overlay/sheet_presentation_pattern.cpp +++ b/frameworks/core/components_ng/pattern/overlay/sheet_presentation_pattern.cpp @@ -152,9 +152,6 @@ void SheetPresentationPattern::InitPanEvent() void SheetPresentationPattern::HandleDragUpdate(const GestureEvent& info) { - if (isAnimating_) { - return; - } auto mainDelta = static_cast(info.GetMainDelta()); auto host = GetHost(); CHECK_NULL_VOID(host); @@ -174,9 +171,6 @@ void SheetPresentationPattern::HandleDragUpdate(const GestureEvent& info) void SheetPresentationPattern::HandleDragEnd(float dragVelocity) { - if (isAnimating_) { - return; - } // current sheet animation if (std::abs(dragVelocity) < SHEET_VELOCITY_THRESHOLD) { // Drag velocity not reached to threshold, mode based on the location. @@ -223,7 +217,7 @@ void SheetPresentationPattern::InitialLayoutProps() void SheetPresentationPattern::SheetTransition(bool isTransitionIn) { - isAnimating_ = true; + FireCallback("false"); auto host = GetHost(); CHECK_NULL_VOID(host); auto context = host->GetRenderContext(); @@ -256,7 +250,6 @@ void SheetPresentationPattern::SheetTransition(bool isTransitionIn) MarginProperty margin; margin.top = CalcLength(marginValue + padding.top.value()); layoutProperty->UpdateMargin(margin); - pattern->SetIsAnimating(false); pattern->SetCurrentOffset(0.0); } else { auto context = PipelineContext::GetCurrentContext(); diff --git a/frameworks/core/components_ng/pattern/overlay/sheet_presentation_pattern.h b/frameworks/core/components_ng/pattern/overlay/sheet_presentation_pattern.h index 0d3fef75c8b..407c87d424b 100644 --- a/frameworks/core/components_ng/pattern/overlay/sheet_presentation_pattern.h +++ b/frameworks/core/components_ng/pattern/overlay/sheet_presentation_pattern.h @@ -83,11 +83,6 @@ public: void SheetTransition(bool isTransitionIn); - void SetIsAnimating(bool isOnAnmation) - { - isAnimating_ = isOnAnmation; - } - void SetCurrentOffset(float currentOffset) { currentOffset_ = currentOffset; @@ -111,7 +106,6 @@ private: float currentOffset_ = 0.0f; float height_ = 0.0f; float heightBoundary_ = 0.0f; - bool isAnimating_ = false; float pageHeight_ = 0.0f; ACE_DISALLOW_COPY_AND_MOVE(SheetPresentationPattern); diff --git a/frameworks/core/components_ng/pattern/overlay/sheet_view.cpp b/frameworks/core/components_ng/pattern/overlay/sheet_view.cpp index 1467c7b3658..82c9272e54b 100644 --- a/frameworks/core/components_ng/pattern/overlay/sheet_view.cpp +++ b/frameworks/core/components_ng/pattern/overlay/sheet_view.cpp @@ -38,7 +38,7 @@ RefPtr SheetView::CreateSheetPage(int32_t targetId, RefPtr std::function&& callback, NG::SheetStyle& sheetStyle) { // create sheet node - auto sheetNode = FrameNode::CreateFrameNode("SheetPage", ElementRegister::GetInstance()->MakeUniqueId(), + auto sheetNode = FrameNode::CreateFrameNode(V2::SHEET_PAGE_TAG, ElementRegister::GetInstance()->MakeUniqueId(), AceType::MakeRefPtr(targetId, std::move(callback))); auto sheetLayoutProperty = sheetNode->GetLayoutProperty(); CHECK_NULL_RETURN(sheetLayoutProperty, nullptr); diff --git a/frameworks/core/components_ng/pattern/panel/sliding_panel_pattern.cpp b/frameworks/core/components_ng/pattern/panel/sliding_panel_pattern.cpp index e72b35f5b48..c53b3d9fda5 100644 --- a/frameworks/core/components_ng/pattern/panel/sliding_panel_pattern.cpp +++ b/frameworks/core/components_ng/pattern/panel/sliding_panel_pattern.cpp @@ -73,7 +73,7 @@ void SlidingPanelPattern::OnModifyDone() } } - if (layoutProperty->GetShowCloseIconValue(true)) { + if (layoutProperty->GetShowCloseIconValue(false)) { auto closeIconNode = GetCloseIconNode(); CHECK_NULL_VOID(closeIconNode); auto closeIconPattern = closeIconNode->GetPattern(); diff --git a/frameworks/core/components_ng/pattern/picker/date_time_animation_controller.cpp b/frameworks/core/components_ng/pattern/picker/date_time_animation_controller.cpp index 8bace069bac..b6dfcdcc9dd 100644 --- a/frameworks/core/components_ng/pattern/picker/date_time_animation_controller.cpp +++ b/frameworks/core/components_ng/pattern/picker/date_time_animation_controller.cpp @@ -134,6 +134,10 @@ void DateTimeAnimationController::PlayOldColumnOpacityInAnimation() animationOption.SetOnFinishEvent([weak = AceType::WeakClaim(this)] { auto ref = weak.Upgrade(); CHECK_NULL_VOID(ref); + if (ref->isOutAnimationPlaying_) { + ref->isInAnimationPlaying_ = false; + return; + } auto monthDaysNode = ref->monthDays_; CHECK_NULL_VOID(monthDaysNode); auto layoutProperty = monthDaysNode->GetLayoutProperty(); @@ -145,6 +149,7 @@ void DateTimeAnimationController::PlayOldColumnOpacityInAnimation() layoutProperty = timePickerNode->GetLayoutProperty(); CHECK_NULL_VOID(layoutProperty); layoutProperty->UpdateVisibility(VisibleType::GONE); + ref->isInAnimationPlaying_ = false; }); monthDaysRender->UpdateOpacity(1); timePickerRender->UpdateOpacity(1); @@ -154,7 +159,7 @@ void DateTimeAnimationController::PlayOldColumnOpacityInAnimation() CHECK_NULL_VOID_NOLOG(timePickerRender); monthDaysRender->UpdateOpacity(0); timePickerRender->UpdateOpacity(0); - }); + }, animationOption.GetOnFinishEvent()); } void DateTimeAnimationController::PlayNewColumnOpacityInAnimation() @@ -241,11 +246,16 @@ void DateTimeAnimationController::PlayOldColumnOpacityOutAnimation() animationOption.SetOnFinishEvent([weak = AceType::WeakClaim(this)] { auto ref = weak.Upgrade(); CHECK_NULL_VOID(ref); + if (ref->isInAnimationPlaying_) { + ref->isOutAnimationPlaying_ = false; + return; + } auto datePickerNode = ref->datePicker_; CHECK_NULL_VOID(datePickerNode); auto layoutProperty = datePickerNode->GetLayoutProperty(); CHECK_NULL_VOID(layoutProperty); layoutProperty->UpdateVisibility(VisibleType::GONE); + ref->isOutAnimationPlaying_ = false; }); monthDaysRender->UpdateOpacity(0); @@ -256,7 +266,7 @@ void DateTimeAnimationController::PlayOldColumnOpacityOutAnimation() CHECK_NULL_VOID_NOLOG(timePickerRender); monthDaysRender->UpdateOpacity(1); timePickerRender->UpdateOpacity(1); - }); + }, animationOption.GetOnFinishEvent()); } void DateTimeAnimationController::PlayNewColumnOpacityOutAnimation() @@ -338,6 +348,7 @@ void DateTimeAnimationController::StopOldColumnOpacityOutAnimation() void DateTimeAnimationController::PlayInAnimation() { + isInAnimationPlaying_ = true; PlayTitleInAnimation(); PlayMovingInAnimation(); @@ -350,6 +361,7 @@ void DateTimeAnimationController::PlayInAnimation() void DateTimeAnimationController::PlayOutAnimation() { + isOutAnimationPlaying_ = true; PlayTitleOutAnimation(); PlayMovingOutAnimation(); diff --git a/frameworks/core/components_ng/pattern/picker/date_time_animation_controller.h b/frameworks/core/components_ng/pattern/picker/date_time_animation_controller.h index e19f0168b76..28d03ffd41d 100644 --- a/frameworks/core/components_ng/pattern/picker/date_time_animation_controller.h +++ b/frameworks/core/components_ng/pattern/picker/date_time_animation_controller.h @@ -99,6 +99,8 @@ private: std::shared_ptr oldColumnOpacityInAnimation_; std::shared_ptr oldColumnOpacityOutAnimation_; bool created_ = false; + bool isInAnimationPlaying_ = false; + bool isOutAnimationPlaying_ = false; }; } // namespace OHOS::Ace diff --git a/frameworks/core/components_ng/pattern/picker/datepicker_column_layout_algorithm.cpp b/frameworks/core/components_ng/pattern/picker/datepicker_column_layout_algorithm.cpp index 73145174a85..48175138062 100644 --- a/frameworks/core/components_ng/pattern/picker/datepicker_column_layout_algorithm.cpp +++ b/frameworks/core/components_ng/pattern/picker/datepicker_column_layout_algorithm.cpp @@ -45,7 +45,7 @@ void DatePickerColumnLayoutAlgorithm::Measure(LayoutWrapper* layoutWrapper) showCount_ = OPTION_COUNT_PHONE_LANDSCAPE; } auto height = static_cast(pickerTheme->GetGradientHeight().ConvertToPx() * (showCount_ - 1) + - pickerTheme->GetDividerSpacing().ConvertToPx()); + pickerTheme->GetDividerSpacing().ConvertToPx()); auto columnNode = layoutWrapper->GetHostNode(); CHECK_NULL_VOID(columnNode); auto stackNode = DynamicCast(columnNode->GetParent()); @@ -140,13 +140,18 @@ void DatePickerColumnLayoutAlgorithm::Layout(LayoutWrapper* layoutWrapper) auto children = layoutWrapper->GetAllChildrenWithBuild(); uint32_t halfCount = layoutWrapper->GetTotalChildCount() / 2; float childStartCoordinate = static_cast(pickerItemHeight_ / ITEM_HEIGHT_HALF - - pickerTheme->GetGradientHeight().ConvertToPx() * halfCount - - pickerTheme->GetDividerSpacing().ConvertToPx() / ITEM_HEIGHT_HALF); + pickerTheme->GetGradientHeight().ConvertToPx() * halfCount - + pickerTheme->GetDividerSpacing().ConvertToPx() / ITEM_HEIGHT_HALF); + uint32_t i = 0; + uint32_t showCount = pickerTheme->GetShowOptionCount(); for (const auto& child : children) { + if (i >= showCount) { + break; + } auto childGeometryNode = child->GetGeometryNode(); auto childSize = childGeometryNode->GetMarginFrameSize(); auto childOffset = - OffsetF(0.0f, childStartCoordinate + static_cast(currentOffset_) + padding.Offset().GetY()); + OffsetF(0.0f, childStartCoordinate + static_cast(currentOffset_[i++]) + padding.Offset().GetY()); childGeometryNode->SetMarginFrameOffset(childOffset); child->Layout(); childStartCoordinate += childSize.Height(); diff --git a/frameworks/core/components_ng/pattern/picker/datepicker_column_layout_algorithm.h b/frameworks/core/components_ng/pattern/picker/datepicker_column_layout_algorithm.h index 4c7569a89e5..b5340c506e8 100644 --- a/frameworks/core/components_ng/pattern/picker/datepicker_column_layout_algorithm.h +++ b/frameworks/core/components_ng/pattern/picker/datepicker_column_layout_algorithm.h @@ -37,20 +37,19 @@ public: void ChangeTextStyle(uint32_t index, uint32_t showOptionCount, const SizeF& size, const RefPtr& childLayoutWrapper, LayoutWrapper* layoutWrapper); - double GetCurrentOffset() const + std::vector GetCurrentOffset() const { return currentOffset_; } - void SetCurrentOffset(double currentOffset) + void SetCurrentOffset(const std::vector& currentOffset) { currentOffset_ = currentOffset; } private: - double currentOffset_ = 0.0; float pickerItemHeight_ = 0.0f; - + std::vector currentOffset_; ACE_DISALLOW_COPY_AND_MOVE(DatePickerColumnLayoutAlgorithm); }; } // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/pattern/picker/datepicker_column_pattern.cpp b/frameworks/core/components_ng/pattern/picker/datepicker_column_pattern.cpp index 4e0a9c32075..0cce6d3eb5e 100644 --- a/frameworks/core/components_ng/pattern/picker/datepicker_column_pattern.cpp +++ b/frameworks/core/components_ng/pattern/picker/datepicker_column_pattern.cpp @@ -20,6 +20,7 @@ #include #include +#include "base/utils/measure_util.h" #include "base/utils/utils.h" #include "core/components/common/layout/constants.h" #include "core/components/common/properties/color.h" @@ -46,11 +47,14 @@ const float TEXT_HEIGHT_NUMBER = 3.0f; const float TEXT_WEIGHT_NUMBER = 6.0f; const int32_t ANIMATION_ZERO_TO_OUTER = 200; const int32_t ANIMATION_OUTER_TO_ZERO = 150; +const int32_t OPTION_COUNT_PHONE_LANDSCAPE = 3; const Dimension FOCUS_SIZE = Dimension(1.0); const float MOVE_DISTANCE = 5.0f; constexpr int32_t HOVER_ANIMATION_DURATION = 250; constexpr int32_t PRESS_ANIMATION_DURATION = 100; +constexpr int32_t CLICK_ANIMATION_DURATION = 300; constexpr int32_t MINDDLE_CHILD_INDEX = 2; +const char* MEASURE_SIZE_STRING = "TEST"; } // namespace void DatePickerColumnPattern::OnAttachToFrameNode() @@ -80,8 +84,42 @@ void DatePickerColumnPattern::OnModifyDone() CHECK_NULL_VOID(theme); pressColor_ = theme->GetPressColor(); hoverColor_ = theme->GetHoverColor(); + auto showCount = theme->GetShowOptionCount(); InitMouseAndPressEvent(); SetAccessibilityAction(); + if (optionProperties_.empty()) { + auto midIndex = showCount / 2; + auto host = GetHost(); + CHECK_NULL_VOID(host); + dividerSpacing_ = pipeline->NormalizeToPx(theme->GetDividerSpacing()); + gradientHeight_ = static_cast(pipeline->NormalizeToPx(theme->GetGradientHeight())); + MeasureContext measureContext; + measureContext.textContent = MEASURE_SIZE_STRING; + uint32_t childIndex = 0; + DatePickerOptionProperty prop; + while (childIndex < showCount) { + if (childIndex == midIndex) { // selected + auto selectedOptionSize = theme->GetOptionStyle(true, false).GetFontSize(); + measureContext.fontSize = selectedOptionSize; + } else if (childIndex % midIndex == 1 && (childIndex != 0 || childIndex != (showCount - 1))) { + auto focusOptionSize = theme->GetOptionStyle(false, false).GetFontSize() + FONT_SIZE; + measureContext.fontSize = focusOptionSize; + } else { + auto normalOptionSize = theme->GetOptionStyle(false, false).GetFontSize(); + measureContext.fontSize = normalOptionSize; + } + if (childIndex == showCount / MINDDLE_CHILD_INDEX) { + prop.height = dividerSpacing_; + } else { + prop.height = gradientHeight_; + } + Size size = MeasureUtil::MeasureTextSize(measureContext); + prop.fontheight = size.Height(); + optionProperties_.emplace_back(prop); + childIndex++; + } + SetOptionShiftDistance(); + } } void DatePickerColumnPattern::InitMouseAndPressEvent() @@ -91,6 +129,7 @@ void DatePickerColumnPattern::InitMouseAndPressEvent() } auto host = GetHost(); CHECK_NULL_VOID(host); + auto childSize = static_cast(host->GetChildren().size()); RefPtr middleChild = nullptr; middleChild = DynamicCast(host->GetChildAtIndex(MINDDLE_CHILD_INDEX)); CHECK_NULL_VOID(middleChild); @@ -126,6 +165,24 @@ void DatePickerColumnPattern::InitMouseAndPressEvent() }; touchListener_ = MakeRefPtr(std::move(touchCallback)); gesture->AddTouchEvent(touchListener_); + for (int32_t i = 0; i < childSize; i++) { + RefPtr childNode = DynamicCast(host->GetChildAtIndex(i)); + CHECK_NULL_VOID(childNode); + RefPtr param = MakeRefPtr(); + param->instance_ = childNode; + param->itemIndex_ = i; + param->itemTotalCounts_ = childSize; + + auto eventHub = childNode->GetEventHub(); + CHECK_NULL_VOID(eventHub); + if (i != childSize / MINDDLE_CHILD_INDEX) { + RefPtr clickListener = CreateItemClickEventListener(param); + CHECK_NULL_VOID(clickListener); + auto gesture = eventHub->GetOrCreateGestureEventHub(); + CHECK_NULL_VOID(gesture); + gesture->AddClickEvent(clickListener); + } + } } void DatePickerColumnPattern::HandleMouseEvent(bool isHover) @@ -200,8 +257,8 @@ bool DatePickerColumnPattern::OnDirtyLayoutWrapperSwap( return true; } -void DatePickerColumnPattern::FlushCurrentOptions(bool isDown, bool isUpateTextContentOnly, - bool isUpdateAnimationProperties) +void DatePickerColumnPattern::FlushCurrentOptions( + bool isDown, bool isUpateTextContentOnly, bool isUpdateAnimationProperties) { auto host = GetHost(); CHECK_NULL_VOID(host); @@ -268,8 +325,8 @@ void DatePickerColumnPattern::FlushCurrentOptions(bool isDown, bool isUpateTextC } } -void DatePickerColumnPattern::UpdatePickerTextProperties( - uint32_t index, uint32_t showOptionCount, const RefPtr& textLayoutProperty, +void DatePickerColumnPattern::UpdatePickerTextProperties(uint32_t index, uint32_t showOptionCount, + const RefPtr& textLayoutProperty, const RefPtr& dataPickerRowLayoutProperty) { auto pipeline = PipelineBase::GetCurrentContext(); @@ -299,19 +356,20 @@ void DatePickerColumnPattern::UpdateDisappearTextProperties(const RefPtr& dataPickerRowLayoutProperty) { auto normalOptionSize = pickerTheme->GetOptionStyle(false, false).GetFontSize(); - if (dataPickerRowLayoutProperty->HasDisappearColor()) { - textLayoutProperty->UpdateTextColor(dataPickerRowLayoutProperty->GetDisappearColor().value()); - } + textLayoutProperty->UpdateTextColor(dataPickerRowLayoutProperty->GetDisappearColor().value_or( + pickerTheme->GetOptionStyle(false, false).GetTextColor())); if (dataPickerRowLayoutProperty->HasDisappearFontSize()) { textLayoutProperty->UpdateFontSize(dataPickerRowLayoutProperty->GetDisappearFontSize().value()); } else { textLayoutProperty->UpdateAdaptMaxFontSize(normalOptionSize); - textLayoutProperty->UpdateAdaptMinFontSize( - pickerTheme->GetOptionStyle(false, false).GetAdaptMinFontSize()); - } - if (dataPickerRowLayoutProperty->HasDisappearWeight()) { - textLayoutProperty->UpdateFontWeight(dataPickerRowLayoutProperty->GetDisappearWeight().value()); + textLayoutProperty->UpdateAdaptMinFontSize(pickerTheme->GetOptionStyle(false, false).GetAdaptMinFontSize()); } + textLayoutProperty->UpdateFontWeight(dataPickerRowLayoutProperty->GetDisappearWeight().value_or( + pickerTheme->GetOptionStyle(false, false).GetFontWeight())); + textLayoutProperty->UpdateFontFamily(dataPickerRowLayoutProperty->GetDisappearFontFamily().value_or( + pickerTheme->GetOptionStyle(false, false).GetFontFamilies())); + textLayoutProperty->UpdateItalicFontStyle(dataPickerRowLayoutProperty->GetDisappearFontStyle().value_or( + pickerTheme->GetOptionStyle(false, false).GetFontStyle())); } void DatePickerColumnPattern::UpdateCandidateTextProperties(const RefPtr& pickerTheme, @@ -319,9 +377,8 @@ void DatePickerColumnPattern::UpdateCandidateTextProperties(const RefPtr& dataPickerRowLayoutProperty) { auto focusOptionSize = pickerTheme->GetOptionStyle(false, false).GetFontSize() + FONT_SIZE; - if (dataPickerRowLayoutProperty->HasColor()) { - textLayoutProperty->UpdateTextColor(dataPickerRowLayoutProperty->GetColor().value()); - } + textLayoutProperty->UpdateTextColor(dataPickerRowLayoutProperty->GetColor().value_or( + pickerTheme->GetOptionStyle(false, false).GetTextColor())); if (dataPickerRowLayoutProperty->HasFontSize()) { textLayoutProperty->UpdateFontSize(dataPickerRowLayoutProperty->GetFontSize().value()); } else { @@ -329,9 +386,12 @@ void DatePickerColumnPattern::UpdateCandidateTextProperties(const RefPtrUpdateAdaptMinFontSize( pickerTheme->GetOptionStyle(true, false).GetAdaptMinFontSize() - FOCUS_SIZE); } - if (dataPickerRowLayoutProperty->HasWeight()) { - textLayoutProperty->UpdateFontWeight(dataPickerRowLayoutProperty->GetWeight().value()); - } + textLayoutProperty->UpdateFontWeight(dataPickerRowLayoutProperty->GetWeight().value_or( + pickerTheme->GetOptionStyle(false, false).GetFontWeight())); + textLayoutProperty->UpdateFontFamily(dataPickerRowLayoutProperty->GetFontFamily().value_or( + pickerTheme->GetOptionStyle(false, false).GetFontFamilies())); + textLayoutProperty->UpdateItalicFontStyle(dataPickerRowLayoutProperty->GetFontStyle().value_or( + pickerTheme->GetOptionStyle(false, false).GetFontStyle())); } void DatePickerColumnPattern::UpdateSelectedTextProperties(const RefPtr& pickerTheme, @@ -339,18 +399,20 @@ void DatePickerColumnPattern::UpdateSelectedTextProperties(const RefPtr& dataPickerRowLayoutProperty) { auto selectedOptionSize = pickerTheme->GetOptionStyle(true, false).GetFontSize(); - Color themeSelectedColor = pickerTheme->GetOptionStyle(true, false).GetTextColor(); - Color selectedColor = dataPickerRowLayoutProperty->GetSelectedColor().value_or(themeSelectedColor); - textLayoutProperty->UpdateTextColor(selectedColor); - FontWeight themeFontWeight = pickerTheme->GetOptionStyle(true, false).GetFontWeight(); - FontWeight selectedFontWeight = dataPickerRowLayoutProperty->GetSelectedWeight().value_or(themeFontWeight); - textLayoutProperty->UpdateFontWeight(selectedFontWeight); + textLayoutProperty->UpdateTextColor(dataPickerRowLayoutProperty->GetSelectedColor().value_or( + pickerTheme->GetOptionStyle(true, false).GetTextColor())); if (dataPickerRowLayoutProperty->HasSelectedFontSize()) { textLayoutProperty->UpdateFontSize(dataPickerRowLayoutProperty->GetSelectedFontSize().value()); } else { textLayoutProperty->UpdateAdaptMaxFontSize(selectedOptionSize); textLayoutProperty->UpdateAdaptMinFontSize(pickerTheme->GetOptionStyle(true, false).GetAdaptMinFontSize()); } + textLayoutProperty->UpdateFontWeight(dataPickerRowLayoutProperty->GetSelectedWeight().value_or( + pickerTheme->GetOptionStyle(true, false).GetFontWeight())); + textLayoutProperty->UpdateFontFamily(dataPickerRowLayoutProperty->GetSelectedFontFamily().value_or( + pickerTheme->GetOptionStyle(true, false).GetFontFamilies())); + textLayoutProperty->UpdateItalicFontStyle(dataPickerRowLayoutProperty->GetSelectedFontStyle().value_or( + pickerTheme->GetOptionStyle(true, false).GetFontStyle())); } void DatePickerColumnPattern::SetDividerHeight(uint32_t showOptionCount) @@ -375,8 +437,8 @@ bool DatePickerColumnPattern::NotLoopOptions() const return totalOptionCount <= showOptionCount / 2 + 1; // the critical value of loop condition. } -void DatePickerColumnPattern::AddAnimationTextProperties(uint32_t currentIndex, - const RefPtr& textLayoutProperty) +void DatePickerColumnPattern::AddAnimationTextProperties( + uint32_t currentIndex, const RefPtr& textLayoutProperty) { DateTextProperties properties; if (textLayoutProperty->HasFontSize()) { @@ -449,18 +511,20 @@ void DatePickerColumnPattern::FlushAnimationTextProperties(bool isDown) } } -void DatePickerColumnPattern::TextPropertiesLinearAnimation(const RefPtr& textLayoutProperty, - uint32_t index, uint32_t showCount, bool isDown, double scale) +void DatePickerColumnPattern::TextPropertiesLinearAnimation( + const RefPtr& textLayoutProperty, uint32_t index, uint32_t showCount, bool isDown, double scale) { if (index >= animationProperties_.size()) { LOGE("Animation Properties vactor is break."); return; } - if ((!index && isDown) || ((index == (showCount - 1)) && !isDown)) { - return; - } Dimension startFontSize = animationProperties_[index].fontSize; Color startColor = animationProperties_[index].currentColor; + if ((!index && isDown) || ((index == (showCount - 1)) && !isDown)) { + textLayoutProperty->UpdateFontSize(startFontSize); + textLayoutProperty->UpdateTextColor(startColor); + return; + } Dimension endFontSize; Color endColor; if (!isDown) { @@ -479,6 +543,9 @@ void DatePickerColumnPattern::TextPropertiesLinearAnimation(const RefPtr 1) { + return; + } auto host = GetHost(); CHECK_NULL_VOID(host); uint32_t showCount = GetShowCount(); @@ -495,20 +562,19 @@ void DatePickerColumnPattern::UpdateTextPropertiesLinear(bool isDown, double sca RefPtr textLayoutProperty = textPattern->GetLayoutProperty(); CHECK_NULL_VOID(textLayoutProperty); TextPropertiesLinearAnimation(textLayoutProperty, index, showCount, isDown, scale); - textNode->MarkModifyDone(); - textNode->MarkDirtyNode(PROPERTY_UPDATE_MEASURE); + iter++; } } -Dimension DatePickerColumnPattern::LinearFontSize(const Dimension& startFontSize, - const Dimension& endFontSize, double percent) +Dimension DatePickerColumnPattern::LinearFontSize( + const Dimension& startFontSize, const Dimension& endFontSize, double percent) { return startFontSize + (endFontSize - startFontSize) * percent; } -bool DatePickerColumnPattern::InnerHandleScroll(bool isDown, bool isUpatePropertiesOnly, - bool isUpdateAnimationProperties) +bool DatePickerColumnPattern::InnerHandleScroll( + bool isDown, bool isUpatePropertiesOnly, bool isUpdateAnimationProperties) { auto host = GetHost(); CHECK_NULL_RETURN(host, false); @@ -528,6 +594,25 @@ bool DatePickerColumnPattern::InnerHandleScroll(bool isDown, bool isUpatePropert FlushCurrentOptions(isDown, isUpatePropertiesOnly, isUpdateAnimationProperties); HandleChangeCallback(isDown, true); HandleEventCallback(true); + + auto textNodes = host->GetChildren(); + DatePickerScrollDirection dir = isDown ? DatePickerScrollDirection::DOWN : DatePickerScrollDirection::UP; + if (dir == DatePickerScrollDirection::UP) { + for (auto iter = textNodes.begin(); iter != (--textNodes.end()); iter++) { + auto curNode = DynamicCast(*iter); + auto shiftIter = std::next(iter, 1); + auto shiftNode = DynamicCast(*shiftIter); + ShiftOptionProp(curNode, shiftNode); + } + } else { + for (auto iter = textNodes.rbegin(); iter != (--textNodes.rend()); iter++) { + auto curNode = DynamicCast(*iter); + auto shiftIter = std::next(iter, 1); + auto shiftNode = DynamicCast(*shiftIter); + ShiftOptionProp(curNode, shiftNode); + } + } + host->MarkDirtyNode(PROPERTY_UPDATE_MEASURE_SELF_AND_CHILD); return true; } @@ -591,7 +676,7 @@ void DatePickerColumnPattern::HandleDragMove(const GestureEvent& event) CHECK_NULL_VOID_NOLOG(GetHost()); CHECK_NULL_VOID_NOLOG(GetToss()); auto toss = GetToss(); - double offsetY = event.GetGlobalPoint().GetY(); + auto offsetY = event.GetGlobalPoint().GetY(); if (NearEqual(offsetY, yLast_, 1.0)) { // if changing less than 1.0, no need to handle return; } @@ -617,12 +702,23 @@ void DatePickerColumnPattern::HandleDragEnd() ScrollOption(0.0); return; } + DatePickerScrollDirection dir = + scrollDelta_ > 0.0 ? DatePickerScrollDirection::DOWN : DatePickerScrollDirection::UP; + int32_t middleIndex = GetShowCount() / 2; + auto shiftDistance = (dir == DatePickerScrollDirection::UP) ? optionProperties_[middleIndex].prevDistance + : optionProperties_[middleIndex].nextDistance; + auto shiftThreshold = shiftDistance / 2; + if (std::abs(scrollDelta_) >= std::abs(shiftThreshold)) { + InnerHandleScroll(LessNotEqual(scrollDelta_, 0.0), true, false); + scrollDelta_ = scrollDelta_ - std::abs(shiftDistance) * (dir == DatePickerScrollDirection::UP ? -1 : 1); + } auto curve = CreateAnimation(scrollDelta_, 0.0); fromController_->ClearInterpolators(); fromController_->AddInterpolator(curve); fromController_->Play(); frameNode->OnAccessibilityEvent(AccessibilityEventType::SCROLL_END); } + void DatePickerColumnPattern::CreateAnimation() { CHECK_NULL_VOID_NOLOG(!animationCreated_); @@ -672,37 +768,44 @@ void DatePickerColumnPattern::HandleCurveStopped() void DatePickerColumnPattern::ScrollOption(double delta, bool isJump) { - UpdateScrollDelta(delta); - double oldDelta = scrollDelta_; scrollDelta_ = delta; + auto midIndex = GetShowCount() / 2; + DatePickerScrollDirection dir = delta > 0.0 ? DatePickerScrollDirection::DOWN : DatePickerScrollDirection::UP; + auto shiftDistance = (dir == DatePickerScrollDirection::UP) ? optionProperties_[midIndex].prevDistance + : optionProperties_[midIndex].nextDistance; + auto distancePercent = delta / shiftDistance; + auto textThresHold = optionProperties_[midIndex].height / 4; // ux required + auto textLinearPercent = 0.0; + if (std::abs(delta) > textThresHold) { + textLinearPercent = (std::abs(delta) - textThresHold) / (std::abs(shiftDistance) - textThresHold); + } + UpdateTextPropertiesLinear(LessNotEqual(delta, 0.0), textLinearPercent); + CalcAlgorithmOffset(dir, distancePercent); + auto host = GetHost(); + CHECK_NULL_VOID(host); + host->MarkDirtyNode(PROPERTY_UPDATE_MEASURE_SELF_AND_CHILD); +} - if ((isJump_ && LessOrEqual(delta * oldDelta, 0.0)) || NearZero(delta) || (isJump_ && isJump)) { - isJump_ = false; - FlushCurrentOptions(); - return; - } - if (isJump) { - isJump_ = true; - } - if (NearZero(jumpInterval_)) { - return; - } - double scale = 0.0; - if (!isJump_) { - scale = fabs(delta) / (jumpInterval_ * 2); - UpdateTextPropertiesLinear(LessNotEqual(delta, 0.0), scale); - } else { - scale = ((2 * jumpInterval_) - fabs(delta)) / (jumpInterval_ * 2); - UpdateTextPropertiesLinear(!LessNotEqual(delta, 0.0), scale); +void DatePickerColumnPattern::ResetAlgorithmOffset() +{ + algorithmOffset_.clear(); + + uint32_t counts = GetShowCount(); + for (uint32_t i = 0; i < counts; i++) { + algorithmOffset_.emplace_back(0.0f); } } -void DatePickerColumnPattern::UpdateScrollDelta(double delta) +void DatePickerColumnPattern::CalcAlgorithmOffset(DatePickerScrollDirection dir, double distancePercent) { - SetCurrentOffset(delta); - auto host = GetHost(); - CHECK_NULL_VOID(host); - host->MarkDirtyNode(PROPERTY_UPDATE_MEASURE_SELF); + algorithmOffset_.clear(); + uint32_t counts = GetShowCount(); + + for (uint32_t i = 0; i < counts; i++) { + auto distance = (dir == DatePickerScrollDirection::UP) ? optionProperties_[i].prevDistance + : optionProperties_[i].nextDistance; + algorithmOffset_.emplace_back(distance * distancePercent); + } } void DatePickerColumnPattern::UpdateToss(double offsetY) @@ -717,23 +820,190 @@ void DatePickerColumnPattern::TossStoped() ScrollOption(0.0); } +int32_t DatePickerColumnPattern::CalcScrollIndex( + int32_t totalOptionCount, int32_t currentIndex, bool canLoop, int32_t step) +{ + int32_t nextIndex = currentIndex; + if (!canLoop) { + // scroll down + if (step > 0) { + nextIndex = (currentIndex + step) > (totalOptionCount - 1) ? totalOptionCount - 1 : currentIndex + step; + // scroll up + } else if (step < 0) { + nextIndex = currentIndex + step < 0 ? 0 : currentIndex + step; + } + } else { + if (totalOptionCount != 0) { + nextIndex = (totalOptionCount + currentIndex + step) % totalOptionCount; + } + } + return nextIndex; +} + +float DatePickerColumnPattern::GetShiftDistance(uint32_t index, DatePickerScrollDirection dir) +{ + auto pipeline = PipelineBase::GetCurrentContext(); + CHECK_NULL_RETURN(pipeline, 0.0f); + auto theme = pipeline->GetTheme(); + CHECK_NULL_RETURN(theme, 0.0f); + uint32_t optionCounts = theme->GetShowOptionCount(); + LOGD("DatePickerColumnPattern::GetShiftDistance start showCount %{public}d", optionCounts); + uint32_t nextIndex = 0; + float distance = 0.0f; + float val = 0.0f; + auto isDown = dir == DatePickerScrollDirection::DOWN; + if (optionCounts == 0) { + return distance; + } + if (isDown) { + nextIndex = (optionCounts + index + 1) % optionCounts; // index add one + } else { + nextIndex = (optionCounts + index - 1) % optionCounts; // index reduce one + } + switch (static_cast(index)) { + case DatePickerOptionIndex::COLUMN_INDEX_0: // first + distance = (dir == DatePickerScrollDirection::DOWN) ? optionProperties_[index].height + : (0.0f - optionProperties_[index].height); + break; + case DatePickerOptionIndex::COLUMN_INDEX_1: + if (dir == DatePickerScrollDirection::UP) { + distance = -optionProperties_[nextIndex].height; + } else { + distance = optionProperties_[index].height + + (optionProperties_[nextIndex].height - optionProperties_[nextIndex].fontheight) / + MINDDLE_CHILD_INDEX; + } + break; + case DatePickerOptionIndex::COLUMN_INDEX_2: + val = optionProperties_[index].height / MINDDLE_CHILD_INDEX + optionProperties_[nextIndex].height - + optionProperties_[nextIndex].fontheight / MINDDLE_CHILD_INDEX; + distance = (dir == DatePickerScrollDirection::DOWN) ? val : (0.0f - val); + break; + case DatePickerOptionIndex::COLUMN_INDEX_3: + if (dir == DatePickerScrollDirection::DOWN) { + distance = optionProperties_[nextIndex].height; + } else { + val = optionProperties_[index].height + + (optionProperties_[nextIndex].height - optionProperties_[nextIndex].fontheight) / + MINDDLE_CHILD_INDEX; + distance = 0.0f - val; + } + break; + case DatePickerOptionIndex::COLUMN_INDEX_4: // last + distance = (dir == DatePickerScrollDirection::DOWN) ? optionProperties_[index].height + : (0.0f - optionProperties_[index].height); + break; + default: + break; + } + return distance; +} + +float DatePickerColumnPattern::GetShiftDistanceForLandscape(uint32_t index, DatePickerScrollDirection dir) +{ + auto pipeline = PipelineBase::GetCurrentContext(); + CHECK_NULL_RETURN(pipeline, 0.0f); + auto theme = pipeline->GetTheme(); + CHECK_NULL_RETURN(theme, 0.0f); + uint32_t optionCounts = theme->GetShowOptionCount(); + uint32_t nextIndex = 0; + float distance = 0.0f; + float val = 0.0f; + auto isDown = dir == DatePickerScrollDirection::DOWN; + if (optionCounts == 0) { + return distance; + } + if (isDown) { + nextIndex = (optionCounts + index + 1) % optionCounts; // index add one + } else { + nextIndex = (optionCounts + index - 1) % optionCounts; // index reduce one + } + + switch (static_cast(index)) { + case DatePickerOptionIndex::COLUMN_INDEX_0: // first + + if (dir == DatePickerScrollDirection::UP) { + distance = 0.0f - optionProperties_[index].height; + } else { + distance = optionProperties_[index].height + + (optionProperties_[nextIndex].height - optionProperties_[nextIndex].fontheight) / + MINDDLE_CHILD_INDEX; + } + break; + case DatePickerOptionIndex::COLUMN_INDEX_1: + val = optionProperties_[index].height / MINDDLE_CHILD_INDEX + optionProperties_[nextIndex].height - + optionProperties_[nextIndex].fontheight / MINDDLE_CHILD_INDEX; + distance = (dir == DatePickerScrollDirection::DOWN) ? val : (0.0f - val); + break; + case DatePickerOptionIndex::COLUMN_INDEX_2: // last + if (dir == DatePickerScrollDirection::DOWN) { + distance = optionProperties_[index].height; + } else { + val = optionProperties_[index].height + + (optionProperties_[nextIndex].height - optionProperties_[nextIndex].fontheight) / + MINDDLE_CHILD_INDEX; + distance = 0.0f - val; + } + break; + default: + break; + } + return distance; +} + +void DatePickerColumnPattern::SetOptionShiftDistance() +{ + auto pipeline = PipelineBase::GetCurrentContext(); + CHECK_NULL_VOID(pipeline); + auto theme = pipeline->GetTheme(); + CHECK_NULL_VOID(theme); + uint32_t itemCounts = theme->GetShowOptionCount(); + bool isLanscape = itemCounts == OPTION_COUNT_PHONE_LANDSCAPE; + for (uint32_t i = 0; i < itemCounts; i++) { + DatePickerOptionProperty& prop = optionProperties_[i]; + if (isLanscape) { + prop.prevDistance = GetShiftDistanceForLandscape(i, DatePickerScrollDirection::UP); + prop.nextDistance = GetShiftDistanceForLandscape(i, DatePickerScrollDirection::DOWN); + } else { + prop.prevDistance = GetShiftDistance(i, DatePickerScrollDirection::UP); + prop.nextDistance = GetShiftDistance(i, DatePickerScrollDirection::DOWN); + } + } +} + void DatePickerColumnPattern::UpdateColumnChildPosition(double offsetY) { yLast_ = offsetY; - double dragDelta = yLast_ - yOffset_; + auto dragDelta = yLast_ - yOffset_; if (!CanMove(LessNotEqual(dragDelta, 0))) { return; } + auto midIndex = GetShowCount() / 2; + DatePickerScrollDirection dir = dragDelta > 0.0 ? DatePickerScrollDirection::DOWN : DatePickerScrollDirection::UP; + auto shiftDistance = (dir == DatePickerScrollDirection::UP) ? optionProperties_[midIndex].prevDistance + : optionProperties_[midIndex].nextDistance; // the abs of drag delta is less than jump interval. - if (LessNotEqual(0.0 - jumpInterval_, dragDelta) && LessNotEqual(dragDelta, jumpInterval_)) { - ScrollOption(dragDelta); - return; + if (GreatOrEqual(std::abs(dragDelta), std::abs(shiftDistance))) { + InnerHandleScroll(LessNotEqual(dragDelta, 0.0), true, false); + dragDelta = dragDelta - (abs(shiftDistance) * (LessNotEqual(dragDelta, 0.0) ? -1 : 1)); + yOffset_ = offsetY; } // update selected option - InnerHandleScroll(LessNotEqual(dragDelta, 0.0), true, true); - double jumpDelta = (LessNotEqual(dragDelta, 0.0) ? jumpInterval_ : 0.0 - jumpInterval_); - ScrollOption(jumpDelta, true); - yOffset_ = offsetY - jumpDelta; + ScrollOption(dragDelta); +} + +void DatePickerColumnPattern::ShiftOptionProp(RefPtr curNode, RefPtr shiftNode) +{ + RefPtr curPattern = curNode->GetPattern(); + CHECK_NULL_VOID(curPattern); + RefPtr curLayoutProperty = curPattern->GetLayoutProperty(); + CHECK_NULL_VOID(curLayoutProperty); + + RefPtr shiftPattern = shiftNode->GetPattern(); + CHECK_NULL_VOID(shiftPattern); + RefPtr shiftLayoutProperty = shiftPattern->GetLayoutProperty(); + CHECK_NULL_VOID(shiftLayoutProperty); + curLayoutProperty->UpdateFontWeight(shiftLayoutProperty->GetFontWeight().value_or(FontWeight::W100)); } bool DatePickerColumnPattern::CanMove(bool isDown) const @@ -789,4 +1059,38 @@ void DatePickerColumnPattern::SetAccessibilityAction() frameNode->OnAccessibilityEvent(AccessibilityEventType::SCROLL_END); }); } + +RefPtr DatePickerColumnPattern::CreateItemClickEventListener(RefPtr param) +{ + auto clickEventHandler = [param, weak = WeakClaim(this)](const GestureEvent& /* info */) { + auto pattern = weak.Upgrade(); + pattern->OnAroundButtonClick(param); + }; + auto listener = AceType::MakeRefPtr(clickEventHandler); + return listener; +} + +void DatePickerColumnPattern::OnAroundButtonClick(RefPtr param) +{ + int32_t middleIndex = GetShowCount() / 2; + int32_t step = param->itemIndex_ - middleIndex; + if (step != 0) { + if (fromController_->IsRunning()) { + fromController_->Finish(); + } + for (int32_t i = 0; i < abs(step); i++) { + InnerHandleScroll(step > 0 ? true : false); + } + auto distance = + (step > 0 ? optionProperties_[middleIndex].prevDistance : optionProperties_[middleIndex].nextDistance) * + std::abs(step); + auto curveTop = CreateAnimation(abs(distance), 0.0); + auto curveBottom = CreateAnimation(0 - abs(distance), 0.0); + fromController_->ClearInterpolators(); + + fromController_->AddInterpolator(step > 0 ? curveTop : curveBottom); + fromController_->SetDuration(CLICK_ANIMATION_DURATION); + fromController_->Play(); + } +} } // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/pattern/picker/datepicker_column_pattern.h b/frameworks/core/components_ng/pattern/picker/datepicker_column_pattern.h index 2dbf3d43d35..4c170ddd57c 100644 --- a/frameworks/core/components_ng/pattern/picker/datepicker_column_pattern.h +++ b/frameworks/core/components_ng/pattern/picker/datepicker_column_pattern.h @@ -28,8 +28,8 @@ #include "core/components_ng/pattern/picker/datepicker_layout_property.h" #include "core/components_ng/pattern/picker/datepicker_paint_method.h" #include "core/components_ng/pattern/picker/datepicker_row_layout_property.h" -#include "core/components_ng/pattern/text/text_layout_property.h" #include "core/components_ng/pattern/picker/toss_animation_controller.h" +#include "core/components_ng/pattern/text/text_layout_property.h" #include "core/pipeline_ng/ui_task_scheduler.h" namespace OHOS::Ace::NG { @@ -47,6 +47,34 @@ struct DateTextProperties { Color downColor; }; +struct DatePickerOptionProperty { + float height = 0.0f; + float fontheight = 0.0f; + float prevDistance = 0.0f; // between the prev item and itself when scroll up + float nextDistance = 0.0f; // between the next item and itself when scroll down +}; + +class DatePickerEventParam : public virtual AceType { + DECLARE_ACE_TYPE(DatePickerEventParam, AceType) + +public: + RefPtr instance_; + int32_t itemIndex_ = 0; + int32_t itemTotalCounts_ = 0; +}; + +enum class DatePickerScrollDirection { + UP = 0, + DOWN, +}; +enum class DatePickerOptionIndex { + COLUMN_INDEX_0 = 0, + COLUMN_INDEX_1, + COLUMN_INDEX_2, + COLUMN_INDEX_3, + COLUMN_INDEX_4, +}; + class DatePickerColumnPattern : public LinearLayoutPattern { DECLARE_ACE_TYPE(DatePickerColumnPattern, LinearLayoutPattern); @@ -58,7 +86,10 @@ public: RefPtr CreateLayoutAlgorithm() override { auto layoutAlgorithm = MakeRefPtr(); - layoutAlgorithm->SetCurrentOffset(GetCurrentOffset()); + if (algorithmOffset_.size() == 0) { + ResetAlgorithmOffset(); + } + layoutAlgorithm->SetCurrentOffset(algorithmOffset_); return layoutAlgorithm; } @@ -72,8 +103,8 @@ public: return MakeRefPtr(); } - void FlushCurrentOptions(bool isDown = false, bool isUpateTextContentOnly = false, - bool isUpdateAnimationProperties = false); + void FlushCurrentOptions( + bool isDown = false, bool isUpateTextContentOnly = false, bool isUpdateAnimationProperties = false); bool NotLoopOptions() const; @@ -181,8 +212,6 @@ public: void TossStoped(); - void UpdateScrollDelta(double delta); - private: void OnModifyDone() override; void OnAttachToFrameNode() override; @@ -196,6 +225,18 @@ private: void PlayPressAnimation(const Color& pressColor); void PlayHoverAnimation(const Color& color); + std::vector optionProperties_; + RefPtr CreateItemClickEventListener(RefPtr param); + void OnAroundButtonClick(RefPtr param); + std::vector algorithmOffset_; + void ResetAlgorithmOffset(); + void CalcAlgorithmOffset(DatePickerScrollDirection dir, double distancePercent); + void SetOptionShiftDistance(); + float GetShiftDistanceForLandscape(uint32_t index, DatePickerScrollDirection dir); + float GetShiftDistance(uint32_t index, DatePickerScrollDirection dir); + int32_t CalcScrollIndex(int32_t totalOptionCount, int32_t currentIndex, bool canLoop, int32_t step); + void ShiftOptionProp(RefPtr curNode, RefPtr shiftNode); + void InitPanEvent(const RefPtr& gestureHub); void HandleDragStart(const GestureEvent& event); void HandleDragMove(const GestureEvent& event); @@ -218,8 +259,8 @@ private: const RefPtr& timePickerLayoutProperty); void AddAnimationTextProperties(uint32_t currentIndex, const RefPtr& textLayoutProperty); void UpdateTextPropertiesLinear(bool isDown, double scale); - void TextPropertiesLinearAnimation(const RefPtr& textLayoutProperty, - uint32_t index, uint32_t showCount, bool isDown, double scale); + void TextPropertiesLinearAnimation(const RefPtr& textLayoutProperty, uint32_t index, + uint32_t showCount, bool isDown, double scale); void FlushAnimationTextProperties(bool isDown); Dimension LinearFontSize(const Dimension& startFontSize, const Dimension& endFontSize, double percent); void SetAccessibilityAction(); @@ -238,6 +279,9 @@ private: float gradientHeight_; float dividerHeight_; float dividerSpacingWidth_; + + float dividerSpacing_ = 0.0f; + Color pressColor_; Color hoverColor_; @@ -253,7 +297,6 @@ private: RefPtr> fromTopCurve_; RefPtr tossAnimationController_ = AceType::MakeRefPtr(); std::vector animationProperties_; - bool isJump_ = false; ACE_DISALLOW_COPY_AND_MOVE(DatePickerColumnPattern); }; diff --git a/frameworks/core/components_ng/pattern/picker/datepicker_dialog_view.cpp b/frameworks/core/components_ng/pattern/picker/datepicker_dialog_view.cpp index a1005eed72c..d10792ef40d 100644 --- a/frameworks/core/components_ng/pattern/picker/datepicker_dialog_view.cpp +++ b/frameworks/core/components_ng/pattern/picker/datepicker_dialog_view.cpp @@ -109,6 +109,8 @@ RefPtr DatePickerDialogView::Show(const DialogProperties& dialogPrope auto monthDaysPickerPattern = monthDaysNode->GetPattern(); CHECK_NULL_RETURN(monthDaysPickerPattern, nullptr); monthDaysPickerPattern->SetTitleId(pickerPattern->GetTitleId()); + monthDaysPickerPattern->SetShowTimeFlag(true); + pickerPattern->SetShowTimeFlag(true); auto monthDaysLayoutProperty = monthDaysNode->GetLayoutProperty(); CHECK_NULL_RETURN(monthDaysLayoutProperty, nullptr); monthDaysLayoutProperty->UpdateUserDefinedIdealSize( @@ -119,6 +121,17 @@ RefPtr DatePickerDialogView::Show(const DialogProperties& dialogPrope monthDaysNode->MarkModifyDone(); monthDaysNode->MountToParent(pickerRow); auto timeNode = CreateTimeNode(settingData.timePickerProperty, settingData.properties, settingData.useMilitary); + auto timePickerEventHub = timeNode->GetEventHub(); + CHECK_NULL_RETURN(timePickerEventHub, nullptr); + auto onChangeCallback = [monthDaysNode]() { + auto pickerPattern = monthDaysNode->GetPattern(); + CHECK_NULL_VOID(pickerPattern); + auto str = pickerPattern->GetSelectedObject(true); + auto datePickerEventHub = pickerPattern->GetEventHub(); + CHECK_NULL_VOID(datePickerEventHub); + datePickerEventHub->FireDialogChangeEvent(str); + }; + timePickerEventHub->SetOnChangeForDatePicker(std::move(onChangeCallback)); auto timeLayoutProperty = timeNode->GetLayoutProperty(); CHECK_NULL_RETURN(timeLayoutProperty, nullptr); timeLayoutProperty->UpdateUserDefinedIdealSize( @@ -210,7 +223,15 @@ RefPtr DatePickerDialogView::Show(const DialogProperties& dialogPrope // build dialog accept and cancel button auto changeEvent = dialogEvent["changeId"]; + auto dateChangeEvent = dialogEvent["dateChangeId"]; + if (settingData.showTime) { + auto changeEventSame = changeEvent; + auto dateChangeEventSame = dateChangeEvent; + SetDialogChange(acceptNode, std::move(changeEventSame)); + SetDialogDateChange(acceptNode, std::move(dateChangeEventSame)); + } SetDialogChange(dateNode, std::move(changeEvent)); + SetDialogDateChange(dateNode, std::move(dateChangeEvent)); auto contentRow = CreateButtonNode(acceptNode, dateNode, dialogEvent, std::move(dialogCancelEvent)); CHECK_NULL_RETURN(contentRow, nullptr); auto event = [dialogNode](const GestureEvent& /* info */) { @@ -346,6 +367,7 @@ RefPtr DatePickerDialogView::CreateButtonNode(const RefPtr std::map dialogCancelEvent) { auto acceptEvent = dialogEvent["acceptId"]; + auto dateAcceptEvent = dialogEvent["dateAcceptId"]; auto cancelEvent = dialogCancelEvent["cancelId"]; auto contentRow = FrameNode::CreateFrameNode(V2::COLUMN_ETS_TAG, ElementRegister::GetInstance()->MakeUniqueId(), AceType::MakeRefPtr(false)); @@ -356,6 +378,7 @@ RefPtr DatePickerDialogView::CreateButtonNode(const RefPtr layoutProps->UpdateMeasureType(MeasureType::MATCH_PARENT_MAIN_AXIS); contentRow->SetNeedCallChildrenUpdate(false); + SetDialogDateAcceptEvent(dateNode, std::move(dateAcceptEvent)); auto buttonCancelNode = CreateCancelNode(cancelEvent, datePickerNode); auto buttonConfirmNode = CreateConfirmNode(dateNode, datePickerNode, acceptEvent); @@ -782,6 +805,14 @@ void DatePickerDialogView::SetDialogChange(const RefPtr& frameNode, D eventHub->SetDialogChange(std::move(onChange)); } +void DatePickerDialogView::SetDialogDateChange(const RefPtr& frameNode, DialogEvent&& onChange) +{ + CHECK_NULL_VOID(frameNode); + auto eventHub = frameNode->GetEventHub(); + CHECK_NULL_VOID(eventHub); + eventHub->SetDialogDateChange(std::move(onChange)); +} + void DatePickerDialogView::SetDialogAcceptEvent(const RefPtr& frameNode, DialogEvent&& onChange) { CHECK_NULL_VOID(frameNode); @@ -790,6 +821,14 @@ void DatePickerDialogView::SetDialogAcceptEvent(const RefPtr& frameNo eventHub->SetDialogAcceptEvent(std::move(onChange)); } +void DatePickerDialogView::SetDialogDateAcceptEvent(const RefPtr& frameNode, DialogEvent&& onChange) +{ + CHECK_NULL_VOID(frameNode); + auto eventHub = frameNode->GetEventHub(); + CHECK_NULL_VOID(eventHub); + eventHub->SetDialogDateAcceptEvent(std::move(onChange)); +} + void DatePickerDialogView::SetDialogSwitchEvent(std::function switchEvent) { auto pipeline = PipelineContext::GetCurrentContext(); @@ -821,6 +860,10 @@ void DatePickerDialogView::SetDateTextProperties( properties.disappearTextStyle_.textColor.value_or(disappearStyle.GetTextColor())); pickerProperty->UpdateDisappearWeight( properties.disappearTextStyle_.fontWeight.value_or(disappearStyle.GetFontWeight())); + pickerProperty->UpdateDisappearFontFamily( + properties.disappearTextStyle_.fontFamily.value_or(disappearStyle.GetFontFamilies())); + pickerProperty->UpdateDisappearFontStyle( + properties.disappearTextStyle_.fontStyle.value_or(disappearStyle.GetFontStyle())); if (properties.normalTextStyle_.fontSize.has_value() && properties.normalTextStyle_.fontSize->IsValid()) { pickerProperty->UpdateFontSize(properties.normalTextStyle_.fontSize.value()); @@ -829,6 +872,8 @@ void DatePickerDialogView::SetDateTextProperties( } pickerProperty->UpdateColor(properties.normalTextStyle_.textColor.value_or(normalStyle.GetTextColor())); pickerProperty->UpdateWeight(properties.normalTextStyle_.fontWeight.value_or(normalStyle.GetFontWeight())); + pickerProperty->UpdateFontFamily(properties.normalTextStyle_.fontFamily.value_or(normalStyle.GetFontFamilies())); + pickerProperty->UpdateFontStyle(properties.normalTextStyle_.fontStyle.value_or(normalStyle.GetFontStyle())); if (properties.selectedTextStyle_.fontSize.has_value() && properties.selectedTextStyle_.fontSize->IsValid()) { pickerProperty->UpdateSelectedFontSize(properties.selectedTextStyle_.fontSize.value()); @@ -838,6 +883,10 @@ void DatePickerDialogView::SetDateTextProperties( pickerProperty->UpdateSelectedColor(properties.selectedTextStyle_.textColor.value_or(selectedStyle.GetTextColor())); pickerProperty->UpdateSelectedWeight( properties.selectedTextStyle_.fontWeight.value_or(selectedStyle.GetFontWeight())); + pickerProperty->UpdateSelectedFontFamily( + properties.selectedTextStyle_.fontFamily.value_or(selectedStyle.GetFontFamilies())); + pickerProperty->UpdateSelectedFontStyle( + properties.selectedTextStyle_.fontStyle.value_or(selectedStyle.GetFontStyle())); } void DatePickerDialogView::SetTimeTextProperties( diff --git a/frameworks/core/components_ng/pattern/picker/datepicker_dialog_view.h b/frameworks/core/components_ng/pattern/picker/datepicker_dialog_view.h index 3890c47ca4b..57c8622a385 100644 --- a/frameworks/core/components_ng/pattern/picker/datepicker_dialog_view.h +++ b/frameworks/core/components_ng/pattern/picker/datepicker_dialog_view.h @@ -38,7 +38,9 @@ public: static void SetDateTextProperties(const RefPtr& frameNode, const PickerTextProperties& properties); static void SetTimeTextProperties(const RefPtr& frameNode, const PickerTextProperties& properties); static void SetDialogChange(const RefPtr& frameNode, DialogEvent&& onChange); + static void SetDialogDateChange(const RefPtr& frameNode, DialogEvent&& onChange); static void SetDialogAcceptEvent(const RefPtr& frameNode, DialogEvent&& onChange); + static void SetDialogDateAcceptEvent(const RefPtr& frameNode, DialogEvent&& onChange); static void SetDialogSwitchEvent(std::function switchEvent); static RefPtr CreateButtonNode(const RefPtr& frameNode, const RefPtr& datePickerNode, diff --git a/frameworks/core/components_ng/pattern/picker/datepicker_event_hub.h b/frameworks/core/components_ng/pattern/picker/datepicker_event_hub.h index b35be5f3529..c21a503a83a 100644 --- a/frameworks/core/components_ng/pattern/picker/datepicker_event_hub.h +++ b/frameworks/core/components_ng/pattern/picker/datepicker_event_hub.h @@ -39,6 +39,11 @@ public: changeEvent_ = std::move(onChange); } + void SetOnDateChange(DateChangeEvent&& onChange) + { + dateChangeEvent_ = std::move(onChange); + } + void FireChangeEvent(const BaseEventInfo* info) const { if (selectedChangeEvent_) { @@ -47,6 +52,9 @@ public: if (changeEvent_) { changeEvent_(info); } + if (dateChangeEvent_) { + dateChangeEvent_(info); + } } void SetDialogChange(DialogEvent&& onChange) @@ -59,6 +67,9 @@ public: if (dialogChangeEvent_) { dialogChangeEvent_(info); } + if (dialogDateChangeEvent_) { + dialogDateChangeEvent_(info); + } } void SetDialogAcceptEvent(DialogEvent&& onChange) @@ -71,6 +82,19 @@ public: if (dialogAcceptEvent_) { dialogAcceptEvent_(info); } + if (dialogDateAcceptEvent_) { + dialogDateAcceptEvent_(info); + } + } + + void SetDialogDateChange(DialogEvent&& onChange) + { + dialogDateChangeEvent_ = std::move(onChange); + } + + void SetDialogDateAcceptEvent(DialogEvent&& onChange) + { + dialogDateAcceptEvent_ = std::move(onChange); } void SetChangeEvent(DateChangeEvent&& onChange) @@ -80,8 +104,11 @@ public: private: DateChangeEvent changeEvent_; + DateChangeEvent dateChangeEvent_; DialogEvent dialogChangeEvent_; DialogEvent dialogAcceptEvent_; + DialogEvent dialogDateChangeEvent_; + DialogEvent dialogDateAcceptEvent_; DateChangeEvent selectedChangeEvent_; ACE_DISALLOW_COPY_AND_MOVE(DatePickerEventHub); diff --git a/frameworks/core/components_ng/pattern/picker/datepicker_model_ng.cpp b/frameworks/core/components_ng/pattern/picker/datepicker_model_ng.cpp index c7e68535e8b..a9d81176ded 100644 --- a/frameworks/core/components_ng/pattern/picker/datepicker_model_ng.cpp +++ b/frameworks/core/components_ng/pattern/picker/datepicker_model_ng.cpp @@ -188,6 +188,15 @@ void DatePickerModelNG::SetOnChange(DateChangeEvent&& onChange) eventHub->SetOnChange(std::move(onChange)); } +void DatePickerModelNG::SetOnDateChange(DateChangeEvent&& onChange) +{ + auto frameNode = ViewStackProcessor::GetInstance()->GetMainFrameNode(); + CHECK_NULL_VOID(frameNode); + auto eventHub = frameNode->GetEventHub(); + CHECK_NULL_VOID(eventHub); + eventHub->SetOnDateChange(std::move(onChange)); +} + void DatePickerModelNG::SetDisappearTextStyle(const RefPtr& theme, const PickerTextStyle& value) { CHECK_NULL_VOID(theme); @@ -201,6 +210,10 @@ void DatePickerModelNG::SetDisappearTextStyle(const RefPtr& theme, DataPickerRowLayoutProperty, DisappearColor, value.textColor.value_or(disappearStyle.GetTextColor())); ACE_UPDATE_LAYOUT_PROPERTY( DataPickerRowLayoutProperty, DisappearWeight, value.fontWeight.value_or(disappearStyle.GetFontWeight())); + ACE_UPDATE_LAYOUT_PROPERTY( + DataPickerRowLayoutProperty, DisappearFontFamily, value.fontFamily.value_or(disappearStyle.GetFontFamilies())); + ACE_UPDATE_LAYOUT_PROPERTY( + DataPickerRowLayoutProperty, DisappearFontStyle, value.fontStyle.value_or(disappearStyle.GetFontStyle())); } void DatePickerModelNG::SetNormalTextStyle(const RefPtr& theme, const PickerTextStyle& value) @@ -216,6 +229,10 @@ void DatePickerModelNG::SetNormalTextStyle(const RefPtr& theme, con DataPickerRowLayoutProperty, Color, value.textColor.value_or(normalStyle.GetTextColor())); ACE_UPDATE_LAYOUT_PROPERTY( DataPickerRowLayoutProperty, Weight, value.fontWeight.value_or(normalStyle.GetFontWeight())); + ACE_UPDATE_LAYOUT_PROPERTY( + DataPickerRowLayoutProperty, FontFamily, value.fontFamily.value_or(normalStyle.GetFontFamilies())); + ACE_UPDATE_LAYOUT_PROPERTY( + DataPickerRowLayoutProperty, FontStyle, value.fontStyle.value_or(normalStyle.GetFontStyle())); } void DatePickerModelNG::SetSelectedTextStyle(const RefPtr& theme, const PickerTextStyle& value) @@ -231,6 +248,10 @@ void DatePickerModelNG::SetSelectedTextStyle(const RefPtr& theme, c DataPickerRowLayoutProperty, SelectedColor, value.textColor.value_or(selectedStyle.GetTextColor())); ACE_UPDATE_LAYOUT_PROPERTY( DataPickerRowLayoutProperty, SelectedWeight, value.fontWeight.value_or(selectedStyle.GetFontWeight())); + ACE_UPDATE_LAYOUT_PROPERTY( + DataPickerRowLayoutProperty, SelectedFontFamily, value.fontFamily.value_or(selectedStyle.GetFontFamilies())); + ACE_UPDATE_LAYOUT_PROPERTY( + DataPickerRowLayoutProperty, SelectedFontStyle, value.fontStyle.value_or(selectedStyle.GetFontStyle())); } void DatePickerModelNG::SetBackgroundColor(const Color& color) @@ -254,6 +275,7 @@ void DatePickerModelNG::SetChangeEvent(DateChangeEvent&& onChange) void DatePickerDialogModelNG::SetDatePickerDialogShow(PickerDialogInfo& pickerDialog, NG::DatePickerSettingData& settingData, std::function&& onCancel, std::function&& onAccept, std::function&& onChange, + std::function&& onDateAccept, std::function&& onDateChange, DatePickerType pickerType) { auto container = Container::Current(); @@ -286,6 +308,8 @@ void DatePickerDialogModelNG::SetDatePickerDialogShow(PickerDialogInfo& pickerDi std::map dialogCancelEvent; dialogEvent["changeId"] = onChange; dialogEvent["acceptId"] = onAccept; + dialogEvent["dateChangeId"] = onDateChange; + dialogEvent["dateAcceptId"] = onDateAccept; auto func = [onCancel](const GestureEvent& /* info */) { if (onCancel) { onCancel(); diff --git a/frameworks/core/components_ng/pattern/picker/datepicker_model_ng.h b/frameworks/core/components_ng/pattern/picker/datepicker_model_ng.h index d0a77da133b..dfee831e473 100644 --- a/frameworks/core/components_ng/pattern/picker/datepicker_model_ng.h +++ b/frameworks/core/components_ng/pattern/picker/datepicker_model_ng.h @@ -32,6 +32,7 @@ public: void SetSelectedDate(const PickerDate& value) override; void SetShowLunar(bool lunar) override; void SetOnChange(DateChangeEvent&& onChange) override; + void SetOnDateChange(DateChangeEvent&& onChange) override; void SetSelectedTime(const PickerTime& selectedTime) override {}; void SetHour24(bool value) override {}; void SetDisappearTextStyle(const RefPtr& theme, const PickerTextStyle& value) override; @@ -49,7 +50,8 @@ class ACE_EXPORT DatePickerDialogModelNG : public DatePickerDialogModel { public: void SetDatePickerDialogShow(PickerDialogInfo& pickerDialog, NG::DatePickerSettingData& settingData, std::function&& onCancel, std::function&& onAccept, - std::function&& onChange, DatePickerType pickerType) override; + std::function&& onChange, std::function&& onDateAccept, + std::function&& onDateChange, DatePickerType pickerType) override; }; } // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/pattern/picker/datepicker_pattern.cpp b/frameworks/core/components_ng/pattern/picker/datepicker_pattern.cpp index 58c5cab26b0..2efb6ae1e30 100644 --- a/frameworks/core/components_ng/pattern/picker/datepicker_pattern.cpp +++ b/frameworks/core/components_ng/pattern/picker/datepicker_pattern.cpp @@ -55,6 +55,7 @@ void DatePickerPattern::OnAttachToFrameNode() auto host = GetHost(); CHECK_NULL_VOID(host); host->GetRenderContext()->SetClipToFrame(true); + host->GetRenderContext()->UpdateClipEdge(true); } bool DatePickerPattern::OnDirtyLayoutWrapperSwap(const RefPtr& dirty, const DirtySwapConfig& config) @@ -583,6 +584,46 @@ void DatePickerPattern::HandleMonthDaysChange( resultTags.emplace_back(monthDaysNode); } +std::string DatePickerPattern::GetSelectedObject(bool isColumnChange, int status) const +{ + auto date = selectedDate_; + if (isColumnChange) { + date = GetCurrentDate(); + } + // W3C's month is between 0 to 11, need to reduce one. + date.SetMonth(date.GetMonth() - 1); + + auto dateTimeString = std::string("{\"year\":") + std::to_string(date.GetYear()) + ",\"month\":" + + std::to_string(date.GetMonth()) + ",\"day\":" + std::to_string(date.GetDay()); + auto pickTime = PickerTime::Current(); + if (showTime_) { + auto host = GetHost(); + CHECK_NULL_RETURN(host, date.ToString(true, status)); + if (showMonthDays_) { + auto pickerRow = host->GetParent(); + CHECK_NULL_RETURN(pickerRow, date.ToString(true, status)); + auto timeNode = AceType::DynamicCast(pickerRow->GetChildAtIndex(1)); + CHECK_NULL_RETURN(timeNode, date.ToString(true, status)); + auto timePickerPattern = timeNode->GetPattern(); + CHECK_NULL_RETURN(timePickerPattern, date.ToString(true, status)); + pickTime = timePickerPattern->GetCurrentTime(); + } else { + auto pickerStack = host->GetParent(); + CHECK_NULL_RETURN(pickerStack, date.ToString(true, status)); + auto pickerRow = pickerStack->GetLastChild(); + CHECK_NULL_RETURN(pickerRow, date.ToString(true, status)); + auto timeNode = AceType::DynamicCast(pickerRow->GetChildAtIndex(1)); + CHECK_NULL_RETURN(timeNode, date.ToString(true, status)); + auto timePickerPattern = timeNode->GetPattern(); + CHECK_NULL_RETURN(timePickerPattern, date.ToString(true, status)); + pickTime = timePickerPattern->GetCurrentTime(); + } + } + dateTimeString += std::string(",\"hour\":") + std::to_string(pickTime.GetHour()) + ",\"minute\":" + + std::to_string(pickTime.GetMinute()) + ",\"status\":" + std::to_string(status) + "}"; + return dateTimeString; +} + void DatePickerPattern::HandleDayChange(bool isAdd, uint32_t index, std::vector>& resultTags) { auto allChildNode = GetAllChildNode(); diff --git a/frameworks/core/components_ng/pattern/picker/datepicker_pattern.h b/frameworks/core/components_ng/pattern/picker/datepicker_pattern.h index 6c542a18cf1..00f143afc78 100644 --- a/frameworks/core/components_ng/pattern/picker/datepicker_pattern.h +++ b/frameworks/core/components_ng/pattern/picker/datepicker_pattern.h @@ -192,6 +192,11 @@ public: return showMonthDays_; } + void SetShowTimeFlag(bool value) + { + showTime_ = value; + } + const EventMarker& GetDialogAcceptEvent() const { return OnDialogAccept_; @@ -320,16 +325,7 @@ public: void HandleMonthDaysChange( const RefPtr& tag, bool isAdd, uint32_t index, std::vector>& resultTags); - std::string GetSelectedObject(bool isColumnChange, int status = -1) const - { - auto date = selectedDate_; - if (isColumnChange) { - date = GetCurrentDate(); - } - // W3C's month is between 0 to 11, need to reduce one. - date.SetMonth(date.GetMonth() - 1); - return date.ToString(true, status); - } + std::string GetSelectedObject(bool isColumnChange, int status = -1) const; const LunarDate& GetSelectDate() { @@ -598,6 +594,7 @@ private: std::vector> datePickerColumns_; bool lunar_ = false; bool showMonthDays_ = false; + bool showTime_ = false; Color backgroundColor_ = Color::WHITE; std::optional yearId_; std::optional monthId_; diff --git a/frameworks/core/components_ng/pattern/picker/datepicker_row_layout_property.h b/frameworks/core/components_ng/pattern/picker/datepicker_row_layout_property.h index 3cbd2bcbf0a..04692548e7d 100644 --- a/frameworks/core/components_ng/pattern/picker/datepicker_row_layout_property.h +++ b/frameworks/core/components_ng/pattern/picker/datepicker_row_layout_property.h @@ -16,6 +16,8 @@ #ifndef FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_NG_PATTERN_DATE_PICKER_DATE_PICKER_ROW_LAYOUT_PROPERTY_H #define FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_NG_PATTERN_DATE_PICKER_DATE_PICKER_ROW_LAYOUT_PROPERTY_H +#include +#include #include "base/geometry/dimension.h" #include "base/i18n/localization.h" #include "base/json/json_util.h" @@ -146,6 +148,10 @@ public: DisappearTextStyle, TextColor, DisappearColor, Color, PROPERTY_UPDATE_MEASURE_SELF); ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( DisappearTextStyle, FontWeight, DisappearWeight, FontWeight, PROPERTY_UPDATE_MEASURE); + ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( + DisappearTextStyle, FontFamily, DisappearFontFamily, std::vector, PROPERTY_UPDATE_MEASURE); + ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( + DisappearTextStyle, ItalicFontStyle, DisappearFontStyle, Ace::FontStyle, PROPERTY_UPDATE_MEASURE); ACE_DEFINE_PROPERTY_GROUP(TextStyle, FontStyle); ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( @@ -154,6 +160,10 @@ public: TextStyle, TextColor, Color, Color, PROPERTY_UPDATE_MEASURE_SELF); ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( TextStyle, FontWeight, Weight, FontWeight, PROPERTY_UPDATE_MEASURE); + ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( + TextStyle, FontFamily, FontFamily, std::vector, PROPERTY_UPDATE_MEASURE); + ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( + TextStyle, ItalicFontStyle, FontStyle, Ace::FontStyle, PROPERTY_UPDATE_MEASURE); ACE_DEFINE_PROPERTY_GROUP(SelectedTextStyle, FontStyle); ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( @@ -162,6 +172,10 @@ public: SelectedTextStyle, TextColor, SelectedColor, Color, PROPERTY_UPDATE_MEASURE_SELF); ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( SelectedTextStyle, FontWeight, SelectedWeight, FontWeight, PROPERTY_UPDATE_MEASURE); + ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( + SelectedTextStyle, FontFamily, SelectedFontFamily, std::vector, PROPERTY_UPDATE_MEASURE); + ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( + SelectedTextStyle, ItalicFontStyle, SelectedFontStyle, Ace::FontStyle, PROPERTY_UPDATE_MEASURE); private: ACE_DISALLOW_COPY_AND_MOVE(DataPickerRowLayoutProperty); }; diff --git a/frameworks/core/components_ng/pattern/picker/picker_model.h b/frameworks/core/components_ng/pattern/picker/picker_model.h index 478a1315442..d29ee01bb0e 100644 --- a/frameworks/core/components_ng/pattern/picker/picker_model.h +++ b/frameworks/core/components_ng/pattern/picker/picker_model.h @@ -48,6 +48,7 @@ public: virtual void SetSelectedDate(const PickerDate& value) = 0; virtual void SetShowLunar(bool lunar) = 0; virtual void SetOnChange(DateChangeEvent&& onChange) = 0; + virtual void SetOnDateChange(DateChangeEvent&& onChange) = 0; virtual void SetSelectedTime(const PickerTime& selectedTime) = 0; virtual void SetHour24(bool value) = 0; virtual void SetDisappearTextStyle(const RefPtr& theme, const NG::PickerTextStyle& value) = 0; @@ -68,7 +69,8 @@ public: virtual void SetDatePickerDialogShow(PickerDialogInfo& pickerDialog, NG::DatePickerSettingData& settingData, std::function&& onCancel, std::function&& onAccept, - std::function&& onChange, DatePickerType pickerType) = 0; + std::function&& onChange, std::function&& onDateAccept, + std::function&& onDateChange, DatePickerType pickerType) = 0; private: static std::unique_ptr datePickerDialogInstance_; diff --git a/frameworks/core/components_ng/pattern/picker/picker_type_define.h b/frameworks/core/components_ng/pattern/picker/picker_type_define.h index b1c919ca1e9..0e48b464e11 100644 --- a/frameworks/core/components_ng/pattern/picker/picker_type_define.h +++ b/frameworks/core/components_ng/pattern/picker/picker_type_define.h @@ -18,6 +18,7 @@ #include +#include "core/components/common/properties/text_style.h" #include "core/components/picker/picker_data.h" namespace OHOS::Ace::NG { @@ -35,6 +36,8 @@ struct PickerTextStyle { std::optional textColor; std::optional fontSize; std::optional fontWeight; + std::optional> fontFamily; + std::optional fontStyle; }; struct PickerTextProperties { PickerTextStyle disappearTextStyle_; diff --git a/frameworks/core/components_ng/pattern/refresh/refresh_model_ng.cpp b/frameworks/core/components_ng/pattern/refresh/refresh_model_ng.cpp index f681d510b03..f890dc32e8e 100644 --- a/frameworks/core/components_ng/pattern/refresh/refresh_model_ng.cpp +++ b/frameworks/core/components_ng/pattern/refresh/refresh_model_ng.cpp @@ -21,6 +21,7 @@ #include "frameworks/base/geometry/ng/offset_t.h" #include "frameworks/base/i18n/localization.h" #include "frameworks/base/utils/time_util.h" +#include "frameworks/core/components/refresh/refresh_theme.h" #include "frameworks/core/components_ng/base/frame_node.h" #include "frameworks/core/components_ng/base/view_stack_processor.h" #include "frameworks/core/components_ng/pattern/loading_progress/loading_progress_pattern.h" @@ -36,7 +37,7 @@ constexpr int32_t CHILD_COUNT = 2; constexpr double DEFAULT_INDICATOR_OFFSET = 16.0; constexpr int32_t DEFAULT_FRICTION_RATIO = 42; constexpr char REFRESH_LAST_UPDATED[] = "refresh.last_updated"; // I18n for last updated - +constexpr Dimension LOADING_PROGRESS_SIZE = 32.0_vp; } // namespace void RefreshModelNG::Create() @@ -101,9 +102,22 @@ void RefreshModelNG::Pop() auto loadingProgressChild = FrameNode::CreateFrameNode(V2::LOADING_PROGRESS_ETS_TAG, ElementRegister::GetInstance()->MakeUniqueId(), AceType::MakeRefPtr()); CHECK_NULL_VOID(loadingProgressChild); - refreshNode->AddChild(loadingProgressChild); auto progressLayoutProperty = loadingProgressChild->GetLayoutProperty(); - CHECK_NULL_VOID(progressLayoutProperty); + progressLayoutProperty->UpdateUserDefinedIdealSize( + CalcSize(CalcLength(LOADING_PROGRESS_SIZE.ConvertToPx()), CalcLength(LOADING_PROGRESS_SIZE.ConvertToPx()))); + auto pipeline = PipelineContext::GetCurrentContext(); + CHECK_NULL_VOID(pipeline); + auto themeManager = pipeline->GetThemeManager(); + CHECK_NULL_VOID(themeManager); + auto theme = themeManager->GetTheme(); + CHECK_NULL_VOID(theme); + auto paintProperty = loadingProgressChild->GetPaintProperty(); + CHECK_NULL_VOID(paintProperty); + paintProperty->UpdateColor(theme->GetProgressColor()); + auto progressContext = loadingProgressChild->GetRenderContext(); + CHECK_NULL_VOID_NOLOG(progressContext); + progressContext->UpdateOpacity(0.0); + refreshNode->AddChild(loadingProgressChild); } NG::ViewStackProcessor::GetInstance()->PopContainer(); } diff --git a/frameworks/core/components_ng/pattern/refresh/refresh_pattern.cpp b/frameworks/core/components_ng/pattern/refresh/refresh_pattern.cpp index 4936c07e221..cdf78e2755c 100644 --- a/frameworks/core/components_ng/pattern/refresh/refresh_pattern.cpp +++ b/frameworks/core/components_ng/pattern/refresh/refresh_pattern.cpp @@ -82,7 +82,6 @@ void RefreshPattern::OnModifyDone() CustomBuilderReset(); } else if (!progressChild_) { progressChild_ = AceType::DynamicCast(host->GetChildAtIndex(host->TotalChildCount() - 1)); - LoadingProgressReset(); } if (layoutProperty->GetIsCustomBuilderExistValue() || isRefreshing_ != refreshingProp) { if (refreshingProp) { @@ -240,8 +239,8 @@ void RefreshPattern::ReplaceLoadingProgressNode() CHECK_NULL_VOID(loadingProgressChild); host->AddChild(loadingProgressChild); progressChild_ = loadingProgressChild; - host->RebuildRenderContextTree(); LoadingProgressReset(); + host->RebuildRenderContextTree(); } void RefreshPattern::LoadingProgressReset() @@ -573,15 +572,25 @@ void RefreshPattern::FireChangeEvent(const std::string& value) float RefreshPattern::GetScrollOffset(float delta) { - auto layoutProperty = GetLayoutProperty(); - CHECK_NULL_RETURN(layoutProperty, 0.0f); - auto frictionRatio = static_cast(layoutProperty->GetFriction().value_or(DEFAULT_FRICTION)) * PERCENT; - auto scrollY = delta * frictionRatio; + auto scrollY = delta * GetFrictionRatio(); auto scrollOffset = std::clamp(scrollOffset_.GetY() + scrollY, static_cast(0.0f), static_cast(MAX_SCROLL_DISTANCE.ConvertToPx())); return scrollOffset; } +float RefreshPattern::GetFrictionRatio() +{ + auto layoutProperty = GetLayoutProperty(); + CHECK_NULL_RETURN(layoutProperty, 0.0f); + auto frictionRatio = static_cast(layoutProperty->GetFriction().value_or(DEFAULT_FRICTION)) * PERCENT; + auto percentage = std::abs(scrollOffset_.GetY() / static_cast(MAX_SCROLL_DISTANCE.ConvertToPx())); + if (NearEqual(percentage, 1.0)) { + return 0.0; + } else { + return frictionRatio * std::pow(1.0 - percentage, SQUARE); + } +} + void RefreshPattern::ResetLoadingProgressColor() { auto pipeline = PipelineContext::GetCurrentContext(); @@ -594,7 +603,6 @@ void RefreshPattern::ResetLoadingProgressColor() auto paintProperty = progressChild_->GetPaintProperty(); CHECK_NULL_VOID(paintProperty); paintProperty->UpdateColor(theme->GetProgressColor()); - progressChild_->MarkDirtyNode(PROPERTY_UPDATE_RENDER); } void RefreshPattern::AddCustomBuilderNode(const RefPtr& builder) const diff --git a/frameworks/core/components_ng/pattern/refresh/refresh_pattern.h b/frameworks/core/components_ng/pattern/refresh/refresh_pattern.h index 7f088f2adb7..f4c402e1861 100644 --- a/frameworks/core/components_ng/pattern/refresh/refresh_pattern.h +++ b/frameworks/core/components_ng/pattern/refresh/refresh_pattern.h @@ -119,6 +119,7 @@ private: float GetFadeAwayRatio(); float GetCustomBuilderOpacityRatio(); float GetScrollOffset(float delta); + float GetFrictionRatio(); bool ScrollComponentReactInMove(); void CustomBuilderAppear(); void CustomBuilderExit(); diff --git a/frameworks/core/components_ng/pattern/scroll/inner/scroll_bar.cpp b/frameworks/core/components_ng/pattern/scroll/inner/scroll_bar.cpp index 644247bf31c..ae929350e96 100644 --- a/frameworks/core/components_ng/pattern/scroll/inner/scroll_bar.cpp +++ b/frameworks/core/components_ng/pattern/scroll/inner/scroll_bar.cpp @@ -496,7 +496,7 @@ void ScrollBar::PlayBarEndAnimation() return; } - scrollEndAnimator_ = CREATE_ANIMATOR(PipelineContext::GetCurrentContext()); + scrollEndAnimator_ = CREATE_ANIMATOR(PipelineContext::GetCurrentContext(), "ScrollBarEndAnimator"); scrollEndAnimator_->PreventFrameJank(); auto animation = AceType::MakeRefPtr>(UINT8_MAX, 0, Curves::SHARP); animation->AddListener([weakBar = AceType::WeakClaim(this)](int32_t value) { diff --git a/frameworks/core/components_ng/pattern/scrollable/scrollable_pattern.cpp b/frameworks/core/components_ng/pattern/scrollable/scrollable_pattern.cpp index f96c06e2169..25ed5ab01db 100644 --- a/frameworks/core/components_ng/pattern/scrollable/scrollable_pattern.cpp +++ b/frameworks/core/components_ng/pattern/scrollable/scrollable_pattern.cpp @@ -256,22 +256,27 @@ void ScrollablePattern::SetEdgeEffect(EdgeEffect edgeEffect) bool ScrollablePattern::HandleEdgeEffect(float offset, int32_t source, const SizeF& size) { + bool isAtTop = IsAtTop(); + bool isAtBottom = IsAtBottom(); // check edgeEffect is not springEffect if (scrollEffect_ && scrollEffect_->IsFadeEffect() && (source == SCROLL_FROM_UPDATE || source == SCROLL_FROM_ANIMATION)) { // handle edge effect - if ((IsAtTop() && Positive(offset)) || (IsAtBottom() && Negative(offset))) { + if ((isAtTop && Positive(offset)) || (isAtBottom && Negative(offset))) { scrollEffect_->HandleOverScroll(GetAxis(), -offset, size); } } if (!(scrollEffect_ && scrollEffect_->IsSpringEffect() && (source == SCROLL_FROM_UPDATE || source == SCROLL_FROM_ANIMATION || source == SCROLL_FROM_ANIMATION_SPRING))) { - if (IsAtTop() && Positive(offset)) { + if (isAtTop && Positive(offset)) { + animateOverScroll_ = false; return false; } - if (IsAtBottom() && Negative(offset)) { + if (isAtBottom && Negative(offset)) { + animateOverScroll_ = false; return false; } } + animateOverScroll_ = (source == SCROLL_FROM_ANIMATION_CONTROLLER) && (isAtTop || isAtBottom); return true; } @@ -306,7 +311,20 @@ void ScrollablePattern::RegisterScrollBarEventTask() gestureHub->AddTouchEvent(scrollBar_->GetTouchEvent()); inputHub->AddOnMouseEvent(scrollBar_->GetMouseEvent()); CHECK_NULL_VOID(scrollableEvent_); - scrollableEvent_->SetScrollBar(scrollBar_); + scrollableEvent_->SetInBarRegionCallback( + [weak = AceType::WeakClaim(AceType::RawPtr(scrollBar_))](const PointF& point) { + auto scrollBar = weak.Upgrade(); + CHECK_NULL_RETURN_NOLOG(scrollBar, false); + return scrollBar->InBarTouchRegion(Point(point.GetX(), point.GetY())); + } + ); + scrollableEvent_->SetBarCollectTouchTargetCallback([weak = AceType::WeakClaim(AceType::RawPtr(scrollBar_))] + (const OffsetF& coordinateOffset, const GetEventTargetImpl& getEventTargetImpl, TouchTestResult& result) { + auto scrollBar = weak.Upgrade(); + CHECK_NULL_VOID_NOLOG(scrollBar); + scrollBar->OnCollectTouchTarget(coordinateOffset, getEventTargetImpl, result); + } + ); } void ScrollablePattern::SetScrollBar(DisplayMode displayMode) @@ -617,6 +635,7 @@ void ScrollablePattern::HandleMouseEventWithoutKeyboard(const MouseInfo& info) mouseStartOffset_ = OffsetF(mouseOffsetX, mouseOffsetY); mouseEndOffset_ = OffsetF(mouseOffsetX, mouseOffsetY); mousePressOffset_ = OffsetF(mouseOffsetX, mouseOffsetY); + totalOffsetOfMousePressed_ = mousePressOffset_.GetMainOffset(axis_) + GetTotalOffset(); mousePressed_ = true; // do not select when click } else if (info.GetAction() == MouseAction::MOVE) { @@ -748,6 +767,22 @@ bool ScrollablePattern::ShouldSelectScrollBeStopped() if (NearZero(offset)) { return true; } + + // avoid start position move when offset is bigger then item height + auto currentMainStartOffset = mouseStartOffset_.GetMainOffset(axis_); + if (Positive(offset)) { + if (LessNotEqual(totalOffsetOfMousePressed_, currentMainStartOffset + offset)) { + offset = totalOffsetOfMousePressed_ - currentMainStartOffset; + } + } else { + auto hostSize = GetHostFrameSize(); + CHECK_NULL_RETURN_NOLOG(hostSize.has_value(), true); + auto minStartOffset = -(GetTotalHeight() - totalOffsetOfMousePressed_ - hostSize->MainSize(axis_)); + if (GreatNotEqual(minStartOffset, currentMainStartOffset + offset)) { + offset = minStartOffset - currentMainStartOffset; + } + } + if (axis_ == Axis::VERTICAL) { mouseStartOffset_.AddY(offset); } else { diff --git a/frameworks/core/components_ng/pattern/scrollable/scrollable_pattern.h b/frameworks/core/components_ng/pattern/scrollable/scrollable_pattern.h index ed597c6a3f1..5b1109cb105 100644 --- a/frameworks/core/components_ng/pattern/scrollable/scrollable_pattern.h +++ b/frameworks/core/components_ng/pattern/scrollable/scrollable_pattern.h @@ -234,13 +234,18 @@ public: { return 0.0f; } + // main size of all children + virtual float GetTotalHeight() const + { + return 0.0f; + } virtual void OnAnimateStop() {} virtual void ScrollTo(float position); virtual void AnimateTo(float position, float duration, const RefPtr& curve, bool smooth); bool CanOverScroll(int32_t source) { return (IsScrollableSpringEffect() && source != SCROLL_FROM_AXIS && source != SCROLL_FROM_BAR && - IsScrollable() && (!ScrollableIdle() || AnimateRunning())); + IsScrollable() && (!ScrollableIdle() || animateOverScroll_)); } void MarkSelectedItems(); bool ShouldSelectScrollBeStopped(); @@ -317,6 +322,7 @@ private: RefPtr animator_; RefPtr springMotion_; bool scrollAbort_ = false; + bool animateOverScroll_ = false; NestedScrollOptions nestedScroll_; @@ -325,6 +331,7 @@ private: OffsetF mouseStartOffset_; OffsetF mouseEndOffset_; OffsetF mousePressOffset_; + float totalOffsetOfMousePressed_ = 0.0f; MouseInfo lastMouseMove_; RefPtr selectMotion_; RefPtr mouseEvent_; diff --git a/frameworks/core/components_ng/pattern/security_component/BUILD.gn b/frameworks/core/components_ng/pattern/security_component/BUILD.gn index ac0ac4787af..ed02ffa399a 100644 --- a/frameworks/core/components_ng/pattern/security_component/BUILD.gn +++ b/frameworks/core/components_ng/pattern/security_component/BUILD.gn @@ -37,7 +37,9 @@ build_component_ng("security_component_pattern_ng") { if (security_component_enable) { sources += [ "security_component_probe.cpp" ] external_deps += [ + "ability_runtime:abilitykit_native", "access_token:libaccesstoken_sdk", + "napi:ace_napi", "security_component:libsecurity_component_framework", "security_component:libsecurity_component_sdk", ] diff --git a/frameworks/core/components_ng/pattern/security_component/location_button/location_button_model_ng.cpp b/frameworks/core/components_ng/pattern/security_component/location_button/location_button_model_ng.cpp index 4280a3a04d7..fff140814bc 100644 --- a/frameworks/core/components_ng/pattern/security_component/location_button/location_button_model_ng.cpp +++ b/frameworks/core/components_ng/pattern/security_component/location_button/location_button_model_ng.cpp @@ -44,7 +44,7 @@ LocationButtonModelNG* LocationButtonModelNG::GetInstance() void LocationButtonModelNG::Create(int32_t text, int32_t icon, int32_t backgroundType) { - SecurityComponentModelNG::CreateCommon(V2::SEC_LOCATION_BUTTON_ETS_TAG, + SecurityComponentModelNG::CreateCommon(V2::LOCATION_BUTTON_ETS_TAG, text, icon, backgroundType, []() { return AceType::MakeRefPtr(); }); } diff --git a/frameworks/core/components_ng/pattern/security_component/paste_button/paste_button_model_ng.cpp b/frameworks/core/components_ng/pattern/security_component/paste_button/paste_button_model_ng.cpp index e0bf70e953a..b6d03cb3320 100644 --- a/frameworks/core/components_ng/pattern/security_component/paste_button/paste_button_model_ng.cpp +++ b/frameworks/core/components_ng/pattern/security_component/paste_button/paste_button_model_ng.cpp @@ -43,7 +43,7 @@ PasteButtonModelNG* PasteButtonModelNG::GetInstance() void PasteButtonModelNG::Create(int32_t text, int32_t icon, int32_t backgroundType) { - SecurityComponentModelNG::CreateCommon(V2::SEC_PASTE_BUTTON_ETS_TAG, + SecurityComponentModelNG::CreateCommon(V2::PASTE_BUTTON_ETS_TAG, text, icon, backgroundType, []() { return AceType::MakeRefPtr(); }); } diff --git a/frameworks/core/components_ng/pattern/security_component/save_button/save_button_common.h b/frameworks/core/components_ng/pattern/security_component/save_button/save_button_common.h index 2c578fd91c1..3642dde1beb 100644 --- a/frameworks/core/components_ng/pattern/security_component/save_button/save_button_common.h +++ b/frameworks/core/components_ng/pattern/security_component/save_button/save_button_common.h @@ -30,10 +30,10 @@ enum class SaveButtonIconStyle : int32_t { enum class SaveButtonSaveDescription : int32_t { TEXT_NULL = -1, DOWNLOAD = 0, - DOWNLOAD_FILES, + DOWNLOAD_FILE, SAVE, - SAVE_IMAGES, - SAVE_FILES, + SAVE_IMAGE, + SAVE_FILE, DOWNLOAD_AND_SHARE, RECEIVE, CONTINUE_TO_RECEIVE, diff --git a/frameworks/core/components_ng/pattern/security_component/save_button/save_button_model_ng.cpp b/frameworks/core/components_ng/pattern/security_component/save_button/save_button_model_ng.cpp index 6762af2762e..803e2f8f214 100644 --- a/frameworks/core/components_ng/pattern/security_component/save_button/save_button_model_ng.cpp +++ b/frameworks/core/components_ng/pattern/security_component/save_button/save_button_model_ng.cpp @@ -44,7 +44,7 @@ SaveButtonModelNG* SaveButtonModelNG::GetInstance() void SaveButtonModelNG::Create(int32_t text, int32_t icon, int32_t backgroundType) { - SecurityComponentModelNG::CreateCommon(V2::SEC_SAVE_BUTTON_ETS_TAG, + SecurityComponentModelNG::CreateCommon(V2::SAVE_BUTTON_ETS_TAG, text, icon, backgroundType, []() { return AceType::MakeRefPtr(); }); } diff --git a/frameworks/core/components_ng/pattern/security_component/security_component_common.h b/frameworks/core/components_ng/pattern/security_component/security_component_common.h index 80eb6669a29..8ebc296d970 100644 --- a/frameworks/core/components_ng/pattern/security_component/security_component_common.h +++ b/frameworks/core/components_ng/pattern/security_component/security_component_common.h @@ -34,23 +34,11 @@ enum class SecurityComponentDescription : int32_t { TEXT_NULL = -1, }; -enum class SecurityComponentBackgroundType : int32_t { - BACKGROUND_NULL = -1, - CAPSULE = 0, - CIRCLE = 1, - NORMAL = 2 -}; - enum class SecurityComponentLayoutDirection : int32_t { HORIZONTAL = 0, VERTICAL = 1, }; -enum class SecSecurityComponentLayoutOrder : int32_t { - ICON_FIRST = 0, - TEXT_FIRST = 1, -}; - static int32_t BUTTON_TYPE_NULL = -1; } // namespace OHOS::Ace diff --git a/frameworks/core/components_ng/pattern/security_component/security_component_handler.cpp b/frameworks/core/components_ng/pattern/security_component/security_component_handler.cpp index 77e982b6451..1609e2460fc 100644 --- a/frameworks/core/components_ng/pattern/security_component/security_component_handler.cpp +++ b/frameworks/core/components_ng/pattern/security_component/security_component_handler.cpp @@ -17,6 +17,9 @@ #include +#ifdef SECURITY_COMPONENT_ENABLE +#include "adapter/ohos/entrance/ace_container.h" +#endif #include "base/log/ace_scoring_log.h" #include "base/utils/system_properties.h" #include "core/common/container.h" @@ -269,6 +272,11 @@ bool SecurityComponentHandler::CheckParentNodesEffect(RefPtr& node) if (CheckRenderEffect(parentNode)) { return true; } + RefPtr parentRenderContext = parentNode->GetRenderContext(); + if (!parentRenderContext->GetClipEdge().value_or(false)) { + parent = parent->GetParent(); + continue; + } GetVisibleRect(parentNode, visibleRect); double currentVisibleRatio = CalculateCurrentVisibleRatio(visibleRect, frameRect); if (!NearEqual(currentVisibleRatio, 1)) { @@ -379,7 +387,7 @@ bool SecurityComponentHandler::InitButtonInfo(std::string& componentInfo, RefPtr auto layoutProperty = AceType::DynamicCast(node->GetLayoutProperty()); CHECK_NULL_RETURN(layoutProperty, false); std::string type = node->GetTag(); - if (type == V2::SEC_LOCATION_BUTTON_ETS_TAG) { + if (type == V2::LOCATION_BUTTON_ETS_TAG) { LocationButton buttonInfo; buttonInfo.parentEffect_ = CheckParentNodesEffect(node); buttonInfo.text_ = layoutProperty->GetSecurityComponentDescription().value(); @@ -391,7 +399,7 @@ bool SecurityComponentHandler::InitButtonInfo(std::string& componentInfo, RefPtr return false; } componentInfo = buttonInfo.ToJsonStr(); - } else if (type == V2::SEC_PASTE_BUTTON_ETS_TAG) { + } else if (type == V2::PASTE_BUTTON_ETS_TAG) { PasteButton buttonInfo; buttonInfo.parentEffect_ = CheckParentNodesEffect(node); buttonInfo.text_ = layoutProperty->GetSecurityComponentDescription().value(); @@ -403,7 +411,7 @@ bool SecurityComponentHandler::InitButtonInfo(std::string& componentInfo, RefPtr return false; } componentInfo = buttonInfo.ToJsonStr(); - } else if (type == V2::SEC_SAVE_BUTTON_ETS_TAG) { + } else if (type == V2::SAVE_BUTTON_ETS_TAG) { SaveButton buttonInfo; buttonInfo.parentEffect_ = CheckParentNodesEffect(node); buttonInfo.text_ = layoutProperty->GetSecurityComponentDescription().value(); @@ -471,7 +479,9 @@ int32_t SecurityComponentHandler::ReportSecurityComponentClickEvent(int32_t scId secEvent.extraInfo.data = data.data(); secEvent.extraInfo.dataSize = data.size(); } - return SecCompKit::ReportSecurityComponentClickEvent(scId, componentInfo, secEvent); + auto container = AceType::DynamicCast(Container::Current()); + CHECK_NULL_RETURN(container, -1); + return SecCompKit::ReportSecurityComponentClickEvent(scId, componentInfo, secEvent, container->GetToken()); } #else int32_t SecurityComponentHandler::RegisterSecurityComponent(RefPtr& node, int32_t& scId) diff --git a/frameworks/core/components_ng/pattern/security_component/security_component_layout_algorithm.cpp b/frameworks/core/components_ng/pattern/security_component/security_component_layout_algorithm.cpp index f0659ded7d8..18c86f32ef4 100644 --- a/frameworks/core/components_ng/pattern/security_component/security_component_layout_algorithm.cpp +++ b/frameworks/core/components_ng/pattern/security_component/security_component_layout_algorithm.cpp @@ -111,8 +111,6 @@ void SecurityComponentLayoutAlgorithm::FillPaddingParams( res.bottom = securityComponentProperty->GetBackgroundBottomPadding().value().ConvertToPx(); res.left = securityComponentProperty->GetBackgroundLeftPadding().value().ConvertToPx(); res.textIconSpace = securityComponentProperty->GetTextIconSpace().value().ConvertToPx(); - res.iconStart = - (securityComponentProperty->GetLayoutOrder().value() == SecSecurityComponentLayoutOrder::ICON_FIRST); } void SecurityComponentLayoutAlgorithm::UpdateVertical(OffsetT& offsetIcon, @@ -122,13 +120,8 @@ void SecurityComponentLayoutAlgorithm::UpdateVertical(OffsetT& offset textSizeF_.Height() + params.bottom; componentWidth_ = params.left + ((iconSizeF_.Width() > textSizeF_.Width()) ? iconSizeF_.Width() : textSizeF_.Width()) + params.right; - if (params.iconStart) { - offsetText = offsetIcon + OffsetT(Dimension(0.0F), - Dimension(iconSizeF_.Height() + params.textIconSpace)); - } else { - offsetIcon = offsetText + OffsetT(Dimension(0.0F), - Dimension(textSizeF_.Height() + params.textIconSpace)); - } + offsetText = offsetIcon + OffsetT(Dimension(0.0F), + Dimension(iconSizeF_.Height() + params.textIconSpace)); if (iconSizeF_.Width() > textSizeF_.Width()) { offsetText += OffsetT(Dimension((iconSizeF_.Width() - textSizeF_.Width()) / HALF), Dimension(0.0F)); } else { @@ -143,13 +136,8 @@ void SecurityComponentLayoutAlgorithm::UpdateHorizontal(OffsetT& offs params.top + ((iconSizeF_.Height() > textSizeF_.Height()) ? iconSizeF_.Height() : textSizeF_.Height()) + params.bottom; componentWidth_ = params.left + iconSizeF_.Width() + params.textIconSpace + textSizeF_.Width() + params.right; - if (params.iconStart) { - offsetText = offsetIcon + - OffsetT(Dimension(iconSizeF_.Width() + params.textIconSpace), Dimension(0.0F)); - } else { - offsetIcon = offsetText + - OffsetT(Dimension(textSizeF_.Width() + params.textIconSpace), Dimension(0.0F)); - } + offsetText = offsetIcon + + OffsetT(Dimension(iconSizeF_.Width() + params.textIconSpace), Dimension(0.0F)); if (iconSizeF_.Height() > textSizeF_.Height()) { offsetText += OffsetT(Dimension(0.0F), Dimension((iconSizeF_.Height() - textSizeF_.Height()) / HALF)); diff --git a/frameworks/core/components_ng/pattern/security_component/security_component_layout_algorithm.h b/frameworks/core/components_ng/pattern/security_component/security_component_layout_algorithm.h index 2e9aad023df..f5ecb3ed32d 100644 --- a/frameworks/core/components_ng/pattern/security_component/security_component_layout_algorithm.h +++ b/frameworks/core/components_ng/pattern/security_component/security_component_layout_algorithm.h @@ -28,7 +28,6 @@ struct SecurityComponentLayoutPaddingParams { double bottom = 0.0; double left = 0.0; double textIconSpace = 0.0; - bool iconStart = false; }; class ACE_EXPORT SecurityComponentLayoutAlgorithm : public BoxLayoutAlgorithm { diff --git a/frameworks/core/components_ng/pattern/security_component/security_component_layout_property.h b/frameworks/core/components_ng/pattern/security_component/security_component_layout_property.h index 9d4e6b2393c..246be4014ec 100644 --- a/frameworks/core/components_ng/pattern/security_component/security_component_layout_property.h +++ b/frameworks/core/components_ng/pattern/security_component/security_component_layout_property.h @@ -44,7 +44,6 @@ public: value->propIconStyle_ = CloneIconStyle(); value->propBackgroundType_ = CloneBackgroundType(); value->propTextIconLayoutDirection_ = CloneTextIconLayoutDirection(); - value->propLayoutOrder_ = CloneLayoutOrder(); return value; } @@ -60,7 +59,6 @@ public: ResetIconStyle(); ResetBackgroundType(); ResetTextIconLayoutDirection(); - ResetLayoutOrder(); } ACE_DEFINE_PROPERTY_ITEM_WITHOUT_GROUP(BackgroundLeftPadding, Dimension, PROPERTY_UPDATE_MEASURE); @@ -73,7 +71,6 @@ public: ACE_DEFINE_PROPERTY_ITEM_WITHOUT_GROUP(BackgroundType, int32_t, PROPERTY_UPDATE_NORMAL); ACE_DEFINE_PROPERTY_ITEM_WITHOUT_GROUP(TextIconLayoutDirection, SecurityComponentLayoutDirection, PROPERTY_UPDATE_MEASURE); - ACE_DEFINE_PROPERTY_ITEM_WITHOUT_GROUP(LayoutOrder, SecSecurityComponentLayoutOrder, PROPERTY_UPDATE_MEASURE); ACE_DISALLOW_COPY_AND_MOVE(SecurityComponentLayoutProperty); }; } // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/pattern/security_component/security_component_model_ng.cpp b/frameworks/core/components_ng/pattern/security_component/security_component_model_ng.cpp index 51f8646b179..5960adbb614 100644 --- a/frameworks/core/components_ng/pattern/security_component/security_component_model_ng.cpp +++ b/frameworks/core/components_ng/pattern/security_component/security_component_model_ng.cpp @@ -69,7 +69,6 @@ void SecurityComponentModelNG::InitLayoutProperty(RefPtr& node, int32 } property->UpdateTextIconLayoutDirection(SecurityComponentLayoutDirection::HORIZONTAL); - property->UpdateLayoutOrder(SecSecurityComponentLayoutOrder::ICON_FIRST); } void SecurityComponentModelNG::CreateCommon(const std::string& tag, int32_t text, int32_t icon, @@ -377,9 +376,4 @@ void SecurityComponentModelNG::SetTextIconLayoutDirection(const SecurityComponen { ACE_UPDATE_LAYOUT_PROPERTY(SecurityComponentLayoutProperty, TextIconLayoutDirection, value); } - -void SecurityComponentModelNG::SetlayoutOrder(const SecSecurityComponentLayoutOrder& value) -{ - ACE_UPDATE_LAYOUT_PROPERTY(SecurityComponentLayoutProperty, LayoutOrder, value); -} } // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/pattern/security_component/security_component_model_ng.h b/frameworks/core/components_ng/pattern/security_component/security_component_model_ng.h index cf6b40dfb2e..43f51b7f8db 100644 --- a/frameworks/core/components_ng/pattern/security_component/security_component_model_ng.h +++ b/frameworks/core/components_ng/pattern/security_component/security_component_model_ng.h @@ -50,7 +50,6 @@ public: static void SetBackgroundPadding(const std::optional& padding); static void SetTextIconSpace(const Dimension& value); static void SetTextIconLayoutDirection(const SecurityComponentLayoutDirection& value); - static void SetlayoutOrder(const SecSecurityComponentLayoutOrder& value); virtual bool GetIconResource(int32_t iconStyle, InternalResource::ResourceId& id) { diff --git a/frameworks/core/components_ng/pattern/security_component/security_component_probe.cpp b/frameworks/core/components_ng/pattern/security_component/security_component_probe.cpp index 65e5637ddad..79e5f8973b2 100644 --- a/frameworks/core/components_ng/pattern/security_component/security_component_probe.cpp +++ b/frameworks/core/components_ng/pattern/security_component/security_component_probe.cpp @@ -63,8 +63,8 @@ int32_t SecurityComponentProbe::GetComponentInfo(int32_t nodeId, std::string& co return; } - if ((node->GetTag() != V2::SEC_LOCATION_BUTTON_ETS_TAG) && (node->GetTag() != V2::SEC_PASTE_BUTTON_ETS_TAG) && - (node->GetTag() != V2::SEC_SAVE_BUTTON_ETS_TAG)) { + if ((node->GetTag() != V2::LOCATION_BUTTON_ETS_TAG) && (node->GetTag() != V2::PASTE_BUTTON_ETS_TAG) && + (node->GetTag() != V2::SAVE_BUTTON_ETS_TAG)) { LOGW("node is not security component."); taskRes = -1; return; diff --git a/frameworks/core/components_ng/pattern/security_component/security_component_theme.h b/frameworks/core/components_ng/pattern/security_component/security_component_theme.h index bd57e71eb55..a48ccf56033 100644 --- a/frameworks/core/components_ng/pattern/security_component/security_component_theme.h +++ b/frameworks/core/components_ng/pattern/security_component/security_component_theme.h @@ -205,13 +205,13 @@ private: theme->saveDescriptions_.emplace_back( securityComponentPattern->GetAttr("description_download", "")); theme->saveDescriptions_.emplace_back( - securityComponentPattern->GetAttr("description_download_files", "")); + securityComponentPattern->GetAttr("description_download_file", "")); theme->saveDescriptions_.emplace_back( securityComponentPattern->GetAttr("description_save", "")); theme->saveDescriptions_.emplace_back( - securityComponentPattern->GetAttr("description_save_images", "")); + securityComponentPattern->GetAttr("description_save_image", "")); theme->saveDescriptions_.emplace_back( - securityComponentPattern->GetAttr("description_save_files", "")); + securityComponentPattern->GetAttr("description_save_file", "")); theme->saveDescriptions_.emplace_back( securityComponentPattern->GetAttr("description_download_and_share", "")); theme->saveDescriptions_.emplace_back( diff --git a/frameworks/core/components_ng/pattern/select_overlay/select_overlay_layout_algorithm.cpp b/frameworks/core/components_ng/pattern/select_overlay/select_overlay_layout_algorithm.cpp index 3e39f4f7cd7..0699870233f 100644 --- a/frameworks/core/components_ng/pattern/select_overlay/select_overlay_layout_algorithm.cpp +++ b/frameworks/core/components_ng/pattern/select_overlay/select_overlay_layout_algorithm.cpp @@ -33,9 +33,11 @@ void SelectOverlayLayoutAlgorithm::Layout(LayoutWrapper* layoutWrapper) { auto menu = layoutWrapper->GetOrCreateChildByIndex(0); CHECK_NULL_VOID(menu); - if (!CheckInShowArea(*info_)) { + if (!CheckInShowArea(*info_) || (!info_->firstHandle.isShow && !info_->secondHandle.isShow)) { menu->SetActive(false); return; + } else { + menu->SetActive(true); } auto menuOffset = ComputeSelectMenuPosition(layoutWrapper); menu->GetGeometryNode()->SetMarginFrameOffset(menuOffset); diff --git a/frameworks/core/components_ng/pattern/select_overlay/select_overlay_node.cpp b/frameworks/core/components_ng/pattern/select_overlay/select_overlay_node.cpp index 04f9b437785..260f1e33283 100644 --- a/frameworks/core/components_ng/pattern/select_overlay/select_overlay_node.cpp +++ b/frameworks/core/components_ng/pattern/select_overlay/select_overlay_node.cpp @@ -125,14 +125,20 @@ RefPtr BuildButton(const std::string& data, const std::functionGetOrCreateGestureEventHub()->SetUserOnClick( [callback, overlayId, isSelectAll](GestureEvent& /*info*/) { - if (callback) { - callback(); - } - // close text overlay. auto pipeline = PipelineContext::GetCurrentContext(); CHECK_NULL_VOID(pipeline); auto overlayManager = pipeline->GetSelectOverlayManager(); CHECK_NULL_VOID(overlayManager); + auto selectOverlay = overlayManager->GetSelectOverlayNode(overlayId); + CHECK_NULL_VOID(selectOverlay); + auto isDoingAnimation = selectOverlay->GetAnimationStatus(); + CHECK_NULL_VOID(!isDoingAnimation); + auto isExtensionMenu = selectOverlay->GetIsExtensionMenu(); + CHECK_NULL_VOID(!isExtensionMenu); + if (callback) { + callback(); + } + // close text overlay. if (!isSelectAll) { overlayManager->DestroySelectOverlay(overlayId); } diff --git a/frameworks/core/components_ng/pattern/select_overlay/select_overlay_node.h b/frameworks/core/components_ng/pattern/select_overlay/select_overlay_node.h index d7562adc1a4..485f2d520ff 100644 --- a/frameworks/core/components_ng/pattern/select_overlay/select_overlay_node.h +++ b/frameworks/core/components_ng/pattern/select_overlay/select_overlay_node.h @@ -55,6 +55,16 @@ public: void SetClosedByGlobalEvent(bool closedByGlobalEvent); + bool GetAnimationStatus() + { + return isDoingAnimation_; + } + + bool GetIsExtensionMenu() + { + return isExtensionMenu_; + } + private: void CreateToolBar(); bool AddSystemDefaultOptions(float maxWidth, float& allocatedSize); diff --git a/frameworks/core/components_ng/pattern/side_bar/side_bar_container_layout_algorithm.cpp b/frameworks/core/components_ng/pattern/side_bar/side_bar_container_layout_algorithm.cpp index 37ff23c83e7..a69bcd61b48 100644 --- a/frameworks/core/components_ng/pattern/side_bar/side_bar_container_layout_algorithm.cpp +++ b/frameworks/core/components_ng/pattern/side_bar/side_bar_container_layout_algorithm.cpp @@ -42,8 +42,7 @@ constexpr static int32_t PLATFORM_VERSION_TEN = 10; static Dimension DEFAULT_SIDE_BAR_WIDTH = 200.0_vp; static Dimension DEFAULT_MIN_SIDE_BAR_WIDTH = 200.0_vp; static Dimension DEFAULT_MIN_CONTENT_WIDTH = 0.0_vp; -static Dimension DEFAULT_CONTROL_BUTTON_WIDTH = 32.0_vp; -static Dimension DEFAULT_CONTROL_BUTTON_HEIGHT = 32.0_vp; +constexpr Dimension CONTROL_BUTTON_PADDING = 12.0_vp; } // namespace void SideBarContainerLayoutAlgorithm::Measure(LayoutWrapper* layoutWrapper) @@ -57,7 +56,10 @@ void SideBarContainerLayoutAlgorithm::Measure(LayoutWrapper* layoutWrapper) auto layoutProperty = AceType::DynamicCast(layoutWrapper->GetLayoutProperty()); CHECK_NULL_VOID(layoutProperty); const auto& constraint = layoutProperty->GetLayoutConstraint(); - auto idealSize = CreateIdealSize( + auto idealSize = PipelineContext::GetCurrentContext()->GetMinPlatformVersion() >= PLATFORM_VERSION_TEN ? + CreateIdealSizeByPercentRef(constraint.value(), Axis::HORIZONTAL, + layoutProperty->GetMeasureType(MeasureType::MATCH_PARENT)).ConvertToSizeT() : + CreateIdealSize( constraint.value(), Axis::HORIZONTAL, layoutProperty->GetMeasureType(MeasureType::MATCH_PARENT), true); layoutWrapper->GetGeometryNode()->SetFrameSize(idealSize); @@ -133,8 +135,6 @@ void SideBarContainerLayoutAlgorithm::UpdateDefaultValueByVersion() DEFAULT_SIDE_BAR_WIDTH = 240.0_vp; DEFAULT_MIN_SIDE_BAR_WIDTH = 240.0_vp; DEFAULT_MIN_CONTENT_WIDTH = 360.0_vp; - DEFAULT_CONTROL_BUTTON_WIDTH = 24.0_vp; - DEFAULT_CONTROL_BUTTON_HEIGHT = 24.0_vp; } } @@ -428,8 +428,11 @@ void SideBarContainerLayoutAlgorithm::MeasureSideBar( } } - auto sideBarIdealSize = CreateIdealSize( - constraint.value(), Axis::HORIZONTAL, layoutProperty->GetMeasureType(MeasureType::MATCH_PARENT), true); + auto sideBarIdealSize = PipelineContext::GetCurrentContext()->GetMinPlatformVersion() >= PLATFORM_VERSION_TEN ? + CreateIdealSizeByPercentRef(constraint.value(), Axis::HORIZONTAL, + layoutProperty->GetMeasureType(MeasureType::MATCH_PARENT)).ConvertToSizeT(): + CreateIdealSize(constraint.value(), Axis::HORIZONTAL, + layoutProperty->GetMeasureType(MeasureType::MATCH_PARENT), true); sideBarIdealSize.SetWidth(realSideBarWidth_); auto sideBarConstraint = layoutProperty->CreateChildConstraint(); sideBarConstraint.selfIdealSize = OptionalSizeF(sideBarIdealSize); @@ -446,7 +449,10 @@ void SideBarContainerLayoutAlgorithm::MeasureDivider(const RefPtrGetLayoutConstraint(); CHECK_NULL_VOID(constraint); auto scaleProperty = constraint->scaleProperty; - auto dividerIdealSize = CreateIdealSize( + auto dividerIdealSize = PipelineContext::GetCurrentContext()->GetMinPlatformVersion() >= PLATFORM_VERSION_TEN ? + CreateIdealSizeByPercentRef(constraint.value(), Axis::HORIZONTAL, + layoutProperty->GetMeasureType(MeasureType::MATCH_PARENT)).ConvertToSizeT() : + CreateIdealSize( constraint.value(), Axis::HORIZONTAL, layoutProperty->GetMeasureType(MeasureType::MATCH_PARENT), true); auto dividerStrokeWidth = layoutProperty->GetDividerStrokeWidth().value_or(DEFAULT_DIVIDER_STROKE_WIDTH); @@ -484,7 +490,10 @@ void SideBarContainerLayoutAlgorithm::MeasureSideBarContent( } } - auto contentIdealSize = CreateIdealSize( + auto contentIdealSize = PipelineContext::GetCurrentContext()->GetMinPlatformVersion() >= PLATFORM_VERSION_TEN ? + CreateIdealSizeByPercentRef(constraint.value(), Axis::HORIZONTAL, + layoutProperty->GetMeasureType(MeasureType::MATCH_PARENT)).ConvertToSizeT() : + CreateIdealSize( constraint.value(), Axis::HORIZONTAL, layoutProperty->GetMeasureType(MeasureType::MATCH_PARENT), true); contentIdealSize.SetWidth(contentWidth); auto contentConstraint = layoutProperty->CreateChildConstraint(); @@ -498,8 +507,8 @@ void SideBarContainerLayoutAlgorithm::MeasureControlButton(const RefPtrGetLayoutConstraint(); auto scaleProperty = constraint->scaleProperty; - auto controlButtonWidth = layoutProperty->GetControlButtonWidth().value_or(DEFAULT_CONTROL_BUTTON_WIDTH); - auto controlButtonHeight = layoutProperty->GetControlButtonHeight().value_or(DEFAULT_CONTROL_BUTTON_HEIGHT); + auto controlButtonWidth = controlImageWidth_ + CONTROL_BUTTON_PADDING * 2; + auto controlButtonHeight = controlImageHeight_ + CONTROL_BUTTON_PADDING * 2; auto controlButtonWidthPx = ConvertToPx(controlButtonWidth, scaleProperty, parentWidth).value_or(0); auto controlButtonHeightPx = ConvertToPx(controlButtonHeight, scaleProperty, parentWidth).value_or(0); @@ -551,15 +560,18 @@ void SideBarContainerLayoutAlgorithm::LayoutControlButton( auto constraint = layoutProperty->GetLayoutConstraint(); auto scaleProperty = constraint->scaleProperty; - auto controlButtonLeft = layoutProperty->GetControlButtonLeft().value_or(DEFAULT_CONTROL_BUTTON_LEFT); - auto controlButtonTop = layoutProperty->GetControlButtonTop().value_or(DEFAULT_CONTROL_BUTTON_TOP); - if (LessNotEqual(controlButtonLeft.Value(), 0.0)) { - controlButtonLeft = DEFAULT_CONTROL_BUTTON_LEFT; + auto controlImageLeft = layoutProperty->GetControlButtonLeft().value_or(DEFAULT_CONTROL_BUTTON_LEFT); + auto controlImageTop = layoutProperty->GetControlButtonTop().value_or(DEFAULT_CONTROL_BUTTON_TOP); + + if (LessNotEqual(controlImageLeft.Value(), 0.0)) { + controlImageLeft = DEFAULT_CONTROL_BUTTON_LEFT; } - if (LessNotEqual(controlButtonTop.Value(), 0.0)) { - controlButtonTop = DEFAULT_CONTROL_BUTTON_TOP; + if (LessNotEqual(controlImageTop.Value(), 0.0)) { + controlImageTop = DEFAULT_CONTROL_BUTTON_TOP; } + auto controlButtonLeft = controlImageLeft - CONTROL_BUTTON_PADDING; + auto controlButtonTop = controlImageTop - CONTROL_BUTTON_PADDING; auto controlButtonLeftPx = ConvertToPx(controlButtonLeft, scaleProperty, parentWidth).value_or(0); auto controlButtonTopPx = ConvertToPx(controlButtonTop, scaleProperty, parentWidth).value_or(0); @@ -574,12 +586,12 @@ void SideBarContainerLayoutAlgorithm::LayoutControlButton( * control button offset the left, if value invalid set to default 16vp */ auto sideBarPosition = GetSideBarPositionWithRtl(layoutProperty); - auto controlButtonWidth = layoutProperty->GetControlButtonWidth().value_or(DEFAULT_CONTROL_BUTTON_WIDTH); + auto controlButtonWidth = controlImageWidth_ + CONTROL_BUTTON_PADDING * 2; if ((sideBarPosition == SideBarPosition::END) && // sideBarPosition is End, other pass (!layoutProperty->GetControlButtonLeft().has_value())) { // origin value has not set - auto defaultControlButtonLeftPx = - ConvertToPx(DEFAULT_CONTROL_BUTTON_LEFT, scaleProperty, parentWidth).value_or(0); + auto defaultControlButtonLeft = DEFAULT_CONTROL_BUTTON_LEFT - CONTROL_BUTTON_PADDING; + auto defaultControlButtonLeftPx = ConvertToPx(defaultControlButtonLeft, scaleProperty, parentWidth).value_or(0); auto controlButtonWidthPx = ConvertToPx(controlButtonWidth, scaleProperty, parentWidth).value_or(0); controlButtonLeftPx = parentWidth - defaultControlButtonLeftPx - controlButtonWidthPx; } diff --git a/frameworks/core/components_ng/pattern/side_bar/side_bar_container_layout_algorithm.h b/frameworks/core/components_ng/pattern/side_bar/side_bar_container_layout_algorithm.h index d14d53c8da1..3eb5374416f 100644 --- a/frameworks/core/components_ng/pattern/side_bar/side_bar_container_layout_algorithm.h +++ b/frameworks/core/components_ng/pattern/side_bar/side_bar_container_layout_algorithm.h @@ -131,6 +131,16 @@ public: pattern_ = pattern; } + void SetControlImageWidth(const Dimension& width) + { + controlImageWidth_ = width; + } + + void SetControlImageHeight(const Dimension& height) + { + controlImageHeight_ = height; + } + private: void MeasureControlButton(const RefPtr& layoutProperty, const RefPtr& buttonLayoutWrapper, float parentWidth); @@ -180,6 +190,8 @@ private: Dimension adjustMaxSideBarWidth_; Dimension adjustMinSideBarWidth_; + Dimension controlImageWidth_; + Dimension controlImageHeight_; ACE_DISALLOW_COPY_AND_MOVE(SideBarContainerLayoutAlgorithm); }; diff --git a/frameworks/core/components_ng/pattern/side_bar/side_bar_container_model_ng.cpp b/frameworks/core/components_ng/pattern/side_bar/side_bar_container_model_ng.cpp index 2ddba46a482..3ca14caf5b3 100644 --- a/frameworks/core/components_ng/pattern/side_bar/side_bar_container_model_ng.cpp +++ b/frameworks/core/components_ng/pattern/side_bar/side_bar_container_model_ng.cpp @@ -18,13 +18,13 @@ #include "base/geometry/dimension.h" #include "base/image/pixel_map.h" #include "core/components_ng/base/view_stack_processor.h" +#include "core/components_ng/pattern/button/button_pattern.h" #include "core/components_ng/pattern/divider/divider_layout_property.h" #include "core/components_ng/pattern/divider/divider_pattern.h" #include "core/components_ng/pattern/divider/divider_render_property.h" #include "core/components_ng/pattern/image/image_pattern.h" #include "core/components_ng/pattern/side_bar/side_bar_container_layout_property.h" #include "core/components_ng/pattern/side_bar/side_bar_container_pattern.h" -#include "core/components_ng/pattern/side_bar/side_bar_theme.h" #include "core/components_v2/inspector/inspector_constants.h" #include "core/image/image_source_info.h" #include "core/pipeline_ng/pipeline_context.h" @@ -114,18 +114,60 @@ void SideBarContainerModelNG::Pop() void SideBarContainerModelNG::CreateAndMountControlButton(const RefPtr& parentNode) { - auto layoutProperty = parentNode->GetLayoutProperty(); - CHECK_NULL_VOID(layoutProperty); - auto showSideBar = layoutProperty->GetShowSideBar().value_or(true); - auto context = PipelineBase::GetCurrentContext(); CHECK_NULL_VOID(context); auto sideBarTheme = context->GetTheme(); CHECK_NULL_VOID(sideBarTheme); - Color controlButtonColor = sideBarTheme->GetControlImageColor(); + auto buttonNode = CreateControlButton(sideBarTheme); + CHECK_NULL_VOID(buttonNode); + auto imgNode = CreateControlImage(sideBarTheme, parentNode); + CHECK_NULL_VOID(imgNode); + + auto buttonHub = buttonNode->GetEventHub(); + CHECK_NULL_VOID(buttonHub); + auto gestureHub = buttonHub->GetOrCreateGestureEventHub(); + CHECK_NULL_VOID(gestureHub); + auto parentPattern = parentNode->GetPattern(); + parentPattern->SetHasControlButton(true); + parentPattern->InitControlButtonTouchEvent(gestureHub); + + imgNode->MountToParent(buttonNode); + buttonNode->MountToParent(parentNode); + imgNode->MarkModifyDone(); + buttonNode->MarkModifyDone(); +} + +RefPtr SideBarContainerModelNG::CreateControlButton(const RefPtr& sideBarTheme) +{ + int32_t buttonId = ElementRegister::GetInstance()->MakeUniqueId(); + auto buttonNode = FrameNode::GetOrCreateFrameNode( + V2::BUTTON_ETS_TAG, buttonId, []() { return AceType::MakeRefPtr(); }); + CHECK_NULL_RETURN(buttonNode, nullptr); + auto buttonLayoutProperty = buttonNode->GetLayoutProperty(); + CHECK_NULL_RETURN(buttonLayoutProperty, nullptr); + buttonLayoutProperty->UpdateType(ButtonType::NORMAL); + auto butttonRadius = sideBarTheme->GetControlButtonRadius(); + buttonLayoutProperty->UpdateBorderRadius(BorderRadiusProperty(butttonRadius)); + auto buttonRenderContext = buttonNode->GetRenderContext(); + CHECK_NULL_RETURN(buttonRenderContext, nullptr); + buttonRenderContext->UpdateBackgroundColor(Color::TRANSPARENT); + return buttonNode; +} + +RefPtr SideBarContainerModelNG::CreateControlImage( + const RefPtr& sideBarTheme, const RefPtr& parentNode) +{ + int32_t imgNodeId = ElementRegister::GetInstance()->MakeUniqueId(); + auto imgNode = FrameNode::GetOrCreateFrameNode( + V2::IMAGE_ETS_TAG, imgNodeId, []() { return AceType::MakeRefPtr(); }); + CHECK_NULL_RETURN(imgNode, nullptr); + + auto layoutProperty = parentNode->GetLayoutProperty(); + CHECK_NULL_RETURN(layoutProperty, nullptr); + auto isShowSideBar = layoutProperty->GetShowSideBar().value_or(true); std::optional info = std::nullopt; - if (showSideBar) { + if (isShowSideBar) { info = layoutProperty->GetControlButtonShowIconInfo(); } else { info = layoutProperty->GetControlButtonHiddenIconInfo(); @@ -133,32 +175,22 @@ void SideBarContainerModelNG::CreateAndMountControlButton(const RefPtr(); info->SetResourceId(InternalResource::ResourceId::SIDE_BAR); + Color controlButtonColor = sideBarTheme->GetControlImageColor(); info->SetFillColor(controlButtonColor); } - - int32_t imgNodeId = ElementRegister::GetInstance()->MakeUniqueId(); - auto imgNode = FrameNode::GetOrCreateFrameNode( - V2::IMAGE_ETS_TAG, imgNodeId, []() { return AceType::MakeRefPtr(); }); - - auto imgHub = imgNode->GetEventHub(); - CHECK_NULL_VOID(imgHub); - auto gestureHub = imgHub->GetOrCreateGestureEventHub(); - CHECK_NULL_VOID(gestureHub); - auto parentPattern = parentNode->GetPattern(); - parentPattern->SetHasControlButton(true); - parentPattern->InitControlButtonTouchEvent(gestureHub); - - auto inputHub = imgHub->GetOrCreateInputEventHub(); - CHECK_NULL_VOID(inputHub); - parentPattern->InitControlButtonMouseEvent(inputHub); - auto imageLayoutProperty = imgNode->GetLayoutProperty(); - CHECK_NULL_VOID(imageLayoutProperty); + CHECK_NULL_RETURN(imageLayoutProperty, nullptr); imageLayoutProperty->UpdateImageSourceInfo(info.value()); imageLayoutProperty->UpdateImageFit(ImageFit::FILL); - - imgNode->MountToParent(parentNode); - imgNode->MarkModifyDone(); + imageLayoutProperty->UpdateAlignment(Alignment::CENTER); + auto parentPattern = parentNode->GetPattern(); + CHECK_NULL_RETURN(parentPattern, nullptr); + Dimension imageWidth; + Dimension imageHeight; + parentPattern->GetControlImageSize(imageWidth, imageHeight); + CalcSize imageCalcSize((CalcLength(imageWidth)), CalcLength(imageHeight)); + imageLayoutProperty->UpdateUserDefinedIdealSize(imageCalcSize); + return imgNode; } void SideBarContainerModelNG::CreateAndMountDivider(const RefPtr& parentNode) diff --git a/frameworks/core/components_ng/pattern/side_bar/side_bar_container_model_ng.h b/frameworks/core/components_ng/pattern/side_bar/side_bar_container_model_ng.h index 2723e72b891..8371fcd2c63 100644 --- a/frameworks/core/components_ng/pattern/side_bar/side_bar_container_model_ng.h +++ b/frameworks/core/components_ng/pattern/side_bar/side_bar_container_model_ng.h @@ -17,6 +17,7 @@ #define FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_NG_PATTERNS_SIDE_BAR_CONTAINER_MODEL_NG_H #include "core/components_ng/pattern/side_bar/side_bar_container_model.h" +#include "core/components_ng/pattern/side_bar/side_bar_theme.h" namespace OHOS::Ace::NG { class ACE_EXPORT SideBarContainerModelNG : public SideBarContainerModel { @@ -54,6 +55,9 @@ private: void CreateAndMountControlButton(const RefPtr& parentNode) override; void CreateAndMountDivider(const RefPtr& parentNode) override; void MarkNeedInitRealSideBarWidth() override; + RefPtr CreateControlButton(const RefPtr& sideBarTheme); + RefPtr CreateControlImage(const RefPtr& sideBarTheme, + const RefPtr& parentNode); }; } // namespace OHOS::Ace::NG #endif // FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_NG_PATTERNS_SIDE_BAR_CONTAINER_MODEL_H diff --git a/frameworks/core/components_ng/pattern/side_bar/side_bar_container_pattern.cpp b/frameworks/core/components_ng/pattern/side_bar/side_bar_container_pattern.cpp index f8830782d21..c0af60a0914 100644 --- a/frameworks/core/components_ng/pattern/side_bar/side_bar_container_pattern.cpp +++ b/frameworks/core/components_ng/pattern/side_bar/side_bar_container_pattern.cpp @@ -20,6 +20,7 @@ #include "base/mousestyle/mouse_style.h" #include "base/resource/internal_resource.h" #include "core/components_ng/base/frame_node.h" +#include "core/components_ng/pattern/button/button_layout_property.h" #include "core/components_ng/pattern/divider/divider_layout_property.h" #include "core/components_ng/pattern/divider/divider_render_property.h" #include "core/components_ng/pattern/image/image_pattern.h" @@ -47,11 +48,11 @@ constexpr Dimension DEFAULT_DIVIDER_STROKE_WIDTH = 1.0_vp; constexpr Dimension DEFAULT_DIVIDER_START_MARGIN = 0.0_vp; constexpr Dimension DEFAULT_DIVIDER_HOT_ZONE_HORIZONTAL_PADDING = 2.0_vp; constexpr Color DEFAULT_DIVIDER_COLOR = Color(0x08000000); -constexpr float HOVER_OPACITY = 0.05f; -constexpr float PRESS_OPACITY = 0.1f; constexpr static int32_t PLATFORM_VERSION_TEN = 10; constexpr static int32_t SIDE_BAR_INDEX = 2; constexpr static int32_t CONTENT_INDEX = 3; +Dimension DEFAULT_CONTROL_BUTTON_WIDTH = 32.0_vp; +Dimension DEFAULT_CONTROL_BUTTON_HEIGHT = 32.0_vp; } // namespace void SideBarContainerPattern::OnAttachToFrameNode() @@ -88,17 +89,17 @@ void SideBarContainerPattern::OnUpdateShowControlButton( } auto controlButtonNode = children.back(); - if (controlButtonNode->GetTag() != V2::IMAGE_ETS_TAG || !AceType::InstanceOf(controlButtonNode)) { + if (controlButtonNode->GetTag() != V2::BUTTON_ETS_TAG || !AceType::InstanceOf(controlButtonNode)) { LOGE("OnUpdateShowControlButton: Get control button failed."); return; } - auto imgFrameNode = AceType::DynamicCast(controlButtonNode); - auto imageLayoutProperty = imgFrameNode->GetLayoutProperty(); - CHECK_NULL_VOID(imageLayoutProperty); + auto buttonFrameNode = AceType::DynamicCast(controlButtonNode); + auto buttonLayoutProperty = buttonFrameNode->GetLayoutProperty(); + CHECK_NULL_VOID(buttonLayoutProperty); - imageLayoutProperty->UpdateVisibility(showControlButton ? VisibleType::VISIBLE : VisibleType::GONE); - imgFrameNode->MarkModifyDone(); + buttonLayoutProperty->UpdateVisibility(showControlButton ? VisibleType::VISIBLE : VisibleType::GONE); + buttonFrameNode->MarkModifyDone(); } void SideBarContainerPattern::OnUpdateShowDivider( @@ -136,6 +137,23 @@ void SideBarContainerPattern::OnUpdateShowDivider( dividerFrameNode->MarkModifyDone(); } +void SideBarContainerPattern::GetControlImageSize(Dimension& width, Dimension& height) +{ + auto pipeline = PipelineContext::GetCurrentContext(); + CHECK_NULL_VOID(pipeline); + if (pipeline->GetMinPlatformVersion() >= PLATFORM_VERSION_TEN) { + DEFAULT_CONTROL_BUTTON_WIDTH = 24.0_vp; + DEFAULT_CONTROL_BUTTON_HEIGHT = 24.0_vp; + } + auto layoutProperty = GetLayoutProperty(); + CHECK_NULL_VOID(layoutProperty); + controlImageWidth_ = layoutProperty->GetControlButtonWidth().value_or(DEFAULT_CONTROL_BUTTON_WIDTH); + controlImageHeight_ = layoutProperty->GetControlButtonHeight().value_or(DEFAULT_CONTROL_BUTTON_HEIGHT); + + width = controlImageWidth_; + height = controlImageHeight_; +} + RefPtr SideBarContainerPattern::GetContentNode(const RefPtr& host) const { CHECK_NULL_RETURN(host, nullptr); @@ -170,6 +188,33 @@ RefPtr SideBarContainerPattern::GetSideBarNode(const RefPtr SideBarContainerPattern::GetControlImageNode() const +{ + auto host = GetHost(); + CHECK_NULL_RETURN(host, nullptr); + + auto children = host->GetChildren(); + if (children.empty()) { + return nullptr; + } + + auto controlButtonNode = children.back(); + if (controlButtonNode->GetTag() != V2::BUTTON_ETS_TAG || !AceType::InstanceOf(controlButtonNode)) { + return nullptr; + } + + auto buttonChildren = controlButtonNode->GetChildren(); + if (buttonChildren.empty()) { + return nullptr; + } + + auto imageNode = buttonChildren.front(); + if (imageNode->GetTag() != V2::IMAGE_ETS_TAG || !AceType::InstanceOf(imageNode)) { + return nullptr; + } + return AceType::DynamicCast(imageNode); +} + void SideBarContainerPattern::OnUpdateSideBarAndContent(const RefPtr& host) { CHECK_NULL_VOID(host); @@ -315,26 +360,6 @@ void SideBarContainerPattern::InitControlButtonTouchEvent(const RefPtrAddClickEvent(controlButtonClickEvent_); } -void SideBarContainerPattern::InitControlButtonMouseEvent(const RefPtr& inputHub) -{ - CHECK_NULL_VOID_NOLOG(!controlButtonHoverEvent_); - - auto hoverTask = [weak = WeakClaim(this)](bool isHover) { - auto pattern = weak.Upgrade(); - if (pattern) { - pattern->OnControlButtonHover(isHover); - } - }; - controlButtonHoverEvent_ = MakeRefPtr(std::move(hoverTask)); - inputHub->AddOnHoverEvent(controlButtonHoverEvent_); - inputHub->SetMouseEvent([weak = WeakClaim(this)](MouseInfo& info) { - auto pattern = weak.Upgrade(); - if (pattern) { - pattern->HandleMouseEvent(info); - } - }); -} - void SideBarContainerPattern::UpdateAnimDir() { auto layoutProperty = GetLayoutProperty(); @@ -496,22 +521,9 @@ void SideBarContainerPattern::UpdateControlButtonIcon() auto layoutProperty = GetLayoutProperty(); CHECK_NULL_VOID(layoutProperty); - auto host = GetHost(); - CHECK_NULL_VOID(host); + auto imgFrameNode = GetControlImageNode(); + CHECK_NULL_VOID(imgFrameNode); - auto children = host->GetChildren(); - if (children.empty()) { - LOGE("UpdateControlButtonIcon: children is empty."); - return; - } - - auto controlButtonNode = children.back(); - if (controlButtonNode->GetTag() != V2::IMAGE_ETS_TAG || !AceType::InstanceOf(controlButtonNode)) { - LOGE("UpdateControlButtonIcon: Get control button failed."); - return; - } - - auto imgFrameNode = AceType::DynamicCast(controlButtonNode); auto imgRenderContext = imgFrameNode->GetRenderContext(); auto imageLayoutProperty = imgFrameNode->GetLayoutProperty(); CHECK_NULL_VOID(imageLayoutProperty); @@ -771,81 +783,6 @@ void SideBarContainerPattern::OnHover(bool isHover) } } -void SideBarContainerPattern::OnControlButtonHover(bool isHover) -{ - auto host = GetHost(); - CHECK_NULL_VOID(host); - - auto children = host->GetChildren(); - if (children.empty()) { - LOGE("UpdateControlButtonIcon: children is empty."); - return; - } - - auto controlButtonNode = children.back(); - if (controlButtonNode->GetTag() != V2::IMAGE_ETS_TAG || !AceType::InstanceOf(controlButtonNode)) { - LOGE("UpdateControlButtonIcon: Get control button failed."); - return; - } - - isControlButtonHover_ = isHover; - auto imgFrameNode = AceType::DynamicCast(controlButtonNode); - CHECK_NULL_VOID(imgFrameNode); - auto imgRenderContext = imgFrameNode->GetRenderContext(); - CHECK_NULL_VOID(imgRenderContext); - if (isHover) { - DoControlButtonHoverAnimation(imgRenderContext, 0.0f, HOVER_OPACITY, HOVER_DURATION, Curves::FRICTION); - } else { - DoControlButtonHoverAnimation(imgRenderContext, HOVER_OPACITY, 0.0f, HOVER_DURATION, Curves::FRICTION); - } -} - -void SideBarContainerPattern::DoControlButtonHoverAnimation(RefPtr& renderContext, float startOpacity, - float endOpacity, int32_t duration, const RefPtr& curve) -{ - Color colorFrom = Color::FromRGBO(0, 0, 0, startOpacity); - Color colorTo = Color::FromRGBO(0, 0, 0, endOpacity); - Color highlightStart = renderContext->GetBackgroundColor().value_or(Color::TRANSPARENT).BlendColor(colorFrom); - Color highlightEnd = renderContext->GetBackgroundColor().value_or(Color::TRANSPARENT).BlendColor(colorTo); - renderContext->OnBackgroundColorUpdate(highlightStart); - AnimationOption option = AnimationOption(); - option.SetDuration(duration); - option.SetCurve(curve); - AnimationUtils::Animate( - option, [renderContext, highlightEnd]() { renderContext->OnBackgroundColorUpdate(highlightEnd); }); -} - -void SideBarContainerPattern::HandleMouseEvent(const MouseInfo& info) -{ - auto host = GetHost(); - CHECK_NULL_VOID(host); - - auto children = host->GetChildren(); - if (children.empty()) { - LOGE("HandleMouseEvent: children is empty."); - return; - } - - auto controlButtonNode = children.back(); - if (controlButtonNode->GetTag() != V2::IMAGE_ETS_TAG || !AceType::InstanceOf(controlButtonNode)) { - LOGE("HandleMouseEvent: Get control button failed."); - return; - } - - auto imgFrameNode = AceType::DynamicCast(controlButtonNode); - CHECK_NULL_VOID(imgFrameNode); - auto imgRenderContext = imgFrameNode->GetRenderContext(); - CHECK_NULL_VOID(imgRenderContext); - if ((info.GetButton() != MouseButton::LEFT_BUTTON) || (!isControlButtonHover_)) { - return; - } - if (info.GetAction() == MouseAction::PRESS) { - DoControlButtonHoverAnimation(imgRenderContext, HOVER_OPACITY, PRESS_OPACITY, PRESS_DURATION, Curves::SHARP); - } else if (info.GetAction() == MouseAction::RELEASE) { - DoControlButtonHoverAnimation(imgRenderContext, PRESS_OPACITY, HOVER_OPACITY, PRESS_DURATION, Curves::SHARP); - } -} - SideBarPosition SideBarContainerPattern::GetSideBarPositionWithRtl( const RefPtr& layoutProperty) { diff --git a/frameworks/core/components_ng/pattern/side_bar/side_bar_container_pattern.h b/frameworks/core/components_ng/pattern/side_bar/side_bar_container_pattern.h index 0cb69dc6fb4..42b984a421c 100644 --- a/frameworks/core/components_ng/pattern/side_bar/side_bar_container_pattern.h +++ b/frameworks/core/components_ng/pattern/side_bar/side_bar_container_pattern.h @@ -62,6 +62,8 @@ public: layoutAlgorithm->SetMaxSideBarWidth(maxSideBarWidth_); layoutAlgorithm->SetMinContentWidth(minContentWidth_); layoutAlgorithm->SetTypeUpdateWidth(typeUpdateWidth_); + layoutAlgorithm->SetControlImageWidth(controlImageWidth_); + layoutAlgorithm->SetControlImageHeight(controlImageHeight_); auto host = GetHost(); auto sideBarContainerPattern = host->GetPattern(); layoutAlgorithm->SetPattern(AceType::WeakClaim(AceType::RawPtr(sideBarContainerPattern))); @@ -110,7 +112,6 @@ public: } void InitControlButtonTouchEvent(const RefPtr& gestureHub); - void InitControlButtonMouseEvent(const RefPtr& inputHub); void InitDividerMouseEvent(const RefPtr& inputHub); void UpdateSideBarPosition(float value); void SetMinSideBarWidth(float minSideBarWidth) @@ -129,6 +130,7 @@ public: { typeUpdateWidth_ = typeUpdateWidth; } + void GetControlImageSize(Dimension& width, Dimension& height); private: bool OnDirtyLayoutWrapperSwap(const RefPtr& dirty, const DirtySwapConfig& config) override; @@ -154,14 +156,11 @@ private: const RefPtr& layoutProperty, const RefPtr& host); void OnUpdateSideBarAndContent(const RefPtr& host); void OnHover(bool isHover); - void OnControlButtonHover(bool isHover); void AddDividerHotZoneRect(const RefPtr& layoutAlgorithm); - void DoControlButtonHoverAnimation(RefPtr& renderContext, float startOpacity, float endOpacity, - int32_t duration, const RefPtr& curve); - void HandleMouseEvent(const MouseInfo& info); SideBarPosition GetSideBarPositionWithRtl(const RefPtr& layoutProperty); RefPtr GetSideBarNode(const RefPtr& host) const; RefPtr GetContentNode(const RefPtr& host) const; + RefPtr GetControlImageNode() const; RefPtr hoverEvent_; RefPtr controlButtonClickEvent_; @@ -182,7 +181,6 @@ private: float preSidebarWidth_ = 0.0f; bool hasControlButton_ = false; SideBarAnimationDirection animDir_ = SideBarAnimationDirection::LTR; - bool isControlButtonHover_ = false; bool isControlButtonClick_ = false; Dimension adjustMaxSideBarWidth_; @@ -192,6 +190,8 @@ private: float minSideBarWidth_ = -1.0f; float maxSideBarWidth_ = -1.0f; float typeUpdateWidth_ = 0.0f; + Dimension controlImageWidth_; + Dimension controlImageHeight_; ACE_DISALLOW_COPY_AND_MOVE(SideBarContainerPattern); }; diff --git a/frameworks/core/components_ng/pattern/side_bar/side_bar_theme.h b/frameworks/core/components_ng/pattern/side_bar/side_bar_theme.h index c458b16f834..4791384c733 100644 --- a/frameworks/core/components_ng/pattern/side_bar/side_bar_theme.h +++ b/frameworks/core/components_ng/pattern/side_bar/side_bar_theme.h @@ -61,6 +61,7 @@ public: theme->controlImageColor_ = sideBarPattern->GetAttr("control_image_color", Color::BLACK); theme->sideBarBackgroundColor_ = sideBarPattern->GetAttr("side_bar_background_color", Color::WHITE); + theme->controlButtonRadius_ = sideBarPattern->GetAttr("control_button_radius", 0.0_vp); } }; @@ -76,12 +77,18 @@ public: return sideBarBackgroundColor_; } + const Dimension& GetControlButtonRadius() const + { + return controlButtonRadius_; + } + protected: SideBarTheme() = default; private: Color controlImageColor_ = Color::BLACK; Color sideBarBackgroundColor_ = Color::WHITE; + Dimension controlButtonRadius_; }; } // namespace OHOS::Ace::NG #endif // FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_NG_PATTERN_SIDE_BAR_SIDE_BAR_THEME_H diff --git a/frameworks/core/components_ng/pattern/slider/slider_content_modifier.cpp b/frameworks/core/components_ng/pattern/slider/slider_content_modifier.cpp index deeb2b8ed85..0b70a6952db 100644 --- a/frameworks/core/components_ng/pattern/slider/slider_content_modifier.cpp +++ b/frameworks/core/components_ng/pattern/slider/slider_content_modifier.cpp @@ -15,9 +15,6 @@ #include "core/components_ng/pattern/slider/slider_content_modifier.h" -#include -#include - #include "base/geometry/ng/offset_t.h" #include "base/utils/utils.h" #include "core/animation/curves.h" @@ -30,7 +27,6 @@ namespace OHOS::Ace::NG { namespace { constexpr float HALF = 0.5f; -constexpr Dimension CIRCLE_SHADOW_WIDTH = 1.0_vp; constexpr float SPRING_MOTION_RESPONSE = 0.314f; constexpr float SPRING_MOTION_DAMPING_FRACTION = 0.95f; } // namespace @@ -126,8 +122,8 @@ void SliderContentModifier::onDraw(DrawingContext& context) DrawBackground(context); DrawStep(context); DrawSelect(context); - DrawBlock(context); DrawShadow(context); + DrawBlock(context); DrawHoverOrPress(context); } @@ -289,19 +285,26 @@ void SliderContentModifier::DrawShadow(DrawingContext& context) return; } - auto& canvas = context.canvas; if (!mouseHoverFlag_ && !mousePressedFlag_) { - RSPen circleShadowPen; - circleShadowPen.SetAntiAlias(true); - circleShadowPen.SetColor(ToRSColor(blockOuterEdgeColor_)); - circleShadowPen.SetWidth(static_cast(CIRCLE_SHADOW_WIDTH.ConvertToPx())); - canvas.AttachPen(circleShadowPen); + auto& canvas = context.canvas; auto blockSize = blockSize_->Get(); - float diameter = std::min(blockSize.Width(), blockSize.Height()); - auto penRadius = (diameter + static_cast(CIRCLE_SHADOW_WIDTH.ConvertToPx())) * HALF; auto blockCenter = PointF(blockCenterX_->Get(), blockCenterY_->Get()); - canvas.DrawCircle(ToRSPoint(blockCenter), penRadius); - canvas.DetachPen(); + float radius = std::min(blockSize.Width(), blockSize.Height()) * HALF; + canvas.Save(); + RSBrush shadowBrush; + shadowBrush.SetAntiAlias(true); + shadowBrush.SetColor(ToRSColor(blockShadowColor_)); + RSFilter filter; + filter.SetMaskFilter(RSMaskFilter::CreateBlurMaskFilter( + RSBlurType::NORMAL, RSDrawing::ConvertRadiusToSigma(hotCircleShadowWidth_))); + shadowBrush.SetFilter(filter); + + canvas.AttachBrush(shadowBrush); + RSPath path; + path.AddCircle(ToRSPoint(blockCenter).GetX(), ToRSPoint(blockCenter).GetY(), radius); + canvas.DrawPath(path); + canvas.DetachBrush(); + canvas.Restore(); } } diff --git a/frameworks/core/components_ng/pattern/slider/slider_content_modifier.h b/frameworks/core/components_ng/pattern/slider/slider_content_modifier.h index 5b2a43ab8de..b310c8f0703 100644 --- a/frameworks/core/components_ng/pattern/slider/slider_content_modifier.h +++ b/frameworks/core/components_ng/pattern/slider/slider_content_modifier.h @@ -67,6 +67,7 @@ public: auto sliderTheme = pipeline->GetTheme(); CHECK_NULL_VOID(sliderTheme); blockOuterEdgeColor_ = sliderTheme->GetBlockOuterEdgeColor(); + blockShadowColor_ = sliderTheme->GetBlockShadowColor(); } void UpdateData(const Parameters& parameters); @@ -295,6 +296,7 @@ private: bool needAnimate_ = false; // Translate Animation on-off float hotCircleShadowWidth_ = 0.0f; Color blockOuterEdgeColor_; + Color blockShadowColor_; RefPtr shape_; ACE_DISALLOW_COPY_AND_MOVE(SliderContentModifier); }; diff --git a/frameworks/core/components_ng/pattern/slider/slider_pattern.cpp b/frameworks/core/components_ng/pattern/slider/slider_pattern.cpp index 8805c112da5..dd234664118 100644 --- a/frameworks/core/components_ng/pattern/slider/slider_pattern.cpp +++ b/frameworks/core/components_ng/pattern/slider/slider_pattern.cpp @@ -198,6 +198,12 @@ bool SliderPattern::AtTouchPanArea(const Offset& offsetInFrame) bool SliderPattern::AtPanArea(const Offset& offset, const SourceType& sourceType) { + auto sliderPaintProperty = GetPaintProperty(); + CHECK_NULL_RETURN(sliderPaintProperty, false); + if (sliderPaintProperty->GetBlockTypeValue(SliderModelNG::BlockStyleType::DEFAULT) != + SliderModelNG::BlockStyleType::DEFAULT) { + return false; + } bool flag = false; switch (sourceType) { case SourceType::MOUSE: @@ -220,7 +226,6 @@ void SliderPattern::HandleTouchEvent(const TouchEventInfo& info) auto touchInfo = touchList.front(); auto touchType = touchInfo.GetTouchType(); if (touchType == TouchType::DOWN) { - hotFlag_ = true; // when Touch Down area is at Pan Area, value is unchanged. if (!AtPanArea(touchInfo.GetLocalLocation(), info.GetSourceDevice())) { UpdateValueByLocalLocation(touchInfo.GetLocalLocation()); @@ -233,7 +238,6 @@ void SliderPattern::HandleTouchEvent(const TouchEventInfo& info) FireChangeEvent(SliderChangeMode::Begin); OpenTranslateAnimation(); } else if (touchType == TouchType::UP) { - hotFlag_ = false; if (bubbleFlag_) { bubbleFlag_ = false; } @@ -275,10 +279,22 @@ void SliderPattern::HandlingGestureStart(const GestureEvent& info) void SliderPattern::HandlingGestureEvent(const GestureEvent& info) { + auto paintProperty = GetPaintProperty(); + CHECK_NULL_VOID(paintProperty); if (info.GetInputEventType() == InputEventType::AXIS) { auto offset = NearZero(info.GetOffsetX()) ? info.GetOffsetY() : info.GetOffsetX(); - offset > 0.0 ? MoveStep(-1) : MoveStep(1); - if (showTips_) { + // offset > 0 when Wheel Up, offset < 0 when Wheel Down + if (direction_ == Axis::HORIZONTAL) { + offset > 0.0 ? MoveStep(1) : MoveStep(-1); + } else { + auto reverse = paintProperty->GetReverseValue(false); + reverse ? (offset > 0.0 ? MoveStep(1) : MoveStep(-1)) : (offset > 0.0 ? MoveStep(-1) : MoveStep(1)); + } + if (hotFlag_) { + // Only when the mouse hovers over the slider, AxisFlag_ can be set true + AxisFlag_ = true; + } + if (showTips_ && AxisFlag_) { bubbleFlag_ = true; InitializeBubble(); } @@ -292,11 +308,8 @@ void SliderPattern::HandlingGestureEvent(const GestureEvent& info) void SliderPattern::HandledGestureEvent() { - hotFlag_ = false; - if (bubbleFlag_) { - bubbleFlag_ = false; - } panMoveFlag_ = false; + UpdateMarkDirtyNode(PROPERTY_UPDATE_RENDER); } @@ -398,6 +411,7 @@ void SliderPattern::InitPanEvent(const RefPtr& gestureHub) CHECK_NULL_VOID_NOLOG(pattern); pattern->HandledGestureEvent(); pattern->FireChangeEvent(SliderChangeMode::End); + pattern->AxisFlag_ = false; }; if (panEvent_) { gestureHub->RemovePanEvent(panEvent_); @@ -584,6 +598,7 @@ bool SliderPattern::OnKeyEvent(const KeyEvent& event) bool SliderPattern::MoveStep(int32_t stepCount) { + // stepCount > 0, slider value increases, block moves in the direction of growth auto host = GetHost(); CHECK_NULL_RETURN(host, false); auto sliderPaintProperty = host->GetPaintProperty(); @@ -641,9 +656,11 @@ void SliderPattern::InitMouseEvent(const RefPtr& inputEventHub) void SliderPattern::HandleHoverEvent(bool isHover) { + hotFlag_ = isHover; mouseHoverFlag_ = mouseHoverFlag_ && isHover; - if (!mouseHoverFlag_ && !mousePressedFlag_ && !focusFlag_) { + if (!mouseHoverFlag_) { bubbleFlag_ = false; + AxisFlag_ = false; } UpdateMarkDirtyNode(PROPERTY_UPDATE_RENDER); } @@ -652,15 +669,15 @@ void SliderPattern::HandleMouseEvent(const MouseInfo& info) { UpdateCircleCenterOffset(); // MouseInfo's LocalLocation is relative to the frame area, circleCenter_ is relative to the content area - bool mouseHoverFlag = AtMousePanArea(info.GetLocalLocation()); - if (!mouseHoverFlag_ && mouseHoverFlag) { + mouseHoverFlag_ = AtMousePanArea(info.GetLocalLocation()); + if (mouseHoverFlag_) { if (showTips_) { bubbleFlag_ = true; InitializeBubble(); } } - mouseHoverFlag_ = mouseHoverFlag; - if (!mouseHoverFlag_ && !mousePressedFlag_ && !focusFlag_) { + // when mouse hovers over slider, distinguish between hover block and Wheel operation. + if (!mouseHoverFlag_ && !AxisFlag_) { bubbleFlag_ = false; } diff --git a/frameworks/core/components_ng/pattern/slider/slider_pattern.h b/frameworks/core/components_ng/pattern/slider/slider_pattern.h index 1cc1af3abb3..b988d0d1845 100644 --- a/frameworks/core/components_ng/pattern/slider/slider_pattern.h +++ b/frameworks/core/components_ng/pattern/slider/slider_pattern.h @@ -180,10 +180,11 @@ private: enum SliderChangeMode { Begin = 0, Moving = 1, End = 2, Click = 3 }; float value_ = 0.0f; bool showTips_ = false; - bool hotFlag_ = false; + bool hotFlag_ = false; // whether the mouse is hovering over the slider bool valueChangeFlag_ = false; bool mouseHoverFlag_ = false; bool mousePressedFlag_ = false; + bool AxisFlag_ = false; // Wheel operation flag bool focusFlag_ = false; bool panMoveFlag_ = false; bool hasVisibleChangeRegistered_ = false; diff --git a/frameworks/core/components_ng/pattern/stage/stage_manager.cpp b/frameworks/core/components_ng/pattern/stage/stage_manager.cpp index c720cd27a9e..dd36e5e63f7 100644 --- a/frameworks/core/components_ng/pattern/stage/stage_manager.cpp +++ b/frameworks/core/components_ng/pattern/stage/stage_manager.cpp @@ -54,27 +54,35 @@ void FirePageTransition(const RefPtr& page, PageTransitionType transi transitionType, [weak = WeakPtr(page), transitionType, instanceId = Container::CurrentId()]() { ContainerScope scope(instanceId); LOGI("pageTransition exit finish"); - auto page = weak.Upgrade(); - CHECK_NULL_VOID(page); auto context = PipelineContext::GetCurrentContext(); CHECK_NULL_VOID(context); - auto pageFocusHub = page->GetFocusHub(); - CHECK_NULL_VOID(pageFocusHub); - pageFocusHub->SetParentFocusable(false); - pageFocusHub->LostFocus(); - if (transitionType == PageTransitionType::EXIT_POP && page->GetParent()) { - auto stageNode = page->GetParent(); - stageNode->RemoveChild(page); - stageNode->RebuildRenderContextTree(); - context->RequestFrame(); - return; - } - page->GetEventHub()->SetEnabled(true); - auto pattern = page->GetPattern(); - CHECK_NULL_VOID(pattern); - pattern->SetPageInTransition(false); - pattern->ProcessHideState(); - context->MarkNeedFlushMouseEvent(); + auto taskExecutor = context->GetTaskExecutor(); + CHECK_NULL_VOID(taskExecutor); + taskExecutor->PostTask( + [weak, weakContext = WeakPtr(context), transitionType]() { + auto page = weak.Upgrade(); + CHECK_NULL_VOID(page); + auto context = weakContext.Upgrade(); + CHECK_NULL_VOID(context); + auto pageFocusHub = page->GetFocusHub(); + CHECK_NULL_VOID(pageFocusHub); + pageFocusHub->SetParentFocusable(false); + pageFocusHub->LostFocus(); + if (transitionType == PageTransitionType::EXIT_POP && page->GetParent()) { + auto stageNode = page->GetParent(); + stageNode->RemoveChild(page); + stageNode->RebuildRenderContextTree(); + context->RequestFrame(); + return; + } + page->GetEventHub()->SetEnabled(true); + auto pattern = page->GetPattern(); + CHECK_NULL_VOID(pattern); + pattern->SetPageInTransition(false); + pattern->ProcessHideState(); + context->MarkNeedFlushMouseEvent(); + }, + TaskExecutor::TaskType::UI); }); return; } @@ -330,6 +338,8 @@ bool StageManager::CleanPageStack() auto popSize = static_cast(children.size() - 1); for (int32_t count = 1; count <= popSize; ++count) { auto pageNode = children.front(); + // mark pageNode child as destroying + pageNode->SetChildrenInDestroying(); stageNode_->RemoveChild(pageNode); } stageNode_->RebuildRenderContextTree(); diff --git a/frameworks/core/components_ng/pattern/stepper/stepper_pattern.cpp b/frameworks/core/components_ng/pattern/stepper/stepper_pattern.cpp index 107d7d1b9c3..f7e95ccc91c 100644 --- a/frameworks/core/components_ng/pattern/stepper/stepper_pattern.cpp +++ b/frameworks/core/components_ng/pattern/stepper/stepper_pattern.cpp @@ -219,7 +219,7 @@ void StepperPattern::UpdateLeftButtonNode(int32_t index) textNode->GetLayoutProperty()->UpdateContent(leftLabel); textNode->MarkModifyDone(); - buttonNode->MarkDirtyNode(PROPERTY_UPDATE_MEASURE); + textNode->MarkDirtyNode(PROPERTY_UPDATE_MEASURE); } void StepperPattern::UpdateOrCreateRightButtonNode(int32_t index) diff --git a/frameworks/core/components_ng/pattern/swiper/swiper_layout_algorithm.cpp b/frameworks/core/components_ng/pattern/swiper/swiper_layout_algorithm.cpp index 0b0ce875d4e..4cd672952c5 100644 --- a/frameworks/core/components_ng/pattern/swiper/swiper_layout_algorithm.cpp +++ b/frameworks/core/components_ng/pattern/swiper/swiper_layout_algorithm.cpp @@ -64,9 +64,9 @@ void SwiperLayoutAlgorithm::Measure(LayoutWrapper* layoutWrapper) bool hasMinSize = swiperLayoutProperty->GetMinSize().has_value() && !LessOrEqual(swiperLayoutProperty->GetMinSizeValue().Value(), 0); bool hasPrevMargin = swiperLayoutProperty->GetPrevMargin().has_value() && - !LessOrEqual(swiperLayoutProperty->GetPrevMarginValue().ConvertToPx(), 0); + !LessOrEqual(swiperLayoutProperty->GetPrevMarginValue().ConvertToPx(), 0); bool hasNextMargin = swiperLayoutProperty->GetNextMargin().has_value() && - !LessOrEqual(swiperLayoutProperty->GetNextMarginValue().ConvertToPx(), 0); + !LessOrEqual(swiperLayoutProperty->GetNextMarginValue().ConvertToPx(), 0); auto isSingleCase = !hasMinSize && (!hasPrevMargin && !hasNextMargin) && @@ -105,11 +105,11 @@ void SwiperLayoutAlgorithm::Measure(LayoutWrapper* layoutWrapper) contentMainSize_ = GetMainAxisSize(contentIdealSize.ConvertToSizeT(), axis); mainSizeIsDefined_ = true; } - auto itemSpace = SwiperUtils::GetItemSpace(swiperLayoutProperty); - spaceWidth_ = itemSpace > (contentMainSize_ + paddingBeforeContent_ + paddingAfterContent_) ? 0.0f : itemSpace; // calculate child layout constraint. auto childLayoutConstraint = SwiperUtils::CreateChildConstraint(swiperLayoutProperty, contentIdealSize); + auto itemSpace = SwiperUtils::GetItemSpace(swiperLayoutProperty); + spaceWidth_ = itemSpace > (contentMainSize_ + paddingBeforeContent_ + paddingAfterContent_) ? 0.0f : itemSpace; if (totalItemCount_ > 0) { currentOffset_ = currentDelta_; startMainPos_ = currentOffset_; @@ -241,15 +241,19 @@ void SwiperLayoutAlgorithm::MeasureSwiper( startPos = itemPosition_.begin()->second.startPos; endPos = itemPosition_.rbegin()->second.endPos; for (const auto& item : itemPosition_) { - if (GreatNotEqual(item.second.endPos, 0.0f)) { + if (GreatNotEqual( + Positive(prevMargin_) ? item.second.endPos + prevMargin_ + spaceWidth_ : item.second.endPos, 0.0f)) { startIndexInVisibleWindow = item.first; break; } } if (!isLoop_) { - startIndex = std::min(GetStartIndex(), totalItemCount_ - 1); - endIndex = std::min(GetEndIndex(), totalItemCount_ - 1); - startIndexInVisibleWindow = std::min(startIndexInVisibleWindow, totalItemCount_ - 1); + startIndex = std::min(GetLoopIndex(GetStartIndex()), totalItemCount_ - 1); + endIndex = std::min(GetLoopIndex(GetEndIndex()), totalItemCount_ - 1); + startIndexInVisibleWindow = std::min(GetLoopIndex(startIndexInVisibleWindow), totalItemCount_ - 1); + if (targetIndex_.has_value()) { + targetIndex_ = GetLoopIndex(targetIndex_.value()); + } } else { startIndex = GetStartIndex(); endIndex = GetEndIndex(); @@ -284,6 +288,9 @@ void SwiperLayoutAlgorithm::MeasureSwiper( } else { targetIsSameWithStartFlag_ = true; LayoutForward(layoutWrapper, layoutConstraint, axis, startIndexInVisibleWindow, startPos); + if (Positive(prevMargin_)) { + LayoutBackward(layoutWrapper, layoutConstraint, axis, GetStartIndex() - 1, GetStartPosition()); + } } } else { LOGD("StartIndex index: %{public}d, offset is %{public}f, startMainPos: %{public}f, endMainPos: %{public}f", diff --git a/frameworks/core/components_ng/pattern/swiper/swiper_pattern.cpp b/frameworks/core/components_ng/pattern/swiper/swiper_pattern.cpp index 0d7958f407b..5e963b7a957 100644 --- a/frameworks/core/components_ng/pattern/swiper/swiper_pattern.cpp +++ b/frameworks/core/components_ng/pattern/swiper/swiper_pattern.cpp @@ -163,6 +163,9 @@ void SwiperPattern::OnModifyDone() StopTranslateAnimation(); StopSpringAnimation(); StopFadeAnimation(); + if (indicatorController_) { + indicatorController_->Stop(); + } currentOffset_ = 0.0f; mainSizeIsMeasured_ = false; itemPosition_.clear(); @@ -275,6 +278,9 @@ void SwiperPattern::InitSurfaceChangedCallback() swiper->StopTranslateAnimation(); swiper->StopSpringAnimation(); swiper->StopFadeAnimation(); + if (swiper->indicatorController_) { + swiper->indicatorController_->Stop(); + } swiper->currentOffset_ = 0.0f; swiper->itemPosition_.clear(); swiper->jumpIndex_ = swiper->currentIndex_; @@ -536,7 +542,8 @@ bool SwiperPattern::OnDirtyLayoutWrapperSwap(const RefPtr& dirty, } jumpIndex_.reset(); } else if (targetIndex_) { - auto iter = itemPosition_.find(targetIndex_.value()); + auto targetIndexValue = IsLoop() ? targetIndex_.value() : GetLoopIndex(targetIndex_.value()); + auto iter = itemPosition_.find(targetIndexValue); if (iter != itemPosition_.end()) { float targetPos = 0.0f; targetPos = iter->second.startPos; @@ -2104,7 +2111,7 @@ std::shared_ptr SwiperPattern::GetSwiperParameters() const swiperParameters_->itemHeight = swiperIndicatorTheme->GetSize(); swiperParameters_->selectedItemWidth = swiperIndicatorTheme->GetSize(); swiperParameters_->selectedItemHeight = swiperIndicatorTheme->GetSize(); - swiperParameters_->maskValue = true; + swiperParameters_->maskValue = false; swiperParameters_->colorVal = swiperIndicatorTheme->GetColor(); swiperParameters_->selectedColorVal = swiperIndicatorTheme->GetSelectedColor(); } @@ -2337,7 +2344,8 @@ void SwiperPattern::PostTranslateTask(uint32_t delayTime) if (childrenSize <= 0 || displayCount <= 0 || swiper->itemPosition_.empty()) { return; } - if (!swiper->IsLoop() && (swiper->autoPlayCurrentIndex_ + 1) > (childrenSize - displayCount)) { + if (!swiper->IsLoop() && + (swiper->GetLoopIndex(swiper->autoPlayCurrentIndex_) + 1) > (childrenSize - displayCount)) { return; } swiper->targetIndex_ = swiper->autoPlayCurrentIndex_ + 1; diff --git a/frameworks/core/components_ng/pattern/swiper/swiper_utils.h b/frameworks/core/components_ng/pattern/swiper/swiper_utils.h index 8892758246c..77ced835612 100644 --- a/frameworks/core/components_ng/pattern/swiper/swiper_utils.h +++ b/frameworks/core/components_ng/pattern/swiper/swiper_utils.h @@ -71,31 +71,26 @@ public: auto childSelfIdealSize = idealSize; float childCalcIdealLength = 0.0f; - if (axis == Axis::HORIZONTAL) { - if (idealSize.Width().has_value()) { - childCalcIdealLength = (idealSize.Width().value() - itemSpace * itemSpaceCount - + if ((axis == Axis::HORIZONTAL && idealSize.Width().has_value()) || + (axis == Axis::VERTICAL && idealSize.Height().has_value())) { + auto length = axis == Axis::HORIZONTAL ? idealSize.Width().value() : + idealSize.Height().value(); + childCalcIdealLength = (length - itemSpace * itemSpaceCount - static_cast(prevMargin + nextMargin)) / displayCount; - if (CheckMarginPropertyExceed(property, childCalcIdealLength)) { - prevMargin = 0.0; - nextMargin = 0.0; - itemSpaceCount = CaculateDisplayItemSpaceCount(property, prevMargin, nextMargin); - childCalcIdealLength = (idealSize.Width().value() - itemSpace * itemSpaceCount) / displayCount; - } - childSelfIdealSize.SetWidth(childCalcIdealLength); + if (LessNotEqual(childCalcIdealLength, 0.0)) { + itemSpace = 0.0f; + childCalcIdealLength = (length - itemSpace * itemSpaceCount - + static_cast(prevMargin + nextMargin)) / displayCount; + property->UpdateItemSpace(Dimension(0.0)); } - } else if (axis == Axis::VERTICAL) { - if (idealSize.Height().has_value()) { - childCalcIdealLength = (idealSize.Height().value() - itemSpace * itemSpaceCount - - static_cast(prevMargin + nextMargin)) / displayCount; - if (CheckMarginPropertyExceed(property, childCalcIdealLength)) { - prevMargin = 0.0; - nextMargin = 0.0; - itemSpaceCount = CaculateDisplayItemSpaceCount(property, prevMargin, nextMargin); - childCalcIdealLength = (idealSize.Height().value() - - itemSpace * itemSpaceCount) / displayCount; - } + if (CheckMarginPropertyExceed(property, childCalcIdealLength)) { + prevMargin = 0.0; + nextMargin = 0.0; + itemSpaceCount = CaculateDisplayItemSpaceCount(property, prevMargin, nextMargin); + childCalcIdealLength = (length - itemSpace * itemSpaceCount) / displayCount; + } + axis == Axis::HORIZONTAL ? childSelfIdealSize.SetWidth(childCalcIdealLength) : childSelfIdealSize.SetHeight(childCalcIdealLength); - } } layoutConstraint.selfIdealSize = childSelfIdealSize; diff --git a/frameworks/core/components_ng/pattern/tabs/tab_bar_pattern.cpp b/frameworks/core/components_ng/pattern/tabs/tab_bar_pattern.cpp index 39905b3764e..304b5d31eb3 100644 --- a/frameworks/core/components_ng/pattern/tabs/tab_bar_pattern.cpp +++ b/frameworks/core/components_ng/pattern/tabs/tab_bar_pattern.cpp @@ -243,8 +243,9 @@ void TabBarPattern::HandleMouseEvent(const MouseInfo& info) return; } if (mouseAction == MouseAction::WINDOW_LEAVE) { - HandleMoveAway(hoverIndex_.value()); - return; + if (hoverIndex_.has_value()) { + HandleMoveAway(hoverIndex_.value()); + } } } @@ -301,7 +302,7 @@ bool TabBarPattern::OnKeyEvent(const KeyEvent& event) auto pipeline = PipelineContext::GetCurrentContext(); CHECK_NULL_RETURN(pipeline, false); if (!pipeline->GetIsFocusActive()) { - return true; + return false; } isFirstFocus_ = false; if (event.action != KeyAction::DOWN) { diff --git a/frameworks/core/components_ng/pattern/text/text_content_modifier.cpp b/frameworks/core/components_ng/pattern/text/text_content_modifier.cpp index a50fcfbd9ef..cf1757b3455 100644 --- a/frameworks/core/components_ng/pattern/text/text_content_modifier.cpp +++ b/frameworks/core/components_ng/pattern/text/text_content_modifier.cpp @@ -425,18 +425,18 @@ void TextContentModifier::SetTextShadow(const Shadow& value) void TextContentModifier::SetTextDecoration(const TextDecoration& type) { - if (oldTextDecoration_ == type) { + auto oldTextDecoration = textDecoration_.value_or(TextDecoration::NONE); + if (oldTextDecoration == type) { return; } - if ((oldTextDecoration_ == TextDecoration::NONE && type == TextDecoration::UNDERLINE) || - (oldTextDecoration_ == TextDecoration::UNDERLINE && type == TextDecoration::NONE)) { + if ((oldTextDecoration == TextDecoration::NONE && type == TextDecoration::UNDERLINE) || + (oldTextDecoration == TextDecoration::UNDERLINE && type == TextDecoration::NONE)) { textDecorationAnimatable_ = true; } else { textDecorationAnimatable_ = false; } - oldTextDecoration_ = textDecoration_.value_or(TextDecoration::NONE); textDecoration_ = type; CHECK_NULL_VOID(textDecorationColorAlpha_); @@ -531,4 +531,4 @@ void TextContentModifier::ContentChange() CHECK_NULL_VOID(contentChange_); contentChange_->Set(!contentChange_->Get()); } -} // namespace OHOS::Ace::NG \ No newline at end of file +} // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/pattern/text/text_content_modifier.h b/frameworks/core/components_ng/pattern/text/text_content_modifier.h index 305fd9a6059..7ea1b368204 100644 --- a/frameworks/core/components_ng/pattern/text/text_content_modifier.h +++ b/frameworks/core/components_ng/pattern/text/text_content_modifier.h @@ -124,7 +124,6 @@ private: RefPtr shadowOffsetYFloat_; RefPtr shadowColor_; - TextDecoration oldTextDecoration_ = TextDecoration::NONE; float oldColorAlpha_ { 0.0f }; std::optional textDecoration_; std::optional textDecorationColor_; diff --git a/frameworks/core/components_ng/pattern/text/text_pattern.cpp b/frameworks/core/components_ng/pattern/text/text_pattern.cpp index a91e823522d..911811c9141 100644 --- a/frameworks/core/components_ng/pattern/text/text_pattern.cpp +++ b/frameworks/core/components_ng/pattern/text/text_pattern.cpp @@ -65,7 +65,7 @@ void TextPattern::OnAttachToFrameNode() PipelineContext::GetCurrentContext()->GetMinPlatformVersion() > API_PROTEXTION_GREATER_NINE) { auto host = GetHost(); CHECK_NULL_VOID(host); - host->GetRenderContext()->SetClipToFrame(true); + host->GetRenderContext()->UpdateClipEdge(true); } } @@ -603,7 +603,7 @@ DragDropInfo TextPattern::OnDragStart(const RefPtr& event, const auto selectedStr = GetSelectedText(textSelector_.GetTextStart(), textSelector_.GetTextEnd()); itemInfo.extraInfo = selectedStr; RefPtr unifiedData = UdmfClient::GetInstance()->CreateUnifiedData(); - UdmfClient::GetInstance()->AddTextRecord(unifiedData, selectedStr); + UdmfClient::GetInstance()->AddPlainTextRecord(unifiedData, selectedStr); event->SetData(unifiedData); AceEngineExt::GetInstance().DragStartExt(); diff --git a/frameworks/core/components_ng/pattern/text_clock/text_clock_layout_algorithm.cpp b/frameworks/core/components_ng/pattern/text_clock/text_clock_layout_algorithm.cpp new file mode 100644 index 00000000000..7f475546d8a --- /dev/null +++ b/frameworks/core/components_ng/pattern/text_clock/text_clock_layout_algorithm.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "core/components_ng/pattern/text_clock/text_clock_layout_algorithm.h" + +#include "core/components_ng/property/measure_utils.h" +namespace OHOS::Ace::NG { +void TextClockLayoutAlgorithm::Measure(LayoutWrapper* layoutWrapper) +{ + const auto& layoutProperty = layoutWrapper->GetLayoutProperty(); + CHECK_NULL_VOID(layoutProperty); + auto childConstraint = layoutProperty->CreateChildConstraint(); + + auto textWrapper = layoutWrapper->GetOrCreateChildByIndex(0); + CHECK_NULL_VOID(textWrapper); + textWrapper->Measure(childConstraint); + + auto textSize = textWrapper->GetGeometryNode()->GetFrameSize(); + OptionalSizeF textClockFrameSize = { textSize.Width(), textSize.Height() }; + auto padding = layoutProperty->CreatePaddingAndBorder(); + AddPaddingToSize(padding, textClockFrameSize); + auto constraint = layoutProperty->GetLayoutConstraint(); + const auto& minSize = constraint->minSize; + const auto& maxSize = constraint->maxSize; + if (constraint->selfIdealSize.Width()) { + textClockFrameSize.ConstrainFloat(minSize, maxSize, false); + } else if (constraint->selfIdealSize.Height()) { + textClockFrameSize.ConstrainFloat(minSize, maxSize, true); + } else { + textClockFrameSize.Constrain(minSize, maxSize); + } + layoutWrapper->GetGeometryNode()->SetFrameSize(textClockFrameSize.ConvertToSizeT()); +} +} // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/pattern/text_clock/text_clock_layout_algorithm.h b/frameworks/core/components_ng/pattern/text_clock/text_clock_layout_algorithm.h new file mode 100644 index 00000000000..f64bd6d9c4f --- /dev/null +++ b/frameworks/core/components_ng/pattern/text_clock/text_clock_layout_algorithm.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_NG_PATTERN_TEXT_CLOCK_TEXT_CLOCK_LAYOUT_ALGORITHM_H +#define FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_NG_PATTERN_TEXT_CLOCK_TEXT_CLOCK_LAYOUT_ALGORITHM_H +#include "core/components_ng/layout/layout_wrapper.h" + +namespace OHOS::Ace::NG { +class ACE_EXPORT TextClockLayoutAlgorithm : public BoxLayoutAlgorithm { + DECLARE_ACE_TYPE(TextClockLayoutAlgorithm, BoxLayoutAlgorithm); + +public: + TextClockLayoutAlgorithm() = default; + + ~TextClockLayoutAlgorithm() override = default; + + void Measure(LayoutWrapper* layoutWrapper) override; + + ACE_DISALLOW_COPY_AND_MOVE(TextClockLayoutAlgorithm); +}; +} // namespace OHOS::Ace::NG + +#endif // FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_NG_PATTERN_TEXT_CLOCK_TEXT_CLOCK_LAYOUT_ALGORITHM_H diff --git a/frameworks/core/components_ng/pattern/text_clock/text_clock_pattern.h b/frameworks/core/components_ng/pattern/text_clock/text_clock_pattern.h index e1dd1056a50..befcbdbf3dd 100644 --- a/frameworks/core/components_ng/pattern/text_clock/text_clock_pattern.h +++ b/frameworks/core/components_ng/pattern/text_clock/text_clock_pattern.h @@ -27,6 +27,7 @@ #include "core/components_ng/pattern/text/text_pattern.h" #include "core/components_ng/pattern/text_clock/text_clock_accessibility_property.h" #include "core/components_ng/pattern/text_clock/text_clock_event_hub.h" +#include "core/components_ng/pattern/text_clock/text_clock_layout_algorithm.h" #include "core/components_ng/pattern/text_clock/text_clock_layout_property.h" #include "core/components_ng/property/property.h" @@ -54,6 +55,11 @@ public: return MakeRefPtr(); } + RefPtr CreateLayoutAlgorithm() override + { + return MakeRefPtr(); + } + RefPtr GetTextClockController() const { return textClockController_; diff --git a/frameworks/core/components_ng/pattern/text_drag/text_drag_pattern.cpp b/frameworks/core/components_ng/pattern/text_drag/text_drag_pattern.cpp index d82d3bb54a5..6ea251a43a9 100644 --- a/frameworks/core/components_ng/pattern/text_drag/text_drag_pattern.cpp +++ b/frameworks/core/components_ng/pattern/text_drag/text_drag_pattern.cpp @@ -15,6 +15,7 @@ #include "core/components_ng/pattern/text_drag/text_drag_pattern.h" +#include "base/utils/utils.h" #include "core/components_ng/pattern/text/text_pattern.h" #include "core/components_ng/pattern/text_drag/text_drag_base.h" #include "core/components_ng/render/drawing.h" @@ -75,10 +76,10 @@ RefPtr TextDragPattern::CreateDragNode( auto rect = rectsForPlaceholders.at(imageIndex); for (const auto& box : boxes) { - if (NearEqual(box.rect_.GetLeft(), rect.Left()) && - NearEqual(box.rect_.GetRight(), rect.Right()) && - NearEqual(box.rect_.GetTop(), rect.Top()) && - NearEqual(box.rect_.GetBottom(), rect.Bottom())) { + if (LessOrEqual(box.rect_.GetLeft(), rect.Left()) && + GreatOrEqual(box.rect_.GetRight(), rect.Right()) && + LessOrEqual(box.rect_.GetTop(), rect.Top()) && + GreatOrEqual(box.rect_.GetBottom(), rect.Bottom())) { realImageChildren.emplace_back(child); realRectsForPlaceholders.emplace_back(rect); } diff --git a/frameworks/core/components_ng/pattern/text_field/text_field_layout_algorithm.cpp b/frameworks/core/components_ng/pattern/text_field/text_field_layout_algorithm.cpp index de74d1e88de..2c8cfbe77d5 100644 --- a/frameworks/core/components_ng/pattern/text_field/text_field_layout_algorithm.cpp +++ b/frameworks/core/components_ng/pattern/text_field/text_field_layout_algorithm.cpp @@ -110,13 +110,21 @@ void TextFieldLayoutAlgorithm::Measure(LayoutWrapper* layoutWrapper) RectF(layoutWrapper->GetGeometryNode()->GetFrameOffset(), layoutWrapper->GetGeometryNode()->GetFrameSize()); return; } + auto pipeline = PipelineBase::GetCurrentContext(); + CHECK_NULL_VOID(pipeline); + auto textFieldTheme = pipeline->GetTheme(); + CHECK_NULL_VOID(textFieldTheme); + auto defaultHeight = textFieldTheme->GetHeight().ConvertToPx(); if (!frameSize.Height().has_value()) { if (calcLayoutConstraint && calcLayoutConstraint->maxSize.has_value() && calcLayoutConstraint->maxSize.value().Height().has_value()) { frameSize.SetHeight(std::max(layoutConstraint->maxSize.Height(), layoutConstraint->minSize.Height())); } else if (!calcLayoutConstraint || NearZero(layoutConstraint->minSize.Height())) { + auto height = contentHeight + pattern->GetVerticalPaddingSum() < defaultHeight + ? defaultHeight + : contentHeight + pattern->GetVerticalPaddingSum(); frameSize.SetHeight( - std::min(layoutConstraint->maxSize.Height(), contentHeight + pattern->GetVerticalPaddingSum())); + std::min(layoutConstraint->maxSize.Height(), static_cast(height))); } else { frameSize.SetHeight(layoutConstraint->minSize.Height()); } @@ -185,7 +193,6 @@ std::optional TextFieldLayoutAlgorithm::MeasureContent( textContent = textFieldLayoutProperty->GetValueValue(""); if (!pattern->IsTextArea()) { textStyle.SetTextOverflow(TextOverflow::ELLIPSIS); - pattern->SetTextInputFlag(true); } } else { UpdatePlaceholderTextStyle(textFieldLayoutProperty, textFieldTheme, textStyle, pattern->IsDisabled()); @@ -210,6 +217,10 @@ std::optional TextFieldLayoutAlgorithm::MeasureContent( CreateParagraph(textStyle, textContent, isPasswordType && pattern->GetTextObscured() && !showPlaceHolder, disableTextAlign); } + float imageSize = 0.0f; + auto showPasswordIcon = textFieldLayoutProperty->GetShowPasswordIcon().value_or(true); + imageSize = showPasswordIcon ? pattern->GetIconSize() : 0.0f; + auto imageHotZoneWidth = showPasswordIcon ? imageSize + pattern->GetIconRightOffset() : 0.0; if (textStyle.GetMaxLines() == 1 && !showPlaceHolder && !isInlineStyle) { // for text input case, need to measure in one line without constraint. paragraph_->Layout(std::numeric_limits::infinity()); @@ -218,6 +229,8 @@ std::optional TextFieldLayoutAlgorithm::MeasureContent( if (isInlineStyle) { paragraph_->Layout(idealWidth + textFieldTheme->GetInlineBorderWidth().ConvertToPx() + textFieldTheme->GetInlineBorderWidth().ConvertToPx() + INLINE_SAFE_BOUNDARY_VALUE); + } else if (showPlaceHolder && isPasswordType) { + paragraph_->Layout(idealWidth - imageHotZoneWidth); } else { paragraph_->Layout(idealWidth - pattern->GetScrollBarWidth() - SCROLL_BAR_LEFT_WIDTH.ConvertToPx()); } @@ -248,7 +261,7 @@ std::optional TextFieldLayoutAlgorithm::MeasureContent( if (textContent.empty() || showPlaceHolder) { preferredHeight = pattern->PreferredLineHeight(); } - if (isInlineStyle && pattern->GetTextInputFlag() && !pattern->IsTextArea()) { + if (pattern->GetTextInputFlag() && !pattern->IsTextArea()) { pattern->SetSingleLineHeight(preferredHeight); } if (pattern->IsTextArea()) { @@ -266,7 +279,6 @@ std::optional TextFieldLayoutAlgorithm::MeasureContent( return SizeF(idealWidth, std::min(idealHeight, useHeight)); } // check password image size. - auto showPasswordIcon = textFieldLayoutProperty->GetShowPasswordIcon().value_or(true); if (!showPasswordIcon || !isPasswordType) { textRect_.SetSize(SizeF(static_cast(paragraph_->GetLongestLine()), preferredHeight)); imageRect_.Reset(); @@ -282,8 +294,6 @@ std::optional TextFieldLayoutAlgorithm::MeasureContent( } return SizeF(idealWidth, std::min(preferredHeight, idealHeight)); } - float imageSize = 0.0f; - imageSize = showPasswordIcon ? pattern->GetIconSize() : 0.0f; if (textStyle.GetMaxLines() > 1 || pattern->IsTextArea()) { // for textArea, need to delete imageWidth and remeasure. @@ -300,9 +310,6 @@ std::optional TextFieldLayoutAlgorithm::MeasureContent( } preferredHeight = std::min(static_cast(paragraph_->GetHeight()), idealHeight); textRect_.SetSize(SizeF(static_cast(paragraph_->GetLongestLine()), static_cast(preferredHeight))); - auto imageHotZoneWidth = imageSize + pattern->GetIconRightOffset(); - paragraph_->Layout(idealWidth - pattern->GetScrollBarWidth() - SCROLL_BAR_LEFT_WIDTH.ConvertToPx() - - imageHotZoneWidth); return SizeF(idealWidth - imageHotZoneWidth, std::min(idealHeight, preferredHeight)); } @@ -504,7 +511,10 @@ void TextFieldLayoutAlgorithm::CreateParagraph(const TextStyle& textStyle, std:: paraStyle.locale_ = Localization::GetInstance()->GetFontLocale(); paraStyle.wordBreakType_ = ToRSWordBreakType(textStyle.GetWordBreak()); paraStyle.fontSize_ = textStyle.GetFontSize().ConvertToPx(); - paraStyle.fontFamily_ = textStyle.GetFontFamilies().at(0); + auto fontFamilies = textStyle.GetFontFamilies(); + if (!fontFamilies.empty()) { + paraStyle.fontFamily_ = fontFamilies.at(0); + } if (textStyle.GetTextOverflow() == TextOverflow::ELLIPSIS) { paraStyle.ellipsis_ = StringUtils::Str8ToStr16(StringUtils::ELLIPSIS); } @@ -536,7 +546,10 @@ void TextFieldLayoutAlgorithm::CreateParagraph(const std::vector& tex paraStyle.locale_ = Localization::GetInstance()->GetFontLocale(); paraStyle.wordBreakType_ = ToRSWordBreakType(textStyle->GetWordBreak()); paraStyle.fontSize_ = textStyle->GetFontSize().ConvertToPx(); - paraStyle.fontFamily_ = textStyle->GetFontFamilies().at(0); + auto fontFamilies = textStyle->GetFontFamilies(); + if (!fontFamilies.empty()) { + paraStyle.fontFamily_ = fontFamilies.at(0); + } if (textStyle->GetTextOverflow() == TextOverflow::ELLIPSIS) { paraStyle.ellipsis_ = StringUtils::Str8ToStr16(StringUtils::ELLIPSIS); } diff --git a/frameworks/core/components_ng/pattern/text_field/text_field_model_ng.cpp b/frameworks/core/components_ng/pattern/text_field/text_field_model_ng.cpp index b8f77ab58aa..3bf625863ad 100644 --- a/frameworks/core/components_ng/pattern/text_field/text_field_model_ng.cpp +++ b/frameworks/core/components_ng/pattern/text_field/text_field_model_ng.cpp @@ -469,7 +469,7 @@ void TextFieldModelNG::SetShowCounter(bool value) void TextFieldModelNG::SetBarState(OHOS::Ace::DisplayMode value) { - ACE_UPDATE_LAYOUT_PROPERTY(TextFieldLayoutProperty, DisplayMode, static_cast(value)); + ACE_UPDATE_LAYOUT_PROPERTY(TextFieldLayoutProperty, DisplayMode, value); } void TextFieldModelNG::SetMaxViewLines(uint32_t value) diff --git a/frameworks/core/components_ng/pattern/text_field/text_field_pattern.cpp b/frameworks/core/components_ng/pattern/text_field/text_field_pattern.cpp index 5570f67c8b2..46d526e1039 100755 --- a/frameworks/core/components_ng/pattern/text_field/text_field_pattern.cpp +++ b/frameworks/core/components_ng/pattern/text_field/text_field_pattern.cpp @@ -290,6 +290,8 @@ bool TextFieldPattern::OnDirtyLayoutWrapperSwap(const RefPtr& dir } if (IsTextArea()) { CheckScrollable(); + } else { + SetScrollEnable(GreatNotEqual(textRect_.Width(), contentRect_.Width())); } UpdateScrollBarOffset(); caretUpdateType_ = CaretUpdateType::NONE; @@ -352,6 +354,7 @@ bool TextFieldPattern::UpdateCaretPosition() LOGW("Not on focus, cannot update caret"); return true; } + UpdateCaretRectByPosition(textEditingValue_.caretPosition); // text input has higher priority than events such as mouse press if (caretUpdateType_ == CaretUpdateType::INPUT) { UpdateCaretPositionByTextEdit(); @@ -920,9 +923,7 @@ void TextFieldPattern::GetTextRectsInRange( if (tmp.size() != 1) { return; } - bool isInRange = offset.GetX() >= tmp[0].rect_.GetLeft() && offset.GetX() <= tmp[0].rect_.GetRight() && - offset.GetY() >= tmp[0].rect_.GetTop() && offset.GetY() <= tmp[0].rect_.GetBottom(); - if (isInRange) { + if (LastTouchIsInSelectRegion(tmp)) { textBoxes = tmp; UpdateSelectorByPosition(base - 1); } @@ -1317,13 +1318,9 @@ void TextFieldPattern::HandleBlurEvent() caretRect_.Reset(); StopTwinkling(); CloseKeyboard(true); - auto pos = static_cast(textEditingValue_.GetWideText().length()); MarkRedrawOverlay(); - UpdateCaretPositionWithClamp(pos); - textEditingValue_.CursorMoveToPosition(pos); textSelector_.Update(-1); selectionMode_ = SelectionMode::NONE; - caretUpdateType_ = CaretUpdateType::EVENT; auto eventHub = host->GetEventHub(); eventHub->FireOnEditChanged(false); ResetBackgroundColor(); @@ -1355,6 +1352,7 @@ void TextFieldPattern::HandleOnUndoAction() redoOperationRecords_.push_back(value); if (operationRecords_.empty()) { LOGW("No record left, clear"); + FireEventHubOnChange(""); ClearEditingValue(); return; } @@ -1803,7 +1801,7 @@ void TextFieldPattern::InitDragDropEvent() pattern->dragContents_ = { beforeStr, selectedStr, afterStr }; itemInfo.extraInfo = selectedStr; RefPtr unifiedData = UdmfClient::GetInstance()->CreateUnifiedData(); - UdmfClient::GetInstance()->AddTextRecord(unifiedData, selectedStr); + UdmfClient::GetInstance()->AddPlainTextRecord(unifiedData, selectedStr); event->SetData(unifiedData); host->MarkDirtyNode(layoutProperty->GetMaxLinesValue(Infinity()) <= 1 ? PROPERTY_UPDATE_MEASURE_SELF : PROPERTY_UPDATE_MEASURE); @@ -1892,7 +1890,7 @@ void TextFieldPattern::InitDragDropEvent() } auto data = event->GetData(); CHECK_NULL_VOID(data); - std::string str = UdmfClient::GetInstance()->GetSingleTextRecord(data); + std::string str = UdmfClient::GetInstance()->GetSinglePlainTextRecord(data); pattern->needToRequestKeyboardInner_ = true; pattern->dragRecipientStatus_ = DragStatus::NONE; if (pattern->dragStatus_ == DragStatus::NONE) { @@ -2199,13 +2197,22 @@ void TextFieldPattern::OnModifyDone() } HandleCounterBorder(); } - if (paintProperty->GetInputStyleValue(InputStyle::DEFAULT) == InputStyle::INLINE && !inlineFocusState_) { + if (!IsTextArea()) { + isTextInput_ = true; + } + auto inputStyle = paintProperty->GetInputStyleValue(InputStyle::DEFAULT); + if ((!IsSelected() && inputStyle == InputStyle::INLINE) || + ((inputStyle == InputStyle::DEFAULT) && preInputStyle_ != InputStyle::INLINE)) { inlineState_.saveInlineState = false; SaveInlineStates(); } - if (IsSelected() && paintProperty->GetInputStyleValue(InputStyle::DEFAULT) == InputStyle::INLINE) { - ApplyInlineStates(false); + if (IsSelected() && inputStyle == InputStyle::INLINE) { + preInputStyle_ == InputStyle::DEFAULT ? ApplyInlineStates(true) : ApplyInlineStates(false); } + if (preInputStyle_ == InputStyle::INLINE && inputStyle == InputStyle::DEFAULT) { + RestorePreInlineStates(); + } + preInputStyle_ = inputStyle; host->MarkDirtyNode(layoutProperty->GetMaxLinesValue(Infinity()) <= 1 ? PROPERTY_UPDATE_MEASURE_SELF : PROPERTY_UPDATE_MEASURE); } @@ -2382,6 +2389,18 @@ void TextFieldPattern::ProcessOverlay() } selectionMode_ = SelectionMode::SELECT; if (caretUpdateType_ == CaretUpdateType::LONG_PRESSED) { + // When the content length is 1, you need to use the TextBox and pressing coordinates to determine whether it is + // selected + if (textEditingValue_.text.length() == 1) { + std::vector box; + GetTextRectsInRange(0, 1, box); + if (LastTouchIsInSelectRegion(box)) { + UpdateSelection(0, 1); + textEditingValue_.CursorMoveToPosition(1); + CreateHandles(); + return; + } + } if (textEditingValue_.caretPosition == 0 && GetLastTouchOffset().GetX() < textRect_.GetX()) { UpdateSelection(0, 0); CreateSingleHandle(); @@ -3479,8 +3498,7 @@ int32_t TextFieldPattern::GetWordLength(int32_t originCaretPosition, int32_t dir } // directionMove == 0 left, directionMove == 1 right // cannot get word length by current caret position and direction - if ((directionMove == 0 && originCaretPosition == 0) || - (directionMove == 1 && originCaretPosition == textLength)) { + if ((directionMove == 0 && originCaretPosition == 0) || (directionMove == 1 && originCaretPosition == textLength)) { return 0; } int32_t offset = 0; @@ -3553,8 +3571,8 @@ int32_t TextFieldPattern::GetLineEndPosition(int32_t originCaretPosition, bool n int32_t moveLineEndOffset = 0; int32_t strIndex = 0; for (strIndex = originCaretPosition + 1; (textEditingValue_.text[strIndex] != '\n' && strIndex <= textLength) || - (needToCheckLineChanged && !CharLineChanged(strIndex)); - strIndex++) { + (needToCheckLineChanged && !CharLineChanged(strIndex)); + strIndex++) { moveLineEndOffset++; } if (moveLineEndOffset > textLength - originCaretPosition) { @@ -5406,4 +5424,20 @@ void TextFieldPattern::StopEditing() CloseSelectOverlay(); CloseKeyboard(true); } + +bool TextFieldPattern::LastTouchIsInSelectRegion(const std::vector& boxes) +{ + if (boxes.empty()) { + return false; + } + + Offset offset = GetLastTouchOffset() - Offset(textRect_.GetX(), textRect_.GetY()); + for (const auto& box : boxes) { + RectF rect(box.rect_.GetLeft(), box.rect_.GetTop(), box.rect_.GetWidth(), box.rect_.GetHeight()); + if (rect.IsInRegion({ offset.GetX(), offset.GetY() })) { + return true; + } + } + return false; +} } // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/pattern/text_field/text_field_pattern.h b/frameworks/core/components_ng/pattern/text_field/text_field_pattern.h index ce39367379a..c6403058152 100644 --- a/frameworks/core/components_ng/pattern/text_field/text_field_pattern.h +++ b/frameworks/core/components_ng/pattern/text_field/text_field_pattern.h @@ -738,10 +738,10 @@ public: } Offset offset = globalOffset - Offset(textRect_.GetX(), textRect_.GetY()) - Offset(parentGlobalOffset_.GetX(), parentGlobalOffset_.GetY()); - auto position = ConvertTouchOffsetToCaretPosition(offset); - auto selectStart = std::min(textSelector_.GetStart(), textSelector_.GetEnd()); - auto selectEnd = std::max(textSelector_.GetStart(), textSelector_.GetEnd()); - return offset.GetX() >= 0 && (position >= selectStart) && (position < selectEnd); + bool isInRange = offset.GetX() >= textBoxes_[0].rect_.GetLeft() && offset.GetX() <= + textBoxes_[0].rect_.GetRight() && offset.GetY() >= textBoxes_[0].rect_.GetTop() && + offset.GetY() <= textBoxes_[0].rect_.GetBottom(); + return isInRange; } // xts @@ -891,11 +891,6 @@ public: caretUpdateType_ = CaretUpdateType::EVENT; } - void SetTextInputFlag(bool enable) - { - isTextInput_ = enable; - } - bool GetTextInputFlag() const { return isTextInput_; @@ -993,6 +988,7 @@ private: void Delete(int32_t start, int32_t end); bool OnDirtyLayoutWrapperSwap(const RefPtr& dirty, const DirtySwapConfig& config) override; + bool LastTouchIsInSelectRegion(const std::vector& boxes); bool FilterWithRegex( const std::string& filter, const std::string& valueToUpdate, std::string& result, bool needToEscape = false); @@ -1115,6 +1111,7 @@ private: float inlineSingleLineHeight_ = 0.0f; float inlinePadding_ = 0.0f; float previewWidth_ = 0.0f; + InputStyle preInputStyle_ = InputStyle::DEFAULT; uint32_t twinklingInterval_ = 0; int32_t obscureTickCountDown_ = 0; diff --git a/frameworks/core/components_ng/pattern/text_picker/textpicker_column_pattern.cpp b/frameworks/core/components_ng/pattern/text_picker/textpicker_column_pattern.cpp index d5f266b1e4a..02f1259b364 100644 --- a/frameworks/core/components_ng/pattern/text_picker/textpicker_column_pattern.cpp +++ b/frameworks/core/components_ng/pattern/text_picker/textpicker_column_pattern.cpp @@ -541,19 +541,20 @@ void TextPickerColumnPattern::UpdateDisappearTextProperties(const RefPtr& textPickerLayoutProperty) { auto normalOptionSize = pickerTheme->GetOptionStyle(false, false).GetFontSize(); - if (textPickerLayoutProperty->HasDisappearColor()) { - textLayoutProperty->UpdateTextColor(textPickerLayoutProperty->GetDisappearColor().value()); - } + textLayoutProperty->UpdateTextColor(textPickerLayoutProperty->GetDisappearColor().value_or( + pickerTheme->GetOptionStyle(false, false).GetTextColor())); if (textPickerLayoutProperty->HasDisappearFontSize()) { textLayoutProperty->UpdateFontSize(textPickerLayoutProperty->GetDisappearFontSize().value()); } else { textLayoutProperty->UpdateAdaptMaxFontSize(normalOptionSize); - textLayoutProperty->UpdateAdaptMinFontSize( - pickerTheme->GetOptionStyle(false, false).GetAdaptMinFontSize()); - } - if (textPickerLayoutProperty->HasDisappearWeight()) { - textLayoutProperty->UpdateFontWeight(textPickerLayoutProperty->GetDisappearWeight().value()); + textLayoutProperty->UpdateAdaptMinFontSize(pickerTheme->GetOptionStyle(false, false).GetAdaptMinFontSize()); } + textLayoutProperty->UpdateFontWeight(textPickerLayoutProperty->GetDisappearWeight().value_or( + pickerTheme->GetOptionStyle(false, false).GetFontWeight())); + textLayoutProperty->UpdateFontFamily(textPickerLayoutProperty->GetDisappearFontFamily().value_or( + pickerTheme->GetOptionStyle(false, false).GetFontFamilies())); + textLayoutProperty->UpdateItalicFontStyle(textPickerLayoutProperty->GetDisappearFontStyle().value_or( + pickerTheme->GetOptionStyle(false, false).GetFontStyle())); } void TextPickerColumnPattern::UpdateCandidateTextProperties(const RefPtr& pickerTheme, @@ -561,9 +562,8 @@ void TextPickerColumnPattern::UpdateCandidateTextProperties(const RefPtr& textPickerLayoutProperty) { auto focusOptionSize = pickerTheme->GetOptionStyle(false, false).GetFontSize() + FONT_SIZE; - if (textPickerLayoutProperty->HasColor()) { - textLayoutProperty->UpdateTextColor(textPickerLayoutProperty->GetColor().value()); - } + textLayoutProperty->UpdateTextColor(textPickerLayoutProperty->GetColor().value_or( + pickerTheme->GetOptionStyle(false, false).GetTextColor())); if (textPickerLayoutProperty->HasFontSize()) { textLayoutProperty->UpdateFontSize(textPickerLayoutProperty->GetFontSize().value()); } else { @@ -571,9 +571,12 @@ void TextPickerColumnPattern::UpdateCandidateTextProperties(const RefPtrUpdateAdaptMinFontSize( pickerTheme->GetOptionStyle(true, false).GetAdaptMinFontSize() - FOCUS_SIZE); } - if (textPickerLayoutProperty->HasWeight()) { - textLayoutProperty->UpdateFontWeight(textPickerLayoutProperty->GetWeight().value()); - } + textLayoutProperty->UpdateFontWeight(textPickerLayoutProperty->GetWeight().value_or( + pickerTheme->GetOptionStyle(false, false).GetFontWeight())); + textLayoutProperty->UpdateFontFamily(textPickerLayoutProperty->GetFontFamily().value_or( + pickerTheme->GetOptionStyle(false, false).GetFontFamilies())); + textLayoutProperty->UpdateItalicFontStyle(textPickerLayoutProperty->GetFontStyle().value_or( + pickerTheme->GetOptionStyle(false, false).GetFontStyle())); } void TextPickerColumnPattern::UpdateSelectedTextProperties(const RefPtr& pickerTheme, @@ -581,18 +584,20 @@ void TextPickerColumnPattern::UpdateSelectedTextProperties(const RefPtr& textPickerLayoutProperty) { auto selectedOptionSize = pickerTheme->GetOptionStyle(true, false).GetFontSize(); - Color themeSelectedColor = pickerTheme->GetOptionStyle(true, false).GetTextColor(); - Color selectedColor = textPickerLayoutProperty->GetSelectedColor().value_or(themeSelectedColor); - textLayoutProperty->UpdateTextColor(selectedColor); - FontWeight themeFontWeight = pickerTheme->GetOptionStyle(true, false).GetFontWeight(); - FontWeight selectedFontWeight = textPickerLayoutProperty->GetSelectedWeight().value_or(themeFontWeight); - textLayoutProperty->UpdateFontWeight(selectedFontWeight); + textLayoutProperty->UpdateTextColor(textPickerLayoutProperty->GetSelectedColor().value_or( + pickerTheme->GetOptionStyle(true, false).GetTextColor())); if (textPickerLayoutProperty->HasSelectedFontSize()) { textLayoutProperty->UpdateFontSize(textPickerLayoutProperty->GetSelectedFontSize().value()); } else { textLayoutProperty->UpdateAdaptMaxFontSize(selectedOptionSize); textLayoutProperty->UpdateAdaptMinFontSize(pickerTheme->GetOptionStyle(true, false).GetAdaptMinFontSize()); } + textLayoutProperty->UpdateFontWeight(textPickerLayoutProperty->GetSelectedWeight().value_or( + pickerTheme->GetOptionStyle(true, false).GetFontWeight())); + textLayoutProperty->UpdateFontFamily(textPickerLayoutProperty->GetSelectedFontFamily().value_or( + pickerTheme->GetOptionStyle(true, false).GetFontFamilies())); + textLayoutProperty->UpdateItalicFontStyle(textPickerLayoutProperty->GetSelectedFontStyle().value_or( + pickerTheme->GetOptionStyle(true, false).GetFontStyle())); } void TextPickerColumnPattern::AddAnimationTextProperties(uint32_t currentIndex, diff --git a/frameworks/core/components_ng/pattern/text_picker/textpicker_dialog_view.cpp b/frameworks/core/components_ng/pattern/text_picker/textpicker_dialog_view.cpp index 04db42eadf8..a338f4ec92d 100644 --- a/frameworks/core/components_ng/pattern/text_picker/textpicker_dialog_view.cpp +++ b/frameworks/core/components_ng/pattern/text_picker/textpicker_dialog_view.cpp @@ -535,6 +535,10 @@ void TextPickerDialogView::SetTextProperties( properties.disappearTextStyle_.textColor.value_or(disappearStyle.GetTextColor())); ACE_UPDATE_LAYOUT_PROPERTY(TextPickerLayoutProperty, DisappearWeight, properties.disappearTextStyle_.fontWeight.value_or(disappearStyle.GetFontWeight())); + ACE_UPDATE_LAYOUT_PROPERTY(TextPickerLayoutProperty, DisappearFontFamily, + properties.disappearTextStyle_.fontFamily.value_or(disappearStyle.GetFontFamilies())); + ACE_UPDATE_LAYOUT_PROPERTY(TextPickerLayoutProperty, DisappearFontStyle, + properties.disappearTextStyle_.fontStyle.value_or(disappearStyle.GetFontStyle())); if (properties.normalTextStyle_.fontSize.has_value() && properties.normalTextStyle_.fontSize->IsValid()) { ACE_UPDATE_LAYOUT_PROPERTY(TextPickerLayoutProperty, FontSize, properties.normalTextStyle_.fontSize.value()); @@ -545,6 +549,10 @@ void TextPickerDialogView::SetTextProperties( TextPickerLayoutProperty, Color, properties.normalTextStyle_.textColor.value_or(normalStyle.GetTextColor())); ACE_UPDATE_LAYOUT_PROPERTY( TextPickerLayoutProperty, Weight, properties.normalTextStyle_.fontWeight.value_or(normalStyle.GetFontWeight())); + ACE_UPDATE_LAYOUT_PROPERTY(TextPickerLayoutProperty, FontFamily, + properties.normalTextStyle_.fontFamily.value_or(normalStyle.GetFontFamilies())); + ACE_UPDATE_LAYOUT_PROPERTY(TextPickerLayoutProperty, FontStyle, + properties.normalTextStyle_.fontStyle.value_or(normalStyle.GetFontStyle())); if (properties.selectedTextStyle_.fontSize.has_value() && properties.selectedTextStyle_.fontSize->IsValid()) { ACE_UPDATE_LAYOUT_PROPERTY( @@ -556,6 +564,10 @@ void TextPickerDialogView::SetTextProperties( properties.selectedTextStyle_.textColor.value_or(selectedStyle.GetTextColor())); ACE_UPDATE_LAYOUT_PROPERTY(TextPickerLayoutProperty, SelectedWeight, properties.selectedTextStyle_.fontWeight.value_or(selectedStyle.GetFontWeight())); + ACE_UPDATE_LAYOUT_PROPERTY(TextPickerLayoutProperty, SelectedFontFamily, + properties.selectedTextStyle_.fontFamily.value_or(selectedStyle.GetFontFamilies())); + ACE_UPDATE_LAYOUT_PROPERTY(TextPickerLayoutProperty, SelectedFontStyle, + properties.selectedTextStyle_.fontStyle.value_or(selectedStyle.GetFontStyle())); } void TextPickerDialogView::SetDialogChange(const RefPtr& frameNode, DialogTextEvent&& onChange) diff --git a/frameworks/core/components_ng/pattern/text_picker/textpicker_layout_property.h b/frameworks/core/components_ng/pattern/text_picker/textpicker_layout_property.h index 429341e42de..be91ea96888 100644 --- a/frameworks/core/components_ng/pattern/text_picker/textpicker_layout_property.h +++ b/frameworks/core/components_ng/pattern/text_picker/textpicker_layout_property.h @@ -138,11 +138,19 @@ public: DisappearTextStyle, TextColor, DisappearColor, Color, PROPERTY_UPDATE_MEASURE_SELF); ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( DisappearTextStyle, FontWeight, DisappearWeight, FontWeight, PROPERTY_UPDATE_MEASURE); + ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( + DisappearTextStyle, FontFamily, DisappearFontFamily, std::vector, PROPERTY_UPDATE_MEASURE); + ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( + DisappearTextStyle, ItalicFontStyle, DisappearFontStyle, Ace::FontStyle, PROPERTY_UPDATE_MEASURE); ACE_DEFINE_PROPERTY_GROUP(TextStyle, FontStyle); ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM(TextStyle, FontSize, FontSize, Dimension, PROPERTY_UPDATE_MEASURE); ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM(TextStyle, TextColor, Color, Color, PROPERTY_UPDATE_MEASURE_SELF); ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM(TextStyle, FontWeight, Weight, FontWeight, PROPERTY_UPDATE_MEASURE); + ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( + TextStyle, FontFamily, FontFamily, std::vector, PROPERTY_UPDATE_MEASURE); + ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( + TextStyle, ItalicFontStyle, FontStyle, Ace::FontStyle, PROPERTY_UPDATE_MEASURE); ACE_DEFINE_PROPERTY_GROUP(SelectedTextStyle, FontStyle); ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( @@ -151,6 +159,10 @@ public: SelectedTextStyle, TextColor, SelectedColor, Color, PROPERTY_UPDATE_MEASURE_SELF); ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( SelectedTextStyle, FontWeight, SelectedWeight, FontWeight, PROPERTY_UPDATE_MEASURE); + ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( + SelectedTextStyle, FontFamily, SelectedFontFamily, std::vector, PROPERTY_UPDATE_MEASURE); + ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( + SelectedTextStyle, ItalicFontStyle, SelectedFontStyle, Ace::FontStyle, PROPERTY_UPDATE_MEASURE); private: ACE_DISALLOW_COPY_AND_MOVE(TextPickerLayoutProperty); }; diff --git a/frameworks/core/components_ng/pattern/text_picker/textpicker_model_ng.cpp b/frameworks/core/components_ng/pattern/text_picker/textpicker_model_ng.cpp index 7cc27811760..8fd5584d3ef 100644 --- a/frameworks/core/components_ng/pattern/text_picker/textpicker_model_ng.cpp +++ b/frameworks/core/components_ng/pattern/text_picker/textpicker_model_ng.cpp @@ -69,16 +69,22 @@ void TextPickerModelNG::SetDefaultAttributes(const RefPtr& pickerTh ACE_UPDATE_LAYOUT_PROPERTY(TextPickerLayoutProperty, SelectedFontSize, selectedStyle.GetFontSize()); ACE_UPDATE_LAYOUT_PROPERTY(TextPickerLayoutProperty, SelectedColor, selectedStyle.GetTextColor()); ACE_UPDATE_LAYOUT_PROPERTY(TextPickerLayoutProperty, SelectedWeight, selectedStyle.GetFontWeight()); + ACE_UPDATE_LAYOUT_PROPERTY(TextPickerLayoutProperty, SelectedFontFamily, selectedStyle.GetFontFamilies()); + ACE_UPDATE_LAYOUT_PROPERTY(TextPickerLayoutProperty, SelectedFontStyle, selectedStyle.GetFontStyle()); auto disappearStyle = pickerTheme->GetDisappearOptionStyle(); ACE_UPDATE_LAYOUT_PROPERTY(TextPickerLayoutProperty, DisappearFontSize, disappearStyle.GetFontSize()); ACE_UPDATE_LAYOUT_PROPERTY(TextPickerLayoutProperty, DisappearColor, disappearStyle.GetTextColor()); ACE_UPDATE_LAYOUT_PROPERTY(TextPickerLayoutProperty, DisappearWeight, disappearStyle.GetFontWeight()); + ACE_UPDATE_LAYOUT_PROPERTY(TextPickerLayoutProperty, DisappearFontFamily, disappearStyle.GetFontFamilies()); + ACE_UPDATE_LAYOUT_PROPERTY(TextPickerLayoutProperty, DisappearFontStyle, disappearStyle.GetFontStyle()); auto normalStyle = pickerTheme->GetOptionStyle(false, false); ACE_UPDATE_LAYOUT_PROPERTY(TextPickerLayoutProperty, FontSize, normalStyle.GetFontSize()); ACE_UPDATE_LAYOUT_PROPERTY(TextPickerLayoutProperty, Color, normalStyle.GetTextColor()); ACE_UPDATE_LAYOUT_PROPERTY(TextPickerLayoutProperty, Weight, normalStyle.GetFontWeight()); + ACE_UPDATE_LAYOUT_PROPERTY(TextPickerLayoutProperty, FontFamily, normalStyle.GetFontFamilies()); + ACE_UPDATE_LAYOUT_PROPERTY(TextPickerLayoutProperty, FontStyle, normalStyle.GetFontStyle()); ACE_UPDATE_LAYOUT_PROPERTY(TextPickerLayoutProperty, CanLoop, true); } @@ -207,6 +213,10 @@ void TextPickerModelNG::SetDisappearTextStyle(const RefPtr& pickerT TextPickerLayoutProperty, DisappearColor, value.textColor.value_or(disappearStyle.GetTextColor())); ACE_UPDATE_LAYOUT_PROPERTY( TextPickerLayoutProperty, DisappearWeight, value.fontWeight.value_or(disappearStyle.GetFontWeight())); + ACE_UPDATE_LAYOUT_PROPERTY( + TextPickerLayoutProperty, DisappearFontFamily, value.fontFamily.value_or(disappearStyle.GetFontFamilies())); + ACE_UPDATE_LAYOUT_PROPERTY( + TextPickerLayoutProperty, DisappearFontStyle, value.fontStyle.value_or(disappearStyle.GetFontStyle())); } void TextPickerModelNG::SetNormalTextStyle(const RefPtr& pickerTheme, const NG::PickerTextStyle& value) @@ -222,6 +232,10 @@ void TextPickerModelNG::SetNormalTextStyle(const RefPtr& pickerThem TextPickerLayoutProperty, Color, value.textColor.value_or(normalStyle.GetTextColor())); ACE_UPDATE_LAYOUT_PROPERTY( TextPickerLayoutProperty, Weight, value.fontWeight.value_or(normalStyle.GetFontWeight())); + ACE_UPDATE_LAYOUT_PROPERTY( + TextPickerLayoutProperty, FontFamily, value.fontFamily.value_or(normalStyle.GetFontFamilies())); + ACE_UPDATE_LAYOUT_PROPERTY( + TextPickerLayoutProperty, FontStyle, value.fontStyle.value_or(normalStyle.GetFontStyle())); } void TextPickerModelNG::SetSelectedTextStyle(const RefPtr& pickerTheme, const NG::PickerTextStyle& value) @@ -237,6 +251,10 @@ void TextPickerModelNG::SetSelectedTextStyle(const RefPtr& pickerTh TextPickerLayoutProperty, SelectedColor, value.textColor.value_or(selectedStyle.GetTextColor())); ACE_UPDATE_LAYOUT_PROPERTY( TextPickerLayoutProperty, SelectedWeight, value.fontWeight.value_or(selectedStyle.GetFontWeight())); + ACE_UPDATE_LAYOUT_PROPERTY( + TextPickerLayoutProperty, SelectedFontFamily, value.fontFamily.value_or(selectedStyle.GetFontFamilies())); + ACE_UPDATE_LAYOUT_PROPERTY( + TextPickerLayoutProperty, SelectedFontStyle, value.fontStyle.value_or(selectedStyle.GetFontStyle())); } void TextPickerModelNG::SetOnCascadeChange(TextCascadeChangeEvent&& onChange) diff --git a/frameworks/core/components_ng/pattern/text_picker/textpicker_pattern.cpp b/frameworks/core/components_ng/pattern/text_picker/textpicker_pattern.cpp index df1779a0928..45534201d11 100644 --- a/frameworks/core/components_ng/pattern/text_picker/textpicker_pattern.cpp +++ b/frameworks/core/components_ng/pattern/text_picker/textpicker_pattern.cpp @@ -46,6 +46,7 @@ void TextPickerPattern::OnAttachToFrameNode() auto host = GetHost(); CHECK_NULL_VOID(host); host->GetRenderContext()->SetClipToFrame(true); + host->GetRenderContext()->UpdateClipEdge(true); } bool TextPickerPattern::OnDirtyLayoutWrapperSwap(const RefPtr& dirty, const DirtySwapConfig& config) diff --git a/frameworks/core/components_ng/pattern/time_picker/timepicker_column_pattern.cpp b/frameworks/core/components_ng/pattern/time_picker/timepicker_column_pattern.cpp index 4e412bd4525..2c7f7c2290e 100644 --- a/frameworks/core/components_ng/pattern/time_picker/timepicker_column_pattern.cpp +++ b/frameworks/core/components_ng/pattern/time_picker/timepicker_column_pattern.cpp @@ -49,7 +49,7 @@ constexpr int32_t HOVER_ANIMATION_DURATION = 250; constexpr int32_t PRESS_ANIMATION_DURATION = 100; constexpr int32_t CLICK_ANIMATION_DURATION = 300; -const std::string MEASURE_SIZE_STRING = "TEST"; +const char* MEASURE_SIZE_STRING = "TEST"; } // namespace void TimePickerColumnPattern::OnAttachToFrameNode() @@ -85,7 +85,7 @@ void TimePickerColumnPattern::OnModifyDone() InitOnKeyEvent(focusHub); InitMouseAndPressEvent(); SetAccessibilityAction(); - if (optionProperties_.size() <= 0) { + if (optionProperties_.empty()) { auto midIndex = showCount / 2; auto host = GetHost(); CHECK_NULL_VOID(host); @@ -99,15 +99,12 @@ void TimePickerColumnPattern::OnModifyDone() if (childIndex == midIndex) { // selected auto selectedOptionSize = theme->GetOptionStyle(true, false).GetFontSize(); measureContext.fontSize = selectedOptionSize; - measureContext.fontFamily = ""; } else if (childIndex % midIndex == 1 && (childIndex != 0 || childIndex != (showCount - 1))) { auto focusOptionSize = theme->GetOptionStyle(false, false).GetFontSize() + FONT_SIZE; measureContext.fontSize = focusOptionSize; - measureContext.fontFamily = ""; } else { auto normalOptionSize = theme->GetOptionStyle(false, false).GetFontSize(); measureContext.fontSize = normalOptionSize; - measureContext.fontFamily = ""; } if (childIndex == showCount / MIDDLE_CHILD_INDEX) { prop.height = dividerSpacing_; @@ -325,18 +322,20 @@ void TimePickerColumnPattern::UpdateDisappearTextProperties(const RefPtr& timePickerLayoutProperty) { auto normalOptionSize = pickerTheme->GetOptionStyle(false, false).GetFontSize(); - if (timePickerLayoutProperty->HasDisappearColor()) { - textLayoutProperty->UpdateTextColor(timePickerLayoutProperty->GetDisappearColor().value()); - } + textLayoutProperty->UpdateTextColor(timePickerLayoutProperty->GetDisappearColor().value_or( + pickerTheme->GetOptionStyle(false, false).GetTextColor())); if (timePickerLayoutProperty->HasDisappearFontSize()) { textLayoutProperty->UpdateFontSize(timePickerLayoutProperty->GetDisappearFontSize().value()); } else { textLayoutProperty->UpdateAdaptMaxFontSize(normalOptionSize); textLayoutProperty->UpdateAdaptMinFontSize(pickerTheme->GetOptionStyle(false, false).GetAdaptMinFontSize()); } - if (timePickerLayoutProperty->HasDisappearWeight()) { - textLayoutProperty->UpdateFontWeight(timePickerLayoutProperty->GetDisappearWeight().value()); - } + textLayoutProperty->UpdateFontWeight(timePickerLayoutProperty->GetDisappearWeight().value_or( + pickerTheme->GetOptionStyle(false, false).GetFontWeight())); + textLayoutProperty->UpdateFontFamily(timePickerLayoutProperty->GetDisappearFontFamily().value_or( + pickerTheme->GetOptionStyle(false, false).GetFontFamilies())); + textLayoutProperty->UpdateItalicFontStyle(timePickerLayoutProperty->GetDisappearFontStyle().value_or( + pickerTheme->GetOptionStyle(false, false).GetFontStyle())); } void TimePickerColumnPattern::UpdateCandidateTextProperties(const RefPtr& pickerTheme, @@ -344,9 +343,8 @@ void TimePickerColumnPattern::UpdateCandidateTextProperties(const RefPtr& timePickerLayoutProperty) { auto focusOptionSize = pickerTheme->GetOptionStyle(false, false).GetFontSize() + FONT_SIZE; - if (timePickerLayoutProperty->HasColor()) { - textLayoutProperty->UpdateTextColor(timePickerLayoutProperty->GetColor().value()); - } + textLayoutProperty->UpdateTextColor(timePickerLayoutProperty->GetColor().value_or( + pickerTheme->GetOptionStyle(false, false).GetTextColor())); if (timePickerLayoutProperty->HasFontSize()) { textLayoutProperty->UpdateFontSize(timePickerLayoutProperty->GetFontSize().value()); } else { @@ -354,9 +352,12 @@ void TimePickerColumnPattern::UpdateCandidateTextProperties(const RefPtrUpdateAdaptMinFontSize( pickerTheme->GetOptionStyle(true, false).GetAdaptMinFontSize() - FOCUS_SIZE); } - if (timePickerLayoutProperty->HasWeight()) { - textLayoutProperty->UpdateFontWeight(timePickerLayoutProperty->GetWeight().value()); - } + textLayoutProperty->UpdateFontWeight(timePickerLayoutProperty->GetWeight().value_or( + pickerTheme->GetOptionStyle(false, false).GetFontWeight())); + textLayoutProperty->UpdateFontFamily(timePickerLayoutProperty->GetFontFamily().value_or( + pickerTheme->GetOptionStyle(false, false).GetFontFamilies())); + textLayoutProperty->UpdateItalicFontStyle(timePickerLayoutProperty->GetFontStyle().value_or( + pickerTheme->GetOptionStyle(false, false).GetFontStyle())); } void TimePickerColumnPattern::UpdateSelectedTextProperties(const RefPtr& pickerTheme, @@ -364,18 +365,20 @@ void TimePickerColumnPattern::UpdateSelectedTextProperties(const RefPtr& timePickerLayoutProperty) { auto selectedOptionSize = pickerTheme->GetOptionStyle(true, false).GetFontSize(); - Color themeSelectedColor = pickerTheme->GetOptionStyle(true, false).GetTextColor(); - Color selectedColor = timePickerLayoutProperty->GetSelectedColor().value_or(themeSelectedColor); - textLayoutProperty->UpdateTextColor(selectedColor); - FontWeight themeFontWeight = pickerTheme->GetOptionStyle(true, false).GetFontWeight(); - FontWeight selectedFontWeight = timePickerLayoutProperty->GetSelectedWeight().value_or(themeFontWeight); - textLayoutProperty->UpdateFontWeight(selectedFontWeight); + textLayoutProperty->UpdateTextColor(timePickerLayoutProperty->GetSelectedColor().value_or( + pickerTheme->GetOptionStyle(true, false).GetTextColor())); if (timePickerLayoutProperty->HasSelectedFontSize()) { textLayoutProperty->UpdateFontSize(timePickerLayoutProperty->GetSelectedFontSize().value()); } else { textLayoutProperty->UpdateAdaptMaxFontSize(selectedOptionSize); textLayoutProperty->UpdateAdaptMinFontSize(pickerTheme->GetOptionStyle(true, false).GetAdaptMinFontSize()); } + textLayoutProperty->UpdateFontWeight(timePickerLayoutProperty->GetSelectedWeight().value_or( + pickerTheme->GetOptionStyle(true, false).GetFontWeight())); + textLayoutProperty->UpdateFontFamily(timePickerLayoutProperty->GetSelectedFontFamily().value_or( + pickerTheme->GetOptionStyle(true, false).GetFontFamilies())); + textLayoutProperty->UpdateItalicFontStyle(timePickerLayoutProperty->GetSelectedFontStyle().value_or( + pickerTheme->GetOptionStyle(true, false).GetFontStyle())); } void TimePickerColumnPattern::ChangeAmPmTextStyle(uint32_t index, uint32_t showOptionCount, diff --git a/frameworks/core/components_ng/pattern/time_picker/timepicker_dialog_view.cpp b/frameworks/core/components_ng/pattern/time_picker/timepicker_dialog_view.cpp index e7751e29a03..225218053c0 100644 --- a/frameworks/core/components_ng/pattern/time_picker/timepicker_dialog_view.cpp +++ b/frameworks/core/components_ng/pattern/time_picker/timepicker_dialog_view.cpp @@ -420,6 +420,10 @@ void TimePickerDialogView::SetTextProperties( properties.disappearTextStyle_.textColor.value_or(disappearStyle.GetTextColor())); ACE_UPDATE_LAYOUT_PROPERTY(TimePickerLayoutProperty, DisappearWeight, properties.disappearTextStyle_.fontWeight.value_or(disappearStyle.GetFontWeight())); + ACE_UPDATE_LAYOUT_PROPERTY(TimePickerLayoutProperty, DisappearFontFamily, + properties.disappearTextStyle_.fontFamily.value_or(disappearStyle.GetFontFamilies())); + ACE_UPDATE_LAYOUT_PROPERTY(TimePickerLayoutProperty, DisappearFontStyle, + properties.disappearTextStyle_.fontStyle.value_or(disappearStyle.GetFontStyle())); if (properties.normalTextStyle_.fontSize.has_value() && properties.normalTextStyle_.fontSize->IsValid()) { ACE_UPDATE_LAYOUT_PROPERTY(TimePickerLayoutProperty, FontSize, properties.normalTextStyle_.fontSize.value()); @@ -430,6 +434,10 @@ void TimePickerDialogView::SetTextProperties( TimePickerLayoutProperty, Color, properties.normalTextStyle_.textColor.value_or(normalStyle.GetTextColor())); ACE_UPDATE_LAYOUT_PROPERTY( TimePickerLayoutProperty, Weight, properties.normalTextStyle_.fontWeight.value_or(normalStyle.GetFontWeight())); + ACE_UPDATE_LAYOUT_PROPERTY(TimePickerLayoutProperty, FontFamily, + properties.normalTextStyle_.fontFamily.value_or(normalStyle.GetFontFamilies())); + ACE_UPDATE_LAYOUT_PROPERTY(TimePickerLayoutProperty, FontStyle, + properties.normalTextStyle_.fontStyle.value_or(normalStyle.GetFontStyle())); if (properties.selectedTextStyle_.fontSize.has_value() && properties.selectedTextStyle_.fontSize->IsValid()) { ACE_UPDATE_LAYOUT_PROPERTY( @@ -441,5 +449,9 @@ void TimePickerDialogView::SetTextProperties( properties.selectedTextStyle_.textColor.value_or(selectedStyle.GetTextColor())); ACE_UPDATE_LAYOUT_PROPERTY(TimePickerLayoutProperty, SelectedWeight, properties.selectedTextStyle_.fontWeight.value_or(selectedStyle.GetFontWeight())); + ACE_UPDATE_LAYOUT_PROPERTY(TimePickerLayoutProperty, SelectedFontFamily, + properties.selectedTextStyle_.fontFamily.value_or(selectedStyle.GetFontFamilies())); + ACE_UPDATE_LAYOUT_PROPERTY(TimePickerLayoutProperty, SelectedFontStyle, + properties.selectedTextStyle_.fontStyle.value_or(selectedStyle.GetFontStyle())); } } // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/pattern/time_picker/timepicker_event_hub.h b/frameworks/core/components_ng/pattern/time_picker/timepicker_event_hub.h index a5bf6a2ad2d..19b96f2ced5 100644 --- a/frameworks/core/components_ng/pattern/time_picker/timepicker_event_hub.h +++ b/frameworks/core/components_ng/pattern/time_picker/timepicker_event_hub.h @@ -25,6 +25,7 @@ using TimeChangeEvent = std::function; using DialogEvent = std::function; using DialogCancelEvent = std::function; using DialogGestureEvent = std::function; +using TimeChangeEventForDatePicker = std::function; class TimePickerEventHub : public EventHub { DECLARE_ACE_TYPE(TimePickerEventHub, EventHub) @@ -38,6 +39,11 @@ public: changeEvent_ = std::move(changeEvent); } + void SetOnChangeForDatePicker(TimeChangeEventForDatePicker&& changeEvent) + { + changeEventForDatePicker_ = std::move(changeEvent); + } + void FireChangeEvent(const BaseEventInfo* info) const { if (selectedTimeChangeEvent_) { @@ -46,6 +52,9 @@ public: if (changeEvent_) { changeEvent_(info); } + if (changeEventForDatePicker_) { + changeEventForDatePicker_(); + } } void SetDialogChange(DialogEvent&& onChange) @@ -82,6 +91,7 @@ private: DialogEvent DialogChangeEvent_; DialogEvent DialogAcceptEvent_; TimeChangeEvent selectedTimeChangeEvent_; + TimeChangeEventForDatePicker changeEventForDatePicker_; ACE_DISALLOW_COPY_AND_MOVE(TimePickerEventHub); }; diff --git a/frameworks/core/components_ng/pattern/time_picker/timepicker_layout_property.h b/frameworks/core/components_ng/pattern/time_picker/timepicker_layout_property.h index 733f10973f0..f97e636ac2c 100644 --- a/frameworks/core/components_ng/pattern/time_picker/timepicker_layout_property.h +++ b/frameworks/core/components_ng/pattern/time_picker/timepicker_layout_property.h @@ -16,6 +16,8 @@ #ifndef FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_NG_PATTERN_TIME_PICKER_TIME_PICKER_LAYOUT_PROPERTY_H #define FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_NG_PATTERN_TIME_PICKER_TIME_PICKER_LAYOUT_PROPERTY_H +#include +#include #include "base/geometry/dimension.h" #include "core/components/common/layout/constants.h" #include "core/components_ng/layout/layout_property.h" @@ -88,11 +90,19 @@ public: DisappearTextStyle, TextColor, DisappearColor, Color, PROPERTY_UPDATE_MEASURE_SELF); ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( DisappearTextStyle, FontWeight, DisappearWeight, FontWeight, PROPERTY_UPDATE_MEASURE); + ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( + DisappearTextStyle, FontFamily, DisappearFontFamily, std::vector, PROPERTY_UPDATE_MEASURE); + ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( + DisappearTextStyle, ItalicFontStyle, DisappearFontStyle, Ace::FontStyle, PROPERTY_UPDATE_MEASURE); ACE_DEFINE_PROPERTY_GROUP(TextStyle, FontStyle); ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM(TextStyle, FontSize, FontSize, Dimension, PROPERTY_UPDATE_MEASURE); ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM(TextStyle, TextColor, Color, Color, PROPERTY_UPDATE_MEASURE_SELF); ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM(TextStyle, FontWeight, Weight, FontWeight, PROPERTY_UPDATE_MEASURE); + ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( + TextStyle, FontFamily, FontFamily, std::vector, PROPERTY_UPDATE_MEASURE); + ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( + TextStyle, ItalicFontStyle, FontStyle, Ace::FontStyle, PROPERTY_UPDATE_MEASURE); ACE_DEFINE_PROPERTY_GROUP(SelectedTextStyle, FontStyle); ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( @@ -101,6 +111,10 @@ public: SelectedTextStyle, TextColor, SelectedColor, Color, PROPERTY_UPDATE_MEASURE_SELF); ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( SelectedTextStyle, FontWeight, SelectedWeight, FontWeight, PROPERTY_UPDATE_MEASURE); + ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( + SelectedTextStyle, FontFamily, SelectedFontFamily, std::vector, PROPERTY_UPDATE_MEASURE); + ACE_DEFINE_PROPERTY_ITEM_WITH_GROUP_ITEM( + SelectedTextStyle, ItalicFontStyle, SelectedFontStyle, Ace::FontStyle, PROPERTY_UPDATE_MEASURE); private: ACE_DISALLOW_COPY_AND_MOVE(TimePickerLayoutProperty); }; diff --git a/frameworks/core/components_ng/pattern/time_picker/timepicker_model_ng.cpp b/frameworks/core/components_ng/pattern/time_picker/timepicker_model_ng.cpp index 764143231c3..8f3daaafcbd 100644 --- a/frameworks/core/components_ng/pattern/time_picker/timepicker_model_ng.cpp +++ b/frameworks/core/components_ng/pattern/time_picker/timepicker_model_ng.cpp @@ -152,6 +152,10 @@ void TimePickerModelNG::SetDisappearTextStyle(const RefPtr& theme, TimePickerLayoutProperty, DisappearColor, value.textColor.value_or(disappearStyle.GetTextColor())); ACE_UPDATE_LAYOUT_PROPERTY( TimePickerLayoutProperty, DisappearWeight, value.fontWeight.value_or(disappearStyle.GetFontWeight())); + ACE_UPDATE_LAYOUT_PROPERTY( + TimePickerLayoutProperty, DisappearFontFamily, value.fontFamily.value_or(disappearStyle.GetFontFamilies())); + ACE_UPDATE_LAYOUT_PROPERTY( + TimePickerLayoutProperty, DisappearFontStyle, value.fontStyle.value_or(disappearStyle.GetFontStyle())); } void TimePickerModelNG::SetNormalTextStyle(const RefPtr& theme, const PickerTextStyle& value) @@ -166,6 +170,10 @@ void TimePickerModelNG::SetNormalTextStyle(const RefPtr& theme, con ACE_UPDATE_LAYOUT_PROPERTY(TimePickerLayoutProperty, Color, value.textColor.value_or(normalStyle.GetTextColor())); ACE_UPDATE_LAYOUT_PROPERTY( TimePickerLayoutProperty, Weight, value.fontWeight.value_or(normalStyle.GetFontWeight())); + ACE_UPDATE_LAYOUT_PROPERTY( + TimePickerLayoutProperty, FontFamily, value.fontFamily.value_or(normalStyle.GetFontFamilies())); + ACE_UPDATE_LAYOUT_PROPERTY( + TimePickerLayoutProperty, FontStyle, value.fontStyle.value_or(normalStyle.GetFontStyle())); } void TimePickerModelNG::SetSelectedTextStyle(const RefPtr& theme, const PickerTextStyle& value) @@ -181,6 +189,10 @@ void TimePickerModelNG::SetSelectedTextStyle(const RefPtr& theme, c TimePickerLayoutProperty, SelectedColor, value.textColor.value_or(selectedStyle.GetTextColor())); ACE_UPDATE_LAYOUT_PROPERTY( TimePickerLayoutProperty, SelectedWeight, value.fontWeight.value_or(selectedStyle.GetFontWeight())); + ACE_UPDATE_LAYOUT_PROPERTY( + TimePickerLayoutProperty, SelectedFontFamily, value.fontFamily.value_or(selectedStyle.GetFontFamilies())); + ACE_UPDATE_LAYOUT_PROPERTY( + TimePickerLayoutProperty, SelectedFontStyle, value.fontStyle.value_or(selectedStyle.GetFontStyle())); } void TimePickerModelNG::SetBackgroundColor(const Color& color) diff --git a/frameworks/core/components_ng/pattern/time_picker/timepicker_row_pattern.cpp b/frameworks/core/components_ng/pattern/time_picker/timepicker_row_pattern.cpp index 9e2afb4df2e..f40f29d1c4e 100644 --- a/frameworks/core/components_ng/pattern/time_picker/timepicker_row_pattern.cpp +++ b/frameworks/core/components_ng/pattern/time_picker/timepicker_row_pattern.cpp @@ -44,6 +44,7 @@ void TimePickerRowPattern::OnAttachToFrameNode() auto host = GetHost(); CHECK_NULL_VOID(host); host->GetRenderContext()->SetClipToFrame(true); + host->GetRenderContext()->UpdateClipEdge(true); } bool TimePickerRowPattern::OnDirtyLayoutWrapperSwap(const RefPtr& dirty, const DirtySwapConfig& config) diff --git a/frameworks/core/components_ng/pattern/toast/toast_pattern.cpp b/frameworks/core/components_ng/pattern/toast/toast_pattern.cpp index bf1c8af142e..4b26ea3fc99 100644 --- a/frameworks/core/components_ng/pattern/toast/toast_pattern.cpp +++ b/frameworks/core/components_ng/pattern/toast/toast_pattern.cpp @@ -16,6 +16,7 @@ #include "core/components_ng/pattern/toast/toast_pattern.h" #include "base/utils/utils.h" +#include "core/components/common/layout/grid_system_manager.h" #include "core/components_ng/layout/layout_wrapper.h" #include "core/pipeline/pipeline_base.h" #include "core/pipeline_ng/pipeline_context.h" @@ -28,9 +29,8 @@ constexpr int32_t API_VERSION_9 = 9; bool ToastPattern::OnDirtyLayoutWrapperSwap(const RefPtr& dirty, const DirtySwapConfig& changeConfig) { CHECK_NULL_RETURN(dirty, false); - auto toastProp = DynamicCast(dirty->GetLayoutProperty()); - CHECK_NULL_RETURN(toastProp, false); - auto toastBottom = toastProp->GetBottomValue(Dimension()).ConvertToPx(); + + auto toastBottom = GetBottomValue(dirty); // todo get parent width and height auto context = PipelineContext::GetCurrentContext(); auto rootHeight = context->GetRootHeight(); @@ -40,7 +40,7 @@ bool ToastPattern::OnDirtyLayoutWrapperSwap(const RefPtr& dirty, auto toastNode = dirty->GetHostNode(); auto toastContext = toastNode->GetRenderContext(); CHECK_NULL_RETURN(toastContext, false); - auto pipeline = PipelineContext::GetCurrentContext(); + OffsetT offset { Dimension((rootWidth - text->GetGeometryNode()->GetMarginFrameSize().Width()) / 2.0f), {} }; if (context->GetMinPlatformVersion() > API_VERSION_9) { @@ -50,8 +50,72 @@ bool ToastPattern::OnDirtyLayoutWrapperSwap(const RefPtr& dirty, } else { offset.SetY(Dimension { rootHeight - toastBottom }); } + LOGD("Toast bottom value: [%{public}f], offsetX [%{public}s] offsetY [%{public}s]", toastBottom, + offset.GetX().ToString().c_str(), offset.GetY().ToString().c_str()); toastContext->UpdateOffset(offset); return true; } + +double ToastPattern::GetBottomValue(const RefPtr& layoutWrapper) +{ + auto pipeline = PipelineBase::GetCurrentContext(); + CHECK_NULL_RETURN(pipeline, 0.0); + auto rootHeight = Dimension(pipeline->GetRootHeight()); + auto toastTheme = pipeline->GetTheme(); + CHECK_NULL_RETURN(toastTheme, 0.0); + + auto toastProp = DynamicCast(layoutWrapper->GetLayoutProperty()); + CHECK_NULL_RETURN(toastProp, 0.0); + auto toastBottom = toastProp->GetBottomValue(toastTheme->GetBottom()); + if (toastBottom.Unit() == DimensionUnit::PERCENT) { + toastBottom = rootHeight * toastBottom.Value(); + } + return GreatOrEqual(toastBottom.ConvertToPx(), 0.0) ? toastBottom.ConvertToPx() + : toastTheme->GetBottom().ConvertToPx(); +} + +void ToastPattern::BeforeCreateLayoutWrapper() +{ + auto toastNode = GetHost(); + CHECK_NULL_VOID(toastNode); + UpdateToastSize(toastNode); + + auto textNode = DynamicCast(toastNode->GetFirstChild()); + CHECK_NULL_VOID(textNode); + UpdateTextSizeConstraint(textNode); +} + +void ToastPattern::UpdateToastSize(const RefPtr& toast) +{ + CHECK_NULL_VOID(toast); + auto toastProperty = toast->GetLayoutProperty(); + CHECK_NULL_VOID(toastProperty); + auto context = PipelineBase::GetCurrentContext(); + CHECK_NULL_VOID(context); + auto rootWidth = Dimension(context->GetRootWidth()); + toastProperty->UpdateUserDefinedIdealSize(CalcSize(NG::CalcLength(rootWidth), std::nullopt)); +} + +void ToastPattern::UpdateTextSizeConstraint(const RefPtr& text) +{ + CHECK_NULL_VOID(text); + auto context = PipelineBase::GetCurrentContext(); + CHECK_NULL_VOID(context); + auto gridColumnInfo = GridSystemManager::GetInstance().GetInfoByType(GridColumnType::TOAST); + auto parent = gridColumnInfo->GetParent(); + if (parent) { + parent->BuildColumnWidth(context->GetRootWidth()); + } + auto maxWidth = Dimension(gridColumnInfo->GetMaxWidth()); + auto textLayoutProperty = text->GetLayoutProperty(); + CHECK_NULL_VOID(textLayoutProperty); + textLayoutProperty->UpdateCalcMaxSize(CalcSize(NG::CalcLength(maxWidth), std::nullopt)); + + auto toastTheme = context->GetTheme(); + CHECK_NULL_VOID(toastTheme); + auto minWidth = Dimension(toastTheme->GetMinWidth().ConvertToPx()); + auto minHeight = Dimension(toastTheme->GetMinHeight().ConvertToPx()); + textLayoutProperty->UpdateCalcMinSize(CalcSize(NG::CalcLength(minWidth), NG::CalcLength(minHeight))); +} } // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/pattern/toast/toast_pattern.h b/frameworks/core/components_ng/pattern/toast/toast_pattern.h index 75cef3006c1..0c85f3ae23d 100644 --- a/frameworks/core/components_ng/pattern/toast/toast_pattern.h +++ b/frameworks/core/components_ng/pattern/toast/toast_pattern.h @@ -54,6 +54,12 @@ public: bool OnDirtyLayoutWrapperSwap(const RefPtr& dirty, const DirtySwapConfig& changeConfig) override; private: + void BeforeCreateLayoutWrapper() override; + void UpdateToastSize(const RefPtr& toast); + void UpdateTextSizeConstraint(const RefPtr& text); + + double GetBottomValue(const RefPtr& layoutWrapper); + ACE_DISALLOW_COPY_AND_MOVE(ToastPattern); }; } // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/pattern/toast/toast_view.cpp b/frameworks/core/components_ng/pattern/toast/toast_view.cpp index e9b914dfb32..ca0f316ef30 100644 --- a/frameworks/core/components_ng/pattern/toast/toast_view.cpp +++ b/frameworks/core/components_ng/pattern/toast/toast_view.cpp @@ -16,13 +16,10 @@ #include "core/components_ng/pattern/toast/toast_view.h" #include "base/geometry/dimension.h" -#include "base/geometry/ng/offset_t.h" #include "base/memory/referenced.h" #include "base/utils/utils.h" -#include "core/components/common/layout/grid_system_manager.h" #include "core/components/common/properties/shadow_config.h" #include "core/components/toast/toast_theme.h" -#include "core/components_ng/pattern/linear_layout/linear_layout_pattern.h" #include "core/components_ng/pattern/text/text_layout_property.h" #include "core/components_ng/pattern/text/text_pattern.h" #include "core/components_ng/pattern/toast/toast_layout_property.h" @@ -63,8 +60,6 @@ RefPtr ToastView::CreateToastNode(const std::string& message, const s CHECK_NULL_RETURN(toastNode, nullptr); auto toastProperty = toastNode->GetLayoutProperty(); CHECK_NULL_RETURN(toastProperty, nullptr); - auto toastContext = toastNode->GetRenderContext(); - CHECK_NULL_RETURN(toastContext, nullptr); auto toastAccessibilityProperty = toastNode->GetAccessibilityProperty(); CHECK_NULL_RETURN(toastAccessibilityProperty, nullptr); @@ -75,17 +70,6 @@ RefPtr ToastView::CreateToastNode(const std::string& message, const s auto textLayoutProperty = textNode->GetLayoutProperty(); CHECK_NULL_RETURN(textLayoutProperty, nullptr); - // update toast props - auto rootHeight = Dimension(context->GetRootHeight()); - auto rootWidth = Dimension(context->GetRootWidth()); - toastProperty->UpdateUserDefinedIdealSize(CalcSize(NG::CalcLength(rootWidth), std::nullopt)); - auto bottomPosition = StringUtils::StringToDimensionWithThemeValue(bottom, true, toastTheme->GetBottom()); - if ((bottomPosition.Unit() == DimensionUnit::PERCENT)) { - bottomPosition = rootHeight * bottomPosition.Value(); - } - auto toastBottom = - Dimension(GreatOrEqual(bottomPosition.ConvertToPx(), 0.0) ? bottomPosition.ConvertToPx() - : toastTheme->GetBottom().ConvertToPx()); UpdateTextLayoutProperty(textNode, message, isRightToLeft); UpdateTextContext(textNode); auto textHeight = GetTextHeight(textNode); @@ -94,7 +78,8 @@ RefPtr ToastView::CreateToastNode(const std::string& message, const s textHeight = GetTextHeight(textNode); } textNode->MountToParent(toastNode); - toastProperty->UpdateBottom(toastBottom); + + toastProperty->UpdateBottom(StringUtils::StringToDimensionWithThemeValue(bottom, true, toastTheme->GetBottom())); toastNode->GetEventHub()->GetOrCreateGestureEventHub()->SetHitTestMode(HitTestMode::HTMTRANSPARENT); toastNode->MarkModifyDone(); return toastNode; @@ -112,14 +97,6 @@ void ToastView::UpdateTextLayoutProperty( auto fontWeight = toastTheme->GetTextStyle().GetFontWeight(); auto textColor = toastTheme->GetTextStyle().GetTextColor(); auto fontSize = toastTheme->GetTextStyle().GetFontSize(); - auto minWidth = Dimension(toastTheme->GetMinWidth().ConvertToPx()); - auto minHeight = Dimension(toastTheme->GetMinHeight().ConvertToPx()); - auto gridColumnInfo = GridSystemManager::GetInstance().GetInfoByType(GridColumnType::TOAST); - auto parent = gridColumnInfo->GetParent(); - if (parent) { - parent->BuildColumnWidth(context->GetRootWidth()); - } - auto maxWidth = Dimension(gridColumnInfo->GetMaxWidth()); auto padding = toastTheme->GetPadding(); PaddingProperty paddings; paddings.top = NG::CalcLength(padding.Top()); @@ -132,8 +109,6 @@ void ToastView::UpdateTextLayoutProperty( textLayoutProperty->UpdateTextAlign(TextAlign::CENTER); textLayoutProperty->UpdateFontWeight(fontWeight); textLayoutProperty->UpdateFontSize(fontSize); - textLayoutProperty->UpdateCalcMaxSize(CalcSize(NG::CalcLength(maxWidth), std::nullopt)); - textLayoutProperty->UpdateCalcMinSize(CalcSize(NG::CalcLength(minWidth), NG::CalcLength(minHeight))); textLayoutProperty->UpdateLayoutDirection((isRightToLeft ? TextDirection::RTL : TextDirection::LTR)); textLayoutProperty->UpdatePadding(paddings); } diff --git a/frameworks/core/components_ng/pattern/ui_extension/ui_extension_pattern.cpp b/frameworks/core/components_ng/pattern/ui_extension/ui_extension_pattern.cpp index 93a6a1297cc..291abdd37a9 100644 --- a/frameworks/core/components_ng/pattern/ui_extension/ui_extension_pattern.cpp +++ b/frameworks/core/components_ng/pattern/ui_extension/ui_extension_pattern.cpp @@ -25,6 +25,7 @@ #include "base/utils/utils.h" #include "core/components_ng/event/event_hub.h" #include "core/components_ng/pattern/pattern.h" +#include "core/components_ng/pattern/text_field/text_field_manager.h" #include "core/components_ng/pattern/ui_extension/ui_extension_layout_algorithm.h" #include "core/components_ng/pattern/ui_extension/ui_extension_proxy.h" #include "core/components_ng/pattern/window_scene/scene/window_pattern.h" @@ -105,9 +106,7 @@ void UIExtensionPattern::OnConnectInner() onRemoteReadyCallback_(MakeRefPtr(session_)); } RegisterVisibleAreaChange(); - auto focusHub = host->GetFocusHub(); - CHECK_NULL_VOID(focusHub); - TransferFocusState(focusHub->IsFocusable()); + TransferFocusState(IsCurrentFocus()); } void UIExtensionPattern::OnDisconnect() @@ -129,6 +128,28 @@ void UIExtensionPattern::OnDisconnect() TaskExecutor::TaskType::UI); } +bool UIExtensionPattern::OnDirtyLayoutWrapperSwap(const RefPtr& dirty, const DirtySwapConfig& config) +{ + CHECK_NULL_RETURN(dirty, false); + auto host = dirty->GetHostNode(); + CHECK_NULL_RETURN(host, false); + auto globalOffsetWithTranslate = host->GetPaintRectGlobalOffsetWithTranslate(); + auto geometryNode = dirty->GetGeometryNode(); + CHECK_NULL_RETURN(geometryNode, false); + auto frameRect = geometryNode->GetFrameRect(); + + Rosen::WSRect windowRect { + .posX_ = std::round(globalOffsetWithTranslate.GetX()), + .posY_ = std::round(globalOffsetWithTranslate.GetY()), + .width_ = std::round(frameRect.Width()), + .height_ = std::round(frameRect.Height()) + }; + + CHECK_NULL_RETURN(session_, false); + session_->UpdateRect(windowRect, Rosen::SizeChangeReason::UNDEFINED); + return false; +} + void UIExtensionPattern::OnWindowShow() { RequestExtensionSessionActivation(); @@ -198,6 +219,10 @@ void UIExtensionPattern::OnDetachFromFrameNode(FrameNode* frameNode) auto pipeline = AceType::DynamicCast(PipelineBase::GetCurrentContext()); CHECK_NULL_VOID_NOLOG(pipeline); pipeline->RemoveWindowStateChangedCallback(id); + auto textFieldManager = DynamicCast(pipeline->GetTextFieldManager()); + if (textFieldManager) { + textFieldManager->ClearOnFocusTextField(); + } } FocusPattern UIExtensionPattern::GetFocusPattern() const @@ -258,6 +283,12 @@ void UIExtensionPattern::HandleBlurEvent() { WindowPattern::DisPatchFocusActiveEvent(false); TransferFocusState(false); + auto pipeline = AceType::DynamicCast(PipelineBase::GetCurrentContext()); + CHECK_NULL_VOID_NOLOG(pipeline); + auto textFieldManager = DynamicCast(pipeline->GetTextFieldManager()); + if (textFieldManager) { + textFieldManager->ClearOnFocusTextField(); + } } bool UIExtensionPattern::KeyEventConsumed(const KeyEvent& event) @@ -330,6 +361,17 @@ void UIExtensionPattern::HandleTouchEvent(const TouchEventInfo& info) auto hub = host->GetFocusHub(); CHECK_NULL_VOID(hub); hub->RequestFocusImmediately(); + + auto touchType = info.GetTouches().front().GetTouchType(); + if (touchType == TouchType::DOWN) { + auto touchOffsetToWindow = info.GetTouches().front().GetGlobalLocation(); + auto touchOffsetToFrameNode = info.GetTouches().front().GetLocalLocation(); + auto rectToWindow = host->GetTransformRectRelativeToWindow(); + UpdateTextFieldManager( + { rectToWindow.GetOffset().GetX(), touchOffsetToWindow.GetY() }, + rectToWindow.Height() - touchOffsetToFrameNode.GetY()); + } + WindowPattern::DispatchPointerEvent(pointerEvent); } @@ -483,4 +525,27 @@ void UIExtensionPattern::RegisterVisibleAreaChange() CHECK_NULL_VOID_NOLOG(host); pipeline->AddVisibleAreaChangeNode(host, 0.0f, callback, false); } + +void UIExtensionPattern::UpdateTextFieldManager(const Offset& offset, float height) +{ + if (!IsCurrentFocus()) { + return; + } + auto context = GetHost()->GetContext(); + CHECK_NULL_VOID(context); + auto textFieldManager = DynamicCast(context->GetTextFieldManager()); + CHECK_NULL_VOID(textFieldManager); + textFieldManager->SetClickPosition(offset); + textFieldManager->SetHeight(height); + textFieldManager->SetOnFocusTextField(WeakClaim(this)); +} + +bool UIExtensionPattern::IsCurrentFocus() const +{ + auto host = GetHost(); + CHECK_NULL_RETURN_NOLOG(host, false); + auto focusHub = host->GetFocusHub(); + CHECK_NULL_RETURN_NOLOG(focusHub, false); + return focusHub->IsCurrentFocus(); +} } // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/pattern/ui_extension/ui_extension_pattern.h b/frameworks/core/components_ng/pattern/ui_extension/ui_extension_pattern.h index 1a48d93c9bd..e18a2071ac1 100644 --- a/frameworks/core/components_ng/pattern/ui_extension/ui_extension_pattern.h +++ b/frameworks/core/components_ng/pattern/ui_extension/ui_extension_pattern.h @@ -42,6 +42,7 @@ public: RefPtr CreateLayoutAlgorithm() override; FocusPattern GetFocusPattern() const override; void OnVisibleChange(bool visible) override; + bool OnDirtyLayoutWrapperSwap(const RefPtr& dirty, const DirtySwapConfig& config) override; bool HasStartingPage() override { @@ -91,6 +92,8 @@ private: void OnConnectInner(); void RegisterVisibleAreaChange(); + void UpdateTextFieldManager(const Offset& offset, float height); + bool IsCurrentFocus() const; RefPtr touchEvent_; RefPtr mouseEvent_; diff --git a/frameworks/core/components_ng/pattern/video/video_pattern.cpp b/frameworks/core/components_ng/pattern/video/video_pattern.cpp index 4ff36c2ef41..03327759638 100644 --- a/frameworks/core/components_ng/pattern/video/video_pattern.cpp +++ b/frameworks/core/components_ng/pattern/video/video_pattern.cpp @@ -1460,11 +1460,10 @@ void VideoPattern::RecoverState(const RefPtr& videoPattern) { CHECK_NULL_VOID(videoPattern); currentPos_ = videoPattern->GetCurrentPos(); - if (mediaPlayer_->IsPlaying() != isPlaying_) { + if (mediaPlayer_->IsMediaPlayerValid() && mediaPlayer_->IsPlaying() != isPlaying_) { isPlaying_ = mediaPlayer_->IsPlaying(); ChangePlayButtonTag(); } - isPlaying_ = mediaPlayer_->IsPlaying(); isInitialState_ = videoPattern->GetInitialState(); auto layoutProperty = videoPattern->GetLayoutProperty(); src_ = layoutProperty->GetVideoSourceValue(""); diff --git a/frameworks/core/components_ng/pattern/web/web_pattern.cpp b/frameworks/core/components_ng/pattern/web/web_pattern.cpp index 3a919d9735d..5a11966f700 100644 --- a/frameworks/core/components_ng/pattern/web/web_pattern.cpp +++ b/frameworks/core/components_ng/pattern/web/web_pattern.cpp @@ -247,7 +247,7 @@ void WebPattern::InitPanEvent(const RefPtr& gestureHub) auto actionEndTask = [weak = WeakClaim(this)](const GestureEvent& info) { return; }; auto actionCancelTask = [weak = WeakClaim(this)]() { return; }; PanDirection panDirection; - panDirection.type = PanDirection::ALL; + panDirection.type = PanDirection::VERTICAL; panEvent_ = MakeRefPtr( std::move(actionStartTask), std::move(actionUpdateTask), std::move(actionEndTask), std::move(actionCancelTask)); gestureHub->AddPanEvent(panEvent_, panDirection, DEFAULT_PAN_FINGER, DEFAULT_PAN_DISTANCE); @@ -373,14 +373,41 @@ void WebPattern::WebOnMouseEvent(const MouseInfo& info) void WebPattern::ResetDragAction() { - LOGI("reset drag action flag in framework"); auto frameNode = GetHost(); - CHECK_NULL_VOID(frameNode); + CHECK_NULL_VOID_NOLOG(frameNode); + frameNode->SetDraggable(false); auto eventHub = frameNode->GetEventHub(); - CHECK_NULL_VOID(eventHub); + CHECK_NULL_VOID_NOLOG(eventHub); auto gestureHub = eventHub->GetOrCreateGestureEventHub(); - CHECK_NULL_VOID(gestureHub); + CHECK_NULL_VOID_NOLOG(gestureHub); gestureHub->ResetDragActionForWeb(); + + if (!isDragging_) { + return; + } + + isDragging_ = false; + LOGI("need to cancel web kernel drag action"); + // cancel drag action to avoid web kernel can't process other input event + CHECK_NULL_VOID_NOLOG(delegate_); + delegate_->HandleDragEvent(0, 0, DragAction::DRAG_CANCEL); + gestureHub->CancelDragForWeb(); +} + +Offset WebPattern::GetDragOffset() const +{ + Offset webDragOffset; + int x = 0; + int y = 0; + if (delegate_ && delegate_->dragData_) { + delegate_->dragData_->GetDragStartPosition(x, y); + } + + webDragOffset.SetX(x); + webDragOffset.SetY(y); + + LOGD("web drag start position = (%{public}d, %{public}d)", x, y); + return webDragOffset; } bool WebPattern::HandleDoubleClickEvent(const MouseInfo& info) @@ -455,7 +482,7 @@ NG::DragDropInfo WebPattern::HandleOnDragStart(const RefPtrdragData_->GetLinkTitle(); // plain text if (!plainContent.empty()) { - UdmfClient::GetInstance()->AddTextRecord(aceUnifiedData, plainContent); + UdmfClient::GetInstance()->AddPlainTextRecord(aceUnifiedData, plainContent); } // html if (!htmlContent.empty()) { @@ -625,6 +652,7 @@ bool WebPattern::NotifyStartDragTask() } LOGI("notify to start web drag task"); + isDragging_ = true; auto frameNode = GetHost(); CHECK_NULL_RETURN_NOLOG(frameNode, false); auto eventHub = frameNode->GetEventHub(); @@ -636,38 +664,10 @@ bool WebPattern::NotifyStartDragTask() gestureHub->SetPixelMap(delegate_->GetDragPixelMap()); if (!isMouseEvent_) { // mouse drag does not need long press action - LOGI("is not mouse drag, do not need to do long press action"); + LOGI("is not mouse drag, need to do long press action"); gestureHub->StartLongPressActionForWeb(); } gestureHub->StartDragTaskForWeb(); - - auto pipeline = PipelineContext::GetCurrentContext(); - CHECK_NULL_RETURN_NOLOG(pipeline, false); - auto taskScheduler = pipeline->GetTaskExecutor(); - CHECK_NULL_RETURN_NOLOG(taskScheduler, false); - if (isMouseEvent_) { - taskScheduler->PostDelayedTask( - [weak = WeakClaim(this)]() { - auto webPattern = weak.Upgrade(); - CHECK_NULL_VOID_NOLOG(webPattern); - if (!(webPattern->isDragging_)) { - LOGE("timeout, need to cancel drag action"); - // timeout, cancel drag action to avoid web kernel can't process other input event - CHECK_NULL_VOID_NOLOG(webPattern->delegate_); - webPattern->delegate_->HandleDragEvent(0, 0, DragAction::DRAG_CANCEL); - auto frameNode = webPattern->GetHost(); - CHECK_NULL_VOID_NOLOG(frameNode); - frameNode->SetDraggable(false); - auto eventHub = frameNode->GetEventHub(); - CHECK_NULL_VOID_NOLOG(eventHub); - auto gestureHub = eventHub->GetOrCreateGestureEventHub(); - CHECK_NULL_VOID_NOLOG(gestureHub); - gestureHub->CancelDragForWeb(); - } - }, - TaskExecutor::TaskType::UI, 100); // 100: 100ms - } - return true; } @@ -780,7 +780,7 @@ void WebPattern::HandleOnDragDrop(const RefPtr& info) if (aceData && aceData->GetSize() >= 1) { LOGI("DragDrop event WebEventHub onDragDropId, size:%{public}d", (int)aceData->GetSize()); // plain text - std::string plain = UdmfClient::GetInstance()->GetSingleTextRecord(aceData); + std::string plain = UdmfClient::GetInstance()->GetSinglePlainTextRecord(aceData); if (!plain.empty()) { delegate_->dragData_->SetFragmentText(plain); LOGI("DragDrop event WebEventHub onDragDropId, plain size:%{public}d", (int)plain.size()); @@ -909,6 +909,9 @@ void WebPattern::HandleBlurEvent(const BlurReason& blurReason) delegate_->OnBlur(); } OnQuickMenuDismissed(); + if (quickMenuCallback_) { + quickMenuCallback_->Cancel(); + } } bool WebPattern::HandleKeyEvent(const KeyEvent& keyEvent) @@ -1490,10 +1493,14 @@ void WebPattern::HandleTouchDown(const TouchEventInfo& info, bool fromOverlay) } delegate_->HandleTouchDown(touchPoint.id, touchPoint.x, touchPoint.y, fromOverlay); } + if (!touchInfos.empty()) { + WebRequestFocus(); + } } void WebPattern::HandleTouchUp(const TouchEventInfo& info, bool fromOverlay) { + ResetDragAction(); CHECK_NULL_VOID(delegate_); std::list touchInfos; if (!ParseTouchInfo(info, touchInfos)) { @@ -1507,9 +1514,6 @@ void WebPattern::HandleTouchUp(const TouchEventInfo& info, bool fromOverlay) } delegate_->HandleTouchUp(touchPoint.id, touchPoint.x, touchPoint.y, fromOverlay); } - if (!touchInfos.empty()) { - WebRequestFocus(); - } } void WebPattern::HandleTouchMove(const TouchEventInfo& info, bool fromOverlay) @@ -1661,6 +1665,7 @@ void WebPattern::RegisterSelectOverlayCallback(SelectOverlayInfo& selectInfo, std::shared_ptr params, std::shared_ptr callback) { + quickMenuCallback_ = callback; int32_t flags = params->GetEditStateFlags(); if (flags & OHOS::NWeb::NWebQuickMenuParams::QM_EF_CAN_CUT) { selectInfo.menuCallback.onCut = [weak = AceType::WeakClaim(this), callback]() { diff --git a/frameworks/core/components_ng/pattern/web/web_pattern.h b/frameworks/core/components_ng/pattern/web/web_pattern.h index 370d9a072fe..f7ea3bc2304 100644 --- a/frameworks/core/components_ng/pattern/web/web_pattern.h +++ b/frameworks/core/components_ng/pattern/web/web_pattern.h @@ -336,6 +336,7 @@ public: bool NotifyStartDragTask(); bool IsImageDrag(); DragRet GetDragAcceptableStatus(); + Offset GetDragOffset() const; private: void RegistVirtualKeyBoardListener(); @@ -524,6 +525,7 @@ private: bool isEnhanceSurface_ = false; bool isAllowWindowOpenMethod_ = false; OffsetF webOffset_; + std::shared_ptr quickMenuCallback_ = nullptr; SelectMenuInfo selectMenuInfo_; bool selectOverlayDragging_ = false; bool selectPopupMenuShowing_ = false; diff --git a/frameworks/core/components_ng/pattern/window_scene/scene/window_pattern.cpp b/frameworks/core/components_ng/pattern/window_scene/scene/window_pattern.cpp index 9bd63c04baf..ad8b823611f 100644 --- a/frameworks/core/components_ng/pattern/window_scene/scene/window_pattern.cpp +++ b/frameworks/core/components_ng/pattern/window_scene/scene/window_pattern.cpp @@ -177,11 +177,9 @@ void WindowPattern::CreateSnapshotNode() host->AddChild(snapshotNode_); CHECK_NULL_VOID(session_); - auto snapshot = session_->GetSnapshot(); - auto pixelMap = PixelMap::CreatePixelMap(&snapshot); - - CHECK_NULL_VOID(pixelMap); - imageLayoutProperty->UpdateImageSourceInfo(ImageSourceInfo(pixelMap)); + CHECK_NULL_VOID(session_->GetScenePersistence()); + imageLayoutProperty->UpdateImageSourceInfo( + ImageSourceInfo("file:/" + session_->GetScenePersistence()->GetSnapshotFilePath())); imageLayoutProperty->UpdateImageFit(ImageFit::FILL); snapshotNode_->MarkModifyDone(); } diff --git a/frameworks/core/components_ng/pattern/window_scene/scene/window_scene.cpp b/frameworks/core/components_ng/pattern/window_scene/scene/window_scene.cpp index 4f9d8bb9d4f..b9e933d7621 100644 --- a/frameworks/core/components_ng/pattern/window_scene/scene/window_scene.cpp +++ b/frameworks/core/components_ng/pattern/window_scene/scene/window_scene.cpp @@ -67,8 +67,7 @@ void WindowScene::UpdateSession(const sptr& session) return; } - LOGI("session %{public}" PRIu64 " changes to %{public}" PRIu64, - session_->GetPersistentId(), session->GetPersistentId()); + LOGI("session %{public}d changes to %{public}d", session_->GetPersistentId(), session->GetPersistentId()); session_ = session; auto surfaceNode = session_->GetSurfaceNode(); CHECK_NULL_VOID(surfaceNode); @@ -96,29 +95,35 @@ void WindowScene::OnForeground() void WindowScene::OnBackground() { + auto uiTask = [weakThis = WeakClaim(this)]() { + auto self = weakThis.Upgrade(); + CHECK_NULL_VOID(self); + + self->snapshotNode_ = FrameNode::CreateFrameNode( + V2::IMAGE_ETS_TAG, ElementRegister::GetInstance()->MakeUniqueId(), AceType::MakeRefPtr()); + auto imageLayoutProperty = self->snapshotNode_->GetLayoutProperty(); + imageLayoutProperty->UpdateMeasureType(MeasureType::MATCH_PARENT); + auto backgroundColor = SystemProperties::GetColorMode() == ColorMode::DARK ? COLOR_BLACK : COLOR_WHITE; + self->snapshotNode_->GetRenderContext()->UpdateBackgroundColor(Color(backgroundColor)); + + auto host = self->GetHost(); + CHECK_NULL_VOID(host); + host->RemoveChild(self->contentNode_); + host->AddChild(self->snapshotNode_); + host->MarkDirtyNode(PROPERTY_UPDATE_MEASURE); + + CHECK_NULL_VOID(self->session_); + CHECK_NULL_VOID(self->session_->GetScenePersistence()); + imageLayoutProperty->UpdateImageSourceInfo( + ImageSourceInfo("file:/" + self->session_->GetScenePersistence()->GetSnapshotFilePath())); + imageLayoutProperty->UpdateImageFit(ImageFit::FILL); + self->snapshotNode_->MarkModifyDone(); + }; + ContainerScope scope(instanceId_); - - snapshotNode_ = FrameNode::CreateFrameNode( - V2::IMAGE_ETS_TAG, ElementRegister::GetInstance()->MakeUniqueId(), AceType::MakeRefPtr()); - auto imageLayoutProperty = snapshotNode_->GetLayoutProperty(); - imageLayoutProperty->UpdateMeasureType(MeasureType::MATCH_PARENT); - auto backgroundColor = SystemProperties::GetColorMode() == ColorMode::DARK ? COLOR_BLACK : COLOR_WHITE; - snapshotNode_->GetRenderContext()->UpdateBackgroundColor(Color(backgroundColor)); - - auto host = GetHost(); - CHECK_NULL_VOID(host); - host->RemoveChild(contentNode_); - host->AddChild(snapshotNode_); - host->MarkDirtyNode(PROPERTY_UPDATE_MEASURE); - - CHECK_NULL_VOID(session_); - auto snapshot = session_->GetSnapshot(); - auto pixelMap = PixelMap::CreatePixelMap(&snapshot); - - CHECK_NULL_VOID(pixelMap); - imageLayoutProperty->UpdateImageSourceInfo(ImageSourceInfo(pixelMap)); - imageLayoutProperty->UpdateImageFit(ImageFit::FILL); - snapshotNode_->MarkModifyDone(); + auto pipelineContext = PipelineContext::GetCurrentContext(); + CHECK_NULL_VOID(pipelineContext); + pipelineContext->PostAsyncEvent(std::move(uiTask), TaskExecutor::TaskType::UI); } void WindowScene::OnSetDepth(const int32_t depth) diff --git a/frameworks/core/components_ng/pattern/window_scene/scene/window_scene_model.cpp b/frameworks/core/components_ng/pattern/window_scene/scene/window_scene_model.cpp index 69e035b5687..c07909aa4f3 100644 --- a/frameworks/core/components_ng/pattern/window_scene/scene/window_scene_model.cpp +++ b/frameworks/core/components_ng/pattern/window_scene/scene/window_scene_model.cpp @@ -24,7 +24,7 @@ #include "core/components_v2/inspector/inspector_constants.h" namespace OHOS::Ace::NG { -void WindowSceneModel::Create(uint64_t persistentId) +void WindowSceneModel::Create(int32_t persistentId) { auto sceneSession = Rosen::SceneSessionManager::GetInstance().GetSceneSession(persistentId); if (sceneSession == nullptr) { diff --git a/frameworks/core/components_ng/pattern/window_scene/scene/window_scene_model.h b/frameworks/core/components_ng/pattern/window_scene/scene/window_scene_model.h index 39fa6ff692a..6fcd68c1f95 100644 --- a/frameworks/core/components_ng/pattern/window_scene/scene/window_scene_model.h +++ b/frameworks/core/components_ng/pattern/window_scene/scene/window_scene_model.h @@ -23,7 +23,7 @@ namespace OHOS::Ace::NG { class ACE_EXPORT WindowSceneModel { public: - static void Create(uint64_t persistentId); + static void Create(int32_t persistentId); }; } // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/render/adapter/rosen_render_context.cpp b/frameworks/core/components_ng/render/adapter/rosen_render_context.cpp index f1a661752df..114718d33e3 100644 --- a/frameworks/core/components_ng/render/adapter/rosen_render_context.cpp +++ b/frameworks/core/components_ng/render/adapter/rosen_render_context.cpp @@ -588,6 +588,30 @@ void RosenRenderContext::UpdateBackBlurStyle(const std::optional& effectOption) +{ + const auto& groupProperty = GetOrCreateBackground(); + if (groupProperty->CheckEffectOption(effectOption)) { + return; + } + groupProperty->propEffectOption = effectOption; + if (!effectOption.has_value()) { + return; + } + auto context = PipelineBase::GetCurrentContext(); + CHECK_NULL_VOID(context); + float radiusPx = context->NormalizeToPx(effectOption->radius); +#ifndef USE_ROSEN_DRAWING + float backblurRadius = SkiaDecorationPainter::ConvertRadiusToSigma(radiusPx); +#else + float backblurRadius = DrawingDecorationPainter::ConvertRadiusToSigma(radiusPx); +#endif + std::shared_ptr backFilter = Rosen::RSFilter::CreateMaterialFilter( + backblurRadius, static_cast(effectOption->saturation), + static_cast(effectOption->brightness), effectOption->color.GetValue()); + rsNode_->SetBackgroundFilter(backFilter); +} + void RosenRenderContext::UpdateFrontBlurStyle(const std::optional& fgBlurStyle) { const auto& groupProperty = GetOrCreateForeground(); @@ -1334,10 +1358,11 @@ RectF RosenRenderContext::AdjustPaintRect() return rect; } if (HasOffset()) { - CombinePaddingAndOffset( - resultX, resultY, parentPaddingLeft, parentPaddingTop, widthPercentReference, heightPercentReference); - rect.SetLeft(rect.GetX() + resultX.ConvertToPx() - anchorX.value_or(0)); - rect.SetTop(rect.GetY() + resultY.ConvertToPx() - anchorY.value_or(0)); + auto offset = GetOffsetValue({}) + OffsetT(parentPaddingLeft, parentPaddingTop); + auto offsetX = ConvertToPx(offset.GetX(), ScaleProperty::CreateScaleProperty(), widthPercentReference); + auto offsetY = ConvertToPx(offset.GetY(), ScaleProperty::CreateScaleProperty(), heightPercentReference); + rect.SetLeft(rect.GetX() + offsetX.value_or(0) - anchorX.value_or(0)); + rect.SetTop(rect.GetY() + offsetY.value_or(0) - anchorY.value_or(0)); return rect; } rect.SetLeft(rect.GetX() - anchorX.value_or(0)); @@ -1388,31 +1413,6 @@ void RosenRenderContext::CombineMarginAndPosition(Dimension& resultX, Dimension& } } -void RosenRenderContext::CombinePaddingAndOffset(Dimension& resultX, Dimension& resultY, - const Dimension& parentPaddingLeft, const Dimension& parentPaddingTop, float widthPercentReference, - float heightPercentReference) -{ - // to distinguish cases ex. offset has percentage unit and padding has vp unit - if (parentPaddingLeft.Unit() != GetOffsetValue({}).GetX().Unit()) { - resultX = Dimension( - ConvertToPx(parentPaddingLeft, ScaleProperty::CreateScaleProperty(), widthPercentReference).value_or(0) + - ConvertToPx(GetOffsetValue({}).GetX(), ScaleProperty::CreateScaleProperty(), widthPercentReference) - .value_or(0), - DimensionUnit::PX); - } else { - resultX = parentPaddingLeft + GetOffsetValue({}).GetX(); - } - if (parentPaddingTop.Unit() != GetOffsetValue({}).GetY().Unit()) { - resultY = Dimension( - ConvertToPx(parentPaddingTop, ScaleProperty::CreateScaleProperty(), heightPercentReference).value_or(0) + - ConvertToPx(GetOffsetValue({}).GetY(), ScaleProperty::CreateScaleProperty(), heightPercentReference) - .value_or(0), - DimensionUnit::PX); - } else { - resultY = parentPaddingTop + GetOffsetValue({}).GetY(); - } -} - bool RosenRenderContext::IsUsingPosition(const RefPtr& frameNode) { auto layoutProperty = frameNode->GetLayoutProperty(); diff --git a/frameworks/core/components_ng/render/adapter/rosen_render_context.h b/frameworks/core/components_ng/render/adapter/rosen_render_context.h index 92b690503ba..dc02b586fe6 100644 --- a/frameworks/core/components_ng/render/adapter/rosen_render_context.h +++ b/frameworks/core/components_ng/render/adapter/rosen_render_context.h @@ -135,6 +135,7 @@ public: void AnimateHoverEffectBoard(bool isHovered) override; void UpdateBackBlurRadius(const Dimension& radius) override; void UpdateBackBlurStyle(const std::optional& bgBlurStyle) override; + void UpdateBackgroundEffect(const std::optional& effectOption) override; void UpdateFrontBlurRadius(const Dimension& radius) override; void UpdateFrontBlurStyle(const std::optional& fgBlurStyle) override; void ResetBackBlurStyle() override; @@ -350,8 +351,6 @@ private: void SetBackBlurFilter(); void SetFrontBlurFilter(); void GetPaddingOfFirstFrameNodeParent(Dimension& parentPaddingLeft, Dimension& parentPaddingTop); - void CombinePaddingAndOffset(Dimension& resultX, Dimension& resultY, const Dimension& parentPaddingLeft, - const Dimension& parentPaddingTop, float widthPercentReference, float heightPercentReference); void CombineMarginAndPosition(Dimension& resultX, Dimension& resultY, const Dimension& parentPaddingLeft, const Dimension& parentPaddingTop, float widthPercentReference, float heightPercentReference); diff --git a/frameworks/core/components_ng/render/canvas_image.h b/frameworks/core/components_ng/render/canvas_image.h index 1d10f770ff6..3a045567bfc 100644 --- a/frameworks/core/components_ng/render/canvas_image.h +++ b/frameworks/core/components_ng/render/canvas_image.h @@ -43,7 +43,6 @@ struct ImagePaintConfig { std::vector obscuredReasons_; }; -struct RenderTaskHolder; // CanvasImage is interface for drawing image. class CanvasImage : public virtual AceType { DECLARE_ACE_TYPE(CanvasImage, AceType) @@ -56,9 +55,6 @@ public: static RefPtr Create(void* rawImage); static RefPtr Create(); - // TODO: use [PixelMap] as data source when rs provides interface like - // DrawBitmapRect(Media::PixelMap* pixelMap, const Rect& dstRect, const Rect& srcRect, ...) - // now we make [SkImage] from [PixelMap] and use [drawImageRect] to draw image static RefPtr Create(const RefPtr& pixelMap); virtual RefPtr GetPixelMap() const @@ -91,6 +87,7 @@ public: { if (!paintConfig_) { LOGW("image paint config is null"); + paintConfig_ = std::make_unique(); } return *paintConfig_; } diff --git a/frameworks/core/components_ng/render/drawing.h b/frameworks/core/components_ng/render/drawing.h index 6bff8de8ba6..188b3f12015 100644 --- a/frameworks/core/components_ng/render/drawing.h +++ b/frameworks/core/components_ng/render/drawing.h @@ -42,6 +42,7 @@ #include "utils/scalar.h" namespace OHOS::Ace { +namespace RSDrawing = Rosen::Drawing; using RSCanvas = Rosen::Drawing::Canvas; using RSImage = Rosen::Drawing::Image; using RSBrush = Rosen::Drawing::Brush; diff --git a/frameworks/core/components_ng/render/drawing_mock.h b/frameworks/core/components_ng/render/drawing_mock.h index f7ee9d2bc2a..c636aa9304d 100644 --- a/frameworks/core/components_ng/render/drawing_mock.h +++ b/frameworks/core/components_ng/render/drawing_mock.h @@ -33,6 +33,7 @@ #include "core/components_ng/test/mock/rosen/testing_point.h" #include "core/components_ng/test/mock/rosen/testing_point3.h" #include "core/components_ng/test/mock/rosen/testing_sampling_options.h" +#include "core/components_ng/test/mock/rosen/testing_scalar.h" #include "core/components_ng/test/mock/rosen/testing_shader_effect.h" #include "core/components_ng/test/mock/rosen/testing_shadowflags.h" #include "core/components_ng/test/mock/rosen/testing_text_style.h" @@ -41,6 +42,7 @@ #include "core/components_ng/test/mock/rosen/testing_typography_style.h" namespace OHOS::Ace { +namespace RSDrawing = Testing; using RSCanvas = Testing::TestingCanvas; using RSPen = Testing::TestingPen; using RSBrush = Testing::TestingBrush; diff --git a/frameworks/core/components_ng/render/render_context.h b/frameworks/core/components_ng/render/render_context.h index daccfaf89af..34ee34f9777 100644 --- a/frameworks/core/components_ng/render/render_context.h +++ b/frameworks/core/components_ng/render/render_context.h @@ -193,6 +193,7 @@ public: virtual void UpdateBackBlurRadius(const Dimension& radius) {} virtual void UpdateBackBlurStyle(const std::optional& bgBlurStyle) {} + virtual void UpdateBackgroundEffect(const std::optional& effectOption) {} virtual void UpdateFrontBlurStyle(const std::optional& fgBlurStyle) {} virtual void UpdateFrontBlurRadius(const Dimension& radius) {} virtual void ResetBackBlurStyle() {} diff --git a/frameworks/core/components_ng/render/render_property.h b/frameworks/core/components_ng/render/render_property.h index c5980eb10eb..f3212559480 100644 --- a/frameworks/core/components_ng/render/render_property.h +++ b/frameworks/core/components_ng/render/render_property.h @@ -57,8 +57,19 @@ struct BackgroundProperty { } return NearEqual(propBlurRadius.value(), radius); } + bool CheckEffectOption(const std::optional& effectOption) const + { + if (!effectOption.has_value()) { + return false; + } + if (!propEffectOption.has_value()) { + return false; + } + return NearEqual(propEffectOption.value(), effectOption.value()); + } std::optional propBlurStyleOption; std::optional propBlurRadius; + std::optional propEffectOption; void ToJsonValue(std::unique_ptr& json) const; }; diff --git a/frameworks/core/components_ng/svg/parse/svg_animation.cpp b/frameworks/core/components_ng/svg/parse/svg_animation.cpp index a74300ea604..4e4825e6004 100644 --- a/frameworks/core/components_ng/svg/parse/svg_animation.cpp +++ b/frameworks/core/components_ng/svg/parse/svg_animation.cpp @@ -17,11 +17,6 @@ #include -#include "include/core/SkPaint.h" -#include "include/core/SkRect.h" - -#include "bridge/common/dom/dom_type.h" -#include "core/pipeline/base/constants.h" #include "frameworks/core/components/declaration/svg/svg_animate_declaration.h" namespace OHOS::Ace::NG { diff --git a/frameworks/core/components_ng/svg/parse/svg_circle.cpp b/frameworks/core/components_ng/svg/parse/svg_circle.cpp index 603faf15cc2..5afafb36c8d 100644 --- a/frameworks/core/components_ng/svg/parse/svg_circle.cpp +++ b/frameworks/core/components_ng/svg/parse/svg_circle.cpp @@ -16,6 +16,7 @@ #include "frameworks/core/components_ng/svg/parse/svg_circle.h" #include "base/utils/utils.h" +#include "core/components_ng/svg/parse/svg_animation.h" #include "frameworks/core/components/declaration/svg/svg_circle_declaration.h" namespace OHOS::Ace::NG { @@ -56,4 +57,19 @@ RSRecordingPath SvgCircle::AsPath(const Size& viewPort) const } #endif +void SvgCircle::PrepareAnimation(const RefPtr& animate) +{ + auto declaration = AceType::DynamicCast(declaration_); + CHECK_NULL_VOID_NOLOG(declaration); + auto attr = animate->GetAttributeName(); + if (attr == DOM_SVG_CX) { + AnimateOnAttribute(animate, declaration->GetCx()); + } else if (attr == DOM_SVG_CY) { + AnimateOnAttribute(animate, declaration->GetCy()); + } else if (attr == DOM_SVG_R) { + AnimateOnAttribute(animate, declaration->GetR()); + } else { + SvgNode::PrepareAnimation(animate); + } +} } // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/svg/parse/svg_circle.h b/frameworks/core/components_ng/svg/parse/svg_circle.h index 26f8f161f59..00a6d03a85e 100644 --- a/frameworks/core/components_ng/svg/parse/svg_circle.h +++ b/frameworks/core/components_ng/svg/parse/svg_circle.h @@ -29,6 +29,8 @@ public: static RefPtr Create(); + void PrepareAnimation(const RefPtr& animate) override; + #ifndef USE_ROSEN_DRAWING SkPath AsPath(const Size& viewPort) const override; #else diff --git a/frameworks/core/components_ng/svg/parse/svg_node.cpp b/frameworks/core/components_ng/svg/parse/svg_node.cpp index 7a2779fce58..3c80e2b0800 100644 --- a/frameworks/core/components_ng/svg/parse/svg_node.cpp +++ b/frameworks/core/components_ng/svg/parse/svg_node.cpp @@ -26,7 +26,6 @@ #include "core/components/common/painter/rosen_svg_painter.h" #endif #include "core/components/common/properties/decoration.h" -#include "core/components/transform/render_transform.h" #include "core/components_ng/render/drawing.h" #include "core/components_ng/svg/parse/svg_animation.h" #include "core/components_ng/svg/parse/svg_gradient.h" @@ -412,7 +411,7 @@ void SvgNode::AnimateTransform(const RefPtr& animate, double origi if (!animate->GetValues().empty()) { AnimateFrameTransform(animate, originalValue); } else { - AnimateValueTransform(animate, originalValue); + AnimateFromToTransform(animate, originalValue); } } @@ -429,20 +428,19 @@ void SvgNode::AnimateFrameTransform(const RefPtr& animate, double return; } - // set indices instead of frames + // change Values to frame indices to create an index-based animation + // property values of each frame are stored in [frames] std::vector indices; uint32_t size = animate->GetValues().size(); for (uint32_t i = 0; i < size; i++) { indices.emplace_back(std::to_string(i)); } - auto instance = AceType::MakeRefPtr(); - animate->Copy(instance); - instance->SetValues(indices); + animate->SetValues(indices); std::function callback = [weak = WeakClaim(this), type, frames](double value) { auto self = weak.Upgrade(); CHECK_NULL_VOID(self); - // use index and rate to locate frame and position + // use index and rate to locate frame and progress auto index = static_cast(value); double rate = value - index; if (index >= frames.size() - 1) { @@ -460,7 +458,7 @@ void SvgNode::AnimateFrameTransform(const RefPtr& animate, double animate->CreatePropertyAnimation(originalValue, std::move(callback)); } -void SvgNode::AnimateValueTransform(const RefPtr& animate, double originalValue) +void SvgNode::AnimateFromToTransform(const RefPtr& animate, double originalValue) { std::vector fromVec; std::vector toVec; diff --git a/frameworks/core/components_ng/svg/parse/svg_node.h b/frameworks/core/components_ng/svg/parse/svg_node.h index d1f8a24f6a2..439c8ef9559 100644 --- a/frameworks/core/components_ng/svg/parse/svg_node.h +++ b/frameworks/core/components_ng/svg/parse/svg_node.h @@ -143,7 +143,7 @@ protected: void AnimateOnAttribute(const RefPtr& animate, const T& originalValue); // animate a transformation attribute void AnimateTransform(const RefPtr& animate, double originalValue); - void AnimateValueTransform(const RefPtr& animate, double originalValue); + void AnimateFromToTransform(const RefPtr& animate, double originalValue); void AnimateFrameTransform(const RefPtr& animate, double originalValue); // update svg attribute in animation diff --git a/frameworks/core/components_ng/test/event/click_event/BUILD.gn b/frameworks/core/components_ng/test/event/click_event/BUILD.gn index 53049c4d561..d5e8f2b6c31 100644 --- a/frameworks/core/components_ng/test/event/click_event/BUILD.gn +++ b/frameworks/core/components_ng/test/event/click_event/BUILD.gn @@ -43,12 +43,14 @@ ohos_unittest("click_event_test_ng") { "$ace_root/frameworks/core/components_ng/layout/layout_wrapper.cpp", "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_builder.cpp", "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_node.cpp", + "$ace_root/frameworks/core/components_ng/manager/safe_area/safe_area_manager.cpp", "$ace_root/frameworks/core/components_ng/pattern/custom/custom_node.cpp", "$ace_root/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp", "$ace_root/frameworks/core/components_ng/property/border_property.cpp", "$ace_root/frameworks/core/components_ng/property/calc_length.cpp", "$ace_root/frameworks/core/components_ng/property/measure_utils.cpp", "$ace_root/frameworks/core/components_ng/property/property.cpp", + "$ace_root/frameworks/core/components_ng/property/safe_area_insets.cpp", "$ace_root/frameworks/core/components_ng/syntax/lazy_for_each_node.cpp", "$ace_root/frameworks/core/components_v2/inspector/inspector_constants.cpp", diff --git a/frameworks/core/components_ng/test/event/drag_event/BUILD.gn b/frameworks/core/components_ng/test/event/drag_event/BUILD.gn index 33b142da97e..8c44324fb50 100644 --- a/frameworks/core/components_ng/test/event/drag_event/BUILD.gn +++ b/frameworks/core/components_ng/test/event/drag_event/BUILD.gn @@ -40,6 +40,7 @@ ohos_unittest("drag_event_test_ng") { "$ace_root/frameworks/core/components_ng/event/state_style_manager.cpp", "$ace_root/frameworks/core/components_ng/event/touch_event.cpp", "$ace_root/frameworks/core/components_ng/gestures/recognizers/multi_fingers_recognizer.cpp", + "$ace_root/frameworks/core/components_ng/manager/safe_area/safe_area_manager.cpp", "$ace_root/frameworks/core/components_ng/property/border_property.cpp", "$ace_root/frameworks/core/components_ng/property/calc_length.cpp", "$ace_root/frameworks/core/components_ng/property/measure_utils.cpp", diff --git a/frameworks/core/components_ng/test/event/event_hub/BUILD.gn b/frameworks/core/components_ng/test/event/event_hub/BUILD.gn index e23a7ded1d4..c899b0f03aa 100644 --- a/frameworks/core/components_ng/test/event/event_hub/BUILD.gn +++ b/frameworks/core/components_ng/test/event/event_hub/BUILD.gn @@ -41,12 +41,14 @@ ohos_unittest("event_hub_test_ng") { "$ace_root/frameworks/core/components_ng/layout/layout_wrapper.cpp", "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_builder.cpp", "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_node.cpp", + "$ace_root/frameworks/core/components_ng/manager/safe_area/safe_area_manager.cpp", "$ace_root/frameworks/core/components_ng/pattern/custom/custom_node.cpp", "$ace_root/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp", "$ace_root/frameworks/core/components_ng/property/border_property.cpp", "$ace_root/frameworks/core/components_ng/property/calc_length.cpp", "$ace_root/frameworks/core/components_ng/property/measure_utils.cpp", "$ace_root/frameworks/core/components_ng/property/property.cpp", + "$ace_root/frameworks/core/components_ng/property/safe_area_insets.cpp", "$ace_root/frameworks/core/components_ng/syntax/lazy_for_each_node.cpp", "$ace_root/frameworks/core/components_v2/inspector/inspector_constants.cpp", diff --git a/frameworks/core/components_ng/test/event/focus_hub/BUILD.gn b/frameworks/core/components_ng/test/event/focus_hub/BUILD.gn index a47433e02f5..3dd5e2628e5 100644 --- a/frameworks/core/components_ng/test/event/focus_hub/BUILD.gn +++ b/frameworks/core/components_ng/test/event/focus_hub/BUILD.gn @@ -39,12 +39,14 @@ ohos_unittest("focus_hub_test_ng") { "$ace_root/frameworks/core/components_ng/layout/layout_wrapper.cpp", "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_builder.cpp", "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_node.cpp", + "$ace_root/frameworks/core/components_ng/manager/safe_area/safe_area_manager.cpp", "$ace_root/frameworks/core/components_ng/pattern/custom/custom_node.cpp", "$ace_root/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp", "$ace_root/frameworks/core/components_ng/property/border_property.cpp", "$ace_root/frameworks/core/components_ng/property/calc_length.cpp", "$ace_root/frameworks/core/components_ng/property/measure_utils.cpp", "$ace_root/frameworks/core/components_ng/property/property.cpp", + "$ace_root/frameworks/core/components_ng/property/safe_area_insets.cpp", "$ace_root/frameworks/core/components_ng/syntax/lazy_for_each_node.cpp", "$ace_root/frameworks/core/components_v2/inspector/inspector_constants.cpp", diff --git a/frameworks/core/components_ng/test/event/input_event_hub/BUILD.gn b/frameworks/core/components_ng/test/event/input_event_hub/BUILD.gn index b5df2ab4b91..9d25da1f065 100644 --- a/frameworks/core/components_ng/test/event/input_event_hub/BUILD.gn +++ b/frameworks/core/components_ng/test/event/input_event_hub/BUILD.gn @@ -37,12 +37,14 @@ ohos_unittest("input_event_hub_test_ng") { "$ace_root/frameworks/core/components_ng/layout/layout_wrapper.cpp", "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_builder.cpp", "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_node.cpp", + "$ace_root/frameworks/core/components_ng/manager/safe_area/safe_area_manager.cpp", "$ace_root/frameworks/core/components_ng/pattern/custom/custom_node.cpp", "$ace_root/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp", "$ace_root/frameworks/core/components_ng/property/border_property.cpp", "$ace_root/frameworks/core/components_ng/property/calc_length.cpp", "$ace_root/frameworks/core/components_ng/property/measure_utils.cpp", "$ace_root/frameworks/core/components_ng/property/property.cpp", + "$ace_root/frameworks/core/components_ng/property/safe_area_insets.cpp", "$ace_root/frameworks/core/components_ng/syntax/lazy_for_each_node.cpp", "$ace_root/frameworks/core/components_v2/inspector/inspector_constants.cpp", diff --git a/frameworks/core/components_ng/test/event/long_press_event/BUILD.gn b/frameworks/core/components_ng/test/event/long_press_event/BUILD.gn index e026b83f404..e0873ce9a2d 100644 --- a/frameworks/core/components_ng/test/event/long_press_event/BUILD.gn +++ b/frameworks/core/components_ng/test/event/long_press_event/BUILD.gn @@ -39,12 +39,14 @@ ohos_unittest("long_press_event_test_ng") { "$ace_root/frameworks/core/components_ng/layout/layout_wrapper.cpp", "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_builder.cpp", "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_node.cpp", + "$ace_root/frameworks/core/components_ng/manager/safe_area/safe_area_manager.cpp", "$ace_root/frameworks/core/components_ng/pattern/custom/custom_node.cpp", "$ace_root/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp", "$ace_root/frameworks/core/components_ng/property/border_property.cpp", "$ace_root/frameworks/core/components_ng/property/calc_length.cpp", "$ace_root/frameworks/core/components_ng/property/measure_utils.cpp", "$ace_root/frameworks/core/components_ng/property/property.cpp", + "$ace_root/frameworks/core/components_ng/property/safe_area_insets.cpp", "$ace_root/frameworks/core/components_ng/syntax/lazy_for_each_node.cpp", "$ace_root/frameworks/core/components_v2/inspector/inspector_constants.cpp", diff --git a/frameworks/core/components_ng/test/event/mock/mock_scrollable_event.cpp b/frameworks/core/components_ng/test/event/mock/mock_scrollable_event.cpp index 34032c18ca5..2387e7ba2ea 100644 --- a/frameworks/core/components_ng/test/event/mock/mock_scrollable_event.cpp +++ b/frameworks/core/components_ng/test/event/mock/mock_scrollable_event.cpp @@ -20,10 +20,6 @@ ScrollableActuator::ScrollableActuator(const WeakPtr& gestureEv : gestureEventHub_(gestureEventHub) {} -void ScrollableActuator::CollectTouchTarget(const OffsetF& coordinateOffset, const PointF& localPoint, - const GetEventTargetImpl& getEventTargetImpl, TouchTestResult& result) -{} - void ScrollableActuator::AddScrollEdgeEffect(const Axis& axis, RefPtr& effect) {} diff --git a/frameworks/core/components_ng/test/event/pan_event/BUILD.gn b/frameworks/core/components_ng/test/event/pan_event/BUILD.gn index e3c8ee23dd1..b6a475ef831 100644 --- a/frameworks/core/components_ng/test/event/pan_event/BUILD.gn +++ b/frameworks/core/components_ng/test/event/pan_event/BUILD.gn @@ -44,12 +44,14 @@ ohos_unittest("pan_event_test_ng") { "$ace_root/frameworks/core/components_ng/layout/layout_wrapper.cpp", "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_builder.cpp", "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_node.cpp", + "$ace_root/frameworks/core/components_ng/manager/safe_area/safe_area_manager.cpp", "$ace_root/frameworks/core/components_ng/pattern/custom/custom_node.cpp", "$ace_root/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp", "$ace_root/frameworks/core/components_ng/property/border_property.cpp", "$ace_root/frameworks/core/components_ng/property/calc_length.cpp", "$ace_root/frameworks/core/components_ng/property/measure_utils.cpp", "$ace_root/frameworks/core/components_ng/property/property.cpp", + "$ace_root/frameworks/core/components_ng/property/safe_area_insets.cpp", "$ace_root/frameworks/core/components_ng/syntax/lazy_for_each_node.cpp", "$ace_root/frameworks/core/components_v2/inspector/inspector_constants.cpp", diff --git a/frameworks/core/components_ng/test/event/scrollable_event/BUILD.gn b/frameworks/core/components_ng/test/event/scrollable_event/BUILD.gn index 28b9078e28d..6091f4e9eae 100644 --- a/frameworks/core/components_ng/test/event/scrollable_event/BUILD.gn +++ b/frameworks/core/components_ng/test/event/scrollable_event/BUILD.gn @@ -44,12 +44,14 @@ ohos_unittest("scrollable_event_test_ng") { "$ace_root/frameworks/core/components_ng/layout/layout_wrapper.cpp", "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_builder.cpp", "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_node.cpp", + "$ace_root/frameworks/core/components_ng/manager/safe_area/safe_area_manager.cpp", "$ace_root/frameworks/core/components_ng/pattern/custom/custom_node.cpp", "$ace_root/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp", "$ace_root/frameworks/core/components_ng/property/border_property.cpp", "$ace_root/frameworks/core/components_ng/property/calc_length.cpp", "$ace_root/frameworks/core/components_ng/property/measure_utils.cpp", "$ace_root/frameworks/core/components_ng/property/property.cpp", + "$ace_root/frameworks/core/components_ng/property/safe_area_insets.cpp", "$ace_root/frameworks/core/components_ng/syntax/lazy_for_each_node.cpp", "$ace_root/frameworks/core/components_v2/inspector/inspector_constants.cpp", diff --git a/frameworks/core/components_ng/test/layout/layout_property/BUILD.gn b/frameworks/core/components_ng/test/layout/layout_property/BUILD.gn index 2ea25fd1061..cf54384f489 100755 --- a/frameworks/core/components_ng/test/layout/layout_property/BUILD.gn +++ b/frameworks/core/components_ng/test/layout/layout_property/BUILD.gn @@ -49,6 +49,7 @@ ohos_unittest("layout_property_test_ng") { "$ace_root/frameworks/core/components_ng/layout/layout_wrapper.cpp", "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_builder.cpp", "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_node.cpp", + "$ace_root/frameworks/core/components_ng/manager/safe_area/safe_area_manager.cpp", "$ace_root/frameworks/core/components_ng/pattern/custom/custom_node.cpp", "$ace_root/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp", "$ace_root/frameworks/core/components_ng/pattern/grid_container/grid_container_layout_property.cpp", @@ -57,6 +58,7 @@ ohos_unittest("layout_property_test_ng") { "$ace_root/frameworks/core/components_ng/property/grid_property.cpp", "$ace_root/frameworks/core/components_ng/property/measure_utils.cpp", "$ace_root/frameworks/core/components_ng/property/property.cpp", + "$ace_root/frameworks/core/components_ng/property/safe_area_insets.cpp", "$ace_root/frameworks/core/components_ng/syntax/lazy_for_each_node.cpp", "$ace_root/frameworks/core/components_ng/test/event/mock/mock_scrollable_event.cpp", "$ace_root/frameworks/core/components_ng/test/mock/animation/mock_geometry_transition.cpp", diff --git a/frameworks/core/components_ng/test/layout/layout_wrapper/layout_wrapper_test_ng.cpp b/frameworks/core/components_ng/test/layout/layout_wrapper/layout_wrapper_test_ng.cpp index 035ad22ed83..682c2713dea 100755 --- a/frameworks/core/components_ng/test/layout/layout_wrapper/layout_wrapper_test_ng.cpp +++ b/frameworks/core/components_ng/test/layout/layout_wrapper/layout_wrapper_test_ng.cpp @@ -25,8 +25,8 @@ #include "base/utils/utils.h" #include "core/components/common/layout/constants.h" #include "core/components_ng/base/frame_node.h" -#include "core/components_ng/layout/layout_wrapper_node.h" #include "core/components_ng/layout/layout_wrapper_builder.h" +#include "core/components_ng/layout/layout_wrapper_node.h" #include "core/components_ng/pattern/flex/flex_layout_algorithm.h" #include "core/components_ng/pattern/linear_layout/linear_layout_pattern.h" #include "core/components_ng/pattern/menu/wrapper/menu_wrapper_pattern.h" @@ -190,7 +190,7 @@ HWTEST_F(LayoutWrapperTestNg, LayoutWrapperTest001, TestSize.Level1) * @tc.expected: testWrapper->isActive_ is true. */ testWrapper = layoutWrapper->GetOrCreateChildByIndex(INDEX_NUM_0, TEST_TRUE); - + EXPECT_TRUE(AceType::DynamicCast(layoutWrapper->GetOrCreateChildByIndex(0))->isActive_); } @@ -1509,11 +1509,11 @@ HWTEST_F(LayoutWrapperTestNg, LayoutWrapperTest040, TestSize.Level1) auto pipeline = PipelineContext::GetCurrentContext(); EXPECT_TRUE(pipeline); auto [host, wrapper] = CreateNodeAndWrapper(V2::ROOT_ETS_TAG, 0); + host->GetLayoutProperty()->UpdateSafeAreaExpandOpts({ SAFE_AREA_TYPE_ALL, SAFE_AREA_EDGE_ALL }); auto manager = pipeline->GetSafeAreaManager(); - manager->AddWrapper(wrapper); - LayoutWrapperNode::SaveGeoState(); + wrapper->SaveGeoState(); EXPECT_EQ(wrapper->geometryNode_->GetFrameOffset(), OffsetF(0, 0)); EXPECT_EQ(manager->GetGeoRestoreNodes().size(), 1UL); EXPECT_TRUE(wrapper->geometryNode_->previousState_); @@ -1549,7 +1549,7 @@ HWTEST_F(LayoutWrapperTestNg, LayoutWrapperTest041, TestSize.Level1) * @tc.steps: step2. call ExpandSafeArea on a frame that overlaps with SafeAreaInset {top = (0, 1)}. * @tc.expected: frame is expanded. */ - layoutWrapper->ExpandSafeAreaInner(); + layoutWrapper->ExpandSafeArea(); EXPECT_EQ(layoutWrapper->geometryNode_->GetFrameOffset(), OffsetF(0, 0)); EXPECT_EQ(layoutWrapper->geometryNode_->GetFrameSize(), SizeF(RK356_WIDTH, RK356_HEIGHT + 1)); @@ -1559,7 +1559,7 @@ HWTEST_F(LayoutWrapperTestNg, LayoutWrapperTest041, TestSize.Level1) */ layoutWrapper->geometryNode_->SetFrameOffset({ 0, 5 }); layoutWrapper->geometryNode_->SetFrameSize({ RK356_WIDTH, RK356_HEIGHT }); - layoutWrapper->ExpandSafeAreaInner(); + layoutWrapper->ExpandSafeArea(); EXPECT_EQ(layoutWrapper->geometryNode_->GetFrameOffset(), OffsetF(0, 5)); EXPECT_EQ(layoutWrapper->geometryNode_->GetFrameSize(), SizeF(RK356_WIDTH, RK356_HEIGHT)); @@ -1569,7 +1569,7 @@ HWTEST_F(LayoutWrapperTestNg, LayoutWrapperTest041, TestSize.Level1) */ layoutWrapper->geometryNode_->SetFrameOffset({ 0, -1 }); layoutWrapper->geometryNode_->SetFrameSize({ RK356_WIDTH, RK356_HEIGHT + 2 }); - layoutWrapper->ExpandSafeAreaInner(); + layoutWrapper->ExpandSafeArea(); EXPECT_EQ(layoutWrapper->geometryNode_->GetFrameOffset(), OffsetF(0, -1)); EXPECT_EQ(layoutWrapper->geometryNode_->GetFrameSize(), SizeF(RK356_WIDTH, RK356_HEIGHT + 2)); @@ -1580,7 +1580,7 @@ HWTEST_F(LayoutWrapperTestNg, LayoutWrapperTest041, TestSize.Level1) layoutWrapper->geometryNode_->SetFrameOffset({ 0, 1 }); layoutWrapper->geometryNode_->SetFrameSize({ RK356_WIDTH, RK356_HEIGHT }); layoutWrapper->layoutProperty_->UpdateUserDefinedIdealSize({ CalcLength(RK356_WIDTH), CalcLength(RK356_HEIGHT) }); - layoutWrapper->ExpandSafeAreaInner(); + layoutWrapper->ExpandSafeArea(); EXPECT_EQ(layoutWrapper->geometryNode_->GetFrameOffset(), OffsetF(0, 0)); EXPECT_EQ(layoutWrapper->geometryNode_->GetFrameSize(), SizeF(RK356_WIDTH, RK356_HEIGHT)); } @@ -1609,4 +1609,28 @@ HWTEST_F(LayoutWrapperTestNg, LayoutWrapperTest042, TestSize.Level1) layoutWrapper->OffsetNodeToSafeArea(); EXPECT_EQ(layoutWrapper->geometryNode_->GetFrameOffset(), OffsetF(0, 1)); } + +/** + * @tc.name: LayoutWrapperTest043 + * @tc.desc: Test ExpandIntoKeyboard. + * @tc.type: FUNC + */ +HWTEST_F(LayoutWrapperTestNg, LayoutWrapperTest043, TestSize.Level1) +{ + auto [parent, layoutWrapper] = CreateNodeAndWrapper(ROW_FRAME_NODE, NODE_ID_0); + layoutWrapper->layoutProperty_->UpdateSafeAreaExpandOpts({ SAFE_AREA_TYPE_ALL, SAFE_AREA_EDGE_ALL }); + + auto [child, childWrapper] = CreateNodeAndWrapper(FIRST_CHILD_FRAME_NODE, NODE_ID_1); + child->layoutProperty_->UpdateSafeAreaExpandOpts({ SAFE_AREA_TYPE_ALL, SAFE_AREA_EDGE_ALL }); + child->MountToParent(parent); + + auto safeAreaManager = PipelineContext::GetCurrentContext()->safeAreaManager_; + safeAreaManager->UpdateKeyboardOffset(50.0f); + parent->ExpandIntoKeyboard(); + EXPECT_EQ(parent->GetGeometryNode()->GetFrameOffset(), OffsetF(0, -50.0f)); + + // parent already expanded + child->ExpandIntoKeyboard(); + EXPECT_EQ(child->GetGeometryNode()->GetFrameOffset(), OffsetF(0, 0)); +} } // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/test/manager/shared_overlay/BUILD.gn b/frameworks/core/components_ng/test/manager/shared_overlay/BUILD.gn index 20ff8b784df..5272257e0d5 100644 --- a/frameworks/core/components_ng/test/manager/shared_overlay/BUILD.gn +++ b/frameworks/core/components_ng/test/manager/shared_overlay/BUILD.gn @@ -45,6 +45,7 @@ ohos_unittest("shared_overlay_manager_test_ng") { "$ace_root/frameworks/core/components_ng/layout/layout_wrapper.cpp", "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_builder.cpp", "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_node.cpp", + "$ace_root/frameworks/core/components_ng/manager/safe_area/safe_area_manager.cpp", "$ace_root/frameworks/core/components_ng/manager/shared_overlay/shared_overlay_manager.cpp", "$ace_root/frameworks/core/components_ng/manager/shared_overlay/shared_transition_effect.cpp", "$ace_root/frameworks/core/components_ng/pattern/custom/custom_node.cpp", @@ -53,6 +54,7 @@ ohos_unittest("shared_overlay_manager_test_ng") { "$ace_root/frameworks/core/components_ng/property/calc_length.cpp", "$ace_root/frameworks/core/components_ng/property/measure_utils.cpp", "$ace_root/frameworks/core/components_ng/property/property.cpp", + "$ace_root/frameworks/core/components_ng/property/safe_area_insets.cpp", "$ace_root/frameworks/core/components_ng/syntax/lazy_for_each_node.cpp", "$ace_root/test/mock/frameworks/base/log/mock_jank_frame_report.cpp", diff --git a/frameworks/core/components_ng/test/mock/pattern/grid/mock_grid_pattern.cpp b/frameworks/core/components_ng/test/mock/pattern/grid/mock_grid_pattern.cpp index cf1a18b7c02..964445d427d 100644 --- a/frameworks/core/components_ng/test/mock/pattern/grid/mock_grid_pattern.cpp +++ b/frameworks/core/components_ng/test/mock/pattern/grid/mock_grid_pattern.cpp @@ -94,6 +94,11 @@ float GridPattern::EstimateHeight() const return 0.0f; } +float GridPattern::GetTotalHeight() const +{ + return 0.0f; +} + void GridPattern::OnAnimateStop() {} void GridPattern::ScrollTo(float position) {} diff --git a/frameworks/core/components_ng/test/mock/pattern/list/mock_list_pattern.cpp b/frameworks/core/components_ng/test/mock/pattern/list/mock_list_pattern.cpp index dc5596adbc2..efd6d7cf41d 100644 --- a/frameworks/core/components_ng/test/mock/pattern/list/mock_list_pattern.cpp +++ b/frameworks/core/components_ng/test/mock/pattern/list/mock_list_pattern.cpp @@ -91,14 +91,17 @@ bool ListPattern::OnScrollSnapCallback(double targetOffset, double velocity) return false; } -void ListPattern::OnWindowSizeChanged(int32_t width, int32_t height, WindowSizeChangeReason type) {} - void ListPattern::FireOnScrollStart() {} void ListPattern::OnAnimateStop() {} void ListPattern::ScrollTo(float position) {} +float ListPattern::GetTotalHeight() const +{ + return 0.0f; +} + void ListPattern::MultiSelectWithoutKeyboard(const RectF& selectedZone) {}; void ListPattern::ClearMultiSelect() {}; diff --git a/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_observed_property_simple_abstract.ts b/frameworks/core/components_ng/test/mock/rosen/testing_scalar.h similarity index 56% rename from frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_observed_property_simple_abstract.ts rename to frameworks/core/components_ng/test/mock/rosen/testing_scalar.h index 16c7e3babc0..af9eb0c516f 100644 --- a/frameworks/bridge/declarative_frontend/state_mgmt/src/lib/partial_update/pu_observed_property_simple_abstract.ts +++ b/frameworks/core/components_ng/test/mock/rosen/testing_scalar.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,14 +13,13 @@ * limitations under the License. */ -/** - * ObservedPropertySimpleAbstractPU - * - * all definitions in this file are framework internal - */ -abstract class ObservedPropertySimpleAbstractPU extends ObservedPropertyAbstractPU { +#ifndef FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_NG_MOCK_ROSEN_TEST_TESTING_SCALAR_H +#define FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_NG_MOCK_ROSEN_TEST_TESTING_SCALAR_H - constructor(owningView: IPropertySubscriber, propertyName: PropertyInfo) { - super(owningView, propertyName); - } +namespace OHOS::Ace::Testing { +inline float ConvertRadiusToSigma(float radius) +{ + return radius; } +} // namespace OHOS::Ace::Testing +#endif // FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_NG_MOCK_ROSEN_TEST_TESTING_SCALAR_H diff --git a/frameworks/core/components_ng/test/pattern/BUILD.gn b/frameworks/core/components_ng/test/pattern/BUILD.gn index 5228bcd39f9..3b98a6acfd0 100644 --- a/frameworks/core/components_ng/test/pattern/BUILD.gn +++ b/frameworks/core/components_ng/test/pattern/BUILD.gn @@ -27,11 +27,9 @@ group("pattern_unittest") { "container_modal:container_modal_test_ng", "counter:counter_pattern_test_ng", "custom:custom_test_ng", - "custom_dialog:custom_dialog_test_ng", "custom_paint:custom_paint_test_ng", "data_panel:data_panel_test_ng", - - #"dialog:dialog_pattern_test_ng", + "dialog:dialog_pattern_test_ng", "divider:divider_pattern_test_ng", "flex:flex_test_ng", "form:form_test_ng", diff --git a/frameworks/core/components_ng/test/pattern/app_bar/BUILD.gn b/frameworks/core/components_ng/test/pattern/app_bar/BUILD.gn index 7cf14806415..1d930cb9f6a 100644 --- a/frameworks/core/components_ng/test/pattern/app_bar/BUILD.gn +++ b/frameworks/core/components_ng/test/pattern/app_bar/BUILD.gn @@ -29,7 +29,7 @@ ace_unittest("app_bar_test_ng") { "$ace_root/frameworks/core/components_ng/test/mock/pattern/ui_extension/mock_ui_extension_model_ng.cpp", "$ace_root/frameworks/core/components_ng/test/mock/theme/mock_theme_constants.cpp", "$ace_root/frameworks/core/components_ng/test/pattern/image/mock/mock_image_pattern.cpp", - "$ace_root/test/mock/adapter/mock_ui_extension_helper_impl.cpp", + "$ace_root/test/mock/adapter/mock_app_bar_helper_impl.cpp", "$ace_root/test/mock/core/common/mock_font_manager_ng.cpp", "$ace_root/test/unittest/core/pipeline/mock_overlay_manager.cpp", diff --git a/frameworks/core/components_ng/test/pattern/app_bar/app_bar_test_ng.cpp b/frameworks/core/components_ng/test/pattern/app_bar/app_bar_test_ng.cpp index dd2d0edfdc3..aaa530ae5c9 100644 --- a/frameworks/core/components_ng/test/pattern/app_bar/app_bar_test_ng.cpp +++ b/frameworks/core/components_ng/test/pattern/app_bar/app_bar_test_ng.cpp @@ -134,7 +134,6 @@ HWTEST_F(AppBarTestNg, Test003, TestSize.Level1) ClickBtn(backBtn); auto shareBtn = AceType::DynamicCast(titleBar->GetChildAtIndex(2)); EXPECT_TRUE(shareBtn); - ClickBtn(shareBtn); SUCCEED(); } } // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/test/pattern/app_bar/mock_ui_extension_helper_impl.cpp b/frameworks/core/components_ng/test/pattern/app_bar/mock_app_bar_helper_impl.cpp similarity index 84% rename from frameworks/core/components_ng/test/pattern/app_bar/mock_ui_extension_helper_impl.cpp rename to frameworks/core/components_ng/test/pattern/app_bar/mock_app_bar_helper_impl.cpp index 45e9e65bbf9..9b69100c4a1 100644 --- a/frameworks/core/components_ng/test/pattern/app_bar/mock_ui_extension_helper_impl.cpp +++ b/frameworks/core/components_ng/test/pattern/app_bar/mock_app_bar_helper_impl.cpp @@ -13,11 +13,11 @@ * limitations under the License. */ -#include "core/common/ui_extension_helper.h" +#include "core/common/app_bar_helper.h" namespace OHOS::Ace { -RefPtr UIExtensionHelper::CreateUIExtensionNode(const std::string& bundleName, +RefPtr AppBarHelper::CreateUIExtensionNode(const std::string& bundleName, const std::string& abilityName, const std::map& params, std::function&& onRelease) { diff --git a/frameworks/core/components_ng/test/pattern/blank/BUILD.gn b/frameworks/core/components_ng/test/pattern/blank/BUILD.gn index 9103d6da4dc..03617e44317 100644 --- a/frameworks/core/components_ng/test/pattern/blank/BUILD.gn +++ b/frameworks/core/components_ng/test/pattern/blank/BUILD.gn @@ -14,114 +14,9 @@ import("//build/test.gni") import("//foundation/arkui/ace_engine/test/unittest/ace_unittest.gni") -ohos_unittest("blank_pattern_test_ng") { - module_out_path = pattern_test_output_path - +ace_unittest("blank_pattern_test_ng") { sources = [ "$ace_root/frameworks/core/components_ng/pattern/blank/blank_model_ng.cpp", "$ace_root/frameworks/core/components_ng/pattern/blank/blank_pattern.cpp", - - # inheritance relationship - "$ace_root/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/pattern/linear_layout/column_model_ng.cpp", - "$ace_root/frameworks/core/components_ng/pattern/linear_layout/linear_layout_utils.cpp", - "$ace_root/frameworks/core/components_ng/pattern/linear_layout/row_model_ng.cpp", - "blank_pattern_test_ng.cpp", ] - - sources += [ - # base - "$ace_root/frameworks/base/geometry/dimension.cpp", - "$ace_root/frameworks/base/json/json_util.cpp", - "$ace_root/frameworks/base/utils/base_id.cpp", - "$ace_root/frameworks/base/utils/string_expression.cpp", - "$ace_root/frameworks/base/utils/string_utils.cpp", - "$ace_root/frameworks/base/utils/time_util.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_node.cpp", - "$ace_root/frameworks/core/components_ng/pattern/custom/custom_node.cpp", - "$ace_root/frameworks/core/components_ng/syntax/lazy_for_each_node.cpp", - - # components - "$ace_root/frameworks/core/components/common/layout/grid_column_info.cpp", - "$ace_root/frameworks/core/components/common/layout/grid_container_info.cpp", - "$ace_root/frameworks/core/components/common/layout/grid_system_manager.cpp", - "$ace_root/frameworks/core/components/common/layout/screen_system_manager.cpp", - "$ace_root/frameworks/core/components/common/properties/alignment.cpp", - "$ace_root/frameworks/core/components/common/properties/color.cpp", - - # components_ng - "$ace_root/frameworks/core/components_ng/base/frame_node.cpp", - "$ace_root/frameworks/core/components_ng/base/geometry_node.cpp", - "$ace_root/frameworks/core/components_ng/base/modifier.cpp", - "$ace_root/frameworks/core/components_ng/base/ui_node.cpp", - "$ace_root/frameworks/core/components_ng/base/view_stack_processor.cpp", - "$ace_root/frameworks/core/components_ng/event/click_event.cpp", - "$ace_root/frameworks/core/components_ng/event/drag_event.cpp", - "$ace_root/frameworks/core/components_ng/event/event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/focus_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/gesture_event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/input_event.cpp", - "$ace_root/frameworks/core/components_ng/event/input_event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/pan_event.cpp", - "$ace_root/frameworks/core/components_ng/event/state_style_manager.cpp", - "$ace_root/frameworks/core/components_ng/event/touch_event.cpp", - "$ace_root/frameworks/core/components_ng/gestures/gesture_referee.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/click_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/exclusive_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/gesture_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/long_press_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/multi_fingers_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/pan_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/parallel_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/recognizer_group.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/sequenced_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/layout/box_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_property.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_builder.cpp", - "$ace_root/frameworks/core/components_ng/manager/safe_area/safe_area_manager.cpp", - "$ace_root/frameworks/core/components_ng/property/border_property.cpp", - "$ace_root/frameworks/core/components_ng/property/calc_length.cpp", - "$ace_root/frameworks/core/components_ng/property/grid_property.cpp", - "$ace_root/frameworks/core/components_ng/property/measure_utils.cpp", - "$ace_root/frameworks/core/components_ng/property/property.cpp", - "$ace_root/frameworks/core/components_ng/property/safe_area_insets.cpp", - "$ace_root/frameworks/core/components_ng/render/drawing_prop_convertor.cpp", - "$ace_root/frameworks/core/components_ng/render/paint_wrapper.cpp", - - # components_v2 - "$ace_root/frameworks/core/components_v2/inspector/inspector_constants.cpp", - - # pipeline - "$ace_root/frameworks/core/pipeline/base/constants.cpp", - - # mock - "$ace_root/frameworks/base/test/mock/mock_ressched_report.cpp", - "$ace_root/frameworks/base/test/mock/mock_socperf_client_impl.cpp", - "$ace_root/frameworks/base/test/mock/mock_system_properties.cpp", - "$ace_root/frameworks/core/common/test/mock/mock_ace_application_info.cpp", - "$ace_root/frameworks/core/components/test/unittest/mock/ace_trace_mock.cpp", - "$ace_root/frameworks/core/components_ng/test/event/mock/mock_scrollable_event.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/animation/mock_geometry_transition.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/base/mock_localization.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/grid_container/mock_grid_container_layout_property.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_animation_utils.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_modifier_adapter.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_context.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_context_creator.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_surface_creator.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/syntax/mock_for_each_node.cpp", - "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_element_register.cpp", - "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_pipeline_base.cpp", - ] - - deps = [ - "$ace_root/frameworks/base:ace_memory_monitor_ohos", - "$ace_root/frameworks/core/components/theme:build_theme_code", - "$ace_root/test/unittest:ace_unittest_log", - "$cjson_root:cjson_static", - "//third_party/googletest:gmock_main", - ] - - configs = [ "$ace_root/test/unittest:ace_unittest_config" ] } diff --git a/frameworks/core/components_ng/test/pattern/calendar/BUILD.gn b/frameworks/core/components_ng/test/pattern/calendar/BUILD.gn index a70afc820a5..336183bc477 100644 --- a/frameworks/core/components_ng/test/pattern/calendar/BUILD.gn +++ b/frameworks/core/components_ng/test/pattern/calendar/BUILD.gn @@ -14,39 +14,37 @@ import("//build/test.gni") import("//foundation/arkui/ace_engine/test/unittest/ace_unittest.gni") -ohos_unittest("calendar_pattern_test_ng") { - module_out_path = pattern_test_output_path - +ace_unittest("calendar_pattern_test_ng") { + ace_animation = true + flutter_skia = true sources = [ - # animation - "$ace_root/frameworks/base/geometry/least_square_impl.cpp", - "$ace_root/frameworks/base/geometry/matrix3.cpp", - "$ace_root/frameworks/base/geometry/matrix4.cpp", - "$ace_root/frameworks/base/utils/time_util.cpp", - "$ace_root/frameworks/core/animation/animatable_data.cpp", - "$ace_root/frameworks/core/animation/animatable_properties.cpp", - "$ace_root/frameworks/core/animation/anticipate_curve.cpp", - "$ace_root/frameworks/core/animation/cubic_curve.cpp", - "$ace_root/frameworks/core/animation/curves.cpp", - "$ace_root/frameworks/core/animation/friction_motion.cpp", - "$ace_root/frameworks/core/animation/property_animation.cpp", - "$ace_root/frameworks/core/animation/scheduler.cpp", - "$ace_root/frameworks/core/animation/scroll_motion.cpp", - "$ace_root/frameworks/core/animation/spring_curve.cpp", - "$ace_root/frameworks/core/animation/spring_model.cpp", - "$ace_root/frameworks/core/animation/spring_motion.cpp", - "$ace_root/frameworks/core/animation/test/mock/mock_animator.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_node.cpp", - "$ace_root/frameworks/core/components_ng/pattern/custom/custom_node.cpp", - "$ace_root/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/syntax/lazy_for_each_node.cpp", + # text + "$ace_root/frameworks/core/components_ng/pattern/text/image_span_view.cpp", + "$ace_root/frameworks/core/components_ng/pattern/text/span_model_ng.cpp", + "$ace_root/frameworks/core/components_ng/pattern/text/span_node.cpp", + "$ace_root/frameworks/core/components_ng/pattern/text/text_accessibility_property.cpp", + "$ace_root/frameworks/core/components_ng/pattern/text/text_content_modifier.cpp", + "$ace_root/frameworks/core/components_ng/pattern/text/text_layout_algorithm.cpp", + "$ace_root/frameworks/core/components_ng/pattern/text/text_layout_property.cpp", + "$ace_root/frameworks/core/components_ng/pattern/text/text_model_ng.cpp", + "$ace_root/frameworks/core/components_ng/pattern/text/text_overlay_modifier.cpp", + "$ace_root/frameworks/core/components_ng/pattern/text/text_paint_method.cpp", + "$ace_root/frameworks/core/components_ng/pattern/text/text_pattern.cpp", + "$ace_root/frameworks/core/components_ng/pattern/text/text_styles.cpp", - # inner - "$ace_root/frameworks/core/components_ng/pattern/calendar/calendar_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/pattern/calendar/calendar_model_ng.cpp", - "$ace_root/frameworks/core/components_ng/pattern/calendar/calendar_month_pattern.cpp", - "$ace_root/frameworks/core/components_ng/pattern/calendar/calendar_paint_method.cpp", - "$ace_root/frameworks/core/components_ng/pattern/calendar/calendar_pattern.cpp", + #button + "$ace_root/frameworks/core/components_ng/pattern/button/button_layout_algorithm.cpp", + "$ace_root/frameworks/core/components_ng/pattern/button/button_pattern.cpp", + "$ace_root/frameworks/core/components_ng/pattern/button/toggle_button_pattern.cpp", + + # image + "$ace_root/frameworks/core/components_ng/pattern/image/image_layout_algorithm.cpp", + "$ace_root/frameworks/core/components_ng/pattern/image/image_model_ng.cpp", + "$ace_root/frameworks/core/components_ng/pattern/image/image_modifier.cpp", + "$ace_root/frameworks/core/components_ng/pattern/image/image_paint_method.cpp", + "$ace_root/frameworks/core/components_ng/pattern/image/image_pattern.cpp", + + # swiper "$ace_root/frameworks/core/components_ng/pattern/swiper/swiper_accessibility_property.cpp", "$ace_root/frameworks/core/components_ng/pattern/swiper/swiper_layout_algorithm.cpp", "$ace_root/frameworks/core/components_ng/pattern/swiper/swiper_model_ng.cpp", @@ -58,113 +56,38 @@ ohos_unittest("calendar_pattern_test_ng") { "$ace_root/frameworks/core/components_ng/pattern/swiper_indicator/dot_indicator/dot_indicator_modifier.cpp", "$ace_root/frameworks/core/components_ng/pattern/swiper_indicator/dot_indicator/dot_indicator_paint_method.cpp", "$ace_root/frameworks/core/components_ng/pattern/swiper_indicator/indicator_common/swiper_arrow_layout_algorithm.cpp", + "$ace_root/frameworks/core/components_ng/pattern/swiper_indicator/indicator_common/swiper_arrow_pattern.cpp", "$ace_root/frameworks/core/components_ng/pattern/swiper_indicator/indicator_common/swiper_indicator_pattern.cpp", - "$ace_root/frameworks/core/components_ng/property/accessibility_property.cpp", - "$ace_root/frameworks/core/components_ng/test/event/mock/mock_scrollable_event.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/swiper_indicator/mock_swiper_arrow_pattern.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/text/mock_overlay_modifier.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/text/mock_text_accessibility_property.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/text/mock_text_content_modifier.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/text/mock_text_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/text/mock_text_layout_property.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/text/mock_text_paint_method.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/text/mock_text_pattern.cpp", - "$ace_root/frameworks/core/gestures/velocity_tracker.cpp", - # self - "calendar_pattern_test_ng.cpp", - ] - - sources += [ - # base - "$ace_root/frameworks/base/geometry/dimension.cpp", - "$ace_root/frameworks/base/json/json_util.cpp", - "$ace_root/frameworks/base/utils/base_id.cpp", - "$ace_root/frameworks/base/utils/string_expression.cpp", - "$ace_root/frameworks/base/utils/string_utils.cpp", - - # components - "$ace_root/frameworks/core/components/common/layout/grid_column_info.cpp", - "$ace_root/frameworks/core/components/common/layout/grid_container_info.cpp", - "$ace_root/frameworks/core/components/common/layout/grid_system_manager.cpp", - "$ace_root/frameworks/core/components/common/layout/screen_system_manager.cpp", - "$ace_root/frameworks/core/components/common/properties/alignment.cpp", - "$ace_root/frameworks/core/components/common/properties/color.cpp", - - # components_ng - "$ace_root/frameworks/core/components_ng/base/frame_node.cpp", - "$ace_root/frameworks/core/components_ng/base/geometry_node.cpp", - "$ace_root/frameworks/core/components_ng/base/modifier.cpp", - "$ace_root/frameworks/core/components_ng/base/ui_node.cpp", - "$ace_root/frameworks/core/components_ng/base/view_stack_processor.cpp", - "$ace_root/frameworks/core/components_ng/event/click_event.cpp", - "$ace_root/frameworks/core/components_ng/event/drag_event.cpp", - "$ace_root/frameworks/core/components_ng/event/event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/focus_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/gesture_event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/input_event.cpp", - "$ace_root/frameworks/core/components_ng/event/input_event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/pan_event.cpp", - "$ace_root/frameworks/core/components_ng/event/state_style_manager.cpp", - "$ace_root/frameworks/core/components_ng/event/touch_event.cpp", - "$ace_root/frameworks/core/components_ng/gestures/gesture_referee.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/click_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/exclusive_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/gesture_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/long_press_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/multi_fingers_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/pan_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/parallel_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/recognizer_group.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/sequenced_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/layout/box_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_property.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_builder.cpp", - "$ace_root/frameworks/core/components_ng/manager/safe_area/safe_area_manager.cpp", - "$ace_root/frameworks/core/components_ng/property/border_property.cpp", - "$ace_root/frameworks/core/components_ng/property/calc_length.cpp", - "$ace_root/frameworks/core/components_ng/property/grid_property.cpp", - "$ace_root/frameworks/core/components_ng/property/measure_utils.cpp", - "$ace_root/frameworks/core/components_ng/property/property.cpp", - "$ace_root/frameworks/core/components_ng/property/safe_area_insets.cpp", - "$ace_root/frameworks/core/components_ng/render/drawing_prop_convertor.cpp", - "$ace_root/frameworks/core/components_ng/render/paint_wrapper.cpp", - - # components_v2 - "$ace_root/frameworks/core/components_v2/inspector/inspector_constants.cpp", - - # pipeline - "$ace_root/frameworks/core/pipeline/base/constants.cpp", + # select_overlay + "$ace_root/frameworks/core/components_ng/manager/select_overlay/select_overlay_manager.cpp", + "$ace_root/frameworks/core/components_ng/manager/select_overlay/select_overlay_proxy.cpp", + "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_layout_algorithm.cpp", + "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_modifier.cpp", + "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_paint_method.cpp", + "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_pattern.cpp", + "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_property.cpp", + "$ace_root/frameworks/core/components_ng/test/mock/pattern/popup/mock_popup_base_pattern.cpp", + "$ace_root/frameworks/core/components_ng/test/mock/pattern/select_overlay/mock_select_overlay_node.cpp", # mock - "$ace_root/frameworks/base/test/mock/mock_ressched_report.cpp", - "$ace_root/frameworks/base/test/mock/mock_socperf_client_impl.cpp", - "$ace_root/frameworks/base/test/mock/mock_system_properties.cpp", - "$ace_root/frameworks/core/common/container_scope.cpp", - "$ace_root/frameworks/core/common/test/mock/mock_ace_application_info.cpp", - "$ace_root/frameworks/core/components/test/unittest/mock/ace_trace_mock.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/animation/mock_geometry_transition.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/base/mock_localization.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/grid_container/mock_grid_container_layout_property.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_animation_utils.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_modifier_adapter.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_context.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_context_creator.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_surface_creator.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/syntax/mock_for_each_node.cpp", - "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_element_register.cpp", - "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_pipeline_base.cpp", - "$ace_root/test/mock/core/common/mock_container.cpp", - ] + "$ace_root/frameworks/core/components_ng/test/mock/manager/drag_drop/mock_drag_drop_proxy.cpp", + "$ace_root/test/mock/core/common/mock_font_manager_ng.cpp", + "$ace_root/test/unittest/core/pipeline/mock_drag_drop_manager.cpp", - deps = [ - "$ace_root/frameworks/base:ace_memory_monitor_ohos", - "$ace_root/frameworks/core/components/theme:build_theme_code", - "$ace_root/test/unittest:ace_unittest_log", - "$cjson_root:cjson_static", - "//third_party/googletest:gmock_main", - ] + # other + "$ace_root/frameworks/core/animation/spring_curve.cpp", + "$ace_root/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp", + "$ace_root/frameworks/core/components_ng/pattern/grid_container/grid_container_layout_property.cpp", - configs = [ "$ace_root/test/unittest:ace_unittest_config" ] + # self + "$ace_root/frameworks/core/components_ng/pattern/calendar/calendar_controller_model_ng.cpp", + "$ace_root/frameworks/core/components_ng/pattern/calendar/calendar_controller_ng.cpp", + "$ace_root/frameworks/core/components_ng/pattern/calendar/calendar_layout_algorithm.cpp", + "$ace_root/frameworks/core/components_ng/pattern/calendar/calendar_model_ng.cpp", + "$ace_root/frameworks/core/components_ng/pattern/calendar/calendar_month_pattern.cpp", + "$ace_root/frameworks/core/components_ng/pattern/calendar/calendar_paint_method.cpp", + "$ace_root/frameworks/core/components_ng/pattern/calendar/calendar_pattern.cpp", + "calendar_pattern_test_ng.cpp", + ] } diff --git a/frameworks/core/components_ng/test/pattern/calendar_picker/BUILD.gn b/frameworks/core/components_ng/test/pattern/calendar_picker/BUILD.gn index d3f475fa413..9908b9ee704 100644 --- a/frameworks/core/components_ng/test/pattern/calendar_picker/BUILD.gn +++ b/frameworks/core/components_ng/test/pattern/calendar_picker/BUILD.gn @@ -28,7 +28,6 @@ ace_unittest("calendar_picker_test_ng") { # inner "$ace_root/frameworks/base/utils/date_util.cpp", "$ace_root/frameworks/core/components/picker/picker_data.cpp", - "$ace_root/frameworks/core/components_ng/manager/safe_area/safe_area_manager.cpp", "$ace_root/frameworks/core/components_ng/pattern/calendar/calendar_layout_algorithm.cpp", "$ace_root/frameworks/core/components_ng/pattern/calendar/calendar_model_ng.cpp", "$ace_root/frameworks/core/components_ng/pattern/calendar/calendar_month_pattern.cpp", diff --git a/frameworks/core/components_ng/test/pattern/checkbox/BUILD.gn b/frameworks/core/components_ng/test/pattern/checkbox/BUILD.gn index 4e4631f8320..c859643a75f 100644 --- a/frameworks/core/components_ng/test/pattern/checkbox/BUILD.gn +++ b/frameworks/core/components_ng/test/pattern/checkbox/BUILD.gn @@ -14,108 +14,16 @@ import("//build/test.gni") import("//foundation/arkui/ace_engine/test/unittest/ace_unittest.gni") -ohos_unittest("checkbox_test_ng") { - module_out_path = pattern_test_output_path - +ace_unittest("checkbox_test_ng") { + ace_animation = true sources = [ - # inner - "$ace_root/frameworks/base/geometry/dimension.cpp", - "$ace_root/frameworks/base/json/json_util.cpp", - "$ace_root/frameworks/base/utils/string_expression.cpp", - "$ace_root/frameworks/base/utils/string_utils.cpp", - "$ace_root/frameworks/base/utils/time_util.cpp", - "$ace_root/frameworks/core/components/common/layout/grid_column_info.cpp", - "$ace_root/frameworks/core/components/common/layout/grid_container_info.cpp", - "$ace_root/frameworks/core/components/common/layout/grid_system_manager.cpp", - "$ace_root/frameworks/core/components/common/layout/screen_system_manager.cpp", - "$ace_root/frameworks/core/components/common/properties/alignment.cpp", - "$ace_root/frameworks/core/components/common/properties/color.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_node.cpp", - "$ace_root/frameworks/core/components_ng/pattern/custom/custom_node.cpp", + # other + "$ace_root/frameworks/core/animation/spring_curve.cpp", "$ace_root/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/property/safe_area_insets.cpp", - "$ace_root/frameworks/core/components_ng/syntax/lazy_for_each_node.cpp", - "$ace_root/frameworks/core/components_v2/inspector/inspector_constants.cpp", - "$ace_root/frameworks/core/pipeline/base/constants.cpp", - - # components_ng_manager - "$ace_root/frameworks/core/components_ng/manager/safe_area/safe_area_manager.cpp", - - # animation - "$ace_root/frameworks/base/utils/base_id.cpp", - "$ace_root/frameworks/core/animation/anticipate_curve.cpp", - "$ace_root/frameworks/core/animation/cubic_curve.cpp", - "$ace_root/frameworks/core/animation/curves.cpp", - "$ace_root/frameworks/core/animation/scheduler.cpp", - - # components_ng_base - "$ace_root/frameworks/core/components_ng/base/frame_node.cpp", - "$ace_root/frameworks/core/components_ng/base/geometry_node.cpp", - "$ace_root/frameworks/core/components_ng/base/modifier.cpp", - "$ace_root/frameworks/core/components_ng/base/ui_node.cpp", - "$ace_root/frameworks/core/components_ng/base/view_abstract.cpp", - "$ace_root/frameworks/core/components_ng/base/view_stack_processor.cpp", - - # components_ng_layout - "$ace_root/frameworks/core/components_ng/layout/box_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_property.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_builder.cpp", - - # components_ng_property - "$ace_root/frameworks/core/components_ng/property/border_property.cpp", - "$ace_root/frameworks/core/components_ng/property/calc_length.cpp", - "$ace_root/frameworks/core/components_ng/property/grid_property.cpp", - "$ace_root/frameworks/core/components_ng/property/measure_utils.cpp", - "$ace_root/frameworks/core/components_ng/property/property.cpp", - - # components_ng_pattern "$ace_root/frameworks/core/components_ng/pattern/grid_container/grid_container_layout_property.cpp", "$ace_root/frameworks/core/components_ng/pattern/stage/page_event_hub.cpp", "$ace_root/frameworks/core/components_ng/pattern/stage/page_pattern.cpp", - # components_ng_render - "$ace_root/frameworks/core/components_ng/render/paint_wrapper.cpp", - - # components_ng_syntax - "$ace_root/frameworks/core/components_ng/syntax/for_each_node.cpp", - - # components_ng_event - "$ace_root/frameworks/core/components_ng/event/click_event.cpp", - "$ace_root/frameworks/core/components_ng/event/event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/focus_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/gesture_event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/input_event.cpp", - "$ace_root/frameworks/core/components_ng/event/input_event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/state_style_manager.cpp", - "$ace_root/frameworks/core/components_ng/event/touch_event.cpp", - - # components_ng_gestures - "$ace_root/frameworks/core/components_ng/gestures/gesture_referee.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/click_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/exclusive_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/gesture_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/multi_fingers_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/parallel_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/recognizer_group.cpp", - - # mock - "$ace_root/frameworks/base/test/mock/mock_ressched_report.cpp", - "$ace_root/frameworks/base/test/mock/mock_socperf_client_impl.cpp", - "$ace_root/frameworks/base/test/mock/mock_system_properties.cpp", - "$ace_root/frameworks/core/animation/test/mock/mock_animator.cpp", - "$ace_root/frameworks/core/common/test/mock/mock_ace_application_info.cpp", - "$ace_root/frameworks/core/components_ng/test/event/mock/mock_scrollable_event.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/animation/mock_geometry_transition.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_animation_utils.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_drawing_convertor.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_modifier_adapter.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_context.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_context_creator.cpp", - "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_element_register.cpp", - "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_pipeline_base.cpp", - "$ace_root/test/mock/core/common/mock_container.cpp", - # self "$ace_root/frameworks/core/components_ng/pattern/checkbox/checkbox_accessibility_property.cpp", "$ace_root/frameworks/core/components_ng/pattern/checkbox/checkbox_layout_algorithm.cpp", @@ -132,14 +40,4 @@ ohos_unittest("checkbox_test_ng") { "checkbox_test_ng.cpp", "mock_stage_manager.cpp", ] - - deps = [ - "$ace_root/frameworks/base:ace_memory_monitor_ohos", - "$ace_root/test/unittest:ace_unittest_log", - "$ace_root/test/unittest:ace_unittest_trace", - "$cjson_root:cjson_static", - "//third_party/googletest:gmock_main", - ] - - configs = [ "$ace_root/test/unittest:ace_unittest_config" ] } diff --git a/frameworks/core/components_ng/test/pattern/checkboxgroup/BUILD.gn b/frameworks/core/components_ng/test/pattern/checkboxgroup/BUILD.gn index ca6274b7df2..68b7bfeec79 100644 --- a/frameworks/core/components_ng/test/pattern/checkboxgroup/BUILD.gn +++ b/frameworks/core/components_ng/test/pattern/checkboxgroup/BUILD.gn @@ -14,108 +14,16 @@ import("//build/test.gni") import("//foundation/arkui/ace_engine/test/unittest/ace_unittest.gni") -ohos_unittest("checkboxgroup_test_ng") { - module_out_path = pattern_test_output_path - +ace_unittest("checkboxgroup_test_ng") { + ace_animation = true sources = [ - # inner - "$ace_root/frameworks/base/geometry/dimension.cpp", - "$ace_root/frameworks/base/json/json_util.cpp", - "$ace_root/frameworks/base/utils/string_expression.cpp", - "$ace_root/frameworks/base/utils/string_utils.cpp", - "$ace_root/frameworks/base/utils/time_util.cpp", - "$ace_root/frameworks/core/components/common/layout/grid_column_info.cpp", - "$ace_root/frameworks/core/components/common/layout/grid_container_info.cpp", - "$ace_root/frameworks/core/components/common/layout/grid_system_manager.cpp", - "$ace_root/frameworks/core/components/common/layout/screen_system_manager.cpp", - "$ace_root/frameworks/core/components/common/properties/alignment.cpp", - "$ace_root/frameworks/core/components/common/properties/color.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_node.cpp", - "$ace_root/frameworks/core/components_ng/pattern/custom/custom_node.cpp", + # other + "$ace_root/frameworks/core/animation/spring_curve.cpp", "$ace_root/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/property/safe_area_insets.cpp", - "$ace_root/frameworks/core/components_ng/syntax/lazy_for_each_node.cpp", - "$ace_root/frameworks/core/components_ng/test/event/mock/mock_scrollable_event.cpp", - "$ace_root/frameworks/core/components_v2/inspector/inspector_constants.cpp", - "$ace_root/frameworks/core/pipeline/base/constants.cpp", - - # components_ng_manager - "$ace_root/frameworks/core/components_ng/manager/safe_area/safe_area_manager.cpp", - - # animation - "$ace_root/frameworks/base/utils/base_id.cpp", - "$ace_root/frameworks/core/animation/anticipate_curve.cpp", - "$ace_root/frameworks/core/animation/cubic_curve.cpp", - "$ace_root/frameworks/core/animation/curves.cpp", - "$ace_root/frameworks/core/animation/scheduler.cpp", - - # components_ng_base - "$ace_root/frameworks/core/components_ng/base/frame_node.cpp", - "$ace_root/frameworks/core/components_ng/base/geometry_node.cpp", - "$ace_root/frameworks/core/components_ng/base/modifier.cpp", - "$ace_root/frameworks/core/components_ng/base/ui_node.cpp", - "$ace_root/frameworks/core/components_ng/base/view_abstract.cpp", - "$ace_root/frameworks/core/components_ng/base/view_stack_processor.cpp", - - # components_ng_layout - "$ace_root/frameworks/core/components_ng/layout/box_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_property.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_builder.cpp", - - # components_ng_property - "$ace_root/frameworks/core/components_ng/property/border_property.cpp", - "$ace_root/frameworks/core/components_ng/property/calc_length.cpp", - "$ace_root/frameworks/core/components_ng/property/grid_property.cpp", - "$ace_root/frameworks/core/components_ng/property/measure_utils.cpp", - "$ace_root/frameworks/core/components_ng/property/property.cpp", - - # components_ng_pattern "$ace_root/frameworks/core/components_ng/pattern/grid_container/grid_container_layout_property.cpp", "$ace_root/frameworks/core/components_ng/pattern/stage/page_event_hub.cpp", "$ace_root/frameworks/core/components_ng/pattern/stage/page_pattern.cpp", - # components_ng_render - "$ace_root/frameworks/core/components_ng/render/paint_wrapper.cpp", - - # components_ng_syntax - "$ace_root/frameworks/core/components_ng/syntax/for_each_node.cpp", - - # components_ng_event - "$ace_root/frameworks/core/components_ng/event/click_event.cpp", - "$ace_root/frameworks/core/components_ng/event/event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/focus_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/gesture_event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/input_event.cpp", - "$ace_root/frameworks/core/components_ng/event/input_event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/state_style_manager.cpp", - "$ace_root/frameworks/core/components_ng/event/touch_event.cpp", - - # components_ng_gestures - "$ace_root/frameworks/core/components_ng/gestures/gesture_referee.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/click_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/exclusive_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/gesture_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/multi_fingers_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/parallel_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/recognizer_group.cpp", - - # mock - "$ace_root/frameworks/base/test/mock/mock_ressched_report.cpp", - "$ace_root/frameworks/base/test/mock/mock_socperf_client_impl.cpp", - "$ace_root/frameworks/base/test/mock/mock_system_properties.cpp", - "$ace_root/frameworks/core/animation/test/mock/mock_animator.cpp", - "$ace_root/frameworks/core/common/test/mock/mock_ace_application_info.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/animation/mock_geometry_transition.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_animation_utils.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_drawing_convertor.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_modifier_adapter.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_context.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_context_creator.cpp", - "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_element_register.cpp", - "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_pipeline_base.cpp", - "$ace_root/test/mock/core/common/mock_container.cpp", - # self "$ace_root/frameworks/core/components_ng/pattern/checkbox/checkbox_accessibility_property.cpp", "$ace_root/frameworks/core/components_ng/pattern/checkbox/checkbox_layout_algorithm.cpp", @@ -132,14 +40,4 @@ ohos_unittest("checkboxgroup_test_ng") { "checkboxgroup_test_ng.cpp", "mock_stage_manager.cpp", ] - - deps = [ - "$ace_root/frameworks/base:ace_memory_monitor_ohos", - "$ace_root/test/unittest:ace_unittest_log", - "$ace_root/test/unittest:ace_unittest_trace", - "$cjson_root:cjson_static", - "//third_party/googletest:gmock_main", - ] - - configs = [ "$ace_root/test/unittest:ace_unittest_config" ] } diff --git a/frameworks/core/components_ng/test/pattern/container_modal/BUILD.gn b/frameworks/core/components_ng/test/pattern/container_modal/BUILD.gn index 74a235a936b..5be16a35f04 100644 --- a/frameworks/core/components_ng/test/pattern/container_modal/BUILD.gn +++ b/frameworks/core/components_ng/test/pattern/container_modal/BUILD.gn @@ -14,98 +14,11 @@ import("//build/test.gni") import("//foundation/arkui/ace_engine/test/unittest/ace_unittest.gni") -ohos_unittest("container_modal_test_ng") { - module_out_path = pattern_test_output_path - +ace_unittest("container_modal_test_ng") { + ace_animation = true sources = [ - "$ace_root/adapter/preview/osal/ressched_report.cpp", - "$ace_root/frameworks/base/geometry/dimension.cpp", - "$ace_root/frameworks/base/geometry/least_square_impl.cpp", - "$ace_root/frameworks/base/geometry/matrix3.cpp", - "$ace_root/frameworks/base/geometry/matrix4.cpp", - "$ace_root/frameworks/base/json/json_util.cpp", - "$ace_root/frameworks/base/ressched/ressched_report.cpp", - "$ace_root/frameworks/base/utils/base_id.cpp", - "$ace_root/frameworks/base/utils/string_expression.cpp", - "$ace_root/frameworks/base/utils/string_utils.cpp", - "$ace_root/frameworks/base/utils/time_util.cpp", - "$ace_root/frameworks/core/common/clipboard/clipboard_proxy.cpp", - "$ace_root/frameworks/core/common/container_scope.cpp", - "$ace_root/frameworks/core/components/common/layout/grid_column_info.cpp", - "$ace_root/frameworks/core/components/common/layout/grid_container_info.cpp", - "$ace_root/frameworks/core/components/common/layout/grid_system_manager.cpp", - "$ace_root/frameworks/core/components/common/layout/screen_system_manager.cpp", - "$ace_root/frameworks/core/components/common/properties/alignment.cpp", - "$ace_root/frameworks/core/components/common/properties/color.cpp", - "$ace_root/frameworks/core/components/common/properties/shadow_config.cpp", - "$ace_root/frameworks/core/components/common/properties/text_style.cpp", - "$ace_root/frameworks/core/components/font/constants_converter.cpp", - "$ace_root/frameworks/core/components_ng/base/frame_node.cpp", - "$ace_root/frameworks/core/components_ng/base/geometry_node.cpp", - "$ace_root/frameworks/core/components_ng/base/modifier.cpp", - "$ace_root/frameworks/core/components_ng/base/ui_node.cpp", - "$ace_root/frameworks/core/components_ng/base/view_abstract.cpp", - "$ace_root/frameworks/core/components_ng/event/click_event.cpp", - "$ace_root/frameworks/core/components_ng/event/drag_event.cpp", - "$ace_root/frameworks/core/components_ng/event/event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/focus_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/gesture_event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/input_event.cpp", - "$ace_root/frameworks/core/components_ng/event/input_event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/long_press_event.cpp", - "$ace_root/frameworks/core/components_ng/event/pan_event.cpp", - "$ace_root/frameworks/core/components_ng/event/state_style_manager.cpp", - "$ace_root/frameworks/core/components_ng/event/touch_event.cpp", - "$ace_root/frameworks/core/components_ng/gestures/gesture_referee.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/click_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/exclusive_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/gesture_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/long_press_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/multi_fingers_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/pan_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/parallel_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/recognizer_group.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/sequenced_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/layout/box_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_property.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_builder.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_node.cpp", - "$ace_root/frameworks/core/components_ng/manager/safe_area/safe_area_manager.cpp", - "$ace_root/frameworks/core/components_ng/manager/select_overlay/select_overlay_manager.cpp", - "$ace_root/frameworks/core/components_ng/manager/select_overlay/select_overlay_proxy.cpp", - "$ace_root/frameworks/core/components_ng/pattern/button/button_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/pattern/button/button_pattern.cpp", - "$ace_root/frameworks/core/components_ng/pattern/button/toggle_button_accessibility_property.cpp", - "$ace_root/frameworks/core/components_ng/pattern/button/toggle_button_pattern.cpp", - "$ace_root/frameworks/core/components_ng/pattern/custom/custom_node.cpp", - "$ace_root/frameworks/core/components_ng/pattern/divider/divider_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/pattern/divider/divider_pattern.cpp", - "$ace_root/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/pattern/grid_container/grid_container_layout_property.cpp", - "$ace_root/frameworks/core/components_ng/pattern/image/image_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/pattern/image/image_model_ng.cpp", - "$ace_root/frameworks/core/components_ng/pattern/image/image_modifier.cpp", - "$ace_root/frameworks/core/components_ng/pattern/image/image_paint_method.cpp", - "$ace_root/frameworks/core/components_ng/pattern/navigation/bar_item_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/pattern/navigation/bar_item_node.cpp", - "$ace_root/frameworks/core/components_ng/pattern/navigation/bar_item_pattern.cpp", - "$ace_root/frameworks/core/components_ng/pattern/navigation/nav_bar_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/pattern/navigation/nav_bar_node.cpp", - "$ace_root/frameworks/core/components_ng/pattern/navigation/nav_bar_pattern.cpp", - "$ace_root/frameworks/core/components_ng/pattern/navigation/navigation_group_node.cpp", - "$ace_root/frameworks/core/components_ng/pattern/navigation/navigation_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/pattern/navigation/navigation_model_ng.cpp", - "$ace_root/frameworks/core/components_ng/pattern/navigation/navigation_pattern.cpp", - "$ace_root/frameworks/core/components_ng/pattern/navigation/title_bar_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/pattern/navigation/title_bar_node.cpp", - "$ace_root/frameworks/core/components_ng/pattern/navigation/title_bar_pattern.cpp", - "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_modifier.cpp", - "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_paint_method.cpp", - "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_pattern.cpp", - "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_property.cpp", - "$ace_root/frameworks/core/components_ng/pattern/stack/stack_layout_algorithm.cpp", + # text + "$ace_root/frameworks/core/components_ng/pattern/text/image_span_view.cpp", "$ace_root/frameworks/core/components_ng/pattern/text/span_model_ng.cpp", "$ace_root/frameworks/core/components_ng/pattern/text/span_node.cpp", "$ace_root/frameworks/core/components_ng/pattern/text/text_accessibility_property.cpp", @@ -117,53 +30,42 @@ ohos_unittest("container_modal_test_ng") { "$ace_root/frameworks/core/components_ng/pattern/text/text_paint_method.cpp", "$ace_root/frameworks/core/components_ng/pattern/text/text_pattern.cpp", "$ace_root/frameworks/core/components_ng/pattern/text/text_styles.cpp", - "$ace_root/frameworks/core/components_ng/property/border_property.cpp", - "$ace_root/frameworks/core/components_ng/property/calc_length.cpp", - "$ace_root/frameworks/core/components_ng/property/grid_property.cpp", - "$ace_root/frameworks/core/components_ng/property/measure_utils.cpp", - "$ace_root/frameworks/core/components_ng/property/property.cpp", - "$ace_root/frameworks/core/components_ng/property/safe_area_insets.cpp", - "$ace_root/frameworks/core/components_ng/render/divider_painter.cpp", - "$ace_root/frameworks/core/components_ng/render/paint_wrapper.cpp", - "$ace_root/frameworks/core/components_ng/syntax/lazy_for_each_node.cpp", - "$ace_root/frameworks/core/components_ng/test/event/mock/mock_scrollable_event.cpp", + + #button + "$ace_root/frameworks/core/components_ng/pattern/button/button_layout_algorithm.cpp", + "$ace_root/frameworks/core/components_ng/pattern/button/button_pattern.cpp", + "$ace_root/frameworks/core/components_ng/pattern/button/toggle_button_pattern.cpp", + + # image + "$ace_root/frameworks/core/components_ng/pattern/image/image_layout_algorithm.cpp", + "$ace_root/frameworks/core/components_ng/pattern/image/image_model_ng.cpp", + "$ace_root/frameworks/core/components_ng/pattern/image/image_modifier.cpp", + "$ace_root/frameworks/core/components_ng/pattern/image/image_paint_method.cpp", + "$ace_root/frameworks/core/components_ng/pattern/image/image_pattern.cpp", + + # select_overlay + "$ace_root/frameworks/core/components_ng/manager/select_overlay/select_overlay_manager.cpp", + "$ace_root/frameworks/core/components_ng/manager/select_overlay/select_overlay_proxy.cpp", + "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_layout_algorithm.cpp", + "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_modifier.cpp", + "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_paint_method.cpp", + "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_pattern.cpp", + "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_property.cpp", "$ace_root/frameworks/core/components_ng/test/mock/pattern/popup/mock_popup_base_pattern.cpp", - "$ace_root/frameworks/core/components_ng/test/pattern/image/mock/mock_image_pattern.cpp", - "$ace_root/frameworks/core/components_v2/inspector/inspector_constants.cpp", - "$ace_root/frameworks/core/gestures/velocity_tracker.cpp", + "$ace_root/frameworks/core/components_ng/test/mock/pattern/select_overlay/mock_select_overlay_node.cpp", # mock - "$ace_root/frameworks/base/test/mock/mock_drag_window.cpp", - "$ace_root/frameworks/base/test/mock/mock_pixel_map.cpp", - "$ace_root/frameworks/base/test/mock/mock_socperf_client_impl.cpp", - "$ace_root/frameworks/base/test/mock/mock_system_properties.cpp", - "$ace_root/frameworks/core/animation/anticipate_curve.cpp", - "$ace_root/frameworks/core/animation/cubic_curve.cpp", - "$ace_root/frameworks/core/animation/curves.cpp", - "$ace_root/frameworks/core/common/test/mock/mock_ace_application_info.cpp", - "$ace_root/frameworks/core/components/test/mock/mock_resource_adapter.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/animation/mock_geometry_transition.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/base/mock_localization.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/base/mock_view_stack_processor.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/image_provider/mock_image_loading_context.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/image_provider/mock_image_painter.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/image_provider/mock_image_source_info.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/manager/drag_drop/mock_drag_drop_manager.cpp", "$ace_root/frameworks/core/components_ng/test/mock/manager/drag_drop/mock_drag_drop_proxy.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/select_overlay/mock_select_overlay_node.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_animation_utils.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_drawing_convertor.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_modifier_adapter.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_context.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_context_creator.cpp", "$ace_root/frameworks/core/components_ng/test/mock/theme/mock_theme_constants.cpp", - "$ace_root/frameworks/core/components_ng/test/pattern/text/mock/mock_text_layout_adapter.cpp", - "$ace_root/frameworks/core/components_ng/test/pattern/text/mock/mock_txt_font_collection.cpp", - "$ace_root/frameworks/core/components_ng/test/pattern/text/mock/mock_txt_paragraph.cpp", - "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_element_register.cpp", - "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_pipeline_base.cpp", - "$ace_root/test/mock/core/common/mock_container.cpp", + "$ace_root/frameworks/core/components_ng/test/mock/theme/mock_theme_utils.cpp", + "$ace_root/frameworks/core/components_ng/test/pattern/test_ng.cpp", "$ace_root/test/mock/core/common/mock_font_manager_ng.cpp", + "$ace_root/test/unittest/core/pipeline/mock_drag_drop_manager.cpp", + + # other + "$ace_root/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp", + "$ace_root/frameworks/core/components_ng/pattern/grid_container/grid_container_layout_property.cpp", + "$ace_root/frameworks/core/components_ng/pattern/stack/stack_layout_algorithm.cpp", # self "$ace_root/frameworks/core/components_ng/pattern/container_modal/container_modal_accessibility_property.cpp", @@ -171,15 +73,4 @@ ohos_unittest("container_modal_test_ng") { "$ace_root/frameworks/core/components_ng/pattern/container_modal/container_modal_view.cpp", "container_modal_test_ng.cpp", ] - - deps = [ - "$ace_root/frameworks/base:ace_memory_monitor_ohos", - "$ace_root/test/unittest:ace_engine_unittest_flutter_deps", - "$ace_root/test/unittest:ace_unittest_log", - "$ace_root/test/unittest:ace_unittest_trace", - "$cjson_root:cjson_static", - "//third_party/googletest:gmock_main", - ] - - configs = [ "$ace_root/test/unittest:ace_unittest_config" ] } diff --git a/frameworks/core/components_ng/test/pattern/container_modal/container_modal_test_ng.cpp b/frameworks/core/components_ng/test/pattern/container_modal/container_modal_test_ng.cpp index fab893c2120..5968d59405c 100644 --- a/frameworks/core/components_ng/test/pattern/container_modal/container_modal_test_ng.cpp +++ b/frameworks/core/components_ng/test/pattern/container_modal/container_modal_test_ng.cpp @@ -33,6 +33,7 @@ #include "core/components_ng/pattern/text/text_pattern.h" #include "core/components_ng/test/mock/render/mock_render_context.h" #include "core/components_ng/test/mock/theme/mock_theme_manager.h" +#include "core/components_ng/test/pattern/test_ng.h" #include "core/pipeline_ng/pipeline_context.h" #include "core/pipeline_ng/test/mock/mock_pipeline_base.h" @@ -40,20 +41,15 @@ using namespace testing; using namespace testing::ext; namespace OHOS::Ace::NG { namespace { -constexpr float DEVICE_WIDTH = 480.f; -constexpr float DEVICE_HEIGHT = 800.f; constexpr double MOUSE_MOVE_POPUP_DISTANCE = 5.0; // 5.0px } // namespace -class ContainerModelTestNg : public testing::Test { +class ContainerModelTestNg : public testing::Test, public TestNG { protected: static void SetUpTestSuite(); static void TearDownTestSuite(); void SetUp() override; void TearDown() override; void GetInstance(); - RefPtr RunMeasureAndLayout(float width = DEVICE_WIDTH, float height = DEVICE_HEIGHT); - static void SetWidth(const Dimension& width); - static void SetHeight(const Dimension& height); RefPtr CreateContent(); void SetMockWindow(WindowMode windowMode); void CreateContainerModal(); @@ -108,35 +104,6 @@ void ContainerModelTestNg::GetInstance() accessibilityProperty_ = frameNode_->GetAccessibilityProperty(); } -RefPtr ContainerModelTestNg::RunMeasureAndLayout(float width, float height) -{ - RefPtr layoutWrapper = frameNode_->CreateLayoutWrapper(false, false); - layoutWrapper->SetActive(); - LayoutConstraintF LayoutConstraint; - LayoutConstraint.parentIdealSize = { DEVICE_WIDTH, DEVICE_HEIGHT }; - LayoutConstraint.percentReference = { DEVICE_WIDTH, DEVICE_HEIGHT }; - LayoutConstraint.selfIdealSize = { width, height }; - LayoutConstraint.maxSize = { width, height }; - layoutWrapper->Measure(LayoutConstraint); - layoutWrapper->Layout(); - layoutWrapper->MountToHostOnMainThread(); - return layoutWrapper; -} - -void ContainerModelTestNg::SetWidth(const Dimension& width) -{ - auto frameNode = ViewStackProcessor::GetInstance()->GetMainFrameNode(); - auto layoutProperty = frameNode->GetLayoutProperty(); - layoutProperty->UpdateUserDefinedIdealSize(CalcSize(CalcLength(width), std::nullopt)); -} - -void ContainerModelTestNg::SetHeight(const Dimension& height) -{ - auto frameNode = ViewStackProcessor::GetInstance()->GetMainFrameNode(); - auto layoutProperty = frameNode->GetLayoutProperty(); - layoutProperty->UpdateUserDefinedIdealSize(CalcSize(std::nullopt, CalcLength(height))); -} - RefPtr ContainerModelTestNg::CreateContent() { return AceType::MakeRefPtr("content", 0, AceType::MakeRefPtr()); @@ -158,7 +125,7 @@ void ContainerModelTestNg::CreateContainerModal() auto frameNode = view.Create(content); ViewStackProcessor::GetInstance()->Push(frameNode); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); } void ContainerModelTestNg::Touch(TouchLocationInfo locationInfo) diff --git a/frameworks/core/components_ng/test/pattern/counter/BUILD.gn b/frameworks/core/components_ng/test/pattern/counter/BUILD.gn index cb4ddf94214..5d36655293f 100644 --- a/frameworks/core/components_ng/test/pattern/counter/BUILD.gn +++ b/frameworks/core/components_ng/test/pattern/counter/BUILD.gn @@ -12,141 +12,54 @@ # limitations under the License. import("//build/test.gni") -import("//foundation/arkui/ace_engine/ace_config.gni") import("//foundation/arkui/ace_engine/test/unittest/ace_unittest.gni") -ohos_unittest("counter_pattern_test_ng") { - module_out_path = pattern_test_output_path - - include_dirs = [ - "//commonlibrary/c_utils/base/include", - "//foundation/graphic/graphic_2d/rosen/modules/2d_graphics/include", - ] - +ace_unittest("counter_pattern_test_ng") { + ace_animation = true sources = [ - # inner - "$ace_root/frameworks/base/geometry/dimension.cpp", - "$ace_root/frameworks/base/geometry/matrix4.cpp", - "$ace_root/frameworks/base/json/json_util.cpp", - "$ace_root/frameworks/base/ressched/ressched_report.cpp", - "$ace_root/frameworks/base/utils/base_id.cpp", - "$ace_root/frameworks/base/utils/string_expression.cpp", - "$ace_root/frameworks/base/utils/string_utils.cpp", - "$ace_root/frameworks/base/utils/time_util.cpp", - "$ace_root/frameworks/core/animation/anticipate_curve.cpp", - "$ace_root/frameworks/core/animation/cubic_curve.cpp", - "$ace_root/frameworks/core/animation/curves.cpp", - "$ace_root/frameworks/core/components/common/properties/alignment.cpp", - "$ace_root/frameworks/core/components/common/properties/border_image.cpp", - "$ace_root/frameworks/core/components/common/properties/color.cpp", - "$ace_root/frameworks/core/components_ng/base/view_abstract.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_node.cpp", - "$ace_root/frameworks/core/components_ng/pattern/custom/custom_node.cpp", - "$ace_root/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp", + # text + "$ace_root/frameworks/core/components_ng/pattern/text/image_span_view.cpp", + "$ace_root/frameworks/core/components_ng/pattern/text/span_model_ng.cpp", + "$ace_root/frameworks/core/components_ng/pattern/text/span_node.cpp", "$ace_root/frameworks/core/components_ng/pattern/text/text_accessibility_property.cpp", "$ace_root/frameworks/core/components_ng/pattern/text/text_content_modifier.cpp", + "$ace_root/frameworks/core/components_ng/pattern/text/text_layout_algorithm.cpp", "$ace_root/frameworks/core/components_ng/pattern/text/text_layout_property.cpp", + "$ace_root/frameworks/core/components_ng/pattern/text/text_model_ng.cpp", "$ace_root/frameworks/core/components_ng/pattern/text/text_overlay_modifier.cpp", "$ace_root/frameworks/core/components_ng/pattern/text/text_paint_method.cpp", + "$ace_root/frameworks/core/components_ng/pattern/text/text_pattern.cpp", "$ace_root/frameworks/core/components_ng/pattern/text/text_styles.cpp", - "$ace_root/frameworks/core/components_ng/property/safe_area_insets.cpp", - "$ace_root/frameworks/core/components_ng/render/render_context.cpp", - "$ace_root/frameworks/core/components_ng/syntax/lazy_for_each_node.cpp", - "$ace_root/frameworks/core/components_v2/inspector/inspector_constants.cpp", - "$ace_root/frameworks/core/gestures/velocity_tracker.cpp", - # components_ng_manager - "$ace_root/frameworks/core/components_ng/manager/safe_area/safe_area_manager.cpp", - - # components_ng_base - "$ace_root/frameworks/core/components_ng/base/frame_node.cpp", - "$ace_root/frameworks/core/components_ng/base/geometry_node.cpp", - "$ace_root/frameworks/core/components_ng/base/modifier.cpp", - "$ace_root/frameworks/core/components_ng/base/ui_node.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/base/mock_view_stack_processor.cpp", - - # components_ng_layout - "$ace_root/frameworks/core/components_ng/layout/box_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_property.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_builder.cpp", - - # components_ng_property - "$ace_root/frameworks/core/components_ng/property/border_property.cpp", - "$ace_root/frameworks/core/components_ng/property/calc_length.cpp", - "$ace_root/frameworks/core/components_ng/property/measure_utils.cpp", - "$ace_root/frameworks/core/components_ng/property/property.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/property/mock_grid_property.cpp", - - # components_ng_pattern - "$ace_root/frameworks/core/components_ng/pattern/grid_container/grid_container_layout_property.cpp", - - # components_ng_event - "$ace_root/frameworks/core/components_ng/event/click_event.cpp", - "$ace_root/frameworks/core/components_ng/event/drag_event.cpp", - "$ace_root/frameworks/core/components_ng/event/event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/input_event.cpp", - "$ace_root/frameworks/core/components_ng/event/input_event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/long_press_event.cpp", - "$ace_root/frameworks/core/components_ng/event/pan_event.cpp", - "$ace_root/frameworks/core/components_ng/event/state_style_manager.cpp", - "$ace_root/frameworks/core/components_ng/event/touch_event.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/event/mock_focus_hub.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/event/mock_gesture_event_hub.cpp", - - # components_ng_gestures - "$ace_root/frameworks/core/components_ng/gestures/gesture_referee.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/gesture/recognizers/mock_click_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/gesture/recognizers/mock_exclusive_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/gesture/recognizers/mock_gesture_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/gesture/recognizers/mock_long_press_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/gesture/recognizers/mock_pan_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/gesture/recognizers/mock_parallel_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/gesture/recognizers/mock_recognizer_group.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/gesture/recognizers/mock_sequenced_recognizer.cpp", - - # mock - "$ace_root/frameworks/base/test/mock/mock_animatable_dimension.cpp", - "$ace_root/frameworks/base/test/mock/mock_system_properties.cpp", - "$ace_root/frameworks/core/animation/test/mock/mock_animator.cpp", - "$ace_root/frameworks/core/animation/test/mock/mock_scheduler.cpp", - "$ace_root/frameworks/core/common/test/mock/mock_ace_application_info.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/animation/mock_geometry_transition.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/base/mock_localization.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/text/mock_text_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/text/mock_text_pattern.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_animation_utils.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_drawing_convertor.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_modifier_adapter.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_context_creator.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_property.cpp", - "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_element_register.cpp", - "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_pipeline_base.cpp", - "$ace_root/test/mock/core/common/mock_container.cpp", - "$ace_root/test/mock/core/common/mock_font_manager_ng.cpp", - - # self - "$ace_root//frameworks/core/components_ng/pattern/counter/counter_node.cpp", + #button "$ace_root/frameworks/core/components_ng/pattern/button/button_layout_algorithm.cpp", "$ace_root/frameworks/core/components_ng/pattern/button/button_pattern.cpp", - "$ace_root/frameworks/core/components_ng/pattern/button/toggle_button_accessibility_property.cpp", "$ace_root/frameworks/core/components_ng/pattern/button/toggle_button_pattern.cpp", + + # select_overlay + "$ace_root/frameworks/core/components_ng/manager/select_overlay/select_overlay_manager.cpp", + "$ace_root/frameworks/core/components_ng/manager/select_overlay/select_overlay_proxy.cpp", + "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_layout_algorithm.cpp", + "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_modifier.cpp", + "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_paint_method.cpp", + "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_pattern.cpp", + "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_property.cpp", + "$ace_root/frameworks/core/components_ng/test/mock/pattern/popup/mock_popup_base_pattern.cpp", + "$ace_root/frameworks/core/components_ng/test/mock/pattern/select_overlay/mock_select_overlay_node.cpp", + + # mock + "$ace_root/frameworks/core/components_ng/test/mock/manager/drag_drop/mock_drag_drop_proxy.cpp", + "$ace_root/test/mock/core/common/mock_font_manager_ng.cpp", + "$ace_root/test/unittest/core/pipeline/mock_drag_drop_manager.cpp", + + # other + "$ace_root/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp", + "$ace_root/frameworks/core/components_ng/pattern/grid_container/grid_container_layout_property.cpp", + + # self "$ace_root/frameworks/core/components_ng/pattern/counter/counter_layout_algorithm.cpp", "$ace_root/frameworks/core/components_ng/pattern/counter/counter_model_ng.cpp", + "$ace_root/frameworks/core/components_ng/pattern/counter/counter_node.cpp", "counter_pattern_test_ng.cpp", ] - - deps = [ - "$ace_root/frameworks/base:ace_memory_monitor_ohos", - "$ace_root/test/unittest:ace_unittest_log", - "$ace_root/test/unittest:ace_unittest_trace", - "$cjson_root:cjson", - "//third_party/googletest:gmock_main", - ] - - configs = [ - "$ace_root/test/unittest:ace_unittest_config", - - "//commonlibrary/c_utils/base:utils_config", - ] } diff --git a/frameworks/core/components_ng/test/pattern/custom_dialog/BUILD.gn b/frameworks/core/components_ng/test/pattern/custom_dialog/BUILD.gn deleted file mode 100644 index 43ff79df7da..00000000000 --- a/frameworks/core/components_ng/test/pattern/custom_dialog/BUILD.gn +++ /dev/null @@ -1,208 +0,0 @@ -# Copyright (c) 2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/test.gni") -import("//foundation/arkui/ace_engine/ace_config.gni") -import("//foundation/arkui/ace_engine/test/unittest/ace_unittest.gni") -import("$ace_root/frameworks/core/components_ng/components.gni") - -ohos_unittest("custom_dialog_test_ng") { - module_out_path = pattern_test_output_path - - include_dirs = [ - "$ace_hitrace/interfaces/native/innerkits/include/hitrace_meter", - "$ace_graphic/rosen/modules/2d_graphics/src/drawing/engine_adapter", - "$ace_graphic/rosen/modules/2d_engine/rosen_text", - "$ace_graphic/rosen/modules/2d_engine/rosen_text/properties", - "$ace_graphic/rosen/modules/2d_engine", - "$ace_root/frameworks/base/log", - "$ace_root/frameworks/base/geometry", - "$ace_root/frameworks/base/memory", - ] - - sources = [ - # inner - "$ace_root/adapter/ohos/osal/ace_trace.cpp", - "$ace_root/adapter/ohos/osal/log_wrapper.cpp", - "$ace_root/frameworks/base/geometry/dimension.cpp", - "$ace_root/frameworks/base/json/json_util.cpp", - "$ace_root/frameworks/base/log/ace_trace.cpp", - "$ace_root/frameworks/base/log/dump_log.cpp", - "$ace_root/frameworks/base/memory/memory_monitor.cpp", - "$ace_root/frameworks/base/utils/base_id.cpp", - "$ace_root/frameworks/base/utils/string_expression.cpp", - "$ace_root/frameworks/base/utils/string_utils.cpp", - "$ace_root/frameworks/base/utils/time_util.cpp", - "$ace_root/frameworks/core/animation/anticipate_curve.cpp", - "$ace_root/frameworks/core/animation/cubic_curve.cpp", - "$ace_root/frameworks/core/animation/curves.cpp", - "$ace_root/frameworks/core/animation/spring_model.cpp", - "$ace_root/frameworks/core/animation/spring_motion.cpp", - "$ace_root/frameworks/core/common/container_scope.cpp", - "$ace_root/frameworks/core/components/common/layout/grid_column_info.cpp", - "$ace_root/frameworks/core/components/common/layout/grid_container_info.cpp", - "$ace_root/frameworks/core/components/common/layout/grid_system_manager.cpp", - "$ace_root/frameworks/core/components/common/layout/screen_system_manager.cpp", - "$ace_root/frameworks/core/components/common/properties/alignment.cpp", - "$ace_root/frameworks/core/components/common/properties/color.cpp", - "$ace_root/frameworks/core/components_ng/base/geometry_node.cpp", - "$ace_root/frameworks/core/components_ng/base/modifier.cpp", - "$ace_root/frameworks/core/components_ng/event/event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/state_style_manager.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/multi_fingers_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_node.cpp", - "$ace_root/frameworks/core/components_ng/pattern/custom/custom_node.cpp", - "$ace_root/frameworks/core/components_ng/pattern/dialog/dialog_accessibility_property.cpp", - "$ace_root/frameworks/core/components_ng/pattern/dialog/dialog_event_hub.cpp", - "$ace_root/frameworks/core/components_ng/pattern/dialog/dialog_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/pattern/dialog/dialog_pattern.cpp", - "$ace_root/frameworks/core/components_ng/pattern/dialog/dialog_view.cpp", - "$ace_root/frameworks/core/components_ng/pattern/divider/divider_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/pattern/divider/divider_modifier.cpp", - "$ace_root/frameworks/core/components_ng/pattern/divider/divider_pattern.cpp", - "$ace_root/frameworks/core/components_ng/pattern/image/image_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/pattern/image/image_modifier.cpp", - "$ace_root/frameworks/core/components_ng/pattern/image/image_paint_method.cpp", - "$ace_root/frameworks/core/components_ng/pattern/list/list_item_accessibility_property.cpp", - "$ace_root/frameworks/core/components_ng/pattern/list/list_item_event_hub.cpp", - "$ace_root/frameworks/core/components_ng/pattern/list/list_item_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/pattern/list/list_item_layout_property.cpp", - "$ace_root/frameworks/core/components_ng/pattern/list/list_item_pattern.cpp", - "$ace_root/frameworks/core/components_ng/pattern/list/list_layout_property.cpp", - "$ace_root/frameworks/core/components_ng/pattern/relative_container/relative_container_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/pattern/relative_container/relative_container_view.cpp", - "$ace_root/frameworks/core/components_ng/pattern/text/span_node.cpp", - "$ace_root/frameworks/core/components_ng/pattern/text/text_accessibility_property.cpp", - "$ace_root/frameworks/core/components_ng/pattern/text/text_content_modifier.cpp", - "$ace_root/frameworks/core/components_ng/pattern/text/text_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/pattern/text/text_layout_property.cpp", - "$ace_root/frameworks/core/components_ng/pattern/text/text_overlay_modifier.cpp", - "$ace_root/frameworks/core/components_ng/pattern/text/text_paint_method.cpp", - "$ace_root/frameworks/core/components_ng/pattern/text/text_styles.cpp", - "$ace_root/frameworks/core/components_ng/property/border_property.cpp", - "$ace_root/frameworks/core/components_ng/property/calc_length.cpp", - "$ace_root/frameworks/core/components_ng/property/measure_utils.cpp", - "$ace_root/frameworks/core/components_ng/property/property.cpp", - "$ace_root/frameworks/core/components_ng/property/safe_area_insets.cpp", - "$ace_root/frameworks/core/components_ng/render/divider_painter.cpp", - "$ace_root/frameworks/core/components_ng/render/drawing_prop_convertor.cpp", - "$ace_root/frameworks/core/components_ng/syntax/lazy_for_each_node.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/popup/mock_popup_base_pattern.cpp", - "$ace_root/frameworks/core/components_ng/test/pattern/image/mock/mock_image_pattern.cpp", - "$ace_root/frameworks/core/components_v2/inspector/inspector_constants.cpp", - - # components_ng_manager - "$ace_root/frameworks/core/components_ng/manager/safe_area/safe_area_manager.cpp", - - # components_ng_base - "$ace_root/frameworks/core/components_ng/base/frame_node.cpp", - "$ace_root/frameworks/core/components_ng/base/ui_node.cpp", - - # components_ng_layout - "$ace_root/frameworks/core/components_ng/layout/box_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_property.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_builder.cpp", - - # components_ng_property - "$ace_root/frameworks/core/components_ng/property/grid_property.cpp", - - # components_ng_pattern - "$ace_root/frameworks/core/components_ng/pattern/grid_container/grid_container_layout_property.cpp", - "$ace_root/frameworks/core/components_ng/pattern/scroll/inner/scroll_bar.cpp", - "$ace_root/frameworks/core/components_ng/pattern/scroll/scroll_accessibility_property.cpp", - "$ace_root/frameworks/core/components_ng/pattern/scroll/scroll_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/pattern/scroll/scroll_model_ng.cpp", - "$ace_root/frameworks/core/components_ng/pattern/scroll/scroll_paint_method.cpp", - "$ace_root/frameworks/core/components_ng/pattern/scroll/scroll_pattern.cpp", - "$ace_root/frameworks/core/components_ng/pattern/scroll_bar/proxy/scroll_bar_proxy.cpp", - "$ace_root/frameworks/core/components_ng/pattern/scroll_bar/scroll_bar_pattern.cpp", - - # components_ng_event - "$ace_root/frameworks/core/components_ng/event/click_event.cpp", - "$ace_root/frameworks/core/components_ng/event/drag_event.cpp", - "$ace_root/frameworks/core/components_ng/event/gesture_event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/input_event.cpp", - "$ace_root/frameworks/core/components_ng/event/input_event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/pan_event.cpp", - - # components_ng_gestures - "$ace_root/frameworks/core/components_ng/gestures/gesture_referee.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/gesture_recognizer.cpp", - - # mock - "$ace_root/frameworks/base/test/mock/mock_animatable_dimension.cpp", - "$ace_root/frameworks/base/test/mock/mock_subwindow_manager.cpp", - "$ace_root/frameworks/base/test/mock/mock_system_properties.cpp", - "$ace_root/frameworks/core/animation/test/mock/mock_animator.cpp", - "$ace_root/frameworks/core/animation/test/mock/mock_scheduler.cpp", - "$ace_root/frameworks/core/common/test/mock/mock_ace_application_info.cpp", - "$ace_root/frameworks/core/components_ng/test/event/mock/mock_scrollable_event.cpp", - "$ace_root/frameworks/core/components_ng/test/event/mock/mock_touch_event.cpp", - "$ace_root/frameworks/core/components_ng/test/event/scrollable_event/mock_scrollable.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/animation/mock_geometry_transition.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/base/mock_localization.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/base/mock_view_stack_processor.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/event/mock_focus_hub.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/gesture/recognizers/mock_click_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/gesture/recognizers/mock_exclusive_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/gesture/recognizers/mock_pan_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/gesture/recognizers/mock_parallel_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/gesture/recognizers/mock_recognizer_group.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/image_provider/mock_image_loading_context.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/image_provider/mock_image_painter.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/image_provider/mock_image_source_info.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/button/mock_button_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/button/mock_button_pattern.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/flex/mock_flex_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/list/mock_list_accessibility_property.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/list/mock_list_event_hub.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/list/mock_list_paint_method.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/list/mock_list_pattern.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/scroll/mock_scroll_bar_painter.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/scroll/mock_scroll_fade_painter.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/scrollable/mock_scrollable_pattern.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/text/mock_text_pattern.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_animation_utils.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_modifier_adapter.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_context.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_context_creator.cpp", - "$ace_root/frameworks/core/components_ng/test/pattern/image/mock_icon_theme.cpp", - "$ace_root/frameworks/core/components_ng/test/pattern/text/mock/mock_text_layout_adapter.cpp", - "$ace_root/frameworks/core/components_ng/test/pattern/text/mock/mock_txt_font_collection.cpp", - "$ace_root/frameworks/core/components_ng/test/pattern/text/mock/mock_txt_paragraph.cpp", - "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_element_register.cpp", - "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_pipeline_base.cpp", - "$ace_root/test/mock/core/common/mock_container.cpp", - "$ace_root/test/mock/core/common/mock_font_manager_ng.cpp", - "$ace_root/test/unittest/core/pipeline/mock_overlay_manager.cpp", - - # self - "custom_dialog_test_ng.cpp", - ] - - deps = [ - "$ace_graphic/rosen/modules/2d_graphics:2d_graphics", - "$ace_graphic/rosen/modules/render_service_client:librender_service_client", - "$ace_root/test/unittest:ace_engine_unittest_flutter_deps", - "$cjson_root:cjson", - "//third_party/googletest:gmock_main", - ] - - external_deps = [ - "hilog:libhilog", - "hitrace:hitrace_meter", - ] - - configs = [ "$ace_root/test/unittest:ace_unittest_config" ] -} diff --git a/frameworks/core/components_ng/test/pattern/custom_dialog/custom_dialog_test_ng.cpp b/frameworks/core/components_ng/test/pattern/custom_dialog/custom_dialog_test_ng.cpp deleted file mode 100644 index bdbadc98166..00000000000 --- a/frameworks/core/components_ng/test/pattern/custom_dialog/custom_dialog_test_ng.cpp +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include - -#include "gtest/gtest.h" - -#include "core/components_ng/pattern/overlay/overlay_manager.h" -#include "core/components_ng/test/mock/theme/mock_theme_manager.h" -#include "core/components_v2/inspector/inspector_constants.h" -#include "core/pipeline_ng/test/mock/mock_pipeline_base.h" -#define private public -#define protected public -#include "core/components_ng/pattern/dialog/dialog_pattern.h" -#include "core/components_ng/pattern/dialog/dialog_view.h" -#undef private -#undef protected -using namespace testing; -using namespace testing::ext; -namespace OHOS::Ace::NG { -class CustomDialogTestNg : public testing::Test { -public: - static void SetUpTestCase(); - static void TearDownTestCase(); - void SetUp() override; - void TearDown() override; -}; - -void CustomDialogTestNg::SetUpTestCase() {} - -void CustomDialogTestNg::TearDownTestCase() {} - -void CustomDialogTestNg::SetUp() -{ - MockPipelineBase::SetUp(); -} - -void CustomDialogTestNg::TearDown() -{ - MockPipelineBase::TearDown(); -} - -/** - * @tc.name: CustomDialogTestNg001 - * @tc.desc: Verify function CreateDialogNode - * @tc.type: FUNC - */ -HWTEST_F(CustomDialogTestNg, CustomDialogTestNg001, TestSize.Level1) -{ - DialogProperties param; - param.maskColor = Color::BLACK; - auto themeManager = AceType::MakeRefPtr(); - MockPipelineBase::GetCurrent()->SetThemeManager(themeManager); - EXPECT_CALL(*themeManager, GetTheme(_)).WillOnce(Return(AceType::MakeRefPtr())); - auto result = DialogView::CreateDialogNode(param, nullptr); - EXPECT_TRUE(result); - if (result) { - EXPECT_EQ(result->GetRenderContext()->GetBackgroundColorValue(Color::TRANSPARENT).GetValue(), - Color::BLACK.GetValue()); - } -} - -/** - * @tc.name: CustomDialogTestNg002 - * @tc.desc: Verify function CreateDialogNode - * @tc.type: FUNC - */ -HWTEST_F(CustomDialogTestNg, CustomDialogTestNg002, TestSize.Level1) -{ - DialogProperties param; - param.maskColor = Color::BLACK; - param.type = DialogType::ALERT_DIALOG; - auto themeManager = AceType::MakeRefPtr(); - MockPipelineBase::GetCurrent()->SetThemeManager(themeManager); - EXPECT_CALL(*themeManager, GetTheme(_)).WillOnce(Return(AceType::MakeRefPtr())); - auto result = DialogView::CreateDialogNode(param, nullptr); - EXPECT_TRUE(result); - if (result) { - EXPECT_EQ(result->GetRenderContext()->GetBackgroundColorValue(Color::TRANSPARENT).GetValue(), - Color::BLACK.GetValue()); - } -} - -/** - * @tc.name: CustomDialogTestNg003 - * @tc.desc: Verify function CreateDialogNode - * @tc.type: FUNC - */ -HWTEST_F(CustomDialogTestNg, CustomDialogTestNg003, TestSize.Level1) -{ - DialogProperties param; - param.maskColor = Color::BLACK; - param.type = DialogType::ACTION_SHEET; - auto themeManager = AceType::MakeRefPtr(); - MockPipelineBase::GetCurrent()->SetThemeManager(themeManager); - EXPECT_CALL(*themeManager, GetTheme(_)).WillOnce(Return(AceType::MakeRefPtr())); - auto result = DialogView::CreateDialogNode(param, nullptr); - EXPECT_TRUE(result); - if (result) { - EXPECT_EQ(result->GetRenderContext()->GetBackgroundColorValue(Color::TRANSPARENT).GetValue(), - Color::BLACK.GetValue()); - } -} - -/** - * @tc.name: CustomDialogTestNg004 - * @tc.desc: Verify function GetCloseAnimation and GetOpenAnimation - * @tc.type: FUNC - */ -HWTEST_F(CustomDialogTestNg, CustomDialogTestNg004, TestSize.Level1) -{ - DialogProperties param; - AnimationOption animationOption; - animationOption.SetDelay(10); - param.openAnimation = animationOption; - auto themeManager = AceType::MakeRefPtr(); - MockPipelineBase::GetCurrent()->SetThemeManager(themeManager); - EXPECT_CALL(*themeManager, GetTheme(_)).WillOnce(Return(AceType::MakeRefPtr())); - auto result = DialogView::CreateDialogNode(param, nullptr); - EXPECT_TRUE(result); - if (!result) { - return; - } - auto dialogPattern = result->GetPattern(); - EXPECT_TRUE(dialogPattern); - if (!dialogPattern) { - return; - } - if (dialogPattern->GetOpenAnimation().has_value()) { - EXPECT_EQ(dialogPattern->GetOpenAnimation().value().GetDelay(), animationOption.GetDelay()); - } - - if (dialogPattern->GetCloseAnimation().has_value()) { - EXPECT_EQ(dialogPattern->GetCloseAnimation().value().GetDelay(), animationOption.GetDelay()); - } -} - -/** - * @tc.name: CustomDialogTestNg005 - * @tc.desc: Verify function HandleClick - * @tc.type: FUNC - */ -HWTEST_F(CustomDialogTestNg, CustomDialogTestNg005, TestSize.Level1) -{ - GestureEvent info; - Offset globalLocation(10, 6); - OffsetF translate(10, 5); - DialogProperties param; - param.autoCancel = false; - auto themeManager = AceType::MakeRefPtr(); - MockPipelineBase::GetCurrent()->SetThemeManager(themeManager); - EXPECT_CALL(*themeManager, GetTheme(_)).WillOnce(Return(AceType::MakeRefPtr())); - auto child = FrameNode::GetOrCreateFrameNode( - V2::CUSTOM_DIALOG_COMPONENT_TAG, 0, []() { return AceType::MakeRefPtr(nullptr, nullptr); }); - auto Dialog = DialogView::CreateDialogNode(param, child); - EXPECT_TRUE(Dialog); - ASSERT_NE(Dialog, nullptr); - child->GetGeometryNode()->SetMarginFrameOffset(translate); - EXPECT_EQ(Dialog->TotalChildCount(), 1); - auto dialogPattern = Dialog->GetPattern(); - EXPECT_TRUE(dialogPattern); - ASSERT_NE(dialogPattern, nullptr); - info.SetGlobalLocation(globalLocation); - dialogPattern->HandleClick(info); -} - -/** - * @tc.name: CustomDialogTestNg006 - * @tc.desc: Verify function HandleClick - * @tc.type: FUNC - */ -HWTEST_F(CustomDialogTestNg, CustomDialogTestNg006, TestSize.Level1) -{ - GestureEvent info; - Offset globalLocation(10, 6); - OffsetF translate(10, 5); - DialogProperties param; - param.autoCancel = true; - auto themeManager = AceType::MakeRefPtr(); - MockPipelineBase::GetCurrent()->SetThemeManager(themeManager); - EXPECT_CALL(*themeManager, GetTheme(_)).WillOnce(Return(AceType::MakeRefPtr())); - auto child = FrameNode::GetOrCreateFrameNode( - V2::CUSTOM_DIALOG_COMPONENT_TAG, 0, []() { return AceType::MakeRefPtr(nullptr, nullptr); }); - auto Dialog = DialogView::CreateDialogNode(param, child); - EXPECT_TRUE(Dialog); - ASSERT_NE(Dialog, nullptr); - child->GetGeometryNode()->SetMarginFrameOffset(translate); - EXPECT_EQ(Dialog->TotalChildCount(), 1); - auto dialogPattern = Dialog->GetPattern(); - EXPECT_TRUE(dialogPattern); - ASSERT_NE(dialogPattern, nullptr); - info.SetGlobalLocation(globalLocation); - dialogPattern->HandleClick(info); -} -} // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/test/pattern/data_panel/data_panel_test_ng.cpp b/frameworks/core/components_ng/test/pattern/data_panel/data_panel_test_ng.cpp index 7b802a21bba..bff3214ca9d 100644 --- a/frameworks/core/components_ng/test/pattern/data_panel/data_panel_test_ng.cpp +++ b/frameworks/core/components_ng/test/pattern/data_panel/data_panel_test_ng.cpp @@ -884,9 +884,10 @@ HWTEST_F(DataPanelTestNg, DataPanelPaintMethodTest003, TestSize.Level1) DataPanelModifier dataPanelModifier; Testing::MockCanvas rsCanvas; - EXPECT_CALL(rsCanvas, AttachBrush(_)).WillOnce(ReturnRef(rsCanvas)); - EXPECT_CALL(rsCanvas, DetachBrush()).WillOnce(ReturnRef(rsCanvas)); - dataPanelModifier.PaintBackground(rsCanvas, OFFSET, TOTAL_WIDTH, TOTAL_HEIGHT); + EXPECT_CALL(rsCanvas, AttachBrush(_)).WillRepeatedly(ReturnRef(rsCanvas)); + EXPECT_CALL(rsCanvas, DetachBrush()).WillRepeatedly(ReturnRef(rsCanvas)); + dataPanelModifier.PaintBackground(rsCanvas, OFFSET, TOTAL_WIDTH, TOTAL_HEIGHT, SEGMENTWIDTH); + dataPanelModifier.PaintBackground(rsCanvas, OFFSET, TOTAL_WIDTH, TOTAL_HEIGHT * 4, SEGMENTWIDTH); } /** diff --git a/frameworks/core/components_ng/test/pattern/dialog/BUILD.gn b/frameworks/core/components_ng/test/pattern/dialog/BUILD.gn index eaba52d3259..d818e9b2580 100644 --- a/frameworks/core/components_ng/test/pattern/dialog/BUILD.gn +++ b/frameworks/core/components_ng/test/pattern/dialog/BUILD.gn @@ -106,18 +106,21 @@ ace_unittest("dialog_pattern_test_ng") { "$ace_root/frameworks/core/components_ng/pattern/list/list_position_controller.cpp", # mock + "$ace_root/frameworks/core/components_ng/test/mock/base/mock_stage_manager.cpp", + "$ace_root/frameworks/core/components_ng/test/mock/manager/drag_drop/mock_drag_drop_manager.cpp", + "$ace_root/frameworks/core/components_ng/test/mock/manager/drag_drop/mock_drag_drop_proxy.cpp", + "$ace_root/frameworks/core/components_ng/test/mock/pattern/navigation/mock_menu_view.cpp", + "$ace_root/test/mock/core/common/mock_font_manager_ng.cpp", + "$ace_root/test/mock/frameworks/base/log/mock_jank_frame_report.cpp", + "$ace_root/test/unittest/core/pipeline/mock_overlay_manager.cpp", + + # self "$ace_root/frameworks/core/components_ng/pattern/dialog/alert_dialog_model_ng.cpp", "$ace_root/frameworks/core/components_ng/pattern/dialog/dialog_accessibility_property.cpp", "$ace_root/frameworks/core/components_ng/pattern/dialog/dialog_event_hub.cpp", "$ace_root/frameworks/core/components_ng/pattern/dialog/dialog_layout_algorithm.cpp", "$ace_root/frameworks/core/components_ng/pattern/dialog/dialog_pattern.cpp", "$ace_root/frameworks/core/components_ng/pattern/dialog/dialog_view.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/base/mock_stage_manager.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/manager/drag_drop/mock_drag_drop_manager.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/manager/drag_drop/mock_drag_drop_proxy.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/navigation/mock_menu_view.cpp", - "$ace_root/test/mock/core/common/mock_font_manager_ng.cpp", - "$ace_root/test/unittest/core/pipeline/mock_overlay_manager.cpp", "dialog_pattern_test_ng.cpp", ] } diff --git a/frameworks/core/components_ng/test/pattern/dialog/dialog_pattern_test_ng.cpp b/frameworks/core/components_ng/test/pattern/dialog/dialog_pattern_test_ng.cpp index dd833a92fb1..170cd496850 100644 --- a/frameworks/core/components_ng/test/pattern/dialog/dialog_pattern_test_ng.cpp +++ b/frameworks/core/components_ng/test/pattern/dialog/dialog_pattern_test_ng.cpp @@ -17,6 +17,7 @@ #define private public #define protected public +#include "core/components/button/button_theme.h" #include "core/components/dialog/dialog_properties.h" #include "core/components_ng/base/view_stack_processor.h" #include "core/components_ng/pattern/dialog/dialog_event_hub.h" @@ -24,10 +25,9 @@ #include "core/components_ng/pattern/dialog/dialog_pattern.h" #include "core/components_ng/pattern/dialog/dialog_view.h" #include "core/components_ng/pattern/overlay/overlay_manager.h" -#include "core/components_v2/inspector/inspector_constants.h" #include "core/components_ng/test/mock/theme/mock_theme_manager.h" +#include "core/components_v2/inspector/inspector_constants.h" #include "core/pipeline_ng/test/mock/mock_pipeline_base.h" -#include "core/components/button/button_theme.h" using namespace testing; using namespace testing::ext; @@ -77,8 +77,10 @@ public: static void SetUpTestCase(); static void TearDownTestCase(); void SetDialogTheme(); + protected: RefPtr CreateDialog(); + private: vector sheetItems = { ActionSheetInfo { @@ -223,8 +225,7 @@ HWTEST_F(DialogPatternTestNg, DialogFrameNodeCreator0020, TestSize.Level1) * @tc.steps: step2. call SetAlignmentSwitch function. * @tc.expected: the results are correct. */ - for (size_t i = 0; i < sizeof(aligns) / sizeof(aligns[0]); i++) - { + for (size_t i = 0; i < sizeof(aligns) / sizeof(aligns[0]); i++) { dialogLayoutAlgorithm->alignment_ = aligns[i]; auto result = dialogLayoutAlgorithm->SetAlignmentSwitch(maxSize, childSize, topLeftPoint); if (dialogLayoutAlgorithm->alignment_ == DialogAlignment::DEFAULT) { @@ -276,7 +277,7 @@ HWTEST_F(DialogPatternTestNg, ToJsonValue, TestSize.Level1) pattern->message_ = MESSAGE; std::unique_ptr json = JsonUtil::Create(true); pattern->ToJsonValue(json); - EXPECT_EQ(json->GetKey(),""); + EXPECT_EQ(json->GetKey(), ""); } /** @@ -331,28 +332,17 @@ HWTEST_F(DialogPatternTestNg, DialogPatternTest001, TestSize.Level1) /** * @tc.steps: step1. create params and DialogLayoutAlgorithm object. */ - const ScreenSizeType types[] = { - ScreenSizeType::SM, - ScreenSizeType::MD, - ScreenSizeType::LG, - ScreenSizeType::UNDEFINED - }; - const DeviceType deviceTypes[] = { - DeviceType::WATCH, - DeviceType::PHONE, - DeviceType::CAR, - DeviceType::UNKNOWN - }; + const ScreenSizeType types[] = { ScreenSizeType::SM, ScreenSizeType::MD, ScreenSizeType::LG, + ScreenSizeType::UNDEFINED }; + const DeviceType deviceTypes[] = { DeviceType::WATCH, DeviceType::PHONE, DeviceType::CAR, DeviceType::UNKNOWN }; auto columnInfo = GridSystemManager::GetInstance().GetInfoByType(GridColumnType::CAR_DIALOG); auto dialogLayoutAlgorithm = AceType::MakeRefPtr(); /** * @tc.steps: step2. call GetMaxWidthBasedOnGridType function. * @tc.expected: the result equal to WIDTH_A. */ - for (size_t i = 0; i < sizeof(deviceTypes) / sizeof(deviceTypes[0]); i++) - { - for (size_t j = 0; j < sizeof(types) / sizeof(types[0]); j++) - { + for (size_t i = 0; i < sizeof(deviceTypes) / sizeof(deviceTypes[0]); i++) { + for (size_t j = 0; j < sizeof(types) / sizeof(types[0]); j++) { auto Width = dialogLayoutAlgorithm->GetMaxWidthBasedOnGridType(columnInfo, types[j], deviceTypes[i]); EXPECT_EQ(Width, WIDTH_A); } @@ -369,30 +359,23 @@ HWTEST_F(DialogPatternTestNg, DialogPatternTest002, TestSize.Level1) /** * @tc.steps: step1. set properties */ - const DialogType types[] = { - DialogType::ALERT_DIALOG, - DialogType::ACTION_SHEET, - DialogType::COMMON - }; + const DialogType types[] = { DialogType::ALERT_DIALOG, DialogType::ACTION_SHEET, DialogType::COMMON }; SetDialogTheme(); /** * @tc.steps: step2. call CreateDialogNode function with different props. * @tc.expected: the dialog node created successfully. */ - for (size_t i = 0; i < sizeof(types) / sizeof(types[0]); i++) - { + for (size_t i = 0; i < sizeof(types) / sizeof(types[0]); i++) { DialogProperties props; props.type = types[i]; - if (i == 1) - { + if (i == 1) { props.title = "dialog test"; props.content = "dialog content test"; props.customStyle = true; props.sheetsInfo = sheetItems; props.isMenu = true; props.buttons = btnItems; - }else if (i == 0) - { + } else if (i == 0) { props.buttons = btnItems; } auto dialog = DialogView::CreateDialogNode(props, nullptr); @@ -475,8 +458,7 @@ HWTEST_F(DialogPatternTestNg, DialogPatternTest004, TestSize.Level1) * @tc.steps: step1. create DialogLayoutAlgorithm instance. */ DialogLayoutAlgorithm dialogLayoutAlgorithm; - for (auto& props : propsVectors) - { + for (auto& props : propsVectors) { /** * @tc.steps: step2. create dialog node and layoutWrapper. * @tc.expected: the dialog node created successfully. @@ -494,8 +476,8 @@ HWTEST_F(DialogPatternTestNg, DialogPatternTest004, TestSize.Level1) childLayoutWrapper->AppendChild(grandsonLayoutWrapper); } - auto layoutWrapper = AceType::MakeRefPtr( - dialog, dialog->GetGeometryNode(), dialog->GetLayoutProperty()); + auto layoutWrapper = + AceType::MakeRefPtr(dialog, dialog->GetGeometryNode(), dialog->GetLayoutProperty()); layoutWrapper->AppendChild(childLayoutWrapper); /** * @tc.steps: step3. test DialogLayoutAlgorithm's Measure function. @@ -506,4 +488,157 @@ HWTEST_F(DialogPatternTestNg, DialogPatternTest004, TestSize.Level1) EXPECT_EQ(dialogLayoutAlgorithm.alignment_, DialogAlignment::DEFAULT); } } + +/** + * @tc.name: CustomDialogTestNg001 + * @tc.desc: Verify function CreateDialogNode + * @tc.type: FUNC + */ +HWTEST_F(DialogPatternTestNg, CustomDialogTestNg001, TestSize.Level1) +{ + DialogProperties param; + param.maskColor = Color::BLACK; + auto themeManager = AceType::MakeRefPtr(); + MockPipelineBase::GetCurrent()->SetThemeManager(themeManager); + EXPECT_CALL(*themeManager, GetTheme(_)).WillOnce(Return(AceType::MakeRefPtr())); + auto result = DialogView::CreateDialogNode(param, nullptr); + EXPECT_TRUE(result); + if (result) { + EXPECT_EQ(result->GetRenderContext()->GetBackgroundColorValue(Color::TRANSPARENT).GetValue(), + Color::BLACK.GetValue()); + } +} + +/** + * @tc.name: CustomDialogTestNg002 + * @tc.desc: Verify function CreateDialogNode + * @tc.type: FUNC + */ +HWTEST_F(DialogPatternTestNg, CustomDialogTestNg002, TestSize.Level1) +{ + DialogProperties param; + param.maskColor = Color::BLACK; + param.type = DialogType::ALERT_DIALOG; + auto themeManager = AceType::MakeRefPtr(); + MockPipelineBase::GetCurrent()->SetThemeManager(themeManager); + EXPECT_CALL(*themeManager, GetTheme(_)).WillOnce(Return(AceType::MakeRefPtr())); + auto result = DialogView::CreateDialogNode(param, nullptr); + EXPECT_TRUE(result); + if (result) { + EXPECT_EQ(result->GetRenderContext()->GetBackgroundColorValue(Color::TRANSPARENT).GetValue(), + Color::BLACK.GetValue()); + } +} + +/** + * @tc.name: CustomDialogTestNg003 + * @tc.desc: Verify function CreateDialogNode + * @tc.type: FUNC + */ +HWTEST_F(DialogPatternTestNg, CustomDialogTestNg003, TestSize.Level1) +{ + DialogProperties param; + param.maskColor = Color::BLACK; + param.type = DialogType::ACTION_SHEET; + auto themeManager = AceType::MakeRefPtr(); + MockPipelineBase::GetCurrent()->SetThemeManager(themeManager); + EXPECT_CALL(*themeManager, GetTheme(_)).WillOnce(Return(AceType::MakeRefPtr())); + auto result = DialogView::CreateDialogNode(param, nullptr); + EXPECT_TRUE(result); + if (result) { + EXPECT_EQ(result->GetRenderContext()->GetBackgroundColorValue(Color::TRANSPARENT).GetValue(), + Color::BLACK.GetValue()); + } +} + +/** + * @tc.name: CustomDialogTestNg004 + * @tc.desc: Verify function GetCloseAnimation and GetOpenAnimation + * @tc.type: FUNC + */ +HWTEST_F(DialogPatternTestNg, CustomDialogTestNg004, TestSize.Level1) +{ + DialogProperties param; + AnimationOption animationOption; + animationOption.SetDelay(10); + param.openAnimation = animationOption; + auto themeManager = AceType::MakeRefPtr(); + MockPipelineBase::GetCurrent()->SetThemeManager(themeManager); + EXPECT_CALL(*themeManager, GetTheme(_)).WillOnce(Return(AceType::MakeRefPtr())); + auto result = DialogView::CreateDialogNode(param, nullptr); + EXPECT_TRUE(result); + if (!result) { + return; + } + auto dialogPattern = result->GetPattern(); + EXPECT_TRUE(dialogPattern); + if (!dialogPattern) { + return; + } + if (dialogPattern->GetOpenAnimation().has_value()) { + EXPECT_EQ(dialogPattern->GetOpenAnimation().value().GetDelay(), animationOption.GetDelay()); + } + + if (dialogPattern->GetCloseAnimation().has_value()) { + EXPECT_EQ(dialogPattern->GetCloseAnimation().value().GetDelay(), animationOption.GetDelay()); + } +} + +/** + * @tc.name: CustomDialogTestNg005 + * @tc.desc: Verify function HandleClick + * @tc.type: FUNC + */ +HWTEST_F(DialogPatternTestNg, CustomDialogTestNg005, TestSize.Level1) +{ + GestureEvent info; + Offset globalLocation(10, 6); + OffsetF translate(10, 5); + DialogProperties param; + param.autoCancel = false; + auto themeManager = AceType::MakeRefPtr(); + MockPipelineBase::GetCurrent()->SetThemeManager(themeManager); + EXPECT_CALL(*themeManager, GetTheme(_)).WillOnce(Return(AceType::MakeRefPtr())); + auto child = FrameNode::GetOrCreateFrameNode( + V2::CUSTOM_DIALOG_COMPONENT_TAG, 0, []() { return AceType::MakeRefPtr(nullptr, nullptr); }); + auto Dialog = DialogView::CreateDialogNode(param, child); + EXPECT_TRUE(Dialog); + ASSERT_NE(Dialog, nullptr); + child->GetGeometryNode()->SetMarginFrameOffset(translate); + EXPECT_EQ(Dialog->TotalChildCount(), 1); + auto dialogPattern = Dialog->GetPattern(); + EXPECT_TRUE(dialogPattern); + ASSERT_NE(dialogPattern, nullptr); + info.SetGlobalLocation(globalLocation); + dialogPattern->HandleClick(info); +} + +/** + * @tc.name: CustomDialogTestNg006 + * @tc.desc: Verify function HandleClick + * @tc.type: FUNC + */ +HWTEST_F(DialogPatternTestNg, CustomDialogTestNg006, TestSize.Level1) +{ + GestureEvent info; + Offset globalLocation(10, 6); + OffsetF translate(10, 5); + DialogProperties param; + param.autoCancel = true; + auto themeManager = AceType::MakeRefPtr(); + MockPipelineBase::GetCurrent()->SetThemeManager(themeManager); + EXPECT_CALL(*themeManager, GetTheme(_)).WillOnce(Return(AceType::MakeRefPtr())); + auto child = FrameNode::GetOrCreateFrameNode( + V2::CUSTOM_DIALOG_COMPONENT_TAG, 0, []() { return AceType::MakeRefPtr(nullptr, nullptr); }); + auto Dialog = DialogView::CreateDialogNode(param, child); + EXPECT_TRUE(Dialog); + ASSERT_NE(Dialog, nullptr); + child->GetGeometryNode()->SetMarginFrameOffset(translate); + EXPECT_EQ(Dialog->TotalChildCount(), 1); + auto dialogPattern = Dialog->GetPattern(); + EXPECT_TRUE(dialogPattern); + ASSERT_NE(dialogPattern, nullptr); + info.SetGlobalLocation(globalLocation); + dialogPattern->HandleClick(info); +} } // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/test/pattern/divider/BUILD.gn b/frameworks/core/components_ng/test/pattern/divider/BUILD.gn index 3c9b2d54b21..69d3c9dcd0b 100644 --- a/frameworks/core/components_ng/test/pattern/divider/BUILD.gn +++ b/frameworks/core/components_ng/test/pattern/divider/BUILD.gn @@ -14,112 +14,18 @@ import("//build/test.gni") import("//foundation/arkui/ace_engine/test/unittest/ace_unittest.gni") -ohos_unittest("divider_pattern_test_ng") { - module_out_path = pattern_test_output_path - +ace_unittest("divider_pattern_test_ng") { + ace_animation = true sources = [ + # other + "$ace_root/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp", + "$ace_root/frameworks/core/components_ng/pattern/grid_container/grid_container_layout_property.cpp", + + # self "$ace_root/frameworks/core/components_ng/pattern/divider/divider_layout_algorithm.cpp", "$ace_root/frameworks/core/components_ng/pattern/divider/divider_model_ng.cpp", "$ace_root/frameworks/core/components_ng/pattern/divider/divider_modifier.cpp", "$ace_root/frameworks/core/components_ng/pattern/divider/divider_pattern.cpp", - "$ace_root/frameworks/core/components_ng/render/divider_painter.cpp", "divider_pattern_test_ng.cpp", ] - - sources += [ - # base - "$ace_root/frameworks/base/geometry/dimension.cpp", - "$ace_root/frameworks/base/json/json_util.cpp", - "$ace_root/frameworks/base/utils/base_id.cpp", - "$ace_root/frameworks/base/utils/string_expression.cpp", - "$ace_root/frameworks/base/utils/string_utils.cpp", - "$ace_root/frameworks/base/utils/time_util.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_node.cpp", - "$ace_root/frameworks/core/components_ng/pattern/custom/custom_node.cpp", - "$ace_root/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/syntax/lazy_for_each_node.cpp", - - # components - "$ace_root/frameworks/core/components/common/layout/grid_column_info.cpp", - "$ace_root/frameworks/core/components/common/layout/grid_container_info.cpp", - "$ace_root/frameworks/core/components/common/layout/grid_system_manager.cpp", - "$ace_root/frameworks/core/components/common/layout/screen_system_manager.cpp", - "$ace_root/frameworks/core/components/common/properties/alignment.cpp", - "$ace_root/frameworks/core/components/common/properties/color.cpp", - - # components_ng - "$ace_root/frameworks/core/components_ng/base/frame_node.cpp", - "$ace_root/frameworks/core/components_ng/base/geometry_node.cpp", - "$ace_root/frameworks/core/components_ng/base/modifier.cpp", - "$ace_root/frameworks/core/components_ng/base/ui_node.cpp", - "$ace_root/frameworks/core/components_ng/base/view_stack_processor.cpp", - "$ace_root/frameworks/core/components_ng/event/click_event.cpp", - "$ace_root/frameworks/core/components_ng/event/drag_event.cpp", - "$ace_root/frameworks/core/components_ng/event/event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/focus_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/gesture_event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/input_event.cpp", - "$ace_root/frameworks/core/components_ng/event/input_event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/pan_event.cpp", - "$ace_root/frameworks/core/components_ng/event/state_style_manager.cpp", - "$ace_root/frameworks/core/components_ng/event/touch_event.cpp", - "$ace_root/frameworks/core/components_ng/gestures/gesture_referee.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/click_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/exclusive_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/gesture_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/long_press_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/multi_fingers_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/pan_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/parallel_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/recognizer_group.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/sequenced_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/layout/box_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_property.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_builder.cpp", - "$ace_root/frameworks/core/components_ng/manager/safe_area/safe_area_manager.cpp", - "$ace_root/frameworks/core/components_ng/property/border_property.cpp", - "$ace_root/frameworks/core/components_ng/property/calc_length.cpp", - "$ace_root/frameworks/core/components_ng/property/grid_property.cpp", - "$ace_root/frameworks/core/components_ng/property/measure_utils.cpp", - "$ace_root/frameworks/core/components_ng/property/property.cpp", - "$ace_root/frameworks/core/components_ng/property/safe_area_insets.cpp", - "$ace_root/frameworks/core/components_ng/render/drawing_prop_convertor.cpp", - "$ace_root/frameworks/core/components_ng/render/paint_wrapper.cpp", - - # components_v2 - "$ace_root/frameworks/core/components_v2/inspector/inspector_constants.cpp", - - # pipeline - "$ace_root/frameworks/core/pipeline/base/constants.cpp", - - # mock - "$ace_root/frameworks/base/test/mock/mock_ressched_report.cpp", - "$ace_root/frameworks/base/test/mock/mock_socperf_client_impl.cpp", - "$ace_root/frameworks/base/test/mock/mock_system_properties.cpp", - "$ace_root/frameworks/core/common/test/mock/mock_ace_application_info.cpp", - "$ace_root/frameworks/core/components/test/unittest/mock/ace_trace_mock.cpp", - "$ace_root/frameworks/core/components_ng/test/event/mock/mock_scrollable_event.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/animation/mock_geometry_transition.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/base/mock_localization.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/grid_container/mock_grid_container_layout_property.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_animation_utils.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_modifier_adapter.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_context.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_context_creator.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_surface_creator.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/syntax/mock_for_each_node.cpp", - "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_element_register.cpp", - "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_pipeline_base.cpp", - ] - - deps = [ - "$ace_root/frameworks/base:ace_memory_monitor_ohos", - "$ace_root/frameworks/core/components/theme:build_theme_code", - "$ace_root/test/unittest:ace_unittest_log", - "$cjson_root:cjson_static", - "//third_party/googletest:gmock_main", - ] - - configs = [ "$ace_root/test/unittest:ace_unittest_config" ] } diff --git a/frameworks/core/components_ng/test/pattern/flex/BUILD.gn b/frameworks/core/components_ng/test/pattern/flex/BUILD.gn index f92fca5b7ca..b552eb5366a 100644 --- a/frameworks/core/components_ng/test/pattern/flex/BUILD.gn +++ b/frameworks/core/components_ng/test/pattern/flex/BUILD.gn @@ -12,121 +12,23 @@ # limitations under the License. import("//build/test.gni") -import("//foundation/arkui/ace_engine/ace_config.gni") -import( - "//foundation/arkui/ace_engine/frameworks/core/components_ng/components.gni") import("//foundation/arkui/ace_engine/test/unittest/ace_unittest.gni") -ohos_unittest("flex_test_ng") { - module_out_path = pattern_test_output_path +ace_unittest("flex_test_ng") { + ace_animation = true sources = [ - # base - "$ace_root/frameworks/base/geometry/dimension.cpp", - "$ace_root/frameworks/base/json/json_util.cpp", - "$ace_root/frameworks/base/utils/base_id.cpp", - "$ace_root/frameworks/base/utils/string_expression.cpp", - "$ace_root/frameworks/base/utils/string_utils.cpp", - "$ace_root/frameworks/base/utils/time_util.cpp", - - # components - "$ace_root/frameworks/core/components/common/layout/grid_column_info.cpp", - "$ace_root/frameworks/core/components/common/layout/grid_container_info.cpp", - "$ace_root/frameworks/core/components/common/layout/grid_system_manager.cpp", - "$ace_root/frameworks/core/components/common/layout/screen_system_manager.cpp", - "$ace_root/frameworks/core/components/common/properties/alignment.cpp", - "$ace_root/frameworks/core/components/common/properties/color.cpp", - - # components_ng - "$ace_root/frameworks/core/components_ng/base/frame_node.cpp", - "$ace_root/frameworks/core/components_ng/base/geometry_node.cpp", - "$ace_root/frameworks/core/components_ng/base/modifier.cpp", - "$ace_root/frameworks/core/components_ng/base/ui_node.cpp", - "$ace_root/frameworks/core/components_ng/base/view_stack_processor.cpp", - "$ace_root/frameworks/core/components_ng/event/click_event.cpp", - "$ace_root/frameworks/core/components_ng/event/drag_event.cpp", - "$ace_root/frameworks/core/components_ng/event/event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/focus_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/gesture_event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/input_event.cpp", - "$ace_root/frameworks/core/components_ng/event/input_event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/pan_event.cpp", - "$ace_root/frameworks/core/components_ng/event/state_style_manager.cpp", - "$ace_root/frameworks/core/components_ng/event/touch_event.cpp", - "$ace_root/frameworks/core/components_ng/gestures/gesture_referee.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/click_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/exclusive_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/gesture_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/long_press_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/multi_fingers_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/pan_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/parallel_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/recognizer_group.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/sequenced_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/layout/box_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_property.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_builder.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_node.cpp", - "$ace_root/frameworks/core/components_ng/manager/safe_area/safe_area_manager.cpp", - "$ace_root/frameworks/core/components_ng/pattern/custom/custom_node.cpp", - "$ace_root/frameworks/core/components_ng/property/border_property.cpp", - "$ace_root/frameworks/core/components_ng/property/calc_length.cpp", - "$ace_root/frameworks/core/components_ng/property/grid_property.cpp", - "$ace_root/frameworks/core/components_ng/property/measure_utils.cpp", - "$ace_root/frameworks/core/components_ng/property/property.cpp", - "$ace_root/frameworks/core/components_ng/property/safe_area_insets.cpp", - "$ace_root/frameworks/core/components_ng/render/drawing_prop_convertor.cpp", - "$ace_root/frameworks/core/components_ng/render/paint_wrapper.cpp", - "$ace_root/frameworks/core/components_ng/syntax/lazy_for_each_node.cpp", - "$ace_root/frameworks/core/components_ng/test/event/mock/mock_scrollable_event.cpp", - - # components_v2 - "$ace_root/frameworks/core/components_v2/inspector/inspector_constants.cpp", - - # pipeline - "$ace_root/frameworks/core/pipeline/base/constants.cpp", - - # mock - "$ace_root/frameworks/base/test/mock/mock_ressched_report.cpp", - "$ace_root/frameworks/base/test/mock/mock_socperf_client_impl.cpp", - "$ace_root/frameworks/base/test/mock/mock_system_properties.cpp", - "$ace_root/frameworks/core/common/test/mock/mock_ace_application_info.cpp", - "$ace_root/frameworks/core/components/test/unittest/mock/ace_trace_mock.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/animation/mock_geometry_transition.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/base/mock_localization.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/grid_container/mock_grid_container_layout_property.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_animation_utils.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_modifier_adapter.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_context.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_context_creator.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_surface_creator.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/syntax/mock_for_each_node.cpp", - "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_element_register.cpp", - "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_pipeline_base.cpp", - ] - - sources += [ - "$ace_root/frameworks/core/animation/animator.cpp", - "$ace_root/frameworks/core/animation/anticipate_curve.cpp", - "$ace_root/frameworks/core/animation/cubic_curve.cpp", - "$ace_root/frameworks/core/animation/curves.cpp", - "$ace_root/frameworks/core/animation/scheduler.cpp", + #button "$ace_root/frameworks/core/components_ng/pattern/button/button_layout_algorithm.cpp", "$ace_root/frameworks/core/components_ng/pattern/button/button_pattern.cpp", "$ace_root/frameworks/core/components_ng/pattern/button/toggle_button_pattern.cpp", + + # other + "$ace_root/frameworks/core/components_ng/pattern/grid_container/grid_container_layout_property.cpp", + + # self "$ace_root/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp", "$ace_root/frameworks/core/components_ng/pattern/flex/flex_model_ng.cpp", "$ace_root/frameworks/core/components_ng/pattern/flex/wrap_layout_algorithm.cpp", - "$ace_root/test/mock/frameworks/base/log/mock_jank_frame_report.cpp", "flex_test_ng.cpp", ] - - deps = [ - "$ace_root/frameworks/base:ace_memory_monitor_ohos", - "$ace_root/test/unittest:ace_unittest_log", - "$cjson_root:cjson", - "//third_party/googletest:gmock_main", - ] - - configs = [ "$ace_root/test/unittest:ace_unittest_config" ] } diff --git a/frameworks/core/components_ng/test/pattern/gauge/gauge_test_ng.cpp b/frameworks/core/components_ng/test/pattern/gauge/gauge_test_ng.cpp index 8bfcf8e9c8c..daa7cb70c67 100644 --- a/frameworks/core/components_ng/test/pattern/gauge/gauge_test_ng.cpp +++ b/frameworks/core/components_ng/test/pattern/gauge/gauge_test_ng.cpp @@ -18,6 +18,7 @@ #include "gtest/internal/gtest-port.h" #define private public +#define protected public #include "base/log/log_wrapper.h" #include "base/geometry/offset.h" #include "core/components/theme/theme.h" @@ -31,6 +32,7 @@ #include "core/components_ng/test/mock/rosen/testing_canvas.h" #include "core/components_ng/test/mock/theme/mock_theme_manager.h" #include "core/pipeline_ng/test/mock/mock_pipeline_base.h" +#include "core/components/progress/progress_theme.h" using namespace testing; using namespace testing::ext; @@ -78,35 +80,20 @@ const Alignment ALIGNMENT = Alignment::BOTTOM_RIGHT; class GaugeTestNg : public testing::Test { public: - static void SetUpTestCase(); - static void TearDownTestCase(); + static void SetUpTestSuite(); + static void TearDownTestSuite(); }; -void GaugeTestNg::SetUpTestCase() +void GaugeTestNg::SetUpTestSuite() { MockPipelineBase::SetUp(); } -void GaugeTestNg::TearDownTestCase() +void GaugeTestNg::TearDownTestSuite() { MockPipelineBase::TearDown(); } -class ProgressTheme : public Theme { - DECLARE_ACE_TYPE(ProgressTheme, Theme) -public: - ProgressTheme() = default; - ~ProgressTheme() override = default; - - Dimension GetTrackWidth() const - { - return dimension_; - } - -private: - Dimension dimension_; -}; - /** * @tc.name: GaugePatternTest001 * @tc.desc: Test Gauge Create @@ -222,7 +209,7 @@ HWTEST_F(GaugeTestNg, GaugeMeasureTest003, TestSize.Level1) // create mock theme manager auto themeManager = AceType::MakeRefPtr(); MockPipelineBase::GetCurrent()->SetThemeManager(themeManager); - EXPECT_CALL(*themeManager, GetTheme(_)).WillOnce(Return(AceType::MakeRefPtr())); + EXPECT_CALL(*themeManager, GetTheme(_)).WillRepeatedly(Return(AceType::MakeRefPtr())); auto gaugeSize = gaugeLayoutAlgorithm->MeasureContent(layoutConstraintSizevalid, &layoutWrapper).value(); EXPECT_EQ(gaugeSize, SizeF(WIDTH.ConvertToPx(), HEIGHT.ConvertToPx())); @@ -235,9 +222,11 @@ HWTEST_F(GaugeTestNg, GaugeMeasureTest003, TestSize.Level1) LayoutConstraintF layoutConstraintHeightUnvalid; layoutConstraintHeightUnvalid.maxSize = MAX_SIZE; layoutConstraintHeightUnvalid.selfIdealSize.SetHeight(NEGATIVE_NUMBER); - EXPECT_CALL(*themeManager, GetTheme(_)).WillOnce(Return(AceType::MakeRefPtr())); + auto gaugeTheme = AceType::MakeRefPtr(); + gaugeTheme->trackWidth_ = WIDTH; + EXPECT_CALL(*themeManager, GetTheme(_)).WillOnce(Return(gaugeTheme)); gaugeSize = gaugeLayoutAlgorithm->MeasureContent(layoutConstraintHeightUnvalid, &layoutWrapper).value(); - EXPECT_EQ(gaugeSize, SizeF(MAX_WIDTH, MAX_HEIGHT)); + EXPECT_EQ(gaugeSize, SizeF(WIDTH.ConvertToPx(), WIDTH.ConvertToPx())); /** * corresponding ets code: @@ -248,9 +237,9 @@ HWTEST_F(GaugeTestNg, GaugeMeasureTest003, TestSize.Level1) LayoutConstraintF layoutConstraintWidthUnvalid; layoutConstraintWidthUnvalid.maxSize = MAX_SIZE; layoutConstraintWidthUnvalid.selfIdealSize.SetWidth(NEGATIVE_NUMBER); - EXPECT_CALL(*themeManager, GetTheme(_)).WillOnce(Return(AceType::MakeRefPtr())); + EXPECT_CALL(*themeManager, GetTheme(_)).WillOnce(Return(gaugeTheme)); gaugeSize = gaugeLayoutAlgorithm->MeasureContent(layoutConstraintWidthUnvalid, &layoutWrapper).value(); - EXPECT_EQ(gaugeSize, SizeF(MAX_WIDTH, MAX_HEIGHT)); + EXPECT_EQ(gaugeSize, SizeF(WIDTH.ConvertToPx(), WIDTH.ConvertToPx())); /** * corresponding ets code: @@ -261,7 +250,7 @@ HWTEST_F(GaugeTestNg, GaugeMeasureTest003, TestSize.Level1) LayoutConstraintF layoutConstraintWidth; layoutConstraintWidth.selfIdealSize.SetWidth(WIDTH.ConvertToPx()); layoutConstraintWidth.maxSize = MAX_SIZE; - EXPECT_CALL(*themeManager, GetTheme(_)).WillOnce(Return(AceType::MakeRefPtr())); + EXPECT_CALL(*themeManager, GetTheme(_)).WillRepeatedly(Return(AceType::MakeRefPtr())); gaugeSize = gaugeLayoutAlgorithm->MeasureContent(layoutConstraintWidth, &layoutWrapper).value(); EXPECT_EQ(gaugeSize, SizeF(WIDTH.ConvertToPx(), WIDTH.ConvertToPx())); @@ -274,7 +263,7 @@ HWTEST_F(GaugeTestNg, GaugeMeasureTest003, TestSize.Level1) LayoutConstraintF layoutConstraintHeight; layoutConstraintHeight.selfIdealSize.SetHeight(HEIGHT.ConvertToPx()); layoutConstraintHeight.maxSize = MAX_SIZE; - EXPECT_CALL(*themeManager, GetTheme(_)).WillOnce(Return(AceType::MakeRefPtr())); + EXPECT_CALL(*themeManager, GetTheme(_)).WillRepeatedly(Return(AceType::MakeRefPtr())); gaugeSize = gaugeLayoutAlgorithm->MeasureContent(layoutConstraintHeight, &layoutWrapper).value(); EXPECT_EQ(gaugeSize, SizeF(HEIGHT.ConvertToPx(), HEIGHT.ConvertToPx())); @@ -286,7 +275,8 @@ HWTEST_F(GaugeTestNg, GaugeMeasureTest003, TestSize.Level1) */ LayoutConstraintF layoutConstraintSmallWidth; layoutConstraintSmallWidth.maxSize = SizeF(SMALL_WIDTH, MAX_HEIGHT); - EXPECT_CALL(*themeManager, GetTheme(_)).WillOnce(Return(AceType::MakeRefPtr())); + gaugeTheme->trackWidth_ = 500.0_vp; + EXPECT_CALL(*themeManager, GetTheme(_)).WillOnce(Return(gaugeTheme)); gaugeSize = gaugeLayoutAlgorithm->MeasureContent(layoutConstraintSmallWidth, &layoutWrapper).value(); EXPECT_EQ(gaugeSize, SizeF(SMALL_WIDTH, SMALL_WIDTH)); @@ -298,14 +288,14 @@ HWTEST_F(GaugeTestNg, GaugeMeasureTest003, TestSize.Level1) */ LayoutConstraintF layoutConstraintSmallHeight; layoutConstraintSmallWidth.maxSize = SizeF(MAX_WIDTH, SMALL_HEIGHT); - EXPECT_CALL(*themeManager, GetTheme(_)).WillOnce(Return(AceType::MakeRefPtr())); + EXPECT_CALL(*themeManager, GetTheme(_)).WillOnce(Return(gaugeTheme)); gaugeSize = gaugeLayoutAlgorithm->MeasureContent(layoutConstraintSmallWidth, &layoutWrapper).value(); EXPECT_EQ(gaugeSize, SizeF(SMALL_HEIGHT, SMALL_HEIGHT)); LayoutConstraintF layoutConstraintInfinite; layoutConstraintInfinite.maxSize = MAX_SIZE; layoutConstraintInfinite.maxSize.SetWidth(INFINITE); - EXPECT_CALL(*themeManager, GetTheme(_)).WillOnce(Return(AceType::MakeRefPtr())); + EXPECT_CALL(*themeManager, GetTheme(_)).WillOnce(Return(gaugeTheme)); gaugeSize = gaugeLayoutAlgorithm->MeasureContent(layoutConstraintInfinite, &layoutWrapper).value(); EXPECT_EQ(gaugeSize, SizeF(MAX_HEIGHT, MAX_HEIGHT)); } diff --git a/frameworks/core/components_ng/test/pattern/grid/BUILD.gn b/frameworks/core/components_ng/test/pattern/grid/BUILD.gn index 59a416ad0e0..a38a544bdda 100644 --- a/frameworks/core/components_ng/test/pattern/grid/BUILD.gn +++ b/frameworks/core/components_ng/test/pattern/grid/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. +# Copyright (c) 2022-2023 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -14,47 +14,71 @@ import("//build/test.gni") import("//foundation/arkui/ace_engine/test/unittest/ace_unittest.gni") -ohos_unittest("grid_test_ng") { - module_out_path = pattern_test_output_path - +ace_unittest("grid_test_ng") { + ace_animation = true sources = [ - # special - "$ace_root/frameworks/base/geometry/animatable_dimension.cpp", - "$ace_root/frameworks/base/geometry/least_square_impl.cpp", - "$ace_root/frameworks/base/geometry/matrix3.cpp", - "$ace_root/frameworks/base/geometry/matrix4.cpp", - "$ace_root/frameworks/base/test/mock/mock_drag_window.cpp", - "$ace_root/frameworks/base/utils/time_util.cpp", - "$ace_root/frameworks/core/animation/anticipate_curve.cpp", - "$ace_root/frameworks/core/animation/cubic_curve.cpp", - "$ace_root/frameworks/core/animation/curves.cpp", - "$ace_root/frameworks/core/animation/friction_motion.cpp", - "$ace_root/frameworks/core/animation/spring_curve.cpp", - "$ace_root/frameworks/core/animation/spring_model.cpp", - "$ace_root/frameworks/core/animation/spring_motion.cpp", - "$ace_root/frameworks/core/animation/test/mock/mock_animator.cpp", - "$ace_root/frameworks/core/animation/test/mock/mock_scheduler.cpp", - "$ace_root/frameworks/core/common/test/mock/mock_clipboard.cpp", - "$ace_root/frameworks/core/common/test/mock/mock_layout_inspector.cpp", - "$ace_root/frameworks/core/components_ng/event/scrollable_event.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_node.cpp", + #button "$ace_root/frameworks/core/components_ng/pattern/button/button_layout_algorithm.cpp", "$ace_root/frameworks/core/components_ng/pattern/button/button_model_ng.cpp", "$ace_root/frameworks/core/components_ng/pattern/button/button_pattern.cpp", - "$ace_root/frameworks/core/components_ng/pattern/button/toggle_button_accessibility_property.cpp", - "$ace_root/frameworks/core/components_ng/pattern/button/toggle_button_model_ng.cpp", "$ace_root/frameworks/core/components_ng/pattern/button/toggle_button_pattern.cpp", - "$ace_root/frameworks/core/components_ng/pattern/custom/custom_node.cpp", + + # text + "$ace_root/frameworks/core/components_ng/pattern/text/image_span_view.cpp", + "$ace_root/frameworks/core/components_ng/pattern/text/span_model_ng.cpp", + "$ace_root/frameworks/core/components_ng/pattern/text/span_node.cpp", "$ace_root/frameworks/core/components_ng/pattern/text/text_accessibility_property.cpp", "$ace_root/frameworks/core/components_ng/pattern/text/text_content_modifier.cpp", + "$ace_root/frameworks/core/components_ng/pattern/text/text_layout_algorithm.cpp", "$ace_root/frameworks/core/components_ng/pattern/text/text_layout_property.cpp", + "$ace_root/frameworks/core/components_ng/pattern/text/text_model_ng.cpp", "$ace_root/frameworks/core/components_ng/pattern/text/text_overlay_modifier.cpp", "$ace_root/frameworks/core/components_ng/pattern/text/text_paint_method.cpp", + "$ace_root/frameworks/core/components_ng/pattern/text/text_pattern.cpp", "$ace_root/frameworks/core/components_ng/pattern/text/text_styles.cpp", - "$ace_root/frameworks/core/components_ng/syntax/lazy_for_each_node.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/text/mock_text_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/text/mock_text_pattern.cpp", + + # select_overlay + "$ace_root/frameworks/core/components_ng/manager/select_overlay/select_overlay_manager.cpp", + "$ace_root/frameworks/core/components_ng/manager/select_overlay/select_overlay_proxy.cpp", + "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_layout_algorithm.cpp", + "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_modifier.cpp", + "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_paint_method.cpp", + "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_pattern.cpp", + "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_property.cpp", + "$ace_root/frameworks/core/components_ng/test/mock/pattern/popup/mock_popup_base_pattern.cpp", + "$ace_root/frameworks/core/components_ng/test/mock/pattern/select_overlay/mock_select_overlay_node.cpp", + + # Scroll + "$ace_root/frameworks/core/components_ng/pattern/scroll/effect/scroll_fade_controller.cpp", + "$ace_root/frameworks/core/components_ng/pattern/scroll/effect/scroll_fade_effect.cpp", + "$ace_root/frameworks/core/components_ng/pattern/scroll/effect/scroll_fade_painter.cpp", + "$ace_root/frameworks/core/components_ng/pattern/scroll/inner/scroll_bar_painter.cpp", + "$ace_root/frameworks/core/components_ng/pattern/scroll/scroll_accessibility_property.cpp", + "$ace_root/frameworks/core/components_ng/pattern/scroll/scroll_layout_algorithm.cpp", + "$ace_root/frameworks/core/components_ng/pattern/scroll/scroll_model_ng.cpp", + "$ace_root/frameworks/core/components_ng/pattern/scroll/scroll_paint_method.cpp", + "$ace_root/frameworks/core/components_ng/pattern/scroll/scroll_pattern.cpp", + "$ace_root/frameworks/core/components_ng/pattern/scroll/scroll_position_controller.cpp", + "$ace_root/frameworks/core/components_ng/pattern/scroll/scroll_spring_effect.cpp", + "$ace_root/frameworks/core/components_ng/pattern/scroll_bar/proxy/scroll_bar_proxy.cpp", + "$ace_root/frameworks/core/components_ng/pattern/scroll_bar/scroll_bar_pattern.cpp", + "$ace_root/frameworks/core/components_ng/pattern/scrollable/scrollable_controller.cpp", + "$ace_root/frameworks/core/components_ng/pattern/scrollable/scrollable_paint_property.cpp", + "$ace_root/frameworks/core/components_ng/pattern/scrollable/scrollable_pattern.cpp", + + # mock + "$ace_root/frameworks/core/components_ng/test/mock/manager/drag_drop/mock_drag_drop_proxy.cpp", + "$ace_root/frameworks/core/components_ng/test/pattern/test_ng.cpp", + "$ace_root/test/mock/core/common/mock_font_manager_ng.cpp", "$ace_root/test/mock/frameworks/base/log/mock_jank_frame_report.cpp", + "$ace_root/test/unittest/core/pipeline/mock_drag_drop_manager.cpp", + + # other + "$ace_root/frameworks/core/animation/friction_motion.cpp", + "$ace_root/frameworks/core/animation/spring_curve.cpp", + "$ace_root/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp", + "$ace_root/frameworks/core/components_ng/pattern/grid_container/grid_container_layout_property.cpp", + "$ace_root/frameworks/core/components_ng/property/templates_parser.cpp", # self "$ace_root/frameworks/core/components_ng/pattern/grid/grid_accessibility_property.cpp", @@ -73,121 +97,7 @@ ohos_unittest("grid_test_ng") { "$ace_root/frameworks/core/components_ng/pattern/grid/grid_position_controller.cpp", "$ace_root/frameworks/core/components_ng/pattern/grid/grid_scroll/grid_scroll_layout_algorithm.cpp", "$ace_root/frameworks/core/components_ng/pattern/grid/grid_utils.cpp", - "$ace_root/frameworks/core/components_ng/pattern/list/list_event_hub.cpp", - "$ace_root/frameworks/core/components_ng/pattern/scroll/effect/scroll_fade_controller.cpp", - "$ace_root/frameworks/core/components_ng/pattern/scroll/effect/scroll_fade_effect.cpp", - "$ace_root/frameworks/core/components_ng/pattern/scroll/inner/scroll_bar.cpp", - "$ace_root/frameworks/core/components_ng/pattern/scroll/scroll_spring_effect.cpp", - "$ace_root/frameworks/core/components_ng/pattern/scroll_bar/proxy/scroll_bar_proxy.cpp", - "$ace_root/frameworks/core/components_ng/pattern/scroll_bar/scroll_bar_accessibility_property.cpp", - "$ace_root/frameworks/core/components_ng/pattern/scroll_bar/scroll_bar_pattern.cpp", - "$ace_root/frameworks/core/components_ng/pattern/scrollable/scrollable_controller.cpp", - "$ace_root/frameworks/core/components_ng/pattern/scrollable/scrollable_paint_property.cpp", - "$ace_root/frameworks/core/components_ng/pattern/scrollable/scrollable_pattern.cpp", - "$ace_root/frameworks/core/components_ng/property/accessibility_property.cpp", - "$ace_root/frameworks/core/components_ng/property/templates_parser.cpp", - "$ace_root/frameworks/core/components_ng/test/event/scrollable_event/mock_scrollable.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/base/mock_view_abstract.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/manager/drag_drop/mock_drag_drop_manager.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/manager/drag_drop/mock_drag_drop_proxy.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/scroll/mock_scroll_bar_painter.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/scroll/mock_scroll_fade_painter.cpp", "$ace_root/frameworks/core/components_v2/grid/grid_event.cpp", - "$ace_root/frameworks/core/gestures/velocity_tracker.cpp", - "$ace_root/frameworks/core/pipeline/base/related_node.cpp", "grid_test_ng.cpp", ] - - sources += [ - # base - "$ace_root/frameworks/base/geometry/dimension.cpp", - "$ace_root/frameworks/base/json/json_util.cpp", - "$ace_root/frameworks/base/utils/base_id.cpp", - "$ace_root/frameworks/base/utils/string_expression.cpp", - "$ace_root/frameworks/base/utils/string_utils.cpp", - - # components - "$ace_root/frameworks/core/components/common/layout/grid_column_info.cpp", - "$ace_root/frameworks/core/components/common/layout/grid_container_info.cpp", - "$ace_root/frameworks/core/components/common/layout/grid_system_manager.cpp", - "$ace_root/frameworks/core/components/common/layout/screen_system_manager.cpp", - "$ace_root/frameworks/core/components/common/properties/alignment.cpp", - "$ace_root/frameworks/core/components/common/properties/color.cpp", - - # components_ng - "$ace_root/frameworks/core/components_ng/base/frame_node.cpp", - "$ace_root/frameworks/core/components_ng/base/geometry_node.cpp", - "$ace_root/frameworks/core/components_ng/base/modifier.cpp", - "$ace_root/frameworks/core/components_ng/base/ui_node.cpp", - "$ace_root/frameworks/core/components_ng/base/view_stack_processor.cpp", - "$ace_root/frameworks/core/components_ng/event/click_event.cpp", - "$ace_root/frameworks/core/components_ng/event/drag_event.cpp", - "$ace_root/frameworks/core/components_ng/event/event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/focus_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/gesture_event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/input_event.cpp", - "$ace_root/frameworks/core/components_ng/event/input_event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/pan_event.cpp", - "$ace_root/frameworks/core/components_ng/event/state_style_manager.cpp", - "$ace_root/frameworks/core/components_ng/event/touch_event.cpp", - "$ace_root/frameworks/core/components_ng/gestures/gesture_referee.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/click_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/exclusive_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/gesture_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/long_press_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/multi_fingers_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/pan_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/parallel_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/recognizer_group.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/sequenced_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/layout/box_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_property.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_builder.cpp", - "$ace_root/frameworks/core/components_ng/manager/safe_area/safe_area_manager.cpp", - "$ace_root/frameworks/core/components_ng/property/border_property.cpp", - "$ace_root/frameworks/core/components_ng/property/calc_length.cpp", - "$ace_root/frameworks/core/components_ng/property/grid_property.cpp", - "$ace_root/frameworks/core/components_ng/property/measure_utils.cpp", - "$ace_root/frameworks/core/components_ng/property/property.cpp", - "$ace_root/frameworks/core/components_ng/property/safe_area_insets.cpp", - "$ace_root/frameworks/core/components_ng/render/drawing_prop_convertor.cpp", - "$ace_root/frameworks/core/components_ng/render/paint_wrapper.cpp", - - # components_v2 - "$ace_root/frameworks/core/components_v2/inspector/inspector_constants.cpp", - - # pipeline - "$ace_root/frameworks/core/pipeline/base/constants.cpp", - - # mock - "$ace_root/frameworks/base/test/mock/mock_ressched_report.cpp", - "$ace_root/frameworks/base/test/mock/mock_socperf_client_impl.cpp", - "$ace_root/frameworks/base/test/mock/mock_system_properties.cpp", - "$ace_root/frameworks/core/common/test/mock/mock_ace_application_info.cpp", - "$ace_root/frameworks/core/components/test/unittest/mock/ace_trace_mock.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/animation/mock_geometry_transition.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/base/mock_localization.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/flex/mock_flex_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/grid_container/mock_grid_container_layout_property.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_animation_utils.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_modifier_adapter.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_context.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_context_creator.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_surface_creator.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/syntax/mock_for_each_node.cpp", - "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_element_register.cpp", - "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_pipeline_base.cpp", - "$ace_root/test/mock/core/common/mock_font_manager_ng.cpp", - ] - - deps = [ - "$ace_root/frameworks/base:ace_memory_monitor_ohos", - "$ace_root/frameworks/core/components/theme:build_theme_code", - "$ace_root/test/unittest:ace_unittest_log", - "$cjson_root:cjson_static", - "//third_party/googletest:gmock_main", - ] - - configs = [ "$ace_root/test/unittest:ace_unittest_config" ] } diff --git a/frameworks/core/components_ng/test/pattern/grid/grid_test_ng.cpp b/frameworks/core/components_ng/test/pattern/grid/grid_test_ng.cpp index 1b93ae00d93..fb33cb7bddf 100644 --- a/frameworks/core/components_ng/test/pattern/grid/grid_test_ng.cpp +++ b/frameworks/core/components_ng/test/pattern/grid/grid_test_ng.cpp @@ -37,6 +37,7 @@ #include "core/components_ng/test/mock/render/mock_render_context.h" #include "core/components_ng/test/mock/rosen/mock_canvas.h" #include "core/components_ng/test/mock/theme/mock_theme_manager.h" +#include "core/components_ng/test/pattern/test_ng.h" #include "core/pipeline/base/constants.h" #include "core/pipeline_ng/test/mock/mock_pipeline_base.h" #include "core/components_ng/pattern/grid/grid_scroll/grid_scroll_layout_algorithm.h" @@ -47,40 +48,29 @@ using namespace testing::ext; namespace OHOS::Ace::NG { namespace { -constexpr float DEVICE_WIDTH = 720.0f; -constexpr float DEVICE_HEIGHT = 1136.0f; -constexpr float ITEM_HEIGHT = 100.f; constexpr float ITEM_WIDTH = 100.f; +constexpr float ITEM_HEIGHT = 100.f; constexpr float GRID_HEIGHT = 300.f; } // namespace -class GridTestNg : public testing::Test { +class GridTestNg : public testing::Test, public TestNG { protected: static void SetUpTestSuite(); static void TearDownTestSuite(); void SetUp() override; void TearDown() override; void GetInstance(); - static void SetWidth(const Dimension& width); - static void SetHeight(const Dimension& height); void CreateGrid(int32_t itemNumber = 20, Axis axis = Axis::VERTICAL); void CreateGridItem(int32_t count = 10, float width = -1, float height = -1, bool focusable = false); void CreateSingleGridItem(int32_t rowStart = -1, int32_t rowEnd = -1, int32_t colStart = -1, int32_t colEnd = -1, float width = -1, float height = -1); - RefPtr RunMeasureAndLayout( - float width = DEVICE_WIDTH, float height = GRID_HEIGHT); void UpdateLayoutWrapper( RefPtr& layoutWrapper, float width = DEVICE_WIDTH, float height = GRID_HEIGHT); - RefPtr GetItemFrameNode(int32_t index); - RectF GetItemRect(int32_t index); - RefPtr GetItemPattern(int32_t index); - RefPtr GetItemFocusHub(int32_t index); void UpdateCurrentOffset(float offset, int32_t source = SCROLL_FROM_UPDATE); void MouseSelect(Offset start, Offset end); void MouseSelectRelease(); int32_t CalculateGridColumnsOrRows(float contentWidth, float gridWidth, float gutter = 0.0f, float margin = 0.0f); testing::AssertionResult IsEqualNextFocusNode(FocusStep step, int32_t currentIndex, int32_t nextIndex); - testing::AssertionResult IsEqualRect(RectF rect, RectF expectRect); testing::AssertionResult IsEqualCurrentOffset(float expectOffset); void UpdateLayoutInfo(); @@ -94,7 +84,7 @@ protected: void GridTestNg::UpdateLayoutInfo() { GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); pattern_->gridLayoutInfo_.lineHeightMap_[0] = ITEM_HEIGHT; pattern_->gridLayoutInfo_.gridMatrix_[0][0] = 0; pattern_->gridLayoutInfo_.gridMatrix_[0][1] = 1; @@ -138,20 +128,6 @@ void GridTestNg::GetInstance() accessibilityProperty_ = frameNode_->GetAccessibilityProperty(); } -void GridTestNg::SetWidth(const Dimension& width) -{ - auto frameNode = ViewStackProcessor::GetInstance()->GetMainFrameNode(); - auto layoutProperty = frameNode->GetLayoutProperty(); - layoutProperty->UpdateUserDefinedIdealSize(CalcSize(CalcLength(width), std::nullopt)); -} - -void GridTestNg::SetHeight(const Dimension& height) -{ - auto frameNode = ViewStackProcessor::GetInstance()->GetMainFrameNode(); - auto layoutProperty = frameNode->GetLayoutProperty(); - layoutProperty->UpdateUserDefinedIdealSize(CalcSize(std::nullopt, CalcLength(height))); -} - void GridTestNg::CreateGrid(int32_t itemNumber, Axis axis) { GridModelNG gridModelNG; @@ -166,7 +142,7 @@ void GridTestNg::CreateGrid(int32_t itemNumber, Axis axis) CreateGridItem(itemNumber, -1, ITEM_HEIGHT); } GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); } void GridTestNg::CreateGridItem( @@ -216,22 +192,6 @@ void GridTestNg::CreateSingleGridItem( ViewStackProcessor::GetInstance()->Pop(); } -RefPtr GridTestNg::RunMeasureAndLayout(float width, float height) -{ - RefPtr layoutWrapper = frameNode_->CreateLayoutWrapper(false, false); - layoutWrapper->SetActive(); - layoutWrapper->SetRootMeasureNode(); - LayoutConstraintF LayoutConstraint; - LayoutConstraint.parentIdealSize = { DEVICE_WIDTH, DEVICE_HEIGHT }; - LayoutConstraint.percentReference = { DEVICE_WIDTH, DEVICE_HEIGHT }; - LayoutConstraint.selfIdealSize = { width, height }; - LayoutConstraint.maxSize = { width, height }; - layoutWrapper->Measure(LayoutConstraint); - layoutWrapper->Layout(); - layoutWrapper->MountToHostOnMainThread(); - return layoutWrapper; -} - void GridTestNg::UpdateLayoutWrapper(RefPtr& layoutWrapper, float width, float height) { LayoutConstraintF LayoutConstraint; @@ -244,26 +204,6 @@ void GridTestNg::UpdateLayoutWrapper(RefPtr& layoutWrapper, f layoutWrapper->MountToHostOnMainThread(); } -RefPtr GridTestNg::GetItemFrameNode(int32_t index) -{ - return AceType::DynamicCast(frameNode_->GetChildAtIndex(index)); -} - -RectF GridTestNg::GetItemRect(int32_t index) -{ - return GetItemFrameNode(index)->GetGeometryNode()->GetFrameRect(); -} - -RefPtr GridTestNg::GetItemPattern(int32_t index) -{ - return GetItemFrameNode(index)->GetPattern(); -} - -RefPtr GridTestNg::GetItemFocusHub(int32_t index) -{ - return GetItemFrameNode(index)->GetOrCreateFocusHub(); -} - void GridTestNg::MouseSelect(Offset start, Offset end) { MouseInfo info; @@ -295,35 +235,24 @@ int32_t GridTestNg::CalculateGridColumnsOrRows(float contentWidth, float gridWid void GridTestNg::UpdateCurrentOffset(float offset, int32_t source) { pattern_->UpdateCurrentOffset(offset, source); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); } testing::AssertionResult GridTestNg::IsEqualNextFocusNode( FocusStep step, int32_t currentIndex, int32_t nextIndex) { - RefPtr currentFocusNode = GetItemFocusHub(currentIndex); + RefPtr currentFocusNode = GetChildFocusHub(frameNode_, currentIndex); currentFocusNode->RequestFocusImmediately(); RefPtr nextFocusNode = pattern_->GetNextFocusNode(step, currentFocusNode).Upgrade(); if (nextIndex == -1 && nextFocusNode != nullptr) { return testing::AssertionFailure() << "Next FocusNode is not null."; } - if (nextIndex != -1 && nextFocusNode != GetItemFocusHub(nextIndex)) { + if (nextIndex != -1 && nextFocusNode != GetChildFocusHub(frameNode_, nextIndex)) { return testing::AssertionFailure() << "Get wrong next FocusNode."; } return testing::AssertionSuccess(); } -testing::AssertionResult GridTestNg::IsEqualRect(RectF rect, RectF expectRect) -{ - if (rect == expectRect) { - return testing::AssertionSuccess(); - } - return testing::AssertionFailure() << - "rect: " << rect.ToString() << - " != " << - "expectRect: " << expectRect.ToString(); -} - testing::AssertionResult GridTestNg::IsEqualCurrentOffset(float expectOffset) { float currentOffset = pattern_->GetGridLayoutInfo().currentOffset_; @@ -354,7 +283,7 @@ HWTEST_F(GridTestNg, Property001, TestSize.Level1) gridModelNG.SetEdgeEffect(EdgeEffect::SPRING); CreateGridItem(10, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); EXPECT_EQ(layoutProperty_->GetRowsTemplateValue(), "1fr 1fr 1fr"); EXPECT_EQ(layoutProperty_->GetColumnsTemplateValue(), "1fr 1fr"); @@ -385,7 +314,7 @@ HWTEST_F(GridTestNg, Property002, TestSize.Level1) gridModelNG.SetColumnsGap(Dimension(-10)); CreateGridItem(10, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. Verify GapValue @@ -475,7 +404,7 @@ HWTEST_F(GridTestNg, AttrColumnsTemplate001, TestSize.Level1) gridModelNG.SetRowsGap(rowsGap); CreateGridItem(gridItemNumber, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. While only set ColumnsTemplate @@ -491,12 +420,12 @@ HWTEST_F(GridTestNg, AttrColumnsTemplate001, TestSize.Level1) const float colsGapTotal = columnsGap.ConvertToPx() * (colsNumber - 1); const float averageWidth = (DEVICE_WIDTH - colsGapTotal) / colsNumber; for (int32_t index = 0; index < gridItemNumber; index++) { - RectF childRect = GetItemRect(index); + RectF childRect = GetChildRect(frameNode_, index); float offsetX = index % colsNumber * (averageWidth + columnsGap.ConvertToPx()); float offsetY = floor(index / colsNumber) * (ITEM_HEIGHT + rowsGap.ConvertToPx()); RectF expectRect = RectF(offsetX, offsetY, averageWidth, ITEM_HEIGHT); EXPECT_TRUE(IsEqualRect(childRect, expectRect)); - EXPECT_TRUE(GetItemFrameNode(index)->IsActive()); + EXPECT_TRUE(GetChildFrameNode(frameNode_, index)->IsActive()); } } @@ -515,14 +444,14 @@ HWTEST_F(GridTestNg, AttrColumnsTemplate002, TestSize.Level1) constexpr int32_t gridItemNumber = 10; CreateGridItem(gridItemNumber, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. Verify index 1 gridItem rect * @tc.expected: The rect is equal to expectRect */ const float averageWidth = DEVICE_WIDTH / 7; - RectF rect_1 = GetItemRect(1); + RectF rect_1 = GetChildRect(frameNode_, 1); const float offsetX_1 = averageWidth; const float offsetY_1 = 0.f; const float width_1 = averageWidth * 2; @@ -534,7 +463,7 @@ HWTEST_F(GridTestNg, AttrColumnsTemplate002, TestSize.Level1) * @tc.steps: step2. Verify index 6 gridItem rect * @tc.expected: The rect is equal to expectRect */ - RectF rect_6 = GetItemRect(6); + RectF rect_6 = GetChildRect(frameNode_, 6); const float offsetX_6 = averageWidth * 3; const float offsetY_6 = ITEM_HEIGHT; const float width_6 = averageWidth * 3; @@ -558,14 +487,14 @@ HWTEST_F(GridTestNg, AttrColumnsTemplate003, TestSize.Level1) constexpr int32_t gridItemNumber = 10; CreateGridItem(gridItemNumber, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. Verify index 1 gridItem rect * @tc.expected: The item width is zero */ const float averageWidth = DEVICE_WIDTH / 2; - RectF rect_1 = GetItemRect(1); + RectF rect_1 = GetChildRect(frameNode_, 1); const float offsetX_1 = averageWidth; const float offsetY_1 = 0.f; const float width_1 = 0.f; @@ -593,7 +522,7 @@ HWTEST_F(GridTestNg, AttrColumnsTemplate004, TestSize.Level1) constexpr int32_t gridItemNumber = 10; CreateGridItem(gridItemNumber, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. While only set ColumnsTemplate @@ -610,7 +539,7 @@ HWTEST_F(GridTestNg, AttrColumnsTemplate004, TestSize.Level1) const float colsGapTotal = columnsGap.ConvertToPx() * (colsNumber - 1); const float averageWidth = (DEVICE_WIDTH - colsGapTotal) / colsNumber; for (int32_t index = 0; index < gridItemNumber; index++) { - RectF childRect = GetItemRect(index); + RectF childRect = GetChildRect(frameNode_, index); float offsetX = index % colsNumber * (averageWidth + columnsGap.ConvertToPx()); float offsetY = floor(index / colsNumber) * (ITEM_HEIGHT + rowsGap.ConvertToPx()); RectF expectRect = RectF(offsetX, offsetY, averageWidth, ITEM_HEIGHT); @@ -637,7 +566,7 @@ HWTEST_F(GridTestNg, AttrRowsTemplate001, TestSize.Level1) constexpr int32_t gridItemNumber = 10; CreateGridItem(gridItemNumber, ITEM_WIDTH, -1); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. While only set rowsTemplate @@ -653,12 +582,12 @@ HWTEST_F(GridTestNg, AttrRowsTemplate001, TestSize.Level1) const float rowsGapTotal = rowsGap.ConvertToPx() * (rowsNumber - 1); const float averageHeight = (GRID_HEIGHT - rowsGapTotal) / rowsNumber; for (int32_t index = 0; index < gridItemNumber; index++) { - RectF childRect = GetItemRect(index); + RectF childRect = GetChildRect(frameNode_, index); float offsetX = floor(index / rowsNumber) * (ITEM_WIDTH + columnsGap.ConvertToPx()); float offsetY = index % rowsNumber * (averageHeight + rowsGap.ConvertToPx()); RectF expectRect = RectF(offsetX, offsetY, ITEM_WIDTH, averageHeight); EXPECT_TRUE(IsEqualRect(childRect, expectRect)); - EXPECT_TRUE(GetItemFrameNode(index)->IsActive()); + EXPECT_TRUE(GetChildFrameNode(frameNode_, index)->IsActive()); } } @@ -677,14 +606,14 @@ HWTEST_F(GridTestNg, AttrRowsTemplate002, TestSize.Level1) constexpr int32_t gridItemNumber = 10; CreateGridItem(gridItemNumber, ITEM_WIDTH, -1); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. Verify index 1 gridItem rect * @tc.expected: The rect is equal to expectRect */ const float averageHeight = GRID_HEIGHT / 7; - RectF rect_1 = GetItemRect(1); + RectF rect_1 = GetChildRect(frameNode_, 1); const float offsetX_1 = 0.f; const float offsetY_1 = averageHeight; const float width_1 = ITEM_WIDTH; @@ -696,7 +625,7 @@ HWTEST_F(GridTestNg, AttrRowsTemplate002, TestSize.Level1) * @tc.steps: step2. Verify index 6 gridItem rect * @tc.expected: The rect is equal to expectRect */ - RectF rect_6 = GetItemRect(6); + RectF rect_6 = GetChildRect(frameNode_, 6); const float offsetX_6 = ITEM_WIDTH; const float offsetY_6 = averageHeight * 3; const float width_6 = ITEM_WIDTH; @@ -720,14 +649,14 @@ HWTEST_F(GridTestNg, AttrRowsTemplate003, TestSize.Level1) constexpr int32_t gridItemNumber = 10; CreateGridItem(gridItemNumber, ITEM_WIDTH, -1); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. Verify index 1 gridItem rect * @tc.expected: The item height is zero */ const float averageHeight = GRID_HEIGHT / 2; - RectF rect_1 = GetItemRect(1); + RectF rect_1 = GetChildRect(frameNode_, 1); const float offsetX_1 = 0.f; const float offsetY_1 = averageHeight; const float width_1 = ITEM_WIDTH; @@ -755,7 +684,7 @@ HWTEST_F(GridTestNg, AttrRowsTemplate004, TestSize.Level1) constexpr int32_t gridItemNumber = 10; CreateGridItem(gridItemNumber, ITEM_WIDTH, -1); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. While only set rowsTemplate @@ -772,7 +701,7 @@ HWTEST_F(GridTestNg, AttrRowsTemplate004, TestSize.Level1) const float rowsGapTotal = rowsGap.ConvertToPx() * (rowsNumber - 1); const float averageHeight = (GRID_HEIGHT - rowsGapTotal) / rowsNumber; for (int32_t index = 0; index < gridItemNumber; index++) { - RectF childRect = GetItemRect(index); + RectF childRect = GetChildRect(frameNode_, index); float offsetX = floor(index / rowsNumber) * (ITEM_WIDTH + columnsGap.ConvertToPx()); float offsetY = index % rowsNumber * (averageHeight + rowsGap.ConvertToPx()); RectF expectRect = RectF(offsetX, offsetY, ITEM_WIDTH, averageHeight); @@ -794,7 +723,7 @@ HWTEST_F(GridTestNg, AttrColumnsRows001, TestSize.Level1) gridModelNG.SetColumnsTemplate(""); CreateGridItem(10, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. compare grid properties and expected value after change. @@ -812,13 +741,6 @@ HWTEST_F(GridTestNg, AttrColumnsRows001, TestSize.Level1) */ HWTEST_F(GridTestNg, AttrColumnsRows002, TestSize.Level1) { - /** - * 0__180_360_540_720 - * 75 |___|___|___|___| - * 150|___|___|___|___| - * 225|___|___|___|___| - * 300|___|___|___|___| - */ GridModelNG gridModelNG; gridModelNG.Create(nullptr, nullptr); const std::string colstemplate = "1fr 1fr 1fr 1fr"; @@ -829,7 +751,7 @@ HWTEST_F(GridTestNg, AttrColumnsRows002, TestSize.Level1) // not set gridItem width/height, gridItem will fill the mesh size by default CreateGridItem(gridItemNumber); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. Set both columns/rows Template @@ -840,12 +762,12 @@ HWTEST_F(GridTestNg, AttrColumnsRows002, TestSize.Level1) const float averageWidth = DEVICE_WIDTH / colsNumber; const float averageHeight = GRID_HEIGHT / rowsNumber; for (int32_t index = 0; index < gridItemNumber; index++) { - RectF childRect = GetItemRect(index); + RectF childRect = GetChildRect(frameNode_, index); float offsetX = index % colsNumber * averageWidth; float offsetY = floor(index / colsNumber) * averageHeight; RectF expectRect = RectF(offsetX, offsetY, averageWidth, averageHeight); EXPECT_TRUE(IsEqualRect(childRect, expectRect)); - EXPECT_TRUE(GetItemFrameNode(index)->IsActive()); + EXPECT_TRUE(GetChildFrameNode(frameNode_, index)->IsActive()); } } @@ -857,12 +779,6 @@ HWTEST_F(GridTestNg, AttrColumnsRows002, TestSize.Level1) */ HWTEST_F(GridTestNg, AttrLayoutDirection001, TestSize.Level1) { - /** - * 0__110_220_330_430_________720 - * 105|_0_|_1_|___|___| | - * 210|___|___|___|___| | - * 300|__________________________| - */ GridModelNG gridModelNG; gridModelNG.Create(nullptr, nullptr); gridModelNG.SetLayoutDirection(FlexDirection::ROW); @@ -878,7 +794,7 @@ HWTEST_F(GridTestNg, AttrLayoutDirection001, TestSize.Level1) constexpr int32_t gridItemNumber = 10; CreateGridItem(gridItemNumber, ITEM_WIDTH, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. Not set columns/rows Template @@ -888,15 +804,15 @@ HWTEST_F(GridTestNg, AttrLayoutDirection001, TestSize.Level1) constexpr int32_t activeCount = 8; for (int32_t index = 0; index < gridItemNumber; index++) { if (index < activeCount) { - RectF childRect = GetItemRect(index); + RectF childRect = GetChildRect(frameNode_, index); float offsetX = index % colsNumber * (ITEM_WIDTH + columnsGap.ConvertToPx()); float offsetY = floor(index / colsNumber) * (ITEM_HEIGHT + rowsGap.ConvertToPx()); RectF expectRect = RectF(offsetX, offsetY, ITEM_WIDTH, ITEM_HEIGHT); EXPECT_TRUE(IsEqualRect(childRect, expectRect)) << "index: " << index; - EXPECT_TRUE(GetItemFrameNode(index)->IsActive()); + EXPECT_TRUE(GetChildFrameNode(frameNode_, index)->IsActive()); } else { // beyond grid size, would not load - EXPECT_FALSE(GetItemFrameNode(index)->IsActive()); + EXPECT_FALSE(GetChildFrameNode(frameNode_, index)->IsActive()); } } } @@ -909,12 +825,6 @@ HWTEST_F(GridTestNg, AttrLayoutDirection001, TestSize.Level1) */ HWTEST_F(GridTestNg, AttrLayoutDirection002, TestSize.Level1) { - /** - * 0__110_220_330_430_________720 - * 105|___|___|_1_|_0_| | - * 210|___|___|___|___| | - * 300|__________________________| - */ GridModelNG gridModelNG; gridModelNG.Create(nullptr, nullptr); gridModelNG.SetLayoutDirection(FlexDirection::ROW_REVERSE); @@ -930,7 +840,7 @@ HWTEST_F(GridTestNg, AttrLayoutDirection002, TestSize.Level1) constexpr int32_t gridItemNumber = 10; CreateGridItem(gridItemNumber, ITEM_WIDTH, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. Not set columns/rows Template @@ -941,16 +851,16 @@ HWTEST_F(GridTestNg, AttrLayoutDirection002, TestSize.Level1) const float colsWidthTotal = colsNumber * ITEM_WIDTH + (colsNumber - 1) * columnsGap.ConvertToPx(); for (int32_t index = 0; index < gridItemNumber; index++) { if (index < activeCount) { - RectF childRect = GetItemRect(index); + RectF childRect = GetChildRect(frameNode_, index); float offsetX = colsWidthTotal - (index % colsNumber + 1) * ITEM_WIDTH - index % colsNumber * columnsGap.ConvertToPx(); float offsetY = floor(index / colsNumber) * (ITEM_HEIGHT + rowsGap.ConvertToPx()); RectF expectRect = RectF(offsetX, offsetY, ITEM_WIDTH, ITEM_HEIGHT); EXPECT_TRUE(IsEqualRect(childRect, expectRect)) << "index: " << index; - EXPECT_TRUE(GetItemFrameNode(index)->IsActive()); + EXPECT_TRUE(GetChildFrameNode(frameNode_, index)->IsActive()); } else { // beyond grid size, would not load - EXPECT_FALSE(GetItemFrameNode(index)->IsActive()); + EXPECT_FALSE(GetChildFrameNode(frameNode_, index)->IsActive()); } } } @@ -963,12 +873,6 @@ HWTEST_F(GridTestNg, AttrLayoutDirection002, TestSize.Level1) */ HWTEST_F(GridTestNg, AttrLayoutDirection003, TestSize.Level1) { - /** - * 0__110_220_330_440_540_____720 - * 105|_0_|___|___|___|___| | - * 210|_1_|___|___|___|___| | - * 300|__________________________| - */ GridModelNG gridModelNG; gridModelNG.Create(nullptr, nullptr); gridModelNG.SetLayoutDirection(FlexDirection::COLUMN); @@ -984,20 +888,25 @@ HWTEST_F(GridTestNg, AttrLayoutDirection003, TestSize.Level1) constexpr int32_t gridItemNumber = 10; CreateGridItem(gridItemNumber, ITEM_WIDTH, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. Not set columns/rows Template * @tc.expected: The gridItem rect would effect by minCount, maxCount, gap ... */ constexpr int32_t rowsNumber = 2; + constexpr int32_t showItemNumber = 8; for (int32_t index = 0; index < gridItemNumber; index++) { - RectF childRect = GetItemRect(index); - float offsetX = floor(index / rowsNumber) * (ITEM_WIDTH + columnsGap.ConvertToPx()); - float offsetY = index % rowsNumber * (ITEM_HEIGHT + rowsGap.ConvertToPx()); - RectF expectRect = RectF(offsetX, offsetY, ITEM_WIDTH, ITEM_HEIGHT); - EXPECT_TRUE(IsEqualRect(childRect, expectRect)) << "index: " << index; - EXPECT_TRUE(GetItemFrameNode(index)->IsActive()); + if (index < showItemNumber) { + RectF childRect = GetChildRect(frameNode_, index); + float offsetX = floor(index / rowsNumber) * (ITEM_WIDTH + columnsGap.ConvertToPx()); + float offsetY = index % rowsNumber * (ITEM_HEIGHT + rowsGap.ConvertToPx()); + RectF expectRect = RectF(offsetX, offsetY, ITEM_WIDTH, ITEM_HEIGHT); + EXPECT_TRUE(IsEqualRect(childRect, expectRect)) << "index: " << index; + EXPECT_TRUE(GetChildFrameNode(frameNode_, index)->IsActive()); + } else { + EXPECT_FALSE(GetChildFrameNode(frameNode_, index)->IsActive()); + } } } @@ -1009,12 +918,6 @@ HWTEST_F(GridTestNg, AttrLayoutDirection003, TestSize.Level1) */ HWTEST_F(GridTestNg, AttrLayoutDirection004, TestSize.Level1) { - /** - * 0__110_220_330_440_540_____720 - * 105|_1_|___|___|___|___| | - * 210|_0_|___|___|___|___| | - * 300|__________________________| - */ GridModelNG gridModelNG; gridModelNG.Create(nullptr, nullptr); gridModelNG.SetLayoutDirection(FlexDirection::COLUMN_REVERSE); @@ -1030,22 +933,27 @@ HWTEST_F(GridTestNg, AttrLayoutDirection004, TestSize.Level1) constexpr int32_t gridItemNumber = 10; CreateGridItem(gridItemNumber, ITEM_WIDTH, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. Not set columns/rows Template * @tc.expected: The gridItem rect would effect by minCount, maxCount, gap ... */ constexpr int32_t rowsNumber = 2; + constexpr int32_t showItemNumber = 8; const float rowsHeightTotal = rowsNumber * ITEM_HEIGHT + (rowsNumber - 1) * rowsGap.ConvertToPx(); for (int32_t index = 0; index < gridItemNumber; index++) { - RectF childRect = GetItemRect(index); - float offsetX = floor(index / rowsNumber) * (ITEM_WIDTH + columnsGap.ConvertToPx()); - float offsetY = rowsHeightTotal - (index % rowsNumber + 1) * ITEM_HEIGHT - - index % rowsNumber * rowsGap.ConvertToPx(); - RectF expectRect = RectF(offsetX, offsetY, ITEM_WIDTH, ITEM_HEIGHT); - EXPECT_TRUE(IsEqualRect(childRect, expectRect)) << "index: " << index; - EXPECT_TRUE(GetItemFrameNode(index)->IsActive()); + if (index < showItemNumber) { + RectF childRect = GetChildRect(frameNode_, index); + float offsetX = floor(index / rowsNumber) * (ITEM_WIDTH + columnsGap.ConvertToPx()); + float offsetY = rowsHeightTotal - (index % rowsNumber + 1) * ITEM_HEIGHT - + index % rowsNumber * rowsGap.ConvertToPx(); + RectF expectRect = RectF(offsetX, offsetY, ITEM_WIDTH, ITEM_HEIGHT); + EXPECT_TRUE(IsEqualRect(childRect, expectRect)) << "index: " << index; + EXPECT_TRUE(GetChildFrameNode(frameNode_, index)->IsActive()); + } else { + EXPECT_FALSE(GetChildFrameNode(frameNode_, index)->IsActive()); + } } } @@ -1056,13 +964,6 @@ HWTEST_F(GridTestNg, AttrLayoutDirection004, TestSize.Level1) */ HWTEST_F(GridTestNg, AttrGridItem001, TestSize.Level1) { - /** - * 0__180_360_540_720 - * 75|_____1_____| | - * 150|___| 0 | 2 | - * 225|___|_______| | - * 300|___|___|___|___| - */ GridModelNG gridModelNG; gridModelNG.Create(nullptr, nullptr); const std::string rowsTemplate = "1fr 1fr 1fr 1fr"; @@ -1075,9 +976,9 @@ HWTEST_F(GridTestNg, AttrGridItem001, TestSize.Level1) CreateSingleGridItem(1, 3, -1, -1); CreateGridItem(7); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); - RectF rect_0 = GetItemRect(0); + RectF rect_0 = GetChildRect(frameNode_, 0); const float averageWidth = DEVICE_WIDTH / 4; const float averageHeight = GRID_HEIGHT / 4; const float offsetX_0 = averageWidth; @@ -1087,7 +988,7 @@ HWTEST_F(GridTestNg, AttrGridItem001, TestSize.Level1) const RectF expectRect_0 = RectF(offsetX_0, offsetY_0, width_0, height_0); EXPECT_TRUE(IsEqualRect(rect_0, expectRect_0)); - RectF rect_1 = GetItemRect(1); + RectF rect_1 = GetChildRect(frameNode_, 1); const float offsetX_1 = 0.f; const float offsetY_1 = 0.f; const float width_1 = averageWidth * 3; @@ -1095,7 +996,7 @@ HWTEST_F(GridTestNg, AttrGridItem001, TestSize.Level1) const RectF expectRect_1 = RectF(offsetX_1, offsetY_1, width_1, height_1); EXPECT_TRUE(IsEqualRect(rect_1, expectRect_1)); - RectF rect_2 = GetItemRect(2); + RectF rect_2 = GetChildRect(frameNode_, 2); const float offsetX_2 = averageWidth * 3; const float offsetY_2 = 0.f; const float width_2 = averageWidth; @@ -1111,13 +1012,6 @@ HWTEST_F(GridTestNg, AttrGridItem001, TestSize.Level1) */ HWTEST_F(GridTestNg, AttrGridItem002, TestSize.Level1) { - /** - * 0__100_200_300 - * 75|___| |___| - * 150| 0 | 1 |___| - * 225|___|___| 2 | - * 300|___|___|___| - */ GridModelNG gridModelNG; gridModelNG.Create(nullptr, nullptr); const std::string rowsTemplate = "1fr 1fr 1fr 1fr"; @@ -1128,22 +1022,22 @@ HWTEST_F(GridTestNg, AttrGridItem002, TestSize.Level1) CreateSingleGridItem(2, 3, -1, -1, ITEM_WIDTH, -1); CreateGridItem(7, ITEM_WIDTH, -1); GetInstance(); - RunMeasureAndLayout(300.f); + RunMeasureAndLayout(frameNode_, 300.f, GRID_HEIGHT); const float averageHeight = GRID_HEIGHT / 4; - EXPECT_TRUE(IsEqualRect(GetItemRect(0), RectF( + EXPECT_TRUE(IsEqualRect(GetChildRect(frameNode_, 0), RectF( 0.f, averageHeight, ITEM_WIDTH, averageHeight * 2 ))); - EXPECT_TRUE(IsEqualRect(GetItemRect(1), RectF( + EXPECT_TRUE(IsEqualRect(GetChildRect(frameNode_, 1), RectF( ITEM_WIDTH, 0.f, ITEM_WIDTH, averageHeight * 3 ))); - EXPECT_TRUE(IsEqualRect(GetItemRect(2), RectF( + EXPECT_TRUE(IsEqualRect(GetChildRect(frameNode_, 2), RectF( ITEM_WIDTH * 2, averageHeight * 2, ITEM_WIDTH, @@ -1151,14 +1045,14 @@ HWTEST_F(GridTestNg, AttrGridItem002, TestSize.Level1) ))); UpdateCurrentOffset(-ITEM_WIDTH); - EXPECT_TRUE(IsEqualRect(GetItemRect(1), RectF( - ITEM_WIDTH, + EXPECT_TRUE(IsEqualRect(GetChildRect(frameNode_, 1), RectF( + 80.f, 0.f, ITEM_WIDTH, averageHeight * 3 ))); - EXPECT_TRUE(IsEqualRect(GetItemRect(2), RectF( - ITEM_WIDTH * 2, + EXPECT_TRUE(IsEqualRect(GetChildRect(frameNode_, 2), RectF( + 180.f, averageHeight * 2, ITEM_WIDTH, averageHeight * 2 @@ -1172,12 +1066,6 @@ HWTEST_F(GridTestNg, AttrGridItem002, TestSize.Level1) */ HWTEST_F(GridTestNg, AttrGridItem003, TestSize.Level1) { - /** - * 0__180_360_540_720 - * 100|___|___|___0___| - * 200|_____1_____|___| - * 300|___|___|_2_|___| - */ GridModelNG gridModelNG; gridModelNG.Create(nullptr, nullptr); const std::string columnsTemplate = "1fr 1fr 1fr 1fr"; @@ -1188,22 +1076,22 @@ HWTEST_F(GridTestNg, AttrGridItem003, TestSize.Level1) CreateSingleGridItem(-1, -1, 2, 1, -1, ITEM_HEIGHT); CreateGridItem(7, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); const float averageWidth = DEVICE_WIDTH / 4; - EXPECT_TRUE(IsEqualRect(GetItemRect(0), RectF( + EXPECT_TRUE(IsEqualRect(GetChildRect(frameNode_, 0), RectF( averageWidth * 2, 0.f, averageWidth * 2, ITEM_HEIGHT ))); - EXPECT_TRUE(IsEqualRect(GetItemRect(1), RectF( + EXPECT_TRUE(IsEqualRect(GetChildRect(frameNode_, 1), RectF( 0.f, ITEM_HEIGHT, averageWidth * 3, ITEM_HEIGHT ))); - EXPECT_TRUE(IsEqualRect(GetItemRect(2), RectF( + EXPECT_TRUE(IsEqualRect(GetChildRect(frameNode_, 2), RectF( averageWidth * 2, ITEM_HEIGHT * 2, averageWidth, @@ -1211,13 +1099,13 @@ HWTEST_F(GridTestNg, AttrGridItem003, TestSize.Level1) ))); UpdateCurrentOffset(-ITEM_HEIGHT); - EXPECT_TRUE(IsEqualRect(GetItemRect(1), RectF( + EXPECT_TRUE(IsEqualRect(GetChildRect(frameNode_, 1), RectF( 0.f, 0.f, averageWidth * 3, ITEM_HEIGHT ))); - EXPECT_TRUE(IsEqualRect(GetItemRect(2), RectF( + EXPECT_TRUE(IsEqualRect(GetChildRect(frameNode_, 2), RectF( averageWidth * 2, ITEM_HEIGHT, averageWidth, @@ -1241,7 +1129,7 @@ HWTEST_F(GridTestNg, AttrEnableScrollInteraction001, TestSize.Level1) gridModelNG.SetScrollEnabled(true); CreateGridItem(10, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); EXPECT_EQ(layoutProperty_->GetScrollEnabled(), true); /** @@ -1305,7 +1193,7 @@ HWTEST_F(GridTestNg, GridTest001, TestSize.Level1) gridModelNG.SetColumnsTemplate("1fr 1fr 1fr 1fr"); CreateGridItem(20, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. test OnModifyDone(). @@ -1335,7 +1223,7 @@ HWTEST_F(GridTestNg, GridTest002, TestSize.Level1) gridModelNG.Create(nullptr, nullptr); CreateGridItem(10, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); pattern_->AnimateTo(100.f, 200.f, Curves::LINEAR, false); ASSERT_EQ(pattern_->animator_, nullptr); @@ -1404,7 +1292,7 @@ HWTEST_F(GridTestNg, ScrollablePattern001, TestSize.Level1) */ HWTEST_F(GridTestNg, EventHub001, TestSize.Level1) { - CreateGrid(); + CreateGrid(8); RectF gridRect(0.f, 0.f, DEVICE_WIDTH, GRID_HEIGHT); EXPECT_CALL( *(AceType::RawPtr(AceType::DynamicCast(frameNode_->renderContext_))), @@ -1416,17 +1304,17 @@ HWTEST_F(GridTestNg, EventHub001, TestSize.Level1) */ EXPECT_EQ(eventHub_->GetInsertPosition(DEVICE_WIDTH + 1, DEVICE_HEIGHT), -1); // out of grid EXPECT_EQ(eventHub_->GetInsertPosition(0.f, 0.f), 0); // 0, 0 - EXPECT_EQ(eventHub_->GetInsertPosition(90.f, 50.f), 0); // first item - EXPECT_EQ(eventHub_->GetInsertPosition(360.f, 50.f), 1); // between the second and third - EXPECT_EQ(eventHub_->GetInsertPosition(360.f, 100.f), 1); // between the 2nd, 3rd, 6th, 7th - EXPECT_EQ(eventHub_->GetInsertPosition(180.f, 300.f), 8); // in grid but not on item + EXPECT_EQ(eventHub_->GetInsertPosition(ITEM_WIDTH / 2, ITEM_HEIGHT / 2), 0); // first item + EXPECT_EQ(eventHub_->GetInsertPosition(ITEM_WIDTH * 2, ITEM_HEIGHT / 2), 1); // between the second and third + EXPECT_EQ(eventHub_->GetInsertPosition(ITEM_WIDTH * 2, ITEM_HEIGHT), 1); // between the 2nd, 3rd, 6th, 7th + EXPECT_EQ(eventHub_->GetInsertPosition(ITEM_WIDTH, GRID_HEIGHT), 8); // in grid but not on item pattern_->GetGridLayoutInfo().currentRect_ = RectF(0.f, 0.f, 180.f, 300.f); EXPECT_EQ(eventHub_->GetInsertPosition(180.f, 300.f), 8); // on currentRect_ /** * @tc.steps: step2. call GetFrameNodeChildSize func. */ - EXPECT_EQ(eventHub_->GetFrameNodeChildSize(), 20); + EXPECT_EQ(eventHub_->GetFrameNodeChildSize(), 8); } /** @@ -1483,7 +1371,7 @@ HWTEST_F(GridTestNg, PositionController001, TestSize.Level1) * @tc.steps: step6. Test ScrollPage func. * @tc.expected: Verify currentOffset. */ - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); controller->ScrollPage(true, true); EXPECT_EQ(controller->GetCurrentOffset(), Offset(0, -300.f)); @@ -1495,7 +1383,7 @@ HWTEST_F(GridTestNg, PositionController001, TestSize.Level1) */ EXPECT_FALSE(controller->IsAtEnd()); controller->ScrollToEdge(ScrollEdgeType::SCROLL_BOTTOM, true); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); EXPECT_TRUE(controller->IsAtEnd()); } @@ -1510,7 +1398,7 @@ HWTEST_F(GridTestNg, PositionController002, TestSize.Level1) * @tc.steps: step1. Change Grid width to 300. */ CreateGrid(20, Axis::HORIZONTAL); - RunMeasureAndLayout(300.f); + RunMeasureAndLayout(frameNode_, 300.f, GRID_HEIGHT); /** * @tc.steps: step2. Test GetScrollDirection func. @@ -1537,11 +1425,11 @@ HWTEST_F(GridTestNg, PositionController002, TestSize.Level1) * @tc.expected: Verify currentOffset. */ pattern_->UpdateCurrentOffset(-20.f, SCROLL_FROM_UPDATE); - controller->ScrollPage(true, true); - EXPECT_EQ(controller->GetCurrentOffset(), Offset(0, 0)); - EXPECT_EQ(pattern_->GetMainContentSize(), 720.f); - controller->ScrollPage(false, true); - EXPECT_EQ(controller->GetCurrentOffset(), Offset(0, 0)); + controller->ScrollPage(true, false); + EXPECT_TRUE(IsEqualOffset(controller->GetCurrentOffset(), Offset(-460.f, 0))); + EXPECT_EQ(pattern_->GetMainContentSize(), DEVICE_WIDTH); + controller->ScrollPage(false, false); + EXPECT_TRUE(IsEqualOffset(controller->GetCurrentOffset(), Offset(20.f, 0))); } /** @@ -1577,7 +1465,7 @@ HWTEST_F(GridTestNg, GridAccessibilityTest001, TestSize.Level1) gridModelNG.SetEditable(true); CreateGridItem(14, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. Run accessibility func. @@ -1605,7 +1493,7 @@ HWTEST_F(GridTestNg, GridAccessibilityTest002, TestSize.Level1) gridModelNG.Create(nullptr, nullptr); CreateGridItem(8, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. Run GetCollectionInfo Func. @@ -1630,7 +1518,7 @@ HWTEST_F(GridTestNg, GridAccessibilityTest003, TestSize.Level1) gridModelNG.SetColumnsTemplate("1fr 1fr 1fr 1fr"); CreateGridItem(14, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. Run SetSpecificSupportAction func. @@ -1658,7 +1546,7 @@ HWTEST_F(GridTestNg, GridAccessibilityTest004, TestSize.Level1) gridModelNG.Create(nullptr, nullptr); CreateGridItem(14, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. Run SetSpecificSupportAction func. @@ -1686,14 +1574,14 @@ HWTEST_F(GridTestNg, GridAccessibilityTest005, TestSize.Level1) gridModelNG.SetColumnsTemplate("1fr 1fr 1fr 1fr"); CreateGridItem(14, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. Run SetSpecificSupportAction func. * @tc.expected: The return_value is correct. */ pattern_->UpdateCurrentOffset(100.f, SCROLL_FROM_UPDATE); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); accessibilityProperty_->ResetSupportAction(); std::unordered_set supportAceActions = accessibilityProperty_->GetSupportAction(); uint64_t actions = 0, exptectActions = 0; @@ -1717,14 +1605,14 @@ HWTEST_F(GridTestNg, GridAccessibilityTest006, TestSize.Level1) gridModelNG.SetColumnsTemplate("1fr 1fr 1fr 1fr"); CreateGridItem(14, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. Run SetSpecificSupportAction func. * @tc.expected: The return_value is correct. */ pattern_->UpdateCurrentOffset(-200.f, SCROLL_FROM_UPDATE); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); accessibilityProperty_->ResetSupportAction(); std::unordered_set supportAceActions = accessibilityProperty_->GetSupportAction(); uint64_t actions = 0, exptectActions = 0; @@ -1747,12 +1635,12 @@ HWTEST_F(GridTestNg, GridAccessibilityTest007, TestSize.Level1) gridModelNG.SetColumnsTemplate("1fr 1fr 1fr 1fr"); CreateGridItem(10, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. Get 2nd GridItem. */ - auto itemFrameNode = GetItemFrameNode(1); + auto itemFrameNode = GetChildFrameNode(frameNode_, 1); ASSERT_NE(itemFrameNode, nullptr); auto itemAccessibility = itemFrameNode->GetAccessibilityProperty(); ASSERT_NE(itemAccessibility, nullptr); @@ -1806,12 +1694,12 @@ HWTEST_F(GridTestNg, GridAccessibilityTest008, TestSize.Level1) ViewStackProcessor::GetInstance()->Pop(); CreateGridItem(10, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step2. Get 1st GridItem. */ - auto itemFrameNode = GetItemFrameNode(0); + auto itemFrameNode = GetChildFrameNode(frameNode_, 0); ASSERT_NE(itemFrameNode, nullptr); auto itemAccessibility = itemFrameNode->GetAccessibilityProperty(); ASSERT_NE(itemAccessibility, nullptr); @@ -1841,14 +1729,14 @@ HWTEST_F(GridTestNg, MouseSelect001, TestSize.Level1) gridModelNG.SetMultiSelectable(true); CreateGridItem(8, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. Click the (0, 0) point of firstItem. * @tc.expected: item not selected on MouseAction::PRESS. */ MouseSelect(Offset(0.f, 0.f), Offset(0.f, 0.f)); - EXPECT_FALSE(GetItemPattern(0)->IsSelected()); + EXPECT_FALSE(GetChildPattern(frameNode_, 0)->IsSelected()); } /** @@ -1869,17 +1757,17 @@ HWTEST_F(GridTestNg, MouseSelect002, TestSize.Level1) gridModelNG.SetMultiSelectable(true); CreateGridItem(8, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. Select (0, 0) - (180, 100) zone. * @tc.expected: The 1st, 2nd, 5th, 6th items are selected. */ MouseSelect(Offset(0.f, 0.f), Offset(180.f, 100.f)); - EXPECT_TRUE(GetItemPattern(0)->IsSelected()); - EXPECT_TRUE(GetItemPattern(1)->IsSelected()); - EXPECT_TRUE(GetItemPattern(4)->IsSelected()); - EXPECT_TRUE(GetItemPattern(5)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 0)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 1)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 4)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 5)->IsSelected()); MouseSelectRelease(); /** @@ -1887,10 +1775,10 @@ HWTEST_F(GridTestNg, MouseSelect002, TestSize.Level1) * @tc.expected: The 1st, 2nd, 5th, 6th are selected. */ MouseSelect(LEFT_TOP, RIGHT_BOTTOM); - EXPECT_TRUE(GetItemPattern(0)->IsSelected()); - EXPECT_TRUE(GetItemPattern(1)->IsSelected()); - EXPECT_TRUE(GetItemPattern(4)->IsSelected()); - EXPECT_TRUE(GetItemPattern(5)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 0)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 1)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 4)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 5)->IsSelected()); MouseSelectRelease(); /** @@ -1898,10 +1786,10 @@ HWTEST_F(GridTestNg, MouseSelect002, TestSize.Level1) * @tc.expected: The 1st, 2nd, 5th, 6th are selected. */ MouseSelect(RIGHT_TOP, LEFT_BOTTOM); - EXPECT_TRUE(GetItemPattern(0)->IsSelected()); - EXPECT_TRUE(GetItemPattern(1)->IsSelected()); - EXPECT_TRUE(GetItemPattern(4)->IsSelected()); - EXPECT_TRUE(GetItemPattern(5)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 0)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 1)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 4)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 5)->IsSelected()); MouseSelectRelease(); /** @@ -1909,10 +1797,10 @@ HWTEST_F(GridTestNg, MouseSelect002, TestSize.Level1) * @tc.expected: The 1st, 2nd, 5th, 6th are selected. */ MouseSelect(LEFT_BOTTOM, RIGHT_TOP); - EXPECT_TRUE(GetItemPattern(0)->IsSelected()); - EXPECT_TRUE(GetItemPattern(1)->IsSelected()); - EXPECT_TRUE(GetItemPattern(4)->IsSelected()); - EXPECT_TRUE(GetItemPattern(5)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 0)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 1)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 4)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 5)->IsSelected()); MouseSelectRelease(); /** @@ -1920,10 +1808,10 @@ HWTEST_F(GridTestNg, MouseSelect002, TestSize.Level1) * @tc.expected: The 1st, 2nd, 5th, 6th are selected. */ MouseSelect(RIGHT_BOTTOM, LEFT_TOP); - EXPECT_TRUE(GetItemPattern(0)->IsSelected()); - EXPECT_TRUE(GetItemPattern(1)->IsSelected()); - EXPECT_TRUE(GetItemPattern(4)->IsSelected()); - EXPECT_TRUE(GetItemPattern(5)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 0)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 1)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 4)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 5)->IsSelected()); MouseSelectRelease(); } @@ -1944,12 +1832,6 @@ HWTEST_F(GridTestNg, MouseSelect003, TestSize.Level1) GridItemModelNG gridItemModel; gridItemModel.Create(); SetHeight(Dimension(ITEM_HEIGHT)); - /** - * ___180__360___540___720 - * |____|__1__|__2__|____|100 - * |____|__5__|_____|____|200 - * |____|_____| 300 - */ if (i == 1) { gridItemModel.SetSelectable(false); } @@ -1964,16 +1846,16 @@ HWTEST_F(GridTestNg, MouseSelect003, TestSize.Level1) ViewStackProcessor::GetInstance()->Pop(); } GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step2. Select (225, 50) - (315, 150) zone, include 2nd, 3rd, 6th, 7th item. * @tc.expected: The 2nd and 3rd item is not selected but 6th item is selected. */ MouseSelect(Offset(225.f, 50.f), Offset(315.f, 150.f)); - EXPECT_FALSE(GetItemPattern(1)->IsSelected()); - EXPECT_FALSE(GetItemPattern(2)->IsSelected()); - EXPECT_TRUE(GetItemPattern(5)->IsSelected()); + EXPECT_FALSE(GetChildPattern(frameNode_, 1)->IsSelected()); + EXPECT_FALSE(GetChildPattern(frameNode_, 2)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 5)->IsSelected()); EXPECT_TRUE(isSixthItemSelected); } @@ -1990,7 +1872,7 @@ HWTEST_F(GridTestNg, MouseSelect005, TestSize.Level1) gridModelNG.SetMultiSelectable(true); CreateGridItem(8, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); const Offset startOffset = Offset(225.f, 50.f); const Offset endOffset = Offset(315.f, 150.f); @@ -2007,7 +1889,7 @@ HWTEST_F(GridTestNg, MouseSelect005, TestSize.Level1) info.SetAction(MouseAction::MOVE); info.SetLocalLocation(endOffset); pattern_->HandleMouseEventWithoutKeyboard(info); - EXPECT_FALSE(GetItemPattern(1)->IsSelected()); + EXPECT_FALSE(GetChildPattern(frameNode_, 1)->IsSelected()); /** * @tc.steps: step2. Select (225, 50) - (315, 150) zone with HOVER @@ -2020,14 +1902,14 @@ HWTEST_F(GridTestNg, MouseSelect005, TestSize.Level1) info.SetAction(MouseAction::MOVE); info.SetLocalLocation(endOffset); pattern_->HandleMouseEventWithoutKeyboard(info); - EXPECT_FALSE(GetItemPattern(1)->IsSelected()); + EXPECT_FALSE(GetChildPattern(frameNode_, 1)->IsSelected()); /** * @tc.steps: step3. Move distance < FRAME_SELECTION_DISTANCE * @tc.expected: The item is not Selected */ MouseSelect(Offset(0.f, 0.f), Offset(1.f, 1.f)); - EXPECT_FALSE(GetItemPattern(0)->IsSelected()); + EXPECT_FALSE(GetChildPattern(frameNode_, 0)->IsSelected()); } /** @@ -2048,11 +1930,11 @@ HWTEST_F(GridTestNg, Drag001, TestSize.Level1) gridModelNG.SetOnItemDragStart(onItemDragStart); CreateGridItem(8, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); eventHub_->onItemDragStart_ = onItemDragStart; GestureEvent info; - Point globalPoint = Point(270.f, 50.f); // Point at the second item. + Point globalPoint = Point(ITEM_WIDTH * 1.5, ITEM_HEIGHT / 2); // Point at the second item. info.SetGlobalPoint(globalPoint); /** @@ -2062,7 +1944,7 @@ HWTEST_F(GridTestNg, Drag001, TestSize.Level1) eventHub_->HandleOnItemDragStart(info); EXPECT_EQ(eventHub_->draggedIndex_, 1); ASSERT_NE(eventHub_->dragDropProxy_, nullptr); - auto itemFrameNode = GetItemFrameNode(1); + auto itemFrameNode = GetChildFrameNode(frameNode_, 1); EXPECT_EQ(eventHub_->draggingItem_, itemFrameNode); eventHub_->HandleOnItemDragUpdate(info); eventHub_->HandleOnItemDragEnd(info); @@ -2099,7 +1981,7 @@ HWTEST_F(GridTestNg, Drag002, TestSize.Level1) CreateSingleGridItem(-1, -1, 2, 1, -1, ITEM_HEIGHT); CreateGridItem(8, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); auto onItemDragStart = [](const ItemDragInfo&, int32_t) { auto dragItem = AceType::MakeRefPtr("test", 0, AceType::MakeRefPtr()); return AceType::DynamicCast(dragItem); @@ -2121,7 +2003,7 @@ HWTEST_F(GridTestNg, Drag002, TestSize.Level1) eventHub_->FireOnItemDragEnter(dragInfo); eventHub_->FireOnItemDragLeave(dragInfo, -1); EXPECT_EQ(pattern_->GetOriginalIndex(), 11); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step2. Drag 2nd item to 3rd item, Drag 3 item to 2 item. @@ -2138,7 +2020,7 @@ HWTEST_F(GridTestNg, Drag002, TestSize.Level1) // SupportAnimation, ClearDragState eventHub_->FireOnItemDrop(dragInfo, 0, 1, true); EXPECT_EQ(pattern_->GetOriginalIndex(), -1); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step3. Move something to 3rd item. @@ -2151,7 +2033,7 @@ HWTEST_F(GridTestNg, Drag002, TestSize.Level1) // SupportAnimation, ClearDragState eventHub_->FireOnItemDrop(dragInfo, -1, 1, true); EXPECT_EQ(pattern_->GetOriginalIndex(), -1); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step4. Move one item to wrong insertIndex. @@ -2164,7 +2046,7 @@ HWTEST_F(GridTestNg, Drag002, TestSize.Level1) // insertIndex >= itemCount eventHub_->FireOnItemDragMove(dragInfo, 1, 11); EXPECT_EQ(pattern_->GetOriginalIndex(), -1); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); } /** @@ -2187,7 +2069,7 @@ HWTEST_F(GridTestNg, Drag003, TestSize.Level1) const int32_t itemCount = 8; CreateGridItem(itemCount, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); auto onItemDragStart = [](const ItemDragInfo&, int32_t) { auto dragItem = AceType::MakeRefPtr("test", 0, AceType::MakeRefPtr()); return AceType::DynamicCast(dragItem); @@ -2209,7 +2091,7 @@ HWTEST_F(GridTestNg, Drag003, TestSize.Level1) eventHub_->FireOnItemDragEnter(dragInfo); eventHub_->FireOnItemDragLeave(dragInfo, -1); EXPECT_EQ(pattern_->GetOriginalIndex(), itemCount); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step2. Drag 2nd item to 3rd item, Drag 3 item to 2 item. @@ -2226,7 +2108,7 @@ HWTEST_F(GridTestNg, Drag003, TestSize.Level1) // SupportAnimation, ClearDragState eventHub_->FireOnItemDrop(dragInfo, 0, 1, true); EXPECT_EQ(pattern_->GetOriginalIndex(), -1); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step3. Move something to 3rd item. @@ -2239,7 +2121,7 @@ HWTEST_F(GridTestNg, Drag003, TestSize.Level1) // SupportAnimation, ClearDragState eventHub_->FireOnItemDrop(dragInfo, -1, 1, true); EXPECT_EQ(pattern_->GetOriginalIndex(), -1); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step4. Move one item to wrong insertIndex. @@ -2252,7 +2134,7 @@ HWTEST_F(GridTestNg, Drag003, TestSize.Level1) // insertIndex >= itemCount eventHub_->FireOnItemDragMove(dragInfo, 1, itemCount); EXPECT_EQ(pattern_->GetOriginalIndex(), -1); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); } /** @@ -2262,18 +2144,12 @@ HWTEST_F(GridTestNg, Drag003, TestSize.Level1) */ HWTEST_F(GridTestNg, FocusStep001, TestSize.Level1) { - /** - * ___180__360__540__720 - * |____|____|____|____|100 - * |____|____|____|____|200 - * |____|____| 300 - */ GridModelNG gridModelNG; gridModelNG.Create(nullptr, nullptr); gridModelNG.SetColumnsTemplate("1fr 1fr 1fr 1fr"); CreateGridItem(10, -1, ITEM_HEIGHT, true); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. GetNextFocusNode from left_top. @@ -2368,19 +2244,12 @@ HWTEST_F(GridTestNg, FocusStep001, TestSize.Level1) */ HWTEST_F(GridTestNg, FocusStep002, TestSize.Level1) { - /** - * ___180__360__540__720 - * |____|____|____| 100 - * |____|____|____| 200 - * |____|____| 300 - * |____|____| 400 - */ GridModelNG gridModelNG; gridModelNG.Create(nullptr, nullptr); gridModelNG.SetRowsTemplate("1fr 1fr 1fr 1fr"); CreateGridItem(10, ITEM_WIDTH, -1, true); GetInstance(); - RunMeasureAndLayout(DEVICE_WIDTH, 400.f); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, 400.f); /** * @tc.steps: step1. GetNextFocusNode from left_top. @@ -2480,13 +2349,13 @@ HWTEST_F(GridTestNg, FocusStep003, TestSize.Level1) gridModelNG.SetColumnsTemplate("1fr 1fr 1fr 1fr"); CreateGridItem(10, -1, ITEM_HEIGHT, true); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. GetNextFocusNode from 1st item and FocusStep::RIGHT. * @tc.expected: The 3rd item is focused. */ - GetItemFocusHub(1)->SetFocusable(false); // The 2nd item can not focus. + GetChildFocusHub(frameNode_, 1)->SetFocusable(false); // The 2nd item can not focus. int32_t currentIndex = 0; EXPECT_TRUE(IsEqualNextFocusNode(FocusStep::RIGHT, currentIndex, 2)); } @@ -2503,7 +2372,7 @@ HWTEST_F(GridTestNg, FocusStep004, TestSize.Level1) gridModelNG.SetColumnsTemplate("1fr 1fr 1fr 1fr"); CreateGridItem(18, -1, ITEM_HEIGHT, true); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. Scroll to second row @@ -2530,7 +2399,7 @@ HWTEST_F(GridTestNg, FocusStep005, TestSize.Level1) gridModelNG.SetColumnsTemplate("1fr 1fr 1fr 1fr"); CreateGridItem(18, -1, ITEM_HEIGHT, true); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. Scroll to first row @@ -2560,7 +2429,7 @@ HWTEST_F(GridTestNg, Focus001, TestSize.Level1) gridModelNG.SetColumnsTemplate("1fr 1fr 1fr 1fr"); CreateGridItem(18, -1, ITEM_HEIGHT, true); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. When focus grid from the outside @@ -2568,17 +2437,17 @@ HWTEST_F(GridTestNg, Focus001, TestSize.Level1) */ auto gridFocus = frameNode_->GetOrCreateFocusHub(); gridFocus->RequestFocusImmediately(); - RunMeasureAndLayout(); - EXPECT_TRUE(GetItemFocusHub(0)->IsCurrentFocus()); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); + EXPECT_TRUE(GetChildFocusHub(frameNode_, 0)->IsCurrentFocus()); /** * @tc.steps: step2. When grid IsCurrentFocus and has lastFocus child * @tc.expected: Will focus last child */ - GetItemFocusHub(1)->RequestFocusImmediately(); + GetChildFocusHub(frameNode_, 1)->RequestFocusImmediately(); gridFocus->RequestFocusImmediately(); - RunMeasureAndLayout(); - EXPECT_TRUE(GetItemFocusHub(1)->IsCurrentFocus()); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); + EXPECT_TRUE(GetChildFocusHub(frameNode_, 1)->IsCurrentFocus()); /** * @tc.steps: step3. Scroll to second row @@ -2586,7 +2455,7 @@ HWTEST_F(GridTestNg, Focus001, TestSize.Level1) */ gridFocus->RequestFocusImmediately(); UpdateCurrentOffset(-ITEM_HEIGHT - 1.f); - EXPECT_TRUE(GetItemFocusHub(1)->IsCurrentFocus()); + EXPECT_TRUE(GetChildFocusHub(frameNode_, 1)->IsCurrentFocus()); } /** @@ -2601,41 +2470,41 @@ HWTEST_F(GridTestNg, GridPatternTest001, TestSize.Level1) gridModelNG.SetColumnsTemplate("1fr 1fr 1fr 1fr"); CreateGridItem(14, -1, ITEM_HEIGHT); GetInstance(); - auto layoutWrapper = RunMeasureAndLayout(); + auto layoutWrapper = RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. UpdateCurrentOffset to end, over start, over end * @tc.expected: veridy currentOffset_. */ pattern_->UpdateCurrentOffset(-100.f, SCROLL_FROM_UPDATE); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); EXPECT_TRUE(IsEqualCurrentOffset(-100.f)); pattern_->UpdateCurrentOffset(200.f, SCROLL_FROM_UPDATE); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); EXPECT_TRUE(IsEqualCurrentOffset(0)); pattern_->UpdateCurrentOffset(-200.f, SCROLL_FROM_UPDATE); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); EXPECT_TRUE(IsEqualCurrentOffset(0)); pattern_->UpdateCurrentOffset(-100.f, SCROLL_FROM_BAR); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); EXPECT_TRUE(IsEqualCurrentOffset(0)); pattern_->UpdateCurrentOffset(200.f, SCROLL_FROM_BAR); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); EXPECT_TRUE(IsEqualCurrentOffset(0)); pattern_->UpdateCurrentOffset(-200.f, SCROLL_FROM_BAR); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); EXPECT_TRUE(IsEqualCurrentOffset(0)); pattern_->scrollEffect_ = AceType::MakeRefPtr(EdgeEffect::FADE); pattern_->UpdateCurrentOffset(-100.f, SCROLL_FROM_UPDATE); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); EXPECT_TRUE(IsEqualCurrentOffset(0)); pattern_->UpdateCurrentOffset(200.f, SCROLL_FROM_UPDATE); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); EXPECT_TRUE(IsEqualCurrentOffset(0)); pattern_->UpdateCurrentOffset(-200.f, SCROLL_FROM_UPDATE); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); EXPECT_TRUE(IsEqualCurrentOffset(0)); } @@ -2704,7 +2573,7 @@ HWTEST_F(GridTestNg, ScrollLayout001, TestSize.Level1) gridModelNG.SetMaxCount(2); CreateGridItem(18, -1, ITEM_HEIGHT, true); GetInstance(); - auto layoutWrapper = RunMeasureAndLayout(); + auto layoutWrapper = RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); // MOCK GetPaintRectWithTransform() const float smallerHeight = GRID_HEIGHT - ITEM_HEIGHT; @@ -2748,7 +2617,7 @@ HWTEST_F(GridTestNg, ScrollLayout002, TestSize.Level1) gridModelNG.SetMaxCount(2); CreateGridItem(18, -1, ITEM_HEIGHT, true); GetInstance(); - auto layoutWrapper = RunMeasureAndLayout(); + auto layoutWrapper = RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. While axis_ == Axis::HORIZONTAL @@ -2803,15 +2672,15 @@ HWTEST_F(GridTestNg, AdaptiveLayout001, TestSize.Level1) constexpr int32_t gridItemNumber = 10; CreateGridItem(gridItemNumber, ITEM_WIDTH, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. While the before set minCount > maxCount * @tc.expected: would let minCount = 1, maxCount = Infinity; */ - constexpr int32_t colsNumber = 7; // 7 * 100(itemWidth) < 720(gridWidth) + constexpr int32_t colsNumber = 4; // 4 * 100(itemWidth) < 480(gridWidth) for (int32_t index = 0; index < gridItemNumber; index++) { - RectF childRect = GetItemRect(index); + RectF childRect = GetChildRect(frameNode_, index); float offsetX = index % colsNumber * ITEM_WIDTH; float offsetY = floor(index / colsNumber) * ITEM_HEIGHT; RectF expectRect = RectF(offsetX, offsetY, ITEM_WIDTH, ITEM_HEIGHT); @@ -2831,7 +2700,7 @@ HWTEST_F(GridTestNg, EventHubCoverage001, TestSize.Level1) gridModelNG.SetColumnsTemplate("1fr 1fr 1fr 1fr"); CreateGridItem(8, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. Supplement InitItemDragEvent branch. @@ -2869,7 +2738,7 @@ HWTEST_F(GridTestNg, EventHubCoverage002, TestSize.Level1) gridModelNG.SetEditable(true); CreateGridItem(8, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. Supplement HandleOnItemDragEnd branch, @@ -2914,7 +2783,7 @@ HWTEST_F(GridTestNg, EventHubCoverage003, TestSize.Level1) gridModelNG.SetOnItemDrop([](const ItemDragInfo&, int32_t, int32_t, bool) {}); CreateGridItem(8, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.steps: step1. Supplement drag callback branch. @@ -3056,7 +2925,7 @@ HWTEST_F(GridTestNg, GridScrollTest001, TestSize.Level1) CreateSingleGridItem(1, 1, 1, 2); CreateGridItem(2, -1, ITEM_HEIGHT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); Dimension offset(1.0); auto fireOnScroll = eventHub_->FireOnScrollBarUpdate(1.0, offset); EXPECT_FLOAT_EQ(fireOnScroll.first.value(), 1.0f); @@ -3156,9 +3025,9 @@ HWTEST_F(GridTestNg, GridScrollTest005, TestSize.Level1) gridItemModelNG.SetColumnEnd(-1); ViewStackProcessor::GetInstance()->Pop(); GetInstance(); - auto layoutWrapper = RunMeasureAndLayout(); + auto layoutWrapper = RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); ASSERT_NE(layoutWrapper, nullptr); - auto item = GetItemFrameNode(0); + auto item = GetChildFrameNode(frameNode_, 0); auto gridScrollLayoutAlgorithm = AceType::MakeRefPtr(pattern_->gridLayoutInfo_, 2, 0); ASSERT_NE(gridScrollLayoutAlgorithm, nullptr); auto itemWrapper = layoutWrapper->GetOrCreateChildByIndex(0); @@ -3185,7 +3054,7 @@ HWTEST_F(GridTestNg, GridSetFriction001, TestSize.Level1) gridModelNG.Create(positionController, scrollBarProxy); gridModelNG.SetFriction(friction); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); /** * @tc.expected: friction shouled be more than 0.0,if out of range,should be default value. */ @@ -3206,7 +3075,7 @@ HWTEST_F(GridTestNg, GridSetFriction002, TestSize.Level1) gridModelNG.Create(positionController, scrollBarProxy); gridModelNG.SetFriction(friction); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, GRID_HEIGHT); EXPECT_DOUBLE_EQ(pattern_->GetFriction(), 10); } } // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/test/pattern/grid_col/BUILD.gn b/frameworks/core/components_ng/test/pattern/grid_col/BUILD.gn index e36d662b8f8..62fac11f331 100644 --- a/frameworks/core/components_ng/test/pattern/grid_col/BUILD.gn +++ b/frameworks/core/components_ng/test/pattern/grid_col/BUILD.gn @@ -14,110 +14,17 @@ import("//build/test.gni") import("//foundation/arkui/ace_engine/test/unittest/ace_unittest.gni") -ohos_unittest("grid_col_pattern_test_ng") { - module_out_path = pattern_test_output_path - +ace_unittest("grid_col_pattern_test_ng") { + ace_animation = true sources = [ - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_node.cpp", - "$ace_root/frameworks/core/components_ng/pattern/custom/custom_node.cpp", + # other "$ace_root/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp", + "$ace_root/frameworks/core/components_ng/pattern/grid_container/grid_container_layout_property.cpp", + + # self "$ace_root/frameworks/core/components_ng/pattern/grid_col/grid_col_layout_algorithm.cpp", "$ace_root/frameworks/core/components_ng/pattern/grid_col/grid_col_layout_property.cpp", "$ace_root/frameworks/core/components_ng/pattern/grid_col/grid_col_model_ng.cpp", - "$ace_root/frameworks/core/components_ng/syntax/lazy_for_each_node.cpp", "grid_col_pattern_test_ng.cpp", ] - - sources += [ - # base - "$ace_root/frameworks/base/geometry/dimension.cpp", - "$ace_root/frameworks/base/json/json_util.cpp", - "$ace_root/frameworks/base/utils/base_id.cpp", - "$ace_root/frameworks/base/utils/string_expression.cpp", - "$ace_root/frameworks/base/utils/string_utils.cpp", - "$ace_root/frameworks/base/utils/time_util.cpp", - - # components - "$ace_root/frameworks/core/components/common/layout/grid_column_info.cpp", - "$ace_root/frameworks/core/components/common/layout/grid_container_info.cpp", - "$ace_root/frameworks/core/components/common/layout/grid_system_manager.cpp", - "$ace_root/frameworks/core/components/common/layout/screen_system_manager.cpp", - "$ace_root/frameworks/core/components/common/properties/alignment.cpp", - "$ace_root/frameworks/core/components/common/properties/color.cpp", - - # components_ng - "$ace_root/frameworks/core/components_ng/base/frame_node.cpp", - "$ace_root/frameworks/core/components_ng/base/geometry_node.cpp", - "$ace_root/frameworks/core/components_ng/base/modifier.cpp", - "$ace_root/frameworks/core/components_ng/base/ui_node.cpp", - "$ace_root/frameworks/core/components_ng/base/view_stack_processor.cpp", - "$ace_root/frameworks/core/components_ng/event/click_event.cpp", - "$ace_root/frameworks/core/components_ng/event/drag_event.cpp", - "$ace_root/frameworks/core/components_ng/event/event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/focus_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/gesture_event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/input_event.cpp", - "$ace_root/frameworks/core/components_ng/event/input_event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/pan_event.cpp", - "$ace_root/frameworks/core/components_ng/event/state_style_manager.cpp", - "$ace_root/frameworks/core/components_ng/event/touch_event.cpp", - "$ace_root/frameworks/core/components_ng/gestures/gesture_referee.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/click_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/exclusive_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/gesture_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/long_press_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/multi_fingers_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/pan_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/parallel_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/recognizer_group.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/sequenced_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/layout/box_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_property.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_builder.cpp", - "$ace_root/frameworks/core/components_ng/manager/safe_area/safe_area_manager.cpp", - "$ace_root/frameworks/core/components_ng/property/border_property.cpp", - "$ace_root/frameworks/core/components_ng/property/calc_length.cpp", - "$ace_root/frameworks/core/components_ng/property/grid_property.cpp", - "$ace_root/frameworks/core/components_ng/property/measure_utils.cpp", - "$ace_root/frameworks/core/components_ng/property/property.cpp", - "$ace_root/frameworks/core/components_ng/property/safe_area_insets.cpp", - "$ace_root/frameworks/core/components_ng/render/drawing_prop_convertor.cpp", - "$ace_root/frameworks/core/components_ng/render/paint_wrapper.cpp", - - # components_v2 - "$ace_root/frameworks/core/components_v2/inspector/inspector_constants.cpp", - - # pipeline - "$ace_root/frameworks/core/pipeline/base/constants.cpp", - - # mock - "$ace_root/frameworks/base/test/mock/mock_ressched_report.cpp", - "$ace_root/frameworks/base/test/mock/mock_socperf_client_impl.cpp", - "$ace_root/frameworks/base/test/mock/mock_system_properties.cpp", - "$ace_root/frameworks/core/common/test/mock/mock_ace_application_info.cpp", - "$ace_root/frameworks/core/components/test/unittest/mock/ace_trace_mock.cpp", - "$ace_root/frameworks/core/components_ng/test/event/mock/mock_scrollable_event.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/animation/mock_geometry_transition.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/base/mock_localization.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/grid_container/mock_grid_container_layout_property.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_animation_utils.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_modifier_adapter.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_context.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_context_creator.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_surface_creator.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/syntax/mock_for_each_node.cpp", - "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_element_register.cpp", - "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_pipeline_base.cpp", - ] - - deps = [ - "$ace_root/frameworks/base:ace_memory_monitor_ohos", - "$ace_root/frameworks/core/components/theme:build_theme_code", - "$ace_root/test/unittest:ace_unittest_log", - "$cjson_root:cjson_static", - "//third_party/googletest:gmock_main", - ] - - configs = [ "$ace_root/test/unittest:ace_unittest_config" ] } diff --git a/frameworks/core/components_ng/test/pattern/hyperlink/BUILD.gn b/frameworks/core/components_ng/test/pattern/hyperlink/BUILD.gn index 124c734302e..dc2cfd8d027 100644 --- a/frameworks/core/components_ng/test/pattern/hyperlink/BUILD.gn +++ b/frameworks/core/components_ng/test/pattern/hyperlink/BUILD.gn @@ -14,129 +14,46 @@ import("//build/test.gni") import("//foundation/arkui/ace_engine/test/unittest/ace_unittest.gni") -ohos_unittest("hyperlink_test_ng") { - module_out_path = pattern_test_output_path - +ace_unittest("hyperlink_test_ng") { + ace_animation = true sources = [ - # drag - "$ace_root/frameworks/base/geometry/least_square_impl.cpp", - "$ace_root/frameworks/base/geometry/matrix3.cpp", - "$ace_root/frameworks/base/geometry/matrix4.cpp", - "$ace_root/frameworks/base/test/mock/mock_drag_window.cpp", - "$ace_root/frameworks/core/common/test/mock/mock_clipboard.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_node.cpp", - "$ace_root/frameworks/core/components_ng/pattern/custom/custom_node.cpp", - "$ace_root/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp", + # text + "$ace_root/frameworks/core/components_ng/pattern/text/image_span_view.cpp", + "$ace_root/frameworks/core/components_ng/pattern/text/span_model_ng.cpp", + "$ace_root/frameworks/core/components_ng/pattern/text/span_node.cpp", "$ace_root/frameworks/core/components_ng/pattern/text/text_accessibility_property.cpp", "$ace_root/frameworks/core/components_ng/pattern/text/text_content_modifier.cpp", + "$ace_root/frameworks/core/components_ng/pattern/text/text_layout_algorithm.cpp", "$ace_root/frameworks/core/components_ng/pattern/text/text_layout_property.cpp", + "$ace_root/frameworks/core/components_ng/pattern/text/text_model_ng.cpp", "$ace_root/frameworks/core/components_ng/pattern/text/text_overlay_modifier.cpp", + "$ace_root/frameworks/core/components_ng/pattern/text/text_paint_method.cpp", + "$ace_root/frameworks/core/components_ng/pattern/text/text_pattern.cpp", "$ace_root/frameworks/core/components_ng/pattern/text/text_styles.cpp", - "$ace_root/frameworks/core/components_ng/syntax/lazy_for_each_node.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/manager/drag_drop/mock_drag_drop_manager.cpp", + + # select_overlay + "$ace_root/frameworks/core/components_ng/manager/select_overlay/select_overlay_manager.cpp", + "$ace_root/frameworks/core/components_ng/manager/select_overlay/select_overlay_proxy.cpp", + "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_layout_algorithm.cpp", + "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_modifier.cpp", + "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_paint_method.cpp", + "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_pattern.cpp", + "$ace_root/frameworks/core/components_ng/pattern/select_overlay/select_overlay_property.cpp", + "$ace_root/frameworks/core/components_ng/test/mock/pattern/popup/mock_popup_base_pattern.cpp", + "$ace_root/frameworks/core/components_ng/test/mock/pattern/select_overlay/mock_select_overlay_node.cpp", + + # mock "$ace_root/frameworks/core/components_ng/test/mock/manager/drag_drop/mock_drag_drop_proxy.cpp", - "$ace_root/frameworks/core/gestures/velocity_tracker.cpp", + "$ace_root/test/mock/core/common/mock_font_manager_ng.cpp", + "$ace_root/test/unittest/core/pipeline/mock_drag_drop_manager.cpp", + + # other + "$ace_root/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp", + "$ace_root/frameworks/core/components_ng/pattern/grid_container/grid_container_layout_property.cpp", # self "$ace_root/frameworks/core/components_ng/pattern/hyperlink/hyperlink_model_ng.cpp", "$ace_root/frameworks/core/components_ng/pattern/hyperlink/hyperlink_pattern.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/text/mock_text_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/text/mock_text_paint_method.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/text/mock_text_pattern.cpp", "hyperlink_test_ng.cpp", ] - - sources += [ - # base - "$ace_root/frameworks/base/geometry/dimension.cpp", - "$ace_root/frameworks/base/json/json_util.cpp", - "$ace_root/frameworks/base/utils/base_id.cpp", - "$ace_root/frameworks/base/utils/string_expression.cpp", - "$ace_root/frameworks/base/utils/string_utils.cpp", - "$ace_root/frameworks/base/utils/time_util.cpp", - - # components - "$ace_root/frameworks/core/components/common/layout/grid_column_info.cpp", - "$ace_root/frameworks/core/components/common/layout/grid_container_info.cpp", - "$ace_root/frameworks/core/components/common/layout/grid_system_manager.cpp", - "$ace_root/frameworks/core/components/common/layout/screen_system_manager.cpp", - "$ace_root/frameworks/core/components/common/properties/alignment.cpp", - "$ace_root/frameworks/core/components/common/properties/color.cpp", - - # components_ng - "$ace_root/frameworks/core/components_ng/base/frame_node.cpp", - "$ace_root/frameworks/core/components_ng/base/geometry_node.cpp", - "$ace_root/frameworks/core/components_ng/base/modifier.cpp", - "$ace_root/frameworks/core/components_ng/base/ui_node.cpp", - "$ace_root/frameworks/core/components_ng/base/view_stack_processor.cpp", - "$ace_root/frameworks/core/components_ng/event/click_event.cpp", - "$ace_root/frameworks/core/components_ng/event/drag_event.cpp", - "$ace_root/frameworks/core/components_ng/event/event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/focus_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/gesture_event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/input_event.cpp", - "$ace_root/frameworks/core/components_ng/event/input_event_hub.cpp", - "$ace_root/frameworks/core/components_ng/event/pan_event.cpp", - "$ace_root/frameworks/core/components_ng/event/state_style_manager.cpp", - "$ace_root/frameworks/core/components_ng/event/touch_event.cpp", - "$ace_root/frameworks/core/components_ng/gestures/gesture_referee.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/click_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/exclusive_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/gesture_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/long_press_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/multi_fingers_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/pan_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/parallel_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/recognizer_group.cpp", - "$ace_root/frameworks/core/components_ng/gestures/recognizers/sequenced_recognizer.cpp", - "$ace_root/frameworks/core/components_ng/layout/box_layout_algorithm.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_property.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper.cpp", - "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_builder.cpp", - "$ace_root/frameworks/core/components_ng/manager/safe_area/safe_area_manager.cpp", - "$ace_root/frameworks/core/components_ng/property/border_property.cpp", - "$ace_root/frameworks/core/components_ng/property/calc_length.cpp", - "$ace_root/frameworks/core/components_ng/property/grid_property.cpp", - "$ace_root/frameworks/core/components_ng/property/measure_utils.cpp", - "$ace_root/frameworks/core/components_ng/property/property.cpp", - "$ace_root/frameworks/core/components_ng/property/safe_area_insets.cpp", - "$ace_root/frameworks/core/components_ng/render/drawing_prop_convertor.cpp", - "$ace_root/frameworks/core/components_ng/render/paint_wrapper.cpp", - - # components_v2 - "$ace_root/frameworks/core/components_v2/inspector/inspector_constants.cpp", - - # pipeline - "$ace_root/frameworks/core/pipeline/base/constants.cpp", - - # mock - "$ace_root/frameworks/base/test/mock/mock_ressched_report.cpp", - "$ace_root/frameworks/base/test/mock/mock_socperf_client_impl.cpp", - "$ace_root/frameworks/base/test/mock/mock_system_properties.cpp", - "$ace_root/frameworks/core/common/test/mock/mock_ace_application_info.cpp", - "$ace_root/frameworks/core/components/test/unittest/mock/ace_trace_mock.cpp", - "$ace_root/frameworks/core/components_ng/test/event/mock/mock_scrollable_event.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/animation/mock_geometry_transition.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/base/mock_localization.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/pattern/grid_container/mock_grid_container_layout_property.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_animation_utils.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_modifier_adapter.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_context.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_context_creator.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_surface_creator.cpp", - "$ace_root/frameworks/core/components_ng/test/mock/syntax/mock_for_each_node.cpp", - "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_element_register.cpp", - "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_pipeline_base.cpp", - "$ace_root/test/mock/core/common/mock_font_manager_ng.cpp", - ] - - deps = [ - "$ace_root/frameworks/base:ace_memory_monitor_ohos", - "$ace_root/frameworks/core/components/theme:build_theme_code", - "$ace_root/test/unittest:ace_unittest_log", - "$cjson_root:cjson_static", - "//third_party/googletest:gmock_main", - ] - - configs = [ "$ace_root/test/unittest:ace_unittest_config" ] } diff --git a/frameworks/core/components_ng/test/pattern/indexer/BUILD.gn b/frameworks/core/components_ng/test/pattern/indexer/BUILD.gn index 9263c2fa7f1..fc93c21e227 100644 --- a/frameworks/core/components_ng/test/pattern/indexer/BUILD.gn +++ b/frameworks/core/components_ng/test/pattern/indexer/BUILD.gn @@ -65,6 +65,7 @@ ohos_unittest("indexer_test_ng") { "$ace_root/frameworks/core/components_ng/syntax/lazy_layout_wrapper_builder.cpp", "$ace_root/frameworks/core/components_ng/test/event/mock/mock_scrollable_event.cpp", "$ace_root/frameworks/core/components_ng/test/pattern/image/mock/mock_image_pattern.cpp", + "$ace_root/frameworks/core/components_ng/test/pattern/test_ng.cpp", "$ace_root/frameworks/core/gestures/velocity_tracker.cpp", "$ace_root/frameworks/core/image/image_source_info.cpp", diff --git a/frameworks/core/components_ng/test/pattern/indexer/indexer_test_ng.cpp b/frameworks/core/components_ng/test/pattern/indexer/indexer_test_ng.cpp index 4a851156efa..879cc5f8e82 100644 --- a/frameworks/core/components_ng/test/pattern/indexer/indexer_test_ng.cpp +++ b/frameworks/core/components_ng/test/pattern/indexer/indexer_test_ng.cpp @@ -33,6 +33,7 @@ #include "core/components_ng/pattern/linear_layout/linear_layout_property.h" #include "core/components_ng/pattern/text/text_layout_property.h" #include "core/components_ng/test/mock/theme/mock_theme_manager.h" +#include "core/components_ng/test/pattern/test_ng.h" #include "core/pipeline_ng/pipeline_context.h" #include "core/pipeline_ng/test/mock/mock_pipeline_base.h" @@ -41,8 +42,6 @@ using namespace testing::ext; namespace OHOS::Ace::NG { namespace { -constexpr float DEFAULT_ROOT_WIDTH = 720.f; -constexpr float DEFAULT_ROOT_HEIGHT = 1136.f; std::vector CREATE_ARRAY = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }; std::vector GetPopupData(int32_t) @@ -55,14 +54,13 @@ std::vector GetMorePopupData(int32_t) } } // namespace -class IndexerTestNg : public testing::Test { +class IndexerTestNg : public testing::Test, public TestNG { public: static void SetUpTestSuite(); static void TearDownTestSuite(); void SetUp() override; void TearDown() override; void GetInstance(); - void RunMeasureAndLayout(); float GetFirstChildOffsetY(); RefPtr frameNode_; @@ -109,24 +107,9 @@ void IndexerTestNg::GetInstance() accessibilityProperty_ = frameNode_->GetAccessibilityProperty(); } -void IndexerTestNg::RunMeasureAndLayout() -{ - RefPtr layoutWrapper = frameNode_->CreateLayoutWrapper(false, false); - layoutWrapper->SetActive(); - LayoutConstraintF LayoutConstraint; - LayoutConstraint.parentIdealSize = { DEFAULT_ROOT_WIDTH, DEFAULT_ROOT_HEIGHT }; - LayoutConstraint.percentReference = { DEFAULT_ROOT_WIDTH, DEFAULT_ROOT_HEIGHT }; - LayoutConstraint.maxSize = { DEFAULT_ROOT_WIDTH, DEFAULT_ROOT_HEIGHT }; - layoutWrapper->Measure(LayoutConstraint); - layoutWrapper->Layout(); - layoutWrapper->MountToHostOnMainThread(); -} - float IndexerTestNg::GetFirstChildOffsetY() { - auto firstChild = AceType::DynamicCast(frameNode_->GetFirstChild()); - float firstOffsetY = firstChild->GetGeometryNode()->GetFrameOffset().GetY(); - return firstOffsetY; + return GetChildRect(frameNode_, 0).GetY(); } /** @@ -139,7 +122,7 @@ HWTEST_F(IndexerTestNg, IndexerMoveIndex001, TestSize.Level1) IndexerModelNG IndexerModelNG; IndexerModelNG.Create(CREATE_ARRAY, 0); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); ASSERT_NE(pattern_->panEvent_, nullptr); /** @@ -195,7 +178,7 @@ HWTEST_F(IndexerTestNg, IndexerMoveIndex002, TestSize.Level1) IndexerModelNG IndexerModelNG; IndexerModelNG.Create(CREATE_ARRAY, 0); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); ASSERT_NE(pattern_->panEvent_, nullptr); /** @@ -236,7 +219,7 @@ HWTEST_F(IndexerTestNg, IndexerMoveIndex003, TestSize.Level1) IndexerModelNG IndexerModelNG; IndexerModelNG.Create(arrayValue, 0); // empty array GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); ASSERT_NE(pattern_->panEvent_, nullptr); /** @@ -264,7 +247,7 @@ HWTEST_F(IndexerTestNg, IndexerTouch001, TestSize.Level1) IndexerModelNG IndexerModelNG; IndexerModelNG.Create(CREATE_ARRAY, 0); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); ASSERT_NE(pattern_->touchListener_, nullptr); /** @@ -308,7 +291,7 @@ HWTEST_F(IndexerTestNg, IndexerTouch002, TestSize.Level1) IndexerModelNG IndexerModelNG; IndexerModelNG.Create(CREATE_ARRAY, 0); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); ASSERT_NE(pattern_->touchListener_, nullptr); /** @@ -350,7 +333,7 @@ HWTEST_F(IndexerTestNg, IndexerTouch003, TestSize.Level1) IndexerModelNG IndexerModelNG; IndexerModelNG.Create(CREATE_ARRAY, 0); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); ASSERT_NE(pattern_->touchListener_, nullptr); /** @@ -377,7 +360,7 @@ HWTEST_F(IndexerTestNg, IndexerKeyEvent001, TestSize.Level1) IndexerModelNG IndexerModelNG; IndexerModelNG.Create(CREATE_ARRAY, 0); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. UNKNOWN keyEvent. @@ -432,7 +415,7 @@ HWTEST_F(IndexerTestNg, IndexerKeyEvent002, TestSize.Level1) IndexerModelNG IndexerModelNG; IndexerModelNG.Create(CREATE_ARRAY, 0); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. IsCombinationKey && KEY_UNKNOWN. @@ -506,7 +489,7 @@ HWTEST_F(IndexerTestNg, IndexerHover001, TestSize.Level1) IndexerModelNG.Create(CREATE_ARRAY, 0); IndexerModelNG.SetUsingPopup(true); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); pattern_->OnChildHover(1, true); EXPECT_EQ(pattern_->childHoverIndex_, 1); @@ -575,7 +558,7 @@ HWTEST_F(IndexerTestNg, IndexerPattern002, TestSize.Level1) IndexerModelNG.SetPopupUnselectedColor(Color(0x00000000)); IndexerModelNG.SetOnRequestPopupData(GetPopupData); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); pattern_->MoveIndexByStep(1); ASSERT_NE(pattern_->popupNode_, nullptr); @@ -601,7 +584,7 @@ HWTEST_F(IndexerTestNg, IndexerPattern003, TestSize.Level1) IndexerModelNG1.SetPopupHorizontalSpace(Dimension(50)); IndexerModelNG1.SetOnRequestPopupData(GetPopupData); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); pattern_->MoveIndexByStep(1); @@ -617,7 +600,7 @@ HWTEST_F(IndexerTestNg, IndexerPattern003, TestSize.Level1) IndexerModelNG2.SetPopupHorizontalSpace(Dimension(50)); IndexerModelNG2.SetOnRequestPopupData(GetPopupData); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); pattern_->MoveIndexByStep(1); @@ -643,7 +626,7 @@ HWTEST_F(IndexerTestNg, IndexerPattern004, TestSize.Level1) IndexerModelNG.SetPopupItemBackground(Color(0x00000000)); IndexerModelNG.SetOnRequestPopupData(GetPopupData); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); pattern_->MoveIndexByStep(1); pattern_->OnListItemClick(0); @@ -670,7 +653,7 @@ HWTEST_F(IndexerTestNg, IndexerUpdateBubble001, TestSize.Level1) IndexerModelNG.SetUsingPopup(true); IndexerModelNG.SetOnRequestPopupData(GetPopupData); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. has popListData. @@ -699,7 +682,7 @@ HWTEST_F(IndexerTestNg, IndexerUpdateBubble002, TestSize.Level1) IndexerModelNG.SetUsingPopup(true); IndexerModelNG.SetOnRequestPopupData(GetPopupData); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. childPressIndex_ less than 0. @@ -728,7 +711,7 @@ HWTEST_F(IndexerTestNg, IndexerUpdateBubble003, TestSize.Level1) IndexerModelNG.SetUsingPopup(true); IndexerModelNG.SetOnRequestPopupData(GetMorePopupData); // GetMorePopupData. GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. has popListData and popListData size equal INDEXER_BUBBLE_MAXSIZE. @@ -756,7 +739,7 @@ HWTEST_F(IndexerTestNg, IndexerPopupTouchDown001, TestSize.Level1) IndexerModelNG.Create(CREATE_ARRAY, 0); IndexerModelNG.SetUsingPopup(true); // NeedShowPopupView is true. GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. NeedShowPopupView is true. @@ -785,7 +768,7 @@ HWTEST_F(IndexerTestNg, IndexerCallback001, TestSize.Level1) OnPopupSelectedEvent event = [&isOnPopupSelectedCalled](int32_t) { isOnPopupSelectedCalled = true; }; IndexerModelNG.SetOnPopupSelected(std::move(event)); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. Trigger OnPopupSelected callback. @@ -809,7 +792,7 @@ HWTEST_F(IndexerTestNg, IndexerCallback002, TestSize.Level1) OnSelectedEvent event = [&isOnSelectedCalled](int32_t) { isOnSelectedCalled = true; }; IndexerModelNG.SetOnSelected(std::move(event)); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. Trigger OnSelected callback. @@ -845,7 +828,7 @@ HWTEST_F(IndexerTestNg, IndexerModelNGTest001, TestSize.Level1) IndexerModelNG.SetPopupPositionX(Dimension(-96.f, DimensionUnit::VP)); IndexerModelNG.SetPopupPositionY(Dimension(48.f, DimensionUnit::VP)); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. Get properties. @@ -881,7 +864,7 @@ HWTEST_F(IndexerTestNg, IndexerModelNGTest002, TestSize.Level1) IndexerModelNG.SetSelected(-1); IndexerModelNG.SetItemSize(Dimension(-1)); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. Get properties. @@ -907,7 +890,7 @@ HWTEST_F(IndexerTestNg, IndexerModelNGTest003, TestSize.Level1) IndexerModelNG.SetFontSize(Dimension(24)); IndexerModelNG.SetFontWeight(FontWeight::MEDIUM); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. Get properties. @@ -936,7 +919,7 @@ HWTEST_F(IndexerTestNg, IndexerModelNGTest004, TestSize.Level1) IndexerModelNG.SetPopupHorizontalSpace(Dimension(-1)); IndexerModelNG.SetFontSize(Dimension()); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. Get properties. @@ -998,7 +981,7 @@ HWTEST_F(IndexerTestNg, IndexerAccessibilityTest001, TestSize.Level1) IndexerModelNG IndexerModelNG; IndexerModelNG.Create(CREATE_ARRAY, 0); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. Test GetEndIndex, GetText func. @@ -1026,10 +1009,10 @@ HWTEST_F(IndexerTestNg, IndexerAlgorithmTest001, TestSize.Level1) RefPtr layoutWrapper = frameNode_->CreateLayoutWrapper(false, false); layoutWrapper->SetActive(); LayoutConstraintF LayoutConstraint; - LayoutConstraint.parentIdealSize = { DEFAULT_ROOT_WIDTH, DEFAULT_ROOT_HEIGHT }; - LayoutConstraint.percentReference = { DEFAULT_ROOT_WIDTH, DEFAULT_ROOT_HEIGHT }; + LayoutConstraint.parentIdealSize = { DEVICE_WIDTH, DEVICE_HEIGHT }; + LayoutConstraint.percentReference = { DEVICE_WIDTH, DEVICE_HEIGHT }; LayoutConstraint.selfIdealSize = { 0, 0 }; - LayoutConstraint.maxSize = { DEFAULT_ROOT_WIDTH, DEFAULT_ROOT_HEIGHT }; + LayoutConstraint.maxSize = { DEVICE_WIDTH, DEVICE_HEIGHT }; layoutWrapper->Measure(LayoutConstraint); layoutWrapper->Layout(); layoutWrapper->MountToHostOnMainThread(); @@ -1050,7 +1033,7 @@ HWTEST_F(IndexerTestNg, IndexerPatternCoverage001, TestSize.Level1) IndexerModelNG.Create(CREATE_ARRAY, 0); IndexerModelNG.SetUsingPopup(true); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); pattern_->OnModifyDone(); /** @@ -1108,7 +1091,7 @@ HWTEST_F(IndexerTestNg, IndexerPatternCoverage002, TestSize.Level1) IndexerModelNG IndexerModelNG; IndexerModelNG.Create(CREATE_ARRAY, 0); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. Supplement OnPopupTouchDown branch, @@ -1130,7 +1113,7 @@ HWTEST_F(IndexerTestNg, IndexerAlgorithmCoverage001, TestSize.Level1) IndexerModelNG IndexerModelNG; IndexerModelNG.Create(CREATE_ARRAY, 0); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. Supplement Measure branch, @@ -1140,9 +1123,9 @@ HWTEST_F(IndexerTestNg, IndexerAlgorithmCoverage001, TestSize.Level1) RefPtr layoutWrapper = frameNode_->CreateLayoutWrapper(false, false); layoutWrapper->SetActive(); LayoutConstraintF LayoutConstraint; - LayoutConstraint.parentIdealSize = { DEFAULT_ROOT_WIDTH, DEFAULT_ROOT_HEIGHT }; - LayoutConstraint.percentReference = { DEFAULT_ROOT_WIDTH, DEFAULT_ROOT_HEIGHT }; - LayoutConstraint.maxSize = { DEFAULT_ROOT_WIDTH, DEFAULT_ROOT_HEIGHT }; + LayoutConstraint.parentIdealSize = { DEVICE_WIDTH, DEVICE_HEIGHT }; + LayoutConstraint.percentReference = { DEVICE_WIDTH, DEVICE_HEIGHT }; + LayoutConstraint.maxSize = { DEVICE_WIDTH, DEVICE_HEIGHT }; layoutWrapper->Measure(LayoutConstraint); layoutWrapper->Layout(); layoutWrapper->MountToHostOnMainThread(); diff --git a/frameworks/core/components_ng/test/pattern/list/BUILD.gn b/frameworks/core/components_ng/test/pattern/list/BUILD.gn index e9ceafc3c54..6c8ac9ddb10 100644 --- a/frameworks/core/components_ng/test/pattern/list/BUILD.gn +++ b/frameworks/core/components_ng/test/pattern/list/BUILD.gn @@ -123,6 +123,7 @@ common_sources = [ "$ace_root/frameworks/core/components_ng/test/mock/render/mock_modifier_adapter.cpp", "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_context.cpp", "$ace_root/frameworks/core/components_ng/test/mock/render/mock_render_context_creator.cpp", + "$ace_root/frameworks/core/components_ng/test/pattern/test_ng.cpp", "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_element_register.cpp", "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_pipeline_base.cpp", "$ace_root/test/mock/core/common/mock_container.cpp", diff --git a/frameworks/core/components_ng/test/pattern/list/list_test_ng.cpp b/frameworks/core/components_ng/test/pattern/list/list_test_ng.cpp index c82e0c706e0..b5b748f4d39 100644 --- a/frameworks/core/components_ng/test/pattern/list/list_test_ng.cpp +++ b/frameworks/core/components_ng/test/pattern/list/list_test_ng.cpp @@ -51,6 +51,7 @@ #include "core/components_ng/pattern/list/list_pattern.h" #include "core/components_ng/pattern/list/list_position_controller.h" #include "core/components_ng/test/mock/theme/mock_theme_manager.h" +#include "core/components_ng/test/pattern/test_ng.h" #include "core/components_v2/list/list_properties.h" #include "core/pipeline_ng/test/mock/mock_pipeline_base.h" #include "core/components_ng/test/mock/theme/mock_theme_manager.h" @@ -61,8 +62,6 @@ using namespace testing::ext; namespace OHOS::Ace::NG { namespace { -constexpr float DEVICE_WIDTH = 480.f; -constexpr float DEVICE_HEIGHT = 800.f; constexpr float GROUP_WIDTH = 400.f; constexpr float GROUP_ITEM_WIDTH = 300.f; constexpr int32_t TOTAL_NUMBER = 10; @@ -70,7 +69,6 @@ constexpr int32_t VIEWPORT_NUMBER = 8; constexpr int32_t GROUP_ITEM_NUMBER = 4; constexpr float ITEM_HEIGHT = 100.f; constexpr float ITEM_WIDTH = 60.f; -constexpr Dimension FILL_LENGTH = Dimension(1.0, DimensionUnit::PERCENT); constexpr float HEADER_MAIN_LENGTH = 50.f; constexpr float START_NODE_SIZE = 80.f; constexpr float END_NODE_SIZE = 100.f; @@ -87,16 +85,14 @@ constexpr float SPACE = 10.f; constexpr float STROKE_WIDTH = 2.f; } // namespace -class ListTestNg : public testing::Test { +class ListTestNg : public testing::Test, public TestNG { protected: static void SetUpTestSuite(); static void TearDownTestSuite(); void SetUp() override; void TearDown() override; void GetInstance(); - RefPtr RunMeasureAndLayout(float width = DEVICE_WIDTH, float height = DEVICE_HEIGHT); - static void SetWidth(const Dimension& width); - static void SetHeight(const Dimension& height); + void UpdateCurrentOffset(float offset); void CreateList(int32_t number = TOTAL_NUMBER, Axis axis = Axis::VERTICAL); void CreateSwipeList(bool isStartNode, V2::SwipeEdgeEffect swipeEdgeEffect, int32_t itemNumber = TOTAL_NUMBER); void CreateSelectableList(); @@ -110,11 +106,6 @@ protected: void CreateListItemWithSwipeActionItem(std::function builderAction, bool useDefaultDeleteAnimation, OnDeleteEvent onDelete, OnEnterDeleteAreaEvent onEnterDeleteArea, OnExitDeleteAreaEvent onExitDeleteArea, const Dimension& length, bool isStartArea, V2::SwipeEdgeEffect effect); - RefPtr GetChildFrameNode(int32_t index); - RefPtr GetChildFocusHub(int32_t index); - RefPtr GetItemPattern(int32_t index); - RefPtr GetGroupPattern(int32_t index); - const RectF& GetChildRect(const RefPtr& frameNode, int32_t index); std::function GetDefaultSwiperBuilder(float crossSize); std::function GetDefaultHeaderBuilder(); testing::AssertionResult VerifyItemPosition(int32_t expectCount, int32_t lanes = DEFAULT_LANES, @@ -122,20 +113,17 @@ protected: testing::AssertionResult VerifyGroupItemPosition( RefPtr groupNode, int32_t expectNumber, int32_t lanes = DEFAULT_LANES, float interval = DEFAULT_INTERVAL, float startOffset = 0); - testing::AssertionResult IsEqualNextFocusNode(FocusStep step, int32_t currentIndex, int32_t nextIndex = -1); testing::AssertionResult IsEqualCurrentOffset(Offset expectOffset); - testing::AssertionResult IsEqualRect(RectF rect, RectF expectRect); + testing::AssertionResult IsEqualNextFocusNode(FocusStep step, int32_t currentIndex, int32_t nextIndex = -1); testing::AssertionResult ScrollToIndex(int32_t index, bool smooth, ScrollAlign align, Offset expectOffset); testing::AssertionResult ScrollToIndex(int32_t index, int32_t indexInGroup, ScrollAlign align, Offset expectOffset); void MouseSelect(Offset start, Offset end); - void UpdateCurrentOffset(float offset); void ScrollToTop(); void ScrollToBottom(); void DragSwiperItem(int32_t index, float mainDelta, float mainVelocity = SWIPER_SPEED_TH); void HandleDragStart(int32_t index); void HandleDragUpdate(int32_t index, float mainDelta); void HandleDragEnd(int32_t index, float mainVelocity = SWIPER_SPEED_TH); - uint64_t GetActions(const RefPtr& accessibilityProperty); RefPtr frameNode_; RefPtr pattern_; @@ -184,38 +172,6 @@ void ListTestNg::GetInstance() accessibilityProperty_ = frameNode_->GetAccessibilityProperty(); } -RefPtr ListTestNg::RunMeasureAndLayout(float width, float height) -{ - RefPtr layoutWrapper = frameNode_->CreateLayoutWrapper(false, false); - layoutWrapper->SetActive(); - layoutWrapper->SetRootMeasureNode(); - LayoutConstraintF LayoutConstraint; - LayoutConstraint.parentIdealSize = { DEVICE_WIDTH, DEVICE_HEIGHT }; - LayoutConstraint.percentReference = { DEVICE_WIDTH, DEVICE_HEIGHT }; - if (NonNegative(width) && NonNegative(height)) { - LayoutConstraint.selfIdealSize = { width, height }; - } - LayoutConstraint.maxSize = { DEVICE_WIDTH, DEVICE_HEIGHT }; - layoutWrapper->Measure(LayoutConstraint); - layoutWrapper->Layout(); - layoutWrapper->MountToHostOnMainThread(); - return layoutWrapper; -} - -void ListTestNg::SetWidth(const Dimension& width) -{ - auto frameNode = ViewStackProcessor::GetInstance()->GetMainFrameNode(); - auto layoutProperty = frameNode->GetLayoutProperty(); - layoutProperty->UpdateUserDefinedIdealSize(CalcSize(CalcLength(width), std::nullopt)); -} - -void ListTestNg::SetHeight(const Dimension& height) -{ - auto frameNode = ViewStackProcessor::GetInstance()->GetMainFrameNode(); - auto layoutProperty = frameNode->GetLayoutProperty(); - layoutProperty->UpdateUserDefinedIdealSize(CalcSize(std::nullopt, CalcLength(height))); -} - void ListTestNg::CreateList(int32_t number, Axis axis) { ListModelNG listModelNG; @@ -225,7 +181,7 @@ void ListTestNg::CreateList(int32_t number, Axis axis) listModelNG.SetScroller(scroller, nullptr); CreateListItem(number, axis); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); } void ListTestNg::CreateSwipeList(bool isStartNode, V2::SwipeEdgeEffect swipeEdgeEffect, int32_t itemNumber) @@ -242,7 +198,7 @@ void ListTestNg::CreateSwipeList(bool isStartNode, V2::SwipeEdgeEffect swipeEdge } } GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); } void ListTestNg::CreateSelectableList() @@ -252,7 +208,7 @@ void ListTestNg::CreateSelectableList() listModelNG.SetMultiSelectable(true); CreateListItem(TOTAL_NUMBER); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); } void ListTestNg::CreateFocusableList(int32_t number, Axis axis) @@ -262,7 +218,7 @@ void ListTestNg::CreateFocusableList(int32_t number, Axis axis) listModelNG.SetListDirection(axis); CreateListItem(number, axis, true); // Create focusable ListItem. GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); } void ListTestNg::CreateChainList(const ChainAnimationOptions& options) @@ -274,7 +230,7 @@ void ListTestNg::CreateChainList(const ChainAnimationOptions& options) listModelNG.SetChainAnimationOptions(options); CreateListItem(TOTAL_NUMBER); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); } void ListTestNg::CreateListItemGroup(int32_t groupNumber) @@ -413,33 +369,7 @@ void ListTestNg::CreateListItemWithSwipeActionItem(std::function builder } ViewStackProcessor::GetInstance()->Pop(); GetInstance(); - RunMeasureAndLayout(); -} - -RefPtr ListTestNg::GetChildFrameNode(int32_t index) -{ - return AceType::DynamicCast(frameNode_->GetChildAtIndex(index)); -} - -RefPtr ListTestNg::GetChildFocusHub(int32_t index) -{ - return GetChildFrameNode(index)->GetOrCreateFocusHub(); -} - -RefPtr ListTestNg::GetItemPattern(int32_t index) -{ - return GetChildFrameNode(index)->GetPattern(); -} - -RefPtr ListTestNg::GetGroupPattern(int32_t index) -{ - return GetChildFrameNode(index)->GetPattern(); -} - -const RectF& ListTestNg::GetChildRect(const RefPtr& frameNode, int32_t index) -{ - auto child = AceType::DynamicCast(frameNode->GetChildAtIndex(index)); - return child->GetGeometryNode()->GetFrameRect(); + RunMeasureAndLayout(frameNode_); } std::function ListTestNg::GetDefaultSwiperBuilder(float crossSize) @@ -506,55 +436,38 @@ testing::AssertionResult ListTestNg::VerifyGroupItemPosition( return testing::AssertionSuccess(); } +testing::AssertionResult ListTestNg::IsEqualCurrentOffset(Offset expectOffset) +{ + RunMeasureAndLayout(frameNode_); + Offset currentOffset = pattern_->GetCurrentOffset(); + return IsEqualOffset(currentOffset, expectOffset); +} + testing::AssertionResult ListTestNg::IsEqualNextFocusNode( FocusStep step, int32_t currentIndex, int32_t nextIndex) { - RefPtr currentFocusNode = GetChildFocusHub(currentIndex); + RefPtr currentFocusNode = GetChildFocusHub(frameNode_, currentIndex); currentFocusNode->RequestFocusImmediately(); RefPtr nextFocusNode = pattern_->GetNextFocusNode(step, currentFocusNode).Upgrade(); if (nextIndex == -1 && nextFocusNode != nullptr) { return testing::AssertionFailure() << "Next FocusNode is not null."; } - if (nextIndex != -1 && nextFocusNode != GetChildFocusHub(nextIndex)) { + if (nextIndex != -1 && nextFocusNode != GetChildFocusHub(frameNode_, nextIndex)) { return testing::AssertionFailure() << "Get wrong next FocusNode."; } return testing::AssertionSuccess(); } -testing::AssertionResult ListTestNg::IsEqualCurrentOffset(Offset expectOffset) -{ - RunMeasureAndLayout(); - Offset currentOffset = pattern_->GetCurrentOffset(); - if (expectOffset == currentOffset) { - return testing::AssertionSuccess(); - } - return testing::AssertionFailure() << - "GetCurrentOffset(): " << currentOffset.ToString() << - " != " << - "expectOffset: " << expectOffset.ToString(); -} - -testing::AssertionResult ListTestNg::IsEqualRect(RectF rect, RectF expectRect) -{ - if (rect == expectRect) { - return testing::AssertionSuccess(); - } - return testing::AssertionFailure() << - "rect: " << rect.ToString() << - " != " << - "expectRect: " << expectRect.ToString(); -} - testing::AssertionResult ListTestNg::ScrollToIndex( int32_t index, bool smooth, ScrollAlign align, Offset expectOffset) { float originalOffsetY = pattern_->GetCurrentOffset().GetY(); pattern_->ScrollToIndex(index, smooth, align); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); Offset currentOffset = pattern_->GetCurrentOffset(); // reset offset before return pattern_->ScrollTo(originalOffsetY); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); if (currentOffset != expectOffset) { return testing::AssertionFailure() << "ScrollToIndex(" << index << ", " << smooth << @@ -571,11 +484,11 @@ testing::AssertionResult ListTestNg::ScrollToIndex( { float originalOffsetY = pattern_->GetCurrentOffset().GetY(); pattern_->ScrollToIndex(index, indexInGroup, align); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); Offset currentOffset = pattern_->GetCurrentOffset(); // reset offset before return pattern_->ScrollTo(originalOffsetY); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); if (currentOffset != expectOffset) { return testing::AssertionFailure() << "ScrollToIndex(" << index << ", " << indexInGroup << @@ -606,19 +519,19 @@ void ListTestNg::MouseSelect(Offset start, Offset end) void ListTestNg::UpdateCurrentOffset(float offset) { pattern_->UpdateCurrentOffset(offset, SCROLL_FROM_UPDATE); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); } void ListTestNg::ScrollToTop() { pattern_->ScrollToEdge(ScrollEdgeType::SCROLL_TOP); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); } void ListTestNg::ScrollToBottom() { pattern_->ScrollToEdge(ScrollEdgeType::SCROLL_BOTTOM); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); } void ListTestNg::DragSwiperItem(int32_t index, float mainDelta, float mainVelocity) @@ -631,7 +544,7 @@ void ListTestNg::DragSwiperItem(int32_t index, float mainDelta, float mainVeloci void ListTestNg::HandleDragStart(int32_t index) { GestureEvent info; - auto itemPattern = GetItemPattern(index); + auto itemPattern = GetChildPattern(frameNode_, index); itemPattern->HandleDragStart(info); } @@ -639,33 +552,23 @@ void ListTestNg::HandleDragUpdate(int32_t index, float mainDelta) { GestureEvent info; info.SetMainDelta(mainDelta); - auto itemPattern = GetItemPattern(index); + auto itemPattern = GetChildPattern(frameNode_, index); itemPattern->HandleDragUpdate(info); frameNode_->MarkDirtyNode(PROPERTY_UPDATE_MEASURE); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); } void ListTestNg::HandleDragEnd(int32_t index, float mainVelocity) { GestureEvent info; info.SetMainVelocity(mainVelocity); - auto itemPattern = GetItemPattern(index); + auto itemPattern = GetChildPattern(frameNode_, index); itemPattern->HandleDragEnd(info); // curOffset_ would be NodeSize or Zero double position = itemPattern->springMotion_->GetEndValue(); itemPattern->UpdatePostion(position - itemPattern->curOffset_); frameNode_->MarkDirtyNode(PROPERTY_UPDATE_MEASURE); - RunMeasureAndLayout(); -} - -uint64_t ListTestNg::GetActions(const RefPtr& accessibilityProperty) -{ - std::unordered_set supportAceActions = accessibilityProperty->GetSupportAction(); - uint64_t actions = 0; - for (auto action : supportAceActions) { - actions |= 1UL << static_cast(action); - } - return actions; + RunMeasureAndLayout(frameNode_); } /** @@ -698,7 +601,7 @@ HWTEST_F(ListTestNg, ListLayoutProperty001, TestSize.Level1) listModelNG.SetCachedCount(10); listModelNG.SetSticky(V2::StickyStyle::HEADER); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. Call ToJsonValue() @@ -772,7 +675,7 @@ HWTEST_F(ListTestNg, ListLayoutProperty001, TestSize.Level1) HWTEST_F(ListTestNg, ListItemLayoutProperty001, TestSize.Level1) { CreateList(TOTAL_NUMBER); - auto layoutProperty = GetChildFrameNode(0)->GetLayoutProperty(); + auto layoutProperty = GetChildFrameNode(frameNode_, 0)->GetLayoutProperty(); /** * @tc.steps: step1. Call ToJsonValue() @@ -847,7 +750,7 @@ HWTEST_F(ListTestNg, AttrSpace001, TestSize.Level1) listModelNG.SetSpace(Dimension(space)); CreateListItem(TOTAL_NUMBER); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); EXPECT_TRUE(VerifyItemPosition(VIEWPORT_NUMBER, 1, space)); } @@ -871,7 +774,7 @@ HWTEST_F(ListTestNg, AttrSpace002, TestSize.Level1) listModelNG.SetDivider(itemDivider); CreateListItem(TOTAL_NUMBER); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); EXPECT_TRUE(VerifyItemPosition(VIEWPORT_NUMBER, 1, strokeWidth)); } @@ -891,7 +794,7 @@ HWTEST_F(ListTestNg, AttrInitIndex001, TestSize.Level1) listModelNG.SetInitialIndex(initIndex); CreateListItem(TOTAL_NUMBER); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); EXPECT_TRUE(VerifyItemPosition(VIEWPORT_NUMBER, 1, 0, initIndex)); } @@ -913,7 +816,7 @@ HWTEST_F(ListTestNg, AttrInitIndex002, TestSize.Level1) listModelNG.SetInitialIndex(initIndex); CreateListItem(itemCount); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); EXPECT_TRUE(VerifyItemPosition(itemCount)); } @@ -934,7 +837,7 @@ HWTEST_F(ListTestNg, AttrInitIndex003, TestSize.Level1) listModelNG.SetInitialIndex(initIndex); CreateListItem(TOTAL_NUMBER); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); EXPECT_TRUE(VerifyItemPosition(VIEWPORT_NUMBER, 1, 0, expectStartIndex)); } @@ -954,7 +857,7 @@ HWTEST_F(ListTestNg, AttrInitIndex004, TestSize.Level1) listModelNG.SetInitialIndex(initIndex); CreateListItem(TOTAL_NUMBER); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); EXPECT_TRUE(VerifyItemPosition(VIEWPORT_NUMBER)); } @@ -980,7 +883,7 @@ HWTEST_F(ListTestNg, AttrInitIndex005, TestSize.Level1) listModelNG.SetLanes(lanes); CreateListItem(itemCount); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); EXPECT_TRUE(VerifyItemPosition(expectItemCount, lanes, 0, expectStartIndex)); } @@ -1007,7 +910,7 @@ HWTEST_F(ListTestNg, AttrDivider001, TestSize.Level1) listModelNG.SetDivider(itemDivider); CreateListItem(TOTAL_NUMBER); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); EXPECT_TRUE(VerifyItemPosition(VIEWPORT_NUMBER, 1, strokeWidth)); } @@ -1027,7 +930,7 @@ HWTEST_F(ListTestNg, AttrScrollBar001, TestSize.Level1) listModelNG.SetScrollBar(Ace::DisplayMode::ON); CreateListItem(TOTAL_NUMBER); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); RefPtr scrollBar = pattern_->GetScrollBar(); ASSERT_NE(scrollBar, nullptr); @@ -1051,7 +954,7 @@ HWTEST_F(ListTestNg, AttrScrollBar002, TestSize.Level1) MockPipelineBase::pipeline_->SetMinPlatformVersion(platformVersionTen); CreateListItem(TOTAL_NUMBER); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); RefPtr scrollBar = pattern_->GetScrollBar(); ASSERT_NE(scrollBar, nullptr); @@ -1073,7 +976,7 @@ HWTEST_F(ListTestNg, AttrLanes001, TestSize.Level1) listModelNG.SetLanes(lanes); CreateListItem(itemCount); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); int32_t expectItemCount = 16; int32_t expectLanes = 2; @@ -1106,7 +1009,7 @@ HWTEST_F(ListTestNg, AttrLanes002, TestSize.Level1) listModelNG.SetLaneMaxLength(Dimension(maxLaneLength)); CreateListItem(itemCount); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); int32_t expectLanes = 2; int32_t expectItemCount = 16; @@ -1148,7 +1051,7 @@ HWTEST_F(ListTestNg, AttrLanes003, TestSize.Level1) listModelNG.SetLaneMaxLength(Dimension(maxLaneLength)); CreateListItem(itemCount); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); int32_t expectItemCount = 16; int32_t expectLanes = 2; @@ -1180,7 +1083,7 @@ HWTEST_F(ListTestNg, AttrLanes005, TestSize.Level1) listModelNG.SetLaneGutter(laneGutter); CreateListItemGroup(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); EXPECT_EQ(laneGutter, layoutProperty_->GetLaneGutter().value_or(Dimension(0.0f, DimensionUnit::VP))); } @@ -1203,7 +1106,7 @@ HWTEST_F(ListTestNg, AttrAlignListItem001, TestSize.Level1) ViewStackProcessor::GetInstance()->Pop(); } GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); for (int32_t index = 0; index < TOTAL_NUMBER; index++) { float offsetX = GetChildRect(frameNode_, index).GetX(); @@ -1231,7 +1134,7 @@ HWTEST_F(ListTestNg, AttrAlignListItem002, TestSize.Level1) ViewStackProcessor::GetInstance()->Pop(); } GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); for (int32_t index = 0; index < TOTAL_NUMBER; index++) { float offsetX = GetChildRect(frameNode_, index).GetX(); @@ -1260,7 +1163,7 @@ HWTEST_F(ListTestNg, AttrAlignListItem003, TestSize.Level1) ViewStackProcessor::GetInstance()->Pop(); } GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); for (int32_t index = 0; index < TOTAL_NUMBER; index++) { float offsetX = GetChildRect(frameNode_, index).GetX(); @@ -1287,7 +1190,7 @@ HWTEST_F(ListTestNg, AttrSLECM001, TestSize.Level1) listModelNG.SetMultiSelectable(true); CreateListItem(TOTAL_NUMBER); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); EXPECT_NE(pattern_->positionController_, nullptr); EXPECT_EQ(pattern_->GetAxis(), Axis::HORIZONTAL); @@ -1312,7 +1215,7 @@ HWTEST_F(ListTestNg, AttrEnableScrollInteraction001, TestSize.Level1) listModelNG.SetScrollEnabled(true); CreateListItem(TOTAL_NUMBER); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); EXPECT_EQ(layoutProperty_->GetScrollEnabled(), true); /** @@ -1331,8 +1234,8 @@ HWTEST_F(ListTestNg, SwiperItem001, TestSize.Level1) { CreateSwipeList(true, V2::SwipeEdgeEffect::None); const int32_t listItemIndex = 0; - const RefPtr listItem = GetChildFrameNode(listItemIndex); - const RefPtr listItemPattern = GetItemPattern(listItemIndex); + const RefPtr listItem = GetChildFrameNode(frameNode_, listItemIndex); + const RefPtr listItemPattern = GetChildPattern(frameNode_, listItemIndex); const int32_t startNodeIndex = 0; const int32_t itemNodeIndex = 1; const RectF itemNodeInitialRect = RectF(0, 0, DEVICE_WIDTH, ITEM_HEIGHT); @@ -1434,8 +1337,8 @@ HWTEST_F(ListTestNg, SwiperItem002, TestSize.Level1) { CreateSwipeList(false, V2::SwipeEdgeEffect::None); const int32_t listItemIndex = 0; - const RefPtr listItem = GetChildFrameNode(listItemIndex); - const RefPtr listItemPattern = GetItemPattern(listItemIndex); + const RefPtr listItem = GetChildFrameNode(frameNode_, listItemIndex); + const RefPtr listItemPattern = GetChildPattern(frameNode_, listItemIndex); const int32_t endNodeIndex = 0; const int32_t itemNodeIndex = 1; const RectF itemNodeInitialRect = RectF(0, 0, DEVICE_WIDTH, ITEM_HEIGHT); @@ -1537,8 +1440,8 @@ HWTEST_F(ListTestNg, SwiperItem003, TestSize.Level1) { CreateSwipeList(true, V2::SwipeEdgeEffect::None); int32_t listItemIndex = 0; - auto listItem = GetChildFrameNode(listItemIndex); - auto listItemPattern = GetItemPattern(listItemIndex); + auto listItem = GetChildFrameNode(frameNode_, listItemIndex); + auto listItemPattern = GetChildPattern(frameNode_, listItemIndex); const float fastSpeed = SWIPER_SPEED_TH + 1; const float swipeDelta = 1; @@ -1569,8 +1472,8 @@ HWTEST_F(ListTestNg, SwiperItem003, TestSize.Level1) * @tc.expected: swiperIndex_ change to SWIPER_END */ CreateSwipeList(false, V2::SwipeEdgeEffect::None); - listItem = GetChildFrameNode(listItemIndex); - listItemPattern = GetItemPattern(listItemIndex); + listItem = GetChildFrameNode(frameNode_, listItemIndex); + listItemPattern = GetChildPattern(frameNode_, listItemIndex); DragSwiperItem(listItemIndex, -swipeDelta, -fastSpeed); swiperIndex = listItemPattern->GetSwiperIndex(); @@ -1597,8 +1500,8 @@ HWTEST_F(ListTestNg, SwiperItem004, TestSize.Level1) const float swipeDelta = 1; const int32_t firstItemIndex = 0; const int32_t secondItemIndex = 1; - const RefPtr firstItemPattern = GetItemPattern(firstItemIndex); - const RefPtr secondItemPattern = GetItemPattern(secondItemIndex); + const RefPtr firstItemPattern = GetChildPattern(frameNode_, firstItemIndex); + const RefPtr secondItemPattern = GetChildPattern(frameNode_, secondItemIndex); /** * @tc.steps: step1. Swipe first item fast @@ -1630,7 +1533,7 @@ HWTEST_F(ListTestNg, SwiperItem005, TestSize.Level1) { CreateSwipeList(true, V2::SwipeEdgeEffect::Spring); const int32_t listItemIndex = 0; - const RefPtr listItemPattern = GetItemPattern(listItemIndex); + const RefPtr listItemPattern = GetChildPattern(frameNode_, listItemIndex); /** * @tc.steps: step1. swipe end exceed listItem size @@ -1669,7 +1572,7 @@ HWTEST_F(ListTestNg, SwiperItem006, TestSize.Level1) { CreateSwipeList(false, V2::SwipeEdgeEffect::Spring); const int32_t listItemIndex = 0; - const RefPtr listItemPattern = GetItemPattern(listItemIndex); + const RefPtr listItemPattern = GetChildPattern(frameNode_, listItemIndex); /** * @tc.steps: step1. swipe start exceed listItem size @@ -1713,7 +1616,7 @@ HWTEST_F(ListTestNg, SwiperItem007, TestSize.Level1) CreateListItemWithSwipeActionItem( startFunc, true, nullptr, nullptr, nullptr, Dimension(DELETE_AREA_DISTANCE), true, V2::SwipeEdgeEffect::None); const int32_t listItemIndex = 0; - const RefPtr listItemPattern = GetItemPattern(listItemIndex); + const RefPtr listItemPattern = GetChildPattern(frameNode_, listItemIndex); const float maxDistance = START_NODE_SIZE + DELETE_AREA_DISTANCE; /** @@ -1756,7 +1659,7 @@ HWTEST_F(ListTestNg, SwiperItem008, TestSize.Level1) CreateListItemWithSwipeActionItem( endFunc, true, nullptr, nullptr, nullptr, Dimension(DELETE_AREA_DISTANCE), false, V2::SwipeEdgeEffect::None); const int32_t listItemIndex = 0; - const RefPtr listItemPattern = GetItemPattern(listItemIndex); + const RefPtr listItemPattern = GetChildPattern(frameNode_, listItemIndex); const float maxDistance = END_NODE_SIZE + DELETE_AREA_DISTANCE; /** @@ -1798,7 +1701,7 @@ HWTEST_F(ListTestNg, SwiperItem009, TestSize.Level1) CreateListItemWithSwipeActionItem( startFunc, true, nullptr, nullptr, nullptr, Dimension(DELETE_AREA_DISTANCE), true, V2::SwipeEdgeEffect::Spring); const int32_t listItemIndex = 0; - const RefPtr listItemPattern = GetItemPattern(listItemIndex); + const RefPtr listItemPattern = GetChildPattern(frameNode_, listItemIndex); const float maxDistance = START_NODE_SIZE + DELETE_AREA_DISTANCE; /** @@ -1840,7 +1743,7 @@ HWTEST_F(ListTestNg, SwiperItem010, TestSize.Level1) CreateListItemWithSwipeActionItem( endFunc, true, nullptr, nullptr, nullptr, Dimension(DELETE_AREA_DISTANCE), false, V2::SwipeEdgeEffect::Spring); const int32_t listItemIndex = 0; - const RefPtr listItemPattern = GetItemPattern(listItemIndex); + const RefPtr listItemPattern = GetChildPattern(frameNode_, listItemIndex); const float maxDistance = END_NODE_SIZE + DELETE_AREA_DISTANCE; /** * @tc.steps: step1. Swipe end greater than maxDistance @@ -2011,14 +1914,14 @@ HWTEST_F(ListTestNg, ListItemGroup001, TestSize.Level1) listModelNG.SetInitialIndex(1); CreateListItemGroup(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. Verify second ListItemGroup itemPosition_/rect. */ int32_t groupIndex = 1; - auto groupNode = GetChildFrameNode(groupIndex); - auto groupItemPosition = GetGroupPattern(groupIndex)->GetItemPosition(); + auto groupNode = GetChildFrameNode(frameNode_, groupIndex); + auto groupItemPosition = GetChildPattern(frameNode_, groupIndex)->GetItemPosition(); EXPECT_EQ(groupItemPosition.size(), static_cast(GROUP_ITEM_NUMBER)); auto groupRect = GetChildRect(frameNode_, groupIndex); EXPECT_TRUE(IsEqualRect(groupRect, RectF(0, 0, GROUP_WIDTH, @@ -2035,8 +1938,8 @@ HWTEST_F(ListTestNg, ListItemGroup001, TestSize.Level1) */ UpdateCurrentOffset(-GetChildRect(frameNode_, groupIndex).Height()); groupIndex = 2; - groupNode = GetChildFrameNode(groupIndex); - groupItemPosition = GetGroupPattern(groupIndex)->GetItemPosition(); + groupNode = GetChildFrameNode(frameNode_, groupIndex); + groupItemPosition = GetChildPattern(frameNode_, groupIndex)->GetItemPosition(); EXPECT_EQ(groupItemPosition.size(), static_cast(GROUP_ITEM_NUMBER)); VerifyGroupItemPosition(groupNode, GROUP_ITEM_NUMBER, DEFAULT_LANES, SPACE, 0); @@ -2045,8 +1948,8 @@ HWTEST_F(ListTestNg, ListItemGroup001, TestSize.Level1) */ UpdateCurrentOffset(-GetChildRect(frameNode_, groupIndex).Height()); groupIndex = 3; - groupNode = GetChildFrameNode(groupIndex); - groupItemPosition = GetGroupPattern(groupIndex)->GetItemPosition(); + groupNode = GetChildFrameNode(frameNode_, groupIndex); + groupItemPosition = GetChildPattern(frameNode_, groupIndex)->GetItemPosition(); EXPECT_EQ(groupItemPosition.size(), static_cast(GROUP_ITEM_NUMBER)); VerifyGroupItemPosition(groupNode, GROUP_ITEM_NUMBER, DEFAULT_LANES, SPACE, 0); @@ -2054,8 +1957,8 @@ HWTEST_F(ListTestNg, ListItemGroup001, TestSize.Level1) * @tc.steps: step4. Verify fifth ListItemGroup itemPosition_/rect. */ groupIndex = 4; - groupNode = GetChildFrameNode(groupIndex); - groupItemPosition = GetGroupPattern(groupIndex)->GetItemPosition(); + groupNode = GetChildFrameNode(frameNode_, groupIndex); + groupItemPosition = GetChildPattern(frameNode_, groupIndex)->GetItemPosition(); EXPECT_EQ(groupItemPosition.size(), 0); EXPECT_EQ(GetChildRect(frameNode_, groupIndex).Height(), 0); groupRect = GetChildRect(frameNode_, groupIndex); @@ -2078,9 +1981,9 @@ HWTEST_F(ListTestNg, ListItemGroup002, TestSize.Level1) listModelNG_1.SetSticky(V2::StickyStyle::HEADER); CreateListItemGroup(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); int32_t groupIndex = 0; - auto groupNode = GetChildFrameNode(groupIndex); + auto groupNode = GetChildFrameNode(frameNode_, groupIndex); auto headRect = GetChildRect(groupNode, 0); EXPECT_TRUE(IsEqualRect(headRect, RectF(0, 0, GROUP_WIDTH, HEADER_MAIN_LENGTH))); UpdateCurrentOffset(-ITEM_HEIGHT); @@ -2096,9 +1999,9 @@ HWTEST_F(ListTestNg, ListItemGroup002, TestSize.Level1) listModelNG_2.SetSticky(V2::StickyStyle::FOOTER); CreateListItemGroup(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); groupIndex = 1; - groupNode = GetChildFrameNode(groupIndex); + groupNode = GetChildFrameNode(frameNode_, groupIndex); auto footRect = GetChildRect(groupNode, 1); float footOffsetY = DEVICE_HEIGHT - GetChildRect(frameNode_, 0).Height() - HEADER_MAIN_LENGTH; EXPECT_TRUE(IsEqualRect(footRect, RectF(0, footOffsetY, GROUP_WIDTH, HEADER_MAIN_LENGTH))); @@ -2115,9 +2018,9 @@ HWTEST_F(ListTestNg, ListItemGroup002, TestSize.Level1) listModelNG_3.SetSticky(V2::StickyStyle::BOTH); CreateListItemGroup(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); groupIndex = 0; - groupNode = GetChildFrameNode(groupIndex); + groupNode = GetChildFrameNode(frameNode_, groupIndex); headRect = GetChildRect(groupNode, 0); EXPECT_TRUE(IsEqualRect(headRect, RectF(0, 0, GROUP_WIDTH, HEADER_MAIN_LENGTH))); UpdateCurrentOffset(-ITEM_HEIGHT); @@ -2125,7 +2028,7 @@ HWTEST_F(ListTestNg, ListItemGroup002, TestSize.Level1) EXPECT_TRUE(IsEqualRect(headRect, RectF(0, ITEM_HEIGHT, GROUP_WIDTH, HEADER_MAIN_LENGTH))); groupIndex = 1; - groupNode = GetChildFrameNode(groupIndex); + groupNode = GetChildFrameNode(frameNode_, groupIndex); footRect = GetChildRect(groupNode, 1); footOffsetY = DEVICE_HEIGHT - GetChildRect(frameNode_, 0).Height() - HEADER_MAIN_LENGTH + ITEM_HEIGHT; EXPECT_TRUE(IsEqualRect(footRect, RectF(0, footOffsetY, GROUP_WIDTH, HEADER_MAIN_LENGTH))); @@ -2151,9 +2054,9 @@ HWTEST_F(ListTestNg, ListItemGroup004, TestSize.Level1) listModelNG_1.SetLanes(lanes); CreateListItemGroup(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); int32_t groupIndex = 0; - auto groupNode = GetChildFrameNode(groupIndex); + auto groupNode = GetChildFrameNode(frameNode_, groupIndex); auto groupRect = GetChildRect(frameNode_, groupIndex); EXPECT_TRUE(VerifyGroupItemPosition(groupNode, GROUP_ITEM_NUMBER, lanes, SPACE, HEADER_MAIN_LENGTH)); int32_t rows = std::floor(GROUP_ITEM_NUMBER / lanes); @@ -2171,9 +2074,9 @@ HWTEST_F(ListTestNg, ListItemGroup004, TestSize.Level1) listModelNG_2.SetLaneMaxLength(Dimension(maxLaneLength)); CreateListItemGroup(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); groupIndex = 0; - groupNode = GetChildFrameNode(groupIndex); + groupNode = GetChildFrameNode(frameNode_, groupIndex); EXPECT_TRUE(VerifyGroupItemPosition(groupNode, GROUP_ITEM_NUMBER, DEFAULT_LANES, SPACE, HEADER_MAIN_LENGTH)); EXPECT_EQ(GetChildRect(groupNode, 2).Width(), GROUP_WIDTH); @@ -2188,9 +2091,9 @@ HWTEST_F(ListTestNg, ListItemGroup004, TestSize.Level1) listModelNG_3.SetLaneMaxLength(Dimension(maxLaneLength)); CreateListItemGroup(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); groupIndex = 0; - groupNode = GetChildFrameNode(groupIndex); + groupNode = GetChildFrameNode(frameNode_, groupIndex); EXPECT_TRUE(VerifyGroupItemPosition(groupNode, GROUP_ITEM_NUMBER, DEFAULT_LANES, SPACE, HEADER_MAIN_LENGTH)); EXPECT_EQ(GetChildRect(groupNode, 2).Width(), maxLaneLength); } @@ -2210,11 +2113,11 @@ HWTEST_F(ListTestNg, ListItemGroup005, TestSize.Level1) listModelNG_1.SetListItemAlign(V2::ListItemAlign::START); CreateListItemGroup(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); // scroll to second group UpdateCurrentOffset(-GetChildRect(frameNode_, 0).Height()); int32_t groupIndex = 1; - auto groupNode = GetChildFrameNode(groupIndex); + auto groupNode = GetChildFrameNode(frameNode_, groupIndex); auto listItemRect = GetChildRect(groupNode, 2); EXPECT_TRUE(IsEqualRect(listItemRect, RectF(0, HEADER_MAIN_LENGTH, GROUP_ITEM_WIDTH, ITEM_HEIGHT))); @@ -2226,10 +2129,10 @@ HWTEST_F(ListTestNg, ListItemGroup005, TestSize.Level1) listModelNG_2.SetListItemAlign(V2::ListItemAlign::CENTER); CreateListItemGroup(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); UpdateCurrentOffset(-GetChildRect(frameNode_, 0).Height()); groupIndex = 1; - groupNode = GetChildFrameNode(groupIndex); + groupNode = GetChildFrameNode(frameNode_, groupIndex); listItemRect = GetChildRect(groupNode, 2); EXPECT_TRUE(IsEqualRect(listItemRect, RectF((GROUP_WIDTH - GROUP_ITEM_WIDTH) / 2, HEADER_MAIN_LENGTH, GROUP_ITEM_WIDTH, ITEM_HEIGHT))); @@ -2242,10 +2145,10 @@ HWTEST_F(ListTestNg, ListItemGroup005, TestSize.Level1) listModelNG_3.SetListItemAlign(V2::ListItemAlign::END); CreateListItemGroup(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); UpdateCurrentOffset(-GetChildRect(frameNode_, 0).Height()); groupIndex = 1; - groupNode = GetChildFrameNode(groupIndex); + groupNode = GetChildFrameNode(frameNode_, groupIndex); listItemRect = GetChildRect(groupNode, 2); EXPECT_TRUE(IsEqualRect(listItemRect, RectF(GROUP_WIDTH - GROUP_ITEM_WIDTH, HEADER_MAIN_LENGTH, GROUP_ITEM_WIDTH, ITEM_HEIGHT))); @@ -2269,25 +2172,25 @@ HWTEST_F(ListTestNg, Event001, TestSize.Level1) listModelNG.SetOnScroll(event); CreateListItem(TOTAL_NUMBER); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); pattern_->UpdateCurrentOffset(-ITEM_HEIGHT, SCROLL_FROM_UPDATE); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); EXPECT_EQ(offsetY.ConvertToPx(), ITEM_HEIGHT); EXPECT_EQ(scrollState, ScrollState::SCROLL); pattern_->UpdateCurrentOffset(ITEM_HEIGHT, SCROLL_FROM_ANIMATION); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); EXPECT_EQ(offsetY.ConvertToPx(), -ITEM_HEIGHT); EXPECT_EQ(scrollState, ScrollState::FLING); pattern_->UpdateCurrentOffset(-ITEM_HEIGHT, SCROLL_FROM_ANIMATION_SPRING); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); EXPECT_EQ(offsetY.ConvertToPx(), ITEM_HEIGHT); EXPECT_EQ(scrollState, ScrollState::FLING); pattern_->UpdateCurrentOffset(ITEM_HEIGHT, SCROLL_FROM_NONE); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); EXPECT_EQ(offsetY.ConvertToPx(), -ITEM_HEIGHT); EXPECT_EQ(scrollState, ScrollState::IDLE); } @@ -2312,7 +2215,7 @@ HWTEST_F(ListTestNg, Event002, TestSize.Level1) listModelNG.SetOnScrollIndex(event); CreateListItem(TOTAL_NUMBER); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); UpdateCurrentOffset(-ITEM_HEIGHT); EXPECT_EQ(startIndex, 0); @@ -2339,7 +2242,7 @@ HWTEST_F(ListTestNg, Event003, TestSize.Level1) listModelNG.SetOnReachStart(event); CreateListItem(TOTAL_NUMBER); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); EXPECT_TRUE(isTrigger); isTrigger = false; @@ -2365,7 +2268,7 @@ HWTEST_F(ListTestNg, Event004, TestSize.Level1) listModelNG.SetOnReachEnd(event); CreateListItem(TOTAL_NUMBER); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); isTrigger = false; UpdateCurrentOffset(-ITEM_HEIGHT * 2); @@ -2395,13 +2298,13 @@ HWTEST_F(ListTestNg, Event005, TestSize.Level1) listModelNG.SetOnScrollStart(scrollStart); listModelNG.SetOnScrollStop(scrollStop); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); pattern_->OnScrollCallback(100.f, SCROLL_FROM_START); EXPECT_TRUE(isScrollStartCalled); pattern_->OnScrollEndCallback(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); EXPECT_TRUE(isScrollStopCalled); } @@ -2423,13 +2326,13 @@ HWTEST_F(ListTestNg, Event006, TestSize.Level1) return result; }); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); auto scrollableEvent = pattern_->GetScrollableEvent(); ASSERT_NE(scrollableEvent, nullptr); EXPECT_NE(scrollableEvent->GetScrollBeginCallback(), nullptr); EXPECT_NE(scrollableEvent->GetScrollFrameBeginCallback(), nullptr); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); } /** @@ -2452,7 +2355,7 @@ HWTEST_F(ListTestNg, EventHub001, TestSize.Level1) * @tc.steps: step2. Run ListItem GetDragExtraParams func. * @tc.expected: Verify return value. */ - auto itemFrameNode = GetChildFrameNode(0); + auto itemFrameNode = GetChildFrameNode(frameNode_, 0); auto itemEventHub = itemFrameNode->GetEventHub(); jsonStr = itemEventHub->GetDragExtraParams("", Point(0, 200.f), DragEventType::START); EXPECT_NE(jsonStr, ""); @@ -2474,18 +2377,18 @@ HWTEST_F(ListTestNg, MouseSelect001, TestSize.Level1) * @tc.expected: The 1st and 2nd items are selected. */ MouseSelect(Offset(0.f, 0.f), Offset(200.f, 100.f)); - EXPECT_TRUE(GetItemPattern(0)->IsSelected()); - EXPECT_TRUE(GetItemPattern(1)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 0)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 1)->IsSelected()); /** * @tc.steps: step2. Change select zone. * @tc.expected: Selected items changed. */ MouseSelect(Offset(200.f, 200.f), Offset(200.f, 300.f)); - EXPECT_FALSE(GetItemPattern(0)->IsSelected()); - EXPECT_TRUE(GetItemPattern(1)->IsSelected()); - EXPECT_TRUE(GetItemPattern(2)->IsSelected()); - EXPECT_TRUE(GetItemPattern(3)->IsSelected()); + EXPECT_FALSE(GetChildPattern(frameNode_, 0)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 1)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 2)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 3)->IsSelected()); /** * @tc.steps: step3. Click first item. @@ -2493,7 +2396,7 @@ HWTEST_F(ListTestNg, MouseSelect001, TestSize.Level1) */ MouseSelect(Offset(10.f, 10.f), Offset(10.f, 10.f)); for (int32_t index = 0; index < VIEWPORT_NUMBER; index++) { - EXPECT_FALSE(GetItemPattern(index)->IsSelected()) << "Index: " << index; + EXPECT_FALSE(GetChildPattern(frameNode_, index)->IsSelected()) << "Index: " << index; } } @@ -2514,29 +2417,29 @@ HWTEST_F(ListTestNg, MouseSelect002, TestSize.Level1) * @tc.steps: step1. Select from LEFT_TOP to RIGHT_BOTTOM */ MouseSelect(LEFT_TOP, RIGHT_BOTTOM); - EXPECT_TRUE(GetItemPattern(2)->IsSelected()); - EXPECT_TRUE(GetItemPattern(3)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 2)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 3)->IsSelected()); /** * @tc.steps: step2. Select from RIGHT_TOP to LEFT_BOTTOM */ MouseSelect(RIGHT_TOP, LEFT_BOTTOM); - EXPECT_TRUE(GetItemPattern(2)->IsSelected()); - EXPECT_TRUE(GetItemPattern(3)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 2)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 3)->IsSelected()); /** * @tc.steps: step3. Select from LEFT_BOTTOM to RIGHT_TOP */ MouseSelect(LEFT_BOTTOM, RIGHT_TOP); - EXPECT_TRUE(GetItemPattern(2)->IsSelected()); - EXPECT_TRUE(GetItemPattern(3)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 2)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 3)->IsSelected()); /** * @tc.steps: step4. Select from RIGHT_BOTTOM to LEFT_TOP */ MouseSelect(RIGHT_BOTTOM, LEFT_TOP); - EXPECT_TRUE(GetItemPattern(2)->IsSelected()); - EXPECT_TRUE(GetItemPattern(3)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 2)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 3)->IsSelected()); } /** @@ -2569,15 +2472,15 @@ HWTEST_F(ListTestNg, MouseSelect003, TestSize.Level1) ViewStackProcessor::GetInstance()->Pop(); } GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step2. Select zone. * @tc.expected: The 4th item is not selected but 5th item is selected. */ MouseSelect(Offset(120.f, 350.f), Offset(360.f, 450.f)); - EXPECT_FALSE(GetItemPattern(3)->IsSelected()); - EXPECT_TRUE(GetItemPattern(4)->IsSelected()); + EXPECT_FALSE(GetChildPattern(frameNode_, 3)->IsSelected()); + EXPECT_TRUE(GetChildPattern(frameNode_, 4)->IsSelected()); EXPECT_TRUE(isFifthItemSelected); } @@ -2603,7 +2506,7 @@ HWTEST_F(ListTestNg, MouseSelect004, TestSize.Level1) info.SetLocalLocation(Offset(200.f, 100.f)); pattern_->HandleMouseEventWithoutKeyboard(info); for (int32_t index = 0; index < VIEWPORT_NUMBER; index++) { - EXPECT_FALSE(GetItemPattern(index)->IsSelected()) << "Index: " << index; + EXPECT_FALSE(GetChildPattern(frameNode_, index)->IsSelected()) << "Index: " << index; } /** @@ -2615,7 +2518,7 @@ HWTEST_F(ListTestNg, MouseSelect004, TestSize.Level1) info.SetLocalLocation(Offset::Zero()); pattern_->HandleMouseEventWithoutKeyboard(info); for (int32_t index = 0; index < VIEWPORT_NUMBER; index++) { - EXPECT_FALSE(GetItemPattern(index)->IsSelected()) << "Index: " << index; + EXPECT_FALSE(GetChildPattern(frameNode_, index)->IsSelected()) << "Index: " << index; } } @@ -2703,7 +2606,8 @@ HWTEST_F(ListTestNg, AccessibilityProperty002, TestSize.Level1) HWTEST_F(ListTestNg, AccessibilityProperty003, TestSize.Level1) { CreateList(TOTAL_NUMBER); - auto itemAccessibilityProperty = GetChildFrameNode(0)->GetAccessibilityProperty(); + auto listItem = GetChildFrameNode(frameNode_, 0); + auto itemAccessibilityProperty = listItem->GetAccessibilityProperty(); EXPECT_FALSE(itemAccessibilityProperty->IsSelected()); itemAccessibilityProperty->ResetSupportAction(); @@ -2724,14 +2628,15 @@ HWTEST_F(ListTestNg, AccessibilityProperty004, TestSize.Level1) listModelNG.Create(); CreateListItemGroup(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); auto groupAccessibilityProperty = - GetChildFrameNode(0)->GetAccessibilityProperty(); + GetChildFrameNode(frameNode_, 0)->GetAccessibilityProperty(); EXPECT_EQ(groupAccessibilityProperty->GetBeginIndex(), 0); EXPECT_EQ(groupAccessibilityProperty->GetEndIndex(), 3); - groupAccessibilityProperty = GetChildFrameNode(4)->GetAccessibilityProperty(); + groupAccessibilityProperty = + GetChildFrameNode(frameNode_, 4)->GetAccessibilityProperty(); EXPECT_EQ(groupAccessibilityProperty->GetBeginIndex(), -1); EXPECT_EQ(groupAccessibilityProperty->GetEndIndex(), -1); } @@ -2907,7 +2812,7 @@ HWTEST_F(ListTestNg, FocusStep003, TestSize.Level1) * @tc.expected: The unfocuseable item would be skiped. */ CreateFocusableList(VIEWPORT_NUMBER, Axis::VERTICAL); - GetChildFocusHub(1)->SetFocusable(false); + GetChildFocusHub(frameNode_, 1)->SetFocusable(false); EXPECT_TRUE(IsEqualNextFocusNode(FocusStep::DOWN, 0, 2)); /** @@ -2946,7 +2851,7 @@ HWTEST_F(ListTestNg, FocusStep006, TestSize.Level1) CreateListItem(10, Axis::VERTICAL, true); listModelNG.SetLanes(3); GetInstance(); - auto layoutWrapper = RunMeasureAndLayout(); + auto layoutWrapper = RunMeasureAndLayout(frameNode_); /** * @tc.steps: step2. Obtain nodes for items in the list and set focusable itme parameter. @@ -2989,7 +2894,7 @@ HWTEST_F(ListTestNg, FocusStep007, TestSize.Level1) CreateListItemGroup(); ViewStackProcessor::GetInstance()->Pop(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); ASSERT_NE(frameNode_, nullptr); /** @@ -3053,7 +2958,7 @@ HWTEST_F(ListTestNg, PaintMethod001, TestSize.Level1) RefPtr scrollController = listModelNG.CreateScrollController(); listModelNG.SetScroller(scrollController, nullptr); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); RefPtr paint = pattern_->CreateNodePaintMethod(); ASSERT_NE(paint, nullptr); @@ -3091,7 +2996,7 @@ HWTEST_F(ListTestNg, PaintMethod002, TestSize.Level1) CreateListItemGroup(); CreateListItem(TOTAL_NUMBER); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); auto scrollBar = pattern_->GetScrollBar(); scrollBar->SetScrollable(true); @@ -3137,7 +3042,7 @@ HWTEST_F(ListTestNg, PaintMethod003, TestSize.Level1) CreateListItemGroup(); CreateListItem(TOTAL_NUMBER); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); RefPtr paint = pattern_->CreateNodePaintMethod(); RefPtr listPaint = AceType::DynamicCast(paint); @@ -3168,9 +3073,9 @@ HWTEST_F(ListTestNg, PaintMethod004, TestSize.Level1) CreateListItem(TOTAL_NUMBER); ViewStackProcessor::GetInstance()->Pop(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); - auto groupFrameNode = GetChildFrameNode(0); + auto groupFrameNode = GetChildFrameNode(frameNode_, 0); auto groupPattern = groupFrameNode->GetPattern(); RefPtr paint = groupPattern->CreateNodePaintMethod(); @@ -3314,7 +3219,7 @@ HWTEST_F(ListTestNg, Pattern001, TestSize.Level1) listModelNG.SetMultiSelectable(true); CreateListItem(TOTAL_NUMBER); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); pattern_->OnModifyDone(); EXPECT_TRUE(pattern_->isMouseEventInit_); @@ -3364,7 +3269,7 @@ HWTEST_F(ListTestNg, Pattern003, TestSize.Level1) { Dimension(0), Dimension(10), 0, 0, 0, DEFAULT_STIFFNESS, DEFAULT_DAMPING }); CreateListItem(TOTAL_NUMBER); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); EXPECT_NE(pattern_->springProperty_, nullptr); EXPECT_NE(pattern_->chainAnimation_, nullptr); pattern_->OutBoundaryCallback(); @@ -3502,7 +3407,7 @@ HWTEST_F(ListTestNg, ScrollToIndex002, TestSize.Level1) listModelNG.SetLanes(lanes); CreateListItem(itemNumber); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. first item in viewport @@ -3610,7 +3515,7 @@ HWTEST_F(ListTestNg, ScrollToIndex003, TestSize.Level1) listModelNG.Create(); CreateListItemGroup(groupNumber); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); constexpr float groupHeight = GROUP_ITEM_NUMBER * ITEM_HEIGHT; // 400 /** @@ -3719,7 +3624,7 @@ HWTEST_F(ListTestNg, ScrollToIndex004, TestSize.Level1) listModelNG.Create(); CreateListItemGroup(groupNumber); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); constexpr float groupHeight = GROUP_ITEM_NUMBER * ITEM_HEIGHT; constexpr int32_t indexInGroup = 2; @@ -3794,7 +3699,7 @@ HWTEST_F(ListTestNg, ScrollToIndex005, TestSize.Level1) listModelNG.SetLanes(lanes); CreateListItemGroup(groupNumber); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); constexpr float groupHeight = GROUP_ITEM_NUMBER * ITEM_HEIGHT / lanes; /** @@ -3877,7 +3782,7 @@ HWTEST_F(ListTestNg, Pattern005, TestSize.Level1) CreateListItemWithSwiper(startFunc, nullptr, V2::SwipeEdgeEffect::None); CreateListItem(TOTAL_NUMBER); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); // Set swiperItem_ to list pattern DragSwiperItem(0, 1.f); @@ -3933,7 +3838,7 @@ HWTEST_F(ListTestNg, Pattern006, TestSize.Level1) listModelNG.SetLanes(2); CreateListItem(VIEWPORT_NUMBER); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. When lanes > 1, call GetItemIndexByPosition @@ -3956,7 +3861,7 @@ HWTEST_F(ListTestNg, Pattern007, TestSize.Level1) listModelNG.Create(); CreateListItem(VIEWPORT_NUMBER); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. When has ListItem, position not at any ListItem @@ -3977,7 +3882,7 @@ HWTEST_F(ListTestNg, Pattern008, TestSize.Level1) ListModelNG listModelNG; listModelNG.Create(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. When has no ListItem, call GetItemIndexByPosition @@ -4026,7 +3931,7 @@ HWTEST_F(ListTestNg, Pattern010, TestSize.Level1) ListModelNG listModelNG_1; listModelNG_1.Create(); GetInstance(); - RunMeasureAndLayout(-1, -1); + RunMeasureAndLayout(frameNode_, -1, -1); EXPECT_EQ(frameNode_->GetGeometryNode()->GetFrameSize().Width(), DEVICE_WIDTH); /** @@ -4036,7 +3941,7 @@ HWTEST_F(ListTestNg, Pattern010, TestSize.Level1) listModelNG_2.Create(); CreateListItem(TOTAL_NUMBER); GetInstance(); - RunMeasureAndLayout(-1, -1); + RunMeasureAndLayout(frameNode_, -1, -1); EXPECT_EQ(frameNode_->GetGeometryNode()->GetFrameSize().Width(), DEVICE_WIDTH); /** @@ -4046,7 +3951,7 @@ HWTEST_F(ListTestNg, Pattern010, TestSize.Level1) listModelNG_3.Create(); CreateListItem(TOTAL_NUMBER); GetInstance(); - RunMeasureAndLayout(Infinity(), DEVICE_HEIGHT); + RunMeasureAndLayout(frameNode_, Infinity(), DEVICE_HEIGHT); EXPECT_EQ(frameNode_->GetGeometryNode()->GetFrameSize().Width(), Infinity()); } @@ -4069,7 +3974,7 @@ HWTEST_F(ListTestNg, ListSelectForCardModeTest001, TestSize.Level1) CreateListItem(9); ViewStackProcessor::GetInstance()->Pop(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step2. Click the (0, 0) point of firstItem. @@ -4127,7 +4032,7 @@ HWTEST_F(ListTestNg, ListSelectForCardModeTest002, TestSize.Level1) CreateListItem(9); ViewStackProcessor::GetInstance()->Pop(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step2. Select (0, 0) - (200, 100) zone. @@ -4201,7 +4106,7 @@ HWTEST_F(ListTestNg, ListSelectForCardModeTest003, TestSize.Level1) ViewStackProcessor::GetInstance()->Pop(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step2. Select (120, 250) - (360, 350) zone. @@ -4220,7 +4125,7 @@ HWTEST_F(ListTestNg, ListSelectForCardModeTest003, TestSize.Level1) * @tc.steps: step3. Get ListItemGroup frameNode and ListItemPattern. * @tc.expected: Get ListItemGroup frameNode/ListItemPattern success, and judge the step2. */ - auto itemGroupFrameNode = GetChildFrameNode(0); + auto itemGroupFrameNode = GetChildFrameNode(frameNode_, 0); ASSERT_NE(itemGroupFrameNode, nullptr); auto itemFourth = itemGroupFrameNode->GetChildAtIndex(3); ASSERT_NE(itemFourth, nullptr); @@ -4677,7 +4582,7 @@ HWTEST_F(ListTestNg, ListPattern_OnDirtyLayoutWrapperSwap001, TestSize.Level1) ListModelNG listModelNG; listModelNG.Create(); GetInstance(); - auto layoutWrapper = RunMeasureAndLayout(); + auto layoutWrapper = RunMeasureAndLayout(frameNode_); ASSERT_NE(layoutWrapper, nullptr); auto layoutAlgorithmWrapper = AceType::DynamicCast(layoutWrapper->GetLayoutAlgorithm()); ASSERT_NE(layoutAlgorithmWrapper, nullptr); @@ -4828,7 +4733,7 @@ HWTEST_F(ListTestNg, ListPositionControllerTest001, TestSize.Level1) listModelNG.SetScroller(scroller, nullptr); CreateListItem(10); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. Get positionController and set scroll_. @@ -4865,7 +4770,7 @@ HWTEST_F(ListTestNg, ListPositionControllerTest002, TestSize.Level1) listModelNG.SetScroller(scroller, nullptr); CreateListItem(10); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. Get positionController and set scroll_. @@ -4901,7 +4806,7 @@ HWTEST_F(ListTestNg, ListPositionControllerTest003, TestSize.Level1) listModelNG.SetScroller(scroller, nullptr); CreateListItem(10); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. Get positionController and set scroll_. @@ -4936,7 +4841,7 @@ HWTEST_F(ListTestNg, ListPositionControllerTest004, TestSize.Level1) listModelNG.SetScroller(scrollController, proxy); CreateListItem(10); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); EXPECT_FALSE(scrollController->IsAtEnd()); @@ -4983,7 +4888,7 @@ HWTEST_F(ListTestNg, ScrollToIndexAlign001, TestSize.Level1) listModelNG.SetInitialIndex(0); CreateListItem(TOTAL_NUMBER); GetInstance(); - auto layoutWrapper = RunMeasureAndLayout(); + auto layoutWrapper = RunMeasureAndLayout(frameNode_); ASSERT_NE(layoutWrapper, nullptr); /** @@ -5004,7 +4909,7 @@ HWTEST_F(ListTestNg, ScrollToIndexAlign001, TestSize.Level1) EXPECT_EQ(listLayoutAlgorithm->jumpIndex_, TOTAL_NUMBER - 2); EXPECT_EQ(listLayoutAlgorithm->scrollAlign_, ScrollAlign::AUTO); EXPECT_EQ(listLayoutAlgorithm->GetStartIndex(), 0); - layoutWrapper = RunMeasureAndLayout(); + layoutWrapper = RunMeasureAndLayout(frameNode_); ASSERT_NE(layoutWrapper, nullptr); auto layoutAlgorithmWrapper = AceType::DynamicCast(layoutWrapper->GetLayoutAlgorithm()); ASSERT_NE(layoutAlgorithmWrapper, nullptr); @@ -5026,7 +4931,7 @@ HWTEST_F(ListTestNg, ScrollToIndexAlign001, TestSize.Level1) EXPECT_FALSE(pattern_->jumpIndex_.has_value()); EXPECT_EQ(pattern_->targetIndex_, TOTAL_NUMBER - 1); EXPECT_EQ(pattern_->scrollAlign_, ScrollAlign::AUTO); - layoutWrapper = RunMeasureAndLayout(); + layoutWrapper = RunMeasureAndLayout(frameNode_); ASSERT_NE(layoutWrapper, nullptr); EXPECT_TRUE(pattern_->OnDirtyLayoutWrapperSwap(layoutWrapper, config)); pattern_->scrollAlign_ = ScrollAlign::END; @@ -5191,7 +5096,7 @@ HWTEST_F(ListTestNg, ListLayoutAlgorithm_FixPredictSnapOffset003, TestSize.Level listLayoutAlgorithm->SetTotalOffset(10.0f); listLayoutAlgorithm->SetPredictSnapOffset(10.0f); listLayoutAlgorithm->FixPredictSnapOffset(layoutProperty_); - EXPECT_EQ(listLayoutAlgorithm->GetPredictSnapOffset().value(), 15); + EXPECT_EQ(listLayoutAlgorithm->GetPredictSnapOffset().value(), 10); } /** diff --git a/frameworks/core/components_ng/test/pattern/loading_progress/loading_progress_test_ng.cpp b/frameworks/core/components_ng/test/pattern/loading_progress/loading_progress_test_ng.cpp index a2dc5a33aa9..103fe569eaa 100644 --- a/frameworks/core/components_ng/test/pattern/loading_progress/loading_progress_test_ng.cpp +++ b/frameworks/core/components_ng/test/pattern/loading_progress/loading_progress_test_ng.cpp @@ -98,10 +98,10 @@ HWTEST_F(LoadingProgressTestNg, LoadingProgressLayoutAlgorithm001, TestSize.Leve * contentSize with maxSize LayoutConstraint. */ LayoutConstraintF layoutConstraint; - layoutConstraint.maxSize = SizeF(MAXSIZE_WIDTH, MAXSIZE_HEIGHT); + layoutConstraint.percentReference = SizeF(MAXSIZE_WIDTH, MAXSIZE_HEIGHT); auto size1 = layoutAlgorithm.MeasureContent(layoutConstraint, nullptr); EXPECT_NE(size1, std::nullopt); - EXPECT_EQ(size1.value(), SizeF(MAXSIZE_WIDTH, MAXSIZE_HEIGHT)); + EXPECT_EQ(size1.value(), SizeF(MAXSIZE_WIDTH, MAXSIZE_WIDTH)); /** * @tc.cases: case2. When father selfIdealSize is valid, LoadingProgressLayoutAlgorithm will calculate * contentSize with maxSize LayoutConstraint and selfIdealSize. @@ -110,7 +110,7 @@ HWTEST_F(LoadingProgressTestNg, LoadingProgressLayoutAlgorithm001, TestSize.Leve layoutConstraint.selfIdealSize.height_ = SELFSIZE_HEIGHT; auto size2 = layoutAlgorithm.MeasureContent(layoutConstraint, nullptr); EXPECT_NE(size2, std::nullopt); - EXPECT_EQ(size2.value(), SizeF(fmin(SELFSIZE_WIDTH, MAXSIZE_WIDTH), fmin(SELFSIZE_HEIGHT, MAXSIZE_HEIGHT))); + EXPECT_EQ(size2.value(), SizeF(SELFSIZE_WIDTH, SELFSIZE_WIDTH)); } /** @@ -206,7 +206,10 @@ HWTEST_F(LoadingProgressTestNg, LoadingProgressPatternTest003, TestSize.Level1) ASSERT_NE(paintProperty, nullptr); EXPECT_TRUE(paintProperty->GetEnableLoading().value()); loadingProgressPattern->OnModifyDone(); - PaintWrapper paintWrapper(nullptr, nullptr, paintProperty); + RefPtr geometryNode = AceType::MakeRefPtr(); + geometryNode->SetContentSize(SizeF()); + geometryNode->SetContentOffset(OffsetF()); + PaintWrapper paintWrapper(nullptr, geometryNode, paintProperty); paintMethod->UpdateContentModifier(&paintWrapper); EXPECT_TRUE(loadingProgressPattern->enableLoading_); EXPECT_TRUE(loadingProgressPattern->loadingProgressModifier_->isVisible_); @@ -221,7 +224,7 @@ HWTEST_F(LoadingProgressTestNg, LoadingProgressPatternTest003, TestSize.Level1) loadingProgressPattern->OnModifyDone(); EXPECT_FALSE(paintProperty->GetEnableLoading().value()); EXPECT_FALSE(loadingProgressPattern->enableLoading_); - PaintWrapper paintWrapper2(nullptr, nullptr, paintProperty); + PaintWrapper paintWrapper2(nullptr, geometryNode, paintProperty); paintMethod->UpdateContentModifier(&paintWrapper2); EXPECT_FALSE(loadingProgressPattern->loadingProgressModifier_->isVisible_); EXPECT_FALSE(loadingProgressPattern->loadingProgressModifier_->enableLoading_->Get()); @@ -302,7 +305,10 @@ HWTEST_F(LoadingProgressTestNg, LoadingProgressPaintMethodTest001, TestSize.Leve */ auto renderContext = frameNode->GetRenderContext(); ASSERT_NE(renderContext, nullptr); - PaintWrapper paintWrapper(renderContext, nullptr, nullptr); + RefPtr geometryNode = AceType::MakeRefPtr(); + geometryNode->SetContentSize(SizeF()); + geometryNode->SetContentOffset(OffsetF()); + PaintWrapper paintWrapper(renderContext, geometryNode, nullptr); auto themeManager = AceType::MakeRefPtr(); MockPipelineBase::GetCurrent()->SetThemeManager(themeManager); auto progressTheme = AceType::MakeRefPtr(); @@ -312,7 +318,7 @@ HWTEST_F(LoadingProgressTestNg, LoadingProgressPaintMethodTest001, TestSize.Leve */ auto loadingProgressPaintProperty = loadingProgressPattern->GetPaintProperty(); EXPECT_TRUE(loadingProgressPaintProperty != nullptr); - PaintWrapper paintWrapper1(renderContext, nullptr, loadingProgressPaintProperty); + PaintWrapper paintWrapper1(renderContext, geometryNode, loadingProgressPaintProperty); EXPECT_CALL(*themeManager, GetTheme(_)).WillOnce(Return(progressTheme)); paintMethod->UpdateContentModifier(&paintWrapper1); EXPECT_EQ(paintMethod->color_, COLOR_DEFAULT); @@ -320,7 +326,7 @@ HWTEST_F(LoadingProgressTestNg, LoadingProgressPaintMethodTest001, TestSize.Leve * @tc.cases: case2. renderContext ForegroundColorStrategy and modifier will use foreground color flag */ renderContext->UpdateForegroundColorStrategy(ForegroundColorStrategy()); - PaintWrapper paintWrapper3(renderContext, nullptr, loadingProgressPaintProperty); + PaintWrapper paintWrapper3(renderContext, geometryNode, loadingProgressPaintProperty); EXPECT_CALL(*themeManager, GetTheme(_)).WillOnce(Return(progressTheme)); paintMethod->UpdateContentModifier(&paintWrapper3); EXPECT_EQ(paintMethod->color_, Color::FOREGROUND); diff --git a/frameworks/core/components_ng/test/pattern/navigation/BUILD.gn b/frameworks/core/components_ng/test/pattern/navigation/BUILD.gn index ff1d07dfe60..755521ed26c 100755 --- a/frameworks/core/components_ng/test/pattern/navigation/BUILD.gn +++ b/frameworks/core/components_ng/test/pattern/navigation/BUILD.gn @@ -87,6 +87,7 @@ ohos_unittest("navigation_test_ng") { "$ace_root/frameworks/core/components_ng/layout/layout_property.cpp", "$ace_root/frameworks/core/components_ng/layout/layout_wrapper.cpp", "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_builder.cpp", + "$ace_root/frameworks/core/components_ng/manager/safe_area/safe_area_manager.cpp", "$ace_root/frameworks/core/components_ng/manager/select_overlay/select_overlay_manager.cpp", "$ace_root/frameworks/core/components_ng/manager/select_overlay/select_overlay_proxy.cpp", "$ace_root/frameworks/core/components_ng/pattern/bubble/bubble_layout_algorithm.cpp", @@ -177,6 +178,7 @@ ohos_unittest("navigation_test_ng") { "$ace_root/frameworks/core/components_ng/test/pattern/text/mock/mock_txt_paragraph.cpp", "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_element_register.cpp", "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_pipeline_base.cpp", + "$ace_root/test/mock/core/common/mock_ace_engine.cpp", "$ace_root/test/mock/core/common/mock_container.cpp", "$ace_root/test/mock/core/common/mock_font_manager_ng.cpp", "$ace_root/test/mock/frameworks/base/log/mock_jank_frame_report.cpp", diff --git a/frameworks/core/components_ng/test/pattern/overlay/overlay_manager_test_ng.cpp b/frameworks/core/components_ng/test/pattern/overlay/overlay_manager_test_ng.cpp index 35f2aa790a6..5a3a1243040 100644 --- a/frameworks/core/components_ng/test/pattern/overlay/overlay_manager_test_ng.cpp +++ b/frameworks/core/components_ng/test/pattern/overlay/overlay_manager_test_ng.cpp @@ -528,7 +528,7 @@ HWTEST_F(OverlayManagerTestNg, BindSheet003, TestSize.Level1) overlayManager->BindSheet(isShow, nullptr, std::move(builderFunc), sheetStyle, nullptr, nullptr, targetId); EXPECT_FALSE(overlayManager->modalStack_.empty()); auto sheetNode = overlayManager->modalStack_.top().Upgrade(); - EXPECT_EQ(sheetNode->GetTag(), "SheetPage"); + EXPECT_EQ(sheetNode->GetTag(), V2::SHEET_PAGE_TAG); /** * @tc.steps: step4. destroy modal page. diff --git a/frameworks/core/components_ng/test/pattern/picker/datepicker_test_ng.cpp b/frameworks/core/components_ng/test/pattern/picker/datepicker_test_ng.cpp index 5d1107c1119..ffc4875c138 100644 --- a/frameworks/core/components_ng/test/pattern/picker/datepicker_test_ng.cpp +++ b/frameworks/core/components_ng/test/pattern/picker/datepicker_test_ng.cpp @@ -66,6 +66,9 @@ const double YOFFSET_START2 = 2000.0; const double YOFFSET_END2 = 3000.0; const double TIME_PLUS = 1 * 100.0; const double TIME_PLUS_LARGE = 10 * 1000.0; +const SizeF TEST_FRAME_SIZE1 { 20, 50 }; +const SizeF TEST_FRAME_SIZE2 { 0, 0 }; +const std::string SELECTED_DATE_STRING = "{\"year\":2000,\"month\":5,\"day\":6,\"hour\":1,\"minute\":1,\"status\":-1}"; } // namespace class DatePickerTestNg : public testing::Test { @@ -385,105 +388,6 @@ HWTEST_F(DatePickerTestNg, DatePickerModelNGSetSelectedTextStyle003, TestSize.Le * @tc.type: FUNC */ HWTEST_F(DatePickerTestNg, DatePickerDialogViewShow001, TestSize.Level1) -{ - DatePickerSettingData settingData; - settingData.properties.disappearTextStyle_.textColor = Color::RED; - settingData.properties.disappearTextStyle_.fontSize = Dimension(0); - settingData.properties.disappearTextStyle_.fontWeight = Ace::FontWeight::BOLD; - - settingData.properties.normalTextStyle_.textColor = Color::RED; - settingData.properties.normalTextStyle_.fontSize = Dimension(0); - settingData.properties.normalTextStyle_.fontWeight = Ace::FontWeight::BOLD; - - settingData.properties.selectedTextStyle_.textColor = Color::RED; - settingData.properties.selectedTextStyle_.fontSize = Dimension(0); - settingData.properties.normalTextStyle_.fontWeight = Ace::FontWeight::BOLD; - settingData.datePickerProperty["start"] = PickerDate(START_YEAR_BEFORE, 1, 1); - settingData.datePickerProperty["end"] = PickerDate(END_YEAR, 1, 1); - settingData.datePickerProperty["selected"] = PickerDate(SELECTED_YEAR, 1, 1); - settingData.timePickerProperty["selected"] = PickerTime(1, 1, 1); - settingData.isLunar = false; - settingData.showTime = true; - settingData.useMilitary = false; - - DialogProperties dialogProperties; - - std::map dialogEvent; - auto eventFunc = [](const std::string& info) { (void)info; }; - dialogEvent["changeId"] = eventFunc; - dialogEvent["acceptId"] = eventFunc; - auto cancelFunc = [](const GestureEvent& info) { (void)info; }; - std::map dialogCancelEvent; - dialogCancelEvent["cancelId"] = cancelFunc; - - auto dialogNode = DatePickerDialogView::Show(dialogProperties, settingData, dialogEvent, dialogCancelEvent); - EXPECT_NE(dialogNode, nullptr); -} - -/** - * @tc.name: DatePickerDialogViewShow002 - * @tc.desc: Test DatePickerDialogView Show. - * @tc.type: FUNC - */ -HWTEST_F(DatePickerTestNg, DatePickerDialogViewShow002, TestSize.Level1) -{ - DatePickerSettingData settingData; - settingData.properties.disappearTextStyle_.textColor = Color::RED; - settingData.properties.disappearTextStyle_.fontSize = Dimension(TEST_FONT_SIZE); - settingData.properties.disappearTextStyle_.fontWeight = Ace::FontWeight::BOLD; - - settingData.properties.normalTextStyle_.textColor = Color::RED; - settingData.properties.normalTextStyle_.fontSize = Dimension(TEST_FONT_SIZE); - settingData.properties.normalTextStyle_.fontWeight = Ace::FontWeight::BOLD; - - settingData.properties.selectedTextStyle_.textColor = Color::RED; - settingData.properties.selectedTextStyle_.fontSize = Dimension(TEST_FONT_SIZE); - settingData.properties.normalTextStyle_.fontWeight = Ace::FontWeight::BOLD; - settingData.datePickerProperty["start"] = PickerDate(START_YEAR_BEFORE, 1, 1); - settingData.datePickerProperty["end"] = PickerDate(START_YEAR_BEFORE, CURRENT_DAY, 1); - settingData.datePickerProperty["selected"] = PickerDate(SELECTED_YEAR, 1, 1); - settingData.timePickerProperty["selected"] = PickerTime(1, 1, 1); - settingData.isLunar = true; - settingData.showTime = true; - settingData.useMilitary = false; - - DialogProperties dialogProperties; - - std::map dialogEvent; - auto eventFunc = [](const std::string& info) { (void)info; }; - dialogEvent["changeId"] = eventFunc; - dialogEvent["acceptId"] = eventFunc; - auto cancelFunc = [](const GestureEvent& info) { (void)info; }; - std::map dialogCancelEvent; - dialogCancelEvent["cancelId"] = cancelFunc; - - auto dialogNode = DatePickerDialogView::Show(dialogProperties, settingData, dialogEvent, dialogCancelEvent); - - ASSERT_NE(dialogNode, nullptr); - auto titleNode = AceType::DynamicCast(dialogNode->GetFirstChild()->GetFirstChild()); - ASSERT_NE(titleNode, nullptr); - DatePickerDialogView::HandleMouseEvent(titleNode, true); - auto renderContext = titleNode->GetRenderContext(); - EXPECT_EQ(renderContext->GetBackgroundColorValue(), Color::BLACK); - DatePickerDialogView::HandleMouseEvent(titleNode, false); - renderContext = titleNode->GetRenderContext(); - EXPECT_EQ(renderContext->GetBackgroundColorValue(), Color::TRANSPARENT); - auto titleEventHub = titleNode->GetOrCreateGestureEventHub(); - titleEventHub->ActClick(); - titleEventHub->ActClick(); - titleEventHub->ActClick(); - auto pipeline = PipelineContext::GetCurrentContext(); - auto overlayManger = pipeline->GetOverlayManager(); - overlayManger->FireBackPressEvent(); - overlayManger->FireBackPressEvent(); -} - -/** - * @tc.name: DatePickerDialogViewShow003 - * @tc.desc: Test DatePickerDialogView Show. - * @tc.type: FUNC - */ -HWTEST_F(DatePickerTestNg, DatePickerDialogViewShow003, TestSize.Level1) { DatePickerSettingData settingData; settingData.isLunar = true; @@ -515,11 +419,11 @@ HWTEST_F(DatePickerTestNg, DatePickerDialogViewShow003, TestSize.Level1) } /** - * @tc.name: DatePickerDialogViewShow004 + * @tc.name: DatePickerDialogViewShow002 * @tc.desc: Test DatePickerDialogView Show. * @tc.type: FUNC */ -HWTEST_F(DatePickerTestNg, DatePickerDialogViewShow004, TestSize.Level1) +HWTEST_F(DatePickerTestNg, DatePickerDialogViewShow002, TestSize.Level1) { DatePickerSettingData settingData; settingData.properties.disappearTextStyle_.textColor = Color::RED; @@ -562,6 +466,98 @@ HWTEST_F(DatePickerTestNg, DatePickerDialogViewShow004, TestSize.Level1) columnPattern->UpdateToss(PATTERN_OFFSET); } +/** + * @tc.name: DatePickerDialogViewShow003 + * @tc.desc: Test DatePickerDialogView Show. + * @tc.type: FUNC + */ +HWTEST_F(DatePickerTestNg, DatePickerDialogViewShow003, TestSize.Level1) +{ + DatePickerSettingData settingData; + settingData.properties.disappearTextStyle_.textColor = Color::RED; + settingData.properties.disappearTextStyle_.fontSize = Dimension(0); + settingData.properties.disappearTextStyle_.fontWeight = Ace::FontWeight::BOLD; + + settingData.properties.normalTextStyle_.textColor = Color::RED; + settingData.properties.normalTextStyle_.fontSize = Dimension(0); + settingData.properties.normalTextStyle_.fontWeight = Ace::FontWeight::BOLD; + + settingData.properties.selectedTextStyle_.textColor = Color::RED; + settingData.properties.selectedTextStyle_.fontSize = Dimension(0); + settingData.properties.normalTextStyle_.fontWeight = Ace::FontWeight::BOLD; + settingData.datePickerProperty["start"] = PickerDate(START_YEAR_BEFORE, 1, 1); + settingData.datePickerProperty["end"] = PickerDate(END_YEAR, 1, 1); + settingData.datePickerProperty["selected"] = PickerDate(SELECTED_YEAR, 1, 1); + settingData.timePickerProperty["selected"] = PickerTime(1, 1, 1); + settingData.isLunar = false; + settingData.showTime = true; + settingData.useMilitary = false; + + DialogProperties dialogProperties; + + std::map dialogEvent; + auto eventFunc = [](const std::string& info) { (void)info; }; + dialogEvent["changeId"] = eventFunc; + dialogEvent["acceptId"] = eventFunc; + auto cancelFunc = [](const GestureEvent& info) { (void)info; }; + std::map dialogCancelEvent; + dialogCancelEvent["cancelId"] = cancelFunc; + + auto dialogNode = DatePickerDialogView::Show(dialogProperties, settingData, dialogEvent, dialogCancelEvent); + EXPECT_NE(dialogNode, nullptr); +} + +/** + * @tc.name: DatePickerDialogViewShow004 + * @tc.desc: Test DatePickerDialogView Show. + * @tc.type: FUNC + */ +HWTEST_F(DatePickerTestNg, DatePickerDialogViewShow004, TestSize.Level1) +{ + DatePickerSettingData settingData; + settingData.properties.disappearTextStyle_.textColor = Color::RED; + settingData.properties.disappearTextStyle_.fontSize = Dimension(TEST_FONT_SIZE); + settingData.properties.disappearTextStyle_.fontWeight = Ace::FontWeight::BOLD; + + settingData.properties.normalTextStyle_.textColor = Color::RED; + settingData.properties.normalTextStyle_.fontSize = Dimension(TEST_FONT_SIZE); + settingData.properties.normalTextStyle_.fontWeight = Ace::FontWeight::BOLD; + + settingData.properties.selectedTextStyle_.textColor = Color::RED; + settingData.properties.selectedTextStyle_.fontSize = Dimension(TEST_FONT_SIZE); + settingData.properties.normalTextStyle_.fontWeight = Ace::FontWeight::BOLD; + settingData.datePickerProperty["start"] = PickerDate(START_YEAR_BEFORE, 1, 1); + settingData.datePickerProperty["end"] = PickerDate(START_YEAR_BEFORE, CURRENT_DAY, 1); + settingData.datePickerProperty["selected"] = PickerDate(SELECTED_YEAR, 1, 1); + settingData.timePickerProperty["selected"] = PickerTime(1, 1, 1); + settingData.isLunar = true; + settingData.showTime = true; + settingData.useMilitary = false; + + DialogProperties dialogProperties; + + std::map dialogEvent; + auto eventFunc = [](const std::string& info) { (void)info; }; + dialogEvent["changeId"] = eventFunc; + dialogEvent["acceptId"] = eventFunc; + auto cancelFunc = [](const GestureEvent& info) { (void)info; }; + std::map dialogCancelEvent; + dialogCancelEvent["cancelId"] = cancelFunc; + + auto dialogNode = DatePickerDialogView::Show(dialogProperties, settingData, dialogEvent, dialogCancelEvent); + + ASSERT_NE(dialogNode, nullptr); + auto titleNode = AceType::DynamicCast(dialogNode->GetFirstChild()->GetFirstChild()); + auto titleEventHub = titleNode->GetOrCreateGestureEventHub(); + titleEventHub->ActClick(); + titleEventHub->ActClick(); + titleEventHub->ActClick(); + auto pipeline = PipelineContext::GetCurrentContext(); + auto overlayManger = pipeline->GetOverlayManager(); + overlayManger->FireBackPressEvent(); + overlayManger->FireBackPressEvent(); +} + /** * @tc.name: DatePickerDialogViewShow005 * @tc.desc: Test DatePickerDialogView Show. @@ -1346,6 +1342,7 @@ HWTEST_F(DatePickerTestNg, DatePickerAlgorithmTest001, TestSize.Level1) * @tc.step: step1. create frameNode and pattern. */ auto theme = MockPipelineBase::GetCurrent()->GetTheme(); + theme->showOptionCount_ = 2; DatePickerModelNG::GetInstance()->CreateDatePicker(theme); auto frameNode = AceType::DynamicCast(ViewStackProcessor::GetInstance()->Finish()); ASSERT_NE(frameNode, nullptr); @@ -1365,20 +1362,29 @@ HWTEST_F(DatePickerTestNg, DatePickerAlgorithmTest001, TestSize.Level1) layoutWrapper.AppendChild(std::move(subLayoutWrapper)); layoutWrapper.AppendChild(std::move(subTwoLayoutWrapper)); EXPECT_EQ(layoutWrapper.GetTotalChildCount(), 2); - auto contentConstraint = layoutWrapper.GetLayoutProperty()->CreateContentConstraint(); auto layoutConstraint = layoutWrapper.GetLayoutProperty()->CreateChildConstraint(); - layoutWrapper.GetLayoutProperty()->contentConstraint_ = contentConstraint; - layoutWrapper.GetLayoutProperty()->layoutConstraint_ = layoutConstraint; + layoutConstraint.selfIdealSize.SetWidth(20); + layoutWrapper.GetLayoutProperty()->UpdateLayoutConstraint(layoutConstraint); + layoutWrapper.GetLayoutProperty()->UpdateContentConstraint(); /** * @tc.step: step2. initialize DatePickerColumnLayoutAlgorithm and call Measure function. */ DatePickerColumnLayoutAlgorithm datePickerColumnLayoutAlgorithm; + for (int32_t i = 0; i < layoutWrapper.GetTotalChildCount(); i++) { + datePickerColumnLayoutAlgorithm.currentOffset_.emplace_back(0.0f); + } datePickerColumnLayoutAlgorithm.Measure(&layoutWrapper); + /** * test branch width.has_value() */ layoutConstraint.parentIdealSize = OptionalSize(300.0f, 200.0f); + for (int32_t i = 0; i < layoutWrapper.GetTotalChildCount(); i++) { + datePickerColumnLayoutAlgorithm.currentOffset_.emplace_back(0.0f); + } datePickerColumnLayoutAlgorithm.Measure(&layoutWrapper); + auto frameSize = layoutWrapper.geometryNode_->GetFrameSize(); + EXPECT_EQ(frameSize, TEST_FRAME_SIZE1); } /** @@ -1413,7 +1419,12 @@ HWTEST_F(DatePickerTestNg, DatePickerAlgorithmTest002, TestSize.Level1) layoutWrapper.AppendChild(std::move(subLayoutWrapper)); EXPECT_EQ(layoutWrapper.GetTotalChildCount(), 1); DatePickerColumnLayoutAlgorithm datePickerColumnLayoutAlgorithm; + for (int32_t i = 0; i < layoutWrapper.GetTotalChildCount(); i++) { + datePickerColumnLayoutAlgorithm.currentOffset_.emplace_back(0.0f); + } datePickerColumnLayoutAlgorithm.Layout(&layoutWrapper); + auto frameSize = layoutWrapper.geometryNode_->GetFrameSize(); + EXPECT_EQ(frameSize, TEST_FRAME_SIZE2); } /** @@ -1800,19 +1811,6 @@ HWTEST_F(DatePickerTestNg, DatePickerColumnPatternTest004, TestSize.Level1) EXPECT_EQ(columnPattern->yOffset_, 0.0); EXPECT_EQ(columnPattern->yLast_, 0.0); EXPECT_EQ(columnPattern->scrollDelta_, 0.0); - - columnPattern->scrollDelta_ = TOSS_DELTA; - columnPattern->animationCreated_ = true; - panEvent->actionEnd_(gestureEvent); - - columnPattern->pressed_ = true; - columnPattern->yOffset_ = OFFSET_Y; - columnPattern->yLast_ = OFFSET_Y; - gestureEvent.SetInputEventType(InputEventType::AXIS); - panEvent->actionEnd_(gestureEvent); - EXPECT_EQ(columnPattern->yOffset_, OFFSET_Y); - EXPECT_EQ(columnPattern->yLast_, OFFSET_Y); - EXPECT_TRUE(columnPattern->pressed_); } /** @@ -1856,30 +1854,29 @@ HWTEST_F(DatePickerTestNg, DatePickerColumnPatternTest005, TestSize.Level1) HWTEST_F(DatePickerTestNg, DatePickerColumnPatternTest006, TestSize.Level1) { /** - * @tc.step: step1. create datepicker framenode and columnpattern. + * @tc.steps: step1. Create datepicker framenode and columnpattern. */ auto theme = MockPipelineBase::GetCurrent()->GetTheme(); + ASSERT_NE(theme, nullptr); DatePickerModelNG::GetInstance()->CreateDatePicker(theme); auto pickerFrameNode = AceType::DynamicCast(ViewStackProcessor::GetInstance()->Finish()); ASSERT_NE(pickerFrameNode, nullptr); pickerFrameNode->MarkModifyDone(); - auto columnNode = AceType::DynamicCast(pickerFrameNode->GetFirstChild()->GetChildAtIndex(1)); + auto firstChild = AceType::DynamicCast(pickerFrameNode->GetFirstChild()); + ASSERT_NE(firstChild, nullptr); + auto columnNode = AceType::DynamicCast(firstChild->GetChildAtIndex(1)); ASSERT_NE(columnNode, nullptr); - auto columnPattern = columnNode->GetPattern(); ASSERT_NE(columnPattern, nullptr); - columnPattern->OnAttachToFrameNode(); - EXPECT_TRUE(columnPattern->animationCreated_); - auto options = columnPattern->GetOptions(); + columnPattern->SetAccessibilityAction(); options[columnNode].clear(); - for (auto& Value : DEFAULT_VALUE) { - options[columnNode].emplace_back(std::to_string(Value)); - } columnPattern->SetOptions(options); columnPattern->SetCurrentIndex(1); EXPECT_EQ(columnPattern->GetCurrentIndex(), 1); + columnPattern->OnAttachToFrameNode(); + EXPECT_TRUE(columnPattern->animationCreated_); auto accessibilityProperty = columnNode->GetAccessibilityProperty(); ASSERT_NE(accessibilityProperty, nullptr); /** @@ -1897,30 +1894,28 @@ HWTEST_F(DatePickerTestNg, DatePickerColumnPatternTest006, TestSize.Level1) HWTEST_F(DatePickerTestNg, DatePickerColumnPatternTest007, TestSize.Level1) { /** - * @tc.step: step1. create datepicker framenode and columnpattern. + * @tc.steps: step1. Create datepicker framenode and columnpattern. */ auto theme = MockPipelineBase::GetCurrent()->GetTheme(); + ASSERT_NE(theme, nullptr); DatePickerModelNG::GetInstance()->CreateDatePicker(theme); auto pickerFrameNode = AceType::DynamicCast(ViewStackProcessor::GetInstance()->Finish()); ASSERT_NE(pickerFrameNode, nullptr); pickerFrameNode->MarkModifyDone(); - auto columnNode = AceType::DynamicCast(pickerFrameNode->GetFirstChild()->GetChildAtIndex(1)); + auto firstChild = AceType::DynamicCast(pickerFrameNode->GetFirstChild()); + ASSERT_NE(firstChild, nullptr); + auto columnNode = AceType::DynamicCast(firstChild->GetChildAtIndex(1)); ASSERT_NE(columnNode, nullptr); - auto columnPattern = columnNode->GetPattern(); ASSERT_NE(columnPattern, nullptr); - columnPattern->OnAttachToFrameNode(); - EXPECT_TRUE(columnPattern->animationCreated_); - auto options = columnPattern->GetOptions(); + columnPattern->SetAccessibilityAction(); options[columnNode].clear(); - for (auto& Value : DEFAULT_VALUE) { - options[columnNode].emplace_back(std::to_string(Value)); - } columnPattern->SetOptions(options); columnPattern->SetCurrentIndex(1); EXPECT_EQ(columnPattern->GetCurrentIndex(), 1); - + columnPattern->OnAttachToFrameNode(); + EXPECT_TRUE(columnPattern->animationCreated_); auto accessibilityProperty = columnNode->GetAccessibilityProperty(); ASSERT_NE(accessibilityProperty, nullptr); /** @@ -2354,19 +2349,19 @@ HWTEST_F(DatePickerTestNg, PerformActionTest001, TestSize.Level1) * accessibilityProperty. * @tc.expected: Related function is called. */ - options = columnPattern->GetOptions(); options[columnNode].clear(); for (auto& Value : DEFAULT_VALUE) { options[columnNode].emplace_back(std::to_string(Value)); } + options = columnPattern->GetOptions(); columnPattern->SetOptions(options); columnPattern->SetCurrentIndex(1); EXPECT_TRUE(accessibilityProperty->ActActionScrollForward()); - options = columnPattern->GetOptions(); options[columnNode].clear(); for (auto& Value : DEFAULT_VALUE) { options[columnNode].emplace_back(std::to_string(Value)); } + options = columnPattern->GetOptions(); columnPattern->SetOptions(options); columnPattern->SetCurrentIndex(1); EXPECT_TRUE(accessibilityProperty->ActActionScrollBackward()); @@ -2457,10 +2452,6 @@ HWTEST_F(DatePickerTestNg, TossAnimationControllerTest001, TestSize.Level1) EXPECT_TRUE(ret); auto column = AceType::MakeRefPtr(); toss->SetColumn(column); - /** - * cover StopCallback callback - */ - toss->toss_->controller_->NotifyStopListener(); } /** @@ -2494,10 +2485,6 @@ HWTEST_F(DatePickerTestNg, TossAnimationControllerTest002, TestSize.Level1) EXPECT_TRUE(ret); auto column = AceType::MakeRefPtr(); toss->SetColumn(column); - /** - * cover PickerAnimation callback - */ - toss->toss_->callback_(0.5); } /** @@ -2550,4 +2537,48 @@ HWTEST_F(DatePickerTestNg, TossAnimationControllerTest005, TestSize.Level1) EXPECT_EQ(toss->yEnd_, YOFFSET_END1); EXPECT_FALSE(ret); } + +/** + * @tc.name: DatePickerDialogViewShow011 + * @tc.desc: Test GetSelectedObject. + * @tc.type: FUNC + */ +HWTEST_F(DatePickerTestNg, DatePickerDialogViewShow011, TestSize.Level1) +{ + /** + * @tc.steps: step1. Set DatePickerSettingData with showtime. + */ + DatePickerSettingData settingData; + settingData.datePickerProperty["start"] = PickerDate(START_YEAR_BEFORE, 1, 1); + settingData.datePickerProperty["end"] = PickerDate(END_YEAR, 1, 1); + settingData.datePickerProperty["selected"] = PickerDate(SELECTED_YEAR, CURRENT_DAY, CURRENT_DAY); + settingData.timePickerProperty["selected"] = PickerTime(1, 1, 1); + settingData.isLunar = false; + settingData.showTime = true; + /** + * @tc.steps: step2. Set DialogProperties. + */ + DialogProperties dialogProperties; + std::map dialogEvent; + auto eventFunc = [](const std::string& info) { (void)info; }; + dialogEvent["changeId"] = eventFunc; + dialogEvent["acceptId"] = eventFunc; + auto cancelFunc = [](const GestureEvent& info) { (void)info; }; + std::map dialogCancelEvent; + dialogCancelEvent["cancelId"] = cancelFunc; + /** + * @tc.step: step3. call DatePickerDialogView::Show and find DatePickerPattern call GetSelectedObject. + * @tc.expected: selectedDate same as setting. + */ + auto dialogNode = DatePickerDialogView::Show(dialogProperties, settingData, dialogEvent, dialogCancelEvent); + ASSERT_NE(dialogNode, nullptr); + auto midStackNode = AceType::DynamicCast(dialogNode->GetFirstChild()->GetChildAtIndex(1)); + auto dateNode = AceType::DynamicCast(midStackNode->GetLastChild()->GetFirstChild()); + auto pickerPattern = dateNode->GetPattern(); + ASSERT_NE(pickerPattern, nullptr); + pickerPattern->SetShowTimeFlag(true); + pickerPattern->SetShowMonthDaysFlag(true); + auto selectedDate = pickerPattern->GetSelectedObject(true); + EXPECT_EQ(selectedDate, SELECTED_DATE_STRING); +} } // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/test/pattern/plugin/mock/mock_plugin_frontend.cpp b/frameworks/core/components_ng/test/pattern/plugin/mock/mock_plugin_frontend.cpp index 81442d798e3..179c54fd7ab 100644 --- a/frameworks/core/components_ng/test/pattern/plugin/mock/mock_plugin_frontend.cpp +++ b/frameworks/core/components_ng/test/pattern/plugin/mock/mock_plugin_frontend.cpp @@ -22,6 +22,8 @@ void PluginFrontend::Destroy() {} bool PluginFrontend::Initialize(FrontendType type, const RefPtr& taskExecutor) { + type_ = type; + taskExecutor_ = taskExecutor; return true; } diff --git a/frameworks/core/components_ng/test/pattern/refresh/BUILD.gn b/frameworks/core/components_ng/test/pattern/refresh/BUILD.gn index 9e55d854d01..bdca14589a4 100644 --- a/frameworks/core/components_ng/test/pattern/refresh/BUILD.gn +++ b/frameworks/core/components_ng/test/pattern/refresh/BUILD.gn @@ -19,6 +19,7 @@ ace_unittest("refresh_test_ng") { sources = [ "$ace_root/frameworks/core/components_ng/pattern/flex/flex_layout_algorithm.cpp", "$ace_root/frameworks/core/components_ng/pattern/grid_container/grid_container_layout_property.cpp", + "$ace_root/frameworks/core/components_ng/test/pattern/test_ng.cpp", # animation "$ace_root/frameworks/core/animation/anticipate_curve.cpp", diff --git a/frameworks/core/components_ng/test/pattern/refresh/refresh_test_ng.cpp b/frameworks/core/components_ng/test/pattern/refresh/refresh_test_ng.cpp index 2a29c0390f0..a7eb87ea75b 100644 --- a/frameworks/core/components_ng/test/pattern/refresh/refresh_test_ng.cpp +++ b/frameworks/core/components_ng/test/pattern/refresh/refresh_test_ng.cpp @@ -31,6 +31,7 @@ #include "core/components_ng/pattern/refresh/refresh_pattern.h" #include "core/components_v2/inspector/inspector_constants.h" #include "core/pipeline_ng/test/mock/mock_pipeline_base.h" +#include "core/components_ng/test/pattern/test_ng.h" #include "frameworks/core/components_ng/pattern/loading_progress/loading_progress_paint_property.h" #include "frameworks/core/components_ng/pattern/loading_progress/loading_progress_pattern.h" #include "frameworks/core/components_ng/pattern/text/text_pattern.h" @@ -40,31 +41,17 @@ using namespace testing::ext; namespace OHOS::Ace::NG { namespace { -constexpr float CONTAINER_WIDTH = 300.0f; -constexpr float CONTAINER_HEIGHT = 300.0f; -const SizeF CONTAINER_SIZE(CONTAINER_WIDTH, CONTAINER_HEIGHT); - -constexpr float IDEAL_WIDTH = 300.0f; -constexpr float IDEAL_HEIGHT = 300.0f; -const SizeF IDEAL_SIZE(IDEAL_WIDTH, IDEAL_HEIGHT); - -constexpr float MAX_WIDTH = 400.0f; -constexpr float MAX_HEIGHT = 400.0f; -const SizeF MAX_SIZE(MAX_WIDTH, MAX_HEIGHT); - constexpr float CUSTOM_NODE_WIDTH = 100.f; constexpr float CUSTOM_NODE_HEIGHT = 10.f; } // namespace -class RefreshTestNg : public testing::Test { +class RefreshTestNg : public testing::Test, public TestNG { public: static void SetUpTestCase(); static void TearDownTestCase(); void SetUp() override; void TearDown() override; void GetInstance(); - void RunMeasureAndLayout(); void CreateRefreshNodeAndInitParam(); - RefPtr GetChildFrameNode(int32_t index); RefPtr CreateCustomNode(); RefPtr frameNode_; @@ -108,21 +95,6 @@ void RefreshTestNg::GetInstance() accessibilityProperty_ = frameNode_->GetAccessibilityProperty(); } -void RefreshTestNg::RunMeasureAndLayout() -{ - RefPtr layoutWrapper = frameNode_->CreateLayoutWrapper(false, false); - layoutWrapper->SetActive(); - layoutWrapper->SetRootMeasureNode(); - LayoutConstraintF LayoutConstraint; - LayoutConstraint.parentIdealSize = { CONTAINER_WIDTH, CONTAINER_HEIGHT }; - LayoutConstraint.percentReference = { CONTAINER_WIDTH, CONTAINER_HEIGHT }; - LayoutConstraint.selfIdealSize = { CONTAINER_WIDTH, CONTAINER_HEIGHT }; - LayoutConstraint.maxSize = { CONTAINER_WIDTH, CONTAINER_HEIGHT }; - layoutWrapper->Measure(LayoutConstraint); - layoutWrapper->Layout(); - layoutWrapper->MountToHostOnMainThread(); -} - void RefreshTestNg::CreateRefreshNodeAndInitParam() { RefreshModelNG modelNG; @@ -140,12 +112,6 @@ void RefreshTestNg::CreateRefreshNodeAndInitParam() modelNG.SetTextStyle(TextStyle()); } -RefPtr RefreshTestNg::GetChildFrameNode(int32_t index) -{ - auto child = frameNode_->GetChildAtIndex(index); - return AceType::DynamicCast(child); -} - RefPtr RefreshTestNg::CreateCustomNode() { auto frameNode = AceType::MakeRefPtr("test", 0, AceType::MakeRefPtr()); @@ -175,7 +141,7 @@ HWTEST_F(RefreshTestNg, Drag001, TestSize.Level1) modelNG.SetOnStateChange(std::move(onStateChangeEvent)); modelNG.SetOnRefreshing(std::move(onRefreshingEvent)); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. HandleDrag to refresh, and set IsRefreshing to false by front end @@ -244,7 +210,7 @@ HWTEST_F(RefreshTestNg, Drag002, TestSize.Level1) modelNG.SetTextStyle(TextStyle()); modelNG.Pop(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. HandleDrag to refresh, and set IsRefreshing to false by front end @@ -311,7 +277,7 @@ HWTEST_F(RefreshTestNg, Drag003, TestSize.Level1) modelNG.SetTextStyle(TextStyle()); modelNG.Pop(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); pattern_->HandleDragStart(); @@ -359,11 +325,11 @@ HWTEST_F(RefreshTestNg, Pattern001, TestSize.Level1) * @tc.expected: would not replace node */ pattern_->AddCustomBuilderNode(builder_1); - EXPECT_EQ(GetChildFrameNode(0), builder_1); + EXPECT_EQ(GetChildFrameNode(frameNode_, 0), builder_1); auto builder_2 = AceType::MakeRefPtr("test", -1, AceType::MakeRefPtr()); pattern_->AddCustomBuilderNode(builder_2); - EXPECT_EQ(GetChildFrameNode(0), builder_2); + EXPECT_EQ(GetChildFrameNode(frameNode_, 0), builder_2); } /** @@ -380,7 +346,7 @@ HWTEST_F(RefreshTestNg, AttrRefreshing001, TestSize.Level1) modelNG.SetTextStyle(TextStyle()); modelNG.Pop(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. IsRefreshing: true -> false @@ -411,7 +377,7 @@ HWTEST_F(RefreshTestNg, AttrRefreshing002, TestSize.Level1) modelNG.SetTextStyle(TextStyle()); modelNG.Pop(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. IsRefreshing: true -> false @@ -517,7 +483,7 @@ HWTEST_F(RefreshTestNg, RefreshAccessibility001, TestSize.Level1) RefreshModelNG modelNG; modelNG.Create(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. When IsScrollable() == true @@ -558,7 +524,7 @@ HWTEST_F(RefreshTestNg, PerformActionTest001, TestSize.Level1) RefreshModelNG refreshModelNG; refreshModelNG.Create(); GetInstance(); - RunMeasureAndLayout(); // trigger SetAccessibilityAction() + RunMeasureAndLayout(frameNode_); // trigger SetAccessibilityAction() /** * @tc.steps: step1. pattern->IsRefreshing() == false diff --git a/frameworks/core/components_ng/test/pattern/scroll/BUILD.gn b/frameworks/core/components_ng/test/pattern/scroll/BUILD.gn index a094c75f3ab..52068ad1186 100644 --- a/frameworks/core/components_ng/test/pattern/scroll/BUILD.gn +++ b/frameworks/core/components_ng/test/pattern/scroll/BUILD.gn @@ -51,6 +51,7 @@ ohos_unittest("scroll_test_ng") { "$ace_root/frameworks/core/components_ng/test/event/scrollable_event/mock_scrollable.cpp", "$ace_root/frameworks/core/components_ng/test/mock/manager/drag_drop/mock_drag_drop_manager.cpp", "$ace_root/frameworks/core/components_ng/test/mock/manager/drag_drop/mock_drag_drop_proxy.cpp", + "$ace_root/frameworks/core/components_ng/test/pattern/test_ng.cpp", "$ace_root/frameworks/core/components_v2/grid/grid_event.cpp", "$ace_root/frameworks/core/gestures/velocity_tracker.cpp", "$ace_root/frameworks/core/pipeline/base/related_node.cpp", diff --git a/frameworks/core/components_ng/test/pattern/scroll/scroll_test_ng.cpp b/frameworks/core/components_ng/test/pattern/scroll/scroll_test_ng.cpp index 7dd3f07e213..f1e2df4428c 100644 --- a/frameworks/core/components_ng/test/pattern/scroll/scroll_test_ng.cpp +++ b/frameworks/core/components_ng/test/pattern/scroll/scroll_test_ng.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -42,6 +42,7 @@ #include "core/components_ng/pattern/scroll/scroll_spring_effect.h" #include "core/components_ng/test/mock/rosen/mock_canvas.h" #include "core/components_ng/test/mock/theme/mock_theme_manager.h" +#include "core/components_ng/test/pattern/test_ng.h" #include "core/components_v2/inspector/inspector_constants.h" #include "core/pipeline/base/constants.h" #include "core/pipeline_ng/test/mock/mock_pipeline_base.h" @@ -51,29 +52,25 @@ using namespace testing::ext; namespace OHOS::Ace::NG { namespace { -constexpr float ROOT_WIDTH = 720.0f; -constexpr float ROOT_HEIGHT = 1136.0f; -constexpr Dimension FILL_LENGTH = Dimension(1.0, DimensionUnit::PERCENT); constexpr int32_t VIEWPORT_CHILD_NUMBER = 10; -constexpr float COLUMN_CHILD_WIDTH = ROOT_WIDTH / VIEWPORT_CHILD_NUMBER; -constexpr float COLUMN_CHILD_HEIGHT = ROOT_HEIGHT / VIEWPORT_CHILD_NUMBER; constexpr int32_t CHILD_NUMBER = 12; -constexpr float COLUMN_WIDTH = COLUMN_CHILD_WIDTH * CHILD_NUMBER; -constexpr float COLUMN_HEIGHT = COLUMN_CHILD_HEIGHT * CHILD_NUMBER; +constexpr float CONTENT_CHILD_WIDTH = DEVICE_WIDTH / VIEWPORT_CHILD_NUMBER; +constexpr float CONTENT_CHILD_HEIGHT = DEVICE_HEIGHT / VIEWPORT_CHILD_NUMBER; +constexpr float CONTENT_WIDTH = CONTENT_CHILD_WIDTH * CHILD_NUMBER; +constexpr float CONTENT_HEIGHT = CONTENT_CHILD_HEIGHT * CHILD_NUMBER; constexpr int32_t BAR_EXPAND_DURATION = 150; // 150ms, scroll bar width expands from 4dp to 8dp constexpr int32_t BAR_SHRINK_DURATION = 250; // 250ms, scroll bar width shrinks from 8dp to 4dp -const static int32_t PLATFORM_VERSION_TEN = 10; +constexpr double DEFAULT_FRICTION = 0.6; } // namespace -class ScrollTestNg : public testing::Test { +class ScrollTestNg : public testing::Test, public TestNG { public: static void SetUpTestSuite(); static void TearDownTestSuite(); void SetUp() override; void TearDown() override; void GetInstance(); - static void SetWidth(const Dimension& width); - static void SetHeight(const Dimension& height); + void UpdateCurrentOffset(float offset); RefPtr CreateScroll(Axis axis = Axis::VERTICAL); RefPtr CreateScroll(NG::DisplayMode displayMode); RefPtr CreateScroll(Color color); @@ -84,18 +81,12 @@ public: RefPtr CreateScroll(Axis axis, OnScrollStartEvent&& event); RefPtr CreateScroll(bool isScrollEnabled); void CreateContent(Axis axis = Axis::VERTICAL); - RefPtr RunMeasureAndLayout(float width = ROOT_WIDTH, float height = ROOT_HEIGHT); RefPtr GetContentChild(int32_t index); void Touch(TouchLocationInfo locationInfo, SourceType sourceType); void Touch(TouchType touchType, Offset offset, SourceType sourceType); void Mouse(MouseInfo mouseInfo); void Mouse(Offset moveOffset); - RefPtr GetColumnChild(int32_t index); - void UpdateCurrentOffset(float offset); - uint64_t GetActions(); testing::AssertionResult IsEqualCurrentOffset(Offset expectOffset); - testing::AssertionResult IsEqualOverScrollOffset(OverScrollOffset offset, OverScrollOffset expectOffset); - testing::AssertionResult IsEqualRect(Rect rect, Rect expectRect); RefPtr frameNode_; RefPtr pattern_; @@ -142,20 +133,6 @@ void ScrollTestNg::GetInstance() accessibilityProperty_ = frameNode_->GetAccessibilityProperty(); } -void ScrollTestNg::SetWidth(const Dimension& width) -{ - auto frameNode = ViewStackProcessor::GetInstance()->GetMainFrameNode(); - auto layoutProperty = frameNode->GetLayoutProperty(); - layoutProperty->UpdateUserDefinedIdealSize(CalcSize(CalcLength(width), std::nullopt)); -} - -void ScrollTestNg::SetHeight(const Dimension& height) -{ - auto frameNode = ViewStackProcessor::GetInstance()->GetMainFrameNode(); - auto layoutProperty = frameNode->GetLayoutProperty(); - layoutProperty->UpdateUserDefinedIdealSize(CalcSize(std::nullopt, CalcLength(height))); -} - RefPtr ScrollTestNg::CreateScroll(Axis axis) { ScrollModelNG scrollModel; @@ -163,7 +140,7 @@ RefPtr ScrollTestNg::CreateScroll(Axis axis) scrollModel.SetAxis(axis); CreateContent(axis); GetInstance(); - return RunMeasureAndLayout(); + return RunMeasureAndLayout(frameNode_); } RefPtr ScrollTestNg::CreateScroll(NG::DisplayMode displayMode) @@ -173,7 +150,7 @@ RefPtr ScrollTestNg::CreateScroll(NG::DisplayMode displayMode scrollModel.SetDisplayMode(static_cast(displayMode)); CreateContent(); GetInstance(); - return RunMeasureAndLayout(); + return RunMeasureAndLayout(frameNode_); } RefPtr ScrollTestNg::CreateScroll(Color color) @@ -183,7 +160,7 @@ RefPtr ScrollTestNg::CreateScroll(Color color) scrollModel.SetScrollBarColor(color); CreateContent(); GetInstance(); - return RunMeasureAndLayout(); + return RunMeasureAndLayout(frameNode_); } RefPtr ScrollTestNg::CreateScroll(Dimension barWidth, Axis axis) @@ -194,7 +171,7 @@ RefPtr ScrollTestNg::CreateScroll(Dimension barWidth, Axis ax scrollModel.SetScrollBarWidth(barWidth); CreateContent(axis); GetInstance(); - return RunMeasureAndLayout(); + return RunMeasureAndLayout(frameNode_); } RefPtr ScrollTestNg::CreateScroll(EdgeEffect edgeEffect) @@ -204,7 +181,7 @@ RefPtr ScrollTestNg::CreateScroll(EdgeEffect edgeEffect) scrollModel.SetEdgeEffect(edgeEffect); CreateContent(); GetInstance(); - return RunMeasureAndLayout(); + return RunMeasureAndLayout(frameNode_); } RefPtr ScrollTestNg::CreateScroll(Axis axis, NG::ScrollEvent&& event) @@ -215,7 +192,7 @@ RefPtr ScrollTestNg::CreateScroll(Axis axis, NG::ScrollEvent& scrollModel.SetOnScroll(std::move(event)); CreateContent(axis); GetInstance(); - return RunMeasureAndLayout(); + return RunMeasureAndLayout(frameNode_); } RefPtr ScrollTestNg::CreateScroll(Axis axis, NG::ScrollEdgeEvent&& event) @@ -226,7 +203,7 @@ RefPtr ScrollTestNg::CreateScroll(Axis axis, NG::ScrollEdgeEv scrollModel.SetOnScrollEdge(std::move(event)); CreateContent(axis); GetInstance(); - return RunMeasureAndLayout(); + return RunMeasureAndLayout(frameNode_); } RefPtr ScrollTestNg::CreateScroll(Axis axis, OnScrollStartEvent&& event) @@ -239,7 +216,7 @@ RefPtr ScrollTestNg::CreateScroll(Axis axis, OnScrollStartEve scrollModel.SetOnScrollEnd(std::move(event)); CreateContent(axis); GetInstance(); - return RunMeasureAndLayout(); + return RunMeasureAndLayout(frameNode_); } RefPtr ScrollTestNg::CreateScroll(bool isScrollEnabled) @@ -249,7 +226,7 @@ RefPtr ScrollTestNg::CreateScroll(bool isScrollEnabled) scrollModel.SetScrollEnabled(isScrollEnabled); CreateContent(); GetInstance(); - return RunMeasureAndLayout(); + return RunMeasureAndLayout(frameNode_); } void ScrollTestNg::CreateContent(Axis axis) @@ -257,12 +234,12 @@ void ScrollTestNg::CreateContent(Axis axis) if (axis == Axis::HORIZONTAL) { RowModelNG rowModelNG; rowModelNG.Create(Dimension(0), nullptr, ""); - SetWidth(Dimension(COLUMN_WIDTH)); + SetWidth(Dimension(CONTENT_WIDTH)); SetHeight(FILL_LENGTH); for (int32_t index = 0; index < CHILD_NUMBER; index++) { RowModelNG rowModelNG; rowModelNG.Create(Dimension(0), nullptr, ""); - SetWidth(Dimension(COLUMN_CHILD_WIDTH)); + SetWidth(Dimension(CONTENT_CHILD_WIDTH)); SetHeight(FILL_LENGTH); ViewStackProcessor::GetInstance()->Pop(); } @@ -270,54 +247,28 @@ void ScrollTestNg::CreateContent(Axis axis) ColumnModelNG columnModel; columnModel.Create(Dimension(0), nullptr, ""); SetWidth(FILL_LENGTH); - SetHeight(Dimension(COLUMN_HEIGHT)); + SetHeight(Dimension(CONTENT_HEIGHT)); for (int32_t index = 0; index < CHILD_NUMBER; index++) { ColumnModelNG columnModel; columnModel.Create(Dimension(0), nullptr, ""); SetWidth(FILL_LENGTH); - SetHeight(Dimension(COLUMN_CHILD_HEIGHT)); + SetHeight(Dimension(CONTENT_CHILD_HEIGHT)); ViewStackProcessor::GetInstance()->Pop(); } } ViewStackProcessor::GetInstance()->Pop(); } -RefPtr ScrollTestNg::RunMeasureAndLayout(float width, float height) -{ - RefPtr layoutWrapper = frameNode_->CreateLayoutWrapper(false, false); - layoutWrapper->SetActive(); - layoutWrapper->SetRootMeasureNode(); - LayoutConstraintF LayoutConstraint; - LayoutConstraint.parentIdealSize = { ROOT_WIDTH, ROOT_HEIGHT }; - LayoutConstraint.percentReference = { ROOT_WIDTH, ROOT_HEIGHT }; - LayoutConstraint.selfIdealSize = { width, height }; - LayoutConstraint.maxSize = { width, height }; - layoutWrapper->Measure(LayoutConstraint); - layoutWrapper->Layout(); - layoutWrapper->MountToHostOnMainThread(); - return layoutWrapper; -} - void ScrollTestNg::UpdateCurrentOffset(float offset) { pattern_->UpdateCurrentOffset(offset, SCROLL_FROM_UPDATE); - RunMeasureAndLayout(); -} - -uint64_t ScrollTestNg::GetActions() -{ - std::unordered_set supportAceActions = accessibilityProperty_->GetSupportAction(); - uint64_t actions = 0; - for (auto action : supportAceActions) { - actions |= 1UL << static_cast(action); - } - return actions; + RunMeasureAndLayout(frameNode_); } RefPtr ScrollTestNg::GetContentChild(int32_t index) { - auto content = AceType::DynamicCast(frameNode_->GetChildAtIndex(0)); - auto contentChild = AceType::DynamicCast(content->GetChildAtIndex(index)); + auto content = GetChildFrameNode(frameNode_, 0); + auto contentChild = GetChildFrameNode(content, index); return contentChild; } @@ -358,34 +309,9 @@ void ScrollTestNg::Mouse(Offset moveOffset) testing::AssertionResult ScrollTestNg::IsEqualCurrentOffset(Offset expectOffset) { - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); Offset currentOffset = pattern_->GetCurrentOffset(); - if (expectOffset == currentOffset) { - return testing::AssertionSuccess(); - } - return testing::AssertionFailure() << "GetCurrentOffset(): " << currentOffset.ToString() << " != " - << "expectOffset: " << expectOffset.ToString(); -} - -testing::AssertionResult ScrollTestNg::IsEqualOverScrollOffset(OverScrollOffset offset, OverScrollOffset expectOffset) -{ - if (NearEqual(offset.start, expectOffset.start) && NearEqual(offset.end, expectOffset.end)) { - return testing::AssertionSuccess(); - } - return testing::AssertionFailure() << "offset: " - << "{ " << offset.start << " , " << offset.end << " }" - << " != " - << "expectOffset: " - << "{ " << expectOffset.start << " , " << expectOffset.end << " }"; -} - -testing::AssertionResult ScrollTestNg::IsEqualRect(Rect rect, Rect expectRect) -{ - if (rect == expectRect) { - return testing::AssertionSuccess(); - } - return testing::AssertionFailure() << "rect: " << rect.ToString() << " != " - << "expectRect: " << expectRect.ToString(); + return IsEqualOffset(currentOffset, expectOffset); } /** @@ -399,23 +325,22 @@ HWTEST_F(ScrollTestNg, AttrScrollable001, TestSize.Level1) * @tc.steps: step1. Text default value: Vertical */ CreateScroll(); - const float delta = -100.f; - UpdateCurrentOffset(delta); - EXPECT_TRUE(IsEqualCurrentOffset(Offset(0, delta))); + UpdateCurrentOffset(-CONTENT_CHILD_HEIGHT); + EXPECT_TRUE(IsEqualCurrentOffset(Offset(0, -CONTENT_CHILD_HEIGHT))); /** * @tc.steps: step2. Text set value: Horizontal */ CreateScroll(Axis::HORIZONTAL); - UpdateCurrentOffset(delta); - EXPECT_TRUE(IsEqualCurrentOffset(Offset(delta, 0))); + UpdateCurrentOffset(-CONTENT_CHILD_WIDTH); + EXPECT_TRUE(IsEqualCurrentOffset(Offset(-CONTENT_CHILD_WIDTH, 0))); /** * @tc.steps: step3. Text set value: None */ CreateScroll(Axis::NONE); - UpdateCurrentOffset(delta); - EXPECT_TRUE(IsEqualCurrentOffset(Offset(0, delta))); + UpdateCurrentOffset(-CONTENT_CHILD_HEIGHT); + EXPECT_TRUE(IsEqualCurrentOffset(Offset(0, -CONTENT_CHILD_HEIGHT))); } /** @@ -425,21 +350,10 @@ HWTEST_F(ScrollTestNg, AttrScrollable001, TestSize.Level1) */ HWTEST_F(ScrollTestNg, AttrScrollBar001, TestSize.Level1) { - /** - * @tc.steps: step1. Text default value: Auto - */ CreateScroll(); EXPECT_EQ(paintProperty_->GetBarStateString(), "BarState.Auto"); - - /** - * @tc.steps: step2. Text set value: Off - */ CreateScroll(NG::DisplayMode::OFF); EXPECT_EQ(paintProperty_->GetBarStateString(), "BarState.Off"); - - /** - * @tc.steps: step3. Text set value: On - */ CreateScroll(NG::DisplayMode::ON); EXPECT_EQ(paintProperty_->GetBarStateString(), "BarState.On"); } @@ -480,21 +394,10 @@ HWTEST_F(ScrollTestNg, AttrScrollBarColorWidth001, TestSize.Level1) */ HWTEST_F(ScrollTestNg, AttrEdgeEffect001, TestSize.Level1) { - /** - * @tc.steps: step1. Text default value: None - */ CreateScroll(); EXPECT_EQ(layoutProperty_->GetEdgeEffectValue(), EdgeEffect::NONE); - - /** - * @tc.steps: step2. Text set value: SPRING - */ CreateScroll(EdgeEffect::SPRING); EXPECT_EQ(layoutProperty_->GetEdgeEffectValue(), EdgeEffect::SPRING); - - /** - * @tc.steps: step3. Text set value: SPRING - */ CreateScroll(EdgeEffect::FADE); EXPECT_EQ(layoutProperty_->GetEdgeEffectValue(), EdgeEffect::FADE); } @@ -547,7 +450,7 @@ HWTEST_F(ScrollTestNg, Event001, TestSize.Level1) scrollModel.SetOnScrollBegin(event2); CreateContent(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step1. When set event @@ -577,7 +480,7 @@ HWTEST_F(ScrollTestNg, Event002, TestSize.Level1) * @tc.steps: step2. Trigger event by OnScrollCallback * @tc.expected: isTrigger is true */ - pattern_->OnScrollCallback(-COLUMN_HEIGHT, SCROLL_FROM_UPDATE); + pattern_->OnScrollCallback(-CONTENT_HEIGHT, SCROLL_FROM_UPDATE); EXPECT_TRUE(isTrigger); /** @@ -599,7 +502,7 @@ HWTEST_F(ScrollTestNg, Event002, TestSize.Level1) * @tc.expected: isTrigger is true */ isTrigger = false; - pattern_->OnScrollCallback(-COLUMN_WIDTH, SCROLL_FROM_UPDATE); + pattern_->OnScrollCallback(-CONTENT_WIDTH, SCROLL_FROM_UPDATE); EXPECT_TRUE(isTrigger); /** @@ -631,7 +534,7 @@ HWTEST_F(ScrollTestNg, Event003, TestSize.Level1) * @tc.steps: step2. Trigger event by OnScrollCallback * @tc.expected: isTrigger is true */ - pattern_->OnScrollCallback(-COLUMN_HEIGHT, SCROLL_FROM_UPDATE); + pattern_->OnScrollCallback(-CONTENT_HEIGHT, SCROLL_FROM_UPDATE); EXPECT_TRUE(isTrigger); /** @@ -652,7 +555,7 @@ HWTEST_F(ScrollTestNg, Event003, TestSize.Level1) * @tc.steps: step5. Trigger event by OnScrollCallback * @tc.expected: isTrigger is true */ - pattern_->OnScrollCallback(-COLUMN_WIDTH, SCROLL_FROM_UPDATE); + pattern_->OnScrollCallback(-CONTENT_WIDTH, SCROLL_FROM_UPDATE); EXPECT_TRUE(isTrigger); /** @@ -684,7 +587,7 @@ HWTEST_F(ScrollTestNg, Event004, TestSize.Level1) * @tc.steps: step2. Trigger onScrollStart event by OnScrollCallback * @tc.expected: isTrigger is true */ - pattern_->OnScrollCallback(-COLUMN_HEIGHT, SCROLL_FROM_START); + pattern_->OnScrollCallback(-CONTENT_HEIGHT, SCROLL_FROM_START); EXPECT_TRUE(isTrigger); /** @@ -703,7 +606,7 @@ HWTEST_F(ScrollTestNg, Event004, TestSize.Level1) pattern_->OnScrollEndCallback(); // Trigger onScrollEnd, set scrollStop_ = true; EXPECT_TRUE(isTrigger); isTrigger = false; - RunMeasureAndLayout(); // Trigger onScrollStop + RunMeasureAndLayout(frameNode_); // Trigger onScrollStop EXPECT_TRUE(isTrigger); } @@ -717,7 +620,7 @@ HWTEST_F(ScrollTestNg, ScrollPositionController001, TestSize.Level1) CreateScroll(); auto controller = pattern_->GetScrollPositionController(); - const Dimension position1(COLUMN_HEIGHT); + const Dimension position1(CONTENT_HEIGHT); const float duration1 = -1.f; bool animate = controller->AnimateTo(position1, duration1, Curves::LINEAR, false); EXPECT_TRUE(animate); @@ -728,16 +631,16 @@ HWTEST_F(ScrollTestNg, ScrollPositionController001, TestSize.Level1) EXPECT_FALSE(animate); controller->ScrollToEdge(ScrollEdgeType::SCROLL_BOTTOM, false); - const Offset expectOffset1(0, ROOT_HEIGHT - COLUMN_HEIGHT); + const Offset expectOffset1(0, DEVICE_HEIGHT - CONTENT_HEIGHT); EXPECT_TRUE(IsEqualCurrentOffset(expectOffset1)); controller->ScrollPage(false, false); - const Offset expectOffset2(0, ROOT_HEIGHT - COLUMN_HEIGHT); + const Offset expectOffset2(0, DEVICE_HEIGHT - CONTENT_HEIGHT); EXPECT_TRUE(IsEqualCurrentOffset(expectOffset2)); controller->ScrollToEdge(ScrollEdgeType::SCROLL_TOP, false); EXPECT_FALSE(controller->IsAtEnd()); - const float delta = COLUMN_HEIGHT - ROOT_HEIGHT; + const float delta = CONTENT_HEIGHT - DEVICE_HEIGHT; UpdateCurrentOffset(-delta); EXPECT_TRUE(controller->IsAtEnd()); } @@ -752,7 +655,7 @@ HWTEST_F(ScrollTestNg, ScrollPositionControlle002, TestSize.Level1) CreateScroll(Axis::NONE); auto controller = pattern_->GetScrollPositionController(); - const Dimension position(COLUMN_HEIGHT); + const Dimension position(CONTENT_HEIGHT); const float duration = 1.f; bool animate = controller->AnimateTo(position, duration, Curves::LINEAR, false); EXPECT_FALSE(animate); @@ -826,31 +729,6 @@ HWTEST_F(ScrollTestNg, SpringEffect001, TestSize.Level1) EXPECT_TRUE(true); } -/** - * @tc.name: ScrollTest001 - * @tc.desc: Test OnDirtyLayoutWrapperSwap - * @tc.type: FUNC - */ -HWTEST_F(ScrollTestNg, ScrollTest001, TestSize.Level1) -{ - auto layoutWrapper = CreateScroll(); - DirtySwapConfig config; - config.skipMeasure = true; - config.skipLayout = false; - auto dirty = pattern_->OnDirtyLayoutWrapperSwap(layoutWrapper, config); - EXPECT_FALSE(dirty); - - config.skipMeasure = true; - config.skipLayout = true; - dirty = pattern_->OnDirtyLayoutWrapperSwap(layoutWrapper, config); - EXPECT_FALSE(dirty); - - config.skipMeasure = false; - config.skipLayout = false; - dirty = pattern_->OnDirtyLayoutWrapperSwap(layoutWrapper, config); - EXPECT_FALSE(dirty); -} - /** * @tc.name: ScrollTest002 * @tc.desc: When setting a fixed length and width, verify the related functions in the scroll pattern. @@ -866,7 +744,7 @@ HWTEST_F(ScrollTestNg, ScrollTest002, TestSize.Level1) scrollModel.SetScrollBarProxy(scrollProxy); CreateContent(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); /** * @tc.steps: step5. When Axis is HORIZONTAL, Verify the callback function registered in scrollBarProxy. @@ -1055,7 +933,7 @@ HWTEST_F(ScrollTestNg, UpdateCurrentOffset001, TestSize.Level1) ScrollModelNG scrollModel; scrollModel.Create(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); pattern_->UpdateCurrentOffset(10.f, SCROLL_FROM_UPDATE); EXPECT_TRUE(IsEqualCurrentOffset(Offset::Zero())); @@ -1105,7 +983,7 @@ HWTEST_F(ScrollTestNg, UpdateCurrentOffset001, TestSize.Level1) EXPECT_EQ(pattern_->GetScrollBarOutBoundaryExtent(), 5.f); pattern_->currentOffset_ = -1000.f; pattern_->UpdateCurrentOffset(-10.f, SCROLL_FROM_UPDATE); - EXPECT_EQ(pattern_->GetScrollBarOutBoundaryExtent(), -pattern_->currentOffset_ - (COLUMN_HEIGHT - ROOT_HEIGHT)); + EXPECT_EQ(pattern_->GetScrollBarOutBoundaryExtent(), -pattern_->currentOffset_ - (CONTENT_HEIGHT - DEVICE_HEIGHT)); } /** @@ -1132,7 +1010,7 @@ HWTEST_F(ScrollTestNg, ScrollFadeEffect001, TestSize.Level1) * @tc.steps: step2. call HandleOverScroll(), overScroll is 0 * @tc.expected: do nothing */ - const SizeF viewPort(ROOT_WIDTH, ROOT_HEIGHT); + const SizeF viewPort(DEVICE_WIDTH, DEVICE_HEIGHT); scrollFadeEffect->HandleOverScroll(Axis::VERTICAL, 0.f, viewPort); /** @@ -1166,42 +1044,69 @@ HWTEST_F(ScrollTestNg, ScrollFadeEffect001, TestSize.Level1) * @tc.steps: step5. Call CalculateOverScroll() */ // minExtent: 0 - // maxExtent: COLUMN_CHILD_HEIGHT * 2 - EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(COLUMN_CHILD_HEIGHT, true), 0.0)); + // maxExtent: CONTENT_CHILD_HEIGHT * 2 + EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(CONTENT_CHILD_HEIGHT, true), 0.0)); EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(0.0, true), 0.0)); - EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(-COLUMN_CHILD_HEIGHT, true), 0.0)); + EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(-CONTENT_CHILD_HEIGHT, true), 0.0)); - UpdateCurrentOffset(-COLUMN_CHILD_HEIGHT); - EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(COLUMN_CHILD_HEIGHT * 2, true), 0.0)); + UpdateCurrentOffset(-CONTENT_CHILD_HEIGHT); + EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(CONTENT_CHILD_HEIGHT * 2, true), 0.0)); EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(0.0, true), 0.0)); - EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(-COLUMN_CHILD_HEIGHT * 2, true), 0.0)); + EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(-CONTENT_CHILD_HEIGHT * 2, true), 0.0)); - UpdateCurrentOffset(-COLUMN_CHILD_HEIGHT); - EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(COLUMN_CHILD_HEIGHT, true), 0.0)); + UpdateCurrentOffset(-CONTENT_CHILD_HEIGHT); + EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(CONTENT_CHILD_HEIGHT, true), 0.0)); EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(0.0, true), 0.0)); - EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(-COLUMN_CHILD_HEIGHT, true), 0.0)); + EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(-CONTENT_CHILD_HEIGHT, true), 0.0)); - pattern_->currentOffset_ = COLUMN_CHILD_HEIGHT; - EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(COLUMN_CHILD_HEIGHT, true), -COLUMN_CHILD_HEIGHT)); - EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(0.0, true), -COLUMN_CHILD_HEIGHT)); - EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(-COLUMN_CHILD_HEIGHT * 2, true), 0.0)); + pattern_->currentOffset_ = CONTENT_CHILD_HEIGHT; + EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(CONTENT_CHILD_HEIGHT, true), -CONTENT_CHILD_HEIGHT)); + EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(0.0, true), -CONTENT_CHILD_HEIGHT)); + EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(-CONTENT_CHILD_HEIGHT * 2, true), 0.0)); - pattern_->currentOffset_ = -COLUMN_CHILD_HEIGHT; - EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(COLUMN_CHILD_HEIGHT * 2, true), 0.0)); + pattern_->currentOffset_ = -CONTENT_CHILD_HEIGHT; + EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(CONTENT_CHILD_HEIGHT * 2, true), 0.0)); EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(0.0, true), 0.0)); - EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(-COLUMN_CHILD_HEIGHT, true), 0.0)); + EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(-CONTENT_CHILD_HEIGHT, true), 0.0)); // over scroll - pattern_->currentOffset_ = -COLUMN_CHILD_HEIGHT * 3; - EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(COLUMN_CHILD_HEIGHT * 2, true), COLUMN_CHILD_HEIGHT)); + pattern_->currentOffset_ = -CONTENT_CHILD_HEIGHT * 3; + EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(CONTENT_CHILD_HEIGHT * 2, true), CONTENT_CHILD_HEIGHT)); // crash the bottom - pattern_->currentOffset_ = -COLUMN_CHILD_HEIGHT * 3; - EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(COLUMN_CHILD_HEIGHT, true), COLUMN_CHILD_HEIGHT)); - pattern_->currentOffset_ = -COLUMN_CHILD_HEIGHT * 3; - EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(COLUMN_CHILD_HEIGHT, false), 0.0)); - pattern_->currentOffset_ = -COLUMN_CHILD_HEIGHT * 3; - EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(COLUMN_CHILD_HEIGHT * 3, false), 0.0)); + pattern_->currentOffset_ = -CONTENT_CHILD_HEIGHT * 3; + EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(CONTENT_CHILD_HEIGHT, true), CONTENT_CHILD_HEIGHT)); + pattern_->currentOffset_ = -CONTENT_CHILD_HEIGHT * 3; + EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(CONTENT_CHILD_HEIGHT, false), 0.0)); + pattern_->currentOffset_ = -CONTENT_CHILD_HEIGHT * 3; + EXPECT_TRUE(NearEqual(scrollFadeEffect->CalculateOverScroll(CONTENT_CHILD_HEIGHT * 3, false), 0.0)); +} + +/** + * @tc.name: ScrollFadeEffect002 + * @tc.desc: Test + * @tc.type: FUNC + */ +HWTEST_F(ScrollTestNg, ScrollFadeEffect002, TestSize.Level1) +{ + CreateScroll(EdgeEffect::FADE); + RefPtr scrollEdgeEffect = pattern_->GetScrollEdgeEffect(); + auto scrollFadeEffect = AceType::DynamicCast(scrollEdgeEffect); + scrollFadeEffect->InitialEdgeEffect(); + + Testing::MockCanvas rsCanvas; + OffsetF offset = OffsetF(0, 0); + scrollFadeEffect->fadePainter_->SetOpacity(0); + scrollFadeEffect->fadePainter_->direction_ = OverScrollDirection::UP; + scrollFadeEffect->Paint(rsCanvas, SizeF(1, 1), offset); + scrollFadeEffect->fadePainter_->SetOpacity(1); + scrollFadeEffect->fadePainter_->direction_ = OverScrollDirection::DOWN; + scrollFadeEffect->Paint(rsCanvas, SizeF(0, 1), offset); + scrollFadeEffect->fadePainter_->direction_ = OverScrollDirection::LEFT; + scrollFadeEffect->Paint(rsCanvas, SizeF(1, 0), offset); + scrollFadeEffect->fadePainter_->direction_ = OverScrollDirection::RIGHT; + scrollFadeEffect->Paint(rsCanvas, SizeF(0, 0), offset); + SUCCEED(); } /** @@ -1389,10 +1294,10 @@ HWTEST_F(ScrollTestNg, ScrollBar002, TestSize.Level1) const float barWidth = 10.f; CreateScroll(Dimension(barWidth)); auto scrollBar = pattern_->GetScrollBar(); - const Offset downInBar = Offset(ROOT_WIDTH - 1.f, 0.f); - const Offset moveInBar = Offset(ROOT_WIDTH - 1.f, 10.f); + const Offset downInBar = Offset(DEVICE_WIDTH - 1.f, 0.f); + const Offset moveInBar = Offset(DEVICE_WIDTH - 1.f, 10.f); const Offset upInBar = moveInBar; - const Offset upOutBar = Offset(ROOT_WIDTH - barWidth - 1.f, 10.f); + const Offset upOutBar = Offset(DEVICE_WIDTH - barWidth - 1.f, 10.f); Touch(TouchType::DOWN, downInBar, SourceType::TOUCH); EXPECT_EQ(scrollBar->touchAnimator_->GetDuration(), BAR_EXPAND_DURATION); @@ -1481,7 +1386,7 @@ HWTEST_F(ScrollTestNg, ScrollBar002, TestSize.Level1) */ CreateScroll(Dimension(barWidth)); scrollBar = pattern_->GetScrollBar(); - const Offset moveOutBar = Offset(ROOT_WIDTH - barWidth - 1.f, 0.f); + const Offset moveOutBar = Offset(DEVICE_WIDTH - barWidth - 1.f, 0.f); Mouse(moveOutBar); EXPECT_EQ(scrollBar->touchAnimator_->GetDuration(), 0); @@ -1528,21 +1433,28 @@ HWTEST_F(ScrollTestNg, ScrollBar003, TestSize.Level1) * @tc.expected: Verify bar rect */ const float barWidth = 10.f; + const float ratio = static_cast(VIEWPORT_CHILD_NUMBER) / CHILD_NUMBER; CreateScroll(Dimension(barWidth)); auto scrollBar = pattern_->GetScrollBar(); - EXPECT_TRUE(IsEqualRect(scrollBar->touchRegion_, - Rect(ROOT_WIDTH - barWidth, 0.f, barWidth, ROOT_HEIGHT / CHILD_NUMBER * VIEWPORT_CHILD_NUMBER))); + Rect rect = scrollBar->touchRegion_; + Rect expectRect = Rect( + DEVICE_WIDTH - barWidth, + 0.f, + barWidth, + DEVICE_HEIGHT * ratio + ); + EXPECT_TRUE(IsEqualRect(rect, expectRect)); - UpdateCurrentOffset(-COLUMN_CHILD_HEIGHT); - EXPECT_TRUE(IsEqualRect( - scrollBar->touchRegion_, Rect(ROOT_WIDTH - barWidth, COLUMN_CHILD_HEIGHT / CHILD_NUMBER * VIEWPORT_CHILD_NUMBER, - barWidth, ROOT_HEIGHT / CHILD_NUMBER * VIEWPORT_CHILD_NUMBER))); - - UpdateCurrentOffset(-COLUMN_CHILD_HEIGHT); - EXPECT_TRUE(IsEqualRect(scrollBar->touchRegion_, - Rect(ROOT_WIDTH - barWidth, COLUMN_CHILD_HEIGHT * 2 / CHILD_NUMBER * VIEWPORT_CHILD_NUMBER, barWidth, - ROOT_HEIGHT / CHILD_NUMBER * VIEWPORT_CHILD_NUMBER))); + UpdateCurrentOffset(-CONTENT_CHILD_HEIGHT); + rect = scrollBar->touchRegion_; + expectRect = Rect( + DEVICE_WIDTH - barWidth, + CONTENT_CHILD_HEIGHT * ratio, + barWidth, + DEVICE_HEIGHT * ratio + ); + EXPECT_TRUE(IsEqualRect(rect, expectRect)); /** * @tc.steps: step2. Test Bar in HORIZONTAL @@ -1551,18 +1463,24 @@ HWTEST_F(ScrollTestNg, ScrollBar003, TestSize.Level1) CreateScroll(Dimension(barWidth), Axis::HORIZONTAL); scrollBar = pattern_->GetScrollBar(); - EXPECT_TRUE(IsEqualRect(scrollBar->touchRegion_, - Rect(0.f, ROOT_HEIGHT - barWidth, ROOT_WIDTH / CHILD_NUMBER * VIEWPORT_CHILD_NUMBER, barWidth))); + rect = scrollBar->touchRegion_; + expectRect = Rect( + 0.f, + DEVICE_HEIGHT - barWidth, + DEVICE_WIDTH * ratio, + barWidth + ); + EXPECT_TRUE(IsEqualRect(rect, expectRect)); - UpdateCurrentOffset(-COLUMN_CHILD_WIDTH); - EXPECT_TRUE(IsEqualRect( - scrollBar->touchRegion_, Rect(COLUMN_CHILD_WIDTH / CHILD_NUMBER * VIEWPORT_CHILD_NUMBER, ROOT_HEIGHT - barWidth, - ROOT_WIDTH / CHILD_NUMBER * VIEWPORT_CHILD_NUMBER, barWidth))); - - UpdateCurrentOffset(-COLUMN_CHILD_WIDTH); - EXPECT_TRUE(IsEqualRect(scrollBar->touchRegion_, - Rect(COLUMN_CHILD_WIDTH * 2 / CHILD_NUMBER * VIEWPORT_CHILD_NUMBER, ROOT_HEIGHT - barWidth, - ROOT_WIDTH / CHILD_NUMBER * VIEWPORT_CHILD_NUMBER, barWidth))); + UpdateCurrentOffset(-CONTENT_CHILD_WIDTH); + rect = scrollBar->touchRegion_; + expectRect = Rect( + CONTENT_CHILD_WIDTH * ratio, + DEVICE_HEIGHT - barWidth, + DEVICE_WIDTH * ratio, + barWidth + ); + EXPECT_TRUE(IsEqualRect(rect, expectRect)); } /** @@ -1596,6 +1514,48 @@ HWTEST_F(ScrollTestNg, ScrollBar004, TestSize.Level1) EXPECT_EQ(scrollBar->touchRegion_.Left(), 30.f); } +/** + * @tc.name: ScrollBar005 + * @tc.desc: Test CalcReservedHeight() + * @tc.type: FUNC + */ +HWTEST_F(ScrollTestNg, ScrollBar005, TestSize.Level1) +{ + CreateScroll(); + auto pipelineContext = PipelineContext::GetCurrentContext(); + pipelineContext->SetMinPlatformVersion(PLATFORM_VERSION_TEN + 1); + auto scrollBar = pattern_->GetScrollBar(); + + scrollBar->SetPositionMode(PositionMode::LEFT); + scrollBar->SetNormalWidth(Dimension(1)); // call CalcReservedHeight; + EXPECT_EQ(scrollBar->startReservedHeight_, Dimension(0.0)); + EXPECT_EQ(scrollBar->endReservedHeight_, Dimension(0.0)); + + BorderRadiusProperty borderRadiusProperty; + float radius = 13.f; + borderRadiusProperty.radiusTopRight = std::make_optional(radius); + borderRadiusProperty.radiusBottomRight = std::make_optional(radius); + scrollBar->SetHostBorderRadius(borderRadiusProperty); + scrollBar->SetPadding(Edge(1, 1, 1, 1)); + scrollBar->SetPositionMode(PositionMode::RIGHT); + scrollBar->SetNormalWidth(Dimension(2)); // call CalcReservedHeight; + EXPECT_EQ(scrollBar->startReservedHeight_, Dimension(14.5)) + << "startReservedHeight_: " << scrollBar->startReservedHeight_.ConvertToPx(); + EXPECT_EQ(scrollBar->endReservedHeight_, Dimension(14.5)) + << "endReservedHeight_: " << scrollBar->endReservedHeight_.ConvertToPx(); + + borderRadiusProperty.radiusBottomLeft = std::make_optional(radius); + borderRadiusProperty.radiusBottomRight = std::make_optional(radius); + scrollBar->SetHostBorderRadius(borderRadiusProperty); + scrollBar->SetPadding(Edge(1, 1, 1, 1)); + scrollBar->SetPositionMode(PositionMode::BOTTOM); + scrollBar->SetNormalWidth(Dimension(6)); // call CalcReservedHeight; + EXPECT_EQ(scrollBar->startReservedHeight_, Dimension(11.25)) + << "startReservedHeight_: " << scrollBar->startReservedHeight_.ConvertToPx(); + EXPECT_EQ(scrollBar->endReservedHeight_, Dimension(11.25)) + << "endReservedHeight_: " << scrollBar->endReservedHeight_.ConvertToPx(); +} + /** * @tc.name: Measure001 * @tc.desc: Test Measure @@ -1617,13 +1577,13 @@ HWTEST_F(ScrollTestNg, Measure001, TestSize.Level1) layoutWrapper->SetActive(); layoutWrapper->SetRootMeasureNode(); LayoutConstraintF LayoutConstraint; - LayoutConstraint.parentIdealSize = { ROOT_WIDTH, ROOT_HEIGHT }; - LayoutConstraint.percentReference = { ROOT_WIDTH, ROOT_HEIGHT }; + LayoutConstraint.parentIdealSize = { DEVICE_WIDTH, DEVICE_HEIGHT }; + LayoutConstraint.percentReference = { DEVICE_WIDTH, DEVICE_HEIGHT }; layoutWrapper->Measure(LayoutConstraint); layoutWrapper->Layout(); layoutWrapper->MountToHostOnMainThread(); auto scrollSize = frameNode_->GetGeometryNode()->GetFrameSize(); - auto expectSize = SizeF(ROOT_WIDTH, COLUMN_HEIGHT); + auto expectSize = SizeF(DEVICE_WIDTH, CONTENT_HEIGHT); EXPECT_EQ(scrollSize, expectSize) << "scrollSize: " << scrollSize.ToString() << " expectSize: " << expectSize.ToString(); } @@ -1640,10 +1600,10 @@ HWTEST_F(ScrollTestNg, Layout001, TestSize.Level1) scrollModel.SetAxis(Axis::NONE); CreateContent(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); layoutProperty_->UpdateAlignment(Alignment::CENTER); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); auto col = frameNode_->GetChildAtIndex(0); auto colNode = AceType::DynamicCast(col); auto colOffset = colNode->GetGeometryNode()->GetMarginFrameOffset(); @@ -1685,14 +1645,6 @@ HWTEST_F(ScrollTestNg, OnScrollCallback001, TestSize.Level1) EXPECT_TRUE(pattern_->OnScrollCallback(-100.f, SCROLL_FROM_UPDATE)); EXPECT_TRUE(IsEqualCurrentOffset(Offset(0, -100.f))); - /** - * @tc.steps: step4. scrollBar->IsDriving() is true and SCROLL_FROM_UPDATE - * @tc.expected: Trigger UpdateCurrentOffset() - */ - CreateScroll(); - EXPECT_TRUE(pattern_->OnScrollCallback(100.f, SCROLL_FROM_UPDATE)); - EXPECT_TRUE(IsEqualCurrentOffset(Offset(0, -100.f / pattern_->GetScrollBar()->offsetScale_))); - /** * @tc.steps: step5. no animator and SCROLL_FROM_START * @tc.expected: Trigger FireOnScrollStart() @@ -1743,9 +1695,9 @@ HWTEST_F(ScrollTestNg, ScrollToNode001, TestSize.Level1) pattern_->ScrollToNode(GetContentChild(5)); EXPECT_TRUE(IsEqualCurrentOffset(Offset::Zero())); pattern_->ScrollToNode(GetContentChild(10)); - EXPECT_TRUE(IsEqualCurrentOffset(Offset(0, -COLUMN_CHILD_HEIGHT))); + EXPECT_TRUE(IsEqualCurrentOffset(Offset(0, -CONTENT_CHILD_HEIGHT))); pattern_->ScrollToNode(GetContentChild(11)); - EXPECT_TRUE(IsEqualCurrentOffset(Offset(0, -COLUMN_CHILD_HEIGHT * 2))); + EXPECT_TRUE(IsEqualCurrentOffset(Offset(0, -CONTENT_CHILD_HEIGHT * 2))); pattern_->ScrollToNode(GetContentChild(0)); EXPECT_TRUE(IsEqualCurrentOffset(Offset::Zero())); @@ -1757,9 +1709,9 @@ HWTEST_F(ScrollTestNg, ScrollToNode001, TestSize.Level1) pattern_->ScrollToNode(GetContentChild(5)); EXPECT_TRUE(IsEqualCurrentOffset(Offset::Zero())); pattern_->ScrollToNode(GetContentChild(10)); - EXPECT_TRUE(IsEqualCurrentOffset(Offset(-COLUMN_CHILD_WIDTH, 0))); + EXPECT_TRUE(IsEqualCurrentOffset(Offset(-CONTENT_CHILD_WIDTH, 0))); pattern_->ScrollToNode(GetContentChild(11)); - EXPECT_TRUE(IsEqualCurrentOffset(Offset(-COLUMN_CHILD_WIDTH * 2, 0))); + EXPECT_TRUE(IsEqualCurrentOffset(Offset(-CONTENT_CHILD_WIDTH * 2, 0))); pattern_->ScrollToNode(GetContentChild(0)); EXPECT_TRUE(IsEqualCurrentOffset(Offset::Zero())); @@ -1770,7 +1722,7 @@ HWTEST_F(ScrollTestNg, ScrollToNode001, TestSize.Level1) CreateScroll(); pattern_->ScrollToNode(frameNode_); EXPECT_TRUE(IsEqualCurrentOffset(Offset::Zero())); - pattern_->ScrollToNode(AceType::DynamicCast(frameNode_->GetChildAtIndex(0))); + pattern_->ScrollToNode(GetChildFrameNode(frameNode_, 0)); EXPECT_TRUE(IsEqualCurrentOffset(Offset::Zero())); } @@ -1801,80 +1753,53 @@ HWTEST_F(ScrollTestNg, Pattern001, TestSize.Level1) } /** - * @tc.name: Pattern004 + * @tc.name: Pattern002 * @tc.desc: Test SetAccessibilityAction * @tc.type: FUNC */ -HWTEST_F(ScrollTestNg, Pattern004, TestSize.Level1) +HWTEST_F(ScrollTestNg, Pattern002, TestSize.Level1) { /** - * @tc.steps: step1. Test SetAccessibilityAction with unScrollable scroll + * @tc.steps: step1. Test SetAccessibilityAction with scrollable scroll + * @tc.expected: Can trigger AnimateTo() + */ + CreateScroll(); + accessibilityProperty_->actionScrollForwardImpl_(); + ASSERT_NE(pattern_->animator_, nullptr); + pattern_->animator_ = nullptr; + accessibilityProperty_->actionScrollBackwardImpl_(); + ASSERT_NE(pattern_->animator_, nullptr); + + /** + * @tc.steps: step2. Test SetAccessibilityAction with unScrollable scroll, scrollableDistance_ <= 0 + * @tc.expected: Cannot trigger AnimateTo() */ ScrollModelNG scrollModel; scrollModel.Create(); GetInstance(); - RunMeasureAndLayout(); - - /** - * @tc.steps: step2. Trigger actionScrollForwardImpl_ - * @tc.expected: Can not ScrollPage - */ + RunMeasureAndLayout(frameNode_); accessibilityProperty_->actionScrollForwardImpl_(); EXPECT_EQ(pattern_->animator_, nullptr); - - /** - * @tc.steps: step3. Trigger actionScrollBackwardImpl_ - * @tc.expected: Can not ScrollPage - */ accessibilityProperty_->actionScrollBackwardImpl_(); EXPECT_EQ(pattern_->animator_, nullptr); /** - * @tc.steps: step4. Test SetAccessibilityAction with Axis::NONE + * @tc.steps: step3. Test SetAccessibilityAction with unScrollable scroll, Axis::NONE + * @tc.expected: Cannot trigger AnimateTo() */ CreateScroll(Axis::NONE); - - /** - * @tc.steps: step5. Trigger actionScrollForwardImpl_ - * @tc.expected: Can not ScrollPage - */ accessibilityProperty_->actionScrollForwardImpl_(); EXPECT_EQ(pattern_->animator_, nullptr); - - /** - * @tc.steps: step6. Trigger actionScrollBackwardImpl_ - * @tc.expected: Can not ScrollPage - */ accessibilityProperty_->actionScrollBackwardImpl_(); EXPECT_EQ(pattern_->animator_, nullptr); - - /** - * @tc.steps: step7. Test SetAccessibilityAction with Axis::Vertical - */ - CreateScroll(); - - /** - * @tc.steps: step8. Trigger actionScrollForwardImpl_ - * @tc.expected: ScrollPage forward, would trigger AnimateTo() - */ - accessibilityProperty_->actionScrollForwardImpl_(); - ASSERT_NE(pattern_->animator_, nullptr); - - /** - * @tc.steps: step9. Trigger actionScrollBackwardImpl_ - * @tc.expected: ScrollPage backward, would trigger AnimateTo() - */ - pattern_->animator_ = nullptr; - accessibilityProperty_->actionScrollBackwardImpl_(); - ASSERT_NE(pattern_->animator_, nullptr); } /** - * @tc.name: Pattern007 + * @tc.name: Pattern003 * @tc.desc: Test HandleScrollBarOutBoundary * @tc.type: FUNC */ -HWTEST_F(ScrollTestNg, Pattern007, TestSize.Level1) +HWTEST_F(ScrollTestNg, Pattern003, TestSize.Level1) { CreateScroll(); @@ -1898,146 +1823,55 @@ HWTEST_F(ScrollTestNg, Pattern007, TestSize.Level1) } /** - * @tc.name: Pattern010 + * @tc.name: Pattern004 * @tc.desc: Test * @tc.type: FUNC */ -HWTEST_F(ScrollTestNg, Pattern010, TestSize.Level1) +HWTEST_F(ScrollTestNg, Pattern004, TestSize.Level1) { /** - * @tc.steps: step1. Test DoJump - */ - CreateScroll(); - - /** - * @tc.steps: step2. jump to a position + * @tc.steps: step1. jump to a position * @tc.expected: CurrentOffset would be to the position */ + CreateScroll(); pattern_->DoJump(-100.f, SCROLL_FROM_UPDATE); EXPECT_TRUE(IsEqualCurrentOffset(Offset(0, -100.f))); /** - * @tc.steps: step3. jump to the same position + * @tc.steps: step2. jump to the same position * @tc.expected: CurrentOffset would not be change */ pattern_->DoJump(-100.f, SCROLL_FROM_UPDATE); EXPECT_TRUE(IsEqualCurrentOffset(Offset(0, -100.f))); /** - * @tc.steps: step4. Test ScrollBy - */ - CreateScroll(); - - /** - * @tc.steps: step5. ScrollBy 0 + * @tc.steps: step3. ScrollBy 0 * @tc.expected: CurrentOffset would not change */ + CreateScroll(); pattern_->ScrollBy(0, 0, false); EXPECT_TRUE(IsEqualCurrentOffset(Offset::Zero())); /** - * @tc.steps: step6. ScrollBy a distance + * @tc.steps: step4. ScrollBy a distance * @tc.expected: Scroll by the distance */ pattern_->ScrollBy(0, -100.f, false); EXPECT_TRUE(IsEqualCurrentOffset(Offset(0, -100.f))); /** - * @tc.steps: step7. Test ScrollToEdge + * @tc.steps: step5. Test different ScrollEdgeType + * @tc.expected: CurrentOffset would be effected by ScrollEdgeType */ CreateScroll(); - - /** - * @tc.steps: step8. ScrollEdgeType::SCROLL_NONE - * @tc.expected: CurrentOffset would not be change - */ pattern_->ScrollToEdge(ScrollEdgeType::SCROLL_NONE, false); EXPECT_TRUE(IsEqualCurrentOffset(Offset::Zero())); - - /** - * @tc.steps: step9. ScrollEdgeType::SCROLL_BOTTOM - * @tc.expected: CurrentOffset would down to bottom - */ pattern_->ScrollToEdge(ScrollEdgeType::SCROLL_BOTTOM, false); - EXPECT_TRUE(IsEqualCurrentOffset(Offset(0, ROOT_HEIGHT - COLUMN_HEIGHT))); - - /** - * @tc.steps: step10. ScrollEdgeType::SCROLL_TOP - * @tc.expected: CurrentOffset would up to top - */ + EXPECT_TRUE(IsEqualCurrentOffset(Offset(0, DEVICE_HEIGHT - CONTENT_HEIGHT))); pattern_->ScrollToEdge(ScrollEdgeType::SCROLL_TOP, false); EXPECT_TRUE(IsEqualCurrentOffset(Offset::Zero())); } -/** - * @tc.name: Pattern011 - * @tc.desc: Test - * @tc.type: FUNC - */ -HWTEST_F(ScrollTestNg, Pattern011, TestSize.Level1) -{ - CreateScroll(EdgeEffect::FADE); - RefPtr scrollEdgeEffect = pattern_->GetScrollEdgeEffect(); - auto scrollFadeEffect = AceType::DynamicCast(scrollEdgeEffect); - scrollFadeEffect->InitialEdgeEffect(); - - Testing::MockCanvas rsCanvas; - OffsetF offset = OffsetF(0, 0); - scrollFadeEffect->fadePainter_->SetOpacity(0); - scrollFadeEffect->fadePainter_->direction_ = OverScrollDirection::UP; - scrollFadeEffect->Paint(rsCanvas, SizeF(1, 1), offset); - scrollFadeEffect->fadePainter_->SetOpacity(1); - scrollFadeEffect->fadePainter_->direction_ = OverScrollDirection::DOWN; - scrollFadeEffect->Paint(rsCanvas, SizeF(0, 1), offset); - scrollFadeEffect->fadePainter_->direction_ = OverScrollDirection::LEFT; - scrollFadeEffect->Paint(rsCanvas, SizeF(1, 0), offset); - scrollFadeEffect->fadePainter_->direction_ = OverScrollDirection::RIGHT; - scrollFadeEffect->Paint(rsCanvas, SizeF(0, 0), offset); - SUCCEED(); -} - -/** - * @tc.name: Pattern012 - * @tc.desc: Test CalcReservedHeight() - * @tc.type: FUNC - */ -HWTEST_F(ScrollTestNg, Pattern012, TestSize.Level1) -{ - CreateScroll(); - auto pipelineContext = PipelineContext::GetCurrentContext(); - pipelineContext->SetMinPlatformVersion(PLATFORM_VERSION_TEN + 1); - auto scrollBar = pattern_->GetScrollBar(); - - scrollBar->SetPositionMode(PositionMode::LEFT); - scrollBar->SetNormalWidth(Dimension(1)); // call CalcReservedHeight; - EXPECT_EQ(scrollBar->startReservedHeight_, Dimension(0.0)); - EXPECT_EQ(scrollBar->endReservedHeight_, Dimension(0.0)); - - BorderRadiusProperty borderRadiusProperty; - float radius = 13.f; - borderRadiusProperty.radiusTopRight = std::make_optional(radius); - borderRadiusProperty.radiusBottomRight = std::make_optional(radius); - scrollBar->SetHostBorderRadius(borderRadiusProperty); - scrollBar->SetPadding(Edge(1, 1, 1, 1)); - scrollBar->SetPositionMode(PositionMode::RIGHT); - scrollBar->SetNormalWidth(Dimension(2)); // call CalcReservedHeight; - EXPECT_EQ(scrollBar->startReservedHeight_, Dimension(14.5)) - << "startReservedHeight_: " << scrollBar->startReservedHeight_.ConvertToPx(); - EXPECT_EQ(scrollBar->endReservedHeight_, Dimension(14.5)) - << "endReservedHeight_: " << scrollBar->endReservedHeight_.ConvertToPx(); - - borderRadiusProperty.radiusBottomLeft = std::make_optional(radius); - borderRadiusProperty.radiusBottomRight = std::make_optional(radius); - scrollBar->SetHostBorderRadius(borderRadiusProperty); - scrollBar->SetPadding(Edge(1, 1, 1, 1)); - scrollBar->SetPositionMode(PositionMode::BOTTOM); - scrollBar->SetNormalWidth(Dimension(6)); // call CalcReservedHeight; - EXPECT_EQ(scrollBar->startReservedHeight_, Dimension(11.25)) - << "startReservedHeight_: " << scrollBar->startReservedHeight_.ConvertToPx(); - EXPECT_EQ(scrollBar->endReservedHeight_, Dimension(11.25)) - << "endReservedHeight_: " << scrollBar->endReservedHeight_.ConvertToPx(); -} - /** * @tc.name: Test001 * @tc.desc: Test GetOverScrollOffset @@ -2047,37 +1881,59 @@ HWTEST_F(ScrollTestNg, Test001, TestSize.Level1) { CreateScroll(); - EXPECT_TRUE( - IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(COLUMN_CHILD_HEIGHT), { COLUMN_CHILD_HEIGHT, 0 })); - EXPECT_TRUE(IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(0.f), { 0, 0 })); - EXPECT_TRUE(IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(-COLUMN_CHILD_HEIGHT), { 0, 0 })); + OverScrollOffset offset = pattern_->GetOverScrollOffset(CONTENT_CHILD_HEIGHT); + OverScrollOffset expectOffset = { CONTENT_CHILD_HEIGHT, 0 }; + EXPECT_TRUE(IsEqualOverScrollOffset(offset, expectOffset)); + offset = pattern_->GetOverScrollOffset(0.f); + expectOffset = { 0, 0 }; + EXPECT_TRUE(IsEqualOverScrollOffset(offset, expectOffset)); + offset = pattern_->GetOverScrollOffset(-CONTENT_CHILD_HEIGHT); + expectOffset = { 0, 0 }; + EXPECT_TRUE(IsEqualOverScrollOffset(offset, expectOffset)); - UpdateCurrentOffset(-COLUMN_CHILD_HEIGHT); - EXPECT_TRUE( - IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(COLUMN_CHILD_HEIGHT * 2), { COLUMN_CHILD_HEIGHT, 0 })); - EXPECT_TRUE(IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(0.f), { 0, 0 })); - EXPECT_TRUE( - IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(-COLUMN_CHILD_HEIGHT * 2), { 0, -COLUMN_CHILD_HEIGHT })); + pattern_->currentOffset_ = -CONTENT_CHILD_HEIGHT; + offset = pattern_->GetOverScrollOffset(CONTENT_CHILD_HEIGHT * 2); + expectOffset = { CONTENT_CHILD_HEIGHT, 0 }; + EXPECT_TRUE(IsEqualOverScrollOffset(offset, expectOffset)); + offset = pattern_->GetOverScrollOffset(0.f); + expectOffset = { 0, 0 }; + EXPECT_TRUE(IsEqualOverScrollOffset(offset, expectOffset)); + offset = pattern_->GetOverScrollOffset(-CONTENT_CHILD_HEIGHT * 2); + expectOffset = { 0, -CONTENT_CHILD_HEIGHT }; + EXPECT_TRUE(IsEqualOverScrollOffset(offset, expectOffset)); - UpdateCurrentOffset(-COLUMN_CHILD_HEIGHT); - EXPECT_TRUE(IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(COLUMN_CHILD_HEIGHT), { 0, 0 })); - EXPECT_TRUE(IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(0.f), { 0, 0 })); - EXPECT_TRUE( - IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(-COLUMN_CHILD_HEIGHT), { 0, -COLUMN_CHILD_HEIGHT })); + pattern_->currentOffset_ = -CONTENT_CHILD_HEIGHT * 2; + offset = pattern_->GetOverScrollOffset(CONTENT_CHILD_HEIGHT); + expectOffset = { 0, 0 }; + EXPECT_TRUE(IsEqualOverScrollOffset(offset, expectOffset)); + offset = pattern_->GetOverScrollOffset(0.f); + expectOffset = { 0, 0 }; + EXPECT_TRUE(IsEqualOverScrollOffset(offset, expectOffset)); + offset = pattern_->GetOverScrollOffset(-CONTENT_CHILD_HEIGHT); + expectOffset = { 0, -CONTENT_CHILD_HEIGHT }; + EXPECT_TRUE(IsEqualOverScrollOffset(offset, expectOffset)); - pattern_->currentOffset_ = COLUMN_CHILD_HEIGHT; - EXPECT_TRUE( - IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(COLUMN_CHILD_HEIGHT), { COLUMN_CHILD_HEIGHT, 0 })); - EXPECT_TRUE(IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(0.f), { 0, 0 })); - EXPECT_TRUE( - IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(-COLUMN_CHILD_HEIGHT * 2), { -COLUMN_CHILD_HEIGHT, 0 })); + pattern_->currentOffset_ = CONTENT_CHILD_HEIGHT; + offset = pattern_->GetOverScrollOffset(CONTENT_CHILD_HEIGHT); + expectOffset = { CONTENT_CHILD_HEIGHT, 0 }; + EXPECT_TRUE(IsEqualOverScrollOffset(offset, expectOffset)); + offset = pattern_->GetOverScrollOffset(0.f); + expectOffset = { 0, 0 }; + EXPECT_TRUE(IsEqualOverScrollOffset(offset, expectOffset)); + offset = pattern_->GetOverScrollOffset(-CONTENT_CHILD_HEIGHT * 2); + expectOffset = { -CONTENT_CHILD_HEIGHT, 0 }; + EXPECT_TRUE(IsEqualOverScrollOffset(offset, expectOffset)); - pattern_->currentOffset_ = -COLUMN_CHILD_HEIGHT * 3; - EXPECT_TRUE( - IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(COLUMN_CHILD_HEIGHT * 2), { 0, COLUMN_CHILD_HEIGHT })); - EXPECT_TRUE(IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(0.f), { 0, 0 })); - EXPECT_TRUE( - IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(-COLUMN_CHILD_HEIGHT), { 0, -COLUMN_CHILD_HEIGHT })); + pattern_->currentOffset_ = -CONTENT_CHILD_HEIGHT * 3; + offset = pattern_->GetOverScrollOffset(CONTENT_CHILD_HEIGHT * 2); + expectOffset = { 0, CONTENT_CHILD_HEIGHT }; + EXPECT_TRUE(IsEqualOverScrollOffset(offset, expectOffset)); + offset = pattern_->GetOverScrollOffset(0.f); + expectOffset = { 0, 0 }; + EXPECT_TRUE(IsEqualOverScrollOffset(offset, expectOffset)); + offset = pattern_->GetOverScrollOffset(-CONTENT_CHILD_HEIGHT); + expectOffset = { 0, -CONTENT_CHILD_HEIGHT }; + EXPECT_TRUE(IsEqualOverScrollOffset(offset, expectOffset)); } /** @@ -2094,10 +1950,10 @@ HWTEST_F(ScrollTestNg, AccessibilityProperty001, TestSize.Level1) ScrollModelNG scrollModel; scrollModel.Create(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_); accessibilityProperty_->ResetSupportAction(); uint64_t expectActions = 0; - EXPECT_EQ(GetActions(), expectActions); + EXPECT_EQ(GetActions(accessibilityProperty_), expectActions); /** * @tc.steps: step2. scroll is at top @@ -2107,28 +1963,28 @@ HWTEST_F(ScrollTestNg, AccessibilityProperty001, TestSize.Level1) accessibilityProperty_->ResetSupportAction(); expectActions = 0; expectActions |= 1UL << static_cast(AceAction::ACTION_SCROLL_FORWARD); - EXPECT_EQ(GetActions(), expectActions); + EXPECT_EQ(GetActions(accessibilityProperty_), expectActions); /** * @tc.steps: step3. scroll to middle * @tc.expected: action is correct */ - UpdateCurrentOffset(-COLUMN_CHILD_HEIGHT); + UpdateCurrentOffset(-CONTENT_CHILD_HEIGHT); accessibilityProperty_->ResetSupportAction(); expectActions = 0; expectActions |= 1UL << static_cast(AceAction::ACTION_SCROLL_FORWARD); expectActions |= 1UL << static_cast(AceAction::ACTION_SCROLL_BACKWARD); - EXPECT_EQ(GetActions(), expectActions); + EXPECT_EQ(GetActions(accessibilityProperty_), expectActions); /** * @tc.steps: step4. scroll to bottom * @tc.expected: action is correct */ - UpdateCurrentOffset(-COLUMN_CHILD_HEIGHT); + UpdateCurrentOffset(-CONTENT_CHILD_HEIGHT); accessibilityProperty_->ResetSupportAction(); expectActions = 0; expectActions |= 1UL << static_cast(AceAction::ACTION_SCROLL_BACKWARD); - EXPECT_EQ(GetActions(), expectActions); + EXPECT_EQ(GetActions(accessibilityProperty_), expectActions); /** * @tc.steps: step6. test IsScrollable() @@ -2142,34 +1998,33 @@ HWTEST_F(ScrollTestNg, AccessibilityProperty001, TestSize.Level1) /** * @tc.name: ScrollSetFrictionTest001 - * @tc.desc: Test ScrollSetFriction + * @tc.desc: Test SetFriction * @tc.type: FUNC */ HWTEST_F(ScrollTestNg, ScrollSetFrictionTest001, TestSize.Level1) { - constexpr double friction = -1; - ScrollModelNG scrollModelNG; - scrollModelNG.Create(); - scrollModelNG.SetFriction(friction); - GetInstance(); /** + * @tc.steps: step1. set friction less than 0 + * @tc.expected: shouled be more than 0.0,if out of range,should be default value. + */ + double friction = -1; + ScrollModelNG scrollModelNG_1; + scrollModelNG_1.Create(); + scrollModelNG_1.SetFriction(friction); + GetInstance(); + RunMeasureAndLayout(frameNode_); + EXPECT_DOUBLE_EQ(pattern_->GetFriction(), DEFAULT_FRICTION); + + /** + * @tc.steps: step1. set friction more than 0 * @tc.expected: friction shouled be more than 0.0,if out of range,should be default value. */ - EXPECT_DOUBLE_EQ(pattern_->GetFriction(), 0.6); -} - -/** - * @tc.name: ScrollSetFrictionTest002 - * @tc.desc: Test ScrollSetFriction - * @tc.type: FUNC - */ -HWTEST_F(ScrollTestNg, ScrollSetFrictionTest002, TestSize.Level1) -{ - constexpr double friction = 10; - ScrollModelNG scrollModelNG; - scrollModelNG.Create(); - scrollModelNG.SetFriction(friction); + friction = 10; + ScrollModelNG scrollModelNG_2; + scrollModelNG_2.Create(); + scrollModelNG_2.SetFriction(friction); GetInstance(); - EXPECT_DOUBLE_EQ(pattern_->GetFriction(), 10); + RunMeasureAndLayout(frameNode_); + EXPECT_DOUBLE_EQ(pattern_->GetFriction(), friction); } } // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/test/pattern/security_component/BUILD.gn b/frameworks/core/components_ng/test/pattern/security_component/BUILD.gn index 073f484d8e5..e804d712904 100644 --- a/frameworks/core/components_ng/test/pattern/security_component/BUILD.gn +++ b/frameworks/core/components_ng/test/pattern/security_component/BUILD.gn @@ -147,10 +147,15 @@ ohos_unittest("security_component_pattern_test_ng") { ] if (security_component_enable) { - sources += [ "$ace_root/frameworks/core/components_ng/pattern/security_component/security_component_probe.cpp" ] + sources += [ + "$ace_root/frameworks/core/components_ng/pattern/security_component/security_component_probe.cpp", + "$ace_root/test/mock/adapter/mock_ace_container.cpp", + ] cflags_cc = [ "-DSECURITY_COMPONENT_ENABLE" ] external_deps = [ + "ability_runtime:abilitykit_native", "access_token:libaccesstoken_sdk", + "napi:ace_napi", "security_component:libsecurity_component_framework", "security_component:libsecurity_component_sdk", ] diff --git a/frameworks/core/components_ng/test/pattern/security_component/security_component_model_test_ng.cpp b/frameworks/core/components_ng/test/pattern/security_component/security_component_model_test_ng.cpp index 26011ec354e..77435581162 100644 --- a/frameworks/core/components_ng/test/pattern/security_component/security_component_model_test_ng.cpp +++ b/frameworks/core/components_ng/test/pattern/security_component/security_component_model_test_ng.cpp @@ -148,13 +148,13 @@ void SecurityComponentModelTestNg::TearDownTestCase() RefPtr SecurityComponentModelTestNg::CreateSecurityComponent(int32_t text, int32_t icon, int32_t backgroundType, std::string type) { - if (type == V2::SEC_LOCATION_BUTTON_ETS_TAG) { + if (type == V2::LOCATION_BUTTON_ETS_TAG) { LocationButtonModelNG locationSc; locationSc.Create(text, icon, backgroundType); - } else if (type == V2::SEC_PASTE_BUTTON_ETS_TAG) { + } else if (type == V2::PASTE_BUTTON_ETS_TAG) { PasteButtonModelNG pasteSc; pasteSc.Create(text, icon, backgroundType); - } else if (type == V2::SEC_SAVE_BUTTON_ETS_TAG) { + } else if (type == V2::SAVE_BUTTON_ETS_TAG) { SaveButtonModelNG saveSc; saveSc.Create(text, icon, backgroundType); } @@ -165,13 +165,13 @@ RefPtr SecurityComponentModelTestNg::CreateSecurityComponent(int32_t void SecurityComponentModelTestNg::CreateSecurityComponentNotFinish(int32_t text, int32_t icon, int32_t backgroundType, std::string type) { - if (type == V2::SEC_LOCATION_BUTTON_ETS_TAG) { + if (type == V2::LOCATION_BUTTON_ETS_TAG) { LocationButtonModelNG locationSc; locationSc.Create(text, icon, backgroundType); - } else if (type == V2::SEC_PASTE_BUTTON_ETS_TAG) { + } else if (type == V2::PASTE_BUTTON_ETS_TAG) { PasteButtonModelNG pasteSc; pasteSc.Create(text, icon, backgroundType); - } else if (type == V2::SEC_SAVE_BUTTON_ETS_TAG) { + } else if (type == V2::SAVE_BUTTON_ETS_TAG) { SaveButtonModelNG saveSc; saveSc.Create(text, icon, backgroundType); } @@ -196,7 +196,6 @@ void SecurityComponentModelTestNg::SetLocationUserDefinedPropty() sc.SetBackgroundPadding(Dimension(25.0)); // 25.0 vp sc.SetTextIconSpace(Dimension(25.0)); // 25.0 vp sc.SetTextIconLayoutDirection(SecurityComponentLayoutDirection::VERTICAL); - sc.SetlayoutOrder(SecSecurityComponentLayoutOrder::TEXT_FIRST); } void SecurityComponentModelTestNg::SetPasteUserDefinedPropty() @@ -218,7 +217,6 @@ void SecurityComponentModelTestNg::SetPasteUserDefinedPropty() sc.SetBackgroundPadding(Dimension(25.0)); // 25.0 vp sc.SetTextIconSpace(Dimension(25.0)); // 25.0 vp sc.SetTextIconLayoutDirection(SecurityComponentLayoutDirection::VERTICAL); - sc.SetlayoutOrder(SecSecurityComponentLayoutOrder::TEXT_FIRST); } void SecurityComponentModelTestNg::SetSaveUserDefinedPropty() @@ -240,7 +238,6 @@ void SecurityComponentModelTestNg::SetSaveUserDefinedPropty() sc.SetBackgroundPadding(Dimension(25.0)); // 25.0 vp sc.SetTextIconSpace(Dimension(25.0)); // 25.0 vp sc.SetTextIconLayoutDirection(SecurityComponentLayoutDirection::VERTICAL); - sc.SetlayoutOrder(SecSecurityComponentLayoutOrder::TEXT_FIRST); } RefPtr SecurityComponentModelTestNg::CreateLayoutWrapper(RefPtr& node) @@ -299,8 +296,6 @@ void SecurityComponentModelTestNg::CheckSecurityComponentDefaultProp(RefPtrGetBackgroundLeftPadding().value_or(Dimension(0.0)).ConvertToVp(), DEFAULT_PADDING); EXPECT_EQ(property->GetTextIconLayoutDirection().value_or(SecurityComponentLayoutDirection::VERTICAL), SecurityComponentLayoutDirection::HORIZONTAL); - EXPECT_EQ(property->GetLayoutOrder().value_or(SecSecurityComponentLayoutOrder::TEXT_FIRST), - SecSecurityComponentLayoutOrder::ICON_FIRST); } /** @@ -312,9 +307,9 @@ void SecurityComponentModelTestNg::CheckSecurityComponentDefaultProp(RefPtr frameNode = CreateSecurityComponent(0, 0, static_cast(ButtonType::CAPSULE), - V2::SEC_LOCATION_BUTTON_ETS_TAG); + V2::LOCATION_BUTTON_ETS_TAG); ASSERT_NE(frameNode, nullptr); - ASSERT_EQ(frameNode->GetTag(), V2::SEC_LOCATION_BUTTON_ETS_TAG); + ASSERT_EQ(frameNode->GetTag(), V2::LOCATION_BUTTON_ETS_TAG); CheckSecurityComponentDefaultProp(frameNode); @@ -368,9 +363,9 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentLocationPropertyTest001, HWTEST_F(SecurityComponentModelTestNg, SecurityComponentLocationPropertyTest002, TestSize.Level1) { RefPtr frameNode = CreateSecurityComponent(0, 0, - BUTTON_TYPE_NULL, V2::SEC_LOCATION_BUTTON_ETS_TAG); + BUTTON_TYPE_NULL, V2::LOCATION_BUTTON_ETS_TAG); ASSERT_NE(frameNode, nullptr); - ASSERT_EQ(frameNode->GetTag(), V2::SEC_LOCATION_BUTTON_ETS_TAG); + ASSERT_EQ(frameNode->GetTag(), V2::LOCATION_BUTTON_ETS_TAG); auto property = frameNode->GetLayoutProperty(); ASSERT_NE(property, nullptr); @@ -415,9 +410,9 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentLocationPropertyTest002, HWTEST_F(SecurityComponentModelTestNg, SecurityComponentLocationPropertyTest003, TestSize.Level1) { RefPtr frameNode = CreateSecurityComponent(1, -1, - BUTTON_TYPE_NULL, V2::SEC_LOCATION_BUTTON_ETS_TAG); + BUTTON_TYPE_NULL, V2::LOCATION_BUTTON_ETS_TAG); ASSERT_NE(frameNode, nullptr); - ASSERT_EQ(frameNode->GetTag(), V2::SEC_LOCATION_BUTTON_ETS_TAG); + ASSERT_EQ(frameNode->GetTag(), V2::LOCATION_BUTTON_ETS_TAG); auto property = frameNode->GetLayoutProperty(); ASSERT_NE(property, nullptr); @@ -436,7 +431,7 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentLocationPropertyTest003, */ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentLocationPropertyTest004, TestSize.Level1) { - CreateSecurityComponentNotFinish(0, 0, static_cast(ButtonType::CAPSULE), V2::SEC_LOCATION_BUTTON_ETS_TAG); + CreateSecurityComponentNotFinish(0, 0, static_cast(ButtonType::CAPSULE), V2::LOCATION_BUTTON_ETS_TAG); SetLocationUserDefinedPropty(); auto frameNode = ViewStackProcessor::GetInstance()->GetMainFrameNode(); ASSERT_NE(frameNode, nullptr); @@ -449,8 +444,6 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentLocationPropertyTest004, EXPECT_EQ(property->GetBackgroundBottomPadding().value_or(Dimension(0.0)).ConvertToVp(), 25.0); // 25.0 vp EXPECT_EQ(property->GetTextIconLayoutDirection().value_or(SecurityComponentLayoutDirection::HORIZONTAL), SecurityComponentLayoutDirection::VERTICAL); - EXPECT_EQ(property->GetLayoutOrder().value_or(SecSecurityComponentLayoutOrder::ICON_FIRST), - SecSecurityComponentLayoutOrder::TEXT_FIRST); auto iconNode = GetCurSecCompChildNode(V2::IMAGE_ETS_TAG); ASSERT_NE(iconNode, nullptr); @@ -495,7 +488,7 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentLocationPropertyTest004, */ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentLocationPropertyTest005, TestSize.Level1) { - CreateSecurityComponentNotFinish(0, 0, static_cast(ButtonType::CAPSULE), V2::SEC_LOCATION_BUTTON_ETS_TAG); + CreateSecurityComponentNotFinish(0, 0, static_cast(ButtonType::CAPSULE), V2::LOCATION_BUTTON_ETS_TAG); SetLocationUserDefinedPropty(); auto frameNode = ViewStackProcessor::GetInstance()->GetMainFrameNode(); ASSERT_NE(frameNode, nullptr); @@ -508,8 +501,6 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentLocationPropertyTest005, EXPECT_EQ(property->GetBackgroundBottomPadding().value_or(Dimension(0.0)).ConvertToVp(), 25.0); // 25.0 vp EXPECT_EQ(property->GetTextIconLayoutDirection().value_or(SecurityComponentLayoutDirection::HORIZONTAL), SecurityComponentLayoutDirection::VERTICAL); - EXPECT_EQ(property->GetLayoutOrder().value_or(SecSecurityComponentLayoutOrder::ICON_FIRST), - SecSecurityComponentLayoutOrder::TEXT_FIRST); auto iconNode = GetCurSecCompChildNode(V2::IMAGE_ETS_TAG); ASSERT_NE(iconNode, nullptr); @@ -554,7 +545,7 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentLocationPropertyTest005, */ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentLocationPropertyTest006, TestSize.Level1) { - CreateSecurityComponentNotFinish(0, 0, BUTTON_TYPE_NULL, V2::SEC_LOCATION_BUTTON_ETS_TAG); + CreateSecurityComponentNotFinish(0, 0, BUTTON_TYPE_NULL, V2::LOCATION_BUTTON_ETS_TAG); LocationButtonModelNG locationSc; locationSc.SetBackgroundColor(Color::GRAY); locationSc.SetBackgroundBorderWidth(Dimension(15.0)); // 15.0 vp @@ -594,7 +585,7 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentLocationPropertyTest006, HWTEST_F(SecurityComponentModelTestNg, SecurityComponentLocationPropertyTest007, TestSize.Level1) { CreateSecurityComponentNotFinish(1, -1, static_cast(ButtonType::CAPSULE), - V2::SEC_LOCATION_BUTTON_ETS_TAG); + V2::LOCATION_BUTTON_ETS_TAG); LocationButtonModelNG locationSc; locationSc.SetTextIconSpace(Dimension(15.0)); // 15.0vp @@ -614,9 +605,9 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentLocationPropertyTest007, HWTEST_F(SecurityComponentModelTestNg, SecurityComponentLocationPatternTest001, TestSize.Level1) { RefPtr frameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_LOCATION_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::LOCATION_BUTTON_ETS_TAG); ASSERT_NE(frameNode, nullptr); - ASSERT_EQ(frameNode->GetTag(), V2::SEC_LOCATION_BUTTON_ETS_TAG); + ASSERT_EQ(frameNode->GetTag(), V2::LOCATION_BUTTON_ETS_TAG); auto pattern = frameNode->GetPattern(); ASSERT_NE(pattern, nullptr); @@ -643,9 +634,9 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentLocationPatternTest001, HWTEST_F(SecurityComponentModelTestNg, SecurityComponentLocationPatternTest002, TestSize.Level1) { RefPtr frameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_LOCATION_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::LOCATION_BUTTON_ETS_TAG); ASSERT_NE(frameNode, nullptr); - ASSERT_EQ(frameNode->GetTag(), V2::SEC_LOCATION_BUTTON_ETS_TAG); + ASSERT_EQ(frameNode->GetTag(), V2::LOCATION_BUTTON_ETS_TAG); auto pattern = frameNode->GetPattern(); ASSERT_NE(pattern, nullptr); @@ -677,9 +668,9 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentLocationPatternTest002, HWTEST_F(SecurityComponentModelTestNg, SecurityComponentLocationLayoutAlgoTest001, TestSize.Level1) { RefPtr frameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_LOCATION_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::LOCATION_BUTTON_ETS_TAG); ASSERT_NE(frameNode, nullptr); - ASSERT_EQ(frameNode->GetTag(), V2::SEC_LOCATION_BUTTON_ETS_TAG); + ASSERT_EQ(frameNode->GetTag(), V2::LOCATION_BUTTON_ETS_TAG); auto pattern = frameNode->GetPattern(); ASSERT_NE(pattern, nullptr); pattern->OnModifyDone(); @@ -697,7 +688,6 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentLocationLayoutAlgoTest00 ASSERT_NE(property, nullptr); property->UpdateBackgroundType(static_cast(ButtonType::CAPSULE)); property->UpdateTextIconLayoutDirection(SecurityComponentLayoutDirection::VERTICAL); - property->UpdateLayoutOrder(SecSecurityComponentLayoutOrder::ICON_FIRST); pattern->OnModifyDone(); layoutAlgo->Measure(layoutWrapper.rawPtr_); @@ -706,7 +696,6 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentLocationLayoutAlgoTest00 property->UpdateBackgroundType(static_cast(ButtonType::CIRCLE)); property->UpdateTextIconLayoutDirection(SecurityComponentLayoutDirection::VERTICAL); - property->UpdateLayoutOrder(SecSecurityComponentLayoutOrder::ICON_FIRST); pattern->OnModifyDone(); layoutAlgo->Measure(layoutWrapper.rawPtr_); @@ -723,9 +712,9 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentLocationLayoutAlgoTest00 HWTEST_F(SecurityComponentModelTestNg, SecurityComponentLocationAccessibilityPropertyTest001, TestSize.Level1) { RefPtr frameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_LOCATION_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::LOCATION_BUTTON_ETS_TAG); ASSERT_NE(frameNode, nullptr); - ASSERT_EQ(frameNode->GetTag(), V2::SEC_LOCATION_BUTTON_ETS_TAG); + ASSERT_EQ(frameNode->GetTag(), V2::LOCATION_BUTTON_ETS_TAG); auto pattern = frameNode->GetPattern(); ASSERT_NE(pattern, nullptr); pattern->OnModifyDone(); @@ -744,9 +733,9 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentLocationAccessibilityPro HWTEST_F(SecurityComponentModelTestNg, SecurityComponentSavePropertyTest001, TestSize.Level1) { RefPtr frameNode = CreateSecurityComponent(0, 0, static_cast(ButtonType::CAPSULE), - V2::SEC_SAVE_BUTTON_ETS_TAG); + V2::SAVE_BUTTON_ETS_TAG); ASSERT_NE(frameNode, nullptr); - ASSERT_EQ(frameNode->GetTag(), V2::SEC_SAVE_BUTTON_ETS_TAG); + ASSERT_EQ(frameNode->GetTag(), V2::SAVE_BUTTON_ETS_TAG); CheckSecurityComponentDefaultProp(frameNode); @@ -800,9 +789,9 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentSavePropertyTest001, Tes HWTEST_F(SecurityComponentModelTestNg, SecurityComponentSavePropertyTest002, TestSize.Level1) { RefPtr frameNode = CreateSecurityComponent(0, 0, - BUTTON_TYPE_NULL, V2::SEC_SAVE_BUTTON_ETS_TAG); + BUTTON_TYPE_NULL, V2::SAVE_BUTTON_ETS_TAG); ASSERT_NE(frameNode, nullptr); - ASSERT_EQ(frameNode->GetTag(), V2::SEC_SAVE_BUTTON_ETS_TAG); + ASSERT_EQ(frameNode->GetTag(), V2::SAVE_BUTTON_ETS_TAG); auto property = frameNode->GetLayoutProperty(); ASSERT_NE(property, nullptr); @@ -847,9 +836,9 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentSavePropertyTest002, Tes HWTEST_F(SecurityComponentModelTestNg, SecurityComponentSavePropertyTest003, TestSize.Level1) { RefPtr frameNode = CreateSecurityComponent(1, -1, - BUTTON_TYPE_NULL, V2::SEC_SAVE_BUTTON_ETS_TAG); + BUTTON_TYPE_NULL, V2::SAVE_BUTTON_ETS_TAG); ASSERT_NE(frameNode, nullptr); - ASSERT_EQ(frameNode->GetTag(), V2::SEC_SAVE_BUTTON_ETS_TAG); + ASSERT_EQ(frameNode->GetTag(), V2::SAVE_BUTTON_ETS_TAG); auto property = frameNode->GetLayoutProperty(); ASSERT_NE(property, nullptr); @@ -868,7 +857,7 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentSavePropertyTest003, Tes */ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentSavePropertyTest004, TestSize.Level1) { - CreateSecurityComponentNotFinish(0, 0, static_cast(ButtonType::CAPSULE), V2::SEC_SAVE_BUTTON_ETS_TAG); + CreateSecurityComponentNotFinish(0, 0, static_cast(ButtonType::CAPSULE), V2::SAVE_BUTTON_ETS_TAG); SetSaveUserDefinedPropty(); auto frameNode = ViewStackProcessor::GetInstance()->GetMainFrameNode(); ASSERT_NE(frameNode, nullptr); @@ -881,8 +870,6 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentSavePropertyTest004, Tes EXPECT_EQ(property->GetBackgroundBottomPadding().value_or(Dimension(0.0)).ConvertToVp(), 25.0); // 25.0 vp EXPECT_EQ(property->GetTextIconLayoutDirection().value_or(SecurityComponentLayoutDirection::HORIZONTAL), SecurityComponentLayoutDirection::VERTICAL); - EXPECT_EQ(property->GetLayoutOrder().value_or(SecSecurityComponentLayoutOrder::ICON_FIRST), - SecSecurityComponentLayoutOrder::TEXT_FIRST); auto iconNode = GetCurSecCompChildNode(V2::IMAGE_ETS_TAG); ASSERT_NE(iconNode, nullptr); @@ -927,7 +914,7 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentSavePropertyTest004, Tes */ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentSavePropertyTest005, TestSize.Level1) { - CreateSecurityComponentNotFinish(0, 0, static_cast(ButtonType::CAPSULE), V2::SEC_SAVE_BUTTON_ETS_TAG); + CreateSecurityComponentNotFinish(0, 0, static_cast(ButtonType::CAPSULE), V2::SAVE_BUTTON_ETS_TAG); SetSaveUserDefinedPropty(); auto frameNode = ViewStackProcessor::GetInstance()->GetMainFrameNode(); ASSERT_NE(frameNode, nullptr); @@ -940,8 +927,6 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentSavePropertyTest005, Tes EXPECT_EQ(property->GetBackgroundBottomPadding().value_or(Dimension(0.0)).ConvertToVp(), 25.0); // 25.0 vp EXPECT_EQ(property->GetTextIconLayoutDirection().value_or(SecurityComponentLayoutDirection::HORIZONTAL), SecurityComponentLayoutDirection::VERTICAL); - EXPECT_EQ(property->GetLayoutOrder().value_or(SecSecurityComponentLayoutOrder::ICON_FIRST), - SecSecurityComponentLayoutOrder::TEXT_FIRST); auto iconNode = GetCurSecCompChildNode(V2::IMAGE_ETS_TAG); ASSERT_NE(iconNode, nullptr); @@ -986,7 +971,7 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentSavePropertyTest005, Tes */ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentSavePropertyTest006, TestSize.Level1) { - CreateSecurityComponentNotFinish(0, 0, BUTTON_TYPE_NULL, V2::SEC_SAVE_BUTTON_ETS_TAG); + CreateSecurityComponentNotFinish(0, 0, BUTTON_TYPE_NULL, V2::SAVE_BUTTON_ETS_TAG); SaveButtonModelNG saveSc; saveSc.SetBackgroundColor(Color::GRAY); saveSc.SetBackgroundBorderWidth(Dimension(15.0)); // 15.0 vp @@ -1027,7 +1012,7 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentSavePropertyTest006, Tes HWTEST_F(SecurityComponentModelTestNg, SecurityComponentSavePropertyTest007, TestSize.Level1) { CreateSecurityComponentNotFinish(1, -1, static_cast(ButtonType::CAPSULE), - V2::SEC_SAVE_BUTTON_ETS_TAG); + V2::SAVE_BUTTON_ETS_TAG); SaveButtonModelNG saveSc; saveSc.SetTextIconSpace(Dimension(15.0)); // 15.0vp @@ -1047,9 +1032,9 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentSavePropertyTest007, Tes HWTEST_F(SecurityComponentModelTestNg, SecurityComponentSavePatternTest001, TestSize.Level1) { RefPtr frameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_SAVE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::SAVE_BUTTON_ETS_TAG); ASSERT_NE(frameNode, nullptr); - ASSERT_EQ(frameNode->GetTag(), V2::SEC_SAVE_BUTTON_ETS_TAG); + ASSERT_EQ(frameNode->GetTag(), V2::SAVE_BUTTON_ETS_TAG); auto pattern = frameNode->GetPattern(); ASSERT_NE(pattern, nullptr); @@ -1076,9 +1061,9 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentSavePatternTest001, Test HWTEST_F(SecurityComponentModelTestNg, SecurityComponentSavePatternTest002, TestSize.Level1) { RefPtr frameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_SAVE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::SAVE_BUTTON_ETS_TAG); ASSERT_NE(frameNode, nullptr); - ASSERT_EQ(frameNode->GetTag(), V2::SEC_SAVE_BUTTON_ETS_TAG); + ASSERT_EQ(frameNode->GetTag(), V2::SAVE_BUTTON_ETS_TAG); auto pattern = frameNode->GetPattern(); ASSERT_NE(pattern, nullptr); @@ -1110,9 +1095,9 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentSavePatternTest002, Test HWTEST_F(SecurityComponentModelTestNg, SecurityComponentSaveLayoutAlgoTest001, TestSize.Level1) { RefPtr frameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_SAVE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::SAVE_BUTTON_ETS_TAG); ASSERT_NE(frameNode, nullptr); - ASSERT_EQ(frameNode->GetTag(), V2::SEC_SAVE_BUTTON_ETS_TAG); + ASSERT_EQ(frameNode->GetTag(), V2::SAVE_BUTTON_ETS_TAG); auto pattern = frameNode->GetPattern(); ASSERT_NE(pattern, nullptr); pattern->OnModifyDone(); @@ -1130,7 +1115,6 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentSaveLayoutAlgoTest001, T ASSERT_NE(property, nullptr); property->UpdateBackgroundType(static_cast(ButtonType::CAPSULE)); property->UpdateTextIconLayoutDirection(SecurityComponentLayoutDirection::VERTICAL); - property->UpdateLayoutOrder(SecSecurityComponentLayoutOrder::ICON_FIRST); pattern->OnModifyDone(); layoutAlgo->Measure(layoutWrapper.rawPtr_); @@ -1147,9 +1131,9 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentSaveLayoutAlgoTest001, T HWTEST_F(SecurityComponentModelTestNg, SecurityComponentSaveAccessibilityPropertyTest001, TestSize.Level1) { RefPtr frameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_SAVE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::SAVE_BUTTON_ETS_TAG); ASSERT_NE(frameNode, nullptr); - ASSERT_EQ(frameNode->GetTag(), V2::SEC_SAVE_BUTTON_ETS_TAG); + ASSERT_EQ(frameNode->GetTag(), V2::SAVE_BUTTON_ETS_TAG); auto pattern = frameNode->GetPattern(); ASSERT_NE(pattern, nullptr); pattern->OnModifyDone(); @@ -1168,9 +1152,9 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentSaveAccessibilityPropert HWTEST_F(SecurityComponentModelTestNg, SecurityComponentPastePropertyTest001, TestSize.Level1) { RefPtr frameNode = CreateSecurityComponent(0, 0, static_cast(ButtonType::CAPSULE), - V2::SEC_PASTE_BUTTON_ETS_TAG); + V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(frameNode, nullptr); - ASSERT_EQ(frameNode->GetTag(), V2::SEC_PASTE_BUTTON_ETS_TAG); + ASSERT_EQ(frameNode->GetTag(), V2::PASTE_BUTTON_ETS_TAG); CheckSecurityComponentDefaultProp(frameNode); @@ -1224,9 +1208,9 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentPastePropertyTest001, Te HWTEST_F(SecurityComponentModelTestNg, SecurityComponentPastePropertyTest002, TestSize.Level1) { RefPtr frameNode = CreateSecurityComponent(0, 0, - BUTTON_TYPE_NULL, V2::SEC_PASTE_BUTTON_ETS_TAG); + BUTTON_TYPE_NULL, V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(frameNode, nullptr); - ASSERT_EQ(frameNode->GetTag(), V2::SEC_PASTE_BUTTON_ETS_TAG); + ASSERT_EQ(frameNode->GetTag(), V2::PASTE_BUTTON_ETS_TAG); auto property = frameNode->GetLayoutProperty(); ASSERT_NE(property, nullptr); @@ -1271,9 +1255,9 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentPastePropertyTest002, Te HWTEST_F(SecurityComponentModelTestNg, SecurityComponentPastePropertyTest003, TestSize.Level1) { RefPtr frameNode = CreateSecurityComponent(1, -1, - BUTTON_TYPE_NULL, V2::SEC_PASTE_BUTTON_ETS_TAG); + BUTTON_TYPE_NULL, V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(frameNode, nullptr); - ASSERT_EQ(frameNode->GetTag(), V2::SEC_PASTE_BUTTON_ETS_TAG); + ASSERT_EQ(frameNode->GetTag(), V2::PASTE_BUTTON_ETS_TAG); auto property = frameNode->GetLayoutProperty(); ASSERT_NE(property, nullptr); @@ -1292,7 +1276,7 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentPastePropertyTest003, Te */ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentPastePropertyTest004, TestSize.Level1) { - CreateSecurityComponentNotFinish(0, 0, static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + CreateSecurityComponentNotFinish(0, 0, static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); SetPasteUserDefinedPropty(); auto frameNode = ViewStackProcessor::GetInstance()->GetMainFrameNode(); ASSERT_NE(frameNode, nullptr); @@ -1305,8 +1289,6 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentPastePropertyTest004, Te EXPECT_EQ(property->GetBackgroundBottomPadding().value_or(Dimension(0.0)).ConvertToVp(), 25.0); // 25.0 vp EXPECT_EQ(property->GetTextIconLayoutDirection().value_or(SecurityComponentLayoutDirection::HORIZONTAL), SecurityComponentLayoutDirection::VERTICAL); - EXPECT_EQ(property->GetLayoutOrder().value_or(SecSecurityComponentLayoutOrder::ICON_FIRST), - SecSecurityComponentLayoutOrder::TEXT_FIRST); auto iconNode = GetCurSecCompChildNode(V2::IMAGE_ETS_TAG); ASSERT_NE(iconNode, nullptr); @@ -1351,7 +1333,7 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentPastePropertyTest004, Te */ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentPastePropertyTest005, TestSize.Level1) { - CreateSecurityComponentNotFinish(0, 0, static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + CreateSecurityComponentNotFinish(0, 0, static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); SetPasteUserDefinedPropty(); auto frameNode = ViewStackProcessor::GetInstance()->GetMainFrameNode(); ASSERT_NE(frameNode, nullptr); @@ -1364,8 +1346,6 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentPastePropertyTest005, Te EXPECT_EQ(property->GetBackgroundBottomPadding().value_or(Dimension(0.0)).ConvertToVp(), 25.0); // 25.0 vp EXPECT_EQ(property->GetTextIconLayoutDirection().value_or(SecurityComponentLayoutDirection::HORIZONTAL), SecurityComponentLayoutDirection::VERTICAL); - EXPECT_EQ(property->GetLayoutOrder().value_or(SecSecurityComponentLayoutOrder::ICON_FIRST), - SecSecurityComponentLayoutOrder::TEXT_FIRST); auto iconNode = GetCurSecCompChildNode(V2::IMAGE_ETS_TAG); ASSERT_NE(iconNode, nullptr); @@ -1410,7 +1390,7 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentPastePropertyTest005, Te */ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentPastePropertyTest006, TestSize.Level1) { - CreateSecurityComponentNotFinish(0, 0, BUTTON_TYPE_NULL, V2::SEC_PASTE_BUTTON_ETS_TAG); + CreateSecurityComponentNotFinish(0, 0, BUTTON_TYPE_NULL, V2::PASTE_BUTTON_ETS_TAG); PasteButtonModelNG pasteSc; pasteSc.SetBackgroundColor(Color::GRAY); pasteSc.SetBackgroundBorderWidth(Dimension(15.0)); // 15.0 vp @@ -1451,7 +1431,7 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentPastePropertyTest006, Te HWTEST_F(SecurityComponentModelTestNg, SecurityComponentPastePropertyTest007, TestSize.Level1) { CreateSecurityComponentNotFinish(1, -1, static_cast(ButtonType::CAPSULE), - V2::SEC_PASTE_BUTTON_ETS_TAG); + V2::PASTE_BUTTON_ETS_TAG); PasteButtonModelNG pasteSc; pasteSc.SetTextIconSpace(Dimension(15.0)); // 15.0vp @@ -1471,9 +1451,9 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentPastePropertyTest007, Te HWTEST_F(SecurityComponentModelTestNg, SecurityComponentPastePatternTest001, TestSize.Level1) { RefPtr frameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(frameNode, nullptr); - ASSERT_EQ(frameNode->GetTag(), V2::SEC_PASTE_BUTTON_ETS_TAG); + ASSERT_EQ(frameNode->GetTag(), V2::PASTE_BUTTON_ETS_TAG); auto pattern = frameNode->GetPattern(); ASSERT_NE(pattern, nullptr); @@ -1500,9 +1480,9 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentPastePatternTest001, Tes HWTEST_F(SecurityComponentModelTestNg, SecurityComponentPastePatternTest002, TestSize.Level1) { RefPtr frameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(frameNode, nullptr); - ASSERT_EQ(frameNode->GetTag(), V2::SEC_PASTE_BUTTON_ETS_TAG); + ASSERT_EQ(frameNode->GetTag(), V2::PASTE_BUTTON_ETS_TAG); auto pattern = frameNode->GetPattern(); ASSERT_NE(pattern, nullptr); @@ -1534,9 +1514,9 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentPastePatternTest002, Tes HWTEST_F(SecurityComponentModelTestNg, SecurityComponentPasteLayoutAlgoTest001, TestSize.Level1) { RefPtr frameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(frameNode, nullptr); - ASSERT_EQ(frameNode->GetTag(), V2::SEC_PASTE_BUTTON_ETS_TAG); + ASSERT_EQ(frameNode->GetTag(), V2::PASTE_BUTTON_ETS_TAG); auto pattern = frameNode->GetPattern(); ASSERT_NE(pattern, nullptr); pattern->OnModifyDone(); @@ -1554,7 +1534,6 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentPasteLayoutAlgoTest001, ASSERT_NE(property, nullptr); property->UpdateBackgroundType(static_cast(ButtonType::CAPSULE)); property->UpdateTextIconLayoutDirection(SecurityComponentLayoutDirection::VERTICAL); - property->UpdateLayoutOrder(SecSecurityComponentLayoutOrder::ICON_FIRST); pattern->OnModifyDone(); layoutAlgo->Measure(layoutWrapper.rawPtr_); @@ -1571,9 +1550,9 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentPasteLayoutAlgoTest001, HWTEST_F(SecurityComponentModelTestNg, SecurityComponentPasteAccessibilityPropertyTest001, TestSize.Level1) { RefPtr frameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(frameNode, nullptr); - ASSERT_EQ(frameNode->GetTag(), V2::SEC_PASTE_BUTTON_ETS_TAG); + ASSERT_EQ(frameNode->GetTag(), V2::PASTE_BUTTON_ETS_TAG); auto pattern = frameNode->GetPattern(); ASSERT_NE(pattern, nullptr); pattern->OnModifyDone(); @@ -1610,7 +1589,7 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentGetIconResourceTest001, HWTEST_F(SecurityComponentModelTestNg, SecurityComponentHandlerTest001, TestSize.Level1) { RefPtr frameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); RefPtr invalidFrameNode = CreateSecurityComponent(0, 0, static_cast(ButtonType::CAPSULE), "test"); int32_t scId; @@ -1632,7 +1611,7 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentHandlerTest001, TestSize HWTEST_F(SecurityComponentModelTestNg, SecurityComponentHandlerTest002, TestSize.Level1) { RefPtr frameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_SAVE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::SAVE_BUTTON_ETS_TAG); int32_t scId; GestureEvent info; @@ -1652,7 +1631,7 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentHandlerTest002, TestSize HWTEST_F(SecurityComponentModelTestNg, SecurityComponentHandlerTest003, TestSize.Level1) { RefPtr frameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_LOCATION_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::LOCATION_BUTTON_ETS_TAG); int32_t scId; GestureEvent info; @@ -1672,7 +1651,7 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentHandlerTest003, TestSize HWTEST_F(SecurityComponentModelTestNg, SecurityComponentHandlerTest004, TestSize.Level1) { RefPtr frameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); int32_t scId; GestureEvent info; @@ -1692,10 +1671,10 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentHandlerTest004, TestSize HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTest001, TestSize.Level1) { RefPtr parentFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(parentFrameNode, nullptr); RefPtr childFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(childFrameNode, nullptr); parentFrameNode->AddChild(childFrameNode); ASSERT_FALSE(SecurityComponentHandler::CheckParentNodesEffect(childFrameNode)); @@ -1716,10 +1695,10 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTe HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTest002, TestSize.Level1) { RefPtr parentFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(parentFrameNode, nullptr); RefPtr childFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(childFrameNode, nullptr); parentFrameNode->AddChild(childFrameNode); ASSERT_FALSE(SecurityComponentHandler::CheckParentNodesEffect(childFrameNode)); @@ -1739,10 +1718,10 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTe HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTest003, TestSize.Level1) { RefPtr parentFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(parentFrameNode, nullptr); RefPtr childFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(childFrameNode, nullptr); parentFrameNode->AddChild(childFrameNode); ASSERT_FALSE(SecurityComponentHandler::CheckParentNodesEffect(childFrameNode)); @@ -1764,10 +1743,10 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTe HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTest004, TestSize.Level1) { RefPtr parentFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(parentFrameNode, nullptr); RefPtr childFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(childFrameNode, nullptr); parentFrameNode->AddChild(childFrameNode); ASSERT_FALSE(SecurityComponentHandler::CheckParentNodesEffect(childFrameNode)); @@ -1789,10 +1768,10 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTe HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTest005, TestSize.Level1) { RefPtr parentFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(parentFrameNode, nullptr); RefPtr childFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(childFrameNode, nullptr); parentFrameNode->AddChild(childFrameNode); ASSERT_FALSE(SecurityComponentHandler::CheckParentNodesEffect(childFrameNode)); @@ -1813,10 +1792,10 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTe HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTest006, TestSize.Level1) { RefPtr parentFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(parentFrameNode, nullptr); RefPtr childFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(childFrameNode, nullptr); parentFrameNode->AddChild(childFrameNode); ASSERT_FALSE(SecurityComponentHandler::CheckParentNodesEffect(childFrameNode)); @@ -1836,10 +1815,10 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTe HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTest007, TestSize.Level1) { RefPtr parentFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(parentFrameNode, nullptr); RefPtr childFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(childFrameNode, nullptr); parentFrameNode->AddChild(childFrameNode); ASSERT_FALSE(SecurityComponentHandler::CheckParentNodesEffect(childFrameNode)); @@ -1861,10 +1840,10 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTe HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTest008, TestSize.Level1) { RefPtr parentFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(parentFrameNode, nullptr); RefPtr childFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(childFrameNode, nullptr); parentFrameNode->AddChild(childFrameNode); ASSERT_FALSE(SecurityComponentHandler::CheckParentNodesEffect(childFrameNode)); @@ -1888,10 +1867,10 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTe HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTest009, TestSize.Level1) { RefPtr parentFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(parentFrameNode, nullptr); RefPtr childFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(childFrameNode, nullptr); parentFrameNode->AddChild(childFrameNode); ASSERT_FALSE(SecurityComponentHandler::CheckParentNodesEffect(childFrameNode)); @@ -1913,10 +1892,10 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTe HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTest010, TestSize.Level1) { RefPtr parentFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(parentFrameNode, nullptr); RefPtr childFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(childFrameNode, nullptr); parentFrameNode->AddChild(childFrameNode); ASSERT_FALSE(SecurityComponentHandler::CheckParentNodesEffect(childFrameNode)); @@ -1938,10 +1917,10 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTe HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTest011, TestSize.Level1) { RefPtr parentFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(parentFrameNode, nullptr); RefPtr childFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(childFrameNode, nullptr); parentFrameNode->AddChild(childFrameNode); ASSERT_FALSE(SecurityComponentHandler::CheckParentNodesEffect(childFrameNode)); @@ -1963,10 +1942,10 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTe HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTest012, TestSize.Level1) { RefPtr parentFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(parentFrameNode, nullptr); RefPtr childFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(childFrameNode, nullptr); parentFrameNode->AddChild(childFrameNode); ASSERT_FALSE(SecurityComponentHandler::CheckParentNodesEffect(childFrameNode)); @@ -1988,10 +1967,10 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTe HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTest013, TestSize.Level1) { RefPtr parentFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(parentFrameNode, nullptr); RefPtr childFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(childFrameNode, nullptr); parentFrameNode->AddChild(childFrameNode); ASSERT_FALSE(SecurityComponentHandler::CheckParentNodesEffect(childFrameNode)); @@ -2013,10 +1992,10 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTe HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTest014, TestSize.Level1) { RefPtr parentFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(parentFrameNode, nullptr); RefPtr childFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(childFrameNode, nullptr); parentFrameNode->AddChild(childFrameNode); ASSERT_FALSE(SecurityComponentHandler::CheckParentNodesEffect(childFrameNode)); @@ -2036,10 +2015,10 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTe HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTest015, TestSize.Level1) { RefPtr parentFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(parentFrameNode, nullptr); RefPtr childFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(childFrameNode, nullptr); parentFrameNode->AddChild(childFrameNode); ASSERT_FALSE(SecurityComponentHandler::CheckParentNodesEffect(childFrameNode)); @@ -2061,10 +2040,10 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTe HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTest016, TestSize.Level1) { RefPtr parentFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(parentFrameNode, nullptr); RefPtr childFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(childFrameNode, nullptr); parentFrameNode->AddChild(childFrameNode); ASSERT_FALSE(SecurityComponentHandler::CheckParentNodesEffect(childFrameNode)); @@ -2086,10 +2065,10 @@ HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTe HWTEST_F(SecurityComponentModelTestNg, SecurityComponentCheckParentNodesEffectTest017, TestSize.Level1) { RefPtr parentFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(parentFrameNode, nullptr); RefPtr childFrameNode = CreateSecurityComponent(0, 0, - static_cast(ButtonType::CAPSULE), V2::SEC_PASTE_BUTTON_ETS_TAG); + static_cast(ButtonType::CAPSULE), V2::PASTE_BUTTON_ETS_TAG); ASSERT_NE(childFrameNode, nullptr); parentFrameNode->AddChild(childFrameNode); ASSERT_FALSE(SecurityComponentHandler::CheckParentNodesEffect(childFrameNode)); diff --git a/frameworks/core/components_ng/test/pattern/select_overlay/BUILD.gn b/frameworks/core/components_ng/test/pattern/select_overlay/BUILD.gn index 948c380982b..ffc1693ba94 100644 --- a/frameworks/core/components_ng/test/pattern/select_overlay/BUILD.gn +++ b/frameworks/core/components_ng/test/pattern/select_overlay/BUILD.gn @@ -22,6 +22,7 @@ ohos_unittest("select_overlay_test_ng") { "$ace_root/frameworks/core/animation/test/mock/mock_scheduler.cpp", "$ace_root/frameworks/core/common/container_scope.cpp", "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_node.cpp", + "$ace_root/frameworks/core/components_ng/manager/safe_area/safe_area_manager.cpp", "$ace_root/frameworks/core/components_ng/pattern/custom/custom_node.cpp", "$ace_root/frameworks/core/components_ng/pattern/image/image_layout_algorithm.cpp", "$ace_root/frameworks/core/components_ng/pattern/image/image_modifier.cpp", diff --git a/frameworks/core/components_ng/test/pattern/side_bar/BUILD.gn b/frameworks/core/components_ng/test/pattern/side_bar/BUILD.gn index 92a4353072d..f4b8f97a240 100644 --- a/frameworks/core/components_ng/test/pattern/side_bar/BUILD.gn +++ b/frameworks/core/components_ng/test/pattern/side_bar/BUILD.gn @@ -141,6 +141,8 @@ ohos_unittest("side_bar_pattern_test_ng") { "$ace_root/frameworks/core/components/test/unittest/mock/ace_trace_mock.cpp", "$ace_root/frameworks/core/components_ng/test/mock/animation/mock_geometry_transition.cpp", "$ace_root/frameworks/core/components_ng/test/mock/base/mock_localization.cpp", + "$ace_root/frameworks/core/components_ng/test/mock/pattern/button/mock_button_layout_algorithm.cpp", + "$ace_root/frameworks/core/components_ng/test/mock/pattern/button/mock_button_pattern.cpp", "$ace_root/frameworks/core/components_ng/test/mock/pattern/grid_container/mock_grid_container_layout_property.cpp", "$ace_root/frameworks/core/components_ng/test/mock/render/mock_animation_utils.cpp", "$ace_root/frameworks/core/components_ng/test/mock/render/mock_modifier_adapter.cpp", diff --git a/frameworks/core/components_ng/test/pattern/side_bar/side_bar_pattern_test_ng.cpp b/frameworks/core/components_ng/test/pattern/side_bar/side_bar_pattern_test_ng.cpp index cfd55557487..d307d6052a8 100644 --- a/frameworks/core/components_ng/test/pattern/side_bar/side_bar_pattern_test_ng.cpp +++ b/frameworks/core/components_ng/test/pattern/side_bar/side_bar_pattern_test_ng.cpp @@ -23,6 +23,7 @@ #include "core/components_ng/base/ui_node.h" #include "core/components_ng/base/view_stack_processor.h" #include "core/components_ng/event/gesture_event_hub.h" +#include "core/components_ng/pattern/button/button_layout_property.h" #include "core/components_ng/pattern/image/image_pattern.h" #include "core/components_ng/pattern/pattern.h" #include "core/components_ng/pattern/side_bar/side_bar_container_layout_property.h" @@ -60,6 +61,12 @@ constexpr float FLOAT_240 = 240.0f; const std::string SHOW_ICON_STR = "123"; const std::string HIDDEN_ICON_STR = "123"; const std::string SWITCHING_ICON_STR = "123"; +constexpr Dimension IMAGE_WIDTH = 10.0_vp; +constexpr Dimension IMAGE_HEIGHT = 10.0_vp; +constexpr Dimension DEFAULT_IMAGE_WIDTH_V10 = 24.0_vp; +constexpr Dimension DEFAULT_IMAGE_HEIGHT_V10 = 24.0_vp; +constexpr int32_t PLATFORM_VERSION_9 = 9; +constexpr int32_t PLATFORM_VERSION_10 = 10; } // namespace class SideBarPatternTestNg : public testing::Test { @@ -360,8 +367,12 @@ HWTEST_F(SideBarPatternTestNg, SideBarPatternTestNg011, TestSize.Level1) auto sideBarTheme = AceType::MakeRefPtr(); ASSERT_NE(sideBarTheme, nullptr); Color controlButtonColor = sideBarTheme->GetControlImageColor(); - - auto imgFrameNode = AceType::DynamicCast(children.front()); + auto buttonFrameNode = AceType::DynamicCast(children.front()); + ASSERT_NE(buttonFrameNode, nullptr); + auto buttonChildren = buttonFrameNode->GetChildren(); + ASSERT_FALSE(buttonChildren.empty()); + auto imgFrameNode = AceType::DynamicCast(buttonChildren.front()); + ASSERT_NE(imgFrameNode, nullptr); auto imageLayoutProperty = imgFrameNode->GetLayoutProperty(); ASSERT_NE(imageLayoutProperty, nullptr); @@ -950,7 +961,12 @@ HWTEST_F(SideBarPatternTestNg, SideBarPatternTestNg031, TestSize.Level1) ASSERT_NE(sideBarTheme, nullptr); Color controlButtonColor = sideBarTheme->GetControlImageColor(); - auto imgFrameNode = AceType::DynamicCast(children.front()); + auto buttonFrameNode = AceType::DynamicCast(children.front()); + ASSERT_NE(buttonFrameNode, nullptr); + auto buttonChildren = buttonFrameNode->GetChildren(); + ASSERT_FALSE(buttonChildren.empty()); + auto imgFrameNode = AceType::DynamicCast(buttonChildren.front()); + ASSERT_NE(imgFrameNode, nullptr); auto imageLayoutProperty = imgFrameNode->GetLayoutProperty(); ASSERT_NE(imageLayoutProperty, nullptr); auto imgSourceInfo = imageLayoutProperty->GetImageSourceInfoValue(); @@ -959,46 +975,67 @@ HWTEST_F(SideBarPatternTestNg, SideBarPatternTestNg031, TestSize.Level1) /** * @tc.name: SideBarPatternTestNg032 - * @tc.desc: Test SideBar InitControlButtonMouseEvent + * @tc.desc: Test SideBar OnUpdateShowControlButton * @tc.type: FUNC */ HWTEST_F(SideBarPatternTestNg, SideBarPatternTestNg032, TestSize.Level1) { /** - * @tc.steps: step1. create sideBar and controlbutton node,then register inputEvent to inputeEventHub. - * @tc.expected: check whether the controlButtonHoverEvent_ is not nullptr. + * @tc.steps: step1. create control button. */ + SideBarContainerModelNG SideBarContainerModelInstance; auto pattern = AceType::MakeRefPtr(); ASSERT_NE(pattern, nullptr); auto* stack = ViewStackProcessor::GetInstance(); auto nodeId = stack->ClaimNodeId(); auto frameNode = FrameNode::CreateFrameNode("Test", nodeId, pattern); ASSERT_NE(frameNode, nullptr); + stack->Push(frameNode); pattern->AttachToFrameNode(frameNode); - int32_t imgNodeId = ElementRegister::GetInstance()->MakeUniqueId(); - auto imgNode = FrameNode::GetOrCreateFrameNode( - OHOS::Ace::V2::IMAGE_ETS_TAG, imgNodeId, []() { return AceType::MakeRefPtr(); }); - ASSERT_NE(imgNode, nullptr); - auto imgHub = imgNode->GetEventHub(); - ASSERT_NE(imgHub, nullptr); - auto inputHub = imgHub->GetOrCreateInputEventHub(); - ASSERT_NE(inputHub, nullptr); - pattern->SetHasControlButton(true); - EXPECT_EQ(pattern->controlButtonHoverEvent_, nullptr); - pattern->InitControlButtonMouseEvent(inputHub); - EXPECT_NE(pattern->controlButtonHoverEvent_, nullptr); + + auto themeManagerOne = AceType::MakeRefPtr(); + MockPipelineBase::GetCurrent()->SetThemeManager(themeManagerOne); + EXPECT_CALL(*themeManagerOne, GetTheme(_)).WillRepeatedly(Return(AceType::MakeRefPtr())); + SideBarContainerModelInstance.CreateAndMountControlButton(frameNode); + + /** + * @tc.steps: step2. Set showControlButton's value to false, then execute OnUpdateShowControlButton. + * @tc.expected: button is not visible. + */ + auto layoutProperty = pattern->GetLayoutProperty(); + ASSERT_NE(layoutProperty, nullptr); + layoutProperty->UpdateShowControlButton(false); + pattern->OnUpdateShowControlButton(layoutProperty, frameNode); + + auto children = frameNode->GetChildren(); + ASSERT_FALSE(children.empty()); + auto buttonFrameNode = AceType::DynamicCast(children.front()); + ASSERT_NE(buttonFrameNode, nullptr); + auto buttonLayoutProperty = buttonFrameNode->GetLayoutProperty(); + ASSERT_NE(buttonLayoutProperty, nullptr); + auto visibility = buttonLayoutProperty->GetVisibility(); + EXPECT_EQ(visibility, VisibleType::GONE); + + /** + * @tc.steps: step3. Set showControlButton's value to true, then execute OnUpdateShowControlButton. + * @tc.expected: button is visible. + */ + layoutProperty->UpdateShowControlButton(true); + pattern->OnUpdateShowControlButton(layoutProperty, frameNode); + buttonLayoutProperty = buttonFrameNode->GetLayoutProperty(); + visibility = buttonLayoutProperty->GetVisibility(); + EXPECT_EQ(visibility, VisibleType::VISIBLE); } /** * @tc.name: SideBarPatternTestNg033 - * @tc.desc: Test SideBar OnControlButtonHover + * @tc.desc: Test SideBar GetControlImageSize * @tc.type: FUNC */ HWTEST_F(SideBarPatternTestNg, SideBarPatternTestNg033, TestSize.Level1) { /** - * @tc.steps: step1. create sideBarContainer frameNode, then execute OnControlButtonHover method(hover is true). - * @tc.expected: check whether the isControlButtonHover_ is false. + * @tc.steps: step1. create sidebarContainer frame node. */ auto pattern = AceType::MakeRefPtr(); ASSERT_NE(pattern, nullptr); @@ -1006,83 +1043,33 @@ HWTEST_F(SideBarPatternTestNg, SideBarPatternTestNg033, TestSize.Level1) auto nodeId = stack->ClaimNodeId(); auto frameNode = FrameNode::CreateFrameNode("Test", nodeId, pattern); ASSERT_NE(frameNode, nullptr); + stack->Push(frameNode); pattern->AttachToFrameNode(frameNode); - pattern->OnControlButtonHover(true); - EXPECT_FALSE(pattern->isControlButtonHover_); + /** + * @tc.steps: step2. Set platform version to 10, then execute GetControlImageSize. + * @tc.expected: image's width is 24vp, and height is 24vp. + */ + auto pipeline = PipelineContext::GetCurrentContext(); + CHECK_NULL_VOID(pipeline); + pipeline->SetMinPlatformVersion(PLATFORM_VERSION_10); + Dimension width; + Dimension height; + pattern->GetControlImageSize(width, height); + EXPECT_EQ(width, DEFAULT_IMAGE_WIDTH_V10); + EXPECT_EQ(height, DEFAULT_IMAGE_HEIGHT_V10); /** - * @tc.steps: step2. create controlButton node,and mount controlButton node to its parent frameNode. - * Then execute OnControlButtonHover method(hover is true). - * @tc.expected: check whether the isControlButtonHover_ is true. + * @tc.steps: step3. Set image's width and height to 10vp, then execute GetControlImageSize. + * @tc.expected: image's width is 10vp, and height is 10vp. */ - int32_t imgNodeId = ElementRegister::GetInstance()->MakeUniqueId(); - auto imgNode = FrameNode::GetOrCreateFrameNode( - OHOS::Ace::V2::IMAGE_ETS_TAG, imgNodeId, []() { return AceType::MakeRefPtr(); }); - ASSERT_NE(imgNode, nullptr); - imgNode->MountToParent(frameNode); - pattern->OnControlButtonHover(true); - EXPECT_TRUE(pattern->isControlButtonHover_); - - /** - * @tc.steps: step3. remove hover from the controlButton. - * @tc.expected: check whether the isControlButtonHover_ is false. - */ - pattern->OnControlButtonHover(false); - EXPECT_FALSE(pattern->isControlButtonHover_); -} - -/** - * @tc.name: SideBarPatternTestNg034 - * @tc.desc: Test SideBar HandleMouseEvent - * @tc.type: FUNC - */ -HWTEST_F(SideBarPatternTestNg, SideBarPatternTestNg034, TestSize.Level1) -{ - /** - * @tc.steps: step1. create sideBarContainer frameNode,then execute HandleMouseEvent method. - * @tc.expected: check whether the isControlButtonHover_ is false. - */ - auto pattern = AceType::MakeRefPtr(); - ASSERT_NE(pattern, nullptr); - auto* stack = ViewStackProcessor::GetInstance(); - auto nodeId = stack->ClaimNodeId(); - auto frameNode = FrameNode::CreateFrameNode("Test", nodeId, pattern); - ASSERT_NE(frameNode, nullptr); - pattern->AttachToFrameNode(frameNode); - - MouseInfo info; - info.SetAction(MouseAction::PRESS); - info.SetButton(MouseButton::LEFT_BUTTON); - pattern->HandleMouseEvent(info); - EXPECT_FALSE(pattern->isControlButtonHover_); - - /** - * @tc.steps: step2. create controlButton frameNode, and mount it to its parent frameNode. - * Then execute HandleMouseEvent method. - * @tc.expected: check whether the isControlButtonHover_ is false. - */ - int32_t imgNodeId = ElementRegister::GetInstance()->MakeUniqueId(); - auto imgNode = FrameNode::GetOrCreateFrameNode( - OHOS::Ace::V2::IMAGE_ETS_TAG, imgNodeId, []() { return AceType::MakeRefPtr(); }); - ASSERT_NE(imgNode, nullptr); - imgNode->MountToParent(frameNode); - - pattern->HandleMouseEvent(info); - EXPECT_FALSE(pattern->isControlButtonHover_); - - /** - * @tc.steps: step3. execute OnControlButtonHover method(hover is true). - * @tc.expected: check whether the isControlButtonHover_ is true. - */ - pattern->OnControlButtonHover(true); - pattern->HandleMouseEvent(info); - info.SetAction(MouseAction::RELEASE); - pattern->HandleMouseEvent(info); - info.SetAction(MouseAction::HOVER_ENTER); - pattern->HandleMouseEvent(info); - info.SetButton(MouseButton::RIGHT_BUTTON); - pattern->HandleMouseEvent(info); - EXPECT_TRUE(pattern->isControlButtonHover_); + pipeline->SetMinPlatformVersion(PLATFORM_VERSION_9); + auto layoutProperty = pattern->GetLayoutProperty(); + ASSERT_NE(layoutProperty, nullptr); + layoutProperty->UpdateControlButtonWidth(IMAGE_WIDTH); + layoutProperty->UpdateControlButtonHeight(IMAGE_HEIGHT); + pattern->GetControlImageSize(width, height); + EXPECT_EQ(width, IMAGE_WIDTH); + EXPECT_EQ(height, IMAGE_HEIGHT); } } // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/test/pattern/slider/slider_pattern_test_ng.cpp b/frameworks/core/components_ng/test/pattern/slider/slider_pattern_test_ng.cpp index 945fba650e8..ef60e1d1074 100644 --- a/frameworks/core/components_ng/test/pattern/slider/slider_pattern_test_ng.cpp +++ b/frameworks/core/components_ng/test/pattern/slider/slider_pattern_test_ng.cpp @@ -434,7 +434,6 @@ HWTEST_F(SliderPatternTestNg, SliderPatternTestNg005, TestSize.Level1) TouchEventInfo info(""); info.changedTouches_.emplace_back(LInfo); sliderPattern->HandleTouchEvent(info); - EXPECT_EQ(sliderPattern->hotFlag_, true); sliderPattern->showTips_ = true; sliderPattern->HandleTouchEvent(info); EXPECT_EQ(sliderPattern->bubbleFlag_, true); @@ -450,8 +449,6 @@ HWTEST_F(SliderPatternTestNg, SliderPatternTestNg005, TestSize.Level1) */ info.changedTouches_.front().touchType_ = TouchType::UP; sliderPattern->HandleTouchEvent(info); - EXPECT_EQ(sliderPattern->hotFlag_, false); - sliderPattern->HandleTouchEvent(info); EXPECT_EQ(sliderPattern->bubbleFlag_, false); } @@ -535,8 +532,8 @@ HWTEST_F(SliderPatternTestNg, SliderPatternTestNg007, TestSize.Level1) info.SetOffsetX(.0); info.SetOffsetY(1.0); sliderPattern->HandlingGestureEvent(info); - EXPECT_EQ(sliderPattern->valueRatio_, .0f); - EXPECT_EQ(sliderPattern->value_, .0f); + EXPECT_EQ(sliderPattern->valueRatio_, .02f); + EXPECT_EQ(sliderPattern->value_, 2.0f); /** * @tc.cases: case2. InputEventType is AXIS and MoveStep(1). */ @@ -690,7 +687,6 @@ HWTEST_F(SliderPatternTestNg, SliderPatternTestNg010, TestSize.Level1) * @tc.cases: case1. mouse down position is outside the block side, UpdateValueByLocalLocation */ sliderPattern->HandleTouchEvent(info); - EXPECT_EQ(sliderPattern->hotFlag_, true); EXPECT_NE(sliderPattern->value_, .0f); /** * @tc.cases: case2. mouse down position is inside the block side, not UpdateValueByLocalLocation @@ -765,6 +761,68 @@ HWTEST_F(SliderPatternTestNg, SliderPatternTestNg011, TestSize.Level1) EXPECT_FALSE(sliderPattern->valueChangeFlag_); } +/** + * @tc.name: SliderPatternTestNg012 + * @tc.desc: Test Slider mouse Event and wheel operation + * @tc.type: FUNC + */ +HWTEST_F(SliderPatternTestNg, SliderPatternTestNg012, TestSize.Level1) +{ + /** + * @tc.steps: step1. create frameNode and set theme. + */ + SliderModelNG sliderModelNG; + sliderModelNG.Create(MIN, STEP, MIN, MAX); + auto frameNode = AceType::DynamicCast(ViewStackProcessor::GetInstance()->Finish()); + ASSERT_NE(frameNode, nullptr); + frameNode->geometryNode_->SetContentSize(SizeF(MAX_WIDTH, MAX_HEIGHT)); + auto sliderPattern = frameNode->GetPattern(); + ASSERT_NE(sliderPattern, nullptr); + auto sliderLayoutProperty = frameNode->GetLayoutProperty(); + ASSERT_NE(sliderLayoutProperty, nullptr); + auto themeManager = AceType::MakeRefPtr(); + PipelineBase::GetCurrentContext()->SetThemeManager(themeManager); + auto sliderTheme = AceType::MakeRefPtr(); + EXPECT_CALL(*themeManager, GetTheme(_)).WillRepeatedly(Return(sliderTheme)); + sliderPattern->mouseHoverFlag_ = true; + sliderPattern->showTips_ = true; + /** + * @tc.steps: step2. When the mouse moves into the slider area. + */ + sliderPattern->HandleHoverEvent(true); + EXPECT_TRUE(sliderPattern->hotFlag_); + EXPECT_TRUE(sliderPattern->mouseHoverFlag_); + /** + * @tc.steps: step3. When the mouse wheel starts scrolling. + */ + GestureEvent info; + info.inputEventType_ = InputEventType::AXIS; + sliderPattern->HandlingGestureEvent(info); + EXPECT_TRUE(sliderPattern->bubbleFlag_); + EXPECT_TRUE(sliderPattern->AxisFlag_); + /** + * @tc.steps: step4. After the mouse wheel starts scrolling, move the mouse out of the slider area + */ + sliderLayoutProperty->UpdateDirection(Axis::VERTICAL); + sliderPattern->HandleHoverEvent(false); + EXPECT_FALSE(sliderPattern->hotFlag_); + EXPECT_FALSE(sliderPattern->mouseHoverFlag_); + EXPECT_FALSE(sliderPattern->bubbleFlag_); + EXPECT_FALSE(sliderPattern->AxisFlag_); + /** + * @tc.steps: step5. When moving the mouse out of the slider area, mouse wheel starts scrolling quickly. + * @tc.desc: SliderTips will not show. + */ + sliderPattern->HandleHoverEvent(true); + sliderPattern->HandleHoverEvent(false); + sliderPattern->HandlingGestureEvent(info); + EXPECT_FALSE(sliderPattern->hotFlag_); + EXPECT_FALSE(sliderPattern->mouseHoverFlag_); + EXPECT_FALSE(sliderPattern->bubbleFlag_); + EXPECT_FALSE(sliderPattern->AxisFlag_); +} + + /** * @tc.name: SliderLayoutAlgorithm001 * @tc.desc: Test SliderLayoutAlgorithm MeasureContent. diff --git a/frameworks/core/components_ng/test/pattern/test_ng.cpp b/frameworks/core/components_ng/test/pattern/test_ng.cpp new file mode 100644 index 00000000000..816ab8ad9b5 --- /dev/null +++ b/frameworks/core/components_ng/test/pattern/test_ng.cpp @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "core/components_ng/test/pattern/test_ng.h" + +namespace OHOS::Ace::NG { +void TestNG::SetWidth(const Dimension& width) +{ + auto frameNode = ViewStackProcessor::GetInstance()->GetMainFrameNode(); + auto layoutProperty = frameNode->GetLayoutProperty(); + layoutProperty->UpdateUserDefinedIdealSize(CalcSize(CalcLength(width), std::nullopt)); +} + +void TestNG::SetHeight(const Dimension& height) +{ + auto frameNode = ViewStackProcessor::GetInstance()->GetMainFrameNode(); + auto layoutProperty = frameNode->GetLayoutProperty(); + layoutProperty->UpdateUserDefinedIdealSize(CalcSize(std::nullopt, CalcLength(height))); +} + +RefPtr TestNG::RunMeasureAndLayout(const RefPtr& frameNode, float width, float height) +{ + RefPtr layoutWrapper = frameNode->CreateLayoutWrapper(false, false); + layoutWrapper->SetActive(); + layoutWrapper->SetRootMeasureNode(); + LayoutConstraintF LayoutConstraint; + LayoutConstraint.parentIdealSize = { DEVICE_WIDTH, DEVICE_HEIGHT }; + LayoutConstraint.percentReference = { DEVICE_WIDTH, DEVICE_HEIGHT }; + if (NonNegative(width) && NonNegative(height)) { + LayoutConstraint.selfIdealSize = { width, height }; + } + LayoutConstraint.maxSize = { DEVICE_WIDTH, DEVICE_HEIGHT }; + layoutWrapper->Measure(LayoutConstraint); + layoutWrapper->Layout(); + layoutWrapper->MountToHostOnMainThread(); + return layoutWrapper; +} + +uint64_t TestNG::GetActions(const RefPtr& accessibilityProperty) +{ + std::unordered_set supportAceActions = accessibilityProperty->GetSupportAction(); + uint64_t actions = 0; + for (auto action : supportAceActions) { + actions |= 1UL << static_cast(action); + } + return actions; +} + +testing::AssertionResult TestNG::IsEqualOffset(Offset offset, Offset expectOffset) +{ + if (offset == expectOffset) { + return testing::AssertionSuccess(); + } + return testing::AssertionFailure() << + "offset: " << offset.ToString() << + " != " << + "expectOffset: " << expectOffset.ToString(); +} + +testing::AssertionResult TestNG::IsEqualOverScrollOffset(OverScrollOffset offset, OverScrollOffset expectOffset) +{ + if (NearEqual(offset.start, expectOffset.start) && NearEqual(offset.end, expectOffset.end)) { + return testing::AssertionSuccess(); + } + return testing::AssertionFailure() << "offset: " + << "{ " << offset.start << " , " << offset.end << " }" + << " != " + << "expectOffset: " + << "{ " << expectOffset.start << " , " << expectOffset.end << " }"; +} + +testing::AssertionResult TestNG::IsEqualRect(Rect rect, Rect expectRect) +{ + if (rect == expectRect) { + return testing::AssertionSuccess(); + } + return testing::AssertionFailure() << + "rect: " << rect.ToString() << + " != " << + "expectRect: " << expectRect.ToString(); +} + +testing::AssertionResult TestNG::IsEqualRect(RectF rect, RectF expectRect) +{ + if (rect == expectRect) { + return testing::AssertionSuccess(); + } + return testing::AssertionFailure() << + "rect: " << rect.ToString() << + " != " << + "expectRect: " << expectRect.ToString(); +} +} // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/test/pattern/test_ng.h b/frameworks/core/components_ng/test/pattern/test_ng.h new file mode 100644 index 00000000000..7fcc356fa6b --- /dev/null +++ b/frameworks/core/components_ng/test/pattern/test_ng.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_NG_TEST_PATTERN_TEST_NG_H +#define FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_NG_TEST_PATTERN_TEST_NG_H + +#include "gtest/gtest.h" + +#include "base/geometry/axis.h" +#include "base/geometry/dimension.h" +#include "base/memory/ace_type.h" +#include "base/memory/referenced.h" +#include "base/utils/utils.h" +#include "core/components_ng/base/frame_node.h" +#include "core/components_ng/base/view_stack_processor.h" + +namespace OHOS::Ace::NG { +namespace { +using namespace testing; +using namespace testing::ext; +constexpr int32_t PLATFORM_VERSION_TEN = 10; +constexpr float DEVICE_WIDTH = 480.f; +constexpr float DEVICE_HEIGHT = 800.f; +constexpr Dimension FILL_LENGTH = Dimension(1.0, DimensionUnit::PERCENT); +} // namespace + +class TestNG { +public: + static void SetWidth(const Dimension& width); + static void SetHeight(const Dimension& height); + RefPtr RunMeasureAndLayout(const RefPtr& frameNode, + float width = DEVICE_WIDTH, float height = DEVICE_HEIGHT); + uint64_t GetActions(const RefPtr& accessibilityProperty); + + testing::AssertionResult IsEqualOffset(Offset offset, Offset expectOffset); + testing::AssertionResult IsEqualOverScrollOffset(OverScrollOffset offset, OverScrollOffset expectOffset); + testing::AssertionResult IsEqualRect(Rect rect, Rect expectRect); + testing::AssertionResult IsEqualRect(RectF rect, RectF expectRect); + + RefPtr GetChildFrameNode(const RefPtr& frameNode, int32_t index) + { + return AceType::DynamicCast(frameNode->GetChildAtIndex(index)); + } + + RefPtr GetChildFocusHub(const RefPtr& frameNode, int32_t index) + { + return GetChildFrameNode(frameNode, index)->GetOrCreateFocusHub(); + } + + template + RefPtr GetChildPattern(const RefPtr& frameNode, int32_t index) + { + RefPtr pattern = GetChildFrameNode(frameNode, index)->GetPattern(); + return AceType::DynamicCast(pattern); + } + + const RectF& GetChildRect(const RefPtr& frameNode, int32_t index) + { + return GetChildFrameNode(frameNode, index)->GetGeometryNode()->GetFrameRect(); + } +}; +} // namespace OHOS::Ace::NG + +#endif // FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_NG_PATTERNS_SCROLL_SCROLL_PATTERN_H diff --git a/frameworks/core/components_ng/test/pattern/text/text_test_ng.cpp b/frameworks/core/components_ng/test/pattern/text/text_test_ng.cpp index b87132b96c0..da58f3990dc 100644 --- a/frameworks/core/components_ng/test/pattern/text/text_test_ng.cpp +++ b/frameworks/core/components_ng/test/pattern/text/text_test_ng.cpp @@ -2170,7 +2170,7 @@ HWTEST_F(TextTestNg, TextContentModifier002, TestSize.Level1) MockPipelineBase::SetUp(); // set textDecorationAnimatable_ true textContentModifier.textDecorationAnimatable_ = true; - textContentModifier.oldTextDecoration_ = TextDecoration::UNDERLINE; + textContentModifier.textDecoration_ = TextDecoration::UNDERLINE; textContentModifier.SetTextDecoration(TextDecoration::NONE); textContentModifier.ModifyTextStyle(textStyle); // set textDecorationColorAlpha_ value diff --git a/frameworks/core/components_ng/test/pattern/text_clock/BUILD.gn b/frameworks/core/components_ng/test/pattern/text_clock/BUILD.gn index 5dce8f8b07a..f942d478fd1 100644 --- a/frameworks/core/components_ng/test/pattern/text_clock/BUILD.gn +++ b/frameworks/core/components_ng/test/pattern/text_clock/BUILD.gn @@ -25,6 +25,7 @@ ace_unittest("text_clock_test_ng") { "$ace_root/frameworks/core/components_ng/pattern/text/text_paint_method.cpp", "$ace_root/frameworks/core/components_ng/pattern/text/text_styles.cpp", "$ace_root/frameworks/core/components_ng/pattern/text_clock/text_clock_accessibility_property.cpp", + "$ace_root/frameworks/core/components_ng/pattern/text_clock/text_clock_layout_algorithm.cpp", "$ace_root/frameworks/core/components_ng/pattern/text_clock/text_clock_layout_property.cpp", "$ace_root/frameworks/core/components_ng/pattern/text_clock/text_clock_model_ng.cpp", "$ace_root/frameworks/core/components_ng/pattern/text_clock/text_clock_pattern.cpp", diff --git a/frameworks/core/components_ng/test/pattern/time_picker/timepicker_test_ng.cpp b/frameworks/core/components_ng/test/pattern/time_picker/timepicker_test_ng.cpp index 0f5846cb538..22ee1096c86 100644 --- a/frameworks/core/components_ng/test/pattern/time_picker/timepicker_test_ng.cpp +++ b/frameworks/core/components_ng/test/pattern/time_picker/timepicker_test_ng.cpp @@ -97,6 +97,7 @@ constexpr int32_t CHILD_WITH_AMPM_SIZE = 3; const double YOFFSET_START1 = 0.0; const double YOFFSET_END1 = 1000.0; const double TIME_PLUS = 1 * 100.0; +const SizeF TEST_FRAME_SIZE { 20, 50 }; } // namespace class TimePickerPatternTestNg : public testing::Test { public: @@ -1884,4 +1885,43 @@ HWTEST_F(TimePickerPatternTestNg, PerformActionTest001, TestSize.Level1) EXPECT_TRUE(accessibilityProperty->ActActionScrollForward()); EXPECT_TRUE(accessibilityProperty->ActActionScrollBackward()); } + +/** + * @tc.name: TimePickerAlgorithmTest001 + * @tc.desc: Test Measure. + * @tc.type: FUNC + */ +HWTEST_F(TimePickerPatternTestNg, TimePickerAlgorithmTest001, TestSize.Level1) +{ + /** + * @tc.step: step1. create frameNode and pattern. + */ + auto theme = MockPipelineBase::GetCurrent()->GetTheme(); + TimePickerModelNG::GetInstance()->CreateTimePicker(theme); + auto frameNode = AceType::DynamicCast(ViewStackProcessor::GetInstance()->Finish()); + ASSERT_TRUE(frameNode); + frameNode->MarkModifyDone(); + auto pickerProperty = frameNode->GetLayoutProperty(); + auto layoutConstraint = LayoutConstraintF(); + layoutConstraint.selfIdealSize.SetWidth(20); + auto timePickerRowPattern = frameNode->GetPattern(); + ASSERT_TRUE(timePickerRowPattern); + auto allChildNode = timePickerRowPattern->GetAllChildNode(); + auto minuteColumn = allChildNode["minute"]; + ASSERT_TRUE(minuteColumn); + auto minuteColumnPattern = minuteColumn->GetPattern(); + ASSERT_TRUE(minuteColumnPattern); + LayoutWrapperNode layoutWrapper = LayoutWrapperNode(minuteColumn, minuteColumn->GetGeometryNode(), pickerProperty); + layoutWrapper.GetLayoutProperty()->UpdateLayoutConstraint(layoutConstraint); + layoutWrapper.GetLayoutProperty()->UpdateContentConstraint(); + /** + * @tc.step: step2. initialize TimePickerColumnLayoutAlgorithm and call Measure + * and Layout function. + */ + TimePickerColumnLayoutAlgorithm timePickerColumnLayoutAlgorithm; + timePickerColumnLayoutAlgorithm.Measure(&layoutWrapper); + timePickerColumnLayoutAlgorithm.Layout(&layoutWrapper); + auto frameSize = layoutWrapper.geometryNode_->GetFrameSize(); + EXPECT_EQ(frameSize, TEST_FRAME_SIZE); +} } // namespace OHOS::Ace::NG diff --git a/frameworks/core/components_ng/test/pattern/waterflow/BUILD.gn b/frameworks/core/components_ng/test/pattern/waterflow/BUILD.gn index 84ca4c1e230..3c8294c2962 100644 --- a/frameworks/core/components_ng/test/pattern/waterflow/BUILD.gn +++ b/frameworks/core/components_ng/test/pattern/waterflow/BUILD.gn @@ -112,6 +112,7 @@ ohos_unittest("water_flow_test_ng") { "$ace_root/frameworks/core/components_ng/syntax/lazy_for_each_node.cpp", "$ace_root/frameworks/core/components_ng/test/event/scrollable_event/mock_scrollable.cpp", "$ace_root/frameworks/core/components_ng/test/mock/base/mock_view_abstract.cpp", + "$ace_root/frameworks/core/components_ng/test/pattern/test_ng.cpp", "$ace_root/frameworks/core/components_v2/grid/grid_event.cpp", "$ace_root/frameworks/core/gestures/velocity_tracker.cpp", "$ace_root/frameworks/core/pipeline/base/related_node.cpp", diff --git a/frameworks/core/components_ng/test/pattern/waterflow/water_flow_test_ng.cpp b/frameworks/core/components_ng/test/pattern/waterflow/water_flow_test_ng.cpp index 44e2051222e..8210f38dec5 100644 --- a/frameworks/core/components_ng/test/pattern/waterflow/water_flow_test_ng.cpp +++ b/frameworks/core/components_ng/test/pattern/waterflow/water_flow_test_ng.cpp @@ -46,6 +46,7 @@ #include "core/components_ng/property/measure_property.h" #include "core/components_ng/test/mock/render/mock_render_context.h" #include "core/components_ng/test/mock/theme/mock_theme_manager.h" +#include "core/components_ng/test/pattern/test_ng.h" #include "core/components_v2/inspector/inspector_constants.h" #include "core/pipeline/base/constants.h" #include "core/pipeline_ng/test/mock/mock_pipeline_base.h" @@ -55,33 +56,22 @@ using namespace testing::ext; namespace OHOS::Ace::NG { namespace { -constexpr float DEVICE_WIDTH = 720.0f; -constexpr float DEVICE_HEIGHT = 1136.0f; -constexpr float DEFAULT_ITEM_HEIGHT = 100.f; -constexpr float DEFAULT_WATER_FLOW_HEIGHT = 300.f; +constexpr float ITEM_HEIGHT = 100.f; +constexpr float WATER_FLOW_HEIGHT = 300.f; } // namespace -class WaterFlowTestNg : public testing::Test { +class WaterFlowTestNg : public testing::Test, public TestNG { protected: static void SetUpTestSuite(); static void TearDownTestSuite(); void SetUp() override; void TearDown() override; void GetInstance(); - static void SetWidth(const Dimension& width); - static void SetHeight(const Dimension& height); void CreateWaterFlowItem(int32_t number = 10); - RefPtr RunMeasureAndLayout(float width = DEVICE_WIDTH, float height = DEFAULT_WATER_FLOW_HEIGHT); - RefPtr GetItemFrameNode(int32_t index); - RefPtr GetItemPattern(int32_t index); - RefPtr GetItemFocusHub(int32_t index); void UpdateCurrentOffset(float offset); void MouseSelect(Offset start, Offset end); void MouseSelectRelease(); std::function GetDefaultHeaderBuilder(); - RefPtr GetChildGeometryNode(int32_t index); - uint64_t GetActions(); - testing::AssertionResult IsEqualOverScrollOffset(OverScrollOffset offset, OverScrollOffset expectOffset); RefPtr frameNode_; RefPtr pattern_; @@ -124,69 +114,20 @@ void WaterFlowTestNg::GetInstance() accessibilityProperty_ = frameNode_->GetAccessibilityProperty(); } -void WaterFlowTestNg::SetWidth(const Dimension& width) -{ - auto frameNode = ViewStackProcessor::GetInstance()->GetMainFrameNode(); - auto layoutProperty = frameNode->GetLayoutProperty(); - layoutProperty->UpdateUserDefinedIdealSize(CalcSize(CalcLength(width), std::nullopt)); -} - -void WaterFlowTestNg::SetHeight(const Dimension& height) -{ - auto frameNode = ViewStackProcessor::GetInstance()->GetMainFrameNode(); - auto layoutProperty = frameNode->GetLayoutProperty(); - layoutProperty->UpdateUserDefinedIdealSize(CalcSize(std::nullopt, CalcLength(height))); -} - void WaterFlowTestNg::CreateWaterFlowItem(int32_t number) { for (int32_t i = 0; i < number; i++) { WaterFlowItemModelNG waterFlowItemModel; waterFlowItemModel.Create(); - SetHeight(Dimension(DEFAULT_ITEM_HEIGHT)); + SetHeight(Dimension(ITEM_HEIGHT)); ViewStackProcessor::GetInstance()->Pop(); } } -RefPtr WaterFlowTestNg::RunMeasureAndLayout(float width, float height) -{ - RefPtr layoutWrapper = frameNode_->CreateLayoutWrapper(false, false); - layoutWrapper->SetActive(); - LayoutConstraintF LayoutConstraint; - LayoutConstraint.parentIdealSize = { DEVICE_WIDTH, DEVICE_HEIGHT }; - LayoutConstraint.percentReference = { DEVICE_WIDTH, DEVICE_HEIGHT }; - LayoutConstraint.selfIdealSize = { width, height }; - LayoutConstraint.maxSize = { width, height }; - layoutWrapper->Measure(LayoutConstraint); - layoutWrapper->Layout(); - layoutWrapper->MountToHostOnMainThread(); - return layoutWrapper; -} - -RefPtr WaterFlowTestNg::GetItemFrameNode(int32_t index) -{ - auto item = frameNode_->GetChildAtIndex(index); - return AceType::DynamicCast(item); -} - -RefPtr WaterFlowTestNg::GetItemPattern(int32_t index) -{ - auto item = frameNode_->GetChildAtIndex(index); - auto itemFrameNode = AceType::DynamicCast(item); - return itemFrameNode->GetPattern(); -} - -RefPtr WaterFlowTestNg::GetItemFocusHub(int32_t index) -{ - auto item = frameNode_->GetChildAtIndex(index); - auto itemFrameNode = AceType::DynamicCast(item); - return itemFrameNode->GetOrCreateFocusHub(); -} - void WaterFlowTestNg::UpdateCurrentOffset(float offset) { pattern_->UpdateCurrentOffset(offset, SCROLL_FROM_UPDATE); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); } std::function WaterFlowTestNg::GetDefaultHeaderBuilder() @@ -199,36 +140,6 @@ std::function WaterFlowTestNg::GetDefaultHeaderBuilder() }; } -RefPtr WaterFlowTestNg::GetChildGeometryNode(int32_t index) -{ - auto item = frameNode_->GetChildAtIndex(index); - auto itemFrameNode = AceType::DynamicCast(item); - return itemFrameNode->GetGeometryNode(); -} - -uint64_t WaterFlowTestNg::GetActions() -{ - std::unordered_set supportAceActions = accessibilityProperty_->GetSupportAction(); - uint64_t actions = 0; - for (auto action : supportAceActions) { - actions |= 1UL << static_cast(action); - } - return actions; -} - -testing::AssertionResult WaterFlowTestNg::IsEqualOverScrollOffset( - OverScrollOffset offset, OverScrollOffset expectOffset) -{ - if (NearEqual(offset.start, expectOffset.start) && NearEqual(offset.end, expectOffset.end)) { - return testing::AssertionSuccess(); - } - return testing::AssertionFailure() << "offset: " - << "{ " << offset.start << " , " << offset.end << " }" - << " != " - << "expectOffset: " - << "{ " << expectOffset.start << " , " << expectOffset.end << " }"; -} - /** * @tc.name: Property001 * @tc.desc: Test all the properties of WaterFlow. @@ -252,7 +163,7 @@ HWTEST_F(WaterFlowTestNg, Property001, TestSize.Level1) waterFlowModelNG.SetItemMaxHeight(Dimension(500)); CreateWaterFlowItem(10); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); /** * @tc.steps: step1. compare waterFlow properties and expected value. @@ -290,7 +201,7 @@ HWTEST_F(WaterFlowTestNg, Property002, TestSize.Level1) waterFlowModelNG.SetColumnsTemplate(""); CreateWaterFlowItem(10); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); /** * @tc.steps: step1. compare waterFlow properties and expected value after change. @@ -311,7 +222,7 @@ HWTEST_F(WaterFlowTestNg, Property003, TestSize.Level1) waterFlowModelNG.Create(); CreateWaterFlowItem(10); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); EXPECT_EQ(layoutProperty_->GetWaterflowDirectionStr(), "FlexDirection.Column"); EXPECT_FALSE(layoutProperty_->IsReverse()); @@ -340,7 +251,7 @@ HWTEST_F(WaterFlowTestNg, Property004, TestSize.Level1) waterFlowModelNG.SetScroller(scrollController, proxy); CreateWaterFlowItem(DEFAULT_ITEM_COUNT); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); EXPECT_NE(pattern_->controller_, nullptr); } @@ -358,7 +269,7 @@ HWTEST_F(WaterFlowTestNg, Property005, TestSize.Level1) waterFlowModelNG.SetColumnsTemplate("auto"); CreateWaterFlowItem(10); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); EXPECT_EQ(pattern_->GetColumns(), 1); EXPECT_EQ(pattern_->GetRows(), 3); @@ -376,7 +287,7 @@ HWTEST_F(WaterFlowTestNg, Property006, TestSize.Level1) waterFlowModelNG.SetColumnsTemplate("repeat(3, 2fr)"); CreateWaterFlowItem(10); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); EXPECT_EQ(pattern_->GetRows(), 3); } @@ -394,7 +305,7 @@ HWTEST_F(WaterFlowTestNg, Property007, TestSize.Level1) waterFlowModelNG.SetColumnsTemplate("repeat(auto-fill, 113px)"); CreateWaterFlowItem(10); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); EXPECT_TRUE(true); } @@ -416,7 +327,7 @@ HWTEST_F(WaterFlowTestNg, Property008, TestSize.Level1) waterFlowModelNG.SetColumnsGap(Dimension(-10)); CreateWaterFlowItem(10); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); EXPECT_FALSE(false); } @@ -437,7 +348,7 @@ HWTEST_F(WaterFlowTestNg, Property009, TestSize.Level1) waterFlowModelNG.SetScrollEnabled(true); CreateWaterFlowItem(10); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); EXPECT_EQ(layoutProperty_->GetScrollEnabled(), true); /** @@ -465,7 +376,7 @@ HWTEST_F(WaterFlowTestNg, WaterFlowTest001, TestSize.Level1) * @tc.steps: step1. When setting fixed rows and columns, check the status of child nodes in the waterFlow. * @tc.expected: All child nodes are active. */ - RefPtr layoutWrapper = RunMeasureAndLayout(); + RefPtr layoutWrapper = RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); for (int32_t i = 0; i < 9; ++i) { EXPECT_TRUE(layoutWrapper->GetOrCreateChildByIndex(i, false)->IsActive()); } @@ -488,7 +399,7 @@ HWTEST_F(WaterFlowTestNg, WaterFlowTest002, TestSize.Level1) * @tc.steps: step1. When setting fixed rows and columns, check the status of child nodes in the waterFlow. * @tc.expected: All child nodes are active. */ - RefPtr layoutWrapper = RunMeasureAndLayout(); + RefPtr layoutWrapper = RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); for (int32_t i = 0; i < 9; ++i) { EXPECT_TRUE(layoutWrapper->GetOrCreateChildByIndex(i, false)->IsActive()); } @@ -507,7 +418,7 @@ HWTEST_F(WaterFlowTestNg, WaterFlowTest003, TestSize.Level1) CreateWaterFlowItem(9); GetInstance(); - RefPtr layoutWrapper = RunMeasureAndLayout(DEVICE_WIDTH, 200.f); + RefPtr layoutWrapper = RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, 200.f); for (int32_t i = 0; i < 6; ++i) { EXPECT_TRUE(layoutWrapper->GetOrCreateChildByIndex(i, false)->IsActive()); } @@ -526,7 +437,7 @@ HWTEST_F(WaterFlowTestNg, WaterFlowTest004, TestSize.Level1) CreateWaterFlowItem(9); GetInstance(); - RefPtr layoutWrapper = RunMeasureAndLayout(DEVICE_WIDTH, 250.f); + RefPtr layoutWrapper = RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, 250.f); for (int32_t i = 0; i < 9; ++i) { EXPECT_TRUE(layoutWrapper->GetOrCreateChildByIndex(i, false)->IsActive()); } @@ -545,9 +456,9 @@ HWTEST_F(WaterFlowTestNg, WaterFlowTest005, TestSize.Level1) CreateWaterFlowItem(9); GetInstance(); - RefPtr layoutWrapper = RunMeasureAndLayout(DEVICE_WIDTH, 200.f); + RefPtr layoutWrapper = RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, 200.f); pattern_->UpdateCurrentOffset(-50.f, SCROLL_FROM_UPDATE); - layoutWrapper = RunMeasureAndLayout(DEVICE_WIDTH, 200.f); + layoutWrapper = RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, 200.f); for (int32_t i = 0; i < 9; ++i) { EXPECT_TRUE(layoutWrapper->GetOrCreateChildByIndex(i, false)->IsActive()); } @@ -566,9 +477,9 @@ HWTEST_F(WaterFlowTestNg, WaterFlowTest006, TestSize.Level1) CreateWaterFlowItem(9); GetInstance(); - RefPtr layoutWrapper = RunMeasureAndLayout(DEVICE_WIDTH, 200.f); + RefPtr layoutWrapper = RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, 200.f); pattern_->UpdateCurrentOffset(-100.f, SCROLL_FROM_UPDATE); - layoutWrapper = RunMeasureAndLayout(DEVICE_WIDTH, 200.f); + layoutWrapper = RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, 200.f); for (int32_t i = 3; i < 9; ++i) { EXPECT_TRUE(layoutWrapper->GetOrCreateChildByIndex(i, false)->IsActive()); } @@ -587,9 +498,9 @@ HWTEST_F(WaterFlowTestNg, WaterFlowTest007, TestSize.Level1) CreateWaterFlowItem(9); GetInstance(); - RefPtr layoutWrapper = RunMeasureAndLayout(DEVICE_WIDTH, 200.f); + RefPtr layoutWrapper = RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, 200.f); pattern_->UpdateStartIndex(8); - layoutWrapper = RunMeasureAndLayout(DEVICE_WIDTH, 200.f); + layoutWrapper = RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, 200.f); for (int32_t i = 0; i < 3; ++i) { EXPECT_FALSE(layoutWrapper->GetOrCreateChildByIndex(i, false)->IsActive()); } @@ -608,9 +519,9 @@ HWTEST_F(WaterFlowTestNg, WaterFlowTest008, TestSize.Level1) CreateWaterFlowItem(9); GetInstance(); - RefPtr layoutWrapper = RunMeasureAndLayout(DEVICE_WIDTH, 200.f); + RefPtr layoutWrapper = RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, 200.f); pattern_->UpdateStartIndex(1); - layoutWrapper = RunMeasureAndLayout(DEVICE_WIDTH, 200.f); + layoutWrapper = RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, 200.f); for (int32_t i = 6; i < 9; ++i) { EXPECT_FALSE(layoutWrapper->GetOrCreateChildByIndex(i, false)->IsActive()); } @@ -629,9 +540,9 @@ HWTEST_F(WaterFlowTestNg, WaterFlowTest009, TestSize.Level1) CreateWaterFlowItem(9); GetInstance(); - RefPtr layoutWrapper = RunMeasureAndLayout(DEVICE_WIDTH, 200.f); + RefPtr layoutWrapper = RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, 200.f); pattern_->UpdateStartIndex(3); - layoutWrapper = RunMeasureAndLayout(DEVICE_WIDTH, 200.f); + layoutWrapper = RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, 200.f); for (int32_t i = 0; i < 6; ++i) { EXPECT_TRUE(layoutWrapper->GetOrCreateChildByIndex(i, false)->IsActive()); } @@ -650,14 +561,14 @@ HWTEST_F(WaterFlowTestNg, WaterFlowTest010, TestSize.Level1) CreateWaterFlowItem(10); GetInstance(); - RefPtr layoutWrapper = RunMeasureAndLayout(DEVICE_WIDTH, 200.f); + RefPtr layoutWrapper = RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, 200.f); pattern_->UpdateStartIndex(9); - layoutWrapper = RunMeasureAndLayout(DEVICE_WIDTH, 200.f); + layoutWrapper = RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, 200.f); EXPECT_TRUE(layoutWrapper->GetOrCreateChildByIndex(9, false)->IsActive()); EXPECT_FALSE(layoutWrapper->GetOrCreateChildByIndex(0, false)->IsActive()); pattern_->UpdateStartIndex(0); - layoutWrapper = RunMeasureAndLayout(DEVICE_WIDTH, 200.f); + layoutWrapper = RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, 200.f); EXPECT_FALSE(layoutWrapper->GetOrCreateChildByIndex(9, false)->IsActive()); EXPECT_TRUE(layoutWrapper->GetOrCreateChildByIndex(0, false)->IsActive()); } @@ -674,40 +585,40 @@ HWTEST_F(WaterFlowTestNg, WaterFlowTest011, TestSize.Level1) waterFlowModelNG.SetColumnsTemplate("1fr"); CreateWaterFlowItem(5); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); EXPECT_TRUE( - IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(DEFAULT_ITEM_HEIGHT), { DEFAULT_ITEM_HEIGHT, 0 })); + IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(ITEM_HEIGHT), { ITEM_HEIGHT, 0 })); EXPECT_TRUE(IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(0.f), { 0, 0 })); - EXPECT_TRUE(IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(-DEFAULT_ITEM_HEIGHT), { 0, 0 })); + EXPECT_TRUE(IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(-ITEM_HEIGHT), { 0, 0 })); - UpdateCurrentOffset(-DEFAULT_ITEM_HEIGHT); + UpdateCurrentOffset(-ITEM_HEIGHT); EXPECT_TRUE( - IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(DEFAULT_ITEM_HEIGHT * 2), { 0, 0 })); + IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(ITEM_HEIGHT * 2), { 0, 0 })); EXPECT_TRUE(IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(0.f), { 0, 0 })); EXPECT_TRUE( - IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(-DEFAULT_ITEM_HEIGHT * 2), { 0, 0 })); + IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(-ITEM_HEIGHT * 2), { 0, 0 })); - UpdateCurrentOffset(-DEFAULT_ITEM_HEIGHT); - EXPECT_TRUE(IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(DEFAULT_ITEM_HEIGHT), { 0, 0 })); + UpdateCurrentOffset(-ITEM_HEIGHT); + EXPECT_TRUE(IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(ITEM_HEIGHT), { 0, 0 })); EXPECT_TRUE(IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(0.f), { 0, 0 })); EXPECT_TRUE( - IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(-DEFAULT_ITEM_HEIGHT), { 0, -DEFAULT_ITEM_HEIGHT })); + IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(-ITEM_HEIGHT), { 0, -ITEM_HEIGHT })); pattern_->layoutInfo_.startIndex_ = 0; - pattern_->layoutInfo_.currentOffset_ = DEFAULT_ITEM_HEIGHT; + pattern_->layoutInfo_.currentOffset_ = ITEM_HEIGHT; EXPECT_TRUE( - IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(DEFAULT_ITEM_HEIGHT), { DEFAULT_ITEM_HEIGHT, 0 })); + IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(ITEM_HEIGHT), { ITEM_HEIGHT, 0 })); EXPECT_TRUE(IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(0.f), { 0, 0 })); EXPECT_TRUE( - IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(-DEFAULT_ITEM_HEIGHT * 2), { -DEFAULT_ITEM_HEIGHT, 0 })); + IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(-ITEM_HEIGHT * 2), { -ITEM_HEIGHT, 0 })); - pattern_->layoutInfo_.currentOffset_ = -DEFAULT_ITEM_HEIGHT * 3; + pattern_->layoutInfo_.currentOffset_ = -ITEM_HEIGHT * 3; EXPECT_TRUE( - IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(DEFAULT_ITEM_HEIGHT * 2), { 0, DEFAULT_ITEM_HEIGHT })); + IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(ITEM_HEIGHT * 2), { 0, ITEM_HEIGHT })); EXPECT_TRUE(IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(0.f), { 0, 0 })); EXPECT_TRUE( - IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(-DEFAULT_ITEM_HEIGHT), { 0, -DEFAULT_ITEM_HEIGHT })); + IsEqualOverScrollOffset(pattern_->GetOverScrollOffset(-ITEM_HEIGHT), { 0, -ITEM_HEIGHT })); } /** @@ -724,7 +635,7 @@ HWTEST_F(WaterFlowTestNg, PositionControllerCoverage001, TestSize.Level1) waterFlowModelNG.SetColumnsTemplate("1fr 1fr 1fr 1fr"); CreateWaterFlowItem(8); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); /** * @tc.steps: step1. Supplement ScrollPage, GetCurrentOffset branch @@ -750,7 +661,7 @@ HWTEST_F(WaterFlowTestNg, PositionControllerCoverage002, TestSize.Level1) waterFlowModelNG.SetColumnsTemplate("1fr 1fr 1fr"); CreateWaterFlowItem(14); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); /** * @tc.steps: step1. Test JumpTo func. @@ -764,13 +675,13 @@ HWTEST_F(WaterFlowTestNg, PositionControllerCoverage002, TestSize.Level1) * @tc.steps: step2. Test ScrollPage func. * @tc.expected: Verify currentOffset. */ - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); controller->ScrollPage(true, true); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); EXPECT_EQ(controller->GetCurrentOffset(), Offset(0, 0)); controller->ScrollPage(false, true); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); EXPECT_EQ(controller->GetCurrentOffset(), Offset(0, 200)); } @@ -789,7 +700,7 @@ HWTEST_F(WaterFlowTestNg, PositionControllerCoverage003, TestSize.Level1) waterFlowModelNG.SetColumnsTemplate("1fr 1fr 1fr"); CreateWaterFlowItem(14); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); /** * @tc.steps: step1. Test JumpTo func. @@ -804,9 +715,9 @@ HWTEST_F(WaterFlowTestNg, PositionControllerCoverage003, TestSize.Level1) * @tc.steps: step2. Test ScrollPage func. * @tc.expected: Verify currentOffset. */ - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); controller->ScrollPage(true, true); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); EXPECT_EQ(controller->GetCurrentOffset(), Offset(0, 0)); } @@ -822,14 +733,14 @@ HWTEST_F(WaterFlowTestNg, WaterFlowPatternTest001, TestSize.Level1) waterFlowModelNG.SetColumnsTemplate("1fr 1fr 1fr 1fr"); CreateWaterFlowItem(14); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); /** * @tc.steps: step1. Run pattern func. * @tc.expected: The return_value is correct. */ EXPECT_TRUE(pattern_->IsScrollable()); - EXPECT_FALSE(pattern_->IsAtTop()); + EXPECT_TRUE(pattern_->IsAtTop()); EXPECT_FALSE(pattern_->IsAtBottom()); } @@ -846,19 +757,19 @@ HWTEST_F(WaterFlowTestNg, WaterFlowPatternTest002, TestSize.Level1) waterFlowModelNG.SetLayoutDirection(FlexDirection::COLUMN_REVERSE); CreateWaterFlowItem(14); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); /** * @tc.steps: step1. Run pattern func. * @tc.expected: The return_value is correct. */ pattern_->UpdateCurrentOffset(-100.f, SCROLL_FROM_UPDATE); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); pattern_->UpdateScrollBarOffset(); EXPECT_EQ(pattern_->layoutInfo_.currentOffset_, 0.f); pattern_->UpdateCurrentOffset(200.f, SCROLL_FROM_UPDATE); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); EXPECT_EQ(pattern_->layoutInfo_.currentOffset_, -100.f); } @@ -874,7 +785,7 @@ HWTEST_F(WaterFlowTestNg, WaterFlowAccessibilityTest001, TestSize.Level1) waterFlowModelNG.SetColumnsTemplate("1fr 1fr 1fr 1fr"); CreateWaterFlowItem(18); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); /** * @tc.steps: step1. Run Accessibility func. @@ -891,32 +802,32 @@ HWTEST_F(WaterFlowTestNg, WaterFlowAccessibilityTest001, TestSize.Level1) * @tc.steps: step1. Scroll to Top. * @tc.expected: Verify return value. */ - UpdateCurrentOffset(DEFAULT_ITEM_HEIGHT); + UpdateCurrentOffset(ITEM_HEIGHT); accessibilityProperty_->ResetSupportAction(); uint64_t exptectActions_1 = 0; exptectActions_1 |= 1UL << static_cast(AceAction::ACTION_SCROLL_FORWARD); - EXPECT_EQ(GetActions(), exptectActions_1); + EXPECT_EQ(GetActions(accessibilityProperty_), exptectActions_1); /** * @tc.steps: step2. Scroll to middle. * @tc.expected: Verify return value. */ - UpdateCurrentOffset(-DEFAULT_ITEM_HEIGHT); + UpdateCurrentOffset(-ITEM_HEIGHT); accessibilityProperty_->ResetSupportAction(); uint64_t exptectActions_2 = 0; exptectActions_2 |= 1UL << static_cast(AceAction::ACTION_SCROLL_FORWARD); exptectActions_2 |= 1UL << static_cast(AceAction::ACTION_SCROLL_BACKWARD); - EXPECT_EQ(GetActions(), exptectActions_2); + EXPECT_EQ(GetActions(accessibilityProperty_), exptectActions_2); /** * @tc.steps: step3. Scroll to bottom. * @tc.expected: Verify return value. */ - UpdateCurrentOffset(-DEFAULT_ITEM_HEIGHT); + UpdateCurrentOffset(-ITEM_HEIGHT); accessibilityProperty_->ResetSupportAction(); uint64_t exptectActions_3 = 0; exptectActions_3 |= 1UL << static_cast(AceAction::ACTION_SCROLL_BACKWARD); - EXPECT_EQ(GetActions(), exptectActions_3); + EXPECT_EQ(GetActions(accessibilityProperty_), exptectActions_3); /** * @tc.steps: step4. UnScrollable. @@ -927,10 +838,10 @@ HWTEST_F(WaterFlowTestNg, WaterFlowAccessibilityTest001, TestSize.Level1) waterFlowModelNG_2.SetColumnsTemplate("1fr 1fr 1fr 1fr"); CreateWaterFlowItem(1); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); accessibilityProperty_->ResetSupportAction(); uint64_t exptectActions_4 = 0; - EXPECT_EQ(GetActions(), exptectActions_4); + EXPECT_EQ(GetActions(accessibilityProperty_), exptectActions_4); } /** @@ -945,7 +856,7 @@ HWTEST_F(WaterFlowTestNg, WaterFlowAccessibilityTest002, TestSize.Level1) waterFlowModelNG.SetColumnsTemplate("1fr 1fr 1fr 1fr"); CreateWaterFlowItem(14); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); /** * @tc.steps: step1. Run Accessibility func. @@ -972,14 +883,14 @@ HWTEST_F(WaterFlowTestNg, WaterFlowFooterTest001, TestSize.Level1) CreateWaterFlowItem(5); ViewStackProcessor::GetInstance()->Pop(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); /** * @tc.steps: step1. Run footer func. * @tc.expected: The return_value is correct. */ - auto footerNode = GetChildGeometryNode(0); - EXPECT_FLOAT_EQ(footerNode->GetFrameOffset().GetY(), 200.f); + auto footerRect = GetChildRect(frameNode_, 0); + EXPECT_FLOAT_EQ(footerRect.GetY(), 200.f); } /** @@ -997,7 +908,7 @@ HWTEST_F(WaterFlowTestNg, WaterFlowFooterTest002, TestSize.Level1) CreateWaterFlowItem(5); ViewStackProcessor::GetInstance()->Pop(); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); EXPECT_TRUE(true); } @@ -1019,17 +930,17 @@ HWTEST_F(WaterFlowTestNg, Callback001, TestSize.Level1) waterFlowModelNG.SetOnReachEnd(reachEnd); CreateWaterFlowItem(8); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); - constexpr float scrollUpOffset = DEFAULT_ITEM_HEIGHT; - constexpr float scrollDownOffset = -DEFAULT_ITEM_HEIGHT; + constexpr float scrollUpOffset = ITEM_HEIGHT; + constexpr float scrollDownOffset = -ITEM_HEIGHT; /** * @tc.steps: step1. Scroll up 100px. * @tc.expected: Callback is called. */ pattern_->UpdateCurrentOffset(scrollUpOffset, SCROLL_FROM_ANIMATION); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); EXPECT_TRUE(isReachStartCalled); /** @@ -1053,13 +964,13 @@ HWTEST_F(WaterFlowTestNg, WaterFlowLayoutInfoTest001, TestSize.Level1) waterFlowModelNG.SetRowsGap(Dimension(5)); CreateWaterFlowItem(10); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); /** * @tc.steps: Test IsAllCrossReachend function * @tc.expected: step1. Check whether the return value is correct. */ - auto reached = pattern_->layoutInfo_.IsAllCrossReachend(DEFAULT_ITEM_HEIGHT); + auto reached = pattern_->layoutInfo_.IsAllCrossReachend(ITEM_HEIGHT); EXPECT_TRUE(reached); reached = pattern_->layoutInfo_.IsAllCrossReachend(DEVICE_HEIGHT); EXPECT_FALSE(reached); @@ -1089,12 +1000,12 @@ HWTEST_F(WaterFlowTestNg, PositionController001, TestSize.Level1) waterFlowModelNG.SetColumnsTemplate("1fr 1fr 1fr"); CreateWaterFlowItem(10); GetInstance(); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); EXPECT_FALSE(scrollController->IsAtEnd()); pattern_->UpdateCurrentOffset(-100.f, SCROLL_FROM_UPDATE); - RunMeasureAndLayout(); + RunMeasureAndLayout(frameNode_, DEVICE_WIDTH, WATER_FLOW_HEIGHT); EXPECT_TRUE(scrollController->IsAtEnd()); } diff --git a/frameworks/core/components_ng/test/svg/parse/BUILD.gn b/frameworks/core/components_ng/test/svg/parse/BUILD.gn index ae58534c953..f5eabefc6a3 100644 --- a/frameworks/core/components_ng/test/svg/parse/BUILD.gn +++ b/frameworks/core/components_ng/test/svg/parse/BUILD.gn @@ -375,9 +375,27 @@ ohos_unittest("parse_use_test_ng") { ] } +ohos_unittest("parse_animate_test_ng") { + module_out_path = svg_test_output_path + + sources = [ "parse_animate_test_ng.cpp" ] + + deps = [ + "$ace_root/build:ace_ohos_unittest_base", + "$ace_root/frameworks/core/components_ng/base:ace_core_components_base_ng_ohos", + "//third_party/googletest:gtest_main", + ] + + configs = [ + ":config_svg_parse_test", + "$ace_root:ace_config", + ] +} + group("svg_parse_unit_test") { testonly = true deps = [ + ":parse_animate_test_ng", ":parse_circle_test_ng", ":parse_clippath_test_ng", ":parse_ellipse_test_ng", diff --git a/frameworks/core/components_ng/test/svg/parse/parse_animate_test_ng.cpp b/frameworks/core/components_ng/test/svg/parse/parse_animate_test_ng.cpp new file mode 100644 index 00000000000..06047a6ca27 --- /dev/null +++ b/frameworks/core/components_ng/test/svg/parse/parse_animate_test_ng.cpp @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#define private public +#define protected public +#include "gtest/gtest.h" + +using namespace testing; +using namespace testing::ext; + +#include "include/core/SkStream.h" + +#include "base/memory/ace_type.h" +#include "base/memory/referenced.h" +#include "core/components_ng/svg/parse/svg_animation.h" +#include "core/components_ng/svg/parse/svg_svg.h" +#include "core/components_ng/svg/svg_dom.h" + +namespace OHOS::Ace::NG { +namespace { +const std::string SVG_ANIMATE_TRANSFORM( + "" + "" + ""); +} // namespace +class ParseAnimateTestNg : public testing::Test {}; + +/** + * @tc.name: ParseTest001 + * @tc.desc: parse circle label + * @tc.type: FUNC + */ + +HWTEST_F(ParseAnimateTestNg, ParseTest001, TestSize.Level1) +{ + auto svgStream = SkMemoryStream::MakeCopy(SVG_ANIMATE_TRANSFORM.c_str(), SVG_ANIMATE_TRANSFORM.length()); + EXPECT_NE(svgStream, nullptr); + auto svgDom = SvgDom::CreateSvgDom(*svgStream, Color::BLACK); + EXPECT_TRUE(svgDom); + auto svg = AceType::DynamicCast(svgDom->root_); + EXPECT_TRUE(svg); + EXPECT_GT(svg->children_.size(), 0); + + auto svgAnimate = AceType::DynamicCast(svg->children_.at(0)->children_.at(0)); + EXPECT_TRUE(svgAnimate); + // values changed to indices + std::vector values { "0", "1", "2" }; + EXPECT_EQ(svgAnimate->GetValues(), values); +} +} // namespace OHOS::Ace::NG \ No newline at end of file diff --git a/frameworks/core/components_ng/test/syntax/if_else/BUILD.gn b/frameworks/core/components_ng/test/syntax/if_else/BUILD.gn index bce5cb895fe..2856234120d 100644 --- a/frameworks/core/components_ng/test/syntax/if_else/BUILD.gn +++ b/frameworks/core/components_ng/test/syntax/if_else/BUILD.gn @@ -52,6 +52,7 @@ ohos_unittest("if_else_syntax_test_ng") { "$ace_root/frameworks/core/components_ng/layout/layout_property.cpp", "$ace_root/frameworks/core/components_ng/layout/layout_wrapper.cpp", "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_builder.cpp", + "$ace_root/frameworks/core/components_ng/manager/safe_area/safe_area_manager.cpp", # components_ng_pattern "$ace_root/frameworks/core/components_ng/pattern/grid_container/grid_container_layout_property.cpp", diff --git a/frameworks/core/components_v2/inspector/inspector_composed_component.cpp b/frameworks/core/components_v2/inspector/inspector_composed_component.cpp index cfb79f48c2c..ea48fe23f8a 100644 --- a/frameworks/core/components_v2/inspector/inspector_composed_component.cpp +++ b/frameworks/core/components_v2/inspector/inspector_composed_component.cpp @@ -340,9 +340,9 @@ const std::unordered_map COMPONENT_TAG_TO_ETS_TAG_MAP { JS_VIEW_COMPONENT_TAG, JS_VIEW_ETS_TAG }, { RELATIVE_CONTAINER_COMPONENT_TAG, RELATIVE_CONTAINER_ETS_TAG }, { UI_EXTENSION_COMPONENT_TAG, UI_EXTENSION_COMPONENT_ETS_TAG }, - { SEC_LOCATION_BUTTON_COMPONENT_TAG, SEC_LOCATION_BUTTON_ETS_TAG }, - { SEC_PASTE_BUTTON_COMPONENT_TAG, SEC_PASTE_BUTTON_ETS_TAG }, - { SEC_SAVE_BUTTON_COMPONENT_TAG, SEC_SAVE_BUTTON_ETS_TAG }, + { LOCATION_BUTTON_COMPONENT_TAG, LOCATION_BUTTON_ETS_TAG }, + { PASTE_BUTTON_COMPONENT_TAG, PASTE_BUTTON_ETS_TAG }, + { SAVE_BUTTON_COMPONENT_TAG, SAVE_BUTTON_ETS_TAG }, }; thread_local int32_t InspectorComposedComponent::composedElementId_ = 1; diff --git a/frameworks/core/components_v2/inspector/inspector_constants.cpp b/frameworks/core/components_v2/inspector/inspector_constants.cpp index 49213d09594..dafc75784bf 100644 --- a/frameworks/core/components_v2/inspector/inspector_constants.cpp +++ b/frameworks/core/components_v2/inspector/inspector_constants.cpp @@ -344,6 +344,7 @@ const char DATA_PANEL_ETS_TAG[] = "DataPanel"; const char SHEET_COMPONENT_TAG[] = "SheetComponent"; const char SHEET_ETS_TAG[] = "Sheet"; const char SHEET_MASK_TAG[] = "SheetMask"; +const char SHEET_PAGE_TAG[] = "SheetPage"; // hyperlink const char HYPERLINK_COMPONENT_TAG[] = "HyperlinkComponent"; @@ -518,15 +519,15 @@ ACE_EXPORT extern const char WINDOW_SCENE_ETS_TAG[] = "WindowScene"; const char UI_EXTENSION_COMPONENT_TAG[] = "UIExtensionComponent"; const char UI_EXTENSION_COMPONENT_ETS_TAG[] = "UIExtensionComponent"; -// SecLocationButton -const char SEC_LOCATION_BUTTON_COMPONENT_TAG[] = "SecLocationButtonComponent"; -const char SEC_LOCATION_BUTTON_ETS_TAG[] = "SecLocationButton"; +// LocationButton +const char LOCATION_BUTTON_COMPONENT_TAG[] = "LocationButtonComponent"; +const char LOCATION_BUTTON_ETS_TAG[] = "LocationButton"; -// SecPasteButton -const char SEC_PASTE_BUTTON_COMPONENT_TAG[] = "SecPasteButtonComponent"; -const char SEC_PASTE_BUTTON_ETS_TAG[] = "SecPasteButton"; +// PasteButton +const char PASTE_BUTTON_COMPONENT_TAG[] = "PasteButtonComponent"; +const char PASTE_BUTTON_ETS_TAG[] = "PasteButton"; -// SecSaveButton -const char SEC_SAVE_BUTTON_COMPONENT_TAG[] = "SecSaveButtonComponent"; -const char SEC_SAVE_BUTTON_ETS_TAG[] = "SecSaveButton"; +// SaveButton +const char SAVE_BUTTON_COMPONENT_TAG[] = "SaveButtonComponent"; +const char SAVE_BUTTON_ETS_TAG[] = "SaveButton"; } // namespace OHOS::Ace::V2 diff --git a/frameworks/core/components_v2/inspector/inspector_constants.h b/frameworks/core/components_v2/inspector/inspector_constants.h index b7909b98d3b..890218c57be 100644 --- a/frameworks/core/components_v2/inspector/inspector_constants.h +++ b/frameworks/core/components_v2/inspector/inspector_constants.h @@ -353,6 +353,7 @@ ACE_EXPORT extern const char DATA_PANEL_ETS_TAG[]; ACE_EXPORT extern const char SHEET_COMPONENT_TAG[]; ACE_EXPORT extern const char SHEET_ETS_TAG[]; ACE_EXPORT extern const char SHEET_MASK_TAG[]; +ACE_EXPORT extern const char SHEET_PAGE_TAG[]; // hyperlink ACE_EXPORT extern const char HYPERLINK_COMPONENT_TAG[]; @@ -529,15 +530,15 @@ ACE_EXPORT extern const char UI_EXTENSION_COMPONENT_TAG[]; ACE_EXPORT extern const char UI_EXTENSION_COMPONENT_ETS_TAG[]; // LocationButton -ACE_EXPORT extern const char SEC_LOCATION_BUTTON_COMPONENT_TAG[]; -ACE_EXPORT extern const char SEC_LOCATION_BUTTON_ETS_TAG[]; +ACE_EXPORT extern const char LOCATION_BUTTON_COMPONENT_TAG[]; +ACE_EXPORT extern const char LOCATION_BUTTON_ETS_TAG[]; // PasteButton -ACE_EXPORT extern const char SEC_PASTE_BUTTON_COMPONENT_TAG[]; -ACE_EXPORT extern const char SEC_PASTE_BUTTON_ETS_TAG[]; +ACE_EXPORT extern const char PASTE_BUTTON_COMPONENT_TAG[]; +ACE_EXPORT extern const char PASTE_BUTTON_ETS_TAG[]; // SaveButton -ACE_EXPORT extern const char SEC_SAVE_BUTTON_COMPONENT_TAG[]; -ACE_EXPORT extern const char SEC_SAVE_BUTTON_ETS_TAG[]; +ACE_EXPORT extern const char SAVE_BUTTON_COMPONENT_TAG[]; +ACE_EXPORT extern const char SAVE_BUTTON_ETS_TAG[]; } // namespace OHOS::Ace::V2 #endif // FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_V2_INSPECTOR_INSPECTOR_CONSTANTS_H diff --git a/frameworks/core/pipeline/pipeline_base.cpp b/frameworks/core/pipeline/pipeline_base.cpp index 0d465998465..654401a9477 100644 --- a/frameworks/core/pipeline/pipeline_base.cpp +++ b/frameworks/core/pipeline/pipeline_base.cpp @@ -614,8 +614,10 @@ void PipelineBase::OnVirtualKeyboardAreaChange( double keyboardHeight = keyboardArea.Height(); if (windowManager_ && windowManager_->GetWindowMode() == WindowMode::WINDOW_MODE_FLOATING) { if (windowManager_->GetWindowType() == WindowType::WINDOW_TYPE_UNDEFINED || - windowManager_->GetWindowType() > WindowType::WINDOW_TYPE_APP_END) { - // only app window need avoid virtual keyboard + (windowManager_->GetWindowType() > WindowType::WINDOW_TYPE_APP_END && + windowManager_->GetWindowType() != WindowType::WINDOW_TYPE_FLOAT)) { + LOGW("this window type: %{public}d do not need avoid virtual keyboard.", + static_cast(windowManager_->GetWindowMode())); return; } keyboardHeight = ModifyKeyboardHeight(keyboardHeight); @@ -721,6 +723,19 @@ void PipelineBase::RemoveSubWindowVsyncCallback(int32_t subWindowId) subWindowVsyncCallbacks_.erase(subWindowId); } +bool PipelineBase::MaybeRelease() +{ + CHECK_RUN_ON(UI); + CHECK_NULL_RETURN(taskExecutor_, true); + if (taskExecutor_->WillRunOnCurrentThread(TaskExecutor::TaskType::UI)) { + LOGI("Destroy Pipeline on UI thread."); + return true; + } else { + LOGI("Post Destroy Pipeline Task to UI thread."); + return !taskExecutor_->PostTask([this] { delete this; }, TaskExecutor::TaskType::UI); + } +} + void PipelineBase::Destroy() { CHECK_RUN_ON(UI); @@ -742,6 +757,7 @@ void PipelineBase::Destroy() touchPluginPipelineContext_.clear(); virtualKeyBoardCallback_.clear(); etsCardTouchEventCallback_.clear(); + formLinkInfoMap_.clear(); LOGI("PipelineBase::Destroy end."); } } // namespace OHOS::Ace diff --git a/frameworks/core/pipeline/pipeline_base.h b/frameworks/core/pipeline/pipeline_base.h index 04820c8c589..fb04dc23ad0 100644 --- a/frameworks/core/pipeline/pipeline_base.h +++ b/frameworks/core/pipeline/pipeline_base.h @@ -903,13 +903,14 @@ public: return lastTouchTime_; } - void AddFormLinkInfo(const std::string& info) + void AddFormLinkInfo(int32_t id, const std::string& info) { - LOGI("AddFormLinkInfo is %{public}s", info.c_str()); - formLinkInfos_.push_back(info); + LOGI("AddFormLinkInfo is %{public}s, id is %{public}d", info.c_str(), id); + formLinkInfoMap_[id] = info; } protected: + virtual bool MaybeRelease() override; void TryCallNextFrameLayoutCallback() { if (isForegroundCalled_ && nextFrameLayoutCallback_) { @@ -917,10 +918,6 @@ protected: nextFrameLayoutCallback_(); LOGI("nextFrameLayoutCallback called"); } - // Update FormLinkInfo after layout. (For static form use only) - if (formLinkInfoUpdateHandler_) { - formLinkInfoUpdateHandler_(formLinkInfos_); - } } virtual bool OnDumpInfo(const std::vector& params) const @@ -1021,7 +1018,7 @@ protected: SharePanelCallback sharePanelCallback_ = nullptr; std::atomic isForegroundCalled_ = false; uint64_t lastTouchTime_ = 0; - std::vector formLinkInfos_; + std::map formLinkInfoMap_; private: void DumpFrontend() const; diff --git a/frameworks/core/pipeline_ng/pipeline_context.cpp b/frameworks/core/pipeline_ng/pipeline_context.cpp index 2f53fbdc4b1..fb284402e4e 100644 --- a/frameworks/core/pipeline_ng/pipeline_context.cpp +++ b/frameworks/core/pipeline_ng/pipeline_context.cpp @@ -217,7 +217,7 @@ void PipelineContext::FlushVsync(uint64_t nanoTimestamp, uint32_t frameCount) ? AceApplicationInfo::GetInstance().GetPackageName() : AceApplicationInfo::GetInstance().GetProcessName(); window_->RecordFrameTime(nanoTimestamp, abilityName); - + FlushFrameTrace(); #ifdef UICAST_COMPONENT_SUPPORTED do { auto container = Container::Current(); @@ -227,7 +227,6 @@ void PipelineContext::FlushVsync(uint64_t nanoTimestamp, uint32_t frameCount) distributedUI->ApplyOneUpdate(); } while (false); #endif - FlushAnimation(GetTimeFromExternalTimer()); FlushTouchEvents(); FlushBuild(); @@ -261,9 +260,6 @@ void PipelineContext::FlushVsync(uint64_t nanoTimestamp, uint32_t frameCount) if (hasAnimation) { RequestFrame(); } - if (FrameReport::GetInstance().GetEnable()) { - FrameReport::GetInstance().FlushEnd(); - } FlushMessages(); InspectDrew(); if (!isFormRender_ && onShow_ && onFocus_) { @@ -278,6 +274,9 @@ void PipelineContext::FlushVsync(uint64_t nanoTimestamp, uint32_t frameCount) needRenderNode_.clear(); taskScheduler_.FlushAfterRenderTask(); // Keep the call sent at the end of the function + if (FrameReport::GetInstance().GetEnable()) { + FrameReport::GetInstance().FlushEnd(); + } ResSchedReport::GetInstance().LoadPageEvent(ResDefine::LOAD_PAGE_COMPLETE_EVENT); } @@ -289,6 +288,13 @@ void PipelineContext::InspectDrew() } } +void PipelineContext::FlushFrameTrace() +{ + if (FrameReport::GetInstance().GetEnable()) { + FrameReport::GetInstance().FlushBegin(); + } +} + void PipelineContext::FlushAnimation(uint64_t nanoTimestamp) { CHECK_RUN_ON(UI); @@ -296,11 +302,7 @@ void PipelineContext::FlushAnimation(uint64_t nanoTimestamp) if (scheduleTasks_.empty()) { return; } - FrameReport& fr = FrameReport::GetInstance(); - if (fr.GetEnable()) { - fr.FlushBegin(); - fr.BeginFlushAnimation(); - } + if (FrameReport::GetInstance().GetEnable()) { FrameReport::GetInstance().BeginFlushAnimation(); } @@ -773,6 +775,10 @@ void PipelineContext::SyncSafeArea() CHECK_NULL_VOID_NOLOG(!ignoreViewSafeArea_); CHECK_NULL_VOID_NOLOG(isLayoutFullScreen_); rootNode_->MarkDirtyNode(PROPERTY_UPDATE_MEASURE); + auto page = stageManager_->GetLastPage(); + if (page) { + page->MarkDirtyNode(PROPERTY_UPDATE_MEASURE); + } } void PipelineContext::OnVirtualKeyboardHeightChange( @@ -824,6 +830,10 @@ void PipelineContext::OnVirtualKeyboardHeightChange( safeAreaManager_->UpdateKeyboardOffset(-height - offsetFix / 2.0f); } rootNode_->MarkDirtyNode(PROPERTY_UPDATE_MEASURE); + auto page = stageManager_->GetLastPage(); + if (page) { + page->MarkDirtyNode(PROPERTY_UPDATE_LAYOUT); + } // layout immediately FlushUITasks(); @@ -1488,6 +1498,20 @@ void PipelineContext::HandleOnAreaChangeEvent() for (auto&& frameNode : nodes) { frameNode->TriggerOnAreaChangeCallback(); } + UpdateFormLinkInfos(); +} + +void PipelineContext::UpdateFormLinkInfos() +{ + if (formLinkInfoUpdateHandler_ && !formLinkInfoMap_.empty()) { + LOGI("formLinkInfoUpdateHandler called"); + std::vector formLinkInfos; + for (auto iter = formLinkInfoMap_.rbegin(); iter != formLinkInfoMap_.rend(); ++iter) { + auto info = iter->second; + formLinkInfos.push_back(info); + } + formLinkInfoUpdateHandler_(formLinkInfos); + } } void PipelineContext::OnShow() diff --git a/frameworks/core/pipeline_ng/pipeline_context.h b/frameworks/core/pipeline_ng/pipeline_context.h index 0028632f3bd..72fb3ace32a 100644 --- a/frameworks/core/pipeline_ng/pipeline_context.h +++ b/frameworks/core/pipeline_ng/pipeline_context.h @@ -379,6 +379,7 @@ protected: void FlushVsync(uint64_t nanoTimestamp, uint32_t frameCount) override; void FlushPipelineWithoutAnimation() override; void FlushFocus(); + void FlushFrameTrace(); void FlushAnimation(uint64_t nanoTimestamp) override; bool OnDumpInfo(const std::vector& params) const override; @@ -408,6 +409,9 @@ private: void SyncSafeArea(); + // only used for static form. + void UpdateFormLinkInfos(); + template struct NodeCompare { bool operator()(const T& nodeLeft, const T& nodeRight) const diff --git a/frameworks/core/pipeline_ng/test/mock/mock_pipeline_base.cpp b/frameworks/core/pipeline_ng/test/mock/mock_pipeline_base.cpp index a58a5267cde..36bd5c17eb5 100644 --- a/frameworks/core/pipeline_ng/test/mock/mock_pipeline_base.cpp +++ b/frameworks/core/pipeline_ng/test/mock/mock_pipeline_base.cpp @@ -409,6 +409,10 @@ bool PipelineBase::Animate(const AnimationOption& option, const RefPtr& c } void PipelineBase::Destroy() {} +bool PipelineBase::MaybeRelease() +{ + return AceType::MaybeRelease(); +} void PipelineBase::AddEtsCardTouchEventCallback(int32_t ponitId, EtsCardTouchEventCallback&& callback) {} diff --git a/interfaces/napi/kits/drag_controller/js_drag_controller.cpp b/interfaces/napi/kits/drag_controller/js_drag_controller.cpp index 47a8dbb94df..4761349a587 100644 --- a/interfaces/napi/kits/drag_controller/js_drag_controller.cpp +++ b/interfaces/napi/kits/drag_controller/js_drag_controller.cpp @@ -76,6 +76,16 @@ struct DragControllerAsyncCtx { }; } // namespace +napi_value CreateCallbackErrorValue(napi_env env, int32_t errCode) +{ + napi_value jsObject = nullptr; + napi_value jsValue = nullptr; + NAPI_CALL(env, napi_create_int32(env, errCode, &jsValue)); + NAPI_CALL(env, napi_create_object(env, &jsObject)); + NAPI_CALL(env, napi_set_named_property(env, jsObject, "code", jsValue)); + return jsObject; +} + void HandleSuccess(DragControllerAsyncCtx* asyncCtx, const DragNotifyMsg& dragNotifyMsg) { if (!asyncCtx) { @@ -103,12 +113,12 @@ void HandleSuccess(DragControllerAsyncCtx* asyncCtx, const DragNotifyMsg& dragNo LOGE("DragControllerAsyncContext is null"); return; } - napi_value result[1] = { nullptr }; - napi_get_undefined(asyncCtx->env, &result[0]); + napi_value result[2] = { nullptr }; + napi_get_undefined(asyncCtx->env, &result[1]); auto resultCode = dragNotifyMsg.result; LOGI("resultCode = %{public}d", static_cast(resultCode)); // do success thing - napi_create_object(asyncCtx->env, &result[0]); + napi_create_object(asyncCtx->env, &result[1]); napi_value eventNapi = nullptr; napi_value globalObj = nullptr; napi_value customDragEvent = nullptr; @@ -148,20 +158,21 @@ void HandleSuccess(DragControllerAsyncCtx* asyncCtx, const DragNotifyMsg& dragNo } dragEvent->SetResult(static_cast(resultCode)); jsDragEvent->SetDragEvent(dragEvent); - status = napi_set_named_property(asyncCtx->env, result[0], "event", eventNapi); + status = napi_set_named_property(asyncCtx->env, result[1], "event", eventNapi); napi_value extraParamsNapi = nullptr; napi_create_string_utf8( asyncCtx->env, asyncCtx->extraParams.c_str(), asyncCtx->extraParams.length(), &extraParamsNapi); - napi_set_named_property(asyncCtx->env, result[0], "extraParams", extraParamsNapi); + napi_set_named_property(asyncCtx->env, result[1], "extraParams", extraParamsNapi); if (asyncCtx->callbackRef) { napi_value ret = nullptr; napi_value napiCallback = nullptr; napi_get_reference_value(asyncCtx->env, asyncCtx->callbackRef, &napiCallback); - napi_call_function(asyncCtx->env, nullptr, napiCallback, 1, result, &ret); + result[0] = CreateCallbackErrorValue(asyncCtx->env, 0); + napi_call_function(asyncCtx->env, nullptr, napiCallback, argCount2, result, &ret); napi_delete_reference(asyncCtx->env, asyncCtx->callbackRef); } else { - napi_resolve_deferred(asyncCtx->env, asyncCtx->deferred, result[0]); + napi_resolve_deferred(asyncCtx->env, asyncCtx->deferred, result[1]); } }, TaskExecutor::TaskType::JS); @@ -178,14 +189,14 @@ void HandleFail(DragControllerAsyncCtx* asyncCtx, int32_t errorCode) if (asyncCtx->flag) { return; } - napi_value result[1] = { nullptr }; - napi_get_undefined(asyncCtx->env, &result[0]); - napi_create_int32(asyncCtx->env, static_cast(errorCode), &result[0]); + napi_value result[2] = { nullptr }; + result[0] = CreateCallbackErrorValue(asyncCtx->env, errorCode); if (asyncCtx->callbackRef) { napi_value ret = nullptr; napi_value napiCallback = nullptr; napi_get_reference_value(asyncCtx->env, asyncCtx->callbackRef, &napiCallback); - napi_call_function(asyncCtx->env, nullptr, napiCallback, 1, result, &ret); + napi_create_object(asyncCtx->env, &result[1]); + napi_call_function(asyncCtx->env, nullptr, napiCallback, argCount2, result, &ret); napi_delete_reference(asyncCtx->env, asyncCtx->callbackRef); } else { napi_reject_deferred(asyncCtx->env, asyncCtx->deferred, result[0]); diff --git a/test/fuzztest/acereskeyparser_fuzzer/BUILD.gn b/test/fuzztest/acereskeyparser_fuzzer/BUILD.gn index 25e575c97e9..4a4ce81fc68 100644 --- a/test/fuzztest/acereskeyparser_fuzzer/BUILD.gn +++ b/test/fuzztest/acereskeyparser_fuzzer/BUILD.gn @@ -118,10 +118,7 @@ ohos_fuzztest("AceResKeyParserFuzzTest") { "init_lite:libbegetutil", ] } - external_deps += [ - "c_utils:utils", - "window_manager:libwsutils", - ] + external_deps += [ "c_utils:utils" ] sources += [ "$ace_root/adapter/ohos/osal/log_wrapper.cpp", "$ace_root/frameworks/core/components/test/mock/mock_resource_adapter.cpp", diff --git a/test/fuzztest/arkressched_fuzzer/BUILD.gn b/test/fuzztest/arkressched_fuzzer/BUILD.gn index 8a7386f0fef..37ddb1e3203 100644 --- a/test/fuzztest/arkressched_fuzzer/BUILD.gn +++ b/test/fuzztest/arkressched_fuzzer/BUILD.gn @@ -52,14 +52,15 @@ ohos_fuzztest("ArkResschedFuzzTest") { ] defines = [ "FUZZTEST" ] - external_deps = [ "window_manager:libwsutils" ] + if (is_ohos_standard_system) { - external_deps += [ + external_deps = [ "hilog:libhilog", "init:libbegetutil", ] + #deps += [ "$ace_flutter_engine_root/icu:ace_libicu_ohos" ] } else { - external_deps += [ + external_deps = [ "hilog:libhilog", "init_lite:libbegetutil", ] diff --git a/test/fuzztest/imageApi_fuzzer/BUILD.gn b/test/fuzztest/imageApi_fuzzer/BUILD.gn index ae0b7cac07e..6d1a2ae1616 100644 --- a/test/fuzztest/imageApi_fuzzer/BUILD.gn +++ b/test/fuzztest/imageApi_fuzzer/BUILD.gn @@ -131,10 +131,7 @@ ohos_fuzztest("ImageApiFuzzTest") { "init_lite:libbegetutil", ] } - external_deps += [ - "c_utils:utils", - "window_manager:libwsutils", - ] + external_deps += [ "c_utils:utils" ] sources += [ "$ace_root/adapter/ohos/osal/log_wrapper.cpp", "$ace_root/frameworks/core/components/test/mock/mock_resource_adapter.cpp", diff --git a/test/fuzztest/imageloader_fuzzer/BUILD.gn b/test/fuzztest/imageloader_fuzzer/BUILD.gn index 3396aec19da..29b7b4a0ce3 100644 --- a/test/fuzztest/imageloader_fuzzer/BUILD.gn +++ b/test/fuzztest/imageloader_fuzzer/BUILD.gn @@ -141,10 +141,7 @@ ohos_fuzztest("ImageLoaderFuzzTest") { "init_lite:libbegetutil", ] } - external_deps += [ - "c_utils:utils", - "window_manager:libwsutils", - ] + external_deps += [ "c_utils:utils" ] sources += [ "$ace_root/adapter/ohos/osal/log_wrapper.cpp", "$ace_root/frameworks/core/components/test/mock/mock_resource_adapter.cpp", diff --git a/test/fuzztest/manifest_fuzzer/BUILD.gn b/test/fuzztest/manifest_fuzzer/BUILD.gn index 88a1374628a..9deee680b1a 100644 --- a/test/fuzztest/manifest_fuzzer/BUILD.gn +++ b/test/fuzztest/manifest_fuzzer/BUILD.gn @@ -124,10 +124,7 @@ ohos_fuzztest("ManifestFuzzTest") { "init_lite:libbegetutil", ] } - external_deps += [ - "c_utils:utils", - "window_manager:libwsutils", - ] + external_deps += [ "c_utils:utils" ] sources += [ "$ace_root/adapter/ohos/osal/log_wrapper.cpp", "$ace_root/frameworks/core/components/test/mock/mock_resource_adapter.cpp", diff --git a/test/fuzztest/res2_fuzzer/BUILD.gn b/test/fuzztest/res2_fuzzer/BUILD.gn index e6efe8b7844..6e976354222 100644 --- a/test/fuzztest/res2_fuzzer/BUILD.gn +++ b/test/fuzztest/res2_fuzzer/BUILD.gn @@ -123,10 +123,7 @@ ohos_fuzztest("Res2FuzzTest") { "init_lite:libbegetutil", ] } - external_deps += [ - "c_utils:utils", - "window_manager:libwsutils", - ] + external_deps += [ "c_utils:utils" ] sources += [ "$ace_root/adapter/ohos/osal/log_wrapper.cpp", "$ace_root/frameworks/core/components/test/mock/mock_resource_adapter.cpp", diff --git a/test/fuzztest/sharedimagemanager_fuzzer/BUILD.gn b/test/fuzztest/sharedimagemanager_fuzzer/BUILD.gn index bfc906ddadd..6969dda41ac 100644 --- a/test/fuzztest/sharedimagemanager_fuzzer/BUILD.gn +++ b/test/fuzztest/sharedimagemanager_fuzzer/BUILD.gn @@ -120,10 +120,7 @@ ohos_fuzztest("SharedImageManagerFuzzTest") { "init_lite:libbegetutil", ] } - external_deps += [ - "c_utils:utils", - "window_manager:libwsutils", - ] + external_deps += [ "c_utils:utils" ] sources += [ "$ace_root/adapter/ohos/osal/log_wrapper.cpp", "$ace_root/frameworks/core/components/test/mock/mock_resource_adapter.cpp", diff --git a/test/mock/adapter/mock_ui_extension_helper_impl.cpp b/test/mock/adapter/mock_app_bar_helper_impl.cpp similarity index 79% rename from test/mock/adapter/mock_ui_extension_helper_impl.cpp rename to test/mock/adapter/mock_app_bar_helper_impl.cpp index 7f03361872c..44e2fbeb3c9 100644 --- a/test/mock/adapter/mock_ui_extension_helper_impl.cpp +++ b/test/mock/adapter/mock_app_bar_helper_impl.cpp @@ -13,11 +13,11 @@ * limitations under the License. */ -#include "core/common/ui_extension_helper.h" +#include "core/common/app_bar_helper.h" namespace OHOS::Ace { -RefPtr UIExtensionHelper::CreateUIExtensionNode(const std::string& bundleName, +RefPtr AppBarHelper::CreateUIExtensionNode(const std::string& bundleName, const std::string& abilityName, const std::map& params, std::function&& onRelease, std::function&& onError) @@ -25,4 +25,9 @@ RefPtr UIExtensionHelper::CreateUIExtensionNode(const std::string return nullptr; } +std::string AppBarHelper::QueryAppGalleryBundleName() +{ + return ""; +} + } // namespace OHOS::Ace \ No newline at end of file diff --git a/test/mock/base/mock_subwindow.h b/test/mock/base/mock_subwindow.h index edafd544c04..52ff8caac76 100644 --- a/test/mock/base/mock_subwindow.h +++ b/test/mock/base/mock_subwindow.h @@ -35,14 +35,13 @@ public: MOCK_METHOD2(ShowPopup, void(const RefPtr& newComponent, bool disableTouchEvent)); MOCK_METHOD2(ShowPopupNG, void(int32_t targetId, const NG::PopupInfo& popupInfo)); MOCK_METHOD1(HidePopupNG, void(int32_t targetId)); - MOCK_METHOD0(HidePopupNG, void()); MOCK_METHOD2(GetPopupInfoNG, void(int32_t targetId, NG::PopupInfo& popupInfo)); MOCK_METHOD1(CancelPopup, bool(const std::string& id)); MOCK_METHOD0(CloseMenu, void()); MOCK_METHOD0(ClearMenu, void()); MOCK_METHOD0(ClearMenuNG, void()); MOCK_METHOD2( - ShowDialogNG, RefPtr(const DialogProperties& dialogProps, const RefPtr& customNode)); + ShowDialogNG, RefPtr(const DialogProperties& dialogProps, std::function&& buildFunc)); MOCK_METHOD0(HideSubWindowNG, void()); MOCK_CONST_METHOD0(GetChildContainerId, int32_t()); MOCK_METHOD0(GetShown, bool()); diff --git a/test/mock/core/common/mock_container.cpp b/test/mock/core/common/mock_container.cpp index 608e9f6163a..0950c910985 100755 --- a/test/mock/core/common/mock_container.cpp +++ b/test/mock/core/common/mock_container.cpp @@ -23,6 +23,10 @@ int32_t g_id = 0; } // namespace RefPtr MockContainer::container_; +bool Frontend::MaybeRelease() +{ + return AceType::MaybeRelease(); +} int32_t Container::CurrentId() { diff --git a/test/mock/core/common/mock_frontend.h b/test/mock/core/common/mock_frontend.h index 6ed4c55e24e..8d54307c47c 100644 --- a/test/mock/core/common/mock_frontend.h +++ b/test/mock/core/common/mock_frontend.h @@ -40,7 +40,6 @@ public: MOCK_METHOD(void, UpdateState, (Frontend::State state), (override)); MOCK_METHOD(RefPtr, GetAccessibilityManager, (), (const override)); MOCK_METHOD(bool, IsForeground, (), (override)); - MOCK_METHOD(FrontendType, GetType, (), (override)); MOCK_METHOD(RefPtr, GetEventHandler, (), (override)); MOCK_METHOD(void, RebuildAllPages, (), (override)); MOCK_METHOD(void, SetColorMode, (ColorMode colorMode), (override)); diff --git a/test/mock/core/common/mock_udmf.h b/test/mock/core/common/mock_udmf.h index e64171e2221..eaf220f7d1e 100644 --- a/test/mock/core/common/mock_udmf.h +++ b/test/mock/core/common/mock_udmf.h @@ -48,8 +48,8 @@ public: void, AddPixelMapRecord, (const RefPtr& unifiedData, (std::vector& data)), (override)); MOCK_METHOD(void, AddImageRecord, (const RefPtr& unifiedData, const std::string& uri), (override)); MOCK_METHOD( - void, AddTextRecord, (const RefPtr& unifiedData, const std::string& selectedStr), (override)); - MOCK_METHOD(std::string, GetSingleTextRecord, (const RefPtr& unifiedData), (override)); + void, AddPlainTextRecord, (const RefPtr& unifiedData, const std::string& selectedStr), (override)); + MOCK_METHOD(std::string, GetSinglePlainTextRecord, (const RefPtr& unifiedData), (override)); MOCK_METHOD(int32_t, GetVideoRecordUri, (const RefPtr& unifiedData, std::string& uri), (override)); }; class MockUnifiedData : public UnifiedData { diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 9ceed38950b..d50f3c3199f 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -183,6 +183,7 @@ ohos_source_set("ace_components_layout") { "$ace_root/frameworks/core/components_ng/layout/layout_wrapper.cpp", "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_builder.cpp", "$ace_root/frameworks/core/components_ng/layout/layout_wrapper_node.cpp", + "$ace_root/frameworks/core/components_ng/manager/safe_area/safe_area_manager.cpp", ] configs = [ ":ace_unittest_config" ] } diff --git a/test/unittest/core/pattern/window_scene/window_scene_test.cpp b/test/unittest/core/pattern/window_scene/window_scene_test.cpp index 6d36f300b4d..496980bc578 100644 --- a/test/unittest/core/pattern/window_scene/window_scene_test.cpp +++ b/test/unittest/core/pattern/window_scene/window_scene_test.cpp @@ -104,7 +104,7 @@ HWTEST_F(WindowPatternTest, WindowPatternTest001, TestSize.Level1) * @tc.steps: step1. Create WindowSceneModel. */ auto model = WindowSceneModel(); - uint64_t persistentId = 0; + int32_t persistentId = 0; model.Create(persistentId); auto windowSceneNode = ViewStackProcessor::GetInstance()->GetMainElementNode(); @@ -125,7 +125,7 @@ HWTEST_F(WindowPatternTest, WindowPatternTest002, TestSize.Level1) Rosen::SessionInfo sessionInfo = { .bundleName_ = BUNDLE_NAME, .abilityName_ = ABILITY_NAME }; auto session = Rosen::SceneSessionManager::GetInstance().RequestSceneSession(sessionInfo); - uint64_t persistentId = session->GetPersistentId(); + auto persistentId = session->GetPersistentId(); model.Create(persistentId); auto frameNode = ViewStackProcessor::GetInstance()->GetMainElementNode(); @@ -153,7 +153,7 @@ HWTEST_F(WindowPatternTest, WindowPatternTest003, TestSize.Level1) Rosen::SessionInfo sessionInfo = { .bundleName_ = BUNDLE_NAME, .abilityName_ = ABILITY_NAME }; auto session = Rosen::SceneSessionManager::GetInstance().RequestSceneSession(sessionInfo); - uint64_t persistentId = session->GetPersistentId(); + auto persistentId = session->GetPersistentId(); model.Create(persistentId); auto frameNode = ViewStackProcessor::GetInstance()->GetMainElementNode(); @@ -185,7 +185,7 @@ HWTEST_F(WindowPatternTest, WindowPatternTest004, TestSize.Level1) Rosen::SessionInfo sessionInfo = { .bundleName_ = BUNDLE_NAME, .abilityName_ = ABILITY_NAME }; auto session = Rosen::SceneSessionManager::GetInstance().RequestSceneSession(sessionInfo); - uint64_t persistentId = session->GetPersistentId(); + auto persistentId = session->GetPersistentId(); /** * @tc.steps: step2. Set session state to STATE_DISCONNECT. @@ -236,7 +236,7 @@ HWTEST_F(WindowPatternTest, WindowPatternTest006, TestSize.Level1) Rosen::SessionInfo sessionInfo = { .bundleName_ = BUNDLE_NAME, .abilityName_ = ABILITY_NAME }; auto session = Rosen::SceneSessionManager::GetInstance().RequestSceneSession(sessionInfo); - uint64_t persistentId = session->GetPersistentId(); + auto persistentId = session->GetPersistentId(); model.Create(persistentId); } @@ -254,7 +254,7 @@ HWTEST_F(WindowPatternTest, WindowPatternTest010, TestSize.Level1) Rosen::SessionInfo sessionInfo = { .bundleName_ = BUNDLE_NAME, .abilityName_ = ABILITY_NAME, .isSystem_ = true }; auto session = Rosen::SceneSessionManager::GetInstance().RequestSceneSession(sessionInfo); - uint64_t persistentId = session->GetPersistentId(); + auto persistentId = session->GetPersistentId(); model.Create(persistentId); auto frameNode = ViewStackProcessor::GetInstance()->GetMainElementNode(); diff --git a/test/unittest/core/pipeline/BUILD.gn b/test/unittest/core/pipeline/BUILD.gn index d5c8b35169e..065065a8c7e 100644 --- a/test/unittest/core/pipeline/BUILD.gn +++ b/test/unittest/core/pipeline/BUILD.gn @@ -279,7 +279,7 @@ ohos_unittest("pipeline_context_test_ng") { "$ace_root/frameworks/core/components_ng/test/mock/rosen/testing_typography_style.cpp", "$ace_root/frameworks/core/components_ng/test/pattern/text/mock/mock_text_layout_adapter.cpp", "$ace_root/frameworks/core/pipeline_ng/test/mock/mock_element_register.cpp", - "$ace_root/test/mock/adapter/mock_ui_extension_helper_impl.cpp", + "$ace_root/test/mock/adapter/mock_app_bar_helper_impl.cpp", "$ace_root/test/mock/base/mock_event_report.cpp", "$ace_root/test/mock/core/common/mock_container.cpp", "$ace_root/test/mock/core/common/mock_font_loader_ng.cpp", diff --git a/test/unittest/core/pipeline/mock_overlay_manager.cpp b/test/unittest/core/pipeline/mock_overlay_manager.cpp index 64abbc84fc3..6ba26a78ec1 100644 --- a/test/unittest/core/pipeline/mock_overlay_manager.cpp +++ b/test/unittest/core/pipeline/mock_overlay_manager.cpp @@ -46,7 +46,7 @@ void OverlayManager::ShowMenu(int32_t targetId, const NG::OffsetF& offset, RefPt // subwindow only contains one menu instance. void OverlayManager::ShowMenuInSubWindow(int32_t targetId, const NG::OffsetF& offset, RefPtr menu) {} -void OverlayManager::HideMenu(int32_t targetId) {} +void OverlayManager::HideMenu(int32_t targetId, bool isMenuOnTouch) {} void OverlayManager::HideAllMenus() {} @@ -55,7 +55,7 @@ void OverlayManager::DeleteMenu(int32_t targetId) {} void OverlayManager::CleanMenuInSubWindow() {} RefPtr OverlayManager::ShowDialog( - const DialogProperties& dialogProps, const RefPtr& customNode, bool isRightToLeft) + const DialogProperties& dialogProps, std::function&& buildFunc, bool isRightToLeft) { return nullptr; }