editormanager.cpp 96.3 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
3
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
con's avatar
con committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
con's avatar
con committed
7
**
hjk's avatar
hjk committed
8 9 10 11 12 13 14
** 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 Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
15
**
16
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17 18 19 20 21 22 23 24 25
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
con's avatar
con committed
26 27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
hjk's avatar
hjk committed
29

con's avatar
con committed
30
#include "editormanager.h"
31
#include "editormanager_p.h"
32
#include "editorwindow.h"
33

34
#include "editorview.h"
con's avatar
con committed
35
#include "openeditorswindow.h"
mae's avatar
mae committed
36
#include "openeditorsview.h"
37
#include "documentmodel.h"
Friedemann Kleint's avatar
Friedemann Kleint committed
38
#include "ieditor.h"
con's avatar
con committed
39

40
#include <coreplugin/actionmanager/actioncontainer.h>
hjk's avatar
hjk committed
41 42
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/coreconstants.h>
43 44 45
#include <coreplugin/dialogs/openwithdialog.h>
#include <coreplugin/dialogs/readonlyfilesdialog.h>
#include <coreplugin/documentmanager.h>
con's avatar
con committed
46
#include <coreplugin/editormanager/ieditorfactory.h>
47
#include <coreplugin/editormanager/iexternaleditor.h>
hjk's avatar
hjk committed
48 49
#include <coreplugin/editortoolbar.h>
#include <coreplugin/fileutils.h>
50 51
#include <coreplugin/findplaceholder.h>
#include <coreplugin/icore.h>
52
#include <coreplugin/icorelistener.h>
hjk's avatar
hjk committed
53
#include <coreplugin/infobar.h>
54 55
#include <coreplugin/iversioncontrol.h>
#include <coreplugin/mimedatabase.h>
hjk's avatar
hjk committed
56
#include <coreplugin/modemanager.h>
57 58 59
#include <coreplugin/outputpane.h>
#include <coreplugin/outputpanemanager.h>
#include <coreplugin/rightpane.h>
60
#include <coreplugin/settingsdatabase.h>
61
#include <coreplugin/variablemanager.h>
62
#include <coreplugin/vcsmanager.h>
con's avatar
con committed
63

64 65
#include <extensionsystem/pluginmanager.h>

66
#include <utils/algorithm.h>
67
#include <utils/fileutils.h>
68
#include <utils/hostosinfo.h>
hjk's avatar
hjk committed
69 70
#include <utils/qtcassert.h>

71
#include <QClipboard>
72 73 74 75 76 77 78 79
#include <QDateTime>
#include <QDebug>
#include <QFileInfo>
#include <QMap>
#include <QSet>
#include <QSettings>
#include <QTextCodec>
#include <QTimer>
con's avatar
con committed
80

81 82 83 84 85 86 87
#include <QAction>
#include <QApplication>
#include <QFileDialog>
#include <QMenu>
#include <QMessageBox>
#include <QPushButton>
#include <QSplitter>
con's avatar
con committed
88 89 90

enum { debugEditorManager=0 };

91
static const char kCurrentDocumentPrefix[] = "CurrentDocument";
Friedemann Kleint's avatar
Friedemann Kleint committed
92 93
static const char kCurrentDocumentXPos[] = "CurrentDocument:XPos";
static const char kCurrentDocumentYPos[] = "CurrentDocument:YPos";
94
static const char kMakeWritableWarning[] = "Core.EditorManager.MakeWritable";
con's avatar
con committed
95

96 97 98 99 100
static const char documentStatesKey[] = "EditorManager/DocumentStates";
static const char reloadBehaviorKey[] = "EditorManager/ReloadBehavior";
static const char autoSaveEnabledKey[] = "EditorManager/AutoSaveEnabled";
static const char autoSaveIntervalKey[] = "EditorManager/AutoSaveInterval";

101 102 103 104 105 106 107 108
//===================EditorClosingCoreListener======================

namespace Core {
namespace Internal {

class EditorClosingCoreListener : public ICoreListener
{
public:
109 110 111 112 113 114 115
    bool editorAboutToClose(IEditor *) { return true; }
    bool coreAboutToClose()
    {
        // Do not ask for files to save.
        // MainWindow::closeEvent has already done that.
        return EditorManager::closeAllEditors(false);
    }
116 117 118 119 120 121 122 123 124
};

} // namespace Internal
} // namespace Core

using namespace Core;
using namespace Core::Internal;
using namespace Utils;

con's avatar
con committed
125 126 127 128 129 130 131
//===================EditorManager=====================

EditorManagerPlaceHolder::EditorManagerPlaceHolder(Core::IMode *mode, QWidget *parent)
    : QWidget(parent), m_mode(mode)
{
    setLayout(new QVBoxLayout);
    layout()->setMargin(0);
132
    setFocusProxy(EditorManagerPrivate::mainEditorArea());
Robert Loehning's avatar
Robert Loehning committed
133 134
    connect(Core::ModeManager::instance(), SIGNAL(currentModeChanged(Core::IMode*)),
            this, SLOT(currentModeChanged(Core::IMode*)));
135

136
    currentModeChanged(ModeManager::currentMode());
con's avatar
con committed
137 138 139 140
}

EditorManagerPlaceHolder::~EditorManagerPlaceHolder()
{
Kai Koehne's avatar
Kai Koehne committed
141
    // EditorManager will be deleted in ~MainWindow()
142
    QWidget *em = EditorManagerPrivate::mainEditorArea();
Kai Koehne's avatar
Kai Koehne committed
143 144 145
    if (em && em->parent() == this) {
        em->hide();
        em->setParent(0);
con's avatar
con committed
146 147 148 149 150 151
    }
}

void EditorManagerPlaceHolder::currentModeChanged(Core::IMode *mode)
{
    if (m_mode == mode) {
152
        QWidget *previousFocus = 0;
153
        QWidget *em = EditorManagerPrivate::mainEditorArea();
154 155 156 157
        if (em->focusWidget() && em->focusWidget()->hasFocus())
            previousFocus = em->focusWidget();
        layout()->addWidget(em);
        em->show();
158 159
        if (previousFocus)
            previousFocus->setFocus();
con's avatar
con committed
160 161 162 163 164
    }
}

