editormanager.cpp 60.6 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2
3
4
**
** This file is part of Qt Creator
**
5
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
7
8
**
** Contact:  Qt Software Information (qt-info@nokia.com)
**
9
** Commercial Usage
10
**
11
12
13
14
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
15
**
16
** GNU Lesser General Public License Usage
17
**
18
19
20
21
22
23
** 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.
24
**
25
26
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
con's avatar
con committed
27
**
28
**************************************************************************/
hjk's avatar
hjk committed
29

con's avatar
con committed
30
#include "editormanager.h"
31
#include "editorview.h"
con's avatar
con committed
32
#include "openeditorswindow.h"
mae's avatar
mae committed
33
#include "openeditorsview.h"
con's avatar
con committed
34
35
#include "openwithdialog.h"
#include "filemanager.h"
36
#include "icore.h"
con's avatar
con committed
37
38
#include "iversioncontrol.h"
#include "mimedatabase.h"
39
40
41
#include "saveitemsdialog.h"
#include "tabpositionindicator.h"
#include "vcsmanager.h"
con's avatar
con committed
42
43
44
45

#include <coreplugin/coreconstants.h>
#include <coreplugin/modemanager.h>
#include <coreplugin/uniqueidmanager.h>
46
#include <coreplugin/actionmanager/actionmanager.h>
con's avatar
con committed
47
48
49
50
#include <coreplugin/editormanager/ieditorfactory.h>
#include <coreplugin/baseview.h>
#include <coreplugin/imode.h>

51
52
#include <extensionsystem/pluginmanager.h>

hjk's avatar
hjk committed
53
54
55
#include <utils/qtcassert.h>

#include <QtCore/QDebug>
con's avatar
con committed
56
57
58
#include <QtCore/QFileInfo>
#include <QtCore/QMap>
#include <QtCore/QProcess>
hjk's avatar
hjk committed
59
60
#include <QtCore/QSet>
#include <QtCore/QSettings>
con's avatar
con committed
61
62
63
64

#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QFileDialog>
hjk's avatar
hjk committed
65
#include <QtGui/QLayout>
66
#include <QtGui/QMainWindow>
con's avatar
con committed
67
68
69
#include <QtGui/QMenu>
#include <QtGui/QMessageBox>
#include <QtGui/QPushButton>
hjk's avatar
hjk committed
70
#include <QtGui/QSplitter>
71
#include <QtGui/QStackedLayout>
con's avatar
con committed
72

73
74
Q_DECLARE_METATYPE(Core::IEditor*)

con's avatar
con committed
75
76
77
78
79
using namespace Core;
using namespace Core::Internal;

enum { debugEditorManager=0 };

80
81
82
83
84
static inline ExtensionSystem::PluginManager *pluginManager()
{
    return ExtensionSystem::PluginManager::instance();
}

con's avatar
con committed
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
//===================EditorManager=====================

EditorManagerPlaceHolder *EditorManagerPlaceHolder::m_current = 0;

EditorManagerPlaceHolder::EditorManagerPlaceHolder(Core::IMode *mode, QWidget *parent)
    : QWidget(parent), m_mode(mode)
{
    setLayout(new QVBoxLayout);
    layout()->setMargin(0);
    connect(Core::ModeManager::instance(), SIGNAL(currentModeChanged(Core::IMode *)),
            this, SLOT(currentModeChanged(Core::IMode *)));
}

EditorManagerPlaceHolder::~EditorManagerPlaceHolder()
{
    if (m_current == this) {
        EditorManager::instance()->setParent(0);
        EditorManager::instance()->hide();
    }
}

void EditorManagerPlaceHolder::currentModeChanged(Core::IMode *mode)
{
    if (m_current == this) {
        m_current = 0;
        EditorManager::instance()->setParent(0);
        EditorManager::instance()->hide();
    }
    if (m_mode == mode) {
        m_current = this;
        layout()->addWidget(EditorManager::instance());
        EditorManager::instance()->show();
    }
}

EditorManagerPlaceHolder* EditorManagerPlaceHolder::current()
{
    return m_current;
}

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

127
128
namespace Core {
struct EditorManagerPrivate {
con's avatar
con committed
129
130
131
132
133
134
135
136
    struct EditLocation {
        QPointer<IEditor> editor;
        QString fileName;
        QString kind;
        QVariant state;
    };
    explicit EditorManagerPrivate(ICore *core, QWidget *parent);
    ~EditorManagerPrivate();
137
    Internal::EditorView *m_view;
mae's avatar
mae committed
138
    Internal::SplitterOrView *m_splitter;
mae's avatar
mae committed
139
    QPointer<IEditor> m_currentEditor;
mae's avatar
mae committed
140
    QPointer<SplitterOrView> m_currentView;
141

con's avatar
con committed
142
143
144
145
146
147
148
149
150
151
152
153
154
155
    ICore *m_core;


    // actions
    QAction *m_revertToSavedAction;
    QAction *m_saveAction;
    QAction *m_saveAsAction;
    QAction *m_closeCurrentEditorAction;
    QAction *m_closeAllEditorsAction;
    QAction *m_gotoNextDocHistoryAction;
    QAction *m_gotoPreviousDocHistoryAction;
    QAction *m_goBackAction;
    QAction *m_goForwardAction;
    QAction *m_openInExternalEditorAction;
156
157
158
    QAction *m_splitAction;
    QAction *m_splitSideBySideAction;
    QAction *m_unsplitAction;
159
    QAction *m_gotoOtherWindowAction;
con's avatar
con committed
160
161
162
163
164
165
166
167
168
169
170
171
172
173

    QList<IEditor *> m_editorHistory;
    QList<EditLocation *> m_navigationHistory;
    int currentNavigationHistoryPosition;
    Internal::OpenEditorsWindow *m_windowPopup;
    Core::BaseView *m_openEditorsView;
    Internal::EditorClosingCoreListener *m_coreListener;

    QMap<QString, QVariant> m_editorStates;
    Internal::OpenEditorsViewFactory *m_openEditorsFactory;

    QString fileFilters;
    QString selectedFilter;

174
    EditorModel *m_editorModel;
con's avatar
con committed
175
176
    QString m_externalEditor;
};
177
}
con's avatar
con committed
178
179

EditorManagerPrivate::EditorManagerPrivate(ICore *core, QWidget *parent) :
180
    m_view(0),
181
    m_splitter(0),
con's avatar
con committed
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
    m_core(core),
    m_revertToSavedAction(new QAction(EditorManager::tr("Revert to Saved"), parent)),
    m_saveAction(new QAction(parent)),
    m_saveAsAction(new QAction(parent)),
    m_closeCurrentEditorAction(new QAction(EditorManager::tr("Close"), parent)),
    m_closeAllEditorsAction(new QAction(EditorManager::tr("Close All"), parent)),
    m_gotoNextDocHistoryAction(new QAction(EditorManager::tr("Next Document in History"), parent)),
    m_gotoPreviousDocHistoryAction(new QAction(EditorManager::tr("Previous Document in History"), parent)),
    m_goBackAction(new QAction(EditorManager::tr("Go back"), parent)),
    m_goForwardAction(new QAction(EditorManager::tr("Go forward"), parent)),
    m_openInExternalEditorAction(new QAction(EditorManager::tr("Open in External Editor"), parent)),
    currentNavigationHistoryPosition(-1),
    m_windowPopup(0),
    m_coreListener(0)
{
197
    m_editorModel = new EditorModel(parent);
con's avatar
con committed
198
199
200
201
202
203
204
205
206
207
}

EditorManagerPrivate::~EditorManagerPrivate()
{
    qDeleteAll(m_navigationHistory);
    m_navigationHistory.clear();
}

EditorManager *EditorManager::m_instance = 0;

