filemanager.cpp 45.1 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2 3 4
**
** This file is part of Qt Creator
**
con's avatar
con committed
5
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
**
hjk's avatar
hjk committed
7
** Contact: Nokia Corporation (info@qt.nokia.com)
con's avatar
con committed
8
**
9
**
10
** GNU Lesser General Public License Usage
11
**
hjk's avatar
hjk committed
12 13 14 15 16 17
** 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.
18
**
con's avatar
con committed
19
** In addition, as a special exception, Nokia gives you certain additional
hjk's avatar
hjk committed
20
** rights. These rights are described in the Nokia Qt LGPL Exception
con's avatar
con committed
21 22
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
23 24 25 26 27
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
con's avatar
con committed
28 29
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
con's avatar
con committed
30
**
31
**************************************************************************/
hjk's avatar
hjk committed
32

con's avatar
con committed
33
#include "filemanager.h"
hjk's avatar
hjk committed
34

35
#include "editormanager.h"
36
#include "ieditor.h"
37
#include "icore.h"
con's avatar
con committed
38
#include "ifile.h"
39 40
#include "iversioncontrol.h"
#include "mimedatabase.h"
con's avatar
con committed
41 42
#include "saveitemsdialog.h"
#include "vcsmanager.h"
43
#include "coreconstants.h"
con's avatar
con committed
44

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

con's avatar
con committed
50 51 52 53 54 55
#include <QtCore/QSettings>
#include <QtCore/QFileInfo>
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtCore/QTimer>
#include <QtCore/QFileSystemWatcher>
56
#include <QtCore/QDateTime>
con's avatar
con committed
57 58
#include <QtGui/QFileDialog>
#include <QtGui/QMessageBox>
59
#include <QtGui/QMainWindow>
60
#include <QtGui/QPushButton>
con's avatar
con committed
61 62

/*!
con's avatar
con committed
63
  \class Core::FileManager
con's avatar
con committed
64 65 66 67 68 69 70 71 72 73 74
  \mainclass
  \inheaderfile filemanager.h
  \brief Manages a set of IFile objects.

  The FileManager service monitors a set of IFile's. Plugins should register
  files they work with at the service. The files the IFile's point to will be
  monitored at filesystem level. If a file changes, the status of the IFile's
  will be adjusted accordingly. Furthermore, on application exit the user will
  be asked to save all modified files.

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

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

con's avatar
con committed
82 83 84 85 86 87 88 89 90
  The FileManager service also provides two convenience methods for saving
  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()).
 */

91 92 93
static const char * const settingsGroupC = "RecentFiles";
static const char * const filesKeyC = "Files";
static const char * const editorsKeyC = "EditorIds";
94

95 96 97
static const char * const directoryGroupC = "Directories";
static const char * const projectDirectoryKeyC = "Projects";
static const char * const useProjectDirectoryKeyC = "UseProjectsDirectory";
con's avatar
con committed
98

99 100 101
namespace Core {
namespace Internal {

102
struct FileStateItem
103 104 105 106 107
{
    QDateTime modified;
    QFile::Permissions permissions;
};

108 109 110 111 112 113
struct FileState
{
    QMap<IFile *, FileStateItem> lastUpdatedState;
    FileStateItem expected;
};

dt's avatar
dt committed
114

115
struct FileManagerPrivate {
116
    explicit FileManagerPrivate(FileManager *q, QMainWindow *mw);
117 118 119

    void watchFile(const QString &f);
    void watchLink(const QString &f);
120

121
    static FileManager *m_instance;
dt's avatar
dt committed
122
    QMap<QString, FileState> m_states;
123
    QStringList m_changedFiles;
dt's avatar
dt committed
124
    QList<IFile *> m_filesWithoutWatch;
125
    QMap<IFile *, QStringList> m_filesWithWatch;
126
    QSet<QString> m_expectedFileNames;
127

128
    QList<FileManager::RecentFile> m_recentFiles;
129 130 131 132 133
    static const int m_maxRecentFiles = 7;

    QString m_currentFile;

    QMainWindow *m_mainWindow;
134
    Utils::FileSystemWatcher *m_fileWatcher; // Delayed creation.
135
    QFileSystemWatcher *m_linkWatcher; // Delayed creation (only UNIX/if a link is seen).
136
    bool m_blockActivated;
137 138 139
    QString m_lastVisitedDirectory;
    QString m_projectsDirectory;
    bool m_useProjectsDirectory;
dt's avatar
dt committed
140 141 142 143 144
    // When we are callling into a IFile
    // we don't want to receive a changed()
    // signal
    // That makes the code easier
    IFile *m_blockedIFile;
145 146
};

147
void FileManagerPrivate::watchFile(const QString &f)
148 149
{
    if (!m_fileWatcher) {
150 151
        m_fileWatcher = new Utils::FileSystemWatcher(m_instance);
        m_fileWatcher->setObjectName(QLatin1String("FileManagerWatcher"));
152 153 154
        QObject::connect(m_fileWatcher, SIGNAL(fileChanged(QString)),
                         m_instance, SLOT(changedFile(QString)));
    }
155
    m_fileWatcher->addFile(f, Utils::FileSystemWatcher::WatchAllChanges);
156 157
}

158
void FileManagerPrivate::watchLink(const QString &f)
159 160 161
{
#ifdef Q_OS_UNIX
    if (!m_linkWatcher) {
162
        // Use a different file watcher engine for links on UNIX
163 164 165 166 167
        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)));
    }
