session.cpp 31.8 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 45 46
#include <coreplugin/modemanager.h>

#include <texteditor/itexteditor.h>

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 517 518
    return Utils::findOrDefault(d->m_projects, [rootProjectNode](Project *p) {
        return p->rootProjectNode() == rootProjectNode;
    });
con's avatar
con committed
519 520
}

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

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

532 533 534 535 536 537 538 539 540 541 542 543 544
    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
545 546 547
    return node;
}

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

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

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

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

564 565 566
    return 0;
}

hjk's avatar
hjk committed
567
bool SessionManagerPrivate::projectContainsFile(Project *p, const QString &fileName) const
568 569 570 571 572
{
    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
573 574
}

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

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

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

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


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

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

hjk's avatar
hjk committed
630
    d->m_depMap = resMap;
con's avatar
con committed
631

632 633 634 635 636
    // TODO: Clear m_modelProjectHash

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

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

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

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

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

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

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

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

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

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

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

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

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

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

722 723 724 725 726 727 728 729 730 731 732 733

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

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

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

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

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

hjk's avatar
hjk committed
772
void SessionManagerPrivate::restoreDependencies(const PersistentSettingsReader &reader)
773 774 775 776 777
{
    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();
778 779 780 781 782 783 784
        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);
785 786 787 788 789
        }
        ++i;
    }
}

hjk's avatar
hjk committed
790
void SessionManagerPrivate::askUserAboutFailedProjects()
791 792 793 794 795 796
{
    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
797 798
                                            SessionManager::tr("Failed to restore project files"),
                                            SessionManager::tr("Could not restore the following project files:<br><b>%1</b>").
799
                                            arg(fileList));
hjk's avatar
hjk committed
800 801
        QPushButton * keepButton = new QPushButton(SessionManager::tr("Keep projects in Session"), box);
        QPushButton * removeButton = new QPushButton(SessionManager::tr("Remove projects from Session"), box);
802 803 804 805 806 807 808 809 810 811
        box->addButton(keepButton, QMessageBox::AcceptRole);
        box->addButton(removeButton, QMessageBox::DestructiveRole);

        box->exec();

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

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

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

840
/*!
841
     Loads a session, takes a session name (not filename).
842
*/
hjk's avatar
hjk committed
843
void SessionManagerPrivate::restoreProjects(const QStringList &fileList)
844 845 846 847 848 849 850 851
{
    // 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
852
            QMessageBox::critical(Core::ICore::mainWindow(), SessionManager::tr("Failed to open project"), errors);
853
        foreach (Project *p, projects)
854
            m_failedProjects.removeAll(p->projectFilePath().toString());
855 856
    }
}
857

con's avatar
con committed
858 859 860 861 862
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
863
    if (session == d->m_sessionName && !isDefaultVirgin())
con's avatar
con committed
864 865 866 867
        return true;

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

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

hjk's avatar
hjk committed
880
    d->m_loadingSession = true;
881

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

    if (!isDefaultVirgin()) {
886
        if (!save()) {
hjk's avatar
hjk committed
887
            d->m_loadingSession = false;
888
            return false;
889
        }