filemanager.cpp 29.5 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 40
#include "saveitemsdialog.h"
#include "vcsmanager.h"

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

con's avatar
con committed
44 45 46 47 48 49
#include <QtCore/QSettings>
#include <QtCore/QFileInfo>
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtCore/QTimer>
#include <QtCore/QFileSystemWatcher>
50
#include <QtCore/QDateTime>
con's avatar
con committed
51 52
#include <QtGui/QFileDialog>
#include <QtGui/QMessageBox>
53
#include <QtGui/QMainWindow>
con's avatar
con committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67

/*!
  \class FileManager
  \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
68
  filesystem. The monitoring for a IFile can be blocked by blockFileChange(), and
con's avatar
con committed
69 70
  enabled again by unblockFileChange().

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

84 85 86 87 88 89
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
90

91 92 93
namespace Core {
namespace Internal {

94
struct FileStateItem
95 96 97 98 99
{
    QDateTime modified;
    QFile::Permissions permissions;
};

100 101
struct FileState
{
Friedemann Kleint's avatar
Friedemann Kleint committed
102
    FileState() : watched(false) {}
103 104
    QMap<IFile *, FileStateItem> lastUpdatedState;
    FileStateItem expected;
Friedemann Kleint's avatar
Friedemann Kleint committed
105
    bool watched;
106 107
};

108 109
struct FileManagerPrivate {
    explicit FileManagerPrivate(QObject *q, QMainWindow *mw);
Friedemann Kleint's avatar
Friedemann Kleint committed
110
    typedef QMap<QString, FileState> NameFileStateMap;
111

Friedemann Kleint's avatar
Friedemann Kleint committed
112
    NameFileStateMap m_states;
113
    QStringList m_changedFiles;
114 115 116 117 118 119 120 121 122

    QStringList m_recentFiles;
    static const int m_maxRecentFiles = 7;

    QString m_currentFile;

    QMainWindow *m_mainWindow;
    QFileSystemWatcher *m_fileWatcher;
    bool m_blockActivated;
123 124 125
    QString m_lastVisitedDirectory;
    QString m_projectsDirectory;
    bool m_useProjectsDirectory;
126 127 128
};

FileManagerPrivate::FileManagerPrivate(QObject *q, QMainWindow *mw) :
con's avatar
con committed
129
    m_mainWindow(mw),
130
    m_fileWatcher(new QFileSystemWatcher(q)),
131 132 133 134 135 136 137
    m_blockActivated(false),
    m_lastVisitedDirectory(QDir::currentPath()),
#ifdef Q_OS_MAC  // Creator is in bizarre places when launched via finder.
    m_useProjectsDirectory(true)
#else
    m_useProjectsDirectory(false)
#endif
con's avatar
con committed
138
{
139 140 141 142 143 144 145 146 147 148
}

} // 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
149
        this, SLOT(changedFile(QString)));
150
    connect(d->m_mainWindow, SIGNAL(windowActivated()),
con's avatar
con committed
151
        this, SLOT(mainWindowActivated()));
152
    connect(core, SIGNAL(contextChanged(Core::IContext*)),
con's avatar
con committed
153 154
        this, SLOT(syncWithEditor(Core::IContext*)));

155
    const QSettings *s = core->settings();
156
    d->m_recentFiles = s->value(QLatin1String(settingsGroupC) + QLatin1Char('/') + QLatin1String(filesKeyC), QStringList()).toStringList();
157
    for (QStringList::iterator it = d->m_recentFiles.begin(); it != d->m_recentFiles.end(); ) {
con's avatar
con committed
158 159 160
        if (QFileInfo(*it).isFile()) {
            ++it;
        } else {
161
            it = d->m_recentFiles.erase(it);
con's avatar
con committed
162 163
        }
    }
164
    const QString directoryGroup = QLatin1String(directoryGroupC) + QLatin1Char('/');
165 166 167 168 169 170 171
    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();
    }
172 173
    d->m_useProjectsDirectory = s->value(directoryGroup + QLatin1String(useProjectDirectoryKeyC),
                                         d->m_useProjectsDirectory).toBool();
con's avatar
con committed
174 175
}

176 177 178 179 180
FileManager::~FileManager()
{
    delete d;
}

con's avatar
con committed
181 182 183 184 185 186 187
/*!
    \fn bool FileManager::addFiles(const QList<IFile *> &files)

    Adds a list of IFile's to the collection.

    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
188
bool FileManager::addFiles(const QList<IFile *> &files, bool addWatcher)
con's avatar
con committed
189 190 191
{
    bool filesAdded = false;
    foreach (IFile *file, files) {
192 193 194 195
        if (!file)
            continue;
        const QString &fixedFileName = fixFileName(file->fileName());
        if (d->m_states.value(fixedFileName).lastUpdatedState.contains(file))
con's avatar
con committed
196 197 198 199
            continue;
        connect(file, SIGNAL(changed()), this, SLOT(checkForNewFileName()));
        connect(file, SIGNAL(destroyed(QObject *)), this, SLOT(fileDestroyed(QObject *)));
        filesAdded = true;
200

Friedemann Kleint's avatar
Friedemann Kleint committed
201
        addFileInfo(file, addWatcher);
con's avatar
con committed
202 203 204 205
    }
    return filesAdded;
}

Friedemann Kleint's avatar
Friedemann Kleint committed
206
void FileManager::addFileInfo(IFile *file, bool addWatcher)
207
{
Friedemann Kleint's avatar
Friedemann Kleint committed
208
    typedef Internal::FileManagerPrivate::NameFileStateMap NameFileStateMap;
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();
    }

Friedemann Kleint's avatar
Friedemann Kleint committed
220 221 222 223 224 225 226
    // Ensure entry
    NameFileStateMap::iterator it = d->m_states.find(fixedname);
    if (it == d->m_states.end()) {
        Internal::FileState state;
        state.watched = addWatcher;
        it = d->m_states.insert(fixedname, state);
        if (addWatcher && !fixedname.isEmpty()) {
227
            d->m_fileWatcher->addPath(fixedname);
Friedemann Kleint's avatar
Friedemann Kleint committed
228
        }
229 230
    }

Friedemann Kleint's avatar
Friedemann Kleint committed
231
    it.value().lastUpdatedState.insert(file, item);
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
}

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

    d->m_states[fixedname].lastUpdatedState.insert(file, item);
}

///
/// Does not use file->fileName, as such is save to use
/// with renamed files and deleted files
void FileManager::removeFileInfo(IFile *file)
{
Friedemann Kleint's avatar
Friedemann Kleint committed
254
    typedef Internal::FileManagerPrivate::NameFileStateMap NameFileStateMap;
255
    QString fileName;
Friedemann Kleint's avatar
Friedemann Kleint committed
256 257
    const NameFileStateMap::const_iterator end = d->m_states.constEnd();
    for (NameFileStateMap::const_iterator it = d->m_states.constBegin(); it != end; ++it) {
258 259 260 261 262 263 264 265 266 267 268 269 270 271
        if (it.value().lastUpdatedState.contains(file)) {
            fileName = it.key();
            break;
        }
    }

    // The filename might be empty but not null
    Q_ASSERT(fileName != QString::null);

    removeFileInfo(fileName, file);
}

void FileManager::removeFileInfo(const QString &fileName, IFile *file)
{
Friedemann Kleint's avatar
Friedemann Kleint committed
272
    typedef Internal::FileManagerPrivate::NameFileStateMap NameFileStateMap;
273 274
    const QString &fixedName = fixFileName(fileName);

Friedemann Kleint's avatar
Friedemann Kleint committed
275 276 277 278 279 280 281
    NameFileStateMap::iterator it = d->m_states.find(fixedName);
    QTC_ASSERT(it != d->m_states.end(), return);

    it.value().lastUpdatedState.remove(file);

    if (it.value().lastUpdatedState.isEmpty()) {
        if (!fixedName.isEmpty() && it.value().watched) {
282
            d->m_fileWatcher->removePath(fixedName);
Friedemann Kleint's avatar
Friedemann Kleint committed
283 284
        }
        d->m_states.erase(it);
285 286 287
    }
}

con's avatar
con committed
288 289 290 291 292 293 294
/*!
    \fn bool FileManager::addFile(IFile *files)

    Adds a IFile object to the collection.

    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
295
bool FileManager::addFile(IFile *file, bool addWatcher)
con's avatar
con committed
296
{
Friedemann Kleint's avatar
Friedemann Kleint committed
297
    return addFiles(QList<IFile *>() << file, addWatcher);
con's avatar
con committed
298 299 300 301
}

void FileManager::fileDestroyed(QObject *obj)
{
302
    // removeFileInfo works even if the file does not really exist anymore
con's avatar
con committed
303
    IFile *file = static_cast<IFile*>(obj);
304
    removeFileInfo(file);
con's avatar
con committed
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
}

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

    disconnect(file, SIGNAL(changed()), this, SLOT(checkForNewFileName()));
    disconnect(file, SIGNAL(destroyed(QObject *)), this, SLOT(fileDestroyed(QObject *)));

322
    removeFileInfo(file->fileName(), file);
con's avatar
con committed
323 324 325 326 327
    return true;
}

void FileManager::checkForNewFileName()
{
Friedemann Kleint's avatar
Friedemann Kleint committed
328
    typedef Internal::FileManagerPrivate::NameFileStateMap NameFileStateMap;
con's avatar
con committed
329
    IFile *file = qobject_cast<IFile *>(sender());
hjk's avatar
hjk committed
330
    QTC_ASSERT(file, return);
331 332 333
    const QString &fileName = fixFileName(file->fileName());

    // check if the IFile is in the map
Friedemann Kleint's avatar
Friedemann Kleint committed
334 335
    const NameFileStateMap::const_iterator nfit = d->m_states.constFind(fileName);
    if (nfit != d->m_states.constEnd() && nfit.value().lastUpdatedState.contains(file)) {
336 337 338
        // Should checkForNewFileName also call updateFileInfo if the name didn't change?
        updateFileInfo(file);
        return;
con's avatar
con committed
339
    }
340 341 342 343

    // Probably the name has changed...
    // This also updates the state to the on disk state
    removeFileInfo(file);
Friedemann Kleint's avatar
Friedemann Kleint committed
344 345
    const bool wasWatched = nfit != d->m_states.constEnd() && nfit.value().watched;
    addFileInfo(file, wasWatched);
con's avatar
con committed
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
}

// TODO Rename to nativeFileName
QString FileManager::fixFileName(const QString &fileName)
{
    QString s = fileName;
#ifdef Q_OS_WIN
    s = s.toLower();
#endif
    if (!QFile::exists(s))
        return QDir::toNativeSeparators(s);
    return QFileInfo(QDir::toNativeSeparators(s)).canonicalFilePath();
}

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

370
    return !d->m_states.contains(fixFileName(fileName));
con's avatar
con committed
371 372 373 374 375 376 377 378 379 380 381
}

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

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

382 383 384 385 386 387 388 389 390
    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;
        jt = it.value().lastUpdatedState.constBegin();
        jend = it.value().lastUpdatedState.constEnd();
        for( ; jt != jend; ++jt)
            if (jt.key()->isModified())
                modifiedFiles << jt.key();
con's avatar
con committed
391 392 393 394 395 396 397 398 399 400 401
    }
    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)
{
402 403
    // Nothing to do
    Q_UNUSED(file);
con's avatar
con committed
404 405 406 407 408 409 410 411 412
}

/*!
    \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)
{
413 414 415 416 417 418 419 420 421 422 423 424
    // 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
425 426
}

427 428 429 430 431 432 433 434
/*!
    \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
435
{
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
    // 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);
    d->m_states[fixedName].expected.modified = fi.lastModified();
    d->m_states[fixedName].expected.permissions = fi.permissions();
con's avatar
con committed
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
}

/*!
    \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());
}

/*!
    \fn QList<IFile*> FileManager::saveModifiedFiles(const QList<IFile*> &files, bool *cancelled, const QString &message)

    Asks the user whether to save the files listed in \a files . Returns the files that have not been saved.
*/
QList<IFile *> FileManager::saveModifiedFiles(const QList<IFile *> &files,
483 484 485
                                              bool *cancelled, const QString &message,
                                              const QString &alwaysSaveMessage,
                                              bool *alwaysSave)