168
    m_linkWatcher->addPath(f);
169
#else
170
    watchFile(f);
171 172 173
#endif
}

174 175 176
FileManager *FileManagerPrivate::m_instance = 0;

FileManagerPrivate::FileManagerPrivate(FileManager *q, QMainWindow *mw) :
con's avatar
con committed
177
    m_mainWindow(mw),
178 179
    m_fileWatcher(0),
    m_linkWatcher(0),
180 181 182
    m_blockActivated(false),
    m_lastVisitedDirectory(QDir::currentPath()),
#ifdef Q_OS_MAC  // Creator is in bizarre places when launched via finder.
dt's avatar
dt committed
183
    m_useProjectsDirectory(true),
184
#else
dt's avatar
dt committed
185
    m_useProjectsDirectory(false),
186
#endif
dt's avatar
dt committed
187
    m_blockedIFile(0)
con's avatar
con committed
188
{
189
    m_instance = q;
190 191 192 193 194 195 196 197 198 199
}

} // namespace Internal

FileManager::FileManager(QMainWindow *mw)
  : QObject(mw),
    d(new Internal::FileManagerPrivate(this, mw))
{
    Core::ICore *core = Core::ICore::instance();
    connect(d->m_mainWindow, SIGNAL(windowActivated()),
con's avatar
con committed
200
        this, SLOT(mainWindowActivated()));
hjk's avatar
hjk committed
201
    connect(core, SIGNAL(contextChanged(Core::IContext*,Core::Context)),
con's avatar
con committed
202 203
        this, SLOT(syncWithEditor(Core::IContext*)));

204
    readSettings();
con's avatar
con committed
205 206
}

207 208 209 210 211
FileManager::~FileManager()
{
    delete d;
}

212 213 214 215 216
FileManager *FileManager::instance()
{
    return Internal::FileManagerPrivate::m_instance;
}

con's avatar
con committed
217
/*!
con's avatar
con committed
218
    \fn bool FileManager::addFiles(const QList<IFile *> &files, bool addWatcher)
con's avatar
con committed
219

con's avatar
con committed
220 221 222
    Adds a list of IFile's to the collection. If \a addWatcher is true (the default),
    the files are added to a file system watcher that notifies the file manager
    about file changes.
con's avatar
con committed
223
*/
con's avatar
con committed
224
void FileManager::addFiles(const QList<IFile *> &files, bool addWatcher)
con's avatar
con committed
225
{
dt's avatar
dt committed
226 227 228
    if (!addWatcher) {
        // We keep those in a separate list

229
        foreach (IFile *file, files) {
230 231 232 233 234
            if (file && !d->m_filesWithoutWatch.contains(file)) {
                connect(file, SIGNAL(destroyed(QObject *)), this, SLOT(fileDestroyed(QObject *)));
                d->m_filesWithoutWatch.append(file);
            }
        }
con's avatar
con committed
235
        return;
dt's avatar
dt committed
236 237
    }

con's avatar
con committed
238
    foreach (IFile *file, files) {
239 240 241 242 243
        if (file && !d->m_filesWithWatch.contains(file)) {
            connect(file, SIGNAL(changed()), this, SLOT(checkForNewFileName()));
            connect(file, SIGNAL(destroyed(QObject *)), this, SLOT(fileDestroyed(QObject *)));
            addFileInfo(file);
        }
con's avatar
con committed
244 245 246
    }
}

247 248 249 250
/* Adds the IFile's file and possibly it's final link target to both m_states
   (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.) */
dt's avatar
dt committed
251
void FileManager::addFileInfo(IFile *file)
252
{
253 254 255 256 257 258
    const QString fixedName = fixFileName(file->fileName(), KeepLinks);
    const QString fixedResolvedName = fixFileName(file->fileName(), ResolveLinks);
    addFileInfo(fixedResolvedName, file, false);
    if (fixedName != fixedResolvedName)
        addFileInfo(fixedName, file, true);
}
259

260 261 262 263 264 265 266 267 268 269 270 271 272
/* only called from addFileInfo(IFile *) */
void FileManager::addFileInfo(const QString &fileName, IFile *file, bool isLink)
{
    Internal::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
        if (!d->m_states.contains(fileName)) {
            d->m_states.insert(fileName, Internal::FileState());

            if (isLink)
273
                d->watchLink(fileName);
274
            else
275
                d->watchFile(fileName);
276
        }
277
        d->m_states[fileName].lastUpdatedState.insert(file, state);
278
    }
