filemanager.cpp 39.1 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2 3 4
**
** This file is part of Qt Creator
**
hjk's avatar
hjk committed
5
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
con's avatar
con committed
8
**
9
** Commercial Usage
10
**
11 12 13 14
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
15
**
16
** GNU Lesser General Public License Usage
17
**
18 19 20 21 22 23
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24
**
25
** If you are unsure which license is appropriate for your use, please
hjk's avatar
hjk committed
26
** contact the sales department at http://qt.nokia.com/contact.
con's avatar
con committed
27
**
28
**************************************************************************/
hjk's avatar
hjk committed
29

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

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

hjk's avatar
hjk committed
42
#include <utils/qtcassert.h>
43
#include <utils/pathchooser.h>
44
#include <utils/reloadpromptutils.h>
hjk's avatar
hjk committed
45

con's avatar
con committed
46 47 48 49 50 51
#include <QtCore/QSettings>
#include <QtCore/QFileInfo>
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtCore/QTimer>
#include <QtCore/QFileSystemWatcher>
52
#include <QtCore/QDateTime>
con's avatar
con committed
53 54
#include <QtGui/QFileDialog>
#include <QtGui/QMessageBox>
55
#include <QtGui/QMainWindow>
con's avatar
con committed
56 57

/*!
con's avatar
con committed
58
  \class Core::FileManager
con's avatar
con committed
59 60 61 62 63 64 65 66 67 68 69
  \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
70
  filesystem. The monitoring for a IFile can be blocked by blockFileChange(), and
con's avatar
con committed
71 72
  enabled again by unblockFileChange().

73 74 75 76
  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
77 78 79 80 81 82 83 84 85
  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()).
 */

86 87 88 89 90 91
static const char settingsGroupC[] = "RecentFiles";
static const char filesKeyC[] = "Files";

static const char directoryGroupC[] = "Directories";
static const char projectDirectoryKeyC[] = "Projects";
static const char useProjectDirectoryKeyC[] = "UseProjectsDirectory";
con's avatar
con committed
92

93 94 95
namespace Core {
namespace Internal {

96
struct FileStateItem
97 98 99 100 101
{
    QDateTime modified;
    QFile::Permissions permissions;
};

102 103 104 105 106 107
struct FileState
{
    QMap<IFile *, FileStateItem> lastUpdatedState;
    FileStateItem expected;
};

dt's avatar
dt committed
108

109 110 111
struct FileManagerPrivate {
    explicit FileManagerPrivate(QObject *q, QMainWindow *mw);

dt's avatar
dt committed
112
    QMap<QString, FileState> m_states;
113
    QStringList m_changedFiles;
dt's avatar
dt committed
114
    QList<IFile *> m_filesWithoutWatch;
115 116 117 118 119 120 121 122 123

    QStringList m_recentFiles;
    static const int m_maxRecentFiles = 7;

    QString m_currentFile;

    QMainWindow *m_mainWindow;
    QFileSystemWatcher *m_fileWatcher;
    bool m_blockActivated;
124 125 126
    QString m_lastVisitedDirectory;
    QString m_projectsDirectory;
    bool m_useProjectsDirectory;
dt's avatar
dt committed
127 128 129 130 131
    // When we are callling into a IFile
    // we don't want to receive a changed()
    // signal
    // That makes the code easier
    IFile *m_blockedIFile;
132 133 134
};

FileManagerPrivate::FileManagerPrivate(QObject *q, QMainWindow *mw) :
con's avatar
con committed
135
    m_mainWindow(mw),
136
    m_fileWatcher(new QFileSystemWatcher(q)),
137 138 139
    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
140
    m_useProjectsDirectory(true),
141
#else
dt's avatar
dt committed
142
    m_useProjectsDirectory(false),
143
#endif
dt's avatar
dt committed
144
    m_blockedIFile(0)
con's avatar
con committed
145
{
146 147 148 149 150 151 152 153 154 155
}

} // namespace Internal

FileManager::FileManager(QMainWindow *mw)
  : QObject(mw),
    d(new Internal::FileManagerPrivate(this, mw))
{
    Core::ICore *core = Core::ICore::instance();
    connect(d->m_fileWatcher, SIGNAL(fileChanged(QString)),
hjk's avatar
hjk committed
156
        this, SLOT(changedFile(QString)));
157
    connect(d->m_mainWindow, SIGNAL(windowActivated()),
con's avatar
con committed
158
        this, SLOT(mainWindowActivated()));
hjk's avatar
hjk committed
159
    connect(core, SIGNAL(contextChanged(Core::IContext*,Core::Context)),
con's avatar
con committed
160 161
        this, SLOT(syncWithEditor(Core::IContext*)));

162
    readSettings();
con's avatar
con committed
163 164
}

165 166 167 168 169
FileManager::~FileManager()
{
    delete d;
}

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

con's avatar
con committed
173 174 175
    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
176 177 178

