editormanager.cpp 55.8 KB
Newer Older
con's avatar
con committed
1
2
3
4
/***************************************************************************
**
** This file is part of Qt Creator
**
5
** Copyright (c) 2008-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
10
11
**
** Non-Open Source Usage
**
con's avatar
con committed
12
13
14
** Licensees may use this file in accordance with the Qt Beta Version
** License Agreement, Agreement version 2.2 provided with the Software or,
** alternatively, in accordance with the terms contained in a written
15
16
17
18
** agreement between you and Nokia.
**
** GNU General Public License Usage
**
con's avatar
con committed
19
20
21
22
23
24
25
26
27
28
** Alternatively, this file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the packaging
** of this file.  Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
**
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** In addition, as a special exception, Nokia gives you certain additional
29
** rights. These rights are described in the Nokia Qt GPL Exception
30
** version 1.3, included in the file GPL_EXCEPTION.txt in this package.
31
**
con's avatar
con committed
32
***************************************************************************/
hjk's avatar
hjk committed
33

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

#include <coreplugin/coreconstants.h>
#include <coreplugin/modemanager.h>
#include <coreplugin/uniqueidmanager.h>
50
#include <coreplugin/actionmanager/actionmanager.h>
con's avatar
con committed
51
52
53
54
#include <coreplugin/editormanager/ieditorfactory.h>
#include <coreplugin/baseview.h>
#include <coreplugin/imode.h>

55
56
#include <extensionsystem/pluginmanager.h>

hjk's avatar
hjk committed
57
58
59
#include <utils/qtcassert.h>

#include <QtCore/QDebug>
con's avatar
con committed
60
61
62
#include <QtCore/QFileInfo>
#include <QtCore/QMap>
#include <QtCore/QProcess>
hjk's avatar
hjk committed
63
64
#include <QtCore/QSet>
#include <QtCore/QSettings>
con's avatar
con committed
65
66
67
68

#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QFileDialog>
hjk's avatar
hjk committed
69
#include <QtGui/QLayout>
70
#include <QtGui/QMainWindow>
con's avatar
con committed
71
72
73
#include <QtGui/QMenu>
#include <QtGui/QMessageBox>
#include <QtGui/QPushButton>
hjk's avatar
hjk committed
74
#include <QtGui/QSplitter>
75
#include <QtGui/QStackedLayout>
con's avatar
con committed
76
77
78
79
80
81

using namespace Core;
using namespace Core::Internal;

enum { debugEditorManager=0 };

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

con's avatar
con committed
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
//===================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

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

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

    bool m_suppressEditorChanges;

    // 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;
159
160
161
    QAction *m_splitAction;
    QAction *m_splitSideBySideAction;
    QAction *m_unsplitAction;
162
    QAction *m_gotoOtherWindowAction;
con's avatar
con committed
163
164
165
166
167
168
169
170
171
172
173
174
175
176

    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;

177
    EditorModel *m_editorModel;
con's avatar
con committed
178
179
    QString m_externalEditor;
};
180
}
con's avatar
con committed
181
182

EditorManagerPrivate::EditorManagerPrivate(ICore *core, QWidget *parent) :
183
    m_view(0),
184
185
    m_splitter(0),
    m_stackedLayout(0),
con's avatar
con committed
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
    m_core(core),
    m_suppressEditorChanges(false),
    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)
{
202
    m_editorModel = new EditorModel(parent);
con's avatar
con committed
203
204
205
206
207
208
209
210
211
212
}

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

EditorManager *EditorManager::m_instance = 0;

213
214
215
216
217
218
219
220
221
222
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
223
224
225
226
227
228
229
230
231
232
233
234
235
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 *)),
            this, SLOT(updateCurrentEditorAndGroup(Core::IContext *)));

    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);

236
    ActionManager *am = m_d->m_core->actionManager();
237
    ActionContainer *mfile = am->actionContainer(Constants::M_FILE);
con's avatar
con committed
238
239

    //Revert to saved
con's avatar
con committed
240
    Command *cmd = am->registerAction(m_d->m_revertToSavedAction,
con's avatar
con committed
241
                                       Constants::REVERTTOSAVED, editManagerContext);