279
    d->m_filesWithWatch[file].append(fileName); // inserts a new QStringList if not already there
280 281
}

282 283
/* Updates the time stamp and permission information of the files
   registered for this IFile (in m_filesWithWatch; can be the IFile's file + final link target) */
284 285
void FileManager::updateFileInfo(IFile *file)
{
286 287 288 289 290 291 292 293 294 295 296 297
    foreach (const QString &fileName, d->m_filesWithWatch.value(file)) {
        // If the filename is empty there's nothing to do
        if (fileName.isEmpty())
            continue;
        const QFileInfo fi(fileName);
        Internal::FileStateItem item;
        item.modified = fi.lastModified();
        item.permissions = fi.permissions();
        QTC_ASSERT(d->m_states.contains(fileName), continue);
        QTC_ASSERT(d->m_states.value(fileName).lastUpdatedState.contains(file), continue);
        d->m_states[fileName].lastUpdatedState.insert(file, item);
    }
298 299
}

dt's avatar
dt committed
300 301 302 303
/// Dumps the state of the file manager's map
/// For debugging purposes
void FileManager::dump()
{
304
    qDebug() << "======== dumping state map";
dt's avatar
dt committed
305 306 307 308 309
    QMap<QString, Internal::FileState>::const_iterator it, end;
    it = d->m_states.constBegin();
    end = d->m_states.constEnd();
    for (; it != end; ++it) {
        qDebug() << it.key();
310
        qDebug() << "   expected:" << it.value().expected.modified;
dt's avatar
dt committed
311 312 313 314 315

        QMap<IFile *, Internal::FileStateItem>::const_iterator jt, jend;
        jt = it.value().lastUpdatedState.constBegin();
        jend = it.value().lastUpdatedState.constEnd();
        for (; jt != jend; ++jt) {
316
            qDebug() << "  " << jt.key()->fileName() << jt.value().modified;
dt's avatar
dt committed
317 318
        }
    }
319 320 321 322 323
    qDebug() << "------- dumping files with watch list";
    foreach (IFile *key, d->m_filesWithWatch.keys()) {
        qDebug() << key->fileName() << d->m_filesWithWatch.value(key);
    }
    qDebug() << "------- dumping watch list";
324 325
    if (d->m_fileWatcher)
        qDebug() << d->m_fileWatcher->files();
326
    qDebug() << "------- dumping link watch list";
327 328
    if (d->m_linkWatcher)
        qDebug() << d->m_linkWatcher->files();
dt's avatar
dt committed
329 330
}

331
/*!
332
    \fn void FileManager::renamedFile(const QString &from, const QString &to)
333 334 335 336 337 338 339 340 341
    \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.
    This will notify all IFile objects pointing to that file of the rename
    by calling IFile::rename, and update the cached time and permission
    information to avoid annoying the user with "file has been removed"
    popups.
*/
342
void FileManager::renamedFile(const QString &from, const QString &to)
dt's avatar
dt committed
343
{
344
    const QString &fixedFrom = fixFileName(from, KeepLinks);
dt's avatar
dt committed
345

346 347 348 349 350 351 352
    // gather the list of IFiles
    QList<IFile *> filesToRename;
    QMapIterator<IFile *, QStringList> it(d->m_filesWithWatch);
    while (it.hasNext()) {
        it.next();
        if (it.value().contains(fixedFrom))
            filesToRename.append(it.key());
353 354
    }

355 356 357 358 359 360 361 362
    // rename the IFiles
    foreach (IFile *file, filesToRename) {
        d->m_blockedIFile = file;
        removeFileInfo(file);
        file->rename(to);
        addFileInfo(file);
        d->m_blockedIFile = 0;
    }
363 364
}

365
/* Removes all occurrences of the IFile from m_filesWithWatch and m_states.
366 367 368 369
   If that results in a file no longer being referenced by any IFile, this
   also removes the file watcher.
*/
void FileManager::removeFileInfo(IFile *file)
370
{
371 372 373 374 375 376 377
    if (!d->m_filesWithWatch.contains(file))
        return;
    foreach (const QString &fileName, d->m_filesWithWatch.value(file)) {
        if (!d->m_states.contains(fileName))
            continue;
        d->m_states[fileName].lastUpdatedState.remove(file);
        if (d->m_states.value(fileName).lastUpdatedState.isEmpty()) {
378 379
            if (d->m_fileWatcher && d->m_fileWatcher->watchesFile(fileName))
                d->m_fileWatcher->removeFile(fileName);
380
            if (d->m_linkWatcher && d->m_linkWatcher->files().contains(fileName))
381 382 383
                d->m_linkWatcher->removePath(fileName);
            d->m_states.remove(fileName);
        }
384
    }
385
    d->m_filesWithWatch.remove(file);
386 387
}

