From a8f6df546c83124031d9f7d0b7fcfe4505c0122f Mon Sep 17 00:00:00 2001 From: Eike Ziller Date: Mon, 25 Sep 2023 11:23:30 +0200 Subject: [PATCH 01/27] ExtensionSystem: Restrict export of privates to building with tests Change-Id: Ie75fbd38770c832aab443c977b8f5c34094d17c7 Reviewed-by: hjk --- src/libs/extensionsystem/extensionsystem_global.h | 12 ++++++++++++ src/libs/extensionsystem/pluginmanager_p.h | 2 +- src/libs/extensionsystem/pluginspec_p.h | 2 +- 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/libs/extensionsystem/extensionsystem_global.h b/src/libs/extensionsystem/extensionsystem_global.h index 85fa8de831c..13c82e75d5c 100644 --- a/src/libs/extensionsystem/extensionsystem_global.h +++ b/src/libs/extensionsystem/extensionsystem_global.h @@ -14,4 +14,16 @@ # define EXTENSIONSYSTEM_EXPORT Q_DECL_IMPORT #endif +#if defined(WITH_TESTS) +# if defined(EXTENSIONSYSTEM_LIBRARY) +# define EXTENSIONSYSTEM_TEST_EXPORT Q_DECL_EXPORT +# elif defined(EXTENSIONSYSTEM_STATIC_LIBRARY) +# define EXTENSIONSYSTEM_TEST_EXPORT +# else +# define EXTENSIONSYSTEM_TEST_EXPORT Q_DECL_IMPORT +# endif +#else +# define QTSUPPORT_TEST_EXPORT +#endif + Q_DECLARE_LOGGING_CATEGORY(pluginLog) diff --git a/src/libs/extensionsystem/pluginmanager_p.h b/src/libs/extensionsystem/pluginmanager_p.h index 4b9a34b246d..5845684b862 100644 --- a/src/libs/extensionsystem/pluginmanager_p.h +++ b/src/libs/extensionsystem/pluginmanager_p.h @@ -38,7 +38,7 @@ namespace Internal { class PluginSpecPrivate; -class EXTENSIONSYSTEM_EXPORT PluginManagerPrivate : public QObject +class EXTENSIONSYSTEM_TEST_EXPORT PluginManagerPrivate : public QObject { Q_OBJECT public: diff --git a/src/libs/extensionsystem/pluginspec_p.h b/src/libs/extensionsystem/pluginspec_p.h index c87111f02ae..f802902e53c 100644 --- a/src/libs/extensionsystem/pluginspec_p.h +++ b/src/libs/extensionsystem/pluginspec_p.h @@ -22,7 +22,7 @@ class IPlugin; namespace Internal { -class EXTENSIONSYSTEM_EXPORT PluginSpecPrivate : public QObject +class EXTENSIONSYSTEM_TEST_EXPORT PluginSpecPrivate : public QObject { Q_OBJECT From 05614ab7402623eb0a69ae7d0301044f70f93e91 Mon Sep 17 00:00:00 2001 From: Cristian Adam Date: Fri, 22 Sep 2023 22:47:31 +0200 Subject: [PATCH 02/27] CMakePM: Display help details for code completion The first 1024 bytes from the CMake .rst files are displayed raw data. A .rst to html or markdown would be needed for nicer user experience. Change-Id: Ie6adbb404d844ae88b868b465d4125c2177e6cfe Reviewed-by: Reviewed-by: Alessandro Portale --- .../cmakeprojectmanager/cmakebuildsystem.cpp | 4 +- .../cmakefilecompletionassist.cpp | 32 +++++ src/plugins/cmakeprojectmanager/cmaketool.cpp | 118 ++++++++---------- src/plugins/cmakeprojectmanager/cmaketool.h | 22 ++-- 4 files changed, 95 insertions(+), 81 deletions(-) diff --git a/src/plugins/cmakeprojectmanager/cmakebuildsystem.cpp b/src/plugins/cmakeprojectmanager/cmakebuildsystem.cpp index d8bb9155856..ecfbd3769aa 100644 --- a/src/plugins/cmakeprojectmanager/cmakebuildsystem.cpp +++ b/src/plugins/cmakeprojectmanager/cmakebuildsystem.cpp @@ -1278,9 +1278,9 @@ void CMakeBuildSystem::setupCMakeSymbolsHash() m_cmakeSymbolsHash.insert(QString::fromUtf8(arg.Value), link); if (func.LowerCaseName() == "option") - m_projectKeywords.variables << QString::fromUtf8(arg.Value); + m_projectKeywords.variables[QString::fromUtf8(arg.Value)] = FilePath(); else - m_projectKeywords.functions << QString::fromUtf8(arg.Value); + m_projectKeywords.functions[QString::fromUtf8(arg.Value)] = FilePath(); } } } diff --git a/src/plugins/cmakeprojectmanager/cmakefilecompletionassist.cpp b/src/plugins/cmakeprojectmanager/cmakefilecompletionassist.cpp index 5319eb37509..a2ba8b3a604 100644 --- a/src/plugins/cmakeprojectmanager/cmakefilecompletionassist.cpp +++ b/src/plugins/cmakeprojectmanager/cmakefilecompletionassist.cpp @@ -153,6 +153,38 @@ QList generateList(const T &words, const QIcon &i }); } +QString readFirstParagraphs(const QString &element, const FilePath &helpFile) +{ + auto content = helpFile.fileContents(1024).value_or(QByteArray()); + return QString("```\n%1\n```").arg(QString::fromUtf8(content.left(content.lastIndexOf("\n")))); +} + +QList generateList(const QMap &words, + const QIcon &icon) +{ + static QMap map; + struct MarkDownAssitProposalItem : public AssistProposalItem + { + Qt::TextFormat detailFormat() const { return Qt::MarkdownText; } + }; + + QList list; + for (const auto &[text, helpFile] : words.asKeyValueRange()) { + MarkDownAssitProposalItem *item = new MarkDownAssitProposalItem(); + item->setText(text); + + if (!helpFile.isEmpty()) { + if (!map.contains(helpFile)) + map[helpFile] = readFirstParagraphs(text, helpFile); + item->setDetail(map.value(helpFile)); + } + + item->setIcon(icon); + list << item; + }; + return list; +} + static int addFilePathItems(const AssistInterface *interface, QList &items, int symbolStartPos) diff --git a/src/plugins/cmakeprojectmanager/cmaketool.cpp b/src/plugins/cmakeprojectmanager/cmaketool.cpp index 64fc5af5580..0e2e1c64bf0 100644 --- a/src/plugins/cmakeprojectmanager/cmaketool.cpp +++ b/src/plugins/cmakeprojectmanager/cmaketool.cpp @@ -89,19 +89,8 @@ public: bool m_didRun = true; QList m_generators; - QMap m_functionArgs; + CMakeKeywords m_keywords; QVector m_fileApis; - QStringList m_variables; - QStringList m_functions; - QStringList m_properties; - QStringList m_generatorExpressions; - QStringList m_directoryProperties; - QStringList m_sourceProperties; - QStringList m_targetProperties; - QStringList m_testProperties; - QStringList m_includeStandardModules; - QStringList m_findModules; - QStringList m_policies; CMakeTool::Version m_version; }; @@ -260,7 +249,7 @@ CMakeKeywords CMakeTool::keywords() if (!isValid()) return {}; - if (m_introspection->m_functions.isEmpty() && m_introspection->m_didRun) { + if (m_introspection->m_keywords.functions.isEmpty() && m_introspection->m_didRun) { Process proc; const FilePath findCMakeRoot = TemporaryDirectory::masterDirectoryFilePath() @@ -279,61 +268,52 @@ CMakeKeywords CMakeTool::keywords() const struct { const QString helpPath; - QStringList &targetList; + QMap &targetMap; } introspections[] = { // Functions - {"Help/command", m_introspection->m_functions}, + {"Help/command", m_introspection->m_keywords.functions}, // Properties - {"Help/prop_dir", m_introspection->m_directoryProperties}, - {"Help/prop_sf", m_introspection->m_sourceProperties}, - {"Help/prop_test", m_introspection->m_testProperties}, - {"Help/prop_tgt", m_introspection->m_targetProperties}, - {"Help/prop_gbl", m_introspection->m_properties}, + {"Help/prop_dir", m_introspection->m_keywords.directoryProperties}, + {"Help/prop_sf", m_introspection->m_keywords.sourceProperties}, + {"Help/prop_test", m_introspection->m_keywords.testProperties}, + {"Help/prop_tgt", m_introspection->m_keywords.targetProperties}, + {"Help/prop_gbl", m_introspection->m_keywords.properties}, // Variables - {"Help/variable", m_introspection->m_variables}, + {"Help/variable", m_introspection->m_keywords.variables}, // Policies - {"Help/policy", m_introspection->m_policies}, + {"Help/policy", m_introspection->m_keywords.policies}, }; for (auto &i : introspections) { const FilePaths files = cmakeRoot.pathAppended(i.helpPath) .dirEntries({{"*.rst"}, QDir::Files}, QDir::Name); - i.targetList = transform(files, &FilePath::completeBaseName); + for (const auto &filePath : files) + i.targetMap[filePath.completeBaseName()] = filePath; } - m_introspection->m_properties << m_introspection->m_directoryProperties; - m_introspection->m_properties << m_introspection->m_sourceProperties; - m_introspection->m_properties << m_introspection->m_testProperties; - m_introspection->m_properties << m_introspection->m_targetProperties; + for (const auto &map : {m_introspection->m_keywords.directoryProperties, + m_introspection->m_keywords.sourceProperties, + m_introspection->m_keywords.testProperties, + m_introspection->m_keywords.targetProperties}) { + m_introspection->m_keywords.properties.insert(map); + } // Modules const FilePaths files = cmakeRoot.pathAppended("Help/module").dirEntries({{"*.rst"}, QDir::Files}, QDir::Name); - const QStringList fileNames = transform(files, &FilePath::completeBaseName); - for (const QString &fileName : fileNames) { + for (const FilePath &filePath : files) { + const QString fileName = filePath.completeBaseName(); if (fileName.startsWith("Find")) - m_introspection->m_findModules << fileName.mid(4); + m_introspection->m_keywords.findModules[fileName.mid(4)] = filePath; else - m_introspection->m_includeStandardModules << fileName; + m_introspection->m_keywords.includeStandardModules[fileName] = filePath; } - parseSyntaxHighlightingXml(); + const QStringList moduleFunctions = parseSyntaxHighlightingXml(); + for (const auto &function : moduleFunctions) + m_introspection->m_keywords.functions[function] = FilePath(); } - CMakeKeywords keywords; - keywords.functions = Utils::toSet(m_introspection->m_functions); - keywords.variables = Utils::toSet(m_introspection->m_variables); - keywords.functionArgs = m_introspection->m_functionArgs; - keywords.properties = Utils::toSet(m_introspection->m_properties); - keywords.generatorExpressions = Utils::toSet(m_introspection->m_generatorExpressions); - keywords.directoryProperties = Utils::toSet(m_introspection->m_directoryProperties); - keywords.sourceProperties = Utils::toSet(m_introspection->m_sourceProperties); - keywords.targetProperties = Utils::toSet(m_introspection->m_targetProperties); - keywords.testProperties = Utils::toSet(m_introspection->m_testProperties); - keywords.includeStandardModules = Utils::toSet(m_introspection->m_includeStandardModules); - keywords.findModules = Utils::toSet(m_introspection->m_findModules); - keywords.policies = Utils::toSet(m_introspection->m_policies); - - return keywords; + return m_introspection->m_keywords; } bool CMakeTool::hasFileApi(bool ignoreCache) const @@ -495,8 +475,6 @@ static QStringList parseDefinition(const QString &definition) void CMakeTool::parseFunctionDetailsOutput(const QString &output) { - const QSet functionSet = Utils::toSet(m_introspection->m_functions); - bool expectDefinition = false; QString currentDefinition; @@ -515,14 +493,15 @@ void CMakeTool::parseFunctionDetailsOutput(const QString &output) QStringList words = parseDefinition(currentDefinition); if (!words.isEmpty()) { const QString command = words.takeFirst(); - if (functionSet.contains(command)) { + if (m_introspection->m_keywords.functions.contains(command)) { const QStringList tmp = Utils::sorted( - words + m_introspection->m_functionArgs[command]); - m_introspection->m_functionArgs[command] = Utils::filteredUnique(tmp); + words + m_introspection->m_keywords.functionArgs[command]); + m_introspection->m_keywords.functionArgs[command] = Utils::filteredUnique( + tmp); } } - if (!words.isEmpty() && functionSet.contains(words.at(0))) - m_introspection->m_functionArgs[words.at(0)]; + if (!words.isEmpty() && m_introspection->m_keywords.functions.contains(words.at(0))) + m_introspection->m_keywords.functionArgs[words.at(0)]; currentDefinition.clear(); } else { currentDefinition.append(line.trimmed() + ' '); @@ -560,9 +539,9 @@ QStringList CMakeTool::parseVariableOutput(const QString &output) return result; } -void CMakeTool::parseSyntaxHighlightingXml() +QStringList CMakeTool::parseSyntaxHighlightingXml() { - QSet functionSet = Utils::toSet(m_introspection->m_functions); + QStringList moduleFunctions; const FilePath cmakeXml = Core::ICore::resourcePath("generic-highlighter/syntax/cmake.xml"); QXmlStreamReader reader(cmakeXml.fileContents().value_or(QByteArray())); @@ -588,19 +567,19 @@ void CMakeTool::parseSyntaxHighlightingXml() const auto functionName = name.left(name.length() - 6); QStringList arguments = readItemList(reader); - if (m_introspection->m_functionArgs.contains(functionName)) - arguments.append(m_introspection->m_functionArgs.value(functionName)); + if (m_introspection->m_keywords.functionArgs.contains(functionName)) + arguments.append( + m_introspection->m_keywords.functionArgs.value(functionName)); - m_introspection->m_functionArgs[functionName] = arguments; + m_introspection->m_keywords.functionArgs[functionName] = arguments; // Functions that are part of CMake modules like ExternalProject_Add // which are not reported by cmake --help-list-commands - if (!functionSet.contains(functionName)) { - functionSet.insert(functionName); - m_introspection->m_functions.append(functionName); + if (!m_introspection->m_keywords.functions.contains(functionName)) { + moduleFunctions << functionName; } } else if (name == u"generator-expressions") { - m_introspection->m_generatorExpressions = readItemList(reader); + m_introspection->m_keywords.generatorExpressions = toSet(readItemList(reader)); } else { reader.skipCurrentElement(); } @@ -623,16 +602,19 @@ void CMakeTool::parseSyntaxHighlightingXml() {"set_target_properties", "set_directory_properties"}, {"set_tests_properties", "set_directory_properties"}}; for (const auto &pair : std::as_const(functionPairs)) { - if (!m_introspection->m_functionArgs.contains(pair.first)) - m_introspection->m_functionArgs[pair.first] = m_introspection->m_functionArgs.value( - pair.second); + if (!m_introspection->m_keywords.functionArgs.contains(pair.first)) + m_introspection->m_keywords.functionArgs[pair.first] + = m_introspection->m_keywords.functionArgs.value(pair.second); } // Special case for cmake_print_variables, which will print the names and values for variables // and needs to be as a known function const QString cmakePrintVariables("cmake_print_variables"); - m_introspection->m_functionArgs[cmakePrintVariables] = {}; - m_introspection->m_functions.append(cmakePrintVariables); + m_introspection->m_keywords.functionArgs[cmakePrintVariables] = {}; + moduleFunctions << cmakePrintVariables; + + moduleFunctions.removeDuplicates(); + return moduleFunctions; } void CMakeTool::fetchFromCapabilities(bool ignoreCache) const diff --git a/src/plugins/cmakeprojectmanager/cmaketool.h b/src/plugins/cmakeprojectmanager/cmaketool.h index 0ad9780971b..b72a926c768 100644 --- a/src/plugins/cmakeprojectmanager/cmaketool.h +++ b/src/plugins/cmakeprojectmanager/cmaketool.h @@ -21,17 +21,17 @@ namespace Internal { class IntrospectionData; } struct CMAKE_EXPORT CMakeKeywords { - QSet variables; - QSet functions; - QSet properties; + QMap variables; + QMap functions; + QMap properties; QSet generatorExpressions; - QSet directoryProperties; - QSet sourceProperties; - QSet targetProperties; - QSet testProperties; - QSet includeStandardModules; - QSet findModules; - QSet policies; + QMap directoryProperties; + QMap sourceProperties; + QMap targetProperties; + QMap testProperties; + QMap includeStandardModules; + QMap findModules; + QMap policies; QMap functionArgs; }; @@ -117,7 +117,7 @@ private: void runCMake(Utils::Process &proc, const QStringList &args, int timeoutS = 1) const; void parseFunctionDetailsOutput(const QString &output); QStringList parseVariableOutput(const QString &output); - void parseSyntaxHighlightingXml(); + QStringList parseSyntaxHighlightingXml(); void fetchFromCapabilities(bool ignoreCache = false) const; void parseFromCapabilities(const QString &input) const; From cd94514dbb7471d5c338e9ed7c0baca7ccc772bd Mon Sep 17 00:00:00 2001 From: Cristian Adam Date: Mon, 18 Sep 2023 22:08:23 +0200 Subject: [PATCH 03/27] CMakePM: Add hover help for CMakeEditor Fixes: QTCREATORBUG-25780 Change-Id: I954023f701e6c1c6ca5e25190b37f8b9a8becfb5 Reviewed-by: Alessandro Portale Reviewed-by: --- .../cmakeprojectmanager/cmakeeditor.cpp | 84 +++++++++++++++++++ .../cmakefilecompletionassist.cpp | 20 +++-- 2 files changed, 95 insertions(+), 9 deletions(-) diff --git a/src/plugins/cmakeprojectmanager/cmakeeditor.cpp b/src/plugins/cmakeprojectmanager/cmakeeditor.cpp index 6ba35180c31..1f1e873be52 100644 --- a/src/plugins/cmakeprojectmanager/cmakeeditor.cpp +++ b/src/plugins/cmakeprojectmanager/cmakeeditor.cpp @@ -9,6 +9,7 @@ #include "cmakefilecompletionassist.h" #include "cmakeindenter.h" #include "cmakekitaspect.h" +#include "cmakeproject.h" #include "cmakeprojectconstants.h" #include "3rdparty/cmake/cmListFileCache.h" @@ -19,11 +20,14 @@ #include #include #include +#include #include #include +#include #include #include #include +#include #include @@ -31,6 +35,7 @@ using namespace Core; using namespace ProjectExplorer; +using namespace Utils; using namespace TextEditor; namespace CMakeProjectManager::Internal { @@ -308,6 +313,83 @@ static TextDocument *createCMakeDocument() return doc; } +// +// CMakeHoverHandler +// + +class CMakeHoverHandler : public TextEditor::BaseHoverHandler +{ + mutable CMakeKeywords m_keywords; + QString m_helpToolTip; + +public: + const CMakeKeywords &keywords() const; + + void identifyMatch(TextEditor::TextEditorWidget *editorWidget, + int pos, + ReportPriority report) final; + void operateTooltip(TextEditorWidget *editorWidget, const QPoint &point) final; +}; + +const CMakeKeywords &CMakeHoverHandler::keywords() const +{ + if (m_keywords.functions.isEmpty()) { + CMakeTool *tool = nullptr; + if (auto bs = ProjectTree::currentBuildSystem()) + tool = CMakeKitAspect::cmakeTool(bs->target()->kit()); + if (!tool) + tool = CMakeToolManager::defaultCMakeTool(); + + if (tool) + m_keywords = tool->keywords(); + } + + return m_keywords; +} + +QString readFirstParagraphs(const QString &element, const FilePath &helpFile); + +void CMakeHoverHandler::identifyMatch(TextEditor::TextEditorWidget *editorWidget, + int pos, + ReportPriority report) +{ + const QScopeGuard cleanup([this, report] { report(priority()); }); + + QTextCursor cursor = editorWidget->textCursor(); + cursor.setPosition(pos); + const QString word = Utils::Text::wordUnderCursor(cursor); + + FilePath helpFile; + for (const auto &map : {keywords().functions, + keywords().variables, + keywords().directoryProperties, + keywords().sourceProperties, + keywords().targetProperties, + keywords().testProperties, + keywords().properties, + keywords().includeStandardModules, + keywords().findModules, + keywords().policies}) { + if (map.contains(word)) { + helpFile = map.value(word); + break; + } + } + m_helpToolTip.clear(); + if (!helpFile.isEmpty()) + m_helpToolTip = readFirstParagraphs(word, helpFile); + + setPriority(m_helpToolTip.isEmpty() ? Priority_Tooltip : Priority_None); +} + +void CMakeHoverHandler::operateTooltip(TextEditorWidget *editorWidget, const QPoint &point) +{ + if (!m_helpToolTip.isEmpty()) + Utils::ToolTip::show(point, m_helpToolTip, Qt::MarkdownText, editorWidget); + else + Utils::ToolTip::hide(); +} + // // CMakeEditorFactory // @@ -334,6 +416,8 @@ CMakeEditorFactory::CMakeEditorFactory() | TextEditorActionHandler::FollowSymbolUnderCursor | TextEditorActionHandler::Format); + addHoverHandler(new CMakeHoverHandler); + ActionContainer *contextMenu = ActionManager::createMenu(Constants::M_CONTEXT); contextMenu->addAction(ActionManager::command(TextEditor::Constants::FOLLOW_SYMBOL_UNDER_CURSOR)); contextMenu->addSeparator(Context(Constants::CMAKE_EDITOR_ID)); diff --git a/src/plugins/cmakeprojectmanager/cmakefilecompletionassist.cpp b/src/plugins/cmakeprojectmanager/cmakefilecompletionassist.cpp index a2ba8b3a604..339a11b64ae 100644 --- a/src/plugins/cmakeprojectmanager/cmakefilecompletionassist.cpp +++ b/src/plugins/cmakeprojectmanager/cmakefilecompletionassist.cpp @@ -155,14 +155,21 @@ QList generateList(const T &words, const QIcon &i QString readFirstParagraphs(const QString &element, const FilePath &helpFile) { + static QMap map; + if (map.contains(helpFile)) + return map.value(helpFile); + auto content = helpFile.fileContents(1024).value_or(QByteArray()); - return QString("```\n%1\n```").arg(QString::fromUtf8(content.left(content.lastIndexOf("\n")))); + const QString firstParagraphs + = QString("```\n%1\n```").arg(QString::fromUtf8(content.left(content.lastIndexOf("\n")))); + + map[helpFile] = firstParagraphs; + return firstParagraphs; } QList generateList(const QMap &words, const QIcon &icon) { - static QMap map; struct MarkDownAssitProposalItem : public AssistProposalItem { Qt::TextFormat detailFormat() const { return Qt::MarkdownText; } @@ -172,13 +179,8 @@ QList generateList(const QMap for (const auto &[text, helpFile] : words.asKeyValueRange()) { MarkDownAssitProposalItem *item = new MarkDownAssitProposalItem(); item->setText(text); - - if (!helpFile.isEmpty()) { - if (!map.contains(helpFile)) - map[helpFile] = readFirstParagraphs(text, helpFile); - item->setDetail(map.value(helpFile)); - } - + if (!helpFile.isEmpty()) + item->setDetail(readFirstParagraphs(text, helpFile)); item->setIcon(icon); list << item; }; From e374f809ad98610ccb5728417382f0b22e9bd141 Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Mon, 25 Sep 2023 13:34:54 +0200 Subject: [PATCH 04/27] QmakeProjectManager: Remove bogus condition from importer Fixes: QTCREATORBUG-18150 Change-Id: If9c7aaa7745b9cd0ef57d3ecd71308ffb2991c48 Reviewed-by: Christian Stenger --- src/plugins/qmakeprojectmanager/qmakeprojectimporter.cpp | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/plugins/qmakeprojectmanager/qmakeprojectimporter.cpp b/src/plugins/qmakeprojectmanager/qmakeprojectimporter.cpp index 9a9450a218f..e159f5dd6dc 100644 --- a/src/plugins/qmakeprojectmanager/qmakeprojectimporter.cpp +++ b/src/plugins/qmakeprojectmanager/qmakeprojectimporter.cpp @@ -61,11 +61,7 @@ QmakeProjectImporter::QmakeProjectImporter(const FilePath &path) : FilePaths QmakeProjectImporter::importCandidates() { - FilePaths candidates; - - const FilePath pfp = projectFilePath(); - const QString prefix = pfp.baseName(); - candidates << pfp.absolutePath(); + FilePaths candidates{projectFilePath().absolutePath()}; for (Kit *k : KitManager::kits()) { const FilePath sbdir = QmakeBuildConfiguration::shadowBuildDirectory @@ -73,7 +69,7 @@ FilePaths QmakeProjectImporter::importCandidates() const FilePath baseDir = sbdir.absolutePath(); for (const FilePath &path : baseDir.dirEntries(QDir::Dirs | QDir::NoDotAndDotDot)) { - if (path.fileName().startsWith(prefix) && !candidates.contains(path)) + if (!candidates.contains(path)) candidates << path; } } From a7d265852044751d174f2124b8d125ebfff9f64c Mon Sep 17 00:00:00 2001 From: hjk Date: Mon, 25 Sep 2023 15:28:48 +0200 Subject: [PATCH 05/27] Utils: Bark when encountering a default-constructed QDir::Filter This would always result in no hits, contrary to NoFilter. Change-Id: I22591581373eed10fb1d1f660f705992e9653d5a Reviewed-by: Christian Kandeler --- src/libs/utils/filepath.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/libs/utils/filepath.cpp b/src/libs/utils/filepath.cpp index a5a51b43bbe..26d6d667f90 100644 --- a/src/libs/utils/filepath.cpp +++ b/src/libs/utils/filepath.cpp @@ -2173,6 +2173,7 @@ FileFilter::FileFilter(const QStringList &nameFilters, fileFilters(fileFilters), iteratorFlags(flags) { + QTC_CHECK(this->fileFilters != QDir::Filters()); } QStringList FileFilter::asFindArguments(const QString &path) const From e0f6ed0fe7339818550ccb6ae2696ff7fe77cf59 Mon Sep 17 00:00:00 2001 From: hjk Date: Tue, 5 Sep 2023 11:16:52 +0200 Subject: [PATCH 06/27] ProjectExplorer: Move some code from derived GccTCFactory classes ... to base as preliminary step to merge the factories. Combining the code paths is not part of this change to keep it mechanical. Change-Id: Ia1a43000a1e3978eae85be36493a67a18ba0c3e6 Reviewed-by: Christian Kandeler --- src/plugins/projectexplorer/gcctoolchain.cpp | 242 +++++++++---------- src/plugins/projectexplorer/gcctoolchain.h | 15 +- 2 files changed, 124 insertions(+), 133 deletions(-) diff --git a/src/plugins/projectexplorer/gcctoolchain.cpp b/src/plugins/projectexplorer/gcctoolchain.cpp index bfe5e9621a6..8b9610ce0c6 100644 --- a/src/plugins/projectexplorer/gcctoolchain.cpp +++ b/src/plugins/projectexplorer/gcctoolchain.cpp @@ -1208,6 +1208,76 @@ GccToolChainFactory::GccToolChainFactory() Toolchains GccToolChainFactory::autoDetect(const ToolchainDetector &detector) const { + if (m_subType == GccToolChain::LinuxIcc) { + Toolchains result = autoDetectToolchains("icpc", + DetectVariants::No, + Constants::CXX_LANGUAGE_ID, + Constants::LINUXICC_TOOLCHAIN_TYPEID, + detector, + toolchainConstructor()); + result += autoDetectToolchains("icc", + DetectVariants::Yes, + Constants::C_LANGUAGE_ID, + Constants::LINUXICC_TOOLCHAIN_TYPEID, + detector, + toolchainConstructor()); + return result; + } + + if (m_subType == GccToolChain::MinGW) { + static const auto tcChecker = [](const ToolChain *tc) { + return tc->targetAbi().osFlavor() == Abi::WindowsMSysFlavor; + }; + Toolchains result = autoDetectToolchains("g++", + DetectVariants::Yes, + Constants::CXX_LANGUAGE_ID, + Constants::MINGW_TOOLCHAIN_TYPEID, + detector, + toolchainConstructor(), + tcChecker); + result += autoDetectToolchains("gcc", + DetectVariants::Yes, + Constants::C_LANGUAGE_ID, + Constants::MINGW_TOOLCHAIN_TYPEID, + detector, + toolchainConstructor(), + tcChecker); + return result; + } + + if (m_subType == GccToolChain::Clang) { + Toolchains tcs; + Toolchains known = detector.alreadyKnown; + + tcs.append(autoDetectToolchains("clang++", + DetectVariants::Yes, + Constants::CXX_LANGUAGE_ID, + Constants::CLANG_TOOLCHAIN_TYPEID, + detector, + toolchainConstructor())); + tcs.append(autoDetectToolchains("clang", + DetectVariants::Yes, + Constants::C_LANGUAGE_ID, + Constants::CLANG_TOOLCHAIN_TYPEID, + detector, + toolchainConstructor())); + known.append(tcs); + + const FilePath compilerPath = Core::ICore::clangExecutable(CLANG_BINDIR); + if (!compilerPath.isEmpty()) { + const FilePath clang = compilerPath.parentDir().pathAppended("clang").withExecutableSuffix(); + tcs.append( + autoDetectToolchains(clang.toString(), + DetectVariants::No, + Constants::C_LANGUAGE_ID, + Constants::CLANG_TOOLCHAIN_TYPEID, + ToolchainDetector(known, detector.device, detector.searchPaths), + toolchainConstructor())); + } + + return tcs; + } + // GCC is almost never what you want on macOS, but it is by default found in /usr/bin if (HostOsInfo::isMacHost() && detector.device->type() == Constants::DESKTOP_DEVICE_TYPE) return {}; @@ -1237,6 +1307,53 @@ Toolchains GccToolChainFactory::autoDetect(const ToolchainDetector &detector) co Toolchains GccToolChainFactory::detectForImport(const ToolChainDescription &tcd) const { + if (m_subType == GccToolChain::LinuxIcc) { + const QString fileName = tcd.compilerPath.completeBaseName(); + if ((tcd.language == Constants::CXX_LANGUAGE_ID && fileName.startsWith("icpc")) || + (tcd.language == Constants::C_LANGUAGE_ID && fileName.startsWith("icc"))) { + return autoDetectToolChain(tcd, toolchainConstructor()); + } + return {}; + } + + if (m_subType == GccToolChain::MinGW) { + const QString fileName = tcd.compilerPath.completeBaseName(); + + const bool cCompiler = tcd.language == Constants::C_LANGUAGE_ID + && ((fileName.startsWith("gcc") || fileName.endsWith("gcc")) + || fileName == "cc"); + + const bool cxxCompiler = tcd.language == Constants::CXX_LANGUAGE_ID + && ((fileName.startsWith("g++") || fileName.endsWith("g++")) + || (fileName.startsWith("c++") || fileName.endsWith("c++"))); + + if (cCompiler || cxxCompiler) { + return autoDetectToolChain(tcd, toolchainConstructor(), [](const ToolChain *tc) { + return tc->targetAbi().osFlavor() == Abi::WindowsMSysFlavor; + }); + } + + return {}; + } + + if (m_subType == GccToolChain::Clang) { + const QString fileName = tcd.compilerPath.completeBaseName(); + const QString resolvedSymlinksFileName = tcd.compilerPath.resolveSymlinks().completeBaseName(); + + const bool isCCompiler = tcd.language == Constants::C_LANGUAGE_ID + && ((fileName.startsWith("clang") && !fileName.startsWith("clang++")) + || (fileName == "cc" && resolvedSymlinksFileName.contains("clang"))); + + const bool isCxxCompiler = tcd.language == Constants::CXX_LANGUAGE_ID + && (fileName.startsWith("clang++") + || (fileName == "c++" && resolvedSymlinksFileName.contains("clang"))); + + if (isCCompiler || isCxxCompiler) + return autoDetectToolChain(tcd, toolchainConstructor()); + + return {}; + } + const QString fileName = tcd.compilerPath.completeBaseName(); const QString resolvedSymlinksFileName = tcd.compilerPath.resolveSymlinks().completeBaseName(); @@ -1798,6 +1915,7 @@ QString GccToolChain::sysRoot() const ClangToolChainFactory::ClangToolChainFactory() { + m_subType = GccToolChain::Clang; setDisplayName(Tr::tr("Clang")); setSupportedToolChainType(Constants::CLANG_TOOLCHAIN_TYPEID); setSupportedLanguages({Constants::CXX_LANGUAGE_ID, Constants::C_LANGUAGE_ID}); @@ -1806,58 +1924,6 @@ ClangToolChainFactory::ClangToolChainFactory() }); } -Toolchains ClangToolChainFactory::autoDetect(const ToolchainDetector &detector) const -{ - Toolchains tcs; - Toolchains known = detector.alreadyKnown; - - tcs.append(autoDetectToolchains("clang++", - DetectVariants::Yes, - Constants::CXX_LANGUAGE_ID, - Constants::CLANG_TOOLCHAIN_TYPEID, - detector, - toolchainConstructor())); - tcs.append(autoDetectToolchains("clang", - DetectVariants::Yes, - Constants::C_LANGUAGE_ID, - Constants::CLANG_TOOLCHAIN_TYPEID, - detector, - toolchainConstructor())); - known.append(tcs); - - const FilePath compilerPath = Core::ICore::clangExecutable(CLANG_BINDIR); - if (!compilerPath.isEmpty()) { - const FilePath clang = compilerPath.parentDir().pathAppended("clang").withExecutableSuffix(); - tcs.append( - autoDetectToolchains(clang.toString(), - DetectVariants::No, - Constants::C_LANGUAGE_ID, - Constants::CLANG_TOOLCHAIN_TYPEID, - ToolchainDetector(known, detector.device, detector.searchPaths), - toolchainConstructor())); - } - - return tcs; -} - -Toolchains ClangToolChainFactory::detectForImport(const ToolChainDescription &tcd) const -{ - const QString fileName = tcd.compilerPath.completeBaseName(); - const QString resolvedSymlinksFileName = tcd.compilerPath.resolveSymlinks().completeBaseName(); - - const bool isCCompiler = tcd.language == Constants::C_LANGUAGE_ID - && ((fileName.startsWith("clang") && !fileName.startsWith("clang++")) - || (fileName == "cc" && resolvedSymlinksFileName.contains("clang"))); - - const bool isCxxCompiler = tcd.language == Constants::CXX_LANGUAGE_ID - && (fileName.startsWith("clang++") - || (fileName == "c++" && resolvedSymlinksFileName.contains("clang"))); - - if (isCCompiler || isCxxCompiler) { - return autoDetectToolChain(tcd, toolchainConstructor()); - } - return {}; -} void GccToolChainConfigWidget::updateParentToolChainComboBox() { @@ -1892,6 +1958,7 @@ void GccToolChainConfigWidget::updateParentToolChainComboBox() MingwToolChainFactory::MingwToolChainFactory() { + m_subType = GccToolChain::MinGW; setDisplayName(Tr::tr("MinGW")); setSupportedToolChainType(Constants::MINGW_TOOLCHAIN_TYPEID); setSupportedLanguages({Constants::CXX_LANGUAGE_ID, Constants::C_LANGUAGE_ID}); @@ -1900,55 +1967,13 @@ MingwToolChainFactory::MingwToolChainFactory() }); } -Toolchains MingwToolChainFactory::autoDetect(const ToolchainDetector &detector) const -{ - static const auto tcChecker = [](const ToolChain *tc) { - return tc->targetAbi().osFlavor() == Abi::WindowsMSysFlavor; - }; - Toolchains result = autoDetectToolchains("g++", - DetectVariants::Yes, - Constants::CXX_LANGUAGE_ID, - Constants::MINGW_TOOLCHAIN_TYPEID, - detector, - toolchainConstructor(), - tcChecker); - result += autoDetectToolchains("gcc", - DetectVariants::Yes, - Constants::C_LANGUAGE_ID, - Constants::MINGW_TOOLCHAIN_TYPEID, - detector, - toolchainConstructor(), - tcChecker); - return result; -} - -Toolchains MingwToolChainFactory::detectForImport(const ToolChainDescription &tcd) const -{ - const QString fileName = tcd.compilerPath.completeBaseName(); - - const bool cCompiler = tcd.language == Constants::C_LANGUAGE_ID - && ((fileName.startsWith("gcc") || fileName.endsWith("gcc")) - || fileName == "cc"); - - const bool cxxCompiler = tcd.language == Constants::CXX_LANGUAGE_ID - && ((fileName.startsWith("g++") || fileName.endsWith("g++")) - || (fileName.startsWith("c++") || fileName.endsWith("c++"))); - - if (cCompiler || cxxCompiler) { - return autoDetectToolChain(tcd, toolchainConstructor(), [](const ToolChain *tc) { - return tc->targetAbi().osFlavor() == Abi::WindowsMSysFlavor; - }); - } - - return {}; -} - // -------------------------------------------------------------------------- // LinuxIccToolChainFactory // -------------------------------------------------------------------------- LinuxIccToolChainFactory::LinuxIccToolChainFactory() { + m_subType = GccToolChain::LinuxIcc; setDisplayName(Tr::tr("ICC")); setSupportedToolChainType(Constants::LINUXICC_TOOLCHAIN_TYPEID); setSupportedLanguages({Constants::CXX_LANGUAGE_ID, Constants::C_LANGUAGE_ID}); @@ -1957,33 +1982,6 @@ LinuxIccToolChainFactory::LinuxIccToolChainFactory() }); } -Toolchains LinuxIccToolChainFactory::autoDetect(const ToolchainDetector &detector) const -{ - Toolchains result = autoDetectToolchains("icpc", - DetectVariants::No, - Constants::CXX_LANGUAGE_ID, - Constants::LINUXICC_TOOLCHAIN_TYPEID, - detector, - toolchainConstructor()); - result += autoDetectToolchains("icc", - DetectVariants::Yes, - Constants::C_LANGUAGE_ID, - Constants::LINUXICC_TOOLCHAIN_TYPEID, - detector, - toolchainConstructor()); - return result; -} - -Toolchains LinuxIccToolChainFactory::detectForImport(const ToolChainDescription &tcd) const -{ - const QString fileName = tcd.compilerPath.completeBaseName(); - if ((tcd.language == Constants::CXX_LANGUAGE_ID && fileName.startsWith("icpc")) || - (tcd.language == Constants::C_LANGUAGE_ID && fileName.startsWith("icc"))) { - return autoDetectToolChain(tcd, toolchainConstructor()); - } - return {}; -} - GccToolChain::WarningFlagAdder::WarningFlagAdder(const QString &flag, WarningFlags &flags) : m_flags(flags) { diff --git a/src/plugins/projectexplorer/gcctoolchain.h b/src/plugins/projectexplorer/gcctoolchain.h index 9607f0a8ef8..87a2beaf62a 100644 --- a/src/plugins/projectexplorer/gcctoolchain.h +++ b/src/plugins/projectexplorer/gcctoolchain.h @@ -198,10 +198,12 @@ class GccToolChainFactory : public ToolChainFactory public: GccToolChainFactory(); - Toolchains autoDetect(const ToolchainDetector &detector) const override; - Toolchains detectForImport(const ToolChainDescription &tcd) const override; + Toolchains autoDetect(const ToolchainDetector &detector) const final; + Toolchains detectForImport(const ToolChainDescription &tcd) const final; protected: + GccToolChain::SubType m_subType = GccToolChain::RealGcc; + enum class DetectVariants { Yes, No }; using ToolchainChecker = std::function; static Toolchains autoDetectToolchains(const QString &compilerName, @@ -220,27 +222,18 @@ class ClangToolChainFactory : public GccToolChainFactory { public: ClangToolChainFactory(); - - Toolchains autoDetect(const ToolchainDetector &detector) const final; - Toolchains detectForImport(const ToolChainDescription &tcd) const final; }; class MingwToolChainFactory : public GccToolChainFactory { public: MingwToolChainFactory(); - - Toolchains autoDetect(const ToolchainDetector &detector) const final; - Toolchains detectForImport(const ToolChainDescription &tcd) const final; }; class LinuxIccToolChainFactory : public GccToolChainFactory { public: LinuxIccToolChainFactory(); - - Toolchains autoDetect(const ToolchainDetector &detector) const final; - Toolchains detectForImport(const ToolChainDescription &tcd) const final; }; } // namespace Internal From 359f6e54b82d8ae89bb5c74a0b1e53db1145cf3a Mon Sep 17 00:00:00 2001 From: hjk Date: Mon, 25 Sep 2023 17:09:21 +0200 Subject: [PATCH 07/27] ProjectExplorer: Reduce scope of projectexploererconstants include plus a bit of cosmetics. Change-Id: I744b28ebf4285bd61b948988a0192632f5b360a8 Reviewed-by: Christian Kandeler --- src/plugins/android/androidplugin.cpp | 1 + src/plugins/android/androidtoolchain.cpp | 1 + src/plugins/projectexplorer/gcctoolchain.cpp | 1 + src/plugins/projectexplorer/gcctoolchain.h | 2 -- src/plugins/projectexplorer/projectexplorer.cpp | 1 + src/plugins/webassembly/webassemblysettings.cpp | 3 ++- 6 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/plugins/android/androidplugin.cpp b/src/plugins/android/androidplugin.cpp index 2ed71e194b4..9eeee4dad29 100644 --- a/src/plugins/android/androidplugin.cpp +++ b/src/plugins/android/androidplugin.cpp @@ -44,6 +44,7 @@ #include #include #include +#include #include #include diff --git a/src/plugins/android/androidtoolchain.cpp b/src/plugins/android/androidtoolchain.cpp index b472498a806..26ca46be2a5 100644 --- a/src/plugins/android/androidtoolchain.cpp +++ b/src/plugins/android/androidtoolchain.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include diff --git a/src/plugins/projectexplorer/gcctoolchain.cpp b/src/plugins/projectexplorer/gcctoolchain.cpp index 8b9610ce0c6..084fd9c8f33 100644 --- a/src/plugins/projectexplorer/gcctoolchain.cpp +++ b/src/plugins/projectexplorer/gcctoolchain.cpp @@ -8,6 +8,7 @@ #include "devicesupport/idevice.h" #include "gccparser.h" #include "linuxiccparser.h" +#include "projectexplorerconstants.h" #include "projectexplorertr.h" #include "projectmacro.h" #include "toolchainconfigwidget.h" diff --git a/src/plugins/projectexplorer/gcctoolchain.h b/src/plugins/projectexplorer/gcctoolchain.h index 87a2beaf62a..e76398621d6 100644 --- a/src/plugins/projectexplorer/gcctoolchain.h +++ b/src/plugins/projectexplorer/gcctoolchain.h @@ -5,7 +5,6 @@ #include "projectexplorer_export.h" -#include "projectexplorerconstants.h" #include "toolchain.h" #include "abi.h" #include "headerpath.h" @@ -30,7 +29,6 @@ const QStringList gccPredefinedMacrosOptions(Utils::Id languageId); // GccToolChain // -------------------------------------------------------------------------- - class PROJECTEXPLORER_EXPORT GccToolChain : public ToolChain { public: diff --git a/src/plugins/projectexplorer/projectexplorer.cpp b/src/plugins/projectexplorer/projectexplorer.cpp index c1f90598218..3b199217212 100644 --- a/src/plugins/projectexplorer/projectexplorer.cpp +++ b/src/plugins/projectexplorer/projectexplorer.cpp @@ -56,6 +56,7 @@ #include "processstep.h" #include "project.h" #include "projectcommentssettings.h" +#include "projectexplorerconstants.h" #include "projectexplorericons.h" #include "projectexplorersettings.h" #include "projectexplorertr.h" diff --git a/src/plugins/webassembly/webassemblysettings.cpp b/src/plugins/webassembly/webassemblysettings.cpp index e6ad931ccb9..88a7cc22130 100644 --- a/src/plugins/webassembly/webassemblysettings.cpp +++ b/src/plugins/webassembly/webassemblysettings.cpp @@ -12,6 +12,8 @@ #include #include +#include + #include #include #include @@ -19,7 +21,6 @@ #include #include -#include #include #include From 6ff28649c2f596110486978c593e9cefe12a095b Mon Sep 17 00:00:00 2001 From: David Schulz Date: Thu, 21 Sep 2023 12:52:01 +0200 Subject: [PATCH 08/27] ProjectExplorer: speed up clang-cl toolchain detection Do not guess the extension when we already it's clang-cl.exe Change-Id: Ifd0d069f466d4b01bc3cfadc456ea6c97ea30743 Reviewed-by: Christian Stenger Reviewed-by: --- src/plugins/projectexplorer/msvctoolchain.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/plugins/projectexplorer/msvctoolchain.cpp b/src/plugins/projectexplorer/msvctoolchain.cpp index c6f435a9f4f..dd5181990de 100644 --- a/src/plugins/projectexplorer/msvctoolchain.cpp +++ b/src/plugins/projectexplorer/msvctoolchain.cpp @@ -2057,7 +2057,7 @@ Toolchains ClangClToolChainFactory::autoDetect(const ToolchainDetector &detector } const Utils::Environment systemEnvironment = Utils::Environment::systemEnvironment(); - const Utils::FilePath clangClPath = systemEnvironment.searchInPath("clang-cl"); + const Utils::FilePath clangClPath = systemEnvironment.searchInPath("clang-cl.exe"); if (!clangClPath.isEmpty()) results.append(detectClangClToolChainInPath(clangClPath, known, "")); From 8ebcd73e130eb423736c311a3dd00fcc502fbf23 Mon Sep 17 00:00:00 2001 From: Christian Stenger Date: Fri, 25 Aug 2023 16:06:18 +0200 Subject: [PATCH 09/27] AutoTest: Provide a couple of test related snippets Unfortunately there is no easy way to enhance existing providers based on conditions or by extending the snippet collection with plugin internal paths. So, add snippets to known snippet providers. Change-Id: I55da59389b5dc28aa27bb2974699aa4674c0bbf2 Reviewed-by: David Schulz Reviewed-by: --- share/qtcreator/snippets/test.xml | 58 +++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 share/qtcreator/snippets/test.xml diff --git a/share/qtcreator/snippets/test.xml b/share/qtcreator/snippets/test.xml new file mode 100644 index 00000000000..4c7f8d1c39b --- /dev/null +++ b/share/qtcreator/snippets/test.xml @@ -0,0 +1,58 @@ + + +TestCase { + name: "$TestCaseName$" + + function test_$TestFunctionName$() { + $$ + } +} + +TEST($TestSuite$, $TestName$) +{ + $$ +} + +TEST_F($TestFixtureName$, $TestName$) +{ + $$ +} + +INSTANTIATE_TEST_SUITE_P($InstantiationName$, $TestFixtureName$, $ParameterGenerator$); + +TEST_P($TestFixtureName$, $TestName$) +{ + $$ +} + +BOOST_AUTO_TEST_CASE($TestName$) +{ + $$ +} + +BOOST_AUTO_TEST_SUITE($SuiteName$) +BOOST_AUTO_TEST_CASE($TestName$) +{ + $$ +} +BOOST_AUTO_TEST_SUITE_END() + +TEST_CASE("$TestCaseName$") { + SECTION("$SectionName$") { + $$ + } +} + +SCENARIO("$ScenarioName$") { + GIVEN("$Initial$") { + $$ + WHEN("$Condition$") { + $$ + THEN("$Expectation$") { + $$ + } + } + } +} + + From e85f750debf45237613be4da04b9b4a80effc9be Mon Sep 17 00:00:00 2001 From: hjk Date: Tue, 26 Sep 2023 08:30:56 +0200 Subject: [PATCH 10/27] ProjectExplorer: Remove a few toolchain friends Change-Id: Ibc665d3ce0c9e1d65a5eee5dcc31e9c3369fd331 Reviewed-by: David Schulz --- src/plugins/projectexplorer/gcctoolchain.h | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/plugins/projectexplorer/gcctoolchain.h b/src/plugins/projectexplorer/gcctoolchain.h index e76398621d6..7694cc524c4 100644 --- a/src/plugins/projectexplorer/gcctoolchain.h +++ b/src/plugins/projectexplorer/gcctoolchain.h @@ -16,11 +16,8 @@ namespace ProjectExplorer { namespace Internal { -class ClangToolChainFactory; class GccToolChainConfigWidget; class GccToolChainFactory; -class MingwToolChainFactory; -class LinuxIccToolChainFactory; const QStringList gccPredefinedMacrosOptions(Utils::Id languageId); } @@ -172,9 +169,6 @@ private: friend class Internal::GccToolChainConfigWidget; friend class Internal::GccToolChainFactory; - friend class Internal::LinuxIccToolChainFactory; - friend class Internal::MingwToolChainFactory; - friend class Internal::ClangToolChainFactory; friend class ToolChainFactory; // "resolved" on macOS from /usr/bin/clang(++) etc to /usr/bin/clang(++) From d7ef2f816cd97fce263e3f42a84a1155a41eedc0 Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Tue, 26 Sep 2023 07:25:25 +0200 Subject: [PATCH 11/27] CompilerExplorer: Fix saving Change-Id: I7f6770170c76d636fa2d3631d9ff462da9e227bd Reviewed-by: Reviewed-by: David Schulz --- .../compilerexplorer/compilerexplorereditor.cpp | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/plugins/compilerexplorer/compilerexplorereditor.cpp b/src/plugins/compilerexplorer/compilerexplorereditor.cpp index 719b61299fc..b02b3585ace 100644 --- a/src/plugins/compilerexplorer/compilerexplorereditor.cpp +++ b/src/plugins/compilerexplorer/compilerexplorereditor.cpp @@ -107,8 +107,11 @@ JsonSettingsDocument::JsonSettingsDocument(QUndoStack *undoStack) { setId(Constants::CE_EDITOR_ID); setMimeType("application/compiler-explorer"); - connect(&m_ceSettings, &CompilerExplorerSettings::changed, this, [this] { emit changed(); }); - m_ceSettings.setAutoApply(true); + connect(&m_ceSettings, &CompilerExplorerSettings::changed, this, [this] { + emit changed(); + emit contentsChanged(); + }); + m_ceSettings.setAutoApply(false); m_ceSettings.setUndoStack(undoStack); } @@ -157,8 +160,10 @@ bool JsonSettingsDocument::saveImpl(QString *errorString, const FilePath &newFil Utils::FilePath path = newFilePath.isEmpty() ? filePath() : newFilePath; - if (!newFilePath.isEmpty() && !autoSave) + if (!newFilePath.isEmpty() && !autoSave) { + setPreferredDisplayName({}); setFilePath(newFilePath); + } auto result = path.writeFileContents(jsonFromStore(store)); if (!result && errorString) { @@ -182,6 +187,8 @@ bool JsonSettingsDocument::setContents(const QByteArray &contents) m_ceSettings.fromMap(*result); emit settingsChanged(); + emit changed(); + emit contentsChanged(); return true; } From a43191497da10a874a5d9274dbaa50ce3f3d3662 Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Tue, 26 Sep 2023 08:38:09 +0200 Subject: [PATCH 12/27] Utils: Fix StringSelectionAspect Previously the undo state was not updated when the value was set from the outside before the gui model was setup. Change-Id: I380916f888edd120f512089bdb94762977c11978 Reviewed-by: hjk --- src/libs/utils/aspects.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/libs/utils/aspects.cpp b/src/libs/utils/aspects.cpp index 05b4d8796bf..d9bf38688ac 100644 --- a/src/libs/utils/aspects.cpp +++ b/src/libs/utils/aspects.cpp @@ -3286,8 +3286,10 @@ QStandardItem *StringSelectionAspect::itemById(const QString &id) void StringSelectionAspect::bufferToGui() { - if (!m_model) + if (!m_model) { + m_undoable.setSilently(m_buffer); return; + } auto selected = itemById(m_buffer); if (selected) { @@ -3302,8 +3304,10 @@ void StringSelectionAspect::bufferToGui() m_selectionModel->setCurrentIndex(m_model->item(0)->index(), QItemSelectionModel::SelectionFlag::ClearAndSelect); } else { + m_undoable.setSilently(m_buffer); m_selectionModel->setCurrentIndex(QModelIndex(), QItemSelectionModel::SelectionFlag::Clear); } + handleGuiChanged(); } From 658e2a3197362e03d5473c2dae014cf10e568621 Mon Sep 17 00:00:00 2001 From: Christian Stenger Date: Tue, 26 Sep 2023 07:35:01 +0200 Subject: [PATCH 13/27] CMakePM: Fix build with Qt6.2 Change-Id: Iac128851da0aa7895d5c2352be550702fbc1e7f9 Reviewed-by: Cristian Adam --- .../cmakeprojectmanager/cmakefilecompletionassist.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/plugins/cmakeprojectmanager/cmakefilecompletionassist.cpp b/src/plugins/cmakeprojectmanager/cmakefilecompletionassist.cpp index 339a11b64ae..84902f9d495 100644 --- a/src/plugins/cmakeprojectmanager/cmakefilecompletionassist.cpp +++ b/src/plugins/cmakeprojectmanager/cmakefilecompletionassist.cpp @@ -176,11 +176,11 @@ QList generateList(const QMap }; QList list; - for (const auto &[text, helpFile] : words.asKeyValueRange()) { + for (auto it = words.cbegin(); it != words.cend(); ++it) { MarkDownAssitProposalItem *item = new MarkDownAssitProposalItem(); - item->setText(text); - if (!helpFile.isEmpty()) - item->setDetail(readFirstParagraphs(text, helpFile)); + item->setText(it.key()); + if (!it.value().isEmpty()) + item->setDetail(readFirstParagraphs(it.key(), it.value())); item->setIcon(icon); list << item; }; From 25c7390d0a6600a0ca31593fc3a78cd82b5800ef Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Fri, 22 Sep 2023 14:14:45 +0200 Subject: [PATCH 14/27] ClangCodeModel: Start fallback clangd on demand E.g. when a non-project source file is opened. Fixes: QTCREATORBUG-29576 Change-Id: Ia99346a7a1016c4c7dcdb41ad6c8dbbc85ed95ff Reviewed-by: Qt CI Bot Reviewed-by: Reviewed-by: David Schulz Reviewed-by: Eike Ziller --- .../clangcodemodel/clangmodelmanagersupport.cpp | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/plugins/clangcodemodel/clangmodelmanagersupport.cpp b/src/plugins/clangcodemodel/clangmodelmanagersupport.cpp index e1bd9114717..b201d5a364c 100644 --- a/src/plugins/clangcodemodel/clangmodelmanagersupport.cpp +++ b/src/plugins/clangcodemodel/clangmodelmanagersupport.cpp @@ -231,10 +231,10 @@ ClangModelManagerSupport::ClangModelManagerSupport() connect(modelManager, &CppModelManager::fallbackProjectPartUpdated, this, [this] { if (sessionModeEnabled()) return; - if (ClangdClient * const fallbackClient = clientForProject(nullptr)) { + if (ClangdClient * const fallbackClient = clientForProject(nullptr)) LanguageClientManager::shutdownClient(fallbackClient); + if (ClangdSettings::instance().useClangd()) claimNonProjectSources(new ClangdClient(nullptr, {})); - } }); auto projectManager = ProjectManager::instance(); @@ -251,9 +251,6 @@ ClangModelManagerSupport::ClangModelManagerSupport() connect(&ClangdSettings::instance(), &ClangdSettings::changed, this, &ClangModelManagerSupport::onClangdSettingsChanged); - if (ClangdSettings::instance().useClangd()) - new ClangdClient(nullptr, {}); - new ClangdQuickFixFactory(); // memory managed by CppEditor::g_cppQuickFixFactories } @@ -777,8 +774,13 @@ void ClangModelManagerSupport::onEditorOpened(IEditor *editor) project = nullptr; else if (!project && ProjectFile::isHeader(document->filePath())) project = fallbackProject(); - if (ClangdClient * const client = clientForProject(project)) - LanguageClientManager::openDocumentWithClient(textDocument, client); + ClangdClient *client = clientForProject(project); + if (!client) { + if (project) + return; + client = new ClangdClient(nullptr, {}); + } + LanguageClientManager::openDocumentWithClient(textDocument, client); } } From 873a719174d2cc31d550c2c87bc7a6a979a56012 Mon Sep 17 00:00:00 2001 From: Christian Kandeler Date: Mon, 25 Sep 2023 16:00:02 +0200 Subject: [PATCH 15/27] QmakeProjectManager: Speed up project importer Change-Id: I0cc5661f76c1d8f9182473d5f8da18452e3f85bf Reviewed-by: Reviewed-by: Qt CI Bot Reviewed-by: Christian Stenger --- src/plugins/qmakeprojectmanager/qmakeprojectimporter.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/plugins/qmakeprojectmanager/qmakeprojectimporter.cpp b/src/plugins/qmakeprojectmanager/qmakeprojectimporter.cpp index e159f5dd6dc..832fb1a6809 100644 --- a/src/plugins/qmakeprojectmanager/qmakeprojectimporter.cpp +++ b/src/plugins/qmakeprojectmanager/qmakeprojectimporter.cpp @@ -27,9 +27,9 @@ #include #include -#include -#include #include +#include +#include #include @@ -63,11 +63,14 @@ FilePaths QmakeProjectImporter::importCandidates() { FilePaths candidates{projectFilePath().absolutePath()}; + QSet seenBaseDirs; for (Kit *k : KitManager::kits()) { const FilePath sbdir = QmakeBuildConfiguration::shadowBuildDirectory (projectFilePath(), k, QString(), BuildConfiguration::Unknown); const FilePath baseDir = sbdir.absolutePath(); + if (!Utils::insert(seenBaseDirs, baseDir)) + continue; for (const FilePath &path : baseDir.dirEntries(QDir::Dirs | QDir::NoDotAndDotDot)) { if (!candidates.contains(path)) candidates << path; From 61048fa7376ea4a3f4be0b319ad768d54319fec8 Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Tue, 26 Sep 2023 09:57:35 +0200 Subject: [PATCH 16/27] Utils: Add AspectList::clear() Change-Id: Ic3e90bc76d271c1bb3b84e545fae5ba1c7a10468 Reviewed-by: hjk --- src/libs/utils/aspects.cpp | 15 +++++++++++++++ src/libs/utils/aspects.h | 1 + 2 files changed, 16 insertions(+) diff --git a/src/libs/utils/aspects.cpp b/src/libs/utils/aspects.cpp index d9bf38688ac..04cf8b786d0 100644 --- a/src/libs/utils/aspects.cpp +++ b/src/libs/utils/aspects.cpp @@ -3154,6 +3154,21 @@ void AspectList::removeItem(const std::shared_ptr &item) actualRemoveItem(item); } +void AspectList::clear() +{ + if (undoStack()) { + undoStack()->beginMacro("Clear"); + + for (auto item : volatileItems()) + undoStack()->push(new RemoveItemCommand(this, item)); + + undoStack()->endMacro(); + } else { + for (auto item : volatileItems()) + actualRemoveItem(item); + } +} + void AspectList::apply() { d->items = d->volatileItems; diff --git a/src/libs/utils/aspects.h b/src/libs/utils/aspects.h index ccdaadcc631..d5d47a79d7e 100644 --- a/src/libs/utils/aspects.h +++ b/src/libs/utils/aspects.h @@ -1031,6 +1031,7 @@ public: void removeItem(const std::shared_ptr &item); void actualRemoveItem(const std::shared_ptr &item); + void clear(); void apply() override; From 4d2f3e8b01da7ceacfc4c10b25dc40e5211f3bff Mon Sep 17 00:00:00 2001 From: hjk Date: Tue, 26 Sep 2023 10:25:16 +0200 Subject: [PATCH 17/27] ProjectExplorer: Merge GccToolChainFactories further This replaces the four classes from the GccToolChainFactories hierarchy by a single (parametrized) GccToolChainFactory, but makes the "RealGcc" one responsible for all autodetection. This is a hack to move closer to a "scan only once" setup, and temporarily necessary as there is currently one factory creates one type of toolchain, so we need four factories for the current four gcc-ish toolchain types. Change-Id: Icbecb1be6e89cf5efad76baf92ef38ac63be074f Reviewed-by: Christian Kandeler --- src/plugins/projectexplorer/gcctoolchain.cpp | 360 +++++++++--------- src/plugins/projectexplorer/gcctoolchain.h | 28 +- .../projectexplorer/projectexplorer.cpp | 9 +- src/plugins/projectexplorer/toolchain.cpp | 3 +- 4 files changed, 190 insertions(+), 210 deletions(-) diff --git a/src/plugins/projectexplorer/gcctoolchain.cpp b/src/plugins/projectexplorer/gcctoolchain.cpp index 084fd9c8f33..ff5387d63a3 100644 --- a/src/plugins/projectexplorer/gcctoolchain.cpp +++ b/src/plugins/projectexplorer/gcctoolchain.cpp @@ -1198,182 +1198,228 @@ static Utils::FilePaths renesasRl78SearchPathsFromRegistry() return searchPaths; } -GccToolChainFactory::GccToolChainFactory() +static ToolChain *constructRealGccToolchain() { - setDisplayName(Tr::tr("GCC")); - setSupportedToolChainType(Constants::GCC_TOOLCHAIN_TYPEID); + return new GccToolChain(Constants::GCC_TOOLCHAIN_TYPEID, GccToolChain::RealGcc); +} + +static ToolChain *constructClangToolchain() +{ + return new GccToolChain(Constants::CLANG_TOOLCHAIN_TYPEID, GccToolChain::Clang); +} + +static ToolChain *constructMinGWToolchain() +{ + return new GccToolChain(Constants::MINGW_TOOLCHAIN_TYPEID, GccToolChain::MinGW); +} + +static ToolChain *constructLinuxIccToolchain() +{ + return new GccToolChain(Constants::LINUXICC_TOOLCHAIN_TYPEID, GccToolChain::LinuxIcc); +} + +GccToolChainFactory::GccToolChainFactory(GccToolChain::SubType subType) + : m_autoDetecting(subType == GccToolChain::RealGcc) +{ + switch (subType) { + case GccToolChain::RealGcc: + setDisplayName(Tr::tr("GCC")); + setSupportedToolChainType(Constants::GCC_TOOLCHAIN_TYPEID); + setToolchainConstructor(&constructRealGccToolchain); + break; + case GccToolChain::Clang: + setDisplayName(Tr::tr("Clang")); + setSupportedToolChainType(Constants::CLANG_TOOLCHAIN_TYPEID); + setToolchainConstructor(&constructClangToolchain); + break; + case GccToolChain::MinGW: + setDisplayName(Tr::tr("MinGW")); + setSupportedToolChainType(Constants::MINGW_TOOLCHAIN_TYPEID); + setToolchainConstructor(&constructMinGWToolchain); + break; + case GccToolChain::LinuxIcc: + setDisplayName(Tr::tr("ICC")); + setSupportedToolChainType(Constants::LINUXICC_TOOLCHAIN_TYPEID); + setToolchainConstructor(&constructLinuxIccToolchain); + break; + } setSupportedLanguages({Constants::C_LANGUAGE_ID, Constants::CXX_LANGUAGE_ID}); - setToolchainConstructor([] { return new GccToolChain(Constants::GCC_TOOLCHAIN_TYPEID); }); setUserCreatable(true); } Toolchains GccToolChainFactory::autoDetect(const ToolchainDetector &detector) const { - if (m_subType == GccToolChain::LinuxIcc) { - Toolchains result = autoDetectToolchains("icpc", - DetectVariants::No, - Constants::CXX_LANGUAGE_ID, - Constants::LINUXICC_TOOLCHAIN_TYPEID, - detector, - toolchainConstructor()); - result += autoDetectToolchains("icc", - DetectVariants::Yes, - Constants::C_LANGUAGE_ID, - Constants::LINUXICC_TOOLCHAIN_TYPEID, - detector, - toolchainConstructor()); + Toolchains result; + + // Do all autodetection in th 'RealGcc' case, and none in the others. + if (!m_autoDetecting) return result; - } - if (m_subType == GccToolChain::MinGW) { - static const auto tcChecker = [](const ToolChain *tc) { - return tc->targetAbi().osFlavor() == Abi::WindowsMSysFlavor; - }; - Toolchains result = autoDetectToolchains("g++", - DetectVariants::Yes, - Constants::CXX_LANGUAGE_ID, - Constants::MINGW_TOOLCHAIN_TYPEID, - detector, - toolchainConstructor(), - tcChecker); - result += autoDetectToolchains("gcc", - DetectVariants::Yes, - Constants::C_LANGUAGE_ID, - Constants::MINGW_TOOLCHAIN_TYPEID, - detector, - toolchainConstructor(), - tcChecker); - return result; - } + // Linux ICC - if (m_subType == GccToolChain::Clang) { - Toolchains tcs; - Toolchains known = detector.alreadyKnown; + result += autoDetectToolchains("icpc", + DetectVariants::No, + Constants::CXX_LANGUAGE_ID, + Constants::LINUXICC_TOOLCHAIN_TYPEID, + detector, + &constructLinuxIccToolchain); + result += autoDetectToolchains("icc", + DetectVariants::Yes, + Constants::C_LANGUAGE_ID, + Constants::LINUXICC_TOOLCHAIN_TYPEID, + detector, + &constructLinuxIccToolchain); - tcs.append(autoDetectToolchains("clang++", - DetectVariants::Yes, - Constants::CXX_LANGUAGE_ID, - Constants::CLANG_TOOLCHAIN_TYPEID, - detector, - toolchainConstructor())); - tcs.append(autoDetectToolchains("clang", - DetectVariants::Yes, - Constants::C_LANGUAGE_ID, - Constants::CLANG_TOOLCHAIN_TYPEID, - detector, - toolchainConstructor())); - known.append(tcs); + // MinGW - const FilePath compilerPath = Core::ICore::clangExecutable(CLANG_BINDIR); - if (!compilerPath.isEmpty()) { - const FilePath clang = compilerPath.parentDir().pathAppended("clang").withExecutableSuffix(); - tcs.append( - autoDetectToolchains(clang.toString(), - DetectVariants::No, - Constants::C_LANGUAGE_ID, - Constants::CLANG_TOOLCHAIN_TYPEID, - ToolchainDetector(known, detector.device, detector.searchPaths), - toolchainConstructor())); - } + static const auto tcChecker = [](const ToolChain *tc) { + return tc->targetAbi().osFlavor() == Abi::WindowsMSysFlavor; + }; + result += autoDetectToolchains("g++", + DetectVariants::Yes, + Constants::CXX_LANGUAGE_ID, + Constants::MINGW_TOOLCHAIN_TYPEID, + detector, + &constructMinGWToolchain, + tcChecker); + result += autoDetectToolchains("gcc", + DetectVariants::Yes, + Constants::C_LANGUAGE_ID, + Constants::MINGW_TOOLCHAIN_TYPEID, + detector, + &constructMinGWToolchain, + tcChecker); - return tcs; - } - - // GCC is almost never what you want on macOS, but it is by default found in /usr/bin - if (HostOsInfo::isMacHost() && detector.device->type() == Constants::DESKTOP_DEVICE_TYPE) - return {}; + // Clang Toolchains tcs; - static const auto tcChecker = [](const ToolChain *tc) { - return tc->targetAbi().osFlavor() != Abi::WindowsMSysFlavor - && tc->compilerCommand().fileName() != "c89-gcc" - && tc->compilerCommand().fileName() != "c99-gcc"; - }; - tcs.append(autoDetectToolchains("g++", + Toolchains known = detector.alreadyKnown; + + tcs.append(autoDetectToolchains("clang++", DetectVariants::Yes, Constants::CXX_LANGUAGE_ID, - Constants::GCC_TOOLCHAIN_TYPEID, + Constants::CLANG_TOOLCHAIN_TYPEID, detector, - toolchainConstructor(), - tcChecker)); - tcs.append(autoDetectToolchains("gcc", + &constructClangToolchain)); + tcs.append(autoDetectToolchains("clang", DetectVariants::Yes, Constants::C_LANGUAGE_ID, - Constants::GCC_TOOLCHAIN_TYPEID, + Constants::CLANG_TOOLCHAIN_TYPEID, detector, - toolchainConstructor(), - tcChecker)); - return tcs; + &constructClangToolchain)); + known.append(tcs); + + const FilePath compilerPath = Core::ICore::clangExecutable(CLANG_BINDIR); + if (!compilerPath.isEmpty()) { + const FilePath clang = compilerPath.parentDir().pathAppended("clang").withExecutableSuffix(); + tcs.append( + autoDetectToolchains(clang.toString(), + DetectVariants::No, + Constants::C_LANGUAGE_ID, + Constants::CLANG_TOOLCHAIN_TYPEID, + ToolchainDetector(known, detector.device, detector.searchPaths), + &constructClangToolchain)); + } + + result += tcs; + + // GCC + + // Gcc is almost never what you want on macOS, but it is by default found in /usr/bin + if (!HostOsInfo::isMacHost() || detector.device->type() != Constants::DESKTOP_DEVICE_TYPE) { + + Toolchains tcs; + static const auto tcChecker = [](const ToolChain *tc) { + return tc->targetAbi().osFlavor() != Abi::WindowsMSysFlavor + && tc->compilerCommand().fileName() != "c89-gcc" + && tc->compilerCommand().fileName() != "c99-gcc"; + }; + tcs.append(autoDetectToolchains("g++", + DetectVariants::Yes, + Constants::CXX_LANGUAGE_ID, + Constants::GCC_TOOLCHAIN_TYPEID, + detector, + &constructRealGccToolchain, + tcChecker)); + tcs.append(autoDetectToolchains("gcc", + DetectVariants::Yes, + Constants::C_LANGUAGE_ID, + Constants::GCC_TOOLCHAIN_TYPEID, + detector, + &constructRealGccToolchain, + tcChecker)); + result += tcs; + } + + return result; } Toolchains GccToolChainFactory::detectForImport(const ToolChainDescription &tcd) const { - if (m_subType == GccToolChain::LinuxIcc) { - const QString fileName = tcd.compilerPath.completeBaseName(); - if ((tcd.language == Constants::CXX_LANGUAGE_ID && fileName.startsWith("icpc")) || - (tcd.language == Constants::C_LANGUAGE_ID && fileName.startsWith("icc"))) { - return autoDetectToolChain(tcd, toolchainConstructor()); - } - return {}; - } + Toolchains result; - if (m_subType == GccToolChain::MinGW) { - const QString fileName = tcd.compilerPath.completeBaseName(); - - const bool cCompiler = tcd.language == Constants::C_LANGUAGE_ID - && ((fileName.startsWith("gcc") || fileName.endsWith("gcc")) - || fileName == "cc"); - - const bool cxxCompiler = tcd.language == Constants::CXX_LANGUAGE_ID - && ((fileName.startsWith("g++") || fileName.endsWith("g++")) - || (fileName.startsWith("c++") || fileName.endsWith("c++"))); - - if (cCompiler || cxxCompiler) { - return autoDetectToolChain(tcd, toolchainConstructor(), [](const ToolChain *tc) { - return tc->targetAbi().osFlavor() == Abi::WindowsMSysFlavor; - }); - } - - return {}; - } - - if (m_subType == GccToolChain::Clang) { - const QString fileName = tcd.compilerPath.completeBaseName(); - const QString resolvedSymlinksFileName = tcd.compilerPath.resolveSymlinks().completeBaseName(); - - const bool isCCompiler = tcd.language == Constants::C_LANGUAGE_ID - && ((fileName.startsWith("clang") && !fileName.startsWith("clang++")) - || (fileName == "cc" && resolvedSymlinksFileName.contains("clang"))); - - const bool isCxxCompiler = tcd.language == Constants::CXX_LANGUAGE_ID - && (fileName.startsWith("clang++") - || (fileName == "c++" && resolvedSymlinksFileName.contains("clang"))); - - if (isCCompiler || isCxxCompiler) - return autoDetectToolChain(tcd, toolchainConstructor()); - - return {}; - } + // Do all autodetection in th 'RealGcc' case, and none in the others. + if (!m_autoDetecting) + return result; const QString fileName = tcd.compilerPath.completeBaseName(); const QString resolvedSymlinksFileName = tcd.compilerPath.resolveSymlinks().completeBaseName(); - const bool isCCompiler = tcd.language == Constants::C_LANGUAGE_ID + // Linux ICC + + if ((tcd.language == Constants::CXX_LANGUAGE_ID && fileName.startsWith("icpc")) || + (tcd.language == Constants::C_LANGUAGE_ID && fileName.startsWith("icc"))) { + result += autoDetectToolChain(tcd, &constructLinuxIccToolchain); + } + + // MingW + + const bool cCompiler = tcd.language == Constants::C_LANGUAGE_ID + && ((fileName.startsWith("gcc") || fileName.endsWith("gcc")) + || fileName == "cc"); + + const bool cxxCompiler = tcd.language == Constants::CXX_LANGUAGE_ID + && ((fileName.startsWith("g++") || fileName.endsWith("g++")) + || (fileName.startsWith("c++") || fileName.endsWith("c++"))); + + if (cCompiler || cxxCompiler) { + result += autoDetectToolChain(tcd, &constructMinGWToolchain, [](const ToolChain *tc) { + return tc->targetAbi().osFlavor() == Abi::WindowsMSysFlavor; + }); + } + + // Clang + + bool isCCompiler = tcd.language == Constants::C_LANGUAGE_ID + && ((fileName.startsWith("clang") && !fileName.startsWith("clang++")) + || (fileName == "cc" && resolvedSymlinksFileName.contains("clang"))); + + bool isCxxCompiler = tcd.language == Constants::CXX_LANGUAGE_ID + && (fileName.startsWith("clang++") + || (fileName == "c++" && resolvedSymlinksFileName.contains("clang"))); + + if (isCCompiler || isCxxCompiler) + result += autoDetectToolChain(tcd, &constructClangToolchain); + + // GCC + + isCCompiler = tcd.language == Constants::C_LANGUAGE_ID && (fileName.startsWith("gcc") || fileName.endsWith("gcc") || (fileName == "cc" && !resolvedSymlinksFileName.contains("clang"))); - const bool isCxxCompiler = tcd.language == Constants::CXX_LANGUAGE_ID + isCxxCompiler = tcd.language == Constants::CXX_LANGUAGE_ID && (fileName.startsWith("g++") || fileName.endsWith("g++") || (fileName == "c++" && !resolvedSymlinksFileName.contains("clang"))); if (isCCompiler || isCxxCompiler) { - return autoDetectToolChain(tcd, toolchainConstructor(), [](const ToolChain *tc) { + result += autoDetectToolChain(tcd, &constructRealGccToolchain, [](const ToolChain *tc) { return tc->targetAbi().osFlavor() != Abi::WindowsMSysFlavor; }); } - return {}; + + return result; } static FilePaths findCompilerCandidates(const ToolchainDetector &detector, @@ -1910,22 +1956,6 @@ QString GccToolChain::sysRoot() const return {}; } -// -------------------------------------------------------------------------- -// ClangToolChainFactory -// -------------------------------------------------------------------------- - -ClangToolChainFactory::ClangToolChainFactory() -{ - m_subType = GccToolChain::Clang; - setDisplayName(Tr::tr("Clang")); - setSupportedToolChainType(Constants::CLANG_TOOLCHAIN_TYPEID); - setSupportedLanguages({Constants::CXX_LANGUAGE_ID, Constants::C_LANGUAGE_ID}); - setToolchainConstructor([] { - return new GccToolChain(Constants::CLANG_TOOLCHAIN_TYPEID, GccToolChain::Clang); - }); -} - - void GccToolChainConfigWidget::updateParentToolChainComboBox() { QTC_ASSERT(m_parentToolchainCombo, return); @@ -1953,36 +1983,6 @@ void GccToolChainConfigWidget::updateParentToolChainComboBox() } } -// -------------------------------------------------------------------------- -// MingwToolChainFactory -// -------------------------------------------------------------------------- - -MingwToolChainFactory::MingwToolChainFactory() -{ - m_subType = GccToolChain::MinGW; - setDisplayName(Tr::tr("MinGW")); - setSupportedToolChainType(Constants::MINGW_TOOLCHAIN_TYPEID); - setSupportedLanguages({Constants::CXX_LANGUAGE_ID, Constants::C_LANGUAGE_ID}); - setToolchainConstructor([] { - return new GccToolChain(Constants::MINGW_TOOLCHAIN_TYPEID, GccToolChain::MinGW); - }); -} - -// -------------------------------------------------------------------------- -// LinuxIccToolChainFactory -// -------------------------------------------------------------------------- - -LinuxIccToolChainFactory::LinuxIccToolChainFactory() -{ - m_subType = GccToolChain::LinuxIcc; - setDisplayName(Tr::tr("ICC")); - setSupportedToolChainType(Constants::LINUXICC_TOOLCHAIN_TYPEID); - setSupportedLanguages({Constants::CXX_LANGUAGE_ID, Constants::C_LANGUAGE_ID}); - setToolchainConstructor([] { - return new GccToolChain(Constants::LINUXICC_TOOLCHAIN_TYPEID, GccToolChain::LinuxIcc); - }); -} - GccToolChain::WarningFlagAdder::WarningFlagAdder(const QString &flag, WarningFlags &flags) : m_flags(flags) { diff --git a/src/plugins/projectexplorer/gcctoolchain.h b/src/plugins/projectexplorer/gcctoolchain.h index 7694cc524c4..fb8909d3881 100644 --- a/src/plugins/projectexplorer/gcctoolchain.h +++ b/src/plugins/projectexplorer/gcctoolchain.h @@ -180,22 +180,18 @@ private: QMetaObject::Connection m_thisToolchainRemovedConnection; }; -// -------------------------------------------------------------------------- -// Factories -// -------------------------------------------------------------------------- namespace Internal { + class GccToolChainFactory : public ToolChainFactory { public: - GccToolChainFactory(); + explicit GccToolChainFactory(GccToolChain::SubType subType); Toolchains autoDetect(const ToolchainDetector &detector) const final; Toolchains detectForImport(const ToolChainDescription &tcd) const final; -protected: - GccToolChain::SubType m_subType = GccToolChain::RealGcc; - +private: enum class DetectVariants { Yes, No }; using ToolchainChecker = std::function; static Toolchains autoDetectToolchains(const QString &compilerName, @@ -208,24 +204,8 @@ protected: static Toolchains autoDetectToolChain(const ToolChainDescription &tcd, const ToolChainConstructor &constructor, const ToolchainChecker &checker = {}); -}; -class ClangToolChainFactory : public GccToolChainFactory -{ -public: - ClangToolChainFactory(); -}; - -class MingwToolChainFactory : public GccToolChainFactory -{ -public: - MingwToolChainFactory(); -}; - -class LinuxIccToolChainFactory : public GccToolChainFactory -{ -public: - LinuxIccToolChainFactory(); + const bool m_autoDetecting; }; } // namespace Internal diff --git a/src/plugins/projectexplorer/projectexplorer.cpp b/src/plugins/projectexplorer/projectexplorer.cpp index 3b199217212..b85e7abafce 100644 --- a/src/plugins/projectexplorer/projectexplorer.cpp +++ b/src/plugins/projectexplorer/projectexplorer.cpp @@ -626,15 +626,16 @@ public: MsvcToolChainFactory m_mscvToolChainFactory; ClangClToolChainFactory m_clangClToolChainFactory; #else - LinuxIccToolChainFactory m_linuxToolChainFactory; + GccToolChainFactory m_linuxToolChainFactory{GccToolChain::LinuxIcc}; #endif #ifndef Q_OS_MACOS - MingwToolChainFactory m_mingwToolChainFactory; // Mingw offers cross-compiling to windows + // Mingw offers cross-compiling to windows + GccToolChainFactory m_mingwToolChainFactory{GccToolChain::MinGW}; #endif - GccToolChainFactory m_gccToolChainFactory; - ClangToolChainFactory m_clangToolChainFactory; + GccToolChainFactory m_gccToolChainFactory{GccToolChain::RealGcc}; + GccToolChainFactory m_clangToolChainFactory{GccToolChain::Clang}; CustomToolChainFactory m_customToolChainFactory; DesktopDeviceFactory m_desktopDeviceFactory; diff --git a/src/plugins/projectexplorer/toolchain.cpp b/src/plugins/projectexplorer/toolchain.cpp index f4ceb06720d..5d51c501715 100644 --- a/src/plugins/projectexplorer/toolchain.cpp +++ b/src/plugins/projectexplorer/toolchain.cpp @@ -671,8 +671,7 @@ void ToolChainFactory::setSupportsAllLanguages(bool supportsAllLanguages) m_supportsAllLanguages = supportsAllLanguages; } -void ToolChainFactory::setToolchainConstructor - (const ToolChainConstructor &toolchainContructor) +void ToolChainFactory::setToolchainConstructor(const ToolChainConstructor &toolchainContructor) { m_toolchainConstructor = toolchainContructor; } From e5f74d217b8c8c469ba16afd38c723be5e156555 Mon Sep 17 00:00:00 2001 From: hjk Date: Fri, 15 Sep 2023 12:58:44 +0200 Subject: [PATCH 18/27] Core: Merge mainwindow and icore file pairs So far the main window acted a bit like ICore's pimpl. Aim at making that a bit more similar to other places. The files are kept for now to not have to adjust #includes all over the place and there's some hope to move code back there. Change-Id: I150e2dd0971bfab44cba89e0c51bb3f37062b8d3 Reviewed-by: Eike Ziller --- src/plugins/coreplugin/icore.cpp | 1670 ++++++++++++++++++++++++- src/plugins/coreplugin/icore.h | 68 +- src/plugins/coreplugin/mainwindow.cpp | 1664 ------------------------ src/plugins/coreplugin/mainwindow.h | 77 -- 4 files changed, 1722 insertions(+), 1757 deletions(-) diff --git a/src/plugins/coreplugin/icore.cpp b/src/plugins/coreplugin/icore.cpp index fba0d66f1a5..a4cad44e702 100644 --- a/src/plugins/coreplugin/icore.cpp +++ b/src/plugins/coreplugin/icore.cpp @@ -3,23 +3,97 @@ #include "icore.h" +#include "actionmanager/actioncontainer.h" +#include "actionmanager/actionmanager.h" +#include "actionmanager/command.h" +#include "coreicons.h" #include "coreplugintr.h" +#include "coreplugintr.h" +#include "dialogs/externaltoolconfig.h" #include "dialogs/settingsdialog.h" +#include "dialogs/shortcutsettings.h" +#include "documentmanager.h" +#include "editormanager/documentmodel_p.h" +#include "editormanager/editormanager.h" +#include "editormanager/editormanager_p.h" +#include "editormanager/ieditor.h" +#include "editormanager/ieditorfactory.h" +#include "editormanager/systemeditor.h" +#include "externaltoolmanager.h" +#include "fancytabwidget.h" +#include "fileutils.h" +#include "find/basetextfind.h" +#include "findplaceholder.h" +#include "helpmanager.h" +#include "icore.h" +#include "idocumentfactory.h" +#include "inavigationwidgetfactory.h" +#include "iwizardfactory.h" +#include "jsexpander.h" +#include "loggingviewer.h" +#include "manhattanstyle.h" +#include "messagemanager.h" +#include "mimetypesettings.h" +#include "modemanager.h" +#include "navigationwidget.h" +#include "outputpanemanager.h" +#include "plugindialog.h" +#include "progressmanager/progressmanager_p.h" +#include "progressmanager/progressview.h" +#include "rightpane.h" +#include "statusbarmanager.h" +#include "systemsettings.h" +#include "vcsmanager.h" +#include "versiondialog.h" #include "windowsupport.h" #include #include #include +#include #include #include +#include +#include +#include +#include +#include +#include #include +#include +#include +#include +#include +#include +#include +#include + +#include #include +#include +#include +#include #include +#include #include +#include +#include +#include +#include #include +#include +#include #include +#include +#include +#include +#include + +#ifdef Q_OS_LINUX +#include +#endif /*! \namespace Core @@ -127,7 +201,6 @@ #include "dialogs/newdialogwidget.h" #include "dialogs/newdialog.h" #include "iwizardfactory.h" -#include "mainwindow.h" #include "documentmanager.h" #include @@ -146,7 +219,7 @@ using namespace Utils; namespace Core { // The Core Singleton -static ICore *m_instance = nullptr; +static ICore *m_core = nullptr; static MainWindow *m_mainwindow = nullptr; static NewDialog *defaultDialogFactory(QWidget *parent) @@ -154,6 +227,108 @@ static NewDialog *defaultDialogFactory(QWidget *parent) return new NewDialogWidget(parent); } +namespace Internal { + +class MainWindowPrivate : public QObject +{ +public: + explicit MainWindowPrivate(MainWindow *mainWindow) + : q(mainWindow) + {} + + ~MainWindowPrivate(); + + void init(); + + static void openFile(); + static IDocument *openFiles(const FilePaths &filePaths, ICore::OpenFilesFlags flags, + const FilePath &workingDirectory = {}); + void aboutToShowRecentFiles(); + + static void setFocusToEditor(); + void aboutQtCreator(); + void aboutPlugins(); + void changeLog(); + void contact(); + void updateFocusWidget(QWidget *old, QWidget *now); + NavigationWidget *navigationWidget(Side side) const; + void setSidebarVisible(bool visible, Side side); + void destroyVersionDialog(); + void openDroppedFiles(const QList &files); + void restoreWindowState(); + + void openFileFromDevice(); + + void updateContextObject(const QList &context); + void updateContext(); + + void registerDefaultContainers(); + void registerDefaultActions(); + void registerModeSelectorStyleActions(); + + void readSettings(); + void saveWindowSettings(); + + void updateModeSelectorStyleMenu(); + + MainWindow *q = nullptr; + QTimer m_trimTimer; + QStringList m_aboutInformation; + Context m_highPrioAdditionalContexts; + Context m_lowPrioAdditionalContexts{Constants::C_GLOBAL}; + mutable QPrinter *m_printer = nullptr; + WindowSupport *m_windowSupport = nullptr; + EditorManager *m_editorManager = nullptr; + ExternalToolManager *m_externalToolManager = nullptr; + MessageManager *m_messageManager = nullptr; + ProgressManagerPrivate *m_progressManager = nullptr; + JsExpander *m_jsExpander = nullptr; + VcsManager *m_vcsManager = nullptr; + ModeManager *m_modeManager = nullptr; + FancyTabWidget *m_modeStack = nullptr; + NavigationWidget *m_leftNavigationWidget = nullptr; + NavigationWidget *m_rightNavigationWidget = nullptr; + RightPaneWidget *m_rightPaneWidget = nullptr; + VersionDialog *m_versionDialog = nullptr; + + QList m_activeContext; + + std::unordered_map m_contextWidgets; + + ShortcutSettings *m_shortcutSettings = nullptr; + ToolSettings *m_toolSettings = nullptr; + MimeTypeSettings *m_mimeTypeSettings = nullptr; + SystemEditor *m_systemEditor = nullptr; + + // actions + QAction *m_focusToEditor = nullptr; + QAction *m_newAction = nullptr; + QAction *m_openAction = nullptr; + QAction *m_openWithAction = nullptr; + QAction *m_openFromDeviceAction = nullptr; + QAction *m_saveAllAction = nullptr; + QAction *m_exitAction = nullptr; + QAction *m_optionsAction = nullptr; + QAction *m_loggerAction = nullptr; + QAction *m_toggleLeftSideBarAction = nullptr; + QAction *m_toggleRightSideBarAction = nullptr; + QAction *m_toggleMenubarAction = nullptr; + QAction *m_cycleModeSelectorStyleAction = nullptr; + QAction *m_setModeSelectorStyleIconsAndTextAction = nullptr; + QAction *m_setModeSelectorStyleHiddenAction = nullptr; + QAction *m_setModeSelectorStyleIconsOnlyAction = nullptr; + QAction *m_themeAction = nullptr; + + QToolButton *m_toggleLeftSideBarButton = nullptr; + QToolButton *m_toggleRightSideBarButton = nullptr; + QColor m_overrideColor; + QList> m_preCloseListeners; +}; + +} // Internal + +static MainWindowPrivate *d = nullptr; + static std::function m_newDialogFactory = defaultDialogFactory; /*! @@ -161,7 +336,7 @@ static std::function m_newDialogFactory = defaultDialogF */ ICore *ICore::instance() { - return m_instance; + return m_core; } /*! @@ -188,10 +363,9 @@ QWidget *ICore::newItemDialog() /*! \internal */ -ICore::ICore(MainWindow *mainwindow) +ICore::ICore() { - m_instance = this; - m_mainwindow = mainwindow; + m_core = this; connect(PluginManager::instance(), &PluginManager::testsFinished, this, [this](int failedTests) { @@ -206,7 +380,7 @@ ICore::ICore(MainWindow *mainwindow) QCoreApplication::exit(exitCode); }); - FileUtils::setDialogParentGetter(&ICore::dialogParent); + Utils::FileUtils::setDialogParentGetter(&ICore::dialogParent); } /*! @@ -214,7 +388,7 @@ ICore::ICore(MainWindow *mainwindow) */ ICore::~ICore() { - m_instance = nullptr; + m_core = nullptr; m_mainwindow = nullptr; } @@ -257,7 +431,7 @@ void ICore::showNewItemDialog(const QString &title, dialogFactory = defaultDialogFactory; NewDialog *newDialog = dialogFactory(dialogParent()); - connect(newDialog->widget(), &QObject::destroyed, m_instance, &ICore::updateNewItemDialogState); + connect(newDialog->widget(), &QObject::destroyed, m_core, &ICore::updateNewItemDialogState); newDialog->setWizardFactories(factories, defaultLocation, extraVariables); newDialog->setWindowTitle(title); newDialog->showDialog(); @@ -908,7 +1082,7 @@ void ICore::restart() */ void ICore::saveSettings(SaveSettingsReason reason) { - emit m_instance->saveSettingsRequested(reason); + emit m_core->saveSettingsRequested(reason); m_mainwindow->saveSettings(); ICore::settings(QSettings::SystemScope)->sync(); @@ -958,4 +1132,1480 @@ void ICore::setNewDialogFactory(const std::function &new m_newDialogFactory = newFactory; } + +namespace Internal { + +const char settingsGroup[] = "MainWindow"; +const char colorKey[] = "Color"; +const char windowGeometryKey[] = "WindowGeometry"; +const char windowStateKey[] = "WindowState"; +const char modeSelectorLayoutKey[] = "ModeSelectorLayout"; +const char menubarVisibleKey[] = "MenubarVisible"; + +static bool hideToolsMenu() +{ + return Core::ICore::settings()->value(Constants::SETTINGS_MENU_HIDE_TOOLS, false).toBool(); +} + +enum { debugMainWindow = 0 }; + + +void MainWindowPrivate::init() +{ + m_core = new ICore; + m_progressManager = new ProgressManagerPrivate; + m_jsExpander = JsExpander::createGlobalJsExpander(); + m_vcsManager = new VcsManager; + m_modeStack = new FancyTabWidget(q); + m_shortcutSettings = new ShortcutSettings; + m_toolSettings = new ToolSettings; + m_mimeTypeSettings = new MimeTypeSettings; + m_systemEditor = new SystemEditor; + m_toggleLeftSideBarButton = new QToolButton; + m_toggleRightSideBarButton = new QToolButton; + + (void) new DocumentManager(q); + + HistoryCompleter::setSettings(PluginManager::settings()); + + if (HostOsInfo::isLinuxHost()) + QApplication::setWindowIcon(Icons::QTCREATORLOGO_BIG.icon()); + QString baseName = QApplication::style()->objectName(); + // Sometimes we get the standard windows 95 style as a fallback + if (HostOsInfo::isAnyUnixHost() && !HostOsInfo::isMacHost() + && baseName == QLatin1String("windows")) { + baseName = QLatin1String("fusion"); + } + + // if the user has specified as base style in the theme settings, + // prefer that + const QStringList available = QStyleFactory::keys(); + const QStringList styles = Utils::creatorTheme()->preferredStyles(); + for (const QString &s : styles) { + if (available.contains(s, Qt::CaseInsensitive)) { + baseName = s; + break; + } + } + + QApplication::setStyle(new ManhattanStyle(baseName)); + + m_modeManager = new ModeManager(q, m_modeStack); + connect(m_modeStack, &FancyTabWidget::topAreaClicked, this, [](Qt::MouseButton, Qt::KeyboardModifiers modifiers) { + if (modifiers & Qt::ShiftModifier) { + QColor color = QColorDialog::getColor(StyleHelper::requestedBaseColor(), ICore::dialogParent()); + if (color.isValid()) + StyleHelper::setBaseColor(color); + } + }); + + registerDefaultContainers(); + registerDefaultActions(); + + m_leftNavigationWidget = new NavigationWidget(m_toggleLeftSideBarAction, Side::Left); + m_rightNavigationWidget = new NavigationWidget(m_toggleRightSideBarAction, Side::Right); + m_rightPaneWidget = new RightPaneWidget(); + + m_messageManager = new MessageManager; + m_editorManager = new EditorManager(this); + m_externalToolManager = new ExternalToolManager(); + + m_progressManager->progressView()->setParent(q); + + connect(qApp, &QApplication::focusChanged, this, &MainWindowPrivate::updateFocusWidget); + + // Add small Toolbuttons for toggling the navigation widgets + StatusBarManager::addStatusBarWidget(m_toggleLeftSideBarButton, StatusBarManager::First); + int childsCount = q->statusBar()->findChildren(QString(), Qt::FindDirectChildrenOnly).count(); + q->statusBar()->insertPermanentWidget(childsCount - 1, m_toggleRightSideBarButton); // before QSizeGrip + +// setUnifiedTitleAndToolBarOnMac(true); + //if (HostOsInfo::isAnyUnixHost()) + //signal(SIGINT, handleSigInt); + + q->statusBar()->setProperty("p_styled", true); + + /*auto dropSupport = new DropSupport(this, [](QDropEvent *event, DropSupport *) { + return event->source() == nullptr; // only accept drops from the "outside" (e.g. file manager) + }); + connect(dropSupport, &DropSupport::filesDropped, + this, &MainWindow::openDroppedFiles); +*/ + if (HostOsInfo::isLinuxHost()) { + m_trimTimer.setSingleShot(true); + m_trimTimer.setInterval(60000); + // glibc may not actually free memory in free(). +#ifdef Q_OS_LINUX + connect(&m_trimTimer, &QTimer::timeout, this, [] { malloc_trim(0); }); +#endif + } +} + +MainWindow::MainWindow() +{ + m_mainwindow = this; + d = new MainWindowPrivate(this); + d->init(); // Separation needed for now as the call triggers other MainWindow calls. + + setWindowTitle(QGuiApplication::applicationDisplayName()); + setDockNestingEnabled(true); + setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea); + setCorner(Qt::BottomRightCorner, Qt::BottomDockWidgetArea); + + setCentralWidget(d->m_modeStack); +} + +NavigationWidget *MainWindowPrivate::navigationWidget(Side side) const +{ + return side == Side::Left ? m_leftNavigationWidget : m_rightNavigationWidget; +} + +void MainWindowPrivate::setSidebarVisible(bool visible, Side side) +{ + if (NavigationWidgetPlaceHolder::current(side)) + navigationWidget(side)->setShown(visible); +} + +void MainWindow::setOverrideColor(const QColor &color) +{ + d->m_overrideColor = color; +} + +QStringList MainWindow::additionalAboutInformation() const +{ + return d->m_aboutInformation; +} + +void MainWindow::clearAboutInformation() +{ + d->m_aboutInformation.clear(); +} + +void MainWindow::appendAboutInformation(const QString &line) +{ + d->m_aboutInformation.append(line); +} + +void MainWindow::addPreCloseListener(const std::function &listener) +{ + d->m_preCloseListeners.append(listener); +} + +MainWindow::~MainWindow() +{ + delete d; + d = nullptr; +} + +MainWindowPrivate::~MainWindowPrivate() +{ + // explicitly delete window support, because that calls methods from ICore that call methods + // from mainwindow, so mainwindow still needs to be alive + delete m_windowSupport; + m_windowSupport = nullptr; + + delete m_externalToolManager; + m_externalToolManager = nullptr; + delete m_messageManager; + m_messageManager = nullptr; + delete m_shortcutSettings; + m_shortcutSettings = nullptr; + delete m_toolSettings; + m_toolSettings = nullptr; + delete m_mimeTypeSettings; + m_mimeTypeSettings = nullptr; + delete m_systemEditor; + m_systemEditor = nullptr; + delete m_printer; + m_printer = nullptr; + delete m_vcsManager; + m_vcsManager = nullptr; + //we need to delete editormanager and statusbarmanager explicitly before the end of the destructor, + //because they might trigger stuff that tries to access data from editorwindow, like removeContextWidget + + // All modes are now gone + OutputPaneManager::destroy(); + + delete m_leftNavigationWidget; + delete m_rightNavigationWidget; + m_leftNavigationWidget = nullptr; + m_rightNavigationWidget = nullptr; + + delete m_editorManager; + m_editorManager = nullptr; + delete m_progressManager; + m_progressManager = nullptr; + + delete m_core; + m_core = nullptr; + + delete m_rightPaneWidget; + m_rightPaneWidget = nullptr; + + delete m_modeManager; + m_modeManager = nullptr; + + delete m_jsExpander; + m_jsExpander = nullptr; +} + +void MainWindow::init() +{ + d->m_progressManager->init(); // needs the status bar manager + MessageManager::init(); + OutputPaneManager::create(); +} + +void MainWindow::extensionsInitialized() +{ + EditorManagerPrivate::extensionsInitialized(); + MimeTypeSettings::restoreSettings(); + d->m_windowSupport = new WindowSupport(this, Context("Core.MainWindow")); + d->m_windowSupport->setCloseActionEnabled(false); + OutputPaneManager::initialize(); + VcsManager::extensionsInitialized(); + d->m_leftNavigationWidget->setFactories(INavigationWidgetFactory::allNavigationFactories()); + d->m_rightNavigationWidget->setFactories(INavigationWidgetFactory::allNavigationFactories()); + + ModeManager::extensionsInitialized(); + + d->readSettings(); + d->updateContext(); + + emit m_core->coreAboutToOpen(); + // Delay restoreWindowState, since it is overridden by LayoutRequest event + QMetaObject::invokeMethod(d, &MainWindowPrivate::restoreWindowState, Qt::QueuedConnection); + QMetaObject::invokeMethod(m_core, &ICore::coreOpened, Qt::QueuedConnection); +} + +static void setRestart(bool restart) +{ + qApp->setProperty("restart", restart); +} + +void MainWindow::restart() +{ + setRestart(true); + exit(); +} + +void MainWindow::restartTrimmer() +{ + if (HostOsInfo::isLinuxHost() && !d->m_trimTimer.isActive()) + d->m_trimTimer.start(); +} + +void MainWindow::closeEvent(QCloseEvent *event) +{ + const auto cancelClose = [event] { + event->ignore(); + setRestart(false); + }; + + // work around QTBUG-43344 + static bool alreadyClosed = false; + if (alreadyClosed) { + event->accept(); + return; + } + + if (systemSettings().askBeforeExit() + && (QMessageBox::question(this, + Tr::tr("Exit %1?").arg(QGuiApplication::applicationDisplayName()), + Tr::tr("Exit %1?").arg(QGuiApplication::applicationDisplayName()), + QMessageBox::Yes | QMessageBox::No, + QMessageBox::No) + == QMessageBox::No)) { + event->ignore(); + return; + } + + ICore::saveSettings(ICore::MainWindowClosing); + + // Save opened files + if (!DocumentManager::saveAllModifiedDocuments()) { + cancelClose(); + return; + } + + const QList> listeners = d->m_preCloseListeners; + for (const std::function &listener : listeners) { + if (!listener()) { + cancelClose(); + return; + } + } + + emit m_core->coreAboutToClose(); + + d->saveWindowSettings(); + + d->m_leftNavigationWidget->closeSubWidgets(); + d->m_rightNavigationWidget->closeSubWidgets(); + + event->accept(); + alreadyClosed = true; +} + +void MainWindow::keyPressEvent(QKeyEvent *event) +{ + restartTrimmer(); + AppMainWindow::keyPressEvent(event); +} + +void MainWindow::mousePressEvent(QMouseEvent *event) +{ + restartTrimmer(); + AppMainWindow::mousePressEvent(event); +} + +void MainWindowPrivate::openDroppedFiles(const QList &files) +{ + q->raiseWindow(); + const FilePaths filePaths = Utils::transform(files, &DropSupport::FileSpec::filePath); + q->openFiles(filePaths, ICore::SwitchMode); +} + +IContext *MainWindow::currentContextObject() const +{ + return d->m_activeContext.isEmpty() ? nullptr : d->m_activeContext.first(); +} + +QStatusBar *MainWindow::statusBar() const +{ + return d->m_modeStack->statusBar(); +} + +InfoBar *MainWindow::infoBar() const +{ + return d->m_modeStack->infoBar(); +} + +void MainWindowPrivate::registerDefaultContainers() +{ + ActionContainer *menubar = ActionManager::createMenuBar(Constants::MENU_BAR); + + if (!HostOsInfo::isMacHost()) // System menu bar on Mac + q->setMenuBar(menubar->menuBar()); + menubar->appendGroup(Constants::G_FILE); + menubar->appendGroup(Constants::G_EDIT); + menubar->appendGroup(Constants::G_VIEW); + menubar->appendGroup(Constants::G_TOOLS); + menubar->appendGroup(Constants::G_WINDOW); + menubar->appendGroup(Constants::G_HELP); + + // File Menu + ActionContainer *filemenu = ActionManager::createMenu(Constants::M_FILE); + menubar->addMenu(filemenu, Constants::G_FILE); + filemenu->menu()->setTitle(Tr::tr("&File")); + filemenu->appendGroup(Constants::G_FILE_NEW); + filemenu->appendGroup(Constants::G_FILE_OPEN); + filemenu->appendGroup(Constants::G_FILE_SESSION); + filemenu->appendGroup(Constants::G_FILE_PROJECT); + filemenu->appendGroup(Constants::G_FILE_SAVE); + filemenu->appendGroup(Constants::G_FILE_EXPORT); + filemenu->appendGroup(Constants::G_FILE_CLOSE); + filemenu->appendGroup(Constants::G_FILE_PRINT); + filemenu->appendGroup(Constants::G_FILE_OTHER); + connect(filemenu->menu(), &QMenu::aboutToShow, this, &MainWindowPrivate::aboutToShowRecentFiles); + + + // Edit Menu + ActionContainer *medit = ActionManager::createMenu(Constants::M_EDIT); + menubar->addMenu(medit, Constants::G_EDIT); + medit->menu()->setTitle(Tr::tr("&Edit")); + medit->appendGroup(Constants::G_EDIT_UNDOREDO); + medit->appendGroup(Constants::G_EDIT_COPYPASTE); + medit->appendGroup(Constants::G_EDIT_SELECTALL); + medit->appendGroup(Constants::G_EDIT_ADVANCED); + medit->appendGroup(Constants::G_EDIT_FIND); + medit->appendGroup(Constants::G_EDIT_OTHER); + + ActionContainer *mview = ActionManager::createMenu(Constants::M_VIEW); + menubar->addMenu(mview, Constants::G_VIEW); + mview->menu()->setTitle(Tr::tr("&View")); + mview->appendGroup(Constants::G_VIEW_VIEWS); + mview->appendGroup(Constants::G_VIEW_PANES); + + // Tools Menu + ActionContainer *ac = ActionManager::createMenu(Constants::M_TOOLS); + ac->setParent(this); + if (!hideToolsMenu()) + menubar->addMenu(ac, Constants::G_TOOLS); + + ac->menu()->setTitle(Tr::tr("&Tools")); + + // Window Menu + ActionContainer *mwindow = ActionManager::createMenu(Constants::M_WINDOW); + menubar->addMenu(mwindow, Constants::G_WINDOW); + mwindow->menu()->setTitle(Tr::tr("&Window")); + mwindow->appendGroup(Constants::G_WINDOW_SIZE); + mwindow->appendGroup(Constants::G_WINDOW_SPLIT); + mwindow->appendGroup(Constants::G_WINDOW_NAVIGATE); + mwindow->appendGroup(Constants::G_WINDOW_LIST); + mwindow->appendGroup(Constants::G_WINDOW_OTHER); + + // Help Menu + ac = ActionManager::createMenu(Constants::M_HELP); + menubar->addMenu(ac, Constants::G_HELP); + ac->menu()->setTitle(Tr::tr("&Help")); + Theme::setHelpMenu(ac->menu()); + ac->appendGroup(Constants::G_HELP_HELP); + ac->appendGroup(Constants::G_HELP_SUPPORT); + ac->appendGroup(Constants::G_HELP_ABOUT); + ac->appendGroup(Constants::G_HELP_UPDATES); + + // macOS touch bar + ac = ActionManager::createTouchBar(Constants::TOUCH_BAR, + QIcon(), + "Main TouchBar" /*never visible*/); + ac->appendGroup(Constants::G_TOUCHBAR_HELP); + ac->appendGroup(Constants::G_TOUCHBAR_NAVIGATION); + ac->appendGroup(Constants::G_TOUCHBAR_EDITOR); + ac->appendGroup(Constants::G_TOUCHBAR_OTHER); + ac->touchBar()->setApplicationTouchBar(); +} + +static QMenuBar *globalMenuBar() +{ + return ActionManager::actionContainer(Constants::MENU_BAR)->menuBar(); +} + +void MainWindowPrivate::registerDefaultActions() +{ + ActionContainer *mfile = ActionManager::actionContainer(Constants::M_FILE); + ActionContainer *medit = ActionManager::actionContainer(Constants::M_EDIT); + ActionContainer *mview = ActionManager::actionContainer(Constants::M_VIEW); + ActionContainer *mtools = ActionManager::actionContainer(Constants::M_TOOLS); + ActionContainer *mwindow = ActionManager::actionContainer(Constants::M_WINDOW); + ActionContainer *mhelp = ActionManager::actionContainer(Constants::M_HELP); + + // File menu separators + mfile->addSeparator(Constants::G_FILE_SAVE); + mfile->addSeparator(Constants::G_FILE_EXPORT); + mfile->addSeparator(Constants::G_FILE_PRINT); + mfile->addSeparator(Constants::G_FILE_CLOSE); + mfile->addSeparator(Constants::G_FILE_OTHER); + // Edit menu separators + medit->addSeparator(Constants::G_EDIT_COPYPASTE); + medit->addSeparator(Constants::G_EDIT_SELECTALL); + medit->addSeparator(Constants::G_EDIT_FIND); + medit->addSeparator(Constants::G_EDIT_ADVANCED); + + // Return to editor shortcut: Note this requires Qt to fix up + // handling of shortcut overrides in menus, item views, combos.... + m_focusToEditor = new QAction(Tr::tr("Return to Editor"), this); + Command *cmd = ActionManager::registerAction(m_focusToEditor, Constants::S_RETURNTOEDITOR); + cmd->setDefaultKeySequence(QKeySequence(Qt::Key_Escape)); + connect(m_focusToEditor, &QAction::triggered, this, &MainWindowPrivate::setFocusToEditor); + + // New File Action + QIcon icon = Icon::fromTheme("document-new"); + + m_newAction = new QAction(icon, Tr::tr("&New Project..."), this); + cmd = ActionManager::registerAction(m_newAction, Constants::NEW); + cmd->setDefaultKeySequence(QKeySequence("Ctrl+Shift+N")); + mfile->addAction(cmd, Constants::G_FILE_NEW); + connect(m_newAction, &QAction::triggered, this, [] { + if (!ICore::isNewItemDialogRunning()) { + ICore::showNewItemDialog( + Tr::tr("New Project", "Title of dialog"), + Utils::filtered(Core::IWizardFactory::allWizardFactories(), + Utils::equal(&Core::IWizardFactory::kind, + Core::IWizardFactory::ProjectWizard)), + FilePath()); + } else { + ICore::raiseWindow(ICore::newItemDialog()); + } + }); + + auto action = new QAction(icon, Tr::tr("New File..."), this); + cmd = ActionManager::registerAction(action, Constants::NEW_FILE); + cmd->setDefaultKeySequence(QKeySequence::New); + mfile->addAction(cmd, Constants::G_FILE_NEW); + connect(action, &QAction::triggered, this, [] { + if (!ICore::isNewItemDialogRunning()) { + ICore::showNewItemDialog(Tr::tr("New File", "Title of dialog"), + Utils::filtered(Core::IWizardFactory::allWizardFactories(), + Utils::equal(&Core::IWizardFactory::kind, + Core::IWizardFactory::FileWizard)), + FilePath()); + } else { + ICore::raiseWindow(ICore::newItemDialog()); + } + }); + + // Open Action + icon = Icon::fromTheme("document-open"); + m_openAction = new QAction(icon, Tr::tr("&Open File or Project..."), this); + cmd = ActionManager::registerAction(m_openAction, Constants::OPEN); + cmd->setDefaultKeySequence(QKeySequence::Open); + mfile->addAction(cmd, Constants::G_FILE_OPEN); + connect(m_openAction, &QAction::triggered, this, &MainWindowPrivate::openFile); + + // Open With Action + m_openWithAction = new QAction(Tr::tr("Open File &With..."), this); + cmd = ActionManager::registerAction(m_openWithAction, Constants::OPEN_WITH); + mfile->addAction(cmd, Constants::G_FILE_OPEN); + connect(m_openWithAction, &QAction::triggered, this, &MainWindow::openFileWith); + + if (FSEngine::isAvailable()) { + // Open From Device Action + m_openFromDeviceAction = new QAction(Tr::tr("Open From Device..."), this); + cmd = ActionManager::registerAction(m_openFromDeviceAction, Constants::OPEN_FROM_DEVICE); + mfile->addAction(cmd, Constants::G_FILE_OPEN); + connect(m_openFromDeviceAction, &QAction::triggered, this, &MainWindowPrivate::openFileFromDevice); + } + + // File->Recent Files Menu + ActionContainer *ac = ActionManager::createMenu(Constants::M_FILE_RECENTFILES); + mfile->addMenu(ac, Constants::G_FILE_OPEN); + ac->menu()->setTitle(Tr::tr("Recent &Files")); + ac->setOnAllDisabledBehavior(ActionContainer::Show); + + // Save Action + icon = Icon::fromTheme("document-save"); + QAction *tmpaction = new QAction(icon, Tr::tr("&Save"), this); + tmpaction->setEnabled(false); + cmd = ActionManager::registerAction(tmpaction, Constants::SAVE); + cmd->setDefaultKeySequence(QKeySequence::Save); + cmd->setAttribute(Command::CA_UpdateText); + cmd->setDescription(Tr::tr("Save")); + mfile->addAction(cmd, Constants::G_FILE_SAVE); + + // Save As Action + icon = Icon::fromTheme("document-save-as"); + tmpaction = new QAction(icon, Tr::tr("Save &As..."), this); + tmpaction->setEnabled(false); + cmd = ActionManager::registerAction(tmpaction, Constants::SAVEAS); + cmd->setDefaultKeySequence(QKeySequence(useMacShortcuts ? Tr::tr("Ctrl+Shift+S") : QString())); + cmd->setAttribute(Command::CA_UpdateText); + cmd->setDescription(Tr::tr("Save As...")); + mfile->addAction(cmd, Constants::G_FILE_SAVE); + + // SaveAll Action + DocumentManager::registerSaveAllAction(); + + // Print Action + icon = Icon::fromTheme("document-print"); + tmpaction = new QAction(icon, Tr::tr("&Print..."), this); + tmpaction->setEnabled(false); + cmd = ActionManager::registerAction(tmpaction, Constants::PRINT); + cmd->setDefaultKeySequence(QKeySequence::Print); + mfile->addAction(cmd, Constants::G_FILE_PRINT); + + // Exit Action + icon = Icon::fromTheme("application-exit"); + m_exitAction = new QAction(icon, Tr::tr("E&xit"), this); + m_exitAction->setMenuRole(QAction::QuitRole); + cmd = ActionManager::registerAction(m_exitAction, Constants::EXIT); + cmd->setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Q"))); + mfile->addAction(cmd, Constants::G_FILE_OTHER); + connect(m_exitAction, &QAction::triggered, q, &MainWindow::exit); + + // Undo Action + icon = Icon::fromTheme("edit-undo"); + tmpaction = new QAction(icon, Tr::tr("&Undo"), this); + cmd = ActionManager::registerAction(tmpaction, Constants::UNDO); + cmd->setDefaultKeySequence(QKeySequence::Undo); + cmd->setAttribute(Command::CA_UpdateText); + cmd->setDescription(Tr::tr("Undo")); + medit->addAction(cmd, Constants::G_EDIT_UNDOREDO); + tmpaction->setEnabled(false); + + // Redo Action + icon = Icon::fromTheme("edit-redo"); + tmpaction = new QAction(icon, Tr::tr("&Redo"), this); + cmd = ActionManager::registerAction(tmpaction, Constants::REDO); + cmd->setDefaultKeySequence(QKeySequence::Redo); + cmd->setAttribute(Command::CA_UpdateText); + cmd->setDescription(Tr::tr("Redo")); + medit->addAction(cmd, Constants::G_EDIT_UNDOREDO); + tmpaction->setEnabled(false); + + // Cut Action + icon = Icon::fromTheme("edit-cut"); + tmpaction = new QAction(icon, Tr::tr("Cu&t"), this); + cmd = ActionManager::registerAction(tmpaction, Constants::CUT); + cmd->setDefaultKeySequence(QKeySequence::Cut); + medit->addAction(cmd, Constants::G_EDIT_COPYPASTE); + tmpaction->setEnabled(false); + + // Copy Action + icon = Icon::fromTheme("edit-copy"); + tmpaction = new QAction(icon, Tr::tr("&Copy"), this); + cmd = ActionManager::registerAction(tmpaction, Constants::COPY); + cmd->setDefaultKeySequence(QKeySequence::Copy); + medit->addAction(cmd, Constants::G_EDIT_COPYPASTE); + tmpaction->setEnabled(false); + + // Paste Action + icon = Icon::fromTheme("edit-paste"); + tmpaction = new QAction(icon, Tr::tr("&Paste"), this); + cmd = ActionManager::registerAction(tmpaction, Constants::PASTE); + cmd->setDefaultKeySequence(QKeySequence::Paste); + medit->addAction(cmd, Constants::G_EDIT_COPYPASTE); + tmpaction->setEnabled(false); + + // Select All + icon = Icon::fromTheme("edit-select-all"); + tmpaction = new QAction(icon, Tr::tr("Select &All"), this); + cmd = ActionManager::registerAction(tmpaction, Constants::SELECTALL); + cmd->setDefaultKeySequence(QKeySequence::SelectAll); + medit->addAction(cmd, Constants::G_EDIT_SELECTALL); + tmpaction->setEnabled(false); + + // Goto Action + icon = Icon::fromTheme("go-jump"); + tmpaction = new QAction(icon, Tr::tr("&Go to Line..."), this); + cmd = ActionManager::registerAction(tmpaction, Constants::GOTO); + cmd->setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+L"))); + medit->addAction(cmd, Constants::G_EDIT_OTHER); + tmpaction->setEnabled(false); + + // Zoom In Action + icon = Icon::fromTheme("zoom-in"); + tmpaction = new QAction(icon, Tr::tr("Zoom In"), this); + cmd = ActionManager::registerAction(tmpaction, Constants::ZOOM_IN); + cmd->setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl++"))); + tmpaction->setEnabled(false); + + // Zoom Out Action + icon = Icon::fromTheme("zoom-out"); + tmpaction = new QAction(icon, Tr::tr("Zoom Out"), this); + cmd = ActionManager::registerAction(tmpaction, Constants::ZOOM_OUT); + if (useMacShortcuts) + cmd->setDefaultKeySequences({QKeySequence(Tr::tr("Ctrl+-")), QKeySequence(Tr::tr("Ctrl+Shift+-"))}); + else + cmd->setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+-"))); + tmpaction->setEnabled(false); + + // Zoom Reset Action + icon = Icon::fromTheme("zoom-original"); + tmpaction = new QAction(icon, Tr::tr("Original Size"), this); + cmd = ActionManager::registerAction(tmpaction, Constants::ZOOM_RESET); + cmd->setDefaultKeySequence(QKeySequence(Core::useMacShortcuts ? Tr::tr("Meta+0") : Tr::tr("Ctrl+0"))); + tmpaction->setEnabled(false); + + // Debug Qt Creator menu + mtools->appendGroup(Constants::G_TOOLS_DEBUG); + ActionContainer *mtoolsdebug = ActionManager::createMenu(Constants::M_TOOLS_DEBUG); + mtoolsdebug->menu()->setTitle(Tr::tr("Debug %1").arg(QGuiApplication::applicationDisplayName())); + mtools->addMenu(mtoolsdebug, Constants::G_TOOLS_DEBUG); + + m_loggerAction = new QAction(Tr::tr("Show Logs..."), this); + cmd = ActionManager::registerAction(m_loggerAction, Constants::LOGGER); + mtoolsdebug->addAction(cmd); + connect(m_loggerAction, &QAction::triggered, this, [] { LoggingViewer::showLoggingView(); }); + + // Options Action + medit->appendGroup(Constants::G_EDIT_PREFERENCES); + medit->addSeparator(Constants::G_EDIT_PREFERENCES); + + m_optionsAction = new QAction(Tr::tr("Pr&eferences..."), this); + m_optionsAction->setMenuRole(QAction::PreferencesRole); + cmd = ActionManager::registerAction(m_optionsAction, Constants::OPTIONS); + cmd->setDefaultKeySequence(QKeySequence::Preferences); + medit->addAction(cmd, Constants::G_EDIT_PREFERENCES); + connect(m_optionsAction, &QAction::triggered, this, [] { ICore::showOptionsDialog(Id()); }); + + mwindow->addSeparator(Constants::G_WINDOW_LIST); + + if (useMacShortcuts) { + // Minimize Action + QAction *minimizeAction = new QAction(Tr::tr("Minimize"), this); + minimizeAction->setEnabled(false); // actual implementation in WindowSupport + cmd = ActionManager::registerAction(minimizeAction, Constants::MINIMIZE_WINDOW); + cmd->setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+M"))); + mwindow->addAction(cmd, Constants::G_WINDOW_SIZE); + + // Zoom Action + QAction *zoomAction = new QAction(Tr::tr("Zoom"), this); + zoomAction->setEnabled(false); // actual implementation in WindowSupport + cmd = ActionManager::registerAction(zoomAction, Constants::ZOOM_WINDOW); + mwindow->addAction(cmd, Constants::G_WINDOW_SIZE); + } + + // Full Screen Action + QAction *toggleFullScreenAction = new QAction(Tr::tr("Full Screen"), this); + toggleFullScreenAction->setCheckable(!HostOsInfo::isMacHost()); + toggleFullScreenAction->setEnabled(false); // actual implementation in WindowSupport + cmd = ActionManager::registerAction(toggleFullScreenAction, Constants::TOGGLE_FULLSCREEN); + cmd->setDefaultKeySequence(QKeySequence(useMacShortcuts ? Tr::tr("Ctrl+Meta+F") : Tr::tr("Ctrl+Shift+F11"))); + if (HostOsInfo::isMacHost()) + cmd->setAttribute(Command::CA_UpdateText); + mwindow->addAction(cmd, Constants::G_WINDOW_SIZE); + + if (useMacShortcuts) { + mwindow->addSeparator(Constants::G_WINDOW_SIZE); + + QAction *closeAction = new QAction(Tr::tr("Close Window"), this); + closeAction->setEnabled(false); + cmd = ActionManager::registerAction(closeAction, Constants::CLOSE_WINDOW); + cmd->setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Meta+W"))); + mwindow->addAction(cmd, Constants::G_WINDOW_SIZE); + + mwindow->addSeparator(Constants::G_WINDOW_SIZE); + } + + // Show Left Sidebar Action + m_toggleLeftSideBarAction = new QAction(Utils::Icons::TOGGLE_LEFT_SIDEBAR.icon(), + Tr::tr(Constants::TR_SHOW_LEFT_SIDEBAR), + this); + m_toggleLeftSideBarAction->setCheckable(true); + cmd = ActionManager::registerAction(m_toggleLeftSideBarAction, Constants::TOGGLE_LEFT_SIDEBAR); + cmd->setAttribute(Command::CA_UpdateText); + cmd->setDefaultKeySequence(QKeySequence(useMacShortcuts ? Tr::tr("Ctrl+0") : Tr::tr("Alt+0"))); + connect(m_toggleLeftSideBarAction, &QAction::triggered, + this, [this](bool visible) { setSidebarVisible(visible, Side::Left); }); + ProxyAction *toggleLeftSideBarProxyAction = + ProxyAction::proxyActionWithIcon(cmd->action(), Utils::Icons::TOGGLE_LEFT_SIDEBAR_TOOLBAR.icon()); + m_toggleLeftSideBarButton->setDefaultAction(toggleLeftSideBarProxyAction); + mview->addAction(cmd, Constants::G_VIEW_VIEWS); + m_toggleLeftSideBarAction->setEnabled(false); + + // Show Right Sidebar Action + m_toggleRightSideBarAction = new QAction(Utils::Icons::TOGGLE_RIGHT_SIDEBAR.icon(), + Tr::tr(Constants::TR_SHOW_RIGHT_SIDEBAR), + this); + m_toggleRightSideBarAction->setCheckable(true); + cmd = ActionManager::registerAction(m_toggleRightSideBarAction, Constants::TOGGLE_RIGHT_SIDEBAR); + cmd->setAttribute(Command::CA_UpdateText); + cmd->setDefaultKeySequence(QKeySequence(useMacShortcuts ? Tr::tr("Ctrl+Shift+0") : Tr::tr("Alt+Shift+0"))); + connect(m_toggleRightSideBarAction, &QAction::triggered, + this, [this](bool visible) { setSidebarVisible(visible, Side::Right); }); + ProxyAction *toggleRightSideBarProxyAction = + ProxyAction::proxyActionWithIcon(cmd->action(), Utils::Icons::TOGGLE_RIGHT_SIDEBAR_TOOLBAR.icon()); + m_toggleRightSideBarButton->setDefaultAction(toggleRightSideBarProxyAction); + mview->addAction(cmd, Constants::G_VIEW_VIEWS); + m_toggleRightSideBarButton->setEnabled(false); + + // Show Menubar Action + if (globalMenuBar() && !globalMenuBar()->isNativeMenuBar()) { + m_toggleMenubarAction = new QAction(Tr::tr("Show Menubar"), this); + m_toggleMenubarAction->setCheckable(true); + cmd = ActionManager::registerAction(m_toggleMenubarAction, Constants::TOGGLE_MENUBAR); + cmd->setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Alt+M"))); + connect(m_toggleMenubarAction, &QAction::toggled, this, [cmd](bool visible) { + if (!visible) { + CheckableMessageBox::information( + Core::ICore::dialogParent(), + Tr::tr("Hide Menubar"), + Tr::tr( + "This will hide the menu bar completely. You can show it again by typing ") + + cmd->keySequence().toString(QKeySequence::NativeText), + QString("ToogleMenuBarHint")); + } + globalMenuBar()->setVisible(visible); + }); + mview->addAction(cmd, Constants::G_VIEW_VIEWS); + } + + registerModeSelectorStyleActions(); + + // Window->Views + ActionContainer *mviews = ActionManager::createMenu(Constants::M_VIEW_VIEWS); + mview->addMenu(mviews, Constants::G_VIEW_VIEWS); + mviews->menu()->setTitle(Tr::tr("&Views")); + + // "Help" separators + mhelp->addSeparator(Constants::G_HELP_SUPPORT); + if (!HostOsInfo::isMacHost()) + mhelp->addSeparator(Constants::G_HELP_ABOUT); + + // About IDE Action + icon = Icon::fromTheme("help-about"); + if (HostOsInfo::isMacHost()) + tmpaction = new QAction(icon, + Tr::tr("About &%1").arg(QGuiApplication::applicationDisplayName()), + this); // it's convention not to add dots to the about menu + else + tmpaction + = new QAction(icon, + Tr::tr("About &%1...").arg(QGuiApplication::applicationDisplayName()), + this); + tmpaction->setMenuRole(QAction::AboutRole); + cmd = ActionManager::registerAction(tmpaction, Constants::ABOUT_QTCREATOR); + mhelp->addAction(cmd, Constants::G_HELP_ABOUT); + tmpaction->setEnabled(true); + connect(tmpaction, &QAction::triggered, this, &MainWindowPrivate::aboutQtCreator); + + //About Plugins Action + tmpaction = new QAction(Tr::tr("About &Plugins..."), this); + tmpaction->setMenuRole(QAction::ApplicationSpecificRole); + cmd = ActionManager::registerAction(tmpaction, Constants::ABOUT_PLUGINS); + mhelp->addAction(cmd, Constants::G_HELP_ABOUT); + tmpaction->setEnabled(true); + connect(tmpaction, &QAction::triggered, this, &MainWindowPrivate::aboutPlugins); + // About Qt Action + // tmpaction = new QAction(Tr::tr("About &Qt..."), this); + // cmd = ActionManager::registerAction(tmpaction, Constants:: ABOUT_QT); + // mhelp->addAction(cmd, Constants::G_HELP_ABOUT); + // tmpaction->setEnabled(true); + // connect(tmpaction, &QAction::triggered, qApp, &QApplication::aboutQt); + + // Change Log Action + tmpaction = new QAction(Tr::tr("Change Log..."), this); + tmpaction->setMenuRole(QAction::ApplicationSpecificRole); + cmd = ActionManager::registerAction(tmpaction, Constants::CHANGE_LOG); + mhelp->addAction(cmd, Constants::G_HELP_ABOUT); + tmpaction->setEnabled(true); + connect(tmpaction, &QAction::triggered, this, &MainWindowPrivate::changeLog); + + // Contact + tmpaction = new QAction(Tr::tr("Contact..."), this); + cmd = ActionManager::registerAction(tmpaction, "QtCreator.Contact"); + mhelp->addAction(cmd, Constants::G_HELP_ABOUT); + tmpaction->setEnabled(true); + connect(tmpaction, &QAction::triggered, this, &MainWindowPrivate::contact); + + // About sep + if (!HostOsInfo::isMacHost()) { // doesn't have the "About" actions in the Help menu + tmpaction = new QAction(this); + tmpaction->setSeparator(true); + cmd = ActionManager::registerAction(tmpaction, "QtCreator.Help.Sep.About"); + mhelp->addAction(cmd, Constants::G_HELP_ABOUT); + } +} + +void MainWindowPrivate::registerModeSelectorStyleActions() +{ + ActionContainer *mview = ActionManager::actionContainer(Constants::M_VIEW); + + // Cycle Mode Selector Styles + m_cycleModeSelectorStyleAction = new QAction(Tr::tr("Cycle Mode Selector Styles"), this); + ActionManager::registerAction(m_cycleModeSelectorStyleAction, Constants::CYCLE_MODE_SELECTOR_STYLE); + connect(m_cycleModeSelectorStyleAction, &QAction::triggered, this, [this] { + ModeManager::cycleModeStyle(); + updateModeSelectorStyleMenu(); + }); + + // Mode Selector Styles + ActionContainer *mmodeLayouts = ActionManager::createMenu(Constants::M_VIEW_MODESTYLES); + mview->addMenu(mmodeLayouts, Constants::G_VIEW_VIEWS); + QMenu *styleMenu = mmodeLayouts->menu(); + styleMenu->setTitle(Tr::tr("Mode Selector Style")); + auto *stylesGroup = new QActionGroup(styleMenu); + stylesGroup->setExclusive(true); + + m_setModeSelectorStyleIconsAndTextAction = stylesGroup->addAction(Tr::tr("Icons and Text")); + connect(m_setModeSelectorStyleIconsAndTextAction, &QAction::triggered, + [] { ModeManager::setModeStyle(ModeManager::Style::IconsAndText); }); + m_setModeSelectorStyleIconsAndTextAction->setCheckable(true); + m_setModeSelectorStyleIconsOnlyAction = stylesGroup->addAction(Tr::tr("Icons Only")); + connect(m_setModeSelectorStyleIconsOnlyAction, &QAction::triggered, + [] { ModeManager::setModeStyle(ModeManager::Style::IconsOnly); }); + m_setModeSelectorStyleIconsOnlyAction->setCheckable(true); + m_setModeSelectorStyleHiddenAction = stylesGroup->addAction(Tr::tr("Hidden")); + connect(m_setModeSelectorStyleHiddenAction, &QAction::triggered, + [] { ModeManager::setModeStyle(ModeManager::Style::Hidden); }); + m_setModeSelectorStyleHiddenAction->setCheckable(true); + + styleMenu->addActions(stylesGroup->actions()); +} + +void MainWindowPrivate::openFile() +{ + openFiles(EditorManager::getOpenFilePaths(), ICore::SwitchMode); +} + +static IDocumentFactory *findDocumentFactory(const QList &fileFactories, + const FilePath &filePath) +{ + const QString typeName = Utils::mimeTypeForFile(filePath, MimeMatchMode::MatchDefaultAndRemote) + .name(); + return Utils::findOrDefault(fileFactories, [typeName](IDocumentFactory *f) { + return f->mimeTypes().contains(typeName); + }); +} + +/*! + * \internal + * Either opens \a filePaths with editors or loads a project. + * + * \a flags can be used to stop on first failure, indicate that a file name + * might include line numbers and/or switch mode to edit mode. + * + * \a workingDirectory is used when files are opened by a remote client, since + * the file names are relative to the client working directory. + * + * Returns the first opened document. Required to support the \c -block flag + * for client mode. + * + * \sa IPlugin::remoteArguments() + */ +IDocument *MainWindow::openFiles(const FilePaths &filePaths, + ICore::OpenFilesFlags flags, + const FilePath &workingDirectory) +{ + return MainWindowPrivate::openFiles(filePaths, flags, workingDirectory); +} + +IDocument *MainWindowPrivate::openFiles(const FilePaths &filePaths, + ICore::OpenFilesFlags flags, + const FilePath &workingDirectory) +{ + const QList documentFactories = IDocumentFactory::allDocumentFactories(); + IDocument *res = nullptr; + + const FilePath workingDirBase = + workingDirectory.isEmpty() ? FilePath::currentWorkingPath() : workingDirectory; + for (const FilePath &filePath : filePaths) { + const FilePath absoluteFilePath = workingDirBase.resolvePath(filePath); + if (IDocumentFactory *documentFactory = findDocumentFactory(documentFactories, filePath)) { + IDocument *document = documentFactory->open(absoluteFilePath); + if (!document) { + if (flags & ICore::StopOnLoadFail) + return res; + } else { + if (!res) + res = document; + if (flags & ICore::SwitchMode) + ModeManager::activateMode(Id(Constants::MODE_EDIT)); + } + } else if (flags & (ICore::SwitchSplitIfAlreadyVisible | ICore::CanContainLineAndColumnNumbers) + || !res) { + QFlags emFlags; + if (flags & ICore::SwitchSplitIfAlreadyVisible) + emFlags |= EditorManager::SwitchSplitIfAlreadyVisible; + IEditor *editor = nullptr; + if (flags & ICore::CanContainLineAndColumnNumbers) { + const Link &link = Link::fromString(absoluteFilePath.toString(), true); + editor = EditorManager::openEditorAt(link, {}, emFlags); + } else { + editor = EditorManager::openEditor(absoluteFilePath, {}, emFlags); + } + if (!editor) { + if (flags & ICore::StopOnLoadFail) + return res; + } else if (!res) { + res = editor->document(); + } + } else { + auto factory = IEditorFactory::preferredEditorFactories(absoluteFilePath).value(0); + DocumentModelPrivate::addSuspendedDocument(absoluteFilePath, {}, + factory ? factory->id() : Id()); + } + } + return res; +} + +void MainWindowPrivate::setFocusToEditor() +{ + EditorManagerPrivate::doEscapeKeyFocusMoveMagic(); +} + +static void acceptModalDialogs() +{ + const QWidgetList topLevels = QApplication::topLevelWidgets(); + QList dialogsToClose; + for (QWidget *topLevel : topLevels) { + if (auto dialog = qobject_cast(topLevel)) { + if (dialog->isModal()) + dialogsToClose.append(dialog); + } + } + for (QDialog *dialog : dialogsToClose) + dialog->accept(); +} + +void MainWindow::exit() +{ + // this function is most likely called from a user action + // that is from an event handler of an object + // since on close we are going to delete everything + // so to prevent the deleting of that object we + // just append it + QMetaObject::invokeMethod( + this, + [this] { + // Modal dialogs block the close event. So close them, in case this was triggered from + // a RestartDialog in the settings dialog. + acceptModalDialogs(); + close(); + }, + Qt::QueuedConnection); +} + +void MainWindow::openFileWith() +{ + const FilePaths filePaths = EditorManager::getOpenFilePaths(); + for (const FilePath &filePath : filePaths) { + bool isExternal; + const Id editorId = EditorManagerPrivate::getOpenWithEditorId(filePath, &isExternal); + if (!editorId.isValid()) + continue; + if (isExternal) + EditorManager::openExternalEditor(filePath, editorId); + else + EditorManagerPrivate::openEditorWith(filePath, editorId); + } +} + +void MainWindowPrivate::openFileFromDevice() +{ + openFiles(EditorManager::getOpenFilePaths(QFileDialog::DontUseNativeDialog), ICore::SwitchMode); +} + +IContext *MainWindow::contextObject(QWidget *widget) const +{ + const auto it = d->m_contextWidgets.find(widget); + return it == d->m_contextWidgets.end() ? nullptr : it->second; +} + +void MainWindow::addContextObject(IContext *context) +{ + if (!context) + return; + QWidget *widget = context->widget(); + if (d->m_contextWidgets.find(widget) != d->m_contextWidgets.end()) + return; + + d->m_contextWidgets.insert({widget, context}); + connect(context, &QObject::destroyed, this, [this, context] { removeContextObject(context); }); +} + +void MainWindow::removeContextObject(IContext *context) +{ + if (!context) + return; + + disconnect(context, &QObject::destroyed, this, nullptr); + + const auto it = std::find_if(d->m_contextWidgets.cbegin(), + d->m_contextWidgets.cend(), + [context](const std::pair &v) { + return v.second == context; + }); + if (it == d->m_contextWidgets.cend()) + return; + + d->m_contextWidgets.erase(it); + if (d->m_activeContext.removeAll(context) > 0) + d->updateContextObject(d->m_activeContext); +} + +void MainWindowPrivate::updateFocusWidget(QWidget *old, QWidget *now) +{ + Q_UNUSED(old) + + // Prevent changing the context object just because the menu or a menu item is activated + if (qobject_cast(now) || qobject_cast(now)) + return; + + QList newContext; + if (QWidget *p = QApplication::focusWidget()) { + IContext *context = nullptr; + while (p) { + context = q->contextObject(p); + if (context) + newContext.append(context); + p = p->parentWidget(); + } + } + + // ignore toplevels that define no context, like popups without parent + if (!newContext.isEmpty() || QApplication::focusWidget() == q->focusWidget()) + updateContextObject(newContext); +} + +void MainWindowPrivate::updateContextObject(const QList &context) +{ + emit m_core->contextAboutToChange(context); + m_activeContext = context; + updateContext(); + if (debugMainWindow) { + qDebug() << "new context objects =" << context; + for (const IContext *c : context) + qDebug() << (c ? c->widget() : nullptr) << (c ? c->widget()->metaObject()->className() : nullptr); + } +} + +void MainWindow::aboutToShutdown() +{ + disconnect(qApp, &QApplication::focusChanged, d, &MainWindowPrivate::updateFocusWidget); + for (auto contextPair : d->m_contextWidgets) + disconnect(contextPair.second, &QObject::destroyed, this, nullptr); + d->m_activeContext.clear(); + hide(); +} + +void MainWindowPrivate::readSettings() +{ + QtcSettings *settings = PluginManager::settings(); + settings->beginGroup(QLatin1String(settingsGroup)); + + if (m_overrideColor.isValid()) { + StyleHelper::setBaseColor(m_overrideColor); + // Get adapted base color. + m_overrideColor = StyleHelper::baseColor(); + } else { + StyleHelper::setBaseColor(settings->value(colorKey, + QColor(StyleHelper::DEFAULT_BASE_COLOR)).value()); + } + + { + ModeManager::Style modeStyle = + ModeManager::Style(settings->value(modeSelectorLayoutKey, int(ModeManager::Style::IconsAndText)).toInt()); + + // Migrate legacy setting from Qt Creator 4.6 and earlier + static const char modeSelectorVisibleKey[] = "ModeSelectorVisible"; + if (!settings->contains(modeSelectorLayoutKey) && settings->contains(modeSelectorVisibleKey)) { + bool visible = settings->value(modeSelectorVisibleKey, true).toBool(); + modeStyle = visible ? ModeManager::Style::IconsAndText : ModeManager::Style::Hidden; + } + + ModeManager::setModeStyle(modeStyle); + updateModeSelectorStyleMenu(); + } + + if (globalMenuBar() && !globalMenuBar()->isNativeMenuBar()) { + const bool isVisible = settings->value(menubarVisibleKey, true).toBool(); + + globalMenuBar()->setVisible(isVisible); + if (m_toggleMenubarAction) + m_toggleMenubarAction->setChecked(isVisible); + } + + settings->endGroup(); + + EditorManagerPrivate::readSettings(); + m_leftNavigationWidget->restoreSettings(settings); + m_rightNavigationWidget->restoreSettings(settings); + m_rightPaneWidget->readSettings(settings); +} + +void MainWindow::saveSettings() +{ + QtcSettings *settings = PluginManager::settings(); + settings->beginGroup(QLatin1String(settingsGroup)); + + if (!(d->m_overrideColor.isValid() && StyleHelper::baseColor() == d->m_overrideColor)) + settings->setValueWithDefault(colorKey, + StyleHelper::requestedBaseColor(), + QColor(StyleHelper::DEFAULT_BASE_COLOR)); + + if (globalMenuBar() && !globalMenuBar()->isNativeMenuBar()) + settings->setValue(menubarVisibleKey, globalMenuBar()->isVisible()); + + settings->endGroup(); + + DocumentManager::saveSettings(); + ActionManager::saveSettings(); + EditorManagerPrivate::saveSettings(); + d->m_leftNavigationWidget->saveSettings(settings); + d->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 MainWindowPrivate::saveWindowSettings() +{ + QtcSettings *settings = PluginManager::settings(); + settings->beginGroup(settingsGroup); + + // On OS X applications usually do not restore their full screen state. + // To be able to restore the correct non-full screen geometry, we have to put + // the window out of full screen before saving the geometry. + // Works around QTBUG-45241 + if (Utils::HostOsInfo::isMacHost() && q->isFullScreen()) + q->setWindowState(q->windowState() & ~Qt::WindowFullScreen); + settings->setValue(windowGeometryKey, q->saveGeometry()); + settings->setValue(windowStateKey, q->saveState()); + settings->setValue(modeSelectorLayoutKey, int(ModeManager::modeStyle())); + + settings->endGroup(); +} + +void MainWindowPrivate::updateModeSelectorStyleMenu() +{ + switch (ModeManager::modeStyle()) { + case ModeManager::Style::IconsAndText: + m_setModeSelectorStyleIconsAndTextAction->setChecked(true); + break; + case ModeManager::Style::IconsOnly: + m_setModeSelectorStyleIconsOnlyAction->setChecked(true); + break; + case ModeManager::Style::Hidden: + m_setModeSelectorStyleHiddenAction->setChecked(true); + break; + } +} + +void MainWindow::updateAdditionalContexts(const Context &remove, const Context &add, + ICore::ContextPriority priority) +{ + for (const Id id : remove) { + if (!id.isValid()) + continue; + int index = d->m_lowPrioAdditionalContexts.indexOf(id); + if (index != -1) + d->m_lowPrioAdditionalContexts.removeAt(index); + index = d->m_highPrioAdditionalContexts.indexOf(id); + if (index != -1) + d->m_highPrioAdditionalContexts.removeAt(index); + } + + for (const Id id : add) { + if (!id.isValid()) + continue; + Context &cref = (priority == ICore::ContextPriority::High ? d->m_highPrioAdditionalContexts + : d->m_lowPrioAdditionalContexts); + if (!cref.contains(id)) + cref.prepend(id); + } + + d->updateContext(); +} + +void MainWindowPrivate::updateContext() +{ + Context contexts = m_highPrioAdditionalContexts; + + for (IContext *context : std::as_const(m_activeContext)) + contexts.add(context->context()); + + contexts.add(m_lowPrioAdditionalContexts); + + Context uniquecontexts; + for (const Id &id : std::as_const(contexts)) { + if (!uniquecontexts.contains(id)) + uniquecontexts.add(id); + } + + ActionManager::setContext(uniquecontexts); + emit m_core->contextChanged(uniquecontexts); +} + +void MainWindowPrivate::aboutToShowRecentFiles() +{ + ActionContainer *aci = ActionManager::actionContainer(Constants::M_FILE_RECENTFILES); + QMenu *menu = aci->menu(); + menu->clear(); + + const QList recentFiles = DocumentManager::recentFiles(); + for (int i = 0; i < recentFiles.count(); ++i) { + const DocumentManager::RecentFile file = recentFiles[i]; + + const QString filePath = Utils::quoteAmpersands(file.first.shortNativePath()); + const QString actionText = ActionManager::withNumberAccelerator(filePath, i + 1); + QAction *action = menu->addAction(actionText); + connect(action, &QAction::triggered, this, [file] { + EditorManager::openEditor(file.first, file.second); + }); + } + + bool hasRecentFiles = !recentFiles.isEmpty(); + menu->setEnabled(hasRecentFiles); + + // add the Clear Menu item + if (hasRecentFiles) { + menu->addSeparator(); + QAction *action = menu->addAction(Tr::tr(Constants::TR_CLEAR_MENU)); + connect(action, &QAction::triggered, + DocumentManager::instance(), &DocumentManager::clearRecentFiles); + } +} + +void MainWindowPrivate::aboutQtCreator() +{ + if (!m_versionDialog) { + m_versionDialog = new VersionDialog(q); + connect(m_versionDialog, &QDialog::finished, + this, &MainWindowPrivate::destroyVersionDialog); + ICore::registerWindow(m_versionDialog, Context("Core.VersionDialog")); + m_versionDialog->show(); + } else { + ICore::raiseWindow(m_versionDialog); + } +} + +void MainWindowPrivate::destroyVersionDialog() +{ + if (m_versionDialog) { + m_versionDialog->deleteLater(); + m_versionDialog = nullptr; + } +} + +void MainWindowPrivate::aboutPlugins() +{ + PluginDialog dialog(q); + dialog.exec(); +} + +class LogDialog : public QDialog +{ +public: + LogDialog(QWidget *parent) + : QDialog(parent) + {} + bool event(QEvent *event) override + { + if (event->type() == QEvent::ShortcutOverride) { + auto ke = static_cast(event); + if (ke->key() == Qt::Key_Escape && !ke->modifiers()) { + ke->accept(); + return true; + } + } + return QDialog::event(event); + } +}; + +void MainWindowPrivate::changeLog() +{ + static QPointer dialog; + if (dialog) { + ICore::raiseWindow(dialog); + return; + } + const FilePaths files = + ICore::resourcePath("changelog").dirEntries({{"changes-*"}, QDir::Files}); + static const QRegularExpression versionRegex("\\d+[.]\\d+[.]\\d+"); + using VersionFilePair = std::pair; + QList versionedFiles = Utils::transform(files, [](const FilePath &fp) { + const QRegularExpressionMatch match = versionRegex.match(fp.fileName()); + const QVersionNumber version = match.hasMatch() + ? QVersionNumber::fromString(match.captured()) + : QVersionNumber(); + return std::make_pair(version, fp); + }); + Utils::sort(versionedFiles, [](const VersionFilePair &a, const VersionFilePair &b) { + return a.first > b.first; + }); + + auto versionCombo = new QComboBox; + for (const VersionFilePair &f : versionedFiles) + versionCombo->addItem(f.first.toString()); + dialog = new LogDialog(ICore::dialogParent()); + auto versionLayout = new QHBoxLayout; + versionLayout->addWidget(new QLabel(Tr::tr("Version:"))); + versionLayout->addWidget(versionCombo); + versionLayout->addStretch(1); + auto showInExplorer = new QPushButton(FileUtils::msgGraphicalShellAction()); + versionLayout->addWidget(showInExplorer); + auto textEdit = new QTextBrowser; + textEdit->setOpenExternalLinks(true); + + auto aggregate = new Aggregation::Aggregate; + aggregate->add(textEdit); + aggregate->add(new Core::BaseTextFind(textEdit)); + + new MarkdownHighlighter(textEdit->document()); + + auto textEditWidget = new QFrame; + textEditWidget->setFrameStyle(QFrame::NoFrame); + auto findToolBar = new FindToolBarPlaceHolder(dialog); + findToolBar->setLightColored(true); + auto textEditLayout = new QVBoxLayout; + textEditLayout->setContentsMargins(0, 0, 0, 0); + textEditLayout->setSpacing(0); + textEditLayout->addWidget(textEdit); + textEditLayout->addWidget(findToolBar); + textEditWidget->setLayout(textEditLayout); + auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Close); + auto dialogLayout = new QVBoxLayout; + dialogLayout->addLayout(versionLayout); + dialogLayout->addWidget(textEditWidget); + dialogLayout->addWidget(buttonBox); + dialog->setLayout(dialogLayout); + dialog->resize(700, 600); + dialog->setWindowTitle(Tr::tr("Change Log")); + dialog->setAttribute(Qt::WA_DeleteOnClose); + ICore::registerWindow(dialog, Context("CorePlugin.VersionDialog")); + + connect(buttonBox, &QDialogButtonBox::rejected, dialog, &QDialog::close); + QPushButton *closeButton = buttonBox->button(QDialogButtonBox::Close); + if (QTC_GUARD(closeButton)) + closeButton->setDefault(true); // grab from "Open in Explorer" button + + const auto showLog = [textEdit, versionedFiles](int index) { + if (index < 0 || index >= versionedFiles.size()) + return; + const FilePath file = versionedFiles.at(index).second; + QString contents = QString::fromUtf8(file.fileContents().value_or(QByteArray())); + // (? matches; + for (const QRegularExpressionMatch &m : docexpr.globalMatch(contents)) + matches.append(m); + Utils::reverseForeach(matches, [&contents](const QRegularExpressionMatch &match) { + const QString qthelpUrl = "qthelp://org.qt-project.qtcreator/doc/" + match.captured(1); + if (!HelpManager::fileData(qthelpUrl).isEmpty()) + contents.replace(match.capturedStart(), match.capturedLength(), qthelpUrl); + }); + textEdit->setMarkdown(contents); + }; + connect(versionCombo, &QComboBox::currentIndexChanged, textEdit, showLog); + showLog(versionCombo->currentIndex()); + + connect(showInExplorer, &QPushButton::clicked, this, [versionCombo, versionedFiles] { + const int index = versionCombo->currentIndex(); + if (index >= 0 && index < versionedFiles.size()) + FileUtils::showInGraphicalShell(ICore::dialogParent(), versionedFiles.at(index).second); + else + FileUtils::showInGraphicalShell(ICore::dialogParent(), ICore::resourcePath("changelog")); + }); + + dialog->show(); +} + +void MainWindowPrivate::contact() +{ + QMessageBox dlg(QMessageBox::Information, Tr::tr("Contact"), + Tr::tr("

