diff --git a/dist/changelog/changes-11.0.0.md b/dist/changelog/changes-11.0.0.md index 5600390c091..32860826363 100644 --- a/dist/changelog/changes-11.0.0.md +++ b/dist/changelog/changes-11.0.0.md @@ -14,6 +14,7 @@ General ------- * Added a `Terminal` view (QTCREATORBUG-8511) + ([Documentation](https://doc-snapshots.qt.io/qtcreator-11.0/creator-output-panes.html#terminal)) * Opt-out via `Preferences` > `Terminal` preferences * Added support for * different shells, colors, fonts, and multiple tabs @@ -53,6 +54,7 @@ Editing * Added experimental support for GitHub Copilot ([GitHub documentation](https://github.com/features/copilot)) + ([Qt Creator documentation](https://doc-snapshots.qt.io/qtcreator-11.0/creator-copilot.html)) * Added missing actions for opening the `Call Hierarchy` (QTCREATORBUG-28839, QTCREATORBUG-28842) diff --git a/doc/qtcreator/images/qtcreator-options-environment-interface.png b/doc/qtcreator/images/qtcreator-options-environment-interface.png deleted file mode 100644 index 41374d1b5dc..00000000000 Binary files a/doc/qtcreator/images/qtcreator-options-environment-interface.png and /dev/null differ diff --git a/doc/qtcreator/images/qtcreator-preferences-environment-interface.webp b/doc/qtcreator/images/qtcreator-preferences-environment-interface.webp new file mode 100644 index 00000000000..d6d5098bc63 Binary files /dev/null and b/doc/qtcreator/images/qtcreator-preferences-environment-interface.webp differ diff --git a/doc/qtcreator/images/qtcreator-python-install.webp b/doc/qtcreator/images/qtcreator-python-install.webp new file mode 100644 index 00000000000..519c4b79d62 Binary files /dev/null and b/doc/qtcreator/images/qtcreator-python-install.webp differ diff --git a/doc/qtcreator/images/qtcreator-python-wizard-define-python-interpreter.webp b/doc/qtcreator/images/qtcreator-python-wizard-define-python-interpreter.webp new file mode 100644 index 00000000000..8621040267a Binary files /dev/null and b/doc/qtcreator/images/qtcreator-python-wizard-define-python-interpreter.webp differ diff --git a/doc/qtcreator/images/qtcreator-terminal-python.webp b/doc/qtcreator/images/qtcreator-terminal-python.webp new file mode 100644 index 00000000000..30fd14cd818 Binary files /dev/null and b/doc/qtcreator/images/qtcreator-terminal-python.webp differ diff --git a/doc/qtcreator/src/editors/creator-coding-edit-mode.qdoc b/doc/qtcreator/src/editors/creator-coding-edit-mode.qdoc index 82d3530d2bc..fb7cc429f43 100644 --- a/doc/qtcreator/src/editors/creator-coding-edit-mode.qdoc +++ b/doc/qtcreator/src/editors/creator-coding-edit-mode.qdoc @@ -29,6 +29,12 @@ \if defined(qtcreator) \image qtcreator-editortoolbar-symbols.webp {Edit mode toolbar} + + To add more space around the toolbar items, select \uicontrol Edit > + \uicontrol Preferences > \uicontrol Environment > \uicontrol Interface, and + then select \uicontrol Relaxed in the \uicontrol {Toolbar style} field. + + \image qtcreator-preferences-environment-interface.webp {Interface tab in Environment preferences} \else \image studio-edit-mode.png \endif diff --git a/doc/qtcreator/src/editors/creator-coding.qdoc b/doc/qtcreator/src/editors/creator-coding.qdoc index 23fd888d576..e7b44dd57e4 100644 --- a/doc/qtcreator/src/editors/creator-coding.qdoc +++ b/doc/qtcreator/src/editors/creator-coding.qdoc @@ -85,6 +85,13 @@ \l{https://github.com/features/copilot}{GitHub Copilot} into \QC. You can view suggestions from Copilot in the code editor. + \li \l{Developing Qt for Python Applications} + + To support developing Qt for Python applications, \QC lets you + set up Qt for Python, use project wizards to create Qt for + Python applications, write Python code, and run and debug the + applications. + \li \l{Editing MIME Types} \QC uses the MIME type of a file to determine which mode and editor diff --git a/doc/qtcreator/src/editors/creator-only/creator-copilot.qdoc b/doc/qtcreator/src/editors/creator-only/creator-copilot.qdoc index 16dcf80d4bf..69f3a35454e 100644 --- a/doc/qtcreator/src/editors/creator-only/creator-copilot.qdoc +++ b/doc/qtcreator/src/editors/creator-only/creator-copilot.qdoc @@ -4,7 +4,7 @@ /*! \previouspage creator-language-servers.html \page creator-copilot.html - \nextpage creator-mime-types.html + \nextpage creator-python-development.html \title Using GitHub Copilot diff --git a/doc/qtcreator/src/editors/creator-only/creator-mime-types.qdoc b/doc/qtcreator/src/editors/creator-only/creator-mime-types.qdoc index 662b3c0fa20..17fb6d32768 100644 --- a/doc/qtcreator/src/editors/creator-only/creator-mime-types.qdoc +++ b/doc/qtcreator/src/editors/creator-only/creator-mime-types.qdoc @@ -8,7 +8,7 @@ // ********************************************************************** /*! - \previouspage creator-copilot.html + \previouspage creator-python-development.html \page creator-mime-types.html \nextpage creator-modeling.html diff --git a/doc/qtcreator/src/howto/creator-keyboard-shortcuts.qdoc b/doc/qtcreator/src/howto/creator-keyboard-shortcuts.qdoc index c763d587ae6..62d34751441 100644 --- a/doc/qtcreator/src/howto/creator-keyboard-shortcuts.qdoc +++ b/doc/qtcreator/src/howto/creator-keyboard-shortcuts.qdoc @@ -58,7 +58,7 @@ in context menus} check box indicates whether the platform default value is \c on or \c off. - \image qtcreator-options-environment-interface.png "Interface tab in the Environment preferences" + \image qtcreator-preferences-environment-interface.webp {Interface tab in Environment preferences} \section1 Configuring Keyboard Shortcuts diff --git a/doc/qtcreator/src/python/creator-python-development.qdoc b/doc/qtcreator/src/python/creator-python-development.qdoc new file mode 100644 index 00000000000..75865bd6798 --- /dev/null +++ b/doc/qtcreator/src/python/creator-python-development.qdoc @@ -0,0 +1,96 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only + +/*! + \page creator-python-development.html + \previouspage creator-copilot.html + \nextpage creator-mime-types.html + + \title Developing Qt for Python Applications + + \l {https://doc.qt.io/qtforpython/index.html}{Qt for Python} enables you + to use Qt 6 API in Python applications. You can use the PySide6 modules + to gain access to individual Qt modules, such as \l {Qt Core}, \l {Qt GUI}, + and \l {Qt Widgets}. + + The following sections describe using \QC for developing with Qt for Python: + + \list + \li \l{Creating Widget-Based Qt for Python Applications} + {Creating Qt for Python Applications} + \li \l{Setting Up PySide6} + \li \l{Selecting the Python Interpreter} + \li \l{Creating a Virtual Environment} + \li \l{Using Python Interactive Shell} + \li \l{Python Language Server} + \li \l{Running Python Projects} + \li \l{Specifying Run Settings for Python Projects} + \li \l{PDB} + \li \l{Launching the Debugger} + \endlist + + For more information about developing with Qt for Python, including + limitations, see \l {https://doc.qt.io/qtforpython/index.html} + {Qt for Python}. + + \section1 Setting Up PySide6 + + If you have not installed the required version of PySide6, \QC prompts you to + do so when you open a .py file. + + \image qtcreator-python-install.webp {Prompts to install PySide6 and Python language server} + + Further, \QC prompts you to install the \l {Python Language Server} + {Python language server} that offers services such as code completion + and annotations. Select \uicontrol Install to install PySide6 and the + language server. + + \section1 Selecting the Python Interpreter + + You select the initial Python interpreter when you use the Qt for Python + Application wizard templates to create Python projects. + + \image qtcreator-python-wizard-define-python-interpreter.webp {Define Python Interpreter wizard page} + + You can see the current Python interpreter on the \uicontrol Edit mode + toolbar. + + \image qtcreator-python-interpreter-edit-mode.webp {Python interpreter on the Edit mode toolbar} + + You can change the interpreter to use for a particular project in + \uicontrol Projects > \uicontrol Run > \uicontrol Interpreter. + + \image qtcreator-python-run-settings.png {Python run settings} + + To see the available interpreters and choose another interpreter, select the + current interpreter, and then select \uicontrol {Manage Python Interpreters}. + Or, select \uicontrol Edit > \uicontrol Preferences > \uicontrol Python > + \uicontrol Interpreters. + + \image qtcreator-python-interpreters.png {Python Interpreters in Preferences} + + You can add and remove interpreters and clean up references to interpreters + that you uninstalled, but that still appear in the list. In addition, you + can set the interpreter to use by default. + + \section1 Creating a Virtual Environment + + To create a virtual environment (\c venv) when you use the Qt for + Python Application wizard templates to create Python projects, select + the \uicontrol {Create new virtual environment} check box on the + \uicontrol {Define Python Interpreter} wizard page. Specify the + directory where to create the environment in + \uicontrol {Path to virtual environment}. + + \section1 Using Python Interactive Shell + + You can write Python code in the Edit mode. Select \uicontrol REPL on the + toolbar to start the \l{https://pythonprogramminglanguage.com/repl/} + {Python interactive shell} in the \l Terminal pane. + + \image qtcreator-terminal-python.webp {Python shell on the taskbar} + + To start the shell and import the current file as a module, select + \uicontrol {REPL Import File}. To also import all functions from + the file, select \uicontrol {REPL Import *}. +*/ diff --git a/doc/qtcreator/src/python/creator-python-project.qdocinc b/doc/qtcreator/src/python/creator-python-project.qdocinc index 0ef6bb2d3fd..80887fc9788 100644 --- a/doc/qtcreator/src/python/creator-python-project.qdocinc +++ b/doc/qtcreator/src/python/creator-python-project.qdocinc @@ -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 /*! @@ -6,38 +6,12 @@ \section2 Creating Widget-Based Qt for Python Applications - \l {https://doc.qt.io/qtforpython/index.html}{Qt for Python} enables you - to use Qt 6 API in Python applications. You can use the PySide6 modules - to gain access to individual Qt modules, such as \l {Qt Core}, \l {Qt GUI}, - and \l {Qt Widgets}. - - If you have not installed PySide6, \QC prompts you to install it after - you create the project. Further, it prompts you to install the - \l {Python Language Server}{Python language server} that offers services - such as code completion and annotations. Select \uicontrol Install to install - PySide6 and the language server. - - You can see the current Python interpreter on the \uicontrol Edit mode - toolbar. - - \image qtcreator-python-interpreter-edit-mode.webp {Python interpreter on the Edit mode toolbar} - - To see the available interpreters and change their paths, select - the interpreter, and then select \uicontrol {Manage Python Interpreters}. - Or, select \uicontrol Edit > \uicontrol Preferences > \uicontrol Python > - \uicontrol Interpreters. - - \image qtcreator-python-interpreters.png {Python Interpreters in Preferences} - - You can add and remove interpreters and clean up references to interpreters - that you uninstalled, but that still appear in the list. In addition, you - can set the interpreter to use by default. - The Qt for Python Application wizards generate a \c {.pyproject} file that - lists the files in the Python project and a \c {.py} file that has - some boilerplate code. In addition, the widget-based UI wizard creates a - \c {.ui} file that has a \QD form, and the Qt Quick Application wizard - creates a \c {.qml} file that has Qt Quick controls. + lists the files in the \l{Developing Qt for Python Applications}{Python} + project and a \c {.py} file that has some boilerplate code. In addition, the + widget-based UI wizard creates a \c {.ui} file that has a \QD form, and the + Qt Quick Application wizard creates a \c {.qml} file that imports Qt Quick + controls. The \c{.pyproject} files are JSON-based configuration files that replace the previously used \c {.pyqtc} configuration files. You can still open and @@ -49,7 +23,7 @@ the PySide version, class name, base class, and source file for the class. - \image qtcreator-python-wizard-app-window.png {Qt for Python wizard for creating a widget-based UI} + \image qtcreator-python-wizard-app-window.png {Define Class wizard page} The wizard adds the imports to the source file for access to the QApplication, the base class you selected in the Qt @@ -121,13 +95,8 @@ \endcode You can now modify the boilerplate code in the Edit mode to develop your - Python application. Select \uicontrol REPL on the toolbar to start the - \l{https://pythonprogramminglanguage.com/repl/}{Python interactive shell}. - To start the shell and import the current file as a module, select - \uicontrol {REPL Import File}. To also import all functions from - the file, select \uicontrol {REPL Import *}. - - Always regenerate the Python code after modifying a UI file. + Python application. Always regenerate the Python code after modifying a + UI file. Open the .ui file in the \uicontrol Design mode to create a widget-based UI in \QD. diff --git a/doc/qtcreator/src/python/creator-python-run.qdocinc b/doc/qtcreator/src/python/creator-python-run.qdocinc index d1f96a7eeba..2356607a837 100644 --- a/doc/qtcreator/src/python/creator-python-run.qdocinc +++ b/doc/qtcreator/src/python/creator-python-run.qdocinc @@ -23,7 +23,7 @@ You can specify settings for running Qt for Python applications: - \image qtcreator-python-run-settings.png + \image qtcreator-python-run-settings.png {Python run settings} \list \li In the \uicontrol Interpreter field, specify the path to the diff --git a/doc/qtcreator/src/qtcreator-toc.qdoc b/doc/qtcreator/src/qtcreator-toc.qdoc index 3215f402708..b9649bb2b4b 100644 --- a/doc/qtcreator/src/qtcreator-toc.qdoc +++ b/doc/qtcreator/src/qtcreator-toc.qdoc @@ -131,6 +131,7 @@ \li \l{Editing Markdown Files} \li \l{Using Language Servers} \li \l{Using GitHub Copilot} + \li \l{Developing Qt for Python Applications} \li \l{Editing MIME Types} \li \l{Modeling} \li \l{Editing State Charts} diff --git a/doc/qtcreator/src/user-interface/creator-ui.qdoc b/doc/qtcreator/src/user-interface/creator-ui.qdoc index c4ba6cad417..031e15cedbc 100644 --- a/doc/qtcreator/src/user-interface/creator-ui.qdoc +++ b/doc/qtcreator/src/user-interface/creator-ui.qdoc @@ -143,7 +143,7 @@ > \uicontrol Environment, and then select a theme in the \uicontrol Theme field. - \image qtcreator-options-environment-interface.png "Interface preferences" + \image qtcreator-preferences-environment-interface.webp {Interface preferences} \section1 Changing Languages @@ -452,7 +452,7 @@ \uicontrol Preferences > \uicontrol Environment > \uicontrol Interface, and then select the codec in the \uicontrol {Text codec for tools} field. - \image qtcreator-options-environment-interface.png "Interface tab in the Environment preferences" + \image qtcreator-preferences-environment-interface.webp {Interface tab in Environment preferences} \section1 Finding and Filtering Output diff --git a/doc/qtdesignstudio/config/qtdesignstudio.qdocconf b/doc/qtdesignstudio/config/qtdesignstudio.qdocconf index f9722725e87..5bcfe70d400 100644 --- a/doc/qtdesignstudio/config/qtdesignstudio.qdocconf +++ b/doc/qtdesignstudio/config/qtdesignstudio.qdocconf @@ -51,6 +51,7 @@ excludedirs += ../../qtcreator/examples/accelbubble \ ../../qtcreator/src/meson \ ../../qtcreator/src/overview/creator-only \ ../../qtcreator/src/projects \ + ../../qtcreator/src/python \ ../../qtcreator/src/qnx \ ../../qtcreator/src/qtquick/creator-only \ ../../qtcreator/src/vcs/creator-only \ diff --git a/src/app/main.cpp b/src/app/main.cpp index ec401522928..e6a7bdcd7ec 100644 --- a/src/app/main.cpp +++ b/src/app/main.cpp @@ -586,7 +586,7 @@ int main(int argc, char **argv) QCoreApplication::setOrganizationName(QLatin1String(Core::Constants::IDE_SETTINGSVARIANT_STR)); QGuiApplication::setApplicationDisplayName(Core::Constants::IDE_DISPLAY_NAME); - auto cleanup = qScopeGuard([] { Utils::Singleton::deleteAll(); }); + const QScopeGuard cleanup([] { Utils::Singleton::deleteAll(); }); const QStringList pluginArguments = app.arguments(); diff --git a/src/libs/3rdparty/cplusplus/Lexer.cpp b/src/libs/3rdparty/cplusplus/Lexer.cpp index fc1b72cb7db..deafe432b6a 100644 --- a/src/libs/3rdparty/cplusplus/Lexer.cpp +++ b/src/libs/3rdparty/cplusplus/Lexer.cpp @@ -25,7 +25,7 @@ #include "cppassert.h" -#include +#include #include @@ -756,9 +756,9 @@ void Lexer::scanStringLiteral(Token *tok, unsigned char hint) void Lexer::scanRawStringLiteral(Token *tok, unsigned char hint) { - Utils::ExecuteOnDestruction suffixCleaner; - if (!control()) - suffixCleaner.reset([this] { _expectedRawStringSuffix.clear(); }); + QScopeGuard cleanup([this] { _expectedRawStringSuffix.clear(); }); + if (control()) + cleanup.dismiss(); const char *yytext = _currentChar; @@ -827,7 +827,7 @@ void Lexer::scanRawStringLiteral(Token *tok, unsigned char hint) tok->f.kind = T_RAW_STRING_LITERAL; if (!control() && !closed) { - suffixCleaner.reset([]{}); + cleanup.dismiss(); s._tokenKind = tok->f.kind; _expectedRawStringSuffix.prepend(')'); _expectedRawStringSuffix.append('"'); diff --git a/src/libs/advanceddockingsystem/dockwidgettab.cpp b/src/libs/advanceddockingsystem/dockwidgettab.cpp index 4531e0da2da..1775da373f4 100644 --- a/src/libs/advanceddockingsystem/dockwidgettab.cpp +++ b/src/libs/advanceddockingsystem/dockwidgettab.cpp @@ -187,7 +187,7 @@ namespace ADS void DockWidgetTabPrivate::moveTab(QMouseEvent *event) { event->accept(); - QPoint distance = event->globalPos() - m_globalDragStartMousePosition; + QPoint distance = event->globalPosition().toPoint() - m_globalDragStartMousePosition; distance.setY(0); auto targetPos = distance + m_tabDragStartPosition; targetPos.rx() = qMax(targetPos.x(), 0); @@ -294,7 +294,7 @@ namespace ADS { if (event->button() == Qt::LeftButton) { event->accept(); - d->saveDragStartMousePosition(event->globalPos()); + d->saveDragStartMousePosition(event->globalPosition().toPoint()); d->m_dragState = DraggingMousePressed; emit clicked(); return; @@ -314,7 +314,7 @@ namespace ADS case DraggingTab: // End of tab moving, emit signal if (d->m_dockArea) { - emit moved(event->globalPos()); + emit moved(event->globalPosition().toPoint()); } break; @@ -354,7 +354,7 @@ namespace ADS auto mappedPos = mapToParent(event->pos()); bool mouseOutsideBar = (mappedPos.x() < 0) || (mappedPos.x() > parentWidget()->rect().right()); // Maybe a fixed drag distance is better here ? - int dragDistanceY = qAbs(d->m_globalDragStartMousePosition.y() - event->globalPos().y()); + int dragDistanceY = qAbs(d->m_globalDragStartMousePosition.y() - event->globalPosition().toPoint().y()); if (dragDistanceY >= DockManager::startDragDistance() || mouseOutsideBar) { // If this is the last dock area in a dock container with only // one single dock widget it does not make sense to move it to a new @@ -382,7 +382,7 @@ namespace ADS } return; } else if (d->m_dockArea->openDockWidgetsCount() > 1 - && (event->globalPos() - d->m_globalDragStartMousePosition).manhattanLength() + && (event->globalPosition().toPoint() - d->m_globalDragStartMousePosition).manhattanLength() >= QApplication::startDragDistance()) // Wait a few pixels before start moving { // If we start dragging the tab, we save its initial position to @@ -502,7 +502,7 @@ namespace ADS // sense to move it to a new floating widget and leave this one empty if ((!d->m_dockArea->dockContainer()->isFloating() || d->m_dockArea->dockWidgetsCount() > 1) && d->m_dockWidget->features().testFlag(DockWidget::DockWidgetFloatable)) { - d->saveDragStartMousePosition(event->globalPos()); + d->saveDragStartMousePosition(event->globalPosition().toPoint()); d->startFloating(DraggingInactive); } diff --git a/src/libs/cplusplus/pp-engine.cpp b/src/libs/cplusplus/pp-engine.cpp index ef27d9eace8..f4e8dbdbd0c 100644 --- a/src/libs/cplusplus/pp-engine.cpp +++ b/src/libs/cplusplus/pp-engine.cpp @@ -30,7 +30,6 @@ #include #include -#include #include #include @@ -40,6 +39,7 @@ #include #include #include +#include #include #include @@ -1513,14 +1513,15 @@ bool Preprocessor::collectActualArguments(PPToken *tk, QVector Q_ASSERT(tk); Q_ASSERT(actuals); - ExecuteOnDestruction removeBlockedName; - if (m_state.m_tokenBuffer) { - removeBlockedName.reset([this] { - if (m_state.m_tokenBuffer && !m_state.m_tokenBuffer->blockedMacroNames.empty()) - m_state.m_tokenBuffer->blockedMacroNames.pop_back(); - }); + QScopeGuard cleanup([this] { + if (m_state.m_tokenBuffer && !m_state.m_tokenBuffer->blockedMacroNames.empty()) + m_state.m_tokenBuffer->blockedMacroNames.pop_back(); + }); + + if (m_state.m_tokenBuffer) m_state.m_tokenBuffer->blockedMacroNames.push_back(parentMacroName); - } + else + cleanup.dismiss(); lex(tk); // consume the identifier diff --git a/src/libs/extensionsystem/pluginmanager.cpp b/src/libs/extensionsystem/pluginmanager.cpp index b567d753250..45b9807958e 100644 --- a/src/libs/extensionsystem/pluginmanager.cpp +++ b/src/libs/extensionsystem/pluginmanager.cpp @@ -10,6 +10,17 @@ #include "pluginspec.h" #include "pluginspec_p.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + #include #include #include @@ -23,23 +34,12 @@ #include #include #include +#include #include #include #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - #ifdef WITH_TESTS #include #include @@ -1268,8 +1268,7 @@ void PluginManagerPrivate::startTests() continue; // plugin not loaded const QVector testObjects = plugin->createTestObjects(); - ExecuteOnDestruction deleteTestObjects([&]() { qDeleteAll(testObjects); }); - Q_UNUSED(deleteTestObjects) + const QScopeGuard cleanup([&] { qDeleteAll(testObjects); }); const bool hasDuplicateTestObjects = testObjects.size() != Utils::filteredUnique(testObjects).size(); diff --git a/src/libs/qmleditorwidgets/contextpanewidget.cpp b/src/libs/qmleditorwidgets/contextpanewidget.cpp index 8d675bf95b1..93d124b6a5d 100644 --- a/src/libs/qmleditorwidgets/contextpanewidget.cpp +++ b/src/libs/qmleditorwidgets/contextpanewidget.cpp @@ -44,7 +44,7 @@ DragWidget::DragWidget(QWidget *parent) : QFrame(parent) void DragWidget::mousePressEvent(QMouseEvent * event) { if (event->button() == Qt::LeftButton) { - m_startPos = event->globalPos() - parentWidget()->mapToGlobal((pos())); + m_startPos = event->globalPosition().toPoint() - parentWidget()->mapToGlobal((pos())); m_opacityEffect = new QGraphicsOpacityEffect; setGraphicsEffect(m_opacityEffect); event->accept(); @@ -77,7 +77,7 @@ void DragWidget::mouseMoveEvent(QMouseEvent * event) { if (event->buttons() & Qt::LeftButton) { if (m_startPos != QPoint(-1, -1)) { - QPoint newPos = parentWidget()->mapFromGlobal(event->globalPos() - m_startPos); + QPoint newPos = parentWidget()->mapFromGlobal(event->globalPosition().toPoint() - m_startPos); newPos.setX(limit(newPos.x(), 20, parentWidget()->width() - 20 - width())); newPos.setY(limit(newPos.y(), 2, parentWidget()->height() - 20 - height())); diff --git a/src/libs/qmljs/qmljscheck.cpp b/src/libs/qmljs/qmljscheck.cpp index 51be467387d..78d93fb6c5d 100644 --- a/src/libs/qmljs/qmljscheck.cpp +++ b/src/libs/qmljs/qmljscheck.cpp @@ -649,6 +649,7 @@ QList Check::defaultDisabledMessages() HintBinaryOperatorSpacing, HintOneStatementPerLine, HintExtraParentheses, + WarnAliasReferRootHierarchy, // QmlDesigner related WarnImperativeCodeNotEditableInVisualDesigner, @@ -748,6 +749,7 @@ void Check::enableQmlDesignerChecks() enableMessage(WarnReferenceToParentItemNotSupportedByVisualDesigner); enableMessage(ErrUnsupportedRootTypeInVisualDesigner); enableMessage(ErrInvalidIdeInVisualDesigner); + enableMessage(WarnAliasReferRootHierarchy); //## triggers too often ## check.enableMessage(StaticAnalysis::WarnUndefinedValueForVisualDesigner); } diff --git a/src/libs/solutions/tasking/CMakeLists.txt b/src/libs/solutions/tasking/CMakeLists.txt index f70c910e042..926343e9c8b 100644 --- a/src/libs/solutions/tasking/CMakeLists.txt +++ b/src/libs/solutions/tasking/CMakeLists.txt @@ -5,7 +5,9 @@ add_qtc_library(Tasking OBJECT SOURCES barrier.cpp barrier.h concurrentcall.h - networkquery.cpp networkquery.h + networkquery.cpp tasking_global.h tasktree.cpp tasktree.h + EXPLICIT_MOC + networkquery.h ) diff --git a/src/libs/solutions/tasking/tasktree.cpp b/src/libs/solutions/tasking/tasktree.cpp index 2a4c7cefd98..43a47121b2a 100644 --- a/src/libs/solutions/tasking/tasktree.cpp +++ b/src/libs/solutions/tasking/tasktree.cpp @@ -1750,9 +1750,9 @@ TaskTree::TaskTree() { } -TaskTree::TaskTree(const Group &root) : TaskTree() +TaskTree::TaskTree(const Group &recipe) : TaskTree() { - setupRoot(root); + setRecipe(recipe); } TaskTree::~TaskTree() @@ -1763,27 +1763,27 @@ TaskTree::~TaskTree() delete d; } -void TaskTree::setupRoot(const Group &root) +void TaskTree::setRecipe(const Group &recipe) { QTC_ASSERT(!isRunning(), qWarning("The TaskTree is already running, ignoring..."); return); - QTC_ASSERT(!d->m_guard.isLocked(), qWarning("The setupRoot() is called from one of the" - "TaskTree handlers, ingoring..."); return); + QTC_ASSERT(!d->m_guard.isLocked(), qWarning("The setRecipe() is called from one of the" + "TaskTree handlers, ignoring..."); return); d->m_storages.clear(); - d->m_root.reset(new TaskNode(d, root, nullptr)); + d->m_root.reset(new TaskNode(d, recipe, nullptr)); } void TaskTree::start() { QTC_ASSERT(!isRunning(), qWarning("The TaskTree is already running, ignoring..."); return); QTC_ASSERT(!d->m_guard.isLocked(), qWarning("The start() is called from one of the" - "TaskTree handlers, ingoring..."); return); + "TaskTree handlers, ignoring..."); return); d->start(); } void TaskTree::stop() { QTC_ASSERT(!d->m_guard.isLocked(), qWarning("The stop() is called from one of the" - "TaskTree handlers, ingoring..."); return); + "TaskTree handlers, ignoring..."); return); d->stop(); } diff --git a/src/libs/solutions/tasking/tasktree.h b/src/libs/solutions/tasking/tasktree.h index dcd7b86ac18..11cc2708dd4 100644 --- a/src/libs/solutions/tasking/tasktree.h +++ b/src/libs/solutions/tasking/tasktree.h @@ -378,10 +378,10 @@ class TASKING_EXPORT TaskTree final : public QObject public: TaskTree(); - TaskTree(const Group &root); + TaskTree(const Group &recipe); ~TaskTree(); - void setupRoot(const Group &root); + void setRecipe(const Group &recipe); void start(); void stop(); diff --git a/src/libs/utils/CMakeLists.txt b/src/libs/utils/CMakeLists.txt index aa6a3e199e6..a0ec62ac244 100644 --- a/src/libs/utils/CMakeLists.txt +++ b/src/libs/utils/CMakeLists.txt @@ -43,7 +43,6 @@ add_qtc_library(Utils environmentfwd.h environmentmodel.cpp environmentmodel.h execmenu.cpp execmenu.h - executeondestruction.h expected.h externalterminalprocessimpl.cpp externalterminalprocessimpl.h fadingindicator.cpp fadingindicator.h diff --git a/src/libs/utils/aspects.cpp b/src/libs/utils/aspects.cpp index 999385e1ca9..5ba4922d668 100644 --- a/src/libs/utils/aspects.cpp +++ b/src/libs/utils/aspects.cpp @@ -2347,7 +2347,7 @@ void IntegersAspect::setDefaultValue(const QList &value) */ TextDisplay::TextDisplay(AspectContainer *container) - : BaseAspect(container) + : BaseAspect(container), d(new Internal::TextDisplayPrivate) {} /*! diff --git a/src/libs/utils/basetreeview.cpp b/src/libs/utils/basetreeview.cpp index 3ccbf1f86e8..14d17257841 100644 --- a/src/libs/utils/basetreeview.cpp +++ b/src/libs/utils/basetreeview.cpp @@ -587,7 +587,7 @@ ItemViewEvent::ItemViewEvent(QEvent *ev, QAbstractItemView *view) case QEvent::DragEnter: case QEvent::DragMove: case QEvent::Drop: - m_pos = static_cast(ev)->pos(); + m_pos = static_cast(ev)->position().toPoint(); m_index = view->indexAt(m_pos); break; default: diff --git a/src/libs/utils/deviceshell.cpp b/src/libs/utils/deviceshell.cpp index f96c5da8f2d..99ddecdeec9 100644 --- a/src/libs/utils/deviceshell.cpp +++ b/src/libs/utils/deviceshell.cpp @@ -8,7 +8,6 @@ #include "qtcassert.h" #include -#include Q_LOGGING_CATEGORY(deviceShellLog, "qtc.utils.deviceshell", QtWarningMsg) diff --git a/src/libs/utils/differ.cpp b/src/libs/utils/differ.cpp index 9dc2ce8454e..f929efbeeb0 100644 --- a/src/libs/utils/differ.cpp +++ b/src/libs/utils/differ.cpp @@ -24,8 +24,8 @@ namespace Utils { static int commonPrefix(const QString &text1, const QString &text2) { int i = 0; - const int text1Count = text1.count(); - const int text2Count = text2.count(); + const int text1Count = text1.size(); + const int text2Count = text2.size(); const int maxCount = qMin(text1Count, text2Count); while (i < maxCount) { if (text1.at(i) != text2.at(i)) @@ -38,8 +38,8 @@ static int commonPrefix(const QString &text1, const QString &text2) static int commonSuffix(const QString &text1, const QString &text2) { int i = 0; - const int text1Count = text1.count(); - const int text2Count = text2.count(); + const int text1Count = text1.size(); + const int text2Count = text2.size(); const int maxCount = qMin(text1Count, text2Count); while (i < maxCount) { if (text1.at(text1Count - i - 1) != text2.at(text2Count - i - 1)) @@ -52,8 +52,8 @@ static int commonSuffix(const QString &text1, const QString &text2) static int commonOverlap(const QString &text1, const QString &text2) { int i = 0; - const int text1Count = text1.count(); - const int text2Count = text2.count(); + const int text1Count = text1.size(); + const int text2Count = text2.size(); const int maxCount = qMin(text1Count, text2Count); while (i < maxCount) { if (QStringView(text1).mid(text1Count - maxCount + i) == QStringView(text2).left(maxCount - i)) @@ -66,7 +66,7 @@ static int commonOverlap(const QString &text1, const QString &text2) static QList decode(const QList &diffList, const QStringList &lines) { QList newDiffList; - newDiffList.reserve(diffList.count()); + newDiffList.reserve(diffList.size()); for (const Diff &diff : diffList) { QString text; for (QChar c : diff.text) { @@ -80,7 +80,7 @@ static QList decode(const QList &diffList, const QStringList &lines) static QList squashEqualities(const QList &diffList) { - if (diffList.count() < 3) // we need at least 3 items + if (diffList.size() < 3) // we need at least 3 items return diffList; QList newDiffList; @@ -88,20 +88,20 @@ static QList squashEqualities(const QList &diffList) Diff thisDiff = diffList.at(1); Diff nextDiff = diffList.at(2); int i = 2; - while (i < diffList.count()) { + while (i < diffList.size()) { if (prevDiff.command == Diff::Equal && nextDiff.command == Diff::Equal) { if (thisDiff.text.endsWith(prevDiff.text)) { thisDiff.text = prevDiff.text - + thisDiff.text.left(thisDiff.text.count() - - prevDiff.text.count()); + + thisDiff.text.left(thisDiff.text.size() + - prevDiff.text.size()); nextDiff.text = prevDiff.text + nextDiff.text; } else if (thisDiff.text.startsWith(nextDiff.text)) { prevDiff.text += nextDiff.text; - thisDiff.text = thisDiff.text.mid(nextDiff.text.count()) + thisDiff.text = thisDiff.text.mid(nextDiff.text.size()) + nextDiff.text; i++; - if (i < diffList.count()) + if (i < diffList.size()) nextDiff = diffList.at(i); newDiffList.append(prevDiff); } else { @@ -113,11 +113,11 @@ static QList squashEqualities(const QList &diffList) prevDiff = thisDiff; thisDiff = nextDiff; i++; - if (i < diffList.count()) + if (i < diffList.size()) nextDiff = diffList.at(i); } newDiffList.append(prevDiff); - if (i == diffList.count()) + if (i == diffList.size()) newDiffList.append(thisDiff); return newDiffList; } @@ -132,9 +132,9 @@ static QList cleanupOverlaps(const QList &diffList) // DEL(XXXXABC), INS(DEFXXXX) -> INS(DEF), EQ(XXXX), DEL(ABC) QList newDiffList; int i = 0; - while (i < diffList.count()) { + while (i < diffList.size()) { Diff thisDiff = diffList.at(i); - Diff nextDiff = i < diffList.count() - 1 + Diff nextDiff = i < diffList.size() - 1 ? diffList.at(i + 1) : Diff(Diff::Equal); if (thisDiff.command == Diff::Delete @@ -142,9 +142,9 @@ static QList cleanupOverlaps(const QList &diffList) const int delInsOverlap = commonOverlap(thisDiff.text, nextDiff.text); const int insDelOverlap = commonOverlap(nextDiff.text, thisDiff.text); if (delInsOverlap >= insDelOverlap) { - if (delInsOverlap > thisDiff.text.count() / 2 - || delInsOverlap > nextDiff.text.count() / 2) { - thisDiff.text = thisDiff.text.left(thisDiff.text.count() - delInsOverlap); + if (delInsOverlap > thisDiff.text.size() / 2 + || delInsOverlap > nextDiff.text.size() / 2) { + thisDiff.text = thisDiff.text.left(thisDiff.text.size() - delInsOverlap); const Diff equality(Diff::Equal, nextDiff.text.left(delInsOverlap)); nextDiff.text = nextDiff.text.mid(delInsOverlap); newDiffList.append(thisDiff); @@ -155,9 +155,9 @@ static QList cleanupOverlaps(const QList &diffList) newDiffList.append(nextDiff); } } else { - if (insDelOverlap > thisDiff.text.count() / 2 - || insDelOverlap > nextDiff.text.count() / 2) { - nextDiff.text = nextDiff.text.left(nextDiff.text.count() - insDelOverlap); + if (insDelOverlap > thisDiff.text.size() / 2 + || insDelOverlap > nextDiff.text.size() / 2) { + nextDiff.text = nextDiff.text.left(nextDiff.text.size() - insDelOverlap); const Diff equality(Diff::Equal, thisDiff.text.left(insDelOverlap)); thisDiff.text = thisDiff.text.mid(insDelOverlap); newDiffList.append(nextDiff); @@ -186,7 +186,7 @@ static int cleanupSemanticsScore(const QString &text1, const QString &text2) if (text1.isEmpty() || text2.isEmpty()) // Edges return 6; - const QChar char1 = text1[text1.count() - 1]; + const QChar char1 = text1[text1.size() - 1]; const QChar char2 = text2[0]; const bool nonAlphaNumeric1 = !char1.isLetterOrNumber(); const bool nonAlphaNumeric2 = !char2.isLetterOrNumber(); @@ -256,19 +256,19 @@ QList Differ::moveWhitespaceIntoEqualities(const QList &input) { QList output = input; - for (int i = 0; i < output.count(); i++) { + for (int i = 0; i < output.size(); i++) { Diff diff = output[i]; if (diff.command != Diff::Equal) { if (i > 0) { // check previous equality Diff &previousDiff = output[i - 1]; - const int previousDiffCount = previousDiff.text.count(); + const int previousDiffCount = previousDiff.text.size(); if (previousDiff.command == Diff::Equal && previousDiffCount && isWhitespace(previousDiff.text.at(previousDiffCount - 1))) { // previous diff ends with whitespace int j = 0; - while (j < diff.text.count()) { + while (j < diff.text.size()) { if (!isWhitespace(diff.text.at(j))) break; ++j; @@ -280,10 +280,10 @@ QList Differ::moveWhitespaceIntoEqualities(const QList &input) } } } - if (i < output.count() - 1) { // check next equality - const int diffCount = diff.text.count(); + if (i < output.size() - 1) { // check next equality + const int diffCount = diff.text.size(); Diff &nextDiff = output[i + 1]; - const int nextDiffCount = nextDiff.text.count(); + const int nextDiffCount = nextDiff.text.size(); if (nextDiff.command == Diff::Equal && nextDiffCount && (isWhitespace(nextDiff.text.at(0)) || isNewLine(nextDiff.text.at(0)))) { @@ -331,7 +331,7 @@ static QString encodeReducedWhitespace(const QString &input, int inputIndex = 0; int outputIndex = 0; - while (inputIndex < input.count()) { + while (inputIndex < input.size()) { QChar c = input.at(inputIndex); if (isWhitespace(c)) { @@ -339,7 +339,7 @@ static QString encodeReducedWhitespace(const QString &input, codeMap->insert(outputIndex, QString(c)); ++inputIndex; - while (inputIndex < input.count()) { + while (inputIndex < input.size()) { QChar reducedChar = input.at(inputIndex); if (!isWhitespace(reducedChar)) @@ -372,10 +372,10 @@ static QList decodeReducedWhitespace(const QList &input, auto it = codeMap.constBegin(); const auto itEnd = codeMap.constEnd(); for (Diff diff : input) { - const int diffCount = diff.text.count(); + const int diffCount = diff.text.size(); while ((it != itEnd) && (it.key() < counter + diffCount)) { const int reversePosition = diffCount + counter - it.key(); - const int updatedDiffCount = diff.text.count(); + const int updatedDiffCount = diff.text.size(); diff.text.replace(updatedDiffCount - reversePosition, 1, it.value()); ++it; } @@ -502,8 +502,8 @@ static QString encodeExpandedWhitespace(const QString &leftEquality, rightCodeMap->clear(); QString output; - const int leftCount = leftEquality.count(); - const int rightCount = rightEquality.count(); + const int leftCount = leftEquality.size(); + const int rightCount = rightEquality.size(); int leftIndex = 0; int rightIndex = 0; while (leftIndex < leftCount && rightIndex < rightCount) { @@ -534,8 +534,8 @@ static QString encodeExpandedWhitespace(const QString &leftEquality, } if (!leftWhitespaces.isEmpty() && !rightWhitespaces.isEmpty()) { - const int replacementPosition = output.count(); - const int replacementSize = qMax(leftWhitespaces.count(), rightWhitespaces.count()); + const int replacementPosition = output.size(); + const int replacementSize = qMax(leftWhitespaces.size(), rightWhitespaces.size()); const QString replacement(replacementSize, ' '); leftCodeMap->insert(replacementPosition, {replacementSize, leftWhitespaces}); rightCodeMap->insert(replacementPosition, {replacementSize, rightWhitespaces}); @@ -574,14 +574,14 @@ static QList decodeExpandedWhitespace(const QList &input, auto it = codeMap.constBegin(); const auto itEnd = codeMap.constEnd(); for (Diff diff : input) { - const int diffCount = diff.text.count(); + const int diffCount = diff.text.size(); while ((it != itEnd) && (it.key() < counter + diffCount)) { const int replacementSize = it.value().first; const int reversePosition = diffCount + counter - it.key(); if (reversePosition < replacementSize) return QList(); // replacement exceeds one Diff const QString replacement = it.value().second; - const int updatedDiffCount = diff.text.count(); + const int updatedDiffCount = diff.text.size(); diff.text.replace(updatedDiffCount - reversePosition, replacementSize, replacement); ++it; @@ -619,8 +619,8 @@ static bool diffWithWhitespaceExpandedInEqualities(const QList &leftInput, leftOutput->clear(); rightOutput->clear(); - const int leftCount = leftInput.count(); - const int rightCount = rightInput.count(); + const int leftCount = leftInput.size(); + const int rightCount = rightInput.size(); int l = 0; int r = 0; @@ -649,10 +649,10 @@ static bool diffWithWhitespaceExpandedInEqualities(const QList &leftInput, // join code map positions with common maps for (auto it = leftCodeMap.cbegin(), end = leftCodeMap.cend(); it != end; ++it) - commonLeftCodeMap.insert(leftText.count() + it.key(), it.value()); + commonLeftCodeMap.insert(leftText.size() + it.key(), it.value()); for (auto it = rightCodeMap.cbegin(), end = rightCodeMap.cend(); it != end; ++it) - commonRightCodeMap.insert(rightText.count() + it.key(), it.value()); + commonRightCodeMap.insert(rightText.size() + it.key(), it.value()); leftText.append(commonEquality); rightText.append(commonEquality); @@ -739,8 +739,8 @@ void Differ::ignoreWhitespaceBetweenEqualities(const QList &leftInput, leftOutput->clear(); rightOutput->clear(); - const int leftCount = leftInput.count(); - const int rightCount = rightInput.count(); + const int leftCount = leftInput.size(); + const int rightCount = rightInput.size(); int l = 0; int r = 0; @@ -836,8 +836,8 @@ void Differ::diffBetweenEqualities(const QList &leftInput, leftOutput->clear(); rightOutput->clear(); - const int leftCount = leftInput.count(); - const int rightCount = rightInput.count(); + const int leftCount = leftInput.size(); + const int rightCount = rightInput.size(); int l = 0; int r = 0; @@ -1000,8 +1000,8 @@ QList Differ::preprocess1AndDiff(const QString &text1, const QString &text const int suffixCount = commonSuffix(newText1, newText2); if (suffixCount) { suffix = newText1.right(suffixCount); - newText1 = newText1.left(newText1.count() - suffixCount); - newText2 = newText2.left(newText2.count() - suffixCount); + newText1 = newText1.left(newText1.size() - suffixCount); + newText2 = newText2.left(newText2.size() - suffixCount); } QList diffList = preprocess2AndDiff(newText1, newText2); if (prefixCount) @@ -1025,28 +1025,27 @@ QList Differ::preprocess2AndDiff(const QString &text1, const QString &text return diffList; } - if (text1.count() != text2.count()) - { - const QString longtext = text1.count() > text2.count() ? text1 : text2; - const QString shorttext = text1.count() > text2.count() ? text2 : text1; + if (text1.size() != text2.size()) { + const QString longtext = text1.size() > text2.size() ? text1 : text2; + const QString shorttext = text1.size() > text2.size() ? text2 : text1; const int i = longtext.indexOf(shorttext); if (i != -1) { - const Diff::Command command = (text1.count() > text2.count()) + const Diff::Command command = (text1.size() > text2.size()) ? Diff::Delete : Diff::Insert; diffList.append(Diff(command, longtext.left(i))); diffList.append(Diff(Diff::Equal, shorttext)); - diffList.append(Diff(command, longtext.mid(i + shorttext.count()))); + diffList.append(Diff(command, longtext.mid(i + shorttext.size()))); return diffList; } - if (shorttext.count() == 1) { + if (shorttext.size() == 1) { diffList.append(Diff(Diff::Delete, text1)); diffList.append(Diff(Diff::Insert, text2)); return diffList; } } - if (m_currentDiffMode != Differ::CharMode && text1.count() > 80 && text2.count() > 80) + if (m_currentDiffMode != Differ::CharMode && text1.size() > 80 && text2.size() > 80) return diffNonCharMode(text1, text2); return diffMyers(text1, text2); @@ -1054,8 +1053,8 @@ QList Differ::preprocess2AndDiff(const QString &text1, const QString &text QList Differ::diffMyers(const QString &text1, const QString &text2) { - const int n = text1.count(); - const int m = text2.count(); + const int n = text1.size(); + const int m = text2.size(); const bool odd = (n + m) % 2; const int D = odd ? (n + m) / 2 + 1 : (n + m) / 2; const int delta = n - m; @@ -1191,12 +1190,12 @@ QList Differ::diffNonCharMode(const QString &text1, const QString &text2) QString lastDelete; QString lastInsert; QList newDiffList; - for (int i = 0; i <= diffList.count(); i++) { + for (int i = 0; i <= diffList.size(); i++) { if (m_future && m_future->isCanceled()) { m_currentDiffMode = diffMode; return {}; } - const Diff diffItem = i < diffList.count() + const Diff diffItem = i < diffList.size() ? diffList.at(i) : Diff(Diff::Equal); // dummy, ensure we process to the end // even when diffList doesn't end with equality @@ -1240,14 +1239,14 @@ int Differ::findSubtextEnd(const QString &text, if (m_currentDiffMode == Differ::LineMode) { int subtextEnd = text.indexOf('\n', subtextStart); if (subtextEnd == -1) - subtextEnd = text.count() - 1; + subtextEnd = text.size() - 1; return ++subtextEnd; } else if (m_currentDiffMode == Differ::WordMode) { if (!text.at(subtextStart).isLetter()) return subtextStart + 1; int i = subtextStart + 1; - const int count = text.count(); + const int count = text.size(); while (i < count && text.at(i).isLetter()) i++; return i; @@ -1262,7 +1261,7 @@ QString Differ::encode(const QString &text, int subtextStart = 0; int subtextEnd = -1; QString codes; - while (subtextEnd < text.count()) { + while (subtextEnd < text.size()) { subtextEnd = findSubtextEnd(text, subtextStart); const QString line = text.mid(subtextStart, subtextEnd - subtextStart); subtextStart = subtextEnd; @@ -1271,8 +1270,8 @@ QString Differ::encode(const QString &text, codes += QChar(static_cast(lineToCode->value(line))); } else { lines->append(line); - lineToCode->insert(line, lines->count() - 1); - codes += QChar(static_cast(lines->count() - 1)); + lineToCode->insert(line, lines->size() - 1); + codes += QChar(static_cast(lines->size() - 1)); } } return codes; @@ -1283,8 +1282,8 @@ QList Differ::merge(const QList &diffList) QString lastDelete; QString lastInsert; QList newDiffList; - for (int i = 0; i <= diffList.count(); i++) { - Diff diff = i < diffList.count() + for (int i = 0; i <= diffList.size(); i++) { + Diff diff = i < diffList.size() ? diffList.at(i) : Diff(Diff::Equal); // dummy, ensure we process to the end // even when diffList doesn't end with equality @@ -1314,8 +1313,8 @@ QList Differ::merge(const QList &diffList) const int suffixCount = commonSuffix(lastDelete, lastInsert); if (suffixCount) { const QString suffix = lastDelete.right(suffixCount); - lastDelete = lastDelete.left(lastDelete.count() - suffixCount); - lastInsert = lastInsert.left(lastInsert.count() - suffixCount); + lastDelete = lastDelete.left(lastDelete.size() - suffixCount); + lastInsert = lastInsert.left(lastInsert.size() - suffixCount); diff.text.prepend(suffix); } @@ -1342,7 +1341,7 @@ QList Differ::merge(const QList &diffList) } QList squashedDiffList = squashEqualities(newDiffList); - if (squashedDiffList.count() != newDiffList.count()) + if (squashedDiffList.size() != newDiffList.size()) return merge(squashedDiffList); return squashedDiffList; @@ -1363,8 +1362,8 @@ QList Differ::cleanupSemantics(const QList &diffList) int inserts = 0; // equality index, equality data QList equalities; - for (int i = 0; i <= diffList.count(); i++) { - const Diff diff = i < diffList.count() + for (int i = 0; i <= diffList.size(); i++) { + const Diff diff = i < diffList.size() ? diffList.at(i) : Diff(Diff::Equal); // dummy, ensure we process to the end // even when diffList doesn't end with equality @@ -1374,10 +1373,10 @@ QList Differ::cleanupSemantics(const QList &diffList) previousData.deletesAfter = deletes; previousData.insertsAfter = inserts; } - if (i < diffList.count()) { // don't insert dummy + if (i < diffList.size()) { // don't insert dummy EqualityData data; data.equalityIndex = i; - data.textCount = diff.text.count(); + data.textCount = diff.text.size(); data.deletesBefore = deletes; data.insertsBefore = inserts; equalities.append(data); @@ -1386,15 +1385,15 @@ QList Differ::cleanupSemantics(const QList &diffList) } } else { if (diff.command == Diff::Delete) - deletes += diff.text.count(); + deletes += diff.text.size(); else if (diff.command == Diff::Insert) - inserts += diff.text.count(); + inserts += diff.text.size(); } } QMap equalitiesToBeSplit; int i = 0; - while (i < equalities.count()) { + while (i < equalities.size()) { const EqualityData &data = equalities.at(i); if (data.textCount <= qMax(data.deletesBefore, data.insertsBefore) && data.textCount <= qMax(data.deletesAfter, data.insertsAfter)) { @@ -1403,7 +1402,7 @@ QList Differ::cleanupSemantics(const QList &diffList) previousData.deletesAfter += data.textCount + data.deletesAfter; previousData.insertsAfter += data.textCount + data.insertsAfter; } - if (i < equalities.count() - 1) { + if (i < equalities.size() - 1) { EqualityData &nextData = equalities[i + 1]; nextData.deletesBefore += data.textCount + data.deletesBefore; nextData.insertsBefore += data.textCount + data.insertsBefore; @@ -1418,7 +1417,7 @@ QList Differ::cleanupSemantics(const QList &diffList) } QList newDiffList; - for (int i = 0; i < diffList.count(); i++) { + for (int i = 0; i < diffList.size(); i++) { const Diff &diff = diffList.at(i); if (equalitiesToBeSplit.contains(i)) { newDiffList.append(Diff(Diff::Delete, diff.text)); @@ -1433,7 +1432,7 @@ QList Differ::cleanupSemantics(const QList &diffList) QList Differ::cleanupSemanticsLossless(const QList &diffList) { - if (diffList.count() < 3) // we need at least 3 items + if (diffList.size() < 3) // we need at least 3 items return diffList; QList newDiffList; @@ -1441,7 +1440,7 @@ QList Differ::cleanupSemanticsLossless(const QList &diffList) Diff thisDiff = diffList.at(1); Diff nextDiff = diffList.at(2); int i = 2; - while (i < diffList.count()) { + while (i < diffList.size()) { if (prevDiff.command == Diff::Equal && nextDiff.command == Diff::Equal) { @@ -1453,9 +1452,9 @@ QList Differ::cleanupSemanticsLossless(const QList &diffList) // Shift the edit as far left as possible const int suffixCount = commonSuffix(equality1, edit); if (suffixCount) { - const QString commonString = edit.mid(edit.count() - suffixCount); - equality1 = equality1.left(equality1.count() - suffixCount); - edit = commonString + edit.left(edit.count() - suffixCount); + const QString commonString = edit.mid(edit.size() - suffixCount); + equality1 = equality1.left(equality1.size() - suffixCount); + edit = commonString + edit.left(edit.size() - suffixCount); equality2 = commonString + equality2; } @@ -1488,7 +1487,7 @@ QList Differ::cleanupSemanticsLossless(const QList &diffList) newDiffList.append(prevDiff); // append modified equality1 if (bestEquality2.isEmpty()) { i++; - if (i < diffList.count()) + if (i < diffList.size()) nextDiff = diffList.at(i); // omit equality2 } } else { @@ -1497,11 +1496,11 @@ QList Differ::cleanupSemanticsLossless(const QList &diffList) prevDiff = thisDiff; thisDiff = nextDiff; i++; - if (i < diffList.count()) + if (i < diffList.size()) nextDiff = diffList.at(i); } newDiffList.append(prevDiff); - if (i == diffList.count()) + if (i == diffList.size()) newDiffList.append(thisDiff); return newDiffList; } diff --git a/src/libs/utils/executeondestruction.h b/src/libs/utils/executeondestruction.h deleted file mode 100644 index 82832afb9a9..00000000000 --- a/src/libs/utils/executeondestruction.h +++ /dev/null @@ -1,23 +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 - -namespace Utils { - -class ExecuteOnDestruction -{ -public: - ExecuteOnDestruction() noexcept : destructionCode([] {}) {} - ExecuteOnDestruction(std::function code) : destructionCode(std::move(code)) {} - ~ExecuteOnDestruction() { if (destructionCode) destructionCode(); } - - void reset(std::function code) { destructionCode = std::move(code); } - -private: - std::function destructionCode; -}; - -} // Utils diff --git a/src/libs/utils/filenamevalidatinglineedit.cpp b/src/libs/utils/filenamevalidatinglineedit.cpp index 5602e72d1a1..47721b23120 100644 --- a/src/libs/utils/filenamevalidatinglineedit.cpp +++ b/src/libs/utils/filenamevalidatinglineedit.cpp @@ -151,12 +151,12 @@ bool FileNameValidatingLineEdit::validateFileNameExtension(const QString &fileNa if (!requiredExtensions.isEmpty()) { for (const QString &requiredExtension : requiredExtensions) { QString extension = QLatin1Char('.') + requiredExtension; - if (fileName.endsWith(extension, Qt::CaseSensitive) && extension.count() < fileName.count()) + if (fileName.endsWith(extension, Qt::CaseSensitive) && extension.size() < fileName.size()) return true; } if (errorMessage) { - if (requiredExtensions.count() == 1) + if (requiredExtensions.size() == 1) *errorMessage = Tr::tr("File extension %1 is required:").arg(requiredExtensions.first()); else *errorMessage = Tr::tr("File extensions %1 are required:").arg(requiredExtensions.join(QLatin1String(", "))); diff --git a/src/libs/utils/highlightingitemdelegate.cpp b/src/libs/utils/highlightingitemdelegate.cpp index a8b144dbdb3..22d55e23bf0 100644 --- a/src/libs/utils/highlightingitemdelegate.cpp +++ b/src/libs/utils/highlightingitemdelegate.cpp @@ -201,7 +201,7 @@ void HighlightingItemDelegate::drawText(QPainter *painter, static QString replaceNewLine(QString text) { static const QChar nl = '\n'; - for (int i = 0; i < text.count(); ++i) + for (int i = 0; i < text.size(); ++i) if (text.at(i) == nl) text[i] = QChar::LineSeparator; return text; diff --git a/src/libs/utils/outputformatter.cpp b/src/libs/utils/outputformatter.cpp index 2bcdffb5864..f8b3d8cec79 100644 --- a/src/libs/utils/outputformatter.cpp +++ b/src/libs/utils/outputformatter.cpp @@ -449,7 +449,7 @@ void OutputFormatter::append(const QString &text, const QTextCharFormat &format) d->cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor); startPos = crPos + 1; } - if (startPos < text.count()) + if (startPos < text.size()) d->cursor.insertText(text.mid(startPos), format); } diff --git a/src/libs/utils/process.cpp b/src/libs/utils/process.cpp index e1302671e34..970b0b4a296 100644 --- a/src/libs/utils/process.cpp +++ b/src/libs/utils/process.cpp @@ -66,7 +66,7 @@ public: return std::invoke(std::forward(function), std::forward(args)...); QElapsedTimer timer; timer.start(); - auto cleanup = qScopeGuard([this, &timer] { + const QScopeGuard cleanup([this, &timer] { const qint64 currentNsecs = timer.nsecsElapsed(); const bool mainThread = isMainThread(); const int hitThisAll = m_hitThisAll.fetch_add(1) + 1; diff --git a/src/libs/utils/projectintropage.cpp b/src/libs/utils/projectintropage.cpp index dba9a801e4b..0b1a0a63557 100644 --- a/src/libs/utils/projectintropage.cpp +++ b/src/libs/utils/projectintropage.cpp @@ -303,7 +303,7 @@ bool ProjectIntroPage::validateProjectName(const QString &name, QString *errorMe // if pos is set by validate it is cought at the bottom where it shows // a more detailed error message - if (validatorState != QValidator::Acceptable && (pos == -1 || pos >= name.count())) { + if (validatorState != QValidator::Acceptable && (pos == -1 || pos >= name.size())) { if (errorMessage) { if (d->m_projectNameValidatorUserMessage.isEmpty()) *errorMessage = Tr::tr("Project name is invalid."); diff --git a/src/libs/utils/templateengine.cpp b/src/libs/utils/templateengine.cpp index e5636960dea..a917ea27cb8 100644 --- a/src/libs/utils/templateengine.cpp +++ b/src/libs/utils/templateengine.cpp @@ -235,9 +235,9 @@ QString TemplateEngine::processText(MacroExpander *expander, const QString &inpu // Expand \n, \t and handle line continuation: QString result; - result.reserve(out.count()); + result.reserve(out.size()); bool isEscaped = false; - for (int i = 0; i < out.count(); ++i) { + for (int i = 0; i < out.size(); ++i) { const QChar c = out.at(i); if (isEscaped) { diff --git a/src/libs/utils/terminalcommand.cpp b/src/libs/utils/terminalcommand.cpp index 102fc42e05d..bb1492515f3 100644 --- a/src/libs/utils/terminalcommand.cpp +++ b/src/libs/utils/terminalcommand.cpp @@ -112,7 +112,14 @@ const char kTerminalExecuteOptionsKey[] = "General/Terminal/ExecuteOptions"; TerminalCommand TerminalCommand::terminalEmulator() { if (s_settings && HostOsInfo::isAnyUnixHost() && s_settings->contains(kTerminalCommandKey)) { - return {FilePath::fromSettings(s_settings->value(kTerminalCommandKey)), + FilePath command = FilePath::fromSettings(s_settings->value(kTerminalCommandKey)); + + // TODO Remove some time after Qt Creator 11 + // Work around Qt Creator <= 10 writing the default terminal to the settings. + if (HostOsInfo::isMacHost() && command.endsWith("openTerminal.py")) + command = FilePath::fromString("Terminal.app"); + + return {command, s_settings->value(kTerminalOpenOptionsKey).toString(), s_settings->value(kTerminalExecuteOptionsKey).toString()}; } diff --git a/src/libs/utils/utils.qbs b/src/libs/utils/utils.qbs index df23fc3ba24..d117b7057cb 100644 --- a/src/libs/utils/utils.qbs +++ b/src/libs/utils/utils.qbs @@ -109,7 +109,6 @@ Project { "environmentmodel.h", "execmenu.cpp", "execmenu.h", - "executeondestruction.h", "externalterminalprocessimpl.cpp", "externalterminalprocessimpl.h", "fadingindicator.cpp", diff --git a/src/plugins/android/androidrunnerworker.cpp b/src/plugins/android/androidrunnerworker.cpp index 65ef8695580..b9a09629fb2 100644 --- a/src/plugins/android/androidrunnerworker.cpp +++ b/src/plugins/android/androidrunnerworker.cpp @@ -341,7 +341,7 @@ bool AndroidRunnerWorker::uploadDebugServer(const QString &debugServerFileName) } const QString tempDebugServerPath = tempDebugServerPathTemplate.arg(count); - auto cleanUp = qScopeGuard([this, tempDebugServerPath] { + const QScopeGuard cleanup([this, tempDebugServerPath] { if (!runAdb({"shell", "rm", "-f", tempDebugServerPath})) qCDebug(androidRunWorkerLog) << "Debug server cleanup failed."; }); diff --git a/src/plugins/autotest/qtest/qttestoutputreader.cpp b/src/plugins/autotest/qtest/qttestoutputreader.cpp index 70df35e6632..9f10e06846e 100644 --- a/src/plugins/autotest/qtest/qttestoutputreader.cpp +++ b/src/plugins/autotest/qtest/qttestoutputreader.cpp @@ -54,10 +54,10 @@ static QString formatResult(double value) QString beforeDecimalPoint = QString::number(value, 'f', 0); QString afterDecimalPoint = QString::number(value, 'f', 20); - afterDecimalPoint.remove(0, beforeDecimalPoint.count() + 1); + afterDecimalPoint.remove(0, beforeDecimalPoint.size() + 1); - const int beforeUse = qMin(beforeDecimalPoint.count(), significantDigits); - const int beforeRemove = beforeDecimalPoint.count() - beforeUse; + const int beforeUse = qMin(beforeDecimalPoint.size(), significantDigits); + const int beforeRemove = beforeDecimalPoint.size() - beforeUse; beforeDecimalPoint.chop(beforeRemove); for (int i = 0; i < beforeRemove; ++i) @@ -67,12 +67,12 @@ static QString formatResult(double value) if (beforeDecimalPoint == QString("0") && !afterDecimalPoint.isEmpty()) { ++afterUse; int i = 0; - while (i < afterDecimalPoint.count() && afterDecimalPoint.at(i) == '0') + while (i < afterDecimalPoint.size() && afterDecimalPoint.at(i) == '0') ++i; afterUse += i; } - const int afterRemove = afterDecimalPoint.count() - afterUse; + const int afterRemove = afterDecimalPoint.size() - afterUse; afterDecimalPoint.chop(afterRemove); QString result = beforeDecimalPoint; diff --git a/src/plugins/axivion/axivionoutputpane.cpp b/src/plugins/axivion/axivionoutputpane.cpp index ba226f63b5b..ae3aed35488 100644 --- a/src/plugins/axivion/axivionoutputpane.cpp +++ b/src/plugins/axivion/axivionoutputpane.cpp @@ -124,7 +124,7 @@ QList AxivionOutputPane::toolBarWidgets() const { QList buttons; auto showDashboard = new QToolButton(m_outputWidget); - showDashboard->setIcon(Utils::Icons::ONLINE_TOOLBAR.icon()); + showDashboard->setIcon(Utils::Icons::HOME_TOOLBAR.icon()); showDashboard->setToolTip(Tr::tr("Show dashboard")); connect(showDashboard, &QToolButton::clicked, this, [this]{ QTC_ASSERT(m_outputWidget, return); diff --git a/src/plugins/clangcodemodel/clangdclient.cpp b/src/plugins/clangcodemodel/clangdclient.cpp index 0082ff6cef9..87a059c15cd 100644 --- a/src/plugins/clangcodemodel/clangdclient.cpp +++ b/src/plugins/clangcodemodel/clangdclient.cpp @@ -230,14 +230,22 @@ public: void enableCodeActionsInline() {insert(u"codeActionsInline", true);} }; +class InactiveRegionsCapabilities : public JsonObject +{ +public: + using JsonObject::JsonObject; + void enableInactiveRegionsSupport() { insert(u"inactiveRegions", true); } +}; + class ClangdTextDocumentClientCapabilities : public TextDocumentClientCapabilities { public: using TextDocumentClientCapabilities::TextDocumentClientCapabilities; - void setPublishDiagnostics(const DiagnosticsCapabilities &caps) { insert(u"publishDiagnostics", caps); } + void setInactiveRegionsCapabilities(const InactiveRegionsCapabilities &caps) + { insert(u"inactiveRegionsCapabilities", caps); } }; static qint64 getRevision(const TextDocument *doc) @@ -428,6 +436,9 @@ ClangdClient::ClangdClient(Project *project, const Utils::FilePath &jsonDbDir, c diagnostics.enableCategorySupport(); diagnostics.enableCodeActionsInline(); clangdTextCaps.setPublishDiagnostics(diagnostics); + InactiveRegionsCapabilities inactiveRegions; + inactiveRegions.enableInactiveRegionsSupport(); + clangdTextCaps.setInactiveRegionsCapabilities(inactiveRegions); std::optional completionCaps = textCaps->completion(); if (completionCaps) @@ -456,6 +467,9 @@ ClangdClient::ClangdClient(Project *project, const Utils::FilePath &jsonDbDir, c const Utils::FilePath &filePath) { gatherHelpItemForTooltip(response, filePath); }); + registerCustomMethod(inactiveRegionsMethodName(), [this](const JsonRpcMessage &msg) { + handleInactiveRegions(this, msg); + }); connect(this, &Client::workDone, this, [this, p = QPointer(project)](const ProgressToken &token) { @@ -691,7 +705,8 @@ class ClangdDiagnosticManager : public LanguageClient::DiagnosticManager return Utils::filtered(diagnostics, [](const Diagnostic &diag){ const Diagnostic::Code code = diag.code().value_or(Diagnostic::Code()); const QString * const codeString = std::get_if(&code); - return !codeString || *codeString != "drv_unknown_argument"; + return !codeString || (*codeString != "drv_unknown_argument" + && !codeString->startsWith("drv_unsupported_opt")); }); } diff --git a/src/plugins/clangcodemodel/clangdsemantichighlighting.cpp b/src/plugins/clangcodemodel/clangdsemantichighlighting.cpp index e1b82ab3770..f93d8302bd3 100644 --- a/src/plugins/clangcodemodel/clangdsemantichighlighting.cpp +++ b/src/plugins/clangcodemodel/clangdsemantichighlighting.cpp @@ -330,6 +330,8 @@ void doSemanticHighlighting( styles.mainStyle = C_TYPE; } else if (token.type == "modifier") { styles.mainStyle = C_KEYWORD; + } else if (token.type == "label") { + styles.mainStyle = C_LABEL; } else if (token.type == "typeParameter") { // clangd reports both type and non-type template parameters as type parameters, // but the latter can be distinguished by the readonly modifier. @@ -396,7 +398,10 @@ void doSemanticHighlighting( } }; auto results = QtConcurrent::blockingMapped(tokens, safeToResult); - const QList ifdefedOutBlocks = cleanupDisabledCode(results, &doc, docContents); + const bool handleInactiveCode = clangdMajorVersion < 17; + QList ifdefedOutBlocks; + if (handleInactiveCode) + ifdefedOutBlocks = cleanupDisabledCode(results, &doc, docContents); ExtraHighlightingResultsCollector(promise, results, filePath, ast, &doc, docContents, clangdVersion).collect(); Utils::erase(results, [](const HighlightingResult &res) { @@ -405,10 +410,12 @@ void doSemanticHighlighting( }); if (!promise.isCanceled()) { qCInfo(clangdLogHighlight) << "reporting" << results.size() << "highlighting results"; - QMetaObject::invokeMethod(textDocument, [textDocument, ifdefedOutBlocks, docRevision] { - if (textDocument && textDocument->document()->revision() == docRevision) - textDocument->setIfdefedOutBlocks(ifdefedOutBlocks); - }, Qt::QueuedConnection); + if (handleInactiveCode) { + QMetaObject::invokeMethod(textDocument, [textDocument, ifdefedOutBlocks, docRevision] { + if (textDocument && textDocument->document()->revision() == docRevision) + textDocument->setIfdefedOutBlocks(ifdefedOutBlocks); + }, Qt::QueuedConnection); + } QList virtualRanges; for (const HighlightingResult &r : results) { if (r.textStyles.mainStyle != C_VIRTUAL_METHOD) @@ -953,4 +960,45 @@ void ExtraHighlightingResultsCollector::visitNode(const ClangdAstNode &node) m_currentFileStatus = prevFileStatus; } +class InactiveRegionsParams : public JsonObject +{ +public: + using JsonObject::JsonObject; + + DocumentUri uri() const { return TextDocumentIdentifier(value(u"textDocument")).uri(); } + QList inactiveRegions() const { return array(u"regions"); } +}; + +class InactiveRegionsNotification : public Notification +{ +public: + explicit InactiveRegionsNotification(const InactiveRegionsParams ¶ms) + : Notification(inactiveRegionsMethodName(), params) {} + using Notification::Notification; +}; + +void handleInactiveRegions(LanguageClient::Client *client, const JsonRpcMessage &msg) +{ + const auto params = InactiveRegionsNotification(msg.toJsonObject()).params(); + if (!params) + return; + TextDocument * const doc = client->documentForFilePath( + params->uri().toFilePath(client->hostPathMapper())); + if (!doc) + return; + const QList inactiveRegions = params->inactiveRegions(); + QList ifdefedOutBlocks; + for (const Range &r : inactiveRegions) { + const int startPos = r.start().toPositionInDocument(doc->document()); + const int endPos = r.end().toPositionInDocument(doc->document()) + 1; + ifdefedOutBlocks.emplaceBack(startPos, endPos); + } + doc->setIfdefedOutBlocks(ifdefedOutBlocks); +} + +QString inactiveRegionsMethodName() +{ + return "textDocument/inactiveRegions"; +} + } // namespace ClangCodeModel::Internal diff --git a/src/plugins/clangcodemodel/clangdsemantichighlighting.h b/src/plugins/clangcodemodel/clangdsemantichighlighting.h index a7f667d459f..285ba2323e7 100644 --- a/src/plugins/clangcodemodel/clangdsemantichighlighting.h +++ b/src/plugins/clangcodemodel/clangdsemantichighlighting.h @@ -12,7 +12,11 @@ template class QPromise; QT_END_NAMESPACE -namespace LanguageClient { class ExpandedSemanticToken; } +namespace LanguageClient { +class Client; +class ExpandedSemanticToken; +} +namespace LanguageServerProtocol { class JsonRpcMessage; } namespace TextEditor { class HighlightingResult; class TextDocument; @@ -36,4 +40,9 @@ void doSemanticHighlighting( const TaskTimer &taskTimer ); + +QString inactiveRegionsMethodName(); +void handleInactiveRegions(LanguageClient::Client *client, + const LanguageServerProtocol::JsonRpcMessage &msg); + } // namespace ClangCodeModel::Internal diff --git a/src/plugins/clangcodemodel/clangutils.cpp b/src/plugins/clangcodemodel/clangutils.cpp index f236fa81b07..d5d7868137b 100644 --- a/src/plugins/clangcodemodel/clangutils.cpp +++ b/src/plugins/clangcodemodel/clangutils.cpp @@ -230,7 +230,7 @@ QString DiagnosticTextInfo::option() const return QString(); const int index = m_squareBracketStartIndex + 1; - return m_text.mid(index, m_text.count() - index - 1); + return m_text.mid(index, m_text.size() - index - 1); } QString DiagnosticTextInfo::category() const diff --git a/src/plugins/clangcodemodel/test/clangdtests.cpp b/src/plugins/clangcodemodel/test/clangdtests.cpp index a90126c00e8..a102f1d3527 100644 --- a/src/plugins/clangcodemodel/test/clangdtests.cpp +++ b/src/plugins/clangcodemodel/test/clangdtests.cpp @@ -1225,8 +1225,10 @@ void ClangdTestHighlighting::test_data() << QList{C_PUNCTUATION} << int(CppEditor::SemanticHighlighter::AngleBracketClose); QTest::newRow("macro in struct") << 795 << 9 << 795 << 14 << QList{C_MACRO, C_DECLARATION} << 0; - QTest::newRow("#ifdef'ed out code") << 800 << 1 << 800 << 17 - << QList{C_DISABLED_CODE} << 0; + if (client()->versionNumber() < QVersionNumber(17)) { + QTest::newRow("#ifdef'ed out code") << 800 << 1 << 800 << 17 + << QList{C_DISABLED_CODE} << 0; + } QTest::newRow("static function call (object)") << 819 << 5 << 819 << 6 << QList{C_LOCAL} << 0; QTest::newRow("static function call (argument)") << 819 << 18 << 819 << 19 @@ -1302,6 +1304,9 @@ void ClangdTestHighlighting::test_data() QTest::newRow("concept definition") << 1053 << 30 << 1053 << 42 << QList{C_TYPE, C_DECLARATION} << 0; QTest::newRow("concept use") << 1054 << 29 << 1054 << 41 << QList{C_TYPE} << 0; + QTest::newRow("label declaration") << 242 << 1 << 242 << 11 + << QList{C_LABEL, C_DECLARATION} << 0; + QTest::newRow("label use") << 244 << 10 << 244 << 20 << QList{C_LABEL} << 0; } void ClangdTestHighlighting::test() diff --git a/src/plugins/clangtools/documentclangtoolrunner.cpp b/src/plugins/clangtools/documentclangtoolrunner.cpp index 93cd27bac38..8dab531dcb6 100644 --- a/src/plugins/clangtools/documentclangtoolrunner.cpp +++ b/src/plugins/clangtools/documentclangtoolrunner.cpp @@ -158,7 +158,7 @@ void DocumentClangToolRunner::run() if (m_projectSettingsUpdate) disconnect(m_projectSettingsUpdate); m_taskTree.reset(); - QScopeGuard guard([this] { finalize(); }); + QScopeGuard cleanup([this] { finalize(); }); auto isEditorForCurrentDocument = [this](const IEditor *editor) { return editor->document() == m_document; @@ -216,7 +216,7 @@ void DocumentClangToolRunner::run() if (tasks.isEmpty()) return; - guard.dismiss(); + cleanup.dismiss(); m_taskTree.reset(new TaskTree(tasks)); connect(m_taskTree.get(), &TaskTree::done, this, &DocumentClangToolRunner::finalize); connect(m_taskTree.get(), &TaskTree::errorOccurred, this, &DocumentClangToolRunner::finalize); diff --git a/src/plugins/cmakeprojectmanager/cmakeconfigitem.cpp b/src/plugins/cmakeprojectmanager/cmakeconfigitem.cpp index baa884d9f23..2646c5c5808 100644 --- a/src/plugins/cmakeprojectmanager/cmakeconfigitem.cpp +++ b/src/plugins/cmakeprojectmanager/cmakeconfigitem.cpp @@ -215,13 +215,13 @@ bool CMakeConfigItem::less(const CMakeConfigItem &a, const CMakeConfigItem &b) CMakeConfigItem CMakeConfigItem::fromString(const QString &s) { // Strip comments (only at start of line!): - int commentStart = s.count(); - for (int i = 0; i < s.count(); ++i) { + int commentStart = s.size(); + for (int i = 0; i < s.size(); ++i) { const QChar c = s.at(i); if (c == ' ' || c == '\t') continue; else if ((c == '#') - || (c == '/' && i < s.count() - 1 && s.at(i + 1) == '/')) { + || (c == '/' && i < s.size() - 1 && s.at(i + 1) == '/')) { commentStart = i; break; } else { @@ -234,7 +234,7 @@ CMakeConfigItem CMakeConfigItem::fromString(const QString &s) int firstPos = -1; int colonPos = -1; int equalPos = -1; - for (int i = 0; i < line.count(); ++i) { + for (int i = 0; i < line.size(); ++i) { const QChar c = s.at(i); if (firstPos < 0 && !c.isSpace()) { firstPos = i; @@ -371,7 +371,7 @@ CMakeConfig CMakeConfig::fromFile(const Utils::FilePath &cacheFile, QString *err if (pieces.isEmpty()) continue; - QTC_ASSERT(pieces.count() == 3, continue); + QTC_ASSERT(pieces.size() == 3, continue); const QByteArray key = pieces.at(0); const QByteArray type = pieces.at(1); const QByteArray value = pieces.at(2); @@ -387,7 +387,7 @@ CMakeConfig CMakeConfig::fromFile(const Utils::FilePath &cacheFile, QString *err } // Set advanced flags: - for (int i = 0; i < result.count(); ++i) { + for (int i = 0; i < result.size(); ++i) { CMakeConfigItem &item = result[i]; item.isAdvanced = advancedSet.contains(item.key); diff --git a/src/plugins/cmakeprojectmanager/cmakeeditor.cpp b/src/plugins/cmakeprojectmanager/cmakeeditor.cpp index 3411fd85b58..4bbe75b77c0 100644 --- a/src/plugins/cmakeprojectmanager/cmakeeditor.cpp +++ b/src/plugins/cmakeprojectmanager/cmakeeditor.cpp @@ -169,7 +169,7 @@ void CMakeEditorWidget::findLinkAt(const QTextCursor &cursor, // find the end of a filename int endPos = column; - while (endPos < block.count()) { + while (endPos < block.size()) { if (isValidFileNameChar(block, endPos)) { buffer.append(block.at(endPos)); endPos++; diff --git a/src/plugins/copilot/Copilot.json.in b/src/plugins/copilot/Copilot.json.in index 55ff6f6bf42..ae5853c212d 100644 --- a/src/plugins/copilot/Copilot.json.in +++ b/src/plugins/copilot/Copilot.json.in @@ -2,7 +2,7 @@ \"Name\" : \"Copilot\", \"Version\" : \"$$QTCREATOR_VERSION\", \"CompatVersion\" : \"$$QTCREATOR_COMPAT_VERSION\", - \"Experimental\" : true, + \"DisabledByDefault\" : true, \"Vendor\" : \"The Qt Company Ltd\", \"Copyright\" : \"(C) $$QTCREATOR_COPYRIGHT_YEAR The Qt Company Ltd\", \"License\" : [ \"Commercial Usage\", diff --git a/src/plugins/copilot/copilothoverhandler.cpp b/src/plugins/copilot/copilothoverhandler.cpp index 135cbd8390f..d17ec073b2c 100644 --- a/src/plugins/copilot/copilothoverhandler.cpp +++ b/src/plugins/copilot/copilothoverhandler.cpp @@ -15,6 +15,7 @@ #include #include +#include #include #include @@ -117,7 +118,7 @@ void CopilotHoverHandler::identifyMatch(TextEditorWidget *editorWidget, int pos, ReportPriority report) { - auto reportNone = qScopeGuard([&] { report(Priority_None); }); + QScopeGuard cleanup([&] { report(Priority_None); }); if (!editorWidget->suggestionVisible()) return; @@ -133,7 +134,7 @@ void CopilotHoverHandler::identifyMatch(TextEditorWidget *editorWidget, if (completions.isEmpty()) return; - reportNone.dismiss(); + cleanup.dismiss(); report(Priority_Suggestion); } diff --git a/src/plugins/coreplugin/editormanager/editormanager.cpp b/src/plugins/coreplugin/editormanager/editormanager.cpp index 81262f5ebfe..261146797b4 100644 --- a/src/plugins/coreplugin/editormanager/editormanager.cpp +++ b/src/plugins/coreplugin/editormanager/editormanager.cpp @@ -3325,7 +3325,7 @@ IEditor *EditorManager::openEditorWithContents(Id editorId, EditorManager::gotoOtherSplit(); QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); - const auto cleanup = qScopeGuard(&QApplication::restoreOverrideCursor); + const QScopeGuard cleanup(&QApplication::restoreOverrideCursor); const QString title = makeTitleUnique(titlePattern); diff --git a/src/plugins/coreplugin/find/searchresulttreeitemdelegate.cpp b/src/plugins/coreplugin/find/searchresulttreeitemdelegate.cpp index dcaf86ecb9f..274d79499aa 100644 --- a/src/plugins/coreplugin/find/searchresulttreeitemdelegate.cpp +++ b/src/plugins/coreplugin/find/searchresulttreeitemdelegate.cpp @@ -28,7 +28,7 @@ static std::pair lineNumberInfo(const QStyleOptionViewItem &option if (lineNumber < 1) return {0, {}}; const QString lineNumberText = QString::number(lineNumber); - const int lineNumberDigits = qMax(minimumLineNumberDigits, lineNumberText.count()); + const int lineNumberDigits = qMax(minimumLineNumberDigits, lineNumberText.size()); const int fontWidth = option.fontMetrics.horizontalAdvance(QString(lineNumberDigits, QLatin1Char('0'))); const QStyle *style = option.widget ? option.widget->style() : QApplication::style(); return {lineNumberAreaHorizontalPadding + fontWidth + lineNumberAreaHorizontalPadding diff --git a/src/plugins/coreplugin/helpitem.cpp b/src/plugins/coreplugin/helpitem.cpp index 7245a4769bd..cbe0998e03b 100644 --- a/src/plugins/coreplugin/helpitem.cpp +++ b/src/plugins/coreplugin/helpitem.cpp @@ -177,7 +177,7 @@ QString HelpItem::extractContent(bool extended) const // include separators for major vs minor vs patch version. static QVersionNumber qtVersionHeuristic(const QString &digits) { - if (digits.count() > 6 || digits.count() < 3) + if (digits.size() > 6 || digits.size() < 3) return {}; // suspicious version number for (const QChar &digit : digits) @@ -188,7 +188,7 @@ static QVersionNumber qtVersionHeuristic(const QString &digits) // When we have 4 digits, we split it like: ABCD -> A.BC.D // When we have 5 digits, we split it like: ABCDE -> A.BC.DE // When we have 6 digits, we split it like: ABCDEF -> AB.CD.EF - switch (digits.count()) { + switch (digits.size()) { case 3: return QVersionNumber(digits.mid(0, 1).toInt(), digits.mid(1, 1).toInt(), diff --git a/src/plugins/coreplugin/ioutputpane.h b/src/plugins/coreplugin/ioutputpane.h index f3ae7fa0b82..9193699ca4a 100644 --- a/src/plugins/coreplugin/ioutputpane.h +++ b/src/plugins/coreplugin/ioutputpane.h @@ -92,6 +92,8 @@ protected: void setupContext(const Context &context, QWidget *widget); void setZoomButtonsEnabled(bool enabled); + IContext *m_context = nullptr; + private: virtual void updateFilter(); @@ -108,7 +110,6 @@ private: QAction *m_filterActionCaseSensitive = nullptr; QAction *m_invertFilterAction = nullptr; Utils::FancyLineEdit *m_filterOutputLineEdit = nullptr; - IContext *m_context = nullptr; bool m_filterRegexp = false; bool m_invertFilter = false; Qt::CaseSensitivity m_filterCaseSensitivity = Qt::CaseInsensitive; diff --git a/src/plugins/coreplugin/locator/ilocatorfilter.cpp b/src/plugins/coreplugin/locator/ilocatorfilter.cpp index 0a4665361d2..74ad227e977 100644 --- a/src/plugins/coreplugin/locator/ilocatorfilter.cpp +++ b/src/plugins/coreplugin/locator/ilocatorfilter.cpp @@ -490,7 +490,7 @@ void LocatorMatcher::start() } }; - d->m_taskTree->setupRoot(root); + d->m_taskTree->setRecipe(root); const auto onFinish = [this](bool success) { return [this, success] { diff --git a/src/plugins/coreplugin/locator/javascriptfilter.cpp b/src/plugins/coreplugin/locator/javascriptfilter.cpp index 3656d673205..b179b32316d 100644 --- a/src/plugins/coreplugin/locator/javascriptfilter.cpp +++ b/src/plugins/coreplugin/locator/javascriptfilter.cpp @@ -15,7 +15,6 @@ #include #include #include -#include #include diff --git a/src/plugins/coreplugin/loggingviewer.cpp b/src/plugins/coreplugin/loggingviewer.cpp index 63fba41a4df..742e65a34c5 100644 --- a/src/plugins/coreplugin/loggingviewer.cpp +++ b/src/plugins/coreplugin/loggingviewer.cpp @@ -591,7 +591,7 @@ void LoggingViewManagerWidget::saveLoggingsToFile() const { // should we just let it continue without temporarily disabling? const bool enabled = m_manager->isEnabled(); - const auto cleanup = qScopeGuard([this, enabled] { m_manager->setEnabled(enabled); }); + const QScopeGuard cleanup([this, enabled] { m_manager->setEnabled(enabled); }); if (enabled) m_manager->setEnabled(false); const Utils::FilePath fp = Utils::FileUtils::getSaveFilePath(ICore::dialogParent(), diff --git a/src/plugins/coreplugin/mainwindow.cpp b/src/plugins/coreplugin/mainwindow.cpp index 2d7ec70c8eb..c93710ff580 100644 --- a/src/plugins/coreplugin/mainwindow.cpp +++ b/src/plugins/coreplugin/mainwindow.cpp @@ -63,6 +63,7 @@ #include #include #include +#include #include #include @@ -1228,6 +1229,14 @@ void MainWindow::saveSettings() EditorManagerPrivate::saveSettings(); m_leftNavigationWidget->saveSettings(settings); m_rightNavigationWidget->saveSettings(settings); + + // TODO Remove some time after Qt Creator 11 + // Work around Qt Creator <= 10 writing the default terminal to the settings. + // TerminalCommand writes the terminal to the settings when changing it, which usually is + // enough. But because of the bug in Qt Creator <= 10 we want to clean up the settings + // even if the user never touched the terminal setting. + if (HostOsInfo::isMacHost()) + TerminalCommand::setTerminalEmulator(TerminalCommand::terminalEmulator()); } void MainWindow::saveWindowSettings() diff --git a/src/plugins/coreplugin/modemanager.cpp b/src/plugins/coreplugin/modemanager.cpp index e1bac00a883..9608ed6caff 100644 --- a/src/plugins/coreplugin/modemanager.cpp +++ b/src/plugins/coreplugin/modemanager.cpp @@ -99,7 +99,7 @@ static int indexOf(Id id) void ModeManagerPrivate::showMenu(int index, QMouseEvent *event) { QTC_ASSERT(m_modes.at(index)->menu(), return); - m_modes.at(index)->menu()->popup(event->globalPos()); + m_modes.at(index)->menu()->popup(event->globalPosition().toPoint()); } ModeManager::ModeManager(Internal::MainWindow *mainWindow, diff --git a/src/plugins/coreplugin/vcsmanager.cpp b/src/plugins/coreplugin/vcsmanager.cpp index f9da6ee59f2..4b5e60b2fcc 100644 --- a/src/plugins/coreplugin/vcsmanager.cpp +++ b/src/plugins/coreplugin/vcsmanager.cpp @@ -80,7 +80,7 @@ public: QTC_ASSERT((topLevel.isEmpty() && !vc) || (!topLevel.isEmpty() && vc), return); FilePath tmpDir = dir; - while (tmpDir.toString().count() >= topLevelString.count() && !tmpDir.isEmpty()) { + while (tmpDir.toString().size() >= topLevelString.size() && !tmpDir.isEmpty()) { m_cachedMatches.insert(tmpDir, {vc, topLevel}); // if no vc was found, this might mean we're inside a repo internal directory (.git) // Cache only input directory, not parents @@ -237,7 +237,7 @@ IVersionControl* VcsManager::findVersionControlForDirectory(const FilePath &inpu for (auto i = allThatCanManage.constBegin(); i != allThatCanManage.constEnd(); ++i) { const QString firstString = i->first.toString(); // If topLevel was already cached for another VC, skip this one - if (tmpDir.toString().count() < firstString.count()) + if (tmpDir.toString().size() < firstString.size()) continue; d->cache(i->second, i->first, tmpDir); tmpDir = i->first.parentDir(); @@ -458,7 +458,7 @@ static FileHash makeHash(const QStringList &list) FileHash result; for (const QString &i : list) { QStringList parts = i.split(QLatin1Char(':')); - QTC_ASSERT(parts.count() == 2, continue); + QTC_ASSERT(parts.size() == 2, continue); result.insert(FilePath::fromString(QString::fromLatin1(TEST_PREFIX) + parts.at(0)), FilePath::fromString(QString::fromLatin1(TEST_PREFIX) + parts.at(1))); } @@ -547,7 +547,7 @@ void CorePlugin::testVcsManager() // qDebug() << "Expecting:" << result; const QStringList split = result.split(QLatin1Char(':')); - QCOMPARE(split.count(), 4); + QCOMPARE(split.size(), 4); QVERIFY(split.at(3) == QLatin1String("*") || split.at(3) == QLatin1String("-")); diff --git a/src/plugins/cppeditor/builtineditordocumentprocessor.cpp b/src/plugins/cppeditor/builtineditordocumentprocessor.cpp index 8e551fd15be..f4df1fcd0cd 100644 --- a/src/plugins/cppeditor/builtineditordocumentprocessor.cpp +++ b/src/plugins/cppeditor/builtineditordocumentprocessor.cpp @@ -254,8 +254,10 @@ void BuiltinEditorDocumentProcessor::onParserFinished(CPlusPlus::Document::Ptr d qCDebug(log) << "document parsed" << document->filePath() << document->editorRevision(); // Emit ifdefed out blocks - const auto ifdefoutBlocks = toTextEditorBlocks(document->skippedBlocks()); - emit ifdefedOutBlocksUpdated(revision(), ifdefoutBlocks); + if (!m_semanticHighlightingChecker || m_semanticHighlightingChecker()) { + const auto ifdefoutBlocks = toTextEditorBlocks(document->skippedBlocks()); + emit ifdefedOutBlocksUpdated(revision(), ifdefoutBlocks); + } // Store parser warnings m_codeWarnings = toTextEditorSelections(document->diagnosticMessages(), textDocument()); diff --git a/src/plugins/cppeditor/compileroptionsbuilder.cpp b/src/plugins/cppeditor/compileroptionsbuilder.cpp index 5f092121214..8b7dd11b2d7 100644 --- a/src/plugins/cppeditor/compileroptionsbuilder.cpp +++ b/src/plugins/cppeditor/compileroptionsbuilder.cpp @@ -875,7 +875,8 @@ void CompilerOptionsBuilder::evaluateCompilerFlags() || option.startsWith("/M", Qt::CaseSensitive) || option.startsWith(includeUserPathOption) || option.startsWith(includeSystemPathOption) - || option.startsWith(includeUserPathOptionWindows)) { + || option.startsWith(includeUserPathOptionWindows) + || option.startsWith("-flto")) { // Optimization and run-time flags. continue; } diff --git a/src/plugins/cppeditor/cppqtstyleindenter.cpp b/src/plugins/cppeditor/cppqtstyleindenter.cpp index adf514f6e7a..cbcaad47a2f 100644 --- a/src/plugins/cppeditor/cppqtstyleindenter.cpp +++ b/src/plugins/cppeditor/cppqtstyleindenter.cpp @@ -58,7 +58,7 @@ static bool isElectricInLine(const QChar ch, const QString &text) case '<': case '>': { // Electric if at line beginning (after space indentation) - for (int i = 0, len = text.count(); i < len; ++i) { + for (int i = 0, len = text.size(); i < len; ++i) { if (!text.at(i).isSpace()) return text.at(i) == ch; } diff --git a/src/plugins/debugger/debuggerplugin.cpp b/src/plugins/debugger/debuggerplugin.cpp index d3a74d5d304..dffa503c456 100644 --- a/src/plugins/debugger/debuggerplugin.cpp +++ b/src/plugins/debugger/debuggerplugin.cpp @@ -110,6 +110,7 @@ #include #include #include +#include #include #include #include @@ -125,8 +126,6 @@ #include #include -#include - #include #include #include @@ -2338,7 +2337,7 @@ void DebuggerUnitTests::testStateMachine() BuildManager::buildProjectWithDependencies(ProjectManager::startupProject()); loop.exec(); - ExecuteOnDestruction guard([] { EditorManager::closeAllEditors(false); }); + const QScopeGuard cleanup([] { EditorManager::closeAllEditors(false); }); RunConfiguration *rc = ProjectManager::startupRunConfiguration(); QVERIFY(rc); diff --git a/src/plugins/debugger/debuggertooltipmanager.cpp b/src/plugins/debugger/debuggertooltipmanager.cpp index 8efea0c487a..90b5f4edb15 100644 --- a/src/plugins/debugger/debuggertooltipmanager.cpp +++ b/src/plugins/debugger/debuggertooltipmanager.cpp @@ -173,7 +173,7 @@ public: void DraggableLabel::mousePressEvent(QMouseEvent * event) { if (active && event->button() == Qt::LeftButton) { - m_moveStartPos = event->globalPos(); + m_moveStartPos = event->globalPosition().toPoint(); event->accept(); } QLabel::mousePressEvent(event); @@ -190,7 +190,7 @@ void DraggableLabel::mouseMoveEvent(QMouseEvent * event) { if (active && (event->buttons() & Qt::LeftButton)) { if (m_moveStartPos != QPoint(-1, -1)) { - const QPoint newPos = event->globalPos(); + const QPoint newPos = event->globalPosition().toPoint(); const QPoint offset = newPos - m_moveStartPos; m_target->move(m_target->pos() + offset); diff --git a/src/plugins/debugger/loadcoredialog.cpp b/src/plugins/debugger/loadcoredialog.cpp index 4a0fea3f165..e192a7d90ac 100644 --- a/src/plugins/debugger/loadcoredialog.cpp +++ b/src/plugins/debugger/loadcoredialog.cpp @@ -257,7 +257,7 @@ void AttachCoreDialog::accepted() [=](const auto &task) { d->symbolFileResult = task.result(); }}, }; - d->taskTree.setupRoot(root); + d->taskTree.setRecipe(root); d->taskTree.start(); d->progressLabel->setText(Tr::tr("Copying files to device...")); diff --git a/src/plugins/designer/qtcreatorintegration.cpp b/src/plugins/designer/qtcreatorintegration.cpp index 010ab85a82b..9c73ee755c9 100644 --- a/src/plugins/designer/qtcreatorintegration.cpp +++ b/src/plugins/designer/qtcreatorintegration.cpp @@ -339,7 +339,7 @@ static QString addConstRefIfNeeded(const QString &argument) "long", "short", "char", "signed", "unsigned", "qint64", "quint64"}); - for (int i = 0; i < nonConstRefs.count(); i++) { + for (int i = 0; i < nonConstRefs.size(); i++) { const QString &nonConstRef = nonConstRefs.at(i); if (argument == nonConstRef || argument.startsWith(nonConstRef + ' ')) return argument; @@ -350,7 +350,7 @@ static QString addConstRefIfNeeded(const QString &argument) static QString formatArgument(const QString &argument) { QString formattedArgument = argument; - int i = argument.count(); + int i = argument.size(); while (i > 0) { // from the end of the "argument" string i--; const QChar c = argument.at(i); // take the char @@ -373,8 +373,8 @@ static QString addParameterNames(const QString &functionSignature, const QString if (lastParen != -1) argumentsString.truncate(lastParen); const QStringList arguments = argumentsString.split(',', Qt::SkipEmptyParts); - const int pCount = parameterNames.count(); - const int aCount = arguments.count(); + const int pCount = parameterNames.size(); + const int aCount = arguments.size(); for (int i = 0; i < aCount; ++i) { if (i > 0) functionName += ", "; diff --git a/src/plugins/diffeditor/diffeditorplugin.cpp b/src/plugins/diffeditor/diffeditorplugin.cpp index 867217d86d8..10ae3b76a26 100644 --- a/src/plugins/diffeditor/diffeditorplugin.cpp +++ b/src/plugins/diffeditor/diffeditorplugin.cpp @@ -133,7 +133,7 @@ DiffFilesController::DiffFilesController(IDocument *document) tasks.append(AsyncTask(std::bind(setupDiff, _1, inputList.at(i)), std::bind(onDiffDone, _1, i))); } - taskTree.setupRoot(tasks); + taskTree.setRecipe(tasks); }; const auto onTreeDone = [this, storage] { const QList> &results = *storage; diff --git a/src/plugins/diffeditor/sidebysidediffeditorwidget.cpp b/src/plugins/diffeditor/sidebysidediffeditorwidget.cpp index d2f58f83ac4..ef8e2504972 100644 --- a/src/plugins/diffeditor/sidebysidediffeditorwidget.cpp +++ b/src/plugins/diffeditor/sidebysidediffeditorwidget.cpp @@ -316,7 +316,7 @@ static SideBySideDiffOutput diffOutput(QPromise &promise, addChunkLine(RightSide, -2); blockNumber++; } else { - for (int j = 0; j < contextFileData.chunks.count(); j++) { + for (int j = 0; j < contextFileData.chunks.size(); j++) { const ChunkData &chunkData = contextFileData.chunks.at(j); int leftLineNumber = chunkData.startingLineNumber[LeftSide]; @@ -331,7 +331,7 @@ static SideBySideDiffOutput diffOutput(QPromise &promise, blockNumber++; } - const int rows = chunkData.rows.count(); + const int rows = chunkData.rows.size(); output.side[LeftSide].diffData.m_chunkInfo.setChunkIndex(blockNumber, rows, j); output.side[RightSide].diffData.m_chunkInfo.setChunkIndex(blockNumber, rows, j); @@ -342,11 +342,11 @@ static SideBySideDiffOutput diffOutput(QPromise &promise, } } - if (j == contextFileData.chunks.count() - 1) { // the last chunk + if (j == contextFileData.chunks.size() - 1) { // the last chunk int skippedLines = -2; if (chunkData.contextChunk) { // if it's context chunk - skippedLines = chunkData.rows.count(); + skippedLines = chunkData.rows.size(); } else if (!contextFileData.lastChunkAtTheEndOfFile && !contextFileData.contextChunksIncluded) { // if not a context chunk and not a chunk at the end of file @@ -381,7 +381,7 @@ void SideDiffData::setLineNumber(int blockNumber, int lineNumber) { const QString lineNumberString = QString::number(lineNumber); m_lineNumbers.insert(blockNumber, lineNumber); - m_lineNumberDigits = qMax(m_lineNumberDigits, lineNumberString.count()); + m_lineNumberDigits = qMax(m_lineNumberDigits, lineNumberString.size()); } void SideDiffData::setFileInfo(int blockNumber, const DiffFileInfo &fileInfo) @@ -986,7 +986,7 @@ void SideBySideDiffEditorWidget::setFontSettings(const FontSettings &fontSetting void SideBySideDiffEditorWidget::jumpToOriginalFileRequested(DiffSide side, int diffFileIndex, int lineNumber, int columnNumber) { - if (diffFileIndex < 0 || diffFileIndex >= m_controller.m_contextFileData.count()) + if (diffFileIndex < 0 || diffFileIndex >= m_controller.m_contextFileData.size()) return; const FileData fileData = m_controller.m_contextFileData.at(diffFileIndex); @@ -1007,7 +1007,7 @@ void SideBySideDiffEditorWidget::jumpToOriginalFileRequested(DiffSide side, int int thisLineNumber = chunkData.startingLineNumber[side]; int otherLineNumber = chunkData.startingLineNumber[otherSide]; - for (int j = 0; j < chunkData.rows.count(); j++) { + for (int j = 0; j < chunkData.rows.size(); j++) { const RowData rowData = chunkData.rows.at(j); if (rowData.line[side].textLineType == TextLineData::TextLine) thisLineNumber++; diff --git a/src/plugins/diffeditor/unifieddiffeditorwidget.cpp b/src/plugins/diffeditor/unifieddiffeditorwidget.cpp index bb64e61d5b0..0c06c85bae0 100644 --- a/src/plugins/diffeditor/unifieddiffeditorwidget.cpp +++ b/src/plugins/diffeditor/unifieddiffeditorwidget.cpp @@ -226,7 +226,7 @@ QString UnifiedDiffEditorWidget::lineNumber(int blockNumber) const const QString line = lineExists ? QString::number(m_data.m_lineNumbers[side].value(blockNumber).first) : QString(); - lineNumberString += QString(m_data.m_lineNumberDigits[side] - line.count(), ' ') + line; + lineNumberString += QString(m_data.m_lineNumberDigits[side] - line.size(), ' ') + line; }; addSideNumber(LeftSide, leftLineExists); lineNumberString += '|'; @@ -263,7 +263,7 @@ void UnifiedDiffData::setLineNumber(DiffSide side, int blockNumber, int lineNumb QTC_ASSERT(side < SideCount, return); const QString lineNumberString = QString::number(lineNumber); m_lineNumbers[side].insert(blockNumber, {lineNumber, rowNumberInChunk}); - m_lineNumberDigits[side] = qMax(m_lineNumberDigits[side], lineNumberString.count()); + m_lineNumberDigits[side] = qMax(m_lineNumberDigits[side], lineNumberString.size()); } QString UnifiedDiffData::setChunk(const DiffEditorInput &input, const ChunkData &chunkData, diff --git a/src/plugins/git/commitdata.cpp b/src/plugins/git/commitdata.cpp index 172d30e2c52..1bc66adf0dc 100644 --- a/src/plugins/git/commitdata.cpp +++ b/src/plugins/git/commitdata.cpp @@ -91,7 +91,7 @@ bool operator<(const CommitData::StateFilePair &a, const CommitData::StateFilePa bool CommitData::checkLine(const QString &stateInfo, const QString &file) { - QTC_ASSERT(stateInfo.count() == 2, return false); + QTC_ASSERT(stateInfo.size() == 2, return false); if (stateInfo == "??") { files.push_back({FileStates(UntrackedFile), file}); diff --git a/src/plugins/git/gitclient.cpp b/src/plugins/git/gitclient.cpp index 4f2bdc4912a..845531ed825 100644 --- a/src/plugins/git/gitclient.cpp +++ b/src/plugins/git/gitclient.cpp @@ -446,7 +446,7 @@ ShowController::ShowController(IDocument *document, const QString &id) tasks.append(ProcessTask(std::bind(setupFollow, _1, parents.at(i)), std::bind(onFollowDone, _1, i))); } - taskTree.setupRoot(tasks); + taskTree.setRecipe(tasks); }; const auto setupDiff = [this, id](Process &process) { @@ -2405,7 +2405,7 @@ QStringList GitClient::synchronousRepositoryBranches(const QString &repositoryUR const int pos = line.lastIndexOf(pattern); if (pos != -1) { branchFound = true; - const QString branchName = line.mid(pos + pattern.count()); + const QString branchName = line.mid(pos + pattern.size()); if (!headFound && line.startsWith(headSha)) { branches[0] = branchName; headFound = true; @@ -2816,7 +2816,7 @@ bool GitClient::addAndCommit(const FilePath &repositoryDirectory, if (state & (ModifiedFile | AddedFile | DeletedFile | TypeChangedFile)) { filesToReset.append(file); } else if (state & (RenamedFile | CopiedFile)) { - const QString newFile = file.mid(file.indexOf(renameSeparator) + renameSeparator.count()); + const QString newFile = file.mid(file.indexOf(renameSeparator) + renameSeparator.size()); filesToReset.append(newFile); } } else if (state & UnmergedFile && checked) { diff --git a/src/plugins/imageviewer/exportdialog.cpp b/src/plugins/imageviewer/exportdialog.cpp index 3595d525cba..d9a0460c989 100644 --- a/src/plugins/imageviewer/exportdialog.cpp +++ b/src/plugins/imageviewer/exportdialog.cpp @@ -24,8 +24,9 @@ #include #include -namespace ImageViewer { -namespace Internal { +using namespace Utils; + +namespace ImageViewer::Internal { enum { exportMinimumSize = 1, exportMaximumSize = 2000 }; @@ -98,10 +99,10 @@ void ExportDialog::accept() QMessageBox::warning(this, windowTitle(), m_pathChooser->errorMessage()); return; } - const QString fileName = exportFileName(); - if (QFileInfo::exists(fileName)) { + const FilePath filePath = exportFileName(); + if (filePath.exists()) { const QString question = Tr::tr("%1 already exists.\nWould you like to overwrite it?") - .arg(QDir::toNativeSeparators(fileName)); + .arg(filePath.toUserOutput()); if (QMessageBox::question(this, windowTitle(), question, QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) return; } @@ -156,14 +157,14 @@ void ExportDialog::exportHeightChanged(int height) setExportWidthBlocked(square ? height : qRound(qreal(height) * m_aspectRatio)); } -QString ExportDialog::exportFileName() const +FilePath ExportDialog::exportFileName() const { - return m_pathChooser->filePath().toString(); + return m_pathChooser->filePath(); } -void ExportDialog::setExportFileName(const QString &f) +void ExportDialog::setExportFileName(const FilePath &f) { - m_pathChooser->setFilePath(Utils::FilePath::fromString(f)); + m_pathChooser->setFilePath(f); } ExportData ExportDialog::exportData() const @@ -171,5 +172,4 @@ ExportData ExportDialog::exportData() const return {exportFileName(), exportSize()}; } -} // namespace Internal -} // namespace ImageViewer +} // ImageViewer::Internal diff --git a/src/plugins/imageviewer/exportdialog.h b/src/plugins/imageviewer/exportdialog.h index b251a2ab65f..5868cc7ef7c 100644 --- a/src/plugins/imageviewer/exportdialog.h +++ b/src/plugins/imageviewer/exportdialog.h @@ -7,7 +7,10 @@ QT_FORWARD_DECLARE_CLASS(QSpinBox) -namespace Utils { class PathChooser; } +namespace Utils { +class FilePath; +class PathChooser; +} // Utils namespace ImageViewer::Internal { @@ -21,8 +24,8 @@ public: QSize exportSize() const; void setExportSize(const QSize &); - QString exportFileName() const; - void setExportFileName(const QString &); + Utils::FilePath exportFileName() const; + void setExportFileName(const Utils::FilePath &); ExportData exportData() const; diff --git a/src/plugins/imageviewer/imageview.cpp b/src/plugins/imageviewer/imageview.cpp index 9a2af284f49..01d9b3968fc 100644 --- a/src/plugins/imageviewer/imageview.cpp +++ b/src/plugins/imageviewer/imageview.cpp @@ -40,6 +40,8 @@ const char kSettingsBackground[] = "ShowBackground"; const char kSettingsOutline[] = "ShowOutline"; const char kSettingsFitToScreen[] = "FitToScreen"; +using namespace Utils; + namespace ImageViewer { namespace Constants { const qreal DEFAULT_SCALE_FACTOR = 1.2; @@ -157,25 +159,24 @@ QImage ImageView::renderSvg(const QSize &imageSize) const bool ImageView::exportSvg(const ExportData &ed) { - const bool result = renderSvg(ed.size).save(ed.fileName); + const bool result = renderSvg(ed.size).save(ed.filePath.toFSPathString()); if (result) { const QString message = Tr::tr("Exported \"%1\", %2x%3, %4 bytes") - .arg(QDir::toNativeSeparators(ed.fileName)) + .arg(ed.filePath.toUserOutput()) .arg(ed.size.width()).arg(ed.size.height()) - .arg(QFileInfo(ed.fileName).size()); + .arg(ed.filePath.fileSize()); Core::MessageManager::writeDisrupting(message); } else { - const QString message = Tr::tr("Could not write file \"%1\".").arg(QDir::toNativeSeparators(ed.fileName)); + const QString message = Tr::tr("Could not write file \"%1\".").arg(ed.filePath.toUserOutput()); QMessageBox::critical(this, Tr::tr("Export Image"), message); } return result; } #ifndef QT_NO_SVG -static QString suggestedExportFileName(const QFileInfo &fi) +static FilePath suggestedExportFileName(const FilePath &fi) { - return fi.absolutePath() + QLatin1Char('/') + fi.baseName() - + QStringLiteral(".png"); + return fi.absolutePath().pathAppended(fi.baseName() + ".png"); } #endif @@ -195,11 +196,11 @@ void ImageView::exportImage() auto svgItem = qgraphicsitem_cast(m_imageItem); QTC_ASSERT(svgItem, return); - const QFileInfo origFi = m_file->filePath().toFileInfo(); + const FilePath origPath = m_file->filePath(); ExportDialog exportDialog(this); - exportDialog.setWindowTitle(Tr::tr("Export %1").arg(origFi.fileName())); + exportDialog.setWindowTitle(Tr::tr("Export %1").arg(origPath.fileName())); exportDialog.setExportSize(svgSize()); - exportDialog.setExportFileName(suggestedExportFileName(origFi)); + exportDialog.setExportFileName(suggestedExportFileName(origPath)); while (exportDialog.exec() == QDialog::Accepted && !exportSvg(exportDialog.exportData())) {} #endif // !QT_NO_SVG @@ -210,14 +211,13 @@ void ImageView::exportMultiImages() #ifndef QT_NO_SVG QTC_ASSERT(qgraphicsitem_cast(m_imageItem), return); - const QFileInfo origFi = m_file->filePath().toFileInfo(); + const FilePath origPath = m_file->filePath(); const QSize size = svgSize(); - const QString title = - Tr::tr("Export a Series of Images from %1 (%2x%3)") - .arg(origFi.fileName()).arg(size.width()).arg(size.height()); + const QString title = Tr::tr("Export a Series of Images from %1 (%2x%3)") + .arg(origPath.fileName()).arg(size.width()).arg(size.height()); MultiExportDialog multiExportDialog; multiExportDialog.setWindowTitle(title); - multiExportDialog.setExportFileName(suggestedExportFileName(origFi)); + multiExportDialog.setExportFileName(suggestedExportFileName(origPath)); multiExportDialog.setSvgSize(size); multiExportDialog.suggestSizes(); diff --git a/src/plugins/imageviewer/imageview.h b/src/plugins/imageviewer/imageview.h index 0538b58b1a6..6bee8e3243e 100644 --- a/src/plugins/imageviewer/imageview.h +++ b/src/plugins/imageviewer/imageview.h @@ -4,6 +4,8 @@ #pragma once +#include + #include QT_FORWARD_DECLARE_CLASS(QImage) @@ -17,7 +19,7 @@ namespace ImageViewer::Internal { class ImageViewerFile; struct ExportData { - QString fileName; + Utils::FilePath filePath; QSize size; }; diff --git a/src/plugins/imageviewer/multiexportdialog.cpp b/src/plugins/imageviewer/multiexportdialog.cpp index 0befd2fe378..1b526c9b11f 100644 --- a/src/plugins/imageviewer/multiexportdialog.cpp +++ b/src/plugins/imageviewer/multiexportdialog.cpp @@ -15,8 +15,6 @@ #include #include -#include -#include #include #include #include @@ -27,6 +25,8 @@ #include #include +using namespace Utils; + namespace ImageViewer::Internal { static const int standardIconSizesValues[] = {16, 24, 32, 48, 64, 128, 256}; @@ -95,11 +95,11 @@ static QVector stringToSizes(const QString &s) return result; } -static QString fileNameForSize(QString pattern, const QSize &s) +static FilePath fileNameForSize(QString pattern, const QSize &s) { pattern.replace("%1", QString::number(s.width())); pattern.replace("%2", QString::number(s.height())); - return pattern; + return FilePath::fromString(pattern); } // Helpers for writing/reading the user-specified size specifications @@ -236,7 +236,7 @@ void MultiExportDialog::suggestSizes() QVector MultiExportDialog::exportData() const { const QVector sizeList = sizes(); - const QString pattern = exportFileName(); + const QString pattern = exportFileName().toString(); QVector result; result.reserve(sizeList.size()); for (const QSize &s : sizeList) @@ -268,7 +268,7 @@ void MultiExportDialog::accept() Tr::tr("Invalid size specification: %1").arg(sizeSpec)); return; } - if (data.size() > 1 && data.at(0).fileName == data.at(1).fileName) { + if (data.size() > 1 && data.at(0).filePath == data.at(1).filePath) { QMessageBox::warning(this, windowTitle(), Tr::tr("The file name must contain one of the placeholders %1, %2.") .arg(QString("%1"), QString("%2"))); @@ -277,17 +277,17 @@ void MultiExportDialog::accept() writeSettings(m_svgSize, sizeSpec); - QStringList existingFiles; + FilePaths existingFiles; for (const ExportData &d : data) { - if (QFileInfo::exists(d.fileName)) - existingFiles.append(d.fileName); + if (d.filePath.exists()) + existingFiles.append(d.filePath); } if (!existingFiles.isEmpty()) { const QString message = existingFiles.size() == 1 ? Tr::tr("The file %1 already exists.\nWould you like to overwrite it?") - .arg(QDir::toNativeSeparators(existingFiles.constFirst())) + .arg(existingFiles.constFirst().toUserOutput()) : Tr::tr("The files %1 already exist.\nWould you like to overwrite them?") - .arg(QDir::toNativeSeparators(existingFiles.join(", "))); + .arg(FilePath::formatFilePaths(existingFiles, ", ")); QMessageBox messageBox(QMessageBox::Question, windowTitle(), message, QMessageBox::Yes | QMessageBox::No, this); if (messageBox.exec() != QMessageBox::Yes) @@ -297,17 +297,21 @@ void MultiExportDialog::accept() QDialog::accept(); } -QString MultiExportDialog::exportFileName() const +FilePath MultiExportDialog::exportFileName() const { - return m_pathChooser->filePath().toString(); + return m_pathChooser->filePath(); } -void MultiExportDialog::setExportFileName(QString f) +void MultiExportDialog::setExportFileName(const FilePath &filePath) { - const int lastDot = f.lastIndexOf('.'); - if (lastDot != -1) - f.insert(lastDot, "-%1"); - m_pathChooser->setFilePath(Utils::FilePath::fromString(f)); + FilePath f = filePath; + QString ff = f.path(); + const int lastDot = ff.lastIndexOf('.'); + if (lastDot != -1) { + ff.insert(lastDot, "-%1"); + f = f.withNewPath(ff); + }; + m_pathChooser->setFilePath(f); } } // ImageViewer:Internal diff --git a/src/plugins/imageviewer/multiexportdialog.h b/src/plugins/imageviewer/multiexportdialog.h index 75fcaae3df3..bd8ed32b1a2 100644 --- a/src/plugins/imageviewer/multiexportdialog.h +++ b/src/plugins/imageviewer/multiexportdialog.h @@ -4,14 +4,16 @@ #pragma once #include - #include #include #include QT_FORWARD_DECLARE_CLASS(QLineEdit) -namespace Utils { class PathChooser; } +namespace Utils { +class FilePath; +class PathChooser; +} // Utils namespace ImageViewer::Internal { @@ -19,12 +21,11 @@ struct ExportData; class MultiExportDialog : public QDialog { - Q_OBJECT public: explicit MultiExportDialog(QWidget *parent = nullptr); - QString exportFileName() const; - void setExportFileName(QString); + Utils::FilePath exportFileName() const; + void setExportFileName(const Utils::FilePath &); void accept() override; diff --git a/src/plugins/ios/iosdeploystep.cpp b/src/plugins/ios/iosdeploystep.cpp index 7bf9d7cbe0d..2995f290ffe 100644 --- a/src/plugins/ios/iosdeploystep.cpp +++ b/src/plugins/ios/iosdeploystep.cpp @@ -46,11 +46,11 @@ private: void doRun() final; void doCancel() final; - void handleIsTransferringApp(IosToolHandler *handler, const QString &bundlePath, + void handleIsTransferringApp(IosToolHandler *handler, const FilePath &bundlePath, const QString &deviceId, int progress, int maxProgress, const QString &info); - void handleDidTransferApp(IosToolHandler *handler, const QString &bundlePath, const QString &deviceId, - IosToolHandler::OpStatus status); + void handleDidTransferApp(IosToolHandler *handler, const FilePath &bundlePath, + const QString &deviceId, IosToolHandler::OpStatus status); void handleFinished(IosToolHandler *handler); void handleErrorMsg(IosToolHandler *handler, const QString &msg); void updateDisplayNames(); @@ -133,7 +133,7 @@ void IosDeployStep::doRun() connect(m_toolHandler, &IosToolHandler::errorMsg, this, &IosDeployStep::handleErrorMsg); checkProvisioningProfile(); - m_toolHandler->requestTransferApp(m_bundlePath.toString(), m_deviceType.identifier); + m_toolHandler->requestTransferApp(m_bundlePath, m_deviceType.identifier); } void IosDeployStep::doCancel() @@ -151,7 +151,7 @@ void IosDeployStep::cleanup() m_expectFail = false; } -void IosDeployStep::handleIsTransferringApp(IosToolHandler *handler, const QString &bundlePath, +void IosDeployStep::handleIsTransferringApp(IosToolHandler *handler, const FilePath &bundlePath, const QString &deviceId, int progress, int maxProgress, const QString &info) { @@ -160,7 +160,7 @@ void IosDeployStep::handleIsTransferringApp(IosToolHandler *handler, const QStri emit this->progress(progress * 100 / maxProgress, info); } -void IosDeployStep::handleDidTransferApp(IosToolHandler *handler, const QString &bundlePath, +void IosDeployStep::handleDidTransferApp(IosToolHandler *handler, const FilePath &bundlePath, const QString &deviceId, IosToolHandler::OpStatus status) { Q_UNUSED(handler); Q_UNUSED(bundlePath); Q_UNUSED(deviceId) diff --git a/src/plugins/ios/iosrunner.cpp b/src/plugins/ios/iosrunner.cpp index 828bb65c007..9b1f2d04869 100644 --- a/src/plugins/ios/iosrunner.cpp +++ b/src/plugins/ios/iosrunner.cpp @@ -81,7 +81,7 @@ public: void setCppDebugging(bool cppDebug); void setQmlDebugging(QmlDebug::QmlDebugServicesPreset qmlDebugServices); - QString bundlePath(); + Utils::FilePath bundlePath() const; QString deviceId(); IosToolHandler::RunKind runType(); bool cppDebug() const; @@ -101,9 +101,9 @@ public: bool isAppRunning() const; private: - void handleGotServerPorts(Ios::IosToolHandler *handler, const QString &bundlePath, + void handleGotServerPorts(Ios::IosToolHandler *handler, const FilePath &bundlePath, const QString &deviceId, Port gdbPort, Port qmlPort); - void handleGotInferiorPid(Ios::IosToolHandler *handler, const QString &bundlePath, + void handleGotInferiorPid(Ios::IosToolHandler *handler, const FilePath &bundlePath, const QString &deviceId, qint64 pid); void handleAppOutput(Ios::IosToolHandler *handler, const QString &output); void handleErrorMsg(Ios::IosToolHandler *handler, const QString &msg); @@ -111,7 +111,7 @@ private: void handleFinished(Ios::IosToolHandler *handler); IosToolHandler *m_toolHandler = nullptr; - QString m_bundleDir; + FilePath m_bundleDir; IDeviceConstPtr m_device; IosDeviceType m_deviceType; bool m_cppDebug = false; @@ -130,7 +130,7 @@ IosRunner::IosRunner(RunControl *runControl) stopRunningRunControl(runControl); const IosDeviceTypeAspect::Data *data = runControl->aspect(); QTC_ASSERT(data, return); - m_bundleDir = data->bundleDirectory.toString(); + m_bundleDir = data->bundleDirectory; m_device = DeviceKitAspect::device(runControl->kit()); m_deviceType = data->deviceType; } @@ -150,7 +150,7 @@ void IosRunner::setQmlDebugging(QmlDebug::QmlDebugServicesPreset qmlDebugService m_qmlDebugServices = qmlDebugServices; } -QString IosRunner::bundlePath() +FilePath IosRunner::bundlePath() const { return m_bundleDir; } @@ -192,9 +192,9 @@ void IosRunner::start() m_cleanExit = false; m_qmlServerPort = Port(); - if (!QFileInfo::exists(m_bundleDir)) { + if (!m_bundleDir.exists()) { TaskHub::addTask(DeploymentTask(Task::Warning, - Tr::tr("Could not find %1.").arg(m_bundleDir))); + Tr::tr("Could not find %1.").arg(m_bundleDir.toUserOutput()))); reportFailure(); return; } @@ -247,7 +247,7 @@ void IosRunner::stop() m_toolHandler->stop(); } -void IosRunner::handleGotServerPorts(IosToolHandler *handler, const QString &bundlePath, +void IosRunner::handleGotServerPorts(IosToolHandler *handler, const FilePath &bundlePath, const QString &deviceId, Port gdbPort, Port qmlPort) { @@ -278,7 +278,7 @@ void IosRunner::handleGotServerPorts(IosToolHandler *handler, const QString &bun reportFailure(Tr::tr("Could not get necessary ports for the debugger connection.")); } -void IosRunner::handleGotInferiorPid(IosToolHandler *handler, const QString &bundlePath, +void IosRunner::handleGotInferiorPid(IosToolHandler *handler, const FilePath &bundlePath, const QString &deviceId, qint64 pid) { // Called when debugging on Simulator. diff --git a/src/plugins/ios/iostoolhandler.cpp b/src/plugins/ios/iostoolhandler.cpp index 0e4545bf1da..18cc42d44e2 100644 --- a/src/plugins/ios/iostoolhandler.cpp +++ b/src/plugins/ios/iostoolhandler.cpp @@ -20,7 +20,6 @@ #include #include -#include #include #include #include @@ -42,6 +41,8 @@ static Q_LOGGING_CATEGORY(toolHandlerLog, "qtc.ios.toolhandler", QtWarningMsg) +using namespace Utils; + namespace Ios { namespace Internal { @@ -166,9 +167,9 @@ class IosToolHandlerPrivate public: explicit IosToolHandlerPrivate(const IosDeviceType &devType, IosToolHandler *q); virtual ~IosToolHandlerPrivate(); - virtual void requestTransferApp(const QString &bundlePath, const QString &deviceId, + virtual void requestTransferApp(const FilePath &bundlePath, const QString &deviceId, int timeout = 1000) = 0; - virtual void requestRunApp(const QString &bundlePath, const QStringList &extraArgs, + virtual void requestRunApp(const FilePath &bundlePath, const QStringList &extraArgs, IosToolHandler::RunKind runKind, const QString &deviceId, int timeout = 1000) = 0; virtual void requestDeviceInfo(const QString &deviceId, int timeout = 1000) = 0; @@ -176,15 +177,15 @@ public: virtual void stop(int errorCode) = 0; // signals - void isTransferringApp(const QString &bundlePath, const QString &deviceId, int progress, + void isTransferringApp(const FilePath &bundlePath, const QString &deviceId, int progress, int maxProgress, const QString &info); - void didTransferApp(const QString &bundlePath, const QString &deviceId, + void didTransferApp(const FilePath &bundlePath, const QString &deviceId, IosToolHandler::OpStatus status); - void didStartApp(const QString &bundlePath, const QString &deviceId, + void didStartApp(const FilePath &bundlePath, const QString &deviceId, IosToolHandler::OpStatus status); - void gotServerPorts(const QString &bundlePath, const QString &deviceId, Utils::Port gdbPort, - Utils::Port qmlPort); - void gotInferiorPid(const QString &bundlePath, const QString &deviceId, qint64 pid); + void gotServerPorts(const FilePath &bundlePath, const QString &deviceId, Port gdbPort, + Port qmlPort); + void gotInferiorPid(const FilePath &bundlePath, const QString &deviceId, qint64 pid); void deviceInfo(const QString &deviceId, const IosToolHandler::Dict &info); void appOutput(const QString &output); void errorMsg(const QString &msg); @@ -193,7 +194,7 @@ public: protected: IosToolHandler *q; QString m_deviceId; - QString m_bundlePath; + FilePath m_bundlePath; IosToolHandler::RunKind m_runKind = IosToolHandler::NormalRun; IosDeviceType m_devType; }; @@ -219,9 +220,9 @@ public: // IosToolHandlerPrivate overrides public: - void requestTransferApp(const QString &bundlePath, const QString &deviceId, + void requestTransferApp(const FilePath &bundlePath, const QString &deviceId, int timeout = 1000) override; - void requestRunApp(const QString &bundlePath, const QStringList &extraArgs, + void requestRunApp(const FilePath &bundlePath, const QStringList &extraArgs, IosToolHandler::RunKind runKind, const QString &deviceId, int timeout = 1000) override; void requestDeviceInfo(const QString &deviceId, int timeout = 1000) override; @@ -287,9 +288,9 @@ public: // IosToolHandlerPrivate overrides public: - void requestTransferApp(const QString &appBundlePath, const QString &deviceIdentifier, + void requestTransferApp(const FilePath &appBundlePath, const QString &deviceIdentifier, int timeout = 1000) override; - void requestRunApp(const QString &appBundlePath, const QStringList &extraArgs, + void requestRunApp(const FilePath &appBundlePath, const QStringList &extraArgs, IosToolHandler::RunKind runKind, const QString &deviceIdentifier, int timeout = 1000) override; void requestDeviceInfo(const QString &deviceId, int timeout = 1000) override; @@ -317,31 +318,31 @@ IosToolHandlerPrivate::IosToolHandlerPrivate(const IosDeviceType &devType, IosToolHandlerPrivate::~IosToolHandlerPrivate() = default; // signals -void IosToolHandlerPrivate::isTransferringApp(const QString &bundlePath, const QString &deviceId, +void IosToolHandlerPrivate::isTransferringApp(const FilePath &bundlePath, const QString &deviceId, int progress, int maxProgress, const QString &info) { emit q->isTransferringApp(q, bundlePath, deviceId, progress, maxProgress, info); } -void IosToolHandlerPrivate::didTransferApp(const QString &bundlePath, const QString &deviceId, +void IosToolHandlerPrivate::didTransferApp(const FilePath &bundlePath, const QString &deviceId, Ios::IosToolHandler::OpStatus status) { emit q->didTransferApp(q, bundlePath, deviceId, status); } -void IosToolHandlerPrivate::didStartApp(const QString &bundlePath, const QString &deviceId, +void IosToolHandlerPrivate::didStartApp(const FilePath &bundlePath, const QString &deviceId, IosToolHandler::OpStatus status) { emit q->didStartApp(q, bundlePath, deviceId, status); } -void IosToolHandlerPrivate::gotServerPorts(const QString &bundlePath, const QString &deviceId, - Utils::Port gdbPort, Utils::Port qmlPort) +void IosToolHandlerPrivate::gotServerPorts(const FilePath &bundlePath, const QString &deviceId, + Port gdbPort, Port qmlPort) { emit q->gotServerPorts(q, bundlePath, deviceId, gdbPort, qmlPort); } -void IosToolHandlerPrivate::gotInferiorPid(const QString &bundlePath, const QString &deviceId, +void IosToolHandlerPrivate::gotInferiorPid(const FilePath &bundlePath, const QString &deviceId, qint64 pid) { emit q->gotInferiorPid(q, bundlePath, deviceId, pid); @@ -674,7 +675,7 @@ IosDeviceToolHandlerPrivate::~IosDeviceToolHandlerPrivate() } } -void IosDeviceToolHandlerPrivate::requestTransferApp(const QString &bundlePath, +void IosDeviceToolHandlerPrivate::requestTransferApp(const FilePath &bundlePath, const QString &deviceId, int timeout) { m_bundlePath = bundlePath; @@ -682,7 +683,7 @@ void IosDeviceToolHandlerPrivate::requestTransferApp(const QString &bundlePath, QString tmpDeltaPath = Utils::TemporaryDirectory::masterDirectoryFilePath().pathAppended("ios").toString(); QStringList args; args << QLatin1String("--id") << deviceId << QLatin1String("--bundle") - << bundlePath << QLatin1String("--timeout") << QString::number(timeout) + << bundlePath.path() << QLatin1String("--timeout") << QString::number(timeout) << QLatin1String("--install") << QLatin1String("--delta-path") << tmpDeltaPath; @@ -690,7 +691,7 @@ void IosDeviceToolHandlerPrivate::requestTransferApp(const QString &bundlePath, start(IosToolHandler::iosDeviceToolPath(), args); } -void IosDeviceToolHandlerPrivate::requestRunApp(const QString &bundlePath, +void IosDeviceToolHandlerPrivate::requestRunApp(const FilePath &bundlePath, const QStringList &extraArgs, IosToolHandler::RunKind runType, const QString &deviceId, int timeout) @@ -700,7 +701,7 @@ void IosDeviceToolHandlerPrivate::requestRunApp(const QString &bundlePath, m_runKind = runType; QStringList args; args << QLatin1String("--id") << deviceId << QLatin1String("--bundle") - << bundlePath << QLatin1String("--timeout") << QString::number(timeout); + << bundlePath.path() << QLatin1String("--timeout") << QString::number(timeout); switch (runType) { case IosToolHandler::NormalRun: args << QLatin1String("--run"); @@ -789,7 +790,7 @@ IosSimulatorToolHandlerPrivate::IosSimulatorToolHandlerPrivate(const IosDeviceTy std::bind(&IosToolHandlerPrivate::appOutput, this, _1)); } -void IosSimulatorToolHandlerPrivate::requestTransferApp(const QString &appBundlePath, +void IosSimulatorToolHandlerPrivate::requestTransferApp(const FilePath &appBundlePath, const QString &deviceIdentifier, int timeout) { Q_UNUSED(timeout) @@ -817,7 +818,7 @@ void IosSimulatorToolHandlerPrivate::requestTransferApp(const QString &appBundle SimulatorControl::startSimulator(m_deviceId), q, onSimulatorStart)); } -void IosSimulatorToolHandlerPrivate::requestRunApp(const QString &appBundlePath, +void IosSimulatorToolHandlerPrivate::requestRunApp(const FilePath &appBundlePath, const QStringList &extraArgs, IosToolHandler::RunKind runType, const QString &deviceIdentifier, int timeout) @@ -828,10 +829,9 @@ void IosSimulatorToolHandlerPrivate::requestRunApp(const QString &appBundlePath, m_deviceId = m_devType.identifier; m_runKind = runType; - Utils::FilePath appBundle = Utils::FilePath::fromString(m_bundlePath); - if (!appBundle.exists()) { + if (!m_bundlePath.exists()) { errorMsg(Tr::tr("Application launch on simulator failed. Invalid bundle path %1") - .arg(m_bundlePath)); + .arg(m_bundlePath.toUserOutput())); didStartApp(m_bundlePath, m_deviceId, Ios::IosToolHandler::Failure); return; } @@ -901,15 +901,13 @@ void IosSimulatorToolHandlerPrivate::installAppOnSimulator() }; isTransferringApp(m_bundlePath, m_deviceId, 20, 100, ""); - auto installFuture = SimulatorControl::installApp(m_deviceId, - Utils::FilePath::fromString(m_bundlePath)); + auto installFuture = SimulatorControl::installApp(m_deviceId, m_bundlePath); futureSynchronizer.addFuture(Utils::onResultReady(installFuture, q, onResponseAppInstall)); } void IosSimulatorToolHandlerPrivate::launchAppOnSimulator(const QStringList &extraArgs) { - const Utils::FilePath appBundle = Utils::FilePath::fromString(m_bundlePath); - const QString bundleId = SimulatorControl::bundleIdentifier(appBundle); + const QString bundleId = SimulatorControl::bundleIdentifier(m_bundlePath); const bool debugRun = m_runKind == IosToolHandler::DebugRun; bool captureConsole = IosConfigurations::xcodeVersion() >= QVersionNumber(8); std::shared_ptr stdoutFile; @@ -1012,13 +1010,13 @@ void IosToolHandler::stop() d->stop(-1); } -void IosToolHandler::requestTransferApp(const QString &bundlePath, const QString &deviceId, +void IosToolHandler::requestTransferApp(const FilePath &bundlePath, const QString &deviceId, int timeout) { d->requestTransferApp(bundlePath, deviceId, timeout); } -void IosToolHandler::requestRunApp(const QString &bundlePath, const QStringList &extraArgs, +void IosToolHandler::requestRunApp(const FilePath &bundlePath, const QStringList &extraArgs, RunKind runType, const QString &deviceId, int timeout) { d->requestRunApp(bundlePath, extraArgs, runType, deviceId, timeout); diff --git a/src/plugins/ios/iostoolhandler.h b/src/plugins/ios/iostoolhandler.h index 4d6c4bee780..a85e3250b40 100644 --- a/src/plugins/ios/iostoolhandler.h +++ b/src/plugins/ios/iostoolhandler.h @@ -3,6 +3,7 @@ #pragma once +#include #include #include @@ -35,24 +36,24 @@ public: explicit IosToolHandler(const Internal::IosDeviceType &type, QObject *parent = nullptr); ~IosToolHandler() override; - void requestTransferApp(const QString &bundlePath, const QString &deviceId, int timeout = 1000); - void requestRunApp(const QString &bundlePath, const QStringList &extraArgs, RunKind runType, + void requestTransferApp(const Utils::FilePath &bundlePath, const QString &deviceId, int timeout = 1000); + void requestRunApp(const Utils::FilePath &bundlePath, const QStringList &extraArgs, RunKind runType, const QString &deviceId, int timeout = 1000); void requestDeviceInfo(const QString &deviceId, int timeout = 1000); bool isRunning() const; void stop(); signals: - void isTransferringApp(Ios::IosToolHandler *handler, const QString &bundlePath, + void isTransferringApp(Ios::IosToolHandler *handler, const Utils::FilePath &bundlePath, const QString &deviceId, int progress, int maxProgress, const QString &info); - void didTransferApp(Ios::IosToolHandler *handler, const QString &bundlePath, + void didTransferApp(Ios::IosToolHandler *handler, const Utils::FilePath &bundlePath, const QString &deviceId, Ios::IosToolHandler::OpStatus status); - void didStartApp(Ios::IosToolHandler *handler, const QString &bundlePath, + void didStartApp(Ios::IosToolHandler *handler, const Utils::FilePath &bundlePath, const QString &deviceId, Ios::IosToolHandler::OpStatus status); - void gotServerPorts(Ios::IosToolHandler *handler, const QString &bundlePath, + void gotServerPorts(Ios::IosToolHandler *handler, const Utils::FilePath &bundlePath, const QString &deviceId, Utils::Port gdbPort, Utils::Port qmlPort); - void gotInferiorPid(Ios::IosToolHandler *handler, const QString &bundlePath, + void gotInferiorPid(Ios::IosToolHandler *handler, const Utils::FilePath &bundlePath, const QString &deviceId, qint64 pid); void deviceInfo(Ios::IosToolHandler *handler, const QString &deviceId, const Ios::IosToolHandler::Dict &info); diff --git a/src/plugins/languageclient/client.cpp b/src/plugins/languageclient/client.cpp index 130961ebd1b..bb5a4594dc5 100644 --- a/src/plugins/languageclient/client.cpp +++ b/src/plugins/languageclient/client.cpp @@ -313,6 +313,7 @@ public: AssistProviders m_clientProviders; QMap m_resetAssistProvider; QHash m_highlightRequests; + QHash m_customHandlers; static const int MaxRestarts = 5; int m_restartsLeft = MaxRestarts; QTimer m_restartCountResetTimer; @@ -1921,6 +1922,12 @@ void ClientPrivate::handleMethod(const QString &method, const MessageId &id, con error.setMessage(QString("The client cannot handle the method '%1'.").arg(method)); response.setError(error); sendResponse(response); + } else { + const auto customHandler = m_customHandlers.constFind(method); + if (customHandler != m_customHandlers.constEnd()) { + (*customHandler)(message); + return; + } } // we got a request and handled it somewhere above but we missed to generate a response for it @@ -2136,6 +2143,11 @@ DocumentUri Client::hostPathToServerUri(const Utils::FilePath &path) const }); } +void Client::registerCustomMethod(const QString &method, const CustomMethodHandler &handler) +{ + d->m_customHandlers.insert(method, handler); +} + } // namespace LanguageClient #include diff --git a/src/plugins/languageclient/client.h b/src/plugins/languageclient/client.h index 2ddd155a9f1..9c934ea1611 100644 --- a/src/plugins/languageclient/client.h +++ b/src/plugins/languageclient/client.h @@ -169,6 +169,11 @@ public: Utils::FilePath serverUriToHostPath(const LanguageServerProtocol::DocumentUri &uri) const; LanguageServerProtocol::DocumentUri hostPathToServerUri(const Utils::FilePath &path) const; + // custom methods + using CustomMethodHandler = std::function; + void registerCustomMethod(const QString &method, const CustomMethodHandler &handler); + // logging enum class LogTarget { Console, Ui }; void setLogTarget(LogTarget target); diff --git a/src/plugins/languageclient/clientrequesttask.cpp b/src/plugins/languageclient/clientrequesttask.cpp index ed3ddaff2c5..6da5be5704c 100644 --- a/src/plugins/languageclient/clientrequesttask.cpp +++ b/src/plugins/languageclient/clientrequesttask.cpp @@ -3,8 +3,6 @@ #include "clientrequesttask.h" -#include - using namespace LanguageServerProtocol; namespace LanguageClient { diff --git a/src/plugins/marketplace/productlistmodel.cpp b/src/plugins/marketplace/productlistmodel.cpp index 36b047abc21..1de5a4b833d 100644 --- a/src/plugins/marketplace/productlistmodel.cpp +++ b/src/plugins/marketplace/productlistmodel.cpp @@ -4,7 +4,6 @@ #include "productlistmodel.h" #include -#include #include #include @@ -19,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -107,7 +107,7 @@ void SectionedProducts::updateCollections() void SectionedProducts::onFetchCollectionsFinished(QNetworkReply *reply) { QTC_ASSERT(reply, return); - Utils::ExecuteOnDestruction replyDeleter([reply]() { reply->deleteLater(); }); + const QScopeGuard cleanup([reply] { reply->deleteLater(); }); if (reply->error() == QNetworkReply::NoError) { const QJsonDocument doc = QJsonDocument::fromJson(reply->readAll()); @@ -141,7 +141,7 @@ void SectionedProducts::onFetchSingleCollectionFinished(QNetworkReply *reply) emit toggleProgressIndicator(false); QTC_ASSERT(reply, return); - Utils::ExecuteOnDestruction replyDeleter([reply]() { reply->deleteLater(); }); + const QScopeGuard cleanup([reply] { reply->deleteLater(); }); QList productsForCollection; if (reply->error() == QNetworkReply::NoError) { @@ -259,7 +259,7 @@ void SectionedProducts::fetchNextImage() void SectionedProducts::onImageDownloadFinished(QNetworkReply *reply) { QTC_ASSERT(reply, return); - Utils::ExecuteOnDestruction replyDeleter([reply]() { reply->deleteLater(); }); + const QScopeGuard cleanup([reply] { reply->deleteLater(); }); if (reply->error() == QNetworkReply::NoError) { const QByteArray data = reply->readAll(); diff --git a/src/plugins/projectexplorer/jsonwizard/jsonfieldpage.cpp b/src/plugins/projectexplorer/jsonwizard/jsonfieldpage.cpp index 9e73aa479eb..acb32043dc7 100644 --- a/src/plugins/projectexplorer/jsonwizard/jsonfieldpage.cpp +++ b/src/plugins/projectexplorer/jsonwizard/jsonfieldpage.cpp @@ -950,12 +950,12 @@ QVariant CheckBoxField::toSettings() const std::unique_ptr createStandardItemFromListItem(const QVariant &item, QString *errorMessage) { - if (item.type() == QVariant::List) { + if (item.typeId() == QVariant::List) { *errorMessage = Tr::tr("No JSON lists allowed inside List items."); return {}; } auto standardItem = std::make_unique(); - if (item.type() == QVariant::Map) { + if (item.typeId() == QVariant::Map) { QVariantMap tmp = item.toMap(); const QString key = JsonWizardFactory::localizedString(consumeValue(tmp, "trKey", QString()).toString()); const QVariant value = consumeValue(tmp, "value", key); @@ -985,7 +985,7 @@ ListField::~ListField() = default; bool ListField::parseData(const QVariant &data, QString *errorMessage) { - if (data.type() != QVariant::Map) { + if (data.typeId() != QVariant::Map) { *errorMessage = Tr::tr("%1 (\"%2\") data is not an object.").arg(type(), name()); return false; } @@ -1011,7 +1011,7 @@ bool ListField::parseData(const QVariant &data, QString *errorMessage) *errorMessage = Tr::tr("%1 (\"%2\") \"items\" missing.").arg(type(), name()); return false; } - if (value.type() != QVariant::List) { + if (value.typeId() != QVariant::List) { *errorMessage = Tr::tr("%1 (\"%2\") \"items\" is not a JSON list.").arg(type(), name()); return false; } diff --git a/src/plugins/projectexplorer/kit.cpp b/src/plugins/projectexplorer/kit.cpp index b0d370d13ce..27bad16e8c8 100644 --- a/src/plugins/projectexplorer/kit.cpp +++ b/src/plugins/projectexplorer/kit.cpp @@ -578,7 +578,7 @@ QString Kit::toHtml(const Tasks &additional, const QString &extraText) const const KitAspect::ItemList list = aspect->toUserOutput(this); for (const KitAspect::Item &j : list) { QString contents = j.second; - if (contents.count() > 256) { + if (contents.size() > 256) { int pos = contents.lastIndexOf("
", 256); if (pos < 0) // no linebreak, so cut early. pos = 80; diff --git a/src/plugins/projectexplorer/makestep.cpp b/src/plugins/projectexplorer/makestep.cpp index ee9ffea832b..028706fa2db 100644 --- a/src/plugins/projectexplorer/makestep.cpp +++ b/src/plugins/projectexplorer/makestep.cpp @@ -4,6 +4,7 @@ #include "makestep.h" #include "buildconfiguration.h" +#include "devicesupport/idevice.h" #include "gnumakeparser.h" #include "kitinformation.h" #include "processparameters.h" @@ -46,65 +47,58 @@ MakeStep::MakeStep(BuildStepList *parent, Id id) setCommandLineProvider([this] { return effectiveMakeCommand(Execution); }); - m_makeCommandAspect = addAspect(); - m_makeCommandAspect->setSettingsKey(id.withSuffix(MAKE_COMMAND_SUFFIX).toString()); - m_makeCommandAspect->setExpectedKind(PathChooser::ExistingCommand); - m_makeCommandAspect->setBaseFileName(PathChooser::homePath()); - m_makeCommandAspect->setHistoryCompleter("PE.MakeCommand.History"); + m_makeCommandAspect.setSettingsKey(id.withSuffix(MAKE_COMMAND_SUFFIX).toString()); + m_makeCommandAspect.setExpectedKind(PathChooser::ExistingCommand); + m_makeCommandAspect.setBaseFileName(PathChooser::homePath()); + m_makeCommandAspect.setHistoryCompleter("PE.MakeCommand.History"); - m_userArgumentsAspect = addAspect(); - m_userArgumentsAspect->setSettingsKey(id.withSuffix(MAKE_ARGUMENTS_SUFFIX).toString()); - m_userArgumentsAspect->setLabelText(Tr::tr("Make arguments:")); - m_userArgumentsAspect->setDisplayStyle(StringAspect::LineEditDisplay); + m_userArgumentsAspect.setSettingsKey(id.withSuffix(MAKE_ARGUMENTS_SUFFIX).toString()); + m_userArgumentsAspect.setLabelText(Tr::tr("Make arguments:")); + m_userArgumentsAspect.setDisplayStyle(StringAspect::LineEditDisplay); - m_userJobCountAspect = addAspect(); - m_userJobCountAspect->setSettingsKey(id.withSuffix(JOBCOUNT_SUFFIX).toString()); - m_userJobCountAspect->setLabel(Tr::tr("Parallel jobs:")); - m_userJobCountAspect->setRange(1, 999); - m_userJobCountAspect->setValue(defaultJobCount()); - m_userJobCountAspect->setDefaultValue(defaultJobCount()); + m_jobCountAspect.setSettingsKey(id.withSuffix(JOBCOUNT_SUFFIX).toString()); + m_jobCountAspect.setLabel(Tr::tr("Parallel jobs:")); + m_jobCountAspect.setRange(1, 999); + m_jobCountAspect.setValue(defaultJobCount()); + m_jobCountAspect.setDefaultValue(defaultJobCount()); const QString text = Tr::tr("Override MAKEFLAGS"); - m_overrideMakeflagsAspect = addAspect(); - m_overrideMakeflagsAspect->setSettingsKey(id.withSuffix(OVERRIDE_MAKEFLAGS_SUFFIX).toString()); - m_overrideMakeflagsAspect->setLabel(text, BoolAspect::LabelPlacement::AtCheckBox); + m_overrideMakeflagsAspect.setSettingsKey(id.withSuffix(OVERRIDE_MAKEFLAGS_SUFFIX).toString()); + m_overrideMakeflagsAspect.setLabel(text, BoolAspect::LabelPlacement::AtCheckBox); - m_nonOverrideWarning = addAspect(); - m_nonOverrideWarning->setText("

" + + m_nonOverrideWarning.setText("

" + Tr::tr("MAKEFLAGS specifies parallel jobs. Check \"%1\" to override.") .arg(text) + "

"); - m_nonOverrideWarning->setIconType(InfoLabel::Warning); + m_nonOverrideWarning.setIconType(InfoLabel::Warning); - m_disabledForSubdirsAspect = addAspect(); - m_disabledForSubdirsAspect->setSettingsKey(id.withSuffix(".disabledForSubdirs").toString()); - m_disabledForSubdirsAspect->setLabel(Tr::tr("Disable in subdirectories:")); - m_disabledForSubdirsAspect->setToolTip(Tr::tr("Runs this step only for a top-level build.")); + m_disabledForSubdirsAspect.setSettingsKey(id.withSuffix(".disabledForSubdirs").toString()); + m_disabledForSubdirsAspect.setLabel(Tr::tr("Disable in subdirectories:")); + m_disabledForSubdirsAspect.setToolTip(Tr::tr("Runs this step only for a top-level build.")); - m_buildTargetsAspect = addAspect(); - m_buildTargetsAspect->setSettingsKey(id.withSuffix(BUILD_TARGETS_SUFFIX).toString()); - m_buildTargetsAspect->setLabelText(Tr::tr("Targets:")); + m_buildTargetsAspect.setSettingsKey(id.withSuffix(BUILD_TARGETS_SUFFIX).toString()); + m_buildTargetsAspect.setLabelText(Tr::tr("Targets:")); const auto updateMakeLabel = [this] { const FilePath defaultMake = defaultMakeCommand(); const QString labelText = defaultMake.isEmpty() ? Tr::tr("Make:") : Tr::tr("Override %1:").arg(defaultMake.toUserOutput()); - m_makeCommandAspect->setLabelText(labelText); + m_makeCommandAspect.setLabelText(labelText); }; updateMakeLabel(); - connect(m_makeCommandAspect, &StringAspect::changed, this, updateMakeLabel); + connect(&m_makeCommandAspect, &StringAspect::changed, this, updateMakeLabel); } void MakeStep::setSelectedBuildTarget(const QString &buildTarget) { - m_buildTargetsAspect->setValue({buildTarget}); + m_buildTargetsAspect.setValue({buildTarget}); } void MakeStep::setAvailableBuildTargets(const QStringList &buildTargets) { - m_buildTargetsAspect->setAllValues(buildTargets); + m_buildTargetsAspect.setAllValues(buildTargets); } bool MakeStep::init() @@ -158,8 +152,11 @@ FilePath MakeStep::defaultMakeCommand() const const Environment env = makeEnvironment(); for (const ToolChain *tc : preferredToolChains(kit())) { FilePath make = tc->makeCommand(env); - if (!make.isEmpty()) - return mapFromBuildDeviceToGlobalPath(make); + if (!make.isEmpty()) { + IDevice::ConstPtr dev = BuildDeviceKitAspect::device(kit()); + QTC_ASSERT(dev, return {}); + return dev->filePath(make.path()); + } } return {}; } @@ -183,7 +180,7 @@ bool MakeStep::isJobCountSupported() const bool MakeStep::jobCountOverridesMakeflags() const { - return m_overrideMakeflagsAspect->value(); + return m_overrideMakeflagsAspect(); } static std::optional argsJobCount(const QString &str) @@ -216,12 +213,12 @@ bool MakeStep::makeflagsJobCountMismatch() const if (!env.hasKey(MAKEFLAGS)) return false; std::optional makeFlagsJobCount = argsJobCount(env.expandedValueForKey(MAKEFLAGS)); - return makeFlagsJobCount.has_value() && *makeFlagsJobCount != m_userJobCountAspect->value(); + return makeFlagsJobCount.has_value() && *makeFlagsJobCount != m_jobCountAspect(); } bool MakeStep::enabledForSubDirs() const { - return !m_disabledForSubdirsAspect->value(); + return !m_disabledForSubdirsAspect(); } bool MakeStep::makeflagsContainsJobCount() const @@ -255,7 +252,7 @@ Environment MakeStep::makeEnvironment() const void MakeStep::setMakeCommand(const FilePath &command) { - m_makeCommandAspect->setFilePath(command); + m_makeCommandAspect.setFilePath(command); } int MakeStep::defaultJobCount() @@ -269,17 +266,17 @@ QStringList MakeStep::jobArguments() const || (makeflagsContainsJobCount() && !jobCountOverridesMakeflags())) { return {}; } - return {"-j" + QString::number(m_userJobCountAspect->value())}; + return {"-j" + QString::number(m_jobCountAspect())}; } QString MakeStep::userArguments() const { - return m_userArgumentsAspect->value(); + return m_userArgumentsAspect(); } void MakeStep::setUserArguments(const QString &args) { - m_userArgumentsAspect->setValue(args); + m_userArgumentsAspect.setValue(args); } QStringList MakeStep::displayArguments() const @@ -289,7 +286,7 @@ QStringList MakeStep::displayArguments() const FilePath MakeStep::makeCommand() const { - return m_makeCommandAspect->filePath(); + return m_makeCommandAspect(); } FilePath MakeStep::makeExecutable() const @@ -306,7 +303,7 @@ CommandLine MakeStep::effectiveMakeCommand(MakeCommandType type) const cmd.addArgs(displayArguments()); cmd.addArgs(userArguments(), CommandLine::Raw); cmd.addArgs(jobArguments()); - cmd.addArgs(m_buildTargetsAspect->value()); + cmd.addArgs(m_buildTargetsAspect.value()); return cmd; } @@ -316,7 +313,7 @@ QWidget *MakeStep::createConfigWidget() Layouting::Form builder; builder.addRow({m_makeCommandAspect}); builder.addRow({m_userArgumentsAspect}); - builder.addRow({m_userJobCountAspect, m_overrideMakeflagsAspect, m_nonOverrideWarning}); + builder.addRow({m_jobCountAspect, m_overrideMakeflagsAspect, m_nonOverrideWarning}); if (m_disablingForSubDirsSupported) builder.addRow({m_disabledForSubdirsAspect}); builder.addRow({m_buildTargetsAspect}); @@ -350,23 +347,23 @@ QWidget *MakeStep::createConfigWidget() auto updateDetails = [this] { const bool jobCountVisible = isJobCountSupported(); - m_userJobCountAspect->setVisible(jobCountVisible); - m_overrideMakeflagsAspect->setVisible(jobCountVisible); + m_jobCountAspect.setVisible(jobCountVisible); + m_overrideMakeflagsAspect.setVisible(jobCountVisible); const bool jobCountEnabled = !userArgsContainsJobCount(); - m_userJobCountAspect->setEnabled(jobCountEnabled); - m_overrideMakeflagsAspect->setEnabled(jobCountEnabled); - m_nonOverrideWarning->setVisible(makeflagsJobCountMismatch() + m_jobCountAspect.setEnabled(jobCountEnabled); + m_overrideMakeflagsAspect.setEnabled(jobCountEnabled); + m_nonOverrideWarning.setVisible(makeflagsJobCountMismatch() && !jobCountOverridesMakeflags()); }; updateDetails(); - connect(m_makeCommandAspect, &StringAspect::changed, widget, updateDetails); - connect(m_userArgumentsAspect, &StringAspect::changed, widget, updateDetails); - connect(m_userJobCountAspect, &IntegerAspect::changed, widget, updateDetails); - connect(m_overrideMakeflagsAspect, &BoolAspect::changed, widget, updateDetails); - connect(m_buildTargetsAspect, &BaseAspect::changed, widget, updateDetails); + connect(&m_makeCommandAspect, &StringAspect::changed, widget, updateDetails); + connect(&m_userArgumentsAspect, &StringAspect::changed, widget, updateDetails); + connect(&m_jobCountAspect, &IntegerAspect::changed, widget, updateDetails); + connect(&m_overrideMakeflagsAspect, &BoolAspect::changed, widget, updateDetails); + connect(&m_buildTargetsAspect, &BaseAspect::changed, widget, updateDetails); connect(ProjectExplorerPlugin::instance(), &ProjectExplorerPlugin::settingsChanged, widget, updateDetails); @@ -382,7 +379,7 @@ QWidget *MakeStep::createConfigWidget() QStringList MakeStep::availableTargets() const { - return m_buildTargetsAspect->allValues(); + return m_buildTargetsAspect.allValues(); } } // namespace ProjectExplorer diff --git a/src/plugins/projectexplorer/makestep.h b/src/plugins/projectexplorer/makestep.h index 2f12894ea61..d26820d90c2 100644 --- a/src/plugins/projectexplorer/makestep.h +++ b/src/plugins/projectexplorer/makestep.h @@ -59,26 +59,18 @@ protected: void supportDisablingForSubdirs() { m_disablingForSubDirsSupported = true; } virtual QStringList displayArguments() const; - Utils::StringAspect *makeCommandAspect() const { return m_makeCommandAspect; } - Utils::MultiSelectionAspect *buildTargetsAspect() const { return m_buildTargetsAspect; } - Utils::StringAspect *userArgumentsAspect() const { return m_userArgumentsAspect; } - Utils::BoolAspect *overrideMakeflagsAspect() const { return m_overrideMakeflagsAspect; } - Utils::TextDisplay *nonOverrideWarning() const { return m_nonOverrideWarning; } - Utils::IntegerAspect *jobCountAspect() const { return m_userJobCountAspect; } - Utils::BoolAspect *disabledForSubdirsAspect() const { return m_disabledForSubdirsAspect; } - + Utils::FilePathAspect m_makeCommandAspect{this}; + Utils::MultiSelectionAspect m_buildTargetsAspect{this}; + Utils::StringAspect m_userArgumentsAspect{this}; + Utils::BoolAspect m_overrideMakeflagsAspect{this}; + Utils::TextDisplay m_nonOverrideWarning{this}; + Utils::IntegerAspect m_jobCountAspect{this}; + Utils::BoolAspect m_disabledForSubdirsAspect{this}; private: static int defaultJobCount(); QStringList jobArguments() const; - Utils::MultiSelectionAspect *m_buildTargetsAspect = nullptr; - Utils::StringAspect *m_makeCommandAspect = nullptr; - Utils::StringAspect *m_userArgumentsAspect = nullptr; - Utils::IntegerAspect *m_userJobCountAspect = nullptr; - Utils::BoolAspect *m_overrideMakeflagsAspect = nullptr; - Utils::BoolAspect *m_disabledForSubdirsAspect = nullptr; - Utils::TextDisplay *m_nonOverrideWarning = nullptr; bool m_disablingForSubDirsSupported = false; }; diff --git a/src/plugins/projectexplorer/projectconfiguration.cpp b/src/plugins/projectexplorer/projectconfiguration.cpp index 841be317312..4aad7c4a392 100644 --- a/src/plugins/projectexplorer/projectconfiguration.cpp +++ b/src/plugins/projectexplorer/projectconfiguration.cpp @@ -6,7 +6,6 @@ #include "kitinformation.h" #include "target.h" -#include #include #include @@ -108,13 +107,6 @@ bool ProjectConfiguration::fromMap(const QVariantMap &map) return true; } -FilePath ProjectConfiguration::mapFromBuildDeviceToGlobalPath(const FilePath &path) const -{ - IDevice::ConstPtr dev = BuildDeviceKitAspect::device(kit()); - QTC_ASSERT(dev, return path); - return dev->filePath(path.path()); -} - Id ProjectExplorer::idFromMap(const QVariantMap &map) { return Id::fromSetting(map.value(QLatin1String(CONFIGURATION_ID_KEY))); diff --git a/src/plugins/projectexplorer/projectconfiguration.h b/src/plugins/projectexplorer/projectconfiguration.h index 8c5dac1d902..790d9ebf6b5 100644 --- a/src/plugins/projectexplorer/projectconfiguration.h +++ b/src/plugins/projectexplorer/projectconfiguration.h @@ -54,8 +54,6 @@ public: static QString settingsIdKey(); - Utils::FilePath mapFromBuildDeviceToGlobalPath(const Utils::FilePath &path) const; - signals: void displayNameChanged(); void toolTipChanged(); diff --git a/src/plugins/projectexplorer/projectmodels.cpp b/src/plugins/projectexplorer/projectmodels.cpp index 9805e654b74..64fabcb30ab 100644 --- a/src/plugins/projectexplorer/projectmodels.cpp +++ b/src/plugins/projectexplorer/projectmodels.cpp @@ -436,6 +436,8 @@ void FlatModel::handleProjectAdded(Project *project) { QTC_ASSERT(project, return); + auto oldName = project->displayName(); + project->setProperty("_q_oldProjectName", oldName); connect(project, &Project::anyParsingStarted, this, [this, project]() { if (nodeForProject(project)) @@ -443,8 +445,28 @@ void FlatModel::handleProjectAdded(Project *project) }); connect(project, &Project::anyParsingFinished, this, [this, project]() { - if (nodeForProject(project)) + auto wrapper = nodeForProject(project); + if (wrapper) { + // In case the project was renamed, change the name in expand data as well + // FIXME: Redesign node expansion so that it does not rely on display name of a node + auto oldName = project->property("_q_oldProjectName").toString(); + auto currentName = project->displayName(); + if (oldName != currentName) { + project->setProperty("_q_oldProjectName", currentName); + auto node = wrapper->m_node; + ExpandData oldData(node->filePath().toString(), oldName); + ExpandData newData(oldData.path, currentName); + auto it = m_toExpand.find(oldData); + if (it != m_toExpand.end()) { + m_toExpand.erase(it); + m_toExpand.insert(newData); + emit requestExpansion(wrapper->index()); + } else if (m_toExpand.contains(newData)) { + emit requestExpansion(wrapper->index()); + } + } parsingStateChanged(project); + } emit ProjectTree::instance()->nodeActionsChanged(); }); addOrRebuildProjectModel(project); diff --git a/src/plugins/projectexplorer/projectwelcomepage.cpp b/src/plugins/projectexplorer/projectwelcomepage.cpp index 4eef637077c..5def44f9482 100644 --- a/src/plugins/projectexplorer/projectwelcomepage.cpp +++ b/src/plugins/projectexplorer/projectwelcomepage.cpp @@ -535,7 +535,7 @@ public: projectModel->resetProjects(); }); contextMenu.addAction(action); - contextMenu.exec(mouseEvent->globalPos()); + contextMenu.exec(mouseEvent->globalPosition().toPoint()); return true; } } diff --git a/src/plugins/projectexplorer/rawprojectpart.cpp b/src/plugins/projectexplorer/rawprojectpart.cpp index 31147c3803b..81d4951ed0c 100644 --- a/src/plugins/projectexplorer/rawprojectpart.cpp +++ b/src/plugins/projectexplorer/rawprojectpart.cpp @@ -45,9 +45,10 @@ void RawProjectPart::setFiles(const QStringList &files, this->getMimeType = getMimeType; } -static QString trimTrailingSlashes(const QString &path) { +static QString trimTrailingSlashes(const QString &path) +{ QString p = path; - while (p.endsWith('/') && p.count() > 1) { + while (p.endsWith('/') && p.size() > 1) { p.chop(1); } return p; diff --git a/src/plugins/projectexplorer/runconfigurationaspects.cpp b/src/plugins/projectexplorer/runconfigurationaspects.cpp index ce28582d558..5a155794460 100644 --- a/src/plugins/projectexplorer/runconfigurationaspects.cpp +++ b/src/plugins/projectexplorer/runconfigurationaspects.cpp @@ -386,7 +386,7 @@ void ArgumentsAspect::fromMap(const QVariantMap &map) { QVariant args = map.value(settingsKey()); // Until 3.7 a QStringList was stored for Remote Linux - if (args.type() == QVariant::StringList) + if (args.typeId() == QVariant::StringList) m_arguments = ProcessArgs::joinArgs(args.toStringList(), OsTypeLinux); else m_arguments = args.toString(); diff --git a/src/plugins/projectexplorer/taskfile.cpp b/src/plugins/projectexplorer/taskfile.cpp index c967521d894..b6a95c0325a 100644 --- a/src/plugins/projectexplorer/taskfile.cpp +++ b/src/plugins/projectexplorer/taskfile.cpp @@ -79,9 +79,9 @@ static QStringList parseRawLine(const QByteArray &raw) static QString unescape(const QString &input) { QString result; - for (int i = 0; i < input.count(); ++i) { + for (int i = 0; i < input.size(); ++i) { if (input.at(i) == '\\') { - if (i == input.count() - 1) + if (i == input.size() - 1) continue; if (input.at(i + 1) == 'n') { result.append('\n'); @@ -123,16 +123,16 @@ static bool parseTaskFile(QString *errorString, const FilePath &name) Task::TaskType type = Task::Unknown; int line = -1; - if (chunks.count() == 1) { + if (chunks.size() == 1) { description = chunks.at(0); - } else if (chunks.count() == 2) { + } else if (chunks.size() == 2) { type = typeFrom(chunks.at(0)); description = chunks.at(1); - } else if (chunks.count() == 3) { + } else if (chunks.size() == 3) { file = chunks.at(0); type = typeFrom(chunks.at(1)); description = chunks.at(2); - } else if (chunks.count() >= 4) { + } else if (chunks.size() >= 4) { file = chunks.at(0); bool ok; line = chunks.at(1).toInt(&ok); diff --git a/src/plugins/projectexplorer/userfileaccessor.cpp b/src/plugins/projectexplorer/userfileaccessor.cpp index ae900ea818d..5a765cb537f 100644 --- a/src/plugins/projectexplorer/userfileaccessor.cpp +++ b/src/plugins/projectexplorer/userfileaccessor.cpp @@ -455,7 +455,7 @@ QVariantMap UserFileVersion14Upgrader::upgrade(const QVariantMap &map) { QVariantMap result; for (auto it = map.cbegin(), end = map.cend(); it != end; ++it) { - if (it.value().type() == QVariant::Map) + if (it.value().typeId() == QVariant::Map) result.insert(it.key(), upgrade(it.value().toMap())); else if (it.key() == "AutotoolsProjectManager.AutotoolsBuildConfiguration.BuildDirectory" || it.key() == "CMakeProjectManager.CMakeBuildConfiguration.BuildDirectory" @@ -710,7 +710,7 @@ QVariantMap UserFileVersion17Upgrader::upgrade(const QVariantMap &map) QVariant UserFileVersion17Upgrader::process(const QVariant &entry) { - switch (entry.type()) { + switch (entry.typeId()) { case QVariant::List: { QVariantList result; for (const QVariant &item : entry.toList()) @@ -738,7 +738,7 @@ QVariantMap UserFileVersion18Upgrader::upgrade(const QVariantMap &map) QVariant UserFileVersion18Upgrader::process(const QVariant &entry) { - switch (entry.type()) { + switch (entry.typeId()) { case QVariant::List: return Utils::transform(entry.toList(), &UserFileVersion18Upgrader::process); case QVariant::Map: @@ -792,7 +792,7 @@ QVariant UserFileVersion19Upgrader::process(const QVariant &entry, const QString "QmakeProjectManager.QmakeRunConfiguration.UseLibrarySearchPath"}; static const QStringList dyldKeys = {"Qbs.RunConfiguration.UseDyldImageSuffix", "QmakeProjectManager.QmakeRunConfiguration.UseDyldImageSuffix"}; - switch (entry.type()) { + switch (entry.typeId()) { case QVariant::List: return Utils::transform(entry.toList(), std::bind(&UserFileVersion19Upgrader::process, std::placeholders::_1, path)); @@ -827,7 +827,7 @@ QVariantMap UserFileVersion20Upgrader::upgrade(const QVariantMap &map) QVariant UserFileVersion20Upgrader::process(const QVariant &entry) { - switch (entry.type()) { + switch (entry.typeId()) { case QVariant::List: return Utils::transform(entry.toList(), &UserFileVersion20Upgrader::process); case QVariant::Map: @@ -853,7 +853,7 @@ QVariantMap UserFileVersion21Upgrader::upgrade(const QVariantMap &map) QVariant UserFileVersion21Upgrader::process(const QVariant &entry) { - switch (entry.type()) { + switch (entry.typeId()) { case QVariant::List: return Utils::transform(entry.toList(), &UserFileVersion21Upgrader::process); case QVariant::Map: { diff --git a/src/plugins/qmakeprojectmanager/profileeditor.cpp b/src/plugins/qmakeprojectmanager/profileeditor.cpp index c17d3d91935..1a3e15fdd59 100644 --- a/src/plugins/qmakeprojectmanager/profileeditor.cpp +++ b/src/plugins/qmakeprojectmanager/profileeditor.cpp @@ -142,7 +142,7 @@ void ProFileEditorWidget::findLinkAt(const QTextCursor &cursor, bool doBackwardScan = true; if (posCurlyPwd >= 0) { - const int end = chunkStart + posCurlyPwd + curlyPwd.count(); + const int end = chunkStart + posCurlyPwd + curlyPwd.size(); const int start = chunkStart + posCurlyPwd; if (start <= column && end >= column) { buffer = pwd; @@ -151,7 +151,7 @@ void ProFileEditorWidget::findLinkAt(const QTextCursor &cursor, doBackwardScan = false; } } else if (posPwd >= 0) { - const int end = chunkStart + posPwd + pwd.count(); + const int end = chunkStart + posPwd + pwd.size(); const int start = chunkStart + posPwd; if (start <= column && end >= column) { buffer = pwd; @@ -173,19 +173,19 @@ void ProFileEditorWidget::findLinkAt(const QTextCursor &cursor, if (doBackwardScan && beginPos > 0 - && block.mid(beginPos - 1, pwd.count()) == pwd - && (block.at(beginPos + pwd.count() - 1) == '/' || block.at(beginPos + pwd.count() - 1) == '\\')) { + && block.mid(beginPos - 1, pwd.size()) == pwd + && (block.at(beginPos + pwd.size() - 1) == '/' || block.at(beginPos + pwd.size() - 1) == '\\')) { buffer.prepend("$$"); beginPos -= 2; } else if (doBackwardScan - && beginPos >= curlyPwd.count() - 1 - && block.mid(beginPos - curlyPwd.count() + 1, curlyPwd.count()) == curlyPwd) { + && beginPos >= curlyPwd.size() - 1 + && block.mid(beginPos - curlyPwd.size() + 1, curlyPwd.size()) == curlyPwd) { buffer.prepend(pwd); - beginPos -= curlyPwd.count(); + beginPos -= curlyPwd.size(); } // find the end of a filename - while (endPos < block.count()) { + while (endPos < block.size()) { QChar c = block.at(endPos); if (isValidFileNameChar(c)) { buffer.append(c); diff --git a/src/plugins/qmakeprojectmanager/profilehoverhandler.cpp b/src/plugins/qmakeprojectmanager/profilehoverhandler.cpp index 2ab532cd569..30808887803 100644 --- a/src/plugins/qmakeprojectmanager/profilehoverhandler.cpp +++ b/src/plugins/qmakeprojectmanager/profilehoverhandler.cpp @@ -8,8 +8,8 @@ #include #include #include -#include +#include #include #include @@ -28,7 +28,7 @@ void ProFileHoverHandler::identifyMatch(TextEditor::TextEditorWidget *editorWidg int pos, ReportPriority report) { - ExecuteOnDestruction reportPriority([this, report](){ report(priority()); }); + const QScopeGuard cleanup([this, report] { report(priority()); }); m_docFragment.clear(); m_manualKind = UnknownManual; diff --git a/src/plugins/qmakeprojectmanager/qmakebuildconfiguration.cpp b/src/plugins/qmakeprojectmanager/qmakebuildconfiguration.cpp index 9da9f7f65a7..39618c41956 100644 --- a/src/plugins/qmakeprojectmanager/qmakebuildconfiguration.cpp +++ b/src/plugins/qmakeprojectmanager/qmakebuildconfiguration.cpp @@ -643,33 +643,29 @@ QString QmakeBuildConfiguration::extractSpecFromArguments(QString *args, if (parsedSpec.isEmpty()) return {}; - FilePath baseMkspecDir = FilePath::fromUserInput(version->hostDataPath().toString() - + "/mkspecs"); - baseMkspecDir = FilePath::fromString(baseMkspecDir.toFileInfo().canonicalFilePath()); + const FilePath baseMkspecDir = version->hostDataPath().pathAppended("mkspecs") + .canonicalPath(); // if the path is relative it can be // relative to the working directory (as found in the Makefiles) // or relatively to the mkspec directory // if it is the former we need to get the canonical form // for the other one we don't need to do anything - if (parsedSpec.toFileInfo().isRelative()) { - if (QFileInfo::exists(directory.path() + QLatin1Char('/') + parsedSpec.toString())) - parsedSpec = FilePath::fromUserInput(directory.path() + QLatin1Char('/') + parsedSpec.toString()); + if (parsedSpec.isRelativePath()) { + FilePath mkspecs = directory.pathAppended(parsedSpec.path()); + if (mkspecs.exists()) + parsedSpec = mkspecs; else - parsedSpec = FilePath::fromUserInput(baseMkspecDir.toString() + QLatin1Char('/') + parsedSpec.toString()); + parsedSpec = baseMkspecDir.pathAppended(parsedSpec.path()); } - QFileInfo f2 = parsedSpec.toFileInfo(); - while (f2.isSymLink()) { - parsedSpec = FilePath::fromString(f2.symLinkTarget()); - f2.setFile(parsedSpec.toString()); - } + while (parsedSpec.isSymLink()) + parsedSpec = parsedSpec.symLinkTarget(); if (parsedSpec.isChildOf(baseMkspecDir)) { parsedSpec = parsedSpec.relativeChildPath(baseMkspecDir); } else { - FilePath sourceMkSpecPath = FilePath::fromString(version->sourcePath().toString() - + QLatin1String("/mkspecs")); + FilePath sourceMkSpecPath = version->sourcePath().pathAppended("mkspecs"); if (parsedSpec.isChildOf(sourceMkSpecPath)) parsedSpec = parsedSpec.relativeChildPath(sourceMkSpecPath); } diff --git a/src/plugins/qmldesigner/components/assetslibrary/assetslibrarywidget.cpp b/src/plugins/qmldesigner/components/assetslibrary/assetslibrarywidget.cpp index 14110cc699a..3b106d30b57 100644 --- a/src/plugins/qmldesigner/components/assetslibrary/assetslibrarywidget.cpp +++ b/src/plugins/qmldesigner/components/assetslibrary/assetslibrarywidget.cpp @@ -59,7 +59,7 @@ bool AssetsLibraryWidget::eventFilter(QObject *obj, QEvent *event) } else if (event->type() == QMouseEvent::MouseMove) { if (!m_assetsToDrag.isEmpty() && m_assetsView->model()) { QMouseEvent *me = static_cast(event); - if ((me->globalPos() - m_dragStartPoint).manhattanLength() > 10) { + if ((me->globalPosition().toPoint() - m_dragStartPoint).manhattanLength() > 10) { QMimeData *mimeData = new QMimeData; mimeData->setData(Constants::MIME_TYPE_ASSETS, m_assetsToDrag.join(',').toUtf8()); diff --git a/src/plugins/qmldesigner/components/componentcore/designeractionmanager.cpp b/src/plugins/qmldesigner/components/componentcore/designeractionmanager.cpp index 32a3d4af700..1562d13b0e4 100644 --- a/src/plugins/qmldesigner/components/componentcore/designeractionmanager.cpp +++ b/src/plugins/qmldesigner/components/componentcore/designeractionmanager.cpp @@ -635,7 +635,7 @@ public: const auto selection = selectionContext(); bool showMenu = false; - auto cleanup = qScopeGuard([&]{ menu()->setEnabled(showMenu); }); + const QScopeGuard cleanup([&]{ menu()->setEnabled(showMenu); }); if (!selection.isValid()) return; diff --git a/src/plugins/qmldesigner/components/contentlibrary/contentlibrarywidget.cpp b/src/plugins/qmldesigner/components/contentlibrary/contentlibrarywidget.cpp index 8e9ef0be2b1..095ebb7d165 100644 --- a/src/plugins/qmldesigner/components/contentlibrary/contentlibrarywidget.cpp +++ b/src/plugins/qmldesigner/components/contentlibrary/contentlibrarywidget.cpp @@ -66,7 +66,7 @@ bool ContentLibraryWidget::eventFilter(QObject *obj, QEvent *event) if (m_materialToDrag) { QMouseEvent *me = static_cast(event); - if ((me->globalPos() - m_dragStartPoint).manhattanLength() > 20 + if ((me->globalPosition().toPoint() - m_dragStartPoint).manhattanLength() > 20 && m_materialToDrag->isDownloaded()) { QByteArray data; QMimeData *mimeData = new QMimeData; @@ -81,7 +81,7 @@ bool ContentLibraryWidget::eventFilter(QObject *obj, QEvent *event) } } else if (m_textureToDrag) { QMouseEvent *me = static_cast(event); - if ((me->globalPos() - m_dragStartPoint).manhattanLength() > 20 + if ((me->globalPosition().toPoint() - m_dragStartPoint).manhattanLength() > 20 && m_textureToDrag->isDownloaded()) { QMimeData *mimeData = new QMimeData; mimeData->setData(Constants::MIME_TYPE_BUNDLE_TEXTURE, diff --git a/src/plugins/qmldesigner/components/curveeditor/detail/graphicsview.cpp b/src/plugins/qmldesigner/components/curveeditor/detail/graphicsview.cpp index 8082ba5c3d3..819a52d2159 100644 --- a/src/plugins/qmldesigner/components/curveeditor/detail/graphicsview.cpp +++ b/src/plugins/qmldesigner/components/curveeditor/detail/graphicsview.cpp @@ -341,14 +341,14 @@ void GraphicsView::keyPressEvent(QKeyEvent *event) void GraphicsView::mousePressEvent(QMouseEvent *event) { - if (m_playhead.mousePress(globalToScene(event->globalPos()))) { + if (m_playhead.mousePress(globalToScene(event->globalPosition().toPoint()))) { m_dragging = true; return; } Shortcut shortcut(event); if (shortcut == m_style.shortcuts.insertKeyframe) { - m_scene->insertKeyframe(globalToRaster(event->globalPos()).x()); + m_scene->insertKeyframe(globalToRaster(event->globalPosition().toPoint()).x()); return; } @@ -371,7 +371,7 @@ void GraphicsView::mousePressEvent(QMouseEvent *event) void GraphicsView::mouseMoveEvent(QMouseEvent *event) { - if (m_playhead.mouseMove(globalToScene(event->globalPos()), this)) + if (m_playhead.mouseMove(globalToScene(event->globalPosition().toPoint()), this)) return; QGraphicsView::mouseMoveEvent(event); diff --git a/src/plugins/qmldesigner/components/curveeditor/detail/selector.cpp b/src/plugins/qmldesigner/components/curveeditor/detail/selector.cpp index 2f1a44d2f5e..dfebbefc968 100644 --- a/src/plugins/qmldesigner/components/curveeditor/detail/selector.cpp +++ b/src/plugins/qmldesigner/components/curveeditor/detail/selector.cpp @@ -38,7 +38,7 @@ void Selector::mousePress(QMouseEvent *event, GraphicsView *view, GraphicsScene { m_shortcut = Shortcut(event); - QPointF click = view->globalToScene(event->globalPos()); + QPointF click = view->globalToScene(event->globalPosition().toPoint()); if (SelectableItem *sitem = scene->intersect(click)) { KeyframeItem *kitem = qobject_cast(sitem); @@ -54,8 +54,8 @@ void Selector::mousePress(QMouseEvent *event, GraphicsView *view, GraphicsScene applyPreSelection(scene); // Init selection tools. - m_mouseInit = event->globalPos(); - m_mouseCurr = event->globalPos(); + m_mouseInit = event->globalPosition().toPoint(); + m_mouseCurr = event->globalPosition().toPoint(); m_lasso = QPainterPath(click); m_lasso.closeSubpath(); @@ -72,17 +72,17 @@ void Selector::mouseMove(QMouseEvent *event, if (m_mouseInit.isNull()) return; - if ((event->globalPos() - m_mouseInit).manhattanLength() < QApplication::startDragDistance()) + if ((event->globalPosition().toPoint() - m_mouseInit).manhattanLength() < QApplication::startDragDistance()) return; - QPointF delta = event->globalPos() - m_mouseCurr; + QPointF delta = event->globalPosition().toPoint() - m_mouseCurr; if (m_shortcut == m_shortcuts.newSelection || m_shortcut == m_shortcuts.addToSelection || m_shortcut == m_shortcuts.removeFromSelection || m_shortcut == m_shortcuts.toggleSelection) { if (scene->hasActiveItem()) return; - select(m_tool, view->globalToScene(event->globalPos()), scene); + select(m_tool, view->globalToScene(event->globalPosition().toPoint()), scene); event->accept(); view->viewport()->update(); @@ -91,13 +91,13 @@ void Selector::mouseMove(QMouseEvent *event, double bigger = std::abs(delta.x()) > std::abs(delta.y()) ? delta.x() : delta.y(); double factor = bigger / view->width(); view->setZoomX(view->zoomX() + factor, m_mouseInit); - m_mouseCurr = event->globalPos(); + m_mouseCurr = event->globalPosition().toPoint(); event->accept(); } else if (m_shortcut == m_shortcuts.pan) { view->scrollContent(-delta.x(), -delta.y()); playhead.resize(view); - m_mouseCurr = event->globalPos(); + m_mouseCurr = event->globalPosition().toPoint(); } } diff --git a/src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.cpp b/src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.cpp index d43dcc47c67..2fab06dea89 100644 --- a/src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.cpp +++ b/src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.cpp @@ -77,7 +77,7 @@ bool ItemLibraryWidget::eventFilter(QObject *obj, QEvent *event) } else if (event->type() == QMouseEvent::MouseMove) { if (m_itemToDrag.isValid()) { QMouseEvent *me = static_cast(event); - if ((me->globalPos() - m_dragStartPoint).manhattanLength() > 10) { + if ((me->globalPosition().toPoint() - m_dragStartPoint).manhattanLength() > 10) { ItemLibraryEntry entry = m_itemToDrag.value(); // For drag to be handled correctly, we must have the component properly imported // beforehand, so we import the module immediately when the drag starts diff --git a/src/plugins/qmldesigner/components/materialbrowser/materialbrowserwidget.cpp b/src/plugins/qmldesigner/components/materialbrowser/materialbrowserwidget.cpp index d0c5483bdde..e2bb82216bb 100644 --- a/src/plugins/qmldesigner/components/materialbrowser/materialbrowserwidget.cpp +++ b/src/plugins/qmldesigner/components/materialbrowser/materialbrowserwidget.cpp @@ -95,7 +95,7 @@ bool MaterialBrowserWidget::eventFilter(QObject *obj, QEvent *event) if (m_materialToDrag.isValid() || m_textureToDrag.isValid()) { QMouseEvent *me = static_cast(event); - if ((me->globalPos() - m_dragStartPoint).manhattanLength() > 20) { + if ((me->globalPosition().toPoint() - m_dragStartPoint).manhattanLength() > 20) { bool isMaterial = m_materialToDrag.isValid(); QMimeData *mimeData = new QMimeData; QByteArray internalId; diff --git a/src/plugins/qmldesigner/components/navigator/nameitemdelegate.cpp b/src/plugins/qmldesigner/components/navigator/nameitemdelegate.cpp index e9fa8b49252..a955a81c0ee 100644 --- a/src/plugins/qmldesigner/components/navigator/nameitemdelegate.cpp +++ b/src/plugins/qmldesigner/components/navigator/nameitemdelegate.cpp @@ -288,7 +288,7 @@ bool NameItemDelegate::editorEvent(QEvent *event, QAbstractItemModel *, const QS if (event->type() == QEvent::MouseButtonRelease) { auto mouseEvent = static_cast(event); if (mouseEvent->button() == Qt::RightButton) { - openContextMenu(index, mouseEvent->globalPos()); + openContextMenu(index, mouseEvent->globalPosition().toPoint()); mouseEvent->accept(); return true; } diff --git a/src/plugins/qmldesigner/components/propertyeditor/colorpalettebackend.cpp b/src/plugins/qmldesigner/components/propertyeditor/colorpalettebackend.cpp index 5ccab3165d9..f2f5ba77063 100644 --- a/src/plugins/qmldesigner/components/propertyeditor/colorpalettebackend.cpp +++ b/src/plugins/qmldesigner/components/propertyeditor/colorpalettebackend.cpp @@ -340,14 +340,14 @@ void ColorPaletteBackend::releaseEyeDropper() bool ColorPaletteBackend::handleEyeDropperMouseMove(QMouseEvent *e) { - updateEyeDropperPosition(e->globalPos()); + updateEyeDropperPosition(e->globalPosition().toPoint()); return true; } bool ColorPaletteBackend::handleEyeDropperMouseButtonRelease(QMouseEvent *e) { if (e->button() == Qt::LeftButton) - emit currentColorChanged(grabScreenColor(e->globalPos())); + emit currentColorChanged(grabScreenColor(e->globalPosition().toPoint())); else emit eyeDropperRejected(); @@ -364,7 +364,7 @@ bool ColorPaletteBackend::handleEyeDropperKeyPress(QKeyEvent *e) } //else #endif //if (e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter) { - // emit currentColorChanged(grabScreenColor(e->globalPos())); + // emit currentColorChanged(grabScreenColor(e->globalPosition().toPoint())); // releaseEyeDropper(); //} e->accept(); diff --git a/src/plugins/qmldesigner/components/propertyeditor/dynamicpropertiesproxymodel.cpp b/src/plugins/qmldesigner/components/propertyeditor/dynamicpropertiesproxymodel.cpp index 5067a6f5b1b..046f95ed738 100644 --- a/src/plugins/qmldesigner/components/propertyeditor/dynamicpropertiesproxymodel.cpp +++ b/src/plugins/qmldesigner/components/propertyeditor/dynamicpropertiesproxymodel.cpp @@ -330,7 +330,7 @@ void DynamicPropertyRow::commitValue(const QVariant &value) return; m_lock = true; - auto unlock = qScopeGuard([this] { m_lock = false; }); + const QScopeGuard cleanup([this] { m_lock = false; }); auto view = propertiesModel->view(); RewriterTransaction transaction = view->beginRewriterTransaction(__FUNCTION__); @@ -371,7 +371,7 @@ void DynamicPropertyRow::commitExpression(const QString &expression) } m_lock = true; - auto unlock = qScopeGuard([this] { m_lock = false; }); + const QScopeGuard cleanup([this] { m_lock = false; }); auto view = propertiesModel->view(); RewriterTransaction transaction = view->beginRewriterTransaction(__FUNCTION__); @@ -426,7 +426,7 @@ void DynamicPropertyRow::resetValue() } } else { m_lock = true; - auto unlock = qScopeGuard([this] { m_lock = false; }); + const QScopeGuard cleanup([this] { m_lock = false; }); RewriterTransaction transaction = view->beginRewriterTransaction(__FUNCTION__); try { diff --git a/src/plugins/qmldesigner/components/propertyeditor/gradientmodel.cpp b/src/plugins/qmldesigner/components/propertyeditor/gradientmodel.cpp index d037846df75..570927a8638 100644 --- a/src/plugins/qmldesigner/components/propertyeditor/gradientmodel.cpp +++ b/src/plugins/qmldesigner/components/propertyeditor/gradientmodel.cpp @@ -306,7 +306,7 @@ QString GradientModel::readGradientOrientation() const void GradientModel::setupModel() { m_locked = true; - auto guard = qScopeGuard([&] { m_locked = false; }); + const QScopeGuard cleanup([&] { m_locked = false; }); beginResetModel(); endResetModel(); @@ -329,7 +329,7 @@ void GradientModel::setAnchorBackend(const QVariant &anchorBackend) setupModel(); m_locked = true; - auto guard = qScopeGuard([&] { m_locked = false; }); + const QScopeGuard cleanup([&] { m_locked = false; }); emit anchorBackendChanged(); emit hasGradientChanged(); diff --git a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorview.cpp b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorview.cpp index 976d2078a56..4b5467f1247 100644 --- a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorview.cpp +++ b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorview.cpp @@ -29,16 +29,17 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include #include +#include +#include +#include +#include +#include +#include +#include #include +#include +#include enum { debug = false @@ -241,10 +242,10 @@ void PropertyEditorView::changeExpression(const QString &propertyName) if (noValidSelection()) return; - QScopeGuard unlock([&](){ m_locked = false; }); + const QScopeGuard cleanup([&] { m_locked = false; }); m_locked = true; - executeInTransaction("PropertyEditorView::changeExpression", [this, name](){ + executeInTransaction("PropertyEditorView::changeExpression", [this, name] { PropertyName underscoreName(name); underscoreName.replace('.', '_'); diff --git a/src/plugins/qmldesigner/components/richtexteditor/richtexteditor.cpp b/src/plugins/qmldesigner/components/richtexteditor/richtexteditor.cpp index b32e0e69262..258c8a0a68f 100644 --- a/src/plugins/qmldesigner/components/richtexteditor/richtexteditor.cpp +++ b/src/plugins/qmldesigner/components/richtexteditor/richtexteditor.cpp @@ -13,7 +13,6 @@ #include #include #include -#include #include #include #include diff --git a/src/plugins/qmldesigner/components/stateseditor/stateseditorview.cpp b/src/plugins/qmldesigner/components/stateseditor/stateseditorview.cpp index 62a62506e4c..5334110cacf 100644 --- a/src/plugins/qmldesigner/components/stateseditor/stateseditorview.cpp +++ b/src/plugins/qmldesigner/components/stateseditor/stateseditorview.cpp @@ -28,6 +28,14 @@ #include #include +#include +#include +#include +#include + +#include +#include + namespace QmlDesigner { /** @@ -549,7 +557,7 @@ void StatesEditorView::setWhenCondition(int internalNodeId, const QString &condi return; m_block = true; - auto guard = qScopeGuard([&]() { m_block = false; }); + const QScopeGuard cleanup([&] { m_block = false; }); if (hasModelNodeForInternalId(internalNodeId)) { QmlModelState state(modelNodeForInternalId(internalNodeId)); @@ -569,7 +577,7 @@ void StatesEditorView::resetWhenCondition(int internalNodeId) return; m_block = true; - auto guard = qScopeGuard([&]() { m_block = false; }); + const QScopeGuard cleanup([&] { m_block = false; }); if (hasModelNodeForInternalId(internalNodeId)) { QmlModelState state(modelNodeForInternalId(internalNodeId)); @@ -589,7 +597,7 @@ void StatesEditorView::setStateAsDefault(int internalNodeId) return; m_block = true; - auto guard = qScopeGuard([&]() { m_block = false; }); + const QScopeGuard cleanup([&] { m_block = false; }); if (hasModelNodeForInternalId(internalNodeId)) { QmlModelState state(modelNodeForInternalId(internalNodeId)); @@ -609,7 +617,7 @@ void StatesEditorView::resetDefaultState() return; m_block = true; - auto guard = qScopeGuard([&]() { m_block = false; }); + const QScopeGuard cleanup([&] { m_block = false; }); try { if (activeStatesGroupNode().hasProperty("state")) @@ -631,7 +639,7 @@ void StatesEditorView::setAnnotation(int internalNodeId) return; m_block = true; - auto guard = qScopeGuard([&]() { m_block = false; }); + const QScopeGuard cleanup([&] { m_block = false; }); if (hasModelNodeForInternalId(internalNodeId)) { QmlModelState state(modelNodeForInternalId(internalNodeId)); @@ -660,7 +668,7 @@ void StatesEditorView::removeAnnotation(int internalNodeId) return; m_block = true; - auto guard = qScopeGuard([&]() { m_block = false; }); + const QScopeGuard cleanup([&] { m_block = false; }); if (hasModelNodeForInternalId(internalNodeId)) { QmlModelState state(modelNodeForInternalId(internalNodeId)); @@ -846,7 +854,7 @@ void StatesEditorView::variantPropertiesChanged(const QList &pr return; m_block = true; - auto guard = qScopeGuard([&]() { m_block = false; }); + const QScopeGuard cleanup([&] { m_block = false; }); for (const VariantProperty &property : propertyList) { if (property.name() == "name" diff --git a/src/plugins/qmldesigner/designercore/model/texttomodelmerger.cpp b/src/plugins/qmldesigner/designercore/model/texttomodelmerger.cpp index 29088dac407..9f9c200ecfb 100644 --- a/src/plugins/qmldesigner/designercore/model/texttomodelmerger.cpp +++ b/src/plugins/qmldesigner/designercore/model/texttomodelmerger.cpp @@ -1090,7 +1090,7 @@ Document::MutablePtr TextToModelMerger::createParsedDocument(const QUrl &url, co bool TextToModelMerger::load(const QString &data, DifferenceHandler &differenceHandler) { QmlJS::ScopeChain::setSkipmakeComponentChain(true); - QScopeGuard unSkip([]() { QmlJS::ScopeChain::setSkipmakeComponentChain(false); }); + const QScopeGuard cleanup([] { QmlJS::ScopeChain::setSkipmakeComponentChain(false); }); qCInfo(rewriterBenchmark) << Q_FUNC_INFO; diff --git a/src/plugins/qmljseditor/qmljshoverhandler.cpp b/src/plugins/qmljseditor/qmljshoverhandler.cpp index 72b9c73869d..3f7d3a5c110 100644 --- a/src/plugins/qmljseditor/qmljshoverhandler.cpp +++ b/src/plugins/qmljseditor/qmljshoverhandler.cpp @@ -23,7 +23,6 @@ #include #include #include -#include #include #include @@ -31,6 +30,7 @@ #include #include #include +#include using namespace Core; using namespace QmlJS; @@ -175,7 +175,7 @@ bool QmlJSHoverHandler::setQmlTypeHelp(const ScopeChain &scopeChain, const Docum void QmlJSHoverHandler::identifyMatch(TextEditorWidget *editorWidget, int pos, ReportPriority report) { - Utils::ExecuteOnDestruction reportPriority([this, report](){ report(priority()); }); + const QScopeGuard cleanup([this, report] { report(priority()); }); reset(); diff --git a/src/plugins/qmlprojectmanager/buildsystem/qmlbuildsystem.cpp b/src/plugins/qmlprojectmanager/buildsystem/qmlbuildsystem.cpp index 559bdeb198c..20052b45e44 100644 --- a/src/plugins/qmlprojectmanager/buildsystem/qmlbuildsystem.cpp +++ b/src/plugins/qmlprojectmanager/buildsystem/qmlbuildsystem.cpp @@ -107,8 +107,9 @@ void QmlBuildSystem::updateDeploymentData() } ProjectExplorer::DeploymentData deploymentData; - for (const auto &file : m_projectItem->files()) - deploymentData.addFile(file, m_projectItem->targetDirectory()); + for (const auto &file : m_projectItem->files()) { + deploymentData.addFile(file, targetFile(file).parentDir().path()); + } setDeploymentData(deploymentData); } @@ -187,7 +188,7 @@ void QmlBuildSystem::refresh(RefreshOptions options) project()->files(Project::HiddenRccFolders)); for (const QString &searchPath : customImportPaths()) { - projectInfo.importPaths.maybeInsert(projectFilePath().pathAppended(searchPath), + projectInfo.importPaths.maybeInsert(projectDirectory().pathAppended(searchPath), QmlJS::Dialect::Qml); } diff --git a/src/plugins/qnx/qnxdeployqtlibrariesdialog.cpp b/src/plugins/qnx/qnxdeployqtlibrariesdialog.cpp index d9eb88273e6..856f8740a62 100644 --- a/src/plugins/qnx/qnxdeployqtlibrariesdialog.cpp +++ b/src/plugins/qnx/qnxdeployqtlibrariesdialog.cpp @@ -228,7 +228,7 @@ GroupItem QnxDeployQtLibrariesDialogPrivate::chmodTree() QTC_ASSERT(file.isValid(), continue); chmodList.append(chmodTask(file)); } - tree.setupRoot(chmodList); + tree.setRecipe(chmodList); }; return TaskTreeTask{setupChmodHandler}; } diff --git a/src/plugins/qtsupport/baseqtversion.cpp b/src/plugins/qtsupport/baseqtversion.cpp index 4720718a860..d6f2efacefc 100644 --- a/src/plugins/qtsupport/baseqtversion.cpp +++ b/src/plugins/qtsupport/baseqtversion.cpp @@ -2130,7 +2130,7 @@ static QStringList extractFieldsFromBuildString(const QByteArray &buildString) const QString endian = abiInfo.takeFirst(); QTC_ASSERT(endian.endsWith("_endian"), return QStringList()); - result.append(endian.left(endian.count() - 7)); // without the "_endian" + result.append(endian.left(endian.size() - 7)); // without the "_endian" result.append(abiInfo.takeFirst()); // pointer @@ -2160,7 +2160,7 @@ static QStringList extractFieldsFromBuildString(const QByteArray &buildString) static Abi refineAbiFromBuildString(const QByteArray &buildString, const Abi &probableAbi) { QStringList buildStringData = extractFieldsFromBuildString(buildString); - if (buildStringData.count() != 9) + if (buildStringData.size() != 9) return probableAbi; const QString compiler = buildStringData.at(8); diff --git a/src/plugins/qtsupport/qtoptionspage.cpp b/src/plugins/qtsupport/qtoptionspage.cpp index 92b439ea1a2..fba6b8154ff 100644 --- a/src/plugins/qtsupport/qtoptionspage.cpp +++ b/src/plugins/qtsupport/qtoptionspage.cpp @@ -969,20 +969,13 @@ void QtOptionsPageWidget::linkWithQt() bool askForRestart = false; QDialog dialog(Core::ICore::dialogParent()); dialog.setWindowTitle(title); - auto layout = new QVBoxLayout; - dialog.setLayout(layout); auto tipLabel = new QLabel(linkingPurposeText()); tipLabel->setWordWrap(true); - layout->addWidget(tipLabel); - auto pathLayout = new QHBoxLayout; - layout->addLayout(pathLayout); auto pathLabel = new QLabel(Tr::tr("Qt installation path:")); pathLabel->setToolTip( Tr::tr("Choose the Qt installation directory, or a directory that contains \"%1\".") .arg(settingsFile(""))); - pathLayout->addWidget(pathLabel); auto pathInput = new PathChooser; - pathLayout->addWidget(pathInput); pathInput->setExpectedKind(PathChooser::ExistingDirectory); pathInput->setBaseDirectory(FilePath::fromString(QCoreApplication::applicationDirPath())); pathInput->setPromptDialogTitle(title); @@ -997,8 +990,17 @@ void QtOptionsPageWidget::linkWithQt() pathInput->setFilePath(currentLink ? *currentLink : defaultQtInstallationPath()); pathInput->setAllowPathFromDevice(true); auto buttons = new QDialogButtonBox; - layout->addStretch(10); - layout->addWidget(buttons); + + using namespace Layouting; + Column { + tipLabel, + Form { + Tr::tr("Qt installation path:"), pathInput, br, + }, + st, + buttons, + }.attachTo(&dialog); + auto linkButton = buttons->addButton(Tr::tr("Link with Qt"), QDialogButtonBox::AcceptRole); connect(linkButton, &QPushButton::clicked, &dialog, &QDialog::accept); auto cancelButton = buttons->addButton(Tr::tr("Cancel"), QDialogButtonBox::RejectRole); @@ -1022,6 +1024,7 @@ void QtOptionsPageWidget::linkWithQt() connect(pathInput, &PathChooser::validChanged, linkButton, &QPushButton::setEnabled); linkButton->setEnabled(pathInput->isValid()); + dialog.setMinimumWidth(520); dialog.exec(); if (dialog.result() == QDialog::Accepted) { const std::optional settingsDir = settingsDirForQtDir(pathInput->baseDirectory(), diff --git a/src/plugins/qtsupport/qtparser.cpp b/src/plugins/qtsupport/qtparser.cpp index 25ab3604828..2708b19c5e6 100644 --- a/src/plugins/qtsupport/qtparser.cpp +++ b/src/plugins/qtsupport/qtparser.cpp @@ -89,6 +89,21 @@ Utils::OutputLineParser::Result QtParser::handleLine(const QString &line, Utils: scheduleTask(task, 1); return {Status::Done, linkSpecs}; } + + if (lne.startsWith(QLatin1String("Error:"))) { + constexpr int matchLength = 6; + CompileTask task(Task::TaskType::Error, line.mid(matchLength).trimmed()); + scheduleTask(task, 1); + return Status::Done; + } + + if (lne.startsWith(QLatin1String("Warning:"))) { + constexpr int matchLength = 8; + CompileTask task(Task::TaskType::Warning, line.mid(matchLength).trimmed()); + scheduleTask(task, 1); + return Status::Done; + } + return Status::NotHandled; } @@ -205,6 +220,15 @@ void QtSupportPlugin::testQtOutputParser_data() QLatin1String("dropping duplicate messages"), Utils::FilePath::fromUserInput(QLatin1String("/some/place/qtcreator_fr.qm")), -1)) << QString(); + QTest::newRow("qmlsc warning") // QTCREATORBUG-28720 + << QString::fromUtf8("Warning: Main.qml:4:1: Warnings occurred while importing module " + "\"QtQuick.Controls\": [import]\"") + << OutputParserTester::STDERR << QString() << QString() + << (Tasks() << CompileTask(Task::Warning, + QString::fromUtf8( + "Main.qml:4:1: Warnings occurred while importing module " + "\"QtQuick.Controls\": [import]\""))) + << QString(); } void QtSupportPlugin::testQtOutputParser() diff --git a/src/plugins/remotelinux/genericdirectuploadstep.cpp b/src/plugins/remotelinux/genericdirectuploadstep.cpp index 714404ec5b7..4449284ea64 100644 --- a/src/plugins/remotelinux/genericdirectuploadstep.cpp +++ b/src/plugins/remotelinux/genericdirectuploadstep.cpp @@ -184,7 +184,7 @@ GroupItem GenericDirectUploadStep::statTree(const TreeStorage &st QTC_ASSERT(file.isValid(), continue); statList.append(statTask(storagePtr, file, statEndHandler)); } - tree.setupRoot({statList}); + tree.setRecipe({statList}); }; return TaskTreeTask(setupHandler); } @@ -261,7 +261,7 @@ GroupItem GenericDirectUploadStep::chmodTree(const TreeStorage &s QTC_ASSERT(file.isValid(), continue); chmodList.append(chmodTask(file)); } - tree.setupRoot({chmodList}); + tree.setRecipe({chmodList}); }; return TaskTreeTask(setupChmodHandler); } diff --git a/src/plugins/remotelinux/linuxdevice.cpp b/src/plugins/remotelinux/linuxdevice.cpp index 59af192eaa2..61939f20954 100644 --- a/src/plugins/remotelinux/linuxdevice.cpp +++ b/src/plugins/remotelinux/linuxdevice.cpp @@ -40,7 +40,6 @@ #include #include #include -#include #include #include #include diff --git a/src/plugins/remotelinux/makeinstallstep.cpp b/src/plugins/remotelinux/makeinstallstep.cpp index 42f0467c947..a93fccba41b 100644 --- a/src/plugins/remotelinux/makeinstallstep.cpp +++ b/src/plugins/remotelinux/makeinstallstep.cpp @@ -41,13 +41,13 @@ const char CustomCommandLineAspectId[] = "RemoteLinux.MakeInstall.CustomCommandL MakeInstallStep::MakeInstallStep(BuildStepList *parent, Id id) : MakeStep(parent, id) { - makeCommandAspect()->setVisible(false); - buildTargetsAspect()->setVisible(false); - userArgumentsAspect()->setVisible(false); - overrideMakeflagsAspect()->setVisible(false); - nonOverrideWarning()->setVisible(false); - jobCountAspect()->setVisible(false); - disabledForSubdirsAspect()->setVisible(false); + m_makeCommandAspect.setVisible(false); + m_buildTargetsAspect.setVisible(false); + m_userArgumentsAspect.setVisible(false); + m_overrideMakeflagsAspect.setVisible(false); + m_nonOverrideWarning.setVisible(false); + m_jobCountAspect.setVisible(false); + m_disabledForSubdirsAspect.setVisible(false); // FIXME: Hack, Part#1: If the build device is not local, start with a temp dir // inside the build dir. On Docker that's typically shared with the host. diff --git a/src/plugins/scxmleditor/common/sizegrip.cpp b/src/plugins/scxmleditor/common/sizegrip.cpp index 096fbc80a14..a2651fdb856 100644 --- a/src/plugins/scxmleditor/common/sizegrip.cpp +++ b/src/plugins/scxmleditor/common/sizegrip.cpp @@ -23,7 +23,7 @@ void SizeGrip::resizeEvent(QResizeEvent *e) void SizeGrip::mousePressEvent(QMouseEvent *e) { QWidget::mousePressEvent(e); - m_startPoint = e->globalPos(); + m_startPoint = e->globalPosition().toPoint(); m_startRect = parentWidget()->rect(); m_mouseDown = true; checkCursor(e->pos()); @@ -32,7 +32,7 @@ void SizeGrip::mousePressEvent(QMouseEvent *e) void SizeGrip::mouseMoveEvent(QMouseEvent *e) { if (m_mouseDown) { - QPoint p = e->globalPos() - m_startPoint; + QPoint p = e->globalPosition().toPoint() - m_startPoint; parentWidget()->resize(m_startRect.width() + p.x(), m_startRect.height() + p.y()); } else { checkCursor(e->pos()); diff --git a/src/plugins/scxmleditor/common/treeview.cpp b/src/plugins/scxmleditor/common/treeview.cpp index 0a0d76ee959..4e2b6aad6b7 100644 --- a/src/plugins/scxmleditor/common/treeview.cpp +++ b/src/plugins/scxmleditor/common/treeview.cpp @@ -37,5 +37,5 @@ void TreeView::mousePressEvent(QMouseEvent *event) { QTreeView::mousePressEvent(event); if (event->button() == Qt::RightButton) - emit rightButtonClicked(currentIndex(), event->globalPos()); + emit rightButtonClicked(currentIndex(), event->globalPosition().toPoint()); } diff --git a/src/plugins/squish/squishrunnerprocess.cpp b/src/plugins/squish/squishrunnerprocess.cpp index ca1e330a7c3..fbbf7a57b3a 100644 --- a/src/plugins/squish/squishrunnerprocess.cpp +++ b/src/plugins/squish/squishrunnerprocess.cpp @@ -6,9 +6,9 @@ #include "squishtr.h" #include -#include #include +#include Q_LOGGING_CATEGORY(runnerLOG, "qtc.squish.squishrunner", QtWarningMsg) @@ -153,7 +153,7 @@ void SquishRunnerProcess::onStdOutput(const QString &lineIn) void SquishRunnerProcess::handleMultiLineOutput(OutputMode mode) { - Utils::ExecuteOnDestruction atExit([this]{ + const QScopeGuard cleanup([this] { m_multiLineContent.clear(); m_context.clear(); }); diff --git a/src/plugins/terminal/CMakeLists.txt b/src/plugins/terminal/CMakeLists.txt index 69da526cdc0..c7b64cc8ad4 100644 --- a/src/plugins/terminal/CMakeLists.txt +++ b/src/plugins/terminal/CMakeLists.txt @@ -9,6 +9,7 @@ add_qtc_plugin(Terminal scrollback.cpp scrollback.h shellintegration.cpp shellintegration.h shellmodel.cpp shellmodel.h + shortcutmap.cpp shortcutmap.h terminal.qrc terminalconstants.h terminalicons.h diff --git a/src/plugins/terminal/shortcutmap.cpp b/src/plugins/terminal/shortcutmap.cpp new file mode 100644 index 00000000000..72023e808a0 --- /dev/null +++ b/src/plugins/terminal/shortcutmap.cpp @@ -0,0 +1,564 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +// COPIED FROM qshortcutmap.cpp + +#include "shortcutmap.h" + +#include + +#include + +#include +#include +#include +#include + +Q_LOGGING_CATEGORY(lcShortcutMap, "terminal.shortcutmap", QtWarningMsg) + +namespace Terminal::Internal { + +/* \internal + Entry data for ShortcutMap + Contains: + Keysequence for entry + Pointer to parent owning the sequence +*/ +struct ShortcutEntry +{ + ShortcutEntry() + : keyseq(0) + , context(Qt::WindowShortcut) + , enabled(false) + , autorepeat(1) + , id(0) + , owner(nullptr) + , contextMatcher(nullptr) + {} + + ShortcutEntry(const QKeySequence &k) + : keyseq(k) + , context(Qt::WindowShortcut) + , enabled(false) + , autorepeat(1) + , id(0) + , owner(nullptr) + , contextMatcher(nullptr) + {} + + ShortcutEntry(QObject *o, + const QKeySequence &k, + Qt::ShortcutContext c, + int i, + bool a, + ShortcutMap::ContextMatcher m) + : keyseq(k) + , context(c) + , enabled(true) + , autorepeat(a) + , id(i) + , owner(o) + , contextMatcher(m) + {} + + bool correctContext() const { return contextMatcher(owner, context); } + + bool operator<(const ShortcutEntry &f) const { return keyseq < f.keyseq; } + + QKeySequence keyseq; + Qt::ShortcutContext context; + bool enabled : 1; + bool autorepeat : 1; + signed int id; + QObject *owner; + ShortcutMap::ContextMatcher contextMatcher; +}; + +/* \internal + Private data for ShortcutMap +*/ +class ShortcutMapPrivate +{ + Q_DECLARE_PUBLIC(ShortcutMap) + +public: + ShortcutMapPrivate(ShortcutMap *parent) + : q_ptr(parent) + , currentId(0) + , ambigCount(0) + , currentState(QKeySequence::NoMatch) + { + identicals.reserve(10); + currentSequences.reserve(10); + } + ShortcutMap *q_ptr; // Private's parent + + QList sequences; // All sequences! + + int currentId; // Global shortcut ID number + int ambigCount; // Index of last enabled ambiguous dispatch + QKeySequence::SequenceMatch currentState; + QList currentSequences; // Sequence for the current state + QList newEntries; + QKeySequence prevSequence; // Sequence for the previous identical match + QList identicals; // Last identical matches +}; + +/*! \internal + ShortcutMap constructor. +*/ +ShortcutMap::ShortcutMap() + : d_ptr(new ShortcutMapPrivate(this)) +{ + resetState(); +} + +/*! \internal + ShortcutMap destructor. +*/ +ShortcutMap::~ShortcutMap() {} + +/*! \internal + Adds a shortcut to the global map. + Returns the id of the newly added shortcut. +*/ +int ShortcutMap::addShortcut(QObject *owner, + const QKeySequence &key, + Qt::ShortcutContext context, + ContextMatcher matcher) +{ + QTC_ASSERT(owner, return 0); // "ShortcutMap::addShortcut", "All shortcuts need an owner"); + QTC_ASSERT(!key.isEmpty(), + return 0); // "ShortcutMap::addShortcut", "Cannot add keyless shortcuts to map"); + Q_D(ShortcutMap); + + ShortcutEntry newEntry(owner, key, context, --(d->currentId), true, matcher); + const auto it = std::upper_bound(d->sequences.begin(), d->sequences.end(), newEntry); + d->sequences.insert(it, newEntry); // Insert sorted + qCDebug(lcShortcutMap).nospace() << "ShortcutMap::addShortcut(" << owner << ", " << key << ", " + << context << ") added shortcut with ID " << d->currentId; + return d->currentId; +} + +/*! \internal + Removes a shortcut from the global map. + If \a owner is \nullptr, all entries in the map with the key sequence specified + is removed. If \a key is null, all sequences for \a owner is removed from + the map. If \a id is 0, any identical \a key sequences owned by \a owner + are removed. + Returns the number of sequences removed from the map. +*/ + +int ShortcutMap::removeShortcut(int id, QObject *owner, const QKeySequence &key) +{ + Q_D(ShortcutMap); + int itemsRemoved = 0; + bool allOwners = (owner == nullptr); + bool allKeys = key.isEmpty(); + bool allIds = id == 0; + + auto debug = qScopeGuard([&]() { + qCDebug(lcShortcutMap).nospace() + << "ShortcutMap::removeShortcut(" << id << ", " << owner << ", " << key << ") removed " + << itemsRemoved << " shortcuts(s)"; + }); + + // Special case, remove everything + if (allOwners && allKeys && allIds) { + itemsRemoved = d->sequences.size(); + d->sequences.clear(); + return itemsRemoved; + } + + int i = d->sequences.size() - 1; + while (i >= 0) { + const ShortcutEntry &entry = d->sequences.at(i); + int entryId = entry.id; + if ((allOwners || entry.owner == owner) && (allIds || entry.id == id) + && (allKeys || entry.keyseq == key)) { + d->sequences.removeAt(i); + ++itemsRemoved; + } + if (id == entryId) + return itemsRemoved; + --i; + } + return itemsRemoved; +} + +/*! \internal + Resets the state of the statemachine to NoMatch +*/ +void ShortcutMap::resetState() +{ + Q_D(ShortcutMap); + d->currentState = QKeySequence::NoMatch; + clearSequence(d->currentSequences); +} + +/*! \internal + Returns the current state of the statemachine +*/ +QKeySequence::SequenceMatch ShortcutMap::state() +{ + Q_D(ShortcutMap); + return d->currentState; +} + +/*! \internal + Uses nextState(QKeyEvent) to check for a grabbed shortcut. + + If so, it is dispatched using dispatchEvent(). + + Returns true if a shortcut handled the event. + + \sa nextState, dispatchEvent +*/ +bool ShortcutMap::tryShortcut(QKeyEvent *e) +{ + Q_D(ShortcutMap); + + if (e->key() == Qt::Key_unknown) + return false; + + QKeySequence::SequenceMatch previousState = state(); + + switch (nextState(e)) { + case QKeySequence::NoMatch: + // In the case of going from a partial match to no match we handled the + // event, since we already stated that we did for the partial match. But + // in the normal case of directly going to no match we say we didn't. + return previousState == QKeySequence::PartialMatch; + case QKeySequence::PartialMatch: + // For a partial match we don't know yet if we will handle the shortcut + // but we need to say we did, so that we get the follow-up key-presses. + return true; + case QKeySequence::ExactMatch: { + // Save number of identical matches before dispatching + // to keep ShortcutMap and tryShortcut reentrant. + const int identicalMatches = d->identicals.size(); + resetState(); + dispatchEvent(e); + // If there are no identicals we've only found disabled shortcuts, and + // shouldn't say that we handled the event. + return identicalMatches > 0; + } + } +#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0) + Q_UNREACHABLE_RETURN(false); +#else + return false; +#endif +} + +/*! \internal + Returns the next state of the statemachine + If return value is SequenceMatch::ExactMatch, then a call to matches() + will return a QObjects* list of all matching objects for the last matching + sequence. +*/ +QKeySequence::SequenceMatch ShortcutMap::nextState(QKeyEvent *e) +{ + Q_D(ShortcutMap); + // Modifiers can NOT be shortcuts... + if (e->key() >= Qt::Key_Shift && e->key() <= Qt::Key_ScrollLock) + return d->currentState; + + QKeySequence::SequenceMatch result = QKeySequence::NoMatch; + + // We start fresh each time.. + d->identicals.clear(); + + result = find(e); + if (result == QKeySequence::NoMatch && (e->modifiers() & Qt::KeypadModifier)) { + // Try to find a match without keypad modifier + result = find(e, Qt::KeypadModifier); + } + if (result == QKeySequence::NoMatch && e->modifiers() & Qt::ShiftModifier) { + // If Shift + Key_Backtab, also try Shift + Qt::Key_Tab + if (e->key() == Qt::Key_Backtab) { + QKeyEvent pe = QKeyEvent(e->type(), Qt::Key_Tab, e->modifiers(), e->text()); + result = find(&pe); + } + } + + // Does the new state require us to clean up? + if (result == QKeySequence::NoMatch) + clearSequence(d->currentSequences); + d->currentState = result; + + qCDebug(lcShortcutMap).nospace() << "ShortcutMap::nextState(" << e << ") = " << result; + return result; +} + +/*! \internal + Determines if an enabled shortcut has a matching key sequence. +*/ +bool ShortcutMap::hasShortcutForKeySequence(const QKeySequence &seq) const +{ + Q_D(const ShortcutMap); + ShortcutEntry entry(seq); // needed for searching + const auto itEnd = d->sequences.cend(); + auto it = std::lower_bound(d->sequences.cbegin(), itEnd, entry); + + for (; it != itEnd; ++it) { + if (matches(entry.keyseq, (*it).keyseq) == QKeySequence::ExactMatch + && (*it).correctContext() && (*it).enabled) { + return true; + } + } + + //end of the loop: we didn't find anything + return false; +} + +/*! \internal + Returns the next state of the statemachine, based + on the new key event \a e. + Matches are appended to the list of identicals, + which can be access through matches(). + \sa matches +*/ +QKeySequence::SequenceMatch ShortcutMap::find(QKeyEvent *e, int ignoredModifiers) +{ + Q_D(ShortcutMap); + if (!d->sequences.size()) + return QKeySequence::NoMatch; + + createNewSequences(e, d->newEntries, ignoredModifiers); + qCDebug(lcShortcutMap) << "Possible shortcut key sequences:" << d->newEntries; + + // Should never happen + if (d->newEntries == d->currentSequences) { + QTC_ASSERT(e->key() != Qt::Key_unknown || e->text().size(), return QKeySequence::NoMatch); + //"ShortcutMap::find", + // "New sequence to find identical to previous"); + return QKeySequence::NoMatch; + } + + // Looking for new identicals, scrap old + d->identicals.clear(); + + bool partialFound = false; + bool identicalDisabledFound = false; + QList okEntries; + int result = QKeySequence::NoMatch; + for (int i = d->newEntries.size() - 1; i >= 0; --i) { + ShortcutEntry entry(d->newEntries.at(i)); // needed for searching + qCDebug(lcShortcutMap) << "- checking entry" << entry.id << entry.keyseq; + const auto itEnd = d->sequences.constEnd(); + auto it = std::lower_bound(d->sequences.constBegin(), itEnd, entry); + + int oneKSResult = QKeySequence::NoMatch; + int tempRes = QKeySequence::NoMatch; + do { + if (it == itEnd) + break; + tempRes = matches(entry.keyseq, (*it).keyseq); + oneKSResult = qMax(oneKSResult, tempRes); + qCDebug(lcShortcutMap) << " - matches returned" << tempRes << "for" << entry.keyseq + << it->keyseq << "- correctContext()?" << it->correctContext(); + if (tempRes != QKeySequence::NoMatch && (*it).correctContext()) { + if (tempRes == QKeySequence::ExactMatch) { + if ((*it).enabled) + d->identicals.append(&*it); + else + identicalDisabledFound = true; + } else if (tempRes == QKeySequence::PartialMatch) { + // We don't need partials, if we have identicals + if (d->identicals.size()) + break; + // We only care about enabled partials, so we don't consume + // key events when all partials are disabled! + partialFound |= (*it).enabled; + } + } + ++it; + // If we got a valid match on this run, there might still be more keys to check against, + // so we'll loop once more. If we get NoMatch, there's guaranteed no more possible + // matches in the shortcutmap. + } while (tempRes != QKeySequence::NoMatch); + + // If the type of match improves (ergo, NoMatch->Partial, or Partial->Exact), clear the + // previous list. If this match is equal or better than the last match, append to the list + if (oneKSResult > result) { + okEntries.clear(); + qCDebug(lcShortcutMap) + << "Found better match (" << d->newEntries << "), clearing key sequence list"; + } + if (oneKSResult && oneKSResult >= result) { + okEntries << d->newEntries.at(i); + qCDebug(lcShortcutMap) << "Added ok key sequence" << d->newEntries; + } + } + + if (d->identicals.size()) { + result = QKeySequence::ExactMatch; + } else if (partialFound) { + result = QKeySequence::PartialMatch; + } else if (identicalDisabledFound) { + result = QKeySequence::ExactMatch; + } else { + clearSequence(d->currentSequences); + result = QKeySequence::NoMatch; + } + if (result != QKeySequence::NoMatch) + d->currentSequences = okEntries; + qCDebug(lcShortcutMap) << "Returning shortcut match == " << result; + return QKeySequence::SequenceMatch(result); +} + +/*! \internal + Clears \a seq to an empty QKeySequence. + Same as doing (the slower) + \snippet code/src_gui_kernel_shortcutmap.cpp 0 +*/ +void ShortcutMap::clearSequence(QList &ksl) +{ + ksl.clear(); + d_func()->newEntries.clear(); +} + +static QList extractKeyFromEvent(QKeyEvent *e) +{ + QList result; + if (e->key() && (e->key() != Qt::Key_unknown)) + result << e->keyCombination().toCombined(); + else if (!e->text().isEmpty()) + result << int(e->text().at(0).unicode() + (int) e->modifiers()); + return result; +} + +/*! \internal + Alters \a seq to the new sequence state, based on the + current sequence state, and the new key event \a e. +*/ +void ShortcutMap::createNewSequences(QKeyEvent *e, QList &ksl, int ignoredModifiers) +{ + Q_D(ShortcutMap); + + QList possibleKeys = extractKeyFromEvent(e); + qCDebug(lcShortcutMap) << "Creating new sequences for" << e + << "with ignoredModifiers=" << Qt::KeyboardModifiers(ignoredModifiers); + int pkTotal = possibleKeys.size(); + if (!pkTotal) + return; + + int ssActual = d->currentSequences.size(); + int ssTotal = qMax(1, ssActual); + // Resize to possible permutations of the current sequence(s). + ksl.resize(pkTotal * ssTotal); + + int index = ssActual ? d->currentSequences.at(0).count() : 0; + for (int pkNum = 0; pkNum < pkTotal; ++pkNum) { + for (int ssNum = 0; ssNum < ssTotal; ++ssNum) { + int i = (pkNum * ssTotal) + ssNum; + QKeySequence &curKsl = ksl[i]; + if (ssActual) { + const QKeySequence &curSeq = d->currentSequences.at(ssNum); + curKsl = QKeySequence(curSeq[0], curSeq[1], curSeq[2], curSeq[3]); + } else { + curKsl = QKeySequence(QKeyCombination::fromCombined(0)); + } + + std::array cur = {curKsl[0], curKsl[1], curKsl[2], curKsl[3]}; + cur[index] = QKeyCombination::fromCombined(possibleKeys.at(pkNum) & ~ignoredModifiers); + curKsl = QKeySequence(cur[0], cur[1], cur[2], cur[3]); + } + } +} + +/*! \internal + Basically the same function as QKeySequence::matches(const QKeySequence &seq) const + only that is specially handles Key_hyphen as Key_Minus, as people mix these up all the time and + they conceptually the same. +*/ +QKeySequence::SequenceMatch ShortcutMap::matches(const QKeySequence &seq1, + const QKeySequence &seq2) const +{ + uint userN = seq1.count(), seqN = seq2.count(); + + if (userN > seqN) + return QKeySequence::NoMatch; + + // If equal in length, we have a potential ExactMatch sequence, + // else we already know it can only be partial. + QKeySequence::SequenceMatch match = (userN == seqN ? QKeySequence::ExactMatch + : QKeySequence::PartialMatch); + + for (uint i = 0; i < userN; ++i) { + int userKey = seq1[i].toCombined(), sequenceKey = seq2[i].toCombined(); + if ((userKey & Qt::Key_unknown) == Qt::Key_hyphen) + userKey = (userKey & Qt::KeyboardModifierMask) | Qt::Key_Minus; + if ((sequenceKey & Qt::Key_unknown) == Qt::Key_hyphen) + sequenceKey = (sequenceKey & Qt::KeyboardModifierMask) | Qt::Key_Minus; + if (userKey != sequenceKey) + return QKeySequence::NoMatch; + } + return match; +} + +/*! \internal + Returns the list of ShortcutEntry's matching the last Identical state. +*/ +QList ShortcutMap::matches() const +{ + Q_D(const ShortcutMap); + return d->identicals; +} + +/*! \internal + Dispatches QShortcutEvents to widgets who grabbed the matched key sequence. +*/ +void ShortcutMap::dispatchEvent(QKeyEvent *e) +{ + Q_D(ShortcutMap); + if (!d->identicals.size()) + return; + + const QKeySequence &curKey = d->identicals.at(0)->keyseq; + if (d->prevSequence != curKey) { + d->ambigCount = 0; + d->prevSequence = curKey; + } + // Find next + const ShortcutEntry *current = nullptr, *next = nullptr; + int i = 0, enabledShortcuts = 0; + QList ambiguousShortcuts; + while (i < d->identicals.size()) { + current = d->identicals.at(i); + if (current->enabled || !next) { + ++enabledShortcuts; + if (lcShortcutMap().isDebugEnabled()) + ambiguousShortcuts.append(current); + if (enabledShortcuts > d->ambigCount + 1) + break; + next = current; + } + ++i; + } + d->ambigCount = (d->identicals.size() == i ? 0 : d->ambigCount + 1); + // Don't trigger shortcut if we're autorepeating and the shortcut is + // grabbed with not accepting autorepeats. + if (!next || (e->isAutoRepeat() && !next->autorepeat)) + return; + // Dispatch next enabled + if (lcShortcutMap().isDebugEnabled()) { + if (ambiguousShortcuts.size() > 1) { + qCDebug(lcShortcutMap) + << "The following shortcuts are about to be activated ambiguously:"; + for (const ShortcutEntry *entry : std::as_const(ambiguousShortcuts)) + qCDebug(lcShortcutMap).nospace() + << "- " << entry->keyseq << " (belonging to " << entry->owner << ")"; + } + + qCDebug(lcShortcutMap).nospace() + << "ShortcutMap::dispatchEvent(): Sending QShortcutEvent(\"" << next->keyseq.toString() + << "\", " << next->id << ", " << static_cast(enabledShortcuts > 1) + << ") to object(" << next->owner << ')'; + } + QShortcutEvent se(next->keyseq, next->id, enabledShortcuts > 1); + QCoreApplication::sendEvent(const_cast(next->owner), &se); +} + +} // namespace Terminal::Internal diff --git a/src/plugins/terminal/shortcutmap.h b/src/plugins/terminal/shortcutmap.h new file mode 100644 index 00000000000..e3de7e01bdf --- /dev/null +++ b/src/plugins/terminal/shortcutmap.h @@ -0,0 +1,52 @@ +// Copyright (C) 2023 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 + +// COPIED FROM shortcutmap_p.h +#pragma once + +#include +#include + +class QKeyEvent; +class QObject; + +namespace Terminal::Internal { + +struct ShortcutEntry; +class ShortcutMapPrivate; + +class ShortcutMap +{ + Q_DECLARE_PRIVATE(ShortcutMap) +public: + ShortcutMap(); + ~ShortcutMap(); + + typedef bool (*ContextMatcher)(QObject *object, Qt::ShortcutContext context); + + int addShortcut(QObject *owner, + const QKeySequence &key, + Qt::ShortcutContext context, + ContextMatcher matcher); + int removeShortcut(int id, QObject *owner, const QKeySequence &key = QKeySequence()); + + QKeySequence::SequenceMatch state(); + + bool tryShortcut(QKeyEvent *e); + bool hasShortcutForKeySequence(const QKeySequence &seq) const; + +private: + void resetState(); + QKeySequence::SequenceMatch nextState(QKeyEvent *e); + void dispatchEvent(QKeyEvent *e); + + QKeySequence::SequenceMatch find(QKeyEvent *e, int ignoredModifiers = 0); + QKeySequence::SequenceMatch matches(const QKeySequence &seq1, const QKeySequence &seq2) const; + QList matches() const; + void createNewSequences(QKeyEvent *e, QList &ksl, int ignoredModifiers); + void clearSequence(QList &ksl); + + QScopedPointer d_ptr; +}; + +} // namespace Terminal::Internal diff --git a/src/plugins/terminal/terminal.qbs b/src/plugins/terminal/terminal.qbs index 300c1acf19d..f9b3409bebd 100644 --- a/src/plugins/terminal/terminal.qbs +++ b/src/plugins/terminal/terminal.qbs @@ -21,6 +21,8 @@ QtcPlugin { "shellmodel.h", "shellintegration.cpp", "shellintegration.h", + "shortcutmap.cpp", + "shortcutmap.h", "terminal.qrc", "terminalconstants.h", "terminalicons.h", diff --git a/src/plugins/terminal/terminalpane.cpp b/src/plugins/terminal/terminalpane.cpp index 965e3ba651c..f77c9bf5f27 100644 --- a/src/plugins/terminal/terminalpane.cpp +++ b/src/plugins/terminal/terminalpane.cpp @@ -4,6 +4,7 @@ #include "terminalpane.h" #include "shellmodel.h" +#include "shortcutmap.h" #include "terminalconstants.h" #include "terminalicons.h" #include "terminalsettings.h" @@ -36,9 +37,9 @@ using namespace Core; TerminalPane::TerminalPane(QObject *parent) : IOutputPane(parent) - , m_context("Terminal.Pane", Core::Constants::C_GLOBAL_CUTOFF) + , m_selfContext("Terminal.Pane") { - setupContext(m_context, &m_tabWidget); + setupContext(m_selfContext, &m_tabWidget); setZoomButtonsEnabled(true); connect(this, &IOutputPane::zoomInRequested, this, [this] { @@ -52,6 +53,9 @@ TerminalPane::TerminalPane(QObject *parent) initActions(); + m_lockKeyboardButton = new QToolButton(); + m_lockKeyboardButton->setDefaultAction(&lockKeyboard); + m_newTerminalButton = new QToolButton(); m_newTerminalButton->setDefaultAction(&newTerminal); @@ -75,10 +79,10 @@ TerminalPane::TerminalPane(QObject *parent) .toString(QKeySequence::NativeText); if (TerminalSettings::instance().sendEscapeToTerminal.value()) { m_escSettingButton->setText(escKey); - m_escSettingButton->setToolTip(Tr::tr("Sending ESC to terminal instead of Qt Creator")); + m_escSettingButton->setToolTip(Tr::tr("Sending Esc to terminal instead of Qt Creator")); } else { m_escSettingButton->setText(shiftEsc); - m_escSettingButton->setToolTip(Tr::tr("Press %1 to send ESC to terminal").arg(shiftEsc)); + m_escSettingButton->setToolTip(Tr::tr("Press %1 to send Esc to terminal").arg(shiftEsc)); } }; @@ -124,6 +128,14 @@ void TerminalPane::openTerminal(const OpenTerminalParameters ¶meters) } const auto terminalWidget = new TerminalWidget(&m_tabWidget, parametersCopy); + + using namespace Constants; + terminalWidget->unlockGlobalAction("Coreplugin.OutputPane.minmax"); + terminalWidget->unlockGlobalAction(Core::Constants::LOCATE); + terminalWidget->unlockGlobalAction(NEWTERMINAL); + terminalWidget->unlockGlobalAction(NEXTTERMINAL); + terminalWidget->unlockGlobalAction(PREVTERMINAL); + m_tabWidget.setCurrentIndex(m_tabWidget.addTab(terminalWidget, Tr::tr("Terminal"))); setupTerminalWidget(terminalWidget); @@ -229,6 +241,23 @@ void TerminalPane::initActions() { createShellMenu(); + lockKeyboard.setCheckable(true); + lockKeyboard.setChecked(TerminalSettings::instance().lockKeyboard()); + + auto updateLockKeyboard = [this](bool locked) { + TerminalSettings::instance().lockKeyboard.setValue(locked); + if (locked) { + lockKeyboard.setIcon(Icons::LOCKED_TOOLBAR.icon()); + lockKeyboard.setToolTip(Tr::tr("Keyboard shortcuts will be send to the Terminal")); + } else { + lockKeyboard.setIcon(Icons::UNLOCKED_TOOLBAR.icon()); + lockKeyboard.setToolTip(Tr::tr("Keyboard shortcuts will be send to Qt Creator")); + } + }; + + updateLockKeyboard(TerminalSettings::instance().lockKeyboard()); + connect(&lockKeyboard, &QAction::toggled, this, updateLockKeyboard); + newTerminal.setText(Tr::tr("New Terminal")); newTerminal.setIcon(NEW_TERMINAL_ICON.icon()); newTerminal.setToolTip(Tr::tr("Create a new Terminal.")); @@ -242,25 +271,22 @@ void TerminalPane::initActions() using namespace Constants; - ActionManager::registerAction(&newTerminal, NEWTERMINAL, m_context) - ->setDefaultKeySequences({QKeySequence( - HostOsInfo::isMacHost() ? QLatin1String("Ctrl+T") : QLatin1String("Ctrl+Shift+T"))}); + Command *cmd = ActionManager::registerAction(&newTerminal, NEWTERMINAL, m_selfContext); + cmd->setDefaultKeySequences({QKeySequence( + HostOsInfo::isMacHost() ? QLatin1String("Ctrl+T") : QLatin1String("Ctrl+Shift+T"))}); - ActionManager::registerAction(&nextTerminal, NEXTTERMINAL, m_context) + ActionManager::registerAction(&nextTerminal, NEXTTERMINAL, m_selfContext) ->setDefaultKeySequences( {QKeySequence("Alt+Tab"), QKeySequence(HostOsInfo::isMacHost() ? QLatin1String("Ctrl+Shift+[") : QLatin1String("Ctrl+PgUp"))}); - ActionManager::registerAction(&prevTerminal, PREVTERMINAL, m_context) + ActionManager::registerAction(&prevTerminal, PREVTERMINAL, m_selfContext) ->setDefaultKeySequences( {QKeySequence("Alt+Shift+Tab"), QKeySequence(HostOsInfo::isMacHost() ? QLatin1String("Ctrl+Shift+]") : QLatin1String("Ctrl+PgDown"))}); - m_minMax = TerminalWidget::unlockGlobalAction("Coreplugin.OutputPane.minmax", m_context); - m_locate = TerminalWidget::unlockGlobalAction(Core::Constants::LOCATE, m_context); - connect(&newTerminal, &QAction::triggered, this, [this] { openTerminal({}); }); connect(&closeTerminal, &QAction::triggered, this, [this] { removeTab(m_tabWidget.currentIndex()); @@ -303,10 +329,11 @@ void TerminalPane::createShellMenu() QList TerminalPane::toolBarWidgets() const { QList widgets = IOutputPane::toolBarWidgets(); + widgets.prepend(m_newTerminalButton); widgets.prepend(m_closeTerminalButton); - return widgets << m_openSettingsButton << m_escSettingButton; + return widgets << m_openSettingsButton << m_lockKeyboardButton << m_escSettingButton; } QString TerminalPane::displayName() const diff --git a/src/plugins/terminal/terminalpane.h b/src/plugins/terminal/terminalpane.h index 21f15168f26..8a24e1cf302 100644 --- a/src/plugins/terminal/terminalpane.h +++ b/src/plugins/terminal/terminalpane.h @@ -62,18 +62,17 @@ private: QToolButton *m_closeTerminalButton{nullptr}; QToolButton *m_openSettingsButton{nullptr}; QToolButton *m_escSettingButton{nullptr}; - - UnlockedGlobalAction m_minMax; - UnlockedGlobalAction m_locate; + QToolButton *m_lockKeyboardButton{nullptr}; QAction newTerminal; QAction nextTerminal; QAction prevTerminal; QAction closeTerminal; + QAction lockKeyboard; QMenu m_shellMenu; - Core::Context m_context; + Core::Context m_selfContext; bool m_widgetInitialized{false}; bool m_isVisible{false}; diff --git a/src/plugins/terminal/terminalsettings.h b/src/plugins/terminal/terminalsettings.h index 4550bbce2a2..1c07f9ab033 100644 --- a/src/plugins/terminal/terminalsettings.h +++ b/src/plugins/terminal/terminalsettings.h @@ -32,6 +32,7 @@ public: Utils::BoolAspect sendEscapeToTerminal{this}; Utils::BoolAspect audibleBell{this}; + Utils::BoolAspect lockKeyboard{this}; }; } // Terminal diff --git a/src/plugins/terminal/terminalwidget.cpp b/src/plugins/terminal/terminalwidget.cpp index b08038ee29d..86171f1882e 100644 --- a/src/plugins/terminal/terminalwidget.cpp +++ b/src/plugins/terminal/terminalwidget.cpp @@ -252,10 +252,39 @@ void TerminalWidget::setupColors() update(); } -static RegisteredAction registerAction(Id commandId, const Context &context) +static bool contextMatcher(QObject *, Qt::ShortcutContext) +{ + return true; +} + +void TerminalWidget::registerShortcut(Command *cmd) +{ + QTC_ASSERT(cmd, return); + auto addShortCut = [this, cmd] { + for (const auto &keySequence : cmd->keySequences()) { + if (!keySequence.isEmpty()) { + m_shortcutMap.addShortcut(cmd->action(), + keySequence, + Qt::ShortcutContext::WindowShortcut, + contextMatcher); + } + } + }; + auto removeShortCut = [this, cmd] { m_shortcutMap.removeShortcut(0, cmd->action()); }; + addShortCut(); + + connect(cmd, &Command::keySequenceChanged, this, [addShortCut, removeShortCut]() { + removeShortCut(); + addShortCut(); + }); +} + +RegisteredAction TerminalWidget::registerAction(Id commandId, const Context &context) { QAction *action = new QAction; - ActionManager::registerAction(action, commandId, context); + Command *cmd = ActionManager::registerAction(action, commandId, context); + + registerShortcut(cmd); return RegisteredAction(action, [commandId](QAction *a) { ActionManager::unregisterAction(a, commandId); @@ -287,10 +316,10 @@ void TerminalWidget::setupActions() this, &TerminalWidget::moveCursorWordRight); - m_exit = unlockGlobalAction(Core::Constants::EXIT, m_context); - m_options = unlockGlobalAction(Core::Constants::OPTIONS, m_context); - m_settings = unlockGlobalAction("Preferences.Terminal.General", m_context); - m_findInDocument = unlockGlobalAction(Core::Constants::FIND_IN_DOCUMENT, m_context); + unlockGlobalAction(Core::Constants::EXIT); + unlockGlobalAction(Core::Constants::OPTIONS); + unlockGlobalAction("Preferences.Terminal.General"); + unlockGlobalAction(Core::Constants::FIND_IN_DOCUMENT); } void TerminalWidget::closeTerminal() @@ -945,6 +974,9 @@ void TerminalWidget::paintCursor(QPainter &p) const auto cursor = m_surface->cursor(); + if (!m_preEditString.isEmpty()) + cursor.shape = Internal::Cursor::Shape::Underline; + const bool blinkState = !cursor.blink || m_cursorBlinkState || !TerminalSettings::instance().allowBlinkingCursor.value(); @@ -990,9 +1022,13 @@ void TerminalWidget::paintPreedit(QPainter &p) const QRectF rect = QRectF(gridToGlobal(cursor.position), gridToGlobal({cursor.position.x(), cursor.position.y()}, true, true)); - p.fillRect(rect, QColor::fromRgb(0, 0, 0)); - p.setPen(Qt::white); - p.drawText(rect, m_preEditString); + rect.setWidth(viewport()->width() - rect.x()); + + p.setPen(toQColor(ColorIndex::Foreground)); + QFont f = font(); + f.setUnderline(true); + p.setFont(f); + p.drawText(rect, Qt::TextDontClip | Qt::TextWrapAnywhere, m_preEditString); } } @@ -1303,7 +1339,7 @@ void TerminalWidget::mousePressEvent(QMouseEvent *event) contextMenu->addSeparator(); contextMenu->addAction(configureAction); - contextMenu->popup(event->globalPos()); + contextMenu->popup(event->globalPosition().toPoint()); } else if (m_selection) { copyToClipboard(); setSelection(std::nullopt); @@ -1506,6 +1542,11 @@ void TerminalWidget::showEvent(QShowEvent *event) bool TerminalWidget::event(QEvent *event) { + if (TerminalSettings::instance().lockKeyboard() && event->type() == QEvent::ShortcutOverride) { + event->accept(); + return true; + } + if (event->type() == QEvent::Paint) { QPainter p(this); p.fillRect(QRect(QPoint(0, 0), size()), m_currentColors[ColorIndex::Background]); @@ -1513,12 +1554,16 @@ bool TerminalWidget::event(QEvent *event) } if (event->type() == QEvent::KeyPress) { - QKeyEvent *k = (QKeyEvent *) event; + auto k = static_cast(event); + + if (TerminalSettings::instance().lockKeyboard() && m_shortcutMap.tryShortcut(k)) + return true; + keyPressEvent(k); return true; } if (event->type() == QEvent::KeyRelease) { - QKeyEvent *k = (QKeyEvent *) event; + auto k = static_cast(event); keyReleaseEvent(k); return true; } @@ -1565,21 +1610,11 @@ void TerminalWidget::initActions() ActionManager::registerAction(&clearTerminal, Constants::CLEAR_TERMINAL, context); } -UnlockedGlobalAction TerminalWidget::unlockGlobalAction(const Utils::Id &commandId, - const Context &context) +void TerminalWidget::unlockGlobalAction(const Utils::Id &commandId) { - QAction *srcAction = ActionManager::command(commandId)->actionForContext( - Core::Constants::C_GLOBAL); - - ProxyAction *proxy = ProxyAction::proxyActionWithIcon(srcAction, srcAction->icon()); - ActionManager::registerAction(proxy, commandId, context); - - UnlockedGlobalAction registeredAction(proxy, [commandId](QAction *a) { - ActionManager::unregisterAction(a, commandId); - delete a; - }); - - return registeredAction; + Command *cmd = ActionManager::command(commandId); + QTC_ASSERT(cmd, return); + registerShortcut(cmd); } } // namespace Terminal diff --git a/src/plugins/terminal/terminalwidget.h b/src/plugins/terminal/terminalwidget.h index 78e50db7ffc..11cd9335cc9 100644 --- a/src/plugins/terminal/terminalwidget.h +++ b/src/plugins/terminal/terminalwidget.h @@ -3,12 +3,14 @@ #pragma once +#include "shortcutmap.h" #include "terminalsearch.h" #include "terminalsurface.h" #include #include +#include #include #include @@ -24,7 +26,6 @@ namespace Terminal { -using UnlockedGlobalAction = std::unique_ptr>; using RegisteredAction = std::unique_ptr>; class TerminalWidget : public QAbstractScrollArea @@ -91,8 +92,7 @@ public: static void initActions(); - [[nodiscard]] static UnlockedGlobalAction unlockGlobalAction(const Utils::Id &commandId, - const Core::Context &context); + void unlockGlobalAction(const Utils::Id &commandId); signals: void started(qint64 pid); @@ -189,6 +189,9 @@ protected: void updateCopyState(); + RegisteredAction registerAction(Utils::Id commandId, const Core::Context &context); + void registerShortcut(Core::Command *command); + private: Core::Context m_context; std::unique_ptr m_process; @@ -248,10 +251,7 @@ private: RegisteredAction m_moveCursorWordRight; RegisteredAction m_close; - UnlockedGlobalAction m_findInDocument; - UnlockedGlobalAction m_exit; - UnlockedGlobalAction m_options; - UnlockedGlobalAction m_settings; + Internal::ShortcutMap m_shortcutMap; }; } // namespace Terminal diff --git a/src/plugins/texteditor/basehoverhandler.cpp b/src/plugins/texteditor/basehoverhandler.cpp index 203ecc36e20..45949fb8863 100644 --- a/src/plugins/texteditor/basehoverhandler.cpp +++ b/src/plugins/texteditor/basehoverhandler.cpp @@ -121,7 +121,7 @@ void BaseHoverHandler::process(TextEditorWidget *widget, int pos, ReportPriority void BaseHoverHandler::identifyMatch(TextEditorWidget *editorWidget, int pos, ReportPriority report) { - const auto cleanup = qScopeGuard([this, report] { report(priority()); }); + const QScopeGuard cleanup([this, report] { report(priority()); }); QString tooltip = editorWidget->extraSelectionTooltip(pos); if (!tooltip.isEmpty()) diff --git a/src/plugins/texteditor/codeassist/codeassistant.cpp b/src/plugins/texteditor/codeassist/codeassistant.cpp index 0da6571da8f..0bdf34efaba 100644 --- a/src/plugins/texteditor/codeassist/codeassistant.cpp +++ b/src/plugins/texteditor/codeassist/codeassistant.cpp @@ -158,7 +158,7 @@ void CodeAssistantPrivate::requestProposal(AssistReason reason, bool isUpdate) { // make sure to cleanup old proposals if we cannot find a new assistant - auto cleanup = qScopeGuard([this] { destroyContext(); }); + QScopeGuard cleanup([this] { destroyContext(); }); if (isWaitingForProposal()) cancelCurrentRequest(); diff --git a/src/plugins/texteditor/colorpreviewhoverhandler.cpp b/src/plugins/texteditor/colorpreviewhoverhandler.cpp index 1a66392c550..7e3134e8c27 100644 --- a/src/plugins/texteditor/colorpreviewhoverhandler.cpp +++ b/src/plugins/texteditor/colorpreviewhoverhandler.cpp @@ -335,7 +335,7 @@ static QColor colorFromFuncAndArgs(const QString &func, const QStringList &args) void ColorPreviewHoverHandler::identifyMatch(TextEditorWidget *editorWidget, int pos, ReportPriority report) { - const auto cleanup = qScopeGuard([this, report] { report(priority()); }); + const QScopeGuard cleanup([this, report] { report(priority()); }); if (editorWidget->extraSelectionTooltip(pos).isEmpty()) { const QTextBlock tb = editorWidget->document()->findBlock(pos); diff --git a/src/plugins/texteditor/snippets/snippet.cpp b/src/plugins/texteditor/snippets/snippet.cpp index 74a4dc543c3..0b3bd080e7a 100644 --- a/src/plugins/texteditor/snippets/snippet.cpp +++ b/src/plugins/texteditor/snippets/snippet.cpp @@ -189,7 +189,7 @@ SnippetParseResult Snippet::parse(const QString &snippet) if (!errorMessage.isEmpty()) return {SnippetParseError{errorMessage, {}, -1}}; - const int count = preprocessedSnippet.count(); + const int count = preprocessedSnippet.size(); NameMangler *mangler = nullptr; QMap variableIndexes; @@ -404,7 +404,7 @@ void Internal::TextEditorPlugin::testSnippetParsing() QCOMPARE(manglerId, expected.manglerId); }; - for (int i = 0; i < parts.count(); ++i) + for (int i = 0; i < parts.size(); ++i) rangesCompare(snippet.parts.at(i), parts.at(i)); } #endif diff --git a/src/plugins/texteditor/textdocumentlayout.cpp b/src/plugins/texteditor/textdocumentlayout.cpp index 703f9563bf1..08c1e21117b 100644 --- a/src/plugins/texteditor/textdocumentlayout.cpp +++ b/src/plugins/texteditor/textdocumentlayout.cpp @@ -596,6 +596,8 @@ bool TextDocumentLayout::updateSuggestion(const QTextBlock &block, { if (TextSuggestion *suggestion = TextDocumentLayout::suggestion(block)) { auto positionInBlock = position - block.position(); + if (positionInBlock < suggestion->position()) + return false; const QString start = block.text().left(positionInBlock); const QString end = block.text().mid(positionInBlock); const QString replacement = suggestion->document()->firstBlock().text(); diff --git a/src/plugins/texteditor/texteditor.cpp b/src/plugins/texteditor/texteditor.cpp index 2c8ff597015..0a0e1dff889 100644 --- a/src/plugins/texteditor/texteditor.cpp +++ b/src/plugins/texteditor/texteditor.cpp @@ -1435,7 +1435,7 @@ void TextEditorWidgetPrivate::print(QPrinter *printer) return; doc = doc->clone(doc); - const auto cleanup = qScopeGuard([doc] { delete doc; }); + const QScopeGuard cleanup([doc] { delete doc; }); QTextOption opt = doc->defaultTextOption(); opt.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); @@ -2555,7 +2555,7 @@ void TextEditorWidget::keyPressEvent(QKeyEvent *e) { ICore::restartTrimmer(); - auto clearBlockSelectionGuard = qScopeGuard([&]() { d->clearBlockSelection(); }); + QScopeGuard cleanup([&] { d->clearBlockSelection(); }); if (!isModifier(e) && mouseHidingEnabled()) viewport()->setCursor(Qt::BlankCursor); @@ -2834,7 +2834,7 @@ void TextEditorWidget::keyPressEvent(QKeyEvent *e) } if (blockSelectionOperation != QTextCursor::NoMove) { - clearBlockSelectionGuard.dismiss(); + cleanup.dismiss(); d->handleMoveBlockSelection(blockSelectionOperation); } else if (!d->cursorMoveKeyEvent(e)) { QTextCursor cursor = textCursor(); @@ -5284,7 +5284,7 @@ void TextEditorWidgetPrivate::paintTextMarks(QPainter &painter, const ExtraAreaP int yoffset = blockBoundingRect.top(); painter.save(); - const auto cleanup = qScopeGuard([&painter, size, yoffset, xoffset, overrideIcon] { + const QScopeGuard cleanup([&painter, size, yoffset, xoffset, overrideIcon] { if (!overrideIcon.isNull()) { const QRect r(xoffset, yoffset, size, size); overrideIcon.paint(&painter, r, Qt::AlignCenter); diff --git a/src/shared/designerintegrationv2/sizehandlerect.cpp b/src/shared/designerintegrationv2/sizehandlerect.cpp index 111b14b2560..4a775eaeae0 100644 --- a/src/shared/designerintegrationv2/sizehandlerect.cpp +++ b/src/shared/designerintegrationv2/sizehandlerect.cpp @@ -78,7 +78,7 @@ void SizeHandleRect::mousePressEvent(QMouseEvent *e) return; m_startSize = m_curSize = m_resizable->size(); - m_startPos = m_curPos = m_resizable->mapFromGlobal(e->globalPos()); + m_startPos = m_curPos = m_resizable->mapFromGlobal(e->globalPosition().toPoint()); if (debugSizeHandle) qDebug() << "SizeHandleRect::mousePressEvent" << m_startSize << m_startPos << m_curPos; @@ -94,7 +94,7 @@ void SizeHandleRect::mouseMoveEvent(QMouseEvent *e) // causes the handle and the mouse cursor to become out of sync // once a min/maxSize limit is hit. When the cursor reenters the valid // areas, it will now snap to it. - m_curPos = m_resizable->mapFromGlobal(e->globalPos()); + m_curPos = m_resizable->mapFromGlobal(e->globalPosition().toPoint()); QSize delta = QSize(m_curPos.x() - m_startPos.x(), m_curPos.y() - m_startPos.y()); switch (m_dir) { case Right: diff --git a/src/tools/process_stub/main.cpp b/src/tools/process_stub/main.cpp index f606b063694..d5fdc2f4086 100644 --- a/src/tools/process_stub/main.cpp +++ b/src/tools/process_stub/main.cpp @@ -48,20 +48,16 @@ std::optional environmentVariables; QProcess inferiorProcess; int inferiorId{0}; -#ifndef Q_OS_WIN - #ifdef Q_OS_DARWIN // A memory mapped helper to retrieve the pid of the inferior process in debugMode static int *shared_child_pid = nullptr; #endif -using OSSocketNotifier = QSocketNotifier; -#else +#ifdef Q_OS_WIN Q_PROCESS_INFORMATION *win_process_information = nullptr; -using OSSocketNotifier = QWinEventNotifier; #endif -// Helper to read a single character from stdin in testMode -OSSocketNotifier *stdInNotifier; + +bool waitingForExitKeyPress = false; QThread processThread; @@ -77,8 +73,10 @@ std::optional readEnvFile(); void setupControlSocket(); void setupSignalHandlers(); void startProcess(const QString &program, const QStringList &arguments, const QString &workingDir); -void readKey(); +void onKeyPress(std::function callback); void sendSelfPid(); +void killInferior(); +void resumeInferior(); int main(int argc, char *argv[]) { @@ -117,7 +115,15 @@ int main(int argc, char *argv[]) if (debugMode) { qDebug() << "Press 'c' to continue or 'k' to kill, followed by 'enter'"; - readKey(); + + onKeyPress([] { + char ch; + std::cin >> ch; + if (ch == 'k') + killInferior(); + else + resumeInferior(); + }); } return a.exec(); @@ -169,15 +175,20 @@ void sendErrChDir() void doExit(int exitCode) { + if (waitingForExitKeyPress) + exit(exitCode); + if (controlSocket.state() == QLocalSocket::ConnectedState && controlSocket.bytesToWrite()) controlSocket.waitForBytesWritten(1000); if (!commandLineParser.value("wait").isEmpty()) { - std::cout << commandLineParser.value("wait").toStdString(); - std::cin.get(); - } + std::cout << commandLineParser.value("wait").toStdString() << std::endl; - exit(exitCode); + waitingForExitKeyPress = true; + onKeyPress([exitCode] { doExit(exitCode); }); + } else { + exit(exitCode); + } } void onInferiorFinished(int exitCode, QProcess::ExitStatus status) @@ -550,23 +561,15 @@ void setupControlSocket() controlSocket.connectToServer(commandLineParser.value("socket")); } -void onStdInReadyRead() -{ - char ch; - std::cin >> ch; - if (ch == 'k') { - killInferior(); - } else { - resumeInferior(); - } -} - -void readKey() +void onKeyPress(std::function callback) { #ifdef Q_OS_WIN - stdInNotifier = new QWinEventNotifier(GetStdHandle(STD_INPUT_HANDLE)); + // On windows, QWinEventNotifier() doesn't work for stdin, so we have to use a thread instead. + QThread *thread = QThread::create([] { std::cin.ignore(); }); + thread->start(); + QObject::connect(thread, &QThread::finished, &controlSocket, callback); #else - stdInNotifier = new QSocketNotifier(fileno(stdin), QSocketNotifier::Read); + static auto stdInNotifier = new QSocketNotifier(fileno(stdin), QSocketNotifier::Read); + QObject::connect(stdInNotifier, &QSocketNotifier::activated, callback); #endif - QObject::connect(stdInNotifier, &OSSocketNotifier::activated, &onStdInReadyRead); } diff --git a/src/tools/processlauncher/processlauncher-main.cpp b/src/tools/processlauncher/processlauncher-main.cpp index 0629ec3c6d2..980839cd8a8 100644 --- a/src/tools/processlauncher/processlauncher-main.cpp +++ b/src/tools/processlauncher/processlauncher-main.cpp @@ -32,7 +32,7 @@ int main(int argc, char *argv[]) return 1; } - auto cleanup = qScopeGuard([] { Utils::Singleton::deleteAll(); }); + const QScopeGuard cleanup([] { Utils::Singleton::deleteAll(); }); Utils::Internal::LauncherSocketHandler launcher(app.arguments().constLast()); QTimer::singleShot(0, &launcher, &Utils::Internal::LauncherSocketHandler::start); diff --git a/src/tools/sdktool/addqtoperation.cpp b/src/tools/sdktool/addqtoperation.cpp index ee48c1e5ec5..61e19855ff6 100644 --- a/src/tools/sdktool/addqtoperation.cpp +++ b/src/tools/sdktool/addqtoperation.cpp @@ -270,7 +270,7 @@ QVariantMap AddQtData::addQt(const QVariantMap &map) const for (QVariantMap::const_iterator i = map.begin(); i != map.end(); ++i) { if (!i.key().startsWith(QLatin1String(PREFIX))) continue; - QString number = i.key().mid(QString::fromLatin1(PREFIX).count()); + QString number = i.key().mid(QString::fromLatin1(PREFIX).size()); bool ok; int count = number.toInt(&ok); if (ok && count >= versionCount) diff --git a/tests/auto/solutions/tasking/tst_tasking.cpp b/tests/auto/solutions/tasking/tst_tasking.cpp index 69d87e8188e..64442529b49 100644 --- a/tests/auto/solutions/tasking/tst_tasking.cpp +++ b/tests/auto/solutions/tasking/tst_tasking.cpp @@ -509,7 +509,7 @@ void tst_Tasking::testTree_data() createSuccessTask(3), createSuccessTask(4) }; - taskTree.setupRoot(nestedRoot); + taskTree.setRecipe(nestedRoot); CustomStorage *activeStorage = storage.activeStorage(); auto collectSubLog = [activeStorage](CustomStorage *subTreeStorage){ activeStorage->m_log += subTreeStorage->m_log; diff --git a/tests/auto/utils/process/processtestapp/main.cpp b/tests/auto/utils/process/processtestapp/main.cpp index 91952c2528e..34923c407aa 100644 --- a/tests/auto/utils/process/processtestapp/main.cpp +++ b/tests/auto/utils/process/processtestapp/main.cpp @@ -28,7 +28,7 @@ int main(int argc, char **argv) #endif QCoreApplication app(argc, argv); - auto cleanup = qScopeGuard([] { Singleton::deleteAll(); }); + const QScopeGuard cleanup([] { Singleton::deleteAll(); }); TemporaryDirectory::setMasterTemporaryDirectory(QDir::tempPath() + "/" + Core::Constants::IDE_CASED_ID + "-XXXXXX"); diff --git a/tests/auto/utils/process/processtestapp/processtestapp.cpp b/tests/auto/utils/process/processtestapp/processtestapp.cpp index 3905d0a22b5..6cf7510eb78 100644 --- a/tests/auto/utils/process/processtestapp/processtestapp.cpp +++ b/tests/auto/utils/process/processtestapp/processtestapp.cpp @@ -33,7 +33,7 @@ void ProcessTestApp::invokeSubProcess() { ProcessTestApp processTestApp; int returnValue = 1; - auto cleanup = qScopeGuard([&returnValue] { + const QScopeGuard cleanup([&returnValue] { QMetaObject::invokeMethod(qApp, [returnValue] { qApp->exit(returnValue); }, Qt::QueuedConnection); diff --git a/tests/system/suite_tools/tst_git_clone/test.py b/tests/system/suite_tools/tst_git_clone/test.py index c41ee6fd981..42473264f7e 100644 --- a/tests/system/suite_tools/tst_git_clone/test.py +++ b/tests/system/suite_tools/tst_git_clone/test.py @@ -43,7 +43,7 @@ def verifyVersionControlView(targetDir, canceled): vcsLog = str(waitForObject("{type='Core::OutputWindow' unnamed='1' visible='1' " "window=':Qt Creator_Core::Internal::MainWindow'}").plainText) test.log("Clone log is: %s" % vcsLog) - test.verify("Running in " + targetDir + ":" in vcsLog, + test.verify('Running in "' + targetDir + '":' in vcsLog, "Searching for target directory in clone log") test.verify(" ".join(["clone", "--progress", cloneUrl, cloneDir]) in vcsLog, "Searching for git parameters in clone log") diff --git a/tests/unit/tests/unittests/unittests-main.cpp b/tests/unit/tests/unittests/unittests-main.cpp index 8fc6da3402a..06c8268f07e 100644 --- a/tests/unit/tests/unittests/unittests-main.cpp +++ b/tests/unit/tests/unittests/unittests-main.cpp @@ -13,7 +13,6 @@ #include #include -#include #ifdef WITH_BENCHMARKS #include