con's avatar
con committed
388
/*!
con's avatar
con committed
389
    \fn bool FileManager::addFile(IFile *files, bool addWatcher)
con's avatar
con committed
390

con's avatar
con committed
391 392 393
    Adds a IFile object to the collection. If \a addWatcher is true (the default),
    the file is added to a file system watcher that notifies the file manager
    about file changes.
con's avatar
con committed
394
*/
con's avatar
con committed
395
void FileManager::addFile(IFile *file, bool addWatcher)
con's avatar
con committed
396
{
con's avatar
con committed
397
    addFiles(QList<IFile *>() << file, addWatcher);
con's avatar
con committed
398 399 400 401 402
}

void FileManager::fileDestroyed(QObject *obj)
{
    IFile *file = static_cast<IFile*>(obj);
dt's avatar
dt committed
403
    // Check the special unwatched first:
404 405
    if (!d->m_filesWithoutWatch.removeOne(file))
        removeFileInfo(file);
con's avatar
con committed
406 407 408 409 410 411 412 413 414
}

/*!
    \fn bool FileManager::removeFile(IFile *file)

    Removes a IFile object from the collection.

    Returns true if the file specified by \a file has been part of the file list.
*/
con's avatar
con committed
415
void FileManager::removeFile(IFile *file)
con's avatar
con committed
416
{
417
    QTC_ASSERT(file, return);
con's avatar
con committed
418

dt's avatar
dt committed
419
    // Special casing unwatched files
420 421 422
    if (!d->m_filesWithoutWatch.removeOne(file)) {
        removeFileInfo(file);
        disconnect(file, SIGNAL(changed()), this, SLOT(checkForNewFileName()));
dt's avatar
dt committed
423
    }
con's avatar
con committed
424 425 426
    disconnect(file, SIGNAL(destroyed(QObject *)), this, SLOT(fileDestroyed(QObject *)));
}

427 428
/* Slot reacting on IFile::changed. We need to check if the signal was sent
   because the file was saved under different name. */
con's avatar
con committed
429 430 431
void FileManager::checkForNewFileName()
{
    IFile *file = qobject_cast<IFile *>(sender());
dt's avatar
dt committed
432 433 434 435
    // We modified the IFile
    // Trust the other code to also update the m_states map
    if (file == d->m_blockedIFile)
        return;
hjk's avatar
hjk committed
436
    QTC_ASSERT(file, return);
437
    QTC_ASSERT(d->m_filesWithWatch.contains(file), return);
438

439
    // Maybe the name has changed or file has been deleted and created again ...
440 441
    // This also updates the state to the on disk state
    removeFileInfo(file);
dt's avatar
dt committed
442
    addFileInfo(file);
con's avatar
con committed
443 444
}

445 446 447 448 449 450 451
/*!
    \fn QString FileManager::fixFileName(const QString &fileName, FixMode fixmode)
    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).
*/
QString FileManager::fixFileName(const QString &fileName, FixMode fixmode)
con's avatar
con committed
452 453
{
    QString s = fileName;
454
    QFileInfo fi(s);
455 456 457 458 459 460 461 462 463
    if (fi.exists()) {
        if (fixmode == ResolveLinks)
            s = fi.canonicalFilePath();
        else
            s = QDir::cleanPath(fi.absoluteFilePath());
    } else {
        s = QDir::cleanPath(s);
    }
    s = QDir::toNativeSeparators(s);
con's avatar
con committed
464 465 466
#ifdef Q_OS_WIN
    s = s.toLower();
#endif
467
    return s;
con's avatar
con committed
468 469 470 471 472 473 474 475 476 477 478
}

/*!
    \fn QList<IFile*> FileManager::modifiedFiles() const

    Returns the list of IFile's that have been modified.
*/
QList<IFile *> FileManager::modifiedFiles() const
{
    QList<IFile *> modifiedFiles;

479 480 481
    foreach (IFile *file, d->m_filesWithWatch.keys()) {
        if (file->isModified())
            modifiedFiles << file;
con's avatar
con committed
482
    }
483

dt's avatar
dt committed
484 485 486 487 488
    foreach(IFile *file, d->m_filesWithoutWatch) {
        if (file->isModified())
            modifiedFiles << file;
    }

con's avatar
con committed
489 490 491
    return modifiedFiles;
}

492 493 494 495 496 497 498 499
/*!
    \fn void FileManager::expectFileChange(const QString &fileName)

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

    \see FileManager::unexpectFileChange(const QString &fileName)
*/
void FileManager::expectFileChange(const QString &fileName)
con's avatar
con committed
500
{
501 502 503
    if (fileName.isEmpty())
        return;
    d->m_expectedFileNames.insert(fileName);
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
}