Qt Creator developers can be reached at the Qt Creator mailing list:

" + "%1" + "

or the #qt-creator channel on Libera.Chat IRC:

" + "%2" + "

Our bug tracker is located at %3.

" + "

Please use %4 for bigger chunks of text.

") + .arg("

    " + "" + "mailto:qt-creator@qt-project.org" + "

") + .arg("

    " + "" + "https://web.libera.chat/#qt-creator" + "

") + .arg("" + "https://bugreports.qt.io" + "") + .arg("" + "https://pastebin.com" + ""), + QMessageBox::Ok, q); + dlg.exec(); +} + +QPrinter *MainWindow::printer() const +{ + if (!d->m_printer) + d->m_printer = new QPrinter(QPrinter::HighResolution); + return d->m_printer; +} + +void MainWindowPrivate::restoreWindowState() +{ + NANOTRACE_SCOPE("Core", "MainWindow::restoreWindowState"); + QtcSettings *settings = PluginManager::settings(); + settings->beginGroup(settingsGroup); + if (!q->restoreGeometry(settings->value(windowGeometryKey).toByteArray())) + q->resize(1260, 700); // size without window decoration + q->restoreState(settings->value(windowStateKey).toByteArray()); + settings->endGroup(); + q->show(); + StatusBarManager::restoreSettings(); +} + +} // namespace Internal } // namespace Core diff --git a/src/plugins/coreplugin/icore.h b/src/plugins/coreplugin/icore.h index 3b8dfe8a0b3..95ba146cd32 100644 --- a/src/plugins/coreplugin/icore.h +++ b/src/plugins/coreplugin/icore.h @@ -6,6 +6,7 @@ #include "core_global.h" #include "icontext.h" +#include #include #include @@ -17,6 +18,7 @@ #include QT_BEGIN_NAMESPACE +class QColor; class QMainWindow; class QPrinter; class QStatusBar; @@ -26,25 +28,25 @@ QT_END_NAMESPACE namespace Utils { class InfoBar; } namespace Core { + class Context; +class IDocument; class IWizardFactory; +class NewDialog; namespace Internal { class MainWindow; class MainWindowPrivate; } // Internal -class NewDialog; - class CORE_EXPORT ICore : public QObject { Q_OBJECT friend class Internal::MainWindow; friend class Internal::MainWindowPrivate; - friend class IWizardFactory; - explicit ICore(Internal::MainWindow *mw); + ICore(); ~ICore() override; public: @@ -154,9 +156,63 @@ public: static void saveSettings(SaveSettingsReason reason); static void setNewDialogFactory(const std::function &newFactory); - -private: static void updateNewItemDialogState(); }; +namespace Internal { + +class MainWindow : public Utils::AppMainWindow +{ + Q_OBJECT + +public: + MainWindow(); + ~MainWindow() override; + + void init(); + void extensionsInitialized(); + void aboutToShutdown(); + + IContext *contextObject(QWidget *widget) const; + void addContextObject(IContext *context); + void removeContextObject(IContext *context); + + static IDocument *openFiles(const Utils::FilePaths &filePaths, + ICore::OpenFilesFlags flags, + const Utils::FilePath &workingDirectory = {}); + + QPrinter *printer() const; + IContext *currentContextObject() const; + QStatusBar *statusBar() const; + Utils::InfoBar *infoBar() const; + + void updateAdditionalContexts(const Context &remove, const Context &add, + ICore::ContextPriority priority); + + void setOverrideColor(const QColor &color); + + QStringList additionalAboutInformation() const; + void clearAboutInformation(); + void appendAboutInformation(const QString &line); + + void addPreCloseListener(const std::function &listener); + + void saveSettings(); + + void restart(); + + void restartTrimmer(); + +public slots: + static void openFileWith(); + void exit(); + +private: + void closeEvent(QCloseEvent *event) override; + void keyPressEvent(QKeyEvent *event) override; + void mousePressEvent(QMouseEvent *event) override; +}; + +} // namespace Internal + } // namespace Core diff --git a/src/plugins/coreplugin/mainwindow.cpp b/src/plugins/coreplugin/mainwindow.cpp index 852e33f5cfe..e69de29bb2d 100644 --- a/src/plugins/coreplugin/mainwindow.cpp +++ b/src/plugins/coreplugin/mainwindow.cpp @@ -1,1664 +0,0 @@ -// Copyright (C) 2016 The Qt Company Ltd. -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 - -#include "mainwindow.h" - -#include "actionmanager/actioncontainer.h" -#include "actionmanager/actionmanager.h" -#include "actionmanager/command.h" -#include "coreicons.h" -#include "coreplugintr.h" -#include "dialogs/externaltoolconfig.h" -#include "dialogs/shortcutsettings.h" -#include "documentmanager.h" -#include "editormanager/documentmodel_p.h" -#include "editormanager/editormanager.h" -#include "editormanager/editormanager_p.h" -#include "editormanager/ieditor.h" -#include "editormanager/ieditorfactory.h" -#include "editormanager/systemeditor.h" -#include "externaltoolmanager.h" -#include "fancytabwidget.h" -#include "fileutils.h" -#include "find/basetextfind.h" -#include "findplaceholder.h" -#include "helpmanager.h" -#include "icore.h" -#include "idocumentfactory.h" -#include "inavigationwidgetfactory.h" -#include "iwizardfactory.h" -#include "jsexpander.h" -#include "loggingviewer.h" -#include "manhattanstyle.h" -#include "messagemanager.h" -#include "mimetypesettings.h" -#include "modemanager.h" -#include "navigationwidget.h" -#include "outputpanemanager.h" -#include "plugindialog.h" -#include "progressmanager/progressmanager_p.h" -#include "progressmanager/progressview.h" -#include "rightpane.h" -#include "statusbarmanager.h" -#include "systemsettings.h" -#include "vcsmanager.h" -#include "versiondialog.h" -#include "windowsupport.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef Q_OS_LINUX -#include -#endif - -using namespace ExtensionSystem; -using namespace Utils; - -namespace Core { -namespace Internal { - -const char settingsGroup[] = "MainWindow"; -const char colorKey[] = "Color"; -const char windowGeometryKey[] = "WindowGeometry"; -const char windowStateKey[] = "WindowState"; -const char modeSelectorLayoutKey[] = "ModeSelectorLayout"; -const char menubarVisibleKey[] = "MenubarVisible"; - -static bool hideToolsMenu() -{ - return Core::ICore::settings()->value(Constants::SETTINGS_MENU_HIDE_TOOLS, false).toBool(); -} - -enum { debugMainWindow = 0 }; - - -class MainWindowPrivate : public QObject -{ -public: - explicit MainWindowPrivate(MainWindow *mainWindow) - : q(mainWindow) - {} - - ~MainWindowPrivate(); - - void init(); - - static void openFile(); - static IDocument *openFiles(const FilePaths &filePaths, ICore::OpenFilesFlags flags, - const FilePath &workingDirectory = {}); - void aboutToShowRecentFiles(); - - static void setFocusToEditor(); - void aboutQtCreator(); - void aboutPlugins(); - void changeLog(); - void contact(); - void updateFocusWidget(QWidget *old, QWidget *now); - NavigationWidget *navigationWidget(Side side) const; - void setSidebarVisible(bool visible, Side side); - void destroyVersionDialog(); - void openDroppedFiles(const QList &files); - void restoreWindowState(); - - void openFileFromDevice(); - - void updateContextObject(const QList &context); - void updateContext(); - - void registerDefaultContainers(); - void registerDefaultActions(); - void registerModeSelectorStyleActions(); - - void readSettings(); - void saveWindowSettings(); - - void updateModeSelectorStyleMenu(); - - MainWindow *q = nullptr; - ICore *m_coreImpl = nullptr; - QTimer m_trimTimer; - QStringList m_aboutInformation; - Context m_highPrioAdditionalContexts; - Context m_lowPrioAdditionalContexts{Constants::C_GLOBAL}; - mutable QPrinter *m_printer = nullptr; - WindowSupport *m_windowSupport = nullptr; - EditorManager *m_editorManager = nullptr; - ExternalToolManager *m_externalToolManager = nullptr; - MessageManager *m_messageManager = nullptr; - ProgressManagerPrivate *m_progressManager = nullptr; - JsExpander *m_jsExpander = nullptr; - VcsManager *m_vcsManager = nullptr; - ModeManager *m_modeManager = nullptr; - FancyTabWidget *m_modeStack = nullptr; - NavigationWidget *m_leftNavigationWidget = nullptr; - NavigationWidget *m_rightNavigationWidget = nullptr; - RightPaneWidget *m_rightPaneWidget = nullptr; - VersionDialog *m_versionDialog = nullptr; - - QList m_activeContext; - - std::unordered_map m_contextWidgets; - - ShortcutSettings *m_shortcutSettings = nullptr; - ToolSettings *m_toolSettings = nullptr; - MimeTypeSettings *m_mimeTypeSettings = nullptr; - SystemEditor *m_systemEditor = nullptr; - - // actions - QAction *m_focusToEditor = nullptr; - QAction *m_newAction = nullptr; - QAction *m_openAction = nullptr; - QAction *m_openWithAction = nullptr; - QAction *m_openFromDeviceAction = nullptr; - QAction *m_saveAllAction = nullptr; - QAction *m_exitAction = nullptr; - QAction *m_optionsAction = nullptr; - QAction *m_loggerAction = nullptr; - QAction *m_toggleLeftSideBarAction = nullptr; - QAction *m_toggleRightSideBarAction = nullptr; - QAction *m_toggleMenubarAction = nullptr; - QAction *m_cycleModeSelectorStyleAction = nullptr; - QAction *m_setModeSelectorStyleIconsAndTextAction = nullptr; - QAction *m_setModeSelectorStyleHiddenAction = nullptr; - QAction *m_setModeSelectorStyleIconsOnlyAction = nullptr; - QAction *m_themeAction = nullptr; - - QToolButton *m_toggleLeftSideBarButton = nullptr; - QToolButton *m_toggleRightSideBarButton = nullptr; - QColor m_overrideColor; - QList> m_preCloseListeners; -}; - -void MainWindowPrivate::init() -{ - m_coreImpl = new ICore(q); - m_progressManager = new ProgressManagerPrivate; - m_jsExpander = JsExpander::createGlobalJsExpander(); - m_vcsManager = new VcsManager; - m_modeStack = new FancyTabWidget(q); - m_shortcutSettings = new ShortcutSettings; - m_toolSettings = new ToolSettings; - m_mimeTypeSettings = new MimeTypeSettings; - m_systemEditor = new SystemEditor; - m_toggleLeftSideBarButton = new QToolButton; - m_toggleRightSideBarButton = new QToolButton; - - (void) new DocumentManager(q); - - HistoryCompleter::setSettings(PluginManager::settings()); - - if (HostOsInfo::isLinuxHost()) - QApplication::setWindowIcon(Icons::QTCREATORLOGO_BIG.icon()); - QString baseName = QApplication::style()->objectName(); - // Sometimes we get the standard windows 95 style as a fallback - if (HostOsInfo::isAnyUnixHost() && !HostOsInfo::isMacHost() - && baseName == QLatin1String("windows")) { - baseName = QLatin1String("fusion"); - } - - // if the user has specified as base style in the theme settings, - // prefer that - const QStringList available = QStyleFactory::keys(); - const QStringList styles = Utils::creatorTheme()->preferredStyles(); - for (const QString &s : styles) { - if (available.contains(s, Qt::CaseInsensitive)) { - baseName = s; - break; - } - } - - QApplication::setStyle(new ManhattanStyle(baseName)); - - m_modeManager = new ModeManager(q, m_modeStack); - connect(m_modeStack, &FancyTabWidget::topAreaClicked, this, [](Qt::MouseButton, Qt::KeyboardModifiers modifiers) { - if (modifiers & Qt::ShiftModifier) { - QColor color = QColorDialog::getColor(StyleHelper::requestedBaseColor(), ICore::dialogParent()); - if (color.isValid()) - StyleHelper::setBaseColor(color); - } - }); - - registerDefaultContainers(); - registerDefaultActions(); - - m_leftNavigationWidget = new NavigationWidget(m_toggleLeftSideBarAction, Side::Left); - m_rightNavigationWidget = new NavigationWidget(m_toggleRightSideBarAction, Side::Right); - m_rightPaneWidget = new RightPaneWidget(); - - m_messageManager = new MessageManager; - m_editorManager = new EditorManager(this); - m_externalToolManager = new ExternalToolManager(); - - m_progressManager->progressView()->setParent(q); - - connect(qApp, &QApplication::focusChanged, this, &MainWindowPrivate::updateFocusWidget); - - // Add small Toolbuttons for toggling the navigation widgets - StatusBarManager::addStatusBarWidget(m_toggleLeftSideBarButton, StatusBarManager::First); - int childsCount = q->statusBar()->findChildren(QString(), Qt::FindDirectChildrenOnly).count(); - q->statusBar()->insertPermanentWidget(childsCount - 1, m_toggleRightSideBarButton); // before QSizeGrip - -// setUnifiedTitleAndToolBarOnMac(true); - //if (HostOsInfo::isAnyUnixHost()) - //signal(SIGINT, handleSigInt); - - q->statusBar()->setProperty("p_styled", true); - - auto dropSupport = new DropSupport(q, [](QDropEvent *event, DropSupport *) { - return event->source() == nullptr; // only accept drops from the "outside" (e.g. file manager) - }); - connect(dropSupport, &DropSupport::filesDropped, - this, &MainWindowPrivate::openDroppedFiles); - - if (HostOsInfo::isLinuxHost()) { - m_trimTimer.setSingleShot(true); - m_trimTimer.setInterval(60000); - // glibc may not actually free memory in free(). -#ifdef Q_OS_LINUX - connect(&m_trimTimer, &QTimer::timeout, this, [] { malloc_trim(0); }); -#endif - } -} - -MainWindow::MainWindow() - : d(new MainWindowPrivate(this)) -{ - d->init(); // Separation needed for now as the call triggers other MainWindow calls. - - setWindowTitle(QGuiApplication::applicationDisplayName()); - setDockNestingEnabled(true); - setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea); - setCorner(Qt::BottomRightCorner, Qt::BottomDockWidgetArea); - - setCentralWidget(d->m_modeStack); -} - -NavigationWidget *MainWindowPrivate::navigationWidget(Side side) const -{ - return side == Side::Left ? m_leftNavigationWidget : m_rightNavigationWidget; -} - -void MainWindowPrivate::setSidebarVisible(bool visible, Side side) -{ - if (NavigationWidgetPlaceHolder::current(side)) - navigationWidget(side)->setShown(visible); -} - -void MainWindow::setOverrideColor(const QColor &color) -{ - d->m_overrideColor = color; -} - -QStringList MainWindow::additionalAboutInformation() const -{ - return d->m_aboutInformation; -} - -void MainWindow::clearAboutInformation() -{ - d->m_aboutInformation.clear(); -} - -void MainWindow::appendAboutInformation(const QString &line) -{ - d->m_aboutInformation.append(line); -} - -void MainWindow::addPreCloseListener(const std::function &listener) -{ - d->m_preCloseListeners.append(listener); -} - -MainWindow::~MainWindow() -{ - delete d; -} - -MainWindowPrivate::~MainWindowPrivate() -{ - // explicitly delete window support, because that calls methods from ICore that call methods - // from mainwindow, so mainwindow still needs to be alive - delete m_windowSupport; - m_windowSupport = nullptr; - - delete m_externalToolManager; - m_externalToolManager = nullptr; - delete m_messageManager; - m_messageManager = nullptr; - delete m_shortcutSettings; - m_shortcutSettings = nullptr; - delete m_toolSettings; - m_toolSettings = nullptr; - delete m_mimeTypeSettings; - m_mimeTypeSettings = nullptr; - delete m_systemEditor; - m_systemEditor = nullptr; - delete m_printer; - m_printer = nullptr; - delete m_vcsManager; - m_vcsManager = nullptr; - //we need to delete editormanager and statusbarmanager explicitly before the end of the destructor, - //because they might trigger stuff that tries to access data from editorwindow, like removeContextWidget - - // All modes are now gone - OutputPaneManager::destroy(); - - delete m_leftNavigationWidget; - delete m_rightNavigationWidget; - m_leftNavigationWidget = nullptr; - m_rightNavigationWidget = nullptr; - - delete m_editorManager; - m_editorManager = nullptr; - delete m_progressManager; - m_progressManager = nullptr; - - delete m_coreImpl; - m_coreImpl = nullptr; - - delete m_rightPaneWidget; - m_rightPaneWidget = nullptr; - - delete m_modeManager; - m_modeManager = nullptr; - - delete m_jsExpander; - m_jsExpander = nullptr; -} - -void MainWindow::init() -{ - d->m_progressManager->init(); // needs the status bar manager - MessageManager::init(); - OutputPaneManager::create(); -} - -void MainWindow::extensionsInitialized() -{ - EditorManagerPrivate::extensionsInitialized(); - MimeTypeSettings::restoreSettings(); - d->m_windowSupport = new WindowSupport(this, Context("Core.MainWindow")); - d->m_windowSupport->setCloseActionEnabled(false); - OutputPaneManager::initialize(); - VcsManager::extensionsInitialized(); - d->m_leftNavigationWidget->setFactories(INavigationWidgetFactory::allNavigationFactories()); - d->m_rightNavigationWidget->setFactories(INavigationWidgetFactory::allNavigationFactories()); - - ModeManager::extensionsInitialized(); - - d->readSettings(); - d->updateContext(); - - emit d->m_coreImpl->coreAboutToOpen(); - // Delay restoreWindowState, since it is overridden by LayoutRequest event - QMetaObject::invokeMethod(d, &MainWindowPrivate::restoreWindowState, Qt::QueuedConnection); - QMetaObject::invokeMethod(d->m_coreImpl, &ICore::coreOpened, Qt::QueuedConnection); -} - -static void setRestart(bool restart) -{ - qApp->setProperty("restart", restart); -} - -void MainWindow::restart() -{ - setRestart(true); - exit(); -} - -void MainWindow::restartTrimmer() -{ - if (HostOsInfo::isLinuxHost() && !d->m_trimTimer.isActive()) - d->m_trimTimer.start(); -} - -void MainWindow::closeEvent(QCloseEvent *event) -{ - const auto cancelClose = [event] { - event->ignore(); - setRestart(false); - }; - - // work around QTBUG-43344 - static bool alreadyClosed = false; - if (alreadyClosed) { - event->accept(); - return; - } - - if (systemSettings().askBeforeExit() - && (QMessageBox::question(this, - Tr::tr("Exit %1?").arg(QGuiApplication::applicationDisplayName()), - Tr::tr("Exit %1?").arg(QGuiApplication::applicationDisplayName()), - QMessageBox::Yes | QMessageBox::No, - QMessageBox::No) - == QMessageBox::No)) { - event->ignore(); - return; - } - - ICore::saveSettings(ICore::MainWindowClosing); - - // Save opened files - if (!DocumentManager::saveAllModifiedDocuments()) { - cancelClose(); - return; - } - - const QList> listeners = d->m_preCloseListeners; - for (const std::function &listener : listeners) { - if (!listener()) { - cancelClose(); - return; - } - } - - emit d->m_coreImpl->coreAboutToClose(); - - d->saveWindowSettings(); - - d->m_leftNavigationWidget->closeSubWidgets(); - d->m_rightNavigationWidget->closeSubWidgets(); - - event->accept(); - alreadyClosed = true; -} - -void MainWindow::keyPressEvent(QKeyEvent *event) -{ - restartTrimmer(); - AppMainWindow::keyPressEvent(event); -} - -void MainWindow::mousePressEvent(QMouseEvent *event) -{ - restartTrimmer(); - AppMainWindow::mousePressEvent(event); -} - -void MainWindowPrivate::openDroppedFiles(const QList &files) -{ - q->raiseWindow(); - const FilePaths filePaths = Utils::transform(files, &DropSupport::FileSpec::filePath); - q->openFiles(filePaths, ICore::SwitchMode); -} - -IContext *MainWindow::currentContextObject() const -{ - return d->m_activeContext.isEmpty() ? nullptr : d->m_activeContext.first(); -} - -QStatusBar *MainWindow::statusBar() const -{ - return d->m_modeStack->statusBar(); -} - -InfoBar *MainWindow::infoBar() const -{ - return d->m_modeStack->infoBar(); -} - -void MainWindowPrivate::registerDefaultContainers() -{ - ActionContainer *menubar = ActionManager::createMenuBar(Constants::MENU_BAR); - - if (!HostOsInfo::isMacHost()) // System menu bar on Mac - q->setMenuBar(menubar->menuBar()); - menubar->appendGroup(Constants::G_FILE); - menubar->appendGroup(Constants::G_EDIT); - menubar->appendGroup(Constants::G_VIEW); - menubar->appendGroup(Constants::G_TOOLS); - menubar->appendGroup(Constants::G_WINDOW); - menubar->appendGroup(Constants::G_HELP); - - // File Menu - ActionContainer *filemenu = ActionManager::createMenu(Constants::M_FILE); - menubar->addMenu(filemenu, Constants::G_FILE); - filemenu->menu()->setTitle(Tr::tr("&File")); - filemenu->appendGroup(Constants::G_FILE_NEW); - filemenu->appendGroup(Constants::G_FILE_OPEN); - filemenu->appendGroup(Constants::G_FILE_SESSION); - filemenu->appendGroup(Constants::G_FILE_PROJECT); - filemenu->appendGroup(Constants::G_FILE_SAVE); - filemenu->appendGroup(Constants::G_FILE_EXPORT); - filemenu->appendGroup(Constants::G_FILE_CLOSE); - filemenu->appendGroup(Constants::G_FILE_PRINT); - filemenu->appendGroup(Constants::G_FILE_OTHER); - connect(filemenu->menu(), &QMenu::aboutToShow, this, &MainWindowPrivate::aboutToShowRecentFiles); - - - // Edit Menu - ActionContainer *medit = ActionManager::createMenu(Constants::M_EDIT); - menubar->addMenu(medit, Constants::G_EDIT); - medit->menu()->setTitle(Tr::tr("&Edit")); - medit->appendGroup(Constants::G_EDIT_UNDOREDO); - medit->appendGroup(Constants::G_EDIT_COPYPASTE); - medit->appendGroup(Constants::G_EDIT_SELECTALL); - medit->appendGroup(Constants::G_EDIT_ADVANCED); - medit->appendGroup(Constants::G_EDIT_FIND); - medit->appendGroup(Constants::G_EDIT_OTHER); - - ActionContainer *mview = ActionManager::createMenu(Constants::M_VIEW); - menubar->addMenu(mview, Constants::G_VIEW); - mview->menu()->setTitle(Tr::tr("&View")); - mview->appendGroup(Constants::G_VIEW_VIEWS); - mview->appendGroup(Constants::G_VIEW_PANES); - - // Tools Menu - ActionContainer *ac = ActionManager::createMenu(Constants::M_TOOLS); - ac->setParent(this); - if (!hideToolsMenu()) - menubar->addMenu(ac, Constants::G_TOOLS); - - ac->menu()->setTitle(Tr::tr("&Tools")); - - // Window Menu - ActionContainer *mwindow = ActionManager::createMenu(Constants::M_WINDOW); - menubar->addMenu(mwindow, Constants::G_WINDOW); - mwindow->menu()->setTitle(Tr::tr("&Window")); - mwindow->appendGroup(Constants::G_WINDOW_SIZE); - mwindow->appendGroup(Constants::G_WINDOW_SPLIT); - mwindow->appendGroup(Constants::G_WINDOW_NAVIGATE); - mwindow->appendGroup(Constants::G_WINDOW_LIST); - mwindow->appendGroup(Constants::G_WINDOW_OTHER); - - // Help Menu - ac = ActionManager::createMenu(Constants::M_HELP); - menubar->addMenu(ac, Constants::G_HELP); - ac->menu()->setTitle(Tr::tr("&Help")); - Theme::setHelpMenu(ac->menu()); - ac->appendGroup(Constants::G_HELP_HELP); - ac->appendGroup(Constants::G_HELP_SUPPORT); - ac->appendGroup(Constants::G_HELP_ABOUT); - ac->appendGroup(Constants::G_HELP_UPDATES); - - // macOS touch bar - ac = ActionManager::createTouchBar(Constants::TOUCH_BAR, - QIcon(), - "Main TouchBar" /*never visible*/); - ac->appendGroup(Constants::G_TOUCHBAR_HELP); - ac->appendGroup(Constants::G_TOUCHBAR_NAVIGATION); - ac->appendGroup(Constants::G_TOUCHBAR_EDITOR); - ac->appendGroup(Constants::G_TOUCHBAR_OTHER); - ac->touchBar()->setApplicationTouchBar(); -} - -static QMenuBar *globalMenuBar() -{ - return ActionManager::actionContainer(Constants::MENU_BAR)->menuBar(); -} - -void MainWindowPrivate::registerDefaultActions() -{ - ActionContainer *mfile = ActionManager::actionContainer(Constants::M_FILE); - ActionContainer *medit = ActionManager::actionContainer(Constants::M_EDIT); - ActionContainer *mview = ActionManager::actionContainer(Constants::M_VIEW); - ActionContainer *mtools = ActionManager::actionContainer(Constants::M_TOOLS); - ActionContainer *mwindow = ActionManager::actionContainer(Constants::M_WINDOW); - ActionContainer *mhelp = ActionManager::actionContainer(Constants::M_HELP); - - // File menu separators - mfile->addSeparator(Constants::G_FILE_SAVE); - mfile->addSeparator(Constants::G_FILE_EXPORT); - mfile->addSeparator(Constants::G_FILE_PRINT); - mfile->addSeparator(Constants::G_FILE_CLOSE); - mfile->addSeparator(Constants::G_FILE_OTHER); - // Edit menu separators - medit->addSeparator(Constants::G_EDIT_COPYPASTE); - medit->addSeparator(Constants::G_EDIT_SELECTALL); - medit->addSeparator(Constants::G_EDIT_FIND); - medit->addSeparator(Constants::G_EDIT_ADVANCED); - - // Return to editor shortcut: Note this requires Qt to fix up - // handling of shortcut overrides in menus, item views, combos.... - m_focusToEditor = new QAction(Tr::tr("Return to Editor"), this); - Command *cmd = ActionManager::registerAction(m_focusToEditor, Constants::S_RETURNTOEDITOR); - cmd->setDefaultKeySequence(QKeySequence(Qt::Key_Escape)); - connect(m_focusToEditor, &QAction::triggered, this, &MainWindowPrivate::setFocusToEditor); - - // New File Action - QIcon icon = Icon::fromTheme("document-new"); - - m_newAction = new QAction(icon, Tr::tr("&New Project..."), this); - cmd = ActionManager::registerAction(m_newAction, Constants::NEW); - cmd->setDefaultKeySequence(QKeySequence("Ctrl+Shift+N")); - mfile->addAction(cmd, Constants::G_FILE_NEW); - connect(m_newAction, &QAction::triggered, this, [] { - if (!ICore::isNewItemDialogRunning()) { - ICore::showNewItemDialog( - Tr::tr("New Project", "Title of dialog"), - Utils::filtered(Core::IWizardFactory::allWizardFactories(), - Utils::equal(&Core::IWizardFactory::kind, - Core::IWizardFactory::ProjectWizard)), - FilePath()); - } else { - ICore::raiseWindow(ICore::newItemDialog()); - } - }); - - auto action = new QAction(icon, Tr::tr("New File..."), this); - cmd = ActionManager::registerAction(action, Constants::NEW_FILE); - cmd->setDefaultKeySequence(QKeySequence::New); - mfile->addAction(cmd, Constants::G_FILE_NEW); - connect(action, &QAction::triggered, this, [] { - if (!ICore::isNewItemDialogRunning()) { - ICore::showNewItemDialog(Tr::tr("New File", "Title of dialog"), - Utils::filtered(Core::IWizardFactory::allWizardFactories(), - Utils::equal(&Core::IWizardFactory::kind, - Core::IWizardFactory::FileWizard)), - FilePath()); - } else { - ICore::raiseWindow(ICore::newItemDialog()); - } - }); - - // Open Action - icon = Icon::fromTheme("document-open"); - m_openAction = new QAction(icon, Tr::tr("&Open File or Project..."), this); - cmd = ActionManager::registerAction(m_openAction, Constants::OPEN); - cmd->setDefaultKeySequence(QKeySequence::Open); - mfile->addAction(cmd, Constants::G_FILE_OPEN); - connect(m_openAction, &QAction::triggered, this, &MainWindowPrivate::openFile); - - // Open With Action - m_openWithAction = new QAction(Tr::tr("Open File &With..."), this); - cmd = ActionManager::registerAction(m_openWithAction, Constants::OPEN_WITH); - mfile->addAction(cmd, Constants::G_FILE_OPEN); - connect(m_openWithAction, &QAction::triggered, this, &MainWindow::openFileWith); - - if (FSEngine::isAvailable()) { - // Open From Device Action - m_openFromDeviceAction = new QAction(Tr::tr("Open From Device..."), this); - cmd = ActionManager::registerAction(m_openFromDeviceAction, Constants::OPEN_FROM_DEVICE); - mfile->addAction(cmd, Constants::G_FILE_OPEN); - connect(m_openFromDeviceAction, &QAction::triggered, this, &MainWindowPrivate::openFileFromDevice); - } - - // File->Recent Files Menu - ActionContainer *ac = ActionManager::createMenu(Constants::M_FILE_RECENTFILES); - mfile->addMenu(ac, Constants::G_FILE_OPEN); - ac->menu()->setTitle(Tr::tr("Recent &Files")); - ac->setOnAllDisabledBehavior(ActionContainer::Show); - - // Save Action - icon = Icon::fromTheme("document-save"); - QAction *tmpaction = new QAction(icon, Tr::tr("&Save"), this); - tmpaction->setEnabled(false); - cmd = ActionManager::registerAction(tmpaction, Constants::SAVE); - cmd->setDefaultKeySequence(QKeySequence::Save); - cmd->setAttribute(Command::CA_UpdateText); - cmd->setDescription(Tr::tr("Save")); - mfile->addAction(cmd, Constants::G_FILE_SAVE); - - // Save As Action - icon = Icon::fromTheme("document-save-as"); - tmpaction = new QAction(icon, Tr::tr("Save &As..."), this); - tmpaction->setEnabled(false); - cmd = ActionManager::registerAction(tmpaction, Constants::SAVEAS); - cmd->setDefaultKeySequence(QKeySequence(useMacShortcuts ? Tr::tr("Ctrl+Shift+S") : QString())); - cmd->setAttribute(Command::CA_UpdateText); - cmd->setDescription(Tr::tr("Save As...")); - mfile->addAction(cmd, Constants::G_FILE_SAVE); - - // SaveAll Action - DocumentManager::registerSaveAllAction(); - - // Print Action - icon = Icon::fromTheme("document-print"); - tmpaction = new QAction(icon, Tr::tr("&Print..."), this); - tmpaction->setEnabled(false); - cmd = ActionManager::registerAction(tmpaction, Constants::PRINT); - cmd->setDefaultKeySequence(QKeySequence::Print); - mfile->addAction(cmd, Constants::G_FILE_PRINT); - - // Exit Action - icon = Icon::fromTheme("application-exit"); - m_exitAction = new QAction(icon, Tr::tr("E&xit"), this); - m_exitAction->setMenuRole(QAction::QuitRole); - cmd = ActionManager::registerAction(m_exitAction, Constants::EXIT); - cmd->setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Q"))); - mfile->addAction(cmd, Constants::G_FILE_OTHER); - connect(m_exitAction, &QAction::triggered, q, &MainWindow::exit); - - // Undo Action - icon = Icon::fromTheme("edit-undo"); - tmpaction = new QAction(icon, Tr::tr("&Undo"), this); - cmd = ActionManager::registerAction(tmpaction, Constants::UNDO); - cmd->setDefaultKeySequence(QKeySequence::Undo); - cmd->setAttribute(Command::CA_UpdateText); - cmd->setDescription(Tr::tr("Undo")); - medit->addAction(cmd, Constants::G_EDIT_UNDOREDO); - tmpaction->setEnabled(false); - - // Redo Action - icon = Icon::fromTheme("edit-redo"); - tmpaction = new QAction(icon, Tr::tr("&Redo"), this); - cmd = ActionManager::registerAction(tmpaction, Constants::REDO); - cmd->setDefaultKeySequence(QKeySequence::Redo); - cmd->setAttribute(Command::CA_UpdateText); - cmd->setDescription(Tr::tr("Redo")); - medit->addAction(cmd, Constants::G_EDIT_UNDOREDO); - tmpaction->setEnabled(false); - - // Cut Action - icon = Icon::fromTheme("edit-cut"); - tmpaction = new QAction(icon, Tr::tr("Cu&t"), this); - cmd = ActionManager::registerAction(tmpaction, Constants::CUT); - cmd->setDefaultKeySequence(QKeySequence::Cut); - medit->addAction(cmd, Constants::G_EDIT_COPYPASTE); - tmpaction->setEnabled(false); - - // Copy Action - icon = Icon::fromTheme("edit-copy"); - tmpaction = new QAction(icon, Tr::tr("&Copy"), this); - cmd = ActionManager::registerAction(tmpaction, Constants::COPY); - cmd->setDefaultKeySequence(QKeySequence::Copy); - medit->addAction(cmd, Constants::G_EDIT_COPYPASTE); - tmpaction->setEnabled(false); - - // Paste Action - icon = Icon::fromTheme("edit-paste"); - tmpaction = new QAction(icon, Tr::tr("&Paste"), this); - cmd = ActionManager::registerAction(tmpaction, Constants::PASTE); - cmd->setDefaultKeySequence(QKeySequence::Paste); - medit->addAction(cmd, Constants::G_EDIT_COPYPASTE); - tmpaction->setEnabled(false); - - // Select All - icon = Icon::fromTheme("edit-select-all"); - tmpaction = new QAction(icon, Tr::tr("Select &All"), this); - cmd = ActionManager::registerAction(tmpaction, Constants::SELECTALL); - cmd->setDefaultKeySequence(QKeySequence::SelectAll); - medit->addAction(cmd, Constants::G_EDIT_SELECTALL); - tmpaction->setEnabled(false); - - // Goto Action - icon = Icon::fromTheme("go-jump"); - tmpaction = new QAction(icon, Tr::tr("&Go to Line..."), this); - cmd = ActionManager::registerAction(tmpaction, Constants::GOTO); - cmd->setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+L"))); - medit->addAction(cmd, Constants::G_EDIT_OTHER); - tmpaction->setEnabled(false); - - // Zoom In Action - icon = Icon::fromTheme("zoom-in"); - tmpaction = new QAction(icon, Tr::tr("Zoom In"), this); - cmd = ActionManager::registerAction(tmpaction, Constants::ZOOM_IN); - cmd->setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl++"))); - tmpaction->setEnabled(false); - - // Zoom Out Action - icon = Icon::fromTheme("zoom-out"); - tmpaction = new QAction(icon, Tr::tr("Zoom Out"), this); - cmd = ActionManager::registerAction(tmpaction, Constants::ZOOM_OUT); - if (useMacShortcuts) - cmd->setDefaultKeySequences({QKeySequence(Tr::tr("Ctrl+-")), QKeySequence(Tr::tr("Ctrl+Shift+-"))}); - else - cmd->setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+-"))); - tmpaction->setEnabled(false); - - // Zoom Reset Action - icon = Icon::fromTheme("zoom-original"); - tmpaction = new QAction(icon, Tr::tr("Original Size"), this); - cmd = ActionManager::registerAction(tmpaction, Constants::ZOOM_RESET); - cmd->setDefaultKeySequence(QKeySequence(Core::useMacShortcuts ? Tr::tr("Meta+0") : Tr::tr("Ctrl+0"))); - tmpaction->setEnabled(false); - - // Debug Qt Creator menu - mtools->appendGroup(Constants::G_TOOLS_DEBUG); - ActionContainer *mtoolsdebug = ActionManager::createMenu(Constants::M_TOOLS_DEBUG); - mtoolsdebug->menu()->setTitle(Tr::tr("Debug %1").arg(QGuiApplication::applicationDisplayName())); - mtools->addMenu(mtoolsdebug, Constants::G_TOOLS_DEBUG); - - m_loggerAction = new QAction(Tr::tr("Show Logs..."), this); - cmd = ActionManager::registerAction(m_loggerAction, Constants::LOGGER); - mtoolsdebug->addAction(cmd); - connect(m_loggerAction, &QAction::triggered, this, [] { LoggingViewer::showLoggingView(); }); - - // Options Action - medit->appendGroup(Constants::G_EDIT_PREFERENCES); - medit->addSeparator(Constants::G_EDIT_PREFERENCES); - - m_optionsAction = new QAction(Tr::tr("Pr&eferences..."), this); - m_optionsAction->setMenuRole(QAction::PreferencesRole); - cmd = ActionManager::registerAction(m_optionsAction, Constants::OPTIONS); - cmd->setDefaultKeySequence(QKeySequence::Preferences); - medit->addAction(cmd, Constants::G_EDIT_PREFERENCES); - connect(m_optionsAction, &QAction::triggered, this, [] { ICore::showOptionsDialog(Id()); }); - - mwindow->addSeparator(Constants::G_WINDOW_LIST); - - if (useMacShortcuts) { - // Minimize Action - QAction *minimizeAction = new QAction(Tr::tr("Minimize"), this); - minimizeAction->setEnabled(false); // actual implementation in WindowSupport - cmd = ActionManager::registerAction(minimizeAction, Constants::MINIMIZE_WINDOW); - cmd->setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+M"))); - mwindow->addAction(cmd, Constants::G_WINDOW_SIZE); - - // Zoom Action - QAction *zoomAction = new QAction(Tr::tr("Zoom"), this); - zoomAction->setEnabled(false); // actual implementation in WindowSupport - cmd = ActionManager::registerAction(zoomAction, Constants::ZOOM_WINDOW); - mwindow->addAction(cmd, Constants::G_WINDOW_SIZE); - } - - // Full Screen Action - QAction *toggleFullScreenAction = new QAction(Tr::tr("Full Screen"), this); - toggleFullScreenAction->setCheckable(!HostOsInfo::isMacHost()); - toggleFullScreenAction->setEnabled(false); // actual implementation in WindowSupport - cmd = ActionManager::registerAction(toggleFullScreenAction, Constants::TOGGLE_FULLSCREEN); - cmd->setDefaultKeySequence(QKeySequence(useMacShortcuts ? Tr::tr("Ctrl+Meta+F") : Tr::tr("Ctrl+Shift+F11"))); - if (HostOsInfo::isMacHost()) - cmd->setAttribute(Command::CA_UpdateText); - mwindow->addAction(cmd, Constants::G_WINDOW_SIZE); - - if (useMacShortcuts) { - mwindow->addSeparator(Constants::G_WINDOW_SIZE); - - QAction *closeAction = new QAction(Tr::tr("Close Window"), this); - closeAction->setEnabled(false); - cmd = ActionManager::registerAction(closeAction, Constants::CLOSE_WINDOW); - cmd->setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Meta+W"))); - mwindow->addAction(cmd, Constants::G_WINDOW_SIZE); - - mwindow->addSeparator(Constants::G_WINDOW_SIZE); - } - - // Show Left Sidebar Action - m_toggleLeftSideBarAction = new QAction(Utils::Icons::TOGGLE_LEFT_SIDEBAR.icon(), - Tr::tr(Constants::TR_SHOW_LEFT_SIDEBAR), - this); - m_toggleLeftSideBarAction->setCheckable(true); - cmd = ActionManager::registerAction(m_toggleLeftSideBarAction, Constants::TOGGLE_LEFT_SIDEBAR); - cmd->setAttribute(Command::CA_UpdateText); - cmd->setDefaultKeySequence(QKeySequence(useMacShortcuts ? Tr::tr("Ctrl+0") : Tr::tr("Alt+0"))); - connect(m_toggleLeftSideBarAction, &QAction::triggered, - this, [this](bool visible) { setSidebarVisible(visible, Side::Left); }); - ProxyAction *toggleLeftSideBarProxyAction = - ProxyAction::proxyActionWithIcon(cmd->action(), Utils::Icons::TOGGLE_LEFT_SIDEBAR_TOOLBAR.icon()); - m_toggleLeftSideBarButton->setDefaultAction(toggleLeftSideBarProxyAction); - mview->addAction(cmd, Constants::G_VIEW_VIEWS); - m_toggleLeftSideBarAction->setEnabled(false); - - // Show Right Sidebar Action - m_toggleRightSideBarAction = new QAction(Utils::Icons::TOGGLE_RIGHT_SIDEBAR.icon(), - Tr::tr(Constants::TR_SHOW_RIGHT_SIDEBAR), - this); - m_toggleRightSideBarAction->setCheckable(true); - cmd = ActionManager::registerAction(m_toggleRightSideBarAction, Constants::TOGGLE_RIGHT_SIDEBAR); - cmd->setAttribute(Command::CA_UpdateText); - cmd->setDefaultKeySequence(QKeySequence(useMacShortcuts ? Tr::tr("Ctrl+Shift+0") : Tr::tr("Alt+Shift+0"))); - connect(m_toggleRightSideBarAction, &QAction::triggered, - this, [this](bool visible) { setSidebarVisible(visible, Side::Right); }); - ProxyAction *toggleRightSideBarProxyAction = - ProxyAction::proxyActionWithIcon(cmd->action(), Utils::Icons::TOGGLE_RIGHT_SIDEBAR_TOOLBAR.icon()); - m_toggleRightSideBarButton->setDefaultAction(toggleRightSideBarProxyAction); - mview->addAction(cmd, Constants::G_VIEW_VIEWS); - m_toggleRightSideBarButton->setEnabled(false); - - // Show Menubar Action - if (globalMenuBar() && !globalMenuBar()->isNativeMenuBar()) { - m_toggleMenubarAction = new QAction(Tr::tr("Show Menubar"), this); - m_toggleMenubarAction->setCheckable(true); - cmd = ActionManager::registerAction(m_toggleMenubarAction, Constants::TOGGLE_MENUBAR); - cmd->setDefaultKeySequence(QKeySequence(Tr::tr("Ctrl+Alt+M"))); - connect(m_toggleMenubarAction, &QAction::toggled, this, [cmd](bool visible) { - if (!visible) { - CheckableMessageBox::information( - Core::ICore::dialogParent(), - Tr::tr("Hide Menubar"), - Tr::tr( - "This will hide the menu bar completely. You can show it again by typing ") - + cmd->keySequence().toString(QKeySequence::NativeText), - QString("ToogleMenuBarHint")); - } - globalMenuBar()->setVisible(visible); - }); - mview->addAction(cmd, Constants::G_VIEW_VIEWS); - } - - registerModeSelectorStyleActions(); - - // Window->Views - ActionContainer *mviews = ActionManager::createMenu(Constants::M_VIEW_VIEWS); - mview->addMenu(mviews, Constants::G_VIEW_VIEWS); - mviews->menu()->setTitle(Tr::tr("&Views")); - - // "Help" separators - mhelp->addSeparator(Constants::G_HELP_SUPPORT); - if (!HostOsInfo::isMacHost()) - mhelp->addSeparator(Constants::G_HELP_ABOUT); - - // About IDE Action - icon = Icon::fromTheme("help-about"); - if (HostOsInfo::isMacHost()) - tmpaction = new QAction(icon, - Tr::tr("About &%1").arg(QGuiApplication::applicationDisplayName()), - this); // it's convention not to add dots to the about menu - else - tmpaction - = new QAction(icon, - Tr::tr("About &%1...").arg(QGuiApplication::applicationDisplayName()), - this); - tmpaction->setMenuRole(QAction::AboutRole); - cmd = ActionManager::registerAction(tmpaction, Constants::ABOUT_QTCREATOR); - mhelp->addAction(cmd, Constants::G_HELP_ABOUT); - tmpaction->setEnabled(true); - connect(tmpaction, &QAction::triggered, this, &MainWindowPrivate::aboutQtCreator); - - //About Plugins Action - tmpaction = new QAction(Tr::tr("About &Plugins..."), this); - tmpaction->setMenuRole(QAction::ApplicationSpecificRole); - cmd = ActionManager::registerAction(tmpaction, Constants::ABOUT_PLUGINS); - mhelp->addAction(cmd, Constants::G_HELP_ABOUT); - tmpaction->setEnabled(true); - connect(tmpaction, &QAction::triggered, this, &MainWindowPrivate::aboutPlugins); - // About Qt Action - // tmpaction = new QAction(Tr::tr("About &Qt..."), this); - // cmd = ActionManager::registerAction(tmpaction, Constants:: ABOUT_QT); - // mhelp->addAction(cmd, Constants::G_HELP_ABOUT); - // tmpaction->setEnabled(true); - // connect(tmpaction, &QAction::triggered, qApp, &QApplication::aboutQt); - - // Change Log Action - tmpaction = new QAction(Tr::tr("Change Log..."), this); - tmpaction->setMenuRole(QAction::ApplicationSpecificRole); - cmd = ActionManager::registerAction(tmpaction, Constants::CHANGE_LOG); - mhelp->addAction(cmd, Constants::G_HELP_ABOUT); - tmpaction->setEnabled(true); - connect(tmpaction, &QAction::triggered, this, &MainWindowPrivate::changeLog); - - // Contact - tmpaction = new QAction(Tr::tr("Contact..."), this); - cmd = ActionManager::registerAction(tmpaction, "QtCreator.Contact"); - mhelp->addAction(cmd, Constants::G_HELP_ABOUT); - tmpaction->setEnabled(true); - connect(tmpaction, &QAction::triggered, this, &MainWindowPrivate::contact); - - // About sep - if (!HostOsInfo::isMacHost()) { // doesn't have the "About" actions in the Help menu - tmpaction = new QAction(this); - tmpaction->setSeparator(true); - cmd = ActionManager::registerAction(tmpaction, "QtCreator.Help.Sep.About"); - mhelp->addAction(cmd, Constants::G_HELP_ABOUT); - } -} - -void MainWindowPrivate::registerModeSelectorStyleActions() -{ - ActionContainer *mview = ActionManager::actionContainer(Constants::M_VIEW); - - // Cycle Mode Selector Styles - m_cycleModeSelectorStyleAction = new QAction(Tr::tr("Cycle Mode Selector Styles"), this); - ActionManager::registerAction(m_cycleModeSelectorStyleAction, Constants::CYCLE_MODE_SELECTOR_STYLE); - connect(m_cycleModeSelectorStyleAction, &QAction::triggered, this, [this] { - ModeManager::cycleModeStyle(); - updateModeSelectorStyleMenu(); - }); - - // Mode Selector Styles - ActionContainer *mmodeLayouts = ActionManager::createMenu(Constants::M_VIEW_MODESTYLES); - mview->addMenu(mmodeLayouts, Constants::G_VIEW_VIEWS); - QMenu *styleMenu = mmodeLayouts->menu(); - styleMenu->setTitle(Tr::tr("Mode Selector Style")); - auto *stylesGroup = new QActionGroup(styleMenu); - stylesGroup->setExclusive(true); - - m_setModeSelectorStyleIconsAndTextAction = stylesGroup->addAction(Tr::tr("Icons and Text")); - connect(m_setModeSelectorStyleIconsAndTextAction, &QAction::triggered, - [] { ModeManager::setModeStyle(ModeManager::Style::IconsAndText); }); - m_setModeSelectorStyleIconsAndTextAction->setCheckable(true); - m_setModeSelectorStyleIconsOnlyAction = stylesGroup->addAction(Tr::tr("Icons Only")); - connect(m_setModeSelectorStyleIconsOnlyAction, &QAction::triggered, - [] { ModeManager::setModeStyle(ModeManager::Style::IconsOnly); }); - m_setModeSelectorStyleIconsOnlyAction->setCheckable(true); - m_setModeSelectorStyleHiddenAction = stylesGroup->addAction(Tr::tr("Hidden")); - connect(m_setModeSelectorStyleHiddenAction, &QAction::triggered, - [] { ModeManager::setModeStyle(ModeManager::Style::Hidden); }); - m_setModeSelectorStyleHiddenAction->setCheckable(true); - - styleMenu->addActions(stylesGroup->actions()); -} - -void MainWindowPrivate::openFile() -{ - openFiles(EditorManager::getOpenFilePaths(), ICore::SwitchMode); -} - -static IDocumentFactory *findDocumentFactory(const QList &fileFactories, - const FilePath &filePath) -{ - const QString typeName = Utils::mimeTypeForFile(filePath, MimeMatchMode::MatchDefaultAndRemote) - .name(); - return Utils::findOrDefault(fileFactories, [typeName](IDocumentFactory *f) { - return f->mimeTypes().contains(typeName); - }); -} - -/*! - * \internal - * Either opens \a filePaths with editors or loads a project. - * - * \a flags can be used to stop on first failure, indicate that a file name - * might include line numbers and/or switch mode to edit mode. - * - * \a workingDirectory is used when files are opened by a remote client, since - * the file names are relative to the client working directory. - * - * Returns the first opened document. Required to support the \c -block flag - * for client mode. - * - * \sa IPlugin::remoteArguments() - */ -IDocument *MainWindow::openFiles(const FilePaths &filePaths, - ICore::OpenFilesFlags flags, - const FilePath &workingDirectory) -{ - return MainWindowPrivate::openFiles(filePaths, flags, workingDirectory); -} - -IDocument *MainWindowPrivate::openFiles(const FilePaths &filePaths, - ICore::OpenFilesFlags flags, - const FilePath &workingDirectory) -{ - const QList documentFactories = IDocumentFactory::allDocumentFactories(); - IDocument *res = nullptr; - - const FilePath workingDirBase = - workingDirectory.isEmpty() ? FilePath::currentWorkingPath() : workingDirectory; - for (const FilePath &filePath : filePaths) { - const FilePath absoluteFilePath = workingDirBase.resolvePath(filePath); - if (IDocumentFactory *documentFactory = findDocumentFactory(documentFactories, filePath)) { - IDocument *document = documentFactory->open(absoluteFilePath); - if (!document) { - if (flags & ICore::StopOnLoadFail) - return res; - } else { - if (!res) - res = document; - if (flags & ICore::SwitchMode) - ModeManager::activateMode(Id(Constants::MODE_EDIT)); - } - } else if (flags & (ICore::SwitchSplitIfAlreadyVisible | ICore::CanContainLineAndColumnNumbers) - || !res) { - QFlags emFlags; - if (flags & ICore::SwitchSplitIfAlreadyVisible) - emFlags |= EditorManager::SwitchSplitIfAlreadyVisible; - IEditor *editor = nullptr; - if (flags & ICore::CanContainLineAndColumnNumbers) { - const Link &link = Link::fromString(absoluteFilePath.toString(), true); - editor = EditorManager::openEditorAt(link, {}, emFlags); - } else { - editor = EditorManager::openEditor(absoluteFilePath, {}, emFlags); - } - if (!editor) { - if (flags & ICore::StopOnLoadFail) - return res; - } else if (!res) { - res = editor->document(); - } - } else { - auto factory = IEditorFactory::preferredEditorFactories(absoluteFilePath).value(0); - DocumentModelPrivate::addSuspendedDocument(absoluteFilePath, {}, - factory ? factory->id() : Id()); - } - } - return res; -} - -void MainWindowPrivate::setFocusToEditor() -{ - EditorManagerPrivate::doEscapeKeyFocusMoveMagic(); -} - -static void acceptModalDialogs() -{ - const QWidgetList topLevels = QApplication::topLevelWidgets(); - QList dialogsToClose; - for (QWidget *topLevel : topLevels) { - if (auto dialog = qobject_cast(topLevel)) { - if (dialog->isModal()) - dialogsToClose.append(dialog); - } - } - for (QDialog *dialog : dialogsToClose) - dialog->accept(); -} - -void MainWindow::exit() -{ - // this function is most likely called from a user action - // that is from an event handler of an object - // since on close we are going to delete everything - // so to prevent the deleting of that object we - // just append it - QMetaObject::invokeMethod( - this, - [this] { - // Modal dialogs block the close event. So close them, in case this was triggered from - // a RestartDialog in the settings dialog. - acceptModalDialogs(); - close(); - }, - Qt::QueuedConnection); -} - -void MainWindow::openFileWith() -{ - const FilePaths filePaths = EditorManager::getOpenFilePaths(); - for (const FilePath &filePath : filePaths) { - bool isExternal; - const Id editorId = EditorManagerPrivate::getOpenWithEditorId(filePath, &isExternal); - if (!editorId.isValid()) - continue; - if (isExternal) - EditorManager::openExternalEditor(filePath, editorId); - else - EditorManagerPrivate::openEditorWith(filePath, editorId); - } -} - -void MainWindowPrivate::openFileFromDevice() -{ - openFiles(EditorManager::getOpenFilePaths(QFileDialog::DontUseNativeDialog), ICore::SwitchMode); -} - -IContext *MainWindow::contextObject(QWidget *widget) const -{ - const auto it = d->m_contextWidgets.find(widget); - return it == d->m_contextWidgets.end() ? nullptr : it->second; -} - -void MainWindow::addContextObject(IContext *context) -{ - if (!context) - return; - QWidget *widget = context->widget(); - if (d->m_contextWidgets.find(widget) != d->m_contextWidgets.end()) - return; - - d->m_contextWidgets.insert({widget, context}); - connect(context, &QObject::destroyed, this, [this, context] { removeContextObject(context); }); -} - -void MainWindow::removeContextObject(IContext *context) -{ - if (!context) - return; - - disconnect(context, &QObject::destroyed, this, nullptr); - - const auto it = std::find_if(d->m_contextWidgets.cbegin(), - d->m_contextWidgets.cend(), - [context](const std::pair &v) { - return v.second == context; - }); - if (it == d->m_contextWidgets.cend()) - return; - - d->m_contextWidgets.erase(it); - if (d->m_activeContext.removeAll(context) > 0) - d->updateContextObject(d->m_activeContext); -} - -void MainWindowPrivate::updateFocusWidget(QWidget *old, QWidget *now) -{ - Q_UNUSED(old) - - // Prevent changing the context object just because the menu or a menu item is activated - if (qobject_cast(now) || qobject_cast(now)) - return; - - QList newContext; - if (QWidget *p = QApplication::focusWidget()) { - IContext *context = nullptr; - while (p) { - context = q->contextObject(p); - if (context) - newContext.append(context); - p = p->parentWidget(); - } - } - - // ignore toplevels that define no context, like popups without parent - if (!newContext.isEmpty() || QApplication::focusWidget() == q->focusWidget()) - updateContextObject(newContext); -} - -void MainWindowPrivate::updateContextObject(const QList &context) -{ - emit m_coreImpl->contextAboutToChange(context); - m_activeContext = context; - updateContext(); - if (debugMainWindow) { - qDebug() << "new context objects =" << context; - for (const IContext *c : context) - qDebug() << (c ? c->widget() : nullptr) << (c ? c->widget()->metaObject()->className() : nullptr); - } -} - -void MainWindow::aboutToShutdown() -{ - disconnect(qApp, &QApplication::focusChanged, d, &MainWindowPrivate::updateFocusWidget); - for (auto contextPair : d->m_contextWidgets) - disconnect(contextPair.second, &QObject::destroyed, this, nullptr); - d->m_activeContext.clear(); - hide(); -} - -void MainWindowPrivate::readSettings() -{ - QtcSettings *settings = PluginManager::settings(); - settings->beginGroup(QLatin1String(settingsGroup)); - - if (m_overrideColor.isValid()) { - StyleHelper::setBaseColor(m_overrideColor); - // Get adapted base color. - m_overrideColor = StyleHelper::baseColor(); - } else { - StyleHelper::setBaseColor(settings->value(colorKey, - QColor(StyleHelper::DEFAULT_BASE_COLOR)).value()); - } - - { - ModeManager::Style modeStyle = - ModeManager::Style(settings->value(modeSelectorLayoutKey, int(ModeManager::Style::IconsAndText)).toInt()); - - // Migrate legacy setting from Qt Creator 4.6 and earlier - static const char modeSelectorVisibleKey[] = "ModeSelectorVisible"; - if (!settings->contains(modeSelectorLayoutKey) && settings->contains(modeSelectorVisibleKey)) { - bool visible = settings->value(modeSelectorVisibleKey, true).toBool(); - modeStyle = visible ? ModeManager::Style::IconsAndText : ModeManager::Style::Hidden; - } - - ModeManager::setModeStyle(modeStyle); - updateModeSelectorStyleMenu(); - } - - if (globalMenuBar() && !globalMenuBar()->isNativeMenuBar()) { - const bool isVisible = settings->value(menubarVisibleKey, true).toBool(); - - globalMenuBar()->setVisible(isVisible); - if (m_toggleMenubarAction) - m_toggleMenubarAction->setChecked(isVisible); - } - - settings->endGroup(); - - EditorManagerPrivate::readSettings(); - m_leftNavigationWidget->restoreSettings(settings); - m_rightNavigationWidget->restoreSettings(settings); - m_rightPaneWidget->readSettings(settings); -} - -void MainWindow::saveSettings() -{ - QtcSettings *settings = PluginManager::settings(); - settings->beginGroup(QLatin1String(settingsGroup)); - - if (!(d->m_overrideColor.isValid() && StyleHelper::baseColor() == d->m_overrideColor)) - settings->setValueWithDefault(colorKey, - StyleHelper::requestedBaseColor(), - QColor(StyleHelper::DEFAULT_BASE_COLOR)); - - if (globalMenuBar() && !globalMenuBar()->isNativeMenuBar()) - settings->setValue(menubarVisibleKey, globalMenuBar()->isVisible()); - - settings->endGroup(); - - DocumentManager::saveSettings(); - ActionManager::saveSettings(); - EditorManagerPrivate::saveSettings(); - d->m_leftNavigationWidget->saveSettings(settings); - d->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 MainWindowPrivate::saveWindowSettings() -{ - QtcSettings *settings = PluginManager::settings(); - settings->beginGroup(settingsGroup); - - // On OS X applications usually do not restore their full screen state. - // To be able to restore the correct non-full screen geometry, we have to put - // the window out of full screen before saving the geometry. - // Works around QTBUG-45241 - if (Utils::HostOsInfo::isMacHost() && q->isFullScreen()) - q->setWindowState(q->windowState() & ~Qt::WindowFullScreen); - settings->setValue(windowGeometryKey, q->saveGeometry()); - settings->setValue(windowStateKey, q->saveState()); - settings->setValue(modeSelectorLayoutKey, int(ModeManager::modeStyle())); - - settings->endGroup(); -} - -void MainWindowPrivate::updateModeSelectorStyleMenu() -{ - switch (ModeManager::modeStyle()) { - case ModeManager::Style::IconsAndText: - m_setModeSelectorStyleIconsAndTextAction->setChecked(true); - break; - case ModeManager::Style::IconsOnly: - m_setModeSelectorStyleIconsOnlyAction->setChecked(true); - break; - case ModeManager::Style::Hidden: - m_setModeSelectorStyleHiddenAction->setChecked(true); - break; - } -} - -void MainWindow::updateAdditionalContexts(const Context &remove, const Context &add, - ICore::ContextPriority priority) -{ - for (const Id id : remove) { - if (!id.isValid()) - continue; - int index = d->m_lowPrioAdditionalContexts.indexOf(id); - if (index != -1) - d->m_lowPrioAdditionalContexts.removeAt(index); - index = d->m_highPrioAdditionalContexts.indexOf(id); - if (index != -1) - d->m_highPrioAdditionalContexts.removeAt(index); - } - - for (const Id id : add) { - if (!id.isValid()) - continue; - Context &cref = (priority == ICore::ContextPriority::High ? d->m_highPrioAdditionalContexts - : d->m_lowPrioAdditionalContexts); - if (!cref.contains(id)) - cref.prepend(id); - } - - d->updateContext(); -} - -void MainWindowPrivate::updateContext() -{ - Context contexts = m_highPrioAdditionalContexts; - - for (IContext *context : std::as_const(m_activeContext)) - contexts.add(context->context()); - - contexts.add(m_lowPrioAdditionalContexts); - - Context uniquecontexts; - for (const Id &id : std::as_const(contexts)) { - if (!uniquecontexts.contains(id)) - uniquecontexts.add(id); - } - - ActionManager::setContext(uniquecontexts); - emit m_coreImpl->contextChanged(uniquecontexts); -} - -void MainWindowPrivate::aboutToShowRecentFiles() -{ - ActionContainer *aci = ActionManager::actionContainer(Constants::M_FILE_RECENTFILES); - QMenu *menu = aci->menu(); - menu->clear(); - - const QList recentFiles = DocumentManager::recentFiles(); - for (int i = 0; i < recentFiles.count(); ++i) { - const DocumentManager::RecentFile file = recentFiles[i]; - - const QString filePath = Utils::quoteAmpersands(file.first.shortNativePath()); - const QString actionText = ActionManager::withNumberAccelerator(filePath, i + 1); - QAction *action = menu->addAction(actionText); - connect(action, &QAction::triggered, this, [file] { - EditorManager::openEditor(file.first, file.second); - }); - } - - bool hasRecentFiles = !recentFiles.isEmpty(); - menu->setEnabled(hasRecentFiles); - - // add the Clear Menu item - if (hasRecentFiles) { - menu->addSeparator(); - QAction *action = menu->addAction(Tr::tr(Constants::TR_CLEAR_MENU)); - connect(action, &QAction::triggered, - DocumentManager::instance(), &DocumentManager::clearRecentFiles); - } -} - -void MainWindowPrivate::aboutQtCreator() -{ - if (!m_versionDialog) { - m_versionDialog = new VersionDialog(q); - connect(m_versionDialog, &QDialog::finished, - this, &MainWindowPrivate::destroyVersionDialog); - ICore::registerWindow(m_versionDialog, Context("Core.VersionDialog")); - m_versionDialog->show(); - } else { - ICore::raiseWindow(m_versionDialog); - } -} - -void MainWindowPrivate::destroyVersionDialog() -{ - if (m_versionDialog) { - m_versionDialog->deleteLater(); - m_versionDialog = nullptr; - } -} - -void MainWindowPrivate::aboutPlugins() -{ - PluginDialog dialog(q); - dialog.exec(); -} - -class LogDialog : public QDialog -{ -public: - LogDialog(QWidget *parent) - : QDialog(parent) - {} - bool event(QEvent *event) override - { - if (event->type() == QEvent::ShortcutOverride) { - auto ke = static_cast(event); - if (ke->key() == Qt::Key_Escape && !ke->modifiers()) { - ke->accept(); - return true; - } - } - return QDialog::event(event); - } -}; - -void MainWindowPrivate::changeLog() -{ - static QPointer dialog; - if (dialog) { - ICore::raiseWindow(dialog); - return; - } - const FilePaths files = - ICore::resourcePath("changelog").dirEntries({{"changes-*"}, QDir::Files}); - static const QRegularExpression versionRegex("\\d+[.]\\d+[.]\\d+"); - using VersionFilePair = std::pair; - QList versionedFiles = Utils::transform(files, [](const FilePath &fp) { - const QRegularExpressionMatch match = versionRegex.match(fp.fileName()); - const QVersionNumber version = match.hasMatch() - ? QVersionNumber::fromString(match.captured()) - : QVersionNumber(); - return std::make_pair(version, fp); - }); - Utils::sort(versionedFiles, [](const VersionFilePair &a, const VersionFilePair &b) { - return a.first > b.first; - }); - - auto versionCombo = new QComboBox; - for (const VersionFilePair &f : versionedFiles) - versionCombo->addItem(f.first.toString()); - dialog = new LogDialog(ICore::dialogParent()); - auto versionLayout = new QHBoxLayout; - versionLayout->addWidget(new QLabel(Tr::tr("Version:"))); - versionLayout->addWidget(versionCombo); - versionLayout->addStretch(1); - auto showInExplorer = new QPushButton(FileUtils::msgGraphicalShellAction()); - versionLayout->addWidget(showInExplorer); - auto textEdit = new QTextBrowser; - textEdit->setOpenExternalLinks(true); - - auto aggregate = new Aggregation::Aggregate; - aggregate->add(textEdit); - aggregate->add(new Core::BaseTextFind(textEdit)); - - new MarkdownHighlighter(textEdit->document()); - - auto textEditWidget = new QFrame; - textEditWidget->setFrameStyle(QFrame::NoFrame); - auto findToolBar = new FindToolBarPlaceHolder(dialog); - findToolBar->setLightColored(true); - auto textEditLayout = new QVBoxLayout; - textEditLayout->setContentsMargins(0, 0, 0, 0); - textEditLayout->setSpacing(0); - textEditLayout->addWidget(textEdit); - textEditLayout->addWidget(findToolBar); - textEditWidget->setLayout(textEditLayout); - auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Close); - auto dialogLayout = new QVBoxLayout; - dialogLayout->addLayout(versionLayout); - dialogLayout->addWidget(textEditWidget); - dialogLayout->addWidget(buttonBox); - dialog->setLayout(dialogLayout); - dialog->resize(700, 600); - dialog->setWindowTitle(Tr::tr("Change Log")); - dialog->setAttribute(Qt::WA_DeleteOnClose); - ICore::registerWindow(dialog, Context("CorePlugin.VersionDialog")); - - connect(buttonBox, &QDialogButtonBox::rejected, dialog, &QDialog::close); - QPushButton *closeButton = buttonBox->button(QDialogButtonBox::Close); - if (QTC_GUARD(closeButton)) - closeButton->setDefault(true); // grab from "Open in Explorer" button - - const auto showLog = [textEdit, versionedFiles](int index) { - if (index < 0 || index >= versionedFiles.size()) - return; - const FilePath file = versionedFiles.at(index).second; - QString contents = QString::fromUtf8(file.fileContents().value_or(QByteArray())); - // (? matches; - for (const QRegularExpressionMatch &m : docexpr.globalMatch(contents)) - matches.append(m); - Utils::reverseForeach(matches, [&contents](const QRegularExpressionMatch &match) { - const QString qthelpUrl = "qthelp://org.qt-project.qtcreator/doc/" + match.captured(1); - if (!HelpManager::fileData(qthelpUrl).isEmpty()) - contents.replace(match.capturedStart(), match.capturedLength(), qthelpUrl); - }); - textEdit->setMarkdown(contents); - }; - connect(versionCombo, &QComboBox::currentIndexChanged, textEdit, showLog); - showLog(versionCombo->currentIndex()); - - connect(showInExplorer, &QPushButton::clicked, this, [versionCombo, versionedFiles] { - const int index = versionCombo->currentIndex(); - if (index >= 0 && index < versionedFiles.size()) - FileUtils::showInGraphicalShell(ICore::dialogParent(), versionedFiles.at(index).second); - else - FileUtils::showInGraphicalShell(ICore::dialogParent(), ICore::resourcePath("changelog")); - }); - - dialog->show(); -} - -void MainWindowPrivate::contact() -{ - QMessageBox dlg(QMessageBox::Information, Tr::tr("Contact"), - Tr::tr("