con's avatar
con committed
242
    cmd->setAttribute(Command::CA_UpdateText);
con's avatar
con committed
243
244
245
246
247
248
249
250
251
252
253
254
255
    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
256
    ActionContainer *mwindow = am->actionContainer(Constants::M_WINDOW);
con's avatar
con committed
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286

    //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
287
    cmd->setAttribute(Core::Command::CA_UpdateText);
con's avatar
con committed
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
    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()));

338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
    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()));

356
357
358
359
360
    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()));
361

con's avatar
con committed
362

363
364
    ActionContainer *medit = am->actionContainer(Constants::M_EDIT);
    ActionContainer *advancedMenu = am->createMenu(Constants::M_EDIT_ADVANCED);
365
    medit->addMenu(advancedMenu, Constants::G_EDIT_ADVANCED);
con's avatar
con committed
366
    advancedMenu->menu()->setTitle(tr("&Advanced"));
367
368
369
370
371
372
373
374
375
376
377
378
    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
379

con's avatar
con committed
380
381
    cmd = am->registerAction(m_d->m_openInExternalEditorAction, Constants::OPEN_IN_EXTERNAL_EDITOR, editManagerContext);
    cmd->setDefaultKeySequence(QKeySequence(tr("Alt+V,Alt+I")));
382
    advancedMenu->addAction(cmd, Constants::G_EDIT_EDITOR);
con's avatar
con committed
383
384
385
386
387
388
389
390
    connect(m_d->m_openInExternalEditorAction, SIGNAL(triggered()), this, SLOT(openInExternalEditor()));


    // other setup
    connect(this, SIGNAL(currentEditorChanged(Core::IEditor*)),
            this, SLOT(updateActions()));
    connect(this, SIGNAL(currentEditorChanged(Core::IEditor*)),
            this, SLOT(updateEditorHistory()));
391
    m_d->m_view = new EditorView(m_d->m_editorModel, this);
mae's avatar
mae committed
392
    m_d->m_splitter = new SplitterOrView(m_d->m_view);
con's avatar
con committed
393

394
    m_d->m_stackedLayout = new QStackedLayout(this);
mae's avatar
mae committed
395
    m_d->m_stackedLayout->addWidget(m_d->m_splitter);
con's avatar
con committed
396
397
398
399
400
401
402
403
404

    updateActions();

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

EditorManager::~EditorManager()
{
    if (m_d->m_core) {
405
        ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
con's avatar
con committed
406
        if (m_d->m_coreListener) {
407
            pm->removeObject(m_d->m_coreListener);
con's avatar
con committed
408
409
            delete m_d->m_coreListener;
        }
410
        pm->removeObject(m_d->m_openEditorsFactory);
con's avatar
con committed
411
412
413
414
415
416
417
418
419
420
421
        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);
422
423
    
    pluginManager()->addObject(m_d->m_coreListener);
con's avatar
con committed
424
425

    m_d->m_openEditorsFactory = new OpenEditorsViewFactory();
426
    pluginManager()->addObject(m_d->m_openEditorsFactory);
con's avatar
con committed
427
428
429
430
431
432
433
}

QSize EditorManager::minimumSizeHint() const
{
    return QSize(400, 300);
}

Roberto Raggi's avatar
Roberto Raggi committed
434
435
436
437
438
439
440
441
442
443
444
445
446
447
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
448
449
450
451
452
453
454
455
456
457
458
459
void EditorManager::updateEditorHistory()
{
    IEditor *editor = currentEditor();
    if (!editor)
        return;
    m_d->m_editorHistory.removeAll(editor);
    m_d->m_editorHistory.prepend(editor);
}

bool EditorManager::registerEditor(IEditor *editor)
{
    if (editor) {
460
        m_d->m_editorModel->addEditor(editor);
461
462
463
        m_d->m_core->fileManager()->addFile(editor->file());
        m_d->m_core->fileManager()->addToRecentFiles(editor->file()->fileName());

con's avatar
con committed
464
465
466
467
468
469
470
471
472
473
        m_d->m_editorHistory.removeAll(editor);
        m_d->m_editorHistory.prepend(editor);
        return true;
    }
    return false;
}