con's avatar
con committed
486
{
487
    return saveModifiedFiles(files, cancelled, false, message, alwaysSaveMessage, alwaysSave);
con's avatar
con committed
488 489 490 491 492
}

static QMessageBox::StandardButton skipFailedPrompt(QWidget *parent, const QString &fileName)
{
    return QMessageBox::question(parent,
493 494
                                 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
495 496 497 498 499
                                 QMessageBox::YesToAll| QMessageBox::Yes|QMessageBox::No,
                                 QMessageBox::No);
}

QList<IFile *> FileManager::saveModifiedFiles(const QList<IFile *> &files,
500 501 502 503 504
                                              bool *cancelled,
                                              bool silently,
                                              const QString &message,
                                              const QString &alwaysSaveMessage,
                                              bool *alwaysSave)
con's avatar
con committed
505 506 507 508 509
{
    if (cancelled)
        (*cancelled) = false;

    QList<IFile *> notSaved;
510 511
    QMap<IFile *, QString> modifiedFilesMap;
    QList<IFile *> modifiedFiles;
con's avatar
con committed
512 513 514 515 516 517 518 519 520

    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
521 522
            if (!(modifiedFilesMap.key(name, 0)
                    && file->isReadOnly()))
523
                modifiedFilesMap.insert(file, name);
con's avatar
con committed
524 525
        }
    }
