diff --git a/.clang-format b/.clang-format index 0a0df0c152d..c433c9809ef 100644 --- a/.clang-format +++ b/.clang-format @@ -79,6 +79,7 @@ IncludeIsMainRegex: '(Test)?$' IndentCaseLabels: false IndentWidth: 4 IndentWrappedFunctionNames: false +InsertBraces: false JavaScriptQuotes: Leave JavaScriptWrapImports: true KeepEmptyLinesAtTheStartOfBlocks: false diff --git a/.gitignore b/.gitignore index de76458a885..bb073b45dc2 100644 --- a/.gitignore +++ b/.gitignore @@ -280,7 +280,6 @@ tmp/ /tests/manual/ssh/shell/shell /tests/tools/qml-ast2dot/qml-ast2dot /tests/unit/echoserver/echo -/tests/unit/unittest/unittest # qbs builds /*-debug/ diff --git a/.gitmodules b/.gitmodules index 428e75ff118..45d62de0644 100644 --- a/.gitmodules +++ b/.gitmodules @@ -6,9 +6,9 @@ path = src/tools/perfparser url = ../perfparser.git ignore = dirty -[submodule "googletest"] - path = tests/unit/unittest/3rdparty/googletest - url = https://github.com/google/googletest.git [submodule "src/libs/qlitehtml"] path = src/libs/qlitehtml url = https://code.qt.io/playground/qlitehtml.git +[submodule "googletest"] + path = src/libs/3rdparty/googletest + url = https://github.com/google/googletest.git diff --git a/cmake/FindGoogletest.cmake b/cmake/FindGoogletest.cmake deleted file mode 100644 index e3bd22ba217..00000000000 --- a/cmake/FindGoogletest.cmake +++ /dev/null @@ -1,116 +0,0 @@ -#.rst: -# FindGoogletest -# ----------------- -# -# Try to locate the Googletest source files, and then build them as a -# static library. -# -# The ``GOOGLETEST_DIR`` (CMake or Environment) variable should be used -# to pinpoint the Googletest source files. -# -# If found, this will define the following variables: -# -# ``Googletest_FOUND`` -# True if the Googletest source package has been found. -# -# ``Googletest`` -# Target compiled as static library. -# - -find_path(GOOGLE_TEST_INCLUDE_DIR - NAMES gtest/gtest.h - PATH_SUFFIXES googletest/include - HINTS - "${GOOGLETEST_DIR}" ENV GOOGLETEST_DIR - "${PROJECT_SOURCE_DIR}/googletest" - "${PROJECT_SOURCE_DIR}/../googletest" - "${PROJECT_SOURCE_DIR}/../../googletest" - "${PROJECT_SOURCE_DIR}/tests/unit/unittest/3rdparty/googletest" -) - -find_path(GOOGLE_TEST_SRC_ALL - NAMES gtest-all.cc - PATH_SUFFIXES googletest/src - HINTS - "${GOOGLETEST_DIR}" ENV GOOGLETEST_DIR - "${PROJECT_SOURCE_DIR}/googletest" - "${PROJECT_SOURCE_DIR}/../googletest" - "${PROJECT_SOURCE_DIR}/../../googletest" - "${PROJECT_SOURCE_DIR}/tests/unit/unittest/3rdparty/googletest" -) - - -find_path(GOOGLE_MOCK_INCLUDE_DIR - NAMES gmock/gmock.h - PATH_SUFFIXES googlemock/include - HINTS - "${GOOGLETEST_DIR}" ENV GOOGLETEST_DIR - "${PROJECT_SOURCE_DIR}/googletest" - "${PROJECT_SOURCE_DIR}/../googletest" - "${PROJECT_SOURCE_DIR}/../../googletest" - "${PROJECT_SOURCE_DIR}/tests/unit/unittest/3rdparty/googletest" -) - -find_path(GOOGLE_MOCK_SRC_ALL - NAMES gmock-all.cc - PATH_SUFFIXES googlemock/src - HINTS - "${GOOGLETEST_DIR}" ENV GOOGLETEST_DIR - "${PROJECT_SOURCE_DIR}/googletest" - "${PROJECT_SOURCE_DIR}/../googletest" - "${PROJECT_SOURCE_DIR}/../../googletest" - "${PROJECT_SOURCE_DIR}/tests/unit/unittest/3rdparty/googletest" -) - -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(Googletest - DEFAULT_MSG - GOOGLE_TEST_INCLUDE_DIR GOOGLE_MOCK_INCLUDE_DIR - GOOGLE_TEST_SRC_ALL GOOGLE_MOCK_SRC_ALL -) -find_package(Threads REQUIRED) - -if(Googletest_FOUND AND NOT TARGET Googletest) - add_library(Googletest STATIC - "${GOOGLE_TEST_SRC_ALL}/gtest-all.cc" - "${GOOGLE_MOCK_SRC_ALL}/gmock-all.cc" - ) - target_include_directories(Googletest - PUBLIC - "${GOOGLE_TEST_INCLUDE_DIR}" - "${GOOGLE_MOCK_INCLUDE_DIR}" - PRIVATE - "${GOOGLE_TEST_SRC_ALL}/.." - "${GOOGLE_MOCK_SRC_ALL}/.." - ) - target_compile_definitions(Googletest - PRIVATE - GTEST_HAS_STD_INITIALIZER_LIST_ - GTEST_LANG_CXX11 - GTEST_HAS_STD_TUPLE_ - GTEST_HAS_STD_TYPE_TRAITS_ - GTEST_HAS_STD_FUNCTION_ - GTEST_HAS_RTTI - GTEST_HAS_STD_BEGIN_AND_END_ - GTEST_HAS_STD_UNIQUE_PTR_ - GTEST_HAS_EXCEPTIONS - GTEST_HAS_STREAM_REDIRECTION - GTEST_HAS_TYPED_TEST - GTEST_HAS_TYPED_TEST_P - GTEST_HAS_PARAM_TEST - GTEST_HAS_DEATH_TEST - ) - set_target_properties(Googletest PROPERTIES AUTOMOC OFF AUTOUIC OFF QT_COMPILE_OPTIONS_DISABLE_WARNINGS ON) - set_property(TARGET Googletest PROPERTY POSITION_INDEPENDENT_CODE ON) - target_compile_definitions(Googletest PUBLIC GOOGLE_TEST_IS_FOUND) - - target_link_libraries(Googletest Threads::Threads) -endif() - -mark_as_advanced(GOOGLE_TEST_INCLUDE_DIR GOOGLE_MOCK_INCLUDE_DIR - GOOGLE_TEST_SRC_ALL GOOGLE_MOCK_SRC_ALL) - -include(FeatureSummary) -set_package_properties(Googletest PROPERTIES - URL "https://github.com/google/googletest" - DESCRIPTION "Google Testing and Mocking Framework") diff --git a/dist/branding/qtdesignstudio/QtCreatorIDEBranding.cmake b/dist/branding/qtdesignstudio/QtCreatorIDEBranding.cmake index 9b805bff125..5877838a481 100644 --- a/dist/branding/qtdesignstudio/QtCreatorIDEBranding.cmake +++ b/dist/branding/qtdesignstudio/QtCreatorIDEBranding.cmake @@ -1,6 +1,6 @@ -set(IDE_VERSION "4.2.0") # The IDE version. -set(IDE_VERSION_COMPAT "4.2.0") # The IDE Compatibility version. -set(IDE_VERSION_DISPLAY "4.2.0") # The IDE display version. +set(IDE_VERSION "4.3.0") # The IDE version. +set(IDE_VERSION_COMPAT "4.3.0") # The IDE Compatibility version. +set(IDE_VERSION_DISPLAY "4.3.0") # The IDE display version. set(IDE_COPYRIGHT_YEAR "2023") # The IDE current copyright year. set(IDE_SETTINGSVARIANT "QtProject") # The IDE settings variation. diff --git a/doc/qtcreator/images/qtcreator-application-output.png b/doc/qtcreator/images/qtcreator-application-output.png deleted file mode 100644 index 064e8d9e0d3..00000000000 Binary files a/doc/qtcreator/images/qtcreator-application-output.png and /dev/null differ diff --git a/doc/qtcreator/images/qtcreator-application-output.webp b/doc/qtcreator/images/qtcreator-application-output.webp new file mode 100644 index 00000000000..4a6277c7ba4 Binary files /dev/null and b/doc/qtcreator/images/qtcreator-application-output.webp differ diff --git a/doc/qtcreator/images/qtcreator-compile-output.png b/doc/qtcreator/images/qtcreator-compile-output.png deleted file mode 100644 index 3ecc83c25ec..00000000000 Binary files a/doc/qtcreator/images/qtcreator-compile-output.png and /dev/null differ diff --git a/doc/qtcreator/images/qtcreator-compile-output.webp b/doc/qtcreator/images/qtcreator-compile-output.webp new file mode 100644 index 00000000000..ef7d16003b8 Binary files /dev/null and b/doc/qtcreator/images/qtcreator-compile-output.webp differ diff --git a/doc/qtcreator/images/qtcreator-general-messages.png b/doc/qtcreator/images/qtcreator-general-messages.png deleted file mode 100644 index 89d80a260cd..00000000000 Binary files a/doc/qtcreator/images/qtcreator-general-messages.png and /dev/null differ diff --git a/doc/qtcreator/images/qtcreator-general-messages.webp b/doc/qtcreator/images/qtcreator-general-messages.webp new file mode 100644 index 00000000000..c77cc159e4e Binary files /dev/null and b/doc/qtcreator/images/qtcreator-general-messages.webp differ diff --git a/doc/qtcreator/images/qtcreator-installed-plugins.png b/doc/qtcreator/images/qtcreator-installed-plugins.png deleted file mode 100644 index 2d9e9da951d..00000000000 Binary files a/doc/qtcreator/images/qtcreator-installed-plugins.png and /dev/null differ diff --git a/doc/qtcreator/images/qtcreator-installed-plugins.webp b/doc/qtcreator/images/qtcreator-installed-plugins.webp new file mode 100644 index 00000000000..b6aa4253b2b Binary files /dev/null and b/doc/qtcreator/images/qtcreator-installed-plugins.webp differ diff --git a/doc/qtcreator/images/qtcreator-issues.webp b/doc/qtcreator/images/qtcreator-issues.webp index 329a66b29b3..503e23a5113 100644 Binary files a/doc/qtcreator/images/qtcreator-issues.webp and b/doc/qtcreator/images/qtcreator-issues.webp differ diff --git a/doc/qtcreator/images/qtcreator-search-results-matches.webp b/doc/qtcreator/images/qtcreator-search-results-matches.webp new file mode 100644 index 00000000000..8b49a72fbf2 Binary files /dev/null and b/doc/qtcreator/images/qtcreator-search-results-matches.webp differ diff --git a/doc/qtcreator/images/qtcreator-search-results.png b/doc/qtcreator/images/qtcreator-search-results.png deleted file mode 100644 index 363207038a7..00000000000 Binary files a/doc/qtcreator/images/qtcreator-search-results.png and /dev/null differ diff --git a/doc/qtcreator/images/qtcreator-search-results.webp b/doc/qtcreator/images/qtcreator-search-results.webp new file mode 100644 index 00000000000..d36ec5e2851 Binary files /dev/null and b/doc/qtcreator/images/qtcreator-search-results.webp differ diff --git a/doc/qtcreator/images/qtcreator-searchresults.png b/doc/qtcreator/images/qtcreator-searchresults.png deleted file mode 100644 index 3e2bc2f5309..00000000000 Binary files a/doc/qtcreator/images/qtcreator-searchresults.png and /dev/null differ diff --git a/doc/qtcreator/images/qtcreator-to-do-entries.webp b/doc/qtcreator/images/qtcreator-to-do-entries.webp new file mode 100644 index 00000000000..0662993be13 Binary files /dev/null and b/doc/qtcreator/images/qtcreator-to-do-entries.webp differ diff --git a/doc/qtcreator/images/qtcreator-todo-pane.png b/doc/qtcreator/images/qtcreator-todo-pane.png deleted file mode 100644 index 21122b96a22..00000000000 Binary files a/doc/qtcreator/images/qtcreator-todo-pane.png and /dev/null differ diff --git a/doc/qtcreator/src/editors/creator-coding-edit-mode.qdoc b/doc/qtcreator/src/editors/creator-coding-edit-mode.qdoc index fb7cc429f43..c5042fd7553 100644 --- a/doc/qtcreator/src/editors/creator-coding-edit-mode.qdoc +++ b/doc/qtcreator/src/editors/creator-coding-edit-mode.qdoc @@ -1,4 +1,4 @@ -// Copyright (C) 2022 The Qt Company Ltd. +// Copyright (C) 2023 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only // ********************************************************************** @@ -11,7 +11,7 @@ \previouspage creator-editor-functions.html \page creator-coding-navigating.html \if defined(qtdesignstudio) - \nextpage creator-sidebars.html + \nextpage creator-views.html \else \nextpage creator-highlighting.html \endif @@ -246,7 +246,12 @@ \endlist To view the note, move the mouse pointer over the bookmark or open the - \uicontrol Bookmarks view in the \l{Working with Sidebars}{sidebar}. + \uicontrol Bookmarks view + \if defined(qtcreator) + in the \l{Show and hide sidebars}{sidebar}. + \else + in the \l{Managing Workspaces}{workspace}. + \endif \section2 Navigating Bookmarks @@ -358,13 +363,11 @@ \QC underlines semantic errors in olive in the C++ code editor. To check the correct paths for includes that are not resolved or that are resolved to the wrong file, select \uicontrol {Project Parts} > \uicontrol {Header Paths}. - \endif - \if defined(qtdesignstudio) + \else \section1 Related Topics \list - \li \l{Working with Sidebars} \li \l{Browsing Project Contents} \li \l{Viewing Output} \endlist diff --git a/doc/qtcreator/src/editors/creator-search.qdoc b/doc/qtcreator/src/editors/creator-search.qdoc index 13dc963896e..502a87367aa 100644 --- a/doc/qtcreator/src/editors/creator-search.qdoc +++ b/doc/qtcreator/src/editors/creator-search.qdoc @@ -176,7 +176,7 @@ \li Enter the text you are looking for and click \uicontrol Search. - \image qtcreator-searchresults.png + \image qtcreator-search-results-matches.webp {Found matches in Search Results} \l {Search Results} shows a list of files that have the searched text. diff --git a/doc/qtcreator/src/external-resources/external-resources-qds.qdoc b/doc/qtcreator/src/external-resources/external-resources-qds.qdoc index b1c64e785d1..610e0926344 100644 --- a/doc/qtcreator/src/external-resources/external-resources-qds.qdoc +++ b/doc/qtcreator/src/external-resources/external-resources-qds.qdoc @@ -57,3 +57,7 @@ \externalpage https://doc.qt.io/QtForMCUs/qtul-renesas-rh850-qsg.html \title Renesas RH850-D1M1A quick start guide */ +/*! + \externalpage https://doc.qt.io/QtForMCUs/qtul-known-issues.html + \title \QMCU Known Issues or Limitations +*/ diff --git a/doc/qtcreator/src/howto/creator-only/creator-how-to-enable-plugins.qdoc b/doc/qtcreator/src/howto/creator-only/creator-how-to-enable-plugins.qdoc new file mode 100644 index 00000000000..72592cdca5a --- /dev/null +++ b/doc/qtcreator/src/howto/creator-only/creator-how-to-enable-plugins.qdoc @@ -0,0 +1,35 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only + +/*! + \page creator-how-to-enable-plugins.html + \previouspage creator-how-tos.html + \nextpage creator-known-issues.html + \ingroup creator-how-to-use + + \title Enable and disable plugins + + New \QC plugins are often introduced as \e {experimental plugins} to let you + try them out before they are fully supported. Experimental plugins are + disabled by default and you must enable them for them to become visible + after you restart \QC. By default, all the plugins that the plugin depends + on are also enabled. + + You can also disable plugins that you do not use, to streamline \QC. + By default, all the plugins that depend on the plugin are also disabled. + + To enable and disable plugins: + + \list 1 + \li Select \uicontrol Help > \uicontrol {About Plugins}. + \li Start typing in the \uicontrol Filter field to find a plugin. + \image qtcreator-installed-plugins.webp {Installed Plugins dialog} + \li Select the \uicontrol Load check box to enable a plugin, or deselect + it to disable a plugin. + \li Select \uicontrol OK. + \li Select \uicontrol {Restart Now} to restart \QC and have the changes + take effect. + \endlist + + \sa {Install plugins}{How-to: Install plugins} +*/ diff --git a/doc/qtcreator/src/howto/creator-only/creator-how-to-install-plugins.qdoc b/doc/qtcreator/src/howto/creator-only/creator-how-to-install-plugins.qdoc new file mode 100644 index 00000000000..10eb5e36c45 --- /dev/null +++ b/doc/qtcreator/src/howto/creator-only/creator-how-to-install-plugins.qdoc @@ -0,0 +1,43 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only + +/*! + \page creator-how-to-install-plugins.html + \previouspage creator-how-tos.html + \nextpage creator-known-issues.html + \ingroup creator-how-to-use + + \title Install plugins + + \l{https://marketplace.qt.io/}{Qt Marketplace} has links to \QC plugins that + you can download and install either for free or for a price set by their + publisher. Browse the available plugins in the \uicontrol Marketplace tab + in the \uicontrol Welcome mode. + + You can also install plugins from other sources, such as + \l{https://github.com/}{GitHub}. + + \note You can install only plugins that your \QC version supports. + + To install plugins: + + \list 1 + \li Select \uicontrol Help > \uicontrol {About Plugins} > + \uicontrol {Install Plugins}. + \li In the \uicontrol Source dialog, enter the path to the archive + or library that has the plugin. + \image qtcreator-install-plugin-source.png + \li In the \uicontrol {Install Location} dialog, select + \uicontrol {User plugins} to make the plugin available for the + current user in all compatible \QC instances or + \uicontrol {\QC installation} to make the plugin available for + all users of a particular \QC instance. + \image qtcreator-install-plugin-location.png + \li In the \uicontrol Summary dialog, select \uicontrol Finish to + install the plugin. + \image qtcreator-install-plugin-summary.png + \li Select \uicontrol {Restart Now} to restart \QC and load the plugin. + \endlist + + \sa {Enable and disable plugins}{How-to: Enable and disable plugins} +*/ diff --git a/doc/qtcreator/src/howto/creator-only/creator-how-tos.qdoc b/doc/qtcreator/src/howto/creator-only/creator-how-tos.qdoc index e4fb87f7c10..ae2b15c2509 100644 --- a/doc/qtcreator/src/howto/creator-only/creator-how-tos.qdoc +++ b/doc/qtcreator/src/howto/creator-only/creator-how-tos.qdoc @@ -64,36 +64,13 @@ \section1 Use \QC \list + \li \l {Enable and disable plugins} \li \l {Find settings files} + \li \l {Install plugins} \li \l {Run \QC from the command line} \endlist */ -/*! - \page creator-how-to-switch-between-modes.html - \previouspage creator-how-tos.html - \nextpage creator-known-issues.html - \ingroup creator-how-to-ui - - \title Switch between modes - - \QC uses different modes for different purposes. You can quickly - switch between these modes with the following keyboard shortcuts: - - \list - - \li \uicontrol Welcome mode \key Ctrl+1 - \li \uicontrol Edit mode \key Ctrl+2 - \li \uicontrol Design mode \key Ctrl+3 - \li \uicontrol Debug mode \key Ctrl+4 - \li \uicontrol Projects mode \key Ctrl+5 - \li \uicontrol Help mode \key Ctrl+6 - - \endlist - - For more information about \QC modes, see \l {Selecting Modes}. -*/ - /*! \page creator-how-to-move-between-open-files.html \previouspage creator-how-tos.html @@ -216,28 +193,6 @@ For more information, see \l{Using Command Line Options}. */ -/*! - \page creator-how-to-show-and-hide-sidebars.html - \previouspage creator-how-tos.html - \nextpage creator-known-issues.html - \ingroup creator-how-to-ui - - \title Show and hide sidebars - - You can toggle the left and right sidebar in some \QC modes. - - To toggle the left sidebar, click \inlineimage icons/leftsidebaricon.png - (\uicontrol {Hide Left Sidebar/Show Left Sidebar}) or press \key Alt+0 - (\key Cmd+0 on \macos). - - To toggle the right sidebar, click \inlineimage icons/rightsidebaricon.png - (\uicontrol {Hide Right Sidebar/Show Right Sidebar}) or press - \key Alt+Shift+0 (\key Cmd+Shift+0 on \macos). - - For more information on using the sidebars, see - \l {Browsing Project Contents}. -*/ - /*! \page creator-how-to-move-to-symbols.html \previouspage creator-how-tos.html diff --git a/doc/qtcreator/src/howto/creator-only/creator-squish.qdoc b/doc/qtcreator/src/howto/creator-only/creator-squish.qdoc index 27918da3e48..874b4b389e4 100644 --- a/doc/qtcreator/src/howto/creator-only/creator-squish.qdoc +++ b/doc/qtcreator/src/howto/creator-only/creator-squish.qdoc @@ -130,7 +130,7 @@ \section1 Managing Test Suites and Cases You can manage Squish test suites and cases in the \uicontrol Squish - \l {Working with Sidebars}{view}. + \l {Show and hide sidebars}{view}. \image qtcreator-squish-view.png "Squish sidebar view" diff --git a/doc/qtcreator/src/meson/creator-projects-meson.qdoc b/doc/qtcreator/src/meson/creator-projects-meson.qdoc index ac15cd4ed83..ffc9a0d4c7b 100644 --- a/doc/qtcreator/src/meson/creator-projects-meson.qdoc +++ b/doc/qtcreator/src/meson/creator-projects-meson.qdoc @@ -22,7 +22,7 @@ in different build and run \l{glossary-buildandrun-kit}{kits}. \note Meson build plugin is disabled by default, see - \l{Enabling and Disabling Plugins}. + \l{Enable and disable plugins}{How-to: Enable and disable plugins}. \section1 Adding Meson Tools diff --git a/doc/qtcreator/src/overview/creator-only/creator-configuring.qdoc b/doc/qtcreator/src/overview/creator-only/creator-configuring.qdoc index 631e7e879c7..2e9330159f5 100644 --- a/doc/qtcreator/src/overview/creator-only/creator-configuring.qdoc +++ b/doc/qtcreator/src/overview/creator-only/creator-configuring.qdoc @@ -1,4 +1,4 @@ -// Copyright (C) 2021 The Qt Company Ltd. +// Copyright (C) 2023 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only // ********************************************************************** @@ -142,55 +142,16 @@ \section1 Managing Plugins \QC comes with a set of plugins, some of which are disabled by default. - You can enable disabled plugins if you need them and disable plugins you - don't need. + You can \l{Enable and disable plugins}{enable} disabled plugins if you + need them and disable plugins you don't need. - You can download and install additional plugins from + You can \l{Install plugins}{download and install} more plugins from \l{https://marketplace.qt.io/}{Qt Marketplace} or some other source, such as \l{https://github.com/}{GitHub}. - \section2 Enabling and Disabling Plugins - - New \QC plugins are often introduced as \e {experimental plugins} to let you - try them out before they are fully supported. Experimental plugins are - disabled by default and you must enable them for them to become visible - after you restart \QC. By default, all the plugins that the plugin depends - on are also enabled. - - You can also disable plugins that you do not use, to streamline \QC. - By default, all the plugins that depend on the plugin are also disabled. - To enable and disable plugins, select \uicontrol Help > \uicontrol {About Plugins}. - \image qtcreator-installed-plugins.png "Installed Plugins dialog" - - \section2 Installing Plugins - - Qt Marketplace has links to \QC plugins that you can download and - install either for free or for a price set by their publisher. You can - browse the available plugins in the \uicontrol Marketplace tab in the - Welcome mode. - - \note You can install only plugins that your \QC version supports. - - To install plugins: - - \list 1 - \li Select \uicontrol Help > \uicontrol {About Plugins} > - \uicontrol {Install Plugins}. - \li In the \uicontrol Source dialog, enter the path to the archive - or library that has the plugin. - \image qtcreator-install-plugin-source.png - \li In the \uicontrol {Install Location} dialog, select - \uicontrol {User plugins} to make the plugin available for the - current user in all compatible \QC instances or - \uicontrol {\QC installation} to make the plugin available for - all users of a particular \QC instance. - \image qtcreator-install-plugin-location.png - \li In the \uicontrol Summary dialog, select \uicontrol Finish to - install the plugin. - \image qtcreator-install-plugin-summary.png - \li Select \uicontrol {Restart Now} to restart \QC and load the plugin. - \endlist + To install plugins, select \uicontrol Help > \uicontrol {About Plugins} > + \uicontrol {Install Plugins}. */ diff --git a/doc/qtcreator/src/projects/creator-projects-running.qdoc b/doc/qtcreator/src/projects/creator-projects-running.qdoc index 2393c4d2bb1..a6311d58d0a 100644 --- a/doc/qtcreator/src/projects/creator-projects-running.qdoc +++ b/doc/qtcreator/src/projects/creator-projects-running.qdoc @@ -64,7 +64,7 @@ the application has large image files that would need to be bundled into the resource file before running the application. - \image qtcreator-application-output.png + \image qtcreator-application-output.webp {Application Output view} \if defined(qtcreator) For more information on the options you have, see diff --git a/doc/qtcreator/src/qtcreator-toc.qdoc b/doc/qtcreator/src/qtcreator-toc.qdoc index acf3ca83a7c..eb8ced88e3b 100644 --- a/doc/qtcreator/src/qtcreator-toc.qdoc +++ b/doc/qtcreator/src/qtcreator-toc.qdoc @@ -19,8 +19,6 @@ \li \l{IDE Overview} \li \l{User Interface} \list - \li \l{Selecting Modes} - \li \l{Working with Sidebars} \li \l{Browsing Project Contents} \list \li \l{Projects} diff --git a/doc/qtcreator/src/user-interface/creator-file-system-view.qdoc b/doc/qtcreator/src/user-interface/creator-file-system-view.qdoc index da554a3ab08..b7eddea19a0 100644 --- a/doc/qtcreator/src/user-interface/creator-file-system-view.qdoc +++ b/doc/qtcreator/src/user-interface/creator-file-system-view.qdoc @@ -1,4 +1,4 @@ -// Copyright (C) 2022 The Qt Company Ltd. +// Copyright (C) 2023 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only /*! @@ -8,8 +8,7 @@ \title File System - If you cannot see a file in the \l Projects view, switch to the - \uicontrol {File System} view, which shows all the files in the file system. + The \uicontrol {File System} view shows all the files in the file system. \note Usually, \l{Searching with the Locator}{searching with the locator} is the fastest way to find a particular project, file, class, or function, @@ -17,12 +16,9 @@ to open files from anywhere in the file system. \if defined(qtdesignstudio) - The following image displays the \uicontrol {File System} view in the - \uicontrol Design mode: - - \image qtcreator-filesystem-view-design.png "File System view in the Design mode" + \image qtcreator-filesystem-view-design.png {File System view} \else - \image qtcreator-filesystem-view.webp "File System view in the sidebar" + \image qtcreator-filesystem-view.webp {File System view in the sidebar} \endif To move to the root directory of the file system, select \uicontrol Computer @@ -87,19 +83,11 @@ \li Collapse all open folders. \endlist + \if defined(qtcreator) \section1 File System View Toolbar - \if defined(qtdesignstudio) - In the \uicontrol Edit and \uicontrol Debug mode, the - \uicontrol {File System} view is displayed in the \l{Working with Sidebars} - {sidebar}. It has a toolbar with additional options. - - \image qtcreator-filesystem-view.webp "File System view in the sidebar" - \else The toolbar in the \uicontrol {File System} view has additional options. - \endif - To manage view contents, select \inlineimage icons/filtericon.png (\uicontrol Options): @@ -116,4 +104,5 @@ To stop the synchronization with the file currently open in the editor, deselect \inlineimage icons/linkicon.png (\uicontrol {Synchronize with Editor}). + \endif */ diff --git a/doc/qtcreator/src/user-interface/creator-sidebars.qdoc b/doc/qtcreator/src/user-interface/creator-only/creator-how-to-show-and-hide-sidebars.qdoc similarity index 53% rename from doc/qtcreator/src/user-interface/creator-sidebars.qdoc rename to doc/qtcreator/src/user-interface/creator-only/creator-how-to-show-and-hide-sidebars.qdoc index aecb42aa76c..d1a07de2cef 100644 --- a/doc/qtcreator/src/user-interface/creator-sidebars.qdoc +++ b/doc/qtcreator/src/user-interface/creator-only/creator-how-to-show-and-hide-sidebars.qdoc @@ -1,24 +1,19 @@ -// Copyright (C) 2020 The Qt Company Ltd. +// Copyright (C) 2023 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only /*! - \page creator-sidebars.html - \if defined(qtdesignstudio) - \previouspage creator-coding-navigating.html - \else - \previouspage creator-modes.html - \endif - \nextpage creator-views.html + \page creator-how-to-show-and-hide-sidebars.html + \previouspage creator-how-tos.html + \nextpage creator-known-issues.html + \ingroup creator-how-to-ui + \title Show and hide sidebars - \title Working with Sidebars + In some \l{Switch between modes}{modes}, you can use a left and right + sidebar to organize different views into project contents. Only views + that are relevant to the mode you are working in are available in it. - In the \uicontrol Edit mode, you can use a left and right sidebar to - organize different views into project contents. Only views that are - relevant to the \l{Selecting Modes}{mode} you are working in are - available in it. - - You can select views in the sidebar menu (1): + Select views in the sidebar menu (1): \image qtcreator-sidebar.png @@ -27,8 +22,8 @@ \list \li To toggle the left sidebar, click \inlineimage icons/leftsidebaricon.png (\uicontrol {Hide Left Sidebar/Show Left Sidebar}) or press - \key Alt+0 (\key Cmd+0 on \macos). To toggle the right - sidebar, click \inlineimage icons/rightsidebaricon.png + \key Alt+0 (\key Cmd+0 on \macos). + \li To toggle the right sidebar, click \inlineimage icons/rightsidebaricon.png (\uicontrol {Hide Right Sidebar/Show Right Sidebar}) or press \key Alt+Shift+0 (\key Cmd+Shift+0 on \macos). \li To split a sidebar, click \inlineimage icons/splitbutton_horizontal.png diff --git a/doc/qtcreator/src/user-interface/creator-only/creator-how-to-switch-between-modes.qdoc b/doc/qtcreator/src/user-interface/creator-only/creator-how-to-switch-between-modes.qdoc new file mode 100644 index 00000000000..a43cffc4f04 --- /dev/null +++ b/doc/qtcreator/src/user-interface/creator-only/creator-how-to-switch-between-modes.qdoc @@ -0,0 +1,75 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only + +/*! + \page creator-how-to-switch-between-modes.html + \previouspage creator-how-tos.html + \nextpage creator-known-issues.html + \ingroup creator-how-to-ui + + \title Switch between modes + + \e Modes let you quickly switch between tasks such as editing + project and source files, designing application UIs, configuring projects + for building and running, and debugging or analyzing source code. + + To switch between modes: + + \list + \li Click the icons on the mode selector. + \li Use the \l{keyboard-shortcuts}{corresponding keyboard shortcut}. + \endlist + + \table + \header + \li {2,1} Mode + \li Keyboard Shortcut + \li Purpose + \li Read More + \row + \li {1,7} \inlineimage qtcreator-mode-selector.png + \row + \li \uicontrol Welcome + \li \key Ctrl+1 + \li Open projects, tutorials, and examples. + \li \l{User Interface} + \row + \li \uicontrol Edit + \li \key Ctrl+2 + \li Edit project and source files. + \li \l{Working in Edit Mode} + \row + \li \uicontrol Design + \li \key Ctrl+3 + \li Design and develop application user interfaces. + This mode is available for UI files. + \li \l{Designing User Interfaces} + \row + \li \uicontrol Debug + \li \key Ctrl+4 + \li Inspect the state of your application while debugging or use code + analysis tools to detect memory leaks and profile code. + \li \l{Debugging} + \row + \li \uicontrol Projects + \li \key Ctrl+5 + \li Configure how to build and run projects. + This mode is available when a project is open. + \li \l{Specifying Build Settings} + \row + \li \uicontrol Help + \li \key Ctrl+6 + \li Read documentation. + \li \l{Using the Help Mode} + \endtable + + Some actions in \QC trigger a mode change. For example, + selecting \uicontrol {Debug} > \uicontrol {Start Debugging} > + \uicontrol {Start Debugging of Startup Project} automatically + switches to \uicontrol {Debug} mode. + + To hide the mode selector and to save space on the display, select + \uicontrol View > \uicontrol {Mode Selector Style} > \uicontrol Hidden. + To only show icons on the mode selector, select the \uicontrol {Icons Only} + style. +*/ diff --git a/doc/qtcreator/src/user-interface/creator-projects-view.qdoc b/doc/qtcreator/src/user-interface/creator-projects-view.qdoc index cd8fd9a62a6..ef356c81cf4 100644 --- a/doc/qtcreator/src/user-interface/creator-projects-view.qdoc +++ b/doc/qtcreator/src/user-interface/creator-projects-view.qdoc @@ -1,4 +1,4 @@ -// Copyright (C) 2022 The Qt Company Ltd. +// Copyright (C) 2023 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only /*! @@ -13,6 +13,7 @@ \title Projects The \uicontrol Projects view displays projects in a project tree. + The project tree has a list of all projects open in the current \l{Managing Sessions}{session}. For each project, the tree visualizes the build system structure of the project and lists all files that @@ -23,12 +24,9 @@ or almost anything else in your project. \if defined(qtdesignstudio) - The following image displays the \uicontrol Projects view in the - \uicontrol Design mode: - - \image qtcreator-projects-view-design.png "Projects view in the Design mode" + \image qtcreator-projects-view-design.png {Projects view} \else - \image qtcreator-projects-view-edit.png "Projects view in the sidebar" + \image qtcreator-projects-view-edit.png {Projects view in the sidebar} \endif You can use the project tree in the following ways: @@ -37,8 +35,11 @@ \li To open files that belong to a \l{Creating Projects}{project}, double-click them in the project tree. Files open in the appropriate editor, according to the file type. For example, code - source files open in the code editor. Use the \l{Selecting Modes} - {mode selector} to open the current file in another editor. + source files open in the code editor. + \if defined(qtcreator) + Use the \l{Switch between modes} {mode selector} to open the current + file in another editor. + \endif \li To bring up a \l{Projects View Context Menu}{context menu} that has the actions most commonly needed, right-click an item in the project tree. For example, through the menu of @@ -51,6 +52,9 @@ configuration files. \endlist + \note If you cannot see a file in the \l Projects view, switch to the + \uicontrol {File System} view, which shows all the files in the file system. + \section1 Projects View Context Menu The \uicontrol Projects view has context menus for managing projects, @@ -58,8 +62,10 @@ projects and subprojects: \list + \if defined(qtcreator) \li Set a project as the active project. - \li Execute the \uicontrol Build menu commands. + \endif + \li Execute \uicontrol Build menu commands. \li Create new files. For more information, see \if defined(qtdesignstudio) \l{Adding Files to Projects}. @@ -106,18 +112,10 @@ the \l {File System} view. To view a project in it, select \uicontrol {Show in File System View}. + \if defined(qtcreator) \section1 Projects View Toolbar - \if defined(qtdesignstudio) - In the \uicontrol Edit and \uicontrol Debug mode, the - \l{Working with Sidebars}{sidebar} has the \uicontrol Projects - view. It has a toolbar with additional options. - - \image qtcreator-projects-view-edit.png "Projects view in the sidebar" - \else The toolbar in the \uicontrol Projects view has additional options. - \endif - To filter view contents, select \inlineimage icons/filtericon.png (\uicontrol {Filter Tree}): @@ -140,7 +138,6 @@ currently opened in the editor, deselect \inlineimage icons/linkicon.png (\uicontrol {Synchronize with Editor}). - \if defined(qtcreator) Some build systems support adding and removing files to a project in \QC (currently qmake and Qbs). The faithful display of the project structure enables you to specify exactly where to place a new file in the build system. @@ -152,8 +149,5 @@ from the version control system in brackets after the project name. \QC currently implements this for Git (the view displays the branch name or a tag) and ClearCase (the view displays the branch name). - \else - If the project is under Git version control, you can see the currently - checked out branch or tag in brackets after the project name. \endif */ diff --git a/doc/qtcreator/src/user-interface/creator-ui.qdoc b/doc/qtcreator/src/user-interface/creator-ui.qdoc index f2261381d55..29fe61bb26b 100644 --- a/doc/qtcreator/src/user-interface/creator-ui.qdoc +++ b/doc/qtcreator/src/user-interface/creator-ui.qdoc @@ -11,10 +11,11 @@ \page creator-quick-tour.html \if defined(qtdesignstudio) \previouspage {Tutorials} + \nextpage creator-using-qt-quick-designer.html \else \previouspage creator-overview.html + \nextpage creator-views.html \endif - \nextpage creator-modes.html \title User Interface @@ -34,7 +35,7 @@ \li Mode selector \li Perform a particular task, such as designing the UI, writing code, or debugging the application. - \li \l{Selecting Modes} + \li \l{Switch between modes} \row \li \inlineimage numbers/02.png \li Kit selector @@ -81,9 +82,11 @@ For information about new features and bug fixes in each \QC release, select \uicontrol Help > \uicontrol {Change Log}. - \sa {Working with Sidebars}, {Browsing Project Contents} + \sa {Show and hide sidebars}, {Browsing Project Contents} \sa {Use the UI}{How-to: Use the UI} + \else + When you start \QC, it opens to the \uicontrol Welcome mode, where you can: \list @@ -139,91 +142,6 @@ \endif */ -/*! - \page creator-modes.html - \previouspage creator-quick-tour.html - \if defined(qtdesignstudio) - \nextpage creator-using-qt-quick-designer.html - \else - \nextpage creator-sidebars.html - \endif - - \title Selecting Modes - - \image qtcreator-mode-selector.png - - \if defined(qtcreator) - The mode selector allows you to quickly switch between tasks such as editing - project and source files, designing application UIs, configuring projects for - building and running, and debugging your applications. To change - modes, click the icons, or use the \l{keyboard-shortcuts} - {corresponding keyboard shortcut}. - - To hide the mode selector and to save space on the display, select - \uicontrol View > \uicontrol {Mode Selector Style} > \uicontrol Hidden. - To only show icons on the mode selector, select the \uicontrol {Icons Only} - style. - \endif - - \if defined(qtdesignstudio) - The mode selector is hidden by default. - - To show the mode selector, go to \uicontrol Views > - \uicontrol {Mode Selector Style} and select \uicontrol {Icons and Text} - or \uicontrol {Icons Only}. - \endif - - - You can use \QC in the following modes: - - \list - - \li \uicontrol {\l{User Interface}{Welcome}} mode for opening projects, - tutorials, and examples. - - \li \uicontrol{\l{Coding}{Edit}} mode for editing project and source - files. - - \if defined(qtcreator) - \li \uicontrol{\l{Designing User Interfaces}{Design}} - mode for designing and developing application user interfaces. - This mode is available for UI files. - \else - \li \uicontrol{\l{Design Views}{Design}} - mode for designing and developing application user interfaces. - As a designer, you'll do most of your work in this mode. - \endif - - \if defined(qtcreator) - \li \uicontrol{\l{Debugging}{Debug}} - \else - \li \uicontrol {\l{Debugging and Profiling}{Debug}} - \endif - mode for inspecting the state of your - application while debugging and for using code analysis tools - to detect memory leaks and profile code. - - \if defined(qtcreator) - \li \uicontrol{\l{Specifying Build Settings}{Projects}} mode - for configuring project building and execution. - \else - \li \uicontrol{\l{Selecting the Preview Tool}{Projects}} mode - for selecting the tool to use for live preview. - \endif - This mode is available when a project is open. - - \li \uicontrol{\l{Using the Help Mode}{Help}} mode for viewing - documentation. - - \endlist - - \if defined(qtcreator) - Certain actions in \QC trigger a mode change. Clicking on \uicontrol {Debug} > - \uicontrol {Start Debugging} > \uicontrol {Start Debugging} automatically switches to - \uicontrol {Debug} mode. - \endif -*/ - /*! \page creator-output-panes.html \if defined(qtdesignstudio) @@ -236,9 +154,9 @@ \title Viewing Output - \image qtcreator-general-messages.png "General Messages" + \image qtcreator-general-messages.webp {General Messages} - The taskbar in \QC can display following types of output: + You can view the following types of output: \list @@ -276,7 +194,12 @@ \endlist - Output is available on the taskbar in all \l{Selecting Modes}{modes}. + Output is available on the taskbar in all + \if defined(qtcreator) + \l{Switch between modes}{modes}. + \else + \l{Mode}{modes}. + \endif \image qtcreator-output-panes-taskbar.webp "Output on the taskbar" @@ -441,7 +364,7 @@ In \uicontrol{Search Results}, you can search through projects, files on a file system or the currently open files: - \image qtcreator-search-results.png "Search Results" + \image qtcreator-search-results.webp {Search Results - criteria} The search history (1) stores the search results. You can select earlier searches from the history. @@ -449,7 +372,7 @@ The figure below shows an example search result for all occurrences of the search string in the specified directory. - \image qtcreator-searchresults.png + \image qtcreator-search-results-matches.webp {Search Results - matches found} For more information about the different search options, see \l {Finding and Replacing}. @@ -459,7 +382,7 @@ \uicontrol{Application Output} displays the status of a program when you execute it, and the debug output. - \image qtcreator-application-output.png + \image qtcreator-application-output.webp {Application Output} \if defined(qtcreator) If you specify command line arguments in the run settings that are passed @@ -485,7 +408,7 @@ The \uicontrol{Compile Output} is a more detailed version of information displayed in \l Issues. - \image qtcreator-compile-output.png "Compile Output" + \image qtcreator-compile-output.webp {Compile Output} Double-click on a file name in an error message to open the file in the code editor. @@ -636,13 +559,13 @@ subproject. Click the icons on the toolbar to show only the selected keywords. - \image qtcreator-todo-pane.png + \image qtcreator-to-do-entries.webp {To-Do Entries} To add keywords, select \uicontrol Edit > \uicontrol Preferences > \uicontrol {To-Do} > \uicontrol Add. Set an icon and a line background color for the keyword. - \image qtcreator-todo-options.png "To-Do preferences" + \image qtcreator-todo-options.png {To-Do preferences} To change the icon and line background color of the selected keyword, select \uicontrol Edit. @@ -659,7 +582,7 @@ To exclude files from scanning, select \uicontrol {Project Settings} > \uicontrol {To-Do} in the \uicontrol Projects mode. - \image qtcreator-todo-excluded-files.png "Excluded Files in To-Do preferences" + \image qtcreator-todo-excluded-files.png {Excluded Files in To-Do preferences} Select \uicontrol Add and double-click the placeholder text in \uicontrol {Exclude Files} to enter a regular expression that diff --git a/doc/qtcreator/src/user-interface/creator-views.qdoc b/doc/qtcreator/src/user-interface/creator-views.qdoc index e676ed18907..673e902736d 100644 --- a/doc/qtcreator/src/user-interface/creator-views.qdoc +++ b/doc/qtcreator/src/user-interface/creator-views.qdoc @@ -1,26 +1,25 @@ -// Copyright (C) 2021 The Qt Company Ltd. +// Copyright (C) 2023 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only /*! \page creator-views.html - \previouspage creator-sidebars.html \if defined(qtdesignstudio) + \previouspage creator-coding-navigating.html \nextpage creator-output-panes.html \else + \previouspage creator-quick-tour.html \nextpage creator-projects-view.html \endif \title Browsing Project Contents - You can organize \QC views in \l {Working with Sidebars}{sidebars} or as \if defined(qtdesignstudio) - \l {Managing Workspaces}{workspaces}, + You can organize \QDS views as \l {Managing Workspaces}{workspaces}. \else - workspaces + You can organize \QC views in \l {Show and hide sidebars}{sidebars} or as + workspaces, depending on the \l{Switch between modes}{mode} you are working + in. Only views that are relevant to a mode are available in it. \endif - depending on the \l{Selecting Modes} - {mode} you are working in. Only views that are relevant to a mode are - available in it. \note Usually, \l{Searching with the Locator}{searching with the locator} is the fastest way to find a particular project, file, class, or function, diff --git a/doc/qtdesignstudio/config/qtdesignstudio.qdocconf b/doc/qtdesignstudio/config/qtdesignstudio.qdocconf index 5bcfe70d400..86a948bd889 100644 --- a/doc/qtdesignstudio/config/qtdesignstudio.qdocconf +++ b/doc/qtdesignstudio/config/qtdesignstudio.qdocconf @@ -54,6 +54,7 @@ excludedirs += ../../qtcreator/examples/accelbubble \ ../../qtcreator/src/python \ ../../qtcreator/src/qnx \ ../../qtcreator/src/qtquick/creator-only \ + ../../qtcreator/src/user-interface/creator-only \ ../../qtcreator/src/vcs/creator-only \ ../../qtcreator/src/widgets \ ../../qtcreator/src/webassembly diff --git a/doc/qtdesignstudio/examples/Loginui1/src/main.cpp b/doc/qtdesignstudio/examples/Loginui1/src/main.cpp index 1df03ed16b6..eacbde58784 100644 --- a/doc/qtdesignstudio/examples/Loginui1/src/main.cpp +++ b/doc/qtdesignstudio/examples/Loginui1/src/main.cpp @@ -14,7 +14,7 @@ int main(int argc, char *argv[]) QGuiApplication app(argc, argv); QQmlApplicationEngine engine; - const QUrl url(u"qrc:Main/main.qml"_qs); + const QUrl url(u"qrc:/qt/qml/Main/main.qml"_qs); QObject::connect( &engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) { diff --git a/doc/qtdesignstudio/examples/doc/3DsceneTutorial.qdoc b/doc/qtdesignstudio/examples/doc/3DsceneTutorial.qdoc new file mode 100644 index 00000000000..78a3490113f --- /dev/null +++ b/doc/qtdesignstudio/examples/doc/3DsceneTutorial.qdoc @@ -0,0 +1,120 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only + +/*! + \page 3d-scene-tutorial.html + \ingroup gstutorials + + \title Setting up a 3D Scene + \sa {Content Library} + \brief Illustrates how to set up a 3D scene with, for example, lights, models, and materials in + \QDS. + + \image 3d-scene-tutorial.webp + + The \e {Setting up a 3D Scene} tutorial illustrates how you can set up and improve a 3D + scene with the following: + \list + \li 3D models + \li Materials + \li Lights + \li Environmental lights + \li Background images + \endlist + + The assets you use in this tutorial are available in \uicontrol {Content Library}. + + To follow this tutorial, you need to first download the starting project from + \l{https://git.qt.io/public-demos/qtdesign-studio/-/tree/master/tutorial%20projects/3Dscene%20tutorial/Start}{here}. + + Download the completed project from + \l{https://git.qt.io/public-demos/qtdesign-studio/-/tree/master/tutorial%20projects/3Dscene%20tutorial/Completed/}{here}. + + This tutorial requires that you know the basics of \QDS, see + \l{Getting Started}. + + \section1 The Starting Project + + The starting project consists of an animated 3D model of a ball bearing. Control the animations + with a slider and a switch in the user interface. + + Besides the 3D model, the 3D scene also has the default camera and the default directional + light. + + \section1 Adding Materials to the 3D Models + + First, use materials from \uicontrol {Content Library} on the ball bearing. + + \list 1 + \li In the \uicontrol 3D view, right-click the ball bearing and select + \uicontrol {Edit Component}. + \image 3d-scene-edit-component-menu.png + \li From \uicontrol {Content Library}, drag materials to the different parts of the ball + bearing in the \uicontrol Navigator view. + Drag the following materials to the following parts: + \list + \li Chrome to \e inner_race and \e outer_race. + \li Copper to \e balls. + \li Gold to \e retainer. + \li Carbon Fiber to \e shield_left and \e shield_right. + \endlist + \note The first time you use an asset from \uicontrol {Content Library}, you need to + download it. + \image 3d-scene-drag-material.png + \li Select \e {Screen01.ui.qml} in the breadcrumb in the top menu bar to return to the 3D + scene. + \image 3d-scene-bread-crumb.png + \endlist + When you run the application or live preview, notice that you don't see much of the materials. + The next step is to set up the environmental light. + + \section1 Adding Environmental Lighting to the Scene + + Environmental lighting is a good way to create a realistic light for your scene. + + \list 1 + \li In \uicontrol {Content Library}, go to the \uicontrol Environments tab. + \li Right-click the image \e BasicLights3_4k.hdr and select \uicontrol {Add Light Probe}. + \image 3d-scene-add-light-probe.webp + Setting an image as a light probe for a scene adds the image as the source for the image-based + lighting and also sets it as a skybox, meaning that the same image is used as the background + in the scene. + \endlist + + When you run the application, notice an improvement in the scene lighting. + + Next, adjust the environmental light. As you will add a background image to the scene later, + you don't want to use the skybox. + \list 1 + \li In the \uicontrol Navigator view, select \e sceneEnvironment. + \li In the \uicontrol Properties view, set \uicontrol {Background Mode} to + \uicontrol Transparent. + \endlist + + You also want to increase the brightness of the light a bit. In the \uicontrol Properties view, + set \uicontrol Exposure to 10. + + \section2 Adding a Background Image to the Scene + + In the final step of this tutorial, you add a background image to your scene. + + \list 1 + \li Go to the \uicontrol Textures tab in \uicontrol {Content Library}. + \li Right-click the image \e 4kScratchySurface.png and select \uicontrol {Add Texture} + \image 3d-scene-add-texture.webp + This adds the image as a texture to the project. It is now available in the \uicontrol Assets + view. + \li From the \uicontrol Assets view, drag \e 4KScratchySurface.png to \e Rectangle in the + \uicontrol Navigator view. + \li Go to the \uicontrol Layout tab in \uicontrol Properties and set \uicontrol Anchors to + \uicontrol FillParentComponent. + \image 3d-scene-fill-parent.png + \li Go to the \uicontrol Image tab and set \uicontrol {Fill Mode} to \uicontrol Stretch. + \li The background is rendered on top of the 3D scene as it is located at the bottom of the + \uicontrol Navigator view. + With the background image selected, select the down arrow to move it to the top of the + hierarchy. + \image 3d-scene-navigator-background.png + \endlist + +*/ diff --git a/doc/qtdesignstudio/examples/doc/images/3d-scene-add-light-probe.webp b/doc/qtdesignstudio/examples/doc/images/3d-scene-add-light-probe.webp new file mode 100644 index 00000000000..79ea955232b Binary files /dev/null and b/doc/qtdesignstudio/examples/doc/images/3d-scene-add-light-probe.webp differ diff --git a/doc/qtdesignstudio/examples/doc/images/3d-scene-add-texture.webp b/doc/qtdesignstudio/examples/doc/images/3d-scene-add-texture.webp new file mode 100644 index 00000000000..3624fa94183 Binary files /dev/null and b/doc/qtdesignstudio/examples/doc/images/3d-scene-add-texture.webp differ diff --git a/doc/qtdesignstudio/examples/doc/images/3d-scene-bread-crumb.png b/doc/qtdesignstudio/examples/doc/images/3d-scene-bread-crumb.png new file mode 100644 index 00000000000..810deb47498 Binary files /dev/null and b/doc/qtdesignstudio/examples/doc/images/3d-scene-bread-crumb.png differ diff --git a/doc/qtdesignstudio/examples/doc/images/3d-scene-drag-material.png b/doc/qtdesignstudio/examples/doc/images/3d-scene-drag-material.png new file mode 100644 index 00000000000..5d346e761f7 Binary files /dev/null and b/doc/qtdesignstudio/examples/doc/images/3d-scene-drag-material.png differ diff --git a/doc/qtdesignstudio/examples/doc/images/3d-scene-edit-component-menu.png b/doc/qtdesignstudio/examples/doc/images/3d-scene-edit-component-menu.png new file mode 100644 index 00000000000..ca43f352ed4 Binary files /dev/null and b/doc/qtdesignstudio/examples/doc/images/3d-scene-edit-component-menu.png differ diff --git a/doc/qtdesignstudio/examples/doc/images/3d-scene-fill-parent.png b/doc/qtdesignstudio/examples/doc/images/3d-scene-fill-parent.png new file mode 100644 index 00000000000..fecb23b9f34 Binary files /dev/null and b/doc/qtdesignstudio/examples/doc/images/3d-scene-fill-parent.png differ diff --git a/doc/qtdesignstudio/examples/doc/images/3d-scene-navigator-background.png b/doc/qtdesignstudio/examples/doc/images/3d-scene-navigator-background.png new file mode 100644 index 00000000000..54a9a3cc2bf Binary files /dev/null and b/doc/qtdesignstudio/examples/doc/images/3d-scene-navigator-background.png differ diff --git a/doc/qtdesignstudio/examples/doc/images/3d-scene-tutorial.webp b/doc/qtdesignstudio/examples/doc/images/3d-scene-tutorial.webp new file mode 100644 index 00000000000..6aeb929608d Binary files /dev/null and b/doc/qtdesignstudio/examples/doc/images/3d-scene-tutorial.webp differ diff --git a/doc/qtdesignstudio/examples/doc/images/robot-arm-components.png b/doc/qtdesignstudio/examples/doc/images/robot-arm-components.png new file mode 100644 index 00000000000..6db6cbddff2 Binary files /dev/null and b/doc/qtdesignstudio/examples/doc/images/robot-arm-components.png differ diff --git a/doc/qtdesignstudio/examples/doc/images/robotarm-3d-view.png b/doc/qtdesignstudio/examples/doc/images/robotarm-3d-view.png new file mode 100644 index 00000000000..70de427f164 Binary files /dev/null and b/doc/qtdesignstudio/examples/doc/images/robotarm-3d-view.png differ diff --git a/doc/qtdesignstudio/examples/doc/images/robotarm-button-connections.png b/doc/qtdesignstudio/examples/doc/images/robotarm-button-connections.png new file mode 100644 index 00000000000..93bb6c4016e Binary files /dev/null and b/doc/qtdesignstudio/examples/doc/images/robotarm-button-connections.png differ diff --git a/doc/qtdesignstudio/examples/doc/images/robotarm-example.webp b/doc/qtdesignstudio/examples/doc/images/robotarm-example.webp new file mode 100644 index 00000000000..aa9aab9297a Binary files /dev/null and b/doc/qtdesignstudio/examples/doc/images/robotarm-example.webp differ diff --git a/doc/qtdesignstudio/examples/doc/loginui1.qdoc b/doc/qtdesignstudio/examples/doc/loginui1.qdoc index c10c118fdd6..afb7c50556e 100644 --- a/doc/qtdesignstudio/examples/doc/loginui1.qdoc +++ b/doc/qtdesignstudio/examples/doc/loginui1.qdoc @@ -275,8 +275,7 @@ \li In \uicontrol Component > \uicontrol ID, enter \e username. \li In \uicontrol {Button Content} > \uicontrol Text, enter \e {Username or Email} and select \uicontrol tr to mark the text - \l {Internationalization and Localization with Qt Quick} - {translatable}. + \l {Mark Strings for Translation}{translatable}. \li Select the second EntryField instance, and change its ID to \e password and text to \e Password. Again, mark the text translatable. diff --git a/doc/qtdesignstudio/examples/doc/robotarm.qdoc b/doc/qtdesignstudio/examples/doc/robotarm.qdoc new file mode 100644 index 00000000000..6c6ae78b023 --- /dev/null +++ b/doc/qtdesignstudio/examples/doc/robotarm.qdoc @@ -0,0 +1,97 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only + +/*! + \page robotarm-example.html + \ingroup gstutorials + + \title Creating a C++ Backend for a \QDS Application + + \brief Illustrates how to create an application in \QDS and add a backend + in Qt Creator. + + \image robotarm-example.webp + + The \e Robotarm example demonstrates adding a C++ backend to a 3D project created in \QDS. + + The example itself consists of an interactive industrial robot arm in a Qt Quick 3D scene. + The 2D UI to control the robot arm is implemented using Qt Quick Controls. + + You can open the example from the \uicontrol Examples tab on the \uicontrol Welcome page + in \QDS. + + To complete this tutorial, you need experience in using \QDS and Qt Creator as well as knowledge + in C++ programming. + + \section1 The Designer-Developer Workflow + + This section describes the high-level steps for creating the robot arm example. + + \section2 Creating the User Interface + + First, the designer creates the user interface in \QDS. + + \list 1 + \li Create a new 3D project. + \li Import the 3D asset (RoboticArm). + \li Create the following custom components: + \list + \li NodeIndicator: This component consists of a rounded rectangle and a label. It is used + to indicate which joint in the robotic arm is currently active. Located in the 3D + scene, it follows the movement of the 3D model. + \li LabeledSlider: This component is a slider with a label. It is connected to the + rotation of the different robot arm parts so that you can use it to control the rotation + of those parts. + \li Toggle: This component consists of a switch and a label. It is used in two places; to + toggle dark mode and to toggle the claw of the robotic arm. + \li Backend: This serves as a mock backend for the \QDS application. Once you open, + compile, and run the application in Qt Creator, it uses the C++ backend. + \endlist + \li Add the 3D model and lights to the \uicontrol View3D scene. + \image robotarm-3d-view.png + \li Create the 2D UI controls: + \list + \li Four buttons for preset positions. As you can see from the \uicontrol Connections tab + in the \uicontrol Connections view, each button changes the rotation of the robot arm + parts. + \image robotarm-button-connections.png + \li Four sliders for controlling the robot arm parts individually. The \uicontrol Backend + component uses these sliders to control the robot arm position. + \li A switch to control the robot arm claw. This is also done through the + \uicontrol Backend component. + \li A switch to toggle dark mode of the application. + \li A label to display the status of the robot arm through the \uicontrol Backend + component. + \endlist + \endlist + + \section2 Creating the C++ Backend + + With the frontend and user interface created, it is time to create the C++ backend. + + To open the project in Qt Creator: + \list 1 + \li Open \c CMakeLists.txt located in the root folder of the robot arm example. This is the + CMake project file. + \li In Qt Creator, add the empty C++ backend classes in the \c backend folder. + \li Ensure that the \c CMakeLists.txt file in the \c backend folder has the classes in it. It + should look something like this: + \code + find_package(Qt6 REQUIRED COMPONENTS Gui) + + qt_add_qml_module(backend + URI Backend + VERSION 1.0 + SOURCES + animatedparam.cpp + animatedparam.h + backend.cpp + backend.h + ) + + target_link_libraries(backend PRIVATE Qt6::Gui) + \endcode + \li Add the backend logic to the created backend classes. + \endlist + +*/ diff --git a/doc/qtdesignstudio/images/bake-lights-dialog.png b/doc/qtdesignstudio/images/bake-lights-dialog.png new file mode 100644 index 00000000000..d35599dce6a Binary files /dev/null and b/doc/qtdesignstudio/images/bake-lights-dialog.png differ diff --git a/doc/qtdesignstudio/images/qds-front-advanced.png b/doc/qtdesignstudio/images/qds-front-advanced.png new file mode 100644 index 00000000000..87780aa3863 Binary files /dev/null and b/doc/qtdesignstudio/images/qds-front-advanced.png differ diff --git a/doc/qtdesignstudio/images/qds-front-gs.png b/doc/qtdesignstudio/images/qds-front-gs.png new file mode 100644 index 00000000000..27706a8cc6a Binary files /dev/null and b/doc/qtdesignstudio/images/qds-front-gs.png differ diff --git a/doc/qtdesignstudio/images/qds-front-help.png b/doc/qtdesignstudio/images/qds-front-help.png new file mode 100644 index 00000000000..d2f9d42fece Binary files /dev/null and b/doc/qtdesignstudio/images/qds-front-help.png differ diff --git a/doc/qtdesignstudio/images/qds-front-preview.png b/doc/qtdesignstudio/images/qds-front-preview.png new file mode 100644 index 00000000000..fe7aab39668 Binary files /dev/null and b/doc/qtdesignstudio/images/qds-front-preview.png differ diff --git a/doc/qtdesignstudio/images/qds-front-projects.png b/doc/qtdesignstudio/images/qds-front-projects.png new file mode 100644 index 00000000000..69414f48626 Binary files /dev/null and b/doc/qtdesignstudio/images/qds-front-projects.png differ diff --git a/doc/qtdesignstudio/images/qds-front-ui.png b/doc/qtdesignstudio/images/qds-front-ui.png new file mode 100644 index 00000000000..d413b52dbfd Binary files /dev/null and b/doc/qtdesignstudio/images/qds-front-ui.png differ diff --git a/doc/qtdesignstudio/images/qds-studio-3d-scenes.png b/doc/qtdesignstudio/images/qds-studio-3d-scenes.png new file mode 100644 index 00000000000..e4774e8223e Binary files /dev/null and b/doc/qtdesignstudio/images/qds-studio-3d-scenes.png differ diff --git a/doc/qtdesignstudio/images/qds-studio-animation.png b/doc/qtdesignstudio/images/qds-studio-animation.png new file mode 100644 index 00000000000..b08a6deed86 Binary files /dev/null and b/doc/qtdesignstudio/images/qds-studio-animation.png differ diff --git a/doc/qtdesignstudio/src/components/qtquick-text.qdoc b/doc/qtdesignstudio/src/components/qtquick-text.qdoc index f47ac82d7bd..0bb541f1c31 100644 --- a/doc/qtdesignstudio/src/components/qtquick-text.qdoc +++ b/doc/qtdesignstudio/src/components/qtquick-text.qdoc @@ -69,15 +69,13 @@ \c qsTrId(). Select \uicontrol Edit > \uicontrol Preferences > \uicontrol {Qt Quick} > \uicontrol {Qt Quick Designer}, and then select the \uicontrol {qsTrId()} radio button in the \uicontrol Internationalization - group. For more information about text ID based translations, see - \l {Qt Linguist Manual: Text ID Based Translations}. + group. For more information, see \l {Text ID based translations}. To preserve the context when editing the text or to change the context by setting a binding on the text property, change the default call to \c qsTranslate() by selecting the \uicontrol {qsTranslate()} radio button. - For more information, see - \l {Internationalization and Localization with Qt Quick}. + For more information, see \l {Mark Strings for Translation}. \section1 Character Properties diff --git a/doc/qtdesignstudio/src/mcus/qtdesignstudio-compatibility-with-mcu-sdks.qdoc b/doc/qtdesignstudio/src/mcus/qtdesignstudio-compatibility-with-mcu-sdks.qdoc index c6dab76398d..2a0e49cda65 100644 --- a/doc/qtdesignstudio/src/mcus/qtdesignstudio-compatibility-with-mcu-sdks.qdoc +++ b/doc/qtdesignstudio/src/mcus/qtdesignstudio-compatibility-with-mcu-sdks.qdoc @@ -4,7 +4,7 @@ /*! \previouspage studio-on-mcus.html \page studio-compatibility-with-mcu-sdks.html - \nextpage studio-help.html + \nextpage studio-features-on-mcu-projects.html \title \QDS Version Compatibility with \QMCU SDKs diff --git a/doc/qtdesignstudio/src/mcus/qtdesignstudio-features-on-mcu-projects.qdoc b/doc/qtdesignstudio/src/mcus/qtdesignstudio-features-on-mcu-projects.qdoc new file mode 100644 index 00000000000..5cec8d690e4 --- /dev/null +++ b/doc/qtdesignstudio/src/mcus/qtdesignstudio-features-on-mcu-projects.qdoc @@ -0,0 +1,129 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only + +/*! + \previouspage studio-compatibility-with-mcu-sdks.html + \page studio-features-on-mcu-projects.html + \nextpage studio-help.html + + \title \QDS Features on MCU Projects + + The table below provides a summary of how the key \QDS features are supported + for developing MCU projects. + + \table + \header + \li View + \li Fully Supported + \li Partially Supported + \li Not Supported + \li Comments + \row + \li \l 2D + \li \b X + \li \b - + \li \b - + \li A scene in the \uicontrol 2D view is rendered by the regular Qt Quick + and QML, and not as \QUL and \QMCU, so some imperfections or inaccuracies + can occur. + \row + \li \l 3D + \li \b - + \li \b - + \li \b X + \li The \uicontrol 3D view is not a part of \QUL or \QMCU. + \row + \li \l {Material Editor and Browser} + \li \b - + \li \b - + \li \b X + \li The \uicontrol {Material Editor} and \uicontrol {Material Browser} views + are not a part of \QUL or \QMCU. + \row + \li \l {Components} + \li \b X + \li \b - + \li \b - + \li Shows only the components and modules available for MCU projects. + \row + \li \l {Assets} + \li \b X + \li \b - + \li \b - + \li Shows all the listed assets in the \c QmlProject file. + \row + \li \l {Navigator} + \li \b X + \li \b - + \li \b - + \li Displays the composition of the current component file as a tree + structure. + \row + \li \l {Properties} + \li \b X + \li \b - + \li \b - + \li Shows only the preset properties available for MCU projects (such as + by Qt Quick and its modules). + \row + \li \l {Connections} + \li \b X + \li \b - + \li \b - + \li The \uicontrol Connections view displays all signal handlers in the + current file but it doesn't filter available signals, so you can still + see and select signals that are available in Qt Quick, but not in \QUL. + \row + \li \l {States} + \li \b X + \li \b - + \li \b - + \li The feature is fully supported as such, but there are some + limitations listed in \l {\QMCU Known Issues or Limitations}. + \row + \li \l {Transitions} + \li \b X + \li \b - + \li \b - + \li \b - + \row + \li \l {Translations} + \li \b - + \li \b - + \li \b X + \li \b - + \row + \li \l {Timeline} + \li \b X + \li \b - + \li \b - + \li \b - + \row + \li \l {Curves} + \li \b - + \li \b X + \li \b - + \li Linear interpolation works, but \QMCU does not support the + \c easing.bezierCurve property of a keyframe. + \row + \li \l Code + \li \b X + \li \b - + \li \b - + \li The \uicontrol Code view uses regular Qt Quick instead of \QUL, so it may + not show an error if you are using or assigning an unsupported property. + \row + \li \l {Content Library} + \li \b - + \li \b - + \li \b X + \li The \uicontrol {Content Library} view is not a part of \QUL or \QMCU. + \row + \li \l {Texture Editor} + \li \b - + \li \b - + \li \b X + \li The \uicontrol {Texture Editor} view is not a part of \QUL or \QMCU. + \endtable + +*/ diff --git a/doc/qtdesignstudio/src/overviews/qtquick-motion-design.qdoc b/doc/qtdesignstudio/src/overviews/qtquick-motion-design.qdoc index 70ebb9115dc..382c2f5fea8 100644 --- a/doc/qtdesignstudio/src/overviews/qtquick-motion-design.qdoc +++ b/doc/qtdesignstudio/src/overviews/qtquick-motion-design.qdoc @@ -10,7 +10,7 @@ \table \row - \li \image studio-animation.png + \li \image qds-studio-animation.png \li You can use different animation techniques for different purposes. \QDS supports common motion design techniques, such as timeline and keyframe based animation and easing diff --git a/doc/qtdesignstudio/src/overviews/qtquick-prototyping.qdoc b/doc/qtdesignstudio/src/overviews/qtquick-prototyping.qdoc index 2cda8239de4..af936f1507f 100644 --- a/doc/qtdesignstudio/src/overviews/qtquick-prototyping.qdoc +++ b/doc/qtdesignstudio/src/overviews/qtquick-prototyping.qdoc @@ -10,7 +10,7 @@ \table \row - \li \image studio-3d-scenes.png + \li \image qds-studio-3d-scenes.png \li After your UI wireframe has been approved, you can turn it into an interactive prototype to ensure that you and the developers share a common vision about the UI appearance diff --git a/doc/qtdesignstudio/src/overviews/qtquick-uis.qdoc b/doc/qtdesignstudio/src/overviews/qtquick-uis.qdoc index 82a6f2acfa3..2f0aa723b8f 100644 --- a/doc/qtdesignstudio/src/overviews/qtquick-uis.qdoc +++ b/doc/qtdesignstudio/src/overviews/qtquick-uis.qdoc @@ -10,7 +10,7 @@ \table \row - \li \image front-ui.png + \li \image qds-front-ui.png \li Plan your UI properly. Know what elements, such as screens, components, and states, you need. Create a descriptive wireframe and acquire a detailed UI specification before you start to make diff --git a/doc/qtdesignstudio/src/qtdesignstudio-advanced.qdoc b/doc/qtdesignstudio/src/qtdesignstudio-advanced.qdoc index 21733c996ac..fbc362f6c8c 100644 --- a/doc/qtdesignstudio/src/qtdesignstudio-advanced.qdoc +++ b/doc/qtdesignstudio/src/qtdesignstudio-advanced.qdoc @@ -10,7 +10,7 @@ \table \row - \li \image front-advanced.png + \li \image qds-front-advanced.png \li Learn more about the UI files (.ui.qml), collecting data about using \QDS, and about packaging applications for delivering them to users or uploading them to app stores. diff --git a/doc/qtdesignstudio/src/qtdesignstudio-developer-topics.qdoc b/doc/qtdesignstudio/src/qtdesignstudio-developer-topics.qdoc index 845e25b0198..da1799439a4 100644 --- a/doc/qtdesignstudio/src/qtdesignstudio-developer-topics.qdoc +++ b/doc/qtdesignstudio/src/qtdesignstudio-developer-topics.qdoc @@ -10,7 +10,7 @@ \table \row - \li \image front-projects.png + \li \image qds-front-projects.png \li Learn more about using the Git version control system, converting UI projects into applications, and using external tools directly from \QDS. diff --git a/doc/qtdesignstudio/src/qtdesignstudio-getting-started.qdoc b/doc/qtdesignstudio/src/qtdesignstudio-getting-started.qdoc index 76aac701ce8..47800afab72 100644 --- a/doc/qtdesignstudio/src/qtdesignstudio-getting-started.qdoc +++ b/doc/qtdesignstudio/src/qtdesignstudio-getting-started.qdoc @@ -10,7 +10,7 @@ \table \row - \li \image front-gs.png + \li \image qds-front-gs.png \li When you install \QDS, everything you need to start wireframing and prototyping UIs is installed and set up for you. You can move directly to learning about how to use the different \QDS diff --git a/doc/qtdesignstudio/src/qtdesignstudio-help-overview.qdoc b/doc/qtdesignstudio/src/qtdesignstudio-help-overview.qdoc index e3a00cb8dfb..578129024a9 100644 --- a/doc/qtdesignstudio/src/qtdesignstudio-help-overview.qdoc +++ b/doc/qtdesignstudio/src/qtdesignstudio-help-overview.qdoc @@ -3,14 +3,14 @@ /*! \page studio-help.html - \previouspage studio-compatibility-with-mcu-sdks.html + \previouspage studio-features-on-mcu-projects.html \nextpage creator-help.html \title Help \table \row - \li \image front-help.png + \li \image qds-front-help.png \li Learn more about using the \uicontrol Help mode, frequently asked questions, and supported platforms. \endtable diff --git a/doc/qtdesignstudio/src/qtdesignstudio-implementing-applications.qdoc b/doc/qtdesignstudio/src/qtdesignstudio-implementing-applications.qdoc index ace3fe41482..8c88d525426 100644 --- a/doc/qtdesignstudio/src/qtdesignstudio-implementing-applications.qdoc +++ b/doc/qtdesignstudio/src/qtdesignstudio-implementing-applications.qdoc @@ -10,7 +10,7 @@ \table \row - \li \image front-preview.png + \li \image qds-front-preview.png \li \QDS attempts to meet your needs, whether you have previous experience with QML and coding or not. When you install \QDS, the default configuration allows you to start wireframing, diff --git a/doc/qtdesignstudio/src/qtdesignstudio-terms.qdoc b/doc/qtdesignstudio/src/qtdesignstudio-terms.qdoc index 4859c20488c..d4dcb9a75ee 100644 --- a/doc/qtdesignstudio/src/qtdesignstudio-terms.qdoc +++ b/doc/qtdesignstudio/src/qtdesignstudio-terms.qdoc @@ -151,12 +151,11 @@ \image studio-design-mode.webp "Design mode" - Read more about modes: + The mode selector is hidden by default. - \list - \li \l{Selecting Modes} - \li \l{Design Views} - \endlist + To show the mode selector, go to \uicontrol Views > + \uicontrol {Mode Selector Style} and select \uicontrol {Icons and Text} + or \uicontrol {Icons Only}. \section1 Project \target glossary-project diff --git a/doc/qtdesignstudio/src/qtdesignstudio-toc.qdoc b/doc/qtdesignstudio/src/qtdesignstudio-toc.qdoc index 6fc2014020f..0448079cbb4 100644 --- a/doc/qtdesignstudio/src/qtdesignstudio-toc.qdoc +++ b/doc/qtdesignstudio/src/qtdesignstudio-toc.qdoc @@ -12,7 +12,6 @@ \li \l{Tutorials} \li \l{User Interface} \list - \li \l{Selecting Modes} \li \l{Design Views} \list \li \l{2D} @@ -203,7 +202,6 @@ \list \li \l{Working in Edit Mode} \list - \li \l{Working with Sidebars} \li \l{Browsing Project Contents} \li \l{Viewing Output} \endlist @@ -262,6 +260,7 @@ \li \l{\QDS on MCUs} \list \li \l {\QDS Version Compatibility with \QMCU SDKs} + \li \l {\QDS Features on MCU Projects} \endlist \endlist \li \l Help diff --git a/doc/qtdesignstudio/src/qtdesignstudio-use-cases.qdoc b/doc/qtdesignstudio/src/qtdesignstudio-use-cases.qdoc index 1efb484160c..54e90305c0c 100644 --- a/doc/qtdesignstudio/src/qtdesignstudio-use-cases.qdoc +++ b/doc/qtdesignstudio/src/qtdesignstudio-use-cases.qdoc @@ -13,10 +13,10 @@ \table \row - \li \inlineimage front-ui.png + \li \inlineimage qds-front-ui.png \li \inlineimage studio-flow.png - \li \inlineimage studio-3d-scenes.png - \li \inlineimage front-projects.png + \li \inlineimage qds-studio-3d-scenes.png + \li \inlineimage qds-front-projects.png \row \li \b {Creating UI wireframes} \li \b {Creating UI prototypes} diff --git a/doc/qtdesignstudio/src/qtdesignstudio.qdoc b/doc/qtdesignstudio/src/qtdesignstudio.qdoc index adf772987d4..94ad24b6cc5 100644 --- a/doc/qtdesignstudio/src/qtdesignstudio.qdoc +++ b/doc/qtdesignstudio/src/qtdesignstudio.qdoc @@ -18,10 +18,10 @@ \table \row - \li \inlineimage front-gs.png - \li \inlineimage front-ui.png - \li \inlineimage studio-3d-scenes.png - \li \inlineimage studio-animation.png + \li \inlineimage qds-front-gs.png + \li \inlineimage qds-front-ui.png + \li \inlineimage qds-studio-3d-scenes.png + \li \inlineimage qds-studio-animation.png \row \li \b {\l{Getting Started}} \list @@ -58,10 +58,10 @@ \li \l{Optimizing Designs} \endlist \row - \li \inlineimage front-preview.png - \li \inlineimage front-advanced.png - \li \inlineimage front-projects.png - \li \inlineimage front-help.png + \li \inlineimage qds-front-preview.png + \li \inlineimage qds-front-advanced.png + \li \inlineimage qds-front-projects.png + \li \inlineimage qds-front-help.png \row \li \b {\l{Implementing Applications}} \list diff --git a/doc/qtdesignstudio/src/qtquick3d-editor/qtdesignstudio-3d-editor.qdoc b/doc/qtdesignstudio/src/qtquick3d-editor/qtdesignstudio-3d-editor.qdoc index 1f69fe95cdf..23c998d9fcd 100644 --- a/doc/qtdesignstudio/src/qtquick3d-editor/qtdesignstudio-3d-editor.qdoc +++ b/doc/qtdesignstudio/src/qtquick3d-editor/qtdesignstudio-3d-editor.qdoc @@ -313,7 +313,7 @@ \endlist You can pause the particle animation by selecting - \inlineimage icons/particle-animation-on.png + \inlineimage icons/particle-pause.png . When the animation is paused, you can use \inlineimage icons/particles-seek.png to manually seek forward or backward in the particle animation. diff --git a/doc/qtdesignstudio/src/qtquick3d-editor/qtdesignstudio-3d-lights.qdoc b/doc/qtdesignstudio/src/qtquick3d-editor/qtdesignstudio-3d-lights.qdoc index 8c798a31a4f..ec1de943f2b 100644 --- a/doc/qtdesignstudio/src/qtquick3d-editor/qtdesignstudio-3d-lights.qdoc +++ b/doc/qtdesignstudio/src/qtquick3d-editor/qtdesignstudio-3d-lights.qdoc @@ -209,11 +209,38 @@ \uicontrol {Shadow map far} property value. Using smaller values may improve the precision and effects of the map. - \section1 Baking Lightmaps + \section1 Baked Lightmaps \note Lightmaps baking is released as technical preview in \QDS 4.1. - \section2 Baking Lightmaps for a 3D Model + Baked lightmaps allow pre-generating the direct lighting from lights such as DirectionalLight, + PointLight, and SpotLight, including the shadows cast by the lights. At run time, instead of + performing the appropriate calculations in the fragment shader, and, in case of shadows, + generating the potentially costly shadow maps in real time, the pre-generated light map is + sampled instead. + + \section2 Baking Lightmaps + + To bake lightmaps for models in your 3D scene: + + \list 1 + \li Right-click anywhere in the \uicontrol 3D view and select \uicontrol {Bake Lights}. + \li In the \uicontrol {Lights Baking Setup} dialog: + \list + \li For every light you want to use to bake lightmaps, set \uicontrol {Bake Mode} to BakeModeAll. + \li For every 3D model you want to bake lightmaps, select \uicontrol {In Use} and + \uicontrol {Enabled}, and set the desired \uicontrol {Resolution}. + \endlist + \li Optional. If you have components with unexposed models or lights (for example, imported + 3D models created in other software), select \uicontrol {Expose models and lights} to add the + models and light of that component to the \uicontrol Models and \uicontrol Lights sections of + the dialog. + \li Select \uicontrol Bake. + \endlist + + \image bake-lights-dialog.png + + \section2 Manually Baking Lightmaps for a 3D Model Baked lightmap components are not visible in the \uicontrol Navigator view by default. To make them visible, select \inlineimage icons/visibilityon.png in the \uicontrol Navigator view. @@ -239,9 +266,10 @@ \li In the \uicontrol Navigator view, select the light component that you want to bake lightmaps for, and in the \uicontrol Properties view, set \uicontrol {Bake Mode} to BakeModeAll. \li Right-click anywhere in the \uicontrol 3D view and select \uicontrol {Bake Lights}. + \li Select \uicontrol {Setup baking manually}, and then select \uicontrol Bake. \endlist - \section2 Baking Lightmaps for a 3D Model Inside a Sub Component + \section2 Manually Baking Lightmaps for a 3D Model Inside a Sub Component To bake lightmaps for a 3D model inside a sub component, first add a local custom property to expose the model: @@ -299,6 +327,7 @@ a unique name. \endlist \li Right-click anywhere in the \uicontrol 3D view and select \uicontrol {Bake Lights}. + \li Select \uicontrol {Setup baking manually}, and then select \uicontrol Bake. \endlist */ diff --git a/doc/qtdesignstudio/src/views/qtquick-designer.qdoc b/doc/qtdesignstudio/src/views/qtquick-designer.qdoc index cc18d924417..1e7d58326ee 100644 --- a/doc/qtdesignstudio/src/views/qtquick-designer.qdoc +++ b/doc/qtdesignstudio/src/views/qtquick-designer.qdoc @@ -10,7 +10,7 @@ /*! \page creator-using-qt-quick-designer.html - \previouspage creator-modes.html + \previouspage creator-quick-tour.html \nextpage qtquick-form-editor.html \title Design Views @@ -31,52 +31,65 @@ \section1 Summary of Design Views + In addition to the summary of design views, the table below includes an MCU + column that indicates the views which are fully supported on MCU projects. + For more information, see \l {\QDS Features on MCU Projects}. + \table \header \li View \li Purpose + \li MCU \li Read More \row \li \l {2D} \li Provides a working area for designing 2D UIs. When you are editing 3D scenes, the \uicontrol {2D} view is used as a canvas for the 3D scene projected by the camera. + \li \image ok.png \li \l {2D} \row \li \l {3D} \li Provides an editor for files you created using 3D graphics applications and stored in one of the supported formats. + \li \li \l {3D} \row \li \l {Material Editor and Browser} \li In the \uicontrol {Material Editor} and \uicontrol {Material Browser} views, you create and manage materials and textures. + \li \li \l {Material Editor and Browser} \row \li \l Components \li Contains preset components and your own components, that you can use to design you application. + \li \image ok.png \li \l{Using Components} \row \li \l Assets \li Contains assets such as images and fonts that you can use in your application. + \li \image ok.png \li \l Assets \row \li \l Navigator \li Displays the composition of the current component file as a tree structure. A component file can contain references to other components and assets. + \li \image ok.png \li \l Navigator \row \li \l Properties \li Enables you to modify the properties of the selected component. + \li \image ok.png \li \l {Specifying Component Properties} \row \li \l{Connections} \li Enables you to add functionality to the UI by creating connections between components, signals, and component properties. + \li \image ok.png \li \l{Working with Connections} \row \li \l States @@ -84,54 +97,65 @@ Typically, states describe UI configurations, such as the visibility and behavior of components and the available user actions. + \li \image ok.png \li \l{Working with States} \row \li \l{Transitions} \li Enables you to make movement between states smooth by animating the changes between states. + \li \image ok.png \li \l{Animating Transitions Between States} \row \li \l Translations \li Provides functionality to add multi-language support to your project. + \li \li \l{Translations} \row \li \l Timeline \li Provides a timeline and keyframe based editor for animating the properties of components. + \li \image ok.png \li \l{Creating Timeline Animations} \row \li \l{Curves} \li Enables you to view and modify the whole animation curve by inserting keyframes to the curve and dragging them and the point handlers to modify the curve. + \li \li \l {Editing Animation Curves} \row \li \l{Code} \li Provides a code editor for viewing and modifying the code generated by the visual editors. + \li \image ok.png \li \l {Working in Edit Mode} \row \li \l Projects \li Shows a list of open projects and the files they contain. + \li \image ok.png \li \l Projects \row \li \l{File System} \li Shows all files in the currently selected directory. + \li \image ok.png \li \l{File System} \row \li \l{Open Documents} \li Shows currently open files. + \li \image ok.png \li \l{Open Documents} \row \li \l{Content Library} \li The \uicontrol {Content Library} view contains material, texture, and environment bundles with assets that you can use in your project. + \li \li \l{Content Library} \row \li \l{Texture Editor} \li In the \uicontrol {Texture Editor} view, you create and manage textures. + \li \li \l{Texture Editor} \endtable diff --git a/qbs/modules/qtc_gtest_gmock/qtc_gtest_gmock.qbs b/qbs/modules/qtc_gtest_gmock/qtc_gtest_gmock.qbs index 02bbb8a3022..7b1d663cf0e 100644 --- a/qbs/modules/qtc_gtest_gmock/qtc_gtest_gmock.qbs +++ b/qbs/modules/qtc_gtest_gmock/qtc_gtest_gmock.qbs @@ -19,7 +19,7 @@ Module { property bool hasRepo configure: { - repoDir = FileInfo.cleanPath(path + "/../../../tests/unit/unittest/3rdparty/googletest"); + repoDir = FileInfo.cleanPath(path + "/../../../tests/unit/3rdparty/googletest"); gtestDir = FileInfo.joinPaths(repoDir, "googletest"); gmockDir = FileInfo.joinPaths(repoDir, "googlemock"); hasRepo = File.exists(gtestDir); diff --git a/share/qtcreator/qmldesigner/assetsLibraryQmlSources/AssetDelegate.qml b/share/qtcreator/qmldesigner/assetsLibraryQmlSources/AssetDelegate.qml index 7c017476cdd..12f5ebf4c15 100644 --- a/share/qtcreator/qmldesigner/assetsLibraryQmlSources/AssetDelegate.qml +++ b/share/qtcreator/qmldesigner/assetsLibraryQmlSources/AssetDelegate.qml @@ -9,6 +9,8 @@ import AssetsLibraryBackend TreeViewDelegate { id: root + property StudioTheme.ControlStyle style: StudioTheme.Values.controlStyle + required property Item assetsView required property Item assetsRoot @@ -68,6 +70,21 @@ TreeViewDelegate { root.depth = root.initialDepth } + indicator: Item { + implicitWidth: 20 + implicitHeight: root.implicitHeight + anchors.left: bg.left + + Image { + id: arrow + width: 8 + height: 4 + source: "image://icons/down-arrow" + anchors.centerIn: parent + rotation: root.expanded ? 0 : -90 + } + } + background: Rectangle { id: bg @@ -109,7 +126,7 @@ TreeViewDelegate { id: assetLabel text: assetLabel.__computeText() color: StudioTheme.Values.themeTextColor - font.pixelSize: StudioTheme.Values.mediumFont + font.pixelSize: StudioTheme.Values.baseFontSize anchors.verticalCenter: parent.verticalCenter verticalAlignment: Qt.AlignVCenter diff --git a/share/qtcreator/qmldesigner/contentLibraryImages/new_flag_triangle.png b/share/qtcreator/qmldesigner/contentLibraryImages/new_flag_triangle.png new file mode 100644 index 00000000000..af282807491 Binary files /dev/null and b/share/qtcreator/qmldesigner/contentLibraryImages/new_flag_triangle.png differ diff --git a/share/qtcreator/qmldesigner/contentLibraryQmlSource/ContentLibrary.qml b/share/qtcreator/qmldesigner/contentLibraryQmlSource/ContentLibrary.qml index 37154ec170b..1932af0eef9 100644 --- a/share/qtcreator/qmldesigner/contentLibraryQmlSource/ContentLibrary.qml +++ b/share/qtcreator/qmldesigner/contentLibraryQmlSource/ContentLibrary.qml @@ -19,6 +19,7 @@ Item { materialsView.closeContextMenu() texturesView.closeContextMenu() environmentsView.closeContextMenu() + effectsView.closeContextMenu() HelperWidgets.Controller.closeContextMenu() } @@ -67,6 +68,7 @@ Item { materialsView.expandVisibleSections() texturesView.expandVisibleSections() environmentsView.expandVisibleSections() + effectsView.expandVisibleSections() } } @@ -76,7 +78,8 @@ Item { height: StudioTheme.Values.toolbarHeight tabsModel: [{name: qsTr("Materials"), icon: StudioTheme.Constants.material_medium}, {name: qsTr("Textures"), icon: StudioTheme.Constants.textures_medium}, - {name: qsTr("Environments"), icon: StudioTheme.Constants.languageList_medium}] + {name: qsTr("Environments"), icon: StudioTheme.Constants.languageList_medium}, + {name: qsTr("Effects"), icon: StudioTheme.Constants.effects}] } } } @@ -98,7 +101,8 @@ Item { searchBox: searchBox onUnimport: (bundleMat) => { - confirmUnimportDialog.targetBundleMaterial = bundleMat + confirmUnimportDialog.targetBundleItem = bundleMat + confirmUnimportDialog.targetBundleType = "material" confirmUnimportDialog.open() } } @@ -122,6 +126,20 @@ Item { searchBox: searchBox } + + ContentLibraryEffectsView { + id: effectsView + + width: root.width + + searchBox: searchBox + + onUnimport: (bundleItem) => { + confirmUnimportDialog.targetBundleItem = bundleItem + confirmUnimportDialog.targetBundleType = "effect" + confirmUnimportDialog.open() + } + } } } } diff --git a/share/qtcreator/qmldesigner/contentLibraryQmlSource/ContentLibraryEffect.qml b/share/qtcreator/qmldesigner/contentLibraryQmlSource/ContentLibraryEffect.qml new file mode 100644 index 00000000000..6230d38974e --- /dev/null +++ b/share/qtcreator/qmldesigner/contentLibraryQmlSource/ContentLibraryEffect.qml @@ -0,0 +1,90 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +import QtQuick +import QtQuick.Layouts +import QtQuickDesignerTheme +import HelperWidgets +import QtQuick.Controls + +import StudioTheme as StudioTheme +import ContentLibraryBackend + +Item { + id: root + + signal showContextMenu() + + visible: modelData.bundleItemVisible + + MouseArea { + id: mouseArea + + hoverEnabled: true + anchors.fill: parent + acceptedButtons: Qt.LeftButton | Qt.RightButton + + onPressed: (mouse) => { + if (mouse.button === Qt.LeftButton && !ContentLibraryBackend.effectsModel.importerRunning) + ContentLibraryBackend.rootView.startDragEffect(modelData, mapToGlobal(mouse.x, mouse.y)) + else if (mouse.button === Qt.RightButton) + root.showContextMenu() + } + } + + Column { + anchors.fill: parent + spacing: 1 + + Item { width: 1; height: 5 } // spacer + + Image { + id: img + + width: root.width - 10 + height: img.width + anchors.horizontalCenter: parent.horizontalCenter + source: modelData.bundleItemIcon + cache: false + + Rectangle { // circular indicator for imported bundle effect + width: 10 + height: 10 + radius: 5 + anchors.right: img.right + anchors.top: img.top + anchors.margins: 5 + color: "#00ff00" + border.color: "#555555" + border.width: 1 + visible: modelData.bundleItemImported + + ToolTip { + visible: indicatorMouseArea.containsMouse + text: qsTr("Effect is imported to project") + delay: 1000 + } + + MouseArea { + id: indicatorMouseArea + anchors.fill: parent + hoverEnabled: true + } + } + } + + Text { + text: modelData.bundleItemName + + width: img.width + clip: true + + anchors.horizontalCenter: parent.horizontalCenter + horizontalAlignment: TextInput.AlignHCenter + + font.pixelSize: StudioTheme.Values.myFontSize + + color: StudioTheme.Values.themeTextColor + } + } // Column +} diff --git a/share/qtcreator/qmldesigner/contentLibraryQmlSource/ContentLibraryEffectContextMenu.qml b/share/qtcreator/qmldesigner/contentLibraryQmlSource/ContentLibraryEffectContextMenu.qml new file mode 100644 index 00000000000..3abbfe88ada --- /dev/null +++ b/share/qtcreator/qmldesigner/contentLibraryQmlSource/ContentLibraryEffectContextMenu.qml @@ -0,0 +1,39 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +import QtQuick +import HelperWidgets +import StudioControls as StudioControls +import StudioTheme as StudioTheme +import ContentLibraryBackend + +StudioControls.Menu { + id: root + + property var targetItem: null + + readonly property bool targetAvailable: targetItem && !ContentLibraryBackend.effectsModel.importerRunning + + signal unimport(var bundleEff); + + function popupMenu(targetItem = null) + { + this.targetItem = targetItem + popup() + } + + closePolicy: StudioControls.Menu.CloseOnEscape | StudioControls.Menu.CloseOnPressOutside + + StudioControls.MenuItem { + text: qsTr("Add an instance") + enabled: root.targetAvailable + onTriggered: ContentLibraryBackend.effectsModel.addInstance(root.targetItem) + } + + StudioControls.MenuItem { + enabled: root.targetAvailable && root.targetItem.bundleItemImported + text: qsTr("Remove from project") + + onTriggered: root.unimport(root.targetItem) + } +} diff --git a/share/qtcreator/qmldesigner/contentLibraryQmlSource/ContentLibraryEffectsView.qml b/share/qtcreator/qmldesigner/contentLibraryQmlSource/ContentLibraryEffectsView.qml new file mode 100644 index 00000000000..1fe8f52c134 --- /dev/null +++ b/share/qtcreator/qmldesigner/contentLibraryQmlSource/ContentLibraryEffectsView.qml @@ -0,0 +1,112 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +import QtQuick +import HelperWidgets as HelperWidgets +import StudioControls as StudioControls +import StudioTheme as StudioTheme +import ContentLibraryBackend + +HelperWidgets.ScrollView { + id: root + + clip: true + interactive: !ctxMenu.opened && !ContentLibraryBackend.rootView.isDragging + && !HelperWidgets.Controller.contextMenuOpened + + readonly property int cellWidth: 100 + readonly property int cellHeight: 120 + + required property var searchBox + + signal unimport(var bundleItem); + + function closeContextMenu() + { + ctxMenu.close() + } + + function expandVisibleSections() + { + for (let i = 0; i < categoryRepeater.count; ++i) { + let cat = categoryRepeater.itemAt(i) + if (cat.visible && !cat.expanded) + cat.expandSection() + } + } + + Column { + ContentLibraryEffectContextMenu { + id: ctxMenu + + onUnimport: (bundleEff) => root.unimport(bundleEff) + } + + Repeater { + id: categoryRepeater + + model: ContentLibraryBackend.effectsModel + + delegate: HelperWidgets.Section { + width: root.width + caption: bundleCategoryName + addTopPadding: false + sectionBackgroundColor: "transparent" + visible: bundleCategoryVisible && !ContentLibraryBackend.effectsModel.isEmpty + expanded: bundleCategoryExpanded + expandOnClick: false + category: "ContentLib_Effect" + + onToggleExpand: bundleCategoryExpanded = !bundleCategoryExpanded + onExpand: bundleCategoryExpanded = true + onCollapse: bundleCategoryExpanded = false + + function expandSection() { + bundleCategoryExpanded = true + } + + Grid { + width: root.width + leftPadding: 5 + rightPadding: 5 + bottomPadding: 5 + columns: root.width / root.cellWidth + + Repeater { + model: bundleCategoryItems + + delegate: ContentLibraryEffect { + width: root.cellWidth + height: root.cellHeight + + onShowContextMenu: ctxMenu.popupMenu(modelData) + } + } + } + } + } + + Text { + id: infoText + text: { + if (!ContentLibraryBackend.effectsModel.bundleExists) + qsTr("No effects available.") + else if (!ContentLibraryBackend.rootView.hasQuick3DImport) + qsTr("To use Content Library, first add the QtQuick3D module in the Components view.") + else if (!ContentLibraryBackend.effectsModel.hasRequiredQuick3DImport) + qsTr("To use Content Library, version 6.4 or later of the QtQuick3D module is required.") + else if (!ContentLibraryBackend.rootView.hasMaterialLibrary) + qsTr("Content Library is disabled inside a non-visual component.") + else if (!searchBox.isEmpty()) + qsTr("No match found.") + else + "" + } + color: StudioTheme.Values.themeTextColor + font.pixelSize: StudioTheme.Values.baseFontSize + topPadding: 10 + leftPadding: 10 + visible: ContentLibraryBackend.effectsModel.isEmpty + } + } +} diff --git a/share/qtcreator/qmldesigner/contentLibraryQmlSource/ContentLibraryMaterial.qml b/share/qtcreator/qmldesigner/contentLibraryQmlSource/ContentLibraryMaterial.qml index aadd4b0d991..9d723dc0ef8 100644 --- a/share/qtcreator/qmldesigner/contentLibraryQmlSource/ContentLibraryMaterial.qml +++ b/share/qtcreator/qmldesigner/contentLibraryQmlSource/ContentLibraryMaterial.qml @@ -95,7 +95,7 @@ Item { icon: StudioTheme.Constants.plus tooltip: qsTr("Add an instance to project") buttonSize: 22 - property color c: StudioTheme.Values.themeIconColor + property color c: "white" normalColor: Qt.hsla(c.hslHue, c.hslSaturation, c.hslLightness, .2) hoverColor: Qt.hsla(c.hslHue, c.hslSaturation, c.hslLightness, .3) pressColor: Qt.hsla(c.hslHue, c.hslSaturation, c.hslLightness, .4) @@ -118,7 +118,7 @@ Item { iconColor: root.downloadState === "unavailable" || root.downloadState === "failed" ? StudioTheme.Values.themeRedLight - : StudioTheme.Values.themeTextColor + : "white" iconSize: 22 iconScale: downloadIcon.containsMouse ? 1.2 : 1 diff --git a/share/qtcreator/qmldesigner/contentLibraryQmlSource/ContentLibraryTexture.qml b/share/qtcreator/qmldesigner/contentLibraryQmlSource/ContentLibraryTexture.qml index 3ba94430290..6a938ed14d6 100644 --- a/share/qtcreator/qmldesigner/contentLibraryQmlSource/ContentLibraryTexture.qml +++ b/share/qtcreator/qmldesigner/contentLibraryQmlSource/ContentLibraryTexture.qml @@ -20,6 +20,8 @@ Item { property string downloadState: modelData.isDownloaded() ? "downloaded" : "" property bool delegateVisible: modelData.textureVisible + property bool _isUpdating: false + property alias allowCancel: progressBar.closeButtonVisible property alias progressValue: progressBar.value property alias progressText: progressLabel.text @@ -40,6 +42,55 @@ Item { return qsTr("Click to download the texture.") } + function startDownload(message) + { + if (root.downloadState !== "" && root.downloadState !== "failed") + return + + root._startDownload(textureDownloader, message) + } + + function updateTexture() + { + if (root.downloadState !== "downloaded") + return + + root._isUpdating = true + root._startDownload(textureDownloader, qsTr("Updating...")) + } + + function _startDownload(downloader, message) + { + progressBar.visible = true + tooltip.visible = false + root.progressText = message + root.allowCancel = true + root.progressValue = Qt.binding(function() { return downloader.progress }) + + root.downloadState = "" + downloader.start() + } + + MouseArea { + id: mouseArea + + anchors.fill: parent + hoverEnabled: !downloadIcon.visible + acceptedButtons: Qt.LeftButton | Qt.RightButton + + onEntered: tooltip.visible = image.visible + onExited: tooltip.visible = false + + onPressed: (mouse) => { + if (mouse.button === Qt.LeftButton) { + if (root.downloadState === "downloaded") + ContentLibraryBackend.rootView.startDragTexture(modelData, mapToGlobal(mouse.x, mouse.y)) + } else if (mouse.button === Qt.RightButton && root.downloadState === "downloaded") { + root.showContextMenu() + } + } + } + Rectangle { id: downloadPane anchors.fill: parent @@ -60,7 +111,7 @@ Item { visible: false onCancelRequested: { - downloader.cancel() + textureDownloader.cancel() } Text { @@ -114,7 +165,7 @@ Item { iconColor: root.downloadState === "unavailable" || root.downloadState === "failed" ? StudioTheme.Values.themeRedLight - : StudioTheme.Values.themeTextColor + : "white" iconSize: 22 iconScale: downloadIcon.containsMouse ? 1.2 : 1 @@ -144,20 +195,76 @@ Item { } onClicked: { - if (root.downloadState !== "" && root.downloadState !== "failed") - return - - progressBar.visible = true - tooltip.visible = false - root.progressText = qsTr("Downloading...") - root.allowCancel = true - root.progressValue = Qt.binding(function() { return downloader.progress }) - - root.downloadState = "" - downloader.start() + root.startDownload(qsTr("Downloading...")) } } // IconButton + IconButton { + id: updateButton + icon: StudioTheme.Constants.updateAvailable_medium + iconColor: "white" + tooltip: qsTr("Update texture") + buttonSize: 22 + iconSize: 22 + + iconScale: updateButton.containsMouse ? 1.2 : 1 + iconStyle: Text.Outline + iconStyleColor: "black" + + anchors.left: parent.left + anchors.bottom: parent.bottom + + visible: root.downloadState === "downloaded" && modelData.textureHasUpdate + transparentBg: true + + onClicked: root.updateTexture() + + Text { + text: StudioTheme.Constants.updateContent_medium + font.family: StudioTheme.Constants.iconFont.family + color: "black" + + anchors.horizontalCenter: parent.horizontalCenter + anchors.bottom: parent.bottom + anchors.bottomMargin: 5 + + font.pixelSize: 10 + font.bold: true + + scale: updateButton.containsMouse ? 1.2 : 1 + } + } // Update IconButton + + Rectangle { + id: isNewFlag + + width: 32 + height: 32 + + visible: downloadIcon.visible && modelData.textureIsNew + color: "transparent" + + anchors.top: parent.top + anchors.right: parent.right + + Image { + source: "image://contentlibrary/new_flag_triangle.png" + width: 32 + height: 32 + } + + Text { + color: "white" + font.family: StudioTheme.Constants.iconFont.family + text: StudioTheme.Constants.favorite + font.pixelSize: StudioTheme.Values.baseIconFontSize + anchors.right: parent.right + anchors.top: parent.top + anchors.topMargin: 2 + anchors.rightMargin: 4 + } // New texture flag + } + ToolTip { id: tooltip // contentWidth is not calculated correctly by the toolTip (resulting in a wider tooltip than @@ -177,29 +284,8 @@ Item { } } // Image - MouseArea { - id: mouseArea - - anchors.fill: parent - hoverEnabled: !downloadIcon.visible - propagateComposedEvents: downloadIcon.visible - acceptedButtons: Qt.LeftButton | Qt.RightButton - - onEntered: tooltip.visible = image.visible - onExited: tooltip.visible = false - - onPressed: (mouse) => { - if (mouse.button === Qt.LeftButton) { - if (root.downloadState === "downloaded") - ContentLibraryBackend.rootView.startDragTexture(modelData, mapToGlobal(mouse.x, mouse.y)) - } else if (mouse.button === Qt.RightButton && root.downloadState === "downloaded") { - root.showContextMenu() - } - } - } - FileDownloader { - id: downloader + id: textureDownloader url: image.webUrl probeUrl: false downloadEnabled: true @@ -210,9 +296,9 @@ Item { onFinishedChanged: { root.progressText = qsTr("Extracting...") root.allowCancel = false - root.progressValue = Qt.binding(function() { return extractor.progress }) + root.progressValue = Qt.binding(function() { return textureExtractor.progress }) - extractor.extract() + textureExtractor.extract() } onDownloadCanceled: { @@ -238,14 +324,50 @@ Item { } FileExtractor { - id: extractor - archiveName: downloader.completeBaseName - sourceFile: downloader.outputFile + id: textureExtractor + archiveName: textureDownloader.completeBaseName + sourceFile: textureDownloader.outputFile targetPath: modelData.textureParentPath alwaysCreateDir: false clearTargetPathContents: false onFinishedChanged: { + if (root._isUpdating) + root._startDownload(iconDownloader, qsTr("Updating...")) + else + delayedFinish.restart() + } + } + + FileDownloader { + id: iconDownloader + url: modelData.textureWebIconUrl + probeUrl: false + downloadEnabled: true + targetFilePath: modelData.textureIconPath + overwriteTarget: true + + onDownloadStarting: { + root.downloadState = "downloading" + } + + onFinishedChanged: { + image.source = "" + image.source = modelData.textureIcon + + ContentLibraryBackend.rootView.markTextureUpdated(modelData.textureKey) + delayedFinish.restart() } + + onDownloadCanceled: { + root.progressText = "" + root.progressValue = 0 + + root.downloadState = "" + } + + onDownloadFailed: { + root.downloadState = "failed" + } } } diff --git a/share/qtcreator/qmldesigner/contentLibraryQmlSource/UnimportBundleMaterialDialog.qml b/share/qtcreator/qmldesigner/contentLibraryQmlSource/UnimportBundleMaterialDialog.qml index a8c3758eb5b..edb6ce36707 100644 --- a/share/qtcreator/qmldesigner/contentLibraryQmlSource/UnimportBundleMaterialDialog.qml +++ b/share/qtcreator/qmldesigner/contentLibraryQmlSource/UnimportBundleMaterialDialog.qml @@ -10,7 +10,7 @@ import StudioControls as StudioControls import StudioTheme as StudioTheme import ContentLibraryBackend -Dialog { +StudioControls.Dialog { id: root title: qsTr("Bundle material might be in use") @@ -19,7 +19,8 @@ Dialog { implicitWidth: 300 modal: true - property var targetBundleMaterial + property var targetBundleType // "effect" or "material" + property var targetBundleItem contentItem: Column { spacing: 20 @@ -28,7 +29,8 @@ Dialog { Text { id: folderNotEmpty - text: qsTr("If the material you are removing is in use, it might cause the project to malfunction.\n\nAre you sure you want to remove the material?") + text: qsTr("If the %1 you are removing is in use, it might cause the project to malfunction.\n\nAre you sure you want to remove the %1?") + .arg(root.targetBundleType) color: StudioTheme.Values.themeTextColor wrapMode: Text.WordWrap anchors.right: parent.right @@ -48,7 +50,11 @@ Dialog { text: qsTr("Remove") onClicked: { - ContentLibraryBackend.materialsModel.removeFromProject(root.targetBundleMaterial) + if (root.targetBundleType === "material") + ContentLibraryBackend.materialsModel.removeFromProject(root.targetBundleItem) + else if (root.targetBundleType === "effect") + ContentLibraryBackend.effectsModel.removeFromProject(root.targetBundleItem) + root.accept() } } diff --git a/share/qtcreator/qmldesigner/edit3dQmlSource/BakeLightsProgressDialog.qml b/share/qtcreator/qmldesigner/edit3dQmlSource/BakeLightsProgressDialog.qml index 18494d5f327..259a0a1ab59 100644 --- a/share/qtcreator/qmldesigner/edit3dQmlSource/BakeLightsProgressDialog.qml +++ b/share/qtcreator/qmldesigner/edit3dQmlSource/BakeLightsProgressDialog.qml @@ -63,11 +63,14 @@ Rectangle { } } - Text { + TextEdit { id: progressText width: scrollView.width font.pixelSize: StudioTheme.Values.myFontSize color: StudioTheme.Values.themeTextColor + readOnly: true + selectByMouse: true + selectByKeyboard: true } function ensureVisible() diff --git a/share/qtcreator/qmldesigner/edit3dQmlSource/BakeLightsSetupDialog.qml b/share/qtcreator/qmldesigner/edit3dQmlSource/BakeLightsSetupDialog.qml index 5924756bedf..5c202a4a60b 100644 --- a/share/qtcreator/qmldesigner/edit3dQmlSource/BakeLightsSetupDialog.qml +++ b/share/qtcreator/qmldesigner/edit3dQmlSource/BakeLightsSetupDialog.qml @@ -12,6 +12,8 @@ import StudioTheme as StudioTheme Rectangle { id: root + property int toolTipDelay: 1000 + color: StudioTheme.Values.themePanelBackground Column { @@ -99,6 +101,7 @@ Rectangle { hoverEnabled: true ToolTip.visible: hovered ToolTip.text: qsTr("The baking mode applied to this light.") + ToolTip.delay: root.toolTipDelay onActivated: bakeMode = currentValue } @@ -112,6 +115,7 @@ Rectangle { hoverEnabled: true ToolTip.visible: hovered ToolTip.text: qsTr("If checked, this model contributes to baked lighting,\nfor example in form of casting shadows or indirect light.") + ToolTip.delay: root.toolTipDelay onToggled: inUse = checked } @@ -125,6 +129,7 @@ Rectangle { hoverEnabled: true ToolTip.visible: hovered ToolTip.text: qsTr("If checked, baked lightmap texture is generated and rendered for this model.") + ToolTip.delay: root.toolTipDelay onToggled: isEnabled = checked } @@ -155,6 +160,7 @@ Rectangle { hoverEnabled: true ToolTip.visible: hovered ToolTip.text: qsTr("Generated lightmap resolution for this model.") + ToolTip.delay: root.toolTipDelay onRealValueChanged: resolution = realValue } @@ -176,6 +182,7 @@ Rectangle { hoverEnabled: true ToolTip.visible: hovered ToolTip.text: qsTr("If checked, baking settings above are not applied on close or bake.\nInstead, user is expected to set baking properties manually.") + ToolTip.delay: root.toolTipDelay onToggled: rootView.manualMode = checked } diff --git a/share/qtcreator/qmldesigner/materialBrowserQmlSource/MaterialItem.qml b/share/qtcreator/qmldesigner/materialBrowserQmlSource/MaterialItem.qml index 86fec0936da..f055d1d665d 100644 --- a/share/qtcreator/qmldesigner/materialBrowserQmlSource/MaterialItem.qml +++ b/share/qtcreator/qmldesigner/materialBrowserQmlSource/MaterialItem.qml @@ -24,6 +24,11 @@ Rectangle { matName.commitRename() } + function startRename() + { + matName.startRename() + } + border.width: MaterialBrowserBackend.materialBrowserModel.selectedIndex === index ? MaterialBrowserBackend.rootView.materialSectionFocused ? 3 : 1 : 0 border.color: MaterialBrowserBackend.materialBrowserModel.selectedIndex === index ? StudioTheme.Values.themeControlOutlineInteraction diff --git a/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/HelperWidgets/EditableListView.qml b/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/HelperWidgets/EditableListView.qml index b8792c71ea6..1d007e0222a 100644 --- a/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/HelperWidgets/EditableListView.qml +++ b/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/HelperWidgets/EditableListView.qml @@ -24,7 +24,9 @@ Item { property real __actionIndicatorWidth: StudioTheme.Values.squareComponentWidth property real __actionIndicatorHeight: StudioTheme.Values.height property string typeFilter: "QtQuick3D.Material" - property string textRole: "idAndName" + // This binding is a workaround to overcome the rather long adaption to new Qt versions. This + // should actually be fixed in the ModelSection.qml by setting the textRole: "idAndName". + property string textRole: (root.typeFilter === "QtQuick3D.Material") ? "idAndName" : "id" property string valueRole: "id" property int activatedReason: ComboBox.ActivatedReason.Other @@ -42,60 +44,78 @@ Item { Layout.preferredWidth: StudioTheme.Values.height * 10 Layout.preferredHeight: myColumn.height + HelperWidgets.ListValidator { + id: listValidator + filterList: itemFilterModel.validationItems + } + HelperWidgets.ItemFilterModel { id: itemFilterModel typeFilter: root.typeFilter modelNodeBackendProperty: modelNodeBackend selectedItems: root.allowDuplicates ? [] : root.model + validationRoles: [root.textRole, root.valueRole] } Component { id: myDelegate Row { - property alias comboBox: itemFilterComboBox + property alias comboBox: delegateComboBox ListViewComboBox { - id: itemFilterComboBox + id: delegateComboBox property int myIndex: index - property bool empty: itemFilterComboBox.initialModelData === "" - - validator: RegExpValidator { regExp: /(^[a-z_]\w*|^[A-Z]\w*\.{1}([a-z_]\w*\.?)+)/ } + property bool empty: delegateComboBox.initialModelData === "" + validator: listValidator actionIndicatorVisible: false model: itemFilterModel initialModelData: modelData textRole: root.textRole valueRole: root.valueRole implicitWidth: StudioTheme.Values.singleControlColumnWidth - width: implicitWidth + width: delegateComboBox.implicitWidth textElidable: true onFocusChanged: { - if (itemFilterComboBox.focus) + if (delegateComboBox.focus) { myColumn.currentIndex = index + } else { + if (!delegateComboBox.dirty) + return - var curValue = itemFilterComboBox.availableValue() - if (itemFilterComboBox.empty && curValue !== "") { - myRepeater.dirty = false - root.add(curValue) + // If focus is lost check if text was changed and try to search for it in + // the text as well as in the value role. + let idx = delegateComboBox.indexOfString(delegateComboBox.editText) + if (idx === -1) { + delegateComboBox.editText = delegateComboBox.preFocusText + } else { + delegateComboBox.currentIndex = idx + if (delegateComboBox.empty && delegateComboBox.currentValue !== "") { + myRepeater.dirty = false + root.add(delegateComboBox.currentValue) + } else { + root.replace(delegateComboBox.myIndex, delegateComboBox.currentValue) + } + } } } onCompressedActivated: function(index, reason) { root.activatedReason = reason - var curValue = itemFilterComboBox.availableValue() - if (itemFilterComboBox.empty && curValue) { + var curValue = delegateComboBox.availableValue() + if (delegateComboBox.empty && curValue) { myRepeater.dirty = false root.add(curValue) } else { - root.replace(itemFilterComboBox.myIndex, curValue) + root.replace(delegateComboBox.myIndex, curValue) } } - onHoverChanged: root.delegateHover = itemFilterComboBox.hover + onHoverChanged: root.delegateHover = delegateComboBox.hover } Spacer { implicitWidth: extraButton.visible ? 5 : StudioTheme.Values.twoControlColumnGap } @@ -114,15 +134,17 @@ Item { icon: StudioTheme.Constants.closeCross onClicked: { var lastItem = index === myRepeater.localModel.length - 1 - if (myColumn.currentItem.initialModelData === "") { + var tmp = myRepeater.itemAt(index) + + myColumn.currentIndex = index - 1 + + if (tmp.comboBox.initialModelData === "") { myRepeater.localModel.pop() myRepeater.dirty = false myRepeater.model = myRepeater.localModel // trigger on change handler } else { root.remove(index) } - if (!lastItem) - myColumn.currentIndex = index - 1 } onHoveredChanged: root.delegateHover = closeIndicator.hovered } @@ -152,6 +174,11 @@ Item { myColumn.currentItem = tmp.comboBox } + onCurrentItemChanged: { + if (myColumn.currentItem !== null) + myColumn.currentItem.forceActiveFocus() + } + Repeater { id: myRepeater @@ -162,7 +189,7 @@ Item { onItemAdded: function(index, item) { if (index === myColumn.currentIndex) - myColumn.currentItem = item + myColumn.currentItem = item.comboBox } function updateModel() { @@ -180,9 +207,7 @@ Item { myRepeater.model = myRepeater.localModel // trigger on change handler - if (lastIndex < 0 && myRepeater.localModel.length > 0) - myColumn.currentIndex = 0 - else if (myRepeater.localModel.length > lastIndex) + if (myRepeater.localModel.length > lastIndex) myColumn.currentIndex = lastIndex else myColumn.currentIndex = myRepeater.localModel.length - 1 @@ -196,28 +221,41 @@ Item { ListViewComboBox { id: dummyComboBox visible: myRepeater.count === 0 - validator: RegExpValidator { regExp: /(^[a-z_]\w*|^[A-Z]\w*\.{1}([a-z_]\w*\.?)+)/ } + validator: listValidator actionIndicatorVisible: false model: itemFilterModel textRole: root.textRole valueRole: root.valueRole implicitWidth: StudioTheme.Values.singleControlColumnWidth - width: implicitWidth + width: dummyComboBox.implicitWidth + + onVisibleChanged: dummyComboBox.currentIndex = -1 onFocusChanged: { - var curValue = dummyComboBox.availableValue() - if (curValue !== "") - root.add(curValue) + if (dummyComboBox.focus) + return + + if (!dummyComboBox.dirty) + return + + // If focus is lost check if text was changed and try to search for it in + // the text as well as in the value role. + let idx = dummyComboBox.indexOfString(dummyComboBox.editText) + if (idx === -1) { + dummyComboBox.editText = dummyComboBox.preFocusText + } else { + dummyComboBox.currentIndex = idx + if (dummyComboBox.currentValue !== "") + root.add(dummyComboBox.currentValue) + } } - onCompressedActivated: { + onCompressedActivated: function(index, reason) { root.activatedReason = reason var curValue = dummyComboBox.availableValue() if (curValue !== "") root.add(curValue) - else - root.replace(dummyComboBox.myIndex, curValue) } onHoverChanged: root.delegateHover = dummyComboBox.hover diff --git a/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/HelperWidgets/LineEdit.qml b/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/HelperWidgets/LineEdit.qml index b73bde29310..dffe3d779ea 100644 --- a/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/HelperWidgets/LineEdit.qml +++ b/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/HelperWidgets/LineEdit.qml @@ -40,7 +40,7 @@ StudioControls.TextField { function escapeString(string) { var str = string str = str.replace(/\\/g, "\\\\") - str.replace(/\"/g, "\\\"") + str = str.replace(/\"/g, "\\\"") str = str.replace(/\t/g, "\\t") str = str.replace(/\r/g, "\\r") str = str.replace(/\n/g, '\\n') diff --git a/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/HelperWidgets/ListViewComboBox.qml b/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/HelperWidgets/ListViewComboBox.qml index 1f8dbbb3d41..3e15540d140 100644 --- a/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/HelperWidgets/ListViewComboBox.qml +++ b/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/HelperWidgets/ListViewComboBox.qml @@ -51,4 +51,21 @@ StudioControls.ComboBox { return root.editText } + + // Checks if the given parameter can be found as a value or text (valueRole vs. textRole). If + // both searches result an index !== -1 the text is preferred, otherwise index will be returned + // or -1 if not found. + // Text is preferred due to the fact that usually the users use the autocomplete functionality + // of an editable ComboBox hence there will be more hits on text search then on value. + function indexOfString(text) { + let textIndex = root.find(text) + if (textIndex !== -1) + return textIndex + + let valueIndex = root.indexOfValue(text) + if (valueIndex !== -1) + return valueIndex + + return -1 + } } diff --git a/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/HelperWidgets/OriginControl.qml b/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/HelperWidgets/OriginControl.qml index f4d4f7af856..e07b371cbde 100644 --- a/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/HelperWidgets/OriginControl.qml +++ b/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/HelperWidgets/OriginControl.qml @@ -17,6 +17,11 @@ Row { root.backendValue.setEnumeration("Item", value) } + Connections { + target: modelNodeBackend + function onSelectionChanged() { originPopup.close() } + } + ExtendedFunctionLogic { id: extFuncLogic backendValue: root.backendValue diff --git a/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/StudioControls/ComboBox.qml b/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/StudioControls/ComboBox.qml index 39b1ac8a1cf..abbb32744b5 100644 --- a/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/StudioControls/ComboBox.qml +++ b/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/StudioControls/ComboBox.qml @@ -34,6 +34,8 @@ T.ComboBox { property int maximumPopupHeight: control.style.maxComboBoxPopupHeight + property string preFocusText: "" + signal compressedActivated(int index, int reason) enum ActivatedReason { EditingFinished, Other } @@ -53,7 +55,7 @@ T.ComboBox { onActiveFocusChanged: { if (control.activeFocus) - comboBoxInput.preFocusText = control.editText + control.preFocusText = control.editText } ActionIndicator { @@ -69,8 +71,6 @@ T.ComboBox { contentItem: ComboBoxInput { id: comboBoxInput - property string preFocusText: "" - style: control.style __parentControl: control text: control.editText @@ -332,8 +332,8 @@ T.ComboBox { Keys.onPressed: function(event) { if (event.key === Qt.Key_Escape) { - control.editText = comboBoxInput.preFocusText - control.dirty = true + control.editText = control.preFocusText + control.dirty = false control.focus = false } } diff --git a/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/StudioTheme/InternalConstants.qml b/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/StudioTheme/InternalConstants.qml index 1a07944b241..f5a3bbdc7bf 100644 --- a/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/StudioTheme/InternalConstants.qml +++ b/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/StudioTheme/InternalConstants.qml @@ -133,209 +133,212 @@ QtObject { readonly property string editLightOn_medium: "\u0096" readonly property string edit_medium: "\u0097" readonly property string edit_small: "\u0098" - readonly property string events_small: "\u0099" - readonly property string export_medium: "\u009A" - readonly property string eyeDropper: "\u009B" - readonly property string favorite: "\u009D" - readonly property string fitAll_medium: "\u009E" - readonly property string fitSelected_small: "\u009F" - readonly property string fitSelection_medium: "\u00A0" - readonly property string fitToView_medium: "\u00A1" - readonly property string flowAction: "\u00A2" - readonly property string flowTransition: "\u00A3" - readonly property string fontStyleBold: "\u00A4" - readonly property string fontStyleItalic: "\u00A5" - readonly property string fontStyleStrikethrough: "\u00A6" - readonly property string fontStyleUnderline: "\u00A7" - readonly property string forward_medium: "\u00A8" - readonly property string globalOrient_medium: "\u00A9" - readonly property string gradient: "\u00AA" - readonly property string gridView: "\u00AB" - readonly property string grid_medium: "\u00AC" - readonly property string group_small: "\u00AE" - readonly property string home_large: "\u00AF" - readonly property string idAliasOff: "\u00B0" - readonly property string idAliasOn: "\u00B1" - readonly property string import_medium: "\u00B2" - readonly property string imported: "\u00B3" - readonly property string importedModels_small: "\u00B4" - readonly property string infinity: "\u00B5" - readonly property string invisible_medium: "\u00B6" - readonly property string keyframe: "\u00B7" - readonly property string languageList_medium: "\u00B8" - readonly property string layouts_small: "\u00B9" - readonly property string lights_small: "\u00BA" - readonly property string linear_medium: "\u00BB" - readonly property string linkTriangle: "\u00BC" - readonly property string linked: "\u00BD" - readonly property string listView: "\u00BE" - readonly property string list_medium: "\u00BF" - readonly property string localOrient_medium: "\u00C0" - readonly property string lockOff: "\u00C1" - readonly property string lockOn: "\u00C2" - readonly property string loopPlayback_medium: "\u00C3" - readonly property string materialBrowser_medium: "\u00C4" - readonly property string materialPreviewEnvironment: "\u00C5" - readonly property string materialPreviewModel: "\u00C6" - readonly property string material_medium: "\u00C7" - readonly property string mergeCells: "\u00C8" - readonly property string merge_small: "\u00C9" - readonly property string minus: "\u00CA" - readonly property string mirror: "\u00CB" - readonly property string more_medium: "\u00CC" - readonly property string mouseArea_small: "\u00CD" - readonly property string moveDown_medium: "\u00CE" - readonly property string moveInwards_medium: "\u00CF" - readonly property string moveUp_medium: "\u00D0" - readonly property string moveUpwards_medium: "\u00D1" - readonly property string move_medium: "\u00D2" - readonly property string newMaterial: "\u00D3" - readonly property string nextFile_large: "\u00D4" - readonly property string openLink: "\u00D5" - readonly property string openMaterialBrowser: "\u00D6" - readonly property string orientation: "\u00D7" - readonly property string orthCam_medium: "\u00D8" - readonly property string orthCam_small: "\u00D9" - readonly property string paddingEdge: "\u00DA" - readonly property string paddingFrame: "\u00DB" - readonly property string particleAnimation_medium: "\u00DC" - readonly property string pasteStyle: "\u00DD" - readonly property string paste_small: "\u00DE" - readonly property string pause: "\u00DF" - readonly property string perspectiveCam_medium: "\u00E0" - readonly property string perspectiveCam_small: "\u00E1" - readonly property string pin: "\u00E2" - readonly property string plane_medium: "\u00E3" - readonly property string plane_small: "\u00E4" - readonly property string play: "\u00E5" - readonly property string playFill_medium: "\u00E6" - readonly property string playOutline_medium: "\u00E7" - readonly property string plus: "\u00E8" - readonly property string pointLight_small: "\u00E9" - readonly property string positioners_small: "\u00EA" - readonly property string previewEnv_medium: "\u00EB" - readonly property string previousFile_large: "\u00EC" - readonly property string promote: "\u00ED" - readonly property string properties_medium: "\u00EE" - readonly property string readOnly: "\u00EF" - readonly property string recordFill_medium: "\u00F0" - readonly property string recordOutline_medium: "\u00F1" - readonly property string redo: "\u00F2" - readonly property string reload_medium: "\u00F3" - readonly property string remove_medium: "\u00F4" - readonly property string remove_small: "\u00F5" - readonly property string rename_small: "\u00F6" - readonly property string replace_small: "\u00F7" - readonly property string resetView_small: "\u00F8" - readonly property string restartParticles_medium: "\u00F9" - readonly property string reverseOrder_medium: "\u00FA" - readonly property string roatate_medium: "\u00FB" - readonly property string rotationFill: "\u00FC" - readonly property string rotationOutline: "\u00FD" - readonly property string runProjFill_large: "\u00FE" - readonly property string runProjOutline_large: "\u00FF" - readonly property string s_anchors: "\u0100" - readonly property string s_annotations: "\u0101" - readonly property string s_arrange: "\u0102" - readonly property string s_boundingBox: "\u0103" - readonly property string s_component: "\u0104" - readonly property string s_connections: "\u0105" - readonly property string s_edit: "\u0106" - readonly property string s_enterComponent: "\u0107" - readonly property string s_eventList: "\u0108" - readonly property string s_group: "\u0109" - readonly property string s_layouts: "\u010A" - readonly property string s_merging: "\u010B" - readonly property string s_mouseArea: "\u010C" - readonly property string s_positioners: "\u010D" - readonly property string s_selection: "\u010E" - readonly property string s_snapping: "\u010F" - readonly property string s_timeline: "\u0110" - readonly property string s_visibility: "\u0111" - readonly property string saveLogs_medium: "\u0112" - readonly property string scale_medium: "\u0113" - readonly property string search: "\u0114" - readonly property string search_small: "\u0115" - readonly property string sectionToggle: "\u0116" - readonly property string selectFill_medium: "\u0117" - readonly property string selectOutline_medium: "\u0118" - readonly property string selectParent_small: "\u0119" - readonly property string selection_small: "\u011A" - readonly property string settings_medium: "\u011B" - readonly property string signal_small: "\u011C" - readonly property string snapping_small: "\u011D" - readonly property string sphere_medium: "\u011E" - readonly property string sphere_small: "\u011F" - readonly property string splitColumns: "\u0120" - readonly property string splitRows: "\u0121" - readonly property string spotLight_small: "\u0122" - readonly property string stackedContainer_small: "\u0123" - readonly property string startNode: "\u0124" - readonly property string step_medium: "\u0125" - readonly property string stop_medium: "\u0126" - readonly property string testIcon: "\u0127" - readonly property string textAlignBottom: "\u0128" - readonly property string textAlignCenter: "\u0129" - readonly property string textAlignJustified: "\u012A" - readonly property string textAlignLeft: "\u012B" - readonly property string textAlignMiddle: "\u012C" - readonly property string textAlignRight: "\u012D" - readonly property string textAlignTop: "\u012E" - readonly property string textBulletList: "\u012F" - readonly property string textFullJustification: "\u0130" - readonly property string textNumberedList: "\u0131" - readonly property string textures_medium: "\u0132" - readonly property string tickIcon: "\u0133" - readonly property string tickMark_small: "\u0134" - readonly property string timeline_small: "\u0135" - readonly property string toEndFrame_medium: "\u0136" - readonly property string toNextFrame_medium: "\u0137" - readonly property string toPrevFrame_medium: "\u0138" - readonly property string toStartFrame_medium: "\u0139" - readonly property string topToolbar_annotations: "\u013A" - readonly property string topToolbar_closeFile: "\u013B" - readonly property string topToolbar_designMode: "\u013C" - readonly property string topToolbar_enterComponent: "\u013D" - readonly property string topToolbar_home: "\u013E" - readonly property string topToolbar_makeComponent: "\u013F" - readonly property string topToolbar_navFile: "\u0140" - readonly property string topToolbar_runProject: "\u0141" - readonly property string translationCreateFiles: "\u0142" - readonly property string translationCreateReport: "\u0143" - readonly property string translationExport: "\u0144" - readonly property string translationImport: "\u0145" - readonly property string translationSelectLanguages: "\u0146" - readonly property string translationTest: "\u0147" - readonly property string transparent: "\u0148" - readonly property string triState: "\u0149" - readonly property string triangleArcA: "\u014A" - readonly property string triangleArcB: "\u014B" - readonly property string triangleCornerA: "\u014C" - readonly property string triangleCornerB: "\u014D" - readonly property string unLinked: "\u014E" - readonly property string undo: "\u014F" - readonly property string unify_medium: "\u0150" - readonly property string unpin: "\u0151" - readonly property string upDownIcon: "\u0152" - readonly property string upDownSquare2: "\u0153" - readonly property string visibilityOff: "\u0154" - readonly property string visibilityOn: "\u0155" - readonly property string visible_medium: "\u0156" - readonly property string visible_small: "\u0157" - readonly property string wildcard: "\u0158" - readonly property string wizardsAutomotive: "\u0159" - readonly property string wizardsDesktop: "\u015A" - readonly property string wizardsGeneric: "\u015B" - readonly property string wizardsMcuEmpty: "\u015C" - readonly property string wizardsMcuGraph: "\u015D" - readonly property string wizardsMobile: "\u015E" - readonly property string wizardsUnknown: "\u015F" - readonly property string zoomAll: "\u0160" - readonly property string zoomIn: "\u0161" - readonly property string zoomIn_medium: "\u0162" - readonly property string zoomOut: "\u0163" - readonly property string zoomOut_medium: "\u0164" - readonly property string zoomSelection: "\u0165" + readonly property string effects: "\u0099" + readonly property string events_small: "\u009A" + readonly property string export_medium: "\u009B" + readonly property string eyeDropper: "\u009D" + readonly property string favorite: "\u009E" + readonly property string fitAll_medium: "\u009F" + readonly property string fitSelected_small: "\u00A0" + readonly property string fitSelection_medium: "\u00A1" + readonly property string fitToView_medium: "\u00A2" + readonly property string flowAction: "\u00A3" + readonly property string flowTransition: "\u00A4" + readonly property string fontStyleBold: "\u00A5" + readonly property string fontStyleItalic: "\u00A6" + readonly property string fontStyleStrikethrough: "\u00A7" + readonly property string fontStyleUnderline: "\u00A8" + readonly property string forward_medium: "\u00A9" + readonly property string globalOrient_medium: "\u00AA" + readonly property string gradient: "\u00AB" + readonly property string gridView: "\u00AC" + readonly property string grid_medium: "\u00AE" + readonly property string group_small: "\u00AF" + readonly property string home_large: "\u00B0" + readonly property string idAliasOff: "\u00B1" + readonly property string idAliasOn: "\u00B2" + readonly property string import_medium: "\u00B3" + readonly property string imported: "\u00B4" + readonly property string importedModels_small: "\u00B5" + readonly property string infinity: "\u00B6" + readonly property string invisible_medium: "\u00B7" + readonly property string keyframe: "\u00B8" + readonly property string languageList_medium: "\u00B9" + readonly property string layouts_small: "\u00BA" + readonly property string lights_small: "\u00BB" + readonly property string linear_medium: "\u00BC" + readonly property string linkTriangle: "\u00BD" + readonly property string linked: "\u00BE" + readonly property string listView: "\u00BF" + readonly property string list_medium: "\u00C0" + readonly property string localOrient_medium: "\u00C1" + readonly property string lockOff: "\u00C2" + readonly property string lockOn: "\u00C3" + readonly property string loopPlayback_medium: "\u00C4" + readonly property string materialBrowser_medium: "\u00C5" + readonly property string materialPreviewEnvironment: "\u00C6" + readonly property string materialPreviewModel: "\u00C7" + readonly property string material_medium: "\u00C8" + readonly property string mergeCells: "\u00C9" + readonly property string merge_small: "\u00CA" + readonly property string minus: "\u00CB" + readonly property string mirror: "\u00CC" + readonly property string more_medium: "\u00CD" + readonly property string mouseArea_small: "\u00CE" + readonly property string moveDown_medium: "\u00CF" + readonly property string moveInwards_medium: "\u00D0" + readonly property string moveUp_medium: "\u00D1" + readonly property string moveUpwards_medium: "\u00D2" + readonly property string move_medium: "\u00D3" + readonly property string newMaterial: "\u00D4" + readonly property string nextFile_large: "\u00D5" + readonly property string openLink: "\u00D6" + readonly property string openMaterialBrowser: "\u00D7" + readonly property string orientation: "\u00D8" + readonly property string orthCam_medium: "\u00D9" + readonly property string orthCam_small: "\u00DA" + readonly property string paddingEdge: "\u00DB" + readonly property string paddingFrame: "\u00DC" + readonly property string particleAnimation_medium: "\u00DD" + readonly property string pasteStyle: "\u00DE" + readonly property string paste_small: "\u00DF" + readonly property string pause: "\u00E0" + readonly property string perspectiveCam_medium: "\u00E1" + readonly property string perspectiveCam_small: "\u00E2" + readonly property string pin: "\u00E3" + readonly property string plane_medium: "\u00E4" + readonly property string plane_small: "\u00E5" + readonly property string play: "\u00E6" + readonly property string playFill_medium: "\u00E7" + readonly property string playOutline_medium: "\u00E8" + readonly property string plus: "\u00E9" + readonly property string pointLight_small: "\u00EA" + readonly property string positioners_small: "\u00EB" + readonly property string previewEnv_medium: "\u00EC" + readonly property string previousFile_large: "\u00ED" + readonly property string promote: "\u00EE" + readonly property string properties_medium: "\u00EF" + readonly property string readOnly: "\u00F0" + readonly property string recordFill_medium: "\u00F1" + readonly property string recordOutline_medium: "\u00F2" + readonly property string redo: "\u00F3" + readonly property string reload_medium: "\u00F4" + readonly property string remove_medium: "\u00F5" + readonly property string remove_small: "\u00F6" + readonly property string rename_small: "\u00F7" + readonly property string replace_small: "\u00F8" + readonly property string resetView_small: "\u00F9" + readonly property string restartParticles_medium: "\u00FA" + readonly property string reverseOrder_medium: "\u00FB" + readonly property string roatate_medium: "\u00FC" + readonly property string rotationFill: "\u00FD" + readonly property string rotationOutline: "\u00FE" + readonly property string runProjFill_large: "\u00FF" + readonly property string runProjOutline_large: "\u0100" + readonly property string s_anchors: "\u0101" + readonly property string s_annotations: "\u0102" + readonly property string s_arrange: "\u0103" + readonly property string s_boundingBox: "\u0104" + readonly property string s_component: "\u0105" + readonly property string s_connections: "\u0106" + readonly property string s_edit: "\u0107" + readonly property string s_enterComponent: "\u0108" + readonly property string s_eventList: "\u0109" + readonly property string s_group: "\u010A" + readonly property string s_layouts: "\u010B" + readonly property string s_merging: "\u010C" + readonly property string s_mouseArea: "\u010D" + readonly property string s_positioners: "\u010E" + readonly property string s_selection: "\u010F" + readonly property string s_snapping: "\u0110" + readonly property string s_timeline: "\u0111" + readonly property string s_visibility: "\u0112" + readonly property string saveLogs_medium: "\u0113" + readonly property string scale_medium: "\u0114" + readonly property string search: "\u0115" + readonly property string search_small: "\u0116" + readonly property string sectionToggle: "\u0117" + readonly property string selectFill_medium: "\u0118" + readonly property string selectOutline_medium: "\u0119" + readonly property string selectParent_small: "\u011A" + readonly property string selection_small: "\u011B" + readonly property string settings_medium: "\u011C" + readonly property string signal_small: "\u011D" + readonly property string snapping_small: "\u011E" + readonly property string sphere_medium: "\u011F" + readonly property string sphere_small: "\u0120" + readonly property string splitColumns: "\u0121" + readonly property string splitRows: "\u0122" + readonly property string spotLight_small: "\u0123" + readonly property string stackedContainer_small: "\u0124" + readonly property string startNode: "\u0125" + readonly property string step_medium: "\u0126" + readonly property string stop_medium: "\u0127" + readonly property string testIcon: "\u0128" + readonly property string textAlignBottom: "\u0129" + readonly property string textAlignCenter: "\u012A" + readonly property string textAlignJustified: "\u012B" + readonly property string textAlignLeft: "\u012C" + readonly property string textAlignMiddle: "\u012D" + readonly property string textAlignRight: "\u012E" + readonly property string textAlignTop: "\u012F" + readonly property string textBulletList: "\u0130" + readonly property string textFullJustification: "\u0131" + readonly property string textNumberedList: "\u0132" + readonly property string textures_medium: "\u0133" + readonly property string tickIcon: "\u0134" + readonly property string tickMark_small: "\u0135" + readonly property string timeline_small: "\u0136" + readonly property string toEndFrame_medium: "\u0137" + readonly property string toNextFrame_medium: "\u0138" + readonly property string toPrevFrame_medium: "\u0139" + readonly property string toStartFrame_medium: "\u013A" + readonly property string topToolbar_annotations: "\u013B" + readonly property string topToolbar_closeFile: "\u013C" + readonly property string topToolbar_designMode: "\u013D" + readonly property string topToolbar_enterComponent: "\u013E" + readonly property string topToolbar_home: "\u013F" + readonly property string topToolbar_makeComponent: "\u0140" + readonly property string topToolbar_navFile: "\u0141" + readonly property string topToolbar_runProject: "\u0142" + readonly property string translationCreateFiles: "\u0143" + readonly property string translationCreateReport: "\u0144" + readonly property string translationExport: "\u0145" + readonly property string translationImport: "\u0146" + readonly property string translationSelectLanguages: "\u0147" + readonly property string translationTest: "\u0148" + readonly property string transparent: "\u0149" + readonly property string triState: "\u014A" + readonly property string triangleArcA: "\u014B" + readonly property string triangleArcB: "\u014C" + readonly property string triangleCornerA: "\u014D" + readonly property string triangleCornerB: "\u014E" + readonly property string unLinked: "\u014F" + readonly property string undo: "\u0150" + readonly property string unify_medium: "\u0151" + readonly property string unpin: "\u0152" + readonly property string upDownIcon: "\u0153" + readonly property string upDownSquare2: "\u0154" + readonly property string updateAvailable_medium: "\u0155" + readonly property string updateContent_medium: "\u0156" + readonly property string visibilityOff: "\u0157" + readonly property string visibilityOn: "\u0158" + readonly property string visible_medium: "\u0159" + readonly property string visible_small: "\u015A" + readonly property string wildcard: "\u015B" + readonly property string wizardsAutomotive: "\u015C" + readonly property string wizardsDesktop: "\u015D" + readonly property string wizardsGeneric: "\u015E" + readonly property string wizardsMcuEmpty: "\u015F" + readonly property string wizardsMcuGraph: "\u0160" + readonly property string wizardsMobile: "\u0161" + readonly property string wizardsUnknown: "\u0162" + readonly property string zoomAll: "\u0163" + readonly property string zoomIn: "\u0164" + readonly property string zoomIn_medium: "\u0165" + readonly property string zoomOut: "\u0166" + readonly property string zoomOut_medium: "\u0167" + readonly property string zoomSelection: "\u0168" readonly property font iconFont: Qt.font({ "family": controlIcons.name, diff --git a/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/StudioTheme/icons.ttf b/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/StudioTheme/icons.ttf index 1b1821ae999..3c3fa3bd67d 100644 Binary files a/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/StudioTheme/icons.ttf and b/share/qtcreator/qmldesigner/propertyEditorQmlSources/imports/StudioTheme/icons.ttf differ diff --git a/share/qtcreator/qmldesigner/qt4mcu/qul-24.qml b/share/qtcreator/qmldesigner/qt4mcu/qul-24.qml index f78b00b8c65..1c5d00a33f3 100644 --- a/share/qtcreator/qmldesigner/qt4mcu/qul-24.qml +++ b/share/qtcreator/qmldesigner/qt4mcu/qul-24.qml @@ -207,4 +207,8 @@ VersionData { bannedProperties: ["dashOffset", "dashPattern", "fillGradient", "strokeStyle"] } + + QtQuickUltralite.Extras.ItemBuffer { + allowedProperties: ["rotation", "scale", "transformOrigin"] + } } diff --git a/share/qtcreator/qmldesigner/statesEditorQmlSources/StatesDelegate.qml b/share/qtcreator/qmldesigner/statesEditorQmlSources/StatesDelegate.qml deleted file mode 100644 index 3f42fb75117..00000000000 --- a/share/qtcreator/qmldesigner/statesEditorQmlSources/StatesDelegate.qml +++ /dev/null @@ -1,296 +0,0 @@ -// Copyright (C) 2020 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 - -import QtQuick 2.15 -import QtQuick.Layouts 1.15 -import QtQuickDesignerTheme 1.0 -import HelperWidgets 2.0 -import StudioControls 1.0 as StudioControls -import StudioTheme 1.0 as StudioTheme - -Rectangle { - id: myRoot - - property bool isBaseState - property bool isCurrentState - property string delegateStateName - property string delegateStateImageSource - property bool delegateHasWhenCondition - property string delegateWhenConditionString - property bool hasAnnotation: checkAnnotation() - property int topAreaHeight - property int bottomAreaHeight - property int stateMargin - property int previewMargin - - readonly property bool isDefaultState: isDefault - - property int closeButtonMargin: 6 - property int textFieldMargin: 4 - - property int scrollBarH: 0 - property int listMargin: 0 - - function autoComplete(text, pos, explicitComplete, filter) { - var stringList = statesEditorModel.autoComplete(text, pos, explicitComplete) - return stringList - } - - function checkAnnotation() { - return statesEditorModel.hasAnnotation(internalNodeId) - } - - color: isCurrentState ? StudioTheme.Values.themeInteraction - : StudioTheme.Values.themeControlBackgroundInteraction - MouseArea { - id: mouseArea - anchors.fill: parent - - onClicked: { - focus = true - root.currentStateInternalId = internalNodeId - contextMenu.dismiss() // close potentially open context menu - } - } - - StudioControls.AbstractButton { - id: removeStateButton - - buttonIcon: StudioTheme.Constants.closeCross - - anchors.right: parent.right - anchors.rightMargin: myRoot.closeButtonMargin - anchors.top: parent.top - anchors.topMargin: myRoot.closeButtonMargin - - visible: !isBaseState && isCurrentState - - onClicked: { - if (isDefaultState) - statesEditorModel.resetDefaultState() - - root.deleteState(internalNodeId) - } - } - - StudioControls.Menu { - id: contextMenu - - StudioControls.MenuItem { - enabled: !isBaseState - text: qsTr("Set when Condition") - onTriggered: { - bindingEditor.showWidget() - bindingEditor.text = delegateWhenConditionString - bindingEditor.prepareBindings() - bindingEditor.updateWindowName() - } - } - - StudioControls.MenuItem { - enabled: !isBaseState && delegateHasWhenCondition - text: qsTr("Reset when Condition") - onTriggered: { - statesEditorModel.resetWhenCondition(internalNodeId) - } - } - - StudioControls.MenuItem { - enabled: !isBaseState && !isDefaultState - text: qsTr("Set as Default") - onTriggered: { - statesEditorModel.setStateAsDefault(internalNodeId) - } - } - - StudioControls.MenuItem { - enabled: (!isBaseState && isDefaultState) || (isBaseState && modelHasDefaultState) - text: qsTr("Reset Default") - onTriggered: { - statesEditorModel.resetDefaultState() - } - } - - StudioControls.MenuItem { - enabled: !isBaseState - text: (hasAnnotation ? qsTr("Edit Annotation") - : qsTr("Add Annotation")) - onTriggered: { - statesEditorModel.setAnnotation(internalNodeId) - hasAnnotation = checkAnnotation() - } - } - - StudioControls.MenuItem { - enabled: !isBaseState && hasAnnotation - text: qsTr("Remove Annotation") - onTriggered: { - statesEditorModel.removeAnnotation(internalNodeId) - hasAnnotation = checkAnnotation() - } - } - - onClosed: { - stateNameField.actionIndicator.forceVisible = false - } - - onOpened: { - hasAnnotation = checkAnnotation() - myRoot.delegateInteraction() - } - } - - Column { - id: column - - anchors.margins: myRoot.stateMargin - anchors.fill: parent - - Rectangle { - width: myRoot.width - 2 * myRoot.stateMargin - height: myRoot.topAreaHeight - - color: StudioTheme.Values.themeStateBackground - - StudioControls.TextField { - id: stateNameField - - property string oldValue - - width: StudioTheme.Values.height * 5.5 - - anchors.top: parent.top - anchors.topMargin: myRoot.textFieldMargin - anchors.left: parent.left - anchors.leftMargin: myRoot.textFieldMargin - - translationIndicatorVisible: false - readOnly: isBaseState - - actionIndicator.icon.text: delegateHasWhenCondition - ? StudioTheme.Constants.actionIconBinding - : StudioTheme.Constants.actionIcon - - - actionIndicator.onClicked: { - stateNameField.actionIndicator.forceVisible = true - contextMenu.popup() - } - - onEditChanged: { - if (contextMenu.open && stateNameField.edit) - contextMenu.dismiss() - } - - onActiveFocusChanged: { - if (activeFocus) - root.currentStateInternalId = internalNodeId - } - - onEditingFinished: { - if (stateNameField.oldValue === stateNameField.text) - return - - stateNameField.oldValue = stateNameField.text - - if (stateNameField.text !== myRoot.delegateStateName) - statesEditorModel.renameState(internalNodeId, stateNameField.text) - } - - Component.onCompleted: { - text = myRoot.delegateStateName - } - - //QDS-5649: - Keys.priority: Keys.BeforeItem - Keys.onEscapePressed: function (event) { - event.accepted = true - stateNameField.text = myRoot.delegateStateName - stateNameField.focus = false - } - } - - Text { - id: stateDefaultIndicator - - anchors.right: parent.right - anchors.rightMargin: myRoot.previewMargin - anchors.verticalCenter: stateNameField.verticalCenter - - color: StudioTheme.Values.themeTextColor - font.italic: true - font.pixelSize: StudioTheme.Values.myFontSize - font.family: StudioTheme.Constants.font - - visible: isDefaultState || (isBaseState && !modelHasDefaultState) - - text: qsTr("Default") - } - } - - Rectangle { // separator - width: column.width - height: 2 - color: StudioTheme.Values.themeStateSeparator - } - - Rectangle { - id: stateImageArea - width: myRoot.width - 2 * myRoot.stateMargin - height: myRoot.bottomAreaHeight - color: StudioTheme.Values.themeStateBackground - - Image { - anchors.fill: stateImageBackground - source: "images/checkers.png" - fillMode: Image.Tile - } - - Rectangle { - id: stateImageBackground - anchors.centerIn: parent - width: Math.round(stateImage.paintedWidth) + 2 * StudioTheme.Values.border - height: Math.round(stateImage.paintedHeight) + 2 * StudioTheme.Values.border - color: "transparent" - border.width: StudioTheme.Values.border - border.color: StudioTheme.Values.themeStatePreviewOutline - } - - Image { - id: stateImage - anchors.margins: myRoot.previewMargin - anchors.centerIn: parent - anchors.fill: parent - source: delegateStateImageSource - fillMode: Image.PreserveAspectFit - mipmap: true - } - } - } - - BindingEditor { - id: bindingEditor - - property string newWhenCondition - - property Timer timer: Timer { - id: timer - running: false - interval: 50 - repeat: false - onTriggered: statesEditorModel.setWhenCondition(internalNodeId, bindingEditor.newWhenCondition) - } - - stateModelNodeProperty: statesEditorModel.stateModelNode() - stateNameProperty: myRoot.delegateStateName - - onRejected: { - hideWidget() - } - onAccepted: { - bindingEditor.newWhenCondition = bindingEditor.text.trim() - timer.start() - hideWidget() - } - } -} diff --git a/share/qtcreator/qmldesigner/statesEditorQmlSources/StatesList.qml b/share/qtcreator/qmldesigner/statesEditorQmlSources/StatesList.qml deleted file mode 100644 index e56d7419099..00000000000 --- a/share/qtcreator/qmldesigner/statesEditorQmlSources/StatesList.qml +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright (C) 2020 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 - -import QtQuick 2.15 -import QtQuick.Controls 2.15 -import QtQuickDesignerTheme 1.0 -import Qt.labs.qmlmodels 1.0 -import HelperWidgets 2.0 -import StudioControls 1.0 as StudioControls -import StudioTheme 1.0 as StudioTheme - -FocusScope { - id: root - - readonly property int delegateTopAreaHeight: StudioTheme.Values.height + 8 - readonly property int delegateBottomAreaHeight: delegateHeight - 2 * delegateStateMargin - delegateTopAreaHeight - 2 - readonly property int delegateStateMargin: 16 - readonly property int delegatePreviewMargin: 10 - readonly property int effectiveHeight: root.height < 130 ? 89 : Math.min(root.height, 287) - - readonly property int scrollBarH: statesListView.ScrollBar.horizontal.scrollBarVisible ? StudioTheme.Values.scrollBarThickness : 0 - readonly property int listMargin: 10 - readonly property int delegateWidth: 264 - readonly property int delegateHeight: Math.max(effectiveHeight - scrollBarH - 2 * listMargin, 69) - readonly property int innerSpacing: 2 - - property int currentStateInternalId: 0 - - signal createNewState - signal deleteState(int internalNodeId) - signal duplicateCurrentState - - Connections { - target: statesEditorModel - function onChangedToState(n) { root.currentStateInternalId = n } - } - - Rectangle { - id: background - anchors.fill: parent - color: StudioTheme.Values.themePanelBackground - } - - AbstractButton { - id: addStateButton - - buttonIcon: StudioTheme.Constants.plus - iconFont: StudioTheme.Constants.iconFont - iconSize: StudioTheme.Values.myIconFontSize - tooltip: qsTr("Add a new state.") - visible: canAddNewStates - anchors.right: parent.right - anchors.rightMargin: 4 - anchors.bottom: parent.bottom - anchors.bottomMargin: statesListView.contentWidth - statesListView.contentX - root.delegateWidth / 2 > statesListView.width ? scrollBarH + 5 : -35 - width: 35 - height: 35 - - Behavior on anchors.bottomMargin { - PropertyAnimation { - duration: 700 - easing.type: Easing.InOutBack - } - } - - onClicked: root.createNewState() - } - - ListView { - id: statesListView - - clip: true - anchors.fill: parent - anchors.topMargin: listMargin - anchors.leftMargin: listMargin - anchors.rightMargin: listMargin - - model: statesEditorModel - orientation: ListView.Horizontal - spacing: root.innerSpacing - - property int prevCount: 0 - onCountChanged: { - if (count > prevCount) - Qt.callLater(statesListView.positionViewAtEnd) - prevCount = count - } - - delegate: DelegateChooser { - role: "type" - - DelegateChoice { - roleValue: "state" - - StatesDelegate { - width: root.delegateWidth - height: root.delegateHeight - anchors.verticalCenter: parent ? parent.verticalCenter : undefined - anchors.verticalCenterOffset: -.5 * (scrollBarH + listMargin) - isBaseState: 0 === internalNodeId - isCurrentState: root.currentStateInternalId === internalNodeId - delegateStateName: stateName - delegateStateImageSource: stateImageSource - delegateHasWhenCondition: hasWhenCondition - delegateWhenConditionString: whenConditionString - - topAreaHeight: root.delegateTopAreaHeight - bottomAreaHeight: root.delegateBottomAreaHeight - stateMargin: root.delegateStateMargin - previewMargin: root.delegatePreviewMargin - scrollBarH: root.scrollBarH - listMargin: root.listMargin - } - } - - DelegateChoice { - roleValue: "add" - - Rectangle { - visible: canAddNewStates - - width: root.delegateWidth - height: root.delegateHeight - anchors.verticalCenter: parent ? parent.verticalCenter : undefined - anchors.verticalCenterOffset: -.5 * (scrollBarH + listMargin) - color: Qt.lighter(StudioTheme.Values.themeControlBackgroundInteraction, addState.containsMouse ? 1.5 : 1) - - ToolTip.text: qsTr("Add a new state.") - ToolTip.visible: addState.containsMouse - ToolTip.delay: 1000 - - Rectangle { // inner rect - width: parent.width - 30 - height: parent.height - 30 - anchors.centerIn: parent - color: StudioTheme.Values.themeStateBackground - } - - Text { - text: "+" - anchors.centerIn: parent - anchors.verticalCenterOffset: -(5 + (font.pixelSize - 35) / 9) - font.pixelSize: parent.height * .5 - color: Qt.lighter(StudioTheme.Values.themeControlBackgroundInteraction, addState.containsMouse ? 1.5 : 1) - } - - MouseArea { - id: addState - hoverEnabled: true - anchors.fill: parent - onClicked: root.createNewState() - } - } - } - } - - ScrollBar.horizontal: HorizontalScrollBar {} - } -} diff --git a/share/qtcreator/qmldesigner/statesEditorQmlSources/images/checkers.png b/share/qtcreator/qmldesigner/statesEditorQmlSources/images/checkers.png deleted file mode 100644 index 72cb9f03506..00000000000 Binary files a/share/qtcreator/qmldesigner/statesEditorQmlSources/images/checkers.png and /dev/null differ diff --git a/share/qtcreator/qmldesigner/newstateseditor/Main.qml b/share/qtcreator/qmldesigner/stateseditor/Main.qml similarity index 92% rename from share/qtcreator/qmldesigner/newstateseditor/Main.qml rename to share/qtcreator/qmldesigner/stateseditor/Main.qml index 4cd85bb1ad3..13f26884bcf 100644 --- a/share/qtcreator/qmldesigner/newstateseditor/Main.qml +++ b/share/qtcreator/qmldesigner/stateseditor/Main.qml @@ -29,6 +29,7 @@ import StatesEditor import HelperWidgets 2.0 as HelperWidgets import StudioControls 1.0 as StudioControls import StudioTheme as StudioTheme +import StatesEditorBackend Rectangle { id: root @@ -221,20 +222,20 @@ Rectangle { // These function assume that the order of the states is as follows: // State A, State B (extends State A), ... so the extended state always comes first function isInRange(i) { - return i >= 0 && i < statesEditorModel.count() + return i >= 0 && i < StatesEditorBackend.statesEditorModel.count() } function nextStateHasExtend(i) { let next = i + 1 - return root.isInRange(next) ? statesEditorModel.get(next).hasExtend : false + return root.isInRange(next) ? StatesEditorBackend.statesEditorModel.get(next).hasExtend : false } function previousStateHasExtend(i) { let prev = i - 1 - return root.isInRange(prev) ? statesEditorModel.get(prev).hasExtend : false + return root.isInRange(prev) ? StatesEditorBackend.statesEditorModel.get(prev).hasExtend : false } - property bool showExtendGroups: statesEditorModel.hasExtend + property bool showExtendGroups: StatesEditorBackend.statesEditorModel.hasExtend onShowExtendGroupsChanged: root.responsiveResize(root.width, root.height) @@ -263,7 +264,7 @@ Rectangle { property int menuOpen: 0 Connections { - target: statesEditorModel + target: StatesEditorBackend.statesEditorModel function onModelReset() { root.menuOpen = 0 editDialog.close() @@ -343,7 +344,7 @@ Rectangle { } onAccepted: { - let renamed = statesEditorModel.renameActiveStateGroup(editTextField.text) + let renamed = StatesEditorBackend.statesEditorModel.renameActiveStateGroup(editTextField.text) if (renamed) editDialog.close() } @@ -351,8 +352,8 @@ Rectangle { property string previousString onAboutToShow: { - editTextField.text = statesEditorModel.activeStateGroup - editDialog.previousString = statesEditorModel.activeStateGroup + editTextField.text = StatesEditorBackend.statesEditorModel.activeStateGroup + editDialog.previousString = StatesEditorBackend.statesEditorModel.activeStateGroup let btn = editDialog.standardButton(Dialog.Apply) btn.enabled = false @@ -406,8 +407,8 @@ Rectangle { style: StudioTheme.Values.viewBarControlStyle id: stateGroupComboBox actionIndicatorVisible: false - model: statesEditorModel.stateGroups - currentIndex: statesEditorModel.activeStateGroupIndex + model: StatesEditorBackend.statesEditorModel.stateGroups + currentIndex: StatesEditorBackend.statesEditorModel.activeStateGroupIndex anchors.verticalCenter: parent.verticalCenter width: stateGroupLabel.visible ? StudioTheme.Values.defaultControlWidth : root.width - 2 * root.padding @@ -434,18 +435,18 @@ Rectangle { // currentIndex needs special treatment, because if model is changed, it will be // reset regardless of binding. Connections { - target: statesEditorModel + target: StatesEditorBackend.statesEditorModel function onActiveStateGroupIndexChanged() { - stateGroupComboBox.currentIndex = statesEditorModel.activeStateGroupIndex + stateGroupComboBox.currentIndex = StatesEditorBackend.statesEditorModel.activeStateGroupIndex } } onModelChanged: { - stateGroupComboBox.currentIndex = statesEditorModel.activeStateGroupIndex + stateGroupComboBox.currentIndex = StatesEditorBackend.statesEditorModel.activeStateGroupIndex } onCompressedActivated: function (index, reason) { - statesEditorModel.activeStateGroupIndex = index + StatesEditorBackend.statesEditorModel.activeStateGroupIndex = index root.responsiveResize(root.width, root.height) } } @@ -463,16 +464,16 @@ Rectangle { buttonIcon: StudioTheme.Constants.add_medium anchors.verticalCenter: parent.verticalCenter tooltip: qsTr("Create State Group") - onClicked: statesEditorModel.addStateGroup("stateGroup") + onClicked: StatesEditorBackend.statesEditorModel.addStateGroup("stateGroup") } HelperWidgets.AbstractButton { style: StudioTheme.Values.viewBarButtonStyle buttonIcon: StudioTheme.Constants.remove_medium anchors.verticalCenter: parent.verticalCenter - enabled: statesEditorModel.activeStateGroupIndex !== 0 + enabled: StatesEditorBackend.statesEditorModel.activeStateGroupIndex !== 0 tooltip: qsTr("Remove State Group") - onClicked: statesEditorModel.removeStateGroup() + onClicked: StatesEditorBackend.statesEditorModel.removeStateGroup() } HelperWidgets.AbstractButton { @@ -480,7 +481,7 @@ Rectangle { style: StudioTheme.Values.viewBarButtonStyle buttonIcon: StudioTheme.Constants.edit_medium anchors.verticalCenter: parent.verticalCenter - enabled: statesEditorModel.activeStateGroupIndex !== 0 + enabled: StatesEditorBackend.statesEditorModel.activeStateGroupIndex !== 0 checked: editDialog.visible tooltip: qsTr("Rename State Group") onClicked: { @@ -550,13 +551,13 @@ Rectangle { width: Constants.thumbnailSize height: Constants.thumbnailSize baseState: true - defaultChecked: !statesEditorModel.baseState.modelHasDefaultState // TODO Make this one a model property + defaultChecked: !StatesEditorBackend.statesEditorModel.baseState.modelHasDefaultState // TODO Make this one a model property isChecked: root.currentStateInternalId === 0 - thumbnailImageSource: statesEditorModel.baseState.stateImageSource ?? "" // TODO Get rid of the QVariantMap + thumbnailImageSource: StatesEditorBackend.statesEditorModel.baseState.stateImageSource ?? "" // TODO Get rid of the QVariantMap isTiny: root.tinyMode onFocusSignal: root.currentStateInternalId = 0 - onDefaultClicked: statesEditorModel.resetDefaultState() + onDefaultClicked: StatesEditorBackend.statesEditorModel.resetDefaultState } } @@ -649,7 +650,7 @@ Rectangle { property int grabIndex: -1 - model: statesEditorModel + model: StatesEditorBackend.statesEditorModel onItemAdded: root.responsiveResize(root.width, root.height) onItemRemoved: root.responsiveResize(root.width, root.height) @@ -691,7 +692,7 @@ Rectangle { return } - statesEditorModel.move(dragSource.visualIndex, + StatesEditorBackend.statesEditorModel.move(dragSource.visualIndex, stateThumbnail.visualIndex) } @@ -709,7 +710,7 @@ Rectangle { if (statesRepeater.grabIndex === dropSource.visualIndex) return - statesEditorModel.drop(statesRepeater.grabIndex, + StatesEditorBackend.statesEditorModel.drop(statesRepeater.grabIndex, dropSource.visualIndex) statesRepeater.grabIndex = -1 } @@ -807,7 +808,7 @@ Rectangle { hasExtend: delegateRoot.hasExtend extendString: delegateRoot.extendString - extendedState: statesEditorModel.extendedStates.includes( + extendedState: StatesEditorBackend.statesEditorModel.extendedStates.includes( delegateRoot.stateName) hasWhenCondition: delegateRoot.hasWhenCondition @@ -840,19 +841,14 @@ Rectangle { isChecked: root.currentStateInternalId === delegateRoot.internalNodeId onFocusSignal: root.currentStateInternalId = delegateRoot.internalNodeId - onDefaultClicked: statesEditorModel.setStateAsDefault( + onDefaultClicked: StatesEditorBackend.statesEditorModel.setStateAsDefault( delegateRoot.internalNodeId) onClone: root.cloneState(delegateRoot.internalNodeId) onExtend: root.extendState(delegateRoot.internalNodeId) - onRemove: { - if (delegateRoot.isDefault) - statesEditorModel.resetDefaultState() + onRemove: root.deleteState(delegateRoot.internalNodeId) - root.deleteState(delegateRoot.internalNodeId) - } - - onStateNameFinished: statesEditorModel.renameState( + onStateNameFinished: StatesEditorBackend.statesEditorModel.renameState( delegateRoot.internalNodeId, stateThumbnail.stateName) } @@ -865,7 +861,7 @@ Rectangle { Item { id: addWrapper - visible: canAddNewStates + visible: StatesEditorBackend.statesEditorModel.canAddNewStates Canvas { id: addCanvas diff --git a/share/qtcreator/qmldesigner/newstateseditor/MenuButton.qml b/share/qtcreator/qmldesigner/stateseditor/MenuButton.qml similarity index 100% rename from share/qtcreator/qmldesigner/newstateseditor/MenuButton.qml rename to share/qtcreator/qmldesigner/stateseditor/MenuButton.qml diff --git a/share/qtcreator/qmldesigner/newstateseditor/StateMenu.qml b/share/qtcreator/qmldesigner/stateseditor/StateMenu.qml similarity index 100% rename from share/qtcreator/qmldesigner/newstateseditor/StateMenu.qml rename to share/qtcreator/qmldesigner/stateseditor/StateMenu.qml diff --git a/share/qtcreator/qmldesigner/newstateseditor/StateScrollBar.qml b/share/qtcreator/qmldesigner/stateseditor/StateScrollBar.qml similarity index 100% rename from share/qtcreator/qmldesigner/newstateseditor/StateScrollBar.qml rename to share/qtcreator/qmldesigner/stateseditor/StateScrollBar.qml diff --git a/share/qtcreator/qmldesigner/newstateseditor/StateThumbnail.qml b/share/qtcreator/qmldesigner/stateseditor/StateThumbnail.qml similarity index 97% rename from share/qtcreator/qmldesigner/newstateseditor/StateThumbnail.qml rename to share/qtcreator/qmldesigner/stateseditor/StateThumbnail.qml index e54732c8d09..1d8147d0425 100644 --- a/share/qtcreator/qmldesigner/newstateseditor/StateThumbnail.qml +++ b/share/qtcreator/qmldesigner/stateseditor/StateThumbnail.qml @@ -28,6 +28,7 @@ import QtQuick.Controls import HelperWidgets 2.0 as HelperWidgets import StudioControls 1.0 as StudioControls import StudioTheme 1.0 as StudioTheme +import StatesEditorBackend Item { id: root @@ -77,7 +78,7 @@ Item { property alias dragActive: dragHandler.active function checkAnnotation() { - return statesEditorModel.hasAnnotation(root.internalNodeId) + return StatesEditorBackend.statesEditorModel.hasAnnotation(root.internalNodeId) } function setPropertyChangesVisible(value) { @@ -256,7 +257,7 @@ Item { PropertyChangesModel { id: propertyChangesModel - modelNodeBackendProperty: statesEditorModel.stateModelNode(root.internalNodeId) + modelNodeBackendProperty: StatesEditorBackend.statesEditorModel.stateModelNode(root.internalNodeId) } Text { @@ -631,14 +632,14 @@ Item { return if ( bindingEditor.newWhenCondition !== "") - statesEditorModel.setWhenCondition(root.internalNodeId, + StatesEditorBackend.statesEditorModel.setWhenCondition(root.internalNodeId, bindingEditor.newWhenCondition) else - statesEditorModel.resetWhenCondition(root.internalNodeId) + StatesEditorBackend.statesEditorModel.resetWhenCondition(root.internalNodeId) } } - stateModelNodeProperty: statesEditorModel.stateModelNode(root.internalNodeId) + stateModelNodeProperty: StatesEditorBackend.statesEditorModel.stateModelNode(root.internalNodeId) stateNameProperty: root.stateName onRejected: bindingEditor.hideWidget() @@ -691,9 +692,9 @@ Item { whenCondition.previousCondition = whenCondition.text if (whenCondition.text !== "") - statesEditorModel.setWhenCondition(root.internalNodeId, root.whenCondition) + StatesEditorBackend.statesEditorModel.setWhenCondition(root.internalNodeId, root.whenCondition) else - statesEditorModel.resetWhenCondition(root.internalNodeId) + StatesEditorBackend.statesEditorModel.resetWhenCondition(root.internalNodeId) } @@ -736,11 +737,11 @@ Item { onToggle: root.setPropertyChangesVisible(!root.propertyChangesVisible) onResetWhenCondition: statesEditorModel.resetWhenCondition(root.internalNodeId) onEditAnnotation: { - statesEditorModel.setAnnotation(root.internalNodeId) + StatesEditorBackend.statesEditorModel.setAnnotation(root.internalNodeId) stateMenu.hasAnnotation = root.checkAnnotation() } onRemoveAnnotation: { - statesEditorModel.removeAnnotation(root.internalNodeId) + StatesEditorBackend.statesEditorModel.removeAnnotation(root.internalNodeId) stateMenu.hasAnnotation = root.checkAnnotation() } diff --git a/share/qtcreator/qmldesigner/newstateseditor/images/checkers.png b/share/qtcreator/qmldesigner/stateseditor/images/checkers.png similarity index 100% rename from share/qtcreator/qmldesigner/newstateseditor/images/checkers.png rename to share/qtcreator/qmldesigner/stateseditor/images/checkers.png diff --git a/share/qtcreator/qmldesigner/newstateseditor/imports/StatesEditor/Constants.qml b/share/qtcreator/qmldesigner/stateseditor/imports/StatesEditor/Constants.qml similarity index 100% rename from share/qtcreator/qmldesigner/newstateseditor/imports/StatesEditor/Constants.qml rename to share/qtcreator/qmldesigner/stateseditor/imports/StatesEditor/Constants.qml diff --git a/share/qtcreator/qmldesigner/newstateseditor/imports/StatesEditor/qmldir b/share/qtcreator/qmldesigner/stateseditor/imports/StatesEditor/qmldir similarity index 100% rename from share/qtcreator/qmldesigner/newstateseditor/imports/StatesEditor/qmldir rename to share/qtcreator/qmldesigner/stateseditor/imports/StatesEditor/qmldir diff --git a/share/qtcreator/qmldesigner/studio_templates/projects/app_mcu.qmlproject b/share/qtcreator/qmldesigner/studio_templates/projects/app_mcu.qmlproject index 55204175faa..80bb0c5743e 100644 --- a/share/qtcreator/qmldesigner/studio_templates/projects/app_mcu.qmlproject +++ b/share/qtcreator/qmldesigner/studio_templates/projects/app_mcu.qmlproject @@ -4,6 +4,7 @@ import QmlProject 1.3 Project { mainFile: "%{MainQmlFileName}" + QDS.mainUiFile: "Screen01.ui.qml" /* Include .qml, .js, and image files from current directory and subdirectories */ QmlFiles { @@ -47,18 +48,18 @@ Project { /* Following entries are for Qt Design Studio compatibility: */ - Environment { + QDS.Environment { QT_QUICK_CONTROLS_CONF: "qtquickcontrols2.conf" } - qtForMCUs: true - qt6Project: true + QDS.qtForMCUs: true + QDS.qt6Project: true - qdsVersion: "4.1" - quickVersion: "6.5" + QDS.qdsVersion: "4.2" + QDS.quickVersion: "6.5" /* List of plugin directories passed to QML runtime */ importPaths: [ "imports" ] - targetDirectory: "/opt/%{ProjectName}" + QDS.targetDirectory: "/opt/%{ProjectName}" } diff --git a/share/qtcreator/qmldesigner/studio_templates/projects/application-3d/wizard.json b/share/qtcreator/qmldesigner/studio_templates/projects/application-3d/wizard.json index 3e26a5f0f20..0bc60900074 100644 --- a/share/qtcreator/qmldesigner/studio_templates/projects/application-3d/wizard.json +++ b/share/qtcreator/qmldesigner/studio_templates/projects/application-3d/wizard.json @@ -241,14 +241,6 @@ "index": 4, "items": [ - { - "trKey": "Qt 5", - "value": - "({ - 'TargetQuickVersion': '2.15', - 'TargetQuick3DVersion': '1.15' - })" - }, { "trKey": "Qt 6.2", "value": diff --git a/share/qtcreator/qmldesigner/studio_templates/projects/application-mcu/Constants.qml.tpl b/share/qtcreator/qmldesigner/studio_templates/projects/application-mcu/Constants.qml.tpl index ad50e39e9ac..c6bbb001993 100644 --- a/share/qtcreator/qmldesigner/studio_templates/projects/application-mcu/Constants.qml.tpl +++ b/share/qtcreator/qmldesigner/studio_templates/projects/application-mcu/Constants.qml.tpl @@ -1,5 +1,5 @@ pragma Singleton -import QtQuick 6.5 +import QtQuick QtObject { readonly property int width: %{ScreenWidth} diff --git a/share/qtcreator/qmldesigner/studio_templates/projects/application-mcu/Screen01.ui.qml.tpl b/share/qtcreator/qmldesigner/studio_templates/projects/application-mcu/Screen01.ui.qml.tpl index 4a70ce692b6..4a16e2c6b1c 100644 --- a/share/qtcreator/qmldesigner/studio_templates/projects/application-mcu/Screen01.ui.qml.tpl +++ b/share/qtcreator/qmldesigner/studio_templates/projects/application-mcu/Screen01.ui.qml.tpl @@ -5,8 +5,8 @@ this file manually, you might introduce QML code that is not supported by Qt Des Check out https://doc.qt.io/qtcreator/creator-quick-ui-forms.html for details on .ui.qml files. */ -import QtQuick 6.5 -import Constants 1.0 +import QtQuick +import Constants Rectangle { width: Constants.width diff --git a/share/qtcreator/qmldesigner/studio_templates/projects/application-mcu/main.qml.tpl b/share/qtcreator/qmldesigner/studio_templates/projects/application-mcu/main.qml.tpl index e25113c67f9..cd6a735a099 100644 --- a/share/qtcreator/qmldesigner/studio_templates/projects/application-mcu/main.qml.tpl +++ b/share/qtcreator/qmldesigner/studio_templates/projects/application-mcu/main.qml.tpl @@ -1,5 +1,5 @@ -import QtQuick 6.5 -import Constants 1.0 +import QtQuick +import Constants Item { width: Constants.width diff --git a/share/qtcreator/qmldesigner/studio_templates/projects/application/wizard.json b/share/qtcreator/qmldesigner/studio_templates/projects/application/wizard.json index ea5f9ef671b..e1a25e23fb5 100644 --- a/share/qtcreator/qmldesigner/studio_templates/projects/application/wizard.json +++ b/share/qtcreator/qmldesigner/studio_templates/projects/application/wizard.json @@ -296,23 +296,28 @@ }, { "source": "../common/CMakeLists.main.txt.tpl", - "target": "%{ProjectDirectory}/CMakeLists.txt" + "target": "%{ProjectDirectory}/CMakeLists.txt", + "condition": "%{IsQt6Project}" }, { "source": "../common/qmlmodules.tpl", - "target": "%{ProjectDirectory}/qmlmodules" + "target": "%{ProjectDirectory}/qmlmodules", + "condition": "%{IsQt6Project}" }, { "source": "../common/qmlcomponents.tpl", - "target": "%{ProjectDirectory}/qmlcomponents" + "target": "%{ProjectDirectory}/qmlcomponents", + "condition": "%{IsQt6Project}" }, { "source": "../common/insight.tpl", - "target": "%{ProjectDirectory}/insight" + "target": "%{ProjectDirectory}/insight", + "condition": "%{IsQt6Project}" }, { "source": "../common/main.qml", - "target": "%{ProjectDirectory}/main.qml" + "target": "%{ProjectDirectory}/main.qml", + "condition": "%{IsQt6Project}" }, { "source": "../common/qtquickcontrols2.conf.tpl", @@ -320,23 +325,28 @@ }, { "source": "../common/main.cpp.tpl", - "target": "%{ProjectDirectory}/src/main.cpp" + "target": "%{ProjectDirectory}/src/main.cpp", + "condition": "%{IsQt6Project}" }, { "source": "../common/app_environment.h.tpl", - "target": "%{ProjectDirectory}/src/app_environment.h" + "target": "%{ProjectDirectory}/src/app_environment.h", + "condition": "%{IsQt6Project}" }, { "source": "../common/import_qml_plugins.h.tpl", - "target": "%{ProjectDirectory}/src/import_qml_plugins.h" + "target": "%{ProjectDirectory}/src/import_qml_plugins.h", + "condition": "%{IsQt6Project}" }, { "source": "../common/import_qml_components_plugins.h.tpl", - "target": "%{ProjectDirectory}/src/import_qml_components_plugins.h" + "target": "%{ProjectDirectory}/src/import_qml_components_plugins.h", + "condition": "%{IsQt6Project}" }, { "source": "../common/CMakeLists.content.txt.tpl", - "target": "%{ProjectDirectory}/content/CMakeLists.txt" + "target": "%{ProjectDirectory}/content/CMakeLists.txt", + "condition": "%{IsQt6Project}" }, { "source": "../common/App.qml.tpl", @@ -356,11 +366,13 @@ }, { "source": "../common/CMakeLists.imports.txt.tpl", - "target": "%{ProjectDirectory}/imports/CMakeLists.txt" + "target": "%{ProjectDirectory}/imports/CMakeLists.txt", + "condition": "%{IsQt6Project}" }, { "source": "../shared-plugin/name/CMakeLists.importmodule.txt.tpl", - "target": "%{ProjectDirectory}/imports/%{ImportModuleName}/CMakeLists.txt" + "target": "%{ProjectDirectory}/imports/%{ImportModuleName}/CMakeLists.txt", + "condition": "%{IsQt6Project}" }, { "source": "../shared-plugin/name/importmodule.qmldir.tpl", diff --git a/share/qtcreator/qmldesigner/studio_templates/projects/common/CMakeLists.content.txt.tpl b/share/qtcreator/qmldesigner/studio_templates/projects/common/CMakeLists.content.txt.tpl index a95da583f37..a5a4360e3f2 100644 --- a/share/qtcreator/qmldesigner/studio_templates/projects/common/CMakeLists.content.txt.tpl +++ b/share/qtcreator/qmldesigner/studio_templates/projects/common/CMakeLists.content.txt.tpl @@ -5,6 +5,7 @@ qt_add_library(content STATIC) qt6_add_qml_module(content URI "content" VERSION 1.0 + RESOURCE_PREFIX "/qt/qml" QML_FILES App.qml %{UIClassFileName} diff --git a/share/qtcreator/qmldesigner/studio_templates/projects/common/app.qmlproject.tpl b/share/qtcreator/qmldesigner/studio_templates/projects/common/app.qmlproject.tpl index 9cfbab9228b..0b96ccf3ba3 100644 --- a/share/qtcreator/qmldesigner/studio_templates/projects/common/app.qmlproject.tpl +++ b/share/qtcreator/qmldesigner/studio_templates/projects/common/app.qmlproject.tpl @@ -105,7 +105,7 @@ Project { /* Required for deployment */ targetDirectory: "/opt/%{ProjectName}" - qdsVersion: "4.1" + qdsVersion: "4.2" quickVersion: "%{QtQuickVersion}" diff --git a/share/qtcreator/qmldesigner/studio_templates/projects/common/main.cpp.tpl b/share/qtcreator/qmldesigner/studio_templates/projects/common/main.cpp.tpl index 53c355b6b8a..915d08462e2 100644 --- a/share/qtcreator/qmldesigner/studio_templates/projects/common/main.cpp.tpl +++ b/share/qtcreator/qmldesigner/studio_templates/projects/common/main.cpp.tpl @@ -15,7 +15,7 @@ int main(int argc, char *argv[]) QGuiApplication app(argc, argv); QQmlApplicationEngine engine; - const QUrl url(u"qrc:Main/main.qml"_qs); + const QUrl url(u"qrc:/qt/qml/Main/main.qml"_qs); QObject::connect( &engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) { diff --git a/share/qtcreator/qmldesigner/studio_templates/projects/common/qmlmodules.tpl b/share/qtcreator/qmldesigner/studio_templates/projects/common/qmlmodules.tpl index fa3069a770a..5a22661b5a1 100644 --- a/share/qtcreator/qmldesigner/studio_templates/projects/common/qmlmodules.tpl +++ b/share/qtcreator/qmldesigner/studio_templates/projects/common/qmlmodules.tpl @@ -4,6 +4,7 @@ qt6_add_qml_module(${CMAKE_PROJECT_NAME} URI "Main" VERSION 1.0 + RESOURCE_PREFIX "/qt/qml" NO_PLUGIN QML_FILES main.qml ) diff --git a/share/qtcreator/qmldesigner/studio_templates/projects/mobile-stack/CMakeLists.content.txt.tpl b/share/qtcreator/qmldesigner/studio_templates/projects/mobile-stack/CMakeLists.content.txt.tpl index 255afffa3ea..5601c89997d 100644 --- a/share/qtcreator/qmldesigner/studio_templates/projects/mobile-stack/CMakeLists.content.txt.tpl +++ b/share/qtcreator/qmldesigner/studio_templates/projects/mobile-stack/CMakeLists.content.txt.tpl @@ -5,6 +5,7 @@ qt_add_library(content STATIC) qt6_add_qml_module(content URI "content" VERSION 1.0 + RESOURCE_PREFIX "/qt/qml" QML_FILES App.qml Screen01.ui.qml diff --git a/share/qtcreator/qmldesigner/studio_templates/projects/mobile-swipe/CMakeLists.content.txt.tpl b/share/qtcreator/qmldesigner/studio_templates/projects/mobile-swipe/CMakeLists.content.txt.tpl index 255afffa3ea..5601c89997d 100644 --- a/share/qtcreator/qmldesigner/studio_templates/projects/mobile-swipe/CMakeLists.content.txt.tpl +++ b/share/qtcreator/qmldesigner/studio_templates/projects/mobile-swipe/CMakeLists.content.txt.tpl @@ -5,6 +5,7 @@ qt_add_library(content STATIC) qt6_add_qml_module(content URI "content" VERSION 1.0 + RESOURCE_PREFIX "/qt/qml" QML_FILES App.qml Screen01.ui.qml diff --git a/share/qtcreator/qmldesigner/studio_templates/projects/shared-plugin/name/CMakeLists.importmodule.txt.tpl b/share/qtcreator/qmldesigner/studio_templates/projects/shared-plugin/name/CMakeLists.importmodule.txt.tpl index df10020cb23..517b91355a7 100644 --- a/share/qtcreator/qmldesigner/studio_templates/projects/shared-plugin/name/CMakeLists.importmodule.txt.tpl +++ b/share/qtcreator/qmldesigner/studio_templates/projects/shared-plugin/name/CMakeLists.importmodule.txt.tpl @@ -8,11 +8,12 @@ set_source_files_properties(Constants.qml ) qt6_add_qml_module(%{ImportModuleName} - URI "%{ImportModuleName}" - VERSION 1.0 - QML_FILES - Constants.qml - DirectoryFontLoader.qml - EventListModel.qml - EventListSimulator.qml + URI "%{ImportModuleName}" + VERSION 1.0 + RESOURCE_PREFIX "/qt/qml" + QML_FILES + Constants.qml + DirectoryFontLoader.qml + EventListModel.qml + EventListSimulator.qml ) diff --git a/tests/unit/unittest/3rdparty/googletest b/src/libs/3rdparty/googletest similarity index 100% rename from tests/unit/unittest/3rdparty/googletest rename to src/libs/3rdparty/googletest diff --git a/src/libs/3rdparty/sqlite/config.h b/src/libs/3rdparty/sqlite/config.h index 3672f4c5ddf..f0e73be3009 100644 --- a/src/libs/3rdparty/sqlite/config.h +++ b/src/libs/3rdparty/sqlite/config.h @@ -27,10 +27,6 @@ #include -#if defined(SQLITE_STATIC_LIBRARY) || defined(SQLITEC_STATIC_LIBRARY) -#include "sqlite_static_config.h" -#endif - #if __has_include() #include #endif diff --git a/src/libs/CMakeLists.txt b/src/libs/CMakeLists.txt index de2d2b01ef3..73a554bae8b 100644 --- a/src/libs/CMakeLists.txt +++ b/src/libs/CMakeLists.txt @@ -22,6 +22,10 @@ if (WITH_QMLDESIGNER) add_subdirectory(qmlpuppetcommunication) endif() +if (WITH_TESTS) + add_subdirectory(googletest) +endif() + if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/qlitehtml/src/CMakeLists.txt) option(BUILD_LIBRARY_QLITEHTML "Build library qlitehtml." ${BUILD_LIBRARIES_BY_DEFAULT}) set(QLITEHTML_VERSION_COMPAT ${IDE_VERSION_COMPAT} CACHE STRING "") diff --git a/src/libs/googletest/CMakeLists.txt b/src/libs/googletest/CMakeLists.txt new file mode 100644 index 00000000000..50e82e1edf6 --- /dev/null +++ b/src/libs/googletest/CMakeLists.txt @@ -0,0 +1,27 @@ +set(GOOGLETEST_DIR ${CMAKE_CURRENT_LIST_DIR}/../3rdparty/googletest) + +if(EXISTS "${GOOGLETEST_DIR}/googletest") + set(GOOGLETEST_SUBMODULE_IS_CHECKED_OUT YES) +else() + set(GOOGLETEST_SUBMODULE_IS_CHECKED_OUT NO) +endif() + +add_qtc_library(Googletest STATIC + CONDITION GOOGLETEST_SUBMODULE_IS_CHECKED_OUT + DEPENDS + Threads::Threads + PUBLIC_INCLUDES + "${GOOGLETEST_DIR}/googletest/include" + "${GOOGLETEST_DIR}/googlemock/include" + INCLUDES + "${GOOGLETEST_DIR}/googletest" + "${GOOGLETEST_DIR}/googlemock" + PROPERTIES + AUTOMOC OFF AUTOUIC OFF QT_COMPILE_OPTIONS_DISABLE_WARNINGS ON + POSITION_INDEPENDENT_CODE ON + URL "https://github.com/google/googletest" + DESCRIPTION "Google Testing and Mocking Framework" + SOURCES + "${GOOGLETEST_DIR}/googletest/src/gtest-all.cc" + "${GOOGLETEST_DIR}/googlemock/src/gmock-all.cc" +) diff --git a/src/libs/qmljs/qmljsreformatter.cpp b/src/libs/qmljs/qmljsreformatter.cpp index 232c0361a1a..d2891451e95 100644 --- a/src/libs/qmljs/qmljsreformatter.cpp +++ b/src/libs/qmljs/qmljsreformatter.cpp @@ -590,14 +590,35 @@ protected: return true; } - bool visit(UiObjectDefinition *ast) override + bool visit(UiAnnotation *ast) override { + out("@"); accept(ast->qualifiedTypeNameId); out(" "); accept(ast->initializer); return false; } + bool visit(UiAnnotationList *ast) override + { + for (UiAnnotationList *it = ast; it; it = it->next) { + accept(it->annotation); + newLine(); + } + return false; + } + + bool visit(UiObjectDefinition *ast) override + { + accept(ast->annotations); + + accept(ast->qualifiedTypeNameId); + out(" "); + accept(ast->initializer); + + return false; + } + bool visit(UiObjectInitializer *ast) override { out(ast->lbraceToken); @@ -687,9 +708,12 @@ protected: bool visit(UiScriptBinding *ast) override { + accept(ast->annotations); + accept(ast->qualifiedId); out(": ", ast->colonToken); accept(ast->statement); + return false; } @@ -1290,6 +1314,7 @@ protected: { for (UiObjectMemberList *it = ast; it; it = it->next) { accept(it->member); + if (it->next) newLine(); } diff --git a/src/libs/sqlite/CMakeLists.txt b/src/libs/sqlite/CMakeLists.txt index 4c7cd774c60..aa33171bab1 100644 --- a/src/libs/sqlite/CMakeLists.txt +++ b/src/libs/sqlite/CMakeLists.txt @@ -1,8 +1,7 @@ -add_qtc_library(SqliteC OBJECT +add_qtc_library(SqliteInternal OBJECT PROPERTIES AUTOMOC OFF AUTOUIC OFF QT_COMPILE_OPTIONS_DISABLE_WARNINGS ON DEFINES SQLITE_CORE SQLITE_CUSTOM_INCLUDE=config.h $<$:SQLITE_DEBUG> - PROPERTIES COMPILE_OPTIONS $,/FIconfig.h,-includeconfig.h> - PUBLIC_INCLUDES + INCLUDES ../3rdparty/sqlite SOURCES ../3rdparty/sqlite @@ -11,12 +10,26 @@ add_qtc_library(SqliteC OBJECT ../3rdparty/sqlite/sqlite3ext.h ../3rdparty/sqlite/carray.c ../3rdparty/sqlite/config.h + ../3rdparty/sqlite/sqlite_static_config.h ../3rdparty/sqlite/sqlite.h ) +extend_qtc_library(SqliteInternal + CONDITION QTC_STATIC_BUILD + PROPERTIES COMPILE_OPTIONS $,/FIsqlite_static_config.h,-includesqlite_static_config.h> +) + +if (APPLE) + extend_qtc_library(SqliteInternal DEFINES _BSD_SOURCE) +elseif (UNIX) + extend_qtc_library(SqliteInternal DEFINES _POSIX_C_SOURCE=200809L _GNU_SOURCE _DEFAULT_SOURCE) +endif() + add_qtc_library(Sqlite PROPERTIES AUTOMOC OFF AUTOUIC OFF - DEPENDS Qt::Core Threads::Threads ${CMAKE_DL_LIBS} SqliteC + DEPENDS Qt::Core Threads::Threads ${CMAKE_DL_LIBS} SqliteInternal + INCLUDES + ../3rdparty/sqlite PUBLIC_INCLUDES "${CMAKE_CURRENT_LIST_DIR}" DEFINES SQLITE_CUSTOM_INCLUDE=config.h $<$:SQLITE_REVERSE> @@ -53,8 +66,7 @@ add_qtc_library(Sqlite sqliteids.h ) -if (APPLE) - extend_qtc_library(SqliteC DEFINES _BSD_SOURCE) -elseif (UNIX) - extend_qtc_library(SqliteC DEFINES _POSIX_C_SOURCE=200809L _GNU_SOURCE _DEFAULT_SOURCE) -endif() +extend_qtc_library(Sqlite + CONDITION QTC_STATIC_BUILD + PROPERTIES COMPILE_OPTIONS $,/FIsqlite_static_config.h,-includesqlite_static_config.h> +) diff --git a/src/libs/sqlite/sqlitebasestatement.cpp b/src/libs/sqlite/sqlitebasestatement.cpp index 91b417bea12..d9d677c3959 100644 --- a/src/libs/sqlite/sqlitebasestatement.cpp +++ b/src/libs/sqlite/sqlitebasestatement.cpp @@ -274,6 +274,9 @@ void BaseStatement::bind(int index, ValueView value) void BaseStatement::prepare(Utils::SmallStringView sqlStatement) { + if (!m_database.isLocked()) + throw DatabaseIsNotLocked{}; + int resultCode; do { diff --git a/src/libs/sqlite/sqlitebasestatement.h b/src/libs/sqlite/sqlitebasestatement.h index 1178b97f3a1..54d08260b7c 100644 --- a/src/libs/sqlite/sqlitebasestatement.h +++ b/src/libs/sqlite/sqlitebasestatement.h @@ -49,6 +49,7 @@ public: BaseStatement(const BaseStatement &) = delete; BaseStatement &operator=(const BaseStatement &) = delete; + BaseStatement(BaseStatement &&) = default; bool next() const; void step() const; @@ -146,6 +147,7 @@ class StatementImplementation : public BaseStatement public: using BaseStatement::BaseStatement; + StatementImplementation(StatementImplementation &&) = default; void execute() { @@ -496,16 +498,30 @@ private: return createValue(std::make_integer_sequence{}); } + template + CallbackControl invokeCallable(Callable &&callable, Arguments &&...arguments) + { + if constexpr (std::is_void_v>) { + std::invoke(std::forward(callable), std::forward(arguments)...); + return CallbackControl::Continue; + } else { + return std::invoke(std::forward(callable), + std::forward(arguments)...); + } + } + template CallbackControl callCallable(Callable &&callable, std::integer_sequence) { - return std::invoke(callable, ValueGetter(*this, ColumnIndices)...); + return invokeCallable(std::forward(callable), + ValueGetter(*this, ColumnIndices)...); } template CallbackControl callCallable(Callable &&callable) { - return callCallable(callable, std::make_integer_sequence{}); + return callCallable(std::forward(callable), + std::make_integer_sequence{}); } void setMaximumResultCount(std::size_t count) diff --git a/src/libs/utils/set_algorithm.h b/src/libs/utils/set_algorithm.h index a3e442f736d..f6d3f73fedf 100644 --- a/src/libs/utils/set_algorithm.h +++ b/src/libs/utils/set_algorithm.h @@ -60,8 +60,17 @@ bool set_intersection_compare( ++first1; } else { if (!comp(*first2, *first1)) { - if (call(*first1++, *first2)) - return true; + if constexpr (std::is_void_v>) { + call(*first1, *first2); + ++first1; + } else { + auto success = call(*first1, *first2); + ++first1; + if (success) + return true; + } } ++first2; } @@ -70,6 +79,52 @@ bool set_intersection_compare( return false; } +template +bool set_greedy_intersection_compare( + InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, Callable call, Compare comp) +{ + while (first1 != last1 && first2 != last2) { + if (comp(*first1, *first2)) { + ++first1; + } else { + if (!comp(*first2, *first1)) { + if constexpr (std::is_void_v>) { + call(*first1, *first2); + ++first1; + } else { + auto success = call(*first1, *first2); + ++first1; + if (success) + return true; + } + } else { + ++first2; + } + } + } + + return false; +} + +template +constexpr OutputIt set_greedy_intersection( + InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt result) +{ + while (first1 != last1 && first2 != last2) + if (*first1 < *first2) + ++first1; + else if (*first2 < *first1) + ++first2; + else { + *result = *first1; + ++first1; + ++result; + } + return result; +} + template void set_greedy_difference( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, Callable call, Compare comp) diff --git a/src/libs/utils/smallstringview.h b/src/libs/utils/smallstringview.h index 82a8c503051..982192c7a44 100644 --- a/src/libs/utils/smallstringview.h +++ b/src/libs/utils/smallstringview.h @@ -12,6 +12,12 @@ #include #include +#if __cpp_lib_constexpr_string >= 201907L +#define constexpr_string constexpr +#else +#define constexpr_string +#endif + namespace Utils { template @@ -63,7 +69,7 @@ public: return SmallStringView(data() + position, length); } - constexpr20 operator std::string() const { return std::string(data(), size()); } + constexpr_string operator std::string() const { return std::string(data(), size()); } explicit operator QString() const { @@ -131,38 +137,6 @@ constexpr int compare(SmallStringView first, SmallStringView second) noexcept return first.compare(second); } -namespace Internal { -constexpr int reverse_memcmp(const char *first, const char *second, size_t n) -{ - const char *currentFirst = first + n - 1; - const char *currentSecond = second + n - 1; - - while (n > 0) { - // If the current characters differ, return an appropriately signed - // value; otherwise, keep searching backwards - int difference = *currentFirst - *currentSecond; - if (difference != 0) - return difference; - - --currentFirst; - --currentSecond; - --n; - } - - return 0; -} -} // namespace Internal - -constexpr int reverseCompare(SmallStringView first, SmallStringView second) noexcept -{ - int difference = Internal::reverse_memcmp(first.data(), second.data(), first.size()); - - if (difference == 0) - return int(first.size()) - int(second.size()); - - return difference; -} - } // namespace Utils constexpr Utils::SmallStringView operator""_sv(const char *const string, size_t size) diff --git a/src/plugins/insight/insightmodel.cpp b/src/plugins/insight/insightmodel.cpp index b80249d2124..2d2550aac55 100644 --- a/src/plugins/insight/insightmodel.cpp +++ b/src/plugins/insight/insightmodel.cpp @@ -227,7 +227,7 @@ InsightModel::InsightModel(InsightView *view, ExternalDependenciesInterface &ext int InsightModel::rowCount(const QModelIndex &) const { - return m_qtdsConfig.empty() ? 0 : m_qtdsConfig.size(); + return m_qtdsConfig.empty() ? 0 : static_cast(m_qtdsConfig.size()); } QVariant InsightModel::data(const QModelIndex &index, int role) const diff --git a/src/plugins/mcusupport/test/CMakeLists.txt b/src/plugins/mcusupport/test/CMakeLists.txt index 2df4faa891d..7d2a94c286e 100644 --- a/src/plugins/mcusupport/test/CMakeLists.txt +++ b/src/plugins/mcusupport/test/CMakeLists.txt @@ -1,13 +1,8 @@ -find_package(Googletest MODULE) - -if(TARGET Googletest) - message("Googletest target is present") - extend_qtc_plugin(McuSupport - CONDITION WITH_TESTS - DEPENDS Googletest - SOURCES - unittest.h unittest.cpp packagemock.h settingshandlermock.h - ) -else() - message("Googletest target is missing") -endif() +extend_qtc_plugin(McuSupport + CONDITION WITH_TESTS AND TARGET Googletest + DEPENDS Googletest + SOURCES + unittest.h unittest.cpp + packagemock.h + settingshandlermock.h +) diff --git a/src/plugins/projectexplorer/projectwindow.cpp b/src/plugins/projectexplorer/projectwindow.cpp index 6d51ada4106..a69ee4c855a 100644 --- a/src/plugins/projectexplorer/projectwindow.cpp +++ b/src/plugins/projectexplorer/projectwindow.cpp @@ -585,7 +585,7 @@ public: PanelsWidget::PanelVMargin, 0); QStringList list = Core::ICore::settings()->value("HideOptionCategories").toStringList(); - if (!list.contains("Kit")) { + if (!list.contains("Kits")) { innerLayout->addWidget(m_manageKits); innerLayout->addSpacerItem(new QSpacerItem(10, 30, QSizePolicy::Maximum, QSizePolicy::Maximum)); } diff --git a/src/plugins/python/pythonlanguageclient.cpp b/src/plugins/python/pythonlanguageclient.cpp index 9f347d8e486..eecfb35c97f 100644 --- a/src/plugins/python/pythonlanguageclient.cpp +++ b/src/plugins/python/pythonlanguageclient.cpp @@ -115,6 +115,7 @@ static PythonLanguageServerState checkPythonLanguageServer(const FilePath &pytho const FilePath &modulePath = getPylsModulePath(pythonLShelpCommand); Process pythonProcess; + pythonProcess.setTimeoutS(2); pythonProcess.setCommand(pythonLShelpCommand); pythonProcess.runBlocking(); if (pythonProcess.allOutput().contains("Python Language Server")) diff --git a/src/plugins/qmldesigner/.clang-format b/src/plugins/qmldesigner/.clang-format index e1dad0fa0c0..968dfdec7d1 100644 --- a/src/plugins/qmldesigner/.clang-format +++ b/src/plugins/qmldesigner/.clang-format @@ -6,10 +6,12 @@ AlignConsecutiveDeclarations: false AlignEscapedNewlines: DontAlign AlignOperands: true AlignTrailingComments: true +AllowAllArgumentsOnNextLine: true AllowAllParametersOfDeclarationOnNextLine: true AllowShortBlocksOnASingleLine: false AllowShortCaseLabelsOnASingleLine: false AllowShortFunctionsOnASingleLine: Inline +AllowShortLambdasOnASingleLine: All AllowShortIfStatementsOnASingleLine: false AllowShortLoopsOnASingleLine: false AlwaysBreakAfterReturnType: None @@ -32,13 +34,16 @@ BraceWrapping: SplitEmptyFunction: false SplitEmptyRecord: false SplitEmptyNamespace: false +BreakAfterAttributes: Never BreakBeforeBinaryOperators: All BreakBeforeBraces: Custom +BreakBeforeConceptDeclarations: Always BreakBeforeInheritanceComma: false BreakBeforeTernaryOperators: true BreakConstructorInitializersBeforeComma: false BreakConstructorInitializers: BeforeComma BreakAfterJavaFieldAnnotations: false +BreakInheritanceList: AfterComma BreakStringLiterals: true ColumnLimit: 100 CommentPragmas: '^ IWYU pragma:' @@ -49,6 +54,8 @@ ContinuationIndentWidth: 4 Cpp11BracedListStyle: true DerivePointerAlignment: false DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock ExperimentalAutoDetectBinPacking: false FixNamespaceComments: true ForEachMacros: @@ -56,17 +63,23 @@ ForEachMacros: - foreach - Q_FOREACH - BOOST_FOREACH +#IncludeBlocks: Regroup IncludeCategories: - Regex: '^(this)); - connect(m_preprocessWatcher.get(), &QFutureWatcher::resultReadyAt, this, + connect(m_preprocessWatcher.get(), + &QFutureWatcher::resultReadyAt, + this, [this](int resultIndex) { - beginInsertRows(index(0, 0) , m_files.count(), m_files.count()); - m_files.append(m_preprocessWatcher->resultAt(resultIndex)); - endInsertRows(); - }); + beginInsertRows(index(0, 0), m_files.size(), m_files.size()); + m_files.append(m_preprocessWatcher->resultAt(resultIndex)); + endInsertRows(); + }); connect(m_preprocessWatcher.get(), &QFutureWatcher::finished, this, &FilePathModel::endResetModel); diff --git a/src/plugins/qmldesigner/components/annotationeditor/annotationtableview.cpp b/src/plugins/qmldesigner/components/annotationeditor/annotationtableview.cpp index 7c8daa5eebb..f3cc629dd80 100644 --- a/src/plugins/qmldesigner/components/annotationeditor/annotationtableview.cpp +++ b/src/plugins/qmldesigner/components/annotationeditor/annotationtableview.cpp @@ -66,7 +66,7 @@ void CommentDelegate::updateEditorGeometry(QWidget *editor, editor->setGeometry(option.rect); } -Comment CommentDelegate::comment(QModelIndex const &index) +Comment CommentDelegate::comment(const QModelIndex &index) { auto *model = index.model(); return model->data(model->index(index.row(), ColumnId::Title), CommentRole).value(); @@ -136,9 +136,9 @@ void CommentValueDelegate::paint(QPainter *painter, const QModelIndex &index) const { auto data = index.model()->data(index, Qt::DisplayRole); - if (data.userType() == qMetaTypeId()) + if (data.typeId() == qMetaTypeId()) drawDisplay(painter, option, option.rect, data.value().plainText()); - else if (data.userType() == QMetaType::QColor) + else if (data.typeId() == QMetaType::QColor) painter->fillRect(option.rect, data.value()); else QItemDelegate::paint(painter, option, index); @@ -147,7 +147,7 @@ void CommentValueDelegate::paint(QPainter *painter, void CommentValueDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { auto data = index.model()->data(index, Qt::DisplayRole); - if (data.userType() == qMetaTypeId()) { + if (data.typeId() == qMetaTypeId()) { auto richText = data.value(); auto *e = qobject_cast(editor); e->setText(richText.plainText()); @@ -157,10 +157,10 @@ void CommentValueDelegate::setEditorData(QWidget *editor, const QModelIndex &ind this, &CommentValueDelegate::richTextEditorRequested, Qt::UniqueConnection); - } else if (data.userType() == QMetaType::QString) { + } else if (data.typeId() == QMetaType::QString) { auto *e = qobject_cast(editor); e->setText(data.toString()); - } else if (data.userType() == QMetaType::QColor) { + } else if (data.typeId() == QMetaType::QColor) { auto *e = qobject_cast(editor); e->setColor(data.value()); e->installEventFilter(e); @@ -206,15 +206,13 @@ void CommentValueDelegate::setModelData(QWidget *editor, const QModelIndex &index) const { auto data = model->data(index, Qt::EditRole); - if (data.userType() == qMetaTypeId()) + if (data.typeId() == qMetaTypeId()) return; - else if (data.userType() == QMetaType::QColor) - { + else if (data.typeId() == QMetaType::QColor) { model->setData(index, qobject_cast(editor)->color(), Qt::DisplayRole); - } - else if (data.userType() == QMetaType::QString) + } else if (data.typeId() == QMetaType::QString) model->setData(index, qobject_cast(editor)->text(), Qt::DisplayRole); else QItemDelegate::setModelData(editor, model, index); @@ -288,7 +286,7 @@ AnnotationTableView::AnnotationTableView(QWidget *parent) // When comment title was edited, make value item editable if (item->column() == ColumnId::Title && valueItem) { valueItem->setEditable(!item->text().isEmpty()); - valueItem->setCheckable(valueItem->data(Qt::DisplayRole).userType() == QMetaType::Bool); + valueItem->setCheckable(valueItem->data(Qt::DisplayRole).typeId() == QMetaType::Bool); } m_modelUpdating = true; @@ -344,7 +342,7 @@ Comment AnnotationTableView::fetchComment(int row) const return comment; } -void AnnotationTableView::setupComments(QVector const &comments) +void AnnotationTableView::setupComments(const QVector &comments) { m_model->clear(); m_modelUpdating = true; @@ -379,7 +377,7 @@ void AnnotationTableView::setDefaultAnnotations(DefaultAnnotationsModel *default m_valueDelegate.setDefaultAnnotations(defaults); } -void AnnotationTableView::changeRow(int index, Comment const &comment) +void AnnotationTableView::changeRow(int index, const Comment &comment) { auto *titleItem = m_model->item(index, ColumnId::Title); auto *authorItem = m_model->item(index, ColumnId::Author); @@ -395,7 +393,7 @@ void AnnotationTableView::changeRow(int index, Comment const &comment) : QMetaType::UnknownType); textItem->setEditable(data.isValid()); - textItem->setCheckable(data.userType() == QMetaType::Bool); + textItem->setCheckable(data.typeId() == QMetaType::Bool); textItem->setData(data, Qt::DisplayRole); } @@ -433,9 +431,9 @@ bool AnnotationTableView::rowIsEmpty(int row) const return QString(itemText(0) + itemText(1) + itemText(2)).isEmpty(); } -QString AnnotationTableView::dataToCommentText(QVariant const &data) +QString AnnotationTableView::dataToCommentText(const QVariant &data) { - auto type = data.userType(); + auto type = data.typeId(); if (type == qMetaTypeId()) return data.value().text; @@ -451,7 +449,7 @@ QString AnnotationTableView::dataToCommentText(QVariant const &data) return {}; } -QVariant AnnotationTableView::commentToData(Comment const& comment, QMetaType::Type type) +QVariant AnnotationTableView::commentToData(const Comment &comment, QMetaType::Type type) { switch (type) { case QMetaType::Bool: diff --git a/src/plugins/qmldesigner/components/annotationeditor/defaultannotations.cpp b/src/plugins/qmldesigner/components/annotationeditor/defaultannotations.cpp index 7a9212d5353..d3a302a7829 100644 --- a/src/plugins/qmldesigner/components/annotationeditor/defaultannotations.cpp +++ b/src/plugins/qmldesigner/components/annotationeditor/defaultannotations.cpp @@ -58,7 +58,7 @@ bool DefaultAnnotationsModel::hasDefault(const Comment &comment) const QMetaType::Type DefaultAnnotationsModel::defaultType(const Comment &comment) const { - return hasDefault(comment) ? QMetaType::Type(m_defaultMap[comment.title().toLower()].userType()) + return hasDefault(comment) ? QMetaType::Type(m_defaultMap[comment.title().toLower()].typeId()) : QMetaType::UnknownType; } @@ -73,7 +73,7 @@ bool DefaultAnnotationsModel::isRichText(const Comment &comment) const return type == QMetaType::UnknownType || type == qMetaTypeId(); } -void DefaultAnnotationsModel::loadFromFile(QString const &filename) +void DefaultAnnotationsModel::loadFromFile(const QString &filename) { QFile file(filename); if (file.open(QFile::ReadOnly)) { diff --git a/src/plugins/qmldesigner/components/bindingeditor/actioneditordialog.cpp b/src/plugins/qmldesigner/components/bindingeditor/actioneditordialog.cpp index ba797ee1a77..8fddcb1ade8 100644 --- a/src/plugins/qmldesigner/components/bindingeditor/actioneditordialog.cpp +++ b/src/plugins/qmldesigner/components/bindingeditor/actioneditordialog.cpp @@ -88,7 +88,7 @@ void ActionEditorDialog::adjustProperties() bool typeDone = false; bool targetDone = false; - for (int i = 0; i < expression.count(); ++i) { + for (int i = 0; i < expression.size(); ++i) { switch (expression[i].first) { case QmlJS::AST::Node::Kind::Kind_CallExpression: @@ -592,7 +592,7 @@ void ActionEditorDialog::fillAndSetSourceProperty(const QString &value, for (const auto &state : std::as_const(m_states)) m_assignmentSourceProperty->addItem(state, specificItem); - specificsEnd = m_states.count(); + specificsEnd = m_states.size(); } if (specificsEnd != -1) diff --git a/src/plugins/qmldesigner/components/bindingeditor/bindingeditor.cpp b/src/plugins/qmldesigner/components/bindingeditor/bindingeditor.cpp index 6cd3e814929..8c8d0911793 100644 --- a/src/plugins/qmldesigner/components/bindingeditor/bindingeditor.cpp +++ b/src/plugins/qmldesigner/components/bindingeditor/bindingeditor.cpp @@ -174,27 +174,38 @@ void BindingEditor::prepareBindings() QList bindings; - const QList variantTypes = {"alias", "unknown", "variant", "var"}; - const QList numericTypes = {"double", "real", "int"}; - const QList colorTypes = {"QColor", "color"}; - auto isVariant = [&variantTypes](const TypeName &compareType) { return variantTypes.contains(compareType); }; - auto isNumeric = [&numericTypes](const TypeName &compareType) { return numericTypes.contains(compareType); }; - auto isColor = [&colorTypes](const TypeName &compareType) { return colorTypes.contains(compareType); }; + const QVarLengthArray variantTypes = {"alias", "unknown", "variant", "var"}; + const QVarLengthArray numericTypes = {"double", "real", "int"}; + const QVarLengthArray colorTypes = {"QColor", "color"}; + const QVarLengthArray stringTypes = {"QString", "string"}; - const bool skipTypeFiltering = isVariant(m_backendValueTypeName); - const bool targetTypeIsNumeric = isNumeric(m_backendValueTypeName); + auto isVariant = [&variantTypes](const TypeName &compareType) { + return variantTypes.contains(compareType); + }; + auto isNumeric = [&numericTypes](const TypeName &compareType) { + return numericTypes.contains(compareType); + }; + auto isColor = [&colorTypes](const TypeName &compareType) { + return colorTypes.contains(compareType); + }; + auto isString = [&stringTypes](const TypeName &compareType) { + return stringTypes.contains(compareType); + }; + + auto compareTypes = [&](const TypeName &targetType, const TypeName &sourceType) { + return isVariant(targetType) || isVariant(sourceType) || (targetType == sourceType) + || (isNumeric(targetType) && isNumeric(sourceType)) + || (isColor(targetType) && isColor(sourceType)) + || (isString(targetType) && isString(sourceType)); + }; for (const auto &objnode : allNodes) { BindingEditorDialog::BindingOption binding; for (const auto &property : objnode.metaInfo().properties()) { const TypeName &propertyTypeName = property.propertyType().simplifiedTypeName(); - if (skipTypeFiltering - || (m_backendValueTypeName == propertyTypeName) - || isVariant(propertyTypeName) - || (targetTypeIsNumeric && isNumeric(propertyTypeName))) { + if (compareTypes(m_backendValueTypeName, propertyTypeName)) binding.properties.append(QString::fromUtf8(property.name())); - } } //dynamic properties: @@ -202,12 +213,8 @@ void BindingEditor::prepareBindings() if (bindingProperty.isValid()) { if (bindingProperty.isDynamic()) { const TypeName dynamicTypeName = bindingProperty.dynamicTypeName(); - if (skipTypeFiltering - || (dynamicTypeName == m_backendValueTypeName) - || isVariant(dynamicTypeName) - || (targetTypeIsNumeric && isNumeric(dynamicTypeName))) { + if (compareTypes(m_backendValueTypeName, dynamicTypeName)) binding.properties.append(QString::fromUtf8(bindingProperty.name())); - } } } } @@ -215,12 +222,8 @@ void BindingEditor::prepareBindings() if (variantProperty.isValid()) { if (variantProperty.isDynamic()) { const TypeName dynamicTypeName = variantProperty.dynamicTypeName(); - if (skipTypeFiltering - || (dynamicTypeName == m_backendValueTypeName) - || isVariant(dynamicTypeName) - || (targetTypeIsNumeric && isNumeric(dynamicTypeName))) { + if (compareTypes(m_backendValueTypeName, dynamicTypeName)) binding.properties.append(QString::fromUtf8(variantProperty.name())); - } } } } @@ -241,15 +244,10 @@ void BindingEditor::prepareBindings() BindingEditorDialog::BindingOption binding; for (const auto &property : metaInfo.properties()) { - TypeName propertyTypeName = property.propertyType().typeName(); + const TypeName propertyTypeName = property.propertyType().typeName(); - if (skipTypeFiltering - || (m_backendValueTypeName == propertyTypeName) - || (isVariant(propertyTypeName)) - || (targetTypeIsNumeric && isNumeric(propertyTypeName)) - || (isColor(m_backendValueTypeName) && isColor(propertyTypeName))) { + if (compareTypes(m_backendValueTypeName, propertyTypeName)) binding.properties.append(QString::fromUtf8(property.name())); - } } if (!binding.properties.isEmpty()) { diff --git a/src/plugins/qmldesigner/components/componentcore/crumblebar.cpp b/src/plugins/qmldesigner/components/componentcore/crumblebar.cpp index f4b6697c86b..005e353be25 100644 --- a/src/plugins/qmldesigner/components/componentcore/crumblebar.cpp +++ b/src/plugins/qmldesigner/components/componentcore/crumblebar.cpp @@ -73,10 +73,8 @@ void CrumbleBar::pushFile(const Utils::FilePath &fileName) } if (match != -1) { - for (int i = crumblePath()->length() - 1 - match; i > 0; --i) { - crumblePath()->popElement(); - m_pathes.removeLast(); - } + for (int i = crumblePath()->length() - 1 - match; i > 0; --i) + popElement(); } } @@ -163,6 +161,14 @@ bool CrumbleBar::showSaveDialog() return !canceled; } +void CrumbleBar::popElement() +{ + crumblePath()->popElement(); + + if (!m_pathes.isEmpty()) + m_pathes.removeLast(); +} + void CrumbleBar::onCrumblePathElementClicked(const QVariant &data) { CrumbleBarInfo clickedCrumbleBarInfo = data.value(); @@ -176,15 +182,12 @@ void CrumbleBar::onCrumblePathElementClicked(const QVariant &data) if (!inlineComp && !showSaveDialog()) return; - while (clickedCrumbleBarInfo != crumblePath()->dataForLastIndex().value()) { - crumblePath()->popElement(); - m_pathes.removeLast(); - } + while (clickedCrumbleBarInfo != crumblePath()->dataForLastIndex().value() + && crumblePath()->length() > 0) + popElement(); - if (crumblePath()->dataForLastIndex().value().modelNode.isValid()) { - crumblePath()->popElement(); - m_pathes.removeLast(); - } + if (crumblePath()->dataForLastIndex().value().modelNode.isValid()) + popElement(); m_isInternalCalled = true; if (inlineComp) { @@ -192,8 +195,7 @@ void CrumbleBar::onCrumblePathElementClicked(const QVariant &data) currentDesignDocument()->changeToDocumentModel(); QmlDesignerPlugin::instance()->viewManager().setComponentViewToMaster(); } else { - crumblePath()->popElement(); - m_pathes.removeLast(); + popElement(); nextFileIsCalledInternally(); Core::EditorManager::openEditor(clickedCrumbleBarInfo.fileName, Utils::Id(), diff --git a/src/plugins/qmldesigner/components/componentcore/crumblebar.h b/src/plugins/qmldesigner/components/componentcore/crumblebar.h index b9da4488f69..48e71efba6d 100644 --- a/src/plugins/qmldesigner/components/componentcore/crumblebar.h +++ b/src/plugins/qmldesigner/components/componentcore/crumblebar.h @@ -54,6 +54,7 @@ signals: private: void updateVisibility(); bool showSaveDialog(); + void popElement(); private: bool m_isInternalCalled = false; diff --git a/src/plugins/qmldesigner/components/componentcore/designeractionmanager.cpp b/src/plugins/qmldesigner/components/componentcore/designeractionmanager.cpp index 7243225c887..1562d13b0e4 100644 --- a/src/plugins/qmldesigner/components/componentcore/designeractionmanager.cpp +++ b/src/plugins/qmldesigner/components/componentcore/designeractionmanager.cpp @@ -50,7 +50,7 @@ namespace QmlDesigner { -static inline QString captionForModelNode(const ModelNode &modelNode) +inline static QString captionForModelNode(const ModelNode &modelNode) { if (modelNode.id().isEmpty()) return modelNode.simplifiedTypeName(); @@ -58,7 +58,7 @@ static inline QString captionForModelNode(const ModelNode &modelNode) return modelNode.id(); } -static inline bool contains(const QmlItemNode &node, const QPointF &position) +inline static bool contains(const QmlItemNode &node, const QPointF &position) { return node.isValid() && node.instanceSceneTransform().mapRect(node.instanceBoundingRect()).contains(position); } @@ -1208,7 +1208,7 @@ bool isStackedContainerAndIndexCanBeIncreased(const SelectionContext &context) const int value = containerItemNode.instanceValue(propertyName).toInt(); - const int maxValue = currentSelectedNode.directSubModelNodes().count() - 1; + const int maxValue = currentSelectedNode.directSubModelNodes().size() - 1; return value < maxValue; } diff --git a/src/plugins/qmldesigner/components/componentcore/formatoperation.cpp b/src/plugins/qmldesigner/components/componentcore/formatoperation.cpp index 4676e0f46a9..546ad0cc6b0 100644 --- a/src/plugins/qmldesigner/components/componentcore/formatoperation.cpp +++ b/src/plugins/qmldesigner/components/componentcore/formatoperation.cpp @@ -52,7 +52,7 @@ void readFormatConfiguration(){ QVariantMap rootMap = jsonObject.toVariantMap(); QJsonArray jsonArray = rootMap["propertylist"].toJsonArray(); - for (int i=0; i< jsonArray.count(); ++i){ + for (int i = 0; i < jsonArray.size(); ++i) { auto item = jsonArray.at(i).toObject(); QVariantMap itemMap = item.toVariantMap(); StylePropertyStruct current; diff --git a/src/plugins/qmldesigner/components/componentcore/layoutingridlayout.cpp b/src/plugins/qmldesigner/components/componentcore/layoutingridlayout.cpp index 09d3fdeffd9..89a5868d89d 100644 --- a/src/plugins/qmldesigner/components/componentcore/layoutingridlayout.cpp +++ b/src/plugins/qmldesigner/components/componentcore/layoutingridlayout.cpp @@ -15,7 +15,7 @@ namespace QmlDesigner { -static inline void reparentTo(const ModelNode &node, const QmlItemNode &parent) +inline static void reparentTo(const ModelNode &node, const QmlItemNode &parent) { if (parent.isValid() && node.isValid()) { @@ -78,7 +78,7 @@ static int lowerBound(int i) return i; } -static inline QPointF getUpperLeftPosition(const QList &modelNodeList) +inline static QPointF getUpperLeftPosition(const QList &modelNodeList) { QPointF postion(std::numeric_limits::max(), std::numeric_limits::max()); for (const ModelNode &modelNode : modelNodeList) { @@ -193,7 +193,7 @@ void LayoutInGridLayout::doIt() } } -bool static hasQtQuickLayoutImport(const SelectionContext &context) +static bool hasQtQuickLayoutImport(const SelectionContext &context) { if (context.view() && context.view()->model()) { Import import = Import::createLibraryImport(QStringLiteral("QtQuick.Layouts"), QStringLiteral("1.0")); @@ -219,12 +219,12 @@ void LayoutInGridLayout::layout(const SelectionContext &context) int LayoutInGridLayout::columnCount() const { - return m_xTopOffsets.count(); + return m_xTopOffsets.size(); } int LayoutInGridLayout::rowCount() const { - return m_yTopOffsets.count(); + return m_yTopOffsets.size(); } void LayoutInGridLayout::collectItemNodes() diff --git a/src/plugins/qmldesigner/components/componentcore/modelnodeoperations.cpp b/src/plugins/qmldesigner/components/componentcore/modelnodeoperations.cpp index 258ae0ba925..d791b04672b 100644 --- a/src/plugins/qmldesigner/components/componentcore/modelnodeoperations.cpp +++ b/src/plugins/qmldesigner/components/componentcore/modelnodeoperations.cpp @@ -88,7 +88,7 @@ Utils::SmallString auxPropertyString(Utils::SmallStringView name) } } // namespace -static inline void reparentTo(const ModelNode &node, const QmlItemNode &parent) +inline static void reparentTo(const ModelNode &node, const QmlItemNode &parent) { if (parent.isValid() && node.isValid()) { @@ -103,7 +103,7 @@ static inline void reparentTo(const ModelNode &node, const QmlItemNode &parent) } } -static inline QPointF getUpperLeftPosition(const QList &modelNodeList) +inline static QPointF getUpperLeftPosition(const QList &modelNodeList) { QPointF postion(std::numeric_limits::max(), std::numeric_limits::max()); for (const ModelNode &modelNode : modelNodeList) { @@ -364,7 +364,7 @@ void reverse(const SelectionContext &selectionState) }); } -static inline void backupPropertyAndRemove(const ModelNode &node, const PropertyName &propertyName) +inline static void backupPropertyAndRemove(const ModelNode &node, const PropertyName &propertyName) { if (node.hasVariantProperty(propertyName)) { node.setAuxiliaryData(AuxiliaryDataType::Document, @@ -695,7 +695,8 @@ void addSignalHandlerOrGotoImplementation(const SelectionContext &selectionState Core::ModeManager::activateMode(Core::Constants::MODE_EDIT); - if (!usages.isEmpty() && (addAlwaysNewSlot || usages.count() < 2) && (!isModelNodeRoot || addAlwaysNewSlot)) { + if (!usages.isEmpty() && (addAlwaysNewSlot || usages.size() < 2) + && (!isModelNodeRoot || addAlwaysNewSlot)) { Core::EditorManager::openEditorAt( {usages.constFirst().path, usages.constFirst().line, usages.constFirst().col}); @@ -879,7 +880,7 @@ void addItemToStackedContainer(const SelectionContext &selectionContext) if (potentialTabBar.isValid()) {// The stacked container is hooked up to a TabBar NodeMetaInfo tabButtonMetaInfo = view->model()->metaInfo("QtQuick.Controls.TabButton", -1, -1); if (tabButtonMetaInfo.isValid()) { - const int buttonIndex = potentialTabBar.directSubModelNodes().count(); + const int buttonIndex = potentialTabBar.directSubModelNodes().size(); ModelNode tabButtonNode = view->createModelNode("QtQuick.Controls.TabButton", tabButtonMetaInfo.majorVersion(), @@ -949,7 +950,7 @@ void increaseIndexOfStackedContainer(const SelectionContext &selectionContext) int value = containerItemNode.instanceValue(propertyName).toInt(); ++value; - const int maxValue = container.directSubModelNodes().count(); + const int maxValue = container.directSubModelNodes().size(); QTC_ASSERT(value < maxValue, return); @@ -1012,7 +1013,7 @@ void addTabBarToStackedContainer(const SelectionContext &selectionContext) container.parentProperty().reparentHere(tabBarNode); - const int maxValue = container.directSubModelNodes().count(); + const int maxValue = container.directSubModelNodes().size(); QmlItemNode tabBarItem(tabBarNode); @@ -1239,8 +1240,7 @@ void setFlowStartItem(const SelectionContext &selectionContext) }); } - -bool static hasStudioComponentsImport(const SelectionContext &context) +static bool hasStudioComponentsImport(const SelectionContext &context) { if (context.view() && context.view()->model()) { Import import = Import::createLibraryImport("QtQuick.Studio.Components", "1.0"); @@ -1250,7 +1250,7 @@ bool static hasStudioComponentsImport(const SelectionContext &context) return false; } -static inline void setAdjustedPos(const QmlDesigner::ModelNode &modelNode) +inline static void setAdjustedPos(const QmlDesigner::ModelNode &modelNode) { if (modelNode.hasParentProperty()) { ModelNode parentNode = modelNode.parentProperty().parentModelNode(); diff --git a/src/plugins/qmldesigner/components/componentcore/svgpasteaction.cpp b/src/plugins/qmldesigner/components/componentcore/svgpasteaction.cpp index 99bf56078b9..738b1affedd 100644 --- a/src/plugins/qmldesigner/components/componentcore/svgpasteaction.cpp +++ b/src/plugins/qmldesigner/components/componentcore/svgpasteaction.cpp @@ -27,7 +27,7 @@ namespace { /* Copied from qquicksvgparser.cpp 3e783b26a8fb41e3f5a53b883735f5d10fbbd98a */ // '0' is 0x30 and '9' is 0x39 -static inline bool isDigit(ushort ch) +inline static bool isDigit(ushort ch) { static quint16 magic = 0x3ff; return ((ch >> 4) == 3) && (magic >> (ch & 15)); @@ -110,7 +110,7 @@ static qreal toDouble(const QChar *&str) return val; } -static inline void parseNumbersArray(const QChar *&str, QVarLengthArray &points) +inline static void parseNumbersArray(const QChar *&str, QVarLengthArray &points) { while (str->isSpace()) ++str; @@ -261,7 +261,7 @@ bool parsePathDataFast(const QString &dataStr, QPainterPath &path) if (pathElem == QLatin1Char('z') || pathElem == QLatin1Char('Z')) arg.append(0);//dummy const qreal *num = arg.constData(); - int count = arg.count(); + int count = arg.size(); while (count > 0) { qreal offsetX = x; // correction offsets qreal offsetY = y; // for relative commands diff --git a/src/plugins/qmldesigner/components/componentcore/theme.h b/src/plugins/qmldesigner/components/componentcore/theme.h index 8e5f10d3615..a565ae03fcf 100644 --- a/src/plugins/qmldesigner/components/componentcore/theme.h +++ b/src/plugins/qmldesigner/components/componentcore/theme.h @@ -141,6 +141,7 @@ public: editLightOn_medium, edit_medium, edit_small, + effects, events_small, export_medium, eyeDropper, @@ -326,6 +327,8 @@ public: unpin, upDownIcon, upDownSquare2, + updateAvailable_medium, + updateContent_medium, visibilityOff, visibilityOn, visible_medium, diff --git a/src/plugins/qmldesigner/components/componentcore/viewmanager.cpp b/src/plugins/qmldesigner/components/componentcore/viewmanager.cpp index ee7ae3f6788..29bee73620a 100644 --- a/src/plugins/qmldesigner/components/componentcore/viewmanager.cpp +++ b/src/plugins/qmldesigner/components/componentcore/viewmanager.cpp @@ -8,9 +8,8 @@ #include #include #include -#include -#include #include +#include #include #include #include @@ -23,12 +22,11 @@ #include #include #include +#include #include -#include #include #include #include -#include #include @@ -38,14 +36,6 @@ namespace QmlDesigner { -static bool useOldStatesEditor() -{ - return QmlDesignerPlugin::instance() - ->settings() - .value(DesignerSettingsKey::OLD_STATES_EDITOR) - .toBool(); -} - static Q_LOGGING_CATEGORY(viewBenchmark, "qtc.viewmanager.attach", QtWarningMsg) class ViewManagerData @@ -58,7 +48,8 @@ public: , nodeInstanceView(QCoreApplication::arguments().contains("-capture-puppet-stream") ? capturingConnectionManager : connectionManager, - externalDependencies) + externalDependencies, + true) , contentLibraryView{externalDependencies} , componentView{externalDependencies} , edit3DView{externalDependencies} @@ -72,7 +63,6 @@ public: , materialBrowserView{imageCache, externalDependencies} , textureEditorView{imageCache, externalDependencies} , statesEditorView{externalDependencies} - , newStatesEditorView{externalDependencies} {} InteractiveConnectionManager connectionManager; @@ -94,7 +84,6 @@ public: MaterialBrowserView materialBrowserView; TextureEditorView textureEditorView; StatesEditorView statesEditorView; - Experimental::StatesEditorView newStatesEditorView; std::vector> additionalViews; bool disableStandardViews = false; @@ -176,30 +165,16 @@ void ViewManager::detachRewriterView() void ViewManager::switchStateEditorViewToBaseState() { - if (useOldStatesEditor()) { - if (d->statesEditorView.isAttached()) { - d->savedState = d->statesEditorView.currentState(); - d->statesEditorView.setCurrentState(d->statesEditorView.baseState()); - } - } else { - // TODO remove old statesview - if (d->newStatesEditorView.isAttached()) { - d->savedState = d->newStatesEditorView.currentState(); - d->newStatesEditorView.setCurrentState(d->newStatesEditorView.baseState()); - } + if (d->statesEditorView.isAttached()) { + d->savedState = d->statesEditorView.currentState(); + d->statesEditorView.setCurrentState(d->statesEditorView.baseState()); } } void ViewManager::switchStateEditorViewToSavedState() { - if (useOldStatesEditor()) { - if (d->savedState.isValid() && d->statesEditorView.isAttached()) - d->statesEditorView.setCurrentState(d->savedState); - } else { - // TODO remove old statesview - if (d->savedState.isValid() && d->newStatesEditorView.isAttached()) - d->newStatesEditorView.setCurrentState(d->savedState); - } + if (d->savedState.isValid() && d->statesEditorView.isAttached()) + d->statesEditorView.setCurrentState(d->savedState); } QList ViewManager::views() const @@ -223,14 +198,8 @@ QList ViewManager::standardViews() const &d->materialBrowserView, &d->textureEditorView, &d->statesEditorView, - &d->newStatesEditorView, // TODO &d->designerActionManagerView}; - if (useOldStatesEditor()) - list.removeAll(&d->newStatesEditorView); - else - list.removeAll(&d->statesEditorView); - if (QmlDesignerPlugin::instance() ->settings() .value(DesignerSettingsKey::ENABLE_DEBUGVIEW) @@ -410,10 +379,7 @@ QList ViewManager::widgetInfos() const widgetInfoList.append(d->materialEditorView.widgetInfo()); widgetInfoList.append(d->materialBrowserView.widgetInfo()); widgetInfoList.append(d->textureEditorView.widgetInfo()); - if (useOldStatesEditor()) - widgetInfoList.append(d->statesEditorView.widgetInfo()); - else - widgetInfoList.append(d->newStatesEditorView.widgetInfo()); + widgetInfoList.append(d->statesEditorView.widgetInfo()); #ifdef CHECK_LICENSE if (checkLicense() == FoundLicense::enterprise) diff --git a/src/plugins/qmldesigner/components/connectioneditor/backendmodel.cpp b/src/plugins/qmldesigner/components/connectioneditor/backendmodel.cpp index 6c970f2646d..5778d8242f7 100644 --- a/src/plugins/qmldesigner/components/connectioneditor/backendmodel.cpp +++ b/src/plugins/qmldesigner/components/connectioneditor/backendmodel.cpp @@ -203,7 +203,7 @@ void BackendModel::addNewBackend() if (dialog.applied()) { QStringList importSplit = dialog.importString().split(" "); - if (importSplit.count() != 2) { + if (importSplit.size() != 2) { qWarning() << Q_FUNC_INFO << "invalid import" << importSplit; QTC_ASSERT(false, return); } diff --git a/src/plugins/qmldesigner/components/connectioneditor/bindingmodel.cpp b/src/plugins/qmldesigner/components/connectioneditor/bindingmodel.cpp index e0a8f03e99e..191900d5e9d 100644 --- a/src/plugins/qmldesigner/components/connectioneditor/bindingmodel.cpp +++ b/src/plugins/qmldesigner/components/connectioneditor/bindingmodel.cpp @@ -217,7 +217,7 @@ static PropertyName unusedProperty(const ModelNode &modelNode) void BindingModel::addBindingForCurrentNode() { - if (connectionView()->selectedModelNodes().count() == 1) { + if (connectionView()->selectedModelNodes().size() == 1) { const ModelNode modelNode = connectionView()->selectedModelNodes().constFirst(); if (modelNode.isValid()) { try { @@ -380,9 +380,9 @@ bool BindingModel::getExpressionStrings(const BindingProperty &bindingProperty, QString propertyName; - for (int i=1; i < stringList.count(); i++) { + for (int i = 1; i < stringList.size(); i++) { propertyName += stringList.at(i); - if (i != stringList.count() - 1) + if (i != stringList.size() - 1) propertyName += QLatin1String("."); } *sourceProperty = propertyName; diff --git a/src/plugins/qmldesigner/components/connectioneditor/connectionmodel.cpp b/src/plugins/qmldesigner/components/connectioneditor/connectionmodel.cpp index 25a5756c28e..4abb7b21376 100644 --- a/src/plugins/qmldesigner/components/connectioneditor/connectionmodel.cpp +++ b/src/plugins/qmldesigner/components/connectioneditor/connectionmodel.cpp @@ -301,7 +301,7 @@ void ConnectionModel::addConnection() nodeMetaInfo.minorVersion()); QString source = "console.log(\"clicked\")"; - if (connectionView()->selectedModelNodes().count() == 1) { + if (connectionView()->selectedModelNodes().size() == 1) { ModelNode selectedNode = connectionView()->selectedModelNodes().constFirst(); if (QmlItemNode::isValidQmlItemNode(selectedNode)) selectedNode.nodeAbstractProperty("data").reparentHere(newNode); diff --git a/src/plugins/qmldesigner/components/connectioneditor/connectionview.cpp b/src/plugins/qmldesigner/components/connectioneditor/connectionview.cpp index 56fcc7ef6bf..d8f84f3e0fc 100644 --- a/src/plugins/qmldesigner/components/connectioneditor/connectionview.cpp +++ b/src/plugins/qmldesigner/components/connectioneditor/connectionview.cpp @@ -155,7 +155,7 @@ void ConnectionView::selectedNodesChanged(const QList & selectedNodeL if (connectionViewWidget()->currentTab() == ConnectionViewWidget::BindingTab || connectionViewWidget()->currentTab() == ConnectionViewWidget::DynamicPropertiesTab) - emit connectionViewWidget()->setEnabledAddButton(selectedNodeList.count() == 1); + emit connectionViewWidget()->setEnabledAddButton(selectedNodeList.size() == 1); } void ConnectionView::auxiliaryDataChanged([[maybe_unused]] const ModelNode &node, diff --git a/src/plugins/qmldesigner/components/connectioneditor/connectionviewwidget.cpp b/src/plugins/qmldesigner/components/connectioneditor/connectionviewwidget.cpp index f1b0c3f4cbe..edade6ae400 100644 --- a/src/plugins/qmldesigner/components/connectioneditor/connectionviewwidget.cpp +++ b/src/plugins/qmldesigner/components/connectioneditor/connectionviewwidget.cpp @@ -347,14 +347,14 @@ void ConnectionViewWidget::invalidateButtonStatus() } else if (currentTab() == BindingTab) { emit setEnabledRemoveButton(ui->bindingView->selectionModel()->hasSelection()); auto bindingModel = qobject_cast(ui->bindingView->model()); - emit setEnabledAddButton(bindingModel->connectionView()->model() && - bindingModel->connectionView()->selectedModelNodes().count() == 1); + emit setEnabledAddButton(bindingModel->connectionView()->model() + && bindingModel->connectionView()->selectedModelNodes().size() == 1); } else if (currentTab() == DynamicPropertiesTab) { emit setEnabledRemoveButton(ui->dynamicPropertiesView->selectionModel()->hasSelection()); auto dynamicPropertiesModel = qobject_cast(ui->dynamicPropertiesView->model()); - emit setEnabledAddButton(dynamicPropertiesModel->view()->model() && - dynamicPropertiesModel->selectedNodes().count() == 1); + emit setEnabledAddButton(dynamicPropertiesModel->view()->model() + && dynamicPropertiesModel->selectedNodes().size() == 1); } else if (currentTab() == BackendTab) { emit setEnabledAddButton(true); emit setEnabledRemoveButton(ui->backendView->selectionModel()->hasSelection()); diff --git a/src/plugins/qmldesigner/components/connectioneditor/dynamicpropertiesmodel.cpp b/src/plugins/qmldesigner/components/connectioneditor/dynamicpropertiesmodel.cpp index 89e08c5441f..4faf5d23f17 100644 --- a/src/plugins/qmldesigner/components/connectioneditor/dynamicpropertiesmodel.cpp +++ b/src/plugins/qmldesigner/components/connectioneditor/dynamicpropertiesmodel.cpp @@ -180,7 +180,7 @@ void DynamicPropertiesModel::resetModel() // Value copying is optional BindingProperty DynamicPropertiesModel::replaceVariantWithBinding(const PropertyName &name, bool copyValue) { - if (selectedNodes().count() == 1) { + if (selectedNodes().size() == 1) { const ModelNode modelNode = selectedNodes().constFirst(); if (modelNode.isValid()) { if (modelNode.hasVariantProperty(name)) { @@ -214,7 +214,7 @@ BindingProperty DynamicPropertiesModel::replaceVariantWithBinding(const Property // If it's a BindingProperty, then replaces it with empty VariantProperty void DynamicPropertiesModel::resetProperty(const PropertyName &name) { - if (selectedNodes().count() == 1) { + if (selectedNodes().size() == 1) { const ModelNode modelNode = selectedNodes().constFirst(); if (modelNode.isValid()) { if (modelNode.hasProperty(name)) { @@ -454,7 +454,7 @@ void DynamicPropertiesModel::addDynamicPropertyForCurrentNode() { QmlDesignerPlugin::emitUsageStatistics(Constants::EVENT_PROPERTY_ADDED); - if (selectedNodes().count() == 1) { + if (selectedNodes().size() == 1) { const ModelNode modelNode = selectedNodes().constFirst(); if (modelNode.isValid()) { try { @@ -839,9 +839,9 @@ bool DynamicPropertiesModel::getExpressionStrings(const BindingProperty &binding QString propertyName; - for (int i = 1; i < expressionParts.count(); ++i) { + for (int i = 1; i < expressionParts.size(); ++i) { propertyName += expressionParts.at(i); - if (i != expressionParts.count() - 1) + if (i != expressionParts.size() - 1) propertyName += QLatin1String("."); } *sourceProperty = propertyName; diff --git a/src/plugins/qmldesigner/components/contentlibrary/contentlibraryeffect.cpp b/src/plugins/qmldesigner/components/contentlibrary/contentlibraryeffect.cpp new file mode 100644 index 00000000000..f572fbe65f4 --- /dev/null +++ b/src/plugins/qmldesigner/components/contentlibrary/contentlibraryeffect.cpp @@ -0,0 +1,78 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +#include "contentlibraryeffect.h" + +#include + +namespace QmlDesigner { + +ContentLibraryEffect::ContentLibraryEffect(QObject *parent, + const QString &name, + const QString &qml, + const TypeName &type, + const QUrl &icon, + const QStringList &files) + : QObject(parent), m_name(name), m_qml(qml), m_type(type), m_icon(icon), m_files(files) +{ + m_allFiles = m_files; + m_allFiles.push_back(m_qml); +} + +bool ContentLibraryEffect::filter(const QString &searchText) +{ + if (m_visible != m_name.contains(searchText, Qt::CaseInsensitive)) { + m_visible = !m_visible; + emit itemVisibleChanged(); + } + + return m_visible; +} + +QUrl ContentLibraryEffect::icon() const +{ + return m_icon; +} + +QString ContentLibraryEffect::qml() const +{ + return m_qml; +} + +TypeName ContentLibraryEffect::type() const +{ + return m_type; +} + +QStringList ContentLibraryEffect::files() const +{ + return m_files; +} + +bool ContentLibraryEffect::visible() const +{ + return m_visible; +} + +bool ContentLibraryEffect::setImported(bool imported) +{ + if (m_imported != imported) { + m_imported = imported; + emit itemImportedChanged(); + return true; + } + + return false; +} + +bool ContentLibraryEffect::imported() const +{ + return m_imported; +} + +QStringList ContentLibraryEffect::allFiles() const +{ + return m_allFiles; +} + +} // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/contentlibrary/contentlibraryeffect.h b/src/plugins/qmldesigner/components/contentlibrary/contentlibraryeffect.h new file mode 100644 index 00000000000..fdb302b6139 --- /dev/null +++ b/src/plugins/qmldesigner/components/contentlibrary/contentlibraryeffect.h @@ -0,0 +1,62 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +#pragma once + +#include "modelfwd.h" + +#include +#include + +namespace QmlDesigner { + +class ContentLibraryEffect : public QObject +{ + Q_OBJECT + + Q_PROPERTY(QString bundleItemName MEMBER m_name CONSTANT) + Q_PROPERTY(QUrl bundleItemIcon MEMBER m_icon CONSTANT) + Q_PROPERTY(QStringList bundleItemFiles READ allFiles CONSTANT) + Q_PROPERTY(bool bundleItemVisible MEMBER m_visible NOTIFY itemVisibleChanged) + Q_PROPERTY(bool bundleItemImported READ imported WRITE setImported NOTIFY itemImportedChanged) + +public: + ContentLibraryEffect(QObject *parent, + const QString &name, + const QString &qml, + const TypeName &type, + const QUrl &icon, + const QStringList &files); + + bool filter(const QString &searchText); + + QUrl icon() const; + QString qml() const; + TypeName type() const; + QStringList files() const; + bool visible() const; + QString qmlFilePath() const; + + bool setImported(bool imported); + bool imported() const; + QString parentDirPath() const; + QStringList allFiles() const; + +signals: + void itemVisibleChanged(); + void itemImportedChanged(); + +private: + QString m_name; + QString m_qml; + TypeName m_type; + QUrl m_icon; + QStringList m_files; + + bool m_visible = true; + bool m_imported = false; + + QStringList m_allFiles; +}; + +} // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/contentlibrary/contentlibraryeffectscategory.cpp b/src/plugins/qmldesigner/components/contentlibrary/contentlibraryeffectscategory.cpp new file mode 100644 index 00000000000..38e6eed3dad --- /dev/null +++ b/src/plugins/qmldesigner/components/contentlibrary/contentlibraryeffectscategory.cpp @@ -0,0 +1,63 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +#include "contentlibraryeffectscategory.h" + +#include "contentlibraryeffect.h" + +namespace QmlDesigner { + +ContentLibraryEffectsCategory::ContentLibraryEffectsCategory(QObject *parent, const QString &name) + : QObject(parent), m_name(name) {} + +void ContentLibraryEffectsCategory::addBundleItem(ContentLibraryEffect *bundleItem) +{ + m_categoryItems.append(bundleItem); +} + +bool ContentLibraryEffectsCategory::updateImportedState(const QStringList &importedItems) +{ + bool changed = false; + + for (ContentLibraryEffect *item : std::as_const(m_categoryItems)) + changed |= item->setImported(importedItems.contains(item->qml().chopped(4))); + + return changed; +} + +bool ContentLibraryEffectsCategory::filter(const QString &searchText) +{ + bool visible = false; + for (ContentLibraryEffect *item : std::as_const(m_categoryItems)) + visible |= item->filter(searchText); + + if (visible != m_visible) { + m_visible = visible; + emit categoryVisibleChanged(); + return true; + } + + return false; +} + +QString ContentLibraryEffectsCategory::name() const +{ + return m_name; +} + +bool ContentLibraryEffectsCategory::visible() const +{ + return m_visible; +} + +bool ContentLibraryEffectsCategory::expanded() const +{ + return m_expanded; +} + +QList ContentLibraryEffectsCategory::categoryItems() const +{ + return m_categoryItems; +} + +} // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/contentlibrary/contentlibraryeffectscategory.h b/src/plugins/qmldesigner/components/contentlibrary/contentlibraryeffectscategory.h new file mode 100644 index 00000000000..79737c1ec24 --- /dev/null +++ b/src/plugins/qmldesigner/components/contentlibrary/contentlibraryeffectscategory.h @@ -0,0 +1,47 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +#pragma once + +#include + +namespace QmlDesigner { + +class ContentLibraryEffect; + +class ContentLibraryEffectsCategory : public QObject +{ + Q_OBJECT + + Q_PROPERTY(QString bundleCategoryName MEMBER m_name CONSTANT) + Q_PROPERTY(bool bundleCategoryVisible MEMBER m_visible NOTIFY categoryVisibleChanged) + Q_PROPERTY(bool bundleCategoryExpanded MEMBER m_expanded NOTIFY categoryExpandChanged) + Q_PROPERTY(QList bundleCategoryItems MEMBER m_categoryItems + NOTIFY categoryItemsChanged) + +public: + ContentLibraryEffectsCategory(QObject *parent, const QString &name); + + void addBundleItem(ContentLibraryEffect *bundleItem); + bool updateImportedState(const QStringList &importedMats); + bool filter(const QString &searchText); + + QString name() const; + bool visible() const; + bool expanded() const; + QList categoryItems() const; + +signals: + void categoryVisibleChanged(); + void categoryExpandChanged(); + void categoryItemsChanged(); + +private: + QString m_name; + bool m_visible = true; + bool m_expanded = true; + + QList m_categoryItems; +}; + +} // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/contentlibrary/contentlibraryeffectsmodel.cpp b/src/plugins/qmldesigner/components/contentlibrary/contentlibraryeffectsmodel.cpp new file mode 100644 index 00000000000..3bfd374bd81 --- /dev/null +++ b/src/plugins/qmldesigner/components/contentlibrary/contentlibraryeffectsmodel.cpp @@ -0,0 +1,286 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +#include "contentlibraryeffectsmodel.h" + +#include "contentlibrarybundleimporter.h" +#include "contentlibraryeffect.h" +#include "contentlibraryeffectscategory.h" +#include "contentlibrarywidget.h" +#include "qmldesignerconstants.h" + +#include +#include + +#include +#include +#include +#include + +namespace QmlDesigner { + +ContentLibraryEffectsModel::ContentLibraryEffectsModel(ContentLibraryWidget *parent) + : QAbstractListModel(parent) + , m_widget(parent) +{ +} + +int ContentLibraryEffectsModel::rowCount(const QModelIndex &) const +{ + return m_bundleCategories.size(); +} + +QVariant ContentLibraryEffectsModel::data(const QModelIndex &index, int role) const +{ + QTC_ASSERT(index.isValid() && index.row() < m_bundleCategories.count(), return {}); + QTC_ASSERT(roleNames().contains(role), return {}); + + return m_bundleCategories.at(index.row())->property(roleNames().value(role)); +} + +bool ContentLibraryEffectsModel::setData(const QModelIndex &index, const QVariant &value, int role) +{ + if (!index.isValid() || !roleNames().contains(role)) + return false; + + QByteArray roleName = roleNames().value(role); + ContentLibraryEffectsCategory *bundleCategory = m_bundleCategories.at(index.row()); + QVariant currValue = bundleCategory->property(roleName); + + if (currValue != value) { + bundleCategory->setProperty(roleName, value); + + emit dataChanged(index, index, {role}); + return true; + } + + return false; +} + +bool ContentLibraryEffectsModel::isValidIndex(int idx) const +{ + return idx > -1 && idx < rowCount(); +} + +void ContentLibraryEffectsModel::updateIsEmpty() +{ + bool anyCatVisible = Utils::anyOf(m_bundleCategories, [&](ContentLibraryEffectsCategory *cat) { + return cat->visible(); + }); + + bool newEmpty = !anyCatVisible || m_bundleCategories.isEmpty() || !hasRequiredQuick3DImport(); + + if (newEmpty != m_isEmpty) { + m_isEmpty = newEmpty; + emit isEmptyChanged(); + } +} + +QHash ContentLibraryEffectsModel::roleNames() const +{ + static const QHash roles { + {Qt::UserRole + 1, "bundleCategoryName"}, + {Qt::UserRole + 2, "bundleCategoryVisible"}, + {Qt::UserRole + 3, "bundleCategoryExpanded"}, + {Qt::UserRole + 4, "bundleCategoryItems"} + }; + return roles; +} + +void ContentLibraryEffectsModel::createImporter(const QString &bundlePath, const QString &bundleId, + const QStringList &sharedFiles) +{ + m_importer = new Internal::ContentLibraryBundleImporter(bundlePath, bundleId, sharedFiles); + connect(m_importer, &Internal::ContentLibraryBundleImporter::importFinished, this, + [&](const QmlDesigner::NodeMetaInfo &metaInfo) { + m_importerRunning = false; + emit importerRunningChanged(); + if (metaInfo.isValid()) + emit bundleItemImported(metaInfo); + }); + + connect(m_importer, &Internal::ContentLibraryBundleImporter::unimportFinished, this, + [&](const QmlDesigner::NodeMetaInfo &metaInfo) { + Q_UNUSED(metaInfo) + m_importerRunning = false; + emit importerRunningChanged(); + emit bundleItemUnimported(metaInfo); + }); + + resetModel(); + updateIsEmpty(); +} + +void ContentLibraryEffectsModel::loadBundle() +{ + if (m_bundleExists || m_probeBundleDir) + return; + + QDir bundleDir = qEnvironmentVariable("EFFECT_BUNDLE_PATH"); + + // search for bundleDir from exec dir and up + if (bundleDir.dirName() == ".") { + m_probeBundleDir = true; // probe only once + bundleDir.setPath(QCoreApplication::applicationDirPath()); + while (!bundleDir.cd("effect_bundle") && bundleDir.cdUp()) + ; // do nothing + + if (bundleDir.dirName() != "effect_bundle") // bundlePathDir not found + return; + } + + QString bundlePath = bundleDir.filePath("effect_bundle.json"); + + if (m_bundleObj.isEmpty()) { + QFile propsFile(bundlePath); + + if (!propsFile.open(QIODevice::ReadOnly)) { + qWarning("Couldn't open effect_bundle.json"); + return; + } + + QJsonDocument bundleJsonDoc = QJsonDocument::fromJson(propsFile.readAll()); + if (bundleJsonDoc.isNull()) { + qWarning("Invalid effect_bundle.json file"); + return; + } else { + m_bundleObj = bundleJsonDoc.object(); + } + } + + QString bundleId = m_bundleObj.value("id").toString(); + + const QJsonObject catsObj = m_bundleObj.value("categories").toObject(); + const QStringList categories = catsObj.keys(); + for (const QString &cat : categories) { + auto category = new ContentLibraryEffectsCategory(this, cat); + + const QJsonObject itemsObj = catsObj.value(cat).toObject(); + const QStringList items = itemsObj.keys(); + for (const QString &item : items) { + const QJsonObject itemObj = itemsObj.value(item).toObject(); + + QStringList files; + const QJsonArray assetsArr = itemObj.value("files").toArray(); + for (const auto /*QJson{Const,}ValueRef*/ &asset : assetsArr) + files.append(asset.toString()); + + QUrl icon = QUrl::fromLocalFile(bundleDir.filePath(itemObj.value("icon").toString())); + QString qml = itemObj.value("qml").toString(); + TypeName type = QLatin1String("%1.%2.%3").arg( + QLatin1String(Constants::COMPONENT_BUNDLES_FOLDER).mid(1), + bundleId, + qml.chopped(4)).toLatin1(); // chopped(4): remove .qml + + auto bundleItem = new ContentLibraryEffect(category, item, qml, type, icon, files); + + category->addBundleItem(bundleItem); + } + m_bundleCategories.append(category); + } + + QStringList sharedFiles; + const QJsonArray sharedFilesArr = m_bundleObj.value("sharedFiles").toArray(); + for (const auto /*QJson{Const,}ValueRef*/ &file : sharedFilesArr) + sharedFiles.append(file.toString()); + + createImporter(bundleDir.path(), bundleId, sharedFiles); + + m_bundleExists = true; + emit bundleExistsChanged(); +} + +bool ContentLibraryEffectsModel::hasRequiredQuick3DImport() const +{ + return m_widget->hasQuick3DImport() && m_quick3dMajorVersion == 6 && m_quick3dMinorVersion >= 4; +} + +bool ContentLibraryEffectsModel::bundleExists() const +{ + return m_bundleExists; +} + +Internal::ContentLibraryBundleImporter *ContentLibraryEffectsModel::bundleImporter() const +{ + return m_importer; +} + +void ContentLibraryEffectsModel::setSearchText(const QString &searchText) +{ + QString lowerSearchText = searchText.toLower(); + + if (m_searchText == lowerSearchText) + return; + + m_searchText = lowerSearchText; + + for (int i = 0; i < m_bundleCategories.size(); ++i) { + ContentLibraryEffectsCategory *cat = m_bundleCategories.at(i); + bool catVisibilityChanged = cat->filter(m_searchText); + if (catVisibilityChanged) + emit dataChanged(index(i), index(i), {roleNames().keys("bundleCategoryVisible")}); + } + + updateIsEmpty(); +} + +void ContentLibraryEffectsModel::updateImportedState(const QStringList &importedItems) +{ + bool changed = false; + for (ContentLibraryEffectsCategory *cat : std::as_const(m_bundleCategories)) + changed |= cat->updateImportedState(importedItems); + + if (changed) + resetModel(); +} + +void ContentLibraryEffectsModel::setQuick3DImportVersion(int major, int minor) +{ + bool oldRequiredImport = hasRequiredQuick3DImport(); + + m_quick3dMajorVersion = major; + m_quick3dMinorVersion = minor; + + bool newRequiredImport = hasRequiredQuick3DImport(); + + if (oldRequiredImport == newRequiredImport) + return; + + emit hasRequiredQuick3DImportChanged(); + + updateIsEmpty(); +} + +void ContentLibraryEffectsModel::resetModel() +{ + beginResetModel(); + endResetModel(); +} + +void ContentLibraryEffectsModel::addInstance(ContentLibraryEffect *bundleItem) +{ + QString err = m_importer->importComponent(bundleItem->qml(), bundleItem->files()); + + if (err.isEmpty()) { + m_importerRunning = true; + emit importerRunningChanged(); + } else { + qWarning() << __FUNCTION__ << err; + } +} + +void ContentLibraryEffectsModel::removeFromProject(ContentLibraryEffect *bundleItem) +{ + emit bundleItemAboutToUnimport(bundleItem->type()); + + QString err = m_importer->unimportComponent(bundleItem->qml()); + + if (err.isEmpty()) { + m_importerRunning = true; + emit importerRunningChanged(); + } else { + qWarning() << __FUNCTION__ << err; + } +} + +} // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/contentlibrary/contentlibraryeffectsmodel.h b/src/plugins/qmldesigner/components/contentlibrary/contentlibraryeffectsmodel.h new file mode 100644 index 00000000000..104d34af2d2 --- /dev/null +++ b/src/plugins/qmldesigner/components/contentlibrary/contentlibraryeffectsmodel.h @@ -0,0 +1,90 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +#pragma once + +#include "nodemetainfo.h" + +#include +#include +#include + +namespace QmlDesigner { + +class ContentLibraryEffect; +class ContentLibraryEffectsCategory; +class ContentLibraryWidget; + +namespace Internal { +class ContentLibraryBundleImporter; +} + +class ContentLibraryEffectsModel : public QAbstractListModel +{ + Q_OBJECT + + Q_PROPERTY(bool bundleExists READ bundleExists NOTIFY bundleExistsChanged) + Q_PROPERTY(bool isEmpty MEMBER m_isEmpty NOTIFY isEmptyChanged) + Q_PROPERTY(bool hasRequiredQuick3DImport READ hasRequiredQuick3DImport NOTIFY hasRequiredQuick3DImportChanged) + Q_PROPERTY(bool importerRunning MEMBER m_importerRunning NOTIFY importerRunningChanged) + +public: + ContentLibraryEffectsModel(ContentLibraryWidget *parent = nullptr); + + int rowCount(const QModelIndex &parent = QModelIndex()) const override; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + bool setData(const QModelIndex &index, const QVariant &value, int role) override; + QHash roleNames() const override; + + void loadBundle(); + void setSearchText(const QString &searchText); + void updateImportedState(const QStringList &importedItems); + + void setQuick3DImportVersion(int major, int minor); + + bool hasRequiredQuick3DImport() const; + + bool bundleExists() const; + + void resetModel(); + void updateIsEmpty(); + + Internal::ContentLibraryBundleImporter *bundleImporter() const; + + Q_INVOKABLE void addInstance(QmlDesigner::ContentLibraryEffect *bundleItem); + Q_INVOKABLE void removeFromProject(QmlDesigner::ContentLibraryEffect *bundleItem); + +signals: + void isEmptyChanged(); + void hasRequiredQuick3DImportChanged(); + void bundleItemImported(const QmlDesigner::NodeMetaInfo &metaInfo); + void bundleItemAboutToUnimport(const QmlDesigner::TypeName &type); + void bundleItemUnimported(const QmlDesigner::NodeMetaInfo &metaInfo); + void importerRunningChanged(); + void bundleExistsChanged(); + +private: + bool isValidIndex(int idx) const; + void createImporter(const QString &bundlePath, const QString &bundleId, + const QStringList &sharedFiles); + + ContentLibraryWidget *m_widget = nullptr; + QString m_searchText; + QList m_bundleCategories; + QJsonObject m_bundleObj; + Internal::ContentLibraryBundleImporter *m_importer = nullptr; + + bool m_isEmpty = true; + bool m_bundleExists = false; + bool m_probeBundleDir = false; + bool m_importerRunning = false; + + int m_quick3dMajorVersion = -1; + int m_quick3dMinorVersion = -1; + + QString m_importerBundlePath; + QString m_importerBundleId; + QStringList m_importerSharedFiles; +}; + +} // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/contentlibrary/contentlibraryiconprovider.cpp b/src/plugins/qmldesigner/components/contentlibrary/contentlibraryiconprovider.cpp new file mode 100644 index 00000000000..96102bf8379 --- /dev/null +++ b/src/plugins/qmldesigner/components/contentlibrary/contentlibraryiconprovider.cpp @@ -0,0 +1,42 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +#include "contentlibraryiconprovider.h" + +#include + +namespace QmlDesigner { + +namespace Internal { + +ContentLibraryIconProvider::ContentLibraryIconProvider() + : QQuickImageProvider(Pixmap) +{ + +} + +QPixmap ContentLibraryIconProvider::requestPixmap(const QString &id, + QSize *size, + [[maybe_unused]] const QSize &requestedSize) +{ + QString realPath = Core::ICore::resourcePath("qmldesigner/contentLibraryImages/" + id).toString(); + + QPixmap pixmap{realPath}; + + if (size) { + size->setWidth(pixmap.width()); + size->setHeight(pixmap.height()); + } + + if (pixmap.isNull()) + return pixmap; + + if (requestedSize.isValid()) + return pixmap.scaled(requestedSize); + + return pixmap; +} + +} // namespace Internal + +} // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/contentlibrary/contentlibraryiconprovider.h b/src/plugins/qmldesigner/components/contentlibrary/contentlibraryiconprovider.h new file mode 100644 index 00000000000..56633959d6a --- /dev/null +++ b/src/plugins/qmldesigner/components/contentlibrary/contentlibraryiconprovider.h @@ -0,0 +1,17 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +#pragma once + +#include + +namespace QmlDesigner::Internal { + +class ContentLibraryIconProvider : public QQuickImageProvider +{ +public: + ContentLibraryIconProvider(); + QPixmap requestPixmap(const QString &id, QSize *size, const QSize &requestedSize) override; +}; + +} // namespace QmlDesigner::Internal diff --git a/src/plugins/qmldesigner/components/contentlibrary/contentlibrarymaterialsmodel.cpp b/src/plugins/qmldesigner/components/contentlibrary/contentlibrarymaterialsmodel.cpp index f272a4121df..e5ee371002e 100644 --- a/src/plugins/qmldesigner/components/contentlibrary/contentlibrarymaterialsmodel.cpp +++ b/src/plugins/qmldesigner/components/contentlibrary/contentlibrarymaterialsmodel.cpp @@ -53,7 +53,7 @@ int ContentLibraryMaterialsModel::rowCount(const QModelIndex &) const QVariant ContentLibraryMaterialsModel::data(const QModelIndex &index, int role) const { - QTC_ASSERT(index.isValid() && index.row() < m_bundleCategories.count(), return {}); + QTC_ASSERT(index.isValid() && index.row() < m_bundleCategories.size(), return {}); QTC_ASSERT(roleNames().contains(role), return {}); return m_bundleCategories.at(index.row())->property(roleNames().value(role)); @@ -332,14 +332,14 @@ void ContentLibraryMaterialsModel::setSearchText(const QString &searchText) m_searchText = lowerSearchText; - bool catVisibilityChanged = false; - for (ContentLibraryMaterialsCategory *cat : std::as_const(m_bundleCategories)) - catVisibilityChanged |= cat->filter(m_searchText); + for (int i = 0; i < m_bundleCategories.size(); ++i) { + ContentLibraryMaterialsCategory *cat = m_bundleCategories.at(i); + bool catVisibilityChanged = cat->filter(m_searchText); + if (catVisibilityChanged) + emit dataChanged(index(i), index(i), {roleNames().keys("bundleCategoryVisible")}); + } updateIsEmpty(); - - if (catVisibilityChanged) - resetModel(); } void ContentLibraryMaterialsModel::updateImportedState(const QStringList &importedMats) diff --git a/src/plugins/qmldesigner/components/contentlibrary/contentlibrarytexture.cpp b/src/plugins/qmldesigner/components/contentlibrary/contentlibrarytexture.cpp index fbc5199f989..7ab239aab4e 100644 --- a/src/plugins/qmldesigner/components/contentlibrary/contentlibrarytexture.cpp +++ b/src/plugins/qmldesigner/components/contentlibrary/contentlibrarytexture.cpp @@ -13,17 +13,23 @@ namespace QmlDesigner { ContentLibraryTexture::ContentLibraryTexture(QObject *parent, const QFileInfo &iconFileInfo, const QString &downloadPath, const QUrl &icon, - const QString &webUrl, const QString &fileExt, - const QSize &dimensions, const qint64 sizeInBytes) + const QString &key, const QString &webTextureUrl, + const QString &webIconUrl, const QString &fileExt, + const QSize &dimensions, const qint64 sizeInBytes, + bool hasUpdate, bool isNew) : QObject(parent) , m_iconPath(iconFileInfo.filePath()) , m_downloadPath(downloadPath) - , m_webUrl(webUrl) + , m_webTextureUrl(webTextureUrl) + , m_webIconUrl(webIconUrl) , m_baseName{iconFileInfo.baseName()} , m_fileExt(fileExt) + , m_textureKey(key) , m_icon(icon) , m_dimensions(dimensions) , m_sizeInBytes(sizeInBytes) + , m_hasUpdate(hasUpdate) + , m_isNew(isNew) { doSetDownloaded(); } @@ -58,7 +64,7 @@ QString ContentLibraryTexture::resolveFileExt() if (textureFiles.isEmpty()) return {}; - if (textureFiles.count() > 1) { + if (textureFiles.size() > 1) { qWarning() << "Found multiple textures with the same name in the same directories: " << Utils::transform(textureFiles, [](const QFileInfo &fi) { return fi.fileName(); @@ -122,4 +128,22 @@ QString ContentLibraryTexture::parentDirPath() const return m_downloadPath; } +QString ContentLibraryTexture::textureKey() const +{ + return m_textureKey; +} + +void ContentLibraryTexture::setHasUpdate(bool value) +{ + if (m_hasUpdate != value) { + m_hasUpdate = value; + emit hasUpdateChanged(); + } +} + +bool ContentLibraryTexture::hasUpdate() const +{ + return m_hasUpdate; +} + } // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/contentlibrary/contentlibrarytexture.h b/src/plugins/qmldesigner/components/contentlibrary/contentlibrarytexture.h index 074d4abb770..9f5b46630f6 100644 --- a/src/plugins/qmldesigner/components/contentlibrary/contentlibrarytexture.h +++ b/src/plugins/qmldesigner/components/contentlibrary/contentlibrarytexture.h @@ -19,12 +19,17 @@ class ContentLibraryTexture : public QObject Q_PROPERTY(QString textureToolTip MEMBER m_toolTip NOTIFY textureToolTipChanged) Q_PROPERTY(QUrl textureIcon MEMBER m_icon CONSTANT) Q_PROPERTY(bool textureVisible MEMBER m_visible NOTIFY textureVisibleChanged) - Q_PROPERTY(QString textureWebUrl MEMBER m_webUrl CONSTANT) + Q_PROPERTY(QString textureWebUrl MEMBER m_webTextureUrl CONSTANT) + Q_PROPERTY(QString textureWebIconUrl MEMBER m_webIconUrl CONSTANT) + Q_PROPERTY(bool textureHasUpdate WRITE setHasUpdate READ hasUpdate NOTIFY hasUpdateChanged) + Q_PROPERTY(bool textureIsNew MEMBER m_isNew CONSTANT) + Q_PROPERTY(QString textureKey MEMBER m_textureKey CONSTANT) public: - ContentLibraryTexture(QObject *parent, const QFileInfo &iconFileInfo, - const QString &downloadPath, const QUrl &icon, const QString &webUrl, - const QString &fileExt, const QSize &dimensions, const qint64 sizeInBytes); + ContentLibraryTexture(QObject *parent, const QFileInfo &iconFileInfo, const QString &downloadPath, + const QUrl &icon, const QString &key, const QString &webTextureUrl, + const QString &webIconUrl, const QString &fileExt, const QSize &dimensions, + const qint64 sizeInBytes, bool hasUpdate, bool isNew); Q_INVOKABLE bool isDownloaded() const; Q_INVOKABLE void setDownloaded(); @@ -35,10 +40,15 @@ public: QString iconPath() const; QString downloadedTexturePath() const; QString parentDirPath() const; + QString textureKey() const; + + void setHasUpdate(bool value); + bool hasUpdate() const; signals: void textureVisibleChanged(); void textureToolTipChanged(); + void hasUpdateChanged(); private: QString resolveFileExt(); @@ -47,16 +57,20 @@ private: QString m_iconPath; QString m_downloadPath; - QString m_webUrl; + QString m_webTextureUrl; + QString m_webIconUrl; QString m_toolTip; QString m_baseName; QString m_fileExt; + QString m_textureKey; QUrl m_icon; QSize m_dimensions; qint64 m_sizeInBytes = -1; bool m_isDownloaded = false; bool m_visible = true; + bool m_hasUpdate = false; + bool m_isNew = false; }; } // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/contentlibrary/contentlibrarytexturescategory.cpp b/src/plugins/qmldesigner/components/contentlibrary/contentlibrarytexturescategory.cpp index eecab425523..77519ad88f6 100644 --- a/src/plugins/qmldesigner/components/contentlibrary/contentlibrarytexturescategory.cpp +++ b/src/plugins/qmldesigner/components/contentlibrary/contentlibrarytexturescategory.cpp @@ -5,6 +5,8 @@ #include "contentlibrarytexture.h" +#include + #include namespace QmlDesigner { @@ -13,13 +15,16 @@ ContentLibraryTexturesCategory::ContentLibraryTexturesCategory(QObject *parent, : QObject(parent), m_name(name) {} void ContentLibraryTexturesCategory::addTexture(const QFileInfo &tex, const QString &downloadPath, - const QString &webUrl, const QString &fileExt, - const QSize &dimensions, const qint64 sizeInBytes) + const QString &key, const QString &webTextureUrl, + const QString &webIconUrl, const QString &fileExt, + const QSize &dimensions, const qint64 sizeInBytes, + bool hasUpdate, bool isNew) { QUrl icon = QUrl::fromLocalFile(tex.absoluteFilePath()); - m_categoryTextures.append(new ContentLibraryTexture(this, tex, downloadPath, icon, webUrl, - fileExt, dimensions, sizeInBytes)); + m_categoryTextures.append(new ContentLibraryTexture( + this, tex, downloadPath, icon, key, webTextureUrl, webIconUrl, + fileExt, dimensions, sizeInBytes, hasUpdate, isNew)); } bool ContentLibraryTexturesCategory::filter(const QString &searchText) @@ -57,4 +62,14 @@ QList ContentLibraryTexturesCategory::categoryTextures( return m_categoryTextures; } +void ContentLibraryTexturesCategory::markTextureHasNoUpdate(const QString &textureKey) +{ + auto *texture = Utils::findOrDefault(m_categoryTextures, [&textureKey](ContentLibraryTexture *t) { + return t->textureKey() == textureKey; + }); + + if (texture) + texture->setHasUpdate(false); +} + } // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/contentlibrary/contentlibrarytexturescategory.h b/src/plugins/qmldesigner/components/contentlibrary/contentlibrarytexturescategory.h index 91ecaaac969..166528f05a8 100644 --- a/src/plugins/qmldesigner/components/contentlibrary/contentlibrarytexturescategory.h +++ b/src/plugins/qmldesigner/components/contentlibrary/contentlibrarytexturescategory.h @@ -27,8 +27,9 @@ class ContentLibraryTexturesCategory : public QObject public: ContentLibraryTexturesCategory(QObject *parent, const QString &name); - void addTexture(const QFileInfo &tex, const QString &subPath, const QString &webUrl, - const QString &fileExt, const QSize &dimensions, const qint64 sizeInBytes); + void addTexture(const QFileInfo &tex, const QString &subPath, const QString &key, + const QString &webTextureUrl, const QString &webIconUrl, const QString &fileExt, + const QSize &dimensions, const qint64 sizeInBytes, bool hasUpdate, bool isNew); bool filter(const QString &searchText); QString name() const; @@ -36,6 +37,8 @@ public: bool expanded() const; QList categoryTextures() const; + void markTextureHasNoUpdate(const QString &textureKey); + signals: void categoryVisibleChanged(); void categoryExpandChanged(); diff --git a/src/plugins/qmldesigner/components/contentlibrary/contentlibrarytexturesmodel.cpp b/src/plugins/qmldesigner/components/contentlibrary/contentlibrarytexturesmodel.cpp index 5cf88ab6fcd..319ca2686f2 100644 --- a/src/plugins/qmldesigner/components/contentlibrary/contentlibrarytexturesmodel.cpp +++ b/src/plugins/qmldesigner/components/contentlibrary/contentlibrarytexturesmodel.cpp @@ -36,7 +36,7 @@ int ContentLibraryTexturesModel::rowCount(const QModelIndex &) const QVariant ContentLibraryTexturesModel::data(const QModelIndex &index, int role) const { - QTC_ASSERT(index.isValid() && index.row() < m_bundleCategories.count(), return {}); + QTC_ASSERT(index.isValid() && index.row() < m_bundleCategories.size(), return {}); QTC_ASSERT(roleNames().contains(role), return {}); return m_bundleCategories.at(index.row())->property(roleNames().value(role)); @@ -98,7 +98,8 @@ QHash ContentLibraryTexturesModel::roleNames() const * @param bundlePath local path to the bundle folder and icons * @param metaData bundle textures metadata */ -void ContentLibraryTexturesModel::loadTextureBundle(const QString &remoteUrl, const QString &bundleIconPath, +void ContentLibraryTexturesModel::loadTextureBundle(const QString &remoteUrl, const QString &iconsUrl, + const QString &bundleIconPath, const QVariantMap &metaData) { if (!m_bundleCategories.isEmpty()) @@ -117,8 +118,9 @@ void ContentLibraryTexturesModel::loadTextureBundle(const QString &remoteUrl, co auto category = new ContentLibraryTexturesCategory(this, dir.fileName()); const QFileInfoList texFiles = QDir(dir.filePath()).entryInfoList(QDir::Files); for (const QFileInfo &tex : texFiles) { - QString fullRemoteUrl = QString("%1/%2/%3.zip").arg(remoteUrl, dir.fileName(), - tex.baseName()); + QString textureUrl = QString("%1/%2/%3.zip").arg(remoteUrl, dir.fileName(), tex.baseName()); + QString iconUrl = QString("%1/%2/%3.png").arg(iconsUrl, dir.fileName(), tex.baseName()); + QString localDownloadPath = QString("%1/%2/%3") .arg(Paths::bundlesPathSetting(), m_category, @@ -127,15 +129,20 @@ void ContentLibraryTexturesModel::loadTextureBundle(const QString &remoteUrl, co QString fileExt; QSize dimensions; qint64 sizeInBytes = -1; + bool hasUpdate = false; + bool isNew = false; if (imageItems.contains(key)) { QVariantMap dataMap = imageItems[key].toMap(); fileExt = '.' + dataMap.value("format").toString(); dimensions = QSize(dataMap.value("width").toInt(), dataMap.value("height").toInt()); sizeInBytes = dataMap.value("file_size").toLongLong(); + hasUpdate = m_modifiedFiles.contains(key); + isNew = m_newFiles.contains(key); } - category->addTexture(tex, localDownloadPath, fullRemoteUrl, fileExt, dimensions, sizeInBytes); + category->addTexture(tex, localDownloadPath, key, textureUrl, iconUrl, fileExt, + dimensions, sizeInBytes, hasUpdate, isNew); } m_bundleCategories.append(category); } @@ -144,6 +151,52 @@ void ContentLibraryTexturesModel::loadTextureBundle(const QString &remoteUrl, co updateIsEmpty(); } +void ContentLibraryTexturesModel::setModifiedFileEntries(const QVariantMap &files) +{ + m_modifiedFiles.clear(); + + const QString prefix = m_category + "/"; + const QStringList keys = files.keys(); + + for (const QString &key : keys) { + if (key.startsWith(prefix)) + m_modifiedFiles[key] = files[key]; + } +} + +void ContentLibraryTexturesModel::setNewFileEntries(const QStringList &newFiles) +{ + const QString prefix = m_category + "/"; + + m_newFiles = Utils::filteredCast>(newFiles, [&prefix](const QString &key) { + return key.startsWith(prefix); + }); +} + +QString ContentLibraryTexturesModel::removeModifiedFileEntry(const QString &key) +{ + if (m_modifiedFiles.contains(key)) { + QVariantMap item = m_modifiedFiles[key].toMap(); + m_modifiedFiles.remove(key); + return item["checksum"].toString(); + } else { + return {}; + } +} + +void ContentLibraryTexturesModel::markTextureHasNoUpdates(const QString &subcategory, + const QString &textureKey) +{ + auto *categ = Utils::findOrDefault(m_bundleCategories, + [&subcategory](ContentLibraryTexturesCategory *c) { + return c->name() == subcategory; + }); + if (!categ) + return; + + categ->markTextureHasNoUpdate(textureKey); +} + bool ContentLibraryTexturesModel::texBundleExists() const { return !m_bundleCategories.isEmpty(); @@ -172,15 +225,14 @@ void ContentLibraryTexturesModel::setSearchText(const QString &searchText) m_searchText = lowerSearchText; - bool catVisibilityChanged = false; - - for (ContentLibraryTexturesCategory *cat : std::as_const(m_bundleCategories)) - catVisibilityChanged |= cat->filter(m_searchText); + for (int i = 0; i < m_bundleCategories.size(); ++i) { + ContentLibraryTexturesCategory *cat = m_bundleCategories.at(i); + bool catVisibilityChanged = cat->filter(m_searchText); + if (catVisibilityChanged) + emit dataChanged(index(i), index(i), {roleNames().keys("bundleCategoryVisible")}); + } updateIsEmpty(); - - if (catVisibilityChanged) - resetModel(); } void ContentLibraryTexturesModel::resetModel() diff --git a/src/plugins/qmldesigner/components/contentlibrary/contentlibrarytexturesmodel.h b/src/plugins/qmldesigner/components/contentlibrary/contentlibrarytexturesmodel.h index 3f7e4d48688..92db4151a84 100644 --- a/src/plugins/qmldesigner/components/contentlibrary/contentlibrarytexturesmodel.h +++ b/src/plugins/qmldesigner/components/contentlibrary/contentlibrarytexturesmodel.h @@ -26,6 +26,10 @@ public: QHash roleNames() const override; void setSearchText(const QString &searchText); + void setModifiedFileEntries(const QVariantMap &files); + void setNewFileEntries(const QStringList &newFiles); + QString removeModifiedFileEntry(const QString &key); + void markTextureHasNoUpdates(const QString &subcategory, const QString &textureKey); bool texBundleExists() const; @@ -33,8 +37,8 @@ public: void setHasSceneEnv(bool b); void resetModel(); - void loadTextureBundle(const QString &remoteUrl, const QString &bundlePath, - const QVariantMap &metaData); + void loadTextureBundle(const QString &remoteUrl, const QString &iconsUrl, + const QString &bundlePath, const QVariantMap &metaData); signals: void isEmptyChanged(); @@ -48,6 +52,8 @@ private: QString m_searchText; QString m_category; QList m_bundleCategories; + QVariantMap m_modifiedFiles; + QSet m_newFiles; bool m_isEmpty = true; bool m_hasSceneEnv = false; diff --git a/src/plugins/qmldesigner/components/contentlibrary/contentlibraryview.cpp b/src/plugins/qmldesigner/components/contentlibrary/contentlibraryview.cpp index 3bb579273f6..3f64f8d8b4f 100644 --- a/src/plugins/qmldesigner/components/contentlibrary/contentlibraryview.cpp +++ b/src/plugins/qmldesigner/components/contentlibrary/contentlibraryview.cpp @@ -4,6 +4,8 @@ #include "contentlibraryview.h" #include "contentlibrarybundleimporter.h" +#include "contentlibraryeffect.h" +#include "contentlibraryeffectsmodel.h" #include "contentlibrarymaterial.h" #include "contentlibrarymaterialsmodel.h" #include "contentlibrarytexture.h" @@ -26,6 +28,8 @@ #include #endif +#include + namespace QmlDesigner { ContentLibraryView::ContentLibraryView(ExternalDependenciesInterface &externalDependencies) @@ -54,6 +58,10 @@ WidgetInfo ContentLibraryView::widgetInfo() [&] (QmlDesigner::ContentLibraryTexture *tex) { m_draggedBundleTexture = tex; }); + connect(m_widget, &ContentLibraryWidget::bundleEffectDragStarted, this, + [&] (QmlDesigner::ContentLibraryEffect *eff) { + m_draggedBundleEffect = eff; + }); connect(m_widget, &ContentLibraryWidget::addTextureRequested, this, [&] (const QString &texPath, AddTextureMode mode) { @@ -109,6 +117,46 @@ WidgetInfo ContentLibraryView::widgetInfo() connect(materialsModel, &ContentLibraryMaterialsModel::bundleMaterialUnimported, this, &ContentLibraryView::updateBundleMaterialsImportedState); + + ContentLibraryEffectsModel *effectsModel = m_widget->effectsModel().data(); + + connect(effectsModel, &ContentLibraryEffectsModel::bundleItemImported, this, + [&] (const QmlDesigner::NodeMetaInfo &metaInfo) { + QTC_ASSERT(metaInfo.isValid(), return); + + if (!m_bundleEffectTarget) + m_bundleEffectTarget = active3DSceneNode(); + + QTC_ASSERT(m_bundleEffectTarget, return); + + executeInTransaction("ContentLibraryView::widgetInfo", [&] { + QVector3D pos = m_bundleEffectPos.value(); + ModelNode newEffNode = createModelNode(metaInfo.typeName(), metaInfo.majorVersion(), + metaInfo.minorVersion(), + {{"x", pos.x()}, {"y", pos.y()}, {"z", pos.z()}}); + m_bundleEffectTarget.defaultNodeListProperty().reparentHere(newEffNode); + clearSelectedModelNodes(); + selectModelNode(newEffNode); + }); + + updateBundleEffectsImportedState(); + m_bundleEffectTarget = {}; + m_bundleEffectPos = {}; + }); + + connect(effectsModel, &ContentLibraryEffectsModel::bundleItemAboutToUnimport, this, + [&] (const QmlDesigner::TypeName &type) { + // delete instances of the bundle effect that is about to be unimported + executeInTransaction("ContentLibraryView::widgetInfo", [&] { + NodeMetaInfo metaInfo = model()->metaInfo(type); + QList effects = allModelNodesOfType(metaInfo); + for (ModelNode &eff : effects) + eff.destroy(); + }); + }); + + connect(effectsModel, &ContentLibraryEffectsModel::bundleItemUnimported, this, + &ContentLibraryView::updateBundleEffectsImportedState); } return createWidgetInfo(m_widget.data(), @@ -124,7 +172,7 @@ void ContentLibraryView::modelAttached(Model *model) m_hasQuick3DImport = model->hasImport("QtQuick3D"); - updateBundleMaterialsQuick3DVersion(); + updateBundlesQuick3DVersion(); updateBundleMaterialsImportedState(); const bool hasLibrary = materialLibraryNode().isValid(); @@ -134,6 +182,9 @@ void ContentLibraryView::modelAttached(Model *model) m_sceneId = model->active3DSceneId(); m_widget->clearSearchFilter(); + + m_widget->effectsModel()->loadBundle(); + updateBundleEffectsImportedState(); } void ContentLibraryView::modelAboutToBeDetached(Model *model) @@ -149,7 +200,7 @@ void ContentLibraryView::importsChanged(const Imports &addedImports, const Impor Q_UNUSED(addedImports) Q_UNUSED(removedImports) - updateBundleMaterialsQuick3DVersion(); + updateBundlesQuick3DVersion(); bool hasQuick3DImport = model()->hasImport("QtQuick3D"); @@ -211,6 +262,12 @@ void ContentLibraryView::customNotification(const AbstractView *view, const QStr m_widget->addTexture(m_draggedBundleTexture); m_draggedBundleTexture = nullptr; + } else if (identifier == "drop_bundle_effect") { + QTC_ASSERT(nodeList.size() == 1, return); + + m_bundleEffectPos = data.size() == 1 ? data.first() : QVariant(); + m_widget->effectsModel()->addInstance(m_draggedBundleEffect); + m_bundleEffectTarget = nodeList.first() ? nodeList.first() : active3DSceneNode(); } } @@ -349,7 +406,26 @@ void ContentLibraryView::updateBundleMaterialsImportedState() m_widget->materialsModel()->updateImportedState(importedBundleMats); } -void ContentLibraryView::updateBundleMaterialsQuick3DVersion() +void ContentLibraryView::updateBundleEffectsImportedState() +{ + using namespace Utils; + + if (!m_widget->effectsModel()->bundleImporter()) + return; + + QStringList importedBundleEffs; + + FilePath bundlePath = m_widget->effectsModel()->bundleImporter()->resolveBundleImportPath(); + + if (bundlePath.exists()) { + importedBundleEffs = transform(bundlePath.dirEntries({{"*.qml"}, QDir::Files}), + [](const FilePath &f) { return f.fileName().chopped(4); }); + } + + m_widget->effectsModel()->updateImportedState(importedBundleEffs); +} + +void ContentLibraryView::updateBundlesQuick3DVersion() { bool hasImport = false; int major = -1; @@ -382,6 +458,7 @@ void ContentLibraryView::updateBundleMaterialsQuick3DVersion() } #endif m_widget->materialsModel()->setQuick3DImportVersion(major, minor); + m_widget->effectsModel()->setQuick3DImportVersion(major, minor); } } // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/contentlibrary/contentlibraryview.h b/src/plugins/qmldesigner/components/contentlibrary/contentlibraryview.h index 137034dd955..741a77759eb 100644 --- a/src/plugins/qmldesigner/components/contentlibrary/contentlibraryview.h +++ b/src/plugins/qmldesigner/components/contentlibrary/contentlibraryview.h @@ -3,8 +3,8 @@ #pragma once -#include "createtexture.h" #include "abstractview.h" +#include "createtexture.h" #include "nodemetainfo.h" #include @@ -12,6 +12,7 @@ namespace QmlDesigner { +class ContentLibraryEffect; class ContentLibraryMaterial; class ContentLibraryTexture; class ContentLibraryWidget; @@ -44,16 +45,20 @@ public: private: void updateBundleMaterialsImportedState(); - void updateBundleMaterialsQuick3DVersion(); + void updateBundleEffectsImportedState(); + void updateBundlesQuick3DVersion(); void applyBundleMaterialToDropTarget(const ModelNode &bundleMat, const NodeMetaInfo &metaInfo = {}); ModelNode getBundleMaterialDefaultInstance(const TypeName &type); ModelNode createMaterial(const NodeMetaInfo &metaInfo); QPointer m_widget; QList m_bundleMaterialTargets; + ModelNode m_bundleEffectTarget; // target of the dropped bundle effect + QVariant m_bundleEffectPos; // pos of the dropped bundle effect QList m_selectedModels; // selected 3D model nodes ContentLibraryMaterial *m_draggedBundleMaterial = nullptr; ContentLibraryTexture *m_draggedBundleTexture = nullptr; + ContentLibraryEffect *m_draggedBundleEffect = nullptr; bool m_bundleMaterialAddToSelected = false; bool m_hasQuick3DImport = false; qint32 m_sceneId = -1; diff --git a/src/plugins/qmldesigner/components/contentlibrary/contentlibrarywidget.cpp b/src/plugins/qmldesigner/components/contentlibrary/contentlibrarywidget.cpp index 4c15cce8d7a..78bc1f07c3c 100644 --- a/src/plugins/qmldesigner/components/contentlibrary/contentlibrarywidget.cpp +++ b/src/plugins/qmldesigner/components/contentlibrary/contentlibrarywidget.cpp @@ -3,13 +3,17 @@ #include "contentlibrarywidget.h" +#include "contentlibraryeffect.h" +#include "contentlibraryeffectsmodel.h" #include "contentlibrarymaterial.h" #include "contentlibrarymaterialsmodel.h" #include "contentlibrarytexture.h" #include "contentlibrarytexturesmodel.h" +#include "contentlibraryiconprovider.h" #include "utils/filedownloader.h" #include "utils/fileextractor.h" +#include "utils/multifiledownloader.h" #include #include @@ -24,13 +28,16 @@ #include #include +#include #include +#include #include #include #include #include #include #include +#include #include #include #include @@ -59,7 +66,20 @@ bool ContentLibraryWidget::eventFilter(QObject *obj, QEvent *event) Model *model = document->currentModel(); QTC_ASSERT(model, return false); - if (m_materialToDrag) { + if (m_effectToDrag) { + QMouseEvent *me = static_cast(event); + if ((me->globalPos() - m_dragStartPoint).manhattanLength() > 20) { + QByteArray data; + QMimeData *mimeData = new QMimeData; + QDataStream stream(&data, QIODevice::WriteOnly); + stream << m_effectToDrag->type(); + mimeData->setData(Constants::MIME_TYPE_BUNDLE_EFFECT, data); + + emit bundleEffectDragStarted(m_effectToDrag); + model->startDrag(mimeData, m_effectToDrag->icon().toLocalFile()); + m_effectToDrag = nullptr; + } + } else if (m_materialToDrag) { QMouseEvent *me = static_cast(event); if ((me->globalPosition().toPoint() - m_dragStartPoint).manhattanLength() > 20 && m_materialToDrag->isDownloaded()) { @@ -91,6 +111,7 @@ bool ContentLibraryWidget::eventFilter(QObject *obj, QEvent *event) } } } else if (event->type() == QMouseEvent::MouseButtonRelease) { + m_effectToDrag = nullptr; m_materialToDrag = nullptr; m_textureToDrag = nullptr; setIsDragging(false); @@ -104,6 +125,7 @@ ContentLibraryWidget::ContentLibraryWidget() , m_materialsModel(new ContentLibraryMaterialsModel(this)) , m_texturesModel(new ContentLibraryTexturesModel("Textures", this)) , m_environmentsModel(new ContentLibraryTexturesModel("Environments", this)) + , m_effectsModel(new ContentLibraryEffectsModel(this)) { qmlRegisterType("WebFetcher", 1, 0, "FileDownloader"); qmlRegisterType("WebFetcher", 1, 0, "FileExtractor"); @@ -113,6 +135,8 @@ ContentLibraryWidget::ContentLibraryWidget() m_quickWidget->quickWidget()->setObjectName(Constants::OBJECT_NAME_CONTENT_LIBRARY); m_quickWidget->setResizeMode(QQuickWidget::SizeRootObjectToView); + m_quickWidget->engine()->addImageProvider(QStringLiteral("contentlibrary"), + new Internal::ContentLibraryIconProvider); m_quickWidget->engine()->addImportPath(propertyEditorResourcesPath() + "/imports"); m_quickWidget->setClearColor(Theme::getColor(Theme::Color::DSpanelBackground)); @@ -121,6 +145,8 @@ ContentLibraryWidget::ContentLibraryWidget() + "/textures"; m_texturesUrl = m_baseUrl + "/Textures"; + m_textureIconsUrl = m_baseUrl + "/icons/Textures"; + m_environmentIconsUrl = m_baseUrl + "/icons/Environments"; m_environmentsUrl = m_baseUrl + "/Environments"; m_downloadPath = Paths::bundlesPathSetting(); @@ -147,10 +173,11 @@ ContentLibraryWidget::ContentLibraryWidget() auto map = m_quickWidget->registerPropertyMap("ContentLibraryBackend"); - map->setProperties({{"rootView", QVariant::fromValue(this)}, - {"materialsModel", QVariant::fromValue(m_materialsModel.data())}, - {"texturesModel", QVariant::fromValue(m_texturesModel.data())}, - {"environmentsModel", QVariant::fromValue(m_environmentsModel.data())}}); + map->setProperties({{"rootView", QVariant::fromValue(this)}, + {"materialsModel", QVariant::fromValue(m_materialsModel.data())}, + {"texturesModel", QVariant::fromValue(m_texturesModel.data())}, + {"environmentsModel", QVariant::fromValue(m_environmentsModel.data())}, + {"effectsModel", QVariant::fromValue(m_effectsModel.data())}}); reloadQmlSource(); } @@ -178,8 +205,231 @@ void ContentLibraryWidget::loadTextureBundle() if (fetchTextureBundleMetadata(bundleDir) && fetchTextureBundleIcons(bundleDir)) { QString bundleIconPath = m_downloadPath + "/TextureBundleIcons"; QVariantMap metaData = readBundleMetadata(); - m_texturesModel->loadTextureBundle(m_texturesUrl, bundleIconPath, metaData); - m_environmentsModel->loadTextureBundle(m_environmentsUrl, bundleIconPath, metaData); + m_texturesModel->loadTextureBundle(m_texturesUrl, m_textureIconsUrl, bundleIconPath, metaData); + m_environmentsModel->loadTextureBundle(m_environmentsUrl, m_environmentIconsUrl, + bundleIconPath, metaData); + } +} + +std::tuple ContentLibraryWidget::compareTextureMetaFiles( + const QString &existingMetaFilePath, const QString downloadedMetaFilePath) +{ + QVariantMap existingMeta; + QFile existingFile(existingMetaFilePath); + if (existingFile.open(QIODeviceBase::ReadOnly | QIODeviceBase::Text)) + existingMeta = QJsonDocument::fromJson(existingFile.readAll()).toVariant().toMap(); + + QVariantMap downloadedMeta; + QFile downloadedFile(downloadedMetaFilePath); + if (downloadedFile.open(QIODeviceBase::ReadOnly | QIODeviceBase::Text)) + downloadedMeta = QJsonDocument::fromJson(downloadedFile.readAll()).toVariant().toMap(); + + int existingVersion = existingMeta["version"].toInt(); + int downloadedVersion = downloadedMeta["version"].toInt(); + + if (existingVersion != downloadedVersion) { + qWarning() << "We're not comparing local vs downloaded textures metadata because they are " + "of different versions"; + return {}; + } + + QVariantMap existingItems = existingMeta["image_items"].toMap(); + QVariantMap downloadedItems = downloadedMeta["image_items"].toMap(); + + QStringList existingKeys = existingItems.keys(); + QStringList downloadedKeys = downloadedItems.keys(); + + QSet existing(existingKeys.cbegin(), existingKeys.cend()); + QSet downloaded(downloadedKeys.cbegin(), downloadedKeys.cend()); + + const QSet newFiles = downloaded - existing; + const QSet commonFiles = downloaded & existing; + + QVariantMap modifiedFileEntries; + + for (const QString &file: commonFiles) { + QString existingCsum = existingItems[file].toMap()["checksum"].toString(); + QString downloadedCsum = downloadedItems[file].toMap()["checksum"].toString(); + + if (existingCsum != downloadedCsum) + modifiedFileEntries[file] = downloadedItems[file]; + } + + QVariantMap newFileEntries; + for (const QString &path: newFiles) + newFileEntries[path] = downloadedItems[path]; + + return std::make_tuple(existingItems, newFileEntries, modifiedFileEntries); +} + +void ContentLibraryWidget::fetchNewTextureIcons(const QVariantMap &existingFiles, + const QVariantMap &newFiles, + const QString &existingMetaFilePath, + const QDir &bundleDir) +{ + QStringList fileList = Utils::transform(newFiles.keys(), [](const QString &file) -> QString { + return file + ".png"; + }); + + auto multidownloader = new MultiFileDownloader(this); + multidownloader->setBaseUrl(QString(m_baseUrl + "/icons")); + multidownloader->setFiles(fileList); + multidownloader->setTargetDirPath(m_downloadPath + "/TextureBundleIcons"); + + auto downloader = new FileDownloader(this); + downloader->setDownloadEnabled(true); + downloader->setProbeUrl(false); + + downloader->setUrl(multidownloader->nextUrl()); + downloader->setTargetFilePath(multidownloader->nextTargetPath()); + + QObject::connect(multidownloader, &MultiFileDownloader::nextUrlChanged, downloader, [=]() { + downloader->setUrl(multidownloader->nextUrl()); + }); + + QObject::connect(multidownloader, &MultiFileDownloader::nextTargetPathChanged, downloader, [=]() { + downloader->setTargetFilePath(multidownloader->nextTargetPath()); + }); + + multidownloader->setDownloader(downloader); + + QVariantMap files = existingFiles; + files.insert(newFiles); + + QObject::connect(multidownloader, &MultiFileDownloader::finishedChanged, this, + [multidownloader, files, existingMetaFilePath, this, bundleDir]() { + multidownloader->deleteLater(); + + QVariantMap newMap; + newMap["version"] = TextureBundleMetadataVersion; + newMap["image_items"] = files; + + QJsonObject jobj = QJsonObject::fromVariantMap(newMap); + QJsonDocument doc(jobj); + QByteArray data = doc.toJson(); + + QFile existingFile(existingMetaFilePath); + if (existingFile.open(QIODeviceBase::WriteOnly | QIODeviceBase::Text)) { + existingFile.write(data); + existingFile.flush(); + } + + if (fetchTextureBundleIcons(bundleDir)) { + QString bundleIconPath = m_downloadPath + "/TextureBundleIcons"; + QVariantMap metaData = readBundleMetadata(); + m_texturesModel->loadTextureBundle(m_texturesUrl, m_textureIconsUrl, bundleIconPath, + metaData); + m_environmentsModel->loadTextureBundle(m_environmentsUrl, m_environmentIconsUrl, + bundleIconPath, metaData); + } + + }); + + multidownloader->start(); +} + +QStringList ContentLibraryWidget::saveNewTextures(const QDir &bundleDir, const QStringList &newFiles) +{ + int newFileExpirationDays = QmlDesignerPlugin::settings() + .value(DesignerSettingsKey::CONTENT_LIBRARY_NEW_FLAG_EXPIRATION_DAYS) + .toInt(); + + int newFileExpirationSecs = newFileExpirationDays * 24 * 3600; + + QString newFilesPath = bundleDir.filePath(".new_textures_on_server.json"); + + QFile jsonFile(newFilesPath); + if (jsonFile.exists()) { + jsonFile.open(QFile::ReadOnly | QFile::Text); + + qint64 now = QDateTime::currentSecsSinceEpoch(); + QByteArray existingData = jsonFile.readAll(); + QJsonDocument doc = QJsonDocument::fromJson(existingData); + jsonFile.close(); + + QJsonObject mainObj = doc.object(); + if (mainObj.value("version").toInt() > TextureBundleMetadataVersion) { + qDebug() << "Existing version of cached 'New Items' does not have a known version."; + + // TODO: do simple save new file + return newFiles; + } + + QJsonValue jsonValue = mainObj.value("image_items"); + QJsonArray imageItems = jsonValue.toArray(); + + // remove those files that are older than N days (configurable via QSettings) + imageItems = Utils::filtered(imageItems, [newFileExpirationSecs, now](const QJsonValue &v) { + qint64 time = v["time"].toInt(); + if (now - time >= newFileExpirationSecs) + return false; + + return true; + }); + + QStringList pruned = Utils::transform(imageItems, [](const QJsonValue &value) -> QString { + return value.toObject()["file"].toString(); + }); + + // filter out files from newFiles that already exist in the document + + QStringList newFilesNow = Utils::filtered(newFiles, [&imageItems](const QString &file) { + bool contains = Utils::anyOf(imageItems, [file](const QJsonValue &v) { + if (!v.isObject()) + return false; + + QJsonObject o = v.toObject(); + if (!o.contains("file")) + return false; + + bool hasFile = (o["file"] == file); + return hasFile; + + return false; + }); + return !contains; + }); + + // add the filtered out files to the doc. + for (const QString &file: newFilesNow) { + QJsonObject obj({{"file", file}, {"time", now}}); + imageItems.push_back(obj); + } + + mainObj["image_items"] = imageItems; + + // save the json file. + doc.setObject(mainObj); + QByteArray data = doc.toJson(); + + jsonFile.open(QFile::WriteOnly | QFile::Text); + jsonFile.write(data); + jsonFile.close(); + + return newFilesNow + pruned; + } else { + qint64 now = QDateTime::currentSecsSinceEpoch(); + + QJsonArray texturesFoundNow = Utils::transform(newFiles, [now](const QString &file) { + QJsonObject obj({{"file", file}, {"time", now}}); + return QJsonValue(obj); + }); + + QVariantMap varMap; + varMap["version"] = TextureBundleMetadataVersion; + varMap["image_items"] = texturesFoundNow; + + QJsonObject mainObj({{"version", TextureBundleMetadataVersion}, + {"image_items", texturesFoundNow}}); + + QJsonDocument doc(mainObj); + QByteArray data = doc.toJson(); + + jsonFile.open(QFile::WriteOnly | QFile::Text); + jsonFile.write(data); + jsonFile.close(); + + return newFiles; } } @@ -188,8 +438,7 @@ bool ContentLibraryWidget::fetchTextureBundleMetadata(const QDir &bundleDir) QString filePath = bundleDir.filePath("texture_bundle.json"); QFileInfo fi(filePath); - if (fi.exists() && fi.size() > 0) - return true; + bool metaFileExists = fi.exists() && fi.size() > 0; QString metaFileUrl = m_baseUrl + "/texture_bundle.zip"; FileDownloader *downloader = new FileDownloader(this); @@ -197,11 +446,26 @@ bool ContentLibraryWidget::fetchTextureBundleMetadata(const QDir &bundleDir) downloader->setProbeUrl(false); downloader->setDownloadEnabled(true); + QObject::connect(downloader, &FileDownloader::downloadFailed, this, [=]() { + if (metaFileExists) { + if (fetchTextureBundleIcons(bundleDir)) { + QString bundleIconPath = m_downloadPath + "/TextureBundleIcons"; + QVariantMap metaData = readBundleMetadata(); + m_texturesModel->loadTextureBundle(m_texturesUrl, m_textureIconsUrl, bundleIconPath, + metaData); + m_environmentsModel->loadTextureBundle(m_environmentsUrl, m_environmentIconsUrl, + bundleIconPath, metaData); + } + } + }); + QObject::connect(downloader, &FileDownloader::finishedChanged, this, [=]() { FileExtractor *extractor = new FileExtractor(this); extractor->setArchiveName(downloader->completeBaseName()); extractor->setSourceFile(downloader->outputFile()); - extractor->setTargetPath(bundleDir.absolutePath()); + if (!metaFileExists) + extractor->setTargetPath(bundleDir.absolutePath()); + extractor->setAlwaysCreateDir(false); extractor->setClearTargetPathContents(false); @@ -209,11 +473,35 @@ bool ContentLibraryWidget::fetchTextureBundleMetadata(const QDir &bundleDir) downloader->deleteLater(); extractor->deleteLater(); + if (metaFileExists) { + QVariantMap newFiles, existing; + QVariantMap modifiedFilesEntries; + + std::tie(existing, newFiles, modifiedFilesEntries) = + compareTextureMetaFiles(filePath, extractor->targetPath() + "/texture_bundle.json"); + + const QStringList newFilesKeys = newFiles.keys(); + const QStringList actualNewFiles = saveNewTextures(bundleDir, newFilesKeys); + + m_texturesModel->setModifiedFileEntries(modifiedFilesEntries); + m_texturesModel->setNewFileEntries(actualNewFiles); + + m_environmentsModel->setModifiedFileEntries(modifiedFilesEntries); + m_environmentsModel->setNewFileEntries(actualNewFiles); + + if (newFiles.count() > 0) { + fetchNewTextureIcons(existing, newFiles, filePath, bundleDir); + return; + } + } + if (fetchTextureBundleIcons(bundleDir)) { QString bundleIconPath = m_downloadPath + "/TextureBundleIcons"; QVariantMap metaData = readBundleMetadata(); - m_texturesModel->loadTextureBundle(m_texturesUrl, bundleIconPath, metaData); - m_environmentsModel->loadTextureBundle(m_environmentsUrl, bundleIconPath, metaData); + m_texturesModel->loadTextureBundle(m_texturesUrl, m_textureIconsUrl, bundleIconPath, + metaData); + m_environmentsModel->loadTextureBundle(m_environmentsUrl, m_environmentIconsUrl, + bundleIconPath, metaData); } }); @@ -253,8 +541,10 @@ bool ContentLibraryWidget::fetchTextureBundleIcons(const QDir &bundleDir) QString bundleIconPath = m_downloadPath + "/TextureBundleIcons"; QVariantMap metaData = readBundleMetadata(); - m_texturesModel->loadTextureBundle(m_texturesUrl, bundleIconPath, metaData); - m_environmentsModel->loadTextureBundle(m_environmentsUrl, bundleIconPath, metaData); + m_texturesModel->loadTextureBundle(m_texturesUrl, m_textureIconsUrl, bundleIconPath, + metaData); + m_environmentsModel->loadTextureBundle(m_environmentsUrl, m_environmentIconsUrl, + bundleIconPath, metaData); }); extractor->extract(); @@ -264,6 +554,48 @@ bool ContentLibraryWidget::fetchTextureBundleIcons(const QDir &bundleDir) return false; } +void ContentLibraryWidget::markTextureUpdated(const QString &textureKey) +{ + static QRegularExpression re("([^/]+)/([^/]+)/.*"); + QString category = re.match(textureKey).captured(1); + QString subcategory = re.match(textureKey).captured(2); + + QString checksumOnServer; + if (category == "Textures") + checksumOnServer = m_texturesModel->removeModifiedFileEntry(textureKey); + else if (category == "Environments") + checksumOnServer = m_environmentsModel->removeModifiedFileEntry(textureKey); + + QJsonObject metaDataObj; + QFile jsonFile(m_downloadPath + "/texture_bundle.json"); + if (jsonFile.open(QIODevice::ReadOnly | QIODevice::Text)) { + metaDataObj = QJsonDocument::fromJson(jsonFile.readAll()).object(); + jsonFile.close(); + } + + QJsonObject imageItems = metaDataObj["image_items"].toObject(); + + QJsonObject oldImageItem = imageItems[textureKey].toObject(); + oldImageItem["checksum"] = checksumOnServer; + imageItems[textureKey] = oldImageItem; + + metaDataObj["image_items"] = imageItems; + + QJsonDocument outDoc(metaDataObj); + QByteArray data = outDoc.toJson(); + + QFile outFile(m_downloadPath + "/texture_bundle.json"); + if (outFile.open(QIODeviceBase::WriteOnly | QIODeviceBase::Text)) { + outFile.write(data); + outFile.flush(); + } + + if (category == "Textures") + m_texturesModel->markTextureHasNoUpdates(subcategory, textureKey); + else if (category == "Environments") + m_environmentsModel->markTextureHasNoUpdates(subcategory, textureKey); +} + QList ContentLibraryWidget::createToolBarWidgets() { return {}; @@ -311,6 +643,7 @@ void ContentLibraryWidget::setHasQuick3DImport(bool b) emit hasQuick3DImportChanged(); m_materialsModel->updateIsEmpty(); + m_effectsModel->updateIsEmpty(); } bool ContentLibraryWidget::hasMaterialLibrary() const @@ -341,6 +674,7 @@ void ContentLibraryWidget::reloadQmlSource() void ContentLibraryWidget::updateSearch() { m_materialsModel->setSearchText(m_filterText); + m_effectsModel->setSearchText(m_filterText); m_texturesModel->setSearchText(m_filterText); m_environmentsModel->setSearchText(m_filterText); m_quickWidget->update(); @@ -376,6 +710,14 @@ QString ContentLibraryWidget::findTextureBundlePath() return texBundleDir.path(); } +void ContentLibraryWidget::startDragEffect(QmlDesigner::ContentLibraryEffect *eff, + const QPointF &mousePos) +{ + m_effectToDrag = eff; + m_dragStartPoint = mousePos.toPoint(); + setIsDragging(true); +} + void ContentLibraryWidget::startDragMaterial(QmlDesigner::ContentLibraryMaterial *mat, const QPointF &mousePos) { @@ -436,4 +778,9 @@ QPointer ContentLibraryWidget::environmentsModel() return m_environmentsModel; } +QPointer ContentLibraryWidget::effectsModel() const +{ + return m_effectsModel; +} + } // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/contentlibrary/contentlibrarywidget.h b/src/plugins/qmldesigner/components/contentlibrary/contentlibrarywidget.h index 6d4ba51a300..9f9fd167c32 100644 --- a/src/plugins/qmldesigner/components/contentlibrary/contentlibrarywidget.h +++ b/src/plugins/qmldesigner/components/contentlibrary/contentlibrarywidget.h @@ -18,10 +18,12 @@ class StudioQuickWidget; namespace QmlDesigner { -class ContentLibraryTexture; +class ContentLibraryEffect; +class ContentLibraryEffectsModel; class ContentLibraryMaterial; -class ContentLibraryTexturesModel; class ContentLibraryMaterialsModel; +class ContentLibraryTexture; +class ContentLibraryTexturesModel; class ContentLibraryWidget : public QFrame { @@ -54,15 +56,19 @@ public: QPointer materialsModel() const; QPointer texturesModel() const; QPointer environmentsModel() const; + QPointer effectsModel() const; + Q_INVOKABLE void startDragEffect(QmlDesigner::ContentLibraryEffect *eff, const QPointF &mousePos); Q_INVOKABLE void startDragMaterial(QmlDesigner::ContentLibraryMaterial *mat, const QPointF &mousePos); Q_INVOKABLE void startDragTexture(QmlDesigner::ContentLibraryTexture *tex, const QPointF &mousePos); Q_INVOKABLE void addImage(QmlDesigner::ContentLibraryTexture *tex); Q_INVOKABLE void addTexture(QmlDesigner::ContentLibraryTexture *tex); Q_INVOKABLE void addLightProbe(QmlDesigner::ContentLibraryTexture *tex); Q_INVOKABLE void updateSceneEnvState(); + Q_INVOKABLE void markTextureUpdated(const QString &textureKey); signals: + void bundleEffectDragStarted(QmlDesigner::ContentLibraryEffect *bundleEff); void bundleMaterialDragStarted(QmlDesigner::ContentLibraryMaterial *bundleMat); void bundleTextureDragStarted(QmlDesigner::ContentLibraryTexture *bundleTex); void addTextureRequested(const QString texPath, QmlDesigner::AddTextureMode mode); @@ -83,16 +89,23 @@ private: QVariantMap readBundleMetadata(); bool fetchTextureBundleMetadata(const QDir &bundleDir); bool fetchTextureBundleIcons(const QDir &bundleDir); + void fetchNewTextureIcons(const QVariantMap &existingFiles, const QVariantMap &newFiles, + const QString &existingMetaFilePath, const QDir &bundleDir); + std::tuple compareTextureMetaFiles( + const QString &existingMetaFile, const QString downloadedMetaFile); + QStringList saveNewTextures(const QDir &bundleDir, const QStringList &newFiles); QScopedPointer m_quickWidget; QPointer m_materialsModel; QPointer m_texturesModel; QPointer m_environmentsModel; + QPointer m_effectsModel; QShortcut *m_qmlSourceUpdateShortcut = nullptr; QString m_filterText; + ContentLibraryEffect *m_effectToDrag = nullptr; ContentLibraryMaterial *m_materialToDrag = nullptr; ContentLibraryTexture *m_textureToDrag = nullptr; QPoint m_dragStartPoint; @@ -102,6 +115,8 @@ private: bool m_isDragging = false; QString m_baseUrl; QString m_texturesUrl; + QString m_textureIconsUrl; + QString m_environmentIconsUrl; QString m_environmentsUrl; QString m_downloadPath; }; diff --git a/src/plugins/qmldesigner/components/curveeditor/curveeditormodel.cpp b/src/plugins/qmldesigner/components/curveeditor/curveeditormodel.cpp index 802a75c2bf8..84c8cb56bd8 100644 --- a/src/plugins/qmldesigner/components/curveeditor/curveeditormodel.cpp +++ b/src/plugins/qmldesigner/components/curveeditor/curveeditormodel.cpp @@ -319,7 +319,7 @@ std::vector resolveSmallCurves(const std::vector &frames) if (frame.hasData() && !out.empty()) { QEasingCurve curve = frame.data().toEasingCurve(); // One-segment-curve: Since (0,0) is implicit => 3 - if (curve.toCubicSpline().count() == 3) { + if (curve.toCubicSpline().size() == 3) { Keyframe &previous = out.back(); #if 0 // Do not resolve when two adjacent keyframes have the same value. diff --git a/src/plugins/qmldesigner/components/curveeditor/curveeditorstyle.h b/src/plugins/qmldesigner/components/curveeditor/curveeditorstyle.h index 163f998d7d1..8193bdbf530 100644 --- a/src/plugins/qmldesigner/components/curveeditor/curveeditorstyle.h +++ b/src/plugins/qmldesigner/components/curveeditor/curveeditorstyle.h @@ -59,7 +59,7 @@ struct KeyframeItemStyleOption double size = 10.0; QColor color = QColor(200, 200, 0); QColor selectionColor = QColor(200, 200, 200); - QColor lockedColor = QColor(50, 50, 50); + QColor lockedColor = QColor(80, 80, 80); QColor unifiedColor = QColor(250, 50, 250); QColor splitColor = QColor(0, 250, 0); }; @@ -71,7 +71,7 @@ struct CurveItemStyleOption QColor errorColor = QColor(200, 0, 0); QColor selectionColor = QColor(200, 200, 200); QColor easingCurveColor = QColor(200, 0, 200); - QColor lockedColor = QColor(50, 50, 50); + QColor lockedColor = QColor(120, 120, 120); QColor hoverColor = QColor(200, 0, 200); }; diff --git a/src/plugins/qmldesigner/components/curveeditor/curveeditorview.cpp b/src/plugins/qmldesigner/components/curveeditor/curveeditorview.cpp index 2a401fc4fb1..1d0b38b3f15 100644 --- a/src/plugins/qmldesigner/components/curveeditor/curveeditorview.cpp +++ b/src/plugins/qmldesigner/components/curveeditor/curveeditorview.cpp @@ -338,7 +338,7 @@ void CurveEditorView::commitKeyframes(TreeItem *item) attachEasingCurve(group, pos.x(), segment.easingCurve()); } else if (frame.interpolation() == Keyframe::Interpolation::Easing) { QVariant data = frame.data(); - if (data.type() == static_cast(QMetaType::QEasingCurve)) + if (data.typeId() == static_cast(QMetaType::QEasingCurve)) attachEasingCurve(group, pos.x(), data.value()); } } diff --git a/src/plugins/qmldesigner/components/curveeditor/curvesegment.cpp b/src/plugins/qmldesigner/components/curveeditor/curvesegment.cpp index 2608e65144c..76fa2a2ffc2 100644 --- a/src/plugins/qmldesigner/components/curveeditor/curvesegment.cpp +++ b/src/plugins/qmldesigner/components/curveeditor/curvesegment.cpp @@ -244,7 +244,7 @@ void CurveSegment::extendWithEasingCurve(QPainterPath &path, const QEasingCurve }; QVector points = curve.toCubicSpline(); - int numSegments = points.count() / 3; + int numSegments = points.size() / 3; for (int i = 0; i < numSegments; i++) { QPointF p1 = mapEasing(m_left.position(), m_right.position(), points.at(i * 3)); QPointF p2 = mapEasing(m_left.position(), m_right.position(), points.at(i * 3 + 1)); @@ -264,7 +264,7 @@ void CurveSegment::extend(QPainterPath &path) const extendWithEasingCurve(path, easingCurve()); } else if (interpolation() == Keyframe::Interpolation::Easing) { QVariant data = m_right.data(); - if (data.isValid() && data.type() == static_cast(QMetaType::QEasingCurve)) { + if (data.isValid() && data.typeId() == static_cast(QMetaType::QEasingCurve)) { extendWithEasingCurve(path, data.value()); } } diff --git a/src/plugins/qmldesigner/components/curveeditor/detail/graphicsview.cpp b/src/plugins/qmldesigner/components/curveeditor/detail/graphicsview.cpp index 819a52d2159..b7548020723 100644 --- a/src/plugins/qmldesigner/components/curveeditor/detail/graphicsview.cpp +++ b/src/plugins/qmldesigner/components/curveeditor/detail/graphicsview.cpp @@ -252,13 +252,21 @@ void GraphicsView::setPinned(TreeItem *item) void GraphicsView::setZoomX(double zoom, const QPoint &pivot) { - applyZoom(zoom, m_zoomY, pivot); + if (pivot.isNull()) + applyZoom(zoom, m_zoomY, viewportCenter()); + else + applyZoom(zoom, m_zoomY, pivot); + viewport()->update(); } void GraphicsView::setZoomY(double zoom, const QPoint &pivot) { - applyZoom(m_zoomX, zoom, pivot); + if (pivot.isNull()) + applyZoom(zoom, m_zoomY, viewportCenter()); + else + applyZoom(zoom, m_zoomY, pivot); + viewport()->update(); } @@ -514,7 +522,14 @@ void GraphicsView::applyZoom(double x, double y, const QPoint &pivot) m_transform = QTransform::fromScale(scaleX, scaleY); m_scene->setComponentTransform(m_transform); - QRectF sr = m_scene->rect().adjusted( + QRectF sr = m_scene->rect(); + if (sr.isNull()) { + sr.setLeft(m_scene->animationRangeMin()); + sr.setRight(m_scene->animationRangeMax()); + sr = m_transform.mapRect(sr); + } + + sr = sr.adjusted( -m_style.valueAxisWidth - m_style.canvasMargin, -m_style.timeAxisHeight - m_style.canvasMargin, m_style.canvasMargin, @@ -750,4 +765,10 @@ QRectF GraphicsView::rangeMaxHandle(const QRectF &rect) return QRectF(QPointF(handle, bottom), size); } +QPoint GraphicsView::viewportCenter() const +{ + QPoint viewCenter = viewport()->rect().center(); + return viewport()->mapToGlobal(viewCenter); +} + } // End namespace QmlDesigner. diff --git a/src/plugins/qmldesigner/components/curveeditor/detail/graphicsview.h b/src/plugins/qmldesigner/components/curveeditor/detail/graphicsview.h index c292d0203da..120249b605f 100644 --- a/src/plugins/qmldesigner/components/curveeditor/detail/graphicsview.h +++ b/src/plugins/qmldesigner/components/curveeditor/detail/graphicsview.h @@ -136,6 +136,8 @@ private: QRectF rangeMaxHandle(const QRectF &rect); + QPoint viewportCenter() const; + private: bool m_dragging; diff --git a/src/plugins/qmldesigner/components/curveeditor/detail/treeview.cpp b/src/plugins/qmldesigner/components/curveeditor/detail/treeview.cpp index c8b99d61c8d..82d8e2dd99d 100644 --- a/src/plugins/qmldesigner/components/curveeditor/detail/treeview.cpp +++ b/src/plugins/qmldesigner/components/curveeditor/detail/treeview.cpp @@ -37,6 +37,8 @@ TreeView::TreeView(CurveEditorModel *model, QWidget *parent) setStyle(model->style()); + header()->setMinimumSectionSize(20); + header()->setSectionResizeMode(0, QHeaderView::Stretch); header()->setSectionResizeMode(1, QHeaderView::Fixed); header()->setSectionResizeMode(2, QHeaderView::Fixed); diff --git a/src/plugins/qmldesigner/components/curveeditor/keyframe.cpp b/src/plugins/qmldesigner/components/curveeditor/keyframe.cpp index aa698c35da5..8e71e593c3b 100644 --- a/src/plugins/qmldesigner/components/curveeditor/keyframe.cpp +++ b/src/plugins/qmldesigner/components/curveeditor/keyframe.cpp @@ -149,7 +149,7 @@ void Keyframe::setRightHandle(const QPointF &pos) void Keyframe::setData(const QVariant &data) { - if (data.type() == static_cast(QMetaType::QEasingCurve)) + if (data.typeId() == static_cast(QMetaType::QEasingCurve)) m_interpolation = Interpolation::Easing; m_data = data; diff --git a/src/plugins/qmldesigner/components/edit3d/bakelights.cpp b/src/plugins/qmldesigner/components/edit3d/bakelights.cpp index 53c7e53df9d..c0ff5de2af3 100644 --- a/src/plugins/qmldesigner/components/edit3d/bakelights.cpp +++ b/src/plugins/qmldesigner/components/edit3d/bakelights.cpp @@ -321,11 +321,13 @@ void BakeLights::showSetupDialog() if (!m_dataModel) m_dataModel = new BakeLightsDataModel(m_view); - m_dataModel->reset(); - - auto data = m_dataModel->view3dNode().auxiliaryData(bakeLightsManualProperty); - if (data) - m_manualMode = data->toBool(); + if (!m_dataModel->reset()) { + m_manualMode = true; + } else { + auto data = m_dataModel->view3dNode().auxiliaryData(bakeLightsManualProperty); + if (data) + m_manualMode = data->toBool(); + } if (!m_setupDialog) { // Show non-modal progress dialog with cancel button diff --git a/src/plugins/qmldesigner/components/edit3d/bakelightsconnectionmanager.cpp b/src/plugins/qmldesigner/components/edit3d/bakelightsconnectionmanager.cpp index 9fb41b46865..e8faa42833d 100644 --- a/src/plugins/qmldesigner/components/edit3d/bakelightsconnectionmanager.cpp +++ b/src/plugins/qmldesigner/components/edit3d/bakelightsconnectionmanager.cpp @@ -29,7 +29,7 @@ void BakeLightsConnectionManager::dispatchCommand(const QVariant &command, { static const int commandType = QMetaType::type("PuppetToCreatorCommand"); - if (command.userType() == commandType) { + if (command.typeId() == commandType) { auto cmd = command.value(); switch (cmd.type()) { case PuppetToCreatorCommand::BakeLightsProgress: diff --git a/src/plugins/qmldesigner/components/edit3d/bakelightsdatamodel.cpp b/src/plugins/qmldesigner/components/edit3d/bakelightsdatamodel.cpp index 36d192a9244..e812bb6d00e 100644 --- a/src/plugins/qmldesigner/components/edit3d/bakelightsdatamodel.cpp +++ b/src/plugins/qmldesigner/components/edit3d/bakelightsdatamodel.cpp @@ -36,7 +36,7 @@ BakeLightsDataModel::~BakeLightsDataModel() int BakeLightsDataModel::rowCount(const QModelIndex &) const { - return m_dataList.count(); + return m_dataList.size(); } QHash BakeLightsDataModel::roleNames() const @@ -57,7 +57,7 @@ QHash BakeLightsDataModel::roleNames() const QVariant BakeLightsDataModel::data(const QModelIndex &index, int role) const { - QTC_ASSERT(index.isValid() && index.row() < m_dataList.count(), return {}); + QTC_ASSERT(index.isValid() && index.row() < m_dataList.size(), return {}); QTC_ASSERT(roleNames().contains(role), return {}); QByteArray roleName = roleNames().value(role); @@ -102,7 +102,7 @@ QVariant BakeLightsDataModel::data(const QModelIndex &index, int role) const bool BakeLightsDataModel::setData(const QModelIndex &index, const QVariant &value, int role) { - QTC_ASSERT(index.isValid() && index.row() < m_dataList.count(), return false); + QTC_ASSERT(index.isValid() && index.row() < m_dataList.size(), return false); QTC_ASSERT(roleNames().contains(role), return false); QByteArray roleName = roleNames().value(role); @@ -130,10 +130,12 @@ bool BakeLightsDataModel::setData(const QModelIndex &index, const QVariant &valu return changed; } -void BakeLightsDataModel::reset() +// Return value of false indicates unexpected property assignments were detected, which means manual +// mode for baking setup should be enforced. +bool BakeLightsDataModel::reset() { if (!m_view || !m_view->model()) - return; + return true; beginResetModel(); m_dataList.clear(); @@ -152,6 +154,8 @@ void BakeLightsDataModel::reset() QList compLightList; QList unexposedList; + bool forceManualMode = false; + // Note: We are always loading base state values for baking. If users want to bake // differently for different states, they need to setup things manually for now. // Same goes if they want to use any unusual bindings in baking properties. @@ -169,23 +173,42 @@ void BakeLightsDataModel::reset() if (node.hasBindingProperty("bakedLightmap")) { ModelNode blm = node.bindingProperty("bakedLightmap").resolveToModelNode(); if (blm.isValid()) { - if (blm.hasVariantProperty("enabled")) + if (blm.hasVariantProperty("enabled")) { data.enabled = blm.variantProperty("enabled").value().toBool(); - else + } else { data.enabled = true; + if (blm.hasProperty("enabled")) + forceManualMode = true; + } } + } else if (node.hasProperty("bakedLightmap")) { + forceManualMode = true; } if (node.hasVariantProperty("lightmapBaseResolution")) data.resolution = node.variantProperty("lightmapBaseResolution").value().toInt(); + else if (node.hasProperty("lightmapBaseResolution")) + forceManualMode = true; + if (node.hasVariantProperty("usedInBakedLighting")) data.inUse = node.variantProperty("usedInBakedLighting").value().toBool(); + else if (node.hasProperty("usedInBakedLighting")) + forceManualMode = true; + modelList.append(data); } else if (node.metaInfo().isQtQuick3DLight()) { if (node.hasVariantProperty("bakeMode")) { - data.bakeMode = node.variantProperty("bakeMode").value() - .value().toString(); + // Enum properties that have binding can still resolve as variant property, + // so check if the value is actually valid enum + QString bakeModeStr = node.variantProperty("bakeMode").value() + .value().toString(); + if (bakeModeStr.startsWith("Light.BakeMode")) + data.bakeMode = bakeModeStr; + else + forceManualMode = true; } else { data.bakeMode = "Light.BakeModeDisabled"; + if (node.hasProperty("bakeMode")) + forceManualMode = true; } lightList.append(data); } @@ -211,16 +234,29 @@ void BakeLightsDataModel::reset() if (subName == "bakedLightmap") { ModelNode blm = prop.toBindingProperty().resolveToModelNode(); if (blm.isValid()) { - if (blm.hasVariantProperty("enabled")) + if (blm.hasVariantProperty("enabled")) { propData.enabled = blm.variantProperty("enabled").value().toBool(); - else + } else { propData.enabled = true; + if (blm.hasProperty("enabled")) + forceManualMode = true; + } + } else { + forceManualMode = true; } } - if (subName == "lightmapBaseResolution") - propData.resolution = prop.toVariantProperty().value().toInt(); - if (subName == "usedInBakedLighting") - propData.inUse = prop.toVariantProperty().value().toBool(); + if (subName == "lightmapBaseResolution") { + if (prop.isVariantProperty()) + propData.resolution = prop.toVariantProperty().value().toInt(); + else + forceManualMode = true; + } + if (subName == "usedInBakedLighting") { + if (prop.isVariantProperty()) + propData.inUse = prop.toVariantProperty().value().toBool(); + else + forceManualMode = true; + } } } compModelList.append(propData); @@ -231,9 +267,17 @@ void BakeLightsDataModel::reset() if (prop.name().startsWith(dotName)) { PropertyName subName = prop.name().mid(dotName.size()); if (subName == "bakeMode") { - propData.bakeMode = prop.toVariantProperty().value() - .value() - .toString(); + if (prop.isVariantProperty()) { + QString bakeModeStr = prop.toVariantProperty().value() + .value() + .toString(); + if (bakeModeStr.startsWith("Light.BakeMode")) + propData.bakeMode = bakeModeStr; + else + forceManualMode = true; + } else { + forceManualMode = true; + } } } } @@ -292,6 +336,8 @@ void BakeLightsDataModel::reset() } endResetModel(); + + return !forceManualMode; } void BakeLightsDataModel::apply() diff --git a/src/plugins/qmldesigner/components/edit3d/bakelightsdatamodel.h b/src/plugins/qmldesigner/components/edit3d/bakelightsdatamodel.h index 313c09cf459..3ed7bfeed3c 100644 --- a/src/plugins/qmldesigner/components/edit3d/bakelightsdatamodel.h +++ b/src/plugins/qmldesigner/components/edit3d/bakelightsdatamodel.h @@ -38,7 +38,7 @@ public: QHash roleNames() const override; bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; - void reset(); + bool reset(); void apply(); ModelNode view3dNode() const { return m_view3dNode; } diff --git a/src/plugins/qmldesigner/components/edit3d/edit3dactions.cpp b/src/plugins/qmldesigner/components/edit3d/edit3dactions.cpp index 12d2dd05528..4ffdf0e801c 100644 --- a/src/plugins/qmldesigner/components/edit3d/edit3dactions.cpp +++ b/src/plugins/qmldesigner/components/edit3d/edit3dactions.cpp @@ -98,25 +98,6 @@ bool Edit3DAction::isEnabled(const SelectionContext &selectionContext) const return isVisible(selectionContext); } -Edit3DCameraAction::Edit3DCameraAction(const QByteArray &menuId, - View3DActionType type, - const QString &description, - const QKeySequence &key, - bool checkable, - bool checked, - const QIcon &icon, - Edit3DView *view, - SelectionContextOperation selectionAction) - : Edit3DAction(menuId, type, description, key, checkable, checked, icon, view, selectionAction) -{ -} - -bool Edit3DCameraAction::isEnabled(const SelectionContext &selectionContext) const -{ - return Utils::anyOf(selectionContext.selectedModelNodes(), - [](const ModelNode &node) { return node.metaInfo().isQtQuick3DCamera(); }); -} - Edit3DParticleSeekerAction::Edit3DParticleSeekerAction(const QByteArray &menuId, View3DActionType type, Edit3DView *view) diff --git a/src/plugins/qmldesigner/components/edit3d/edit3dactions.h b/src/plugins/qmldesigner/components/edit3d/edit3dactions.h index 4cf1ab837d8..3a451ea40d5 100644 --- a/src/plugins/qmldesigner/components/edit3d/edit3dactions.h +++ b/src/plugins/qmldesigner/components/edit3d/edit3dactions.h @@ -91,23 +91,6 @@ private: View3DActionType m_actionType; }; -class Edit3DCameraAction : public Edit3DAction -{ -public: - Edit3DCameraAction(const QByteArray &menuId, - View3DActionType type, - const QString &description, - const QKeySequence &key, - bool checkable, - bool checked, - const QIcon &icon, - Edit3DView *view, - SelectionContextOperation selectionAction = nullptr); - -protected: - bool isEnabled(const SelectionContext &selectionContext) const override; -}; - class Edit3DParticleSeekerAction : public Edit3DAction { public: diff --git a/src/plugins/qmldesigner/components/edit3d/edit3dview.cpp b/src/plugins/qmldesigner/components/edit3d/edit3dview.cpp index 10d62a5dc21..a96ca59cae7 100644 --- a/src/plugins/qmldesigner/components/edit3d/edit3dview.cpp +++ b/src/plugins/qmldesigner/components/edit3d/edit3dview.cpp @@ -106,17 +106,6 @@ Edit3DWidget *Edit3DView::edit3DWidget() const return m_edit3DWidget.data(); } -void Edit3DView::selectedNodesChanged([[maybe_unused]] const QList &selectedNodeList, - [[maybe_unused]] const QList &lastSelectedNodeList) -{ - SelectionContext selectionContext(this); - selectionContext.setUpdateMode(SelectionContext::UpdateMode::Fast); - if (m_alignCamerasAction) - m_alignCamerasAction->currentContextChanged(selectionContext); - if (m_alignViewAction) - m_alignViewAction->currentContextChanged(selectionContext); -} - void Edit3DView::renderImage3DChanged(const QImage &img) { edit3DWidget()->canvas()->updateRenderImage(img); @@ -149,6 +138,7 @@ void Edit3DView::updateActiveScene3D(const QVariantMap &sceneState) qint32 newActiveScene = sceneState[sceneKey].value(); edit3DWidget()->canvas()->updateActiveScene(newActiveScene); model()->setActive3DSceneId(newActiveScene); + updateAlignActionStates(); } if (sceneState.contains(selectKey)) @@ -298,6 +288,22 @@ void Edit3DView::handleEntriesChanged() m_edit3DWidget->updateCreateSubMenu(entriesMap.values()); } +void Edit3DView::updateAlignActionStates() +{ + bool enabled = false; + + ModelNode activeScene = active3DSceneNode(); + if (activeScene.isValid()) { + const QList nodes = activeScene.allSubModelNodes(); + enabled = ::Utils::anyOf(nodes, [](const ModelNode &node) { + return node.metaInfo().isQtQuick3DCamera(); + }); + } + + m_alignCamerasAction->action()->setEnabled(enabled); + m_alignViewAction->action()->setEnabled(enabled); +} + void Edit3DView::modelAboutToBeDetached(Model *model) { m_isBakingLightsSupported = false; @@ -364,6 +370,8 @@ void Edit3DView::nodeAtPosReady(const ModelNode &modelNode, const QVector3D &pos } } else if (m_nodeAtPosReqType == NodeAtPosReqType::BundleMaterialDrop) { emitCustomNotification("drop_bundle_material", {modelNode}); // To ContentLibraryView + } else if (m_nodeAtPosReqType == NodeAtPosReqType::BundleEffectDrop) { + emitCustomNotification("drop_bundle_effect", {modelNode}, {pos3d}); // To ContentLibraryView } else if (m_nodeAtPosReqType == NodeAtPosReqType::TextureDrop) { emitCustomNotification("apply_texture_to_model3D", {modelNode, m_droppedModelNode}); } else if (m_nodeAtPosReqType == NodeAtPosReqType::AssetDrop) { @@ -377,6 +385,21 @@ void Edit3DView::nodeAtPosReady(const ModelNode &modelNode, const QVector3D &pos m_nodeAtPosReqType = NodeAtPosReqType::None; } +void Edit3DView::nodeReparented(const ModelNode &, + const NodeAbstractProperty &, + const NodeAbstractProperty &, + PropertyChangeFlags) +{ + updateAlignActionStates(); +} + +void Edit3DView::nodeRemoved(const ModelNode &, + const NodeAbstractProperty &, + PropertyChangeFlags) +{ + updateAlignActionStates(); +} + void Edit3DView::sendInputEvent(QInputEvent *e) const { if (nodeInstanceView()) @@ -581,25 +604,27 @@ void Edit3DView::createEdit3DActions() toolbarIcon(Theme::fitToView_medium), this); - m_alignCamerasAction = new Edit3DCameraAction( + m_alignCamerasAction = new Edit3DAction( QmlDesigner::Constants::EDIT3D_ALIGN_CAMERAS, View3DActionType::AlignCamerasToView, - QCoreApplication::translate("AlignCamerasToViewAction", "Align Selected Cameras to View"), + QCoreApplication::translate("AlignCamerasToViewAction", "Align Cameras to View"), QKeySequence(), false, false, toolbarIcon(Theme::alignToCam_medium), this); + m_alignCamerasAction->action()->setEnabled(false); - m_alignViewAction = new Edit3DCameraAction( + m_alignViewAction = new Edit3DAction( QmlDesigner::Constants::EDIT3D_ALIGN_VIEW, View3DActionType::AlignViewToCamera, - QCoreApplication::translate("AlignCamerasToViewAction", "Align View to Selected Camera"), + QCoreApplication::translate("AlignCamerasToViewAction", "Align View to Camera"), QKeySequence(), false, false, toolbarIcon(Theme::alignToView_medium), this); + m_alignViewAction->action()->setEnabled(false); m_cameraModeAction = new Edit3DAction( QmlDesigner::Constants::EDIT3D_EDIT_CAMERA, @@ -922,7 +947,7 @@ void Edit3DView::addQuick3DImport() { DesignDocument *document = QmlDesignerPlugin::instance()->currentDesignDocument(); if (document && !document->inFileComponentModelActive() && model() - && Utils::addImportWithCheck( + && ModelUtils::addImportWithCheck( "QtQuick3D", [](const Import &import) { return !import.hasVersion() || import.majorVersion() >= 6; }, model())) { @@ -953,6 +978,12 @@ void Edit3DView::dropBundleMaterial(const QPointF &pos) emitView3DAction(View3DActionType::GetNodeAtPos, pos); } +void Edit3DView::dropBundleEffect(const QPointF &pos) +{ + m_nodeAtPosReqType = NodeAtPosReqType::BundleEffectDrop; + emitView3DAction(View3DActionType::GetNodeAtPos, pos); +} + void Edit3DView::dropTexture(const ModelNode &textureNode, const QPointF &pos) { m_nodeAtPosReqType = NodeAtPosReqType::TextureDrop; diff --git a/src/plugins/qmldesigner/components/edit3d/edit3dview.h b/src/plugins/qmldesigner/components/edit3d/edit3dview.h index cd3e686d3bb..6e6b82948e5 100644 --- a/src/plugins/qmldesigner/components/edit3d/edit3dview.h +++ b/src/plugins/qmldesigner/components/edit3d/edit3dview.h @@ -26,7 +26,6 @@ class BakeLights; class Edit3DWidget; class Edit3DAction; class Edit3DBakeLightsAction; -class Edit3DCameraAction; class QMLDESIGNERCOMPONENTS_EXPORT Edit3DView : public AbstractView { @@ -39,14 +38,19 @@ public: Edit3DWidget *edit3DWidget() const; - void selectedNodesChanged(const QList &selectedNodeList, const QList &lastSelectedNodeList) override; void renderImage3DChanged(const QImage &img) override; void updateActiveScene3D(const QVariantMap &sceneState) override; void modelAttached(Model *model) override; void modelAboutToBeDetached(Model *model) override; void importsChanged(const Imports &addedImports, const Imports &removedImports) override; - void customNotification(const AbstractView *view, const QString &identifier, const QList &nodeList, const QList &data) override; + void customNotification(const AbstractView *view, const QString &identifier, + const QList &nodeList, const QList &data) override; void nodeAtPosReady(const ModelNode &modelNode, const QVector3D &pos3d) override; + void nodeReparented(const ModelNode &node, const NodeAbstractProperty &newPropertyParent, + const NodeAbstractProperty &oldPropertyParent, + PropertyChangeFlags propertyChange) override; + void nodeRemoved(const ModelNode &removedNode, const NodeAbstractProperty &parentProperty, + PropertyChangeFlags propertyChange) override; void sendInputEvent(QInputEvent *e) const; void edit3DViewResized(const QSize &size) const; @@ -65,6 +69,7 @@ public: void startContextMenu(const QPoint &pos); void dropMaterial(const ModelNode &matNode, const QPointF &pos); void dropBundleMaterial(const QPointF &pos); + void dropBundleEffect(const QPointF &pos); void dropTexture(const ModelNode &textureNode, const QPointF &pos); void dropComponent(const ItemLibraryEntry &entry, const QPointF &pos); void dropAsset(const QString &file, const QPointF &pos); @@ -76,6 +81,7 @@ private slots: private: enum class NodeAtPosReqType { + BundleEffectDrop, BundleMaterialDrop, ComponentDrop, MaterialDrop, @@ -91,6 +97,7 @@ private: void checkImports(); void handleEntriesChanged(); void showMaterialPropertiesView(); + void updateAlignActionStates(); Edit3DAction *createSelectBackgroundColorAction(QAction *syncBackgroundColorAction); Edit3DAction *createGridColorSelectionAction(); @@ -110,8 +117,8 @@ private: Edit3DAction *m_rotateToolAction = nullptr; Edit3DAction *m_scaleToolAction = nullptr; Edit3DAction *m_fitAction = nullptr; - Edit3DCameraAction *m_alignCamerasAction = nullptr; - Edit3DCameraAction *m_alignViewAction = nullptr; + Edit3DAction *m_alignCamerasAction = nullptr; + Edit3DAction *m_alignViewAction = nullptr; Edit3DAction *m_cameraModeAction = nullptr; Edit3DAction *m_orientationModeAction = nullptr; Edit3DAction *m_editLightAction = nullptr; diff --git a/src/plugins/qmldesigner/components/edit3d/edit3dwidget.cpp b/src/plugins/qmldesigner/components/edit3d/edit3dwidget.cpp index a217e396d9c..163cfc951ed 100644 --- a/src/plugins/qmldesigner/components/edit3d/edit3dwidget.cpp +++ b/src/plugins/qmldesigner/components/edit3d/edit3dwidget.cpp @@ -21,6 +21,7 @@ #include #include +#include #include #include #include @@ -167,6 +168,11 @@ Edit3DWidget::Edit3DWidget(Edit3DView *view) createContextMenu(); + m_mcuLabel = new QLabel(this); + m_mcuLabel->setText(tr("MCU project does not support Qt Quick 3D.")); + m_mcuLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + fillLayout->addWidget(m_mcuLabel.data()); + // Onboarding label contains instructions for new users how to get 3D content into the project m_onboardingLabel = new QLabel(this); QString labelText = @@ -413,7 +419,24 @@ void Edit3DWidget::showCanvas(bool show) m_canvas->updateRenderImage(emptyImage); } m_canvas->setVisible(show); - m_onboardingLabel->setVisible(!show); + + if (show) { + m_onboardingLabel->setVisible(false); + m_mcuLabel->setVisible(false); + } else { + bool quick3dAllowed = true; + const DesignerMcuManager &mcuManager = DesignerMcuManager::instance(); + if (mcuManager.isMCUProject()) { + const QStringList mcuAllowedList = mcuManager.allowedImports(); + if (!mcuAllowedList.contains("QtQuick3d")) + quick3dAllowed = false; + } + + m_onboardingLabel->setVisible(quick3dAllowed); + m_mcuLabel->setVisible(!quick3dAllowed); + } + + } QMenu *Edit3DWidget::visibilityTogglesMenu() const @@ -451,9 +474,8 @@ void Edit3DWidget::showContextMenu(const QPoint &pos, const ModelNode &modelNode m_contextMenuTarget = modelNode; m_contextMenuPos3d = pos3d; - const bool isValid = modelNode.isValid(); const bool isModel = modelNode.metaInfo().isQtQuick3DModel(); - const bool isCamera = isValid && modelNode.metaInfo().isQtQuick3DCamera(); + const bool allowAlign = view()->edit3DAction(View3DActionType::AlignCamerasToView)->action()->isEnabled(); const bool isSingleComponent = view()->hasSingleSelectedModelNode() && modelNode.isComponent(); const bool anyNodeSelected = view()->hasSelectedModelNodes(); const bool selectionExcludingRoot = anyNodeSelected && !view()->rootModelNode().isSelected(); @@ -468,8 +490,8 @@ void Edit3DWidget::showContextMenu(const QPoint &pos, const ModelNode &modelNode m_pasteAction->setEnabled(isPasteAvailable()); m_deleteAction->setEnabled(selectionExcludingRoot); m_fitSelectedAction->setEnabled(anyNodeSelected); - m_alignCameraAction->setEnabled(isCamera); - m_alignViewAction->setEnabled(isCamera); + m_alignCameraAction->setEnabled(allowAlign); + m_alignViewAction->setEnabled(allowAlign); m_selectParentAction->setEnabled(selectionExcludingRoot); m_toggleGroupAction->setEnabled(true); m_bakeLightsAction->setVisible(view()->bakeLightsAction()->action()->isVisible()); @@ -517,6 +539,7 @@ void Edit3DWidget::dragEnterEvent(QDragEnterEvent *dragEnterEvent) } else if (actionManager.externalDragHasSupportedAssets(dragEnterEvent->mimeData()) || dragEnterEvent->mimeData()->hasFormat(Constants::MIME_TYPE_MATERIAL) || dragEnterEvent->mimeData()->hasFormat(Constants::MIME_TYPE_BUNDLE_MATERIAL) + || dragEnterEvent->mimeData()->hasFormat(Constants::MIME_TYPE_BUNDLE_EFFECT) || dragEnterEvent->mimeData()->hasFormat(Constants::MIME_TYPE_TEXTURE)) { dragEnterEvent->acceptProposedAction(); } else if (dragEnterEvent->mimeData()->hasFormat(Constants::MIME_TYPE_ITEM_LIBRARY_INFO)) { @@ -560,6 +583,13 @@ void Edit3DWidget::dropEvent(QDropEvent *dropEvent) return; } + // handle dropping bundle effects + if (dropEvent->mimeData()->hasFormat(Constants::MIME_TYPE_BUNDLE_EFFECT)) { + m_view->dropBundleEffect(pos); + m_view->model()->endDrag(); + return; + } + // handle dropping from component view if (dropEvent->mimeData()->hasFormat(Constants::MIME_TYPE_ITEM_LIBRARY_INFO)) { if (!m_draggedEntry.name().isEmpty()) diff --git a/src/plugins/qmldesigner/components/edit3d/edit3dwidget.h b/src/plugins/qmldesigner/components/edit3d/edit3dwidget.h index eecd52345fa..f764f068bf4 100644 --- a/src/plugins/qmldesigner/components/edit3d/edit3dwidget.h +++ b/src/plugins/qmldesigner/components/edit3d/edit3dwidget.h @@ -70,6 +70,7 @@ private: QPointer m_view; QPointer m_canvas; QPointer m_onboardingLabel; + QPointer m_mcuLabel; QPointer m_toolBox; Core::IContext *m_context = nullptr; QPointer m_visibilityTogglesMenu; diff --git a/src/plugins/qmldesigner/components/formeditor/abstractformeditortool.cpp b/src/plugins/qmldesigner/components/formeditor/abstractformeditortool.cpp index c6cbb8252c4..774b4c0d911 100644 --- a/src/plugins/qmldesigner/components/formeditor/abstractformeditortool.cpp +++ b/src/plugins/qmldesigner/components/formeditor/abstractformeditortool.cpp @@ -260,7 +260,7 @@ void AbstractFormEditorTool::mouseReleaseEvent(const QList & ite QmlItemNode currentSelectedNode; - if (view()->selectedModelNodes().count() == 1) { + if (view()->selectedModelNodes().size() == 1) { currentSelectedNode = view()->selectedModelNodes().constFirst(); if (!containsItemNode(itemList, currentSelectedNode)) { diff --git a/src/plugins/qmldesigner/components/formeditor/anchorindicator.cpp b/src/plugins/qmldesigner/components/formeditor/anchorindicator.cpp index 7d75c71c229..8a8a3e524ff 100644 --- a/src/plugins/qmldesigner/components/formeditor/anchorindicator.cpp +++ b/src/plugins/qmldesigner/components/formeditor/anchorindicator.cpp @@ -64,7 +64,7 @@ void AnchorIndicator::setItems(const QList &itemList) { clear(); - if (itemList.count() == 1) { + if (itemList.size() == 1) { m_formEditorItem = itemList.constFirst(); QmlItemNode sourceQmlItemNode = m_formEditorItem->qmlItemNode(); if (!sourceQmlItemNode.modelNode().isRootNode()) { diff --git a/src/plugins/qmldesigner/components/formeditor/backgroundaction.cpp b/src/plugins/qmldesigner/components/formeditor/backgroundaction.cpp index a9d72be8ddb..37dfafad9a2 100644 --- a/src/plugins/qmldesigner/components/formeditor/backgroundaction.cpp +++ b/src/plugins/qmldesigner/components/formeditor/backgroundaction.cpp @@ -45,7 +45,7 @@ QWidget *BackgroundAction::createWidget(QWidget *parent) auto comboBox = new QComboBox(parent); comboBox->setFixedWidth(42); - for (int i = 0; i < colors().count(); ++i) { + for (int i = 0; i < colors().size(); ++i) { comboBox->addItem(tr("")); comboBox->setItemIcon(i, iconForColor((colors().at(i)))); } @@ -62,7 +62,7 @@ QWidget *BackgroundAction::createWidget(QWidget *parent) void BackgroundAction::emitBackgroundChanged(int index) { - if (index < colors().count()) + if (index < colors().size()) emit backgroundChanged(colors().at(index)); } diff --git a/src/plugins/qmldesigner/components/formeditor/bindingindicator.cpp b/src/plugins/qmldesigner/components/formeditor/bindingindicator.cpp index e5a990d1efe..57958416937 100644 --- a/src/plugins/qmldesigner/components/formeditor/bindingindicator.cpp +++ b/src/plugins/qmldesigner/components/formeditor/bindingindicator.cpp @@ -91,7 +91,7 @@ void BindingIndicator::setItems(const QList &itemList) { clear(); - if (itemList.count() == 1) { + if (itemList.size() == 1) { m_formEditorItem = itemList.constFirst(); const QmlItemNode qmlItemNode = m_formEditorItem->qmlItemNode(); diff --git a/src/plugins/qmldesigner/components/formeditor/movetool.cpp b/src/plugins/qmldesigner/components/formeditor/movetool.cpp index 449cdd745cd..76b8f9a5f64 100644 --- a/src/plugins/qmldesigner/components/formeditor/movetool.cpp +++ b/src/plugins/qmldesigner/components/formeditor/movetool.cpp @@ -94,9 +94,9 @@ void MoveTool::mouseMoveEvent(const QList &itemList, const FormEditorItem *movingItem = m_movingItems.constFirst(); - if (m_movingItems.count() > 1 - || (movingItem->qmlItemNode().canBereparentedTo(containerItem->qmlItemNode()))) - m_moveManipulator.reparentTo(containerItem, MoveManipulator::EnforceReparent); + if (m_movingItems.size() > 1 + || (movingItem->qmlItemNode().canBereparentedTo(containerItem->qmlItemNode()))) + m_moveManipulator.reparentTo(containerItem, MoveManipulator::EnforceReparent); } } diff --git a/src/plugins/qmldesigner/components/formeditor/seekerslider.cpp b/src/plugins/qmldesigner/components/formeditor/seekerslider.cpp index 804f061657a..a6bfd25873f 100644 --- a/src/plugins/qmldesigner/components/formeditor/seekerslider.cpp +++ b/src/plugins/qmldesigner/components/formeditor/seekerslider.cpp @@ -97,9 +97,11 @@ QWidget *SeekerSliderAction::createWidget(QWidget *parent) QObject::connect(m_defaultSlider, &SeekerSlider::valueChanged, slider, &SeekerSlider::setValue); QObject::connect(slider, &SeekerSlider::valueChanged, m_defaultSlider, &SeekerSlider::setValue); QObject::connect(m_defaultSlider, &QSlider::rangeChanged, slider, &QSlider::setRange); + QObject::connect(this, &QWidgetAction::enabledChanged, slider, &QSlider::setEnabled); slider->setValue(m_defaultSlider->value()); slider->setMaxValue(m_defaultSlider->maxValue()); + slider->setEnabled(isEnabled()); return slider; } diff --git a/src/plugins/qmldesigner/components/formeditor/snapper.cpp b/src/plugins/qmldesigner/components/formeditor/snapper.cpp index da50f92a81d..828a7132118 100644 --- a/src/plugins/qmldesigner/components/formeditor/snapper.cpp +++ b/src/plugins/qmldesigner/components/formeditor/snapper.cpp @@ -426,7 +426,7 @@ double Snapper::snappingDistance() const static QLineF mergedHorizontalLine(const QList &lineList) { - if (lineList.count() == 1) + if (lineList.size() == 1) return lineList.constFirst(); double minimumX = std::numeric_limits::max(); @@ -444,7 +444,7 @@ static QLineF mergedHorizontalLine(const QList &lineList) static QLineF mergedVerticalLine(const QList &lineList) { - if (lineList.count() == 1) + if (lineList.size() == 1) return lineList.constFirst(); double minimumY = std::numeric_limits::max(); diff --git a/src/plugins/qmldesigner/components/formeditor/toolbox.cpp b/src/plugins/qmldesigner/components/formeditor/toolbox.cpp index 47a9503b2d3..53da8773eb6 100644 --- a/src/plugins/qmldesigner/components/formeditor/toolbox.cpp +++ b/src/plugins/qmldesigner/components/formeditor/toolbox.cpp @@ -34,11 +34,13 @@ ToolBox::ToolBox(QWidget *parentWidget) Utils::StyleHelper::setPanelWidget(m_leftToolBar, false); Utils::StyleHelper::setPanelWidgetSingleRow(m_leftToolBar, false); m_leftToolBar->setFixedHeight(Theme::toolbarSize()); + m_leftToolBar->setStyleSheet("QToolBarExtension {margin-top: 5px;}"); Utils::StyleHelper::setPanelWidget(m_rightToolBar, false); Utils::StyleHelper::setPanelWidgetSingleRow(m_rightToolBar, false); m_rightToolBar->setFixedHeight(Theme::toolbarSize()); m_rightToolBar->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Expanding); + m_rightToolBar->setStyleSheet("QToolBarExtension {margin-top: 5px;}"); auto stretchToolbar = new QToolBar(this); Utils::StyleHelper::setPanelWidget(stretchToolbar, false); diff --git a/src/plugins/qmldesigner/components/integration/designdocument.cpp b/src/plugins/qmldesigner/components/integration/designdocument.cpp index fecaaefadf3..089efb87cdd 100644 --- a/src/plugins/qmldesigner/components/integration/designdocument.cpp +++ b/src/plugins/qmldesigner/components/integration/designdocument.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include #include @@ -62,7 +63,8 @@ namespace QmlDesigner { */ DesignDocument::DesignDocument(ProjectStorage &projectStorage, ExternalDependenciesInterface &externalDependencies) - : m_documentModel(Model::create("QtQuick.Item", 1, 0)) + : m_documentModel( + Model::create("QtQuick.Item", 1, 0, nullptr, std::make_unique())) , m_subComponentManager(new SubComponentManager(m_documentModel.get(), externalDependencies)) , m_rewriterView(new RewriterView(externalDependencies, RewriterView::Amend)) , m_documentLoaded(false) @@ -149,7 +151,11 @@ const AbstractView *DesignDocument::view() const ModelPointer DesignDocument::createInFileComponentModel() { - auto model = Model::create("QtQuick.Item", 1, 0); + auto model = Model::create("QtQuick.Item", + 1, + 0, + nullptr, + std::make_unique()); model->setFileUrl(m_documentModel->fileUrl()); model->setMetaInfo(m_documentModel->metaInfo()); @@ -205,8 +211,7 @@ void DesignDocument::moveNodesToPosition(const QList &nodes, const st targetNode = view.firstSelectedModelNode(); // in case we copy and paste a selection we paste in the parent item - if ((view.selectedModelNodes().count() == movingNodes.count()) - && targetNode.hasParentProperty()) { + if ((view.selectedModelNodes().size() == movingNodes.size()) && targetNode.hasParentProperty()) { targetNode = targetNode.parentProperty().parentModelNode(); } else if (view.selectedModelNodes().isEmpty()) { // if selection is empty and copied nodes are all 3D nodes, paste them under the active scene @@ -366,7 +371,7 @@ void DesignDocument::loadDocument(QPlainTextEdit *edit) connect(m_documentTextModifier.data(), &TextModifier::textChanged, this, &DesignDocument::updateQrcFiles); - m_documentModel->setTextModifier(m_documentTextModifier.data()); + m_rewriterView->setTextModifier(m_documentTextModifier.data()); m_inFileComponentTextModifier.reset(); @@ -386,6 +391,8 @@ void DesignDocument::changeToDocumentModel() if (edit) edit->document()->clearUndoRedoStacks(); + m_rewriterView->setTextModifier(m_documentTextModifier.data()); + m_inFileComponentModel.reset(); m_inFileComponentTextModifier.reset(); @@ -426,7 +433,8 @@ void DesignDocument::changeToInFileComponentModel(ComponentTextModifier *textMod edit->document()->clearUndoRedoStacks(); m_inFileComponentModel = createInFileComponentModel(); - m_inFileComponentModel->setTextModifier(m_inFileComponentTextModifier.data()); + + m_rewriterView->setTextModifier(m_inFileComponentTextModifier.data()); viewManager().attachRewriterView(); viewManager().attachViewsExceptRewriterAndComponetView(); diff --git a/src/plugins/qmldesigner/components/integration/designdocumentview.cpp b/src/plugins/qmldesigner/components/integration/designdocumentview.cpp index 4a1c92ad0aa..9d0deef713b 100644 --- a/src/plugins/qmldesigner/components/integration/designdocumentview.cpp +++ b/src/plugins/qmldesigner/components/integration/designdocumentview.cpp @@ -227,7 +227,7 @@ void DesignDocumentView::copyModelNodes(const QList &nodesToCopy, DesignDocumentView view{externalDependencies}; copyModel->attachView(&view); - if (selectedNodes.count() == 1) { + if (selectedNodes.size() == 1) { const ModelNode &selectedNode = selectedNodes.constFirst(); if (!selectedNode.isValid()) @@ -253,7 +253,6 @@ void DesignDocumentView::copyModelNodes(const QList &nodesToCopy, view.toClipboard(); } - } }// namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/itemlibrary/assetimportupdatetreeitem.cpp b/src/plugins/qmldesigner/components/itemlibrary/assetimportupdatetreeitem.cpp index 6fa6ec4c342..a5d84605dd2 100644 --- a/src/plugins/qmldesigner/components/itemlibrary/assetimportupdatetreeitem.cpp +++ b/src/plugins/qmldesigner/components/itemlibrary/assetimportupdatetreeitem.cpp @@ -32,7 +32,7 @@ void AssetImportUpdateTreeItem::clear() int AssetImportUpdateTreeItem::childCount() const { - return m_children.count(); + return m_children.size(); } int AssetImportUpdateTreeItem::rowOfItem() const diff --git a/src/plugins/qmldesigner/components/itemlibrary/itemlibraryaddimportmodel.cpp b/src/plugins/qmldesigner/components/itemlibrary/itemlibraryaddimportmodel.cpp index 41a9c6b5f4a..66afa19f8b8 100644 --- a/src/plugins/qmldesigner/components/itemlibrary/itemlibraryaddimportmodel.cpp +++ b/src/plugins/qmldesigner/components/itemlibrary/itemlibraryaddimportmodel.cpp @@ -28,12 +28,12 @@ ItemLibraryAddImportModel::~ItemLibraryAddImportModel() int ItemLibraryAddImportModel::rowCount(const QModelIndex & /*parent*/) const { - return m_importList.count(); + return m_importList.size(); } QVariant ItemLibraryAddImportModel::data(const QModelIndex &index, int role) const { - if (!index.isValid() || index.row() >= m_importList.count()) + if (!index.isValid() || index.row() >= m_importList.size()) return {}; Import import = m_importList[index.row()]; diff --git a/src/plugins/qmldesigner/components/itemlibrary/itemlibraryassetimportdialog.cpp b/src/plugins/qmldesigner/components/itemlibrary/itemlibraryassetimportdialog.cpp index 91f403f218a..f8a9fd97718 100644 --- a/src/plugins/qmldesigner/components/itemlibrary/itemlibraryassetimportdialog.cpp +++ b/src/plugins/qmldesigner/components/itemlibrary/itemlibraryassetimportdialog.cpp @@ -109,7 +109,7 @@ ItemLibraryAssetImportDialog::ItemLibraryAssetImportDialog( connect(ui->buttonBox->button(QDialogButtonBox::Ok), &QPushButton::clicked, this, &ItemLibraryAssetImportDialog::onImport); - ui->buttonBox->button(QDialogButtonBox::Close)->setDefault(true); + ui->buttonBox->button(QDialogButtonBox::Ok)->setDefault(true); ui->advancedSettingsButton->setStyleSheet( "QPushButton#advancedSettingsButton {background-color: transparent}"); diff --git a/src/plugins/qmldesigner/components/itemlibrary/itemlibraryassetimporter.cpp b/src/plugins/qmldesigner/components/itemlibrary/itemlibraryassetimporter.cpp index d141b88dc85..99f07cb8a8a 100644 --- a/src/plugins/qmldesigner/components/itemlibrary/itemlibraryassetimporter.cpp +++ b/src/plugins/qmldesigner/components/itemlibrary/itemlibraryassetimporter.cpp @@ -216,7 +216,7 @@ void ItemLibraryAssetImporter::parseFiles(const QStringList &filePaths, addInfo(progressTitle); notifyProgress(0, progressTitle); uint count = 0; - double quota = 100.0 / filePaths.count(); + double quota = 100.0 / filePaths.size(); std::function progress = [this, quota, &count, &progressTitle](double value) { notifyProgress(qRound(quota * (count + value)), progressTitle); }; @@ -709,7 +709,7 @@ void ItemLibraryAssetImporter::finalizeQuick3DImport() try { RewriterTransaction transaction = model->rewriterView()->beginRewriterTransaction( QByteArrayLiteral("ItemLibraryAssetImporter::finalizeQuick3DImport")); - bool success = Utils::addImportsWithCheck(m_requiredImports, model); + bool success = ModelUtils::addImportsWithCheck(m_requiredImports, model); if (!success) addError(tr("Failed to insert import statement into qml document.")); transaction.commit(); diff --git a/src/plugins/qmldesigner/components/itemlibrary/itemlibrarycategoriesmodel.cpp b/src/plugins/qmldesigner/components/itemlibrary/itemlibrarycategoriesmodel.cpp index 187bd38e2fa..824027e5558 100644 --- a/src/plugins/qmldesigner/components/itemlibrary/itemlibrarycategoriesmodel.cpp +++ b/src/plugins/qmldesigner/components/itemlibrary/itemlibrarycategoriesmodel.cpp @@ -27,12 +27,12 @@ ItemLibraryCategoriesModel::~ItemLibraryCategoriesModel() int ItemLibraryCategoriesModel::rowCount(const QModelIndex &) const { - return m_categoryList.count(); + return m_categoryList.size(); } QVariant ItemLibraryCategoriesModel::data(const QModelIndex &index, int role) const { - if (!index.isValid() || index.row() >= m_categoryList.count()) { + if (!index.isValid() || index.row() >= m_categoryList.size()) { qWarning() << Q_FUNC_INFO << "invalid index requested"; return {}; } diff --git a/src/plugins/qmldesigner/components/itemlibrary/itemlibraryitemsmodel.cpp b/src/plugins/qmldesigner/components/itemlibrary/itemlibraryitemsmodel.cpp index 8ee40b6d248..65330af023a 100644 --- a/src/plugins/qmldesigner/components/itemlibrary/itemlibraryitemsmodel.cpp +++ b/src/plugins/qmldesigner/components/itemlibrary/itemlibraryitemsmodel.cpp @@ -21,7 +21,7 @@ ItemLibraryItemsModel::~ItemLibraryItemsModel() int ItemLibraryItemsModel::rowCount(const QModelIndex &) const { - return m_itemList.count(); + return m_itemList.size(); } QVariant ItemLibraryItemsModel::data(const QModelIndex &index, int role) const diff --git a/src/plugins/qmldesigner/components/itemlibrary/itemlibrarymodel.cpp b/src/plugins/qmldesigner/components/itemlibrary/itemlibrarymodel.cpp index 21f2e6aa55d..3f611a0dbba 100644 --- a/src/plugins/qmldesigner/components/itemlibrary/itemlibrarymodel.cpp +++ b/src/plugins/qmldesigner/components/itemlibrary/itemlibrarymodel.cpp @@ -228,12 +228,12 @@ ItemLibraryModel::~ItemLibraryModel() int ItemLibraryModel::rowCount(const QModelIndex & /*parent*/) const { - return m_importList.count(); + return m_importList.size(); } QVariant ItemLibraryModel::data(const QModelIndex &index, int role) const { - if (!index.isValid() || index.row() >= m_importList.count()) + if (!index.isValid() || index.row() >= m_importList.size()) return {}; if (m_roleNames.contains(role)) { @@ -317,15 +317,17 @@ void ItemLibraryModel::update(ItemLibraryInfo *itemLibraryInfo, Model *model) ProjectExplorer::Project *project = ProjectExplorer::ProjectManager::projectForFile(qmlFileName); QString projectName = project ? project->displayName() : ""; - QString materialBundlePrefix = QLatin1String(Constants::COMPONENT_BUNDLES_FOLDER).mid(1); - materialBundlePrefix.append(".MaterialBundle"); + QStringList excludedImports { + QLatin1String(Constants::COMPONENT_BUNDLES_FOLDER).mid(1) + ".MaterialBundle", + QLatin1String(Constants::COMPONENT_BUNDLES_FOLDER).mid(1) + ".EffectBundle" + }; // create import sections const Imports usedImports = model->usedImports(); QHash importHash; for (const Import &import : model->imports()) { if (import.url() != projectName) { - if (import.url() == materialBundlePrefix) + if (excludedImports.contains(import.url())) continue; bool addNew = true; bool isQuick3DAsset = import.url().startsWith("Quick3DAssets."); diff --git a/src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.cpp b/src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.cpp index 445372e24b9..1cbde45ba0b 100644 --- a/src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.cpp +++ b/src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.cpp @@ -82,7 +82,7 @@ bool ItemLibraryWidget::eventFilter(QObject *obj, QEvent *event) // For drag to be handled correctly, we must have the component properly imported // beforehand, so we import the module immediately when the drag starts if (!entry.requiredImport().isEmpty() - && !Utils::addImportWithCheck(entry.requiredImport(), m_model)) { + && !ModelUtils::addImportWithCheck(entry.requiredImport(), m_model)) { qWarning() << __FUNCTION__ << "Required import adding failed:" << entry.requiredImport(); } @@ -217,7 +217,7 @@ QString ItemLibraryWidget::getDependencyImport(const Import &import) const QStringList splitImport = import.url().split('.'); - if (splitImport.count() > 1) { + if (splitImport.size() > 1) { if (prefixDependencies.contains(splitImport.first())) return splitImport.first(); } diff --git a/src/plugins/qmldesigner/components/listmodeleditor/listmodeleditormodel.cpp b/src/plugins/qmldesigner/components/listmodeleditor/listmodeleditormodel.cpp index a1b25c37c87..b6009edc774 100644 --- a/src/plugins/qmldesigner/components/listmodeleditor/listmodeleditormodel.cpp +++ b/src/plugins/qmldesigner/components/listmodeleditor/listmodeleditormodel.cpp @@ -29,10 +29,10 @@ public: QVariant maybeConvertToNumber(const QVariant &value) { - if (value.type() == QVariant::Bool) + if (value.typeId() == QVariant::Bool) return value; - if (value.type() == QVariant::String) { + if (value.typeId() == QVariant::String) { const QString text = value.toString(); if (text == "true") return QVariant(true); diff --git a/src/plugins/qmldesigner/components/materialbrowser/materialbrowsermodel.cpp b/src/plugins/qmldesigner/components/materialbrowser/materialbrowsermodel.cpp index d4aedb1cec9..81ec4cbb3a5 100644 --- a/src/plugins/qmldesigner/components/materialbrowser/materialbrowsermodel.cpp +++ b/src/plugins/qmldesigner/components/materialbrowser/materialbrowsermodel.cpp @@ -4,6 +4,7 @@ #include "materialbrowsermodel.h" #include "designmodewidget.h" +#include "materialbrowserview.h" #include "qmldesignerplugin.h" #include "qmlobjectnode.h" #include "variantproperty.h" @@ -13,8 +14,9 @@ namespace QmlDesigner { -MaterialBrowserModel::MaterialBrowserModel(QObject *parent) +MaterialBrowserModel::MaterialBrowserModel(MaterialBrowserView *view, QObject *parent) : QAbstractListModel(parent) + , m_view(view) { } @@ -24,12 +26,12 @@ MaterialBrowserModel::~MaterialBrowserModel() int MaterialBrowserModel::rowCount(const QModelIndex &) const { - return m_materialList.count(); + return m_materialList.size(); } QVariant MaterialBrowserModel::data(const QModelIndex &index, int role) const { - QTC_ASSERT(index.isValid() && index.row() < m_materialList.count(), return {}); + QTC_ASSERT(index.isValid() && index.row() < m_materialList.size(), return {}); QTC_ASSERT(roleNames().contains(role), return {}); QByteArray roleName = roleNames().value(role); @@ -223,7 +225,7 @@ void MaterialBrowserModel::refreshSearch() // if selected material goes invisible, select nearest material if (!isVisible(m_selectedIndex)) { int inc = 1; - int incCap = m_materialList.count(); + int incCap = m_materialList.size(); while (!isEmpty && inc < incCap) { if (isVisible(m_selectedIndex - inc)) { selectMaterial(m_selectedIndex - inc); @@ -459,10 +461,13 @@ void MaterialBrowserModel::pasteMaterialProperties(int idx) void MaterialBrowserModel::deleteMaterial(int idx) { - if (isValidIndex(idx)) { + if (m_view && isValidIndex(idx)) { ModelNode node = m_materialList[idx]; - if (node.isValid()) - QmlObjectNode(node).destroy(); + if (node.isValid()) { + m_view->executeInTransaction(__FUNCTION__, [&] { + node.destroy(); + }); + } } } diff --git a/src/plugins/qmldesigner/components/materialbrowser/materialbrowsermodel.h b/src/plugins/qmldesigner/components/materialbrowser/materialbrowsermodel.h index 23e6a68973b..24c34394386 100644 --- a/src/plugins/qmldesigner/components/materialbrowser/materialbrowsermodel.h +++ b/src/plugins/qmldesigner/components/materialbrowser/materialbrowsermodel.h @@ -12,6 +12,8 @@ namespace QmlDesigner { +class MaterialBrowserView; + class MaterialBrowserModel : public QAbstractListModel { Q_OBJECT @@ -28,7 +30,7 @@ class MaterialBrowserModel : public QAbstractListModel Q_PROPERTY(QStringList customMaterialSections MEMBER m_customMaterialSections NOTIFY materialSectionsChanged) public: - MaterialBrowserModel(QObject *parent = nullptr); + MaterialBrowserModel(MaterialBrowserView *view, QObject *parent = nullptr); ~MaterialBrowserModel() override; int rowCount(const QModelIndex &parent = QModelIndex()) const override; @@ -125,6 +127,8 @@ private: bool m_hasMaterialLibrary = false; bool m_allPropsCopied = true; QString m_copiedMaterialType; + + QPointer m_view; }; } // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/materialbrowser/materialbrowsertexturesmodel.cpp b/src/plugins/qmldesigner/components/materialbrowser/materialbrowsertexturesmodel.cpp index 4ed241abf98..ec95f3e5d3d 100644 --- a/src/plugins/qmldesigner/components/materialbrowser/materialbrowsertexturesmodel.cpp +++ b/src/plugins/qmldesigner/components/materialbrowser/materialbrowsertexturesmodel.cpp @@ -5,6 +5,7 @@ #include "designmodewidget.h" #include "imageutils.h" +#include "materialbrowserview.h" #include "qmldesignerplugin.h" #include "qmlobjectnode.h" #include "variantproperty.h" @@ -13,8 +14,9 @@ namespace QmlDesigner { -MaterialBrowserTexturesModel::MaterialBrowserTexturesModel(QObject *parent) +MaterialBrowserTexturesModel::MaterialBrowserTexturesModel(MaterialBrowserView *view, QObject *parent) : QAbstractListModel(parent) + , m_view(view) { } @@ -24,12 +26,12 @@ MaterialBrowserTexturesModel::~MaterialBrowserTexturesModel() int MaterialBrowserTexturesModel::rowCount(const QModelIndex &) const { - return m_textureList.count(); + return m_textureList.size(); } QVariant MaterialBrowserTexturesModel::data(const QModelIndex &index, int role) const { - QTC_ASSERT(index.isValid() && index.row() < m_textureList.count(), return {}); + QTC_ASSERT(index.isValid() && index.row() < m_textureList.size(), return {}); QTC_ASSERT(roleNames().contains(role), return {}); if (role == RoleTexSource) { @@ -124,7 +126,7 @@ void MaterialBrowserTexturesModel::refreshSearch() // if selected texture goes invisible, select nearest one if (!isVisible(m_selectedIndex)) { int inc = 1; - int incCap = m_textureList.count(); + int incCap = m_textureList.size(); while (!isEmpty && inc < incCap) { if (isVisible(m_selectedIndex - inc)) { selectTexture(m_selectedIndex - inc); @@ -292,10 +294,13 @@ void MaterialBrowserTexturesModel::duplicateTexture(int idx) void MaterialBrowserTexturesModel::deleteTexture(int idx) { - if (isValidIndex(idx)) { + if (m_view && isValidIndex(idx)) { ModelNode node = m_textureList[idx]; - if (node.isValid()) - QmlObjectNode(node).destroy(); + if (node.isValid()) { + m_view->executeInTransaction(__FUNCTION__, [&] { + node.destroy(); + }); + } } } diff --git a/src/plugins/qmldesigner/components/materialbrowser/materialbrowsertexturesmodel.h b/src/plugins/qmldesigner/components/materialbrowser/materialbrowsertexturesmodel.h index 9cb7c5ac18f..8836d3b5db8 100644 --- a/src/plugins/qmldesigner/components/materialbrowser/materialbrowsertexturesmodel.h +++ b/src/plugins/qmldesigner/components/materialbrowser/materialbrowsertexturesmodel.h @@ -10,6 +10,8 @@ namespace QmlDesigner { +class MaterialBrowserView; + class MaterialBrowserTexturesModel : public QAbstractListModel { Q_OBJECT @@ -20,7 +22,7 @@ class MaterialBrowserTexturesModel : public QAbstractListModel Q_PROPERTY(bool hasSceneEnv READ hasSceneEnv NOTIFY hasSceneEnvChanged) public: - MaterialBrowserTexturesModel(QObject *parent = nullptr); + MaterialBrowserTexturesModel(MaterialBrowserView *view, QObject *parent = nullptr); ~MaterialBrowserTexturesModel() override; int rowCount(const QModelIndex &parent = QModelIndex()) const override; @@ -89,6 +91,8 @@ private: bool m_hasSingleModelSelection = false; bool m_hasSceneEnv = false; + QPointer m_view; + enum { RoleTexHasDynamicProps = Qt::UserRole + 1, RoleTexInternalId, diff --git a/src/plugins/qmldesigner/components/materialbrowser/materialbrowserwidget.cpp b/src/plugins/qmldesigner/components/materialbrowser/materialbrowserwidget.cpp index e2bb82216bb..98a1a5a5def 100644 --- a/src/plugins/qmldesigner/components/materialbrowser/materialbrowserwidget.cpp +++ b/src/plugins/qmldesigner/components/materialbrowser/materialbrowserwidget.cpp @@ -141,8 +141,8 @@ bool MaterialBrowserWidget::eventFilter(QObject *obj, QEvent *event) MaterialBrowserWidget::MaterialBrowserWidget(AsynchronousImageCache &imageCache, MaterialBrowserView *view) : m_materialBrowserView(view) - , m_materialBrowserModel(new MaterialBrowserModel(this)) - , m_materialBrowserTexturesModel(new MaterialBrowserTexturesModel(this)) + , m_materialBrowserModel(new MaterialBrowserModel(view, this)) + , m_materialBrowserTexturesModel(new MaterialBrowserTexturesModel(view, this)) , m_quickWidget(new StudioQuickWidget(this)) , m_previewImageProvider(new PreviewImageProvider()) { @@ -204,7 +204,7 @@ MaterialBrowserWidget::MaterialBrowserWidget(AsynchronousImageCache &imageCache, reloadQmlSource(); - setFocusProxy(m_quickWidget.data()); + setFocusProxy(m_quickWidget->quickWidget()); } void MaterialBrowserWidget::updateMaterialPreview(const ModelNode &node, const QPixmap &pixmap) diff --git a/src/plugins/qmldesigner/components/materialeditor/materialeditorcontextobject.cpp b/src/plugins/qmldesigner/components/materialeditor/materialeditorcontextobject.cpp index a99d4133afc..4a4057d8ab3 100644 --- a/src/plugins/qmldesigner/components/materialeditor/materialeditorcontextobject.cpp +++ b/src/plugins/qmldesigner/components/materialeditor/materialeditorcontextobject.cpp @@ -510,18 +510,9 @@ QStringList MaterialEditorContextObject::allStatesForId(const QString &id) return {}; } -bool MaterialEditorContextObject::isBlocked(const QString &propName) const +bool MaterialEditorContextObject::isBlocked(const QString &) const { - if (!m_selectedMaterial.isValid()) - return false; - - if (!m_model || !m_model->rewriterView()) - return false; - - if (QmlObjectNode(m_selectedMaterial).isBlocked(propName.toUtf8())) - return true; - - return false; + return false; } void MaterialEditorContextObject::goIntoComponent() diff --git a/src/plugins/qmldesigner/components/materialeditor/materialeditorqmlbackend.cpp b/src/plugins/qmldesigner/components/materialeditor/materialeditorqmlbackend.cpp index edae2377bfb..fe84c0c1841 100644 --- a/src/plugins/qmldesigner/components/materialeditor/materialeditorqmlbackend.cpp +++ b/src/plugins/qmldesigner/components/materialeditor/materialeditorqmlbackend.cpp @@ -31,7 +31,7 @@ static QObject *variantToQObject(const QVariant &value) { - if (value.userType() == QMetaType::QObjectStar || value.userType() > QMetaType::User) + if (value.typeId() == QMetaType::QObjectStar || value.typeId() > QMetaType::User) return *(QObject **)value.constData(); return nullptr; @@ -143,7 +143,7 @@ void MaterialEditorQmlBackend::createPropertyEditorValue(const QmlObjectNode &qm void MaterialEditorQmlBackend::setValue(const QmlObjectNode &, const PropertyName &name, const QVariant &value) { // Vector*D values need to be split into their subcomponents - if (value.type() == QVariant::Vector2D) { + if (value.typeId() == QVariant::Vector2D) { const char *suffix[2] = {"_x", "_y"}; auto vecValue = value.value(); for (int i = 0; i < 2; ++i) { @@ -154,7 +154,7 @@ void MaterialEditorQmlBackend::setValue(const QmlObjectNode &, const PropertyNam if (propertyValue) propertyValue->setValue(QVariant(vecValue[i])); } - } else if (value.type() == QVariant::Vector3D) { + } else if (value.typeId() == QVariant::Vector3D) { const char *suffix[3] = {"_x", "_y", "_z"}; auto vecValue = value.value(); for (int i = 0; i < 3; ++i) { @@ -165,7 +165,7 @@ void MaterialEditorQmlBackend::setValue(const QmlObjectNode &, const PropertyNam if (propertyValue) propertyValue->setValue(QVariant(vecValue[i])); } - } else if (value.type() == QVariant::Vector4D) { + } else if (value.typeId() == QVariant::Vector4D) { const char *suffix[4] = {"_x", "_y", "_z", "_w"}; auto vecValue = value.value(); for (int i = 0; i < 4; ++i) { diff --git a/src/plugins/qmldesigner/components/materialeditor/materialeditorview.cpp b/src/plugins/qmldesigner/components/materialeditor/materialeditorview.cpp index 55c587f3cb4..933686febda 100644 --- a/src/plugins/qmldesigner/components/materialeditor/materialeditorview.cpp +++ b/src/plugins/qmldesigner/components/materialeditor/materialeditorview.cpp @@ -442,8 +442,11 @@ void MaterialEditorView::handleToolBarAction(int action) } case MaterialEditorContextObject::DeleteCurrentMaterial: { - if (m_selectedMaterial.isValid()) - m_selectedMaterial.destroy(); + if (m_selectedMaterial.isValid()) { + executeInTransaction(__FUNCTION__, [&] { + m_selectedMaterial.destroy(); + }); + } break; } diff --git a/src/plugins/qmldesigner/components/navigator/choosefrompropertylistdialog.cpp b/src/plugins/qmldesigner/components/navigator/choosefrompropertylistdialog.cpp index 91c300e87a2..304ff91fcda 100644 --- a/src/plugins/qmldesigner/components/navigator/choosefrompropertylistdialog.cpp +++ b/src/plugins/qmldesigner/components/navigator/choosefrompropertylistdialog.cpp @@ -115,10 +115,10 @@ ChooseFromPropertyListDialog::ChooseFromPropertyListDialog(const QStringList &pr : QDialog(parent) , m_ui(new Ui::ChooseFromPropertyListDialog) { - if (propNames.count() == 1) { - m_selectedProperty = propNames.first().toLatin1(); - m_isSoloProperty = true; - return; + if (propNames.size() == 1) { + m_selectedProperty = propNames.first().toLatin1(); + m_isSoloProperty = true; + return; } m_ui->setupUi(this); setWindowTitle(tr("Select Property")); diff --git a/src/plugins/qmldesigner/components/navigator/navigatortreemodel.cpp b/src/plugins/qmldesigner/components/navigator/navigatortreemodel.cpp index 16dd2242863..8b7f1f8a61e 100644 --- a/src/plugins/qmldesigner/components/navigator/navigatortreemodel.cpp +++ b/src/plugins/qmldesigner/components/navigator/navigatortreemodel.cpp @@ -69,13 +69,12 @@ static QList modelNodesFromMimeData(const QMimeData *mineData, Abstra bool fitsToTargetProperty(const NodeAbstractProperty &targetProperty, const QList &modelNodeList) { - bool const canBeContainer = - NodeHints::fromModelNode(targetProperty.parentModelNode()).canBeContainerFor(modelNodeList.first()); - return !(targetProperty.isNodeProperty() && - modelNodeList.count() > 1) && canBeContainer; + const bool canBeContainer = NodeHints::fromModelNode(targetProperty.parentModelNode()) + .canBeContainerFor(modelNodeList.first()); + return !(targetProperty.isNodeProperty() && modelNodeList.size() > 1) && canBeContainer; } -static inline QString msgUnknownItem(const QString &t) +inline static QString msgUnknownItem(const QString &t) { return NavigatorTreeModel::tr("Unknown component: %1").arg(t); } @@ -289,7 +288,7 @@ Qt::ItemFlags NavigatorTreeModel::flags(const QModelIndex &index) const return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable; } -void static appendForcedNodes(const NodeListProperty &property, QList &list) +static void appendForcedNodes(const NodeListProperty &property, QList &list) { const QSet set = QSet(list.constBegin(), list.constEnd()); for (const ModelNode &node : property.parentModelNode().directSubModelNodes()) { @@ -411,7 +410,8 @@ int NavigatorTreeModel::rowCount(const QModelIndex &parent) const if (modelNode.defaultNodeListProperty().isValid()) { rows = filteredList(modelNode.defaultNodeListProperty(), m_showOnlyVisibleItems, - m_reverseItemOrder).count(); + m_reverseItemOrder) + .size(); } return rows; @@ -451,12 +451,13 @@ void NavigatorTreeModel::setView(NavigatorView *view) QStringList NavigatorTreeModel::mimeTypes() const { - const static QStringList types({Constants::MIME_TYPE_MODELNODE_LIST, + static const QStringList types({Constants::MIME_TYPE_MODELNODE_LIST, Constants::MIME_TYPE_ITEM_LIBRARY_INFO, Constants::MIME_TYPE_TEXTURE, Constants::MIME_TYPE_MATERIAL, Constants::MIME_TYPE_BUNDLE_TEXTURE, Constants::MIME_TYPE_BUNDLE_MATERIAL, + Constants::MIME_TYPE_BUNDLE_EFFECT, Constants::MIME_TYPE_ASSETS}); return types; @@ -565,6 +566,10 @@ bool NavigatorTreeModel::dropMimeData(const QMimeData *mimeData, ModelNode targetNode(modelNodeForIndex(dropModelIndex)); if (targetNode.isValid()) m_view->emitCustomNotification("drop_bundle_material", {targetNode}); // To ContentLibraryView + } else if (mimeData->hasFormat(Constants::MIME_TYPE_BUNDLE_EFFECT)) { + ModelNode targetNode(modelNodeForIndex(dropModelIndex)); + if (targetNode.isValid()) + m_view->emitCustomNotification("drop_bundle_effect", {targetNode}); // To ContentLibraryView } else if (mimeData->hasFormat(Constants::MIME_TYPE_ASSETS)) { const QStringList assetsPaths = QString::fromUtf8(mimeData->data(Constants::MIME_TYPE_ASSETS)).split(','); NodeAbstractProperty targetProperty; @@ -777,21 +782,6 @@ void NavigatorTreeModel::handleItemLibraryItemDrop(const QMimeData *mimeData, in if (newQmlObjectNode.isValid()) m_view->setSelectedModelNode(newQmlObjectNode.modelNode()); } - - const QStringList copyFiles = itemLibraryEntry.extraFilePaths(); - if (!copyFiles.isEmpty()) { - // Files are copied into the same directory as the current qml document - for (const auto ©File : copyFiles) { - QFileInfo fi(copyFile); - const QString targetFile = DocumentManager::currentFilePath().toFileInfo().dir() - .absoluteFilePath(fi.fileName()); - // We don't want to overwrite existing default files - if (!QFileInfo::exists(targetFile)) { - if (!QFile::copy(copyFile, targetFile)) - qWarning() << QStringLiteral("Copying extra file '%1' failed.").arg(copyFile); - } - } - } } } @@ -900,7 +890,7 @@ ModelNode NavigatorTreeModel::handleItemLibraryFontDrop(const QString &fontFamil void NavigatorTreeModel::addImport(const QString &importName) { - if (!Utils::addImportWithCheck(importName, m_view->model())) + if (!ModelUtils::addImportWithCheck(importName, m_view->model())) qWarning() << __FUNCTION__ << "Adding import failed:" << importName; } @@ -943,7 +933,7 @@ ModelNode NavigatorTreeModel::handleItemLibraryShaderDrop(const QString &shaderP // set shader properties PropertyName prop = "shader"; - QString type = "QByteArray"; + QString type = "QUrl"; QVariant val = relPath; itemLibraryEntry.addProperty(prop, type, val); prop = "stage"; diff --git a/src/plugins/qmldesigner/components/navigator/navigatorview.cpp b/src/plugins/qmldesigner/components/navigator/navigatorview.cpp index f1a00a36c7c..ceccf25554c 100644 --- a/src/plugins/qmldesigner/components/navigator/navigatorview.cpp +++ b/src/plugins/qmldesigner/components/navigator/navigatorview.cpp @@ -42,7 +42,7 @@ #include #include -static inline void setScenePos(const QmlDesigner::ModelNode &modelNode,const QPointF &pos) +inline static void setScenePos(const QmlDesigner::ModelNode &modelNode, const QPointF &pos) { if (modelNode.hasParentProperty() && QmlDesigner::QmlItemNode::isValidQmlItemNode(modelNode.parentProperty().parentModelNode())) { QmlDesigner::QmlItemNode parentNode = modelNode.parentProperty().parentQmlObjectNode().toQmlItemNode(); @@ -58,7 +58,7 @@ static inline void setScenePos(const QmlDesigner::ModelNode &modelNode,const QPo } } -static inline void moveNodesUp(const QList &nodes) +inline static void moveNodesUp(const QList &nodes) { for (const auto &node : nodes) { if (!node.isRootNode() && node.parentProperty().isNodeListProperty()) { @@ -73,7 +73,7 @@ static inline void moveNodesUp(const QList &nodes) } } -static inline void moveNodesDown(const QList &nodes) +inline static void moveNodesDown(const QList &nodes) { for (const auto &node : nodes) { if (!node.isRootNode() && node.parentProperty().isNodeListProperty()) { @@ -280,7 +280,7 @@ void NavigatorView::dragStarted(QMimeData *mimeData) m_widget->update(); } else if (mimeData->hasFormat(Constants::MIME_TYPE_ASSETS)) { const QStringList assetsPaths = QString::fromUtf8(mimeData->data(Constants::MIME_TYPE_ASSETS)).split(','); - if (assetsPaths.count() > 0) { + if (assetsPaths.size() > 0) { auto assetTypeAndData = AssetsLibraryWidget::getAssetTypeAndData(assetsPaths[0]); QString assetType = assetTypeAndData.first; if (assetType == Constants::MIME_TYPE_ASSET_EFFECT) { @@ -517,7 +517,7 @@ void NavigatorView::propagateInstanceErrorToExplorer(const ModelNode &modelNode) void NavigatorView::leftButtonClicked() { - if (selectedModelNodes().count() > 1) + if (selectedModelNodes().size() > 1) return; //Semantics are unclear for multi selection. bool blocked = blockSelectionChangedSignal(true); @@ -541,14 +541,15 @@ void NavigatorView::leftButtonClicked() void NavigatorView::rightButtonClicked() { - if (selectedModelNodes().count() > 1) + if (selectedModelNodes().size() > 1) return; //Semantics are unclear for multi selection. bool blocked = blockSelectionChangedSignal(true); bool reverse = QmlDesignerPlugin::settings().value(DesignerSettingsKey::NAVIGATOR_REVERSE_ITEM_ORDER).toBool(); for (const ModelNode &node : selectedModelNodes()) { - if (!node.isRootNode() && node.parentProperty().isNodeListProperty() && node.parentProperty().count() > 1) { + if (!node.isRootNode() && node.parentProperty().isNodeListProperty() + && node.parentProperty().count() > 1) { int index = node.parentProperty().indexOf(node); bool indexOk = false; diff --git a/src/plugins/qmldesigner/components/pathtool/pathitem.cpp b/src/plugins/qmldesigner/components/pathtool/pathitem.cpp index 10c93ad5594..801be712ad8 100644 --- a/src/plugins/qmldesigner/components/pathtool/pathitem.cpp +++ b/src/plugins/qmldesigner/components/pathtool/pathitem.cpp @@ -587,7 +587,7 @@ QAction *PathItem::createClosedPathAction(QMenu *contextMenu) const closedPathAction->setText(tr("Closed Path")); contextMenu->addAction(closedPathAction); - if (m_cubicSegments.count() == 1) + if (m_cubicSegments.size() == 1) closedPathAction->setDisabled(true); return closedPathAction; @@ -617,7 +617,7 @@ void PathItem::createCubicSegmentContextMenu(CubicSegment &cubicSegment, const Q straightLinePointAction->setText(tr("Make Curve Segment Straight")); contextMenu.addAction(straightLinePointAction); - if (m_cubicSegments.count() == 1 && isClosedPath()) + if (m_cubicSegments.size() == 1 && isClosedPath()) straightLinePointAction->setDisabled(true); QAction *closedPathAction = createClosedPathAction(&contextMenu); @@ -649,7 +649,7 @@ void PathItem::createEditPointContextMenu(const ControlPoint &controlPoint, cons QAction *closedPathAction = createClosedPathAction(&contextMenu); - if (m_cubicSegments.count() <= 1 || (m_cubicSegments.count() == 2 && isClosedPath())) + if (m_cubicSegments.size() <= 1 || (m_cubicSegments.size() == 2 && isClosedPath())) removeEditPointAction->setDisabled(true); QAction *activatedAction = contextMenu.exec(menuPosition); @@ -663,7 +663,7 @@ void PathItem::createEditPointContextMenu(const ControlPoint &controlPoint, cons const QList PathItem::controlPoints() const { QList controlPointList; - controlPointList.reserve((m_cubicSegments.count() * 4)); + controlPointList.reserve((m_cubicSegments.size() * 4)); if (!m_cubicSegments.isEmpty()) controlPointList.append(m_cubicSegments.constFirst().firstControlPoint()); @@ -914,9 +914,9 @@ void PathItem::removeEditPoint(const ControlPoint &controlPoint) { QList cubicSegments = cubicSegmentsContainingControlPoint(controlPoint, m_cubicSegments); - if (cubicSegments.count() == 1) { + if (cubicSegments.size() == 1) { m_cubicSegments.removeOne(cubicSegments.constFirst()); - } else if (cubicSegments.count() == 2){ + } else if (cubicSegments.size() == 2) { CubicSegment mergedCubicSegment = CubicSegment::create(); const CubicSegment &firstCubicSegment = cubicSegments.at(0); const CubicSegment &secondCubicSegment = cubicSegments.at(1); diff --git a/src/plugins/qmldesigner/components/pathtool/pathselectionmanipulator.cpp b/src/plugins/qmldesigner/components/pathtool/pathselectionmanipulator.cpp index 6d620578481..c1c2fd725ac 100644 --- a/src/plugins/qmldesigner/components/pathtool/pathselectionmanipulator.cpp +++ b/src/plugins/qmldesigner/components/pathtool/pathselectionmanipulator.cpp @@ -54,12 +54,12 @@ static ControlPoint getControlPoint(const QList &selectedPoints, c int controlPointIndex = selectedPoints.indexOf(controlPoint); if (controlPointIndex >= 0) { int offsetIndex = controlPointIndex + indexOffset; - if (offsetIndex >= 0 && offsetIndex < selectedPoints.count()) + if (offsetIndex >= 0 && offsetIndex < selectedPoints.size()) return selectedPoints.at(offsetIndex); else if (isClosedPath) { if (offsetIndex == -1) return selectedPoints.constLast(); - else if (offsetIndex < selectedPoints.count()) + else if (offsetIndex < selectedPoints.size()) return selectedPoints.at(1); } } diff --git a/src/plugins/qmldesigner/components/propertyeditor/aligndistribute.cpp b/src/plugins/qmldesigner/components/propertyeditor/aligndistribute.cpp index 5d8400b47e2..f14e423c9f0 100644 --- a/src/plugins/qmldesigner/components/propertyeditor/aligndistribute.cpp +++ b/src/plugins/qmldesigner/components/propertyeditor/aligndistribute.cpp @@ -30,7 +30,7 @@ bool AlignDistribute::multiSelection() const if (!m_qmlObjectNode.isValid()) return false; - return m_qmlObjectNode.view()->selectedModelNodes().count() > 1; + return m_qmlObjectNode.view()->selectedModelNodes().size() > 1; } bool AlignDistribute::selectionHasAnchors() const @@ -210,7 +210,7 @@ bool compareByDepth(const ModelNode &node1, const ModelNode &node2) return false; } -static inline QRectF getBoundingRect(const QList &modelNodeList) +inline static QRectF getBoundingRect(const QList &modelNodeList) { QRectF boundingRect; for (const ModelNode &modelNode : modelNodeList) { @@ -222,7 +222,7 @@ static inline QRectF getBoundingRect(const QList &modelNodeList) return boundingRect; } -static inline QSizeF getSummedSize(const QList &modelNodeList) +inline static QSizeF getSummedSize(const QList &modelNodeList) { QSizeF summedSize = QSizeF(0, 0); for (const ModelNode &modelNode : modelNodeList) { @@ -234,7 +234,7 @@ static inline QSizeF getSummedSize(const QList &modelNodeList) return summedSize; } -static inline qreal getInstanceSceneX(const QmlItemNode &qmlItemNode) +inline static qreal getInstanceSceneX(const QmlItemNode &qmlItemNode) { const qreal x = qmlItemNode.modelValue("x").toReal(); if (qmlItemNode.hasInstanceParentItem()) @@ -242,7 +242,7 @@ static inline qreal getInstanceSceneX(const QmlItemNode &qmlItemNode) return x; } -static inline qreal getInstanceSceneY(const QmlItemNode &qmlItemNode) +inline static qreal getInstanceSceneY(const QmlItemNode &qmlItemNode) { const qreal y = qmlItemNode.modelValue("y").toReal(); if (qmlItemNode.hasInstanceParentItem()) diff --git a/src/plugins/qmldesigner/components/propertyeditor/dynamicpropertiesproxymodel.cpp b/src/plugins/qmldesigner/components/propertyeditor/dynamicpropertiesproxymodel.cpp index 977488a107a..046f95ed738 100644 --- a/src/plugins/qmldesigner/components/propertyeditor/dynamicpropertiesproxymodel.cpp +++ b/src/plugins/qmldesigner/components/propertyeditor/dynamicpropertiesproxymodel.cpp @@ -152,7 +152,7 @@ void DynamicPropertiesProxyModel::createProperty(const QString &name, const QStr TypeName typeName = type.toUtf8(); const auto selectedNodes = dynamicPropertiesModel()->selectedNodes(); - if (selectedNodes.count() == 1) { + if (selectedNodes.size() == 1) { const ModelNode modelNode = selectedNodes.constFirst(); if (modelNode.isValid()) { if (modelNode.hasProperty(name.toUtf8())) { diff --git a/src/plugins/qmldesigner/components/propertyeditor/gradientmodel.cpp b/src/plugins/qmldesigner/components/propertyeditor/gradientmodel.cpp index 67ee0ec15ce..570927a8638 100644 --- a/src/plugins/qmldesigner/components/propertyeditor/gradientmodel.cpp +++ b/src/plugins/qmldesigner/components/propertyeditor/gradientmodel.cpp @@ -100,11 +100,11 @@ int GradientModel::addStop(qreal position, const QColor &color) const QList stopNodes = gradientNode.nodeListProperty("stops").toModelNodeList(); - for (int i = 0; i < stopNodes.count(); i++) { + for (int i = 0; i < stopNodes.size(); i++) { if (QmlDesigner::QmlObjectNode(stopNodes.at(i)).modelValue("position").toReal() < position) properPos = i + 1; } - gradientNode.nodeListProperty("stops").slide(stopNodes.count() - 1, properPos); + gradientNode.nodeListProperty("stops").slide(stopNodes.size() - 1, properPos); setupModel(); resetPuppet(); diff --git a/src/plugins/qmldesigner/components/propertyeditor/gradientpresetlistmodel.cpp b/src/plugins/qmldesigner/components/propertyeditor/gradientpresetlistmodel.cpp index 5b25f56f511..b4b41773321 100644 --- a/src/plugins/qmldesigner/components/propertyeditor/gradientpresetlistmodel.cpp +++ b/src/plugins/qmldesigner/components/propertyeditor/gradientpresetlistmodel.cpp @@ -28,12 +28,12 @@ GradientPresetListModel::~GradientPresetListModel() int GradientPresetListModel::rowCount(const QModelIndex & /*parent*/) const { - return m_items.count(); + return m_items.size(); } QVariant GradientPresetListModel::data(const QModelIndex &index, int role) const { - if (index.isValid() && (index.row() >= 0) && (index.row() < m_items.count())) { + if (index.isValid() && (index.row() >= 0) && (index.row() < m_items.size())) { if (m_roleNames.contains(role)) { QVariant value = m_items.at(index.row()) .getProperty(static_cast(role)); diff --git a/src/plugins/qmldesigner/components/propertyeditor/itemfiltermodel.cpp b/src/plugins/qmldesigner/components/propertyeditor/itemfiltermodel.cpp index c5d9a23d7ea..aa1d41888b6 100644 --- a/src/plugins/qmldesigner/components/propertyeditor/itemfiltermodel.cpp +++ b/src/plugins/qmldesigner/components/propertyeditor/itemfiltermodel.cpp @@ -61,6 +61,19 @@ void ItemFilterModel::setSelectedItems(const QStringList &selectedItems) emit selectedItemsChanged(); } +void ItemFilterModel::setValidationRoles(const QStringList &validationRoles) +{ + auto tmp = validationRoles; + tmp.removeDuplicates(); + + if (m_validationRoles == tmp) + return; + + m_validationRoles = tmp; + setupValidationItems(); + emit validationRolesChanged(); +} + QString ItemFilterModel::typeFilter() const { return m_typeFilter; @@ -76,6 +89,29 @@ QStringList ItemFilterModel::selectedItems() const return m_selectedItems; } +QStringList ItemFilterModel::itemModel() const +{ + AbstractView *view = m_modelNode.view(); + if (!view || !view->model()) + return {}; + + QStringList retval; + for (const auto &internalId : std::as_const(m_modelInternalIds)) + retval << view->modelNodeForInternalId(internalId).id(); + + return retval; +} + +QStringList ItemFilterModel::validationRoles() const +{ + return m_validationRoles; +} + +QStringList ItemFilterModel::validationItems() const +{ + return m_validationItems; +} + void ItemFilterModel::registerDeclarativeType() { qmlRegisterType("HelperWidgets", 2, 0, "ItemFilterModel"); @@ -154,17 +190,33 @@ void ItemFilterModel::setupModel() endResetModel(); emit itemModelChanged(); + + setupValidationItems(); } -QStringList ItemFilterModel::itemModel() const +void ItemFilterModel::setupValidationItems() { - AbstractView *view = m_modelNode.view(); - if (!view || !view->model()) - return {}; + QStringList validationItems; - QStringList retval; - for (const auto &internalId : std::as_const(m_modelInternalIds)) - retval << view->modelNodeForInternalId(internalId).id(); + for (const QString &role : m_validationRoles) { + int r = roleNames().key(role.toUtf8(), -1); - return retval; + if (r == -1) + continue; + + for (int i = 0; i < rowCount(); ++i) { + QVariant item = data(index(i), r); + if (item.canConvert()) + validationItems.append(item.toString()); + } + } + + validationItems.removeDuplicates(); + + if (m_validationItems == validationItems) + return; + + m_validationItems = validationItems; + + emit validationItemsChanged(); } diff --git a/src/plugins/qmldesigner/components/propertyeditor/itemfiltermodel.h b/src/plugins/qmldesigner/components/propertyeditor/itemfiltermodel.h index cb7ae131778..eaf23820d4f 100644 --- a/src/plugins/qmldesigner/components/propertyeditor/itemfiltermodel.h +++ b/src/plugins/qmldesigner/components/propertyeditor/itemfiltermodel.h @@ -25,6 +25,10 @@ class ItemFilterModel : public QAbstractListModel Q_PROPERTY(QStringList selectedItems READ selectedItems WRITE setSelectedItems NOTIFY selectedItemsChanged) + Q_PROPERTY(QStringList validationRoles READ validationRoles WRITE setValidationRoles NOTIFY + validationRolesChanged) + Q_PROPERTY(QStringList validationItems READ validationItems NOTIFY validationItemsChanged) + public: enum { IdRole = Qt::DisplayRole, NameRole = Qt::UserRole, IdAndNameRole, EnabledRole }; @@ -34,17 +38,18 @@ public: void setTypeFilter(const QString &typeFilter); void setSelectionOnly(bool value); void setSelectedItems(const QStringList &selectedItems); + void setValidationRoles(const QStringList &validationRoles); QString typeFilter() const; bool selectionOnly() const; QStringList selectedItems() const; - void setupModel(); QStringList itemModel() const; + QStringList validationRoles() const; + QStringList validationItems() const; static void registerDeclarativeType(); virtual int rowCount(const QModelIndex &parent = QModelIndex()) const override; virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; - virtual QHash roleNames() const override; signals: @@ -53,8 +58,12 @@ signals: void itemModelChanged(); void selectionOnlyChanged(); void selectedItemsChanged(); + void validationRolesChanged(); + void validationItemsChanged(); private: + void setupModel(); + void setupValidationItems(); QVariant modelNodeBackend() const; QmlDesigner::ModelNode modelNodeForRow(const int &row) const; @@ -64,6 +73,9 @@ private: QmlDesigner::ModelNode m_modelNode; bool m_selectionOnly; QStringList m_selectedItems; + + QStringList m_validationRoles; + QStringList m_validationItems; }; QML_DECLARE_TYPE(ItemFilterModel) diff --git a/src/plugins/qmldesigner/components/propertyeditor/listvalidator.cpp b/src/plugins/qmldesigner/components/propertyeditor/listvalidator.cpp new file mode 100644 index 00000000000..c1eaa48c3fe --- /dev/null +++ b/src/plugins/qmldesigner/components/propertyeditor/listvalidator.cpp @@ -0,0 +1,58 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +#include "listvalidator.h" + +ListValidator::ListValidator(QObject *parent) + : QValidator{parent} +{} + +QValidator::State ListValidator::validate(QString &input, int &) const +{ + if (input.isEmpty()) + return QValidator::Intermediate; + + State state = QValidator::Invalid; + + for (const QString &item : m_filterList) { + if (item.compare(input, Qt::CaseSensitive) == 0) + return QValidator::Acceptable; + + if (item.compare(input, Qt::CaseInsensitive) == 0) + return QValidator::Intermediate; + + if (item.contains(input, Qt::CaseInsensitive)) + state = QValidator::Intermediate; + } + + return state; +} + +void ListValidator::fixup(QString &input) const +{ + for (const QString &item : m_filterList) { + if (item.compare(input, Qt::CaseInsensitive) == 0) { + input = item; + return; + } + } +} + +void ListValidator::setFilterList(const QStringList &filterList) +{ + if (m_filterList == filterList) + return; + + m_filterList = filterList; + emit filterListChanged(); +} + +QStringList ListValidator::filterList() const +{ + return m_filterList; +} + +void ListValidator::registerDeclarativeType() +{ + qmlRegisterType("HelperWidgets", 2, 0, "ListValidator"); +} diff --git a/src/plugins/qmldesigner/components/propertyeditor/listvalidator.h b/src/plugins/qmldesigner/components/propertyeditor/listvalidator.h new file mode 100644 index 00000000000..46e8e4649f2 --- /dev/null +++ b/src/plugins/qmldesigner/components/propertyeditor/listvalidator.h @@ -0,0 +1,33 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +#pragma once + +#include +#include + +class ListValidator : public QValidator +{ + Q_OBJECT + + Q_PROPERTY(QStringList filterList READ filterList WRITE setFilterList NOTIFY filterListChanged) + +public: + explicit ListValidator(QObject *parent = nullptr); + + QValidator::State validate(QString &data, int &pos) const override; + void fixup(QString &input) const override; + + void setFilterList(const QStringList &filterList); + QStringList filterList() const; + + static void registerDeclarativeType(); + +signals: + void filterListChanged(); + +private: + QStringList m_filterList; +}; + +QML_DECLARE_TYPE(ListValidator) diff --git a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorcontextobject.cpp b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorcontextobject.cpp index a8aebbfb073..8c9b19d62ee 100644 --- a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorcontextobject.cpp +++ b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorcontextobject.cpp @@ -7,6 +7,8 @@ #include #include #include +#include +#include #include #include #include @@ -408,7 +410,13 @@ QQmlComponent *PropertyEditorContextObject::specificQmlComponent() m_qmlComponent = new QQmlComponent(m_qmlContext->engine(), this); - m_qmlComponent->setData(m_specificQmlData.toUtf8(), QUrl::fromLocalFile(QStringLiteral("specfics.qml"))); + m_qmlComponent->setData(m_specificQmlData.toUtf8(), QUrl::fromLocalFile("specifics.qml")); + + const bool showError = qEnvironmentVariableIsSet(Constants::ENVIRONMENT_SHOW_QML_ERRORS); + if (showError && !m_specificQmlData.isEmpty() && !m_qmlComponent->errors().isEmpty()) { + const QString errMsg = m_qmlComponent->errors().constFirst().toString(); + Core::AsynchronousMessageBox::warning(tr("Invalid QML source"), errMsg); + } return m_qmlComponent; } @@ -590,10 +598,8 @@ bool PropertyEditorContextObject::isBlocked(const QString &propName) const { if (m_model && m_model->rewriterView()) { const QList nodes = m_model->rewriterView()->selectedModelNodes(); - QScopedPointer objNode; for (const auto &node : nodes) { - objNode.reset(QmlObjectNode::getQmlObjectNodeOfCorrectType(node)); - if (objNode->isBlocked(propName.toUtf8())) + if (Qml3DNode qml3DNode{node}; qml3DNode.isBlocked(propName.toUtf8())) return true; } } diff --git a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorqmlbackend.cpp b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorqmlbackend.cpp index 909530dbc3c..3b991a5f622 100644 --- a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorqmlbackend.cpp +++ b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorqmlbackend.cpp @@ -19,6 +19,7 @@ #include #include +#include #include #include #include @@ -40,7 +41,7 @@ static Q_LOGGING_CATEGORY(propertyEditorBenchmark, "qtc.propertyeditor.load", Qt static QmlJS::SimpleReaderNode::Ptr s_templateConfiguration = QmlJS::SimpleReaderNode::Ptr(); -static inline QString propertyTemplatesPath() +inline static QString propertyTemplatesPath() { return QmlDesigner::PropertyEditorQmlBackend::propertyEditorResourcesPath() + QStringLiteral("/PropertyTemplates/"); } @@ -70,7 +71,7 @@ QStringList variantToStringList(const QVariant &variant) { static QObject *variantToQObject(const QVariant &value) { - if (value.userType() == QMetaType::QObjectStar || value.userType() > QMetaType::User) + if (value.typeId() == QMetaType::QObjectStar || value.typeId() > QMetaType::User) return *(QObject **)value.constData(); return nullptr; @@ -322,7 +323,7 @@ void PropertyEditorQmlBackend::createPropertyEditorValue(const QmlObjectNode &qm void PropertyEditorQmlBackend::setValue(const QmlObjectNode & , const PropertyName &name, const QVariant &value) { // Vector*D values need to be split into their subcomponents - if (value.type() == QVariant::Vector2D) { + if (value.typeId() == QVariant::Vector2D) { const char *suffix[2] = {"_x", "_y"}; auto vecValue = value.value(); for (int i = 0; i < 2; ++i) { @@ -333,7 +334,7 @@ void PropertyEditorQmlBackend::setValue(const QmlObjectNode & , const PropertyNa if (propertyValue) propertyValue->setValue(QVariant(vecValue[i])); } - } else if (value.type() == QVariant::Vector3D) { + } else if (value.typeId() == QVariant::Vector3D) { const char *suffix[3] = {"_x", "_y", "_z"}; auto vecValue = value.value(); for (int i = 0; i < 3; ++i) { @@ -344,7 +345,7 @@ void PropertyEditorQmlBackend::setValue(const QmlObjectNode & , const PropertyNa if (propertyValue) propertyValue->setValue(QVariant(vecValue[i])); } - } else if (value.type() == QVariant::Vector4D) { + } else if (value.typeId() == QVariant::Vector4D) { const char *suffix[4] = {"_x", "_y", "_z", "_w"}; auto vecValue = value.value(); for (int i = 0; i < 4; ++i) { @@ -372,23 +373,35 @@ void PropertyEditorQmlBackend::setExpression(const PropertyName &propName, const propertyValue->setExpression(exp); } -QQmlContext *PropertyEditorQmlBackend::context() { +QQmlContext *PropertyEditorQmlBackend::context() +{ return m_view->rootContext(); } -PropertyEditorContextObject* PropertyEditorQmlBackend::contextObject() { +PropertyEditorContextObject *PropertyEditorQmlBackend::contextObject() +{ return m_contextObject.data(); } -QQuickWidget *PropertyEditorQmlBackend::widget() { +QQuickWidget *PropertyEditorQmlBackend::widget() +{ return m_view; } -void PropertyEditorQmlBackend::setSource(const QUrl& url) { +void PropertyEditorQmlBackend::setSource(const QUrl &url) +{ m_view->setSource(url); + + const bool showError = qEnvironmentVariableIsSet(Constants::ENVIRONMENT_SHOW_QML_ERRORS); + + if (showError && !m_view->errors().isEmpty()) { + const QString errMsg = m_view->errors().constFirst().toString(); + Core::AsynchronousMessageBox::warning(PropertyEditorView::tr("Invalid QML source"), errMsg); + } } -Internal::QmlAnchorBindingProxy &PropertyEditorQmlBackend::backendAnchorBinding() { +Internal::QmlAnchorBindingProxy &PropertyEditorQmlBackend::backendAnchorBinding() +{ return m_backendAnchorBinding; } @@ -482,7 +495,8 @@ void PropertyEditorQmlBackend::setup(const QmlObjectNode &qmlObjectNode, const Q if (!qmlObjectNode.isValid()) return; - context()->setContextProperty(QLatin1String("propertyCount"), QVariant(qmlObjectNode.modelNode().properties().count())); + context()->setContextProperty(QLatin1String("propertyCount"), + QVariant(qmlObjectNode.modelNode().properties().size())); QStringList stateNames = qmlObjectNode.allStateNames(); stateNames.prepend("base state"); @@ -849,7 +863,7 @@ NodeMetaInfo PropertyEditorQmlBackend::findCommonAncestor(const ModelNode &node) AbstractView *view = node.view(); - if (view->selectedModelNodes().count() > 1) { + if (view->selectedModelNodes().size() > 1) { NodeMetaInfo commonClass = node.metaInfo(); for (const ModelNode ¤tNode : view->selectedModelNodes()) { if (currentNode.metaInfo().isValid() && !currentNode.metaInfo().isBasedOn(commonClass)) @@ -964,7 +978,7 @@ QString PropertyEditorQmlBackend::locateQmlFile(const NodeMetaInfo &info, const const QDir importDir(info.importDirectoryPath() + Constants::QML_DESIGNER_SUBFOLDER); const QDir importDirVersion(info.importDirectoryPath() + QStringLiteral(".") + QString::number(info.majorVersion()) + Constants::QML_DESIGNER_SUBFOLDER); - const QString relativePathWithoutEnding = relativePath.left(relativePath.count() - 4); + const QString relativePathWithoutEnding = relativePath.left(relativePath.size() - 4); const QString relativePathWithVersion = QString("%1_%2_%3.qml").arg(relativePathWithoutEnding ).arg(info.majorVersion()).arg(info.minorVersion()); diff --git a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorvalue.cpp b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorvalue.cpp index 6a9ce6164a1..3f3ddaaf162 100644 --- a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorvalue.cpp +++ b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorvalue.cpp @@ -41,7 +41,7 @@ QVariant PropertyEditorValue::value() const static bool cleverDoubleCompare(const QVariant &value1, const QVariant &value2) { - if (value1.type() == QVariant::Double && value2.type() == QVariant::Double) { + if (value1.typeId() == QVariant::Double && value2.typeId() == QVariant::Double) { // ignore slight changes on doubles if (qFuzzyCompare(value1.toDouble(), value2.toDouble())) return true; @@ -51,16 +51,16 @@ static bool cleverDoubleCompare(const QVariant &value1, const QVariant &value2) static bool cleverColorCompare(const QVariant &value1, const QVariant &value2) { - if (value1.type() == QVariant::Color && value2.type() == QVariant::Color) { + if (value1.typeId() == QVariant::Color && value2.typeId() == QVariant::Color) { QColor c1 = value1.value(); QColor c2 = value2.value(); return c1.name() == c2.name() && c1.alpha() == c2.alpha(); } - if (value1.type() == QVariant::String && value2.type() == QVariant::Color) + if (value1.typeId() == QVariant::String && value2.typeId() == QVariant::Color) return cleverColorCompare(QVariant(QColor(value1.toString())), value2); - if (value1.type() == QVariant::Color && value2.type() == QVariant::String) + if (value1.typeId() == QVariant::Color && value2.typeId() == QVariant::String) return cleverColorCompare(value1, QVariant(QColor(value2.toString()))); return false; @@ -71,7 +71,7 @@ static bool cleverColorCompare(const QVariant &value1, const QVariant &value2) static void fixAmbigousColorNames(const ModelNode &modelNode, const PropertyName &name, QVariant *value) { if (auto metaInfo = modelNode.metaInfo(); metaInfo.property(name).propertyType().isColor()) { - if (value->type() == QVariant::Color) { + if (value->typeId() == QVariant::Color) { QColor color = value->value(); int alpha = color.alpha(); color = QColor(color.name()); @@ -623,16 +623,13 @@ void PropertyEditorNodeWrapper::changeValue(const QString &propertyName) if (name.isNull()) return; - if (m_modelNode.isValid()) { - QScopedPointer qmlObjectNode{ - QmlObjectNode::getQmlObjectNodeOfCorrectType(m_modelNode)}; - + if (auto qmlObjectNode = QmlObjectNode{m_modelNode}) { auto valueObject = qvariant_cast(m_valuesPropertyMap.value(QString::fromLatin1(name))); if (valueObject->value().isValid()) - qmlObjectNode->setVariantProperty(name, valueObject->value()); + qmlObjectNode.setVariantProperty(name, valueObject->value()); else - qmlObjectNode->removeProperty(name); + qmlObjectNode.removeProperty(name); } } diff --git a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorview.cpp b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorview.cpp index 2cf47789e43..5d00f373c49 100644 --- a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorview.cpp +++ b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorview.cpp @@ -249,7 +249,7 @@ void PropertyEditorView::changeExpression(const QString &propertyName) PropertyName underscoreName(name); underscoreName.replace('.', '_'); - QScopedPointer qmlObjectNode {QmlObjectNode::getQmlObjectNodeOfCorrectType(m_selectedNode)}; + QmlObjectNode qmlObjectNode{m_selectedNode}; PropertyEditorValue *value = m_qmlBackEndForCurrentType->propertyValueForName(QString::fromLatin1(underscoreName)); if (!value) { @@ -257,46 +257,46 @@ void PropertyEditorView::changeExpression(const QString &propertyName) return; } - if (auto property = qmlObjectNode->modelNode().metaInfo().property(name)) { + if (auto property = qmlObjectNode.modelNode().metaInfo().property(name)) { const auto &propertType = property.propertyType(); if (propertType.isColor()) { if (QColor(value->expression().remove('"')).isValid()) { - qmlObjectNode->setVariantProperty(name, QColor(value->expression().remove('"'))); + qmlObjectNode.setVariantProperty(name, QColor(value->expression().remove('"'))); return; } } else if (propertType.isBool()) { if (isTrueFalseLiteral(value->expression())) { if (value->expression().compare("true", Qt::CaseInsensitive) == 0) - qmlObjectNode->setVariantProperty(name, true); + qmlObjectNode.setVariantProperty(name, true); else - qmlObjectNode->setVariantProperty(name, false); + qmlObjectNode.setVariantProperty(name, false); return; } } else if (propertType.isInteger()) { bool ok; int intValue = value->expression().toInt(&ok); if (ok) { - qmlObjectNode->setVariantProperty(name, intValue); + qmlObjectNode.setVariantProperty(name, intValue); return; } } else if (propertType.isFloat()) { bool ok; qreal realValue = value->expression().toDouble(&ok); if (ok) { - qmlObjectNode->setVariantProperty(name, realValue); + qmlObjectNode.setVariantProperty(name, realValue); return; } } else if (propertType.isVariant()) { bool ok; qreal realValue = value->expression().toDouble(&ok); if (ok) { - qmlObjectNode->setVariantProperty(name, realValue); + qmlObjectNode.setVariantProperty(name, realValue); return; } else if (isTrueFalseLiteral(value->expression())) { if (value->expression().compare("true", Qt::CaseInsensitive) == 0) - qmlObjectNode->setVariantProperty(name, true); + qmlObjectNode.setVariantProperty(name, true); else - qmlObjectNode->setVariantProperty(name, false); + qmlObjectNode.setVariantProperty(name, false); return; } } @@ -307,9 +307,9 @@ void PropertyEditorView::changeExpression(const QString &propertyName) return; } - if (qmlObjectNode->expression(name) != value->expression() - || !qmlObjectNode->propertyAffectedByCurrentState(name)) - qmlObjectNode->setBindingProperty(name, value->expression()); + if (qmlObjectNode.expression(name) != value->expression() + || !qmlObjectNode.propertyAffectedByCurrentState(name)) + qmlObjectNode.setBindingProperty(name, value->expression()); }); /* end of transaction */ } @@ -477,13 +477,10 @@ void PropertyEditorView::setupQmlBackend() m_stackedWidget->addWidget(currentQmlBackend->widget()); m_qmlBackendHash.insert(qmlFile.toString(), currentQmlBackend); - QScopedPointer qmlObjectNode; if (m_selectedNode.isValid()) { - qmlObjectNode.reset(QmlObjectNode::getQmlObjectNodeOfCorrectType(m_selectedNode)); - Q_ASSERT(qmlObjectNode->isValid()); - currentQmlBackend->setup(*qmlObjectNode, currentStateName, qmlSpecificsFile, this); - } else { - qmlObjectNode.reset(new QmlObjectNode); + QmlObjectNode qmlObjectNode{m_selectedNode}; + Q_ASSERT(qmlObjectNode.isValid()); + currentQmlBackend->setup(qmlObjectNode, currentStateName, qmlSpecificsFile, this); } if (specificQmlData.isEmpty()) @@ -492,15 +489,11 @@ void PropertyEditorView::setupQmlBackend() currentQmlBackend->contextObject()->setSpecificQmlData(specificQmlData); currentQmlBackend->setSource(qmlFile); } else { - QScopedPointer qmlObjectNode; - if (m_selectedNode.isValid()) - qmlObjectNode.reset(QmlObjectNode::getQmlObjectNodeOfCorrectType(m_selectedNode)); - else - qmlObjectNode.reset(new QmlObjectNode); + QmlObjectNode qmlObjectNode{m_selectedNode}; if (specificQmlData.isEmpty()) currentQmlBackend->contextObject()->setSpecificQmlData(specificQmlData); - currentQmlBackend->setup(*qmlObjectNode, currentStateName, qmlSpecificsFile, this); + currentQmlBackend->setup(qmlObjectNode, currentStateName, qmlSpecificsFile, this); currentQmlBackend->contextObject()->setSpecificQmlData(specificQmlData); } @@ -527,10 +520,8 @@ void PropertyEditorView::commitVariantValueToModel(const PropertyName &propertyN RewriterTransaction transaction = beginRewriterTransaction("PropertyEditorView::commitVariantValueToMode"); for (const ModelNode &node : m_selectedNode.view()->selectedModelNodes()) { - if (QmlObjectNode::isValidQmlObjectNode(node)) { - QScopedPointer{QmlObjectNode::getQmlObjectNodeOfCorrectType(node)} - ->setVariantProperty(propertyName, value); - } + if (auto qmlObjectNode = QmlObjectNode(node)) + qmlObjectNode.setVariantProperty(propertyName, value); } transaction.commit(); } @@ -646,9 +637,20 @@ void PropertyEditorView::propertiesRemoved(const QList &proper if (node == m_selectedNode || QmlObjectNode(m_selectedNode).propertyChangeForCurrentState() == node) { m_locked = true; - PropertyEditorValue *value = m_qmlBackEndForCurrentType->propertyValueForName(QString::fromUtf8(property.name())); - if (value) + + PropertyName propertyName = property.name(); + propertyName.replace('.', '_'); + + PropertyEditorValue *value = m_qmlBackEndForCurrentType->propertyValueForName( + QString::fromUtf8(propertyName)); + + if (value) { value->resetValue(); + m_qmlBackEndForCurrentType + ->setValue(m_selectedNode, + property.name(), + QmlObjectNode(m_selectedNode).instanceValue(property.name())); + } m_locked = false; if (propertyIsAttachedLayoutProperty(property.name())) { diff --git a/src/plugins/qmldesigner/components/propertyeditor/qmlmodelnodeproxy.cpp b/src/plugins/qmldesigner/components/propertyeditor/qmlmodelnodeproxy.cpp index f121489916c..96ec5f92e7c 100644 --- a/src/plugins/qmldesigner/components/propertyeditor/qmlmodelnodeproxy.cpp +++ b/src/plugins/qmldesigner/components/propertyeditor/qmlmodelnodeproxy.cpp @@ -50,7 +50,7 @@ bool QmlModelNodeProxy::multiSelection() const if (!m_qmlObjectNode.isValid()) return false; - return m_qmlObjectNode.view()->selectedModelNodes().count() > 1; + return m_qmlObjectNode.view()->selectedModelNodes().size() > 1; } QString QmlModelNodeProxy::nodeId() const diff --git a/src/plugins/qmldesigner/components/propertyeditor/quick2propertyeditorview.cpp b/src/plugins/qmldesigner/components/propertyeditor/quick2propertyeditorview.cpp index 610c0e27319..1c0071ee91b 100644 --- a/src/plugins/qmldesigner/components/propertyeditor/quick2propertyeditorview.cpp +++ b/src/plugins/qmldesigner/components/propertyeditor/quick2propertyeditorview.cpp @@ -6,17 +6,17 @@ #include #include "aligndistribute.h" -#include "assetimageprovider.h" #include "annotationeditor/annotationeditor.h" +#include "assetimageprovider.h" #include "bindingeditor/actioneditor.h" #include "bindingeditor/bindingeditor.h" #include "colorpalettebackend.h" -#include "selectiondynamicpropertiesproxymodel.h" #include "fileresourcesmodel.h" #include "gradientmodel.h" #include "gradientpresetcustomlistmodel.h" #include "gradientpresetdefaultlistmodel.h" #include "itemfiltermodel.h" +#include "listvalidator.h" #include "propertychangesmodel.h" #include "propertyeditorcontextobject.h" #include "propertyeditorqmlbackend.h" @@ -24,6 +24,7 @@ #include "propertymodel.h" #include "qmlanchorbindingproxy.h" #include "richtexteditor/richtexteditorproxy.h" +#include "selectiondynamicpropertiesproxymodel.h" #include "theme.h" #include "tooltip.h" @@ -50,6 +51,7 @@ void Quick2PropertyEditorView::registerQmlTypes() GradientPresetDefaultListModel::registerDeclarativeType(); GradientPresetCustomListModel::registerDeclarativeType(); ItemFilterModel::registerDeclarativeType(); + ListValidator::registerDeclarativeType(); ColorPaletteBackend::registerDeclarativeType(); Internal::QmlAnchorBindingProxy::registerDeclarativeType(); BindingEditor::registerDeclarativeType(); @@ -61,8 +63,8 @@ void Quick2PropertyEditorView::registerQmlTypes() RichTextEditorProxy::registerDeclarativeType(); SelectionDynamicPropertiesProxyModel::registerDeclarativeType(); DynamicPropertyRow::registerDeclarativeType(); - Experimental::PropertyChangesModel::registerDeclarativeType(); - Experimental::PropertyModel::registerDeclarativeType(); + PropertyChangesModel::registerDeclarativeType(); + PropertyModel::registerDeclarativeType(); const QString resourcePath = PropertyEditorQmlBackend::propertyEditorResourcesPath(); diff --git a/src/plugins/qmldesigner/components/stateseditornew/propertychangesmodel.cpp b/src/plugins/qmldesigner/components/stateseditor/propertychangesmodel.cpp similarity index 74% rename from src/plugins/qmldesigner/components/stateseditornew/propertychangesmodel.cpp rename to src/plugins/qmldesigner/components/stateseditor/propertychangesmodel.cpp index d559aea1ca1..f0f177ed9e5 100644 --- a/src/plugins/qmldesigner/components/stateseditornew/propertychangesmodel.cpp +++ b/src/plugins/qmldesigner/components/stateseditor/propertychangesmodel.cpp @@ -1,27 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2022 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of Qt Creator. -** -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3 as published by the Free Software -** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-3.0.html. -** -****************************************************************************/ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0 #include "propertychangesmodel.h" @@ -39,7 +17,6 @@ enum { }; namespace QmlDesigner { -namespace Experimental { PropertyChangesModel::PropertyChangesModel(QObject *parent) : QAbstractListModel(parent) @@ -164,5 +141,4 @@ QVariant PropertyChangesModel::modelNodeBackend() const return QVariant(); } -} // namespace Experimental } // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/stateseditornew/propertychangesmodel.h b/src/plugins/qmldesigner/components/stateseditor/propertychangesmodel.h similarity index 55% rename from src/plugins/qmldesigner/components/stateseditornew/propertychangesmodel.h rename to src/plugins/qmldesigner/components/stateseditor/propertychangesmodel.h index b73d4dad693..6686131aff6 100644 --- a/src/plugins/qmldesigner/components/stateseditornew/propertychangesmodel.h +++ b/src/plugins/qmldesigner/components/stateseditor/propertychangesmodel.h @@ -1,27 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2022 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of Qt Creator. -** -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3 as published by the Free Software -** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-3.0.html. -** -****************************************************************************/ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0 #pragma once @@ -31,7 +9,6 @@ #include namespace QmlDesigner { -namespace Experimental { class StatesEditorView; @@ -82,5 +59,4 @@ private: QPointer m_view; }; -} // namespace Experimental } // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/stateseditornew/propertymodel.cpp b/src/plugins/qmldesigner/components/stateseditor/propertymodel.cpp similarity index 75% rename from src/plugins/qmldesigner/components/stateseditornew/propertymodel.cpp rename to src/plugins/qmldesigner/components/stateseditor/propertymodel.cpp index 35dea7cb23a..0a72d60ef7a 100644 --- a/src/plugins/qmldesigner/components/stateseditornew/propertymodel.cpp +++ b/src/plugins/qmldesigner/components/stateseditor/propertymodel.cpp @@ -1,27 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2022 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of Qt Creator. -** -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3 as published by the Free Software -** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-3.0.html. -** -****************************************************************************/ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0 #include "propertymodel.h" @@ -44,7 +22,6 @@ enum { }; namespace QmlDesigner { -namespace Experimental { PropertyModel::PropertyModel(QObject *parent) : QAbstractListModel(parent) @@ -188,5 +165,4 @@ void PropertyModel::setupModel() m_properties = propertyChanges.targetProperties(); } -} // namespace Experimental } // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/stateseditornew/propertymodel.h b/src/plugins/qmldesigner/components/stateseditor/propertymodel.h similarity index 51% rename from src/plugins/qmldesigner/components/stateseditornew/propertymodel.h rename to src/plugins/qmldesigner/components/stateseditor/propertymodel.h index 492b1362c0e..c9d8e93c3f8 100644 --- a/src/plugins/qmldesigner/components/stateseditornew/propertymodel.h +++ b/src/plugins/qmldesigner/components/stateseditor/propertymodel.h @@ -1,27 +1,5 @@ -/**************************************************************************** -** -** Copyright (C) 2022 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of Qt Creator. -** -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3 as published by the Free Software -** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-3.0.html. -** -****************************************************************************/ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0 #pragma once @@ -31,7 +9,6 @@ #include namespace QmlDesigner { -namespace Experimental { class PropertyModel : public QAbstractListModel { @@ -74,5 +51,4 @@ private: QList m_properties; }; -} // namespace Experimental } // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/stateseditor/stateseditorimageprovider.cpp b/src/plugins/qmldesigner/components/stateseditor/stateseditorimageprovider.cpp index 55fcf61932a..f0a7d0bf86f 100644 --- a/src/plugins/qmldesigner/components/stateseditor/stateseditorimageprovider.cpp +++ b/src/plugins/qmldesigner/components/stateseditor/stateseditorimageprovider.cpp @@ -1,16 +1,18 @@ -// Copyright (C) 2016 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0 #include "stateseditorimageprovider.h" #include "nodeinstanceview.h" #include -namespace QmlDesigner::Internal { +namespace QmlDesigner { +namespace Internal { StatesEditorImageProvider::StatesEditorImageProvider() : QQuickImageProvider(QQuickImageProvider::Image) -{} +{ +} QImage StatesEditorImageProvider::requestImage(const QString &id, QSize *size, const QSize &requestedSize) { @@ -25,8 +27,7 @@ QImage StatesEditorImageProvider::requestImage(const QString &id, QSize *size, c bool canBeConverted; int instanceId = imageId.toInt(&canBeConverted); if (canBeConverted && m_nodeInstanceView->hasModelNodeForInternalId(instanceId)) { - image = m_nodeInstanceView->statePreviewImage( - m_nodeInstanceView->modelNodeForInternalId(instanceId)); + image = m_nodeInstanceView->statePreviewImage(m_nodeInstanceView->modelNodeForInternalId(instanceId)); } } } @@ -52,4 +53,5 @@ void StatesEditorImageProvider::setNodeInstanceView(const NodeInstanceView *node m_nodeInstanceView = nodeInstanceView; } -} // QmlDesigner::Internal +} // namespace Internal +} // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/stateseditor/stateseditorimageprovider.h b/src/plugins/qmldesigner/components/stateseditor/stateseditorimageprovider.h index 0bfb0bf3302..1bd4432a956 100644 --- a/src/plugins/qmldesigner/components/stateseditor/stateseditorimageprovider.h +++ b/src/plugins/qmldesigner/components/stateseditor/stateseditorimageprovider.h @@ -1,12 +1,12 @@ -// Copyright (C) 2016 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0 #pragma once #include "abstractview.h" -#include #include +#include namespace QmlDesigner { namespace Internal { diff --git a/src/plugins/qmldesigner/components/stateseditor/stateseditormodel.cpp b/src/plugins/qmldesigner/components/stateseditor/stateseditormodel.cpp index 96ec3fa8e63..0b53af121b8 100644 --- a/src/plugins/qmldesigner/components/stateseditor/stateseditormodel.cpp +++ b/src/plugins/qmldesigner/components/stateseditor/stateseditormodel.cpp @@ -1,31 +1,39 @@ -// Copyright (C) 2016 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0 #include "stateseditormodel.h" #include "stateseditorview.h" -#include - #include #include #include +#include #include #include #include #include +#include +#include + +#include #include -enum { debug = false }; +enum { + debug = false +}; namespace QmlDesigner { StatesEditorModel::StatesEditorModel(StatesEditorView *view) : QAbstractListModel(view) , m_statesEditorView(view) - , m_updateCounter(0) -{} + , m_hasExtend(false) + , m_extendedStates() +{ + QObject::connect(this, &StatesEditorModel::dataChanged, [this]() { emit baseStateChanged(); }); +} int StatesEditorModel::count() const { @@ -38,8 +46,8 @@ QModelIndex StatesEditorModel::index(int row, int column, const QModelIndex &par return {}; int internalNodeId = 0; - if (row > 0 && row < rowCount() - 1) // first and last rows are base state, add state - internalNodeId = m_statesEditorView->acitveStatesGroupNode() + if (row > 0) + internalNodeId = m_statesEditorView->activeStatesGroupNode() .nodeListProperty("states") .at(row - 1) .internalId(); @@ -52,17 +60,19 @@ int StatesEditorModel::rowCount(const QModelIndex &parent) const if (parent.isValid() || m_statesEditorView.isNull() || !m_statesEditorView->model()) return 0; - if (!m_statesEditorView->acitveStatesGroupNode().hasNodeListProperty("states")) - return 2; // base state + add new state + if (!m_statesEditorView->activeStatesGroupNode().hasNodeListProperty("states")) + return 1; // base state - return m_statesEditorView->acitveStatesGroupNode().nodeListProperty("states").count() - + 2; // 2 = base state + add new state + return m_statesEditorView->activeStatesGroupNode().nodeListProperty("states").count() + 1; } void StatesEditorModel::reset() { QAbstractListModel::beginResetModel(); QAbstractListModel::endResetModel(); + + evaluateExtend(); + emit baseStateChanged(); } QVariant StatesEditorModel::data(const QModelIndex &index, int role) const @@ -101,20 +111,34 @@ QVariant StatesEditorModel::data(const QModelIndex &index, int role) const return index.internalId(); case HasWhenCondition: - return stateNode.hasProperty("when"); + return stateNode.isValid() && stateNode.hasProperty("when"); - case WhenConditionString: - return stateNode.bindingProperty("when").expression(); + case WhenConditionString: { + if (stateNode.isValid() && stateNode.hasBindingProperty("when")) + return stateNode.bindingProperty("when").expression(); + else + return QString(); + } case IsDefault: { - return QmlModelState(stateNode).isDefault(); + QmlModelState modelState(stateNode); + if (modelState.isValid()) + return modelState.isDefault(); + return false; } case ModelHasDefaultState: return hasDefaultState(); - case StateType: - return index.row() == rowCount() - 1 ? "add" : "state"; + case HasExtend: + return stateNode.isValid() && stateNode.hasProperty("extend"); + + case ExtendString: { + if (stateNode.isValid() && stateNode.hasVariantProperty("extend")) + return stateNode.variantProperty("extend").value(); + else + return QString(); + } } return QVariant(); @@ -129,7 +153,8 @@ QHash StatesEditorModel::roleNames() const {WhenConditionString, "whenConditionString"}, {IsDefault, "isDefault"}, {ModelHasDefaultState, "modelHasDefaultState"}, - {StateType, "type"}}; + {HasExtend, "hasExtend"}, + {ExtendString, "extendString"}}; return roleNames; } @@ -155,9 +180,6 @@ void StatesEditorModel::removeState(int stateIndex) if (stateIndex >= 0) { beginRemoveRows(QModelIndex(), 0, stateIndex); endRemoveRows(); - - beginResetModel(); - endResetModel(); } } @@ -166,12 +188,13 @@ void StatesEditorModel::renameState(int internalNodeId, const QString &newName) if (newName == m_statesEditorView->currentStateName()) return; - if (newName.isEmpty() || !m_statesEditorView->validStateName(newName)) { - QTimer::singleShot(0, [newName] { + if (newName.isEmpty() ||! m_statesEditorView->validStateName(newName)) { + QTimer::singleShot(0, this, [newName] { Core::AsynchronousMessageBox::warning( - tr("Invalid State Name"), - newName.isEmpty() ? tr("The empty string as a name is reserved for the base state.") - : tr("Name already used in another state.")); + tr("Invalid state name"), + newName.isEmpty() ? + tr("The empty string as a name is reserved for the base state.") : + tr("Name already used in another state")); }); reset(); } else { @@ -198,9 +221,14 @@ QStringList StatesEditorModel::autoComplete(const QString &text, int pos, bool e return QStringList(); } -QVariant StatesEditorModel::stateModelNode() +QVariant StatesEditorModel::stateModelNode(int internalNodeId) { - return QVariant::fromValue(m_statesEditorView->currentStateNode()); + if (!m_statesEditorView->model()) + return QVariant(); + + ModelNode node = m_statesEditorView->modelNodeForInternalId(internalNodeId); + + return QVariant::fromValue(m_statesEditorView->modelNodeForInternalId(internalNodeId)); } void StatesEditorModel::setStateAsDefault(int internalNodeId) @@ -233,4 +261,193 @@ bool StatesEditorModel::hasAnnotation(int internalNodeId) const return m_statesEditorView->hasAnnotation(internalNodeId); } +QStringList StatesEditorModel::stateGroups() const +{ + if (!m_statesEditorView->isAttached()) + return {}; + + const auto groupMetaInfo = m_statesEditorView->model()->qtQuickStateGroupMetaInfo(); + + auto stateGroups = Utils::transform(m_statesEditorView->allModelNodesOfType(groupMetaInfo), + [](const ModelNode &node) { return node.displayName(); }); + stateGroups.prepend(tr("Default")); + return stateGroups; +} + +QString StatesEditorModel::activeStateGroup() const +{ + if (auto stateGroup = m_statesEditorView->activeStatesGroupNode()) + return stateGroup.displayName(); + + return {}; +} + +void StatesEditorModel::setActiveStateGroup(const QString &name) +{ + if (!m_statesEditorView->isAttached()) + return; + + const auto groupMetaInfo = m_statesEditorView->model()->qtQuickStateGroupMetaInfo(); + + auto modelNode = Utils::findOrDefault(m_statesEditorView->allModelNodesOfType(groupMetaInfo), + [&name](const ModelNode &node) { + return node.displayName() == name; + }); + + QTC_ASSERT(!modelNode.isValid(), return ); + + if (modelNode.isValid()) + m_statesEditorView->setActiveStatesGroupNode(modelNode); +} + +int StatesEditorModel::activeStateGroupIndex() const +{ + return m_statesEditorView->activeStatesGroupIndex(); +} + +void StatesEditorModel::setActiveStateGroupIndex(int index) +{ + m_statesEditorView->setActiveStatesGroupIndex(index); +} + +bool StatesEditorModel::renameActiveStateGroup(const QString &name) +{ + auto stateGroup = m_statesEditorView->activeStatesGroupNode(); + + if (!stateGroup.isValid() || stateGroup.isRootNode()) + return false; + + if (!QmlDesigner::ModelNode::isValidId(name) || m_statesEditorView->hasId(name)) { + QString errMsg = QmlDesigner::ModelNode::getIdValidityErrorMessage(name); + if (!errMsg.isEmpty()) + Core::AsynchronousMessageBox::warning(tr("Invalid ID"), errMsg); + else + Core::AsynchronousMessageBox::warning(tr("Invalid ID"), + tr("%1 already exists.").arg(name)); + return false; + } + + stateGroup.setIdWithRefactoring(name); + emit stateGroupsChanged(); + return true; +} + +void StatesEditorModel::addStateGroup(const QString &name) +{ + m_statesEditorView->executeInTransaction("createStateGroup", [this, name]() { + const TypeName typeName = "QtQuick.StateGroup"; + auto metaInfo = m_statesEditorView->model()->metaInfo(typeName); + int minorVersion = metaInfo.minorVersion(); + int majorVersion = metaInfo.majorVersion(); + auto stateGroupNode = m_statesEditorView->createModelNode(typeName, + majorVersion, + minorVersion); + stateGroupNode.setIdWithoutRefactoring(m_statesEditorView->model()->generateNewId(name)); + + m_statesEditorView->rootModelNode().defaultNodeAbstractProperty().reparentHere( + stateGroupNode); + m_statesEditorView->setActiveStatesGroupNode(stateGroupNode); + }); +} + +void StatesEditorModel::removeStateGroup() +{ + if (m_statesEditorView->activeStatesGroupNode().isRootNode()) + return; + + m_statesEditorView->executeInTransaction("removeStateGroup", [this]() { + m_statesEditorView->activeStatesGroupNode().destroy(); + }); +} + +QVariantMap StatesEditorModel::get(int idx) const +{ + const QHash &names = roleNames(); + QHash::const_iterator i = names.constBegin(); + + QVariantMap res; + QModelIndex modelIndex = index(idx); + + while (i != names.constEnd()) { + QVariant data = modelIndex.data(i.key()); + + res[QString::fromUtf8(i.value())] = data; + ++i; + } + return res; +} + +QVariantMap StatesEditorModel::baseState() const +{ + return get(0); +} + +bool StatesEditorModel::hasExtend() const +{ + return m_hasExtend; +} + +QStringList StatesEditorModel::extendedStates() const +{ + return m_extendedStates; +} + +void StatesEditorModel::move(int from, int to) +{ + // This does not alter the code (rewriter) which means the reordering is not presistent + + if (from == to) + return; + + int specialIndex = (from < to ? to + 1 : to); + beginMoveRows(QModelIndex(), from, from, QModelIndex(), specialIndex); + endMoveRows(); +} + +void StatesEditorModel::drop(int from, int to) +{ + m_statesEditorView->moveStates(from, to); +} + +void StatesEditorModel::evaluateExtend() +{ + bool hasExtend = m_statesEditorView->hasExtend(); + + if (m_hasExtend != hasExtend) { + m_hasExtend = hasExtend; + emit hasExtendChanged(); + } + + auto extendedStates = m_statesEditorView->extendedStates(); + + if (extendedStates.size() != m_extendedStates.size()) { + m_extendedStates = extendedStates; + emit extendedStatesChanged(); + return; + } + + for (int i = 0; i != m_extendedStates.size(); ++i) { + if (extendedStates[i] != m_extendedStates[i]) { + m_extendedStates = extendedStates; + emit extendedStatesChanged(); + return; + } + } +} + +bool StatesEditorModel::canAddNewStates() const +{ + return m_canAddNewStates; +} + +void StatesEditorModel::setCanAddNewStates(bool b) +{ + if (b == m_canAddNewStates) + return; + + m_canAddNewStates = b; + + emit canAddNewStatesChanged(); +} + } // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/stateseditor/stateseditormodel.h b/src/plugins/qmldesigner/components/stateseditor/stateseditormodel.h index 832f0cdbffd..8eff287c869 100644 --- a/src/plugins/qmldesigner/components/stateseditor/stateseditormodel.h +++ b/src/plugins/qmldesigner/components/stateseditor/stateseditormodel.h @@ -1,5 +1,5 @@ -// Copyright (C) 2016 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0 #pragma once @@ -14,6 +14,9 @@ class StatesEditorModel : public QAbstractListModel { Q_OBJECT + Q_PROPERTY(bool canAddNewStates READ canAddNewStates WRITE setCanAddNewStates NOTIFY + canAddNewStatesChanged) + enum { StateNameRole = Qt::DisplayRole, StateImageSourceRole = Qt::UserRole, @@ -22,13 +25,14 @@ class StatesEditorModel : public QAbstractListModel WhenConditionString, IsDefault, ModelHasDefaultState, - StateType + HasExtend, + ExtendString }; public: StatesEditorModel(StatesEditorView *view); - int count() const; + Q_INVOKABLE int count() const; QModelIndex index(int row, int column = 0, const QModelIndex &parent = QModelIndex()) const override; int rowCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; @@ -41,7 +45,8 @@ public: Q_INVOKABLE void setWhenCondition(int internalNodeId, const QString &condition); Q_INVOKABLE void resetWhenCondition(int internalNodeId); Q_INVOKABLE QStringList autoComplete(const QString &text, int pos, bool explicitComplete); - Q_INVOKABLE QVariant stateModelNode(); + Q_INVOKABLE QVariant stateModelNode(int internalNodeId); + Q_INVOKABLE void setStateAsDefault(int internalNodeId); Q_INVOKABLE void resetDefaultState(); Q_INVOKABLE bool hasDefaultState() const; @@ -49,14 +54,58 @@ public: Q_INVOKABLE void removeAnnotation(int internalNodeId); Q_INVOKABLE bool hasAnnotation(int internalNodeId) const; + QStringList stateGroups() const; + QString activeStateGroup() const; + void setActiveStateGroup(const QString &name); + int activeStateGroupIndex() const; + void setActiveStateGroupIndex(int index); + + Q_INVOKABLE bool renameActiveStateGroup(const QString &name); + + Q_INVOKABLE void addStateGroup(const QString &name); + Q_INVOKABLE void removeStateGroup(); + + Q_INVOKABLE QVariantMap get(int idx) const; + + QVariantMap baseState() const; + bool hasExtend() const; + QStringList extendedStates() const; + + Q_PROPERTY(QVariantMap baseState READ baseState NOTIFY baseStateChanged) + Q_PROPERTY(QStringList extendedStates READ extendedStates NOTIFY extendedStatesChanged) + + Q_PROPERTY(bool hasExtend READ hasExtend NOTIFY hasExtendChanged) + + Q_PROPERTY(QString activeStateGroup READ activeStateGroup WRITE setActiveStateGroup NOTIFY + activeStateGroupChanged) + Q_PROPERTY(int activeStateGroupIndex READ activeStateGroupIndex WRITE setActiveStateGroupIndex + NOTIFY activeStateGroupIndexChanged) + Q_PROPERTY(QStringList stateGroups READ stateGroups NOTIFY stateGroupsChanged) + + Q_INVOKABLE void move(int from, int to); + Q_INVOKABLE void drop(int from, int to); + void reset(); + void evaluateExtend(); + + bool canAddNewStates() const; + void setCanAddNewStates(bool b); signals: void changedToState(int n); + void baseStateChanged(); + void hasExtendChanged(); + void extendedStatesChanged(); + void activeStateGroupChanged(); + void activeStateGroupIndexChanged(); + void stateGroupsChanged(); + void canAddNewStatesChanged(); private: QPointer m_statesEditorView; - int m_updateCounter; + bool m_hasExtend; + QStringList m_extendedStates; + bool m_canAddNewStates = false; }; } // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/stateseditor/stateseditorview.cpp b/src/plugins/qmldesigner/components/stateseditor/stateseditorview.cpp index ea9bed74890..03cd658f22a 100644 --- a/src/plugins/qmldesigner/components/stateseditor/stateseditorview.cpp +++ b/src/plugins/qmldesigner/components/stateseditor/stateseditorview.cpp @@ -1,21 +1,29 @@ -// Copyright (C) 2016 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0 #include "stateseditorview.h" - +#include "propertychangesmodel.h" #include "stateseditormodel.h" #include "stateseditorwidget.h" -#include -#include -#include +#include +#include +#include +#include +#include + #include + +#include +#include +#include +#include #include + #include #include #include #include - #include #include #include @@ -34,8 +42,9 @@ namespace QmlDesigner { We always have 'one' current state, where we get updates from (see sceneChanged()). In case the current state is the base state, we render the base state + all other states. */ + StatesEditorView::StatesEditorView(ExternalDependenciesInterface &externalDependencies) - : AbstractView{externalDependencies} + : AbstractView(externalDependencies) , m_statesEditorModel(new StatesEditorModel(this)) , m_lastIndex(-1) , m_editor(nullptr) @@ -57,32 +66,215 @@ WidgetInfo StatesEditorView::widgetInfo() m_statesEditorWidget = new StatesEditorWidget(this, m_statesEditorModel.data()); return createWidgetInfo(m_statesEditorWidget.data(), - QLatin1String("StatesEditor"), + "StatesEditor", WidgetInfo::BottomPane, 0, - tr("States"), - tr("States view")); + tr("States")); } -void StatesEditorView::rootNodeTypeChanged(const QString & /*type*/, - int /*majorVersion*/, - int /*minorVersion*/) +void StatesEditorView::rootNodeTypeChanged(const QString &/*type*/, int /*majorVersion*/, int /*minorVersion*/) { checkForStatesAvailability(); } -ModelNode StatesEditorView::acitveStatesGroupNode() const +ModelNode StatesEditorView::activeStatesGroupNode() const { return m_activeStatesGroupNode; } -void StatesEditorView::setAcitveStatesGroupNode(const ModelNode &modelNode) +void StatesEditorView::setActiveStatesGroupNode(const ModelNode &modelNode) { if (m_activeStatesGroupNode == modelNode) return; m_activeStatesGroupNode = modelNode; resetModel(); + + checkForStatesAvailability(); + + emit m_statesEditorModel->activeStateGroupChanged(); + emit m_statesEditorModel->activeStateGroupIndexChanged(); +} + +int StatesEditorView::activeStatesGroupIndex() const +{ + if (!model()) + return -1; + + return Utils::indexOf(allModelNodesOfType(model()->qtQuickStateGroupMetaInfo()), + [this](const ModelNode &node) { return node == m_activeStatesGroupNode; }) + + 1; +} + +void StatesEditorView::setActiveStatesGroupIndex(int index) +{ + if (!model()) + return; + + if (index > 0) { + const ModelNode statesGroup = allModelNodesOfType(model()->qtQuickStateGroupMetaInfo()) + .at(index - 1); + if (statesGroup.isValid()) + setActiveStatesGroupNode(statesGroup); + } else { + setActiveStatesGroupNode(rootModelNode()); + } +} + +void StatesEditorView::registerPropertyChangesModel(PropertyChangesModel *model) +{ + m_propertyChangedModels.insert(model); +} + +void StatesEditorView::deregisterPropertyChangesModel(PropertyChangesModel *model) +{ + m_propertyChangedModels.remove(model); +} + +void StatesEditorView::synchonizeCurrentStateFromWidget() +{ + if (!model()) + return; + + if (m_block) + return; + + int internalId = m_statesEditorWidget->currentStateInternalId(); + + if (internalId > 0 && hasModelNodeForInternalId(internalId)) { + ModelNode node = modelNodeForInternalId(internalId); + QmlModelState modelState(node); + if (modelState.isValid() && modelState != currentState()) + setCurrentState(modelState); + } else { + setCurrentState(baseState()); + } +} + +void StatesEditorView::createNewState() +{ + // can happen when root node is e.g. a ListModel + if (!QmlVisualNode::isValidQmlVisualNode(activeStatesGroupNode()) + && m_activeStatesGroupNode.type() != "QtQuick.StateGroup") + return; + + QmlDesignerPlugin::emitUsageStatistics(Constants::EVENT_STATE_ADDED); + + QStringList modelStateNames = activeStateGroup().names(); + + QString newStateName; + int index = 1; + while (true) { + newStateName = QString(QStringLiteral("State%1")).arg(index++); + if (!modelStateNames.contains(newStateName)) + break; + } + + executeInTransaction("createNewState", [this, newStateName]() { + activeStatesGroupNode().validId(); + + ModelNode newState = activeStateGroup().addState(newStateName); + setCurrentState(newState); + }); +} + +void StatesEditorView::cloneState(int nodeId) +{ + if (!(nodeId > 0 && hasModelNodeForInternalId(nodeId))) + return; + + ModelNode stateNode(modelNodeForInternalId(nodeId)); + QTC_ASSERT(stateNode.simplifiedTypeName() == "State", return ); + + QmlModelState modelState(stateNode); + if (!modelState.isValid() || modelState.isBaseState()) + return; + + QmlDesignerPlugin::emitUsageStatistics(Constants::EVENT_STATE_CLONED); + + QString newName = modelState.name(); + + // Strip out numbers at the end of the string + QRegularExpression regEx(QLatin1String("[0-9]+$")); + const QRegularExpressionMatch match = regEx.match(newName); + if (match.hasMatch() && (match.capturedStart() + match.capturedLength() == newName.length())) + newName = newName.left(match.capturedStart()); + + int i = 1; + QStringList stateNames = activeStateGroup().names(); + while (stateNames.contains(newName + QString::number(i))) + i++; + const QString newStateName = newName + QString::number(i); + + QmlModelState newState; + + executeInTransaction("cloneState", [newStateName, modelState, &newState]() { + newState = modelState.duplicate(newStateName); + }); + + ModelNode newNode = newState.modelNode(); + int from = newNode.parentProperty().indexOf(newNode); + int to = stateNode.parentProperty().indexOf(stateNode) + 1; + + // When duplicating an extended state the new state needs to be added after the extend group. + if (!modelState.hasExtend()) { + auto modelNodeList = activeStatesGroupNode().nodeListProperty("states").toModelNodeList(); + for (; to != modelNodeList.count(); ++to) { + QmlModelState currentState(modelNodeList.at(to)); + if (!currentState.isValid() || currentState.isBaseState() || !currentState.hasExtend()) + break; + } + } + + executeInTransaction("moveState", [this, &newState, from, to]() { + activeStatesGroupNode().nodeListProperty("states").slide(from, to); + setCurrentState(newState); + }); +} + +void StatesEditorView::extendState(int nodeId) +{ + if (!(nodeId > 0 && hasModelNodeForInternalId(nodeId))) + return; + + ModelNode stateNode(modelNodeForInternalId(nodeId)); + QTC_ASSERT(stateNode.simplifiedTypeName() == "State", return ); + + QmlModelState modelState(stateNode); + if (!modelState.isValid() || modelState.isBaseState()) + return; + + QmlDesignerPlugin::emitUsageStatistics(Constants::EVENT_STATE_EXTENDED); + + QString newName = modelState.name(); + + // Strip out numbers at the end of the string + QRegularExpression regEx(QLatin1String("[0-9]+$")); + const QRegularExpressionMatch match = regEx.match(newName); + if (match.hasMatch() && (match.capturedStart() + match.capturedLength() == newName.length())) + newName = newName.left(match.capturedStart()); + + int i = 1; + QStringList stateNames = activeStateGroup().names(); + while (stateNames.contains(newName + QString::number(i))) + i++; + const QString newStateName = newName + QString::number(i); + + QmlModelState newState; + + executeInTransaction("extendState", [this, newStateName, modelState, &newState]() { + newState = activeStateGroup().addState(newStateName); + newState.setExtend(modelState.name()); + }); + + ModelNode newNode = newState.modelNode(); + int from = newNode.parentProperty().indexOf(newNode); + int to = stateNode.parentProperty().indexOf(stateNode) + 1; + + executeInTransaction("moveState", [this, &newState, from, to]() { + activeStatesGroupNode().nodeListProperty("states").slide(from, to); + setCurrentState(newState); + }); } void StatesEditorView::removeState(int nodeId) @@ -90,7 +282,7 @@ void StatesEditorView::removeState(int nodeId) try { if (nodeId > 0 && hasModelNodeForInternalId(nodeId)) { ModelNode stateNode(modelNodeForInternalId(nodeId)); - Q_ASSERT(stateNode.metaInfo().isQtQuickState()); + QTC_ASSERT(stateNode.simplifiedTypeName() == "State", return ); QmlModelState modelState(stateNode); if (modelState.isValid()) { @@ -147,6 +339,9 @@ void StatesEditorView::removeState(int nodeId) NodeListProperty parentProperty = stateNode.parentProperty().toNodeListProperty(); + if (modelState.isDefault()) + m_statesEditorModel->resetDefaultState(); + if (parentProperty.count() <= 1) { setCurrentState(baseState()); } else if (parentProperty.isValid()) { @@ -164,63 +359,13 @@ void StatesEditorView::removeState(int nodeId) } } -void StatesEditorView::synchonizeCurrentStateFromWidget() -{ - if (!model()) - return; - - if (m_block) - return; - - int internalId = m_statesEditorWidget->currentStateInternalId(); - - if (internalId > 0 && hasModelNodeForInternalId(internalId)) { - ModelNode node = modelNodeForInternalId(internalId); - QmlModelState modelState(node); - if (modelState.isValid() && modelState != currentState()) - setCurrentState(modelState); - } else { - setCurrentState(baseState()); - } -} - -void StatesEditorView::createNewState() -{ - if (currentState().isBaseState()) - addState(); - else - duplicateCurrentState(); -} - -void StatesEditorView::addState() -{ - // can happen when root node is e.g. a ListModel - if (!QmlVisualNode::isValidQmlVisualNode(acitveStatesGroupNode()) - && m_activeStatesGroupNode.type() != "QtQuick.StateGroup") - return; - - QmlDesignerPlugin::emitUsageStatistics(Constants::EVENT_STATE_ADDED); - - QStringList modelStateNames = activeStateGroup().names(); - - QString newStateName; - int index = 1; - while (true) { - newStateName = QString(QStringLiteral("State%1")).arg(index++); - if (!modelStateNames.contains(newStateName)) - break; - } - - executeInTransaction("addState", [this, newStateName]() { - acitveStatesGroupNode().validId(); - - ModelNode newState = activeStateGroup().addState(newStateName); - setCurrentState(newState); - }); -} - void StatesEditorView::resetModel() { + if (m_bulkChange) { + m_modelDirty = true; + return; + } + if (m_statesEditorModel) m_statesEditorModel->reset(); @@ -230,42 +375,83 @@ void StatesEditorView::resetModel() else m_statesEditorWidget->setCurrentStateInternalId(currentState().modelNode().internalId()); } + + m_modelDirty = false; } -void StatesEditorView::duplicateCurrentState() +void StatesEditorView::resetPropertyChangesModels() { - QmlModelState state = currentState(); + if (m_bulkChange) { + m_propertyChangesDirty = true; + return; + } - Q_ASSERT(!state.isBaseState()); + std::for_each(m_propertyChangedModels.begin(), + m_propertyChangedModels.end(), + [](PropertyChangesModel *model) { model->reset(); }); - QString newName = state.name(); + m_propertyChangesDirty = false; +} - // Strip out numbers at the end of the string - QRegularExpression regEx(QLatin1String("[0-9]+$")); - const QRegularExpressionMatch match = regEx.match(newName); - if (match.hasMatch() && (match.capturedStart() + match.capturedLength() == newName.length())) - newName = newName.left(match.capturedStart()); +void StatesEditorView::resetExtend() +{ + if (m_bulkChange) { + m_extendDirty = true; + return; + } - int i = 1; - QStringList stateNames = activeStateGroup().names(); - while (stateNames.contains(newName + QString::number(i))) - i++; - const QString newStateName = newName + QString::number(i); + m_statesEditorModel->evaluateExtend(); - executeInTransaction("addState", [this, newStateName, state]() { - QmlModelState newState = state.duplicate(newStateName); - setCurrentState(newState); - }); + m_extendDirty = false; +} + +void StatesEditorView::resetStateGroups() +{ + if (m_bulkChange) { + m_stateGroupsDirty = true; + return; + } + + emit m_statesEditorModel->stateGroupsChanged(); + + m_stateGroupsDirty = false; } void StatesEditorView::checkForStatesAvailability() { if (m_statesEditorWidget) { - const bool isVisual = QmlVisualNode::isValidQmlVisualNode(acitveStatesGroupNode()); - m_statesEditorWidget->showAddNewStatesButton(isVisual); + const bool isVisual = activeStatesGroupNode().metaInfo().isBasedOn( + model()->qtQuickItemMetaInfo(), model()->qtQuick3DNodeMetaInfo()); + const bool isRoot = activeStatesGroupNode().isRootNode(); + m_statesEditorModel->setCanAddNewStates(isVisual || !isRoot); } } +void StatesEditorView::beginBulkChange() +{ + m_bulkChange = true; +} + +void StatesEditorView::endBulkChange() +{ + if (!m_bulkChange) + return; + + m_bulkChange = false; + + if (m_modelDirty) + resetModel(); + + if (m_propertyChangesDirty) + resetPropertyChangesModels(); + + if (m_extendDirty) + resetExtend(); + + if (m_stateGroupsDirty) + resetStateGroups(); +} + void StatesEditorView::setCurrentState(const QmlModelState &state) { if (!model() && !state.isValid()) @@ -282,7 +468,7 @@ QmlModelState StatesEditorView::baseState() const QmlModelStateGroup StatesEditorView::activeStateGroup() const { - return QmlModelStateGroup(acitveStatesGroupNode()); + return QmlModelStateGroup(activeStatesGroupNode()); } bool StatesEditorView::validStateName(const QString &name) const @@ -297,6 +483,35 @@ bool StatesEditorView::validStateName(const QString &name) const return true; } +bool StatesEditorView::hasExtend() const +{ + if (!model()) + return false; + + const QList modelStates = activeStateGroup().allStates(); + for (const QmlModelState &state : modelStates) { + if (state.hasExtend()) + return true; + } + return false; +} + +QStringList StatesEditorView::extendedStates() const +{ + if (!model()) + return QStringList(); + + QStringList states; + + const QList modelStates = activeStateGroup().allStates(); + for (const QmlModelState &state : modelStates) { + if (state.hasExtend()) + states.append(state.extend()); + } + states.removeDuplicates(); + return states; +} + QString StatesEditorView::currentStateName() const { return currentState().isValid() ? currentState().name() : QString(); @@ -305,20 +520,33 @@ QString StatesEditorView::currentStateName() const void StatesEditorView::renameState(int internalNodeId, const QString &newName) { if (hasModelNodeForInternalId(internalNodeId)) { - QmlModelState state(modelNodeForInternalId(internalNodeId)); + QmlModelState renamedState(modelNodeForInternalId(internalNodeId)); try { - if (state.isValid() && state.name() != newName) { - // Jump to base state for the change - QmlModelState oldState = currentState(); - setCurrentState(baseState()); - const bool updateDefault = state.isDefault(); + if (renamedState.isValid() && renamedState.name() != newName) { + executeInTransaction("renameState", [this, &renamedState, &newName]() { + // Jump to base state for the change + QmlModelState oldState = currentState(); + setCurrentState(baseState()); + const bool updateDefault = renamedState.isDefault(); - state.setName(newName.trimmed()); + // If state is extended rename all references + QList states; + const QList modelStates = activeStateGroup().allStates(); + for (const QmlModelState &state : modelStates) { + if (state.hasExtend() && state.extend() == renamedState.name()) + states.append(state); + } - if (updateDefault) - state.setAsDefault(); + renamedState.setName(newName.trimmed()); - setCurrentState(oldState); + for (QmlModelState &state : states) + state.setExtend(newName.trimmed()); + + if (updateDefault) + renamedState.setAsDefault(); + + setCurrentState(oldState); + }); } } catch (const RewritingException &e) { e.showException(); @@ -357,7 +585,9 @@ void StatesEditorView::resetWhenCondition(int internalNodeId) if (hasModelNodeForInternalId(internalNodeId)) { QmlModelState state(modelNodeForInternalId(internalNodeId)); try { - state.modelNode().removeProperty("when"); + if (state.isValid() && state.modelNode().hasProperty("when")) + state.modelNode().removeProperty("when"); + } catch (const RewritingException &e) { e.showException(); } @@ -393,8 +623,8 @@ void StatesEditorView::resetDefaultState() const QScopeGuard cleanup([&] { m_block = false; }); try { - if (acitveStatesGroupNode().hasProperty("state")) - acitveStatesGroupNode().removeProperty("state"); + if (activeStatesGroupNode().hasProperty("state")) + activeStatesGroupNode().removeProperty("state"); } catch (const RewritingException &e) { e.showException(); @@ -403,7 +633,7 @@ void StatesEditorView::resetDefaultState() bool StatesEditorView::hasDefaultState() const { - return acitveStatesGroupNode().hasProperty("state"); + return activeStatesGroupNode().hasProperty("state"); } void StatesEditorView::setAnnotation(int internalNodeId) @@ -418,7 +648,9 @@ void StatesEditorView::setAnnotation(int internalNodeId) QmlModelState state(modelNodeForInternalId(internalNodeId)); try { if (state.isValid()) { - if (ModelNode modelNode = state.modelNode()) { + ModelNode modelNode = state.modelNode(); + + if (modelNode.isValid()) { if (!m_editor) m_editor = new AnnotationEditor(this); @@ -444,9 +676,8 @@ void StatesEditorView::removeAnnotation(int internalNodeId) if (hasModelNodeForInternalId(internalNodeId)) { QmlModelState state(modelNodeForInternalId(internalNodeId)); try { - if (state.isValid()) { + if (state.isValid()) state.removeAnnotation(); - } } catch (const RewritingException &e) { e.showException(); @@ -456,11 +687,13 @@ void StatesEditorView::removeAnnotation(int internalNodeId) bool StatesEditorView::hasAnnotation(int internalNodeId) const { + if (!model()) + return false; + if (hasModelNodeForInternalId(internalNodeId)) { QmlModelState state(modelNodeForInternalId(internalNodeId)); - if (state.isValid()) { + if (state.isValid()) return state.hasAnnotation(); - } } return false; @@ -471,7 +704,7 @@ void StatesEditorView::modelAttached(Model *model) if (model == AbstractView::model()) return; - Q_ASSERT(model); + QTC_ASSERT(model, return ); AbstractView::modelAttached(model); m_activeStatesGroupNode = rootModelNode(); @@ -482,6 +715,10 @@ void StatesEditorView::modelAttached(Model *model) checkForStatesAvailability(); resetModel(); + resetStateGroups(); + + emit m_statesEditorModel->activeStateGroupChanged(); + emit m_statesEditorModel->activeStateGroupIndexChanged(); } void StatesEditorView::modelAboutToBeDetached(Model *model) @@ -493,12 +730,17 @@ void StatesEditorView::modelAboutToBeDetached(Model *model) void StatesEditorView::propertiesRemoved(const QList &propertyList) { for (const AbstractProperty &property : propertyList) { - if (property.name() == "states" - && property.parentModelNode() == activeStateGroup().modelNode()) + if (property.name() == "states" && property.parentModelNode() == activeStateGroup().modelNode()) resetModel(); - if (property.name() == "when" + if ((property.name() == "when" || property.name() == "name") && QmlModelState::isValidQmlModelState(property.parentModelNode())) resetModel(); + if (property.name() == "extend") + resetExtend(); + if (property.parentModelNode().simplifiedTypeName() == "PropertyChanges" + || (property.name() == "changes" + && property.parentModelNode().simplifiedTypeName() == "State")) + resetPropertyChangesModels(); } } @@ -512,16 +754,38 @@ void StatesEditorView::nodeAboutToBeRemoved(const ModelNode &removedNode) } if (currentState().isValid() && removedNode == currentState()) setCurrentState(baseState()); + + if (removedNode.simplifiedTypeName() == "PropertyChanges") + m_propertyChangesRemoved = true; + + if (removedNode.simplifiedTypeName() == "StateGroup") { + if (removedNode == activeStatesGroupNode()) + setActiveStatesGroupNode(rootModelNode()); + + m_stateGroupRemoved = true; + } } void StatesEditorView::nodeRemoved(const ModelNode & /*removedNode*/, const NodeAbstractProperty &parentProperty, PropertyChangeFlags /*propertyChange*/) { - if (parentProperty.isValid() && parentProperty.parentModelNode() == activeStateGroup().modelNode() + if (parentProperty.isValid() + && parentProperty.parentModelNode() == activeStateGroup().modelNode() && parentProperty.name() == "states") { m_statesEditorModel->removeState(m_lastIndex); m_lastIndex = -1; + resetModel(); + } + + if (m_propertyChangesRemoved) { + m_propertyChangesRemoved = false; + resetPropertyChangesModels(); + } + + if (m_stateGroupRemoved) { + m_stateGroupRemoved = false; + resetStateGroups(); } } @@ -534,6 +798,9 @@ void StatesEditorView::nodeAboutToBeReparented(const ModelNode &node, && oldPropertyParent.parentModelNode() == activeStateGroup().modelNode() && oldPropertyParent.name() == "states") m_lastIndex = oldPropertyParent.indexOf(node); + + if (node.simplifiedTypeName() == "StateGroup") + resetStateGroups(); } void StatesEditorView::nodeReparented(const ModelNode &node, @@ -543,10 +810,11 @@ void StatesEditorView::nodeReparented(const ModelNode &node, { if (oldPropertyParent.isValid() && oldPropertyParent.parentModelNode() == activeStateGroup().modelNode() - && oldPropertyParent.name() == "states") + && oldPropertyParent.name() == "states") { m_statesEditorModel->removeState(m_lastIndex); - - m_lastIndex = -1; + resetModel(); + m_lastIndex = -1; + } if (newPropertyParent.isValid() && newPropertyParent.parentModelNode() == activeStateGroup().modelNode() @@ -554,23 +822,31 @@ void StatesEditorView::nodeReparented(const ModelNode &node, int index = newPropertyParent.indexOf(node); m_statesEditorModel->insertState(index); } + + if (node.simplifiedTypeName() == "PropertyChanges") + resetPropertyChangesModels(); } void StatesEditorView::nodeOrderChanged(const NodeListProperty &listProperty) { + if (m_block) + return; + if (listProperty.isValid() && listProperty.parentModelNode() == activeStateGroup().modelNode() && listProperty.name() == "states") resetModel(); } -void StatesEditorView::bindingPropertiesChanged( - const QList &propertyList, - [[maybe_unused]] AbstractView::PropertyChangeFlags propertyChange) +void StatesEditorView::bindingPropertiesChanged(const QList &propertyList, AbstractView::PropertyChangeFlags propertyChange) { + Q_UNUSED(propertyChange) + for (const BindingProperty &property : propertyList) { if (property.name() == "when" && QmlModelState::isValidQmlModelState(property.parentModelNode())) resetModel(); + if (property.parentModelNode().simplifiedTypeName() == "PropertyChanges") + resetPropertyChangesModels(); } } @@ -590,9 +866,36 @@ void StatesEditorView::variantPropertiesChanged(const QList &pr else if (property.name() == "state" && property.parentModelNode() == activeStateGroup().modelNode()) resetModel(); + else if (property.name() == "extend") + resetExtend(); + + if (property.parentModelNode().simplifiedTypeName() == "PropertyChanges") + resetPropertyChangesModels(); } } +void StatesEditorView::customNotification(const AbstractView * /*view*/, + const QString &identifier, + const QList & /*nodeList*/, + const QList & /*data*/) +{ + if (identifier == StartRewriterAmend) + beginBulkChange(); + + if (identifier == EndRewriterAmend) + endBulkChange(); +} + +void StatesEditorView::rewriterBeginTransaction() +{ + beginBulkChange(); +} + +void StatesEditorView::rewriterEndTransaction() +{ + endBulkChange(); +} + void StatesEditorView::currentStateChanged(const ModelNode &node) { QmlModelState newQmlModelState(node); @@ -627,4 +930,20 @@ void StatesEditorView::instancesPreviewImageChanged(const QVector &no m_statesEditorModel->updateState(minimumIndex, maximumIndex); } +void StatesEditorView::moveStates(int from, int to) +{ + if (m_block) + return; + + m_block = true; + auto guard = qScopeGuard([&]() { m_block = false; }); + + if (!activeStatesGroupNode().hasNodeListProperty("states")) + return; + + executeInTransaction("moveState", [this, from, to]() { + activeStatesGroupNode().nodeListProperty("states").slide(from - 1, to - 1); + }); +} + } // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/stateseditor/stateseditorview.h b/src/plugins/qmldesigner/components/stateseditor/stateseditorview.h index 52329b940d8..502e5d2ac6f 100644 --- a/src/plugins/qmldesigner/components/stateseditor/stateseditorview.h +++ b/src/plugins/qmldesigner/components/stateseditor/stateseditorview.h @@ -1,5 +1,5 @@ -// Copyright (C) 2016 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0 #pragma once @@ -7,14 +7,17 @@ #include +#include + namespace QmlDesigner { +class AnnotationEditor; + class StatesEditorModel; class StatesEditorWidget; -class AnnotationEditor; +class PropertyChangesModel; -class StatesEditorView : public AbstractView -{ +class StatesEditorView : public AbstractView { Q_OBJECT public: @@ -31,11 +34,15 @@ public: void removeAnnotation(int internalNodeId); bool hasAnnotation(int internalNodeId) const; bool validStateName(const QString &name) const; + bool hasExtend() const; + QStringList extendedStates() const; QString currentStateName() const; void setCurrentState(const QmlModelState &state); QmlModelState baseState() const; QmlModelStateGroup activeStateGroup() const; + void moveStates(int from, int to); + // AbstractView void modelAttached(Model *model) override; void modelAboutToBeDetached(Model *model) override; @@ -58,6 +65,13 @@ public: void variantPropertiesChanged(const QList &propertyList, PropertyChangeFlags propertyChange) override; + void customNotification(const AbstractView *view, + const QString &identifier, + const QList &nodeList, + const QList &data) override; + void rewriterBeginTransaction() override; + void rewriterEndTransaction() override; + // AbstractView void currentStateChanged(const ModelNode &node) override; @@ -67,21 +81,33 @@ public: void rootNodeTypeChanged(const QString &type, int majorVersion, int minorVersion) override; - ModelNode acitveStatesGroupNode() const; - void setAcitveStatesGroupNode(const ModelNode &modelNode); + ModelNode activeStatesGroupNode() const; + void setActiveStatesGroupNode(const ModelNode &modelNode); + + int activeStatesGroupIndex() const; + void setActiveStatesGroupIndex(int index); + + void registerPropertyChangesModel(PropertyChangesModel *model); + void deregisterPropertyChangesModel(PropertyChangesModel *model); public slots: void synchonizeCurrentStateFromWidget(); void createNewState(); + void cloneState(int nodeId); + void extendState(int nodeId); void removeState(int nodeId); private: - StatesEditorWidget *statesEditorWidget() const; void resetModel(); - void addState(); - void duplicateCurrentState(); + void resetPropertyChangesModels(); + void resetExtend(); + void resetStateGroups(); + void checkForStatesAvailability(); + void beginBulkChange(); + void endBulkChange(); + private: QPointer m_statesEditorModel; QPointer m_statesEditorWidget; @@ -89,6 +115,18 @@ private: bool m_block = false; QPointer m_editor; ModelNode m_activeStatesGroupNode; + + bool m_propertyChangesRemoved = false; + bool m_stateGroupRemoved = false; + + bool m_bulkChange = false; + + bool m_modelDirty = false; + bool m_extendDirty = false; + bool m_propertyChangesDirty = false; + bool m_stateGroupsDirty = false; + + QSet m_propertyChangedModels; }; } // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/stateseditor/stateseditorwidget.cpp b/src/plugins/qmldesigner/components/stateseditor/stateseditorwidget.cpp index 5c127727521..d0d5e88f5c4 100644 --- a/src/plugins/qmldesigner/components/stateseditor/stateseditorwidget.cpp +++ b/src/plugins/qmldesigner/components/stateseditor/stateseditorwidget.cpp @@ -1,10 +1,10 @@ -// Copyright (C) 2016 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0 #include "stateseditorwidget.h" -#include "stateseditorimageprovider.h" #include "stateseditormodel.h" #include "stateseditorview.h" +#include "stateseditorimageprovider.h" #include #include @@ -13,10 +13,9 @@ #include -#include #include +#include -#include #include #include @@ -31,14 +30,16 @@ #include #include -enum { debug = false }; +enum { + debug = false +}; namespace QmlDesigner { static QString propertyEditorResourcesPath() { #ifdef SHARE_QML_PATH - if (Utils::qtcEnvironmentVariableIsSet("LOAD_QML_FROM_SOURCE")) + if (qEnvironmentVariableIsSet("LOAD_QML_FROM_SOURCE")) return QLatin1String(SHARE_QML_PATH) + "/propertyEditorQmlSources"; #endif return Core::ICore::resourcePath("qmldesigner/propertyEditorQmlSources").toString(); @@ -63,11 +64,6 @@ void StatesEditorWidget::setNodeInstanceView(const NodeInstanceView *nodeInstanc m_imageProvider->setNodeInstanceView(nodeInstanceView); } -void StatesEditorWidget::showAddNewStatesButton(bool showAddNewStatesButton) -{ - rootContext()->setContextProperty(QLatin1String("canAddNewStates"), showAddNewStatesButton); -} - StatesEditorWidget::StatesEditorWidget(StatesEditorView *statesEditorView, StatesEditorModel *statesEditorModel) : m_statesEditorView(statesEditorView) @@ -80,21 +76,23 @@ StatesEditorWidget::StatesEditorWidget(StatesEditorView *statesEditorView, engine()->addImageProvider(QStringLiteral("qmldesigner_stateseditor"), m_imageProvider); engine()->addImportPath(qmlSourcesPath()); engine()->addImportPath(propertyEditorResourcesPath() + "/imports"); + engine()->addImportPath(qmlSourcesPath() + "/imports"); - m_qmlSourceUpdateShortcut = new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_F4), this); + m_qmlSourceUpdateShortcut = new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_F10), this); connect(m_qmlSourceUpdateShortcut, &QShortcut::activated, this, &StatesEditorWidget::reloadQmlSource); + quickWidget()->setObjectName(Constants::OBJECT_NAME_STATES_EDITOR); setResizeMode(QQuickWidget::SizeRootObjectToView); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - rootContext()->setContextProperties( - QVector{{{"statesEditorModel"}, - QVariant::fromValue(statesEditorModel)}, - {{"canAddNewStates"}, true}}); + auto map = registerPropertyMap("StatesEditorBackend"); + map->setProperties({{"statesEditorModel", QVariant::fromValue(statesEditorModel)}}); Theme::setupTheme(engine()); setWindowTitle(tr("States", "Title of Editor widget")); + setMinimumWidth(195); + setMinimumHeight(195); // init the first load of the QML UI elements reloadQmlSource(); @@ -105,16 +103,17 @@ StatesEditorWidget::~StatesEditorWidget() = default; QString StatesEditorWidget::qmlSourcesPath() { #ifdef SHARE_QML_PATH - if (Utils::qtcEnvironmentVariableIsSet("LOAD_QML_FROM_SOURCE")) - return QLatin1String(SHARE_QML_PATH) + "/statesEditorQmlSources"; + if (qEnvironmentVariableIsSet("LOAD_QML_FROM_SOURCE")) + return QLatin1String(SHARE_QML_PATH) + "/stateseditor"; #endif - return Core::ICore::resourcePath("qmldesigner/statesEditorQmlSources").toString(); + return Core::ICore::resourcePath("qmldesigner/stateseditor").toString(); } void StatesEditorWidget::showEvent(QShowEvent *event) { StudioQuickWidget::showEvent(event); update(); + QMetaObject::invokeMethod(rootObject(), "showEvent"); } void StatesEditorWidget::focusOutEvent(QFocusEvent *focusEvent) @@ -132,9 +131,8 @@ void StatesEditorWidget::focusInEvent(QFocusEvent *focusEvent) void StatesEditorWidget::reloadQmlSource() { - QString statesListQmlFilePath = qmlSourcesPath() + QStringLiteral("/StatesList.qml"); - QTC_ASSERT(QFileInfo::exists(statesListQmlFilePath), return); - engine()->clearComponentCache(); + QString statesListQmlFilePath = qmlSourcesPath() + QStringLiteral("/Main.qml"); + QTC_ASSERT(QFileInfo::exists(statesListQmlFilePath), return ); setSource(QUrl::fromLocalFile(statesListQmlFilePath)); if (!rootObject()) { @@ -152,8 +150,19 @@ void StatesEditorWidget::reloadQmlSource() SIGNAL(currentStateInternalIdChanged()), m_statesEditorView.data(), SLOT(synchonizeCurrentStateFromWidget())); - connect(rootObject(), SIGNAL(createNewState()), m_statesEditorView.data(), SLOT(createNewState())); - connect(rootObject(), SIGNAL(deleteState(int)), m_statesEditorView.data(), SLOT(removeState(int))); + connect(rootObject(), + SIGNAL(createNewState()), + m_statesEditorView.data(), + SLOT(createNewState())); + connect(rootObject(), SIGNAL(cloneState(int)), m_statesEditorView.data(), SLOT(cloneState(int))); + connect(rootObject(), + SIGNAL(extendState(int)), + m_statesEditorView.data(), + SLOT(extendState(int))); + connect(rootObject(), + SIGNAL(deleteState(int)), + m_statesEditorView.data(), + SLOT(removeState(int))); m_statesEditorView.data()->synchonizeCurrentStateFromWidget(); } diff --git a/src/plugins/qmldesigner/components/stateseditor/stateseditorwidget.h b/src/plugins/qmldesigner/components/stateseditor/stateseditorwidget.h index fb83872a131..395cdbfac21 100644 --- a/src/plugins/qmldesigner/components/stateseditor/stateseditorwidget.h +++ b/src/plugins/qmldesigner/components/stateseditor/stateseditorwidget.h @@ -1,5 +1,5 @@ -// Copyright (C) 2016 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0 #pragma once @@ -15,13 +15,12 @@ QT_END_NAMESPACE namespace QmlDesigner { -class StatesEditorModel; -class StatesEditorView; class NodeInstanceView; -namespace Internal { -class StatesEditorImageProvider; -} +class StatesEditorModel; +class StatesEditorView; + +namespace Internal { class StatesEditorImageProvider; } class StatesEditorWidget : public StudioQuickWidget { @@ -35,8 +34,6 @@ public: void setCurrentStateInternalId(int internalId); void setNodeInstanceView(const NodeInstanceView *nodeInstanceView); - void showAddNewStatesButton(bool showAddNewStatesButton); - static QString qmlSourcesPath(); protected: diff --git a/src/plugins/qmldesigner/components/stateseditornew/stateseditorimageprovider.cpp b/src/plugins/qmldesigner/components/stateseditornew/stateseditorimageprovider.cpp deleted file mode 100644 index d2d9ebdf4ce..00000000000 --- a/src/plugins/qmldesigner/components/stateseditornew/stateseditorimageprovider.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2022 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of Qt Creator. -** -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3 as published by the Free Software -** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-3.0.html. -** -****************************************************************************/ - -#include "stateseditorimageprovider.h" -#include "nodeinstanceview.h" - -#include - -namespace QmlDesigner { -namespace Experimental { -namespace Internal { - -StatesEditorImageProvider::StatesEditorImageProvider() - : QQuickImageProvider(QQuickImageProvider::Image) -{ -} - -QImage StatesEditorImageProvider::requestImage(const QString &id, QSize *size, const QSize &requestedSize) -{ - QImage image; - - bool nodeInstanceViewIsDetached = m_nodeInstanceView.isNull() || !m_nodeInstanceView->model(); - if (!nodeInstanceViewIsDetached) { - QString imageId = id.split(QLatin1Char('-')).constFirst(); - if (imageId == QLatin1String("baseState")) { - image = m_nodeInstanceView->statePreviewImage(m_nodeInstanceView->rootModelNode()); - } else { - bool canBeConverted; - int instanceId = imageId.toInt(&canBeConverted); - if (canBeConverted && m_nodeInstanceView->hasModelNodeForInternalId(instanceId)) { - image = m_nodeInstanceView->statePreviewImage(m_nodeInstanceView->modelNodeForInternalId(instanceId)); - } - } - } - - if (image.isNull()) { - //creating white QImage - QSize newSize = requestedSize; - if (newSize.isEmpty()) - newSize = QSize (100, 100); - - QImage image(newSize, QImage::Format_ARGB32); - image.fill(0xFFFFFFFF); - return image; - } - - *size = image.size(); - - return image; -} - -void StatesEditorImageProvider::setNodeInstanceView(const NodeInstanceView *nodeInstanceView) -{ - m_nodeInstanceView = nodeInstanceView; -} - -} // namespace Internal -} // namespace Experimental -} // namespace QmlDesigner - diff --git a/src/plugins/qmldesigner/components/stateseditornew/stateseditorimageprovider.h b/src/plugins/qmldesigner/components/stateseditornew/stateseditorimageprovider.h deleted file mode 100644 index c89e9ea723e..00000000000 --- a/src/plugins/qmldesigner/components/stateseditornew/stateseditorimageprovider.h +++ /dev/null @@ -1,54 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2022 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of Qt Creator. -** -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3 as published by the Free Software -** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-3.0.html. -** -****************************************************************************/ - -#pragma once - -#include"abstractview.h" - -#include -#include - -namespace QmlDesigner { -namespace Experimental { -namespace Internal { - -class StatesEditorView; - -class StatesEditorImageProvider : public QQuickImageProvider -{ -public: - StatesEditorImageProvider(); - - QImage requestImage(const QString &id, QSize *size, const QSize &requestedSize) override; - - void setNodeInstanceView(const NodeInstanceView *nodeInstanceView); - -private: - QPointer m_nodeInstanceView; -}; - -} // namespace Internal -} // namespace Experimental -} // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/stateseditornew/stateseditormodel.cpp b/src/plugins/qmldesigner/components/stateseditornew/stateseditormodel.cpp deleted file mode 100644 index 398bdfb6f60..00000000000 --- a/src/plugins/qmldesigner/components/stateseditornew/stateseditormodel.cpp +++ /dev/null @@ -1,462 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2022 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of Qt Creator. -** -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3 as published by the Free Software -** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-3.0.html. -** -****************************************************************************/ - -#include "stateseditormodel.h" -#include "stateseditorview.h" - -#include -#include -#include -#include -#include -#include - -#include -#include - -#include -#include - -#include -#include - -enum { - debug = false -}; - -namespace QmlDesigner { -namespace Experimental { - -StatesEditorModel::StatesEditorModel(StatesEditorView *view) - : QAbstractListModel(view) - , m_statesEditorView(view) - , m_hasExtend(false) - , m_extendedStates() -{ - QObject::connect(this, &StatesEditorModel::dataChanged, [this]() { emit baseStateChanged(); }); -} - -int StatesEditorModel::count() const -{ - return rowCount(); -} - -QModelIndex StatesEditorModel::index(int row, int column, const QModelIndex &parent) const -{ - if (m_statesEditorView.isNull()) - return {}; - - int internalNodeId = 0; - if (row > 0) - internalNodeId = m_statesEditorView->activeStatesGroupNode() - .nodeListProperty("states") - .at(row - 1) - .internalId(); - - return hasIndex(row, column, parent) ? createIndex(row, column, internalNodeId) : QModelIndex(); -} - -int StatesEditorModel::rowCount(const QModelIndex &parent) const -{ - if (parent.isValid() || m_statesEditorView.isNull() || !m_statesEditorView->model()) - return 0; - - if (!m_statesEditorView->activeStatesGroupNode().hasNodeListProperty("states")) - return 1; // base state - - return m_statesEditorView->activeStatesGroupNode().nodeListProperty("states").count() + 1; -} - -void StatesEditorModel::reset() -{ - QAbstractListModel::beginResetModel(); - QAbstractListModel::endResetModel(); - - evaluateExtend(); - emit baseStateChanged(); -} - -QVariant StatesEditorModel::data(const QModelIndex &index, int role) const -{ - if (index.parent().isValid() || index.column() != 0 || m_statesEditorView.isNull() - || !m_statesEditorView->hasModelNodeForInternalId(index.internalId())) - return QVariant(); - - ModelNode stateNode; - - if (index.internalId() > 0) - stateNode = m_statesEditorView->modelNodeForInternalId(index.internalId()); - - switch (role) { - case StateNameRole: { - if (index.row() == 0) { - return tr("base state", "Implicit default state"); - } else { - if (stateNode.hasVariantProperty("name")) - return stateNode.variantProperty("name").value(); - else - return QVariant(); - } - } - - case StateImageSourceRole: { - static int randomNumber = 0; - randomNumber++; - if (index.row() == 0) - return QString("image://qmldesigner_stateseditor/baseState-%1").arg(randomNumber); - else - return QString("image://qmldesigner_stateseditor/%1-%2").arg(index.internalId()).arg(randomNumber); - } - - case InternalNodeId: - return index.internalId(); - - case HasWhenCondition: - return stateNode.isValid() && stateNode.hasProperty("when"); - - case WhenConditionString: { - if (stateNode.isValid() && stateNode.hasBindingProperty("when")) - return stateNode.bindingProperty("when").expression(); - else - return QString(); - } - - case IsDefault: { - QmlModelState modelState(stateNode); - if (modelState.isValid()) - return modelState.isDefault(); - return false; - } - - case ModelHasDefaultState: - return hasDefaultState(); - - case HasExtend: - return stateNode.isValid() && stateNode.hasProperty("extend"); - - case ExtendString: { - if (stateNode.isValid() && stateNode.hasVariantProperty("extend")) - return stateNode.variantProperty("extend").value(); - else - return QString(); - } - } - - return QVariant(); -} - -QHash StatesEditorModel::roleNames() const -{ - static QHash roleNames{{StateNameRole, "stateName"}, - {StateImageSourceRole, "stateImageSource"}, - {InternalNodeId, "internalNodeId"}, - {HasWhenCondition, "hasWhenCondition"}, - {WhenConditionString, "whenConditionString"}, - {IsDefault, "isDefault"}, - {ModelHasDefaultState, "modelHasDefaultState"}, - {HasExtend, "hasExtend"}, - {ExtendString, "extendString"}}; - return roleNames; -} - -void StatesEditorModel::insertState(int stateIndex) -{ - if (stateIndex >= 0) { - const int updateIndex = stateIndex + 1; - beginInsertRows(QModelIndex(), updateIndex, updateIndex); - endInsertRows(); - - emit dataChanged(index(updateIndex, 0), index(updateIndex, 0)); - } -} - -void StatesEditorModel::updateState(int beginIndex, int endIndex) -{ - if (beginIndex >= 0 && endIndex >= 0) - emit dataChanged(index(beginIndex, 0), index(endIndex, 0)); -} - -void StatesEditorModel::removeState(int stateIndex) -{ - if (stateIndex >= 0) { - beginRemoveRows(QModelIndex(), 0, stateIndex); - endRemoveRows(); - } -} - -void StatesEditorModel::renameState(int internalNodeId, const QString &newName) -{ - if (newName == m_statesEditorView->currentStateName()) - return; - - if (newName.isEmpty() ||! m_statesEditorView->validStateName(newName)) { - QTimer::singleShot(0, this, [newName] { - Core::AsynchronousMessageBox::warning( - tr("Invalid state name"), - newName.isEmpty() ? - tr("The empty string as a name is reserved for the base state.") : - tr("Name already used in another state")); - }); - reset(); - } else { - m_statesEditorView->renameState(internalNodeId, newName); - } -} - -void StatesEditorModel::setWhenCondition(int internalNodeId, const QString &condition) -{ - m_statesEditorView->setWhenCondition(internalNodeId, condition); -} - -void StatesEditorModel::resetWhenCondition(int internalNodeId) -{ - m_statesEditorView->resetWhenCondition(internalNodeId); -} - -QStringList StatesEditorModel::autoComplete(const QString &text, int pos, bool explicitComplete) -{ - Model *model = m_statesEditorView->model(); - if (model && model->rewriterView()) - return model->rewriterView()->autoComplete(text, pos, explicitComplete); - - return QStringList(); -} - -QVariant StatesEditorModel::stateModelNode(int internalNodeId) -{ - if (!m_statesEditorView->model()) - return QVariant(); - - ModelNode node = m_statesEditorView->modelNodeForInternalId(internalNodeId); - - return QVariant::fromValue(m_statesEditorView->modelNodeForInternalId(internalNodeId)); -} - -void StatesEditorModel::setStateAsDefault(int internalNodeId) -{ - m_statesEditorView->setStateAsDefault(internalNodeId); -} - -void StatesEditorModel::resetDefaultState() -{ - m_statesEditorView->resetDefaultState(); -} - -bool StatesEditorModel::hasDefaultState() const -{ - return m_statesEditorView->hasDefaultState(); -} - -void StatesEditorModel::setAnnotation(int internalNodeId) -{ - m_statesEditorView->setAnnotation(internalNodeId); -} - -void StatesEditorModel::removeAnnotation(int internalNodeId) -{ - m_statesEditorView->removeAnnotation(internalNodeId); -} - -bool StatesEditorModel::hasAnnotation(int internalNodeId) const -{ - return m_statesEditorView->hasAnnotation(internalNodeId); -} - -QStringList StatesEditorModel::stateGroups() const -{ - if (!m_statesEditorView->isAttached()) - return {}; - - const auto groupMetaInfo = m_statesEditorView->model()->qtQuickStateGroupMetaInfo(); - - auto stateGroups = Utils::transform(m_statesEditorView->allModelNodesOfType(groupMetaInfo), - [](const ModelNode &node) { return node.displayName(); }); - stateGroups.prepend(tr("Default")); - return stateGroups; -} - -QString StatesEditorModel::activeStateGroup() const -{ - if (auto stateGroup = m_statesEditorView->activeStatesGroupNode()) - return stateGroup.displayName(); - - return {}; -} - -void StatesEditorModel::setActiveStateGroup(const QString &name) -{ - if (!m_statesEditorView->isAttached()) - return; - - const auto groupMetaInfo = m_statesEditorView->model()->qtQuickStateGroupMetaInfo(); - - auto modelNode = Utils::findOrDefault(m_statesEditorView->allModelNodesOfType(groupMetaInfo), - [&name](const ModelNode &node) { - return node.displayName() == name; - }); - - QTC_ASSERT(!modelNode.isValid(), return ); - - if (modelNode.isValid()) - m_statesEditorView->setActiveStatesGroupNode(modelNode); -} - -int StatesEditorModel::activeStateGroupIndex() const -{ - return m_statesEditorView->activeStatesGroupIndex(); -} - -void StatesEditorModel::setActiveStateGroupIndex(int index) -{ - m_statesEditorView->setActiveStatesGroupIndex(index); -} - -bool StatesEditorModel::renameActiveStateGroup(const QString &name) -{ - auto stateGroup = m_statesEditorView->activeStatesGroupNode(); - - if (!stateGroup.isValid() || stateGroup.isRootNode()) - return false; - - if (!QmlDesigner::ModelNode::isValidId(name) || m_statesEditorView->hasId(name)) { - QString errMsg = QmlDesigner::ModelNode::getIdValidityErrorMessage(name); - if (!errMsg.isEmpty()) - Core::AsynchronousMessageBox::warning(tr("Invalid ID"), errMsg); - else - Core::AsynchronousMessageBox::warning(tr("Invalid ID"), - tr("%1 already exists.").arg(name)); - return false; - } - - stateGroup.setIdWithRefactoring(name); - emit stateGroupsChanged(); - return true; -} - -void StatesEditorModel::addStateGroup(const QString &name) -{ - m_statesEditorView->executeInTransaction("createStateGroup", [this, name]() { - const TypeName typeName = "QtQuick.StateGroup"; - auto metaInfo = m_statesEditorView->model()->metaInfo(typeName); - int minorVersion = metaInfo.minorVersion(); - int majorVersion = metaInfo.majorVersion(); - auto stateGroupNode = m_statesEditorView->createModelNode(typeName, - majorVersion, - minorVersion); - stateGroupNode.setIdWithoutRefactoring(m_statesEditorView->model()->generateNewId(name)); - - m_statesEditorView->rootModelNode().defaultNodeAbstractProperty().reparentHere( - stateGroupNode); - m_statesEditorView->setActiveStatesGroupNode(stateGroupNode); - }); -} - -void StatesEditorModel::removeStateGroup() -{ - if (m_statesEditorView->activeStatesGroupNode().isRootNode()) - return; - - m_statesEditorView->executeInTransaction("removeStateGroup", [this]() { - m_statesEditorView->activeStatesGroupNode().destroy(); - }); -} - -QVariantMap StatesEditorModel::get(int idx) const -{ - const QHash &names = roleNames(); - QHash::const_iterator i = names.constBegin(); - - QVariantMap res; - QModelIndex modelIndex = index(idx); - - while (i != names.constEnd()) { - QVariant data = modelIndex.data(i.key()); - - res[QString::fromUtf8(i.value())] = data; - ++i; - } - return res; -} - -QVariantMap StatesEditorModel::baseState() const -{ - return get(0); -} - -bool StatesEditorModel::hasExtend() const -{ - return m_hasExtend; -} - -QStringList StatesEditorModel::extendedStates() const -{ - return m_extendedStates; -} - -void StatesEditorModel::move(int from, int to) -{ - // This does not alter the code (rewriter) which means the reordering is not presistent - - if (from == to) - return; - - int specialIndex = (from < to ? to + 1 : to); - beginMoveRows(QModelIndex(), from, from, QModelIndex(), specialIndex); - endMoveRows(); -} - -void StatesEditorModel::drop(int from, int to) -{ - m_statesEditorView->moveStates(from, to); -} - -void StatesEditorModel::evaluateExtend() -{ - bool hasExtend = m_statesEditorView->hasExtend(); - - if (m_hasExtend != hasExtend) { - m_hasExtend = hasExtend; - emit hasExtendChanged(); - } - - auto extendedStates = m_statesEditorView->extendedStates(); - - if (extendedStates.size() != m_extendedStates.size()) { - m_extendedStates = extendedStates; - emit extendedStatesChanged(); - return; - } - - for (int i = 0; i != m_extendedStates.size(); ++i) { - if (extendedStates[i] != m_extendedStates[i]) { - m_extendedStates = extendedStates; - emit extendedStatesChanged(); - return; - } - } -} - -} // namespace Experimental -} // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/stateseditornew/stateseditormodel.h b/src/plugins/qmldesigner/components/stateseditornew/stateseditormodel.h deleted file mode 100644 index c1f12878387..00000000000 --- a/src/plugins/qmldesigner/components/stateseditornew/stateseditormodel.h +++ /dev/null @@ -1,127 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2022 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of Qt Creator. -** -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3 as published by the Free Software -** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-3.0.html. -** -****************************************************************************/ - -#pragma once - -#include -#include - -namespace QmlDesigner { -namespace Experimental { - -class StatesEditorView; - -class StatesEditorModel : public QAbstractListModel -{ - Q_OBJECT - - enum { - StateNameRole = Qt::DisplayRole, - StateImageSourceRole = Qt::UserRole, - InternalNodeId, - HasWhenCondition, - WhenConditionString, - IsDefault, - ModelHasDefaultState, - HasExtend, - ExtendString - }; - -public: - StatesEditorModel(StatesEditorView *view); - - Q_INVOKABLE int count() const; - QModelIndex index(int row, int column = 0, const QModelIndex &parent = QModelIndex()) const override; - int rowCount(const QModelIndex &parent = QModelIndex()) const override; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; - QHash roleNames() const override; - - void insertState(int stateIndex); - void removeState(int stateIndex); - void updateState(int beginIndex, int endIndex); - Q_INVOKABLE void renameState(int internalNodeId, const QString &newName); - Q_INVOKABLE void setWhenCondition(int internalNodeId, const QString &condition); - Q_INVOKABLE void resetWhenCondition(int internalNodeId); - Q_INVOKABLE QStringList autoComplete(const QString &text, int pos, bool explicitComplete); - Q_INVOKABLE QVariant stateModelNode(int internalNodeId); - - Q_INVOKABLE void setStateAsDefault(int internalNodeId); - Q_INVOKABLE void resetDefaultState(); - Q_INVOKABLE bool hasDefaultState() const; - Q_INVOKABLE void setAnnotation(int internalNodeId); - Q_INVOKABLE void removeAnnotation(int internalNodeId); - Q_INVOKABLE bool hasAnnotation(int internalNodeId) const; - - QStringList stateGroups() const; - QString activeStateGroup() const; - void setActiveStateGroup(const QString &name); - int activeStateGroupIndex() const; - void setActiveStateGroupIndex(int index); - - Q_INVOKABLE bool renameActiveStateGroup(const QString &name); - - Q_INVOKABLE void addStateGroup(const QString &name); - Q_INVOKABLE void removeStateGroup(); - - Q_INVOKABLE QVariantMap get(int idx) const; - - QVariantMap baseState() const; - bool hasExtend() const; - QStringList extendedStates() const; - - Q_PROPERTY(QVariantMap baseState READ baseState NOTIFY baseStateChanged) - Q_PROPERTY(QStringList extendedStates READ extendedStates NOTIFY extendedStatesChanged) - - Q_PROPERTY(bool hasExtend READ hasExtend NOTIFY hasExtendChanged) - - Q_PROPERTY(QString activeStateGroup READ activeStateGroup WRITE setActiveStateGroup NOTIFY - activeStateGroupChanged) - Q_PROPERTY(int activeStateGroupIndex READ activeStateGroupIndex WRITE setActiveStateGroupIndex - NOTIFY activeStateGroupIndexChanged) - Q_PROPERTY(QStringList stateGroups READ stateGroups NOTIFY stateGroupsChanged) - - Q_INVOKABLE void move(int from, int to); - Q_INVOKABLE void drop(int from, int to); - - void reset(); - void evaluateExtend(); - -signals: - void changedToState(int n); - void baseStateChanged(); - void hasExtendChanged(); - void extendedStatesChanged(); - void activeStateGroupChanged(); - void activeStateGroupIndexChanged(); - void stateGroupsChanged(); - -private: - QPointer m_statesEditorView; - bool m_hasExtend; - QStringList m_extendedStates; -}; - -} // namespace Experimental -} // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/stateseditornew/stateseditorview.cpp b/src/plugins/qmldesigner/components/stateseditornew/stateseditorview.cpp deleted file mode 100644 index b35bd214778..00000000000 --- a/src/plugins/qmldesigner/components/stateseditornew/stateseditorview.cpp +++ /dev/null @@ -1,964 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2022 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of Qt Creator. -** -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3 as published by the Free Software -** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-3.0.html. -** -****************************************************************************/ - -#include "stateseditorview.h" -#include "propertychangesmodel.h" -#include "stateseditormodel.h" -#include "stateseditorwidget.h" - -#include -#include -#include -#include - -#include -#include - -#include - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace QmlDesigner { -namespace Experimental { - -/** - We always have 'one' current state, where we get updates from (see sceneChanged()). In case - the current state is the base state, we render the base state + all other states. - */ - -StatesEditorView::StatesEditorView(ExternalDependenciesInterface &externalDependencies) - : AbstractView(externalDependencies) - , m_statesEditorModel(new StatesEditorModel(this)) - , m_lastIndex(-1) - , m_editor(nullptr) -{ - Q_ASSERT(m_statesEditorModel); - // base state -} - -StatesEditorView::~StatesEditorView() -{ - if (m_editor) - delete m_editor; - delete m_statesEditorWidget.data(); -} - -WidgetInfo StatesEditorView::widgetInfo() -{ - if (!m_statesEditorWidget) - m_statesEditorWidget = new StatesEditorWidget(this, m_statesEditorModel.data()); - - return createWidgetInfo(m_statesEditorWidget.data(), - "StatesEditor", - WidgetInfo::BottomPane, - 0, - tr("States")); -} - -void StatesEditorView::rootNodeTypeChanged(const QString &/*type*/, int /*majorVersion*/, int /*minorVersion*/) -{ - checkForStatesAvailability(); -} - -ModelNode StatesEditorView::activeStatesGroupNode() const -{ - return m_activeStatesGroupNode; -} - -void StatesEditorView::setActiveStatesGroupNode(const ModelNode &modelNode) -{ - if (m_activeStatesGroupNode == modelNode) - return; - - m_activeStatesGroupNode = modelNode; - resetModel(); - - checkForStatesAvailability(); - - emit m_statesEditorModel->activeStateGroupChanged(); - emit m_statesEditorModel->activeStateGroupIndexChanged(); -} - -int StatesEditorView::activeStatesGroupIndex() const -{ - if (!model()) - return -1; - - return Utils::indexOf(allModelNodesOfType(model()->qtQuickStateGroupMetaInfo()), - [this](const ModelNode &node) { return node == m_activeStatesGroupNode; }) - + 1; -} - -void StatesEditorView::setActiveStatesGroupIndex(int index) -{ - if (!model()) - return; - - if (index > 0) { - const ModelNode statesGroup = allModelNodesOfType(model()->qtQuickStateGroupMetaInfo()) - .at(index - 1); - if (statesGroup.isValid()) - setActiveStatesGroupNode(statesGroup); - } else { - setActiveStatesGroupNode(rootModelNode()); - } -} - -void StatesEditorView::registerPropertyChangesModel(PropertyChangesModel *model) -{ - m_propertyChangedModels.insert(model); -} - -void StatesEditorView::deregisterPropertyChangesModel(PropertyChangesModel *model) -{ - m_propertyChangedModels.remove(model); -} - -void StatesEditorView::synchonizeCurrentStateFromWidget() -{ - if (!model()) - return; - - if (m_block) - return; - - int internalId = m_statesEditorWidget->currentStateInternalId(); - - if (internalId > 0 && hasModelNodeForInternalId(internalId)) { - ModelNode node = modelNodeForInternalId(internalId); - QmlModelState modelState(node); - if (modelState.isValid() && modelState != currentState()) - setCurrentState(modelState); - } else { - setCurrentState(baseState()); - } -} - -void StatesEditorView::createNewState() -{ - // can happen when root node is e.g. a ListModel - if (!QmlVisualNode::isValidQmlVisualNode(activeStatesGroupNode()) - && m_activeStatesGroupNode.type() != "QtQuick.StateGroup") - return; - - QmlDesignerPlugin::emitUsageStatistics(Constants::EVENT_STATE_ADDED); - - QStringList modelStateNames = activeStateGroup().names(); - - QString newStateName; - int index = 1; - while (true) { - newStateName = QString(QStringLiteral("State%1")).arg(index++); - if (!modelStateNames.contains(newStateName)) - break; - } - - executeInTransaction("createNewState", [this, newStateName]() { - activeStatesGroupNode().validId(); - - ModelNode newState = activeStateGroup().addState(newStateName); - setCurrentState(newState); - }); -} - -void StatesEditorView::cloneState(int nodeId) -{ - if (!(nodeId > 0 && hasModelNodeForInternalId(nodeId))) - return; - - ModelNode stateNode(modelNodeForInternalId(nodeId)); - QTC_ASSERT(stateNode.simplifiedTypeName() == "State", return ); - - QmlModelState modelState(stateNode); - if (!modelState.isValid() || modelState.isBaseState()) - return; - - QmlDesignerPlugin::emitUsageStatistics(Constants::EVENT_STATE_CLONED); - - QString newName = modelState.name(); - - // Strip out numbers at the end of the string - QRegularExpression regEx(QLatin1String("[0-9]+$")); - const QRegularExpressionMatch match = regEx.match(newName); - if (match.hasMatch() && (match.capturedStart() + match.capturedLength() == newName.length())) - newName = newName.left(match.capturedStart()); - - int i = 1; - QStringList stateNames = activeStateGroup().names(); - while (stateNames.contains(newName + QString::number(i))) - i++; - const QString newStateName = newName + QString::number(i); - - QmlModelState newState; - - executeInTransaction("cloneState", [newStateName, modelState, &newState]() { - newState = modelState.duplicate(newStateName); - }); - - ModelNode newNode = newState.modelNode(); - int from = newNode.parentProperty().indexOf(newNode); - int to = stateNode.parentProperty().indexOf(stateNode) + 1; - - // When duplicating an extended state the new state needs to be added after the extend group. - if (!modelState.hasExtend()) { - auto modelNodeList = activeStatesGroupNode().nodeListProperty("states").toModelNodeList(); - for (; to != modelNodeList.count(); ++to) { - QmlModelState currentState(modelNodeList.at(to)); - if (!currentState.isValid() || currentState.isBaseState() || !currentState.hasExtend()) - break; - } - } - - executeInTransaction("moveState", [this, &newState, from, to]() { - activeStatesGroupNode().nodeListProperty("states").slide(from, to); - setCurrentState(newState); - }); -} - -void StatesEditorView::extendState(int nodeId) -{ - if (!(nodeId > 0 && hasModelNodeForInternalId(nodeId))) - return; - - ModelNode stateNode(modelNodeForInternalId(nodeId)); - QTC_ASSERT(stateNode.simplifiedTypeName() == "State", return ); - - QmlModelState modelState(stateNode); - if (!modelState.isValid() || modelState.isBaseState()) - return; - - QmlDesignerPlugin::emitUsageStatistics(Constants::EVENT_STATE_EXTENDED); - - QString newName = modelState.name(); - - // Strip out numbers at the end of the string - QRegularExpression regEx(QLatin1String("[0-9]+$")); - const QRegularExpressionMatch match = regEx.match(newName); - if (match.hasMatch() && (match.capturedStart() + match.capturedLength() == newName.length())) - newName = newName.left(match.capturedStart()); - - int i = 1; - QStringList stateNames = activeStateGroup().names(); - while (stateNames.contains(newName + QString::number(i))) - i++; - const QString newStateName = newName + QString::number(i); - - QmlModelState newState; - - executeInTransaction("extendState", [this, newStateName, modelState, &newState]() { - newState = activeStateGroup().addState(newStateName); - newState.setExtend(modelState.name()); - }); - - ModelNode newNode = newState.modelNode(); - int from = newNode.parentProperty().indexOf(newNode); - int to = stateNode.parentProperty().indexOf(stateNode) + 1; - - executeInTransaction("moveState", [this, &newState, from, to]() { - activeStatesGroupNode().nodeListProperty("states").slide(from, to); - setCurrentState(newState); - }); -} - -void StatesEditorView::removeState(int nodeId) -{ - try { - if (nodeId > 0 && hasModelNodeForInternalId(nodeId)) { - ModelNode stateNode(modelNodeForInternalId(nodeId)); - QTC_ASSERT(stateNode.simplifiedTypeName() == "State", return ); - - QmlModelState modelState(stateNode); - if (modelState.isValid()) { - QStringList lockedTargets; - const auto propertyChanges = modelState.propertyChanges(); - - // confirm removing not empty states - if (!propertyChanges.isEmpty()) { - QMessageBox msgBox; - msgBox.setTextFormat(Qt::RichText); - msgBox.setIcon(QMessageBox::Question); - msgBox.setWindowTitle(tr("Remove State")); - msgBox.setText( - tr("This state is not empty. Are you sure you want to remove it?")); - msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel); - msgBox.setDefaultButton(QMessageBox::Yes); - - if (msgBox.exec() == QMessageBox::Cancel) - return; - } - - // confirm removing states with locked targets - for (const QmlPropertyChanges &change : propertyChanges) { - const ModelNode target = change.target(); - QTC_ASSERT(target.isValid(), continue); - if (target.locked()) - lockedTargets.push_back(target.id()); - } - - if (!lockedTargets.empty()) { - Utils::sort(lockedTargets); - QString detailedText = QString("" + tr("Locked components:") + "
"); - - for (const auto &id : std::as_const(lockedTargets)) - detailedText.append("- " + id + "
"); - - detailedText.chop(QString("
").size()); - - QMessageBox msgBox; - msgBox.setTextFormat(Qt::RichText); - msgBox.setIcon(QMessageBox::Question); - msgBox.setWindowTitle(tr("Remove State")); - msgBox.setText(QString(tr("Removing this state will modify locked components.") - + "

%1") - .arg(detailedText)); - msgBox.setInformativeText(tr("Continue by removing the state?")); - msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); - msgBox.setDefaultButton(QMessageBox::Ok); - - if (msgBox.exec() == QMessageBox::Cancel) - return; - } - } - - NodeListProperty parentProperty = stateNode.parentProperty().toNodeListProperty(); - - if (parentProperty.count() <= 1) { - setCurrentState(baseState()); - } else if (parentProperty.isValid()) { - int index = parentProperty.indexOf(stateNode); - if (index == 0) - setCurrentState(parentProperty.at(1)); - else - setCurrentState(parentProperty.at(index - 1)); - } - - stateNode.destroy(); - } - } catch (const RewritingException &e) { - e.showException(); - } -} - -void StatesEditorView::resetModel() -{ - if (m_bulkChange) { - m_modelDirty = true; - return; - } - - if (m_statesEditorModel) - m_statesEditorModel->reset(); - - if (m_statesEditorWidget) { - if (currentState().isBaseState()) - m_statesEditorWidget->setCurrentStateInternalId(0); - else - m_statesEditorWidget->setCurrentStateInternalId(currentState().modelNode().internalId()); - } - - m_modelDirty = false; -} - -void StatesEditorView::resetPropertyChangesModels() -{ - if (m_bulkChange) { - m_propertyChangesDirty = true; - return; - } - - std::for_each(m_propertyChangedModels.begin(), - m_propertyChangedModels.end(), - [](PropertyChangesModel *model) { model->reset(); }); - - m_propertyChangesDirty = false; -} - -void StatesEditorView::resetExtend() -{ - if (m_bulkChange) { - m_extendDirty = true; - return; - } - - m_statesEditorModel->evaluateExtend(); - - m_extendDirty = false; -} - -void StatesEditorView::resetStateGroups() -{ - if (m_bulkChange) { - m_stateGroupsDirty = true; - return; - } - - emit m_statesEditorModel->stateGroupsChanged(); - - m_stateGroupsDirty = false; -} - -void StatesEditorView::checkForStatesAvailability() -{ - if (m_statesEditorWidget) { - const bool isVisual = activeStatesGroupNode().metaInfo().isBasedOn( - model()->qtQuickItemMetaInfo(), model()->qtQuick3DNodeMetaInfo()); - const bool isRoot = activeStatesGroupNode().isRootNode(); - m_statesEditorWidget->showAddNewStatesButton(isVisual || !isRoot); - } -} - -void StatesEditorView::beginBulkChange() -{ - m_bulkChange = true; -} - -void StatesEditorView::endBulkChange() -{ - if (!m_bulkChange) - return; - - m_bulkChange = false; - - if (m_modelDirty) - resetModel(); - - if (m_propertyChangesDirty) - resetPropertyChangesModels(); - - if (m_extendDirty) - resetExtend(); - - if (m_stateGroupsDirty) - resetStateGroups(); -} - -void StatesEditorView::setCurrentState(const QmlModelState &state) -{ - if (!model() && !state.isValid()) - return; - - if (currentStateNode() != state.modelNode()) - setCurrentStateNode(state.modelNode()); -} - -QmlModelState StatesEditorView::baseState() const -{ - return QmlModelState::createBaseState(this); -} - -QmlModelStateGroup StatesEditorView::activeStateGroup() const -{ - return QmlModelStateGroup(activeStatesGroupNode()); -} - -bool StatesEditorView::validStateName(const QString &name) const -{ - if (name == tr("base state")) - return false; - const QList modelStates = activeStateGroup().allStates(); - for (const QmlModelState &state : modelStates) { - if (state.name() == name) - return false; - } - return true; -} - -bool StatesEditorView::hasExtend() const -{ - if (!model()) - return false; - - const QList modelStates = activeStateGroup().allStates(); - for (const QmlModelState &state : modelStates) { - if (state.hasExtend()) - return true; - } - return false; -} - -QStringList StatesEditorView::extendedStates() const -{ - if (!model()) - return QStringList(); - - QStringList states; - - const QList modelStates = activeStateGroup().allStates(); - for (const QmlModelState &state : modelStates) { - if (state.hasExtend()) - states.append(state.extend()); - } - states.removeDuplicates(); - return states; -} - -QString StatesEditorView::currentStateName() const -{ - return currentState().isValid() ? currentState().name() : QString(); -} - -void StatesEditorView::renameState(int internalNodeId, const QString &newName) -{ - if (hasModelNodeForInternalId(internalNodeId)) { - QmlModelState renamedState(modelNodeForInternalId(internalNodeId)); - try { - if (renamedState.isValid() && renamedState.name() != newName) { - executeInTransaction("renameState", [this, &renamedState, &newName]() { - // Jump to base state for the change - QmlModelState oldState = currentState(); - setCurrentState(baseState()); - const bool updateDefault = renamedState.isDefault(); - - // If state is extended rename all references - QList states; - const QList modelStates = activeStateGroup().allStates(); - for (const QmlModelState &state : modelStates) { - if (state.hasExtend() && state.extend() == renamedState.name()) - states.append(state); - } - - renamedState.setName(newName.trimmed()); - - for (QmlModelState &state : states) - state.setExtend(newName.trimmed()); - - if (updateDefault) - renamedState.setAsDefault(); - - setCurrentState(oldState); - }); - } - } catch (const RewritingException &e) { - e.showException(); - } - } -} - -void StatesEditorView::setWhenCondition(int internalNodeId, const QString &condition) -{ - if (m_block) - return; - - m_block = true; - const QScopeGuard cleanup([&] { m_block = false; }); - - if (hasModelNodeForInternalId(internalNodeId)) { - QmlModelState state(modelNodeForInternalId(internalNodeId)); - try { - if (state.isValid()) - state.modelNode().bindingProperty("when").setExpression(condition); - - } catch (const Exception &e) { - e.showException(); - } - } -} - -void StatesEditorView::resetWhenCondition(int internalNodeId) -{ - if (m_block) - return; - - m_block = true; - const QScopeGuard cleanup([&] { m_block = false; }); - - if (hasModelNodeForInternalId(internalNodeId)) { - QmlModelState state(modelNodeForInternalId(internalNodeId)); - try { - if (state.isValid() && state.modelNode().hasProperty("when")) - state.modelNode().removeProperty("when"); - - } catch (const RewritingException &e) { - e.showException(); - } - } -} - -void StatesEditorView::setStateAsDefault(int internalNodeId) -{ - if (m_block) - return; - - m_block = true; - const QScopeGuard cleanup([&] { m_block = false; }); - - if (hasModelNodeForInternalId(internalNodeId)) { - QmlModelState state(modelNodeForInternalId(internalNodeId)); - try { - if (state.isValid()) - state.setAsDefault(); - - } catch (const RewritingException &e) { - e.showException(); - } - } -} - -void StatesEditorView::resetDefaultState() -{ - if (m_block) - return; - - m_block = true; - const QScopeGuard cleanup([&] { m_block = false; }); - - try { - if (activeStatesGroupNode().hasProperty("state")) - activeStatesGroupNode().removeProperty("state"); - - } catch (const RewritingException &e) { - e.showException(); - } -} - -bool StatesEditorView::hasDefaultState() const -{ - return activeStatesGroupNode().hasProperty("state"); -} - -void StatesEditorView::setAnnotation(int internalNodeId) -{ - if (m_block) - return; - - m_block = true; - const QScopeGuard cleanup([&] { m_block = false; }); - - if (hasModelNodeForInternalId(internalNodeId)) { - QmlModelState state(modelNodeForInternalId(internalNodeId)); - try { - if (state.isValid()) { - ModelNode modelNode = state.modelNode(); - - if (modelNode.isValid()) { - if (!m_editor) - m_editor = new AnnotationEditor(this); - - m_editor->setModelNode(modelNode); - m_editor->showWidget(); - } - } - - } catch (const RewritingException &e) { - e.showException(); - } - } -} - -void StatesEditorView::removeAnnotation(int internalNodeId) -{ - if (m_block) - return; - - m_block = true; - const QScopeGuard cleanup([&] { m_block = false; }); - - if (hasModelNodeForInternalId(internalNodeId)) { - QmlModelState state(modelNodeForInternalId(internalNodeId)); - try { - if (state.isValid()) - state.removeAnnotation(); - - } catch (const RewritingException &e) { - e.showException(); - } - } -} - -bool StatesEditorView::hasAnnotation(int internalNodeId) const -{ - if (!model()) - return false; - - if (hasModelNodeForInternalId(internalNodeId)) { - QmlModelState state(modelNodeForInternalId(internalNodeId)); - if (state.isValid()) - return state.hasAnnotation(); - } - - return false; -} - -void StatesEditorView::modelAttached(Model *model) -{ - if (model == AbstractView::model()) - return; - - QTC_ASSERT(model, return ); - AbstractView::modelAttached(model); - - m_activeStatesGroupNode = rootModelNode(); - - if (m_statesEditorWidget) - m_statesEditorWidget->setNodeInstanceView(nodeInstanceView()); - - checkForStatesAvailability(); - - resetModel(); - resetStateGroups(); - - emit m_statesEditorModel->activeStateGroupChanged(); - emit m_statesEditorModel->activeStateGroupIndexChanged(); -} - -void StatesEditorView::modelAboutToBeDetached(Model *model) -{ - AbstractView::modelAboutToBeDetached(model); - resetModel(); -} - -void StatesEditorView::propertiesRemoved(const QList& propertyList) -{ - for (const AbstractProperty &property : propertyList) { - if (property.name() == "states" && property.parentModelNode() == activeStateGroup().modelNode()) - resetModel(); - if ((property.name() == "when" || property.name() == "name") - && QmlModelState::isValidQmlModelState(property.parentModelNode())) - resetModel(); - if (property.name() == "extend") - resetExtend(); - if (property.parentModelNode().simplifiedTypeName() == "PropertyChanges" - || (property.name() == "changes" - && property.parentModelNode().simplifiedTypeName() == "State")) - resetPropertyChangesModels(); - } -} - -void StatesEditorView::nodeAboutToBeRemoved(const ModelNode &removedNode) -{ - if (removedNode.hasParentProperty()) { - const NodeAbstractProperty propertyParent = removedNode.parentProperty(); - if (propertyParent.parentModelNode() == activeStateGroup().modelNode() - && propertyParent.name() == "states") - m_lastIndex = propertyParent.indexOf(removedNode); - } - if (currentState().isValid() && removedNode == currentState()) - setCurrentState(baseState()); - - if (removedNode.simplifiedTypeName() == "PropertyChanges") - m_propertyChangesRemoved = true; - - if (removedNode.simplifiedTypeName() == "StateGroup") { - if (removedNode == activeStatesGroupNode()) - setActiveStatesGroupNode(rootModelNode()); - - m_stateGroupRemoved = true; - } -} - -void StatesEditorView::nodeRemoved(const ModelNode & /*removedNode*/, - const NodeAbstractProperty &parentProperty, - PropertyChangeFlags /*propertyChange*/) -{ - if (parentProperty.isValid() - && parentProperty.parentModelNode() == activeStateGroup().modelNode() - && parentProperty.name() == "states") { - m_statesEditorModel->removeState(m_lastIndex); - m_lastIndex = -1; - resetModel(); - } - - if (m_propertyChangesRemoved) { - m_propertyChangesRemoved = false; - resetPropertyChangesModels(); - } - - if (m_stateGroupRemoved) { - m_stateGroupRemoved = false; - resetStateGroups(); - } -} - -void StatesEditorView::nodeAboutToBeReparented(const ModelNode &node, - const NodeAbstractProperty & /*newPropertyParent*/, - const NodeAbstractProperty &oldPropertyParent, - AbstractView::PropertyChangeFlags /*propertyChange*/) -{ - if (oldPropertyParent.isValid() - && oldPropertyParent.parentModelNode() == activeStateGroup().modelNode() - && oldPropertyParent.name() == "states") - m_lastIndex = oldPropertyParent.indexOf(node); - - if (node.simplifiedTypeName() == "StateGroup") - resetStateGroups(); -} - -void StatesEditorView::nodeReparented(const ModelNode &node, - const NodeAbstractProperty &newPropertyParent, - const NodeAbstractProperty &oldPropertyParent, - AbstractView::PropertyChangeFlags /*propertyChange*/) -{ - if (oldPropertyParent.isValid() - && oldPropertyParent.parentModelNode() == activeStateGroup().modelNode() - && oldPropertyParent.name() == "states") { - m_statesEditorModel->removeState(m_lastIndex); - resetModel(); - m_lastIndex = -1; - } - - if (newPropertyParent.isValid() - && newPropertyParent.parentModelNode() == activeStateGroup().modelNode() - && newPropertyParent.name() == "states") { - int index = newPropertyParent.indexOf(node); - m_statesEditorModel->insertState(index); - } - - if (node.simplifiedTypeName() == "PropertyChanges") - resetPropertyChangesModels(); -} - -void StatesEditorView::nodeOrderChanged(const NodeListProperty &listProperty) -{ - if (m_block) - return; - - if (listProperty.isValid() && listProperty.parentModelNode() == activeStateGroup().modelNode() - && listProperty.name() == "states") - resetModel(); -} - -void StatesEditorView::bindingPropertiesChanged(const QList &propertyList, AbstractView::PropertyChangeFlags propertyChange) -{ - Q_UNUSED(propertyChange) - - for (const BindingProperty &property : propertyList) { - if (property.name() == "when" - && QmlModelState::isValidQmlModelState(property.parentModelNode())) - resetModel(); - if (property.parentModelNode().simplifiedTypeName() == "PropertyChanges") - resetPropertyChangesModels(); - } -} - -void StatesEditorView::variantPropertiesChanged(const QList &propertyList, - AbstractView::PropertyChangeFlags /*propertyChange*/) -{ - if (m_block) - return; - - m_block = true; - const QScopeGuard cleanup([&] { m_block = false; }); - - for (const VariantProperty &property : propertyList) { - if (property.name() == "name" - && QmlModelState::isValidQmlModelState(property.parentModelNode())) - resetModel(); - else if (property.name() == "state" - && property.parentModelNode() == activeStateGroup().modelNode()) - resetModel(); - else if (property.name() == "extend") - resetExtend(); - - if (property.parentModelNode().simplifiedTypeName() == "PropertyChanges") - resetPropertyChangesModels(); - } -} - -void StatesEditorView::customNotification(const AbstractView * /*view*/, - const QString &identifier, - const QList & /*nodeList*/, - const QList & /*data*/) -{ - if (identifier == StartRewriterAmend) - beginBulkChange(); - - if (identifier == EndRewriterAmend) - endBulkChange(); -} - -void StatesEditorView::rewriterBeginTransaction() -{ - beginBulkChange(); -} - -void StatesEditorView::rewriterEndTransaction() -{ - endBulkChange(); -} - -void StatesEditorView::currentStateChanged(const ModelNode &node) -{ - QmlModelState newQmlModelState(node); - - if (newQmlModelState.isBaseState()) - m_statesEditorWidget->setCurrentStateInternalId(0); - else - m_statesEditorWidget->setCurrentStateInternalId(newQmlModelState.modelNode().internalId()); -} - -void StatesEditorView::instancesPreviewImageChanged(const QVector &nodeList) -{ - if (!model()) - return; - - int minimumIndex = 10000; - int maximumIndex = -1; - for (const ModelNode &node : nodeList) { - if (node.isRootNode()) { - minimumIndex = qMin(minimumIndex, 0); - maximumIndex = qMax(maximumIndex, 0); - } else { - int index = activeStateGroup().allStates().indexOf(QmlModelState(node)) + 1; - if (index > 0) { - minimumIndex = qMin(minimumIndex, index); - maximumIndex = qMax(maximumIndex, index); - } - } - } - - if (maximumIndex >= 0) - m_statesEditorModel->updateState(minimumIndex, maximumIndex); -} - -void StatesEditorView::moveStates(int from, int to) -{ - if (m_block) - return; - - m_block = true; - const QScopeGuard cleanup([&] { m_block = false; }); - - if (!activeStatesGroupNode().hasNodeListProperty("states")) - return; - - executeInTransaction("moveState", [this, from, to]() { - activeStatesGroupNode().nodeListProperty("states").slide(from - 1, to - 1); - }); -} - -} // namespace Experimental -} // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/stateseditornew/stateseditorview.h b/src/plugins/qmldesigner/components/stateseditornew/stateseditorview.h deleted file mode 100644 index 57adacd87b8..00000000000 --- a/src/plugins/qmldesigner/components/stateseditornew/stateseditorview.h +++ /dev/null @@ -1,157 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2022 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of Qt Creator. -** -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3 as published by the Free Software -** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-3.0.html. -** -****************************************************************************/ - -#pragma once - -#include - -#include - -#include - -namespace QmlDesigner { - -class AnnotationEditor; - -namespace Experimental { - -class StatesEditorModel; -class StatesEditorWidget; -class PropertyChangesModel; - -class StatesEditorView : public AbstractView { - Q_OBJECT - -public: - explicit StatesEditorView(ExternalDependenciesInterface &externalDependencies); - ~StatesEditorView() override; - - void renameState(int internalNodeId,const QString &newName); - void setWhenCondition(int internalNodeId, const QString &condition); - void resetWhenCondition(int internalNodeId); - void setStateAsDefault(int internalNodeId); - void resetDefaultState(); - bool hasDefaultState() const; - void setAnnotation(int internalNodeId); - void removeAnnotation(int internalNodeId); - bool hasAnnotation(int internalNodeId) const; - bool validStateName(const QString &name) const; - bool hasExtend() const; - QStringList extendedStates() const; - QString currentStateName() const; - void setCurrentState(const QmlModelState &state); - QmlModelState baseState() const; - QmlModelStateGroup activeStateGroup() const; - - void moveStates(int from, int to); - - // AbstractView - void modelAttached(Model *model) override; - void modelAboutToBeDetached(Model *model) override; - void propertiesRemoved(const QList& propertyList) override; - void nodeAboutToBeRemoved(const ModelNode &removedNode) override; - void nodeRemoved(const ModelNode &removedNode, - const NodeAbstractProperty &parentProperty, - PropertyChangeFlags propertyChange) override; - void nodeAboutToBeReparented(const ModelNode &node, - const NodeAbstractProperty &newPropertyParent, - const NodeAbstractProperty &oldPropertyParent, - AbstractView::PropertyChangeFlags propertyChange) override; - void nodeReparented(const ModelNode &node, - const NodeAbstractProperty &newPropertyParent, - const NodeAbstractProperty &oldPropertyParent, - AbstractView::PropertyChangeFlags propertyChange) override; - void nodeOrderChanged(const NodeListProperty &listProperty) override; - void bindingPropertiesChanged(const QList &propertyList, - PropertyChangeFlags propertyChange) override; - void variantPropertiesChanged(const QList &propertyList, - PropertyChangeFlags propertyChange) override; - - void customNotification(const AbstractView *view, - const QString &identifier, - const QList &nodeList, - const QList &data) override; - void rewriterBeginTransaction() override; - void rewriterEndTransaction() override; - - // AbstractView - void currentStateChanged(const ModelNode &node) override; - - void instancesPreviewImageChanged(const QVector &nodeList) override; - - WidgetInfo widgetInfo() override; - - void rootNodeTypeChanged(const QString &type, int majorVersion, int minorVersion) override; - - ModelNode activeStatesGroupNode() const; - void setActiveStatesGroupNode(const ModelNode &modelNode); - - int activeStatesGroupIndex() const; - void setActiveStatesGroupIndex(int index); - - void registerPropertyChangesModel(PropertyChangesModel *model); - void deregisterPropertyChangesModel(PropertyChangesModel *model); - -public slots: - void synchonizeCurrentStateFromWidget(); - void createNewState(); - void cloneState(int nodeId); - void extendState(int nodeId); - void removeState(int nodeId); - -private: - void resetModel(); - void resetPropertyChangesModels(); - void resetExtend(); - void resetStateGroups(); - - void checkForStatesAvailability(); - - void beginBulkChange(); - void endBulkChange(); - -private: - QPointer m_statesEditorModel; - QPointer m_statesEditorWidget; - int m_lastIndex; - bool m_block = false; - QPointer m_editor; - ModelNode m_activeStatesGroupNode; - - bool m_propertyChangesRemoved = false; - bool m_stateGroupRemoved = false; - - bool m_bulkChange = false; - - bool m_modelDirty = false; - bool m_extendDirty = false; - bool m_propertyChangesDirty = false; - bool m_stateGroupsDirty = false; - - QSet m_propertyChangedModels; -}; - -} // namespace Experimental -} // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/stateseditornew/stateseditorwidget.cpp b/src/plugins/qmldesigner/components/stateseditornew/stateseditorwidget.cpp deleted file mode 100644 index e07ba02ae01..00000000000 --- a/src/plugins/qmldesigner/components/stateseditornew/stateseditorwidget.cpp +++ /dev/null @@ -1,200 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2022 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of Qt Creator. -** -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3 as published by the Free Software -** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-3.0.html. -** -****************************************************************************/ - -#include "stateseditorwidget.h" -#include "stateseditormodel.h" -#include "stateseditorview.h" -#include "stateseditorimageprovider.h" - -#include -#include -#include -#include - -#include - -#include -#include - -#include -#include - -#include - -#include -#include -#include -#include - -#include -#include -#include - -enum { - debug = false -}; - -namespace QmlDesigner { -namespace Experimental { - -static QString propertyEditorResourcesPath() -{ -#ifdef SHARE_QML_PATH - if (qEnvironmentVariableIsSet("LOAD_QML_FROM_SOURCE")) - return QLatin1String(SHARE_QML_PATH) + "/propertyEditorQmlSources"; -#endif - return Core::ICore::resourcePath("qmldesigner/propertyEditorQmlSources").toString(); -} - -int StatesEditorWidget::currentStateInternalId() const -{ - QTC_ASSERT(rootObject(), return -1); - QTC_ASSERT(rootObject()->property("currentStateInternalId").isValid(), return -1); - - return rootObject()->property("currentStateInternalId").toInt(); -} - -void StatesEditorWidget::setCurrentStateInternalId(int internalId) -{ - QTC_ASSERT(rootObject(), return); - rootObject()->setProperty("currentStateInternalId", internalId); -} - -void StatesEditorWidget::setNodeInstanceView(const NodeInstanceView *nodeInstanceView) -{ - m_imageProvider->setNodeInstanceView(nodeInstanceView); -} - -void StatesEditorWidget::showAddNewStatesButton(bool showAddNewStatesButton) -{ - rootContext()->setContextProperty(QLatin1String("canAddNewStates"), showAddNewStatesButton); -} - -StatesEditorWidget::StatesEditorWidget(StatesEditorView *statesEditorView, - StatesEditorModel *statesEditorModel) - : m_statesEditorView(statesEditorView) - , m_imageProvider(nullptr) - , m_qmlSourceUpdateShortcut(nullptr) -{ - m_imageProvider = new Internal::StatesEditorImageProvider; - m_imageProvider->setNodeInstanceView(statesEditorView->nodeInstanceView()); - - engine()->addImageProvider(QStringLiteral("qmldesigner_stateseditor"), m_imageProvider); - engine()->addImportPath(qmlSourcesPath()); - engine()->addImportPath(propertyEditorResourcesPath() + "/imports"); - engine()->addImportPath(qmlSourcesPath() + "/imports"); - - m_qmlSourceUpdateShortcut = new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_F10), this); - connect(m_qmlSourceUpdateShortcut, &QShortcut::activated, this, &StatesEditorWidget::reloadQmlSource); - - setObjectName(Constants::OBJECT_NAME_STATES_EDITOR); - setResizeMode(QQuickWidget::SizeRootObjectToView); - setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - - rootContext()->setContextProperties( - QVector{{{"statesEditorModel"}, - QVariant::fromValue(statesEditorModel)}, - {{"canAddNewStates"}, true}}); - - Theme::setupTheme(engine()); - - setWindowTitle(tr("States New", "Title of Editor widget")); - setMinimumWidth(195); - setMinimumHeight(195); - - // init the first load of the QML UI elements - reloadQmlSource(); -} - -StatesEditorWidget::~StatesEditorWidget() = default; - -QString StatesEditorWidget::qmlSourcesPath() -{ -#ifdef SHARE_QML_PATH - if (qEnvironmentVariableIsSet("LOAD_QML_FROM_SOURCE")) - return QLatin1String(SHARE_QML_PATH) + "/newstateseditor"; -#endif - return Core::ICore::resourcePath("qmldesigner/newstateseditor").toString(); -} - -void StatesEditorWidget::showEvent(QShowEvent *event) -{ - QQuickWidget::showEvent(event); - update(); - QMetaObject::invokeMethod(rootObject(), "showEvent"); -} - -void StatesEditorWidget::focusOutEvent(QFocusEvent *focusEvent) -{ - QmlDesignerPlugin::emitUsageStatisticsTime(Constants::EVENT_STATESEDITOR_TIME, - m_usageTimer.elapsed()); - QQuickWidget::focusOutEvent(focusEvent); -} - -void StatesEditorWidget::focusInEvent(QFocusEvent *focusEvent) -{ - m_usageTimer.restart(); - QQuickWidget::focusInEvent(focusEvent); -} - -void StatesEditorWidget::reloadQmlSource() -{ - QString statesListQmlFilePath = qmlSourcesPath() + QStringLiteral("/Main.qml"); - QTC_ASSERT(QFileInfo::exists(statesListQmlFilePath), return ); - setSource(QUrl::fromLocalFile(statesListQmlFilePath)); - - if (!rootObject()) { - QString errorString; - for (const QQmlError &error : errors()) - errorString += "\n" + error.toString(); - - Core::AsynchronousMessageBox::warning(tr("Cannot Create QtQuick View"), - tr("StatesEditorWidget: %1 cannot be created.%2") - .arg(qmlSourcesPath(), errorString)); - return; - } - - connect(rootObject(), - SIGNAL(currentStateInternalIdChanged()), - m_statesEditorView.data(), - SLOT(synchonizeCurrentStateFromWidget())); - connect(rootObject(), - SIGNAL(createNewState()), - m_statesEditorView.data(), - SLOT(createNewState())); - connect(rootObject(), SIGNAL(cloneState(int)), m_statesEditorView.data(), SLOT(cloneState(int))); - connect(rootObject(), - SIGNAL(extendState(int)), - m_statesEditorView.data(), - SLOT(extendState(int))); - connect(rootObject(), - SIGNAL(deleteState(int)), - m_statesEditorView.data(), - SLOT(removeState(int))); - m_statesEditorView.data()->synchonizeCurrentStateFromWidget(); -} - -} // namespace Experimental -} // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/stateseditornew/stateseditorwidget.h b/src/plugins/qmldesigner/components/stateseditornew/stateseditorwidget.h deleted file mode 100644 index 0b8ca901e03..00000000000 --- a/src/plugins/qmldesigner/components/stateseditornew/stateseditorwidget.h +++ /dev/null @@ -1,80 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2022 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of Qt Creator. -** -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3 as published by the Free Software -** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT -** included in the packaging of this file. Please review the following -** information to ensure the GNU General Public License requirements will -** be met: https://www.gnu.org/licenses/gpl-3.0.html. -** -****************************************************************************/ - -#pragma once - -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE -class QShortcut; -QT_END_NAMESPACE - -namespace QmlDesigner { - -class NodeInstanceView; - -namespace Experimental { - -class StatesEditorModel; -class StatesEditorView; - -namespace Internal { class StatesEditorImageProvider; } - -class StatesEditorWidget : public QQuickWidget -{ - Q_OBJECT - -public: - StatesEditorWidget(StatesEditorView *m_statesEditorView, StatesEditorModel *statesEditorModel); - ~StatesEditorWidget() override; - - int currentStateInternalId() const; - void setCurrentStateInternalId(int internalId); - void setNodeInstanceView(const NodeInstanceView *nodeInstanceView); - - void showAddNewStatesButton(bool showAddNewStatesButton); - - static QString qmlSourcesPath(); - -protected: - void showEvent(QShowEvent *) override; - void focusOutEvent(QFocusEvent *focusEvent) override; - void focusInEvent(QFocusEvent *focusEvent) override; - -private: - void reloadQmlSource(); - -private: - QPointer m_statesEditorView; - Internal::StatesEditorImageProvider *m_imageProvider; - QShortcut *m_qmlSourceUpdateShortcut; - QElapsedTimer m_usageTimer; -}; - -} // namespace Experimental -} // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/components/textureeditor/textureeditorcontextobject.cpp b/src/plugins/qmldesigner/components/textureeditor/textureeditorcontextobject.cpp index 1148e31e2ba..8d1b03bddd6 100644 --- a/src/plugins/qmldesigner/components/textureeditor/textureeditorcontextobject.cpp +++ b/src/plugins/qmldesigner/components/textureeditor/textureeditorcontextobject.cpp @@ -315,17 +315,8 @@ QStringList TextureEditorContextObject::allStatesForId(const QString &id) return {}; } -bool TextureEditorContextObject::isBlocked(const QString &propName) const +bool TextureEditorContextObject::isBlocked(const QString &) const { - if (!m_selectedTexture.isValid()) - return false; - - if (!m_model || !m_model->rewriterView()) - return false; - - if (QmlObjectNode(m_selectedTexture).isBlocked(propName.toUtf8())) - return true; - return false; } diff --git a/src/plugins/qmldesigner/components/textureeditor/textureeditorqmlbackend.cpp b/src/plugins/qmldesigner/components/textureeditor/textureeditorqmlbackend.cpp index e54909049ed..1325ade10c7 100644 --- a/src/plugins/qmldesigner/components/textureeditor/textureeditorqmlbackend.cpp +++ b/src/plugins/qmldesigner/components/textureeditor/textureeditorqmlbackend.cpp @@ -34,7 +34,7 @@ static QObject *variantToQObject(const QVariant &value) { - if (value.userType() == QMetaType::QObjectStar || value.userType() > QMetaType::User) + if (value.typeId() == QMetaType::QObjectStar || value.typeId() > QMetaType::User) return *(QObject **)value.constData(); return nullptr; @@ -109,7 +109,7 @@ void TextureEditorQmlBackend::createPropertyEditorValue(const QmlObjectNode &qml void TextureEditorQmlBackend::setValue(const QmlObjectNode &, const PropertyName &name, const QVariant &value) { // Vector*D values need to be split into their subcomponents - if (value.type() == QVariant::Vector2D) { + if (value.typeId() == QVariant::Vector2D) { const char *suffix[2] = {"_x", "_y"}; auto vecValue = value.value(); for (int i = 0; i < 2; ++i) { @@ -120,7 +120,7 @@ void TextureEditorQmlBackend::setValue(const QmlObjectNode &, const PropertyName if (propertyValue) propertyValue->setValue(QVariant(vecValue[i])); } - } else if (value.type() == QVariant::Vector3D) { + } else if (value.typeId() == QVariant::Vector3D) { const char *suffix[3] = {"_x", "_y", "_z"}; auto vecValue = value.value(); for (int i = 0; i < 3; ++i) { @@ -131,7 +131,7 @@ void TextureEditorQmlBackend::setValue(const QmlObjectNode &, const PropertyName if (propertyValue) propertyValue->setValue(QVariant(vecValue[i])); } - } else if (value.type() == QVariant::Vector4D) { + } else if (value.typeId() == QVariant::Vector4D) { const char *suffix[4] = {"_x", "_y", "_z", "_w"}; auto vecValue = value.value(); for (int i = 0; i < 4; ++i) { diff --git a/src/plugins/qmldesigner/components/textureeditor/textureeditorview.cpp b/src/plugins/qmldesigner/components/textureeditor/textureeditorview.cpp index 221de40509f..98601ce45ed 100644 --- a/src/plugins/qmldesigner/components/textureeditor/textureeditorview.cpp +++ b/src/plugins/qmldesigner/components/textureeditor/textureeditorview.cpp @@ -141,7 +141,7 @@ void TextureEditorView::changeValue(const QString &name) if (name == "state" && castedValue.toString() == "base state") castedValue = ""; - if (castedValue.type() == QVariant::Color) { + if (castedValue.typeId() == QVariant::Color) { QColor color = castedValue.value(); QColor newColor = QColor(color.name()); newColor.setAlpha(color.alpha()); @@ -389,8 +389,11 @@ void TextureEditorView::handleToolBarAction(int action) } case TextureEditorContextObject::DeleteCurrentTexture: { - if (m_selectedTexture.isValid()) - m_selectedTexture.destroy(); + if (m_selectedTexture.isValid()) { + executeInTransaction(__FUNCTION__, [&] { + m_selectedTexture.destroy(); + }); + } break; } diff --git a/src/plugins/qmldesigner/components/timelineeditor/canvas.cpp b/src/plugins/qmldesigner/components/timelineeditor/canvas.cpp index f82d2098c6e..66f207bd836 100644 --- a/src/plugins/qmldesigner/components/timelineeditor/canvas.cpp +++ b/src/plugins/qmldesigner/components/timelineeditor/canvas.cpp @@ -134,7 +134,7 @@ void Canvas::paintCurve(QPainter *painter, const EasingCurve &curve, const QColo void Canvas::paintControlPoints(QPainter *painter, const EasingCurve &curve) { QVector points = curve.toCubicSpline(); - int count = points.count(); + int count = points.size(); if (count <= 1) return; diff --git a/src/plugins/qmldesigner/components/timelineeditor/easingcurve.cpp b/src/plugins/qmldesigner/components/timelineeditor/easingcurve.cpp index 92f7590503e..ae9833e46ec 100644 --- a/src/plugins/qmldesigner/components/timelineeditor/easingcurve.cpp +++ b/src/plugins/qmldesigner/components/timelineeditor/easingcurve.cpp @@ -49,7 +49,7 @@ void EasingCurve::registerStreamOperators() int EasingCurve::count() const { - return toCubicSpline().count(); + return toCubicSpline().size(); } int EasingCurve::active() const @@ -59,7 +59,7 @@ int EasingCurve::active() const int EasingCurve::segmentCount() const { - return toCubicSpline().count() / 3; + return toCubicSpline().size() / 3; } bool EasingCurve::isLegal() const @@ -127,10 +127,10 @@ bool EasingCurve::fromString(const QString &code) if (code.startsWith(QLatin1Char('[')) && code.endsWith(QLatin1Char(']'))) { const auto stringList = code.mid(1, code.size() - 2).split(QLatin1Char(','), Qt::SkipEmptyParts); - if (stringList.count() >= 6 && (stringList.count() % 6 == 0)) { + if (stringList.size() >= 6 && (stringList.size() % 6 == 0)) { bool checkX, checkY; QVector points; - for (int i = 0; i < stringList.count(); ++i) { + for (int i = 0; i < stringList.size(); ++i) { QPointF point; point.rx() = stringList[i].toDouble(&checkX); point.ry() = stringList[++i].toDouble(&checkY); @@ -146,7 +146,7 @@ bool EasingCurve::fromString(const QString &code) QEasingCurve easingCurve(QEasingCurve::BezierSpline); - for (int i = 0; i < points.count() / 3; ++i) { + for (int i = 0; i < points.size() / 3; ++i) { easingCurve.addCubicBezierSegment(points.at(i * 3), points.at(i * 3 + 1), points.at(i * 3 + 2)); @@ -176,7 +176,7 @@ QPainterPath EasingCurve::path() const QVector controlPoints = toCubicSpline(); - int numSegments = controlPoints.count() / 3; + int numSegments = controlPoints.size() / 3; for (int i = 0; i < numSegments; i++) { QPointF p1 = controlPoints.at(i * 3); QPointF p2 = controlPoints.at(i * 3 + 1); @@ -202,7 +202,7 @@ QPointF EasingCurve::point(int idx) const { QVector controlPoints = toCubicSpline(); - QTC_ASSERT(controlPoints.count() > idx || idx < 0, return QPointF()); + QTC_ASSERT(controlPoints.size() > idx || idx < 0, return QPointF()); return controlPoints.at(idx); } @@ -259,7 +259,7 @@ void EasingCurve::makeSmooth(int idx) before = controlPoints.at(idx - 3); QPointF after = end(); - if ((idx + 3) < controlPoints.count()) + if ((idx + 3) < controlPoints.size()) after = controlPoints.at(idx + 3); QPointF tangent = (after - before) / 6; @@ -269,7 +269,7 @@ void EasingCurve::makeSmooth(int idx) if (idx > 0) controlPoints[idx - 1] = thisPoint - tangent; - if (idx + 1 < controlPoints.count()) + if (idx + 1 < controlPoints.size()) controlPoints[idx + 1] = thisPoint + tangent; fromCubicSpline(controlPoints); @@ -288,7 +288,7 @@ void EasingCurve::breakTangent(int idx) before = controlPoints.at(idx - 3); QPointF after = end(); - if ((idx + 3) < controlPoints.count()) + if ((idx + 3) < controlPoints.size()) after = controlPoints.at(idx + 3); QPointF thisPoint = controlPoints.at(idx); @@ -296,7 +296,7 @@ void EasingCurve::breakTangent(int idx) if (idx > 0) controlPoints[idx - 1] = (before - thisPoint) / 3 + thisPoint; - if (idx + 1 < controlPoints.count()) + if (idx + 1 < controlPoints.size()) controlPoints[idx + 1] = (after - thisPoint) / 3 + thisPoint; fromCubicSpline(controlPoints); @@ -326,7 +326,7 @@ void EasingCurve::addPoint(const QPointF &point) } QPointF after = end(); - if ((splitIndex + 3) < controlPoints.count()) { + if ((splitIndex + 3) < controlPoints.size()) { after = controlPoints.at(splitIndex + 3); } @@ -394,7 +394,7 @@ void EasingCurve::fromCubicSpline(const QVector &points) { QEasingCurve tmp(QEasingCurve::BezierSpline); - int numSegments = points.count() / 3; + int numSegments = points.size() / 3; for (int i = 0; i < numSegments; ++i) { tmp.addCubicBezierSegment(points.at(i * 3), points.at(i * 3 + 1), points.at(i * 3 + 2)); } diff --git a/src/plugins/qmldesigner/components/timelineeditor/timelineanimationform.cpp b/src/plugins/qmldesigner/components/timelineeditor/timelineanimationform.cpp index d7b700dde81..83551378eea 100644 --- a/src/plugins/qmldesigner/components/timelineeditor/timelineanimationform.cpp +++ b/src/plugins/qmldesigner/components/timelineeditor/timelineanimationform.cpp @@ -292,7 +292,7 @@ void TimelineAnimationForm::populateStateComboBox() if (m_animation.signalHandlerProperty("onFinished").isValid()) { const QString source = m_animation.signalHandlerProperty("onFinished").source(); const QStringList list = source.split("="); - if (list.count() == 2) { + if (list.size() == 2) { QString name = list.last().trimmed(); name.chop(1); name.remove(0, 1); diff --git a/src/plugins/qmldesigner/components/timelineeditor/timelinecontrols.cpp b/src/plugins/qmldesigner/components/timelineeditor/timelinecontrols.cpp index d9f3dd4d167..708bd8c4d3e 100644 --- a/src/plugins/qmldesigner/components/timelineeditor/timelinecontrols.cpp +++ b/src/plugins/qmldesigner/components/timelineeditor/timelinecontrols.cpp @@ -78,7 +78,7 @@ QVariant FloatControl::controlValue() const void FloatControl::setControlValue(const QVariant &value) { - if (value.userType() != QMetaType::Float && value.userType() != QMetaType::Double) + if (value.typeId() != QMetaType::Float && value.typeId() != QMetaType::Double) return; QSignalBlocker blocker(this); @@ -129,7 +129,7 @@ QVariant ColorControl::controlValue() const void ColorControl::setControlValue(const QVariant &value) { - if (value.userType() != QMetaType::QColor) + if (value.typeId() != QMetaType::QColor) return; m_color = qvariant_cast(value); diff --git a/src/plugins/qmldesigner/components/timelineeditor/timelinegraphicsscene.cpp b/src/plugins/qmldesigner/components/timelineeditor/timelinegraphicsscene.cpp index ddddc7c753a..f116d96223e 100644 --- a/src/plugins/qmldesigner/components/timelineeditor/timelinegraphicsscene.cpp +++ b/src/plugins/qmldesigner/components/timelineeditor/timelinegraphicsscene.cpp @@ -386,7 +386,7 @@ bool AbstractScrollGraphicsScene::isKeyframeSelected(TimelineKeyframeItem *keyfr bool AbstractScrollGraphicsScene::multipleKeyframesSelected() const { - return m_selectedKeyframes.count() > 1; + return m_selectedKeyframes.size() > 1; } void TimelineGraphicsScene::invalidateSectionForTarget(const ModelNode &target) diff --git a/src/plugins/qmldesigner/components/timelineeditor/timelinepropertyitem.cpp b/src/plugins/qmldesigner/components/timelineeditor/timelinepropertyitem.cpp index 8c0a9c9d734..6dcb39f2a01 100644 --- a/src/plugins/qmldesigner/components/timelineeditor/timelinepropertyitem.cpp +++ b/src/plugins/qmldesigner/components/timelineeditor/timelinepropertyitem.cpp @@ -105,7 +105,7 @@ static void editValue(const ModelNode &frameNode, const std::pair if (newFrame != frame) frameNode.variantProperty("frame").setValue(newFrame); - int userType = value.userType(); + int userType = value.typeId(); QVariant newValue = dialog->value(); if (newValue.canConvert(userType)) { @@ -264,7 +264,7 @@ bool TimelinePropertyItem::isSelected() const QString convertVariant(const QVariant &variant) { - if (variant.userType() == QMetaType::QColor) + if (variant.typeId() == QMetaType::QColor) return variant.toString(); return QString::number(variant.toFloat(), 'f', 2); @@ -335,9 +335,8 @@ void TimelinePropertyItem::changePropertyValue(const QVariant &value) QTimer::singleShot(0, deferredFunc); } else { - QScopedPointer objectNode { - QmlObjectNode::getQmlObjectNodeOfCorrectType(m_frames.target())}; - objectNode->setVariantProperty(m_frames.propertyName(), value); + if (auto qmlObjectNode = QmlObjectNode(m_frames.target())) + qmlObjectNode.setVariantProperty(m_frames.propertyName(), value); } } diff --git a/src/plugins/qmldesigner/components/timelineeditor/timelinesectionitem.cpp b/src/plugins/qmldesigner/components/timelineeditor/timelinesectionitem.cpp index 4604e9e3b86..7a733c37291 100644 --- a/src/plugins/qmldesigner/components/timelineeditor/timelinesectionitem.cpp +++ b/src/plugins/qmldesigner/components/timelineeditor/timelinesectionitem.cpp @@ -420,7 +420,7 @@ void TimelineSectionItem::invalidateHeight() visible = false; } else { height = TimelineConstants::sectionHeight - + m_timeline.keyframeGroupsForTarget(m_targetNode).count() + + m_timeline.keyframeGroupsForTarget(m_targetNode).size() * TimelineConstants::sectionHeight; visible = true; } @@ -801,7 +801,7 @@ void TimelineRulerSectionItem::extendPlaybackLoop(const QList &positions, qreal right = m_playbackLoopEnd; if (reset) { - if (positions.count() >= 2) { + if (positions.size() >= 2) { left = m_duration; right = 0; } else { diff --git a/src/plugins/qmldesigner/components/timelineeditor/timelineselectiontool.cpp b/src/plugins/qmldesigner/components/timelineeditor/timelineselectiontool.cpp index 68aeefcd238..230ab401a7b 100644 --- a/src/plugins/qmldesigner/components/timelineeditor/timelineselectiontool.cpp +++ b/src/plugins/qmldesigner/components/timelineeditor/timelineselectiontool.cpp @@ -169,7 +169,7 @@ void TimelineSelectionTool::aboutToSelect(SelectionMode mode, QList(scene())->layoutRuler()->extendPlaybackLoop(m_playbackLoopTimeSteps, mode == SelectionMode::Toggle); // TODO: Highlighting items with selection tool is set or added to loop range. Select shortcut for this QDS-4941 scene()->selectKeyframes(mode, m_aboutToSelectBuffer); diff --git a/src/plugins/qmldesigner/components/toolbar/toolbarbackend.cpp b/src/plugins/qmldesigner/components/toolbar/toolbarbackend.cpp index 1b9f1e3271f..c917dfe8a84 100644 --- a/src/plugins/qmldesigner/components/toolbar/toolbarbackend.cpp +++ b/src/plugins/qmldesigner/components/toolbar/toolbarbackend.cpp @@ -86,7 +86,7 @@ CrumbleBarModel::CrumbleBarModel(QObject *) int CrumbleBarModel::rowCount(const QModelIndex &) const { - return crumbleBar()->path().count(); + return crumbleBar()->path().size(); } QHash CrumbleBarModel::roleNames() const @@ -148,7 +148,7 @@ WorkspaceModel::WorkspaceModel(QObject *) int WorkspaceModel::rowCount(const QModelIndex &) const { if (designModeWidget() && designModeWidget()->dockManager()) - return designModeWidget()->dockManager()->workspaces().count(); + return designModeWidget()->dockManager()->workspaces().size(); return 0; } @@ -476,7 +476,7 @@ void ToolBarBackend::setCurrentStyle(int index) QmlDesignerPlugin::emitUsageStatistics(Constants::EVENT_STATUSBAR_SET_STYLE); const QList items = ChangeStyleWidgetAction::getAllStyleItems(); - QTC_ASSERT(items.count() > index, return ); + QTC_ASSERT(items.size() > index, return); QTC_ASSERT(index > 0, return ); QTC_ASSERT(currentDesignDocument(), return ); @@ -499,7 +499,7 @@ void ToolBarBackend::setCurrentKit(int index) const auto kits = ProjectExplorer::KitManager::kits(); - QTC_ASSERT(kits.count() > index, return ); + QTC_ASSERT(kits.size() > index, return); QTC_ASSERT(index >= 0, return ); const auto kit = kits.at(index); diff --git a/src/plugins/qmldesigner/components/transitioneditor/transitioneditorsectionitem.cpp b/src/plugins/qmldesigner/components/transitioneditor/transitioneditorsectionitem.cpp index d331e82b403..a5ec84fad2c 100644 --- a/src/plugins/qmldesigner/components/transitioneditor/transitioneditorsectionitem.cpp +++ b/src/plugins/qmldesigner/components/transitioneditor/transitioneditorsectionitem.cpp @@ -441,7 +441,7 @@ void TransitionEditorSectionItem::invalidateHeight() model->qtQuickPropertyAnimationMetaInfo()); height = TimelineConstants::sectionHeight - + propertyAnimations.count() * TimelineConstants::sectionHeight; + + propertyAnimations.size() * TimelineConstants::sectionHeight; visible = true; } diff --git a/src/plugins/qmldesigner/components/transitioneditor/transitioneditorview.cpp b/src/plugins/qmldesigner/components/transitioneditor/transitioneditorview.cpp index 03ebf4738e5..c24ebc1ce32 100644 --- a/src/plugins/qmldesigner/components/transitioneditor/transitioneditorview.cpp +++ b/src/plugins/qmldesigner/components/transitioneditor/transitioneditorview.cpp @@ -201,7 +201,7 @@ ModelNode TransitionEditorView::addNewTransition() const ModelNode target = change.target(); if (auto targetMetaInfo = target.metaInfo()) { const QString targetId = target.id(); - for (const VariantProperty &property : change.modelNode().variantProperties()) { + for (const AbstractProperty &property : change.modelNode().properties()) { auto type = targetMetaInfo.property(property.name()).propertyType(); if (type.isInteger() || type.isColor() || type.isFloat()) diff --git a/src/plugins/qmldesigner/components/transitioneditor/transitionform.cpp b/src/plugins/qmldesigner/components/transitioneditor/transitionform.cpp index 9613be51785..c58bdf61d52 100644 --- a/src/plugins/qmldesigner/components/transitioneditor/transitionform.cpp +++ b/src/plugins/qmldesigner/components/transitioneditor/transitionform.cpp @@ -66,7 +66,7 @@ TransitionForm::TransitionForm(QWidget *parent) QTC_ASSERT(m_transition.isValid(), return ); const QmlItemNode root(m_transition.view()->rootModelNode()); QTC_ASSERT(root.isValid(), return ); - const int stateCount = root.states().names().count(); + const int stateCount = root.states().names().size(); QStringList stateNames; @@ -76,7 +76,7 @@ TransitionForm::TransitionForm(QWidget *parent) } QString toValue; - if (stateCount == stateNames.count()) + if (stateCount == stateNames.size()) toValue = "*"; else toValue = stateNames.join(","); @@ -90,7 +90,7 @@ TransitionForm::TransitionForm(QWidget *parent) QTC_ASSERT(m_transition.isValid(), return ); const QmlItemNode root(m_transition.view()->rootModelNode()); QTC_ASSERT(root.isValid(), return ); - const int stateCount = root.states().names().count(); + const int stateCount = root.states().names().size(); QStringList stateNames; @@ -100,7 +100,7 @@ TransitionForm::TransitionForm(QWidget *parent) } QString fromValue; - if (stateCount == stateNames.count()) + if (stateCount == stateNames.size()) fromValue = "*"; else fromValue = stateNames.join(","); diff --git a/src/plugins/qmldesigner/designercore/imagecache/imagecacheconnectionmanager.cpp b/src/plugins/qmldesigner/designercore/imagecache/imagecacheconnectionmanager.cpp index ee40b3ec318..20728b445e4 100644 --- a/src/plugins/qmldesigner/designercore/imagecache/imagecacheconnectionmanager.cpp +++ b/src/plugins/qmldesigner/designercore/imagecache/imagecacheconnectionmanager.cpp @@ -47,7 +47,7 @@ void ImageCacheConnectionManager::dispatchCommand(const QVariant &command, { static const int capturedDataCommandType = QMetaType::type("CapturedDataCommand"); - if (command.userType() == capturedDataCommandType) { + if (command.typeId() == capturedDataCommandType) { m_captureCallback(command.value().image); m_capturedDataArrived = true; } diff --git a/src/plugins/qmldesigner/designercore/imagecache/imagecachestorage.h b/src/plugins/qmldesigner/designercore/imagecache/imagecachestorage.h index 37131012d69..0306349b23e 100644 --- a/src/plugins/qmldesigner/designercore/imagecache/imagecachestorage.h +++ b/src/plugins/qmldesigner/designercore/imagecache/imagecachestorage.h @@ -30,6 +30,7 @@ public: : database(database) { transaction.commit(); + database.walCheckpointFull(); } ImageEntry fetchImage(Utils::SmallStringView name, Sqlite::TimeStamp minimumTimeStamp) const override @@ -157,16 +158,10 @@ private: Initializer(DatabaseType &database) { if (!database.isInitialized()) { - Sqlite::ExclusiveTransaction transaction{database}; - createImagesTable(database); database.setVersion(1); - transaction.commit(); - database.setIsInitialized(true); - - database.walCheckpointFull(); } else if (database.version() < 1) { updateTableToVersion1(database); } @@ -203,13 +198,9 @@ private: void updateTableToVersion1(DatabaseType &database) { - Sqlite::ExclusiveTransaction transaction{database}; - database.execute("DELETE FROM images"); database.execute("ALTER TABLE images ADD COLUMN midSizeImage"); database.setVersion(1); - - transaction.commit(); } }; @@ -277,8 +268,8 @@ private: public: DatabaseType &database; + Sqlite::ExclusiveNonThrowingDestructorTransaction transaction{database}; Initializer initializer{database}; - Sqlite::ImmediateNonThrowingDestructorTransaction transaction{database}; mutable ReadStatement<1, 2> selectImageStatement{ "SELECT image FROM images WHERE name=?1 AND mtime >= ?2", database}; mutable ReadStatement<1, 2> selectMidSizeImageStatement{ diff --git a/src/plugins/qmldesigner/designercore/include/abstractproperty.h b/src/plugins/qmldesigner/designercore/include/abstractproperty.h index c22402202d8..6074858265a 100644 --- a/src/plugins/qmldesigner/designercore/include/abstractproperty.h +++ b/src/plugins/qmldesigner/designercore/include/abstractproperty.h @@ -19,7 +19,7 @@ namespace QmlDesigner { class InternalProperty; using InternalNodePointer = std::shared_ptr; - using InternalPropertyPointer = QSharedPointer; + using InternalPropertyPointer = std::shared_ptr; } class Model; @@ -45,9 +45,6 @@ class QMLDESIGNERCORE_EXPORT AbstractProperty friend ModelNode; friend Internal::ModelPrivate; - friend QMLDESIGNERCORE_EXPORT bool operator ==(const AbstractProperty &property1, const AbstractProperty &property2); - friend QMLDESIGNERCORE_EXPORT bool operator !=(const AbstractProperty &property1, const AbstractProperty &property2); - public: AbstractProperty() = default; AbstractProperty(const AbstractProperty &) = default; @@ -82,6 +79,8 @@ public: bool isSignalHandlerProperty() const; bool isSignalDeclarationProperty() const; + PropertyType type() const; + bool isDynamic() const; TypeName dynamicTypeName() const; @@ -107,10 +106,27 @@ public: return ::qHash(property.m_internalNode.get()) ^ ::qHash(property.m_propertyName); } + friend bool operator==(const AbstractProperty &first, const AbstractProperty &second) + { + return first.m_internalNode == second.m_internalNode + && first.m_propertyName == second.m_propertyName; + } + + friend bool operator!=(const AbstractProperty &first, const AbstractProperty &second) + { + return !(first == second); + } + + friend bool operator<(const AbstractProperty &first, const AbstractProperty &second) + { + return std::tie(first.m_internalNode, first.m_propertyName) + < std::tie(second.m_internalNode, second.m_propertyName); + } + protected: AbstractProperty(const PropertyName &propertyName, const Internal::InternalNodePointer &internalNode, Model* model, AbstractView *view); AbstractProperty(const Internal::InternalPropertyPointer &property, Model* model, AbstractView *view); - Internal::InternalNodePointer internalNode() const; + Internal::InternalNodePointer internalNode() const { return m_internalNode; } Internal::ModelPrivate *privateModel() const; private: @@ -120,8 +136,8 @@ private: QPointer m_view; }; -QMLDESIGNERCORE_EXPORT bool operator ==(const AbstractProperty &property1, const AbstractProperty &property2); -QMLDESIGNERCORE_EXPORT bool operator !=(const AbstractProperty &property1, const AbstractProperty &property2); +using AbstractProperties = QList; + QMLDESIGNERCORE_EXPORT QTextStream& operator<<(QTextStream &stream, const AbstractProperty &property); QMLDESIGNERCORE_EXPORT QDebug operator<<(QDebug debug, const AbstractProperty &AbstractProperty); } diff --git a/src/plugins/qmldesigner/designercore/include/abstractview.h b/src/plugins/qmldesigner/designercore/include/abstractview.h index 0c3df94030c..9035aba0fde 100644 --- a/src/plugins/qmldesigner/designercore/include/abstractview.h +++ b/src/plugins/qmldesigner/designercore/include/abstractview.h @@ -119,6 +119,7 @@ public: bool hasModelNodeForInternalId(qint32 internalId) const; QList allModelNodes() const; + QList allModelNodesUnordered() const; QList allModelNodesOfType(const NodeMetaInfo &typeName) const; void emitDocumentMessage(const QList &errors, const QList &warnings = {}); @@ -161,7 +162,8 @@ public: virtual void variantPropertiesChanged(const QList &propertyList, PropertyChangeFlags propertyChange); virtual void bindingPropertiesAboutToBeChanged(const QList &propertyList); - virtual void bindingPropertiesChanged(const QList &propertyList, PropertyChangeFlags propertyChange); + virtual void bindingPropertiesChanged(const QList &propertyList, + PropertyChangeFlags propertyChange); virtual void signalHandlerPropertiesChanged(const QVector &propertyList, PropertyChangeFlags propertyChange); virtual void signalDeclarationPropertiesChanged(const QVector &propertyList, @@ -304,5 +306,6 @@ private: }; QMLDESIGNERCORE_EXPORT QList toInternalNodeList(const QList &nodeList); -QMLDESIGNERCORE_EXPORT QList toModelNodeList(const QList &nodeList, AbstractView *view); +QMLDESIGNERCORE_EXPORT QList toModelNodeList( + const QList &nodeList, Model *model, AbstractView *view); } // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/designercore/include/bindingproperty.h b/src/plugins/qmldesigner/designercore/include/bindingproperty.h index 904866f0410..3ddf554c2cf 100644 --- a/src/plugins/qmldesigner/designercore/include/bindingproperty.h +++ b/src/plugins/qmldesigner/designercore/include/bindingproperty.h @@ -40,9 +40,17 @@ public: static QVariant convertToLiteral(const TypeName &typeName, const QString &expression); protected: - BindingProperty(const PropertyName &propertyName, const Internal::InternalNodePointer &internalNode, Model* model, AbstractView *view); + BindingProperty(const PropertyName &propertyName, + const Internal::InternalNodePointer &internalNode, + Model *model, + AbstractView *view); + +private: + ModelNode resolveBinding(const QString &binding, ModelNode currentNode) const; }; +using BindingProperties = QList; + bool compareBindingProperties(const QmlDesigner::BindingProperty &bindingProperty01, const QmlDesigner::BindingProperty &bindingProperty02); QMLDESIGNERCORE_EXPORT QTextStream& operator<<(QTextStream &stream, const BindingProperty &property); diff --git a/src/plugins/qmldesigner/designercore/include/model.h b/src/plugins/qmldesigner/designercore/include/model.h index c2cd807a8a2..3dbb0cceac2 100644 --- a/src/plugins/qmldesigner/designercore/include/model.h +++ b/src/plugins/qmldesigner/designercore/include/model.h @@ -34,6 +34,7 @@ class AbstractView; class NodeStateChangeSet; class MetaInfo; class NodeMetaInfo; +class NodeMetaInfoPrivate; class ModelState; class NodeAnchors; class AbstractProperty; @@ -43,15 +44,18 @@ class TextModifier; using PropertyListType = QList>; +enum class BypassModelResourceManagement { No, Yes }; + class QMLDESIGNERCORE_EXPORT Model : public QObject { friend ModelNode; + friend NodeMetaInfo; + friend NodeMetaInfoPrivate; friend AbstractProperty; friend AbstractView; friend Internal::ModelPrivate; friend Internal::WriteLocker; friend ModelDeleter; - friend class NodeMetaInfoPrivate; Q_OBJECT @@ -101,7 +105,9 @@ public: bool hasNodeMetaInfo(const TypeName &typeName, int majorVersion = -1, int minorVersion = -1) const; void setMetaInfo(const MetaInfo &metaInfo); + NodeMetaInfo flowViewFlowActionAreaMetaInfo() const; NodeMetaInfo flowViewFlowDecisionMetaInfo() const; + NodeMetaInfo flowViewFlowItemMetaInfo() const; NodeMetaInfo flowViewFlowTransitionMetaInfo() const; NodeMetaInfo flowViewFlowWildcardMetaInfo() const; NodeMetaInfo fontMetaInfo() const; @@ -117,12 +123,14 @@ public: NodeMetaInfo qtQuickImageMetaInfo() const; NodeMetaInfo qtQuickItemMetaInfo() const; NodeMetaInfo qtQuickPropertyAnimationMetaInfo() const; + NodeMetaInfo qtQuickPropertyChangesMetaInfo() const; NodeMetaInfo qtQuickRectangleMetaInfo() const; NodeMetaInfo qtQuickStateGroupMetaInfo() const; NodeMetaInfo qtQuickTextEditMetaInfo() const; NodeMetaInfo qtQuickTextMetaInfo() const; NodeMetaInfo qtQuickTimelineKeyframeGroupMetaInfo() const; NodeMetaInfo qtQuickTimelineTimelineMetaInfo() const; + NodeMetaInfo qtQuickTransistionMetaInfo() const; NodeMetaInfo vector2dMetaInfo() const; NodeMetaInfo vector3dMetaInfo() const; NodeMetaInfo vector4dMetaInfo() const; @@ -130,7 +138,18 @@ public: void attachView(AbstractView *view); void detachView(AbstractView *view, ViewNotification emitDetachNotify = NotifyView); - QList allModelNodes() const; + QList allModelNodesUnordered(); + ModelNode rootModelNode(); + + ModelNode modelNodeForId(const QString &id); + QHash idModelNodeDict(); + + ModelNode createModelNode(const TypeName &typeName); + + void removeModelNodes(ModelNodes nodes, + BypassModelResourceManagement = BypassModelResourceManagement::No); + void removeProperties(AbstractProperties properties, + BypassModelResourceManagement = BypassModelResourceManagement::No); // Editing sub-components: @@ -155,8 +174,6 @@ public: Model *metaInfoProxyModel() const; - TextModifier *textModifier() const; - void setTextModifier(TextModifier *textModifier); void setDocumentMessages(const QList &errors, const QList &warnings); diff --git a/src/plugins/qmldesigner/designercore/include/modelfwd.h b/src/plugins/qmldesigner/designercore/include/modelfwd.h index 66712499958..44154ce10b1 100644 --- a/src/plugins/qmldesigner/designercore/include/modelfwd.h +++ b/src/plugins/qmldesigner/designercore/include/modelfwd.h @@ -39,4 +39,14 @@ using ProjectStorageType = ProjectStorageInterface; using ProjectStorageType = ProjectStorage; #endif +enum class PropertyType { + None, + Variant, + Node, + NodeList, + Binding, + SignalHandler, + SignalDeclaration +}; + } // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/designercore/include/modelnode.h b/src/plugins/qmldesigner/designercore/include/modelnode.h index e9891da620c..657093b0ac0 100644 --- a/src/plugins/qmldesigner/designercore/include/modelnode.h +++ b/src/plugins/qmldesigner/designercore/include/modelnode.h @@ -28,7 +28,7 @@ namespace Internal { class InternalProperty; using InternalNodePointer = std::shared_ptr; - using InternalPropertyPointer = QSharedPointer; + using InternalPropertyPointer = std::shared_ptr; } class NodeMetaInfo; class BindingProperty; @@ -58,10 +58,7 @@ inline constexpr AuxiliaryDataKeyView transitionExpandedPropery{AuxiliaryDataTyp class QMLDESIGNERCORE_EXPORT ModelNode { - friend QMLDESIGNERCORE_EXPORT bool operator ==(const ModelNode &firstNode, const ModelNode &secondNode); - friend QMLDESIGNERCORE_EXPORT bool operator !=(const ModelNode &firstNode, const ModelNode &secondNode); friend QMLDESIGNERCORE_EXPORT QDebug operator<<(QDebug debug, const ModelNode &modelNode); - friend QMLDESIGNERCORE_EXPORT bool operator <(const ModelNode &firstNode, const ModelNode &secondNode); friend QMLDESIGNERCORE_EXPORT QList toInternalNodeList(const QList &nodeList); friend Model; friend AbstractView; @@ -77,7 +74,7 @@ public: NodeWithComponentSource = 2 }; - ModelNode(); + ModelNode() = default; ModelNode(const Internal::InternalNodePointer &internalNode, Model *model, const AbstractView *view); ModelNode(const ModelNode &modelNode, AbstractView *view); ModelNode(const ModelNode &) = default; @@ -176,7 +173,7 @@ public: void selectNode(); void deselectNode(); - static int variantUserType(); + static int variantTypeId(); QVariant toVariant() const; std::optional auxiliaryData(AuxiliaryDataKeyView key) const; @@ -254,6 +251,21 @@ public: friend auto qHash(const ModelNode &node) { return ::qHash(node.m_internalNode.get()); } + friend bool operator==(const ModelNode &firstNode, const ModelNode &secondNode) + { + return firstNode.m_internalNode == secondNode.m_internalNode; + } + + friend bool operator!=(const ModelNode &firstNode, const ModelNode &secondNode) + { + return !(firstNode == secondNode); + } + + friend bool operator<(const ModelNode &firstNode, const ModelNode &secondNode) + { + return firstNode.m_internalNode < secondNode.m_internalNode; + } + private: // functions Internal::InternalNodePointer internalNode() const; @@ -265,9 +277,6 @@ private: // variables QPointer m_view; }; -QMLDESIGNERCORE_EXPORT bool operator ==(const ModelNode &firstNode, const ModelNode &secondNode); -QMLDESIGNERCORE_EXPORT bool operator !=(const ModelNode &firstNode, const ModelNode &secondNode); -QMLDESIGNERCORE_EXPORT bool operator <(const ModelNode &firstNode, const ModelNode &secondNode); QMLDESIGNERCORE_EXPORT QDebug operator<<(QDebug debug, const ModelNode &modelNode); QMLDESIGNERCORE_EXPORT QTextStream& operator<<(QTextStream &stream, const ModelNode &modelNode); diff --git a/src/plugins/qmldesigner/designercore/include/nodeabstractproperty.h b/src/plugins/qmldesigner/designercore/include/nodeabstractproperty.h index d96840e51fa..f4db7339872 100644 --- a/src/plugins/qmldesigner/designercore/include/nodeabstractproperty.h +++ b/src/plugins/qmldesigner/designercore/include/nodeabstractproperty.h @@ -9,7 +9,7 @@ namespace QmlDesigner { namespace Internal { class InternalNodeAbstractProperty; - using InternalNodeAbstractPropertyPointer = QSharedPointer; + using InternalNodeAbstractPropertyPointer = std::shared_ptr; } class QMLDESIGNERCORE_EXPORT NodeAbstractProperty : public AbstractProperty diff --git a/src/plugins/qmldesigner/designercore/include/nodeinstanceview.h b/src/plugins/qmldesigner/designercore/include/nodeinstanceview.h index 93b4e82a2a2..fd7f21d090b 100644 --- a/src/plugins/qmldesigner/designercore/include/nodeinstanceview.h +++ b/src/plugins/qmldesigner/designercore/include/nodeinstanceview.h @@ -67,7 +67,8 @@ public: using Pointer = QWeakPointer; explicit NodeInstanceView(ConnectionManagerInterface &connectionManager, - ExternalDependenciesInterface &externalDependencies); + ExternalDependenciesInterface &externalDependencies, + bool qsbEnabled = false); ~NodeInstanceView() override; void modelAttached(Model *model) override; @@ -289,6 +290,7 @@ private: QTimer m_rotBlockTimer; QSize m_captureImageMinimumSize{150, 150}; QSize m_captureImageMaximumSize{1000, 1000}; + bool m_qsbEnabled = false; }; } // namespace ProxyNodeInstanceView diff --git a/src/plugins/qmldesigner/designercore/include/nodelistproperty.h b/src/plugins/qmldesigner/designercore/include/nodelistproperty.h index e0c25eb6c41..334a2a2758c 100644 --- a/src/plugins/qmldesigner/designercore/include/nodelistproperty.h +++ b/src/plugins/qmldesigner/designercore/include/nodelistproperty.h @@ -16,7 +16,7 @@ namespace QmlDesigner { namespace Internal { class ModelPrivate; class InternalNodeListProperty; -using InternalNodeListPropertyPointer = QSharedPointer; +using InternalNodeListPropertyPointer = std::shared_ptr; class NodeListPropertyIterator { diff --git a/src/plugins/qmldesigner/designercore/include/nodemetainfo.h b/src/plugins/qmldesigner/designercore/include/nodemetainfo.h index c7d1e2a342f..55ce166d904 100644 --- a/src/plugins/qmldesigner/designercore/include/nodemetainfo.h +++ b/src/plugins/qmldesigner/designercore/include/nodemetainfo.h @@ -14,6 +14,7 @@ #include #include +#include #include #include @@ -26,11 +27,12 @@ namespace QmlDesigner { class MetaInfo; class Model; class AbstractProperty; +class NodeMetaInfoPrivate; class QMLDESIGNERCORE_EXPORT NodeMetaInfo { public: - NodeMetaInfo() = default; + NodeMetaInfo(); NodeMetaInfo(Model *model, const TypeName &typeName, int majorVersion, int minorVersion); NodeMetaInfo(TypeId typeId, NotNullPointer projectStorage) : m_typeId{typeId} @@ -39,10 +41,17 @@ public: NodeMetaInfo(NotNullPointer projectStorage) : m_projectStorage{projectStorage} {} + + NodeMetaInfo(const NodeMetaInfo &); + NodeMetaInfo &operator=(const NodeMetaInfo &); + NodeMetaInfo(NodeMetaInfo &&); + NodeMetaInfo &operator=(NodeMetaInfo &&); ~NodeMetaInfo(); bool isValid() const; explicit operator bool() const { return isValid(); } + + TypeId id() const { return m_typeId; } bool isFileComponent() const; bool hasProperty(::Utils::SmallStringView propertyName) const; PropertyMetaInfos properties() const; @@ -197,7 +206,7 @@ private: TypeId m_typeId; NotNullPointer m_projectStorage = {}; mutable std::optional m_typeData; - QSharedPointer m_privateData; + std::shared_ptr m_privateData; }; using NodeMetaInfos = std::vector; diff --git a/src/plugins/qmldesigner/designercore/include/propertymetainfo.h b/src/plugins/qmldesigner/designercore/include/propertymetainfo.h index a3c928bc36f..99a704a4066 100644 --- a/src/plugins/qmldesigner/designercore/include/propertymetainfo.h +++ b/src/plugins/qmldesigner/designercore/include/propertymetainfo.h @@ -9,21 +9,22 @@ #include #include -#include #include +#include #include #include namespace QmlDesigner { class NodeMetaInfo; +class NodeMetaInfoPrivate; class QMLDESIGNERCORE_EXPORT PropertyMetaInfo { public: - PropertyMetaInfo() = default; - PropertyMetaInfo(QSharedPointer nodeMetaInfoPrivateData, + PropertyMetaInfo(); + PropertyMetaInfo(std::shared_ptr nodeMetaInfoPrivateData, const PropertyName &propertyName); PropertyMetaInfo([[maybe_unused]] PropertyDeclarationId id, [[maybe_unused]] NotNullPointer projectStorage) @@ -32,6 +33,10 @@ public: , m_id{id} #endif {} + PropertyMetaInfo(const PropertyMetaInfo &); + PropertyMetaInfo &operator=(const PropertyMetaInfo &); + PropertyMetaInfo(PropertyMetaInfo &&); + PropertyMetaInfo &operator=(PropertyMetaInfo &&); ~PropertyMetaInfo(); explicit operator bool() const { return isValid(); } @@ -44,6 +49,9 @@ public: return bool(m_nodeMetaInfoPrivateData); #endif } + + PropertyDeclarationId id() const { return m_id; } + PropertyName name() const; NodeMetaInfo propertyType() const; bool isWritable() const; @@ -74,7 +82,7 @@ private: mutable std::optional m_propertyData; PropertyDeclarationId m_id; #ifndef QDS_USE_PROJECTSTORAGE - QSharedPointer m_nodeMetaInfoPrivateData; + std::shared_ptr m_nodeMetaInfoPrivateData; PropertyName m_propertyName; #endif }; diff --git a/src/plugins/qmldesigner/designercore/include/propertynode.h b/src/plugins/qmldesigner/designercore/include/propertynode.h index 2489bac3c03..2df0b195a46 100644 --- a/src/plugins/qmldesigner/designercore/include/propertynode.h +++ b/src/plugins/qmldesigner/designercore/include/propertynode.h @@ -12,7 +12,7 @@ class QMLDESIGNERCORE_EXPORT PropertyNode // : public BaseModelNode public: PropertyNode(); -// static int variantUserType() { return qMetaTypeId(); } +// static int variantTypeId() { return qMetaTypeId(); } // static QVariant toVariant(const InternalNode::Pointer &internalNodePointer) { return QVariant::fromValue(internalNodePointer); } }; diff --git a/src/plugins/qmldesigner/designercore/include/qml3dnode.h b/src/plugins/qmldesigner/designercore/include/qml3dnode.h index ffcc2ea7ffe..280691c7a9f 100644 --- a/src/plugins/qmldesigner/designercore/include/qml3dnode.h +++ b/src/plugins/qmldesigner/designercore/include/qml3dnode.h @@ -25,14 +25,13 @@ class QMLDESIGNERCORE_EXPORT Qml3DNode : public QmlVisualNode public: Qml3DNode() : QmlVisualNode() {} Qml3DNode(const ModelNode &modelNode) : QmlVisualNode(modelNode) {} - bool isValid() const override; + bool isValid() const; + explicit operator bool() const { return isValid(); } static bool isValidQml3DNode(const ModelNode &modelNode); static bool isValidVisualRoot(const ModelNode &modelNode); - // From QmlObjectNode - void setVariantProperty(const PropertyName &name, const QVariant &value) override; - void setBindingProperty(const PropertyName &name, const QString &expression) override; - bool isBlocked(const PropertyName &propName) const override; + bool handleEulerRotation(const PropertyName &name); + bool isBlocked(const PropertyName &propName) const; friend auto qHash(const Qml3DNode &node) { return qHash(node.modelNode()); } diff --git a/src/plugins/qmldesigner/designercore/include/qmlchangeset.h b/src/plugins/qmldesigner/designercore/include/qmlchangeset.h index f7c6b8e56a2..67d7a910840 100644 --- a/src/plugins/qmldesigner/designercore/include/qmlchangeset.h +++ b/src/plugins/qmldesigner/designercore/include/qmlchangeset.h @@ -21,7 +21,7 @@ public: bool restoreEntryValues() const; void setRestoreEntryValues(bool value); QList targetProperties() const; - bool isValid() const override; + bool isValid() const; explicit operator bool() const { return isValid(); } static bool isValidQmlModelStateOperation(const ModelNode &modelNode); }; @@ -31,7 +31,7 @@ class QMLDESIGNERCORE_EXPORT QmlPropertyChanges : public QmlModelStateOperation public: QmlPropertyChanges() : QmlModelStateOperation() {} QmlPropertyChanges(const ModelNode &modelNode) : QmlModelStateOperation(modelNode) {} - bool isValid() const override; + bool isValid() const; explicit operator bool() const { return isValid(); } static bool isValidQmlPropertyChanges(const ModelNode &modelNode); void removeProperty(const PropertyName &name); diff --git a/src/plugins/qmldesigner/designercore/include/qmlconnections.h b/src/plugins/qmldesigner/designercore/include/qmlconnections.h index f8db7642b0f..5dfc33ce619 100644 --- a/src/plugins/qmldesigner/designercore/include/qmlconnections.h +++ b/src/plugins/qmldesigner/designercore/include/qmlconnections.h @@ -20,7 +20,8 @@ public: QmlConnections(); QmlConnections(const ModelNode &modelNode); - bool isValid() const override; + explicit operator bool() const { return isValid(); } + bool isValid() const; static bool isValidQmlConnections(const ModelNode &modelNode); void destroy(); diff --git a/src/plugins/qmldesigner/designercore/include/qmlitemnode.h b/src/plugins/qmldesigner/designercore/include/qmlitemnode.h index f95a97258bf..5816d60ce1b 100644 --- a/src/plugins/qmldesigner/designercore/include/qmlitemnode.h +++ b/src/plugins/qmldesigner/designercore/include/qmlitemnode.h @@ -27,7 +27,7 @@ class QMLDESIGNERCORE_EXPORT QmlItemNode : public QmlVisualNode public: QmlItemNode() = default; QmlItemNode(const ModelNode &modelNode) : QmlVisualNode(modelNode) {} - bool isValid() const override; + bool isValid() const; explicit operator bool() const { return isValid(); } static bool isValidQmlItemNode(const ModelNode &modelNode); @@ -84,7 +84,7 @@ public: bool instanceHasAnchors() const; bool instanceHasShowContent() const; - bool instanceCanReparent() const override; + bool instanceCanReparent() const; bool instanceIsAnchoredBySibling() const; bool instanceIsAnchoredByChildren() const; bool instanceIsMovable() const; @@ -149,7 +149,7 @@ class QMLDESIGNERCORE_EXPORT QmlFlowTargetNode final : public QmlItemNode { public: QmlFlowTargetNode(const ModelNode &modelNode) : QmlItemNode(modelNode) {} - bool isValid() const override; + bool isValid() const; explicit operator bool() const { return isValid(); } void assignTargetItem(const QmlFlowTargetNode &node); @@ -165,7 +165,7 @@ class QMLDESIGNERCORE_EXPORT QmlFlowActionAreaNode final : public QmlItemNode { public: QmlFlowActionAreaNode(const ModelNode &modelNode) : QmlItemNode(modelNode) {} - bool isValid() const override; + bool isValid() const; explicit operator bool() const { return isValid(); } static bool isValidQmlFlowActionAreaNode(const ModelNode &modelNode); ModelNode targetTransition() const; @@ -178,7 +178,7 @@ class QMLDESIGNERCORE_EXPORT QmlFlowItemNode final : public QmlItemNode { public: QmlFlowItemNode(const ModelNode &modelNode) : QmlItemNode(modelNode) {} - bool isValid() const override; + bool isValid() const; explicit operator bool() const { return isValid(); } static bool isValidQmlFlowItemNode(const ModelNode &modelNode); QList flowActionAreas() const; @@ -191,7 +191,7 @@ class QMLDESIGNERCORE_EXPORT QmlFlowViewNode final : public QmlItemNode { public: QmlFlowViewNode(const ModelNode &modelNode) : QmlItemNode(modelNode) {} - bool isValid() const override; + bool isValid() const; explicit operator bool() const { return isValid(); } static bool isValidQmlFlowViewNode(const ModelNode &modelNode); QList flowItems() const; diff --git a/src/plugins/qmldesigner/designercore/include/qmlmodelnodefacade.h b/src/plugins/qmldesigner/designercore/include/qmlmodelnodefacade.h index 27c4c86cc0b..0a81e00c904 100644 --- a/src/plugins/qmldesigner/designercore/include/qmlmodelnodefacade.h +++ b/src/plugins/qmldesigner/designercore/include/qmlmodelnodefacade.h @@ -4,7 +4,9 @@ #pragma once #include + #include +#include namespace QmlDesigner { @@ -14,27 +16,58 @@ class NodeInstanceView; class QMLDESIGNERCORE_EXPORT QmlModelNodeFacade { public: - QmlModelNodeFacade(const QmlModelNodeFacade &) = default; - QmlModelNodeFacade &operator=(const QmlModelNodeFacade &) = default; - QmlModelNodeFacade(QmlModelNodeFacade &&) noexcept = default; - QmlModelNodeFacade &operator=(QmlModelNodeFacade &&) noexcept = default; - virtual ~QmlModelNodeFacade() = default; operator ModelNode() const { return m_modelNode; } ModelNode modelNode() const { return m_modelNode; } bool hasModelNode() const; static bool isValidQmlModelNodeFacade(const ModelNode &modelNode); - virtual bool isValid() const; + bool isValid() const; explicit operator bool() const { return isValid(); } QmlModelNodeFacade() = default; AbstractView *view() const; Model *model() const; + NodeMetaInfo metaInfo() const { return m_modelNode.metaInfo(); } static const NodeInstanceView *nodeInstanceView(const ModelNode &modelNode); const NodeInstanceView *nodeInstanceView() const; bool isRootNode() const; static void enableUglyWorkaroundForIsValidQmlModelNodeFacadeInTests(); + friend bool operator==(const QmlModelNodeFacade &firstNode, const QmlModelNodeFacade &secondNode) + { + return firstNode.m_modelNode == secondNode.m_modelNode; + } + + friend bool operator==(const QmlModelNodeFacade &firstNode, const ModelNode &secondNode) + { + return firstNode.m_modelNode == secondNode; + } + + friend bool operator==(const ModelNode &firstNode, const QmlModelNodeFacade &secondNode) + { + return firstNode == secondNode.m_modelNode; + } + + friend bool operator!=(const QmlModelNodeFacade &firstNode, const QmlModelNodeFacade &secondNode) + { + return !(firstNode == secondNode); + } + + friend bool operator!=(const QmlModelNodeFacade &firstNode, const ModelNode &secondNode) + { + return firstNode.m_modelNode != secondNode; + } + + friend bool operator!=(const ModelNode &firstNode, const QmlModelNodeFacade &secondNode) + { + return firstNode != secondNode.m_modelNode; + } + + friend bool operator<(const QmlModelNodeFacade &firstNode, const QmlModelNodeFacade &secondNode) + { + return firstNode.m_modelNode < secondNode.m_modelNode; + } + protected: QmlModelNodeFacade(const ModelNode &modelNode) : m_modelNode(modelNode) diff --git a/src/plugins/qmldesigner/designercore/include/qmlobjectnode.h b/src/plugins/qmldesigner/designercore/include/qmlobjectnode.h index 1eea5063c99..eb652a4010f 100644 --- a/src/plugins/qmldesigner/designercore/include/qmlobjectnode.h +++ b/src/plugins/qmldesigner/designercore/include/qmlobjectnode.h @@ -32,7 +32,7 @@ public: virtual ~QmlObjectNode() = default; static bool isValidQmlObjectNode(const ModelNode &modelNode); - bool isValid() const override; + bool isValid() const; explicit operator bool() const { return isValid(); } bool hasError() const; @@ -52,8 +52,8 @@ public: QmlModelState currentState() const; QmlTimeline currentTimeline() const; - virtual void setVariantProperty(const PropertyName &name, const QVariant &value); - virtual void setBindingProperty(const PropertyName &name, const QString &expression); + void setVariantProperty(const PropertyName &name, const QVariant &value); + void setBindingProperty(const PropertyName &name, const QString &expression); NodeAbstractProperty nodeAbstractProperty(const PropertyName &name) const; NodeAbstractProperty defaultNodeAbstractProperty() const; NodeProperty nodeProperty(const PropertyName &name) const; @@ -76,7 +76,7 @@ public: bool timelineIsActive() const; QmlPropertyChanges propertyChangeForCurrentState() const; - virtual bool instanceCanReparent() const; + bool instanceCanReparent() const; bool isRootModelNode() const; @@ -114,10 +114,6 @@ public: QStringList allStateNames() const; - static QmlObjectNode *getQmlObjectNodeOfCorrectType(const ModelNode &modelNode); - - virtual bool isBlocked(const PropertyName &propName) const; - friend auto qHash(const QmlObjectNode &node) { return qHash(node.modelNode()); } QList allDefinedStates() const; QList allInvalidStateOperations() const; diff --git a/src/plugins/qmldesigner/designercore/include/qmlstate.h b/src/plugins/qmldesigner/designercore/include/qmlstate.h index c5ba5c89657..58515aff3b1 100644 --- a/src/plugins/qmldesigner/designercore/include/qmlstate.h +++ b/src/plugins/qmldesigner/designercore/include/qmlstate.h @@ -23,7 +23,6 @@ class StatesEditorView; class QMLDESIGNERCORE_EXPORT QmlModelState final : public QmlModelNodeFacade { friend StatesEditorView; - friend Experimental::StatesEditorView; public: QmlModelState(); @@ -45,7 +44,7 @@ public: QList allAffectedNodes() const; QString name() const; void setName(const QString &name); - bool isValid() const override; + bool isValid() const; explicit operator bool() const { return isValid(); } static bool isValidQmlModelState(const ModelNode &modelNode); void destroy(); diff --git a/src/plugins/qmldesigner/designercore/include/qmltimeline.h b/src/plugins/qmldesigner/designercore/include/qmltimeline.h index 26dc4721174..7a2809f5287 100644 --- a/src/plugins/qmldesigner/designercore/include/qmltimeline.h +++ b/src/plugins/qmldesigner/designercore/include/qmltimeline.h @@ -20,7 +20,7 @@ public: QmlTimeline(); QmlTimeline(const ModelNode &modelNode); - bool isValid() const override; + bool isValid() const; explicit operator bool() const { return isValid(); } static bool isValidQmlTimeline(const ModelNode &modelNode); void destroy(); diff --git a/src/plugins/qmldesigner/designercore/include/qmltimelinekeyframegroup.h b/src/plugins/qmldesigner/designercore/include/qmltimelinekeyframegroup.h index 76897b6235c..a319c5ac319 100644 --- a/src/plugins/qmldesigner/designercore/include/qmltimelinekeyframegroup.h +++ b/src/plugins/qmldesigner/designercore/include/qmltimelinekeyframegroup.h @@ -19,7 +19,7 @@ public: QmlTimelineKeyframeGroup(); QmlTimelineKeyframeGroup(const ModelNode &modelNode); - bool isValid() const override; + bool isValid() const; explicit operator bool() const { return isValid(); } static bool isValidQmlTimelineKeyframeGroup(const ModelNode &modelNode); void destroy(); diff --git a/src/plugins/qmldesigner/designercore/include/qmlvisualnode.h b/src/plugins/qmldesigner/designercore/include/qmlvisualnode.h index 6827243083d..69917dbc23b 100644 --- a/src/plugins/qmldesigner/designercore/include/qmlvisualnode.h +++ b/src/plugins/qmldesigner/designercore/include/qmlvisualnode.h @@ -48,7 +48,7 @@ public: QmlVisualNode() = default; QmlVisualNode(const ModelNode &modelNode) : QmlObjectNode(modelNode) {} - bool isValid() const override; + bool isValid() const; explicit operator bool() const { return isValid(); } static bool isValidQmlVisualNode(const ModelNode &modelNode); bool isRootNode() const; @@ -107,7 +107,6 @@ class QMLDESIGNERCORE_EXPORT QmlModelStateGroup { friend class QmlObjectNode; friend class StatesEditorView; - friend class Experimental::StatesEditorView; public: QmlModelStateGroup() = default; diff --git a/src/plugins/qmldesigner/designercore/include/stringutils.h b/src/plugins/qmldesigner/designercore/include/stringutils.h new file mode 100644 index 00000000000..38c3c260a97 --- /dev/null +++ b/src/plugins/qmldesigner/designercore/include/stringutils.h @@ -0,0 +1,42 @@ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +#pragma once + +#include + +namespace QmlDesigner { + +inline QString escape(const QString &value) +{ + QString result = value; + + if (value.length() == 6 && value.startsWith("\\u")) //Do not double escape unicode chars + return value; + + result.replace(QStringLiteral("\\"), QStringLiteral("\\\\")); + result.replace(QStringLiteral("\""), QStringLiteral("\\\"")); + result.replace(QStringLiteral("\t"), QStringLiteral("\\t")); + result.replace(QStringLiteral("\r"), QStringLiteral("\\r")); + result.replace(QStringLiteral("\n"), QStringLiteral("\\n")); + + return result; +} + +inline QString deescape(const QString &value) +{ + QString result = value; + + if (value.length() == 6 && value.startsWith("\\u")) //Ignore unicode chars + return value; + + result.replace(QStringLiteral("\\\\"), QStringLiteral("\\")); + result.replace(QStringLiteral("\\\""), QStringLiteral("\"")); + result.replace(QStringLiteral("\\t"), QStringLiteral("\t")); + result.replace(QStringLiteral("\\r"), QStringLiteral("\r")); + result.replace(QStringLiteral("\\n"), QStringLiteral("\n")); + + return result; +} + +} // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/designercore/instances/baseconnectionmanager.cpp b/src/plugins/qmldesigner/designercore/instances/baseconnectionmanager.cpp index 15f84e92c97..39da5f99ba7 100644 --- a/src/plugins/qmldesigner/designercore/instances/baseconnectionmanager.cpp +++ b/src/plugins/qmldesigner/designercore/instances/baseconnectionmanager.cpp @@ -107,8 +107,8 @@ void BaseConnectionManager::readDataStream(Connection &connection) connection.blockSize = 0; #ifdef NANOTRACE_ENABLED - if (command.userType() != QMetaType::type("PuppetAliveCommand")) { - if (command.userType() == QMetaType::type("SyncNanotraceCommand")) { + if (command.typeId() != QMetaType::type("PuppetAliveCommand")) { + if (command.typeId() == QMetaType::type("SyncNanotraceCommand")) { SyncNanotraceCommand cmd = command.value(); NANOTRACE_INSTANT_ARGS("Sync", "readCommand", {"name", cmd.name().toStdString()}, diff --git a/src/plugins/qmldesigner/designercore/instances/capturingconnectionmanager.cpp b/src/plugins/qmldesigner/designercore/instances/capturingconnectionmanager.cpp index b2b8f297f71..77b087e8c9e 100644 --- a/src/plugins/qmldesigner/designercore/instances/capturingconnectionmanager.cpp +++ b/src/plugins/qmldesigner/designercore/instances/capturingconnectionmanager.cpp @@ -55,7 +55,7 @@ void CapturingConnectionManager::writeCommand(const QVariant &command) InteractiveConnectionManager::writeCommand(command); if (m_captureFileForTest.isWritable()) { - qDebug() << "command name: " << QMetaType::typeName(command.userType()); + qDebug() << "command name: " << QMetaType::typeName(command.typeId()); writeCommandToIODevice(command, &m_captureFileForTest, writeCommandCounter()); qDebug() << "\tcatpure file offset: " << m_captureFileForTest.pos(); } diff --git a/src/plugins/qmldesigner/designercore/instances/interactiveconnectionmanager.cpp b/src/plugins/qmldesigner/designercore/instances/interactiveconnectionmanager.cpp index 33dad3c37df..cd36cac76da 100644 --- a/src/plugins/qmldesigner/designercore/instances/interactiveconnectionmanager.cpp +++ b/src/plugins/qmldesigner/designercore/instances/interactiveconnectionmanager.cpp @@ -70,7 +70,7 @@ void InteractiveConnectionManager::dispatchCommand(const QVariant &command, Conn { static const int puppetAliveCommandType = QMetaType::type("PuppetAliveCommand"); - if (command.userType() == puppetAliveCommandType) { + if (command.typeId() == puppetAliveCommandType) { puppetAlive(connection); } else { BaseConnectionManager::dispatchCommand(command, connection); diff --git a/src/plugins/qmldesigner/designercore/instances/nodeinstance.cpp b/src/plugins/qmldesigner/designercore/instances/nodeinstance.cpp index 7ed29063383..414a05683e3 100644 --- a/src/plugins/qmldesigner/designercore/instances/nodeinstance.cpp +++ b/src/plugins/qmldesigner/designercore/instances/nodeinstance.cpp @@ -296,7 +296,7 @@ QVariant NodeInstance::property(const PropertyName &name) const if (index != -1) { PropertyName parentPropName = name.left(index); QVariant varValue = d->propertyValues.value(parentPropName); - if (varValue.type() == QVariant::Vector2D) { + if (varValue.typeId() == QVariant::Vector2D) { auto value = varValue.value(); char subProp = name.right(1)[0]; float subValue = 0.f; @@ -312,7 +312,7 @@ QVariant NodeInstance::property(const PropertyName &name) const break; } return QVariant(subValue); - } else if (varValue.type() == QVariant::Vector3D) { + } else if (varValue.typeId() == QVariant::Vector3D) { auto value = varValue.value(); char subProp = name.right(1)[0]; float subValue = 0.f; @@ -331,7 +331,7 @@ QVariant NodeInstance::property(const PropertyName &name) const break; } return QVariant(subValue); - } else if (varValue.type() == QVariant::Vector4D) { + } else if (varValue.typeId() == QVariant::Vector4D) { auto value = varValue.value(); char subProp = name.right(1)[0]; float subValue = 0.f; @@ -417,9 +417,9 @@ void NodeInstance::setProperty(const PropertyName &name, const QVariant &value) QVariant oldValue = d->propertyValues.value(parentPropName); QVariant newValueVar; bool update = false; - if (oldValue.type() == QVariant::Vector2D) { + if (oldValue.typeId() == QVariant::Vector2D) { QVector2D newValue; - if (oldValue.type() == QVariant::Vector2D) + if (oldValue.typeId() == QVariant::Vector2D) newValue = oldValue.value(); if (name.endsWith(".x")) { newValue.setX(value.toFloat()); @@ -429,9 +429,9 @@ void NodeInstance::setProperty(const PropertyName &name, const QVariant &value) update = true; } newValueVar = newValue; - } else if (oldValue.type() == QVariant::Vector3D) { + } else if (oldValue.typeId() == QVariant::Vector3D) { QVector3D newValue; - if (oldValue.type() == QVariant::Vector3D) + if (oldValue.typeId() == QVariant::Vector3D) newValue = oldValue.value(); if (name.endsWith(".x")) { newValue.setX(value.toFloat()); @@ -444,9 +444,9 @@ void NodeInstance::setProperty(const PropertyName &name, const QVariant &value) update = true; } newValueVar = newValue; - } else if (oldValue.type() == QVariant::Vector4D) { + } else if (oldValue.typeId() == QVariant::Vector4D) { QVector4D newValue; - if (oldValue.type() == QVariant::Vector4D) + if (oldValue.typeId() == QVariant::Vector4D) newValue = oldValue.value(); if (name.endsWith(".x")) { newValue.setX(value.toFloat()); diff --git a/src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.cpp b/src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.cpp index 2893d0e1314..8b80a9c4af2 100644 --- a/src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.cpp +++ b/src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.cpp @@ -107,37 +107,38 @@ void NodeInstanceServerProxy::dispatchCommand(const QVariant &command) static const int puppetToCreatorCommandType = QMetaType::type("PuppetToCreatorCommand"); static const int SyncNanotraceCommandType = QMetaType::type("SyncNanotraceCommand"); - qCInfo(instanceViewBenchmark) << "dispatching command" << command.userType() << command.typeName(); - if (command.userType() == informationChangedCommandType) { + qCInfo(instanceViewBenchmark) << "dispatching command" << command.typeId() << command.typeName(); + if (command.typeId() == informationChangedCommandType) { nodeInstanceClient()->informationChanged(command.value()); - } else if (command.userType() == valuesChangedCommandType) { + } else if (command.typeId() == valuesChangedCommandType) { nodeInstanceClient()->valuesChanged(command.value()); - } else if (command.userType() == valuesModifiedCommandType) { + } else if (command.typeId() == valuesModifiedCommandType) { nodeInstanceClient()->valuesModified(command.value()); - } else if (command.userType() == pixmapChangedCommandType) { + } else if (command.typeId() == pixmapChangedCommandType) { nodeInstanceClient()->pixmapChanged(command.value()); - } else if (command.userType() == childrenChangedCommandType) { + } else if (command.typeId() == childrenChangedCommandType) { nodeInstanceClient()->childrenChanged(command.value()); - } else if (command.userType() == statePreviewImageChangedCommandType) { + } else if (command.typeId() == statePreviewImageChangedCommandType) { nodeInstanceClient()->statePreviewImagesChanged(command.value()); - } else if (command.userType() == componentCompletedCommandType) { + } else if (command.typeId() == componentCompletedCommandType) { nodeInstanceClient()->componentCompleted(command.value()); - } else if (command.userType() == tokenCommandType) { + } else if (command.typeId() == tokenCommandType) { nodeInstanceClient()->token(command.value()); - } else if (command.userType() == debugOutputCommandType) { + } else if (command.typeId() == debugOutputCommandType) { nodeInstanceClient()->debugOutput(command.value()); - } else if (command.userType() == changeSelectionCommandType) { + } else if (command.typeId() == changeSelectionCommandType) { nodeInstanceClient()->selectionChanged(command.value()); - } else if (command.userType() == puppetToCreatorCommandType) { + } else if (command.typeId() == puppetToCreatorCommandType) { nodeInstanceClient()->handlePuppetToCreatorCommand(command.value()); - } else if (command.userType() == SyncNanotraceCommandType) { + } else if (command.typeId() == SyncNanotraceCommandType) { // ignore. } else { QTC_ASSERT(false, ); Q_ASSERT(false); } - qCInfo(instanceViewBenchmark) << "dispatching command" << "done" << command.userType(); + qCInfo(instanceViewBenchmark) << "dispatching command" + << "done" << command.typeId(); } NodeInstanceClientInterface *NodeInstanceServerProxy::nodeInstanceClient() const @@ -173,7 +174,7 @@ QString NodeInstanceServerProxy::qrcMappingString() const void NodeInstanceServerProxy::writeCommand(const QVariant &command) { #ifdef NANOTRACE_ENABLED - if (command.userType() == QMetaType::type("SyncNanotraceCommand")) { + if (command.typeId() == QMetaType::type("SyncNanotraceCommand")) { SyncNanotraceCommand cmd = command.value(); NANOTRACE_INSTANT_ARGS("Sync", "writeCommand", {"name", cmd.name().toStdString()}, diff --git a/src/plugins/qmldesigner/designercore/instances/nodeinstanceview.cpp b/src/plugins/qmldesigner/designercore/instances/nodeinstanceview.cpp index 3befd6ec52c..fee28a9dd3a 100644 --- a/src/plugins/qmldesigner/designercore/instances/nodeinstanceview.cpp +++ b/src/plugins/qmldesigner/designercore/instances/nodeinstanceview.cpp @@ -124,13 +124,15 @@ namespace QmlDesigner { \sa ~NodeInstanceView, setRenderOffScreen() */ NodeInstanceView::NodeInstanceView(ConnectionManagerInterface &connectionManager, - ExternalDependenciesInterface &externalDependencies) + ExternalDependenciesInterface &externalDependencies, + bool qsbEnabled) : AbstractView{externalDependencies} , m_connectionManager(connectionManager) , m_externalDependencies(externalDependencies) , m_baseStatePreviewImage(QSize(100, 100), QImage::Format_ARGB32) , m_restartProcessTimerId(0) , m_fileSystemWatcher(new QFileSystemWatcher(this)) + , m_qsbEnabled(qsbEnabled) { m_baseStatePreviewImage.fill(0xFFFFFF); @@ -201,7 +203,7 @@ NodeInstanceView::~NodeInstanceView() //\{ -bool static isSkippedRootNode(const ModelNode &node) +static bool isSkippedRootNode(const ModelNode &node) { static const PropertyNameList skipList({"Qt.ListModel", "QtQuick.ListModel", "Qt.ListModel", "QtQuick.ListModel"}); @@ -211,8 +213,7 @@ bool static isSkippedRootNode(const ModelNode &node) return false; } - -bool static isSkippedNode(const ModelNode &node) +static bool isSkippedNode(const ModelNode &node) { static const PropertyNameList skipList({"QtQuick.XmlRole", "Qt.XmlRole", "QtQuick.ListElement", "Qt.ListElement"}); @@ -222,7 +223,7 @@ bool static isSkippedNode(const ModelNode &node) return false; } -bool static parentTakesOverRendering(const ModelNode &modelNode) +static bool parentTakesOverRendering(const ModelNode &modelNode) { ModelNode currentNode = modelNode; @@ -257,10 +258,7 @@ void NodeInstanceView::modelAttached(Model *model) activateState(newStateInstance); } - // If model gets attached on non-main thread of the application, do not attempt to monitor - // file changes. Such models are typically short lived for specific purpose, and timers - // will not work at all, if the thread is not based on QThread. - if (Utils::isMainThread()) { + if (m_qsbEnabled) { m_generateQsbFilesTimer.stop(); m_qsbTargets.clear(); updateQsbPathToFilterMap(); @@ -1463,10 +1461,10 @@ void NodeInstanceView::valuesModified(const ValuesModifiedCommand &command) if (hasInstanceForId(container.instanceId())) { NodeInstance instance = instanceForId(container.instanceId()); if (instance.isValid()) { - QScopedPointer node { - QmlObjectNode::getQmlObjectNodeOfCorrectType(instance.modelNode())}; - if (node->modelValue(container.name()) != container.value()) - node->setVariantProperty(container.name(), container.value()); + if (auto qmlObjectNode = QmlObjectNode(instance.modelNode())) { + if (qmlObjectNode.modelValue(container.name()) != container.value()) + qmlObjectNode.setVariantProperty(container.name(), container.value()); + } } } } @@ -1503,7 +1501,7 @@ void NodeInstanceView::pixmapChanged(const PixmapChangedCommand &command) } } - m_nodeInstanceServer->benchmark(Q_FUNC_INFO + QString::number(renderImageChangeSet.count())); + m_nodeInstanceServer->benchmark(Q_FUNC_INFO + QString::number(renderImageChangeSet.size())); if (!renderImageChangeSet.isEmpty()) emitInstancesRenderImageChanged(Utils::toList(renderImageChangeSet)); @@ -1542,7 +1540,7 @@ void NodeInstanceView::informationChanged(const InformationChangedCommand &comma QMultiHash informationChangeHash = informationChanged(command.informations()); - m_nodeInstanceServer->benchmark(Q_FUNC_INFO + QString::number(informationChangeHash.count())); + m_nodeInstanceServer->benchmark(Q_FUNC_INFO + QString::number(informationChangeHash.size())); if (!informationChangeHash.isEmpty()) emitInstanceInformationsChange(informationChangeHash); @@ -1615,7 +1613,7 @@ void NodeInstanceView::componentCompleted(const ComponentCompletedCommand &comma nodeVector.append(modelNodeForInternalId(instanceId)); } - m_nodeInstanceServer->benchmark(Q_FUNC_INFO + QString::number(nodeVector.count())); + m_nodeInstanceServer->benchmark(Q_FUNC_INFO + QString::number(nodeVector.size())); if (!nodeVector.isEmpty()) emitInstancesCompleted(nodeVector); diff --git a/src/plugins/qmldesigner/designercore/metainfo/metainfo.cpp b/src/plugins/qmldesigner/designercore/metainfo/metainfo.cpp index 144df144483..abecca1788a 100644 --- a/src/plugins/qmldesigner/designercore/metainfo/metainfo.cpp +++ b/src/plugins/qmldesigner/designercore/metainfo/metainfo.cpp @@ -128,8 +128,7 @@ void MetaInfoPrivate::parseItemLibraryDescriptions(const ExternalDependenciesInt Internal::MetaInfoReader reader(*m_q); try { reader.readMetaInfoFile(path.toString()); - } catch (const InvalidMetaInfoException &e) { - Q_UNUSED(e); + } catch ([[maybe_unused]] const InvalidMetaInfoException &e) { #ifndef UNIT_TESTS qWarning() << e.description(); const QString errorMessage = path.toString() + QLatin1Char('\n') + QLatin1Char('\n') diff --git a/src/plugins/qmldesigner/designercore/metainfo/metainforeader.cpp b/src/plugins/qmldesigner/designercore/metainfo/metainforeader.cpp index f418d003e10..a56221f6438 100644 --- a/src/plugins/qmldesigner/designercore/metainfo/metainforeader.cpp +++ b/src/plugins/qmldesigner/designercore/metainfo/metainforeader.cpp @@ -289,7 +289,7 @@ inline QString deEscape(const QString &value) inline QVariant deEscapeVariant(const QVariant &value) { - if (value.type() == QVariant::String) + if (value.typeId() == QVariant::String) return deEscape(value.toString()); return value; } diff --git a/src/plugins/qmldesigner/designercore/metainfo/nodehints.cpp b/src/plugins/qmldesigner/designercore/metainfo/nodehints.cpp index 0a4f84f3209..ece5b4bf6f1 100644 --- a/src/plugins/qmldesigner/designercore/metainfo/nodehints.cpp +++ b/src/plugins/qmldesigner/designercore/metainfo/nodehints.cpp @@ -266,7 +266,7 @@ QPair NodeHints::setParentProperty() const QStringList list = str.split(":"); - if (list.count() != 2) + if (list.size() != 2) return {}; return qMakePair(list.first().trimmed(), parseValue(list.last().trimmed())); diff --git a/src/plugins/qmldesigner/designercore/metainfo/nodemetainfo.cpp b/src/plugins/qmldesigner/designercore/metainfo/nodemetainfo.cpp index 7ca3aedff28..fd25d9c450d 100644 --- a/src/plugins/qmldesigner/designercore/metainfo/nodemetainfo.cpp +++ b/src/plugins/qmldesigner/designercore/metainfo/nodemetainfo.cpp @@ -336,7 +336,7 @@ private: const ContextPtr m_context; }; -static inline bool isValueType(const TypeName &type) +inline static bool isValueType(const TypeName &type) { static const PropertyTypeList objectValuesList({"QFont", "QPoint", @@ -356,7 +356,7 @@ static inline bool isValueType(const TypeName &type) return objectValuesList.contains(type); } -static inline bool isValueType(const QString &type) +inline static bool isValueType(const QString &type) { static const QStringList objectValuesList({"QFont", "QPoint", @@ -587,8 +587,11 @@ QVector getObjectTypes(const ObjectValue *objectValue, const Conte class NodeMetaInfoPrivate { public: - using Pointer = QSharedPointer; - NodeMetaInfoPrivate() = default; + using Pointer = std::shared_ptr; + NodeMetaInfoPrivate() = delete; + NodeMetaInfoPrivate(Model *model, TypeName type, int maj = -1, int min = -1); + NodeMetaInfoPrivate(const NodeMetaInfoPrivate &) = delete; + NodeMetaInfoPrivate &operator=(const NodeMetaInfoPrivate &) = delete; ~NodeMetaInfoPrivate() = default; bool isValid() const; @@ -621,13 +624,15 @@ public: QString componentFileName() const; QString importDirectoryPath() const; - static Pointer create(Model *model, const TypeName &type, int maj = -1, int min = -1); + static std::shared_ptr create(Model *model, + const TypeName &type, + int maj = -1, + int min = -1); QSet &prototypeCachePositives(); QSet &prototypeCacheNegatives(); private: - NodeMetaInfoPrivate(Model *model, TypeName type, int maj = -1, int min = -1); const CppComponentValue *getCppComponentValue() const; const ObjectValue *getObjectValue() const; @@ -713,20 +718,23 @@ PropertyName NodeMetaInfoPrivate::defaultPropertyName() const return PropertyName("data"); } -static inline TypeName stringIdentifier( const TypeName &type, int maj, int min) +inline static TypeName stringIdentifier(const TypeName &type, int maj, int min) { return type + QByteArray::number(maj) + '_' + QByteArray::number(min); } -NodeMetaInfoPrivate::Pointer NodeMetaInfoPrivate::create(Model *model, const TypeName &type, int major, int minor) +std::shared_ptr NodeMetaInfoPrivate::create(Model *model, + const TypeName &type, + int major, + int minor) { - auto &&cache = model->d->m_nodeMetaInfoCache; + auto &cache = model->d->nodeMetaInfoCache(); if (auto found = cache.find(stringIdentifier(type, major, minor)); found != cache.end()) return *found; - Pointer newData(new NodeMetaInfoPrivate(model, type, major, minor)); + auto newData = std::make_shared(model, type, major, minor); if (newData->isValid()) - model->d->m_nodeMetaInfoCache.insert(stringIdentifier(type, major, minor), newData); + cache.insert(stringIdentifier(type, major, minor), newData); return newData; } @@ -931,7 +939,7 @@ bool NodeMetaInfoPrivate::isPropertyWritable(const PropertyName &propertyName) c if (isValueType(objectType)) return true; - QSharedPointer objectInfo(create(m_model, objectType)); + auto objectInfo = create(m_model, objectType); if (objectInfo->isValid()) return objectInfo->isPropertyWritable(rawPropertyName); else @@ -947,7 +955,6 @@ bool NodeMetaInfoPrivate::isPropertyWritable(const PropertyName &propertyName) c return true; //all properties of components are writable } - bool NodeMetaInfoPrivate::isPropertyList(const PropertyName &propertyName) const { if (!isValid()) @@ -964,7 +971,7 @@ bool NodeMetaInfoPrivate::isPropertyList(const PropertyName &propertyName) const if (isValueType(objectType)) return false; - QSharedPointer objectInfo(create(m_model, objectType)); + auto objectInfo = create(m_model, objectType); if (objectInfo->isValid()) return objectInfo->isPropertyList(rawPropertyName); else @@ -999,7 +1006,7 @@ bool NodeMetaInfoPrivate::isPropertyPointer(const PropertyName &propertyName) co if (isValueType(objectType)) return false; - QSharedPointer objectInfo(create(m_model, objectType)); + auto objectInfo = create(m_model, objectType); if (objectInfo->isValid()) return objectInfo->isPropertyPointer(rawPropertyName); else @@ -1031,7 +1038,7 @@ bool NodeMetaInfoPrivate::isPropertyEnum(const PropertyName &propertyName) const if (isValueType(objectType)) return false; - QSharedPointer objectInfo(create(m_model, objectType)); + auto objectInfo = create(m_model, objectType); if (objectInfo->isValid()) return objectInfo->isPropertyEnum(rawPropertyName); else @@ -1157,7 +1164,6 @@ Model *NodeMetaInfoPrivate::model() const return m_model; } - QStringList NodeMetaInfoPrivate::keysForEnum(const QString &enumName) const { if (!isValid()) @@ -1245,7 +1251,6 @@ QStringList NodeMetaInfoPrivate::lookupNameComponent() const return tempString.split('.'); } - bool NodeMetaInfoPrivate::isValid() const { return m_isValid && context() && document(); @@ -1349,7 +1354,6 @@ void NodeMetaInfoPrivate::setupPrototypes() } } - QList NodeMetaInfoPrivate::prototypes() const { return m_prototypes; @@ -1393,6 +1397,12 @@ void NodeMetaInfoPrivate::initialiseProperties() m_slots = getSlots(m_objectValue, context()); } +NodeMetaInfo::NodeMetaInfo() = default; +NodeMetaInfo::NodeMetaInfo(const NodeMetaInfo &) = default; +NodeMetaInfo &NodeMetaInfo::operator=(const NodeMetaInfo &) = default; +NodeMetaInfo::NodeMetaInfo(NodeMetaInfo &&) = default; +NodeMetaInfo &NodeMetaInfo::operator=(NodeMetaInfo &&) = default; + NodeMetaInfo::NodeMetaInfo(Model *model, const TypeName &type, int maj, int min) : m_privateData(NodeMetaInfoPrivate::create(model, type, maj, min)) { @@ -1411,7 +1421,7 @@ bool NodeMetaInfo::isValid() const bool NodeMetaInfo::isFileComponent() const { if constexpr (useProjectStorage()) - return bool(typeData().traits & Storage::TypeTraits::IsFileComponent); + return isValid() && bool(typeData().traits & Storage::TypeTraits::IsFileComponent); else return isValid() && m_privateData->isFileComponent(); } @@ -1419,19 +1429,23 @@ bool NodeMetaInfo::isFileComponent() const bool NodeMetaInfo::hasProperty(Utils::SmallStringView propertyName) const { if constexpr (useProjectStorage()) - return bool(m_projectStorage->propertyDeclarationId(m_typeId, propertyName)); + return isValid() && bool(m_projectStorage->propertyDeclarationId(m_typeId, propertyName)); else return isValid() && m_privateData->properties().contains(propertyName); } PropertyMetaInfos NodeMetaInfo::properties() const { - if constexpr (useProjectStorage()) { - return Utils::transform( - m_projectStorage->propertyDeclarationIds(m_typeId), [&](auto id) { - return PropertyMetaInfo{id, m_projectStorage}; - }); + if (!isValid()) + return {}; + if constexpr (useProjectStorage()) { + if (isValid()) { + return Utils::transform( + m_projectStorage->propertyDeclarationIds(m_typeId), [&](auto id) { + return PropertyMetaInfo{id, m_projectStorage}; + }); + } } else { const auto &properties = m_privateData->properties(); @@ -1439,19 +1453,23 @@ PropertyMetaInfos NodeMetaInfo::properties() const propertyMetaInfos.reserve(static_cast(properties.size())); for (const auto &name : properties) - propertyMetaInfos.emplace_back(m_privateData, name); + propertyMetaInfos.push_back({m_privateData, name}); return propertyMetaInfos; } + + return {}; } PropertyMetaInfos NodeMetaInfo::localProperties() const { if constexpr (useProjectStorage()) { - return Utils::transform( - m_projectStorage->localPropertyDeclarationIds(m_typeId), [&](auto id) { - return PropertyMetaInfo{id, m_projectStorage}; - }); + if (isValid()) { + return Utils::transform( + m_projectStorage->localPropertyDeclarationIds(m_typeId), [&](auto id) { + return PropertyMetaInfo{id, m_projectStorage}; + }); + } } else { const auto &properties = m_privateData->localProperties(); @@ -1463,15 +1481,21 @@ PropertyMetaInfos NodeMetaInfo::localProperties() const return propertyMetaInfos; } + + return {}; } PropertyMetaInfo NodeMetaInfo::property(const PropertyName &propertyName) const { if constexpr (useProjectStorage()) { - return {m_projectStorage->propertyDeclarationId(m_typeId, propertyName), m_projectStorage}; + if (isValid()) { + return {m_projectStorage->propertyDeclarationId(m_typeId, propertyName), + m_projectStorage}; + } } else { - if (hasProperty(propertyName)) + if (hasProperty(propertyName)) { return PropertyMetaInfo{m_privateData, propertyName}; + } } return {}; @@ -1480,10 +1504,13 @@ PropertyMetaInfo NodeMetaInfo::property(const PropertyName &propertyName) const PropertyNameList NodeMetaInfo::signalNames() const { if constexpr (useProjectStorage()) { - return Utils::transform(m_projectStorage->signalDeclarationNames(m_typeId), - [&](const auto &name) { - return name.toQByteArray(); - }); + if (isValid()) { + return Utils::transform(m_projectStorage->signalDeclarationNames( + m_typeId), + [&](const auto &name) { + return name.toQByteArray(); + }); + } } else { if (isValid()) return m_privateData->signalNames(); @@ -1495,10 +1522,13 @@ PropertyNameList NodeMetaInfo::signalNames() const PropertyNameList NodeMetaInfo::slotNames() const { if constexpr (useProjectStorage()) { - return Utils::transform(m_projectStorage->functionDeclarationNames(m_typeId), - [&](const auto &name) { - return name.toQByteArray(); - }); + if (isValid()) { + return Utils::transform(m_projectStorage->functionDeclarationNames( + m_typeId), + [&](const auto &name) { + return name.toQByteArray(); + }); + } } else { if (isValid()) return m_privateData->slotNames(); @@ -1510,9 +1540,11 @@ PropertyNameList NodeMetaInfo::slotNames() const PropertyName NodeMetaInfo::defaultPropertyName() const { if constexpr (useProjectStorage()) { - if (auto name = m_projectStorage->propertyName(typeData().defaultPropertyId)) - return name->toQByteArray(); - return {}; + if (isValid()) { + if (auto name = m_projectStorage->propertyName(typeData().defaultPropertyId)) { + return name->toQByteArray(); + } + } } else { if (isValid()) return m_privateData->defaultPropertyName(); @@ -1524,10 +1556,14 @@ PropertyName NodeMetaInfo::defaultPropertyName() const PropertyMetaInfo NodeMetaInfo::defaultProperty() const { if constexpr (useProjectStorage()) { - return PropertyMetaInfo(typeData().defaultPropertyId, m_projectStorage); + if (isValid()) { + return PropertyMetaInfo(typeData().defaultPropertyId, m_projectStorage); + } } else { return property(defaultPropertyName()); } + + return {}; } bool NodeMetaInfo::hasDefaultProperty() const { @@ -2801,8 +2837,14 @@ bool NodeMetaInfo::isEnumeration() const return false; } +PropertyMetaInfo::PropertyMetaInfo() = default; +PropertyMetaInfo::PropertyMetaInfo(const PropertyMetaInfo &) = default; +PropertyMetaInfo &PropertyMetaInfo::operator=(const PropertyMetaInfo &) = default; +PropertyMetaInfo::PropertyMetaInfo(PropertyMetaInfo &&) = default; +PropertyMetaInfo &PropertyMetaInfo::operator=(PropertyMetaInfo &&) = default; + PropertyMetaInfo::PropertyMetaInfo( - [[maybe_unused]] QSharedPointer nodeMetaInfoPrivateData, + [[maybe_unused]] std::shared_ptr nodeMetaInfoPrivateData, [[maybe_unused]] const PropertyName &propertyName) #ifndef QDS_USE_PROJECTSTORAGE : m_nodeMetaInfoPrivateData{nodeMetaInfoPrivateData} @@ -2829,10 +2871,14 @@ NodeMetaInfo PropertyMetaInfo::propertyType() const PropertyName PropertyMetaInfo::name() const { - if constexpr (useProjectStorage()) - return PropertyName(Utils::SmallStringView(propertyData().name)); - else - return propertyName(); + if (isValid()) { + if constexpr (useProjectStorage()) + return PropertyName(Utils::SmallStringView(propertyData().name)); + else + return propertyName(); + } + + return {}; } bool PropertyMetaInfo::isWritable() const @@ -2890,8 +2936,7 @@ QVariant PropertyMetaInfo::castedValue(const QVariant &value) const QVariant::Type typeId = nodeMetaInfoPrivateData()->variantTypeId(propertyName()); - if (variant.type() == QVariant::UserType - && variant.userType() == ModelNode::variantUserType()) { + if (variant.typeId() == QVariant::UserType && variant.typeId() == ModelNode::variantTypeId()) { return variant; } else if (typeId == QVariant::UserType && typeName == "QVariant") { return variant; @@ -2899,7 +2944,7 @@ QVariant PropertyMetaInfo::castedValue(const QVariant &value) const return variant; } else if (typeId == QVariant::UserType && typeName == "var") { return variant; - } else if (variant.type() == QVariant::List) { + } else if (variant.typeId() == QVariant::List) { // TODO: check the contents of the list return variant; } else if (typeName == "var" || typeName == "variant") { @@ -2925,11 +2970,11 @@ QVariant PropertyMetaInfo::castedValue(const QVariant &value) const const TypeId &typeId = propertyData().typeId; - if (value.type() == QVariant::UserType && value.userType() == ModelNode::variantUserType()) { + if (value.typeId() == QVariant::UserType && value.typeId() == ModelNode::variantTypeId()) { return value; } else if (typeId == m_projectStorage->builtinTypeId()) { return value; - } else if (value.type() == QVariant::List) { + } else if (value.typeId() == QVariant::List) { // TODO: check the contents of the list return value; } else if (typeId == m_projectStorage->builtinTypeId()) { @@ -2983,7 +3028,7 @@ TypeName PropertyMetaInfo::propertyTypeName() const const NodeMetaInfoPrivate *PropertyMetaInfo::nodeMetaInfoPrivateData() const { #ifndef QDS_USE_PROJECTSTORAGE - return m_nodeMetaInfoPrivateData.data(); + return m_nodeMetaInfoPrivateData.get(); #else return nullptr; #endif diff --git a/src/plugins/qmldesigner/designercore/model/abstractproperty.cpp b/src/plugins/qmldesigner/designercore/model/abstractproperty.cpp index 00541e12e2f..e2e5800cab3 100644 --- a/src/plugins/qmldesigner/designercore/model/abstractproperty.cpp +++ b/src/plugins/qmldesigner/designercore/model/abstractproperty.cpp @@ -29,7 +29,6 @@ AbstractProperty::AbstractProperty(const PropertyName &propertyName, const Inter m_model(model), m_view(view) { - Q_ASSERT(!m_model || m_view); Q_ASSERT_X(!m_propertyName.contains(' '), Q_FUNC_INFO, "a property name cannot contain a space"); } @@ -52,11 +51,6 @@ AbstractProperty::AbstractProperty(const AbstractProperty &property, AbstractVie AbstractProperty::~AbstractProperty() = default; -Internal::InternalNodePointer AbstractProperty::internalNode() const -{ - return m_internalNode; -} - Internal::ModelPrivate *AbstractProperty::privateModel() const { return m_model ? m_model->d.get() : nullptr; @@ -296,6 +290,17 @@ bool AbstractProperty::isSignalDeclarationProperty() const return false; } +PropertyType AbstractProperty::type() const +{ + if (!isValid()) + return PropertyType::None; + + if (internalNode()->hasProperty(name())) + return internalNode()->property(name())->propertyType(); + + return PropertyType::None; +} + bool AbstractProperty::isBindingProperty() const { if (!isValid()) @@ -325,32 +330,13 @@ TypeName AbstractProperty::dynamicTypeName() const return TypeName(); } -/*! - Returns whether \a property1 and \a property2 reference the same property in - the same node. -*/ -bool operator ==(const AbstractProperty &property1, const AbstractProperty &property2) -{ - return (property1.m_model == property2.m_model) - && (property1.m_internalNode == property2.m_internalNode) - && (property1.m_propertyName == property2.m_propertyName); -} - -/*! - Returns whether \a property1 and \a property2 do not reference the same - property in the same node. - */ -bool operator !=(const AbstractProperty &property1, const AbstractProperty &property2) -{ - return !(property1 == property2); -} - QDebug operator<<(QDebug debug, const AbstractProperty &property) { - return debug.nospace() << "AbstractProperty(" << (property.isValid() ? property.name() : PropertyName("invalid")) << ')'; + return debug.nospace() << "AbstractProperty(" + << (property.isValid() ? property.name() : PropertyName("invalid")) << ')'; } -QTextStream& operator<<(QTextStream &stream, const AbstractProperty &property) +QTextStream &operator<<(QTextStream &stream, const AbstractProperty &property) { stream << "AbstractProperty(" << property.name() << ')'; @@ -358,4 +344,3 @@ QTextStream& operator<<(QTextStream &stream, const AbstractProperty &property) } } // namespace QmlDesigner - diff --git a/src/plugins/qmldesigner/designercore/model/abstractview.cpp b/src/plugins/qmldesigner/designercore/model/abstractview.cpp index 9967d49ee7b..a8ad4b76e7c 100644 --- a/src/plugins/qmldesigner/designercore/model/abstractview.cpp +++ b/src/plugins/qmldesigner/designercore/model/abstractview.cpp @@ -380,14 +380,16 @@ void AbstractView::dragEnded() {} QList AbstractView::toModelNodeList(const QList &nodeList) const { - return QmlDesigner::toModelNodeList(nodeList, const_cast(this)); + return QmlDesigner::toModelNodeList(nodeList, m_model, const_cast(this)); } -QList toModelNodeList(const QList &nodeList, AbstractView *view) +QList toModelNodeList(const QList &nodeList, + Model *model, + AbstractView *view) { QList newNodeList; for (const Internal::InternalNode::Pointer &node : nodeList) - newNodeList.append(ModelNode(node, view->model(), view)); + newNodeList.append(ModelNode(node, model, view)); return newNodeList; } @@ -438,7 +440,7 @@ bool AbstractView::hasSelectedModelNodes() const bool AbstractView::hasSingleSelectedModelNode() const { - return model()->d->selectedNodes().count() == 1; + return model()->d->selectedNodes().size() == 1; } bool AbstractView::isSelectedModelNode(const ModelNode &modelNode) const @@ -623,7 +625,12 @@ void AbstractView::setEnabled(bool b) QList AbstractView::allModelNodes() const { QTC_ASSERT(model(), return {}); - return toModelNodeList(model()->d->allNodes()); + return toModelNodeList(model()->d->allNodesOrdered()); +} + +QList AbstractView::allModelNodesUnordered() const +{ + return toModelNodeList(model()->d->allNodesUnordered()); } QList AbstractView::allModelNodesOfType(const NodeMetaInfo &type) const diff --git a/src/plugins/qmldesigner/designercore/model/bindingproperty.cpp b/src/plugins/qmldesigner/designercore/model/bindingproperty.cpp index 45d4e4cf20e..558f6849be2 100644 --- a/src/plugins/qmldesigner/designercore/model/bindingproperty.cpp +++ b/src/plugins/qmldesigner/designercore/model/bindingproperty.cpp @@ -7,6 +7,7 @@ #include "internalnode_p.h" #include "model.h" #include "model_p.h" + namespace QmlDesigner { bool compareBindingProperties(const QmlDesigner::BindingProperty &bindingProperty01, const QmlDesigner::BindingProperty &bindingProperty02) @@ -47,16 +48,15 @@ void BindingProperty::setExpression(const QString &expression) if (expression.isEmpty()) return; - if (internalNode()->hasProperty(name())) { //check if oldValue != value - Internal::InternalProperty::Pointer internalProperty = internalNode()->property(name()); - if (internalProperty->isBindingProperty() - && internalProperty->toBindingProperty()->expression() == expression) - + if (auto internalProperty = internalNode()->property(name())) { + auto bindingProperty = internalProperty->to(); + //check if oldValue != value + if (bindingProperty && bindingProperty->expression() == expression) return; - } - if (internalNode()->hasProperty(name()) && !internalNode()->property(name())->isBindingProperty()) - privateModel()->removePropertyAndRelatedResources(internalNode()->property(name())); + if (!bindingProperty) + privateModel()->removePropertyAndRelatedResources(internalProperty); + } privateModel()->setBindingProperty(internalNode(), name(), expression); } @@ -70,7 +70,7 @@ QString BindingProperty::expression() const return QString(); } -static ModelNode resolveBinding(const QString &binding, ModelNode currentNode, AbstractView* view) +ModelNode BindingProperty::resolveBinding(const QString &binding, ModelNode currentNode) const { int index = 0; QString element = binding.split(QLatin1Char('.')).at(0); @@ -85,16 +85,14 @@ static ModelNode resolveBinding(const QString &binding, ModelNode currentNode, A } else if (currentNode.hasProperty(element.toUtf8())) { if (currentNode.property(element.toUtf8()).isNodeProperty()) currentNode = currentNode.nodeProperty(element.toUtf8()).modelNode(); - else if (view->hasId(element)) - currentNode = view->modelNodeForId(element); //id else - return ModelNode(); //binding not valid + return ModelNode(privateModel()->nodeForId(element), model(), view()); } else { - currentNode = view->modelNodeForId(element); //id + currentNode = ModelNode(privateModel()->nodeForId(element), model(), view()); } index++; - if (index < binding.split(QLatin1Char('.')).count()) + if (index < binding.split(QLatin1Char('.')).size()) element = binding.split(QLatin1Char('.')).at(index); else element.clear(); @@ -111,10 +109,15 @@ ModelNode BindingProperty::resolveToModelNode() const if (!isValid()) return {}; - return resolveBinding(expression(), parentModelNode(), view()); + QString binding = expression(); + + if (binding.isEmpty()) + return {}; + + return resolveBinding(binding, parentModelNode()); } -static inline QStringList commaSeparatedSimplifiedStringList(const QString &string) +inline static QStringList commaSeparatedSimplifiedStringList(const QString &string) { const QStringList stringList = string.split(QStringLiteral(",")); QStringList simpleList; @@ -130,13 +133,17 @@ AbstractProperty BindingProperty::resolveToProperty() const return {}; QString binding = expression(); + + if (binding.isEmpty()) + return {}; + ModelNode node = parentModelNode(); QString element; if (binding.contains(QLatin1Char('.'))) { element = binding.split(QLatin1Char('.')).constLast(); QString nodeBinding = binding; nodeBinding.chop(element.length()); - node = resolveBinding(nodeBinding, parentModelNode(), view()); + node = resolveBinding(nodeBinding, parentModelNode()); } else { element = binding; } @@ -160,15 +167,19 @@ QList BindingProperty::resolveToModelNodeList() const if (!isValid()) return {}; + QString binding = expression(); + + if (binding.isEmpty()) + return {}; + QList returnList; if (isList()) { - QString string = expression(); - string.chop(1); - string.remove(0, 1); - const QStringList simplifiedList = commaSeparatedSimplifiedStringList(string); + binding.chop(1); + binding.remove(0, 1); + const QStringList simplifiedList = commaSeparatedSimplifiedStringList(binding); for (const QString &nodeId : simplifiedList) { - if (view()->hasId(nodeId)) - returnList.append(view()->modelNodeForId(nodeId)); + if (auto internalNode = privateModel()->nodeForId(nodeId)) + returnList.append(ModelNode{internalNode, model(), view()}); } } return returnList; @@ -262,11 +273,9 @@ bool BindingProperty::isAliasExport() const { if (!isValid()) return false; - return parentModelNode() == parentModelNode().view()->rootModelNode() - && isDynamic() - && dynamicTypeName() == "alias" - && name() == expression().toUtf8() - && parentModelNode().view()->modelNodeForId(expression()).isValid(); + return parentModelNode() == parentModelNode().model()->rootModelNode() && isDynamic() + && dynamicTypeName() == "alias" && name() == expression().toUtf8() + && parentModelNode().model()->modelNodeForId(expression()).isValid(); } static bool isTrueFalseLiteral(const QString &expression) @@ -330,20 +339,19 @@ void BindingProperty::setDynamicTypeNameAndExpression(const TypeName &typeName, if (typeName.isEmpty()) return; - if (internalNode()->hasProperty(name())) { //check if oldValue != value - Internal::InternalProperty::Pointer internalProperty = internalNode()->property(name()); - if (internalProperty->isBindingProperty() - && internalProperty->toBindingProperty()->expression() == expression - && internalProperty->toBindingProperty()->dynamicTypeName() == typeName) { - + if (auto internalProperty = internalNode()->property(name())) { + auto bindingProperty = internalProperty->to(); + //check if oldValue != value + if (bindingProperty && bindingProperty->expression() == expression + && internalProperty->dynamicTypeName() == typeName) { return; } + + if (!bindingProperty) + privateModel()->removePropertyAndRelatedResources(internalProperty); } - if (internalNode()->hasProperty(name()) && !internalNode()->property(name())->isBindingProperty()) - privateModel()->removePropertyAndRelatedResources(internalNode()->property(name())); - - privateModel()->setDynamicBindingProperty(internalNode(), name(), typeName, expression); + privateModel()->setDynamicBindingProperty(internalNode(), name(), typeName, expression); } QDebug operator<<(QDebug debug, const BindingProperty &property) diff --git a/src/plugins/qmldesigner/designercore/model/internalbindingproperty.cpp b/src/plugins/qmldesigner/designercore/model/internalbindingproperty.cpp index 28cd56a7904..6a3eee19753 100644 --- a/src/plugins/qmldesigner/designercore/model/internalbindingproperty.cpp +++ b/src/plugins/qmldesigner/designercore/model/internalbindingproperty.cpp @@ -6,22 +6,12 @@ namespace QmlDesigner { namespace Internal { -InternalBindingProperty::InternalBindingProperty(const PropertyName &name, const InternalNodePointer &propertyOwner) - : InternalProperty(name, propertyOwner) +InternalBindingProperty::InternalBindingProperty(const PropertyName &name, + const InternalNodePointer &propertyOwner) + : InternalProperty(name, propertyOwner, PropertyType::Binding) { } - -InternalBindingProperty::Pointer InternalBindingProperty::create(const PropertyName &name, const InternalNodePointer &propertyOwner) -{ - auto newPointer(new InternalBindingProperty(name, propertyOwner)); - InternalBindingProperty::Pointer smartPointer(newPointer); - - newPointer->setInternalWeakPointer(smartPointer); - - return smartPointer; -} - bool InternalBindingProperty::isValid() const { return InternalProperty::isValid() && isBindingProperty(); @@ -36,11 +26,6 @@ void InternalBindingProperty::setExpression(const QString &expression) m_expression = expression; } -bool InternalBindingProperty::isBindingProperty() const -{ - return true; -} - void InternalBindingProperty::setDynamicExpression(const TypeName &type, const QString &expression) { setExpression(expression); diff --git a/src/plugins/qmldesigner/designercore/model/internalbindingproperty.h b/src/plugins/qmldesigner/designercore/model/internalbindingproperty.h index 202434bec80..9ad0e19fc9e 100644 --- a/src/plugins/qmldesigner/designercore/model/internalbindingproperty.h +++ b/src/plugins/qmldesigner/designercore/model/internalbindingproperty.h @@ -11,9 +11,10 @@ namespace Internal { class InternalBindingProperty : public InternalProperty { public: - using Pointer = QSharedPointer; + using Pointer = std::shared_ptr; + static constexpr PropertyType type = PropertyType::Binding; - static Pointer create(const PropertyName &name, const InternalNodePointer &propertyOwner); + InternalBindingProperty(const PropertyName &name, const InternalNodePointer &propertyOwner); bool isValid() const override; @@ -22,11 +23,7 @@ public: void setDynamicExpression(const TypeName &type, const QString &expression); - - bool isBindingProperty() const override; - protected: - InternalBindingProperty(const PropertyName &name, const InternalNodePointer &propertyOwner); private: QString m_expression; diff --git a/src/plugins/qmldesigner/designercore/model/internalnode.cpp b/src/plugins/qmldesigner/designercore/model/internalnode.cpp index 003ab8d31cc..0c81d2ab28f 100644 --- a/src/plugins/qmldesigner/designercore/model/internalnode.cpp +++ b/src/plugins/qmldesigner/designercore/model/internalnode.cpp @@ -1,11 +1,14 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 +#include "internalbindingproperty.h" #include "internalnode_p.h" -#include "internalproperty.h" -#include "internalvariantproperty.h" -#include "internalnodeproperty.h" +#include "internalnodeabstractproperty.h" #include "internalnodelistproperty.h" +#include "internalnodeproperty.h" +#include "internalproperty.h" +#include "internalsignalhandlerproperty.h" +#include "internalvariantproperty.h" #include @@ -17,11 +20,11 @@ namespace Internal { InternalNodeAbstractProperty::Pointer InternalNode::parentProperty() const { - return m_parentProperty; + return m_parentProperty.lock(); } void InternalNode::setParentProperty(const InternalNodeAbstractProperty::Pointer &parent) { - InternalNodeAbstractProperty::Pointer parentProperty = m_parentProperty.toStrongRef(); + InternalNodeAbstractProperty::Pointer parentProperty = m_parentProperty.lock(); if (parentProperty) parentProperty->remove(shared_from_this()); @@ -33,11 +36,11 @@ void InternalNode::setParentProperty(const InternalNodeAbstractProperty::Pointer void InternalNode::resetParentProperty() { - InternalNodeAbstractProperty::Pointer parentProperty = m_parentProperty.toStrongRef(); + InternalNodeAbstractProperty::Pointer parentProperty = m_parentProperty.lock(); if (parentProperty) parentProperty->remove(shared_from_this()); - m_parentProperty.clear(); + m_parentProperty.reset(); } namespace { @@ -111,117 +114,10 @@ AuxiliaryDatasForType InternalNode::auxiliaryData(AuxiliaryDataType type) const return data; } -InternalProperty::Pointer InternalNode::property(const PropertyName &name) const -{ - return m_namePropertyHash.value(name); -} - -InternalBindingProperty::Pointer InternalNode::bindingProperty(const PropertyName &name) const -{ - InternalProperty::Pointer property = m_namePropertyHash.value(name); - if (property->isBindingProperty()) - return property.staticCast(); - - return InternalBindingProperty::Pointer(); -} - -InternalSignalHandlerProperty::Pointer InternalNode::signalHandlerProperty(const PropertyName &name) const -{ - InternalProperty::Pointer property = m_namePropertyHash.value(name); - if (property->isSignalHandlerProperty()) - return property.staticCast(); - - return InternalSignalHandlerProperty::Pointer(); -} - -InternalSignalDeclarationProperty::Pointer InternalNode::signalDeclarationProperty(const PropertyName &name) const -{ - InternalProperty::Pointer property = m_namePropertyHash.value(name); - if (property->isSignalDeclarationProperty()) - return property.staticCast(); - - return InternalSignalDeclarationProperty::Pointer(); -} - -InternalVariantProperty::Pointer InternalNode::variantProperty(const PropertyName &name) const -{ - InternalProperty::Pointer property = m_namePropertyHash.value(name); - if (property->isVariantProperty()) - return property.staticCast(); - - return InternalVariantProperty::Pointer(); -} - -void InternalNode::addBindingProperty(const PropertyName &name) -{ - InternalProperty::Pointer newProperty(InternalBindingProperty::create(name, shared_from_this())); - m_namePropertyHash.insert(name, newProperty); -} - -void InternalNode::addSignalHandlerProperty(const PropertyName &name) -{ - InternalProperty::Pointer newProperty( - InternalSignalHandlerProperty::create(name, shared_from_this())); - m_namePropertyHash.insert(name, newProperty); -} - -void InternalNode::addSignalDeclarationProperty(const PropertyName &name) -{ - InternalProperty::Pointer newProperty( - InternalSignalDeclarationProperty::create(name, shared_from_this())); - m_namePropertyHash.insert(name, newProperty); -} - -InternalNodeListProperty::Pointer InternalNode::nodeListProperty(const PropertyName &name) const -{ - InternalProperty::Pointer property = m_namePropertyHash.value(name); - if (property && property->isNodeListProperty()) - return property.staticCast(); - - return InternalNodeListProperty::Pointer(); -} - -InternalNodeAbstractProperty::Pointer InternalNode::nodeAbstractProperty(const PropertyName &name) const -{ - InternalProperty::Pointer property = m_namePropertyHash.value(name); - if (property && property->isNodeAbstractProperty()) - return property.staticCast(); - - return InternalNodeProperty::Pointer(); -} - -InternalNodeProperty::Pointer InternalNode::nodeProperty(const PropertyName &name) const -{ - InternalProperty::Pointer property = m_namePropertyHash.value(name); - if (property->isNodeProperty()) - return property.staticCast(); - - return InternalNodeProperty::Pointer(); -} - -void InternalNode::addVariantProperty(const PropertyName &name) -{ - InternalProperty::Pointer newProperty(InternalVariantProperty::create(name, shared_from_this())); - m_namePropertyHash.insert(name, newProperty); -} - -void InternalNode::addNodeProperty(const PropertyName &name, const TypeName &dynamicTypeName) -{ - InternalNodeProperty::Pointer newProperty(InternalNodeProperty::create(name, shared_from_this())); - newProperty->setDynamicTypeName(dynamicTypeName); - m_namePropertyHash.insert(name, newProperty); -} - -void InternalNode::addNodeListProperty(const PropertyName &name) -{ - InternalProperty::Pointer newProperty(InternalNodeListProperty::create(name, shared_from_this())); - m_namePropertyHash.insert(name, newProperty); -} - void InternalNode::removeProperty(const PropertyName &name) { InternalProperty::Pointer property = m_namePropertyHash.take(name); - Q_ASSERT(!property.isNull()); + Q_ASSERT(property); } PropertyNameList InternalNode::propertyNameList() const @@ -250,13 +146,12 @@ QList InternalNode::nodeAbstractPropertyL const QList properties = propertyList(); for (const InternalProperty::Pointer &property : properties) { if (property->isNodeAbstractProperty()) - abstractPropertyList.append(property->toNodeAbstractProperty()); + abstractPropertyList.append(property->toProperty()); } return abstractPropertyList; } - QList InternalNode::allSubNodes() const { QList nodeList; @@ -280,4 +175,4 @@ QList InternalNode::allDirectSubNodes() const } } // namespace Internal -} +} // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/designercore/model/internalnode_p.h b/src/plugins/qmldesigner/designercore/model/internalnode_p.h index ddcb3c9cbb6..8b3ff86d2bc 100644 --- a/src/plugins/qmldesigner/designercore/model/internalnode_p.h +++ b/src/plugins/qmldesigner/designercore/model/internalnode_p.h @@ -34,7 +34,7 @@ class InternalProperty; class InternalNode; using InternalNodePointer = std::shared_ptr; -using InternalPropertyPointer = QSharedPointer; +using InternalPropertyPointer = std::shared_ptr; class InternalNode : public std::enable_shared_from_this { @@ -44,8 +44,6 @@ public: using Pointer = std::shared_ptr; using WeakPointer = std::weak_ptr; - explicit InternalNode() = default; - explicit InternalNode(TypeName typeName, int majorVersion, int minorVersion, qint32 internalId) : typeName(std::move(typeName)) , majorVersion(majorVersion) @@ -67,21 +65,101 @@ public: AuxiliaryDatasForType auxiliaryData(AuxiliaryDataType type) const; AuxiliaryDatasView auxiliaryData() const { return std::as_const(m_auxiliaryDatas); } - InternalProperty::Pointer property(const PropertyName &name) const; - InternalBindingProperty::Pointer bindingProperty(const PropertyName &name) const; - InternalSignalHandlerProperty::Pointer signalHandlerProperty(const PropertyName &name) const; - InternalSignalDeclarationProperty::Pointer signalDeclarationProperty(const PropertyName &name) const; - InternalVariantProperty::Pointer variantProperty(const PropertyName &name) const; - InternalNodeListProperty::Pointer nodeListProperty(const PropertyName &name) const; - InternalNodeAbstractProperty::Pointer nodeAbstractProperty(const PropertyName &name) const; - InternalNodeProperty::Pointer nodeProperty(const PropertyName &name) const; + template + typename Type::Pointer property(const PropertyName &name) const + { + auto property = m_namePropertyHash.value(name); + if (property && property->propertyType() == Type::type) + return std::static_pointer_cast(property); - void addBindingProperty(const PropertyName &name); - void addSignalHandlerProperty(const PropertyName &name); - void addSignalDeclarationProperty(const PropertyName &name); - void addNodeListProperty(const PropertyName &name); - void addVariantProperty(const PropertyName &name); - void addNodeProperty(const PropertyName &name, const TypeName &dynamicTypeName); + return {}; + } + + InternalProperty::Pointer property(const PropertyName &name) const + { + return m_namePropertyHash.value(name); + } + + auto bindingProperty(const PropertyName &name) const + { + return property(name); + } + + auto signalHandlerProperty(const PropertyName &name) const + { + return property(name); + } + + auto signalDeclarationProperty(const PropertyName &name) const + { + return property(name); + } + + auto variantProperty(const PropertyName &name) const + { + return property(name); + } + + auto nodeListProperty(const PropertyName &name) const + { + return property(name); + } + + InternalNodeAbstractProperty::Pointer nodeAbstractProperty(const PropertyName &name) const + { + auto property = m_namePropertyHash.value(name); + if (property + && (property->propertyType() == PropertyType::NodeList + || property->propertyType() == PropertyType::Node)) { + return std::static_pointer_cast(property); + } + return {}; + } + + InternalNodeProperty::Pointer nodeProperty(const PropertyName &name) const + { + return property(name); + } + + template + auto &addProperty(const PropertyName &name) + { + auto newProperty = std::make_shared(name, shared_from_this()); + auto inserted = m_namePropertyHash.insert(name, std::move(newProperty)); + + return *inserted->get(); + } + + void addBindingProperty(const PropertyName &name) + { + addProperty(name); + } + + void addSignalHandlerProperty(const PropertyName &name) + { + addProperty(name); + } + + void addSignalDeclarationProperty(const PropertyName &name) + { + addProperty(name); + } + + void addNodeListProperty(const PropertyName &name) + { + addProperty(name); + } + + void addVariantProperty(const PropertyName &name) + { + addProperty(name); + } + + void addNodeProperty(const PropertyName &name, const TypeName &dynamicTypeName) + { + auto &property = addProperty(name); + property.setDynamicTypeName(dynamicTypeName); + } PropertyNameList propertyNameList() const; @@ -105,13 +183,7 @@ public: return firstNode->internalId < secondNode->internalId; } - friend size_t qHash(const InternalNodePointer &node) - { - if (!node) - return ::qHash(-1); - - return ::qHash(node->internalId); - } + friend size_t qHash(const InternalNodePointer &node) { return ::qHash(node.get()); } protected: void removeProperty(const PropertyName &name); diff --git a/src/plugins/qmldesigner/designercore/model/internalnodeabstractproperty.cpp b/src/plugins/qmldesigner/designercore/model/internalnodeabstractproperty.cpp index e2b753604f7..6dff33436e4 100644 --- a/src/plugins/qmldesigner/designercore/model/internalnodeabstractproperty.cpp +++ b/src/plugins/qmldesigner/designercore/model/internalnodeabstractproperty.cpp @@ -7,16 +7,13 @@ namespace QmlDesigner { namespace Internal { -InternalNodeAbstractProperty::InternalNodeAbstractProperty(const PropertyName &name, const InternalNode::Pointer &propertyOwner) - : InternalProperty(name, propertyOwner) +InternalNodeAbstractProperty::InternalNodeAbstractProperty(const PropertyName &name, + const InternalNode::Pointer &propertyOwner, + PropertyType propertyType) + : InternalProperty(name, propertyOwner, propertyType) { } -bool InternalNodeAbstractProperty::isNodeAbstractProperty() const -{ - return true; -} - bool InternalNodeAbstractProperty::isValid() const { return InternalProperty::isValid() && isNodeAbstractProperty(); diff --git a/src/plugins/qmldesigner/designercore/model/internalnodeabstractproperty.h b/src/plugins/qmldesigner/designercore/model/internalnodeabstractproperty.h index 7867025da9b..72e01d019b2 100644 --- a/src/plugins/qmldesigner/designercore/model/internalnodeabstractproperty.h +++ b/src/plugins/qmldesigner/designercore/model/internalnodeabstractproperty.h @@ -14,10 +14,8 @@ class InternalNodeAbstractProperty : public InternalProperty friend InternalNode; public: - using Pointer = QSharedPointer; - using WeakPointer = QWeakPointer; - - bool isNodeAbstractProperty() const override; + using Pointer = std::shared_ptr; + using WeakPointer = std::weak_ptr; virtual QList allSubNodes() const = 0; virtual QList directSubNodes() const = 0; @@ -31,7 +29,9 @@ public: using InternalProperty::remove; // keep the virtual remove(...) function around protected: - InternalNodeAbstractProperty(const PropertyName &name, const InternalNodePointer &propertyOwner); + InternalNodeAbstractProperty(const PropertyName &name, + const InternalNodePointer &propertyOwner, + PropertyType propertyType); virtual void remove(const InternalNodePointer &node) = 0; virtual void add(const InternalNodePointer &node) = 0; }; diff --git a/src/plugins/qmldesigner/designercore/model/internalnodelistproperty.cpp b/src/plugins/qmldesigner/designercore/model/internalnodelistproperty.cpp index e47b8588ccd..f5c46627856 100644 --- a/src/plugins/qmldesigner/designercore/model/internalnodelistproperty.cpp +++ b/src/plugins/qmldesigner/designercore/model/internalnodelistproperty.cpp @@ -8,21 +8,12 @@ namespace QmlDesigner { namespace Internal { -InternalNodeListProperty::InternalNodeListProperty(const PropertyName &name, const InternalNodePointer &propertyOwner) - : InternalNodeAbstractProperty(name, propertyOwner) +InternalNodeListProperty::InternalNodeListProperty(const PropertyName &name, + const InternalNodePointer &propertyOwner) + : InternalNodeAbstractProperty(name, propertyOwner, PropertyType::NodeList) { } -InternalNodeListProperty::Pointer InternalNodeListProperty::create(const PropertyName &name, const InternalNodePointer &propertyOwner) -{ - auto newPointer(new InternalNodeListProperty(name, propertyOwner)); - InternalProperty::Pointer smartPointer(newPointer); - - newPointer->setInternalWeakPointer(smartPointer.toWeakRef()); - - return smartPointer.staticCast(); -} - bool InternalNodeListProperty::isValid() const { return InternalProperty::isValid() && isNodeListProperty(); @@ -35,7 +26,7 @@ bool InternalNodeListProperty::isEmpty() const int InternalNodeListProperty::count() const { - return m_nodeList.count(); + return m_nodeList.size(); } int InternalNodeListProperty::indexOf(const InternalNode::Pointer &node) const @@ -46,11 +37,6 @@ int InternalNodeListProperty::indexOf(const InternalNode::Pointer &node) const return m_nodeList.indexOf(node); } -bool InternalNodeListProperty::isNodeListProperty() const -{ - return true; -} - void InternalNodeListProperty::add(const InternalNode::Pointer &internalNode) { Q_ASSERT(!m_nodeList.contains(internalNode)); diff --git a/src/plugins/qmldesigner/designercore/model/internalnodelistproperty.h b/src/plugins/qmldesigner/designercore/model/internalnodelistproperty.h index 7f4dced451b..2e15fdf8aef 100644 --- a/src/plugins/qmldesigner/designercore/model/internalnodelistproperty.h +++ b/src/plugins/qmldesigner/designercore/model/internalnodelistproperty.h @@ -14,9 +14,10 @@ namespace Internal { class InternalNodeListProperty final : public InternalNodeAbstractProperty { public: - using Pointer = QSharedPointer; + using Pointer = std::shared_ptr; + static constexpr PropertyType type = PropertyType::NodeList; - static Pointer create(const PropertyName &name, const InternalNodePointer &propertyOwner); + InternalNodeListProperty(const PropertyName &name, const InternalNodePointer &propertyOwner); bool isValid() const override; @@ -26,13 +27,13 @@ public: int indexOf(const InternalNodePointer &node) const override; const InternalNodePointer &at(int index) const { - Q_ASSERT(index >= 0 && index < m_nodeList.count()); + Q_ASSERT(index >= 0 && index < m_nodeList.size()); return m_nodeList[index]; } InternalNodePointer &at(int index) { - Q_ASSERT(index >= 0 && index < m_nodeList.count()); + Q_ASSERT(index >= 0 && index < m_nodeList.size()); return m_nodeList[index]; } @@ -43,8 +44,6 @@ public: return *found; } - bool isNodeListProperty() const override; - QList allSubNodes() const override; QList directSubNodes() const override; const QList &nodeList() const; @@ -54,7 +53,6 @@ public: QList::iterator end() { return m_nodeList.end(); } protected: - InternalNodeListProperty(const PropertyName &name, const InternalNodePointer &propertyOwner); void add(const InternalNodePointer &node) override; void remove(const InternalNodePointer &node) override; diff --git a/src/plugins/qmldesigner/designercore/model/internalnodeproperty.cpp b/src/plugins/qmldesigner/designercore/model/internalnodeproperty.cpp index 508a3d75db7..0dd286e765e 100644 --- a/src/plugins/qmldesigner/designercore/model/internalnodeproperty.cpp +++ b/src/plugins/qmldesigner/designercore/model/internalnodeproperty.cpp @@ -7,21 +7,12 @@ namespace QmlDesigner { namespace Internal { -InternalNodeProperty::InternalNodeProperty(const PropertyName &name, const InternalNode::Pointer &propertyOwner) - : InternalNodeAbstractProperty(name, propertyOwner) +InternalNodeProperty::InternalNodeProperty(const PropertyName &name, + const InternalNode::Pointer &propertyOwner) + : InternalNodeAbstractProperty(name, propertyOwner, PropertyType::Node) { } -InternalNodeProperty::Pointer InternalNodeProperty::create(const PropertyName &name, const InternalNode::Pointer &propertyOwner) -{ - auto newPointer = new InternalNodeProperty(name, propertyOwner); - InternalNodeProperty::Pointer smartPointer(newPointer); - - newPointer->setInternalWeakPointer(smartPointer); - - return smartPointer; -} - bool InternalNodeProperty::isEmpty() const { return !m_node; @@ -48,11 +39,6 @@ bool InternalNodeProperty::isValid() const return InternalProperty::isValid() && isNodeProperty(); } -bool InternalNodeProperty::isNodeProperty() const -{ - return true; -} - InternalNode::Pointer InternalNodeProperty::node() const { return m_node; diff --git a/src/plugins/qmldesigner/designercore/model/internalnodeproperty.h b/src/plugins/qmldesigner/designercore/model/internalnodeproperty.h index 905a3eccfe0..65b9b895e8a 100644 --- a/src/plugins/qmldesigner/designercore/model/internalnodeproperty.h +++ b/src/plugins/qmldesigner/designercore/model/internalnodeproperty.h @@ -11,24 +11,22 @@ namespace Internal { class InternalNodeProperty : public InternalNodeAbstractProperty { public: - using Pointer = QSharedPointer; + using Pointer = std::shared_ptr; + static constexpr PropertyType type = PropertyType::Node; - static Pointer create(const PropertyName &name, const InternalNodePointer &propertyOwner); + InternalNodeProperty(const PropertyName &name, const InternalNodePointer &node); bool isValid() const override; bool isEmpty() const override; int count() const override; int indexOf(const InternalNodePointer &node) const override; - bool isNodeProperty() const override; QList allSubNodes() const override; QList directSubNodes() const override; InternalNodePointer node() const; - protected: - InternalNodeProperty(const PropertyName &name, const InternalNodePointer &node); void add(const InternalNodePointer &node) override; void remove(const InternalNodePointer &node) override; diff --git a/src/plugins/qmldesigner/designercore/model/internalproperty.cpp b/src/plugins/qmldesigner/designercore/model/internalproperty.cpp index 8b15b1f7777..076c14fa9b6 100644 --- a/src/plugins/qmldesigner/designercore/model/internalproperty.cpp +++ b/src/plugins/qmldesigner/designercore/model/internalproperty.cpp @@ -18,26 +18,15 @@ InternalProperty::InternalProperty() = default; InternalProperty::~InternalProperty() = default; -InternalProperty::InternalProperty(const PropertyName &name, const InternalNode::Pointer &propertyOwner) - : m_name(name), - m_propertyOwner(propertyOwner) +InternalProperty::InternalProperty(const PropertyName &name, + const InternalNode::Pointer &propertyOwner, + PropertyType propertyType) + : m_name(name) + , m_propertyOwner(propertyOwner) + , m_propertyType{propertyType} { - Q_ASSERT_X(!name.isEmpty(), Q_FUNC_INFO, "Name of property cannot be empty"); } -InternalProperty::Pointer InternalProperty::internalPointer() const -{ - Q_ASSERT(!m_internalPointer.isNull()); - return m_internalPointer.toStrongRef(); -} - -void InternalProperty::setInternalWeakPointer(const Pointer &pointer) -{ - Q_ASSERT(!pointer.isNull()); - m_internalPointer = pointer; -} - - bool InternalProperty::isValid() const { return !m_propertyOwner.expired() && !m_name.isEmpty(); @@ -48,90 +37,11 @@ PropertyName InternalProperty::name() const return m_name; } -bool InternalProperty::isBindingProperty() const -{ - return false; -} - -bool InternalProperty::isVariantProperty() const -{ - return false; -} - -QSharedPointer InternalProperty::toBindingProperty() const -{ - Q_ASSERT(internalPointer().dynamicCast()); - return internalPointer().staticCast(); -} - - -bool InternalProperty::isNodeListProperty() const -{ - return false; -} - -bool InternalProperty::isNodeProperty() const -{ - return false; -} - -bool InternalProperty::isNodeAbstractProperty() const -{ - return false; -} - -bool InternalProperty::isSignalHandlerProperty() const -{ - return false; -} - -bool InternalProperty::isSignalDeclarationProperty() const -{ - return false; -} - -QSharedPointer InternalProperty::toVariantProperty() const - -{ - Q_ASSERT(internalPointer().dynamicCast()); - return internalPointer().staticCast(); -} - InternalNode::Pointer InternalProperty::propertyOwner() const { return m_propertyOwner.lock(); } -QSharedPointer InternalProperty::toNodeListProperty() const -{ - Q_ASSERT(internalPointer().dynamicCast()); - return internalPointer().staticCast(); -} - -QSharedPointer InternalProperty::toNodeProperty() const -{ - Q_ASSERT(internalPointer().dynamicCast()); - return internalPointer().staticCast(); -} - -QSharedPointer InternalProperty::toNodeAbstractProperty() const -{ - Q_ASSERT(internalPointer().dynamicCast()); - return internalPointer().staticCast(); -} - -QSharedPointer InternalProperty::toSignalHandlerProperty() const -{ - Q_ASSERT(internalPointer().dynamicCast()); - return internalPointer().staticCast(); -} - -QSharedPointer InternalProperty::toSignalDeclarationProperty() const -{ - Q_ASSERT(internalPointer().dynamicCast()); - return internalPointer().staticCast(); -} - void InternalProperty::remove() { propertyOwner()->removeProperty(name()); @@ -148,7 +58,6 @@ void InternalProperty::setDynamicTypeName(const TypeName &name) m_dynamicType = name; } - void InternalProperty::resetDynamicTypeName() { m_dynamicType.clear(); diff --git a/src/plugins/qmldesigner/designercore/model/internalproperty.h b/src/plugins/qmldesigner/designercore/model/internalproperty.h index 2038fb40e53..1f24b825093 100644 --- a/src/plugins/qmldesigner/designercore/model/internalproperty.h +++ b/src/plugins/qmldesigner/designercore/model/internalproperty.h @@ -6,7 +6,6 @@ #include "qmldesignercorelib_global.h" #include -#include #include @@ -25,10 +24,55 @@ class InternalNode; using InternalNodePointer = std::shared_ptr; -class QMLDESIGNERCORE_EXPORT InternalProperty +template +struct TypeLookup +{}; + +template<> +struct TypeLookup +{ + using Type = InternalBindingProperty; +}; + +template<> +struct TypeLookup +{ + using Type = InternalNodeProperty; +}; + +template<> +struct TypeLookup +{ + using Type = InternalNodeListProperty; +}; + +template<> +struct TypeLookup +{}; + +template<> +struct TypeLookup +{ + using Type = InternalSignalDeclarationProperty; +}; + +template<> +struct TypeLookup +{ + using Type = InternalSignalHandlerProperty; +}; + +template<> +struct TypeLookup +{ + using Type = InternalVariantProperty; +}; + +class QMLDESIGNERCORE_EXPORT InternalProperty : public std::enable_shared_from_this { public: - using Pointer = QSharedPointer; + friend InternalNode; + using Pointer = std::shared_ptr; InternalProperty(); virtual ~InternalProperty(); @@ -37,21 +81,37 @@ public: PropertyName name() const; - virtual bool isBindingProperty() const; - virtual bool isVariantProperty() const; - virtual bool isNodeListProperty() const; - virtual bool isNodeProperty() const; - virtual bool isNodeAbstractProperty() const; - virtual bool isSignalHandlerProperty() const; - virtual bool isSignalDeclarationProperty() const; + bool isBindingProperty() const { return m_propertyType == PropertyType::Binding; } + bool isVariantProperty() const { return m_propertyType == PropertyType::Variant; } + bool isNodeListProperty() const { return m_propertyType == PropertyType::NodeList; } + bool isNodeProperty() const { return m_propertyType == PropertyType::Node; } + bool isNodeAbstractProperty() const + { + return m_propertyType == PropertyType::Node || m_propertyType == PropertyType::NodeList; + } + bool isSignalHandlerProperty() const { return m_propertyType == PropertyType::SignalHandler; } + bool isSignalDeclarationProperty() const + { + return m_propertyType == PropertyType::SignalDeclaration; + } + PropertyType propertyType() const { return m_propertyType; } - QSharedPointer toBindingProperty() const; - QSharedPointer toVariantProperty() const; - QSharedPointer toNodeListProperty() const; - QSharedPointer toNodeProperty() const; - QSharedPointer toNodeAbstractProperty() const; - QSharedPointer toSignalHandlerProperty() const; - QSharedPointer toSignalDeclarationProperty() const; + template + auto toProperty() + { + Q_ASSERT(std::dynamic_pointer_cast(shared_from_this())); + return std::static_pointer_cast(shared_from_this()); + } + + template + auto to() + { + if (propertyType == m_propertyType) + return std::static_pointer_cast::Type>( + shared_from_this()); + + return std::shared_ptr::Type>{}; + } InternalNodePointer propertyOwner() const; @@ -62,15 +122,17 @@ public: void resetDynamicTypeName(); protected: // functions - InternalProperty(const PropertyName &name, const InternalNodePointer &propertyOwner); - Pointer internalPointer() const; - void setInternalWeakPointer(const Pointer &pointer); + InternalProperty(const PropertyName &name, + const InternalNodePointer &propertyOwner, + PropertyType propertyType); + void setDynamicTypeName(const TypeName &name); + private: - QWeakPointer m_internalPointer; PropertyName m_name; TypeName m_dynamicType; std::weak_ptr m_propertyOwner; + PropertyType m_propertyType = PropertyType::None; }; } // namespace Internal diff --git a/src/plugins/qmldesigner/designercore/model/internalsignalhandlerproperty.cpp b/src/plugins/qmldesigner/designercore/model/internalsignalhandlerproperty.cpp index ef246229289..70aade63a68 100644 --- a/src/plugins/qmldesigner/designercore/model/internalsignalhandlerproperty.cpp +++ b/src/plugins/qmldesigner/designercore/model/internalsignalhandlerproperty.cpp @@ -6,22 +6,12 @@ namespace QmlDesigner { namespace Internal { -InternalSignalHandlerProperty::InternalSignalHandlerProperty(const PropertyName &name, const InternalNodePointer &propertyOwner) - : InternalProperty(name, propertyOwner) +InternalSignalHandlerProperty::InternalSignalHandlerProperty(const PropertyName &name, + const InternalNodePointer &propertyOwner) + : InternalProperty(name, propertyOwner, PropertyType::SignalHandler) { } - -InternalSignalHandlerProperty::Pointer InternalSignalHandlerProperty::create(const PropertyName &name, const InternalNodePointer &propertyOwner) -{ - auto newPointer(new InternalSignalHandlerProperty(name, propertyOwner)); - InternalSignalHandlerProperty::Pointer smartPointer(newPointer); - - newPointer->setInternalWeakPointer(smartPointer); - - return smartPointer; -} - bool InternalSignalHandlerProperty::isValid() const { return InternalProperty::isValid() && isSignalHandlerProperty(); @@ -36,23 +26,6 @@ void InternalSignalHandlerProperty::setSource(const QString &source) m_source = source; } -bool InternalSignalHandlerProperty::isSignalHandlerProperty() const -{ - return true; -} - -InternalSignalDeclarationProperty::Pointer InternalSignalDeclarationProperty::create(const PropertyName &name, const InternalNodePointer &propertyOwner) -{ - auto newPointer(new InternalSignalDeclarationProperty(name, propertyOwner)); - InternalSignalDeclarationProperty::Pointer smartPointer(newPointer); - - newPointer->setInternalWeakPointer(smartPointer); - - newPointer->setDynamicTypeName("signal"); - - return smartPointer; -} - bool InternalSignalDeclarationProperty::isValid() const { return InternalProperty::isValid() && isSignalDeclarationProperty(); @@ -68,14 +41,11 @@ void InternalSignalDeclarationProperty::setSignature(const QString &signature) m_signature = signature; } -bool InternalSignalDeclarationProperty::isSignalDeclarationProperty() const -{ - return true; -} - -InternalSignalDeclarationProperty::InternalSignalDeclarationProperty(const PropertyName &name, const InternalNodePointer &propertyOwner) - : InternalProperty(name, propertyOwner) +InternalSignalDeclarationProperty::InternalSignalDeclarationProperty( + const PropertyName &name, const InternalNodePointer &propertyOwner) + : InternalProperty(name, propertyOwner, PropertyType::SignalDeclaration) { + setDynamicTypeName("signal"); } } // namespace Internal diff --git a/src/plugins/qmldesigner/designercore/model/internalsignalhandlerproperty.h b/src/plugins/qmldesigner/designercore/model/internalsignalhandlerproperty.h index 5fbf665fc6f..f0d88e2d239 100644 --- a/src/plugins/qmldesigner/designercore/model/internalsignalhandlerproperty.h +++ b/src/plugins/qmldesigner/designercore/model/internalsignalhandlerproperty.h @@ -11,20 +11,16 @@ namespace Internal { class InternalSignalHandlerProperty : public InternalProperty { public: - using Pointer = QSharedPointer; + using Pointer = std::shared_ptr; + static constexpr PropertyType type = PropertyType::SignalHandler; - static Pointer create(const PropertyName &name, const InternalNodePointer &propertyOwner); + InternalSignalHandlerProperty(const PropertyName &name, const InternalNodePointer &propertyOwner); bool isValid() const override; QString source() const; void setSource(const QString &source); - bool isSignalHandlerProperty() const override; - -protected: - InternalSignalHandlerProperty(const PropertyName &name, const InternalNodePointer &propertyOwner); - private: QString m_source; }; @@ -32,20 +28,17 @@ private: class InternalSignalDeclarationProperty : public InternalProperty { public: - using Pointer = QSharedPointer; + using Pointer = std::shared_ptr; + static constexpr PropertyType type = PropertyType::SignalDeclaration; - static Pointer create(const PropertyName &name, const InternalNodePointer &propertyOwner); + InternalSignalDeclarationProperty(const PropertyName &name, + const InternalNodePointer &propertyOwner); bool isValid() const override; QString signature() const; void setSignature(const QString &source); - bool isSignalDeclarationProperty() const override; - -protected: - InternalSignalDeclarationProperty(const PropertyName &name, const InternalNodePointer &propertyOwner); - private: QString m_signature; }; diff --git a/src/plugins/qmldesigner/designercore/model/internalvariantproperty.cpp b/src/plugins/qmldesigner/designercore/model/internalvariantproperty.cpp index 612a41e8b62..53a0347c173 100644 --- a/src/plugins/qmldesigner/designercore/model/internalvariantproperty.cpp +++ b/src/plugins/qmldesigner/designercore/model/internalvariantproperty.cpp @@ -6,21 +6,12 @@ namespace QmlDesigner { namespace Internal { -InternalVariantProperty::InternalVariantProperty(const PropertyName &name, const InternalNodePointer &node) - : InternalProperty(name, node) +InternalVariantProperty::InternalVariantProperty(const PropertyName &name, + const InternalNodePointer &node) + : InternalProperty(name, node, PropertyType::Variant) { } -InternalVariantProperty::Pointer InternalVariantProperty::create(const PropertyName &name, const InternalNodePointer &propertyOwner) -{ - auto newPointer(new InternalVariantProperty(name, propertyOwner)); - InternalVariantProperty::Pointer smartPointer(newPointer); - - newPointer->setInternalWeakPointer(smartPointer); - - return smartPointer; -} - QVariant InternalVariantProperty::value() const { return m_value; @@ -31,11 +22,6 @@ void InternalVariantProperty::setValue(const QVariant &value) m_value = value; } -bool InternalVariantProperty::isVariantProperty() const -{ - return true; -} - void InternalVariantProperty::setDynamicValue(const TypeName &type, const QVariant &value) { setValue(value); diff --git a/src/plugins/qmldesigner/designercore/model/internalvariantproperty.h b/src/plugins/qmldesigner/designercore/model/internalvariantproperty.h index 521009b834e..f9bb85d38d7 100644 --- a/src/plugins/qmldesigner/designercore/model/internalvariantproperty.h +++ b/src/plugins/qmldesigner/designercore/model/internalvariantproperty.h @@ -11,9 +11,10 @@ namespace Internal { class InternalVariantProperty : public InternalProperty { public: - using Pointer = QSharedPointer; + using Pointer = std::shared_ptr; + static constexpr PropertyType type = PropertyType::Variant; - static Pointer create(const PropertyName &name, const InternalNodePointer &propertyOwner); + InternalVariantProperty(const PropertyName &name, const InternalNodePointer &propertyOwner); bool isValid() const override; @@ -22,11 +23,6 @@ public: void setDynamicValue(const TypeName &type, const QVariant &value); - bool isVariantProperty() const override; - -protected: - InternalVariantProperty(const PropertyName &name, const InternalNodePointer &propertyOwner); - private: QVariant m_value; }; diff --git a/src/plugins/qmldesigner/designercore/model/model.cpp b/src/plugins/qmldesigner/designercore/model/model.cpp index 844454ae55e..12a8c091838 100644 --- a/src/plugins/qmldesigner/designercore/model/model.cpp +++ b/src/plugins/qmldesigner/designercore/model/model.cpp @@ -8,10 +8,13 @@ #include "abstractview.h" #include "auxiliarydataproperties.h" +#include "internalbindingproperty.h" #include "internalnodeabstractproperty.h" #include "internalnodelistproperty.h" +#include "internalnodeproperty.h" #include "internalproperty.h" #include "internalsignalhandlerproperty.h" +#include "internalvariantproperty.h" #include "metainfo.h" #include "nodeinstanceview.h" #include "nodemetainfo.h" @@ -23,7 +26,6 @@ #include "rewriterview.h" #include "rewritingexception.h" #include "signalhandlerproperty.h" -#include "textmodifier.h" #include "variantproperty.h" #include @@ -277,7 +279,7 @@ InternalNodePointer ModelPrivate::createNode(const TypeName &typeName, for (const auto &auxiliaryData : auxiliaryDatas) newNode->setAuxiliaryData(AuxiliaryDataKeyView{auxiliaryData.first}, auxiliaryData.second); - m_nodeSet.insert(newNode); + m_nodes.push_back(newNode); m_internalIdNodeHash.insert(newNode->internalId, newNode); if (!nodeSource.isNull()) @@ -303,7 +305,7 @@ void ModelPrivate::removeNodeFromModel(const InternalNodePointer &node) if (!node->id.isEmpty()) m_idNodeHash.remove(node->id); node->isValid = false; - m_nodeSet.remove(node); + m_nodes.removeOne(node); m_internalIdNodeHash.remove(node->internalId); } @@ -319,15 +321,9 @@ void ModelPrivate::handleResourceSet(const ModelResourceSet &resourceSet) removeNode(node.m_internalNode); } - for (const AbstractProperty &property : resourceSet.removeProperties) { - if (property) - removeProperty(property.m_internalNode->property(property.m_propertyName)); - } + removeProperties(toInternalProperties(resourceSet.removeProperties)); - for (const auto &[property, expression] : resourceSet.setExpressions) { - if (property) - setBindingProperty(property.m_internalNode, property.m_propertyName, expression); - } + setBindingProperties(resourceSet.setExpressions); } void ModelPrivate::removeAllSubNodes(const InternalNodePointer &node) @@ -338,10 +334,12 @@ void ModelPrivate::removeAllSubNodes(const InternalNodePointer &node) void ModelPrivate::removeNodeAndRelatedResources(const InternalNodePointer &node) { - if (m_resourceManagement) - handleResourceSet(m_resourceManagement->removeNode(ModelNode{node, m_model, nullptr})); - else + if (m_resourceManagement) { + handleResourceSet( + m_resourceManagement->removeNodes({ModelNode{node, m_model, nullptr}}, m_model)); + } else { removeNode(node); + } } void ModelPrivate::removeNode(const InternalNodePointer &node) @@ -935,7 +933,7 @@ void ModelPrivate::notifyNodeAboutToBeReparent(const InternalNodePointer &node, if (!oldPropertyName.isEmpty() && oldParent->isValid) oldProperty = NodeAbstractProperty(oldPropertyName, oldParent, m_model, view); - if (!newPropertyParent.isNull()) + if (newPropertyParent) newProperty = NodeAbstractProperty(newPropertyParent, m_model, view); ModelNode modelNode(node, m_model, view); @@ -956,7 +954,7 @@ void ModelPrivate::notifyNodeReparent(const InternalNodePointer &node, if (!oldPropertyName.isEmpty() && oldParent->isValid) oldProperty = NodeAbstractProperty(oldPropertyName, oldParent, m_model, view); - if (!newPropertyParent.isNull()) + if (newPropertyParent) newProperty = NodeAbstractProperty(newPropertyParent, m_model, view); ModelNode modelNode(node, m_model, view); @@ -1055,6 +1053,39 @@ QVector ModelPrivate::toInternalNodeVector(const QVector ModelPrivate::toInternalProperties(const AbstractProperties &properties) +{ + QList internalProperties; + internalProperties.reserve(properties.size()); + + for (const auto &property : properties) { + if (property.m_internalNode) { + if (auto internalProperty = property.m_internalNode->property(property.m_propertyName)) + internalProperties.push_back(internalProperty); + } + } + + return internalProperties; +} + +QList> ModelPrivate::toInternalBindingProperties( + const ModelResourceSet::SetExpressions &setExpressions) +{ + QList> internalProperties; + internalProperties.reserve(setExpressions.size()); + + for (const auto &setExpression : setExpressions) { + const auto &property = setExpression.property; + if (property.m_internalNode) { + if (auto internalProperty = property.m_internalNode->bindingProperty( + property.m_propertyName)) + internalProperties.emplace_back(internalProperty, setExpression.expression); + } + } + + return internalProperties; +} + void ModelPrivate::changeSelectedNodes(const QList &newSelectedNodeList, const QList &oldSelectedNodeList) { @@ -1102,7 +1133,7 @@ void ModelPrivate::deselectNode(const InternalNodePointer &node) void ModelPrivate::removePropertyWithoutNotification(const InternalPropertyPointer &property) { if (property->isNodeAbstractProperty()) { - const auto &&allSubNodes = property->toNodeAbstractProperty()->allSubNodes(); + const auto &&allSubNodes = property->toProperty()->allSubNodes(); for (const InternalNodePointer &node : allSubNodes) removeNodeFromModel(node); } @@ -1123,25 +1154,38 @@ static QList toPropertyPairList(const QListremoveProperty(AbstractProperty{property, m_model, nullptr})); - else + m_resourceManagement->removeProperties({AbstractProperty{property, m_model, nullptr}}, + m_model)); + } else { removeProperty(property); + } } void ModelPrivate::removeProperty(const InternalPropertyPointer &property) { - notifyPropertiesAboutToBeRemoved({property}); + removeProperties({property}); +} - const QList propertyPairList = toPropertyPairList({property}); +void ModelPrivate::removeProperties(const QList &properties) +{ + if (properties.isEmpty()) + return; - removePropertyWithoutNotification(property); + notifyPropertiesAboutToBeRemoved(properties); + + const QList propertyPairList = toPropertyPairList(properties); + + for (const auto &property : properties) + removePropertyWithoutNotification(property); notifyPropertiesRemoved(propertyPairList); } -void ModelPrivate::setBindingProperty(const InternalNodePointer &node, const PropertyName &name, const QString &expression) +void ModelPrivate::setBindingProperty(const InternalNodePointer &node, + const PropertyName &name, + const QString &expression) { AbstractView::PropertyChangeFlags propertyChange = AbstractView::NoAdditionalChanges; if (!node->hasProperty(name)) { @@ -1155,6 +1199,22 @@ void ModelPrivate::setBindingProperty(const InternalNodePointer &node, const Pro notifyBindingPropertiesChanged({bindingProperty}, propertyChange); } +void ModelPrivate::setBindingProperties(const ModelResourceSet::SetExpressions &setExpressions) +{ + if (setExpressions.isEmpty()) + return; + + AbstractView::PropertyChangeFlags propertyChange = AbstractView::NoAdditionalChanges; + + auto bindingPropertiesWithExpressions = toInternalBindingProperties(setExpressions); + auto bindingProperties = Utils::transform(bindingPropertiesWithExpressions, + [](const auto &entry) { return std::get<0>(entry); }); + notifyBindingPropertiesAboutToBeChanged(bindingProperties); + for (const auto &[bindingProperty, expression] : bindingPropertiesWithExpressions) + bindingProperty->setExpression(expression); + notifyBindingPropertiesChanged(bindingProperties, propertyChange); +} + void ModelPrivate::setSignalHandlerProperty(const InternalNodePointer &node, const PropertyName &name, const QString &source) { AbstractView::PropertyChangeFlags propertyChange = AbstractView::NoAdditionalChanges; @@ -1250,7 +1310,7 @@ void ModelPrivate::reparentNode(const InternalNodePointer &parentNode, } InternalNodeAbstractPropertyPointer newParentProperty(parentNode->nodeAbstractProperty(name)); - Q_ASSERT(!newParentProperty.isNull()); + Q_ASSERT(newParentProperty); notifyNodeAboutToBeReparent(childNode, newParentProperty, oldParentNode, oldParentPropertyName, propertyChange); @@ -1305,7 +1365,7 @@ void ModelPrivate::setNodeSource(const InternalNodePointer &node, const QString void ModelPrivate::changeNodeOrder(const InternalNodePointer &parentNode, const PropertyName &listPropertyName, int from, int to) { InternalNodeListPropertyPointer nodeList(parentNode->nodeListProperty(listPropertyName)); - Q_ASSERT(!nodeList.isNull()); + Q_ASSERT(nodeList); nodeList->slide(from, to); const InternalNodePointer internalNode = nodeList->nodeList().at(to); @@ -1376,8 +1436,7 @@ bool ModelPrivate::hasNodeForInternalId(qint32 internalId) const { return m_internalIdNodeHash.contains(internalId); } - -QList ModelPrivate::allNodes() const +QList ModelPrivate::allNodesOrdered() const { if (!m_rootInternalNode || !m_rootInternalNode->isValid) return {}; @@ -1388,10 +1447,14 @@ QList ModelPrivate::allNodes() const nodeList.append(m_rootInternalNode); nodeList.append(m_rootInternalNode->allSubNodes()); // FIXME: This is horribly expensive compared to a loop. - nodeList.append(Utils::toList(m_nodeSet - Utils::toSet(nodeList))); + nodeList.append(Utils::toList(Utils::toSet(m_nodes) - Utils::toSet(nodeList))); return nodeList; } +QList ModelPrivate::allNodesUnordered() const +{ + return m_nodes; +} bool ModelPrivate::isWriteLocked() const { @@ -1786,16 +1849,6 @@ Model *Model::metaInfoProxyModel() const return const_cast(this); } -TextModifier *Model::textModifier() const -{ - return d->m_textModifier.data(); -} - -void Model::setTextModifier(TextModifier *textModifier) -{ - d->m_textModifier = textModifier; -} - void Model::setDocumentMessages(const QList &errors, const QList &warnings) { @@ -1921,6 +1974,26 @@ NodeMetaInfo Model::qtQuickPropertyAnimationMetaInfo() const } } +NodeMetaInfo Model::qtQuickPropertyChangesMetaInfo() const +{ + if constexpr (useProjectStorage()) { + using namespace Storage::Info; + return createNodeMetaInfo(); + } else { + return metaInfo("QtQuick.PropertyChanges"); + } +} + +NodeMetaInfo Model::flowViewFlowActionAreaMetaInfo() const +{ + if constexpr (useProjectStorage()) { + using namespace Storage::Info; + return createNodeMetaInfo(); + } else { + return metaInfo("FlowView.FlowActionArea"); + } +} + NodeMetaInfo Model::flowViewFlowDecisionMetaInfo() const { if constexpr (useProjectStorage()) { @@ -1931,6 +2004,16 @@ NodeMetaInfo Model::flowViewFlowDecisionMetaInfo() const } } +NodeMetaInfo Model::flowViewFlowItemMetaInfo() const +{ + if constexpr (useProjectStorage()) { + using namespace Storage::Info; + return createNodeMetaInfo(); + } else { + return metaInfo("FlowView.FlowItem"); + } +} + NodeMetaInfo Model::flowViewFlowWildcardMetaInfo() const { if constexpr (useProjectStorage()) { @@ -2041,6 +2124,16 @@ NodeMetaInfo Model::qtQuickTimelineTimelineMetaInfo() const } } +NodeMetaInfo Model::qtQuickTransistionMetaInfo() const +{ + if constexpr (useProjectStorage()) { + using namespace Storage::Info; + return createNodeMetaInfo(); + } else { + return metaInfo("QtQuick.Transition"); + } +} + NodeMetaInfo Model::qtQuickConnectionsMetaInfo() const { if constexpr (useProjectStorage()) { @@ -2204,9 +2297,105 @@ void Model::detachView(AbstractView *view, ViewNotification emitDetachNotify) d->detachView(view, emitNotify); } -QList Model::allModelNodes() const +namespace { +QList toModelNodeList(const QList &nodeList, Model *model) { - return QmlDesigner::toModelNodeList(d->allNodes(), nullptr); + QList newNodeList; + for (const Internal::InternalNode::Pointer &node : nodeList) + newNodeList.append(ModelNode(node, model, nullptr)); + + return newNodeList; +} +} // namespace + +QList Model::allModelNodesUnordered() +{ + return toModelNodeList(d->allNodesUnordered(), this); +} + +ModelNode Model::rootModelNode() +{ + return ModelNode{d->rootNode(), this, nullptr}; +} + +ModelNode Model::modelNodeForId(const QString &id) +{ + return ModelNode(d->nodeForId(id), this, nullptr); +} + +QHash Model::idModelNodeDict() +{ + QHash idModelNodes; + + for (const auto &[key, internalNode] : d->m_idNodeHash.asKeyValueRange()) + idModelNodes.insert(key, ModelNode(internalNode, this, nullptr)); + + return idModelNodes; +} + +namespace { +ModelNode createNode(Model *model, + Internal::ModelPrivate *d, + const TypeName &typeName, + int majorVersion, + int minorVersion) +{ + return ModelNode(d->createNode(typeName, majorVersion, minorVersion, {}, {}, {}, {}, {}), + model, + nullptr); +} +} // namespace + +ModelNode Model::createModelNode(const TypeName &typeName) +{ + if constexpr (useProjectStorage()) { + return createNode(this, d.get(), typeName, -1, -1); + } else { + const NodeMetaInfo m = metaInfo(typeName); + return createNode(this, d.get(), typeName, m.majorVersion(), m.minorVersion()); + } +} + +void Model::removeModelNodes(ModelNodes nodes, BypassModelResourceManagement bypass) +{ + nodes.erase(std::remove_if(nodes.begin(), nodes.end(), [](auto &&node) { return !node; }), + nodes.end()); + + if (nodes.empty()) + return; + + std::sort(nodes.begin(), nodes.end()); + + ModelResourceSet set; + + if (d->m_resourceManagement && bypass == BypassModelResourceManagement::No) + set = d->m_resourceManagement->removeNodes(std::move(nodes), this); + else + set = {std::move(nodes), {}, {}}; + + d->handleResourceSet(set); +} + +void Model::removeProperties(AbstractProperties properties, BypassModelResourceManagement bypass) +{ + properties.erase(std::remove_if(properties.begin(), + properties.end(), + [](auto &&property) { return !property; }), + properties.end()); + + if (properties.empty()) + return; + + std::sort(properties.begin(), properties.end()); + + ModelResourceSet set; + + if (d->m_resourceManagement && bypass == BypassModelResourceManagement::No) + set = d->m_resourceManagement->removeProperties(std::move(properties), this); + else + set = {{}, std::move(properties), {}}; + + d->handleResourceSet(set); } } // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/designercore/model/model_p.h b/src/plugins/qmldesigner/designercore/model/model_p.h index b802d703f25..5c69e756164 100644 --- a/src/plugins/qmldesigner/designercore/model/model_p.h +++ b/src/plugins/qmldesigner/designercore/model/model_p.h @@ -10,6 +10,8 @@ #include "modelnode.h" #include "skipiterator.h" +#include + #include #include #include @@ -42,13 +44,13 @@ class InternalNodeAbstractProperty; class InternalNodeListProperty; using InternalNodePointer = std::shared_ptr; -using InternalPropertyPointer = QSharedPointer; -using InternalBindingPropertyPointer = QSharedPointer; -using InternalSignalHandlerPropertyPointer = QSharedPointer; -using InternalSignalDeclarationPropertyPointer = QSharedPointer; -using InternalVariantPropertyPointer = QSharedPointer; -using InternalNodeAbstractPropertyPointer = QSharedPointer; -using InternalNodeListPropertyPointer = QSharedPointer; +using InternalPropertyPointer = std::shared_ptr; +using InternalBindingPropertyPointer = std::shared_ptr; +using InternalSignalHandlerPropertyPointer = std::shared_ptr; +using InternalSignalDeclarationPropertyPointer = std::shared_ptr; +using InternalVariantPropertyPointer = std::shared_ptr; +using InternalNodeAbstractPropertyPointer = std::shared_ptr; +using InternalNodeListPropertyPointer = std::shared_ptr; using PropertyPair = QPair; class ModelPrivate; @@ -93,7 +95,6 @@ class ModelPrivate : public QObject friend Model; friend Internal::WriteLocker; - friend NodeMetaInfoPrivate; public: ModelPrivate(Model *model, @@ -244,8 +245,12 @@ public: void setPropertyValue(const InternalNodePointer &node,const PropertyName &name, const QVariant &value); void removePropertyAndRelatedResources(const InternalPropertyPointer &property); void removeProperty(const InternalPropertyPointer &property); + void removeProperties(const QList &properties); - void setBindingProperty(const InternalNodePointer &node, const PropertyName &name, const QString &expression); + void setBindingProperty(const InternalNodePointer &node, + const PropertyName &name, + const QString &expression); + void setBindingProperties(const ModelResourceSet::SetExpressions &setExpressions); void setSignalHandlerProperty(const InternalNodePointer &node, const PropertyName &name, const QString &source); void setSignalDeclarationProperty(const InternalNodePointer &node, const PropertyName &name, const QString &signature); void setVariantProperty(const InternalNodePointer &node, const PropertyName &name, const QVariant &value); @@ -266,7 +271,8 @@ public: InternalNodePointer nodeForInternalId(qint32 internalId) const; bool hasNodeForInternalId(qint32 internalId) const; - QList allNodes() const; + QList allNodesUnordered() const; + QList allNodesOrdered() const; bool isWriteLocked() const; @@ -281,6 +287,13 @@ public: InternalNodePointer currentStateNode() const; InternalNodePointer currentTimelineNode() const; + void handleResourceSet(const ModelResourceSet &resourceSet); + + QHash> &nodeMetaInfoCache() + { + return m_nodeMetaInfoCache; + } + private: void removePropertyWithoutNotification(const InternalPropertyPointer &property); void removeAllSubNodes(const InternalNodePointer &node); @@ -289,8 +302,10 @@ private: QList toModelNodeList(const QList &nodeList, AbstractView *view) const; QVector toModelNodeVector(const QVector &nodeVector, AbstractView *view) const; QVector toInternalNodeVector(const QVector &modelNodeVector) const; + static QList toInternalProperties(const AbstractProperties &properties); + static QList> toInternalBindingProperties( + const ModelResourceSet::SetExpressions &setExpressions); EnabledViewRange enabledViews() const; - void handleResourceSet(const ModelResourceSet &resourceSet); public: NotNullPointer projectStorage = nullptr; @@ -305,7 +320,7 @@ private: QList m_selectedInternalNodeList; QHash m_idNodeHash; QHash m_internalIdNodeHash; - QSet m_nodeSet; + QList m_nodes; InternalNodePointer m_currentStateNode; InternalNodePointer m_rootInternalNode; InternalNodePointer m_currentTimelineNode; @@ -313,9 +328,8 @@ private: QUrl m_fileUrl; QPointer m_rewriterView; QPointer m_nodeInstanceView; - QPointer m_textModifier; QPointer m_metaInfoProxyModel; - QHash> m_nodeMetaInfoCache; + QHash> m_nodeMetaInfoCache; bool m_writeLock = false; qint32 m_internalIdCounter = 1; }; diff --git a/src/plugins/qmldesigner/designercore/model/modelnode.cpp b/src/plugins/qmldesigner/designercore/model/modelnode.cpp index 7e64f4c4bf4..45c076022da 100644 --- a/src/plugins/qmldesigner/designercore/model/modelnode.cpp +++ b/src/plugins/qmldesigner/designercore/model/modelnode.cpp @@ -3,15 +3,15 @@ #include "modelnode.h" +#include "annotation.h" +#include "bindingproperty.h" #include "internalnode_p.h" #include "model_p.h" -#include "variantproperty.h" -#include "bindingproperty.h" -#include "signalhandlerproperty.h" #include "nodeabstractproperty.h" #include "nodelistproperty.h" #include "nodeproperty.h" -#include "annotation.h" +#include "signalhandlerproperty.h" +#include "variantproperty.h" #include #include @@ -51,33 +51,20 @@ childNode.addProperty("pos", QPoint(2, 12)); All the manipulation functions are generating undo commands internally. */ - - /*! \brief internal constructor */ -ModelNode::ModelNode(const InternalNodePointer &internalNode, Model *model, const AbstractView *view): - m_internalNode(internalNode), - m_model(model), - m_view(const_cast(view)) -{ -} +ModelNode::ModelNode(const InternalNodePointer &internalNode, Model *model, const AbstractView *view) + : m_internalNode(internalNode) + , m_model(model) + , m_view(const_cast(view)) +{} ModelNode::ModelNode(const ModelNode &modelNode, AbstractView *view) - : m_internalNode(modelNode.m_internalNode), - m_model(modelNode.model()), - m_view(view) -{ -} - -/*! \brief contructs a invalid model node -\return invalid node -\see invalid -*/ -ModelNode::ModelNode(): - m_internalNode(new InternalNode) -{ -} + : m_internalNode(modelNode.m_internalNode) + , m_model(modelNode.model()) + , m_view(view) +{} /*! \brief does nothing */ @@ -102,7 +89,7 @@ QString ModelNode::validId() return id(); } -static bool idIsQmlKeyWord(const QString& id) +static bool idIsQmlKeyWord(const QString &id) { static const QSet keywords = {"as", "break", "case", "catch", "continue", "debugger", "default", "delete", @@ -116,49 +103,22 @@ static bool idIsQmlKeyWord(const QString& id) return keywords.contains(id); } -static bool isIdToAvoid(const QString& id) +static bool isIdToAvoid(const QString &id) { - static const QSet ids = { - "top", - "bottom", - "left", - "right", - "width", - "height", - "x", - "y", - "opacity", - "parent", - "item", - "flow", - "color", - "margin", - "padding", - "border", - "font", - "text", - "source", - "state", - "visible", - "focus", - "data", - "clip", - "layer", - "scale", - "enabled", - "anchors", - "texture", - "shaderInfo", - "sprite", - "spriteSequence", - "baseState", - "rect" - }; + static const QSet ids = {"top", "bottom", "left", "right", + "width", "height", "x", "y", + "opacity", "parent", "item", "flow", + "color", "margin", "padding", "border", + "font", "text", "source", "state", + "visible", "focus", "data", "clip", + "layer", "scale", "enabled", "anchors", + "texture", "shaderInfo", "sprite", "spriteSequence", + "baseState", "rect"}; return ids.contains(id); } -static bool idContainsWrongLetter(const QString& id) +static bool idContainsWrongLetter(const QString &id) { static QRegularExpression idExpr(QStringLiteral("^[a-z_][a-zA-Z0-9_]*$")); return !id.contains(idExpr); @@ -200,7 +160,7 @@ bool ModelNode::hasId() const return !m_internalNode->id.isEmpty(); } -void ModelNode::setIdWithRefactoring(const QString& id) +void ModelNode::setIdWithRefactoring(const QString &id) { if (isValid()) { if (model()->rewriterView() && !id.isEmpty() @@ -323,13 +283,15 @@ NodeAbstractProperty ModelNode::parentProperty() const if (!isValid()) return {}; - if (m_internalNode->parentProperty().isNull()) + if (!m_internalNode->parentProperty()) return {}; - return NodeAbstractProperty(m_internalNode->parentProperty()->name(), m_internalNode->parentProperty()->propertyOwner(), m_model.data(), view()); + return NodeAbstractProperty(m_internalNode->parentProperty()->name(), + m_internalNode->parentProperty()->propertyOwner(), + m_model.data(), + view()); } - /*! \brief the command id is used to compress the some commands together. \param newParentNode parent of this node will be set to this node \param commandId integer which is used to descripe commands which should compressed together to one command @@ -387,7 +349,7 @@ bool ModelNode::hasParentProperty() const if (!isValid()) return false; - if (m_internalNode->parentProperty().isNull()) + if (!m_internalNode->parentProperty()) return false; return true; @@ -543,7 +505,6 @@ QList ModelNode::properties() const return propertyList; } - /*! \brief returns a list of all VariantProperties \return list of all VariantProperties @@ -594,7 +555,6 @@ QList ModelNode::nodeListProperties() const return propertyList; } - /*! \brief returns a list of all BindingProperties \return list of all BindingProperties @@ -694,35 +654,13 @@ void ModelNode::destroy() removeModelNodeFromSelection(*this); model()->d->removeNodeAndRelatedResources(m_internalNode); } + //\} /*! \name Property Manipulation * This functions interact with properties. */ - -/*! - \brief Returns if the two nodes reference the same entity in the same model - */ -bool operator ==(const ModelNode &firstNode, const ModelNode &secondNode) -{ - return firstNode.internalId() == secondNode.internalId(); -} - -/*! - \brief Returns if the two nodes do not reference the same entity in the same model - */ -bool operator !=(const ModelNode &firstNode, const ModelNode &secondNode) -{ - return firstNode.internalId() != secondNode.internalId(); -} - -bool operator <(const ModelNode &firstNode, const ModelNode &secondNode) -{ - return firstNode.internalId() < secondNode.internalId(); -} - - Internal::InternalNodePointer ModelNode::internalNode() const { return m_internalNode; @@ -747,7 +685,6 @@ AbstractView *ModelNode::view() const return m_view.data(); } - /*! \brief returns all ModelNodes that are direct children of this ModelNode The list contains every ModelNode that belongs to one of this ModelNodes @@ -759,7 +696,7 @@ QList ModelNode::directSubModelNodes() const if (!isValid()) return {}; - return toModelNodeList(m_internalNode->allDirectSubNodes(), view()); + return toModelNodeList(m_internalNode->allDirectSubNodes(), model(), view()); } QList ModelNode::directSubModelNodesOfType(const NodeMetaInfo &type) const @@ -788,7 +725,7 @@ QList ModelNode::allSubModelNodes() const if (!isValid()) return {}; - return toModelNodeList(internalNode()->allSubNodes(), view()); + return toModelNodeList(internalNode()->allSubNodes(), model(), view()); } QList ModelNode::allSubModelNodesAndThisNode() const @@ -937,7 +874,7 @@ static bool recursiveAncestor(const ModelNode &possibleAncestor, const ModelNode if (node.hasParentProperty()) { if (node.parentProperty().parentModelNode() == possibleAncestor) - return true; + return true; return recursiveAncestor(possibleAncestor, node.parentProperty().parentModelNode()); } @@ -952,10 +889,8 @@ bool ModelNode::isAncestorOf(const ModelNode &node) const QDebug operator<<(QDebug debug, const ModelNode &modelNode) { if (modelNode.isValid()) { - debug.nospace() << "ModelNode(" - << modelNode.internalId() << ", " - << modelNode.type() << ", " - << modelNode.id() << ')'; + debug.nospace() << "ModelNode(" << modelNode.internalId() << ", " << modelNode.type() + << ", " << modelNode.id() << ')'; } else { debug.nospace() << "ModelNode(invalid)"; } @@ -963,12 +898,12 @@ QDebug operator<<(QDebug debug, const ModelNode &modelNode) return debug.space(); } -QTextStream& operator<<(QTextStream &stream, const ModelNode &modelNode) +QTextStream &operator<<(QTextStream &stream, const ModelNode &modelNode) { if (modelNode.isValid()) { stream << "ModelNode(" - << "type: " << modelNode.type() << ", " - << "id: " << modelNode.id() << ')'; + << "type: " << modelNode.type() << ", " + << "id: " << modelNode.id() << ')'; } else { stream << "ModelNode(invalid)"; } @@ -998,7 +933,7 @@ void ModelNode::deselectNode() view()->setSelectedModelNodes(selectedNodeList); } -int ModelNode::variantUserType() +int ModelNode::variantTypeId() { return qMetaTypeId(); } @@ -1016,8 +951,7 @@ std::optional ModelNode::auxiliaryData(AuxiliaryDataKeyView key) const return m_internalNode->auxiliaryData(key); } -std::optional ModelNode::auxiliaryData(AuxiliaryDataType type, - Utils::SmallStringView name) const +std::optional ModelNode::auxiliaryData(AuxiliaryDataType type, Utils::SmallStringView name) const { return auxiliaryData({type, name}); } @@ -1330,7 +1264,7 @@ static ModelNode lowestCommonAncestor(const ModelNode &node1, { Q_ASSERT(node1.isValid() && node2.isValid()); - auto depthOfNode = [] (const ModelNode &node) -> int { + auto depthOfNode = [](const ModelNode &node) -> int { int depth = 0; ModelNode parentNode = node; while (!parentNode.isRootNode()) { @@ -1341,9 +1275,8 @@ static ModelNode lowestCommonAncestor(const ModelNode &node1, }; if (node1 == node2) { - depthOfLCA = (depthOfNode1 < 0) - ? ((depthOfNode2 < 0) ? depthOfNode(node1) : depthOfNode2) - : depthOfNode1; + depthOfLCA = (depthOfNode1 < 0) ? ((depthOfNode2 < 0) ? depthOfNode(node1) : depthOfNode2) + : depthOfNode1; return node1; } @@ -1360,7 +1293,7 @@ static ModelNode lowestCommonAncestor(const ModelNode &node1, ModelNode nodeLower = node1; ModelNode nodeHigher = node2; int depthLower = (depthOfNode1 < 0) ? depthOfNode(nodeLower) : depthOfNode1; - int depthHigher = (depthOfNode2 < 0) ? depthOfNode(nodeHigher) :depthOfNode2; + int depthHigher = (depthOfNode2 < 0) ? depthOfNode(nodeHigher) : depthOfNode2; if (depthLower > depthHigher) { std::swap(depthLower, depthHigher); @@ -1407,9 +1340,8 @@ QList ModelNode::pruneChildren(const QList &nodes) QList forwardNodes; QList backNodes; - auto pushIfIsNotChild = [] (QList &container, const ModelNode &node) { - bool hasAncestor = Utils::anyOf(container, - [node] (const ModelNode &testNode) -> bool { + auto pushIfIsNotChild = [](QList &container, const ModelNode &node) { + bool hasAncestor = Utils::anyOf(container, [node](const ModelNode &testNode) -> bool { return testNode.isAncestorOf(node); }); if (!hasAncestor) @@ -1427,13 +1359,19 @@ QList ModelNode::pruneChildren(const QList &nodes) return backNodes; } -void ModelNode::setScriptFunctions(const QStringList &scriptFunctionList) +void ModelNode::setScriptFunctions(const QStringList &scriptFunctionList) { + if (!isValid()) + return; + model()->d->setScriptFunctions(m_internalNode, scriptFunctionList); } -QStringList ModelNode::scriptFunctions() const +QStringList ModelNode::scriptFunctions() const { + if (!isValid()) + return {}; + return m_internalNode->scriptFunctions; } @@ -1528,8 +1466,7 @@ bool ModelNode::isComponent() const if (metaInfo().isQtQuickLoader()) { if (hasNodeListProperty("component")) { - - /* + /* * The component property should be a NodeProperty, but currently is a NodeListProperty, because * the default property is always implcitly a NodeListProperty. This is something that has to be fixed. */ @@ -1542,7 +1479,8 @@ bool ModelNode::isComponent() const } if (hasNodeProperty("sourceComponent")) { - if (nodeProperty("sourceComponent").modelNode().nodeSourceType() == ModelNode::NodeWithComponentSource) + if (nodeProperty("sourceComponent").modelNode().nodeSourceType() + == ModelNode::NodeWithComponentSource) return true; if (nodeProperty("sourceComponent").modelNode().metaInfo().isFileComponent()) return true; @@ -1560,8 +1498,9 @@ QIcon ModelNode::typeIcon() const if (isValid()) { // if node has no own icon, search for it in the itemlibrary const ItemLibraryInfo *libraryInfo = model()->metaInfo().itemLibraryInfo(); - QList itemLibraryEntryList = libraryInfo->entriesForType( - type(), majorVersion(), minorVersion()); + QList itemLibraryEntryList = libraryInfo->entriesForType(type(), + majorVersion(), + minorVersion()); if (!itemLibraryEntryList.isEmpty()) return itemLibraryEntryList.constFirst().typeIcon(); else if (metaInfo().isValid()) @@ -1579,4 +1518,4 @@ QString ModelNode::behaviorPropertyName() const return m_internalNode->behaviorPropertyName; } -} +} // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/designercore/model/modelresourcemanagement.cpp b/src/plugins/qmldesigner/designercore/model/modelresourcemanagement.cpp new file mode 100644 index 00000000000..a61f1001f96 --- /dev/null +++ b/src/plugins/qmldesigner/designercore/model/modelresourcemanagement.cpp @@ -0,0 +1,796 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +#include "modelresourcemanagement.h" + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +#include + +namespace QmlDesigner { + +namespace { + +enum class CheckRecursive { No, Yes }; + +class NodeActions; + +template +void forEachAction(NodeActions &nodeActions, ActionCall actionCall); + +struct Base +{ + Base(ModelResourceSet &resourceSet, NodeActions &nodeActions) + : resourceSet{resourceSet} + , nodeActions{nodeActions} + {} + + void removeNodes(ModelNodes newModelNodes, CheckRecursive checkRecursive) + { + if (newModelNodes.empty()) + return; + + auto oldModelNodes = removeNodes(newModelNodes); + + if (checkRecursive == CheckRecursive::Yes) + checkNewModelNodes(newModelNodes, oldModelNodes); + } + + void checkModelNodes(ModelNodes newModelNodes) + { + if (newModelNodes.empty()) + return; + + std::sort(newModelNodes.begin(), newModelNodes.end()); + + checkNewModelNodes(newModelNodes, resourceSet.removeModelNodes); + } + + void removeProperties(AbstractProperties newProperties, CheckRecursive checkRecursive) + { + if (newProperties.empty()) + return; + + auto oldProperties = removeProperties(newProperties); + + if (checkRecursive == CheckRecursive::Yes) + checkNewProperties(newProperties, oldProperties); + } + + void addSetExpressions(ModelResourceSet::SetExpressions newSetExpressions) + { + auto &setExpressions = resourceSet.setExpressions; + setExpressions.append(std::move(newSetExpressions)); + } + + void handleNodes(const ModelNodes &) {} + + void handleProperties(const AbstractProperties &) {} + + void finally() {} + +private: + ModelNodes removeNodes(ModelNodes &newModelNodes) + { + std::sort(newModelNodes.begin(), newModelNodes.end()); + + newModelNodes.erase(std::unique(newModelNodes.begin(), newModelNodes.end()), + newModelNodes.end()); + + auto oldModelNodes = std::move(resourceSet.removeModelNodes); + resourceSet.removeModelNodes = {}; + resourceSet.removeModelNodes.reserve(oldModelNodes.size() + newModelNodes.size()); + + std::set_union(newModelNodes.begin(), + newModelNodes.end(), + oldModelNodes.begin(), + oldModelNodes.end(), + std::back_inserter(resourceSet.removeModelNodes)); + + return oldModelNodes; + } + + AbstractProperties removeProperties(AbstractProperties &newProperties) + { + std::sort(newProperties.begin(), newProperties.end()); + + newProperties.erase(std::unique(newProperties.begin(), newProperties.end()), + newProperties.end()); + + auto oldProperties = std::move(resourceSet.removeProperties); + resourceSet.removeProperties = {}; + resourceSet.removeProperties.reserve(oldProperties.size() + newProperties.size()); + + std::set_union(newProperties.begin(), + newProperties.end(), + oldProperties.begin(), + oldProperties.end(), + std::back_inserter(resourceSet.removeProperties)); + + return oldProperties; + } + + void checkNewModelNodes(const ModelNodes &newModelNodes, const ModelNodes &oldModelNodes) + { + ModelNodes addedModelNodes; + addedModelNodes.reserve(newModelNodes.size()); + + std::set_difference(newModelNodes.begin(), + newModelNodes.end(), + oldModelNodes.begin(), + oldModelNodes.end(), + std::back_inserter(addedModelNodes)); + + if (addedModelNodes.size()) + forEachAction(nodeActions, [&](auto &action) { action.handleNodes(addedModelNodes); }); + } + + void checkNewProperties(const AbstractProperties &newProperties, + const AbstractProperties &oldProperties) + { + AbstractProperties addedProperties; + addedProperties.reserve(newProperties.size()); + + std::set_difference(newProperties.begin(), + newProperties.end(), + oldProperties.begin(), + oldProperties.end(), + std::back_inserter(addedProperties)); + + if (addedProperties.size()) + forEachAction(nodeActions, + [&](auto &action) { action.handleProperties(addedProperties); }); + } + +private: + ModelResourceSet &resourceSet; + NodeActions &nodeActions; +}; + +struct CheckChildNodes : public Base +{ + using Base::Base; + + void handleNodes(const ModelNodes &nodes) + { + ModelNodes childNodes; + for (const ModelNode &node : nodes) + childNodes.append(node.directSubModelNodes()); + + checkModelNodes(childNodes); + } +}; + +struct CheckNodesInNodeAbstractProperties : public Base +{ + using Base::Base; + + ModelNodes collectNodes(const AbstractProperties &properties) + { + ModelNodes modelNodes; + + for (const AbstractProperty &property : properties) { + if (property.isNodeAbstractProperty()) + modelNodes.append(property.toNodeAbstractProperty().directSubNodes()); + } + + return modelNodes; + } + + void handleProperties(const AbstractProperties &properties) + { + checkModelNodes(collectNodes(properties)); + } +}; + +struct RemoveLayerEnabled : public Base +{ + using Base::Base; + + AbstractProperties collectProperties(const ModelNodes &nodes) + { + AbstractProperties properties; + + for (const ModelNode &node : nodes) { + if (node.parentProperty().name() == "layer.effect") { + auto layerEnabledProperty = node.parentProperty().parentModelNode().property( + "layer.enabled"); + if (layerEnabledProperty.exists()) + properties.push_back(layerEnabledProperty); + } + } + + return properties; + } + + void handleNodes(const ModelNodes &nodes) + { + removeProperties(collectProperties(nodes), CheckRecursive::No); + } +}; + +struct NodeDependency +{ + ModelNode target; + ModelNode source; + + friend bool operator<(const NodeDependency &first, const NodeDependency &second) + { + return std::tie(first.target, first.source) < std::tie(second.target, second.source); + } + + friend bool operator<(const NodeDependency &first, const ModelNode &second) + { + return first.target < second; + } + + friend bool operator<(const ModelNode &first, const NodeDependency &second) + { + return first < second.target; + } +}; + +using NodeDependencies = std::vector; + +struct BindingDependency +{ + ModelNode target; + BindingProperty property; + + friend bool operator<(const BindingDependency &first, const BindingDependency &second) + { + return std::tie(first.target, first.property) < std::tie(second.target, second.property); + } + + friend bool operator<(const BindingDependency &first, const ModelNode &second) + { + return first.target < second; + } + + friend bool operator<(const ModelNode &first, const BindingDependency &second) + { + return first < second.target; + } +}; + +using BindingDependencies = std::vector; + +struct NameNode +{ + QString name; + ModelNode node; + + friend bool operator<(const NameNode &first, const NameNode &second) + { + return first.name < second.name; + } +}; + +using NameNodes = std::vector; + +struct NodesProperty +{ + ModelNode source; + PropertyName name; + ModelNodes targets; + bool isChanged = false; + + friend bool operator<(const NodesProperty &first, const NodesProperty &second) + { + return first.source < second.source; + } +}; + +using NodesProperties = std::vector; + +struct RemoveDependentBindings : public Base +{ + RemoveDependentBindings(ModelResourceSet &resourceSet, + NodeActions &nodeActions, + BindingDependencies dependencies) + : Base{resourceSet, nodeActions} + , dependencies{std::move(dependencies)} + {} + + AbstractProperties collectProperties(const ModelNodes &nodes) + { + AbstractProperties properties; + ::Utils::set_greedy_intersection(dependencies.begin(), + dependencies.end(), + nodes.begin(), + nodes.end(), + ::Utils::make_iterator([&](const BindingDependency &dependency) { + properties.push_back(dependency.property); + })); + + return properties; + } + + void handleNodes(const ModelNodes &nodes) + { + removeProperties(collectProperties(nodes), CheckRecursive::No); + } + + BindingDependencies dependencies; +}; + +struct RemoveDependencies : public Base +{ + RemoveDependencies(ModelResourceSet &resourceSet, + NodeActions &nodeActions, + NodeDependencies dependencies) + : Base{resourceSet, nodeActions} + , dependencies{std::move(dependencies)} + {} + + ModelNodes collectNodes(const ModelNodes &nodes) const + { + ModelNodes targetNodes; + ::Utils::set_greedy_intersection(dependencies.begin(), + dependencies.end(), + nodes.begin(), + nodes.end(), + ::Utils::make_iterator([&](const NodeDependency &dependency) { + targetNodes.push_back(dependency.source); + })); + + return targetNodes; + } + + void handleNodes(const ModelNodes &nodes) + { + removeNodes(collectNodes(nodes), CheckRecursive::No); + } + + NodeDependencies dependencies; +}; + +struct RemoveTargetsSources : public Base +{ + RemoveTargetsSources(ModelResourceSet &resourceSet, + NodeActions &nodeActions, + NodeDependencies dependencies, + NodesProperties nodesProperties) + : Base{resourceSet, nodeActions} + , dependencies{std::move(dependencies)} + , nodesProperties{std::move(nodesProperties)} + {} + + static void removeDependency(NodesProperties &removedTargetNodesInProperties, + const NodeDependency &dependency) + { + auto found = std::find_if(removedTargetNodesInProperties.begin(), + removedTargetNodesInProperties.end(), + [&](const auto &nodeProperty) { + return nodeProperty.source == dependency.source; + }); + + if (found == removedTargetNodesInProperties.end()) + removedTargetNodesInProperties.push_back({dependency.source, "", {dependency.target}}); + else + found->targets.push_back(dependency.target); + } + + NodesProperties collectRemovedDependencies(const ModelNodes &nodes) + { + NodesProperties removedTargetNodesInProperties; + + ModelNodes targetNodes; + ::Utils::set_greedy_intersection(dependencies.begin(), + dependencies.end(), + nodes.begin(), + nodes.end(), + ::Utils::make_iterator([&](const NodeDependency &dependency) { + removeDependency(removedTargetNodesInProperties, + dependency); + })); + + std::sort(removedTargetNodesInProperties.begin(), removedTargetNodesInProperties.end()); + + return removedTargetNodesInProperties; + } + + ModelNodes collectNodesToBeRemoved(const ModelNodes &nodes) + { + ModelNodes nodesToBeRemoved; + + auto removeTargets = [&](auto &first, auto &second) { + auto newEnd = std::remove_if(first.targets.begin(), + first.targets.end(), + [&](const ModelNode &node) { + return std::find(second.targets.begin(), + second.targets.end(), + node) + != second.targets.end(); + }); + if (newEnd != first.targets.end()) { + first.isChanged = true; + first.targets.erase(newEnd, first.targets.end()); + + if (first.targets.empty()) + nodesToBeRemoved.push_back(first.source); + } + }; + + NodesProperties removedTargetNodesInProperties = collectRemovedDependencies(nodes); + ::Utils::set_intersection_compare(nodesProperties.begin(), + nodesProperties.end(), + removedTargetNodesInProperties.begin(), + removedTargetNodesInProperties.end(), + removeTargets, + std::less{}); + + return nodesToBeRemoved; + } + + void handleNodes(const ModelNodes &nodes) + { + removeNodes(collectNodesToBeRemoved(nodes), CheckRecursive::No); + } + + QString createExpression(const NodesProperty &nodesProperty) + { + QString expression = "["; + const ModelNode &last = nodesProperty.targets.back(); + for (const ModelNode &node : nodesProperty.targets) { + expression += node.id(); + if (node != last) + expression += ", "; + } + expression += "]"; + + return expression; + } + + void finally() + { + ModelResourceSet::SetExpressions setExpressions; + + for (const NodesProperty &nodesProperty : nodesProperties) { + if (nodesProperty.isChanged && nodesProperty.targets.size()) { + setExpressions.push_back({nodesProperty.source.bindingProperty(nodesProperty.name), + createExpression(nodesProperty)}); + } + } + + addSetExpressions(std::move(setExpressions)); + } + + NodeDependencies dependencies; + NodesProperties nodesProperties; +}; + +struct DependenciesSet +{ + NodeDependencies nodeDependencies; + NodeDependencies targetsDependencies; + NodesProperties targetsNodesProperties; + BindingDependencies bindingDependencies; +}; + +struct BindingFilter +{ + BindingFilter(BindingDependencies &dependencies, Model *model) + : dependencies{dependencies} + , idModelNodeDict{model->idModelNodeDict()} + , wordsRegex{"[[:<:]](\\w+)[[:>:]]"} + {} + + void filterBindingProperty(const BindingProperty &property) + { + const QString &expression = property.expression(); + auto iterator = wordsRegex.globalMatch(expression); + + while (iterator.hasNext()) { + auto match = iterator.next(); + auto word = match.capturedView(); + if (auto modelNode = idModelNodeDict.value(word)) + dependencies.push_back({modelNode, property}); + } + } + + void operator()(const NodeMetaInfo &, const ModelNode &node) + { + for (const BindingProperty &property : node.bindingProperties()) + filterBindingProperty(property); + } + + void finally() { std::sort(dependencies.begin(), dependencies.end()); } + + BindingDependencies &dependencies; + QHash idModelNodeDict; + QRegularExpression wordsRegex; +}; + +struct TargetFilter +{ + TargetFilter(NodeDependencies &dependencies, Model *model) + : flowViewFlowActionAreaMetaInfo{model->flowViewFlowActionAreaMetaInfo()} + , flowViewFlowTransitionMetaInfo{model->flowViewFlowTransitionMetaInfo()} + , qtQuickPropertyChangesMetaInfo{model->qtQuickPropertyChangesMetaInfo()} + , qtQuickTimelineKeyframeGroupMetaInfo{model->qtQuickTimelineKeyframeGroupMetaInfo()} + , qtQuickPropertyAnimationMetaInfo{model->qtQuickPropertyAnimationMetaInfo()} + , dependencies{dependencies} + {} + + static std::optional resolveBinding(const ModelNode &node, + const PropertyName &propertyName) + { + auto property = node.bindingProperty(propertyName); + if (property.exists()) { + if (ModelNode targetNode = property.resolveToModelNode()) + return targetNode; + } + + return {}; + } + + bool hasTargetProperty(const NodeMetaInfo &metaInfo) const + { + return metaInfo.isBasedOn(qtQuickPropertyChangesMetaInfo, + qtQuickTimelineKeyframeGroupMetaInfo, + flowViewFlowActionAreaMetaInfo, + qtQuickPropertyAnimationMetaInfo); + } + + bool hasToOrFromProperty(const NodeMetaInfo &metaInfo) + { + return metaInfo.isBasedOn(flowViewFlowTransitionMetaInfo); + } + + void operator()(const NodeMetaInfo &metaInfo, const ModelNode &node) + { + if (hasTargetProperty(metaInfo)) { + if (auto targetNode = resolveBinding(node, "target")) + dependencies.push_back({std::move(*targetNode), node}); + } else if (hasToOrFromProperty(metaInfo)) { + if (auto toNode = resolveBinding(node, "to")) + dependencies.push_back({std::move(*toNode), node}); + if (auto fromNode = resolveBinding(node, "from")) + dependencies.push_back({std::move(*fromNode), node}); + } + } + + void finally() { std::sort(dependencies.begin(), dependencies.end()); } + + NodeMetaInfo flowViewFlowActionAreaMetaInfo; + NodeMetaInfo flowViewFlowTransitionMetaInfo; + NodeMetaInfo qtQuickPropertyChangesMetaInfo; + NodeMetaInfo qtQuickTimelineKeyframeGroupMetaInfo; + NodeMetaInfo qtQuickPropertyAnimationMetaInfo; + NodeDependencies &dependencies; +}; + +template +struct TargetsFilter +{ + TargetsFilter(Predicate predicate, + NodeDependencies &dependencies, + NodesProperties &targetsNodesProperties) + : predicate{std::move(predicate)} + , dependencies{dependencies} + , targetsNodesProperties{targetsNodesProperties} + {} + + static ModelNodes resolveTargets(const ModelNode &node) + { + auto targetProperty = node.bindingProperty("targets"); + if (targetProperty.exists()) + return targetProperty.resolveToModelNodeList(); + + return {}; + } + + void operator()(const NodeMetaInfo &metaInfo, const ModelNode &node) + { + if (predicate(metaInfo)) { + const auto targetNodes = resolveTargets(node); + if (targetNodes.size()) { + targetsNodesProperties.push_back({node, "targets", targetNodes}); + for (auto &&targetNode : targetNodes) + dependencies.push_back({targetNode, node}); + } + } + } + + void finally() + { + std::sort(dependencies.begin(), dependencies.end()); + std::sort(targetsNodesProperties.begin(), targetsNodesProperties.end()); + } + + Predicate predicate; + NodeDependencies &dependencies; + NodesProperties &targetsNodesProperties; +}; + +void addDependency(NameNodes &dependencies, const ModelNode &node, const PropertyName &propertyName) +{ + if (auto property = node.variantProperty(propertyName); property.exists()) { + QString stateName = property.value().toString(); + if (stateName.size() && stateName != "*") + dependencies.push_back({stateName, node}); + } +} + +struct StateFilter +{ + StateFilter(NameNodes &dependencies) + : dependencies{dependencies} + {} + + void operator()(const NodeMetaInfo &metaInfo, const ModelNode &node) + { + if (metaInfo.isQtQuickState()) + addDependency(dependencies, node, "name"); + } + + void finally() { std::sort(dependencies.begin(), dependencies.end()); } + + NameNodes &dependencies; +}; + +struct TransitionFilter +{ + TransitionFilter(NodeDependencies &dependencies, NameNodes &stateNodes) + : stateNodes{stateNodes} + , dependencies{dependencies} + {} + + void operator()(const NodeMetaInfo &metaInfo, const ModelNode &node) + { + if (metaInfo.isQtQuickTransition()) { + addDependency(transitionNodes, node, "to"); + addDependency(transitionNodes, node, "from"); + } + } + + void finally() + { + std::sort(transitionNodes.begin(), transitionNodes.end()); + + auto removeTransition = [&](const auto &first, const auto &second) { + dependencies.push_back({second.node, first.node}); + }; + + ::Utils::set_greedy_intersection_compare(transitionNodes.begin(), + transitionNodes.end(), + stateNodes.begin(), + stateNodes.end(), + removeTransition, + std::less{}); + std::sort(dependencies.begin(), dependencies.end()); + } + + NameNodes transitionNodes; + NameNodes &stateNodes; + NodeDependencies &dependencies; +}; + +DependenciesSet createDependenciesSet(Model *model) +{ + const ModelNodes nodes = model->allModelNodesUnordered(); + + DependenciesSet set; + NameNodes stateNames; + + auto flowViewFlowActionAreaMetaInfo = model->flowViewFlowActionAreaMetaInfo(); + auto flowViewFlowDecisionMetaInfo = model->flowViewFlowDecisionMetaInfo(); + auto flowViewFlowWildcardMetaInfo = model->flowViewFlowWildcardMetaInfo(); + auto qtQuickPropertyChangesMetaInfo = model->qtQuickPropertyChangesMetaInfo(); + auto qtQuickTimelineKeyframeGroupMetaInfo = model->qtQuickTimelineKeyframeGroupMetaInfo(); + auto qtQuickPropertyAnimationMetaInfo = model->qtQuickPropertyAnimationMetaInfo(); + + auto filters = std::make_tuple( + TargetFilter{set.nodeDependencies, model}, + TargetsFilter{[&](auto &&metaInfo) { + return metaInfo.isBasedOn(flowViewFlowDecisionMetaInfo, + flowViewFlowWildcardMetaInfo, + qtQuickPropertyAnimationMetaInfo); + }, + set.targetsDependencies, + set.targetsNodesProperties}, + StateFilter{stateNames}, + TransitionFilter{set.nodeDependencies, stateNames}, + BindingFilter{set.bindingDependencies, model}); + + for (const ModelNode &node : nodes) { + auto metaInfo = node.metaInfo(); + std::apply([&](auto &&...filter) { (filter(metaInfo, node), ...); }, filters); + } + + std::apply([&](auto &&...filter) { (filter.finally(), ...); }, filters); + + return set; +} + +using NodeActionsTuple = std::tuple; + +class NodeActions : public NodeActionsTuple +{ + NodeActions(const NodeActions &) = delete; + NodeActions &opertor(const NodeActions &) = delete; + NodeActions(NodeActions &&) = delete; + NodeActions &opertor(NodeActions &&) = delete; + + using NodeActionsTuple::NodeActionsTuple; +}; + +template +void forEachAction(NodeActions &nodeActions, ActionCall actionCall) +{ + std::apply([&](auto &...action) { (actionCall(action), ...); }, + static_cast(nodeActions)); +} + +} // namespace + +ModelResourceSet ModelResourceManagement::removeNodes(ModelNodes nodes, Model *model) const +{ + std::sort(nodes.begin(), nodes.end()); + + ModelResourceSet resourceSet; + + DependenciesSet set = createDependenciesSet(model); + + NodeActions nodeActions = { + CheckChildNodes{resourceSet, nodeActions}, + CheckNodesInNodeAbstractProperties{resourceSet, nodeActions}, + RemoveLayerEnabled{resourceSet, nodeActions}, + RemoveDependentBindings{resourceSet, nodeActions, std::move(set.bindingDependencies)}, + RemoveDependencies{resourceSet, nodeActions, std::move(set.nodeDependencies)}, + RemoveTargetsSources{resourceSet, + nodeActions, + std::move(set.targetsDependencies), + std::move(set.targetsNodesProperties)}}; + + Base{resourceSet, nodeActions}.removeNodes(nodes, CheckRecursive::Yes); + + forEachAction(nodeActions, [&](auto &action) { action.finally(); }); + + return resourceSet; +} + +ModelResourceSet ModelResourceManagement::removeProperties(AbstractProperties properties, + Model *model) const +{ + std::sort(properties.begin(), properties.end()); + + ModelResourceSet resourceSet; + + DependenciesSet set = createDependenciesSet(model); + + NodeActions nodeActions = { + CheckChildNodes{resourceSet, nodeActions}, + CheckNodesInNodeAbstractProperties{resourceSet, nodeActions}, + RemoveLayerEnabled{resourceSet, nodeActions}, + RemoveDependentBindings{resourceSet, nodeActions, std::move(set.bindingDependencies)}, + RemoveDependencies{resourceSet, nodeActions, std::move(set.nodeDependencies)}, + RemoveTargetsSources{resourceSet, + nodeActions, + std::move(set.targetsDependencies), + std::move(set.targetsNodesProperties)}}; + + Base{resourceSet, nodeActions}.removeProperties(properties, CheckRecursive::Yes); + + forEachAction(nodeActions, [&](auto &action) { action.finally(); }); + + return resourceSet; +} + +} // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/designercore/model/modelresourcemanagement.h b/src/plugins/qmldesigner/designercore/model/modelresourcemanagement.h new file mode 100644 index 00000000000..4d505047263 --- /dev/null +++ b/src/plugins/qmldesigner/designercore/model/modelresourcemanagement.h @@ -0,0 +1,20 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +#pragma once + +#include "modelresourcemanagementinterface.h" + +#include +#include + +namespace QmlDesigner { + +class ModelResourceManagement final : public ModelResourceManagementInterface +{ +public: + ModelResourceSet removeNodes(ModelNodes nodes, Model *model) const override; + ModelResourceSet removeProperties(AbstractProperties properties, Model *model) const override; +}; + +} // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/designercore/model/modelresourcemanagementfwd.h b/src/plugins/qmldesigner/designercore/model/modelresourcemanagementfwd.h new file mode 100644 index 00000000000..4031fdd9189 --- /dev/null +++ b/src/plugins/qmldesigner/designercore/model/modelresourcemanagementfwd.h @@ -0,0 +1,27 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +#pragma once + +#include "../include/qmldesignercorelib_exports.h" + +#include + +namespace QmlDesigner { + +struct ModelResourceSet +{ + struct SetExpression + { + BindingProperty property; + QString expression; + }; + + using SetExpressions = QList; + + QList removeModelNodes; + QList removeProperties; + QList setExpressions; +}; + +} // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/designercore/model/modelresourcemanagementinterface.h b/src/plugins/qmldesigner/designercore/model/modelresourcemanagementinterface.h index b2188132d6a..94047d95b0d 100644 --- a/src/plugins/qmldesigner/designercore/model/modelresourcemanagementinterface.h +++ b/src/plugins/qmldesigner/designercore/model/modelresourcemanagementinterface.h @@ -5,23 +5,13 @@ #include +#include "modelresourcemanagementfwd.h" + #include +#include namespace QmlDesigner { -struct ModelResourceSet -{ - struct SetExpression - { - BindingProperty property; - QString expression; - }; - - QList removeModelNodes; - QList removeProperties; - QList setExpressions; -}; - class QMLDESIGNERCORE_EXPORT ModelResourceManagementInterface { public: @@ -33,7 +23,7 @@ public: ModelResourceManagementInterface(ModelResourceManagementInterface &&) = default; ModelResourceManagementInterface &operator=(ModelResourceManagementInterface &&) = default; - virtual ModelResourceSet removeNode(const ModelNode &node) const = 0; - virtual ModelResourceSet removeProperty(const AbstractProperty &property) const = 0; + virtual ModelResourceSet removeNodes(ModelNodes nodes, Model *model) const = 0; + virtual ModelResourceSet removeProperties(AbstractProperties properties, Model *model) const = 0; }; } // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/designercore/model/modelutils.cpp b/src/plugins/qmldesigner/designercore/model/modelutils.cpp index 2e454527b88..70da6f98b9c 100644 --- a/src/plugins/qmldesigner/designercore/model/modelutils.cpp +++ b/src/plugins/qmldesigner/designercore/model/modelutils.cpp @@ -3,11 +3,13 @@ #include "modelutils.h" +#include + #include #include -namespace QmlDesigner::Utils { +namespace QmlDesigner::ModelUtils { namespace { @@ -90,4 +92,14 @@ bool addImportsWithCheck(const QStringList &importNames, return true; } -} // namespace QmlDesigner::Utils +PropertyMetaInfo metainfo(const AbstractProperty &property) +{ + return metainfo(property.parentModelNode(), property.name()); +} + +PropertyMetaInfo metainfo(const ModelNode &node, const PropertyName &propertyName) +{ + return node.metaInfo().property(propertyName); +} + +} // namespace QmlDesigner::ModelUtils diff --git a/src/plugins/qmldesigner/designercore/model/modelutils.h b/src/plugins/qmldesigner/designercore/model/modelutils.h index 58055f39065..578a7adb444 100644 --- a/src/plugins/qmldesigner/designercore/model/modelutils.h +++ b/src/plugins/qmldesigner/designercore/model/modelutils.h @@ -10,7 +10,11 @@ #include -namespace QmlDesigner::Utils { +namespace QmlDesigner { +class PropertyMetaInfo; +} + +namespace QmlDesigner::ModelUtils { QMLDESIGNERCORE_EXPORT bool addImportsWithCheck(const QStringList &importNames, const std::function &predicate, @@ -21,4 +25,8 @@ QMLDESIGNERCORE_EXPORT bool addImportWithCheck(const QString &importName, Model *model); QMLDESIGNERCORE_EXPORT bool addImportWithCheck(const QString &importName, Model *model); -} // namespace QmlDesigner::Utils +QMLDESIGNERCORE_EXPORT PropertyMetaInfo metainfo(const AbstractProperty &property); +QMLDESIGNERCORE_EXPORT PropertyMetaInfo metainfo(const ModelNode &node, + const PropertyName &propertyName); + +} // namespace QmlDesigner::ModelUtils diff --git a/src/plugins/qmldesigner/designercore/model/nodeabstractproperty.cpp b/src/plugins/qmldesigner/designercore/model/nodeabstractproperty.cpp index 60b4e77dc6d..0688ff1c256 100644 --- a/src/plugins/qmldesigner/designercore/model/nodeabstractproperty.cpp +++ b/src/plugins/qmldesigner/designercore/model/nodeabstractproperty.cpp @@ -70,16 +70,16 @@ void NodeAbstractProperty::reparentHere(const ModelNode &modelNode, bool isNode if (modelNode.hasParentProperty() && modelNode.parentProperty().isDynamic()) return; - if (internalNode()->hasProperty(name()) && !internalNode()->property(name())->isNodeAbstractProperty()) - privateModel()->removePropertyAndRelatedResources(internalNode()->property(name())); + auto internalProperty = internalNode()->property(name()); + if (internalProperty && !internalProperty->isNodeAbstractProperty()) + privateModel()->removePropertyAndRelatedResources(internalProperty); if (modelNode.hasParentProperty()) { Internal::InternalNodeAbstractProperty::Pointer oldParentProperty = modelNode.internalNode()->parentProperty(); privateModel()->reparentNode(internalNode(), name(), modelNode.internalNode(), isNodeList, dynamicTypeName); - Q_ASSERT(!oldParentProperty.isNull()); - + Q_ASSERT(oldParentProperty); } else { privateModel()->reparentNode(internalNode(), name(), modelNode.internalNode(), isNodeList, dynamicTypeName); @@ -91,7 +91,7 @@ bool NodeAbstractProperty::isEmpty() const if (isValid()) { Internal::InternalNodeAbstractProperty::Pointer property = internalNode()->nodeAbstractProperty( name()); - if (property.isNull()) + if (!property) return true; else return property->isEmpty(); @@ -105,7 +105,7 @@ int NodeAbstractProperty::indexOf(const ModelNode &node) const if (isValid()) { Internal::InternalNodeAbstractProperty::Pointer property = internalNode()->nodeAbstractProperty( name()); - if (property.isNull()) + if (!property) return 0; return property->indexOf(node.internalNode()); @@ -119,7 +119,7 @@ NodeAbstractProperty NodeAbstractProperty::parentProperty() const if (!isValid()) return {}; - if (internalNode()->parentProperty().isNull()) + if (!internalNode()->parentProperty()) return {}; return NodeAbstractProperty(internalNode()->parentProperty()->name(), internalNode()->parentProperty()->propertyOwner(), model(), view()); @@ -128,7 +128,7 @@ NodeAbstractProperty NodeAbstractProperty::parentProperty() const int NodeAbstractProperty::count() const { Internal::InternalNodeAbstractProperty::Pointer property = internalNode()->nodeAbstractProperty(name()); - if (property.isNull()) + if (!property) return 0; else return property->count(); @@ -141,7 +141,7 @@ QList NodeAbstractProperty::allSubNodes() return {}; Internal::InternalNodeAbstractProperty::Pointer property = internalNode()->nodeAbstractProperty(name()); - return QmlDesigner::toModelNodeList(property->allSubNodes(), view()); + return QmlDesigner::toModelNodeList(property->allSubNodes(), model(), view()); } QList NodeAbstractProperty::directSubNodes() const @@ -151,7 +151,7 @@ QList NodeAbstractProperty::directSubNodes() const return {}; Internal::InternalNodeAbstractProperty::Pointer property = internalNode()->nodeAbstractProperty(name()); - return QmlDesigner::toModelNodeList(property->directSubNodes(), view()); + return QmlDesigner::toModelNodeList(property->directSubNodes(), model(), view()); } /*! diff --git a/src/plugins/qmldesigner/designercore/model/nodelistproperty.cpp b/src/plugins/qmldesigner/designercore/model/nodelistproperty.cpp index 5f36efc6185..0822786467e 100644 --- a/src/plugins/qmldesigner/designercore/model/nodelistproperty.cpp +++ b/src/plugins/qmldesigner/designercore/model/nodelistproperty.cpp @@ -15,6 +15,9 @@ namespace QmlDesigner { Internal::NodeListPropertyIterator::value_type Internal::NodeListPropertyIterator::operator*() const { + if (!m_nodeListProperty) + return {}; + return {m_nodeListProperty->at(m_currentIndex), m_model, m_view}; } @@ -41,11 +44,9 @@ Internal::InternalNodeListPropertyPointer &NodeListProperty::internalNodeListPro if (m_internalNodeListProperty) return m_internalNodeListProperty; - if (internalNode()->hasProperty(name())) { - Internal::InternalProperty::Pointer internalProperty = internalNode()->property(name()); - if (internalProperty->isNodeListProperty()) - m_internalNodeListProperty = internalProperty->toNodeListProperty(); - } + auto internalProperty = internalNode()->nodeListProperty(name()); + if (internalProperty) + m_internalNodeListProperty = internalProperty; return m_internalNodeListProperty; } @@ -65,9 +66,7 @@ QList NodeListProperty::toModelNodeList() const return {}; if (internalNodeListProperty()) - return internalNodesToModelNodes(m_internalNodeListProperty->toNodeListProperty()->nodeList(), - model(), - view()); + return internalNodesToModelNodes(m_internalNodeListProperty->nodeList(), model(), view()); return QList(); } @@ -162,7 +161,7 @@ NodeListProperty::iterator NodeListProperty::rotate(NodeListProperty::iterator f privateModel()->notifyNodeOrderChanged(m_internalNodeListProperty); - return {iter - begin, internalNodeListProperty().data(), model(), view()}; + return {iter - begin, internalNodeListProperty().get(), model(), view()}; } void NodeListProperty::reverse(NodeListProperty::iterator first, NodeListProperty::iterator last) @@ -212,15 +211,21 @@ Internal::NodeListPropertyIterator NodeListProperty::end() Internal::NodeListPropertyIterator NodeListProperty::begin() const { - return {0, internalNodeListProperty().data(), model(), view()}; + if (!isValid()) + return {}; + + return {0, internalNodeListProperty().get(), model(), view()}; } Internal::NodeListPropertyIterator NodeListProperty::end() const { + if (!isValid()) + return {}; + auto nodeListProperty = internalNodeListProperty(); auto size = nodeListProperty ? nodeListProperty->size() : 0; - return {size, nodeListProperty.data(), model(), view()}; + return {size, nodeListProperty.get(), model(), view()}; } } // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/designercore/model/nodeproperty.cpp b/src/plugins/qmldesigner/designercore/model/nodeproperty.cpp index 4af8428e6be..a628c96b7d2 100644 --- a/src/plugins/qmldesigner/designercore/model/nodeproperty.cpp +++ b/src/plugins/qmldesigner/designercore/model/nodeproperty.cpp @@ -24,11 +24,10 @@ void NodeProperty::setModelNode(const ModelNode &modelNode) if (!modelNode.isValid()) return; - if (internalNode()->hasProperty(name())) { //check if oldValue != value - Internal::InternalProperty::Pointer internalProperty = internalNode()->property(name()); - if (internalProperty->isNodeProperty() - && internalProperty->toNodeProperty()->node() == modelNode.internalNode()) - return; + auto internalProperty = internalNode()->nodeProperty(name()); + if (internalProperty + && internalProperty->node() == modelNode.internalNode()) { //check if oldValue != value + return; } if (internalNode()->hasProperty(name()) && !internalNode()->property(name())->isNodeProperty()) @@ -42,11 +41,9 @@ ModelNode NodeProperty::modelNode() const if (!isValid()) return {}; - if (internalNode()->hasProperty(name())) { //check if oldValue != value - Internal::InternalProperty::Pointer internalProperty = internalNode()->property(name()); - if (internalProperty->isNodeProperty()) - return ModelNode(internalProperty->toNodeProperty()->node(), model(), view()); - } + auto internalProperty = internalNode()->nodeProperty(name()); + if (internalProperty) //check if oldValue != value + return ModelNode(internalProperty->node(), model(), view()); return ModelNode(); } diff --git a/src/plugins/qmldesigner/designercore/model/propertycontainer.cpp b/src/plugins/qmldesigner/designercore/model/propertycontainer.cpp index 8cd55cac4b9..cd7cebbb73a 100644 --- a/src/plugins/qmldesigner/designercore/model/propertycontainer.cpp +++ b/src/plugins/qmldesigner/designercore/model/propertycontainer.cpp @@ -41,7 +41,7 @@ PropertyName PropertyContainer::name() const QVariant PropertyContainer::value() const { - if (m_value.type() == QVariant::String) + if (m_value.typeId() == QVariant::String) m_value = PropertyParser::read(m_type, m_value.toString()); return m_value; } diff --git a/src/plugins/qmldesigner/designercore/model/qml3dnode.cpp b/src/plugins/qmldesigner/designercore/model/qml3dnode.cpp index e8d3aa15569..4db2567e36d 100644 --- a/src/plugins/qmldesigner/designercore/model/qml3dnode.cpp +++ b/src/plugins/qmldesigner/designercore/model/qml3dnode.cpp @@ -41,26 +41,15 @@ bool Qml3DNode::isValidVisualRoot(const ModelNode &modelNode) && (modelNode.metaInfo().isQtQuick3DNode() || modelNode.metaInfo().isQtQuick3DMaterial()); } -void Qml3DNode::setVariantProperty(const PropertyName &name, const QVariant &value) +bool Qml3DNode::handleEulerRotation(const PropertyName &name) { if (isBlocked(name)) - return; + return false; if (name.startsWith("eulerRotation")) handleEulerRotationSet(); - QmlObjectNode::setVariantProperty(name, value); -} - -void Qml3DNode::setBindingProperty(const PropertyName &name, const QString &expression) -{ - if (isBlocked(name)) - return; - - if (name.startsWith("eulerRotation")) - handleEulerRotationSet(); - - QmlObjectNode::setBindingProperty(name, expression); + return true; } bool Qml3DNode::isBlocked(const PropertyName &propName) const diff --git a/src/plugins/qmldesigner/designercore/model/qmlchangeset.cpp b/src/plugins/qmldesigner/designercore/model/qmlchangeset.cpp index 134c4bf1c20..889a5a38650 100644 --- a/src/plugins/qmldesigner/designercore/model/qmlchangeset.cpp +++ b/src/plugins/qmldesigner/designercore/model/qmlchangeset.cpp @@ -85,7 +85,7 @@ void QmlPropertyChanges::removeProperty(const PropertyName &name) if (name == "name") return; modelNode().removeProperty(name); - if (modelNode().variantProperties().isEmpty() && modelNode().bindingProperties().count() < 2) + if (modelNode().variantProperties().isEmpty() && modelNode().bindingProperties().size() < 2) modelNode().destroy(); } diff --git a/src/plugins/qmldesigner/designercore/model/qmlitemnode.cpp b/src/plugins/qmldesigner/designercore/model/qmlitemnode.cpp index 2c990a50364..175d3291183 100644 --- a/src/plugins/qmldesigner/designercore/model/qmlitemnode.cpp +++ b/src/plugins/qmldesigner/designercore/model/qmlitemnode.cpp @@ -309,7 +309,7 @@ bool QmlItemNode::instanceHasShowContent() const bool QmlItemNode::instanceCanReparent() const { - return QmlObjectNode::instanceCanReparent() && !anchors().instanceHasAnchors() && !instanceIsAnchoredBySibling(); + return isInBaseState() && !anchors().instanceHasAnchors() && !instanceIsAnchoredBySibling(); } bool QmlItemNode::instanceIsAnchoredBySibling() const diff --git a/src/plugins/qmldesigner/designercore/model/qmlobjectnode.cpp b/src/plugins/qmldesigner/designercore/model/qmlobjectnode.cpp index 0a7039ff130..b2694b9951d 100644 --- a/src/plugins/qmldesigner/designercore/model/qmlobjectnode.cpp +++ b/src/plugins/qmldesigner/designercore/model/qmlobjectnode.cpp @@ -14,6 +14,7 @@ #include "qmlstate.h" #include "qmltimelinekeyframegroup.h" #include "qmlvisualnode.h" +#include "stringutils.h" #include "variantproperty.h" #include @@ -34,6 +35,9 @@ void QmlObjectNode::setVariantProperty(const PropertyName &name, const QVariant if (!isValid()) return; + if (metaInfo().isQtQuick3DNode() && !Qml3DNode(modelNode()).handleEulerRotation(name)) + return; + if (timelineIsActive() && currentTimeline().isRecording()) { modelNode().validId(); @@ -78,6 +82,9 @@ void QmlObjectNode::setBindingProperty(const PropertyName &name, const QString & if (!isValid()) return; + if (metaInfo().isQtQuick3DNode() && !Qml3DNode(modelNode()).handleEulerRotation(name)) + return; + if (isInBaseState()) { modelNode().bindingProperty(name).setExpression(expression); //basestate } else { @@ -250,7 +257,7 @@ QString QmlObjectNode::stripedTranslatableText(const PropertyName &name) const const QRegularExpressionMatch match = regularExpressionPattern.match( modelNode().bindingProperty(name).expression()); if (match.hasMatch()) - return match.captured(2); + return deescape(match.captured(2)); return instanceValue(name).toString(); } return instanceValue(name).toString(); @@ -295,7 +302,10 @@ bool QmlObjectNode::timelineIsActive() const bool QmlObjectNode::instanceCanReparent() const { - return isInBaseState(); + if (auto qmlItemNode = QmlItemNode{modelNode()}) + return qmlItemNode.instanceCanReparent(); + else + return isInBaseState(); } QmlPropertyChanges QmlObjectNode::propertyChangeForCurrentState() const @@ -312,102 +322,6 @@ QmlPropertyChanges QmlObjectNode::propertyChangeForCurrentState() const return currentState().propertyChanges(modelNode()); } -static void removeStateOperationsForChildren(const QmlObjectNode &node) -{ - if (node.isValid()) { - for (QmlModelStateOperation stateOperation : node.allAffectingStatesOperations()) { - stateOperation.modelNode().destroy(); //remove of belonging StatesOperations - } - - for (const QmlObjectNode childNode : node.modelNode().directSubModelNodes()) { - removeStateOperationsForChildren(childNode); - } - } -} - -static void removeAnimationsFromAnimation(const ModelNode &animation) -{ - QTC_ASSERT(animation.isValid(), return ); - - auto model = animation.model(); - const QList propertyAnimations = animation.subModelNodesOfType( - model->qtQuickPropertyAnimationMetaInfo()); - - for (const ModelNode &child : propertyAnimations) { - if (!child.hasBindingProperty("target")) { - ModelNode nonConst = animation; - nonConst.destroy(); - return; - } - } -} - -static void removeAnimationsFromTransition(const ModelNode &transition, const QmlObjectNode &node) -{ - QTC_ASSERT(node.isValid(), return); - QTC_ASSERT(transition.isValid(), return); - - const auto children = transition.directSubModelNodes(); - for (const ModelNode ¶llel : children) - removeAnimationsFromAnimation(parallel); -} - -static void removeDanglingAnimationsFromTransitions(const QmlObjectNode &node) -{ - QTC_ASSERT(node.isValid(), return); - - auto root = node.view()->rootModelNode(); - - if (root.isValid() && root.hasProperty("transitions")) { - NodeAbstractProperty transitions = root.nodeAbstractProperty("transitions"); - if (transitions.isValid()) { - const auto transitionNodes = transitions.directSubNodes(); - for (const auto &transition : transitionNodes) - removeAnimationsFromTransition(transition, node); - } - } -} - -static void removeAliasExports(const QmlObjectNode &node) -{ - - PropertyName propertyName = node.id().toUtf8(); - - ModelNode rootNode = node.view()->rootModelNode(); - bool hasAliasExport = !propertyName.isEmpty() - && rootNode.isValid() - && rootNode.hasBindingProperty(propertyName) - && rootNode.bindingProperty(propertyName).isAliasExport(); - - if (hasAliasExport) - rootNode.removeProperty(propertyName); - - - const QList nodes = node.modelNode().directSubModelNodes(); - for (const ModelNode &childNode : nodes) { - removeAliasExports(childNode); - } - -} - -static void removeLayerEnabled(const ModelNode &node) -{ - QTC_ASSERT(node.isValid(), return ); - if (node.parentProperty().isValid() && node.parentProperty().name() == "layer.effect") { - ModelNode parent = node.parentProperty().parentModelNode(); - if (parent.isValid() && parent.hasProperty("layer.enabled")) - parent.removeProperty("layer.enabled"); - } -} - -static void deleteAllReferencesToNodeAndChildren(const ModelNode &node) -{ - BindingProperty::deleteAllReferencesTo(node); - const auto subNodes = node.allSubModelNodes(); - for (const ModelNode &child : subNodes) - BindingProperty::deleteAllReferencesTo(child); -} - /*! Deletes this object's node and its dependencies from the model. Everything that belongs to this Object, the ModelNode, and ChangeOperations @@ -415,47 +329,7 @@ static void deleteAllReferencesToNodeAndChildren(const ModelNode &node) */ void QmlObjectNode::destroy() { - if (!isValid()) - return; - - removeLayerEnabled(modelNode()); - removeAliasExports(modelNode()); - - for (QmlModelStateOperation stateOperation : allAffectingStatesOperations()) { - stateOperation.modelNode().destroy(); //remove of belonging StatesOperations - } - - QVector timelineNodes; - const auto allNodes = view()->allModelNodes(); - for (const auto &timelineNode : allNodes) { - if (QmlTimeline::isValidQmlTimeline(timelineNode)) - timelineNodes.append(timelineNode); - } - - const auto subNodes = modelNode().allSubModelNodesAndThisNode(); - for (auto &timelineNode : std::as_const(timelineNodes)) { - QmlTimeline timeline(timelineNode); - for (const auto &subNode : subNodes) - timeline.destroyKeyframesForTarget(subNode); - } - - bool wasFlowEditorTarget = false; - if (QmlFlowTargetNode::isFlowEditorTarget(modelNode())) { - QmlFlowTargetNode(modelNode()).destroyTargets(); - wasFlowEditorTarget = true; - } - - removeStateOperationsForChildren(modelNode()); - deleteAllReferencesToNodeAndChildren(modelNode()); - - removeDanglingAnimationsFromTransitions(modelNode()); - - QmlFlowViewNode root(view()->rootModelNode()); - modelNode().destroy(); - - if (wasFlowEditorTarget && root.isValid()) - root.removeDanglingTransitions(); } void QmlObjectNode::ensureAliasExport() @@ -525,7 +399,7 @@ QList QmlObjectNode::allAffectingStatesOperations() cons return returnList; } -static QList allQmlVisualNodesRecursive(const QmlItemNode &qmlItemNode) +static QList allQmlVisualNodesRecursive(const QmlVisualNode &qmlItemNode) { QList qmlVisualNodeList; @@ -663,15 +537,17 @@ QVariant QmlObjectNode::instanceValue(const ModelNode &modelNode, const Property QString QmlObjectNode::generateTranslatableText([[maybe_unused]] const QString &text, const DesignerSettings &settings) { + const QString escapedText = escape(text); + if (settings.value(DesignerSettingsKey::TYPE_OF_QSTR_FUNCTION).toInt()) switch (settings.value(DesignerSettingsKey::TYPE_OF_QSTR_FUNCTION).toInt()) { - case 0: return QString(QStringLiteral("qsTr(\"%1\")")).arg(text); - case 1: return QString(QStringLiteral("qsTrId(\"%1\")")).arg(text); - case 2: return QString(QStringLiteral("qsTranslate(\"%1\", \"context\")")).arg(text); + case 0: return QString(QStringLiteral("qsTr(\"%1\")")).arg(escapedText); + case 1: return QString(QStringLiteral("qsTrId(\"%1\")")).arg(escapedText); + case 2: return QString(QStringLiteral("qsTranslate(\"%1\", \"context\")")).arg(escapedText); default: break; } - return QString(QStringLiteral("qsTr(\"%1\")")).arg(text); + return QString(QStringLiteral("qsTr(\"%1\")")).arg(escapedText); } QString QmlObjectNode::stripedTranslatableTextFunction(const QString &text) @@ -680,7 +556,7 @@ QString QmlObjectNode::stripedTranslatableTextFunction(const QString &text) QLatin1String("^qsTr(|Id|anslate)\\(\"(.*)\"\\)$")); const QRegularExpressionMatch match = regularExpressionPattern.match(text); if (match.hasMatch()) - return match.captured(2); + return deescape(match.captured(2)); return text; } @@ -837,19 +713,4 @@ QStringList QmlObjectNode::allStateNames() const return nodeInstance().allStateNames(); } -QmlObjectNode *QmlObjectNode::getQmlObjectNodeOfCorrectType(const ModelNode &modelNode) -{ - // Create QmlObjectNode of correct type for the modelNode - // Note: Currently we are only interested in differentiating 3D nodes, so no check for - // visual nodes is done for efficiency reasons - if (modelNode.isValid() && modelNode.metaInfo().isQtQuick3DNode()) - return new Qml3DNode(modelNode); - return new QmlObjectNode(modelNode); -} - -bool QmlObjectNode::isBlocked([[maybe_unused]] const PropertyName &propName) const -{ - return false; -} - } //QmlDesigner diff --git a/src/plugins/qmldesigner/designercore/model/qmltextgenerator.cpp b/src/plugins/qmldesigner/designercore/model/qmltextgenerator.cpp index af9b6a24252..e5721d21c32 100644 --- a/src/plugins/qmldesigner/designercore/model/qmltextgenerator.cpp +++ b/src/plugins/qmldesigner/designercore/model/qmltextgenerator.cpp @@ -3,19 +3,20 @@ #include "qmltextgenerator.h" -#include #include -#include -#include +#include #include +#include +#include #include "bindingproperty.h" -#include "signalhandlerproperty.h" -#include "nodeproperty.h" +#include "model.h" #include "nodelistproperty.h" +#include "nodeproperty.h" +#include "signalhandlerproperty.h" +#include "stringutils.h" #include "variantproperty.h" #include -#include "model.h" using namespace QmlDesigner; using namespace QmlDesigner::Internal; @@ -114,14 +115,10 @@ QString QmlTextGenerator::toQml(const AbstractProperty &property, int indentDept if (property.name() == "id") return stringValue; - - if (false) { - } if (variantProperty.holdsEnumeration()) { return variantProperty.enumeration().toString(); } else { - - switch (value.userType()) { + switch (value.typeId()) { case QMetaType::Bool: if (value.toBool()) return QStringLiteral("true"); @@ -284,20 +281,3 @@ QString QmlTextGenerator::propertyToQml(const AbstractProperty &property, int in return result; } - -QString QmlTextGenerator::escape(const QString &value) -{ - QString result = value; - - if (value.size() == 6 && value.startsWith("\\u")) //Do not dobule escape unicode chars - return result; - - result.replace(QStringLiteral("\\"), QStringLiteral("\\\\")); - - result.replace(QStringLiteral("\""), QStringLiteral("\\\"")); - result.replace(QStringLiteral("\t"), QStringLiteral("\\t")); - result.replace(QStringLiteral("\r"), QStringLiteral("\\r")); - result.replace(QStringLiteral("\n"), QStringLiteral("\\n")); - - return result; -} diff --git a/src/plugins/qmldesigner/designercore/model/qmltextgenerator.h b/src/plugins/qmldesigner/designercore/model/qmltextgenerator.h index 6b114ebe1bf..971d6a2d1d0 100644 --- a/src/plugins/qmldesigner/designercore/model/qmltextgenerator.h +++ b/src/plugins/qmldesigner/designercore/model/qmltextgenerator.h @@ -32,8 +32,6 @@ private: QString propertiesToQml(const ModelNode &node, int indentDepth) const; QString propertyToQml(const AbstractProperty &property, int indentDepth) const; - static QString escape(const QString &value); - private: PropertyNameList m_propertyOrder; TextEditor::TabSettings m_tabSettings; diff --git a/src/plugins/qmldesigner/designercore/model/qmlvisualnode.cpp b/src/plugins/qmldesigner/designercore/model/qmlvisualnode.cpp index 3831a90d97c..2bfbe860314 100644 --- a/src/plugins/qmldesigner/designercore/model/qmlvisualnode.cpp +++ b/src/plugins/qmldesigner/designercore/model/qmlvisualnode.cpp @@ -417,6 +417,20 @@ QmlObjectNode QmlVisualNode::createQmlObjectNode(AbstractView *view, newQmlObjectNode.setBindingProperty(property, parent.validId()); } + const QStringList copyFiles = itemLibraryEntry.extraFilePaths(); + if (!copyFiles.isEmpty()) { + // Files are copied into the same directory as the current qml document + for (const auto ©FileStr : copyFiles) { + Utils::FilePath sourceFile = Utils::FilePath::fromString(copyFileStr); + Utils::FilePath qmlFilePath = Utils::FilePath::fromString( + view->model()->fileUrl().toLocalFile()).absolutePath(); + Utils::FilePath targetFile = qmlFilePath.pathAppended(sourceFile.fileName()); + // We don't want to overwrite existing default files + if (!targetFile.exists() && !sourceFile.copyFile(targetFile)) + qWarning() << QStringLiteral("Copying extra file '%1' failed.").arg(copyFileStr); + } + } + return newQmlObjectNode; } diff --git a/src/plugins/qmldesigner/designercore/model/rewriterview.cpp b/src/plugins/qmldesigner/designercore/model/rewriterview.cpp index 53a0f4de596..60067a6bc91 100644 --- a/src/plugins/qmldesigner/designercore/model/rewriterview.cpp +++ b/src/plugins/qmldesigner/designercore/model/rewriterview.cpp @@ -88,9 +88,6 @@ void RewriterView::modelAttached(Model *model) { m_modelAttachPending = false; - if (model && model->textModifier()) - setTextModifier(model->textModifier()); - AbstractView::modelAttached(model); ModelAmender differenceHandler(m_textToModelMerger.data()); @@ -954,12 +951,12 @@ const QmlJS::Document *RewriterView::document() const return textToModelMerger()->document(); } -static inline QString getUrlFromType(const QString& typeName) +inline static QString getUrlFromType(const QString &typeName) { QStringList nameComponents = typeName.split('.'); QString result; - for (int i = 0; i < (nameComponents.count() - 1); i++) { + for (int i = 0; i < (nameComponents.size() - 1); i++) { result += nameComponents.at(i); } diff --git a/src/plugins/qmldesigner/designercore/model/signalhandlerproperty.cpp b/src/plugins/qmldesigner/designercore/model/signalhandlerproperty.cpp index 4690044fa61..a260a2a0ef9 100644 --- a/src/plugins/qmldesigner/designercore/model/signalhandlerproperty.cpp +++ b/src/plugins/qmldesigner/designercore/model/signalhandlerproperty.cpp @@ -32,22 +32,24 @@ void SignalHandlerProperty::setSource(const QString &source) if (source.isEmpty()) return; - if (internalNode()->hasProperty(name())) { //check if oldValue != value - Internal::InternalProperty::Pointer internalProperty = internalNode()->property(name()); - if (internalProperty->isSignalHandlerProperty() - && internalProperty->toSignalHandlerProperty()->source() == source) - + if (auto internalProperty = internalNode()->property(name())) { + auto signalHandlerProperty = internalProperty->to(); + //check if oldValue != value + if (signalHandlerProperty && signalHandlerProperty->source() == source) return; - } - if (internalNode()->hasProperty(name()) && !internalNode()->property(name())->isSignalHandlerProperty()) - privateModel()->removePropertyAndRelatedResources(internalNode()->property(name())); + if (!signalHandlerProperty) + privateModel()->removePropertyAndRelatedResources(internalProperty); + } privateModel()->setSignalHandlerProperty(internalNode(), name(), source); } QString SignalHandlerProperty::source() const { + if (!isValid()) + return {}; + if (internalNode()->hasProperty(name()) && internalNode()->property(name())->isSignalHandlerProperty()) return internalNode()->signalHandlerProperty(name())->source(); @@ -109,23 +111,25 @@ void SignalDeclarationProperty::setSignature(const QString &signature) if (signature.isEmpty()) return; - if (internalNode()->hasProperty(name())) { //check if oldValue != value - Internal::InternalProperty::Pointer internalProperty = internalNode()->property(name()); - if (internalProperty->isSignalDeclarationProperty() - && internalProperty->toSignalDeclarationProperty()->signature() == signature) - + if (auto internalProperty = internalNode()->property(name())) { + auto signalDeclarationProperty = internalProperty->to(); + //check if oldValue != value + if (signalDeclarationProperty && signalDeclarationProperty->signature() == signature) return; - } - if (internalNode()->hasProperty(name()) && !internalNode()->property(name())->isSignalDeclarationProperty()) - privateModel()->removePropertyAndRelatedResources(internalNode()->property(name())); + if (!signalDeclarationProperty) + privateModel()->removePropertyAndRelatedResources(internalProperty); + } privateModel()->setSignalDeclarationProperty(internalNode(), name(), signature); } QString SignalDeclarationProperty::signature() const { - if (internalNode() && internalNode()->hasProperty(name()) + if (!isValid()) + return {}; + + if (internalNode()->hasProperty(name()) && internalNode()->property(name())->isSignalDeclarationProperty()) return internalNode()->signalDeclarationProperty(name())->signature(); diff --git a/src/plugins/qmldesigner/designercore/model/texttomodelmerger.cpp b/src/plugins/qmldesigner/designercore/model/texttomodelmerger.cpp index 3b5df397eab..3108e26a618 100644 --- a/src/plugins/qmldesigner/designercore/model/texttomodelmerger.cpp +++ b/src/plugins/qmldesigner/designercore/model/texttomodelmerger.cpp @@ -12,6 +12,7 @@ #include "itemlibraryinfo.h" #include "metainfo.h" #include "modelnodepositionstorage.h" +#include "modelutils.h" #include "nodemetainfo.h" #include "nodeproperty.h" #include "propertyparser.h" @@ -132,7 +133,7 @@ QString deEscape(const QString &value) result.replace(QStringLiteral("\\\\"), QStringLiteral("\\")); result.replace(QStringLiteral("\\\""), QStringLiteral("\"")); result.replace(QStringLiteral("\\t"), QStringLiteral("\t")); - result.replace(QStringLiteral("\\r"), QStringLiteral("\\\r")); + result.replace(QStringLiteral("\\r"), QStringLiteral("\r")); result.replace(QStringLiteral("\\n"), QStringLiteral("\n")); return result; @@ -165,10 +166,13 @@ bool isHexDigit(ushort c) QString fixEscapedUnicodeChar(const QString &value) //convert "\u2939" { - if (value.size() == 6 && value.at(0) == QLatin1Char('\\') && value.at(1) == QLatin1Char('u') && - isHexDigit(value.at(2).unicode()) && isHexDigit(value.at(3).unicode()) && - isHexDigit(value.at(4).unicode()) && isHexDigit(value.at(5).unicode())) { - return convertUnicode(value.at(2).unicode(), value.at(3).unicode(), value.at(4).unicode(), value.at(5).unicode()); + if (value.size() == 6 && value.at(0) == QLatin1Char('\\') && value.at(1) == QLatin1Char('u') + && isHexDigit(value.at(2).unicode()) && isHexDigit(value.at(3).unicode()) + && isHexDigit(value.at(4).unicode()) && isHexDigit(value.at(5).unicode())) { + return convertUnicode(value.at(2).unicode(), + value.at(3).unicode(), + value.at(4).unicode(), + value.at(5).unicode()); } return value; } @@ -362,8 +366,8 @@ bool compareJavaScriptExpression(const QString &expression1, const QString &expr bool smartVeryFuzzyCompare(const QVariant &value1, const QVariant &value2) { //we ignore slight changes on doubles and only check three digits - const auto type1 = static_cast(value1.type()); - const auto type2 = static_cast(value2.type()); + const auto type1 = static_cast(value1.typeId()); + const auto type2 = static_cast(value2.typeId()); if (type1 == QMetaType::Double || type2 == QMetaType::Double || type1 == QMetaType::Float @@ -387,13 +391,23 @@ bool smartVeryFuzzyCompare(const QVariant &value1, const QVariant &value2) return false; } + void removeModelNode(const QmlDesigner::ModelNode &modelNode) + { + modelNode.model()->removeModelNodes({modelNode}, + QmlDesigner::BypassModelResourceManagement::Yes); + } bool smartColorCompare(const QVariant &value1, const QVariant &value2) { - if ((value1.type() == QVariant::Color) || (value2.type() == QVariant::Color)) + if ((value1.typeId() == QVariant::Color) || (value2.typeId() == QVariant::Color)) return value1.value().rgba() == value2.value().rgba(); return false; } + void removeProperty(const QmlDesigner::AbstractProperty &modelProperty) + { + modelProperty.model()->removeProperties({modelProperty}, + QmlDesigner::BypassModelResourceManagement::Yes); + } bool equals(const QVariant &a, const QVariant &b) { if (a.canConvert() && b.canConvert()) @@ -573,25 +587,64 @@ public: return true; } - bool isArrayProperty(const Value *value, const ObjectValue *containingObject, const QString &name) + bool isArrayProperty(const AbstractProperty &property) { - if (!value) - return false; - const ObjectValue *objectValue = value->asObjectValue(); - if (objectValue && objectValue->prototype(m_context) == m_context->valueOwner()->arrayPrototype()) - return true; + return ModelUtils::metainfo(property).isListProperty(); + } - PrototypeIterator iter(containingObject, m_context); - while (iter.hasNext()) { - const ObjectValue *proto = iter.next(); - if (proto->lookupMember(name, m_context) == m_context->valueOwner()->arrayPrototype()) - return true; - if (const CppComponentValue *qmlIter = value_cast(proto)) { - if (qmlIter->isListProperty(name)) - return true; - } + QVariant convertToVariant(const ModelNode &node, + const QString &astValue, + const QString &propertyPrefix, + AST::UiQualifiedId *propertyId) + { + const QString propertyName = propertyPrefix.isEmpty() + ? toString(propertyId) + : propertyPrefix + "." + toString(propertyId); + + + const PropertyMetaInfo propertyMetaInfo = node.metaInfo().property(propertyName.toUtf8()); + const bool hasQuotes = astValue.trimmed().left(1) == QStringLiteral("\"") + && astValue.trimmed().right(1) == QStringLiteral("\""); + const QString cleanedValue = fixEscapedUnicodeChar(deEscape(stripQuotes(astValue.trimmed()))); + if (!propertyMetaInfo.isValid()) { + qCInfo(texttomodelMergerDebug) + << Q_FUNC_INFO << "Unknown property" + << propertyPrefix + QLatin1Char('.') + toString(propertyId) << "on line" + << propertyId->identifierToken.startLine << "column" + << propertyId->identifierToken.startColumn; + return hasQuotes ? QVariant(cleanedValue) : cleverConvert(cleanedValue); } - return false; + + const NodeMetaInfo &propertyTypeMetaInfo = propertyMetaInfo.propertyType(); + + if (propertyTypeMetaInfo.isColor()) + return PropertyParser::read(QVariant::Color, cleanedValue); + else if (propertyTypeMetaInfo.isUrl()) + return PropertyParser::read(QVariant::Url, cleanedValue); + else if (propertyTypeMetaInfo.isVector2D()) + return PropertyParser::read(QVariant::Vector2D, cleanedValue); + else if (propertyTypeMetaInfo.isVector3D()) + return PropertyParser::read(QVariant::Vector3D, cleanedValue); + else if (propertyTypeMetaInfo.isVector4D()) + return PropertyParser::read(QVariant::Vector4D, cleanedValue); + + QVariant value(cleanedValue); + if (propertyTypeMetaInfo.isBool()) { + value.convert(QVariant::Bool); + return value; + } else if (propertyTypeMetaInfo.isInteger()) { + value.convert(QVariant::Int); + return value; + } else if (propertyTypeMetaInfo.isFloat()) { + value.convert(QVariant::Double); + return value; + } else if (propertyTypeMetaInfo.isString()) { + // nothing to do + } else { //property alias et al + if (!hasQuotes) + return cleverConvert(cleanedValue); + } + return value; } QVariant convertToVariant(const QString &astValue, const QString &propertyPrefix, AST::UiQualifiedId *propertyId) @@ -1255,12 +1308,13 @@ void TextToModelMerger::syncNode(ModelNode &modelNode, } else { const Value *propertyType = nullptr; const ObjectValue *containingObject = nullptr; - QString name; - if (context->lookupProperty(QString(), binding->qualifiedId, &propertyType, &containingObject, &name) - || isPropertyChangesType(typeName) - || isConnectionsType(typeName)) { + if (context->lookupProperty({}, + binding->qualifiedId, + &propertyType, + &containingObject) + || isPropertyChangesType(typeName) || isConnectionsType(typeName)) { AbstractProperty modelProperty = modelNode.property(astPropertyName.toUtf8()); - if (context->isArrayProperty(propertyType, containingObject, name)) + if (context->isArrayProperty(modelProperty)) syncArrayProperty(modelProperty, {member}, context, differenceHandler); else syncNodeProperty(modelProperty, binding, context, TypeName(), differenceHandler); @@ -1447,7 +1501,10 @@ QmlDesigner::PropertyName TextToModelMerger::syncScriptBinding(ModelNode &modelN syncVariantProperty(modelProperty, variantValue, TypeName(), differenceHandler); return astPropertyName.toUtf8(); } else { - const QVariant variantValue = context->convertToVariant(astValue, prefix, script->qualifiedId); + const QVariant variantValue = context->convertToVariant(modelNode, + astValue, + prefix, + script->qualifiedId); if (variantValue.isValid()) { AbstractProperty modelProperty = modelNode.property(astPropertyName.toUtf8()); syncVariantProperty(modelProperty, variantValue, TypeName(), differenceHandler); @@ -2018,7 +2075,7 @@ void ModelAmender::shouldBeNodeProperty(AbstractProperty &modelProperty, void ModelAmender::modelNodeAbsentFromQml(ModelNode &modelNode) { - modelNode.destroy(); + removeModelNode(modelNode); } ModelNode ModelAmender::listPropertyMissingModelNode(NodeListProperty &modelProperty, @@ -2095,7 +2152,7 @@ void ModelAmender::typeDiffers(bool isRootNode, Q_ASSERT(nodeIndex >= 0); } - modelNode.destroy(); + removeModelNode(modelNode); const ModelNode &newNode = m_merger->createModelNode(typeName, majorVersion, @@ -2115,7 +2172,7 @@ void ModelAmender::typeDiffers(bool isRootNode, void ModelAmender::propertyAbsentFromQml(AbstractProperty &modelProperty) { - modelProperty.parentModelNode().removeProperty(modelProperty.name()); + removeProperty(modelProperty); } void ModelAmender::idsDiffer(ModelNode &modelNode, const QString &qmlId) diff --git a/src/plugins/qmldesigner/designercore/model/variantproperty.cpp b/src/plugins/qmldesigner/designercore/model/variantproperty.cpp index c879ec7a347..859bb0691ec 100644 --- a/src/plugins/qmldesigner/designercore/model/variantproperty.cpp +++ b/src/plugins/qmldesigner/designercore/model/variantproperty.cpp @@ -36,27 +36,29 @@ void VariantProperty::setValue(const QVariant &value) if (isDynamic()) qWarning() << "Calling VariantProperty::setValue on dynamic property."; + if (auto internalProperty = internalNode()->property(name())) { + auto variantProperty = internalProperty->to(); - if (internalNode()->hasProperty(name())) { //check if oldValue != value - Internal::InternalProperty::Pointer internalProperty = internalNode()->property(name()); - if (internalProperty->isVariantProperty() - && internalProperty->toVariantProperty()->value() == value - && dynamicTypeName().isEmpty()) - + //check if oldValue != value + if (variantProperty && variantProperty->value() == value + && variantProperty->dynamicTypeName().isEmpty()) { return; - } + } - if (internalNode()->hasProperty(name()) && !internalNode()->property(name())->isVariantProperty()) - privateModel()->removePropertyAndRelatedResources(internalNode()->property(name())); + if (!variantProperty) + privateModel()->removePropertyAndRelatedResources(internalProperty); + } privateModel()->setVariantProperty(internalNode(), name(), value); } QVariant VariantProperty::value() const { - if (isValid() && internalNode()->hasProperty(name()) - && internalNode()->property(name())->isVariantProperty()) - return internalNode()->variantProperty(name())->value(); + if (isValid()) { + auto property = internalNode()->variantProperty(name()); + if (property) + return property->value(); + } return QVariant(); } @@ -86,19 +88,18 @@ void VariantProperty::setDynamicTypeNameAndValue(const TypeName &type, const QVa Internal::WriteLocker locker(model()); - if (internalNode()->hasProperty(name())) { //check if oldValue != value - Internal::InternalProperty::Pointer internalProperty = internalNode()->property(name()); - if (internalProperty->isVariantProperty() - && internalProperty->toVariantProperty()->value() == value - && internalProperty->toVariantProperty()->dynamicTypeName() == type) - + //check if oldValue != value + if (auto internalProperty = internalNode()->property(name())) { + auto variantProperty = internalProperty->to(); + if (variantProperty && variantProperty->value() == value + && internalProperty->dynamicTypeName() == type) return; + + if (!variantProperty) + privateModel()->removePropertyAndRelatedResources(internalProperty); } - if (internalNode()->hasProperty(name()) && !internalNode()->property(name())->isVariantProperty()) - privateModel()->removePropertyAndRelatedResources(internalNode()->property(name())); - - privateModel()->setDynamicVariantProperty(internalNode(), name(), type, value); + privateModel()->setDynamicVariantProperty(internalNode(), name(), type, value); } void VariantProperty::setDynamicTypeNameAndEnumeration(const TypeName &type, const EnumerationName &enumerationName) diff --git a/src/plugins/qmldesigner/designercore/projectstorage/projectstorage.h b/src/plugins/qmldesigner/designercore/projectstorage/projectstorage.h index 974ebdf6aab..337145638c1 100644 --- a/src/plugins/qmldesigner/designercore/projectstorage/projectstorage.h +++ b/src/plugins/qmldesigner/designercore/projectstorage/projectstorage.h @@ -38,8 +38,13 @@ public: ProjectStorage(Database &database, bool isInitialized) : database{database} + , exclusiveTransaction{database} , initializer{database, isInitialized} { + exclusiveTransaction.commit(); + + database.walCheckpointFull(); + moduleCache.populate(); } @@ -494,7 +499,7 @@ private: static bool moduleNameLess(Utils::SmallStringView first, Utils::SmallStringView second) noexcept { - return Utils::reverseCompare(first, second) < 0; + return first < second; } using ModuleCache = StorageCache{}); } + template void relinkPrototypes(Prototypes &relinkablePrototypes, const TypeIds &deletedTypeIds, @@ -1080,7 +1078,6 @@ private: relinkablePropertyDeclarations, relinkablePrototypes, relinkableExtensions); - return Sqlite::CallbackControl::Continue; }; selectNotUpdatedTypesInSourcesStatement.readCallback(callback, @@ -1553,10 +1550,10 @@ private: int majorVersion, int minorVersion, ModuleExportedImportId moduleExportedImportId) { - Storage::Synchronization::Import additionImport{ - exportedModuleId, - Storage::Version{majorVersion, minorVersion}, - import.sourceId}; + Storage::Synchronization::Import additionImport{exportedModuleId, + Storage::Version{majorVersion, + minorVersion}, + import.sourceId}; auto exportedImportKind = importKind == Storage::Synchronization::ImportKind::Import ? Storage::Synchronization::ImportKind::ModuleExportedImport @@ -1566,8 +1563,6 @@ private: exportedImportKind, import.moduleId, moduleExportedImportId); - - return Sqlite::CallbackControl::Continue; }; selectModuleExportedImportsForModuleIdStatement.readCallback(callback, @@ -1964,8 +1959,6 @@ private: auto callback = [=](TypeId currentTypeId) { if (typeId == currentTypeId) throw PrototypeChainCycle{}; - - return Sqlite::CallbackControl::Continue; }; selectTypeIdsForPrototypeChainIdStatement.readCallback(callback, typeId); @@ -1976,8 +1969,6 @@ private: auto callback = [=](PropertyDeclarationId currentPropertyDeclarationId) { if (propertyDeclarationId == currentPropertyDeclarationId) throw AliasChainCycle{}; - - return Sqlite::CallbackControl::Continue; }; selectPropertyDeclarationIdsForAliasChainStatement.readCallback(callback, @@ -2209,8 +2200,6 @@ private: auto &functionDeclaration = functionDeclarations.emplace_back(name, returnType); functionDeclaration.parameters = selectFunctionParameterDeclarationsStatement.template values< Storage::Synchronization::ParameterDeclaration>(8, functionDeclarationId); - - return Sqlite::CallbackControl::Continue; }; selectFunctionDeclarationsForTypeIdWithoutSignatureStatement.readCallback(callback, typeId); @@ -2226,8 +2215,6 @@ private: auto &signalDeclaration = signalDeclarations.emplace_back(name); signalDeclaration.parameters = selectSignalParameterDeclarationsStatement.template values< Storage::Synchronization::ParameterDeclaration>(8, signalDeclarationId); - - return Sqlite::CallbackControl::Continue; }; selectSignalDeclarationsForTypeIdWithoutSignatureStatement.readCallback(callback, typeId); @@ -2245,8 +2232,6 @@ private: name, selectEnumeratorDeclarationStatement.template values< Storage::Synchronization::EnumeratorDeclaration>(8, enumerationDeclarationId)); - - return Sqlite::CallbackControl::Continue; }; selectEnumerationDeclarationsForTypeIdWithoutEnumeratorDeclarationsStatement @@ -2261,8 +2246,6 @@ private: Initializer(Database &database, bool isInitialized) { if (!isInitialized) { - Sqlite::ExclusiveTransaction transaction{database}; - auto moduleIdColumn = createModulesTable(database); createSourceContextsTable(database); createSourcesTable(database); @@ -2276,10 +2259,6 @@ private: createDocumentImportsTable(database, moduleIdColumn); createFileStatusesTable(database); createProjectDatasTable(database); - - transaction.commit(); - - database.walCheckpointFull(); } database.setIsInitialized(true); } @@ -2617,6 +2596,7 @@ private: public: Database &database; + Sqlite::ExclusiveNonThrowingDestructorTransaction exclusiveTransaction; Initializer initializer; mutable ModuleCache moduleCache{ModuleStorageAdapter{*this}}; Storage::Info::CommonTypeCache commonTypeCache_{*this}; diff --git a/src/plugins/qmldesigner/designercore/projectstorage/projectstoragesqlitefunctionregistry.cpp b/src/plugins/qmldesigner/designercore/projectstorage/projectstoragesqlitefunctionregistry.cpp deleted file mode 100644 index 5f50c5bcdad..00000000000 --- a/src/plugins/qmldesigner/designercore/projectstorage/projectstoragesqlitefunctionregistry.cpp +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (C) 2021 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 - -#include "projectstoragesqlitefunctionregistry.h" - -#include "sqlite.h" - -namespace QmlDesigner { - -extern "C" { -namespace { -void unqualifiedTypeName(sqlite3_context *context, int, sqlite3_value **arguments) -{ - auto argument = arguments[0]; - - auto errorText = "unqualifiedTypeName only accepts text"; - - if (sqlite3_value_type(argument) != SQLITE_TEXT) { - sqlite3_result_error(context, errorText, int(std::char_traits::length(errorText))); - return; - } - - auto size = sqlite3_value_bytes(argument); - - auto content = reinterpret_cast(sqlite3_value_text(argument)); - - auto begin = content; - auto end = content + size; - - auto rbegin = std::make_reverse_iterator(end); - auto rend = std::make_reverse_iterator(begin); - - auto found = std::find(rbegin, rend, '.').base(); - - auto unqualifiedSize = end - found; - - sqlite3_result_text(context, found, int(unqualifiedSize), SQLITE_STATIC); -} - -void registerUnqualifiedTypeName(sqlite3 *database) -{ - sqlite3_create_function(database, - "unqualifiedTypeName", - 1, - SQLITE_UTF8 | SQLITE_DETERMINISTIC | SQLITE_INNOCUOUS, - nullptr, - unqualifiedTypeName, - nullptr, - nullptr); -} -} // namespace -} - -ProjectStorageSqliteFunctionRegistry::ProjectStorageSqliteFunctionRegistry(Sqlite::Database &database) -{ - auto databaseHandle = database.backend().sqliteDatabaseHandle(); - - registerUnqualifiedTypeName(databaseHandle); -} - -} // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/designercore/projectstorage/projectstoragesqlitefunctionregistry.h b/src/plugins/qmldesigner/designercore/projectstorage/projectstoragesqlitefunctionregistry.h deleted file mode 100644 index 64836dd686c..00000000000 --- a/src/plugins/qmldesigner/designercore/projectstorage/projectstoragesqlitefunctionregistry.h +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (C) 2021 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 - -#pragma once - -#include - -namespace QmlDesigner { - -class ProjectStorageSqliteFunctionRegistry -{ -public: - ProjectStorageSqliteFunctionRegistry(Sqlite::Database &database); -}; - -} // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/designercore/projectstorage/projectstorageupdater.h b/src/plugins/qmldesigner/designercore/projectstorage/projectstorageupdater.h index 22778ac932a..519d11a920a 100644 --- a/src/plugins/qmldesigner/designercore/projectstorage/projectstorageupdater.h +++ b/src/plugins/qmldesigner/designercore/projectstorage/projectstorageupdater.h @@ -32,7 +32,7 @@ class ProjectStorage; class QmlDocumentParserInterface; class QmlTypesParserInterface; -class ProjectStorageUpdater : public ProjectStoragePathWatcherNotifierInterface +class ProjectStorageUpdater final : public ProjectStoragePathWatcherNotifierInterface { public: using PathCache = SourcePathCache, NonLockingMutex>; diff --git a/src/plugins/qmldesigner/designercore/projectstorage/qmldocumentparser.h b/src/plugins/qmldesigner/designercore/projectstorage/qmldocumentparser.h index 2896d54ebe7..96f28a4585f 100644 --- a/src/plugins/qmldesigner/designercore/projectstorage/qmldocumentparser.h +++ b/src/plugins/qmldesigner/designercore/projectstorage/qmldocumentparser.h @@ -12,7 +12,7 @@ namespace QmlDesigner { template class SourcePathCache; -class QmlDocumentParser : public QmlDocumentParserInterface +class QmlDocumentParser final : public QmlDocumentParserInterface { public: using ProjectStorage = QmlDesigner::ProjectStorage; diff --git a/src/plugins/qmldesigner/designercore/projectstorage/qmltypesparser.h b/src/plugins/qmldesigner/designercore/projectstorage/qmltypesparser.h index c1d9a3a0d45..6fcf82a2bb2 100644 --- a/src/plugins/qmldesigner/designercore/projectstorage/qmltypesparser.h +++ b/src/plugins/qmldesigner/designercore/projectstorage/qmltypesparser.h @@ -18,7 +18,7 @@ class ProjectStorage; template class SourcePathCache; -class QmlTypesParser : public QmlTypesParserInterface +class QmlTypesParser final : public QmlTypesParserInterface { public: using ProjectStorage = QmlDesigner::ProjectStorage; diff --git a/src/plugins/qmldesigner/designercore/projectstorage/sourcepathcache.h b/src/plugins/qmldesigner/designercore/projectstorage/sourcepathcache.h index bc7e2f9ec17..0327ddcae0d 100644 --- a/src/plugins/qmldesigner/designercore/projectstorage/sourcepathcache.h +++ b/src/plugins/qmldesigner/designercore/projectstorage/sourcepathcache.h @@ -143,7 +143,10 @@ private: static bool sourceContextLess(Utils::SmallStringView first, Utils::SmallStringView second) noexcept { - return Utils::reverseCompare(first, second) < 0; + return std::lexicographical_compare(first.rbegin(), + first.rend(), + second.rbegin(), + second.rend()); } static bool sourceLess(Cache::SourceNameView first, Cache::SourceNameView second) noexcept diff --git a/src/plugins/qmldesigner/designercore/projectstorage/sourcepathcachetypes.h b/src/plugins/qmldesigner/designercore/projectstorage/sourcepathcachetypes.h index 8bbd5badafc..5feaf30d006 100644 --- a/src/plugins/qmldesigner/designercore/projectstorage/sourcepathcachetypes.h +++ b/src/plugins/qmldesigner/designercore/projectstorage/sourcepathcachetypes.h @@ -35,6 +35,7 @@ public: class SourceNameEntry { public: + SourceNameEntry() = default; SourceNameEntry(Utils::SmallStringView sourceName, SourceContextId sourceContextId) : sourceName(sourceName) , sourceContextId(sourceContextId) diff --git a/src/plugins/qmldesigner/designercore/projectstorage/storagecache.h b/src/plugins/qmldesigner/designercore/projectstorage/storagecache.h index 945a6e38e56..f2d6841052d 100644 --- a/src/plugins/qmldesigner/designercore/projectstorage/storagecache.h +++ b/src/plugins/qmldesigner/designercore/projectstorage/storagecache.h @@ -47,12 +47,12 @@ class StorageCache template constexpr explicit StorageCacheIndex(IntegerType id) noexcept - : id{static_cast(id)} + : id{static_cast(id)} {} constexpr StorageCacheIndex operator=(std::ptrdiff_t newId) noexcept { - id = static_cast(newId); + id = static_cast(newId); return *this; } @@ -77,12 +77,15 @@ class StorageCache return first.id >= second.id; } - constexpr bool isValid() const noexcept { return id >= 0; } + constexpr bool isValid() const noexcept + { + return id != std::numeric_limits::max(); + } explicit operator std::size_t() const noexcept { return static_cast(id); } public: - int id = -1; + std::size_t id = std::numeric_limits::max(); }; public: @@ -149,7 +152,7 @@ public: }); if (found != m_entries.end()) - max_id = static_cast(found->id) + 1; + max_id = static_cast(found->id); m_indices.resize(max_id); @@ -184,7 +187,7 @@ public: return first.id < second.id; }); - auto max_id = static_cast(found->id) + 1; + auto max_id = static_cast(found->id); if (max_id > m_indices.size()) m_indices.resize(max_id); @@ -247,10 +250,11 @@ public: { std::shared_lock sharedLock(m_mutex); - if (IndexType::create(static_cast(m_indices.size())) > id) { - if (auto indirectionIndex = m_indices.at(static_cast(id)); - indirectionIndex.isValid()) + if (IndexType::create(static_cast(m_indices.size()) + 1) > id) { + if (StorageCacheIndex indirectionIndex = m_indices.at(static_cast(id) - 1); + indirectionIndex.isValid()) { return m_entries.at(static_cast(indirectionIndex)).value; + } } sharedLock.unlock(); @@ -271,7 +275,9 @@ public: for (IndexType id : ids) { values.emplace_back( - m_entries.at(static_cast(m_indices.at(static_cast(id)))).value); + m_entries + .at(static_cast(m_indices.at(static_cast(id) - 1))) + .value); } return values; } @@ -284,23 +290,63 @@ private: void updateIndices() { auto begin = m_entries.cbegin(); - for (auto current = begin; current != m_entries.cend(); ++current) - m_indices[static_cast(current->id)] = std::distance(begin, current); + for (auto current = begin; current != m_entries.cend(); ++current) { + if (current->id) + m_indices[static_cast(current->id) - 1] = std::distance(begin, current); + } } - auto find(ViewType view) + template + static auto find(Entries &&entries, ViewType view) { - auto found = std::lower_bound(m_entries.begin(), m_entries.end(), view, compare); + auto begin = entries.begin(); + auto end = entries.end(); + auto found = std::lower_bound(begin, end, view, compare); - if (found == m_entries.end()) - return m_entries.end(); + if (found == entries.end()) { + return entries.end(); + } - if (*found == view) + auto value = *found; + + if (value == view) { return found; + } - return m_entries.end(); + return entries.end(); } + IndexType id(ViewType view) const + { + std::shared_lock sharedLock(m_mutex); + + auto found = find(view); + + if (found != m_entries.end()) { + return found->id; + } + + return IndexType(); + } + + ResultType value(IndexType id) const + { + std::shared_lock sharedLock(m_mutex); + + if (IndexType::create(static_cast(m_indices.size()) + 1) > id) { + if (StorageCacheIndex indirectionIndex = m_indices.at(static_cast(id) - 1); + indirectionIndex.isValid()) { + return m_entries.at(static_cast(indirectionIndex)).value; + } + } + + return ResultType(); + } + + auto find(ViewType view) const { return find(m_entries, view); } + + auto find(ViewType view) { return find(m_entries, view); } + void incrementLargerOrEqualIndicesByOne(StorageCacheIndex newIndirectionIndex) { std::transform(m_indices.begin(), m_indices.end(), m_indices.begin(), [&](StorageCacheIndex index) { @@ -322,14 +368,14 @@ private: incrementLargerOrEqualIndicesByOne(newIndirectionIndex); - auto indirectionIndex = static_cast(id); + auto indirectionIndex = static_cast(id) - 1; ensureSize(indirectionIndex); m_indices.at(indirectionIndex) = newIndirectionIndex; return inserted; } - void checkEntries() + void checkEntries() const { for (const auto &entry : m_entries) { if (entry.value != value(entry.id) || entry.id != id(entry.value)) diff --git a/src/plugins/qmldesigner/documentwarningwidget.cpp b/src/plugins/qmldesigner/documentwarningwidget.cpp index d7bd70d5e34..49eb5acd465 100644 --- a/src/plugins/qmldesigner/documentwarningwidget.cpp +++ b/src/plugins/qmldesigner/documentwarningwidget.cpp @@ -121,13 +121,13 @@ QString DocumentWarningWidget::generateNavigateLinks() { static const QString link("%2"); QStringList links; - if (m_messages.count() > 1) { + if (m_messages.size() > 1) { if (m_currentMessage != 0) links << link.arg(QLatin1String("previous"), tr("Previous")); else links << tr("Previous"); - if (m_messages.count() - 1 > m_currentMessage) + if (m_messages.size() - 1 > m_currentMessage) links << link.arg(QLatin1String("next"), tr("Next")); else links << tr("Next"); diff --git a/src/plugins/qmldesigner/generateresource.cpp b/src/plugins/qmldesigner/generateresource.cpp index 439e124b705..be7f536662c 100644 --- a/src/plugins/qmldesigner/generateresource.cpp +++ b/src/plugins/qmldesigner/generateresource.cpp @@ -288,7 +288,7 @@ void GenerateResource::generateMenuEntry(QObject *parent) bool found = false; QString compareString = "./" + relativepath.trimmed(); - for (int i = 0; i < fileList.count(); ++i) + for (int i = 0; i < fileList.size(); ++i) if (fileList.at(i).fileName == compareString) { fileList[i].inProject = true; found = true; @@ -424,7 +424,7 @@ void GenerateResource::generateMenuEntry(QObject *parent) bool found = false; QString compareString = "./" + relativepath.trimmed(); - for (int i = 0; i < fileList.count(); ++i) + for (int i = 0; i < fileList.size(); ++i) if (fileList.at(i).fileName == compareString) { fileList[i].inProject = true; found = true; diff --git a/src/plugins/qmldesigner/qmldesignerconstants.h b/src/plugins/qmldesigner/qmldesignerconstants.h index d38dad74c7e..1e16848c6b5 100644 --- a/src/plugins/qmldesigner/qmldesignerconstants.h +++ b/src/plugins/qmldesigner/qmldesignerconstants.h @@ -80,6 +80,7 @@ const char MIME_TYPE_ITEM_LIBRARY_INFO[] = "application/vnd.qtdesignstudio.iteml const char MIME_TYPE_ASSETS[] = "application/vnd.qtdesignstudio.assets"; const char MIME_TYPE_MATERIAL[] = "application/vnd.qtdesignstudio.material"; const char MIME_TYPE_TEXTURE[] = "application/vnd.qtdesignstudio.texture"; +const char MIME_TYPE_BUNDLE_EFFECT[] = "application/vnd.qtdesignstudio.bundleeffect"; const char MIME_TYPE_BUNDLE_MATERIAL[] = "application/vnd.qtdesignstudio.bundlematerial"; const char MIME_TYPE_BUNDLE_TEXTURE[] = "application/vnd.qtdesignstudio.bundletexture"; const char MIME_TYPE_ASSET_IMAGE[] = "application/vnd.qtdesignstudio.asset.image"; @@ -99,6 +100,7 @@ const int MODELNODE_PREVIEW_IMAGE_DIMENSIONS = 150; const char EVENT_TIMELINE_ADDED[] = "timelineAdded"; const char EVENT_TRANSITION_ADDED[] = "transitionAdded"; const char EVENT_STATE_ADDED[] = "stateAdded"; +const char EVENT_STATE_ADDED_AND_CLONED[] = "stateAddedAndCloned"; const char EVENT_STATE_CLONED[] = "stateCloned"; const char EVENT_STATE_EXTENDED[] = "stateExtended"; const char EVENT_CONNECTION_ADDED[] = "connectionAdded"; @@ -162,6 +164,8 @@ const char OBJECT_NAME_NEW_DIALOG[] = "QQuickWidgetQDSNewDialog"; const char OBJECT_NAME_SPLASH_SCREEN[] = "QQuickWidgetSplashScreen"; const char OBJECT_NAME_WELCOME_PAGE[] = "QQuickWidgetQDSWelcomePage"; +const char ENVIRONMENT_SHOW_QML_ERRORS[] = "QMLDESIGNER_SHOW_QML_ERRORS"; + namespace Internal { enum { debug = 0 }; } diff --git a/src/plugins/qmldesigner/qmldesignerplugin.cpp b/src/plugins/qmldesigner/qmldesignerplugin.cpp index c83f830072c..b586c5d5ad2 100644 --- a/src/plugins/qmldesigner/qmldesignerplugin.cpp +++ b/src/plugins/qmldesigner/qmldesignerplugin.cpp @@ -131,6 +131,20 @@ QtQuickDesignerFactory::QtQuickDesignerFactory() } // namespace Internal +struct TraceIdentifierData +{ + TraceIdentifierData(const QString &_identifier, const QString &_newIdentifer, int _duration) + : identifier(_identifier), newIdentifer(_newIdentifer), maxDuration(_duration) + {} + + TraceIdentifierData() = default; + + QString identifier; + QString newIdentifer; + int maxDuration; + int time = 0; +}; + class QmlDesignerPluginPrivate { public: @@ -145,6 +159,9 @@ public: bool blockEditorChange = false; Utils::UniqueObjectPtr toolBar; Utils::UniqueObjectPtr statusBar; + QHash m_traceIdentifierDataHash; + QHash m_activeTraceIdentifierDataHash; + QElapsedTimer timer; }; QmlDesignerPlugin *QmlDesignerPlugin::m_instance = nullptr; @@ -249,6 +266,7 @@ bool QmlDesignerPlugin::initialize(const QStringList & /*arguments*/, QString *e if (!Utils::HostOsInfo::canCreateOpenGLContext(errorMessage)) return false; d = new QmlDesignerPluginPrivate; + d->timer.start(); if (QmlProjectManager::QmlProject::isQtDesignStudio()) GenerateResource::generateMenuEntry(this); @@ -284,58 +302,7 @@ bool QmlDesignerPlugin::initialize(const QStringList & /*arguments*/, QString *e bool QmlDesignerPlugin::delayedInitialize() { - // adding default path to item library plugins - const QString postfix = Utils::HostOsInfo::isMacHost() ? QString("/QmlDesigner") - : QString("/qmldesigner"); - const QStringList pluginPaths = - Utils::transform(ExtensionSystem::PluginManager::pluginPaths(), [postfix](const QString &p) { - return QString(p + postfix); - }); - - MetaInfo::initializeGlobal(pluginPaths, d->externalDependencies); - - d->viewManager.registerView(std::make_unique(d->externalDependencies)); - - auto timelineView = d->viewManager.registerView( - std::make_unique(d->externalDependencies)); - timelineView->registerActions(); - - d->viewManager.registerView( - std::make_unique(d->externalDependencies)); - - auto eventlistView = d->viewManager.registerView( - std::make_unique(d->externalDependencies)); - eventlistView->registerActions(); - - auto transitionEditorView = d->viewManager.registerView( - std::make_unique(d->externalDependencies)); - transitionEditorView->registerActions(); - - d->viewManager.registerFormEditorTool(std::make_unique()); - d->viewManager.registerFormEditorTool(std::make_unique()); - d->viewManager.registerFormEditorTool(std::make_unique()); - d->viewManager.registerFormEditorTool( - std::make_unique(d->externalDependencies)); - d->viewManager.registerFormEditorTool(std::make_unique()); - - if (QmlProjectManager::QmlProject::isQtDesignStudio()) { - d->mainWidget.initialize(); - - emitUsageStatistics("StandaloneMode"); - if (QmlProjectManager::QmlProject::isQtDesignStudioStartedFromQtC()) - emitUsageStatistics("QDSlaunchedFromQtC"); - emitUsageStatistics("qdsStartupCount"); - - FoundLicense license = checkLicense(); - if (license == FoundLicense::enterprise) - Core::ICore::appendAboutInformation(tr("License: Enterprise")); - else if (license == FoundLicense::professional) - Core::ICore::appendAboutInformation(tr("License: Professional")); - - if (!licensee().isEmpty()) - Core::ICore::appendAboutInformation(tr("Licensee: %1").arg(licensee())); - } - + enforceDelayedInitialize(); return true; } @@ -352,6 +319,10 @@ void QmlDesignerPlugin::extensionsInitialized() actionManager.createDefaultAddResourceHandler(); actionManager.createDefaultModelNodePreviewImageHandlers(); actionManager.polishActions(); + + registerCombinedTracedPoints(Constants::EVENT_STATE_ADDED, + Constants::EVENT_STATE_CLONED, + Constants::EVENT_STATE_ADDED_AND_CLONED); } ExtensionSystem::IPlugin::ShutdownFlag QmlDesignerPlugin::aboutToShutdown() @@ -452,6 +423,8 @@ void QmlDesignerPlugin::showDesigner() { QTC_ASSERT(!d->documentManager.hasCurrentDesignDocument(), return); + enforceDelayedInitialize(); + d->mainWidget.initialize(); const Utils::FilePath fileName = Core::EditorManager::currentEditor()->document()->filePath(); @@ -612,6 +585,70 @@ Model *QmlDesignerPlugin::currentModel() const return currentDesignDocument()->currentModel(); } +QmlDesignerPluginPrivate *QmlDesignerPlugin::privateInstance() +{ + QTC_ASSERT(instance(), return nullptr); + return instance()->d; +} + +void QmlDesignerPlugin::enforceDelayedInitialize() +{ + if (m_delayedInitialized) + return; + + // adding default path to item library plugins + const QString postfix = Utils::HostOsInfo::isMacHost() ? QString("/QmlDesigner") + : QString("/qmldesigner"); + const QStringList pluginPaths = Utils::transform(ExtensionSystem::PluginManager::pluginPaths(), + [postfix](const QString &p) { + return QString(p + postfix); + }); + + MetaInfo::initializeGlobal(pluginPaths, d->externalDependencies); + + d->viewManager.registerView(std::make_unique(d->externalDependencies)); + + auto timelineView = d->viewManager.registerView( + std::make_unique(d->externalDependencies)); + timelineView->registerActions(); + + d->viewManager.registerView(std::make_unique(d->externalDependencies)); + + auto eventlistView = d->viewManager.registerView( + std::make_unique(d->externalDependencies)); + eventlistView->registerActions(); + + auto transitionEditorView = d->viewManager.registerView( + std::make_unique(d->externalDependencies)); + transitionEditorView->registerActions(); + + d->viewManager.registerFormEditorTool(std::make_unique()); + d->viewManager.registerFormEditorTool(std::make_unique()); + d->viewManager.registerFormEditorTool(std::make_unique()); + d->viewManager.registerFormEditorTool(std::make_unique(d->externalDependencies)); + d->viewManager.registerFormEditorTool(std::make_unique()); + + if (QmlProjectManager::QmlProject::isQtDesignStudio()) { + d->mainWidget.initialize(); + + emitUsageStatistics("StandaloneMode"); + if (QmlProjectManager::QmlProject::isQtDesignStudioStartedFromQtC()) + emitUsageStatistics("QDSlaunchedFromQtC"); + emitUsageStatistics("qdsStartupCount"); + + FoundLicense license = checkLicense(); + if (license == FoundLicense::enterprise) + Core::ICore::appendAboutInformation(tr("License: Enterprise")); + else if (license == FoundLicense::professional) + Core::ICore::appendAboutInformation(tr("License: Professional")); + + if (!licensee().isEmpty()) + Core::ICore::appendAboutInformation(tr("Licensee: %1").arg(licensee())); + } + + m_delayedInitialized = true; +} + DesignDocument *QmlDesignerPlugin::currentDesignDocument() const { if (d) @@ -673,6 +710,35 @@ void QmlDesignerPlugin::emitUsageStatistics(const QString &identifier) { QTC_ASSERT(instance(), return); emit instance()->usageStatisticsNotifier(normalizeIdentifier(identifier)); + + TraceIdentifierData activeData = privateInstance()->m_activeTraceIdentifierDataHash.value( + identifier); + + if (activeData.time) { + const int currentTime = privateInstance()->timer.elapsed(); + const int currentDuration = (currentTime - activeData.time); + if (currentDuration < activeData.maxDuration) + instance()->emitUsageStatisticsUsageDuration(activeData.newIdentifer, currentDuration); + + privateInstance()->m_activeTraceIdentifierDataHash.remove(identifier); + } + + TraceIdentifierData data = privateInstance()->m_traceIdentifierDataHash.value(identifier); + + if (!data.identifier.isEmpty()) { + data.time = privateInstance()->timer.elapsed(); + privateInstance()->m_activeTraceIdentifierDataHash.insert(data.identifier, data); + } + + const auto values = privateInstance()->m_activeTraceIdentifierDataHash.values(); + for (const auto &activeData : values) { + const int currentTime = privateInstance()->timer.elapsed(); + const int currentDuration = (currentTime - activeData.time); + + if (currentDuration > activeData.maxDuration) { + privateInstance()->m_activeTraceIdentifierDataHash.remove(activeData.identifier); + } + } } void QmlDesignerPlugin::emitUsageStatisticsContextAction(const QString &identifier) @@ -727,6 +793,18 @@ void QmlDesignerPlugin::trackWidgetFocusTime(QWidget *widget, const QString &ide }); } +void QmlDesignerPlugin::registerCombinedTracedPoints(const QString &identifierFirst, + const QString &identifierSecond, + const QString &newIdentifier, + int maxDuration) +{ + QTC_ASSERT(privateInstance(), return ); + privateInstance()->m_traceIdentifierDataHash.insert(identifierFirst, + TraceIdentifierData(identifierSecond, + newIdentifier, + maxDuration)); +} + void QmlDesignerPlugin::lauchFeedbackPopup(const QString &identifier) { if (Core::ModeManager::currentModeId() == Core::Constants::MODE_DESIGN) @@ -792,6 +870,12 @@ void QmlDesignerPlugin::emitUsageStatisticsTime(const QString &identifier, int e emit instance()->usageStatisticsUsageTimer(normalizeIdentifier(identifier), elapsed); } +void QmlDesignerPlugin::emitUsageStatisticsUsageDuration(const QString &identifier, int elapsed) +{ + QTC_ASSERT(instance(), return ); + emit instance()->usageStatisticsUsageDuration(identifier, elapsed); +} + QmlDesignerPlugin *QmlDesignerPlugin::instance() { return m_instance; diff --git a/src/plugins/qmldesigner/qmldesignerplugin.h b/src/plugins/qmldesigner/qmldesignerplugin.h index ee078b273ab..455810fa206 100644 --- a/src/plugins/qmldesigner/qmldesignerplugin.h +++ b/src/plugins/qmldesigner/qmldesignerplugin.h @@ -76,17 +76,25 @@ public: static void emitUsageStatisticsContextAction(const QString &identifier); static void emitUsageStatisticsHelpRequested(const QString &identifier); static void emitUsageStatisticsTime(const QString &identifier, int elapsed); + static void emitUsageStatisticsUsageDuration(const QString &identifier, int elapsed); static AsynchronousImageCache &imageCache(); static void registerPreviewImageProvider(QQmlEngine *engine); static void trackWidgetFocusTime(QWidget *widget, const QString &identifier); + static void registerCombinedTracedPoints(const QString &identifierFirst, + const QString &identifierSecond, + const QString &newIdentifier, + int maxDuration = 10000); signals: void usageStatisticsNotifier(const QString &identifier); void usageStatisticsUsageTimer(const QString &identifier, int elapsed); - void usageStatisticsInsertFeedback(const QString &identifier, const QString &feedback, int rating); + void usageStatisticsUsageDuration(const QString &identifier, int elapsed); + void usageStatisticsInsertFeedback(const QString &identifier, + const QString &feedback, + int rating); void assetChanged(const QString &assetPath); private slots: @@ -110,11 +118,14 @@ private: // functions RewriterView *rewriterView() const; Model *currentModel() const; QQuickWidget *m_feedbackWidget = nullptr; + static QmlDesignerPluginPrivate *privateInstance(); + void enforceDelayedInitialize(); private: // variables QmlDesignerPluginPrivate *d = nullptr; static QmlDesignerPlugin *m_instance; QElapsedTimer m_usageTimer; + bool m_delayedInitialized = false; }; } // namespace QmlDesigner diff --git a/src/plugins/qmldesigner/qtquickplugin/images/mouse-area-icon.png b/src/plugins/qmldesigner/qtquickplugin/images/mouse-area-icon.png index 791e5f95203..fe316caf8d8 100644 Binary files a/src/plugins/qmldesigner/qtquickplugin/images/mouse-area-icon.png and b/src/plugins/qmldesigner/qtquickplugin/images/mouse-area-icon.png differ diff --git a/src/plugins/qmldesigner/qtquickplugin/images/mouse-area-icon16.png b/src/plugins/qmldesigner/qtquickplugin/images/mouse-area-icon16.png index f426957af38..bc8725fb5ff 100644 Binary files a/src/plugins/qmldesigner/qtquickplugin/images/mouse-area-icon16.png and b/src/plugins/qmldesigner/qtquickplugin/images/mouse-area-icon16.png differ diff --git a/src/plugins/qmldesigner/qtquickplugin/images/mouse-area-icon@2x.png b/src/plugins/qmldesigner/qtquickplugin/images/mouse-area-icon@2x.png index 14607fb896f..04a25e13db3 100644 Binary files a/src/plugins/qmldesigner/qtquickplugin/images/mouse-area-icon@2x.png and b/src/plugins/qmldesigner/qtquickplugin/images/mouse-area-icon@2x.png differ diff --git a/src/plugins/qmldesigner/utils/filedownloader.cpp b/src/plugins/qmldesigner/utils/filedownloader.cpp index 7825be5081b..38f0caeeb36 100644 --- a/src/plugins/qmldesigner/utils/filedownloader.cpp +++ b/src/plugins/qmldesigner/utils/filedownloader.cpp @@ -9,6 +9,7 @@ #include #include #include +#include namespace QmlDesigner { @@ -38,6 +39,27 @@ bool FileDownloader::deleteFileAtTheEnd() const return m_targetFilePath.isEmpty(); } +QNetworkRequest FileDownloader::makeRequest() const +{ + QUrl url = m_url; + + if (url.scheme() == "https") { +#ifndef QT_NO_SSL + if (!QSslSocket::supportsSsl()) +#endif + { + qWarning() << "SSL is not available. HTTP will be used instead of HTTPS."; + url.setScheme("http"); + } + } + + auto request = QNetworkRequest(url); + request.setAttribute(QNetworkRequest::RedirectPolicyAttribute, + QNetworkRequest::UserVerifiedRedirectPolicy); + + return request; +} + void FileDownloader::start() { emit downloadStarting(); @@ -48,9 +70,7 @@ void FileDownloader::start() m_outputFile.setFileName(tempFileName); m_outputFile.open(QIODevice::WriteOnly); - auto request = QNetworkRequest(m_url); - request.setAttribute(QNetworkRequest::RedirectPolicyAttribute, - QNetworkRequest::UserVerifiedRedirectPolicy); + QNetworkRequest request = makeRequest(); QNetworkReply *reply = Utils::NetworkAccessManager::instance()->get(request); m_reply = reply; @@ -114,6 +134,13 @@ void FileDownloader::start() return; } + if (m_overwriteTarget && QFileInfo().exists(m_targetFilePath)) { + if (!QFile::remove(m_targetFilePath)) { + emit downloadFailed(); + return; + } + } + if (!QFileInfo().exists(m_targetFilePath) && !m_outputFile.rename(m_targetFilePath)) { emit downloadFailed(); return; @@ -183,6 +210,19 @@ bool FileDownloader::downloadEnabled() const return m_downloadEnabled; } +bool FileDownloader::overwriteTarget() const +{ + return m_overwriteTarget; +} + +void FileDownloader::setOverwriteTarget(bool value) +{ + if (value != m_overwriteTarget) { + m_overwriteTarget = value; + emit overwriteTargetChanged(); + } +} + bool FileDownloader::finished() const { return m_finished; @@ -235,9 +275,7 @@ void FileDownloader::doProbeUrl() return; } - auto request = QNetworkRequest(m_url); - request.setAttribute(QNetworkRequest::RedirectPolicyAttribute, - QNetworkRequest::UserVerifiedRedirectPolicy); + QNetworkRequest request = makeRequest(); QNetworkReply *reply = Utils::NetworkAccessManager::instance()->head(request); QNetworkReply::connect(reply, &QNetworkReply::redirected, [reply](const QUrl &) { diff --git a/src/plugins/qmldesigner/utils/filedownloader.h b/src/plugins/qmldesigner/utils/filedownloader.h index 4ecb6b49671..6027338af02 100644 --- a/src/plugins/qmldesigner/utils/filedownloader.h +++ b/src/plugins/qmldesigner/utils/filedownloader.h @@ -26,6 +26,7 @@ class FileDownloader : public QObject Q_PROPERTY(QString outputFile READ outputFile NOTIFY outputFileChanged) Q_PROPERTY(QDateTime lastModified READ lastModified NOTIFY lastModifiedChanged) Q_PROPERTY(bool available READ available NOTIFY availableChanged) + Q_PROPERTY(bool overwriteTarget READ overwriteTarget WRITE setOverwriteTarget NOTIFY overwriteTargetChanged) public: explicit FileDownloader(QObject *parent = nullptr); @@ -47,6 +48,9 @@ public: void setDownloadEnabled(bool value); bool downloadEnabled() const; + bool overwriteTarget() const; + void setOverwriteTarget(bool value); + void setProbeUrl(bool value); bool probeUrl() const; @@ -69,10 +73,12 @@ signals: void downloadCanceled(); void probeUrlChanged(); void targetFilePathChanged(); + void overwriteTargetChanged(); private: void doProbeUrl(); bool deleteFileAtTheEnd() const; + QNetworkRequest makeRequest() const; QUrl m_url; bool m_probeUrl = false; @@ -85,6 +91,7 @@ private: QNetworkReply *m_reply = nullptr; bool m_downloadEnabled = false; + bool m_overwriteTarget = false; QString m_targetFilePath; }; diff --git a/src/plugins/qmldesigner/utils/fileextractor.cpp b/src/plugins/qmldesigner/utils/fileextractor.cpp index 7c32381b69c..e2ba28e8876 100644 --- a/src/plugins/qmldesigner/utils/fileextractor.cpp +++ b/src/plugins/qmldesigner/utils/fileextractor.cpp @@ -3,6 +3,7 @@ #include "fileextractor.h" #include +#include #include #include @@ -198,6 +199,13 @@ QString FileExtractor::sourceFile() const void FileExtractor::extract() { + if (m_targetPath.isEmpty()) { + auto uniqueText = QByteArray::number(QRandomGenerator::global()->generate(), 16); + QString tempFileName = QDir::tempPath() + "/.qds_" + uniqueText + "_extract_" + m_archiveName + "_dir"; + + m_targetPath = Utils::FilePath::fromString(tempFileName); + } + m_targetFolder = m_targetPath.toString() + "/" + m_archiveName; // If the target directory already exists, remove it and its content diff --git a/src/plugins/qmldesigner/utils/multifiledownloader.cpp b/src/plugins/qmldesigner/utils/multifiledownloader.cpp index 6a8ac9761e9..6a452d6b098 100644 --- a/src/plugins/qmldesigner/utils/multifiledownloader.cpp +++ b/src/plugins/qmldesigner/utils/multifiledownloader.cpp @@ -24,7 +24,7 @@ void MultiFileDownloader::setDownloader(FileDownloader *downloader) QObject::connect(m_downloader, &FileDownloader::progressChanged, this, [this]() { double curProgress = m_downloader->progress() / 100.0; - double totalProgress = (m_nextFile + curProgress) / m_files.count(); + double totalProgress = (m_nextFile + curProgress) / m_files.size(); m_progress = totalProgress * 100; emit progressChanged(); }); diff --git a/src/plugins/qmldesignerbase/utils/designersettings.cpp b/src/plugins/qmldesignerbase/utils/designersettings.cpp index fe1ee169c7a..7071cfffbd1 100644 --- a/src/plugins/qmldesignerbase/utils/designersettings.cpp +++ b/src/plugins/qmldesignerbase/utils/designersettings.cpp @@ -85,11 +85,11 @@ void DesignerSettings::fromSettings(QSettings *settings) restoreValue(settings, DesignerSettingsKey::EDIT3DVIEW_GRID_COLOR, "#aaaaaa"); restoreValue(settings, DesignerSettingsKey::SMOOTH_RENDERING, false); restoreValue(settings, DesignerSettingsKey::SHOW_DEBUG_SETTINGS, false); - restoreValue(settings, DesignerSettingsKey::OLD_STATES_EDITOR, false); restoreValue(settings, DesignerSettingsKey::EDITOR_ZOOM_FACTOR, 1.0); restoreValue(settings, DesignerSettingsKey::ACTIONS_MERGE_TEMPLATE_ENABLED, false); restoreValue(settings, DesignerSettingsKey::DOWNLOADABLE_BUNDLES_URL, "https://cdn.qt.io/designstudio/bundles"); + restoreValue(settings, DesignerSettingsKey::CONTENT_LIBRARY_NEW_FLAG_EXPIRATION_DAYS, 3); settings->endGroup(); settings->endGroup(); diff --git a/src/plugins/qmldesignerbase/utils/designersettings.h b/src/plugins/qmldesignerbase/utils/designersettings.h index 78b43705268..2e2e90c83f1 100644 --- a/src/plugins/qmldesignerbase/utils/designersettings.h +++ b/src/plugins/qmldesignerbase/utils/designersettings.h @@ -57,10 +57,10 @@ inline constexpr char ALWAYS_DESIGN_MODE[] = "AlwaysDesignMode"; inline constexpr char DISABLE_ITEM_LIBRARY_UPDATE_TIMER[] = "DisableItemLibraryUpdateTimer"; inline constexpr char ASK_BEFORE_DELETING_ASSET[] = "AskBeforeDeletingAsset"; inline constexpr char SMOOTH_RENDERING[] = "SmoothRendering"; -inline constexpr char OLD_STATES_EDITOR[] = "ForceOldStatesEditor"; inline constexpr char EDITOR_ZOOM_FACTOR[] = "EditorZoomFactor"; inline constexpr char ACTIONS_MERGE_TEMPLATE_ENABLED[] = "ActionsMergeTemplateEnabled"; inline constexpr char DOWNLOADABLE_BUNDLES_URL[] = "DownloadableBundlesLocation"; +inline constexpr char CONTENT_LIBRARY_NEW_FLAG_EXPIRATION_DAYS[] = "ContentLibraryNewFlagExpirationInDays"; } class QMLDESIGNERBASE_EXPORT DesignerSettings diff --git a/src/plugins/qmlprojectmanager/buildsystem/projectitem/converters.cpp b/src/plugins/qmlprojectmanager/buildsystem/projectitem/converters.cpp index 0097611a4dd..7f01e33f435 100644 --- a/src/plugins/qmlprojectmanager/buildsystem/projectitem/converters.cpp +++ b/src/plugins/qmlprojectmanager/buildsystem/projectitem/converters.cpp @@ -10,7 +10,8 @@ namespace QmlProjectManager::Converters { using PropsPair = QPair; struct FileProps { - const PropsPair image{"image", QStringList{"*.jpeg", "*.jpg", "*.png", "*.svg", "*.hdr", ".ktx"}}; + const PropsPair image{"image", + QStringList{"*.jpeg", "*.jpg", "*.png", "*.svg", "*.hdr", ".ktx"}}; const PropsPair qml{"qml", QStringList{"*.qml"}}; const PropsPair qmlDir{"qmldir", QStringList{"qmldir"}}; const PropsPair javaScr{"javaScript", QStringList{"*.js", "*.ts"}}; @@ -43,7 +44,7 @@ QString jsonToQmlProject(const QJsonObject &rootObject) auto appendBreak = [&ts]() { ts << Qt::endl; }; auto appendComment = [&ts, &indentationLevel](const QString &comment) { - ts << QString(" ").repeated(indentationLevel * 4) << "\\\\ " << comment << Qt::endl; + ts << QString(" ").repeated(indentationLevel * 4) << "// " << comment << Qt::endl; }; auto appendItem = @@ -153,10 +154,14 @@ QString jsonToQmlProject(const QJsonObject &rootObject) } { // append ShaderTool object - startObject("ShaderTool"); - appendString("args", shaderConfig["args"].toVariant().toStringList().join(" ")); - appendArray("files", shaderConfig["files"].toVariant().toStringList()); - endObject(); + if (!shaderConfig["args"].toVariant().toStringList().isEmpty()) { + startObject("ShaderTool"); + appendString("args", + shaderConfig["args"].toVariant().toStringList().join(" ").replace( + "\"", "\\\"")); + appendArray("files", shaderConfig["files"].toVariant().toStringList()); + endObject(); + } } { // append files objects @@ -190,7 +195,7 @@ QJsonObject qmlProjectTojson(const Utils::FilePath &projectFile) } if (rootNode->name() != QLatin1String("Project")) { - qCritical() << "Cannot find root 'Proejct' item in the project file: " << projectFile; + qCritical() << "Cannot find root 'Project' item in the project file: " << projectFile; return {}; } @@ -216,18 +221,22 @@ QJsonObject qmlProjectTojson(const Utils::FilePath &projectFile) // convert the the non-object props for (const QString &propName : rootNode->propertyNames()) { QJsonObject *currentObj = &rootObject; - QString objKey = propName; + QString objKey = QString(propName).remove("QDS.", Qt::CaseInsensitive); QJsonValue value = rootNode->property(propName).value.toJsonValue(); - if (propName.contains("language", Qt::CaseInsensitive)) { + if (propName.startsWith("mcu.", Qt::CaseInsensitive)) { + currentObj = &mcuObject; + objKey = QString(propName).remove("MCU."); + } else if (propName.contains("language", Qt::CaseInsensitive)) { currentObj = &languageObject; - if (propName.toLower() == "multilanguagesupport") // fixing the camelcase + if (propName.contains("multilanguagesupport", Qt::CaseInsensitive)) + // fixing the camelcase objKey = "multiLanguageSupport"; } else if (propName.contains("version", Qt::CaseInsensitive)) { currentObj = &versionObject; - if (propName.toLower() == "qdsversion") + if (propName.contains("qdsversion", Qt::CaseInsensitive)) objKey = "designStudio"; - else if (propName.toLower() == "quickversion") + else if (propName.contains("quickversion", Qt::CaseInsensitive)) objKey = "qtQuick"; } else if (propName.contains("widgetapp", Qt::CaseInsensitive) || propName.contains("fileselector", Qt::CaseInsensitive) @@ -265,7 +274,8 @@ QJsonObject qmlProjectTojson(const Utils::FilePath &projectFile) FileProps fileProps; const QString childNodeName = childNode->name().toLower(); const QmlJS::SimpleReaderNode::Property childNodeFilter = childNode->property("filter"); - const QmlJS::SimpleReaderNode::Property childNodeDirectory = childNode->property("directory"); + const QmlJS::SimpleReaderNode::Property childNodeDirectory = childNode->property( + "directory"); const QmlJS::SimpleReaderNode::Property childNodeFiles = childNode->property("files"); const QString childNodeFilterValue = childNodeFilter.value.toString(); @@ -304,12 +314,12 @@ QJsonObject qmlProjectTojson(const Utils::FilePath &projectFile) // populate & update filters if (filters.isEmpty()) { - filters = QJsonArray::fromStringList(propsPair.second); // populate the filters with the predefined ones + filters = QJsonArray::fromStringList( + propsPair.second); // populate the filters with the predefined ones } if (childNodeFilter.isValid()) { // append filters from qmlproject (merge) - const QStringList filtersFromProjectFile = childNodeFilterValue.split( - ";"); + const QStringList filtersFromProjectFile = childNodeFilterValue.split(";"); for (const QString &filter : filtersFromProjectFile) { if (!filters.contains(QJsonValue(filter))) { filters.append(QJsonValue(filter)); @@ -337,7 +347,8 @@ QJsonObject qmlProjectTojson(const Utils::FilePath &projectFile) targetObject.insert("files", files); fileGroupsObject.insert(propsPair.first, targetObject); } else if (childNode->name().contains("shadertool", Qt::CaseInsensitive)) { - QStringList quotedArgs = childNode->property("args").value.toString().split('\"', Qt::SkipEmptyParts); + QStringList quotedArgs + = childNode->property("args").value.toString().split('\"', Qt::SkipEmptyParts); QStringList args; for (int i = 0; i < quotedArgs.size(); ++i) { // Each odd arg in this list is a single quoted argument, which we should @@ -351,7 +362,8 @@ QJsonObject qmlProjectTojson(const Utils::FilePath &projectFile) shaderToolObject.insert("args", QJsonArray::fromStringList(args)); shaderToolObject.insert("files", childNode->property("files").value.toJsonValue()); } else { - rootObject.insert(toCamelCase(childNode->name()), nodeToJsonObject(childNode)); + rootObject.insert(toCamelCase(childNode->name().remove("qds.", Qt::CaseInsensitive)), + nodeToJsonObject(childNode)); } } @@ -361,7 +373,8 @@ QJsonObject qmlProjectTojson(const Utils::FilePath &projectFile) rootObject.insert("runConfig", runConfigObject); rootObject.insert("deployment", deploymentObject); rootObject.insert("mcuConfig", mcuObject); - rootObject.insert("shaderTool", shaderToolObject); + if (!shaderToolObject.isEmpty()) + rootObject.insert("shaderTool", shaderToolObject); rootObject.insert("fileVersion", 1); return rootObject; } diff --git a/src/plugins/qmlprojectmanager/buildsystem/projectitem/qmlprojectitem.h b/src/plugins/qmlprojectmanager/buildsystem/projectitem/qmlprojectitem.h index 83ef5ca0000..214614f5365 100644 --- a/src/plugins/qmlprojectmanager/buildsystem/projectitem/qmlprojectitem.h +++ b/src/plugins/qmlprojectmanager/buildsystem/projectitem/qmlprojectitem.h @@ -7,11 +7,11 @@ #include +#include #include #include -#include #include -#include +#include #include #include @@ -30,7 +30,6 @@ public: bool isQt4McuProject() const; - QString versionQt() const; void setVersionQt(const QString &version); @@ -102,7 +101,7 @@ private: // runtime variables Utils::FilePath m_projectFile; // design studio project file - QJsonObject m_project; // root project object + QJsonObject m_project; // root project object const bool m_skipRewrite; // initializing functions diff --git a/src/plugins/qmlprojectmanager/buildsystem/qmlbuildsystem.cpp b/src/plugins/qmlprojectmanager/buildsystem/qmlbuildsystem.cpp index bce1b5babc1..307b6d61451 100644 --- a/src/plugins/qmlprojectmanager/buildsystem/qmlbuildsystem.cpp +++ b/src/plugins/qmlprojectmanager/buildsystem/qmlbuildsystem.cpp @@ -5,6 +5,7 @@ #include "../qmlprojectconstants.h" #include "../qmlprojectmanagertr.h" +#include "../qmlproject.h" #include #include @@ -82,11 +83,11 @@ QmlBuildSystem::QmlBuildSystem(Target *target) updateDeploymentData(); registerMenuButtons(); - connect(target->project(), &Project::activeTargetChanged, [this](Target *target) { + connect(target->project(), &Project::activeTargetChanged, this, [this](Target *target) { refresh(RefreshOptions::NoFileRefresh); updateMcuBuildStep(target, qtForMCUs()); }); - connect(target->project(), &Project::projectFileIsDirty, [this]() { + connect(target->project(), &Project::projectFileIsDirty, this, [this]() { refresh(RefreshOptions::Project); updateMcuBuildStep(project()->activeTarget(), qtForMCUs()); }); @@ -155,6 +156,11 @@ bool QmlBuildSystem::updateProjectFile() return true; } +QmlProject *QmlBuildSystem::qmlProject() const +{ + return qobject_cast(project()); +} + void QmlBuildSystem::triggerParsing() { refresh(RefreshOptions::Project); @@ -284,14 +290,14 @@ bool QmlBuildSystem::setFileSettingInProjectFile(const QString &setting, const QString relativePath = mainFilePath.relativeChildPath(projectDir).path(); if (fileContent.indexOf(settingQmlCode) < 0) { - QString addedText = QString("\n %1 \"%2\"\n").arg(settingQmlCode).arg(relativePath); + QString addedText = QString("\n %1 \"%2\"\n").arg(settingQmlCode, relativePath); auto index = fileContent.lastIndexOf("}"); fileContent.insert(index, addedText); } else { QString originalFileName = oldFile; originalFileName.replace(".", "\\."); const QRegularExpression expression( - QString("%1\\s*\"(%2)\"").arg(settingQmlCode).arg(originalFileName)); + QString("%1\\s*\"(%2)\"").arg(settingQmlCode, originalFileName)); const QRegularExpressionMatch match = expression.match(fileContent); @@ -315,14 +321,85 @@ void QmlBuildSystem::setBlockFilesUpdate(bool newBlockFilesUpdate) m_blockFilesUpdate = newBlockFilesUpdate; } +Utils::FilePath QmlBuildSystem::getStartupQmlFileWithFallback() const +{ + const auto currentProject = project(); + + if (!currentProject) + return {}; + + if (!target()) + return {}; + + const auto getFirstFittingFile = [](const Utils::FilePaths &files) -> Utils::FilePath { + for (const auto &file : files) { + if (file.exists()) + return file; + } + return {}; + }; + + const QStringView uiqmlstr = u"ui.qml"; + const QStringView qmlstr = u"qml"; + + //we will check mainUiFile and mainFile twice: + //first priority if it's ui.qml file, second if it's just a qml file + const Utils::FilePath mainUiFile = mainUiFilePath(); + if (mainUiFile.exists() && mainUiFile.completeSuffix() == uiqmlstr) + return mainUiFile; + + const Utils::FilePath mainQmlFile = mainFilePath(); + if (mainQmlFile.exists() && mainQmlFile.completeSuffix() == uiqmlstr) + return mainQmlFile; + + const Utils::FilePaths uiFiles = currentProject->files([&](const ProjectExplorer::Node *node) { + return node->filePath().completeSuffix() == uiqmlstr; + }); + if (!uiFiles.isEmpty()) { + if (const auto file = getFirstFittingFile(uiFiles); !file.isEmpty()) + return file; + } + + //check the suffix of mainUiFiles again, since there are no ui.qml files: + if (mainUiFile.exists() && mainUiFile.completeSuffix() == qmlstr) + return mainUiFile; + + if (mainQmlFile.exists() && mainQmlFile.completeSuffix() == qmlstr) + return mainQmlFile; + + //maybe it's also worth priotizing qml files containing common words like "Screen"? + const Utils::FilePaths qmlFiles = currentProject->files([&](const ProjectExplorer::Node *node) { + return node->filePath().completeSuffix() == qmlstr; + }); + if (!qmlFiles.isEmpty()) { + if (const auto file = getFirstFittingFile(qmlFiles); !file.isEmpty()) + return file; + } + + //if no source files exist in the project, lets try to open the .qmlproject file itself + const Utils::FilePath projectFile = projectFilePath(); + if (projectFile.exists()) + return projectFile; + + return {}; +} + Utils::FilePath QmlBuildSystem::mainFilePath() const { - return projectDirectory().pathAppended(mainFile()); + const QString fileName = mainFile(); + if (fileName.isEmpty() || fileName.isNull()) { + return {}; + } + return projectDirectory().pathAppended(fileName); } Utils::FilePath QmlBuildSystem::mainUiFilePath() const { - return projectDirectory().pathAppended(mainUiFile()); + const QString fileName = mainUiFile(); + if (fileName.isEmpty() || fileName.isNull()) { + return {}; + } + return projectDirectory().pathAppended(fileName); } bool QmlBuildSystem::setMainFileInProjectFile(const Utils::FilePath &newMainFilePath) diff --git a/src/plugins/qmlprojectmanager/buildsystem/qmlbuildsystem.h b/src/plugins/qmlprojectmanager/buildsystem/qmlbuildsystem.h index 0a0e9cfcbaf..2d689a19712 100644 --- a/src/plugins/qmlprojectmanager/buildsystem/qmlbuildsystem.h +++ b/src/plugins/qmlprojectmanager/buildsystem/qmlbuildsystem.h @@ -94,6 +94,8 @@ public: bool blockFilesUpdate() const; void setBlockFilesUpdate(bool newBlockFilesUpdate); + Utils::FilePath getStartupQmlFileWithFallback() const; + signals: void projectChanged(); diff --git a/src/plugins/qmlprojectmanager/cmakegen/generatecmakelists.cpp b/src/plugins/qmlprojectmanager/cmakegen/generatecmakelists.cpp index 5a3bedf098a..9603562dc68 100644 --- a/src/plugins/qmlprojectmanager/cmakegen/generatecmakelists.cpp +++ b/src/plugins/qmlprojectmanager/cmakegen/generatecmakelists.cpp @@ -20,6 +20,10 @@ #include #include +#include +#include +#include + #include #include @@ -37,6 +41,27 @@ namespace QmlProjectManager { namespace GenerateCmake { +static bool isQmlDesigner(const ExtensionSystem::PluginSpec *spec) +{ + if (!spec) + return false; + + return spec->name().contains("QmlDesigner"); +} + +static void trackUsage(const QString &id) +{ + const auto plugins = ExtensionSystem::PluginManager::plugins(); + const auto it = std::find_if(plugins.begin(), plugins.end(), &isQmlDesigner); + if (it != plugins.end()) { + QObject *qmlDesignerPlugin = (*it)->plugin(); + QMetaObject::invokeMethod(qmlDesignerPlugin, + "usageStatisticsNotifier", + Qt::DirectConnection, + Q_ARG(QString, id)); + } +} + bool operator==(const GeneratableFile &left, const GeneratableFile &right) { return (left.filePath == right.filePath && left.content == right.content); @@ -100,6 +125,7 @@ void generateMenuEntry(QObject *parent) void onGenerateCmakeLists() { + trackUsage("generateCMakeProjectDialogOpened"); FilePath rootDir = ProjectExplorer::ProjectManager::startupProject()->projectDirectory(); int projectDirErrors = isProjectCorrectlyFormed(rootDir); @@ -122,6 +148,8 @@ void onGenerateCmakeLists() cmakeGen.filterFileQueue(confirmedFiles); cmakeGen.execute(); } + + trackUsage("generateCMakeProjectExecuted"); } bool isErrorFatal(int error) diff --git a/src/plugins/qmlprojectmanager/cmakegen/qmlprojectmaincpp.tpl b/src/plugins/qmlprojectmanager/cmakegen/qmlprojectmaincpp.tpl index cedd80d76dd..0ff9201d916 100644 --- a/src/plugins/qmlprojectmanager/cmakegen/qmlprojectmaincpp.tpl +++ b/src/plugins/qmlprojectmanager/cmakegen/qmlprojectmaincpp.tpl @@ -13,7 +13,7 @@ int main(int argc, char *argv[]) QGuiApplication app(argc, argv); QQmlApplicationEngine engine; - const QUrl url(u"qrc:Main/main.qml"_qs); + const QUrl url(u"qrc:/qt/qml/Main/main.qml"_qs); QObject::connect( &engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) { diff --git a/src/plugins/qmlprojectmanager/cmakegen/qmlprojectmodulecmakelists.tpl b/src/plugins/qmlprojectmanager/cmakegen/qmlprojectmodulecmakelists.tpl index e193ebf5ba1..93573a1ed7a 100644 --- a/src/plugins/qmlprojectmanager/cmakegen/qmlprojectmodulecmakelists.tpl +++ b/src/plugins/qmlprojectmanager/cmakegen/qmlprojectmodulecmakelists.tpl @@ -7,5 +7,6 @@ qt_add_library(%2 STATIC) qt6_add_qml_module(%2 URI "%3" VERSION 1.0 + RESOURCE_PREFIX "/qt/qml" %4 ) diff --git a/src/plugins/qmlprojectmanager/cmakegen/qmlprojectmodules.tpl b/src/plugins/qmlprojectmanager/cmakegen/qmlprojectmodules.tpl index a1fdb4071dc..2b74c49af38 100644 --- a/src/plugins/qmlprojectmanager/cmakegen/qmlprojectmodules.tpl +++ b/src/plugins/qmlprojectmanager/cmakegen/qmlprojectmodules.tpl @@ -4,6 +4,7 @@ qt6_add_qml_module(%1 URI "Main" VERSION 1.0 + RESOURCE_PREFIX "/qt/qml" NO_PLUGIN QML_FILES main.qml ) diff --git a/src/plugins/qmlprojectmanager/qmlproject.cpp b/src/plugins/qmlprojectmanager/qmlproject.cpp index 45aedb0177f..12e1b9f7cbe 100644 --- a/src/plugins/qmlprojectmanager/qmlproject.cpp +++ b/src/plugins/qmlprojectmanager/qmlproject.cpp @@ -67,40 +67,24 @@ void QmlProject::parsingFinished(const Target *target, bool success) // trigger only once disconnect(this, &QmlProject::anyParsingFinished, this, &QmlProject::parsingFinished); - // FIXME: what to do in this case? if (!target || !success || !activeTarget()) return; - auto targetActive = activeTarget(); - auto qmlBuildSystem = qobject_cast( - targetActive->buildSystem()); - - const Utils::FilePath mainUiFile = qmlBuildSystem->mainUiFilePath(); - - if (mainUiFile.completeSuffix() == "ui.qml" && mainUiFile.exists()) { - QTimer::singleShot(1000, [mainUiFile]() { - Core::EditorManager::openEditor(mainUiFile, Utils::Id()); - }); + const auto qmlBuildSystem = qobject_cast( + activeTarget()->buildSystem()); + if (!qmlBuildSystem) return; - } - Utils::FilePaths uiFiles = collectUiQmlFilesForFolder( - projectDirectory().pathAppended("content")); - if (uiFiles.isEmpty()) { - uiFiles = collectUiQmlFilesForFolder(projectDirectory()); - if (uiFiles.isEmpty()) - return; - } - - Utils::FilePath currentFile; - if (auto cd = Core::EditorManager::currentDocument()) - currentFile = cd->filePath(); - - if (currentFile.isEmpty() || !isKnownFile(currentFile)) { - QTimer::singleShot(1000, [uiFiles]() { - Core::EditorManager::openEditor(uiFiles.first(), Utils::Id()); + const auto openFile = [&](const Utils::FilePath file) { + //why is this timer needed here? + QTimer::singleShot(1000, this, [file] { + Core::EditorManager::openEditor(file, Utils::Id()); }); - } + }; + + const Utils::FilePath fileToOpen = qmlBuildSystem->getStartupQmlFileWithFallback(); + if (!fileToOpen.isEmpty() && fileToOpen.exists() && !fileToOpen.isDir()) + openFile(fileToOpen); } Project::RestoreResult QmlProject::fromMap(const QVariantMap &map, QString *errorMessage) @@ -175,6 +159,14 @@ Utils::FilePaths QmlProject::collectUiQmlFilesForFolder(const Utils::FilePath &f return uiFiles; } +Utils::FilePaths QmlProject::collectQmlFiles() const +{ + const Utils::FilePaths qmlFiles = files([&](const Node *node) { + return node->filePath().completeSuffix() == "qml"; + }); + return qmlFiles; +} + Tasks QmlProject::projectIssues(const Kit *k) const { Tasks result = Project::projectIssues(k); diff --git a/src/plugins/studiowelcome/studiowelcomeplugin.cpp b/src/plugins/studiowelcome/studiowelcomeplugin.cpp index 7769f5f470e..f2123cd2b2e 100644 --- a/src/plugins/studiowelcome/studiowelcomeplugin.cpp +++ b/src/plugins/studiowelcome/studiowelcomeplugin.cpp @@ -102,30 +102,20 @@ static StudioWelcomePlugin *s_pluginInstance = nullptr; static Utils::FilePath getMainUiFileWithFallback() { - auto project = ProjectExplorer::ProjectManager::startupProject(); + const auto project = ProjectExplorer::ProjectManager::startupProject(); if (!project) return {}; if (!project->activeTarget()) return {}; - auto qmlBuildSystem = qobject_cast( + const auto qmlBuildSystem = qobject_cast( project->activeTarget()->buildSystem()); if (!qmlBuildSystem) return {}; - auto mainUiFile = qmlBuildSystem->mainUiFilePath(); - if (mainUiFile.exists()) - return mainUiFile; - - const Utils::FilePaths uiFiles = project->files([&](const ProjectExplorer::Node *node) { - return node->filePath().completeSuffix() == "ui.qml"; - }); - if (!uiFiles.isEmpty()) - return uiFiles.first(); - - return {}; + return qmlBuildSystem->getStartupQmlFileWithFallback(); } std::unique_ptr makeUserFeedbackSettings() @@ -254,14 +244,16 @@ public: return; m_blockOpenRecent = true; - const FilePath projectFile = FilePath::fromVariant(data(index(row, 0), ProjectModel::FilePathRole)); + const FilePath projectFile = FilePath::fromVariant( + data(index(row, 0), ProjectModel::FilePathRole)); if (projectFile.exists()) { const ProjectExplorerPlugin::OpenProjectResult result = ProjectExplorer::ProjectExplorerPlugin::openProject(projectFile); if (!result && !result.alreadyOpen().isEmpty()) { - const auto mainUiFile = getMainUiFileWithFallback(); - if (mainUiFile.exists()) - Core::EditorManager::openEditor(mainUiFile, Utils::Id()); + const auto fileToOpen = getMainUiFileWithFallback(); + if (!fileToOpen.isEmpty() && fileToOpen.exists() && !fileToOpen.isDir()) { + Core::EditorManager::openEditor(fileToOpen, Utils::Id()); + } }; } @@ -413,20 +405,25 @@ static QString tags(const FilePath &projectFilePath) const QByteArray data = reader.data(); - bool mcu = data.contains("qtForMCUs: true"); + const bool isQt6 = data.contains("qt6Project: true"); + const bool isMcu = data.contains("qtForMCUs: true"); - if (data.contains("qt6Project: true")) + if (isQt6) ret.append("Qt 6"); - else if (mcu) - ret.append("Qt For MCU"); else ret.append("Qt 5"); + if (isMcu) + ret.append("Qt For MCU"); + return ret.join(","); } QVariant ProjectModel::data(const QModelIndex &index, int role) const { + if (index.row() >= ProjectExplorer::ProjectExplorerPlugin::recentProjects().count()) + return {}; + const ProjectExplorer::RecentProjectsEntry data = ProjectExplorer::ProjectExplorerPlugin::recentProjects().at(index.row()); switch (role) { diff --git a/src/tools/qml2puppet/instances/nodeinstanceclientproxy.cpp b/src/tools/qml2puppet/instances/nodeinstanceclientproxy.cpp index ffafb7bb00e..489c8c840b7 100644 --- a/src/tools/qml2puppet/instances/nodeinstanceclientproxy.cpp +++ b/src/tools/qml2puppet/instances/nodeinstanceclientproxy.cpp @@ -79,6 +79,7 @@ NodeInstanceClientProxy::NodeInstanceClientProxy(QObject *parent) : QObject(parent) , m_inputIoDevice(nullptr) , m_outputIoDevice(nullptr) + , m_localSocket(nullptr) , m_writeCommandCounter(0) , m_synchronizeId(-1) { @@ -101,6 +102,7 @@ void NodeInstanceClientProxy::initializeSocket() m_inputIoDevice = localSocket; m_outputIoDevice = localSocket; + m_localSocket = localSocket; } void NodeInstanceClientProxy::initializeCapturedStream(const QString &fileName) @@ -145,28 +147,28 @@ bool compareCommands(const QVariant &command, const QVariant &controlCommand) static const int debugOutputCommandType = QMetaType::type("DebugOutputCommand"); static const int changeSelectionCommandType = QMetaType::type("ChangeSelectionCommand"); - if (command.userType() == controlCommand.userType()) { - if (command.userType() == informationChangedCommandType) + if (command.typeId() == controlCommand.typeId()) { + if (command.typeId() == informationChangedCommandType) return command.value() == controlCommand.value(); - else if (command.userType() == valuesChangedCommandType) + else if (command.typeId() == valuesChangedCommandType) return command.value() == controlCommand.value(); - else if (command.userType() == valuesModifiedCommandType) + else if (command.typeId() == valuesModifiedCommandType) return command.value() == controlCommand.value(); - else if (command.userType() == pixmapChangedCommandType) + else if (command.typeId() == pixmapChangedCommandType) return command.value() == controlCommand.value(); - else if (command.userType() == childrenChangedCommandType) + else if (command.typeId() == childrenChangedCommandType) return command.value() == controlCommand.value(); - else if (command.userType() == statePreviewImageChangedCommandType) + else if (command.typeId() == statePreviewImageChangedCommandType) return command.value() == controlCommand.value(); - else if (command.userType() == componentCompletedCommandType) + else if (command.typeId() == componentCompletedCommandType) return command.value() == controlCommand.value(); - else if (command.userType() == synchronizeCommandType) + else if (command.typeId() == synchronizeCommandType) return command.value() == controlCommand.value(); - else if (command.userType() == tokenCommandType) + else if (command.typeId() == tokenCommandType) return command.value() == controlCommand.value(); - else if (command.userType() == debugOutputCommandType) + else if (command.typeId() == debugOutputCommandType) return command.value() == controlCommand.value(); - else if (command.userType() == changeSelectionCommandType) + else if (command.typeId() == changeSelectionCommandType) return command.value() == controlCommand.value(); } @@ -188,8 +190,8 @@ void NodeInstanceClientProxy::writeCommand(const QVariant &command) } } else if (m_outputIoDevice) { #ifdef NANOTRACE_ENABLED - if (command.userType() != QMetaType::type("PuppetAliveCommand")) { - if (command.userType() == QMetaType::type("SyncNanotraceCommand")) { + if (command.typeId() != QMetaType::type("PuppetAliveCommand")) { + if (command.typeId() == QMetaType::type("SyncNanotraceCommand")) { SyncNanotraceCommand cmd = command.value(); NANOTRACE_INSTANT_ARGS("Sync", "writeCommand", {"name", cmd.name().toStdString()}, @@ -288,6 +290,8 @@ void NodeInstanceClientProxy::sceneCreated(const SceneCreatedCommand &command) void NodeInstanceClientProxy::flush() { + if (m_localSocket) + m_localSocket->flush(); } void NodeInstanceClientProxy::synchronizeWithClientProcess() @@ -391,8 +395,8 @@ void NodeInstanceClientProxy::readDataStream() QVariant command = readCommandFromIOStream(m_inputIoDevice, &readCommandCounter, &blockSize); #ifdef NANOTRACE_ENABLED - if (command.userType() != QMetaType::type("EndNanotraceCommand")) { - if (command.userType() == QMetaType::type("SyncNanotraceCommand")) { + if (command.typeId() != QMetaType::type("EndNanotraceCommand")) { + if (command.typeId() == QMetaType::type("SyncNanotraceCommand")) { SyncNanotraceCommand cmd = command.value(); NANOTRACE_INSTANT_ARGS("Sync", "readCommand", {"name", cmd.name().toStdString()}, @@ -570,7 +574,7 @@ void NodeInstanceClientProxy::dispatchCommand(const QVariant &command) static const int startNanotraceCommandType = QMetaType::type("StartNanotraceCommand"); static const int endNanotraceCommandType = QMetaType::type("EndNanotraceCommand"); - const int commandType = command.userType(); + const int commandType = command.typeId(); if (commandType == inputEventCommandType) inputEvent(command.value()); @@ -620,13 +624,13 @@ void NodeInstanceClientProxy::dispatchCommand(const QVariant &command) } else if (commandType == changeSelectionCommandType) { ChangeSelectionCommand changeSelectionCommand = command.value(); changeSelection(changeSelectionCommand); - } else if (command.userType() == changeLanguageCommand) { + } else if (command.typeId() == changeLanguageCommand) { changeLanguage(command.value()); - } else if (command.userType() == changePreviewImageSizeCommand) { + } else if (command.typeId() == changePreviewImageSizeCommand) { changePreviewImageSize(command.value()); - } else if (command.userType() == startNanotraceCommandType) { + } else if (command.typeId() == startNanotraceCommandType) { startNanotrace(command.value()); - } else if (command.userType() == endNanotraceCommandType) { + } else if (command.typeId() == endNanotraceCommandType) { NANOTRACE_SHUTDOWN(); } else { Q_ASSERT(false); diff --git a/src/tools/qml2puppet/instances/nodeinstanceclientproxy.h b/src/tools/qml2puppet/instances/nodeinstanceclientproxy.h index 8015dd01920..46d7eebfe67 100644 --- a/src/tools/qml2puppet/instances/nodeinstanceclientproxy.h +++ b/src/tools/qml2puppet/instances/nodeinstanceclientproxy.h @@ -117,6 +117,7 @@ private: QTimer m_puppetAliveTimer; QIODevice *m_inputIoDevice; QIODevice *m_outputIoDevice; + QLocalSocket *m_localSocket; std::unique_ptr m_nodeInstanceServer; quint32 m_writeCommandCounter; int m_synchronizeId; diff --git a/src/tools/qml2puppet/mockfiles/qt5/EditView3D.qml b/src/tools/qml2puppet/mockfiles/qt5/EditView3D.qml index bc8ef4e46b7..1860e70efb4 100644 --- a/src/tools/qml2puppet/mockfiles/qt5/EditView3D.qml +++ b/src/tools/qml2puppet/mockfiles/qt5/EditView3D.qml @@ -181,20 +181,20 @@ Item { } } - function alignCamerasToView() + function alignCamerasToView(cameraNodes) { if (editView) { - cameraControl.alignCameras(selectedNodes); + cameraControl.alignCameras(cameraNodes); var propertyNames = ["position", "eulerRotation"]; - viewRoot.changeObjectProperty(selectedNodes, propertyNames); - viewRoot.commitObjectProperty(selectedNodes, propertyNames); + viewRoot.changeObjectProperty(cameraNodes, propertyNames); + viewRoot.commitObjectProperty(cameraNodes, propertyNames); } } - function alignViewToCamera() + function alignViewToCamera(cameraNodes) { if (editView) - cameraControl.alignView(selectedNodes); + cameraControl.alignView(cameraNodes); } function updateViewStates(viewStates) diff --git a/src/tools/qml2puppet/mockfiles/qt6/EditView3D.qml b/src/tools/qml2puppet/mockfiles/qt6/EditView3D.qml index fad4ae822f5..964f47941bf 100644 --- a/src/tools/qml2puppet/mockfiles/qt6/EditView3D.qml +++ b/src/tools/qml2puppet/mockfiles/qt6/EditView3D.qml @@ -175,20 +175,20 @@ Item { } } - function alignCamerasToView() + function alignCamerasToView(cameraNodes) { if (editView) { - cameraControl.alignCameras(selectedNodes); + cameraControl.alignCameras(cameraNodes); var propertyNames = ["position", "eulerRotation"]; - viewRoot.changeObjectProperty(selectedNodes, propertyNames); - viewRoot.commitObjectProperty(selectedNodes, propertyNames); + viewRoot.changeObjectProperty(cameraNodes, propertyNames); + viewRoot.commitObjectProperty(cameraNodes, propertyNames); } } - function alignViewToCamera() + function alignViewToCamera(cameraNodes) { if (editView) - cameraControl.alignView(selectedNodes); + cameraControl.alignView(cameraNodes); } function updateViewStates(viewStates) diff --git a/src/tools/qml2puppet/qml2puppet/editor3d/generalhelper.cpp b/src/tools/qml2puppet/qml2puppet/editor3d/generalhelper.cpp index 52a3f6d74aa..bfa2fcb1ae8 100644 --- a/src/tools/qml2puppet/qml2puppet/editor3d/generalhelper.cpp +++ b/src/tools/qml2puppet/qml2puppet/editor3d/generalhelper.cpp @@ -520,8 +520,8 @@ void GeneralHelper::storeToolState(const QString &sceneId, const QString &tool, handlePendingToolStateUpdate(); QVariant theState; // Convert JS arrays to QVariantLists for easier handling down the line - // metaType().id() which only exist in Qt6 is the same as userType() - if (state.userType() != QMetaType::QString && state.canConvert(QMetaType::QVariantList)) + // metaType().id() which only exist in Qt6 is the same as typeId() + if (state.typeId() != QMetaType::QString && state.canConvert(QMetaType::QVariantList)) theState = state.value(); else theState = state; diff --git a/src/tools/qml2puppet/qml2puppet/instances/nodeinstanceserver.cpp b/src/tools/qml2puppet/qml2puppet/instances/nodeinstanceserver.cpp index aff80c62aff..3d6445e2404 100644 --- a/src/tools/qml2puppet/qml2puppet/instances/nodeinstanceserver.cpp +++ b/src/tools/qml2puppet/qml2puppet/instances/nodeinstanceserver.cpp @@ -1058,6 +1058,21 @@ QList NodeInstanceServer::allView3DInstances() const return view3Ds; } +QList NodeInstanceServer::allCameraInstances() const +{ + QList cameras; + std::copy_if(nodeInstances().cbegin(), + nodeInstances().cend(), + std::back_inserter(cameras), + [](const ServerNodeInstance &instance) { + return instance.isValid() + && ServerNodeInstance::isSubclassOf(instance.internalObject(), + QByteArrayLiteral("QQuick3DCamera")); + }); + + return cameras; +} + void NodeInstanceServer::setStateInstance(const ServerNodeInstance &stateInstance) { m_activeStateInstance = stateInstance; @@ -1194,7 +1209,7 @@ ValuesChangedCommand NodeInstanceServer::createValuesChangedCommand(const QList< const QList propertyNames = instance.propertyNames(); for (const PropertyName &propertyName : propertyNames) { QVariant propertyValue = instance.property(propertyName); - if (supportedVariantType(propertyValue.userType())) { + if (supportedVariantType(propertyValue.typeId())) { valueVector.append(PropertyValueContainer(instance.instanceId(), propertyName, propertyValue, PropertyName())); } @@ -1236,13 +1251,13 @@ ValuesChangedCommand NodeInstanceServer::createValuesChangedCommand(const QVecto if (instance.isValid()) { QVariant propertyValue = instance.property(propertyName); - bool isValid = QMetaType::isRegistered(propertyValue.userType()) - && supportedVariantType(propertyValue.type()); - if (!isValid && propertyValue.userType() == 0) { + bool isValid = QMetaType::isRegistered(propertyValue.typeId()) + && supportedVariantType(propertyValue.typeId()); + if (!isValid && propertyValue.typeId() == 0) { // If the property is QVariant type, invalid variant can be a valid value const QMetaObject *mo = instance.internalObject()->metaObject(); const int idx = mo->indexOfProperty(propertyName); - isValid = idx >= 0 && mo->property(idx).userType() == QMetaType::QVariant; + isValid = idx >= 0 && mo->property(idx).typeId() == QMetaType::QVariant; } if (isValid) { valueVector.append(PropertyValueContainer(instance.instanceId(), propertyName, @@ -1265,8 +1280,8 @@ ValuesModifiedCommand NodeInstanceServer::createValuesModifiedCommand( const QVariant propertyValue = property.propertyValue; if (instance.isValid()) { - if (QMetaType::isRegistered(propertyValue.userType()) - && supportedVariantType(propertyValue.type())) { + if (QMetaType::isRegistered(propertyValue.typeId()) + && supportedVariantType(propertyValue.typeId())) { valueVector.append(PropertyValueContainer(instance.instanceId(), propertyName, propertyValue, diff --git a/src/tools/qml2puppet/qml2puppet/instances/nodeinstanceserver.h b/src/tools/qml2puppet/qml2puppet/instances/nodeinstanceserver.h index 0fed4790baf..f4eee1e8745 100644 --- a/src/tools/qml2puppet/qml2puppet/instances/nodeinstanceserver.h +++ b/src/tools/qml2puppet/qml2puppet/instances/nodeinstanceserver.h @@ -180,6 +180,7 @@ public: QList allGroupStateInstances() const; QList allView3DInstances() const; + QList allCameraInstances() const; void notifyPropertyChange(qint32 instanceid, const PropertyName &propertyName); diff --git a/src/tools/qml2puppet/qml2puppet/instances/objectnodeinstance.cpp b/src/tools/qml2puppet/qml2puppet/instances/objectnodeinstance.cpp index 48b42e70295..24ac4004115 100644 --- a/src/tools/qml2puppet/qml2puppet/instances/objectnodeinstance.cpp +++ b/src/tools/qml2puppet/qml2puppet/instances/objectnodeinstance.cpp @@ -843,7 +843,7 @@ QObject *ObjectNodeInstance::createComponentWrap(const QString &nodeSource, cons //The component might also be shipped with Creator. //To avoid trouble with import "." we use the component shipped with Creator. -static inline QString fixComponentPathForIncompatibleQt(const QString &componentPath) +inline static QString fixComponentPathForIncompatibleQt(const QString &componentPath) { QString result = componentPath; const QLatin1String importString("/imports/"); diff --git a/src/tools/qml2puppet/qml2puppet/instances/qt5bakelightsnodeinstanceserver.cpp b/src/tools/qml2puppet/qml2puppet/instances/qt5bakelightsnodeinstanceserver.cpp index 4287808c8a8..2a1aff912ac 100644 --- a/src/tools/qml2puppet/qml2puppet/instances/qt5bakelightsnodeinstanceserver.cpp +++ b/src/tools/qml2puppet/qml2puppet/instances/qt5bakelightsnodeinstanceserver.cpp @@ -97,10 +97,11 @@ void Qt5BakeLightsNodeInstanceServer::bakeLights() switch (status) { case QQuick3DLightmapBaker::BakingStatus::Progress: case QQuick3DLightmapBaker::BakingStatus::Warning: - case QQuick3DLightmapBaker::BakingStatus::Error: + case QQuick3DLightmapBaker::BakingStatus::Error: { nodeInstanceClient()->handlePuppetToCreatorCommand( - {PuppetToCreatorCommand::BakeLightsProgress, msg.value_or("")}); - break; + {PuppetToCreatorCommand::BakeLightsProgress, msg.value_or("")}); + nodeInstanceClient()->flush(); + } break; case QQuick3DLightmapBaker::BakingStatus::Cancelled: abort(tr("Baking cancelled.")); break; diff --git a/src/tools/qml2puppet/qml2puppet/instances/qt5informationnodeinstanceserver.cpp b/src/tools/qml2puppet/qml2puppet/instances/qt5informationnodeinstanceserver.cpp index 0d7b4fa215c..b4c47a0a2a9 100644 --- a/src/tools/qml2puppet/qml2puppet/instances/qt5informationnodeinstanceserver.cpp +++ b/src/tools/qml2puppet/qml2puppet/instances/qt5informationnodeinstanceserver.cpp @@ -179,6 +179,7 @@ void Qt5InformationNodeInstanceServer::createAuxiliaryQuickView(const QUrl &url, #else viewData.renderControl = new QQuickRenderControl; viewData.window = new QQuickWindow(viewData.renderControl); + setPipelineCacheConfig(viewData.window); viewData.renderControl->initialize(); #endif QQmlComponent component(engine()); @@ -654,7 +655,7 @@ Qt5InformationNodeInstanceServer::propertyToPropertyValueTriples( QVector result; InstancePropertyValueTriple propTriple; - if (variant.type() == QVariant::Vector3D) { + if (variant.typeId() == QVariant::Vector3D) { auto vector3d = variant.value(); if (vector3d.isNull()) @@ -950,6 +951,18 @@ void Qt5InformationNodeInstanceServer::removeNode3D(QObject *node) m_active3DView = nullptr; updateActiveSceneToEditView3D(); } + if (m_selectedCameras.contains(node)) { + m_selectedCameras.remove(node); + } else { + auto cit = m_selectedCameras.constBegin(); + while (cit != m_selectedCameras.constEnd()) { + if (cit.value().contains(node)) { + m_selectedCameras[cit.key()].removeOne(node); + break; + } + ++cit; + } + } } void Qt5InformationNodeInstanceServer::resolveSceneRoots() @@ -1130,6 +1143,16 @@ void Qt5InformationNodeInstanceServer::doRender3DEditView() m_render3DEditViewTimer.start(17); // 16.67ms = ~60fps, rounds up to 17 --m_need3DEditViewRender; } +#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 1) + else { + static bool pipelineSaved = false; + if (!pipelineSaved) { + // Store pipeline cache for quicker initialization in future + savePipelineCacheData(); + pipelineSaved = true; + } + } +#endif #ifdef FPS_COUNTER // Force constant rendering for accurate fps count @@ -2173,6 +2196,7 @@ void Qt5InformationNodeInstanceServer::changeSelection(const ChangeSelectionComm QVariantList selectedObjs; QObject *firstSceneRoot = nullptr; ServerNodeInstance firstInstance; + QObjectList selectedCameras; #ifdef QUICK3D_PARTICLES_MODULE QList selectedParticleSystems; #endif @@ -2215,15 +2239,20 @@ void Qt5InformationNodeInstanceServer::changeSelection(const ChangeSelectionComm if (node) { const auto childItems = node->childItems(); for (const auto &childItem : childItems) { - if (qobject_cast(childItem) && !hasInstanceForObject(childItem)) + if (qobject_cast(childItem)) return true; } } #endif return false; }; - if (object && (firstSceneRoot != object || isSelectableAsRoot())) + if (object && (firstSceneRoot != object || isSelectableAsRoot())) { selectedObjs << objectToVariant(object); +#ifdef QUICK3D_MODULE + if (qobject_cast(object)) + selectedCameras << object; +#endif + } } } @@ -2241,6 +2270,11 @@ void Qt5InformationNodeInstanceServer::changeSelection(const ChangeSelectionComm updateActiveSceneToEditView3D(); } + // Only update selected cameras if there are cameras in selection. + // This way m_selectedCameras retains previous camera selection. + if (!selectedCameras.isEmpty()) + m_selectedCameras.insert(m_active3DScene, selectedCameras); + // Ensure the UI has enough selection box items. If it doesn't yet have them, which can be the // case when the first selection processed is a multiselection, we wait a bit as // using the new boxes immediately leads to visual glitches. @@ -2297,6 +2331,45 @@ void Qt5InformationNodeInstanceServer::setSceneEnvironmentColor(const PropertyVa #endif } +// Returns list of camera objects to align +// If m_selectedCameras contains cameras, return those +// If no cameras have been selected yet, return camera associated with current view3D, if any +// If scene is not View3D scene, return first camera in the scene +QVariantList Qt5InformationNodeInstanceServer::alignCameraList() const +{ +#ifdef QUICK3D_MODULE + QVariantList cameras; + if (m_selectedCameras.contains(m_active3DScene)) { + const QObjectList cameraList = m_selectedCameras[m_active3DScene]; + for (const auto camera : cameraList) { + if (hasInstanceForObject(camera) && find3DSceneRoot(camera) == m_active3DScene) + cameras.append(objectToVariant(camera)); + } + } + + if (cameras.isEmpty()) { + if (auto activeView = qobject_cast(m_active3DView)) { + if (auto camera = activeView->camera()) { + if (hasInstanceForObject(camera) && find3DSceneRoot(camera) == m_active3DScene) + cameras.append(objectToVariant(camera)); + } + } + } + + if (cameras.isEmpty()) { + const QList allCameras = allCameraInstances(); + for (const auto &camera : allCameras) { + if (find3DSceneRoot(camera) == m_active3DScene) { + cameras.append(objectToVariant(camera.internalObject())); + break; + } + } + } + + return cameras; +#endif +} + void Qt5InformationNodeInstanceServer::changePropertyValues(const ChangeValuesCommand &command) { bool hasDynamicProperties = false; @@ -2375,10 +2448,12 @@ void Qt5InformationNodeInstanceServer::view3DAction(const View3DActionCommand &c QMetaObject::invokeMethod(m_editView3DData.rootItem, "fitToView"); break; case View3DActionType::AlignCamerasToView: - QMetaObject::invokeMethod(m_editView3DData.rootItem, "alignCamerasToView"); + QMetaObject::invokeMethod(m_editView3DData.rootItem, "alignCamerasToView", + Q_ARG(QVariant, alignCameraList())); break; case View3DActionType::AlignViewToCamera: - QMetaObject::invokeMethod(m_editView3DData.rootItem, "alignViewToCamera"); + QMetaObject::invokeMethod(m_editView3DData.rootItem, "alignViewToCamera", + Q_ARG(QVariant, alignCameraList())); break; case View3DActionType::SelectionModeToggle: updatedToolState.insert("selectionMode", command.isEnabled() ? 1 : 0); diff --git a/src/tools/qml2puppet/qml2puppet/instances/qt5informationnodeinstanceserver.h b/src/tools/qml2puppet/qml2puppet/instances/qt5informationnodeinstanceserver.h index c8b6c1c2507..8d02b586c20 100644 --- a/src/tools/qml2puppet/qml2puppet/instances/qt5informationnodeinstanceserver.h +++ b/src/tools/qml2puppet/qml2puppet/instances/qt5informationnodeinstanceserver.h @@ -135,6 +135,7 @@ private: void handleParticleSystemDeselected(); #endif void setSceneEnvironmentColor(const PropertyValueContainer &container); + QVariantList alignCameraList() const; RenderViewData m_editView3DData; RenderViewData m_modelNode3DImageViewData; @@ -172,6 +173,9 @@ private: int m_need3DEditViewRender = 0; QSet m_dynamicObjectConstructors; + // Current or previous camera selections for each scene + QHash m_selectedCameras; // key: scene root, value: camera node + struct PreviewData { QString env; QString envValue; diff --git a/src/tools/qml2puppet/qml2puppet/instances/qt5nodeinstanceserver.cpp b/src/tools/qml2puppet/qml2puppet/instances/qt5nodeinstanceserver.cpp index 74481d150fc..e520079a5d1 100644 --- a/src/tools/qml2puppet/qml2puppet/instances/qt5nodeinstanceserver.cpp +++ b/src/tools/qml2puppet/qml2puppet/instances/qt5nodeinstanceserver.cpp @@ -41,6 +41,14 @@ #include #endif +#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 1) +#include +#include +#include +#include +#include +#endif + namespace QmlDesigner { Qt5NodeInstanceServer::Qt5NodeInstanceServer(NodeInstanceClientInterface *nodeInstanceClient) @@ -90,6 +98,7 @@ void Qt5NodeInstanceServer::initializeView() #else m_viewData.renderControl = new QQuickRenderControl; m_viewData.window = new QQuickWindow(m_viewData.renderControl); + setPipelineCacheConfig(m_viewData.window); m_viewData.renderControl->initialize(); m_qmlEngine = new QQmlEngine; #endif @@ -160,6 +169,20 @@ void Qt5NodeInstanceServer::setupScene(const CreateSceneCommand &command) setupInstances(command); resizeCanvasToRootItem(); + +#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 1) + if (!m_pipelineCacheLocation.isEmpty()) { + QString fileId = command.fileUrl.toLocalFile(); + fileId.remove(':'); + fileId.remove('/'); + fileId.remove('.'); + m_pipelineCacheFile = QStringLiteral("%1/%2").arg(m_pipelineCacheLocation, fileId); + + QFile cacheFile(m_pipelineCacheFile); + if (cacheFile.open(QIODevice::ReadOnly)) + m_pipelineCacheData = cacheFile.readAll(); + } +#endif } QList subItems(QQuickItem *parentItem) @@ -185,7 +208,61 @@ const QList Qt5NodeInstanceServer::allItems() const bool Qt5NodeInstanceServer::rootIsRenderable3DObject() const { return rootNodeInstance().isSubclassOf("QQuick3DNode") - || rootNodeInstance().isSubclassOf("QQuick3DMaterial"); + || rootNodeInstance().isSubclassOf("QQuick3DMaterial"); +} + +void Qt5NodeInstanceServer::savePipelineCacheData() +{ +#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 1) + if (!m_viewData.rhi) + return; + + QByteArray pipelineData = m_viewData.rhi->pipelineCacheData(); + + if (pipelineData.isEmpty()) + return; + + char count = 0; + if (!m_pipelineCacheData.isEmpty()) + count = m_pipelineCacheData[m_pipelineCacheData.size() - 1]; + pipelineData.append(++count); + + const bool needWrite = m_pipelineCacheData.size() != pipelineData.size() + && !m_pipelineCacheFile.isEmpty(); + + if (needWrite) { + m_pipelineCacheData = pipelineData; + + QTimer::singleShot(0, this, [this]() { + QFile cacheFile(m_pipelineCacheFile); + + // Cache file can grow indefinitely, so let's just purge it every so often. + // The count is stored as the last char in the data. + char count = m_pipelineCacheData[m_pipelineCacheData.size() - 1]; + if (count > 25) + cacheFile.remove(); + else if (cacheFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) + cacheFile.write(m_pipelineCacheData); + }); + } +#endif +} + +void Qt5NodeInstanceServer::setPipelineCacheConfig([[maybe_unused]] QQuickWindow *w) +{ +#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 1) + // This dummy file is not actually used for cache as we manage cache save/load ourselves, + // but some file needs to be set to enable pipeline caching + const QString cachePath = QStandardPaths::writableLocation(QStandardPaths::CacheLocation); + m_pipelineCacheLocation = QStringLiteral("%1/%2").arg(cachePath, "pipecache"); + QDir(m_pipelineCacheLocation).mkpath("."); + const QString dummyCache = m_pipelineCacheLocation + "/dummycache"; + + QQuickGraphicsConfiguration config = w->graphicsConfiguration(); + config.setPipelineCacheSaveFile(dummyCache); + config.setAutomaticPipelineCache(false); + w->setGraphicsConfiguration(config); +#endif } bool Qt5NodeInstanceServer::initRhi([[maybe_unused]] RenderViewData &viewData) @@ -204,6 +281,10 @@ bool Qt5NodeInstanceServer::initRhi([[maybe_unused]] RenderViewData &viewData) qWarning() << __FUNCTION__ << "Rhi is null"; return false; } +#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 1) + if (!m_pipelineCacheData.isEmpty()) + viewData.rhi->setPipelineCacheData(m_pipelineCacheData.left(m_pipelineCacheData.size() - 1)); +#endif } auto cleanRhiResources = [&viewData]() { diff --git a/src/tools/qml2puppet/qml2puppet/instances/qt5nodeinstanceserver.h b/src/tools/qml2puppet/qml2puppet/instances/qt5nodeinstanceserver.h index ccbcc5c1e39..b76e639897a 100644 --- a/src/tools/qml2puppet/qml2puppet/instances/qt5nodeinstanceserver.h +++ b/src/tools/qml2puppet/qml2puppet/instances/qt5nodeinstanceserver.h @@ -59,6 +59,8 @@ protected: void setupScene(const CreateSceneCommand &command) override; const QList allItems() const; bool rootIsRenderable3DObject() const; + void savePipelineCacheData(); + void setPipelineCacheConfig(QQuickWindow *w); struct RenderViewData { QPointer window = nullptr; @@ -80,6 +82,9 @@ protected: private: RenderViewData m_viewData; + QByteArray m_pipelineCacheData; + QString m_pipelineCacheLocation; + QString m_pipelineCacheFile; std::unique_ptr m_designerSupport; QQmlEngine *m_qmlEngine = nullptr; }; diff --git a/src/tools/qml2puppet/qmlprivategate/qmlprivategate.cpp b/src/tools/qml2puppet/qmlprivategate/qmlprivategate.cpp index 7fd4e75dc23..a8c715c9958 100644 --- a/src/tools/qml2puppet/qmlprivategate/qmlprivategate.cpp +++ b/src/tools/qml2puppet/qmlprivategate/qmlprivategate.cpp @@ -110,8 +110,8 @@ PropertyNameList allPropertyNamesInline(QObject *object, inspectedObjects, depth + 1)); } - } else if (QQmlGadgetPtrWrapper *valueType - = QQmlGadgetPtrWrapper::instance(qmlEngine(object), metaProperty.userType())) { + } else if (QQmlGadgetPtrWrapper *valueType = QQmlGadgetPtrWrapper::instance( + qmlEngine(object), metaProperty.typeId())) { valueType->setValue(metaProperty.read(object)); propertyNameList.append(baseName + QQuickDesignerSupport::PropertyName(metaProperty.name())); @@ -224,8 +224,7 @@ static QString qmlDesignerRCPath() QVariant fixResourcePaths(const QVariant &value) { - if (value.type() == QVariant::Url) - { + if (value.typeId() == QVariant::Url) { const QUrl url = value.toUrl(); if (url.scheme() == QLatin1String("qrc")) { const QString path = QLatin1String("qrc:") + url.path(); @@ -246,7 +245,7 @@ QVariant fixResourcePaths(const QVariant &value) } } } - if (value.type() == QVariant::String) { + if (value.typeId() == QVariant::String) { const QString str = value.toString(); if (str.contains(QLatin1String("qrc:"))) { if (!qmlDesignerRCPath().isEmpty()) { diff --git a/tests/auto/qml/CMakeLists.txt b/tests/auto/qml/CMakeLists.txt index a1fbe474570..4aa7c363f9b 100644 --- a/tests/auto/qml/CMakeLists.txt +++ b/tests/auto/qml/CMakeLists.txt @@ -8,6 +8,5 @@ add_subdirectory(qmldesigner) add_subdirectory(qmleditor) add_subdirectory(qmljssimplereader) add_subdirectory(qmljsutils) -add_subdirectory(qmlprojectmanager) add_subdirectory(qrcparser) add_subdirectory(reformatter) diff --git a/tests/auto/qml/qmldesigner/CMakeLists.txt b/tests/auto/qml/qmldesigner/CMakeLists.txt index cf8d848b073..c03e09799e8 100644 --- a/tests/auto/qml/qmldesigner/CMakeLists.txt +++ b/tests/auto/qml/qmldesigner/CMakeLists.txt @@ -1,2 +1,2 @@ add_subdirectory(coretests) -add_subdirectory(wizard) +# add_subdirectory(wizard) diff --git a/tests/auto/qml/qmldesigner/testconnectionmanager.cpp b/tests/auto/qml/qmldesigner/testconnectionmanager.cpp index 0db53e538ea..9341d39a454 100644 --- a/tests/auto/qml/qmldesigner/testconnectionmanager.cpp +++ b/tests/auto/qml/qmldesigner/testconnectionmanager.cpp @@ -40,7 +40,7 @@ void TestConnectionManager::dispatchCommand(const QVariant &command, Connection { static const int synchronizeCommandType = QMetaType::type("SynchronizeCommand"); - if (command.userType() == synchronizeCommandType) { + if (command.typeId() == synchronizeCommandType) { SynchronizeCommand synchronizeCommand = command.value(); m_synchronizeId = synchronizeCommand.synchronizeId(); } else { diff --git a/tests/auto/qml/qmldesigner/wizard/CMakeLists.txt b/tests/auto/qml/qmldesigner/wizard/CMakeLists.txt index 9a50fab71be..c61214d404f 100644 --- a/tests/auto/qml/qmldesigner/wizard/CMakeLists.txt +++ b/tests/auto/qml/qmldesigner/wizard/CMakeLists.txt @@ -2,9 +2,8 @@ set(StudioWelcomeDir "${PROJECT_SOURCE_DIR}/src/plugins/studiowelcome") set(WITH_TESTS ON) -find_package(Googletest MODULE) - add_qtc_test(tst_qml_wizard + CONDITION TARGET Googletest DEPENDS Core Utils StudioWelcome ProjectExplorer QmlDesigner Googletest DEFINES QT_CREATOR diff --git a/tests/auto/qml/qmlprojectmanager/CMakeLists.txt b/tests/auto/qml/qmlprojectmanager/CMakeLists.txt deleted file mode 100644 index f7c00d44bd5..00000000000 --- a/tests/auto/qml/qmlprojectmanager/CMakeLists.txt +++ /dev/null @@ -1 +0,0 @@ -add_subdirectory(fileformat) diff --git a/tests/auto/qml/qmlprojectmanager/fileformat/CMakeLists.txt b/tests/auto/qml/qmlprojectmanager/fileformat/CMakeLists.txt deleted file mode 100644 index 315db12ac18..00000000000 --- a/tests/auto/qml/qmlprojectmanager/fileformat/CMakeLists.txt +++ /dev/null @@ -1,20 +0,0 @@ -if (NOT TARGET QmlProjectManager) - return() -endif() - -get_target_property(QmlProjectManagerSources QmlProjectManager SOURCES) -foreach(source IN LISTS QmlProjectManagerSources) - if (source MATCHES "fileformat") - list(APPEND fileformat_sources "${PROJECT_SOURCE_DIR}/src/plugins/qmlprojectmanager/${source}") - endif() -endforeach() - -#add_qtc_test(tst_qml_fileformat -# DEPENDS QmlJS Utils -# INCLUDES "${PROJECT_SOURCE_DIR}/src/plugins/qmlprojectmanager/fileformat" -# DEFINES -# QT_CREATOR -# SRCDIR="${CMAKE_CURRENT_SOURCE_DIR}" -# SOURCES tst_fileformat.cpp ${fileformat_sources} -#) - diff --git a/tests/auto/qml/qmlprojectmanager/fileformat/data/file1.qml b/tests/auto/qml/qmlprojectmanager/fileformat/data/file1.qml deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/tests/auto/qml/qmlprojectmanager/fileformat/data/file1.qrc b/tests/auto/qml/qmlprojectmanager/fileformat/data/file1.qrc deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/tests/auto/qml/qmlprojectmanager/fileformat/data/file2.qml b/tests/auto/qml/qmlprojectmanager/fileformat/data/file2.qml deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/tests/auto/qml/qmlprojectmanager/fileformat/data/image.gif b/tests/auto/qml/qmlprojectmanager/fileformat/data/image.gif deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/tests/auto/qml/qmlprojectmanager/fileformat/data/script.js b/tests/auto/qml/qmlprojectmanager/fileformat/data/script.js deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/tests/auto/qml/qmlprojectmanager/fileformat/data/subdir/file3.qml b/tests/auto/qml/qmlprojectmanager/fileformat/data/subdir/file3.qml deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/tests/auto/qml/qmlprojectmanager/fileformat/data/testFileFilter1.qmlproject b/tests/auto/qml/qmlprojectmanager/fileformat/data/testFileFilter1.qmlproject deleted file mode 100644 index 8e10572a9c4..00000000000 --- a/tests/auto/qml/qmlprojectmanager/fileformat/data/testFileFilter1.qmlproject +++ /dev/null @@ -1,6 +0,0 @@ -import QmlProject 1.0 - -Project { - QmlFiles { - } -} diff --git a/tests/auto/qml/qmlprojectmanager/fileformat/data/testFileFilter2.qmlproject b/tests/auto/qml/qmlprojectmanager/fileformat/data/testFileFilter2.qmlproject deleted file mode 100644 index 11548bb7682..00000000000 --- a/tests/auto/qml/qmlprojectmanager/fileformat/data/testFileFilter2.qmlproject +++ /dev/null @@ -1,7 +0,0 @@ -import QmlProject 1.0 - -Project { - QmlFiles { - recursive: false - } -} diff --git a/tests/auto/qml/qmlprojectmanager/fileformat/data/testFileFilter3.qmlproject b/tests/auto/qml/qmlprojectmanager/fileformat/data/testFileFilter3.qmlproject deleted file mode 100644 index 814c829234c..00000000000 --- a/tests/auto/qml/qmlprojectmanager/fileformat/data/testFileFilter3.qmlproject +++ /dev/null @@ -1,7 +0,0 @@ -import QmlProject 1.0 - -Project { - QmlFiles { - directory: "subdir" - } -} diff --git a/tests/auto/qml/qmlprojectmanager/fileformat/data/testFileFilter4.qmlproject b/tests/auto/qml/qmlprojectmanager/fileformat/data/testFileFilter4.qmlproject deleted file mode 100644 index 19f1953e817..00000000000 --- a/tests/auto/qml/qmlprojectmanager/fileformat/data/testFileFilter4.qmlproject +++ /dev/null @@ -1,11 +0,0 @@ -import QmlProject 1.0 - -Project { - QmlFiles { - directory: "." - recursive: false - } - QmlFiles { - directory: "subdir" - } -} diff --git a/tests/auto/qml/qmlprojectmanager/fileformat/data/testFileFilter5.qmlproject b/tests/auto/qml/qmlprojectmanager/fileformat/data/testFileFilter5.qmlproject deleted file mode 100644 index d464bb1c4b9..00000000000 --- a/tests/auto/qml/qmlprojectmanager/fileformat/data/testFileFilter5.qmlproject +++ /dev/null @@ -1,8 +0,0 @@ -import QmlProject 1.0 - -Project { - QmlFiles { - paths: [ "file1.qml", - "file2.qml" ] - } -} diff --git a/tests/auto/qml/qmlprojectmanager/fileformat/data/testFileFilter6.qmlproject b/tests/auto/qml/qmlprojectmanager/fileformat/data/testFileFilter6.qmlproject deleted file mode 100644 index 526a8050ef3..00000000000 --- a/tests/auto/qml/qmlprojectmanager/fileformat/data/testFileFilter6.qmlproject +++ /dev/null @@ -1,7 +0,0 @@ -import QmlProject 1.0 - -Project { - ImageFiles { - directory: "." - } -} diff --git a/tests/auto/qml/qmlprojectmanager/fileformat/data/testFileFilter7.qmlproject b/tests/auto/qml/qmlprojectmanager/fileformat/data/testFileFilter7.qmlproject deleted file mode 100644 index 4eacf55c840..00000000000 --- a/tests/auto/qml/qmlprojectmanager/fileformat/data/testFileFilter7.qmlproject +++ /dev/null @@ -1,7 +0,0 @@ -import QmlProject 1.0 - -Project { - ImageFiles { - filter: "?mage.[gf]if" - } -} diff --git a/tests/auto/qml/qmlprojectmanager/fileformat/data/testFileFilter8.qmlproject b/tests/auto/qml/qmlprojectmanager/fileformat/data/testFileFilter8.qmlproject deleted file mode 100644 index 1dd518c6807..00000000000 --- a/tests/auto/qml/qmlprojectmanager/fileformat/data/testFileFilter8.qmlproject +++ /dev/null @@ -1,7 +0,0 @@ -import QmlProject 1.1 - -Project { - Files { - filter: "image.gif" - } -} diff --git a/tests/auto/qml/qmlprojectmanager/fileformat/data/testLibraryPaths.qmlproject b/tests/auto/qml/qmlprojectmanager/fileformat/data/testLibraryPaths.qmlproject deleted file mode 100644 index a9cdc3cb2f0..00000000000 --- a/tests/auto/qml/qmlprojectmanager/fileformat/data/testLibraryPaths.qmlproject +++ /dev/null @@ -1,5 +0,0 @@ -import QmlProject 1.0 - -Project { - importPaths: [ "../otherLibrary", "library" ] -} diff --git a/tests/auto/qml/qmlprojectmanager/fileformat/data/testMainFile.qmlproject b/tests/auto/qml/qmlprojectmanager/fileformat/data/testMainFile.qmlproject deleted file mode 100644 index 18e1ba8a5d7..00000000000 --- a/tests/auto/qml/qmlprojectmanager/fileformat/data/testMainFile.qmlproject +++ /dev/null @@ -1,5 +0,0 @@ -import QmlProject 1.1 - -Project { - mainFile: "file1.qml" -} diff --git a/tests/auto/qml/qmlprojectmanager/fileformat/data/testMatchesFile.qmlproject b/tests/auto/qml/qmlprojectmanager/fileformat/data/testMatchesFile.qmlproject deleted file mode 100644 index 81398d69d46..00000000000 --- a/tests/auto/qml/qmlprojectmanager/fileformat/data/testMatchesFile.qmlproject +++ /dev/null @@ -1,10 +0,0 @@ -import QmlProject 1.0 - -Project { - QmlFiles { - recursive: true - } - JavaScriptFiles { - paths: ["script.js"] - } -} diff --git a/tests/auto/qml/qmlprojectmanager/fileformat/fileformat.qbs b/tests/auto/qml/qmlprojectmanager/fileformat/fileformat.qbs deleted file mode 100644 index f32bd21c05d..00000000000 --- a/tests/auto/qml/qmlprojectmanager/fileformat/fileformat.qbs +++ /dev/null @@ -1,26 +0,0 @@ -import qbs - -QtcAutotest { - name: "QmlProjectManager file format autotest" - Depends { name: "QmlJS" } - Depends { name: "Utils" } - property path fileFormatDir: project.ide_source_tree + "/src/plugins/qmlprojectmanager/buildsystem/projectitem" - files: "tst_fileformat.cpp" - Group { - name: "Files from QmlProjectManager" - prefix: product.fileFormatDir + '/' - files: [ - "converters.cpp", - "converters.h", - "filefilteritems.cpp", - "filefilteritems.h", - "qmlprojectitem.cpp", - "qmlprojectitem.h", - ] - } - cpp.includePaths: base.concat([fileFormatDir]) - cpp.defines: base.concat([ - 'QT_CREATOR', - 'SRCDIR="' + path + '"' - ]) -} diff --git a/tests/auto/qml/qmlprojectmanager/fileformat/tst_fileformat.cpp b/tests/auto/qml/qmlprojectmanager/fileformat/tst_fileformat.cpp deleted file mode 100644 index b8b5f11dee7..00000000000 --- a/tests/auto/qml/qmlprojectmanager/fileformat/tst_fileformat.cpp +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright (C) 2016 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 - -#include "qmlprojectitem.h" - -#include - -#include - -//TESTED_COMPONENT=src/plugins/qmlprojectmanager/fileformat - -using namespace QmlProjectManager; -using namespace Utils; - -#define COMPARE_AS_SETS(actual, expected) \ - do {\ - if (!QTest::qCompare(Utils::toSet(actual), Utils::toSet(expected), #actual, #expected, __FILE__, __LINE__)) {\ - qDebug() << actual << "\nvs." << expected; \ - return;\ - }\ - } while (false) - - -class tst_FileFormat : public QObject -{ - Q_OBJECT -public: - tst_FileFormat(); - -private slots: - void testFileFilter(); - void testMatchesFile(); - void testLibraryPaths(); - void testMainFile(); -}; - -tst_FileFormat::tst_FileFormat() -{ -} - -const QString testDataDir = QLatin1String(SRCDIR "/data"); -const FilePath testDataDirPath = FilePath::fromString(testDataDir); - -static std::unique_ptr loadQmlProject(QString name) -{ - return std::unique_ptr(new QmlProjectItem( - testDataDirPath.pathAppended(name + ".qmlproject"))); -} - -void tst_FileFormat::testFileFilter() -{ - // - // Search for qml files in directory + subdirectories - // - { - auto project = loadQmlProject(QLatin1String("testFileFilter1")); - QVERIFY(project); - QVERIFY(!project->project().isEmpty()); - - FilePaths expectedFiles{ - testDataDirPath / "file1.qml", - testDataDirPath / "file2.qml", - testDataDirPath / "subdir/file3.qml" - }; - COMPARE_AS_SETS(project->files(), expectedFiles); - } - - // - // search for all qml files in directory - // - { - auto project = loadQmlProject(QLatin1String("testFileFilter2")); - QVERIFY(project); - QVERIFY(!project->project().isEmpty()); - - FilePaths expectedFiles{ testDataDirPath / "file1.qml", testDataDirPath / "file2.qml" }; - COMPARE_AS_SETS(project->files(), expectedFiles); - } - - // - // search for all qml files in subdirectory - // - { - auto project = loadQmlProject(QLatin1String("testFileFilter3")); - QVERIFY(project); - QVERIFY(!project->project().isEmpty()); - - FilePaths expectedFiles{ testDataDirPath / "subdir/file3.qml" }; - COMPARE_AS_SETS(project->files(), expectedFiles); - } - - // - // multiple entries - // - { - auto project = loadQmlProject(QLatin1String("testFileFilter4")); - QVERIFY(project); - QVERIFY(!project->project().isEmpty()); - - FilePaths expectedFiles{ - testDataDirPath / "file1.qml", - testDataDirPath / "file2.qml", - testDataDirPath / "/subdir/file3.qml" - }; - QCOMPARE(project->files().size(), 3); - COMPARE_AS_SETS(project->files(), expectedFiles); - } - - // - // include specific list - // - { - auto project = loadQmlProject(QLatin1String("testFileFilter5")); - QVERIFY(project); - QVERIFY(!project->project().isEmpty()); - - FilePaths expectedFiles{ testDataDirPath / "file1.qml", testDataDirPath / "file2.qml" }; - COMPARE_AS_SETS(project->files(), expectedFiles); - } - - // - // include specific list - // - { - auto project = loadQmlProject(QLatin1String("testFileFilter6")); - QVERIFY(project); - QVERIFY(!project->project().isEmpty()); - - FilePaths expectedFiles{ testDataDirPath / "image.gif" }; - COMPARE_AS_SETS(project->files(), expectedFiles); - } - - // - // use wildcards - // - { - auto project = loadQmlProject(QLatin1String("testFileFilter7")); - QVERIFY(project); - QVERIFY(!project->project().isEmpty()); - - FilePaths expectedFiles{ testDataDirPath / "image.gif" }; - COMPARE_AS_SETS(project->files(), expectedFiles); - } - - // - // use Files element (1.1) - // - { - auto project = loadQmlProject(QLatin1String("testFileFilter8")); - QVERIFY(project); - QVERIFY(!project->project().isEmpty()); - - FilePaths expectedFiles{ testDataDirPath / "image.gif" }; - COMPARE_AS_SETS(project->files(), expectedFiles); - } -} - -void tst_FileFormat::testMatchesFile() -{ - // - // search for qml files in local directory - // - auto project = loadQmlProject(QLatin1String("testMatchesFile")); - QVERIFY(project); - QVERIFY(!project->project().isEmpty()); - - QVERIFY(project->matchesFile(testDataDir + "/file1.qml")); - QVERIFY(project->matchesFile(testDataDir + "/notyetexistingfile.qml")); - QVERIFY(project->matchesFile(testDataDir + "/subdir/notyetexistingfile.qml")); - QVERIFY(project->matchesFile(testDataDir + "/script.js")); - QVERIFY(!project->matchesFile(testDataDir + "/script.css")); -} - -void tst_FileFormat::testLibraryPaths() -{ - // - // search for qml files in local directory - // - auto project = loadQmlProject(QLatin1String("testLibraryPaths")); - QVERIFY(project); - QVERIFY(!project->project().isEmpty()); - - const QDir base(testDataDir); - const QStringList expectedPaths({base.relativeFilePath(SRCDIR "/otherLibrary"), - base.relativeFilePath(SRCDIR "/data/library")}); - COMPARE_AS_SETS(project->importPaths(), expectedPaths); -} - -void tst_FileFormat::testMainFile() -{ - // - // search for qml files in local directory - // - auto project = loadQmlProject(QLatin1String("testMainFile")); - QVERIFY(project); - QVERIFY(!project->project().isEmpty()); - - QCOMPARE(project->mainFile(), QString("file1.qml")); -} - -QTEST_GUILESS_MAIN(tst_FileFormat); -#include "tst_fileformat.moc" diff --git a/tests/auto/qml/qmlprojectmanager/qmlprojectmanager.qbs b/tests/auto/qml/qmlprojectmanager/qmlprojectmanager.qbs deleted file mode 100644 index 1d1f1ea988c..00000000000 --- a/tests/auto/qml/qmlprojectmanager/qmlprojectmanager.qbs +++ /dev/null @@ -1,6 +0,0 @@ -import qbs - -Project { - name: "QmlProjectManager autotests" - references: "fileformat/fileformat.qbs" -} diff --git a/tests/auto/qml/reformatter/annotations.qml b/tests/auto/qml/reformatter/annotations.qml new file mode 100644 index 00000000000..ee3d1fb45ca --- /dev/null +++ b/tests/auto/qml/reformatter/annotations.qml @@ -0,0 +1,22 @@ +import QtQuick + +@Annotation {} +Item { + // properties + property int foo + property alias bar: x + @Annotation2 { + someproperty: 10 + } + id: someId + + @Annotation3 { + someproperty: 10 + } + Rectangle { + // properties + property int foo + property alias bar: x + id: someId2 + } +} diff --git a/tests/system/suite_tools/tst_git_local/test.py b/tests/system/suite_tools/tst_git_local/test.py index ab36b86b251..9ce9a0b3164 100644 --- a/tests/system/suite_tools/tst_git_local/test.py +++ b/tests/system/suite_tools/tst_git_local/test.py @@ -206,6 +206,7 @@ def main(): test.compare(str(changed.plainText), "Retrieving data failed.", "Showing an invalid commit can't succeed but Creator survived.") invokeMenuItem("File", "Exit") + waitForCleanShutdown() def deleteProject(): path = os.path.join(srcPath, projectName) diff --git a/tests/unit/.clang-format b/tests/unit/.clang-format index e1dad0fa0c0..968dfdec7d1 100644 --- a/tests/unit/.clang-format +++ b/tests/unit/.clang-format @@ -6,10 +6,12 @@ AlignConsecutiveDeclarations: false AlignEscapedNewlines: DontAlign AlignOperands: true AlignTrailingComments: true +AllowAllArgumentsOnNextLine: true AllowAllParametersOfDeclarationOnNextLine: true AllowShortBlocksOnASingleLine: false AllowShortCaseLabelsOnASingleLine: false AllowShortFunctionsOnASingleLine: Inline +AllowShortLambdasOnASingleLine: All AllowShortIfStatementsOnASingleLine: false AllowShortLoopsOnASingleLine: false AlwaysBreakAfterReturnType: None @@ -32,13 +34,16 @@ BraceWrapping: SplitEmptyFunction: false SplitEmptyRecord: false SplitEmptyNamespace: false +BreakAfterAttributes: Never BreakBeforeBinaryOperators: All BreakBeforeBraces: Custom +BreakBeforeConceptDeclarations: Always BreakBeforeInheritanceComma: false BreakBeforeTernaryOperators: true BreakConstructorInitializersBeforeComma: false BreakConstructorInitializers: BeforeComma BreakAfterJavaFieldAnnotations: false +BreakInheritanceList: AfterComma BreakStringLiterals: true ColumnLimit: 100 CommentPragmas: '^ IWYU pragma:' @@ -49,6 +54,8 @@ ContinuationIndentWidth: 4 Cpp11BracedListStyle: true DerivePointerAlignment: false DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock ExperimentalAutoDetectBinPacking: false FixNamespaceComments: true ForEachMacros: @@ -56,17 +63,23 @@ ForEachMacros: - foreach - Q_FOREACH - BOOST_FOREACH +#IncludeBlocks: Regroup IncludeCategories: - Regex: '^/data` path. +* Name your test files as `foo-test.cpp`. * Always include `googletest.h` header. Without that you may get the printer function can be broken because the are not anymore ODR (because of weak linking to printers for example). It is also necessary for nice printers, also adds Qt known matchers. +* Use snake_case for the test name to improve readability for long sentences ## Building Tests diff --git a/tests/unit/tests/CMakeLists.txt b/tests/unit/tests/CMakeLists.txt new file mode 100644 index 00000000000..fe1f0c84b32 --- /dev/null +++ b/tests/unit/tests/CMakeLists.txt @@ -0,0 +1,23 @@ +find_package(Qt6 COMPONENTS QmlDomPrivate QmlCompilerPrivate) + +if (MSVC) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj") +elseif (MINGW) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wa,-mbig-obj") +endif() + +set(QtCreatorLibsDir "${QtCreator_SOURCE_DIR}/src/libs") +set(QtCreatorPluginsDir "${QtCreator_SOURCE_DIR}/src/plugins") +set(QtCreatorResourcesDir "${QtCreator_SOURCE_DIR}/share/qtcreator") +set(QmlDesignerDir "${QtCreatorPluginsDir}/qmldesigner") + +set(UnittestStubsDir "${CMAKE_CURRENT_SOURCE_DIR}/stubs") +set(UnittestUtilsDir "${CMAKE_CURRENT_SOURCE_DIR}/utils") +set(UnittestPrintersDir "${CMAKE_CURRENT_SOURCE_DIR}/printers") + +add_subdirectory(testdesignercore) +add_subdirectory(utils) +add_subdirectory(mocks) +add_subdirectory(printers) +add_subdirectory(matchers) +add_subdirectory(unittests) diff --git a/tests/unit/tests/matchers/CMakeLists.txt b/tests/unit/tests/matchers/CMakeLists.txt new file mode 100644 index 00000000000..2aebc0bc58b --- /dev/null +++ b/tests/unit/tests/matchers/CMakeLists.txt @@ -0,0 +1,9 @@ +add_qtc_library(TestMatchers OBJECT + EXCLUDE_FROM_INSTALL + SKIP_AUTOMOC ON + PUBLIC_INCLUDES ${CMAKE_CURRENT_LIST_DIR} + DEPENDS + Googletest Utils + SOURCES + unittest-matchers.h +) diff --git a/tests/unit/unittest/unittest-matchers.h b/tests/unit/tests/matchers/unittest-matchers.h similarity index 90% rename from tests/unit/unittest/unittest-matchers.h rename to tests/unit/tests/matchers/unittest-matchers.h index 0f59a5e79a8..f4ff225c747 100644 --- a/tests/unit/unittest/unittest-matchers.h +++ b/tests/unit/tests/matchers/unittest-matchers.h @@ -4,6 +4,7 @@ #pragma once #include +#include #include @@ -90,6 +91,16 @@ public: return false; } + bool MatchAndExplain(const QByteArray &s, testing::MatchResultListener *listener) const + { + if (s.isEmpty()) { + return true; + } + + *listener << "whose size is " << s.size(); + return false; + } + void DescribeTo(std::ostream *os) const { *os << "is empty"; } void DescribeNegationTo(std::ostream *os) const { *os << "isn't empty"; } diff --git a/tests/unit/tests/mocks/CMakeLists.txt b/tests/unit/tests/mocks/CMakeLists.txt new file mode 100644 index 00000000000..b357164c93e --- /dev/null +++ b/tests/unit/tests/mocks/CMakeLists.txt @@ -0,0 +1,40 @@ +add_qtc_library(TestMocks OBJECT + EXCLUDE_FROM_INSTALL + SKIP_AUTOMOC ON + PUBLIC_INCLUDES ${CMAKE_CURRENT_LIST_DIR} + DEPENDS + Qt::Core Qt::Widgets Googletest Sqlite TestDesignerCore + SOURCES + abstractviewmock.h + externaldependenciesmock.h + filesystemmock.h + imagecachecollectormock.h + mockimagecachegenerator.h + mockimagecachestorage.h + mocklistmodeleditorview.h + mockmutex.h + mockqfilesystemwatcher.h + mocksqlitestatement.h + mocksqlitetransactionbackend.h + mocksyntaxhighligher.h + mocktimer.cpp + mocktimer.h + mocktimestampprovider.h + modelresourcemanagementmock.h + projectstoragemock.cpp + projectstoragemock.h + projectstoragepathwatchermock.h + projectstoragepathwatchernotifiermock.h + qmldocumentparsermock.h + qmltypesparsermock.h + sourcepathcachemock.h + sqlitedatabasemock.h + sqlitereadstatementmock.cpp + sqlitereadstatementmock.h + sqlitereadwritestatementmock.cpp + sqlitereadwritestatementmock.h + sqlitestatementmock.h + sqlitetransactionbackendmock.h + sqlitewritestatementmock.cpp + sqlitewritestatementmock.h +) diff --git a/tests/unit/unittest/abstractviewmock.h b/tests/unit/tests/mocks/abstractviewmock.h similarity index 85% rename from tests/unit/unittest/abstractviewmock.h rename to tests/unit/tests/mocks/abstractviewmock.h index d846311995f..c3a3be581cb 100644 --- a/tests/unit/unittest/abstractviewmock.h +++ b/tests/unit/tests/mocks/abstractviewmock.h @@ -3,9 +3,9 @@ #pragma once -#include +#include "../utils/googletest.h" -#include +#include class AbstractViewMock : public QmlDesigner::AbstractView { diff --git a/tests/unit/unittest/externaldependenciesmock.h b/tests/unit/tests/mocks/externaldependenciesmock.h similarity index 98% rename from tests/unit/unittest/externaldependenciesmock.h rename to tests/unit/tests/mocks/externaldependenciesmock.h index 22654f70551..37c2da1850c 100644 --- a/tests/unit/unittest/externaldependenciesmock.h +++ b/tests/unit/tests/mocks/externaldependenciesmock.h @@ -3,7 +3,7 @@ #pragma once -#include "googletest.h" +#include "../utils/googletest.h" #include diff --git a/tests/unit/unittest/filesystemmock.h b/tests/unit/tests/mocks/filesystemmock.h similarity index 96% rename from tests/unit/unittest/filesystemmock.h rename to tests/unit/tests/mocks/filesystemmock.h index 4e72ff6f7f2..cb1d4df4bc4 100644 --- a/tests/unit/unittest/filesystemmock.h +++ b/tests/unit/tests/mocks/filesystemmock.h @@ -3,7 +3,7 @@ #pragma once -#include "googletest.h" +#include "../utils/googletest.h" #include #include diff --git a/tests/unit/unittest/imagecachecollectormock.h b/tests/unit/tests/mocks/imagecachecollectormock.h similarity index 97% rename from tests/unit/unittest/imagecachecollectormock.h rename to tests/unit/tests/mocks/imagecachecollectormock.h index 81575b7604f..d8a8608faa6 100644 --- a/tests/unit/unittest/imagecachecollectormock.h +++ b/tests/unit/tests/mocks/imagecachecollectormock.h @@ -3,7 +3,7 @@ #pragma once -#include "googletest.h" +#include "../utils/googletest.h" #include diff --git a/tests/unit/unittest/mockimagecachegenerator.h b/tests/unit/tests/mocks/mockimagecachegenerator.h similarity index 96% rename from tests/unit/unittest/mockimagecachegenerator.h rename to tests/unit/tests/mocks/mockimagecachegenerator.h index e7118de5664..30d322ac7f2 100644 --- a/tests/unit/unittest/mockimagecachegenerator.h +++ b/tests/unit/tests/mocks/mockimagecachegenerator.h @@ -3,7 +3,7 @@ #pragma once -#include "googletest.h" +#include "../utils/googletest.h" #include diff --git a/tests/unit/unittest/mockimagecachestorage.h b/tests/unit/tests/mocks/mockimagecachestorage.h similarity index 98% rename from tests/unit/unittest/mockimagecachestorage.h rename to tests/unit/tests/mocks/mockimagecachestorage.h index 9eb8af53726..e723adbcaaa 100644 --- a/tests/unit/unittest/mockimagecachestorage.h +++ b/tests/unit/tests/mocks/mockimagecachestorage.h @@ -3,7 +3,7 @@ #pragma once -#include "googletest.h" +#include "../utils/googletest.h" #include diff --git a/tests/unit/unittest/mocklistmodeleditorview.h b/tests/unit/tests/mocks/mocklistmodeleditorview.h similarity index 96% rename from tests/unit/unittest/mocklistmodeleditorview.h rename to tests/unit/tests/mocks/mocklistmodeleditorview.h index 0f6ff38742e..df228dcf2f7 100644 --- a/tests/unit/unittest/mocklistmodeleditorview.h +++ b/tests/unit/tests/mocks/mocklistmodeleditorview.h @@ -3,9 +3,9 @@ #pragma once -#include +#include "../utils/googletest.h" -#include +#include class MockListModelEditorView : public QmlDesigner::AbstractView { diff --git a/tests/unit/unittest/mockmutex.h b/tests/unit/tests/mocks/mockmutex.h similarity index 94% rename from tests/unit/unittest/mockmutex.h rename to tests/unit/tests/mocks/mockmutex.h index a26acb7a35a..2422ca96106 100644 --- a/tests/unit/unittest/mockmutex.h +++ b/tests/unit/tests/mocks/mockmutex.h @@ -3,7 +3,7 @@ #pragma once -#include "googletest.h" +#include "../utils/googletest.h" class MockMutex { diff --git a/tests/unit/unittest/mockqfilesystemwatcher.h b/tests/unit/tests/mocks/mockqfilesystemwatcher.h similarity index 66% rename from tests/unit/unittest/mockqfilesystemwatcher.h rename to tests/unit/tests/mocks/mockqfilesystemwatcher.h index 8a334c9afe0..be0dc9cfb29 100644 --- a/tests/unit/unittest/mockqfilesystemwatcher.h +++ b/tests/unit/tests/mocks/mockqfilesystemwatcher.h @@ -3,7 +3,7 @@ #pragma once -#include "googletest.h" +#include "../utils/googletest.h" #include @@ -12,10 +12,8 @@ class MockQFileSytemWatcher : public QObject Q_OBJECT public: - MOCK_METHOD1(addPaths, - void (const QStringList&)); - MOCK_METHOD1(removePaths, - void (const QStringList&)); + MOCK_METHOD1(addPaths, void(const QStringList &)); + MOCK_METHOD1(removePaths, void(const QStringList &)); signals: void fileChanged(const QString &); diff --git a/tests/unit/unittest/mocksqlitestatement.h b/tests/unit/tests/mocks/mocksqlitestatement.h similarity index 98% rename from tests/unit/unittest/mocksqlitestatement.h rename to tests/unit/tests/mocks/mocksqlitestatement.h index 20eed627bf4..f34b13f6d0f 100644 --- a/tests/unit/unittest/mocksqlitestatement.h +++ b/tests/unit/tests/mocks/mocksqlitestatement.h @@ -3,7 +3,7 @@ #pragma once -#include "googletest.h" +#include "../utils/googletest.h" #include "sqlitedatabasemock.h" #include diff --git a/tests/unit/unittest/mocksqlitetransactionbackend.h b/tests/unit/tests/mocks/mocksqlitetransactionbackend.h similarity index 95% rename from tests/unit/unittest/mocksqlitetransactionbackend.h rename to tests/unit/tests/mocks/mocksqlitetransactionbackend.h index e4114b537d4..478579d2395 100644 --- a/tests/unit/unittest/mocksqlitetransactionbackend.h +++ b/tests/unit/tests/mocks/mocksqlitetransactionbackend.h @@ -4,7 +4,7 @@ #pragma once -#include "googletest.h" +#include "../utils/googletest.h" #include diff --git a/tests/unit/unittest/mocksyntaxhighligher.h b/tests/unit/tests/mocks/mocksyntaxhighligher.h similarity index 91% rename from tests/unit/unittest/mocksyntaxhighligher.h rename to tests/unit/tests/mocks/mocksyntaxhighligher.h index 1b5f773835f..4ba7b773142 100644 --- a/tests/unit/unittest/mocksyntaxhighligher.h +++ b/tests/unit/tests/mocks/mocksyntaxhighligher.h @@ -3,7 +3,7 @@ #pragma once -#include "googletest.h" +#include "../utils/googletest.h" #include diff --git a/tests/unit/unittest/mocktimer.cpp b/tests/unit/tests/mocks/mocktimer.cpp similarity index 91% rename from tests/unit/unittest/mocktimer.cpp rename to tests/unit/tests/mocks/mocktimer.cpp index 9bd979ccc53..4dfac31ec86 100644 --- a/tests/unit/unittest/mocktimer.cpp +++ b/tests/unit/tests/mocks/mocktimer.cpp @@ -13,9 +13,7 @@ MockTimer::~MockTimer() emitTimoutIfStarted(); } -void MockTimer::setSingleShot(bool) -{ -} +void MockTimer::setSingleShot(bool) {} void MockTimer::emitTimoutIfStarted() { diff --git a/tests/unit/unittest/mocktimer.h b/tests/unit/tests/mocks/mocktimer.h similarity index 83% rename from tests/unit/unittest/mocktimer.h rename to tests/unit/tests/mocks/mocktimer.h index 478b0939a92..ea0adf8c6b3 100644 --- a/tests/unit/unittest/mocktimer.h +++ b/tests/unit/tests/mocks/mocktimer.h @@ -2,7 +2,7 @@ // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 #pragma once -#include "googletest.h" +#include "../utils/googletest.h" #include @@ -14,8 +14,7 @@ public: MockTimer(); ~MockTimer(); - MOCK_METHOD1(start, - void (int)); + MOCK_METHOD1(start, void(int)); void setSingleShot(bool); diff --git a/tests/unit/unittest/mocktimestampprovider.h b/tests/unit/tests/mocks/mocktimestampprovider.h similarity index 93% rename from tests/unit/unittest/mocktimestampprovider.h rename to tests/unit/tests/mocks/mocktimestampprovider.h index d954838819f..1b447a2b4ce 100644 --- a/tests/unit/unittest/mocktimestampprovider.h +++ b/tests/unit/tests/mocks/mocktimestampprovider.h @@ -3,7 +3,7 @@ #pragma once -#include "googletest.h" +#include "../utils/googletest.h" #include diff --git a/tests/unit/unittest/modelresourcemanagementmock.h b/tests/unit/tests/mocks/modelresourcemanagementmock.h similarity index 52% rename from tests/unit/unittest/modelresourcemanagementmock.h rename to tests/unit/tests/mocks/modelresourcemanagementmock.h index 0b98adfcff0..87454b2d201 100644 --- a/tests/unit/unittest/modelresourcemanagementmock.h +++ b/tests/unit/tests/mocks/modelresourcemanagementmock.h @@ -3,7 +3,7 @@ #pragma once -#include "googletest.h" +#include "../utils/googletest.h" #include #include @@ -12,12 +12,12 @@ class ModelResourceManagementMock : public QmlDesigner::ModelResourceManagementI { public: MOCK_METHOD(QmlDesigner::ModelResourceSet, - removeNode, - (const QmlDesigner::ModelNode &), + removeNodes, + (QmlDesigner::ModelNodes, QmlDesigner::Model *), (const, override)); MOCK_METHOD(QmlDesigner::ModelResourceSet, - removeProperty, - (const QmlDesigner::AbstractProperty &), + removeProperties, + (QmlDesigner::AbstractProperties, QmlDesigner::Model *), (const, override)); }; @@ -28,14 +28,16 @@ public: : mock{mock} {} - QmlDesigner::ModelResourceSet removeNode(const QmlDesigner::ModelNode &node) const override + QmlDesigner::ModelResourceSet removeNodes(QmlDesigner::ModelNodes nodes, + QmlDesigner::Model *model) const override { - return mock.removeNode(node); + return mock.removeNodes(std::move(nodes), model); } - QmlDesigner::ModelResourceSet removeProperty(const QmlDesigner::AbstractProperty &property) const override + QmlDesigner::ModelResourceSet removeProperties(QmlDesigner::AbstractProperties properties, + QmlDesigner::Model *model) const override { - return mock.removeProperty(property); + return mock.removeProperties(std::move(properties), model); } ModelResourceManagementMock &mock; diff --git a/tests/unit/tests/mocks/projectstoragemock.cpp b/tests/unit/tests/mocks/projectstoragemock.cpp new file mode 100644 index 00000000000..2c3a4a622ff --- /dev/null +++ b/tests/unit/tests/mocks/projectstoragemock.cpp @@ -0,0 +1,245 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +#include "projectstoragemock.h" + +#include + +using QmlDesigner::ModuleId; +using QmlDesigner::PropertyDeclarationId; +using QmlDesigner::TypeId; +using QmlDesigner::TypeIds; +using QmlDesigner::Storage::PropertyDeclarationTraits; + +namespace Storage = QmlDesigner::Storage; + +namespace { + +template +void incrementBasicId(BasicId &id) +{ + id = BasicId::create(id.internalId() + 1); +} + +void setupIsBasedOn(ProjectStorageMock &mock) +{ + auto call = [&](TypeId typeId, auto... ids) -> bool { + return (mock.isBasedOn(typeId, ids) || ...); + }; + ON_CALL(mock, isBasedOn(_, _, _)).WillByDefault(call); + ON_CALL(mock, isBasedOn(_, _, _, _)).WillByDefault(call); + ON_CALL(mock, isBasedOn(_, _, _, _, _)).WillByDefault(call); + ON_CALL(mock, isBasedOn(_, _, _, _, _, _)).WillByDefault(call); + ON_CALL(mock, isBasedOn(_, _, _, _, _, _, _)).WillByDefault(call); + ON_CALL(mock, isBasedOn(_, _, _, _, _, _, _, _)).WillByDefault(call); +} + +} // namespace + +ModuleId ProjectStorageMock::createModule(Utils::SmallStringView moduleName) +{ + static ModuleId moduleId; + incrementBasicId(moduleId); + + ON_CALL(*this, moduleId(Eq(moduleName))).WillByDefault(Return(moduleId)); + + return moduleId; +} + +PropertyDeclarationId ProjectStorageMock::createProperty(TypeId typeId, + Utils::SmallString name, + PropertyDeclarationTraits traits, + TypeId propertyTypeId) +{ + static PropertyDeclarationId propertyId; + incrementBasicId(propertyId); + + ON_CALL(*this, propertyDeclarationId(Eq(typeId), Eq(name))).WillByDefault(Return(propertyId)); + ON_CALL(*this, propertyName(Eq(propertyId))).WillByDefault(Return(name)); + + ON_CALL(*this, propertyDeclaration(Eq(propertyId))) + .WillByDefault(Return( + QmlDesigner::Storage::Info::PropertyDeclaration{typeId, name, traits, propertyTypeId})); + + auto ids = localPropertyDeclarationIds(typeId); + ids.push_back(propertyId); + ON_CALL(*this, propertyDeclarationIds(Eq(typeId))).WillByDefault(Return(ids)); + ON_CALL(*this, localPropertyDeclarationIds(Eq(typeId))).WillByDefault(Return(ids)); + + return propertyId; +} + +QmlDesigner::PropertyDeclarationId ProjectStorageMock::createProperty( + QmlDesigner::TypeId typeId, Utils::SmallString name, QmlDesigner::TypeId propertyTypeId) +{ + return createProperty(typeId, name, {}, propertyTypeId); +} + +void ProjectStorageMock::createSignal(QmlDesigner::TypeId typeId, Utils::SmallString name) +{ + auto signalNames = signalDeclarationNames(typeId); + signalNames.push_back(name); + ON_CALL(*this, signalDeclarationNames(Eq(typeId))).WillByDefault(Return(signalNames)); +} + +void ProjectStorageMock::createFunction(QmlDesigner::TypeId typeId, Utils::SmallString name) +{ + auto functionNames = functionDeclarationNames(typeId); + functionNames.push_back(name); + ON_CALL(*this, functionDeclarationNames(Eq(typeId))).WillByDefault(Return(functionNames)); +} + +TypeId ProjectStorageMock::createType(ModuleId moduleId, + Utils::SmallStringView typeName, + Utils::SmallStringView defaultPropertyName, + PropertyDeclarationTraits defaultPropertyTraits, + TypeId defaultPropertyTypeId, + Storage::TypeTraits typeTraits, + TypeIds baseTypeIds) +{ + static TypeId typeId; + incrementBasicId(typeId); + + ON_CALL(*this, typeId(Eq(moduleId), Eq(typeName), _)).WillByDefault(Return(typeId)); + PropertyDeclarationId defaultPropertyDeclarationId; + if (defaultPropertyName.size()) { + if (!defaultPropertyTypeId) { + defaultPropertyTypeId = typeId; + } + + defaultPropertyDeclarationId = createProperty(typeId, + defaultPropertyName, + defaultPropertyTraits, + defaultPropertyTypeId); + } + + ON_CALL(*this, type(Eq(typeId))) + .WillByDefault(Return(Storage::Info::Type{defaultPropertyDeclarationId, typeTraits})); + + ON_CALL(*this, isBasedOn(Eq(typeId), Eq(typeId))).WillByDefault(Return(true)); + + for (TypeId baseTypeId : baseTypeIds) + ON_CALL(*this, isBasedOn(Eq(typeId), Eq(baseTypeId))).WillByDefault(Return(true)); + + return typeId; +} + +QmlDesigner::TypeId ProjectStorageMock::createType(QmlDesigner::ModuleId moduleId, + Utils::SmallStringView typeName, + QmlDesigner::Storage::TypeTraits typeTraits, + QmlDesigner::TypeIds baseTypeIds) +{ + return createType(moduleId, typeName, {}, {}, TypeId{}, typeTraits, baseTypeIds); +} + +TypeId ProjectStorageMock::createObject(ModuleId moduleId, + Utils::SmallStringView typeName, + Utils::SmallStringView defaultPropertyName, + PropertyDeclarationTraits defaultPropertyTraits, + QmlDesigner::TypeId defaultPropertyTypeId, + TypeIds baseTypeIds) +{ + return createType(moduleId, + typeName, + defaultPropertyName, + defaultPropertyTraits, + defaultPropertyTypeId, + Storage::TypeTraits::Reference, + baseTypeIds); +} + +TypeId ProjectStorageMock::createObject(ModuleId moduleId, + Utils::SmallStringView typeName, + TypeIds baseTypeIds) +{ + return createType(moduleId, typeName, Storage::TypeTraits::Reference, baseTypeIds); +} + +void ProjectStorageMock::setupQtQtuick() +{ + setupIsBasedOn(*this); + + auto qmlModuleId = createModule("QML"); + auto qtQmlModelsModuleId = createModule("QtQml.Models"); + auto qtQuickModuleId = createModule("QtQuick"); + auto qtQuickNativeModuleId = createModule("QtQuick-cppnative"); + + createType(qmlModuleId, "int", Storage::TypeTraits::Value); + + auto qtObjectId = createObject(qmlModuleId, + "QtObject", + "children", + PropertyDeclarationTraits::IsList, + TypeId{}); + + auto listElementId = createObject(qtQmlModelsModuleId, "ListElement", {qtObjectId}); + createObject(qtQmlModelsModuleId, + "ListModel", + "children", + PropertyDeclarationTraits::IsList, + listElementId, + {qtObjectId}); + + auto itemId = createObject(qtQuickModuleId, + "Item", + "data", + PropertyDeclarationTraits::IsList, + qtObjectId, + {qtObjectId}); + createObject(qtQuickModuleId, + "ListView", + "data", + PropertyDeclarationTraits::IsList, + qtObjectId, + {qtObjectId, itemId}); + createObject(qtQuickModuleId, "StateGroup", {qtObjectId}); + createObject(qtQuickModuleId, + "State", + "changes", + PropertyDeclarationTraits::IsList, + qtObjectId, + {qtObjectId}); + auto animationId = createObject(qtQuickModuleId, "Animation", {qtObjectId}); + createObject(qtQuickModuleId, + "Transition", + "animations", + PropertyDeclarationTraits::IsList, + animationId, + {qtObjectId}); + createObject(qtQuickModuleId, "PropertyAnimation", {qtObjectId}); + auto stateOperationsId = createObject(qtQuickNativeModuleId, + " QQuickStateOperation", + {qtObjectId}); + createObject(qtQuickModuleId, "PropertyChanges", {qtObjectId, stateOperationsId}); + + auto qtQuickTimelineModuleId = createModule("QtQuick.Timeline"); + createObject(qtQuickTimelineModuleId, "KeyframeGroup", {qtObjectId}); + createObject(qtQuickTimelineModuleId, "Keyframe", {qtObjectId}); + + auto flowViewModuleId = createModule("FlowView"); + createObject(flowViewModuleId, + "FlowActionArea", + "data", + PropertyDeclarationTraits::IsList, + qtObjectId, + {qtObjectId, itemId}); + createObject(flowViewModuleId, + "FlowWildcard", + "data", + PropertyDeclarationTraits::IsList, + qtObjectId, + {qtObjectId}); + createObject(flowViewModuleId, "FlowDecision", {qtObjectId}); + createObject(flowViewModuleId, "FlowTransition", {qtObjectId}); + createObject(flowViewModuleId, + "FlowItem", + "data", + PropertyDeclarationTraits::IsList, + qtObjectId, + {qtObjectId, itemId}); +} + +void ProjectStorageMock::setupCommonTypeCache() +{ + ON_CALL(*this, commonTypeCache()).WillByDefault(ReturnRef(typeCache)); +} diff --git a/tests/unit/unittest/projectstoragemock.h b/tests/unit/tests/mocks/projectstoragemock.h similarity index 74% rename from tests/unit/unittest/projectstoragemock.h rename to tests/unit/tests/mocks/projectstoragemock.h index cb30521c959..fc2544979ae 100644 --- a/tests/unit/unittest/projectstoragemock.h +++ b/tests/unit/tests/mocks/projectstoragemock.h @@ -3,10 +3,11 @@ #pragma once -#include "googletest.h" +#include "../utils/googletest.h" #include "sqlitedatabasemock.h" +#include #include #include #include @@ -15,6 +16,48 @@ class ProjectStorageMock : public QmlDesigner::ProjectStorageInterface { public: void setupQtQtuick(); + void setupCommonTypeCache(); + + QmlDesigner::ModuleId createModule(Utils::SmallStringView moduleName); + + QmlDesigner::TypeId createType( + QmlDesigner::ModuleId moduleId, + Utils::SmallStringView typeName, + Utils::SmallStringView defaultPropertyName, + QmlDesigner::Storage::PropertyDeclarationTraits defaultPropertyTraits, + QmlDesigner::TypeId defaultPropertyTypeId, + QmlDesigner::Storage::TypeTraits typeTraits, + QmlDesigner::TypeIds baseTypeIds = {}); + + QmlDesigner::TypeId createType(QmlDesigner::ModuleId moduleId, + Utils::SmallStringView typeName, + QmlDesigner::Storage::TypeTraits typeTraits, + QmlDesigner::TypeIds baseTypeIds = {}); + + QmlDesigner::TypeId createObject( + QmlDesigner::ModuleId moduleId, + Utils::SmallStringView typeName, + Utils::SmallStringView defaultPropertyName, + QmlDesigner::Storage::PropertyDeclarationTraits defaultPropertyTraits, + QmlDesigner::TypeId defaultPropertyTypeId, + QmlDesigner::TypeIds baseTypeIds = {}); + + QmlDesigner::TypeId createObject(QmlDesigner::ModuleId moduleId, + Utils::SmallStringView typeName, + QmlDesigner::TypeIds baseTypeIds = {}); + + QmlDesigner::PropertyDeclarationId createProperty( + QmlDesigner::TypeId typeId, + Utils::SmallString name, + QmlDesigner::Storage::PropertyDeclarationTraits traits, + QmlDesigner::TypeId propertyTypeId); + + QmlDesigner::PropertyDeclarationId createProperty(QmlDesigner::TypeId typeId, + Utils::SmallString name, + QmlDesigner::TypeId propertyTypeId); + + void createSignal(QmlDesigner::TypeId typeId, Utils::SmallString name); + void createFunction(QmlDesigner::TypeId typeId, Utils::SmallString name); MOCK_METHOD(void, synchronize, @@ -157,10 +200,16 @@ public: (QmlDesigner::SourceId sourceId)); MOCK_METHOD(std::vector, fetchAllSourceContexts, (), ()); MOCK_METHOD(std::vector, fetchAllSources, (), ()); + + QmlDesigner::Storage::Info::CommonTypeCache typeCache{*this}; }; class ProjectStorageMockWithQtQtuick : public ProjectStorageMock { public: - ProjectStorageMockWithQtQtuick() { setupQtQtuick(); } + ProjectStorageMockWithQtQtuick() + { + setupQtQtuick(); + setupCommonTypeCache(); + } }; diff --git a/tests/unit/unittest/projectstoragepathwatchermock.h b/tests/unit/tests/mocks/projectstoragepathwatchermock.h similarity index 96% rename from tests/unit/unittest/projectstoragepathwatchermock.h rename to tests/unit/tests/mocks/projectstoragepathwatchermock.h index 97ebb65e45e..dd4e015d0b0 100644 --- a/tests/unit/unittest/projectstoragepathwatchermock.h +++ b/tests/unit/tests/mocks/projectstoragepathwatchermock.h @@ -3,7 +3,7 @@ #pragma once -#include "googletest.h" +#include "../utils/googletest.h" #include "projectstorage/projectstoragepathwatcherinterface.h" diff --git a/tests/unit/unittest/projectstoragepathwatchernotifiermock.h b/tests/unit/tests/mocks/projectstoragepathwatchernotifiermock.h similarity index 94% rename from tests/unit/unittest/projectstoragepathwatchernotifiermock.h rename to tests/unit/tests/mocks/projectstoragepathwatchernotifiermock.h index 2a5f7fa9423..1131c5f2ac3 100644 --- a/tests/unit/unittest/projectstoragepathwatchernotifiermock.h +++ b/tests/unit/tests/mocks/projectstoragepathwatchernotifiermock.h @@ -3,7 +3,7 @@ #pragma once -#include "googletest.h" +#include "../utils/googletest.h" #include diff --git a/tests/unit/unittest/qmldocumentparsermock.h b/tests/unit/tests/mocks/qmldocumentparsermock.h similarity index 95% rename from tests/unit/unittest/qmldocumentparsermock.h rename to tests/unit/tests/mocks/qmldocumentparsermock.h index 1bb41f57737..11b6cd7a1dc 100644 --- a/tests/unit/unittest/qmldocumentparsermock.h +++ b/tests/unit/tests/mocks/qmldocumentparsermock.h @@ -3,7 +3,7 @@ #pragma once -#include "googletest.h" +#include "../utils/googletest.h" #include diff --git a/tests/unit/unittest/qmltypesparsermock.h b/tests/unit/tests/mocks/qmltypesparsermock.h similarity index 95% rename from tests/unit/unittest/qmltypesparsermock.h rename to tests/unit/tests/mocks/qmltypesparsermock.h index 4368f6e821c..b4590a405f4 100644 --- a/tests/unit/unittest/qmltypesparsermock.h +++ b/tests/unit/tests/mocks/qmltypesparsermock.h @@ -3,7 +3,7 @@ #pragma once -#include "googletest.h" +#include "../utils/googletest.h" #include diff --git a/tests/unit/unittest/sourcepathcachemock.h b/tests/unit/tests/mocks/sourcepathcachemock.h similarity index 96% rename from tests/unit/unittest/sourcepathcachemock.h rename to tests/unit/tests/mocks/sourcepathcachemock.h index dd2f9e27d38..6a2cf2ec97d 100644 --- a/tests/unit/unittest/sourcepathcachemock.h +++ b/tests/unit/tests/mocks/sourcepathcachemock.h @@ -3,7 +3,7 @@ #pragma once -#include "googletest.h" +#include "../utils/googletest.h" #include #include diff --git a/tests/unit/unittest/sqlitedatabasemock.h b/tests/unit/tests/mocks/sqlitedatabasemock.h similarity index 98% rename from tests/unit/unittest/sqlitedatabasemock.h rename to tests/unit/tests/mocks/sqlitedatabasemock.h index 658a0ec88b4..5d6ab107e0a 100644 --- a/tests/unit/unittest/sqlitedatabasemock.h +++ b/tests/unit/tests/mocks/sqlitedatabasemock.h @@ -3,7 +3,7 @@ #pragma once -#include "googletest.h" +#include "../utils/googletest.h" #include "sqlitereadstatementmock.h" #include "sqlitereadwritestatementmock.h" diff --git a/tests/unit/unittest/sqlitereadstatementmock.cpp b/tests/unit/tests/mocks/sqlitereadstatementmock.cpp similarity index 100% rename from tests/unit/unittest/sqlitereadstatementmock.cpp rename to tests/unit/tests/mocks/sqlitereadstatementmock.cpp diff --git a/tests/unit/unittest/sqlitereadstatementmock.h b/tests/unit/tests/mocks/sqlitereadstatementmock.h similarity index 99% rename from tests/unit/unittest/sqlitereadstatementmock.h rename to tests/unit/tests/mocks/sqlitereadstatementmock.h index 38d7e41ecfb..615e3d23b14 100644 --- a/tests/unit/unittest/sqlitereadstatementmock.h +++ b/tests/unit/tests/mocks/sqlitereadstatementmock.h @@ -3,7 +3,7 @@ #pragma once -#include "googletest.h" +#include "../utils/googletest.h" #include #include diff --git a/tests/unit/unittest/sqlitereadwritestatementmock.cpp b/tests/unit/tests/mocks/sqlitereadwritestatementmock.cpp similarity index 100% rename from tests/unit/unittest/sqlitereadwritestatementmock.cpp rename to tests/unit/tests/mocks/sqlitereadwritestatementmock.cpp diff --git a/tests/unit/unittest/sqlitereadwritestatementmock.h b/tests/unit/tests/mocks/sqlitereadwritestatementmock.h similarity index 92% rename from tests/unit/unittest/sqlitereadwritestatementmock.h rename to tests/unit/tests/mocks/sqlitereadwritestatementmock.h index aaf59530741..8a787cfb69e 100644 --- a/tests/unit/unittest/sqlitereadwritestatementmock.h +++ b/tests/unit/tests/mocks/sqlitereadwritestatementmock.h @@ -3,7 +3,7 @@ #pragma once -#include "googletest.h" +#include "../utils/googletest.h" #include @@ -45,8 +45,8 @@ public: template auto optionalValue([[maybe_unused]] const QueryTypes &...queryValues) { - static_assert(!std::is_same_v, - "SqliteReadStatementMock::value does not handle result type!"); + static_assert(!std::is_same_v, + "SqliteReadStatementMock::value does not handle result type!"); } template diff --git a/tests/unit/unittest/sqlitestatementmock.h b/tests/unit/tests/mocks/sqlitestatementmock.h similarity index 98% rename from tests/unit/unittest/sqlitestatementmock.h rename to tests/unit/tests/mocks/sqlitestatementmock.h index bda9f537990..b641803da0a 100644 --- a/tests/unit/unittest/sqlitestatementmock.h +++ b/tests/unit/tests/mocks/sqlitestatementmock.h @@ -3,7 +3,7 @@ #pragma once -#include +#include "../utils/googletest.h" #include diff --git a/tests/unit/unittest/sqlitetransactionbackendmock.h b/tests/unit/tests/mocks/sqlitetransactionbackendmock.h similarity index 96% rename from tests/unit/unittest/sqlitetransactionbackendmock.h rename to tests/unit/tests/mocks/sqlitetransactionbackendmock.h index a633662c00b..22cf4fa44d1 100644 --- a/tests/unit/unittest/sqlitetransactionbackendmock.h +++ b/tests/unit/tests/mocks/sqlitetransactionbackendmock.h @@ -4,7 +4,7 @@ #pragma once -#include "googletest.h" +#include "../utils/googletest.h" #include diff --git a/tests/unit/unittest/sqlitewritestatementmock.cpp b/tests/unit/tests/mocks/sqlitewritestatementmock.cpp similarity index 100% rename from tests/unit/unittest/sqlitewritestatementmock.cpp rename to tests/unit/tests/mocks/sqlitewritestatementmock.cpp diff --git a/tests/unit/unittest/sqlitewritestatementmock.h b/tests/unit/tests/mocks/sqlitewritestatementmock.h similarity index 99% rename from tests/unit/unittest/sqlitewritestatementmock.h rename to tests/unit/tests/mocks/sqlitewritestatementmock.h index 2fa3146601b..458beacc5c9 100644 --- a/tests/unit/unittest/sqlitewritestatementmock.h +++ b/tests/unit/tests/mocks/sqlitewritestatementmock.h @@ -3,7 +3,7 @@ #pragma once -#include "googletest.h" +#include "../utils/googletest.h" #include #include diff --git a/tests/unit/tests/printers/CMakeLists.txt b/tests/unit/tests/printers/CMakeLists.txt new file mode 100644 index 00000000000..83f6812ef03 --- /dev/null +++ b/tests/unit/tests/printers/CMakeLists.txt @@ -0,0 +1,11 @@ +add_qtc_library(TestPrinters OBJECT + EXCLUDE_FROM_INSTALL + SKIP_AUTOMOC ON + PUBLIC_INCLUDES ${CMAKE_CURRENT_LIST_DIR} + DEPENDS + Qt::Core Qt::Widgets Sqlite Googletest TestDesignerCore + SOURCES + gtest-creator-printing.cpp gtest-creator-printing.h + gtest-qt-printing.cpp gtest-qt-printing.h + gtest-std-printing.h +) diff --git a/tests/unit/unittest/gtest-creator-printing.cpp b/tests/unit/tests/printers/gtest-creator-printing.cpp similarity index 94% rename from tests/unit/unittest/gtest-creator-printing.cpp rename to tests/unit/tests/printers/gtest-creator-printing.cpp index 722dd01bc81..9a5c000c390 100644 --- a/tests/unit/unittest/gtest-creator-printing.cpp +++ b/tests/unit/tests/printers/gtest-creator-printing.cpp @@ -9,8 +9,8 @@ #include #include -#include -#include +#include <3rdparty/sqlite/sqlite.h> +#include #include #include #include @@ -18,12 +18,10 @@ #include #include #include -#include #include #include #include #include -#include namespace std { template ostream &operator<<(ostream &out, const QVector &vector) @@ -238,6 +236,7 @@ Utils::SmallStringView operationText(int operation) std::ostream &operator<<(std::ostream &out, sqlite3_changeset_iter *iter) { +#if 0 out << "("; const char *tableName = nullptr; @@ -280,7 +279,7 @@ std::ostream &operator<<(std::ostream &out, sqlite3_changeset_iter *iter) } out << "})"; - +#endif return out; } @@ -317,6 +316,7 @@ const char *toText(LockingMode lockingMode) std::ostream &operator<<(std::ostream &out, const SessionChangeSet &changeset) { +#if 0 sqlite3_changeset_iter *iter = nullptr; sqlite3changeset_start(&iter, changeset.size(), const_cast(changeset.data())); @@ -331,7 +331,7 @@ std::ostream &operator<<(std::ostream &out, const SessionChangeSet &changeset) sqlite3changeset_finalize(iter); out << "])"; - +#endif return out; } @@ -403,39 +403,6 @@ std::ostream &operator<<(std::ostream &out, const ConstTupleIterator &iterator) } // namespace SessionChangeSetInternal } // namespace Sqlite -namespace Debugger { -std::ostream &operator<<(std::ostream &out, const DiagnosticLocation &loc) -{ - return out << "(" << loc.filePath << ", " << loc.line << ", " << loc.column << ")"; -} -} // namespace Debugger - -namespace ClangTools { -namespace Internal { -std::ostream &operator<<(std::ostream &out, const ExplainingStep &step) -{ - return out << "(" - << step.message << ", " - << step.location << ", " - << step.ranges << ", " - << step.isFixIt - << ")"; -} - -std::ostream &operator<<(std::ostream &out, const Diagnostic &diag) { - return out << "(" - << diag.name << ", " - << diag.description << ", " - << diag.category << ", " - << diag.type << ", " - << diag.location << ", " - << diag.explainingSteps << ", " - << diag.hasFixits - << ")"; -} -} // namespace Internal -} // namespace ClangTools - namespace QmlDesigner { namespace { const char *sourceTypeToText(SourceType sourceType) @@ -506,6 +473,25 @@ std::ostream &operator<<(std::ostream &out, const VariantProperty &property) << property.value() << ")"; } +std::ostream &operator<<(std::ostream &out, const AbstractProperty &property) +{ + if (!property.isValid()) + return out << "(invalid)"; + + return out << "(" << property.parentModelNode() << ", " << property.name() << ")"; +} + +std::ostream &operator<<(std::ostream &out, const ModelResourceSet::SetExpression &setExpression) +{ + return out << "(" << setExpression.property << ", " << setExpression.expression << ")"; +} + +std::ostream &operator<<(std::ostream &out, const ModelResourceSet &set) +{ + return out << "(" << set.removeModelNodes << ", " << set.removeProperties << ", " + << set.setExpressions << ")"; +} + namespace Cache { std::ostream &operator<<(std::ostream &out, const SourceContext &sourceContext) diff --git a/tests/unit/unittest/gtest-creator-printing.h b/tests/unit/tests/printers/gtest-creator-printing.h similarity index 95% rename from tests/unit/unittest/gtest-creator-printing.h rename to tests/unit/tests/printers/gtest-creator-printing.h index aa8e6e77ac3..7506f6cb11b 100644 --- a/tests/unit/unittest/gtest-creator-printing.h +++ b/tests/unit/tests/printers/gtest-creator-printing.h @@ -3,6 +3,7 @@ #pragma once +#include #include #include @@ -115,6 +116,7 @@ std::ostream &operator<<(std::ostream &out, const Diagnostic &diag); namespace QmlDesigner { class ModelNode; class VariantProperty; +class AbstractProperty; class WatcherEntry; class IdPaths; class ProjectChunkId; @@ -124,12 +126,15 @@ class Import; std::ostream &operator<<(std::ostream &out, const ModelNode &node); std::ostream &operator<<(std::ostream &out, const VariantProperty &property); +std::ostream &operator<<(std::ostream &out, const AbstractProperty &property); std::ostream &operator<<(std::ostream &out, const WatcherEntry &entry); std::ostream &operator<<(std::ostream &out, const IdPaths &idPaths); std::ostream &operator<<(std::ostream &out, const ProjectChunkId &id); std::ostream &operator<<(std::ostream &out, SourceType sourceType); std::ostream &operator<<(std::ostream &out, const FileStatus &fileStatus); std::ostream &operator<<(std::ostream &out, const Import &import); +std::ostream &operator<<(std::ostream &out, const ModelResourceSet::SetExpression &setExpression); +std::ostream &operator<<(std::ostream &out, const ModelResourceSet &modelResourceSet); namespace Cache { class SourceContext; diff --git a/tests/unit/unittest/gtest-qt-printing.cpp b/tests/unit/tests/printers/gtest-qt-printing.cpp similarity index 100% rename from tests/unit/unittest/gtest-qt-printing.cpp rename to tests/unit/tests/printers/gtest-qt-printing.cpp diff --git a/tests/unit/unittest/gtest-qt-printing.h b/tests/unit/tests/printers/gtest-qt-printing.h similarity index 100% rename from tests/unit/unittest/gtest-qt-printing.h rename to tests/unit/tests/printers/gtest-qt-printing.h diff --git a/tests/unit/unittest/gtest-std-printing.h b/tests/unit/tests/printers/gtest-std-printing.h similarity index 100% rename from tests/unit/unittest/gtest-std-printing.h rename to tests/unit/tests/printers/gtest-std-printing.h diff --git a/tests/unit/mockup/clangcodemodel/clangcompletionassistinterface.h b/tests/unit/tests/stubs/clangcodemodel/clangcompletionassistinterface.h similarity index 100% rename from tests/unit/mockup/clangcodemodel/clangcompletionassistinterface.h rename to tests/unit/tests/stubs/clangcodemodel/clangcompletionassistinterface.h diff --git a/tests/unit/mockup/coreplugin/helpitem.h b/tests/unit/tests/stubs/coreplugin/helpitem.h similarity index 100% rename from tests/unit/mockup/coreplugin/helpitem.h rename to tests/unit/tests/stubs/coreplugin/helpitem.h diff --git a/tests/unit/mockup/coreplugin/icontext.h b/tests/unit/tests/stubs/coreplugin/icontext.h similarity index 100% rename from tests/unit/mockup/coreplugin/icontext.h rename to tests/unit/tests/stubs/coreplugin/icontext.h diff --git a/tests/unit/mockup/coreplugin/icore.h b/tests/unit/tests/stubs/coreplugin/icore.h similarity index 93% rename from tests/unit/mockup/coreplugin/icore.h rename to tests/unit/tests/stubs/coreplugin/icore.h index 239085d56d6..6ede100bef9 100644 --- a/tests/unit/mockup/coreplugin/icore.h +++ b/tests/unit/tests/stubs/coreplugin/icore.h @@ -1,4 +1,4 @@ -#include "utils/fileutils.h" +#include "../utils/fileutils.h" #include diff --git a/tests/unit/mockup/coreplugin/vcsmanager.h b/tests/unit/tests/stubs/coreplugin/vcsmanager.h similarity index 100% rename from tests/unit/mockup/coreplugin/vcsmanager.h rename to tests/unit/tests/stubs/coreplugin/vcsmanager.h diff --git a/tests/unit/mockup/qmldesigner/designercore/include/documentmessage.h b/tests/unit/tests/stubs/qmldesigner/designercore/include/documentmessage.h similarity index 100% rename from tests/unit/mockup/qmldesigner/designercore/include/documentmessage.h rename to tests/unit/tests/stubs/qmldesigner/designercore/include/documentmessage.h diff --git a/tests/unit/mockup/qmldesigner/designercore/include/itemlibraryitem.h b/tests/unit/tests/stubs/qmldesigner/designercore/include/itemlibraryitem.h similarity index 100% rename from tests/unit/mockup/qmldesigner/designercore/include/itemlibraryitem.h rename to tests/unit/tests/stubs/qmldesigner/designercore/include/itemlibraryitem.h diff --git a/tests/unit/mockup/qmldesigner/designercore/include/nodeinstanceview.h b/tests/unit/tests/stubs/qmldesigner/designercore/include/nodeinstanceview.h similarity index 100% rename from tests/unit/mockup/qmldesigner/designercore/include/nodeinstanceview.h rename to tests/unit/tests/stubs/qmldesigner/designercore/include/nodeinstanceview.h diff --git a/tests/unit/mockup/qmldesigner/designercore/include/qmlmodelnodefacade.h b/tests/unit/tests/stubs/qmldesigner/designercore/include/qmlmodelnodefacade.h similarity index 100% rename from tests/unit/mockup/qmldesigner/designercore/include/qmlmodelnodefacade.h rename to tests/unit/tests/stubs/qmldesigner/designercore/include/qmlmodelnodefacade.h diff --git a/tests/unit/mockup/qmldesigner/designercore/include/qmlobjectnode.h b/tests/unit/tests/stubs/qmldesigner/designercore/include/qmlobjectnode.h similarity index 100% rename from tests/unit/mockup/qmldesigner/designercore/include/qmlobjectnode.h rename to tests/unit/tests/stubs/qmldesigner/designercore/include/qmlobjectnode.h diff --git a/tests/unit/mockup/qmldesigner/designercore/include/qmlstate.h b/tests/unit/tests/stubs/qmldesigner/designercore/include/qmlstate.h similarity index 100% rename from tests/unit/mockup/qmldesigner/designercore/include/qmlstate.h rename to tests/unit/tests/stubs/qmldesigner/designercore/include/qmlstate.h diff --git a/tests/unit/mockup/qmldesigner/designercore/include/qmltimeline.h b/tests/unit/tests/stubs/qmldesigner/designercore/include/qmltimeline.h similarity index 100% rename from tests/unit/mockup/qmldesigner/designercore/include/qmltimeline.h rename to tests/unit/tests/stubs/qmldesigner/designercore/include/qmltimeline.h diff --git a/tests/unit/mockup/qmldesigner/designercore/include/rewriterview.h b/tests/unit/tests/stubs/qmldesigner/designercore/include/rewriterview.h similarity index 100% rename from tests/unit/mockup/qmldesigner/designercore/include/rewriterview.h rename to tests/unit/tests/stubs/qmldesigner/designercore/include/rewriterview.h diff --git a/tests/unit/mockup/texteditor/assistenums.h b/tests/unit/tests/stubs/texteditor/assistenums.h similarity index 100% rename from tests/unit/mockup/texteditor/assistenums.h rename to tests/unit/tests/stubs/texteditor/assistenums.h diff --git a/tests/unit/mockup/texteditor/codeassist/assistinterface.h b/tests/unit/tests/stubs/texteditor/codeassist/assistinterface.h similarity index 100% rename from tests/unit/mockup/texteditor/codeassist/assistinterface.h rename to tests/unit/tests/stubs/texteditor/codeassist/assistinterface.h diff --git a/tests/unit/mockup/texteditor/quickfix.h b/tests/unit/tests/stubs/texteditor/quickfix.h similarity index 100% rename from tests/unit/mockup/texteditor/quickfix.h rename to tests/unit/tests/stubs/texteditor/quickfix.h diff --git a/tests/unit/mockup/texteditor/refactoringchanges.h b/tests/unit/tests/stubs/texteditor/refactoringchanges.h similarity index 89% rename from tests/unit/mockup/texteditor/refactoringchanges.h rename to tests/unit/tests/stubs/texteditor/refactoringchanges.h index 05bb9c96404..96121b59ff3 100644 --- a/tests/unit/mockup/texteditor/refactoringchanges.h +++ b/tests/unit/tests/stubs/texteditor/refactoringchanges.h @@ -3,7 +3,7 @@ #pragma once -#include "googletest.h" +// #include "../utils/googletest.h" #include #include @@ -36,18 +36,11 @@ class RefactoringFile public: RefactoringFile(std::unique_ptr &&textDocument) : textDocument(std::move(textDocument)) - { - } + {} - const QTextDocument *document() const - { - return textDocument.get(); - } + const QTextDocument *document() const { return textDocument.get(); } - void setChangeSet(const Utils::ChangeSet &changes) - { - this->changes = changes; - } + void setChangeSet(const Utils::ChangeSet &changes) { this->changes = changes; } void apply() { @@ -85,6 +78,7 @@ class RefactoringChanges { public: RefactoringChanges() {} + virtual ~RefactoringChanges() {} RefactoringFilePtr file(const Utils::FilePath &filePath) const diff --git a/tests/unit/mockup/texteditor/semantichighlighter.h b/tests/unit/tests/stubs/texteditor/semantichighlighter.h similarity index 100% rename from tests/unit/mockup/texteditor/semantichighlighter.h rename to tests/unit/tests/stubs/texteditor/semantichighlighter.h diff --git a/tests/unit/mockup/texteditor/syntaxhighlighter.h b/tests/unit/tests/stubs/texteditor/syntaxhighlighter.h similarity index 100% rename from tests/unit/mockup/texteditor/syntaxhighlighter.h rename to tests/unit/tests/stubs/texteditor/syntaxhighlighter.h diff --git a/tests/unit/tests/testdesignercore/CMakeLists.txt b/tests/unit/tests/testdesignercore/CMakeLists.txt new file mode 100644 index 00000000000..a3f1697f68a --- /dev/null +++ b/tests/unit/tests/testdesignercore/CMakeLists.txt @@ -0,0 +1,165 @@ +add_qtc_library(TestDesignerCore OBJECT + EXCLUDE_FROM_INSTALL + PUBLIC_INCLUDES ${CMAKE_CURRENT_LIST_DIR} + SKIP_AUTOMOC ON + DEPENDS + Qt::Core Qt::Network Qt::Widgets + Qt::Xml Qt::Concurrent Qt::QmlPrivate Qt::Gui + Qt::Core5Compat Utils QmlJS Sqlite + PUBLIC_DEPENDS + QmlPuppetCommunication + SOURCES_PREFIX ${QmlDesignerDir}/designercore + PUBLIC_INCLUDES + ${UnittestStubsDir} + ${UnittestStubsDir}/qmldesigner/designercore/include + ${QtCreatorLibsDir} + ${QtCreatorPluginsDir} + ${QmlDesignerDir} + ${QmlDesignerDir}/designercore + ${QmlDesignerDir}/designercore/include + ${QmlDesignerDir}/designercore/imagecache + PUBLIC_DEFINES + UNIT_TESTS + DONT_CHECK_MESSAGE_COUNTER + QTC_RESOURCE_DIR="${QtCreatorResourcesDir}" + QDS_MODEL_USE_PROJECTSTORAGEINTERFACE + QDS_USE_PROJECTSTORAGE + QMLDESIGNERCORE_STATIC_LIBRARY + QMLDESIGNER_STATIC_LIBRARY + SOURCES + exceptions/exception.cpp + exceptions/invalidargumentexception.cpp + exceptions/invalididexception.cpp + exceptions/invalidmetainfoexception.cpp + exceptions/invalidmodelnodeexception.cpp + exceptions/invalidmodelstateexception.cpp + exceptions/invalidpropertyexception.cpp + exceptions/invalidqmlsourceexception.cpp + exceptions/invalidreparentingexception.cpp + exceptions/invalidslideindexexception.cpp + exceptions/notimplementedexception.cpp + exceptions/removebasestateexception.cpp + exceptions/rewritingexception.cpp + imagecache/asynchronousexplicitimagecache.cpp + imagecache/asynchronousimagecache.cpp + imagecache/asynchronousimagefactory.cpp + imagecache/asynchronousimagefactory.h + imagecache/imagecachecollectorinterface.h + imagecache/imagecachegenerator.cpp + imagecache/imagecachegenerator.h + imagecache/imagecachegeneratorinterface.h + imagecache/imagecachestorage.h + imagecache/imagecachedispatchcollector.h + imagecache/imagecachestorageinterface.h + imagecache/synchronousimagecache.cpp + imagecache/timestampproviderinterface.h + include/abstractproperty.h + include/abstractview.h + include/asynchronousexplicitimagecache.h + include/asynchronousimagecache.h + include/asynchronousimagecacheinterface.h + include/bindingproperty.h + include/imagecacheauxiliarydata.h + include/import.h + include/itemlibraryinfo.h + include/metainfo.h + include/metainforeader.h + include/model.h + include/modelnode.h + include/nodeabstractproperty.h + include/nodelistproperty.h + include/nodemetainfo.h + include/nodeproperty.h + include/projectstorageids.h + include/propertymetainfo.h + include/propertycontainer.h + include/propertyparser.h + include/qmldesignercorelib_global.h + include/signalhandlerproperty.h + include/synchronousimagecache.h + include/variantproperty.h + metainfo/itemlibraryinfo.cpp + metainfo/metainfo.cpp + metainfo/metainforeader.cpp + metainfo/nodemetainfo.cpp + model/abstractproperty.cpp + model/abstractview.cpp + model/annotation.cpp + model/bindingproperty.cpp + model/import.cpp + model/internalbindingproperty.cpp + model/internalbindingproperty.h + model/internalnode.cpp + model/internalnode_p.h + model/internalnodeabstractproperty.cpp + model/internalnodeabstractproperty.h + model/internalnodelistproperty.cpp + model/internalnodelistproperty.h + model/internalnodeproperty.cpp + model/internalnodeproperty.h + model/internalproperty.cpp + model/internalproperty.h + model/internalsignalhandlerproperty.cpp + model/internalsignalhandlerproperty.h + model/internalvariantproperty.cpp + model/internalvariantproperty.h + model/model.cpp + model/model_p.h + model/modelnode.cpp + model/modelresourcemanagementinterface.h + model/modelresourcemanagement.cpp model/modelresourcemanagement.h + model/propertycontainer.cpp + model/propertyparser.cpp + model/nodeabstractproperty.cpp + model/nodelistproperty.cpp + model/nodeproperty.cpp + model/signalhandlerproperty.cpp + model/variantproperty.cpp + pluginmanager/widgetpluginmanager.h pluginmanager/widgetpluginmanager.cpp + pluginmanager/widgetpluginpath.h pluginmanager/widgetpluginpath.cpp + projectstorage/directorypathcompressor.h + projectstorage/filesysteminterface.h + projectstorage/filesystem.cpp projectstorage/filesystem.h + projectstorage/filestatus.h + projectstorage/filestatuscache.cpp projectstorage/filestatuscache.h + projectstorage/modulescanner.cpp projectstorage/modulescanner.h + projectstorage/nonlockingmutex.h + projectstorage/projectstorageexceptions.cpp projectstorage/projectstorageexceptions.h + projectstorage/projectstorageinterface.h + projectstorage/projectstorage.cpp projectstorage/projectstorage.h + projectstorage/projectstoragepathwatcher.h + projectstorage/projectstoragepathwatcherinterface.h + projectstorage/projectstoragepathwatchernotifierinterface.h + projectstorage/projectstoragepathwatcher.h + projectstorage/projectstoragepathwatchertypes.h + projectstorage/projectstoragetypes.h + projectstorage/projectstorageupdater.cpp projectstorage/projectstorageupdater.h + projectstorage/sourcepath.h + projectstorage/sourcepathcache.h + projectstorage/sourcepathcache.h + projectstorage/sourcepathcachetypes.h + projectstorage/sourcepathview.h + projectstorage/storagecache.h + projectstorage/storagecacheentry.h + projectstorage/storagecachefwd.h + projectstorage/qmldocumentparserinterface.h + projectstorage/qmltypesparserinterface.h + rewritertransaction.cpp + rewritertransaction.h +) + +extend_qtc_library(TestDesignerCore + SOURCES_PREFIX ${QmlDesignerDir}/designercore/include + SOURCES_PROPERTIES AUTOMOC ON + SOURCES + model.h + abstractview.h +) + +extend_qtc_library(TestDesignerCore + SOURCES_PROPERTIES AUTOMOC ON + SOURCES_PREFIX ../stubs/qmldesigner/designercore/include + SOURCES + nodeinstanceview.h + rewriterview.h +) diff --git a/tests/unit/tests/unittests/CMakeLists.txt b/tests/unit/tests/unittests/CMakeLists.txt new file mode 100644 index 00000000000..7f745301670 --- /dev/null +++ b/tests/unit/tests/unittests/CMakeLists.txt @@ -0,0 +1,69 @@ +file(RELATIVE_PATH RELATIVE_TEST_PATH "${PROJECT_BINARY_DIR}" "${CMAKE_CURRENT_BINARY_DIR}") +file(RELATIVE_PATH TEST_RELATIVE_LIBEXEC_PATH "/${RELATIVE_TEST_PATH}" "/${IDE_LIBEXEC_PATH}") + +add_qtc_test(unittest GTEST + PROPERTIES COMPILE_WARNING_AS_ERROR OFF + SKIP_AUTOMOC ON + DEPENDS + Qt::Core Qt::Network Qt::Widgets + Qt::Xml Qt::Concurrent Qt::QmlPrivate Qt::Gui + Qt::Core5Compat Utils QmlJS Sqlite + Googletest TestDesignerCore TestUtils TestMatchers TestPrinters TestMocks + DEFINES + GTEST_INTERNAL_HAS_STRING_VIEW + QT_NO_CAST_TO_ASCII + QT_RESTRICTED_CAST_FROM_ASCII + UNIT_TESTS + DONT_CHECK_MESSAGE_COUNTER + QTC_RESOURCE_DIR="${QtCreatorResourcesDir}" + UNITTEST_DIR="${CMAKE_CURRENT_SOURCE_DIR}" + TEST_RELATIVE_LIBEXEC_PATH="${TEST_RELATIVE_LIBEXEC_PATH}" + QT6_INSTALL_PREFIX="${QT6_INSTALL_PREFIX}" + QDS_MODEL_USE_PROJECTSTORAGEINTERFACE + QDS_USE_PROJECTSTORAGE + SOURCES + unittests-main.cpp +) + +function(extend_qtc_test_with_target_sources target) + cmake_parse_arguments(_arg "" "" "DEFINES;INCLUDES" ${ARGN}) + + get_target_property(${target}Sources ${target} SOURCES) + # work around issue with CMake < 3.14 where target sources can contain + # $ + list(FILTER ${target}Sources EXCLUDE REGEX "^\\$ + ${_arg_DEFINES} + INCLUDES + $ + ${_arg_INCLUDES} + ) +endfunction() + +finalize_qtc_gtest(unittest + EXCLUDE_SOURCES_REGEX ".c$" + EXCLUDE_ALL_FROM_PRECHECK +) + +function(unittest_copy_data_folder) + execute_process( + COMMAND ${CMAKE_COMMAND} -E copy_directory + "${CMAKE_CURRENT_SOURCE_DIR}/data" + "${CMAKE_CURRENT_BINARY_DIR}/data" + ) +endfunction(unittest_copy_data_folder) + +add_subdirectory(listmodeleditor) +add_subdirectory(imagecache) +add_subdirectory(metainfo) +add_subdirectory(model) +add_subdirectory(sqlite) +add_subdirectory(projectstorage) +add_subdirectory(qmlprojectmanager) +add_subdirectory(utils) diff --git a/tests/unit/tests/unittests/imagecache/CMakeLists.txt b/tests/unit/tests/unittests/imagecache/CMakeLists.txt new file mode 100644 index 00000000000..7f004221d3a --- /dev/null +++ b/tests/unit/tests/unittests/imagecache/CMakeLists.txt @@ -0,0 +1,11 @@ +# qmldesigner/designercore/imagecache +extend_qtc_test(unittest + SOURCES + asynchronousexplicitimagecache-test.cpp + asynchronousimagecache-test.cpp + asynchronousimagefactory-test.cpp + imagecachedispatchcollector-test.cpp + imagecachegenerator-test.cpp + imagecachestorage-test.cpp + synchronousimagecache-test.cpp +) diff --git a/tests/unit/unittest/asynchronousexplicitimagecache-test.cpp b/tests/unit/tests/unittests/imagecache/asynchronousexplicitimagecache-test.cpp similarity index 85% rename from tests/unit/unittest/asynchronousexplicitimagecache-test.cpp rename to tests/unit/tests/unittests/imagecache/asynchronousexplicitimagecache-test.cpp index 3bad57fc832..15d8f1dd7e5 100644 --- a/tests/unit/unittest/asynchronousexplicitimagecache-test.cpp +++ b/tests/unit/tests/unittests/imagecache/asynchronousexplicitimagecache-test.cpp @@ -1,10 +1,10 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" -#include "mockimagecachestorage.h" -#include "notification.h" +#include "../mocks/mockimagecachestorage.h" +#include "../utils/notification.h" #include @@ -26,7 +26,7 @@ protected: QImage smallImage1{1, 1, QImage::Format_ARGB32}; }; -TEST_F(AsynchronousExplicitImageCache, RequestImageFetchesImageFromStorage) +TEST_F(AsynchronousExplicitImageCache, request_image_fetches_image_from_storage) { EXPECT_CALL(mockStorage, fetchImage(Eq("/path/to/Component.qml"), Eq(Sqlite::TimeStamp{}))) .WillRepeatedly([&](Utils::SmallStringView, auto) { @@ -40,7 +40,7 @@ TEST_F(AsynchronousExplicitImageCache, RequestImageFetchesImageFromStorage) notification.wait(); } -TEST_F(AsynchronousExplicitImageCache, RequestImageFetchesImageFromStorageWithTimeStamp) +TEST_F(AsynchronousExplicitImageCache, request_image_fetches_image_from_storage_with_time_stamp) { EXPECT_CALL(mockStorage, fetchImage(Eq("/path/to/Component.qml"), Eq(Sqlite::TimeStamp{}))) .WillRepeatedly([&](Utils::SmallStringView, auto) { @@ -54,7 +54,7 @@ TEST_F(AsynchronousExplicitImageCache, RequestImageFetchesImageFromStorageWithTi notification.wait(); } -TEST_F(AsynchronousExplicitImageCache, RequestImageCallsCaptureCallbackWithImageFromStorage) +TEST_F(AsynchronousExplicitImageCache, request_image_calls_capture_callback_with_image_from_storage) { ON_CALL(mockStorage, fetchImage(Eq("/path/to/Component.qml"), _)) .WillByDefault(Return(QmlDesigner::ImageCacheStorageInterface::ImageEntry{image1})); @@ -69,7 +69,7 @@ TEST_F(AsynchronousExplicitImageCache, RequestImageCallsCaptureCallbackWithImage notification.wait(); } -TEST_F(AsynchronousExplicitImageCache, RequestImageCallsAbortCallbackWithoutEntry) +TEST_F(AsynchronousExplicitImageCache, request_image_calls_abort_callback_without_entry) { ON_CALL(mockStorage, fetchImage(Eq("/path/to/Component.qml"), _)) .WillByDefault(Return(QmlDesigner::ImageCacheStorageInterface::ImageEntry{})); @@ -83,7 +83,7 @@ TEST_F(AsynchronousExplicitImageCache, RequestImageCallsAbortCallbackWithoutEntr notification.wait(); } -TEST_F(AsynchronousExplicitImageCache, RequestImageCallsAbortCallbackWithoutImage) +TEST_F(AsynchronousExplicitImageCache, request_image_calls_abort_callback_without_image) { ON_CALL(mockStorage, fetchImage(Eq("/path/to/Component.qml"), _)) .WillByDefault(Return(QmlDesigner::ImageCacheStorageInterface::ImageEntry{QImage{}})); @@ -97,7 +97,7 @@ TEST_F(AsynchronousExplicitImageCache, RequestImageCallsAbortCallbackWithoutImag notification.wait(); } -TEST_F(AsynchronousExplicitImageCache, RequestMidSizeImageFetchesMidSizeImageFromStorage) +TEST_F(AsynchronousExplicitImageCache, request_mid_size_image_fetches_mid_size_image_from_storage) { EXPECT_CALL(mockStorage, fetchMidSizeImage(Eq("/path/to/Component.qml"), Eq(Sqlite::TimeStamp{}))) .WillRepeatedly([&](Utils::SmallStringView, auto) { @@ -111,7 +111,7 @@ TEST_F(AsynchronousExplicitImageCache, RequestMidSizeImageFetchesMidSizeImageFro notification.wait(); } -TEST_F(AsynchronousExplicitImageCache, RequestMidSizeImageCallsCaptureCallbackWithImageFromStorage) +TEST_F(AsynchronousExplicitImageCache, request_mid_size_image_calls_capture_callback_with_image_from_storage) { ON_CALL(mockStorage, fetchMidSizeImage(Eq("/path/to/Component.qml"), _)) .WillByDefault(Return(QmlDesigner::ImageCacheStorageInterface::ImageEntry{midSizeImage1})); @@ -126,7 +126,7 @@ TEST_F(AsynchronousExplicitImageCache, RequestMidSizeImageCallsCaptureCallbackWi notification.wait(); } -TEST_F(AsynchronousExplicitImageCache, RequestMidSizeImageCallsAbortCallbackWithoutEntry) +TEST_F(AsynchronousExplicitImageCache, request_mid_size_image_calls_abort_callback_without_entry) { ON_CALL(mockStorage, fetchMidSizeImage(Eq("/path/to/Component.qml"), _)) .WillByDefault(Return(QmlDesigner::ImageCacheStorageInterface::ImageEntry{})); @@ -140,7 +140,7 @@ TEST_F(AsynchronousExplicitImageCache, RequestMidSizeImageCallsAbortCallbackWith notification.wait(); } -TEST_F(AsynchronousExplicitImageCache, RequestMidSizeImageCallsAbortCallbackWithoutMidSizeImage) +TEST_F(AsynchronousExplicitImageCache, request_mid_size_image_calls_abort_callback_without_mid_size_image) { ON_CALL(mockStorage, fetchMidSizeImage(Eq("/path/to/Component.qml"), _)) .WillByDefault(Return(QmlDesigner::ImageCacheStorageInterface::ImageEntry{QImage{}})); @@ -154,7 +154,7 @@ TEST_F(AsynchronousExplicitImageCache, RequestMidSizeImageCallsAbortCallbackWith notification.wait(); } -TEST_F(AsynchronousExplicitImageCache, RequestSmallImageFetchesSmallImageFromStorage) +TEST_F(AsynchronousExplicitImageCache, request_small_image_fetches_small_image_from_storage) { EXPECT_CALL(mockStorage, fetchSmallImage(Eq("/path/to/Component.qml"), Eq(Sqlite::TimeStamp{}))) .WillRepeatedly([&](Utils::SmallStringView, auto) { @@ -168,7 +168,7 @@ TEST_F(AsynchronousExplicitImageCache, RequestSmallImageFetchesSmallImageFromSto notification.wait(); } -TEST_F(AsynchronousExplicitImageCache, RequestSmallImageCallsCaptureCallbackWithImageFromStorage) +TEST_F(AsynchronousExplicitImageCache, request_small_image_calls_capture_callback_with_image_from_storage) { ON_CALL(mockStorage, fetchSmallImage(Eq("/path/to/Component.qml"), _)) .WillByDefault(Return(QmlDesigner::ImageCacheStorageInterface::ImageEntry{smallImage1})); @@ -183,7 +183,7 @@ TEST_F(AsynchronousExplicitImageCache, RequestSmallImageCallsCaptureCallbackWith notification.wait(); } -TEST_F(AsynchronousExplicitImageCache, RequestSmallImageCallsAbortCallbackWithoutEntry) +TEST_F(AsynchronousExplicitImageCache, request_small_image_calls_abort_callback_without_entry) { ON_CALL(mockStorage, fetchSmallImage(Eq("/path/to/Component.qml"), _)) .WillByDefault(Return(QmlDesigner::ImageCacheStorageInterface::ImageEntry{})); @@ -197,7 +197,7 @@ TEST_F(AsynchronousExplicitImageCache, RequestSmallImageCallsAbortCallbackWithou notification.wait(); } -TEST_F(AsynchronousExplicitImageCache, RequestSmallImageCallsAbortCallbackWithoutSmallImage) +TEST_F(AsynchronousExplicitImageCache, request_small_image_calls_abort_callback_without_small_image) { ON_CALL(mockStorage, fetchSmallImage(Eq("/path/to/Component.qml"), _)) .WillByDefault(Return(QmlDesigner::ImageCacheStorageInterface::ImageEntry{QImage{}})); @@ -211,7 +211,7 @@ TEST_F(AsynchronousExplicitImageCache, RequestSmallImageCallsAbortCallbackWithou notification.wait(); } -TEST_F(AsynchronousExplicitImageCache, CleanRemovesEntries) +TEST_F(AsynchronousExplicitImageCache, clean_removes_entries) { ON_CALL(mockStorage, fetchSmallImage(_, _)).WillByDefault([&](Utils::SmallStringView, auto) { return QmlDesigner::ImageCacheStorageInterface::ImageEntry{smallImage1}; @@ -230,7 +230,7 @@ TEST_F(AsynchronousExplicitImageCache, CleanRemovesEntries) waitInThread.notify(); } -TEST_F(AsynchronousExplicitImageCache, CleanCallsAbort) +TEST_F(AsynchronousExplicitImageCache, clean_calls_abort) { ON_CALL(mockStorage, fetchSmallImage(Eq("/path/to/Component1.qml"), _)) .WillByDefault([&](Utils::SmallStringView, auto) { @@ -250,7 +250,7 @@ TEST_F(AsynchronousExplicitImageCache, CleanCallsAbort) waitInThread.notify(); } -TEST_F(AsynchronousExplicitImageCache, AfterCleanNewJobsWorks) +TEST_F(AsynchronousExplicitImageCache, after_clean_new_jobs_works) { cache.clean(); @@ -266,7 +266,7 @@ TEST_F(AsynchronousExplicitImageCache, AfterCleanNewJobsWorks) notification.wait(); } -TEST_F(AsynchronousExplicitImageCache, RequestImageWithExtraIdFetchesImageFromStorage) +TEST_F(AsynchronousExplicitImageCache, request_image_with_extra_id_fetches_image_from_storage) { EXPECT_CALL(mockStorage, fetchImage(Eq("/path/to/Component.qml+extraId1"), _)) .WillRepeatedly([&](Utils::SmallStringView, auto) { @@ -281,7 +281,7 @@ TEST_F(AsynchronousExplicitImageCache, RequestImageWithExtraIdFetchesImageFromSt notification.wait(); } -TEST_F(AsynchronousExplicitImageCache, RequestMidSizeImageWithExtraIdFetchesImageFromStorage) +TEST_F(AsynchronousExplicitImageCache, request_mid_size_image_with_extra_id_fetches_image_from_storage) { EXPECT_CALL(mockStorage, fetchMidSizeImage(Eq("/path/to/Component.qml+extraId1"), _)) .WillRepeatedly([&](Utils::SmallStringView, auto) { @@ -296,7 +296,7 @@ TEST_F(AsynchronousExplicitImageCache, RequestMidSizeImageWithExtraIdFetchesImag notification.wait(); } -TEST_F(AsynchronousExplicitImageCache, RequestSmallImageWithExtraIdFetchesImageFromStorage) +TEST_F(AsynchronousExplicitImageCache, request_small_image_with_extra_id_fetches_image_from_storage) { EXPECT_CALL(mockStorage, fetchSmallImage(Eq("/path/to/Component.qml+extraId1"), _)) .WillRepeatedly([&](Utils::SmallStringView, auto) { diff --git a/tests/unit/unittest/asynchronousimagecache-test.cpp b/tests/unit/tests/unittests/imagecache/asynchronousimagecache-test.cpp similarity index 87% rename from tests/unit/unittest/asynchronousimagecache-test.cpp rename to tests/unit/tests/unittests/imagecache/asynchronousimagecache-test.cpp index 16e1a59d194..e7c51c40fc4 100644 --- a/tests/unit/unittest/asynchronousimagecache-test.cpp +++ b/tests/unit/tests/unittests/imagecache/asynchronousimagecache-test.cpp @@ -1,12 +1,12 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" +#include "../utils/notification.h" -#include "mockimagecachegenerator.h" -#include "mockimagecachestorage.h" -#include "mocktimestampprovider.h" -#include "notification.h" +#include "../mocks/mockimagecachegenerator.h" +#include "../mocks/mockimagecachestorage.h" +#include "../mocks/mocktimestampprovider.h" #include @@ -28,7 +28,7 @@ protected: QImage smallImage1{1, 1, QImage::Format_ARGB32}; }; -TEST_F(AsynchronousImageCache, RequestImageFetchesImageFromStorage) +TEST_F(AsynchronousImageCache, request_image_fetches_image_from_storage) { EXPECT_CALL(mockStorage, fetchImage(Eq("/path/to/Component.qml"), _)) .WillRepeatedly([&](Utils::SmallStringView, auto) { @@ -42,7 +42,7 @@ TEST_F(AsynchronousImageCache, RequestImageFetchesImageFromStorage) notification.wait(); } -TEST_F(AsynchronousImageCache, RequestImageFetchesImageFromStorageWithTimeStamp) +TEST_F(AsynchronousImageCache, request_image_fetches_image_from_storage_with_time_stamp) { EXPECT_CALL(mockTimeStampProvider, timeStamp(Eq("/path/to/Component.qml"))) .WillRepeatedly(Return(Sqlite::TimeStamp{123})); @@ -58,7 +58,7 @@ TEST_F(AsynchronousImageCache, RequestImageFetchesImageFromStorageWithTimeStamp) notification.wait(); } -TEST_F(AsynchronousImageCache, RequestImageCallsCaptureCallbackWithImageFromStorage) +TEST_F(AsynchronousImageCache, request_image_calls_capture_callback_with_image_from_storage) { ON_CALL(mockStorage, fetchImage(Eq("/path/to/Component.qml"), _)) .WillByDefault(Return(QmlDesigner::ImageCacheStorageInterface::ImageEntry{image1})); @@ -73,7 +73,7 @@ TEST_F(AsynchronousImageCache, RequestImageCallsCaptureCallbackWithImageFromStor notification.wait(); } -TEST_F(AsynchronousImageCache, RequestImageCallsAbortCallbackWithoutImage) +TEST_F(AsynchronousImageCache, request_image_calls_abort_callback_without_image) { ON_CALL(mockStorage, fetchImage(Eq("/path/to/Component.qml"), _)) .WillByDefault(Return(QmlDesigner::ImageCacheStorageInterface::ImageEntry{QImage{}})); @@ -87,7 +87,7 @@ TEST_F(AsynchronousImageCache, RequestImageCallsAbortCallbackWithoutImage) notification.wait(); } -TEST_F(AsynchronousImageCache, RequestImageRequestImageFromGenerator) +TEST_F(AsynchronousImageCache, request_image_request_image_from_generator) { ON_CALL(mockTimeStampProvider, timeStamp(Eq("/path/to/Component.qml"))) .WillByDefault(Return(Sqlite::TimeStamp{123})); @@ -102,7 +102,7 @@ TEST_F(AsynchronousImageCache, RequestImageRequestImageFromGenerator) notification.wait(); } -TEST_F(AsynchronousImageCache, RequestImageCallsCaptureCallbackWithImageFromGenerator) +TEST_F(AsynchronousImageCache, request_image_calls_capture_callback_with_image_from_generator) { ON_CALL(mockGenerator, generateImage(Eq("/path/to/Component.qml"), _, _, _, _, _)) .WillByDefault([&](auto, auto, auto, auto &&callback, auto, auto) { @@ -118,7 +118,7 @@ TEST_F(AsynchronousImageCache, RequestImageCallsCaptureCallbackWithImageFromGene notification.wait(); } -TEST_F(AsynchronousImageCache, RequestImageCallsAbortCallbackFromGenerator) +TEST_F(AsynchronousImageCache, request_image_calls_abort_callback_from_generator) { ON_CALL(mockGenerator, generateImage(Eq("/path/to/Component.qml"), _, _, _, _, _)) .WillByDefault([&](auto, auto, auto, auto &&, auto &&abortCallback, auto) { @@ -134,7 +134,7 @@ TEST_F(AsynchronousImageCache, RequestImageCallsAbortCallbackFromGenerator) notification.wait(); } -TEST_F(AsynchronousImageCache, RequestMidSizeImageFetchesMidSizeImageFromStorage) +TEST_F(AsynchronousImageCache, request_mid_size_image_fetches_mid_size_image_from_storage) { EXPECT_CALL(mockStorage, fetchMidSizeImage(Eq("/path/to/Component.qml"), _)) .WillRepeatedly([&](Utils::SmallStringView, auto) { @@ -148,7 +148,7 @@ TEST_F(AsynchronousImageCache, RequestMidSizeImageFetchesMidSizeImageFromStorage notification.wait(); } -TEST_F(AsynchronousImageCache, RequestMidSizeImageFetchesMidSizeImageFromStorageWithTimeStamp) +TEST_F(AsynchronousImageCache, request_mid_size_image_fetches_mid_size_image_from_storage_with_time_stamp) { EXPECT_CALL(mockTimeStampProvider, timeStamp(Eq("/path/to/Component.qml"))) .WillRepeatedly(Return(Sqlite::TimeStamp{123})); @@ -165,7 +165,7 @@ TEST_F(AsynchronousImageCache, RequestMidSizeImageFetchesMidSizeImageFromStorage notification.wait(); } -TEST_F(AsynchronousImageCache, RequestMidSizeImageCallsCaptureCallbackWithImageFromStorage) +TEST_F(AsynchronousImageCache, request_mid_size_image_calls_capture_callback_with_image_from_storage) { ON_CALL(mockStorage, fetchMidSizeImage(Eq("/path/to/Component.qml"), _)) .WillByDefault(Return(QmlDesigner::ImageCacheStorageInterface::ImageEntry{smallImage1})); @@ -180,7 +180,7 @@ TEST_F(AsynchronousImageCache, RequestMidSizeImageCallsCaptureCallbackWithImageF notification.wait(); } -TEST_F(AsynchronousImageCache, RequestMidSizeImageCallsAbortCallbackWithoutMidSizeImage) +TEST_F(AsynchronousImageCache, request_mid_size_image_calls_abort_callback_without_mid_size_image) { ON_CALL(mockStorage, fetchMidSizeImage(Eq("/path/to/Component.qml"), _)) .WillByDefault(Return(QmlDesigner::ImageCacheStorageInterface::ImageEntry{QImage{}})); @@ -194,7 +194,7 @@ TEST_F(AsynchronousImageCache, RequestMidSizeImageCallsAbortCallbackWithoutMidSi notification.wait(); } -TEST_F(AsynchronousImageCache, RequestMidSizeImageRequestImageFromGenerator) +TEST_F(AsynchronousImageCache, request_mid_size_image_request_image_from_generator) { ON_CALL(mockTimeStampProvider, timeStamp(Eq("/path/to/Component.qml"))) .WillByDefault(Return(Sqlite::TimeStamp{123})); @@ -209,7 +209,7 @@ TEST_F(AsynchronousImageCache, RequestMidSizeImageRequestImageFromGenerator) notification.wait(); } -TEST_F(AsynchronousImageCache, RequestMidSizeImageCallsCaptureCallbackWithImageFromGenerator) +TEST_F(AsynchronousImageCache, request_mid_size_image_calls_capture_callback_with_image_from_generator) { ON_CALL(mockGenerator, generateImage(Eq("/path/to/Component.qml"), _, _, _, _, _)) .WillByDefault([&](auto, auto, auto, auto &&callback, auto, auto) { @@ -225,7 +225,7 @@ TEST_F(AsynchronousImageCache, RequestMidSizeImageCallsCaptureCallbackWithImageF notification.wait(); } -TEST_F(AsynchronousImageCache, RequestMidSizeImageCallsAbortCallbackFromGenerator) +TEST_F(AsynchronousImageCache, request_mid_size_image_calls_abort_callback_from_generator) { ON_CALL(mockGenerator, generateImage(Eq("/path/to/Component.qml"), _, _, _, _, _)) .WillByDefault([&](auto, auto, auto, auto &&, auto &&abortCallback, auto) { @@ -241,7 +241,7 @@ TEST_F(AsynchronousImageCache, RequestMidSizeImageCallsAbortCallbackFromGenerato notification.wait(); } -TEST_F(AsynchronousImageCache, RequestSmallImageFetchesSmallImageFromStorage) +TEST_F(AsynchronousImageCache, request_small_image_fetches_small_image_from_storage) { EXPECT_CALL(mockStorage, fetchSmallImage(Eq("/path/to/Component.qml"), _)) .WillRepeatedly([&](Utils::SmallStringView, auto) { @@ -255,7 +255,7 @@ TEST_F(AsynchronousImageCache, RequestSmallImageFetchesSmallImageFromStorage) notification.wait(); } -TEST_F(AsynchronousImageCache, RequestSmallImageFetchesSmallImageFromStorageWithTimeStamp) +TEST_F(AsynchronousImageCache, request_small_image_fetches_small_image_from_storage_with_time_stamp) { EXPECT_CALL(mockTimeStampProvider, timeStamp(Eq("/path/to/Component.qml"))) .WillRepeatedly(Return(Sqlite::TimeStamp{123})); @@ -271,7 +271,7 @@ TEST_F(AsynchronousImageCache, RequestSmallImageFetchesSmallImageFromStorageWith notification.wait(); } -TEST_F(AsynchronousImageCache, RequestSmallImageCallsCaptureCallbackWithImageFromStorage) +TEST_F(AsynchronousImageCache, request_small_image_calls_capture_callback_with_image_from_storage) { ON_CALL(mockStorage, fetchSmallImage(Eq("/path/to/Component.qml"), _)) .WillByDefault(Return(QmlDesigner::ImageCacheStorageInterface::ImageEntry{smallImage1})); @@ -286,7 +286,7 @@ TEST_F(AsynchronousImageCache, RequestSmallImageCallsCaptureCallbackWithImageFro notification.wait(); } -TEST_F(AsynchronousImageCache, RequestSmallImageCallsAbortCallbackWithoutSmallImage) +TEST_F(AsynchronousImageCache, request_small_image_calls_abort_callback_without_small_image) { ON_CALL(mockStorage, fetchSmallImage(Eq("/path/to/Component.qml"), _)) .WillByDefault(Return(QmlDesigner::ImageCacheStorageInterface::ImageEntry{QImage{}})); @@ -300,7 +300,7 @@ TEST_F(AsynchronousImageCache, RequestSmallImageCallsAbortCallbackWithoutSmallIm notification.wait(); } -TEST_F(AsynchronousImageCache, RequestSmallImageRequestImageFromGenerator) +TEST_F(AsynchronousImageCache, request_small_image_request_image_from_generator) { ON_CALL(mockTimeStampProvider, timeStamp(Eq("/path/to/Component.qml"))) .WillByDefault(Return(Sqlite::TimeStamp{123})); @@ -315,7 +315,7 @@ TEST_F(AsynchronousImageCache, RequestSmallImageRequestImageFromGenerator) notification.wait(); } -TEST_F(AsynchronousImageCache, RequestSmallImageCallsCaptureCallbackWithImageFromGenerator) +TEST_F(AsynchronousImageCache, request_small_image_calls_capture_callback_with_image_from_generator) { ON_CALL(mockGenerator, generateImage(Eq("/path/to/Component.qml"), _, _, _, _, _)) .WillByDefault([&](auto, auto, auto, auto &&callback, auto, auto) { @@ -331,7 +331,7 @@ TEST_F(AsynchronousImageCache, RequestSmallImageCallsCaptureCallbackWithImageFro notification.wait(); } -TEST_F(AsynchronousImageCache, RequestSmallImageCallsAbortCallbackFromGenerator) +TEST_F(AsynchronousImageCache, request_small_image_calls_abort_callback_from_generator) { ON_CALL(mockGenerator, generateImage(Eq("/path/to/Component.qml"), _, _, _, _, _)) .WillByDefault([&](auto, auto, auto, auto &&, auto &&abortCallback, auto) { @@ -347,7 +347,7 @@ TEST_F(AsynchronousImageCache, RequestSmallImageCallsAbortCallbackFromGenerator) notification.wait(); } -TEST_F(AsynchronousImageCache, CleanRemovesEntries) +TEST_F(AsynchronousImageCache, clean_removes_entries) { EXPECT_CALL(mockGenerator, generateImage(_, _, _, _, _, _)) .WillRepeatedly([&](auto, auto, auto, auto &&captureCallback, auto &&, auto) { @@ -367,7 +367,7 @@ TEST_F(AsynchronousImageCache, CleanRemovesEntries) waitInThread.notify(); } -TEST_F(AsynchronousImageCache, CleanCallsAbort) +TEST_F(AsynchronousImageCache, clean_calls_abort) { ON_CALL(mockGenerator, generateImage(_, _, _, _, _, _)) .WillByDefault([&](auto, auto, auto, auto, auto &&, auto) { waitInThread.wait(); }); @@ -388,14 +388,14 @@ TEST_F(AsynchronousImageCache, CleanCallsAbort) waitInThread.notify(); } -TEST_F(AsynchronousImageCache, CleanCallsGeneratorClean) +TEST_F(AsynchronousImageCache, clean_calls_generator_clean) { EXPECT_CALL(mockGenerator, clean()).Times(AtLeast(1)); cache.clean(); } -TEST_F(AsynchronousImageCache, AfterCleanNewJobsWorks) +TEST_F(AsynchronousImageCache, after_clean_new_jobs_works) { cache.clean(); @@ -408,7 +408,7 @@ TEST_F(AsynchronousImageCache, AfterCleanNewJobsWorks) notification.wait(); } -TEST_F(AsynchronousImageCache, RequestImageWithExtraIdFetchesImageFromStorage) +TEST_F(AsynchronousImageCache, request_image_with_extra_id_fetches_image_from_storage) { EXPECT_CALL(mockStorage, fetchImage(Eq("/path/to/Component.qml+extraId1"), _)) .WillRepeatedly([&](Utils::SmallStringView, auto) { @@ -423,7 +423,7 @@ TEST_F(AsynchronousImageCache, RequestImageWithExtraIdFetchesImageFromStorage) notification.wait(); } -TEST_F(AsynchronousImageCache, RequestMidSizeImageWithExtraIdFetchesImageFromStorage) +TEST_F(AsynchronousImageCache, request_mid_size_image_with_extra_id_fetches_image_from_storage) { EXPECT_CALL(mockStorage, fetchMidSizeImage(Eq("/path/to/Component.qml+extraId1"), _)) .WillRepeatedly([&](Utils::SmallStringView, auto) { @@ -438,7 +438,7 @@ TEST_F(AsynchronousImageCache, RequestMidSizeImageWithExtraIdFetchesImageFromSto notification.wait(); } -TEST_F(AsynchronousImageCache, RequestSmallImageWithExtraIdFetchesImageFromStorage) +TEST_F(AsynchronousImageCache, request_small_image_with_extra_id_fetches_image_from_storage) { EXPECT_CALL(mockStorage, fetchSmallImage(Eq("/path/to/Component.qml+extraId1"), _)) .WillRepeatedly([&](Utils::SmallStringView, auto) { @@ -453,7 +453,7 @@ TEST_F(AsynchronousImageCache, RequestSmallImageWithExtraIdFetchesImageFromStora notification.wait(); } -TEST_F(AsynchronousImageCache, RequestImageWithExtraIdRequestImageFromGenerator) +TEST_F(AsynchronousImageCache, request_image_with_extra_id_request_image_from_generator) { ON_CALL(mockTimeStampProvider, timeStamp(Eq("/path/to/Component.qml"))) .WillByDefault(Return(Sqlite::TimeStamp{123})); @@ -470,7 +470,7 @@ TEST_F(AsynchronousImageCache, RequestImageWithExtraIdRequestImageFromGenerator) notification.wait(); } -TEST_F(AsynchronousImageCache, RequestMidSizeImageWithExtraIdRequestImageFromGenerator) +TEST_F(AsynchronousImageCache, request_mid_size_image_with_extra_id_request_image_from_generator) { ON_CALL(mockTimeStampProvider, timeStamp(Eq("/path/to/Component.qml"))) .WillByDefault(Return(Sqlite::TimeStamp{123})); @@ -487,7 +487,7 @@ TEST_F(AsynchronousImageCache, RequestMidSizeImageWithExtraIdRequestImageFromGen notification.wait(); } -TEST_F(AsynchronousImageCache, RequestSmallImageWithExtraIdRequestImageFromGenerator) +TEST_F(AsynchronousImageCache, request_small_image_with_extra_id_request_image_from_generator) { ON_CALL(mockTimeStampProvider, timeStamp(Eq("/path/to/Component.qml"))) .WillByDefault(Return(Sqlite::TimeStamp{123})); @@ -504,7 +504,7 @@ TEST_F(AsynchronousImageCache, RequestSmallImageWithExtraIdRequestImageFromGener notification.wait(); } -TEST_F(AsynchronousImageCache, RequestImageWithAuxiliaryDataRequestImageFromGenerator) +TEST_F(AsynchronousImageCache, request_image_with_auxiliary_data_request_image_from_generator) { using QmlDesigner::ImageCache::FontCollectorSizesAuxiliaryData; std::vector sizes{{20, 11}}; @@ -532,7 +532,7 @@ TEST_F(AsynchronousImageCache, RequestImageWithAuxiliaryDataRequestImageFromGene notification.wait(); } -TEST_F(AsynchronousImageCache, RequestMidSizeImageWithAuxiliaryDataRequestImageFromGenerator) +TEST_F(AsynchronousImageCache, request_mid_size_image_with_auxiliary_data_request_image_from_generator) { using QmlDesigner::ImageCache::FontCollectorSizesAuxiliaryData; std::vector sizes{{20, 11}}; @@ -560,7 +560,7 @@ TEST_F(AsynchronousImageCache, RequestMidSizeImageWithAuxiliaryDataRequestImageF notification.wait(); } -TEST_F(AsynchronousImageCache, RequestSmallImageWithAuxiliaryDataRequestImageFromGenerator) +TEST_F(AsynchronousImageCache, request_small_image_with_auxiliary_data_request_image_from_generator) { using QmlDesigner::ImageCache::FontCollectorSizesAuxiliaryData; std::vector sizes{{20, 11}}; diff --git a/tests/unit/unittest/asynchronousimagefactory-test.cpp b/tests/unit/tests/unittests/imagecache/asynchronousimagefactory-test.cpp similarity index 86% rename from tests/unit/unittest/asynchronousimagefactory-test.cpp rename to tests/unit/tests/unittests/imagecache/asynchronousimagefactory-test.cpp index 49a44c9afed..e98f0d70e52 100644 --- a/tests/unit/unittest/asynchronousimagefactory-test.cpp +++ b/tests/unit/tests/unittests/imagecache/asynchronousimagefactory-test.cpp @@ -1,13 +1,13 @@ // Copyright (C) 2022 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" +#include "../utils/notification.h" -#include "imagecachecollectormock.h" -#include "mockimagecachegenerator.h" -#include "mockimagecachestorage.h" -#include "mocktimestampprovider.h" -#include "notification.h" +#include "../mocks/imagecachecollectormock.h" +#include "../mocks/mockimagecachegenerator.h" +#include "../mocks/mockimagecachestorage.h" +#include "../mocks/mocktimestampprovider.h" #include @@ -36,7 +36,7 @@ protected: QImage smallImage1{1, 1, QImage::Format_ARGB32}; }; -TEST_F(AsynchronousImageFactory, RequestImageRequestImageFromCollector) +TEST_F(AsynchronousImageFactory, request_image_request_image_from_collector) { EXPECT_CALL(collectorMock, start(Eq("/path/to/Component.qml"), @@ -50,7 +50,7 @@ TEST_F(AsynchronousImageFactory, RequestImageRequestImageFromCollector) notification.wait(); } -TEST_F(AsynchronousImageFactory, RequestImageWithExtraIdRequestImageFromCollector) +TEST_F(AsynchronousImageFactory, request_image_with_extra_id_request_image_from_collector) { EXPECT_CALL(collectorMock, start(Eq("/path/to/Component.qml"), @@ -64,7 +64,7 @@ TEST_F(AsynchronousImageFactory, RequestImageWithExtraIdRequestImageFromCollecto notification.wait(); } -TEST_F(AsynchronousImageFactory, RequestImageWithAuxiliaryDataRequestImageFromCollector) +TEST_F(AsynchronousImageFactory, request_image_with_auxiliary_data_request_image_from_collector) { std::vector sizes{{20, 11}}; @@ -88,7 +88,7 @@ TEST_F(AsynchronousImageFactory, RequestImageWithAuxiliaryDataRequestImageFromCo notification.wait(); } -TEST_F(AsynchronousImageFactory, DontRequestImageRequestImageFromCollectorIfFileWasUpdatedRecently) +TEST_F(AsynchronousImageFactory, dont_request_image_request_image_from_collector_if_file_was_updated_recently) { ON_CALL(storageMock, fetchModifiedImageTime(Eq("/path/to/Component.qml"))).WillByDefault([&](auto) { notification.notify(); @@ -105,7 +105,7 @@ TEST_F(AsynchronousImageFactory, DontRequestImageRequestImageFromCollectorIfFile notification.wait(); } -TEST_F(AsynchronousImageFactory, RequestImageRequestImageFromCollectorIfFileWasNotUpdatedRecently) +TEST_F(AsynchronousImageFactory, request_image_request_image_from_collector_if_file_was_not_updated_recently) { ON_CALL(storageMock, fetchModifiedImageTime(Eq("/path/to/Component.qml"))) .WillByDefault(Return(Sqlite::TimeStamp{123})); @@ -121,7 +121,7 @@ TEST_F(AsynchronousImageFactory, RequestImageRequestImageFromCollectorIfFileWasN notification.wait(); } -TEST_F(AsynchronousImageFactory, CleanRemovesEntries) +TEST_F(AsynchronousImageFactory, clean_removes_entries) { EXPECT_CALL(collectorMock, start(Eq("/path/to/Component1.qml"), _, _, _, _)) .WillRepeatedly([&](auto, auto, auto, auto, auto) { waitInThread.wait(); }); @@ -134,7 +134,7 @@ TEST_F(AsynchronousImageFactory, CleanRemovesEntries) waitInThread.notify(); } -TEST_F(AsynchronousImageFactory, AfterCleanNewJobsWorks) +TEST_F(AsynchronousImageFactory, after_clean_new_jobs_works) { factory.clean(); @@ -150,7 +150,7 @@ TEST_F(AsynchronousImageFactory, AfterCleanNewJobsWorks) notification.wait(); } -TEST_F(AsynchronousImageFactory, CaptureImageCallbackStoresImage) +TEST_F(AsynchronousImageFactory, capture_image_callback_stores_image) { ON_CALL(storageMock, fetchModifiedImageTime(Eq("/path/to/Component.qml"))) .WillByDefault(Return(Sqlite::TimeStamp{123})); diff --git a/tests/unit/unittest/imagecachedispatchcollector-test.cpp b/tests/unit/tests/unittests/imagecache/imagecachedispatchcollector-test.cpp similarity index 94% rename from tests/unit/unittest/imagecachedispatchcollector-test.cpp rename to tests/unit/tests/unittests/imagecache/imagecachedispatchcollector-test.cpp index 756304e7d1e..8d459916ffc 100644 --- a/tests/unit/unittest/imagecachedispatchcollector-test.cpp +++ b/tests/unit/tests/unittests/imagecache/imagecachedispatchcollector-test.cpp @@ -1,9 +1,9 @@ // Copyright (C) 2022 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" -#include "imagecachecollectormock.h" +#include "../mocks/imagecachecollectormock.h" #include #include @@ -61,7 +61,7 @@ protected: QIcon icon2{QPixmap::fromImage(image2)}; }; -TEST_F(ImageCacheDispatchCollector, CallQmlCollectorStart) +TEST_F(ImageCacheDispatchCollector, call_qml_collector_start) { QmlDesigner::ImageCacheDispatchCollector collector{std::make_tuple( std::make_pair( @@ -107,7 +107,7 @@ TEST_F(ImageCacheDispatchCollector, CallQmlCollectorStart) abortCallbackMock.AsStdFunction()); } -TEST_F(ImageCacheDispatchCollector, CallUiFileCollectorStart) +TEST_F(ImageCacheDispatchCollector, call_ui_file_collector_start) { QmlDesigner::ImageCacheDispatchCollector collector{std::make_tuple( std::make_pair([](Utils::SmallStringView, @@ -143,7 +143,7 @@ TEST_F(ImageCacheDispatchCollector, CallUiFileCollectorStart) abortCallbackMock.AsStdFunction()); } -TEST_F(ImageCacheDispatchCollector, DontCallCollectorStartForUnknownFile) +TEST_F(ImageCacheDispatchCollector, dont_call_collector_start_for_unknown_file) { QmlDesigner::ImageCacheDispatchCollector collector{std::make_tuple( std::make_pair([](Utils::SmallStringView, @@ -165,7 +165,7 @@ TEST_F(ImageCacheDispatchCollector, DontCallCollectorStartForUnknownFile) abortCallbackMock.AsStdFunction()); } -TEST_F(ImageCacheDispatchCollector, CallFirstCollectorCreateIcon) +TEST_F(ImageCacheDispatchCollector, call_first_collector_create_icon) { QmlDesigner::ImageCacheDispatchCollector collector{std::make_tuple( std::make_pair([](Utils::SmallStringView, @@ -184,7 +184,7 @@ TEST_F(ImageCacheDispatchCollector, CallFirstCollectorCreateIcon) ASSERT_THAT(icon, IsIcon(icon1)); } -TEST_F(ImageCacheDispatchCollector, FirstCollectorCreateIconCalls) +TEST_F(ImageCacheDispatchCollector, first_collector_create_icon_calls) { QmlDesigner::ImageCacheDispatchCollector collector{std::make_tuple( std::make_pair([](Utils::SmallStringView, @@ -211,7 +211,7 @@ TEST_F(ImageCacheDispatchCollector, FirstCollectorCreateIconCalls) FontCollectorSizesAuxiliaryData{sizes, "color", "text"}); } -TEST_F(ImageCacheDispatchCollector, CallSecondCollectorCreateIcon) +TEST_F(ImageCacheDispatchCollector, call_second_collector_create_icon) { QmlDesigner::ImageCacheDispatchCollector collector{std::make_tuple( std::make_pair([](Utils::SmallStringView, @@ -230,7 +230,7 @@ TEST_F(ImageCacheDispatchCollector, CallSecondCollectorCreateIcon) ASSERT_THAT(icon, IsIcon(icon2)); } -TEST_F(ImageCacheDispatchCollector, SecondCollectorCreateIconCalls) +TEST_F(ImageCacheDispatchCollector, second_collector_create_icon_calls) { QmlDesigner::ImageCacheDispatchCollector collector{std::make_tuple( std::make_pair([](Utils::SmallStringView, @@ -257,7 +257,7 @@ TEST_F(ImageCacheDispatchCollector, SecondCollectorCreateIconCalls) FontCollectorSizesAuxiliaryData{sizes, "color", "text"}); } -TEST_F(ImageCacheDispatchCollector, DontCallCollectorCreateIconForUnknownFile) +TEST_F(ImageCacheDispatchCollector, dont_call_collector_create_icon_for_unknown_file) { QmlDesigner::ImageCacheDispatchCollector collector{std::make_tuple( std::make_pair([](Utils::SmallStringView, @@ -276,7 +276,7 @@ TEST_F(ImageCacheDispatchCollector, DontCallCollectorCreateIconForUnknownFile) ASSERT_TRUE(icon.isNull()); } -TEST_F(ImageCacheDispatchCollector, CallFirstCollectorCreateImage) +TEST_F(ImageCacheDispatchCollector, call_first_collector_create_image) { QmlDesigner::ImageCacheDispatchCollector collector{std::make_tuple( std::make_pair([](Utils::SmallStringView, @@ -295,7 +295,7 @@ TEST_F(ImageCacheDispatchCollector, CallFirstCollectorCreateImage) ASSERT_THAT(image, IsImage(image1, midSizeImage1, smallImage1)); } -TEST_F(ImageCacheDispatchCollector, FirstCollectorCreateImageCalls) +TEST_F(ImageCacheDispatchCollector, first_collector_create_image_calls) { QmlDesigner::ImageCacheDispatchCollector collector{std::make_tuple( std::make_pair([](Utils::SmallStringView, @@ -322,7 +322,7 @@ TEST_F(ImageCacheDispatchCollector, FirstCollectorCreateImageCalls) FontCollectorSizesAuxiliaryData{sizes, "color", "text"}); } -TEST_F(ImageCacheDispatchCollector, CallSecondCollectorCreateImage) +TEST_F(ImageCacheDispatchCollector, call_second_collector_create_image) { QmlDesigner::ImageCacheDispatchCollector collector{std::make_tuple( std::make_pair([](Utils::SmallStringView, @@ -341,7 +341,7 @@ TEST_F(ImageCacheDispatchCollector, CallSecondCollectorCreateImage) ASSERT_THAT(image, IsImage(image2, midSizeImage2, smallImage2)); } -TEST_F(ImageCacheDispatchCollector, SecondCollectorCreateImageCalls) +TEST_F(ImageCacheDispatchCollector, second_collector_create_image_calls) { QmlDesigner::ImageCacheDispatchCollector collector{std::make_tuple( std::make_pair([](Utils::SmallStringView, @@ -368,7 +368,7 @@ TEST_F(ImageCacheDispatchCollector, SecondCollectorCreateImageCalls) FontCollectorSizesAuxiliaryData{sizes, "color", "text"}); } -TEST_F(ImageCacheDispatchCollector, DontCallCollectorCreateImageForUnknownFile) +TEST_F(ImageCacheDispatchCollector, dont_call_collector_create_image_for_unknown_file) { QmlDesigner::ImageCacheDispatchCollector collector{std::make_tuple( std::make_pair([](Utils::SmallStringView, diff --git a/tests/unit/unittest/imagecachegenerator-test.cpp b/tests/unit/tests/unittests/imagecache/imagecachegenerator-test.cpp similarity index 91% rename from tests/unit/unittest/imagecachegenerator-test.cpp rename to tests/unit/tests/unittests/imagecache/imagecachegenerator-test.cpp index 871a3768bb6..dfbcdee3dd0 100644 --- a/tests/unit/unittest/imagecachegenerator-test.cpp +++ b/tests/unit/tests/unittests/imagecache/imagecachegenerator-test.cpp @@ -1,11 +1,11 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" -#include "imagecachecollectormock.h" -#include "mockimagecachestorage.h" -#include "notification.h" +#include "../mocks/imagecachecollectormock.h" +#include "../mocks/mockimagecachestorage.h" +#include "../utils/notification.h" #include @@ -41,7 +41,7 @@ protected: QmlDesigner::ImageCacheGenerator generator{collectorMock, storageMock}; }; -TEST_F(ImageCacheGenerator, CallsCollectorWithCaptureCallback) +TEST_F(ImageCacheGenerator, calls_collector_with_capture_callback) { EXPECT_CALL(collectorMock, start(Eq("name"), _, _, _, _)) .WillRepeatedly([&](auto, auto, auto, auto captureCallback, auto) { @@ -55,7 +55,7 @@ TEST_F(ImageCacheGenerator, CallsCollectorWithCaptureCallback) notification.wait(); } -TEST_F(ImageCacheGenerator, CallsCollectorOnlyIfNotProcessing) +TEST_F(ImageCacheGenerator, calls_collector_only_if_not_processing) { EXPECT_CALL(collectorMock, start(AnyOf(Eq("name"), Eq("name2")), _, _, _, _)) .WillRepeatedly([&](auto, auto, auto, auto, auto) { notification.notify(); }); @@ -65,7 +65,7 @@ TEST_F(ImageCacheGenerator, CallsCollectorOnlyIfNotProcessing) notification.wait(2); } -TEST_F(ImageCacheGenerator, ProcessTaskAfterFirstFinished) +TEST_F(ImageCacheGenerator, process_task_after_first_finished) { ON_CALL(imageCallbackMock, Call(_, _, _)) .WillByDefault([&](const QImage &, const QImage &, const QImage &) { notification.notify(); }); @@ -84,7 +84,7 @@ TEST_F(ImageCacheGenerator, ProcessTaskAfterFirstFinished) notification.wait(2); } -TEST_F(ImageCacheGenerator, DontCrashAtDestructingGenerator) +TEST_F(ImageCacheGenerator, dont_crash_at_destructing_generator) { ON_CALL(collectorMock, start(Eq("name"), _, _, _, _)) .WillByDefault([&](auto, auto, auto, auto captureCallback, auto) { @@ -101,7 +101,7 @@ TEST_F(ImageCacheGenerator, DontCrashAtDestructingGenerator) "name4", {}, {}, imageCallbackMock.AsStdFunction(), abortCallbackMock.AsStdFunction(), {}); } -TEST_F(ImageCacheGenerator, StoreImage) +TEST_F(ImageCacheGenerator, store_image) { ON_CALL(collectorMock, start(Eq("name"), _, _, _, _)) .WillByDefault([&](auto, auto, auto, auto captureCallback, auto) { @@ -120,7 +120,7 @@ TEST_F(ImageCacheGenerator, StoreImage) notification.wait(); } -TEST_F(ImageCacheGenerator, StoreImageWithExtraId) +TEST_F(ImageCacheGenerator, store_image_with_extra_id) { ON_CALL(collectorMock, start(Eq("name"), _, _, _, _)) .WillByDefault([&](auto, auto, auto, auto captureCallback, auto) { @@ -139,7 +139,7 @@ TEST_F(ImageCacheGenerator, StoreImageWithExtraId) notification.wait(); } -TEST_F(ImageCacheGenerator, StoreNullImage) +TEST_F(ImageCacheGenerator, store_null_image) { ON_CALL(collectorMock, start(Eq("name"), _, _, _, _)) .WillByDefault([&](auto, auto, auto, auto captureCallback, auto) { @@ -156,7 +156,7 @@ TEST_F(ImageCacheGenerator, StoreNullImage) notification.wait(); } -TEST_F(ImageCacheGenerator, StoreNullImageWithExtraId) +TEST_F(ImageCacheGenerator, store_null_image_with_extra_id) { ON_CALL(collectorMock, start(Eq("name"), _, _, _, _)) .WillByDefault([&](auto, auto, auto, auto captureCallback, auto) { @@ -180,7 +180,7 @@ TEST_F(ImageCacheGenerator, StoreNullImageWithExtraId) notification.wait(); } -TEST_F(ImageCacheGenerator, AbortCallback) +TEST_F(ImageCacheGenerator, abort_callback) { ON_CALL(collectorMock, start(Eq("name"), _, _, _, _)) .WillByDefault([&](auto, auto, auto, auto captureCallback, auto) { @@ -203,7 +203,7 @@ TEST_F(ImageCacheGenerator, AbortCallback) notification.wait(2); } -TEST_F(ImageCacheGenerator, StoreNullImageForAbortCallbackAbort) +TEST_F(ImageCacheGenerator, store_null_image_for_abort_callback_abort) { ON_CALL(collectorMock, start(Eq("name"), _, _, _, _)) .WillByDefault([&](auto, auto, auto, auto, auto abortCallback) { @@ -220,7 +220,7 @@ TEST_F(ImageCacheGenerator, StoreNullImageForAbortCallbackAbort) notification.wait(); } -TEST_F(ImageCacheGenerator, DontStoreNullImageForAbortCallbackFailed) +TEST_F(ImageCacheGenerator, dont_store_null_image_for_abort_callback_failed) { ON_CALL(collectorMock, start(_, _, _, _, _)) .WillByDefault([&](auto, auto, auto, auto, auto abortCallback) { @@ -237,7 +237,7 @@ TEST_F(ImageCacheGenerator, DontStoreNullImageForAbortCallbackFailed) notification.wait(); } -TEST_F(ImageCacheGenerator, AbortForNullImage) +TEST_F(ImageCacheGenerator, abort_for_null_image) { ON_CALL(collectorMock, start(Eq("name"), _, _, _, _)) .WillByDefault([&](auto, auto, auto, auto captureCallback, auto) { @@ -252,7 +252,7 @@ TEST_F(ImageCacheGenerator, AbortForNullImage) notification.wait(); } -TEST_F(ImageCacheGenerator, CallImageCallbackIfSmallImageIsNotNull) +TEST_F(ImageCacheGenerator, call_image_callback_if_small_image_is_not_null) { ON_CALL(collectorMock, start(Eq("name"), _, _, _, _)) .WillByDefault([&](auto, auto, auto, auto captureCallback, auto) { @@ -267,7 +267,7 @@ TEST_F(ImageCacheGenerator, CallImageCallbackIfSmallImageIsNotNull) notification.wait(); } -TEST_F(ImageCacheGenerator, StoreImageIfSmallImageIsNotNull) +TEST_F(ImageCacheGenerator, store_image_if_small_image_is_not_null) { ON_CALL(collectorMock, start(Eq("name"), _, _, _, _)) .WillByDefault([&](auto, auto, auto, auto captureCallback, auto) { @@ -282,7 +282,7 @@ TEST_F(ImageCacheGenerator, StoreImageIfSmallImageIsNotNull) notification.wait(); } -TEST_F(ImageCacheGenerator, CallImageCallbackIfMidSizeImageIsNotNull) +TEST_F(ImageCacheGenerator, call_image_callback_if_mid_size_image_is_not_null) { ON_CALL(collectorMock, start(Eq("name"), _, _, _, _)) .WillByDefault([&](auto, auto, auto, auto captureCallback, auto) { @@ -297,7 +297,7 @@ TEST_F(ImageCacheGenerator, CallImageCallbackIfMidSizeImageIsNotNull) notification.wait(); } -TEST_F(ImageCacheGenerator, StoreImageIfMidSizeImageIsNotNull) +TEST_F(ImageCacheGenerator, store_image_if_mid_size_image_is_not_null) { ON_CALL(collectorMock, start(Eq("name"), _, _, _, _)) .WillByDefault([&](auto, auto, auto, auto captureCallback, auto) { @@ -312,7 +312,7 @@ TEST_F(ImageCacheGenerator, StoreImageIfMidSizeImageIsNotNull) notification.wait(); } -TEST_F(ImageCacheGenerator, CallImageCallbackIfImageIsNotNull) +TEST_F(ImageCacheGenerator, call_image_callback_if_image_is_not_null) { ON_CALL(collectorMock, start(Eq("name"), _, _, _, _)) .WillByDefault( @@ -326,7 +326,7 @@ TEST_F(ImageCacheGenerator, CallImageCallbackIfImageIsNotNull) notification.wait(); } -TEST_F(ImageCacheGenerator, StoreImageIfImageIsNotNull) +TEST_F(ImageCacheGenerator, store_image_if_image_is_not_null) { ON_CALL(collectorMock, start(Eq("name"), _, _, _, _)) .WillByDefault( @@ -340,7 +340,7 @@ TEST_F(ImageCacheGenerator, StoreImageIfImageIsNotNull) notification.wait(); } -TEST_F(ImageCacheGenerator, CallWalCheckpointFullIfQueueIsEmpty) +TEST_F(ImageCacheGenerator, call_wal_checkpoint_full_if_queue_is_empty) { ON_CALL(collectorMock, start(Eq("name"), _, _, _, _)) .WillByDefault( @@ -355,7 +355,7 @@ TEST_F(ImageCacheGenerator, CallWalCheckpointFullIfQueueIsEmpty) notification.wait(); } -TEST_F(ImageCacheGenerator, CleanIsCallingAbortCallback) +TEST_F(ImageCacheGenerator, clean_is_calling_abort_callback) { ON_CALL(collectorMock, start(_, _, _, _, _)).WillByDefault([&](auto, auto, auto, auto, auto) { notification.wait(); @@ -374,7 +374,7 @@ TEST_F(ImageCacheGenerator, CleanIsCallingAbortCallback) waitInThread.wait(); } -TEST_F(ImageCacheGenerator, WaitForFinished) +TEST_F(ImageCacheGenerator, wait_for_finished) { ON_CALL(collectorMock, start(Eq("name"), _, _, _, _)) .WillByDefault([&](auto, auto, auto, auto captureCallback, auto) { @@ -397,7 +397,7 @@ TEST_F(ImageCacheGenerator, WaitForFinished) generator.waitForFinished(); } -TEST_F(ImageCacheGenerator, CallsCollectorWithExtraId) +TEST_F(ImageCacheGenerator, calls_collector_with_extra_id) { EXPECT_CALL(collectorMock, start(Eq("name"), Eq("extraId1"), _, _, _)) .WillRepeatedly([&](auto, auto, auto, auto, auto) { notification.notify(); }); @@ -406,7 +406,7 @@ TEST_F(ImageCacheGenerator, CallsCollectorWithExtraId) notification.wait(); } -TEST_F(ImageCacheGenerator, CallsCollectorWithAuxiliaryData) +TEST_F(ImageCacheGenerator, calls_collector_with_auxiliary_data) { using QmlDesigner::ImageCache::FontCollectorSizesAuxiliaryData; std::vector sizes{{20, 11}}; @@ -431,7 +431,7 @@ TEST_F(ImageCacheGenerator, CallsCollectorWithAuxiliaryData) notification.wait(); } -TEST_F(ImageCacheGenerator, MergeTasks) +TEST_F(ImageCacheGenerator, merge_tasks) { EXPECT_CALL(collectorMock, start(Eq("waitDummy"), _, _, _, _)) .WillRepeatedly([&](auto, auto, auto, auto, auto) { waitInThread.wait(); }); @@ -448,7 +448,7 @@ TEST_F(ImageCacheGenerator, MergeTasks) notification.wait(); } -TEST_F(ImageCacheGenerator, DontMergeTasksWithDifferentId) +TEST_F(ImageCacheGenerator, dont_merge_tasks_with_different_id) { EXPECT_CALL(collectorMock, start(Eq("waitDummy"), _, _, _, _)) .WillRepeatedly([&](auto, auto, auto, auto, auto) { waitInThread.wait(); }); @@ -465,7 +465,7 @@ TEST_F(ImageCacheGenerator, DontMergeTasksWithDifferentId) notification.wait(2); } -TEST_F(ImageCacheGenerator, MergeTasksWithSameExtraId) +TEST_F(ImageCacheGenerator, merge_tasks_with_same_extra_id) { EXPECT_CALL(collectorMock, start(Eq("waitDummy"), _, _, _, _)) .WillRepeatedly([&](auto, auto, auto, auto, auto) { waitInThread.wait(); }); @@ -482,7 +482,7 @@ TEST_F(ImageCacheGenerator, MergeTasksWithSameExtraId) notification.wait(); } -TEST_F(ImageCacheGenerator, DontMergeTasksWithDifferentExtraId) +TEST_F(ImageCacheGenerator, dont_merge_tasks_with_different_extra_id) { EXPECT_CALL(collectorMock, start(Eq("waitDummy"), _, _, _, _)) .WillRepeatedly([&](auto, auto, auto, auto, auto) { waitInThread.wait(); }); @@ -498,7 +498,7 @@ TEST_F(ImageCacheGenerator, DontMergeTasksWithDifferentExtraId) notification.wait(2); } -TEST_F(ImageCacheGenerator, UseLastTimeStampIfTasksAreMerged) +TEST_F(ImageCacheGenerator, use_last_time_stamp_if_tasks_are_merged) { ON_CALL(collectorMock, start(Eq("waitDummy"), _, _, _, _)) .WillByDefault([&](auto, auto, auto, auto, auto) { waitInThread.wait(); }); @@ -519,7 +519,7 @@ TEST_F(ImageCacheGenerator, UseLastTimeStampIfTasksAreMerged) notification.wait(); } -TEST_F(ImageCacheGenerator, MergeCaptureCallbackIfTasksAreMerged) +TEST_F(ImageCacheGenerator, merge_capture_callback_if_tasks_are_merged) { NiceMock> newerImageCallbackMock; ON_CALL(collectorMock, start(Eq("waitDummy"), _, _, _, _)) @@ -542,7 +542,7 @@ TEST_F(ImageCacheGenerator, MergeCaptureCallbackIfTasksAreMerged) notification.wait(); } -TEST_F(ImageCacheGenerator, MergeAbortCallbackIfTasksAreMerged) +TEST_F(ImageCacheGenerator, merge_abort_callback_if_tasks_are_merged) { NiceMock> newerAbortCallbackMock; ON_CALL(collectorMock, start(Eq("waitDummy"), _, _, _, _)) @@ -565,7 +565,7 @@ TEST_F(ImageCacheGenerator, MergeAbortCallbackIfTasksAreMerged) notification.wait(); } -TEST_F(ImageCacheGenerator, DontCallNullImageCallback) +TEST_F(ImageCacheGenerator, dont_call_null_image_callback) { EXPECT_CALL(collectorMock, start(_, _, _, _, _)) .WillOnce([&](auto, auto, auto, auto captureCallback, auto) { @@ -577,7 +577,7 @@ TEST_F(ImageCacheGenerator, DontCallNullImageCallback) notification.wait(); } -TEST_F(ImageCacheGenerator, DontCallNullAbortCallbackForNullImage) +TEST_F(ImageCacheGenerator, dont_call_null_abort_callback_for_null_image) { EXPECT_CALL(collectorMock, start(_, _, _, _, _)) .WillOnce([&](auto, auto, auto, auto captureCallback, auto) { @@ -589,7 +589,7 @@ TEST_F(ImageCacheGenerator, DontCallNullAbortCallbackForNullImage) notification.wait(); } -TEST_F(ImageCacheGenerator, DontCallNullAbortCallback) +TEST_F(ImageCacheGenerator, dont_call_null_abort_callback) { EXPECT_CALL(collectorMock, start(_, _, _, _, _)) .WillOnce([&](auto, auto, auto, auto, auto abortCallback) { diff --git a/tests/unit/unittest/imagecachestorage-test.cpp b/tests/unit/tests/unittests/imagecache/imagecachestorage-test.cpp similarity index 83% rename from tests/unit/unittest/imagecachestorage-test.cpp rename to tests/unit/tests/unittests/imagecache/imagecachestorage-test.cpp index f596fce9d2d..45f602130b9 100644 --- a/tests/unit/unittest/imagecachestorage-test.cpp +++ b/tests/unit/tests/unittests/imagecache/imagecachestorage-test.cpp @@ -1,9 +1,9 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" -#include "sqlitedatabasemock.h" +#include "../mocks/sqlitedatabasemock.h" #include #include @@ -15,7 +15,7 @@ MATCHER_P(IsIcon, icon, std::string(negation ? "is't" : "is") + PrintToString(ic return arg.availableSizes() == icon.availableSizes(); } -TEST(ImageCacheStorageUpdateTest, CheckVersionIfDatabaseIsAlreadyInitialized) +TEST(ImageCacheStorageUpdateTest, check_version_if_database_is_already_initialized) { NiceMock databaseMock; ON_CALL(databaseMock, isInitialized()).WillByDefault(Return(true)); @@ -25,7 +25,7 @@ TEST(ImageCacheStorageUpdateTest, CheckVersionIfDatabaseIsAlreadyInitialized) QmlDesigner::ImageCacheStorage storage{databaseMock}; } -TEST(ImageCacheStorageUpdateTest, AddColumnMidSizeIfVersionIsZero) +TEST(ImageCacheStorageUpdateTest, add_column_mid_size_if_version_is_zero) { NiceMock databaseMock; ON_CALL(databaseMock, isInitialized()).WillByDefault(Return(true)); @@ -36,7 +36,7 @@ TEST(ImageCacheStorageUpdateTest, AddColumnMidSizeIfVersionIsZero) QmlDesigner::ImageCacheStorage storage{databaseMock}; } -TEST(ImageCacheStorageUpdateTest, DeleteAllRowsBeforeAddingMidSizeColumn) +TEST(ImageCacheStorageUpdateTest, delete_all_rows_before_adding_mid_size_column) { NiceMock databaseMock; ON_CALL(databaseMock, isInitialized()).WillByDefault(Return(true)); @@ -48,7 +48,7 @@ TEST(ImageCacheStorageUpdateTest, DeleteAllRowsBeforeAddingMidSizeColumn) QmlDesigner::ImageCacheStorage storage{databaseMock}; } -TEST(ImageCacheStorageUpdateTest, DontCallAddColumnMidSizeIfDatabaseWasNotAlreadyInitialized) +TEST(ImageCacheStorageUpdateTest, dont_call_add_column_mid_size_if_database_was_not_already_initialized) { NiceMock databaseMock; ON_CALL(databaseMock, isInitialized()).WillByDefault(Return(false)); @@ -59,7 +59,7 @@ TEST(ImageCacheStorageUpdateTest, DontCallAddColumnMidSizeIfDatabaseWasNotAlread QmlDesigner::ImageCacheStorage storage{databaseMock}; } -TEST(ImageCacheStorageUpdateTest, SetVersionToOneIfVersionIsZero) +TEST(ImageCacheStorageUpdateTest, set_version_to_one_if_version_is_zero) { NiceMock databaseMock; ON_CALL(databaseMock, isInitialized()).WillByDefault(Return(true)); @@ -69,7 +69,7 @@ TEST(ImageCacheStorageUpdateTest, SetVersionToOneIfVersionIsZero) QmlDesigner::ImageCacheStorage storage{databaseMock}; } -TEST(ImageCacheStorageUpdateTest, DontSetVersionIfVersionIsOne) +TEST(ImageCacheStorageUpdateTest, dont_set_version_if_version_is_one) { NiceMock databaseMock; ON_CALL(databaseMock, isInitialized()).WillByDefault(Return(true)); @@ -80,7 +80,7 @@ TEST(ImageCacheStorageUpdateTest, DontSetVersionIfVersionIsOne) QmlDesigner::ImageCacheStorage storage{databaseMock}; } -TEST(ImageCacheStorageUpdateTest, SetVersionToOneForInitialization) +TEST(ImageCacheStorageUpdateTest, set_version_to_one_for_initialization) { NiceMock databaseMock; ON_CALL(databaseMock, isInitialized()).WillByDefault(Return(false)); @@ -114,7 +114,7 @@ protected: QIcon icon1{QPixmap::fromImage(image1)}; }; -TEST_F(ImageCacheStorageTest, FetchImageCalls) +TEST_F(ImageCacheStorageTest, fetch_image_calls) { InSequence s; @@ -127,7 +127,7 @@ TEST_F(ImageCacheStorageTest, FetchImageCalls) storage.fetchImage("/path/to/component", {123}); } -TEST_F(ImageCacheStorageTest, FetchImageCallsIsBusy) +TEST_F(ImageCacheStorageTest, fetch_image_calls_is_busy) { InSequence s; @@ -146,7 +146,7 @@ TEST_F(ImageCacheStorageTest, FetchImageCallsIsBusy) storage.fetchImage("/path/to/component", {123}); } -TEST_F(ImageCacheStorageTest, FetchMidSizeImageCalls) +TEST_F(ImageCacheStorageTest, fetch_mid_size_image_calls) { InSequence s; @@ -159,7 +159,7 @@ TEST_F(ImageCacheStorageTest, FetchMidSizeImageCalls) storage.fetchMidSizeImage("/path/to/component", {123}); } -TEST_F(ImageCacheStorageTest, FetchMidSizeImageCallsIsBusy) +TEST_F(ImageCacheStorageTest, fetch_mid_size_image_calls_is_busy) { InSequence s; @@ -178,7 +178,7 @@ TEST_F(ImageCacheStorageTest, FetchMidSizeImageCallsIsBusy) storage.fetchMidSizeImage("/path/to/component", {123}); } -TEST_F(ImageCacheStorageTest, FetchSmallImageCalls) +TEST_F(ImageCacheStorageTest, fetch_small_image_calls) { InSequence s; @@ -191,7 +191,7 @@ TEST_F(ImageCacheStorageTest, FetchSmallImageCalls) storage.fetchSmallImage("/path/to/component", {123}); } -TEST_F(ImageCacheStorageTest, FetchSmallImageCallsIsBusy) +TEST_F(ImageCacheStorageTest, fetch_small_image_calls_is_busy) { InSequence s; @@ -210,7 +210,7 @@ TEST_F(ImageCacheStorageTest, FetchSmallImageCallsIsBusy) storage.fetchSmallImage("/path/to/component", {123}); } -TEST_F(ImageCacheStorageTest, FetchIconCalls) +TEST_F(ImageCacheStorageTest, fetch_icon_calls) { InSequence s; @@ -223,7 +223,7 @@ TEST_F(ImageCacheStorageTest, FetchIconCalls) storage.fetchIcon("/path/to/component", {123}); } -TEST_F(ImageCacheStorageTest, FetchIconCallsIsBusy) +TEST_F(ImageCacheStorageTest, fetch_icon_calls_is_busy) { InSequence s; @@ -242,7 +242,7 @@ TEST_F(ImageCacheStorageTest, FetchIconCallsIsBusy) storage.fetchIcon("/path/to/component", {123}); } -TEST_F(ImageCacheStorageTest, StoreImageCalls) +TEST_F(ImageCacheStorageTest, store_image_calls) { InSequence s; @@ -258,7 +258,7 @@ TEST_F(ImageCacheStorageTest, StoreImageCalls) storage.storeImage("/path/to/component", {123}, image1, midSizeImage1, smallImage1); } -TEST_F(ImageCacheStorageTest, StoreEmptyImageCalls) +TEST_F(ImageCacheStorageTest, store_empty_image_calls) { InSequence s; @@ -274,7 +274,7 @@ TEST_F(ImageCacheStorageTest, StoreEmptyImageCalls) storage.storeImage("/path/to/component", {123}, QImage{}, QImage{}, QImage{}); } -TEST_F(ImageCacheStorageTest, StoreImageCallsIsBusy) +TEST_F(ImageCacheStorageTest, store_image_calls_is_busy) { InSequence s; @@ -291,7 +291,7 @@ TEST_F(ImageCacheStorageTest, StoreImageCallsIsBusy) storage.storeImage("/path/to/component", {123}, QImage{}, QImage{}, QImage{}); } -TEST_F(ImageCacheStorageTest, StoreIconCalls) +TEST_F(ImageCacheStorageTest, store_icon_calls) { InSequence s; @@ -305,7 +305,7 @@ TEST_F(ImageCacheStorageTest, StoreIconCalls) storage.storeIcon("/path/to/component", {123}, icon1); } -TEST_F(ImageCacheStorageTest, StoreEmptyIconCalls) +TEST_F(ImageCacheStorageTest, store_empty_icon_calls) { InSequence s; @@ -319,7 +319,7 @@ TEST_F(ImageCacheStorageTest, StoreEmptyIconCalls) storage.storeIcon("/path/to/component", {123}, QIcon{}); } -TEST_F(ImageCacheStorageTest, StoreIconCallsIsBusy) +TEST_F(ImageCacheStorageTest, store_icon_calls_is_busy) { InSequence s; @@ -334,14 +334,14 @@ TEST_F(ImageCacheStorageTest, StoreIconCallsIsBusy) storage.storeIcon("/path/to/component", {123}, QIcon{}); } -TEST_F(ImageCacheStorageTest, CallWalCheckointFull) +TEST_F(ImageCacheStorageTest, call_wal_checkoint_full) { EXPECT_CALL(databaseMock, walCheckpointFull()); storage.walCheckpointFull(); } -TEST_F(ImageCacheStorageTest, CallWalCheckointFullIsBusy) +TEST_F(ImageCacheStorageTest, call_wal_checkoint_full_is_busy) { InSequence s; @@ -372,14 +372,14 @@ protected: QIcon icon1{QPixmap::fromImage(image1)}; }; -TEST_F(ImageCacheStorageSlowTest, StoreImage) +TEST_F(ImageCacheStorageSlowTest, store_image) { storage.storeImage("/path/to/component", {123}, image1, QImage{}, QImage{}); ASSERT_THAT(storage.fetchImage("/path/to/component", {123}), Optional(image1)); } -TEST_F(ImageCacheStorageSlowTest, StoreEmptyImageAfterEntry) +TEST_F(ImageCacheStorageSlowTest, store_empty_image_after_entry) { storage.storeImage("/path/to/component", {123}, image1, midSizeImage1, smallImage1); @@ -388,14 +388,14 @@ TEST_F(ImageCacheStorageSlowTest, StoreEmptyImageAfterEntry) ASSERT_THAT(storage.fetchImage("/path/to/component", {123}), Optional(QImage{})); } -TEST_F(ImageCacheStorageSlowTest, StoreMidSizeImage) +TEST_F(ImageCacheStorageSlowTest, store_mid_size_image) { storage.storeImage("/path/to/component", {123}, QImage{}, midSizeImage1, QImage{}); ASSERT_THAT(storage.fetchMidSizeImage("/path/to/component", {123}), Optional(midSizeImage1)); } -TEST_F(ImageCacheStorageSlowTest, StoreEmptyMidSizeImageAfterEntry) +TEST_F(ImageCacheStorageSlowTest, store_empty_mid_size_image_after_entry) { storage.storeImage("/path/to/component", {123}, image1, midSizeImage1, smallImage1); @@ -404,14 +404,14 @@ TEST_F(ImageCacheStorageSlowTest, StoreEmptyMidSizeImageAfterEntry) ASSERT_THAT(storage.fetchMidSizeImage("/path/to/component", {123}), Optional(QImage{})); } -TEST_F(ImageCacheStorageSlowTest, StoreSmallImage) +TEST_F(ImageCacheStorageSlowTest, store_small_image) { storage.storeImage("/path/to/component", {123}, QImage{}, QImage{}, smallImage1); ASSERT_THAT(storage.fetchSmallImage("/path/to/component", {123}), Optional(smallImage1)); } -TEST_F(ImageCacheStorageSlowTest, StoreEmptySmallImageAfterEntry) +TEST_F(ImageCacheStorageSlowTest, store_empty_small_image_after_entry) { storage.storeImage("/path/to/component", {123}, image1, midSizeImage1, smallImage1); @@ -420,21 +420,21 @@ TEST_F(ImageCacheStorageSlowTest, StoreEmptySmallImageAfterEntry) ASSERT_THAT(storage.fetchSmallImage("/path/to/component", {123}), Optional(QImage{})); } -TEST_F(ImageCacheStorageSlowTest, StoreEmptyEntry) +TEST_F(ImageCacheStorageSlowTest, store_empty_entry) { storage.storeImage("/path/to/component", {123}, QImage{}, QImage{}, QImage{}); ASSERT_THAT(storage.fetchImage("/path/to/component", {123}), Optional(QImage{})); } -TEST_F(ImageCacheStorageSlowTest, FetchNonExistingImageIsEmpty) +TEST_F(ImageCacheStorageSlowTest, fetch_non_existing_image_is_empty) { auto image = storage.fetchImage("/path/to/component", {123}); ASSERT_THAT(image, Eq(std::nullopt)); } -TEST_F(ImageCacheStorageSlowTest, FetchSameTimeImage) +TEST_F(ImageCacheStorageSlowTest, fetch_same_time_image) { storage.storeImage("/path/to/component", {123}, image1, midSizeImage1, smallImage1); @@ -443,7 +443,7 @@ TEST_F(ImageCacheStorageSlowTest, FetchSameTimeImage) ASSERT_THAT(image, Optional(image1)); } -TEST_F(ImageCacheStorageSlowTest, DoNotFetchOlderImage) +TEST_F(ImageCacheStorageSlowTest, do_not_fetch_older_image) { storage.storeImage("/path/to/component", {123}, image1, midSizeImage1, smallImage1); @@ -452,7 +452,7 @@ TEST_F(ImageCacheStorageSlowTest, DoNotFetchOlderImage) ASSERT_THAT(image, Eq(std::nullopt)); } -TEST_F(ImageCacheStorageSlowTest, FetchNewerImage) +TEST_F(ImageCacheStorageSlowTest, fetch_newer_image) { storage.storeImage("/path/to/component", {123}, image1, midSizeImage1, smallImage1); @@ -461,14 +461,14 @@ TEST_F(ImageCacheStorageSlowTest, FetchNewerImage) ASSERT_THAT(image, Optional(image1)); } -TEST_F(ImageCacheStorageSlowTest, FetchNonExistingMidSizeImageIsEmpty) +TEST_F(ImageCacheStorageSlowTest, fetch_non_existing_mid_size_image_is_empty) { auto image = storage.fetchMidSizeImage("/path/to/component", {123}); ASSERT_THAT(image, Eq(std::nullopt)); } -TEST_F(ImageCacheStorageSlowTest, FetchSameTimeMidSizeImage) +TEST_F(ImageCacheStorageSlowTest, fetch_same_time_mid_size_image) { storage.storeImage("/path/to/component", {123}, image1, midSizeImage1, smallImage1); @@ -477,7 +477,7 @@ TEST_F(ImageCacheStorageSlowTest, FetchSameTimeMidSizeImage) ASSERT_THAT(image, Optional(midSizeImage1)); } -TEST_F(ImageCacheStorageSlowTest, DoNotFetchOlderMidSizeImage) +TEST_F(ImageCacheStorageSlowTest, do_not_fetch_older_mid_size_image) { storage.storeImage("/path/to/component", {123}, image1, midSizeImage1, smallImage1); @@ -486,7 +486,7 @@ TEST_F(ImageCacheStorageSlowTest, DoNotFetchOlderMidSizeImage) ASSERT_THAT(image, Eq(std::nullopt)); } -TEST_F(ImageCacheStorageSlowTest, FetchNewerMidSizeImage) +TEST_F(ImageCacheStorageSlowTest, fetch_newer_mid_size_image) { storage.storeImage("/path/to/component", {123}, image1, midSizeImage1, smallImage1); @@ -495,14 +495,14 @@ TEST_F(ImageCacheStorageSlowTest, FetchNewerMidSizeImage) ASSERT_THAT(image, Optional(midSizeImage1)); } -TEST_F(ImageCacheStorageSlowTest, FetchNonExistingSmallImageIsEmpty) +TEST_F(ImageCacheStorageSlowTest, fetch_non_existing_small_image_is_empty) { auto image = storage.fetchSmallImage("/path/to/component", {123}); ASSERT_THAT(image, Eq(std::nullopt)); } -TEST_F(ImageCacheStorageSlowTest, FetchSameTimeSmallImage) +TEST_F(ImageCacheStorageSlowTest, fetch_same_time_small_image) { storage.storeImage("/path/to/component", {123}, image1, midSizeImage1, smallImage1); @@ -511,7 +511,7 @@ TEST_F(ImageCacheStorageSlowTest, FetchSameTimeSmallImage) ASSERT_THAT(image, Optional(smallImage1)); } -TEST_F(ImageCacheStorageSlowTest, DoNotFetchOlderSmallImage) +TEST_F(ImageCacheStorageSlowTest, do_not_fetch_older_small_image) { storage.storeImage("/path/to/component", {123}, image1, midSizeImage1, smallImage1); @@ -520,7 +520,7 @@ TEST_F(ImageCacheStorageSlowTest, DoNotFetchOlderSmallImage) ASSERT_THAT(image, Eq(std::nullopt)); } -TEST_F(ImageCacheStorageSlowTest, FetchNewerSmallImage) +TEST_F(ImageCacheStorageSlowTest, fetch_newer_small_image) { storage.storeImage("/path/to/component", {123}, image1, midSizeImage1, smallImage1); @@ -529,14 +529,14 @@ TEST_F(ImageCacheStorageSlowTest, FetchNewerSmallImage) ASSERT_THAT(image, Optional(smallImage1)); } -TEST_F(ImageCacheStorageSlowTest, StoreIcon) +TEST_F(ImageCacheStorageSlowTest, store_icon) { storage.storeIcon("/path/to/component", {123}, icon1); ASSERT_THAT(storage.fetchIcon("/path/to/component", {123}), Optional(IsIcon(icon1))); } -TEST_F(ImageCacheStorageSlowTest, StoreEmptyIconAfterEntry) +TEST_F(ImageCacheStorageSlowTest, store_empty_icon_after_entry) { storage.storeIcon("/path/to/component", {123}, icon1); @@ -545,21 +545,21 @@ TEST_F(ImageCacheStorageSlowTest, StoreEmptyIconAfterEntry) ASSERT_THAT(storage.fetchIcon("/path/to/component", {123}), Optional(IsIcon(QIcon{}))); } -TEST_F(ImageCacheStorageSlowTest, StoreEmptyIconEntry) +TEST_F(ImageCacheStorageSlowTest, store_empty_icon_entry) { storage.storeIcon("/path/to/component", {123}, QIcon{}); ASSERT_THAT(storage.fetchIcon("/path/to/component", {123}), Optional(IsIcon(QIcon{}))); } -TEST_F(ImageCacheStorageSlowTest, FetchNonExistingIconIsEmpty) +TEST_F(ImageCacheStorageSlowTest, fetch_non_existing_icon_is_empty) { auto image = storage.fetchIcon("/path/to/component", {123}); ASSERT_THAT(image, Eq(std::nullopt)); } -TEST_F(ImageCacheStorageSlowTest, FetchSameTimeIcon) +TEST_F(ImageCacheStorageSlowTest, fetch_same_time_icon) { storage.storeIcon("/path/to/component", {123}, icon1); @@ -568,7 +568,7 @@ TEST_F(ImageCacheStorageSlowTest, FetchSameTimeIcon) ASSERT_THAT(image, Optional(IsIcon(icon1))); } -TEST_F(ImageCacheStorageSlowTest, DoNotFetchOlderIcon) +TEST_F(ImageCacheStorageSlowTest, do_not_fetch_older_icon) { storage.storeIcon("/path/to/component", {123}, icon1); @@ -577,7 +577,7 @@ TEST_F(ImageCacheStorageSlowTest, DoNotFetchOlderIcon) ASSERT_THAT(image, Eq(std::nullopt)); } -TEST_F(ImageCacheStorageSlowTest, FetchNewerIcon) +TEST_F(ImageCacheStorageSlowTest, fetch_newer_icon) { storage.storeIcon("/path/to/component", {123}, icon1); @@ -586,7 +586,7 @@ TEST_F(ImageCacheStorageSlowTest, FetchNewerIcon) ASSERT_THAT(image, Optional(IsIcon(icon1))); } -TEST_F(ImageCacheStorageSlowTest, FetchModifiedImageTime) +TEST_F(ImageCacheStorageSlowTest, fetch_modified_image_time) { storage.storeImage("/path/to/component", {123}, image1, midSizeImage1, smallImage1); @@ -595,7 +595,7 @@ TEST_F(ImageCacheStorageSlowTest, FetchModifiedImageTime) ASSERT_THAT(timeStamp, Eq(Sqlite::TimeStamp{123})); } -TEST_F(ImageCacheStorageSlowTest, FetchInvalidModifiedImageTimeForNoEntry) +TEST_F(ImageCacheStorageSlowTest, fetch_invalid_modified_image_time_for_no_entry) { storage.storeImage("/path/to/component2", {123}, image1, midSizeImage1, smallImage1); @@ -604,7 +604,7 @@ TEST_F(ImageCacheStorageSlowTest, FetchInvalidModifiedImageTimeForNoEntry) ASSERT_THAT(timeStamp, Eq(Sqlite::TimeStamp{})); } -TEST_F(ImageCacheStorageSlowTest, FetchHasImage) +TEST_F(ImageCacheStorageSlowTest, fetch_has_image) { storage.storeImage("/path/to/component", {123}, image1, midSizeImage1, smallImage1); @@ -613,7 +613,7 @@ TEST_F(ImageCacheStorageSlowTest, FetchHasImage) ASSERT_TRUE(hasImage); } -TEST_F(ImageCacheStorageSlowTest, FetchHasImageForNullImage) +TEST_F(ImageCacheStorageSlowTest, fetch_has_image_for_null_image) { storage.storeImage("/path/to/component", {123}, QImage{}, QImage{}, QImage{}); @@ -622,7 +622,7 @@ TEST_F(ImageCacheStorageSlowTest, FetchHasImageForNullImage) ASSERT_FALSE(hasImage); } -TEST_F(ImageCacheStorageSlowTest, FetchHasImageForNoEntry) +TEST_F(ImageCacheStorageSlowTest, fetch_has_image_for_no_entry) { storage.storeImage("/path/to/component", {123}, QImage{}, QImage{}, QImage{}); diff --git a/tests/unit/unittest/synchronousimagecache-test.cpp b/tests/unit/tests/unittests/imagecache/synchronousimagecache-test.cpp similarity index 87% rename from tests/unit/unittest/synchronousimagecache-test.cpp rename to tests/unit/tests/unittests/imagecache/synchronousimagecache-test.cpp index d239c22b0dc..0f6a053988a 100644 --- a/tests/unit/unittest/synchronousimagecache-test.cpp +++ b/tests/unit/tests/unittests/imagecache/synchronousimagecache-test.cpp @@ -1,11 +1,11 @@ // Copyright (C) 2021 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" -#include "imagecachecollectormock.h" -#include "mockimagecachestorage.h" -#include "mocktimestampprovider.h" +#include "../mocks/imagecachecollectormock.h" +#include "../mocks/mockimagecachestorage.h" +#include "../mocks/mocktimestampprovider.h" #include @@ -71,21 +71,21 @@ protected: QIcon icon3{QPixmap::fromImage(image3)}; }; -TEST_F(SynchronousImageCache, GetImageFromStorage) +TEST_F(SynchronousImageCache, get_image_from_storage) { auto image = cache.image("/path/to/Component.qml"); ASSERT_THAT(image, image1); } -TEST_F(SynchronousImageCache, GetImageWithExtraIdFromStorage) +TEST_F(SynchronousImageCache, get_image_with_extra_id_from_storage) { auto image = cache.image("/path/to/Component.qml", "extraId1"); ASSERT_THAT(image, image2); } -TEST_F(SynchronousImageCache, GetImageWithOutdatedTimeStampFromCollector) +TEST_F(SynchronousImageCache, get_image_with_outdated_time_stamp_from_collector) { ON_CALL(mockTimeStampProvider, timeStamp(Eq("/path/to/Component.qml"))) .WillByDefault(Return(Sqlite::TimeStamp{124})); @@ -95,7 +95,7 @@ TEST_F(SynchronousImageCache, GetImageWithOutdatedTimeStampFromCollector) ASSERT_THAT(image, image3); } -TEST_F(SynchronousImageCache, GetImageWithOutdatedTimeStampStored) +TEST_F(SynchronousImageCache, get_image_with_outdated_time_stamp_stored) { ON_CALL(mockTimeStampProvider, timeStamp(Eq("/path/to/Component.qml"))) .WillByDefault(Return(Sqlite::TimeStamp{124})); @@ -110,21 +110,21 @@ TEST_F(SynchronousImageCache, GetImageWithOutdatedTimeStampStored) auto image = cache.image("/path/to/Component.qml", "extraId1"); } -TEST_F(SynchronousImageCache, GetMidSizeImageFromStorage) +TEST_F(SynchronousImageCache, get_mid_size_image_from_storage) { auto image = cache.midSizeImage("/path/to/Component.qml"); ASSERT_THAT(image, midSizeImage1); } -TEST_F(SynchronousImageCache, GetMidSizeImageWithExtraIdFromStorage) +TEST_F(SynchronousImageCache, get_mid_size_image_with_extra_id_from_storage) { auto image = cache.midSizeImage("/path/to/Component.qml", "extraId1"); ASSERT_THAT(image, midSizeImage2); } -TEST_F(SynchronousImageCache, GetMidSizeImageWithOutdatedTimeStampFromCollector) +TEST_F(SynchronousImageCache, get_mid_size_image_with_outdated_time_stamp_from_collector) { ON_CALL(mockTimeStampProvider, timeStamp(Eq("/path/to/Component.qml"))) .WillByDefault(Return(Sqlite::TimeStamp{124})); @@ -134,7 +134,7 @@ TEST_F(SynchronousImageCache, GetMidSizeImageWithOutdatedTimeStampFromCollector) ASSERT_THAT(image, midSizeImage3); } -TEST_F(SynchronousImageCache, GetMidSizeImageWithOutdatedTimeStampStored) +TEST_F(SynchronousImageCache, get_mid_size_image_with_outdated_time_stamp_stored) { ON_CALL(mockTimeStampProvider, timeStamp(Eq("/path/to/Component.qml"))) .WillByDefault(Return(Sqlite::TimeStamp{124})); @@ -149,21 +149,21 @@ TEST_F(SynchronousImageCache, GetMidSizeImageWithOutdatedTimeStampStored) auto image = cache.midSizeImage("/path/to/Component.qml", "extraId1"); } -TEST_F(SynchronousImageCache, GetSmallImageFromStorage) +TEST_F(SynchronousImageCache, get_small_image_from_storage) { auto image = cache.smallImage("/path/to/Component.qml"); ASSERT_THAT(image, smallImage1); } -TEST_F(SynchronousImageCache, GetSmallImageWithExtraIdFromStorage) +TEST_F(SynchronousImageCache, get_small_image_with_extra_id_from_storage) { auto image = cache.smallImage("/path/to/Component.qml", "extraId1"); ASSERT_THAT(image, smallImage2); } -TEST_F(SynchronousImageCache, GetSmallImageWithOutdatedTimeStampFromCollector) +TEST_F(SynchronousImageCache, get_small_image_with_outdated_time_stamp_from_collector) { ON_CALL(mockTimeStampProvider, timeStamp(Eq("/path/to/Component.qml"))) .WillByDefault(Return(Sqlite::TimeStamp{124})); @@ -173,7 +173,7 @@ TEST_F(SynchronousImageCache, GetSmallImageWithOutdatedTimeStampFromCollector) ASSERT_THAT(image, smallImage3); } -TEST_F(SynchronousImageCache, GetSmallImageWithOutdatedTimeStampStored) +TEST_F(SynchronousImageCache, get_small_image_with_outdated_time_stamp_stored) { ON_CALL(mockTimeStampProvider, timeStamp(Eq("/path/to/Component.qml"))) .WillByDefault(Return(Sqlite::TimeStamp{124})); @@ -188,21 +188,21 @@ TEST_F(SynchronousImageCache, GetSmallImageWithOutdatedTimeStampStored) auto image = cache.smallImage("/path/to/Component.qml", "extraId1"); } -TEST_F(SynchronousImageCache, GetIconFromStorage) +TEST_F(SynchronousImageCache, get_icon_from_storage) { auto icon = cache.icon("/path/to/Component.qml"); ASSERT_THAT(icon, IsIcon(icon1)); } -TEST_F(SynchronousImageCache, GetIconWithExtraIdFromStorage) +TEST_F(SynchronousImageCache, get_icon_with_extra_id_from_storage) { auto icon = cache.icon("/path/to/Component.qml", "extraId1"); ASSERT_THAT(icon, IsIcon(icon2)); } -TEST_F(SynchronousImageCache, GetIconWithOutdatedTimeStampFromCollector) +TEST_F(SynchronousImageCache, get_icon_with_outdated_time_stamp_from_collector) { ON_CALL(mockTimeStampProvider, timeStamp(Eq("/path/to/Component.qml"))) .WillByDefault(Return(Sqlite::TimeStamp{124})); @@ -212,7 +212,7 @@ TEST_F(SynchronousImageCache, GetIconWithOutdatedTimeStampFromCollector) ASSERT_THAT(icon, IsIcon(icon3)); } -TEST_F(SynchronousImageCache, GetIconWithOutdatedTimeStampStored) +TEST_F(SynchronousImageCache, get_icon_with_outdated_time_stamp_stored) { using QmlDesigner::ImageCache::FontCollectorSizesAuxiliaryData; std::vector sizes{{20, 11}}; @@ -229,7 +229,7 @@ TEST_F(SynchronousImageCache, GetIconWithOutdatedTimeStampStored) FontCollectorSizesAuxiliaryData{sizes, "color", "text"}); } -TEST_F(SynchronousImageCache, IconCallsCollectorWithAuxiliaryData) +TEST_F(SynchronousImageCache, icon_calls_collector_with_auxiliary_data) { using QmlDesigner::ImageCache::FontCollectorSizesAuxiliaryData; std::vector sizes{{20, 11}}; @@ -250,7 +250,7 @@ TEST_F(SynchronousImageCache, IconCallsCollectorWithAuxiliaryData) FontCollectorSizesAuxiliaryData{sizes, "color", "text"}); } -TEST_F(SynchronousImageCache, ImageCallsCollectorWithAuxiliaryData) +TEST_F(SynchronousImageCache, image_calls_collector_with_auxiliary_data) { using QmlDesigner::ImageCache::FontCollectorSizesAuxiliaryData; std::vector sizes{{20, 11}}; @@ -271,7 +271,7 @@ TEST_F(SynchronousImageCache, ImageCallsCollectorWithAuxiliaryData) FontCollectorSizesAuxiliaryData{sizes, "color", "text"}); } -TEST_F(SynchronousImageCache, SmallImageCallsCollectorWithAuxiliaryData) +TEST_F(SynchronousImageCache, small_image_calls_collector_with_auxiliary_data) { using QmlDesigner::ImageCache::FontCollectorSizesAuxiliaryData; std::vector sizes{{20, 11}}; diff --git a/tests/unit/tests/unittests/listmodeleditor/CMakeLists.txt b/tests/unit/tests/unittests/listmodeleditor/CMakeLists.txt new file mode 100644 index 00000000000..639a6fca290 --- /dev/null +++ b/tests/unit/tests/unittests/listmodeleditor/CMakeLists.txt @@ -0,0 +1,18 @@ +# qmldesigner/designercore/listmodeleditor +extend_qtc_test(unittest + SOURCES + listmodeleditor-test.cpp +) +extend_qtc_test(unittest + SOURCES_PREFIX + "${QmlDesignerDir}" + SOURCES + components/listmodeleditor/listmodeleditormodel.cpp components/listmodeleditor/listmodeleditormodel.h +) + +extend_qtc_test(unittest + SOURCES + ${QtCreatorLibsDir}/qmlpuppetcommunication/interfaces/commondefines.h + ${QmlDesignerDir}/components/listmodeleditor/listmodeleditormodel.cpp + ${QmlDesignerDir}/components/listmodeleditor/listmodeleditormodel.h +) diff --git a/tests/unit/unittest/listmodeleditor-test.cpp b/tests/unit/tests/unittests/listmodeleditor/listmodeleditor-test.cpp similarity index 87% rename from tests/unit/unittest/listmodeleditor-test.cpp rename to tests/unit/tests/unittests/listmodeleditor/listmodeleditor-test.cpp index 8a5e09dc168..97799690c3b 100644 --- a/tests/unit/unittest/listmodeleditor-test.cpp +++ b/tests/unit/tests/unittests/listmodeleditor/listmodeleditor-test.cpp @@ -1,10 +1,10 @@ // Copyright (C) 2020 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" -#include "mocklistmodeleditorview.h" -#include "projectstoragemock.h" +#include "../mocks/mocklistmodeleditorview.h" +#include "../mocks/projectstoragemock.h" #include #include @@ -149,8 +149,7 @@ public: for (int columnIndex = 0; columnIndex < model.columnCount(); ++columnIndex) row.push_back( - model.data(model.index(rowIndex, columnIndex), Qt::BackgroundRole) - .value()); + model.data(model.index(rowIndex, columnIndex), Qt::BackgroundRole).value()); rows.push_back(row); } @@ -200,35 +199,35 @@ protected: ModelNode componentElement; }; -TEST_F(ListModelEditor, CreatePropertyNameSet) +TEST_F(ListModelEditor, create_property_name_set) { model.setListModel(listModelNode); ASSERT_THAT(model.propertyNames(), ElementsAre("image", "name", "value", "value2")); } -TEST_F(ListModelEditor, CreatePropertyNameSetForEmptyList) +TEST_F(ListModelEditor, create_property_name_set_for_empty_list) { model.setListModel(emptyListModelNode); ASSERT_THAT(model.propertyNames(), IsEmpty()); } -TEST_F(ListModelEditor, HorizontalLabels) +TEST_F(ListModelEditor, horizontal_labels) { model.setListModel(listModelNode); ASSERT_THAT(headerLabels(model), ElementsAre(u"image", u"name", u"value", u"value2")); } -TEST_F(ListModelEditor, HorizontalLabelsForEmptyList) +TEST_F(ListModelEditor, horizontal_labels_for_empty_list) { model.setListModel(emptyListModelNode); ASSERT_THAT(headerLabels(model), IsEmpty()); } -TEST_F(ListModelEditor, DisplayValues) +TEST_F(ListModelEditor, display_values) { model.setListModel(listModelNode); @@ -238,7 +237,7 @@ TEST_F(ListModelEditor, DisplayValues) ElementsAre("pic.png", "poo", 111, IsInvalid()))); } -TEST_F(ListModelEditor, ChangeValueChangesDisplayValues) +TEST_F(ListModelEditor, change_value_changes_display_values) { model.setListModel(listModelNode); @@ -250,7 +249,7 @@ TEST_F(ListModelEditor, ChangeValueChangesDisplayValues) ElementsAre("pic.png", "poo", 111, IsInvalid()))); } -TEST_F(ListModelEditor, EditValueCallVariantPropertiesChanged) +TEST_F(ListModelEditor, edit_value_call_variant_properties_changed) { model.setListModel(listModelNode); @@ -261,7 +260,7 @@ TEST_F(ListModelEditor, EditValueCallVariantPropertiesChanged) model.setValue(0, 1, "hello"); } -TEST_F(ListModelEditor, ChangeDisplayValueCallsVariantPropertiesChanged) +TEST_F(ListModelEditor, change_display_value_calls_variant_properties_changed) { model.setListModel(listModelNode); @@ -273,7 +272,7 @@ TEST_F(ListModelEditor, ChangeDisplayValueCallsVariantPropertiesChanged) model.setValue(0, 1, "hello", Qt::DisplayRole); } -TEST_F(ListModelEditor, AddRowAddedInvalidRow) +TEST_F(ListModelEditor, add_row_added_invalid_row) { model.setListModel(listModelNode); @@ -286,7 +285,7 @@ TEST_F(ListModelEditor, AddRowAddedInvalidRow) ElementsAre(IsInvalid(), IsInvalid(), IsInvalid(), IsInvalid()))); } -TEST_F(ListModelEditor, AddRowCreatesNewModelNodeAndReparents) +TEST_F(ListModelEditor, add_row_creates_new_model_node_and_reparents) { model.setListModel(listModelNode); @@ -300,7 +299,7 @@ TEST_F(ListModelEditor, AddRowCreatesNewModelNodeAndReparents) model.addRow(); } -TEST_F(ListModelEditor, ChangeAddedRowPropery) +TEST_F(ListModelEditor, change_added_row_propery) { model.setListModel(listModelNode); model.addRow(); @@ -314,7 +313,7 @@ TEST_F(ListModelEditor, ChangeAddedRowPropery) ElementsAre(IsInvalid(), IsInvalid(), 22, IsInvalid()))); } -TEST_F(ListModelEditor, ChangeAddedRowProperyCallsVariantPropertiesChanged) +TEST_F(ListModelEditor, change_added_row_propery_calls_variant_properties_changed) { model.setListModel(listModelNode); ModelNode element4; @@ -328,7 +327,7 @@ TEST_F(ListModelEditor, ChangeAddedRowProperyCallsVariantPropertiesChanged) model.setValue(3, 2, 22); } -TEST_F(ListModelEditor, AddColumnInsertsPropertyName) +TEST_F(ListModelEditor, add_column_inserts_property_name) { model.setListModel(listModelNode); @@ -337,7 +336,7 @@ TEST_F(ListModelEditor, AddColumnInsertsPropertyName) ASSERT_THAT(model.propertyNames(), ElementsAre("image", "name", "other", "value", "value2")); } -TEST_F(ListModelEditor, AddColumnInsertsPropertyNameToEmptyModel) +TEST_F(ListModelEditor, add_column_inserts_property_name_to_empty_model) { model.setListModel(emptyListModelNode); @@ -346,7 +345,7 @@ TEST_F(ListModelEditor, AddColumnInsertsPropertyNameToEmptyModel) ASSERT_THAT(model.propertyNames(), ElementsAre("foo")); } -TEST_F(ListModelEditor, AddTwiceColumnInsertsPropertyNameToEmptyModel) +TEST_F(ListModelEditor, add_twice_column_inserts_property_name_to_empty_model) { model.setListModel(emptyListModelNode); model.addColumn("foo"); @@ -356,7 +355,7 @@ TEST_F(ListModelEditor, AddTwiceColumnInsertsPropertyNameToEmptyModel) ASSERT_THAT(model.propertyNames(), ElementsAre("foo", "foo2")); } -TEST_F(ListModelEditor, AddSameColumnInsertsPropertyName) +TEST_F(ListModelEditor, add_same_column_inserts_property_name) { model.setListModel(emptyListModelNode); model.addColumn("foo"); @@ -366,7 +365,7 @@ TEST_F(ListModelEditor, AddSameColumnInsertsPropertyName) ASSERT_THAT(model.propertyNames(), ElementsAre("foo")); } -TEST_F(ListModelEditor, AddColumnInsertsHeaderLabel) +TEST_F(ListModelEditor, add_column_inserts_header_label) { model.setListModel(listModelNode); @@ -375,7 +374,7 @@ TEST_F(ListModelEditor, AddColumnInsertsHeaderLabel) ASSERT_THAT(headerLabels(model), ElementsAre(u"image", u"name", u"other", u"value", u"value2")); } -TEST_F(ListModelEditor, AddColumnInsertsHeaderLabelToEmptyModel) +TEST_F(ListModelEditor, add_column_inserts_header_label_to_empty_model) { model.setListModel(emptyListModelNode); @@ -384,7 +383,7 @@ TEST_F(ListModelEditor, AddColumnInsertsHeaderLabelToEmptyModel) ASSERT_THAT(headerLabels(model), ElementsAre(u"foo")); } -TEST_F(ListModelEditor, AddTwiceColumnInsertsHeaderLabelToEmptyModel) +TEST_F(ListModelEditor, add_twice_column_inserts_header_label_to_empty_model) { model.setListModel(emptyListModelNode); model.addColumn("foo"); @@ -394,7 +393,7 @@ TEST_F(ListModelEditor, AddTwiceColumnInsertsHeaderLabelToEmptyModel) ASSERT_THAT(headerLabels(model), ElementsAre(u"foo", u"foo2")); } -TEST_F(ListModelEditor, AddSameColumnInsertsHeaderLabel) +TEST_F(ListModelEditor, add_same_column_inserts_header_label) { model.setListModel(emptyListModelNode); model.addColumn("foo"); @@ -404,7 +403,7 @@ TEST_F(ListModelEditor, AddSameColumnInsertsHeaderLabel) ASSERT_THAT(headerLabels(model), ElementsAre(u"foo")); } -TEST_F(ListModelEditor, AddColumnInsertsDisplayValues) +TEST_F(ListModelEditor, add_column_inserts_display_values) { model.setListModel(listModelNode); @@ -416,7 +415,7 @@ TEST_F(ListModelEditor, AddColumnInsertsDisplayValues) ElementsAre("pic.png", "poo", IsInvalid(), 111, IsInvalid()))); } -TEST_F(ListModelEditor, ChangeAddColumnPropertyDisplayValue) +TEST_F(ListModelEditor, change_add_column_property_display_value) { model.setListModel(listModelNode); model.addColumn("other"); @@ -429,7 +428,7 @@ TEST_F(ListModelEditor, ChangeAddColumnPropertyDisplayValue) ElementsAre("pic.png", "poo", IsInvalid(), 111, IsInvalid()))); } -TEST_F(ListModelEditor, ChangeAddColumnPropertyCallsVariantPropertiesChanged) +TEST_F(ListModelEditor, change_add_column_property_calls_variant_properties_changed) { model.setListModel(listModelNode); model.addColumn("other"); @@ -440,7 +439,7 @@ TEST_F(ListModelEditor, ChangeAddColumnPropertyCallsVariantPropertiesChanged) model.setValue(1, 2, 434); } -TEST_F(ListModelEditor, RemoveColumnRemovesDisplayValues) +TEST_F(ListModelEditor, remove_column_removes_display_values) { model.setListModel(listModelNode); @@ -452,7 +451,7 @@ TEST_F(ListModelEditor, RemoveColumnRemovesDisplayValues) ElementsAre("pic.png", "poo", IsInvalid()))); } -TEST_F(ListModelEditor, RemoveColumnRemovesProperties) +TEST_F(ListModelEditor, remove_column_removes_properties) { model.setListModel(listModelNode); @@ -462,7 +461,7 @@ TEST_F(ListModelEditor, RemoveColumnRemovesProperties) model.removeColumns({index(0, 0)}); } -TEST_F(ListModelEditor, RemoveColumnRemovesPropertyName) +TEST_F(ListModelEditor, remove_column_removes_property_name) { model.setListModel(listModelNode); @@ -471,7 +470,7 @@ TEST_F(ListModelEditor, RemoveColumnRemovesPropertyName) ASSERT_THAT(model.propertyNames(), ElementsAre("image", "value", "value2")); } -TEST_F(ListModelEditor, RemoveRowRemovesDisplayValues) +TEST_F(ListModelEditor, remove_row_removes_display_values) { model.setListModel(listModelNode); @@ -482,7 +481,7 @@ TEST_F(ListModelEditor, RemoveRowRemovesDisplayValues) ElementsAre("pic.png", "poo", 111, IsInvalid()))); } -TEST_F(ListModelEditor, RemoveRowRemovesElementInListModel) +TEST_F(ListModelEditor, remove_row_removes_element_in_list_model) { model.setListModel(listModelNode); @@ -491,7 +490,7 @@ TEST_F(ListModelEditor, RemoveRowRemovesElementInListModel) model.removeRows({index(1, 0)}); } -TEST_F(ListModelEditor, ConvertStringFloatToFloat) +TEST_F(ListModelEditor, convert_string_float_to_float) { model.setListModel(listModelNode); @@ -501,7 +500,7 @@ TEST_F(ListModelEditor, ConvertStringFloatToFloat) ASSERT_THAT(element2.variantProperty("name").value().type(), QVariant::Double); } -TEST_F(ListModelEditor, ConvertStringIntegerToDouble) +TEST_F(ListModelEditor, convert_string_integer_to_double) { model.setListModel(listModelNode); @@ -511,7 +510,7 @@ TEST_F(ListModelEditor, ConvertStringIntegerToDouble) ASSERT_THAT(element2.variantProperty("name").value().type(), QVariant::Double); } -TEST_F(ListModelEditor, DontConvertStringToNumber) +TEST_F(ListModelEditor, dont_convert_string_to_number) { model.setListModel(listModelNode); @@ -521,7 +520,7 @@ TEST_F(ListModelEditor, DontConvertStringToNumber) ASSERT_THAT(element2.variantProperty("name").value().type(), QVariant::String); } -TEST_F(ListModelEditor, EmptyStringsRemovesProperty) +TEST_F(ListModelEditor, empty_strings_removes_property) { model.setListModel(listModelNode); @@ -530,7 +529,7 @@ TEST_F(ListModelEditor, EmptyStringsRemovesProperty) ASSERT_THAT(element2.variantProperty("name").value().value(), Eq(u"")); } -TEST_F(ListModelEditor, InvalidVariantRemovesProperty) +TEST_F(ListModelEditor, invalid_variant_removes_property) { model.setListModel(listModelNode); @@ -539,7 +538,7 @@ TEST_F(ListModelEditor, InvalidVariantRemovesProperty) ASSERT_FALSE(element2.hasProperty("name")); } -TEST_F(ListModelEditor, DispayValueIsChangedToDouble) +TEST_F(ListModelEditor, dispay_value_is_changed_to_double) { model.setListModel(listModelNode); @@ -548,7 +547,7 @@ TEST_F(ListModelEditor, DispayValueIsChangedToDouble) ASSERT_THAT(displayValues()[1][1].type(), QVariant::Double); } -TEST_F(ListModelEditor, StringDispayValueIsNotChanged) +TEST_F(ListModelEditor, string_dispay_value_is_not_changed) { model.setListModel(listModelNode); @@ -557,7 +556,7 @@ TEST_F(ListModelEditor, StringDispayValueIsNotChanged) ASSERT_THAT(displayValues()[1][1].type(), QVariant::String); } -TEST_F(ListModelEditor, SetInvalidToDarkYellowBackgroundColor) +TEST_F(ListModelEditor, set_invalid_to_dark_yellow_background_color) { model.setListModel(listModelNode); @@ -569,7 +568,7 @@ TEST_F(ListModelEditor, SetInvalidToDarkYellowBackgroundColor) ElementsAre(Not(Qt::darkYellow), Not(Qt::darkYellow), Not(Qt::darkYellow), Qt::darkYellow))); } -TEST_F(ListModelEditor, SettingValueChangesBackgroundColor) +TEST_F(ListModelEditor, setting_value_changes_background_color) { model.setListModel(listModelNode); @@ -583,7 +582,7 @@ TEST_F(ListModelEditor, SettingValueChangesBackgroundColor) ElementsAre(Not(Qt::darkYellow), Not(Qt::darkYellow), Not(Qt::darkYellow), Qt::darkYellow))); } -TEST_F(ListModelEditor, SettingValueChangesByDisplayRoleBackgroundColor) +TEST_F(ListModelEditor, setting_value_changes_by_display_role_background_color) { model.setListModel(listModelNode); @@ -597,7 +596,7 @@ TEST_F(ListModelEditor, SettingValueChangesByDisplayRoleBackgroundColor) ElementsAre(Not(Qt::darkYellow), Not(Qt::darkYellow), Not(Qt::darkYellow), Qt::darkYellow))); } -TEST_F(ListModelEditor, ResettingValueChangesBackgroundColor) +TEST_F(ListModelEditor, resetting_value_changes_background_color) { model.setListModel(listModelNode); @@ -611,7 +610,7 @@ TEST_F(ListModelEditor, ResettingValueChangesBackgroundColor) ElementsAre(Not(Qt::darkYellow), Not(Qt::darkYellow), Not(Qt::darkYellow), Qt::darkYellow))); } -TEST_F(ListModelEditor, ResettingValueChangesByDisplayRoleBackgroundColor) +TEST_F(ListModelEditor, resetting_value_changes_by_display_role_background_color) { model.setListModel(listModelNode); @@ -625,7 +624,7 @@ TEST_F(ListModelEditor, ResettingValueChangesByDisplayRoleBackgroundColor) ElementsAre(Not(Qt::darkYellow), Not(Qt::darkYellow), Not(Qt::darkYellow), Qt::darkYellow))); } -TEST_F(ListModelEditor, SettingNullValueChangesBackgroundColor) +TEST_F(ListModelEditor, setting_null_value_changes_background_color) { model.setListModel(listModelNode); @@ -637,7 +636,7 @@ TEST_F(ListModelEditor, SettingNullValueChangesBackgroundColor) ElementsAre(_, _, _, Qt::darkYellow))); } -TEST_F(ListModelEditor, DontRenamePropertyIfColumnNameExists) +TEST_F(ListModelEditor, dont_rename_property_if_column_name_exists) { model.setListModel(listModelNode); @@ -646,7 +645,7 @@ TEST_F(ListModelEditor, DontRenamePropertyIfColumnNameExists) ASSERT_THAT(model.propertyNames(), ElementsAre("image", "name", "value", "value2")); } -TEST_F(ListModelEditor, DontRenameColumnIfColumnNameExists) +TEST_F(ListModelEditor, dont_rename_column_if_column_name_exists) { model.setListModel(listModelNode); @@ -655,7 +654,7 @@ TEST_F(ListModelEditor, DontRenameColumnIfColumnNameExists) ASSERT_THAT(headerLabels(model), ElementsAre(u"image", u"name", u"value", u"value2")); } -TEST_F(ListModelEditor, DontRenameColumnIfColumnNameExistsDoesNotChangeDisplayValues) +TEST_F(ListModelEditor, dont_rename_column_if_column_name_exists_does_not_change_display_values) { model.setListModel(listModelNode); @@ -667,7 +666,7 @@ TEST_F(ListModelEditor, DontRenameColumnIfColumnNameExistsDoesNotChangeDisplayVa ElementsAre("pic.png", "poo", 111, IsInvalid()))); } -TEST_F(ListModelEditor, DontRenameColumnIfColumnNameExistsDoesNotChangeProperties) +TEST_F(ListModelEditor, dont_rename_column_if_column_name_exists_does_not_change_properties) { model.setListModel(listModelNode); @@ -685,7 +684,7 @@ TEST_F(ListModelEditor, DontRenameColumnIfColumnNameExistsDoesNotChangePropertie IsVariantProperty("value", 111)))); } -TEST_F(ListModelEditor, RenamePropertyButDontChangeOrder) +TEST_F(ListModelEditor, rename_property_but_dont_change_order) { model.setListModel(listModelNode); @@ -694,7 +693,7 @@ TEST_F(ListModelEditor, RenamePropertyButDontChangeOrder) ASSERT_THAT(model.propertyNames(), ElementsAre("image", "mood", "value", "value2")); } -TEST_F(ListModelEditor, RenameColumnButDontChangeOrder) +TEST_F(ListModelEditor, rename_column_but_dont_change_order) { model.setListModel(listModelNode); @@ -703,7 +702,7 @@ TEST_F(ListModelEditor, RenameColumnButDontChangeOrder) ASSERT_THAT(headerLabels(model), ElementsAre(u"image", u"mood", u"value", u"value2")); } -TEST_F(ListModelEditor, RenameColumnButDontChangeOrderDisplayValues) +TEST_F(ListModelEditor, rename_column_but_dont_change_order_display_values) { model.setListModel(listModelNode); @@ -715,7 +714,7 @@ TEST_F(ListModelEditor, RenameColumnButDontChangeOrderDisplayValues) ElementsAre("pic.png", "poo", 111, IsInvalid()))); } -TEST_F(ListModelEditor, RenameColumnButDontChangeOrderProperies) +TEST_F(ListModelEditor, rename_column_but_dont_change_order_properies) { model.setListModel(listModelNode); @@ -733,7 +732,7 @@ TEST_F(ListModelEditor, RenameColumnButDontChangeOrderProperies) IsVariantProperty("value", 111)))); } -TEST_F(ListModelEditor, RemoveColumnAfterRenameColumn) +TEST_F(ListModelEditor, remove_column_after_rename_column) { model.setListModel(listModelNode); model.renameColumn(1, "mood"); @@ -749,7 +748,7 @@ TEST_F(ListModelEditor, RemoveColumnAfterRenameColumn) IsVariantProperty("value", 111)))); } -TEST_F(ListModelEditor, ChangeValueAfterRenameColumn) +TEST_F(ListModelEditor, change_value_after_rename_column) { model.setListModel(listModelNode); model.renameColumn(1, "mood"); @@ -768,7 +767,7 @@ TEST_F(ListModelEditor, ChangeValueAfterRenameColumn) IsVariantProperty("value", 111)))); } -TEST_F(ListModelEditor, RemovePropertyAfterRenameColumn) +TEST_F(ListModelEditor, remove_property_after_rename_column) { model.setListModel(listModelNode); model.renameColumn(1, "mood"); @@ -786,7 +785,7 @@ TEST_F(ListModelEditor, RemovePropertyAfterRenameColumn) IsVariantProperty("value", 111)))); } -TEST_F(ListModelEditor, RenameToPrecedingProperty) +TEST_F(ListModelEditor, rename_to_preceding_property) { model.setListModel(listModelNode); @@ -795,7 +794,7 @@ TEST_F(ListModelEditor, RenameToPrecedingProperty) ASSERT_THAT(model.propertyNames(), ElementsAre("alpha", "image", "value", "value2")); } -TEST_F(ListModelEditor, RenameToPrecedingColumn) +TEST_F(ListModelEditor, rename_to_preceding_column) { model.setListModel(listModelNode); @@ -804,7 +803,7 @@ TEST_F(ListModelEditor, RenameToPrecedingColumn) ASSERT_THAT(headerLabels(model), ElementsAre(u"alpha", u"image", u"value", u"value2")); } -TEST_F(ListModelEditor, RenameToPrecedingColumnDisplayValues) +TEST_F(ListModelEditor, rename_to_preceding_column_display_values) { model.setListModel(listModelNode); @@ -816,7 +815,7 @@ TEST_F(ListModelEditor, RenameToPrecedingColumnDisplayValues) ElementsAre("poo", "pic.png", 111, IsInvalid()))); } -TEST_F(ListModelEditor, RenameToPrecedingColumnProperties) +TEST_F(ListModelEditor, rename_to_preceding_column_properties) { model.setListModel(listModelNode); @@ -834,7 +833,7 @@ TEST_F(ListModelEditor, RenameToPrecedingColumnProperties) IsVariantProperty("value", 111)))); } -TEST_F(ListModelEditor, RenameToFollowingProperty) +TEST_F(ListModelEditor, rename_to_following_property) { model.setListModel(listModelNode); @@ -843,7 +842,7 @@ TEST_F(ListModelEditor, RenameToFollowingProperty) ASSERT_THAT(model.propertyNames(), ElementsAre("image", "name", "value2", "zoo")); } -TEST_F(ListModelEditor, RenameToFollowingColumn) +TEST_F(ListModelEditor, rename_to_following_column) { model.setListModel(listModelNode); @@ -852,7 +851,7 @@ TEST_F(ListModelEditor, RenameToFollowingColumn) ASSERT_THAT(headerLabels(model), ElementsAre(u"image", u"name", u"value2", u"zoo")); } -TEST_F(ListModelEditor, RenameToFollowingColumnDisplayValues) +TEST_F(ListModelEditor, rename_to_following_column_display_values) { model.setListModel(listModelNode); @@ -864,7 +863,7 @@ TEST_F(ListModelEditor, RenameToFollowingColumnDisplayValues) ElementsAre("pic.png", "poo", IsInvalid(), 111))); } -TEST_F(ListModelEditor, RenameToFollowingColumnProperties) +TEST_F(ListModelEditor, rename_to_following_column_properties) { model.setListModel(listModelNode); @@ -882,7 +881,7 @@ TEST_F(ListModelEditor, RenameToFollowingColumnProperties) IsVariantProperty("zoo", 111)))); } -TEST_F(ListModelEditor, RenamePropertiesWithInvalidValue) +TEST_F(ListModelEditor, rename_properties_with_invalid_value) { model.setListModel(listModelNode); @@ -900,7 +899,7 @@ TEST_F(ListModelEditor, RenamePropertiesWithInvalidValue) IsVariantProperty("value", 111)))); } -TEST_F(ListModelEditor, ChangeValueAfterRenamePropertiesWithInvalidValue) +TEST_F(ListModelEditor, change_value_after_rename_properties_with_invalid_value) { model.setListModel(listModelNode); model.renameColumn(0, "mood"); @@ -920,7 +919,7 @@ TEST_F(ListModelEditor, ChangeValueAfterRenamePropertiesWithInvalidValue) IsVariantProperty("value", 111)))); } -TEST_F(ListModelEditor, RemoveLastRow) +TEST_F(ListModelEditor, remove_last_row) { model.setListModel(emptyListModelNode); model.addColumn("mood"); @@ -931,7 +930,7 @@ TEST_F(ListModelEditor, RemoveLastRow) ASSERT_THAT(displayValues(), IsEmpty()); } -TEST_F(ListModelEditor, RemoveLastEmptyRow) +TEST_F(ListModelEditor, remove_last_empty_row) { model.setListModel(emptyListModelNode); model.addColumn("mood"); @@ -943,7 +942,7 @@ TEST_F(ListModelEditor, RemoveLastEmptyRow) ASSERT_THAT(displayValues(), ElementsAre(IsEmpty())); } -TEST_F(ListModelEditor, RemoveLastColumn) +TEST_F(ListModelEditor, remove_last_column) { model.setListModel(emptyListModelNode); model.addColumn("mood"); @@ -954,7 +953,7 @@ TEST_F(ListModelEditor, RemoveLastColumn) ASSERT_THAT(displayValues(), ElementsAre(IsEmpty())); } -TEST_F(ListModelEditor, RemoveLastEmptyColumn) +TEST_F(ListModelEditor, remove_last_empty_column) { model.setListModel(emptyListModelNode); model.addColumn("mood"); @@ -966,7 +965,7 @@ TEST_F(ListModelEditor, RemoveLastEmptyColumn) ASSERT_THAT(displayValues(), IsEmpty()); } -TEST_F(ListModelEditor, RemoveColumns) +TEST_F(ListModelEditor, remove_columns) { model.setListModel(listModelNode); model.removeColumns({index(0, 1), index(0, 3), index(1, 1), index(0, 4)}); @@ -979,7 +978,7 @@ TEST_F(ListModelEditor, RemoveColumns) IsVariantProperty("value", 111)))); } -TEST_F(ListModelEditor, RemoveRows) +TEST_F(ListModelEditor, remove_rows) { model.setListModel(listModelNode); @@ -991,7 +990,7 @@ TEST_F(ListModelEditor, RemoveRows) IsVariantProperty("value2", 42)))); } -TEST_F(ListModelEditor, FilterColumns) +TEST_F(ListModelEditor, filter_columns) { model.setListModel(listModelNode); QList indices = {index(0, 0), index(1, 1), index(0, 2), index(0, 1)}; @@ -1001,7 +1000,7 @@ TEST_F(ListModelEditor, FilterColumns) ASSERT_THAT(columns, ElementsAre(0, 1, 2)); } -TEST_F(ListModelEditor, FilterColumnsInvalidColumns) +TEST_F(ListModelEditor, filter_columns_invalid_columns) { QList indices = {index(0, 0), index(1, 1), index(0, 2), index(0, 1)}; @@ -1010,7 +1009,7 @@ TEST_F(ListModelEditor, FilterColumnsInvalidColumns) ASSERT_THAT(columns, IsEmpty()); } -TEST_F(ListModelEditor, FilterColumnsEmptyInput) +TEST_F(ListModelEditor, filter_columns_empty_input) { QList indices; @@ -1019,7 +1018,7 @@ TEST_F(ListModelEditor, FilterColumnsEmptyInput) ASSERT_THAT(columns, IsEmpty()); } -TEST_F(ListModelEditor, FilterRows) +TEST_F(ListModelEditor, filter_rows) { model.setListModel(listModelNode); QList indices = {index(0, 0), index(1, 1), index(2, 2), index(0, 1)}; @@ -1029,7 +1028,7 @@ TEST_F(ListModelEditor, FilterRows) ASSERT_THAT(rows, ElementsAre(0, 1, 2)); } -TEST_F(ListModelEditor, FilterRowsInvalidColumns) +TEST_F(ListModelEditor, filter_rows_invalid_columns) { QList indices = {index(0, 0), index(1, 1), index(2, 2), index(0, 1)}; @@ -1038,7 +1037,7 @@ TEST_F(ListModelEditor, FilterRowsInvalidColumns) ASSERT_THAT(rows, IsEmpty()); } -TEST_F(ListModelEditor, FilterRowsEmptyInput) +TEST_F(ListModelEditor, filter_rows_empty_input) { QList indices; @@ -1047,7 +1046,7 @@ TEST_F(ListModelEditor, FilterRowsEmptyInput) ASSERT_THAT(rows, IsEmpty()); } -TEST_F(ListModelEditor, CannotMoveEmptyRowsUp) +TEST_F(ListModelEditor, cannot_move_empty_rows_up) { model.setListModel(listModelNode); QList indices = {index(-1, 1)}; @@ -1057,7 +1056,7 @@ TEST_F(ListModelEditor, CannotMoveEmptyRowsUp) ASSERT_THAT(elements(listModelNode), ElementsAre(element1, element2, element3)); } -TEST_F(ListModelEditor, MoveRowUp) +TEST_F(ListModelEditor, move_row_up) { model.setListModel(listModelNode); QList indices = {index(1, 1), index(1, 2), index(1, 0)}; @@ -1067,7 +1066,7 @@ TEST_F(ListModelEditor, MoveRowUp) ASSERT_THAT(elements(listModelNode), ElementsAre(element2, element1, element3)); } -TEST_F(ListModelEditor, MoveRowsUp) +TEST_F(ListModelEditor, move_rows_up) { model.setListModel(listModelNode); QList indices = {index(1, 1), index(2, 2), index(1, 0)}; @@ -1077,7 +1076,7 @@ TEST_F(ListModelEditor, MoveRowsUp) ASSERT_THAT(elements(listModelNode), ElementsAre(element2, element3, element1)); } -TEST_F(ListModelEditor, CannotMoveFirstRowsUp) +TEST_F(ListModelEditor, cannot_move_first_rows_up) { model.setListModel(listModelNode); QList indices = {index(0, 1), index(1, 2), index(0, 0)}; @@ -1087,7 +1086,7 @@ TEST_F(ListModelEditor, CannotMoveFirstRowsUp) ASSERT_THAT(elements(listModelNode), ElementsAre(element1, element2, element3)); } -TEST_F(ListModelEditor, CannotMoveEmptyRowsUpDisplayValues) +TEST_F(ListModelEditor, cannot_move_empty_rows_up_display_values) { model.setListModel(listModelNode); QList indices = {index(-1, 1)}; @@ -1100,7 +1099,7 @@ TEST_F(ListModelEditor, CannotMoveEmptyRowsUpDisplayValues) ElementsAre("pic.png", "poo", 111, IsInvalid()))); } -TEST_F(ListModelEditor, CannotMoveFirstRowUpDisplayValues) +TEST_F(ListModelEditor, cannot_move_first_row_up_display_values) { model.setListModel(listModelNode); QList indices = {index(0, 1), index(1, 2), index(0, 0)}; @@ -1113,7 +1112,7 @@ TEST_F(ListModelEditor, CannotMoveFirstRowUpDisplayValues) ElementsAre("pic.png", "poo", 111, IsInvalid()))); } -TEST_F(ListModelEditor, MoveRowsUpDisplayValues) +TEST_F(ListModelEditor, move_rows_up_display_values) { model.setListModel(listModelNode); QList indices = {index(1, 1), index(2, 2), index(1, 0)}; @@ -1126,7 +1125,7 @@ TEST_F(ListModelEditor, MoveRowsUpDisplayValues) ElementsAre(IsInvalid(), "foo", 1, 42))); } -TEST_F(ListModelEditor, NoSelectionAfterCannotMoveLastRowsDown) +TEST_F(ListModelEditor, no_selection_after_cannot_move_last_rows_down) { model.setListModel(listModelNode); QList indices = {index(0, 1), index(1, 2), index(0, 0)}; @@ -1136,7 +1135,7 @@ TEST_F(ListModelEditor, NoSelectionAfterCannotMoveLastRowsDown) ASSERT_THAT(selection.indexes(), IsEmpty()); } -TEST_F(ListModelEditor, NoSelectionAfterMoveEmptyRowsDown) +TEST_F(ListModelEditor, no_selection_after_move_empty_rows_down) { model.setListModel(listModelNode); QList indices = {index(-1, 1)}; @@ -1146,7 +1145,7 @@ TEST_F(ListModelEditor, NoSelectionAfterMoveEmptyRowsDown) ASSERT_THAT(selection.indexes(), IsEmpty()); } -TEST_F(ListModelEditor, SelectionAfterMoveRowsDown) +TEST_F(ListModelEditor, selection_after_move_rows_down) { model.setListModel(listModelNode); QList indices = {index(1, 1), index(2, 2), index(1, 0)}; @@ -1164,7 +1163,7 @@ TEST_F(ListModelEditor, SelectionAfterMoveRowsDown) index(1, 3))); } -TEST_F(ListModelEditor, CannotMoveEmptyRowsDown) +TEST_F(ListModelEditor, cannot_move_empty_rows_down) { model.setListModel(listModelNode); QList indices = {index(-1, 1)}; @@ -1174,7 +1173,7 @@ TEST_F(ListModelEditor, CannotMoveEmptyRowsDown) ASSERT_THAT(elements(listModelNode), ElementsAre(element1, element2, element3)); } -TEST_F(ListModelEditor, MoveRowDown) +TEST_F(ListModelEditor, move_row_down) { model.setListModel(listModelNode); QList indices = {index(1, 1), index(1, 2), index(1, 0)}; @@ -1184,7 +1183,7 @@ TEST_F(ListModelEditor, MoveRowDown) ASSERT_THAT(elements(listModelNode), ElementsAre(element1, element3, element2)); } -TEST_F(ListModelEditor, MoveRowsDown) +TEST_F(ListModelEditor, move_rows_down) { model.setListModel(listModelNode); QList indices = {index(1, 1), index(0, 2), index(1, 0)}; @@ -1194,7 +1193,7 @@ TEST_F(ListModelEditor, MoveRowsDown) ASSERT_THAT(elements(listModelNode), ElementsAre(element3, element1, element2)); } -TEST_F(ListModelEditor, CannotMoveLastRowsDown) +TEST_F(ListModelEditor, cannot_move_last_rows_down) { model.setListModel(listModelNode); QList indices = {index(2, 1), index(1, 2), index(2, 0)}; @@ -1204,7 +1203,7 @@ TEST_F(ListModelEditor, CannotMoveLastRowsDown) ASSERT_THAT(elements(listModelNode), ElementsAre(element1, element2, element3)); } -TEST_F(ListModelEditor, CannotMoveEmptyRowsDownDisplayValues) +TEST_F(ListModelEditor, cannot_move_empty_rows_down_display_values) { model.setListModel(listModelNode); QList indices = {index(-1, 1)}; @@ -1217,7 +1216,7 @@ TEST_F(ListModelEditor, CannotMoveEmptyRowsDownDisplayValues) ElementsAre("pic.png", "poo", 111, IsInvalid()))); } -TEST_F(ListModelEditor, CannotMoveLastRowDownDisplayValues) +TEST_F(ListModelEditor, cannot_move_last_row_down_display_values) { model.setListModel(listModelNode); QList indices = {index(2, 1), index(1, 2), index(2, 0)}; @@ -1230,7 +1229,7 @@ TEST_F(ListModelEditor, CannotMoveLastRowDownDisplayValues) ElementsAre("pic.png", "poo", 111, IsInvalid()))); } -TEST_F(ListModelEditor, MoveRowsDownDisplayValues) +TEST_F(ListModelEditor, move_rows_down_display_values) { model.setListModel(listModelNode); QList indices = {index(1, 1), index(0, 2), index(1, 0)}; @@ -1243,7 +1242,7 @@ TEST_F(ListModelEditor, MoveRowsDownDisplayValues) ElementsAre("pic.png", "bar", 4, IsInvalid()))); } -TEST_F(ListModelEditor, NoSelectionAfterCannotMoveLastRowsUp) +TEST_F(ListModelEditor, no_selection_after_cannot_move_last_rows_up) { model.setListModel(listModelNode); QList indices = {index(2, 1), index(1, 2), index(2, 0)}; @@ -1253,7 +1252,7 @@ TEST_F(ListModelEditor, NoSelectionAfterCannotMoveLastRowsUp) ASSERT_THAT(selection.indexes(), IsEmpty()); } -TEST_F(ListModelEditor, NoSelectionAfterMoveEmptyRowsUp) +TEST_F(ListModelEditor, no_selection_after_move_empty_rows_up) { model.setListModel(listModelNode); QList indices = {index(-1, 1)}; @@ -1263,7 +1262,7 @@ TEST_F(ListModelEditor, NoSelectionAfterMoveEmptyRowsUp) ASSERT_THAT(selection.indexes(), IsEmpty()); } -TEST_F(ListModelEditor, SelectionAfterMoveRowsUp) +TEST_F(ListModelEditor, selection_after_move_rows_up) { model.setListModel(listModelNode); QList indices = {index(1, 1), index(0, 2), index(1, 0)}; @@ -1281,14 +1280,14 @@ TEST_F(ListModelEditor, SelectionAfterMoveRowsUp) index(2, 3))); } -TEST_F(ListModelEditor, ListViewHasNoModel) +TEST_F(ListModelEditor, list_view_has_no_model) { model.setListView(listViewNode); ASSERT_THAT(listViewNode.nodeProperty("model").modelNode().type(), Eq("QtQml.Models.ListModel")); } -TEST_F(ListModelEditor, ListViewHasModelInside) +TEST_F(ListModelEditor, list_view_has_model_inside) { listViewNode.nodeProperty("model").reparentHere(listModelNode); @@ -1300,7 +1299,7 @@ TEST_F(ListModelEditor, ListViewHasModelInside) ElementsAre("pic.png", "poo", 111, IsInvalid()))); } -TEST_F(ListModelEditor, ListViewHasModelBinding) +TEST_F(ListModelEditor, list_view_has_model_binding) { listModelNode.setIdWithoutRefactoring("listModel"); listViewNode.bindingProperty("model").setExpression("listModel"); @@ -1313,7 +1312,7 @@ TEST_F(ListModelEditor, ListViewHasModelBinding) ElementsAre("pic.png", "poo", 111, IsInvalid()))); } -TEST_F(ListModelEditor, AddBooleanDisplayValues) +TEST_F(ListModelEditor, add_boolean_display_values) { model.setListModel(listModelNode); @@ -1325,7 +1324,7 @@ TEST_F(ListModelEditor, AddBooleanDisplayValues) ElementsAre("pic.png", "poo", 111, IsInvalid()))); } -TEST_F(ListModelEditor, AddBooleanProperties) +TEST_F(ListModelEditor, add_boolean_properties) { model.setListModel(listModelNode); @@ -1343,7 +1342,7 @@ TEST_F(ListModelEditor, AddBooleanProperties) IsVariantProperty("value", 111)))); } -TEST_F(ListModelEditor, AddTrueAsStringProperties) +TEST_F(ListModelEditor, add_true_as_string_properties) { model.setListModel(listModelNode); @@ -1361,7 +1360,7 @@ TEST_F(ListModelEditor, AddTrueAsStringProperties) IsVariantProperty("value", 111)))); } -TEST_F(ListModelEditor, AddFalseAsStringProperties) +TEST_F(ListModelEditor, add_false_as_string_properties) { model.setListModel(listModelNode); @@ -1379,7 +1378,7 @@ TEST_F(ListModelEditor, AddFalseAsStringProperties) IsVariantProperty("value", 111)))); } -TEST_F(ListModelEditor, GoIntoComponentForBinding) +TEST_F(ListModelEditor, go_into_component_for_binding) { EXPECT_CALL(goIntoComponentMock, Call(Eq(listModelNode))) .WillRepeatedly(Return(mockComponentView.rootModelNode())); @@ -1391,7 +1390,7 @@ TEST_F(ListModelEditor, GoIntoComponentForBinding) ASSERT_THAT(displayValues(), ElementsAre(ElementsAre("com", 11, 55))); } -TEST_F(ListModelEditor, GoIntoComponentForModelNode) +TEST_F(ListModelEditor, go_into_component_for_model_node) { EXPECT_CALL(goIntoComponentMock, Call(Eq(listModelNode))) .WillRepeatedly(Return(mockComponentView.rootModelNode())); diff --git a/tests/unit/tests/unittests/metainfo/CMakeLists.txt b/tests/unit/tests/unittests/metainfo/CMakeLists.txt new file mode 100644 index 00000000000..7f2728f078b --- /dev/null +++ b/tests/unit/tests/unittests/metainfo/CMakeLists.txt @@ -0,0 +1,5 @@ +# qmldesigner/designercore/model +extend_qtc_test(unittest + SOURCES + nodemetainfo-test.cpp +) diff --git a/tests/unit/tests/unittests/metainfo/nodemetainfo-test.cpp b/tests/unit/tests/unittests/metainfo/nodemetainfo-test.cpp new file mode 100644 index 00000000000..b2532938a3e --- /dev/null +++ b/tests/unit/tests/unittests/metainfo/nodemetainfo-test.cpp @@ -0,0 +1,415 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +#include "../utils/googletest.h" + +#include "../mocks/projectstoragemock.h" + +#include +#include +#include + +namespace { + +using QmlDesigner::ModelNode; +using QmlDesigner::ModelNodes; + +template +auto PropertyId(const Matcher &matcher) +{ + return Property(&QmlDesigner::PropertyMetaInfo::id, matcher); +} + +class NodeMetaInfo : public testing::Test +{ +protected: + NiceMock projectStorageMock; + QmlDesigner::Model model{projectStorageMock, "QtQuick.Item"}; + ModelNode rootNode = model.rootModelNode(); + ModelNode item = model.createModelNode("QtQuick.Item"); + ModelNode object = model.createModelNode("QML.QtObject"); + QmlDesigner::NodeMetaInfo itemMetaInfo = item.metaInfo(); + QmlDesigner::NodeMetaInfo objectMetaInfo = object.metaInfo(); + QmlDesigner::TypeId intTypeId = projectStorageMock.typeId(projectStorageMock.moduleId("QML"), + "int", + QmlDesigner::Storage::Version{}); +}; + +TEST_F(NodeMetaInfo, is_true_if_meta_info_exists) +{ + auto node = model.createModelNode("QtQuick.Item"); + auto metaInfo = node.metaInfo(); + + auto isValid = bool(metaInfo); + + ASSERT_TRUE(isValid); +} + +TEST_F(NodeMetaInfo, is_valid_if_meta_info_exists) +{ + auto node = model.createModelNode("QtQuick.Item"); + auto metaInfo = node.metaInfo(); + + auto isValid = metaInfo.isValid(); + + ASSERT_TRUE(isValid); +} + +TEST_F(NodeMetaInfo, is_false_if_meta_info_not_exists) +{ + auto node = model.createModelNode("QtQuick.Foo"); + auto metaInfo = node.metaInfo(); + + auto isValid = bool(metaInfo); + + ASSERT_FALSE(isValid); +} + +TEST_F(NodeMetaInfo, default_is_false) +{ + auto isValid = bool(QmlDesigner::NodeMetaInfo{}); + + ASSERT_FALSE(isValid); +} + +TEST_F(NodeMetaInfo, is_invalid_if_meta_info_not_exists) +{ + auto node = model.createModelNode("QtQuick.Foo"); + auto metaInfo = node.metaInfo(); + + auto isValid = metaInfo.isValid(); + + ASSERT_FALSE(isValid); +} + +TEST_F(NodeMetaInfo, default_is_invalid) +{ + auto isValid = QmlDesigner::NodeMetaInfo{}.isValid(); + + ASSERT_FALSE(isValid); +} + +TEST_F(NodeMetaInfo, item_is_based_on_object) +{ + bool isBasedOn = itemMetaInfo.isBasedOn(objectMetaInfo); + + ASSERT_TRUE(isBasedOn); +} + +TEST_F(NodeMetaInfo, item_is_based_on_item) +{ + bool isBasedOn = itemMetaInfo.isBasedOn(itemMetaInfo); + + ASSERT_TRUE(isBasedOn); +} + +TEST_F(NodeMetaInfo, object_is_no_based_on_item) +{ + bool isBasedOn = objectMetaInfo.isBasedOn(itemMetaInfo); + + ASSERT_FALSE(isBasedOn); +} + +TEST_F(NodeMetaInfo, object_is_not_file_component) +{ + bool isFileComponent = objectMetaInfo.isFileComponent(); + + ASSERT_FALSE(isFileComponent); +} + +TEST_F(NodeMetaInfo, default_is_not_file_component) +{ + bool isFileComponent = QmlDesigner::NodeMetaInfo{}.isFileComponent(); + + ASSERT_FALSE(isFileComponent); +} + +TEST_F(NodeMetaInfo, invalid_is_not_file_component) +{ + auto node = model.createModelNode("QtQuick.Foo"); + auto metaInfo = node.metaInfo(); + + bool isFileComponent = metaInfo.isFileComponent(); + + ASSERT_FALSE(isFileComponent); +} + +TEST_F(NodeMetaInfo, component_is_file_component) +{ + using QmlDesigner::Storage::TypeTraits; + auto moduleId = projectStorageMock.createModule("/path/to/project"); + auto typeId = projectStorageMock.createType(moduleId, + "Foo", + TypeTraits::IsFileComponent | TypeTraits::Reference); + QmlDesigner::NodeMetaInfo metaInfo{typeId, &projectStorageMock}; + + bool isFileComponent = metaInfo.isFileComponent(); + + ASSERT_TRUE(isFileComponent); +} + +TEST_F(NodeMetaInfo, has_property) +{ + auto node = model.createModelNode("QtQuick.Item"); + auto metaInfo = node.metaInfo(); + projectStorageMock.createProperty(metaInfo.id(), "x", intTypeId); + + bool hasProperty = metaInfo.hasProperty("x"); + + ASSERT_TRUE(hasProperty); +} + +TEST_F(NodeMetaInfo, has_not_property) +{ + auto node = model.createModelNode("QtQuick.Item"); + auto metaInfo = node.metaInfo(); + + bool hasProperty = metaInfo.hasProperty("foo"); + + ASSERT_FALSE(hasProperty); +} + +TEST_F(NodeMetaInfo, default_has_not_property) +{ + auto metaInfo = QmlDesigner::NodeMetaInfo{}; + + bool hasProperty = metaInfo.hasProperty("x"); + + ASSERT_FALSE(hasProperty); +} + +TEST_F(NodeMetaInfo, invalid_has_not_property) +{ + auto node = model.createModelNode("QtQuick.Foo"); + auto metaInfo = node.metaInfo(); + + bool hasProperty = metaInfo.hasProperty("x"); + + ASSERT_FALSE(hasProperty); +} + +TEST_F(NodeMetaInfo, get_property) +{ + auto node = model.createModelNode("QtQuick.Item"); + auto metaInfo = node.metaInfo(); + auto propertyId = projectStorageMock.createProperty(metaInfo.id(), "x", intTypeId); + + auto property = metaInfo.property("x"); + + ASSERT_THAT(property, PropertyId(propertyId)); +} + +TEST_F(NodeMetaInfo, get_invalid_property_if_not_exists) +{ + auto node = model.createModelNode("QtQuick.Item"); + auto metaInfo = node.metaInfo(); + + auto property = metaInfo.property("x"); + + ASSERT_THAT(property, PropertyId(IsFalse())); +} + +TEST_F(NodeMetaInfo, get_invalid_property_for_default) +{ + auto metaInfo = QmlDesigner::NodeMetaInfo{}; + + auto property = metaInfo.property("x"); + + ASSERT_THAT(property, PropertyId(IsFalse())); +} + +TEST_F(NodeMetaInfo, get_invalid_property_if_meta_info_is_invalid) +{ + auto node = model.createModelNode("QtQuick.Foo"); + auto metaInfo = node.metaInfo(); + + auto property = metaInfo.property("x"); + + ASSERT_THAT(property, PropertyId(IsFalse())); +} + +TEST_F(NodeMetaInfo, get_properties) +{ + auto node = model.createModelNode("QtQuick.Item"); + auto metaInfo = node.metaInfo(); + auto xPropertyId = projectStorageMock.createProperty(metaInfo.id(), "x", intTypeId); + auto yPropertyId = projectStorageMock.createProperty(metaInfo.id(), "y", intTypeId); + + auto properties = metaInfo.properties(); + + ASSERT_THAT(properties, IsSupersetOf({PropertyId(xPropertyId), PropertyId(yPropertyId)})); +} + +TEST_F(NodeMetaInfo, get_no_properties_for_default) +{ + auto metaInfo = QmlDesigner::NodeMetaInfo{}; + + auto properties = metaInfo.properties(); + + ASSERT_THAT(properties, IsEmpty()); +} + +TEST_F(NodeMetaInfo, get_no_properties_if_is_invalid) +{ + auto node = model.createModelNode("QtQuick.Foo"); + auto metaInfo = node.metaInfo(); + + auto properties = metaInfo.properties(); + + ASSERT_THAT(properties, IsEmpty()); +} + +TEST_F(NodeMetaInfo, get_local_properties) +{ + auto node = model.createModelNode("QtQuick.Item"); + auto metaInfo = node.metaInfo(); + auto xPropertyId = projectStorageMock.createProperty(metaInfo.id(), "x", intTypeId); + auto yPropertyId = projectStorageMock.createProperty(metaInfo.id(), "y", intTypeId); + + auto properties = metaInfo.localProperties(); + + ASSERT_THAT(properties, IsSupersetOf({PropertyId(xPropertyId), PropertyId(yPropertyId)})); +} + +TEST_F(NodeMetaInfo, get_no_local_properties_for_default_metainfo) +{ + auto metaInfo = QmlDesigner::NodeMetaInfo{}; + + auto properties = metaInfo.localProperties(); + + ASSERT_THAT(properties, IsEmpty()); +} + +TEST_F(NodeMetaInfo, get_no_local_properties_if_node_is_invalid) +{ + auto node = model.createModelNode("QtQuick.Foo"); + auto metaInfo = node.metaInfo(); + + auto properties = metaInfo.localProperties(); + + ASSERT_THAT(properties, IsEmpty()); +} + +TEST_F(NodeMetaInfo, get_signal_names) +{ + auto node = model.createModelNode("QtQuick.Item"); + auto metaInfo = node.metaInfo(); + projectStorageMock.createSignal(metaInfo.id(), "xChanged"); + projectStorageMock.createSignal(metaInfo.id(), "yChanged"); + + auto signalNames = metaInfo.signalNames(); + + ASSERT_THAT(signalNames, IsSupersetOf({"xChanged", "yChanged"})); +} + +TEST_F(NodeMetaInfo, get_no_signal_names_for_default_metainfo) +{ + auto metaInfo = QmlDesigner::NodeMetaInfo{}; + + auto signalNames = metaInfo.signalNames(); + + ASSERT_THAT(signalNames, IsEmpty()); +} + +TEST_F(NodeMetaInfo, get_no_signal_names_if_node_is_invalid) +{ + auto node = model.createModelNode("QtQuick.Foo"); + auto metaInfo = node.metaInfo(); + + auto signalNames = metaInfo.signalNames(); + + ASSERT_THAT(signalNames, IsEmpty()); +} + +TEST_F(NodeMetaInfo, get_function_names) +{ + auto node = model.createModelNode("QtQuick.Item"); + auto metaInfo = node.metaInfo(); + projectStorageMock.createFunction(metaInfo.id(), "setX"); + projectStorageMock.createFunction(metaInfo.id(), "setY"); + + auto functionNames = metaInfo.slotNames(); + + ASSERT_THAT(functionNames, IsSupersetOf({"setX", "setY"})); +} + +TEST_F(NodeMetaInfo, get_no_function_names_for_default_metainfo) +{ + auto metaInfo = QmlDesigner::NodeMetaInfo{}; + + auto functionNames = metaInfo.slotNames(); + + ASSERT_THAT(functionNames, IsEmpty()); +} + +TEST_F(NodeMetaInfo, get_no_function_names_if_node_is_invalid) +{ + auto node = model.createModelNode("QtQuick.Foo"); + auto metaInfo = node.metaInfo(); + + auto functionNames = metaInfo.slotNames(); + + ASSERT_THAT(functionNames, IsEmpty()); +} + +TEST_F(NodeMetaInfo, get_default_property) +{ + auto node = model.createModelNode("QtQuick.Item"); + auto metaInfo = node.metaInfo(); + auto defaultProperty = metaInfo.property("data"); + + auto property = metaInfo.defaultProperty(); + + ASSERT_THAT(property, defaultProperty); +} + +TEST_F(NodeMetaInfo, get_no_default_property_for_default_metainfo) +{ + auto metaInfo = QmlDesigner::NodeMetaInfo{}; + + auto property = metaInfo.defaultProperty(); + + ASSERT_THAT(property, IsFalse()); +} + +TEST_F(NodeMetaInfo, get_no_default_property_if_node_is_invalid) +{ + auto node = model.createModelNode("QtQuick.Foo"); + auto metaInfo = node.metaInfo(); + + auto property = metaInfo.defaultProperty(); + + ASSERT_THAT(property, IsFalse()); +} + +TEST_F(NodeMetaInfo, get_default_property_name) +{ + auto node = model.createModelNode("QtQuick.Item"); + auto metaInfo = node.metaInfo(); + auto defaultProperty = metaInfo.property("data"); + + auto property = metaInfo.defaultPropertyName(); + + ASSERT_THAT(property, "data"); +} + +TEST_F(NodeMetaInfo, get_no_default_property_name_for_default_metainfo) +{ + auto metaInfo = QmlDesigner::NodeMetaInfo{}; + + auto property = metaInfo.defaultPropertyName(); + + ASSERT_THAT(property, IsEmpty()); +} + +TEST_F(NodeMetaInfo, get_no_default_property_name_if_node_is_invalid) +{ + auto node = model.createModelNode("QtQuick.Foo"); + auto metaInfo = node.metaInfo(); + + auto property = metaInfo.defaultPropertyName(); + + ASSERT_THAT(property, IsEmpty()); +} + +} // namespace diff --git a/tests/unit/tests/unittests/model/CMakeLists.txt b/tests/unit/tests/unittests/model/CMakeLists.txt new file mode 100644 index 00000000000..187ed9f99a0 --- /dev/null +++ b/tests/unit/tests/unittests/model/CMakeLists.txt @@ -0,0 +1,9 @@ +# qmldesigner/designercore/model +extend_qtc_test(unittest + SOURCES + import-test.cpp + model-test.cpp + modelnode-test.cpp + nodelistproperty-test.cpp + modelresourcemanagement-test.cpp +) diff --git a/tests/unit/unittest/import-test.cpp b/tests/unit/tests/unittests/model/import-test.cpp similarity index 76% rename from tests/unit/unittest/import-test.cpp rename to tests/unit/tests/unittests/model/import-test.cpp index e4adfd7e5bb..695d286f376 100644 --- a/tests/unit/unittest/import-test.cpp +++ b/tests/unit/tests/unittests/model/import-test.cpp @@ -1,13 +1,13 @@ // Copyright (C) 2023 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" #include namespace { -TEST(Import, ParseVersion) +TEST(Import, parse_version) { auto import = QmlDesigner::Import::createLibraryImport("Qml", "6.5"); @@ -16,7 +16,7 @@ TEST(Import, ParseVersion) ASSERT_THAT(version, FieldsAre(6, 5)); } -TEST(Import, ParseMajorVersion) +TEST(Import, parse_major_version) { auto import = QmlDesigner::Import::createLibraryImport("Qml", "6.5"); @@ -25,7 +25,7 @@ TEST(Import, ParseMajorVersion) ASSERT_THAT(version, 6); } -TEST(Import, MajorVersionIsInvalidForEmptyString) +TEST(Import, major_version_is_invalid_for_empty_string) { auto import = QmlDesigner::Import::createLibraryImport("Qml"); @@ -34,7 +34,7 @@ TEST(Import, MajorVersionIsInvalidForEmptyString) ASSERT_THAT(version, -1); } -TEST(Import, MajorVersionIsInvalidForBrokenString) +TEST(Import, major_version_is_invalid_for_broken_string) { auto import = QmlDesigner::Import::createLibraryImport("Qml", "6,5"); @@ -43,7 +43,7 @@ TEST(Import, MajorVersionIsInvalidForBrokenString) ASSERT_THAT(version, -1); } -TEST(Import, ParseMinorVersion) +TEST(Import, parse_minor_version) { auto import = QmlDesigner::Import::createLibraryImport("Qml", "6.5"); @@ -52,7 +52,7 @@ TEST(Import, ParseMinorVersion) ASSERT_THAT(version, 5); } -TEST(Import, MinorVersionIsInvalidForEmptyString) +TEST(Import, minor_version_is_invalid_for_empty_string) { auto import = QmlDesigner::Import::createLibraryImport("Qml"); @@ -61,7 +61,7 @@ TEST(Import, MinorVersionIsInvalidForEmptyString) ASSERT_THAT(version, -1); } -TEST(Import, MinorVersionIsInvalidForBrokenString) +TEST(Import, minor_version_is_invalid_for_broken_string) { auto import = QmlDesigner::Import::createLibraryImport("Qml", "6,5"); @@ -70,7 +70,7 @@ TEST(Import, MinorVersionIsInvalidForBrokenString) ASSERT_THAT(version, -1); } -TEST(Import, VersionIsNotEmpty) +TEST(Import, version_is_not_empty) { auto import = QmlDesigner::Import::createLibraryImport("Qml", "6.5"); @@ -79,7 +79,7 @@ TEST(Import, VersionIsNotEmpty) ASSERT_FALSE(version.isEmpty()); } -TEST(Import, BrokenVersionStringIsEmptyVersion) +TEST(Import, broken_version_string_is_empty_version) { auto import = QmlDesigner::Import::createLibraryImport("Qml", "6"); @@ -88,7 +88,7 @@ TEST(Import, BrokenVersionStringIsEmptyVersion) ASSERT_TRUE(version.isEmpty()); } -TEST(Import, EmptyVersionStringIsEmptyVersion) +TEST(Import, empty_version_string_is_empty_version) { auto import = QmlDesigner::Import::createLibraryImport("Qml"); @@ -97,7 +97,7 @@ TEST(Import, EmptyVersionStringIsEmptyVersion) ASSERT_TRUE(version.isEmpty()); } -TEST(Import, SameVersionsAreEqual) +TEST(Import, same_versions_are_equal) { QmlDesigner::Version version1{6, 5}; QmlDesigner::Version version2{6, 5}; @@ -107,7 +107,7 @@ TEST(Import, SameVersionsAreEqual) ASSERT_TRUE(isEqual); } -TEST(Import, InvalidVersionsAreEqual) +TEST(Import, invalid_versions_are_equal) { QmlDesigner::Version version1; QmlDesigner::Version version2; @@ -117,7 +117,7 @@ TEST(Import, InvalidVersionsAreEqual) ASSERT_TRUE(isEqual); } -TEST(Import, DifferentMinorVersionsAreNotEqual) +TEST(Import, different_minor_versions_are_not_equal) { QmlDesigner::Version version1{6, 4}; QmlDesigner::Version version2{6, 5}; @@ -127,7 +127,7 @@ TEST(Import, DifferentMinorVersionsAreNotEqual) ASSERT_FALSE(isEqual); } -TEST(Import, DifferentMajorVersionsAreNotEqual) +TEST(Import, different_major_versions_are_not_equal) { QmlDesigner::Version version1{5, 5}; QmlDesigner::Version version2{6, 5}; @@ -137,7 +137,7 @@ TEST(Import, DifferentMajorVersionsAreNotEqual) ASSERT_FALSE(isEqual); } -TEST(Import, LessMinorVersionsAreLess) +TEST(Import, less_minor_versions_are_less) { QmlDesigner::Version version1{6, 4}; QmlDesigner::Version version2{6, 5}; @@ -147,7 +147,7 @@ TEST(Import, LessMinorVersionsAreLess) ASSERT_TRUE(isLess); } -TEST(Import, LessMajorVersionsAreLess) +TEST(Import, less_major_versions_are_less) { QmlDesigner::Version version1{5, 15}; QmlDesigner::Version version2{6, 5}; @@ -157,7 +157,7 @@ TEST(Import, LessMajorVersionsAreLess) ASSERT_TRUE(isLess); } -TEST(Import, SameVersionsAreNotLess) +TEST(Import, same_versions_are_not_less) { QmlDesigner::Version version1{6, 5}; QmlDesigner::Version version2{6, 5}; @@ -167,7 +167,7 @@ TEST(Import, SameVersionsAreNotLess) ASSERT_FALSE(isLess); } -TEST(Import, EmptyVersionIsNotLess) +TEST(Import, empty_version_is_not_less) { QmlDesigner::Version version1; QmlDesigner::Version version2{6, 5}; @@ -177,7 +177,7 @@ TEST(Import, EmptyVersionIsNotLess) ASSERT_FALSE(isLess); } -TEST(Import, NonEmptyVersionIsIsLessThanEmptyVersion) +TEST(Import, non_empty_version_is_is_less_than_empty_version) { QmlDesigner::Version version1{6, 5}; QmlDesigner::Version version2; @@ -187,7 +187,7 @@ TEST(Import, NonEmptyVersionIsIsLessThanEmptyVersion) ASSERT_TRUE(isLess); } -TEST(Import, GreaterMinorVersionsAreGreater) +TEST(Import, greater_minor_versions_are_greater) { QmlDesigner::Version version1{6, 6}; QmlDesigner::Version version2{6, 5}; @@ -197,7 +197,7 @@ TEST(Import, GreaterMinorVersionsAreGreater) ASSERT_TRUE(isGreater); } -TEST(Import, GreaterMajorVersionsAreGreater) +TEST(Import, greater_major_versions_are_greater) { QmlDesigner::Version version1{6, 5}; QmlDesigner::Version version2{5, 15}; @@ -207,7 +207,7 @@ TEST(Import, GreaterMajorVersionsAreGreater) ASSERT_TRUE(isGreater); } -TEST(Import, SameVersionsAreNotGreater) +TEST(Import, same_versions_are_not_greater) { QmlDesigner::Version version1{6, 5}; QmlDesigner::Version version2{6, 5}; @@ -217,7 +217,7 @@ TEST(Import, SameVersionsAreNotGreater) ASSERT_FALSE(isGreater); } -TEST(Import, EmptyVersionIsGreater) +TEST(Import, empty_version_is_greater) { QmlDesigner::Version version1; QmlDesigner::Version version2{6, 5}; @@ -227,7 +227,7 @@ TEST(Import, EmptyVersionIsGreater) ASSERT_TRUE(isGreater); } -TEST(Import, NonEmptyVersionIsIsNotGreaterThanEmptyVersion) +TEST(Import, non_empty_version_is_is_not_greater_than_empty_version) { QmlDesigner::Version version1{6, 5}; QmlDesigner::Version version2; @@ -237,7 +237,7 @@ TEST(Import, NonEmptyVersionIsIsNotGreaterThanEmptyVersion) ASSERT_FALSE(isGreater); } -TEST(Import, LessEqualMinorVersionsAreLessEqual) +TEST(Import, less_equal_minor_versions_are_less_equal) { QmlDesigner::Version version1{6, 4}; QmlDesigner::Version version2{6, 5}; @@ -247,7 +247,7 @@ TEST(Import, LessEqualMinorVersionsAreLessEqual) ASSERT_TRUE(isLessEqual); } -TEST(Import, LessqualMajorVersionsAreLessqual) +TEST(Import, lessqual_major_versions_are_lessqual) { QmlDesigner::Version version1{5, 15}; QmlDesigner::Version version2{6, 5}; @@ -257,7 +257,7 @@ TEST(Import, LessqualMajorVersionsAreLessqual) ASSERT_TRUE(isLessEqual); } -TEST(Import, SameVersionsAreLessqual) +TEST(Import, same_versions_are_lessqual) { QmlDesigner::Version version1{6, 5}; QmlDesigner::Version version2{6, 5}; @@ -267,7 +267,7 @@ TEST(Import, SameVersionsAreLessqual) ASSERT_TRUE(isLessEqual); } -TEST(Import, EmptyVersionIsNotLessqual) +TEST(Import, empty_version_is_not_lessqual) { QmlDesigner::Version version1; QmlDesigner::Version version2{6, 5}; @@ -277,7 +277,7 @@ TEST(Import, EmptyVersionIsNotLessqual) ASSERT_FALSE(isLessEqual); } -TEST(Import, NonEmptyVersionIsIsLessqualThanEmptyVersion) +TEST(Import, non_empty_version_is_is_lessqual_than_empty_version) { QmlDesigner::Version version1{6, 5}; QmlDesigner::Version version2; @@ -287,7 +287,7 @@ TEST(Import, NonEmptyVersionIsIsLessqualThanEmptyVersion) ASSERT_TRUE(isLessEqual); } -TEST(Import, GreaterEqualMinorVersionsAreGreaterEqual) +TEST(Import, greater_equal_minor_versions_are_greater_equal) { QmlDesigner::Version version1{6, 6}; QmlDesigner::Version version2{6, 5}; @@ -297,7 +297,7 @@ TEST(Import, GreaterEqualMinorVersionsAreGreaterEqual) ASSERT_TRUE(isGreaterEqual); } -TEST(Import, GreaterEqualMajorVersionsAreGreaterEqual) +TEST(Import, greater_equal_major_versions_are_greater_equal) { QmlDesigner::Version version1{6, 5}; QmlDesigner::Version version2{5, 15}; @@ -307,7 +307,7 @@ TEST(Import, GreaterEqualMajorVersionsAreGreaterEqual) ASSERT_TRUE(isGreaterEqual); } -TEST(Import, SameVersionsAreGreaterEqual) +TEST(Import, same_versions_are_greater_equal) { QmlDesigner::Version version1{6, 5}; QmlDesigner::Version version2{6, 5}; @@ -317,7 +317,7 @@ TEST(Import, SameVersionsAreGreaterEqual) ASSERT_TRUE(isGreaterEqual); } -TEST(Import, EmptyVersionIsGreaterEqual) +TEST(Import, empty_version_is_greater_equal) { QmlDesigner::Version version1; QmlDesigner::Version version2{6, 5}; @@ -327,7 +327,7 @@ TEST(Import, EmptyVersionIsGreaterEqual) ASSERT_TRUE(isGreaterEqual); } -TEST(Import, NonEmptyVersionIsIsNotGreaterEqualThanEmptyVersion) +TEST(Import, non_empty_version_is_is_not_greater_equal_than_empty_version) { QmlDesigner::Version version1{6, 5}; QmlDesigner::Version version2; diff --git a/tests/unit/tests/unittests/model/model-test.cpp b/tests/unit/tests/unittests/model/model-test.cpp new file mode 100644 index 00000000000..75e865aa1de --- /dev/null +++ b/tests/unit/tests/unittests/model/model-test.cpp @@ -0,0 +1,709 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +#include "../utils/googletest.h" + +#include "../mocks/mocklistmodeleditorview.h" +#include "../mocks/modelresourcemanagementmock.h" +#include "../mocks/projectstoragemock.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using QmlDesigner::AbstractProperty; +using QmlDesigner::ModelNode; +using QmlDesigner::ModelNodes; +using QmlDesigner::ModelResourceSet; + +template +auto HasPropertyName(const Matcher &matcher) +{ + return Property(&AbstractProperty::name, matcher); +} + +MATCHER(IsSorted, std::string(negation ? "isn't sorted" : "is sorted")) +{ + using std::begin; + using std::end; + return std::is_sorted(begin(arg), end(arg)); +} + +class Model : public ::testing::Test +{ +protected: + Model() + { + model.attachView(&viewMock); + rootNode = viewMock.rootModelNode(); + ON_CALL(resourceManagementMock, removeNodes(_, _)).WillByDefault([](auto nodes, auto) { + return ModelResourceSet{std::move(nodes), {}, {}}; + }); + ON_CALL(resourceManagementMock, removeProperties(_, _)).WillByDefault([](auto properties, auto) { + return ModelResourceSet{{}, std::move(properties), {}}; + }); + } + + ~Model() { model.detachView(&viewMock); } + + auto createNodeWithParent(const ModelNode &parentNode, const QString &id = {}) + { + auto node = viewMock.createModelNode("QtQuick.Item"); + node.setIdWithoutRefactoring(id); + parentNode.defaultNodeAbstractProperty().reparentHere(node); + + return node; + } + + auto createProperty(const ModelNode &parentNode, QmlDesigner::PropertyName name) + { + auto property = parentNode.variantProperty(name); + property.setValue(4); + return property; + } + + auto createBindingProperty(const ModelNode &parentNode, + QmlDesigner::PropertyName name, + const QString &expression = "foo") + { + auto property = parentNode.bindingProperty(name); + property.setExpression(expression); + return property; + } + +protected: + NiceMock viewMock; + NiceMock projectStorageMock; + NiceMock resourceManagementMock; + QmlDesigner::Model model{projectStorageMock, + "QtQuick.Item", + -1, + -1, + nullptr, + std::make_unique( + resourceManagementMock)}; + ModelNode rootNode; +}; + +TEST_F(Model, model_node_destroy_is_calling_model_resource_management_remove_node) +{ + auto node = createNodeWithParent(rootNode); + + EXPECT_CALL(resourceManagementMock, removeNodes(ElementsAre(node), &model)); + + node.destroy(); +} + +TEST_F(Model, model_node_remove_propery_is_calling_model_resource_management_remove_property) +{ + auto property = rootNode.variantProperty("foo"); + property.setValue(4); + + EXPECT_CALL(resourceManagementMock, removeProperties(ElementsAre(property), &model)); + + rootNode.removeProperty("foo"); +} + +TEST_F(Model, node_abstract_property_reparent_here_is_calling_model_resource_management_remove_property) +{ + auto node = createNodeWithParent(rootNode); + auto property = rootNode.variantProperty("foo"); + property.setValue(4); + + EXPECT_CALL(resourceManagementMock, removeProperties(ElementsAre(property), &model)); + + rootNode.nodeListProperty("foo").reparentHere(node); +} + +TEST_F(Model, node_property_set_model_node_is_calling_model_resource_management_remove_property) +{ + auto node = createNodeWithParent(rootNode); + auto property = rootNode.variantProperty("foo"); + property.setValue(4); + + EXPECT_CALL(resourceManagementMock, removeProperties(ElementsAre(property), &model)); + + rootNode.nodeProperty("foo").setModelNode(node); +} + +TEST_F(Model, variant_property_set_value_is_calling_model_resource_management_remove_property) +{ + auto property = rootNode.bindingProperty("foo"); + property.setExpression("blah"); + + EXPECT_CALL(resourceManagementMock, removeProperties(ElementsAre(property), &model)); + + rootNode.variantProperty("foo").setValue(7); +} + +TEST_F(Model, + variant_property_set_dynamic_type_name_and_enumeration_is_calling_model_resource_management_remove_property) +{ + auto property = rootNode.bindingProperty("foo"); + property.setExpression("blah"); + + EXPECT_CALL(resourceManagementMock, removeProperties(ElementsAre(property), &model)); + + rootNode.variantProperty("foo").setDynamicTypeNameAndEnumeration("int", "Ha"); +} + +TEST_F(Model, variant_property_set_dynamic_type_name_and_value_is_calling_model_resource_management_remove_property) +{ + auto property = rootNode.bindingProperty("foo"); + property.setExpression("blah"); + + EXPECT_CALL(resourceManagementMock, removeProperties(ElementsAre(property), &model)); + + rootNode.variantProperty("foo").setDynamicTypeNameAndValue("int", 7); +} + +TEST_F(Model, binding_property_set_expression_is_calling_model_resource_management_remove_property) +{ + auto property = rootNode.variantProperty("foo"); + property.setValue(4); + + EXPECT_CALL(resourceManagementMock, removeProperties(ElementsAre(property), &model)); + + rootNode.bindingProperty("foo").setExpression("blah"); +} + +TEST_F(Model, + binding_property_set_dynamic_type_name_and_expression_is_calling_model_resource_management_remove_property) +{ + auto property = rootNode.variantProperty("foo"); + property.setValue(4); + + EXPECT_CALL(resourceManagementMock, removeProperties(ElementsAre(property), &model)); + + rootNode.bindingProperty("foo").setDynamicTypeNameAndExpression("int", "blah"); +} + +TEST_F(Model, signal_handler_property_set_source_is_calling_model_resource_management_remove_property) +{ + auto property = rootNode.bindingProperty("foo"); + property.setExpression("blah"); + + EXPECT_CALL(resourceManagementMock, removeProperties(ElementsAre(property), &model)); + + rootNode.signalHandlerProperty("foo").setSource("blah"); +} + +TEST_F(Model, signal_declaration_property_set_signature_is_calling_model_resource_management_remove_property) +{ + auto property = rootNode.bindingProperty("foo"); + property.setExpression("blah"); + + EXPECT_CALL(resourceManagementMock, removeProperties(ElementsAre(property), &model)); + + rootNode.signalDeclarationProperty("foo").setSignature("blah"); +} + +TEST_F(Model, model_node_destroy_is_calling_abstract_view_node_about_to_be_removed) +{ + auto node = createNodeWithParent(rootNode); + auto node2 = createNodeWithParent(rootNode); + ON_CALL(resourceManagementMock, removeNodes(ElementsAre(node), &model)) + .WillByDefault(Return(ModelResourceSet{{node, node2}, {}, {}})); + + EXPECT_CALL(viewMock, nodeAboutToBeRemoved(Eq(node))); + EXPECT_CALL(viewMock, nodeAboutToBeRemoved(Eq(node2))); + + node.destroy(); +} + +TEST_F(Model, model_node_destroy_is_calling_abstract_view_node_removed) +{ + auto node = createNodeWithParent(rootNode); + auto node2 = createNodeWithParent(rootNode); + ON_CALL(resourceManagementMock, removeNodes(ElementsAre(node), &model)) + .WillByDefault(Return(ModelResourceSet{{node, node2}, {}, {}})); + + EXPECT_CALL(viewMock, nodeRemoved(Eq(node), _, _)); + EXPECT_CALL(viewMock, nodeRemoved(Eq(node2), _, _)); + + node.destroy(); +} + +TEST_F(Model, model_node_destroy_is_calling_abstract_view_node_removed_with_valid_nodes) +{ + auto node = createNodeWithParent(rootNode); + auto node2 = createNodeWithParent(rootNode); + ON_CALL(resourceManagementMock, removeNodes(ElementsAre(node), &model)) + .WillByDefault(Return(ModelResourceSet{{node, node2, ModelNode{}}, {}, {}})); + + EXPECT_CALL(viewMock, nodeRemoved(Eq(node), _, _)); + EXPECT_CALL(viewMock, nodeRemoved(Eq(node2), _, _)); + + node.destroy(); +} + +TEST_F(Model, model_node_destroy_is_calling_abstract_view_properties_about_to_be_removed) +{ + auto node = createNodeWithParent(rootNode); + auto property = createProperty(rootNode, "foo"); + auto property2 = createProperty(rootNode, "bar"); + ON_CALL(resourceManagementMock, removeNodes(ElementsAre(node), &model)) + .WillByDefault(Return(ModelResourceSet{{node}, {property, property2}, {}})); + + EXPECT_CALL(viewMock, propertiesAboutToBeRemoved(UnorderedElementsAre(property, property2))); + + node.destroy(); +} + +TEST_F(Model, model_node_destroy_is_calling_abstract_view_properties_removed) +{ + auto node = createNodeWithParent(rootNode); + auto property = createProperty(rootNode, "foo"); + auto property2 = createProperty(rootNode, "bar"); + ON_CALL(resourceManagementMock, removeNodes(ElementsAre(node), &model)) + .WillByDefault(Return(ModelResourceSet{{node}, {property, property2}, {}})); + + EXPECT_CALL(viewMock, propertiesRemoved(UnorderedElementsAre(property, property2))); + + node.destroy(); +} + +TEST_F(Model, model_node_destroy_is_calling_abstract_view_properties_removed_only_with_valid_properties) +{ + auto node = createNodeWithParent(rootNode); + auto property = createProperty(rootNode, "foo"); + auto property2 = createProperty(rootNode, "bar"); + ON_CALL(resourceManagementMock, removeNodes(ElementsAre(node), &model)) + .WillByDefault(Return(ModelResourceSet{{node}, {property, property2, {}}, {}})); + + EXPECT_CALL(viewMock, propertiesRemoved(UnorderedElementsAre(property, property2))); + + node.destroy(); +} + +TEST_F(Model, model_node_destroy_is_calling_abstract_view_binding_properties_about_to_be_changed) +{ + auto node = createNodeWithParent(rootNode); + auto property = createBindingProperty(rootNode, "foo"); + auto property2 = createBindingProperty(rootNode, "bar"); + ON_CALL(resourceManagementMock, removeNodes(ElementsAre(node), &model)) + .WillByDefault(Return(ModelResourceSet{{node}, {}, {{property, "yi"}, {property2, "er"}}})); + + EXPECT_CALL(viewMock, + bindingPropertiesAboutToBeChanged(UnorderedElementsAre(property, property2))); + + node.destroy(); +} + +TEST_F(Model, model_node_destroy_is_calling_abstract_view_binding_properties_changed) +{ + auto node = createNodeWithParent(rootNode); + auto property = createBindingProperty(rootNode, "foo"); + auto property2 = createBindingProperty(rootNode, "bar"); + ON_CALL(resourceManagementMock, removeNodes(ElementsAre(node), &model)) + .WillByDefault(Return(ModelResourceSet{{node}, {}, {{property, "yi"}, {property2, "er"}}})); + + EXPECT_CALL(viewMock, bindingPropertiesChanged(UnorderedElementsAre(property, property2), _)); + + node.destroy(); +} + +TEST_F(Model, model_node_destroy_is_changing_binding_property_expression) +{ + auto node = createNodeWithParent(rootNode); + auto property = createBindingProperty(rootNode, "foo"); + auto property2 = createBindingProperty(rootNode, "bar"); + ON_CALL(resourceManagementMock, removeNodes(ElementsAre(node), &model)) + .WillByDefault(Return(ModelResourceSet{{node}, {}, {{property, "yi"}, {property2, "er"}}})); + + node.destroy(); + + ASSERT_THAT(property.expression(), "yi"); + ASSERT_THAT(property2.expression(), "er"); +} + +TEST_F(Model, model_node_destroy_is_only_changing_existing_binding_property) +{ + auto node = createNodeWithParent(rootNode); + auto property = rootNode.bindingProperty("foo"); + ON_CALL(resourceManagementMock, removeNodes(ElementsAre(node), &model)) + .WillByDefault(Return(ModelResourceSet{{}, {}, {{property, "yi"}}})); + + node.destroy(); + + ASSERT_FALSE(rootNode.hasBindingProperty("foo")); +} + +TEST_F(Model, model_node_destroy_is_calling_abstract_view_binding_properties_changed_only_with_existing_properties) +{ + auto node = createNodeWithParent(rootNode); + auto property = createBindingProperty(rootNode, "foo"); + auto property2 = rootNode.bindingProperty("bar"); + ON_CALL(resourceManagementMock, removeNodes(ElementsAre(node), &model)) + .WillByDefault(Return( + ModelResourceSet{{node}, {}, {{property, "yi"}, {property2, "er"}, {{}, "san"}}})); + + EXPECT_CALL(viewMock, bindingPropertiesChanged(UnorderedElementsAre(property), _)); + + node.destroy(); +} + +TEST_F(Model, model_node_remove_property_is_calling_abstract_view_node_about_to_be_removed) +{ + auto property = createProperty(rootNode, "foo"); + auto node = createNodeWithParent(rootNode); + auto node2 = createNodeWithParent(rootNode); + ON_CALL(resourceManagementMock, removeProperties(ElementsAre(property), &model)) + .WillByDefault(Return(ModelResourceSet{{node, node2}, {property}, {}})); + + EXPECT_CALL(viewMock, nodeAboutToBeRemoved(Eq(node))); + EXPECT_CALL(viewMock, nodeAboutToBeRemoved(Eq(node2))); + + rootNode.removeProperty("foo"); +} + +TEST_F(Model, model_node_remove_property_is_calling_abstract_view_node_removed) +{ + auto property = createProperty(rootNode, "foo"); + auto node = createNodeWithParent(rootNode); + auto node2 = createNodeWithParent(rootNode); + ON_CALL(resourceManagementMock, removeProperties(ElementsAre(property), &model)) + .WillByDefault(Return(ModelResourceSet{{node, node2}, {property}, {}})); + + EXPECT_CALL(viewMock, nodeRemoved(Eq(node), _, _)); + EXPECT_CALL(viewMock, nodeRemoved(Eq(node2), _, _)); + + rootNode.removeProperty("foo"); +} + +TEST_F(Model, model_node_remove_property_is_calling_abstract_view_node_removed_with_valid_nodes) +{ + auto property = createProperty(rootNode, "foo"); + auto node = createNodeWithParent(rootNode); + auto node2 = createNodeWithParent(rootNode); + ON_CALL(resourceManagementMock, removeProperties(ElementsAre(property), &model)) + .WillByDefault(Return(ModelResourceSet{{node, node2, ModelNode{}}, {property}, {}})); + + EXPECT_CALL(viewMock, nodeRemoved(Eq(node), _, _)); + EXPECT_CALL(viewMock, nodeRemoved(Eq(node2), _, _)); + + rootNode.removeProperty("foo"); +} + +TEST_F(Model, model_node_remove_property_is_calling_abstract_view_properties_about_to_be_removed) +{ + auto property = createProperty(rootNode, "yi"); + auto property2 = createProperty(rootNode, "er"); + ON_CALL(resourceManagementMock, removeProperties(ElementsAre(property), &model)) + .WillByDefault(Return(ModelResourceSet{{}, {property, property2}, {}})); + + EXPECT_CALL(viewMock, propertiesAboutToBeRemoved(UnorderedElementsAre(property, property2))); + + rootNode.removeProperty("yi"); +} + +TEST_F(Model, model_node_remove_property_is_calling_abstract_view_properties_removed) +{ + auto property = createProperty(rootNode, "yi"); + auto property2 = createProperty(rootNode, "er"); + ON_CALL(resourceManagementMock, removeProperties(ElementsAre(property), &model)) + .WillByDefault(Return(ModelResourceSet{{}, {property, property2}, {}})); + + EXPECT_CALL(viewMock, propertiesRemoved(UnorderedElementsAre(property, property2))); + + rootNode.removeProperty("yi"); +} + +TEST_F(Model, model_node_remove_property_is_calling_abstract_view_properties_removed_only_with_valid_properties) +{ + auto property = createProperty(rootNode, "yi"); + auto property2 = createProperty(rootNode, "er"); + ON_CALL(resourceManagementMock, removeProperties(ElementsAre(property), &model)) + .WillByDefault(Return(ModelResourceSet{{}, {property, property2, {}}, {}})); + + EXPECT_CALL(viewMock, propertiesRemoved(UnorderedElementsAre(property, property2))); + + rootNode.removeProperty("yi"); +} + +TEST_F(Model, model_node_remove_property_is_calling_abstract_view_binding_properties_about_to_be_changed) +{ + auto property = createProperty(rootNode, "yi"); + auto property1 = createBindingProperty(rootNode, "foo"); + auto property2 = createBindingProperty(rootNode, "bar"); + ON_CALL(resourceManagementMock, removeProperties(ElementsAre(property), &model)) + .WillByDefault( + Return(ModelResourceSet{{}, {property}, {{property1, "yi"}, {property2, "er"}}})); + + EXPECT_CALL(viewMock, bindingPropertiesAboutToBeChanged(ElementsAre(property1, property2))); + + rootNode.removeProperty("yi"); +} + +TEST_F(Model, model_node_remove_property_is_calling_abstract_view_binding_properties_changed) +{ + auto property = createProperty(rootNode, "yi"); + auto property1 = createBindingProperty(rootNode, "foo"); + auto property2 = createBindingProperty(rootNode, "bar"); + ON_CALL(resourceManagementMock, removeProperties(ElementsAre(property), &model)) + .WillByDefault( + Return(ModelResourceSet{{}, {property}, {{property1, "yi"}, {property2, "er"}}})); + + EXPECT_CALL(viewMock, bindingPropertiesChanged(ElementsAre(property1, property2), _)); + + rootNode.removeProperty("yi"); +} + +TEST_F(Model, + model_node_remove_property_is_calling_abstract_view_binding_properties_changed_only_with_valid_properties) +{ + auto property = createProperty(rootNode, "yi"); + auto property1 = createBindingProperty(rootNode, "foo"); + auto property2 = createBindingProperty(rootNode, "bar"); + ON_CALL(resourceManagementMock, removeProperties(ElementsAre(property), &model)) + .WillByDefault( + Return(ModelResourceSet{{}, {property}, {{property1, "yi"}, {property2, "er"}, {}}})); + + EXPECT_CALL(viewMock, bindingPropertiesChanged(ElementsAre(property1, property2), _)); + + rootNode.removeProperty("yi"); +} + +TEST_F(Model, by_default_remove_model_node_removes_node) +{ + model.detachView(&viewMock); + QmlDesigner::Model newModel{projectStorageMock, "QtQuick.Item"}; + newModel.attachView(&viewMock); + auto node = createNodeWithParent(viewMock.rootModelNode()); + + EXPECT_CALL(viewMock, nodeAboutToBeRemoved(Eq(node))); + + node.destroy(); +} + +TEST_F(Model, by_default_remove_properties_removes_property) +{ + model.detachView(&viewMock); + QmlDesigner::Model newModel{projectStorageMock, "QtQuick.Item"}; + newModel.attachView(&viewMock); + rootNode = viewMock.rootModelNode(); + auto property = createProperty(rootNode, "yi"); + + EXPECT_CALL(viewMock, propertiesAboutToBeRemoved(ElementsAre(Eq(property)))); + + rootNode.removeProperty("yi"); +} + +TEST_F(Model, by_default_remove_model_node_in_factory_method_calls_removes_node) +{ + model.detachView(&viewMock); + auto newModel = QmlDesigner::Model::create(projectStorageMock, "QtQuick.Item"); + newModel->attachView(&viewMock); + auto node = createNodeWithParent(viewMock.rootModelNode()); + + EXPECT_CALL(viewMock, nodeAboutToBeRemoved(Eq(node))); + + node.destroy(); +} + +TEST_F(Model, by_default_remove_properties_in_factory_method_calls_remove_property) +{ + model.detachView(&viewMock); + auto newModel = QmlDesigner::Model::create(projectStorageMock, "QtQuick.Item"); + newModel->attachView(&viewMock); + rootNode = viewMock.rootModelNode(); + auto property = createProperty(rootNode, "yi"); + + EXPECT_CALL(viewMock, propertiesAboutToBeRemoved(ElementsAre(Eq(property)))); + + rootNode.removeProperty("yi"); +} + +TEST_F(Model, remove_model_nodes) +{ + auto node = createNodeWithParent(rootNode, "yi"); + auto node2 = createNodeWithParent(rootNode, "er"); + + EXPECT_CALL(resourceManagementMock, + removeNodes(AllOf(UnorderedElementsAre(node, node2), IsSorted()), &model)); + + model.removeModelNodes({node, node2}); +} + +TEST_F(Model, remove_model_nodes_filters_invalid_model_nodes) +{ + auto node = createNodeWithParent(rootNode, "yi"); + + EXPECT_CALL(resourceManagementMock, removeNodes(UnorderedElementsAre(node), &model)); + + model.removeModelNodes({{}, node}); +} + +TEST_F(Model, remove_model_nodes_for_only_invalid_model_nodes_does_nothing) +{ + EXPECT_CALL(resourceManagementMock, removeNodes(_, _)).Times(0); + + model.removeModelNodes({{}}); +} + +TEST_F(Model, remove_model_nodes_reverse) +{ + auto node = createNodeWithParent(rootNode, "yi"); + auto node2 = createNodeWithParent(rootNode, "er"); + + EXPECT_CALL(resourceManagementMock, + removeNodes(AllOf(UnorderedElementsAre(node, node2), IsSorted()), &model)); + + model.removeModelNodes({node2, node}); +} + +TEST_F(Model, remove_model_nodes_calls_notifier) +{ + auto node = createNodeWithParent(rootNode, "yi"); + auto node2 = createNodeWithParent(rootNode, "er"); + auto property = createProperty(rootNode, "foo"); + auto property2 = createBindingProperty(rootNode, "bar"); + auto property3 = createProperty(rootNode, "oh"); + + ON_CALL(resourceManagementMock, + removeNodes(AllOf(UnorderedElementsAre(node, node2), IsSorted()), &model)) + .WillByDefault( + Return(ModelResourceSet{{node, node2}, {property, property3}, {{property2, "bar"}}})); + + EXPECT_CALL(viewMock, nodeAboutToBeRemoved(node)); + EXPECT_CALL(viewMock, nodeAboutToBeRemoved(node2)); + EXPECT_CALL(viewMock, propertiesAboutToBeRemoved(UnorderedElementsAre(property, property3))); + EXPECT_CALL(viewMock, bindingPropertiesChanged(ElementsAre(property2), _)); + + model.removeModelNodes({node, node2}); +} + +TEST_F(Model, remove_model_nodes_bypasses_model_resource_management) +{ + auto node = createNodeWithParent(rootNode, "yi"); + auto node2 = createNodeWithParent(rootNode, "er"); + auto property = createProperty(rootNode, "foo"); + auto property2 = createBindingProperty(rootNode, "bar"); + auto property3 = createProperty(rootNode, "oh"); + ON_CALL(resourceManagementMock, + removeNodes(AllOf(UnorderedElementsAre(node, node2), IsSorted()), &model)) + .WillByDefault( + Return(ModelResourceSet{{node, node2}, {property, property3}, {{property2, "bar"}}})); + + EXPECT_CALL(viewMock, nodeAboutToBeRemoved(node)); + EXPECT_CALL(viewMock, nodeAboutToBeRemoved(node2)); + EXPECT_CALL(viewMock, propertiesAboutToBeRemoved(_)).Times(0); + EXPECT_CALL(viewMock, bindingPropertiesChanged(_, _)).Times(0); + + model.removeModelNodes({node, node2}, QmlDesigner::BypassModelResourceManagement::Yes); +} + +TEST_F(Model, by_default_remove_model_nodes_in_factory_method_calls_removes_node) +{ + model.detachView(&viewMock); + QmlDesigner::Model newModel{projectStorageMock, "QtQuick.Item"}; + newModel.attachView(&viewMock); + rootNode = viewMock.rootModelNode(); + auto node = createNodeWithParent(rootNode, "yi"); + auto node2 = createNodeWithParent(rootNode, "er"); + + EXPECT_CALL(viewMock, nodeAboutToBeRemoved(node)); + EXPECT_CALL(viewMock, nodeAboutToBeRemoved(node2)); + + newModel.removeModelNodes({node, node2}); +} + +TEST_F(Model, remove_properties) +{ + auto property = createProperty(rootNode, "yi"); + auto property2 = createProperty(rootNode, "er"); + + EXPECT_CALL(resourceManagementMock, + removeProperties(AllOf(UnorderedElementsAre(property, property2), IsSorted()), &model)); + + model.removeProperties({property, property2}); +} + +TEST_F(Model, remove_properties_filters_invalid_properties) +{ + auto property = createProperty(rootNode, "yi"); + + EXPECT_CALL(resourceManagementMock, removeProperties(UnorderedElementsAre(property), &model)); + + model.removeProperties({{}, property}); +} + +TEST_F(Model, remove_properties_for_only_invalid_properties_does_nothing) +{ + EXPECT_CALL(resourceManagementMock, removeProperties(_, _)).Times(0); + + model.removeProperties({{}}); +} + +TEST_F(Model, remove_properties_reverse) +{ + auto property = createProperty(rootNode, "yi"); + auto property2 = createProperty(rootNode, "er"); + + EXPECT_CALL(resourceManagementMock, + removeProperties(AllOf(UnorderedElementsAre(property, property2), IsSorted()), &model)); + + model.removeProperties({property2, property}); +} + +TEST_F(Model, remove_properties_calls_notifier) +{ + auto node = createNodeWithParent(rootNode, "yi"); + auto node2 = createNodeWithParent(rootNode, "er"); + auto property = createProperty(rootNode, "foo"); + auto property2 = createBindingProperty(rootNode, "bar"); + auto property3 = createProperty(rootNode, "oh"); + + ON_CALL(resourceManagementMock, + removeProperties(AllOf(UnorderedElementsAre(property, property3), IsSorted()), &model)) + .WillByDefault( + Return(ModelResourceSet{{node, node2}, {property, property3}, {{property2, "bar"}}})); + + EXPECT_CALL(viewMock, nodeAboutToBeRemoved(node)); + EXPECT_CALL(viewMock, nodeAboutToBeRemoved(node2)); + EXPECT_CALL(viewMock, propertiesAboutToBeRemoved(UnorderedElementsAre(property, property3))); + EXPECT_CALL(viewMock, bindingPropertiesChanged(ElementsAre(property2), _)); + + model.removeProperties({property, property3}); +} + +TEST_F(Model, remove_properties_bypasses_model_resource_management) +{ + auto node = createNodeWithParent(rootNode, "yi"); + auto node2 = createNodeWithParent(rootNode, "er"); + auto property = createProperty(rootNode, "foo"); + auto property2 = createBindingProperty(rootNode, "bar"); + auto property3 = createProperty(rootNode, "oh"); + ON_CALL(resourceManagementMock, + removeProperties(AllOf(UnorderedElementsAre(property, property3), IsSorted()), &model)) + .WillByDefault( + Return(ModelResourceSet{{node, node2}, {property, property3}, {{property2, "bar"}}})); + + EXPECT_CALL(viewMock, nodeAboutToBeRemoved(_)).Times(0); + EXPECT_CALL(viewMock, propertiesAboutToBeRemoved(UnorderedElementsAre(property, property3))); + EXPECT_CALL(viewMock, bindingPropertiesChanged(_, _)).Times(0); + + model.removeProperties({property, property3}, QmlDesigner::BypassModelResourceManagement::Yes); +} + +TEST_F(Model, by_default_remove_properties_in_factory_method_calls_removes_properties) +{ + model.detachView(&viewMock); + QmlDesigner::Model newModel{projectStorageMock, "QtQuick.Item"}; + newModel.attachView(&viewMock); + rootNode = viewMock.rootModelNode(); + auto property = createProperty(rootNode, "yi"); + auto property2 = createProperty(rootNode, "er"); + + EXPECT_CALL(viewMock, propertiesAboutToBeRemoved(UnorderedElementsAre(property, property2))); + + newModel.removeProperties({property, property2}); +} + +} // namespace diff --git a/tests/unit/tests/unittests/model/modelnode-test.cpp b/tests/unit/tests/unittests/model/modelnode-test.cpp new file mode 100644 index 00000000000..0d9cf1b1842 --- /dev/null +++ b/tests/unit/tests/unittests/model/modelnode-test.cpp @@ -0,0 +1,27 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +#include "../utils/googletest.h" + +#include "../mocks/projectstoragemock.h" + +#include +#include +#include + +namespace { + +class ModelNode : public testing::Test +{ +protected: + NiceMock projectStorageMock; + QmlDesigner::Model model{projectStorageMock, "QtQuick.Item"}; + QmlDesigner::ModelNode rootNode = model.rootModelNode(); +}; + +TEST_F(ModelNode, get_meta_info) +{ + auto metaInfo = rootNode.metaInfo(); +} + +} // namespace diff --git a/tests/unit/tests/unittests/model/modelresourcemanagement-test.cpp b/tests/unit/tests/unittests/model/modelresourcemanagement-test.cpp new file mode 100644 index 00000000000..d0dc04db402 --- /dev/null +++ b/tests/unit/tests/unittests/model/modelresourcemanagement-test.cpp @@ -0,0 +1,510 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +#include "../../utils/googletest.h" + +#include "../mocks/mocklistmodeleditorview.h" +#include "../mocks/modelresourcemanagementmock.h" +#include "../mocks/projectstoragemock.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using QmlDesigner::AbstractProperty; +using QmlDesigner::ModelNode; +using QmlDesigner::ModelNodes; +using QmlDesigner::ModelResourceSet; + +template +auto SetExpressionProperty(const Matcher &matcher) +{ + return Field("property", &QmlDesigner::ModelResourceSet::SetExpression::property, matcher); +} + +template +auto SetExpressionExpression(const Matcher &matcher) +{ + return Field("expression", &QmlDesigner::ModelResourceSet::SetExpression::expression, matcher); +} + +template +auto SetExpression(const PropertyMatcher &propertyMatcher, const ExpressionMatcher &expressionMatcher) +{ + return AllOf(SetExpressionProperty(propertyMatcher), SetExpressionExpression(expressionMatcher)); +} + +class ModelResourceManagement : public testing::Test +{ +protected: + ModelResourceManagement() + { + model.attachView(&viewMock); + rootNode = model.rootModelNode(); + auto itemId = rootNode.metaInfo().id(); + projectStorageMock.createProperty(itemId, + "layer.effect", + QmlDesigner::Storage::PropertyDeclarationTraits::IsList, + itemId); + } + + auto createNodeWithParent(const QmlDesigner::TypeName &typeName, + QmlDesigner::NodeAbstractProperty parentProperty, + const QString &id = {}) + { + auto node = model.createModelNode(typeName); + parentProperty.reparentHere(node); + if (id.size()) + node.setIdWithoutRefactoring(id); + + return node; + } + +protected: + NiceMock viewMock; + NiceMock projectStorageMock; + QmlDesigner::ModelResourceManagement management; + QmlDesigner::Model model{projectStorageMock, "QtQuick.Item"}; + ModelNode rootNode; +}; + +TEST_F(ModelResourceManagement, remove_property) +{ + auto layerEnabledProperty = rootNode.variantProperty("layer.enabled"); + layerEnabledProperty.setValue(true); + + auto resources = management.removeProperties({layerEnabledProperty}, &model); + + ASSERT_THAT(resources.removeProperties, Contains(layerEnabledProperty)); +} + +TEST_F(ModelResourceManagement, remove_multiple_properties) +{ + auto layerEnabledProperty = rootNode.variantProperty("layer.enabled"); + layerEnabledProperty.setValue(true); + auto layerHiddenProperty = rootNode.variantProperty("layer.hidden"); + layerHiddenProperty.setValue(true); + + auto resources = management.removeProperties({layerEnabledProperty, layerHiddenProperty}, &model); + + ASSERT_THAT(resources.removeProperties, IsSupersetOf({layerEnabledProperty, layerHiddenProperty})); +} + +TEST_F(ModelResourceManagement, remove_node) +{ + auto node = createNodeWithParent("QtQuick.Item", rootNode.defaultNodeListProperty()); + + auto resources = management.removeNodes({node}, &model); + + ASSERT_THAT(resources.removeModelNodes, Contains(node)); +} + +TEST_F(ModelResourceManagement, remove_multiple_nodes) +{ + auto node = createNodeWithParent("QtQuick.Item", rootNode.defaultNodeListProperty()); + auto node2 = createNodeWithParent("QtQuick.Item", rootNode.defaultNodeListProperty()); + + auto resources = management.removeNodes({node, node2}, &model); + + ASSERT_THAT(resources.removeModelNodes, IsSupersetOf({node, node2})); +} + +TEST_F(ModelResourceManagement, remove_multiple_nodes_once) +{ + auto node = createNodeWithParent("QtQuick.Item", rootNode.defaultNodeListProperty()); + auto node2 = createNodeWithParent("QtQuick.Item", rootNode.defaultNodeListProperty()); + + auto resources = management.removeNodes({node, node2, node, node2}, &model); + + ASSERT_THAT(resources.removeModelNodes, UnorderedElementsAre(node, node2)); +} + +TEST_F(ModelResourceManagement, dont_remove_child_nodes) +{ + auto node = createNodeWithParent("QtQuick.Item", rootNode.defaultNodeListProperty()); + auto childNode = createNodeWithParent("QtQuick.Item", node.defaultNodeListProperty()); + + auto resources = management.removeNodes({node}, &model); + + ASSERT_THAT(resources.removeModelNodes, Not(Contains(childNode))); +} + +TEST_F(ModelResourceManagement, remove_property_layer_enabled) +{ + auto node = createNodeWithParent("QtQuick.Item", rootNode.nodeProperty("layer.effect")); + auto layerEnabledProperty = rootNode.variantProperty("layer.enabled"); + layerEnabledProperty.setValue(true); + + auto resources = management.removeNodes({node}, &model); + + ASSERT_THAT(resources.removeProperties, Contains(layerEnabledProperty)); +} + +TEST_F(ModelResourceManagement, remove_property_layer_enabled_if_layer_effect_property_is_removed) +{ + auto layerEffectProperty = rootNode.nodeProperty("layer.effect"); + auto node = createNodeWithParent("QtQuick.Item", layerEffectProperty); + auto layerEnabledProperty = rootNode.variantProperty("layer.enabled"); + layerEnabledProperty.setValue(true); + + auto resources = management.removeProperties({layerEffectProperty}, &model); + + ASSERT_THAT(resources.removeProperties, Contains(layerEnabledProperty)); +} + +TEST_F(ModelResourceManagement, dont_remove_property_layer_enabled_if_not_exists) +{ + auto node = createNodeWithParent("QtQuick.Item", rootNode.nodeProperty("layer.effect")); + auto layerEnabledProperty = rootNode.variantProperty("layer.enabled"); + + auto resources = management.removeNodes({node}, &model); + + ASSERT_THAT(resources.removeProperties, Not(Contains(layerEnabledProperty))); +} + +TEST_F(ModelResourceManagement, remove_property_with_id) +{ + auto fooNode = createNodeWithParent("QtQuick.Item", rootNode.defaultNodeListProperty(), "foo"); + auto property = rootNode.bindingProperty("foo"); + property.setDynamicTypeNameAndExpression("var", "foo"); + + auto resources = management.removeNodes({fooNode}, &model); + + ASSERT_THAT(resources.removeProperties, Contains(property)); +} + +TEST_F(ModelResourceManagement, remove_property_with_id_in_complex_expression) +{ + auto fooNode = createNodeWithParent("QtQuick.Item", rootNode.defaultNodeListProperty(), "foo"); + auto foobarProperty = rootNode.bindingProperty("foo"); + foobarProperty.setDynamicTypeNameAndExpression("var", "foo.x+bar.y"); + auto resources = management.removeNodes({fooNode}, &model); + + ASSERT_THAT(resources.removeProperties, Contains(foobarProperty)); +} + +TEST_F(ModelResourceManagement, dont_remove_property_without_id) +{ + auto fooNode = createNodeWithParent("QtQuick.Item", rootNode.defaultNodeListProperty(), "foo"); + auto barNode = createNodeWithParent("QtQuick.Item", rootNode.defaultNodeListProperty(), "bar"); + auto fooProperty = rootNode.bindingProperty("foo"); + fooProperty.setDynamicTypeNameAndExpression("var", "foo.x"); + + auto resources = management.removeNodes({barNode}, &model); + + ASSERT_THAT(resources.removeProperties, Not(Contains(fooProperty))); +} + +TEST_F(ModelResourceManagement, remove_property_with_id_once) +{ + auto fooNode = createNodeWithParent("QtQuick.Item", rootNode.defaultNodeListProperty(), "foo"); + auto barNode = createNodeWithParent("QtQuick.Item", rootNode.defaultNodeListProperty(), "bar"); + auto foobarProperty = rootNode.bindingProperty("foo"); + foobarProperty.setDynamicTypeNameAndExpression("var", "foo.x+bar.y"); + + auto resources = management.removeNodes({fooNode, barNode}, &model); + + ASSERT_THAT(resources.removeProperties, ElementsAre(foobarProperty)); +} + +TEST_F(ModelResourceManagement, remove_alias_property_with_id) +{ + auto fooNode = createNodeWithParent("QtQuick.Item", rootNode.defaultNodeListProperty(), "foo"); + auto property = rootNode.bindingProperty("foo"); + property.setDynamicTypeNameAndExpression("alias", "foo"); + + auto resources = management.removeNodes({fooNode}, &model); + + ASSERT_THAT(resources.removeProperties, Contains(property)); +} + +TEST_F(ModelResourceManagement, dont_remove_property_with_different_id_which_contains_id_string) +{ + auto fooNode = createNodeWithParent("QtQuick.Item", rootNode.defaultNodeListProperty(), "foo"); + auto property = rootNode.bindingProperty("foo"); + property.setDynamicTypeNameAndExpression("var", "foobar+barfoo"); + + auto resources = management.removeNodes({fooNode}, &model); + + ASSERT_THAT(resources.removeProperties, Not(Contains(property))); +} + +struct TargetData +{ + QmlDesigner::TypeName targetType; + QmlDesigner::TypeName type; + QmlDesigner::PropertyName propertyName; + + // printer function for TargetData - don't remove + friend std::ostream &operator<<(std::ostream &os, const TargetData &data) + { + return os << "(" << data.targetType << ", " << data.type << ")"; + } +}; + +class ForTarget : public ModelResourceManagement, + public testing::WithParamInterface +{ +protected: + TargetData parameters = GetParam(); + ModelNode fooNode = createNodeWithParent(parameters.targetType, + rootNode.defaultNodeListProperty(), + "foo"); + ModelNode barNode = createNodeWithParent("QtQuick.Item", rootNode.defaultNodeListProperty(), "bar"); + ModelNode source = createNodeWithParent(parameters.type, + rootNode.defaultNodeListProperty(), + "source1"); + ModelNode source2 = createNodeWithParent(parameters.type, + rootNode.defaultNodeListProperty(), + "source2"); + QmlDesigner::BindingProperty sourceTargetProperty = source.bindingProperty(parameters.propertyName); + QmlDesigner::BindingProperty source2TargetProperty = source2.bindingProperty( + parameters.propertyName); +}; + +INSTANTIATE_TEST_SUITE_P( + ModelResourceManagement, + ForTarget, + testing::Values(TargetData{"QtQuick.Item", "QtQuick.PropertyChanges", "target"}, + TargetData{"QtQuick.Item", "QtQuick.Timeline.KeyframeGroup", "target"}, + TargetData{"FlowView.FlowTransition", "FlowView.FlowActionArea", "target"}, + TargetData{"QtQuick.Item", "QtQuick.PropertyAnimation", "target"}, + TargetData{"FlowView.FlowItem", "FlowView.FlowTransition", "to"}, + TargetData{"FlowView.FlowItem", "FlowView.FlowTransition", "from"})); + +TEST_P(ForTarget, remove) +{ + sourceTargetProperty.setExpression("foo"); + source2TargetProperty.setExpression("foo"); + + auto resources = management.removeNodes({fooNode}, &model); + + ASSERT_THAT(resources.removeModelNodes, IsSupersetOf({source, source2})); +} + +TEST_P(ForTarget, dont_remove_for_different_target) +{ + sourceTargetProperty.setExpression("bar"); + + auto resources = management.removeNodes({fooNode}, &model); + + ASSERT_THAT(resources.removeModelNodes, Not(Contains(source))); +} + +TEST_P(ForTarget, dont_remove_key_if_target_is_not_set) +{ + auto resources = management.removeNodes({fooNode}, &model); + + ASSERT_THAT(resources.removeModelNodes, Not(Contains(source))); +} + +TEST_P(ForTarget, dont_remove_if_target_cannot_be_resolved) +{ + sourceTargetProperty.setExpression("not_exists"); + + auto resources = management.removeNodes({fooNode}, &model); + + ASSERT_THAT(resources.removeModelNodes, Not(Contains(source))); +} + +class ForTargets : public ModelResourceManagement, + public testing::WithParamInterface +{ +protected: + TargetData parameters = GetParam(); + ModelNode fooNode = createNodeWithParent(parameters.targetType, + rootNode.defaultNodeListProperty(), + "foo"); + ModelNode barNode = createNodeWithParent(parameters.targetType, + rootNode.defaultNodeListProperty(), + "bar"); + ModelNode yiNode = createNodeWithParent(parameters.targetType, + rootNode.defaultNodeListProperty(), + "yi"); + ModelNode erNode = createNodeWithParent(parameters.targetType, + rootNode.defaultNodeListProperty(), + "er"); + ModelNode sanNode = createNodeWithParent(parameters.targetType, + rootNode.defaultNodeListProperty(), + "san"); + ModelNode source = createNodeWithParent(parameters.type, + rootNode.defaultNodeListProperty(), + "source1"); + ModelNode source2 = createNodeWithParent(parameters.type, + rootNode.defaultNodeListProperty(), + "source2"); + QmlDesigner::BindingProperty sourceTargetsProperty = source.bindingProperty( + parameters.propertyName); + QmlDesigner::BindingProperty source2TargetsProperty = source2.bindingProperty( + parameters.propertyName); +}; + +INSTANTIATE_TEST_SUITE_P( + ModelResourceManagement, + ForTargets, + testing::Values(TargetData{"FlowView.FlowTransition", "FlowView.FlowDecision", "targets"}, + TargetData{"FlowView.FlowTransition", "FlowView.FlowWildcard", "targets"}, + TargetData{"QtQuick.Item", "QtQuick.PropertyAnimation", "targets"})); + +TEST_P(ForTargets, remove) +{ + sourceTargetsProperty.setExpression("[foo]"); + source2TargetsProperty.setExpression("[foo]"); + + auto resources = management.removeNodes({fooNode}, &model); + + ASSERT_THAT(resources.removeModelNodes, IsSupersetOf({source, source2})); +} + +TEST_P(ForTargets, handle_invalid_binding) +{ + sourceTargetsProperty.setExpression("[foo, broken]"); + source2TargetsProperty.setExpression("[foo, fail]"); + + auto resources = management.removeNodes({fooNode}, &model); + + ASSERT_THAT(resources.removeModelNodes, IsSupersetOf({source, source2})); +} + +TEST_P(ForTargets, remove_indirectly) +{ + auto parenNode = createNodeWithParent("QtQuick.Item", rootNode.defaultNodeListProperty(), "hoo"); + parenNode.defaultNodeListProperty().reparentHere(fooNode); + parenNode.defaultNodeListProperty().reparentHere(barNode); + sourceTargetsProperty.setExpression("[foo, bar]"); + source2TargetsProperty.setExpression("[bar, foo]"); + + auto resources = management.removeNodes({parenNode}, &model); + + ASSERT_THAT(resources.removeModelNodes, IsSupersetOf({source, source2})); +} + +TEST_P(ForTargets, dont_remove_target_if_there_are_still_an_other_targets) +{ + sourceTargetsProperty.setExpression("[foo, bar]"); + source2TargetsProperty.setExpression("[foo, bar]"); + + auto resources = management.removeNodes({fooNode}, &model); + + ASSERT_THAT(resources.removeModelNodes, AllOf(Not(Contains(source)), Not(Contains(source2)))); +} + +TEST_P(ForTargets, change_expression_if_there_are_still_an_other_targets) +{ + sourceTargetsProperty.setExpression("[foo, bar]"); + source2TargetsProperty.setExpression("[foo, bar]"); + + auto resources = management.removeNodes({fooNode}, &model); + + ASSERT_THAT(resources.setExpressions, + UnorderedElementsAre(SetExpression(sourceTargetsProperty, "[bar]"), + SetExpression(source2TargetsProperty, "[bar]"))); +} + +TEST_P(ForTargets, dont_change_order_in_expression) +{ + sourceTargetsProperty.setExpression("[yi, foo, er, san]"); + + auto resources = management.removeNodes({fooNode}, &model); + + ASSERT_THAT(resources.setExpressions, + UnorderedElementsAre(SetExpression(sourceTargetsProperty, "[yi, er, san]"))); +} + +struct StateData +{ + QmlDesigner::TypeName type; + QmlDesigner::PropertyName propertyName; + + // printer function for TargetData - don't remove + friend std::ostream &operator<<(std::ostream &os, const StateData &data) + { + return os << "(" << data.type << ", " << data.propertyName << ")"; + } +}; + +class ForState : public ModelResourceManagement, + public testing::WithParamInterface +{ +protected: + ModelNode createStateWithParent(QmlDesigner::NodeAbstractProperty parentProperty, + const QString &name) + { + ModelNode stateNode = createNodeWithParent("QtQuick.State", parentProperty, name); + stateNode.variantProperty("name").setValue(name); + + return stateNode; + } + +protected: + StateData parameters = GetParam(); + ModelNode fooNode = createStateWithParent(rootNode.defaultNodeListProperty(), "foo"); + ModelNode barNode = createStateWithParent(rootNode.defaultNodeListProperty(), "bar"); + ModelNode yiNode = createStateWithParent(rootNode.defaultNodeListProperty(), "yi"); + ModelNode erNode = createStateWithParent(rootNode.defaultNodeListProperty(), "er"); + ModelNode sanNode = createStateWithParent(rootNode.defaultNodeListProperty(), "san"); + ModelNode source = createNodeWithParent(parameters.type, + rootNode.defaultNodeListProperty(), + "source1"); + ModelNode source2 = createNodeWithParent(parameters.type, + rootNode.defaultNodeListProperty(), + "source2"); + QmlDesigner::VariantProperty sourceStateProperty = source.variantProperty(parameters.propertyName); + QmlDesigner::VariantProperty source2StateProperty = source2.variantProperty( + parameters.propertyName); +}; + +INSTANTIATE_TEST_SUITE_P(ModelResourceManagement, + ForState, + testing::Values(StateData{"QtQuick.Transition", "from"}, + StateData{"QtQuick.Transition", "to"})); + +TEST_P(ForState, remove) +{ + sourceStateProperty.setValue(QString{"foo"}); + source2StateProperty.setValue(QString{"foo"}); + + auto resources = management.removeNodes({fooNode}, &model); + + ASSERT_THAT(resources.removeModelNodes, IsSupersetOf({source, source2})); +} + +TEST_P(ForState, dont_remove_for_star_state) +{ + fooNode.variantProperty("name").setValue("*"); + sourceStateProperty.setValue(QString{"*"}); + + auto resources = management.removeNodes({fooNode}, &model); + + ASSERT_THAT(resources.removeModelNodes, Not(Contains(source))); +} + +TEST_P(ForState, dont_remove_for_empty_state) +{ + fooNode.variantProperty("name").setValue(""); + sourceStateProperty.setValue(QString{""}); + + auto resources = management.removeNodes({fooNode}, &model); + + ASSERT_THAT(resources.removeModelNodes, Not(Contains(source))); +} + +TEST_P(ForState, dont_remove_for_different_state) +{ + sourceStateProperty.setValue(QString{"foo"}); + source2StateProperty.setValue(QString{"bar"}); + + auto resources = management.removeNodes({fooNode}, &model); + + ASSERT_THAT(resources.removeModelNodes, IsSupersetOf({source})); +} + +} // namespace diff --git a/tests/unit/unittest/nodelistproperty-test.cpp b/tests/unit/tests/unittests/model/nodelistproperty-test.cpp similarity index 81% rename from tests/unit/unittest/nodelistproperty-test.cpp rename to tests/unit/tests/unittests/model/nodelistproperty-test.cpp index 36a8dcb6df7..2fa80aa9f3a 100644 --- a/tests/unit/unittest/nodelistproperty-test.cpp +++ b/tests/unit/tests/unittests/model/nodelistproperty-test.cpp @@ -1,9 +1,9 @@ // Copyright (C) 2021 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "abstractviewmock.h" -#include "googletest.h" -#include "projectstoragemock.h" +#include +#include +#include #include #include @@ -89,14 +89,14 @@ protected: ModelNode node5; }; -TEST_F(NodeListProperty, BeginAndEndItertors) +TEST_F(NodeListProperty, begin_and_end_itertors) { std::vector nodes{nodeListProperty.begin(), nodeListProperty.end()}; ASSERT_THAT(nodes, ElementsAre(node1, node2, node3, node4, node5)); } -TEST_F(NodeListProperty, LoopOverRange) +TEST_F(NodeListProperty, loop_over_range) { std::vector nodes; @@ -106,7 +106,7 @@ TEST_F(NodeListProperty, LoopOverRange) ASSERT_THAT(nodes, ElementsAre(node1, node2, node3, node4, node5)); } -TEST_F(NodeListProperty, NextIterator) +TEST_F(NodeListProperty, next_iterator) { auto begin = nodeListProperty.begin(); @@ -115,7 +115,7 @@ TEST_F(NodeListProperty, NextIterator) ASSERT_THAT(nodes(nextIterator, nodeListProperty.end()), ElementsAre(node2, node3, node4, node5)); } -TEST_F(NodeListProperty, PreviousIterator) +TEST_F(NodeListProperty, previous_iterator) { auto end = nodeListProperty.end(); @@ -125,7 +125,7 @@ TEST_F(NodeListProperty, PreviousIterator) ElementsAre(node1, node2, node3, node4)); } -TEST_F(NodeListProperty, IncrementIterator) +TEST_F(NodeListProperty, increment_iterator) { auto incrementIterator = nodeListProperty.begin(); @@ -135,7 +135,7 @@ TEST_F(NodeListProperty, IncrementIterator) ElementsAre(node2, node3, node4, node5)); } -TEST_F(NodeListProperty, IncrementIteratorReturnsIterator) +TEST_F(NodeListProperty, increment_iterator_returns_iterator) { auto begin = nodeListProperty.begin(); @@ -145,7 +145,7 @@ TEST_F(NodeListProperty, IncrementIteratorReturnsIterator) ElementsAre(node2, node3, node4, node5)); } -TEST_F(NodeListProperty, PostIncrementIterator) +TEST_F(NodeListProperty, post_increment_iterator) { auto postIncrementIterator = nodeListProperty.begin(); @@ -155,7 +155,7 @@ TEST_F(NodeListProperty, PostIncrementIterator) ElementsAre(node2, node3, node4, node5)); } -TEST_F(NodeListProperty, PostIncrementIteratorReturnsPreincrementIterator) +TEST_F(NodeListProperty, post_increment_iterator_returns_preincrement_iterator) { auto begin = nodeListProperty.begin(); @@ -165,7 +165,7 @@ TEST_F(NodeListProperty, PostIncrementIteratorReturnsPreincrementIterator) ElementsAre(node1, node2, node3, node4, node5)); } -TEST_F(NodeListProperty, DecrementIterator) +TEST_F(NodeListProperty, decrement_iterator) { auto decrementIterator = nodeListProperty.end(); @@ -175,7 +175,7 @@ TEST_F(NodeListProperty, DecrementIterator) ElementsAre(node1, node2, node3, node4)); } -TEST_F(NodeListProperty, DerementIteratorReturnsIterator) +TEST_F(NodeListProperty, derement_iterator_returns_iterator) { auto end = nodeListProperty.end(); @@ -185,7 +185,7 @@ TEST_F(NodeListProperty, DerementIteratorReturnsIterator) ElementsAre(node1, node2, node3, node4)); } -TEST_F(NodeListProperty, PostDecrementIterator) +TEST_F(NodeListProperty, post_decrement_iterator) { auto postDecrementIterator = nodeListProperty.end(); @@ -195,7 +195,7 @@ TEST_F(NodeListProperty, PostDecrementIterator) ElementsAre(node1, node2, node3, node4)); } -TEST_F(NodeListProperty, PostDecrementIteratorReturnsPredecrementIterator) +TEST_F(NodeListProperty, post_decrement_iterator_returns_predecrement_iterator) { auto end = nodeListProperty.end(); @@ -205,7 +205,7 @@ TEST_F(NodeListProperty, PostDecrementIteratorReturnsPredecrementIterator) ElementsAre(node1, node2, node3, node4, node5)); } -TEST_F(NodeListProperty, IncrementIteratorByTwo) +TEST_F(NodeListProperty, increment_iterator_by_two) { auto incrementIterator = nodeListProperty.begin(); @@ -214,7 +214,7 @@ TEST_F(NodeListProperty, IncrementIteratorByTwo) ASSERT_THAT(nodes(incrementIterator, nodeListProperty.end()), ElementsAre(node3, node4, node5)); } -TEST_F(NodeListProperty, IncrementIteratorByTwoReturnsIterator) +TEST_F(NodeListProperty, increment_iterator_by_two_returns_iterator) { auto begin = nodeListProperty.begin(); @@ -223,7 +223,7 @@ TEST_F(NodeListProperty, IncrementIteratorByTwoReturnsIterator) ASSERT_THAT(nodes(incrementIterator, nodeListProperty.end()), ElementsAre(node3, node4, node5)); } -TEST_F(NodeListProperty, DecrementIteratorByTwo) +TEST_F(NodeListProperty, decrement_iterator_by_two) { auto decrementIterator = nodeListProperty.end(); @@ -232,7 +232,7 @@ TEST_F(NodeListProperty, DecrementIteratorByTwo) ASSERT_THAT(nodes(nodeListProperty.begin(), decrementIterator), ElementsAre(node1, node2, node3)); } -TEST_F(NodeListProperty, DecrementIteratorByTwoReturnsIterator) +TEST_F(NodeListProperty, decrement_iterator_by_two_returns_iterator) { auto end = nodeListProperty.end(); @@ -241,7 +241,7 @@ TEST_F(NodeListProperty, DecrementIteratorByTwoReturnsIterator) ASSERT_THAT(nodes(nodeListProperty.begin(), decrementIterator), ElementsAre(node1, node2, node3)); } -TEST_F(NodeListProperty, AccessIterator) +TEST_F(NodeListProperty, access_iterator) { auto iterator = std::next(nodeListProperty.begin(), 3); @@ -250,7 +250,7 @@ TEST_F(NodeListProperty, AccessIterator) ASSERT_THAT(nodes(accessIterator, nodeListProperty.end()), ElementsAre(node3, node4, node5)); } -TEST_F(NodeListProperty, AddIteratorByIndexSecondOperand) +TEST_F(NodeListProperty, add_iterator_by_index_second_operand) { auto begin = nodeListProperty.begin(); @@ -259,7 +259,7 @@ TEST_F(NodeListProperty, AddIteratorByIndexSecondOperand) ASSERT_THAT(nodes(addedIterator, nodeListProperty.end()), ElementsAre(node3, node4, node5)); } -TEST_F(NodeListProperty, AddIteratorByIndexFirstOperand) +TEST_F(NodeListProperty, add_iterator_by_index_first_operand) { auto begin = nodeListProperty.begin(); @@ -268,7 +268,7 @@ TEST_F(NodeListProperty, AddIteratorByIndexFirstOperand) ASSERT_THAT(nodes(addedIterator, nodeListProperty.end()), ElementsAre(node3, node4, node5)); } -TEST_F(NodeListProperty, SubtractIterator) +TEST_F(NodeListProperty, subtract_iterator) { auto end = nodeListProperty.end(); @@ -277,7 +277,7 @@ TEST_F(NodeListProperty, SubtractIterator) ASSERT_THAT(nodes(subtractedIterator, nodeListProperty.end()), ElementsAre(node3, node4, node5)); } -TEST_F(NodeListProperty, CompareEqualIteratorAreEqual) +TEST_F(NodeListProperty, compare_equal_iterator_are_equal) { auto first = nodeListProperty.begin(); auto second = nodeListProperty.begin(); @@ -287,7 +287,7 @@ TEST_F(NodeListProperty, CompareEqualIteratorAreEqual) ASSERT_TRUE(isEqual); } -TEST_F(NodeListProperty, CompareEqualIteratorAreNotEqual) +TEST_F(NodeListProperty, compare_equal_iterator_are_not_equal) { auto first = nodeListProperty.begin(); auto second = std::next(nodeListProperty.begin()); @@ -297,7 +297,7 @@ TEST_F(NodeListProperty, CompareEqualIteratorAreNotEqual) ASSERT_FALSE(isEqual); } -TEST_F(NodeListProperty, CompareUnqualIteratorAreEqual) +TEST_F(NodeListProperty, compare_unqual_iterator_are_equal) { auto first = nodeListProperty.begin(); auto second = nodeListProperty.begin(); @@ -307,7 +307,7 @@ TEST_F(NodeListProperty, CompareUnqualIteratorAreEqual) ASSERT_FALSE(isUnequal); } -TEST_F(NodeListProperty, CompareUnequalIteratorAreNotEqual) +TEST_F(NodeListProperty, compare_unequal_iterator_are_not_equal) { auto first = nodeListProperty.begin(); auto second = std::next(nodeListProperty.begin()); @@ -317,7 +317,7 @@ TEST_F(NodeListProperty, CompareUnequalIteratorAreNotEqual) ASSERT_TRUE(isUnequal); } -TEST_F(NodeListProperty, CompareLessIteratorAreNotLessIfEqual) +TEST_F(NodeListProperty, compare_less_iterator_are_not_less_if_equal) { auto first = nodeListProperty.begin(); auto second = nodeListProperty.begin(); @@ -327,7 +327,7 @@ TEST_F(NodeListProperty, CompareLessIteratorAreNotLessIfEqual) ASSERT_FALSE(isLess); } -TEST_F(NodeListProperty, CompareLessIteratorAreNotLessIfGreater) +TEST_F(NodeListProperty, compare_less_iterator_are_not_less_if_greater) { auto first = std::next(nodeListProperty.begin()); auto second = nodeListProperty.begin(); @@ -337,7 +337,7 @@ TEST_F(NodeListProperty, CompareLessIteratorAreNotLessIfGreater) ASSERT_FALSE(isLess); } -TEST_F(NodeListProperty, CompareLessIteratorAreLessIfLess) +TEST_F(NodeListProperty, compare_less_iterator_are_less_if_less) { auto first = nodeListProperty.begin(); auto second = std::next(nodeListProperty.begin()); @@ -347,7 +347,7 @@ TEST_F(NodeListProperty, CompareLessIteratorAreLessIfLess) ASSERT_TRUE(isLess); } -TEST_F(NodeListProperty, CompareLessEqualIteratorAreLessEqualIfEqual) +TEST_F(NodeListProperty, compare_less_equal_iterator_are_less_equal_if_equal) { auto first = nodeListProperty.begin(); auto second = nodeListProperty.begin(); @@ -357,7 +357,7 @@ TEST_F(NodeListProperty, CompareLessEqualIteratorAreLessEqualIfEqual) ASSERT_TRUE(isLessEqual); } -TEST_F(NodeListProperty, CompareLessEqualIteratorAreNotLessEqualIfGreater) +TEST_F(NodeListProperty, compare_less_equal_iterator_are_not_less_equal_if_greater) { auto first = std::next(nodeListProperty.begin()); auto second = nodeListProperty.begin(); @@ -367,7 +367,7 @@ TEST_F(NodeListProperty, CompareLessEqualIteratorAreNotLessEqualIfGreater) ASSERT_FALSE(isLessEqual); } -TEST_F(NodeListProperty, CompareLessEqualIteratorAreLessEqualIfLess) +TEST_F(NodeListProperty, compare_less_equal_iterator_are_less_equal_if_less) { auto first = nodeListProperty.begin(); auto second = std::next(nodeListProperty.begin()); @@ -377,7 +377,7 @@ TEST_F(NodeListProperty, CompareLessEqualIteratorAreLessEqualIfLess) ASSERT_TRUE(isLessEqual); } -TEST_F(NodeListProperty, CompareGreaterIteratorAreGreaterIfEqual) +TEST_F(NodeListProperty, compare_greater_iterator_are_greater_if_equal) { auto first = nodeListProperty.begin(); auto second = nodeListProperty.begin(); @@ -387,7 +387,7 @@ TEST_F(NodeListProperty, CompareGreaterIteratorAreGreaterIfEqual) ASSERT_FALSE(isGreater); } -TEST_F(NodeListProperty, CompareGreaterIteratorAreGreaterIfGreater) +TEST_F(NodeListProperty, compare_greater_iterator_are_greater_if_greater) { auto first = std::next(nodeListProperty.begin()); auto second = nodeListProperty.begin(); @@ -397,7 +397,7 @@ TEST_F(NodeListProperty, CompareGreaterIteratorAreGreaterIfGreater) ASSERT_TRUE(isGreater); } -TEST_F(NodeListProperty, CompareGreaterIteratorAreNotGreaterIfLess) +TEST_F(NodeListProperty, compare_greater_iterator_are_not_greater_if_less) { auto first = nodeListProperty.begin(); auto second = std::next(nodeListProperty.begin()); @@ -407,7 +407,7 @@ TEST_F(NodeListProperty, CompareGreaterIteratorAreNotGreaterIfLess) ASSERT_FALSE(isGreater); } -TEST_F(NodeListProperty, CompareGreaterEqualIteratorAreGreaterEqualIfEqual) +TEST_F(NodeListProperty, compare_greater_equal_iterator_are_greater_equal_if_equal) { auto first = nodeListProperty.begin(); auto second = nodeListProperty.begin(); @@ -417,7 +417,7 @@ TEST_F(NodeListProperty, CompareGreaterEqualIteratorAreGreaterEqualIfEqual) ASSERT_TRUE(isGreaterEqual); } -TEST_F(NodeListProperty, CompareGreaterEqualIteratorAreGreaterEqualIfGreater) +TEST_F(NodeListProperty, compare_greater_equal_iterator_are_greater_equal_if_greater) { auto first = std::next(nodeListProperty.begin()); auto second = nodeListProperty.begin(); @@ -427,7 +427,7 @@ TEST_F(NodeListProperty, CompareGreaterEqualIteratorAreGreaterEqualIfGreater) ASSERT_TRUE(isGreaterEqual); } -TEST_F(NodeListProperty, CompareGreaterEqualIteratorAreNotGreaterEqualIfLess) +TEST_F(NodeListProperty, compare_greater_equal_iterator_are_not_greater_equal_if_less) { auto first = nodeListProperty.begin(); auto second = std::next(nodeListProperty.begin()); @@ -437,7 +437,7 @@ TEST_F(NodeListProperty, CompareGreaterEqualIteratorAreNotGreaterEqualIfLess) ASSERT_FALSE(isGreaterEqual); } -TEST_F(NodeListProperty, DereferenceIterator) +TEST_F(NodeListProperty, dereference_iterator) { auto iterator = std::next(nodeListProperty.begin()); @@ -446,7 +446,7 @@ TEST_F(NodeListProperty, DereferenceIterator) ASSERT_THAT(node, Eq(node2)); } -TEST_F(NodeListProperty, IterSwap) +TEST_F(NodeListProperty, iter_swap) { auto first = std::next(nodeListProperty.begin(), 2); auto second = nodeListProperty.begin(); @@ -456,7 +456,7 @@ TEST_F(NodeListProperty, IterSwap) ASSERT_THAT(nodes(), ElementsAre(node3, node2, node1, node4, node5)); } -TEST_F(NodeListProperty, Rotate) +TEST_F(NodeListProperty, rotate) { auto first = std::next(nodeListProperty.begin()); auto newFirst = std::next(nodeListProperty.begin(), 2); @@ -467,7 +467,7 @@ TEST_F(NodeListProperty, Rotate) ASSERT_THAT(nodes(), ElementsAre(node1, node3, node4, node2, node5)); } -TEST_F(NodeListProperty, RotateCallsNodeOrderedChanged) +TEST_F(NodeListProperty, rotate_calls_node_ordered_changed) { auto first = std::next(nodeListProperty.begin()); auto newFirst = std::next(nodeListProperty.begin(), 2); @@ -478,7 +478,7 @@ TEST_F(NodeListProperty, RotateCallsNodeOrderedChanged) nodeListProperty.rotate(first, newFirst, last); } -TEST_F(NodeListProperty, RotateRange) +TEST_F(NodeListProperty, rotate_range) { auto newFirst = std::prev(nodeListProperty.end(), 2); @@ -487,7 +487,7 @@ TEST_F(NodeListProperty, RotateRange) ASSERT_THAT(nodes(), ElementsAre(node4, node5, node1, node2, node3)); } -TEST_F(NodeListProperty, RotateReturnsIterator) +TEST_F(NodeListProperty, rotate_returns_iterator) { auto first = std::next(nodeListProperty.begin()); auto newFirst = std::next(nodeListProperty.begin(), 2); @@ -498,7 +498,7 @@ TEST_F(NodeListProperty, RotateReturnsIterator) ASSERT_THAT(iterator, Eq(first + (last - newFirst))); } -TEST_F(NodeListProperty, RotateRangeReturnsIterator) +TEST_F(NodeListProperty, rotate_range_returns_iterator) { auto newFirst = std::prev(nodeListProperty.end(), 2); @@ -507,7 +507,7 @@ TEST_F(NodeListProperty, RotateRangeReturnsIterator) ASSERT_THAT(iterator, Eq(nodeListProperty.begin() + (nodeListProperty.end() - newFirst))); } -TEST_F(NodeListProperty, Reverse) +TEST_F(NodeListProperty, reverse) { auto first = std::next(nodeListProperty.begin()); auto last = std::prev(nodeListProperty.end()); @@ -517,7 +517,7 @@ TEST_F(NodeListProperty, Reverse) ASSERT_THAT(nodes(), ElementsAre(node1, node4, node3, node2, node5)); } -TEST_F(NodeListProperty, ReverseCallsNodeOrderedChanged) +TEST_F(NodeListProperty, reverse_calls_node_ordered_changed) { auto first = std::next(nodeListProperty.begin()); auto last = std::prev(nodeListProperty.end()); diff --git a/tests/unit/tests/unittests/projectstorage/CMakeLists.txt b/tests/unit/tests/unittests/projectstorage/CMakeLists.txt new file mode 100644 index 00000000000..5c3fd4011e2 --- /dev/null +++ b/tests/unit/tests/unittests/projectstorage/CMakeLists.txt @@ -0,0 +1,33 @@ +# qmldesigner/designercore/projectstorage +extend_qtc_test(unittest + SOURCES + directorypathcompressor-test.cpp + filestatuscache-test.cpp + modulescanner-test.cpp + projectstorage-test.cpp + projectstoragepathwatcher-test.cpp + projectstorageupdater-test.cpp + sourcepath-test.cpp + sourcepathcache-test.cpp + sourcepathview-test.cpp + storagecache-test.cpp +) + +extend_qtc_test(unittest + CONDITION TARGET Qt6::QmlDomPrivate AND TARGET Qt6::QmlCompilerPrivate AND Qt6_VERSION VERSION_GREATER_EQUAL 6.5.0 AND Qt6_VERSION VERSION_LESS 6.6.0 + DEPENDS Qt6::QmlDomPrivate Qt6::QmlCompilerPrivate + SOURCES + qmldocumentparser-test.cpp + qmltypesparser-test.cpp +) +extend_qtc_test(unittest + CONDITION TARGET Qt6::QmlDomPrivate AND TARGET Qt6::QmlCompilerPrivate AND Qt6_VERSION VERSION_GREATER_EQUAL 6.5.0 AND Qt6_VERSION VERSION_LESS 6.6.0 + SOURCES_PREFIX "${QmlDesignerDir}/designercore" + DEPENDS Qt6::QmlDomPrivate Qt6::QmlCompilerPrivate + DEFINES QDS_BUILD_QMLPARSER + SOURCES + projectstorage/qmldocumentparser.cpp projectstorage/qmldocumentparser.h + projectstorage/qmltypesparser.cpp projectstorage/qmltypesparser.h +) + +unittest_copy_data_folder() diff --git a/tests/unit/unittest/data/modulescanner/Example/qmldir b/tests/unit/tests/unittests/projectstorage/data/modulescanner/Example/qmldir similarity index 100% rename from tests/unit/unittest/data/modulescanner/Example/qmldir rename to tests/unit/tests/unittests/projectstorage/data/modulescanner/Example/qmldir diff --git a/tests/unit/unittest/data/qml/QmlTime/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QmlTime/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QmlTime/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QmlTime/qmldir diff --git a/tests/unit/unittest/data/qml/Qt/labs/animation/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/Qt/labs/animation/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/Qt/labs/animation/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/Qt/labs/animation/qmldir diff --git a/tests/unit/unittest/data/qml/Qt/labs/folderlistmodel/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/Qt/labs/folderlistmodel/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/Qt/labs/folderlistmodel/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/Qt/labs/folderlistmodel/qmldir diff --git a/tests/unit/unittest/data/qml/Qt/labs/lottieqt/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/Qt/labs/lottieqt/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/Qt/labs/lottieqt/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/Qt/labs/lottieqt/qmldir diff --git a/tests/unit/unittest/data/qml/Qt/labs/platform/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/Qt/labs/platform/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/Qt/labs/platform/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/Qt/labs/platform/qmldir diff --git a/tests/unit/unittest/data/qml/Qt/labs/qmlmodels/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/Qt/labs/qmlmodels/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/Qt/labs/qmlmodels/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/Qt/labs/qmlmodels/qmldir diff --git a/tests/unit/unittest/data/qml/Qt/labs/settings/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/Qt/labs/settings/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/Qt/labs/settings/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/Qt/labs/settings/qmldir diff --git a/tests/unit/unittest/data/qml/Qt/labs/sharedimage/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/Qt/labs/sharedimage/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/Qt/labs/sharedimage/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/Qt/labs/sharedimage/qmldir diff --git a/tests/unit/unittest/data/qml/Qt/labs/wavefrontmesh/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/Qt/labs/wavefrontmesh/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/Qt/labs/wavefrontmesh/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/Qt/labs/wavefrontmesh/qmldir diff --git a/tests/unit/unittest/data/qml/Qt/test/controls/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/Qt/test/controls/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/Qt/test/controls/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/Qt/test/controls/qmldir diff --git a/tests/unit/unittest/data/qml/Qt3D/Animation/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/Qt3D/Animation/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/Qt3D/Animation/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/Qt3D/Animation/qmldir diff --git a/tests/unit/unittest/data/qml/Qt3D/Extras/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/Qt3D/Extras/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/Qt3D/Extras/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/Qt3D/Extras/qmldir diff --git a/tests/unit/unittest/data/qml/Qt3D/Input/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/Qt3D/Input/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/Qt3D/Input/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/Qt3D/Input/qmldir diff --git a/tests/unit/unittest/data/qml/Qt3D/Logic/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/Qt3D/Logic/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/Qt3D/Logic/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/Qt3D/Logic/qmldir diff --git a/tests/unit/unittest/data/qml/Qt3D/Render/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/Qt3D/Render/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/Qt3D/Render/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/Qt3D/Render/qmldir diff --git a/tests/unit/unittest/data/qml/Qt5Compat/GraphicalEffects/private/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/Qt5Compat/GraphicalEffects/private/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/Qt5Compat/GraphicalEffects/private/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/Qt5Compat/GraphicalEffects/private/qmldir diff --git a/tests/unit/unittest/data/qml/Qt5Compat/GraphicalEffects/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/Qt5Compat/GraphicalEffects/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/Qt5Compat/GraphicalEffects/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/Qt5Compat/GraphicalEffects/qmldir diff --git a/tests/unit/unittest/data/qml/QtApplicationManager/Application/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtApplicationManager/Application/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtApplicationManager/Application/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtApplicationManager/Application/qmldir diff --git a/tests/unit/unittest/data/qml/QtApplicationManager/SystemUI/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtApplicationManager/SystemUI/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtApplicationManager/SystemUI/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtApplicationManager/SystemUI/qmldir diff --git a/tests/unit/unittest/data/qml/QtApplicationManager/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtApplicationManager/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtApplicationManager/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtApplicationManager/qmldir diff --git a/tests/unit/unittest/data/qml/QtCharts/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtCharts/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtCharts/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtCharts/qmldir diff --git a/tests/unit/unittest/data/qml/QtCore/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtCore/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtCore/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtCore/qmldir diff --git a/tests/unit/unittest/data/qml/QtDataVisualization/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtDataVisualization/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtDataVisualization/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtDataVisualization/qmldir diff --git a/tests/unit/unittest/data/qml/QtInsightTracker/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtInsightTracker/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtInsightTracker/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtInsightTracker/qmldir diff --git a/tests/unit/unittest/data/qml/QtInterfaceFramework/Media/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtInterfaceFramework/Media/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtInterfaceFramework/Media/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtInterfaceFramework/Media/qmldir diff --git a/tests/unit/unittest/data/qml/QtInterfaceFramework/VehicleFunctions/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtInterfaceFramework/VehicleFunctions/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtInterfaceFramework/VehicleFunctions/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtInterfaceFramework/VehicleFunctions/qmldir diff --git a/tests/unit/unittest/data/qml/QtInterfaceFramework/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtInterfaceFramework/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtInterfaceFramework/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtInterfaceFramework/qmldir diff --git a/tests/unit/unittest/data/qml/QtLocation/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtLocation/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtLocation/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtLocation/qmldir diff --git a/tests/unit/unittest/data/qml/QtMultimedia/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtMultimedia/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtMultimedia/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtMultimedia/qmldir diff --git a/tests/unit/unittest/data/qml/QtOpcUa/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtOpcUa/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtOpcUa/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtOpcUa/qmldir diff --git a/tests/unit/unittest/data/qml/QtPositioning/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtPositioning/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtPositioning/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtPositioning/qmldir diff --git a/tests/unit/unittest/data/qml/QtQml/Base/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQml/Base/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQml/Base/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQml/Base/qmldir diff --git a/tests/unit/unittest/data/qml/QtQml/Models/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQml/Models/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQml/Models/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQml/Models/qmldir diff --git a/tests/unit/unittest/data/qml/QtQml/StateMachine/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQml/StateMachine/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQml/StateMachine/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQml/StateMachine/qmldir diff --git a/tests/unit/unittest/data/qml/QtQml/WorkerScript/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQml/WorkerScript/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQml/WorkerScript/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQml/WorkerScript/qmldir diff --git a/tests/unit/unittest/data/qml/QtQml/XmlListModel/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQml/XmlListModel/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQml/XmlListModel/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQml/XmlListModel/qmldir diff --git a/tests/unit/unittest/data/qml/QtQml/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQml/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQml/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQml/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/Controls/Basic/impl/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Controls/Basic/impl/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/Controls/Basic/impl/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Controls/Basic/impl/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/Controls/Basic/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Controls/Basic/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/Controls/Basic/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Controls/Basic/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/Controls/Fusion/impl/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Controls/Fusion/impl/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/Controls/Fusion/impl/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Controls/Fusion/impl/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/Controls/Fusion/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Controls/Fusion/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/Controls/Fusion/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Controls/Fusion/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/Controls/Imagine/impl/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Controls/Imagine/impl/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/Controls/Imagine/impl/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Controls/Imagine/impl/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/Controls/Imagine/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Controls/Imagine/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/Controls/Imagine/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Controls/Imagine/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/Controls/Material/impl/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Controls/Material/impl/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/Controls/Material/impl/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Controls/Material/impl/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/Controls/Material/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Controls/Material/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/Controls/Material/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Controls/Material/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/Controls/Universal/impl/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Controls/Universal/impl/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/Controls/Universal/impl/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Controls/Universal/impl/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/Controls/Universal/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Controls/Universal/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/Controls/Universal/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Controls/Universal/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/Controls/impl/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Controls/impl/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/Controls/impl/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Controls/impl/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/Controls/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Controls/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/Controls/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Controls/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/Dialogs/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Dialogs/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/Dialogs/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Dialogs/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/Dialogs/quickimpl/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Dialogs/quickimpl/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/Dialogs/quickimpl/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Dialogs/quickimpl/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/Effects/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Effects/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/Effects/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Effects/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/Layouts/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Layouts/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/Layouts/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Layouts/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/LocalStorage/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/LocalStorage/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/LocalStorage/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/LocalStorage/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/NativeStyle/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/NativeStyle/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/NativeStyle/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/NativeStyle/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/Particles/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Particles/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/Particles/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Particles/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/Pdf/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Pdf/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/Pdf/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Pdf/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/Scene2D/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Scene2D/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/Scene2D/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Scene2D/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/Scene3D/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Scene3D/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/Scene3D/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Scene3D/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/Shapes/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Shapes/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/Shapes/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Shapes/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/Templates/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Templates/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/Templates/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Templates/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/Timeline/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Timeline/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/Timeline/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Timeline/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/VirtualKeyboard/Components/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/VirtualKeyboard/Components/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/VirtualKeyboard/Components/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/VirtualKeyboard/Components/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/VirtualKeyboard/Layouts/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/VirtualKeyboard/Layouts/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/VirtualKeyboard/Layouts/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/VirtualKeyboard/Layouts/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/VirtualKeyboard/Plugins/Hangul/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/VirtualKeyboard/Plugins/Hangul/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/VirtualKeyboard/Plugins/Hangul/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/VirtualKeyboard/Plugins/Hangul/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/VirtualKeyboard/Plugins/OpenWNN/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/VirtualKeyboard/Plugins/OpenWNN/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/VirtualKeyboard/Plugins/OpenWNN/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/VirtualKeyboard/Plugins/OpenWNN/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/VirtualKeyboard/Plugins/Pinyin/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/VirtualKeyboard/Plugins/Pinyin/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/VirtualKeyboard/Plugins/Pinyin/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/VirtualKeyboard/Plugins/Pinyin/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/VirtualKeyboard/Plugins/TCIme/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/VirtualKeyboard/Plugins/TCIme/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/VirtualKeyboard/Plugins/TCIme/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/VirtualKeyboard/Plugins/TCIme/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/VirtualKeyboard/Plugins/Thai/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/VirtualKeyboard/Plugins/Thai/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/VirtualKeyboard/Plugins/Thai/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/VirtualKeyboard/Plugins/Thai/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/VirtualKeyboard/Plugins/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/VirtualKeyboard/Plugins/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/VirtualKeyboard/Plugins/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/VirtualKeyboard/Plugins/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/VirtualKeyboard/Settings/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/VirtualKeyboard/Settings/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/VirtualKeyboard/Settings/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/VirtualKeyboard/Settings/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/VirtualKeyboard/Styles/Builtin/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/VirtualKeyboard/Styles/Builtin/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/VirtualKeyboard/Styles/Builtin/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/VirtualKeyboard/Styles/Builtin/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/VirtualKeyboard/Styles/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/VirtualKeyboard/Styles/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/VirtualKeyboard/Styles/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/VirtualKeyboard/Styles/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/VirtualKeyboard/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/VirtualKeyboard/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/VirtualKeyboard/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/VirtualKeyboard/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/Window/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Window/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/Window/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/Window/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick/tooling/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/tooling/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick/tooling/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick/tooling/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick3D/AssetUtils/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick3D/AssetUtils/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick3D/AssetUtils/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick3D/AssetUtils/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick3D/Effects/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick3D/Effects/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick3D/Effects/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick3D/Effects/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick3D/Helpers/impl/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick3D/Helpers/impl/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick3D/Helpers/impl/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick3D/Helpers/impl/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick3D/Helpers/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick3D/Helpers/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick3D/Helpers/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick3D/Helpers/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick3D/MaterialEditor/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick3D/MaterialEditor/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick3D/MaterialEditor/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick3D/MaterialEditor/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick3D/ParticleEffects/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick3D/ParticleEffects/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick3D/ParticleEffects/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick3D/ParticleEffects/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick3D/Particles3D/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick3D/Particles3D/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick3D/Particles3D/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick3D/Particles3D/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick3D/Physics/Helpers/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick3D/Physics/Helpers/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick3D/Physics/Helpers/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick3D/Physics/Helpers/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick3D/Physics/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick3D/Physics/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick3D/Physics/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick3D/Physics/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick3D/SpatialAudio/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick3D/SpatialAudio/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick3D/SpatialAudio/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick3D/SpatialAudio/qmldir diff --git a/tests/unit/unittest/data/qml/QtQuick3D/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtQuick3D/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtQuick3D/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtQuick3D/qmldir diff --git a/tests/unit/unittest/data/qml/QtRemoteObjects/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtRemoteObjects/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtRemoteObjects/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtRemoteObjects/qmldir diff --git a/tests/unit/unittest/data/qml/QtScxml/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtScxml/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtScxml/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtScxml/qmldir diff --git a/tests/unit/unittest/data/qml/QtSensors/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtSensors/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtSensors/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtSensors/qmldir diff --git a/tests/unit/unittest/data/qml/QtTest/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtTest/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtTest/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtTest/qmldir diff --git a/tests/unit/unittest/data/qml/QtTextToSpeech/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtTextToSpeech/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtTextToSpeech/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtTextToSpeech/qmldir diff --git a/tests/unit/unittest/data/qml/QtVncServer/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtVncServer/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtVncServer/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtVncServer/qmldir diff --git a/tests/unit/unittest/data/qml/QtWayland/Client/TextureSharing/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtWayland/Client/TextureSharing/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtWayland/Client/TextureSharing/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtWayland/Client/TextureSharing/qmldir diff --git a/tests/unit/unittest/data/qml/QtWayland/Compositor/IviApplication/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtWayland/Compositor/IviApplication/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtWayland/Compositor/IviApplication/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtWayland/Compositor/IviApplication/qmldir diff --git a/tests/unit/unittest/data/qml/QtWayland/Compositor/PresentationTime/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtWayland/Compositor/PresentationTime/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtWayland/Compositor/PresentationTime/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtWayland/Compositor/PresentationTime/qmldir diff --git a/tests/unit/unittest/data/qml/QtWayland/Compositor/QtShell/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtWayland/Compositor/QtShell/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtWayland/Compositor/QtShell/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtWayland/Compositor/QtShell/qmldir diff --git a/tests/unit/unittest/data/qml/QtWayland/Compositor/TextureSharingExtension/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtWayland/Compositor/TextureSharingExtension/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtWayland/Compositor/TextureSharingExtension/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtWayland/Compositor/TextureSharingExtension/qmldir diff --git a/tests/unit/unittest/data/qml/QtWayland/Compositor/WlShell/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtWayland/Compositor/WlShell/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtWayland/Compositor/WlShell/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtWayland/Compositor/WlShell/qmldir diff --git a/tests/unit/unittest/data/qml/QtWayland/Compositor/XdgShell/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtWayland/Compositor/XdgShell/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtWayland/Compositor/XdgShell/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtWayland/Compositor/XdgShell/qmldir diff --git a/tests/unit/unittest/data/qml/QtWayland/Compositor/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtWayland/Compositor/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtWayland/Compositor/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtWayland/Compositor/qmldir diff --git a/tests/unit/unittest/data/qml/QtWebChannel/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtWebChannel/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtWebChannel/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtWebChannel/qmldir diff --git a/tests/unit/unittest/data/qml/QtWebEngine/ControlsDelegates/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtWebEngine/ControlsDelegates/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtWebEngine/ControlsDelegates/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtWebEngine/ControlsDelegates/qmldir diff --git a/tests/unit/unittest/data/qml/QtWebEngine/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtWebEngine/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtWebEngine/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtWebEngine/qmldir diff --git a/tests/unit/unittest/data/qml/QtWebSockets/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtWebSockets/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtWebSockets/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtWebSockets/qmldir diff --git a/tests/unit/unittest/data/qml/QtWebView/qmldir b/tests/unit/tests/unittests/projectstorage/data/qml/QtWebView/qmldir similarity index 100% rename from tests/unit/unittest/data/qml/QtWebView/qmldir rename to tests/unit/tests/unittests/projectstorage/data/qml/QtWebView/qmldir diff --git a/tests/unit/unittest/directorypathcompressor-test.cpp b/tests/unit/tests/unittests/projectstorage/directorypathcompressor-test.cpp similarity index 76% rename from tests/unit/unittest/directorypathcompressor-test.cpp rename to tests/unit/tests/unittests/projectstorage/directorypathcompressor-test.cpp index 4ce2d450012..d86e2d28287 100644 --- a/tests/unit/unittest/directorypathcompressor-test.cpp +++ b/tests/unit/tests/unittests/projectstorage/directorypathcompressor-test.cpp @@ -1,10 +1,10 @@ // Copyright (C) 2021 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" -#include "filesystemmock.h" -#include "mocktimer.h" +#include "../mocks/filesystemmock.h" +#include "../mocks/mocktimer.h" #include @@ -16,10 +16,7 @@ using QmlDesigner::SourceContextIds; class DirectoryPathCompressor : public testing::Test { protected: - void SetUp() - { - compressor.setCallback(mockCompressorCallback.AsStdFunction()); - } + void SetUp() { compressor.setCallback(mockCompressorCallback.AsStdFunction()); } protected: NiceMock> mockCompressorCallback; @@ -29,14 +26,14 @@ protected: SourceContextId sourceContextId2{SourceContextId::create(2)}; }; -TEST_F(DirectoryPathCompressor, AddFilePath) +TEST_F(DirectoryPathCompressor, add_file_path) { compressor.addSourceContextId(sourceContextId1); ASSERT_THAT(compressor.takeSourceContextIds(), ElementsAre(sourceContextId1)); } -TEST_F(DirectoryPathCompressor, NoFilePathsAferTakenThem) +TEST_F(DirectoryPathCompressor, no_file_paths_afer_taken_them) { compressor.addSourceContextId(sourceContextId1); @@ -45,14 +42,14 @@ TEST_F(DirectoryPathCompressor, NoFilePathsAferTakenThem) ASSERT_THAT(compressor.takeSourceContextIds(), IsEmpty()); } -TEST_F(DirectoryPathCompressor, CallRestartTimerAfterAddingPath) +TEST_F(DirectoryPathCompressor, call_restart_timer_after_adding_path) { EXPECT_CALL(mockTimer, start(20)); compressor.addSourceContextId(sourceContextId1); } -TEST_F(DirectoryPathCompressor, CallTimeOutAfterAddingPath) +TEST_F(DirectoryPathCompressor, call_time_out_after_adding_path) { EXPECT_CALL(mockCompressorCallback, Call(ElementsAre(sourceContextId1, sourceContextId2))); @@ -60,7 +57,7 @@ TEST_F(DirectoryPathCompressor, CallTimeOutAfterAddingPath) compressor.addSourceContextId(sourceContextId2); } -TEST_F(DirectoryPathCompressor, RemoveDuplicates) +TEST_F(DirectoryPathCompressor, remove_duplicates) { EXPECT_CALL(mockCompressorCallback, Call(ElementsAre(sourceContextId1, sourceContextId2))); @@ -69,4 +66,4 @@ TEST_F(DirectoryPathCompressor, RemoveDuplicates) compressor.addSourceContextId(sourceContextId1); } -} +} // namespace diff --git a/tests/unit/unittest/filestatuscache-test.cpp b/tests/unit/tests/unittests/projectstorage/filestatuscache-test.cpp similarity index 87% rename from tests/unit/unittest/filestatuscache-test.cpp rename to tests/unit/tests/unittests/projectstorage/filestatuscache-test.cpp index 6e1d9c1a326..67eb953e9a8 100644 --- a/tests/unit/unittest/filestatuscache-test.cpp +++ b/tests/unit/tests/unittests/projectstorage/filestatuscache-test.cpp @@ -1,8 +1,8 @@ // Copyright (C) 2021 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "filesystemmock.h" -#include "googletest.h" +#include "../mocks/filesystemmock.h" +#include "../utils/googletest.h" #include @@ -54,21 +54,21 @@ protected: long long source2FileSize = 4000; }; -TEST_F(FileStatusCache, CreateEntry) +TEST_F(FileStatusCache, create_entry) { cache.find(header); ASSERT_THAT(cache, SizeIs(1)); } -TEST_F(FileStatusCache, AskCreatedEntryForLastModifiedTime) +TEST_F(FileStatusCache, ask_created_entry_for_last_modified_time) { auto fileStatus = cache.find(header); ASSERT_THAT(fileStatus, (FileStatus{header, headerFileSize, headerLastModifiedTime})); } -TEST_F(FileStatusCache, FindCachedEntry) +TEST_F(FileStatusCache, find_cached_entry) { cache.find(header); @@ -77,7 +77,7 @@ TEST_F(FileStatusCache, FindCachedEntry) ASSERT_THAT(fileStatus, (FileStatus{header, headerFileSize, headerLastModifiedTime})); } -TEST_F(FileStatusCache, LastModifiedTime) +TEST_F(FileStatusCache, last_modified_time) { cache.find(header); @@ -86,7 +86,7 @@ TEST_F(FileStatusCache, LastModifiedTime) ASSERT_THAT(lastModifiedTime, headerLastModifiedTime); } -TEST_F(FileStatusCache, FileSize) +TEST_F(FileStatusCache, file_size) { cache.find(header); @@ -95,7 +95,7 @@ TEST_F(FileStatusCache, FileSize) ASSERT_THAT(fileSize, headerFileSize); } -TEST_F(FileStatusCache, DontAddEntryTwice) +TEST_F(FileStatusCache, dont_add_entry_twice) { cache.find(header); @@ -104,7 +104,7 @@ TEST_F(FileStatusCache, DontAddEntryTwice) ASSERT_THAT(cache, SizeIs(1)); } -TEST_F(FileStatusCache, AddNewEntry) +TEST_F(FileStatusCache, add_new_entry) { cache.find(header); @@ -113,7 +113,7 @@ TEST_F(FileStatusCache, AddNewEntry) ASSERT_THAT(cache, SizeIs(2)); } -TEST_F(FileStatusCache, AskNewEntryForLastModifiedTime) +TEST_F(FileStatusCache, ask_new_entry_for_last_modified_time) { cache.find(header); @@ -122,7 +122,7 @@ TEST_F(FileStatusCache, AskNewEntryForLastModifiedTime) ASSERT_THAT(fileStatus, (FileStatus{source, sourceFileSize, sourceLastModifiedTime})); } -TEST_F(FileStatusCache, AddNewEntryReverseOrder) +TEST_F(FileStatusCache, add_new_entry_reverse_order) { cache.find(source); @@ -131,7 +131,7 @@ TEST_F(FileStatusCache, AddNewEntryReverseOrder) ASSERT_THAT(cache, SizeIs(2)); } -TEST_F(FileStatusCache, AskNewEntryReverseOrderAddedForLastModifiedTime) +TEST_F(FileStatusCache, ask_new_entry_reverse_order_added_for_last_modified_time) { cache.find(source); @@ -140,7 +140,7 @@ TEST_F(FileStatusCache, AskNewEntryReverseOrderAddedForLastModifiedTime) ASSERT_THAT(fileStatus, (FileStatus{header, headerFileSize, headerLastModifiedTime})); } -TEST_F(FileStatusCache, UpdateFile) +TEST_F(FileStatusCache, update_file) { EXPECT_CALL(fileSystem, fileStatus(Eq(header))) .Times(2) @@ -153,7 +153,7 @@ TEST_F(FileStatusCache, UpdateFile) ASSERT_THAT(cache.find(header), (FileStatus{header, headerFileSize2, headerLastModifiedTime2})); } -TEST_F(FileStatusCache, UpdateFileDoesNotChangeEntryCount) +TEST_F(FileStatusCache, update_file_does_not_change_entry_count) { EXPECT_CALL(fileSystem, fileStatus(Eq(header))) .Times(2) @@ -166,14 +166,14 @@ TEST_F(FileStatusCache, UpdateFileDoesNotChangeEntryCount) ASSERT_THAT(cache, SizeIs(1)); } -TEST_F(FileStatusCache, UpdateFileForNonExistingEntry) +TEST_F(FileStatusCache, update_file_for_non_existing_entry) { cache.update(header); ASSERT_THAT(cache, SizeIs(0)); } -TEST_F(FileStatusCache, UpdateFileStats) +TEST_F(FileStatusCache, update_file_stats) { EXPECT_CALL(fileSystem, fileStatus(Eq(header))) .Times(2) @@ -193,7 +193,7 @@ TEST_F(FileStatusCache, UpdateFileStats) (FileStatus{header2, header2FileSize2, header2LastModifiedTime2})); } -TEST_F(FileStatusCache, UpdateFilesDoesNotChangeEntryCount) +TEST_F(FileStatusCache, update_files_does_not_change_entry_count) { EXPECT_CALL(fileSystem, fileStatus(Eq(header))) .Times(2) @@ -211,21 +211,21 @@ TEST_F(FileStatusCache, UpdateFilesDoesNotChangeEntryCount) ASSERT_THAT(cache, SizeIs(2)); } -TEST_F(FileStatusCache, UpdateFilesForNonExistingEntry) +TEST_F(FileStatusCache, update_files_for_non_existing_entry) { cache.update(entries); ASSERT_THAT(cache, SizeIs(0)); } -TEST_F(FileStatusCache, NewModifiedEntries) +TEST_F(FileStatusCache, new_modified_entries) { auto modifiedIds = cache.modified(entries); ASSERT_THAT(modifiedIds, entries); } -TEST_F(FileStatusCache, NoNewModifiedEntries) +TEST_F(FileStatusCache, no_new_modified_entries) { cache.modified(entries); @@ -234,7 +234,7 @@ TEST_F(FileStatusCache, NoNewModifiedEntries) ASSERT_THAT(modifiedIds, IsEmpty()); } -TEST_F(FileStatusCache, SomeNewModifiedEntries) +TEST_F(FileStatusCache, some_new_modified_entries) { cache.modified({source, header2}); @@ -243,7 +243,7 @@ TEST_F(FileStatusCache, SomeNewModifiedEntries) ASSERT_THAT(modifiedIds, ElementsAre(header, source2)); } -TEST_F(FileStatusCache, SomeAlreadyExistingModifiedEntries) +TEST_F(FileStatusCache, some_already_existing_modified_entries) { EXPECT_CALL(fileSystem, fileStatus(Eq(header))) .Times(2) @@ -266,7 +266,7 @@ TEST_F(FileStatusCache, SomeAlreadyExistingModifiedEntries) ASSERT_THAT(modifiedIds, ElementsAre(header, header2)); } -TEST_F(FileStatusCache, SomeAlreadyExistingAndSomeNewModifiedEntries) +TEST_F(FileStatusCache, some_already_existing_and_some_new_modified_entries) { EXPECT_CALL(fileSystem, fileStatus(Eq(header))) .WillRepeatedly(Return(FileStatus{header, headerFileSize, headerLastModifiedTime})); @@ -286,7 +286,7 @@ TEST_F(FileStatusCache, SomeAlreadyExistingAndSomeNewModifiedEntries) ASSERT_THAT(modifiedIds, ElementsAre(header, header2, source2)); } -TEST_F(FileStatusCache, TimeIsUpdatedForSomeAlreadyExistingModifiedEntries) +TEST_F(FileStatusCache, time_is_updated_for_some_already_existing_modified_entries) { EXPECT_CALL(fileSystem, fileStatus(Eq(header))) .Times(2) diff --git a/tests/unit/unittest/modulescanner-test.cpp b/tests/unit/tests/unittests/projectstorage/modulescanner-test.cpp similarity index 82% rename from tests/unit/unittest/modulescanner-test.cpp rename to tests/unit/tests/unittests/projectstorage/modulescanner-test.cpp index a3e8923fd76..b3f09e9b6bf 100644 --- a/tests/unit/unittest/modulescanner-test.cpp +++ b/tests/unit/tests/unittests/projectstorage/modulescanner-test.cpp @@ -1,8 +1,8 @@ // Copyright (C) 2023 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "externaldependenciesmock.h" -#include "googletest.h" +#include "../mocks/externaldependenciesmock.h" +#include "../utils/googletest.h" #include @@ -10,7 +10,7 @@ namespace { -QLatin1String qmlModulesPath(TESTDATA_DIR "/qml"); +QLatin1String qmlModulesPath(UNITTEST_DIR "/projectstorage/data/qml"); template auto UrlProperty(const Matcher &matcher) @@ -65,49 +65,49 @@ protected: externalDependenciesMock}; }; -TEST_F(ModuleScanner, ReturnEmptyOptionalForEmptyPath) +TEST_F(ModuleScanner, return_empty_optional_for_empty_path) { scanner.scan(QStringList{""}); ASSERT_THAT(scanner.modules(), IsEmpty()); } -TEST_F(ModuleScanner, ReturnEmptyOptionalForNullStringPath) +TEST_F(ModuleScanner, return_empty_optional_for_null_string_path) { scanner.scan(QStringList{QString{}}); ASSERT_THAT(scanner.modules(), IsEmpty()); } -TEST_F(ModuleScanner, ReturnEmptyOptionalForEmptyPaths) +TEST_F(ModuleScanner, return_empty_optional_for_empty_paths) { scanner.scan(QStringList{}); ASSERT_THAT(scanner.modules(), IsEmpty()); } -TEST_F(ModuleScanner, GetQtQuick) +TEST_F(ModuleScanner, get_qt_quick) { scanner.scan(QStringList{qmlModulesPath}); ASSERT_THAT(scanner.modules(), Contains(UrlProperty("QtQuick"))); } -TEST_F(ModuleScanner, SkipEmptyModules) +TEST_F(ModuleScanner, skip_empty_modules) { scanner.scan(QStringList{qmlModulesPath}); ASSERT_THAT(scanner.modules(), Not(Contains(UrlProperty(IsEmpty())))); } -TEST_F(ModuleScanner, UseSkipFunction) +TEST_F(ModuleScanner, use_skip_function) { scanner.scan(QStringList{qmlModulesPath}); ASSERT_THAT(scanner.modules(), Not(Contains(UrlProperty(EndsWith(QStringView{u"impl"}))))); } -TEST_F(ModuleScanner, Version) +TEST_F(ModuleScanner, version) { QmlDesigner::ModuleScanner scanner{[](QStringView moduleName) { return moduleName.endsWith(u"impl"); @@ -115,13 +115,12 @@ TEST_F(ModuleScanner, Version) QmlDesigner::VersionScanning::Yes, externalDependenciesMock}; - scanner.scan(QStringList{TESTDATA_DIR "/modulescanner"}); + scanner.scan(QStringList{UNITTEST_DIR "/projectstorage/data/modulescanner"}); ASSERT_THAT(scanner.modules(), ElementsAre(AllOf(UrlProperty("Example"), VersionProperty("1.3")))); - } -TEST_F(ModuleScanner, NoVersion) +TEST_F(ModuleScanner, no_version) { QmlDesigner::ModuleScanner scanner{[](QStringView moduleName) { return moduleName.endsWith(u"impl"); @@ -129,20 +128,20 @@ TEST_F(ModuleScanner, NoVersion) QmlDesigner::VersionScanning::No, externalDependenciesMock}; - scanner.scan(QStringList{TESTDATA_DIR "/modulescanner"}); + scanner.scan(QStringList{UNITTEST_DIR "/projectstorage/data/modulescanner"}); ASSERT_THAT(scanner.modules(), ElementsAre(AllOf(UrlProperty("Example"), VersionProperty(QString{})))); } -TEST_F(ModuleScanner, Duplicates) +TEST_F(ModuleScanner, duplicates) { scanner.scan(QStringList{qmlModulesPath}); ASSERT_THAT(scanner.modules(), Not(HasDuplicates())); } -TEST_F(ModuleScanner, DontAddModulesAgain) +TEST_F(ModuleScanner, dont_add_modules_again) { scanner.scan(QStringList{qmlModulesPath}); @@ -151,14 +150,14 @@ TEST_F(ModuleScanner, DontAddModulesAgain) ASSERT_THAT(scanner.modules(), Not(HasDuplicates())); } -TEST_F(ModuleScanner, SetNoVersionForQtQuickVersion) +TEST_F(ModuleScanner, set_no_version_for_qt_quick_version) { scanner.scan(QStringList{qmlModulesPath}); ASSERT_THAT(scanner.modules(), CorePropertiesHave(VersionProperty(QString{}))); } -TEST_F(ModuleScanner, SetVersionForQtQuickVersion) +TEST_F(ModuleScanner, set_version_for_qt_quick_version) { ON_CALL(externalDependenciesMock, qtQuickVersion()).WillByDefault(Return(QString{"6.4"})); @@ -167,7 +166,7 @@ TEST_F(ModuleScanner, SetVersionForQtQuickVersion) ASSERT_THAT(scanner.modules(), CorePropertiesHave(VersionProperty(u"6.4"))); } -TEST_F(ModuleScanner, DontSetVersionForNonQtQuickVersion) +TEST_F(ModuleScanner, dont_set_version_for_non_qt_quick_version) { ON_CALL(externalDependenciesMock, qtQuickVersion()).WillByDefault(Return(QString{"6.4"})); diff --git a/tests/unit/unittest/projectstorage-test.cpp b/tests/unit/tests/unittests/projectstorage/projectstorage-test.cpp similarity index 92% rename from tests/unit/unittest/projectstorage-test.cpp rename to tests/unit/tests/unittests/projectstorage/projectstorage-test.cpp index 7ff1df47c9e..19a60594373 100644 --- a/tests/unit/unittest/projectstorage-test.cpp +++ b/tests/unit/tests/unittests/projectstorage/projectstorage-test.cpp @@ -1,7 +1,7 @@ // Copyright (C) 2021 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" #include #include @@ -1051,7 +1051,7 @@ protected: Storage::Synchronization::Imports moduleDependenciesSourceId5; }; -TEST_F(ProjectStorage, FetchSourceContextIdReturnsAlwaysTheSameIdForTheSamePath) +TEST_F(ProjectStorage, fetch_source_context_id_returns_always_the_same_id_for_the_same_path) { auto sourceContextId = storage.fetchSourceContextId("/path/to"); @@ -1060,7 +1060,7 @@ TEST_F(ProjectStorage, FetchSourceContextIdReturnsAlwaysTheSameIdForTheSamePath) ASSERT_THAT(newSourceContextId, Eq(sourceContextId)); } -TEST_F(ProjectStorage, FetchSourceContextIdReturnsNotTheSameIdForDifferentPath) +TEST_F(ProjectStorage, fetch_source_context_id_returns_not_the_same_id_for_different_path) { auto sourceContextId = storage.fetchSourceContextId("/path/to"); @@ -1069,7 +1069,7 @@ TEST_F(ProjectStorage, FetchSourceContextIdReturnsNotTheSameIdForDifferentPath) ASSERT_THAT(newSourceContextId, Ne(sourceContextId)); } -TEST_F(ProjectStorage, FetchSourceContextPath) +TEST_F(ProjectStorage, fetch_source_context_path) { auto sourceContextId = storage.fetchSourceContextId("/path/to"); @@ -1078,13 +1078,13 @@ TEST_F(ProjectStorage, FetchSourceContextPath) ASSERT_THAT(path, Eq("/path/to")); } -TEST_F(ProjectStorage, FetchUnknownSourceContextPathThrows) +TEST_F(ProjectStorage, fetch_unknown_source_context_path_throws) { ASSERT_THROW(storage.fetchSourceContextPath(SourceContextId::create(323)), QmlDesigner::SourceContextIdDoesNotExists); } -TEST_F(ProjectStorage, FetchAllSourceContextsAreEmptyIfNoSourceContextsExists) +TEST_F(ProjectStorage, fetch_all_source_contexts_are_empty_if_no_source_contexts_exists) { storage.clearSources(); @@ -1093,7 +1093,7 @@ TEST_F(ProjectStorage, FetchAllSourceContextsAreEmptyIfNoSourceContextsExists) ASSERT_THAT(toValues(sourceContexts), IsEmpty()); } -TEST_F(ProjectStorage, FetchAllSourceContexts) +TEST_F(ProjectStorage, fetch_all_source_contexts) { storage.clearSources(); auto sourceContextId = storage.fetchSourceContextId("/path/to"); @@ -1106,7 +1106,7 @@ TEST_F(ProjectStorage, FetchAllSourceContexts) IsSourceContext(sourceContextId2, "/path/to2"))); } -TEST_F(ProjectStorage, FetchSourceIdFirstTime) +TEST_F(ProjectStorage, fetch_source_id_first_time) { addSomeDummyData(); auto sourceContextId = storage.fetchSourceContextId("/path/to"); @@ -1116,7 +1116,7 @@ TEST_F(ProjectStorage, FetchSourceIdFirstTime) ASSERT_TRUE(sourceId.isValid()); } -TEST_F(ProjectStorage, FetchExistingSourceId) +TEST_F(ProjectStorage, fetch_existing_source_id) { addSomeDummyData(); auto sourceContextId = storage.fetchSourceContextId("/path/to"); @@ -1127,7 +1127,7 @@ TEST_F(ProjectStorage, FetchExistingSourceId) ASSERT_THAT(sourceId, createdSourceId); } -TEST_F(ProjectStorage, FetchSourceIdWithDifferentContextIdAreNotEqual) +TEST_F(ProjectStorage, fetch_source_id_with_different_context_id_are_not_equal) { addSomeDummyData(); auto sourceContextId = storage.fetchSourceContextId("/path/to"); @@ -1139,7 +1139,7 @@ TEST_F(ProjectStorage, FetchSourceIdWithDifferentContextIdAreNotEqual) ASSERT_THAT(sourceId, Ne(sourceId2)); } -TEST_F(ProjectStorage, FetchSourceIdWithDifferentNameAreNotEqual) +TEST_F(ProjectStorage, fetch_source_id_with_different_name_are_not_equal) { addSomeDummyData(); auto sourceContextId = storage.fetchSourceContextId("/path/to"); @@ -1150,19 +1150,19 @@ TEST_F(ProjectStorage, FetchSourceIdWithDifferentNameAreNotEqual) ASSERT_THAT(sourceId, Ne(sourceId2)); } -TEST_F(ProjectStorage, FetchSourceIdWithNonExistingSourceContextIdThrows) +TEST_F(ProjectStorage, fetch_source_id_with_non_existing_source_context_id_throws) { ASSERT_THROW(storage.fetchSourceId(SourceContextId::create(42), "foo"), Sqlite::ConstraintPreventsModification); } -TEST_F(ProjectStorage, FetchSourceNameAndSourceContextIdForNonExistingSourceId) +TEST_F(ProjectStorage, fetch_source_name_and_source_context_id_for_non_existing_source_id) { ASSERT_THROW(storage.fetchSourceNameAndSourceContextId(SourceId::create(212)), QmlDesigner::SourceIdDoesNotExists); } -TEST_F(ProjectStorage, FetchSourceNameAndSourceContextIdForNonExistingEntry) +TEST_F(ProjectStorage, fetch_source_name_and_source_context_id_for_non_existing_entry) { addSomeDummyData(); auto sourceContextId = storage.fetchSourceContextId("/path/to"); @@ -1173,13 +1173,13 @@ TEST_F(ProjectStorage, FetchSourceNameAndSourceContextIdForNonExistingEntry) ASSERT_THAT(sourceNameAndSourceContextId, IsSourceNameAndSourceContextId("foo", sourceContextId)); } -TEST_F(ProjectStorage, FetchSourceContextIdForNonExistingSourceId) +TEST_F(ProjectStorage, fetch_source_context_id_for_non_existing_source_id) { ASSERT_THROW(storage.fetchSourceContextId(SourceId::create(212)), QmlDesigner::SourceIdDoesNotExists); } -TEST_F(ProjectStorage, FetchSourceContextIdForExistingSourceId) +TEST_F(ProjectStorage, fetch_source_context_id_for_existing_source_id) { addSomeDummyData(); auto originalSourceContextId = storage.fetchSourceContextId("/path/to3"); @@ -1190,7 +1190,7 @@ TEST_F(ProjectStorage, FetchSourceContextIdForExistingSourceId) ASSERT_THAT(sourceContextId, Eq(originalSourceContextId)); } -TEST_F(ProjectStorage, FetchAllSources) +TEST_F(ProjectStorage, fetch_all_sources) { storage.clearSources(); @@ -1199,7 +1199,7 @@ TEST_F(ProjectStorage, FetchAllSources) ASSERT_THAT(toValues(sources), IsEmpty()); } -TEST_F(ProjectStorage, FetchSourceIdUnguardedFirstTime) +TEST_F(ProjectStorage, fetch_source_id_unguarded_first_time) { addSomeDummyData(); auto sourceContextId = storage.fetchSourceContextId("/path/to"); @@ -1210,7 +1210,7 @@ TEST_F(ProjectStorage, FetchSourceIdUnguardedFirstTime) ASSERT_TRUE(sourceId.isValid()); } -TEST_F(ProjectStorage, FetchExistingSourceIdUnguarded) +TEST_F(ProjectStorage, fetch_existing_source_id_unguarded) { addSomeDummyData(); auto sourceContextId = storage.fetchSourceContextId("/path/to"); @@ -1222,7 +1222,7 @@ TEST_F(ProjectStorage, FetchExistingSourceIdUnguarded) ASSERT_THAT(sourceId, createdSourceId); } -TEST_F(ProjectStorage, FetchSourceIdUnguardedWithDifferentContextIdAreNotEqual) +TEST_F(ProjectStorage, fetch_source_id_unguarded_with_different_context_id_are_not_equal) { addSomeDummyData(); auto sourceContextId = storage.fetchSourceContextId("/path/to"); @@ -1235,7 +1235,7 @@ TEST_F(ProjectStorage, FetchSourceIdUnguardedWithDifferentContextIdAreNotEqual) ASSERT_THAT(sourceId, Ne(sourceId2)); } -TEST_F(ProjectStorage, FetchSourceIdUnguardedWithDifferentNameAreNotEqual) +TEST_F(ProjectStorage, fetch_source_id_unguarded_with_different_name_are_not_equal) { addSomeDummyData(); auto sourceContextId = storage.fetchSourceContextId("/path/to"); @@ -1247,7 +1247,7 @@ TEST_F(ProjectStorage, FetchSourceIdUnguardedWithDifferentNameAreNotEqual) ASSERT_THAT(sourceId, Ne(sourceId2)); } -TEST_F(ProjectStorage, FetchSourceIdUnguardedWithNonExistingSourceContextIdThrows) +TEST_F(ProjectStorage, fetch_source_id_unguarded_with_non_existing_source_context_id_throws) { std::lock_guard lock{database}; @@ -1255,7 +1255,7 @@ TEST_F(ProjectStorage, FetchSourceIdUnguardedWithNonExistingSourceContextIdThrow Sqlite::ConstraintPreventsModification); } -TEST_F(ProjectStorage, SynchronizeTypesAddsNewTypes) +TEST_F(ProjectStorage, synchronize_types_adds_new_types) { auto package{createSimpleSynchronizationPackage()}; @@ -1278,7 +1278,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddsNewTypes) "QQuickItem")))))); } -TEST_F(ProjectStorage, SynchronizeTypesAddsNewTypesWithExtensionChain) +TEST_F(ProjectStorage, synchronize_types_adds_new_types_with_extension_chain) { auto package{createSimpleSynchronizationPackage()}; swap(package.types.front().extension, package.types.front().prototype); @@ -1303,7 +1303,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddsNewTypesWithExtensionChain) "QQuickItem")))))); } -TEST_F(ProjectStorage, SynchronizeTypesAddsNewTypesWithExportedPrototypeName) +TEST_F(ProjectStorage, synchronize_types_adds_new_types_with_exported_prototype_name) { auto package{createSimpleSynchronizationPackage()}; package.types[0].prototype = Storage::Synchronization::ImportedType{"Object"}; @@ -1328,7 +1328,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddsNewTypesWithExportedPrototypeName) IsExportedType(qtQuickNativeModuleId, "QQuickItem")))))); } -TEST_F(ProjectStorage, SynchronizeTypesAddsNewTypesWithExportedExtensionName) +TEST_F(ProjectStorage, synchronize_types_adds_new_types_with_exported_extension_name) { auto package{createSimpleSynchronizationPackage()}; swap(package.types.front().extension, package.types.front().prototype); @@ -1354,7 +1354,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddsNewTypesWithExportedExtensionName) "QQuickItem")))))); } -TEST_F(ProjectStorage, SynchronizeTypesAddsNewTypesThrowsWithWrongPrototypeName) +TEST_F(ProjectStorage, synchronize_types_adds_new_types_throws_with_wrong_prototype_name) { auto package{createSimpleSynchronizationPackage()}; package.types[0].prototype = Storage::Synchronization::ImportedType{"Objec"}; @@ -1362,7 +1362,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddsNewTypesThrowsWithWrongPrototypeName) ASSERT_THROW(storage.synchronize(std::move(package)), QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, SynchronizeTypesAddsNewTypesThrowsWithWrongExtensionName) +TEST_F(ProjectStorage, synchronize_types_adds_new_types_throws_with_wrong_extension_name) { auto package{createSimpleSynchronizationPackage()}; package.types[0].extension = Storage::Synchronization::ImportedType{"Objec"}; @@ -1370,7 +1370,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddsNewTypesThrowsWithWrongExtensionName) ASSERT_THROW(storage.synchronize(std::move(package)), QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, SynchronizeTypesAddsNewTypesWithMissingModule) +TEST_F(ProjectStorage, synchronize_types_adds_new_types_with_missing_module) { auto package{createSimpleSynchronizationPackage()}; package.types.push_back(Storage::Synchronization::Type{ @@ -1385,7 +1385,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddsNewTypesWithMissingModule) ASSERT_THROW(storage.synchronize(std::move(package)), QmlDesigner::ExportedTypeCannotBeInserted); } -TEST_F(ProjectStorage, SynchronizeTypesAddsNewTypesReverseOrder) +TEST_F(ProjectStorage, synchronize_types_adds_new_types_reverse_order) { auto package{createSimpleSynchronizationPackage()}; std::reverse(package.types.begin(), package.types.end()); @@ -1409,7 +1409,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddsNewTypesReverseOrder) "QQuickItem")))))); } -TEST_F(ProjectStorage, SynchronizeTypesOverwritesTypeTraits) +TEST_F(ProjectStorage, synchronize_types_overwrites_type_traits) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -1432,7 +1432,7 @@ TEST_F(ProjectStorage, SynchronizeTypesOverwritesTypeTraits) IsExportedType(qtQuickNativeModuleId, "QQuickItem")))))); } -TEST_F(ProjectStorage, SynchronizeTypesOverwritesSources) +TEST_F(ProjectStorage, synchronize_types_overwrites_sources) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -1467,7 +1467,7 @@ TEST_F(ProjectStorage, SynchronizeTypesOverwritesSources) "QQuickItem")))))); } -TEST_F(ProjectStorage, SynchronizeTypesInsertTypeIntoPrototypeChain) +TEST_F(ProjectStorage, synchronize_types_insert_type_into_prototype_chain) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -1510,7 +1510,7 @@ TEST_F(ProjectStorage, SynchronizeTypesInsertTypeIntoPrototypeChain) IsExportedType(qtQuickNativeModuleId, "QQuickItem")))))); } -TEST_F(ProjectStorage, SynchronizeTypesInsertTypeIntoExtensionChain) +TEST_F(ProjectStorage, synchronize_types_insert_type_into_extension_chain) { auto package{createSimpleSynchronizationPackage()}; swap(package.types.front().extension, package.types.front().prototype); @@ -1554,7 +1554,7 @@ TEST_F(ProjectStorage, SynchronizeTypesInsertTypeIntoExtensionChain) IsExportedType(qtQuickNativeModuleId, "QQuickItem")))))); } -TEST_F(ProjectStorage, SynchronizeTypesAddQualifiedPrototype) +TEST_F(ProjectStorage, synchronize_types_add_qualified_prototype) { auto package{createSimpleSynchronizationPackage()}; package.types[0].prototype = Storage::Synchronization::QualifiedImportedType{ @@ -1599,7 +1599,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddQualifiedPrototype) IsExportedType(qtQuickNativeModuleId, "QQuickItem")))))); } -TEST_F(ProjectStorage, SynchronizeTypesAddQualifiedExtension) +TEST_F(ProjectStorage, synchronize_types_add_qualified_extension) { auto package{createSimpleSynchronizationPackage()}; swap(package.types.front().extension, package.types.front().prototype); @@ -1645,7 +1645,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddQualifiedExtension) IsExportedType(qtQuickNativeModuleId, "QQuickItem")))))); } -TEST_F(ProjectStorage, SynchronizeTypesThrowsForMissingPrototype) +TEST_F(ProjectStorage, synchronize_types_throws_for_missing_prototype) { auto package{createSimpleSynchronizationPackage()}; package.types = {Storage::Synchronization::Type{ @@ -1660,7 +1660,7 @@ TEST_F(ProjectStorage, SynchronizeTypesThrowsForMissingPrototype) ASSERT_THROW(storage.synchronize(package), QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, SynchronizeTypesThrowsForMissingExtension) +TEST_F(ProjectStorage, synchronize_types_throws_for_missing_extension) { auto package{createSimpleSynchronizationPackage()}; package.types = {Storage::Synchronization::Type{ @@ -1675,7 +1675,7 @@ TEST_F(ProjectStorage, SynchronizeTypesThrowsForMissingExtension) ASSERT_THROW(storage.synchronize(package), QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, SynchronizeTypesThrowsForInvalidModule) +TEST_F(ProjectStorage, synchronize_types_throws_for_invalid_module) { auto package{createSimpleSynchronizationPackage()}; package.types = { @@ -1689,7 +1689,7 @@ TEST_F(ProjectStorage, SynchronizeTypesThrowsForInvalidModule) ASSERT_THROW(storage.synchronize(package), QmlDesigner::ModuleDoesNotExists); } -TEST_F(ProjectStorage, TypeWithInvalidSourceIdThrows) +TEST_F(ProjectStorage, type_with_invalid_source_id_throws) { auto package{createSimpleSynchronizationPackage()}; package.types = { @@ -1704,7 +1704,7 @@ TEST_F(ProjectStorage, TypeWithInvalidSourceIdThrows) ASSERT_THROW(storage.synchronize(package), QmlDesigner::TypeHasInvalidSourceId); } -TEST_F(ProjectStorage, DeleteTypeIfSourceIdIsSynchronized) +TEST_F(ProjectStorage, delete_type_if_source_id_is_synchronized) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -1721,7 +1721,7 @@ TEST_F(ProjectStorage, DeleteTypeIfSourceIdIsSynchronized) IsExportedType(qmlNativeModuleId, "QObject")))))); } -TEST_F(ProjectStorage, DontDeleteTypeIfSourceIdIsNotSynchronized) +TEST_F(ProjectStorage, dont_delete_type_if_source_id_is_not_synchronized) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -1745,7 +1745,7 @@ TEST_F(ProjectStorage, DontDeleteTypeIfSourceIdIsNotSynchronized) "QQuickItem")))))); } -TEST_F(ProjectStorage, UpdateExportedTypesIfTypeNameChanges) +TEST_F(ProjectStorage, update_exported_types_if_type_name_changes) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -1770,7 +1770,7 @@ TEST_F(ProjectStorage, UpdateExportedTypesIfTypeNameChanges) "QQuickItem")))))); } -TEST_F(ProjectStorage, BreakingPrototypeChainByDeletingBaseComponentThrows) +TEST_F(ProjectStorage, breaking_prototype_chain_by_deleting_base_component_throws) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -1781,7 +1781,7 @@ TEST_F(ProjectStorage, BreakingPrototypeChainByDeletingBaseComponentThrows) QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, BreakingExtensionChainByDeletingBaseComponentThrows) +TEST_F(ProjectStorage, breaking_extension_chain_by_deleting_base_component_throws) { auto package{createSimpleSynchronizationPackage()}; std::swap(package.types.front().extension, package.types.front().prototype); @@ -1793,7 +1793,7 @@ TEST_F(ProjectStorage, BreakingExtensionChainByDeletingBaseComponentThrows) QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, SynchronizeTypesAddPropertyDeclarations) +TEST_F(ProjectStorage, synchronize_types_add_property_declarations) { auto package{createSimpleSynchronizationPackage()}; @@ -1814,7 +1814,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddPropertyDeclarations) | Storage::PropertyDeclarationTraits::IsReadOnly)))))); } -TEST_F(ProjectStorage, SynchronizeTypesAddPropertyDeclarationsWithMissingImports) +TEST_F(ProjectStorage, synchronize_types_add_property_declarations_with_missing_imports) { auto package{createSimpleSynchronizationPackage()}; package.imports.clear(); @@ -1822,7 +1822,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddPropertyDeclarationsWithMissingImports ASSERT_THROW(storage.synchronize(package), QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, SynchronizeTypesAddPropertyDeclarationQualifiedType) +TEST_F(ProjectStorage, synchronize_types_add_property_declaration_qualified_type) { auto package{createSimpleSynchronizationPackage()}; package.types[0].propertyDeclarations[0].typeName = Storage::Synchronization::QualifiedImportedType{ @@ -1856,7 +1856,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddPropertyDeclarationQualifiedType) | Storage::PropertyDeclarationTraits::IsReadOnly)))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangesPropertyDeclarationType) +TEST_F(ProjectStorage, synchronize_types_changes_property_declaration_type) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -1880,7 +1880,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangesPropertyDeclarationType) | Storage::PropertyDeclarationTraits::IsReadOnly)))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangesDeclarationTraits) +TEST_F(ProjectStorage, synchronize_types_changes_declaration_traits) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -1903,7 +1903,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangesDeclarationTraits) | Storage::PropertyDeclarationTraits::IsReadOnly)))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangesDeclarationTraitsAndType) +TEST_F(ProjectStorage, synchronize_types_changes_declaration_traits_and_type) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -1928,7 +1928,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangesDeclarationTraitsAndType) | Storage::PropertyDeclarationTraits::IsReadOnly)))))); } -TEST_F(ProjectStorage, SynchronizeTypesRemovesAPropertyDeclaration) +TEST_F(ProjectStorage, synchronize_types_removes_a_property_declaration) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -1948,7 +1948,7 @@ TEST_F(ProjectStorage, SynchronizeTypesRemovesAPropertyDeclaration) Storage::PropertyDeclarationTraits::IsList)))))); } -TEST_F(ProjectStorage, SynchronizeTypesAddsAPropertyDeclaration) +TEST_F(ProjectStorage, synchronize_types_adds_a_property_declaration) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -1978,7 +1978,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddsAPropertyDeclaration) | Storage::PropertyDeclarationTraits::IsReadOnly)))))); } -TEST_F(ProjectStorage, SynchronizeTypesRenameAPropertyDeclaration) +TEST_F(ProjectStorage, synchronize_types_rename_a_property_declaration) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2001,7 +2001,7 @@ TEST_F(ProjectStorage, SynchronizeTypesRenameAPropertyDeclaration) | Storage::PropertyDeclarationTraits::IsReadOnly)))))); } -TEST_F(ProjectStorage, UsingNonExistingPropertyTypeThrows) +TEST_F(ProjectStorage, using_non_existing_property_type_throws) { auto package{createSimpleSynchronizationPackage()}; package.types[0].propertyDeclarations[0].typeName = Storage::Synchronization::ImportedType{ @@ -2012,7 +2012,7 @@ TEST_F(ProjectStorage, UsingNonExistingPropertyTypeThrows) ASSERT_THROW(storage.synchronize(package), QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, UsingNonExistingQualifiedExportedPropertyTypeWithWrongNameThrows) +TEST_F(ProjectStorage, using_non_existing_qualified_exported_property_type_with_wrong_name_throws) { auto package{createSimpleSynchronizationPackage()}; package.types[0].propertyDeclarations[0].typeName = Storage::Synchronization::QualifiedImportedType{ @@ -2026,7 +2026,7 @@ TEST_F(ProjectStorage, UsingNonExistingQualifiedExportedPropertyTypeWithWrongNam ASSERT_THROW(storage.synchronize(package), QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, UsingNonExistingQualifiedExportedPropertyTypeWithWrongModuleThrows) +TEST_F(ProjectStorage, using_non_existing_qualified_exported_property_type_with_wrong_module_throws) { auto package{createSimpleSynchronizationPackage()}; package.types[0].propertyDeclarations[0].typeName = Storage::Synchronization::QualifiedImportedType{ @@ -2038,7 +2038,7 @@ TEST_F(ProjectStorage, UsingNonExistingQualifiedExportedPropertyTypeWithWrongMod ASSERT_THROW(storage.synchronize(package), QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, BreakingPropertyDeclarationTypeDependencyByDeletingTypeThrows) +TEST_F(ProjectStorage, breaking_property_declaration_type_dependency_by_deleting_type_throws) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2049,7 +2049,7 @@ TEST_F(ProjectStorage, BreakingPropertyDeclarationTypeDependencyByDeletingTypeTh ASSERT_THROW(storage.synchronize(package), QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, SynchronizeTypesAddFunctionDeclarations) +TEST_F(ProjectStorage, synchronize_types_add_function_declarations) { auto package{createSimpleSynchronizationPackage()}; @@ -2066,7 +2066,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddFunctionDeclarations) Eq(package.types[0].functionDeclarations[1])))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangesFunctionDeclarationReturnType) +TEST_F(ProjectStorage, synchronize_types_changes_function_declaration_return_type) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2085,7 +2085,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangesFunctionDeclarationReturnType) Eq(package.types[0].functionDeclarations[1])))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangesFunctionDeclarationName) +TEST_F(ProjectStorage, synchronize_types_changes_function_declaration_name) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2104,7 +2104,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangesFunctionDeclarationName) Eq(package.types[0].functionDeclarations[1])))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangesFunctionDeclarationPopParameters) +TEST_F(ProjectStorage, synchronize_types_changes_function_declaration_pop_parameters) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2123,7 +2123,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangesFunctionDeclarationPopParameters) Eq(package.types[0].functionDeclarations[1])))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangesFunctionDeclarationAppendParameters) +TEST_F(ProjectStorage, synchronize_types_changes_function_declaration_append_parameters) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2143,7 +2143,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangesFunctionDeclarationAppendParameter Eq(package.types[0].functionDeclarations[1])))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangesFunctionDeclarationChangeParameterName) +TEST_F(ProjectStorage, synchronize_types_changes_function_declaration_change_parameter_name) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2162,7 +2162,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangesFunctionDeclarationChangeParameter Eq(package.types[0].functionDeclarations[1])))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangesFunctionDeclarationChangeParameterTypeName) +TEST_F(ProjectStorage, synchronize_types_changes_function_declaration_change_parameter_type_name) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2181,7 +2181,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangesFunctionDeclarationChangeParameter Eq(package.types[0].functionDeclarations[1])))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangesFunctionDeclarationChangeParameterTraits) +TEST_F(ProjectStorage, synchronize_types_changes_function_declaration_change_parameter_traits) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2201,7 +2201,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangesFunctionDeclarationChangeParameter Eq(package.types[0].functionDeclarations[1])))))); } -TEST_F(ProjectStorage, SynchronizeTypesRemovesFunctionDeclaration) +TEST_F(ProjectStorage, synchronize_types_removes_function_declaration) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2219,7 +2219,7 @@ TEST_F(ProjectStorage, SynchronizeTypesRemovesFunctionDeclaration) UnorderedElementsAre(Eq(package.types[0].functionDeclarations[0])))))); } -TEST_F(ProjectStorage, SynchronizeTypesAddFunctionDeclaration) +TEST_F(ProjectStorage, synchronize_types_add_function_declaration) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2240,7 +2240,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddFunctionDeclaration) Eq(package.types[0].functionDeclarations[2])))))); } -TEST_F(ProjectStorage, SynchronizeTypesAddFunctionDeclarationsWithOverloads) +TEST_F(ProjectStorage, synchronize_types_add_function_declarations_with_overloads) { auto package{createSimpleSynchronizationPackage()}; package.types[0].functionDeclarations.push_back( @@ -2260,7 +2260,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddFunctionDeclarationsWithOverloads) Eq(package.types[0].functionDeclarations[2])))))); } -TEST_F(ProjectStorage, SynchronizeTypesFunctionDeclarationsAddingOverload) +TEST_F(ProjectStorage, synchronize_types_function_declarations_adding_overload) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2281,7 +2281,7 @@ TEST_F(ProjectStorage, SynchronizeTypesFunctionDeclarationsAddingOverload) Eq(package.types[0].functionDeclarations[2])))))); } -TEST_F(ProjectStorage, SynchronizeTypesFunctionDeclarationsRemovingOverload) +TEST_F(ProjectStorage, synchronize_types_function_declarations_removing_overload) { auto package{createSimpleSynchronizationPackage()}; package.types[0].functionDeclarations.push_back( @@ -2302,7 +2302,7 @@ TEST_F(ProjectStorage, SynchronizeTypesFunctionDeclarationsRemovingOverload) Eq(package.types[0].functionDeclarations[1])))))); } -TEST_F(ProjectStorage, SynchronizeTypesAddSignalDeclarations) +TEST_F(ProjectStorage, synchronize_types_add_signal_declarations) { auto package{createSimpleSynchronizationPackage()}; @@ -2319,7 +2319,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddSignalDeclarations) Eq(package.types[0].signalDeclarations[1])))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangesSignalDeclarationName) +TEST_F(ProjectStorage, synchronize_types_changes_signal_declaration_name) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2338,7 +2338,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangesSignalDeclarationName) Eq(package.types[0].signalDeclarations[1])))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangesSignalDeclarationPopParameters) +TEST_F(ProjectStorage, synchronize_types_changes_signal_declaration_pop_parameters) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2357,7 +2357,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangesSignalDeclarationPopParameters) Eq(package.types[0].signalDeclarations[1])))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangesSignalDeclarationAppendParameters) +TEST_F(ProjectStorage, synchronize_types_changes_signal_declaration_append_parameters) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2377,7 +2377,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangesSignalDeclarationAppendParameters) Eq(package.types[0].signalDeclarations[1])))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangesSignalDeclarationChangeParameterName) +TEST_F(ProjectStorage, synchronize_types_changes_signal_declaration_change_parameter_name) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2396,7 +2396,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangesSignalDeclarationChangeParameterNa Eq(package.types[0].signalDeclarations[1])))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangesSignalDeclarationChangeParameterTypeName) +TEST_F(ProjectStorage, synchronize_types_changes_signal_declaration_change_parameter_type_name) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2415,7 +2415,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangesSignalDeclarationChangeParameterTy Eq(package.types[0].signalDeclarations[1])))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangesSignalDeclarationChangeParameterTraits) +TEST_F(ProjectStorage, synchronize_types_changes_signal_declaration_change_parameter_traits) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2434,7 +2434,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangesSignalDeclarationChangeParameterTr Eq(package.types[0].signalDeclarations[1])))))); } -TEST_F(ProjectStorage, SynchronizeTypesRemovesSignalDeclaration) +TEST_F(ProjectStorage, synchronize_types_removes_signal_declaration) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2452,7 +2452,7 @@ TEST_F(ProjectStorage, SynchronizeTypesRemovesSignalDeclaration) UnorderedElementsAre(Eq(package.types[0].signalDeclarations[0])))))); } -TEST_F(ProjectStorage, SynchronizeTypesAddSignalDeclaration) +TEST_F(ProjectStorage, synchronize_types_add_signal_declaration) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2473,7 +2473,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddSignalDeclaration) Eq(package.types[0].signalDeclarations[2])))))); } -TEST_F(ProjectStorage, SynchronizeTypesAddSignalDeclarationsWithOverloads) +TEST_F(ProjectStorage, synchronize_types_add_signal_declarations_with_overloads) { auto package{createSimpleSynchronizationPackage()}; package.types[0].signalDeclarations.push_back( @@ -2493,7 +2493,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddSignalDeclarationsWithOverloads) Eq(package.types[0].signalDeclarations[2])))))); } -TEST_F(ProjectStorage, SynchronizeTypesSignalDeclarationsAddingOverload) +TEST_F(ProjectStorage, synchronize_types_signal_declarations_adding_overload) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2514,7 +2514,7 @@ TEST_F(ProjectStorage, SynchronizeTypesSignalDeclarationsAddingOverload) Eq(package.types[0].signalDeclarations[2])))))); } -TEST_F(ProjectStorage, SynchronizeTypesSignalDeclarationsRemovingOverload) +TEST_F(ProjectStorage, synchronize_types_signal_declarations_removing_overload) { auto package{createSimpleSynchronizationPackage()}; package.types[0].signalDeclarations.push_back( @@ -2535,7 +2535,7 @@ TEST_F(ProjectStorage, SynchronizeTypesSignalDeclarationsRemovingOverload) Eq(package.types[0].signalDeclarations[1])))))); } -TEST_F(ProjectStorage, SynchronizeTypesAddEnumerationDeclarations) +TEST_F(ProjectStorage, synchronize_types_add_enumeration_declarations) { auto package{createSimpleSynchronizationPackage()}; @@ -2552,7 +2552,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddEnumerationDeclarations) Eq(package.types[0].enumerationDeclarations[1])))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangesEnumerationDeclarationName) +TEST_F(ProjectStorage, synchronize_types_changes_enumeration_declaration_name) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2571,7 +2571,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangesEnumerationDeclarationName) Eq(package.types[0].enumerationDeclarations[1])))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangesEnumerationDeclarationPopEnumeratorDeclaration) +TEST_F(ProjectStorage, synchronize_types_changes_enumeration_declaration_pop_enumerator_declaration) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2590,7 +2590,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangesEnumerationDeclarationPopEnumerato Eq(package.types[0].enumerationDeclarations[1])))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangesEnumerationDeclarationAppendEnumeratorDeclaration) +TEST_F(ProjectStorage, synchronize_types_changes_enumeration_declaration_append_enumerator_declaration) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2610,7 +2610,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangesEnumerationDeclarationAppendEnumer Eq(package.types[0].enumerationDeclarations[1])))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangesEnumerationDeclarationChangeEnumeratorDeclarationName) +TEST_F(ProjectStorage, synchronize_types_changes_enumeration_declaration_change_enumerator_declaration_name) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2629,7 +2629,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangesEnumerationDeclarationChangeEnumer Eq(package.types[0].enumerationDeclarations[1])))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangesEnumerationDeclarationChangeEnumeratorDeclarationValue) +TEST_F(ProjectStorage, synchronize_types_changes_enumeration_declaration_change_enumerator_declaration_value) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2649,7 +2649,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangesEnumerationDeclarationChangeEnumer } TEST_F(ProjectStorage, - SynchronizeTypesChangesEnumerationDeclarationAddThatEnumeratorDeclarationHasValue) + synchronize_types_changes_enumeration_declaration_add_that_enumerator_declaration_has_value) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2670,7 +2670,7 @@ TEST_F(ProjectStorage, } TEST_F(ProjectStorage, - SynchronizeTypesChangesEnumerationDeclarationRemoveThatEnumeratorDeclarationHasValue) + synchronize_types_changes_enumeration_declaration_remove_that_enumerator_declaration_has_value) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2689,7 +2689,7 @@ TEST_F(ProjectStorage, Eq(package.types[0].enumerationDeclarations[1])))))); } -TEST_F(ProjectStorage, SynchronizeTypesRemovesEnumerationDeclaration) +TEST_F(ProjectStorage, synchronize_types_removes_enumeration_declaration) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2707,7 +2707,7 @@ TEST_F(ProjectStorage, SynchronizeTypesRemovesEnumerationDeclaration) Eq(package.types[0].enumerationDeclarations[0])))))); } -TEST_F(ProjectStorage, SynchronizeTypesAddEnumerationDeclaration) +TEST_F(ProjectStorage, synchronize_types_add_enumeration_declaration) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2728,7 +2728,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddEnumerationDeclaration) Eq(package.types[0].enumerationDeclarations[2])))))); } -TEST_F(ProjectStorage, FetchTypeIdBySourceIdAndName) +TEST_F(ProjectStorage, fetch_type_id_by_source_id_and_name) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2738,7 +2738,7 @@ TEST_F(ProjectStorage, FetchTypeIdBySourceIdAndName) ASSERT_THAT(storage.fetchTypeIdByExportedName("Object"), Eq(typeId)); } -TEST_F(ProjectStorage, FetchTypeIdByExportedName) +TEST_F(ProjectStorage, fetch_type_id_by_exported_name) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2748,7 +2748,7 @@ TEST_F(ProjectStorage, FetchTypeIdByExportedName) ASSERT_THAT(storage.fetchTypeIdByName(sourceId2, "QObject"), Eq(typeId)); } -TEST_F(ProjectStorage, FetchTypeIdByImporIdsAndExportedName) +TEST_F(ProjectStorage, fetch_type_id_by_impor_ids_and_exported_name) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2759,7 +2759,7 @@ TEST_F(ProjectStorage, FetchTypeIdByImporIdsAndExportedName) ASSERT_THAT(storage.fetchTypeIdByName(sourceId2, "QObject"), Eq(typeId)); } -TEST_F(ProjectStorage, FetchInvalidTypeIdByImporIdsAndExportedNameIfModuleIdsAreEmpty) +TEST_F(ProjectStorage, fetch_invalid_type_id_by_impor_ids_and_exported_name_if_module_ids_are_empty) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2769,7 +2769,7 @@ TEST_F(ProjectStorage, FetchInvalidTypeIdByImporIdsAndExportedNameIfModuleIdsAre ASSERT_FALSE(typeId.isValid()); } -TEST_F(ProjectStorage, FetchInvalidTypeIdByImporIdsAndExportedNameIfModuleIdsAreInvalid) +TEST_F(ProjectStorage, fetch_invalid_type_id_by_impor_ids_and_exported_name_if_module_ids_are_invalid) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2779,7 +2779,7 @@ TEST_F(ProjectStorage, FetchInvalidTypeIdByImporIdsAndExportedNameIfModuleIdsAre ASSERT_FALSE(typeId.isValid()); } -TEST_F(ProjectStorage, FetchInvalidTypeIdByImporIdsAndExportedNameIfNotInModule) +TEST_F(ProjectStorage, fetch_invalid_type_id_by_impor_ids_and_exported_name_if_not_in_module) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -2790,7 +2790,7 @@ TEST_F(ProjectStorage, FetchInvalidTypeIdByImporIdsAndExportedNameIfNotInModule) ASSERT_FALSE(typeId.isValid()); } -TEST_F(ProjectStorage, SynchronizeTypesAddAliasDeclarations) +TEST_F(ProjectStorage, synchronize_types_add_alias_declarations) { auto package{createSynchronizationPackageWithAliases()}; @@ -2816,7 +2816,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddAliasDeclarations) Storage::PropertyDeclarationTraits::IsList)))))); } -TEST_F(ProjectStorage, SynchronizeTypesAddAliasDeclarationsAgain) +TEST_F(ProjectStorage, synchronize_types_add_alias_declarations_again) { auto package{createSynchronizationPackageWithAliases()}; storage.synchronize(package); @@ -2843,7 +2843,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddAliasDeclarationsAgain) Storage::PropertyDeclarationTraits::IsList)))))); } -TEST_F(ProjectStorage, SynchronizeTypesRemoveAliasDeclarations) +TEST_F(ProjectStorage, synchronize_types_remove_alias_declarations) { auto package{createSynchronizationPackageWithAliases()}; storage.synchronize(package); @@ -2868,7 +2868,7 @@ TEST_F(ProjectStorage, SynchronizeTypesRemoveAliasDeclarations) Storage::PropertyDeclarationTraits::IsList)))))); } -TEST_F(ProjectStorage, SynchronizeTypesAddAliasDeclarationsThrowsForWrongTypeName) +TEST_F(ProjectStorage, synchronize_types_add_alias_declarations_throws_for_wrong_type_name) { auto package{createSynchronizationPackageWithAliases()}; package.types[2].propertyDeclarations[1].typeName = Storage::Synchronization::ImportedType{ @@ -2881,7 +2881,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddAliasDeclarationsThrowsForWrongTypeNam {sourceId4}}), QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, SynchronizeTypesAddAliasDeclarationsThrowsForWrongPropertyName) +TEST_F(ProjectStorage, synchronize_types_add_alias_declarations_throws_for_wrong_property_name) { auto package{createSynchronizationPackageWithAliases()}; package.types[2].propertyDeclarations[1].aliasPropertyName = "childrenWrong"; @@ -2894,7 +2894,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddAliasDeclarationsThrowsForWrongPropert QmlDesigner::PropertyNameDoesNotExists); } -TEST_F(ProjectStorage, SynchronizeTypesChangeAliasDeclarationsTypeName) +TEST_F(ProjectStorage, synchronize_types_change_alias_declarations_type_name) { auto package{createSynchronizationPackageWithAliases()}; storage.synchronize(package); @@ -2924,7 +2924,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangeAliasDeclarationsTypeName) Storage::PropertyDeclarationTraits::IsList)))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangeAliasDeclarationsPropertyName) +TEST_F(ProjectStorage, synchronize_types_change_alias_declarations_property_name) { auto package{createSynchronizationPackageWithAliases()}; storage.synchronize(package); @@ -2951,7 +2951,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangeAliasDeclarationsPropertyName) Storage::PropertyDeclarationTraits::IsList)))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangeAliasDeclarationsToPropertyDeclaration) +TEST_F(ProjectStorage, synchronize_types_change_alias_declarations_to_property_declaration) { auto package{createSynchronizationPackageWithAliases()}; storage.synchronize(package); @@ -2982,7 +2982,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangeAliasDeclarationsToPropertyDeclarat Storage::PropertyDeclarationTraits::IsList)))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangePropertyDeclarationsToAliasDeclaration) +TEST_F(ProjectStorage, synchronize_types_change_property_declarations_to_alias_declaration) { auto package{createSynchronizationPackageWithAliases()}; auto packageChanged = package; @@ -3015,7 +3015,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangePropertyDeclarationsToAliasDeclarat Storage::PropertyDeclarationTraits::IsList)))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangeAliasTargetPropertyDeclarationTraits) +TEST_F(ProjectStorage, synchronize_types_change_alias_target_property_declaration_traits) { auto package{createSynchronizationPackageWithAliases()}; storage.synchronize(package); @@ -3043,7 +3043,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangeAliasTargetPropertyDeclarationTrait Storage::PropertyDeclarationTraits::IsList)))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangeAliasTargetPropertyDeclarationTypeName) +TEST_F(ProjectStorage, synchronize_types_change_alias_target_property_declaration_type_name) { auto package{createSynchronizationPackageWithAliases()}; storage.synchronize(package); @@ -3073,7 +3073,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangeAliasTargetPropertyDeclarationTypeN Storage::PropertyDeclarationTraits::IsList)))))); } -TEST_F(ProjectStorage, SynchronizeTypesRemovePropertyDeclarationWithAnAliasThrows) +TEST_F(ProjectStorage, synchronize_types_remove_property_declaration_with_an_alias_throws) { auto package{createSynchronizationPackageWithAliases()}; storage.synchronize(package); @@ -3084,7 +3084,7 @@ TEST_F(ProjectStorage, SynchronizeTypesRemovePropertyDeclarationWithAnAliasThrow Sqlite::ConstraintPreventsModification); } -TEST_F(ProjectStorage, SynchronizeTypesRemovePropertyDeclarationAndAlias) +TEST_F(ProjectStorage, synchronize_types_remove_property_declaration_and_alias) { auto package{createSynchronizationPackageWithAliases()}; storage.synchronize(package); @@ -3112,7 +3112,7 @@ TEST_F(ProjectStorage, SynchronizeTypesRemovePropertyDeclarationAndAlias) Storage::PropertyDeclarationTraits::IsList)))))); } -TEST_F(ProjectStorage, SynchronizeTypesRemoveTypeWithAliasTargetPropertyDeclarationThrows) +TEST_F(ProjectStorage, synchronize_types_remove_type_with_alias_target_property_declaration_throws) { auto package{createSynchronizationPackageWithAliases()}; package.types[2].propertyDeclarations[2].typeName = Storage::Synchronization::ImportedType{ @@ -3124,7 +3124,7 @@ TEST_F(ProjectStorage, SynchronizeTypesRemoveTypeWithAliasTargetPropertyDeclarat QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, SynchronizeTypesRemoveTypeAndAliasPropertyDeclaration) +TEST_F(ProjectStorage, synchronize_types_remove_type_and_alias_property_declaration) { auto package{createSynchronizationPackageWithAliases()}; package.types[2].propertyDeclarations[2].typeName = Storage::Synchronization::ImportedType{ @@ -3154,7 +3154,7 @@ TEST_F(ProjectStorage, SynchronizeTypesRemoveTypeAndAliasPropertyDeclaration) Storage::PropertyDeclarationTraits::IsList)))))); } -TEST_F(ProjectStorage, UpdateAliasPropertyIfPropertyIsOverloaded) +TEST_F(ProjectStorage, update_alias_property_if_property_is_overloaded) { auto package{createSynchronizationPackageWithAliases()}; storage.synchronize(package); @@ -3184,7 +3184,7 @@ TEST_F(ProjectStorage, UpdateAliasPropertyIfPropertyIsOverloaded) Storage::PropertyDeclarationTraits::IsList)))))); } -TEST_F(ProjectStorage, AliasPropertyIsOverloaded) +TEST_F(ProjectStorage, alias_property_is_overloaded) { auto package{createSynchronizationPackageWithAliases()}; package.types[0].propertyDeclarations.push_back(Storage::Synchronization::PropertyDeclaration{ @@ -3213,7 +3213,7 @@ TEST_F(ProjectStorage, AliasPropertyIsOverloaded) Storage::PropertyDeclarationTraits::IsList)))))); } -TEST_F(ProjectStorage, UpdateAliasPropertyIfOverloadedPropertyIsRemoved) +TEST_F(ProjectStorage, update_alias_property_if_overloaded_property_is_removed) { auto package{createSynchronizationPackageWithAliases()}; package.types[0].propertyDeclarations.push_back(Storage::Synchronization::PropertyDeclaration{ @@ -3245,7 +3245,7 @@ TEST_F(ProjectStorage, UpdateAliasPropertyIfOverloadedPropertyIsRemoved) Storage::PropertyDeclarationTraits::IsList)))))); } -TEST_F(ProjectStorage, RelinkAliasProperty) +TEST_F(ProjectStorage, relink_alias_property) { auto package{createSynchronizationPackageWithAliases()}; package.types[1].propertyDeclarations[0].typeName = Storage::Synchronization::ImportedType{ @@ -3277,7 +3277,7 @@ TEST_F(ProjectStorage, RelinkAliasProperty) Storage::PropertyDeclarationTraits::IsList)))))); } -TEST_F(ProjectStorage, DoNotRelinkAliasPropertyForQualifiedImportedTypeName) +TEST_F(ProjectStorage, do_not_relink_alias_property_for_qualified_imported_type_name) { auto package{createSynchronizationPackageWithAliases()}; package.types[1].propertyDeclarations[0].typeName = Storage::Synchronization::QualifiedImportedType{ @@ -3294,7 +3294,7 @@ TEST_F(ProjectStorage, DoNotRelinkAliasPropertyForQualifiedImportedTypeName) } TEST_F(ProjectStorage, - DoRelinkAliasPropertyForQualifiedImportedTypeNameEvenIfAnOtherSimilarTimeNameExists) + do_relink_alias_property_for_qualified_imported_type_name_even_if_an_other_similar_time_name_exists) { auto package{createSynchronizationPackageWithAliases()}; package.types[1].propertyDeclarations[0].typeName = Storage::Synchronization::QualifiedImportedType{ @@ -3333,7 +3333,7 @@ TEST_F(ProjectStorage, Storage::PropertyDeclarationTraits::IsList)))))); } -TEST_F(ProjectStorage, RelinkAliasPropertyReactToTypeNameChange) +TEST_F(ProjectStorage, relink_alias_property_react_to_type_name_change) { auto package{createSynchronizationPackageWithAliases2()}; package.types[2].propertyDeclarations.push_back(Storage::Synchronization::PropertyDeclaration{ @@ -3361,7 +3361,7 @@ TEST_F(ProjectStorage, RelinkAliasPropertyReactToTypeNameChange) Storage::PropertyDeclarationTraits::IsList)))))); } -TEST_F(ProjectStorage, DoNotRelinkAliasPropertyForDeletedType) +TEST_F(ProjectStorage, do_not_relink_alias_property_for_deleted_type) { auto package{createSynchronizationPackageWithAliases()}; package.types[1].propertyDeclarations[0].typeName = Storage::Synchronization::ImportedType{ @@ -3381,7 +3381,7 @@ TEST_F(ProjectStorage, DoNotRelinkAliasPropertyForDeletedType) TypeTraits::Reference)))); } -TEST_F(ProjectStorage, DoNotRelinkAliasPropertyForDeletedTypeAndPropertyType) +TEST_F(ProjectStorage, do_not_relink_alias_property_for_deleted_type_and_property_type) { auto package{createSynchronizationPackageWithAliases()}; package.types[1].propertyDeclarations[0].typeName = Storage::Synchronization::ImportedType{ @@ -3404,7 +3404,7 @@ TEST_F(ProjectStorage, DoNotRelinkAliasPropertyForDeletedTypeAndPropertyType) ASSERT_THAT(storage.fetchTypes(), SizeIs(2)); } -TEST_F(ProjectStorage, DoNotRelinkAliasPropertyForDeletedTypeAndPropertyTypeNameChange) +TEST_F(ProjectStorage, do_not_relink_alias_property_for_deleted_type_and_property_type_name_change) { auto package{createSynchronizationPackageWithAliases()}; package.types[1].propertyDeclarations[0].typeName = Storage::Synchronization::ImportedType{ @@ -3427,7 +3427,7 @@ TEST_F(ProjectStorage, DoNotRelinkAliasPropertyForDeletedTypeAndPropertyTypeName TypeTraits::Reference)))); } -TEST_F(ProjectStorage, DoNotRelinkPropertyTypeDoesNotExists) +TEST_F(ProjectStorage, do_not_relink_property_type_does_not_exists) { auto package{createSynchronizationPackageWithAliases()}; package.types[1].propertyDeclarations[0].typeName = Storage::Synchronization::ImportedType{ @@ -3440,7 +3440,7 @@ TEST_F(ProjectStorage, DoNotRelinkPropertyTypeDoesNotExists) QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, DoNotRelinkAliasPropertyTypeDoesNotExists) +TEST_F(ProjectStorage, do_not_relink_alias_property_type_does_not_exists) { auto package{createSynchronizationPackageWithAliases2()}; package.types[1].propertyDeclarations[0].typeName = Storage::Synchronization::ImportedType{ @@ -3452,7 +3452,7 @@ TEST_F(ProjectStorage, DoNotRelinkAliasPropertyTypeDoesNotExists) QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, ChangePrototypeTypeName) +TEST_F(ProjectStorage, change_prototype_type_name) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -3468,7 +3468,7 @@ TEST_F(ProjectStorage, ChangePrototypeTypeName) TypeTraits::Reference))); } -TEST_F(ProjectStorage, ChangeExtensionTypeName) +TEST_F(ProjectStorage, change_extension_type_name) { auto package{createSimpleSynchronizationPackage()}; std::swap(package.types.front().extension, package.types.front().prototype); @@ -3485,7 +3485,7 @@ TEST_F(ProjectStorage, ChangeExtensionTypeName) TypeTraits::Reference))); } -TEST_F(ProjectStorage, ChangePrototypeTypeModuleId) +TEST_F(ProjectStorage, change_prototype_type_module_id) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -3501,7 +3501,7 @@ TEST_F(ProjectStorage, ChangePrototypeTypeModuleId) TypeTraits::Reference))); } -TEST_F(ProjectStorage, ChangeExtensionTypeModuleId) +TEST_F(ProjectStorage, change_extension_type_module_id) { auto package{createSimpleSynchronizationPackage()}; std::swap(package.types.front().extension, package.types.front().prototype); @@ -3518,7 +3518,7 @@ TEST_F(ProjectStorage, ChangeExtensionTypeModuleId) TypeTraits::Reference))); } -TEST_F(ProjectStorage, ChangeQualifiedPrototypeTypeModuleIdThrows) +TEST_F(ProjectStorage, change_qualified_prototype_type_module_id_throws) { auto package{createSimpleSynchronizationPackage()}; package.types[0].prototype = Storage::Synchronization::QualifiedImportedType{ @@ -3532,7 +3532,7 @@ TEST_F(ProjectStorage, ChangeQualifiedPrototypeTypeModuleIdThrows) QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, ChangeQualifiedExtensionTypeModuleIdThrows) +TEST_F(ProjectStorage, change_qualified_extension_type_module_id_throws) { auto package{createSimpleSynchronizationPackage()}; std::swap(package.types.front().extension, package.types.front().prototype); @@ -3547,7 +3547,7 @@ TEST_F(ProjectStorage, ChangeQualifiedExtensionTypeModuleIdThrows) QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, ChangeQualifiedPrototypeTypeModuleId) +TEST_F(ProjectStorage, change_qualified_prototype_type_module_id) { auto package{createSimpleSynchronizationPackage()}; package.types[0].prototype = Storage::Synchronization::QualifiedImportedType{ @@ -3573,7 +3573,7 @@ TEST_F(ProjectStorage, ChangeQualifiedPrototypeTypeModuleId) TypeTraits::Reference))); } -TEST_F(ProjectStorage, ChangeQualifiedExtensionTypeModuleId) +TEST_F(ProjectStorage, change_qualified_extension_type_module_id) { auto package{createSimpleSynchronizationPackage()}; std::swap(package.types.front().extension, package.types.front().prototype); @@ -3600,7 +3600,7 @@ TEST_F(ProjectStorage, ChangeQualifiedExtensionTypeModuleId) TypeTraits::Reference))); } -TEST_F(ProjectStorage, ChangePrototypeTypeNameAndModuleId) +TEST_F(ProjectStorage, change_prototype_type_name_and_module_id) { auto package{createSimpleSynchronizationPackage()}; package.types[0].prototype = Storage::Synchronization::ImportedType{"Object"}; @@ -3623,7 +3623,7 @@ TEST_F(ProjectStorage, ChangePrototypeTypeNameAndModuleId) TypeTraits::Reference))); } -TEST_F(ProjectStorage, ChangeExtensionTypeNameAndModuleId) +TEST_F(ProjectStorage, change_extension_type_name_and_module_id) { auto package{createSimpleSynchronizationPackage()}; std::swap(package.types.front().extension, package.types.front().prototype); @@ -3647,7 +3647,7 @@ TEST_F(ProjectStorage, ChangeExtensionTypeNameAndModuleId) TypeTraits::Reference))); } -TEST_F(ProjectStorage, ChangePrototypeTypeNameThrowsForWrongNativePrototupeTypeName) +TEST_F(ProjectStorage, change_prototype_type_name_throws_for_wrong_native_prototupe_type_name) { auto package{createSimpleSynchronizationPackage()}; package.types[0].propertyDeclarations[0].typeName = Storage::Synchronization::ImportedType{ @@ -3661,7 +3661,7 @@ TEST_F(ProjectStorage, ChangePrototypeTypeNameThrowsForWrongNativePrototupeTypeN QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, ChangeExtensionTypeNameThrowsForWrongNativeExtensionTypeName) +TEST_F(ProjectStorage, change_extension_type_name_throws_for_wrong_native_extension_type_name) { auto package{createSimpleSynchronizationPackage()}; std::swap(package.types.front().extension, package.types.front().prototype); @@ -3676,7 +3676,7 @@ TEST_F(ProjectStorage, ChangeExtensionTypeNameThrowsForWrongNativeExtensionTypeN QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, ThrowForPrototypeChainCycles) +TEST_F(ProjectStorage, throw_for_prototype_chain_cycles) { auto package{createSimpleSynchronizationPackage()}; package.types[1].prototype = Storage::Synchronization::ImportedType{"Object2"}; @@ -3700,7 +3700,7 @@ TEST_F(ProjectStorage, ThrowForPrototypeChainCycles) QmlDesigner::PrototypeChainCycle); } -TEST_F(ProjectStorage, ThrowForExtensionChainCycles) +TEST_F(ProjectStorage, throw_for_extension_chain_cycles) { auto package{createSimpleSynchronizationPackage()}; std::swap(package.types.front().extension, package.types.front().prototype); @@ -3725,7 +3725,7 @@ TEST_F(ProjectStorage, ThrowForExtensionChainCycles) QmlDesigner::PrototypeChainCycle); } -TEST_F(ProjectStorage, ThrowForTypeIdAndPrototypeIdAreTheSame) +TEST_F(ProjectStorage, throw_for_type_id_and_prototype_id_are_the_same) { auto package{createSimpleSynchronizationPackage()}; package.types[1].prototype = Storage::Synchronization::ImportedType{"Object"}; @@ -3733,7 +3733,7 @@ TEST_F(ProjectStorage, ThrowForTypeIdAndPrototypeIdAreTheSame) ASSERT_THROW(storage.synchronize(package), QmlDesigner::PrototypeChainCycle); } -TEST_F(ProjectStorage, ThrowForTypeIdAndExtensionIdAreTheSame) +TEST_F(ProjectStorage, throw_for_type_id_and_extension_id_are_the_same) { auto package{createSimpleSynchronizationPackage()}; std::swap(package.types.front().extension, package.types.front().prototype); @@ -3742,7 +3742,7 @@ TEST_F(ProjectStorage, ThrowForTypeIdAndExtensionIdAreTheSame) ASSERT_THROW(storage.synchronize(package), QmlDesigner::PrototypeChainCycle); } -TEST_F(ProjectStorage, ThrowForTypeIdAndPrototypeIdAreTheSameForRelinking) +TEST_F(ProjectStorage, throw_for_type_id_and_prototype_id_are_the_same_for_relinking) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -3755,7 +3755,7 @@ TEST_F(ProjectStorage, ThrowForTypeIdAndPrototypeIdAreTheSameForRelinking) QmlDesigner::PrototypeChainCycle); } -TEST_F(ProjectStorage, ThrowForTypeIdAndExtenssionIdAreTheSameForRelinking) +TEST_F(ProjectStorage, throw_for_type_id_and_extenssion_id_are_the_same_for_relinking) { auto package{createSimpleSynchronizationPackage()}; std::swap(package.types.front().extension, package.types.front().prototype); @@ -3769,7 +3769,7 @@ TEST_F(ProjectStorage, ThrowForTypeIdAndExtenssionIdAreTheSameForRelinking) QmlDesigner::PrototypeChainCycle); } -TEST_F(ProjectStorage, RecursiveAliases) +TEST_F(ProjectStorage, recursive_aliases) { auto package{createSynchronizationPackageWithRecursiveAliases()}; @@ -3787,7 +3787,7 @@ TEST_F(ProjectStorage, RecursiveAliases) Storage::PropertyDeclarationTraits::IsList)))))); } -TEST_F(ProjectStorage, RecursiveAliasesChangePropertyType) +TEST_F(ProjectStorage, recursive_aliases_change_property_type) { auto package{createSynchronizationPackageWithRecursiveAliases()}; storage.synchronize(package); @@ -3809,7 +3809,7 @@ TEST_F(ProjectStorage, RecursiveAliasesChangePropertyType) Storage::PropertyDeclarationTraits::IsList)))))); } -TEST_F(ProjectStorage, UpdateAliasesAfterInjectingProperty) +TEST_F(ProjectStorage, update_aliases_after_injecting_property) { auto package{createSynchronizationPackageWithRecursiveAliases()}; storage.synchronize(package); @@ -3833,7 +3833,7 @@ TEST_F(ProjectStorage, UpdateAliasesAfterInjectingProperty) | Storage::PropertyDeclarationTraits::IsReadOnly)))))); } -TEST_F(ProjectStorage, UpdateAliasesAfterChangeAliasToProperty) +TEST_F(ProjectStorage, update_aliases_after_change_alias_to_property) { auto package{createSynchronizationPackageWithRecursiveAliases()}; storage.synchronize(package); @@ -3870,7 +3870,7 @@ TEST_F(ProjectStorage, UpdateAliasesAfterChangeAliasToProperty) ""))))))); } -TEST_F(ProjectStorage, UpdateAliasesAfterChangePropertyToAlias) +TEST_F(ProjectStorage, update_aliases_after_change_property_to_alias) { auto package{createSynchronizationPackageWithRecursiveAliases()}; package.types[3].propertyDeclarations[0].traits = Storage::PropertyDeclarationTraits::IsList @@ -3897,7 +3897,7 @@ TEST_F(ProjectStorage, UpdateAliasesAfterChangePropertyToAlias) "objects")))))); } -TEST_F(ProjectStorage, CheckForProtoTypeCycleThrows) +TEST_F(ProjectStorage, check_for_proto_type_cycle_throws) { auto package{createSynchronizationPackageWithRecursiveAliases()}; package.types[1].propertyDeclarations.clear(); @@ -3908,7 +3908,7 @@ TEST_F(ProjectStorage, CheckForProtoTypeCycleThrows) ASSERT_THROW(storage.synchronize(package), QmlDesigner::AliasChainCycle); } -TEST_F(ProjectStorage, CheckForProtoTypeCycleAfterUpdateThrows) +TEST_F(ProjectStorage, check_for_proto_type_cycle_after_update_throws) { auto package{createSynchronizationPackageWithRecursiveAliases()}; storage.synchronize(package); @@ -3922,7 +3922,7 @@ TEST_F(ProjectStorage, CheckForProtoTypeCycleAfterUpdateThrows) QmlDesigner::AliasChainCycle); } -TEST_F(ProjectStorage, QualifiedPrototype) +TEST_F(ProjectStorage, qualified_prototype) { auto package{createSimpleSynchronizationPackage()}; package.types[0].prototype = Storage::Synchronization::QualifiedImportedType{ @@ -3949,7 +3949,7 @@ TEST_F(ProjectStorage, QualifiedPrototype) TypeTraits::Reference))); } -TEST_F(ProjectStorage, QualifiedExtension) +TEST_F(ProjectStorage, qualified_extension) { auto package{createSimpleSynchronizationPackage()}; std::swap(package.types.front().extension, package.types.front().prototype); @@ -3977,7 +3977,7 @@ TEST_F(ProjectStorage, QualifiedExtension) TypeTraits::Reference))); } -TEST_F(ProjectStorage, QualifiedPrototypeUpperDownTheModuleChainThrows) +TEST_F(ProjectStorage, qualified_prototype_upper_down_the_module_chain_throws) { auto package{createSimpleSynchronizationPackage()}; package.types[0].prototype = Storage::Synchronization::QualifiedImportedType{ @@ -3989,7 +3989,7 @@ TEST_F(ProjectStorage, QualifiedPrototypeUpperDownTheModuleChainThrows) ASSERT_THROW(storage.synchronize(package), QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, QualifiedExtensionUpperDownTheModuleChainThrows) +TEST_F(ProjectStorage, qualified_extension_upper_down_the_module_chain_throws) { auto package{createSimpleSynchronizationPackage()}; std::swap(package.types.front().extension, package.types.front().prototype); @@ -4002,7 +4002,7 @@ TEST_F(ProjectStorage, QualifiedExtensionUpperDownTheModuleChainThrows) ASSERT_THROW(storage.synchronize(package), QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, QualifiedPrototypeUpperInTheModuleChain) +TEST_F(ProjectStorage, qualified_prototype_upper_in_the_module_chain) { auto package{createSimpleSynchronizationPackage()}; package.types[0].prototype = Storage::Synchronization::QualifiedImportedType{ @@ -4031,7 +4031,7 @@ TEST_F(ProjectStorage, QualifiedPrototypeUpperInTheModuleChain) TypeTraits::Reference))); } -TEST_F(ProjectStorage, QualifiedExtensionUpperInTheModuleChain) +TEST_F(ProjectStorage, qualified_extension_upper_in_the_module_chain) { auto package{createSimpleSynchronizationPackage()}; std::swap(package.types.front().extension, package.types.front().prototype); @@ -4061,7 +4061,7 @@ TEST_F(ProjectStorage, QualifiedExtensionUpperInTheModuleChain) TypeTraits::Reference))); } -TEST_F(ProjectStorage, QualifiedPrototypeWithWrongVersionThrows) +TEST_F(ProjectStorage, qualified_prototype_with_wrong_version_throws) { auto package{createSimpleSynchronizationPackage()}; package.types[0].prototype = Storage::Synchronization::QualifiedImportedType{ @@ -4081,7 +4081,7 @@ TEST_F(ProjectStorage, QualifiedPrototypeWithWrongVersionThrows) ASSERT_THROW(storage.synchronize(package), QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, QualifiedExtensionWithWrongVersionThrows) +TEST_F(ProjectStorage, qualified_extension_with_wrong_version_throws) { auto package{createSimpleSynchronizationPackage()}; std::swap(package.types.front().extension, package.types.front().prototype); @@ -4102,7 +4102,7 @@ TEST_F(ProjectStorage, QualifiedExtensionWithWrongVersionThrows) ASSERT_THROW(storage.synchronize(package), QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, QualifiedPrototypeWithVersion) +TEST_F(ProjectStorage, qualified_prototype_with_version) { auto package{createSimpleSynchronizationPackage()}; package.imports[0].version = Storage::Version{2}; @@ -4129,7 +4129,7 @@ TEST_F(ProjectStorage, QualifiedPrototypeWithVersion) TypeTraits::Reference))); } -TEST_F(ProjectStorage, QualifiedExtensionWithVersion) +TEST_F(ProjectStorage, qualified_extension_with_version) { auto package{createSimpleSynchronizationPackage()}; std::swap(package.types.front().extension, package.types.front().prototype); @@ -4157,7 +4157,7 @@ TEST_F(ProjectStorage, QualifiedExtensionWithVersion) TypeTraits::Reference))); } -TEST_F(ProjectStorage, QualifiedPrototypeWithVersionInTheProtoTypeChain) +TEST_F(ProjectStorage, qualified_prototype_with_version_in_the_proto_type_chain) { auto package{createSimpleSynchronizationPackage()}; package.imports[1].version = Storage::Version{2}; @@ -4186,7 +4186,7 @@ TEST_F(ProjectStorage, QualifiedPrototypeWithVersionInTheProtoTypeChain) TypeTraits::Reference))); } -TEST_F(ProjectStorage, QualifiedExtensionWithVersionInTheProtoTypeChain) +TEST_F(ProjectStorage, qualified_extension_with_version_in_the_proto_type_chain) { auto package{createSimpleSynchronizationPackage()}; std::swap(package.types.front().extension, package.types.front().prototype); @@ -4216,7 +4216,7 @@ TEST_F(ProjectStorage, QualifiedExtensionWithVersionInTheProtoTypeChain) TypeTraits::Reference))); } -TEST_F(ProjectStorage, QualifiedPrototypeWithVersionDownTheProtoTypeChainThrows) +TEST_F(ProjectStorage, qualified_prototype_with_version_down_the_proto_type_chain_throws) { auto package{createSimpleSynchronizationPackage()}; package.types[0].prototype = Storage::Synchronization::QualifiedImportedType{ @@ -4228,7 +4228,7 @@ TEST_F(ProjectStorage, QualifiedPrototypeWithVersionDownTheProtoTypeChainThrows) ASSERT_THROW(storage.synchronize(package), QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, QualifiedExtensionWithVersionDownTheProtoTypeChainThrows) +TEST_F(ProjectStorage, qualified_extension_with_version_down_the_proto_type_chain_throws) { auto package{createSimpleSynchronizationPackage()}; std::swap(package.types.front().extension, package.types.front().prototype); @@ -4241,7 +4241,7 @@ TEST_F(ProjectStorage, QualifiedExtensionWithVersionDownTheProtoTypeChainThrows) ASSERT_THROW(storage.synchronize(package), QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, QualifiedPropertyDeclarationTypeName) +TEST_F(ProjectStorage, qualified_property_declaration_type_name) { auto package{createSimpleSynchronizationPackage()}; package.types[0].propertyDeclarations[0].typeName = Storage::Synchronization::QualifiedImportedType{ @@ -4268,7 +4268,7 @@ TEST_F(ProjectStorage, QualifiedPropertyDeclarationTypeName) Storage::PropertyDeclarationTraits::IsList))))); } -TEST_F(ProjectStorage, QualifiedPropertyDeclarationTypeNameDownTheModuleChainThrows) +TEST_F(ProjectStorage, qualified_property_declaration_type_name_down_the_module_chain_throws) { auto package{createSimpleSynchronizationPackage()}; package.types[0].propertyDeclarations[0].typeName = Storage::Synchronization::QualifiedImportedType{ @@ -4280,7 +4280,7 @@ TEST_F(ProjectStorage, QualifiedPropertyDeclarationTypeNameDownTheModuleChainThr ASSERT_THROW(storage.synchronize(package), QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, QualifiedPropertyDeclarationTypeNameInTheModuleChain) +TEST_F(ProjectStorage, qualified_property_declaration_type_name_in_the_module_chain) { auto package{createSimpleSynchronizationPackage()}; package.types[0].propertyDeclarations[0].typeName = Storage::Synchronization::QualifiedImportedType{ @@ -4309,7 +4309,7 @@ TEST_F(ProjectStorage, QualifiedPropertyDeclarationTypeNameInTheModuleChain) Storage::PropertyDeclarationTraits::IsList))))); } -TEST_F(ProjectStorage, QualifiedPropertyDeclarationTypeNameWithVersion) +TEST_F(ProjectStorage, qualified_property_declaration_type_name_with_version) { auto package{createSimpleSynchronizationPackage()}; package.types[0].propertyDeclarations[0].typeName = Storage::Synchronization::QualifiedImportedType{ @@ -4327,7 +4327,7 @@ TEST_F(ProjectStorage, QualifiedPropertyDeclarationTypeNameWithVersion) Storage::PropertyDeclarationTraits::IsList))))); } -TEST_F(ProjectStorage, ChangePropertyTypeModuleIdWithQualifiedTypeThrows) +TEST_F(ProjectStorage, change_property_type_module_id_with_qualified_type_throws) { auto package{createSimpleSynchronizationPackage()}; package.types[0].propertyDeclarations[0].typeName = Storage::Synchronization::QualifiedImportedType{ @@ -4341,7 +4341,7 @@ TEST_F(ProjectStorage, ChangePropertyTypeModuleIdWithQualifiedTypeThrows) QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, ChangePropertyTypeModuleIdWithQualifiedType) +TEST_F(ProjectStorage, change_property_type_module_id_with_qualified_type) { auto package{createSimpleSynchronizationPackage()}; package.types[0].propertyDeclarations[0].typeName = Storage::Synchronization::QualifiedImportedType{ @@ -4368,7 +4368,7 @@ TEST_F(ProjectStorage, ChangePropertyTypeModuleIdWithQualifiedType) Storage::PropertyDeclarationTraits::IsList)))))); } -TEST_F(ProjectStorage, AddFileStatuses) +TEST_F(ProjectStorage, add_file_statuses) { FileStatus fileStatus1{sourceId1, 100, 100}; FileStatus fileStatus2{sourceId2, 101, 101}; @@ -4379,7 +4379,7 @@ TEST_F(ProjectStorage, AddFileStatuses) UnorderedElementsAre(fileStatus1, fileStatus2)); } -TEST_F(ProjectStorage, RemoveFileStatus) +TEST_F(ProjectStorage, remove_file_status) { FileStatus fileStatus1{sourceId1, 100, 100}; FileStatus fileStatus2{sourceId2, 101, 101}; @@ -4390,7 +4390,7 @@ TEST_F(ProjectStorage, RemoveFileStatus) ASSERT_THAT(convert(storage.fetchAllFileStatuses()), UnorderedElementsAre(fileStatus1)); } -TEST_F(ProjectStorage, UpdateFileStatus) +TEST_F(ProjectStorage, update_file_status) { FileStatus fileStatus1{sourceId1, 100, 100}; FileStatus fileStatus2{sourceId2, 101, 101}; @@ -4403,7 +4403,7 @@ TEST_F(ProjectStorage, UpdateFileStatus) UnorderedElementsAre(fileStatus1, fileStatus2b)); } -TEST_F(ProjectStorage, ThrowForInvalidSourceIdInFileStatus) +TEST_F(ProjectStorage, throw_for_invalid_source_id_in_file_status) { FileStatus fileStatus1{SourceId{}, 100, 100}; @@ -4411,7 +4411,7 @@ TEST_F(ProjectStorage, ThrowForInvalidSourceIdInFileStatus) QmlDesigner::FileStatusHasInvalidSourceId); } -TEST_F(ProjectStorage, FetchAllFileStatuses) +TEST_F(ProjectStorage, fetch_all_file_statuses) { FileStatus fileStatus1{sourceId1, 100, 100}; FileStatus fileStatus2{sourceId2, 101, 101}; @@ -4422,7 +4422,7 @@ TEST_F(ProjectStorage, FetchAllFileStatuses) ASSERT_THAT(fileStatuses, ElementsAre(fileStatus1, fileStatus2)); } -TEST_F(ProjectStorage, FetchAllFileStatusesReverse) +TEST_F(ProjectStorage, fetch_all_file_statuses_reverse) { FileStatus fileStatus1{sourceId1, 100, 100}; FileStatus fileStatus2{sourceId2, 101, 101}; @@ -4433,7 +4433,7 @@ TEST_F(ProjectStorage, FetchAllFileStatusesReverse) ASSERT_THAT(fileStatuses, ElementsAre(fileStatus1, fileStatus2)); } -TEST_F(ProjectStorage, FetchFileStatus) +TEST_F(ProjectStorage, fetch_file_status) { FileStatus fileStatus1{sourceId1, 100, 100}; FileStatus fileStatus2{sourceId2, 101, 101}; @@ -4444,7 +4444,7 @@ TEST_F(ProjectStorage, FetchFileStatus) ASSERT_THAT(fileStatus, Eq(fileStatus1)); } -TEST_F(ProjectStorage, SynchronizeTypesWithoutTypeName) +TEST_F(ProjectStorage, synchronize_types_without_type_name) { auto package{createSynchronizationPackageWithAliases()}; storage.synchronize(package); @@ -4463,7 +4463,7 @@ TEST_F(ProjectStorage, SynchronizeTypesWithoutTypeName) IsExportedType("Obj2")))))); } -TEST_F(ProjectStorage, FetchByMajorVersionForImportedType) +TEST_F(ProjectStorage, fetch_by_major_version_for_imported_type) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -4487,7 +4487,7 @@ TEST_F(ProjectStorage, FetchByMajorVersionForImportedType) sourceId2, "Item", fetchTypeId(sourceId1, "QObject"), TypeTraits::Reference))); } -TEST_F(ProjectStorage, FetchByMajorVersionForQualifiedImportedType) +TEST_F(ProjectStorage, fetch_by_major_version_for_qualified_imported_type) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -4511,7 +4511,7 @@ TEST_F(ProjectStorage, FetchByMajorVersionForQualifiedImportedType) sourceId2, "Item", fetchTypeId(sourceId1, "QObject"), TypeTraits::Reference))); } -TEST_F(ProjectStorage, FetchByMajorVersionAndMinorVersionForImportedType) +TEST_F(ProjectStorage, fetch_by_major_version_and_minor_version_for_imported_type) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -4535,7 +4535,7 @@ TEST_F(ProjectStorage, FetchByMajorVersionAndMinorVersionForImportedType) sourceId2, "Item", fetchTypeId(sourceId1, "QObject"), TypeTraits::Reference))); } -TEST_F(ProjectStorage, FetchByMajorVersionAndMinorVersionForQualifiedImportedType) +TEST_F(ProjectStorage, fetch_by_major_version_and_minor_version_for_qualified_imported_type) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -4560,7 +4560,7 @@ TEST_F(ProjectStorage, FetchByMajorVersionAndMinorVersionForQualifiedImportedTyp } TEST_F(ProjectStorage, - FetchByMajorVersionAndMinorVersionForImportedTypeIfMinorVersionIsNotExportedThrows) + fetch_by_major_version_and_minor_version_for_imported_type_if_minor_version_is_not_exported_throws) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -4582,7 +4582,7 @@ TEST_F(ProjectStorage, } TEST_F(ProjectStorage, - FetchByMajorVersionAndMinorVersionForQualifiedImportedTypeIfMinorVersionIsNotExportedThrows) + fetch_by_major_version_and_minor_version_for_qualified_imported_type_if_minor_version_is_not_exported_throws) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -4603,7 +4603,7 @@ TEST_F(ProjectStorage, QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, FetchLowMinorVersionForImportedTypeThrows) +TEST_F(ProjectStorage, fetch_low_minor_version_for_imported_type_throws) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -4624,7 +4624,7 @@ TEST_F(ProjectStorage, FetchLowMinorVersionForImportedTypeThrows) QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, FetchLowMinorVersionForQualifiedImportedTypeThrows) +TEST_F(ProjectStorage, fetch_low_minor_version_for_qualified_imported_type_throws) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -4645,7 +4645,7 @@ TEST_F(ProjectStorage, FetchLowMinorVersionForQualifiedImportedTypeThrows) QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, FetchHigherMinorVersionForImportedType) +TEST_F(ProjectStorage, fetch_higher_minor_version_for_imported_type) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -4669,7 +4669,7 @@ TEST_F(ProjectStorage, FetchHigherMinorVersionForImportedType) sourceId2, "Item", fetchTypeId(sourceId1, "QObject"), TypeTraits::Reference))); } -TEST_F(ProjectStorage, FetchHigherMinorVersionForQualifiedImportedType) +TEST_F(ProjectStorage, fetch_higher_minor_version_for_qualified_imported_type) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -4693,7 +4693,7 @@ TEST_F(ProjectStorage, FetchHigherMinorVersionForQualifiedImportedType) sourceId2, "Item", fetchTypeId(sourceId1, "QObject"), TypeTraits::Reference))); } -TEST_F(ProjectStorage, FetchDifferentMajorVersionForImportedTypeThrows) +TEST_F(ProjectStorage, fetch_different_major_version_for_imported_type_throws) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -4714,7 +4714,7 @@ TEST_F(ProjectStorage, FetchDifferentMajorVersionForImportedTypeThrows) QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, FetchDifferentMajorVersionForQualifiedImportedTypeThrows) +TEST_F(ProjectStorage, fetch_different_major_version_for_qualified_imported_type_throws) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -4735,7 +4735,7 @@ TEST_F(ProjectStorage, FetchDifferentMajorVersionForQualifiedImportedTypeThrows) QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, FetchOtherTypeByDifferentVersionForImportedType) +TEST_F(ProjectStorage, fetch_other_type_by_different_version_for_imported_type) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -4759,7 +4759,7 @@ TEST_F(ProjectStorage, FetchOtherTypeByDifferentVersionForImportedType) sourceId2, "Item", fetchTypeId(sourceId1, "QObject2"), TypeTraits::Reference))); } -TEST_F(ProjectStorage, FetchOtherTypeByDifferentVersionForQualifiedImportedType) +TEST_F(ProjectStorage, fetch_other_type_by_different_version_for_qualified_imported_type) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -4783,7 +4783,7 @@ TEST_F(ProjectStorage, FetchOtherTypeByDifferentVersionForQualifiedImportedType) sourceId2, "Item", fetchTypeId(sourceId1, "QObject2"), TypeTraits::Reference))); } -TEST_F(ProjectStorage, FetchHighestVersionForImportWithoutVersionForImportedType) +TEST_F(ProjectStorage, fetch_highest_version_for_import_without_version_for_imported_type) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -4805,7 +4805,7 @@ TEST_F(ProjectStorage, FetchHighestVersionForImportWithoutVersionForImportedType sourceId2, "Item", fetchTypeId(sourceId1, "QObject4"), TypeTraits::Reference))); } -TEST_F(ProjectStorage, FetchHighestVersionForImportWithoutVersionForQualifiedImportedType) +TEST_F(ProjectStorage, fetch_highest_version_for_import_without_version_for_qualified_imported_type) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -4827,7 +4827,7 @@ TEST_F(ProjectStorage, FetchHighestVersionForImportWithoutVersionForQualifiedImp sourceId2, "Item", fetchTypeId(sourceId1, "QObject4"), TypeTraits::Reference))); } -TEST_F(ProjectStorage, FetchHighestVersionForImportWithMajorVersionForImportedType) +TEST_F(ProjectStorage, fetch_highest_version_for_import_with_major_version_for_imported_type) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -4851,7 +4851,7 @@ TEST_F(ProjectStorage, FetchHighestVersionForImportWithMajorVersionForImportedTy sourceId2, "Item", fetchTypeId(sourceId1, "QObject3"), TypeTraits::Reference))); } -TEST_F(ProjectStorage, FetchHighestVersionForImportWithMajorVersionForQualifiedImportedType) +TEST_F(ProjectStorage, fetch_highest_version_for_import_with_major_version_for_qualified_imported_type) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -4875,7 +4875,7 @@ TEST_F(ProjectStorage, FetchHighestVersionForImportWithMajorVersionForQualifiedI sourceId2, "Item", fetchTypeId(sourceId1, "QObject3"), TypeTraits::Reference))); } -TEST_F(ProjectStorage, FetchExportedTypeWithoutVersionFirstForImportedType) +TEST_F(ProjectStorage, fetch_exported_type_without_version_first_for_imported_type) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -4897,7 +4897,7 @@ TEST_F(ProjectStorage, FetchExportedTypeWithoutVersionFirstForImportedType) sourceId2, "Item", fetchTypeId(sourceId1, "QObject"), TypeTraits::Reference))); } -TEST_F(ProjectStorage, FetchExportedTypeWithoutVersionFirstForQualifiedImportedType) +TEST_F(ProjectStorage, fetch_exported_type_without_version_first_for_qualified_imported_type) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -4919,7 +4919,7 @@ TEST_F(ProjectStorage, FetchExportedTypeWithoutVersionFirstForQualifiedImportedT sourceId2, "Item", fetchTypeId(sourceId1, "QObject"), TypeTraits::Reference))); } -TEST_F(ProjectStorage, EnsureThatPropertiesForRemovedTypesAreNotAnymoreRelinked) +TEST_F(ProjectStorage, ensure_that_properties_for_removed_types_are_not_anymore_relinked) { Storage::Synchronization::Type type{ "QObject", @@ -4940,7 +4940,7 @@ TEST_F(ProjectStorage, EnsureThatPropertiesForRemovedTypesAreNotAnymoreRelinked) ASSERT_NO_THROW(storage.synchronize(SynchronizationPackage{{sourceId1}})); } -TEST_F(ProjectStorage, EnsureThatPrototypesForRemovedTypesAreNotAnymoreRelinked) +TEST_F(ProjectStorage, ensure_that_prototypes_for_removed_types_are_not_anymore_relinked) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -4948,7 +4948,7 @@ TEST_F(ProjectStorage, EnsureThatPrototypesForRemovedTypesAreNotAnymoreRelinked) ASSERT_NO_THROW(storage.synchronize(SynchronizationPackage{{sourceId1, sourceId2}})); } -TEST_F(ProjectStorage, EnsureThatExtensionsForRemovedTypesAreNotAnymoreRelinked) +TEST_F(ProjectStorage, ensure_that_extensions_for_removed_types_are_not_anymore_relinked) { auto package{createSimpleSynchronizationPackage()}; std::swap(package.types.front().extension, package.types.front().prototype); @@ -4957,7 +4957,7 @@ TEST_F(ProjectStorage, EnsureThatExtensionsForRemovedTypesAreNotAnymoreRelinked) ASSERT_NO_THROW(storage.synchronize(SynchronizationPackage{{sourceId1, sourceId2}})); } -TEST_F(ProjectStorage, MinimalUpdates) +TEST_F(ProjectStorage, minimal_updates) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -5000,14 +5000,14 @@ TEST_F(ProjectStorage, MinimalUpdates) Field(&Storage::Synchronization::Type::enumerationDeclarations, Not(IsEmpty()))))); } -TEST_F(ProjectStorage, GetModuleId) +TEST_F(ProjectStorage, get_module_id) { auto id = storage.moduleId("Qml"); ASSERT_TRUE(id); } -TEST_F(ProjectStorage, GetSameModuleIdAgain) +TEST_F(ProjectStorage, get_same_module_id_again) { auto initialId = storage.moduleId("Qml"); @@ -5016,17 +5016,17 @@ TEST_F(ProjectStorage, GetSameModuleIdAgain) ASSERT_THAT(id, Eq(initialId)); } -TEST_F(ProjectStorage, ModuleNameThrowsIfIdIsInvalid) +TEST_F(ProjectStorage, module_name_throws_if_id_is_invalid) { ASSERT_THROW(storage.moduleName(ModuleId{}), QmlDesigner::ModuleDoesNotExists); } -TEST_F(ProjectStorage, ModuleNameThrowsIfIdDoesNotExists) +TEST_F(ProjectStorage, module_name_throws_if_id_does_not_exists) { ASSERT_THROW(storage.moduleName(ModuleId::create(222)), QmlDesigner::ModuleDoesNotExists); } -TEST_F(ProjectStorage, GetModuleName) +TEST_F(ProjectStorage, get_module_name) { auto id = storage.moduleId("Qml"); @@ -5035,7 +5035,7 @@ TEST_F(ProjectStorage, GetModuleName) ASSERT_THAT(name, Eq("Qml")); } -TEST_F(ProjectStorage, PopulateModuleCache) +TEST_F(ProjectStorage, populate_module_cache) { auto id = storage.moduleId("Qml"); @@ -5044,7 +5044,7 @@ TEST_F(ProjectStorage, PopulateModuleCache) ASSERT_THAT(newStorage.moduleName(id), Eq("Qml")); } -TEST_F(ProjectStorage, AddProjectDataes) +TEST_F(ProjectStorage, add_project_dataes) { Storage::Synchronization::ProjectData projectData1{qmlProjectSourceId, sourceId1, @@ -5066,7 +5066,7 @@ TEST_F(ProjectStorage, AddProjectDataes) UnorderedElementsAre(projectData1, projectData2, projectData3)); } -TEST_F(ProjectStorage, RemoveProjectData) +TEST_F(ProjectStorage, remove_project_data) { Storage::Synchronization::ProjectData projectData1{qmlProjectSourceId, sourceId1, @@ -5090,7 +5090,7 @@ TEST_F(ProjectStorage, RemoveProjectData) UnorderedElementsAre(projectData1)); } -TEST_F(ProjectStorage, UpdateProjectDataFileType) +TEST_F(ProjectStorage, update_project_data_file_type) { Storage::Synchronization::ProjectData projectData1{qmlProjectSourceId, sourceId1, @@ -5117,7 +5117,7 @@ TEST_F(ProjectStorage, UpdateProjectDataFileType) UnorderedElementsAre(projectData1, projectData2b, projectData3)); } -TEST_F(ProjectStorage, UpdateProjectDataModuleId) +TEST_F(ProjectStorage, update_project_data_module_id) { Storage::Synchronization::ProjectData projectData1{qmlProjectSourceId, sourceId1, @@ -5144,7 +5144,7 @@ TEST_F(ProjectStorage, UpdateProjectDataModuleId) UnorderedElementsAre(projectData1, projectData2b, projectData3)); } -TEST_F(ProjectStorage, ThrowForInvalidSourceIdInProjectData) +TEST_F(ProjectStorage, throw_for_invalid_source_id_in_project_data) { Storage::Synchronization::ProjectData projectData1{qmlProjectSourceId, SourceId{}, @@ -5155,7 +5155,7 @@ TEST_F(ProjectStorage, ThrowForInvalidSourceIdInProjectData) QmlDesigner::ProjectDataHasInvalidSourceId); } -TEST_F(ProjectStorage, ThrowForInvalidModuleIdInProjectData) +TEST_F(ProjectStorage, throw_for_invalid_module_id_in_project_data) { Storage::Synchronization::ProjectData projectData1{qmlProjectSourceId, sourceId1, @@ -5166,7 +5166,7 @@ TEST_F(ProjectStorage, ThrowForInvalidModuleIdInProjectData) QmlDesigner::ProjectDataHasInvalidModuleId); } -TEST_F(ProjectStorage, ThrowForUpdatingWithInvalidModuleIdInProjectData) +TEST_F(ProjectStorage, throw_for_updating_with_invalid_module_id_in_project_data) { Storage::Synchronization::ProjectData projectData1{qmlProjectSourceId, sourceId1, @@ -5179,7 +5179,7 @@ TEST_F(ProjectStorage, ThrowForUpdatingWithInvalidModuleIdInProjectData) QmlDesigner::ProjectDataHasInvalidModuleId); } -TEST_F(ProjectStorage, ThrowForUpdatingWithInvalidProjectSourceIdInProjectData) +TEST_F(ProjectStorage, throw_for_updating_with_invalid_project_source_id_in_project_data) { Storage::Synchronization::ProjectData projectData1{SourceId{}, sourceId1, @@ -5190,7 +5190,7 @@ TEST_F(ProjectStorage, ThrowForUpdatingWithInvalidProjectSourceIdInProjectData) QmlDesigner::ProjectDataHasInvalidProjectSourceId); } -TEST_F(ProjectStorage, FetchProjectDatasByDirectorySourceIds) +TEST_F(ProjectStorage, fetch_project_datas_by_directory_source_ids) { Storage::Synchronization::ProjectData projectData1{qmlProjectSourceId, sourceId1, @@ -5212,7 +5212,7 @@ TEST_F(ProjectStorage, FetchProjectDatasByDirectorySourceIds) ASSERT_THAT(projectDatas, UnorderedElementsAre(projectData1, projectData2, projectData3)); } -TEST_F(ProjectStorage, FetchProjectDatasByDirectorySourceId) +TEST_F(ProjectStorage, fetch_project_datas_by_directory_source_id) { Storage::Synchronization::ProjectData projectData1{qmlProjectSourceId, sourceId1, @@ -5234,7 +5234,7 @@ TEST_F(ProjectStorage, FetchProjectDatasByDirectorySourceId) ASSERT_THAT(projectData, UnorderedElementsAre(projectData1, projectData2)); } -TEST_F(ProjectStorage, FetchProjectDataBySourceIds) +TEST_F(ProjectStorage, fetch_project_data_by_source_ids) { Storage::Synchronization::ProjectData projectData1{qmlProjectSourceId, sourceId1, @@ -5256,7 +5256,7 @@ TEST_F(ProjectStorage, FetchProjectDataBySourceIds) ASSERT_THAT(projectData, Eq(projectData2)); } -TEST_F(ProjectStorage, ExcludeExportedTypes) +TEST_F(ProjectStorage, exclude_exported_types) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -5282,7 +5282,7 @@ TEST_F(ProjectStorage, ExcludeExportedTypes) "QQuickItem")))))); } -TEST_F(ProjectStorage, ModuleExportedImport) +TEST_F(ProjectStorage, module_exported_import) { auto package{createModuleExportedImportSynchronizationPackage()}; @@ -5313,7 +5313,7 @@ TEST_F(ProjectStorage, ModuleExportedImport) UnorderedElementsAre(IsExportedType(myModuleModuleId, "MyItem")))))); } -TEST_F(ProjectStorage, ModuleExportedImportWithDifferentVersions) +TEST_F(ProjectStorage, module_exported_import_with_different_versions) { auto package{createModuleExportedImportSynchronizationPackage()}; package.imports.back().version.major.value = 2; @@ -5348,7 +5348,7 @@ TEST_F(ProjectStorage, ModuleExportedImportWithDifferentVersions) UnorderedElementsAre(IsExportedType(myModuleModuleId, "MyItem")))))); } -TEST_F(ProjectStorage, ModuleExportedImportWithIndirectDifferentVersions) +TEST_F(ProjectStorage, module_exported_import_with_indirect_different_versions) { auto package{createModuleExportedImportSynchronizationPackage()}; package.imports[1].version.major.value = 2; @@ -5385,7 +5385,7 @@ TEST_F(ProjectStorage, ModuleExportedImportWithIndirectDifferentVersions) UnorderedElementsAre(IsExportedType(myModuleModuleId, "MyItem")))))); } -TEST_F(ProjectStorage, ModuleExportedImportPreventCollisionIfModuleIsIndirectlyReexportedMultipleTimes) +TEST_F(ProjectStorage, module_exported_import_prevent_collision_if_module_is_indirectly_reexported_multiple_times) { ModuleId qtQuick4DModuleId{storage.moduleId("QtQuick4D")}; auto package{createModuleExportedImportSynchronizationPackage()}; @@ -5443,7 +5443,7 @@ TEST_F(ProjectStorage, ModuleExportedImportPreventCollisionIfModuleIsIndirectlyR UnorderedElementsAre(IsExportedType(myModuleModuleId, "MyItem")))))); } -TEST_F(ProjectStorage, DistinguishBetweenImportKinds) +TEST_F(ProjectStorage, distinguish_between_import_kinds) { ModuleId qml1ModuleId{storage.moduleId("Qml1")}; ModuleId qml11ModuleId{storage.moduleId("Qml11")}; @@ -5477,7 +5477,7 @@ TEST_F(ProjectStorage, DistinguishBetweenImportKinds) "QQuickItem")))))); } -TEST_F(ProjectStorage, ModuleExportedImportDistinguishBetweenDependencyAndImportReExports) +TEST_F(ProjectStorage, module_exported_import_distinguish_between_dependency_and_import_re_exports) { auto package{createModuleExportedImportSynchronizationPackage()}; package.moduleDependencies.emplace_back(qtQuick3DModuleId, @@ -5511,7 +5511,7 @@ TEST_F(ProjectStorage, ModuleExportedImportDistinguishBetweenDependencyAndImport UnorderedElementsAre(IsExportedType(myModuleModuleId, "MyItem")))))); } -TEST_F(ProjectStorage, ModuleExportedImportWithQualifiedImportedType) +TEST_F(ProjectStorage, module_exported_import_with_qualified_imported_type) { auto package{createModuleExportedImportSynchronizationPackage()}; package.types.back().prototype = Storage::Synchronization::QualifiedImportedType{ @@ -5547,7 +5547,7 @@ TEST_F(ProjectStorage, ModuleExportedImportWithQualifiedImportedType) UnorderedElementsAre(IsExportedType(myModuleModuleId, "MyItem")))))); } -TEST_F(ProjectStorage, SynchronizeTypesAddIndirectAliasDeclarations) +TEST_F(ProjectStorage, synchronize_types_add_indirect_alias_declarations) { auto package{createSynchronizationPackageWithIndirectAliases()}; @@ -5568,7 +5568,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddIndirectAliasDeclarations) | Storage::PropertyDeclarationTraits::IsReadOnly)))))); } -TEST_F(ProjectStorage, SynchronizeTypesAddIndirectAliasDeclarationsAgain) +TEST_F(ProjectStorage, synchronize_types_add_indirect_alias_declarations_again) { auto package{createSynchronizationPackageWithIndirectAliases()}; storage.synchronize(package); @@ -5590,7 +5590,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddIndirectAliasDeclarationsAgain) | Storage::PropertyDeclarationTraits::IsReadOnly)))))); } -TEST_F(ProjectStorage, SynchronizeTypesRemoveIndirectAliasDeclaration) +TEST_F(ProjectStorage, synchronize_types_remove_indirect_alias_declaration) { auto package{createSynchronizationPackageWithIndirectAliases()}; storage.synchronize(package); @@ -5610,7 +5610,7 @@ TEST_F(ProjectStorage, SynchronizeTypesRemoveIndirectAliasDeclaration) Storage::PropertyDeclarationTraits::IsList)))))); } -TEST_F(ProjectStorage, SynchronizeTypesAddIndirectAliasDeclarationsThrowsForWrongTypeName) +TEST_F(ProjectStorage, synchronize_types_add_indirect_alias_declarations_throws_for_wrong_type_name) { auto package{createSynchronizationPackageWithIndirectAliases()}; storage.synchronize(package); @@ -5625,7 +5625,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddIndirectAliasDeclarationsThrowsForWron QmlDesigner::TypeNameDoesNotExists); } -TEST_F(ProjectStorage, SynchronizeTypesAddIndirectAliasDeclarationsThrowsForWrongPropertyName) +TEST_F(ProjectStorage, synchronize_types_add_indirect_alias_declarations_throws_for_wrong_property_name) { auto package{createSynchronizationPackageWithIndirectAliases()}; storage.synchronize(package); @@ -5639,7 +5639,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddIndirectAliasDeclarationsThrowsForWron QmlDesigner::PropertyNameDoesNotExists); } -TEST_F(ProjectStorage, SynchronizeTypesAddIndirectAliasDeclarationsThrowsForWrongPropertyNameTail) +TEST_F(ProjectStorage, synchronize_types_add_indirect_alias_declarations_throws_for_wrong_property_name_tail) { auto package{createSynchronizationPackageWithIndirectAliases()}; storage.synchronize(package); @@ -5653,7 +5653,7 @@ TEST_F(ProjectStorage, SynchronizeTypesAddIndirectAliasDeclarationsThrowsForWron QmlDesigner::PropertyNameDoesNotExists); } -TEST_F(ProjectStorage, SynchronizeTypesChangeIndirectAliasDeclarationTypeName) +TEST_F(ProjectStorage, synchronize_types_change_indirect_alias_declaration_type_name) { auto package{createSynchronizationPackageWithIndirectAliases()}; storage.synchronize(package); @@ -5679,7 +5679,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangeIndirectAliasDeclarationTypeName) | Storage::PropertyDeclarationTraits::IsReadOnly)))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangeIndirectAliasDeclarationTailsTypeName) +TEST_F(ProjectStorage, synchronize_types_change_indirect_alias_declaration_tails_type_name) { auto package{createSynchronizationPackageWithIndirectAliases()}; storage.synchronize(package); @@ -5705,7 +5705,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangeIndirectAliasDeclarationTailsTypeNa | Storage::PropertyDeclarationTraits::IsReadOnly)))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangeIndirectAliasDeclarationsPropertyName) +TEST_F(ProjectStorage, synchronize_types_change_indirect_alias_declarations_property_name) { auto package{createSynchronizationPackageWithIndirectAliases()}; storage.synchronize(package); @@ -5729,7 +5729,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangeIndirectAliasDeclarationsPropertyNa | Storage::PropertyDeclarationTraits::IsReadOnly)))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangeIndirectAliasDeclarationsPropertyNameTail) +TEST_F(ProjectStorage, synchronize_types_change_indirect_alias_declarations_property_name_tail) { auto package{createSynchronizationPackageWithIndirectAliases()}; storage.synchronize(package); @@ -5754,7 +5754,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangeIndirectAliasDeclarationsPropertyNa Storage::PropertyDeclarationTraits::IsList)))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangeIndirectAliasDeclarationsToPropertyDeclaration) +TEST_F(ProjectStorage, synchronize_types_change_indirect_alias_declarations_to_property_declaration) { auto package{createSynchronizationPackageWithIndirectAliases()}; storage.synchronize(package); @@ -5782,7 +5782,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangeIndirectAliasDeclarationsToProperty | Storage::PropertyDeclarationTraits::IsReadOnly)))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangePropertyDeclarationsToIndirectAliasDeclaration) +TEST_F(ProjectStorage, synchronize_types_change_property_declarations_to_indirect_alias_declaration) { auto package{createSynchronizationPackageWithIndirectAliases()}; storage.synchronize(package); @@ -5816,7 +5816,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangePropertyDeclarationsToIndirectAlias | Storage::PropertyDeclarationTraits::IsReadOnly)))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangeIndirectAliasTargetPropertyDeclarationTraits) +TEST_F(ProjectStorage, synchronize_types_change_indirect_alias_target_property_declaration_traits) { auto package{createSynchronizationPackageWithIndirectAliases()}; storage.synchronize(package); @@ -5842,7 +5842,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangeIndirectAliasTargetPropertyDeclarat | Storage::PropertyDeclarationTraits::IsReadOnly)))))); } -TEST_F(ProjectStorage, SynchronizeTypesChangeIndirectAliasTargetPropertyDeclarationTypeName) +TEST_F(ProjectStorage, synchronize_types_change_indirect_alias_target_property_declaration_type_name) { auto package{createSynchronizationPackageWithIndirectAliases()}; storage.synchronize(package); @@ -5867,7 +5867,7 @@ TEST_F(ProjectStorage, SynchronizeTypesChangeIndirectAliasTargetPropertyDeclarat | Storage::PropertyDeclarationTraits::IsReadOnly)))))); } -TEST_F(ProjectStorage, SynchronizeTypesRemovePropertyDeclarationWithAnIndirectAliasThrows) +TEST_F(ProjectStorage, synchronize_types_remove_property_declaration_with_an_indirect_alias_throws) { auto package{createSynchronizationPackageWithIndirectAliases()}; storage.synchronize(package); @@ -5881,7 +5881,7 @@ TEST_F(ProjectStorage, SynchronizeTypesRemovePropertyDeclarationWithAnIndirectAl Sqlite::ConstraintPreventsModification); } -TEST_F(ProjectStorage, DISABLED_SynchronizeTypesRemoveStemPropertyDeclarationWithAnIndirectAliasThrows) +TEST_F(ProjectStorage, DISABLED_synchronize_types_remove_stem_property_declaration_with_an_indirect_alias_throws) { auto package{createSynchronizationPackageWithIndirectAliases()}; storage.synchronize(package); @@ -5895,7 +5895,7 @@ TEST_F(ProjectStorage, DISABLED_SynchronizeTypesRemoveStemPropertyDeclarationWit Sqlite::ConstraintPreventsModification); } -TEST_F(ProjectStorage, SynchronizeTypesRemovePropertyDeclarationAndIndirectAlias) +TEST_F(ProjectStorage, synchronize_types_remove_property_declaration_and_indirect_alias) { auto package{createSynchronizationPackageWithIndirectAliases()}; storage.synchronize(package); @@ -5920,7 +5920,7 @@ TEST_F(ProjectStorage, SynchronizeTypesRemovePropertyDeclarationAndIndirectAlias Storage::PropertyDeclarationTraits::IsList)))))); } -TEST_F(ProjectStorage, SynchronizeTypesRemovePropertyDeclarationAndIndirectAliasSteam) +TEST_F(ProjectStorage, synchronize_types_remove_property_declaration_and_indirect_alias_steam) { auto package{createSynchronizationPackageWithIndirectAliases()}; storage.synchronize(package); @@ -5942,7 +5942,7 @@ TEST_F(ProjectStorage, SynchronizeTypesRemovePropertyDeclarationAndIndirectAlias Field(&Storage::Synchronization::Type::propertyDeclarations, IsEmpty())))); } -TEST_F(ProjectStorage, GetTypeId) +TEST_F(ProjectStorage, get_type_id) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -5952,7 +5952,7 @@ TEST_F(ProjectStorage, GetTypeId) ASSERT_THAT(typeId, fetchTypeId(sourceId1, "QObject4")); } -TEST_F(ProjectStorage, GetNoTypeIdForNonExistingTypeName) +TEST_F(ProjectStorage, get_no_type_id_for_non_existing_type_name) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -5962,7 +5962,7 @@ TEST_F(ProjectStorage, GetNoTypeIdForNonExistingTypeName) ASSERT_FALSE(typeId); } -TEST_F(ProjectStorage, GetNoTypeIdForInvalidModuleId) +TEST_F(ProjectStorage, get_no_type_id_for_invalid_module_id) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -5972,7 +5972,7 @@ TEST_F(ProjectStorage, GetNoTypeIdForInvalidModuleId) ASSERT_FALSE(typeId); } -TEST_F(ProjectStorage, GetNoTypeIdForWrongModuleId) +TEST_F(ProjectStorage, get_no_type_id_for_wrong_module_id) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -5982,7 +5982,7 @@ TEST_F(ProjectStorage, GetNoTypeIdForWrongModuleId) ASSERT_FALSE(typeId); } -TEST_F(ProjectStorage, GetTypeIdWithMajorVersion) +TEST_F(ProjectStorage, get_type_id_with_major_version) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -5992,7 +5992,7 @@ TEST_F(ProjectStorage, GetTypeIdWithMajorVersion) ASSERT_THAT(typeId, fetchTypeId(sourceId1, "QObject3")); } -TEST_F(ProjectStorage, GetNoTypeIdWithMajorVersionForNonExistingTypeName) +TEST_F(ProjectStorage, get_no_type_id_with_major_version_for_non_existing_type_name) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -6002,7 +6002,7 @@ TEST_F(ProjectStorage, GetNoTypeIdWithMajorVersionForNonExistingTypeName) ASSERT_FALSE(typeId); } -TEST_F(ProjectStorage, GetNoTypeIdWithMajorVersionForInvalidModuleId) +TEST_F(ProjectStorage, get_no_type_id_with_major_version_for_invalid_module_id) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -6012,7 +6012,7 @@ TEST_F(ProjectStorage, GetNoTypeIdWithMajorVersionForInvalidModuleId) ASSERT_FALSE(typeId); } -TEST_F(ProjectStorage, GetNoTypeIdWithMajorVersionForWrongModuleId) +TEST_F(ProjectStorage, get_no_type_id_with_major_version_for_wrong_module_id) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -6022,7 +6022,7 @@ TEST_F(ProjectStorage, GetNoTypeIdWithMajorVersionForWrongModuleId) ASSERT_FALSE(typeId); } -TEST_F(ProjectStorage, GetNoTypeIdWithMajorVersionForWrongVersion) +TEST_F(ProjectStorage, get_no_type_id_with_major_version_for_wrong_version) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -6032,7 +6032,7 @@ TEST_F(ProjectStorage, GetNoTypeIdWithMajorVersionForWrongVersion) ASSERT_FALSE(typeId); } -TEST_F(ProjectStorage, GetTypeIdWithCompleteVersion) +TEST_F(ProjectStorage, get_type_id_with_complete_version) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -6042,7 +6042,7 @@ TEST_F(ProjectStorage, GetTypeIdWithCompleteVersion) ASSERT_THAT(typeId, fetchTypeId(sourceId1, "QObject2")); } -TEST_F(ProjectStorage, GetNoTypeIdWithCompleteVersionWithHigherMinorVersion) +TEST_F(ProjectStorage, get_no_type_id_with_complete_version_with_higher_minor_version) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -6052,7 +6052,7 @@ TEST_F(ProjectStorage, GetNoTypeIdWithCompleteVersionWithHigherMinorVersion) ASSERT_THAT(typeId, fetchTypeId(sourceId1, "QObject3")); } -TEST_F(ProjectStorage, GetNoTypeIdWithCompleteVersionForNonExistingTypeName) +TEST_F(ProjectStorage, get_no_type_id_with_complete_version_for_non_existing_type_name) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -6062,7 +6062,7 @@ TEST_F(ProjectStorage, GetNoTypeIdWithCompleteVersionForNonExistingTypeName) ASSERT_FALSE(typeId); } -TEST_F(ProjectStorage, GetNoTypeIdWithCompleteVersionForInvalidModuleId) +TEST_F(ProjectStorage, get_no_type_id_with_complete_version_for_invalid_module_id) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -6072,7 +6072,7 @@ TEST_F(ProjectStorage, GetNoTypeIdWithCompleteVersionForInvalidModuleId) ASSERT_FALSE(typeId); } -TEST_F(ProjectStorage, GetNoTypeIdWithCompleteVersionForWrongModuleId) +TEST_F(ProjectStorage, get_no_type_id_with_complete_version_for_wrong_module_id) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -6082,7 +6082,7 @@ TEST_F(ProjectStorage, GetNoTypeIdWithCompleteVersionForWrongModuleId) ASSERT_FALSE(typeId); } -TEST_F(ProjectStorage, GetNoTypeIdWithCompleteVersionForWrongMajorVersion) +TEST_F(ProjectStorage, get_no_type_id_with_complete_version_for_wrong_major_version) { auto package{createSynchronizationPackageWithVersions()}; storage.synchronize(package); @@ -6092,7 +6092,7 @@ TEST_F(ProjectStorage, GetNoTypeIdWithCompleteVersionForWrongMajorVersion) ASSERT_FALSE(typeId); } -TEST_F(ProjectStorage, GetPropertyDeclarationIdsOverPrototypeChain) +TEST_F(ProjectStorage, get_property_declaration_ids_over_prototype_chain) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6109,7 +6109,7 @@ TEST_F(ProjectStorage, GetPropertyDeclarationIdsOverPrototypeChain) HasName("children3"))); } -TEST_F(ProjectStorage, GetPropertyDeclarationIdsOverExtensionChain) +TEST_F(ProjectStorage, get_property_declaration_ids_over_extension_chain) { auto package{createPackageWithProperties()}; std::swap(package.types[1].extension, package.types[1].prototype); @@ -6127,7 +6127,7 @@ TEST_F(ProjectStorage, GetPropertyDeclarationIdsOverExtensionChain) HasName("children3"))); } -TEST_F(ProjectStorage, GetPropertyDeclarationIdsAreReturnedSorted) +TEST_F(ProjectStorage, get_property_declaration_ids_are_returned_sorted) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6138,7 +6138,7 @@ TEST_F(ProjectStorage, GetPropertyDeclarationIdsAreReturnedSorted) ASSERT_THAT(propertyIds, IsSorted()); } -TEST_F(ProjectStorage, GetNoPropertyDeclarationIdsPropertiesFromDerivedTypes) +TEST_F(ProjectStorage, get_no_property_declaration_ids_properties_from_derived_types) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6153,7 +6153,7 @@ TEST_F(ProjectStorage, GetNoPropertyDeclarationIdsPropertiesFromDerivedTypes) HasName("children2"))); } -TEST_F(ProjectStorage, GetNoPropertyDeclarationIdsForWrongTypeId) +TEST_F(ProjectStorage, get_no_property_declaration_ids_for_wrong_type_id) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6164,7 +6164,7 @@ TEST_F(ProjectStorage, GetNoPropertyDeclarationIdsForWrongTypeId) ASSERT_THAT(propertyIds, IsEmpty()); } -TEST_F(ProjectStorage, GetLocalPropertyDeclarationIds) +TEST_F(ProjectStorage, get_local_property_declaration_ids) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6175,7 +6175,7 @@ TEST_F(ProjectStorage, GetLocalPropertyDeclarationIds) ASSERT_THAT(propertyIds, UnorderedElementsAre(HasName("data2"), HasName("children2"))); } -TEST_F(ProjectStorage, GetLocalPropertyDeclarationIdsAreReturnedSorted) +TEST_F(ProjectStorage, get_local_property_declaration_ids_are_returned_sorted) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6186,7 +6186,7 @@ TEST_F(ProjectStorage, GetLocalPropertyDeclarationIdsAreReturnedSorted) ASSERT_THAT(propertyIds, IsSorted()); } -TEST_F(ProjectStorage, GetPropertyDeclarationIdOverPrototypeChain) +TEST_F(ProjectStorage, get_property_declaration_id_over_prototype_chain) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6197,7 +6197,7 @@ TEST_F(ProjectStorage, GetPropertyDeclarationIdOverPrototypeChain) ASSERT_THAT(propertyId, HasName("data")); } -TEST_F(ProjectStorage, GetPropertyDeclarationIdOverExtensionChain) +TEST_F(ProjectStorage, get_property_declaration_id_over_extension_chain) { auto package{createPackageWithProperties()}; std::swap(package.types[1].extension, package.types[1].prototype); @@ -6209,7 +6209,7 @@ TEST_F(ProjectStorage, GetPropertyDeclarationIdOverExtensionChain) ASSERT_THAT(propertyId, HasName("data")); } -TEST_F(ProjectStorage, GetLatestPropertyDeclarationId) +TEST_F(ProjectStorage, get_latest_property_declaration_id) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6229,7 +6229,7 @@ TEST_F(ProjectStorage, GetLatestPropertyDeclarationId) ASSERT_THAT(oldPropertyId, HasName("data")); } -TEST_F(ProjectStorage, GetInvalidPropertyDeclarationIdForInvalidTypeId) +TEST_F(ProjectStorage, get_invalid_property_declaration_id_for_invalid_type_id) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6240,7 +6240,7 @@ TEST_F(ProjectStorage, GetInvalidPropertyDeclarationIdForInvalidTypeId) ASSERT_FALSE(propertyId); } -TEST_F(ProjectStorage, GetInvalidPropertyDeclarationIdForWrongPropertyName) +TEST_F(ProjectStorage, get_invalid_property_declaration_id_for_wrong_property_name) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6251,7 +6251,7 @@ TEST_F(ProjectStorage, GetInvalidPropertyDeclarationIdForWrongPropertyName) ASSERT_FALSE(propertyId); } -TEST_F(ProjectStorage, GetLocalPropertyDeclarationId) +TEST_F(ProjectStorage, get_local_property_declaration_id) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6262,7 +6262,7 @@ TEST_F(ProjectStorage, GetLocalPropertyDeclarationId) ASSERT_THAT(propertyId, HasName("data")); } -TEST_F(ProjectStorage, GetInvalidLocalPropertyDeclarationIdForWrongType) +TEST_F(ProjectStorage, get_invalid_local_property_declaration_id_for_wrong_type) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6273,7 +6273,7 @@ TEST_F(ProjectStorage, GetInvalidLocalPropertyDeclarationIdForWrongType) ASSERT_FALSE(propertyId); } -TEST_F(ProjectStorage, GetInvalidLocalPropertyDeclarationIdForInvalidTypeId) +TEST_F(ProjectStorage, get_invalid_local_property_declaration_id_for_invalid_type_id) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6284,7 +6284,7 @@ TEST_F(ProjectStorage, GetInvalidLocalPropertyDeclarationIdForInvalidTypeId) ASSERT_FALSE(propertyId); } -TEST_F(ProjectStorage, GetInvalidLocalPropertyDeclarationIdForWrongPropertyName) +TEST_F(ProjectStorage, get_invalid_local_property_declaration_id_for_wrong_property_name) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6295,7 +6295,7 @@ TEST_F(ProjectStorage, GetInvalidLocalPropertyDeclarationIdForWrongPropertyName) ASSERT_FALSE(propertyId); } -TEST_F(ProjectStorage, GetPropertyDeclaration) +TEST_F(ProjectStorage, get_property_declaration) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6310,7 +6310,7 @@ TEST_F(ProjectStorage, GetPropertyDeclaration) typeId2, "data2", Storage::PropertyDeclarationTraits::IsReadOnly, typeId3))); } -TEST_F(ProjectStorage, GetInvalidOptionalPropertyDeclarationForInvalidPropertyDeclarationId) +TEST_F(ProjectStorage, get_invalid_optional_property_declaration_for_invalid_property_declaration_id) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6320,7 +6320,7 @@ TEST_F(ProjectStorage, GetInvalidOptionalPropertyDeclarationForInvalidPropertyDe ASSERT_THAT(property, Eq(std::nullopt)); } -TEST_F(ProjectStorage, GetSignalDeclarationNames) +TEST_F(ProjectStorage, get_signal_declaration_names) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6331,7 +6331,7 @@ TEST_F(ProjectStorage, GetSignalDeclarationNames) ASSERT_THAT(signalNames, ElementsAre("itemsChanged", "objectsChanged", "valuesChanged")); } -TEST_F(ProjectStorage, GetSignalDeclarationNamesAreOrdered) +TEST_F(ProjectStorage, get_signal_declaration_names_are_ordered) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6342,7 +6342,7 @@ TEST_F(ProjectStorage, GetSignalDeclarationNamesAreOrdered) ASSERT_THAT(signalNames, StringsAreSorted()); } -TEST_F(ProjectStorage, GetNoSignalDeclarationNamesForInvalidTypeId) +TEST_F(ProjectStorage, get_no_signal_declaration_names_for_invalid_type_id) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6353,7 +6353,7 @@ TEST_F(ProjectStorage, GetNoSignalDeclarationNamesForInvalidTypeId) ASSERT_THAT(signalNames, IsEmpty()); } -TEST_F(ProjectStorage, GetOnlySignalDeclarationNamesFromUpIntoThePrototypeChain) +TEST_F(ProjectStorage, get_only_signal_declaration_names_from_up_into_the_prototype_chain) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6364,7 +6364,7 @@ TEST_F(ProjectStorage, GetOnlySignalDeclarationNamesFromUpIntoThePrototypeChain) ASSERT_THAT(signalNames, ElementsAre("itemsChanged", "valuesChanged")); } -TEST_F(ProjectStorage, GetOnlySignalDeclarationNamesFromUpIntoTheExtensionChain) +TEST_F(ProjectStorage, get_only_signal_declaration_names_from_up_into_the_extension_chain) { auto package{createPackageWithProperties()}; std::swap(package.types[1].extension, package.types[1].prototype); @@ -6376,7 +6376,7 @@ TEST_F(ProjectStorage, GetOnlySignalDeclarationNamesFromUpIntoTheExtensionChain) ASSERT_THAT(signalNames, ElementsAre("itemsChanged", "valuesChanged")); } -TEST_F(ProjectStorage, GetFunctionDeclarationNames) +TEST_F(ProjectStorage, get_function_declaration_names) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6387,7 +6387,7 @@ TEST_F(ProjectStorage, GetFunctionDeclarationNames) ASSERT_THAT(functionNames, ElementsAre("items", "objects", "values")); } -TEST_F(ProjectStorage, GetFunctionDeclarationNamesAreOrdered) +TEST_F(ProjectStorage, get_function_declaration_names_are_ordered) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6398,7 +6398,7 @@ TEST_F(ProjectStorage, GetFunctionDeclarationNamesAreOrdered) ASSERT_THAT(functionNames, StringsAreSorted()); } -TEST_F(ProjectStorage, GetNoFunctionDeclarationNamesForInvalidTypeId) +TEST_F(ProjectStorage, get_no_function_declaration_names_for_invalid_type_id) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6409,7 +6409,7 @@ TEST_F(ProjectStorage, GetNoFunctionDeclarationNamesForInvalidTypeId) ASSERT_THAT(functionNames, IsEmpty()); } -TEST_F(ProjectStorage, GetOnlyFunctionDeclarationNamesFromUpIntoThePrototypeChain) +TEST_F(ProjectStorage, get_only_function_declaration_names_from_up_into_the_prototype_chain) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6420,7 +6420,7 @@ TEST_F(ProjectStorage, GetOnlyFunctionDeclarationNamesFromUpIntoThePrototypeChai ASSERT_THAT(functionNames, ElementsAre("items", "values")); } -TEST_F(ProjectStorage, GetOnlyFunctionDeclarationNamesFromUpIntoTheExtensionChain) +TEST_F(ProjectStorage, get_only_function_declaration_names_from_up_into_the_extension_chain) { auto package{createPackageWithProperties()}; std::swap(package.types[1].extension, package.types[1].prototype); @@ -6432,7 +6432,7 @@ TEST_F(ProjectStorage, GetOnlyFunctionDeclarationNamesFromUpIntoTheExtensionChai ASSERT_THAT(functionNames, ElementsAre("items", "values")); } -TEST_F(ProjectStorage, SynchronizeDefaultProperty) +TEST_F(ProjectStorage, synchronize_default_property) { auto package{createSimpleSynchronizationPackage()}; package.types.front().defaultPropertyName = "children"; @@ -6445,7 +6445,7 @@ TEST_F(ProjectStorage, SynchronizeDefaultProperty) Eq("children"))))); } -TEST_F(ProjectStorage, SynchronizeDefaultPropertyToADifferentName) +TEST_F(ProjectStorage, synchronize_default_property_to_a_different_name) { auto package{createSimpleSynchronizationPackage()}; package.types.front().defaultPropertyName = "children"; @@ -6460,7 +6460,7 @@ TEST_F(ProjectStorage, SynchronizeDefaultPropertyToADifferentName) Field(&Storage::Synchronization::Type::defaultPropertyName, Eq("data"))))); } -TEST_F(ProjectStorage, SynchronizeToRemovedDefaultProperty) +TEST_F(ProjectStorage, synchronize_to_removed_default_property) { auto package{createSimpleSynchronizationPackage()}; package.types.front().defaultPropertyName = "children"; @@ -6475,7 +6475,7 @@ TEST_F(ProjectStorage, SynchronizeToRemovedDefaultProperty) Field(&Storage::Synchronization::Type::defaultPropertyName, IsEmpty())))); } -TEST_F(ProjectStorage, SynchronizeDefaultPropertyThrowsForMissingDefaultProperty) +TEST_F(ProjectStorage, synchronize_default_property_throws_for_missing_default_property) { auto package{createSimpleSynchronizationPackage()}; package.types.front().defaultPropertyName = "child"; @@ -6484,7 +6484,7 @@ TEST_F(ProjectStorage, SynchronizeDefaultPropertyThrowsForMissingDefaultProperty } TEST_F(ProjectStorage, - SynchronizeDefaultPropertyThrowsForRemovingPropertyWithoutChangingDefaultProperty) + synchronize_default_property_throws_for_removing_property_without_changing_default_property) { auto package{createSimpleSynchronizationPackage()}; package.types.front().defaultPropertyName = "children"; @@ -6494,7 +6494,7 @@ TEST_F(ProjectStorage, ASSERT_THROW(storage.synchronize(package), QmlDesigner::PropertyNameDoesNotExists); } -TEST_F(ProjectStorage, SynchronizeChangesDefaultPropertyAndRemovesOldDefaultProperty) +TEST_F(ProjectStorage, synchronize_changes_default_property_and_removes_old_default_property) { auto package{createSimpleSynchronizationPackage()}; auto &type = findType(package, "QQuickItem"); @@ -6511,7 +6511,7 @@ TEST_F(ProjectStorage, SynchronizeChangesDefaultPropertyAndRemovesOldDefaultProp Field(&Storage::Synchronization::Type::defaultPropertyName, Eq("data"))))); } -TEST_F(ProjectStorage, SynchronizeAddNewDefaultPropertyAndRemovesOldDefaultProperty) +TEST_F(ProjectStorage, synchronize_add_new_default_property_and_removes_old_default_property) { auto package{createSimpleSynchronizationPackage()}; auto &type = findType(package, "QQuickItem"); @@ -6533,7 +6533,7 @@ TEST_F(ProjectStorage, SynchronizeAddNewDefaultPropertyAndRemovesOldDefaultPrope Field(&Storage::Synchronization::Type::defaultPropertyName, Eq("data2"))))); } -TEST_F(ProjectStorage, SynchronizeDefaultPropertyToThePrototypeProperty) +TEST_F(ProjectStorage, synchronize_default_property_to_the_prototype_property) { auto package{createSimpleSynchronizationPackage()}; package.types.front().defaultPropertyName = "children"; @@ -6550,7 +6550,7 @@ TEST_F(ProjectStorage, SynchronizeDefaultPropertyToThePrototypeProperty) Eq("children"))))); } -TEST_F(ProjectStorage, SynchronizeDefaultPropertyToTheExtensionProperty) +TEST_F(ProjectStorage, synchronize_default_property_to_the_extension_property) { auto package{createSimpleSynchronizationPackage()}; std::swap(package.types.front().extension, package.types.front().prototype); @@ -6568,7 +6568,7 @@ TEST_F(ProjectStorage, SynchronizeDefaultPropertyToTheExtensionProperty) Eq("children"))))); } -TEST_F(ProjectStorage, SynchronizeMoveTheDefaultPropertyToThePrototypeProperty) +TEST_F(ProjectStorage, synchronize_move_the_default_property_to_the_prototype_property) { auto package{createSimpleSynchronizationPackage()}; package.types.front().defaultPropertyName = "children"; @@ -6586,7 +6586,7 @@ TEST_F(ProjectStorage, SynchronizeMoveTheDefaultPropertyToThePrototypeProperty) Eq("children"))))); } -TEST_F(ProjectStorage, SynchronizeMoveTheDefaultPropertyToTheExtensionProperty) +TEST_F(ProjectStorage, synchronize_move_the_default_property_to_the_extension_property) { auto package{createSimpleSynchronizationPackage()}; std::swap(package.types.front().extension, package.types.front().prototype); @@ -6605,7 +6605,7 @@ TEST_F(ProjectStorage, SynchronizeMoveTheDefaultPropertyToTheExtensionProperty) Eq("children"))))); } -TEST_F(ProjectStorage, GetType) +TEST_F(ProjectStorage, get_type) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -6618,7 +6618,7 @@ TEST_F(ProjectStorage, GetType) ASSERT_THAT(type, Optional(IsInfoType(defaultPropertyId, TypeTraits::Reference))); } -TEST_F(ProjectStorage, DontGetTypeForInvalidId) +TEST_F(ProjectStorage, dont_get_type_for_invalid_id) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -6628,7 +6628,7 @@ TEST_F(ProjectStorage, DontGetTypeForInvalidId) ASSERT_THAT(type, Eq(std::nullopt)); } -TEST_F(ProjectStorage, GetCommonType) +TEST_F(ProjectStorage, get_common_type) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -6639,7 +6639,7 @@ TEST_F(ProjectStorage, GetCommonType) ASSERT_THAT(typeId, fetchTypeId(sourceId1, "QQuickItem")); } -TEST_F(ProjectStorage, GetCommonTypeAgain) +TEST_F(ProjectStorage, get_common_type_again) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -6652,7 +6652,7 @@ TEST_F(ProjectStorage, GetCommonTypeAgain) ASSERT_THAT(typeId, firstTypeId); } -TEST_F(ProjectStorage, GetCommonTypeAfterChangingType) +TEST_F(ProjectStorage, get_common_type_after_changing_type) { auto package{createSimpleSynchronizationPackage()}; storage.synchronize(package); @@ -6668,7 +6668,7 @@ TEST_F(ProjectStorage, GetCommonTypeAfterChangingType) ASSERT_THAT(typeId, fetchTypeId(sourceId1, "QQuickItem2")); } -TEST_F(ProjectStorage, GetBuiltinType) +TEST_F(ProjectStorage, get_builtin_type) { auto package{createBuiltinSynchronizationPackage()}; storage.synchronize(package); @@ -6678,7 +6678,7 @@ TEST_F(ProjectStorage, GetBuiltinType) ASSERT_THAT(typeId, fetchTypeId(sourceId1, "double")); } -TEST_F(ProjectStorage, GetBuiltinTypeAgain) +TEST_F(ProjectStorage, get_builtin_type_again) { auto package{createBuiltinSynchronizationPackage()}; storage.synchronize(package); @@ -6689,7 +6689,7 @@ TEST_F(ProjectStorage, GetBuiltinTypeAgain) ASSERT_THAT(typeId, firstTypeId); } -TEST_F(ProjectStorage, GetBuiltinTypeAfterChangingType) +TEST_F(ProjectStorage, get_builtin_type_after_changing_type) { auto package{createBuiltinSynchronizationPackage()}; storage.synchronize(package); @@ -6703,7 +6703,7 @@ TEST_F(ProjectStorage, GetBuiltinTypeAfterChangingType) ASSERT_THAT(typeId, fetchTypeId(sourceId1, "float")); } -TEST_F(ProjectStorage, GetBuiltinStringType) +TEST_F(ProjectStorage, get_builtin_string_type) { auto package{createBuiltinSynchronizationPackage()}; storage.synchronize(package); @@ -6713,7 +6713,7 @@ TEST_F(ProjectStorage, GetBuiltinStringType) ASSERT_THAT(typeId, fetchTypeId(sourceId1, "var")); } -TEST_F(ProjectStorage, GetBuiltinStringTypeAgain) +TEST_F(ProjectStorage, get_builtin_string_type_again) { auto package{createBuiltinSynchronizationPackage()}; storage.synchronize(package); @@ -6724,7 +6724,7 @@ TEST_F(ProjectStorage, GetBuiltinStringTypeAgain) ASSERT_THAT(typeId, firstTypeId); } -TEST_F(ProjectStorage, GetBuiltinStringTypeAfterChangingType) +TEST_F(ProjectStorage, get_builtin_string_type_after_changing_type) { auto package{createBuiltinSynchronizationPackage()}; storage.synchronize(package); @@ -6738,7 +6738,7 @@ TEST_F(ProjectStorage, GetBuiltinStringTypeAfterChangingType) ASSERT_THAT(typeId, fetchTypeId(sourceId1, "variant")); } -TEST_F(ProjectStorage, GetPrototypeIds) +TEST_F(ProjectStorage, get_prototype_ids) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6750,7 +6750,7 @@ TEST_F(ProjectStorage, GetPrototypeIds) ElementsAre(fetchTypeId(sourceId1, "QObject2"), fetchTypeId(sourceId1, "QObject"))); } -TEST_F(ProjectStorage, GetNoPrototypeIdsForNoPrototype) +TEST_F(ProjectStorage, get_no_prototype_ids_for_no_prototype) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6761,7 +6761,7 @@ TEST_F(ProjectStorage, GetNoPrototypeIdsForNoPrototype) ASSERT_THAT(prototypeIds, IsEmpty()); } -TEST_F(ProjectStorage, GetPrototypeIdsWithExtension) +TEST_F(ProjectStorage, get_prototype_ids_with_extension) { auto package{createPackageWithProperties()}; std::swap(package.types[1].extension, package.types[1].prototype); @@ -6774,7 +6774,7 @@ TEST_F(ProjectStorage, GetPrototypeIdsWithExtension) ElementsAre(fetchTypeId(sourceId1, "QObject2"), fetchTypeId(sourceId1, "QObject"))); } -TEST_F(ProjectStorage, GetPrototypeAndSelfIds) +TEST_F(ProjectStorage, get_prototype_and_self_ids) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6788,7 +6788,7 @@ TEST_F(ProjectStorage, GetPrototypeAndSelfIds) fetchTypeId(sourceId1, "QObject"))); } -TEST_F(ProjectStorage, GetSelfForNoPrototypeIds) +TEST_F(ProjectStorage, get_self_for_no_prototype_ids) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6799,7 +6799,7 @@ TEST_F(ProjectStorage, GetSelfForNoPrototypeIds) ASSERT_THAT(prototypeAndSelfIds, ElementsAre(fetchTypeId(sourceId1, "QObject"))); } -TEST_F(ProjectStorage, GetPrototypeAndSelfIdsWithExtension) +TEST_F(ProjectStorage, get_prototype_and_self_ids_with_extension) { auto package{createPackageWithProperties()}; std::swap(package.types[1].extension, package.types[1].prototype); @@ -6814,7 +6814,7 @@ TEST_F(ProjectStorage, GetPrototypeAndSelfIdsWithExtension) fetchTypeId(sourceId1, "QObject"))); } -TEST_F(ProjectStorage, IsBasedOnForDirectPrototype) +TEST_F(ProjectStorage, is_based_on_for_direct_prototype) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6827,7 +6827,7 @@ TEST_F(ProjectStorage, IsBasedOnForDirectPrototype) ASSERT_TRUE(isBasedOn); } -TEST_F(ProjectStorage, IsBasedOnForIndirectPrototype) +TEST_F(ProjectStorage, is_based_on_for_indirect_prototype) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6839,7 +6839,7 @@ TEST_F(ProjectStorage, IsBasedOnForIndirectPrototype) ASSERT_TRUE(isBasedOn); } -TEST_F(ProjectStorage, IsBasedOnForDirectExtension) +TEST_F(ProjectStorage, is_based_on_for_direct_extension) { auto package{createPackageWithProperties()}; std::swap(package.types[1].extension, package.types[1].prototype); @@ -6852,7 +6852,7 @@ TEST_F(ProjectStorage, IsBasedOnForDirectExtension) ASSERT_TRUE(isBasedOn); } -TEST_F(ProjectStorage, IsBasedOnForIndirectExtension) +TEST_F(ProjectStorage, is_based_on_for_indirect_extension) { auto package{createPackageWithProperties()}; std::swap(package.types[1].extension, package.types[1].prototype); @@ -6865,7 +6865,7 @@ TEST_F(ProjectStorage, IsBasedOnForIndirectExtension) ASSERT_TRUE(isBasedOn); } -TEST_F(ProjectStorage, IsBasedOnForSelf) +TEST_F(ProjectStorage, is_based_on_for_self) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6877,7 +6877,7 @@ TEST_F(ProjectStorage, IsBasedOnForSelf) ASSERT_TRUE(isBasedOn); } -TEST_F(ProjectStorage, IsNotBasedOn) +TEST_F(ProjectStorage, is_not_based_on) { auto package{createPackageWithProperties()}; storage.synchronize(package); @@ -6890,7 +6890,7 @@ TEST_F(ProjectStorage, IsNotBasedOn) ASSERT_FALSE(isBasedOn); } -TEST_F(ProjectStorage, IsNotBasedOnIfNoBaseTypeIsGiven) +TEST_F(ProjectStorage, is_not_based_on_if_no_base_type_is_given) { auto package{createPackageWithProperties()}; storage.synchronize(package); diff --git a/tests/unit/unittest/projectstoragepathwatcher-test.cpp b/tests/unit/tests/unittests/projectstorage/projectstoragepathwatcher-test.cpp similarity index 84% rename from tests/unit/unittest/projectstoragepathwatcher-test.cpp rename to tests/unit/tests/unittests/projectstorage/projectstoragepathwatcher-test.cpp index ad5e0d14878..9fc9c30551b 100644 --- a/tests/unit/unittest/projectstoragepathwatcher-test.cpp +++ b/tests/unit/tests/unittests/projectstorage/projectstoragepathwatcher-test.cpp @@ -1,12 +1,12 @@ // Copyright (C) 2021 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" -#include "filesystemmock.h" -#include "mockqfilesystemwatcher.h" -#include "mocktimer.h" -#include "projectstoragepathwatchernotifiermock.h" +#include "../mocks/filesystemmock.h" +#include "../mocks/mockqfilesystemwatcher.h" +#include "../mocks/mocktimer.h" +#include "../mocks/projectstoragepathwatchernotifiermock.h" #include #include @@ -107,7 +107,7 @@ protected: WatcherEntry watcherEntry13{projectChunkId4, sourceContextIds[2], sourceIds[4]}; }; -TEST_F(ProjectStoragePathWatcher, AddIdPaths) +TEST_F(ProjectStoragePathWatcher, add_id_paths) { EXPECT_CALL(mockQFileSytemWatcher, addPaths( @@ -117,7 +117,7 @@ TEST_F(ProjectStoragePathWatcher, AddIdPaths) {projectChunkId2, {sourceIds[0], sourceIds[1], sourceIds[3]}}}); } -TEST_F(ProjectStoragePathWatcher, UpdateIdPathsCallsAddPathInFileWatcher) +TEST_F(ProjectStoragePathWatcher, update_id_paths_calls_add_path_in_file_watcher) { watcher.updateIdPaths({{projectChunkId1, {sourceIds[0], sourceIds[1]}}, {projectChunkId2, {sourceIds[0], sourceIds[1]}}}); @@ -128,7 +128,7 @@ TEST_F(ProjectStoragePathWatcher, UpdateIdPathsCallsAddPathInFileWatcher) {projectChunkId2, {sourceIds[0], sourceIds[1], sourceIds[3]}}}); } -TEST_F(ProjectStoragePathWatcher, UpdateIdPathsAndRemoveUnusedPathsCallsRemovePathInFileWatcher) +TEST_F(ProjectStoragePathWatcher, update_id_paths_and_remove_unused_paths_calls_remove_path_in_file_watcher) { watcher.updateIdPaths({{projectChunkId1, {sourceIds[0], sourceIds[1], sourceIds[2]}}, {projectChunkId2, {sourceIds[0], sourceIds[1], sourceIds[3]}}}); @@ -139,7 +139,7 @@ TEST_F(ProjectStoragePathWatcher, UpdateIdPathsAndRemoveUnusedPathsCallsRemovePa {projectChunkId2, {sourceIds[0], sourceIds[1]}}}); } -TEST_F(ProjectStoragePathWatcher, UpdateIdPathsAndRemoveUnusedPathsDoNotCallsRemovePathInFileWatcher) +TEST_F(ProjectStoragePathWatcher, update_id_paths_and_remove_unused_paths_do_not_calls_remove_path_in_file_watcher) { watcher.updateIdPaths({{projectChunkId1, {sourceIds[0], sourceIds[1], sourceIds[2]}}, {projectChunkId2, {sourceIds[0], sourceIds[1], sourceIds[3]}}, @@ -150,7 +150,7 @@ TEST_F(ProjectStoragePathWatcher, UpdateIdPathsAndRemoveUnusedPathsDoNotCallsRem watcher.updateIdPaths({{projectChunkId1, {sourceIds[1]}}, {projectChunkId2, {sourceIds[3]}}}); } -TEST_F(ProjectStoragePathWatcher, UpdateIdPathsAndRemoveUnusedPaths) +TEST_F(ProjectStoragePathWatcher, update_id_paths_and_remove_unused_paths) { watcher.updateIdPaths({{projectChunkId1, {sourceIds[0], sourceIds[1]}}, {projectChunkId2, {sourceIds[0], sourceIds[1]}}, @@ -161,7 +161,7 @@ TEST_F(ProjectStoragePathWatcher, UpdateIdPathsAndRemoveUnusedPaths) ASSERT_THAT(watcher.watchedEntries(), ElementsAre(watcherEntry1, watcherEntry4, watcherEntry5)); } -TEST_F(ProjectStoragePathWatcher, ExtractSortedEntriesFromConvertIdPaths) +TEST_F(ProjectStoragePathWatcher, extract_sorted_entries_from_convert_id_paths) { auto entriesAndIds = watcher.convertIdPathsToWatcherEntriesAndIds( {{projectChunkId2, {sourceIds[0], sourceIds[1]}}, @@ -171,7 +171,7 @@ TEST_F(ProjectStoragePathWatcher, ExtractSortedEntriesFromConvertIdPaths) ElementsAre(watcherEntry1, watcherEntry2, watcherEntry3, watcherEntry4)); } -TEST_F(ProjectStoragePathWatcher, ExtractSortedIdsFromConvertIdPaths) +TEST_F(ProjectStoragePathWatcher, extract_sorted_ids_from_convert_id_paths) { auto entriesAndIds = watcher.convertIdPathsToWatcherEntriesAndIds( {{projectChunkId2, {}}, {projectChunkId1, {}}, {projectChunkId3, {}}}); @@ -179,31 +179,31 @@ TEST_F(ProjectStoragePathWatcher, ExtractSortedIdsFromConvertIdPaths) ASSERT_THAT(entriesAndIds.second, ElementsAre(ids[0], ids[1], ids[2])); } -TEST_F(ProjectStoragePathWatcher, MergeEntries) +TEST_F(ProjectStoragePathWatcher, merge_entries) { watcher.updateIdPaths({{projectChunkId1, {sourceIds[0]}}, {projectChunkId2, {sourceIds[1]}}}); ASSERT_THAT(watcher.watchedEntries(), ElementsAre(watcherEntry1, watcherEntry4)); } -TEST_F(ProjectStoragePathWatcher, MergeMoreEntries) +TEST_F(ProjectStoragePathWatcher, merge_more_entries) { watcher.updateIdPaths({{projectChunkId2, {sourceIds[0], sourceIds[1]}}}); watcher.updateIdPaths({{projectChunkId1, {sourceIds[0], sourceIds[1]}}}); - ASSERT_THAT(watcher.watchedEntries(), ElementsAre(watcherEntry1, watcherEntry2, watcherEntry3, watcherEntry4)); + ASSERT_THAT(watcher.watchedEntries(), + ElementsAre(watcherEntry1, watcherEntry2, watcherEntry3, watcherEntry4)); } -TEST_F(ProjectStoragePathWatcher, AddEmptyEntries) +TEST_F(ProjectStoragePathWatcher, add_empty_entries) { - EXPECT_CALL(mockQFileSytemWatcher, addPaths(_)) - .Times(0); + EXPECT_CALL(mockQFileSytemWatcher, addPaths(_)).Times(0); watcher.updateIdPaths({}); } -TEST_F(ProjectStoragePathWatcher, AddEntriesWithSameIdAndDifferentPaths) +TEST_F(ProjectStoragePathWatcher, add_entries_with_same_id_and_different_paths) { EXPECT_CALL(mockQFileSytemWatcher, addPaths(ElementsAre(sourceContextPath, sourceContextPath2, sourceContextPath3))); @@ -212,14 +212,14 @@ TEST_F(ProjectStoragePathWatcher, AddEntriesWithSameIdAndDifferentPaths) {{projectChunkId1, {sourceIds[0], sourceIds[1], sourceIds[2], sourceIds[4]}}}); } -TEST_F(ProjectStoragePathWatcher, AddEntriesWithDifferentIdAndSamePaths) +TEST_F(ProjectStoragePathWatcher, add_entries_with_different_id_and_same_paths) { EXPECT_CALL(mockQFileSytemWatcher, addPaths(ElementsAre(sourceContextPath))); watcher.updateIdPaths({{projectChunkId1, {sourceIds[0], sourceIds[1]}}}); } -TEST_F(ProjectStoragePathWatcher, DontAddNewEntriesWithSameIdAndSamePaths) +TEST_F(ProjectStoragePathWatcher, dont_add_new_entries_with_same_id_and_same_paths) { watcher.updateIdPaths( {{projectChunkId1, {sourceIds[0], sourceIds[1], sourceIds[2], sourceIds[3], sourceIds[4]}}}); @@ -230,7 +230,7 @@ TEST_F(ProjectStoragePathWatcher, DontAddNewEntriesWithSameIdAndSamePaths) {{projectChunkId1, {sourceIds[0], sourceIds[1], sourceIds[2], sourceIds[3], sourceIds[4]}}}); } -TEST_F(ProjectStoragePathWatcher, DontAddNewEntriesWithDifferentIdAndSamePaths) +TEST_F(ProjectStoragePathWatcher, dont_add_new_entries_with_different_id_and_same_paths) { watcher.updateIdPaths( {{projectChunkId1, {sourceIds[0], sourceIds[1], sourceIds[2], sourceIds[3], sourceIds[4]}}}); @@ -241,7 +241,7 @@ TEST_F(ProjectStoragePathWatcher, DontAddNewEntriesWithDifferentIdAndSamePaths) {{projectChunkId2, {sourceIds[0], sourceIds[1], sourceIds[2], sourceIds[3], sourceIds[4]}}}); } -TEST_F(ProjectStoragePathWatcher, RemoveEntriesWithId) +TEST_F(ProjectStoragePathWatcher, remove_entries_with_id) { watcher.updateIdPaths({{projectChunkId1, {sourceIds[0], sourceIds[1]}}, {projectChunkId2, {sourceIds[0], sourceIds[1]}}, @@ -252,26 +252,24 @@ TEST_F(ProjectStoragePathWatcher, RemoveEntriesWithId) ASSERT_THAT(watcher.watchedEntries(), ElementsAre(watcherEntry5, watcherEntry8)); } -TEST_F(ProjectStoragePathWatcher, RemoveNoPathsForEmptyIds) +TEST_F(ProjectStoragePathWatcher, remove_no_paths_for_empty_ids) { - EXPECT_CALL(mockQFileSytemWatcher, removePaths(_)) - .Times(0); + EXPECT_CALL(mockQFileSytemWatcher, removePaths(_)).Times(0); watcher.removeIds({}); } -TEST_F(ProjectStoragePathWatcher, RemoveNoPathsForOneId) +TEST_F(ProjectStoragePathWatcher, remove_no_paths_for_one_id) { watcher.updateIdPaths({{projectChunkId1, {sourceIds[0], sourceIds[1]}}, {projectChunkId2, {sourceIds[0], sourceIds[1], sourceIds[3]}}}); - EXPECT_CALL(mockQFileSytemWatcher, removePaths(_)) - .Times(0); + EXPECT_CALL(mockQFileSytemWatcher, removePaths(_)).Times(0); watcher.removeIds({projectChunkId3.id}); } -TEST_F(ProjectStoragePathWatcher, RemovePathForOneId) +TEST_F(ProjectStoragePathWatcher, remove_path_for_one_id) { watcher.updateIdPaths({{projectChunkId1, {sourceIds[0], sourceIds[1]}}, {projectChunkId3, {sourceIds[0], sourceIds[1], sourceIds[3]}}}); @@ -281,7 +279,7 @@ TEST_F(ProjectStoragePathWatcher, RemovePathForOneId) watcher.removeIds({projectChunkId3.id}); } -TEST_F(ProjectStoragePathWatcher, RemoveNoPathSecondTime) +TEST_F(ProjectStoragePathWatcher, remove_no_path_second_time) { watcher.updateIdPaths({{projectChunkId1, {sourceIds[0], sourceIds[1]}}, {projectChunkId2, {sourceIds[0], sourceIds[1], sourceIds[3]}}}); @@ -292,7 +290,7 @@ TEST_F(ProjectStoragePathWatcher, RemoveNoPathSecondTime) watcher.removeIds({projectChunkId2.id}); } -TEST_F(ProjectStoragePathWatcher, RemoveAllPathsForThreeId) +TEST_F(ProjectStoragePathWatcher, remove_all_paths_for_three_id) { watcher.updateIdPaths({{projectChunkId1, {sourceIds[0], sourceIds[1], sourceIds[2]}}, {projectChunkId2, {sourceIds[0], sourceIds[1], sourceIds[3]}}}); @@ -303,7 +301,7 @@ TEST_F(ProjectStoragePathWatcher, RemoveAllPathsForThreeId) watcher.removeIds({projectChunkId1.id, projectChunkId2.id, projectChunkId3.id}); } -TEST_F(ProjectStoragePathWatcher, RemoveOnePathForTwoId) +TEST_F(ProjectStoragePathWatcher, remove_one_path_for_two_id) { watcher.updateIdPaths({{projectChunkId1, {sourceIds[0], sourceIds[1]}}, {projectChunkId2, {sourceIds[0], sourceIds[1]}}, @@ -314,12 +312,13 @@ TEST_F(ProjectStoragePathWatcher, RemoveOnePathForTwoId) watcher.removeIds({projectChunkId1.id, projectChunkId2.id}); } -TEST_F(ProjectStoragePathWatcher, NotAnymoreWatchedEntriesWithId) +TEST_F(ProjectStoragePathWatcher, not_anymore_watched_entries_with_id) { auto notContainsdId = [&](WatcherEntry entry) { return entry.id != ids[0] && entry.id != ids[1]; }; - watcher.addEntries(sorted({watcherEntry1, watcherEntry2, watcherEntry3, watcherEntry4, watcherEntry5})); + watcher.addEntries( + sorted({watcherEntry1, watcherEntry2, watcherEntry3, watcherEntry4, watcherEntry5})); auto oldEntries = watcher.notAnymoreWatchedEntriesWithIds({watcherEntry1, watcherEntry4}, notContainsdId); @@ -327,16 +326,17 @@ TEST_F(ProjectStoragePathWatcher, NotAnymoreWatchedEntriesWithId) ASSERT_THAT(oldEntries, ElementsAre(watcherEntry2, watcherEntry3)); } -TEST_F(ProjectStoragePathWatcher, RemoveUnusedEntries) +TEST_F(ProjectStoragePathWatcher, remove_unused_entries) { - watcher.addEntries(sorted({watcherEntry1, watcherEntry2, watcherEntry3, watcherEntry4, watcherEntry5})); + watcher.addEntries( + sorted({watcherEntry1, watcherEntry2, watcherEntry3, watcherEntry4, watcherEntry5})); watcher.removeFromWatchedEntries({watcherEntry2, watcherEntry3}); ASSERT_THAT(watcher.watchedEntries(), ElementsAre(watcherEntry1, watcherEntry4, watcherEntry5)); } -TEST_F(ProjectStoragePathWatcher, TwoNotifyFileChanges) +TEST_F(ProjectStoragePathWatcher, two_notify_file_changes) { watcher.updateIdPaths( {{projectChunkId1, {sourceIds[0], sourceIds[1], sourceIds[2]}}, @@ -359,7 +359,7 @@ TEST_F(ProjectStoragePathWatcher, TwoNotifyFileChanges) mockQFileSytemWatcher.directoryChanged(sourceContextPath2); } -TEST_F(ProjectStoragePathWatcher, NotifyForPathChanges) +TEST_F(ProjectStoragePathWatcher, notify_for_path_changes) { watcher.updateIdPaths({{projectChunkId1, {sourceIds[0], sourceIds[1], sourceIds[2]}}, {projectChunkId2, {sourceIds[0], sourceIds[1], sourceIds[3]}}}); @@ -374,7 +374,7 @@ TEST_F(ProjectStoragePathWatcher, NotifyForPathChanges) mockQFileSytemWatcher.directoryChanged(sourceContextPath); } -TEST_F(ProjectStoragePathWatcher, NoNotifyForUnwatchedPathChanges) +TEST_F(ProjectStoragePathWatcher, no_notify_for_unwatched_path_changes) { watcher.updateIdPaths({{projectChunkId1, {sourceIds[3]}}, {projectChunkId2, {sourceIds[3]}}}); @@ -383,7 +383,7 @@ TEST_F(ProjectStoragePathWatcher, NoNotifyForUnwatchedPathChanges) mockQFileSytemWatcher.directoryChanged(sourceContextPath); } -TEST_F(ProjectStoragePathWatcher, NoDuplicatePathChanges) +TEST_F(ProjectStoragePathWatcher, no_duplicate_path_changes) { watcher.updateIdPaths({{projectChunkId1, {sourceIds[0], sourceIds[1], sourceIds[2]}}, {projectChunkId2, {sourceIds[0], sourceIds[1], sourceIds[3]}}}); @@ -396,7 +396,7 @@ TEST_F(ProjectStoragePathWatcher, NoDuplicatePathChanges) mockQFileSytemWatcher.directoryChanged(sourceContextPath); } -TEST_F(ProjectStoragePathWatcher, UpdateContextIdPathsAddsEntryInNewDirectory) +TEST_F(ProjectStoragePathWatcher, update_context_id_paths_adds_entry_in_new_directory) { watcher.updateIdPaths({ {projectChunkId1, {sourceIds[0], sourceIds[1], sourceIds[2]}}, @@ -416,7 +416,7 @@ TEST_F(ProjectStoragePathWatcher, UpdateContextIdPathsAddsEntryInNewDirectory) watcherEntry13)); } -TEST_F(ProjectStoragePathWatcher, UpdateContextIdPathsAddsEntryToDirectory) +TEST_F(ProjectStoragePathWatcher, update_context_id_paths_adds_entry_to_directory) { watcher.updateIdPaths({ {projectChunkId1, {sourceIds[0], sourceIds[1], sourceIds[2]}}, @@ -437,7 +437,7 @@ TEST_F(ProjectStoragePathWatcher, UpdateContextIdPathsAddsEntryToDirectory) watcherEntry12)); } -TEST_F(ProjectStoragePathWatcher, UpdateContextIdPathsRemovesEntry) +TEST_F(ProjectStoragePathWatcher, update_context_id_paths_removes_entry) { watcher.updateIdPaths({ {projectChunkId1, {sourceIds[0], sourceIds[1], sourceIds[2]}}, diff --git a/tests/unit/unittest/projectstorageupdater-test.cpp b/tests/unit/tests/unittests/projectstorage/projectstorageupdater-test.cpp similarity index 90% rename from tests/unit/unittest/projectstorageupdater-test.cpp rename to tests/unit/tests/unittests/projectstorage/projectstorageupdater-test.cpp index f2f52d401f9..80cb7215fce 100644 --- a/tests/unit/unittest/projectstorageupdater-test.cpp +++ b/tests/unit/tests/unittests/projectstorage/projectstorageupdater-test.cpp @@ -1,13 +1,13 @@ // Copyright (C) 2021 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" -#include "filesystemmock.h" -#include "projectstoragemock.h" -#include "projectstoragepathwatchermock.h" -#include "qmldocumentparsermock.h" -#include "qmltypesparsermock.h" +#include "../mocks/filesystemmock.h" +#include "../mocks/projectstoragemock.h" +#include "../mocks/projectstoragepathwatchermock.h" +#include "../mocks/qmldocumentparsermock.h" +#include "../mocks/qmltypesparsermock.h" #include #include @@ -25,13 +25,13 @@ using QmlDesigner::SourceId; namespace Storage = QmlDesigner::Storage; using QmlDesigner::IdPaths; using QmlDesigner::Storage::TypeTraits; +using QmlDesigner::Storage::Version; using QmlDesigner::Storage::Synchronization::FileType; using QmlDesigner::Storage::Synchronization::Import; using QmlDesigner::Storage::Synchronization::IsAutoVersion; using QmlDesigner::Storage::Synchronization::ModuleExportedImport; using QmlDesigner::Storage::Synchronization::ProjectData; using QmlDesigner::Storage::Synchronization::SynchronizationPackage; -using QmlDesigner::Storage::Version; MATCHER_P5(IsStorageType, typeName, @@ -327,21 +327,11 @@ protected: Storage::Synchronization::Type firstType; Storage::Synchronization::Type secondType; Storage::Synchronization::Type thirdType; - Storage::Synchronization::Import import1{qmlModuleId, - Storage::Version{2, 3}, - qmlDocumentSourceId1}; - Storage::Synchronization::Import import2{qmlModuleId, - Storage::Version{}, - qmlDocumentSourceId2}; - Storage::Synchronization::Import import3{qmlModuleId, - Storage::Version{2}, - qmlDocumentSourceId3}; - Storage::Synchronization::Import import4{qmlModuleId, - Storage::Version{2, 3}, - qmltypesPathSourceId}; - Storage::Synchronization::Import import5{qmlModuleId, - Storage::Version{2, 3}, - qmltypes2PathSourceId}; + Storage::Synchronization::Import import1{qmlModuleId, Storage::Version{2, 3}, qmlDocumentSourceId1}; + Storage::Synchronization::Import import2{qmlModuleId, Storage::Version{}, qmlDocumentSourceId2}; + Storage::Synchronization::Import import3{qmlModuleId, Storage::Version{2}, qmlDocumentSourceId3}; + Storage::Synchronization::Import import4{qmlModuleId, Storage::Version{2, 3}, qmltypesPathSourceId}; + Storage::Synchronization::Import import5{qmlModuleId, Storage::Version{2, 3}, qmltypes2PathSourceId}; QString qmldirContent{"module Example\ntypeinfo example.qmltypes\n"}; QString qmltypes1{"Module {\ndependencies: [module1]}"}; QString qmltypes2{"Module {\ndependencies: [module2]}"}; @@ -375,7 +365,7 @@ protected: SourceId qmltypes2SourceId = sourcePathCache.sourceId("/path/two/example2.qmltypes"); }; -TEST_F(ProjectStorageUpdater, GetContentForQmlDirPathsIfFileStatusIsDifferent) +TEST_F(ProjectStorageUpdater, get_content_for_qml_dir_paths_if_file_status_is_different) { SourceId qmlDir1PathSourceId = sourcePathCache.sourceId("/path/one/qmldir"); SourceId qmlDir2PathSourceId = sourcePathCache.sourceId("/path/two/qmldir"); @@ -391,7 +381,7 @@ TEST_F(ProjectStorageUpdater, GetContentForQmlDirPathsIfFileStatusIsDifferent) updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, RequestFileStatusFromFileSystem) +TEST_F(ProjectStorageUpdater, request_file_status_from_file_system) { EXPECT_CALL(fileSystemMock, fileStatus(Ne(directoryPathSourceId))).Times(AnyNumber()); @@ -400,7 +390,7 @@ TEST_F(ProjectStorageUpdater, RequestFileStatusFromFileSystem) updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, GetContentForQmlTypes) +TEST_F(ProjectStorageUpdater, get_content_for_qml_types) { QString qmldir{R"(module Example typeinfo example.qmltypes)"}; @@ -412,7 +402,7 @@ TEST_F(ProjectStorageUpdater, GetContentForQmlTypes) updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, GetContentForQmlTypesIfProjectStorageFileStatusIsInvalid) +TEST_F(ProjectStorageUpdater, get_content_for_qml_types_if_project_storage_file_status_is_invalid) { QString qmldir{R"(module Example typeinfo example.qmltypes)"}; @@ -425,7 +415,7 @@ TEST_F(ProjectStorageUpdater, GetContentForQmlTypesIfProjectStorageFileStatusIsI updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, ParseQmlTypes) +TEST_F(ProjectStorageUpdater, parse_qml_types) { QString qmldir{R"(module Example typeinfo example.qmltypes @@ -444,7 +434,7 @@ TEST_F(ProjectStorageUpdater, ParseQmlTypes) updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, SynchronizeIsEmptyForNoChange) +TEST_F(ProjectStorageUpdater, synchronize_is_empty_for_no_change) { setFilesDontChanged({qmltypesPathSourceId, qmltypes2PathSourceId, qmlDirPathSourceId}); @@ -453,11 +443,9 @@ TEST_F(ProjectStorageUpdater, SynchronizeIsEmptyForNoChange) updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, SynchronizeQmlTypes) +TEST_F(ProjectStorageUpdater, synchronize_qml_types) { - Storage::Synchronization::Import import{qmlModuleId, - Storage::Version{2, 3}, - qmltypesPathSourceId}; + Storage::Synchronization::Import import{qmlModuleId, Storage::Version{2, 3}, qmltypesPathSourceId}; QString qmltypes{"Module {\ndependencies: []}"}; setQmlFileNames(u"/path", {}); setContent(u"/path/example.qmltypes", qmltypes); @@ -490,17 +478,15 @@ TEST_F(ProjectStorageUpdater, SynchronizeQmlTypes) updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, SynchronizeQmlTypesThrowsIfQmltpesDoesNotExists) +TEST_F(ProjectStorageUpdater, synchronize_qml_types_throws_if_qmltpes_does_not_exists) { - Storage::Synchronization::Import import{qmlModuleId, - Storage::Version{2, 3}, - qmltypesPathSourceId}; + Storage::Synchronization::Import import{qmlModuleId, Storage::Version{2, 3}, qmltypesPathSourceId}; setFilesDontExists({qmltypesPathSourceId}); ASSERT_THROW(updater.update(directories, {}), QmlDesigner::CannotParseQmlTypesFile); } -TEST_F(ProjectStorageUpdater, SynchronizeQmlTypesAreEmptyIfFileDoesNotChanged) +TEST_F(ProjectStorageUpdater, synchronize_qml_types_are_empty_if_file_does_not_changed) { QString qmltypes{"Module {\ndependencies: []}"}; setContent(u"/path/example.qmltypes", qmltypes); @@ -513,7 +499,7 @@ TEST_F(ProjectStorageUpdater, SynchronizeQmlTypesAreEmptyIfFileDoesNotChanged) updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, GetContentForQmlDocuments) +TEST_F(ProjectStorageUpdater, get_content_for_qml_documents) { SourceId oldSecondSourceId3 = sourcePathCache.sourceId("/path/OldSecond.qml"); setQmlFileNames(u"/path", {"First.qml", "First2.qml", "OldSecond.qml", "Second.qml"}); @@ -534,7 +520,7 @@ TEST_F(ProjectStorageUpdater, GetContentForQmlDocuments) updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, ParseQmlDocuments) +TEST_F(ProjectStorageUpdater, parse_qml_documents) { QString qmldir{R"(module Example FirstType 1.0 First.qml @@ -555,7 +541,7 @@ TEST_F(ProjectStorageUpdater, ParseQmlDocuments) updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, ParseQmlDocumentsWithNonExistingQmlDocumentThrows) +TEST_F(ProjectStorageUpdater, parse_qml_documents_with_non_existing_qml_document_throws) { QString qmldir{R"(module Example NonexitingType 1.0 NonexitingType.qml)"}; @@ -564,7 +550,7 @@ TEST_F(ProjectStorageUpdater, ParseQmlDocumentsWithNonExistingQmlDocumentThrows) ASSERT_THROW(updater.update(directories, {}), QmlDesigner::CannotParseQmlDocumentFile); } -TEST_F(ProjectStorageUpdater, SynchronizeQmlDocuments) +TEST_F(ProjectStorageUpdater, synchronize_qml_documents) { QString qmldir{R"(module Example FirstType 1.0 First.qml @@ -637,7 +623,7 @@ TEST_F(ProjectStorageUpdater, SynchronizeQmlDocuments) updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, SynchronizeAddOnlyQmlDocumentInDirectory) +TEST_F(ProjectStorageUpdater, synchronize_add_only_qml_document_in_directory) { QString qmldir{R"(module Example FirstType 1.0 First.qml)"}; @@ -693,7 +679,7 @@ TEST_F(ProjectStorageUpdater, SynchronizeAddOnlyQmlDocumentInDirectory) updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, SynchronizeRemovesQmlDocument) +TEST_F(ProjectStorageUpdater, synchronize_removes_qml_document) { QString qmldir{R"(module Example FirstType 1.0 First.qml @@ -756,7 +742,7 @@ TEST_F(ProjectStorageUpdater, SynchronizeRemovesQmlDocument) updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, SynchronizeRemovesQmlDocumentInQmldirOnly) +TEST_F(ProjectStorageUpdater, synchronize_removes_qml_document_in_qmldir_only) { QString qmldir{R"(module Example FirstType 1.0 First.qml @@ -811,7 +797,7 @@ TEST_F(ProjectStorageUpdater, SynchronizeRemovesQmlDocumentInQmldirOnly) updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, SynchronizeAddQmlDocumentToQmldir) +TEST_F(ProjectStorageUpdater, synchronize_add_qml_document_to_qmldir) { QString qmldir{R"(module Example FirstType 1.0 First.qml @@ -869,7 +855,7 @@ TEST_F(ProjectStorageUpdater, SynchronizeAddQmlDocumentToQmldir) updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, SynchronizeRemoveQmlDocumentFromQmldir) +TEST_F(ProjectStorageUpdater, synchronize_remove_qml_document_from_qmldir) { QString qmldir{R"(module Example FirstType 1.0 First.qml @@ -924,7 +910,7 @@ TEST_F(ProjectStorageUpdater, SynchronizeRemoveQmlDocumentFromQmldir) updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, SynchronizeQmlDocumentsDontUpdateIfUpToDate) +TEST_F(ProjectStorageUpdater, synchronize_qml_documents_dont_update_if_up_to_date) { QString qmldir{R"(module Example FirstType 1.0 First.qml @@ -994,7 +980,7 @@ TEST_F(ProjectStorageUpdater, SynchronizeQmlDocumentsDontUpdateIfUpToDate) updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, SynchronizIfQmldirFileHasNotChanged) +TEST_F(ProjectStorageUpdater, synchroniz_if_qmldir_file_has_not_changed) { setProjectDatas( directoryPathSourceId, @@ -1045,7 +1031,7 @@ TEST_F(ProjectStorageUpdater, SynchronizIfQmldirFileHasNotChanged) updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, SynchronizIfQmldirFileHasNotChangedAndSomeUpdatedFiles) +TEST_F(ProjectStorageUpdater, synchroniz_if_qmldir_file_has_not_changed_and_some_updated_files) { setProjectDatas( directoryPathSourceId, @@ -1080,7 +1066,7 @@ TEST_F(ProjectStorageUpdater, SynchronizIfQmldirFileHasNotChangedAndSomeUpdatedF updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, SynchronizIfQmldirFileNotChangedAndSomeRemovedFiles) +TEST_F(ProjectStorageUpdater, synchroniz_if_qmldir_file_not_changed_and_some_removed_files) { setQmlFileNames(u"/path", {"First2.qml"}); setProjectDatas( @@ -1095,7 +1081,7 @@ TEST_F(ProjectStorageUpdater, SynchronizIfQmldirFileNotChangedAndSomeRemovedFile ASSERT_THROW(updater.update(directories, {}), QmlDesigner::CannotParseQmlTypesFile); } -TEST_F(ProjectStorageUpdater, SynchronizIfQmldirFileHasChangedAndSomeRemovedFiles) +TEST_F(ProjectStorageUpdater, synchroniz_if_qmldir_file_has_changed_and_some_removed_files) { QString qmldir{R"(module Example FirstType 2.2 First2.qml @@ -1147,7 +1133,7 @@ TEST_F(ProjectStorageUpdater, SynchronizIfQmldirFileHasChangedAndSomeRemovedFile updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, UpdateQmlTypesFilesIsEmpty) +TEST_F(ProjectStorageUpdater, update_qml_types_files_is_empty) { EXPECT_CALL(projectStorageMock, synchronize( @@ -1162,7 +1148,7 @@ TEST_F(ProjectStorageUpdater, UpdateQmlTypesFilesIsEmpty) updater.update({}, {}); } -TEST_F(ProjectStorageUpdater, UpdateQmlTypesFiles) +TEST_F(ProjectStorageUpdater, update_qml_types_files) { EXPECT_CALL(projectStorageMock, synchronize(AllOf( @@ -1189,7 +1175,7 @@ TEST_F(ProjectStorageUpdater, UpdateQmlTypesFiles) updater.update({}, {"/path/example.qmltypes", "/path/example2.qmltypes"}); } -TEST_F(ProjectStorageUpdater, DontUpdateQmlTypesFilesIfUnchanged) +TEST_F(ProjectStorageUpdater, dont_update_qml_types_files_if_unchanged) { setFilesDontChanged({qmltypes2PathSourceId}); @@ -1213,7 +1199,7 @@ TEST_F(ProjectStorageUpdater, DontUpdateQmlTypesFilesIfUnchanged) updater.update({}, {"/path/example.qmltypes", "/path/example2.qmltypes"}); } -TEST_F(ProjectStorageUpdater, SynchronizeQmlDocumentsWithDifferentVersionButSameTypeNameAndFileName) +TEST_F(ProjectStorageUpdater, synchronize_qml_documents_with_different_version_but_same_type_name_and_file_name) { QString qmldir{R"(module Example FirstType 1.0 First.qml @@ -1256,7 +1242,7 @@ TEST_F(ProjectStorageUpdater, SynchronizeQmlDocumentsWithDifferentVersionButSame updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, SynchronizeQmlDocumentsWithDifferentTypeNameButSameVersionAndFileName) +TEST_F(ProjectStorageUpdater, synchronize_qml_documents_with_different_type_name_but_same_version_and_file_name) { QString qmldir{R"(module Example FirstType 1.0 First.qml @@ -1297,7 +1283,7 @@ TEST_F(ProjectStorageUpdater, SynchronizeQmlDocumentsWithDifferentTypeNameButSam updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, DontSynchronizeSelectors) +TEST_F(ProjectStorageUpdater, dont_synchronize_selectors) { setContent(u"/path/+First.qml", qmlDocument1); setContent(u"/path/qml/+First.qml", qmlDocument1); @@ -1315,7 +1301,7 @@ TEST_F(ProjectStorageUpdater, DontSynchronizeSelectors) updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, SynchronizeQmldirDependencies) +TEST_F(ProjectStorageUpdater, synchronize_qmldir_dependencies) { QString qmldir{R"(module Example depends Qml @@ -1325,28 +1311,22 @@ TEST_F(ProjectStorageUpdater, SynchronizeQmldirDependencies) )"}; setContent(u"/path/qmldir", qmldir); - EXPECT_CALL(projectStorageMock, - synchronize( - AllOf(Field(&SynchronizationPackage::moduleDependencies, - UnorderedElementsAre(Import{qmlCppNativeModuleId, - Storage::Version{}, - qmltypesPathSourceId}, - Import{builtinCppNativeModuleId, - Storage::Version{}, - qmltypesPathSourceId}, - Import{qmlCppNativeModuleId, - Storage::Version{}, - qmltypes2PathSourceId}, - Import{builtinCppNativeModuleId, - Storage::Version{}, - qmltypes2PathSourceId})), - Field(&SynchronizationPackage::updatedModuleDependencySourceIds, - UnorderedElementsAre(qmltypesPathSourceId, qmltypes2PathSourceId))))); + EXPECT_CALL( + projectStorageMock, + synchronize(AllOf( + Field(&SynchronizationPackage::moduleDependencies, + UnorderedElementsAre( + Import{qmlCppNativeModuleId, Storage::Version{}, qmltypesPathSourceId}, + Import{builtinCppNativeModuleId, Storage::Version{}, qmltypesPathSourceId}, + Import{qmlCppNativeModuleId, Storage::Version{}, qmltypes2PathSourceId}, + Import{builtinCppNativeModuleId, Storage::Version{}, qmltypes2PathSourceId})), + Field(&SynchronizationPackage::updatedModuleDependencySourceIds, + UnorderedElementsAre(qmltypesPathSourceId, qmltypes2PathSourceId))))); updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, SynchronizeQmldirDependenciesWithDoubleEntries) +TEST_F(ProjectStorageUpdater, synchronize_qmldir_dependencies_with_double_entries) { QString qmldir{R"(module Example depends Qml @@ -1357,28 +1337,22 @@ TEST_F(ProjectStorageUpdater, SynchronizeQmldirDependenciesWithDoubleEntries) )"}; setContent(u"/path/qmldir", qmldir); - EXPECT_CALL(projectStorageMock, - synchronize( - AllOf(Field(&SynchronizationPackage::moduleDependencies, - UnorderedElementsAre(Import{qmlCppNativeModuleId, - Storage::Version{}, - qmltypesPathSourceId}, - Import{builtinCppNativeModuleId, - Storage::Version{}, - qmltypesPathSourceId}, - Import{qmlCppNativeModuleId, - Storage::Version{}, - qmltypes2PathSourceId}, - Import{builtinCppNativeModuleId, - Storage::Version{}, - qmltypes2PathSourceId})), - Field(&SynchronizationPackage::updatedModuleDependencySourceIds, - UnorderedElementsAre(qmltypesPathSourceId, qmltypes2PathSourceId))))); + EXPECT_CALL( + projectStorageMock, + synchronize(AllOf( + Field(&SynchronizationPackage::moduleDependencies, + UnorderedElementsAre( + Import{qmlCppNativeModuleId, Storage::Version{}, qmltypesPathSourceId}, + Import{builtinCppNativeModuleId, Storage::Version{}, qmltypesPathSourceId}, + Import{qmlCppNativeModuleId, Storage::Version{}, qmltypes2PathSourceId}, + Import{builtinCppNativeModuleId, Storage::Version{}, qmltypes2PathSourceId})), + Field(&SynchronizationPackage::updatedModuleDependencySourceIds, + UnorderedElementsAre(qmltypesPathSourceId, qmltypes2PathSourceId))))); updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, SynchronizeQmldirDependenciesWithCollidingImports) +TEST_F(ProjectStorageUpdater, synchronize_qmldir_dependencies_with_colliding_imports) { QString qmldir{R"(module Example depends Qml @@ -1389,28 +1363,22 @@ TEST_F(ProjectStorageUpdater, SynchronizeQmldirDependenciesWithCollidingImports) )"}; setContent(u"/path/qmldir", qmldir); - EXPECT_CALL(projectStorageMock, - synchronize( - AllOf(Field(&SynchronizationPackage::moduleDependencies, - UnorderedElementsAre(Import{qmlCppNativeModuleId, - Storage::Version{}, - qmltypesPathSourceId}, - Import{builtinCppNativeModuleId, - Storage::Version{}, - qmltypesPathSourceId}, - Import{qmlCppNativeModuleId, - Storage::Version{}, - qmltypes2PathSourceId}, - Import{builtinCppNativeModuleId, - Storage::Version{}, - qmltypes2PathSourceId})), - Field(&SynchronizationPackage::updatedModuleDependencySourceIds, - UnorderedElementsAre(qmltypesPathSourceId, qmltypes2PathSourceId))))); + EXPECT_CALL( + projectStorageMock, + synchronize(AllOf( + Field(&SynchronizationPackage::moduleDependencies, + UnorderedElementsAre( + Import{qmlCppNativeModuleId, Storage::Version{}, qmltypesPathSourceId}, + Import{builtinCppNativeModuleId, Storage::Version{}, qmltypesPathSourceId}, + Import{qmlCppNativeModuleId, Storage::Version{}, qmltypes2PathSourceId}, + Import{builtinCppNativeModuleId, Storage::Version{}, qmltypes2PathSourceId})), + Field(&SynchronizationPackage::updatedModuleDependencySourceIds, + UnorderedElementsAre(qmltypesPathSourceId, qmltypes2PathSourceId))))); updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, SynchronizeQmldirWithNoDependencies) +TEST_F(ProjectStorageUpdater, synchronize_qmldir_with_no_dependencies) { QString qmldir{R"(module Example typeinfo example.qmltypes @@ -1427,7 +1395,7 @@ TEST_F(ProjectStorageUpdater, SynchronizeQmldirWithNoDependencies) updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, SynchronizeQmldirImports) +TEST_F(ProjectStorageUpdater, synchronize_qmldir_imports) { QString qmldir{R"(module Example import Qml auto @@ -1436,40 +1404,40 @@ TEST_F(ProjectStorageUpdater, SynchronizeQmldirImports) )"}; setContent(u"/path/qmldir", qmldir); - EXPECT_CALL( - projectStorageMock, - synchronize(AllOf( - Field(&SynchronizationPackage::moduleExportedImports, - UnorderedElementsAre(ModuleExportedImport{exampleModuleId, - qmlModuleId, - Storage::Version{}, - IsAutoVersion::Yes}, - ModuleExportedImport{exampleCppNativeModuleId, - qmlCppNativeModuleId, - Storage::Version{}, - IsAutoVersion::No}, - ModuleExportedImport{exampleModuleId, - builtinModuleId, - Storage::Version{2, 1}, - IsAutoVersion::No}, - ModuleExportedImport{exampleCppNativeModuleId, - builtinCppNativeModuleId, - Storage::Version{}, - IsAutoVersion::No}, - ModuleExportedImport{exampleModuleId, - quickModuleId, - Storage::Version{}, - IsAutoVersion::No}, - ModuleExportedImport{exampleCppNativeModuleId, - quickCppNativeModuleId, - Storage::Version{}, - IsAutoVersion::No})), - Field(&SynchronizationPackage::updatedModuleIds, ElementsAre(exampleModuleId))))); + EXPECT_CALL(projectStorageMock, + synchronize( + AllOf(Field(&SynchronizationPackage::moduleExportedImports, + UnorderedElementsAre(ModuleExportedImport{exampleModuleId, + qmlModuleId, + Storage::Version{}, + IsAutoVersion::Yes}, + ModuleExportedImport{exampleCppNativeModuleId, + qmlCppNativeModuleId, + Storage::Version{}, + IsAutoVersion::No}, + ModuleExportedImport{exampleModuleId, + builtinModuleId, + Storage::Version{2, 1}, + IsAutoVersion::No}, + ModuleExportedImport{exampleCppNativeModuleId, + builtinCppNativeModuleId, + Storage::Version{}, + IsAutoVersion::No}, + ModuleExportedImport{exampleModuleId, + quickModuleId, + Storage::Version{}, + IsAutoVersion::No}, + ModuleExportedImport{exampleCppNativeModuleId, + quickCppNativeModuleId, + Storage::Version{}, + IsAutoVersion::No})), + Field(&SynchronizationPackage::updatedModuleIds, + ElementsAre(exampleModuleId))))); updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, SynchronizeQmldirWithNoImports) +TEST_F(ProjectStorageUpdater, synchronize_qmldir_with_no_imports) { QString qmldir{R"(module Example )"}; @@ -1483,7 +1451,7 @@ TEST_F(ProjectStorageUpdater, SynchronizeQmldirWithNoImports) updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, SynchronizeQmldirImportsWithDoubleEntries) +TEST_F(ProjectStorageUpdater, synchronize_qmldir_imports_with_double_entries) { QString qmldir{R"(module Example import Qml auto @@ -1493,40 +1461,40 @@ TEST_F(ProjectStorageUpdater, SynchronizeQmldirImportsWithDoubleEntries) )"}; setContent(u"/path/qmldir", qmldir); - EXPECT_CALL( - projectStorageMock, - synchronize(AllOf( - Field(&SynchronizationPackage::moduleExportedImports, - UnorderedElementsAre(ModuleExportedImport{exampleModuleId, - qmlModuleId, - Storage::Version{}, - IsAutoVersion::Yes}, - ModuleExportedImport{exampleCppNativeModuleId, - qmlCppNativeModuleId, - Storage::Version{}, - IsAutoVersion::No}, - ModuleExportedImport{exampleModuleId, - builtinModuleId, - Storage::Version{2, 1}, - IsAutoVersion::No}, - ModuleExportedImport{exampleCppNativeModuleId, - builtinCppNativeModuleId, - Storage::Version{}, - IsAutoVersion::No}, - ModuleExportedImport{exampleModuleId, - quickModuleId, - Storage::Version{}, - IsAutoVersion::No}, - ModuleExportedImport{exampleCppNativeModuleId, - quickCppNativeModuleId, - Storage::Version{}, - IsAutoVersion::No})), - Field(&SynchronizationPackage::updatedModuleIds, ElementsAre(exampleModuleId))))); + EXPECT_CALL(projectStorageMock, + synchronize( + AllOf(Field(&SynchronizationPackage::moduleExportedImports, + UnorderedElementsAre(ModuleExportedImport{exampleModuleId, + qmlModuleId, + Storage::Version{}, + IsAutoVersion::Yes}, + ModuleExportedImport{exampleCppNativeModuleId, + qmlCppNativeModuleId, + Storage::Version{}, + IsAutoVersion::No}, + ModuleExportedImport{exampleModuleId, + builtinModuleId, + Storage::Version{2, 1}, + IsAutoVersion::No}, + ModuleExportedImport{exampleCppNativeModuleId, + builtinCppNativeModuleId, + Storage::Version{}, + IsAutoVersion::No}, + ModuleExportedImport{exampleModuleId, + quickModuleId, + Storage::Version{}, + IsAutoVersion::No}, + ModuleExportedImport{exampleCppNativeModuleId, + quickCppNativeModuleId, + Storage::Version{}, + IsAutoVersion::No})), + Field(&SynchronizationPackage::updatedModuleIds, + ElementsAre(exampleModuleId))))); updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, SynchronizeQmldirOptionalImports) +TEST_F(ProjectStorageUpdater, synchronize_qmldir_optional_imports) { QString qmldir{R"(module Example import Qml auto @@ -1535,40 +1503,40 @@ TEST_F(ProjectStorageUpdater, SynchronizeQmldirOptionalImports) )"}; setContent(u"/path/qmldir", qmldir); - EXPECT_CALL( - projectStorageMock, - synchronize(AllOf( - Field(&SynchronizationPackage::moduleExportedImports, - UnorderedElementsAre(ModuleExportedImport{exampleModuleId, - qmlModuleId, - Storage::Version{}, - IsAutoVersion::Yes}, - ModuleExportedImport{exampleCppNativeModuleId, - qmlCppNativeModuleId, - Storage::Version{}, - IsAutoVersion::No}, - ModuleExportedImport{exampleModuleId, - builtinModuleId, - Storage::Version{2, 1}, - IsAutoVersion::No}, - ModuleExportedImport{exampleCppNativeModuleId, - builtinCppNativeModuleId, - Storage::Version{}, - IsAutoVersion::No}, - ModuleExportedImport{exampleModuleId, - quickModuleId, - Storage::Version{}, - IsAutoVersion::No}, - ModuleExportedImport{exampleCppNativeModuleId, - quickCppNativeModuleId, - Storage::Version{}, - IsAutoVersion::No})), - Field(&SynchronizationPackage::updatedModuleIds, ElementsAre(exampleModuleId))))); + EXPECT_CALL(projectStorageMock, + synchronize( + AllOf(Field(&SynchronizationPackage::moduleExportedImports, + UnorderedElementsAre(ModuleExportedImport{exampleModuleId, + qmlModuleId, + Storage::Version{}, + IsAutoVersion::Yes}, + ModuleExportedImport{exampleCppNativeModuleId, + qmlCppNativeModuleId, + Storage::Version{}, + IsAutoVersion::No}, + ModuleExportedImport{exampleModuleId, + builtinModuleId, + Storage::Version{2, 1}, + IsAutoVersion::No}, + ModuleExportedImport{exampleCppNativeModuleId, + builtinCppNativeModuleId, + Storage::Version{}, + IsAutoVersion::No}, + ModuleExportedImport{exampleModuleId, + quickModuleId, + Storage::Version{}, + IsAutoVersion::No}, + ModuleExportedImport{exampleCppNativeModuleId, + quickCppNativeModuleId, + Storage::Version{}, + IsAutoVersion::No})), + Field(&SynchronizationPackage::updatedModuleIds, + ElementsAre(exampleModuleId))))); updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, UpdatePathWatcherDirectories) +TEST_F(ProjectStorageUpdater, update_path_watcher_directories) { EXPECT_CALL(patchWatcherMock, updateIdPaths(Contains(IdPaths{projectPartId, @@ -1578,7 +1546,7 @@ TEST_F(ProjectStorageUpdater, UpdatePathWatcherDirectories) updater.update(directories3, {}); } -TEST_F(ProjectStorageUpdater, UpdatePathWatcherDirectoryDoesNotExists) +TEST_F(ProjectStorageUpdater, update_path_watcher_directory_does_not_exists) { setFilesDontExists({path2SourceId}); @@ -1590,7 +1558,7 @@ TEST_F(ProjectStorageUpdater, UpdatePathWatcherDirectoryDoesNotExists) updater.update(directories3, {}); } -TEST_F(ProjectStorageUpdater, UpdatePathWatcherDirectoryDoesNotChanged) +TEST_F(ProjectStorageUpdater, update_path_watcher_directory_does_not_changed) { setFilesDontChanged({qmldir1SourceId, qmldir2SourceId, path1SourceId, path2SourceId}); @@ -1602,7 +1570,7 @@ TEST_F(ProjectStorageUpdater, UpdatePathWatcherDirectoryDoesNotChanged) updater.update(directories2, {}); } -TEST_F(ProjectStorageUpdater, UpdatePathWatcherDirectoryRemoved) +TEST_F(ProjectStorageUpdater, update_path_watcher_directory_removed) { setFilesRemoved({qmldir1SourceId, path1SourceId}); @@ -1613,7 +1581,7 @@ TEST_F(ProjectStorageUpdater, UpdatePathWatcherDirectoryRemoved) updater.update(directories2, {}); } -TEST_F(ProjectStorageUpdater, UpdatePathWatcherQmldirs) +TEST_F(ProjectStorageUpdater, update_path_watcher_qmldirs) { EXPECT_CALL(patchWatcherMock, updateIdPaths(Contains(IdPaths{projectPartId, @@ -1623,7 +1591,7 @@ TEST_F(ProjectStorageUpdater, UpdatePathWatcherQmldirs) updater.update(directories3, {}); } -TEST_F(ProjectStorageUpdater, UpdatePathWatcherQmldirDoesNotExists) +TEST_F(ProjectStorageUpdater, update_path_watcher_qmldir_does_not_exists) { setFilesDontExists({qmldir2SourceId}); @@ -1635,7 +1603,7 @@ TEST_F(ProjectStorageUpdater, UpdatePathWatcherQmldirDoesNotExists) updater.update(directories3, {}); } -TEST_F(ProjectStorageUpdater, UpdatePathWatcherQmldirDoesNotChanged) +TEST_F(ProjectStorageUpdater, update_path_watcher_qmldir_does_not_changed) { setFilesDontChanged({qmldir1SourceId, qmldir2SourceId, path1SourceId, path2SourceId}); @@ -1647,7 +1615,7 @@ TEST_F(ProjectStorageUpdater, UpdatePathWatcherQmldirDoesNotChanged) updater.update(directories2, {}); } -TEST_F(ProjectStorageUpdater, UpdatePathWatcherQmldirRemoved) +TEST_F(ProjectStorageUpdater, update_path_watcher_qmldir_removed) { setFilesRemoved({qmldir1SourceId, path1SourceId}); @@ -1658,7 +1626,7 @@ TEST_F(ProjectStorageUpdater, UpdatePathWatcherQmldirRemoved) updater.update(directories2, {}); } -TEST_F(ProjectStorageUpdater, UpdatePathWatcherQmlFiles) +TEST_F(ProjectStorageUpdater, update_path_watcher_qml_files) { QString qmldir1{R"(module Example FirstType 1.0 First.qml @@ -1675,7 +1643,7 @@ TEST_F(ProjectStorageUpdater, UpdatePathWatcherQmlFiles) updater.update(directories2, {}); } -TEST_F(ProjectStorageUpdater, UpdatePathWatcherOnlyQmlFilesDontChanged) +TEST_F(ProjectStorageUpdater, update_path_watcher_only_qml_files_dont_changed) { QString qmldir1{R"(module Example FirstType 1.0 First.qml @@ -1693,7 +1661,7 @@ TEST_F(ProjectStorageUpdater, UpdatePathWatcherOnlyQmlFilesDontChanged) updater.update(directories2, {}); } -TEST_F(ProjectStorageUpdater, UpdatePathWatcherOnlyQmlFilesChanged) +TEST_F(ProjectStorageUpdater, update_path_watcher_only_qml_files_changed) { setFilesDontChanged({qmldir1SourceId, qmldir2SourceId, path1SourceId, path2SourceId}); setFilesChanged({firstSourceId, secondSourceId, thirdSourceId}); @@ -1711,7 +1679,7 @@ TEST_F(ProjectStorageUpdater, UpdatePathWatcherOnlyQmlFilesChanged) updater.update(directories2, {}); } -TEST_F(ProjectStorageUpdater, UpdatePathWatcherQmlFilesAndDirectoriesDontChanged) +TEST_F(ProjectStorageUpdater, update_path_watcher_qml_files_and_directories_dont_changed) { setFilesDontChanged({qmldir1SourceId, qmldir2SourceId, @@ -1734,7 +1702,7 @@ TEST_F(ProjectStorageUpdater, UpdatePathWatcherQmlFilesAndDirectoriesDontChanged updater.update(directories2, {}); } -TEST_F(ProjectStorageUpdater, UpdatePathWatcherQmltypesFilesInQmldir) +TEST_F(ProjectStorageUpdater, update_path_watcher_qmltypes_files_in_qmldir) { QString qmldir1{R"(module Example typeinfo example.qmltypes)"}; @@ -1753,7 +1721,7 @@ TEST_F(ProjectStorageUpdater, UpdatePathWatcherQmltypesFilesInQmldir) updater.update(directories2, {}); } -TEST_F(ProjectStorageUpdater, UpdatePathWatcherOnlyQmltypesFilesInQmldirDontChanged) +TEST_F(ProjectStorageUpdater, update_path_watcher_only_qmltypes_files_in_qmldir_dont_changed) { QString qmldir1{R"(module Example typeinfo example.qmltypes)"}; @@ -1771,7 +1739,7 @@ TEST_F(ProjectStorageUpdater, UpdatePathWatcherOnlyQmltypesFilesInQmldirDontChan updater.update(directories2, {}); } -TEST_F(ProjectStorageUpdater, UpdatePathWatcherOnlyQmltypesFilesChanged) +TEST_F(ProjectStorageUpdater, update_path_watcher_only_qmltypes_files_changed) { setFilesDontChanged({qmldir1SourceId, qmldir2SourceId, path1SourceId, path2SourceId}); setFilesChanged({qmltypes1SourceId, qmltypes2SourceId}); @@ -1788,7 +1756,7 @@ TEST_F(ProjectStorageUpdater, UpdatePathWatcherOnlyQmltypesFilesChanged) updater.update(directories2, {}); } -TEST_F(ProjectStorageUpdater, UpdatePathWatcherQmltypesFilesAndDirectoriesDontChanged) +TEST_F(ProjectStorageUpdater, update_path_watcher_qmltypes_files_and_directories_dont_changed) { setFilesDontChanged({qmldir1SourceId, qmldir2SourceId, @@ -1809,7 +1777,7 @@ TEST_F(ProjectStorageUpdater, UpdatePathWatcherQmltypesFilesAndDirectoriesDontCh updater.update(directories2, {}); } -TEST_F(ProjectStorageUpdater, UpdatePathWatcherBuiltinQmltypesFiles) +TEST_F(ProjectStorageUpdater, update_path_watcher_builtin_qmltypes_files) { QString builtinQmltyplesPath1{"/path/one/example.qmltypes"}; QString builtinQmltyplesPath2{"/path/two/example2.qmltypes"}; @@ -1824,7 +1792,7 @@ TEST_F(ProjectStorageUpdater, UpdatePathWatcherBuiltinQmltypesFiles) updater.update({}, {builtinQmltyplesPath1, builtinQmltyplesPath2}); } -TEST_F(ProjectStorageUpdater, SynchronizeQmlDocumentsWithoutQmldir) +TEST_F(ProjectStorageUpdater, synchronize_qml_documents_without_qmldir) { setFilesDontExists({qmlDirPathSourceId}); setFilesChanged({directoryPathSourceId}); @@ -1891,7 +1859,7 @@ TEST_F(ProjectStorageUpdater, SynchronizeQmlDocumentsWithoutQmldir) updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, SynchronizeQmlDocumentsWithoutQmldirThrowsIfQmlDocumentDoesNotExists) +TEST_F(ProjectStorageUpdater, synchronize_qml_documents_without_qmldir_throws_if_qml_document_does_not_exists) { setFilesDontExists({qmlDirPathSourceId, qmlDocumentSourceId1}); setFilesAdded({directoryPathSourceId}); @@ -1899,7 +1867,7 @@ TEST_F(ProjectStorageUpdater, SynchronizeQmlDocumentsWithoutQmldirThrowsIfQmlDoc ASSERT_THROW(updater.update(directories, {}), QmlDesigner::CannotParseQmlDocumentFile); } -TEST_F(ProjectStorageUpdater, SynchronizeQmlDocumentsWithoutQmldirThrowsIfDirectoryDoesNotExists) +TEST_F(ProjectStorageUpdater, synchronize_qml_documents_without_qmldir_throws_if_directory_does_not_exists) { setFilesDontExists({qmlDirPathSourceId, directoryPathSourceId}); setProjectDatas(directoryPathSourceId, @@ -1929,7 +1897,7 @@ TEST_F(ProjectStorageUpdater, SynchronizeQmlDocumentsWithoutQmldirThrowsIfDirect updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, SynchronizeQmlDocumentsWithoutQmldirAddQmlDocument) +TEST_F(ProjectStorageUpdater, synchronize_qml_documents_without_qmldir_add_qml_document) { setFilesDontExists({qmlDirPathSourceId}); setFilesChanged({directoryPathSourceId}); @@ -1978,7 +1946,7 @@ TEST_F(ProjectStorageUpdater, SynchronizeQmlDocumentsWithoutQmldirAddQmlDocument updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, SynchronizeQmlDocumentsWithoutQmldirRemovesQmlDocument) +TEST_F(ProjectStorageUpdater, synchronize_qml_documents_without_qmldir_removes_qml_document) { setFilesDontExists({qmlDirPathSourceId}); setFilesChanged({directoryPathSourceId}); @@ -2017,7 +1985,7 @@ TEST_F(ProjectStorageUpdater, SynchronizeQmlDocumentsWithoutQmldirRemovesQmlDocu updater.update(directories, {}); } -TEST_F(ProjectStorageUpdater, WatcherUpdatesDirectories) +TEST_F(ProjectStorageUpdater, watcher_updates_directories) { QString qmldir{R"(module Example FirstType 1.0 First.qml @@ -2089,7 +2057,7 @@ TEST_F(ProjectStorageUpdater, WatcherUpdatesDirectories) updater.pathsWithIdsChanged({{directoryProjectChunkId, {directoryPathSourceId}}}); } -TEST_F(ProjectStorageUpdater, WatcherUpdatesRemovedDirectory) +TEST_F(ProjectStorageUpdater, watcher_updates_removed_directory) { setFilesRemoved({directoryPathSourceId, qmlDirPathSourceId, @@ -2123,7 +2091,7 @@ TEST_F(ProjectStorageUpdater, WatcherUpdatesRemovedDirectory) updater.pathsWithIdsChanged({{directoryProjectChunkId, {directoryPathSourceId}}}); } -TEST_F(ProjectStorageUpdater, WatcherWatchesDirectoriesAfterDirectoryChanges) +TEST_F(ProjectStorageUpdater, watcher_watches_directories_after_directory_changes) { QString qmldir{R"(module Example FirstType 1.0 First.qml @@ -2148,7 +2116,7 @@ TEST_F(ProjectStorageUpdater, WatcherWatchesDirectoriesAfterDirectoryChanges) updater.pathsWithIdsChanged({{directoryProjectChunkId, {directoryPathSourceId}}}); } -TEST_F(ProjectStorageUpdater, WatcherDontUpdatesDirectoriesForOtherProject) +TEST_F(ProjectStorageUpdater, watcher_dont_updates_directories_for_other_project) { QString qmldir{R"(module Example FirstType 1.0 First.qml @@ -2161,7 +2129,7 @@ TEST_F(ProjectStorageUpdater, WatcherDontUpdatesDirectoriesForOtherProject) updater.pathsWithIdsChanged({{otherDirectoryProjectChunkId, {directoryPathSourceId}}}); } -TEST_F(ProjectStorageUpdater, WatcherUpdatesDirectoriesAndQmldir) +TEST_F(ProjectStorageUpdater, watcher_updates_directories_and_qmldir) { QString qmldir{R"(module Example FirstType 1.0 First.qml @@ -2238,7 +2206,7 @@ TEST_F(ProjectStorageUpdater, WatcherUpdatesDirectoriesAndQmldir) {qmldirProjectChunkId, {qmlDirPathSourceId}}}); } -TEST_F(ProjectStorageUpdater, WatcherWatchesDirectoriesAfterQmldirChanges) +TEST_F(ProjectStorageUpdater, watcher_watches_directories_after_qmldir_changes) { QString qmldir{R"(module Example FirstType 1.0 First.qml @@ -2261,7 +2229,7 @@ TEST_F(ProjectStorageUpdater, WatcherWatchesDirectoriesAfterQmldirChanges) updater.pathsWithIdsChanged({{qmldirProjectChunkId, {qmlDirPathSourceId}}}); } -TEST_F(ProjectStorageUpdater, WatcherDontUpdatesQmldirForOtherProject) +TEST_F(ProjectStorageUpdater, watcher_dont_updates_qmldir_for_other_project) { QString qmldir{R"(module Example FirstType 1.0 First.qml @@ -2274,7 +2242,7 @@ TEST_F(ProjectStorageUpdater, WatcherDontUpdatesQmldirForOtherProject) updater.pathsWithIdsChanged({{otherQmldirProjectChunkId, {qmlDirPathSourceId}}}); } -TEST_F(ProjectStorageUpdater, WatcherUpdatesAddOnlyQmlDocumentInDirectory) +TEST_F(ProjectStorageUpdater, watcher_updates_add_only_qml_document_in_directory) { QString qmldir{R"(module Example FirstType 1.0 First.qml)"}; @@ -2330,7 +2298,7 @@ TEST_F(ProjectStorageUpdater, WatcherUpdatesAddOnlyQmlDocumentInDirectory) updater.pathsWithIdsChanged({{directoryProjectChunkId, {directoryPathSourceId}}}); } -TEST_F(ProjectStorageUpdater, WatcherUpdatesRemovesQmlDocument) +TEST_F(ProjectStorageUpdater, watcher_updates_removes_qml_document) { QString qmldir{R"(module Example FirstType 1.0 First.qml @@ -2393,7 +2361,7 @@ TEST_F(ProjectStorageUpdater, WatcherUpdatesRemovesQmlDocument) updater.pathsWithIdsChanged({{directoryProjectChunkId, {directoryPathSourceId}}}); } -TEST_F(ProjectStorageUpdater, WatcherUpdatesRemovesQmlDocumentInQmldirOnly) +TEST_F(ProjectStorageUpdater, watcher_updates_removes_qml_document_in_qmldir_only) { QString qmldir{R"(module Example FirstType 1.0 First.qml @@ -2448,7 +2416,7 @@ TEST_F(ProjectStorageUpdater, WatcherUpdatesRemovesQmlDocumentInQmldirOnly) updater.pathsWithIdsChanged({{qmldirProjectChunkId, {qmlDirPathSourceId}}}); } -TEST_F(ProjectStorageUpdater, WatcherUpdatesDirectoriesAddQmlDocumentToQmldir) +TEST_F(ProjectStorageUpdater, watcher_updates_directories_add_qml_document_to_qmldir) { QString qmldir{R"(module Example FirstType 1.0 First.qml @@ -2506,7 +2474,7 @@ TEST_F(ProjectStorageUpdater, WatcherUpdatesDirectoriesAddQmlDocumentToQmldir) updater.pathsWithIdsChanged({{qmldirProjectChunkId, {qmlDirPathSourceId}}}); } -TEST_F(ProjectStorageUpdater, WatcherUpdatesDirectoriesRemoveQmlDocumentFromQmldir) +TEST_F(ProjectStorageUpdater, watcher_updates_directories_remove_qml_document_from_qmldir) { QString qmldir{R"(module Example FirstType 1.0 First.qml @@ -2561,7 +2529,7 @@ TEST_F(ProjectStorageUpdater, WatcherUpdatesDirectoriesRemoveQmlDocumentFromQmld updater.pathsWithIdsChanged({{qmldirProjectChunkId, {qmlDirPathSourceId}}}); } -TEST_F(ProjectStorageUpdater, WatcherUpdatesDirectoriesDontUpdateQmlDocumentsIfUpToDate) +TEST_F(ProjectStorageUpdater, watcher_updates_directories_dont_update_qml_documents_if_up_to_date) { QString qmldir{R"(module Example FirstType 1.0 First.qml @@ -2631,7 +2599,7 @@ TEST_F(ProjectStorageUpdater, WatcherUpdatesDirectoriesDontUpdateQmlDocumentsIfU updater.pathsWithIdsChanged({{directoryProjectChunkId, {directoryPathSourceId}}}); } -TEST_F(ProjectStorageUpdater, WatcherUpdatesQmldirsDontUpdateQmlDocumentsIfUpToDate) +TEST_F(ProjectStorageUpdater, watcher_updates_qmldirs_dont_update_qml_documents_if_up_to_date) { QString qmldir{R"(module Example FirstType 1.0 First.qml @@ -2701,7 +2669,7 @@ TEST_F(ProjectStorageUpdater, WatcherUpdatesQmldirsDontUpdateQmlDocumentsIfUpToD updater.pathsWithIdsChanged({{qmldirProjectChunkId, {qmlDirPathSourceId}}}); } -TEST_F(ProjectStorageUpdater, WatcherUpdatesDirectoryButNotQmldir) +TEST_F(ProjectStorageUpdater, watcher_updates_directory_but_not_qmldir) { setProjectDatas( directoryPathSourceId, @@ -2752,7 +2720,7 @@ TEST_F(ProjectStorageUpdater, WatcherUpdatesDirectoryButNotQmldir) updater.pathsWithIdsChanged({{directoryProjectChunkId, {directoryPathSourceId}}}); } -TEST_F(ProjectStorageUpdater, WatcherUpdatesQmlDocuments) +TEST_F(ProjectStorageUpdater, watcher_updates_qml_documents) { EXPECT_CALL( projectStorageMock, @@ -2785,7 +2753,7 @@ TEST_F(ProjectStorageUpdater, WatcherUpdatesQmlDocuments) {{qmlDocumentProjectChunkId, {qmlDocumentSourceId1, qmlDocumentSourceId2}}}); } -TEST_F(ProjectStorageUpdater, WatcherUpdatesRemovedQmlDocuments) +TEST_F(ProjectStorageUpdater, watcher_updates_removed_qml_documents) { setFilesRemoved({qmlDocumentSourceId2}); @@ -2812,14 +2780,14 @@ TEST_F(ProjectStorageUpdater, WatcherUpdatesRemovedQmlDocuments) {{qmlDocumentProjectChunkId, {qmlDocumentSourceId1, qmlDocumentSourceId2}}}); } -TEST_F(ProjectStorageUpdater, WatcherDontWatchesDirectoriesAfterQmlDocumentChanges) +TEST_F(ProjectStorageUpdater, watcher_dont_watches_directories_after_qml_document_changes) { EXPECT_CALL(patchWatcherMock, updateContextIdPaths(_, _)).Times(0); updater.pathsWithIdsChanged({{qmlDocumentProjectChunkId, {qmlDirPathSourceId}}}); } -TEST_F(ProjectStorageUpdater, WatcherDontUpdatesQmlDocumentsForOtherProjects) +TEST_F(ProjectStorageUpdater, watcher_dont_updates_qml_documents_for_other_projects) { EXPECT_CALL(projectStorageMock, synchronize(PackageIsEmpty())); @@ -2827,7 +2795,7 @@ TEST_F(ProjectStorageUpdater, WatcherDontUpdatesQmlDocumentsForOtherProjects) {{otherQmlDocumentProjectChunkId, {qmlDocumentSourceId1, qmlDocumentSourceId2}}}); } -TEST_F(ProjectStorageUpdater, WatcherUpdatesQmltypes) +TEST_F(ProjectStorageUpdater, watcher_updates_qmltypes) { setProjectDatas( directoryPathSourceId, @@ -2855,7 +2823,7 @@ TEST_F(ProjectStorageUpdater, WatcherUpdatesQmltypes) {{qmltypesProjectChunkId, {qmltypesPathSourceId, qmltypes2PathSourceId}}}); } -TEST_F(ProjectStorageUpdater, WatcherUpdatesRemovedQmltypesWithoutUpdatedQmldir) +TEST_F(ProjectStorageUpdater, watcher_updates_removed_qmltypes_without_updated_qmldir) { setProjectDatas( directoryPathSourceId, @@ -2871,7 +2839,7 @@ TEST_F(ProjectStorageUpdater, WatcherUpdatesRemovedQmltypesWithoutUpdatedQmldir) {{qmltypesProjectChunkId, {qmltypesPathSourceId, qmltypes2PathSourceId}}}); } -TEST_F(ProjectStorageUpdater, WatcherUpdatesRemovedQmltypesWithUpdatedQmldir) +TEST_F(ProjectStorageUpdater, watcher_updates_removed_qmltypes_with_updated_qmldir) { setProjectDatas( directoryPathSourceId, @@ -2912,7 +2880,7 @@ TEST_F(ProjectStorageUpdater, WatcherUpdatesRemovedQmltypesWithUpdatedQmldir) updater.pathsWithIdsChanged({{qmldirProjectChunkId, {qmlDirPathSourceId}}}); } -TEST_F(ProjectStorageUpdater, WatcherDontWatchesDirectoriesAfterQmltypesChanges) +TEST_F(ProjectStorageUpdater, watcher_dont_watches_directories_after_qmltypes_changes) { setProjectDatas( directoryPathSourceId, @@ -2927,7 +2895,7 @@ TEST_F(ProjectStorageUpdater, WatcherDontWatchesDirectoriesAfterQmltypesChanges) {{qmltypesProjectChunkId, {qmltypesPathSourceId, qmltypes2PathSourceId}}}); } -TEST_F(ProjectStorageUpdater, WatcherDontUpdatesQmltypesForOtherProjects) +TEST_F(ProjectStorageUpdater, watcher_dont_updates_qmltypes_for_other_projects) { setProjectDatas( directoryPathSourceId, @@ -2942,7 +2910,7 @@ TEST_F(ProjectStorageUpdater, WatcherDontUpdatesQmltypesForOtherProjects) {{otherQmltypesProjectChunkId, {qmltypesPathSourceId, qmltypes2PathSourceId}}}); } -TEST_F(ProjectStorageUpdater, WatcherUpdatesDirectoriesAndButNotIncludedQmlDocument) +TEST_F(ProjectStorageUpdater, watcher_updates_directories_and_but_not_included_qml_document) { QString qmldir{R"(module Example FirstType 1.0 First.qml @@ -3016,7 +2984,7 @@ TEST_F(ProjectStorageUpdater, WatcherUpdatesDirectoriesAndButNotIncludedQmlDocum {qmlDocumentSourceId1, qmlDocumentSourceId2, qmlDocumentSourceId3}}}); } -TEST_F(ProjectStorageUpdater, WatcherUpdatesQmldirAndButNotIncludedQmlDocument) +TEST_F(ProjectStorageUpdater, watcher_updates_qmldir_and_but_not_included_qml_document) { QString qmldir{R"(module Example FirstType 1.0 First.qml @@ -3093,7 +3061,7 @@ TEST_F(ProjectStorageUpdater, WatcherUpdatesQmldirAndButNotIncludedQmlDocument) {qmlDocumentSourceId1, qmlDocumentSourceId2, qmlDocumentSourceId3}}}); } -TEST_F(ProjectStorageUpdater, WatcherUpdatesQmldirAndButNotIncludedQmltypes) +TEST_F(ProjectStorageUpdater, watcher_updates_qmldir_and_but_not_included_qmltypes) { setProjectDatas( directoryPathSourceId, @@ -3200,7 +3168,7 @@ TEST_F(ProjectStorageUpdater, WatcherUpdatesQmldirAndButNotIncludedQmltypes) {qmltypesProjectChunkId, {qmltypesPathSourceId, qmltypes2PathSourceId}}}); } -TEST_F(ProjectStorageUpdater, ErrorsForWatcherUpdatesAreHandled) +TEST_F(ProjectStorageUpdater, errors_for_watcher_updates_are_handled) { QString qmldir{R"(module Example FirstType 1.0 First.qml @@ -3213,7 +3181,7 @@ TEST_F(ProjectStorageUpdater, ErrorsForWatcherUpdatesAreHandled) ASSERT_NO_THROW(updater.pathsWithIdsChanged({{directoryProjectChunkId, {directoryPathSourceId}}})); } -TEST_F(ProjectStorageUpdater, InputIsReusedNextCallIfAnErrorHappens) +TEST_F(ProjectStorageUpdater, input_is_reused_next_call_if_an_error_happens) { QString qmldir{R"(module Example FirstType 1.0 First.qml @@ -3272,7 +3240,7 @@ TEST_F(ProjectStorageUpdater, InputIsReusedNextCallIfAnErrorHappens) {{qmlDocumentProjectChunkId, {qmlDocumentSourceId1, qmlDocumentSourceId2}}}); } -TEST_F(ProjectStorageUpdater, InputIsReusedNextCallIfAnErrorHappensAndQmltypesDuplicatesAreRemoved) +TEST_F(ProjectStorageUpdater, input_is_reused_next_call_if_an_error_happens_and_qmltypes_duplicates_are_removed) { QString qmldir{R"(module Example FirstType 1.0 First.qml @@ -3332,7 +3300,7 @@ TEST_F(ProjectStorageUpdater, InputIsReusedNextCallIfAnErrorHappensAndQmltypesDu {qmlDocumentProjectChunkId, {qmlDocumentSourceId1, qmlDocumentSourceId2}}}); } -TEST_F(ProjectStorageUpdater, InputIsReusedNextCallIfAnErrorHappensAndQmlDocumentDuplicatesAreRemoved) +TEST_F(ProjectStorageUpdater, input_is_reused_next_call_if_an_error_happens_and_qml_document_duplicates_are_removed) { QString qmldir{R"(module Example FirstType 1.0 First.qml @@ -3394,7 +3362,7 @@ TEST_F(ProjectStorageUpdater, InputIsReusedNextCallIfAnErrorHappensAndQmlDocumen {qmlDocumentProjectChunkId, {qmlDocumentSourceId1, qmlDocumentSourceId2}}}); } -TEST_F(ProjectStorageUpdater, InputIsClearedAfterSuccessfulUpdate) +TEST_F(ProjectStorageUpdater, input_is_cleared_after_successful_update) { QString qmldir{R"(module Example FirstType 1.0 First.qml diff --git a/tests/unit/unittest/qmldocumentparser-test.cpp b/tests/unit/tests/unittests/projectstorage/qmldocumentparser-test.cpp similarity index 95% rename from tests/unit/unittest/qmldocumentparser-test.cpp rename to tests/unit/tests/unittests/projectstorage/qmldocumentparser-test.cpp index a9103d06ea4..e823f5f7f44 100644 --- a/tests/unit/unittest/qmldocumentparser-test.cpp +++ b/tests/unit/tests/unittests/projectstorage/qmldocumentparser-test.cpp @@ -1,7 +1,7 @@ // Copyright (C) 2017 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" #include @@ -150,14 +150,14 @@ protected: ModuleId directoryModuleId{storage.moduleId(directoryPath)}; }; -TEST_F(QmlDocumentParser, Prototype) +TEST_F(QmlDocumentParser, prototype) { auto type = parser.parse("Example{}", imports, qmlFileSourceId, directoryPath); ASSERT_THAT(type, HasPrototype(Storage::ImportedType("Example"))); } -TEST_F(QmlDocumentParser, QualifiedPrototype) +TEST_F(QmlDocumentParser, qualified_prototype) { auto exampleModuleId = storage.moduleId("Example"); QString text = R"(import Example 2.1 as Example @@ -173,7 +173,7 @@ TEST_F(QmlDocumentParser, QualifiedPrototype) qmlFileSourceId}))); } -TEST_F(QmlDocumentParser, Properties) +TEST_F(QmlDocumentParser, properties) { auto type = parser.parse(R"(Example{ property int foo })", imports, qmlFileSourceId, directoryPath); @@ -184,7 +184,7 @@ TEST_F(QmlDocumentParser, Properties) QmlDesigner::Storage::PropertyDeclarationTraits::None))); } -TEST_F(QmlDocumentParser, QualifiedProperties) +TEST_F(QmlDocumentParser, qualified_properties) { auto exampleModuleId = storage.moduleId("Example"); @@ -204,7 +204,7 @@ TEST_F(QmlDocumentParser, QualifiedProperties) QmlDesigner::Storage::PropertyDeclarationTraits::None))); } -TEST_F(QmlDocumentParser, EnumerationInProperties) +TEST_F(QmlDocumentParser, enumeration_in_properties) { auto type = parser.parse(R"(import Example 2.1 as Example Item{ property Enumeration.Foo foo})", @@ -219,7 +219,7 @@ TEST_F(QmlDocumentParser, EnumerationInProperties) QmlDesigner::Storage::PropertyDeclarationTraits::None))); } -TEST_F(QmlDocumentParser, QualifiedEnumerationInProperties) +TEST_F(QmlDocumentParser, qualified_enumeration_in_properties) { auto exampleModuleId = storage.moduleId("Example"); @@ -239,7 +239,7 @@ TEST_F(QmlDocumentParser, QualifiedEnumerationInProperties) QmlDesigner::Storage::PropertyDeclarationTraits::None))); } -TEST_F(QmlDocumentParser, Imports) +TEST_F(QmlDocumentParser, imports) { ModuleId fooDirectoryModuleId = storage.moduleId("/path/foo"); ModuleId qmlModuleId = storage.moduleId("QML"); @@ -261,7 +261,7 @@ TEST_F(QmlDocumentParser, Imports) Storage::Import{qtQuickModuleId, QmlDesigner::Storage::Version{}, qmlFileSourceId})); } -TEST_F(QmlDocumentParser, ImportsWithVersion) +TEST_F(QmlDocumentParser, imports_with_version) { ModuleId fooDirectoryModuleId = storage.moduleId("/path/foo"); ModuleId qmlModuleId = storage.moduleId("QML"); @@ -283,7 +283,7 @@ TEST_F(QmlDocumentParser, ImportsWithVersion) Storage::Import{qtQuickModuleId, QmlDesigner::Storage::Version{2, 1}, qmlFileSourceId})); } -TEST_F(QmlDocumentParser, ImportsWithExplictDirectory) +TEST_F(QmlDocumentParser, imports_with_explict_directory) { ModuleId qmlModuleId = storage.moduleId("QML"); ModuleId qtQuickModuleId = storage.moduleId("QtQuick"); @@ -303,7 +303,7 @@ TEST_F(QmlDocumentParser, ImportsWithExplictDirectory) Storage::Import{qtQuickModuleId, QmlDesigner::Storage::Version{}, qmlFileSourceId})); } -TEST_F(QmlDocumentParser, Functions) +TEST_F(QmlDocumentParser, functions) { auto type = parser.parse( "Example{\n function someScript(x, y) {}\n function otherFunction() {}\n}", @@ -320,7 +320,7 @@ TEST_F(QmlDocumentParser, Functions) IsParameter("y", "")))))); } -TEST_F(QmlDocumentParser, Signals) +TEST_F(QmlDocumentParser, signals) { auto type = parser.parse("Example{\n signal someSignal(int x, real y)\n signal signal2()\n}", imports, @@ -336,7 +336,7 @@ TEST_F(QmlDocumentParser, Signals) Field(&Storage::SignalDeclaration::parameters, IsEmpty())))); } -TEST_F(QmlDocumentParser, Enumeration) +TEST_F(QmlDocumentParser, enumeration) { auto type = parser.parse("Example{\n enum Color{red, green, blue=10, white}\n enum " "State{On,Off}\n}", @@ -357,7 +357,7 @@ TEST_F(QmlDocumentParser, Enumeration) ElementsAre(IsEnumerator("On", 0), IsEnumerator("Off", 1)))))); } -TEST_F(QmlDocumentParser, DISABLED_DuplicateImportsAreRemoved) +TEST_F(QmlDocumentParser, DISABLED_duplicate_imports_are_removed) { ModuleId fooDirectoryModuleId = storage.moduleId("/path/foo"); ModuleId qmlModuleId = storage.moduleId("QML"); @@ -386,7 +386,7 @@ TEST_F(QmlDocumentParser, DISABLED_DuplicateImportsAreRemoved) Storage::Import{qtQuickModuleId, QmlDesigner::Storage::Version{}, qmlFileSourceId})); } -TEST_F(QmlDocumentParser, AliasItemProperties) +TEST_F(QmlDocumentParser, alias_item_properties) { auto type = parser.parse(R"(Example{ property alias delegate: foo @@ -405,7 +405,7 @@ TEST_F(QmlDocumentParser, AliasItemProperties) QmlDesigner::Storage::PropertyDeclarationTraits::None))); } -TEST_F(QmlDocumentParser, AliasProperties) +TEST_F(QmlDocumentParser, alias_properties) { auto type = parser.parse(R"(Example{ property alias text: foo.text2 @@ -425,7 +425,7 @@ TEST_F(QmlDocumentParser, AliasProperties) "text2"))); } -TEST_F(QmlDocumentParser, IndirectAliasProperties) +TEST_F(QmlDocumentParser, indirect_alias_properties) { auto type = parser.parse(R"(Example{ property alias textSize: foo.text.size @@ -446,7 +446,7 @@ TEST_F(QmlDocumentParser, IndirectAliasProperties) "size"))); } -TEST_F(QmlDocumentParser, InvalidAliasPropertiesAreSkipped) +TEST_F(QmlDocumentParser, invalid_alias_properties_are_skipped) { auto type = parser.parse(R"(Example{ property alias textSize: foo2.text.size @@ -461,7 +461,7 @@ TEST_F(QmlDocumentParser, InvalidAliasPropertiesAreSkipped) ASSERT_THAT(type.propertyDeclarations, IsEmpty()); } -TEST_F(QmlDocumentParser, ListProperty) +TEST_F(QmlDocumentParser, list_property) { auto type = parser.parse(R"(Item{ property list foos @@ -477,7 +477,7 @@ TEST_F(QmlDocumentParser, ListProperty) QmlDesigner::Storage::PropertyDeclarationTraits::IsList))); } -TEST_F(QmlDocumentParser, AliasOnListProperty) +TEST_F(QmlDocumentParser, alias_on_list_property) { auto type = parser.parse(R"(Item{ property alias foos: foo.foos @@ -498,7 +498,7 @@ TEST_F(QmlDocumentParser, AliasOnListProperty) QmlDesigner::Storage::PropertyDeclarationTraits::IsList))); } -TEST_F(QmlDocumentParser, QualifiedListProperty) +TEST_F(QmlDocumentParser, qualified_list_property) { auto exampleModuleId = storage.moduleId("Example"); auto type = parser.parse(R"(import Example 2.1 as Example diff --git a/tests/unit/unittest/qmltypesparser-test.cpp b/tests/unit/tests/unittests/projectstorage/qmltypesparser-test.cpp similarity index 97% rename from tests/unit/unittest/qmltypesparser-test.cpp rename to tests/unit/tests/unittests/projectstorage/qmltypesparser-test.cpp index 3fbbaa6b8cc..02b4514841d 100644 --- a/tests/unit/unittest/qmltypesparser-test.cpp +++ b/tests/unit/tests/unittests/projectstorage/qmltypesparser-test.cpp @@ -1,7 +1,7 @@ // Copyright (C) 2017 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" #include @@ -162,7 +162,7 @@ protected: ModuleId directoryModuleId{storage.moduleId("path/to/")}; }; -TEST_F(QmlTypesParser, Imports) +TEST_F(QmlTypesParser, imports) { QString source{R"(import QtQuick.tooling 1.2 Module{ @@ -189,7 +189,7 @@ TEST_F(QmlTypesParser, Imports) qmltypesFileSourceId))); } -TEST_F(QmlTypesParser, Types) +TEST_F(QmlTypesParser, types) { QString source{R"(import QtQuick.tooling 1.2 Module{ @@ -211,7 +211,7 @@ TEST_F(QmlTypesParser, Types) qmltypesFileSourceId))); } -TEST_F(QmlTypesParser, Prototype) +TEST_F(QmlTypesParser, prototype) { QString source{R"(import QtQuick.tooling 1.2 Module{ @@ -234,7 +234,7 @@ TEST_F(QmlTypesParser, Prototype) qmltypesFileSourceId))); } -TEST_F(QmlTypesParser, Extension) +TEST_F(QmlTypesParser, extension) { QString source{R"(import QtQuick.tooling 1.2 Module{ @@ -257,7 +257,7 @@ TEST_F(QmlTypesParser, Extension) qmltypesFileSourceId))); } -TEST_F(QmlTypesParser, ExportedTypes) +TEST_F(QmlTypesParser, exported_types) { QString source{R"(import QtQuick.tooling 1.2 Module{ @@ -279,7 +279,7 @@ TEST_F(QmlTypesParser, ExportedTypes) IsExportedType(qtQmlNativeModuleId, "QObject", QmlDesigner::Storage::Version{}))))); } -TEST_F(QmlTypesParser, Properties) +TEST_F(QmlTypesParser, properties) { QString source{R"(import QtQuick.tooling 1.2 Module{ @@ -313,7 +313,7 @@ TEST_F(QmlTypesParser, Properties) | QmlDesigner::Storage::PropertyDeclarationTraits::IsPointer))))); } -TEST_F(QmlTypesParser, PropertiesWithQualifiedTypes) +TEST_F(QmlTypesParser, properties_with_qualified_types) { QString source{R"(import QtQuick.tooling 1.2 Module{ @@ -343,7 +343,7 @@ TEST_F(QmlTypesParser, PropertiesWithQualifiedTypes) QmlDesigner::Storage::PropertyDeclarationTraits::None))))); } -TEST_F(QmlTypesParser, PropertiesWithoutType) +TEST_F(QmlTypesParser, properties_without_type) { QString source{R"(import QtQuick.tooling 1.2 Module{ @@ -362,7 +362,7 @@ TEST_F(QmlTypesParser, PropertiesWithoutType) QmlDesigner::Storage::PropertyDeclarationTraits::IsPointer))))); } -TEST_F(QmlTypesParser, Functions) +TEST_F(QmlTypesParser, functions) { QString source{R"(import QtQuick.tooling 1.2 Module{ @@ -404,7 +404,7 @@ TEST_F(QmlTypesParser, Functions) Field(&Storage::FunctionDeclaration::parameters, IsEmpty())))))); } -TEST_F(QmlTypesParser, SkipJavaScriptFunctions) +TEST_F(QmlTypesParser, skip_java_script_functions) { QString source{R"(import QtQuick.tooling 1.2 Module{ @@ -420,7 +420,7 @@ TEST_F(QmlTypesParser, SkipJavaScriptFunctions) ASSERT_THAT(types, ElementsAre(Field(&Storage::Type::functionDeclarations, IsEmpty()))); } -TEST_F(QmlTypesParser, FunctionsWithQualifiedTypes) +TEST_F(QmlTypesParser, functions_with_qualified_types) { QString source{R"(import QtQuick.tooling 1.2 Module{ @@ -448,7 +448,7 @@ TEST_F(QmlTypesParser, FunctionsWithQualifiedTypes) IsParameter("values2", "Qt::Vector")))))))); } -TEST_F(QmlTypesParser, Signals) +TEST_F(QmlTypesParser, signals) { QString source{R"(import QtQuick.tooling 1.2 Module{ @@ -487,7 +487,7 @@ TEST_F(QmlTypesParser, Signals) IsParameter("args", "QQmlV4Function")))))))); } -TEST_F(QmlTypesParser, SignalsWithQualifiedTypes) +TEST_F(QmlTypesParser, signals_with_qualified_types) { QString source{R"(import QtQuick.tooling 1.2 Module{ @@ -515,7 +515,7 @@ TEST_F(QmlTypesParser, SignalsWithQualifiedTypes) IsParameter("values2", "Qt::Vector")))))))); } -TEST_F(QmlTypesParser, Enumerations) +TEST_F(QmlTypesParser, enumerations) { QString source{R"(import QtQuick.tooling 1.2 Module{ @@ -553,7 +553,7 @@ TEST_F(QmlTypesParser, Enumerations) IsEnumerator("BottomToTop")))))))); } -TEST_F(QmlTypesParser, EnumerationIsExportedAsType) +TEST_F(QmlTypesParser, enumeration_is_exported_as_type) { QString source{R"(import QtQuick.tooling 1.2 Module{ @@ -600,7 +600,7 @@ TEST_F(QmlTypesParser, EnumerationIsExportedAsType) _)); } -TEST_F(QmlTypesParser, EnumerationIsExportedAsTypeWithAlias) +TEST_F(QmlTypesParser, enumeration_is_exported_as_type_with_alias) { QString source{R"(import QtQuick.tooling 1.2 Module{ @@ -638,7 +638,7 @@ TEST_F(QmlTypesParser, EnumerationIsExportedAsTypeWithAlias) _)); } -TEST_F(QmlTypesParser, EnumerationIsExportedAsTypeWithAliasToo) +TEST_F(QmlTypesParser, enumeration_is_exported_as_type_with_alias_too) { QString source{R"(import QtQuick.tooling 1.2 Module{ @@ -685,7 +685,7 @@ TEST_F(QmlTypesParser, EnumerationIsExportedAsTypeWithAliasToo) _)); } -TEST_F(QmlTypesParser, EnumerationIsReferencedByQualifiedName) +TEST_F(QmlTypesParser, enumeration_is_referenced_by_qualified_name) { QString source{R"(import QtQuick.tooling 1.2 Module{ @@ -712,7 +712,7 @@ TEST_F(QmlTypesParser, EnumerationIsReferencedByQualifiedName) QmlDesigner::Storage::PropertyDeclarationTraits::None))))); } -TEST_F(QmlTypesParser, AliasEnumerationIsReferencedByQualifiedName) +TEST_F(QmlTypesParser, alias_enumeration_is_referenced_by_qualified_name) { QString source{R"(import QtQuick.tooling 1.2 Module{ diff --git a/tests/unit/unittest/sourcepath-test.cpp b/tests/unit/tests/unittests/projectstorage/sourcepath-test.cpp similarity index 81% rename from tests/unit/unittest/sourcepath-test.cpp rename to tests/unit/tests/unittests/projectstorage/sourcepath-test.cpp index bea5404d7a3..ffa4aa84d14 100644 --- a/tests/unit/unittest/sourcepath-test.cpp +++ b/tests/unit/tests/unittests/projectstorage/sourcepath-test.cpp @@ -1,13 +1,13 @@ // Copyright (C) 2017 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" #include namespace { -TEST(SourcePath, CreateFromPathString) +TEST(SourcePath, create_from_path_string) { QmlDesigner::SourcePath sourcePath{Utils::PathString{"/file/pathOne"}}; @@ -15,7 +15,7 @@ TEST(SourcePath, CreateFromPathString) ASSERT_THAT(sourcePath.name(), "pathOne"); } -TEST(FilePath, CreateFromDirectoryAndFileName) +TEST(FilePath, create_from_directory_and_file_name) { QmlDesigner::SourcePath sourcePath{Utils::PathString{"/file"}, Utils::PathString{"pathOne"}}; @@ -24,7 +24,7 @@ TEST(FilePath, CreateFromDirectoryAndFileName) ASSERT_THAT(sourcePath.path(), "/file/pathOne"); } -TEST(FilePath, CreateFromCString) +TEST(FilePath, create_from_c_string) { QmlDesigner::SourcePath sourcePath{"/file/pathOne"}; @@ -32,7 +32,7 @@ TEST(FilePath, CreateFromCString) ASSERT_THAT(sourcePath.name(), "pathOne"); } -TEST(FilePath, CreateFromFilePathView) +TEST(FilePath, create_from_file_path_view) { QmlDesigner::SourcePath sourcePath{QmlDesigner::SourcePathView{"/file/pathOne"}}; @@ -40,7 +40,7 @@ TEST(FilePath, CreateFromFilePathView) ASSERT_THAT(sourcePath.name(), "pathOne"); } -TEST(FilePath, CreateFromQString) +TEST(FilePath, create_from_q_string) { QmlDesigner::SourcePath sourcePath{QString{"/file/pathOne"}}; @@ -48,7 +48,7 @@ TEST(FilePath, CreateFromQString) ASSERT_THAT(sourcePath.name(), "pathOne"); } -TEST(FilePath, DefaultFilePath) +TEST(FilePath, default_file_path) { QmlDesigner::SourcePath sourcePath; @@ -56,7 +56,7 @@ TEST(FilePath, DefaultFilePath) ASSERT_THAT(sourcePath.name(), ""); } -TEST(FilePath, EmptyFilePath) +TEST(FilePath, empty_file_path) { QmlDesigner::SourcePath sourcePath(""); diff --git a/tests/unit/unittest/sourcepathcache-test.cpp b/tests/unit/tests/unittests/projectstorage/sourcepathcache-test.cpp similarity index 76% rename from tests/unit/unittest/sourcepathcache-test.cpp rename to tests/unit/tests/unittests/projectstorage/sourcepathcache-test.cpp index ffcf08299e9..fdc757c2c05 100644 --- a/tests/unit/unittest/sourcepathcache-test.cpp +++ b/tests/unit/tests/unittests/projectstorage/sourcepathcache-test.cpp @@ -1,10 +1,10 @@ // Copyright (C) 2021 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" -#include "projectstoragemock.h" -#include "sqlitedatabasemock.h" +#include "../mocks/projectstoragemock.h" +#include "../mocks/sqlitedatabasemock.h" #include @@ -61,28 +61,28 @@ protected: Cache cacheNotFilled{storageMockFilled}; }; -TEST_F(SourcePathCache, SourceIdWithOutAnyEntryCallSourceContextId) +TEST_F(SourcePathCache, source_id_with_out_any_entry_call_source_context_id) { EXPECT_CALL(storageMock, fetchSourceContextId(Eq("/path/to"))); cache.sourceId(SourcePathView("/path/to/file.cpp")); } -TEST_F(SourcePathCache, SourceIdWithOutAnyEntryCalls) +TEST_F(SourcePathCache, source_id_with_out_any_entry_calls) { EXPECT_CALL(storageMock, fetchSourceId(SourceContextId::create(5), Eq("file.cpp"))); cache.sourceId(SourcePathView("/path/to/file.cpp")); } -TEST_F(SourcePathCache, SourceIdOfSourceIdWithOutAnyEntry) +TEST_F(SourcePathCache, source_id_of_source_id_with_out_any_entry) { auto sourceId = cache.sourceId(SourcePathView("/path/to/file.cpp")); ASSERT_THAT(sourceId, SourceId::create(42)); } -TEST_F(SourcePathCache, SourceIdWithSourceContextIdAndSourceName) +TEST_F(SourcePathCache, source_id_with_source_context_id_and_source_name) { auto sourceContextId = cache.sourceContextId("/path/to"_sv); @@ -91,7 +91,7 @@ TEST_F(SourcePathCache, SourceIdWithSourceContextIdAndSourceName) ASSERT_THAT(sourceId, SourceId::create(42)); } -TEST_F(SourcePathCache, IfEntryExistsDontCallInStrorage) +TEST_F(SourcePathCache, if_entry_exists_dont_call_in_strorage) { cache.sourceId(SourcePathView("/path/to/file.cpp")); @@ -101,7 +101,7 @@ TEST_F(SourcePathCache, IfEntryExistsDontCallInStrorage) cache.sourceId(SourcePathView("/path/to/file.cpp")); } -TEST_F(SourcePathCache, IfDirectoryEntryExistsDontCallFetchSourceContextIdButStillCallFetchSourceId) +TEST_F(SourcePathCache, if_directory_entry_exists_dont_call_fetch_source_context_id_but_still_call_fetch_source_id) { cache.sourceId(SourcePathView("/path/to/file2.cpp")); @@ -111,7 +111,7 @@ TEST_F(SourcePathCache, IfDirectoryEntryExistsDontCallFetchSourceContextIdButSti cache.sourceId(SourcePathView("/path/to/file.cpp")); } -TEST_F(SourcePathCache, GetSourceIdWithCachedValue) +TEST_F(SourcePathCache, get_source_id_with_cached_value) { cache.sourceId(SourcePathView("/path/to/file.cpp")); @@ -120,7 +120,7 @@ TEST_F(SourcePathCache, GetSourceIdWithCachedValue) ASSERT_THAT(sourceId, SourceId::create(42)); } -TEST_F(SourcePathCache, GetSourceIdWithSourceContextIdCached) +TEST_F(SourcePathCache, get_source_id_with_source_context_id_cached) { cache.sourceId(SourcePathView("/path/to/file.cpp")); @@ -129,14 +129,14 @@ TEST_F(SourcePathCache, GetSourceIdWithSourceContextIdCached) ASSERT_THAT(sourceId, SourceId::create(63)); } -TEST_F(SourcePathCache, ThrowForGettingAFilePathWithAnInvalidId) +TEST_F(SourcePathCache, throw_for_getting_a_file_path_with_an_invalid_id) { SourceId sourceId; ASSERT_THROW(cache.sourcePath(sourceId), QmlDesigner::NoSourcePathForInvalidSourceId); } -TEST_F(SourcePathCache, GetAFilePath) +TEST_F(SourcePathCache, get_a_file_path) { SourceId sourceId = cache.sourceId(SourcePathView("/path/to/file.cpp")); @@ -145,7 +145,7 @@ TEST_F(SourcePathCache, GetAFilePath) ASSERT_THAT(sourcePath, Eq(SourcePathView{"/path/to/file.cpp"})); } -TEST_F(SourcePathCache, GetAFilePathWithCachedSourceId) +TEST_F(SourcePathCache, get_a_file_path_with_cached_source_id) { SourceId sourceId{SourceId::create(42)}; @@ -154,7 +154,7 @@ TEST_F(SourcePathCache, GetAFilePathWithCachedSourceId) ASSERT_THAT(sourcePath, Eq(SourcePathView{"/path/to/file.cpp"})); } -TEST_F(SourcePathCache, FileNamesAreUniqueForEveryDirectory) +TEST_F(SourcePathCache, file_names_are_unique_for_every_directory) { SourceId sourceId = cache.sourceId(SourcePathView("/path/to/file.cpp")); @@ -163,7 +163,7 @@ TEST_F(SourcePathCache, FileNamesAreUniqueForEveryDirectory) ASSERT_THAT(sourcePath2Id, Ne(sourceId)); } -TEST_F(SourcePathCache, DuplicateFilePathsAreEqual) +TEST_F(SourcePathCache, duplicate_file_paths_are_equal) { SourceId sourcePath1Id = cache.sourceId(SourcePathView("/path/to/file.cpp")); @@ -172,14 +172,14 @@ TEST_F(SourcePathCache, DuplicateFilePathsAreEqual) ASSERT_THAT(sourcePath2Id, Eq(sourcePath1Id)); } -TEST_F(SourcePathCache, SourceContextIdCallsFetchSourceContextId) +TEST_F(SourcePathCache, source_context_id_calls_fetch_source_context_id) { EXPECT_CALL(storageMock, fetchSourceContextId(Eq("/path/to"))); cache.sourceContextId(Utils::SmallString("/path/to")); } -TEST_F(SourcePathCache, SecondSourceContextIdCallsNotFetchSourceContextId) +TEST_F(SourcePathCache, second_source_context_id_calls_not_fetch_source_context_id) { cache.sourceContextId(Utils::SmallString("/path/to")); @@ -188,21 +188,21 @@ TEST_F(SourcePathCache, SecondSourceContextIdCallsNotFetchSourceContextId) cache.sourceContextId(Utils::SmallString("/path/to")); } -TEST_F(SourcePathCache, SourceContextIdWithTrailingSlash) +TEST_F(SourcePathCache, source_context_id_with_trailing_slash) { EXPECT_CALL(storageMock, fetchSourceContextId(Eq("/path/to"))); cache.sourceContextId(Utils::SmallString("/path/to/")); } -TEST_F(SourcePathCache, SourceContextId) +TEST_F(SourcePathCache, source_context_id) { auto id = cache.sourceContextId(Utils::SmallString("/path/to")); ASSERT_THAT(id, Eq(SourceContextId::create(5))); } -TEST_F(SourcePathCache, SourceContextIdIsAlreadyInCache) +TEST_F(SourcePathCache, source_context_id_is_already_in_cache) { auto firstId = cache.sourceContextId(Utils::SmallString("/path/to")); @@ -211,7 +211,7 @@ TEST_F(SourcePathCache, SourceContextIdIsAlreadyInCache) ASSERT_THAT(secondId, firstId); } -TEST_F(SourcePathCache, SourceContextIdIsAlreadyInCacheWithTrailingSlash) +TEST_F(SourcePathCache, source_context_id_is_already_in_cache_with_trailing_slash) { auto firstId = cache.sourceContextId(Utils::SmallString("/path/to/")); @@ -220,7 +220,7 @@ TEST_F(SourcePathCache, SourceContextIdIsAlreadyInCacheWithTrailingSlash) ASSERT_THAT(secondId, firstId); } -TEST_F(SourcePathCache, SourceContextIdIsAlreadyInCacheWithAndWithoutTrailingSlash) +TEST_F(SourcePathCache, source_context_id_is_already_in_cache_with_and_without_trailing_slash) { auto firstId = cache.sourceContextId(Utils::SmallString("/path/to/")); @@ -229,7 +229,7 @@ TEST_F(SourcePathCache, SourceContextIdIsAlreadyInCacheWithAndWithoutTrailingSla ASSERT_THAT(secondId, firstId); } -TEST_F(SourcePathCache, SourceContextIdIsAlreadyInCacheWithoutAndWithTrailingSlash) +TEST_F(SourcePathCache, source_context_id_is_already_in_cache_without_and_with_trailing_slash) { auto firstId = cache.sourceContextId(Utils::SmallString("/path/to")); @@ -238,7 +238,7 @@ TEST_F(SourcePathCache, SourceContextIdIsAlreadyInCacheWithoutAndWithTrailingSla ASSERT_THAT(secondId, firstId); } -TEST_F(SourcePathCache, ThrowForGettingADirectoryPathWithAnInvalidId) +TEST_F(SourcePathCache, throw_for_getting_a_directory_path_with_an_invalid_id) { SourceContextId sourceContextId; @@ -246,7 +246,7 @@ TEST_F(SourcePathCache, ThrowForGettingADirectoryPathWithAnInvalidId) QmlDesigner::NoSourceContextPathForInvalidSourceContextId); } -TEST_F(SourcePathCache, GetADirectoryPath) +TEST_F(SourcePathCache, get_a_directory_path) { SourceContextId sourceContextId{SourceContextId::create(5)}; @@ -255,7 +255,7 @@ TEST_F(SourcePathCache, GetADirectoryPath) ASSERT_THAT(sourceContextPath, Eq(Utils::SmallStringView{"/path/to"})); } -TEST_F(SourcePathCache, GetADirectoryPathWithCachedSourceContextId) +TEST_F(SourcePathCache, get_a_directory_path_with_cached_source_context_id) { SourceContextId sourceContextId{SourceContextId::create(5)}; cache.sourceContextPath(sourceContextId); @@ -265,14 +265,14 @@ TEST_F(SourcePathCache, GetADirectoryPathWithCachedSourceContextId) ASSERT_THAT(sourceContextPath, Eq(Utils::SmallStringView{"/path/to"})); } -TEST_F(SourcePathCache, DirectoryPathCallsFetchDirectoryPath) +TEST_F(SourcePathCache, directory_path_calls_fetch_directory_path) { EXPECT_CALL(storageMock, fetchSourceContextPath(Eq(SourceContextId::create(5)))); cache.sourceContextPath(SourceContextId::create(5)); } -TEST_F(SourcePathCache, SecondDirectoryPathCallsNotFetchDirectoryPath) +TEST_F(SourcePathCache, second_directory_path_calls_not_fetch_directory_path) { cache.sourceContextPath(SourceContextId::create(5)); @@ -281,21 +281,21 @@ TEST_F(SourcePathCache, SecondDirectoryPathCallsNotFetchDirectoryPath) cache.sourceContextPath(SourceContextId::create(5)); } -TEST_F(SourcePathCache, ThrowForGettingASourceContextIdWithAnInvalidSourceId) +TEST_F(SourcePathCache, throw_for_getting_a_source_context_id_with_an_invalid_source_id) { SourceId sourceId; ASSERT_THROW(cache.sourceContextId(sourceId), QmlDesigner::NoSourcePathForInvalidSourceId); } -TEST_F(SourcePathCache, FetchSourceContextIdBySourceId) +TEST_F(SourcePathCache, fetch_source_context_id_by_source_id) { auto sourceContextId = cache.sourceContextId(SourceId::create(42)); ASSERT_THAT(sourceContextId, Eq(SourceContextId::create(5))); } -TEST_F(SourcePathCache, FetchSourceContextIdBySourceIdCached) +TEST_F(SourcePathCache, fetch_source_context_id_by_source_id_cached) { cache.sourceContextId(SourceId::create(42)); @@ -304,7 +304,7 @@ TEST_F(SourcePathCache, FetchSourceContextIdBySourceIdCached) ASSERT_THAT(sourceContextId, Eq(SourceContextId::create(5))); } -TEST_F(SourcePathCache, FetchFilePathAfterFetchingSourceContextIdBySourceId) +TEST_F(SourcePathCache, fetch_file_path_after_fetching_source_context_id_by_source_id) { cache.sourceContextId(SourceId::create(42)); @@ -313,7 +313,7 @@ TEST_F(SourcePathCache, FetchFilePathAfterFetchingSourceContextIdBySourceId) ASSERT_THAT(sourcePath, Eq("/path/to/file.cpp")); } -TEST_F(SourcePathCache, FetchSourceContextIdAfterFetchingFilePathBySourceId) +TEST_F(SourcePathCache, fetch_source_context_id_after_fetching_file_path_by_source_id) { cache.sourcePath(SourceId::create(42)); @@ -322,7 +322,7 @@ TEST_F(SourcePathCache, FetchSourceContextIdAfterFetchingFilePathBySourceId) ASSERT_THAT(sourceContextId, Eq(SourceContextId::create(5))); } -TEST_F(SourcePathCache, FetchAllSourceContextsAndSourcesAtCreation) +TEST_F(SourcePathCache, fetch_all_source_contexts_and_sources_at_creation) { EXPECT_CALL(storageMock, fetchAllSourceContexts()); EXPECT_CALL(storageMock, fetchAllSources()); @@ -330,7 +330,7 @@ TEST_F(SourcePathCache, FetchAllSourceContextsAndSourcesAtCreation) Cache cache{storageMock}; } -TEST_F(SourcePathCache, GetFileIdInFilledCache) +TEST_F(SourcePathCache, get_file_id_in_filled_cache) { Cache cacheFilled{storageMockFilled}; @@ -339,7 +339,7 @@ TEST_F(SourcePathCache, GetFileIdInFilledCache) ASSERT_THAT(id, Eq(SourceId::create(72))); } -TEST_F(SourcePathCache, GetSourceContextIdInFilledCache) +TEST_F(SourcePathCache, get_source_context_id_in_filled_cache) { Cache cacheFilled{storageMockFilled}; @@ -348,7 +348,7 @@ TEST_F(SourcePathCache, GetSourceContextIdInFilledCache) ASSERT_THAT(id, Eq(SourceContextId::create(5))); } -TEST_F(SourcePathCache, GetDirectoryPathInFilledCache) +TEST_F(SourcePathCache, get_directory_path_in_filled_cache) { Cache cacheFilled{storageMockFilled}; @@ -357,7 +357,7 @@ TEST_F(SourcePathCache, GetDirectoryPathInFilledCache) ASSERT_THAT(path, Eq("/path/to")); } -TEST_F(SourcePathCache, GetFilePathInFilledCache) +TEST_F(SourcePathCache, get_file_path_in_filled_cache) { Cache cacheFilled{storageMockFilled}; @@ -366,7 +366,7 @@ TEST_F(SourcePathCache, GetFilePathInFilledCache) ASSERT_THAT(path, Eq("/path/to/file.cpp")); } -TEST_F(SourcePathCache, GetFileIdInAfterPopulateIfEmpty) +TEST_F(SourcePathCache, get_file_id_in_after_populate_if_empty) { cacheNotFilled.populateIfEmpty(); @@ -375,7 +375,7 @@ TEST_F(SourcePathCache, GetFileIdInAfterPopulateIfEmpty) ASSERT_THAT(id, Eq(SourceId::create(72))); } -TEST_F(SourcePathCache, DontPopulateIfNotEmpty) +TEST_F(SourcePathCache, dont_populate_if_not_empty) { cacheNotFilled.sourceId("/path/to/file.cpp"); @@ -385,7 +385,7 @@ TEST_F(SourcePathCache, DontPopulateIfNotEmpty) cacheNotFilled.populateIfEmpty(); } -TEST_F(SourcePathCache, GetSourceContextIdAfterPopulateIfEmpty) +TEST_F(SourcePathCache, get_source_context_id_after_populate_if_empty) { cacheNotFilled.populateIfEmpty(); @@ -394,7 +394,7 @@ TEST_F(SourcePathCache, GetSourceContextIdAfterPopulateIfEmpty) ASSERT_THAT(id, Eq(SourceContextId::create(5))); } -TEST_F(SourcePathCache, GetDirectoryPathAfterPopulateIfEmpty) +TEST_F(SourcePathCache, get_directory_path_after_populate_if_empty) { cacheNotFilled.populateIfEmpty(); @@ -403,7 +403,7 @@ TEST_F(SourcePathCache, GetDirectoryPathAfterPopulateIfEmpty) ASSERT_THAT(path, Eq("/path/to")); } -TEST_F(SourcePathCache, GetFilePathAfterPopulateIfEmptye) +TEST_F(SourcePathCache, get_file_path_after_populate_if_empty) { cacheNotFilled.populateIfEmpty(); @@ -412,21 +412,21 @@ TEST_F(SourcePathCache, GetFilePathAfterPopulateIfEmptye) ASSERT_THAT(path, Eq("/path/to/file.cpp")); } -TEST_F(SourcePathCache, SourceContextAndSourceIdWithOutAnyEntryCallSourceContextId) +TEST_F(SourcePathCache, source_context_and_source_id_with_out_any_entry_call_source_context_id) { EXPECT_CALL(storageMock, fetchSourceContextId(Eq("/path/to"))); cache.sourceContextAndSourceId(SourcePathView("/path/to/file.cpp")); } -TEST_F(SourcePathCache, SourceContextAndSourceIdWithOutAnyEntryCalls) +TEST_F(SourcePathCache, source_context_and_source_id_with_out_any_entry_calls) { EXPECT_CALL(storageMock, fetchSourceId(SourceContextId::create(5), Eq("file.cpp"))); cache.sourceContextAndSourceId(SourcePathView("/path/to/file.cpp")); } -TEST_F(SourcePathCache, SourceContextAndSourceIdOfSourceIdWithOutAnyEntry) +TEST_F(SourcePathCache, source_context_and_source_id_of_source_id_with_out_any_entry) { auto sourceContextAndSourceId = cache.sourceContextAndSourceId( SourcePathView("/path/to/file.cpp")); @@ -434,7 +434,7 @@ TEST_F(SourcePathCache, SourceContextAndSourceIdOfSourceIdWithOutAnyEntry) ASSERT_THAT(sourceContextAndSourceId, Pair(SourceContextId::create(5), SourceId::create(42))); } -TEST_F(SourcePathCache, SourceContextAndSourceIdIfEntryExistsDontCallInStrorage) +TEST_F(SourcePathCache, source_context_and_source_id_if_entry_exists_dont_call_in_strorage) { cache.sourceContextAndSourceId(SourcePathView("/path/to/file.cpp")); @@ -445,7 +445,7 @@ TEST_F(SourcePathCache, SourceContextAndSourceIdIfEntryExistsDontCallInStrorage) } TEST_F(SourcePathCache, - SourceContextAndSourceIdIfDirectoryEntryExistsDontCallFetchSourceContextIdButStillCallFetchSourceId) + source_context_and_source_id_if_directory_entry_exists_dont_call_fetch_source_context_id_but_still_call_fetch_source_id) { cache.sourceContextAndSourceId(SourcePathView("/path/to/file2.cpp")); @@ -455,7 +455,7 @@ TEST_F(SourcePathCache, cache.sourceContextAndSourceId(SourcePathView("/path/to/file.cpp")); } -TEST_F(SourcePathCache, SourceContextAndSourceIdGetSourceIdWithCachedValue) +TEST_F(SourcePathCache, source_context_and_source_id_get_source_id_with_cached_value) { cache.sourceContextAndSourceId(SourcePathView("/path/to/file.cpp")); @@ -464,7 +464,7 @@ TEST_F(SourcePathCache, SourceContextAndSourceIdGetSourceIdWithCachedValue) ASSERT_THAT(sourceId, Pair(SourceContextId::create(5), SourceId::create(42))); } -TEST_F(SourcePathCache, GetSourceContextAndSourceIdWithSourceContextIdCached) +TEST_F(SourcePathCache, get_source_context_and_source_id_with_source_context_id_cached) { cache.sourceContextAndSourceId(SourcePathView("/path/to/file.cpp")); @@ -474,7 +474,7 @@ TEST_F(SourcePathCache, GetSourceContextAndSourceIdWithSourceContextIdCached) ASSERT_THAT(sourceContextAndSourceId, Pair(SourceContextId::create(5), SourceId::create(63))); } -TEST_F(SourcePathCache, GetSourceContextAndSourceIdFileNamesAreUniqueForEveryDirectory) +TEST_F(SourcePathCache, get_source_context_and_source_id_file_names_are_unique_for_every_directory) { auto sourceContextAndSourceId = cache.sourceContextAndSourceId( SourcePathView("/path/to/file.cpp")); @@ -485,7 +485,7 @@ TEST_F(SourcePathCache, GetSourceContextAndSourceIdFileNamesAreUniqueForEveryDir ASSERT_THAT(sourceContextAndSourceId, Ne(sourceContextAndSourceId2)); } -TEST_F(SourcePathCache, GetSourceContextAndSourceIdDuplicateFilePathsAreEqual) +TEST_F(SourcePathCache, get_source_context_and_source_id_duplicate_file_paths_are_equal) { auto sourceContextAndSourceId = cache.sourceContextAndSourceId( SourcePathView("/path/to/file.cpp")); diff --git a/tests/unit/unittest/sourcepathview-test.cpp b/tests/unit/tests/unittests/projectstorage/sourcepathview-test.cpp similarity index 67% rename from tests/unit/unittest/sourcepathview-test.cpp rename to tests/unit/tests/unittests/projectstorage/sourcepathview-test.cpp index b6236648baa..a05d91ac159 100644 --- a/tests/unit/unittest/sourcepathview-test.cpp +++ b/tests/unit/tests/unittests/projectstorage/sourcepathview-test.cpp @@ -1,97 +1,97 @@ // Copyright (C) 2017 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" #include namespace { -TEST(SourcePathView, FilePathSlashForEmptyPath) +TEST(SourcePathView, file_path_slash_for_empty_path) { QmlDesigner::SourcePathView filePath(""); ASSERT_THAT(filePath.slashIndex(), -1); } -TEST(SourcePathView, FilePathSlashForSingleSlash) +TEST(SourcePathView, file_path_slash_for_single_slash) { QmlDesigner::SourcePathView filePath("/"); ASSERT_THAT(filePath.slashIndex(), 0); } -TEST(SourcePathView, FilePathSlashForFileInRoot) +TEST(SourcePathView, file_path_slash_for_file_in_root) { QmlDesigner::SourcePathView filePath("/file.h"); ASSERT_THAT(filePath.slashIndex(), 0); } -TEST(SourcePathView, FilePathSlashForSomeLongerPath) +TEST(SourcePathView, file_path_slash_for_some_longer_path) { QmlDesigner::SourcePathView filePath("/path/to/some/file.h"); ASSERT_THAT(filePath.slashIndex(), 13); } -TEST(SourcePathView, FilePathSlashForFileNameOnly) +TEST(SourcePathView, file_path_slash_for_file_name_only) { QmlDesigner::SourcePathView filePath("file.h"); ASSERT_THAT(filePath.slashIndex(), -1); } -TEST(SourcePathView, DirectoryPathForEmptyPath) +TEST(SourcePathView, directory_path_for_empty_path) { QmlDesigner::SourcePathView filePath(""); ASSERT_THAT(filePath.directory(), ""); } -TEST(SourcePathView, DirectoryPathForSingleSlashPath) +TEST(SourcePathView, directory_path_for_single_slash_path) { QmlDesigner::SourcePathView filePath{"/"}; ASSERT_THAT(filePath.directory(), ""); } -TEST(SourcePathView, DirectoryPathForLongerPath) +TEST(SourcePathView, directory_path_for_longer_path) { QmlDesigner::SourcePathView filePath{"/path/to/some/file.h"}; ASSERT_THAT(filePath.directory(), "/path/to/some"); } -TEST(SourcePathView, DirectoryPathForFileNameOnly) +TEST(SourcePathView, directory_path_for_file_name_only) { QmlDesigner::SourcePathView filePath{"file.h"}; ASSERT_THAT(filePath.directory(), IsEmpty()); } -TEST(SourcePathView, FileNameForEmptyPath) +TEST(SourcePathView, file_name_for_empty_path) { QmlDesigner::SourcePathView filePath(""); ASSERT_THAT(filePath.name(), ""); } -TEST(SourcePathView, FileNameForSingleSlashPath) +TEST(SourcePathView, file_name_for_single_slash_path) { QmlDesigner::SourcePathView filePath{"/"}; ASSERT_THAT(filePath.name(), ""); } -TEST(SourcePathView, FileNameForLongerPath) +TEST(SourcePathView, file_name_for_longer_path) { QmlDesigner::SourcePathView filePath{"/path/to/some/file.h"}; ASSERT_THAT(filePath.name(), "file.h"); } -TEST(SourcePathView, FileNameForFileNameOnly) +TEST(SourcePathView, file_name_for_file_name_only) { QmlDesigner::SourcePathView filePath{"file.h"}; diff --git a/tests/unit/unittest/storagecache-test.cpp b/tests/unit/tests/unittests/projectstorage/storagecache-test.cpp similarity index 82% rename from tests/unit/unittest/storagecache-test.cpp rename to tests/unit/tests/unittests/projectstorage/storagecache-test.cpp index 543b4dc5787..c95ea23a676 100644 --- a/tests/unit/unittest/storagecache-test.cpp +++ b/tests/unit/tests/unittests/projectstorage/storagecache-test.cpp @@ -1,11 +1,11 @@ // Copyright (C) 2021 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" -#include "mockmutex.h" -#include "projectstoragemock.h" -#include "sqlitedatabasemock.h" +#include "../mocks/mockmutex.h" +#include "../mocks/projectstoragemock.h" +#include "../mocks/sqlitedatabasemock.h" #include #include @@ -17,7 +17,6 @@ namespace { using QmlDesigner::SourceContextId; using QmlDesigner::StorageCacheException; using Utils::compare; -using Utils::reverseCompare; class StorageAdapter { @@ -33,7 +32,7 @@ public: auto less(Utils::SmallStringView first, Utils::SmallStringView second) -> bool { - return Utils::reverseCompare(first, second) < 0; + return Utils::compare(first, second) < 0; }; using CacheWithMockLocking = QmlDesigner::StorageCachemockStorage, fetchSourceContextId(Eq("foo"))).WillByDefault(Return(id42)); @@ -105,14 +104,14 @@ protected: using CacheTypes = ::testing::Types; TYPED_TEST_SUITE(StorageCache, CacheTypes); -TYPED_TEST(StorageCache, AddFilePath) +TYPED_TEST(StorageCache, add_file_path) { auto id = this->cache.id(this->filePath1); ASSERT_THAT(id, this->id1); } -TYPED_TEST(StorageCache, AddSecondFilePath) +TYPED_TEST(StorageCache, add_second_file_path) { this->cache.id(this->filePath1); @@ -121,7 +120,7 @@ TYPED_TEST(StorageCache, AddSecondFilePath) ASSERT_THAT(id, this->id2); } -TYPED_TEST(StorageCache, AddDuplicateFilePath) +TYPED_TEST(StorageCache, add_duplicate_file_path) { this->cache.id(this->filePath1); @@ -130,7 +129,7 @@ TYPED_TEST(StorageCache, AddDuplicateFilePath) ASSERT_THAT(id, this->id1); } -TYPED_TEST(StorageCache, AddDuplicateFilePathBetweenOtherEntries) +TYPED_TEST(StorageCache, add_duplicate_file_path_between_other_entries) { this->cache.id(this->filePath1); this->cache.id(this->filePath2); @@ -142,7 +141,7 @@ TYPED_TEST(StorageCache, AddDuplicateFilePathBetweenOtherEntries) ASSERT_THAT(id, this->id3); } -TYPED_TEST(StorageCache, GetFilePathForIdWithOneEntry) +TYPED_TEST(StorageCache, get_file_path_for_id_with_one_entry) { this->cache.id(this->filePath1); @@ -151,7 +150,7 @@ TYPED_TEST(StorageCache, GetFilePathForIdWithOneEntry) ASSERT_THAT(filePath, this->filePath1); } -TYPED_TEST(StorageCache, GetFilePathForIdWithSomeEntries) +TYPED_TEST(StorageCache, get_file_path_for_id_with_some_entries) { this->cache.id(this->filePath1); this->cache.id(this->filePath2); @@ -163,7 +162,7 @@ TYPED_TEST(StorageCache, GetFilePathForIdWithSomeEntries) ASSERT_THAT(filePath, this->filePath3); } -TYPED_TEST(StorageCache, GetAllFilePaths) +TYPED_TEST(StorageCache, get_all_file_paths) { this->cache.id(this->filePath1); this->cache.id(this->filePath2); @@ -176,28 +175,28 @@ TYPED_TEST(StorageCache, GetAllFilePaths) ElementsAre(this->filePath1, this->filePath2, this->filePath3, this->filePath4)); } -TYPED_TEST(StorageCache, AddFilePaths) +TYPED_TEST(StorageCache, add_file_paths) { auto ids = this->cache.ids({this->filePath1, this->filePath2, this->filePath3, this->filePath4}); ASSERT_THAT(ids, ElementsAre(this->id1, this->id2, this->id3, this->id4)); } -TYPED_TEST(StorageCache, AddFilePathsWithStorageFunction) +TYPED_TEST(StorageCache, add_file_paths_with_storage_function) { auto ids = this->cache.ids({"foo", "taa", "poo", "bar"}); ASSERT_THAT(ids, UnorderedElementsAre(this->id42, this->id43, this->id44, this->id45)); } -TYPED_TEST(StorageCache, IsEmpty) +TYPED_TEST(StorageCache, is_empty) { auto isEmpty = this->cache.isEmpty(); ASSERT_TRUE(isEmpty); } -TYPED_TEST(StorageCache, IsNotEmpty) +TYPED_TEST(StorageCache, is_not_empty) { this->cache.id(this->filePath1); @@ -206,14 +205,14 @@ TYPED_TEST(StorageCache, IsNotEmpty) ASSERT_FALSE(isEmpty); } -TYPED_TEST(StorageCache, PopulateWithEmptyVector) +TYPED_TEST(StorageCache, populate_with_empty_vector) { this->cache.uncheckedPopulate(); ASSERT_TRUE(this->cache.isEmpty()); } -TYPED_TEST(StorageCache, IsNotEmptyAfterPopulateWithSomeEntries) +TYPED_TEST(StorageCache, is_not_empty_after_populate_with_some_entries) { typename TypeParam::CacheEntries entries{{this->filePath1.clone(), this->id1}, {this->filePath2.clone(), this->id4}, @@ -226,7 +225,7 @@ TYPED_TEST(StorageCache, IsNotEmptyAfterPopulateWithSomeEntries) ASSERT_TRUE(!this->cache.isEmpty()); } -TYPED_TEST(StorageCache, GetEntryAfterPopulateWithSomeEntries) +TYPED_TEST(StorageCache, get_entry_after_populate_with_some_entries) { typename TypeParam::CacheEntries entries{{this->filePath1.clone(), this->id1}, {this->filePath2.clone(), this->id2}, @@ -240,7 +239,7 @@ TYPED_TEST(StorageCache, GetEntryAfterPopulateWithSomeEntries) ASSERT_THAT(value, this->filePath3); } -TYPED_TEST(StorageCache, EntriesHaveUniqueIds) +TYPED_TEST(StorageCache, entries_have_unique_ids) { typename TypeParam::CacheEntries entries{{this->filePath1.clone(), this->id1}, {this->filePath2.clone(), this->id2}, @@ -251,7 +250,7 @@ TYPED_TEST(StorageCache, EntriesHaveUniqueIds) ASSERT_THROW(this->cache.populate(), StorageCacheException); } -TYPED_TEST(StorageCache, MultipleEntries) +TYPED_TEST(StorageCache, multiple_entries) { typename TypeParam::CacheEntries entries{{this->filePath1.clone(), this->id1}, {this->filePath1.clone(), this->id2}, @@ -262,7 +261,7 @@ TYPED_TEST(StorageCache, MultipleEntries) ASSERT_THROW(this->cache.populate(), StorageCacheException); } -TYPED_TEST(StorageCache, IdIsReadAndWriteLockedForUnknownEntry) +TYPED_TEST(StorageCache, id_is_read_and_write_locked_for_unknown_entry) { InSequence s; @@ -274,7 +273,7 @@ TYPED_TEST(StorageCache, IdIsReadAndWriteLockedForUnknownEntry) this->cache.id("foo"); } -TYPED_TEST(StorageCache, IdWithStorageFunctionIsReadAndWriteLockedForUnknownEntry) +TYPED_TEST(StorageCache, id_with_storage_function_is_read_and_write_locked_for_unknown_entry) { InSequence s; @@ -287,7 +286,7 @@ TYPED_TEST(StorageCache, IdWithStorageFunctionIsReadAndWriteLockedForUnknownEntr this->cache.id("foo"); } -TYPED_TEST(StorageCache, IdWithStorageFunctionIsReadLockedForKnownEntry) +TYPED_TEST(StorageCache, id_with_storage_function_is_read_locked_for_known_entry) { InSequence s; this->cache.id("foo"); @@ -301,7 +300,7 @@ TYPED_TEST(StorageCache, IdWithStorageFunctionIsReadLockedForKnownEntry) this->cache.id("foo"); } -TYPED_TEST(StorageCache, IdIsReadLockedForKnownEntry) +TYPED_TEST(StorageCache, id_is_read_locked_for_known_entry) { this->cache.id("foo"); @@ -313,7 +312,7 @@ TYPED_TEST(StorageCache, IdIsReadLockedForKnownEntry) this->cache.id("foo"); } -TYPED_TEST(StorageCache, IdsIsLocked) +TYPED_TEST(StorageCache, ids_is_locked) { EXPECT_CALL(this->mockMutex, lock_shared()); EXPECT_CALL(this->mockMutex, unlock_shared()); @@ -321,7 +320,7 @@ TYPED_TEST(StorageCache, IdsIsLocked) this->cache.ids({"foo"}); } -TYPED_TEST(StorageCache, IdsWithStorageIsLocked) +TYPED_TEST(StorageCache, ids_with_storage_is_locked) { EXPECT_CALL(this->mockMutex, lock_shared()); EXPECT_CALL(this->mockMutex, unlock_shared()); @@ -329,7 +328,7 @@ TYPED_TEST(StorageCache, IdsWithStorageIsLocked) this->cache.ids({"foo"}); } -TYPED_TEST(StorageCache, ValueIsLocked) +TYPED_TEST(StorageCache, value_is_locked) { auto id = this->cache.id("foo"); @@ -339,7 +338,7 @@ TYPED_TEST(StorageCache, ValueIsLocked) this->cache.value(id); } -TYPED_TEST(StorageCache, ValuesIsLocked) +TYPED_TEST(StorageCache, values_is_locked) { auto ids = this->cache.ids({"foo", "bar"}); @@ -349,7 +348,7 @@ TYPED_TEST(StorageCache, ValuesIsLocked) this->cache.values(ids); } -TYPED_TEST(StorageCache, ValueWithStorageFunctionIsReadAndWriteLockedForUnknownId) +TYPED_TEST(StorageCache, value_with_storage_function_is_read_and_write_locked_for_unknown_id) { InSequence s; @@ -362,7 +361,7 @@ TYPED_TEST(StorageCache, ValueWithStorageFunctionIsReadAndWriteLockedForUnknownI this->cache.value(this->id41); } -TYPED_TEST(StorageCache, ValueWithStorageFunctionIsReadLockedForKnownId) +TYPED_TEST(StorageCache, value_with_storage_function_is_read_locked_for_known_id) { InSequence s; this->cache.value(this->id41); @@ -376,14 +375,14 @@ TYPED_TEST(StorageCache, ValueWithStorageFunctionIsReadLockedForKnownId) this->cache.value(this->id41); } -TYPED_TEST(StorageCache, IdWithStorageFunctionWhichHasNoEntryIsCallingStorageFunction) +TYPED_TEST(StorageCache, id_with_storage_function_which_has_no_entry_is_calling_storage_function) { EXPECT_CALL(this->mockStorage, fetchSourceContextId(Eq("foo"))); this->cache.id("foo"); } -TYPED_TEST(StorageCache, IdWithStorageFunctionWhichHasEntryIsNotCallingStorageFunction) +TYPED_TEST(StorageCache, id_with_storage_function_which_has_entry_is_not_calling_storage_function) { this->cache.id("foo"); @@ -392,7 +391,7 @@ TYPED_TEST(StorageCache, IdWithStorageFunctionWhichHasEntryIsNotCallingStorageFu this->cache.id("foo"); } -TYPED_TEST(StorageCache, IndexOfIdWithStorageFunctionWhichHasEntry) +TYPED_TEST(StorageCache, index_of_id_with_storage_function_which_has_entry) { this->cache.id("foo"); @@ -401,14 +400,14 @@ TYPED_TEST(StorageCache, IndexOfIdWithStorageFunctionWhichHasEntry) ASSERT_THAT(index, this->id42); } -TYPED_TEST(StorageCache, IndexOfIdWithStorageFunctionWhichHasNoEntry) +TYPED_TEST(StorageCache, index_of_id_with_storage_function_which_has_no_entry) { auto index = this->cache.id("foo"); ASSERT_THAT(index, this->id42); } -TYPED_TEST(StorageCache, GetEntryByIndexAfterInsertingByCustomIndex) +TYPED_TEST(StorageCache, get_entry_by_index_after_inserting_by_custom_index) { auto index = this->cache.id("foo"); @@ -417,7 +416,7 @@ TYPED_TEST(StorageCache, GetEntryByIndexAfterInsertingByCustomIndex) ASSERT_THAT(value, Eq("foo")); } -TYPED_TEST(StorageCache, CallFetchSourceContextPathForLowerIndex) +TYPED_TEST(StorageCache, call_fetch_source_context_path_for_lower_index) { auto index = this->cache.id("foo"); SourceContextId lowerIndex{SourceContextId::create(index.internalId() - 1)}; @@ -427,21 +426,21 @@ TYPED_TEST(StorageCache, CallFetchSourceContextPathForLowerIndex) this->cache.value(lowerIndex); } -TYPED_TEST(StorageCache, CallFetchSourceContextPathForUnknownIndex) +TYPED_TEST(StorageCache, call_fetch_source_context_path_for_unknown_index) { EXPECT_CALL(this->mockStorage, fetchSourceContextPath(Eq(this->id1))); this->cache.value(this->id1); } -TYPED_TEST(StorageCache, FetchSourceContextPathForUnknownIndex) +TYPED_TEST(StorageCache, fetch_source_context_path_for_unknown_index) { auto value = this->cache.value(this->id41); ASSERT_THAT(value, Eq("bar")); } -TYPED_TEST(StorageCache, AddCalls) +TYPED_TEST(StorageCache, add_calls) { EXPECT_CALL(this->mockStorage, fetchSourceContextId(Eq("foo"))); EXPECT_CALL(this->mockStorage, fetchSourceContextId(Eq("bar"))); @@ -450,7 +449,7 @@ TYPED_TEST(StorageCache, AddCalls) this->cache.add({"foo", "bar", "poo"}); } -TYPED_TEST(StorageCache, AddCallsOnlyForNewValues) +TYPED_TEST(StorageCache, add_calls_only_for_new_values) { this->cache.add({"foo", "poo"}); @@ -460,21 +459,21 @@ TYPED_TEST(StorageCache, AddCallsOnlyForNewValues) this->cache.add({"foo", "bar", "poo", "taa"}); } -TYPED_TEST(StorageCache, GetIdAfterAddingValues) +TYPED_TEST(StorageCache, get_id_after_adding_values) { this->cache.add({"foo", "bar", "poo", "taa"}); ASSERT_THAT(this->cache.value(this->cache.id("taa")), Eq("taa")); } -TYPED_TEST(StorageCache, GetValueAfterAddingValues) +TYPED_TEST(StorageCache, get_value_after_adding_values) { this->cache.add({"foo", "bar", "poo", "taa"}); ASSERT_THAT(this->cache.value(this->cache.id("taa")), Eq("taa")); } -TYPED_TEST(StorageCache, GetIdAfterAddingValuesMultipleTimes) +TYPED_TEST(StorageCache, get_id_after_adding_values_multiple_times) { this->cache.add({"foo", "taa"}); @@ -483,19 +482,19 @@ TYPED_TEST(StorageCache, GetIdAfterAddingValuesMultipleTimes) ASSERT_THAT(this->cache.value(this->cache.id("taa")), Eq("taa")); } -TYPED_TEST(StorageCache, GetIdAfterAddingTheSameValuesMultipleTimes) +TYPED_TEST(StorageCache, get_id_after_adding_the_same_values_multiple_times) { this->cache.add({"foo", "taa", "poo", "taa", "bar", "taa"}); ASSERT_THAT(this->cache.value(this->cache.id("taa")), Eq("taa")); } -TYPED_TEST(StorageCache, AddingEmptyValues) +TYPED_TEST(StorageCache, adding_empty_values) { this->cache.add({}); } -TYPED_TEST(StorageCache, FetchIdsFromStorageCalls) +TYPED_TEST(StorageCache, fetch_ids_from_storage_calls) { InSequence s; diff --git a/tests/unit/unittest/qmlprojectmanager/CMakeLists.txt b/tests/unit/tests/unittests/qmlprojectmanager/CMakeLists.txt similarity index 85% rename from tests/unit/unittest/qmlprojectmanager/CMakeLists.txt rename to tests/unit/tests/unittests/qmlprojectmanager/CMakeLists.txt index 52a70c0736a..a3859a9ce7b 100644 --- a/tests/unit/unittest/qmlprojectmanager/CMakeLists.txt +++ b/tests/unit/tests/unittests/qmlprojectmanager/CMakeLists.txt @@ -7,3 +7,5 @@ extend_qtc_test(unittest converters-test.cpp projectitem-test.cpp ) + +unittest_copy_data_folder() diff --git a/tests/unit/unittest/qmlprojectmanager/converters-test.cpp b/tests/unit/tests/unittests/qmlprojectmanager/converters-test.cpp similarity index 94% rename from tests/unit/unittest/qmlprojectmanager/converters-test.cpp rename to tests/unit/tests/unittests/qmlprojectmanager/converters-test.cpp index efa2b647aeb..4131ec48a56 100644 --- a/tests/unit/unittest/qmlprojectmanager/converters-test.cpp +++ b/tests/unit/tests/unittests/qmlprojectmanager/converters-test.cpp @@ -1,7 +1,7 @@ // Copyright (C) 2023 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" // IWYU pragma: keep +#include "../utils/googletest.h" // IWYU pragma: keep #include @@ -31,12 +31,14 @@ public: ? QString::fromLatin1(m_qmlProjectFile.fileContents().value()) : QString{}); } + QString jsonToQmlProjectContent() const { return m_jsonToQmlProjectFile.fileContents() ? QString::fromLatin1(m_jsonToQmlProjectFile.fileContents().value()) : QString{}; } + QString qmlProjectToJsonContent() const { return m_qmlProjectToJsonFile.fileContents() @@ -45,9 +47,13 @@ public: } QString dataSetPath() const { return m_dataSetDirectory.absolutePath(); } + QString dataSetName() const { return m_dataSetDirectory.dirName(); } + Utils::FilePath qmlProjectFile() const { return m_qmlProjectFile; } + Utils::FilePath jsonToQmlProjectFile() const { return m_jsonToQmlProjectFile; } + Utils::FilePath qmlProjectToJsonFile() const { return m_qmlProjectToJsonFile; } private: @@ -57,11 +63,11 @@ private: Utils::FilePath m_qmlProjectToJsonFile; }; -INSTANTIATE_TEST_SUITE_P(ConverterTests, +INSTANTIATE_TEST_SUITE_P(QmlProjectItem, DataSet, ::testing::Values(QString("test-set-1"), QString("test-set-2"))); -TEST_P(DataSet, QmlProjectToJson) +TEST_P(DataSet, qml_project_to_json) { // GIVEN setDataSource(GetParam()); @@ -76,7 +82,7 @@ TEST_P(DataSet, QmlProjectToJson) ASSERT_THAT(convertedContent, Eq(targetContent)); } -TEST_P(DataSet, JsonToQmlProject) +TEST_P(DataSet, json_to_qml_project) { // GIVEN setDataSource(GetParam()); diff --git a/tests/unit/unittest/qmlprojectmanager/data/README.md b/tests/unit/tests/unittests/qmlprojectmanager/data/README.md similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/README.md rename to tests/unit/tests/unittests/qmlprojectmanager/data/README.md diff --git a/tests/unit/unittest/qmlprojectmanager/data/converter/test-set-1/testfile.jsontoqml b/tests/unit/tests/unittests/qmlprojectmanager/data/converter/test-set-1/testfile.jsontoqml similarity index 93% rename from tests/unit/unittest/qmlprojectmanager/data/converter/test-set-1/testfile.jsontoqml rename to tests/unit/tests/unittests/qmlprojectmanager/data/converter/test-set-1/testfile.jsontoqml index 5207599f994..dbd6e4a91ac 100644 --- a/tests/unit/unittest/qmlprojectmanager/data/converter/test-set-1/testfile.jsontoqml +++ b/tests/unit/tests/unittests/qmlprojectmanager/data/converter/test-set-1/testfile.jsontoqml @@ -1,5 +1,5 @@ -\\ prop: json-converted -\\ prop: auto-generated +// prop: json-converted +// prop: auto-generated import QmlProject @@ -28,7 +28,7 @@ Project { } ShaderTool { - args: "-s --glsl "100 es,120,150" --hlsl 50 --msl 12" + args: "-s --glsl \"100 es,120,150\" --hlsl 50 --msl 12" files: [ "content/shaders/*" ] } diff --git a/tests/unit/unittest/qmlprojectmanager/data/converter/test-set-1/testfile.qmlproject b/tests/unit/tests/unittests/qmlprojectmanager/data/converter/test-set-1/testfile.qmlproject similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/converter/test-set-1/testfile.qmlproject rename to tests/unit/tests/unittests/qmlprojectmanager/data/converter/test-set-1/testfile.qmlproject diff --git a/tests/unit/unittest/qmlprojectmanager/data/converter/test-set-1/testfile.qmltojson b/tests/unit/tests/unittests/qmlprojectmanager/data/converter/test-set-1/testfile.qmltojson similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/converter/test-set-1/testfile.qmltojson rename to tests/unit/tests/unittests/qmlprojectmanager/data/converter/test-set-1/testfile.qmltojson diff --git a/tests/unit/unittest/qmlprojectmanager/data/converter/test-set-2/testfile.jsontoqml b/tests/unit/tests/unittests/qmlprojectmanager/data/converter/test-set-2/testfile.jsontoqml similarity index 87% rename from tests/unit/unittest/qmlprojectmanager/data/converter/test-set-2/testfile.jsontoqml rename to tests/unit/tests/unittests/qmlprojectmanager/data/converter/test-set-2/testfile.jsontoqml index aaf8d0fdc0a..a05b24e9e61 100644 --- a/tests/unit/unittest/qmlprojectmanager/data/converter/test-set-2/testfile.jsontoqml +++ b/tests/unit/tests/unittests/qmlprojectmanager/data/converter/test-set-2/testfile.jsontoqml @@ -1,5 +1,5 @@ -\\ prop: json-converted -\\ prop: auto-generated +// prop: json-converted +// prop: auto-generated import QmlProject @@ -24,11 +24,6 @@ Project { QT_QUICK_CONTROLS_CONF: "qtquickcontrols2.conf" } - ShaderTool { - args: "" - files: [ ] - } - QmlFiles { directory: "." } diff --git a/tests/unit/unittest/qmlprojectmanager/data/converter/test-set-2/testfile.qmlproject b/tests/unit/tests/unittests/qmlprojectmanager/data/converter/test-set-2/testfile.qmlproject similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/converter/test-set-2/testfile.qmlproject rename to tests/unit/tests/unittests/qmlprojectmanager/data/converter/test-set-2/testfile.qmlproject diff --git a/tests/unit/unittest/qmlprojectmanager/data/converter/test-set-2/testfile.qmltojson b/tests/unit/tests/unittests/qmlprojectmanager/data/converter/test-set-2/testfile.qmltojson similarity index 98% rename from tests/unit/unittest/qmlprojectmanager/data/converter/test-set-2/testfile.qmltojson rename to tests/unit/tests/unittests/qmlprojectmanager/data/converter/test-set-2/testfile.qmltojson index 5635cf1f638..33a478e2ca4 100644 --- a/tests/unit/unittest/qmlprojectmanager/data/converter/test-set-2/testfile.qmltojson +++ b/tests/unit/tests/unittests/qmlprojectmanager/data/converter/test-set-2/testfile.qmltojson @@ -83,8 +83,6 @@ ], "mainFile": "fileSelectors.qml" }, - "shaderTool": { - }, "versions": { "qt": "5" } diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/MaterialBundle.qmlproject b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/MaterialBundle.qmlproject similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/MaterialBundle.qmlproject rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/MaterialBundle.qmlproject diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/MaterialBundle.qmlproject.qtds b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/MaterialBundle.qmlproject.qtds similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/MaterialBundle.qmlproject.qtds rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/MaterialBundle.qmlproject.qtds diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/MaterialLibrary.qrc b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/MaterialLibrary.qrc similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/MaterialLibrary.qrc rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/MaterialLibrary.qrc diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/CMakeLists.txt b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/CMakeLists.txt similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/CMakeLists.txt rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/CMakeLists.txt diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/CMakeLists.txt b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/CMakeLists.txt similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/CMakeLists.txt rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/CMakeLists.txt diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/AcrylicPaintMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/AcrylicPaintMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/AcrylicPaintMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/AcrylicPaintMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/AluminiumMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/AluminiumMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/AluminiumMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/AluminiumMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/AsphaltMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/AsphaltMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/AsphaltMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/AsphaltMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/BrickMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/BrickMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/BrickMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/BrickMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/CMakeLists.txt b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/CMakeLists.txt similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/CMakeLists.txt rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/CMakeLists.txt diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/CarPaintGlitterMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/CarPaintGlitterMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/CarPaintGlitterMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/CarPaintGlitterMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/CarPaintMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/CarPaintMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/CarPaintMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/CarPaintMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/CarbonFiberMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/CarbonFiberMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/CarbonFiberMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/CarbonFiberMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/CeramicMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/CeramicMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/CeramicMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/CeramicMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/ChromeMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/ChromeMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/ChromeMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/ChromeMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/ConcreteMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/ConcreteMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/ConcreteMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/ConcreteMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/CopperMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/CopperMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/CopperMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/CopperMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/FabricMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/FabricMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/FabricMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/FabricMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/FabricRoughMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/FabricRoughMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/FabricRoughMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/FabricRoughMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/FabricSatinMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/FabricSatinMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/FabricSatinMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/FabricSatinMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/GlassMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/GlassMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/GlassMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/GlassMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/GlassTintedMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/GlassTintedMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/GlassTintedMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/GlassTintedMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/GoldMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/GoldMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/GoldMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/GoldMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/LeatherMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/LeatherMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/LeatherMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/LeatherMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/MirrorMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/MirrorMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/MirrorMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/MirrorMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/PaperMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/PaperMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/PaperMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/PaperMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/PlasticMatteMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/PlasticMatteMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/PlasticMatteMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/PlasticMatteMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/PlasticShinyMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/PlasticShinyMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/PlasticShinyMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/PlasticShinyMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/PlasticTexturedMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/PlasticTexturedMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/PlasticTexturedMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/PlasticTexturedMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/RubberMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/RubberMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/RubberMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/RubberMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/SilverMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/SilverMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/SilverMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/SilverMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/SteelBrushedMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/SteelBrushedMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/SteelBrushedMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/SteelBrushedMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/SteelFloorMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/SteelFloorMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/SteelFloorMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/SteelFloorMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/SteelMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/SteelMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/SteelMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/SteelMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/StoneMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/StoneMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/StoneMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/StoneMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/WaxMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/WaxMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/WaxMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/WaxMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/WoodMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/WoodMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/WoodMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/WoodMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/WoodParquetMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/WoodParquetMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/WoodParquetMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/WoodParquetMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/WoodPlanksMaterial.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/WoodPlanksMaterial.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/WoodPlanksMaterial.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/WoodPlanksMaterial.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/_asset_ref.json b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/_asset_ref.json similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/_asset_ref.json rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/_asset_ref.json diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/acrylicpaint.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/acrylicpaint.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/acrylicpaint.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/acrylicpaint.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/aluminium.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/aluminium.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/aluminium.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/aluminium.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/asphalt.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/asphalt.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/asphalt.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/asphalt.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/brick.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/brick.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/brick.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/brick.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/carbonfiber.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/carbonfiber.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/carbonfiber.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/carbonfiber.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/carpaint.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/carpaint.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/carpaint.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/carpaint.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/carpaintglitter.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/carpaintglitter.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/carpaintglitter.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/carpaintglitter.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/ceramic.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/ceramic.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/ceramic.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/ceramic.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/chrome.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/chrome.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/chrome.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/chrome.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/concrete.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/concrete.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/concrete.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/concrete.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/copper.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/copper.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/copper.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/copper.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/fabric.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/fabric.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/fabric.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/fabric.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/fabricrough.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/fabricrough.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/fabricrough.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/fabricrough.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/fabricsatin.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/fabricsatin.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/fabricsatin.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/fabricsatin.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/glass.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/glass.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/glass.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/glass.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/glasstinted.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/glasstinted.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/glasstinted.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/glasstinted.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/gold.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/gold.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/gold.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/gold.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/images/material.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/images/material.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/images/material.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/images/material.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/images/material16.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/images/material16.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/images/material16.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/images/material16.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/images/material@2x.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/images/material@2x.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/images/material@2x.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/images/material@2x.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/leather.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/leather.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/leather.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/leather.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/mirror.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/mirror.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/mirror.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/mirror.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/paper.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/paper.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/paper.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/paper.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/plasticmatte.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/plasticmatte.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/plasticmatte.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/plasticmatte.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/plasticshiny.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/plasticshiny.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/plasticshiny.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/plasticshiny.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/plastictextured.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/plastictextured.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/plastictextured.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/plastictextured.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/rubber.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/rubber.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/rubber.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/rubber.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/silver.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/silver.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/silver.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/silver.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/steel.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/steel.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/steel.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/steel.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/steelbrushed.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/steelbrushed.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/steelbrushed.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/steelbrushed.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/steelfloor.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/steelfloor.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/steelfloor.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/steelfloor.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/stone.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/stone.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/stone.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/stone.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/wax.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/wax.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/wax.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/wax.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/wood.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/wood.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/wood.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/wood.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/woodparquet.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/woodparquet.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/woodparquet.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/woodparquet.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/woodplanks.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/woodplanks.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/woodplanks.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/designer/woodplanks.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Asphalt010_2K_NormalGL.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Asphalt010_2K_NormalGL.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Asphalt010_2K_NormalGL.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Asphalt010_2K_NormalGL.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Asphalt010_2K_Opacity.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Asphalt010_2K_Opacity.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Asphalt010_2K_Opacity.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Asphalt010_2K_Opacity.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Asphalt010_2K_Roughness.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Asphalt010_2K_Roughness.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Asphalt010_2K_Roughness.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Asphalt010_2K_Roughness.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Bricks026_2K_AmbientOcclusion.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Bricks026_2K_AmbientOcclusion.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Bricks026_2K_AmbientOcclusion.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Bricks026_2K_AmbientOcclusion.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Bricks026_2K_Color.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Bricks026_2K_Color.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Bricks026_2K_Color.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Bricks026_2K_Color.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Bricks026_2K_NormalGL.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Bricks026_2K_NormalGL.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Bricks026_2K_NormalGL.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Bricks026_2K_NormalGL.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Bricks026_2K_Roughness.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Bricks026_2K_Roughness.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Bricks026_2K_Roughness.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Bricks026_2K_Roughness.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Concrete032_2K_NormalGL.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Concrete032_2K_NormalGL.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Concrete032_2K_NormalGL.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Concrete032_2K_NormalGL.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Concrete032_2K_Roughness.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Concrete032_2K_Roughness.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Concrete032_2K_Roughness.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Concrete032_2K_Roughness.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/DiamondPlate001_2K_NormalGL.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/DiamondPlate001_2K_NormalGL.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/DiamondPlate001_2K_NormalGL.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/DiamondPlate001_2K_NormalGL.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/DiamondPlate001_2K_Roughness.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/DiamondPlate001_2K_Roughness.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/DiamondPlate001_2K_Roughness.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/DiamondPlate001_2K_Roughness.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Fabric004_2K_NormalGL.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Fabric004_2K_NormalGL.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Fabric004_2K_NormalGL.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Fabric004_2K_NormalGL.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Fabric030_2K_Displacement.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Fabric030_2K_Displacement.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Fabric030_2K_Displacement.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Fabric030_2K_Displacement.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Fabric030_2K_NormalGL.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Fabric030_2K_NormalGL.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Fabric030_2K_NormalGL.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Fabric030_2K_NormalGL.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Fabric030_2K_Roughness.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Fabric030_2K_Roughness.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Fabric030_2K_Roughness.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Fabric030_2K_Roughness.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Fabric031_2K_Displacement.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Fabric031_2K_Displacement.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Fabric031_2K_Displacement.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Fabric031_2K_Displacement.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Fabric031_2K_NormalGL.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Fabric031_2K_NormalGL.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Fabric031_2K_NormalGL.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Fabric031_2K_NormalGL.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Fabric031_2K_Roughness.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Fabric031_2K_Roughness.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Fabric031_2K_Roughness.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Fabric031_2K_Roughness.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/LDR_RGB1_3.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/LDR_RGB1_3.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/LDR_RGB1_3.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/LDR_RGB1_3.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Leather037_2K_Color.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Leather037_2K_Color.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Leather037_2K_Color.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Leather037_2K_Color.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Leather037_2K_NormalGL.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Leather037_2K_NormalGL.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Leather037_2K_NormalGL.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Leather037_2K_NormalGL.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Leather037_2K_Roughness.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Leather037_2K_Roughness.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Leather037_2K_Roughness.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Leather037_2K_Roughness.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Metal009_2K_NormalGL.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Metal009_2K_NormalGL.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Metal009_2K_NormalGL.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Metal009_2K_NormalGL.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Metal009_2K_Roughness.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Metal009_2K_Roughness.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Metal009_2K_Roughness.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Metal009_2K_Roughness.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Metal029_2K_Displacement.jpg b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Metal029_2K_Displacement.jpg similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Metal029_2K_Displacement.jpg rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Metal029_2K_Displacement.jpg diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Metal029_2K_Displacement.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Metal029_2K_Displacement.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Metal029_2K_Displacement.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Metal029_2K_Displacement.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Paint006_2K_AmbientOcclusion.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Paint006_2K_AmbientOcclusion.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Paint006_2K_AmbientOcclusion.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Paint006_2K_AmbientOcclusion.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Paint006_2K_NormalGL.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Paint006_2K_NormalGL.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Paint006_2K_NormalGL.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Paint006_2K_NormalGL.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Paint006_2K_Roughness.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Paint006_2K_Roughness.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Paint006_2K_Roughness.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Paint006_2K_Roughness.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Rock023_2K_AmbientOcclusion.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Rock023_2K_AmbientOcclusion.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Rock023_2K_AmbientOcclusion.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Rock023_2K_AmbientOcclusion.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Rock023_2K_Color.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Rock023_2K_Color.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Rock023_2K_Color.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Rock023_2K_Color.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Rock023_2K_NormalGL.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Rock023_2K_NormalGL.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Rock023_2K_NormalGL.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Rock023_2K_NormalGL.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Rock023_2K_Roughness.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Rock023_2K_Roughness.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Rock023_2K_Roughness.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Rock023_2K_Roughness.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Wood048_2K_Color.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Wood048_2K_Color.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Wood048_2K_Color.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Wood048_2K_Color.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Wood048_2K_NormalGL.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Wood048_2K_NormalGL.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Wood048_2K_NormalGL.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Wood048_2K_NormalGL.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Wood048_2K_Roughness.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Wood048_2K_Roughness.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Wood048_2K_Roughness.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/Wood048_2K_Roughness.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/WoodFloor044_2K_Color.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/WoodFloor044_2K_Color.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/WoodFloor044_2K_Color.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/WoodFloor044_2K_Color.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/WoodFloor044_2K_NormalGL.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/WoodFloor044_2K_NormalGL.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/WoodFloor044_2K_NormalGL.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/WoodFloor044_2K_NormalGL.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/WoodFloor044_2K_Roughness.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/WoodFloor044_2K_Roughness.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/WoodFloor044_2K_Roughness.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/WoodFloor044_2K_Roughness.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/WoodFloor054_2K_AmbientOcclusion.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/WoodFloor054_2K_AmbientOcclusion.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/WoodFloor054_2K_AmbientOcclusion.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/WoodFloor054_2K_AmbientOcclusion.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/WoodFloor054_2K_Color.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/WoodFloor054_2K_Color.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/WoodFloor054_2K_Color.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/WoodFloor054_2K_Color.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/WoodFloor054_2K_NormalGL.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/WoodFloor054_2K_NormalGL.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/WoodFloor054_2K_NormalGL.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/WoodFloor054_2K_NormalGL.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/WoodFloor054_2K_Roughness.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/WoodFloor054_2K_Roughness.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/WoodFloor054_2K_Roughness.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/WoodFloor054_2K_Roughness.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/blurrynoise.tga b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/blurrynoise.tga similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/blurrynoise.tga rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/blurrynoise.tga diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/noisenormal.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/noisenormal.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/noisenormal.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/images/noisenormal.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/qmldir b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/qmldir similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/qmldir rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/qmldir diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/CMakeLists.txt b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/CMakeLists.txt similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/CMakeLists.txt rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/CMakeLists.txt diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/SSS.frag b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/SSS.frag similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/SSS.frag rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/SSS.frag diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/SSS.vert b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/SSS.vert similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/SSS.vert rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/SSS.vert diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/carmat_simple.frag b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/carmat_simple.frag similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/carmat_simple.frag rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/carmat_simple.frag diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/carmat_simple.vert b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/carmat_simple.vert similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/carmat_simple.vert rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/carmat_simple.vert diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/carmat_simple_nf.frag b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/carmat_simple_nf.frag similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/carmat_simple_nf.frag rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/carmat_simple_nf.frag diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/carmat_simple_nf.vert b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/carmat_simple_nf.vert similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/carmat_simple_nf.vert rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/carmat_simple_nf.vert diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/glass.frag b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/glass.frag similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/glass.frag rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/glass.frag diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/glass.vert b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/glass.vert similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/glass.vert rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/glass.vert diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/satin.frag b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/satin.frag similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/satin.frag rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/satin.frag diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/satin.vert b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/satin.vert similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/satin.vert rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/asset_imports/ComponentBundles/MaterialBundle/shaders/satin.vert diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/App.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/App.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/App.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/App.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/CMakeLists.txt b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/CMakeLists.txt similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/CMakeLists.txt rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/CMakeLists.txt diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/CustomRoundButton.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/CustomRoundButton.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/CustomRoundButton.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/CustomRoundButton.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/MaterialNames.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/MaterialNames.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/MaterialNames.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/MaterialNames.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/MouseRotator.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/MouseRotator.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/MouseRotator.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/MouseRotator.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/Screen01.ui.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/Screen01.ui.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/Screen01.ui.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/Screen01.ui.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/fonts/OpenSans-Bold.ttf b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/fonts/OpenSans-Bold.ttf similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/fonts/OpenSans-Bold.ttf rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/fonts/OpenSans-Bold.ttf diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/fonts/OpenSans-Regular.ttf b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/fonts/OpenSans-Regular.ttf similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/fonts/OpenSans-Regular.ttf rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/fonts/OpenSans-Regular.ttf diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/fonts/fonts.txt b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/fonts/fonts.txt similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/fonts/fonts.txt rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/fonts/fonts.txt diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/Ground_ShadowMap.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/Ground_ShadowMap.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/Ground_ShadowMap.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/Ground_ShadowMap.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/HDR/dark_mode.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/HDR/dark_mode.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/HDR/dark_mode.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/HDR/dark_mode.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/HDR/day_mode.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/HDR/day_mode.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/HDR/day_mode.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/HDR/day_mode.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/LDR_RGB1_3.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/LDR_RGB1_3.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/LDR_RGB1_3.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/LDR_RGB1_3.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/QtLogo_HD.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/QtLogo_HD.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/QtLogo_HD.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/QtLogo_HD.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/UI/innerMesh.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/UI/innerMesh.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/UI/innerMesh.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/UI/innerMesh.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/UI/lightToggle.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/UI/lightToggle.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/UI/lightToggle.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/UI/lightToggle.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/UI/outerMesh.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/UI/outerMesh.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/UI/outerMesh.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/UI/outerMesh.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/UI/perfhudicon.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/UI/perfhudicon.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/UI/perfhudicon.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/UI/perfhudicon.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/UI/perfhudicon_on.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/UI/perfhudicon_on.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/UI/perfhudicon_on.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/UI/perfhudicon_on.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/White.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/White.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/White.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/White.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/checkmark.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/checkmark.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/checkmark.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/checkmark.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/groundAlpha.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/groundAlpha.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/groundAlpha.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/groundAlpha.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/qtlogo.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/qtlogo.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/qtlogo.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/qtlogo.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/scratchmap.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/scratchmap.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/scratchmap.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/scratchmap.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/shadow.png b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/shadow.png similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/shadow.png rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/shadow.png diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/vlkhcah_2K_AO.jpg b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/vlkhcah_2K_AO.jpg similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/vlkhcah_2K_AO.jpg rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/vlkhcah_2K_AO.jpg diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/vlkhcah_2K_Albedo.jpg b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/vlkhcah_2K_Albedo.jpg similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/vlkhcah_2K_Albedo.jpg rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/vlkhcah_2K_Albedo.jpg diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/vlkhcah_2K_Normal.jpg b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/vlkhcah_2K_Normal.jpg similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/vlkhcah_2K_Normal.jpg rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/vlkhcah_2K_Normal.jpg diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/vlkhcah_2K_Roughness.jpg b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/vlkhcah_2K_Roughness.jpg similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/images/vlkhcah_2K_Roughness.jpg rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/images/vlkhcah_2K_Roughness.jpg diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/meshes/floor.mesh b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/meshes/floor.mesh similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/meshes/floor.mesh rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/meshes/floor.mesh diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/content/meshes/materialBall.mesh b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/meshes/materialBall.mesh similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/content/meshes/materialBall.mesh rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/content/meshes/materialBall.mesh diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/filelist.txt b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/filelist.txt similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/filelist.txt rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/filelist.txt diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/imports/CMakeLists.txt b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/imports/CMakeLists.txt similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/imports/CMakeLists.txt rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/imports/CMakeLists.txt diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/imports/MaterialLibrary/CMakeLists.txt b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/imports/MaterialLibrary/CMakeLists.txt similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/imports/MaterialLibrary/CMakeLists.txt rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/imports/MaterialLibrary/CMakeLists.txt diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/imports/MaterialLibrary/Constants.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/imports/MaterialLibrary/Constants.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/imports/MaterialLibrary/Constants.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/imports/MaterialLibrary/Constants.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/imports/MaterialLibrary/DirectoryFontLoader.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/imports/MaterialLibrary/DirectoryFontLoader.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/imports/MaterialLibrary/DirectoryFontLoader.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/imports/MaterialLibrary/DirectoryFontLoader.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/imports/MaterialLibrary/EventListModel.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/imports/MaterialLibrary/EventListModel.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/imports/MaterialLibrary/EventListModel.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/imports/MaterialLibrary/EventListModel.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/imports/MaterialLibrary/EventListSimulator.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/imports/MaterialLibrary/EventListSimulator.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/imports/MaterialLibrary/EventListSimulator.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/imports/MaterialLibrary/EventListSimulator.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/imports/MaterialLibrary/designer/plugin.metainfo b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/imports/MaterialLibrary/designer/plugin.metainfo similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/imports/MaterialLibrary/designer/plugin.metainfo rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/imports/MaterialLibrary/designer/plugin.metainfo diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/imports/MaterialLibrary/qmldir b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/imports/MaterialLibrary/qmldir similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/imports/MaterialLibrary/qmldir rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/imports/MaterialLibrary/qmldir diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/main.qml b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/main.qml similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/main.qml rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/main.qml diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/qmlcomponents b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/qmlcomponents similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/qmlcomponents rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/qmlcomponents diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/qmlmodules b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/qmlmodules similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/qmlmodules rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/qmlmodules diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/qtquickcontrols2.conf b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/qtquickcontrols2.conf similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/qtquickcontrols2.conf rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/qtquickcontrols2.conf diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/share.qrc b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/share.qrc similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/share.qrc rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/share.qrc diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/src/app_environment.h b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/src/app_environment.h similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/src/app_environment.h rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/src/app_environment.h diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/src/import_qml_plugins.h b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/src/import_qml_plugins.h similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/src/import_qml_plugins.h rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/src/import_qml_plugins.h diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/src/main.cpp b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/src/main.cpp similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/src/main.cpp rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/src/main.cpp diff --git a/tests/unit/unittest/qmlprojectmanager/data/file-filters/translations.db b/tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/translations.db similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/file-filters/translations.db rename to tests/unit/tests/unittests/qmlprojectmanager/data/file-filters/translations.db diff --git a/tests/unit/unittest/qmlprojectmanager/data/getter-setter/empty.qmlproject b/tests/unit/tests/unittests/qmlprojectmanager/data/getter-setter/empty.qmlproject similarity index 100% rename from tests/unit/unittest/qmlprojectmanager/data/getter-setter/empty.qmlproject rename to tests/unit/tests/unittests/qmlprojectmanager/data/getter-setter/empty.qmlproject diff --git a/tests/unit/tests/unittests/qmlprojectmanager/data/getter-setter/with_qds_prefix.qmlproject b/tests/unit/tests/unittests/qmlprojectmanager/data/getter-setter/with_qds_prefix.qmlproject new file mode 100644 index 00000000000..a8b5b459d65 --- /dev/null +++ b/tests/unit/tests/unittests/qmlprojectmanager/data/getter-setter/with_qds_prefix.qmlproject @@ -0,0 +1,96 @@ +import QmlProject + +Project { + QDS.mainFile: "content/App.qml" + QDS.mainUiFile: "Screen01.ui.qml" + + QDS.qt6Project: true + QDS.widgetApp: true + QDS.qtForMCUs: true + QDS.forceFreeType: true + + QDS.importPaths: [ "imports", "asset_imports" ] + QDS.targetDirectory: "/opt/targetDirectory" + QDS.fileSelectors: [ "WXGA", "darkTheme", "ShowIndicator"] + + QDS.qdsVersion: "3.9" + QDS.quickVersion: "6.2" + + QDS.multilanguageSupport: true + QDS.supportedLanguages: ["en" , "fr"] + QDS.primaryLanguage: "en" + + QDS.QmlFiles { + directory: "content" + } + + QDS.QmlFiles { + directory: "imports" + } + + QDS.JavaScriptFiles { + directory: "content" + } + + QDS.JavaScriptFiles { + directory: "imports" + } + + QDS.ImageFiles { + directory: "content" + } + + QDS.Files { + filter: "*.conf" + files: ["qtquickcontrols2.conf"] + } + + QDS.Files { + filter: "qmldir" + directory: "." + } + + QDS.Files { + filter: "*.ttf;*.otf" + } + + QDS.Files { + filter: "*.wav;*.mp3" + } + + QDS.Files { + filter: "*.mp4" + } + + QDS.Files { + filter: "*.glsl;*.glslv;*.glslf;*.vsh;*.fsh;*.vert;*.frag" + } + + QDS.Files { + filter: "*.mesh" + directory: "asset_imports" + } + + QDS.Files { + filter: "*.mesh" + directory: "content" + } + + QDS.Files { + filter: "*.qml" + directory: "asset_imports" + } + + QDS.ImageFiles { + directory: "asset_imports" + } + + QDS.Environment { + QT_QUICK_CONTROLS_CONF: "qtquickcontrols2.conf" + } + + QDS.ShaderTool { + args: "-s --glsl \"100 es,120,150\" --hlsl 50 --msl 12" + files: [ "content/shaders/*" ] + } +} diff --git a/tests/unit/unittest/qmlprojectmanager/data/getter-setter/notEmpty.qmlproject b/tests/unit/tests/unittests/qmlprojectmanager/data/getter-setter/without_qds_prefix.qmlproject similarity index 99% rename from tests/unit/unittest/qmlprojectmanager/data/getter-setter/notEmpty.qmlproject rename to tests/unit/tests/unittests/qmlprojectmanager/data/getter-setter/without_qds_prefix.qmlproject index ae866ca3974..6bee5999555 100644 --- a/tests/unit/unittest/qmlprojectmanager/data/getter-setter/notEmpty.qmlproject +++ b/tests/unit/tests/unittests/qmlprojectmanager/data/getter-setter/without_qds_prefix.qmlproject @@ -3,12 +3,12 @@ import QmlProject Project { mainFile: "content/App.qml" mainUiFile: "Screen01.ui.qml" - + qt6Project: true widgetApp: true qtForMCUs: true forceFreeType: true - + importPaths: [ "imports", "asset_imports" ] targetDirectory: "/opt/targetDirectory" fileSelectors: [ "WXGA", "darkTheme", "ShowIndicator"] @@ -19,7 +19,7 @@ Project { multilanguageSupport: true supportedLanguages: ["en" , "fr"] primaryLanguage: "en" - + QmlFiles { directory: "content" } diff --git a/tests/unit/tests/unittests/qmlprojectmanager/projectitem-test.cpp b/tests/unit/tests/unittests/qmlprojectmanager/projectitem-test.cpp new file mode 100644 index 00000000000..976841b541a --- /dev/null +++ b/tests/unit/tests/unittests/qmlprojectmanager/projectitem-test.cpp @@ -0,0 +1,719 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +#include "../utils/google-using-declarations.h" +#include "../utils/googletest.h" // IWYU pragma: keep + +#include + +#include +namespace { + +constexpr QLatin1String localTestDataDir{UNITTEST_DIR "/qmlprojectmanager/data"}; + +class QmlProjectItem : public testing::Test +{ +protected: + static void SetUpTestSuite() + { + projectItemEmpty = std::make_unique( + Utils::FilePath::fromString(localTestDataDir + "/getter-setter/empty.qmlproject"), true); + + projectItemWithQdsPrefix = std::make_unique( + Utils::FilePath::fromString(localTestDataDir + + "/getter-setter/with_qds_prefix.qmlproject"), + true); + + projectItemWithoutQdsPrefix = std::make_unique( + Utils::FilePath::fromString(localTestDataDir + + "/getter-setter/without_qds_prefix.qmlproject"), + true); + + projectItemFileFilters = std::make_unique( + Utils::FilePath::fromString(localTestDataDir + + "/file-filters/MaterialBundle.qmlproject"), + true); + } + + static void TearDownTestSuite() + { + projectItemEmpty.reset(); + projectItemWithQdsPrefix.reset(); + projectItemWithoutQdsPrefix.reset(); + projectItemFileFilters.reset(); + } + +protected: + static inline std::unique_ptr projectItemEmpty; + static inline std::unique_ptr projectItemWithQdsPrefix; + static inline std::unique_ptr + projectItemWithoutQdsPrefix; + std::unique_ptr projectItemSetters = std::make_unique< + QmlProjectManager::QmlProjectItem>(Utils::FilePath::fromString( + localTestDataDir + "/getter-setter/empty.qmlproject"), + true); + static inline std::unique_ptr projectItemFileFilters; +}; + +auto createAbsoluteFilePaths(const QStringList &fileList) +{ + return Utils::transform(fileList, [](const QString &fileName) { + return Utils::FilePath::fromString(localTestDataDir + "/file-filters").pathAppended(fileName); + }); +} + +TEST_F(QmlProjectItem, get_with_qds_prefix_main_file_project) +{ + auto mainFile = projectItemWithQdsPrefix->mainFile(); + + ASSERT_THAT(mainFile, Eq("content/App.qml")); +} + +TEST_F(QmlProjectItem, get_with_qds_prefix_main_ui_file_project) +{ + auto mainUiFile = projectItemWithQdsPrefix->mainUiFile(); + + ASSERT_THAT(mainUiFile, Eq("Screen01.ui.qml")); +} + +TEST_F(QmlProjectItem, get_with_qds_prefix_mcu_project) +{ + auto isMcuProject = projectItemWithQdsPrefix->isQt4McuProject(); + + ASSERT_TRUE(isMcuProject); +} + +TEST_F(QmlProjectItem, get_with_qds_prefix_qt_version) +{ + auto qtVersion = projectItemWithQdsPrefix->versionQt(); + + ASSERT_THAT(qtVersion, Eq("6")); +} + +TEST_F(QmlProjectItem, get_with_qds_prefix_qt_quick_version) +{ + auto qtQuickVersion = projectItemWithQdsPrefix->versionQtQuick(); + + ASSERT_THAT(qtQuickVersion, Eq("6.2")); +} + +TEST_F(QmlProjectItem, get_with_qds_prefix_design_studio_version) +{ + auto designStudioVersion = projectItemWithQdsPrefix->versionDesignStudio(); + + ASSERT_THAT(designStudioVersion, Eq("3.9")); +} + +TEST_F(QmlProjectItem, get_with_qds_prefix_source_directory) +{ + auto sourceDirectory = projectItemWithQdsPrefix->sourceDirectory().path(); + + auto expectedSourceDir = localTestDataDir + "/getter-setter"; + + ASSERT_THAT(sourceDirectory, Eq(expectedSourceDir)); +} + +TEST_F(QmlProjectItem, get_with_qds_prefix_tar_get_with_qds_prefix_directory) +{ + auto targetDirectory = projectItemWithQdsPrefix->targetDirectory(); + + ASSERT_THAT(targetDirectory, Eq("/opt/targetDirectory")); +} + +TEST_F(QmlProjectItem, get_with_qds_prefix_import_paths) +{ + auto importPaths = projectItemWithQdsPrefix->importPaths(); + + ASSERT_THAT(importPaths, UnorderedElementsAre("imports", "asset_imports")); +} + +TEST_F(QmlProjectItem, get_with_qds_prefix_file_selectors) +{ + auto fileSelectors = projectItemWithQdsPrefix->fileSelectors(); + + ASSERT_THAT(fileSelectors, UnorderedElementsAre("WXGA", "darkTheme", "ShowIndicator")); +} + +TEST_F(QmlProjectItem, get_with_qds_prefix_multi_language_support) +{ + auto multilanguageSupport = projectItemWithQdsPrefix->multilanguageSupport(); + + ASSERT_TRUE(multilanguageSupport); +} + +TEST_F(QmlProjectItem, get_with_qds_prefix_supported_languages) +{ + auto supportedLanguages = projectItemWithQdsPrefix->supportedLanguages(); + + ASSERT_THAT(supportedLanguages, UnorderedElementsAre("en", "fr")); +} + +TEST_F(QmlProjectItem, get_with_qds_prefix_primary_language) +{ + auto primaryLanguage = projectItemWithQdsPrefix->primaryLanguage(); + ; + + ASSERT_THAT(primaryLanguage, Eq("en")); +} + +TEST_F(QmlProjectItem, get_with_qds_prefix_widget_app) +{ + auto widgetApp = projectItemWithQdsPrefix->widgetApp(); + + ASSERT_TRUE(widgetApp); +} + +TEST_F(QmlProjectItem, get_with_qds_prefix_file_list) +{ + QStringList fileList; + for (const auto &file : projectItemWithQdsPrefix->files()) { + fileList.append(file.path()); + } + + auto expectedFileList = localTestDataDir + "/getter-setter/qtquickcontrols2.conf"; + + ASSERT_THAT(fileList, UnorderedElementsAre(expectedFileList)); +} + +TEST_F(QmlProjectItem, get_with_qds_prefix_shader_tool_args) +{ + auto shaderToolArgs = projectItemWithQdsPrefix->shaderToolArgs(); + + ASSERT_THAT( + shaderToolArgs, + UnorderedElementsAre("-s", "--glsl", "\"100 es,120,150\"", "--hlsl", "50", "--msl", "12")); +} + +TEST_F(QmlProjectItem, get_with_qds_prefix_shader_tool_files) +{ + auto shaderToolFiles = projectItemWithQdsPrefix->shaderToolFiles(); + + ASSERT_THAT(shaderToolFiles, UnorderedElementsAre("content/shaders/*")); +} + +TEST_F(QmlProjectItem, get_with_qds_prefix_environment) +{ + auto env = projectItemWithQdsPrefix->environment(); + + ASSERT_THAT(env, + UnorderedElementsAre( + Utils::EnvironmentItem("QT_QUICK_CONTROLS_CONF", "qtquickcontrols2.conf"))); +} + +TEST_F(QmlProjectItem, get_with_qds_prefix_force_free_type) +{ + auto forceFreeType = projectItemWithQdsPrefix->forceFreeType(); + + ASSERT_TRUE(forceFreeType); +} + +TEST_F(QmlProjectItem, get_without_qds_prefix_main_file_project) +{ + auto mainFile = projectItemWithoutQdsPrefix->mainFile(); + + ASSERT_THAT(mainFile, Eq("content/App.qml")); +} + +TEST_F(QmlProjectItem, get_without_qds_prefix_main_ui_file_project) +{ + auto mainUiFile = projectItemWithoutQdsPrefix->mainUiFile(); + + ASSERT_THAT(mainUiFile, Eq("Screen01.ui.qml")); +} + +TEST_F(QmlProjectItem, get_without_qds_prefix_mcu_project) +{ + auto isMcuProject = projectItemWithoutQdsPrefix->isQt4McuProject(); + + ASSERT_TRUE(isMcuProject); +} + +TEST_F(QmlProjectItem, get_without_qds_prefix_qt_version) +{ + auto qtVersion = projectItemWithoutQdsPrefix->versionQt(); + + ASSERT_THAT(qtVersion, Eq("6")); +} + +TEST_F(QmlProjectItem, get_without_qds_prefix_qt_quick_version) +{ + auto qtQuickVersion = projectItemWithoutQdsPrefix->versionQtQuick(); + + ASSERT_THAT(qtQuickVersion, Eq("6.2")); +} + +TEST_F(QmlProjectItem, get_without_qds_prefix_design_studio_version) +{ + auto designStudioVersion = projectItemWithoutQdsPrefix->versionDesignStudio(); + + ASSERT_THAT(designStudioVersion, Eq("3.9")); +} + +TEST_F(QmlProjectItem, get_without_qds_prefix_source_directory) +{ + auto sourceDirectory = projectItemWithoutQdsPrefix->sourceDirectory().path(); + + auto expectedSourceDir = localTestDataDir + "/getter-setter"; + + ASSERT_THAT(sourceDirectory, Eq(expectedSourceDir)); +} + +TEST_F(QmlProjectItem, get_without_qds_prefix_tar_get_without_qds_prefix_directory) +{ + auto targetDirectory = projectItemWithoutQdsPrefix->targetDirectory(); + + ASSERT_THAT(targetDirectory, Eq("/opt/targetDirectory")); +} + +TEST_F(QmlProjectItem, get_without_qds_prefix_import_paths) +{ + auto importPaths = projectItemWithoutQdsPrefix->importPaths(); + + ASSERT_THAT(importPaths, UnorderedElementsAre("imports", "asset_imports")); +} + +TEST_F(QmlProjectItem, get_without_qds_prefix_file_selectors) +{ + auto fileSelectors = projectItemWithoutQdsPrefix->fileSelectors(); + + ASSERT_THAT(fileSelectors, UnorderedElementsAre("WXGA", "darkTheme", "ShowIndicator")); +} + +TEST_F(QmlProjectItem, get_without_qds_prefix_multi_language_support) +{ + auto multilanguageSupport = projectItemWithoutQdsPrefix->multilanguageSupport(); + + ASSERT_TRUE(multilanguageSupport); +} + +TEST_F(QmlProjectItem, get_without_qds_prefix_supported_languages) +{ + auto supportedLanguages = projectItemWithoutQdsPrefix->supportedLanguages(); + + ASSERT_THAT(supportedLanguages, UnorderedElementsAre("en", "fr")); +} + +TEST_F(QmlProjectItem, get_without_qds_prefix_primary_language) +{ + auto primaryLanguage = projectItemWithoutQdsPrefix->primaryLanguage(); + ; + + ASSERT_THAT(primaryLanguage, Eq("en")); +} + +TEST_F(QmlProjectItem, get_without_qds_prefix_widget_app) +{ + auto widgetApp = projectItemWithoutQdsPrefix->widgetApp(); + + ASSERT_TRUE(widgetApp); +} + +TEST_F(QmlProjectItem, get_without_qds_prefix_file_list) +{ + QStringList fileList; + for (const auto &file : projectItemWithoutQdsPrefix->files()) { + fileList.append(file.path()); + } + + auto expectedFileList = localTestDataDir + "/getter-setter/qtquickcontrols2.conf"; + + ASSERT_THAT(fileList, UnorderedElementsAre(expectedFileList)); +} + +TEST_F(QmlProjectItem, get_without_qds_prefix_shader_tool_args) +{ + auto shaderToolArgs = projectItemWithoutQdsPrefix->shaderToolArgs(); + + ASSERT_THAT( + shaderToolArgs, + UnorderedElementsAre("-s", "--glsl", "\"100 es,120,150\"", "--hlsl", "50", "--msl", "12")); +} + +TEST_F(QmlProjectItem, get_without_qds_prefix_shader_tool_files) +{ + auto shaderToolFiles = projectItemWithoutQdsPrefix->shaderToolFiles(); + + ASSERT_THAT(shaderToolFiles, UnorderedElementsAre("content/shaders/*")); +} + +TEST_F(QmlProjectItem, get_without_qds_prefix_environment) +{ + auto env = projectItemWithoutQdsPrefix->environment(); + + ASSERT_THAT(env, + UnorderedElementsAre( + Utils::EnvironmentItem("QT_QUICK_CONTROLS_CONF", "qtquickcontrols2.conf"))); +} + +TEST_F(QmlProjectItem, get_without_qds_prefix_force_free_type) +{ + auto forceFreeType = projectItemWithoutQdsPrefix->forceFreeType(); + + ASSERT_TRUE(forceFreeType); +} + +TEST_F(QmlProjectItem, get_empty_main_file_project) +{ + auto mainFile = projectItemEmpty->mainFile(); + + ASSERT_THAT(mainFile, IsEmpty()); +} + +TEST_F(QmlProjectItem, get_empty_main_ui_file_project) +{ + auto mainUiFile = projectItemEmpty->mainUiFile(); + + ASSERT_THAT(mainUiFile, IsEmpty()); +} + +TEST_F(QmlProjectItem, get_empty_mcu_project) +{ + auto isMcuProject = projectItemEmpty->isQt4McuProject(); + + ASSERT_FALSE(isMcuProject); +} + +TEST_F(QmlProjectItem, get_empty_qt_version) +{ + auto qtVersion = projectItemEmpty->versionQt(); + + // default Qt Version is "5" for Design Studio projects + ASSERT_THAT(qtVersion, Eq("5")); +} + +TEST_F(QmlProjectItem, get_empty_qt_quick_version) +{ + auto qtQuickVersion = projectItemEmpty->versionQtQuick(); + + ASSERT_THAT(projectItemEmpty->versionQtQuick(), IsEmpty()); +} + +TEST_F(QmlProjectItem, get_empty_design_studio_version) +{ + auto designStudioVersion = projectItemEmpty->versionDesignStudio(); + + ASSERT_THAT(projectItemEmpty->versionDesignStudio(), IsEmpty()); +} + +TEST_F(QmlProjectItem, get_empty_source_directory) +{ + auto sourceDirectory = projectItemEmpty->sourceDirectory().path(); + + auto expectedSourceDir = localTestDataDir + "/getter-setter"; + + // default source directory is the project directory + ASSERT_THAT(sourceDirectory, Eq(expectedSourceDir)); +} + +TEST_F(QmlProjectItem, get_empty_tar_get_empty_directory) +{ + auto targetDirectory = projectItemEmpty->targetDirectory(); + + ASSERT_THAT(targetDirectory, IsEmpty()); +} + +TEST_F(QmlProjectItem, get_empty_import_paths) +{ + auto importPaths = projectItemEmpty->importPaths(); + + ASSERT_THAT(importPaths, IsEmpty()); +} + +TEST_F(QmlProjectItem, get_empty_file_selectors) +{ + auto fileSelectors = projectItemEmpty->fileSelectors(); + + ASSERT_THAT(fileSelectors, IsEmpty()); +} + +TEST_F(QmlProjectItem, get_empty_multi_language_support) +{ + auto multilanguageSupport = projectItemEmpty->multilanguageSupport(); + + ASSERT_FALSE(multilanguageSupport); +} + +TEST_F(QmlProjectItem, get_empty_supported_languages) +{ + auto supportedLanguages = projectItemEmpty->supportedLanguages(); + + ASSERT_THAT(supportedLanguages, IsEmpty()); +} + +TEST_F(QmlProjectItem, get_empty_primary_language) +{ + auto primaryLanguage = projectItemEmpty->primaryLanguage(); + + ASSERT_THAT(primaryLanguage, IsEmpty()); +} + +TEST_F(QmlProjectItem, get_empty_widget_app) +{ + auto widgetApp = projectItemEmpty->widgetApp(); + + ASSERT_FALSE(widgetApp); +} + +TEST_F(QmlProjectItem, get_empty_file_list) +{ + auto fileList = projectItemEmpty->files(); + + ASSERT_THAT(fileList, IsEmpty()); +} + +TEST_F(QmlProjectItem, get_empty_shader_tool_args) +{ + auto shaderToolArgs = projectItemEmpty->shaderToolArgs(); + + ASSERT_THAT(shaderToolArgs, IsEmpty()); +} + +TEST_F(QmlProjectItem, get_empty_shader_tool_files) +{ + auto shaderToolFiles = projectItemEmpty->shaderToolFiles(); + + ASSERT_THAT(shaderToolFiles, IsEmpty()); +} + +TEST_F(QmlProjectItem, get_empty_environment) +{ + auto env = projectItemEmpty->environment(); + + ASSERT_THAT(env, IsEmpty()); +} + +TEST_F(QmlProjectItem, get_empty_force_free_type) +{ + auto forceFreeType = projectItemEmpty->forceFreeType(); + + ASSERT_FALSE(forceFreeType); +} + +TEST_F(QmlProjectItem, set_main_file_project) +{ + projectItemSetters->setMainFile("testing"); + + auto mainFile = projectItemSetters->mainFile(); + + ASSERT_THAT(mainFile, Eq("testing")); +} + +TEST_F(QmlProjectItem, set_main_ui_file_project) +{ + projectItemSetters->setMainUiFile("testing"); + + auto mainUiFile = projectItemSetters->mainUiFile(); + + ASSERT_THAT(mainUiFile, Eq("testing")); +} + +TEST_F(QmlProjectItem, set_import_paths) +{ + projectItemSetters->setImportPaths({"testing"}); + + auto importPaths = projectItemSetters->importPaths(); + + ASSERT_THAT(importPaths, UnorderedElementsAre("testing")); +} + +TEST_F(QmlProjectItem, add_import_paths) +{ + projectItemSetters->setImportPaths({}); + projectItemSetters->addImportPath("testing"); + + auto importPaths = projectItemSetters->importPaths(); + + ASSERT_THAT(importPaths, UnorderedElementsAre("testing")); +} + +TEST_F(QmlProjectItem, set_file_selectors) +{ + projectItemSetters->setFileSelectors({"testing"}); + + auto fileSelectors = projectItemSetters->fileSelectors(); + + ASSERT_THAT(fileSelectors, UnorderedElementsAre("testing")); +} + +TEST_F(QmlProjectItem, add_file_selectors) +{ + projectItemSetters->setFileSelectors({}); + projectItemSetters->addFileSelector("testing"); + + auto fileSelectors = projectItemSetters->fileSelectors(); + + ASSERT_THAT(fileSelectors, UnorderedElementsAre("testing")); +} + +TEST_F(QmlProjectItem, set_multi_language_support) +{ + projectItemSetters->setMultilanguageSupport(true); + + auto multilanguageSupport = projectItemSetters->multilanguageSupport(); + + ASSERT_TRUE(multilanguageSupport); +} + +TEST_F(QmlProjectItem, set_supported_languages) +{ + projectItemSetters->setSupportedLanguages({"testing"}); + + auto supportedLanguages = projectItemSetters->supportedLanguages(); + + ASSERT_THAT(supportedLanguages, UnorderedElementsAre("testing")); +} + +TEST_F(QmlProjectItem, add_supported_languages) +{ + projectItemSetters->setSupportedLanguages({}); + projectItemSetters->addSupportedLanguage("testing"); + + auto supportedLanguages = projectItemSetters->supportedLanguages(); + + ASSERT_THAT(supportedLanguages, UnorderedElementsAre("testing")); +} + +TEST_F(QmlProjectItem, set_primary_language) +{ + projectItemSetters->setPrimaryLanguage("testing"); + + auto primaryLanguage = projectItemSetters->primaryLanguage(); + ; + + ASSERT_THAT(primaryLanguage, Eq("testing")); +} + +TEST_F(QmlProjectItem, set_widget_app) +{ + projectItemSetters->setWidgetApp(true); + + auto widgetApp = projectItemSetters->widgetApp(); + + ASSERT_TRUE(widgetApp); +} + +TEST_F(QmlProjectItem, set_shader_tool_args) +{ + projectItemSetters->setShaderToolArgs({"testing"}); + + auto shaderToolArgs = projectItemSetters->shaderToolArgs(); + + ASSERT_THAT(shaderToolArgs, UnorderedElementsAre("testing")); +} + +TEST_F(QmlProjectItem, add_shader_tool_args) +{ + projectItemSetters->setShaderToolArgs({}); + projectItemSetters->addShaderToolArg("testing"); + + auto shaderToolArgs = projectItemSetters->shaderToolArgs(); + + ASSERT_THAT(shaderToolArgs, UnorderedElementsAre("testing")); +} + +TEST_F(QmlProjectItem, set_shader_tool_files) +{ + projectItemSetters->setShaderToolFiles({"testing"}); + + auto shaderToolFiles = projectItemSetters->shaderToolFiles(); + + ASSERT_THAT(shaderToolFiles, UnorderedElementsAre("testing")); +} + +TEST_F(QmlProjectItem, add_shader_tool_files) +{ + projectItemSetters->setShaderToolFiles({}); + projectItemSetters->addShaderToolFile("testing"); + + auto shaderToolFiles = projectItemSetters->shaderToolFiles(); + + ASSERT_THAT(shaderToolFiles, UnorderedElementsAre("testing")); +} + +TEST_F(QmlProjectItem, add_environment) +{ + projectItemSetters->addToEnviroment("testing", "testing"); + auto envs = projectItemSetters->environment(); + + Utils::EnvironmentItems expectedEnvs; + expectedEnvs.push_back({"testing", "testing"}); + + ASSERT_EQ(envs, expectedEnvs); +} + +TEST_F(QmlProjectItem, set_force_free_type_true) +{ + projectItemSetters->setForceFreeType(true); + + ASSERT_EQ(projectItemSetters->forceFreeType(), true); +} + +TEST_F(QmlProjectItem, set_force_free_type_false) +{ + projectItemSetters->setForceFreeType(false); + + ASSERT_EQ(projectItemSetters->forceFreeType(), false); +} + +TEST_F(QmlProjectItem, set_qt_version) +{ + projectItemSetters->setVersionQt("6"); + + ASSERT_EQ(projectItemSetters->versionQt().toStdString(), "6"); +} + +TEST_F(QmlProjectItem, set_qt_quick_version) +{ + projectItemSetters->setVersionQtQuick("6"); + + ASSERT_EQ(projectItemSetters->versionQtQuick(), "6"); +} + +TEST_F(QmlProjectItem, set_design_studio_version) +{ + projectItemSetters->setVersionDesignStudio("6"); + + ASSERT_EQ(projectItemSetters->versionDesignStudio(), "6"); +} + +// TODO: We should move these 2 tests into the integration tests +TEST_F(QmlProjectItem, test_file_filters) +{ + // GIVEN + auto fileListPath = Utils::FilePath::fromString(localTestDataDir + "/file-filters/filelist.txt"); + QStringList fileNameList + = QString::fromUtf8(fileListPath.fileContents().value()).replace("\r\n", "\n").split("\n"); + auto expectedAbsoluteFilePaths = createAbsoluteFilePaths(fileNameList); + + // WHEN + auto filePaths = projectItemFileFilters->files(); + + // THEN + ASSERT_THAT(filePaths, UnorderedElementsAreArray(expectedAbsoluteFilePaths)); +} + +TEST_F(QmlProjectItem, matches_file) +{ + // GIVEN + auto fileSearched = localTestDataDir + "/file-filters/content/MaterialNames.qml"; + + // WHEN + auto fileFound = projectItemFileFilters->matchesFile(fileSearched); + + // THEN + ASSERT_TRUE(fileFound); +} + +TEST_F(QmlProjectItem, not_matches_file) +{ + // GIVEN + auto fileSearched = localTestDataDir + "/file-filters/content/non-existing-file.qwerty"; + + // WHEN + auto fileFound = projectItemFileFilters->matchesFile(fileSearched); + + // THEN + ASSERT_FALSE(fileFound); +} + +} // namespace diff --git a/tests/unit/tests/unittests/sqlite/CMakeLists.txt b/tests/unit/tests/unittests/sqlite/CMakeLists.txt new file mode 100644 index 00000000000..ba178fade6e --- /dev/null +++ b/tests/unit/tests/unittests/sqlite/CMakeLists.txt @@ -0,0 +1,21 @@ +# Sqlite tests +extend_qtc_test(unittest +SOURCES + lastchangedrowid-test.cpp + sqlitealgorithms-test.cpp + sqliteindex-test.cpp + sqliteteststatement.h + sqlitetransaction-test.cpp + sqlitecolumn-test.cpp + sqlitedatabasebackend-test.cpp + sqlitedatabase-test.cpp + sqlitefunctionregistry-test.cpp + sqlitesessions-test.cpp + sqlitestatement-test.cpp + sqlitetable-test.cpp + sqlstatementbuilder-test.cpp + createtablesqlstatementbuilder-test.cpp + sqlitevalue-test.cpp +) + +unittest_copy_data_folder() diff --git a/tests/unit/unittest/createtablesqlstatementbuilder-test.cpp b/tests/unit/tests/unittests/sqlite/createtablesqlstatementbuilder-test.cpp similarity index 80% rename from tests/unit/unittest/createtablesqlstatementbuilder-test.cpp rename to tests/unit/tests/unittests/sqlite/createtablesqlstatementbuilder-test.cpp index 050b626fb15..f9ae5bcfdbc 100644 --- a/tests/unit/unittest/createtablesqlstatementbuilder-test.cpp +++ b/tests/unit/tests/unittests/sqlite/createtablesqlstatementbuilder-test.cpp @@ -1,7 +1,7 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" #include #include @@ -49,19 +49,19 @@ protected: Builder builder; }; -TEST_F(CreateTableSqlStatementBuilder, IsNotValidAfterCreation) +TEST_F(CreateTableSqlStatementBuilder, is_not_valid_after_creation) { ASSERT_FALSE(builder.isValid()); } -TEST_F(CreateTableSqlStatementBuilder, IsValidAfterBinding) +TEST_F(CreateTableSqlStatementBuilder, is_valid_after_binding) { bindValues(); ASSERT_TRUE(builder.isValid()); } -TEST_F(CreateTableSqlStatementBuilder, InvalidAfterClear) +TEST_F(CreateTableSqlStatementBuilder, invalid_after_clear) { bindValues(); @@ -70,7 +70,7 @@ TEST_F(CreateTableSqlStatementBuilder, InvalidAfterClear) ASSERT_TRUE(!builder.isValid()); } -TEST_F(CreateTableSqlStatementBuilder, NoSqlStatementAfterClear) +TEST_F(CreateTableSqlStatementBuilder, no_sql_statement_after_clear) { bindValues(); builder.sqlStatement(); @@ -80,7 +80,7 @@ TEST_F(CreateTableSqlStatementBuilder, NoSqlStatementAfterClear) ASSERT_THROW(builder.sqlStatement(), SqlStatementBuilderException); } -TEST_F(CreateTableSqlStatementBuilder, SqlStatement) +TEST_F(CreateTableSqlStatementBuilder, sql_statement) { bindValues(); @@ -88,7 +88,7 @@ TEST_F(CreateTableSqlStatementBuilder, SqlStatement) "CREATE TABLE test(id INTEGER PRIMARY KEY, name TEXT, number NUMERIC)"); } -TEST_F(CreateTableSqlStatementBuilder, AddColumnToExistingColumns) +TEST_F(CreateTableSqlStatementBuilder, add_column_to_existing_columns) { bindValues(); @@ -98,7 +98,7 @@ TEST_F(CreateTableSqlStatementBuilder, AddColumnToExistingColumns) "CREATE TABLE test(id INTEGER PRIMARY KEY, name TEXT, number NUMERIC, number2 REAL)"); } -TEST_F(CreateTableSqlStatementBuilder, ChangeTable) +TEST_F(CreateTableSqlStatementBuilder, change_table) { bindValues(); @@ -108,7 +108,7 @@ TEST_F(CreateTableSqlStatementBuilder, ChangeTable) "CREATE TABLE test2(id INTEGER PRIMARY KEY, name TEXT, number NUMERIC)"); } -TEST_F(CreateTableSqlStatementBuilder, IsInvalidAfterClearColumsOnly) +TEST_F(CreateTableSqlStatementBuilder, is_invalid_after_clear_colums_only) { bindValues(); builder.sqlStatement(); @@ -118,7 +118,7 @@ TEST_F(CreateTableSqlStatementBuilder, IsInvalidAfterClearColumsOnly) ASSERT_THROW(builder.sqlStatement(), SqlStatementBuilderException); } -TEST_F(CreateTableSqlStatementBuilder, ClearColumnsAndAddColumnNewColumns) +TEST_F(CreateTableSqlStatementBuilder, clear_columns_and_add_column_new_columns) { bindValues(); builder.clearColumns(); @@ -130,7 +130,7 @@ TEST_F(CreateTableSqlStatementBuilder, ClearColumnsAndAddColumnNewColumns) "CREATE TABLE test(name3 TEXT, number3 REAL)"); } -TEST_F(CreateTableSqlStatementBuilder, SetWitoutRowId) +TEST_F(CreateTableSqlStatementBuilder, set_witout_row_id) { bindValues(); @@ -140,7 +140,7 @@ TEST_F(CreateTableSqlStatementBuilder, SetWitoutRowId) "CREATE TABLE test(id INTEGER PRIMARY KEY, name TEXT, number NUMERIC) WITHOUT ROWID"); } -TEST_F(CreateTableSqlStatementBuilder, SetColumnDefinitions) +TEST_F(CreateTableSqlStatementBuilder, set_column_definitions) { builder.setTableName("test"); @@ -150,7 +150,7 @@ TEST_F(CreateTableSqlStatementBuilder, SetColumnDefinitions) "CREATE TABLE test(id INTEGER PRIMARY KEY, name TEXT, number NUMERIC)"); } -TEST_F(CreateTableSqlStatementBuilder, UniqueContraint) +TEST_F(CreateTableSqlStatementBuilder, unique_contraint) { builder.setTableName("test"); @@ -160,7 +160,7 @@ TEST_F(CreateTableSqlStatementBuilder, UniqueContraint) "CREATE TABLE test(id INTEGER UNIQUE)"); } -TEST_F(CreateTableSqlStatementBuilder, IfNotExitsModifier) +TEST_F(CreateTableSqlStatementBuilder, if_not_exits_modifier) { builder.setTableName("test"); builder.addColumn("id", ColumnType::Integer, {}); @@ -171,7 +171,7 @@ TEST_F(CreateTableSqlStatementBuilder, IfNotExitsModifier) "CREATE TABLE IF NOT EXISTS test(id INTEGER)"); } -TEST_F(CreateTableSqlStatementBuilder, TemporaryTable) +TEST_F(CreateTableSqlStatementBuilder, temporary_table) { builder.setTableName("test"); builder.addColumn("id", ColumnType::Integer, {}); @@ -182,7 +182,7 @@ TEST_F(CreateTableSqlStatementBuilder, TemporaryTable) "CREATE TEMPORARY TABLE test(id INTEGER)"); } -TEST_F(CreateTableSqlStatementBuilder, ForeignKeyWithoutColumn) +TEST_F(CreateTableSqlStatementBuilder, foreign_key_without_column) { builder.setTableName("test"); @@ -191,7 +191,7 @@ TEST_F(CreateTableSqlStatementBuilder, ForeignKeyWithoutColumn) ASSERT_THAT(builder.sqlStatement(), "CREATE TABLE test(id INTEGER REFERENCES otherTable)"); } -TEST_F(CreateTableSqlStatementBuilder, ForeignKeyWithColumn) +TEST_F(CreateTableSqlStatementBuilder, foreign_key_with_column) { builder.setTableName("test"); @@ -201,7 +201,7 @@ TEST_F(CreateTableSqlStatementBuilder, ForeignKeyWithColumn) "CREATE TABLE test(id INTEGER REFERENCES otherTable(otherColumn))"); } -TEST_F(CreateTableSqlStatementBuilder, ForeignKeyUpdateNoAction) +TEST_F(CreateTableSqlStatementBuilder, foreign_key_update_no_action) { builder.setTableName("test"); @@ -211,7 +211,7 @@ TEST_F(CreateTableSqlStatementBuilder, ForeignKeyUpdateNoAction) "CREATE TABLE test(id INTEGER REFERENCES otherTable(otherColumn))"); } -TEST_F(CreateTableSqlStatementBuilder, ForeignKeyUpdateRestrict) +TEST_F(CreateTableSqlStatementBuilder, foreign_key_update_restrict) { builder.setTableName("test"); @@ -224,7 +224,7 @@ TEST_F(CreateTableSqlStatementBuilder, ForeignKeyUpdateRestrict) "CREATE TABLE test(id INTEGER REFERENCES otherTable(otherColumn) ON UPDATE RESTRICT)"); } -TEST_F(CreateTableSqlStatementBuilder, ForeignKeyUpdateSetNull) +TEST_F(CreateTableSqlStatementBuilder, foreign_key_update_set_null) { builder.setTableName("test"); @@ -237,7 +237,7 @@ TEST_F(CreateTableSqlStatementBuilder, ForeignKeyUpdateSetNull) "CREATE TABLE test(id INTEGER REFERENCES otherTable(otherColumn) ON UPDATE SET NULL)"); } -TEST_F(CreateTableSqlStatementBuilder, ForeignKeyUpdateSetDefault) +TEST_F(CreateTableSqlStatementBuilder, foreign_key_update_set_default) { builder.setTableName("test"); @@ -250,7 +250,7 @@ TEST_F(CreateTableSqlStatementBuilder, ForeignKeyUpdateSetDefault) "CREATE TABLE test(id INTEGER REFERENCES otherTable(otherColumn) ON UPDATE SET DEFAULT)"); } -TEST_F(CreateTableSqlStatementBuilder, ForeignKeyUpdateCascade) +TEST_F(CreateTableSqlStatementBuilder, foreign_key_update_cascade) { builder.setTableName("test"); @@ -263,7 +263,7 @@ TEST_F(CreateTableSqlStatementBuilder, ForeignKeyUpdateCascade) "CREATE TABLE test(id INTEGER REFERENCES otherTable(otherColumn) ON UPDATE CASCADE)"); } -TEST_F(CreateTableSqlStatementBuilder, ForeignKeyDeleteNoAction) +TEST_F(CreateTableSqlStatementBuilder, foreign_key_delete_no_action) { builder.setTableName("test"); @@ -273,7 +273,7 @@ TEST_F(CreateTableSqlStatementBuilder, ForeignKeyDeleteNoAction) "CREATE TABLE test(id INTEGER REFERENCES otherTable(otherColumn))"); } -TEST_F(CreateTableSqlStatementBuilder, ForeignKeyDeleteRestrict) +TEST_F(CreateTableSqlStatementBuilder, foreign_key_delete_restrict) { builder.setTableName("test"); @@ -286,7 +286,7 @@ TEST_F(CreateTableSqlStatementBuilder, ForeignKeyDeleteRestrict) "CREATE TABLE test(id INTEGER REFERENCES otherTable(otherColumn) ON DELETE RESTRICT)"); } -TEST_F(CreateTableSqlStatementBuilder, ForeignKeyDeleteSetNull) +TEST_F(CreateTableSqlStatementBuilder, foreign_key_delete_set_null) { builder.setTableName("test"); @@ -299,7 +299,7 @@ TEST_F(CreateTableSqlStatementBuilder, ForeignKeyDeleteSetNull) "CREATE TABLE test(id INTEGER REFERENCES otherTable(otherColumn) ON DELETE SET NULL)"); } -TEST_F(CreateTableSqlStatementBuilder, ForeignKeyDeleteSetDefault) +TEST_F(CreateTableSqlStatementBuilder, foreign_key_delete_set_default) { builder.setTableName("test"); @@ -312,7 +312,7 @@ TEST_F(CreateTableSqlStatementBuilder, ForeignKeyDeleteSetDefault) "CREATE TABLE test(id INTEGER REFERENCES otherTable(otherColumn) ON DELETE SET DEFAULT)"); } -TEST_F(CreateTableSqlStatementBuilder, ForeignKeyDeleteCascade) +TEST_F(CreateTableSqlStatementBuilder, foreign_key_delete_cascade) { builder.setTableName("test"); @@ -325,7 +325,7 @@ TEST_F(CreateTableSqlStatementBuilder, ForeignKeyDeleteCascade) "CREATE TABLE test(id INTEGER REFERENCES otherTable(otherColumn) ON DELETE CASCADE)"); } -TEST_F(CreateTableSqlStatementBuilder, ForeignKeyDeleteAndUpdateAction) +TEST_F(CreateTableSqlStatementBuilder, foreign_key_delete_and_update_action) { builder.setTableName("test"); @@ -341,7 +341,7 @@ TEST_F(CreateTableSqlStatementBuilder, ForeignKeyDeleteAndUpdateAction) "DEFAULT ON DELETE CASCADE)"); } -TEST_F(CreateTableSqlStatementBuilder, ForeignKeyDeferred) +TEST_F(CreateTableSqlStatementBuilder, foreign_key_deferred) { builder.setTableName("test"); @@ -358,7 +358,7 @@ TEST_F(CreateTableSqlStatementBuilder, ForeignKeyDeferred) "DEFAULT ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED)"); } -TEST_F(CreateTableSqlStatementBuilder, NotNullConstraint) +TEST_F(CreateTableSqlStatementBuilder, not_null_constraint) { builder.setTableName("test"); @@ -367,7 +367,7 @@ TEST_F(CreateTableSqlStatementBuilder, NotNullConstraint) ASSERT_THAT(builder.sqlStatement(), "CREATE TABLE test(id INTEGER NOT NULL)"); } -TEST_F(CreateTableSqlStatementBuilder, NotNullAndUniqueConstraint) +TEST_F(CreateTableSqlStatementBuilder, not_null_and_unique_constraint) { builder.setTableName("test"); @@ -376,7 +376,7 @@ TEST_F(CreateTableSqlStatementBuilder, NotNullAndUniqueConstraint) ASSERT_THAT(builder.sqlStatement(), "CREATE TABLE test(id INTEGER UNIQUE NOT NULL)"); } -TEST_F(CreateTableSqlStatementBuilder, Check) +TEST_F(CreateTableSqlStatementBuilder, check) { builder.setTableName("test"); @@ -385,7 +385,7 @@ TEST_F(CreateTableSqlStatementBuilder, Check) ASSERT_THAT(builder.sqlStatement(), "CREATE TABLE test(id TEXT CHECK (id != ''))"); } -TEST_F(CreateTableSqlStatementBuilder, DefaultValueInt) +TEST_F(CreateTableSqlStatementBuilder, default_value_int) { builder.setTableName("test"); @@ -394,7 +394,7 @@ TEST_F(CreateTableSqlStatementBuilder, DefaultValueInt) ASSERT_THAT(builder.sqlStatement(), "CREATE TABLE test(id INTEGER DEFAULT 1)"); } -TEST_F(CreateTableSqlStatementBuilder, DefaultValueFloat) +TEST_F(CreateTableSqlStatementBuilder, default_value_float) { builder.setTableName("test"); @@ -403,7 +403,7 @@ TEST_F(CreateTableSqlStatementBuilder, DefaultValueFloat) ASSERT_THAT(builder.sqlStatement(), "CREATE TABLE test(id REAL DEFAULT 1.100000)"); } -TEST_F(CreateTableSqlStatementBuilder, DefaultValueString) +TEST_F(CreateTableSqlStatementBuilder, default_value_string) { builder.setTableName("test"); @@ -412,7 +412,7 @@ TEST_F(CreateTableSqlStatementBuilder, DefaultValueString) ASSERT_THAT(builder.sqlStatement(), "CREATE TABLE test(id TEXT DEFAULT 'foo')"); } -TEST_F(CreateTableSqlStatementBuilder, DefaultExpression) +TEST_F(CreateTableSqlStatementBuilder, default_expression) { builder.setTableName("test"); @@ -424,7 +424,7 @@ TEST_F(CreateTableSqlStatementBuilder, DefaultExpression) "CREATE TABLE test(id INTEGER DEFAULT (SELECT name FROM foo WHERE id=?))"); } -TEST_F(CreateTableSqlStatementBuilder, Collation) +TEST_F(CreateTableSqlStatementBuilder, collation) { builder.setTableName("test"); @@ -433,7 +433,7 @@ TEST_F(CreateTableSqlStatementBuilder, Collation) ASSERT_THAT(builder.sqlStatement(), "CREATE TABLE test(id TEXT COLLATE unicode)"); } -TEST_F(CreateTableSqlStatementBuilder, GeneratedAlwaysStored) +TEST_F(CreateTableSqlStatementBuilder, generated_always_stored) { builder.setTableName("test"); @@ -447,7 +447,7 @@ TEST_F(CreateTableSqlStatementBuilder, GeneratedAlwaysStored) "CREATE TABLE test(id TEXT GENERATED ALWAYS AS (SELECT name FROM foo WHERE id=?) STORED)"); } -TEST_F(CreateTableSqlStatementBuilder, GeneratedAlwaysVirtual) +TEST_F(CreateTableSqlStatementBuilder, generated_always_virtual) { builder.setTableName("test"); @@ -461,7 +461,7 @@ TEST_F(CreateTableSqlStatementBuilder, GeneratedAlwaysVirtual) "VIRTUAL)"); } -TEST_F(CreateTableSqlStatementBuilder, PrimaryKeyAutoincrement) +TEST_F(CreateTableSqlStatementBuilder, primary_key_autoincrement) { builder.setTableName("test"); @@ -470,7 +470,7 @@ TEST_F(CreateTableSqlStatementBuilder, PrimaryKeyAutoincrement) ASSERT_THAT(builder.sqlStatement(), "CREATE TABLE test(id INTEGER PRIMARY KEY AUTOINCREMENT)"); } -TEST_F(CreateTableSqlStatementBuilder, BlobType) +TEST_F(CreateTableSqlStatementBuilder, blob_type) { builder.setTableName("test"); @@ -479,7 +479,7 @@ TEST_F(CreateTableSqlStatementBuilder, BlobType) ASSERT_THAT(builder.sqlStatement(), "CREATE TABLE test(data BLOB)"); } -TEST_F(CreateTableSqlStatementBuilder, TablePrimaryKeyConstaint) +TEST_F(CreateTableSqlStatementBuilder, table_primary_key_constaint) { builder.setTableName("test"); builder.addColumn("id", ColumnType::Integer); @@ -491,7 +491,7 @@ TEST_F(CreateTableSqlStatementBuilder, TablePrimaryKeyConstaint) ASSERT_THAT(statement, "CREATE TABLE test(id INTEGER, text TEXT, PRIMARY KEY(id, text))"); } -TEST_F(CreateTableSqlStatementBuilder, NoneColumnTypeStringConversion) +TEST_F(CreateTableSqlStatementBuilder, none_column_type_string_conversion) { builder.setTableName("test"); builder.addColumn("id", ColumnType::None); @@ -501,7 +501,7 @@ TEST_F(CreateTableSqlStatementBuilder, NoneColumnTypeStringConversion) ASSERT_THAT(statement, "CREATE TABLE test(id)"); } -TEST_F(CreateTableSqlStatementBuilder, NumericColumnTypeStringConversion) +TEST_F(CreateTableSqlStatementBuilder, numeric_column_type_string_conversion) { builder.setTableName("test"); builder.addColumn("id", ColumnType::Numeric); @@ -511,7 +511,7 @@ TEST_F(CreateTableSqlStatementBuilder, NumericColumnTypeStringConversion) ASSERT_THAT(statement, "CREATE TABLE test(id NUMERIC)"); } -TEST_F(CreateTableSqlStatementBuilder, IntegerColumnTypeStringConversion) +TEST_F(CreateTableSqlStatementBuilder, integer_column_type_string_conversion) { builder.setTableName("test"); builder.addColumn("id", ColumnType::Integer); @@ -521,7 +521,7 @@ TEST_F(CreateTableSqlStatementBuilder, IntegerColumnTypeStringConversion) ASSERT_THAT(statement, "CREATE TABLE test(id INTEGER)"); } -TEST_F(CreateTableSqlStatementBuilder, RealColumnTypeStringConversion) +TEST_F(CreateTableSqlStatementBuilder, real_column_type_string_conversion) { builder.setTableName("test"); builder.addColumn("id", ColumnType::Real); @@ -531,7 +531,7 @@ TEST_F(CreateTableSqlStatementBuilder, RealColumnTypeStringConversion) ASSERT_THAT(statement, "CREATE TABLE test(id REAL)"); } -TEST_F(CreateTableSqlStatementBuilder, TextColumnTypeStringConversion) +TEST_F(CreateTableSqlStatementBuilder, text_column_type_string_conversion) { builder.setTableName("test"); builder.addColumn("id", ColumnType::Text); @@ -541,7 +541,7 @@ TEST_F(CreateTableSqlStatementBuilder, TextColumnTypeStringConversion) ASSERT_THAT(statement, "CREATE TABLE test(id TEXT)"); } -TEST_F(CreateTableSqlStatementBuilder, BlobColumnTypeStringConversion) +TEST_F(CreateTableSqlStatementBuilder, blob_column_type_string_conversion) { builder.setTableName("test"); builder.addColumn("id", ColumnType::Blob); @@ -579,19 +579,19 @@ protected: Sqlite::CreateTableSqlStatementBuilder builder; }; -TEST_F(CreateStrictTableSqlStatementBuilder, IsNotValidAfterCreation) +TEST_F(CreateStrictTableSqlStatementBuilder, is_not_valid_after_creation) { ASSERT_FALSE(builder.isValid()); } -TEST_F(CreateStrictTableSqlStatementBuilder, IsValidAfterBinding) +TEST_F(CreateStrictTableSqlStatementBuilder, is_valid_after_binding) { bindValues(); ASSERT_TRUE(builder.isValid()); } -TEST_F(CreateStrictTableSqlStatementBuilder, InvalidAfterClear) +TEST_F(CreateStrictTableSqlStatementBuilder, invalid_after_clear) { bindValues(); @@ -600,7 +600,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, InvalidAfterClear) ASSERT_TRUE(!builder.isValid()); } -TEST_F(CreateStrictTableSqlStatementBuilder, NoSqlStatementAfterClear) +TEST_F(CreateStrictTableSqlStatementBuilder, no_sql_statement_after_clear) { bindValues(); builder.sqlStatement(); @@ -610,7 +610,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, NoSqlStatementAfterClear) ASSERT_THROW(builder.sqlStatement(), SqlStatementBuilderException); } -TEST_F(CreateStrictTableSqlStatementBuilder, SqlStatement) +TEST_F(CreateStrictTableSqlStatementBuilder, sql_statement) { bindValues(); @@ -618,7 +618,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, SqlStatement) "CREATE TABLE test(id INTEGER PRIMARY KEY, name TEXT, number ANY) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, AddColumnToExistingColumns) +TEST_F(CreateStrictTableSqlStatementBuilder, add_column_to_existing_columns) { bindValues(); @@ -629,7 +629,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, AddColumnToExistingColumns) "CREATE TABLE test(id INTEGER PRIMARY KEY, name TEXT, number ANY, number2 REAL) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, ChangeTable) +TEST_F(CreateStrictTableSqlStatementBuilder, change_table) { bindValues(); @@ -639,7 +639,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, ChangeTable) "CREATE TABLE test2(id INTEGER PRIMARY KEY, name TEXT, number ANY) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, IsInvalidAfterClearColumsOnly) +TEST_F(CreateStrictTableSqlStatementBuilder, is_invalid_after_clear_colums_only) { bindValues(); builder.sqlStatement(); @@ -649,7 +649,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, IsInvalidAfterClearColumsOnly) ASSERT_THROW(builder.sqlStatement(), SqlStatementBuilderException); } -TEST_F(CreateStrictTableSqlStatementBuilder, ClearColumnsAndAddColumnNewColumns) +TEST_F(CreateStrictTableSqlStatementBuilder, clear_columns_and_add_column_new_columns) { bindValues(); builder.clearColumns(); @@ -660,7 +660,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, ClearColumnsAndAddColumnNewColumns) ASSERT_THAT(builder.sqlStatement(), "CREATE TABLE test(name3 TEXT, number3 REAL) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, SetWitoutRowId) +TEST_F(CreateStrictTableSqlStatementBuilder, set_witout_row_id) { bindValues(); @@ -671,7 +671,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, SetWitoutRowId) "CREATE TABLE test(id INTEGER PRIMARY KEY, name TEXT, number ANY) WITHOUT ROWID, STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, SetColumnDefinitions) +TEST_F(CreateStrictTableSqlStatementBuilder, set_column_definitions) { builder.setTableName("test"); @@ -681,7 +681,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, SetColumnDefinitions) "CREATE TABLE test(id INTEGER PRIMARY KEY, name TEXT, number ANY) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, UniqueContraint) +TEST_F(CreateStrictTableSqlStatementBuilder, unique_contraint) { builder.setTableName("test"); @@ -690,7 +690,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, UniqueContraint) ASSERT_THAT(builder.sqlStatement(), "CREATE TABLE test(id INTEGER UNIQUE) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, IfNotExitsModifier) +TEST_F(CreateStrictTableSqlStatementBuilder, if_not_exits_modifier) { builder.setTableName("test"); builder.addColumn("id", StrictColumnType::Integer, {}); @@ -700,7 +700,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, IfNotExitsModifier) ASSERT_THAT(builder.sqlStatement(), "CREATE TABLE IF NOT EXISTS test(id INTEGER) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, TemporaryTable) +TEST_F(CreateStrictTableSqlStatementBuilder, temporary_table) { builder.setTableName("test"); builder.addColumn("id", StrictColumnType::Integer, {}); @@ -710,7 +710,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, TemporaryTable) ASSERT_THAT(builder.sqlStatement(), "CREATE TEMPORARY TABLE test(id INTEGER) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, ForeignKeyWithoutColumn) +TEST_F(CreateStrictTableSqlStatementBuilder, foreign_key_without_column) { builder.setTableName("test"); @@ -719,7 +719,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, ForeignKeyWithoutColumn) ASSERT_THAT(builder.sqlStatement(), "CREATE TABLE test(id INTEGER REFERENCES otherTable) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, ForeignKeyWithColumn) +TEST_F(CreateStrictTableSqlStatementBuilder, foreign_key_with_column) { builder.setTableName("test"); @@ -729,7 +729,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, ForeignKeyWithColumn) "CREATE TABLE test(id INTEGER REFERENCES otherTable(otherColumn)) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, ForeignKeyUpdateNoAction) +TEST_F(CreateStrictTableSqlStatementBuilder, foreign_key_update_no_action) { builder.setTableName("test"); @@ -739,7 +739,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, ForeignKeyUpdateNoAction) "CREATE TABLE test(id INTEGER REFERENCES otherTable(otherColumn)) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, ForeignKeyUpdateRestrict) +TEST_F(CreateStrictTableSqlStatementBuilder, foreign_key_update_restrict) { builder.setTableName("test"); @@ -752,7 +752,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, ForeignKeyUpdateRestrict) "RESTRICT) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, ForeignKeyUpdateSetNull) +TEST_F(CreateStrictTableSqlStatementBuilder, foreign_key_update_set_null) { builder.setTableName("test"); @@ -765,7 +765,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, ForeignKeyUpdateSetNull) "NULL) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, ForeignKeyUpdateSetDefault) +TEST_F(CreateStrictTableSqlStatementBuilder, foreign_key_update_set_default) { builder.setTableName("test"); @@ -778,7 +778,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, ForeignKeyUpdateSetDefault) "DEFAULT) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, ForeignKeyUpdateCascade) +TEST_F(CreateStrictTableSqlStatementBuilder, foreign_key_update_cascade) { builder.setTableName("test"); @@ -791,7 +791,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, ForeignKeyUpdateCascade) "CASCADE) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, ForeignKeyDeleteNoAction) +TEST_F(CreateStrictTableSqlStatementBuilder, foreign_key_delete_no_action) { builder.setTableName("test"); @@ -801,7 +801,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, ForeignKeyDeleteNoAction) "CREATE TABLE test(id INTEGER REFERENCES otherTable(otherColumn)) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, ForeignKeyDeleteRestrict) +TEST_F(CreateStrictTableSqlStatementBuilder, foreign_key_delete_restrict) { builder.setTableName("test"); @@ -814,7 +814,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, ForeignKeyDeleteRestrict) "RESTRICT) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, ForeignKeyDeleteSetNull) +TEST_F(CreateStrictTableSqlStatementBuilder, foreign_key_delete_set_null) { builder.setTableName("test"); @@ -827,7 +827,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, ForeignKeyDeleteSetNull) "NULL) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, ForeignKeyDeleteSetDefault) +TEST_F(CreateStrictTableSqlStatementBuilder, foreign_key_delete_set_default) { builder.setTableName("test"); @@ -840,7 +840,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, ForeignKeyDeleteSetDefault) "DEFAULT) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, ForeignKeyDeleteCascade) +TEST_F(CreateStrictTableSqlStatementBuilder, foreign_key_delete_cascade) { builder.setTableName("test"); @@ -853,7 +853,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, ForeignKeyDeleteCascade) "CASCADE) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, ForeignKeyDeleteAndUpdateAction) +TEST_F(CreateStrictTableSqlStatementBuilder, foreign_key_delete_and_update_action) { builder.setTableName("test"); @@ -869,7 +869,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, ForeignKeyDeleteAndUpdateAction) "DEFAULT ON DELETE CASCADE) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, ForeignKeyDeferred) +TEST_F(CreateStrictTableSqlStatementBuilder, foreign_key_deferred) { builder.setTableName("test"); @@ -886,7 +886,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, ForeignKeyDeferred) "DEFAULT ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, NotNullConstraint) +TEST_F(CreateStrictTableSqlStatementBuilder, not_null_constraint) { builder.setTableName("test"); @@ -895,7 +895,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, NotNullConstraint) ASSERT_THAT(builder.sqlStatement(), "CREATE TABLE test(id INTEGER NOT NULL) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, NotNullAndUniqueConstraint) +TEST_F(CreateStrictTableSqlStatementBuilder, not_null_and_unique_constraint) { builder.setTableName("test"); @@ -904,7 +904,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, NotNullAndUniqueConstraint) ASSERT_THAT(builder.sqlStatement(), "CREATE TABLE test(id INTEGER UNIQUE NOT NULL) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, Check) +TEST_F(CreateStrictTableSqlStatementBuilder, check) { builder.setTableName("test"); @@ -913,7 +913,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, Check) ASSERT_THAT(builder.sqlStatement(), "CREATE TABLE test(id TEXT CHECK (id != '')) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, DefaultValueInt) +TEST_F(CreateStrictTableSqlStatementBuilder, default_value_int) { builder.setTableName("test"); @@ -922,7 +922,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, DefaultValueInt) ASSERT_THAT(builder.sqlStatement(), "CREATE TABLE test(id INTEGER DEFAULT 1) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, DefaultValueFloat) +TEST_F(CreateStrictTableSqlStatementBuilder, default_value_float) { builder.setTableName("test"); @@ -931,7 +931,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, DefaultValueFloat) ASSERT_THAT(builder.sqlStatement(), "CREATE TABLE test(id REAL DEFAULT 1.100000) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, DefaultValueString) +TEST_F(CreateStrictTableSqlStatementBuilder, default_value_string) { builder.setTableName("test"); @@ -940,7 +940,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, DefaultValueString) ASSERT_THAT(builder.sqlStatement(), "CREATE TABLE test(id TEXT DEFAULT 'foo') STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, DefaultExpression) +TEST_F(CreateStrictTableSqlStatementBuilder, default_expression) { builder.setTableName("test"); @@ -952,7 +952,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, DefaultExpression) "CREATE TABLE test(id INTEGER DEFAULT (SELECT name FROM foo WHERE id=?)) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, Collation) +TEST_F(CreateStrictTableSqlStatementBuilder, collation) { builder.setTableName("test"); @@ -961,7 +961,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, Collation) ASSERT_THAT(builder.sqlStatement(), "CREATE TABLE test(id TEXT COLLATE unicode) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, GeneratedAlwaysStored) +TEST_F(CreateStrictTableSqlStatementBuilder, generated_always_stored) { builder.setTableName("test"); @@ -975,7 +975,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, GeneratedAlwaysStored) "STORED) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, GeneratedAlwaysVirtual) +TEST_F(CreateStrictTableSqlStatementBuilder, generated_always_virtual) { builder.setTableName("test"); @@ -989,7 +989,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, GeneratedAlwaysVirtual) "VIRTUAL) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, PrimaryKeyAutoincrement) +TEST_F(CreateStrictTableSqlStatementBuilder, primary_key_autoincrement) { builder.setTableName("test"); @@ -1001,7 +1001,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, PrimaryKeyAutoincrement) "CREATE TABLE test(id INTEGER PRIMARY KEY AUTOINCREMENT) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, BlobType) +TEST_F(CreateStrictTableSqlStatementBuilder, blob_type) { builder.setTableName("test"); @@ -1010,7 +1010,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, BlobType) ASSERT_THAT(builder.sqlStatement(), "CREATE TABLE test(data BLOB) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, TablePrimaryKeyConstaint) +TEST_F(CreateStrictTableSqlStatementBuilder, table_primary_key_constaint) { builder.setTableName("test"); builder.addColumn("id", StrictColumnType::Integer); @@ -1022,7 +1022,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, TablePrimaryKeyConstaint) ASSERT_THAT(statement, "CREATE TABLE test(id INTEGER, text TEXT, PRIMARY KEY(id, text)) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, AnyColumnTypeStringConversion) +TEST_F(CreateStrictTableSqlStatementBuilder, any_column_type_string_conversion) { builder.setTableName("test"); builder.addColumn("id", StrictColumnType::Any); @@ -1032,7 +1032,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, AnyColumnTypeStringConversion) ASSERT_THAT(statement, "CREATE TABLE test(id ANY) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, IntColumnTypeStringConversion) +TEST_F(CreateStrictTableSqlStatementBuilder, int_column_type_string_conversion) { builder.setTableName("test"); builder.addColumn("id", StrictColumnType::Int); @@ -1042,7 +1042,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, IntColumnTypeStringConversion) ASSERT_THAT(statement, "CREATE TABLE test(id INT) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, IntegerColumnTypeStringConversion) +TEST_F(CreateStrictTableSqlStatementBuilder, integer_column_type_string_conversion) { builder.setTableName("test"); builder.addColumn("id", StrictColumnType::Integer); @@ -1052,7 +1052,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, IntegerColumnTypeStringConversion) ASSERT_THAT(statement, "CREATE TABLE test(id INTEGER) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, RealColumnTypeStringConversion) +TEST_F(CreateStrictTableSqlStatementBuilder, real_column_type_string_conversion) { builder.setTableName("test"); builder.addColumn("id", StrictColumnType::Real); @@ -1062,7 +1062,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, RealColumnTypeStringConversion) ASSERT_THAT(statement, "CREATE TABLE test(id REAL) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, TextColumnTypeStringConversion) +TEST_F(CreateStrictTableSqlStatementBuilder, text_column_type_string_conversion) { builder.setTableName("test"); builder.addColumn("id", StrictColumnType::Text); @@ -1072,7 +1072,7 @@ TEST_F(CreateStrictTableSqlStatementBuilder, TextColumnTypeStringConversion) ASSERT_THAT(statement, "CREATE TABLE test(id TEXT) STRICT"); } -TEST_F(CreateStrictTableSqlStatementBuilder, BlobColumnTypeStringConversion) +TEST_F(CreateStrictTableSqlStatementBuilder, blob_column_type_string_conversion) { builder.setTableName("test"); builder.addColumn("id", StrictColumnType::Blob); diff --git a/tests/unit/tests/unittests/sqlite/data/sqlite_database.db b/tests/unit/tests/unittests/sqlite/data/sqlite_database.db new file mode 100644 index 00000000000..51e0f41eb7f Binary files /dev/null and b/tests/unit/tests/unittests/sqlite/data/sqlite_database.db differ diff --git a/tests/unit/unittest/lastchangedrowid-test.cpp b/tests/unit/tests/unittests/sqlite/lastchangedrowid-test.cpp similarity index 63% rename from tests/unit/unittest/lastchangedrowid-test.cpp rename to tests/unit/tests/unittests/sqlite/lastchangedrowid-test.cpp index 0980b0209b9..cadada2c9f2 100644 --- a/tests/unit/unittest/lastchangedrowid-test.cpp +++ b/tests/unit/tests/unittests/sqlite/lastchangedrowid-test.cpp @@ -1,9 +1,9 @@ // Copyright (C) 2020 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" -#include "sqlitedatabasemock.h" +#include "../mocks/sqlitedatabasemock.h" #include @@ -16,31 +16,31 @@ protected: Sqlite::LastChangedRowId<1> lastRowId{mockSqliteDatabase, "main", "foo"}; }; -TEST_F(LastChangedRowId, SetUpdateHookInContructor) +TEST_F(LastChangedRowId, set_update_hook_in_contructor) { EXPECT_CALL(mockSqliteDatabase, setUpdateHook(_, _)); Sqlite::LastChangedRowId<1> lastRowId{mockSqliteDatabase, "main", "foo"}; } -TEST_F(LastChangedRowId, ResetUpdateHookInDestructor) +TEST_F(LastChangedRowId, reset_update_hook_in_destructor) { EXPECT_CALL(mockSqliteDatabase, resetUpdateHook()); } -TEST_F(LastChangedRowId, GetMinusOneAsRowIdIfNoCallbackWasCalled) +TEST_F(LastChangedRowId, get_minus_one_as_row_id_if_no_callback_was_called) { ASSERT_THAT(lastRowId.lastRowId, -1); } -TEST_F(LastChangedRowId, CallbackSetsLastRowId) +TEST_F(LastChangedRowId, callback_sets_last_row_id) { lastRowId("main", "foo", 42); ASSERT_THAT(lastRowId.lastRowId, 42); } -TEST_F(LastChangedRowId, CallbackChecksDatabaseName) +TEST_F(LastChangedRowId, callback_checks_database_name) { lastRowId("main", "foo", 33); @@ -49,7 +49,7 @@ TEST_F(LastChangedRowId, CallbackChecksDatabaseName) ASSERT_THAT(lastRowId.lastRowId, 33); } -TEST_F(LastChangedRowId, CallbackChecksTableName) +TEST_F(LastChangedRowId, callback_checks_table_name) { lastRowId("main", "foo", 33); @@ -58,7 +58,7 @@ TEST_F(LastChangedRowId, CallbackChecksTableName) ASSERT_THAT(lastRowId.lastRowId, 33); } -TEST_F(LastChangedRowId, LastCallSetsRowId) +TEST_F(LastChangedRowId, last_call_sets_row_id) { lastRowId("main", "foo", 42); lastRowId("main", "foo", 33); @@ -68,7 +68,7 @@ TEST_F(LastChangedRowId, LastCallSetsRowId) ASSERT_THAT(lastRowId.lastRowId, 66); } -TEST_F(LastChangedRowId, TakeLastRowId) +TEST_F(LastChangedRowId, take_last_row_id) { lastRowId("main", "foo", 42); @@ -77,7 +77,7 @@ TEST_F(LastChangedRowId, TakeLastRowId) ASSERT_THAT(id, 42); } -TEST_F(LastChangedRowId, TakeLastRowIdResetsRowIdToMinusOne) +TEST_F(LastChangedRowId, take_last_row_id_resets_row_id_to_minus_one) { lastRowId("main", "foo", 42); lastRowId.takeLastRowId(); @@ -95,38 +95,38 @@ protected: Sqlite::LastChangedRowId<2> lastRowId{mockSqliteDatabase, "main", "foo", "bar"}; }; -TEST_F(LastChangedRowIdWithTwoTables, SetUpdateHookInContructor) +TEST_F(LastChangedRowIdWithTwoTables, set_update_hook_in_contructor) { EXPECT_CALL(mockSqliteDatabase, setUpdateHook(_, _)); Sqlite::LastChangedRowId<2> lastRowId{mockSqliteDatabase, "main", "foo", "bar"}; } -TEST_F(LastChangedRowIdWithTwoTables, ResetUpdateHookInDestructor) +TEST_F(LastChangedRowIdWithTwoTables, reset_update_hook_in_destructor) { EXPECT_CALL(mockSqliteDatabase, resetUpdateHook()); } -TEST_F(LastChangedRowIdWithTwoTables, GetMinusOneAsRowIdIfNoCallbackWasCalled) +TEST_F(LastChangedRowIdWithTwoTables, get_minus_one_as_row_id_if_no_callback_was_called) { ASSERT_THAT(lastRowId.lastRowId, -1); } -TEST_F(LastChangedRowIdWithTwoTables, CallbackSetsLastRowIdFirstTable) +TEST_F(LastChangedRowIdWithTwoTables, callback_sets_last_row_id_first_table) { lastRowId("main", "foo", 42); ASSERT_THAT(lastRowId.lastRowId, 42); } -TEST_F(LastChangedRowIdWithTwoTables, CallbackSetsLastRowIdSecondTable) +TEST_F(LastChangedRowIdWithTwoTables, callback_sets_last_row_id_second_table) { lastRowId("main", "bar", 66); ASSERT_THAT(lastRowId.lastRowId, 66); } -TEST_F(LastChangedRowIdWithTwoTables, CallbackChecksDatabaseName) +TEST_F(LastChangedRowIdWithTwoTables, callback_checks_database_name) { lastRowId("main", "foo", 33); @@ -135,7 +135,7 @@ TEST_F(LastChangedRowIdWithTwoTables, CallbackChecksDatabaseName) ASSERT_THAT(lastRowId.lastRowId, 33); } -TEST_F(LastChangedRowIdWithTwoTables, CallbackChecksTableName) +TEST_F(LastChangedRowIdWithTwoTables, callback_checks_table_name) { lastRowId("main", "foo", 33); @@ -144,7 +144,7 @@ TEST_F(LastChangedRowIdWithTwoTables, CallbackChecksTableName) ASSERT_THAT(lastRowId.lastRowId, 33); } -TEST_F(LastChangedRowIdWithTwoTables, LastCallSetsRowId) +TEST_F(LastChangedRowIdWithTwoTables, last_call_sets_row_id) { lastRowId("main", "foo", 42); @@ -153,7 +153,7 @@ TEST_F(LastChangedRowIdWithTwoTables, LastCallSetsRowId) ASSERT_THAT(lastRowId.lastRowId, 66); } -TEST_F(LastChangedRowIdWithTwoTables, TakeLastRowId) +TEST_F(LastChangedRowIdWithTwoTables, take_last_row_id) { lastRowId("main", "foo", 42); @@ -162,7 +162,7 @@ TEST_F(LastChangedRowIdWithTwoTables, TakeLastRowId) ASSERT_THAT(id, 42); } -TEST_F(LastChangedRowIdWithTwoTables, TakeLastRowIdResetsRowIdToMinusOne) +TEST_F(LastChangedRowIdWithTwoTables, take_last_row_id_resets_row_id_to_minus_one) { lastRowId("main", "foo", 42); lastRowId.takeLastRowId(); @@ -180,45 +180,45 @@ protected: Sqlite::LastChangedRowId<3> lastRowId{mockSqliteDatabase, "main", "foo", "bar", "too"}; }; -TEST_F(LastChangedRowIdWithThreeTables, SetUpdateHookInContructor) +TEST_F(LastChangedRowIdWithThreeTables, set_update_hook_in_contructor) { EXPECT_CALL(mockSqliteDatabase, setUpdateHook(_, _)); Sqlite::LastChangedRowId<3> lastRowId{mockSqliteDatabase, "main", "foo", "bar", "too"}; } -TEST_F(LastChangedRowIdWithThreeTables, ResetUpdateHookInDestructor) +TEST_F(LastChangedRowIdWithThreeTables, reset_update_hook_in_destructor) { EXPECT_CALL(mockSqliteDatabase, resetUpdateHook()); } -TEST_F(LastChangedRowIdWithThreeTables, GetMinusOneAsRowIdIfNoCallbackWasCalled) +TEST_F(LastChangedRowIdWithThreeTables, get_minus_one_as_row_id_if_no_callback_was_called) { ASSERT_THAT(lastRowId.lastRowId, -1); } -TEST_F(LastChangedRowIdWithThreeTables, CallbackSetsLastRowIdFirstTable) +TEST_F(LastChangedRowIdWithThreeTables, callback_sets_last_row_id_first_table) { lastRowId("main", "foo", 42); ASSERT_THAT(lastRowId.lastRowId, 42); } -TEST_F(LastChangedRowIdWithThreeTables, CallbackSetsLastRowIdSecondTable) +TEST_F(LastChangedRowIdWithThreeTables, callback_sets_last_row_id_second_table) { lastRowId("main", "bar", 42); ASSERT_THAT(lastRowId.lastRowId, 42); } -TEST_F(LastChangedRowIdWithThreeTables, CallbackSetsLastRowIdThirdTable) +TEST_F(LastChangedRowIdWithThreeTables, callback_sets_last_row_id_third_table) { lastRowId("main", "too", 42); ASSERT_THAT(lastRowId.lastRowId, 42); } -TEST_F(LastChangedRowIdWithThreeTables, CallbackChecksDatabaseName) +TEST_F(LastChangedRowIdWithThreeTables, callback_checks_database_name) { lastRowId("main", "foo", 33); @@ -227,7 +227,7 @@ TEST_F(LastChangedRowIdWithThreeTables, CallbackChecksDatabaseName) ASSERT_THAT(lastRowId.lastRowId, 33); } -TEST_F(LastChangedRowIdWithThreeTables, CallbackChecksTableName) +TEST_F(LastChangedRowIdWithThreeTables, callback_checks_table_name) { lastRowId("main", "foo", 33); @@ -236,7 +236,7 @@ TEST_F(LastChangedRowIdWithThreeTables, CallbackChecksTableName) ASSERT_THAT(lastRowId.lastRowId, 33); } -TEST_F(LastChangedRowIdWithThreeTables, LastCallSetsRowId) +TEST_F(LastChangedRowIdWithThreeTables, last_call_sets_row_id) { lastRowId("main", "bar", 42); lastRowId("main", "too", 33); @@ -246,7 +246,7 @@ TEST_F(LastChangedRowIdWithThreeTables, LastCallSetsRowId) ASSERT_THAT(lastRowId.lastRowId, 66); } -TEST_F(LastChangedRowIdWithThreeTables, TakeLastRowId) +TEST_F(LastChangedRowIdWithThreeTables, take_last_row_id) { lastRowId("main", "foo", 42); @@ -255,7 +255,7 @@ TEST_F(LastChangedRowIdWithThreeTables, TakeLastRowId) ASSERT_THAT(id, 42); } -TEST_F(LastChangedRowIdWithThreeTables, TakeLastRowIdResetsRowIdToMinusOne) +TEST_F(LastChangedRowIdWithThreeTables, take_last_row_id_resets_row_id_to_minus_one) { lastRowId("main", "foo", 42); lastRowId.takeLastRowId(); @@ -272,31 +272,31 @@ protected: Sqlite::LastChangedRowId<> lastRowId{mockSqliteDatabase}; }; -TEST_F(LastChangedRowIdWithNoDatabaseAndTable, SetUpdateHookInContructor) +TEST_F(LastChangedRowIdWithNoDatabaseAndTable, set_update_hook_in_contructor) { EXPECT_CALL(mockSqliteDatabase, setUpdateHook(_, _)); Sqlite::LastChangedRowId<> lastRowId{mockSqliteDatabase}; } -TEST_F(LastChangedRowIdWithNoDatabaseAndTable, ResetUpdateHookInDestructor) +TEST_F(LastChangedRowIdWithNoDatabaseAndTable, reset_update_hook_in_destructor) { EXPECT_CALL(mockSqliteDatabase, resetUpdateHook()); } -TEST_F(LastChangedRowIdWithNoDatabaseAndTable, GetMinusOneAsRowIdIfNoCallbackWasCalled) +TEST_F(LastChangedRowIdWithNoDatabaseAndTable, get_minus_one_as_row_id_if_no_callback_was_called) { ASSERT_THAT(lastRowId.lastRowId, -1); } -TEST_F(LastChangedRowIdWithNoDatabaseAndTable, CallbackSetsLastRowId) +TEST_F(LastChangedRowIdWithNoDatabaseAndTable, callback_sets_last_row_id) { lastRowId(42); ASSERT_THAT(lastRowId.lastRowId, 42); } -TEST_F(LastChangedRowIdWithNoDatabaseAndTable, LastCallSetsRowId) +TEST_F(LastChangedRowIdWithNoDatabaseAndTable, last_call_sets_row_id) { lastRowId(42); lastRowId(33); @@ -306,7 +306,7 @@ TEST_F(LastChangedRowIdWithNoDatabaseAndTable, LastCallSetsRowId) ASSERT_THAT(lastRowId.lastRowId, 66); } -TEST_F(LastChangedRowIdWithNoDatabaseAndTable, TakeLastRowId) +TEST_F(LastChangedRowIdWithNoDatabaseAndTable, take_last_row_id) { lastRowId(42); @@ -315,7 +315,7 @@ TEST_F(LastChangedRowIdWithNoDatabaseAndTable, TakeLastRowId) ASSERT_THAT(id, 42); } -TEST_F(LastChangedRowIdWithNoDatabaseAndTable, TakeLastRowIdResetsRowIdToMinusOne) +TEST_F(LastChangedRowIdWithNoDatabaseAndTable, take_last_row_id_resets_row_id_to_minus_one) { lastRowId(42); lastRowId.takeLastRowId(); @@ -332,31 +332,31 @@ protected: Sqlite::LastChangedRowId<> lastRowId{mockSqliteDatabase, "main"}; }; -TEST_F(LastChangedRowIdWithNoTable, SetUpdateHookInContructor) +TEST_F(LastChangedRowIdWithNoTable, set_update_hook_in_contructor) { EXPECT_CALL(mockSqliteDatabase, setUpdateHook(_, _)); Sqlite::LastChangedRowId<> lastRowId{mockSqliteDatabase, "main"}; } -TEST_F(LastChangedRowIdWithNoTable, ResetUpdateHookInDestructor) +TEST_F(LastChangedRowIdWithNoTable, reset_update_hook_in_destructor) { EXPECT_CALL(mockSqliteDatabase, resetUpdateHook()); } -TEST_F(LastChangedRowIdWithNoTable, GetMinusOneAsRowIdIfNoCallbackWasCalled) +TEST_F(LastChangedRowIdWithNoTable, get_minus_one_as_row_id_if_no_callback_was_called) { ASSERT_THAT(lastRowId.lastRowId, -1); } -TEST_F(LastChangedRowIdWithNoTable, CallbackSetsLastRowId) +TEST_F(LastChangedRowIdWithNoTable, callback_sets_last_row_id) { lastRowId("main", 42); ASSERT_THAT(lastRowId.lastRowId, 42); } -TEST_F(LastChangedRowIdWithNoTable, CallbackChecksDatabaseName) +TEST_F(LastChangedRowIdWithNoTable, callback_checks_database_name) { lastRowId("main", 33); @@ -365,7 +365,7 @@ TEST_F(LastChangedRowIdWithNoTable, CallbackChecksDatabaseName) ASSERT_THAT(lastRowId.lastRowId, 33); } -TEST_F(LastChangedRowIdWithNoTable, LastCallSetsRowId) +TEST_F(LastChangedRowIdWithNoTable, last_call_sets_row_id) { lastRowId("main", 42); lastRowId("main", 33); @@ -375,7 +375,7 @@ TEST_F(LastChangedRowIdWithNoTable, LastCallSetsRowId) ASSERT_THAT(lastRowId.lastRowId, 66); } -TEST_F(LastChangedRowIdWithNoTable, TakeLastRowId) +TEST_F(LastChangedRowIdWithNoTable, take_last_row_id) { lastRowId("main", 42); @@ -384,7 +384,7 @@ TEST_F(LastChangedRowIdWithNoTable, TakeLastRowId) ASSERT_THAT(id, 42); } -TEST_F(LastChangedRowIdWithNoTable, TakeLastRowIdResetsRowIdToMinusOne) +TEST_F(LastChangedRowIdWithNoTable, take_last_row_id_resets_row_id_to_minus_one) { lastRowId("main", 42); lastRowId.takeLastRowId(); @@ -394,14 +394,14 @@ TEST_F(LastChangedRowIdWithNoTable, TakeLastRowIdResetsRowIdToMinusOne) ASSERT_THAT(id, -1); } -TEST_F(LastChangedRowIdWithNoTable, LastRowIdIsNotValidForNegativeValues) +TEST_F(LastChangedRowIdWithNoTable, last_row_id_is_not_valid_for_negative_values) { auto isValid = lastRowId.lastRowIdIsValid(); ASSERT_FALSE(isValid); } -TEST_F(LastChangedRowIdWithNoTable, LastRowIdIsValidForNull) +TEST_F(LastChangedRowIdWithNoTable, last_row_id_is_valid_for_null) { lastRowId("main", 0); @@ -410,7 +410,7 @@ TEST_F(LastChangedRowIdWithNoTable, LastRowIdIsValidForNull) ASSERT_TRUE(isValid); } -TEST_F(LastChangedRowIdWithNoTable, LastRowIdIsValidForPositiveValues) +TEST_F(LastChangedRowIdWithNoTable, last_row_id_is_valid_for_positive_values) { lastRowId("main", 777); diff --git a/tests/unit/unittest/sqlitealgorithms-test.cpp b/tests/unit/tests/unittests/sqlite/sqlitealgorithms-test.cpp similarity index 92% rename from tests/unit/unittest/sqlitealgorithms-test.cpp rename to tests/unit/tests/unittests/sqlite/sqlitealgorithms-test.cpp index 956d49147a5..a29a552ce59 100644 --- a/tests/unit/unittest/sqlitealgorithms-test.cpp +++ b/tests/unit/tests/unittests/sqlite/sqlitealgorithms-test.cpp @@ -1,7 +1,7 @@ // Copyright (C) 2021 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" #include #include @@ -112,7 +112,7 @@ auto compareKey = [](KeyValueView keyValueView, const KeyValue &keyValue) { return Sqlite::compare(keyValueView.key, keyValue.key); }; -TEST_F(SqliteAlgorithms, InsertValues) +TEST_F(SqliteAlgorithms, insert_values) { KeyValues keyValues = {{"one", 1}, {"oneone", 11}}; @@ -121,7 +121,7 @@ TEST_F(SqliteAlgorithms, InsertValues) ASSERT_THAT(fetchKeyValues(), UnorderedElementsAre(KeyValue{"one", 1}, KeyValue{"oneone", 11})); } -TEST_F(SqliteAlgorithms, InsertBeforeValues) +TEST_F(SqliteAlgorithms, insert_before_values) { KeyValues keyValues = {{"two", 2}, {"twotwo", 22}}; Sqlite::insertUpdateDelete(select(), keyValues, compareKey, insert, update, remove); @@ -136,7 +136,7 @@ TEST_F(SqliteAlgorithms, InsertBeforeValues) KeyValue{"twotwo", 22})); } -TEST_F(SqliteAlgorithms, InsertInBetweenValues) +TEST_F(SqliteAlgorithms, insert_in_between_values) { KeyValues keyValues = {{"one", 1}, {"two", 2}}; Sqlite::insertUpdateDelete(select(), keyValues, compareKey, insert, update, remove); @@ -151,7 +151,7 @@ TEST_F(SqliteAlgorithms, InsertInBetweenValues) KeyValue{"twotwo", 22})); } -TEST_F(SqliteAlgorithms, InsertTrailingValues) +TEST_F(SqliteAlgorithms, insert_trailing_values) { KeyValues keyValues = {{"one", 1}, {"oneone", 11}}; Sqlite::insertUpdateDelete(select(), keyValues, compareKey, insert, update, remove); @@ -166,7 +166,7 @@ TEST_F(SqliteAlgorithms, InsertTrailingValues) KeyValue{"twotwo", 22})); } -TEST_F(SqliteAlgorithms, UpdateValues) +TEST_F(SqliteAlgorithms, update_values) { KeyValues keyValues = {{"one", 1}, {"oneone", 11}}; Sqlite::insertUpdateDelete(select(), keyValues, compareKey, insert, update, remove); @@ -177,7 +177,7 @@ TEST_F(SqliteAlgorithms, UpdateValues) ASSERT_THAT(fetchKeyValues(), UnorderedElementsAre(KeyValue{"one", 2}, KeyValue{"oneone", 22})); } -TEST_F(SqliteAlgorithms, UpdateSomeValues) +TEST_F(SqliteAlgorithms, update_some_values) { KeyValues keyValues = {{"one", 1}, {"oneone", 11}, {"two", 2}, {"twotwo", 22}}; Sqlite::insertUpdateDelete(select(), keyValues, compareKey, insert, update, remove); @@ -192,7 +192,7 @@ TEST_F(SqliteAlgorithms, UpdateSomeValues) KeyValue{"twotwo", 22})); } -TEST_F(SqliteAlgorithms, DeleteBeforeSqliteEntries) +TEST_F(SqliteAlgorithms, delete_before_sqlite_entries) { KeyValues keyValues = {{"one", 1}, {"oneone", 11}, {"two", 2}, {"twotwo", 22}}; Sqlite::insertUpdateDelete(select(), keyValues, compareKey, insert, update, remove); @@ -203,7 +203,7 @@ TEST_F(SqliteAlgorithms, DeleteBeforeSqliteEntries) ASSERT_THAT(fetchKeyValues(), UnorderedElementsAre(KeyValue{"two", 2}, KeyValue{"twotwo", 22})); } -TEST_F(SqliteAlgorithms, DeleteTrailingSqliteEntries2) +TEST_F(SqliteAlgorithms, delete_trailing_sqlite_entries2) { KeyValues keyValues = {{"one", 1}, {"oneone", 11}, {"two", 2}, {"twotwo", 22}}; Sqlite::insertUpdateDelete(select(), keyValues, compareKey, insert, update, remove); @@ -214,7 +214,7 @@ TEST_F(SqliteAlgorithms, DeleteTrailingSqliteEntries2) ASSERT_THAT(fetchKeyValues(), UnorderedElementsAre(KeyValue{"one", 1}, KeyValue{"oneone", 11})); } -TEST_F(SqliteAlgorithms, DeleteTrailingSqliteEntries) +TEST_F(SqliteAlgorithms, delete_trailing_sqlite_entries) { KeyValues keyValues = {{"one", 1}, {"oneone", 11}, {"two", 2}, {"twotwo", 22}}; Sqlite::insertUpdateDelete(select(), keyValues, compareKey, insert, update, remove); @@ -225,7 +225,7 @@ TEST_F(SqliteAlgorithms, DeleteTrailingSqliteEntries) ASSERT_THAT(fetchKeyValues(), UnorderedElementsAre(KeyValue{"one", 1}, KeyValue{"oneone", 11})); } -TEST_F(SqliteAlgorithms, DeleteSqliteEntries) +TEST_F(SqliteAlgorithms, delete_sqlite_entries) { KeyValues keyValues = {{"one", 1}, {"oneone", 11}, {"two", 2}, {"twotwo", 22}}; Sqlite::insertUpdateDelete(select(), keyValues, compareKey, insert, update, remove); @@ -236,7 +236,7 @@ TEST_F(SqliteAlgorithms, DeleteSqliteEntries) ASSERT_THAT(fetchKeyValues(), IsEmpty()); } -TEST_F(SqliteAlgorithms, Synchonize) +TEST_F(SqliteAlgorithms, synchonize) { KeyValues keyValues = {{"one", 1}, {"oneone", 11}, {"two", 2}, {"twotwo", 22}}; Sqlite::insertUpdateDelete(select(), keyValues, compareKey, insert, update, remove); @@ -250,28 +250,28 @@ TEST_F(SqliteAlgorithms, Synchonize) KeyValue{"twotwo", 202})); } -TEST_F(SqliteAlgorithms, CompareEqual) +TEST_F(SqliteAlgorithms, compare_equal) { auto compare = Sqlite::compare("one", "one"); ASSERT_THAT(compare, Eq(0)); } -TEST_F(SqliteAlgorithms, CompareGreater) +TEST_F(SqliteAlgorithms, compare_greater) { auto compare = Sqlite::compare("two", "one"); ASSERT_THAT(compare, Gt(0)); } -TEST_F(SqliteAlgorithms, CompareGreaterForTrailingText) +TEST_F(SqliteAlgorithms, compare_greater_for_trailing_text) { auto compare = Sqlite::compare("oneone", "one"); ASSERT_THAT(compare, Gt(0)); } -TEST_F(SqliteAlgorithms, CompareLessForTrailingText) +TEST_F(SqliteAlgorithms, compare_less_for_trailing_text) { auto compare = Sqlite::compare("one", "oneone"); diff --git a/tests/unit/unittest/sqlitecolumn-test.cpp b/tests/unit/tests/unittests/sqlite/sqlitecolumn-test.cpp similarity index 95% rename from tests/unit/unittest/sqlitecolumn-test.cpp rename to tests/unit/tests/unittests/sqlite/sqlitecolumn-test.cpp index c7e2218cb8f..f75deb65710 100644 --- a/tests/unit/unittest/sqlitecolumn-test.cpp +++ b/tests/unit/tests/unittests/sqlite/sqlitecolumn-test.cpp @@ -1,7 +1,7 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" #include @@ -24,7 +24,7 @@ protected: Column column; }; -TEST_F(SqliteColumn, DefaultConstruct) +TEST_F(SqliteColumn, default_construct) { ASSERT_THAT(column, AllOf(Field(&Column::name, IsEmpty()), @@ -33,7 +33,7 @@ TEST_F(SqliteColumn, DefaultConstruct) Field(&Column::constraints, IsEmpty()))); } -TEST_F(SqliteColumn, Clear) +TEST_F(SqliteColumn, clear) { column.name = "foo"; column.name = "foo"; @@ -49,7 +49,7 @@ TEST_F(SqliteColumn, Clear) Field(&Column::constraints, IsEmpty()))); } -TEST_F(SqliteColumn, Constructor) +TEST_F(SqliteColumn, constructor) { column = Column{"table", "column", @@ -73,7 +73,7 @@ TEST_F(SqliteColumn, Constructor) Field(&ForeignKey::enforcement, Enforment::Deferred))))))); } -TEST_F(SqliteColumn, FlatConstructor) +TEST_F(SqliteColumn, flat_constructor) { column = Column{"table", "column", @@ -105,7 +105,7 @@ protected: Column column; }; -TEST_F(SqliteStrictColumn, DefaultConstruct) +TEST_F(SqliteStrictColumn, default_construct) { ASSERT_THAT(column, AllOf(Field(&Column::name, IsEmpty()), @@ -114,7 +114,7 @@ TEST_F(SqliteStrictColumn, DefaultConstruct) Field(&Column::constraints, IsEmpty()))); } -TEST_F(SqliteStrictColumn, Clear) +TEST_F(SqliteStrictColumn, clear) { column.name = "foo"; column.name = "foo"; @@ -130,7 +130,7 @@ TEST_F(SqliteStrictColumn, Clear) Field(&Column::constraints, IsEmpty()))); } -TEST_F(SqliteStrictColumn, Constructor) +TEST_F(SqliteStrictColumn, constructor) { column = Column{"table", "column", @@ -154,7 +154,7 @@ TEST_F(SqliteStrictColumn, Constructor) Field(&ForeignKey::enforcement, Enforment::Deferred))))))); } -TEST_F(SqliteStrictColumn, FlatConstructor) +TEST_F(SqliteStrictColumn, flat_constructor) { column = Column{"table", "column", diff --git a/tests/unit/unittest/sqlitedatabase-test.cpp b/tests/unit/tests/unittests/sqlite/sqlitedatabase-test.cpp similarity index 78% rename from tests/unit/unittest/sqlitedatabase-test.cpp rename to tests/unit/tests/unittests/sqlite/sqlitedatabase-test.cpp index a7a8585db53..50b5c012c52 100644 --- a/tests/unit/unittest/sqlitedatabase-test.cpp +++ b/tests/unit/tests/unittests/sqlite/sqlitedatabase-test.cpp @@ -1,9 +1,8 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" - -#include "spydummy.h" +#include "../utils/googletest.h" +#include "../utils/spydummy.h" #include #include @@ -52,7 +51,7 @@ protected: } static void updateHookCallback( - void *object, int type, char const *database, char const *table, long long rowId) + void *object, int type, const char *database, const char *table, long long rowId) { static_cast(object)->callback(static_cast(type), database, @@ -65,40 +64,41 @@ protected: Table table; mutable Sqlite::Database database{":memory:", JournalMode::Memory}; Sqlite::TransactionInterface &transactionInterface = database; - MockFunction callbackMock; - std::function + MockFunction callbackMock; + std::function callback = callbackMock.AsStdFunction(); std::unique_lock lock{database}; }; -TEST_F(SqliteDatabase, SetDatabaseFilePath) +TEST_F(SqliteDatabase, set_database_file_path) { ASSERT_THAT(database.databaseFilePath(), ":memory:"); } -TEST_F(SqliteDatabase, SetJournalMode) +TEST_F(SqliteDatabase, set_journal_mode) { database.setJournalMode(JournalMode::Memory); ASSERT_THAT(database.journalMode(), JournalMode::Memory); } -TEST_F(SqliteDatabase, LockingModeIsByDefaultExlusive) +TEST_F(SqliteDatabase, locking_mode_is_by_default_exlusive) { ASSERT_THAT(database.lockingMode(), Sqlite::LockingMode::Exclusive); } -TEST_F(SqliteDatabase, CreateDatabaseWithLockingModeNormal) +TEST_F(SqliteDatabase, create_database_with_locking_mode_normal) { Utils::PathString path{Utils::TemporaryDirectory::masterDirectoryPath() + "/database_exclusive_locked.db"}; Sqlite::Database database{path, JournalMode::Wal, Sqlite::LockingMode::Normal}; - ASSERT_THAT(database.lockingMode(), Sqlite::LockingMode::Normal); + ASSERT_THAT(Sqlite::withImmediateTransaction(database, [&] { return database.lockingMode(); }), + Sqlite::LockingMode::Normal); } -TEST_F(SqliteDatabase, ExclusivelyLockedDatabaseIsLockedForSecondConnection) +TEST_F(SqliteDatabase, exclusively_locked_database_is_locked_for_second_connection) { using namespace std::chrono_literals; Utils::PathString path{Utils::TemporaryDirectory::masterDirectoryPath() @@ -108,7 +108,7 @@ TEST_F(SqliteDatabase, ExclusivelyLockedDatabaseIsLockedForSecondConnection) ASSERT_THROW(Sqlite::Database database2(path, 1ms), Sqlite::StatementIsBusy); } -TEST_F(SqliteDatabase, NormalLockedDatabaseCanBeReopened) +TEST_F(SqliteDatabase, normal_locked_database_can_be_reopened) { Utils::PathString path{Utils::TemporaryDirectory::masterDirectoryPath() + "/database_exclusive_locked.db"}; @@ -117,14 +117,14 @@ TEST_F(SqliteDatabase, NormalLockedDatabaseCanBeReopened) ASSERT_NO_THROW((Sqlite::Database{path, JournalMode::Wal, Sqlite::LockingMode::Normal})); } -TEST_F(SqliteDatabase, SetOpenlMode) +TEST_F(SqliteDatabase, set_openl_mode) { database.setOpenMode(OpenMode::ReadOnly); ASSERT_THAT(database.openMode(), OpenMode::ReadOnly); } -TEST_F(SqliteDatabase, OpenDatabase) +TEST_F(SqliteDatabase, open_database) { database.close(); @@ -133,33 +133,33 @@ TEST_F(SqliteDatabase, OpenDatabase) ASSERT_TRUE(database.isOpen()); } -TEST_F(SqliteDatabase, CloseDatabase) +TEST_F(SqliteDatabase, close_database) { database.close(); ASSERT_FALSE(database.isOpen()); } -TEST_F(SqliteDatabase, DatabaseIsNotInitializedAfterOpening) +TEST_F(SqliteDatabase, database_is_not_initialized_after_opening) { ASSERT_FALSE(database.isInitialized()); } -TEST_F(SqliteDatabase, DatabaseIsIntializedAfterSettingItBeforeOpening) +TEST_F(SqliteDatabase, database_is_intialized_after_setting_it_before_opening) { database.setIsInitialized(true); ASSERT_TRUE(database.isInitialized()); } -TEST_F(SqliteDatabase, DatabaseIsInitializedIfDatabasePathExistsAtOpening) +TEST_F(SqliteDatabase, database_is_initialized_if_database_path_exists_at_opening) { - Sqlite::Database database{TESTDATA_DIR "/sqlite_database.db"}; + Sqlite::Database database{UNITTEST_DIR "/sqlite/data/sqlite_database.db"}; ASSERT_TRUE(database.isInitialized()); } -TEST_F(SqliteDatabase, DatabaseIsNotInitializedIfDatabasePathDoesNotExistAtOpening) +TEST_F(SqliteDatabase, database_is_not_initialized_if_database_path_does_not_exist_at_opening) { Sqlite::Database database{Utils::PathString{Utils::TemporaryDirectory::masterDirectoryPath() + "/database_does_not_exist.db"}}; @@ -167,7 +167,7 @@ TEST_F(SqliteDatabase, DatabaseIsNotInitializedIfDatabasePathDoesNotExistAtOpeni ASSERT_FALSE(database.isInitialized()); } -TEST_F(SqliteDatabase, GetChangesCount) +TEST_F(SqliteDatabase, get_changes_count) { Sqlite::WriteStatement<1> statement("INSERT INTO test(name) VALUES (?)", database); statement.write(42); @@ -175,7 +175,7 @@ TEST_F(SqliteDatabase, GetChangesCount) ASSERT_THAT(database.changesCount(), 1); } -TEST_F(SqliteDatabase, GetTotalChangesCount) +TEST_F(SqliteDatabase, get_total_changes_count) { Sqlite::WriteStatement<1> statement("INSERT INTO test(name) VALUES (?)", database); statement.write(42); @@ -183,7 +183,7 @@ TEST_F(SqliteDatabase, GetTotalChangesCount) ASSERT_THAT(database.lastInsertedRowId(), 1); } -TEST_F(SqliteDatabase, GetLastInsertedRowId) +TEST_F(SqliteDatabase, get_last_inserted_row_id) { Sqlite::WriteStatement<1> statement("INSERT INTO test(name) VALUES (?)", database); statement.write(42); @@ -191,49 +191,49 @@ TEST_F(SqliteDatabase, GetLastInsertedRowId) ASSERT_THAT(database.lastInsertedRowId(), 1); } -TEST_F(SqliteDatabase, LastRowId) +TEST_F(SqliteDatabase, last_row_id) { database.setLastInsertedRowId(42); ASSERT_THAT(database.lastInsertedRowId(), 42); } -TEST_F(SqliteDatabase, DeferredBegin) +TEST_F(SqliteDatabase, deferred_begin) { ASSERT_NO_THROW(transactionInterface.deferredBegin()); transactionInterface.commit(); } -TEST_F(SqliteDatabase, ImmediateBegin) +TEST_F(SqliteDatabase, immediate_begin) { ASSERT_NO_THROW(transactionInterface.immediateBegin()); transactionInterface.commit(); } -TEST_F(SqliteDatabase, ExclusiveBegin) +TEST_F(SqliteDatabase, exclusive_begin) { ASSERT_NO_THROW(transactionInterface.exclusiveBegin()); transactionInterface.commit(); } -TEST_F(SqliteDatabase, Commit) +TEST_F(SqliteDatabase, commit) { transactionInterface.deferredBegin(); ASSERT_NO_THROW(transactionInterface.commit()); } -TEST_F(SqliteDatabase, Rollback) +TEST_F(SqliteDatabase, rollback) { transactionInterface.deferredBegin(); ASSERT_NO_THROW(transactionInterface.rollback()); } -TEST_F(SqliteDatabase, SetUpdateHookSet) +TEST_F(SqliteDatabase, set_update_hook_set) { database.setUpdateHook(this, updateHookCallback); @@ -241,7 +241,7 @@ TEST_F(SqliteDatabase, SetUpdateHookSet) Sqlite::WriteStatement<1>("INSERT INTO test(name) VALUES (?)", database).write(42); } -TEST_F(SqliteDatabase, SetNullUpdateHook) +TEST_F(SqliteDatabase, set_null_update_hook) { database.setUpdateHook(this, updateHookCallback); @@ -251,7 +251,7 @@ TEST_F(SqliteDatabase, SetNullUpdateHook) Sqlite::WriteStatement<1>("INSERT INTO test(name) VALUES (?)", database).write(42); } -TEST_F(SqliteDatabase, ResetUpdateHook) +TEST_F(SqliteDatabase, reset_update_hook) { database.setUpdateHook(this, updateHookCallback); @@ -261,7 +261,7 @@ TEST_F(SqliteDatabase, ResetUpdateHook) Sqlite::WriteStatement<1>("INSERT INTO test(name) VALUES (?)", database).write(42); } -TEST_F(SqliteDatabase, DeleteUpdateHookCall) +TEST_F(SqliteDatabase, delete_update_hook_call) { Sqlite::WriteStatement<1>("INSERT INTO test(name) VALUES (?)", database).write(42); database.setUpdateHook(this, updateHookCallback); @@ -271,7 +271,7 @@ TEST_F(SqliteDatabase, DeleteUpdateHookCall) Sqlite::WriteStatement("DELETE FROM test WHERE name = 42", database).execute(); } -TEST_F(SqliteDatabase, InsertUpdateHookCall) +TEST_F(SqliteDatabase, insert_update_hook_call) { database.setUpdateHook(this, updateHookCallback); @@ -280,7 +280,7 @@ TEST_F(SqliteDatabase, InsertUpdateHookCall) Sqlite::WriteStatement<1>("INSERT INTO test(name) VALUES (?)", database).write(42); } -TEST_F(SqliteDatabase, UpdateUpdateHookCall) +TEST_F(SqliteDatabase, update_update_hook_call) { database.setUpdateHook(this, updateHookCallback); @@ -289,7 +289,7 @@ TEST_F(SqliteDatabase, UpdateUpdateHookCall) Sqlite::WriteStatement<1>("INSERT INTO test(name) VALUES (?)", database).write(42); } -TEST_F(SqliteDatabase, RowIdUpdateHookCall) +TEST_F(SqliteDatabase, row_id_update_hook_call) { database.setUpdateHook(this, updateHookCallback); @@ -298,7 +298,7 @@ TEST_F(SqliteDatabase, RowIdUpdateHookCall) Sqlite::WriteStatement<2>("INSERT INTO test(rowid, name) VALUES (?,?)", database).write(42, "foo"); } -TEST_F(SqliteDatabase, DatabaseUpdateHookCall) +TEST_F(SqliteDatabase, database_update_hook_call) { database.setUpdateHook(this, updateHookCallback); @@ -307,7 +307,7 @@ TEST_F(SqliteDatabase, DatabaseUpdateHookCall) Sqlite::WriteStatement<1>("INSERT INTO test(name) VALUES (?)", database).write(42); } -TEST_F(SqliteDatabase, TableUpdateHookCall) +TEST_F(SqliteDatabase, table_update_hook_call) { database.setUpdateHook(this, updateHookCallback); @@ -316,7 +316,7 @@ TEST_F(SqliteDatabase, TableUpdateHookCall) Sqlite::WriteStatement<1>("INSERT INTO test(name) VALUES (?)", database).write(42); } -TEST_F(SqliteDatabase, SessionsCommit) +TEST_F(SqliteDatabase, sessions_commit) { database.setAttachedTables({"test"}); Sqlite::WriteStatement<2>("INSERT INTO test(id, name) VALUES (?,?)", database).write(1, "foo"); @@ -333,7 +333,7 @@ TEST_F(SqliteDatabase, SessionsCommit) ASSERT_THAT(names(), UnorderedElementsAre("foo", "bar")); } -TEST_F(SqliteDatabase, SessionsRollback) +TEST_F(SqliteDatabase, sessions_rollback) { database.setAttachedTables({"test"}); Sqlite::WriteStatement<2>("INSERT INTO test(id, name) VALUES (?,?)", database).write(1, "foo"); @@ -351,7 +351,7 @@ TEST_F(SqliteDatabase, SessionsRollback) ASSERT_THAT(names(), UnorderedElementsAre("foo", "hoo")); } -TEST_F(SqliteDatabase, ProgressHandlerInterrupts) +TEST_F(SqliteDatabase, progress_handler_interrupts) { Sqlite::WriteStatement<1> statement("INSERT INTO test(name) VALUES (?)", database); lock.unlock(); @@ -362,7 +362,7 @@ TEST_F(SqliteDatabase, ProgressHandlerInterrupts) lock.unlock(); } -TEST_F(SqliteDatabase, ProgressHandlerContinues) +TEST_F(SqliteDatabase, progress_handler_continues) { Sqlite::WriteStatement<1> statement("INSERT INTO test(name) VALUES (?)", database); lock.unlock(); @@ -373,7 +373,7 @@ TEST_F(SqliteDatabase, ProgressHandlerContinues) lock.unlock(); } -TEST_F(SqliteDatabase, ProgressHandlerResetsAfterLeavingScope) +TEST_F(SqliteDatabase, progress_handler_resets_after_leaving_scope) { lock.unlock(); { diff --git a/tests/unit/unittest/sqlitedatabasebackend-test.cpp b/tests/unit/tests/unittests/sqlite/sqlitedatabasebackend-test.cpp similarity index 81% rename from tests/unit/unittest/sqlitedatabasebackend-test.cpp rename to tests/unit/tests/unittests/sqlite/sqlitedatabasebackend-test.cpp index 9e08eb5b00d..b009b7a5252 100644 --- a/tests/unit/unittest/sqlitedatabasebackend-test.cpp +++ b/tests/unit/tests/unittests/sqlite/sqlitedatabasebackend-test.cpp @@ -1,7 +1,7 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" #include #include @@ -9,7 +9,7 @@ #include #include -#include +#include <3rdparty/sqlite/sqlite.h> #include @@ -47,20 +47,20 @@ protected: using SqliteDatabaseBackendSlowTest = SqliteDatabaseBackend; -TEST_F(SqliteDatabaseBackend, OpenAlreadyOpenDatabase) +TEST_F(SqliteDatabaseBackend, open_already_open_database) { ASSERT_THROW(databaseBackend.open(databaseFilePath, OpenMode::ReadWrite, Sqlite::JournalMode::Wal), Sqlite::DatabaseIsAlreadyOpen); } -TEST_F(SqliteDatabaseBackend, CloseAlreadyClosedDatabase) +TEST_F(SqliteDatabaseBackend, close_already_closed_database) { databaseBackend.close(); ASSERT_THROW(databaseBackend.close(), Sqlite::DatabaseIsAlreadyClosed); } -TEST_F(SqliteDatabaseBackend, OpenWithWrongPath) +TEST_F(SqliteDatabaseBackend, open_with_wrong_path) { ASSERT_THROW(databaseBackend.open("/xxx/SqliteDatabaseBackendTest.db", OpenMode::ReadWrite, @@ -68,54 +68,54 @@ TEST_F(SqliteDatabaseBackend, OpenWithWrongPath) Sqlite::WrongFilePath); } -TEST_F(SqliteDatabaseBackend, DefaultJournalMode) +TEST_F(SqliteDatabaseBackend, default_journal_mode) { ASSERT_THAT(databaseBackend.journalMode(), JournalMode::Delete); } -TEST_F(SqliteDatabaseBackendSlowTest, WalJournalMode) +TEST_F(SqliteDatabaseBackendSlowTest, wal_journal_mode) { databaseBackend.setJournalMode(JournalMode::Wal); ASSERT_THAT(databaseBackend.journalMode(), JournalMode::Wal); } -TEST_F(SqliteDatabaseBackend, TruncateJournalMode) +TEST_F(SqliteDatabaseBackend, truncate_journal_mode) { databaseBackend.setJournalMode(JournalMode::Truncate); ASSERT_THAT(databaseBackend.journalMode(), JournalMode::Truncate); } -TEST_F(SqliteDatabaseBackend, MemoryJournalMode) +TEST_F(SqliteDatabaseBackend, memory_journal_mode) { databaseBackend.setJournalMode(JournalMode::Memory); ASSERT_THAT(databaseBackend.journalMode(), JournalMode::Memory); } -TEST_F(SqliteDatabaseBackend, PersistJournalMode) +TEST_F(SqliteDatabaseBackend, persist_journal_mode) { databaseBackend.setJournalMode(JournalMode::Persist); ASSERT_THAT(databaseBackend.journalMode(), JournalMode::Persist); } -TEST_F(SqliteDatabaseBackend, OpenModeReadOnly) +TEST_F(SqliteDatabaseBackend, open_mode_read_only) { auto mode = Backend::createOpenFlags(OpenMode::ReadOnly, Sqlite::JournalMode::Wal); ASSERT_THAT(mode, SQLITE_OPEN_CREATE | SQLITE_OPEN_READONLY | SQLITE_OPEN_EXRESCODE); } -TEST_F(SqliteDatabaseBackend, OpenModeReadWrite) +TEST_F(SqliteDatabaseBackend, open_mode_read_write) { auto mode = Backend::createOpenFlags(OpenMode::ReadWrite, Sqlite::JournalMode::Wal); ASSERT_THAT(mode, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE | SQLITE_OPEN_EXRESCODE); } -TEST_F(SqliteDatabaseBackend, OpenModeReadWriteAndMemoryJournal) +TEST_F(SqliteDatabaseBackend, open_mode_read_write_and_memory_journal) { auto mode = Backend::createOpenFlags(OpenMode::ReadWrite, Sqlite::JournalMode::Memory); diff --git a/tests/unit/unittest/sqlitefunctionregistry-test.cpp b/tests/unit/tests/unittests/sqlite/sqlitefunctionregistry-test.cpp similarity index 64% rename from tests/unit/unittest/sqlitefunctionregistry-test.cpp rename to tests/unit/tests/unittests/sqlite/sqlitefunctionregistry-test.cpp index de9a566fd50..2973ec6167c 100644 --- a/tests/unit/unittest/sqlitefunctionregistry-test.cpp +++ b/tests/unit/tests/unittests/sqlite/sqlitefunctionregistry-test.cpp @@ -1,7 +1,7 @@ // Copyright (C) 2023 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" #include @@ -16,10 +16,11 @@ protected: Sqlite::Database database{":memory:", Sqlite::JournalMode::Memory}; }; -TEST_F(SqliteFunctionRegistry, PathExists) +TEST_F(SqliteFunctionRegistry, path_exists) { std::lock_guard lock{database}; - Sqlite::ReadStatement<1> statement{"SELECT pathExists('" TESTDATA_DIR "/sqlite_database.db')", + Sqlite::ReadStatement<1> statement{"SELECT pathExists('" UNITTEST_DIR + "/sqlite/data/sqlite_database.db')", database}; auto pathExists = statement.value(); @@ -27,10 +28,11 @@ TEST_F(SqliteFunctionRegistry, PathExists) ASSERT_TRUE(pathExists); } -TEST_F(SqliteFunctionRegistry, PathDoesntExists) +TEST_F(SqliteFunctionRegistry, path_doesnt_exists) { std::lock_guard lock{database}; - Sqlite::ReadStatement<1> statement{"SELECT pathExists('" TESTDATA_DIR "/sqlite_database2.db')", + Sqlite::ReadStatement<1> statement{"SELECT pathExists('" UNITTEST_DIR + "/sqlite/data/sqlite_database2.db')", database}; auto pathExists = statement.value(); diff --git a/tests/unit/unittest/sqliteindex-test.cpp b/tests/unit/tests/unittests/sqlite/sqliteindex-test.cpp similarity index 88% rename from tests/unit/unittest/sqliteindex-test.cpp rename to tests/unit/tests/unittests/sqlite/sqliteindex-test.cpp index e2e9172b525..9d3fca88ffa 100644 --- a/tests/unit/unittest/sqliteindex-test.cpp +++ b/tests/unit/tests/unittests/sqlite/sqliteindex-test.cpp @@ -1,7 +1,7 @@ // Copyright (C) 2017 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" #include @@ -11,7 +11,7 @@ using Sqlite::Exception; using Sqlite::Index; using Sqlite::IndexType; -TEST(Index, OneColumn) +TEST(Index, one_column) { Index index{"tableName", {"column1"}}; @@ -20,7 +20,7 @@ TEST(Index, OneColumn) ASSERT_THAT(sqlStatement, Eq("CREATE INDEX IF NOT EXISTS index_tableName_column1 ON tableName(column1)")); } -TEST(Index, TwoColumn) +TEST(Index, two_column) { Index index{"tableName", {"column1", "column2"}}; @@ -29,21 +29,21 @@ TEST(Index, TwoColumn) ASSERT_THAT(sqlStatement, Eq("CREATE INDEX IF NOT EXISTS index_tableName_column1_column2 ON tableName(column1, column2)")); } -TEST(Index, EmptyTableName) +TEST(Index, empty_table_name) { Index index{"", {"column1", "column2"}}; ASSERT_THROW(index.sqlStatement(), Exception); } -TEST(Index, EmptyColumns) +TEST(Index, empty_columns) { Index index{"tableName", {}}; ASSERT_THROW(index.sqlStatement(), Exception); } -TEST(Index, UniqueIndex) +TEST(Index, unique_index) { Index index{"tableName", {"column1"}, IndexType::Unique}; @@ -52,7 +52,7 @@ TEST(Index, UniqueIndex) ASSERT_THAT(sqlStatement, Eq("CREATE UNIQUE INDEX IF NOT EXISTS index_tableName_column1 ON tableName(column1)")); } -TEST(Index, Condition) +TEST(Index, condition) { Index index{"tableName", {"column1"}, IndexType::Normal, "column1 IS NOT NULL"}; diff --git a/tests/unit/unittest/sqlitesessions-test.cpp b/tests/unit/tests/unittests/sqlite/sqlitesessions-test.cpp similarity index 86% rename from tests/unit/unittest/sqlitesessions-test.cpp rename to tests/unit/tests/unittests/sqlite/sqlitesessions-test.cpp index be651ae208b..e6d5fcc1426 100644 --- a/tests/unit/unittest/sqlitesessions-test.cpp +++ b/tests/unit/tests/unittests/sqlite/sqlitesessions-test.cpp @@ -1,7 +1,7 @@ // Copyright (C) 2020 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" #include #include @@ -136,12 +136,12 @@ protected: Sqlite::ReadStatement<1> selectChangeSets{"SELECT changeset FROM testsessions", database}; }; -TEST_F(SqliteSessions, DontThrowForCommittingWithoutSessionStart) +TEST_F(SqliteSessions, dont_throw_for_committing_without_session_start) { ASSERT_NO_THROW(sessions.commit()); } -TEST_F(SqliteSessions, CreateEmptySession) +TEST_F(SqliteSessions, create_empty_session) { sessions.create(); sessions.commit(); @@ -149,7 +149,7 @@ TEST_F(SqliteSessions, CreateEmptySession) ASSERT_THAT(sessions.changeSets(), IsEmpty()); } -TEST_F(SqliteSessions, CreateSessionWithInsert) +TEST_F(SqliteSessions, create_session_with_insert) { sessions.create(); insertData.write("foo", 22, 3.14); @@ -158,7 +158,7 @@ TEST_F(SqliteSessions, CreateSessionWithInsert) ASSERT_THAT(sessions.changeSets(), SizeIs(1)); } -TEST_F(SqliteSessions, CreateSessionWithUpdate) +TEST_F(SqliteSessions, create_session_with_update) { insertData.write("foo", 22, 3.14); @@ -169,7 +169,7 @@ TEST_F(SqliteSessions, CreateSessionWithUpdate) ASSERT_THAT(sessions.changeSets(), SizeIs(1)); } -TEST_F(SqliteSessions, CreateSessionWithDelete) +TEST_F(SqliteSessions, create_session_with_delete) { insertData.write("foo", 22, 3.14); @@ -180,7 +180,7 @@ TEST_F(SqliteSessions, CreateSessionWithDelete) ASSERT_THAT(sessions.changeSets(), SizeIs(1)); } -TEST_F(SqliteSessions, CreateSessionWithInsertAndUpdate) +TEST_F(SqliteSessions, create_session_with_insert_and_update) { sessions.create(); insertData.write("foo", 22, 3.14); @@ -193,7 +193,7 @@ TEST_F(SqliteSessions, CreateSessionWithInsertAndUpdate) ASSERT_THAT(sessions.changeSets(), SizeIs(2)); } -TEST_F(SqliteSessions, CreateSession) +TEST_F(SqliteSessions, create_session) { sessions.create(); insertData.write("foo", 22, 3.14); @@ -203,7 +203,7 @@ TEST_F(SqliteSessions, CreateSession) ASSERT_THAT(sessions.changeSets(), SizeIs(1)); } -TEST_F(SqliteSessions, RevertSession) +TEST_F(SqliteSessions, revert_session) { sessions.create(); insertData.write("foo", 22, 3.14); @@ -214,7 +214,7 @@ TEST_F(SqliteSessions, RevertSession) ASSERT_THAT(fetchData(), IsEmpty()); } -TEST_F(SqliteSessions, RevertSessionToBase) +TEST_F(SqliteSessions, revert_session_to_base) { insertData.write("bar", "foo", 99); sessions.create(); @@ -226,7 +226,7 @@ TEST_F(SqliteSessions, RevertSessionToBase) ASSERT_THAT(fetchData(), ElementsAre(HasData("bar", "foo", 99))); } -TEST_F(SqliteSessions, RevertMultipleSession) +TEST_F(SqliteSessions, revert_multiple_session) { sessions.create(); insertData.write("foo", 22, 3.14); @@ -240,7 +240,7 @@ TEST_F(SqliteSessions, RevertMultipleSession) ASSERT_THAT(fetchData(), IsEmpty()); } -TEST_F(SqliteSessions, ApplySession) +TEST_F(SqliteSessions, apply_session) { sessions.create(); insertData.write("foo", 22, 3.14); @@ -251,7 +251,7 @@ TEST_F(SqliteSessions, ApplySession) ASSERT_THAT(fetchData(), ElementsAre(HasData("foo", 22, 3.14))); } -TEST_F(SqliteSessions, ApplySessionAfterAddingNewEntries) +TEST_F(SqliteSessions, apply_session_after_adding_new_entries) { sessions.create(); insertData.write("foo", 22, 3.14); @@ -264,7 +264,7 @@ TEST_F(SqliteSessions, ApplySessionAfterAddingNewEntries) UnorderedElementsAre(HasData("foo", 22, 3.14), HasData("bar", "foo", 99))); } -TEST_F(SqliteSessions, ApplyOverridesEntriesWithUniqueConstraint) +TEST_F(SqliteSessions, apply_overrides_entries_with_unique_constraint) { sessions.create(); insertData.write("foo", 22, 3.14); @@ -276,7 +276,7 @@ TEST_F(SqliteSessions, ApplyOverridesEntriesWithUniqueConstraint) ASSERT_THAT(fetchData(), ElementsAre(HasData("foo", 22, 3.14))); } -TEST_F(SqliteSessions, ApplyDoesNotOverrideDeletedEntries) +TEST_F(SqliteSessions, apply_does_not_override_deleted_entries) { insertData.write("foo", "bar", 3.14); sessions.create(); @@ -289,7 +289,7 @@ TEST_F(SqliteSessions, ApplyDoesNotOverrideDeletedEntries) ASSERT_THAT(fetchData(), IsEmpty()); } -TEST_F(SqliteSessions, ApplyDoesOnlyOverwriteUpdatedValues) +TEST_F(SqliteSessions, apply_does_only_overwrite_updated_values) { insertData.write("foo", "bar", 3.14); sessions.create(); @@ -302,7 +302,7 @@ TEST_F(SqliteSessions, ApplyDoesOnlyOverwriteUpdatedValues) ASSERT_THAT(fetchData(), ElementsAre(HasData("foo", "poo", 1234))); } -TEST_F(SqliteSessions, ApplyDoesDoesNotOverrideForeignKeyIfReferenceIsDeleted) +TEST_F(SqliteSessions, apply_does_does_not_override_foreign_key_if_reference_is_deleted) { insertData.write("foo2", "bar", 3.14); insertData.write("foo", "bar", 3.14); @@ -317,7 +317,7 @@ TEST_F(SqliteSessions, ApplyDoesDoesNotOverrideForeignKeyIfReferenceIsDeleted) ASSERT_THAT(fetchTags(), ElementsAre(HasTag("foo2", 4321))); } -TEST_F(SqliteSessions, ApplyDoesDoesNotOverrideIfConstraintsIsApplied) +TEST_F(SqliteSessions, apply_does_does_not_override_if_constraints_is_applied) { insertData.write("foo", "bar", 3.14); sessions.create(); @@ -331,7 +331,7 @@ TEST_F(SqliteSessions, ApplyDoesDoesNotOverrideIfConstraintsIsApplied) ASSERT_THAT(fetchTags(), IsEmpty()); } -TEST_F(SqliteSessions, ApplyDoesDoesNotOverrideForeignKeyIfReferenceIsDeletedDeferred) +TEST_F(SqliteSessions, apply_does_does_not_override_foreign_key_if_reference_is_deleted_deferred) { database.unlock(); Sqlite::DeferredTransaction transaction{database}; @@ -350,7 +350,7 @@ TEST_F(SqliteSessions, ApplyDoesDoesNotOverrideForeignKeyIfReferenceIsDeletedDef ASSERT_THAT(fetchTags(), ElementsAre(HasTag("foo2", 4321))); } -TEST_F(SqliteSessions, EndSessionOnRollback) +TEST_F(SqliteSessions, end_session_on_rollback) { insertData.write("foo", "bar", 3.14); sessions.create(); @@ -367,7 +367,7 @@ TEST_F(SqliteSessions, EndSessionOnRollback) ASSERT_THAT(fetchData(), ElementsAre(HasData("foo", 333, 666))); } -TEST_F(SqliteSessions, EndSessionOnCommit) +TEST_F(SqliteSessions, end_session_on_commit) { insertData.write("foo", "bar", 3.14); sessions.create(); @@ -381,7 +381,7 @@ TEST_F(SqliteSessions, EndSessionOnCommit) ASSERT_THAT(fetchData(), ElementsAre(HasData("foo", "bar", 99))); } -TEST_F(SqliteSessions, DeleteSessions) +TEST_F(SqliteSessions, delete_sessions) { insertData.write("foo", "bar", 3.14); sessions.create(); @@ -395,7 +395,7 @@ TEST_F(SqliteSessions, DeleteSessions) ASSERT_THAT(fetchData(), ElementsAre(HasData("foo", "bar", 3.14))); } -TEST_F(SqliteSessions, DeleteAllSessions) +TEST_F(SqliteSessions, delete_all_sessions) { insertData.write("foo", "bar", 3.14); sessions.create(); @@ -409,7 +409,7 @@ TEST_F(SqliteSessions, DeleteAllSessions) ASSERT_THAT(fetchData(), ElementsAre(HasData("foo", "bar", 3.14))); } -TEST_F(SqliteSessions, ApplyAndUpdateSessions) +TEST_F(SqliteSessions, apply_and_update_sessions) { insertData.write("foo", "bar", 3.14); sessions.create(); @@ -424,7 +424,7 @@ TEST_F(SqliteSessions, ApplyAndUpdateSessions) ASSERT_THAT(fetchData(), ElementsAre(HasData("foo", "bar", 22))); } -TEST_F(SqliteSessions, ApplyAndUpdateSessionsHasOnlyOneChangeSet) +TEST_F(SqliteSessions, apply_and_update_sessions_has_only_one_change_set) { insertData.write("foo", "bar", 3.14); sessions.create(); @@ -437,7 +437,7 @@ TEST_F(SqliteSessions, ApplyAndUpdateSessionsHasOnlyOneChangeSet) ASSERT_THAT(sessions.changeSets(), SizeIs(1)); } -TEST_F(SqliteSessions, ForEmptySessionBeginEqualsEnd) +TEST_F(SqliteSessions, for_empty_session_begin_equals_end) { auto changeSets = sessions.changeSets(); @@ -446,7 +446,7 @@ TEST_F(SqliteSessions, ForEmptySessionBeginEqualsEnd) ASSERT_THAT(begin, Eq(changeSets.end())); } -TEST_F(SqliteSessions, IteratorBeginUnequalsEndIfChangeSetHasContent) +TEST_F(SqliteSessions, iterator_begin_unequals_end_if_change_set_has_content) { sessions.create(); insertData.write("foo", "bar", 3.14); @@ -459,7 +459,7 @@ TEST_F(SqliteSessions, IteratorBeginUnequalsEndIfChangeSetHasContent) ASSERT_THAT(begin, Ne(changeSet.end())); } -TEST_F(SqliteSessions, NextIteratorUnequalsBeginIfChangeSetHasContent) +TEST_F(SqliteSessions, next_iterator_unequals_begin_if_change_set_has_content) { sessions.create(); insertData.write("foo", "bar", 3.14); @@ -472,7 +472,7 @@ TEST_F(SqliteSessions, NextIteratorUnequalsBeginIfChangeSetHasContent) ASSERT_NE(next, changeSet.begin()); } -TEST_F(SqliteSessions, NextIteratorEqualsEndIfChangeSetHasContent) +TEST_F(SqliteSessions, next_iterator_equals_end_if_change_set_has_content) { sessions.create(); insertData.write("foo", "bar", 3.14); @@ -485,7 +485,7 @@ TEST_F(SqliteSessions, NextIteratorEqualsEndIfChangeSetHasContent) ASSERT_THAT(next, Eq(changeSet.end())); } -TEST_F(SqliteSessions, NextIteratorNotUnqualsEndIfChangeSetHasContent) +TEST_F(SqliteSessions, next_iterator_not_unquals_end_if_change_set_has_content) { sessions.create(); insertData.write("foo", "bar", 3.14); @@ -498,7 +498,7 @@ TEST_F(SqliteSessions, NextIteratorNotUnqualsEndIfChangeSetHasContent) ASSERT_THAT(next, Not(Ne(changeSet.end()))); } -TEST_F(SqliteSessions, BeginIteratorHasInsertOperation) +TEST_F(SqliteSessions, begin_iterator_has_insert_operation) { sessions.create(); insertData.write("foo", "bar", 3.14); @@ -512,7 +512,7 @@ TEST_F(SqliteSessions, BeginIteratorHasInsertOperation) ASSERT_THAT(tuple.operation, Eq(Operation::Insert)); } -TEST_F(SqliteSessions, BeginIteratorHasUpdateOperation) +TEST_F(SqliteSessions, begin_iterator_has_update_operation) { insertData.write("foo", "bar", 3.14); sessions.create(); @@ -527,7 +527,7 @@ TEST_F(SqliteSessions, BeginIteratorHasUpdateOperation) ASSERT_THAT(tuple.operation, Eq(Operation::Update)); } -TEST_F(SqliteSessions, BeginIteratorHasDeleteOperation) +TEST_F(SqliteSessions, begin_iterator_has_delete_operation) { insertData.write("foo", "bar", 3.14); sessions.create(); @@ -542,7 +542,7 @@ TEST_F(SqliteSessions, BeginIteratorHasDeleteOperation) ASSERT_THAT(tuple.operation, Eq(Operation::Delete)); } -TEST_F(SqliteSessions, BeginIteratorHasDataTableName) +TEST_F(SqliteSessions, begin_iterator_has_data_table_name) { sessions.create(); insertData.write("foo", "bar", 3.14); @@ -556,7 +556,7 @@ TEST_F(SqliteSessions, BeginIteratorHasDataTableName) ASSERT_THAT(tuple.table, Eq("data")); } -TEST_F(SqliteSessions, ConvertAllValueTypesInChangeSet) +TEST_F(SqliteSessions, convert_all_value_types_in_change_set) { sessions.create(); insertData.write("foo", "bar", 3.14); @@ -575,7 +575,7 @@ TEST_F(SqliteSessions, ConvertAllValueTypesInChangeSet) HasValues(3.14, nullptr))); } -TEST_F(SqliteSessions, InsertOneValueChangeSet) +TEST_F(SqliteSessions, insert_one_value_change_set) { sessions.create(); insertOneDatum.write("foo", Sqlite::NullValue{}); @@ -594,7 +594,7 @@ TEST_F(SqliteSessions, InsertOneValueChangeSet) HasValues("foo", nullptr))); } -TEST_F(SqliteSessions, UpdateOneValueChangeSet) +TEST_F(SqliteSessions, update_one_value_change_set) { insertData.write("foo", "bar", 3.14); sessions.create(); @@ -614,7 +614,7 @@ TEST_F(SqliteSessions, UpdateOneValueChangeSet) HasValues(99, 3.14))); } -TEST_F(SqliteSessions, DeleteRowChangeSet) +TEST_F(SqliteSessions, delete_row_change_set) { insertData.write("foo", "bar", 3.14); sessions.create(); @@ -635,7 +635,7 @@ TEST_F(SqliteSessions, DeleteRowChangeSet) HasValues(nullptr, 3.14))); } -TEST_F(SqliteSessions, EmptyChangeSet) +TEST_F(SqliteSessions, empty_change_set) { sessions.create(); sessions.commit(); @@ -645,7 +645,7 @@ TEST_F(SqliteSessions, EmptyChangeSet) ASSERT_THAT(changeSets, ElementsAre()); } -TEST_F(SqliteSessions, AccessInsertOneValueChangeSet) +TEST_F(SqliteSessions, access_insert_one_value_change_set) { sessions.create(); insertOneDatum.write("foo", Sqlite::NullValue{}); @@ -660,7 +660,7 @@ TEST_F(SqliteSessions, AccessInsertOneValueChangeSet) ASSERT_THAT(value, HasValues("foo", nullptr)); } -TEST_F(SqliteSessions, AccessUpdateOneValueChangeSet) +TEST_F(SqliteSessions, access_update_one_value_change_set) { insertData.write("foo", "bar", 3.14); sessions.create(); @@ -676,7 +676,7 @@ TEST_F(SqliteSessions, AccessUpdateOneValueChangeSet) ASSERT_THAT(value, HasValues(99, 3.14)); } -TEST_F(SqliteSessions, AccessDeleteRowChangeSet) +TEST_F(SqliteSessions, access_delete_row_change_set) { insertData.write("foo", "bar", 3.14); sessions.create(); diff --git a/tests/unit/unittest/sqlitestatement-test.cpp b/tests/unit/tests/unittests/sqlite/sqlitestatement-test.cpp similarity index 82% rename from tests/unit/unittest/sqlitestatement-test.cpp rename to tests/unit/tests/unittests/sqlite/sqlitestatement-test.cpp index 84c2df61984..64a9cdd2772 100644 --- a/tests/unit/unittest/sqlitestatement-test.cpp +++ b/tests/unit/tests/unittests/sqlite/sqlitestatement-test.cpp @@ -1,9 +1,11 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" -#include "mocksqlitestatement.h" -#include "sqlitedatabasemock.h" +#include "../utils/googletest.h" + +#include "../mocks/mocksqlitestatement.h" +#include "../mocks/sqlitedatabasemock.h" + #include "sqliteteststatement.h" #include @@ -51,12 +53,12 @@ bool compareValue(SqliteTestStatement<2, 1> &statement, Type value, int column) return false; } -MATCHER_P3(HasValues, value1, value2, rowid, - std::string(negation ? "isn't" : "is") - + PrintToString(value1) - + ", " + PrintToString(value2) - + " and " + PrintToString(rowid) - ) +MATCHER_P3(HasValues, + value1, + value2, + rowid, + std::string(negation ? "isn't" : "is") + PrintToString(value1) + ", " + + PrintToString(value2) + " and " + PrintToString(rowid)) { Database &database = arg.database(); @@ -132,28 +134,29 @@ struct Output } friend std::ostream &operator<<(std::ostream &out, const Output &o) { - return out << "(" << o.name << ", " << ", " << o.number<< ", " << o.value<< ")"; + return out << "(" << o.name << ", " + << ", " << o.number << ", " << o.value << ")"; } }; -TEST_F(SqliteStatement, ThrowsStatementHasErrorForWrongSqlStatement) +TEST_F(SqliteStatement, throws_statement_has_error_for_wrong_sql_statement) { ASSERT_THROW(ReadStatement<0>("blah blah blah", database), Sqlite::StatementHasError); } -TEST_F(SqliteStatement, ThrowsNotReadOnlySqlStatementForWritableSqlStatementInReadStatement) +TEST_F(SqliteStatement, throws_not_read_only_sql_statement_for_writable_sql_statement_in_read_statement) { ASSERT_THROW(ReadStatement<0>("INSERT INTO test(name, number) VALUES (?, ?)", database), Sqlite::NotReadOnlySqlStatement); } -TEST_F(SqliteStatement, ThrowsNotReadonlySqlStatementForWritableSqlStatementInReadStatement) +TEST_F(SqliteStatement, throws_not_readonly_sql_statement_for_writable_sql_statement_in_read_statement) { ASSERT_THROW(WriteStatement("SELECT name, number FROM test", database), Sqlite::NotWriteSqlStatement); } -TEST_F(SqliteStatement, CountRows) +TEST_F(SqliteStatement, count_rows) { SqliteTestStatement<3> statement("SELECT * FROM test", database); int nextCount = 0; @@ -165,7 +168,7 @@ TEST_F(SqliteStatement, CountRows) ASSERT_THAT(nextCount, sqlCount); } -TEST_F(SqliteStatement, Value) +TEST_F(SqliteStatement, value) { SqliteTestStatement<3> statement("SELECT name, number, value FROM test ORDER BY name", database); statement.next(); @@ -189,33 +192,33 @@ TEST_F(SqliteStatement, Value) ASSERT_THAT(statement.fetchValueView(2), Eq(2)); } -TEST_F(SqliteStatement, ToIntegerValue) +TEST_F(SqliteStatement, to_integer_value) { auto value = ReadStatement<1>::toValue("SELECT number FROM test WHERE name='foo'", database); ASSERT_THAT(value, 23); } -TEST_F(SqliteStatement, ToLongIntegerValue) +TEST_F(SqliteStatement, to_long_integer_value) { ASSERT_THAT(ReadStatement<1>::toValue("SELECT number FROM test WHERE name='foo'", database), Eq(23)); } -TEST_F(SqliteStatement, ToDoubleValue) +TEST_F(SqliteStatement, to_double_value) { ASSERT_THAT(ReadStatement<1>::toValue("SELECT number FROM test WHERE name='foo'", database), 23.3); } -TEST_F(SqliteStatement, ToStringValue) +TEST_F(SqliteStatement, to_string_value) { ASSERT_THAT(ReadStatement<1>::toValue( "SELECT name FROM test WHERE name='foo'", database), "foo"); } -TEST_F(SqliteStatement, BindNull) +TEST_F(SqliteStatement, bind_null) { database.execute("INSERT INTO test VALUES (NULL, 323, 344)"); SqliteTestStatement<2, 1> statement("SELECT name, number FROM test WHERE name IS ?", database); @@ -227,7 +230,7 @@ TEST_F(SqliteStatement, BindNull) ASSERT_THAT(statement.fetchValue(1), 323); } -TEST_F(SqliteStatement, BindNullValue) +TEST_F(SqliteStatement, bind_null_value) { database.execute("INSERT INTO test VALUES (NULL, 323, 344)"); SqliteTestStatement<2, 1> statement("SELECT name, number FROM test WHERE name IS ?", database); @@ -239,7 +242,7 @@ TEST_F(SqliteStatement, BindNullValue) ASSERT_THAT(statement.fetchValue(1), 323); } -TEST_F(SqliteStatement, BindInvalidIntIdToNull) +TEST_F(SqliteStatement, bind_invalid_int_id_to_null) { TestIntId id; SqliteTestStatement<0, 1> statement("INSERT INTO test VALUES ('id', 323, ?)", database); @@ -252,7 +255,7 @@ TEST_F(SqliteStatement, BindInvalidIntIdToNull) ASSERT_THAT(readStatement.fetchType(0), Sqlite::Type::Null); } -TEST_F(SqliteStatement, BindIntId) +TEST_F(SqliteStatement, bind_int_id) { TestIntId id{TestIntId::create(42)}; SqliteTestStatement<0, 1> statement("INSERT INTO test VALUES ('id', 323, ?)", database); @@ -266,7 +269,7 @@ TEST_F(SqliteStatement, BindIntId) ASSERT_THAT(readStatement.fetchIntValue(0), 42); } -TEST_F(SqliteStatement, BindInvalidLongLongIdToNull) +TEST_F(SqliteStatement, bind_invalid_long_long_id_to_null) { TestLongLongId id; SqliteTestStatement<0, 1> statement("INSERT INTO test VALUES ('id', 323, ?)", database); @@ -279,7 +282,7 @@ TEST_F(SqliteStatement, BindInvalidLongLongIdToNull) ASSERT_THAT(readStatement.fetchType(0), Sqlite::Type::Null); } -TEST_F(SqliteStatement, BindLongLongId) +TEST_F(SqliteStatement, bind_long_long_id) { TestLongLongId id{TestLongLongId::create(42)}; SqliteTestStatement<0, 1> statement("INSERT INTO test VALUES ('id', 323, ?)", database); @@ -293,7 +296,7 @@ TEST_F(SqliteStatement, BindLongLongId) ASSERT_THAT(readStatement.fetchIntValue(0), 42); } -TEST_F(SqliteStatement, BindString) +TEST_F(SqliteStatement, bind_string) { SqliteTestStatement<2, 1> statement("SELECT name, number FROM test WHERE name=?", database); @@ -304,17 +307,17 @@ TEST_F(SqliteStatement, BindString) ASSERT_THAT(statement.fetchValue(1), 23.3); } -TEST_F(SqliteStatement, BindInteger) +TEST_F(SqliteStatement, bind_integer) { SqliteTestStatement<2, 1> statement("SELECT name, number FROM test WHERE number=?", database); statement.bind(1, 40); statement.next(); - ASSERT_THAT(statement.fetchSmallStringViewValue(0),"poo"); + ASSERT_THAT(statement.fetchSmallStringViewValue(0), "poo"); } -TEST_F(SqliteStatement, BindLongInteger) +TEST_F(SqliteStatement, bind_long_integer) { SqliteTestStatement<2, 1> statement("SELECT name, number FROM test WHERE number=?", database); @@ -324,7 +327,7 @@ TEST_F(SqliteStatement, BindLongInteger) ASSERT_THAT(statement.fetchSmallStringViewValue(0), "poo"); } -TEST_F(SqliteStatement, BindDouble) +TEST_F(SqliteStatement, bind_double) { SqliteTestStatement<2, 1> statement("SELECT name, number FROM test WHERE number=?", database); @@ -334,7 +337,7 @@ TEST_F(SqliteStatement, BindDouble) ASSERT_THAT(statement.fetchSmallStringViewValue(0), "foo"); } -TEST_F(SqliteStatement, BindPointer) +TEST_F(SqliteStatement, bind_pointer) { SqliteTestStatement<1, 1> statement("SELECT value FROM carray(?, 5, 'int64')", database); std::vector values{1, 1, 2, 3, 5}; @@ -345,7 +348,7 @@ TEST_F(SqliteStatement, BindPointer) ASSERT_THAT(statement.fetchIntValue(0), 1); } -TEST_F(SqliteStatement, BindIntCarray) +TEST_F(SqliteStatement, bind_int_carray) { SqliteTestStatement<1, 1> statement("SELECT value FROM carray(?)", database); std::vector values{3, 10, 20, 33, 55}; @@ -359,7 +362,7 @@ TEST_F(SqliteStatement, BindIntCarray) ASSERT_THAT(statement.fetchIntValue(0), 33); } -TEST_F(SqliteStatement, BindLongLongCarray) +TEST_F(SqliteStatement, bind_long_long_carray) { SqliteTestStatement<1, 1> statement("SELECT value FROM carray(?)", database); std::vector values{3, 10, 20, 33, 55}; @@ -373,7 +376,7 @@ TEST_F(SqliteStatement, BindLongLongCarray) ASSERT_THAT(statement.fetchLongLongValue(0), 33); } -TEST_F(SqliteStatement, BindDoubleCarray) +TEST_F(SqliteStatement, bind_double_carray) { SqliteTestStatement<1, 1> statement("SELECT value FROM carray(?)", database); std::vector values{3.3, 10.2, 20.54, 33.21, 55}; @@ -387,7 +390,7 @@ TEST_F(SqliteStatement, BindDoubleCarray) ASSERT_THAT(statement.fetchDoubleValue(0), 33.21); } -TEST_F(SqliteStatement, BindTextCarray) +TEST_F(SqliteStatement, bind_text_carray) { SqliteTestStatement<1, 1> statement("SELECT value FROM carray(?)", database); std::vector values{"yi", "er", "san", "se", "wu"}; @@ -401,7 +404,7 @@ TEST_F(SqliteStatement, BindTextCarray) ASSERT_THAT(statement.fetchSmallStringViewValue(0), Eq("se")); } -TEST_F(SqliteStatement, BindBlob) +TEST_F(SqliteStatement, bind_blob) { SqliteTestStatement<1, 1> statement("WITH T(blob) AS (VALUES (?)) SELECT blob FROM T", database); const unsigned char chars[] = "aaafdfdlll"; @@ -414,7 +417,7 @@ TEST_F(SqliteStatement, BindBlob) ASSERT_THAT(statement.fetchBlobValue(0), Eq(bytes)); } -TEST_F(SqliteStatement, BindEmptyBlob) +TEST_F(SqliteStatement, bind_empty_blob) { SqliteTestStatement<1, 1> statement("WITH T(blob) AS (VALUES (?)) SELECT blob FROM T", database); Sqlite::BlobView bytes; @@ -425,56 +428,56 @@ TEST_F(SqliteStatement, BindEmptyBlob) ASSERT_THAT(statement.fetchBlobValue(0), IsEmpty()); } -TEST_F(SqliteStatement, BindIndexIsZeroIsThrowingBindingIndexIsOutOfBoundInt) +TEST_F(SqliteStatement, bind_index_is_zero_is_throwing_binding_index_is_out_of_bound_int) { SqliteTestStatement<2, 1> statement("SELECT name, number FROM test WHERE number=$1", database); ASSERT_THROW(statement.bind(0, 40), Sqlite::BindingIndexIsOutOfRange); } -TEST_F(SqliteStatement, BindIndexIsZeroIsThrowingBindingIndexIsOutOfBoundNull) +TEST_F(SqliteStatement, bind_index_is_zero_is_throwing_binding_index_is_out_of_bound_null) { SqliteTestStatement<2, 1> statement("SELECT name, number FROM test WHERE number=$1", database); ASSERT_THROW(statement.bind(0, Sqlite::NullValue{}), Sqlite::BindingIndexIsOutOfRange); } -TEST_F(SqliteStatement, BindIndexIsToLargeIsThrowingBindingIndexIsOutOfBoundLongLong) +TEST_F(SqliteStatement, bind_index_is_to_large_is_throwing_binding_index_is_out_of_bound_long_long) { SqliteTestStatement<2, 1> statement("SELECT name, number FROM test WHERE number=$1", database); ASSERT_THROW(statement.bind(2, 40LL), Sqlite::BindingIndexIsOutOfRange); } -TEST_F(SqliteStatement, BindIndexIsToLargeIsThrowingBindingIndexIsOutOfBoundStringView) +TEST_F(SqliteStatement, bind_index_is_to_large_is_throwing_binding_index_is_out_of_bound_string_view) { SqliteTestStatement<2, 1> statement("SELECT name, number FROM test WHERE number=$1", database); ASSERT_THROW(statement.bind(2, "foo"), Sqlite::BindingIndexIsOutOfRange); } -TEST_F(SqliteStatement, BindIndexIsToLargeIsThrowingBindingIndexIsOutOfBoundStringFloat) +TEST_F(SqliteStatement, bind_index_is_to_large_is_throwing_binding_index_is_out_of_bound_string_float) { SqliteTestStatement<2, 1> statement("SELECT name, number FROM test WHERE number=$1", database); ASSERT_THROW(statement.bind(2, 2.), Sqlite::BindingIndexIsOutOfRange); } -TEST_F(SqliteStatement, BindIndexIsToLargeIsThrowingBindingIndexIsOutOfBoundPointer) +TEST_F(SqliteStatement, bind_index_is_to_large_is_throwing_binding_index_is_out_of_bound_pointer) { SqliteTestStatement<2, 1> statement("SELECT name, number FROM test WHERE number=$1", database); ASSERT_THROW(statement.bind(2, nullptr), Sqlite::BindingIndexIsOutOfRange); } -TEST_F(SqliteStatement, BindIndexIsToLargeIsThrowingBindingIndexIsOutOfBoundValue) +TEST_F(SqliteStatement, bind_index_is_to_large_is_throwing_binding_index_is_out_of_bound_value) { SqliteTestStatement<2, 1> statement("SELECT name, number FROM test WHERE number=$1", database); ASSERT_THROW(statement.bind(2, Sqlite::Value{1}), Sqlite::BindingIndexIsOutOfRange); } -TEST_F(SqliteStatement, BindIndexIsToLargeIsThrowingBindingIndexIsOutOfBoundBlob) +TEST_F(SqliteStatement, bind_index_is_to_large_is_throwing_binding_index_is_out_of_bound_blob) { SqliteTestStatement<1, 1> statement("WITH T(blob) AS (VALUES (?)) SELECT blob FROM T", database); Sqlite::BlobView bytes{QByteArray{"XXX"}}; @@ -482,7 +485,7 @@ TEST_F(SqliteStatement, BindIndexIsToLargeIsThrowingBindingIndexIsOutOfBoundBlob ASSERT_THROW(statement.bind(2, bytes), Sqlite::BindingIndexIsOutOfRange); } -TEST_F(SqliteStatement, BindValues) +TEST_F(SqliteStatement, bind_values) { SqliteTestStatement<0, 3> statement("UPDATE test SET name=?, number=? WHERE rowid=?", database); @@ -492,7 +495,7 @@ TEST_F(SqliteStatement, BindValues) ASSERT_THAT(statement, HasValues("see", "7.23", 1)); } -TEST_F(SqliteStatement, BindNullValues) +TEST_F(SqliteStatement, bind_null_values) { SqliteTestStatement<0, 3> statement("UPDATE test SET name=?, number=? WHERE rowid=?", database); @@ -502,7 +505,7 @@ TEST_F(SqliteStatement, BindNullValues) ASSERT_THAT(statement, HasNullValues(1)); } -TEST_F(SqliteStatement, WriteValues) +TEST_F(SqliteStatement, write_values) { WriteStatement<3> statement("UPDATE test SET name=?, number=? WHERE rowid=?", database); @@ -511,7 +514,7 @@ TEST_F(SqliteStatement, WriteValues) ASSERT_THAT(statement, HasValues("see", "7.23", 1)); } -TEST_F(SqliteStatement, WritePointerValues) +TEST_F(SqliteStatement, write_pointer_values) { SqliteTestStatement<1, 2> statement("SELECT value FROM carray(?, ?, 'int64')", database); std::vector values{1, 1, 2, 3, 5}; @@ -521,7 +524,7 @@ TEST_F(SqliteStatement, WritePointerValues) ASSERT_THAT(results, ElementsAre(1, 1, 2, 3, 5)); } -TEST_F(SqliteStatement, WriteIntCarrayValues) +TEST_F(SqliteStatement, write_int_carray_values) { SqliteTestStatement<1, 1> statement("SELECT value FROM carray(?)", database); std::vector values{3, 10, 20, 33, 55}; @@ -531,7 +534,7 @@ TEST_F(SqliteStatement, WriteIntCarrayValues) ASSERT_THAT(results, ElementsAre(3, 10, 20, 33, 55)); } -TEST_F(SqliteStatement, WriteLongLongCarrayValues) +TEST_F(SqliteStatement, write_long_long_carray_values) { SqliteTestStatement<1, 1> statement("SELECT value FROM carray(?)", database); std::vector values{3, 10, 20, 33, 55}; @@ -541,7 +544,7 @@ TEST_F(SqliteStatement, WriteLongLongCarrayValues) ASSERT_THAT(results, ElementsAre(3, 10, 20, 33, 55)); } -TEST_F(SqliteStatement, WriteDoubleCarrayValues) +TEST_F(SqliteStatement, write_double_carray_values) { SqliteTestStatement<1, 1> statement("SELECT value FROM carray(?)", database); std::vector values{3.3, 10.2, 20.54, 33.21, 55}; @@ -551,7 +554,7 @@ TEST_F(SqliteStatement, WriteDoubleCarrayValues) ASSERT_THAT(results, ElementsAre(3.3, 10.2, 20.54, 33.21, 55)); } -TEST_F(SqliteStatement, WriteTextCarrayValues) +TEST_F(SqliteStatement, write_text_carray_values) { SqliteTestStatement<1, 1> statement("SELECT value FROM carray(?)", database); std::vector values{"yi", "er", "san", "se", "wu"}; @@ -561,7 +564,7 @@ TEST_F(SqliteStatement, WriteTextCarrayValues) ASSERT_THAT(results, ElementsAre("yi", "er", "san", "se", "wu")); } -TEST_F(SqliteStatement, WriteNullValues) +TEST_F(SqliteStatement, write_null_values) { WriteStatement<3> statement("UPDATE test SET name=?, number=? WHERE rowid=?", database); statement.write(1, 1, 1); @@ -571,7 +574,7 @@ TEST_F(SqliteStatement, WriteNullValues) ASSERT_THAT(statement, HasNullValues(1)); } -TEST_F(SqliteStatement, WriteSqliteIntegerValue) +TEST_F(SqliteStatement, write_sqlite_integer_value) { WriteStatement<3> statement("UPDATE test SET name=?, number=? WHERE rowid=?", database); statement.write(1, 1, 1); @@ -581,7 +584,7 @@ TEST_F(SqliteStatement, WriteSqliteIntegerValue) ASSERT_THAT(statement, HasValues("see", 33, 1)); } -TEST_F(SqliteStatement, WriteSqliteDoubeValue) +TEST_F(SqliteStatement, write_sqlite_doube_value) { WriteStatement<3> statement("UPDATE test SET name=?, number=? WHERE rowid=?", database); @@ -590,7 +593,7 @@ TEST_F(SqliteStatement, WriteSqliteDoubeValue) ASSERT_THAT(statement, HasValues("see", 7.23, 1)); } -TEST_F(SqliteStatement, WriteSqliteStringValue) +TEST_F(SqliteStatement, write_sqlite_string_value) { WriteStatement<3> statement("UPDATE test SET name=?, number=? WHERE rowid=?", database); @@ -599,7 +602,7 @@ TEST_F(SqliteStatement, WriteSqliteStringValue) ASSERT_THAT(statement, HasValues("see", "foo", 1)); } -TEST_F(SqliteStatement, WriteSqliteBlobValue) +TEST_F(SqliteStatement, write_sqlite_blob_value) { SqliteTestStatement<0, 1> statement("INSERT INTO test VALUES ('blob', 40, ?)", database); SqliteTestStatement<1, 0> readStatement("SELECT value FROM test WHERE name = 'blob'", database); @@ -613,7 +616,7 @@ TEST_F(SqliteStatement, WriteSqliteBlobValue) Optional(Field(&Sqlite::Blob::bytes, Eq(bytes)))); } -TEST_F(SqliteStatement, WriteNullValueView) +TEST_F(SqliteStatement, write_null_value_view) { WriteStatement<3> statement("UPDATE test SET name=?, number=? WHERE rowid=?", database); statement.write(1, 1, 1); @@ -623,7 +626,7 @@ TEST_F(SqliteStatement, WriteNullValueView) ASSERT_THAT(statement, HasNullValues(1)); } -TEST_F(SqliteStatement, WriteSqliteIntegerValueView) +TEST_F(SqliteStatement, write_sqlite_integer_value_view) { WriteStatement<3> statement("UPDATE test SET name=?, number=? WHERE rowid=?", database); statement.write(1, 1, 1); @@ -633,7 +636,7 @@ TEST_F(SqliteStatement, WriteSqliteIntegerValueView) ASSERT_THAT(statement, HasValues("see", 33, 1)); } -TEST_F(SqliteStatement, WriteSqliteDoubeValueView) +TEST_F(SqliteStatement, write_sqlite_doube_value_view) { WriteStatement<3> statement("UPDATE test SET name=?, number=? WHERE rowid=?", database); @@ -642,7 +645,7 @@ TEST_F(SqliteStatement, WriteSqliteDoubeValueView) ASSERT_THAT(statement, HasValues("see", 7.23, 1)); } -TEST_F(SqliteStatement, WriteSqliteStringValueView) +TEST_F(SqliteStatement, write_sqlite_string_value_view) { WriteStatement<3> statement("UPDATE test SET name=?, number=? WHERE rowid=?", database); @@ -651,7 +654,7 @@ TEST_F(SqliteStatement, WriteSqliteStringValueView) ASSERT_THAT(statement, HasValues("see", "foo", 1)); } -TEST_F(SqliteStatement, WriteSqliteBlobValueView) +TEST_F(SqliteStatement, write_sqlite_blob_value_view) { SqliteTestStatement<0, 1> statement("INSERT INTO test VALUES ('blob', 40, ?)", database); SqliteTestStatement<1, 0> readStatement("SELECT value FROM test WHERE name = 'blob'", database); @@ -665,7 +668,7 @@ TEST_F(SqliteStatement, WriteSqliteBlobValueView) Optional(Field(&Sqlite::Blob::bytes, Eq(bytes)))); } -TEST_F(SqliteStatement, WriteEmptyBlobs) +TEST_F(SqliteStatement, write_empty_blobs) { SqliteTestStatement<1, 1> statement("WITH T(blob) AS (VALUES (?)) SELECT blob FROM T", database); @@ -676,7 +679,7 @@ TEST_F(SqliteStatement, WriteEmptyBlobs) ASSERT_THAT(statement.fetchBlobValue(0), IsEmpty()); } -TEST_F(SqliteStatement, EmptyBlobsAreNull) +TEST_F(SqliteStatement, empty_blobs_are_null) { SqliteTestStatement<1, 1> statement( "WITH T(blob) AS (VALUES (?)) SELECT ifnull(blob, 1) FROM T", database); @@ -688,7 +691,7 @@ TEST_F(SqliteStatement, EmptyBlobsAreNull) ASSERT_THAT(statement.fetchType(0), Eq(Sqlite::Type::Null)); } -TEST_F(SqliteStatement, WriteBlobs) +TEST_F(SqliteStatement, write_blobs) { SqliteTestStatement<0, 1> statement("INSERT INTO test VALUES ('blob', 40, ?)", database); SqliteTestStatement<1, 0> readStatement("SELECT value FROM test WHERE name = 'blob'", database); @@ -702,7 +705,7 @@ TEST_F(SqliteStatement, WriteBlobs) Optional(Field(&Sqlite::Blob::bytes, Eq(bytes)))); } -TEST_F(SqliteStatement, CannotWriteToClosedDatabase) +TEST_F(SqliteStatement, cannot_write_to_closed_database) { database.close(); @@ -710,14 +713,14 @@ TEST_F(SqliteStatement, CannotWriteToClosedDatabase) Sqlite::DatabaseIsNotOpen); } -TEST_F(SqliteStatement, CannotReadFromClosedDatabase) +TEST_F(SqliteStatement, cannot_read_from_closed_database) { database.close(); ASSERT_THROW(ReadStatement<3>("SELECT * FROM test", database), Sqlite::DatabaseIsNotOpen); } -TEST_F(SqliteStatement, GetTupleValuesWithoutArguments) +TEST_F(SqliteStatement, get_tuple_values_without_arguments) { using Tuple = std::tuple; ReadStatement<3> statement("SELECT name, number, value FROM test", database); @@ -728,7 +731,7 @@ TEST_F(SqliteStatement, GetTupleValuesWithoutArguments) UnorderedElementsAre(Tuple{"bar", 0, 1}, Tuple{"foo", 23.3, 2}, Tuple{"poo", 40.0, 3})); } -TEST_F(SqliteStatement, GetTupleRangeWithoutArguments) +TEST_F(SqliteStatement, get_tuple_range_without_arguments) { using Tuple = std::tuple; ReadStatement<3> statement("SELECT name, number, value FROM test", database); @@ -739,7 +742,7 @@ TEST_F(SqliteStatement, GetTupleRangeWithoutArguments) UnorderedElementsAre(Tuple{"bar", 0, 1}, Tuple{"foo", 23.3, 2}, Tuple{"poo", 40.0, 3})); } -TEST_F(SqliteStatement, GetTupleRangeWithTransactionWithoutArguments) +TEST_F(SqliteStatement, get_tuple_range_with_transaction_without_arguments) { using Tuple = std::tuple; ReadStatement<3> statement("SELECT name, number, value FROM test", database); @@ -752,7 +755,7 @@ TEST_F(SqliteStatement, GetTupleRangeWithTransactionWithoutArguments) database.lock(); } -TEST_F(SqliteStatement, GetTupleRangeInForRangeLoop) +TEST_F(SqliteStatement, get_tuple_range_in_for_range_loop) { using Tuple = std::tuple; ReadStatement<3> statement("SELECT name, number, value FROM test", database); @@ -765,7 +768,7 @@ TEST_F(SqliteStatement, GetTupleRangeInForRangeLoop) UnorderedElementsAre(Tuple{"bar", 0, 1}, Tuple{"foo", 23.3, 2}, Tuple{"poo", 40.0, 3})); } -TEST_F(SqliteStatement, GetTupleRangeWithTransactionInForRangeLoop) +TEST_F(SqliteStatement, get_tuple_range_with_transaction_in_for_range_loop) { using Tuple = std::tuple; ReadStatement<3> statement("SELECT name, number, value FROM test", database); @@ -780,7 +783,7 @@ TEST_F(SqliteStatement, GetTupleRangeWithTransactionInForRangeLoop) database.lock(); } -TEST_F(SqliteStatement, GetTupleRangeInForRangeLoopWithBreak) +TEST_F(SqliteStatement, get_tuple_range_in_for_range_loop_with_break) { using Tuple = std::tuple; ReadStatement<3> statement("SELECT name, number, value FROM test ORDER BY name", database); @@ -795,7 +798,7 @@ TEST_F(SqliteStatement, GetTupleRangeInForRangeLoopWithBreak) ASSERT_THAT(values, UnorderedElementsAre(Tuple{"bar", 0, 1}, Tuple{"foo", 23.3, 2})); } -TEST_F(SqliteStatement, GetTupleRangeWithTransactionInForRangeLoopWithBreak) +TEST_F(SqliteStatement, get_tuple_range_with_transaction_in_for_range_loop_with_break) { using Tuple = std::tuple; ReadStatement<3> statement("SELECT name, number, value FROM test ORDER BY name", database); @@ -812,7 +815,7 @@ TEST_F(SqliteStatement, GetTupleRangeWithTransactionInForRangeLoopWithBreak) database.lock(); } -TEST_F(SqliteStatement, GetTupleRangeInForRangeLoopWithContinue) +TEST_F(SqliteStatement, get_tuple_range_in_for_range_loop_with_continue) { using Tuple = std::tuple; ReadStatement<3> statement("SELECT name, number, value FROM test ORDER BY name", database); @@ -827,7 +830,7 @@ TEST_F(SqliteStatement, GetTupleRangeInForRangeLoopWithContinue) ASSERT_THAT(values, UnorderedElementsAre(Tuple{"bar", 0, 1}, Tuple{"poo", 40.0, 3})); } -TEST_F(SqliteStatement, GetTupleRangeWithTransactionInForRangeLoopWithContinue) +TEST_F(SqliteStatement, get_tuple_range_with_transaction_in_for_range_loop_with_continue) { using Tuple = std::tuple; ReadStatement<3> statement("SELECT name, number, value FROM test ORDER BY name", database); @@ -844,7 +847,7 @@ TEST_F(SqliteStatement, GetTupleRangeWithTransactionInForRangeLoopWithContinue) database.lock(); } -TEST_F(SqliteStatement, GetSingleValuesWithoutArguments) +TEST_F(SqliteStatement, get_single_values_without_arguments) { ReadStatement<1> statement("SELECT name FROM test", database); @@ -853,7 +856,7 @@ TEST_F(SqliteStatement, GetSingleValuesWithoutArguments) ASSERT_THAT(values, UnorderedElementsAre("bar", "foo", "poo")); } -TEST_F(SqliteStatement, GetSingleRangeWithoutArguments) +TEST_F(SqliteStatement, get_single_range_without_arguments) { ReadStatement<1> statement("SELECT name FROM test", database); @@ -863,7 +866,7 @@ TEST_F(SqliteStatement, GetSingleRangeWithoutArguments) ASSERT_THAT(values, UnorderedElementsAre("bar", "foo", "poo")); } -TEST_F(SqliteStatement, GetSingleRangeWithTransactionWithoutArguments) +TEST_F(SqliteStatement, get_single_range_with_transaction_without_arguments) { ReadStatement<1> statement("SELECT name FROM test", database); database.unlock(); @@ -891,7 +894,7 @@ public: } }; -TEST_F(SqliteStatement, GetSingleSqliteValuesWithoutArguments) +TEST_F(SqliteStatement, get_single_sqlite_values_without_arguments) { ReadStatement<1> statement("SELECT number FROM test", database); database.execute("INSERT INTO test VALUES (NULL, NULL, NULL)"); @@ -901,7 +904,7 @@ TEST_F(SqliteStatement, GetSingleSqliteValuesWithoutArguments) ASSERT_THAT(values, UnorderedElementsAre(Eq("blah"), Eq(23.3), Eq(40), IsNull())); } -TEST_F(SqliteStatement, GetSingleSqliteRangeWithoutArguments) +TEST_F(SqliteStatement, get_single_sqlite_range_without_arguments) { ReadStatement<1> statement("SELECT number FROM test", database); database.execute("INSERT INTO test VALUES (NULL, NULL, NULL)"); @@ -912,7 +915,7 @@ TEST_F(SqliteStatement, GetSingleSqliteRangeWithoutArguments) ASSERT_THAT(values, UnorderedElementsAre(Eq("blah"), Eq(23.3), Eq(40), IsNull())); } -TEST_F(SqliteStatement, GetSingleSqliteRangeWithTransactionWithoutArguments) +TEST_F(SqliteStatement, get_single_sqlite_range_with_transaction_without_arguments) { ReadStatement<1> statement("SELECT number FROM test", database); database.execute("INSERT INTO test VALUES (NULL, NULL, NULL)"); @@ -924,7 +927,7 @@ TEST_F(SqliteStatement, GetSingleSqliteRangeWithTransactionWithoutArguments) database.lock(); } -TEST_F(SqliteStatement, GetStructValuesWithoutArguments) +TEST_F(SqliteStatement, get_struct_values_without_arguments) { ReadStatement<3> statement("SELECT name, number, value FROM test", database); @@ -936,7 +939,7 @@ TEST_F(SqliteStatement, GetStructValuesWithoutArguments) Output{"poo", "40", 3})); } -TEST_F(SqliteStatement, GetStructRangeWithoutArguments) +TEST_F(SqliteStatement, get_struct_range_without_arguments) { ReadStatement<3> statement("SELECT name, number, value FROM test", database); @@ -949,7 +952,7 @@ TEST_F(SqliteStatement, GetStructRangeWithoutArguments) Output{"poo", "40", 3})); } -TEST_F(SqliteStatement, GetStructRangeWithTransactionWithoutArguments) +TEST_F(SqliteStatement, get_struct_range_with_transaction_without_arguments) { ReadStatement<3> statement("SELECT name, number, value FROM test", database); database.unlock(); @@ -963,7 +966,7 @@ TEST_F(SqliteStatement, GetStructRangeWithTransactionWithoutArguments) database.lock(); } -TEST_F(SqliteStatement, GetValuesForSingleOutputWithBindingMultipleTimes) +TEST_F(SqliteStatement, get_values_for_single_output_with_binding_multiple_times) { ReadStatement<1, 1> statement("SELECT name FROM test WHERE number=?", database); statement.values(3, 40); @@ -973,7 +976,7 @@ TEST_F(SqliteStatement, GetValuesForSingleOutputWithBindingMultipleTimes) ASSERT_THAT(values, ElementsAre("poo")); } -TEST_F(SqliteStatement, GetRangeForSingleOutputWithBindingMultipleTimes) +TEST_F(SqliteStatement, get_range_for_single_output_with_binding_multiple_times) { ReadStatement<1, 1> statement("SELECT name FROM test WHERE number=?", database); statement.values(3, 40); @@ -984,7 +987,7 @@ TEST_F(SqliteStatement, GetRangeForSingleOutputWithBindingMultipleTimes) ASSERT_THAT(values, ElementsAre("poo")); } -TEST_F(SqliteStatement, GetRangeWithTransactionForSingleOutputWithBindingMultipleTimes) +TEST_F(SqliteStatement, get_range_with_transaction_for_single_output_with_binding_multiple_times) { ReadStatement<1, 1> statement("SELECT name FROM test WHERE number=?", database); statement.values(3, 40); @@ -997,7 +1000,7 @@ TEST_F(SqliteStatement, GetRangeWithTransactionForSingleOutputWithBindingMultipl database.lock(); } -TEST_F(SqliteStatement, GetValuesForMultipleOutputValuesAndMultipleQueryValue) +TEST_F(SqliteStatement, get_values_for_multiple_output_values_and_multiple_query_value) { using Tuple = std::tuple; ReadStatement<3, 3> statement( @@ -1008,7 +1011,7 @@ TEST_F(SqliteStatement, GetValuesForMultipleOutputValuesAndMultipleQueryValue) ASSERT_THAT(values, ElementsAre(Tuple{"bar", "blah", 1})); } -TEST_F(SqliteStatement, GetRangeForMultipleOutputValuesAndMultipleQueryValue) +TEST_F(SqliteStatement, get_range_for_multiple_output_values_and_multiple_query_value) { using Tuple = std::tuple; ReadStatement<3, 3> statement( @@ -1020,7 +1023,7 @@ TEST_F(SqliteStatement, GetRangeForMultipleOutputValuesAndMultipleQueryValue) ASSERT_THAT(values, ElementsAre(Tuple{"bar", "blah", 1})); } -TEST_F(SqliteStatement, GetRangeWithTransactionForMultipleOutputValuesAndMultipleQueryValue) +TEST_F(SqliteStatement, get_range_with_transaction_for_multiple_output_values_and_multiple_query_value) { using Tuple = std::tuple; ReadStatement<3, 3> statement( @@ -1033,7 +1036,7 @@ TEST_F(SqliteStatement, GetRangeWithTransactionForMultipleOutputValuesAndMultipl database.lock(); } -TEST_F(SqliteStatement, CallGetValuesForMultipleOutputValuesAndMultipleQueryValueMultipleTimes) +TEST_F(SqliteStatement, call_get_values_for_multiple_output_values_and_multiple_query_value_multiple_times) { using Tuple = std::tuple; ReadStatement<3, 2> statement("SELECT name, number, value FROM test WHERE name=? AND number=?", @@ -1045,7 +1048,7 @@ TEST_F(SqliteStatement, CallGetValuesForMultipleOutputValuesAndMultipleQueryValu ASSERT_THAT(values, ElementsAre(Tuple{"bar", "blah", 1})); } -TEST_F(SqliteStatement, CallGetRangeForMultipleOutputValuesAndMultipleQueryValueMultipleTimes) +TEST_F(SqliteStatement, call_get_range_for_multiple_output_values_and_multiple_query_value_multiple_times) { using Tuple = std::tuple; ReadStatement<3, 2> statement("SELECT name, number, value FROM test WHERE name=? AND number=?", @@ -1062,7 +1065,7 @@ TEST_F(SqliteStatement, CallGetRangeForMultipleOutputValuesAndMultipleQueryValue } TEST_F(SqliteStatement, - CallGetRangeWithTransactionForMultipleOutputValuesAndMultipleQueryValueMultipleTimes) + call_get_range_with_transaction_for_multiple_output_values_and_multiple_query_value_multiple_times) { using Tuple = std::tuple; ReadStatement<3, 2> statement("SELECT name, number, value FROM test WHERE name=? AND number=?", @@ -1076,7 +1079,7 @@ TEST_F(SqliteStatement, database.lock(); } -TEST_F(SqliteStatement, GetStructOutputValuesAndMultipleQueryValue) +TEST_F(SqliteStatement, get_struct_output_values_and_multiple_query_value) { ReadStatement<3, 3> statement( "SELECT name, number, value FROM test WHERE name=? AND number=? AND value=?", database); @@ -1086,7 +1089,7 @@ TEST_F(SqliteStatement, GetStructOutputValuesAndMultipleQueryValue) ASSERT_THAT(values, ElementsAre(Output{"bar", "blah", 1})); } -TEST_F(SqliteStatement, GetBlobValues) +TEST_F(SqliteStatement, get_blob_values) { database.execute("INSERT INTO test VALUES ('blob', 40, x'AABBCCDD')"); ReadStatement<1> statement("SELECT value FROM test WHERE name='blob'", database); @@ -1099,7 +1102,7 @@ TEST_F(SqliteStatement, GetBlobValues) ASSERT_THAT(values, ElementsAre(Field(&Sqlite::Blob::bytes, Eq(bytes)))); } -TEST_F(SqliteStatement, GetEmptyOptionalBlobValueForInteger) +TEST_F(SqliteStatement, get_empty_optional_blob_value_for_integer) { ReadStatement<1> statement("SELECT value FROM test WHERE name='poo'", database); @@ -1108,7 +1111,7 @@ TEST_F(SqliteStatement, GetEmptyOptionalBlobValueForInteger) ASSERT_THAT(value, Optional(Field(&Sqlite::Blob::bytes, IsEmpty()))); } -TEST_F(SqliteStatement, GetEmptyOptionalBlobValueForFloat) +TEST_F(SqliteStatement, get_empty_optional_blob_value_for_float) { ReadStatement<1> statement("SELECT number FROM test WHERE name='foo'", database); @@ -1117,7 +1120,7 @@ TEST_F(SqliteStatement, GetEmptyOptionalBlobValueForFloat) ASSERT_THAT(value, Optional(Field(&Sqlite::Blob::bytes, IsEmpty()))); } -TEST_F(SqliteStatement, GetEmptyOptionalBlobValueForText) +TEST_F(SqliteStatement, get_empty_optional_blob_value_for_text) { ReadStatement<1> statement("SELECT number FROM test WHERE name='bar'", database); @@ -1126,7 +1129,7 @@ TEST_F(SqliteStatement, GetEmptyOptionalBlobValueForText) ASSERT_THAT(value, Optional(Field(&Sqlite::Blob::bytes, IsEmpty()))); } -TEST_F(SqliteStatement, GetOptionalSingleValueAndMultipleQueryValue) +TEST_F(SqliteStatement, get_optional_single_value_and_multiple_query_value) { ReadStatement<1, 3> statement("SELECT name FROM test WHERE name=? AND number=? AND value=?", database); @@ -1136,7 +1139,7 @@ TEST_F(SqliteStatement, GetOptionalSingleValueAndMultipleQueryValue) ASSERT_THAT(value.value(), Eq("bar")); } -TEST_F(SqliteStatement, GetOptionalOutputValueAndMultipleQueryValue) +TEST_F(SqliteStatement, get_optional_output_value_and_multiple_query_value) { ReadStatement<3, 3> statement( "SELECT name, number, value FROM test WHERE name=? AND number=? AND value=?", database); @@ -1146,7 +1149,7 @@ TEST_F(SqliteStatement, GetOptionalOutputValueAndMultipleQueryValue) ASSERT_THAT(value.value(), Eq(Output{"bar", "blah", 1})); } -TEST_F(SqliteStatement, GetOptionalTupleValueAndMultipleQueryValue) +TEST_F(SqliteStatement, get_optional_tuple_value_and_multiple_query_value) { using Tuple = std::tuple; ReadStatement<3, 3> statement( @@ -1157,7 +1160,7 @@ TEST_F(SqliteStatement, GetOptionalTupleValueAndMultipleQueryValue) ASSERT_THAT(value.value(), Eq(Tuple{"bar", "blah", 1})); } -TEST_F(SqliteStatement, GetOptionalValueCallsReset) +TEST_F(SqliteStatement, get_optional_value_calls_reset) { MockSqliteStatement<1, 1> mockStatement{databaseMock}; @@ -1166,7 +1169,7 @@ TEST_F(SqliteStatement, GetOptionalValueCallsReset) mockStatement.optionalValue("bar"); } -TEST_F(SqliteStatement, GetOptionalValueCallsResetIfExceptionIsThrown) +TEST_F(SqliteStatement, get_optional_value_calls_reset_if_exception_is_thrown) { MockSqliteStatement<1, 1> mockStatement{databaseMock}; ON_CALL(mockStatement, next()).WillByDefault(Throw(Sqlite::StatementHasError(""))); @@ -1176,7 +1179,7 @@ TEST_F(SqliteStatement, GetOptionalValueCallsResetIfExceptionIsThrown) EXPECT_THROW(mockStatement.optionalValue("bar"), Sqlite::StatementHasError); } -TEST_F(SqliteStatement, GetSingleValueAndMultipleQueryValue) +TEST_F(SqliteStatement, get_single_value_and_multiple_query_value) { ReadStatement<1, 3> statement("SELECT name FROM test WHERE name=? AND number=? AND value=?", database); @@ -1186,7 +1189,7 @@ TEST_F(SqliteStatement, GetSingleValueAndMultipleQueryValue) ASSERT_THAT(value, Eq("bar")); } -TEST_F(SqliteStatement, GetOutputValueAndMultipleQueryValue) +TEST_F(SqliteStatement, get_output_value_and_multiple_query_value) { ReadStatement<3, 3> statement( "SELECT name, number, value FROM test WHERE name=? AND number=? AND value=?", database); @@ -1196,7 +1199,7 @@ TEST_F(SqliteStatement, GetOutputValueAndMultipleQueryValue) ASSERT_THAT(value, Eq(Output{"bar", "blah", 1})); } -TEST_F(SqliteStatement, GetTupleValueAndMultipleQueryValue) +TEST_F(SqliteStatement, get_tuple_value_and_multiple_query_value) { using Tuple = std::tuple; ReadStatement<3, 3> statement( @@ -1207,7 +1210,7 @@ TEST_F(SqliteStatement, GetTupleValueAndMultipleQueryValue) ASSERT_THAT(value, Eq(Tuple{"bar", "blah", 1})); } -TEST_F(SqliteStatement, GetSingleInvalidLongLongId) +TEST_F(SqliteStatement, get_single_invalid_long_long_id) { TestLongLongId id; WriteStatement<1>("INSERT INTO test VALUES ('id', 323, ?)", database).write(id); @@ -1218,7 +1221,7 @@ TEST_F(SqliteStatement, GetSingleInvalidLongLongId) ASSERT_FALSE(value.isValid()); } -TEST_F(SqliteStatement, GetSingleLongLongId) +TEST_F(SqliteStatement, get_single_long_long_id) { TestLongLongId id{TestLongLongId::create(42)}; WriteStatement<1>("INSERT INTO test VALUES ('id', 323, ?)", database).write(id); @@ -1229,7 +1232,7 @@ TEST_F(SqliteStatement, GetSingleLongLongId) ASSERT_THAT(value.internalId(), Eq(42)); } -TEST_F(SqliteStatement, GetSingleInvalidIntId) +TEST_F(SqliteStatement, get_single_invalid_int_id) { TestIntId id; WriteStatement<1>("INSERT INTO test VALUES ('id', 323, ?)", database).write(id); @@ -1240,7 +1243,7 @@ TEST_F(SqliteStatement, GetSingleInvalidIntId) ASSERT_FALSE(value.isValid()); } -TEST_F(SqliteStatement, GetSingleIntId) +TEST_F(SqliteStatement, get_single_int_id) { TestIntId id{TestIntId::create(42)}; WriteStatement<1>("INSERT INTO test VALUES ('id', 323, ?)", database).write(id); @@ -1251,7 +1254,7 @@ TEST_F(SqliteStatement, GetSingleIntId) ASSERT_THAT(value.internalId(), Eq(42)); } -TEST_F(SqliteStatement, GetValueCallsReset) +TEST_F(SqliteStatement, get_value_calls_reset) { struct Value { @@ -1269,7 +1272,7 @@ TEST_F(SqliteStatement, GetValueCallsReset) mockStatement.value("bar"); } -TEST_F(SqliteStatement, GetValueCallsResetIfExceptionIsThrown) +TEST_F(SqliteStatement, get_value_calls_reset_if_exception_is_thrown) { struct Value { @@ -1288,7 +1291,7 @@ TEST_F(SqliteStatement, GetValueCallsResetIfExceptionIsThrown) EXPECT_THROW(mockStatement.value("bar"), Sqlite::StatementHasError); } -TEST_F(SqliteStatement, GetValuesWithoutArgumentsCallsReset) +TEST_F(SqliteStatement, get_values_without_arguments_calls_reset) { MockSqliteStatement<1, 0> mockStatement{databaseMock}; @@ -1297,7 +1300,7 @@ TEST_F(SqliteStatement, GetValuesWithoutArgumentsCallsReset) mockStatement.values(3); } -TEST_F(SqliteStatement, GetRangeWithoutArgumentsCallsReset) +TEST_F(SqliteStatement, get_range_without_arguments_calls_reset) { MockSqliteStatement<1, 0> mockStatement{databaseMock}; @@ -1306,7 +1309,7 @@ TEST_F(SqliteStatement, GetRangeWithoutArgumentsCallsReset) mockStatement.range(); } -TEST_F(SqliteStatement, GetRangeWithTransactionWithoutArgumentsCalls) +TEST_F(SqliteStatement, get_range_with_transaction_without_arguments_calls) { InSequence s; MockSqliteStatement<1, 0> mockStatement{databaseMock}; @@ -1320,7 +1323,7 @@ TEST_F(SqliteStatement, GetRangeWithTransactionWithoutArgumentsCalls) mockStatement.rangeWithTransaction(); } -TEST_F(SqliteStatement, GetValuesWithoutArgumentsCallsResetIfExceptionIsThrown) +TEST_F(SqliteStatement, get_values_without_arguments_calls_reset_if_exception_is_thrown) { MockSqliteStatement<1, 0> mockStatement{databaseMock}; ON_CALL(mockStatement, next()).WillByDefault(Throw(Sqlite::StatementHasError(""))); @@ -1330,7 +1333,7 @@ TEST_F(SqliteStatement, GetValuesWithoutArgumentsCallsResetIfExceptionIsThrown) EXPECT_THROW(mockStatement.values(3), Sqlite::StatementHasError); } -TEST_F(SqliteStatement, GetRangeWithoutArgumentsCallsResetIfExceptionIsThrown) +TEST_F(SqliteStatement, get_range_without_arguments_calls_reset_if_exception_is_thrown) { MockSqliteStatement<1, 0> mockStatement{databaseMock}; ON_CALL(mockStatement, next()).WillByDefault(Throw(Sqlite::StatementHasError(""))); @@ -1341,7 +1344,7 @@ TEST_F(SqliteStatement, GetRangeWithoutArgumentsCallsResetIfExceptionIsThrown) EXPECT_THROW(range.begin(), Sqlite::StatementHasError); } -TEST_F(SqliteStatement, GetRangeWithTransactionWithoutArgumentsCallsResetIfExceptionIsThrown) +TEST_F(SqliteStatement, get_range_with_transaction_without_arguments_calls_reset_if_exception_is_thrown) { InSequence s; MockSqliteStatement<1, 0> mockStatement{databaseMock}; @@ -1361,7 +1364,7 @@ TEST_F(SqliteStatement, GetRangeWithTransactionWithoutArgumentsCallsResetIfExcep Sqlite::StatementHasError); } -TEST_F(SqliteStatement, GetValuesWithSimpleArgumentsCallsReset) +TEST_F(SqliteStatement, get_values_with_simple_arguments_calls_reset) { MockSqliteStatement<1, 2> mockStatement{databaseMock}; @@ -1370,7 +1373,7 @@ TEST_F(SqliteStatement, GetValuesWithSimpleArgumentsCallsReset) mockStatement.values(3, "foo", "bar"); } -TEST_F(SqliteStatement, GetValuesWithSimpleArgumentsCallsResetIfExceptionIsThrown) +TEST_F(SqliteStatement, get_values_with_simple_arguments_calls_reset_if_exception_is_thrown) { MockSqliteStatement<1, 2> mockStatement{databaseMock}; ON_CALL(mockStatement, next()).WillByDefault(Throw(Sqlite::StatementHasError(""))); @@ -1380,18 +1383,18 @@ TEST_F(SqliteStatement, GetValuesWithSimpleArgumentsCallsResetIfExceptionIsThrow EXPECT_THROW(mockStatement.values(3, "foo", "bar"), Sqlite::StatementHasError); } -TEST_F(SqliteStatement, ResetIfWriteIsThrowingException) +TEST_F(SqliteStatement, reset_if_write_is_throwing_exception) { MockSqliteStatement<1, 1> mockStatement{databaseMock}; EXPECT_CALL(mockStatement, bind(1, TypedEq("bar"))) - .WillOnce(Throw(Sqlite::StatementIsBusy(""))); + .WillOnce(Throw(Sqlite::StatementIsBusy(""))); EXPECT_CALL(mockStatement, reset()); ASSERT_ANY_THROW(mockStatement.write("bar")); } -TEST_F(SqliteStatement, ResetIfExecuteThrowsException) +TEST_F(SqliteStatement, reset_if_execute_throws_exception) { MockSqliteStatement<1, 0> mockStatement{databaseMock}; @@ -1401,37 +1404,37 @@ TEST_F(SqliteStatement, ResetIfExecuteThrowsException) ASSERT_ANY_THROW(mockStatement.execute()); } -TEST_F(SqliteStatement, ReadStatementThrowsWrongColumnCount) +TEST_F(SqliteStatement, read_statement_throws_wrong_column_count) { ASSERT_THROW(ReadStatement<1> statement("SELECT name, number FROM test", database), Sqlite::WrongColumnCount); } -TEST_F(SqliteStatement, ReadWriteStatementThrowsWrongColumnCount) +TEST_F(SqliteStatement, read_write_statement_throws_wrong_column_count) { ASSERT_THROW(ReadWriteStatement<1> statement("SELECT name, number FROM test", database), Sqlite::WrongColumnCount); } -TEST_F(SqliteStatement, WriteStatementThrowsWrongBindingParameterCount) +TEST_F(SqliteStatement, write_statement_throws_wrong_binding_parameter_count) { ASSERT_THROW(WriteStatement<1>("INSERT INTO test(name, number) VALUES(?1, ?2)", database), Sqlite::WrongBindingParameterCount); } -TEST_F(SqliteStatement, ReadWriteStatementThrowsWrongBindingParameterCount) +TEST_F(SqliteStatement, read_write_statement_throws_wrong_binding_parameter_count) { ASSERT_THROW((ReadWriteStatement<0, 1>("INSERT INTO test(name, number) VALUES(?1, ?2)", database)), Sqlite::WrongBindingParameterCount); } -TEST_F(SqliteStatement, ReadStatementThrowsWrongBindingParameterCount) +TEST_F(SqliteStatement, read_statement_throws_wrong_binding_parameter_count) { ASSERT_THROW((ReadStatement<2, 0>("SELECT name, number FROM test WHERE name=?", database)), Sqlite::WrongBindingParameterCount); } -TEST_F(SqliteStatement, ReadCallback) +TEST_F(SqliteStatement, read_callback) { MockFunction callbackMock; ReadStatement<2> statement("SELECT name, value FROM test", database); @@ -1443,7 +1446,19 @@ TEST_F(SqliteStatement, ReadCallback) statement.readCallback(callbackMock.AsStdFunction()); } -TEST_F(SqliteStatement, ReadCallbackCalledWithArguments) +TEST_F(SqliteStatement, read_callback_without_control) +{ + MockFunction callbackMock; + ReadStatement<2> statement("SELECT name, value FROM test", database); + + EXPECT_CALL(callbackMock, Call(Eq("bar"), Eq(1))); + EXPECT_CALL(callbackMock, Call(Eq("foo"), Eq(2))); + EXPECT_CALL(callbackMock, Call(Eq("poo"), Eq(3))); + + statement.readCallback(callbackMock.AsStdFunction()); +} + +TEST_F(SqliteStatement, read_callback_called_with_arguments) { MockFunction callbackMock; ReadStatement<2, 1> statement("SELECT name, value FROM test WHERE value=?", database); @@ -1453,7 +1468,7 @@ TEST_F(SqliteStatement, ReadCallbackCalledWithArguments) statement.readCallback(callbackMock.AsStdFunction(), 2); } -TEST_F(SqliteStatement, ReadCallbackAborts) +TEST_F(SqliteStatement, read_callback_aborts) { MockFunction callbackMock; ReadStatement<2> statement("SELECT name, value FROM test ORDER BY name", database); @@ -1465,7 +1480,7 @@ TEST_F(SqliteStatement, ReadCallbackAborts) statement.readCallback(callbackMock.AsStdFunction()); } -TEST_F(SqliteStatement, ReadCallbackCallsResetAfterCallbacks) +TEST_F(SqliteStatement, read_callback_calls_reset_after_callbacks) { MockFunction callbackMock; MockSqliteStatement<2> mockStatement{databaseMock}; @@ -1475,7 +1490,7 @@ TEST_F(SqliteStatement, ReadCallbackCallsResetAfterCallbacks) mockStatement.readCallback(callbackMock.AsStdFunction()); } -TEST_F(SqliteStatement, ReadCallbackCallsResetAfterCallbacksAborts) +TEST_F(SqliteStatement, read_callback_calls_reset_after_callbacks_aborts) { MockFunction callbackMock; MockSqliteStatement<2> mockStatement{databaseMock}; @@ -1486,7 +1501,7 @@ TEST_F(SqliteStatement, ReadCallbackCallsResetAfterCallbacksAborts) mockStatement.readCallback(callbackMock.AsStdFunction()); } -TEST_F(SqliteStatement, ReadCallbackThrowsForError) +TEST_F(SqliteStatement, read_callback_throws_for_error) { MockFunction callbackMock; MockSqliteStatement<2> mockStatement{databaseMock}; @@ -1495,7 +1510,7 @@ TEST_F(SqliteStatement, ReadCallbackThrowsForError) ASSERT_THROW(mockStatement.readCallback(callbackMock.AsStdFunction()), Sqlite::StatementHasError); } -TEST_F(SqliteStatement, ReadCallbackCallsResetIfExceptionIsThrown) +TEST_F(SqliteStatement, read_callback_calls_reset_if_exception_is_thrown) { MockFunction callbackMock; MockSqliteStatement<2> mockStatement{databaseMock}; @@ -1506,7 +1521,7 @@ TEST_F(SqliteStatement, ReadCallbackCallsResetIfExceptionIsThrown) EXPECT_THROW(mockStatement.readCallback(callbackMock.AsStdFunction()), Sqlite::StatementHasError); } -TEST_F(SqliteStatement, ReadToContainer) +TEST_F(SqliteStatement, read_to_container) { std::deque values; ReadStatement<1> statement("SELECT number FROM test", database); @@ -1516,7 +1531,7 @@ TEST_F(SqliteStatement, ReadToContainer) ASSERT_THAT(values, UnorderedElementsAre(Eq("blah"), Eq(23.3), Eq(40))); } -TEST_F(SqliteStatement, ReadToContainerCallCallbackWithArguments) +TEST_F(SqliteStatement, read_to_container_call_callback_with_arguments) { std::deque values; ReadStatement<1, 1> statement("SELECT number FROM test WHERE value=?", database); @@ -1526,7 +1541,7 @@ TEST_F(SqliteStatement, ReadToContainerCallCallbackWithArguments) ASSERT_THAT(values, ElementsAre(Eq(23.3))); } -TEST_F(SqliteStatement, ReadToCallsResetAfterPushingAllValuesBack) +TEST_F(SqliteStatement, read_to_calls_reset_after_pushing_all_values_back) { std::deque values; MockSqliteStatement mockStatement{databaseMock}; @@ -1536,7 +1551,7 @@ TEST_F(SqliteStatement, ReadToCallsResetAfterPushingAllValuesBack) mockStatement.readTo(values); } -TEST_F(SqliteStatement, ReadToThrowsForError) +TEST_F(SqliteStatement, read_to_throws_for_error) { std::deque values; MockSqliteStatement mockStatement{databaseMock}; @@ -1545,7 +1560,7 @@ TEST_F(SqliteStatement, ReadToThrowsForError) ASSERT_THROW(mockStatement.readTo(values), Sqlite::StatementHasError); } -TEST_F(SqliteStatement, ReadToCallsResetIfExceptionIsThrown) +TEST_F(SqliteStatement, read_to_calls_reset_if_exception_is_thrown) { std::deque values; MockSqliteStatement mockStatement{databaseMock}; @@ -1556,7 +1571,7 @@ TEST_F(SqliteStatement, ReadToCallsResetIfExceptionIsThrown) EXPECT_THROW(mockStatement.readTo(values), Sqlite::StatementHasError); } -TEST_F(SqliteStatement, ReadStatementValuesWithTransactions) +TEST_F(SqliteStatement, read_statement_values_with_transactions) { using Tuple = std::tuple; ReadStatement<3, 2> statement("SELECT name, number, value FROM test WHERE name=? AND number=?", @@ -1569,7 +1584,7 @@ TEST_F(SqliteStatement, ReadStatementValuesWithTransactions) database.lock(); } -TEST_F(SqliteStatement, ReadStatementValueWithTransactions) +TEST_F(SqliteStatement, read_statement_value_with_transactions) { using Tuple = std::tuple; ReadStatement<3, 2> statement("SELECT name, number, value FROM test WHERE name=? AND number=?", @@ -1582,7 +1597,7 @@ TEST_F(SqliteStatement, ReadStatementValueWithTransactions) database.lock(); } -TEST_F(SqliteStatement, ReadStatementOptionalValueWithTransactions) +TEST_F(SqliteStatement, read_statement_optional_value_with_transactions) { using Tuple = std::tuple; ReadStatement<3, 2> statement("SELECT name, number, value FROM test WHERE name=? AND number=?", @@ -1595,7 +1610,7 @@ TEST_F(SqliteStatement, ReadStatementOptionalValueWithTransactions) database.lock(); } -TEST_F(SqliteStatement, ReadStatementReadCallbackWithTransactions) +TEST_F(SqliteStatement, read_statement_read_callback_with_transactions) { MockFunction callbackMock; ReadStatement<3, 2> statement("SELECT name, number, value FROM test WHERE name=? AND number=?", @@ -1608,7 +1623,7 @@ TEST_F(SqliteStatement, ReadStatementReadCallbackWithTransactions) database.lock(); } -TEST_F(SqliteStatement, ReadStatementReadToWithTransactions) +TEST_F(SqliteStatement, read_statement_read_to_with_transactions) { using Tuple = std::tuple; ReadStatement<3, 2> statement("SELECT name, number, value FROM test WHERE name=? AND number=?", @@ -1622,7 +1637,7 @@ TEST_F(SqliteStatement, ReadStatementReadToWithTransactions) database.lock(); } -TEST_F(SqliteStatement, ReadWriteStatementValuesWithTransactions) +TEST_F(SqliteStatement, read_write_statement_values_with_transactions) { using Tuple = std::tuple; ReadWriteStatement<3, 2> statement( @@ -1635,7 +1650,7 @@ TEST_F(SqliteStatement, ReadWriteStatementValuesWithTransactions) database.lock(); } -TEST_F(SqliteStatement, ReadWriteStatementValueWithTransactions) +TEST_F(SqliteStatement, read_write_statement_value_with_transactions) { using Tuple = std::tuple; ReadWriteStatement<3, 2> statement( @@ -1648,7 +1663,7 @@ TEST_F(SqliteStatement, ReadWriteStatementValueWithTransactions) database.lock(); } -TEST_F(SqliteStatement, ReadWriteStatementOptionalValueWithTransactions) +TEST_F(SqliteStatement, read_write_statement_optional_value_with_transactions) { using Tuple = std::tuple; ReadWriteStatement<3, 2> statement( @@ -1661,7 +1676,7 @@ TEST_F(SqliteStatement, ReadWriteStatementOptionalValueWithTransactions) database.lock(); } -TEST_F(SqliteStatement, ReadWriteStatementReadCallbackWithTransactions) +TEST_F(SqliteStatement, read_write_statement_read_callback_with_transactions) { MockFunction callbackMock; ReadWriteStatement<3, 2> statement( @@ -1674,7 +1689,7 @@ TEST_F(SqliteStatement, ReadWriteStatementReadCallbackWithTransactions) database.lock(); } -TEST_F(SqliteStatement, ReadWriteStatementReadToWithTransactions) +TEST_F(SqliteStatement, read_write_statement_read_to_with_transactions) { using Tuple = std::tuple; ReadWriteStatement<3, 2> statement( diff --git a/tests/unit/unittest/sqlitetable-test.cpp b/tests/unit/tests/unittests/sqlite/sqlitetable-test.cpp similarity index 91% rename from tests/unit/unittest/sqlitetable-test.cpp rename to tests/unit/tests/unittests/sqlite/sqlitetable-test.cpp index 0560937997d..7b8189b51e4 100644 --- a/tests/unit/unittest/sqlitetable-test.cpp +++ b/tests/unit/tests/unittests/sqlite/sqlitetable-test.cpp @@ -1,11 +1,12 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" -#include "spydummy.h" +#include "../utils/googletest.h" +#include "../utils/spydummy.h" + +#include "../../mocks/sqlitedatabasemock.h" #include -#include #include namespace { @@ -30,29 +31,28 @@ protected: Utils::SmallString tableName = "testTable"; }; - -TEST_F(SqliteTable, ColumnIsAddedToTable) +TEST_F(SqliteTable, column_is_added_to_table) { table.setUseWithoutRowId(true); ASSERT_TRUE(table.useWithoutRowId()); } -TEST_F(SqliteTable, SetTableName) +TEST_F(SqliteTable, set_table_name) { table.setName(tableName.clone()); ASSERT_THAT(table.name(), tableName); } -TEST_F(SqliteTable, SetUseWithoutRowid) +TEST_F(SqliteTable, set_use_without_rowid) { table.setUseWithoutRowId(true); ASSERT_TRUE(table.useWithoutRowId()); } -TEST_F(SqliteTable, AddIndex) +TEST_F(SqliteTable, add_index) { table.setName(tableName.clone()); auto &column = table.addColumn("name"); @@ -60,11 +60,12 @@ TEST_F(SqliteTable, AddIndex) auto index = table.addIndex({column, column2}); - ASSERT_THAT(Utils::SmallStringView(index.sqlStatement()), - Eq("CREATE INDEX IF NOT EXISTS index_testTable_name_value ON testTable(name, value)")); + ASSERT_THAT( + Utils::SmallStringView(index.sqlStatement()), + Eq("CREATE INDEX IF NOT EXISTS index_testTable_name_value ON testTable(name, value)")); } -TEST_F(SqliteTable, InitializeTable) +TEST_F(SqliteTable, initialize_table) { table.setName(tableName.clone()); table.setUseIfNotExists(true); @@ -80,7 +81,7 @@ TEST_F(SqliteTable, InitializeTable) table.initialize(databaseMock); } -TEST_F(SqliteTable, InitializeTableWithIndex) +TEST_F(SqliteTable, initialize_table_with_index) { InSequence sequence; table.setName(tableName.clone()); @@ -90,7 +91,8 @@ TEST_F(SqliteTable, InitializeTableWithIndex) table.addIndex({column2}, "value IS NOT NULL"); EXPECT_CALL(databaseMock, execute(Eq("CREATE TABLE testTable(name, value)"))); - EXPECT_CALL(databaseMock, execute(Eq("CREATE INDEX IF NOT EXISTS index_testTable_name ON testTable(name)"))); + EXPECT_CALL(databaseMock, + execute(Eq("CREATE INDEX IF NOT EXISTS index_testTable_name ON testTable(name)"))); EXPECT_CALL(databaseMock, execute(Eq("CREATE INDEX IF NOT EXISTS index_testTable_value ON testTable(value) " "WHERE value IS NOT NULL"))); @@ -98,7 +100,7 @@ TEST_F(SqliteTable, InitializeTableWithIndex) table.initialize(databaseMock); } -TEST_F(SqliteTable, InitializeTableWithUniqueIndex) +TEST_F(SqliteTable, initialize_table_with_unique_index) { InSequence sequence; table.setName(tableName.clone()); @@ -119,7 +121,7 @@ TEST_F(SqliteTable, InitializeTableWithUniqueIndex) table.initialize(databaseMock); } -TEST_F(SqliteTable, AddForeignKeyColumnWithTableCalls) +TEST_F(SqliteTable, add_foreign_key_column_with_table_calls) { Sqlite::Table foreignTable; foreignTable.setName("foreignTable"); @@ -137,7 +139,7 @@ TEST_F(SqliteTable, AddForeignKeyColumnWithTableCalls) table.initialize(databaseMock); } -TEST_F(SqliteTable, AddForeignKeyColumnWithColumnCalls) +TEST_F(SqliteTable, add_foreign_key_column_with_column_calls) { Sqlite::Table foreignTable; foreignTable.setName("foreignTable"); @@ -158,7 +160,7 @@ TEST_F(SqliteTable, AddForeignKeyColumnWithColumnCalls) table.initialize(databaseMock); } -TEST_F(SqliteTable, AddColumn) +TEST_F(SqliteTable, add_column) { table.setName(tableName); @@ -172,7 +174,7 @@ TEST_F(SqliteTable, AddColumn) ElementsAre(VariantWith(Eq(Sqlite::Unique{})))))); } -TEST_F(SqliteTable, AddForeignKeyColumnWithTable) +TEST_F(SqliteTable, add_foreign_key_column_with_table) { Sqlite::Table foreignTable; foreignTable.setName("foreignTable"); @@ -198,7 +200,7 @@ TEST_F(SqliteTable, AddForeignKeyColumnWithTable) Field(&ForeignKey::enforcement, Enforment::Deferred))))))); } -TEST_F(SqliteTable, AddForeignKeyColumnWithColumn) +TEST_F(SqliteTable, add_foreign_key_column_with_column) { Sqlite::Table foreignTable; foreignTable.setName("foreignTable"); @@ -224,7 +226,7 @@ TEST_F(SqliteTable, AddForeignKeyColumnWithColumn) Field(&ForeignKey::enforcement, Enforment::Deferred))))))); } -TEST_F(SqliteTable, AddForeignKeyWhichIsNotUniqueThrowsAnExceptions) +TEST_F(SqliteTable, add_foreign_key_which_is_not_unique_throws_an_exceptions) { Sqlite::Table foreignTable; foreignTable.setName("foreignTable"); @@ -239,7 +241,7 @@ TEST_F(SqliteTable, AddForeignKeyWhichIsNotUniqueThrowsAnExceptions) Sqlite::ForeignKeyColumnIsNotUnique); } -TEST_F(SqliteTable, AddForeignKeyColumnWithTableAndNotNull) +TEST_F(SqliteTable, add_foreign_key_column_with_table_and_not_null) { Sqlite::Table foreignTable; foreignTable.setName("foreignTable"); @@ -268,7 +270,7 @@ TEST_F(SqliteTable, AddForeignKeyColumnWithTableAndNotNull) VariantWith(Eq(Sqlite::NotNull{})))))); } -TEST_F(SqliteTable, AddForeignKeyColumnWithColumnAndNotNull) +TEST_F(SqliteTable, add_foreign_key_column_with_column_and_not_null) { Sqlite::Table foreignTable; foreignTable.setName("foreignTable"); @@ -297,7 +299,7 @@ TEST_F(SqliteTable, AddForeignKeyColumnWithColumnAndNotNull) VariantWith(Eq(Sqlite::NotNull{})))))); } -TEST_F(SqliteTable, AddPrimaryTableContraint) +TEST_F(SqliteTable, add_primary_table_contraint) { table.setName(tableName.clone()); const auto &idColumn = table.addColumn("id"); @@ -319,28 +321,28 @@ protected: Utils::SmallString tableName = "testTable"; }; -TEST_F(StrictSqliteTable, ColumnIsAddedToTable) +TEST_F(StrictSqliteTable, column_is_added_to_table) { table.setUseWithoutRowId(true); ASSERT_TRUE(table.useWithoutRowId()); } -TEST_F(StrictSqliteTable, SetTableName) +TEST_F(StrictSqliteTable, set_table_name) { table.setName(tableName.clone()); ASSERT_THAT(table.name(), tableName); } -TEST_F(StrictSqliteTable, SetUseWithoutRowid) +TEST_F(StrictSqliteTable, set_use_without_rowid) { table.setUseWithoutRowId(true); ASSERT_TRUE(table.useWithoutRowId()); } -TEST_F(StrictSqliteTable, AddIndex) +TEST_F(StrictSqliteTable, add_index) { table.setName(tableName.clone()); auto &column = table.addColumn("name"); @@ -353,7 +355,7 @@ TEST_F(StrictSqliteTable, AddIndex) "value)")); } -TEST_F(StrictSqliteTable, InitializeTable) +TEST_F(StrictSqliteTable, initialize_table) { table.setName(tableName.clone()); table.setUseIfNotExists(true); @@ -369,7 +371,7 @@ TEST_F(StrictSqliteTable, InitializeTable) table.initialize(databaseMock); } -TEST_F(StrictSqliteTable, InitializeTableWithIndex) +TEST_F(StrictSqliteTable, initialize_table_with_index) { InSequence sequence; table.setName(tableName.clone()); @@ -388,7 +390,7 @@ TEST_F(StrictSqliteTable, InitializeTableWithIndex) table.initialize(databaseMock); } -TEST_F(StrictSqliteTable, InitializeTableWithUniqueIndex) +TEST_F(StrictSqliteTable, initialize_table_with_unique_index) { InSequence sequence; table.setName(tableName.clone()); @@ -409,7 +411,7 @@ TEST_F(StrictSqliteTable, InitializeTableWithUniqueIndex) table.initialize(databaseMock); } -TEST_F(StrictSqliteTable, AddForeignKeyColumnWithTableCalls) +TEST_F(StrictSqliteTable, add_foreign_key_column_with_table_calls) { Sqlite::StrictTable foreignTable; foreignTable.setName("foreignTable"); @@ -427,7 +429,7 @@ TEST_F(StrictSqliteTable, AddForeignKeyColumnWithTableCalls) table.initialize(databaseMock); } -TEST_F(StrictSqliteTable, AddForeignKeyColumnWithColumnCalls) +TEST_F(StrictSqliteTable, add_foreign_key_column_with_column_calls) { Sqlite::StrictTable foreignTable; foreignTable.setName("foreignTable"); @@ -450,7 +452,7 @@ TEST_F(StrictSqliteTable, AddForeignKeyColumnWithColumnCalls) table.initialize(databaseMock); } -TEST_F(StrictSqliteTable, AddColumn) +TEST_F(StrictSqliteTable, add_column) { table.setName(tableName); @@ -464,7 +466,7 @@ TEST_F(StrictSqliteTable, AddColumn) ElementsAre(VariantWith(Eq(Sqlite::Unique{})))))); } -TEST_F(StrictSqliteTable, AddForeignKeyColumnWithTable) +TEST_F(StrictSqliteTable, add_foreign_key_column_with_table) { Sqlite::StrictTable foreignTable; foreignTable.setName("foreignTable"); @@ -490,7 +492,7 @@ TEST_F(StrictSqliteTable, AddForeignKeyColumnWithTable) Field(&ForeignKey::enforcement, Enforment::Deferred))))))); } -TEST_F(StrictSqliteTable, AddForeignKeyColumnWithColumn) +TEST_F(StrictSqliteTable, add_foreign_key_column_with_column) { Sqlite::StrictTable foreignTable; foreignTable.setName("foreignTable"); @@ -518,7 +520,7 @@ TEST_F(StrictSqliteTable, AddForeignKeyColumnWithColumn) Field(&ForeignKey::enforcement, Enforment::Deferred))))))); } -TEST_F(StrictSqliteTable, AddForeignKeyWhichIsNotUniqueThrowsAnExceptions) +TEST_F(StrictSqliteTable, add_foreign_key_which_is_not_unique_throws_an_exceptions) { Sqlite::StrictTable foreignTable; foreignTable.setName("foreignTable"); @@ -533,7 +535,7 @@ TEST_F(StrictSqliteTable, AddForeignKeyWhichIsNotUniqueThrowsAnExceptions) Sqlite::ForeignKeyColumnIsNotUnique); } -TEST_F(StrictSqliteTable, AddForeignKeyColumnWithTableAndNotNull) +TEST_F(StrictSqliteTable, add_foreign_key_column_with_table_and_not_null) { Sqlite::StrictTable foreignTable; foreignTable.setName("foreignTable"); @@ -562,7 +564,7 @@ TEST_F(StrictSqliteTable, AddForeignKeyColumnWithTableAndNotNull) VariantWith(Eq(Sqlite::NotNull{})))))); } -TEST_F(StrictSqliteTable, AddForeignKeyColumnWithColumnAndNotNull) +TEST_F(StrictSqliteTable, add_foreign_key_column_with_column_and_not_null) { Sqlite::StrictTable foreignTable; foreignTable.setName("foreignTable"); @@ -593,7 +595,7 @@ TEST_F(StrictSqliteTable, AddForeignKeyColumnWithColumnAndNotNull) VariantWith(Eq(Sqlite::NotNull{})))))); } -TEST_F(StrictSqliteTable, AddPrimaryTableContraint) +TEST_F(StrictSqliteTable, add_primary_table_contraint) { table.setName(tableName.clone()); const auto &idColumn = table.addColumn("id"); diff --git a/tests/unit/unittest/sqliteteststatement.h b/tests/unit/tests/unittests/sqlite/sqliteteststatement.h similarity index 100% rename from tests/unit/unittest/sqliteteststatement.h rename to tests/unit/tests/unittests/sqlite/sqliteteststatement.h diff --git a/tests/unit/unittest/sqlitetransaction-test.cpp b/tests/unit/tests/unittests/sqlite/sqlitetransaction-test.cpp similarity index 79% rename from tests/unit/unittest/sqlitetransaction-test.cpp rename to tests/unit/tests/unittests/sqlite/sqlitetransaction-test.cpp index ca52dd0ae11..ac98a258c96 100644 --- a/tests/unit/unittest/sqlitetransaction-test.cpp +++ b/tests/unit/tests/unittests/sqlite/sqlitetransaction-test.cpp @@ -1,11 +1,11 @@ // Copyright (C) 2017 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" -#include "mocksqlitetransactionbackend.h" +#include "../mocks/mocksqlitetransactionbackend.h" +#include "../mocks/sqlitedatabasemock.h" -#include #include #include @@ -30,7 +30,7 @@ protected: NiceMock> callableWithReturnMock; }; -TEST_F(SqliteTransaction, DeferredTransactionCommit) +TEST_F(SqliteTransaction, deferred_transaction_commit) { InSequence s; @@ -43,7 +43,7 @@ TEST_F(SqliteTransaction, DeferredTransactionCommit) transaction.commit(); } -TEST_F(SqliteTransaction, DeferredTransactionRollBack) +TEST_F(SqliteTransaction, deferred_transaction_roll_back) { InSequence s; @@ -55,7 +55,7 @@ TEST_F(SqliteTransaction, DeferredTransactionRollBack) DeferredTransaction transaction{mockTransactionBackend}; } -TEST_F(SqliteTransaction, ImmediateTransactionCommit) +TEST_F(SqliteTransaction, immediate_transaction_commit) { InSequence s; @@ -68,7 +68,7 @@ TEST_F(SqliteTransaction, ImmediateTransactionCommit) transaction.commit(); } -TEST_F(SqliteTransaction, ImmediateTransactionRollBack) +TEST_F(SqliteTransaction, immediate_transaction_roll_back) { InSequence s; @@ -80,7 +80,7 @@ TEST_F(SqliteTransaction, ImmediateTransactionRollBack) ImmediateTransaction transaction{mockTransactionBackend}; } -TEST_F(SqliteTransaction, ExclusiveTransactionCommit) +TEST_F(SqliteTransaction, exclusive_transaction_commit) { InSequence s; @@ -93,7 +93,7 @@ TEST_F(SqliteTransaction, ExclusiveTransactionCommit) transaction.commit(); } -TEST_F(SqliteTransaction, ExclusiveTransactionRollBack) +TEST_F(SqliteTransaction, exclusive_transaction_roll_back) { InSequence s; @@ -105,7 +105,7 @@ TEST_F(SqliteTransaction, ExclusiveTransactionRollBack) ExclusiveTransaction transaction{mockTransactionBackend}; } -TEST_F(SqliteTransaction, DeferredNonThrowingDestructorTransactionCommit) +TEST_F(SqliteTransaction, deferred_non_throwing_destructor_transaction_commit) { InSequence s; @@ -118,7 +118,7 @@ TEST_F(SqliteTransaction, DeferredNonThrowingDestructorTransactionCommit) transaction.commit(); } -TEST_F(SqliteTransaction, DeferredNonThrowingDestructorTransactionCommitCallsInterface) +TEST_F(SqliteTransaction, deferred_non_throwing_destructor_transaction_commit_calls_interface) { InSequence s; @@ -131,7 +131,7 @@ TEST_F(SqliteTransaction, DeferredNonThrowingDestructorTransactionCommitCallsInt transaction.commit(); } -TEST_F(SqliteTransaction, DeferredNonThrowingDestructorTransactionRollBack) +TEST_F(SqliteTransaction, deferred_non_throwing_destructor_transaction_roll_back) { InSequence s; @@ -143,7 +143,7 @@ TEST_F(SqliteTransaction, DeferredNonThrowingDestructorTransactionRollBack) DeferredNonThrowingDestructorTransaction transaction{mockTransactionBackend}; } -TEST_F(SqliteTransaction, ImmediateNonThrowingDestructorTransactionCommit) +TEST_F(SqliteTransaction, immediate_non_throwing_destructor_transaction_commit) { InSequence s; @@ -156,7 +156,7 @@ TEST_F(SqliteTransaction, ImmediateNonThrowingDestructorTransactionCommit) transaction.commit(); } -TEST_F(SqliteTransaction, ImmediateNonThrowingDestructorTransactionRollBack) +TEST_F(SqliteTransaction, immediate_non_throwing_destructor_transaction_roll_back) { InSequence s; @@ -168,7 +168,7 @@ TEST_F(SqliteTransaction, ImmediateNonThrowingDestructorTransactionRollBack) ImmediateNonThrowingDestructorTransaction transaction{mockTransactionBackend}; } -TEST_F(SqliteTransaction, ExclusiveNonThrowingDestructorTransactionCommit) +TEST_F(SqliteTransaction, exclusive_non_throwing_destructor_transaction_commit) { InSequence s; @@ -181,7 +181,7 @@ TEST_F(SqliteTransaction, ExclusiveNonThrowingDestructorTransactionCommit) transaction.commit(); } -TEST_F(SqliteTransaction, ExclusiveTNonThrowingDestructorransactionRollBack) +TEST_F(SqliteTransaction, exclusive_t_non_throwing_destructorransaction_roll_back) { InSequence s; @@ -193,31 +193,28 @@ TEST_F(SqliteTransaction, ExclusiveTNonThrowingDestructorransactionRollBack) ExclusiveNonThrowingDestructorTransaction transaction{mockTransactionBackend}; } -TEST_F(SqliteTransaction, DeferredTransactionBeginThrows) +TEST_F(SqliteTransaction, deferred_transaction_begin_throws) { ON_CALL(mockTransactionBackend, deferredBegin()).WillByDefault(Throw(Sqlite::Exception())); - ASSERT_THROW(DeferredTransaction{mockTransactionBackend}, - Sqlite::Exception); + ASSERT_THROW(DeferredTransaction{mockTransactionBackend}, Sqlite::Exception); } -TEST_F(SqliteTransaction, ImmediateTransactionBeginThrows) +TEST_F(SqliteTransaction, immediate_transaction_begin_throws) { ON_CALL(mockTransactionBackend, immediateBegin()).WillByDefault(Throw(Sqlite::Exception())); - ASSERT_THROW(ImmediateTransaction{mockTransactionBackend}, - Sqlite::Exception); + ASSERT_THROW(ImmediateTransaction{mockTransactionBackend}, Sqlite::Exception); } -TEST_F(SqliteTransaction, ExclusiveTransactionBeginThrows) +TEST_F(SqliteTransaction, exclusive_transaction_begin_throws) { ON_CALL(mockTransactionBackend, exclusiveBegin()).WillByDefault(Throw(Sqlite::Exception())); - ASSERT_THROW(ExclusiveTransaction{mockTransactionBackend}, - Sqlite::Exception); + ASSERT_THROW(ExclusiveTransaction{mockTransactionBackend}, Sqlite::Exception); } -TEST_F(SqliteTransaction, DeferredTransactionBeginThrowsAndNotRollback) +TEST_F(SqliteTransaction, deferred_transaction_begin_throws_and_not_rollback) { InSequence s; @@ -229,7 +226,7 @@ TEST_F(SqliteTransaction, DeferredTransactionBeginThrowsAndNotRollback) ASSERT_ANY_THROW(DeferredTransaction{mockTransactionBackend}); } -TEST_F(SqliteTransaction, ImmediateTransactionBeginThrowsAndNotRollback) +TEST_F(SqliteTransaction, immediate_transaction_begin_throws_and_not_rollback) { InSequence s; @@ -238,11 +235,10 @@ TEST_F(SqliteTransaction, ImmediateTransactionBeginThrowsAndNotRollback) EXPECT_CALL(mockTransactionBackend, rollback()).Times(0); EXPECT_CALL(mockTransactionBackend, unlock()); - ASSERT_ANY_THROW(ImmediateTransaction{mockTransactionBackend}); } -TEST_F(SqliteTransaction, ExclusiveTransactionBeginThrowsAndNotRollback) +TEST_F(SqliteTransaction, exclusive_transaction_begin_throws_and_not_rollback) { InSequence s; @@ -254,31 +250,29 @@ TEST_F(SqliteTransaction, ExclusiveTransactionBeginThrowsAndNotRollback) ASSERT_ANY_THROW(ExclusiveTransaction{mockTransactionBackend}); } -TEST_F(SqliteTransaction, TransactionCommitThrows) +TEST_F(SqliteTransaction, transaction_commit_throws) { ON_CALL(mockTransactionBackend, commit()).WillByDefault(Throw(Sqlite::Exception())); ImmediateTransaction transaction{mockTransactionBackend}; - ASSERT_THROW(transaction.commit(), - Sqlite::Exception); + ASSERT_THROW(transaction.commit(), Sqlite::Exception); } -TEST_F(SqliteTransaction, TransactionRollbackInDestructorThrows) +TEST_F(SqliteTransaction, transaction_rollback_in_destructor_throws) { ON_CALL(mockTransactionBackend, rollback()).WillByDefault(Throw(Sqlite::Exception())); - ASSERT_THROW(ExclusiveTransaction{mockTransactionBackend}, - Sqlite::Exception); + ASSERT_THROW(ExclusiveTransaction{mockTransactionBackend}, Sqlite::Exception); } -TEST_F(SqliteTransaction, TransactionRollbackInDestructorDontThrows) +TEST_F(SqliteTransaction, transaction_rollback_in_destructor_dont_throws) { ON_CALL(mockTransactionBackend, rollback()).WillByDefault(Throw(Sqlite::Exception())); ASSERT_NO_THROW(ExclusiveNonThrowingDestructorTransaction{mockTransactionBackend}); } -TEST_F(SqliteTransaction, ImmediateSessionTransactionCommit) +TEST_F(SqliteTransaction, immediate_session_transaction_commit) { InSequence s; @@ -291,7 +285,7 @@ TEST_F(SqliteTransaction, ImmediateSessionTransactionCommit) transaction.commit(); } -TEST_F(SqliteTransaction, ImmediateSessionTransactionRollBack) +TEST_F(SqliteTransaction, immediate_session_transaction_roll_back) { InSequence s; @@ -303,21 +297,21 @@ TEST_F(SqliteTransaction, ImmediateSessionTransactionRollBack) ImmediateSessionTransaction transaction{mockTransactionBackend}; } -TEST_F(SqliteTransaction, SessionTransactionRollbackInDestructorThrows) +TEST_F(SqliteTransaction, session_transaction_rollback_in_destructor_throws) { ON_CALL(mockTransactionBackend, sessionRollback()).WillByDefault(Throw(Sqlite::Exception())); ASSERT_THROW(ImmediateSessionTransaction{mockTransactionBackend}, Sqlite::Exception); } -TEST_F(SqliteTransaction, ImmidiateSessionTransactionBeginThrows) +TEST_F(SqliteTransaction, immidiate_session_transaction_begin_throws) { ON_CALL(mockTransactionBackend, immediateSessionBegin()).WillByDefault(Throw(Sqlite::Exception())); ASSERT_THROW(ImmediateSessionTransaction{mockTransactionBackend}, Sqlite::Exception); } -TEST_F(SqliteTransaction, ImmediateSessionTransactionBeginThrowsAndNotRollback) +TEST_F(SqliteTransaction, immediate_session_transaction_begin_throws_and_not_rollback) { InSequence s; @@ -329,7 +323,7 @@ TEST_F(SqliteTransaction, ImmediateSessionTransactionBeginThrowsAndNotRollback) ASSERT_ANY_THROW(ImmediateSessionTransaction{mockTransactionBackend}); } -TEST_F(SqliteTransaction, WithDeferredTransactionNoReturnCommit) +TEST_F(SqliteTransaction, with_deferred_transaction_no_return_commit) { InSequence s; @@ -342,7 +336,7 @@ TEST_F(SqliteTransaction, WithDeferredTransactionNoReturnCommit) Sqlite::withDeferredTransaction(mockTransactionBackend, callableMock.AsStdFunction()); } -TEST_F(SqliteTransaction, WithDeferredTransactionWithReturnCommit) +TEST_F(SqliteTransaction, with_deferred_transaction_with_return_commit) { InSequence s; @@ -355,7 +349,7 @@ TEST_F(SqliteTransaction, WithDeferredTransactionWithReturnCommit) Sqlite::withDeferredTransaction(mockTransactionBackend, callableWithReturnMock.AsStdFunction()); } -TEST_F(SqliteTransaction, WithDeferredTransactionReturnsValue) +TEST_F(SqliteTransaction, with_deferred_transaction_returns_value) { auto callable = callableWithReturnMock.AsStdFunction(); @@ -365,7 +359,7 @@ TEST_F(SqliteTransaction, WithDeferredTransactionReturnsValue) ASSERT_THAT(value, Eq(212)); } -TEST_F(SqliteTransaction, WithDeferredTransactionRollsbackForException) +TEST_F(SqliteTransaction, with_deferred_transaction_rollsback_for_exception) { InSequence s; ON_CALL(callableMock, Call()).WillByDefault(Throw(std::exception{})); @@ -382,7 +376,7 @@ TEST_F(SqliteTransaction, WithDeferredTransactionRollsbackForException) } } -TEST_F(SqliteTransaction, WithImmediateTransactionNoReturnCommit) +TEST_F(SqliteTransaction, with_immediate_transaction_no_return_commit) { InSequence s; @@ -395,7 +389,7 @@ TEST_F(SqliteTransaction, WithImmediateTransactionNoReturnCommit) Sqlite::withImmediateTransaction(mockTransactionBackend, callableMock.AsStdFunction()); } -TEST_F(SqliteTransaction, WithImmediateTransactionWithReturnCommit) +TEST_F(SqliteTransaction, with_immediate_transaction_with_return_commit) { InSequence s; @@ -408,7 +402,7 @@ TEST_F(SqliteTransaction, WithImmediateTransactionWithReturnCommit) Sqlite::withImmediateTransaction(mockTransactionBackend, callableWithReturnMock.AsStdFunction()); } -TEST_F(SqliteTransaction, WithImmediateTransactionReturnsValue) +TEST_F(SqliteTransaction, with_immediate_transaction_returns_value) { auto callable = callableWithReturnMock.AsStdFunction(); @@ -418,7 +412,7 @@ TEST_F(SqliteTransaction, WithImmediateTransactionReturnsValue) ASSERT_THAT(value, Eq(212)); } -TEST_F(SqliteTransaction, WithImmediateTransactionRollsbackForException) +TEST_F(SqliteTransaction, with_immediate_transaction_rollsback_for_exception) { InSequence s; ON_CALL(callableMock, Call()).WillByDefault(Throw(std::exception{})); diff --git a/tests/unit/unittest/sqlitevalue-test.cpp b/tests/unit/tests/unittests/sqlite/sqlitevalue-test.cpp similarity index 70% rename from tests/unit/unittest/sqlitevalue-test.cpp rename to tests/unit/tests/unittests/sqlite/sqlitevalue-test.cpp index e69c981cd56..56d30419d2b 100644 --- a/tests/unit/unittest/sqlitevalue-test.cpp +++ b/tests/unit/tests/unittests/sqlite/sqlitevalue-test.cpp @@ -1,70 +1,70 @@ // Copyright (C) 2020 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" #include #include namespace { -TEST(SqliteValue, ConstructDefault) +TEST(SqliteValue, construct_default) { Sqlite::Value value{}; ASSERT_TRUE(value.isNull()); } -TEST(SqliteValue, ConstructNullValue) +TEST(SqliteValue, construct_null_value) { Sqlite::Value value{Sqlite::NullValue{}}; ASSERT_TRUE(value.isNull()); } -TEST(SqliteValue, ConstructLongLong) +TEST(SqliteValue, construct_long_long) { Sqlite::Value value{1LL}; ASSERT_THAT(value.toInteger(), Eq(1LL)); } -TEST(SqliteValue, ConstructInteger) +TEST(SqliteValue, construct_integer) { Sqlite::Value value{1}; ASSERT_THAT(value.toInteger(), Eq(1LL)); } -TEST(SqliteValue, ConstructFloatingPoint) +TEST(SqliteValue, construct_floating_point) { Sqlite::Value value{1.1}; ASSERT_THAT(value.toFloat(), Eq(1.1)); } -TEST(SqliteValue, ConstructStringFromCString) +TEST(SqliteValue, construct_string_from_c_string) { Sqlite::Value value{"foo"}; ASSERT_THAT(value.toStringView(), Eq("foo")); } -TEST(SqliteValue, ConstructStringFromUtilsString) +TEST(SqliteValue, construct_string_from_utils_string) { Sqlite::Value value{Utils::SmallString{"foo"}}; ASSERT_THAT(value.toStringView(), Eq("foo")); } -TEST(SqliteValue, ConstructStringFromQString) +TEST(SqliteValue, construct_string_from_q_string) { Sqlite::Value value{QString{"foo"}}; ASSERT_THAT(value.toStringView(), Eq("foo")); } -TEST(SqliteValue, ConstructBlobFromSpan) +TEST(SqliteValue, construct_blob_from_span) { Utils::span bytes{reinterpret_cast("abcd"), 4}; @@ -73,7 +73,7 @@ TEST(SqliteValue, ConstructBlobFromSpan) ASSERT_THAT(value.toBlobView(), Eq(bytes)); } -TEST(SqliteValue, ConstructBlobFromBlob) +TEST(SqliteValue, construct_blob_from_blob) { Utils::span bytes{reinterpret_cast("abcd"), 4}; @@ -82,7 +82,7 @@ TEST(SqliteValue, ConstructBlobFromBlob) ASSERT_THAT(value.toBlobView(), Eq(bytes)); } -TEST(SqliteValue, ConstructNullFromNullQVariant) +TEST(SqliteValue, construct_null_from_null_q_variant) { QVariant variant{}; @@ -91,7 +91,7 @@ TEST(SqliteValue, ConstructNullFromNullQVariant) ASSERT_TRUE(value.isNull()); } -TEST(SqliteValue, ConstructStringFromIntQVariant) +TEST(SqliteValue, construct_string_from_int_q_variant) { QVariant variant{1}; @@ -100,7 +100,7 @@ TEST(SqliteValue, ConstructStringFromIntQVariant) ASSERT_THAT(value.toInteger(), Eq(1)); } -TEST(SqliteValue, ConstructStringFromLongLongQVariant) +TEST(SqliteValue, construct_string_from_long_long_q_variant) { QVariant variant{1LL}; @@ -109,7 +109,7 @@ TEST(SqliteValue, ConstructStringFromLongLongQVariant) ASSERT_THAT(value.toInteger(), Eq(1)); } -TEST(SqliteValue, ConstructStringFromUintQVariant) +TEST(SqliteValue, construct_string_from_uint_q_variant) { QVariant variant{1u}; @@ -118,7 +118,7 @@ TEST(SqliteValue, ConstructStringFromUintQVariant) ASSERT_THAT(value.toInteger(), Eq(1)); } -TEST(SqliteValue, ConstructStringFromFloatQVariant) +TEST(SqliteValue, construct_string_from_float_q_variant) { QVariant variant{1.}; @@ -127,7 +127,7 @@ TEST(SqliteValue, ConstructStringFromFloatQVariant) ASSERT_THAT(value.toFloat(), Eq(1)); } -TEST(SqliteValue, ConstructStringFromStringQVariant) +TEST(SqliteValue, construct_string_from_string_q_variant) { QVariant variant{QString{"foo"}}; @@ -136,7 +136,7 @@ TEST(SqliteValue, ConstructStringFromStringQVariant) ASSERT_THAT(value.toStringView(), Eq("foo")); } -TEST(SqliteValue, ConstructBlobFromByteArrayQVariant) +TEST(SqliteValue, construct_blob_from_byte_array_q_variant) { Utils::span bytes{reinterpret_cast("abcd"), 4}; QVariant variant{QByteArray{"abcd"}}; @@ -146,7 +146,7 @@ TEST(SqliteValue, ConstructBlobFromByteArrayQVariant) ASSERT_THAT(value.toBlobView(), Eq(bytes)); } -TEST(SqliteValue, ConvertToNullQVariant) +TEST(SqliteValue, convert_to_null_q_variant) { Sqlite::Value value{}; @@ -155,7 +155,7 @@ TEST(SqliteValue, ConvertToNullQVariant) ASSERT_TRUE(variant.isNull()); } -TEST(SqliteValue, ConvertToStringQVariant) +TEST(SqliteValue, convert_to_string_q_variant) { Sqlite::Value value{"foo"}; @@ -164,7 +164,7 @@ TEST(SqliteValue, ConvertToStringQVariant) ASSERT_THAT(variant, Eq("foo")); } -TEST(SqliteValue, ConvertToIntegerQVariant) +TEST(SqliteValue, convert_to_integer_q_variant) { Sqlite::Value value{1}; @@ -173,7 +173,7 @@ TEST(SqliteValue, ConvertToIntegerQVariant) ASSERT_THAT(variant, Eq(1)); } -TEST(SqliteValue, ConvertToFloatQVariant) +TEST(SqliteValue, convert_to_float_q_variant) { Sqlite::Value value{1.1}; @@ -182,7 +182,7 @@ TEST(SqliteValue, ConvertToFloatQVariant) ASSERT_THAT(variant, Eq(1.1)); } -TEST(SqliteValue, ConvertToByteArrayQVariant) +TEST(SqliteValue, convert_to_byte_array_q_variant) { Utils::span bytes{reinterpret_cast("abcd"), 4}; Sqlite::Value value{bytes}; @@ -192,49 +192,49 @@ TEST(SqliteValue, ConvertToByteArrayQVariant) ASSERT_THAT(variant, Eq(QByteArray{"abcd"})); } -TEST(SqliteValue, IntegerEquals) +TEST(SqliteValue, integer_equals) { bool isEqual = Sqlite::Value{1} == 1LL; ASSERT_TRUE(isEqual); } -TEST(SqliteValue, IntegerEqualsInverse) +TEST(SqliteValue, integer_equals_inverse) { bool isEqual = 1LL == Sqlite::Value{1}; ASSERT_TRUE(isEqual); } -TEST(SqliteValue, FloatEquals) +TEST(SqliteValue, float_equals) { bool isEqual = Sqlite::Value{1.0} == 1.; ASSERT_TRUE(isEqual); } -TEST(SqliteValue, FloatEqualsInverse) +TEST(SqliteValue, float_equals_inverse) { bool isEqual = 1. == Sqlite::Value{1.0}; ASSERT_TRUE(isEqual); } -TEST(SqliteValue, StringEquals) +TEST(SqliteValue, string_equals) { bool isEqual = Sqlite::Value{"foo"} == "foo"; ASSERT_TRUE(isEqual); } -TEST(SqliteValue, StringEqualsInverse) +TEST(SqliteValue, string_equals_inverse) { bool isEqual = "foo" == Sqlite::Value{"foo"}; ASSERT_TRUE(isEqual); } -TEST(SqliteValue, BlobEquals) +TEST(SqliteValue, blob_equals) { Utils::span bytes{reinterpret_cast("abcd"), 4}; bool isEqual = Sqlite::Value{bytes} == bytes; @@ -242,7 +242,7 @@ TEST(SqliteValue, BlobEquals) ASSERT_TRUE(isEqual); } -TEST(SqliteValue, BlobInverseEquals) +TEST(SqliteValue, blob_inverse_equals) { Utils::span bytes{reinterpret_cast("abcd"), 4}; bool isEqual = bytes == Sqlite::Value{bytes}; @@ -250,105 +250,105 @@ TEST(SqliteValue, BlobInverseEquals) ASSERT_TRUE(isEqual); } -TEST(SqliteValue, IntegerAndFloatAreNotEquals) +TEST(SqliteValue, integer_and_float_are_not_equals) { bool isEqual = Sqlite::Value{1} == 1.; ASSERT_FALSE(isEqual); } -TEST(SqliteValue, NullValuesNeverEqual) +TEST(SqliteValue, null_values_never_equal) { bool isEqual = Sqlite::Value{} == Sqlite::Value{}; ASSERT_FALSE(isEqual); } -TEST(SqliteValue, IntegerValuesAreEquals) +TEST(SqliteValue, integer_values_are_equals) { bool isEqual = Sqlite::Value{1} == Sqlite::Value{1}; ASSERT_TRUE(isEqual); } -TEST(SqliteValue, IntegerAndFloatValuesAreNotEquals) +TEST(SqliteValue, integer_and_float_values_are_not_equals) { bool isEqual = Sqlite::Value{1} == Sqlite::Value{1.}; ASSERT_FALSE(isEqual); } -TEST(SqliteValue, StringAndQStringAreEquals) +TEST(SqliteValue, string_and_q_string_are_equals) { bool isEqual = Sqlite::Value{"foo"} == QString{"foo"}; ASSERT_TRUE(isEqual); } -TEST(SqliteValue, IntegerAndFloatValuesAreUnequal) +TEST(SqliteValue, integer_and_float_values_are_unequal) { bool isUnequal = Sqlite::Value{1} != Sqlite::Value{1.0}; ASSERT_TRUE(isUnequal); } -TEST(SqliteValue, IntegerAndFloatAreUnequal) +TEST(SqliteValue, integer_and_float_are_unequal) { bool isUnequal = Sqlite::Value{1} != 1.0; ASSERT_TRUE(isUnequal); } -TEST(SqliteValue, IntegerAndFloatAreUnequalInverse) +TEST(SqliteValue, integer_and_float_are_unequal_inverse) { bool isUnequal = 1.0 != Sqlite::Value{1}; ASSERT_TRUE(isUnequal); } -TEST(SqliteValue, IntegersAreUnequal) +TEST(SqliteValue, integers_are_unequal) { bool isUnequal = Sqlite::Value{1} != 2; ASSERT_TRUE(isUnequal); } -TEST(SqliteValue, IntegersAreUnequalInverse) +TEST(SqliteValue, integers_are_unequal_inverse) { bool isUnequal = 2 != Sqlite::Value{1}; ASSERT_TRUE(isUnequal); } -TEST(SqliteValue, NullType) +TEST(SqliteValue, null_type) { auto type = Sqlite::Value{}.type(); ASSERT_THAT(type, Sqlite::ValueType::Null); } -TEST(SqliteValue, IntegerType) +TEST(SqliteValue, integer_type) { auto type = Sqlite::Value{1}.type(); ASSERT_THAT(type, Sqlite::ValueType::Integer); } -TEST(SqliteValue, FloatType) +TEST(SqliteValue, float_type) { auto type = Sqlite::Value{1.}.type(); ASSERT_THAT(type, Sqlite::ValueType::Float); } -TEST(SqliteValue, StringType) +TEST(SqliteValue, string_type) { auto type = Sqlite::Value{"foo"}.type(); ASSERT_THAT(type, Sqlite::ValueType::String); } -TEST(SqliteValue, BlobType) +TEST(SqliteValue, blob_type) { Utils::span bytes{reinterpret_cast("abcd"), 4}; auto type = Sqlite::Value{bytes}.type(); @@ -356,70 +356,70 @@ TEST(SqliteValue, BlobType) ASSERT_THAT(type, Sqlite::ValueType::Blob); } -TEST(SqliteValue, NullValueAndValueViewAreNotEqual) +TEST(SqliteValue, null_value_and_value_view_are_not_equal) { bool isEqual = Sqlite::ValueView::create(Sqlite::NullValue{}) == Sqlite::Value{}; ASSERT_FALSE(isEqual); } -TEST(SqliteValue, NullValueViewAndValueAreNotEqual) +TEST(SqliteValue, null_value_view_and_value_are_not_equal) { bool isEqual = Sqlite::Value{} == Sqlite::ValueView::create(Sqlite::NullValue{}); ASSERT_FALSE(isEqual); } -TEST(SqliteValue, StringValueAndValueViewEquals) +TEST(SqliteValue, string_value_and_value_view_equals) { bool isEqual = Sqlite::ValueView::create("foo") == Sqlite::Value{"foo"}; ASSERT_TRUE(isEqual); } -TEST(SqliteValue, StringValueAndValueViewEqualsInverse) +TEST(SqliteValue, string_value_and_value_view_equals_inverse) { bool isEqual = Sqlite::Value{"foo"} == Sqlite::ValueView::create("foo"); ASSERT_TRUE(isEqual); } -TEST(SqliteValue, IntegerValueAndValueViewEquals) +TEST(SqliteValue, integer_value_and_value_view_equals) { bool isEqual = Sqlite::ValueView::create(1) == Sqlite::Value{1}; ASSERT_TRUE(isEqual); } -TEST(SqliteValue, IntegerValueAndValueViewEqualsInverse) +TEST(SqliteValue, integer_value_and_value_view_equals_inverse) { bool isEqual = Sqlite::Value{2} == Sqlite::ValueView::create(2); ASSERT_TRUE(isEqual); } -TEST(SqliteValue, FloatValueAndValueViewEquals) +TEST(SqliteValue, float_value_and_value_view_equals) { bool isEqual = Sqlite::ValueView::create(1.1) == Sqlite::Value{1.1}; ASSERT_TRUE(isEqual); } -TEST(SqliteValue, FloatValueAndValueViewEqualsInverse) +TEST(SqliteValue, float_value_and_value_view_equals_inverse) { bool isEqual = Sqlite::Value{1.1} == Sqlite::ValueView::create(1.1); ASSERT_TRUE(isEqual); } -TEST(SqliteValue, StringValueAndIntergerValueViewAreNotEqual) +TEST(SqliteValue, string_value_and_interger_value_view_are_not_equal) { bool isEqual = Sqlite::Value{"foo"} == Sqlite::ValueView::create(1); ASSERT_FALSE(isEqual); } -TEST(SqliteValue, BlobValueAndValueViewEquals) +TEST(SqliteValue, blob_value_and_value_view_equals) { Utils::span bytes{reinterpret_cast("abcd"), 4}; @@ -428,7 +428,7 @@ TEST(SqliteValue, BlobValueAndValueViewEquals) ASSERT_TRUE(isEqual); } -TEST(SqliteValue, ConvertNullValueViewIntoValue) +TEST(SqliteValue, convert_null_value_view_into_value) { auto view = Sqlite::ValueView::create(Sqlite::NullValue{}); @@ -437,7 +437,7 @@ TEST(SqliteValue, ConvertNullValueViewIntoValue) ASSERT_TRUE(value.isNull()); } -TEST(SqliteValue, ConvertStringValueViewIntoValue) +TEST(SqliteValue, convert_string_value_view_into_value) { auto view = Sqlite::ValueView::create("foo"); @@ -446,7 +446,7 @@ TEST(SqliteValue, ConvertStringValueViewIntoValue) ASSERT_THAT(value, Eq("foo")); } -TEST(SqliteValue, ConvertIntegerValueViewIntoValue) +TEST(SqliteValue, convert_integer_value_view_into_value) { auto view = Sqlite::ValueView::create(1); @@ -455,7 +455,7 @@ TEST(SqliteValue, ConvertIntegerValueViewIntoValue) ASSERT_THAT(value, Eq(1)); } -TEST(SqliteValue, ConvertFloatValueViewIntoValue) +TEST(SqliteValue, convert_float_value_view_into_value) { auto view = Sqlite::ValueView::create(1.4); @@ -464,7 +464,7 @@ TEST(SqliteValue, ConvertFloatValueViewIntoValue) ASSERT_THAT(value, Eq(1.4)); } -TEST(SqliteValue, ConvertBlobValueViewIntoValue) +TEST(SqliteValue, convert_blob_value_view_into_value) { Utils::span bytes{reinterpret_cast("abcd"), 4}; auto view = Sqlite::ValueView::create(Sqlite::BlobView{bytes}); diff --git a/tests/unit/unittest/sqlstatementbuilder-test.cpp b/tests/unit/tests/unittests/sqlite/sqlstatementbuilder-test.cpp similarity index 90% rename from tests/unit/unittest/sqlstatementbuilder-test.cpp rename to tests/unit/tests/unittests/sqlite/sqlstatementbuilder-test.cpp index d70ea1fa2f1..799cf911a17 100644 --- a/tests/unit/unittest/sqlstatementbuilder-test.cpp +++ b/tests/unit/tests/unittests/sqlite/sqlstatementbuilder-test.cpp @@ -1,7 +1,7 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" #include #include @@ -14,7 +14,7 @@ using Sqlite::SqlStatementBuilderException; using SV = Utils::SmallStringVector; -TEST(SqlStatementBuilder, Bind) +TEST(SqlStatementBuilder, bind) { SqlStatementBuilder sqlStatementBuilder("SELECT $columns FROM $table WHERE $column = 'foo' AND rowid=$row AND rowid IN ($rows)"); @@ -27,7 +27,7 @@ TEST(SqlStatementBuilder, Bind) ASSERT_THAT(sqlStatementBuilder.sqlStatement(), "SELECT name, number FROM test WHERE name = 'foo' AND rowid=20 AND rowid IN (1, 2, 3)"); } -TEST(SqlStatementBuilder, BindEmpty) +TEST(SqlStatementBuilder, bind_empty) { SqlStatementBuilder sqlStatementBuilder("SELECT $columns FROM $table$emptyPart"); sqlStatementBuilder.bind("$columns", SV{"name", "number"}); @@ -38,7 +38,7 @@ TEST(SqlStatementBuilder, BindEmpty) ASSERT_THAT(sqlStatementBuilder.sqlStatement(), "SELECT name, number FROM test"); } -TEST(SqlStatementBuilder, BindFailure) +TEST(SqlStatementBuilder, bind_failure) { SqlStatementBuilder sqlStatementBuilder("SELECT $columns FROM $table"); @@ -51,7 +51,7 @@ TEST(SqlStatementBuilder, BindFailure) ASSERT_THROW(sqlStatementBuilder.bindWithUpdateTemplateParameters("$columns", columns), SqlStatementBuilderException); } -TEST(SqlStatementBuilder, BindWithInsertTemplateParameters) +TEST(SqlStatementBuilder, bind_with_insert_template_parameters) { Utils::SmallStringVector columns = {"name", "number"}; @@ -63,7 +63,7 @@ TEST(SqlStatementBuilder, BindWithInsertTemplateParameters) ASSERT_THAT(sqlStatementBuilder.sqlStatement(), "INSERT OR IGNORE INTO test (name, number) VALUES (?, ?)"); } -TEST(SqlStatementBuilder, BindWithUpdateTemplateParameters) +TEST(SqlStatementBuilder, bind_with_update_template_parameters) { Utils::SmallStringVector columns = {"name", "number"}; @@ -74,7 +74,7 @@ TEST(SqlStatementBuilder, BindWithUpdateTemplateParameters) ASSERT_THAT(sqlStatementBuilder.sqlStatement(), "UPDATE test SET name=?, number=? WHERE id=?"); } -TEST(SqlStatementBuilder, BindWithUpdateTemplateNames) +TEST(SqlStatementBuilder, bind_with_update_template_names) { Utils::SmallStringVector columns = {"name", "number"}; @@ -85,7 +85,7 @@ TEST(SqlStatementBuilder, BindWithUpdateTemplateNames) ASSERT_THAT(sqlStatementBuilder.sqlStatement(), "UPDATE test SET name=@name, number=@number WHERE id=@id"); } -TEST(SqlStatementBuilder, ClearOnRebinding) +TEST(SqlStatementBuilder, clear_on_rebinding) { SqlStatementBuilder sqlStatementBuilder("SELECT $columns FROM $table"); @@ -99,7 +99,7 @@ TEST(SqlStatementBuilder, ClearOnRebinding) ASSERT_THAT(sqlStatementBuilder.sqlStatement(), "SELECT name, number FROM test2"); } -TEST(SqlStatementBuilder, ClearBinding) +TEST(SqlStatementBuilder, clear_binding) { SqlStatementBuilder sqlStatementBuilder("SELECT $columns FROM $table"); @@ -113,7 +113,7 @@ TEST(SqlStatementBuilder, ClearBinding) ASSERT_THROW(sqlStatementBuilder.sqlStatement(), SqlStatementBuilderException); } -TEST(SqlStatementBuilder, SqlStatementFailure) +TEST(SqlStatementBuilder, sql_statement_failure) { SqlStatementBuilder sqlStatementBuilder("SELECT $columns FROM $table"); @@ -122,7 +122,7 @@ TEST(SqlStatementBuilder, SqlStatementFailure) ASSERT_THROW(sqlStatementBuilder.sqlStatement(), SqlStatementBuilderException); } -TEST(SqlStatementBuilder, IsBuild) +TEST(SqlStatementBuilder, is_build) { SqlStatementBuilder sqlStatementBuilder("SELECT $columns FROM $table"); diff --git a/tests/unit/unittest/unittests-main.cpp b/tests/unit/tests/unittests/unittests-main.cpp similarity index 98% rename from tests/unit/unittest/unittests-main.cpp rename to tests/unit/tests/unittests/unittests-main.cpp index e2b83c0941a..06c8268f07e 100644 --- a/tests/unit/unittest/unittests-main.cpp +++ b/tests/unit/tests/unittests/unittests-main.cpp @@ -1,7 +1,7 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" #include #include diff --git a/tests/unit/tests/unittests/utils/CMakeLists.txt b/tests/unit/tests/unittests/utils/CMakeLists.txt new file mode 100644 index 00000000000..d4e8e56e2e4 --- /dev/null +++ b/tests/unit/tests/unittests/utils/CMakeLists.txt @@ -0,0 +1,16 @@ +# QtCreator Utils Tests +extend_qtc_test(unittest + SOURCES + matchingtext-test.cpp + sizedarray-test.cpp + smallstring-test.cpp +) + +extend_qtc_test(unittest + CONDITION TARGET GoogleBenchmark + DEPENDS GoogleBenchmark + SOURCES + smallstring-benchmark.cpp +) + +unittest_copy_data_folder() diff --git a/tests/unit/unittest/data/sqlite_database.db b/tests/unit/tests/unittests/utils/data/sqlite_database.db similarity index 100% rename from tests/unit/unittest/data/sqlite_database.db rename to tests/unit/tests/unittests/utils/data/sqlite_database.db diff --git a/tests/unit/unittest/matchingtext-test.cpp b/tests/unit/tests/unittests/utils/matchingtext-test.cpp similarity index 63% rename from tests/unit/unittest/matchingtext-test.cpp rename to tests/unit/tests/unittests/utils/matchingtext-test.cpp index 5028081bdb1..716eb7ff8b8 100644 --- a/tests/unit/unittest/matchingtext-test.cpp +++ b/tests/unit/tests/unittests/utils/matchingtext-test.cpp @@ -1,7 +1,7 @@ // Copyright (C) 2017 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" #include @@ -42,35 +42,35 @@ protected: const IsNextBlockDeeperIndented nextBlockIsIndented = [](const QTextBlock &) { return true; }; }; -TEST_F(MatchingText, ContextAllowsAutoParentheses_ForNoInput) +TEST_F(MatchingText, context_allows_auto_parentheses_for_no_input) { const Document document("@"); ASSERT_TRUE(MT::contextAllowsAutoParentheses(document.cursor, "")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_NotInEmptyLine) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_not_in_empty_line) { const Document document("@"); ASSERT_FALSE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_Initializer) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_initializer) { const Document document("Type object@"); ASSERT_TRUE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_AfterFunctionDeclaratorSameLine) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_after_function_declarator_same_line) { const Document document("void g() @"); ASSERT_TRUE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_AfterFunctionDeclaratorNewLine) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_after_function_declarator_new_line) { const Document document("void g()\n" "@"); @@ -78,7 +78,7 @@ TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_AfterFunctionDeclar ASSERT_TRUE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_AfterFunctionDeclaratorNewLineAndMore) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_after_function_declarator_new_line_and_more) { const Document document("void g()\n" "@\n" @@ -87,70 +87,70 @@ TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_AfterFunctionDeclar ASSERT_TRUE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_AfterLambdaDeclarator) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_after_lambda_declarator) { const Document document("[]() @"); ASSERT_TRUE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_NotBeforeOpeningCurlyBrace) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_not_before_opening_curly_brace) { const Document document("@{"); ASSERT_FALSE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_BeforeClosingCurlyBrace) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_before_closing_curly_brace) { const Document document("@}"); ASSERT_TRUE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_BeforeClosingBracket) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_before_closing_bracket) { const Document document("@]"); ASSERT_TRUE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_BeforeClosingParen) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_before_closing_paren) { const Document document("@)"); ASSERT_TRUE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_BeforeSemicolon) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_before_semicolon) { const Document document("@;"); ASSERT_TRUE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_BeforeComma) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_before_comma) { const Document document("@,"); ASSERT_TRUE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_NotInCppComment) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_not_in_cpp_comment) { const Document document("// @"); ASSERT_FALSE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_NotInCppDoxygenComment) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_not_in_cpp_doxygen_comment) { const Document document("//! @"); ASSERT_FALSE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_NotBeforeIndented) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_not_before_indented) { const Document document("@\n" " 1+1;"); @@ -158,7 +158,7 @@ TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_NotBeforeIndented) ASSERT_FALSE(MT::contextAllowsAutoParentheses(document.cursor, "{", nextBlockIsIndented)); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_NotBeforeIndentedWithFollowingComment) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_not_before_indented_with_following_comment) { const Document document("@\n // comment" " 1+1;"); @@ -166,7 +166,7 @@ TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_NotBeforeIndentedWi ASSERT_FALSE(MT::contextAllowsAutoParentheses(document.cursor, "{", nextBlockIsIndented)); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_NotBeforeIndentedWithTextInFront) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_not_before_indented_with_text_in_front) { const Document document("if (true) @\n" " 1+1;"); @@ -174,7 +174,7 @@ TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_NotBeforeIndentedWi ASSERT_FALSE(MT::contextAllowsAutoParentheses(document.cursor, "{", nextBlockIsIndented)); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_NotBeforeIndentedOnEmptyLine1) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_not_before_indented_on_empty_line1) { const Document document("if (true)\n" "@\n" @@ -183,7 +183,7 @@ TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_NotBeforeIndentedOn ASSERT_FALSE(MT::contextAllowsAutoParentheses(document.cursor, "{", nextBlockIsIndented)); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_NotBeforeIndentedOnEmptyLine2) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_not_before_indented_on_empty_line2) { const Document document("if (true)\n" " @\n" @@ -192,112 +192,112 @@ TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_NotBeforeIndentedOn ASSERT_FALSE(MT::contextAllowsAutoParentheses(document.cursor, "{", nextBlockIsIndented)); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_NotInTheMiddle) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_not_in_the_middle) { const Document document("if (true) @ true;"); ASSERT_FALSE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_NotAfterControlFlow_WhileAndFriends) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_not_after_control_flow_while_and_friends) { const Document document("while (true) @"); ASSERT_FALSE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_NotAfterControlFlow_DoAndFriends) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_not_after_control_flow_do_and_friends) { const Document document("do @"); ASSERT_FALSE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_InvalidCode_UnbalancedParens) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_invalid_code_unbalanced_parens) { const Document document(") @"); ASSERT_TRUE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_InvalidCode_UnbalancedParens2) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_invalid_code_unbalanced_parens2) { const Document document("while true) @"); ASSERT_TRUE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_InvalidCode_OnlyBalancedParens) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_invalid_code_only_balanced_parens) { const Document document("() @"); ASSERT_TRUE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_NotBeforeNamedNamespace) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_not_before_named_namespace) { const Document document("namespace X @"); ASSERT_FALSE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_NotBeforeNamedNamespaceWithAttributeSpecifier) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_not_before_named_namespace_with_attribute_specifier) { const Document document("namespace [[xyz]] X @"); ASSERT_FALSE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_NotBeforeUnnamedNamespace) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_not_before_unnamed_namespace) { const Document document("namespace @"); ASSERT_FALSE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_NotBeforeUnnamedNamespaceWithAttributeSpecifier) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_not_before_unnamed_namespace_with_attribute_specifier) { const Document document("namespace [[xyz]] @"); ASSERT_FALSE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_NotBeforeNestedNamespace) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_not_before_nested_namespace) { const Document document("namespace X::Y::Z @"); ASSERT_FALSE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_NotBeforeClass) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_not_before_class) { const Document document("class X @"); ASSERT_FALSE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_NotBeforeStruct) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_not_before_struct) { const Document document("struct X @"); ASSERT_FALSE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_NotBeforeEnum) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_not_before_enum) { const Document document("enum X @"); ASSERT_FALSE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_NotBeforeUnion) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_not_before_union) { const Document document("union X @"); ASSERT_FALSE(MT::contextAllowsAutoParentheses(document.cursor, "{")); } -TEST_F(MatchingText, ContextAllowsAutoParentheses_CurlyBrace_NotWithinString) +TEST_F(MatchingText, context_allows_auto_parentheses_curly_brace_not_within_string) { const Document document("\"a@b\""); diff --git a/tests/unit/unittest/sizedarray-test.cpp b/tests/unit/tests/unittests/utils/sizedarray-test.cpp similarity index 67% rename from tests/unit/unittest/sizedarray-test.cpp rename to tests/unit/tests/unittests/utils/sizedarray-test.cpp index 8e78771ca55..c672c8c762e 100644 --- a/tests/unit/unittest/sizedarray-test.cpp +++ b/tests/unit/tests/unittests/utils/sizedarray-test.cpp @@ -1,7 +1,7 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" #include @@ -9,21 +9,21 @@ namespace { using Utils::SizedArray; -TEST(SizedArray, EmptySize) +TEST(SizedArray, empty_size) { SizedArray array; ASSERT_THAT(array.size(), 0); } -TEST(SizedArray, IsEmpty) +TEST(SizedArray, is_empty) { SizedArray array; ASSERT_TRUE(array.empty()); } -TEST(SizedArray, IsNotEmpty) +TEST(SizedArray, is_not_empty) { SizedArray array; @@ -32,7 +32,7 @@ TEST(SizedArray, IsNotEmpty) ASSERT_FALSE(array.empty()); } -TEST(SizedArray, SizeOneAfterPushBack) +TEST(SizedArray, size_one_after_push_back) { SizedArray array; @@ -41,7 +41,7 @@ TEST(SizedArray, SizeOneAfterPushBack) ASSERT_THAT(array.size(), 1); } -TEST(SizedArray, FirstValueAfterPushBack) +TEST(SizedArray, first_value_after_push_back) { SizedArray array; @@ -50,7 +50,7 @@ TEST(SizedArray, FirstValueAfterPushBack) ASSERT_THAT(array.front(), 'x'); } -TEST(SizedArray, LastValueAfterPushBack) +TEST(SizedArray, last_value_after_push_back) { SizedArray array; @@ -59,21 +59,21 @@ TEST(SizedArray, LastValueAfterPushBack) ASSERT_THAT(array.back(), 'x'); } -TEST(SizedArray, EndIteratorIsEqualBeginForEmptyArray) +TEST(SizedArray, end_iterator_is_equal_begin_for_empty_array) { SizedArray array; ASSERT_THAT(array.begin(), array.end()); } -TEST(SizedArray, ConstEndIteratorIsEqualBeginForEmptyArray) +TEST(SizedArray, const_end_iterator_is_equal_begin_for_empty_array) { const SizedArray array = {}; ASSERT_THAT(array.begin(), array.end()); } -TEST(SizedArray, EndIteratorIsOneAfterBeginForOneSizedArray) +TEST(SizedArray, end_iterator_is_one_after_begin_for_one_sized_array) { SizedArray array; @@ -82,7 +82,7 @@ TEST(SizedArray, EndIteratorIsOneAfterBeginForOneSizedArray) ASSERT_THAT(std::next(array.begin(), 1), array.end()); } -TEST(SizedArray, CEndIteratorIsOneAfterBeginForOneSizedArray) +TEST(SizedArray, c_end_iterator_is_one_after_begin_for_one_sized_array) { SizedArray array = {}; @@ -91,21 +91,21 @@ TEST(SizedArray, CEndIteratorIsOneAfterBeginForOneSizedArray) ASSERT_THAT(std::next(array.cbegin(), 1), array.cend()); } -TEST(SizedArray, REndIteratorIsEqualRBeginForEmptyArray) +TEST(SizedArray, r_end_iterator_is_equal_r_begin_for_empty_array) { SizedArray array; ASSERT_THAT(array.rbegin(), array.rend()); } -TEST(SizedArray, ConstREndIteratorIsEqualRBeginForEmptyArray) +TEST(SizedArray, const_r_end_iterator_is_equal_r_begin_for_empty_array) { const SizedArray array = {}; ASSERT_THAT(array.rbegin(), array.rend()); } -TEST(SizedArray, REndIteratorIsOneAfterRBeginForOneSizedArray) +TEST(SizedArray, r_end_iterator_is_one_after_r_begin_for_one_sized_array) { SizedArray array; @@ -114,7 +114,7 @@ TEST(SizedArray, REndIteratorIsOneAfterRBeginForOneSizedArray) ASSERT_THAT(std::next(array.rbegin(), 1), array.rend()); } -TEST(SizedArray, ConstREndIteratorIsOneAfterRBeginForOneSizedArray) +TEST(SizedArray, const_r_end_iterator_is_one_after_r_begin_for_one_sized_array) { SizedArray array = {}; @@ -123,7 +123,7 @@ TEST(SizedArray, ConstREndIteratorIsOneAfterRBeginForOneSizedArray) ASSERT_THAT(std::next(array.crbegin(), 1), array.crend()); } -TEST(SizedArray, InitializerListSize) +TEST(SizedArray, initializer_list_size) { SizedArray array{'a', 'b'}; diff --git a/tests/unit/unittest/smallstring-benchmark.cpp b/tests/unit/tests/unittests/utils/smallstring-benchmark.cpp similarity index 100% rename from tests/unit/unittest/smallstring-benchmark.cpp rename to tests/unit/tests/unittests/utils/smallstring-benchmark.cpp diff --git a/tests/unit/unittest/smallstring-test.cpp b/tests/unit/tests/unittests/utils/smallstring-test.cpp similarity index 75% rename from tests/unit/unittest/smallstring-test.cpp rename to tests/unit/tests/unittests/utils/smallstring-test.cpp index ab8ea7fae5d..98cdc266f9a 100644 --- a/tests/unit/unittest/smallstring-test.cpp +++ b/tests/unit/tests/unittests/utils/smallstring-test.cpp @@ -1,7 +1,7 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" #include @@ -22,22 +22,22 @@ static_assert(16 == alignof(Utils::BasicSmallString<31>)); static_assert(16 == alignof(Utils::BasicSmallString<63>)); static_assert(16 == alignof(Utils::BasicSmallString<190>)); -TEST(SmallString, BasicStringEqual) +TEST(SmallString, basic_string_equal) { ASSERT_THAT(SmallString("text"), Eq(SmallString("text"))); } -TEST(SmallString, BasicSmallStringUnequal) +TEST(SmallString, basic_small_string_unequal) { ASSERT_THAT(SmallString("text"), Ne(SmallString("other text"))); } -TEST(SmallString, NullSmallStringIsEqualToEmptySmallString) +TEST(SmallString, null_small_string_is_equal_to_empty_small_string) { ASSERT_THAT(SmallString(), Eq(SmallString(""))); } -TEST(SmallString, ShortSmallStringLiteralIsShortSmallString) +TEST(SmallString, short_small_string_literal_is_short_small_string) { // constexpr SmallStringLiteral shortText("short string"); @@ -45,14 +45,14 @@ TEST(SmallString, ShortSmallStringLiteralIsShortSmallString) ASSERT_TRUE(shortText.isShortString()); } -TEST(SmallString, ShortSmallStringIsShortSmallString) +TEST(SmallString, short_small_string_is_short_small_string) { SmallString shortText("short string"); ASSERT_TRUE(shortText.isShortString()); } -TEST(SmallString, CreateFromCStringIterators) +TEST(SmallString, create_from_c_string_iterators) { char sourceText[] = "this is very very very very very much text"; @@ -61,7 +61,7 @@ TEST(SmallString, CreateFromCStringIterators) ASSERT_THAT(text, SmallString("this is very very very very very much text")); } -TEST(SmallString, CreateFromQByteArrayIterators) +TEST(SmallString, create_from_q_byte_array_iterators) { QByteArray sourceText = "this is very very very very very much text"; @@ -70,7 +70,7 @@ TEST(SmallString, CreateFromQByteArrayIterators) ASSERT_THAT(text, SmallString("this is very very very very very much text")); } -TEST(SmallString, CreateFromSmallStringIterators) +TEST(SmallString, create_from_small_string_iterators) { SmallString sourceText = "this is very very very very very much text"; @@ -79,7 +79,7 @@ TEST(SmallString, CreateFromSmallStringIterators) ASSERT_THAT(text, SmallString("this is very very very very very much text")); } -TEST(SmallString, CreateFromStringView) +TEST(SmallString, create_from_string_view) { SmallStringView sourceText = "this is very very very very very much text"; @@ -88,14 +88,14 @@ TEST(SmallString, CreateFromStringView) ASSERT_THAT(text, SmallString("this is very very very very very much text")); } -TEST(SmallString, ShortSmallStringIsReference) +TEST(SmallString, short_small_string_is_reference) { SmallString longText("very very very very very long text"); ASSERT_TRUE(longText.isReadOnlyReference()); } -TEST(SmallString, SmallStringContructorIsNotReference) +TEST(SmallString, small_string_contructor_is_not_reference) { const char *shortCSmallString = "short string"; auto shortText = SmallString(shortCSmallString); @@ -103,7 +103,7 @@ TEST(SmallString, SmallStringContructorIsNotReference) ASSERT_TRUE(shortText.isShortString()); } -TEST(SmallString, ShortSmallStringIsNotReference) +TEST(SmallString, short_small_string_is_not_reference) { const char *shortCSmallString = "short string"; auto shortText = SmallString::fromUtf8(shortCSmallString); @@ -111,7 +111,7 @@ TEST(SmallString, ShortSmallStringIsNotReference) ASSERT_FALSE(shortText.isReadOnlyReference()); } -TEST(SmallString, LongSmallStringConstrutorIsAllocated) +TEST(SmallString, long_small_string_construtor_is_allocated) { const char *longCSmallString = "very very very very very long text"; auto longText = SmallString(longCSmallString); @@ -119,21 +119,21 @@ TEST(SmallString, LongSmallStringConstrutorIsAllocated) ASSERT_TRUE(longText.hasAllocatedMemory()); } -TEST(SmallString, MaximumShortSmallString) +TEST(SmallString, maximum_short_small_string) { SmallString maximumShortText("very very very very short text", 30); ASSERT_THAT(maximumShortText, StrEq("very very very very short text")); } -TEST(SmallString, LongConstExpressionSmallStringIsReference) +TEST(SmallString, long_const_expression_small_string_is_reference) { SmallString longText("very very very very very very very very very very very long string"); ASSERT_TRUE(longText.isReadOnlyReference()); } -TEST(SmallString, CloneShortSmallString) +TEST(SmallString, clone_short_small_string) { SmallString shortText("short string"); @@ -142,7 +142,7 @@ TEST(SmallString, CloneShortSmallString) ASSERT_THAT(clonedText, Eq("short string")); } -TEST(SmallString, CloneLongSmallString) +TEST(SmallString, clone_long_small_string) { SmallString longText = SmallString::fromUtf8("very very very very very very very very very very very long string"); @@ -151,7 +151,7 @@ TEST(SmallString, CloneLongSmallString) ASSERT_THAT(clonedText, Eq("very very very very very very very very very very very long string")); } -TEST(SmallString, ClonedLongSmallStringDataPointerIsDifferent) +TEST(SmallString, cloned_long_small_string_data_pointer_is_different) { SmallString longText = SmallString::fromUtf8("very very very very very very very very very very very long string"); @@ -160,7 +160,7 @@ TEST(SmallString, ClonedLongSmallStringDataPointerIsDifferent) ASSERT_THAT(clonedText.data(), Ne(longText.data())); } -TEST(SmallString, CopyShortConstExpressionSmallStringIsShortSmallString) +TEST(SmallString, copy_short_const_expression_small_string_is_short_small_string) { SmallString shortText("short string"); @@ -169,7 +169,7 @@ TEST(SmallString, CopyShortConstExpressionSmallStringIsShortSmallString) ASSERT_TRUE(shortTextCopy.isShortString()); } -TEST(SmallString, CopyLongConstExpressionSmallStringIsLongSmallString) +TEST(SmallString, copy_long_const_expression_small_string_is_long_small_string) { SmallString longText("very very very very very very very very very very very long string"); @@ -178,7 +178,7 @@ TEST(SmallString, CopyLongConstExpressionSmallStringIsLongSmallString) ASSERT_FALSE(longTextCopy.isShortString()); } -TEST(SmallString, ShortPathStringIsShortString) +TEST(SmallString, short_path_string_is_short_string) { const char *rawText = "very very very very very very very very very very very long path which fits in the short memory"; @@ -187,7 +187,7 @@ TEST(SmallString, ShortPathStringIsShortString) ASSERT_TRUE(text.isShortString()); } -TEST(SmallString, SmallStringFromCharacterArrayIsReference) +TEST(SmallString, small_string_from_character_array_is_reference) { const char longCString[] = "very very very very very very very very very very very long string"; @@ -196,7 +196,7 @@ TEST(SmallString, SmallStringFromCharacterArrayIsReference) ASSERT_TRUE(longString.isReadOnlyReference()); } -TEST(SmallString, SmallStringFromCharacterPointerIsNotReference) +TEST(SmallString, small_string_from_character_pointer_is_not_reference) { const char *longCString = "very very very very very very very very very very very long string"; @@ -205,7 +205,7 @@ TEST(SmallString, SmallStringFromCharacterPointerIsNotReference) ASSERT_FALSE(longString.isReadOnlyReference()); } -TEST(SmallString, CopyStringFromReference) +TEST(SmallString, copy_string_from_reference) { SmallString longText("very very very very very very very very very very very long string"); SmallString longTextCopy; @@ -215,28 +215,28 @@ TEST(SmallString, CopyStringFromReference) ASSERT_TRUE(longTextCopy.isReadOnlyReference()); } -TEST(SmallString, SmallStringLiteralShortSmallStringDataAccess) +TEST(SmallString, small_string_literal_short_small_string_data_access) { SmallStringLiteral literalText("very very very very very very very very very very very long string"); ASSERT_THAT(literalText, StrEq("very very very very very very very very very very very long string")); } -TEST(SmallString, SmallStringLiteralLongSmallStringDataAccess) +TEST(SmallString, small_string_literal_long_small_string_data_access) { SmallStringLiteral literalText("short string"); ASSERT_THAT(literalText, StrEq("short string")); } -TEST(SmallString, ReferenceDataAccess) +TEST(SmallString, reference_data_access) { SmallString literalText("short string"); ASSERT_THAT(literalText, StrEq("short string")); } -TEST(SmallString, ShortDataAccess) +TEST(SmallString, short_data_access) { const char *shortCString = "short string"; auto shortText = SmallString::fromUtf8(shortCString); @@ -244,7 +244,7 @@ TEST(SmallString, ShortDataAccess) ASSERT_THAT(shortText, StrEq("short string")); } -TEST(SmallString, LongDataAccess) +TEST(SmallString, long_data_access) { const char *longCString = "very very very very very very very very very very very long string"; auto longText = SmallString::fromUtf8(longCString); @@ -252,28 +252,28 @@ TEST(SmallString, LongDataAccess) ASSERT_THAT(longText, StrEq(longCString)); } -TEST(SmallString, LongSmallStringHasShortSmallStringSizeZero) +TEST(SmallString, long_small_string_has_short_small_string_size_zero) { auto longText = SmallString::fromUtf8("very very very very very very very very very very very long string"); ASSERT_THAT(longText.shortStringSize(), 0); } -TEST(SmallString, SmallStringBeginIsEqualEndForEmptySmallString) +TEST(SmallString, small_string_begin_is_equal_end_for_empty_small_string) { SmallString text; ASSERT_THAT(text.begin(), Eq(text.end())); } -TEST(SmallString, SmallStringBeginIsNotEqualEndForNonEmptySmallString) +TEST(SmallString, small_string_begin_is_not_equal_end_for_non_empty_small_string) { SmallString text("x"); ASSERT_THAT(text.begin(), Ne(text.end())); } -TEST(SmallString, SmallStringBeginPlusOneIsEqualEndForSmallStringWidthSizeOne) +TEST(SmallString, small_string_begin_plus_one_is_equal_end_for_small_string_width_size_one) { SmallString text("x"); @@ -282,21 +282,21 @@ TEST(SmallString, SmallStringBeginPlusOneIsEqualEndForSmallStringWidthSizeOne) ASSERT_THAT(beginPlusOne, Eq(text.end())); } -TEST(SmallString, SmallStringRBeginIsEqualREndForEmptySmallString) +TEST(SmallString, small_string_r_begin_is_equal_r_end_for_empty_small_string) { SmallString text; ASSERT_THAT(text.rbegin(), Eq(text.rend())); } -TEST(SmallString, SmallStringRBeginIsNotEqualREndForNonEmptySmallString) +TEST(SmallString, small_string_r_begin_is_not_equal_r_end_for_non_empty_small_string) { SmallString text("x"); ASSERT_THAT(text.rbegin(), Ne(text.rend())); } -TEST(SmallString, SmallStringRBeginPlusOneIsEqualREndForSmallStringWidthSizeOne) +TEST(SmallString, small_string_r_begin_plus_one_is_equal_r_end_for_small_string_width_size_one) { SmallString text("x"); @@ -305,21 +305,21 @@ TEST(SmallString, SmallStringRBeginPlusOneIsEqualREndForSmallStringWidthSizeOne) ASSERT_THAT(beginPlusOne, Eq(text.rend())); } -TEST(SmallString, SmallStringConstRBeginIsEqualREndForEmptySmallString) +TEST(SmallString, small_string_const_r_begin_is_equal_r_end_for_empty_small_string) { const SmallString text; ASSERT_THAT(text.rbegin(), Eq(text.rend())); } -TEST(SmallString, SmallStringConstRBeginIsNotEqualREndForNonEmptySmallString) +TEST(SmallString, small_string_const_r_begin_is_not_equal_r_end_for_non_empty_small_string) { const SmallString text("x"); ASSERT_THAT(text.rbegin(), Ne(text.rend())); } -TEST(SmallString, SmallStringSmallStringConstRBeginPlusOneIsEqualREndForSmallStringWidthSizeOne) +TEST(SmallString, small_string_small_string_const_r_begin_plus_one_is_equal_r_end_for_small_string_width_size_one) { const SmallString text("x"); @@ -328,7 +328,7 @@ TEST(SmallString, SmallStringSmallStringConstRBeginPlusOneIsEqualREndForSmallStr ASSERT_THAT(beginPlusOne, Eq(text.rend())); } -TEST(SmallString, SmallStringDistanceBetweenBeginAndEndIsZeroForEmptyText) +TEST(SmallString, small_string_distance_between_begin_and_end_is_zero_for_empty_text) { SmallString text(""); @@ -337,7 +337,7 @@ TEST(SmallString, SmallStringDistanceBetweenBeginAndEndIsZeroForEmptyText) ASSERT_THAT(distance, 0); } -TEST(SmallString, SmallStringDistanceBetweenBeginAndEndIsOneForOneSign) +TEST(SmallString, small_string_distance_between_begin_and_end_is_one_for_one_sign) { SmallString text("x"); @@ -346,7 +346,7 @@ TEST(SmallString, SmallStringDistanceBetweenBeginAndEndIsOneForOneSign) ASSERT_THAT(distance, 1); } -TEST(SmallString, SmallStringDistanceBetweenRBeginAndREndIsZeroForEmptyText) +TEST(SmallString, small_string_distance_between_r_begin_and_r_end_is_zero_for_empty_text) { SmallString text(""); @@ -355,7 +355,7 @@ TEST(SmallString, SmallStringDistanceBetweenRBeginAndREndIsZeroForEmptyText) ASSERT_THAT(distance, 0); } -TEST(SmallString, SmallStringDistanceBetweenRBeginAndREndIsOneForOneSign) +TEST(SmallString, small_string_distance_between_r_begin_and_r_end_is_one_for_one_sign) { SmallString text("x"); @@ -364,7 +364,7 @@ TEST(SmallString, SmallStringDistanceBetweenRBeginAndREndIsOneForOneSign) ASSERT_THAT(distance, 1); } -TEST(SmallString, SmallStringBeginPointsToX) +TEST(SmallString, small_string_begin_points_to_x) { SmallString text("x"); @@ -373,7 +373,7 @@ TEST(SmallString, SmallStringBeginPointsToX) ASSERT_THAT(sign, 'x'); } -TEST(SmallString, SmallStringRBeginPointsToX) +TEST(SmallString, small_string_r_begin_points_to_x) { SmallString text("x"); @@ -382,7 +382,7 @@ TEST(SmallString, SmallStringRBeginPointsToX) ASSERT_THAT(sign, 'x'); } -TEST(SmallString, ConstSmallStringBeginPointsToX) +TEST(SmallString, const_small_string_begin_points_to_x) { const SmallString text("x"); @@ -391,7 +391,7 @@ TEST(SmallString, ConstSmallStringBeginPointsToX) ASSERT_THAT(sign, 'x'); } -TEST(SmallString, ConstSmallStringRBeginPointsToX) +TEST(SmallString, const_small_string_r_begin_points_to_x) { const SmallString text("x"); @@ -400,21 +400,21 @@ TEST(SmallString, ConstSmallStringRBeginPointsToX) ASSERT_THAT(sign, 'x'); } -TEST(SmallString, SmallStringViewBeginIsEqualEndForEmptySmallString) +TEST(SmallString, small_string_view_begin_is_equal_end_for_empty_small_string) { SmallStringView text{""}; ASSERT_THAT(text.begin(), Eq(text.end())); } -TEST(SmallString, SmallStringViewBeginIsNotEqualEndForNonEmptySmallString) +TEST(SmallString, small_string_view_begin_is_not_equal_end_for_non_empty_small_string) { SmallStringView text("x"); ASSERT_THAT(text.begin(), Ne(text.end())); } -TEST(SmallString, SmallStringViewBeginPlusOneIsEqualEndForSmallStringWidthSizeOne) +TEST(SmallString, small_string_view_begin_plus_one_is_equal_end_for_small_string_width_size_one) { SmallStringView text("x"); @@ -423,21 +423,21 @@ TEST(SmallString, SmallStringViewBeginPlusOneIsEqualEndForSmallStringWidthSizeOn ASSERT_THAT(beginPlusOne, Eq(text.end())); } -TEST(SmallString, SmallStringViewRBeginIsEqualREndForEmptySmallString) +TEST(SmallString, small_string_view_r_begin_is_equal_r_end_for_empty_small_string) { SmallStringView text{""}; ASSERT_THAT(text.rbegin(), Eq(text.rend())); } -TEST(SmallString, SmallStringViewRBeginIsNotEqualREndForNonEmptySmallString) +TEST(SmallString, small_string_view_r_begin_is_not_equal_r_end_for_non_empty_small_string) { SmallStringView text("x"); ASSERT_THAT(text.rbegin(), Ne(text.rend())); } -TEST(SmallString, SmallStringViewRBeginPlusOneIsEqualREndForSmallStringWidthSizeOne) +TEST(SmallString, small_string_view_r_begin_plus_one_is_equal_r_end_for_small_string_width_size_one) { SmallStringView text("x"); @@ -446,21 +446,21 @@ TEST(SmallString, SmallStringViewRBeginPlusOneIsEqualREndForSmallStringWidthSize ASSERT_THAT(beginPlusOne, Eq(text.rend())); } -TEST(SmallString, SmallStringViewConstRBeginIsEqualREndForEmptySmallString) +TEST(SmallString, small_string_view_const_r_begin_is_equal_r_end_for_empty_small_string) { const SmallStringView text{""}; ASSERT_THAT(text.rbegin(), Eq(text.rend())); } -TEST(SmallString, SmallStringViewConstRBeginIsNotEqualREndForNonEmptySmallString) +TEST(SmallString, small_string_view_const_r_begin_is_not_equal_r_end_for_non_empty_small_string) { const SmallStringView text("x"); ASSERT_THAT(text.rbegin(), Ne(text.rend())); } -TEST(SmallString, SmallStringViewConstRBeginPlusOneIsEqualREndForSmallStringWidthSizeOne) +TEST(SmallString, small_string_view_const_r_begin_plus_one_is_equal_r_end_for_small_string_width_size_one) { const SmallStringView text("x"); @@ -469,7 +469,7 @@ TEST(SmallString, SmallStringViewConstRBeginPlusOneIsEqualREndForSmallStringWidt ASSERT_THAT(beginPlusOne, Eq(text.rend())); } -TEST(SmallString, SmallStringViewDistanceBetweenBeginAndEndIsZeroForEmptyText) +TEST(SmallString, small_string_view_distance_between_begin_and_end_is_zero_for_empty_text) { SmallStringView text(""); @@ -478,7 +478,7 @@ TEST(SmallString, SmallStringViewDistanceBetweenBeginAndEndIsZeroForEmptyText) ASSERT_THAT(distance, 0); } -TEST(SmallString, SmallStringViewDistanceBetweenBeginAndEndIsOneForOneSign) +TEST(SmallString, small_string_view_distance_between_begin_and_end_is_one_for_one_sign) { SmallStringView text("x"); @@ -487,7 +487,7 @@ TEST(SmallString, SmallStringViewDistanceBetweenBeginAndEndIsOneForOneSign) ASSERT_THAT(distance, 1); } -TEST(SmallString, SmallStringViewDistanceBetweenRBeginAndREndIsZeroForEmptyText) +TEST(SmallString, small_string_view_distance_between_r_begin_and_r_end_is_zero_for_empty_text) { SmallStringView text(""); @@ -496,7 +496,7 @@ TEST(SmallString, SmallStringViewDistanceBetweenRBeginAndREndIsZeroForEmptyText) ASSERT_THAT(distance, 0); } -TEST(SmallString, SmallStringViewDistanceBetweenRBeginAndREndIsOneForOneSign) +TEST(SmallString, small_string_view_distance_between_r_begin_and_r_end_is_one_for_one_sign) { SmallStringView text("x"); @@ -505,7 +505,7 @@ TEST(SmallString, SmallStringViewDistanceBetweenRBeginAndREndIsOneForOneSign) ASSERT_THAT(distance, 1); } -TEST(SmallString, ConstSmallStringViewDistanceBetweenBeginAndEndIsZeroForEmptyText) +TEST(SmallString, const_small_string_view_distance_between_begin_and_end_is_zero_for_empty_text) { const SmallStringView text(""); @@ -514,7 +514,7 @@ TEST(SmallString, ConstSmallStringViewDistanceBetweenBeginAndEndIsZeroForEmptyTe ASSERT_THAT(distance, 0); } -TEST(SmallString, ConstSmallStringViewDistanceBetweenBeginAndEndIsOneForOneSign) +TEST(SmallString, const_small_string_view_distance_between_begin_and_end_is_one_for_one_sign) { const SmallStringView text("x"); @@ -523,7 +523,7 @@ TEST(SmallString, ConstSmallStringViewDistanceBetweenBeginAndEndIsOneForOneSign) ASSERT_THAT(distance, 1); } -TEST(SmallString, ConstSmallStringViewDistanceBetweenRBeginAndREndIsZeroForEmptyText) +TEST(SmallString, const_small_string_view_distance_between_r_begin_and_r_end_is_zero_for_empty_text) { const SmallStringView text(""); @@ -532,7 +532,7 @@ TEST(SmallString, ConstSmallStringViewDistanceBetweenRBeginAndREndIsZeroForEmpty ASSERT_THAT(distance, 0); } -TEST(SmallString, ConstSmallStringViewDistanceBetweenRBeginAndREndIsOneForOneSign) +TEST(SmallString, const_small_string_view_distance_between_r_begin_and_r_end_is_one_for_one_sign) { const SmallStringView text("x"); @@ -541,7 +541,7 @@ TEST(SmallString, ConstSmallStringViewDistanceBetweenRBeginAndREndIsOneForOneSig ASSERT_THAT(distance, 1); } -TEST(SmallString, SmallStringViewBeginPointsToX) +TEST(SmallString, small_string_view_begin_points_to_x) { SmallStringView text("x"); @@ -550,7 +550,7 @@ TEST(SmallString, SmallStringViewBeginPointsToX) ASSERT_THAT(sign, 'x'); } -TEST(SmallString, SmallStringViewRBeginPointsToX) +TEST(SmallString, small_string_view_r_begin_points_to_x) { SmallStringView text("x"); @@ -559,7 +559,7 @@ TEST(SmallString, SmallStringViewRBeginPointsToX) ASSERT_THAT(sign, 'x'); } -TEST(SmallString, ConstSmallStringViewBeginPointsToX) +TEST(SmallString, const_small_string_view_begin_points_to_x) { const SmallStringView text("x"); @@ -568,7 +568,7 @@ TEST(SmallString, ConstSmallStringViewBeginPointsToX) ASSERT_THAT(sign, 'x'); } -TEST(SmallString, ConstSmallStringViewRBeginPointsToX) +TEST(SmallString, const_small_string_view_r_begin_points_to_x) { const SmallStringView text("x"); @@ -577,7 +577,7 @@ TEST(SmallString, ConstSmallStringViewRBeginPointsToX) ASSERT_THAT(sign, 'x'); } -TEST(SmallString, SmallStringLiteralViewRBeginPointsToX) +TEST(SmallString, small_string_literal_view_r_begin_points_to_x) { SmallStringLiteral text("x"); @@ -586,7 +586,7 @@ TEST(SmallString, SmallStringLiteralViewRBeginPointsToX) ASSERT_THAT(sign, 'x'); } -TEST(SmallString, ConstSmallStringLiteralViewRBeginPointsToX) +TEST(SmallString, const_small_string_literal_view_r_begin_points_to_x) { const SmallStringLiteral text("x"); @@ -595,7 +595,7 @@ TEST(SmallString, ConstSmallStringLiteralViewRBeginPointsToX) ASSERT_THAT(sign, 'x'); } -TEST(SmallString, ConstructorStandardString) +TEST(SmallString, constructor_standard_string) { std::string stdStringText = "short string"; @@ -604,7 +604,7 @@ TEST(SmallString, ConstructorStandardString) ASSERT_THAT(text, SmallString("short string")); } -TEST(SmallString, ToQString) +TEST(SmallString, to_q_string) { SmallString text("short string"); @@ -613,7 +613,7 @@ TEST(SmallString, ToQString) ASSERT_THAT(qStringText, QStringLiteral("short string")); } -TEST(SmallString, FromQString) +TEST(SmallString, from_q_string) { QString qStringText = QStringLiteral("short string"); @@ -623,7 +623,7 @@ TEST(SmallString, FromQString) } -TEST(SmallString, FromQByteArray) +TEST(SmallString, from_q_byte_array) { QByteArray qByteArray = QByteArrayLiteral("short string"); @@ -632,7 +632,7 @@ TEST(SmallString, FromQByteArray) ASSERT_THAT(text, SmallString("short string")); } -TEST(SmallString, MidOneParameter) +TEST(SmallString, mid_one_parameter) { SmallString text("some text"); @@ -641,7 +641,7 @@ TEST(SmallString, MidOneParameter) ASSERT_THAT(midString, Eq(SmallString("text"))); } -TEST(SmallString, MidTwoParameter) +TEST(SmallString, mid_two_parameter) { SmallString text("some text and more"); @@ -650,7 +650,7 @@ TEST(SmallString, MidTwoParameter) ASSERT_THAT(midString, Eq(SmallString("text"))); } -TEST(SmallString, SmallStringViewMidOneParameter) +TEST(SmallString, small_string_view_mid_one_parameter) { SmallStringView text("some text"); @@ -659,7 +659,7 @@ TEST(SmallString, SmallStringViewMidOneParameter) ASSERT_THAT(midString, Eq(SmallStringView("text"))); } -TEST(SmallString, SmallStringViewMidTwoParameter) +TEST(SmallString, small_string_view_mid_two_parameter) { SmallStringView text("some text and more"); @@ -668,7 +668,7 @@ TEST(SmallString, SmallStringViewMidTwoParameter) ASSERT_THAT(midString, Eq(SmallStringView("text"))); } -TEST(SmallString, SizeOfEmptyStringl) +TEST(SmallString, size_of_empty_stringl) { SmallString emptyString; @@ -677,7 +677,7 @@ TEST(SmallString, SizeOfEmptyStringl) ASSERT_THAT(size, 0); } -TEST(SmallString, SizeShortSmallStringLiteral) +TEST(SmallString, size_short_small_string_literal) { SmallStringLiteral shortText("text"); @@ -686,7 +686,7 @@ TEST(SmallString, SizeShortSmallStringLiteral) ASSERT_THAT(size, 4); } -TEST(SmallString, SizeLongSmallStringLiteral) +TEST(SmallString, size_long_small_string_literal) { auto longText = SmallStringLiteral("very very very very very very very very very very very long string"); @@ -695,7 +695,7 @@ TEST(SmallString, SizeLongSmallStringLiteral) ASSERT_THAT(size, 66); } -TEST(SmallString, SizeReference) +TEST(SmallString, size_reference) { SmallString shortText("text"); @@ -704,7 +704,7 @@ TEST(SmallString, SizeReference) ASSERT_THAT(size, 4); } -TEST(SmallString, SizeShortSmallString) +TEST(SmallString, size_short_small_string) { SmallString shortText("text", 4); @@ -713,7 +713,7 @@ TEST(SmallString, SizeShortSmallString) ASSERT_THAT(size, 4); } -TEST(SmallString, SizeShortPathString) +TEST(SmallString, size_short_path_string) { SmallString shortPath("very very very very very very very very very very very long path which fits in the short memory"); @@ -722,7 +722,7 @@ TEST(SmallString, SizeShortPathString) ASSERT_THAT(size, 95); } -TEST(SmallString, SizeLongSmallString) +TEST(SmallString, size_long_small_string) { auto longText = SmallString::fromUtf8("very very very very very very very very very very very long string"); @@ -731,7 +731,7 @@ TEST(SmallString, SizeLongSmallString) ASSERT_THAT(size, 66); } -TEST(SmallString, CapacityReference) +TEST(SmallString, capacity_reference) { SmallString shortText("very very very very very very very long string"); @@ -740,7 +740,7 @@ TEST(SmallString, CapacityReference) ASSERT_THAT(capacity, 0); } -TEST(SmallString, CapacityShortSmallString) +TEST(SmallString, capacity_short_small_string) { SmallString shortText("text", 4); @@ -749,7 +749,7 @@ TEST(SmallString, CapacityShortSmallString) ASSERT_THAT(capacity, 31); } -TEST(SmallString, CapacityLongSmallString) +TEST(SmallString, capacity_long_small_string) { auto longText = SmallString::fromUtf8("very very very very very very very very very very very long string"); @@ -758,49 +758,49 @@ TEST(SmallString, CapacityLongSmallString) ASSERT_THAT(capacity, 66); } -TEST(SmallString, FitsNotInCapacityBecauseNullSmallStringIsAShortSmallString) +TEST(SmallString, fits_not_in_capacity_because_null_small_string_is_a_short_small_string) { SmallString text; ASSERT_FALSE(text.fitsNotInCapacity(30)); } -TEST(SmallString, FitsNotInCapacityBecauseItIsReference) +TEST(SmallString, fits_not_in_capacity_because_it_is_reference) { SmallString text("very very very very very very very long string"); ASSERT_TRUE(text.fitsNotInCapacity(1)); } -TEST(SmallString, FitsInShortSmallStringCapacity) +TEST(SmallString, fits_in_short_small_string_capacity) { SmallString text("text", 4); ASSERT_FALSE(text.fitsNotInCapacity(30)); } -TEST(SmallString, FitsInNotShortSmallStringCapacity) +TEST(SmallString, fits_in_not_short_small_string_capacity) { SmallString text("text", 4); ASSERT_TRUE(text.fitsNotInCapacity(32)); } -TEST(SmallString, FitsInLongSmallStringCapacity) +TEST(SmallString, fits_in_long_small_string_capacity) { SmallString text = SmallString::fromUtf8("very very very very very very long string"); ASSERT_FALSE(text.fitsNotInCapacity(33)) << text.capacity(); } -TEST(SmallString, FitsNotInLongSmallStringCapacity) +TEST(SmallString, fits_not_in_long_small_string_capacity) { SmallString text = SmallString::fromUtf8("very very very very very very long string"); ASSERT_TRUE(text.fitsNotInCapacity(65)) << text.capacity(); } -TEST(SmallString, AppendNullSmallString) +TEST(SmallString, append_null_small_string) { SmallString text("text"); @@ -809,7 +809,7 @@ TEST(SmallString, AppendNullSmallString) ASSERT_THAT(text, SmallString("text")); } -TEST(SmallString, AppendNullQString) +TEST(SmallString, append_null_q_string) { SmallString text("text"); @@ -818,7 +818,7 @@ TEST(SmallString, AppendNullQString) ASSERT_THAT(text, SmallString("text")); } -TEST(SmallString, AppendEmptySmallString) +TEST(SmallString, append_empty_small_string) { SmallString text("text"); @@ -827,7 +827,7 @@ TEST(SmallString, AppendEmptySmallString) ASSERT_THAT(text, SmallString("text")); } -TEST(SmallString, AppendEmptyQString) +TEST(SmallString, append_empty_q_string) { SmallString text("text"); @@ -836,7 +836,7 @@ TEST(SmallString, AppendEmptyQString) ASSERT_THAT(text, SmallString("text")); } -TEST(SmallString, AppendShortSmallString) +TEST(SmallString, append_short_small_string) { SmallString text("some "); @@ -845,7 +845,7 @@ TEST(SmallString, AppendShortSmallString) ASSERT_THAT(text, SmallString("some text")); } -TEST(SmallString, AppendShortQString) +TEST(SmallString, append_short_q_string) { SmallString text("some "); @@ -854,7 +854,7 @@ TEST(SmallString, AppendShortQString) ASSERT_THAT(text, SmallString("some text")); } -TEST(SmallString, AppendLongSmallStringToShortSmallString) +TEST(SmallString, append_long_small_string_to_short_small_string) { SmallString text("some "); @@ -863,7 +863,7 @@ TEST(SmallString, AppendLongSmallStringToShortSmallString) ASSERT_THAT(text, SmallString("some very very very very very long string")); } -TEST(SmallString, AppendLongQStringToShortSmallString) +TEST(SmallString, append_long_q_string_to_short_small_string) { SmallString text("some "); @@ -872,7 +872,7 @@ TEST(SmallString, AppendLongQStringToShortSmallString) ASSERT_THAT(text, SmallString("some very very very very very long string")); } -TEST(SmallString, AppendLongSmallString) +TEST(SmallString, append_long_small_string) { SmallString longText("some very very very very very very very very very very very long string"); @@ -881,7 +881,7 @@ TEST(SmallString, AppendLongSmallString) ASSERT_THAT(longText, SmallString("some very very very very very very very very very very very long string text")); } -TEST(SmallString, AppendLongQString) +TEST(SmallString, append_long_q_string) { SmallString longText("some very very very very very very very very very very very long string"); @@ -893,7 +893,7 @@ TEST(SmallString, AppendLongQString) "some very very very very very very very very very very very long string text")); } -TEST(SmallString, AppendInitializerList) +TEST(SmallString, append_initializer_list) { SmallString text("some text"); @@ -902,7 +902,7 @@ TEST(SmallString, AppendInitializerList) ASSERT_THAT(text, Eq("some text and some other text")); } -TEST(SmallString, AppendEmptyInitializerList) +TEST(SmallString, append_empty_initializer_list) { SmallString text("some text"); @@ -911,14 +911,14 @@ TEST(SmallString, AppendEmptyInitializerList) ASSERT_THAT(text, Eq("some text")); } -TEST(SmallString, ToByteArray) +TEST(SmallString, to_byte_array) { SmallString text("some text"); ASSERT_THAT(text.toQByteArray(), QByteArrayLiteral("some text")); } -TEST(SmallString, Contains) +TEST(SmallString, contains) { SmallString text("some text"); @@ -927,7 +927,7 @@ TEST(SmallString, Contains) ASSERT_TRUE(text.contains('x')); } -TEST(SmallString, NotContains) +TEST(SmallString, not_contains) { SmallString text("some text"); @@ -936,7 +936,7 @@ TEST(SmallString, NotContains) ASSERT_FALSE(text.contains('q')); } -TEST(SmallString, EqualSmallStringOperator) +TEST(SmallString, equal_small_string_operator) { ASSERT_TRUE(SmallString() == SmallString("")); ASSERT_FALSE(SmallString() == SmallString("text")); @@ -944,7 +944,7 @@ TEST(SmallString, EqualSmallStringOperator) ASSERT_FALSE(SmallString("text") == SmallString("text2")); } -TEST(SmallString, EqualSmallStringOperatorWithDifferenceClassSizes) +TEST(SmallString, equal_small_string_operator_with_difference_class_sizes) { ASSERT_TRUE(SmallString() == PathString("")); ASSERT_FALSE(SmallString() == PathString("text")); @@ -952,7 +952,7 @@ TEST(SmallString, EqualSmallStringOperatorWithDifferenceClassSizes) ASSERT_FALSE(SmallString("text") == PathString("text2")); } -TEST(SmallString, EqualCStringArrayOperator) +TEST(SmallString, equal_c_string_array_operator) { ASSERT_TRUE(SmallString() == ""); ASSERT_FALSE(SmallString() == "text"); @@ -960,55 +960,55 @@ TEST(SmallString, EqualCStringArrayOperator) ASSERT_FALSE(SmallString("text") == "text2"); } -TEST(SmallString, EqualCStringPointerOperator) +TEST(SmallString, equal_c_string_pointer_operator) { ASSERT_TRUE(SmallString("text") == std::string("text").data()); ASSERT_FALSE(SmallString("text") == std::string("text2").data()); } -TEST(SmallString, EqualSmallStringViewOperator) +TEST(SmallString, equal_small_string_view_operator) { ASSERT_TRUE(SmallString("text") == SmallStringView("text")); ASSERT_FALSE(SmallString("text") == SmallStringView("text2")); } -TEST(SmallString, EqualSmallStringViewsOperator) +TEST(SmallString, equal_small_string_views_operator) { ASSERT_TRUE(SmallStringView("text") == SmallStringView("text")); ASSERT_FALSE(SmallStringView("text") == SmallStringView("text2")); } -TEST(SmallString, UnequalOperator) +TEST(SmallString, unequal_operator) { ASSERT_FALSE(SmallString("text") != SmallString("text")); ASSERT_TRUE(SmallString("text") != SmallString("text2")); } -TEST(SmallString, UnequalCStringArrayOperator) +TEST(SmallString, unequal_c_string_array_operator) { ASSERT_FALSE(SmallString("text") != "text"); ASSERT_TRUE(SmallString("text") != "text2"); } -TEST(SmallString, UnequalCStringPointerOperator) +TEST(SmallString, unequal_c_string_pointer_operator) { ASSERT_FALSE(SmallString("text") != std::string("text").data()); ASSERT_TRUE(SmallString("text") != std::string("text2").data()); } -TEST(SmallString, UnequalSmallStringViewArrayOperator) +TEST(SmallString, unequal_small_string_view_array_operator) { ASSERT_FALSE(SmallString("text") != SmallStringView("text")); ASSERT_TRUE(SmallString("text") != SmallStringView("text2")); } -TEST(SmallString, UnequalSmallStringViewsArrayOperator) +TEST(SmallString, unequal_small_string_views_array_operator) { ASSERT_FALSE(SmallStringView("text") != SmallStringView("text")); ASSERT_TRUE(SmallStringView("text") != SmallStringView("text2")); } -TEST(SmallString, SmallerOperator) +TEST(SmallString, smaller_operator) { ASSERT_TRUE(SmallString() < SmallString("text")); ASSERT_TRUE(SmallString("some") < SmallString("text")); @@ -1018,7 +1018,7 @@ TEST(SmallString, SmallerOperator) ASSERT_FALSE(SmallString("text") < SmallString("text")); } -TEST(SmallString, SmallerOperatorWithStringViewRight) +TEST(SmallString, smaller_operator_with_string_view_right) { ASSERT_TRUE(SmallString() < SmallStringView("text")); ASSERT_TRUE(SmallString("some") < SmallStringView("text")); @@ -1028,7 +1028,7 @@ TEST(SmallString, SmallerOperatorWithStringViewRight) ASSERT_FALSE(SmallString("text") < SmallStringView("text")); } -TEST(SmallString, SmallerOperatorWithStringViewLeft) +TEST(SmallString, smaller_operator_with_string_view_left) { ASSERT_TRUE(SmallStringView("") < SmallString("text")); ASSERT_TRUE(SmallStringView("some") < SmallString("text")); @@ -1038,7 +1038,7 @@ TEST(SmallString, SmallerOperatorWithStringViewLeft) ASSERT_FALSE(SmallStringView("text") < SmallString("text")); } -TEST(SmallString, SmallerOperatorForDifferenceClassSizes) +TEST(SmallString, smaller_operator_for_difference_class_sizes) { ASSERT_TRUE(SmallString() < PathString("text")); ASSERT_TRUE(SmallString("some") < PathString("text")); @@ -1048,33 +1048,33 @@ TEST(SmallString, SmallerOperatorForDifferenceClassSizes) ASSERT_FALSE(SmallString("text") < PathString("text")); } -TEST(SmallString, IsEmpty) +TEST(SmallString, is_empty) { ASSERT_FALSE(SmallString("text").isEmpty()); ASSERT_TRUE(SmallString("").isEmpty()); ASSERT_TRUE(SmallString().isEmpty()); } -TEST(SmallString, StringViewIsEmpty) +TEST(SmallString, string_view_is_empty) { ASSERT_FALSE(SmallStringView("text").isEmpty()); ASSERT_TRUE(SmallStringView("").isEmpty()); } -TEST(SmallString, StringViewEmpty) +TEST(SmallString, string_view_empty) { ASSERT_FALSE(SmallStringView("text").empty()); ASSERT_TRUE(SmallStringView("").empty()); } -TEST(SmallString, HasContent) +TEST(SmallString, has_content) { ASSERT_TRUE(SmallString("text").hasContent()); ASSERT_FALSE(SmallString("").hasContent()); ASSERT_FALSE(SmallString().hasContent()); } -TEST(SmallString, Clear) +TEST(SmallString, clear) { SmallString text("text"); @@ -1083,7 +1083,7 @@ TEST(SmallString, Clear) ASSERT_TRUE(text.isEmpty()); } -TEST(SmallString, NoOccurrencesForEmptyText) +TEST(SmallString, no_occurrences_for_empty_text) { SmallString text; @@ -1092,7 +1092,7 @@ TEST(SmallString, NoOccurrencesForEmptyText) ASSERT_THAT(occurrences, 0); } -TEST(SmallString, NoOccurrencesInText) +TEST(SmallString, no_occurrences_in_text) { SmallString text("here is some text, here is some text, here is some text"); @@ -1101,7 +1101,7 @@ TEST(SmallString, NoOccurrencesInText) ASSERT_THAT(occurrences, 0); } -TEST(SmallString, SomeOccurrences) +TEST(SmallString, some_occurrences) { SmallString text("here is some text, here is some text, here is some text"); @@ -1110,7 +1110,7 @@ TEST(SmallString, SomeOccurrences) ASSERT_THAT(occurrences, 3); } -TEST(SmallString, SomeMoreOccurrences) +TEST(SmallString, some_more_occurrences) { SmallString text("texttexttext"); @@ -1119,7 +1119,7 @@ TEST(SmallString, SomeMoreOccurrences) ASSERT_THAT(occurrences, 3); } -TEST(SmallString, ReplaceWithCharacter) +TEST(SmallString, replace_with_character) { SmallString text("here is some text, here is some text, here is some text"); @@ -1128,7 +1128,7 @@ TEST(SmallString, ReplaceWithCharacter) ASSERT_THAT(text, SmallString("here ix xome text, here ix xome text, here ix xome text")); } -TEST(SmallString, ReplaceWithEqualSizedText) +TEST(SmallString, replace_with_equal_sized_text) { SmallString text("here is some text"); @@ -1137,7 +1137,7 @@ TEST(SmallString, ReplaceWithEqualSizedText) ASSERT_THAT(text, SmallString("here is much text")); } -TEST(SmallString, ReplaceWithEqualSizedTextOnEmptyText) +TEST(SmallString, replace_with_equal_sized_text_on_empty_text) { SmallString text; @@ -1146,7 +1146,7 @@ TEST(SmallString, ReplaceWithEqualSizedTextOnEmptyText) ASSERT_THAT(text, SmallString()); } -TEST(SmallString, ReplaceWithShorterText) +TEST(SmallString, replace_with_shorter_text) { SmallString text("here is some text"); @@ -1155,7 +1155,7 @@ TEST(SmallString, ReplaceWithShorterText) ASSERT_THAT(text, SmallString("here is any text")); } -TEST(SmallString, ReplaceWithShorterTextOnEmptyText) +TEST(SmallString, replace_with_shorter_text_on_empty_text) { SmallString text; @@ -1164,7 +1164,7 @@ TEST(SmallString, ReplaceWithShorterTextOnEmptyText) ASSERT_THAT(text, SmallString()); } -TEST(SmallString, ReplaceWithLongerText) +TEST(SmallString, replace_with_longer_text) { SmallString text("here is some text"); @@ -1173,7 +1173,7 @@ TEST(SmallString, ReplaceWithLongerText) ASSERT_THAT(text, SmallString("here is much more text")); } -TEST(SmallString, ReplaceWithLongerTextOnEmptyText) +TEST(SmallString, replace_with_longer_text_on_empty_text) { SmallString text; @@ -1182,7 +1182,7 @@ TEST(SmallString, ReplaceWithLongerTextOnEmptyText) ASSERT_THAT(text, SmallString()); } -TEST(SmallString, ReplaceShortSmallStringWithLongerText) +TEST(SmallString, replace_short_small_string_with_longer_text) { SmallString text = SmallString::fromUtf8("here is some text"); @@ -1191,7 +1191,7 @@ TEST(SmallString, ReplaceShortSmallStringWithLongerText) ASSERT_THAT(text, SmallString("here is much more text")); } -TEST(SmallString, ReplaceLongSmallStringWithLongerText) +TEST(SmallString, replace_long_small_string_with_longer_text) { SmallString text = SmallString::fromUtf8("some very very very very very very very very very very very long string"); @@ -1200,7 +1200,7 @@ TEST(SmallString, ReplaceLongSmallStringWithLongerText) ASSERT_THAT(text, "some very very very very very very very very very very very much much much much much much much much much much much much much much much much much much more string"); } -TEST(SmallString, MultipleReplaceSmallStringWithLongerText) +TEST(SmallString, multiple_replace_small_string_with_longer_text) { SmallString text = SmallString("here is some text with some longer text"); @@ -1209,7 +1209,7 @@ TEST(SmallString, MultipleReplaceSmallStringWithLongerText) ASSERT_THAT(text, SmallString("here is much more text with much more longer text")); } -TEST(SmallString, MultipleReplaceSmallStringWithShorterText) +TEST(SmallString, multiple_replace_small_string_with_shorter_text) { SmallString text = SmallString("here is some text with some longer text"); @@ -1218,7 +1218,7 @@ TEST(SmallString, MultipleReplaceSmallStringWithShorterText) ASSERT_THAT(text, SmallString("here is a text with a longer text")); } -TEST(SmallString, DontReplaceReplacedText) +TEST(SmallString, dont_replace_replaced_text) { SmallString text("here is some foo text"); @@ -1227,7 +1227,7 @@ TEST(SmallString, DontReplaceReplacedText) ASSERT_THAT(text, SmallString("here is some foofoo text")); } -TEST(SmallString, DontReserveIfNothingIsReplacedForLongerReplacementText) +TEST(SmallString, dont_reserve_if_nothing_is_replaced_for_longer_replacement_text) { SmallString text("here is some text with some longer text"); @@ -1236,7 +1236,7 @@ TEST(SmallString, DontReserveIfNothingIsReplacedForLongerReplacementText) ASSERT_TRUE(text.isReadOnlyReference()); } -TEST(SmallString, DontReserveIfNothingIsReplacedForShorterReplacementText) +TEST(SmallString, dont_reserve_if_nothing_is_replaced_for_shorter_replacement_text) { SmallString text("here is some text with some longer text"); @@ -1245,7 +1245,7 @@ TEST(SmallString, DontReserveIfNothingIsReplacedForShorterReplacementText) ASSERT_TRUE(text.isReadOnlyReference()); } -TEST(SmallString, StartsWith) +TEST(SmallString, starts_with) { SmallString text("$column"); @@ -1257,7 +1257,7 @@ TEST(SmallString, StartsWith) ASSERT_FALSE(text.startsWith('@')); } -TEST(SmallString, StartsWithStringView) +TEST(SmallString, starts_with_string_view) { SmallStringView text("$column"); @@ -1269,7 +1269,7 @@ TEST(SmallString, StartsWithStringView) ASSERT_FALSE(text.startsWith('@')); } -TEST(SmallString, EndsWith) +TEST(SmallString, ends_with) { SmallString text("/my/path"); @@ -1280,7 +1280,7 @@ TEST(SmallString, EndsWith) ASSERT_FALSE(text.endsWith('x')); } -TEST(SmallString, EndsWithStringView) +TEST(SmallString, ends_with_string_view) { SmallStringView text("/my/path"); @@ -1289,7 +1289,7 @@ TEST(SmallString, EndsWithStringView) ASSERT_FALSE(text.endsWith("paths")); } -TEST(SmallString, EndsWithSmallString) +TEST(SmallString, ends_with_small_string) { SmallString text("/my/path"); @@ -1297,7 +1297,7 @@ TEST(SmallString, EndsWithSmallString) ASSERT_TRUE(text.endsWith('h')); } -TEST(SmallString, ReserveSmallerThanShortStringCapacity) +TEST(SmallString, reserve_smaller_than_short_string_capacity) { SmallString text("text"); @@ -1306,7 +1306,7 @@ TEST(SmallString, ReserveSmallerThanShortStringCapacity) ASSERT_THAT(text.capacity(), 31); } -TEST(SmallString, ReserveSmallerThanShortStringCapacityIsShortString) +TEST(SmallString, reserve_smaller_than_short_string_capacity_is_short_string) { SmallString text("text"); @@ -1315,7 +1315,7 @@ TEST(SmallString, ReserveSmallerThanShortStringCapacityIsShortString) ASSERT_TRUE(text.isShortString()); } -TEST(SmallString, ReserveSmallerThanReference) +TEST(SmallString, reserve_smaller_than_reference) { SmallString text("some very very very very very very very very very very very long string"); @@ -1324,7 +1324,7 @@ TEST(SmallString, ReserveSmallerThanReference) ASSERT_THAT(text.capacity(), 71); } -TEST(SmallString, ReserveBiggerThanShortStringCapacity) +TEST(SmallString, reserve_bigger_than_short_string_capacity) { SmallString text("text"); @@ -1333,7 +1333,7 @@ TEST(SmallString, ReserveBiggerThanShortStringCapacity) ASSERT_THAT(text.capacity(), 31); } -TEST(SmallString, ReserveBiggerThanReference) +TEST(SmallString, reserve_bigger_than_reference) { SmallString text("some very very very very very very very very very very very long string"); @@ -1342,7 +1342,7 @@ TEST(SmallString, ReserveBiggerThanReference) ASSERT_THAT(text.capacity(), 71); } -TEST(SmallString, ReserveMuchBiggerThanShortStringCapacity) +TEST(SmallString, reserve_much_bigger_than_short_string_capacity) { SmallString text("text"); @@ -1351,7 +1351,7 @@ TEST(SmallString, ReserveMuchBiggerThanShortStringCapacity) ASSERT_THAT(text.capacity(), 100); } -TEST(SmallString, TextIsCopiedAfterReserveFromShortToLongString) +TEST(SmallString, text_is_copied_after_reserve_from_short_to_long_string) { SmallString text("text"); @@ -1360,7 +1360,7 @@ TEST(SmallString, TextIsCopiedAfterReserveFromShortToLongString) ASSERT_THAT(text, "text"); } -TEST(SmallString, TextIsCopiedAfterReserveReferenceToLongString) +TEST(SmallString, text_is_copied_after_reserve_reference_to_long_string) { SmallString text("some very very very very very very very very very very very long string"); @@ -1369,7 +1369,7 @@ TEST(SmallString, TextIsCopiedAfterReserveReferenceToLongString) ASSERT_THAT(text, "some very very very very very very very very very very very long string"); } -TEST(SmallString, ReserveSmallerThanShortSmallString) +TEST(SmallString, reserve_smaller_than_short_small_string) { SmallString text = SmallString::fromUtf8("text"); @@ -1378,7 +1378,7 @@ TEST(SmallString, ReserveSmallerThanShortSmallString) ASSERT_THAT(text.capacity(), 31); } -TEST(SmallString, ReserveBiggerThanShortSmallString) +TEST(SmallString, reserve_bigger_than_short_small_string) { SmallString text = SmallString::fromUtf8("text"); @@ -1387,7 +1387,7 @@ TEST(SmallString, ReserveBiggerThanShortSmallString) ASSERT_THAT(text.capacity(), 100); } -TEST(SmallString, ReserveBiggerThanLongSmallString) +TEST(SmallString, reserve_bigger_than_long_small_string) { SmallString text = SmallString::fromUtf8("some very very very very very very very very very very very long string"); @@ -1396,7 +1396,7 @@ TEST(SmallString, ReserveBiggerThanLongSmallString) ASSERT_THAT(text.capacity(), 100); } -TEST(SmallString, OptimalHeapCacheLineForSize) +TEST(SmallString, optimal_heap_cache_line_for_size) { ASSERT_THAT(SmallString::optimalHeapCapacity(64), 64); ASSERT_THAT(SmallString::optimalHeapCapacity(65), 128); @@ -1415,7 +1415,7 @@ TEST(SmallString, OptimalHeapCacheLineForSize) ASSERT_THAT(SmallString::optimalHeapCapacity(4097), 4160); } -TEST(SmallString, OptimalCapacityForSize) +TEST(SmallString, optimal_capacity_for_size) { SmallString text; @@ -1427,7 +1427,7 @@ TEST(SmallString, OptimalCapacityForSize) ASSERT_THAT(text.optimalCapacity(129), 192); } -TEST(SmallString, DataStreamData) +TEST(SmallString, data_stream_data) { SmallString inputText("foo"); QByteArray byteArray; @@ -1438,7 +1438,7 @@ TEST(SmallString, DataStreamData) ASSERT_TRUE(byteArray.endsWith("foo")); } -TEST(SmallString, ReadDataStreamSize) +TEST(SmallString, read_data_stream_size) { SmallString outputText("foo"); QByteArray byteArray; @@ -1454,7 +1454,7 @@ TEST(SmallString, ReadDataStreamSize) ASSERT_THAT(size, 3); } -TEST(SmallString, ReadDataStreamData) +TEST(SmallString, read_data_stream_data) { SmallString outputText("foo"); QByteArray byteArray; @@ -1470,7 +1470,7 @@ TEST(SmallString, ReadDataStreamData) ASSERT_THAT(outputString, SmallString("foo")); } -TEST(SmallString, ShortSmallStringCopyConstuctor) +TEST(SmallString, short_small_string_copy_constuctor) { SmallString text("text"); @@ -1479,7 +1479,7 @@ TEST(SmallString, ShortSmallStringCopyConstuctor) ASSERT_THAT(copy, text); } -TEST(SmallString, LongSmallStringCopyConstuctor) +TEST(SmallString, long_small_string_copy_constuctor) { SmallString text("this is a very very very very long text"); @@ -1488,7 +1488,7 @@ TEST(SmallString, LongSmallStringCopyConstuctor) ASSERT_THAT(copy, text); } -TEST(SmallString, ShortSmallStringMoveConstuctor) +TEST(SmallString, short_small_string_move_constuctor) { SmallString text("text"); @@ -1497,7 +1497,7 @@ TEST(SmallString, ShortSmallStringMoveConstuctor) ASSERT_THAT(copy, SmallString("text")); } -TEST(SmallString, LongSmallStringMoveConstuctor) +TEST(SmallString, long_small_string_move_constuctor) { SmallString text("this is a very very very very long text"); @@ -1506,7 +1506,7 @@ TEST(SmallString, LongSmallStringMoveConstuctor) ASSERT_THAT(copy, SmallString("this is a very very very very long text")); } -TEST(SmallString, ShortPathStringMoveConstuctor) +TEST(SmallString, short_path_string_move_constuctor) { PathString text("text"); @@ -1515,7 +1515,7 @@ TEST(SmallString, ShortPathStringMoveConstuctor) ASSERT_THAT(copy, SmallString("text")); } -TEST(SmallString, LongPathStringMoveConstuctor) +TEST(SmallString, long_path_string_move_constuctor) { PathString text( "this is a very very very very very very very very very very very very very very very very " @@ -1538,7 +1538,7 @@ QT_WARNING_DISABLE_GCC("-Wpragmas") QT_WARNING_DISABLE_GCC("-Wself-move") QT_WARNING_DISABLE_CLANG("-Wself-move") -TEST(SmallString, ShortSmallStringMoveConstuctorToSelf) +TEST(SmallString, short_small_string_move_constuctor_to_self) { SmallString text("text"); @@ -1547,7 +1547,7 @@ TEST(SmallString, ShortSmallStringMoveConstuctorToSelf) ASSERT_THAT(text, SmallString("text")); } -TEST(SmallString, LongSmallStringMoveConstuctorToSelf) +TEST(SmallString, long_small_string_move_constuctor_to_self) { SmallString text("this is a very very very very long text"); @@ -1556,7 +1556,7 @@ TEST(SmallString, LongSmallStringMoveConstuctorToSelf) ASSERT_THAT(text, SmallString("this is a very very very very long text")); } -TEST(SmallString, ShortPathStringMoveConstuctorToSelf) +TEST(SmallString, short_path_string_move_constuctor_to_self) { PathString text("text"); @@ -1565,7 +1565,7 @@ TEST(SmallString, ShortPathStringMoveConstuctorToSelf) ASSERT_THAT(text, SmallString("text")); } -TEST(SmallString, LongPathStringMoveConstuctorToSelf) +TEST(SmallString, long_path_string_move_constuctor_to_self) { PathString text( "this is a very very very very very very very very very very very very very very very very " @@ -1585,7 +1585,7 @@ TEST(SmallString, LongPathStringMoveConstuctorToSelf) QT_WARNING_POP -TEST(SmallString, ShortSmallStringCopyAssignment) +TEST(SmallString, short_small_string_copy_assignment) { SmallString text("text"); SmallString copy("more text"); @@ -1595,7 +1595,7 @@ TEST(SmallString, ShortSmallStringCopyAssignment) ASSERT_THAT(copy, text); } -TEST(SmallString, LongSmallStringCopyAssignment) +TEST(SmallString, long_small_string_copy_assignment) { SmallString text("this is a very very very very long text"); SmallString copy("more text"); @@ -1610,7 +1610,7 @@ TEST(SmallString, LongSmallStringCopyAssignment) #pragma clang diagnostic ignored "-Wself-assign-overloaded" #endif -TEST(SmallString, LongSmallStringCopySelfAssignment) +TEST(SmallString, long_small_string_copy_self_assignment) { SmallString text("this is a very very very very long text"); @@ -1623,7 +1623,7 @@ TEST(SmallString, LongSmallStringCopySelfAssignment) #pragma clang diagnostic pop #endif -TEST(SmallString, ShortSmallStringMoveAssignment) +TEST(SmallString, short_small_string_move_assignment) { SmallString text("text"); SmallString copy("more text"); @@ -1633,7 +1633,7 @@ TEST(SmallString, ShortSmallStringMoveAssignment) ASSERT_THAT(copy, SmallString("text")); } -TEST(SmallString, LongSmallStringMoveAssignment) +TEST(SmallString, long_small_string_move_assignment) { SmallString text("this is a very very very very long text"); SmallString copy("more text"); @@ -1643,7 +1643,7 @@ TEST(SmallString, LongSmallStringMoveAssignment) ASSERT_THAT(copy, SmallString("this is a very very very very long text")); } -TEST(SmallString, ShortPathStringMoveAssignment) +TEST(SmallString, short_path_string_move_assignment) { PathString text("text"); PathString copy("more text"); @@ -1653,7 +1653,7 @@ TEST(SmallString, ShortPathStringMoveAssignment) ASSERT_THAT(copy, SmallString("text")); } -TEST(SmallString, LongPathStringMoveAssignment) +TEST(SmallString, long_path_string_move_assignment) { PathString text( "this is a very very very very very very very very very very very very very very very very " @@ -1672,7 +1672,7 @@ TEST(SmallString, LongPathStringMoveAssignment) "text")); } -TEST(SmallString, ShortSmallStringTake) +TEST(SmallString, short_small_string_take) { SmallString text("text"); SmallString copy("more text"); @@ -1683,7 +1683,7 @@ TEST(SmallString, ShortSmallStringTake) ASSERT_THAT(copy, SmallString("text")); } -TEST(SmallString, LongSmallStringTake) +TEST(SmallString, long_small_string_take) { SmallString text("this is a very very very very long text"); SmallString copy("more text"); @@ -1694,7 +1694,7 @@ TEST(SmallString, LongSmallStringTake) ASSERT_THAT(copy, SmallString("this is a very very very very long text")); } -TEST(SmallString, ReplaceByPositionShorterWithLongerText) +TEST(SmallString, replace_by_position_shorter_with_longer_text) { SmallString text("this is a very very very very long text"); @@ -1703,7 +1703,7 @@ TEST(SmallString, ReplaceByPositionShorterWithLongerText) ASSERT_THAT(text, SmallString("this is some very very very very long text")); } -TEST(SmallString, ReplaceByPositionLongerWithShortText) +TEST(SmallString, replace_by_position_longer_with_short_text) { SmallString text("this is some very very very very long text"); @@ -1712,7 +1712,7 @@ TEST(SmallString, ReplaceByPositionLongerWithShortText) ASSERT_THAT(text, SmallString("this is a very very very very long text")); } -TEST(SmallString, ReplaceByPositionEqualSizedTexts) +TEST(SmallString, replace_by_position_equal_sized_texts) { SmallString text("this is very very very very very long text"); @@ -1721,7 +1721,7 @@ TEST(SmallString, ReplaceByPositionEqualSizedTexts) ASSERT_THAT(text, SmallString("this is very very very very very much text")); } -TEST(SmallString, CompareTextWithDifferentLineEndings) +TEST(SmallString, compare_text_with_different_line_endings) { SmallString unixText("some \ntext"); SmallString windowsText("some \n\rtext"); @@ -1731,7 +1731,7 @@ TEST(SmallString, CompareTextWithDifferentLineEndings) ASSERT_THAT(unixText, convertedText); } -TEST(SmallString, ConstSubscriptOperator) +TEST(SmallString, const_subscript_operator) { const SmallString text{"some text"}; @@ -1740,7 +1740,7 @@ TEST(SmallString, ConstSubscriptOperator) ASSERT_THAT(sign, 't'); } -TEST(SmallString, NonConstSubscriptOperator) +TEST(SmallString, non_const_subscript_operator) { SmallString text{"some text"}; @@ -1749,7 +1749,7 @@ TEST(SmallString, NonConstSubscriptOperator) ASSERT_THAT(sign, 't'); } -TEST(SmallString, ManipulateConstSubscriptOperator) +TEST(SmallString, manipulate_const_subscript_operator) { const SmallString text{"some text"}; auto &&sign = text[5]; @@ -1759,7 +1759,7 @@ TEST(SmallString, ManipulateConstSubscriptOperator) ASSERT_THAT(text, SmallString{"some text"}); } -TEST(SmallString, ManipulateNonConstSubscriptOperator) +TEST(SmallString, manipulate_non_const_subscript_operator) { char rawText[] = "some text"; SmallString text{rawText}; @@ -1770,35 +1770,35 @@ TEST(SmallString, ManipulateNonConstSubscriptOperator) ASSERT_THAT(text, SmallString{"some qext"}); } -TEST(SmallString, EmptyInitializerListContent) +TEST(SmallString, empty_initializer_list_content) { SmallString text = {}; ASSERT_THAT(text, SmallString()); } -TEST(SmallString, EmptyInitializerListSize) +TEST(SmallString, empty_initializer_list_size) { SmallString text = {}; ASSERT_THAT(text, SizeIs(0)); } -TEST(SmallString, InitializerListContent) +TEST(SmallString, initializer_list_content) { auto text = SmallString::join({"some", " ", "text"}); ASSERT_THAT(text, SmallString("some text")); } -TEST(SmallString, InitializerListSize) +TEST(SmallString, initializer_list_size) { auto text = SmallString::join({"some", " ", "text"}); ASSERT_THAT(text, SizeIs(9)); } -TEST(SmallString, NumberToString) +TEST(SmallString, number_to_string) { ASSERT_THAT(SmallString::number(-0), "0"); ASSERT_THAT(SmallString::number(1), "1"); @@ -1811,7 +1811,7 @@ TEST(SmallString, NumberToString) ASSERT_THAT(SmallString::number(-1.2), "-1.200000"); } -TEST(SmallString, StringViewPlusOperator) +TEST(SmallString, string_view_plus_operator) { SmallStringView text = "text"; @@ -1820,7 +1820,7 @@ TEST(SmallString, StringViewPlusOperator) ASSERT_THAT(result, "text and more text"); } -TEST(SmallString, StringViewPlusOperatorReverseOrder) +TEST(SmallString, string_view_plus_operator_reverse_order) { SmallStringView text = " and more text"; @@ -1829,7 +1829,7 @@ TEST(SmallString, StringViewPlusOperatorReverseOrder) ASSERT_THAT(result, "text and more text"); } -TEST(SmallString, StringPlusOperator) +TEST(SmallString, string_plus_operator) { SmallString text = "text"; @@ -1838,7 +1838,7 @@ TEST(SmallString, StringPlusOperator) ASSERT_THAT(result, "text and more text"); } -TEST(SmallString, StringPlusOperatorReverseOrder) +TEST(SmallString, string_plus_operator_reverse_order) { SmallString text = " and more text"; @@ -1847,13 +1847,13 @@ TEST(SmallString, StringPlusOperatorReverseOrder) ASSERT_THAT(result, "text and more text"); } -TEST(SmallString, ShortStringCapacity) +TEST(SmallString, short_string_capacity) { ASSERT_THAT(SmallString().shortStringCapacity(), 31); ASSERT_THAT(PathString().shortStringCapacity(), 190); } -TEST(SmallString, ToView) +TEST(SmallString, to_view) { SmallString text = "text"; @@ -1863,7 +1863,7 @@ TEST(SmallString, ToView) } -TEST(SmallString, Compare) +TEST(SmallString, compare) { const char longText[] = "textfoo"; @@ -1876,17 +1876,3 @@ TEST(SmallString, Compare) ASSERT_THAT(Utils::compare("textx", "texta"), Gt(0)); ASSERT_THAT(Utils::compare("texta", "textx"), Le(0)); } - -TEST(SmallString, ReverseCompare) -{ - const char longText[] = "textfoo"; - - ASSERT_THAT(Utils::reverseCompare("", ""), Eq(0)); - ASSERT_THAT(Utils::reverseCompare("text", "text"), Eq(0)); - ASSERT_THAT(Utils::reverseCompare("text", Utils::SmallStringView(longText, 4)), Eq(0)); - ASSERT_THAT(Utils::reverseCompare("", "text"), Le(0)); - ASSERT_THAT(Utils::reverseCompare("textx", "text"), Gt(0)); - ASSERT_THAT(Utils::reverseCompare("text", "textx"), Le(0)); - ASSERT_THAT(Utils::reverseCompare("textx", "texta"), Gt(0)); - ASSERT_THAT(Utils::reverseCompare("texta", "textx"), Le(0)); -} diff --git a/tests/unit/tests/utils/CMakeLists.txt b/tests/unit/tests/utils/CMakeLists.txt new file mode 100644 index 00000000000..d29e78863b2 --- /dev/null +++ b/tests/unit/tests/utils/CMakeLists.txt @@ -0,0 +1,20 @@ +add_qtc_library(TestUtils OBJECT + EXCLUDE_FROM_INSTALL + PUBLIC_INCLUDES ${CMAKE_CURRENT_LIST_DIR} + DEPENDS + Qt::Core Googletest Utils + SOURCES + googletest.h + google-using-declarations.h + conditionally-disabled-tests.h + eventspy.cpp + eventspy.h + fakeprocess.cpp + fakeprocess.h + notification.h + processevents-utilities.cpp + processevents-utilities.h + spydummy.cpp + spydummy.h + unittest-utility-functions.h +) diff --git a/tests/unit/unittest/conditionally-disabled-tests.h b/tests/unit/tests/utils/conditionally-disabled-tests.h similarity index 100% rename from tests/unit/unittest/conditionally-disabled-tests.h rename to tests/unit/tests/utils/conditionally-disabled-tests.h diff --git a/tests/unit/unittest/eventspy.cpp b/tests/unit/tests/utils/eventspy.cpp similarity index 100% rename from tests/unit/unittest/eventspy.cpp rename to tests/unit/tests/utils/eventspy.cpp diff --git a/tests/unit/unittest/eventspy.h b/tests/unit/tests/utils/eventspy.h similarity index 100% rename from tests/unit/unittest/eventspy.h rename to tests/unit/tests/utils/eventspy.h diff --git a/tests/unit/unittest/fakeprocess.cpp b/tests/unit/tests/utils/fakeprocess.cpp similarity index 100% rename from tests/unit/unittest/fakeprocess.cpp rename to tests/unit/tests/utils/fakeprocess.cpp diff --git a/tests/unit/unittest/fakeprocess.h b/tests/unit/tests/utils/fakeprocess.h similarity index 100% rename from tests/unit/unittest/fakeprocess.h rename to tests/unit/tests/utils/fakeprocess.h diff --git a/tests/unit/unittest/google-using-declarations.h b/tests/unit/tests/utils/google-using-declarations.h similarity index 93% rename from tests/unit/unittest/google-using-declarations.h rename to tests/unit/tests/utils/google-using-declarations.h index 198bbce7842..19e8df2ef20 100644 --- a/tests/unit/unittest/google-using-declarations.h +++ b/tests/unit/tests/utils/google-using-declarations.h @@ -30,7 +30,11 @@ using testing::Gt; using testing::HasSubstr; using testing::InSequence; using testing::Invoke; +using testing::IsFalse; using testing::IsNull; +using testing::IsSubsetOf; +using testing::IsSupersetOf; +using testing::IsTrue; using testing::Le; using testing::Lt; using testing::Matcher; diff --git a/tests/unit/unittest/googletest.h b/tests/unit/tests/utils/googletest.h similarity index 58% rename from tests/unit/unittest/googletest.h rename to tests/unit/tests/utils/googletest.h index a3d3012a09a..a64bdb4435f 100644 --- a/tests/unit/unittest/googletest.h +++ b/tests/unit/tests/utils/googletest.h @@ -4,23 +4,23 @@ #pragma once #ifdef __GNUC__ -#pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant" +# pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant" #endif -#include #include -#include +#include #include #include +#include + +#include "../utils/google-using-declarations.h" #include "conditionally-disabled-tests.h" -#include "gtest-creator-printing.h" -#include "gtest-llvm-printing.h" -#include "gtest-qt-printing.h" -#include "gtest-std-printing.h" -#include "google-using-declarations.h" +#include "../printers/gtest-creator-printing.h" +#include "../printers/gtest-qt-printing.h" +#include "../printers/gtest-std-printing.h" -#include "unittest-matchers.h" +#include "../matchers/unittest-matchers.h" #include "unittest-utility-functions.h" diff --git a/tests/unit/unittest/notification.h b/tests/unit/tests/utils/notification.h similarity index 95% rename from tests/unit/unittest/notification.h rename to tests/unit/tests/utils/notification.h index f34f1545cd9..85624a27962 100644 --- a/tests/unit/unittest/notification.h +++ b/tests/unit/tests/utils/notification.h @@ -1,7 +1,7 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 -#include "googletest.h" +#include "../utils/googletest.h" #include #include diff --git a/tests/unit/unittest/processevents-utilities.cpp b/tests/unit/tests/utils/processevents-utilities.cpp similarity index 100% rename from tests/unit/unittest/processevents-utilities.cpp rename to tests/unit/tests/utils/processevents-utilities.cpp diff --git a/tests/unit/unittest/processevents-utilities.h b/tests/unit/tests/utils/processevents-utilities.h similarity index 100% rename from tests/unit/unittest/processevents-utilities.h rename to tests/unit/tests/utils/processevents-utilities.h diff --git a/tests/unit/unittest/spydummy.cpp b/tests/unit/tests/utils/spydummy.cpp similarity index 100% rename from tests/unit/unittest/spydummy.cpp rename to tests/unit/tests/utils/spydummy.cpp diff --git a/tests/unit/unittest/spydummy.h b/tests/unit/tests/utils/spydummy.h similarity index 100% rename from tests/unit/unittest/spydummy.h rename to tests/unit/tests/utils/spydummy.h diff --git a/tests/unit/unittest/unittest-utility-functions.h b/tests/unit/tests/utils/unittest-utility-functions.h similarity index 100% rename from tests/unit/unittest/unittest-utility-functions.h rename to tests/unit/tests/utils/unittest-utility-functions.h diff --git a/tests/unit/unit.qbs b/tests/unit/unit.qbs deleted file mode 100644 index b263b933f8f..00000000000 --- a/tests/unit/unit.qbs +++ /dev/null @@ -1,4 +0,0 @@ -Product { - name: "QmlDesigner unit tests" - files: ["*", "**/*"] -} diff --git a/tests/unit/unittest/CMakeLists.txt b/tests/unit/unittest/CMakeLists.txt deleted file mode 100644 index a77b855985e..00000000000 --- a/tests/unit/unittest/CMakeLists.txt +++ /dev/null @@ -1,367 +0,0 @@ -find_package(Googletest MODULE) -find_package(GoogleBenchmark MODULE) -find_package(Qt6 COMPONENTS QmlDomPrivate QmlCompilerPrivate) - -if (NOT Googletest_FOUND) - message(STATUS "Googletest was not found. Please set GOOGLETEST_DIR (CMake or Environment) variable.") - message(STATUS "Have a look at cmake/FindGoogletest.cmake file for more details.") - message(STATUS "unittest module will be skipped.") - return() -endif() - -if (MSVC) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj") -elseif (MINGW) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wa,-mbig-obj") -endif() - -file(RELATIVE_PATH RELATIVE_TEST_PATH "${PROJECT_BINARY_DIR}" "${CMAKE_CURRENT_BINARY_DIR}") -file(RELATIVE_PATH TEST_RELATIVE_LIBEXEC_PATH "/${RELATIVE_TEST_PATH}" "/${IDE_LIBEXEC_PATH}") - -add_qtc_test(unittest GTEST - PROPERTIES COMPILE_WARNING_AS_ERROR OFF - INCLUDES - BEFORE "../mockup" - BEFORE "../mockup/qmldesigner/designercore/include" - DEPENDS - Qt::Core Qt::Network Qt::Widgets - Qt::Xml Qt::Concurrent Qt::QmlPrivate Qt::Gui - Qt::Core5Compat QmlJS Sqlite SqliteC - Googletest - DEFINES - GTEST_INTERNAL_HAS_STRING_VIEW - QT_NO_CAST_TO_ASCII - QT_RESTRICTED_CAST_FROM_ASCII - UNIT_TESTS - DONT_CHECK_MESSAGE_COUNTER - QTC_RESOURCE_DIR="${CMAKE_CURRENT_LIST_DIR}/../../../share/qtcreator" - TESTDATA_DIR="${CMAKE_CURRENT_SOURCE_DIR}/data" - UNITTEST_DIR="${CMAKE_CURRENT_SOURCE_DIR}" - TEST_RELATIVE_LIBEXEC_PATH="${TEST_RELATIVE_LIBEXEC_PATH}" - QT6_INSTALL_PREFIX="${QT6_INSTALL_PREFIX}" - QDS_MODEL_USE_PROJECTSTORAGEINTERFACE - QDS_USE_PROJECTSTORAGE - SOURCES - abstractviewmock.h - conditionally-disabled-tests.h - dynamicastmatcherdiagnosticcontainer-matcher.h - eventspy.cpp eventspy.h - fakeprocess.cpp fakeprocess.h - googletest.h - google-using-declarations.h - gtest-creator-printing.cpp gtest-creator-printing.h - gtest-llvm-printing.h - gtest-qt-printing.cpp gtest-qt-printing.h - gtest-std-printing.h - lastchangedrowid-test.cpp - import-test.cpp - model-test.cpp - modelresourcemanagementmock.h - matchingtext-test.cpp - mockfutureinterface.h - mockmutex.h - mockqfilesystemwatcher.h - mocksqlitestatement.h - mocksqlitetransactionbackend.h - mocksyntaxhighligher.h - mocktimer.cpp mocktimer.h - nodelistproperty-test.cpp - processevents-utilities.cpp processevents-utilities.h - projectstoragemock.cpp projectstoragemock.h - sizedarray-test.cpp - smallstring-test.cpp - spydummy.cpp spydummy.h - sqlitealgorithms-test.cpp - sqliteindex-test.cpp - sqliteteststatement.h - sqlitetransaction-test.cpp - unittests-main.cpp - unittest-utility-functions.h - sqlitecolumn-test.cpp - sqlitedatabasebackend-test.cpp - sqlitedatabase-test.cpp - sqlitefunctionregistry-test.cpp - sqlitesessions-test.cpp - sqlitestatement-test.cpp - sqlitetable-test.cpp - sqlstatementbuilder-test.cpp - createtablesqlstatementbuilder-test.cpp - sqlitevalue-test.cpp - asynchronousimagecache-test.cpp - synchronousimagecache-test.cpp - imagecachegenerator-test.cpp - imagecachestorage-test.cpp - imagecachedispatchcollector-test.cpp - sqlitedatabasemock.h - sqlitereadstatementmock.cpp sqlitereadstatementmock.h - sqlitereadwritestatementmock.cpp - sqlitestatementmock.h - sqlitetransactionbackendmock.h - sqlitewritestatementmock.cpp sqlitewritestatementmock.h - notification.h - mocktimestampprovider.h - imagecachecollectormock.h - mockimagecachegenerator.h - mockimagecachestorage.h - asynchronousexplicitimagecache-test.cpp - asynchronousimagefactory-test.cpp - modulescanner-test.cpp -) - -if (NOT TARGET unittest) - return() -endif() - -function(extend_qtc_test_with_target_sources target) - cmake_parse_arguments(_arg "" "" "DEFINES;INCLUDES" ${ARGN}) - - get_target_property(${target}Sources ${target} SOURCES) - # work around issue with CMake < 3.14 where target sources can contain - # $ - list(FILTER ${target}Sources EXCLUDE REGEX "^\\$ - ${_arg_DEFINES} - INCLUDES - $ - ${_arg_INCLUDES} - ) -endfunction() - -# Do not work on the source directory data -add_custom_command(TARGET unittest POST_BUILD - COMMAND "${CMAKE_COMMAND}" -E copy_directory - "${CMAKE_CURRENT_SOURCE_DIR}/data" - "${CMAKE_CURRENT_BINARY_DIR}/data" -) - -extend_qtc_test(unittest - CONDITION TARGET GoogleBenchmark - DEPENDS GoogleBenchmark - SOURCES - smallstring-benchmark.cpp -) - -finalize_qtc_gtest(unittest - EXCLUDE_SOURCES_REGEX ".c$" - EXCLUDE_ALL_FROM_PRECHECK) - -# Path needs to be before CppEditor -target_include_directories(unittest - PRIVATE - BEFORE ../../../src/plugins -) - -# QmlDesigner tests - -set(QmlDesignerDir ../../../src/plugins/qmldesigner) -extend_qtc_test(unittest - INCLUDES - "${QmlDesignerDir}" - "${QmlDesignerDir}/designercore" - "${QmlDesignerDir}/designercore/include" - "${QmlDesignerDir}/designercore/imagecache" - "${QmlDesignerDir}/../../../src/libs/qmlpuppetcommunication/interfaces" - "${QmlDesignerDir}/../../../src/libs/qmlpuppetcommunication/types" - DEFINES - QMLDESIGNERCORE_STATIC_LIBRARY QMLDESIGNER_STATIC_LIBRARY - SOURCES_PREFIX - "${QmlDesignerDir}" - SOURCES - components/listmodeleditor/listmodeleditormodel.cpp components/listmodeleditor/listmodeleditormodel.h -) -extend_qtc_test(unittest - SOURCES_PREFIX "${QmlDesignerDir}/designercore" - SOURCES - ../../../../src/libs/qmlpuppetcommunication/interfaces/commondefines.h - ../components/listmodeleditor/listmodeleditormodel.cpp - ../components/listmodeleditor/listmodeleditormodel.h - exceptions/exception.cpp - exceptions/invalidargumentexception.cpp - exceptions/invalididexception.cpp - exceptions/invalidmetainfoexception.cpp - exceptions/invalidmodelnodeexception.cpp - exceptions/invalidmodelstateexception.cpp - exceptions/invalidpropertyexception.cpp - exceptions/invalidqmlsourceexception.cpp - exceptions/invalidreparentingexception.cpp - exceptions/invalidslideindexexception.cpp - exceptions/notimplementedexception.cpp - exceptions/removebasestateexception.cpp - exceptions/rewritingexception.cpp - imagecache/asynchronousexplicitimagecache.cpp - imagecache/asynchronousimagecache.cpp - imagecache/asynchronousimagefactory.cpp - imagecache/asynchronousimagefactory.h - imagecache/imagecachecollectorinterface.h - imagecache/imagecachegenerator.cpp - imagecache/imagecachegenerator.h - imagecache/imagecachegeneratorinterface.h - imagecache/imagecachestorage.h - imagecache/imagecachedispatchcollector.h - imagecache/imagecachestorageinterface.h - imagecache/synchronousimagecache.cpp - imagecache/timestampproviderinterface.h - include/abstractproperty.h - include/abstractview.h - include/asynchronousexplicitimagecache.h - include/asynchronousimagecache.h - include/asynchronousimagecacheinterface.h - include/bindingproperty.h - include/imagecacheauxiliarydata.h - include/import.h - include/itemlibraryinfo.h - include/metainfo.h - include/metainforeader.h - include/model.h - include/modelnode.h - include/nodeabstractproperty.h - include/nodelistproperty.h - include/nodemetainfo.h - include/nodeproperty.h - include/projectstorageids.h - include/propertymetainfo.h - include/propertycontainer.h - include/propertyparser.h - include/qmldesignercorelib_global.h - include/signalhandlerproperty.h - include/synchronousimagecache.h - include/variantproperty.h - metainfo/itemlibraryinfo.cpp - metainfo/metainfo.cpp - metainfo/metainforeader.cpp - metainfo/nodemetainfo.cpp - model/abstractproperty.cpp - model/abstractview.cpp - model/annotation.cpp - model/bindingproperty.cpp - model/import.cpp - model/internalbindingproperty.cpp - model/internalbindingproperty.h - model/internalnode.cpp - model/internalnode_p.h - model/internalnodeabstractproperty.cpp - model/internalnodeabstractproperty.h - model/internalnodelistproperty.cpp - model/internalnodelistproperty.h - model/internalnodeproperty.cpp - model/internalnodeproperty.h - model/internalproperty.cpp - model/internalproperty.h - model/internalsignalhandlerproperty.cpp - model/internalsignalhandlerproperty.h - model/internalvariantproperty.cpp - model/internalvariantproperty.h - model/model.cpp - model/model_p.h - model/modelnode.cpp - model/modelresourcemanagementinterface.h - model/propertycontainer.cpp - model/propertyparser.cpp - model/nodeabstractproperty.cpp - model/nodelistproperty.cpp - model/nodeproperty.cpp - model/signalhandlerproperty.cpp - model/variantproperty.cpp - pluginmanager/widgetpluginmanager.h pluginmanager/widgetpluginmanager.cpp - pluginmanager/widgetpluginpath.h pluginmanager/widgetpluginpath.cpp - projectstorage/directorypathcompressor.h - projectstorage/filesysteminterface.h - projectstorage/filesystem.cpp projectstorage/filesystem.h - projectstorage/filestatus.h - projectstorage/filestatuscache.cpp projectstorage/filestatuscache.h - projectstorage/modulescanner.cpp projectstorage/modulescanner.h - projectstorage/nonlockingmutex.h - projectstorage/projectstorageexceptions.cpp projectstorage/projectstorageexceptions.h - projectstorage/projectstorageinterface.h - projectstorage/projectstorage.cpp projectstorage/projectstorage.h - projectstorage/projectstoragepathwatcher.h - projectstorage/projectstoragepathwatcherinterface.h - projectstorage/projectstoragepathwatchernotifierinterface.h - projectstorage/projectstoragesqlitefunctionregistry.cpp - projectstorage/projectstoragesqlitefunctionregistry.h - projectstorage/projectstoragepathwatcher.h - projectstorage/projectstoragepathwatchertypes.h - projectstorage/projectstoragetypes.h - projectstorage/projectstorageupdater.cpp projectstorage/projectstorageupdater.h - projectstorage/sourcepath.h - projectstorage/sourcepathcache.h - projectstorage/sourcepathcache.h - projectstorage/sourcepathcachetypes.h - projectstorage/sourcepathview.h - projectstorage/storagecache.h - projectstorage/storagecacheentry.h - projectstorage/storagecachefwd.h - projectstorage/qmldocumentparserinterface.h - projectstorage/qmltypesparserinterface.h - rewritertransaction.cpp - rewritertransaction.h - EXPLICIT_MOC - "../mockup/qmldesigner/designercore/include/nodeinstanceview.h" - "../mockup/qmldesigner/designercore/include/rewriterview.h" - "${QmlDesignerDir}/designercore/include/model.h" -) - -extend_qtc_test(unittest - SOURCES - directorypathcompressor-test.cpp - filesystemmock.h - filestatuscache-test.cpp - listmodeleditor-test.cpp - projectstorage-test.cpp - projectstorageupdater-test.cpp - projectstoragesqlitefunctionregistry-test.cpp - projectstoragepathwatchermock.h - projectstoragepathwatchernotifiermock.h - projectstoragepathwatcher-test.cpp - sourcepath-test.cpp - sourcepathcache-test.cpp - sourcepathcachemock.h - sourcepathview-test.cpp - storagecache-test.cpp - qmldocumentparsermock.h - qmltypesparsermock.h -) - -# QmlDesigner tests END - -if (NOT TARGET Utils) - add_subdirectory(../../../src/libs/utils ${CMAKE_CURRENT_BINARY_DIR}/utils) -endif() -if (NOT TARGET CPlusPlus) - add_subdirectory(../../../src/libs/3rdparty/cplusplus ${CMAKE_CURRENT_BINARY_DIR}/3rd_cplusplus) - add_subdirectory(../../../src/libs/cplusplus ${CMAKE_CURRENT_BINARY_DIR}/cplusplus) -endif() - -extend_qtc_test(unittest DEPENDS Utils CPlusPlus) - -extend_qtc_test(unittest - CONDITION TARGET Qt6::QmlDomPrivate AND TARGET Qt6::QmlCompilerPrivate AND Qt6_VERSION VERSION_GREATER_EQUAL 6.5.0 AND Qt6_VERSION VERSION_LESS 6.6.0 - DEPENDS Qt6::QmlDomPrivate Qt6::QmlCompilerPrivate - SOURCES - qmldocumentparser-test.cpp - qmltypesparser-test.cpp -) - -extend_qtc_test(unittest - CONDITION TARGET Qt6::QmlDomPrivate AND TARGET Qt6::QmlCompilerPrivate AND Qt6_VERSION VERSION_GREATER_EQUAL 6.5.0 AND Qt6_VERSION VERSION_LESS 6.6.0 - SOURCES_PREFIX "${QmlDesignerDir}/designercore" - DEPENDS Qt6::QmlDomPrivate Qt6::QmlCompilerPrivate - DEFINES QDS_BUILD_QMLPARSER - SOURCES - projectstorage/qmldocumentparser.cpp projectstorage/qmldocumentparser.h - projectstorage/qmltypesparser.cpp projectstorage/qmltypesparser.h -) - -file(GLOB PROJECTSTORAGE_EXCLUDED_SOURCES ${QmlDesignerDir}/designercore/projectstorage/*.cpp) -set_property(SOURCE ${PROJECTSTORAGE_EXCLUDED_SOURCES} PROPERTY SKIP_AUTOMOC ON) - -file(GLOB UNITTEST_EXCLUDED_SOURCES *.cpp) -set_property(SOURCE ${UNITTEST_EXCLUDED_SOURCES} PROPERTY SKIP_AUTOMOC ON) - -add_subdirectory(qmlprojectmanager) diff --git a/tests/unit/unittest/data/qml/Qt3D/Core/qmldir b/tests/unit/unittest/data/qml/Qt3D/Core/qmldir deleted file mode 100644 index 7c8712f946c..00000000000 --- a/tests/unit/unittest/data/qml/Qt3D/Core/qmldir +++ /dev/null @@ -1,8 +0,0 @@ -module Qt3D.Core -linktarget Qt6::quick3dcoreplugin -plugin quick3dcoreplugin -classname Qt3DQuick3DCorePlugin -typeinfo plugins.qmltypes -depends QtQuick auto -prefer :/qt-project.org/imports/Qt3D/Core/ - diff --git a/tests/unit/unittest/dynamicastmatcherdiagnosticcontainer-matcher.h b/tests/unit/unittest/dynamicastmatcherdiagnosticcontainer-matcher.h deleted file mode 100644 index dd63682ec48..00000000000 --- a/tests/unit/unittest/dynamicastmatcherdiagnosticcontainer-matcher.h +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (C) 2016 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 - -#pragma once - -#include "googletest.h" - -using testing::PrintToString; - -namespace { - -MATCHER_P5(HasDiagnosticMessage, errorTypeText, startLine, startColumn, endLine, endColumn, - std::string(negation ? "isn't " : "is ") - + "{" + PrintToString(errorTypeText) - + ": (" + PrintToString(startLine) - + ", " + PrintToString(startColumn) - + "), (" + PrintToString(endLine) - + ", " + PrintToString(endColumn) - + ")}" - ) -{ - if (!arg.empty() && arg.front().messages.empty()) { - *result_listener << "no messages"; - return false; - } - - auto message = arg.front().messages.front(); - auto sourceRange = message.sourceRange; - - return message.errorTypeText() == errorTypeText - && sourceRange.start.line == uint(startLine) - && sourceRange.start.column == uint(startColumn) - && sourceRange.end.line == uint(endLine) - && sourceRange.end.column == uint(endColumn); -} - -MATCHER_P5(HasDiagnosticContext, contextTypeText, startLine, startColumn, endLine, endColumn, - std::string(negation ? "isn't " : "is ") - + "{" + PrintToString(contextTypeText) - + ": (" + PrintToString(startLine) - + ", " + PrintToString(startColumn) - + "), (" + PrintToString(endLine) - + ", " + PrintToString(endColumn) - + ")}" - ) -{ - if (!arg.empty() && arg.front().messages.empty()) { - *result_listener << "no context"; - return false; - } - - auto context = arg.front().contexts.front(); - auto sourceRange = context.sourceRange; - - return context.contextTypeText() == contextTypeText - && sourceRange.start.line == uint(startLine) - && sourceRange.start.column == uint(startColumn) - && sourceRange.end.line == uint(endLine) - && sourceRange.end.column == uint(endColumn); -} - -} diff --git a/tests/unit/unittest/gtest-llvm-printing.cpp b/tests/unit/unittest/gtest-llvm-printing.cpp deleted file mode 100644 index 3e7108dd847..00000000000 --- a/tests/unit/unittest/gtest-llvm-printing.cpp +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (C) 2019 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 - -#include "gtest-llvm-printing.h" -#include "gtest-std-printing.h" - -#include - -#include - -#include - -namespace clang { -namespace tooling { -struct CompileCommand; - -std::ostream &operator<<(std::ostream &out, const CompileCommand &command) -{ - return out << "(" << command.Directory << ", " << command.Filename << ", " - << command.CommandLine << ", " << command.Output << ")"; -} -} // namespace tooling -} // namespace clang diff --git a/tests/unit/unittest/gtest-llvm-printing.h b/tests/unit/unittest/gtest-llvm-printing.h deleted file mode 100644 index 9530f32d1bb..00000000000 --- a/tests/unit/unittest/gtest-llvm-printing.h +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (C) 2019 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 - -#pragma once - -#include - -#include - -namespace clang { -namespace tooling { -struct CompileCommand; - -std::ostream &operator<<(std::ostream &out, const CompileCommand &command); - -} // namespace tooling -} // namespace clang diff --git a/tests/unit/unittest/mockfutureinterface.h b/tests/unit/unittest/mockfutureinterface.h deleted file mode 100644 index a2601cd1ffa..00000000000 --- a/tests/unit/unittest/mockfutureinterface.h +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (C) 2018 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 - -#pragma once - -#include "googletest.h" - -class MockQFutureInterface -{ -public: - MOCK_METHOD1(setExpectedResultCount, - void (int)); - MOCK_METHOD1(setProgressValue, - void (int)); - MOCK_CONST_METHOD0(isRunning, - bool ()); - MOCK_METHOD0(reportFinished, - void ()); - -}; diff --git a/tests/unit/unittest/model-test.cpp b/tests/unit/unittest/model-test.cpp deleted file mode 100644 index 7de2618aa93..00000000000 --- a/tests/unit/unittest/model-test.cpp +++ /dev/null @@ -1,491 +0,0 @@ -// Copyright (C) 2023 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 - -#include "googletest.h" - -#include "mocklistmodeleditorview.h" -#include "modelresourcemanagementmock.h" -#include "projectstoragemock.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { -using QmlDesigner::AbstractProperty; -using QmlDesigner::ModelNode; -using QmlDesigner::ModelNodes; -using QmlDesigner::ModelResourceSet; - -template -auto HasPropertyName(const Matcher &matcher) -{ - return Property(&AbstractProperty::name, matcher); -} - -class Model : public ::testing::Test -{ -protected: - Model() - { - model.attachView(&viewMock); - rootNode = viewMock.rootModelNode(); - ON_CALL(resourceManagementMock, removeNode(_)).WillByDefault([](const auto &node) { - return ModelResourceSet{{node}, {}, {}}; - }); - ON_CALL(resourceManagementMock, removeProperty(_)).WillByDefault([](const auto &property) { - return ModelResourceSet{{}, {property}, {}}; - }); - } - - ~Model() { model.detachView(&viewMock); } - - auto createNodeWithParent(const ModelNode &parentNode) - { - auto node = viewMock.createModelNode("QtQuick.Item"); - parentNode.defaultNodeAbstractProperty().reparentHere(node); - - return node; - } - - auto createProperty(const ModelNode &parentNode, QmlDesigner::PropertyName name) - { - auto property = parentNode.variantProperty(name); - property.setValue(4); - return property; - } - -protected: - NiceMock viewMock; - NiceMock projectStorageMock; - NiceMock resourceManagementMock; - QmlDesigner::Model model{projectStorageMock, - "QtQuick.Item", - -1, - -1, - nullptr, - std::make_unique( - resourceManagementMock)}; - ModelNode rootNode; -}; - -TEST_F(Model, ModelNodeDestroyIsCallingModelResourceManagementRemoveNode) -{ - auto node = createNodeWithParent(rootNode); - - EXPECT_CALL(resourceManagementMock, removeNode(node)); - - node.destroy(); -} - -TEST_F(Model, ModelNodeRemoveProperyIsCallingModelResourceManagementRemoveProperty) -{ - auto property = rootNode.variantProperty("foo"); - property.setValue(4); - - EXPECT_CALL(resourceManagementMock, removeProperty(Eq(property))); - - rootNode.removeProperty("foo"); -} - -TEST_F(Model, NodeAbstractPropertyReparentHereIsCallingModelResourceManagementRemoveProperty) -{ - auto node = createNodeWithParent(rootNode); - auto property = rootNode.variantProperty("foo"); - property.setValue(4); - - EXPECT_CALL(resourceManagementMock, removeProperty(Eq(property))); - - rootNode.nodeListProperty("foo").reparentHere(node); -} - -TEST_F(Model, NodePropertySetModelNodeIsCallingModelResourceManagementRemoveProperty) -{ - auto node = createNodeWithParent(rootNode); - auto property = rootNode.variantProperty("foo"); - property.setValue(4); - - EXPECT_CALL(resourceManagementMock, removeProperty(Eq(property))); - - rootNode.nodeProperty("foo").setModelNode(node); -} - -TEST_F(Model, VariantPropertySetValueIsCallingModelResourceManagementRemoveProperty) -{ - auto property = rootNode.bindingProperty("foo"); - property.setExpression("blah"); - - EXPECT_CALL(resourceManagementMock, removeProperty(Eq(property))); - - rootNode.variantProperty("foo").setValue(7); -} - -TEST_F(Model, - VariantPropertySetDynamicTypeNameAndEnumerationIsCallingModelResourceManagementRemoveProperty) -{ - auto property = rootNode.bindingProperty("foo"); - property.setExpression("blah"); - - EXPECT_CALL(resourceManagementMock, removeProperty(Eq(property))); - - rootNode.variantProperty("foo").setDynamicTypeNameAndEnumeration("int", "Ha"); -} - -TEST_F(Model, VariantPropertySetDynamicTypeNameAndValueIsCallingModelResourceManagementRemoveProperty) -{ - auto property = rootNode.bindingProperty("foo"); - property.setExpression("blah"); - - EXPECT_CALL(resourceManagementMock, removeProperty(Eq(property))); - - rootNode.variantProperty("foo").setDynamicTypeNameAndValue("int", 7); -} - -TEST_F(Model, BindingPropertySetExpressionIsCallingModelResourceManagementRemoveProperty) -{ - auto property = rootNode.variantProperty("foo"); - property.setValue(4); - - EXPECT_CALL(resourceManagementMock, removeProperty(Eq(property))); - - rootNode.bindingProperty("foo").setExpression("blah"); -} - -TEST_F(Model, - BindingPropertySetDynamicTypeNameAndExpressionIsCallingModelResourceManagementRemoveProperty) -{ - auto property = rootNode.variantProperty("foo"); - property.setValue(4); - - EXPECT_CALL(resourceManagementMock, removeProperty(Eq(property))); - - rootNode.bindingProperty("foo").setDynamicTypeNameAndExpression("int", "blah"); -} - -TEST_F(Model, SignalHandlerPropertySetSourceIsCallingModelResourceManagementRemoveProperty) -{ - auto property = rootNode.bindingProperty("foo"); - property.setExpression("blah"); - - EXPECT_CALL(resourceManagementMock, removeProperty(Eq(property))); - - rootNode.signalHandlerProperty("foo").setSource("blah"); -} - -TEST_F(Model, SignalDeclarationPropertySetSignatureIsCallingModelResourceManagementRemoveProperty) -{ - auto property = rootNode.bindingProperty("foo"); - property.setExpression("blah"); - - EXPECT_CALL(resourceManagementMock, removeProperty(Eq(property))); - - rootNode.signalDeclarationProperty("foo").setSignature("blah"); -} - -TEST_F(Model, ModelNodeDestroyIsCallingAbstractViewNodeAboutToBeRemoved) -{ - auto node = createNodeWithParent(rootNode); - auto node2 = createNodeWithParent(rootNode); - ON_CALL(resourceManagementMock, removeNode(node)) - .WillByDefault(Return(ModelResourceSet{{node, node2}, {}, {}})); - - EXPECT_CALL(viewMock, nodeAboutToBeRemoved(Eq(node))); - EXPECT_CALL(viewMock, nodeAboutToBeRemoved(Eq(node2))); - - node.destroy(); -} - -TEST_F(Model, ModelNodeDestroyIsCallingAbstractViewNodeRemoved) -{ - auto node = createNodeWithParent(rootNode); - auto node2 = createNodeWithParent(rootNode); - ON_CALL(resourceManagementMock, removeNode(node)) - .WillByDefault(Return(ModelResourceSet{{node, node2}, {}, {}})); - - EXPECT_CALL(viewMock, nodeRemoved(Eq(node), _, _)); - EXPECT_CALL(viewMock, nodeRemoved(Eq(node2), _, _)); - - node.destroy(); -} - -TEST_F(Model, ModelNodeDestroyIsCallingAbstractViewNodeRemovedWithValidNodes) -{ - auto node = createNodeWithParent(rootNode); - auto node2 = createNodeWithParent(rootNode); - ON_CALL(resourceManagementMock, removeNode(node)) - .WillByDefault(Return(ModelResourceSet{{node, node2, ModelNode{}}, {}, {}})); - - EXPECT_CALL(viewMock, nodeRemoved(Eq(node), _, _)); - EXPECT_CALL(viewMock, nodeRemoved(Eq(node2), _, _)); - - node.destroy(); -} - -TEST_F(Model, ModelNodeDestroyIsCallingAbstractViewPropertiesAboutToBeRemoved) -{ - auto node = createNodeWithParent(rootNode); - auto property = createProperty(rootNode, "foo"); - auto property2 = createProperty(rootNode, "bar"); - ON_CALL(resourceManagementMock, removeNode(node)) - .WillByDefault(Return(ModelResourceSet{{node}, {property, property2}, {}})); - - EXPECT_CALL(viewMock, propertiesAboutToBeRemoved(ElementsAre(Eq(property)))); - EXPECT_CALL(viewMock, propertiesAboutToBeRemoved(ElementsAre(Eq(property2)))); - - node.destroy(); -} - -TEST_F(Model, ModelNodeDestroyIsCallingAbstractViewPropertiesRemoved) -{ - auto node = createNodeWithParent(rootNode); - auto property = createProperty(rootNode, "foo"); - auto property2 = createProperty(rootNode, "bar"); - ON_CALL(resourceManagementMock, removeNode(node)) - .WillByDefault(Return(ModelResourceSet{{node}, {property, property2}, {}})); - - EXPECT_CALL(viewMock, propertiesRemoved(ElementsAre(Eq(property)))); - EXPECT_CALL(viewMock, propertiesRemoved(ElementsAre(Eq(property2)))); - - node.destroy(); -} - -TEST_F(Model, ModelNodeDestroyIsCallingAbstractViewPropertiesRemovedOnlyWithValidProperties) -{ - auto node = createNodeWithParent(rootNode); - auto property = createProperty(rootNode, "foo"); - auto property2 = createProperty(rootNode, "bar"); - ON_CALL(resourceManagementMock, removeNode(node)) - .WillByDefault(Return(ModelResourceSet{{node}, {property, property2, {}}, {}})); - - EXPECT_CALL(viewMock, propertiesRemoved(ElementsAre(Eq(property)))); - EXPECT_CALL(viewMock, propertiesRemoved(ElementsAre(Eq(property2)))); - - node.destroy(); -} - -TEST_F(Model, ModelNodeDestroyIsCallingAbstractViewBindingPropertiesAboutToBeChanged) -{ - auto node = createNodeWithParent(rootNode); - auto property = rootNode.bindingProperty("foo"); - auto property2 = rootNode.bindingProperty("bar"); - ON_CALL(resourceManagementMock, removeNode(node)) - .WillByDefault(Return(ModelResourceSet{{node}, {}, {{property, "yi"}, {property2, "er"}}})); - - EXPECT_CALL(viewMock, bindingPropertiesAboutToBeChanged(ElementsAre(Eq(property)))); - EXPECT_CALL(viewMock, bindingPropertiesAboutToBeChanged(ElementsAre(Eq(property2)))); - - node.destroy(); -} - -TEST_F(Model, ModelNodeDestroyIsCallingAbstractViewBindingPropertiesChanged) -{ - auto node = createNodeWithParent(rootNode); - auto property = rootNode.bindingProperty("foo"); - auto property2 = rootNode.bindingProperty("bar"); - ON_CALL(resourceManagementMock, removeNode(node)) - .WillByDefault(Return(ModelResourceSet{{node}, {}, {{property, "yi"}, {property2, "er"}}})); - - EXPECT_CALL(viewMock, bindingPropertiesChanged(ElementsAre(Eq(property)), _)); - EXPECT_CALL(viewMock, bindingPropertiesChanged(ElementsAre(Eq(property2)), _)); - - node.destroy(); -} - -TEST_F(Model, ModelNodeDestroyIsCallingAbstractViewBindingPropertiesChangedOnlyWithValidProperties) -{ - auto node = createNodeWithParent(rootNode); - auto property = rootNode.bindingProperty("foo"); - auto property2 = rootNode.bindingProperty("bar"); - ON_CALL(resourceManagementMock, removeNode(node)) - .WillByDefault(Return( - ModelResourceSet{{node}, {}, {{property, "yi"}, {property2, "er"}, {{}, "san"}}})); - - EXPECT_CALL(viewMock, bindingPropertiesChanged(ElementsAre(Eq(property)), _)); - EXPECT_CALL(viewMock, bindingPropertiesChanged(ElementsAre(Eq(property2)), _)); - - node.destroy(); -} - -TEST_F(Model, ModelNodeRemovePropertyIsCallingAbstractViewNodeAboutToBeRemoved) -{ - auto property = createProperty(rootNode, "foo"); - auto node = createNodeWithParent(rootNode); - auto node2 = createNodeWithParent(rootNode); - ON_CALL(resourceManagementMock, removeProperty(property)) - .WillByDefault(Return(ModelResourceSet{{node, node2}, {property}, {}})); - - EXPECT_CALL(viewMock, nodeAboutToBeRemoved(Eq(node))); - EXPECT_CALL(viewMock, nodeAboutToBeRemoved(Eq(node2))); - - rootNode.removeProperty("foo"); -} - -TEST_F(Model, ModelNodeRemovePropertyIsCallingAbstractViewNodeRemoved) -{ - auto property = createProperty(rootNode, "foo"); - auto node = createNodeWithParent(rootNode); - auto node2 = createNodeWithParent(rootNode); - ON_CALL(resourceManagementMock, removeProperty(property)) - .WillByDefault(Return(ModelResourceSet{{node, node2}, {property}, {}})); - - EXPECT_CALL(viewMock, nodeRemoved(Eq(node), _, _)); - EXPECT_CALL(viewMock, nodeRemoved(Eq(node2), _, _)); - - rootNode.removeProperty("foo"); -} - -TEST_F(Model, ModelNodeRemovePropertyIsCallingAbstractViewNodeRemovedWithValidNodes) -{ - auto property = createProperty(rootNode, "foo"); - auto node = createNodeWithParent(rootNode); - auto node2 = createNodeWithParent(rootNode); - ON_CALL(resourceManagementMock, removeProperty(property)) - .WillByDefault(Return(ModelResourceSet{{node, node2, ModelNode{}}, {property}, {}})); - - EXPECT_CALL(viewMock, nodeRemoved(Eq(node), _, _)); - EXPECT_CALL(viewMock, nodeRemoved(Eq(node2), _, _)); - - rootNode.removeProperty("foo"); -} - -TEST_F(Model, ModelNodeRemovePropertyIsCallingAbstractViewPropertiesAboutToBeRemoved) -{ - auto property = createProperty(rootNode, "yi"); - auto property2 = createProperty(rootNode, "er"); - ON_CALL(resourceManagementMock, removeProperty(property)) - .WillByDefault(Return(ModelResourceSet{{}, {property, property2}, {}})); - - EXPECT_CALL(viewMock, propertiesAboutToBeRemoved(ElementsAre(Eq(property)))); - EXPECT_CALL(viewMock, propertiesAboutToBeRemoved(ElementsAre(Eq(property2)))); - - rootNode.removeProperty("yi"); -} - -TEST_F(Model, ModelNodeRemovePropertyIsCallingAbstractViewPropertiesRemoved) -{ - auto property = createProperty(rootNode, "yi"); - auto property2 = createProperty(rootNode, "er"); - ON_CALL(resourceManagementMock, removeProperty(property)) - .WillByDefault(Return(ModelResourceSet{{}, {property, property2}, {}})); - - EXPECT_CALL(viewMock, propertiesRemoved(ElementsAre(Eq(property)))); - EXPECT_CALL(viewMock, propertiesRemoved(ElementsAre(Eq(property2)))); - - rootNode.removeProperty("yi"); -} - -TEST_F(Model, ModelNodeRemovePropertyIsCallingAbstractViewPropertiesRemovedOnlyWithValidProperties) -{ - auto property = createProperty(rootNode, "yi"); - auto property2 = createProperty(rootNode, "er"); - ON_CALL(resourceManagementMock, removeProperty(property)) - .WillByDefault(Return(ModelResourceSet{{}, {property, property2, {}}, {}})); - - EXPECT_CALL(viewMock, propertiesRemoved(ElementsAre(Eq(property)))); - EXPECT_CALL(viewMock, propertiesRemoved(ElementsAre(Eq(property2)))); - - rootNode.removeProperty("yi"); -} - -TEST_F(Model, ModelNodeRemovePropertyIsCallingAbstractViewBindingPropertiesAboutToBeChanged) -{ - auto property = createProperty(rootNode, "yi"); - auto property1 = rootNode.bindingProperty("foo"); - auto property2 = rootNode.bindingProperty("bar"); - ON_CALL(resourceManagementMock, removeProperty(property)) - .WillByDefault( - Return(ModelResourceSet{{}, {property}, {{property1, "yi"}, {property2, "er"}}})); - - EXPECT_CALL(viewMock, bindingPropertiesAboutToBeChanged(ElementsAre(Eq(property1)))); - EXPECT_CALL(viewMock, bindingPropertiesAboutToBeChanged(ElementsAre(Eq(property2)))); - - rootNode.removeProperty("yi"); -} - -TEST_F(Model, ModelNodeRemovePropertyIsCallingAbstractViewBindingPropertiesChanged) -{ - auto property = createProperty(rootNode, "yi"); - auto property1 = rootNode.bindingProperty("foo"); - auto property2 = rootNode.bindingProperty("bar"); - ON_CALL(resourceManagementMock, removeProperty(property)) - .WillByDefault( - Return(ModelResourceSet{{}, {property}, {{property1, "yi"}, {property2, "er"}}})); - - EXPECT_CALL(viewMock, bindingPropertiesChanged(ElementsAre(Eq(property1)), _)); - EXPECT_CALL(viewMock, bindingPropertiesChanged(ElementsAre(Eq(property2)), _)); - - rootNode.removeProperty("yi"); -} - -TEST_F(Model, - ModelNodeRemovePropertyIsCallingAbstractViewBindingPropertiesChangedOnlyWithValidProperties) -{ - auto property = createProperty(rootNode, "yi"); - auto property1 = rootNode.bindingProperty("foo"); - auto property2 = rootNode.bindingProperty("bar"); - ON_CALL(resourceManagementMock, removeProperty(property)) - .WillByDefault( - Return(ModelResourceSet{{}, {property}, {{property1, "yi"}, {property2, "er"}, {}}})); - - EXPECT_CALL(viewMock, bindingPropertiesChanged(ElementsAre(Eq(property1)), _)); - EXPECT_CALL(viewMock, bindingPropertiesChanged(ElementsAre(Eq(property2)), _)); - - rootNode.removeProperty("yi"); -} - -TEST_F(Model, ByDefaultRemoveModelNodeRemovesNode) -{ - model.detachView(&viewMock); - QmlDesigner::Model newModel{projectStorageMock, "QtQuick.Item"}; - newModel.attachView(&viewMock); - auto node = createNodeWithParent(viewMock.rootModelNode()); - - EXPECT_CALL(viewMock, nodeAboutToBeRemoved(Eq(node))); - - node.destroy(); -} - -TEST_F(Model, ByDefaultRemovePropertiesRemovesProperty) -{ - model.detachView(&viewMock); - QmlDesigner::Model newModel{projectStorageMock, "QtQuick.Item"}; - newModel.attachView(&viewMock); - rootNode = viewMock.rootModelNode(); - auto property = createProperty(rootNode, "yi"); - - EXPECT_CALL(viewMock, propertiesAboutToBeRemoved(ElementsAre(Eq(property)))); - - rootNode.removeProperty("yi"); -} - -TEST_F(Model, ByDefaultRemoveModelNodeInFactoryMethodCallsRemovesNode) -{ - model.detachView(&viewMock); - auto newModel = QmlDesigner::Model::create(projectStorageMock, "QtQuick.Item"); - newModel->attachView(&viewMock); - auto node = createNodeWithParent(viewMock.rootModelNode()); - - EXPECT_CALL(viewMock, nodeAboutToBeRemoved(Eq(node))); - - node.destroy(); -} - -TEST_F(Model, ByDefaultRemovePropertiesInFactoryMethodCallsRemoveProperty) -{ - model.detachView(&viewMock); - auto newModel = QmlDesigner::Model::create(projectStorageMock, "QtQuick.Item"); - newModel->attachView(&viewMock); - rootNode = viewMock.rootModelNode(); - auto property = createProperty(rootNode, "yi"); - - EXPECT_CALL(viewMock, propertiesAboutToBeRemoved(ElementsAre(Eq(property)))); - - rootNode.removeProperty("yi"); -} - -} // namespace diff --git a/tests/unit/unittest/processcreator-test.cpp b/tests/unit/unittest/processcreator-test.cpp deleted file mode 100644 index 2aa3a615004..00000000000 --- a/tests/unit/unittest/processcreator-test.cpp +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (C) 2016 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 - -#include "googletest.h" - -#include "eventspy.h" - -#include -#include -#include - -#include - -#include - -#include - -using testing::NotNull; - -using ClangBackEnd::ProcessCreator; -using ClangBackEnd::ProcessException; -using ClangBackEnd::ProcessStartedEvent; - -namespace { - -class ProcessCreator : public testing::Test -{ -protected: - void SetUp(); - -protected: - ::ProcessCreator processCreator; - QStringList m_arguments = {QStringLiteral("connectionName")}; -}; - -TEST_F(ProcessCreator, ProcessIsNotNull) -{ - auto future = processCreator.createProcess(); - auto process = future.get(); - - ASSERT_THAT(process.get(), NotNull()); -} - -TEST_F(ProcessCreator, ProcessIsRunning) -{ - auto future = processCreator.createProcess(); - auto process = future.get(); - - ASSERT_THAT(process->state(), QProcess::Running); -} - -TEST_F(ProcessCreator, ProcessPathIsNotExisting) -{ - processCreator.setProcessPath(Utils::HostOsInfo::withExecutableSuffix(ECHOSERVER"fail")); - - auto future = processCreator.createProcess(); - ASSERT_THROW(future.get(), ProcessException); -} - -TEST_F(ProcessCreator, ProcessStartIsSucessfull) -{ - auto future = processCreator.createProcess(); - ASSERT_NO_THROW(future.get()); -} - -TEST_F(ProcessCreator, ProcessObserverGetsEvent) -{ - EventSpy eventSpy(ProcessStartedEvent::ProcessStarted); - processCreator.setObserver(&eventSpy); - auto future = processCreator.createProcess(); - - eventSpy.waitForEvent(); -} - -TEST_F(ProcessCreator, TemporayPathIsSetForDefaultInitialization) -{ - QString path = processCreator.temporaryDirectory().path(); - - ASSERT_THAT(path.size(), Gt(0)); -} - -TEST_F(ProcessCreator, TemporayPathIsResetted) -{ - std::string oldPath = processCreator.temporaryDirectory().path().toStdString(); - - processCreator.resetTemporaryDirectory(); - - ASSERT_THAT(processCreator.temporaryDirectory().path().toStdString(), - AllOf(Not(IsEmpty()), Ne(oldPath))); -} - -void ProcessCreator::SetUp() -{ - processCreator.setTemporaryDirectoryPattern("process-XXXXXXX"); - processCreator.resetTemporaryDirectory(); - processCreator.setProcessPath(Utils::HostOsInfo::withExecutableSuffix(ECHOSERVER)); - processCreator.setArguments(m_arguments); -} -} diff --git a/tests/unit/unittest/projectstoragemock.cpp b/tests/unit/unittest/projectstoragemock.cpp deleted file mode 100644 index 8e4928377f4..00000000000 --- a/tests/unit/unittest/projectstoragemock.cpp +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (C) 2023 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 - -#include "projectstoragemock.h" - -namespace QmlDesigner { -namespace { - -template -void incrementBasicId(BasicId &id) -{ - id = BasicId::create(id.internalId() + 1); -} - -ModuleId createModule(ProjectStorageMock &mock, Utils::SmallStringView moduleName) -{ - static ModuleId moduleId; - incrementBasicId(moduleId); - - ON_CALL(mock, moduleId(Eq(moduleName))).WillByDefault(Return(moduleId)); - - return moduleId; -} - -TypeId createType(ProjectStorageMock &mock, - ModuleId moduleId, - Utils::SmallStringView typeName, - Utils::SmallString defaultPropertyName, - Storage::TypeTraits typeTraits, - TypeId baseTypeId = TypeId{}) -{ - static TypeId typeId; - incrementBasicId(typeId); - - static PropertyDeclarationId defaultPropertyId; - incrementBasicId(defaultPropertyId); - - ON_CALL(mock, typeId(Eq(moduleId), Eq(typeName), _)).WillByDefault(Return(typeId)); - ON_CALL(mock, type(Eq(typeId))) - .WillByDefault(Return(Storage::Info::Type{defaultPropertyId, typeTraits})); - ON_CALL(mock, propertyName(Eq(defaultPropertyId))).WillByDefault(Return(defaultPropertyName)); - - if (baseTypeId) - ON_CALL(mock, isBasedOn(Eq(typeId), Eq(baseTypeId))).WillByDefault(Return(true)); - - return typeId; -} - -TypeId createObject(ProjectStorageMock &mock, - ModuleId moduleId, - Utils::SmallStringView typeName, - Utils::SmallString defaultPropertyName, - TypeId baseTypeId = TypeId{}) -{ - return createType( - mock, moduleId, typeName, defaultPropertyName, Storage::TypeTraits::Reference, baseTypeId); -} -void setupIsBasedOn(ProjectStorageMock &mock) -{ - auto call = [&](TypeId typeId, auto... ids) -> bool { - return (mock.isBasedOn(typeId, ids) || ...); - }; - ON_CALL(mock, isBasedOn(_, _, _)).WillByDefault(call); - ON_CALL(mock, isBasedOn(_, _, _, _)).WillByDefault(call); - ON_CALL(mock, isBasedOn(_, _, _, _, _)).WillByDefault(call); - ON_CALL(mock, isBasedOn(_, _, _, _, _, _)).WillByDefault(call); - ON_CALL(mock, isBasedOn(_, _, _, _, _, _, _)).WillByDefault(call); - ON_CALL(mock, isBasedOn(_, _, _, _, _, _, _, _)).WillByDefault(call); -} - -} // namespace -} // namespace QmlDesigner - -void ProjectStorageMock::setupQtQtuick() -{ - QmlDesigner::setupIsBasedOn(*this); - - auto qmlModuleId = QmlDesigner::createModule(*this, "QML"); - auto qtQmlModelsModuleId = QmlDesigner::createModule(*this, "QtQml.Models"); - auto qtQuickModuleId = QmlDesigner::createModule(*this, "QtQuick"); - - auto qtObjectId = QmlDesigner::createObject(*this, qmlModuleId, "QtObject", "children"); - - QmlDesigner::createObject(*this, qtQmlModelsModuleId, "ListModel", "children", qtObjectId); - QmlDesigner::createObject(*this, qtQmlModelsModuleId, "ListElement", "children", qtObjectId); - - auto itemId = QmlDesigner::createObject(*this, qtQuickModuleId, "Item", "data", qtObjectId); - QmlDesigner::createObject(*this, qtQuickModuleId, "ListView", "data", itemId); -} diff --git a/tests/unit/unittest/projectstoragesqlitefunctionregistry-test.cpp b/tests/unit/unittest/projectstoragesqlitefunctionregistry-test.cpp deleted file mode 100644 index 8f272bc775e..00000000000 --- a/tests/unit/unittest/projectstoragesqlitefunctionregistry-test.cpp +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (C) 2021 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 - -#include "googletest.h" - -#include - -namespace { - -class ProjectStorageSqliteFunctionRegistry : public testing::Test -{ -protected: - Sqlite::Database database{":memory:", Sqlite::JournalMode::Memory}; - QmlDesigner::ProjectStorageSqliteFunctionRegistry registry{database}; -}; - -TEST_F(ProjectStorageSqliteFunctionRegistry, ReturnsUnqualifiedType) -{ - std::lock_guard lock{database}; - Sqlite::ReadStatement<1> statement{"SELECT unqualifiedTypeName('Foo.Bar')", database}; - - auto typeName = statement.value(); - - ASSERT_THAT(typeName, Eq("Bar")); -} - -TEST_F(ProjectStorageSqliteFunctionRegistry, ReturnsWholeStringIfNotDotIsFound) -{ - std::lock_guard lock{database}; - Sqlite::ReadStatement<1> statement{"SELECT unqualifiedTypeName('Foo_Bar')", database}; - - auto typeName = statement.value(); - - ASSERT_THAT(typeName, Eq("Foo_Bar")); -} - -TEST_F(ProjectStorageSqliteFunctionRegistry, ReturnEmptyStringForEmptyInput) -{ - std::lock_guard lock{database}; - Sqlite::ReadStatement<1> statement{"SELECT unqualifiedTypeName('')", database}; - - auto typeName = statement.value(); - - ASSERT_THAT(typeName, IsEmpty()); -} - -TEST_F(ProjectStorageSqliteFunctionRegistry, ThrowsErrorForInteger) -{ - std::lock_guard lock{database}; - Sqlite::ReadStatement<1> statement("SELECT unqualifiedTypeName(1)", database); - - ASSERT_THROW(statement.value(), Sqlite::StatementHasError); -} - -TEST_F(ProjectStorageSqliteFunctionRegistry, ThrowsErrorForFloat) -{ - std::lock_guard lock{database}; - Sqlite::ReadStatement<1> statement("SELECT unqualifiedTypeName(1.4)", database); - - ASSERT_THROW(statement.value(), Sqlite::StatementHasError); -} - -TEST_F(ProjectStorageSqliteFunctionRegistry, ThrowsErrorForBlob) -{ - std::lock_guard lock{database}; - Sqlite::ReadStatement<1> statement("SELECT unqualifiedTypeName(x'0500')", database); - - ASSERT_THROW(statement.value(), Sqlite::StatementHasError); -} - -TEST_F(ProjectStorageSqliteFunctionRegistry, ThrowsErrorForNull) -{ - std::lock_guard lock{database}; - Sqlite::ReadStatement<1> statement("SELECT unqualifiedTypeName(NULL)", database); - - ASSERT_THROW(statement.value(), Sqlite::StatementHasError); -} - -TEST_F(ProjectStorageSqliteFunctionRegistry, ThrowsErrorForNoArgument) -{ - std::lock_guard lock{database}; - - ASSERT_THROW(Sqlite::ReadStatement<1> statement("SELECT unqualifiedTypeName()", database), - Sqlite::StatementHasError); -} - -TEST_F(ProjectStorageSqliteFunctionRegistry, ThrowsErrorForToManyArgument) -{ - std::lock_guard lock{database}; - - ASSERT_THROW(Sqlite::ReadStatement<1> statement("SELECT unqualifiedTypeName('foo', 'bar')", - database), - Sqlite::StatementHasError); -} -} // namespace diff --git a/tests/unit/unittest/qmlprojectmanager/projectitem-test.cpp b/tests/unit/unittest/qmlprojectmanager/projectitem-test.cpp deleted file mode 100644 index 294c2e9d77a..00000000000 --- a/tests/unit/unittest/qmlprojectmanager/projectitem-test.cpp +++ /dev/null @@ -1,539 +0,0 @@ -// Copyright (C) 2023 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 - -#include "googletest.h" // IWYU pragma: keep -#include "google-using-declarations.h" - -#include - -#include -namespace { - -constexpr QLatin1String localTestDataDir{UNITTEST_DIR "/qmlprojectmanager/data"}; - -class QmlProjectItem : public testing::Test -{ -protected: - static void SetUpTestSuite() - { - projectItemEmpty = std::make_unique( - Utils::FilePath::fromString(localTestDataDir + "/getter-setter/empty.qmlproject"), true); - - projectItemNotEmpty = std::make_unique( - Utils::FilePath::fromString(localTestDataDir + "/getter-setter/notEmpty.qmlproject"), - true); - - projectItemFileFilters = std::make_unique( - Utils::FilePath::fromString(localTestDataDir + "/file-filters/MaterialBundle.qmlproject"), - true); - } - - static void TearDownTestSuite() - { - projectItemEmpty.reset(); - projectItemNotEmpty.reset(); - projectItemFileFilters.reset(); - } - -protected: - static inline std::unique_ptr projectItemEmpty; - static inline std::unique_ptr projectItemNotEmpty; - std::unique_ptr - projectItemSetters = std::make_unique( - Utils::FilePath::fromString(localTestDataDir + "/getter-setter/empty.qmlproject"), true); - static inline std::unique_ptr projectItemFileFilters; -}; - -auto createAbsoluteFilePaths(const QStringList &fileList) -{ - return Utils::transform(fileList, [](const QString &fileName) { - return Utils::FilePath::fromString(localTestDataDir + "/file-filters").pathAppended(fileName); - }); -} - -TEST_F(QmlProjectItem, GetNotEmptyMainFileProject) -{ - auto mainFile = projectItemNotEmpty->mainFile(); - - ASSERT_THAT(mainFile, Eq(u"content/App.qml")); -} - -TEST_F(QmlProjectItem, GetNotEmptyMainUIFileProject) -{ - auto mainUiFile = projectItemNotEmpty->mainUiFile(); - - ASSERT_THAT(mainUiFile, Eq(u"Screen01.ui.qml")); -} - -TEST_F(QmlProjectItem, GetNotEmptyMcuProject) -{ - auto isMcuProject = projectItemNotEmpty->isQt4McuProject(); - - ASSERT_TRUE(isMcuProject); -} - -TEST_F(QmlProjectItem, GetNotEmptyQtVersion) -{ - auto qtVersion = projectItemNotEmpty->versionQt(); - - ASSERT_THAT(qtVersion, Eq(u"6")); -} - -TEST_F(QmlProjectItem, GetNotEmptyQtQuickVersion) -{ - auto qtQuickVersion = projectItemNotEmpty->versionQtQuick(); - - ASSERT_THAT(qtQuickVersion, Eq(u"6.2")); -} - -TEST_F(QmlProjectItem, GetNotEmptyDesignStudioVersion) -{ - auto designStudioVersion = projectItemNotEmpty->versionDesignStudio(); - - ASSERT_THAT(designStudioVersion, Eq(u"3.9")); -} - -TEST_F(QmlProjectItem, GetNotEmptySourceDirectory) -{ - auto sourceDirectory = projectItemNotEmpty->sourceDirectory().path(); - - auto expectedSourceDir = localTestDataDir + "/getter-setter"; - - ASSERT_THAT(sourceDirectory, Eq(expectedSourceDir)); -} - -TEST_F(QmlProjectItem, GetNotEmptyTarGetNotEmptyDirectory) -{ - auto targetDirectory = projectItemNotEmpty->targetDirectory(); - - ASSERT_THAT(targetDirectory, Eq(u"/opt/targetDirectory")); -} - -TEST_F(QmlProjectItem, GetNotEmptyImportPaths) -{ - auto importPaths = projectItemNotEmpty->importPaths(); - - ASSERT_THAT(importPaths, UnorderedElementsAre(u"imports", u"asset_imports")); -} - -TEST_F(QmlProjectItem, GetNotEmptyFileSelectors) -{ - auto fileSelectors = projectItemNotEmpty->fileSelectors(); - - ASSERT_THAT(fileSelectors, UnorderedElementsAre(u"WXGA", u"darkTheme", u"ShowIndicator")); -} - -TEST_F(QmlProjectItem, GetNotEmptyMultiLanguageSupport) -{ - auto multilanguageSupport = projectItemNotEmpty->multilanguageSupport(); - - ASSERT_TRUE(multilanguageSupport); -} - -TEST_F(QmlProjectItem, GetNotEmptySupportedLanguages) -{ - auto supportedLanguages = projectItemNotEmpty->supportedLanguages(); - - ASSERT_THAT(supportedLanguages, UnorderedElementsAre(u"en", u"fr")); -} - -TEST_F(QmlProjectItem, GetNotEmptyPrimaryLanguage) -{ - auto primaryLanguage = projectItemNotEmpty->primaryLanguage(); - ; - - ASSERT_THAT(primaryLanguage, Eq(u"en")); -} - -TEST_F(QmlProjectItem, GetNotEmptyWidgetApp) -{ - auto widgetApp = projectItemNotEmpty->widgetApp(); - - ASSERT_TRUE(widgetApp); -} - -TEST_F(QmlProjectItem, GetNotEmptyFileList) -{ - QStringList fileList; - for (const auto &file : projectItemNotEmpty->files()) { - fileList.append(file.path()); - } - - auto expectedFileList = localTestDataDir + "/getter-setter/qtquickcontrols2.conf"; - - ASSERT_THAT(fileList, UnorderedElementsAre(expectedFileList)); -} - -TEST_F(QmlProjectItem, GetNotEmptyShaderToolArgs) -{ - auto shaderToolArgs = projectItemNotEmpty->shaderToolArgs(); - - ASSERT_THAT(shaderToolArgs, - UnorderedElementsAre(u"-s", u"--glsl", u"\"100 es,120,150\"", u"--hlsl", u"50", u"--msl", u"12")); -} - -TEST_F(QmlProjectItem, GetNotEmptyShaderToolFiles) -{ - auto shaderToolFiles = projectItemNotEmpty->shaderToolFiles(); - - ASSERT_THAT(shaderToolFiles, UnorderedElementsAre(u"content/shaders/*")); -} - -TEST_F(QmlProjectItem, GetNotEmptyEnvironment) -{ - auto env = projectItemNotEmpty->environment(); - - ASSERT_THAT(env, - UnorderedElementsAre( - Utils::EnvironmentItem("QT_QUICK_CONTROLS_CONF", "qtquickcontrols2.conf"))); -} - -TEST_F(QmlProjectItem, GetNotEmptyForceFreeType) -{ - auto forceFreeType = projectItemNotEmpty->forceFreeType(); - - ASSERT_TRUE(forceFreeType); -} - -TEST_F(QmlProjectItem, GetEmptyMainFileProject) -{ - auto mainFile = projectItemEmpty->mainFile(); - - ASSERT_THAT(mainFile, IsEmpty()); -} - -TEST_F(QmlProjectItem, GetEmptyMainUIFileProject) -{ - auto mainUiFile = projectItemEmpty->mainUiFile(); - - ASSERT_THAT(mainUiFile, IsEmpty()); -} - -TEST_F(QmlProjectItem, GetEmptyMcuProject) -{ - auto isMcuProject = projectItemEmpty->isQt4McuProject(); - - ASSERT_FALSE(isMcuProject); -} - -TEST_F(QmlProjectItem, GetEmptyQtVersion) -{ - auto qtVersion = projectItemEmpty->versionQt(); - - // default Qt Version is "5" for Design Studio projects - ASSERT_THAT(qtVersion, Eq(u"5")); -} - -TEST_F(QmlProjectItem, GetEmptyQtQuickVersion) -{ - auto qtQuickVersion = projectItemEmpty->versionQtQuick(); - - ASSERT_THAT(projectItemEmpty->versionQtQuick(), IsEmpty()); -} - -TEST_F(QmlProjectItem, GetEmptyDesignStudioVersion) -{ - auto designStudioVersion = projectItemEmpty->versionDesignStudio(); - - ASSERT_THAT(projectItemEmpty->versionDesignStudio(), IsEmpty()); -} - -TEST_F(QmlProjectItem, GetEmptySourceDirectory) -{ - auto sourceDirectory = projectItemEmpty->sourceDirectory().path(); - - auto expectedSourceDir = localTestDataDir + "/getter-setter"; - - // default source directory is the project directory - ASSERT_THAT(sourceDirectory, Eq(expectedSourceDir)); -} - -TEST_F(QmlProjectItem, GetEmptyTarGetEmptyDirectory) -{ - auto targetDirectory = projectItemEmpty->targetDirectory(); - - ASSERT_THAT(targetDirectory, IsEmpty()); -} - -TEST_F(QmlProjectItem, GetEmptyImportPaths) -{ - auto importPaths = projectItemEmpty->importPaths(); - - ASSERT_THAT(importPaths, IsEmpty()); -} - -TEST_F(QmlProjectItem, GetEmptyFileSelectors) -{ - auto fileSelectors = projectItemEmpty->fileSelectors(); - - ASSERT_THAT(fileSelectors, IsEmpty()); -} - -TEST_F(QmlProjectItem, GetEmptyMultiLanguageSupport) -{ - auto multilanguageSupport = projectItemEmpty->multilanguageSupport(); - - ASSERT_FALSE(multilanguageSupport); -} - -TEST_F(QmlProjectItem, GetEmptySupportedLanguages) -{ - auto supportedLanguages = projectItemEmpty->supportedLanguages(); - - ASSERT_THAT(supportedLanguages, IsEmpty()); -} - -TEST_F(QmlProjectItem, GetEmptyPrimaryLanguage) -{ - auto primaryLanguage = projectItemEmpty->primaryLanguage(); - - ASSERT_THAT(primaryLanguage, IsEmpty()); -} - -TEST_F(QmlProjectItem, GetEmptyWidgetApp) -{ - auto widgetApp = projectItemEmpty->widgetApp(); - - ASSERT_FALSE(widgetApp); -} - -TEST_F(QmlProjectItem, GetEmptyFileList) -{ - auto fileList = projectItemEmpty->files(); - - ASSERT_THAT(fileList, IsEmpty()); -} - -TEST_F(QmlProjectItem, GetEmptyShaderToolArgs) -{ - auto shaderToolArgs = projectItemEmpty->shaderToolArgs(); - - ASSERT_THAT(shaderToolArgs, IsEmpty()); -} - -TEST_F(QmlProjectItem, GetEmptyShaderToolFiles) -{ - auto shaderToolFiles = projectItemEmpty->shaderToolFiles(); - - ASSERT_THAT(shaderToolFiles, IsEmpty()); -} - -TEST_F(QmlProjectItem, GetEmptyEnvironment) -{ - auto env = projectItemEmpty->environment(); - - ASSERT_THAT(env, IsEmpty()); -} - -TEST_F(QmlProjectItem, GetEmptyForceFreeType) -{ - auto forceFreeType = projectItemEmpty->forceFreeType(); - - ASSERT_FALSE(forceFreeType); -} - -TEST_F(QmlProjectItem, SetMainFileProject) -{ - projectItemSetters->setMainFile("testing"); - - auto mainFile = projectItemSetters->mainFile(); - - ASSERT_THAT(mainFile, Eq(u"testing")); -} - -TEST_F(QmlProjectItem, SetMainUIFileProject) -{ - projectItemSetters->setMainUiFile("testing"); - - auto mainUiFile = projectItemSetters->mainUiFile(); - - ASSERT_THAT(mainUiFile, Eq(u"testing")); -} - -TEST_F(QmlProjectItem, SetImportPaths) -{ - projectItemSetters->setImportPaths({"testing"}); - - auto importPaths = projectItemSetters->importPaths(); - - ASSERT_THAT(importPaths, UnorderedElementsAre(u"testing")); -} - -TEST_F(QmlProjectItem, AddImportPaths) -{ - projectItemSetters->setImportPaths({}); - projectItemSetters->addImportPath("testing"); - - auto importPaths = projectItemSetters->importPaths(); - - ASSERT_THAT(importPaths, UnorderedElementsAre(u"testing")); -} - -TEST_F(QmlProjectItem, SetFileSelectors) -{ - projectItemSetters->setFileSelectors({"testing"}); - - auto fileSelectors = projectItemSetters->fileSelectors(); - - ASSERT_THAT(fileSelectors, UnorderedElementsAre(u"testing")); -} - -TEST_F(QmlProjectItem, AddFileSelectors) -{ - projectItemSetters->setFileSelectors({}); - projectItemSetters->addFileSelector("testing"); - - auto fileSelectors = projectItemSetters->fileSelectors(); - - ASSERT_THAT(fileSelectors, UnorderedElementsAre(u"testing")); -} - -TEST_F(QmlProjectItem, SetMultiLanguageSupport) -{ - projectItemSetters->setMultilanguageSupport(true); - - auto multilanguageSupport = projectItemSetters->multilanguageSupport(); - - ASSERT_TRUE(multilanguageSupport); -} - -TEST_F(QmlProjectItem, SetSupportedLanguages) -{ - projectItemSetters->setSupportedLanguages({"testing"}); - - auto supportedLanguages = projectItemSetters->supportedLanguages(); - - ASSERT_THAT(supportedLanguages, UnorderedElementsAre(u"testing")); -} - -TEST_F(QmlProjectItem, AddSupportedLanguages) -{ - projectItemSetters->setSupportedLanguages({}); - projectItemSetters->addSupportedLanguage("testing"); - - auto supportedLanguages = projectItemSetters->supportedLanguages(); - - ASSERT_THAT(supportedLanguages, UnorderedElementsAre(u"testing")); -} - -TEST_F(QmlProjectItem, SetPrimaryLanguage) -{ - projectItemSetters->setPrimaryLanguage("testing"); - - auto primaryLanguage = projectItemSetters->primaryLanguage(); - ; - - ASSERT_THAT(primaryLanguage, Eq(u"testing")); -} - -TEST_F(QmlProjectItem, SetWidgetApp) -{ - projectItemSetters->setWidgetApp(true); - - auto widgetApp = projectItemSetters->widgetApp(); - - ASSERT_TRUE(widgetApp); -} - -TEST_F(QmlProjectItem, SetShaderToolArgs) -{ - projectItemSetters->setShaderToolArgs({"testing"}); - - auto shaderToolArgs = projectItemSetters->shaderToolArgs(); - - ASSERT_THAT(shaderToolArgs, UnorderedElementsAre(u"testing")); -} - -TEST_F(QmlProjectItem, AddShaderToolArgs) -{ - projectItemSetters->setShaderToolArgs({}); - projectItemSetters->addShaderToolArg("testing"); - - auto shaderToolArgs = projectItemSetters->shaderToolArgs(); - - ASSERT_THAT(shaderToolArgs, UnorderedElementsAre(u"testing")); -} - -TEST_F(QmlProjectItem, SetShaderToolFiles) -{ - projectItemSetters->setShaderToolFiles({"testing"}); - - auto shaderToolFiles = projectItemSetters->shaderToolFiles(); - - ASSERT_THAT(shaderToolFiles, UnorderedElementsAre(u"testing")); -} - -TEST_F(QmlProjectItem, AddShaderToolFiles) -{ - projectItemSetters->setShaderToolFiles({}); - projectItemSetters->addShaderToolFile("testing"); - - auto shaderToolFiles = projectItemSetters->shaderToolFiles(); - - ASSERT_THAT(shaderToolFiles, UnorderedElementsAre(u"testing")); -} - -TEST_F(QmlProjectItem, AddEnvironment) -{ - projectItemSetters->addToEnviroment("testing", "testing"); - auto envs = projectItemSetters->environment(); - - Utils::EnvironmentItems expectedEnvs; - expectedEnvs.push_back({"testing", "testing"}); - - ASSERT_EQ(envs, expectedEnvs); -} - -TEST_F(QmlProjectItem, SetForceFreeTypeTrue) -{ - projectItemSetters->setForceFreeType(true); - - ASSERT_EQ(projectItemSetters->forceFreeType(), true); -} - -TEST_F(QmlProjectItem, SetForceFreeTypeFalse) -{ - projectItemSetters->setForceFreeType(false); - - ASSERT_EQ(projectItemSetters->forceFreeType(), false); -} - -TEST_F(QmlProjectItem, SetQtVersion) -{ - projectItemSetters->setVersionQt("6"); - - ASSERT_EQ(projectItemSetters->versionQt().toStdString(), "6"); -} - -TEST_F(QmlProjectItem, SetQtQuickVersion) -{ - projectItemSetters->setVersionQtQuick("6"); - - ASSERT_EQ(projectItemSetters->versionQtQuick(), "6"); -} - -TEST_F(QmlProjectItem, SetDesignStudioVersion) -{ - projectItemSetters->setVersionDesignStudio("6"); - - ASSERT_EQ(projectItemSetters->versionDesignStudio(), "6"); -} - -// TODO: We should move this one into the integration tests -TEST_F(QmlProjectItem, TestFileFilters) -{ - // GIVEN - auto fileListPath = Utils::FilePath::fromString(localTestDataDir + "/file-filters/filelist.txt"); - QStringList fileNameList = QString::fromUtf8(fileListPath.fileContents().value()) - .replace("\r\n", "\n") - .split("\n"); - auto expectedAbsoluteFilePaths = createAbsoluteFilePaths(fileNameList); - - // WHEN - auto filePaths = projectItemFileFilters->files(); - - // THEN - ASSERT_THAT(filePaths, UnorderedElementsAreArray(expectedAbsoluteFilePaths)); -} - -} // namespace