    Returns true if the file specified by \a files have not been yet part of the file list.
*/
Friedemann Kleint's avatar
Friedemann Kleint committed
179
bool FileManager::addFiles(const QList<IFile *> &files, bool addWatcher)
con's avatar
con committed
180
{
dt's avatar
dt committed
181 182 183 184 185 186 187 188 189 190
    if (!addWatcher) {
        // We keep those in a separate list

        foreach(IFile *file, files)
            connect(file, SIGNAL(destroyed(QObject *)), this, SLOT(fileDestroyed(QObject *)));

        d->m_filesWithoutWatch.append(files);
        return true;
    }

con's avatar
con committed
191 192
    bool filesAdded = false;
    foreach (IFile *file, files) {
193 194 195 196
        if (!file)
            continue;
        const QString &fixedFileName = fixFileName(file->fileName());
        if (d->m_states.value(fixedFileName).lastUpdatedState.contains(file))
con's avatar
con committed
197 198 199 200
            continue;
        connect(file, SIGNAL(changed()), this, SLOT(checkForNewFileName()));
        connect(file, SIGNAL(destroyed(QObject *)), this, SLOT(fileDestroyed(QObject *)));
        filesAdded = true;
201

dt's avatar
dt committed
202
        addFileInfo(file);
con's avatar
con committed
203 204 205 206
    }
    return filesAdded;
}

dt's avatar
dt committed
207
void FileManager::addFileInfo(IFile *file)
208 209 210 211 212 213 214 215 216 217 218 219
{
    // We do want to insert the IFile into d->m_states even if the filename is empty
    // Such that m_states always contains all IFiles

    const QString fixedname = fixFileName(file->fileName());
    Internal::FileStateItem item;
    if (!fixedname.isEmpty()) {
        const QFileInfo fi(file->fileName());
        item.modified = fi.lastModified();
        item.permissions = fi.permissions();
    }

dt's avatar
dt committed
220 221
    if (!d->m_states.contains(fixedname)) {
        d->m_states.insert(fixedname, Internal::FileState());
222
        if (!fixedname.isEmpty()) {
223
            d->m_fileWatcher->addPath(fixedname);
224
        }
225 226
    }

dt's avatar
dt committed
227
    d->m_states[fixedname].lastUpdatedState.insert(file, item);
228 229 230 231 232 233 234 235 236 237 238 239 240 241
}

void FileManager::updateFileInfo(IFile *file)
{
    const QString fixedname = fixFileName(file->fileName());
    // If the filename is empty there's nothing to do
    if (fixedname.isEmpty())
        return;
    const QFileInfo fi(file->fileName());

    Internal::FileStateItem item;
    item.modified = fi.lastModified();
    item.permissions = fi.permissions();

dt's avatar
dt committed
242 243
    if (d->m_states.contains(fixedname) && d->m_states.value(fixedname).lastUpdatedState.contains(file))
        d->m_states[fixedname].lastUpdatedState.insert(file, item);
244 245
}

dt's avatar
dt committed
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
/// Dumps the state of the file manager's map
/// For debugging purposes
void FileManager::dump()
{
    QMap<QString, Internal::FileState>::const_iterator it, end;
    it = d->m_states.constBegin();
    end = d->m_states.constEnd();
    for (; it != end; ++it) {
        qDebug()<<" ";
        qDebug() << it.key();
        qDebug() << it.value().expected.modified;

        QMap<IFile *, Internal::FileStateItem>::const_iterator jt, jend;
        jt = it.value().lastUpdatedState.constBegin();
        jend = it.value().lastUpdatedState.constEnd();
        for (; jt != jend; ++jt) {
            qDebug() << jt.key() << jt.value().modified;
        }
    }
}

void FileManager::renamedFile(const QString &from, QString &to)
{
    QString fixedFrom = fixFileName(from);
    QString fixedTo = fixFileName(to);
    if (d->m_states.contains(fixedFrom)) {
        QTC_ASSERT(!d->m_states.contains(to), return);
        d->m_states.insert(fixedTo, d->m_states.value(fixedFrom));
        d->m_states.remove(fixedFrom);
        QFileInfo fi(to);
        d->m_states[fixedTo].expected.modified = fi.lastModified();
        d->m_states[fixedTo].expected.permissions = fi.permissions();

        d->m_fileWatcher->removePath(fixedFrom);
        d->m_fileWatcher->addPath(fixedTo);

        QMap<IFile *, Internal::FileStateItem>::iterator it, end;
        it = d->m_states[fixedTo].lastUpdatedState.begin();
        end = d->m_states[fixedTo].lastUpdatedState.end();

        for ( ; it != end; ++it) {
            d->m_blockedIFile = it.key();
            it.key()->rename(to);
            d->m_blockedIFile = it.key();
            it.value().modified = fi.lastModified();
        }
    }
}

295 296 297 298 299 300
///
/// Does not use file->fileName, as such is save to use
/// with renamed files and deleted files
void FileManager::removeFileInfo(IFile *file)
{
    QString fileName;
dt's avatar
dt committed
301 302 303
    QMap<QString, Internal::FileState>::const_iterator it, end;
    end = d->m_states.constEnd();
    for (it = d->m_states.constBegin(); it != end; ++it) {
304 305 306 307 308 309 310 311 312 313 314 315
        if (it.value().lastUpdatedState.contains(file)) {
            fileName = it.key();
            break;
        }
    }

    removeFileInfo(fileName, file);
}

void FileManager::removeFileInfo(const QString &fileName, IFile *file)
{
    const QString &fixedName = fixFileName(fileName);
316 317 318 319 320 321 322 323
    if (d->m_states[fixedName].lastUpdatedState.contains(file)) {
        d->m_states[fixedName].lastUpdatedState.remove(file);

        if (d->m_states.value(fixedName).lastUpdatedState.isEmpty()) {
            d->m_states.remove(fixedName);
            if (!fixedName.isEmpty()) {
                d->m_fileWatcher->removePath(fixedName);
            }
324
        }
325 326 327
    } else {
        // We could not find the fileinfo, try harder to remove it
        removeFileInfo(file);
328 329 330
    }
}

con's avatar
con committed
331
/*!
con's avatar
con committed
332
    \fn bool FileManager::addFile(IFile *files, bool addWatcher)
con's avatar
con committed
333

con's avatar
con committed
334 335 336
    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
337 338 339

    Returns true if the file specified by \a file has not been yet part of the file list.
*/
Friedemann Kleint's avatar
Friedemann Kleint committed
340
bool FileManager::addFile(IFile *file, bool addWatcher)
con's avatar
con committed
341
{
Friedemann Kleint's avatar
Friedemann Kleint committed
342
    return addFiles(QList<IFile *>() << file, addWatcher);
con's avatar
con committed
343 344 345 346
}

void FileManager::fileDestroyed(QObject *obj)
{
347
    // removeFileInfo works even if the file does not really exist anymore
con's avatar
con committed
348
    IFile *file = static_cast<IFile*>(obj);
dt's avatar
dt committed
349 350 351 352 353
    // Check the special unwatched first:
    if (d->m_filesWithoutWatch.contains(file)) {
        d->m_filesWithoutWatch.removeOne(file);
        return;
    }
354
    removeFileInfo(file);
con's avatar
con committed
355 356 357 358 359 360 361 362 363 364 365 366 367 368
}

/*!
    \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.
*/
bool FileManager::removeFile(IFile *file)
{
    if (!file)
        return false;

dt's avatar
dt committed
369 370 371 372 373 374 375
    // Special casing unwatched files
    if (d->m_filesWithoutWatch.contains(file)) {
        disconnect(file, SIGNAL(destroyed(QObject *)), this, SLOT(fileDestroyed(QObject *)));
        d->m_filesWithoutWatch.removeOne(file);
        return true;
    }

con's avatar
con committed
376 377 378
    disconnect(file, SIGNAL(changed()), this, SLOT(checkForNewFileName()));
    disconnect(file, SIGNAL(destroyed(QObject *)), this, SLOT(fileDestroyed(QObject *)));

379
    removeFileInfo(file->fileName(), file);
con's avatar
con committed
380 381 382 383 384 385
    return true;
}

void FileManager::checkForNewFileName()
{
    IFile *file = qobject_cast<IFile *>(sender());
dt's avatar
dt committed
386 387 388 389
    // 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
390
    QTC_ASSERT(file, return);
391 392 393
    const QString &fileName = fixFileName(file->fileName());

    // check if the IFile is in the map
394
    if (d->m_states.value(fileName).lastUpdatedState.contains(file)) {
395 396 397
        // the file might have been deleted and written again, so guard against that
        d->m_fileWatcher->removePath(fileName);
        d->m_fileWatcher->addPath(fileName);
398 399
        updateFileInfo(file);
        return;
con's avatar
con committed
400
    }
401 402 403 404

    // Probably the name has changed...
    // This also updates the state to the on disk state
    removeFileInfo(file);
dt's avatar
dt committed
405
    addFileInfo(file);
con's avatar
con committed
406 407 408 409 410 411
}

// TODO Rename to nativeFileName
QString FileManager::fixFileName(const QString &fileName)
{
    QString s = fileName;
412 413 414 415 416
    QFileInfo fi(s);
    if (!fi.exists())
        s = QDir::toNativeSeparators(s);
    else
        s = QDir::toNativeSeparators(fi.canonicalFilePath());
con's avatar
con committed
417 418 419
#ifdef Q_OS_WIN
    s = s.toLower();
#endif
420
    return s;
con's avatar
con committed
421 422 423 424 425 426 427 428 429 430 431 432
}

/*!
    \fn bool FileManager::isFileManaged(const QString  &fileName) const

    Returns true if at least one IFile in the set points to \a fileName.
*/
bool FileManager::isFileManaged(const QString &fileName) const
{
    if (fileName.isEmpty())
        return false;

dt's avatar
dt committed
433 434
    // TOOD check d->m_filesWithoutWatch

435
    return !d->m_states.contains(fixFileName(fileName));
con's avatar
con committed
436 437 438 439 440 441 442 443 444 445 446
}

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

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

447 448 449 450
    QMap<QString, Internal::FileState>::const_iterator it, end;
    end = d->m_states.constEnd();
    for(it = d->m_states.constBegin(); it != end; ++it) {
        QMap<IFile *, Internal::FileStateItem>::const_iterator jt, jend;
dt's avatar
dt committed
451 452
        jt = (*it).lastUpdatedState.constBegin();
        jend = (*it).lastUpdatedState.constEnd();
453 454 455
        for( ; jt != jend; ++jt)
            if (jt.key()->isModified())
                modifiedFiles << jt.key();
con's avatar
con committed
456
    }
dt's avatar
dt committed
457 458 459 460 461
    foreach(IFile *file, d->m_filesWithoutWatch) {
        if (file->isModified())
            modifiedFiles << file;
    }

con's avatar
con committed
462 463 464 465 466 467 468 469 470 471
    return modifiedFiles;
}