526
    modifiedFiles = modifiedFilesMap.keys();
con's avatar
con committed
527 528 529
    if (!modifiedFiles.isEmpty()) {
        QList<IFile *> filesToSave;
        if (silently) {
530
            filesToSave = modifiedFiles;
con's avatar
con committed
531
        } else {
532
            Internal::SaveItemsDialog dia(d->m_mainWindow, modifiedFiles);
con's avatar
con committed
533 534
            if (!message.isEmpty())
                dia.setMessage(message);
535 536
            if (!alwaysSaveMessage.isNull())
                dia.setAlwaysSaveMessage(alwaysSaveMessage);
con's avatar
con committed
537 538 539
            if (dia.exec() != QDialog::Accepted) {
                if (cancelled)
                    (*cancelled) = true;
540 541
                if (alwaysSave)
                    *alwaysSave = dia.alwaysSaveChecked();
542
                notSaved = modifiedFiles;
con's avatar
con committed
543 544
                return notSaved;
            }
545 546
            if (alwaysSave)
                *alwaysSave = dia.alwaysSaveChecked();
con's avatar
con committed
547 548 549 550
            filesToSave = dia.itemsToSave();
        }

        bool yestoall = false;
551
        Core::VCSManager *vcsManager = Core::ICore::instance()->vcsManager();
con's avatar
con committed
552
        foreach (IFile *file, filesToSave) {
553
            if (file->isReadOnly()) {
554 555
                const QString directory = QFileInfo(file->fileName()).absolutePath();
                if (IVersionControl *versionControl = vcsManager->findVersionControlForDirectory(directory))
con's avatar
con committed
556 557 558 559 560 561 562 563 564 565 566 567
                    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());
568
                switch (skipFailedPrompt(d->m_mainWindow, fi.fileName())) {
con's avatar
con committed
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
                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);
585
                    file->checkPermissions();
con's avatar
con committed
586 587 588 589 590 591 592 593 594 595
                    unblockFileChange(file);
                }
                if (!ok)
                    notSaved.append(file);
            }
        }
    }
    return notSaved;
}

