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

#include "session.h"

con's avatar
con committed
32 33 34 35
#include "project.h"
#include "projectexplorer.h"
#include "nodesvisitor.h"
#include "editorconfiguration.h"
36
#include "projectnodes.h"
con's avatar
con committed
37 38 39 40

#include <coreplugin/icore.h>
#include <coreplugin/imode.h>
#include <coreplugin/editormanager/editormanager.h>
41
#include <coreplugin/coreconstants.h>
42
#include <coreplugin/progressmanager/progressmanager.h>
con's avatar
con committed
43 44
#include <coreplugin/modemanager.h>

45
#include <texteditor/basetexteditor.h>
con's avatar
con committed
46

47
#include <utils/algorithm.h>
48
#include <utils/stylehelper.h>
49
#include <utils/algorithm.h>
hjk's avatar
hjk committed
50

51 52 53
#include <QDebug>
#include <QDir>
#include <QFileInfo>
hjk's avatar
hjk committed
54

55 56
#include <QMessageBox>
#include <QPushButton>
con's avatar
con committed
57

hjk's avatar
hjk committed
58
namespace { bool debug = false; }
con's avatar
con committed
59

60
using namespace Core;
hjk's avatar
hjk committed
61
using namespace Utils;
62
using namespace ProjectExplorer::Internal;
con's avatar
con committed
63

hjk's avatar
hjk committed
64 65
namespace ProjectExplorer {

66 67 68
/*!
     \class ProjectExplorer::SessionManager

69
     \brief The SessionManager class manages sessions.
70 71

     TODO the interface of this class is not really great.
72 73
     The implementation suffers from that all the functions from the
     public interface just wrap around functions which do the actual work.
74 75
     This could be improved.
*/
con's avatar
con committed
76

hjk's avatar
hjk committed
77 78 79 80 81 82 83 84 85 86 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 112 113 114 115 116 117 118 119 120 121 122 123
class SessionManagerPrivate
{
public:
    SessionManagerPrivate() :
        m_sessionName(QLatin1String("default")),
        m_virginSession(true),
        m_loadingSession(false),
        m_startupProject(0),
        m_writer(0)
    {}

    bool projectContainsFile(Project *p, const QString &fileName) const;
    void restoreValues(const PersistentSettingsReader &reader);
    void restoreDependencies(const PersistentSettingsReader &reader);
    void restoreStartupProject(const PersistentSettingsReader &reader);
    void restoreEditors(const PersistentSettingsReader &reader);
    void restoreProjects(const QStringList &fileList);
    void askUserAboutFailedProjects();
    void sessionLoadingProgress();

    bool recursiveDependencyCheck(const QString &newDep, const QString &checkDep) const;
    QStringList dependencies(const QString &proName) const;
    QStringList dependenciesOrder() const;
    void dependencies(const QString &proName, QStringList &result) const;

public:
    SessionNode *m_sessionNode;
    QString m_sessionName;
    bool m_virginSession;

    mutable QStringList m_sessions;

    mutable QHash<Project *, QStringList> m_projectFileCache;
    bool m_loadingSession;