/*!
    \fn void FileManager::unexpectFileChange(const QString &fileName)

    Any change to \a fileName are unexpected again.

    \see FileManager::expectFileChange(const QString &fileName)
*/
void FileManager::unexpectFileChange(const QString &fileName)
{
    // 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

520 521
    if (fileName.isEmpty())
        return;
522
    d->m_expectedFileNames.remove(fileName);
523 524 525 526 527
    const QString fixedName = fixFileName(fileName, KeepLinks);
    updateExpectedState(fixedName);
    const QString fixedResolvedName = fixFileName(fileName, ResolveLinks);
    if (fixedName != fixedResolvedName)
        updateExpectedState(fixedResolvedName);
528 529
}

530
/* only called from unblock and unexpect file change methods */
531 532
void FileManager::updateExpectedState(const QString &fileName)
{
533
    if (fileName.isEmpty())
534
        return;
535 536 537 538
    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();
dt's avatar
dt committed
539
    }
con's avatar
con committed
540 541 542 543 544 545 546 547 548 549 550 551 552
}

/*!
    \fn QList<IFile*> FileManager::saveModifiedFilesSilently(const QList<IFile*> &files)

    Tries to save the files listed in \a files . Returns the files that could not be saved.
*/
QList<IFile *> FileManager::saveModifiedFilesSilently(const QList<IFile *> &files)
{
    return saveModifiedFiles(files, 0, true, QString());
}

/*!
con's avatar
con committed
553 554 555 556 557 558 559 560 561 562
    \fn QList<IFile*> FileManager::saveModifiedFiles(const QList<IFile *> &files, bool *cancelled, const QString &message, const QString &alwaysSaveMessage, bool *alwaysSave)

    Asks the user whether to save the files listed in \a files .
    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
    always automatically be saved.
    Returns the files that have not been saved.
con's avatar
con committed
563 564
*/
QList<IFile *> FileManager::saveModifiedFiles(const QList<IFile *> &files,
565 566 567
                                              bool *cancelled, const QString &message,
                                              const QString &alwaysSaveMessage,
                                              bool *alwaysSave)
con's avatar
con committed
568
{
569
    return saveModifiedFiles(files, cancelled, false, message, alwaysSaveMessage, alwaysSave);
con's avatar
con committed
570 571 572
}

QList<IFile *> FileManager::saveModifiedFiles(const QList<IFile *> &files,
573 574 575 576 577
                                              bool *cancelled,
                                              bool silently,
                                              const QString &message,
                                              const QString &alwaysSaveMessage,
                                              bool *alwaysSave)
con's avatar
con committed
578 579 580 581 582
{
    if (cancelled)
        (*cancelled) = false;

    QList<IFile *> notSaved;
583 584
    QMap<IFile *, QString> modifiedFilesMap;
    QList<IFile *> modifiedFiles;
con's avatar
con committed
585 586 587 588 589 590 591 592 593

    foreach (IFile *file, files) {
        if (file->isModified()) {
            QString name = file->fileName();
            if (name.isEmpty())
                name = file->suggestedFileName();

            // There can be several FileInterfaces pointing to the same file
            // Select one that is not readonly.
con's avatar
con committed
594 595
            if (!(modifiedFilesMap.key(name, 0)
                    && file->isReadOnly()))
596
                modifiedFilesMap.insert(file, name);
con's avatar
con committed
597 598
        }
    }
599
    modifiedFiles = modifiedFilesMap.keys();
con's avatar
con committed
600 601 602
    if (!modifiedFiles.isEmpty()) {
        QList<IFile *> filesToSave;
        if (silently) {
603
            filesToSave = modifiedFiles;
con's avatar
con committed
604
        } else {
605
            Internal::SaveItemsDialog dia(d->m_mainWindow, modifiedFiles);
con's avatar
con committed
606 607
            if (!message.isEmpty())
                dia.setMessage(message);
608 609
            if (!alwaysSaveMessage.isNull())
                dia.setAlwaysSaveMessage(alwaysSaveMessage);
con's avatar
con committed
610 611 612
            if (dia.exec() != QDialog::Accepted) {
                if (cancelled)
                    (*cancelled) = true;
613 614
                if (alwaysSave)
                    *alwaysSave = dia.alwaysSaveChecked();
615
                notSaved = modifiedFiles;
con's avatar
con committed
616 617
                return notSaved;
            }
618 619
            if (alwaysSave)
                *alwaysSave = dia.alwaysSaveChecked();
con's avatar
con committed
620 621 622 623
            filesToSave = dia.itemsToSave();
        }

        foreach (IFile *file, filesToSave) {
624 625 626 627
            if (!EditorManager::instance()->saveFile(file)) {
                if (cancelled)
                    *cancelled = true;
                notSaved.append(file);
con's avatar
con committed
628 629 630 631 632 633
            }
        }
    }
    return notSaved;
}

