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

30
#include "documentmanager.h"
hjk's avatar
hjk committed
31

32 33
#include "editormanager.h"
#include "icore.h"
34 35 36
#include "ieditor.h"
#include "ieditorfactory.h"
#include "iexternaleditor.h"
37
#include "idocument.h"
38
#include "mimedatabase.h"
con's avatar
con committed
39
#include "saveitemsdialog.h"
40
#include "coreconstants.h"
con's avatar
con committed
41

42 43
#include "dialogs/readonlyfilesdialog.h"

44
#include <utils/hostosinfo.h>
hjk's avatar
hjk committed
45
#include <utils/qtcassert.h>
46
#include <utils/pathchooser.h>
47
#include <utils/reloadpromptutils.h>
hjk's avatar
hjk committed
48

49
#include <QStringList>
50 51 52 53 54 55 56 57 58 59 60 61
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QFileSystemWatcher>
#include <QSettings>
#include <QTimer>
#include <QAction>
#include <QFileDialog>
#include <QMainWindow>
#include <QMenu>
#include <QMessageBox>
con's avatar
con committed
62 63

/*!
64
  \class Core::DocumentManager
con's avatar
con committed
65
  \mainclass
66 67
  \inheaderfile documentmanager.h
  \brief Manages a set of IDocument objects.
con's avatar
con committed
68

69 70 71
  The DocumentManager service monitors a set of IDocument's. Plugins should register
  files they work with at the service. The files the IDocument's point to will be
  monitored at filesystem level. If a file changes, the status of the IDocument's
con's avatar
con committed
72 73 74
  will be adjusted accordingly. Furthermore, on application exit the user will
  be asked to save all modified files.

75 76
  Different IDocument objects in the set can point to the same file in the
  filesystem. The monitoring for a IDocument can be blocked by blockFileChange(), and
con's avatar
con committed
77 78
  enabled again by unblockFileChange().

79
  The functions expectFileChange() and unexpectFileChange() mark a file change
80
  as expected. On expected file changes all IDocument objects are notified to reload
81 82
  themselves.

83
  The DocumentManager service also provides two convenience methods for saving
con's avatar
con committed
84 85 86 87 88 89 90 91
  files: saveModifiedFiles() and saveModifiedFilesSilently(). Both take a list
  of FileInterfaces as an argument, and return the list of files which were
  _not_ saved.

  The service also manages the list of recent files to be shown to the user
  (see addToRecentFiles() and recentFiles()).
 */

92 93 94
static const char settingsGroupC[] = "RecentFiles";
static const char filesKeyC[] = "Files";
static const char editorsKeyC[] = "EditorIds";
95

96 97 98
static const char directoryGroupC[] = "Directories";
static const char projectDirectoryKeyC[] = "Projects";
static const char useProjectDirectoryKeyC[] = "UseProjectsDirectory";
99
static const char buildDirectoryKeyC[] = "BuildDirectory.Template";
100