    Project *m_startupProject;
    QList<Project *> m_projects;
    QStringList m_failedProjects;
    QMap<QString, QStringList> m_depMap;
    QMap<QString, QVariant> m_values;
    QFutureInterface<void> m_future;
    PersistentSettingsWriter *m_writer;
};

static SessionManager *m_instance = 0;
static SessionManagerPrivate *d = 0;

hjk's avatar
hjk committed
124
SessionManager::SessionManager(QObject *parent)
hjk's avatar
hjk committed
125
  : QObject(parent)
con's avatar
con committed
126
{
hjk's avatar
hjk committed
127 128 129 130 131
    m_instance = this;
    d = new SessionManagerPrivate;

    d->m_sessionNode = new SessionNode(this);

132
    connect(ModeManager::instance(), SIGNAL(currentModeChanged(Core::IMode*)),
con's avatar
con committed
133
            this, SLOT(saveActiveMode(Core::IMode*)));
134

135
    connect(EditorManager::instance(), SIGNAL(editorCreated(Core::IEditor*,QString)),
Robert Loehning's avatar
Robert Loehning committed
136 137
            this, SLOT(configureEditor(Core::IEditor*,QString)));
    connect(ProjectExplorerPlugin::instance(), SIGNAL(currentProjectChanged(ProjectExplorer::Project*)),
con's avatar
con committed
138
            this, SLOT(updateWindowTitle()));
139
    connect(EditorManager::instance(), SIGNAL(editorOpened(Core::IEditor*)),
140
            this, SLOT(markSessionFileDirty()));
141
    connect(EditorManager::instance(), SIGNAL(editorsClosed(QList<Core::IEditor*>)),
142
            this, SLOT(markSessionFileDirty()));
hjk's avatar
hjk committed
143
}
con's avatar
con committed
144 145 146

SessionManager::~SessionManager()
{
hjk's avatar
hjk committed
147 148 149
    emit m_instance->aboutToUnloadSession(d->m_sessionName);
    delete d->m_writer;
    delete d;
con's avatar
con committed
150 151
}

hjk's avatar
hjk committed
152 153 154 155
QObject *SessionManager::instance()
{
   return m_instance;
}
con's avatar
con committed
156

hjk's avatar
hjk committed
157
bool SessionManager::isDefaultVirgin()
con's avatar
con committed
158
{
hjk's avatar
hjk committed
159
    return isDefaultSession(d->m_sessionName) && d->m_virginSession;
con's avatar
con committed
160 161
}

hjk's avatar
hjk committed
162
bool SessionManager::isDefaultSession(const QString &session)
con's avatar
con committed
163
{
hjk's avatar
hjk committed
164
    return session == QLatin1String("default");
con's avatar
con committed
165 166 167 168 169
}


void SessionManager::saveActiveMode(Core::IMode *mode)
{
170
    setValue(QLatin1String("ActiveMode"), mode->id().toString());
con's avatar
con committed
171 172 173 174 175 176
}

void SessionManager::clearProjectFileCache()
{
    // If triggered by the fileListChanged signal of one project
    // only invalidate cache for this project
hjk's avatar
hjk committed
177
    Project *pro = qobject_cast<Project*>(m_instance->sender());
con's avatar
con committed
178
    if (pro)
hjk's avatar
hjk committed
179
        d->m_projectFileCache.remove(pro);
con's avatar
con committed
180
    else
hjk's avatar
hjk committed
181
        d->m_projectFileCache.clear();
con's avatar
con committed
182 183
}

hjk's avatar
hjk committed
184
bool SessionManagerPrivate::recursiveDependencyCheck(const QString &newDep, const QString &checkDep) const
con's avatar
con committed
185 186 187 188
{
    if (newDep == checkDep)
        return false;

hjk's avatar
hjk committed
189
    foreach (const QString &dependency, m_depMap.value(checkDep))
con's avatar
con committed
190 191 192 193 194 195
        if (!recursiveDependencyCheck(newDep, dependency))
            return false;

    return true;
}

196
/*
197
 * The dependency management exposes an interface based on projects, but
198 199 200 201 202
 * is internally purely string based. This is suboptimal. Probably it would be
 * nicer to map the filenames to projects on load and only map it back to
 * filenames when saving.
 */

hjk's avatar
hjk committed
203
QList<Project *> SessionManager::dependencies(const Project *project)
204
{
205
    const QString proName = project->projectFilePath().toString();
hjk's avatar
hjk committed
206
    const QStringList proDeps = d->m_depMap.value(proName);
207 208 209 210 211 212 213 214 215 216

    QList<Project *> projects;
    foreach (const QString &dep, proDeps) {
        if (Project *pro = projectForFile(dep))
            projects += pro;
    }

    return projects;
}

hjk's avatar
hjk committed
217
bool SessionManager::hasDependency(const Project *project, const Project *depProject)
con's avatar
con committed
218
{
219 220
    const QString proName = project->projectFilePath().toString();
    const QString depName = depProject->projectFilePath().toString();
con's avatar
con committed
221

hjk's avatar
hjk committed
222
    const QStringList proDeps = d->m_depMap.value(proName);
con's avatar
con committed
223 224 225
    return proDeps.contains(depName);
}

hjk's avatar
hjk committed
226
bool SessionManager::canAddDependency(const Project *project, const Project *depProject)
con's avatar
con committed
227
{
228 229
    const QString newDep = project->projectFilePath().toString();
    const QString checkDep = depProject->projectFilePath().toString();
con's avatar
con committed
230

hjk's avatar
hjk committed
231
    return d->recursiveDependencyCheck(newDep, checkDep);
con's avatar
con committed
232 233
}

dt's avatar
dt committed
234
bool SessionManager::addDependency(Project *project, Project *depProject)
con's avatar
con committed
235
{
236 237
    const QString proName = project->projectFilePath().toString();
    const QString depName = depProject->projectFilePath().toString();
con's avatar
con committed
238 239

    // check if this dependency is valid
hjk's avatar
hjk committed
240
    if (!d->recursiveDependencyCheck(proName, depName))
con's avatar
con committed
241 242
        return false;

hjk's avatar
hjk committed
243
    QStringList proDeps = d->m_depMap.value(proName);
con's avatar
con committed
244 245
    if (!proDeps.contains(depName)) {
        proDeps.append(depName);
hjk's avatar
hjk committed
246
        d->m_depMap[proName] = proDeps;
con's avatar
con committed
247
    }
hjk's avatar
hjk committed
248
    emit m_instance->dependencyChanged(project, depProject);
con's avatar
con committed
249 250 251 252

    return true;
}

dt's avatar
dt committed
253
void SessionManager::removeDependency(Project *project, Project *depProject)
254
{
255 256
    const QString proName = project->projectFilePath().toString();
    const QString depName = depProject->projectFilePath().toString();
257

hjk's avatar
hjk committed
258
    QStringList proDeps = d->m_depMap.value(proName);
259
    proDeps.removeAll(depName);
260
    if (proDeps.isEmpty())
hjk's avatar
hjk committed
261
        d->m_depMap.remove(proName);
262
    else
hjk's avatar
hjk committed
263 264
        d->m_depMap[proName] = proDeps;
    emit m_instance->dependencyChanged(project, depProject);
265 266
}

con's avatar
con committed
267 268 269
void SessionManager::setStartupProject(Project *startupProject)
{
    if (debug)
270
        qDebug() << Q_FUNC_INFO << (startupProject ? startupProject->displayName() : QLatin1String("0"));
con's avatar
con committed
271 272

    if (startupProject) {
hjk's avatar
hjk committed
273
        Q_ASSERT(d->m_projects.contains(startupProject));
con's avatar
con committed
274 275
    }

hjk's avatar
hjk committed
276
    if (d->m_startupProject == startupProject)
277 278
        return;

hjk's avatar
hjk committed
279 280
    d->m_startupProject = startupProject;
    emit m_instance->startupProjectChanged(startupProject);
con's avatar
con committed
281 282
}

hjk's avatar
hjk committed
283
Project *SessionManager::startupProject()
con's avatar
con committed
284
{
hjk's avatar
hjk committed
285
    return d->m_startupProject;
con's avatar
con committed
286 287 288 289 290 291 292 293 294
}

void SessionManager::addProject(Project *project)
{
    addProjects(QList<Project*>() << project);
}

void SessionManager::addProjects(const QList<Project*> &projects)
{
hjk's avatar
hjk committed
295
    d->m_virginSession = false;
con's avatar
con committed
296 297
    QList<Project*> clearedList;
    foreach (Project *pro, projects) {
hjk's avatar
hjk committed
298
        if (!d->m_projects.contains(pro)) {
con's avatar
con committed
299
            clearedList.append(pro);
hjk's avatar
hjk committed
300 301
            d->m_projects.append(pro);
            d->m_sessionNode->addProjectNodes(QList<ProjectNode *>() << pro->rootProjectNode());
con's avatar
con committed
302 303

            connect(pro, SIGNAL(fileListChanged()),
hjk's avatar
hjk committed
304
                    m_instance, SLOT(clearProjectFileCache()));
con's avatar
con committed
305

306
            connect(pro, SIGNAL(displayNameChanged()),
hjk's avatar
hjk committed
307
                    m_instance, SLOT(projectDisplayNameChanged()));
308

con's avatar
con committed
309
            if (debug)
310
                qDebug() << "SessionManager - adding project " << pro->displayName();
con's avatar
con committed
311 312 313
        }
    }

hjk's avatar
hjk committed
314 315
    foreach (Project *pro, clearedList)
        emit m_instance->projectAdded(pro);
con's avatar
con committed
316 317

    if (clearedList.count() == 1)
hjk's avatar
hjk committed
318
        emit m_instance->singleProjectAdded(clearedList.first());
con's avatar
con committed
319 320 321 322
}

void SessionManager::removeProject(Project *project)
{
hjk's avatar
hjk committed
323
    d->m_virginSession = false;
con's avatar
con committed
324 325 326 327 328 329 330
    if (project == 0) {
        qDebug() << "SessionManager::removeProject(0) ... THIS SHOULD NOT HAPPEN";
        return;
    }
    removeProjects(QList<Project*>() << project);
}

331 332
bool SessionManager::loadingSession()
{
hjk's avatar
hjk committed
333
    return d->m_loadingSession;
334 335
}

con's avatar
con committed
336 337 338
bool SessionManager::save()
{
    if (debug)
hjk's avatar
hjk committed
339
        qDebug() << "SessionManager - saving session" << d->m_sessionName;
con's avatar
con committed
340

hjk's avatar
hjk committed
341
    emit m_instance->aboutToSaveSession();
con's avatar
con committed
342

hjk's avatar
hjk committed
343 344 345
    if (!d->m_writer || d->m_writer->fileName() != sessionNameToFileName(d->m_sessionName)) {
        delete d->m_writer;
        d->m_writer = new PersistentSettingsWriter(sessionNameToFileName(d->m_sessionName),
Tobias Hunger's avatar
Tobias Hunger committed
346 347
                                                       QLatin1String("QtCreatorSession"));
    }
348

349
    QVariantMap data;
350
    // save the startup project
hjk's avatar
hjk committed
351
    if (d->m_startupProject)
352
        data.insert(QLatin1String("StartupProject"), d->m_startupProject->projectFilePath().toString());
353

hjk's avatar
hjk committed
354
    QColor c = StyleHelper::requestedBaseColor();
355 356 357 358 359
    if (c.isValid()) {
        QString tmp = QString::fromLatin1("#%1%2%3")
                .arg(c.red(), 2, 16, QLatin1Char('0'))
                .arg(c.green(), 2, 16, QLatin1Char('0'))
                .arg(c.blue(), 2, 16, QLatin1Char('0'));
360
        data.insert(QLatin1String("Color"), tmp);
361 362
    }

363
    QStringList projectFiles;
hjk's avatar
hjk committed
364
    foreach (Project *pro, d->m_projects)
365
        projectFiles << pro->projectFilePath().toString();
366 367

    // Restore infromation on projects that failed to load:
368
    // don't readd projects to the list, which the user loaded
hjk's avatar
hjk committed
369
    foreach (const QString &failed, d->m_failedProjects)
370 371
        if (!projectFiles.contains(failed))
            projectFiles << failed;
372

373
    data.insert(QLatin1String("ProjectList"), projectFiles);
374 375

    QMap<QString, QVariant> depMap;
hjk's avatar
hjk committed
376 377
    QMap<QString, QStringList>::const_iterator i = d->m_depMap.constBegin();
    while (i != d->m_depMap.constEnd()) {
378 379 380 381 382 383 384 385
        QString key = i.key();
        QStringList values;
        foreach (const QString &value, i.value()) {
            values << value;
        }
        depMap.insert(key, values);
        ++i;
    }
386
    data.insert(QLatin1String("ProjectDependencies"), QVariant(depMap));
387
    data.insert(QLatin1String("EditorSettings"), EditorManager::saveState().toBase64());
388

hjk's avatar
hjk committed
389
    QMap<QString, QVariant>::const_iterator it, end = d->m_values.constEnd();
390
    QStringList keys;
hjk's avatar
hjk committed
391
    for (it = d->m_values.constBegin(); it != end; ++it) {
392
        data.insert(QLatin1String("value-") + it.key(), it.value());
393 394 395
        keys << it.key();
    }

396
    data.insert(QLatin1String("valueKeys"), keys);
397

hjk's avatar
hjk committed
398
    bool result = d->m_writer->save(data, Core::ICore::mainWindow());
con's avatar
con committed
399
    if (!result) {
400
        QMessageBox::warning(ICore::dialogParent(), tr("Error while saving session"),
hjk's avatar
hjk committed
401
            tr("Could not save session to file %1").arg(d->m_writer->fileName().toUserOutput()));
con's avatar
con committed
402 403 404 405 406 407 408 409 410
    }

    if (debug)
        qDebug() << "SessionManager - saving session returned " << result;

    return result;
}

/*!
411
  Closes all projects
con's avatar
con committed
412
  */
413
void SessionManager::closeAllProjects()
con's avatar
con committed
414
{
415 416
    setStartupProject(0);
    removeProjects(projects());
con's avatar
con committed
417 418
}

hjk's avatar
hjk committed
419 420 421 422 423 424
const QList<Project *> &SessionManager::projects()
{
    return d->m_projects;
}

bool SessionManager::hasProjects()
con's avatar
con committed
425
{
hjk's avatar
hjk committed
426
    return !d->m_projects.isEmpty();
con's avatar
con committed
427 428
}

hjk's avatar
hjk committed
429
QStringList SessionManagerPrivate::dependencies(const QString &proName) const
con's avatar
con committed
430 431
{
    QStringList result;
432
    dependencies(proName, result);
con's avatar
con committed
433 434 435
    return result;
}

hjk's avatar
hjk committed
436
void SessionManagerPrivate::dependencies(const QString &proName, QStringList &result) const
437 438 439 440 441 442 443 444 445 446
{
    QStringList depends = m_depMap.value(proName);

    foreach (const QString &dep, depends)
        dependencies(dep, result);

    if (!result.contains(proName))
        result.append(proName);
}

hjk's avatar
hjk committed
447
QStringList SessionManagerPrivate::dependenciesOrder() const
con's avatar
con committed
448 449 450 451 452
{
    QList<QPair<QString, QStringList> > unordered;
    QStringList ordered;

    // copy the map to a temporary list
hjk's avatar
hjk committed
453
    foreach (Project *pro, m_projects) {
454
        const QString &proName = pro->projectFilePath().toString();
hjk's avatar
hjk committed
455
        unordered << QPair<QString, QStringList>(proName, m_depMap.value(proName));
con's avatar
con committed
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
    }

    while (!unordered.isEmpty()) {
        for (int i=(unordered.count()-1); i>=0; --i) {
            if (unordered.at(i).second.isEmpty()) {
                ordered << unordered.at(i).first;
                unordered.removeAt(i);
            }
        }

        // remove the handled projects from the dependency lists
        // of the remaining unordered projects
        for (int i = 0; i < unordered.count(); ++i) {
            foreach (const QString &pro, ordered) {
                QStringList depList = unordered.at(i).second;
                depList.removeAll(pro);
                unordered[i].second = depList;
            }
        }
    }

    return ordered;
}

hjk's avatar
hjk committed
480
QList<Project *> SessionManager::projectOrder(Project *project)
con's avatar
con committed
481 482 483 484
{
    QList<Project *> result;

    QStringList pros;
485
    if (project)
486
        pros = d->dependencies(project->projectFilePath().toString());
487
    else
hjk's avatar
hjk committed
488
        pros = d->dependenciesOrder();
con's avatar
con committed
489 490 491

    foreach (const QString &proFile, pros) {
        foreach (Project *pro, projects()) {
492
            if (pro->projectFilePath().toString() == proFile) {
con's avatar
con committed
493 494 495 496 497 498 499 500 501
                result << pro;
                break;
            }
        }
    }

    return result;
}

hjk's avatar
hjk committed
502
Project *SessionManager::projectForNode(Node *node)
con's avatar
con committed
503 504 505 506 507 508 509
{
    if (!node)
        return 0;

    FolderNode *rootProjectNode = qobject_cast<FolderNode*>(node);
    if (!rootProjectNode)
        rootProjectNode = node->parentFolderNode();
hjk's avatar
hjk committed
510 511

    while (rootProjectNode && rootProjectNode->parentFolderNode() != d->m_sessionNode)
con's avatar
con committed
512 513
        rootProjectNode = rootProjectNode->parentFolderNode();

dt's avatar
dt committed
514
    Q_ASSERT(rootProjectNode);
con's avatar
con committed
515

516
    return Utils::findOrDefault(d->m_projects, Utils::equal(&Project::rootProjectNode, rootProjectNode));
con's avatar
con committed
517 518
}

519
QList<Node *> SessionManager::nodesForFile(const QString &fileName, Project *project)
con's avatar
con committed
520
{
dt's avatar
dt committed
521 522
    if (!project)
        project = projectForFile(fileName);
hjk's avatar
hjk committed
523

dt's avatar
dt committed
524
    if (project) {
con's avatar
con committed
525 526
        FindNodesForFileVisitor findNodes(fileName);
        project->rootProjectNode()->accept(&findNodes);
527
        return findNodes.nodes();
con's avatar
con committed
528 529
    }

530 531 532 533 534 535 536 537 538 539 540 541 542
    return QList<Node *>();
}

// node for file returns a randomly selected node if there are multiple
// prefer to use nodesForFile and figure out which node you want
Node *SessionManager::nodeForFile(const QString &fileName, Project *project)
{
    Node *node = 0;
    foreach (Node *n, nodesForFile(fileName, project)) {
        // prefer file nodes
        if (!node || (node->nodeType() != FileNodeType && n->nodeType() == FileNodeType))
            node = n;
    }
con's avatar
con committed
543 544 545
    return node;
}

hjk's avatar
hjk committed
546
Project *SessionManager::projectForFile(const QString &fileName)
con's avatar
con committed
547 548 549 550
{
    if (debug)
        qDebug() << "SessionManager::projectForFile(" << fileName << ")";

551
    const QList<Project *> &projectList = projects();
con's avatar
con committed
552

553
    // Check current project first
554
    Project *currentProject = ProjectExplorerPlugin::currentProject();
hjk's avatar
hjk committed
555
    if (currentProject && d->projectContainsFile(currentProject, fileName))
556
        return currentProject;
con's avatar
con committed
557

558
    foreach (Project *p, projectList)
hjk's avatar
hjk committed
559
        if (p != currentProject && d->projectContainsFile(p, fileName))
560
            return p;
hjk's avatar
hjk committed
561

562 563 564
    return 0;
}

hjk's avatar
hjk committed
565
bool SessionManagerPrivate::projectContainsFile(Project *p, const QString &fileName) const
566 567 568 569 570
{
    if (!m_projectFileCache.contains(p))
        m_projectFileCache.insert(p, p->files(Project::AllFiles));

    return m_projectFileCache.value(p).contains(fileName);
con's avatar
con committed
571 572
}

573
void SessionManager::configureEditor(Core::IEditor *editor, const QString &fileName)
con's avatar
con committed
574
{
575
    if (TextEditor::BaseTextEditor *textEditor = qobject_cast<TextEditor::BaseTextEditor*>(editor)) {
576 577
        Project *project = projectForFile(fileName);
        // Global settings are the default.
578 579
        if (project)
            project->editorConfiguration()->configureEditor(textEditor);
580
    }
con's avatar
con committed
581 582 583 584
}

void SessionManager::updateWindowTitle()
{
hjk's avatar
hjk committed
585
    if (isDefaultSession(d->m_sessionName)) {
586
        if (Project *currentProject = ProjectExplorerPlugin::currentProject())
587
            EditorManager::setWindowTitleAddition(currentProject->displayName());
588
        else
589
            EditorManager::setWindowTitleAddition(QString());
dt's avatar
dt committed
590
    } else {
hjk's avatar
hjk committed
591
        QString sessionName = d->m_sessionName;
con's avatar
con committed
592 593
        if (sessionName.isEmpty())
            sessionName = tr("Untitled");
594
        EditorManager::setWindowTitleAddition(sessionName);
595
    }
con's avatar
con committed
596 597 598 599 600 601 602 603
}

void SessionManager::removeProjects(QList<Project *> remove)
{
    QMap<QString, QStringList> resMap;

    foreach (Project *pro, remove) {
        if (debug)
604
            qDebug() << "SessionManager - emitting aboutToRemoveProject(" << pro->displayName() << ")";
hjk's avatar
hjk committed
605
        emit m_instance->aboutToRemoveProject(pro);
con's avatar
con committed
606 607 608 609 610 611 612
    }


    // Refresh dependencies
    QSet<QString> projectFiles;
    foreach (Project *pro, projects()) {
        if (!remove.contains(pro))
613
            projectFiles.insert(pro->projectFilePath().toString());
con's avatar
con committed
614 615 616 617 618
    }

    QSet<QString>::const_iterator i = projectFiles.begin();
    while (i != projectFiles.end()) {
        QStringList dependencies;
hjk's avatar
hjk committed
619
        foreach (const QString &dependency, d->m_depMap.value(*i)) {
con's avatar
con committed
620 621 622 623 624 625 626 627
            if (projectFiles.contains(dependency))
                dependencies << dependency;
        }
        if (!dependencies.isEmpty())
            resMap.insert(*i, dependencies);
        ++i;
    }

hjk's avatar
hjk committed
628
    d->m_depMap = resMap;
con's avatar
con committed
629

630 631 632 633 634
    // TODO: Clear m_modelProjectHash

    // Delete projects
    foreach (Project *pro, remove) {
        pro->saveSettings();
hjk's avatar
hjk committed
635
        d->m_projects.removeOne(pro);
636

hjk's avatar
hjk committed
637
        if (pro == d->m_startupProject)
638 639
            setStartupProject(0);

hjk's avatar
hjk committed
640 641
        disconnect(pro, SIGNAL(fileListChanged()), m_instance, SLOT(clearProjectFileCache()));
        d->m_projectFileCache.remove(pro);
642 643 644

        if (debug)
            qDebug() << "SessionManager - emitting projectRemoved(" << pro->displayName() << ")";
hjk's avatar
hjk committed
645 646
        d->m_sessionNode->removeProjectNodes(QList<ProjectNode *>() << pro->rootProjectNode());
        emit m_instance->projectRemoved(pro);
647 648 649
        delete pro;
    }

con's avatar
con committed
650
    if (startupProject() == 0)
hjk's avatar
hjk committed
651 652
        if (!d->m_projects.isEmpty())
            setStartupProject(d->m_projects.first());
con's avatar
con committed
653 654
}

655
/*!
656
    Lets other plugins store persistent values within the session file.
657 658
*/

con's avatar
con committed
659 660
void SessionManager::setValue(const QString &name, const QVariant &value)
{
hjk's avatar
hjk committed
661
    if (d->m_values.value(name) == value)
662
        return;
hjk's avatar
hjk committed
663
    d->m_values.insert(name, value);
664
    markSessionFileDirty(false);
con's avatar
con committed
665 666 667 668
}

QVariant SessionManager::value(const QString &name)
{
hjk's avatar
hjk committed
669 670
    QMap<QString, QVariant>::const_iterator it = d->m_values.find(name);
    return (it == d->m_values.constEnd()) ? QVariant() : *it;
con's avatar
con committed
671 672
}

hjk's avatar
hjk committed
673
QString SessionManager::activeSession()
con's avatar
con committed
674
{
hjk's avatar
hjk committed
675
    return d->m_sessionName;
con's avatar
con committed
676 677
}

hjk's avatar
hjk committed
678
QStringList SessionManager::sessions()
con's avatar
con committed
679
{
hjk's avatar
hjk committed
680
    if (d->m_sessions.isEmpty()) {
Tobias Hunger's avatar
Tobias Hunger committed
681
        // We are not initialized yet, so do that now
hjk's avatar
hjk committed
682
        QDir sessionDir(Core::ICore::userResourcePath());
683
        QList<QFileInfo> sessionFiles = sessionDir.entryInfoList(QStringList() << QLatin1String("*.qws"), QDir::NoFilter, QDir::Time);
hjk's avatar
hjk committed
684
        foreach (const QFileInfo &fileInfo, sessionFiles) {
685
            if (fileInfo.completeBaseName() != QLatin1String("default"))
hjk's avatar
hjk committed
686
                d->m_sessions << fileInfo.completeBaseName();
687
        }
hjk's avatar
hjk committed
688
        d->m_sessions.prepend(QLatin1String("default"));
689
    }
hjk's avatar
hjk committed
690
    return d->m_sessions;
con's avatar
con committed
691 692
}

hjk's avatar
hjk committed
693
FileName SessionManager::sessionNameToFileName(const QString &session)
con's avatar
con committed
694
{
hjk's avatar
hjk committed
695
    return FileName::fromString(ICore::userResourcePath() + QLatin1Char('/') + session + QLatin1String(".qws"));
con's avatar
con committed
696 697
}

698
/*!
699
    Creates \a session, but does not actually create the file.
700 701
*/

con's avatar
con committed
702 703 704 705
bool SessionManager::createSession(const QString &session)
{
    if (sessions().contains(session))
        return false;
hjk's avatar
hjk committed
706 707
    Q_ASSERT(d->m_sessions.size() > 0);
    d->m_sessions.insert(1, session);
con's avatar
con committed
708 709 710
    return true;
}

711 712 713 714 715 716 717 718 719
bool SessionManager::renameSession(const QString &original, const QString &newName)
{
    if (!cloneSession(original, newName))
        return false;
    if (original == activeSession())
        loadSession(newName);
    return deleteSession(original);
}

720 721 722 723 724 725 726 727 728 729 730 731

/*!
    \brief Shows a dialog asking the user to confirm deleting the session \p session
*/
bool SessionManager::confirmSessionDelete(const QString &session)
{
    return QMessageBox::question(Core::ICore::mainWindow(),
                                 tr("Delete Session"),
                                 tr("Delete session %1?").arg(session),
                                 QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes;
}

732
/*!
733
     Deletes \a session name from session list and the file from disk.
734
*/
con's avatar
con committed
735 736
bool SessionManager::deleteSession(const QString &session)
{
hjk's avatar
hjk committed
737
    if (!d->m_sessions.contains(session))
con's avatar
con committed
738
        return false;
hjk's avatar
hjk committed
739
    d->m_sessions.removeOne(session);
740
    QFile fi(sessionNameToFileName(session).toString());
con's avatar
con committed
741 742 743 744 745 746 747
    if (fi.exists())
        return fi.remove();
    return false;
}

bool SessionManager::cloneSession(const QString &original, const QString &clone)
{
hjk's avatar
hjk committed
748
    if (!d->m_sessions.contains(original))
con's avatar
con committed
749 750
        return false;

751
    QFile fi(sessionNameToFileName(original).toString());
con's avatar
con committed
752
    // If the file does not exist, we can still clone
753
    if (!fi.exists() || fi.copy(sessionNameToFileName(clone).toString())) {
hjk's avatar
hjk committed
754 755
        Q_ASSERT(d->m_sessions.size() > 0);
        d->m_sessions.insert(1, clone);
con's avatar
con committed
756 757 758 759 760
        return true;
    }
    return false;
}

hjk's avatar
hjk committed
761
void SessionManagerPrivate::restoreValues(const PersistentSettingsReader &reader)
762
{
hjk's avatar
hjk committed
763
    const QStringList keys = reader.restoreValue(QLatin1String("valueKeys")).toStringList();
764 765 766 767 768 769
    foreach (const QString &key, keys) {
        QVariant value = reader.restoreValue(QLatin1String("value-") + key);
        m_values.insert(key, value);
    }
}

hjk's avatar
hjk committed
770
void SessionManagerPrivate::restoreDependencies(const PersistentSettingsReader &reader)
771 772 773 774 775
{
    QMap<QString, QVariant> depMap = reader.restoreValue(QLatin1String("ProjectDependencies")).toMap();
    QMap<QString, QVariant>::const_iterator i = depMap.constBegin();
    while (i != depMap.constEnd()) {
        const QString &key = i.key();
776 777 778 779 780 781 782
        if (!m_failedProjects.contains(key)) {
            QStringList values;
            foreach (const QString &value, i.value().toStringList()) {
                if (!m_failedProjects.contains(value))
                    values << value;
            }
            m_depMap.insert(key, values);
783 784 785 786 787
        }
        ++i;
    }
}

hjk's avatar
hjk committed
788
void SessionManagerPrivate::askUserAboutFailedProjects()
789 790 791 792 793 794
{
    QStringList failedProjects = m_failedProjects;
    if (!failedProjects.isEmpty()) {
        QString fileList =
            QDir::toNativeSeparators(failedProjects.join(QLatin1String("<br>")));
        QMessageBox * box = new QMessageBox(QMessageBox::Warning,
hjk's avatar
hjk committed
795 796
                                            SessionManager::tr("Failed to restore project files"),
                                            SessionManager::tr("Could not restore the following project files:<br><b>%1</b>").
797
                                            arg(fileList));
hjk's avatar
hjk committed
798 799
        QPushButton * keepButton = new QPushButton(SessionManager::tr("Keep projects in Session"), box);
        QPushButton * removeButton = new QPushButton(SessionManager::tr("Remove projects from Session"), box);
800 801 802 803 804 805 806 807 808 809
        box->addButton(keepButton, QMessageBox::AcceptRole);
        box->addButton(removeButton, QMessageBox::DestructiveRole);

        box->exec();

        if (box->clickedButton() == removeButton)
            m_failedProjects.clear();
    }
}

hjk's avatar
hjk committed
810
void SessionManagerPrivate::restoreStartupProject(const PersistentSettingsReader &reader)
811 812 813
{
    const QString startupProject = reader.restoreValue(QLatin1String("StartupProject")).toString();
    if (!startupProject.isEmpty()) {
hjk's avatar
hjk committed
814
        foreach (Project *pro, d->m_projects) {
815
            if (pro->projectFilePath().toString() == startupProject) {
hjk's avatar
hjk committed
816
                m_instance->setStartupProject(pro);
817 818 819
                break;
            }
        }
820 821
    }
    if (!m_startupProject) {
822 823
        if (!startupProject.isEmpty())
            qWarning() << "Could not find startup project" << startupProject;
hjk's avatar
hjk committed
824 825
        if (!m_projects.isEmpty())
            m_instance->setStartupProject(m_projects.first());
826 827 828
    }
}

hjk's avatar
hjk committed
829
void SessionManagerPrivate::restoreEditors(const PersistentSettingsReader &reader)
830
{
hjk's avatar
hjk committed
831
    const QVariant editorsettings = reader.restoreValue(QLatin1String("EditorSettings"));
832
    if (editorsettings.isValid()) {
833
        EditorManager::restoreState(QByteArray::fromBase64(editorsettings.toByteArray()));
834
        sessionLoadingProgress();
835 836 837
    }
}

838
/*!
839
     Loads a session, takes a session name (not filename).
840
*/
hjk's avatar
hjk committed
841
void SessionManagerPrivate::restoreProjects(const QStringList &fileList)
842 843 844 845 846 847 848 849
{
    // indirectly adds projects to session
    // Keep projects that failed to load in the session!
    m_failedProjects = fileList;
    if (!fileList.isEmpty()) {
        QString errors;
        QList<Project *> projects = ProjectExplorerPlugin::instance()->openProjects(fileList, &errors);
        if (!errors.isEmpty())
hjk's avatar
hjk committed
850
            QMessageBox::critical(Core::ICore::mainWindow(), SessionManager::tr("Failed to open project"), errors);
851
        foreach (Project *p, projects)
852
            m_failedProjects.removeAll(p->projectFilePath().toString());
853 854
    }
}
855

con's avatar
con committed
856 857 858 859 860
bool SessionManager::loadSession(const QString &session)
{
    // Do nothing if we have that session already loaded,
    // exception if the session is the default virgin session
    // we still want to be able to load the default session
hjk's avatar
hjk committed
861
    if (session == d->m_sessionName && !isDefaultVirgin())
con's avatar
con committed
862 863 864 865
        return true;

    if (!sessions().contains(session))
        return false;
866

867
    // Try loading the file
hjk's avatar
hjk committed
868
    FileName fileName = sessionNameToFileName(session);
869
    PersistentSettingsReader reader;
870
    if (fileName.toFileInfo().exists()) {
871
        if (!reader.load(fileName)) {
872
            QMessageBox::warning(ICore::dialogParent(), tr("Error while restoring session"),
873
                                 tr("Could not restore session %1").arg(fileName.toUserOutput()));
874 875 876 877
            return false;
        }
    }

hjk's avatar
hjk committed
878
    d->m_loadingSession = true;
879

880
    // Allow everyone to set something in the session and before saving
hjk's avatar
hjk committed
881
    emit m_instance->aboutToUnloadSession(d->m_sessionName);
882 883

    if (!isDefaultVirgin()) {
884
        if (!save()) {
hjk's avatar
hjk committed
885
            d->m_loadingSession = false;