bool EditorManager::unregisterEditor(IEditor *editor)
{
    if (editor) {
474
        m_d->m_editorModel->removeEditor(editor);
475
        m_d->m_core->fileManager()->removeFile(editor->file());
con's avatar
con committed
476
477
478
479
480
481
482
483
484
485
486
        m_d->m_editorHistory.removeAll(editor);
        return true;
    }
    return false;
}

void EditorManager::updateCurrentEditorAndGroup(IContext *context)
{
    if (debugEditorManager)
        qDebug() << Q_FUNC_INFO;
    IEditor *editor = context ? qobject_cast<IEditor*>(context) : 0;
487
    if (editor) {
con's avatar
con committed
488
489
490
491
492
493
494
495
        setCurrentEditor(editor);
    } else {
        updateActions();
    }
    if (debugEditorManager)
        qDebug() << "leaving method" << Q_FUNC_INFO;
}

496
497
498
499
500
501
502
IEditor *EditorManager::activateEditor(IEditor *editor, bool ignoreNavigationHistory)
{
    if (m_d->m_suppressEditorChanges)
        return editor;
    return activateEditor(m_d->m_splitter->findView(m_d->m_currentEditor)->view(), editor, ignoreNavigationHistory);
}

con's avatar
con committed
503
504
505
506
507
508
509
510
void EditorManager::setCurrentEditor(IEditor *editor, bool ignoreNavigationHistory)
{
    if (debugEditorManager)
        qDebug() << Q_FUNC_INFO << currentEditor() << "-->" << editor
                << (m_d->m_suppressEditorChanges?"suppressed":"")
                << "ignore history?" << ignoreNavigationHistory;
    if (m_d->m_suppressEditorChanges)
        return;
mae's avatar
mae committed
511
    m_d->m_currentEditor = editor;
con's avatar
con committed
512
    if (editor) {
513
        qDebug() << "EditorManager::setCurrentEditor" << editor << editor->file()->fileName();
con's avatar
con committed
514
515
516
517
518
519
        bool addToHistory = (!ignoreNavigationHistory && editor != currentEditor());
        if (debugEditorManager)
            qDebug() << Q_FUNC_INFO << (addToHistory ? "adding to history" : "not adding to history");
        if (addToHistory)
            addCurrentPositionToNavigationHistory(true);
        m_d->m_suppressEditorChanges = true;
520
521
522
523
524
525

        EditorView *view = m_d->m_splitter->findView(editor)->view();
        if (view == m_d->m_view && m_d->m_splitter)
            unsplitAll();
        view->setCurrentEditor(editor);

con's avatar
con committed
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
        m_d->m_suppressEditorChanges = false;
        if (addToHistory)
            addCurrentPositionToNavigationHistory();
    }
    editorChanged(editor);
}

void EditorManager::editorChanged(IEditor *toEditor)
{
    emit currentEditorChanged(toEditor);
}

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
551
    return m_d->m_currentEditor;
con's avatar
con committed
552
553
554
555
556
557
558
559
560
561
562
563
564
}


// 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()
{
    static bool postpone = true;
    if (postpone) {
        QTimer::singleShot(0, this, SLOT(closeEditor()));
        postpone = false;
    } else {
565
        closeEditor(m_d->m_splitter->findView(m_d->m_currentEditor)->view(), m_d->m_currentEditor);
con's avatar
con committed
566
567
568
569
570
        postpone = true;
    }

}

571
void EditorManager::closeEditor(Core::Internal::EditorView *view, Core::IEditor *editor)
con's avatar
con committed
572
{
573
    if (!editor || !view)
con's avatar
con committed
574
        return;
mae's avatar
mae committed
575

576
577
    Q_ASSERT(view->hasEditor(editor));
    if (view == m_d->m_view) {
mae's avatar
mae committed
578
579
        closeEditors(QList<IEditor *>() << editor);
    } else {
580
581
        view->removeEditor(editor);
        closeDuplicate(editor, true);
mae's avatar
mae committed
582
583
584
    }


con's avatar
con committed
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
}

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();
}

QList<IFile *>
        EditorManager::filesForEditors(QList<IEditor *> editors) const
{
    QSet<IEditor *> handledEditors;
    QList<IFile *> files;
    foreach (IEditor *editor, editors) {
        if (!handledEditors.contains(editor)) {
            files << editor->file();
610
            handledEditors.insert(editor);
con's avatar
con committed
611
612
613
614
615
616
617
        }
    }
    return files;
}

