filemanager.cpp 25.6 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2 3 4
**
** This file is part of Qt Creator
**
5
** Copyright (c) 2009 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 50
#include <QtCore/QDebug>
#include <QtCore/QSettings>
#include <QtCore/QFileInfo>
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtCore/QTimer>
#include <QtCore/QFileSystemWatcher>
51
#include <QtCore/QDateTime>
con's avatar
con committed
52 53
#include <QtGui/QFileDialog>
#include <QtGui/QMessageBox>
54
#include <QtGui/QMainWindow>
con's avatar
con committed
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80

/*!
  \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
  filesystem. The monitoring of a file can be blocked by blockFileChange(), and
  enabled again by unblockFileChange().

  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()).
 */

81 82 83 84 85 86
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
87

88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
namespace Core {
namespace Internal {

struct FileInfo
{
    QString fileName;
    QDateTime modified;
    QFile::Permissions permissions;
};

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

    QMap<IFile*, FileInfo> m_managedFiles;

    QStringList m_recentFiles;
    static const int m_maxRecentFiles = 7;

    QString m_currentFile;

    QMainWindow *m_mainWindow;
    QFileSystemWatcher *m_fileWatcher;
    QList<QPointer<IFile> > m_changedFiles;
    bool m_blockActivated;
112 113 114
    QString m_lastVisitedDirectory;
    QString m_projectsDirectory;
    bool m_useProjectsDirectory;
115 116 117
};

FileManagerPrivate::FileManagerPrivate(QObject *q, QMainWindow *mw) :
con's avatar
con committed
118
    m_mainWindow(mw),
119
    m_fileWatcher(new QFileSystemWatcher(q)),
120 121 122 123 124 125 126
    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
127
{
128 129 130 131 132 133 134 135 136 137
}

} // 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
138
        this, SLOT(changedFile(QString)));
139
    connect(d->m_mainWindow, SIGNAL(windowActivated()),
con's avatar
con committed
140
        this, SLOT(mainWindowActivated()));
141
    connect(core, SIGNAL(contextChanged(Core::IContext*)),
con's avatar
con committed
142 143
        this, SLOT(syncWithEditor(Core::IContext*)));

144
    const QSettings *s = core->settings();
145
    d->m_recentFiles = s->value(QLatin1String(settingsGroupC) + QLatin1Char('/') + QLatin1String(filesKeyC), QStringList()).toStringList();
146
    for (QStringList::iterator it = d->m_recentFiles.begin(); it != d->m_recentFiles.end(); ) {
con's avatar
con committed
147 148 149
        if (QFileInfo(*it).isFile()) {
            ++it;
        } else {
150
            it = d->m_recentFiles.erase(it);
con's avatar
con committed
151 152
        }
    }
153
    const QString directoryGroup = QLatin1String(directoryGroupC) + QLatin1Char('/');
154 155 156 157 158 159 160
    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();
    }
161 162
    d->m_useProjectsDirectory = s->value(directoryGroup + QLatin1String(useProjectDirectoryKeyC),
                                         d->m_useProjectsDirectory).toBool();
con's avatar
con committed
163 164
}

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

con's avatar
con committed
170 171 172 173 174 175 176 177 178 179 180
/*!
    \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.
*/
bool FileManager::addFiles(const QList<IFile *> &files)
{
    bool filesAdded = false;
    foreach (IFile *file, files) {
181
        if (!file || d->m_managedFiles.contains(file))
con's avatar
con committed
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
            continue;
        connect(file, SIGNAL(changed()), this, SLOT(checkForNewFileName()));
        connect(file, SIGNAL(destroyed(QObject *)), this, SLOT(fileDestroyed(QObject *)));
        filesAdded = true;
        addWatch(fixFileName(file->fileName()));
        updateFileInfo(file);
    }
    return filesAdded;
}

/*!
    \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.
*/
bool FileManager::addFile(IFile *file)
{
    return addFiles(QList<IFile *>() << file);
}

void FileManager::fileDestroyed(QObject *obj)
{
    // we can't use qobject_cast here, because meta data is already destroyed
    IFile *file = static_cast<IFile*>(obj);
208 209
    const QString filename = d->m_managedFiles.value(file).fileName;
    d->m_managedFiles.remove(file);
con's avatar
con committed
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
    removeWatch(filename);
}

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

228
    if (!d->m_managedFiles.contains(file))