/*!
    \fn void FileManager::blockFileChange(IFile *file)

    Blocks the monitoring of the file the \a file argument points to.
*/
void FileManager::blockFileChange(IFile *file)
{
472 473
    // Nothing to do
    Q_UNUSED(file);
con's avatar
con committed
474 475 476 477 478 479 480 481 482
}

/*!
    \fn void FileManager::unblockFileChange(IFile *file)

    Enables the monitoring of the file the \a file argument points to, and update the status of the corresponding IFile's.
*/
void FileManager::unblockFileChange(IFile *file)
{
483 484 485 486 487 488 489 490 491 492 493 494
    // 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);
    updateExpectedState(fixFileName(file->fileName()));
con's avatar
con committed
495 496
}

497 498 499 500 501 502 503 504
/*!
    \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
505
{
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
    // Nothing to do
    Q_UNUSED(fileName);
}

/*!
    \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

    updateExpectedState(fileName);
}

void FileManager::updateExpectedState(const QString &fileName)
{
    const QString &fixedName = fixFileName(fileName);
    if (fixedName.isEmpty())
        return;
    QFileInfo fi(fixedName);
dt's avatar
dt committed
533 534 535 536
    if (d->m_states.contains(fixedName)) {
        d->m_states[fixedName].expected.modified = fi.lastModified();
        d->m_states[fixedName].expected.permissions = fi.permissions();
    }
con's avatar
con committed
537 538 539 540 541 542 543 544 545 546 547 548 549
}

/*!
    \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
550 551 552 553 554 555 556 557 558 559
    \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
560 561
*/
QList<IFile *> FileManager::saveModifiedFiles(const QList<IFile *> &files,
562 563 564
                                              bool *cancelled, const QString &message,
                                              const QString &alwaysSaveMessage,
                                              bool *alwaysSave)
