1 /****************************************************************************
2 **
3 ** Copyright (C) 2016 The Qt Company Ltd.
4 ** Contact: https://www.qt.io/licensing/
5 **
6 ** This file is part of Qt Creator.
7 **
8 ** Commercial License Usage
9 ** Licensees holding valid commercial Qt licenses may use this file in
10 ** accordance with the commercial license agreement provided with the
11 ** Software or, alternatively, in accordance with the terms contained in
12 ** a written agreement between you and The Qt Company. For licensing terms
13 ** and conditions see https://www.qt.io/terms-conditions. For further
14 ** information use the contact form at https://www.qt.io/contact-us.
15 **
16 ** GNU General Public License Usage
17 ** Alternatively, this file may be used under the terms of the GNU
18 ** General Public License version 3 as published by the Free Software
19 ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
20 ** included in the packaging of this file. Please review the following
21 ** information to ensure the GNU General Public License requirements will
22 ** be met: https://www.gnu.org/licenses/gpl-3.0.html.
23 **
24 ****************************************************************************/
25 
26 #include "qmljseditingsettingspage.h"
27 #include "qmljseditor.h"
28 #include "qmljseditorconstants.h"
29 #include "qmljseditordocument.h"
30 #include "qmljseditorplugin.h"
31 #include "qmljshighlighter.h"
32 #include "qmljsoutline.h"
33 #include "qmljsquickfixassist.h"
34 #include "qmltaskmanager.h"
35 #include "quicktoolbar.h"
36 
37 #include <qmljs/qmljsicons.h>
38 #include <qmljs/qmljsmodelmanagerinterface.h>
39 #include <qmljs/qmljsreformatter.h>
40 #include <qmljstools/qmljstoolsconstants.h>
41 
42 #include <coreplugin/coreconstants.h>
43 #include <coreplugin/icore.h>
44 #include <coreplugin/fileiconprovider.h>
45 #include <coreplugin/actionmanager/actionmanager.h>
46 #include <coreplugin/actionmanager/actioncontainer.h>
47 #include <coreplugin/actionmanager/command.h>
48 #include <coreplugin/editormanager/editormanager.h>
49 #include <projectexplorer/taskhub.h>
50 #include <projectexplorer/project.h>
51 #include <projectexplorer/projecttree.h>
52 #include <projectexplorer/projectexplorerconstants.h>
53 #include <texteditor/snippets/snippetprovider.h>
54 #include <texteditor/texteditorconstants.h>
55 #include <texteditor/tabsettings.h>
56 #include <utils/qtcassert.h>
57 #include <utils/json.h>
58 
59 #include <QTextDocument>
60 #include <QMenu>
61 #include <QAction>
62 
63 using namespace QmlJSEditor::Constants;
64 using namespace ProjectExplorer;
65 using namespace Core;
66 using namespace Utils;
67 
68 namespace QmlJSEditor {
69 namespace Internal {
70 
71 class QmlJSEditorPluginPrivate : public QObject
72 {
73 public:
74     QmlJSEditorPluginPrivate();
75 
76     void currentEditorChanged(IEditor *editor);
77     void runSemanticScan();
78     void checkCurrentEditorSemanticInfoUpToDate();
79     void autoFormatOnSave(IDocument *document);
80 
81     Command *addToolAction(QAction *a, Context &context, Id id,
82                            ActionContainer *c1, const QString &keySequence);
83 
84     void renameUsages();
85     void reformatFile();
86     void showContextPane();
87 
88     QmlJSQuickFixAssistProvider m_quickFixAssistProvider;
89     QmlTaskManager m_qmlTaskManager;
90 
91     QAction *m_reformatFileAction = nullptr;
92 
93     QPointer<QmlJSEditorDocument> m_currentDocument;
94 
95     Utils::JsonSchemaManager m_jsonManager{
96         {ICore::userResourcePath("json/").toString(),
97          ICore::resourcePath("json/").toString()}};
98     QmlJSEditorFactory m_qmlJSEditorFactory;
99     QmlJSOutlineWidgetFactory m_qmlJSOutlineWidgetFactory;
100     QuickToolBar m_quickToolBar;
101     QmlJsEditingSettingsPage m_qmJSEditingSettingsPage;
102 };
103 
104 static QmlJSEditorPlugin *m_instance = nullptr;
105 
QmlJSEditorPlugin()106 QmlJSEditorPlugin::QmlJSEditorPlugin()
107 {
108     m_instance = this;
109 }
110 
~QmlJSEditorPlugin()111 QmlJSEditorPlugin::~QmlJSEditorPlugin()
112 {
113     delete QmlJS::Icons::instance(); // delete object held by singleton
114     delete d;
115     d = nullptr;
116     m_instance = nullptr;
117 }
118 
initialize(const QStringList & arguments,QString * errorMessage)119 bool QmlJSEditorPlugin::initialize(const QStringList &arguments, QString *errorMessage)
120 {
121     Q_UNUSED(arguments)
122     Q_UNUSED(errorMessage)
123 
124     d = new QmlJSEditorPluginPrivate;
125 
126     return true;
127 }
128 
QmlJSEditorPluginPrivate()129 QmlJSEditorPluginPrivate::QmlJSEditorPluginPrivate()
130 {
131     TextEditor::SnippetProvider::registerGroup(Constants::QML_SNIPPETS_GROUP_ID,
132                                                QmlJSEditorPlugin::tr("QML", "SnippetProvider"),
133                                                &QmlJSEditorFactory::decorateEditor);
134 
135     QmlJS::ModelManagerInterface *modelManager = QmlJS::ModelManagerInterface::instance();
136 
137     // QML task updating manager
138     connect(modelManager, &QmlJS::ModelManagerInterface::documentChangedOnDisk,
139             &m_qmlTaskManager, &QmlTaskManager::updateMessages);
140     // recompute messages when information about libraries changes
141     connect(modelManager, &QmlJS::ModelManagerInterface::libraryInfoUpdated,
142             &m_qmlTaskManager, &QmlTaskManager::updateMessages);
143     // recompute messages when project data changes (files added or removed)
144     connect(modelManager, &QmlJS::ModelManagerInterface::projectInfoUpdated,
145             &m_qmlTaskManager, &QmlTaskManager::updateMessages);
146     connect(modelManager,
147             &QmlJS::ModelManagerInterface::aboutToRemoveFiles,
148             &m_qmlTaskManager,
149             &QmlTaskManager::documentsRemoved);
150 
151     Context context(Constants::C_QMLJSEDITOR_ID, Constants::C_QTQUICKDESIGNEREDITOR_ID);
152 
153     ActionContainer *contextMenu = ActionManager::createMenu(Constants::M_CONTEXT);
154     ActionContainer *qmlToolsMenu = ActionManager::actionContainer(Id(QmlJSTools::Constants::M_TOOLS_QMLJS));
155 
156     qmlToolsMenu->addSeparator();
157 
158     Command *cmd;
159     cmd = ActionManager::command(TextEditor::Constants::FOLLOW_SYMBOL_UNDER_CURSOR);
160     contextMenu->addAction(cmd);
161     qmlToolsMenu->addAction(cmd);
162 
163     cmd = ActionManager::command(TextEditor::Constants::FIND_USAGES);
164     contextMenu->addAction(cmd);
165     qmlToolsMenu->addAction(cmd);
166 
167     cmd = ActionManager::command(TextEditor::Constants::RENAME_SYMBOL);
168     contextMenu->addAction(cmd);
169     qmlToolsMenu->addAction(cmd);
170 
171     QAction *semanticScan = new QAction(QmlJSEditorPlugin::tr("Run Checks"), this);
172     cmd = ActionManager::registerAction(semanticScan, Id("QmlJSEditor.RunSemanticScan"));
173     cmd->setDefaultKeySequence(QKeySequence(QmlJSEditorPlugin::tr("Ctrl+Shift+C")));
174     connect(semanticScan, &QAction::triggered, this, &QmlJSEditorPluginPrivate::runSemanticScan);
175     qmlToolsMenu->addAction(cmd);
176 
177     m_reformatFileAction = new QAction(QmlJSEditorPlugin::tr("Reformat File"), this);
178     cmd = ActionManager::registerAction(m_reformatFileAction,
179                                         Id("QmlJSEditor.ReformatFile"),
180                                         context);
181     connect(m_reformatFileAction, &QAction::triggered, this, &QmlJSEditorPluginPrivate::reformatFile);
182     qmlToolsMenu->addAction(cmd);
183 
184     QAction *inspectElementAction = new QAction(QmlJSEditorPlugin::tr("Inspect API for Element Under Cursor"), this);
185     cmd = ActionManager::registerAction(inspectElementAction,
186                                         Id("QmlJSEditor.InspectElementUnderCursor"),
187                                         context);
188     connect(inspectElementAction, &QAction::triggered, [] {
189         if (auto widget = qobject_cast<QmlJSEditorWidget *>(EditorManager::currentEditor()->widget()))
190             widget->inspectElementUnderCursor();
191     });
192     qmlToolsMenu->addAction(cmd);
193 
194     QAction *showQuickToolbar = new QAction(QmlJSEditorPlugin::tr("Show Qt Quick Toolbar"), this);
195     cmd = ActionManager::registerAction(showQuickToolbar, Constants::SHOW_QT_QUICK_HELPER, context);
196     cmd->setDefaultKeySequence(useMacShortcuts ? QKeySequence(Qt::META | Qt::ALT | Qt::Key_Space)
197                                                : QKeySequence(Qt::CTRL | Qt::ALT | Qt::Key_Space));
198     connect(showQuickToolbar, &QAction::triggered, this, &QmlJSEditorPluginPrivate::showContextPane);
199     contextMenu->addAction(cmd);
200     qmlToolsMenu->addAction(cmd);
201 
202     // Insert marker for "Refactoring" menu:
203     Command *sep = contextMenu->addSeparator();
204     sep->action()->setObjectName(QLatin1String(Constants::M_REFACTORING_MENU_INSERTION_POINT));
205     contextMenu->addSeparator();
206 
207     cmd = ActionManager::command(TextEditor::Constants::AUTO_INDENT_SELECTION);
208     contextMenu->addAction(cmd);
209 
210     cmd = ActionManager::command(TextEditor::Constants::UN_COMMENT_SELECTION);
211     contextMenu->addAction(cmd);
212 
213     FileIconProvider::registerIconOverlayForSuffix(ProjectExplorer::Constants::FILEOVERLAY_QML, "qml");
214 
215     connect(EditorManager::instance(), &EditorManager::currentEditorChanged,
216             this, &QmlJSEditorPluginPrivate::currentEditorChanged);
217 
218     connect(EditorManager::instance(), &EditorManager::aboutToSave,
219             this, &QmlJSEditorPluginPrivate::autoFormatOnSave);
220 }
221 
extensionsInitialized()222 void QmlJSEditorPlugin::extensionsInitialized()
223 {
224     TaskHub::addCategory(Constants::TASK_CATEGORY_QML, tr("QML"));
225     TaskHub::addCategory(Constants::TASK_CATEGORY_QML_ANALYSIS, tr("QML Analysis"), false);
226 }
227 
aboutToShutdown()228 ExtensionSystem::IPlugin::ShutdownFlag QmlJSEditorPlugin::aboutToShutdown()
229 {
230     return IPlugin::aboutToShutdown();
231 }
232 
jsonManager()233 Utils::JsonSchemaManager *QmlJSEditorPlugin::jsonManager()
234 {
235     return &m_instance->d->m_jsonManager;
236 }
237 
quickToolBar()238 QuickToolBar *QmlJSEditorPlugin::quickToolBar()
239 {
240     QTC_ASSERT(m_instance && m_instance->d, return new QuickToolBar());
241     return &m_instance->d->m_quickToolBar;
242 }
243 
renameUsages()244 void QmlJSEditorPluginPrivate::renameUsages()
245 {
246     if (auto editor = qobject_cast<QmlJSEditorWidget*>(EditorManager::currentEditor()->widget()))
247         editor->renameSymbolUnderCursor();
248 }
249 
reformatFile()250 void QmlJSEditorPluginPrivate::reformatFile()
251 {
252     if (m_currentDocument) {
253         QmlJS::Document::Ptr document = m_currentDocument->semanticInfo().document;
254         QmlJS::Snapshot snapshot = QmlJS::ModelManagerInterface::instance()->snapshot();
255 
256         if (m_currentDocument->isSemanticInfoOutdated()) {
257             QmlJS::Document::MutablePtr latestDocument;
258 
259             const QString fileName = m_currentDocument->filePath().toString();
260             latestDocument = snapshot.documentFromSource(QString::fromUtf8(m_currentDocument->contents()),
261                                                          fileName,
262                                                          QmlJS::ModelManagerInterface::guessLanguageOfFile(fileName));
263             latestDocument->parseQml();
264             snapshot.insert(latestDocument);
265             document = latestDocument;
266         }
267 
268         if (!document->isParsedCorrectly())
269             return;
270 
271         TextEditor::TabSettings tabSettings = m_currentDocument->tabSettings();
272         const QString &newText = QmlJS::reformat(document,
273                                                  tabSettings.m_indentSize,
274                                                  tabSettings.m_tabSize);
275 
276         //  QTextDocument::setPlainText cannot be used, as it would reset undo/redo history
277         const auto setNewText = [this, &newText]() {
278             QTextCursor tc(m_currentDocument->document());
279             tc.movePosition(QTextCursor::Start);
280             tc.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
281             tc.insertText(newText);
282         };
283 
284         IEditor *ed = EditorManager::currentEditor();
285         if (ed) {
286             int line = ed->currentLine();
287             int column = ed->currentColumn();
288             setNewText();
289             ed->gotoLine(line, column);
290         } else {
291             setNewText();
292         }
293     }
294 }
295 
showContextPane()296 void QmlJSEditorPluginPrivate::showContextPane()
297 {
298     if (auto editor = qobject_cast<QmlJSEditorWidget*>(EditorManager::currentEditor()->widget()))
299         editor->showContextPane();
300 }
301 
addToolAction(QAction * a,Context & context,Id id,ActionContainer * c1,const QString & keySequence)302 Command *QmlJSEditorPluginPrivate::addToolAction(QAction *a,
303                                                  Context &context, Id id,
304                                                  ActionContainer *c1, const QString &keySequence)
305 {
306     Command *command = ActionManager::registerAction(a, id, context);
307     if (!keySequence.isEmpty())
308         command->setDefaultKeySequence(QKeySequence(keySequence));
309     c1->addAction(command);
310     return command;
311 }
312 
quickFixAssistProvider()313 QmlJSQuickFixAssistProvider *QmlJSEditorPlugin::quickFixAssistProvider()
314 {
315     return &m_instance->d->m_quickFixAssistProvider;
316 }
317 
currentEditorChanged(IEditor * editor)318 void QmlJSEditorPluginPrivate::currentEditorChanged(IEditor *editor)
319 {
320     QmlJSEditorDocument *document = nullptr;
321     if (editor)
322         document = qobject_cast<QmlJSEditorDocument *>(editor->document());
323 
324     if (m_currentDocument)
325         m_currentDocument->disconnect(this);
326     m_currentDocument = document;
327     if (document) {
328         connect(document->document(), &QTextDocument::contentsChanged,
329                 this, &QmlJSEditorPluginPrivate::checkCurrentEditorSemanticInfoUpToDate);
330         connect(document, &QmlJSEditorDocument::semanticInfoUpdated,
331                 this, &QmlJSEditorPluginPrivate::checkCurrentEditorSemanticInfoUpToDate);
332     }
333 }
334 
runSemanticScan()335 void QmlJSEditorPluginPrivate::runSemanticScan()
336 {
337     m_qmlTaskManager.updateSemanticMessagesNow();
338     TaskHub::setCategoryVisibility(Constants::TASK_CATEGORY_QML_ANALYSIS, true);
339     TaskHub::requestPopup();
340 }
341 
checkCurrentEditorSemanticInfoUpToDate()342 void QmlJSEditorPluginPrivate::checkCurrentEditorSemanticInfoUpToDate()
343 {
344     const bool semanticInfoUpToDate = m_currentDocument && !m_currentDocument->isSemanticInfoOutdated();
345     m_reformatFileAction->setEnabled(semanticInfoUpToDate);
346 }
347 
autoFormatOnSave(IDocument * document)348 void QmlJSEditorPluginPrivate::autoFormatOnSave(IDocument *document)
349 {
350     if (!QmlJsEditingSettings::get().autoFormatOnSave())
351         return;
352 
353     // Check that we are dealing with a QML/JS editor
354     if (document->id() != Constants::C_QMLJSEDITOR_ID
355         && document->id() != Constants::C_QTQUICKDESIGNEREDITOR_ID)
356         return;
357 
358     // Check if file is contained in the current project (if wished)
359     if (QmlJsEditingSettings::get().autoFormatOnlyCurrentProject()) {
360         const Project *pro = ProjectTree::currentProject();
361         if (!pro || !pro->files(Project::SourceFiles).contains(document->filePath()))
362             return;
363     }
364 
365     reformatFile();
366 }
367 
368 } // namespace Internal
369 } // namespace QmlJSEditor
370