con's avatar
con committed
229
        return false;
230
    const Internal::FileInfo info = d->m_managedFiles.take(file);
con's avatar
con committed
231 232 233 234 235 236 237
    const QString filename = info.fileName;
    removeWatch(filename);
    return true;
}

void FileManager::addWatch(const QString &filename)
{
hjk's avatar
hjk committed
238
    if (!filename.isEmpty() && managedFiles(filename).isEmpty())
239
        d->m_fileWatcher->addPath(filename);
con's avatar
con committed
240 241 242 243
}

void FileManager::removeWatch(const QString &filename)
{
hjk's avatar
hjk committed
244
    if (!filename.isEmpty() && managedFiles(filename).isEmpty())
245
        d->m_fileWatcher->removePath(filename);
con's avatar
con committed
246 247 248 249 250
}

void FileManager::checkForNewFileName()
{
    IFile *file = qobject_cast<IFile *>(sender());
hjk's avatar
hjk committed
251
    QTC_ASSERT(file, return);
con's avatar
con committed
252
    const QString newfilename = fixFileName(file->fileName());
253
    const QString oldfilename = d->m_managedFiles.value(file).fileName;
con's avatar
con committed
254
    if (!newfilename.isEmpty() && newfilename != oldfilename) {
255
        d->m_managedFiles[file].fileName = newfilename;
con's avatar
con committed
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
        removeWatch(oldfilename);
        addWatch(newfilename);
    }
}

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

    return !managedFiles(fixFileName(fileName)).isEmpty();
}

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

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

295 296
    const QMap<IFile*, Internal::FileInfo>::const_iterator cend =  d->m_managedFiles.constEnd();
    for (QMap<IFile*, Internal::FileInfo>::const_iterator i = d->m_managedFiles.constBegin(); i != cend; ++i) {
con's avatar
con committed
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
        IFile *fi = i.key();
        if (fi->isModified())
            modifiedFiles << fi;
    }
    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)
{
    if (!file->fileName().isEmpty())
312
        d->m_fileWatcher->removePath(file->fileName());
con's avatar
con committed
313 314 315 316 317 318 319 320 321 322 323 324
}