// ---------------- EditorManager

165 166
static EditorManager *m_instance = 0;
static EditorManagerPrivate *d;
con's avatar
con committed
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
static int extractLineNumber(QString *fileName)
{
    int i = fileName->length() - 1;
    for (; i >= 0; --i) {
        if (!fileName->at(i).isNumber())
            break;
    }
    if (i == -1)
        return -1;
    const QChar c = fileName->at(i);
    if (c == QLatin1Char(':') || c == QLatin1Char('+')) {
        bool ok;
        const QString suffix = fileName->mid(i + 1);
        const int result = suffix.toInt(&ok);
        if (suffix.isEmpty() || ok) {
            fileName->truncate(i);
            return result;
        }
    }
    return -1;
}

static QString autoSaveName(const QString &fileName)
{
    return fileName + QLatin1String(".autosave");
}

static void setFocusToEditorViewAndUnmaximizePanes(EditorView *view)
{
    IEditor *editor = view->currentEditor();
    QWidget *target = editor ? editor->widget() : view;
    QWidget *focus = target->focusWidget();
    QWidget *w = focus ? focus : target;

    w->setFocus();
    ICore::raiseWindow(w);

    OutputPanePlaceHolder *holder = OutputPanePlaceHolder::getCurrent();
    if (holder && holder->window() == view->window()) {
        // unmaximize output pane if necessary
        if (holder->isVisible() && holder->isMaximized())
            holder->unmaximize();
    }
}

/* For something that has a 'QString id' (IEditorFactory
 * or IExternalEditor), find the one matching a id. */
template <class EditorFactoryLike>
EditorFactoryLike *findById(Core::Id id)
{
    return ExtensionSystem::PluginManager::getObject<EditorFactoryLike>(
        [&id](EditorFactoryLike *efl) {
            return id == efl->id();
        });
}

224
EditorManagerPrivate::EditorManagerPrivate(QObject *parent) :
225
    QObject(parent),
226
    m_autoSaveTimer(0),
227 228 229 230 231
    m_revertToSavedAction(new QAction(EditorManager::tr("Revert to Saved"), this)),
    m_saveAction(new QAction(this)),
    m_saveAsAction(new QAction(this)),
    m_closeCurrentEditorAction(new QAction(EditorManager::tr("Close"), this)),
    m_closeAllEditorsAction(new QAction(EditorManager::tr("Close All"), this)),
232
    m_closeOtherDocumentsAction(new QAction(EditorManager::tr("Close Others"), this)),
233 234 235 236 237
    m_closeAllEditorsExceptVisibleAction(new QAction(EditorManager::tr("Close All Except Visible"), this)),
    m_gotoNextDocHistoryAction(new QAction(EditorManager::tr("Next Open Document in History"), this)),
    m_gotoPreviousDocHistoryAction(new QAction(EditorManager::tr("Previous Open Document in History"), this)),
    m_goBackAction(new QAction(QIcon(QLatin1String(Constants::ICON_PREV)), EditorManager::tr("Go Back"), this)),
    m_goForwardAction(new QAction(QIcon(QLatin1String(Constants::ICON_NEXT)), EditorManager::tr("Go Forward"), this)),
238 239
    m_copyFilePathContextAction(new QAction(EditorManager::tr("Copy Full Path to Clipboard"), this)),
    m_copyFileNameContextAction(new QAction(EditorManager::tr("Copy File Name to Clipboard"), this)),
240 241 242 243 244
    m_saveCurrentEditorContextAction(new QAction(EditorManager::tr("&Save"), this)),
    m_saveAsCurrentEditorContextAction(new QAction(EditorManager::tr("Save &As..."), this)),
    m_revertToSavedCurrentEditorContextAction(new QAction(EditorManager::tr("Revert to Saved"), this)),
    m_closeCurrentEditorContextAction(new QAction(EditorManager::tr("Close"), this)),
    m_closeAllEditorsContextAction(new QAction(EditorManager::tr("Close All"), this)),
245
    m_closeOtherDocumentsContextAction(new QAction(EditorManager::tr("Close Others"), this)),
246 247 248 249
    m_closeAllEditorsExceptVisibleContextAction(new QAction(EditorManager::tr("Close All Except Visible"), this)),
    m_openGraphicalShellAction(new QAction(FileUtils::msgGraphicalShellAction(), this)),
    m_openTerminalAction(new QAction(FileUtils::msgTerminalAction(), this)),
    m_findInDirectoryAction(new QAction(FileUtils::msgFindInDirectory(), this)),
con's avatar
con committed
250
    m_windowPopup(0),
251
    m_coreListener(0),
252
    m_reloadSetting(IDocument::AlwaysAsk),
253 254
    m_autoSaveEnabled(true),
    m_autoSaveInterval(5)
con's avatar
con committed
255
{
256
    d = this;
con's avatar
con committed
257 258 259 260
}

EditorManagerPrivate::~EditorManagerPrivate()
{
261 262 263 264 265 266 267 268
    if (ICore::instance()) {
        if (m_coreListener) {
            ExtensionSystem::PluginManager::removeObject(m_coreListener);
            delete m_coreListener;
        }
        ExtensionSystem::PluginManager::removeObject(m_openEditorsFactory);
        delete m_openEditorsFactory;
    }
con's avatar
con committed
269

270
    // close all extra windows
271 272 273 274
    for (int i = 0; i < m_editorAreas.size(); ++i) {
        EditorArea *area = m_editorAreas.at(i);
        disconnect(area, SIGNAL(destroyed(QObject*)), this, SLOT(editorAreaDestroyed(QObject*)));
        delete area;
275
    }
276
    m_editorAreas.clear();
277
    delete m_windowPopup;
hjk's avatar
hjk committed
278

279 280 281
    DocumentModel::destroy();
    d = 0;
}
con's avatar
con committed
282