bool EditorManager::closeAllEditors(bool askAboutModifiedEditors)
{
mae's avatar
mae committed
618
    unsplitAll();
con's avatar
con committed
619
620
621
622
623
624
625
626
627
628
629
    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 =
630
        pluginManager()->getObjects<ICoreListener>();
con's avatar
con committed
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
    foreach (IEditor *editor, editorsToClose) {
        bool editorAccepted = true;
        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;
648
        QList<IFile*> list = ICore::instance()->fileManager()->
con's avatar
con committed
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
            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;
    bool currentEditorRemoved = false;
    IEditor *current = currentEditor();
    if (current)
        addCurrentPositionToNavigationHistory(true);
    // remove current editor last, for optimization
    if (acceptedEditors.contains(current)) {
        currentEditorRemoved = true;
        acceptedEditors.removeAll(current);
        acceptedEditors.append(current);
    }
    // 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));
        }
        unregisterEditor(editor);
        m_d->m_core->removeContextObject(editor);
        const bool suppress = m_d->m_suppressEditorChanges;
        m_d->m_suppressEditorChanges = true;
682
        m_d->m_view->removeEditor(editor);
con's avatar
con committed
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
        m_d->m_suppressEditorChanges = suppress;
    }
    emit editorsClosed(acceptedEditors);
    foreach (IEditor *editor, acceptedEditors) {
        delete editor;
    }
    if (currentEditorRemoved) {
        if (m_d->m_editorHistory.count() > 0) {
            setCurrentEditor(m_d->m_editorHistory.first(), true);
        } else {
            editorChanged(currentEditor());
        }
    }
    if (currentEditor())
        addCurrentPositionToNavigationHistory();
    updateActions();

    return !closingFailed;
}

mae's avatar
mae committed
703
704
void EditorManager::closeDuplicate(Core::IEditor *editor, bool doDelete)
{
705
    m_d->m_editorHistory.removeAll(editor);
mae's avatar
mae committed
706
    emit editorAboutToClose(editor);
707
    emit editorsClosed(QList<Core::IEditor *>() << editor);
mae's avatar
mae committed
708
709
710
    if (doDelete)
        delete editor;
}
con's avatar
con committed
711

712
Core::IEditor *EditorManager::activateEditor(Core::Internal::EditorView *view, Core::IEditor *editor, bool ignoreNavigationHistory)
mae's avatar
mae committed
713
714
715
716
717
718
719
720
721
722
723
{
    Q_ASSERT(view && editor);
    Q_ASSERT(m_d->m_view->hasEditor(editor));

    if (!editor->duplicateSupported()) {
        unsplitAll();
        view = m_d->m_view;
    }

    if (view == m_d->m_view || view->hasEditor(editor)) {
        view->setCurrentEditor(editor);
724
        return editor;
mae's avatar
mae committed
725
726
727
728
    }
    QList<IEditor*> editors = view->editors();
    IEditor *duplicate = duplicateEditor(editor);
    view->addEditor(duplicate);
729
    view->setCurrentEditor(duplicate, ignoreNavigationHistory);
mae's avatar
mae committed
730
731
732
733
    foreach(IEditor *e, editors) {
        view->removeEditor(e);
        closeDuplicate(e, true);
    }
734
    return duplicate;
mae's avatar
mae committed
735
736
}

con's avatar
con committed
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
/* 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;
775
    const EditorFactoryList allFactories = pluginManager()->getObjects<IEditorFactory>();
con's avatar
con committed
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
    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
802
        const EditorFactoryList allFactories = pluginManager()->getObjects<IEditorFactory>();
con's avatar
con committed
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
        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;
}

void EditorManager::insertEditor(IEditor *editor,
826
                                 bool /*ignoreNavigationHistory*/)