/*!
    \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)
{
    foreach (IFile *managedFile, managedFiles(file->fileName()))
        updateFileInfo(managedFile);
    if (!file->fileName().isEmpty())
325
        d->m_fileWatcher->addPath(file->fileName());
con's avatar
con committed
326 327 328 329 330 331
}

void FileManager::updateFileInfo(IFile *file)
{
    const QString fixedname = fixFileName(file->fileName());
    const QFileInfo fi(file->fileName());
332
    Internal::FileInfo info;
con's avatar
con committed
333 334 335
    info.fileName = fixedname;
    info.modified = fi.lastModified();
    info.permissions = fi.permissions();
336
    d->m_managedFiles.insert(file, info);
con's avatar
con committed
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
}

/*!
    \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,
355 356 357
                                              bool *cancelled, const QString &message,
                                              const QString &alwaysSaveMessage,
                                              bool *alwaysSave)
con's avatar
con committed
358
{
359
    return saveModifiedFiles(files, cancelled, false, message, alwaysSaveMessage, alwaysSave);
con's avatar
con committed
360 361 362 363 364
}

static QMessageBox::StandardButton skipFailedPrompt(QWidget *parent, const QString &fileName)
{
    return QMessageBox::question(parent,
365 366
                                 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
367 368 369 370 371
                                 QMessageBox::YesToAll| QMessageBox::Yes|QMessageBox::No,
                                 QMessageBox::No);
}

QList<IFile *> FileManager::saveModifiedFiles(const QList<IFile *> &files,
372 373 374 375 376
                                              bool *cancelled,
                                              bool silently,
                                              const QString &message,
                                              const QString &alwaysSaveMessage,
                                              bool *alwaysSave)
con's avatar
con committed
377 378 379 380 381
{
    if (cancelled)
        (*cancelled) = false;

    QList<IFile *> notSaved;
382 383
    QMap<IFile *, QString> modifiedFilesMap;
    QList<IFile *> modifiedFiles;
con's avatar
con committed
384 385 386 387 388 389 390 391 392

    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.
393
            if (!(modifiedFilesMap.values().contains(name)
con's avatar
con committed
394
                && file->isReadOnly()))
395
                modifiedFilesMap.insert(file, name);
con's avatar
con committed
396 397
        }
    }
398
    modifiedFiles = modifiedFilesMap.keys();
con's avatar
con committed
399 400 401
    if (!modifiedFiles.isEmpty()) {
        QList<IFile *> filesToSave;
        if (silently) {
402
            filesToSave = modifiedFiles;
con's avatar
con committed
403
        } else {
404
            Internal::SaveItemsDialog dia(d->m_mainWindow, modifiedFiles);
con's avatar
con committed
405 406
            if (!message.isEmpty())
                dia.setMessage(message);
407 408
            if (!alwaysSaveMessage.isNull())
                dia.setAlwaysSaveMessage(alwaysSaveMessage);
con's avatar
con committed
409 410 411
            if (dia.exec() != QDialog::Accepted) {
                if (cancelled)
                    (*cancelled) = true;
412 413
                if (alwaysSave)
                    *alwaysSave = dia.alwaysSaveChecked();
414
                notSaved = modifiedFiles;
con's avatar
con committed
415 416
                return notSaved;
            }
417 418
            if (alwaysSave)
                *alwaysSave = dia.alwaysSaveChecked();
con's avatar
con committed
419 420 421 422
            filesToSave = dia.itemsToSave();
        }

        bool yestoall = false;
423
        Core::VCSManager *vcsManager = Core::ICore::instance()->vcsManager();
con's avatar
con committed
424
        foreach (IFile *file, filesToSave) {
425
            if (file->isReadOnly()) {
426 427
                const QString directory = QFileInfo(file->fileName()).absolutePath();
                if (IVersionControl *versionControl = vcsManager->findVersionControlForDirectory(directory))
con's avatar
con committed
428 429 430 431 432 433 434 435 436 437 438 439
                    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());
440
                switch (skipFailedPrompt(d->m_mainWindow, fi.fileName())) {
con's avatar
con committed
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
                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);
457
                    file->checkPermissions();
con's avatar
con committed
458 459 460 461 462 463 464 465 466 467
                    unblockFileChange(file);
                }
                if (!ok)
                    notSaved.append(file);
            }
        }
    }
    return notSaved;
}

468
QString FileManager::getSaveFileNameWithExtension(const QString &title, const QString &pathIn,
con's avatar
con committed
469 470 471 472 473 474
    const QString &fileFilter, const QString &extension)
{
    QString fileName;
    bool repeat;
    do {
        repeat = false;
475
        const QString path = pathIn.isEmpty() ? fileDialogInitialDirectory() : pathIn;
476
        fileName = QFileDialog::getSaveFileName(d->m_mainWindow, title, path, fileFilter);
con's avatar
con committed
477 478 479
        if (!fileName.isEmpty() && !extension.isEmpty() && !fileName.endsWith(extension)) {
            fileName.append(extension);
            if (QFile::exists(fileName)) {
480
                if (QMessageBox::warning(d->m_mainWindow, tr("Overwrite?"),
con's avatar
con committed
481 482 483 484 485 486
                        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);
487 488
    if (!fileName.isEmpty())
        setFileDialogLastVisitedDirectory(QFileInfo(fileName).absolutePath());
con's avatar
con committed
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
    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
513
    if (const MimeType mt = Core::ICore::instance()->mimeDatabase()->findByFile(fi)) {
con's avatar
con committed
514 515 516 517 518 519 520 521 522 523 524
        filterString = mt.filterString();
        preferredSuffix = mt.preferredSuffix();
    }

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

525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
/*!
    \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;
}


con's avatar
con committed
546 547
void FileManager::changedFile(const QString &file)
{
548
    const bool wasempty = d->m_changedFiles.isEmpty();
con's avatar
con committed
549
    foreach (IFile *fileinterface, managedFiles(file))
550 551
        d->m_changedFiles << fileinterface;
    if (wasempty && !d->m_changedFiles.isEmpty()) {
552
        QTimer::singleShot(200, this, SLOT(checkForReload()));
con's avatar
con committed
553 554 555 556 557
    }
}

void FileManager::mainWindowActivated()
{
558 559 560 561
    //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
562 563 564 565
}

void FileManager::checkForReload()
{
566 567 568 569 570
    if (QApplication::activeWindow() == d->m_mainWindow &&
        !d->m_blockActivated && !d->m_changedFiles.isEmpty()) {
        d->m_blockActivated = true;
        const QList<QPointer<IFile> > changed = d->m_changedFiles;
        d->m_changedFiles.clear();
571
        IFile::ReloadBehavior behavior = EditorManager::instance()->reloadBehavior();
con's avatar
con committed
572 573 574 575
        foreach (IFile *f, changed) {
            if (!f)
                continue;
            QFileInfo fi(f->fileName());
576
            Internal::FileInfo info = d->m_managedFiles.value(f);
con's avatar
con committed
577 578 579 580 581 582 583 584 585 586 587 588
            if (info.modified != fi.lastModified()
                    || info.permissions != fi.permissions()) {
                if (info.modified != fi.lastModified())
                    f->modified(&behavior);
                else {
                    IFile::ReloadBehavior tempBeh =
                        IFile::ReloadPermissions;
                    f->modified(&tempBeh);
                }
                updateFileInfo(f);

                // the file system watchers loses inodes when a file is removed/renamed. Work around it.
589 590
                d->m_fileWatcher->removePath(f->fileName());
                d->m_fileWatcher->addPath(f->fileName());
con's avatar
con committed
591 592
            }
        }
593
        d->m_blockActivated = false;
con's avatar
con committed
594 595 596 597 598 599 600 601 602
        checkForReload();
    }
}

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

603
    Core::IEditor *editor = Core::EditorManager::instance()->currentEditor();
con's avatar
con committed
604 605 606 607 608 609 610 611 612 613 614 615 616 617
    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));
618 619 620 621
    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
622 623 624 625 626 627 628 629 630
}

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

    Returns the list of recent files.
*/
QStringList FileManager::recentFiles() const
{
631
    return d->m_recentFiles;
con's avatar
con committed
632 633 634 635
}