283
void EditorManagerPrivate::init()
con's avatar
con committed
284
{
285
    DocumentModel::init();
286 287
    connect(ICore::instance(), SIGNAL(contextAboutToChange(QList<Core::IContext*>)),
            this, SLOT(handleContextChange(QList<Core::IContext*>)));
con's avatar
con committed
288

289
    const Context editManagerContext(Constants::C_EDITORMANAGER);
Lasse Holmstedt's avatar
Lasse Holmstedt committed
290
    // combined context for edit & design modes
291
    const Context editDesignContext(Constants::C_EDITORMANAGER, Constants::C_DESIGN_MODE);
Lasse Holmstedt's avatar
Lasse Holmstedt committed
292

Eike Ziller's avatar
Eike Ziller committed
293
    ActionContainer *mfile = ActionManager::actionContainer(Constants::M_FILE);
con's avatar
con committed
294

295
    // Revert to saved
296 297
    m_revertToSavedAction->setIcon(QIcon::fromTheme(QLatin1String("document-revert")));
    Command *cmd = ActionManager::registerAction(m_revertToSavedAction,
con's avatar
con committed
298
                                       Constants::REVERTTOSAVED, editManagerContext);
con's avatar
con committed
299
    cmd->setAttribute(Command::CA_UpdateText);
300
    cmd->setDescription(tr("Revert File to Saved"));
con's avatar
con committed
301
    mfile->addAction(cmd, Constants::G_FILE_SAVE);
302
    connect(m_revertToSavedAction, SIGNAL(triggered()), m_instance, SLOT(revertToSaved()));
con's avatar
con committed
303

304
    // Save Action
305 306
    ActionManager::registerAction(m_saveAction, Constants::SAVE, editManagerContext);
    connect(m_saveAction, SIGNAL(triggered()), m_instance, SLOT(saveDocument()));
con's avatar
con committed
307

308
    // Save As Action
309 310
    ActionManager::registerAction(m_saveAsAction, Constants::SAVEAS, editManagerContext);
    connect(m_saveAsAction, SIGNAL(triggered()), m_instance, SLOT(saveDocumentAs()));
con's avatar
con committed
311

312
    // Window Menu
Eike Ziller's avatar
Eike Ziller committed
313
    ActionContainer *mwindow = ActionManager::actionContainer(Constants::M_WINDOW);
con's avatar
con committed
314

315
    // Window menu separators
316 317
    mwindow->addSeparator(editManagerContext, Constants::G_WINDOW_SPLIT);
    mwindow->addSeparator(editManagerContext, Constants::G_WINDOW_NAVIGATE);
con's avatar
con committed
318

319
    // Close Action
320
    cmd = ActionManager::registerAction(m_closeCurrentEditorAction, Constants::CLOSE, editManagerContext, true);
con's avatar
con committed
321
    cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+W")));
con's avatar
con committed
322
    cmd->setAttribute(Core::Command::CA_UpdateText);
323
    cmd->setDescription(m_closeCurrentEditorAction->text());
con's avatar
con committed
324
    mfile->addAction(cmd, Constants::G_FILE_CLOSE);
325 326
    connect(m_closeCurrentEditorAction, SIGNAL(triggered()),
            m_instance, SLOT(slotCloseCurrentEditorOrDocument()));
con's avatar
con committed
327

328 329
    if (Utils::HostOsInfo::isWindowsHost()) {
        // workaround for QTCREATORBUG-72
330 331
        QAction *action = new QAction(tr("Alternative Close"), this);
        cmd = ActionManager::registerAction(action, Constants::CLOSE_ALTERNATIVE, editManagerContext);
332 333
        cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+F4")));
        cmd->setDescription(EditorManager::tr("Close"));
334
        connect(action, SIGNAL(triggered()), m_instance, SLOT(slotCloseCurrentEditorOrDocument()));
335
    }
336

337
    // Close All Action
338
    cmd = ActionManager::registerAction(m_closeAllEditorsAction, Constants::CLOSEALL, editManagerContext, true);
con's avatar
con committed
339 340
    cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+Shift+W")));
    mfile->addAction(cmd, Constants::G_FILE_CLOSE);
341
    connect(m_closeAllEditorsAction, SIGNAL(triggered()), m_instance, SLOT(closeAllEditors()));
con's avatar
con committed
342

343
    // Close All Others Action
344
    cmd = ActionManager::registerAction(m_closeOtherDocumentsAction, Constants::CLOSEOTHERS, editManagerContext, true);
con's avatar
con committed
345 346
    mfile->addAction(cmd, Constants::G_FILE_CLOSE);
    cmd->setAttribute(Core::Command::CA_UpdateText);
347
    connect(m_closeOtherDocumentsAction, SIGNAL(triggered()), m_instance, SLOT(closeOtherDocuments()));
con's avatar
con committed
348

349
    // Close All Others Except Visible Action
350
    cmd = ActionManager::registerAction(m_closeAllEditorsExceptVisibleAction, Constants::CLOSEALLEXCEPTVISIBLE, editManagerContext, true);
351
    mfile->addAction(cmd, Constants::G_FILE_CLOSE);
352 353
    connect(m_closeAllEditorsExceptVisibleAction, SIGNAL(triggered()),
            this, SLOT(closeAllEditorsExceptVisible()));
354

355
    //Save XXX Context Actions
356 357 358 359
    connect(m_copyFilePathContextAction, SIGNAL(triggered()),
            this, SLOT(copyFilePathFromContextMenu()));
    connect(m_copyFileNameContextAction, SIGNAL(triggered()),
            this, SLOT(copyFileNameFromContextMenu()));
360 361 362 363 364 365
    connect(m_saveCurrentEditorContextAction, SIGNAL(triggered()),
            this, SLOT(saveDocumentFromContextMenu()));
    connect(m_saveAsCurrentEditorContextAction, SIGNAL(triggered()),
            this, SLOT(saveDocumentAsFromContextMenu()));
    connect(m_revertToSavedCurrentEditorContextAction, SIGNAL(triggered()),
            this, SLOT(revertToSavedFromContextMenu()));
366

367
    // Close XXX Context Actions
368 369 370 371
    connect(m_closeAllEditorsContextAction, SIGNAL(triggered()),
            m_instance, SLOT(closeAllEditors()));
    connect(m_closeCurrentEditorContextAction, SIGNAL(triggered()),
            this, SLOT(closeEditorFromContextMenu()));
372 373
    connect(m_closeOtherDocumentsContextAction, SIGNAL(triggered()),
            this, SLOT(closeOtherDocumentsFromContextMenu()));
374 375 376 377 378 379
    connect(m_closeAllEditorsExceptVisibleContextAction, SIGNAL(triggered()),
            this, SLOT(closeAllEditorsExceptVisible()));

    connect(m_openGraphicalShellAction, SIGNAL(triggered()), this, SLOT(showInGraphicalShell()));
    connect(m_openTerminalAction, SIGNAL(triggered()), this, SLOT(openTerminal()));
    connect(m_findInDirectoryAction, SIGNAL(triggered()), this, SLOT(findInDirectory()));
Robert Loehning's avatar
Robert Loehning committed
380

con's avatar
con committed
381
    // Goto Previous In History Action
382
    cmd = ActionManager::registerAction(m_gotoPreviousDocHistoryAction, Constants::GOTOPREVINHISTORY, editDesignContext);
383
    cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Alt+Tab") : tr("Ctrl+Tab")));
con's avatar
con committed
384
    mwindow->addAction(cmd, Constants::G_WINDOW_NAVIGATE);
385 386
    connect(m_gotoPreviousDocHistoryAction, SIGNAL(triggered()),
            this, SLOT(gotoPreviousDocHistory()));
con's avatar
con committed
387 388

    // Goto Next In History Action
389
    cmd = ActionManager::registerAction(m_gotoNextDocHistoryAction, Constants::GOTONEXTINHISTORY, editDesignContext);
390
    cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Alt+Shift+Tab") : tr("Ctrl+Shift+Tab")));
con's avatar
con committed
391
    mwindow->addAction(cmd, Constants::G_WINDOW_NAVIGATE);
392
    connect(m_gotoNextDocHistoryAction, SIGNAL(triggered()), this, SLOT(gotoNextDocHistory()));
con's avatar
con committed
393 394

    // Go back in navigation history
395
    cmd = ActionManager::registerAction(m_goBackAction, Constants::GO_BACK, editDesignContext);
396
    cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Ctrl+Alt+Left") : tr("Alt+Left")));
con's avatar
con committed
397
    mwindow->addAction(cmd, Constants::G_WINDOW_NAVIGATE);
398
    connect(m_goBackAction, SIGNAL(triggered()), m_instance, SLOT(goBackInNavigationHistory()));
con's avatar
con committed
399 400

    // Go forward in navigation history
401
    cmd = ActionManager::registerAction(m_goForwardAction, Constants::GO_FORWARD, editDesignContext);
402
    cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Ctrl+Alt+Right") : tr("Alt+Right")));
con's avatar
con committed
403
    mwindow->addAction(cmd, Constants::G_WINDOW_NAVIGATE);
404
    connect(m_goForwardAction, SIGNAL(triggered()), m_instance, SLOT(goForwardInNavigationHistory()));
con's avatar
con committed
405

406 407
    m_splitAction = new QAction(tr("Split"), this);
    cmd = ActionManager::registerAction(m_splitAction, Constants::SPLIT, editManagerContext);
408
    cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+E,2") : tr("Ctrl+E,2")));
409
    mwindow->addAction(cmd, Constants::G_WINDOW_SPLIT);
410
    connect(m_splitAction, SIGNAL(triggered()), this, SLOT(split()));
411

412 413
    m_splitSideBySideAction = new QAction(tr("Split Side by Side"), this);
    cmd = ActionManager::registerAction(m_splitSideBySideAction, Constants::SPLIT_SIDE_BY_SIDE, editManagerContext);
414
    cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+E,3") : tr("Ctrl+E,3")));
415
    mwindow->addAction(cmd, Constants::G_WINDOW_SPLIT);
416
    connect(m_splitSideBySideAction, SIGNAL(triggered()), m_instance, SLOT(splitSideBySide()));
417

418 419
    m_splitNewWindowAction = new QAction(tr("Open in New Window"), this);
    cmd = ActionManager::registerAction(m_splitNewWindowAction, Constants::SPLIT_NEW_WINDOW, editManagerContext);
420 421
    cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+E,4") : tr("Ctrl+E,4")));
    mwindow->addAction(cmd, Constants::G_WINDOW_SPLIT);
422
    connect(m_splitNewWindowAction, SIGNAL(triggered()), this, SLOT(splitNewWindow()));
423

424 425
    m_removeCurrentSplitAction = new QAction(tr("Remove Current Split"), this);
    cmd = ActionManager::registerAction(m_removeCurrentSplitAction, Constants::REMOVE_CURRENT_SPLIT, editManagerContext);
426
    cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+E,0") : tr("Ctrl+E,0")));
427
    mwindow->addAction(cmd, Constants::G_WINDOW_SPLIT);
428
    connect(m_removeCurrentSplitAction, SIGNAL(triggered()), this, SLOT(removeCurrentSplit()));
429

430 431
    m_removeAllSplitsAction = new QAction(tr("Remove All Splits"), this);
    cmd = ActionManager::registerAction(m_removeAllSplitsAction, Constants::REMOVE_ALL_SPLITS, editManagerContext);
432
    cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+E,1") : tr("Ctrl+E,1")));
433
    mwindow->addAction(cmd, Constants::G_WINDOW_SPLIT);
434
    connect(m_removeAllSplitsAction, SIGNAL(triggered()), this, SLOT(removeAllSplits()));
435

436 437
    m_gotoNextSplitAction = new QAction(tr("Go to Next Split or Window"), this);
    cmd = ActionManager::registerAction(m_gotoNextSplitAction, Constants::GOTO_NEXT_SPLIT, editManagerContext);
438
    cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+E,o") : tr("Ctrl+E,o")));
439
    mwindow->addAction(cmd, Constants::G_WINDOW_SPLIT);
440
    connect(m_gotoNextSplitAction, SIGNAL(triggered()), this, SLOT(gotoNextSplit()));
441

Eike Ziller's avatar
Eike Ziller committed
442 443
    ActionContainer *medit = ActionManager::actionContainer(Constants::M_EDIT);
    ActionContainer *advancedMenu = ActionManager::createMenu(Constants::M_EDIT_ADVANCED);
444
    medit->addMenu(advancedMenu, Constants::G_EDIT_ADVANCED);
con's avatar
con committed
445
    advancedMenu->menu()->setTitle(tr("Ad&vanced"));
446
    advancedMenu->appendGroup(Constants::G_EDIT_FORMAT);
447
    advancedMenu->appendGroup(Constants::G_EDIT_TEXT);
448
    advancedMenu->appendGroup(Constants::G_EDIT_COLLAPSING);
mae's avatar
mae committed
449
    advancedMenu->appendGroup(Constants::G_EDIT_BLOCKS);
450 451 452 453
    advancedMenu->appendGroup(Constants::G_EDIT_FONT);
    advancedMenu->appendGroup(Constants::G_EDIT_EDITOR);

    // Advanced menu separators
454
    advancedMenu->addSeparator(editManagerContext, Constants::G_EDIT_TEXT);
455 456 457 458
    advancedMenu->addSeparator(editManagerContext, Constants::G_EDIT_COLLAPSING);
    advancedMenu->addSeparator(editManagerContext, Constants::G_EDIT_BLOCKS);
    advancedMenu->addSeparator(editManagerContext, Constants::G_EDIT_FONT);
    advancedMenu->addSeparator(editManagerContext, Constants::G_EDIT_EDITOR);
hjk's avatar
hjk committed
459

con's avatar
con committed
460
    // other setup
461 462
    auto mainEditorArea = new EditorArea();
    mainEditorArea->hide();
463 464
    connect(mainEditorArea, &EditorArea::windowTitleNeedsUpdate,
            this, &EditorManagerPrivate::updateWindowTitle);
465 466 467
    connect(mainEditorArea, SIGNAL(destroyed(QObject*)), this, SLOT(editorAreaDestroyed(QObject*)));
    d->m_editorAreas.append(mainEditorArea);
    d->m_currentView = mainEditorArea->view();
con's avatar
con committed
468 469 470

    updateActions();

471 472
    m_windowPopup = new OpenEditorsWindow;
    m_windowPopup->hide();
473

474 475
    m_autoSaveTimer = new QTimer(this);
    connect(m_autoSaveTimer, SIGNAL(timeout()), SLOT(autoSave()));
476
    updateAutoSave();
477

478
    d->m_coreListener = new EditorClosingCoreListener();
479
    ExtensionSystem::PluginManager::addObject(d->m_coreListener);
con's avatar
con committed
480

hjk's avatar
hjk committed
481
    d->m_openEditorsFactory = new OpenEditorsViewFactory();
482
    ExtensionSystem::PluginManager::addObject(d->m_openEditorsFactory);
con's avatar
con committed
483

484 485
    VariableManager::registerFileVariables(kCurrentDocumentPrefix, tr("Current document"),
        []() -> QString {
486
            IDocument *document = EditorManager::currentDocument();
487 488 489 490 491 492
            return document ? document->filePath() : QString();
        });

    VariableManager::registerIntVariable(kCurrentDocumentXPos,
        tr("X-coordinate of the current editor's upper left corner, relative to screen."),
        []() -> int {
493
            IEditor *editor = EditorManager::currentEditor();
494 495 496 497 498 499
            return editor ? editor->widget()->mapToGlobal(QPoint(0, 0)).x() : 0;
        });

    VariableManager::registerIntVariable(kCurrentDocumentYPos,
        tr("Y-coordinate of the current editor's upper left corner, relative to screen."),
        []() -> int {
500
            IEditor *editor = EditorManager::currentEditor();
501 502
            return editor ? editor->widget()->mapToGlobal(QPoint(0, 0)).y() : 0;
        });
con's avatar
con committed
503 504
}