596
QString FileManager::getSaveFileNameWithExtension(const QString &title, const QString &pathIn,
con's avatar
con committed
597 598 599 600 601 602
    const QString &fileFilter, const QString &extension)
{
    QString fileName;
    bool repeat;
    do {
        repeat = false;
603
        const QString path = pathIn.isEmpty() ? fileDialogInitialDirectory() : pathIn;
604
        fileName = QFileDialog::getSaveFileName(d->m_mainWindow, title, path, fileFilter);
con's avatar
con committed
605 606 607
        if (!fileName.isEmpty() && !extension.isEmpty() && !fileName.endsWith(extension)) {
            fileName.append(extension);
            if (QFile::exists(fileName)) {
608
                if (QMessageBox::warning(d->m_mainWindow, tr("Overwrite?"),
con's avatar
con committed
609 610 611 612 613 614
                        tr("An item named '%1' already exists at this location. Do you want to overwrite it?").arg(fileName),
                        QMessageBox::Yes | QMessageBox::No) == QMessageBox::No)
                    repeat = true;
            }
        }
    } while (repeat);
615 616
    if (!fileName.isEmpty())
        setFileDialogLastVisitedDirectory(QFileInfo(fileName).absolutePath());
con's avatar
con committed
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
    return fileName;
}

/*!
    \fn QString FileManager::getSaveAsFileName(IFile *file)

    Asks the user for a new file name (Save File As) for /arg file.
*/
QString FileManager::getSaveAsFileName(IFile *file)
{
    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;
    }
    QString filterString;
    QString preferredSuffix;