101
namespace Core {
102 103 104

static void readSettings();

105
static QList<IDocument *> saveModifiedFilesHelper(const QList<IDocument *> &documents,
106 107 108 109 110
                               bool *cancelled, bool silently,
                               const QString &message,
                               const QString &alwaysSaveMessage = QString(),
                               bool *alwaysSave = 0);

111 112
namespace Internal {

113 114 115 116 117 118 119 120
struct OpenWithEntry
{
    OpenWithEntry() : editorFactory(0), externalEditor(0) {}
    IEditorFactory *editorFactory;
    IExternalEditor *externalEditor;
    QString fileName;
};

121
struct FileStateItem
122 123 124 125 126
{
    QDateTime modified;
    QFile::Permissions permissions;
};

127 128
struct FileState
{
129
    QMap<IDocument *, FileStateItem> lastUpdatedState;
130 131 132
    FileStateItem expected;
};

dt's avatar
dt committed
133

134
struct DocumentManagerPrivate
135
{
136
    explicit DocumentManagerPrivate(QMainWindow *mw);
137 138
    QFileSystemWatcher *fileWatcher();
    QFileSystemWatcher *linkWatcher();
139

dt's avatar
dt committed
140
    QMap<QString, FileState> m_states;
141
    QSet<QString> m_changedFiles;
142 143
    QList<IDocument *> m_documentsWithoutWatch;
    QMap<IDocument *, QStringList> m_documentsWithWatch;
144
    QSet<QString> m_expectedFileNames;
145

146
    QList<DocumentManager::RecentFile> m_recentFiles;
147 148 149 150 151
    static const int m_maxRecentFiles = 7;

    QString m_currentFile;

    QMainWindow *m_mainWindow;
152
    QFileSystemWatcher *m_fileWatcher; // Delayed creation.
153
    QFileSystemWatcher *m_linkWatcher; // Delayed creation (only UNIX/if a link is seen).
154
    bool m_blockActivated;
155 156 157
    QString m_lastVisitedDirectory;
    QString m_projectsDirectory;
    bool m_useProjectsDirectory;
158
    QString m_buildDirectory;
159
    // When we are callling into a IDocument
dt's avatar
dt committed
160 161 162
    // we don't want to receive a changed()
    // signal
    // That makes the code easier
163
    IDocument *m_blockedIDocument;
164 165
};

166 167
static DocumentManager *m_instance;
static Internal::DocumentManagerPrivate *d;
168

169
QFileSystemWatcher *DocumentManagerPrivate::fileWatcher()
170 171
{
    if (!m_fileWatcher) {
172
        m_fileWatcher= new QFileSystemWatcher(m_instance);
173 174 175
        QObject::connect(m_fileWatcher, SIGNAL(fileChanged(QString)),
                         m_instance, SLOT(changedFile(QString)));
    }
176
    return m_fileWatcher;
177 178
}

179
QFileSystemWatcher *DocumentManagerPrivate::linkWatcher()
180
{
181 182 183 184 185 186 187 188
    if (Utils::HostOsInfo::isAnyUnixHost()) {
        if (!m_linkWatcher) {
            m_linkWatcher = new QFileSystemWatcher(m_instance);
            m_linkWatcher->setObjectName(QLatin1String("_qt_autotest_force_engine_poller"));
            QObject::connect(m_linkWatcher, SIGNAL(fileChanged(QString)),
                             m_instance, SLOT(changedFile(QString)));
        }
        return m_linkWatcher;
189
    }
190

191
    return fileWatcher();
192 193
}

194
DocumentManagerPrivate::DocumentManagerPrivate(QMainWindow *mw) :
con's avatar
con committed
195
    m_mainWindow(mw),
196 197
    m_fileWatcher(0),
    m_linkWatcher(0),
198 199
    m_blockActivated(false),
    m_lastVisitedDirectory(QDir::currentPath()),
200
    m_useProjectsDirectory(Utils::HostOsInfo::isMacHost()), // Creator is in bizarre places when launched via finder.
201
    m_blockedIDocument(0)
con's avatar
con committed
202
{
203 204 205
}

} // namespace Internal
206 207 208 209 210
} // namespace Core

Q_DECLARE_METATYPE(Core::Internal::OpenWithEntry)