con's avatar
con committed
565
{
566
    return saveModifiedFiles(files, cancelled, false, message, alwaysSaveMessage, alwaysSave);
con's avatar
con committed
567 568 569 570 571
}

static QMessageBox::StandardButton skipFailedPrompt(QWidget *parent, const QString &fileName)
{
    return QMessageBox::question(parent,
572 573
                                 FileManager::tr("Cannot save file"),
                                 FileManager::tr("Cannot save changes to '%1'. Do you want to continue and lose your changes?").arg(fileName),
con's avatar
con committed
574 575 576 577 578
                                 QMessageBox::YesToAll| QMessageBox::Yes|QMessageBox::No,
                                 QMessageBox::No);
}

QList<IFile *> FileManager::saveModifiedFiles(const QList<IFile *> &files,
579 580 581 582 583
                                              bool *cancelled,
                                              bool silently,
                                              const QString &message,
                                              const QString &alwaysSaveMessage,
                                              bool *alwaysSave)
con's avatar
con committed
584 585 586 587 588
{
    if (cancelled)
        (*cancelled) = false;

    QList<IFile *> notSaved;
589 590
    QMap<IFile *, QString> modifiedFilesMap;
    QList<IFile *> modifiedFiles;
con's avatar
con committed
591 592 593 594 595 596 597 598 599

    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
600 601
            if (!(modifiedFilesMap.key(name, 0)
                    && file->isReadOnly()))
602
                modifiedFilesMap.insert(file, name);
con's avatar
con committed
603 604
        }
    }