con's avatar
con committed
827
828
829
830
831
{
    if (!editor)
        return;
    m_d->m_core->addContextObject(editor);
    registerEditor(editor);
832
    m_d->m_view->addEditor(editor);
con's avatar
con committed
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
    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,
                                   bool ignoreNavigationHistory)
{
    if (debugEditorManager)
        qDebug() << Q_FUNC_INFO << fileName << editorKind;

    if (fileName.isEmpty())
        return 0;

    const QList<IEditor *> editors = editorsForFileName(fileName);
    if (!editors.isEmpty()) {
909
        return activateEditor(m_d->m_splitter->findView(m_d->m_currentEditor)->view(), editors.first(), ignoreNavigationHistory);
con's avatar
con committed
910
911
912
913
914
915
916
917
918
919
920
921
922
923
    }
    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;
    }
    insertEditor(editor, ignoreNavigationHistory);
    restoreEditorState(editor);
    QApplication::restoreOverrideCursor();
    ensureEditorManagerVisible();
924
    return activateEditor(editor, ignoreNavigationHistory);
con's avatar
con committed
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
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
}

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()
{
    if (!isVisible()) {
        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);
    insertEditor(edt);
    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
1016
    QTC_ASSERT(editor, return);
con's avatar
con committed
1017
    QString fileName = editor->file()->fileName();
hjk's avatar
hjk committed
1018
    if (m_d->m_editorStates.contains(fileName))
con's avatar
con committed
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
        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;
}

1057
1058
1059
1060
1061
EditorManager::ReadOnlyAction
    EditorManager::promptReadOnlyFile(const QString &fileName,
                                      const IVersionControl *versionControl,
                                      QWidget *parent,
                                      bool displaySaveAsButton)
con's avatar
con committed
1062
1063
1064
1065
1066
1067
{
    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;
1068
1069
1070
    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
1071
    QPushButton *makeWritableButton =  msgBox.addButton(QObject::tr("Make writable"), QMessageBox::AcceptRole);
1072
1073
1074
1075
1076
1077

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

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

con's avatar
con committed
1080
1081
    QAbstractButton *clickedButton = msgBox.clickedButton();
    if (clickedButton == sccButton)
1082
        return RO_OpenVCS;
con's avatar
con committed
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
    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();

1099
1100
    switch (promptReadOnlyFile(fileName, versionControl, m_d->m_core->mainWindow(), true)) {
    case RO_OpenVCS:
con's avatar
con committed
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
        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
1143
    if (success)
con's avatar
con committed
1144
1145
1146
1147
1148
1149
1150
1151
1152
        m_d->m_core->fileManager()->addToRecentFiles(editor->file()->fileName());

    updateActions();
    return success;
}

void EditorManager::gotoNextDocHistory()
{
    OpenEditorsWindow *dialog = windowPopup();
1153
1154
1155
1156
1157
1158
1159
    if (dialog->isVisible()) {
        dialog->selectNextEditor();
    } else {
        dialog->setEditors(m_d->m_editorHistory, m_d->m_currentEditor);
        dialog->selectNextEditor();
        showWindowPopup();
    }
con's avatar
con committed
1160
1161
1162
1163
1164
}

void EditorManager::gotoPreviousDocHistory()
{
    OpenEditorsWindow *dialog = windowPopup();
1165
1166
1167
1168
1169
1170
1171
    if (dialog->isVisible()) {
        dialog->selectPreviousEditor();
    } else {
        dialog->setEditors(m_d->m_editorHistory, m_d->m_currentEditor);
        dialog->selectPreviousEditor();
        showWindowPopup();
    }
con's avatar
con committed
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
}

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));


1214
    m_d->m_closeCurrentEditorAction->setEnabled(curEditor != 0);
con's avatar
con committed
1215
1216
1217
1218
1219
1220
1221
1222
    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);

1223
    m_d->m_openInExternalEditorAction->setEnabled(curEditor != 0);
con's avatar
con committed
1224
1225
1226
1227
}

QList<IEditor*> EditorManager::openedEditors() const
{
1228
    return m_d->m_view->editors();
con's avatar
con committed
1229
1230
}

1231
Internal::EditorModel *EditorManager::openedEditorsModel() const
con's avatar
con committed
1232
{
1233
    return m_d->m_editorModel;
con's avatar
con committed
1234
1235
}

1236

con's avatar
con committed
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
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
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
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
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;
    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;
        }
    } 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();
}