208
209
210
211
212
213
214
215
216
217
static Command *createSeparator(ActionManager *am, QObject *parent,
                                const QString &name,
                                const QList<int> &context)
{
    QAction *tmpaction = new QAction(parent);
    tmpaction->setSeparator(true);
    Command *cmd = am->registerAction(tmpaction, name, context);
    return cmd;
}

con's avatar
con committed
218
219
220
221
222
223
224
EditorManager::EditorManager(ICore *core, QWidget *parent) :
    QWidget(parent),
    m_d(new EditorManagerPrivate(core, parent))
{
    m_instance = this;

    connect(m_d->m_core, SIGNAL(contextAboutToChange(Core::IContext *)),
mae's avatar
mae committed
225
            this, SLOT(handleContextChange(Core::IContext *)));
con's avatar
con committed
226
227
228
229
230

    const QList<int> gc =  QList<int>() << Constants::C_GLOBAL_ID;
    const QList<int> editManagerContext =
            QList<int>() << m_d->m_core->uniqueIDManager()->uniqueIdentifier(Constants::C_EDITORMANAGER);

231
    ActionManager *am = m_d->m_core->actionManager();
232
    ActionContainer *mfile = am->actionContainer(Constants::M_FILE);
con's avatar
con committed
233
234

    //Revert to saved
con's avatar
con committed
235
    Command *cmd = am->registerAction(m_d->m_revertToSavedAction,
con's avatar
con committed
236
                                       Constants::REVERTTOSAVED, editManagerContext);
con's avatar
con committed
237
    cmd->setAttribute(Command::CA_UpdateText);
con's avatar
con committed
238
239
240
241
242
243
244
245
246
247
248
249
250
    cmd->setDefaultText(tr("Revert File to Saved"));
    mfile->addAction(cmd, Constants::G_FILE_SAVE);
    connect(m_d->m_revertToSavedAction, SIGNAL(triggered()), this, SLOT(revertToSaved()));

    //Save Action
    am->registerAction(m_d->m_saveAction, Constants::SAVE, editManagerContext);
    connect(m_d->m_saveAction, SIGNAL(triggered()), this, SLOT(saveFile()));

    //Save As Action
    am->registerAction(m_d->m_saveAsAction, Constants::SAVEAS, editManagerContext);
    connect(m_d->m_saveAsAction, SIGNAL(triggered()), this, SLOT(saveFileAs()));

    //Window Menu
251
    ActionContainer *mwindow = am->actionContainer(Constants::M_WINDOW);
con's avatar
con committed
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

    //Window menu separators
    QAction *tmpaction = new QAction(this);
    tmpaction->setSeparator(true);
    cmd = am->registerAction(tmpaction, QLatin1String("QtCreator.Window.Sep.Split"), editManagerContext);
    mwindow->addAction(cmd, Constants::G_WINDOW_SPLIT);

    tmpaction = new QAction(this);
    tmpaction->setSeparator(true);
    cmd = am->registerAction(tmpaction, QLatin1String("QtCreator.Window.Sep.Close"), editManagerContext);
    mwindow->addAction(cmd, Constants::G_WINDOW_CLOSE);

    tmpaction = new QAction(this);
    tmpaction->setSeparator(true);
    cmd = am->registerAction(tmpaction, QLatin1String("QtCreator.Window.Sep.Navigate"), editManagerContext);
    mwindow->addAction(cmd, Constants::G_WINDOW_NAVIGATE);

    tmpaction = new QAction(this);
    tmpaction->setSeparator(true);
    cmd = am->registerAction(tmpaction, QLatin1String("QtCreator.Window.Sep.Navigate.Groups"), editManagerContext);
    mwindow->addAction(cmd, Constants::G_WINDOW_NAVIGATE_GROUPS);

    tmpaction = new QAction(this);
    tmpaction->setSeparator(true);
    cmd = am->registerAction(tmpaction, QLatin1String("QtCreator.Window.Sep.Bottom"), editManagerContext);
    mwindow->addAction(cmd, Constants::G_WINDOW_LIST);

    //Close Action
    cmd = am->registerAction(m_d->m_closeCurrentEditorAction, Constants::CLOSE, editManagerContext);
    cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+W")));
con's avatar
con committed
282
    cmd->setAttribute(Core::Command::CA_UpdateText);
con's avatar
con committed
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
    cmd->setDefaultText(m_d->m_closeCurrentEditorAction->text());
    mfile->addAction(cmd, Constants::G_FILE_CLOSE);
    connect(m_d->m_closeCurrentEditorAction, SIGNAL(triggered()), this, SLOT(closeEditor()));

    //Close All Action
    cmd = am->registerAction(m_d->m_closeAllEditorsAction, Constants::CLOSEALL, editManagerContext);
    cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+Shift+W")));
    mfile->addAction(cmd, Constants::G_FILE_CLOSE);
    connect(m_d->m_closeAllEditorsAction, SIGNAL(triggered()), this, SLOT(closeAllEditors()));

    // Goto Previous In History Action
    cmd = am->registerAction(m_d->m_gotoPreviousDocHistoryAction, Constants::GOTOPREVINHISTORY, editManagerContext);
#ifdef Q_WS_MAC
    cmd->setDefaultKeySequence(QKeySequence(tr("Alt+Tab")));
#else
    cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+Tab")));
#endif
    mwindow->addAction(cmd, Constants::G_WINDOW_NAVIGATE);
    connect(m_d->m_gotoPreviousDocHistoryAction, SIGNAL(triggered()), this, SLOT(gotoPreviousDocHistory()));

    // Goto Next In History Action
    cmd = am->registerAction(m_d->m_gotoNextDocHistoryAction, Constants::GOTONEXTINHISTORY, editManagerContext);
#ifdef Q_WS_MAC
    cmd->setDefaultKeySequence(QKeySequence(tr("Alt+Shift+Tab")));
#else
    cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+Shift+Tab")));
#endif
    mwindow->addAction(cmd, Constants::G_WINDOW_NAVIGATE);
    connect(m_d->m_gotoNextDocHistoryAction, SIGNAL(triggered()), this, SLOT(gotoNextDocHistory()));

    // Go back in navigation history
    cmd = am->registerAction(m_d->m_goBackAction, Constants::GO_BACK, editManagerContext);
#ifdef Q_WS_MAC
    cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+Alt+Left")));
#else
    cmd->setDefaultKeySequence(QKeySequence(tr("Alt+Left")));
#endif
    mwindow->addAction(cmd, Constants::G_WINDOW_NAVIGATE);
    connect(m_d->m_goBackAction, SIGNAL(triggered()), this, SLOT(goBackInNavigationHistory()));

    // Go forward in navigation history
    cmd = am->registerAction(m_d->m_goForwardAction, Constants::GO_FORWARD, editManagerContext);
#ifdef Q_WS_MAC
    cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+Alt+Right")));
#else
    cmd->setDefaultKeySequence(QKeySequence(tr("Alt+Right")));
#endif
    mwindow->addAction(cmd, Constants::G_WINDOW_NAVIGATE);
    connect(m_d->m_goForwardAction, SIGNAL(triggered()), this, SLOT(goForwardInNavigationHistory()));

333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
    m_d->m_splitAction = new QAction(tr("Split"), this);
    cmd = am->registerAction(m_d->m_splitAction, Constants::SPLIT, editManagerContext);
    cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+E,1")));
    mwindow->addAction(cmd, Constants::G_WINDOW_SPLIT);
    connect(m_d->m_splitAction, SIGNAL(triggered()), this, SLOT(split()));

    m_d->m_splitSideBySideAction = new QAction(tr("Split Side by Side"), this);
    cmd = am->registerAction(m_d->m_splitSideBySideAction, Constants::SPLIT_SIDE_BY_SIDE, editManagerContext);
    cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+E,2")));
    mwindow->addAction(cmd, Constants::G_WINDOW_SPLIT);
    connect(m_d->m_splitSideBySideAction, SIGNAL(triggered()), this, SLOT(splitSideBySide()));

    m_d->m_unsplitAction = new QAction(tr("Unsplit"), this);
    cmd = am->registerAction(m_d->m_unsplitAction, Constants::UNSPLIT, editManagerContext);
    cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+E,0")));
    mwindow->addAction(cmd, Constants::G_WINDOW_SPLIT);
    connect(m_d->m_unsplitAction, SIGNAL(triggered()), this, SLOT(unsplit()));

351
352
353
354
355
    m_d->m_gotoOtherWindowAction = new QAction(tr("Goto other window"), this);
    cmd = am->registerAction(m_d->m_gotoOtherWindowAction, Constants::GOTO_OTHER_WINDOW, editManagerContext);
    cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+E,o")));
    mwindow->addAction(cmd, Constants::G_WINDOW_SPLIT);
    connect(m_d->m_gotoOtherWindowAction, SIGNAL(triggered()), this, SLOT(gotoOtherWindow()));
356

con's avatar
con committed
357

358
359
    ActionContainer *medit = am->actionContainer(Constants::M_EDIT);
    ActionContainer *advancedMenu = am->createMenu(Constants::M_EDIT_ADVANCED);
360
    medit->addMenu(advancedMenu, Constants::G_EDIT_ADVANCED);
con's avatar
con committed
361
    advancedMenu->menu()->setTitle(tr("&Advanced"));
362
363
364
365
366
367
368
369
370
371
372
373
    advancedMenu->appendGroup(Constants::G_EDIT_FORMAT);
    advancedMenu->appendGroup(Constants::G_EDIT_COLLAPSING);
    advancedMenu->appendGroup(Constants::G_EDIT_FONT);
    advancedMenu->appendGroup(Constants::G_EDIT_EDITOR);

    // Advanced menu separators
    cmd = createSeparator(am, this, QLatin1String("QtCreator.Edit.Sep.Collapsing"), editManagerContext);
    advancedMenu->addAction(cmd, Constants::G_EDIT_COLLAPSING);
    cmd = createSeparator(am, this, QLatin1String("QtCreator.Edit.Sep.Font"), editManagerContext);
    advancedMenu->addAction(cmd, Constants::G_EDIT_FONT);
    cmd = createSeparator(am, this, QLatin1String("QtCreator.Edit.Sep.Editor"), editManagerContext);
    advancedMenu->addAction(cmd, Constants::G_EDIT_EDITOR);
hjk's avatar
hjk committed
374

con's avatar
con committed
375
376
    cmd = am->registerAction(m_d->m_openInExternalEditorAction, Constants::OPEN_IN_EXTERNAL_EDITOR, editManagerContext);
    cmd->setDefaultKeySequence(QKeySequence(tr("Alt+V,Alt+I")));
377
    advancedMenu->addAction(cmd, Constants::G_EDIT_EDITOR);
con's avatar
con committed
378
379
380
381
    connect(m_d->m_openInExternalEditorAction, SIGNAL(triggered()), this, SLOT(openInExternalEditor()));


    // other setup
mae's avatar
mae committed
382
383
384
385
    m_d->m_splitter = new SplitterOrView(m_d->m_editorModel);
    m_d->m_splitter->setRoot(true);
    m_d->m_view = m_d->m_splitter->view();

con's avatar
con committed
386

387
388
389
390
    QHBoxLayout *layout = new QHBoxLayout(this);
    layout->setMargin(0);
    layout->setSpacing(0);
    layout->addWidget(m_d->m_splitter);
con's avatar
con committed
391
392
393
394
395
396
397
398
399

    updateActions();

    m_d->m_windowPopup = new OpenEditorsWindow(this);
}