505
EditorArea *EditorManagerPrivate::mainEditorArea()
con's avatar
con committed
506
{
507
    return d->m_editorAreas.at(0);
con's avatar
con committed
508 509
}

510 511
IEditor *EditorManagerPrivate::openEditor(EditorView *view, const QString &fileName, Id editorId,
                                          EditorManager::OpenEditorFlags flags, bool *newEditor)
con's avatar
con committed
512 513
{
    if (debugEditorManager)
514 515 516 517 518 519 520 521 522
        qDebug() << Q_FUNC_INFO << fileName << editorId.name();

    QString fn = fileName;
    QFileInfo fi(fn);
    int lineNumber = -1;
    if ((flags & EditorManager::CanContainLineNumber) && !fi.exists()) {
        lineNumber = extractLineNumber(&fn);
        if (lineNumber != -1)
            fi.setFile(fn);
523
    }
524

525 526
    if (fn.isEmpty())
        return 0;
527

528 529
    if (newEditor)
        *newEditor = false;
mae's avatar
mae committed
530

531 532 533 534 535 536 537
    const QList<IEditor *> editors = DocumentModel::editorsForFilePath(fn);
    if (!editors.isEmpty()) {
        IEditor *editor = editors.first();
        editor = activateEditor(view, editor, flags);
        if (editor && flags & EditorManager::CanContainLineNumber)
            editor->gotoLine(lineNumber, -1);
        return editor;
con's avatar
con committed
538 539
    }

540 541 542 543 544 545
    QString realFn = autoSaveName(fn);
    QFileInfo rfi(realFn);
    if (!fi.exists() || !rfi.exists() || fi.lastModified() >= rfi.lastModified()) {
        QFile::remove(realFn);
        realFn = fn;
    }
mae's avatar
mae committed
546

547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
    IEditor *editor = createEditor(editorId, fn);
    // If we could not open the file in the requested editor, fall
    // back to the default editor:
    if (!editor)
        editor = createEditor(Id(), fn);
    QTC_ASSERT(editor, return 0);
    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
    QString errorString;
    if (!editor->open(&errorString, fn, realFn)) {
        QApplication::restoreOverrideCursor();
        QMessageBox::critical(ICore::mainWindow(), EditorManager::tr("File Error"), errorString);
        delete editor;
        return 0;
    }
    if (realFn != fn)
        editor->document()->setRestoredFrom(realFn);
    addEditor(editor);
mae's avatar
mae committed
564

565 566
    if (newEditor)
        *newEditor = true;
mae's avatar
mae committed
567

568 569 570
    IEditor *result = activateEditor(view, editor, flags);
    if (editor == result)
        restoreEditorState(editor);
571

572 573 574 575 576
    if (flags & EditorManager::CanContainLineNumber)
        editor->gotoLine(lineNumber, -1);

    QApplication::restoreOverrideCursor();
    return result;
mae's avatar
mae committed
577 578
}