void EditorManager::goBackInNavigationHistory()
{
    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;
            setCurrentEditor(location->editor, true);
        } else {
            editor = openEditor(location->fileName, location->kind, true);
            if (!editor) {
                delete m_d->m_navigationHistory.takeAt(m_d->currentNavigationHistoryPosition);
                continue;
            }
        }
        editor->restoreState(location->state.toByteArray());
        updateActions();
        ensureEditorManagerVisible();
        return;
    }
}

void EditorManager::goForwardInNavigationHistory()
{
    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;
        setCurrentEditor(location->editor, true);
    } else {
        editor = openEditor(location->fileName, location->kind, true);
        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);
1344
1345
1346
1347

    qDebug() << "saveState";
    stream << QByteArray("EditorManagerV1");

con's avatar
con committed
1348
    stream << m_d->m_editorStates;
1349

mae's avatar
mae committed
1350
    QList<IEditor *> editors = openedEditors();
1351
1352
    int editorCount = editors.count();

mae's avatar
mae committed
1353
1354
1355
1356
1357
    if (editors.contains(m_d->m_currentEditor)) {
        editors.removeAll(m_d->m_currentEditor);
        editors.prepend(m_d->m_currentEditor);
    }

1358
1359
1360
1361
1362
1363
1364
    qDebug() << "save editors:" << editorCount;

    stream << editorCount;
    foreach (IEditor *editor, editors) {
        stream << editor->file()->fileName() << QByteArray(editor->kind());
    }

con's avatar
con committed
1365
1366
1367
1368
1369
1370
1371
    return bytes;
}

bool EditorManager::restoreState(const QByteArray &state)
{
    closeAllEditors(true);
    QDataStream stream(state);
1372
1373
1374
1375
1376

    QByteArray version;
    stream >> version;

    if (version != "EditorManagerV1")
con's avatar
con committed
1377
1378
        return false;

1379
1380
    QMap<QString, QVariant> editorstates;

1381
1382
    QApplication::setOverrideCursor(Qt::WaitCursor);

con's avatar
con committed
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
    bool editorChangesSuppressed = m_d->m_suppressEditorChanges;
    m_d->m_suppressEditorChanges = true;

    stream >> editorstates;
    QMapIterator<QString, QVariant> i(editorstates);
    while (i.hasNext()) {
        i.next();
        m_d->m_editorStates.insert(i.key(), i.value());
    }

1393
1394
1395
1396
1397
1398
1399
    int editorCount = 0;
    stream >> editorCount;
    while (--editorCount >= 0) {
        QString fileName;
        stream >> fileName;
        QByteArray kind;
        stream >> kind;
mae's avatar
mae committed
1400
1401
1402
        IEditor *editor = openEditor(fileName, kind, true);
        if (!m_d->m_currentEditor)
            m_d->m_currentEditor = editor;
1403
1404
    }

con's avatar
con committed
1405
1406
    m_d->m_suppressEditorChanges = editorChangesSuppressed;
    if (currentEditor())
mae's avatar
mae committed
1407
        setCurrentEditor(m_d->m_currentEditor);
1408
1409
    
    QApplication::restoreOverrideCursor();
con's avatar
con committed
1410
1411
1412
1413
1414
1415
1416
1417

    return true;
}

void EditorManager::saveSettings(QSettings *settings)
{
    settings->setValue(QLatin1String("EditorManager/DocumentStates"),
                       m_d->m_editorStates);
1418
    settings->setValue(QLatin1String("EditorManager/ExternalEditorCommand"),
con's avatar
con committed
1419
1420
1421
1422
1423
1424
1425
1426
                       m_d->m_externalEditor);
}

void EditorManager::readSettings(QSettings *settings)
{
    if (settings->contains(QLatin1String("EditorManager/DocumentStates")))
        m_d->m_editorStates = settings->value(QLatin1String("EditorManager/DocumentStates"))
            .value<QMap<QString, QVariant> >();
1427
    if (settings->contains(QLatin1String("EditorManager/ExternalEditorCommand")))
1428
        m_d->m_externalEditor = settings->value(QLatin1String("EditorManager/ExternalEditorCommand")).toString();
con's avatar
con committed
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
}