Qt Creator developers can be reached at the Qt Creator mailing list:

" - "%1" - "

or the #qt-creator channel on Libera.Chat IRC:

" - "%2" - "

Our bug tracker is located at %3.

" - "

Please use %4 for bigger chunks of text.

") - .arg("

    " - "" - "mailto:qt-creator@qt-project.org" - "

") - .arg("

    " - "" - "https://web.libera.chat/#qt-creator" - "

") - .arg("" - "https://bugreports.qt.io" - "") - .arg("" - "https://pastebin.com" - ""), - QMessageBox::Ok, q); - dlg.exec(); -} - -QPrinter *MainWindow::printer() const -{ - if (!d->m_printer) - d->m_printer = new QPrinter(QPrinter::HighResolution); - return d->m_printer; -} - -void MainWindowPrivate::restoreWindowState() -{ - NANOTRACE_SCOPE("Core", "MainWindow::restoreWindowState"); - QtcSettings *settings = PluginManager::settings(); - settings->beginGroup(settingsGroup); - if (!q->restoreGeometry(settings->value(windowGeometryKey).toByteArray())) - q->resize(1260, 700); // size without window decoration - q->restoreState(settings->value(windowStateKey).toByteArray()); - settings->endGroup(); - q->show(); - StatusBarManager::restoreSettings(); -} - -} // namespace Internal -} // namespace Core diff --git a/src/plugins/coreplugin/mainwindow.h b/src/plugins/coreplugin/mainwindow.h index c1cb685e072..fe84d72dcb3 100644 --- a/src/plugins/coreplugin/mainwindow.h +++ b/src/plugins/coreplugin/mainwindow.h @@ -3,81 +3,4 @@ #pragma once -#include "icontext.h" #include "icore.h" - -#include - -#include - -QT_BEGIN_NAMESPACE -class QColor; -class QPrinter; -QT_END_NAMESPACE - -namespace Utils { class InfoBar; } - -namespace Core { - -class IDocument; - -namespace Internal { - -class MainWindowPrivate; - -class MainWindow : public Utils::AppMainWindow -{ - Q_OBJECT - -public: - MainWindow(); - ~MainWindow() override; - - void init(); - void extensionsInitialized(); - void aboutToShutdown(); - - IContext *contextObject(QWidget *widget) const; - void addContextObject(IContext *context); - void removeContextObject(IContext *context); - - static IDocument *openFiles(const Utils::FilePaths &filePaths, - ICore::OpenFilesFlags flags, - const Utils::FilePath &workingDirectory = {}); - - QPrinter *printer() const; - IContext *currentContextObject() const; - QStatusBar *statusBar() const; - Utils::InfoBar *infoBar() const; - - void updateAdditionalContexts(const Context &remove, const Context &add, - ICore::ContextPriority priority); - - void setOverrideColor(const QColor &color); - - QStringList additionalAboutInformation() const; - void clearAboutInformation(); - void appendAboutInformation(const QString &line); - - void addPreCloseListener(const std::function &listener); - - void saveSettings(); - - void restart(); - - void restartTrimmer(); - -public slots: - static void openFileWith(); - void exit(); - -private: - void closeEvent(QCloseEvent *event) override; - void keyPressEvent(QKeyEvent *event) override; - void mousePressEvent(QMouseEvent *event) override; - - MainWindowPrivate *d = nullptr; -}; - -} // namespace Internal -} // namespace Core From 9e241add5f717ba461a2d258e0a4f59813ce9af7 Mon Sep 17 00:00:00 2001 From: hjk Date: Mon, 25 Sep 2023 17:52:44 +0200 Subject: [PATCH 19/27] ProjectExplorer: Remove an unused include Change-Id: I46e5a2e3cdd4b3abc6108a8d07f35d7a4d6a51f1 Reviewed-by: Christian Kandeler Reviewed-by: --- src/plugins/projectexplorer/projectexplorer.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/plugins/projectexplorer/projectexplorer.cpp b/src/plugins/projectexplorer/projectexplorer.cpp index b85e7abafce..e5dc64d79c9 100644 --- a/src/plugins/projectexplorer/projectexplorer.cpp +++ b/src/plugins/projectexplorer/projectexplorer.cpp @@ -49,7 +49,6 @@ #include "kitfeatureprovider.h" #include "kitaspects.h" #include "kitmanager.h" -#include "kitoptionspage.h" #include "miniprojecttargetselector.h" #include "namedwidget.h" #include "parseissuesdialog.h" From b60a4705d0d91a8c2c34c3a52e5031b9704a08c2 Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Tue, 26 Sep 2023 09:20:26 +0200 Subject: [PATCH 20/27] CompilerExplorer: Add wizard template Also include "src/plugins/**/wizard.json" into .gitignore. Change-Id: Ib0576df15af4c112a4a27101d337522db6c19f25 Reviewed-by: David Schulz --- .gitignore | 1 + src/plugins/compilerexplorer/CMakeLists.txt | 4 +- .../compilerexplorer/compilerexplorer.qbs | 3 ++ .../compilerexplorer/compilerexplorer.qrc | 6 +++ .../compilerexplorereditor.cpp | 3 ++ .../compilerexplorerplugin.cpp | 8 +++- .../compilerexplorer/wizard/cpp/file.qtce | 10 +++++ .../compilerexplorer/wizard/cpp/wizard.json | 37 +++++++++++++++++++ 8 files changed, 69 insertions(+), 3 deletions(-) create mode 100644 src/plugins/compilerexplorer/compilerexplorer.qrc create mode 100644 src/plugins/compilerexplorer/wizard/cpp/file.qtce create mode 100644 src/plugins/compilerexplorer/wizard/cpp/wizard.json diff --git a/.gitignore b/.gitignore index 6cbeb2503d5..7c56e80373d 100644 --- a/.gitignore +++ b/.gitignore @@ -56,6 +56,7 @@ CMakeLists.txt.user* /share/qtcreator/qmldesigner/QtProject/ /src/app/Info.plist /src/plugins/**/*.json +!/src/plugins/**/wizard.json /src/plugins/coreplugin/ide_version.h /src/libs/qt-breakpad/bin /.cmake/ diff --git a/src/plugins/compilerexplorer/CMakeLists.txt b/src/plugins/compilerexplorer/CMakeLists.txt index 4df45f95f30..55368044706 100644 --- a/src/plugins/compilerexplorer/CMakeLists.txt +++ b/src/plugins/compilerexplorer/CMakeLists.txt @@ -1,5 +1,5 @@ add_qtc_plugin(CompilerExplorer - PLUGIN_DEPENDS Core TextEditor + PLUGIN_DEPENDS Core ProjectExplorer TextEditor DEPENDS Qt::Network TerminalLib Spinner SOURCES api/config.h @@ -14,6 +14,8 @@ add_qtc_plugin(CompilerExplorer api/library.h api/request.h + compilerexplorer.qrc + compilerexploreraspects.cpp compilerexploreraspects.h compilerexplorerplugin.cpp diff --git a/src/plugins/compilerexplorer/compilerexplorer.qbs b/src/plugins/compilerexplorer/compilerexplorer.qbs index 88fda3bf616..47eb03f9e46 100644 --- a/src/plugins/compilerexplorer/compilerexplorer.qbs +++ b/src/plugins/compilerexplorer/compilerexplorer.qbs @@ -4,6 +4,7 @@ QtcPlugin { name: "CompilerExplorer" Depends { name: "Core" } + Depends { name: "ProjectExplorer" } Depends { name: "Spinner" } Depends { name: "TerminalLib" } Depends { name: "TextEditor" } @@ -22,6 +23,8 @@ QtcPlugin { "api/library.h", "api/request.h", + "compilerexplorer.qrc", + "compilerexploreraspects.cpp", "compilerexploreraspects.h", "compilerexplorerconstants.h", diff --git a/src/plugins/compilerexplorer/compilerexplorer.qrc b/src/plugins/compilerexplorer/compilerexplorer.qrc new file mode 100644 index 00000000000..592a92d463a --- /dev/null +++ b/src/plugins/compilerexplorer/compilerexplorer.qrc @@ -0,0 +1,6 @@ + + + wizard/cpp/wizard.json + wizard/cpp/file.qtce + + diff --git a/src/plugins/compilerexplorer/compilerexplorereditor.cpp b/src/plugins/compilerexplorer/compilerexplorereditor.cpp index b02b3585ace..633ac3622be 100644 --- a/src/plugins/compilerexplorer/compilerexplorereditor.cpp +++ b/src/plugins/compilerexplorer/compilerexplorereditor.cpp @@ -136,6 +136,8 @@ Core::IDocument::OpenResult JsonSettingsDocument::open(QString *errorString, return OpenResult::ReadError; } + setFilePath(filePath); + m_ceSettings.fromMap(*result); emit settingsChanged(); return OpenResult::Success; @@ -171,6 +173,7 @@ bool JsonSettingsDocument::saveImpl(QString *errorString, const FilePath &newFil return false; } + emit changed(); return true; } diff --git a/src/plugins/compilerexplorer/compilerexplorerplugin.cpp b/src/plugins/compilerexplorer/compilerexplorerplugin.cpp index 5845aa7dea2..4063814e6ca 100644 --- a/src/plugins/compilerexplorer/compilerexplorerplugin.cpp +++ b/src/plugins/compilerexplorer/compilerexplorerplugin.cpp @@ -14,10 +14,12 @@ #include -#include - #include +#include + +#include + using namespace Core; namespace CompilerExplorer::Internal { @@ -40,6 +42,8 @@ public: settings().defaultDocument().toUtf8()); }); + ProjectExplorer::JsonWizardFactory::addWizardPath(":/compilerexplorer/wizard/"); + ActionContainer *mtools = ActionManager::actionContainer(Core::Constants::M_TOOLS); ActionContainer *mCompilerExplorer = ActionManager::createMenu("Tools.CompilerExplorer"); QMenu *menu = mCompilerExplorer->menu(); diff --git a/src/plugins/compilerexplorer/wizard/cpp/file.qtce b/src/plugins/compilerexplorer/wizard/cpp/file.qtce new file mode 100644 index 00000000000..903d5187165 --- /dev/null +++ b/src/plugins/compilerexplorer/wizard/cpp/file.qtce @@ -0,0 +1,10 @@ +{ + "Sources": [{ + "LanguageId": "c++", + "Source": "int main() {\n return 0;\n}", + "Compilers": [{ + "Id": "clang_trunk", + "Options": "-O3" + }] + }] +} diff --git a/src/plugins/compilerexplorer/wizard/cpp/wizard.json b/src/plugins/compilerexplorer/wizard/cpp/wizard.json new file mode 100644 index 00000000000..b736551b69e --- /dev/null +++ b/src/plugins/compilerexplorer/wizard/cpp/wizard.json @@ -0,0 +1,37 @@ +{ + "version": 1, + "supportedProjectTypes": [], + "id": "QTCE.CppSource", + "category": "U.CompilerExplorer", + "trDescription": "Creates an example CompilerExplorer setup for C++.", + "trDisplayName": "Compiler Explorer C++ Source", + "trDisplayCategory": "Compiler Explorer", + "icon": "", + "iconKind": "Plain", + "options": { + "key": "DefaultSuffix", + "value": "%{JS: Util.preferredSuffix('application/compiler-explorer')}" + }, + "pages": [ + { + "trDisplayName": "Location", + "trShortTitle": "Location", + "typeId": "File" + }, + { + "trDisplayName": "Project Management", + "trShortTitle": "Summary", + "typeId": "Summary" + } + ], + "generators": [ + { + "typeId": "File", + "data": { + "source": "file.qtce", + "target": "%{JS: Util.fileName(value('TargetPath'), value('DefaultSuffix'))}", + "openInEditor": true + } + } + ] +} From 6e1c9825e8a1a0fb0cf5c445f88ffea3b91e8684 Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Tue, 26 Sep 2023 09:35:49 +0200 Subject: [PATCH 21/27] CompilerExplorer: Add python template Change-Id: If838a2a89df98763dc424fb6285daa4699cce7ab Reviewed-by: David Schulz --- .../compilerexplorer/compilerexplorer.qrc | 2 + .../compilerexplorer/wizard/python/file.qtce | 9 +++++ .../wizard/python/wizard.json | 37 +++++++++++++++++++ 3 files changed, 48 insertions(+) create mode 100644 src/plugins/compilerexplorer/wizard/python/file.qtce create mode 100644 src/plugins/compilerexplorer/wizard/python/wizard.json diff --git a/src/plugins/compilerexplorer/compilerexplorer.qrc b/src/plugins/compilerexplorer/compilerexplorer.qrc index 592a92d463a..ea46de321c6 100644 --- a/src/plugins/compilerexplorer/compilerexplorer.qrc +++ b/src/plugins/compilerexplorer/compilerexplorer.qrc @@ -2,5 +2,7 @@ wizard/cpp/wizard.json wizard/cpp/file.qtce + wizard/python/wizard.json + wizard/python/file.qtce diff --git a/src/plugins/compilerexplorer/wizard/python/file.qtce b/src/plugins/compilerexplorer/wizard/python/file.qtce new file mode 100644 index 00000000000..5cd735227c9 --- /dev/null +++ b/src/plugins/compilerexplorer/wizard/python/file.qtce @@ -0,0 +1,9 @@ +{ + "Sources": [{ + "LanguageId": "python", + "Source": "def main():\\n print(\\"Hello World\\")\\n\\nif __name__ == \\"__main__\\":\\n main()", + "Compilers": [{ + "Id": "python311" + }] + }] +} diff --git a/src/plugins/compilerexplorer/wizard/python/wizard.json b/src/plugins/compilerexplorer/wizard/python/wizard.json new file mode 100644 index 00000000000..b026adb4cdb --- /dev/null +++ b/src/plugins/compilerexplorer/wizard/python/wizard.json @@ -0,0 +1,37 @@ +{ + "version": 1, + "supportedProjectTypes": [], + "id": "QTCE.PySource", + "category": "U.CompilerExplorer", + "trDescription": "Creates an example CompilerExplorer setup for Python.", + "trDisplayName": "Compiler Explorer Python Source", + "trDisplayCategory": "Compiler Explorer", + "icon": "", + "iconKind": "Plain", + "options": { + "key": "DefaultSuffix", + "value": "%{JS: Util.preferredSuffix('application/compiler-explorer')}" + }, + "pages": [ + { + "trDisplayName": "Location", + "trShortTitle": "Location", + "typeId": "File" + }, + { + "trDisplayName": "Project Management", + "trShortTitle": "Summary", + "typeId": "Summary" + } + ], + "generators": [ + { + "typeId": "File", + "data": { + "source": "file.qtce", + "target": "%{JS: Util.fileName(value('TargetPath'), value('DefaultSuffix'))}", + "openInEditor": true + } + } + ] +} From bb8961c893be5d023f73bcb56f6bfab8b0178753 Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Tue, 26 Sep 2023 10:28:49 +0200 Subject: [PATCH 22/27] CompilerExplorer: Cleanup Split up EditorWidget constructor into member functions. Change-Id: I4c762671263b802612a750568f608ac1823b41a4 Reviewed-by: David Schulz --- .../compilerexplorereditor.cpp | 373 ++++++++++-------- .../compilerexplorer/compilerexplorereditor.h | 23 +- 2 files changed, 233 insertions(+), 163 deletions(-) diff --git a/src/plugins/compilerexplorer/compilerexplorereditor.cpp b/src/plugins/compilerexplorer/compilerexplorereditor.cpp index 633ac3622be..2a184152d24 100644 --- a/src/plugins/compilerexplorer/compilerexplorereditor.cpp +++ b/src/plugins/compilerexplorer/compilerexplorereditor.cpp @@ -323,11 +323,6 @@ CompilerWidget::CompilerWidget(const std::shared_ptr &sourceSett m_spinner = new SpinnerSolution::Spinner(SpinnerSolution::SpinnerSize::Large, this); } -CompilerWidget::~CompilerWidget() -{ - qDebug() << "Good bye!"; -} - Core::SearchableTerminal *CompilerWidget::createTerminal() { m_resultTerminal = new Core::SearchableTerminal(); @@ -477,172 +472,31 @@ EditorWidget::EditorWidget(const QSharedPointer &document, QWidget *parent) : Utils::FancyMainWindow(parent) , m_document(document) + , m_undoStack(undoStack) + , m_actionHandler(actionHandler) { setAutoHideTitleBars(false); setDockNestingEnabled(true); setDocumentMode(true); setTabPosition(Qt::AllDockWidgetAreas, QTabWidget::TabPosition::South); - document->setWindowStateCallback([this] { - auto settings = saveSettings(); - QVariantMap result; + document->setWindowStateCallback([this] { return windowStateCallback(); }); - for (const auto &key : settings.keys()) { - // QTBUG-116339 - if (key != "State") { - result.insert(key, settings.value(key)); - } else { - QVariantMap m; - m["type"] = "Base64"; - m["value"] = settings.value(key).toByteArray().toBase64(); - result.insert(key, m); - } - } + document->settings()->m_sources.setItemAddedCallback( + [this](const std::shared_ptr &source) { addSourceEditor(source); }); - return result; + document->settings()->m_sources.setItemRemovedCallback( + [this](const std::shared_ptr &source) { removeSourceEditor(source); }); + + connect(document.get(), + &JsonSettingsDocument::settingsChanged, + this, + &EditorWidget::recreateEditors); + + connect(this, &EditorWidget::gotFocus, this, [&actionHandler] { + actionHandler.updateCurrentEditor(); }); - auto addCompiler = [this, - &actionHandler](const std::shared_ptr &sourceSettings, - const std::shared_ptr &compilerSettings, - int idx) { - auto compiler = new CompilerWidget(sourceSettings, compilerSettings); - compiler->setWindowTitle("Compiler #" + QString::number(idx)); - compiler->setObjectName("compiler_" + QString::number(idx)); - QDockWidget *dockWidget = addDockForWidget(compiler); - addDockWidget(Qt::RightDockWidgetArea, dockWidget); - m_compilerWidgets.append(dockWidget); - - connect(compiler, - &CompilerWidget::remove, - this, - [sourceSettings = sourceSettings.get(), compilerSettings = compilerSettings.get()] { - sourceSettings->compilers.removeItem(compilerSettings->shared_from_this()); - }); - - connect(compiler, &CompilerWidget::gotFocus, this, [&actionHandler] { - actionHandler.updateCurrentEditor(); - }); - }; - - auto addSourceEditor = [this, &actionHandler, document = document.get(), addCompiler, undoStack]( - const std::shared_ptr &sourceSettings) { - auto sourceEditor = new SourceEditorWidget(sourceSettings, undoStack); - sourceEditor->setWindowTitle("Source Code #" + QString::number(m_sourceWidgets.size() + 1)); - sourceEditor->setObjectName("source_code_editor_" - + QString::number(m_sourceWidgets.size() + 1)); - - QDockWidget *dockWidget = addDockForWidget(sourceEditor); - connect(sourceEditor, - &SourceEditorWidget::remove, - this, - [document, sourceSettings = sourceSettings.get()] { - document->settings()->m_sources.removeItem(sourceSettings->shared_from_this()); - }); - - connect(sourceEditor, &SourceEditorWidget::addCompiler, this, [sourceSettings] { - auto newCompiler = std::make_shared( - sourceSettings->apiConfigFunction()); - newCompiler->setLanguageId(sourceSettings->languageId()); - sourceSettings->compilers.addItem(newCompiler); - }); - - connect(sourceEditor, &SourceEditorWidget::gotFocus, this, [&actionHandler] { - actionHandler.updateCurrentEditor(); - }); - - addDockWidget(Qt::LeftDockWidgetArea, dockWidget); - - sourceSettings->compilers.forEachItem( - [addCompiler, sourceSettings](const std::shared_ptr &compilerSettings, - int idx) { - addCompiler(sourceSettings, compilerSettings, idx + 1); - }); - - sourceSettings->compilers.setItemAddedCallback( - [addCompiler, sourceSettings = sourceSettings.get()]( - const std::shared_ptr &compilerSettings) { - addCompiler(sourceSettings->shared_from_this(), - compilerSettings, - sourceSettings->compilers.size()); - }); - - sourceSettings->compilers.setItemRemovedCallback( - [this](const std::shared_ptr &compilerSettings) { - auto it = std::find_if(m_compilerWidgets.begin(), - m_compilerWidgets.end(), - [compilerSettings](const QDockWidget *c) { - return static_cast(c->widget()) - ->m_compilerSettings - == compilerSettings; - }); - QTC_ASSERT(it != m_compilerWidgets.end(), return); - delete *it; - m_compilerWidgets.erase(it); - }); - - /*Aggregate *agg = Aggregate::parentAggregate(sourceEditor); - if (!agg) { - agg = new Aggregate; - agg->add(sourceEditor); - } - agg->add(this); - - setFocusProxy(sourceEditor); -*/ - m_sourceWidgets.append(dockWidget); - }; - - auto removeSourceEditor = [this](const std::shared_ptr &sourceSettings) { - auto it = std::find_if(m_sourceWidgets.begin(), - m_sourceWidgets.end(), - [sourceSettings](const QDockWidget *c) { - return static_cast(c->widget()) - ->sourceSettings() - == sourceSettings.get(); - }); - QTC_ASSERT(it != m_sourceWidgets.end(), return); - delete *it; - m_sourceWidgets.erase(it); - }; - - auto recreateEditors = [this, addSourceEditor]() { - qDeleteAll(m_sourceWidgets); - qDeleteAll(m_compilerWidgets); - - m_sourceWidgets.clear(); - m_compilerWidgets.clear(); - - m_document->settings()->m_sources.forEachItem(addSourceEditor); - QVariantMap windowState = m_document->settings()->windowState.value(); - - if (!windowState.isEmpty()) { - QHash hashMap; - for (const auto &key : windowState.keys()) { - if (key != "State") - hashMap.insert(key, windowState.value(key)); - else { - QVariant v = windowState.value(key); - if (v.userType() == QMetaType::QByteArray) { - hashMap.insert(key, v); - } else if (v.userType() == QMetaType::QVariantMap) { - QVariantMap m = v.toMap(); - if (m.value("type") == "Base64") { - hashMap.insert(key, - QByteArray::fromBase64(m.value("value").toByteArray())); - } - } - } - } - - restoreSettings(hashMap); - } - }; - - document->settings()->m_sources.setItemAddedCallback(addSourceEditor); - document->settings()->m_sources.setItemRemovedCallback(removeSourceEditor); - connect(document.get(), &JsonSettingsDocument::settingsChanged, this, recreateEditors); - m_context = new Core::IContext(this); m_context->setWidget(this); m_context->setContext(Core::Context(Constants::CE_EDITOR_CONTEXT_ID)); @@ -655,6 +509,203 @@ EditorWidget::~EditorWidget() m_sourceWidgets.clear(); } +void EditorWidget::focusInEvent(QFocusEvent *event) +{ + emit gotFocus(); + FancyMainWindow::focusInEvent(event); +} + +void EditorWidget::addCompiler(const std::shared_ptr &sourceSettings, + const std::shared_ptr &compilerSettings, + int idx, + QDockWidget *parentDockWidget) +{ + auto compiler = new CompilerWidget(sourceSettings, compilerSettings); + compiler->setWindowTitle("Compiler #" + QString::number(idx)); + compiler->setObjectName("compiler_" + QString::number(idx)); + QDockWidget *dockWidget = addDockForWidget(compiler, parentDockWidget); + addDockWidget(Qt::RightDockWidgetArea, dockWidget); + m_compilerWidgets.append(dockWidget); + + connect(compiler, + &CompilerWidget::remove, + this, + [sourceSettings = sourceSettings.get(), compilerSettings = compilerSettings.get()] { + sourceSettings->compilers.removeItem(compilerSettings->shared_from_this()); + }); + + connect(compiler, &CompilerWidget::gotFocus, this, [this]() { + m_actionHandler.updateCurrentEditor(); + }); +} + +QVariantMap EditorWidget::windowStateCallback() +{ + auto settings = saveSettings(); + QVariantMap result; + + for (const auto &key : settings.keys()) { + // QTBUG-116339 + if (key != "State") { + result.insert(key, settings.value(key)); + } else { + QVariantMap m; + m["type"] = "Base64"; + m["value"] = settings.value(key).toByteArray().toBase64(); + result.insert(key, m); + } + } + + return result; +} + +void EditorWidget::addSourceEditor(const std::shared_ptr &sourceSettings) +{ + auto sourceEditor = new SourceEditorWidget(sourceSettings, m_undoStack); + sourceEditor->setWindowTitle("Source Code #" + QString::number(m_sourceWidgets.size() + 1)); + sourceEditor->setObjectName("source_code_editor_" + QString::number(m_sourceWidgets.size() + 1)); + + QDockWidget *dockWidget = addDockForWidget(sourceEditor); + connect(sourceEditor, &SourceEditorWidget::remove, this, [this, sourceSettings]() { + m_undoStack->beginMacro("Remove source"); + sourceSettings->compilers.clear(); + m_document->settings()->m_sources.removeItem(sourceSettings->shared_from_this()); + m_undoStack->endMacro(); + + setupHelpWidget(); + }); + + connect(sourceEditor, &SourceEditorWidget::addCompiler, this, [sourceSettings]() { + auto newCompiler = std::make_shared(sourceSettings->apiConfigFunction()); + newCompiler->setLanguageId(sourceSettings->languageId()); + sourceSettings->compilers.addItem(newCompiler); + }); + + connect(sourceEditor, &SourceEditorWidget::gotFocus, this, [this]() { + m_actionHandler.updateCurrentEditor(); + }); + + addDockWidget(Qt::LeftDockWidgetArea, dockWidget); + + sourceSettings->compilers.forEachItem( + [this, sourceSettings, dockWidget](const std::shared_ptr &compilerSettings, + int idx) { + addCompiler(sourceSettings, compilerSettings, idx + 1, dockWidget); + }); + + sourceSettings->compilers.setItemAddedCallback( + [this, sourceSettings, dockWidget]( + const std::shared_ptr &compilerSettings) { + addCompiler(sourceSettings->shared_from_this(), + compilerSettings, + sourceSettings->compilers.size(), + dockWidget); + }); + + sourceSettings->compilers.setItemRemovedCallback( + [this, sourceSettings](const std::shared_ptr &compilerSettings) { + auto it = std::find_if(m_compilerWidgets.begin(), + m_compilerWidgets.end(), + [compilerSettings](const QDockWidget *c) { + return static_cast(c->widget()) + ->m_compilerSettings + == compilerSettings; + }); + QTC_ASSERT(it != m_compilerWidgets.end(), return); + delete *it; + m_compilerWidgets.erase(it); + }); + + m_sourceWidgets.append(dockWidget); + + setupHelpWidget(); +} + +void EditorWidget::removeSourceEditor(const std::shared_ptr &sourceSettings) +{ + auto it + = std::find_if(m_sourceWidgets.begin(), + m_sourceWidgets.end(), + [sourceSettings](const QDockWidget *c) { + return static_cast(c->widget())->sourceSettings() + == sourceSettings.get(); + }); + QTC_ASSERT(it != m_sourceWidgets.end(), return); + delete *it; + m_sourceWidgets.erase(it); +} + +void EditorWidget::recreateEditors() +{ + qDeleteAll(m_sourceWidgets); + qDeleteAll(m_compilerWidgets); + + m_sourceWidgets.clear(); + m_compilerWidgets.clear(); + + m_document->settings()->m_sources.forEachItem( + [this](const auto &sourceSettings) { addSourceEditor(sourceSettings); }); + + QVariantMap windowState = m_document->settings()->windowState.value(); + + if (!windowState.isEmpty()) { + QHash hashMap; + for (const auto &key : windowState.keys()) { + if (key != "State") + hashMap.insert(key, windowState.value(key)); + else { + QVariant v = windowState.value(key); + if (v.userType() == QMetaType::QByteArray) { + hashMap.insert(key, v); + } else if (v.userType() == QMetaType::QVariantMap) { + QVariantMap m = v.toMap(); + if (m.value("type") == "Base64") { + hashMap.insert(key, QByteArray::fromBase64(m.value("value").toByteArray())); + } + } + } + } + + restoreSettings(hashMap); + } +} + +void EditorWidget::setupHelpWidget() +{ + if (m_document->settings()->m_sources.size() == 0) { + setCentralWidget(createHelpWidget()); + } else { + delete takeCentralWidget(); + } +} + +QWidget *EditorWidget::createHelpWidget() const +{ + using namespace Layouting; + + auto addSourceButton = new QPushButton(Tr::tr("Add source code")); + connect(addSourceButton, &QPushButton::clicked, this, [this] { + auto newSource = std::make_shared( + [settings = m_document->settings()] { return settings->apiConfig(); }); + m_document->settings()->m_sources.addItem(newSource); + }); + + // clang-format off + return Column { + st, + Row { + st, + Column { + Tr::tr("No source code added yet. Add one using the button below."), + Row { st, addSourceButton, st } + }, + st, + }, + st, + }.emerge(); + // clang-format on +} + TextEditor::TextEditorWidget *EditorWidget::focusedEditorWidget() const { for (const QDockWidget *sourceWidget : m_sourceWidgets) { diff --git a/src/plugins/compilerexplorer/compilerexplorereditor.h b/src/plugins/compilerexplorer/compilerexplorereditor.h index 54befd824ef..7b827aa1625 100644 --- a/src/plugins/compilerexplorer/compilerexplorereditor.h +++ b/src/plugins/compilerexplorer/compilerexplorereditor.h @@ -140,8 +140,6 @@ public: CompilerWidget(const std::shared_ptr &sourceSettings, const std::shared_ptr &compilerSettings); - ~CompilerWidget(); - Core::SearchableTerminal *createTerminal(); void compile(const QString &source); @@ -188,11 +186,32 @@ public: signals: void sourceCodeChanged(); + void gotFocus(); + +protected: + void focusInEvent(QFocusEvent *event) override; + + void setupHelpWidget(); + QWidget *createHelpWidget() const; + + void addCompiler(const std::shared_ptr &sourceSettings, + const std::shared_ptr &compilerSettings, + int idx, + QDockWidget *parentDockWidget); + + void addSourceEditor(const std::shared_ptr &sourceSettings); + void removeSourceEditor(const std::shared_ptr &sourceSettings); + + void recreateEditors(); + + QVariantMap windowStateCallback(); private: QSplitter *m_mainSplitter; int m_compilerCount{0}; QSharedPointer m_document; + QUndoStack *m_undoStack; + TextEditor::TextEditorActionHandler &m_actionHandler; Core::IContext *m_context; From 75cfa8a222bd24634e01d2e1e6ee26411632d7d1 Mon Sep 17 00:00:00 2001 From: hjk Date: Tue, 26 Sep 2023 11:14:03 +0200 Subject: [PATCH 23/27] Project: Avoid a temporary in gcc toolchain autodetection Change-Id: I4bd1ee6b63cf2e18ddd83649ee869566011b990f Reviewed-by: Christian Kandeler --- src/plugins/projectexplorer/gcctoolchain.cpp | 30 +++++++++----------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/src/plugins/projectexplorer/gcctoolchain.cpp b/src/plugins/projectexplorer/gcctoolchain.cpp index ff5387d63a3..1ac10103cca 100644 --- a/src/plugins/projectexplorer/gcctoolchain.cpp +++ b/src/plugins/projectexplorer/gcctoolchain.cpp @@ -1328,27 +1328,25 @@ Toolchains GccToolChainFactory::autoDetect(const ToolchainDetector &detector) co // Gcc is almost never what you want on macOS, but it is by default found in /usr/bin if (!HostOsInfo::isMacHost() || detector.device->type() != Constants::DESKTOP_DEVICE_TYPE) { - Toolchains tcs; static const auto tcChecker = [](const ToolChain *tc) { return tc->targetAbi().osFlavor() != Abi::WindowsMSysFlavor && tc->compilerCommand().fileName() != "c89-gcc" && tc->compilerCommand().fileName() != "c99-gcc"; }; - tcs.append(autoDetectToolchains("g++", - DetectVariants::Yes, - Constants::CXX_LANGUAGE_ID, - Constants::GCC_TOOLCHAIN_TYPEID, - detector, - &constructRealGccToolchain, - tcChecker)); - tcs.append(autoDetectToolchains("gcc", - DetectVariants::Yes, - Constants::C_LANGUAGE_ID, - Constants::GCC_TOOLCHAIN_TYPEID, - detector, - &constructRealGccToolchain, - tcChecker)); - result += tcs; + result += autoDetectToolchains("g++", + DetectVariants::Yes, + Constants::CXX_LANGUAGE_ID, + Constants::GCC_TOOLCHAIN_TYPEID, + detector, + &constructRealGccToolchain, + tcChecker); + result += autoDetectToolchains("gcc", + DetectVariants::Yes, + Constants::C_LANGUAGE_ID, + Constants::GCC_TOOLCHAIN_TYPEID, + detector, + &constructRealGccToolchain, + tcChecker); } return result; From ef88a5c3d08165c0278f07574e3dd6975d37be01 Mon Sep 17 00:00:00 2001 From: Semih Yavuz Date: Tue, 26 Sep 2023 10:59:33 +0200 Subject: [PATCH 24/27] designer: Fix livepreview crash Show Live Preview can be triggered with key sequence Alt+P even if you are not in the designer view which results in access to invalid pointers. To fix this, replace the check in action handler with safer isValid which checks the validity of view and initialize live preview for valid contexts. Fixes: QTCREATORBUG-29642 Change-Id: I9dd1741f1de2722a7ac715a2726b6effbe91529c Reviewed-by: Thomas Hartmann --- src/plugins/qmldesigner/qmlpreviewplugin/qmlpreviewactions.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/plugins/qmldesigner/qmlpreviewplugin/qmlpreviewactions.cpp b/src/plugins/qmldesigner/qmlpreviewplugin/qmlpreviewactions.cpp index ebd53b7f649..f44cb0ab24d 100644 --- a/src/plugins/qmldesigner/qmlpreviewplugin/qmlpreviewactions.cpp +++ b/src/plugins/qmldesigner/qmlpreviewplugin/qmlpreviewactions.cpp @@ -33,7 +33,7 @@ const QByteArray livePreviewId = "LivePreview"; static void handleAction(const SelectionContext &context) { - if (context.view()->isAttached()) { + if (context.isValid()) { if (context.toggled()) { bool skipDeploy = false; if (const Target *startupTarget = ProjectManager::startupTarget()) { From ec13beff1cb707d8dbc57655476dea98a7456d94 Mon Sep 17 00:00:00 2001 From: Cristian Adam Date: Mon, 25 Sep 2023 23:01:31 +0200 Subject: [PATCH 25/27] CMakePM: Initial import of the RSTparser Change-Id: I45bc3d53df3358c1f52ca219b53a1dec8e85a4ca Reviewed-by: Alessandro Portale --- README.md | 33 +++ .../overview/creator-acknowledgements.qdoc | 37 +++ .../3rdparty/rstparser/README.qt | 3 + .../3rdparty/rstparser/README.rst | 32 +++ .../3rdparty/rstparser/rstparser-test.cc | 169 ++++++++++++ .../3rdparty/rstparser/rstparser.cc | 249 ++++++++++++++++++ .../3rdparty/rstparser/rstparser.h | 97 +++++++ 7 files changed, 620 insertions(+) create mode 100644 src/plugins/cmakeprojectmanager/3rdparty/rstparser/README.qt create mode 100644 src/plugins/cmakeprojectmanager/3rdparty/rstparser/README.rst create mode 100644 src/plugins/cmakeprojectmanager/3rdparty/rstparser/rstparser-test.cc create mode 100644 src/plugins/cmakeprojectmanager/3rdparty/rstparser/rstparser.cc create mode 100644 src/plugins/cmakeprojectmanager/3rdparty/rstparser/rstparser.h diff --git a/README.md b/README.md index 7d6102f94f2..70500da736d 100644 --- a/README.md +++ b/README.md @@ -970,3 +970,36 @@ SQLite (https://www.sqlite.org) is in the Public Domain. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +### RSTParser + + RSTParser is an open-source C++ library for parsing reStructuredText + + https://github.com/vitaut-archive/rstparser + + License + ------- + + Copyright (c) 2013, Victor Zverovich + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/doc/qtcreator/src/overview/creator-acknowledgements.qdoc b/doc/qtcreator/src/overview/creator-acknowledgements.qdoc index 0e5b2a60ab2..a9773753b67 100644 --- a/doc/qtcreator/src/overview/creator-acknowledgements.qdoc +++ b/doc/qtcreator/src/overview/creator-acknowledgements.qdoc @@ -938,6 +938,43 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \endcode + \li \b RSTParser + + RSTParser is an open-source C++ library for parsing reStructuredText + + \list + \li \l https://github.com/vitaut-archive/rstparser + \endlist + + \badcode + License + ------- + + Copyright (c) 2013, Victor Zverovich + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + \endcode + \endlist */ diff --git a/src/plugins/cmakeprojectmanager/3rdparty/rstparser/README.qt b/src/plugins/cmakeprojectmanager/3rdparty/rstparser/README.qt new file mode 100644 index 00000000000..776cb07f0b8 --- /dev/null +++ b/src/plugins/cmakeprojectmanager/3rdparty/rstparser/README.qt @@ -0,0 +1,3 @@ +Files taken from the CMake repository https://github.com/vitaut-archive/rstparser.git + +49e1e6626ba28357749acfe3bf07c4a19e5bc4ef diff --git a/src/plugins/cmakeprojectmanager/3rdparty/rstparser/README.rst b/src/plugins/cmakeprojectmanager/3rdparty/rstparser/README.rst new file mode 100644 index 00000000000..1d481382226 --- /dev/null +++ b/src/plugins/cmakeprojectmanager/3rdparty/rstparser/README.rst @@ -0,0 +1,32 @@ +RSTParser +========= + +RSTParser is an open-source C++ library for parsing +`reStructuredText `__. + +License +------- + +Copyright (c) 2013, Victor Zverovich + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/src/plugins/cmakeprojectmanager/3rdparty/rstparser/rstparser-test.cc b/src/plugins/cmakeprojectmanager/3rdparty/rstparser/rstparser-test.cc new file mode 100644 index 00000000000..c70fc67c6da --- /dev/null +++ b/src/plugins/cmakeprojectmanager/3rdparty/rstparser/rstparser-test.cc @@ -0,0 +1,169 @@ +/* + reStructuredText parser tests. + + Copyright (c) 2012, Victor Zverovich + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include + +#include + +#ifdef _WIN32 +# include +#endif + +#include "rstparser.h" + +namespace { + +class TestHandler : public rst::ContentHandler { + private: + std::stack tags_; + std::string content_; + + public: + const std::string &content() const { return content_; } + + void StartBlock(rst::BlockType type) { + std::string tag; + switch (type) { + case rst::PARAGRAPH: + tag = "p"; + break; + case rst::LINE_BLOCK: + tag = "lineblock"; + break; + case rst::BLOCK_QUOTE: + tag = "blockquote"; + break; + case rst::BULLET_LIST: + tag = "ul"; + break; + case rst::LIST_ITEM: + tag = "li"; + break; + case rst::LITERAL_BLOCK: + tag = "code"; + break; + } + content_ += "<" + tag + ">"; + tags_.push(tag); + } + + void EndBlock() { + content_ += ""; + tags_.pop(); + } + + void HandleText(const char *text, std::size_t size) { + content_.append(text, size); + } + + void HandleDirective(const char *type) { + content_ += std::string("<") + type + " />"; + } +}; + +std::string Parse(const char *s) { + TestHandler handler; + rst::Parser parser(&handler); + parser.Parse(s); + return handler.content(); +} +} + +TEST(ParserTest, Paragraph) { + EXPECT_EQ("