hjk's avatar
hjk committed
641
    if (const MimeType mt = Core::ICore::instance()->mimeDatabase()->findByFile(fi)) {
con's avatar
con committed
642 643 644 645 646 647 648 649 650 651 652
        filterString = mt.filterString();
        preferredSuffix = mt.preferredSuffix();
    }

    absoluteFilePath = getSaveFileNameWithExtension(tr("Save File As"),
        path + QDir::separator() + fileName,
        filterString,
        preferredSuffix);
    return absoluteFilePath;
}

653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
/*!
    \fn QString FileManager::getOpenFileNames(const QStringList &filters, QString *selectedFilter) const

    Asks the user for a set of file names to be opened.
*/

QStringList FileManager::getOpenFileNames(const QString &filters,
                                          const QString pathIn,
                                          QString *selectedFilter)
{
    const QString path = pathIn.isEmpty() ? fileDialogInitialDirectory() : pathIn;
    const QStringList files = QFileDialog::getOpenFileNames(d->m_mainWindow,
                                                      tr("Open File"),
                                                      path, filters,
                                                      selectedFilter);
    if (!files.isEmpty())
        setFileDialogLastVisitedDirectory(QFileInfo(files.front()).absolutePath());
    return files;
}


674
void FileManager::changedFile(const QString &fileName)
con's avatar
con committed
675
{
676
    const bool wasempty = d->m_changedFiles.isEmpty();
677 678 679 680 681

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

682
    if (wasempty && !d->m_changedFiles.isEmpty()) {
683
        QTimer::singleShot(200, this, SLOT(checkForReload()));
con's avatar
con committed
684 685 686 687 688
    }
}

void FileManager::mainWindowActivated()
{
689 690 691 692
    //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
693 694 695 696
}