EditorManager::~EditorManager()
{
    if (m_d->m_core) {
400
        ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
con's avatar
con committed
401
        if (m_d->m_coreListener) {
402
            pm->removeObject(m_d->m_coreListener);
con's avatar
con committed
403
404
            delete m_d->m_coreListener;
        }
405
        pm->removeObject(m_d->m_openEditorsFactory);
con's avatar
con committed
406
407
408
409
410
411
412
413
414
415
416
        delete m_d->m_openEditorsFactory;
    }
    delete m_d;
}

void EditorManager::init()
{
    QList<int> context;
    context << m_d->m_core->uniqueIDManager()->uniqueIdentifier("QtCreator.OpenDocumentsView");

    m_d->m_coreListener = new EditorClosingCoreListener(this);
417
418
    
    pluginManager()->addObject(m_d->m_coreListener);
con's avatar
con committed
419
420

    m_d->m_openEditorsFactory = new OpenEditorsViewFactory();
421
    pluginManager()->addObject(m_d->m_openEditorsFactory);
con's avatar
con committed
422
423
}

Roberto Raggi's avatar
Roberto Raggi committed
424
425
426
427
428
429
430
431
432
433
434
435
436
437
QString EditorManager::defaultExternalEditor() const
{
#ifdef Q_OS_MAC
    return m_d->m_core->resourcePath()
            +QLatin1String("/runInTerminal.command vi %f %l %c %W %H %x %y");
#elif defined(Q_OS_UNIX)
    return QLatin1String("xterm -geom %Wx%H+%x+%y -e vi %f +%l +\"normal %c|\"");
#elif defined (Q_OS_WIN)
    return QLatin1String("notepad %f");
#else
    return QString();
#endif
}

con's avatar
con committed
438
439
440
441
442
443
444
445
446
void EditorManager::updateEditorHistory()
{
    IEditor *editor = currentEditor();
    if (!editor)
        return;
    m_d->m_editorHistory.removeAll(editor);
    m_d->m_editorHistory.prepend(editor);
}

mae's avatar
mae committed
447
void EditorManager::removeEditor(IEditor *editor)
con's avatar
con committed
448
{
mae's avatar
mae committed
449
    bool isDuplicate = m_d->m_editorModel->isDuplicate(editor);
mae's avatar
mae committed
450
    m_d->m_editorModel->removeEditor(editor);
mae's avatar
mae committed
451
452
453
    if (!isDuplicate) {
        m_d->m_core->fileManager()->removeFile(editor->file());
    }
mae's avatar
mae committed
454
455
    m_d->m_editorHistory.removeAll(editor);
    m_d->m_core->removeContextObject(editor);
con's avatar
con committed
456
457
458

}

mae's avatar
mae committed
459
void EditorManager::handleContextChange(IContext *context)
con's avatar
con committed
460
461
462
463
{
    if (debugEditorManager)
        qDebug() << Q_FUNC_INFO;
    IEditor *editor = context ? qobject_cast<IEditor*>(context) : 0;
464
    if (editor) {
con's avatar
con committed
465
466
467
468
        setCurrentEditor(editor);
    } else {
        updateActions();
    }
469
470
}

con's avatar
con committed
471
472
void EditorManager::setCurrentEditor(IEditor *editor, bool ignoreNavigationHistory)
{
mae's avatar
mae committed
473
    setCurrentView(0);
mae's avatar
mae committed
474
    if (m_d->m_currentEditor == editor)
con's avatar
con committed
475
        return;
476
477
    if (m_d->m_currentEditor)
        updateCurrentPositionInNavigationHistory();
mae's avatar
mae committed
478

mae's avatar
mae committed
479
    m_d->m_currentEditor = editor;
con's avatar
con committed
480
    if (editor) {
481
        bool addToHistory = (!ignoreNavigationHistory);
con's avatar
con committed
482
483
        if (addToHistory)
            addCurrentPositionToNavigationHistory(true);
484

485
486
        if (SplitterOrView *splitterOrView = m_d->m_splitter->findView(editor))
            splitterOrView->view()->setCurrentEditor(editor);
con's avatar
con committed
487
    }
mae's avatar
mae committed
488
489
490
    updateActions();
    updateEditorHistory();
    emit currentEditorChanged(editor);
con's avatar
con committed
491
492
}

mae's avatar
mae committed
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512

