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/stylehelper.h>
48
#include <utils/algorithm.h>
hjk's avatar
hjk committed
49

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

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

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

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

hjk's avatar
hjk committed
63 64
namespace ProjectExplorer {

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

68
     \brief The SessionManager class manages sessions.
69 70

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

hjk's avatar
hjk committed
76 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
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
123
SessionManager::SessionManager(QObject *parent)
hjk's avatar
hjk committed
124
  : QObject(parent)
con's avatar
con committed
125
{
hjk's avatar
hjk committed
126 127 128 129 130
    m_instance = this;
    d = new SessionManagerPrivate;

    d->m_sessionNode = new SessionNode(this);

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

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

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

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

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

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


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

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

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

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

    return true;
}

195
/*
196
 * The dependency management exposes an interface based on projects, but
197 198 199 200 201
 * 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
202
QList<Project *> SessionManager::dependencies(const Project *project)
203
{
204
    const QString proName = project->projectFilePath().toString();
hjk's avatar
hjk committed
205
    const QStringList proDeps = d->m_depMap.value(proName);
206 207 208 209 210 211 212 213 214 215

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

    return projects;
}

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

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

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

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

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

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

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

    return true;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

hjk's avatar
hjk committed
342 343 344
    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
345 346
                                                       QLatin1String("QtCreatorSession"));
    }
347

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

hjk's avatar
hjk committed
353
    QColor c = StyleHelper::requestedBaseColor();
354 355 356 357 358
    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'));
359
        data.insert(QLatin1String("Color"), tmp);
360 361
    }

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

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

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

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

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

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

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

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

    return result;
}

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

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

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

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

hjk's avatar
hjk committed
435
void SessionManagerPrivate::dependencies(const QString &proName, QStringList &result) const
436 437 438 439 440 441 442 443 444 445
{
    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
446
QStringList SessionManagerPrivate::dependenciesOrder() const
con's avatar
con committed
447 448 449 450 451
{
    QList<QPair<QString, QStringList> > unordered;
    QStringList ordered;

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

    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
479
QList<Project *> SessionManager::projectOrder(Project *project)
con's avatar
con committed
480 481 482 483
{
    QList<Project *> result;

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

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

    return result;
}

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

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

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

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

hjk's avatar
hjk committed
515 516 517
    foreach (Project *p, d->m_projects)
        if (p->rootProjectNode() == rootProjectNode)
            return p;
con's avatar
con committed
518

hjk's avatar
hjk committed
519
    return 0;
con's avatar
con committed
520 521
}

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

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

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

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

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

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

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

565 566 567
    return 0;
}

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

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

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

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

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


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

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

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

633 634 635 636 637
    // TODO: Clear m_modelProjectHash

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        box->exec();

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

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

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

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

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

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

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

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

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

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