634
bool FileManager::saveFile(IFile *file, const QString &fileName, bool *isReadOnly)
635
{
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
    QString effName = fileName.isEmpty() ? file->fileName() : fileName;
    QString errorString;
    if (!file->save(&errorString, fileName)) {
        if (isReadOnly) {
            QFile ofi(effName);
            // Check whether the existing file is writable
            if (ofi.exists() && !ofi.open(QIODevice::ReadWrite)
                && ofi.error() == QFile::PermissionsError) {
                *isReadOnly = true;
                return false;
            }
            *isReadOnly = false;
        }
        QMessageBox::critical(d->m_mainWindow, tr("File Error"), errorString);
        return false;
    }
652 653 654 655 656 657 658 659 660 661 662 663 664 665

    // We are updating the lastUpdated time to the current modification time
    // in changedFile we'll compare the modification time with the last updated
    // time, and if they are the same, then we don't deliver that notification
    // to corresponding IFile
    //
    // Also we are updating the expected time of the file
    // 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
    updateFileInfo(file);
    foreach (const QString &fileName, d->m_filesWithWatch.value(file))
        updateExpectedState(fileName);

666
    return true;
667 668
}

669 670
QString FileManager::getSaveFileName(const QString &title, const QString &pathIn,
                                     const QString &filter, QString *selectedFilter)
con's avatar
con committed
671
{
672
    const QString &path = pathIn.isEmpty() ? fileDialogInitialDirectory() : pathIn;
con's avatar
con committed
673 674 675 676
    QString fileName;
    bool repeat;
    do {
        repeat = false;
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
        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)
                QRegExp regExp(".*\\s+\\((.*)\\)$");
                const int index = regExp.lastIndexIn(*selectedFilter);
                bool suffixOk = false;
                if (index != -1) {
                    const QStringList &suffixes = regExp.cap(1).remove('*').split(' ');
                    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
701
            if (QFile::exists(fileName)) {
702
                if (QMessageBox::warning(d->m_mainWindow, tr("Overwrite?"),
703 704 705
                    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
706
                    repeat = true;
707
                }
con's avatar
con committed
708 709 710
            }
        }
    } while (repeat);
711 712
    if (!fileName.isEmpty())
        setFileDialogLastVisitedDirectory(QFileInfo(fileName).absolutePath());
con's avatar
con committed
713 714 715
    return fileName;
}

716 717 718 719 720 721 722
QString FileManager::getSaveFileNameWithExtension(const QString &title, const QString &pathIn,
                                                  const QString &filter)
{
    QString selected = filter;
    return getSaveFileName(title, pathIn, filter, &selected);
}

con's avatar
con committed
723
/*!
724
    \fn QString FileManager::getSaveAsFileName(IFile *file, const QString &filter, QString *selectedFilter)
con's avatar
con committed
725 726 727

    Asks the user for a new file name (Save File As) for /arg file.
*/
728
QString FileManager::getSaveAsFileName(IFile *file, const QString &filter, QString *selectedFilter)
con's avatar
con committed
729 730 731 732 733 734 735 736 737 738 739 740 741
{
    if (!file)
        return QLatin1String("");
    QString absoluteFilePath = file->fileName();
    const QFileInfo fi(absoluteFilePath);
    QString fileName = fi.fileName();
    QString path = fi.absolutePath();
    if (absoluteFilePath.isEmpty()) {
        fileName = file->suggestedFileName();
        const QString defaultPath = file->defaultPath();
        if (!defaultPath.isEmpty())
            path = defaultPath;
    }
742

con's avatar
con committed
743
    QString filterString;
744 745 746 747 748 749
    if (filter.isEmpty()) {
        if (const MimeType &mt = Core::ICore::instance()->mimeDatabase()->findByFile(fi))
            filterString = mt.filterString();
        selectedFilter = &filterString;
    } else {
        filterString = filter;
con's avatar
con committed
750 751
    }

752
    absoluteFilePath = getSaveFileName(tr("Save File As"),
con's avatar
con committed
753 754
        path + QDir::separator() + fileName,
        filterString,
755
        selectedFilter);
con's avatar
con committed
756 757 758
    return absoluteFilePath;
}

759
/*!
760 761 762
    \fn QStringList FileManager::getOpenFileNames(const QString &filters,
                                                  const QString pathIn,
                                                  QString *selectedFilter)
763

con's avatar
con committed
764 765 766 767
    Asks the user for a set of file names to be opened. The \a filters
    and \a selectedFilter parameters is interpreted like in
    QFileDialog::getOpenFileNames(), \a pathIn specifies a path to open the dialog
    in, if that is not overridden by the users policy.
768 769 770 771 772 773
*/