void EditorManager::setCurrentView(Core::Internal::SplitterOrView *view)
{
    if (view == m_d->m_currentView)
        return;

    SplitterOrView *old = m_d->m_currentView;
    m_d->m_currentView = view;

    if (old)
        old->update();
    if (view)
        view->update();
}

Core::Internal::SplitterOrView *EditorManager::currentView() const
{
    return m_d->m_currentView;
}

con's avatar
con committed
513
514
515
516
517
518
519
520
521
522
523
524
525
QList<IEditor *> EditorManager::editorsForFileName(const QString &filename) const
{
    QList<IEditor *> found;
    QString fixedname = FileManager::fixFileName(filename);
    foreach (IEditor *editor, openedEditors()) {
        if (fixedname == FileManager::fixFileName(editor->file()->fileName()))
            found << editor;
    }
    return found;
}

IEditor *EditorManager::currentEditor() const
{
mae's avatar
mae committed
526
    return m_d->m_currentEditor;
con's avatar
con committed
527
528
529
530
531
532
533
534
}


// SLOT connected to action
// since this is potentially called in the event handler of the editor
// we simply postpone it with a single shot timer
void EditorManager::closeEditor()
{
mae's avatar
mae committed
535
    closeEditor(m_d->m_currentEditor);
con's avatar
con committed
536
537
}

mae's avatar
mae committed
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
void EditorManager::emptyView(Core::Internal::EditorView *view)
{
    if (!view)
        return;


    QList<IEditor *> editors = view->editors();
    foreach (IEditor *editor, editors) {
        if (!m_d->m_editorModel->isDuplicate(editor)) {
            editors.removeAll(editor);
            view->removeEditor(editor);
            continue;
        }
        emit editorAboutToClose(editor);
        removeEditor(editor);
        view->removeEditor(editor);
    }
    emit editorsClosed(editors);
    foreach (IEditor *editor, editors) {
        delete editor;
    }
}

mae's avatar
mae committed
561
void EditorManager::closeView(Core::Internal::EditorView *view)
con's avatar
con committed
562
{
mae's avatar
mae committed
563
    if (!view)
con's avatar
con committed
564
        return;
mae's avatar
mae committed
565

566
    if (view == m_d->m_view) {
567
568
        if (IEditor *e = view->currentEditor())
            closeEditors(QList<IEditor *>() << e);
mae's avatar
mae committed
569
570
571
572
573
574
        return;
    }

    emptyView(view);

    SplitterOrView *splitterOrView = m_d->m_splitter->findView(view);
575
    Q_ASSERT(splitterOrView);
mae's avatar
mae committed
576
577
578
    Q_ASSERT(splitterOrView->view() == view);
    SplitterOrView *splitter = m_d->m_splitter->findSplitter(splitterOrView);
    Q_ASSERT(splitterOrView->hasEditors() == false);
579
    splitterOrView->hide();
mae's avatar
mae committed
580
581
582
583
584
585
586
587
588
589
    delete splitterOrView;

    splitter->unsplit();

    SplitterOrView *newCurrent = splitter->findFirstView();
    if (newCurrent) {
        if (newCurrent->editor())
            activateEditor(newCurrent->view(), newCurrent->editor());
        else
            setCurrentView(newCurrent);
mae's avatar
mae committed
590
    }
591
    updateEditorHistory();
mae's avatar
mae committed
592
}
mae's avatar
mae committed
593

mae's avatar
mae committed
594
595
596
597
598
void EditorManager::closeEditor(Core::IEditor *editor)
{
    if (!editor)
        return;
    closeEditors(QList<IEditor *>() << editor);
con's avatar
con committed
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
}

QList<IEditor*>
    EditorManager::editorsForFiles(QList<IFile*> files) const
{
    const QList<IEditor *> editors = openedEditors();
    QSet<IEditor *> found;
    foreach (IFile *file, files) {
        foreach (IEditor *editor, editors) {
            if (editor->file() == file && !found.contains(editor)) {
                    found << editor;
            }
        }
    }
    return found.toList();
}

616
QList<IFile *> EditorManager::filesForEditors(QList<IEditor *> editors) const
con's avatar
con committed
617
618
619
620
621
622
{
    QSet<IEditor *> handledEditors;
    QList<IFile *> files;
    foreach (IEditor *editor, editors) {
        if (!handledEditors.contains(editor)) {
            files << editor->file();
623
            handledEditors.insert(editor);
con's avatar
con committed
624
625
626
627
628
629
630
        }
    }
    return files;
}

bool EditorManager::closeAllEditors(bool askAboutModifiedEditors)
{
631
    m_d->m_editorModel->removeAllRestoredEditors();
con's avatar
con committed
632
633
634
635
636
637
638
639
640
641
642
    return closeEditors(openedEditors(), askAboutModifiedEditors);
}

bool EditorManager::closeEditors(const QList<IEditor*> editorsToClose, bool askAboutModifiedEditors)
{
    if (editorsToClose.isEmpty())
        return true;
    bool closingFailed = false;
    QList<IEditor*> acceptedEditors;
    //ask all core listeners to check whether the editor can be closed
    const QList<ICoreListener *> listeners =
643
        pluginManager()->getObjects<ICoreListener>();
con's avatar
con committed
644
645
    foreach (IEditor *editor, editorsToClose) {
        bool editorAccepted = true;
mae's avatar
mae committed
646
647
        if (m_d->m_editorModel->isDuplicate(editor))
            editor = m_d->m_editorModel->originalForDuplicate(editor);
con's avatar
con committed
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
        foreach (ICoreListener *listener, listeners) {
            if (!listener->editorAboutToClose(editor)) {
                editorAccepted = false;
                closingFailed = false;
                break;
            }
        }
        if (editorAccepted)
            acceptedEditors.append(editor);
    }
    if (acceptedEditors.isEmpty())
        return false;
    //ask whether to save modified files
    if (askAboutModifiedEditors) {
        bool cancelled = false;
663
        QList<IFile*> list = ICore::instance()->fileManager()->
con's avatar
con committed
664
665
666
667
668
669
670
671
672
673
674
            saveModifiedFiles(filesForEditors(acceptedEditors), &cancelled);
        if (cancelled)
            return false;
        if (!list.isEmpty()) {
            QSet<IEditor*> skipSet = editorsForFiles(list).toSet();
            acceptedEditors = acceptedEditors.toSet().subtract(skipSet).toList();
            closingFailed = false;
        }
    }
    if (acceptedEditors.isEmpty())
        return false;
mae's avatar
mae committed
675
676
677
678
679

    // add duplicates
    foreach(IEditor *editor, acceptedEditors)
        acceptedEditors += m_d->m_editorModel->duplicatesFor(editor);

mae's avatar
mae committed
680
681
682
    QList<EditorView*> currentViews;
    EditorView *currentView = 0;

con's avatar
con committed
683
684
685
686
687
688
689
690
    // remove the editors
    foreach (IEditor *editor, acceptedEditors) {
        emit editorAboutToClose(editor);
        if (!editor->file()->fileName().isEmpty()) {
            QByteArray state = editor->saveState();
            if (!state.isEmpty())
                m_d->m_editorStates.insert(editor->file()->fileName(), QVariant(state));
        }
mae's avatar
mae committed
691

mae's avatar
mae committed
692
        removeEditor(editor);
mae's avatar
mae committed
693
694
695
696
697
698
        if (SplitterOrView *view = m_d->m_splitter->findView(editor)) {
            if (editor == view->view()->currentEditor()) {
                currentViews += view->view();
                if (editor == m_d->m_currentEditor)
                    currentView = view->view();
            }
mae's avatar
mae committed
699
            view->view()->removeEditor(editor);
mae's avatar
mae committed
700
        }
con's avatar
con committed
701
    }
mae's avatar
mae committed
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716

    foreach (EditorView *view, currentViews) {
        IEditor *newCurrent = view->currentEditor();
        if (!newCurrent)
            newCurrent = pickUnusedEditor();
        if (!newCurrent) {
            // pick the first one that can be duplicated
            foreach (IEditor *e, m_d->m_editorHistory) {
                if (e->duplicateSupported()) {
                    newCurrent = e;
                    break;
                }
            }
        }

717
        if (newCurrent) {
mae's avatar
mae committed
718
            activateEditor(view, newCurrent, NoActivate);
719
720
721
722
723
        } else {
            QModelIndex idx = m_d->m_editorModel->firstRestoredEditor();
            if (idx.isValid())
                activateEditor(idx, view);
        }
mae's avatar
mae committed
724
725
726
    }


con's avatar
con committed
727
728
729
730
    emit editorsClosed(acceptedEditors);
    foreach (IEditor *editor, acceptedEditors) {
        delete editor;
    }
mae's avatar
mae committed
731

732
733
734
735
736
    if (currentView) {
        setCurrentView(m_d->m_splitter->findView(currentView));
        if (IEditor *e = currentView->currentEditor())
            activateEditor(currentView, e);
    }
mae's avatar
mae committed
737

con's avatar
con committed
738
739
740
    return !closingFailed;
}