605
    modifiedFiles = modifiedFilesMap.keys();
con's avatar
con committed
606 607 608
    if (!modifiedFiles.isEmpty()) {
        QList<IFile *> filesToSave;
        if (silently) {
609
            filesToSave = modifiedFiles;
con's avatar
con committed
610
        } else {
611
            Internal::SaveItemsDialog dia(d->m_mainWindow, modifiedFiles);
con's avatar
con committed
612 613
            if (!message.isEmpty())
                dia.setMessage(message);
614 615
            if (!alwaysSaveMessage.isNull())
                dia.setAlwaysSaveMessage(alwaysSaveMessage);
con's avatar
con committed
616 617 618
            if (dia.exec() != QDialog::Accepted) {
                if (cancelled)
                    (*cancelled) = true;
619 620
                if (alwaysSave)
                    *alwaysSave = dia.alwaysSaveChecked();
621
                notSaved = modifiedFiles;
con's avatar
con committed
622 623
                return notSaved;
            }
624 625
            if (alwaysSave)
                *alwaysSave = dia.alwaysSaveChecked();
con's avatar
con committed
626 627 628 629
            filesToSave = dia.itemsToSave();
        }

        bool yestoall = false;
630
        Core::VCSManager *vcsManager = Core::ICore::instance()->vcsManager();
con's avatar
con committed
631
        foreach (IFile *file, filesToSave) {
632
            if (file->isReadOnly()) {
633 634
                const QString directory = QFileInfo(file->fileName()).absolutePath();
                if (IVersionControl *versionControl = vcsManager->findVersionControlForDirectory(directory))
con's avatar
con committed
635 636 637 638 639 640 641 642 643 644 645 646
                    versionControl->vcsOpen(file->fileName());
            }
            if (!file->isReadOnly() && !file->fileName().isEmpty()) {
                blockFileChange(file);
                const bool ok = file->save();
                unblockFileChange(file);
                if (!ok)
                    notSaved.append(file);
            } else if (QFile::exists(file->fileName()) && !file->isSaveAsAllowed()) {
                if (yestoall)
                    continue;
                const QFileInfo fi(file->fileName());
647
                switch (skipFailedPrompt(d->m_mainWindow, fi.fileName())) {
con's avatar
con committed
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
                case QMessageBox::YesToAll:
                    yestoall = true;
                    break;
                case QMessageBox::No:
                    if (cancelled)
                        *cancelled = true;
                    return filesToSave;
                default:
                    break;
                }
            } else {
                QString fileName = getSaveAsFileName(file);
                bool ok = false;
                if (!fileName.isEmpty()) {
                    blockFileChange(file);
                    ok = file->save(fileName);
664
                    file->checkPermissions();
con's avatar
con committed
665 666 667 668 669 670 671 672 673 674
                    unblockFileChange(file);
                }
                if (!ok)
                    notSaved.append(file);
            }
        }
    }
    return notSaved;
}

675 676
QString FileManager::getSaveFileName(const QString &title, const QString &pathIn,
                                     const QString &filter, QString *selectedFilter)
con's avatar
con committed
677
{
678
    const QString &path = pathIn.isEmpty() ? fileDialogInitialDirectory() : pathIn;
con's avatar
con committed
679 680 681 682
    QString fileName;
    bool repeat;
    do {
        repeat = false;
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
        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
707
            if (QFile::exists(fileName)) {
708
                if (QMessageBox::warning(d->m_mainWindow, tr("Overwrite?"),
709 710 711
                    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
712
                    repeat = true;
713
                }
con's avatar
con committed
714 715 716
            }
        }
    } while (repeat);
717 718
    if (!fileName.isEmpty())
        setFileDialogLastVisitedDirectory(QFileInfo(fileName).absolutePath());
con's avatar
con committed
719 720 721
    return fileName;
}