void FileManager::saveRecentFiles()
{
636
    QSettings *s = Core::ICore::instance()->settings();
637 638 639 640 641 642
    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
643 644 645 646 647 648 649 650
    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
651
  \sa currentFile
con's avatar
con committed
652 653 654
  */
void FileManager::setCurrentFile(const QString &filePath)
{
655
    if (d->m_currentFile == filePath)
con's avatar
con committed
656
        return;
657 658
    d->m_currentFile = filePath;
    emit currentFileChanged(d->m_currentFile);
con's avatar
con committed
659 660 661 662 663 664 665 666
}

/*!
  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
667
  \sa setCurrentFile
con's avatar
con committed
668 669 670
  */
QString FileManager::currentFile() const
{
671
    return d->m_currentFile;
con's avatar
con committed
672 673 674 675 676 677 678 679 680 681 682 683
}

/*!
    \fn QList<IFile*> FileManager::managedFiles(const QString &fileName) const

    Returns the list one IFile's in the set that point to \a fileName.
*/
QList<IFile *> FileManager::managedFiles(const QString &fileName) const
{
    const QString fixedName = fixFileName(fileName);
    QList<IFile *> result;
    if (!fixedName.isEmpty()) {
684 685
        const QMap<IFile*, Internal::FileInfo>::const_iterator cend =  d->m_managedFiles.constEnd();
        for (QMap<IFile*, Internal::FileInfo>::const_iterator i = d->m_managedFiles.constBegin(); i != cend; ++i) {
con's avatar
con committed
686 687 688 689 690 691
            if (i.value().fileName == fixedName)
                result << i.key();
        }
    }
    return result;
}
692

693 694 695 696 697 698 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 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
/*!

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

// -------------- FileChangeBlocker

786 787 788 789 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
FileChangeBlocker::FileChangeBlocker(const QString &fileName)
    : m_reload(false)
{
    Core::FileManager *fm = Core::ICore::instance()->fileManager();
    m_files = fm->managedFiles(fileName);
    foreach (Core::IFile *file, m_files)
        fm->blockFileChange(file);
}

FileChangeBlocker::~FileChangeBlocker()
{
    Core::IFile::ReloadBehavior tempBehavior = Core::IFile::ReloadAll;
    Core::FileManager *fm = Core::ICore::instance()->fileManager();
    foreach (Core::IFile *file, m_files) {
        if (m_reload)
            file->modified(&tempBehavior);
        fm->unblockFileChange(file);
    }
}

void FileChangeBlocker::setModifiedReload(bool b)
{
    m_reload = b;
}

bool FileChangeBlocker::modifiedReload() const
{
    return m_reload;
}
815 816

} // namespace Core