QStringList FileManager::getOpenFileNames(const QString &filters,
                                          const QString pathIn,
                                          QString *selectedFilter)
{
774 775 776 777
    QString path = pathIn;
    if (path.isEmpty()) {
        if (!d->m_currentFile.isEmpty())
            path = QFileInfo(d->m_currentFile).absoluteFilePath();
778 779
        if (path.isEmpty() && useProjectsDirectory())
            path = projectsDirectory();
780
    }
781 782 783 784 785 786 787 788 789
    const QStringList files = QFileDialog::getOpenFileNames(d->m_mainWindow,
                                                      tr("Open File"),
                                                      path, filters,
                                                      selectedFilter);
    if (!files.isEmpty())
        setFileDialogLastVisitedDirectory(QFileInfo(files.front()).absolutePath());
    return files;
}

790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
FileManager::ReadOnlyAction
    FileManager::promptReadOnlyFile(const QString &fileName,
                                      const IVersionControl *versionControl,
                                      QWidget *parent,
                                      bool displaySaveAsButton)
{
    // Version Control: If automatic open is desired, open right away.
    bool promptVCS = false;
    if (versionControl && versionControl->supportsOperation(IVersionControl::OpenOperation)) {
        if (versionControl->settingsFlags() & IVersionControl::AutoOpen)
            return RO_OpenVCS;
        promptVCS = true;
    }

    // Create message box.
    QMessageBox msgBox(QMessageBox::Question, tr("File is Read Only"),
                       tr("The file <i>%1</i> is read only.").arg(QDir::toNativeSeparators(fileName)),
                       QMessageBox::Cancel, parent);

    QPushButton *vcsButton = 0;
    if (promptVCS)
        vcsButton = msgBox.addButton(tr("Open with VCS (%1)").arg(versionControl->displayName()), QMessageBox::AcceptRole);

    QPushButton *makeWritableButton =  msgBox.addButton(tr("Make writable"), QMessageBox::AcceptRole);

    QPushButton *saveAsButton = 0;
    if (displaySaveAsButton)
817
        saveAsButton = msgBox.addButton(tr("Save as..."), QMessageBox::ActionRole);
818 819 820 821 822 823 824 825 826

    msgBox.setDefaultButton(vcsButton ? vcsButton : makeWritableButton);
    msgBox.exec();

    QAbstractButton *clickedButton = msgBox.clickedButton();
    if (clickedButton == vcsButton)
        return RO_OpenVCS;
    if (clickedButton == makeWritableButton)
        return RO_MakeWriteable;
827
    if (displaySaveAsButton && clickedButton == saveAsButton)
828 829 830
        return RO_SaveAs;
    return  RO_Cancel;
}
831

832
void FileManager::changedFile(const QString &fileName)
con's avatar
con committed
833
{
834
    const bool wasempty = d->m_changedFiles.isEmpty();
835

836 837
    if (!d->m_changedFiles.contains(fileName) && d->m_states.contains(fileName))
        d->m_changedFiles.append(fileName);
838

839
    if (wasempty && !d->m_changedFiles.isEmpty()) {
840
        QTimer::singleShot(200, this, SLOT(checkForReload()));
con's avatar
con committed
841 842 843 844 845
    }
}

void FileManager::mainWindowActivated()
{
846 847 848 849
    //we need to do this asynchronously because
    //opening a dialog ("Reload?") in a windowactivated event
    //freezes on Mac
    QTimer::singleShot(0, this, SLOT(checkForReload()));
con's avatar
con committed
850 851 852 853
}