void EditorManager::revertToSaved()
{
    IEditor *currEditor = currentEditor();
    if (!currEditor)
        return;
    const QString fileName =  currEditor->file()->fileName();
    if (fileName.isEmpty())
        return;
    if (currEditor->file()->isModified()) {
        QMessageBox msgBox(QMessageBox::Question, tr("Revert to Saved"),
                           tr("You will lose your current changes if you proceed reverting %1.").arg(fileName),
                           QMessageBox::Yes|QMessageBox::No, m_d->m_core->mainWindow());
        msgBox.button(QMessageBox::Yes)->setText(tr("Proceed"));
        msgBox.button(QMessageBox::No)->setText(tr("Cancel"));
        msgBox.setDefaultButton(QMessageBox::No);
        msgBox.setEscapeButton(QMessageBox::No);
        if (msgBox.exec() == QMessageBox::No)
            return;

    }
    IFile::ReloadBehavior temp = IFile::ReloadAll;
    currEditor->file()->modified(&temp);
}


void EditorManager::showEditorInfoBar(const QString &kind,
                                      const QString &infoText,
                                      const QString &buttonText,
                                      QObject *object, const char *member)
{
1462
    m_d->m_view->showEditorInfoBar(kind, infoText, buttonText, object, member);
con's avatar
con committed
1463
1464
1465
1466
1467
}


void EditorManager::hideEditorInfoBar(const QString &kind)
{
1468
    m_d->m_view->hideEditorInfoBar(kind);
con's avatar
con committed
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
}

QString EditorManager::externalEditorHelpText() const
{
    QString help = tr(
            "<table border=1 cellspacing=0 cellpadding=3>"
            "<tr><th>Variable</th><th>Expands to</th></tr>"
            "<tr><td>%f</td><td>file name</td></tr>"
            "<tr><td>%l</td><td>current line number</td></tr>"
            "<tr><td>%c</td><td>current column number</td></tr>"
            "<tr><td>%x</td><td>editor's x position on screen</td></tr>"
            "<tr><td>%y</td><td>editor's y position on screen</td></tr>"
            "<tr><td>%w</td><td>editor's width in pixels</td></tr>"
            "<tr><td>%h</td><td>editor's height in pixels</td></tr>"
            "<tr><td>%W</td><td>editor's width in characters</td></tr>"
            "<tr><td>%H</td><td>editor's height in characters</td></tr>"
            "<tr><td>%%</td><td>%</td></tr>"
            "</table>");
    return help;
}

void EditorManager::openInExternalEditor()
{
1492
1493
1494
1495
1496
    QString command = m_d->m_externalEditor;
    if (command.isEmpty())
        command = defaultExternalEditor();

    if (command.isEmpty())
1497
1498
        return;

con's avatar
con committed
1499
1500
1501
1502
1503
    IEditor *editor = currentEditor();
    if (!editor)
        return;
    if (editor->file()->isModified()) {
        bool cancelled = false;
1504
        QList<IFile*> list = ICore::instance()->fileManager()->
con's avatar
con committed
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
                             saveModifiedFiles(QList<IFile*>() << editor->file(), &cancelled);
        if (cancelled)
            return;
    }

    QRect rect = editor->widget()->rect();
    QFont font = editor->widget()->font();
    QFontMetrics fm(font);
    rect.moveTo(editor->widget()->mapToGlobal(QPoint(0,0)));

1515
    QString pre = command;
con's avatar
con committed
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
    QString cmd;
    for (int i = 0; i < pre.size(); ++i) {
        QChar c = pre.at(i);
        if (c == QLatin1Char('%') && i < pre.size()-1) {
            c = pre.at(++i);
            QString s;
            if (c == QLatin1Char('f'))
                s = editor->file()->fileName();
            else if (c == QLatin1Char('l'))
                s = QString::number(editor->currentLine());
            else if (c == QLatin1Char('c'))
                s = QString::number(editor->currentColumn());
            else if (c == QLatin1Char('x'))
                s = QString::number(rect.x());
            else if (c == QLatin1Char('y'))
                s = QString::number(rect.y());
            else if (c == QLatin1Char('w'))
                s = QString::number(rect.width());
            else if (c == QLatin1Char('h'))
                s = QString::number(rect.height());
            else if (c == QLatin1Char('W'))
                s = QString::number(rect.width() / fm.width(QLatin1Char('x')));
            else if (c == QLatin1Char('H'))
                s = QString::number(rect.height() / fm.lineSpacing());
            else if (c == QLatin1Char('%'))
                s = c;
            else {
                s = QLatin1Char('%');
                cmd += c;
            }
            cmd += s;
            continue;

        }
        cmd += c;
    }

    QProcess::startDetached(cmd);
}

