summaryrefslogtreecommitdiff
path: root/src/plugins/qmldesigner/qmldesignerplugin.cpp
blob: 6226e54e808ddd675a4377a221955f8c5e7031f2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/

#include "qmldesignerplugin.h"
#include "designmodecontext.h"
#include "designmodewidget.h"
#include "dynamiclicensecheck.h"
#include "exception.h"
#include "generateresource.h"
#include "nodeinstanceview.h"
#include "openuiqmlfiledialog.h"
#include "qmldesignerconstants.h"
#include "qmldesignerprojectmanager.h"
#include "quick2propertyeditorview.h"
#include "settingspage.h"

#include <metainfo.h>
#include <connectionview.h>
#include <sourcetool/sourcetool.h>
#include <colortool/colortool.h>
#include <curveeditor/curveeditorview.h>
#include <formeditor/transitiontool.h>
#include <texttool/texttool.h>
#include <timelineeditor/timelineview.h>
#include <transitioneditor/transitioneditorview.h>
#include <eventlist/eventlistpluginview.h>
#include <pathtool/pathtool.h>

#include <qmljseditor/qmljseditor.h>
#include <qmljseditor/qmljseditorconstants.h>
#include <qmljseditor/qmljseditordocument.h>

#include <qmljstools/qmljstoolsconstants.h>

#include <qmlprojectmanager/qmlproject.h>

#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/designmode.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/icore.h>
#include <coreplugin/idocument.h>
#include <coreplugin/messagebox.h>
#include <coreplugin/modemanager.h>
#include <extensionsystem/pluginmanager.h>
#include <extensionsystem/pluginspec.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/session.h>
#include <projectexplorer/target.h>
#include <sqlitelibraryinitializer.h>
#include <qmljs/qmljsmodelmanagerinterface.h>

#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <utils/algorithm.h>

#include <QAction>
#include <QTimer>
#include <QCoreApplication>
#include <qplugin.h>
#include <QDebug>
#include <QProcessEnvironment>
#include <QScreen>
#include <QWindow>
#include <QApplication>

#include "nanotrace/nanotrace.h"
#include <modelnodecontextmenu_helper.h>

static Q_LOGGING_CATEGORY(qmldesignerLog, "qtc.qmldesigner", QtWarningMsg)

using namespace QmlDesigner::Internal;