test

", Parse("test")); + EXPECT_EQ("

test

", Parse("\ntest")); + EXPECT_EQ("

.

", Parse(".")); + EXPECT_EQ("

..test

", Parse("..test")); +} + +TEST(ParserTest, LineBlock) { + EXPECT_EQ("test", Parse("| test")); + EXPECT_EQ(" abc\ndef", Parse("| abc\n| def")); +} + +TEST(ParserTest, BlockQuote) { + EXPECT_EQ("
test
", Parse(" test")); +} + +TEST(ParserTest, PreserveInnerSpace) { + EXPECT_EQ("

a b

", Parse("a b")); +} + +TEST(ParserTest, ReplaceWhitespace) { + EXPECT_EQ("

a b

", Parse("a\tb")); + EXPECT_EQ("
a b
", Parse(" a\tb")); + EXPECT_EQ("

a b

", Parse("a\vb")); +} + +TEST(ParserTest, StripTrailingSpace) { + EXPECT_EQ("

test

", Parse("test \t")); +} + +TEST(ParserTest, MultiLineBlock) { + EXPECT_EQ("

line 1\nline 2

", Parse("line 1\nline 2")); +} + +TEST(ParserTest, UnindentBlock) { + EXPECT_EQ("
abc

def

", Parse(" abc\ndef")); +} + +TEST(ParserTest, BulletList) { + EXPECT_EQ("
  • item