void EditorManager::setExternalEditor(const QString &editor)
{
1558
1559
1560
1561
    if (editor.isEmpty() || editor == defaultExternalEditor())
        m_d->m_externalEditor = defaultExternalEditor();
    else
        m_d->m_externalEditor = editor;
con's avatar
con committed
1562
1563
1564
1565
}

QString EditorManager::externalEditor() const
{
1566
1567
    if (m_d->m_externalEditor.isEmpty())
        return defaultExternalEditor();
con's avatar
con committed
1568
1569
1570
    return m_d->m_externalEditor;
}

1571

mae's avatar
mae committed
1572
1573
1574
1575
1576
1577
Core::IEditor *EditorManager::duplicateEditor(Core::IEditor *editor)
{
    if (!editor->duplicateSupported())
        return 0;

    IEditor *duplicate = editor->duplicate(0);
mae's avatar
mae committed
1578
1579
    emit editorCreated(duplicate, duplicate->file()->fileName());
    emit editorOpened(duplicate);
mae's avatar
mae committed
1580
1581
1582
    return duplicate;
}

1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
void EditorManager::split(Qt::Orientation orientation)
{
    SplitterOrView *view = m_d->m_currentEditor ? m_d->m_splitter->findView(m_d->m_currentEditor)
                       : m_d->m_splitter->findFirstView();
    if (!view) {
        view = m_d->m_splitter;
        view->unsplit(0);
    }
    view->split(orientation);
}
1593
1594
void EditorManager::split()
{
1595
    split(Qt::Vertical);
1596
1597
1598
1599
}

void EditorManager::splitSideBySide()
{
1600
    split(Qt::Horizontal);
1601
1602
1603
1604
}

void EditorManager::unsplit()
{
1605
1606
1607
1608
1609
    qDebug() << "unsplit" << (m_d->m_currentEditor ? m_d->m_currentEditor->file()->fileName() : QString("no current editor"));
    SplitterOrView *splitter = m_d->m_currentEditor ? m_d->m_splitter->findSplitter(m_d->m_currentEditor) : m_d->m_splitter;
    qDebug() << "splitter" << splitter;
    if (splitter)
        splitter->unsplit(m_d->m_currentEditor);
mae's avatar
mae committed
1610
1611
1612
1613
1614
1615
1616
}

void EditorManager::unsplitAll()
{
    m_d->m_splitter->unsplit(0);
    if (IEditor *e = m_d->m_splitter->editor())
        setCurrentEditor(e);
1617
1618
}

1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
void EditorManager::gotoOtherWindow()
{
    qDebug() << "gotoOtherWindow";
    if (!m_d->m_currentEditor)
        return;
    qDebug() << "current editor" << m_d->m_currentEditor->file()->fileName();
    if (m_d->m_splitter->isSplitter()) {
        qDebug() << "we have a splitter";
        SplitterOrView *view = m_d->m_splitter->findNextView(m_d->m_currentEditor);
        qDebug() << "next view is" << view;
        if (!view)
            view = m_d->m_splitter->findFirstView();
        if (view) {
            if (IEditor *editor = view->editor()) {
                qDebug() << "set new current editor to" << editor->file()->fileName();
                view->view()->setCurrentEditor(editor);
            }
        }
    }
}
con's avatar
con committed
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
//===================EditorClosingCoreListener======================

EditorClosingCoreListener::EditorClosingCoreListener(EditorManager *em)
        : m_em(em)
{
}

bool EditorClosingCoreListener::editorAboutToClose(IEditor *)
{
    return true;
}

bool EditorClosingCoreListener::coreAboutToClose()
{
    // Do not ask for files to save.
    // MainWindow::closeEvent has already done that.
    return m_em->closeAllEditors(false);
}