579 580
IEditor *EditorManagerPrivate::activateEditorForDocument(EditorView *view, IDocument *document,
                                                         EditorManager::OpenEditorFlags flags)
mae's avatar
mae committed
581
{
582 583 584 585 586 587 588
    Q_ASSERT(view);
    IEditor *editor = view->editorForDocument(document);
    if (!editor) {
        const QList<IEditor*> editors = DocumentModel::editorsForDocument(document);
        if (editors.isEmpty())
            return 0;
        editor = editors.first();
589
    }
590
    return activateEditor(view, editor, flags);
mae's avatar
mae committed
591 592
}

593
EditorView *EditorManagerPrivate::viewForEditor(IEditor *editor)
594 595 596 597 598 599 600 601 602 603
{
    QWidget *w = editor->widget();
    while (w) {
        w = w->parentWidget();
        if (EditorView *view = qobject_cast<EditorView *>(w))
            return view;
    }
    return 0;
}

604
MakeWritableResult EditorManagerPrivate::makeFileWritable(IDocument *document)
605
{
606 607 608 609 610 611 612 613 614 615 616 617
    if (!document)
        return Failed;
    // TODO: dialog parent is wrong
    ReadOnlyFilesDialog roDialog(document, ICore::mainWindow(), document->isSaveAsAllowed());
    switch (roDialog.exec()) {
    case ReadOnlyFilesDialog::RO_MakeWritable:
    case ReadOnlyFilesDialog::RO_OpenVCS:
        return MadeWritable;
    case ReadOnlyFilesDialog::RO_SaveAs:
        return SavedAs;
    default:
        return Failed;
618 619 620 621 622 623 624 625
    }
}