namespace QmlDesigner {

namespace Internal {

QString normalizeIdentifier(const QString &string)
{
    if (string.isEmpty())
        return {};
    QString ret = string;
    ret.remove(' ');
    ret[0] = ret.at(0).toLower();
    return ret;
}

class QtQuickDesignerFactory : public QmlJSEditor::QmlJSEditorFactory
{
public:
    QtQuickDesignerFactory();
};

QtQuickDesignerFactory::QtQuickDesignerFactory()
    : QmlJSEditorFactory(QmlJSEditor::Constants::C_QTQUICKDESIGNEREDITOR_ID)
{
    setDisplayName(QCoreApplication::translate("OpenWith::Editors", "Qt Quick Designer"));

    addMimeType(QmlJSTools::Constants::QMLUI_MIMETYPE);
    setDocumentCreator([this]() {
        auto document = new QmlJSEditor::QmlJSEditorDocument(id());
        document->setIsDesignModePreferred(
                    QmlDesigner::QmlDesignerPlugin::settings().value(
                        QmlDesigner::DesignerSettingsKey::ALWAYS_DESIGN_MODE).toBool());
        return document;
    });
}

} // namespace Internal

class QmlDesignerPluginPrivate
{
public:
    DesignerSettings settings{Core::ICore::instance()->settings()};
    QmlDesignerProjectManager projectManager;
    ViewManager viewManager{projectManager.asynchronousImageCache(),
                            projectManager.asynchronousMeshImageCache()};
    DocumentManager documentManager;
    ShortCutManager shortCutManager;
    SettingsPage settingsPage;
    DesignModeWidget mainWidget;
    QtQuickDesignerFactory m_qtQuickDesignerFactory;
    bool blockEditorChange = false;
};

QmlDesignerPlugin *QmlDesignerPlugin::m_instance = nullptr;

static bool isInDesignerMode()
{
    return Core::ModeManager::currentModeId() == Core::Constants::MODE_DESIGN;
}

static bool checkIfEditorIsQtQuick(Core::IEditor *editor)
{
    if (editor
        && (editor->document()->id() == QmlJSEditor::Constants::C_QMLJSEDITOR_ID
            || editor->document()->id() == QmlJSEditor::Constants::C_QTQUICKDESIGNEREDITOR_ID)) {
        QmlJS::ModelManagerInterface *modelManager = QmlJS::ModelManagerInterface::instance();
        QmlJS::Document::Ptr document = modelManager->ensuredGetDocumentForPath(editor->document()->filePath().toString());
        if (!document.isNull())
            return document->language() == QmlJS::Dialect::QmlQtQuick2
                    || document->language() == QmlJS::Dialect::QmlQtQuick2Ui
                    || document->language() == QmlJS::Dialect::Qml;

        if (Core::ModeManager::currentModeId() == Core::Constants::MODE_DESIGN) {
            Core::AsynchronousMessageBox::warning(QmlDesignerPlugin::tr("Cannot Open Design Mode"),
                                                  QmlDesignerPlugin::tr("The QML file is not currently opened in a QML Editor."));
            Core::ModeManager::activateMode(Core::Constants::MODE_EDIT);
        }
    }

    return false;
}

static bool isDesignerMode(Utils::Id mode)
{
    return mode == Core::Constants::MODE_DESIGN;
}

static bool documentIsAlreadyOpen(DesignDocument *designDocument, Core::IEditor *editor, Utils::Id newMode)
{
    return designDocument
            && editor == designDocument->editor()
            && isDesignerMode(newMode);
}

static bool shouldAssertInException()
{
    QProcessEnvironment processEnvironment = QProcessEnvironment::systemEnvironment();
    return !processEnvironment.value("QMLDESIGNER_ASSERT_ON_EXCEPTION").isEmpty();
}

static bool warningsForQmlFilesInsteadOfUiQmlEnabled()
{
    return QmlDesignerPlugin::settings().value(DesignerSettingsKey::WARNING_FOR_QML_FILES_INSTEAD_OF_UIQML_FILES).toBool();
}

QmlDesignerPlugin::QmlDesignerPlugin()
{
    m_instance = this;
    // Exceptions should never ever assert: they are handled in a number of
    // places where it is actually VALID AND EXPECTED BEHAVIOUR to get an
    // exception.
    // If you still want to see exactly where the exception originally
    // occurred, then you have various ways to do this:
    //  1. set a breakpoint on the constructor of the exception
    //  2. in gdb: "catch throw" or "catch throw Exception"
    //  3. set a breakpoint on __raise_exception()
    // And with gdb, you can even do this from your ~/.gdbinit file.
    // DnD is not working with gdb so this is still needed to get a good stacktrace

    Exception::setShouldAssert(shouldAssertInException());
}

QmlDesignerPlugin::~QmlDesignerPlugin()
{
    if (d)
        Core::DesignMode::unregisterDesignWidget(&d->mainWidget);
    delete d;
    d = nullptr;
    m_instance = nullptr;
}

////////////////////////////////////////////////////
//
// INHERITED FROM ExtensionSystem::Plugin
//
////////////////////////////////////////////////////
bool QmlDesignerPlugin::initialize(const QStringList & /*arguments*/, QString *errorMessage/* = 0*/)
{
    Sqlite::LibraryInitializer::initialize();
    QDir{}.mkpath(Core::ICore::cacheResourcePath().toString());

    if (!Utils::HostOsInfo::canCreateOpenGLContext(errorMessage))
        return false;
    d = new QmlDesignerPluginPrivate;
    if (QmlProjectManager::QmlProject::isQtDesignStudio())
        GenerateResource::generateMenuEntry(this);

    const QString fontPath
        = Core::ICore::resourcePath(
                "qmldesigner/propertyEditorQmlSources/imports/StudioTheme/icons.ttf")
              .toString();
    if (QFontDatabase::addApplicationFont(fontPath) < 0)
        qCWarning(qmldesignerLog) << "Could not add font " << fontPath << "to font database";

#ifdef NANOTRACE_ENABLED
    auto handleShutdownNanotraceAction = [](const SelectionContext &) {};
    auto shutdownNanotraceIcon = []() { return QIcon(); };
    auto startNanotraceAction = new ModelNodeAction("Start Nanotrace",
                     QObject::tr("Start Nanotrace"),
                     shutdownNanotraceIcon(),
                     QObject::tr("Start Nanotrace"),
                     ComponentCoreConstants::eventListCategory,
                     QKeySequence(),
                     220,
                     handleShutdownNanotraceAction);

    connect(startNanotraceAction->defaultAction(), &QAction::triggered, [this]() {
        d->viewManager.nodeInstanceView()->startNanotrace();
    });

    designerActionManager().addDesignerAction(startNanotraceAction);

    auto shutDownNanotraceAction = new ModelNodeAction("ShutDown Nanotrace",
                      QObject::tr("Shut Down Nanotrace"),
                      shutdownNanotraceIcon(),
                      QObject::tr("Shut Down Nanotrace"),
                      ComponentCoreConstants::eventListCategory,
                      QKeySequence(),
                      220,
                      handleShutdownNanotraceAction);

    connect(shutDownNanotraceAction->defaultAction(), &QAction::triggered, [this]() {
        d->viewManager.nodeInstanceView()->endNanotrace();
    });

    designerActionManager().addDesignerAction(shutDownNanotraceAction);
#endif
    //TODO Move registering those types out of the property editor, since they are used also in the states editor
    Quick2PropertyEditorView::registerQmlTypes();
    return true;
}

bool QmlDesignerPlugin::delayedInitialize()
{
    // adding default path to item library plugins
    const QString postfix = Utils::HostOsInfo::isMacHost() ? QString("/QmlDesigner")
                                                           : QString("/qmldesigner");
    const QStringList pluginPaths =
        Utils::transform(ExtensionSystem::PluginManager::pluginPaths(), [postfix](const QString &p) {
            return QString(p + postfix);
        });
    MetaInfo::setPluginPaths(pluginPaths);

    d->viewManager.registerView(std::make_unique<QmlDesigner::Internal::ConnectionView>());

    auto timelineView = d->viewManager.registerView(std::make_unique<QmlDesigner::TimelineView>());
    timelineView->registerActions();

    d->viewManager.registerView(std::make_unique<QmlDesigner::CurveEditorView>());

    auto eventlistView = d->viewManager.registerView(
        std::make_unique<QmlDesigner::EventListPluginView>());
    eventlistView->registerActions();

    auto transitionEditorView = d->viewManager.registerView(
        std::make_unique<QmlDesigner::TransitionEditorView>());
    transitionEditorView->registerActions();

    d->viewManager.registerFormEditorTool(std::make_unique<QmlDesigner::SourceTool>());
    d->viewManager.registerFormEditorTool(std::make_unique<QmlDesigner::ColorTool>());
    d->viewManager.registerFormEditorTool(std::make_unique<QmlDesigner::TextTool>());
    d->viewManager.registerFormEditorTool(std::make_unique<QmlDesigner::PathTool>());
    d->viewManager.registerFormEditorTool(std::make_unique<QmlDesigner::TransitionTool>());

    if (QmlProjectManager::QmlProject::isQtDesignStudio()) {
        d->mainWidget.initialize();

        emitUsageStatistics("StandaloneMode");
        if (QmlProjectManager::QmlProject::isQtDesignStudioStartedFromQtC())
            emitUsageStatistics("QDSlaunchedFromQtC");
        emitUsageStatistics("qdsStartupCount");

        FoundLicense license = checkLicense();
        if (license == FoundLicense::enterprise)
            Core::ICore::appendAboutInformation(tr("License: Enterprise"));
        else if (license == FoundLicense::professional)
            Core::ICore::appendAboutInformation(tr("License: Professional"));

        if (!licensee().isEmpty())
            Core::ICore::appendAboutInformation(tr("Licensee: %1").arg(licensee()));
    }

    MetaInfo::global();

    return true;
}

void QmlDesignerPlugin::extensionsInitialized()
{
    Core::DesignMode::setDesignModeIsRequired();
    // delay after Core plugin's extensionsInitialized, so the DesignMode is availabe
    connect(Core::ICore::instance(), &Core::ICore::coreAboutToOpen, this, [this] {
        integrateIntoQtCreator(&d->mainWidget);
    });

    auto &actionManager = d->viewManager.designerActionManager();
    actionManager.createDefaultDesignerActions();
    actionManager.createDefaultAddResourceHandler();
    actionManager.createDefaultModelNodePreviewImageHandlers();
    actionManager.polishActions();
}

ExtensionSystem::IPlugin::ShutdownFlag QmlDesignerPlugin::aboutToShutdown()
{
    if (QmlProjectManager::QmlProject::isQtDesignStudio())
        emitUsageStatistics("qdsShutdownCount");

    return SynchronousShutdown;
}

static QStringList allUiQmlFilesforCurrentProject(const Utils::FilePath &fileName)
{
    QStringList list;
    ProjectExplorer::Project *currentProject = ProjectExplorer::SessionManager::projectForFile(fileName);

    if (currentProject) {
        const QList<Utils::FilePath> fileNames = currentProject->files(ProjectExplorer::Project::SourceFiles);
        for (const Utils::FilePath &fileName : fileNames) {
            if (fileName.endsWith(".ui.qml"))
                list.append(fileName.toString());
        }
    }

    return list;
}

static QString projectPath(const Utils::FilePath &fileName)
{
    QString path;
    ProjectExplorer::Project *currentProject = ProjectExplorer::SessionManager::projectForFile(fileName);

    if (currentProject)
        path = currentProject->projectDirectory().toString();

    return path;
}

void QmlDesignerPlugin::integrateIntoQtCreator(QWidget *modeWidget)
{
    auto context = new Internal::DesignModeContext(modeWidget);
    Core::ICore::addContextObject(context);
    Core::Context qmlDesignerMainContext(Constants::C_QMLDESIGNER);
    Core::Context qmlDesignerFormEditorContext(Constants::C_QMLFORMEDITOR);
    Core::Context qmlDesignerEditor3dContext(Constants::C_QMLEDITOR3D);
    Core::Context qmlDesignerNavigatorContext(Constants::C_QMLNAVIGATOR);
    Core::Context qmlDesignerMaterialBrowserContext(Constants::C_QMLMATERIALBROWSER);

    context->context().add(qmlDesignerMainContext);
    context->context().add(qmlDesignerFormEditorContext);
    context->context().add(qmlDesignerEditor3dContext);
    context->context().add(qmlDesignerNavigatorContext);
    context->context().add(qmlDesignerMaterialBrowserContext);
    context->context().add(ProjectExplorer::Constants::QMLJS_LANGUAGE_ID);

    d->shortCutManager.registerActions(qmlDesignerMainContext, qmlDesignerFormEditorContext,
                                       qmlDesignerEditor3dContext, qmlDesignerNavigatorContext,
                                       qmlDesignerMaterialBrowserContext);

    const QStringList mimeTypes = { QmlJSTools::Constants::QML_MIMETYPE,
                                    QmlJSTools::Constants::QMLUI_MIMETYPE };

    Core::DesignMode::registerDesignWidget(modeWidget, mimeTypes, context->context());

    connect(Core::DesignMode::instance(), &Core::DesignMode::actionsUpdated,
        &d->shortCutManager, &ShortCutManager::updateActions);

    connect(Core::EditorManager::instance(), &Core::EditorManager::currentEditorChanged, [this] (Core::IEditor *editor) {
        if (d && checkIfEditorIsQtQuick(editor) && isInDesignerMode())
            changeEditor();
    });

    connect(Core::EditorManager::instance(), &Core::EditorManager::editorsClosed, [this] (QList<Core::IEditor*> editors) {
        if (d) {
            if (d->documentManager.hasCurrentDesignDocument()
                    && editors.contains(currentDesignDocument()->textEditor()))
                hideDesigner();

            d->documentManager.removeEditors(editors);
        }
    });

    connect(Core::ModeManager::instance(),
            &Core::ModeManager::currentModeChanged,
            [this](Utils::Id newMode, Utils::Id oldMode) {
                Core::IEditor *currentEditor = Core::EditorManager::currentEditor();
                if (d && currentEditor && checkIfEditorIsQtQuick(currentEditor)
                    && !documentIsAlreadyOpen(currentDesignDocument(), currentEditor, newMode)) {
                    if (isDesignerMode(newMode)) {
                        showDesigner();
                    } else if (currentDesignDocument()
                               || (!isDesignerMode(newMode) && isDesignerMode(oldMode))) {
                        hideDesigner();
                    }
                }
            });
}

void QmlDesignerPlugin::showDesigner()
{
    QTC_ASSERT(!d->documentManager.hasCurrentDesignDocument(), return);

    d->mainWidget.initialize();

    const Utils::FilePath fileName = Core::EditorManager::currentEditor()->document()->filePath();
    const QStringList allUiQmlFiles = allUiQmlFilesforCurrentProject(fileName);
    if (warningsForQmlFilesInsteadOfUiQmlEnabled() && !fileName.endsWith(".ui.qml") && !allUiQmlFiles.isEmpty()) {
        OpenUiQmlFileDialog dialog(&d->mainWidget);
        dialog.setUiQmlFiles(projectPath(fileName), allUiQmlFiles);
        dialog.exec();
        if (dialog.uiFileOpened()) {
            Core::ModeManager::activateMode(Core::Constants::MODE_EDIT);
            Core::EditorManager::openEditorAt(
                {Utils::FilePath::fromString(dialog.uiQmlFile()), 0, 0});
            return;
        }
    }

    d->shortCutManager.disconnectUndoActions(currentDesignDocument());
    d->documentManager.setCurrentDesignDocument(Core::EditorManager::currentEditor());
    d->shortCutManager.connectUndoActions(currentDesignDocument());

    if (d->documentManager.hasCurrentDesignDocument()) {
        activateAutoSynchronization();
        d->shortCutManager.updateActions(currentDesignDocument()->textEditor());
        d->viewManager.pushFileOnCrumbleBar(currentDesignDocument()->fileName());
    }

    d->shortCutManager.updateUndoActions(currentDesignDocument());

    m_usageTimer.restart();
}

void QmlDesignerPlugin::hideDesigner()
{
    if (d->documentManager.hasCurrentDesignDocument()) {
        deactivateAutoSynchronization();
        d->mainWidget.saveSettings();
    }

    d->shortCutManager.disconnectUndoActions(currentDesignDocument());
    d->documentManager.setCurrentDesignDocument(nullptr);
    d->shortCutManager.updateUndoActions(nullptr);
    emitUsageStatisticsTime(QmlDesigner::Constants::EVENT_DESIGNMODE_TIME, m_usageTimer.elapsed());
}

void QmlDesignerPlugin::changeEditor()
{
    if (d->blockEditorChange)
         return;

    if (d->documentManager.hasCurrentDesignDocument()) {
        deactivateAutoSynchronization();
        d->mainWidget.saveSettings();
    }

    d->shortCutManager.disconnectUndoActions(currentDesignDocument());
    d->documentManager.setCurrentDesignDocument(Core::EditorManager::currentEditor());
    d->mainWidget.initialize();
    d->shortCutManager.connectUndoActions(currentDesignDocument());

    if (d->documentManager.hasCurrentDesignDocument()) {
        activateAutoSynchronization();
        d->viewManager.pushFileOnCrumbleBar(currentDesignDocument()->fileName());
        d->viewManager.setComponentViewToMaster();
    }

    d->shortCutManager.updateUndoActions(currentDesignDocument());
}

void QmlDesignerPlugin::jumpTextCursorToSelectedModelNode()
{
    // visual editor -> text editor
    ModelNode selectedNode;
    if (!rewriterView()->selectedModelNodes().isEmpty())
        selectedNode = rewriterView()->selectedModelNodes().constFirst();

    if (selectedNode.isValid()) {
        const int nodeOffset = rewriterView()->nodeOffset(selectedNode);
        if (nodeOffset > 0) {
            const ModelNode currentSelectedNode = rewriterView()->
                nodeAtTextCursorPosition(currentDesignDocument()->plainTextEdit()->textCursor().position());
            if (currentSelectedNode != selectedNode) {
                int line, column;
                currentDesignDocument()->textEditor()->convertPosition(nodeOffset, &line, &column);
                // line has to be 1 based, column 0 based!
                currentDesignDocument()->textEditor()->gotoLine(line, column - 1);
            }
        }
    }
}

void QmlDesignerPlugin::selectModelNodeUnderTextCursor()
{
    const int cursorPosition = currentDesignDocument()->plainTextEdit()->textCursor().position();
    ModelNode modelNode = rewriterView()->nodeAtTextCursorPosition(cursorPosition);
    if (modelNode.isValid())
        rewriterView()->setSelectedModelNode(modelNode);
}

void QmlDesignerPlugin::activateAutoSynchronization()
{
    // text editor -> visual editor
    if (!currentDesignDocument()->isDocumentLoaded())
        currentDesignDocument()->loadDocument(currentDesignDocument()->plainTextEdit());

    currentDesignDocument()->updateActiveTarget();
    d->mainWidget.enableWidgets();
    currentDesignDocument()->attachRewriterToModel();

    resetModelSelection();

    viewManager().attachComponentView();
    viewManager().attachViewsExceptRewriterAndComponetView();

    selectModelNodeUnderTextCursor();

    d->mainWidget.setupNavigatorHistory(currentDesignDocument()->textEditor());

    currentDesignDocument()->updateSubcomponentManager();
}

void QmlDesignerPlugin::deactivateAutoSynchronization()
{
    viewManager().detachViewsExceptRewriterAndComponetView();
    viewManager().detachComponentView();
    viewManager().detachRewriterView();
    documentManager().currentDesignDocument()->resetToDocumentModel();
}

void QmlDesignerPlugin::resetModelSelection()
{
    if (!rewriterView()) {
        qCWarning(qmldesignerLog) << "No rewriter existing while calling resetModelSelection";
        return;
    }
    if (!currentModel()) {
        qCWarning(qmldesignerLog) << "No current QmlDesigner document model while calling resetModelSelection";
        return;
    }
    rewriterView()->setSelectedModelNodes(QList<ModelNode>());
}

RewriterView *QmlDesignerPlugin::rewriterView() const
{
    return currentDesignDocument()->rewriterView();
}

Model *QmlDesignerPlugin::currentModel() const
{
    return currentDesignDocument()->currentModel();
}

DesignDocument *QmlDesignerPlugin::currentDesignDocument() const
{
    if (d)
        return d->documentManager.currentDesignDocument();

    return nullptr;
}

Internal::DesignModeWidget *QmlDesignerPlugin::mainWidget() const
{
    if (d)
        return &d->mainWidget;

    return nullptr;
}

QWidget *QmlDesignerPlugin::createProjectExplorerWidget(QWidget *parent) const
{
    return Internal::DesignModeWidget::createProjectExplorerWidget(parent);
}

void QmlDesignerPlugin::switchToTextModeDeferred()
{
    QTimer::singleShot(0, this, [] () {
        Core::ModeManager::activateMode(Core::Constants::MODE_EDIT);
    });
}

void QmlDesignerPlugin::emitCurrentTextEditorChanged(Core::IEditor *editor)
{
    d->blockEditorChange = true;
    emit Core::EditorManager::instance()->currentEditorChanged(editor);
    d->blockEditorChange = false;
}

double QmlDesignerPlugin::formEditorDevicePixelRatio()
{
    if (QmlDesignerPlugin::settings().value(DesignerSettingsKey::IGNORE_DEVICE_PIXEL_RATIO).toBool())
        return 1;

    const QList<QWindow *> topLevelWindows = QApplication::topLevelWindows();
    if (topLevelWindows.isEmpty())
        return 1;
    return topLevelWindows.constFirst()->screen()->devicePixelRatio();
}

void QmlDesignerPlugin::emitUsageStatistics(const QString &identifier)
{
    QTC_ASSERT(instance(), return);
    emit instance()->usageStatisticsNotifier(normalizeIdentifier(identifier));
}

void QmlDesignerPlugin::emitUsageStatisticsContextAction(const QString &identifier)
{
    emitUsageStatistics(Constants::EVENT_ACTION_EXECUTED + identifier);
}

void QmlDesignerPlugin::emitUsageStatisticsHelpRequested(const QString &identifier)
{
    emitUsageStatistics(Constants::EVENT_HELP_REQUESTED + identifier);
}

AsynchronousImageCache &QmlDesignerPlugin::imageCache()
{
    return m_instance->d->projectManager.asynchronousImageCache();
}

void QmlDesignerPlugin::registerPreviewImageProvider(QQmlEngine *engine)
{
    m_instance->d->projectManager.registerPreviewImageProvider(engine);
}


bool isParent(QWidget *parent, QWidget *widget)
{
    if (!widget)
        return false;

    if (widget == parent)
        return true;

    return isParent(parent, widget->parentWidget());
}

void QmlDesignerPlugin::trackWidgetFocusTime(QWidget *widget, const QString &identifier)
{
    connect(qApp,
            &QApplication::focusChanged,
            widget,
            [widget, identifier](QWidget *from, QWidget *to) {
                static QElapsedTimer widgetUsageTimer;
                static QString lastIdentifier;
                if (isParent(widget, to)) {
                    if (!lastIdentifier.isEmpty())
                        emitUsageStatisticsTime(lastIdentifier, widgetUsageTimer.elapsed());
                    widgetUsageTimer.restart();
                    lastIdentifier = identifier;
                } else if (isParent(widget, from) && lastIdentifier == identifier) {
                    emitUsageStatisticsTime(identifier, widgetUsageTimer.elapsed());
                    lastIdentifier.clear();
                }
            });
}

void QmlDesignerPlugin::emitUsageStatisticsTime(const QString &identifier, int elapsed)
{
    QTC_ASSERT(instance(), return);
    emit instance()->usageStatisticsUsageTimer(normalizeIdentifier(identifier), elapsed);
}

QmlDesignerPlugin *QmlDesignerPlugin::instance()
{
    return m_instance;
}

DocumentManager &QmlDesignerPlugin::documentManager()
{
    return d->documentManager;
}

const DocumentManager &QmlDesignerPlugin::documentManager() const
{
    return d->documentManager;
}

ViewManager &QmlDesignerPlugin::viewManager()
{
    return d->viewManager;
}

const ViewManager &QmlDesignerPlugin::viewManager() const
{
    return d->viewManager;
}

DesignerActionManager &QmlDesignerPlugin::designerActionManager()
{
    return d->viewManager.designerActionManager();
}

const DesignerActionManager &QmlDesignerPlugin::designerActionManager() const
{
    return d->viewManager.designerActionManager();
}

DesignerSettings& QmlDesignerPlugin::settings()
{
    return instance()->d->settings;
}

} // namespace QmlDesigner