722 723 724 725 726 727 728
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
729 730 731 732 733
/*!
    \fn QString FileManager::getSaveAsFileName(IFile *file)

    Asks the user for a new file name (Save File As) for /arg file.
*/
734
QString FileManager::getSaveAsFileName(IFile *file, const QString &filter, QString *selectedFilter)
con's avatar
con committed
735 736 737 738 739 740 741 742 743 744 745 746 747
{
    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;
    }
748

con's avatar
con committed
749
    QString filterString;
750 751 752 753 754 755
    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
756 757
    }

758
    absoluteFilePath = getSaveFileName(tr("Save File As"),
con's avatar
con committed
759 760
        path + QDir::separator() + fileName,
        filterString,
761
        selectedFilter);
con's avatar
con committed
762 763 764
    return absoluteFilePath;
}

765
/*!
con's avatar
con committed
766
    \fn QString FileManager::getOpenFileNames(const QString &filters, const QString &pathIn, QString *selectedFilter) const
767

con's avatar
con committed
768 769 770 771
    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.
772 773 774 775 776 777
*/

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


793
void FileManager::changedFile(const QString &fileName)
con's avatar
con committed
794
{
795
    const bool wasempty = d->m_changedFiles.isEmpty();
796 797 798 799 800

    const QString &fixedName = fixFileName(fileName);
    if (!d->m_changedFiles.contains(fixedName))
        d->m_changedFiles.append(fixedName);

801
    if (wasempty && !d->m_changedFiles.isEmpty()) {
802
        QTimer::singleShot(200, this, SLOT(checkForReload()));
con's avatar
con committed
803 804 805 806 807
    }
}

void FileManager::mainWindowActivated()
{
808 809 810 811
    //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
812 813 814 815
}

void FileManager::checkForReload()
{
816 817
    if (QApplication::activeWindow() != d->m_mainWindow)
        return;
con's avatar
con committed
818

819 820 821 822 823
    if (d->m_blockActivated)
        return;

    d->m_blockActivated = true;

824 825
    IFile::ReloadSetting defaultBehavior = EditorManager::instance()->reloadSetting();
    Utils::ReloadPromptAnswer previousAnswer = Utils::ReloadCurrent;
826

827 828 829 830
    QList<IEditor*> editorsToClose;
    QMap<IFile*, QString> filesToSave;
    QStringList modifiedFileNames;
    foreach (const QString &fileName, d->m_changedFiles) {
831
        // Get the information from the filesystem
832 833
        IFile::ChangeTrigger behavior = IFile::TriggerExternal;
        IFile::ChangeType type = IFile::TypeContents;
834
        QFileInfo fi(fileName);
835 836 837 838 839 840 841 842
        if (!fi.exists()) {
            type = IFile::TypeRemoved;
        } else {
            modifiedFileNames << fileName;
            if (fi.lastModified() == d->m_states.value(fileName).expected.modified
                && fi.permissions() == d->m_states.value(fileName).expected.permissions) {
                behavior = IFile::TriggerInternal;
            }
843 844 845 846 847 848 849 850
        }

        const QMap<IFile *, Internal::FileStateItem> &lastUpdated =
                d->m_states.value(fileName).lastUpdatedState;
        QMap<IFile *, Internal::FileStateItem>::const_iterator it, end;
        it = lastUpdated.constBegin();
        end = lastUpdated.constEnd();
        for ( ; it != end; ++it) {
851
            IFile *file = it.key();
dt's avatar
dt committed
852
            d->m_blockedIFile = file;
853 854 855 856
            // Compare
            if (it.value().modified == fi.lastModified()
                && it.value().permissions == fi.permissions()) {
                // Already up to date
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
                continue;
            }
            // we've got some modification
            // check if it's contents or permissions:
            if (it.value().modified == fi.lastModified()) {
                // Only permission change
                file->reload(IFile::FlagReload, IFile::TypePermissions);
            // 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)
                file->reload(IFile::FlagReload, type);
            // 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
                file->reload(IFile::FlagIgnore, type);
            // 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
877
            } else {
878 879 880 881 882 883 884 885 886 887 888 889 890
                // check if IFile wants us to ask
                if (file->reloadBehavior(behavior, type) == IFile::BehaviorSilent) {
                    // content change or removed, IFile wants silent handling
                    file->reload(IFile::FlagReload, type);
                // 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
                        file->reload(IFile::FlagIgnore, IFile::TypeContents);
                    } else if (previousAnswer == Utils::ReloadAll) {
                        // answer already given, reload
                        file->reload(IFile::FlagReload, IFile::TypeContents);
891
                    } else {
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
                        // Ask about content change
                        previousAnswer = Utils::reloadPrompt(fileName, file->isModified(), QApplication::activeWindow());
                        switch (previousAnswer) {
                        case Utils::ReloadAll:
                        case Utils::ReloadCurrent:
                            file->reload(IFile::FlagReload, IFile::TypeContents);
                            break;
                        case Utils::ReloadSkipCurrent:
                        case Utils::ReloadNone:
                            file->reload(IFile::FlagIgnore, IFile::TypeContents);
                            break;
                        }
                    }
                // IFile wants us to ask, and it's the TypeRemoved case
                } else {
                    // Ask about removed file
                    bool unhandled = true;
                    while (unhandled) {
                        switch (Utils::fileDeletedPrompt(fileName, QApplication::activeWindow())) {
                        case Utils::FileDeletedSave:
                            filesToSave.insert(file, fileName);
                            unhandled = false;
                            break;
                        case Utils::FileDeletedSaveAs:
                            {
                                const QString &saveFileName = getSaveAsFileName(file);
                                if (!saveFileName.isEmpty()) {
                                    filesToSave.insert(file, saveFileName);
                                    unhandled = false;
                                }
                                break;
                            }
                        case Utils::FileDeletedClose:
                            editorsToClose << EditorManager::instance()->editorsForFile(file);
                            unhandled = false;
                            break;
                        }
929 930
                    }
                }
con's avatar
con committed
931
            }
932 933

            updateFileInfo(file);
dt's avatar
dt committed
934
            d->m_blockedIFile = 0;
con's avatar
con committed
935 936
        }
    }