void FileManager::checkForReload()
{
854 855
    if (d->m_changedFiles.isEmpty())
        return;
856 857
    if (QApplication::activeWindow() != d->m_mainWindow)
        return;
con's avatar
con committed
858

859 860 861 862 863
    if (d->m_blockActivated)
        return;

    d->m_blockActivated = true;

864 865
    IFile::ReloadSetting defaultBehavior = EditorManager::instance()->reloadSetting();
    Utils::ReloadPromptAnswer previousAnswer = Utils::ReloadCurrent;
866

867 868
    QList<IEditor*> editorsToClose;
    QMap<IFile*, QString> filesToSave;
869 870 871 872 873

    // collect file information
    QMap<QString, Internal::FileStateItem> currentStates;
    QMap<QString, IFile::ChangeType> changeTypes;
    QSet<IFile *> changedIFiles;
874 875
    foreach (const QString &fileName, d->m_changedFiles) {
        IFile::ChangeType type = IFile::TypeContents;
876
        Internal::FileStateItem state;
877
        QFileInfo fi(fileName);
878 879 880
        if (!fi.exists()) {
            type = IFile::TypeRemoved;
        } else {
881 882
            state.modified = fi.lastModified();
            state.permissions = fi.permissions();
883
        }
884 885 886 887 888 889
        currentStates.insert(fileName, state);
        changeTypes.insert(fileName, type);
        foreach (IFile *file, d->m_states.value(fileName).lastUpdatedState.keys())
            changedIFiles.insert(file);
    }

890 891 892 893
    // clean up. do this before we may enter the main loop, otherwise we would
    // lose consecutive notifications.
    d->m_changedFiles.clear();

894 895 896 897 898 899 900 901 902 903 904 905 906
    // collect information about "expected" file names
    // we can't do the "resolving" already in expectFileChange, because
    // if the resolved names are different when unexpectFileChange is called
    // we would end up with never-unexpected file names
    QSet<QString> expectedFileNames;
    foreach (const QString &fileName, d->m_expectedFileNames) {
        const QString fixedName = fixFileName(fileName, KeepLinks);
        expectedFileNames.insert(fixedName);
        const QString fixedResolvedName = fixFileName(fileName, ResolveLinks);
        if (fixedName != fixedResolvedName)
            expectedFileNames.insert(fixedResolvedName);
    }

907
    // handle the IFiles
908
    QStringList errorStrings;
909 910 911 912 913 914 915 916 917 918 919
    foreach (IFile *file, changedIFiles) {
        IFile::ChangeTrigger behavior = IFile::TriggerInternal;
        IFile::ChangeType type = IFile::TypePermissions;
        bool changed = false;
        // find out the type & behavior from the two possible files
        // behavior is internal if all changes are expected (and none removed)
        // type is "max" of both types (remove > contents > permissions)
        foreach (const QString & fileName, d->m_filesWithWatch.value(file)) {
            // was the file reported?
            if (!currentStates.contains(fileName))
                continue;
920

921 922 923 924 925
            Internal::FileStateItem currentState = currentStates.value(fileName);
            Internal::FileStateItem expectedState = d->m_states.value(fileName).expected;
            Internal::FileStateItem lastState = d->m_states.value(fileName).lastUpdatedState.value(file);
            // did the file actually change?
            if (lastState.modified == currentState.modified && lastState.permissions == currentState.permissions)
926
                continue;
927 928 929 930 931 932 933
            changed = true;

            // was it only a permission change?
            if (lastState.modified == currentState.modified)
                continue;

            // was the change unexpected?
934 935
            if ((currentState.modified != expectedState.modified || currentState.permissions != expectedState.permissions)
                    && !expectedFileNames.contains(fileName)) {
936
                behavior = IFile::TriggerExternal;
937
            }
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954

            // find out the type
            IFile::ChangeType fileChange = changeTypes.value(fileName);
            if (fileChange == IFile::TypeRemoved) {
                type = IFile::TypeRemoved;
                behavior = IFile::TriggerExternal; // removed files always trigger externally
            } else if (fileChange == IFile::TypeContents && type == IFile::TypePermissions) {
                type = IFile::TypeContents;
            }
        }

        if (!changed) // probably because the change was blocked with (un)blockFileChange
            continue;

        // handle it!
        d->m_blockedIFile = file;

955 956
        bool success = true;
        QString errorString;
957 958 959 960
        // we've got some modification
        // check if it's contents or permissions:
        if (type == IFile::TypePermissions) {
            // Only permission change
961
            success = file->reload(&errorString, IFile::FlagReload, IFile::TypePermissions);
962 963 964 965
        // now we know it's a content change or file was removed
        } else if (defaultBehavior == IFile::ReloadUnmodified
                   && type == IFile::TypeContents && !file->isModified()) {
            // content change, but unmodified (and settings say to reload in this case)
966
            success = file->reload(&errorString, IFile::FlagReload, type);
967 968 969 970
        // file was removed or it's a content change and the default behavior for
        // unmodified files didn't kick in
        } else if (defaultBehavior == IFile::IgnoreAll) {
            // content change or removed, but settings say ignore
971
            success = file->reload(&errorString, IFile::FlagIgnore, type);
972 973 974 975 976 977 978
        // either the default behavior is to always ask,
        // or the ReloadUnmodified default behavior didn't kick in,
        // so do whatever the IFile wants us to do
        } else {
            // check if IFile wants us to ask
            if (file->reloadBehavior(behavior, type) == IFile::BehaviorSilent) {
                // content change or removed, IFile wants silent handling
979
                success = file->reload(&errorString, IFile::FlagReload, type);
980 981 982 983 984
            // IFile wants us to ask
            } else if (type == IFile::TypeContents) {
                // content change, IFile wants to ask user
                if (previousAnswer == Utils::ReloadNone) {
                    // answer already given, ignore
985
                    success = file->reload(&errorString, IFile::FlagIgnore, IFile::TypeContents);
986 987
                } else if (previousAnswer == Utils::ReloadAll) {
                    // answer already given, reload
988
                    success = file->reload(&errorString, IFile::FlagReload, IFile::TypeContents);
989 990 991 992 993 994
                } else {
                    // Ask about content change
                    previousAnswer = Utils::reloadPrompt(file->fileName(), file->isModified(), QApplication::activeWindow());
                    switch (previousAnswer) {
                    case Utils::ReloadAll:
                    case Utils::ReloadCurrent:
995
                        success = file->reload(&errorString, IFile::FlagReload, IFile::TypeContents);