/*!
    Implements the logic of the escape key shortcut (ReturnToEditor).
    Should only be called by the shortcut handler.
    \internal
*/
626
void EditorManagerPrivate::doEscapeKeyFocusMoveMagic()
627 628
{
    // use cases to cover:
629 630 631 632 633 634 635
    // 1. if app focus is in mode or external window without editor view (e.g. Design, Projects, ext. Help)
    //      if there are extra views (e.g. output)
    //        hide them
    //      otherwise
    //        activate & raise the current editor view (can be external)
    //        if that is in edit mode
    //          activate edit mode and unmaximize output pane
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
    // 2. if app focus is in external window with editor view
    //      hide find if necessary
    // 2. if app focus is in mode with editor view
    //      if current editor view is in external window
    //        raise and activate current editor view
    //      otherwise if the current editor view is not app focus
    //        move focus to editor view in mode and unmaximize output pane
    //      otherwise if the current view is app focus
    //        if mode is not edit mode
    //          if there are extra views (find, help, output)
    //            hide them
    //          otherwise
    //            activate edit mode and unmaximize output pane
    //        otherwise (i.e. mode is edit mode)
    //          hide extra views (find, help, output)

652 653 654 655
    QWidget *activeWindow = qApp->activeWindow();
    if (!activeWindow)
        return;
    QWidget *focus = qApp->focusWidget();
656
    EditorView *editorView = currentEditorView();
657
    bool editorViewActive = (focus && focus == editorView->focusWidget());
658
    bool editorViewVisible = editorView->isVisible();
659

660 661 662 663 664 665
    bool stuffHidden = false;
    FindToolBarPlaceHolder *findPane = FindToolBarPlaceHolder::getCurrent();
    if (findPane && findPane->isVisible() && findPane->isUsedByWidget(focus)) {
        findPane->hide();
        stuffHidden = true;
    }
666
    if (!( editorViewVisible && !editorViewActive && editorView->window() == activeWindow )) {
667
        QWidget *outputPane = OutputPanePlaceHolder::getCurrent();
668
        if (outputPane && outputPane->isVisible() && outputPane->window() == activeWindow) {
669 670 671 672
            OutputPaneManager::instance()->slotHide();
            stuffHidden = true;
        }
        QWidget *rightPane = RightPanePlaceHolder::current();
673
        if (rightPane && rightPane->isVisible() && rightPane->window() == activeWindow) {
674 675 676
            RightPaneWidget::instance()->setShown(false);
            stuffHidden = true;
        }
677
    }
678 679
    if (stuffHidden)
        return;
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699

    if (!editorViewActive && editorViewVisible) {
        setFocusToEditorViewAndUnmaximizePanes(editorView);
        return;
    }

    if (!editorViewActive && !editorViewVisible) {
        // assumption is that editorView is in main window then
        ModeManager::activateMode(Id(Constants::MODE_EDIT));
        QTC_CHECK(editorView->isVisible());
        setFocusToEditorViewAndUnmaximizePanes(editorView);
        return;
    }

    if (editorView->window() == ICore::mainWindow()) {
        // we are in a editor view and there's nothing to hide, switch to edit
        ModeManager::activateMode(Id(Constants::MODE_EDIT));
        QTC_CHECK(editorView->isVisible());
        // next call works only because editor views in main window are shared between modes
        setFocusToEditorViewAndUnmaximizePanes(editorView);
700 701 702
    }
}