namespace Core {
211

212 213
using namespace Internal;

214
DocumentManager::DocumentManager(QMainWindow *mw)
215
  : QObject(mw)
216
{
217
    d = new DocumentManagerPrivate(mw);
218
    m_instance = this;
219
    connect(d->m_mainWindow, SIGNAL(windowActivated()),
con's avatar
con committed
220
        this, SLOT(mainWindowActivated()));
hjk's avatar
hjk committed
221
    connect(ICore::instance(), SIGNAL(contextChanged(Core::IContext*,Core::Context)),
con's avatar
con committed
222 223
        this, SLOT(syncWithEditor(Core::IContext*)));

224
    readSettings();
con's avatar
con committed
225 226
}

227
DocumentManager::~DocumentManager()
228 229 230 231
{
    delete d;
}

232
DocumentManager *DocumentManager::instance()
233
{
234 235 236
    return m_instance;
}

237 238
/* only called from addFileInfo(IDocument *) */
static void addFileInfo(const QString &fileName, IDocument *document, bool isLink)
239 240 241 242 243 244 245
{
    FileStateItem state;
    if (!fileName.isEmpty()) {
        const QFileInfo fi(fileName);
        state.modified = fi.lastModified();
        state.permissions = fi.permissions();
        // Add watcher if we don't have that already
246
        if (!d->m_states.contains(fileName))
247 248 249 250 251 252 253 254 255 256
            d->m_states.insert(fileName, FileState());

        QFileSystemWatcher *watcher = 0;
        if (isLink)
            watcher = d->linkWatcher();
        else
            watcher = d->fileWatcher();
        if (!watcher->files().contains(fileName))
            watcher->addPath(fileName);

257
        d->m_states[fileName].lastUpdatedState.insert(document, state);
258
    }
259
    d->m_documentsWithWatch[document].append(fileName); // inserts a new QStringList if not already there
260 261
}

262
/* Adds the IDocument's file and possibly it's final link target to both m_states
263 264 265
   (if it's file name is not empty), and the m_filesWithWatch list,
   and adds a file watcher for each if not already done.
   (The added file names are guaranteed to be absolute and cleaned.) */
266
static void addFileInfo(IDocument *document)
267
{
268 269 270
    const QString fixedName = DocumentManager::fixFileName(document->fileName(), DocumentManager::KeepLinks);
    const QString fixedResolvedName = DocumentManager::fixFileName(document->fileName(), DocumentManager::ResolveLinks);
    addFileInfo(fixedResolvedName, document, false);
271
    if (fixedName != fixedResolvedName)
272
        addFileInfo(fixedName, document, true);
273 274
}

con's avatar
con committed
275
/*!
276
    \fn bool DocumentManager::addFiles(const QList<IDocument *> &documents, bool addWatcher)
con's avatar
con committed
277

278
    Adds a list of IDocument's to the collection. If \a addWatcher is true (the default),
con's avatar
con committed
279 280
    the files are added to a file system watcher that notifies the file manager
    about file changes.
con's avatar
con committed
281
*/
282
void DocumentManager::addDocuments(const QList<IDocument *> &documents, bool addWatcher)
con's avatar
con committed
283
{
dt's avatar
dt committed
284 285 286
    if (!addWatcher) {
        // We keep those in a separate list

287 288
        foreach (IDocument *document, documents) {
            if (document && !d->m_documentsWithoutWatch.contains(document)) {
Robert Loehning's avatar
Robert Loehning committed
289
                connect(document, SIGNAL(destroyed(QObject*)), m_instance, SLOT(documentDestroyed(QObject*)));
Robert Loehning's avatar
Robert Loehning committed
290
                connect(document, SIGNAL(fileNameChanged(QString,QString)), m_instance, SLOT(fileNameChanged(QString,QString)));
291
                d->m_documentsWithoutWatch.append(document);
292 293
            }
        }
con's avatar
con committed
294
        return;
dt's avatar
dt committed
295 296
    }

297 298 299
    foreach (IDocument *document, documents) {
        if (document && !d->m_documentsWithWatch.contains(document)) {
            connect(document, SIGNAL(changed()), m_instance, SLOT(checkForNewFileName()));
Robert Loehning's avatar
Robert Loehning committed
300
            connect(document, SIGNAL(destroyed(QObject*)), m_instance, SLOT(documentDestroyed(QObject*)));
Robert Loehning's avatar
Robert Loehning committed
301
            connect(document, SIGNAL(fileNameChanged(QString,QString)), m_instance, SLOT(fileNameChanged(QString,QString)));
302
            addFileInfo(document);
303
        }
con's avatar
con committed
304 305 306
    }
}

307

308 309
/* Removes all occurrences of the IDocument from m_filesWithWatch and m_states.
   If that results in a file no longer being referenced by any IDocument, this
310 311
   also removes the file watcher.
*/
312
static void removeFileInfo(IDocument *document)
313
{
314
    if (!d->m_documentsWithWatch.contains(document))
315
        return;
316
    foreach (const QString &fileName, d->m_documentsWithWatch.value(document)) {
317 318
        if (!d->m_states.contains(fileName))
            continue;
319
        d->m_states[fileName].lastUpdatedState.remove(document);
320 321 322 323 324 325
        if (d->m_states.value(fileName).lastUpdatedState.isEmpty()) {
            if (d->m_fileWatcher && d->m_fileWatcher->files().contains(fileName))
                d->m_fileWatcher->removePath(fileName);
            if (d->m_linkWatcher && d->m_linkWatcher->files().contains(fileName))
                d->m_linkWatcher->removePath(fileName);
            d->m_states.remove(fileName);
326
        }
327
    }
328
    d->m_documentsWithWatch.remove(document);
329 330
}

dt's avatar
dt committed
331 332
/// Dumps the state of the file manager's map
/// For debugging purposes
333 334
/*
static void dump()
dt's avatar
dt committed
335
{
336
    qDebug() << "======== dumping state map";
337
    QMap<QString, FileState>::const_iterator it, end;
dt's avatar
dt committed
338 339 340 341
    it = d->m_states.constBegin();
    end = d->m_states.constEnd();
    for (; it != end; ++it) {
        qDebug() << it.key();
342
        qDebug() << "   expected:" << it.value().expected.modified;
dt's avatar
dt committed
343

344
        QMap<IDocument *, FileStateItem>::const_iterator jt, jend;
dt's avatar
dt committed
345 346 347
        jt = it.value().lastUpdatedState.constBegin();
        jend = it.value().lastUpdatedState.constEnd();
        for (; jt != jend; ++jt) {
348
            qDebug() << "  " << jt.key()->fileName() << jt.value().modified;
dt's avatar
dt committed
349 350
        }
    }
351
    qDebug() << "------- dumping files with watch list";
352
    foreach (IDocument *key, d->m_filesWithWatch.keys()) {
353 354 355
        qDebug() << key->fileName() << d->m_filesWithWatch.value(key);
    }
    qDebug() << "------- dumping watch list";
356 357
    if (d->m_fileWatcher)
        qDebug() << d->m_fileWatcher->files();
358
    qDebug() << "------- dumping link watch list";
359 360
    if (d->m_linkWatcher)
        qDebug() << d->m_linkWatcher->files();
dt's avatar
dt committed
361
}
362
*/
dt's avatar
dt committed
363

364
/*!
365
    \fn void DocumentManager::renamedFile(const QString &from, const QString &to)
366 367 368 369
    \brief Tells the file manager that a file has been renamed on disk from within Qt Creator.

    Needs to be called right after the actual renaming on disk (i.e. before the file system
    watcher can report the event during the next event loop run). \a from needs to be an absolute file path.
370 371
    This will notify all IDocument objects pointing to that file of the rename
    by calling IDocument::rename, and update the cached time and permission
372 373 374
    information to avoid annoying the user with "file has been removed"
    popups.
*/
375
void DocumentManager::renamedFile(const QString &from, const QString &to)
dt's avatar
dt committed
376
{
377
    const QString &fixedFrom = fixFileName(from, KeepLinks);
dt's avatar
dt committed
378

379 380 381
    // gather the list of IDocuments
    QList<IDocument *> documentsToRename;
    QMapIterator<IDocument *, QStringList> it(d->m_documentsWithWatch);
382 383 384
    while (it.hasNext()) {
        it.next();
        if (it.value().contains(fixedFrom))
385
            documentsToRename.append(it.key());
386 387
    }

388 389 390 391 392 393 394
    // rename the IDocuments
    foreach (IDocument *document, documentsToRename) {
        d->m_blockedIDocument = document;
        removeFileInfo(document);
        document->rename(to);
        addFileInfo(document);
        d->m_blockedIDocument = 0;
395
    }
396
    emit m_instance->allDocumentsRenamed(from, to);
397
}
398 399 400 401 402 403 404 405 406 407

void DocumentManager::fileNameChanged(const QString &oldName, const QString &newName)
{
    IDocument *doc = qobject_cast<IDocument *>(sender());
    QTC_ASSERT(doc, return);
    if (doc == d->m_blockedIDocument)
        return;
    emit m_instance->documentRenamed(doc, oldName, newName);
}

con's avatar
con committed
408
/*!
409
    \fn bool DocumentManager::addFile(IDocument *document, bool addWatcher)
con's avatar
con committed
410

411
    Adds a IDocument object to the collection. If \a addWatcher is true (the default),
con's avatar
con committed
412 413
    the file is added to a file system watcher that notifies the file manager
    about file changes.
con's avatar
con committed
414
*/
415
void DocumentManager::addDocument(IDocument *document, bool addWatcher)
con's avatar
con committed
416
{
417
    addDocuments(QList<IDocument *>() << document, addWatcher);
con's avatar
con committed
418 419
}

420
void DocumentManager::documentDestroyed(QObject *obj)
con's avatar
con committed
421
{
422
    IDocument *document = static_cast<IDocument*>(obj);
dt's avatar
dt committed
423
    // Check the special unwatched first:
424 425
    if (!d->m_documentsWithoutWatch.removeOne(document))
        removeFileInfo(document);
con's avatar
con committed
426 427 428
}

/*!
429
    \fn bool DocumentManager::removeFile(IDocument *document)
con's avatar
con committed
430

431
    Removes a IDocument object from the collection.
con's avatar
con committed
432

433
    Returns true if the file specified by \a document had the addWatcher argument to addDocument() set.
con's avatar
con committed
434
*/
435
bool DocumentManager::removeDocument(IDocument *document)
con's avatar
con committed
436
{
437
    QTC_ASSERT(document, return false);
con's avatar
con committed
438

439
    bool addWatcher = false;
dt's avatar
dt committed
440
    // Special casing unwatched files
441
    if (!d->m_documentsWithoutWatch.removeOne(document)) {
442
        addWatcher = true;
443 444
        removeFileInfo(document);
        disconnect(document, SIGNAL(changed()), m_instance, SLOT(checkForNewFileName()));
dt's avatar
dt committed
445
    }
Robert Loehning's avatar
Robert Loehning committed
446
    disconnect(document, SIGNAL(destroyed(QObject*)), m_instance, SLOT(documentDestroyed(QObject*)));
447
    return addWatcher;
con's avatar
con committed
448 449
}

450
/* Slot reacting on IDocument::changed. We need to check if the signal was sent
451
   because the file was saved under different name. */
452
void DocumentManager::checkForNewFileName()
con's avatar
con committed
453
{
454 455
    IDocument *document = qobject_cast<IDocument *>(sender());
    // We modified the IDocument
dt's avatar
dt committed
456
    // Trust the other code to also update the m_states map
457
    if (document == d->m_blockedIDocument)
dt's avatar
dt committed
458
        return;
459 460
    QTC_ASSERT(document, return);
    QTC_ASSERT(d->m_documentsWithWatch.contains(document), return);
461

462
    // Maybe the name has changed or file has been deleted and created again ...
463
    // This also updates the state to the on disk state
464 465
    removeFileInfo(document);
    addFileInfo(document);
con's avatar
con committed
466 467
}

468
/*!
469
    \fn QString DocumentManager::fixFileName(const QString &fileName, FixMode fixmode)
470 471 472 473
    Returns a guaranteed cleaned path in native form. If the file exists,
    it will either be a cleaned absolute file path (fixmode == KeepLinks), or
    a cleaned canonical file path (fixmode == ResolveLinks).
*/
474
QString DocumentManager::fixFileName(const QString &fileName, FixMode fixmode)
con's avatar
con committed
475 476
{
    QString s = fileName;
477
    QFileInfo fi(s);
478 479 480 481 482 483 484 485 486
    if (fi.exists()) {
        if (fixmode == ResolveLinks)
            s = fi.canonicalFilePath();
        else
            s = QDir::cleanPath(fi.absoluteFilePath());
    } else {
        s = QDir::cleanPath(s);
    }
    s = QDir::toNativeSeparators(s);
487 488
    if (Utils::HostOsInfo::isWindowsHost())
        s = s.toLower();
489
    return s;
con's avatar
con committed
490 491 492
}

/*!
493
    \fn QList<IDocument*> DocumentManager::modifiedFiles() const
con's avatar
con committed
494

495
    Returns the list of IDocument's that have been modified.
con's avatar
con committed
496
*/
497
QList<IDocument *> DocumentManager::modifiedDocuments()
con's avatar
con committed
498
{
499
    QList<IDocument *> modified;
con's avatar
con committed
500

501 502 503
    foreach (IDocument *document, d->m_documentsWithWatch.keys()) {
        if (document->isModified())
            modified << document;
con's avatar
con committed
504
    }
505

506 507 508
    foreach (IDocument *document, d->m_documentsWithoutWatch) {
        if (document->isModified())
            modified << document;
dt's avatar
dt committed
509 510
    }

511
    return modified;
con's avatar
con committed
512 513
}

514
/*!
515
    \fn void DocumentManager::expectFileChange(const QString &fileName)
516 517 518

    Any subsequent change to \a fileName is treated as a expected file change.

519
    \see DocumentManager::unexpectFileChange(const QString &fileName)
520
*/
521
void DocumentManager::expectFileChange(const QString &fileName)
con's avatar
con committed
522
{
523 524 525
    if (fileName.isEmpty())
        return;
    d->m_expectedFileNames.insert(fileName);
526 527
}

528 529 530 531 532 533 534 535 536 537 538 539
/* only called from unblock and unexpect file change methods */
static void updateExpectedState(const QString &fileName)
{
    if (fileName.isEmpty())
        return;
    if (d->m_states.contains(fileName)) {
        QFileInfo fi(fileName);
        d->m_states[fileName].expected.modified = fi.lastModified();
        d->m_states[fileName].expected.permissions = fi.permissions();
    }
}

540
/*!
541
    \fn void DocumentManager::unexpectFileChange(const QString &fileName)
542 543 544

    Any change to \a fileName are unexpected again.

545
    \see DocumentManager::expectFileChange(const QString &fileName)
546
*/
547
void DocumentManager::unexpectFileChange(const QString &fileName)
548 549 550 551 552 553
{
    // We are updating the expected time of the file
    // And in changedFile we'll check if the modification time
    // is the same as the saved one here
    // If so then it's a expected change

554 555
    if (fileName.isEmpty())
        return;
556
    d->m_expectedFileNames.remove(fileName);
557 558 559 560 561
    const QString fixedName = fixFileName(fileName, KeepLinks);
    updateExpectedState(fixedName);
    const QString fixedResolvedName = fixFileName(fileName, ResolveLinks);
    if (fixedName != fixedResolvedName)
        updateExpectedState(fixedResolvedName);
562 563
}

con's avatar
con committed
564
/*!
565
    \fn QList<IDocument*> DocumentManager::saveModifiedFilesSilently(const QList<IDocument*> &documents)
con's avatar
con committed
566

567
    Tries to save the files listed in \a documents. The \a cancelled argument is set to true
568 569 570
    if the user cancelled the dialog. Returns the files that could not be saved. If the files
    listed in documents have no write permissions an additional dialog will be prompted to
    query the user for these permissions.
con's avatar
con committed
571
*/
572
QList<IDocument *> DocumentManager::saveModifiedDocumentsSilently(const QList<IDocument *> &documents, bool *cancelled)
con's avatar
con committed
573
{
574
    return saveModifiedFilesHelper(documents, cancelled, true, QString());
con's avatar
con committed
575 576 577
}

/*!
578
    \fn QList<IDocument*> DocumentManager::saveModifiedFiles(const QList<IDocument *> &documents, bool *cancelled, const QString &message, const QString &alwaysSaveMessage, bool *alwaysSave)
con's avatar
con committed
579

580
    Asks the user whether to save the files listed in \a documents .
con's avatar
con committed
581 582 583 584 585
    Opens a dialog with the given \a message, and a additional
    text that should be used to ask if the user wants to enabled automatic save
    of modified files (in this context).
    The \a cancelled argument is set to true if the user cancelled the dialog,
    \a alwaysSave is set to match the selection of the user, if files should
586 587
    always automatically be saved. If the files listed in documents have no write
    permissions an additional dialog will be prompted to query the user for these permissions.
con's avatar
con committed
588
    Returns the files that have not been saved.
con's avatar
con committed
589
*/
590
QList<IDocument *> DocumentManager::saveModifiedDocuments(const QList<IDocument *> &documents,
591 592 593
                                              bool *cancelled, const QString &message,
                                              const QString &alwaysSaveMessage,
                                              bool *alwaysSave)
con's avatar
con committed
594
{
595
    return saveModifiedFilesHelper(documents, cancelled, false, message, alwaysSaveMessage, alwaysSave);
con's avatar
con committed
596 597
}

598
static QList<IDocument *> saveModifiedFilesHelper(const QList<IDocument *> &documents,
599 600 601 602 603
                                              bool *cancelled,
                                              bool silently,
                                              const QString &message,
                                              const QString &alwaysSaveMessage,
                                              bool *alwaysSave)
con's avatar
con committed
604 605 606 607
{
    if (cancelled)
        (*cancelled) = false;

608 609 610
    QList<IDocument *> notSaved;
    QMap<IDocument *, QString> modifiedDocumentsMap;
    QList<IDocument *> modifiedDocuments;
con's avatar
con committed
611

612 613 614
    foreach (IDocument *document, documents) {
        if (document->isModified()) {
            QString name = document->fileName();
con's avatar
con committed
615
            if (name.isEmpty())
616
                name = document->suggestedFileName();
con's avatar
con committed
617

618
            // There can be several IDocuments pointing to the same file
619
            // Prefer one that is not readonly
620 621 622
            // (even though it *should* not happen that the IDocuments are inconsistent with readonly)
            if (!modifiedDocumentsMap.key(name, 0) || !document->isFileReadOnly())
                modifiedDocumentsMap.insert(document, name);
con's avatar
con committed
623 624
        }
    }
625 626 627
    modifiedDocuments = modifiedDocumentsMap.keys();
    if (!modifiedDocuments.isEmpty()) {
        QList<IDocument *> documentsToSave;
con's avatar
con committed
628
        if (silently) {
629
            documentsToSave = modifiedDocuments;
con's avatar
con committed
630
        } else {
631
            SaveItemsDialog dia(d->m_mainWindow, modifiedDocuments);
con's avatar
con committed
632 633
            if (!message.isEmpty())
                dia.setMessage(message);
634 635
            if (!alwaysSaveMessage.isNull())
                dia.setAlwaysSaveMessage(alwaysSaveMessage);
con's avatar
con committed
636 637 638
            if (dia.exec() != QDialog::Accepted) {
                if (cancelled)
                    (*cancelled) = true;
639 640
                if (alwaysSave)
                    *alwaysSave = dia.alwaysSaveChecked();
641
                notSaved = modifiedDocuments;
con's avatar
con committed
642 643
                return notSaved;
            }
644 645
            if (alwaysSave)
                *alwaysSave = dia.alwaysSaveChecked();
646
            documentsToSave = dia.itemsToSave();
con's avatar
con committed
647
        }
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
        // Check for files without write permissions.
        QList<IDocument *> roDocuments;
        foreach (IDocument *document, documentsToSave) {
            if (document->isFileReadOnly())
                roDocuments << document;
        }
        if (!roDocuments.isEmpty()) {
            Core::Internal::ReadOnlyFilesDialog roDialog(roDocuments, d->m_mainWindow);
            roDialog.setShowFailWarning(true, QCoreApplication::translate(
                                            "saveModifiedFilesHelper",
                                            "Could not save the files.",
                                            "error message"));
            if (roDialog.exec() == Core::Internal::ReadOnlyFilesDialog::RO_Cancel) {
                if (cancelled)
                    (*cancelled) = true;
                notSaved = modifiedDocuments;
                return notSaved;
            }
        }
667 668
        foreach (IDocument *document, documentsToSave) {
            if (!EditorManager::instance()->saveDocument(document)) {
669 670
                if (cancelled)
                    *cancelled = true;
671
                notSaved.append(document);
con's avatar
con committed
672 673 674 675 676 677
            }
        }
    }
    return notSaved;
}

678
bool DocumentManager::saveDocument(IDocument *document, const QString &fileName, bool *isReadOnly)
679
{
680
    bool ret = true;
681 682 683
    QString effName = fileName.isEmpty() ? document->fileName() : fileName;
    expectFileChange(effName); // This only matters to other IDocuments which refer to this file
    bool addWatcher = removeDocument(document); // So that our own IDocument gets no notification at all
684

685
    QString errorString;
686
    if (!document->save(&errorString, fileName, false)) {
687 688 689
        if (isReadOnly) {
            QFile ofi(effName);
            // Check whether the existing file is writable
690
            if (!ofi.open(QIODevice::ReadWrite) && ofi.open(QIODevice::ReadOnly)) {
691
                *isReadOnly = true;
692
                goto out;
693 694 695
            }
            *isReadOnly = false;
        }
696 697
        QMessageBox::critical(d->m_mainWindow, tr("File Error"),
                              tr("Error while saving file: %1").arg(errorString));
698 699
      out:
        ret = false;
700
    }
701

702
    addDocument(document, addWatcher);
703 704
    unexpectFileChange(effName);
    return ret;
705 706
}

707
QString DocumentManager::getSaveFileName(const QString &title, const QString &pathIn,
708
                                     const QString &filter, QString *selectedFilter)
con's avatar
con committed
709
{
710
    const QString &path = pathIn.isEmpty() ? fileDialogInitialDirectory() : pathIn;
con's avatar
con committed
711 712 713 714
    QString fileName;
    bool repeat;
    do {
        repeat = false;
715 716 717 718 719 720 721 722 723 724
        fileName = QFileDialog::getSaveFileName(
            d->m_mainWindow, title, path, filter, selectedFilter, QFileDialog::DontConfirmOverwrite);
        if (!fileName.isEmpty()) {
            // If the selected filter is All Files (*) we leave the name exactly as the user
            // specified. Otherwise the suffix must be one available in the selected filter. If
            // the name already ends with such suffix nothing needs to be done. But if not, the
            // first one from the filter is appended.
            if (selectedFilter && *selectedFilter != QCoreApplication::translate(
                    "Core", Constants::ALL_FILES_FILTER)) {
                // Mime database creates filter strings like this: Anything here (*.foo *.bar)
725
                QRegExp regExp(QLatin1String(".*\\s+\\((.*)\\)$"));
726 727 728
                const int index = regExp.lastIndexIn(*selectedFilter);
                bool suffixOk = false;
                if (index != -1) {
729
                    const QStringList &suffixes = regExp.cap(1).remove(QLatin1Char('*')).split(QLatin1Char(' '));
730 731 732 733 734 735 736 737 738
                    foreach (const QString &suffix, suffixes)
                        if (fileName.endsWith(suffix)) {
                            suffixOk = true;
                            break;
                        }
                    if (!suffixOk && !suffixes.isEmpty())
                        fileName.append(suffixes.at(0));
                }
            }
con's avatar
con committed
739
            if (QFile::exists(fileName)) {
740
                if (QMessageBox::warning(d->m_mainWindow, tr("Overwrite?"),
741 742 743
                    tr("An item named '%1' already exists at this location. "
                       "Do you want to overwrite it?").arg(fileName),
                    QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) {
con's avatar
con committed
744
                    repeat = true;
745
                }
con's avatar
con committed
746 747 748
            }
        }
    } while (repeat);
749 750
    if (!fileName.isEmpty())
        setFileDialogLastVisitedDirectory(QFileInfo(fileName).absolutePath());
con's avatar
con committed
751 752 753
    return fileName;
}

754
QString DocumentManager::getSaveFileNameWithExtension(const QString &title, const QString &pathIn,
755 756 757 758 759 760
                                                  const QString &filter)
{
    QString selected = filter;
    return getSaveFileName(title, pathIn, filter, &selected);
}

con's avatar
con committed
761
/*!
762
    \fn QString DocumentManager::getSaveAsFileName(IDocument *document, const QString &filter, QString *selectedFilter)
con's avatar
con committed
763

764
    Asks the user for a new file name (Save File As) for /arg document.
con's avatar
con committed
765
*/
766
QString DocumentManager::getSaveAsFileName(const IDocument *document, const QString &filter, QString *selectedFilter)
con's avatar
con committed
767
{
768
    if (!document)
con's avatar
con committed
769
        return QLatin1String("");
770
    QString absoluteFilePath = document->fileName();
con's avatar
con committed
771 772 773 774
    const QFileInfo fi(absoluteFilePath);
    QString fileName = fi.fileName();
    QString path = fi.absolutePath();
    if (absoluteFilePath.isEmpty()) {
775 776
        fileName = document->suggestedFileName();
        const QString defaultPath = document->defaultPath();
con's avatar
con committed
777 778 779
        if (!defaultPath.isEmpty())
            path = defaultPath;
    }
780

con's avatar
con committed
781
    QString filterString;
782
    if (filter.isEmpty()) {
hjk's avatar
hjk committed
783
        if (const MimeType &mt = Core::ICore::mimeDatabase()->findByFile(fi))
784 785 786 787
            filterString = mt.filterString();
        selectedFilter = &filterString;
    } else {
        filterString = filter;
con's avatar
con committed
788 789
    }

790
    absoluteFilePath = getSaveFileName(tr("Save File As"),
con's avatar
con committed
791 <