mae's avatar
mae committed
741
742
743
744
745
746
747
748
749
IEditor *EditorManager::pickUnusedEditor() const
{
    foreach (IEditor *editor, m_d->m_editorHistory) {
        SplitterOrView *view = m_d->m_splitter->findView(editor);
        if (!view || view->editor() != editor)
            return editor;
    }
    return 0;
}
con's avatar
con committed
750

751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770

void EditorManager::activateEditor(const QModelIndex &index, Internal::EditorView *view)
{
    IEditor *editor = index.data(Qt::UserRole).value<IEditor*>();
    if (editor)  {
        if (view)
            activateEditor(view, editor);
        else
            activateEditor(editor);
        return;
    }

    if (view)
        setCurrentView(m_d->m_splitter->findView(view));

    QString fileName = index.data(Qt::UserRole + 1).toString();
    QByteArray kind = index.data(Qt::UserRole + 2).toByteArray();
    openEditor(fileName, kind);
}

mae's avatar
mae committed
771
void EditorManager::activateEditor(IEditor *editor, OpenEditorFlags flags)
mae's avatar
mae committed
772
{
mae's avatar
mae committed
773
    SplitterOrView *splitterOrView = m_d->m_currentView;
774
775
    if (splitterOrView && splitterOrView->splitter())
        splitterOrView = 0; // safety if currentView gets out of sync
mae's avatar
mae committed
776
    setCurrentView(0);
777
778
    if (!editor)
        return;
mae's avatar
mae committed
779

780
781
782
    SplitterOrView *place = m_d->m_splitter->findView(editor);
    if (place && !place->isSplitter()) {
        splitterOrView = place;
783
784
785
    }


mae's avatar
mae committed
786
787
    if (!splitterOrView)
        splitterOrView = m_d->m_splitter->findEmptyView();
mae's avatar
mae committed
788

789
    if (!splitterOrView && m_d->m_currentEditor) {
mae's avatar
mae committed
790
        splitterOrView = m_d->m_splitter->findView(m_d->m_currentEditor);
791
792
793
        if (splitterOrView && !splitterOrView->isVisible()) // safety if currentEditor gets out of sync
            splitterOrView = 0;
    }
mae's avatar
mae committed
794
795
796
797
798
799
800
801
802
803
804
805
806

    if (!splitterOrView)
        splitterOrView = m_d->m_splitter->findFirstView();
    if (!splitterOrView) {
        splitterOrView = m_d->m_splitter;
    }

    activateEditor(splitterOrView->view(), editor, flags);
}

Core::IEditor *EditorManager::placeEditor(Core::Internal::EditorView *view, Core::IEditor *editor)
{
    Q_ASSERT(view && editor)            ;
mae's avatar
mae committed
807
    if (!view->hasEditor(editor)) {
mae's avatar
mae committed
808
809
810
811
        bool duplicateSupported = editor->duplicateSupported();
        if (SplitterOrView *sourceView = m_d->m_splitter->findView(editor)) {
            if (editor != sourceView->editor() || !duplicateSupported) {
                sourceView->view()->removeEditor(editor);
mae's avatar
mae committed
812
813
814
815
816
817
818
819
                view->addEditor(editor);
                view->setCurrentEditor(editor);
                if (!sourceView->editor()) {
                    if (IEditor *replacement = pickUnusedEditor()) {
                        sourceView->view()->addEditor(replacement);
                    }
                }
                return editor;
mae's avatar
mae committed
820
821
822
823
824
            } else if (duplicateSupported) {
                editor = duplicateEditor(editor);
                Q_ASSERT(editor);
            }
        }
mae's avatar
mae committed
825
826
        view->addEditor(editor);
    }
mae's avatar
mae committed
827
828
    return editor;
}
mae's avatar
mae committed
829

mae's avatar
mae committed
830
831
832
void EditorManager::activateEditor(Core::Internal::EditorView *view, Core::IEditor *editor, OpenEditorFlags flags)
{
    Q_ASSERT(view)            ;
mae's avatar
mae committed
833

mae's avatar
mae committed
834
835
836
    if (!editor && !m_d->m_currentEditor) {
        setCurrentEditor(0, (flags & IgnoreNavigationHistory));
        return;
mae's avatar
mae committed
837
838
    }

mae's avatar
mae committed
839
840
841
842
843
844
    editor = placeEditor(view, editor);

    if (!(flags & NoActivate)) {
        setCurrentEditor(editor, (flags & IgnoreNavigationHistory));
        ensureEditorManagerVisible();
        editor->widget()->setFocus();
mae's avatar
mae committed
845
846
847
    }
}

con's avatar
con committed
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
/* Find editors for a mimetype, best matching at the front
 * of the list. Recurse over the parent classes of the mimetype to
 * find them. */
static void mimeTypeFactoryRecursion(const MimeDatabase *db,
                                     const MimeType &mimeType,
                                     const QList<IEditorFactory*> &allFactories,
                                     bool firstMatchOnly,
                                     QList<IEditorFactory*> *list)
{
    typedef QList<IEditorFactory*> EditorFactoryList;
    // Loop factories to find type
    const QString type = mimeType.type();
    const EditorFactoryList::const_iterator fcend = allFactories.constEnd();
    for (EditorFactoryList::const_iterator fit = allFactories.constBegin(); fit != fcend; ++fit) {
        // Exclude duplicates when recursing over xml or C++ -> C -> text.
        IEditorFactory *factory = *fit;
        if (!list->contains(factory) && factory->mimeTypes().contains(type)) {
            list->push_back(*fit);
            if (firstMatchOnly)
                return;
            break;
        }
    }
    // Any parent classes? -> recurse
    QStringList parentTypes = mimeType.subClassesOf();
    if (parentTypes.empty())
        return;
    const QStringList::const_iterator pcend = parentTypes .constEnd();
    for (QStringList::const_iterator pit = parentTypes .constBegin(); pit != pcend; ++pit) {
        if (const MimeType parent = db->findByType(*pit))
            mimeTypeFactoryRecursion(db, parent, allFactories, firstMatchOnly, list);
    }
}

EditorManager::EditorFactoryList
    EditorManager::editorFactories(const MimeType &mimeType, bool bestMatchOnly) const
{
    EditorFactoryList rc;
886
    const EditorFactoryList allFactories = pluginManager()->getObjects<IEditorFactory>();
con's avatar
con committed
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
    mimeTypeFactoryRecursion(m_d->m_core->mimeDatabase(), mimeType, allFactories, bestMatchOnly, &rc);
    if (debugEditorManager)
        qDebug() << Q_FUNC_INFO << mimeType.type() << " returns " << rc;
    return rc;
}