703
OpenEditorsWindow *EditorManagerPrivate::windowPopup()
704
{
705
    return d->m_windowPopup;
706 707
}

708
void EditorManagerPrivate::showPopupOrSelectDocument()
709
{
710 711 712 713 714
    if (QApplication::keyboardModifiers() == Qt::NoModifier) {
        windowPopup()->selectAndHide();
    } else {
        QWidget *activeWindow = qApp->activeWindow();
        // decide where to show the popup
715 716 717 718 719 720
        // if the active window has editors, we want that editor area as a reference
        // TODO: this does not work correctly with multiple editor areas in the same window
        EditorArea *activeEditorArea = 0;
        foreach (EditorArea *area, d->m_editorAreas) {
            if (area->window() == activeWindow) {
                activeEditorArea = area;
721 722 723
                break;
            }
        }
724 725 726 727
        // otherwise we take the "current" editor area
        if (!activeEditorArea)
            activeEditorArea = findEditorArea(EditorManagerPrivate::currentEditorView());
        QTC_ASSERT(activeEditorArea, activeEditorArea = d->m_editorAreas.first());
728

729 730
        // editor area in main window is invisible when invoked from Design Mode.
        QWidget *referenceWidget = activeEditorArea->isVisible() ? activeEditorArea : activeEditorArea->window();
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 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
        QTC_CHECK(referenceWidget->isVisible());
        const QPoint p = referenceWidget->mapToGlobal(QPoint(0, 0));
        OpenEditorsWindow *popup = windowPopup();
        popup->setMaximumSize(qMax(popup->minimumWidth(), referenceWidget->width() / 2),
                              qMax(popup->minimumHeight(), referenceWidget->height() / 2));
        popup->adjustSize();
        popup->move((referenceWidget->width() - popup->width()) / 2 + p.x(),
                    (referenceWidget->height() - popup->height()) / 2 + p.y());
        popup->setVisible(true);
    }
}

// Run the OpenWithDialog and return the editor id
// selected by the user.
Id EditorManagerPrivate::getOpenWithEditorId(const QString &fileName, bool *isExternalEditor)
{
    // Collect editors that can open the file
    MimeType mt = MimeDatabase::findByFile(fileName);
    //Unable to determine mime type of fileName. Falling back to text/plain",
    if (!mt)
        mt = MimeDatabase::findByType(QLatin1String("text/plain"));
    QList<Id> allEditorIds;
    QStringList allEditorDisplayNames;
    QList<Id> externalEditorIds;
    // Built-in
    const EditorManager::EditorFactoryList editors = EditorManager::editorFactories(mt, false);
    const int size = editors.size();
    for (int i = 0; i < size; i++) {
        allEditorIds.push_back(editors.at(i)->id());
        allEditorDisplayNames.push_back(editors.at(i)->displayName());
    }
    // External editors
    const EditorManager::ExternalEditorList exEditors = EditorManager::externalEditors(mt, false);
    const int esize = exEditors.size();
    for (int i = 0; i < esize; i++) {
        externalEditorIds.push_back(exEditors.at(i)->id());
        allEditorIds.push_back(exEditors.at(i)->id());
        allEditorDisplayNames.push_back(exEditors.at(i)->displayName());
    }
    if (allEditorIds.empty())
        return Id();
    QTC_ASSERT(allEditorIds.size() == allEditorDisplayNames.size(), return Id());
    // Run dialog.
    OpenWithDialog dialog(fileName, ICore::mainWindow());
    dialog.setEditors(allEditorDisplayNames);
    dialog.setCurrentEditor(0);
    if (dialog.exec() != QDialog::Accepted)
        return Id();
    const Id selectedId = allEditorIds.at(dialog.editor());
    if (isExternalEditor)
        *isExternalEditor = externalEditorIds.contains(selectedId);
    return selectedId;
}

void EditorManagerPrivate::saveSettings()
{
    SettingsDatabase *settings = ICore::settingsDatabase();
    settings->beginTransaction();
    settings->setValue(QLatin1String(documentStatesKey), d->m_editorStates);
    settings->setValue(QLatin1String(reloadBehaviorKey), d->m_reloadSetting);
    settings->setValue(QLatin1String(autoSaveEnabledKey), d->m_autoSaveEnabled);
    settings->setValue(QLatin1String(autoSaveIntervalKey), d->m_autoSaveInterval);
    settings->endTransaction();
}

void EditorManagerPrivate::readSettings()
{
    // TODO remove
    // Backward compatibility to old locations for these settings
    QSettings *qs = ICore::settings();
    if (qs->contains(QLatin1String(documentStatesKey))) {
        d->m_editorStates = qs->value(QLatin1String(documentStatesKey))
            .value<QMap<QString, QVariant> >();
        qs->remove(QLatin1String(documentStatesKey));
    }

    SettingsDatabase *settings = ICore::settingsDatabase();
    if (settings->contains(QLatin1String(documentStatesKey)))
        d->m_editorStates = settings->value(QLatin1String(documentStatesKey))
            .value<QMap<QString, QVariant> >();

    if (settings->contains(QLatin1String(reloadBehaviorKey)))
        d->m_reloadSetting = (IDocument::ReloadSetting)settings->value(QLatin1String(reloadBehaviorKey)).toInt();

    if (settings->contains(QLatin1String(autoSaveEnabledKey))) {
        d->m_autoSaveEnabled = settings->value(QLatin1String(autoSaveEnabledKey)).toBool();
        d->m_autoSaveInterval = settings->value(QLatin1String(autoSaveIntervalKey)).toInt();
    }
    updateAutoSave();
}

void EditorManagerPrivate::setReloadSetting(IDocument::ReloadSetting behavior)
{
    d->m_reloadSetting = behavior;
}