void FileManager::checkForReload()
{
697 698
    if (QApplication::activeWindow() != d->m_mainWindow)
        return;
con's avatar
con committed
699

700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
    if (d->m_blockActivated)
        return;

    d->m_blockActivated = true;

    IFile::ReloadBehavior behavior = EditorManager::instance()->reloadBehavior();

    foreach(const QString &fileName, d->m_changedFiles) {
        // Get the information from the filesystem
        QFileInfo fi(fileName);
        bool expected = false;
        if (fi.lastModified() == d->m_states.value(fileName).expected.modified
            && fi.permissions() == d->m_states.value(fileName).expected.permissions) {
            expected = true;
        }

        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) {
            // Compare
            if (it.value().modified == fi.lastModified()
                && it.value().permissions == fi.permissions()) {
                // Already up to date
            } else {
                // Update IFile
                if (expected) {
                    IFile::ReloadBehavior tempBeh = IFile::ReloadUnmodified;
                    it.key()->modified(&tempBeh);
                } else {
                    if (it.value().modified == fi.lastModified()) {
                        // Only permission change
                        IFile::ReloadBehavior tempBeh = IFile::ReloadPermissions;
                        it.key()->modified(&tempBeh);
                    } else {
                        it.key()->modified(&behavior);
                    }
                }
                updateFileInfo(it.key());
con's avatar
con committed
742
            }
743

con's avatar
con committed
744
        }
745 746 747

        d->m_fileWatcher->removePath(fileName);
        d->m_fileWatcher->addPath(fileName);
con's avatar
con committed
748
    }
749 750 751

    d->m_changedFiles.clear();
    d->m_blockActivated = false;
con's avatar
con committed
752 753 754 755 756 757 758
}

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

759
    Core::IEditor *editor = Core::EditorManager::instance()->currentEditor();
con's avatar
con committed
760 761 762 763 764 765 766 767 768 769 770 771 772 773
    if (editor && (editor->widget() == context->widget()))
        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;
    QString prettyFileName(QDir::toNativeSeparators(fileName));
774 775 776 777
    d->m_recentFiles.removeAll(prettyFileName);
    if (d->m_recentFiles.count() > d->m_maxRecentFiles)
        d->m_recentFiles.removeLast();
    d->m_recentFiles.prepend(prettyFileName);
con's avatar
con committed
778 779 780 781 782 783 784 785 786
}

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

    Returns the list of recent files.
*/
QStringList FileManager::recentFiles() const
{
787
    return d->m_recentFiles;
con's avatar
con committed
788 789 790 791
}

void FileManager::saveRecentFiles()
{
792
    QSettings *s = Core::ICore::instance()->settings();
793 794 795 796 797 798
    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
799 800 801 802 803 804 805 806
    s->endGroup();
}

/*!

  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
807
  \sa currentFile
con's avatar
con committed
808 809 810
  */
void FileManager::setCurrentFile(const QString &filePath)
{
811
    if (d->m_currentFile == filePath)
con's avatar
con committed
812
        return;
813 814
    d->m_currentFile = filePath;
    emit currentFileChanged(d->m_currentFile);
con's avatar
con committed
815 816 817 818 819 820 821 822
}

/*!
  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
823
  \sa setCurrentFile
con's avatar
con committed
824 825 826
  */
QString FileManager::currentFile() const
{
827
    return d->m_currentFile;
con's avatar
con committed
828 829
}

830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
/*!

  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())
        return QFileInfo(d->m_currentFile).absolutePath();
    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;
}

921 922 923 924 925
void FileManager::notifyFilesChangedInternally(const QStringList &files)
{
    emit filesChangedInternally(files);
}

926 927
// -------------- FileChangeBlocker

928
FileChangeBlocker::FileChangeBlocker(const QString &fileName)
929
    : m_fileName(fileName)
930 931
{
    Core::FileManager *fm = Core::ICore::instance()->fileManager();
932
    fm->expectFileChange(fileName);
933 934 935 936 937
}

FileChangeBlocker::~FileChangeBlocker()
{
    Core::FileManager *fm = Core::ICore::instance()->fileManager();
938
    fm->unexpectFileChange(m_fileName);
939
}
940 941

} // namespace Core