IEditor *EditorManager::createEditor(const QString &editorKind,
                                     const QString &fileName)
{
    typedef QList<IEditorFactory*> FactoryList;
    if (debugEditorManager)
        qDebug() << Q_FUNC_INFO << editorKind << fileName;


    EditorFactoryList factories;
    if (editorKind.isEmpty()) {
        // Find by mime type
        const MimeType mimeType = m_d->m_core->mimeDatabase()->findByFile(QFileInfo(fileName));
        if (!mimeType) {
            qWarning("%s unable to determine mime type of %s/%s.",
                     Q_FUNC_INFO, fileName.toUtf8().constData(), editorKind.toUtf8().constData());
            return 0;
        }
        factories = editorFactories(mimeType, true);
    } else {
        // Find by editor kind
913
        const EditorFactoryList allFactories = pluginManager()->getObjects<IEditorFactory>();
con's avatar
con committed
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
        const EditorFactoryList::const_iterator acend = allFactories.constEnd();
        for (EditorFactoryList::const_iterator ait = allFactories.constBegin(); ait != acend; ++ait) {
            if (editorKind == (*ait)->kind()) {
                factories.push_back(*ait);
                break;
            }
        }
    }
    if (factories.empty()) {
        qWarning("%s: unable to find an editor factory for the file '%s', editor kind '%s'.",
                 Q_FUNC_INFO, fileName.toUtf8().constData(), editorKind.toUtf8().constData());
        return 0;
    }

    IEditor *editor = factories.front()->createEditor(this);
    if (editor)
        connect(editor, SIGNAL(changed()), this, SLOT(updateActions()));
    if (editor)
        emit editorCreated(editor, fileName);
    return editor;
}

mae's avatar
mae committed
936
void EditorManager::addEditor(IEditor *editor, bool isDuplicate)
con's avatar
con committed
937
938
939
940
{
    if (!editor)
        return;
    m_d->m_core->addContextObject(editor);
mae's avatar
mae committed
941

mae's avatar
mae committed
942
    m_d->m_editorModel->addEditor(editor, isDuplicate);
mae's avatar
mae committed
943
944
945
946
947
948
949
950
    if (!isDuplicate) {
        m_d->m_core->fileManager()->addFile(editor->file());
        m_d->m_core->fileManager()->addToRecentFiles(editor->file()->fileName());
    }

    m_d->m_editorHistory.removeAll(editor);
    m_d->m_editorHistory.prepend(editor);

con's avatar
con committed
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
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
    emit editorOpened(editor);
}

// Run the OpenWithDialog and return the editor kind
// selected by the user.
QString EditorManager::getOpenWithEditorKind(const QString &fileName) const
{
    QStringList editorKinds;
    // Collect editors that can open the file
    if (const MimeType mt = m_d->m_core->mimeDatabase()->findByFile(fileName)) {
        const EditorFactoryList editors = editorFactories(mt, false);
        const int size = editors.size();
        for (int i = 0; i < size; i++) {
            editorKinds.push_back(editors.at(i)->kind());
        }
    }
    if (editorKinds.empty())
        return QString();

    // Run dialog.
    OpenWithDialog dialog(fileName, m_d->m_core->mainWindow());
    dialog.setEditors(editorKinds);
    dialog.setCurrentEditor(0);
    if (dialog.exec() != QDialog::Accepted)
        return QString();
    return dialog.editor();
}

static QString formatFileFilters(const Core::ICore *core, QString *selectedFilter)
{
    QString rc;
    // Compile list of filter strings. If we find a glob  matching all files,
    // put it last and set it as default selectedFilter.
    QStringList filters = core->mimeDatabase()->filterStrings();
    filters.sort();
    selectedFilter->clear();
    if (filters.empty())
        return rc;
    const QString filterSeparator = QLatin1String(";;");
    bool hasAllFilter = false;
    const int size = filters.size();
    for (int i = 0; i < size; i++) {
        const QString &filterString = filters.at(i);
        if (filterString.isEmpty()) { // binary editor
            hasAllFilter = true;
        } else {
            if (!rc.isEmpty())
                rc += filterSeparator;
            rc += filterString;
        }
    }
    if (hasAllFilter) {
        // prepend all files filter
        // prepending instead of appending to work around a but in Qt/Mac
        QString allFilesFilter = QLatin1String("All Files (*)");
        if (!rc.isEmpty())
            allFilesFilter += filterSeparator;
        rc.prepend(allFilesFilter);
        *selectedFilter = allFilesFilter;
    } else {
        *selectedFilter = filters.front();
    }
    return rc;
}

IEditor *EditorManager::openEditor(const QString &fileName, const QString &editorKind,
mae's avatar
mae committed
1017
                                   EditorManager::OpenEditorFlags flags)
con's avatar
con committed
1018
1019
1020
1021
1022
1023
1024
1025
1026
{
    if (debugEditorManager)
        qDebug() << Q_FUNC_INFO << fileName << editorKind;

    if (fileName.isEmpty())
        return 0;

    const QList<IEditor *> editors = editorsForFileName(fileName);
    if (!editors.isEmpty()) {
mae's avatar
mae committed
1027
1028
        activateEditor(editors.first(), flags);
        return editors.first();
con's avatar
con committed
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
    }
    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
    IEditor *editor = createEditor(editorKind, fileName);
    if (!editor || !editor->open(fileName)) {
        QApplication::restoreOverrideCursor();
        QMessageBox::critical(m_d->m_core->mainWindow(), tr("Opening File"), tr("Cannot open file %1!").arg(fileName));
        delete editor;
        editor = 0;
        return 0;
    }
mae's avatar
mae committed
1039
    addEditor(editor);
con's avatar
con committed
1040
1041
    restoreEditorState(editor);
    QApplication::restoreOverrideCursor();
mae's avatar
mae committed
1042
1043
1044

    activateEditor(editor, flags);
    return editor;
con's avatar
con committed
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
}

QStringList EditorManager::getOpenFileNames() const
{
    QString dir;
    if (m_d->fileFilters.isEmpty())
        m_d->fileFilters = formatFileFilters(m_d->m_core, &m_d->selectedFilter);

    if (IEditor *curEditor = currentEditor()) {
        const QFileInfo fi(curEditor->file()->fileName());
        dir = fi.absolutePath();
    }

    return QFileDialog::getOpenFileNames(m_d->m_core->mainWindow(), tr("Open File"),
                                         dir, m_d->fileFilters, &m_d->selectedFilter);
}

void EditorManager::ensureEditorManagerVisible()
{
1064
    if (!isVisible())
con's avatar
con committed
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
        m_d->m_core->modeManager()->activateMode(Constants::MODE_EDIT);
}

IEditor *EditorManager::newFile(const QString &editorKind,
                                        QString *titlePattern,
                                        const QString &contents)
{
    if (debugEditorManager)
        qDebug() << Q_FUNC_INFO << editorKind << titlePattern << contents;

    if (editorKind.isEmpty())
        return 0;

    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
    IEditor *edt = createEditor(editorKind);
    if (!edt)
        return 0;

    if (!edt || !edt->createNew(contents)) {
        QApplication::restoreOverrideCursor();
        delete edt;
        edt = 0;
        return 0;
    }

    QString title = edt->displayName();

    if (title.isEmpty() && titlePattern) {
        const QChar dollar = QLatin1Char('$');
        const QChar dot = QLatin1Char('.');

        QString base = *titlePattern;
        if (base.isEmpty())
            base = QLatin1String("unnamed$");
        if (base.contains(dollar)) {
            int i = 1;
            QSet<QString> docnames;
            foreach (IEditor *editor, openedEditors()) {
                QString name = editor->file()->fileName();
                if (name.isEmpty()) {
                    name = editor->displayName();
                    name.remove(QLatin1Char('*'));
                } else {
                    name = QFileInfo(name).completeBaseName();
                }
                docnames << name;
            }

            do {
                title = base;
                title.replace(QString(dollar), QString::number(i++));
            } while (docnames.contains(title));
        } else {
            title = *titlePattern;
        }
    }
    *titlePattern = title;
    edt->setDisplayName(title);
mae's avatar
mae committed
1123
    addEditor(edt);
con's avatar
con committed
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
    QApplication::restoreOverrideCursor();
    return edt;
}