937 938 939 940 941

    // cleanup
    if (!modifiedFileNames.isEmpty()) {
        d->m_fileWatcher->removePaths(modifiedFileNames);
        d->m_fileWatcher->addPaths(modifiedFileNames);
942
    }
943
    d->m_changedFiles.clear();
944 945 946 947 948 949 950 951 952

    // handle deleted files
    EditorManager::instance()->closeEditors(editorsToClose, false);
    QMapIterator<IFile *, QString> it(filesToSave);
    while (it.hasNext()) {
        it.next();
        blockFileChange(it.key());
        it.key()->save(it.value());
        unblockFileChange(it.key());
953
        it.key()->checkPermissions();
954 955
    }

956
    d->m_blockActivated = false;
con's avatar
con committed
957 958 959 960 961 962 963
}

void FileManager::syncWithEditor(Core::IContext *context)
{
    if (!context)
        return;

964
    Core::IEditor *editor = Core::EditorManager::instance()->currentEditor();
965 966
    if (editor && (editor->widget() == context->widget()) &&
        !editor->isTemporary())
con's avatar
con committed
967 968 969 970 971 972 973 974 975 976 977 978
        setCurrentFile(editor->file()->fileName());
}

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

    Adds the \a fileName to the list of recent files.
*/
void FileManager::addToRecentFiles(const QString &fileName)
{
    if (fileName.isEmpty())
        return;
979 980 981 982 983 984 985
    QString unifiedForm(fixFileName(fileName));
    QMutableStringListIterator it(d->m_recentFiles);
    while (it.hasNext()) {
        QString recentUnifiedForm(fixFileName(it.next()));
        if (unifiedForm == recentUnifiedForm)
            it.remove();
    }
986 987
    if (d->m_recentFiles.count() > d->m_maxRecentFiles)
        d->m_recentFiles.removeLast();
988
    d->m_recentFiles.prepend(fileName);
con's avatar
con committed
989 990 991 992 993 994 995 996 997
}

/*!
    \fn QStringList FileManager::recentFiles() const

    Returns the list of recent files.
*/
QStringList FileManager::recentFiles() const
{
998
    return d->m_recentFiles;
con's avatar
con committed
999 1000
}

1001
void FileManager::saveSettings()
con's avatar
con committed
1002
{
1003
    QSettings *s = Core::ICore::instance()->settings();
1004 1005 1006 1007 1008 1009
    s->beginGroup(QLatin1String(settingsGroupC));
    s->setValue(QLatin1String(filesKeyC), d->m_recentFiles);
    s->endGroup();
    s->beginGroup(QLatin1String(directoryGroupC));
    s->setValue(QLatin1String(projectDirectoryKeyC), d->m_projectsDirectory);
    s->setValue(QLatin1String(useProjectDirectoryKeyC), d->m_useProjectsDirectory);
con's avatar
con committed
1010 1011 1012
    s->endGroup();
}