IDocument::ReloadSetting EditorManagerPrivate::reloadSetting()
{
    return d->m_reloadSetting;
}

void EditorManagerPrivate::setAutoSaveEnabled(bool enabled)
{
    d->m_autoSaveEnabled = enabled;
    updateAutoSave();
}

bool EditorManagerPrivate::autoSaveEnabled()
{
    return d->m_autoSaveEnabled;
}

void EditorManagerPrivate::setAutoSaveInterval(int interval)
{
    d->m_autoSaveInterval = interval;
    updateAutoSave();
}

int EditorManagerPrivate::autoSaveInterval()
{
    return d->m_autoSaveInterval;
}

IEditor *EditorManagerPrivate::createEditor(Id editorId, const QString &fileName)
{
    if (debugEditorManager)
        qDebug() << Q_FUNC_INFO << editorId.name() << fileName;

    EditorManager::EditorFactoryList factories;
    if (!editorId.isValid()) {
        const QFileInfo fileInfo(fileName);
        // Find by mime type
        MimeType mimeType = MimeDatabase::findByFile(fileInfo);
        if (!mimeType) {
            qWarning("%s unable to determine mime type of %s/%s. Falling back to text/plain",
                     Q_FUNC_INFO, fileName.toUtf8().constData(), editorId.name().constData());
            mimeType = MimeDatabase::findByType(QLatin1String("text/plain"));
        }
        // open text files > 48 MB in binary editor
        if (fileInfo.size() > EditorManager::maxTextFileSize()
                && mimeType.type().startsWith(QLatin1String("text"))) {
            mimeType = MimeDatabase::findByType(QLatin1String("application/octet-stream"));
        }
        factories = EditorManager::editorFactories(mimeType, true);
    } else {
        // Find by editor id
        if (IEditorFactory *factory = findById<IEditorFactory>(editorId))
            factories.push_back(factory);
    }
    if (factories.empty()) {
        qWarning("%s: unable to find an editor factory for the file '%s', editor Id '%s'.",
                 Q_FUNC_INFO, fileName.toUtf8().constData(), editorId.name().constData());
        return 0;
    }

    IEditor *editor = factories.front()->createEditor();
    if (editor) {
        QTC_CHECK(editor->document()->id().isValid()); // sanity check that the editor has an id set
        connect(editor->document(), SIGNAL(changed()), d, SLOT(handleDocumentStateChange()));
        emit m_instance->editorCreated(editor, fileName);
    }

    return editor;
}

void EditorManagerPrivate::addEditor(IEditor *editor)
{
    if (!editor)
        return;
    ICore::addContextObject(editor);

    bool isNewDocument = false;
    DocumentModel::addEditor(editor, &isNewDocument);
    if (isNewDocument) {
        const bool isTemporary = editor->document()->isTemporary();
        const bool addWatcher = !isTemporary;
        DocumentManager::addDocument(editor->document(), addWatcher);
        if (!isTemporary)
            DocumentManager::addToRecentFiles(editor->document()->filePath(),
                                              editor->document()->id());
    }
    emit m_instance->editorOpened(editor);
}

void EditorManagerPrivate::removeEditor(IEditor *editor)
{
    bool lastOneForDocument = false;
    DocumentModel::removeEditor(editor, &lastOneForDocument);
    if (lastOneForDocument)
        DocumentManager::removeDocument(editor->document());
    ICore::removeContextObject(editor);
}

IEditor *EditorManagerPrivate::placeEditor(EditorView *view, IEditor *editor)
{
    Q_ASSERT(view && editor);

    if (view->hasEditor(editor))
        return editor;
    if (IEditor *e = view->editorForDocument(editor->document()))
        return e;

    if (EditorView *sourceView = viewForEditor(editor)) {
        // try duplication or pull editor over to new view
        bool duplicateSupported = editor->duplicateSupported();
        if (editor != sourceView->currentEditor() || !duplicateSupported) {
            // pull the IEditor over to the new view
            sourceView->removeEditor(editor);
            view->addEditor(editor);
            view->setCurrentEditor(editor);
            if (!sourceView->currentEditor()) {
                EditorView *replacementView = 0;
                if (IEditor *replacement = pickUnusedEditor(&replacementView)) {
                    if (replacementView)
                        replacementView->removeEditor(replacement);
                    sourceView->addEditor(replacement);
                    sourceView->setCurrentEditor(replacement);
                }
            }
            return editor;
        } else if (duplicateSupported) {
            editor = duplicateEditor(editor);
            Q_ASSERT(editor);
        }
    }
    view->addEditor(editor);
    return editor;
}

IEditor *EditorManagerPrivate::duplicateEditor(IEditor *editor)
{
    if (!editor->duplicateSupported())
        return 0;

    IEditor *duplicate = editor->duplicate();
    duplicate->restoreState(editor->saveState());
    emit m_instance->editorCreated(duplicate, duplicate->document()->filePath());
    addEditor(duplicate);
    return duplicate;
}

IEditor *EditorManagerPrivate::activateEditor(EditorView *view, IEditor *editor,
                                              EditorManager::OpenEditorFlags flags)
{
    Q_ASSERT(view);

    if (!editor) {
        if (!d->m_currentEditor)
            setCurrentEditor(0, (flags & EditorManager::IgnoreNavigationHistory));
        return 0;
    }

    editor = placeEditor(view, editor);

    if (!(flags & EditorManager::DoNotChangeCurrentEditor)) {
        setCurrentEditor(editor, (flags & EditorManager::IgnoreNavigationHistory));
        if (!(flags & EditorManager::DoNotMakeVisible)) {
            // switch to design mode?
            if (editor->isDesignModePreferred()) {
                ModeManager::activateMode(Core::Constants::MODE_DESIGN);
                ModeManager::setFocusToCurrentMode();
            } else {
993 994 995
                int index;
                findEditorArea(view, &index);
                if (index == 0) // main window --> we might need to switch mode
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015