", Parse("* item")); + EXPECT_EQ("
  • abc\ndef
", Parse("* abc\n def")); +} + +TEST(ParserTest, Literal) { + EXPECT_EQ("

abc:

def", Parse("abc::\n\n def")); + EXPECT_EQ("abc\ndef", Parse("::\n\n abc\n def")); + EXPECT_EQ("

abc\ndef

", Parse("::\n\nabc\ndef")); + EXPECT_EQ("

::\nabc\ndef

", Parse("::\nabc\ndef")); +} + +TEST(ParserTest, Comment) { + EXPECT_EQ("", Parse("..")); + EXPECT_EQ("", Parse("..\n")); + EXPECT_EQ("", Parse(".. comment")); + EXPECT_EQ("", Parse(".. comment:")); +} + +TEST(ParserTest, Directive) { + EXPECT_EQ("", Parse(".. test::")); + EXPECT_EQ("", Parse(".. test::")); + EXPECT_EQ("", Parse("..\ttest::")); +} + +int main(int argc, char **argv) { +#ifdef _WIN32 + // Disable message boxes on assertion failures. + _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG); + _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); + _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG); + _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); +#endif + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/src/plugins/cmakeprojectmanager/3rdparty/rstparser/rstparser.cc b/src/plugins/cmakeprojectmanager/3rdparty/rstparser/rstparser.cc new file mode 100644 index 00000000000..528c572f683 --- /dev/null +++ b/src/plugins/cmakeprojectmanager/3rdparty/rstparser/rstparser.cc @@ -0,0 +1,249 @@ +/* + A reStructuredText parser written in C++. + + Copyright (c) 2013, Victor Zverovich + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "rstparser.h" + +#include +#include + +namespace { +inline bool IsSpace(char c) { + switch (c) { + case ' ': case '\t': case '\v': case '\f': + return true; + } + return false; +} + +// Returns true if s ends with string end. +bool EndsWith(const std::string &s, const char *end) { + std::size_t size = s.size(), end_size = std::strlen(end); + return size >= end_size ? std::strcmp(&s[size - end_size], end) == 0 : false; +} +} + +rst::ContentHandler::~ContentHandler() {} + +void rst::Parser::SkipSpace() { + while (IsSpace(*ptr_)) + ++ptr_; +} + +std::string rst::Parser::ParseDirectiveType() { + const char *s = ptr_; + if (!std::isalnum(*s)) + return std::string(); + for (;;) { + ++s; + if (std::isalnum(*s)) + continue; + switch (*s) { + case '-': case '_': case '+': case ':': case '.': + if (std::isalnum(s[1])) { + ++s; + continue; + } + // Fall through. + } + break; + } + std::string type; + if (s != ptr_) + type.assign(ptr_, s); + ptr_ = s; + return type; +} + +void rst::Parser::EnterBlock(rst::BlockType &prev_type, rst::BlockType type) { + if (type == prev_type) + return; + if (prev_type == LIST_ITEM) + handler_->EndBlock(); + if (type == LIST_ITEM) + handler_->StartBlock(BULLET_LIST); + prev_type = type; +} + +void rst::Parser::ParseBlock( + rst::BlockType type, rst::BlockType &prev_type, int indent) { + std::string text; + for (bool first = true; ; first = false) { + const char *line_start = ptr_; + if (!first) { + // Check indentation. + SkipSpace(); + if (ptr_ - line_start != indent) + break; + if (*ptr_ == '\n') { + ++ptr_; + break; // Empty line ends the block. + } + if (!*ptr_) + break; // End of input. + } + // Strip indentation. + line_start = ptr_; + + // Find the end of the line. + while (*ptr_ && *ptr_ != '\n') + ++ptr_; + + // Strip whitespace at the end of the line. + const char *end = ptr_; + while (end != line_start && IsSpace(end[-1])) + --end; + + // Copy text converting all whitespace characters to spaces. + text.reserve(end - line_start + 1); + if (!first) + text.push_back('\n'); + enum {TAB_WIDTH = 8}; + for (const char *s = line_start; s != end; ++s) { + char c = *s; + if (c == '\t') { + text.append(" ", + TAB_WIDTH - ((indent + s - line_start) % TAB_WIDTH)); + } else if (IsSpace(c)) { + text.push_back(' '); + } else { + text.push_back(*s); + } + } + if (*ptr_ == '\n') + ++ptr_; + } + + // Remove a trailing newline. + if (*text.rbegin() == '\n') + text.resize(text.size() - 1); + + bool literal = type == PARAGRAPH && EndsWith(text, "::"); + if (!literal || text.size() != 2) { + std::size_t size = text.size(); + if (literal) + --size; + EnterBlock(prev_type, type); + handler_->StartBlock(type); + handler_->HandleText(text.c_str(), size); + handler_->EndBlock(); + } + if (literal) { + // Parse a literal block. + const char *line_start = ptr_; + SkipSpace(); + int new_indent = static_cast(ptr_ - line_start); + if (new_indent > indent) + ParseBlock(LITERAL_BLOCK, prev_type, new_indent); + } +} + +void rst::Parser::ParseLineBlock(rst::BlockType &prev_type, int indent) { + std::string text; + for (bool first = true; ; first = false) { + const char *line_start = ptr_; + if (!first) { + // Check indentation. + SkipSpace(); + if (*ptr_ != '|' || !IsSpace(ptr_[1]) || ptr_ - line_start != indent) + break; + ptr_ += 2; + if (!*ptr_) + break; // End of input. + } + // Strip indentation. + line_start = ptr_; + + // Find the end of the line. + while (*ptr_ && *ptr_ != '\n') + ++ptr_; + if (*ptr_ == '\n') + ++ptr_; + text.append(line_start, ptr_); + } + + EnterBlock(prev_type, rst::LINE_BLOCK); + handler_->StartBlock(rst::LINE_BLOCK); + handler_->HandleText(text.c_str(), text.size()); + handler_->EndBlock(); +} + +void rst::Parser::Parse(const char *s) { + BlockType prev_type = PARAGRAPH; + ptr_ = s; + while (*ptr_) { + // Skip whitespace and empty lines. + const char *line_start = ptr_; + SkipSpace(); + if (*ptr_ == '\n') { + ++ptr_; + continue; + } + switch (*ptr_) { + case '.': + if (ptr_[1] == '.') { + char c = ptr_[2]; + if (!IsSpace(c) && c != '\n' && c) + break; + // Parse a directive or a comment. + ptr_ += 2; + SkipSpace(); + std::string type = ParseDirectiveType(); + if (!type.empty() && ptr_[0] == ':' && ptr_[1] == ':') { + ptr_ += 2; + handler_->HandleDirective(type.c_str()); + } + // Skip everything till the end of the line. + while (*ptr_ && *ptr_ != '\n') + ++ptr_; + if (*ptr_ == '\n') + ++ptr_; + continue; + } + break; + case '*': case '+': case '-': + if (IsSpace(ptr_[1])) { + // Parse a bullet list item. + ptr_ += 2; + ParseBlock(LIST_ITEM, prev_type, static_cast(ptr_ - line_start)); + continue; + } + break; + case '|': + if (IsSpace(ptr_[1])) { + // Parse a line block. + int indent = static_cast(ptr_ - line_start); + ptr_ += 2; + ParseLineBlock(prev_type, indent); + continue; + } + break; + } + ParseBlock(std::isspace(line_start[0]) ? BLOCK_QUOTE : PARAGRAPH, + prev_type, static_cast(ptr_ - line_start)); + } + EnterBlock(prev_type, PARAGRAPH); +} diff --git a/src/plugins/cmakeprojectmanager/3rdparty/rstparser/rstparser.h b/src/plugins/cmakeprojectmanager/3rdparty/rstparser/rstparser.h new file mode 100644 index 00000000000..547f128af7c --- /dev/null +++ b/src/plugins/cmakeprojectmanager/3rdparty/rstparser/rstparser.h @@ -0,0 +1,97 @@ +/* + A reStructuredText parser written in C++. + + Copyright (c) 2013, Victor Zverovich + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef RSTPARSER_H_ +#define RSTPARSER_H_ + +#include +#include +#include + +namespace rst { + +enum BlockType { + PARAGRAPH, + LINE_BLOCK, + BLOCK_QUOTE, + BULLET_LIST, + LIST_ITEM, + LITERAL_BLOCK +}; + +// Receive notification of the logical content of a document. +class ContentHandler { + public: + virtual ~ContentHandler(); + + // Receives notification of the beginning of a text block. + virtual void StartBlock(BlockType type) = 0; + + // Receives notification of the end of a text block. + virtual void EndBlock() = 0; + + // Receives notification of text. + virtual void HandleText(const char *text, std::size_t size) = 0; + + // Receives notification of a directive. + virtual void HandleDirective(const char *type) = 0; +}; + +// A parser for a subset of reStructuredText. +class Parser { + private: + ContentHandler *handler_; + const char *ptr_; + + // Skips whitespace. + void SkipSpace(); + + // Parses a directive type. + std::string ParseDirectiveType(); + + // Parses a paragraph. + void ParseParagraph(); + + // Changes the current block type sending notifications if necessary. + void EnterBlock(rst::BlockType &prev_type, rst::BlockType type); + + // Parses a block of text. + void ParseBlock(rst::BlockType type, rst::BlockType &prev_type, int indent); + + // Parses a line block. + void ParseLineBlock(rst::BlockType &prev_type, int indent); + + public: + explicit Parser(ContentHandler *h) : handler_(h), ptr_(0) {} + + // Parses a string containing reStructuredText and returns a document node. + void Parse(const char *s); +}; +} + +#endif // RSTPARSER_H_ + From fbbb78ee7ec4f8a03a21ae6593b45680cd82c3f3 Mon Sep 17 00:00:00 2001 From: hjk Date: Tue, 26 Sep 2023 13:59:23 +0200 Subject: [PATCH 26/27] ProjectExplorer: Actually instantiate the DeviceTypeKAFactory again Task-number: QTCREATORBUG-29647 Change-Id: Ic2d29ae8d053f6526d6c5e4f4370153ab5b7d902 Reviewed-by: Eike Ziller Reviewed-by: hjk --- src/plugins/projectexplorer/kitaspects.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/plugins/projectexplorer/kitaspects.cpp b/src/plugins/projectexplorer/kitaspects.cpp index 57ef6b0fcd4..489f267b7a1 100644 --- a/src/plugins/projectexplorer/kitaspects.cpp +++ b/src/plugins/projectexplorer/kitaspects.cpp @@ -855,6 +855,8 @@ QSet DeviceTypeKitAspectFactory::availableFeatures(const Kit *k) const return {}; } +const DeviceTypeKitAspectFactory theDeviceTypeKitAspectFactory; + // -------------------------------------------------------------------------- // DeviceKitAspect: // -------------------------------------------------------------------------- From 7adee4da24757b65622260487885d3cd76a04151 Mon Sep 17 00:00:00 2001 From: David Schulz Date: Thu, 21 Sep 2023 08:59:15 +0200 Subject: [PATCH 27/27] Utils: allow specifying the requested extension for searchInPath Reducing the expected executable extensions can improve the performance for search in path on Window. Especially if PATHEXT and PATH has a lot of entries, since we collect file attributes for PATHEXT entry count times PATH entry count file paths. Use this optimization in the android toolchain to search for java.exe on windows. Change-Id: I2c2865d685c2de0c03a0fa1fbe7e8afd283174da Reviewed-by: Alessandro Portale Reviewed-by: --- src/libs/utils/environment.cpp | 5 +++-- src/libs/utils/environment.h | 3 ++- src/plugins/android/androidtoolchain.cpp | 3 ++- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/libs/utils/environment.cpp b/src/libs/utils/environment.cpp index 4af5399a7af..d71d76c8b8a 100644 --- a/src/libs/utils/environment.cpp +++ b/src/libs/utils/environment.cpp @@ -225,11 +225,12 @@ QString Environment::expandedValueForKey(const QString &key) const FilePath Environment::searchInPath(const QString &executable, const FilePaths &additionalDirs, - const FilePathPredicate &filter) const + const FilePathPredicate &filter, + FilePath::MatchScope scope) const { const FilePath exec = FilePath::fromUserInput(expandVariables(executable)); const FilePaths dirs = path() + additionalDirs; - return exec.searchInDirectories(dirs, filter, FilePath::WithAnySuffix); + return exec.searchInDirectories(dirs, filter, scope); } FilePaths Environment::path() const diff --git a/src/libs/utils/environment.h b/src/libs/utils/environment.h index 06ac5d20a5c..679b28f0e08 100644 --- a/src/libs/utils/environment.h +++ b/src/libs/utils/environment.h @@ -61,7 +61,8 @@ public: FilePath searchInPath(const QString &executable, const FilePaths &additionalDirs = FilePaths(), - const FilePathPredicate &func = {}) const; + const FilePathPredicate &func = {}, + FilePath::MatchScope = FilePath::WithAnySuffix) const; FilePaths path() const; FilePaths pathListValue(const QString &varName) const; diff --git a/src/plugins/android/androidtoolchain.cpp b/src/plugins/android/androidtoolchain.cpp index 26ca46be2a5..5d96d8c4bdc 100644 --- a/src/plugins/android/androidtoolchain.cpp +++ b/src/plugins/android/androidtoolchain.cpp @@ -94,7 +94,8 @@ void AndroidToolChain::addToEnvironment(Environment &env) const if (javaHome.exists()) { env.set(Constants::JAVA_HOME_ENV_VAR, javaHome.toUserOutput()); const FilePath javaBin = javaHome.pathAppended("bin"); - const FilePath currentJavaFilePath = env.searchInPath("java"); + const FilePath currentJavaFilePath + = env.searchInPath("java", {}, {}, FilePath::WithExeSuffix); if (!currentJavaFilePath.isChildOf(javaBin)) env.prependOrSetPath(javaBin); }