bool EditorManager::hasEditor(const QString &fileName) const
{
    return !editorsForFileName(fileName).isEmpty();
}

void EditorManager::restoreEditorState(IEditor *editor)
{
hjk's avatar
hjk committed
1135
    QTC_ASSERT(editor, return);
con's avatar
con committed
1136
    QString fileName = editor->file()->fileName();
hjk's avatar
hjk committed
1137
    if (m_d->m_editorStates.contains(fileName))
con's avatar
con committed
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
        editor->restoreState(m_d->m_editorStates.value(fileName).toByteArray());
}

bool EditorManager::saveEditor(IEditor *editor)
{
    return saveFile(editor);
}

bool EditorManager::saveFile(IEditor *editor)
{
    if (!editor)
        editor = currentEditor();
    if (!editor)
        return false;

    IFile *file = editor->file();
    const QString &fileName = file->fileName();
    if (!fileName.isEmpty() && file->isReadOnly()) {
        MakeWritableResult answer =
                makeEditorWritable(editor);
        if (answer == Failed)
            return false;
        if (answer == SavedAs)
            return true;
    }

    if (file->isReadOnly() || fileName.isEmpty()) {
        return saveFileAs(editor);
    }

    m_d->m_core->fileManager()->blockFileChange(file);
    const bool success = file->save(fileName);
    m_d->m_core->fileManager()->unblockFileChange(file);
    if (success)
        m_d->m_core->fileManager()->addToRecentFiles(editor->file()->fileName());
    return success;
}

1176
1177
1178
1179
1180
EditorManager::ReadOnlyAction
    EditorManager::promptReadOnlyFile(const QString &fileName,
                                      const IVersionControl *versionControl,
                                      QWidget *parent,
                                      bool displaySaveAsButton)
con's avatar
con committed
1181
1182
1183
1184
1185
1186
{
    QMessageBox msgBox(QMessageBox::Question, QObject::tr("File is Read Only"),
                       QObject::tr("The file %1 is read only.").arg(fileName),
                       QMessageBox::Cancel, parent);

    QPushButton *sccButton = 0;
1187
1188
1189
    if (versionControl && versionControl->supportsOperation(IVersionControl::OpenOperation))
        sccButton = msgBox.addButton(QObject::tr("Open with VCS (%1)").arg(versionControl->name()), QMessageBox::AcceptRole);

con's avatar
con committed
1190
    QPushButton *makeWritableButton =  msgBox.addButton(QObject::tr("Make writable"), QMessageBox::AcceptRole);
1191
1192
1193
1194
1195
1196

    QPushButton *saveAsButton = 0;
    if (displaySaveAsButton)
        msgBox.addButton(QObject::tr("Save as ..."), QMessageBox::ActionRole);

    msgBox.setDefaultButton(sccButton ? sccButton : makeWritableButton);
con's avatar
con committed
1197
    msgBox.exec();
1198

con's avatar
con committed
1199
1200
    QAbstractButton *clickedButton = msgBox.clickedButton();
    if (clickedButton == sccButton)
1201
        return RO_OpenVCS;
con's avatar
con committed
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
    if (clickedButton == makeWritableButton)
        return RO_MakeWriteable;
    if (clickedButton == saveAsButton)
        return RO_SaveAs;
    return  RO_Cancel;
}


MakeWritableResult
EditorManager::makeEditorWritable(IEditor *editor)
{
    QString directory = QFileInfo(editor->file()->fileName()).absolutePath();
    IVersionControl *versionControl = m_d->m_core->vcsManager()->findVersionControlForDirectory(directory);
    IFile *file = editor->file();
    const QString &fileName = file->fileName();

1218
1219
    switch (promptReadOnlyFile(fileName, versionControl, m_d->m_core->mainWindow(), true)) {
    case RO_OpenVCS:
con's avatar
con committed
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
        if (!versionControl->vcsOpen(fileName)) {
            QMessageBox::warning(m_d->m_core->mainWindow(), tr("Failed!"), tr("Could not open the file for edit with SCC."));
            return Failed;
        }
        return OpenedWithVersionControl;
    case RO_MakeWriteable: {
        const bool permsOk = QFile::setPermissions(fileName, QFile::permissions(fileName) | QFile::WriteUser);
        if (!permsOk) {
            QMessageBox::warning(m_d->m_core->mainWindow(), tr("Failed!"),  tr("Could not set permissions to writable."));
            return Failed;
        }
    }
        return MadeWritable;
    case RO_SaveAs :
        return saveFileAs(editor) ? SavedAs : Failed;
    case RO_Cancel:
        break;
    }
    return Failed;
}

bool EditorManager::saveFileAs(IEditor *editor)
{
    if (!editor)
        editor = currentEditor();
    if (!editor)
        return false;

    QString absoluteFilePath = m_d->m_core->fileManager()->getSaveAsFileName(editor->file());
    if (absoluteFilePath.isEmpty())
        return false;
    if (absoluteFilePath != editor->file()->fileName()) {
        const QList<IEditor *> existList = editorsForFileName(absoluteFilePath);
        if (!existList.isEmpty()) {
            closeEditors(existList, false);
        }
    }

    m_d->m_core->fileManager()->blockFileChange(editor->file());
    const bool success = editor->file()->save(absoluteFilePath);
    m_d->m_core->fileManager()->unblockFileChange(editor->file());

hjk's avatar
hjk committed
1262
    if (success)
con's avatar
con committed
1263
1264
1265
1266
1267
1268
1269
1270
1271
        m_d->m_core->fileManager()->addToRecentFiles(editor->file()->fileName());

    updateActions();
    return success;
}

void EditorManager::gotoNextDocHistory()
{
    OpenEditorsWindow *dialog = windowPopup();
1272
1273
1274
    if (dialog->isVisible()) {
        dialog->selectNextEditor();
    } else {
1275
        dialog->setEditors(m_d->m_editorHistory, m_d->m_currentEditor, m_d->m_editorModel);
1276
1277
1278
        dialog->selectNextEditor();
        showWindowPopup();
    }
con's avatar
con committed
1279
1280
1281
1282
1283
}

void EditorManager::gotoPreviousDocHistory()
{
    OpenEditorsWindow *dialog = windowPopup();
1284
1285
1286
    if (dialog->isVisible()) {
        dialog->selectPreviousEditor();
    } else {
1287
        dialog->setEditors(m_d->m_editorHistory, m_d->m_currentEditor, m_d->m_editorModel);
1288
1289
1290
        dialog->selectPreviousEditor();
        showWindowPopup();
    }
con's avatar
con committed
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
}

void EditorManager::makeCurrentEditorWritable()
{
    if (IEditor* curEditor = currentEditor())
        makeEditorWritable(curEditor);
}