1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
void FileManager::readSettings()
{
    const QSettings *s = Core::ICore::instance()->settings();
    d->m_recentFiles.clear();
    QStringList recentFiles = s->value(QLatin1String(settingsGroupC) + QLatin1Char('/') + QLatin1String(filesKeyC), QStringList()).toStringList();
    // clean non-existing files
    foreach (const QString &file, recentFiles) {
        if (QFileInfo(file).isFile())
            d->m_recentFiles.append(QDir::fromNativeSeparators(file)); // from native to guard against old settings
    }

    const QString directoryGroup = QLatin1String(directoryGroupC) + QLatin1Char('/');
    const QString settingsProjectDir = s->value(directoryGroup + QLatin1String(projectDirectoryKeyC),
                                       QString()).toString();
    if (!settingsProjectDir.isEmpty() && QFileInfo(settingsProjectDir).isDir()) {
        d->m_projectsDirectory = settingsProjectDir;
    } else {
        d->m_projectsDirectory = Utils::PathChooser::homePath();
    }
    d->m_useProjectsDirectory = s->value(directoryGroup + QLatin1String(useProjectDirectoryKeyC),
                                         d->m_useProjectsDirectory).toBool();
}

con's avatar
con committed
1036 1037 1038 1039 1040
/*!

  The current file is e.g. the file currently opened when an editor is active,
  or the selected file in case a Project Explorer is active ...

con's avatar
con committed
1041
  \sa currentFile
con's avatar
con committed
1042 1043 1044
  */
void FileManager::setCurrentFile(const QString &filePath)
{
1045
    if (d->m_currentFile == filePath)
con's avatar
con committed
1046
        return;
1047 1048
    d->m_currentFile = filePath;
    emit currentFileChanged(d->m_currentFile);
con's avatar
con committed
1049 1050 1051 1052 1053 1054 1055 1056
}

/*!
  Returns the absolute path of the current file

  The current file is e.g. the file currently opened when an editor is active,
  or the selected file in case a Project Explorer is active ...

con's avatar
con committed
1057
  \sa setCurrentFile
con's avatar
con committed
1058 1059 1060
  */
QString FileManager::currentFile() const
{
1061
    return d->m_currentFile;
con's avatar
con committed
1062 1063
}

1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
/*!

  Returns the initial directory for a new file dialog. If there is
  a current file, use that, else use last visited directory.

  \sa setFileDialogLastVisitedDirectory
*/

QString FileManager::fileDialogInitialDirectory() const
{
    if (!d->m_currentFile.isEmpty())
1075
        return QFileInfo(d->m_currentFile).absolutePath();
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
    return d->m_lastVisitedDirectory;
}

/*!

  Returns the directory for projects. Defaults to HOME.

  \sa setProjectsDirectory, setUseProjectsDirectory
*/

QString FileManager::projectsDirectory() const
{
    return d->m_projectsDirectory;
}

/*!

  Set the directory for projects.

  \sa projectsDirectory, useProjectsDirectory
*/

void FileManager::setProjectsDirectory(const QString &dir)
{
    d->m_projectsDirectory = dir;
}

/*!

  Returns whether the directory for projects is to be
  used or the user wants the current directory.

  \sa setProjectsDirectory, setUseProjectsDirectory
*/

bool FileManager::useProjectsDirectory() const
{
    return d->m_useProjectsDirectory;
}

/*!

  Sets whether the directory for projects is to be used.

  \sa projectsDirectory, useProjectsDirectory
*/

void FileManager::setUseProjectsDirectory(bool useProjectsDirectory)
{
    d->m_useProjectsDirectory = useProjectsDirectory;
}

/*!

  Returns last visited directory of a file dialog.

  \sa setFileDialogLastVisitedDirectory, fileDialogInitialDirectory

*/

QString FileManager::fileDialogLastVisitedDirectory() const
{
    return d->m_lastVisitedDirectory;
}

/*!

  Set the last visited directory of a file dialog that will be remembered
  for the next one.

  \sa fileDialogLastVisitedDirectory, fileDialogInitialDirectory

  */

void FileManager::setFileDialogLastVisitedDirectory(const QString &directory)
{
    d->m_lastVisitedDirectory = directory;
}

1155 1156 1157 1158 1159
void FileManager::notifyFilesChangedInternally(const QStringList &files)
{
    emit filesChangedInternally(files);
}

1160 1161
// -------------- FileChangeBlocker

1162
FileChangeBlocker::FileChangeBlocker(const QString &fileName)
1163
    : m_fileName(fileName)
1164 1165
{
    Core::FileManager *fm = Core::ICore::instance()->fileManager();
1166
    fm->expectFileChange(fileName);
1167 1168 1169 1170 1171
}

FileChangeBlocker::~FileChangeBlocker()
{
    Core::FileManager *fm = Core::ICore::instance()->fileManager();
1172
    fm->unexpectFileChange(m_fileName);
1173
}
1174 1175

} // namespace Core