void EditorManager::updateActions()
{
    QString fName;
    IEditor *curEditor = currentEditor();
    int openedCount = openedEditors().count();
    if (curEditor) {
        if (!curEditor->file()->fileName().isEmpty()) {
            QFileInfo fi(curEditor->file()->fileName());
            fName = fi.fileName();
        } else {
            fName = curEditor->displayName();
        }


        if (curEditor->file()->isModified() && curEditor->file()->isReadOnly()) {
            // we are about to change a read-only file, warn user
            showEditorInfoBar(QLatin1String("Core.EditorManager.MakeWritable"),
                tr("<b>Warning:</b> You are changing a read-only file."),
                tr("Make writable"), this, SLOT(makeCurrentEditorWritable()));
        } else {
            hideEditorInfoBar(QLatin1String("Core.EditorManager.MakeWritable"));
        }
    }

    m_d->m_saveAction->setEnabled(curEditor != 0 && curEditor->file()->isModified());
    m_d->m_saveAsAction->setEnabled(curEditor != 0 && curEditor->file()->isSaveAsAllowed());
    m_d->m_revertToSavedAction->setEnabled(curEditor != 0
        && !curEditor->file()->fileName().isEmpty() && curEditor->file()->isModified());

    m_d->m_saveAsAction->setText(tr("Save %1 As...").arg(fName));
    m_d->m_saveAction->setText(tr("&Save %1").arg(fName));
    m_d->m_revertToSavedAction->setText(tr("Revert %1 to Saved").arg(fName));


1333
    m_d->m_closeCurrentEditorAction->setEnabled(curEditor != 0);
con's avatar
con committed
1334
1335
1336
1337
1338
1339
1340
1341
    m_d->m_closeCurrentEditorAction->setText(tr("Close %1").arg(fName));
    m_d->m_closeAllEditorsAction->setEnabled(openedCount > 0);

    m_d->m_gotoNextDocHistoryAction->setEnabled(m_d->m_editorHistory.count() > 0);
    m_d->m_gotoPreviousDocHistoryAction->setEnabled(m_d->m_editorHistory.count() > 0);
    m_d->m_goBackAction->setEnabled(m_d->currentNavigationHistoryPosition > 0);
    m_d->m_goForwardAction->setEnabled(m_d->currentNavigationHistoryPosition < m_d->m_navigationHistory.size()-1);

1342
1343
1344
1345
    bool hasSplitter = m_d->m_splitter->isSplitter();
    m_d->m_unsplitAction->setEnabled(hasSplitter);
    m_d->m_gotoOtherWindowAction->setEnabled(hasSplitter);

1346
    m_d->m_openInExternalEditorAction->setEnabled(curEditor != 0);
con's avatar
con committed
1347
1348
1349
1350
}

QList<IEditor*> EditorManager::openedEditors() const
{
1351
    return m_d->m_editorModel->editors();
con's avatar
con committed
1352
1353
}

1354
Internal::EditorModel *EditorManager::openedEditorsModel() const
con's avatar
con committed
1355
{
1356
    return m_d->m_editorModel;
con's avatar
con committed
1357
1358
}

1359

con's avatar
con committed
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
QList<IEditor*> EditorManager::editorHistory() const
{
    return m_d->m_editorHistory;
}

void EditorManager::addCurrentPositionToNavigationHistory(bool compress)
{
    IEditor *editor = currentEditor();
    if (!editor)
        return;
    if (!editor->file())
        return;
1372
    
con's avatar
con committed
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
    QString fileName = editor->file()->fileName();
    QByteArray state = editor->saveState();
    // cut existing
    int firstIndexToRemove;
    if (compress && m_d->currentNavigationHistoryPosition >= 0) {
        EditorManagerPrivate::EditLocation *previousLocation =
                m_d->m_navigationHistory.at(m_d->currentNavigationHistoryPosition);
        if ((previousLocation->editor && editor == previousLocation->editor)
                || (!fileName.isEmpty() && previousLocation->fileName == fileName)) {
            firstIndexToRemove = m_d->currentNavigationHistoryPosition;
con's avatar
con committed
1383
1384
        } else {
            firstIndexToRemove = m_d->currentNavigationHistoryPosition+1;
con's avatar
con committed
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
        }
    } else {
        firstIndexToRemove = m_d->currentNavigationHistoryPosition+1;
    }
    if (firstIndexToRemove >= 0) {
        for (int i = m_d->m_navigationHistory.size()-1; i >= firstIndexToRemove; --i) {
            delete m_d->m_navigationHistory.takeLast();
        }
    }
    while (m_d->m_navigationHistory.size() >= 30) {
        delete m_d->m_navigationHistory.takeFirst();
    }
    EditorManagerPrivate::EditLocation *location = new EditorManagerPrivate::EditLocation;
    location->editor = editor;
    location->fileName = editor->file()->fileName();
    location->kind = editor->kind();
    location->state = QVariant(state);
    m_d->m_navigationHistory.append(location);
    m_d->currentNavigationHistoryPosition = m_d->m_navigationHistory.size()-1;
    updateActions();
}

1407
1408
void EditorManager::updateCurrentPositionInNavigationHistory()
{
1409
1410
1411
    if (!m_d->m_currentEditor
        || m_d->currentNavigationHistoryPosition < 0
        || m_d->m_navigationHistory.at(m_d->currentNavigationHistoryPosition)->editor != m_d->m_currentEditor)
1412
        return;
1413
    m_d->m_navigationHistory.at(m_d->currentNavigationHistoryPosition)->state = m_d->m_currentEditor->saveState();
1414
1415
}

con's avatar
con committed
1416
1417
void EditorManager::goBackInNavigationHistory()
{
1418
    updateCurrentPositionInNavigationHistory();
con's avatar
con committed
1419
1420
1421
1422
1423
1424
    while (m_d->currentNavigationHistoryPosition > 0) {
        --m_d->currentNavigationHistoryPosition;
        EditorManagerPrivate::EditLocation *location = m_d->m_navigationHistory.at(m_d->currentNavigationHistoryPosition);
        IEditor *editor;
        if (location->editor) {
            editor = location->editor;
mae's avatar
mae committed
1425
            activateEditor(location->editor, IgnoreNavigationHistory);
con's avatar
con committed
1426
        } else {
mae's avatar
mae committed
1427
            editor = openEditor(location->fileName, location->kind, IgnoreNavigationHistory);
con's avatar
con committed
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
            if (!editor) {
                delete m_d->m_navigationHistory.takeAt(m_d->currentNavigationHistoryPosition);
                continue;
            }
        }
        editor->restoreState(location->state.toByteArray());
        updateActions();
        ensureEditorManagerVisible();
        return;
    }
}

void EditorManager::goForwardInNavigationHistory()
{
1442
    updateCurrentPositionInNavigationHistory();
con's avatar
con committed
1443
1444
1445
1446
1447
1448
1449
    if (m_d->currentNavigationHistoryPosition >= m_d->m_navigationHistory.size()-1)
        return;
    ++m_d->currentNavigationHistoryPosition;
    EditorManagerPrivate::EditLocation *location = m_d->m_navigationHistory.at(m_d->currentNavigationHistoryPosition);
    IEditor *editor;
    if (location->editor) {
        editor = location->editor;
mae's avatar
mae committed
1450
        activateEditor(location->editor, IgnoreNavigationHistory);
con's avatar
con committed
1451
    } else {
mae's avatar
mae committed
1452
        editor = openEditor(location->fileName, location->kind, IgnoreNavigationHistory);
con's avatar
con committed
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
        if (!editor) {
            //TODO
            qDebug() << Q_FUNC_INFO << "can't open file" << location->fileName;
            return;
        }
    }
    editor->restoreState(location->state.toByteArray());
    updateActions();
    ensureEditorManagerVisible();
}

OpenEditorsWindow *EditorManager::windowPopup() const
{
    return m_d->m_windowPopup;
}

void EditorManager::showWindowPopup() const
{
    const QPoint p(mapToGlobal(QPoint(0, 0)));
    m_d->m_windowPopup->move((width()-m_d->m_windowPopup->width())/2 + p.x(),
                        (height()-m_d->m_windowPopup->height())/2 + p.y());
    m_d->m_windowPopup->setVisible(true);
}

QByteArray EditorManager::saveState() const
{
    QByteArray bytes;
    QDataStream stream(&bytes, QIODevice::WriteOnly);
1481

1482
    stream << QByteArray("EditorManagerV2");
1483

mae's avatar
mae committed
1484
    QList<IEditor *> editors = openedEditors();
1485
1486
1487
1488
1489
1490
    foreach (IEditor *editor, editors) {
        if (!editor->file()->fileName().isEmpty()) {
            QByteArray state = editor->saveState();
            if (!state.isEmpty())
                m_d->m_editorStates.insert(editor->file()->fileName(), QVariant(state));
        }
mae's avatar
mae committed