runconfiguration.cpp 47.6 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
3 4
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
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
** 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
12 13 14
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
15
**
16 17 18 19 20 21 22
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
con's avatar
con committed
23
**
hjk's avatar
hjk committed
24
****************************************************************************/
hjk's avatar
hjk committed
25

con's avatar
con committed
26
#include "runconfiguration.h"
27

con's avatar
con committed
28
#include "project.h"
Tobias Hunger's avatar
Tobias Hunger committed
29
#include "target.h"
30
#include "toolchain.h"
31
#include "abi.h"
32
#include "buildconfiguration.h"
33
#include "environmentaspect.h"
Tobias Hunger's avatar
Tobias Hunger committed
34
#include "kitinformation.h"
35
#include "runnables.h"
36
#include "session.h"
37

Tobias Hunger's avatar
Tobias Hunger committed
38
#include <extensionsystem/pluginmanager.h>
39

40
#include <utils/algorithm.h>
41
#include <utils/checkablemessagebox.h>
42
#include <utils/outputformatter.h>
43
#include <utils/qtcassert.h>
44
#include <utils/utilsicons.h>
45 46

#include <coreplugin/icore.h>
47
#include <coreplugin/icontext.h>
Tobias Hunger's avatar
Tobias Hunger committed
48

49
#include <QDir>
50
#include <QPushButton>
51
#include <QTimer>
52 53
#include <QLoggingCategory>
#include <QSettings>
con's avatar
con committed
54

hjk's avatar
hjk committed
55
#ifdef Q_OS_OSX
Eike Ziller's avatar
Eike Ziller committed
56
#include <ApplicationServices/ApplicationServices.h>
con's avatar
con committed
57 58
#endif

59 60 61 62
#if defined (WITH_JOURNALD)
#include "journaldwatcher.h"
#endif

63
using namespace Utils;
64
using namespace ProjectExplorer::Internal;
65

66 67 68
namespace {
Q_LOGGING_CATEGORY(statesLog, "qtc.projectmanager.states")
}
69

70
namespace ProjectExplorer {
71

72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
///////////////////////////////////////////////////////////////////////
//
// ISettingsAspect
//
///////////////////////////////////////////////////////////////////////

ISettingsAspect *ISettingsAspect::clone() const
{
    ISettingsAspect *other = create();
    QVariantMap data;
    toMap(data);
    other->fromMap(data);
    return other;
}

///////////////////////////////////////////////////////////////////////
//
// IRunConfigurationAspect
//
///////////////////////////////////////////////////////////////////////

93 94 95
IRunConfigurationAspect::IRunConfigurationAspect(RunConfiguration *runConfig) :
    m_runConfiguration(runConfig)
{ }
96 97 98 99 100

IRunConfigurationAspect::~IRunConfigurationAspect()
{
    delete m_projectSettings;
}
101

102
/*!
103 104
    Returns the widget used to configure this run configuration. Ownership is
    transferred to the caller.
105
*/
106

107
RunConfigWidget *IRunConfigurationAspect::createConfigurationWidget() const
108
{
109
    return m_runConfigWidgetCreator ? m_runConfigWidgetCreator() : nullptr;
110 111
}

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
void IRunConfigurationAspect::setProjectSettings(ISettingsAspect *settings)
{
    m_projectSettings = settings;
}

void IRunConfigurationAspect::setGlobalSettings(ISettingsAspect *settings)
{
    m_globalSettings = settings;
}

void IRunConfigurationAspect::setUsingGlobalSettings(bool value)
{
    m_useGlobalSettings = value;
}

ISettingsAspect *IRunConfigurationAspect::currentSettings() const
{
   return m_useGlobalSettings ? m_globalSettings : m_projectSettings;
}

void IRunConfigurationAspect::fromMap(const QVariantMap &map)
{
    m_projectSettings->fromMap(map);
    m_useGlobalSettings = map.value(m_id.toString() + QLatin1String(".UseGlobalSettings"), true).toBool();
}

void IRunConfigurationAspect::toMap(QVariantMap &map) const
{
    m_projectSettings->toMap(map);
    map.insert(m_id.toString() + QLatin1String(".UseGlobalSettings"), m_useGlobalSettings);
}

144 145 146 147 148
void IRunConfigurationAspect::setRunConfigWidgetCreator(const RunConfigWidgetCreator &runConfigWidgetCreator)
{
    m_runConfigWidgetCreator = runConfigWidgetCreator;
}

149
IRunConfigurationAspect *IRunConfigurationAspect::clone(RunConfiguration *runConfig) const
150
{
151
    IRunConfigurationAspect *other = create(runConfig);
152 153
    if (m_projectSettings)
        other->m_projectSettings = m_projectSettings->clone();
154 155 156 157 158 159 160 161 162 163 164 165 166
    other->m_globalSettings = m_globalSettings;
    other->m_useGlobalSettings = m_useGlobalSettings;
    return other;
}

void IRunConfigurationAspect::resetProjectToGlobalSettings()
{
    QTC_ASSERT(m_globalSettings, return);
    QVariantMap map;
    m_globalSettings->toMap(map);
    m_projectSettings->fromMap(map);
}

167

168 169
/*!
    \class ProjectExplorer::RunConfiguration
170
    \brief The RunConfiguration class is the base class for a run configuration.
171

172 173 174 175 176 177
    A run configuration specifies how a target should be run, while a runner
    does the actual running.

    All RunControls and the target hold a shared pointer to the run
    configuration. That is, the lifetime of the run configuration might exceed
    the life of the target.
178 179 180
    The user might still have a RunControl running (or output tab of that RunControl open)
    and yet unloaded the target.

181 182
    Also, a run configuration might be already removed from the list of run
    configurations
183 184 185
    for a target, but still be runnable via the output tab.
*/

186 187
static std::vector<RunConfiguration::AspectFactory> theAspectFactories;

188
RunConfiguration::RunConfiguration(Target *target, Core::Id id) :
189
    ProjectConfiguration(target, id)
con's avatar
con committed
190
{
Tobias Hunger's avatar
Tobias Hunger committed
191
    Q_ASSERT(target);
192
    ctor();
193

194 195
    for (const AspectFactory &factory : theAspectFactories)
        addExtraAspect(factory(this));
196 197
}

Tobias Hunger's avatar
Tobias Hunger committed
198
RunConfiguration::RunConfiguration(Target *target, RunConfiguration *source) :
199
    ProjectConfiguration(target, source)
200
{
Tobias Hunger's avatar
Tobias Hunger committed
201
    Q_ASSERT(target);
202
    ctor();
203
    foreach (IRunConfigurationAspect *aspect, source->m_aspects) {
204 205 206
        IRunConfigurationAspect *clone = aspect->clone(this);
        if (clone)
            m_aspects.append(clone);
207
    }
con's avatar
con committed
208 209 210 211
}

RunConfiguration::~RunConfiguration()
{
212 213 214
    qDeleteAll(m_aspects);
}

215
void RunConfiguration::addAspectFactory(const AspectFactory &aspectFactory)
216
{
217
    theAspectFactories.push_back(aspectFactory);
con's avatar
con committed
218 219
}

220 221 222 223 224 225
void RunConfiguration::addExtraAspect(IRunConfigurationAspect *aspect)
{
    if (aspect)
        m_aspects += aspect;
}

226 227
void RunConfiguration::ctor()
{
228 229
    connect(this, &RunConfiguration::enabledChanged,
            this, &RunConfiguration::requestRunActionsUpdate);
230

231 232 233 234 235 236 237
    Utils::MacroExpander *expander = macroExpander();
    expander->setDisplayName(tr("Run Settings"));
    expander->setAccumulating(true);
    expander->registerSubProvider([this]() -> Utils::MacroExpander * {
        BuildConfiguration *bc = target()->activeBuildConfiguration();
        return bc ? bc->macroExpander() : target()->macroExpander();
    });
238
    expander->registerPrefix("CurrentRun:Env", tr("Variables in the current run environment"),
239 240 241 242
                             [this](const QString &var) {
        const auto envAspect = extraAspect<EnvironmentAspect>();
        return envAspect ? envAspect->environment().value(var) : QString();
    });
243 244 245
    expander->registerVariable(Constants::VAR_CURRENTRUN_NAME,
            QCoreApplication::translate("ProjectExplorer", "The currently active run configuration's name."),
            [this] { return displayName(); }, false);
246 247
}

248 249 250 251 252 253 254 255 256 257 258 259 260 261
/*!
 * Returns the RunConfiguration of the currently active target
 * of the startup project, if such exists, or \c nullptr otherwise.
 */

RunConfiguration *RunConfiguration::startupRunConfiguration()
{
    if (Project *pro = SessionManager::startupProject()) {
        if (const Target *target = pro->activeTarget())
            return target->activeRunConfiguration();
    }
    return nullptr;
}

262
/*!
263
    Checks whether a run configuration is enabled.
264 265
*/

266
bool RunConfiguration::isEnabled() const
con's avatar
con committed
267
{
268
    return true;
con's avatar
con committed
269 270
}

dt_'s avatar
dt_ committed
271 272 273 274 275
QString RunConfiguration::disabledReason() const
{
    return QString();
}

Tobias Hunger's avatar
Tobias Hunger committed
276 277 278 279 280
bool RunConfiguration::isConfigured() const
{
    return true;
}

281
RunConfiguration::ConfigurationState RunConfiguration::ensureConfigured(QString *errorMessage)
282 283
{
    if (isConfigured())
284
        return Configured;
285 286
    if (errorMessage)
        *errorMessage = tr("Unknown error.");
287
    return UnConfigured;
288 289 290
}


291
BuildConfiguration *RunConfiguration::activeBuildConfiguration() const
con's avatar
con committed
292
{
Tobias Hunger's avatar
Tobias Hunger committed
293
    if (!target())
294
        return nullptr;
Tobias Hunger's avatar
Tobias Hunger committed
295
    return target()->activeBuildConfiguration();
con's avatar
con committed
296 297
}

Tobias Hunger's avatar
Tobias Hunger committed
298
Target *RunConfiguration::target() const
con's avatar
con committed
299
{
Tobias Hunger's avatar
Tobias Hunger committed
300
    return static_cast<Target *>(parent());
con's avatar
con committed
301 302
}

303 304
QVariantMap RunConfiguration::toMap() const
{
305 306
    QVariantMap map = ProjectConfiguration::toMap();

307
    foreach (IRunConfigurationAspect *aspect, m_aspects)
308
        aspect->toMap(map);
309

310 311 312
    return map;
}

313
Abi RunConfiguration::abi() const
314 315 316 317
{
    BuildConfiguration *bc = target()->activeBuildConfiguration();
    if (!bc)
        return Abi::hostAbi();
318
    ToolChain *tc = ToolChainKitInformation::toolChain(target()->kit(), Constants::CXX_LANGUAGE_ID);
319 320 321 322 323
    if (!tc)
        return Abi::hostAbi();
    return tc->targetAbi();
}

324 325
bool RunConfiguration::fromMap(const QVariantMap &map)
{
326
    foreach (IRunConfigurationAspect *aspect, m_aspects)
327
        aspect->fromMap(map);
328

329 330 331
    return ProjectConfiguration::fromMap(map);
}

332 333 334
/*!
    \class ProjectExplorer::IRunConfigurationAspect

335 336
    \brief The IRunConfigurationAspect class provides an additional
    configuration aspect.
337

338 339 340 341
    Aspects are a mechanism to add RunControl-specific options to a run
    configuration without subclassing the run configuration for every addition.
    This prevents a combinatorial explosion of subclasses and eliminates
    the need to add all options to the base class.
342 343 344
*/

/*!
345
    Returns extra aspects.
346 347 348 349

    \sa ProjectExplorer::IRunConfigurationAspect
*/

350 351 352 353
QList<IRunConfigurationAspect *> RunConfiguration::extraAspects() const
{
    return m_aspects;
}
354

355 356
IRunConfigurationAspect *RunConfiguration::extraAspect(Core::Id id) const
{
357
    return Utils::findOrDefault(m_aspects, Utils::equal(&IRunConfigurationAspect::id, id));
358
}
359

360 361 362 363 364 365 366 367 368 369
/*!
    \internal

    \class ProjectExplorer::Runnable

    \brief The ProjectExplorer::Runnable class wraps information needed
    to execute a process on a target device.

    A target specific \l RunConfiguration implementation can specify
    what information it considers necessary to execute a process
370
    on the target. Target specific) \n RunWorker implementation
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
    can use that information either unmodified or tweak it or ignore
    it when setting up a RunControl.

    From Qt Creator's core perspective a Runnable object is opaque.
*/

/*!
    \internal

    \brief Returns a \l Runnable described by this RunConfiguration.
*/

Runnable RunConfiguration::runnable() const
{
    return Runnable();
}

con's avatar
con committed
388
Utils::OutputFormatter *RunConfiguration::createOutputFormatter() const
dt's avatar
dt committed
389
{
con's avatar
con committed
390
    return new Utils::OutputFormatter();
dt's avatar
dt committed
391 392
}

393

394 395 396
/*!
    \class ProjectExplorer::IRunConfigurationFactory

397 398
    \brief The IRunConfigurationFactory class restores run configurations from
    settings.
399 400

    The run configuration factory is used for restoring run configurations from
401 402 403 404 405 406 407 408 409 410 411
    settings and for creating new run configurations in the \gui {Run Settings}
    dialog.
    To restore run configurations, use the
    \c {bool canRestore(Target *parent, const QString &id)}
    and \c {RunConfiguration* create(Target *parent, const QString &id)}
    functions.

    To generate a list of creatable run configurations, use the
    \c {QStringList availableCreationIds(Target *parent)} and
    \c {QString displayNameForType(const QString&)} functions. To create a
    run configuration, use \c create().
412 413 414 415 416
*/

/*!
    \fn QStringList ProjectExplorer::IRunConfigurationFactory::availableCreationIds(Target *parent) const

417
    Shows the list of possible additions to a target. Returns a list of types.
418 419 420
*/

/*!
421
    \fn QString ProjectExplorer::IRunConfigurationFactory::displayNameForId(Core::Id id) const
422
    Translates the types to names to display to the user.
423 424
*/

425 426
IRunConfigurationFactory::IRunConfigurationFactory(QObject *parent) :
    QObject(parent)
con's avatar
con committed
427 428 429
{
}

430
RunConfiguration *IRunConfigurationFactory::create(Target *parent, Core::Id id)
431 432
{
    if (!canCreate(parent, id))
433
        return nullptr;
434 435
    RunConfiguration *rc = doCreate(parent, id);
    if (!rc)
436
        return nullptr;
437 438 439
    return rc;
}

440 441 442
RunConfiguration *IRunConfigurationFactory::restore(Target *parent, const QVariantMap &map)
{
    if (!canRestore(parent, map))
443
        return nullptr;
444 445 446
    RunConfiguration *rc = doRestore(parent, map);
    if (!rc->fromMap(map)) {
        delete rc;
447
        rc = nullptr;
448 449 450 451
    }
    return rc;
}

Tobias Hunger's avatar
Tobias Hunger committed
452
IRunConfigurationFactory *IRunConfigurationFactory::find(Target *parent, const QVariantMap &map)
Tobias Hunger's avatar
Tobias Hunger committed
453
{
454 455 456 457
    return ExtensionSystem::PluginManager::getObject<IRunConfigurationFactory>(
        [&parent, &map](IRunConfigurationFactory *factory) {
            return factory->canRestore(parent, map);
        });
Tobias Hunger's avatar
Tobias Hunger committed
458 459
}

460 461
IRunConfigurationFactory *IRunConfigurationFactory::find(Target *parent, RunConfiguration *rc)
{
462 463 464 465
    return ExtensionSystem::PluginManager::getObject<IRunConfigurationFactory>(
        [&parent, rc](IRunConfigurationFactory *factory) {
            return factory->canClone(parent, rc);
        });
466 467
}

Tobias Hunger's avatar
Tobias Hunger committed
468
QList<IRunConfigurationFactory *> IRunConfigurationFactory::find(Target *parent)
Tobias Hunger's avatar
Tobias Hunger committed
469
{
470 471 472 473
    return ExtensionSystem::PluginManager::getObjects<IRunConfigurationFactory>(
        [&parent](IRunConfigurationFactory *factory) {
            return !factory->availableCreationIds(parent).isEmpty();
        });
Tobias Hunger's avatar
Tobias Hunger committed
474 475
}

476 477 478 479 480 481 482 483
using WorkerFactories = std::vector<RunControl::WorkerFactory>;

static WorkerFactories &theWorkerFactories()
{
    static WorkerFactories factories;
    return factories;
}

484 485
bool RunControl::WorkerFactory::canRun(RunConfiguration *runConfiguration, Core::Id runMode) const
{
486
    if (runMode != this->runMode)
487 488 489 490 491 492
        return false;
    if (!constraint)
        return true;
    return constraint(runConfiguration);
}

493 494
/*!
    \class ProjectExplorer::RunControl
495
    \brief The RunControl class instances represent one item that is run.
496 497 498 499
*/

/*!
    \fn QIcon ProjectExplorer::RunControl::icon() const
500
    Returns the icon to be shown in the Outputwindow.
501

502 503
    TODO the icon differs currently only per "mode", so this is more flexible
    than it needs to be.
504 505
*/

506

hjk's avatar
hjk committed
507 508
namespace Internal {

509 510 511 512 513
enum class RunWorkerState
{
    Initialized, Starting, Running, Stopping, Done, Failed
};

hjk's avatar
hjk committed
514 515 516 517 518 519 520 521 522 523 524
static QString stateName(RunWorkerState s)
{
#    define SN(x) case x: return QLatin1String(#x);
    switch (s) {
        SN(RunWorkerState::Initialized)
        SN(RunWorkerState::Starting)
        SN(RunWorkerState::Running)
        SN(RunWorkerState::Stopping)
        SN(RunWorkerState::Done)
        SN(RunWorkerState::Failed)
    }
525
    return QString("<unknown: %1>").arg(int(s));
hjk's avatar
hjk committed
526 527
#    undef SN
}
528 529 530 531 532 533 534 535 536 537 538

class RunWorkerPrivate : public QObject
{
public:
    RunWorkerPrivate(RunWorker *runWorker, RunControl *runControl);

    bool canStart() const;
    void timerEvent(QTimerEvent *ev) override;

    RunWorker *q;
    RunWorkerState state = RunWorkerState::Initialized;
539
    QPointer<RunControl> runControl;
540
    QList<RunWorker *> dependencies;
541
    QString id;
542 543 544 545 546 547

    QVariantMap data;
    int startWatchdogInterval = 0;
    int startWatchdogTimerId = -1;
    int stopWatchdogInterval = 0; // 5000;
    int stopWatchdogTimerId = -1;
548
    bool supportsReRunning = true;
549 550 551 552 553 554 555 556 557
};

enum class RunControlState
{
    Initialized,      // Default value after creation.
    Starting,         // Actual process/tool starts.
    Running,          // All good and running.
    Stopping,         // initiateStop() was called, stop application/tool
    Stopped,          // all good, but stopped. Can possibly be re-started
558 559
    Finishing,        // Application tab manually closed
    Finished          // Final state, will self-destruct with deleteLater()
560 561 562 563 564 565 566 567 568 569 570
};

static QString stateName(RunControlState s)
{
#    define SN(x) case x: return QLatin1String(#x);
    switch (s) {
        SN(RunControlState::Initialized)
        SN(RunControlState::Starting)
        SN(RunControlState::Running)
        SN(RunControlState::Stopping)
        SN(RunControlState::Stopped)
571 572
        SN(RunControlState::Finishing)
        SN(RunControlState::Finished)
573
    }
574
    return QString("<unknown: %1>").arg(int(s));
575 576 577
#    undef SN
}

578
class RunControlPrivate : public QObject
con's avatar
con committed
579
{
hjk's avatar
hjk committed
580
public:
581 582
    RunControlPrivate(RunControl *parent, RunConfiguration *runConfiguration, Core::Id mode)
        : q(parent), runMode(mode), runConfiguration(runConfiguration)
hjk's avatar
hjk committed
583
    {
584
        icon = Icons::RUN_SMALL_TOOLBAR;
hjk's avatar
hjk committed
585
        if (runConfiguration) {
586
            runnable = runConfiguration->runnable();
hjk's avatar
hjk committed
587 588
            displayName  = runConfiguration->displayName();
            outputFormatter = runConfiguration->createOutputFormatter();
hjk's avatar
hjk committed
589 590
            device = DeviceKitInformation::device(runConfiguration->target()->kit());
            project = runConfiguration->target()->project();
hjk's avatar
hjk committed
591 592
        }
    }
593

hjk's avatar
hjk committed
594 595
    ~RunControlPrivate()
    {
596 597 598
        QTC_CHECK(state == RunControlState::Finished || state == RunControlState::Initialized);
        disconnect();
        q = nullptr;
599
        qDeleteAll(m_workers);
600
        m_workers.clear();
hjk's avatar
hjk committed
601
        delete outputFormatter;
dt's avatar
dt committed
602
    }
603

604 605 606 607
    Q_ENUM(RunControlState)

    void checkState(RunControlState expectedState);
    void setState(RunControlState state);
608

609 610
    void debugMessage(const QString &msg);

611
    void initiateStart();
612
    void initiateReStart();
613
    void continueStart();
614
    void initiateStop();
615
    void initiateFinish();
616

617 618 619
    void onWorkerStarted(RunWorker *worker);
    void onWorkerStopped(RunWorker *worker);
    void onWorkerFailed(RunWorker *worker, const QString &msg);
620

621 622
    void showError(const QString &msg);

623
    static bool isAllowedTransition(RunControlState from, RunControlState to);
624
    bool supportsReRunning() const;
625 626

    RunControl *q;
hjk's avatar
hjk committed
627 628
    QString displayName;
    Runnable runnable;
hjk's avatar
hjk committed
629
    IDevice::ConstPtr device;
hjk's avatar
hjk committed
630 631
    Core::Id runMode;
    Utils::Icon icon;
632 633
    const QPointer<RunConfiguration> runConfiguration; // Not owned.
    QPointer<Project> project; // Not owned.
634
    QPointer<Utils::OutputFormatter> outputFormatter = nullptr;
635
    std::function<bool(bool*)> promptToStop;
636
    std::vector<RunControl::WorkerFactory> m_factories;
hjk's avatar
hjk committed
637 638

    // A handle to the actual application process.
639
    Utils::ProcessHandle applicationProcessHandle;
hjk's avatar
hjk committed
640

641
    RunControlState state = RunControlState::Initialized;
642

643
    QList<QPointer<RunWorker>> m_workers;
hjk's avatar
hjk committed
644 645 646 647
};

} // Internal

648 649
using namespace Internal;

650
RunControl::RunControl(RunConfiguration *runConfiguration, Core::Id mode) :
651
    d(new RunControlPrivate(this, runConfiguration, mode))
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
{
#ifdef WITH_JOURNALD
    JournaldWatcher::instance()->subscribe(this, [this](const JournaldWatcher::LogEntry &entry) {
        if (entry.value("_MACHINE_ID") != JournaldWatcher::instance()->machineId())
            return;

        const QByteArray pid = entry.value("_PID");
        if (pid.isEmpty())
            return;

        const qint64 pidNum = static_cast<qint64>(QString::fromLatin1(pid).toInt());
        if (pidNum != d->applicationProcessHandle.pid())
            return;

        const QString message = QString::fromUtf8(entry.value("MESSAGE")) + "\n";
        appendMessageRequested(this, message, Utils::OutputFormat::LogMessageFormat);
    });
#endif
}
con's avatar
con committed
671

672
RunControl::~RunControl()
con's avatar
con committed
673
{
674 675 676
#ifdef WITH_JOURNALD
    JournaldWatcher::instance()->unsubscribe(this);
#endif
hjk's avatar
hjk committed
677
    delete d;
678
    d = nullptr;
dt's avatar
dt committed
679
}
680

681 682
void RunControl::initiateStart()
{
683 684
    emit aboutToStart();
    d->initiateStart();
685 686
}

687 688 689 690 691 692
void RunControl::initiateReStart()
{
    emit aboutToStart();
    d->initiateReStart();
}

693
void RunControl::initiateStop()
694 695 696 697
{
    d->initiateStop();
}

698 699
void RunControl::initiateFinish()
{
hjk's avatar
hjk committed
700
    QTimer::singleShot(0, d, &RunControlPrivate::initiateFinish);
701 702
}

703
using WorkerCreators = QHash<Core::Id, RunControl::WorkerCreator>;
704

705
static WorkerCreators &theWorkerCreators()
706
{
707 708
    static WorkerCreators creators;
    return creators;
709 710
}

711
void RunControl::registerWorkerCreator(Core::Id id, const WorkerCreator &workerCreator)
712
{
713 714 715
    theWorkerCreators().insert(id, workerCreator);
    auto keys = theWorkerCreators().keys();
    Q_UNUSED(keys);
716 717
}

718
RunWorker *RunControl::createWorker(Core::Id id)
719
{
720 721
    auto keys = theWorkerCreators().keys();
    Q_UNUSED(keys);
722
    WorkerCreator creator = theWorkerCreators().value(id);
723 724 725 726 727 728
    if (creator)
        return creator(this);
    creator = device()->workerCreator(id);
    if (creator)
        return creator(this);
    return nullptr;
729 730
}

731
RunControl::WorkerCreator RunControl::producer(RunConfiguration *runConfiguration, Core::Id runMode)
732
{
733 734 735 736
    WorkerFactories candidates;
    for (const RunControl::WorkerFactory &factory : theWorkerFactories()) {
        if (factory.canRun(runConfiguration, runMode))
            candidates.push_back(factory);
737
    }
738 739 740 741 742 743 744 745 746 747 748

    if (candidates.empty())
        return {};

    RunControl::WorkerFactory bestFactory = *candidates.begin();
    for (const RunControl::WorkerFactory &factory : candidates) {
        if (factory.priority > bestFactory.priority)
            bestFactory = factory;
    }

    return bestFactory.producer;
749 750 751 752 753 754 755
}

void RunControl::addWorkerFactory(const RunControl::WorkerFactory &workerFactory)
{
    theWorkerFactories().push_back(workerFactory);
}

756
void RunControlPrivate::initiateStart()
757
{
758 759 760 761 762 763 764
    checkState(RunControlState::Initialized);
    setState(RunControlState::Starting);
    debugMessage("Queue: Starting");

    continueStart();
}

765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
void RunControlPrivate::initiateReStart()
{
    checkState(RunControlState::Stopped);

    // Re-set worked on re-runs.
    for (RunWorker *worker : m_workers) {
        if (worker->d->state == RunWorkerState::Done)
            worker->d->state = RunWorkerState::Initialized;
    }

    setState(RunControlState::Starting);
    debugMessage("Queue: ReStarting");

    continueStart();
}

781 782 783 784 785 786 787
void RunControlPrivate::continueStart()
{
    checkState(RunControlState::Starting);
    bool allDone = true;
    debugMessage("Looking for next worker");
    for (RunWorker *worker : m_workers) {
        if (worker) {
788 789
            const QString &workerId = worker->d->id;
            debugMessage("  Examining worker " + workerId);
790 791
            switch (worker->d->state) {
                case RunWorkerState::Initialized:
792
                    debugMessage("  " + workerId + " is not done yet.");
793
                    if (worker->d->canStart()) {
794
                        debugMessage("Starting " + workerId);
795 796 797 798 799
                        worker->d->state = RunWorkerState::Starting;
                        QTimer::singleShot(0, worker, &RunWorker::initiateStart);
                        return;
                    }
                    allDone = false;
800
                    debugMessage("  " + workerId + " cannot start.");
801 802
                    break;
                case RunWorkerState::Starting:
803
                    debugMessage("  " + workerId + " currently starting");
804 805 806
                    allDone = false;
                    break;
                case RunWorkerState::Running:
807
                    debugMessage("  " + workerId + " currently running");
808 809
                    break;
                case RunWorkerState::Stopping:
810
                    debugMessage("  " + workerId + " currently stopping");
811 812 813
                    continue;
                case RunWorkerState::Failed:
                    // Should not happen.
814
                    debugMessage("  " + workerId + " failed before");
815 816 817 818
                    QTC_CHECK(false);
                    //setState(RunControlState::Stopped);
                    break;
                case RunWorkerState::Done:
819
                    debugMessage("  " + workerId + " was done before");
820 821 822 823 824 825 826 827
                    break;
            }
        } else {
            debugMessage("Found unknown deleted worker while starting");
        }
    }
    if (allDone)
        setState(RunControlState::Running);
828 829
}

830 831
void RunControlPrivate::initiateStop()
{
832 833
    checkState(RunControlState::Running);
    setState(RunControlState::Stopping);
834
    debugMessage("Queue: Stopping for all workers");
835

836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
    bool allDone = true;
    for (RunWorker *worker : m_workers) {
        if (worker) {
            const QString &workerId = worker->d->id;
            debugMessage("  Examining worker " + workerId);
            switch (worker->d->state) {
                case RunWorkerState::Initialized:
                    debugMessage("  " + workerId + " was Initialized, setting to Done");
                    worker->d->state = RunWorkerState::Done;
                    break;
                case RunWorkerState::Stopping:
                    debugMessage("  " + workerId + " was already Stopping. Keeping it that way");
                    allDone = false;
                    break;
                case RunWorkerState::Starting:
                    debugMessage("  " + workerId + " was Starting, queuing stop");
                    worker->d->state = RunWorkerState::Stopping;
                    QTimer::singleShot(0, worker, &RunWorker::initiateStop);
                    allDone = false;
                    break;
                case RunWorkerState::Running:
                    debugMessage("  " + workerId + " was Running, queuing stop");
                    worker->d->state = RunWorkerState::Stopping;
                    allDone = false;
                    QTimer::singleShot(0, worker, &RunWorker::initiateStop);
                    break;
                case RunWorkerState::Done:
                    debugMessage("  " + workerId + " was Done. Good.");
                    break;
                case RunWorkerState::Failed:
                    debugMessage("  " + workerId + " was Failed. Good");
                    break;
            }
        } else {
            debugMessage("Found unknown deleted worker");
        }
    }
    if (allDone) {
        debugMessage("All stopped.");
        setState(RunControlState::Stopped);
    } else {
        debugMessage("Not all workers stopped. Waiting...");
    }
879 880
}

881
void RunControlPrivate::initiateFinish()
882
{
883 884 885
    setState(RunControlState::Finishing);
    debugMessage("Ramping down");

886
    bool allDone = true;
887 888
    for (RunWorker *worker : m_workers) {
        if (worker) {
889 890
            const QString &workerId = worker->d->id;
            debugMessage("  Examining worker " + workerId);
891 892
            switch (worker->d->state) {
                case RunWorkerState::Initialized:
893
                    debugMessage("  " + workerId + " was Initialized, setting to Done");
894 895 896
                    worker->d->state = RunWorkerState::Done;
                    break;
                case RunWorkerState::Stopping:
897
                    debugMessage("  " + workerId + " was already Stopping. Keeping it that way");
898
                    allDone = false;
899 900
                    break;
                case RunWorkerState::Starting:
901
                    debugMessage("  " + workerId + " was Starting, queuing stop");
902
                    worker->d->state = RunWorkerState::Stopping;
903
                    QTimer::singleShot(0, worker, &RunWorker::initiateStop);
904 905
                    allDone = false;
                    break;
906
                case RunWorkerState::Running:
907
                    debugMessage("  " + workerId + " was Running, queuing stop");
908
                    worker->d->state = RunWorkerState::Stopping;
909
                    allDone = false;
910
                    QTimer::singleShot(0, worker, &RunWorker::initiateStop);
911
                    break;
912
                case RunWorkerState::Done:
913
                    debugMessage("  " + workerId + " was Done. Good.");
914 915
                    break;
                case RunWorkerState::Failed:
916
                    debugMessage("  " + workerId + " was Failed. Good");
917 918 919 920 921
                    break;
            }
        } else {
            debugMessage("Found unknown deleted worker");
        }
922
    }
923
    if (allDone) {
924 925 926
        setState(RunControlState::Finished);
    } else {
        debugMessage("Not all workers finished. Waiting...");
927
    }
928 929
}

930
void RunControlPrivate::onWorkerStarted(RunWorker *worker)
931
{
932
    worker->d->state = RunWorkerState::Running;
933

934
    if (state == RunControlState::Starting) {
935
        debugMessage(worker->d->id + " start succeeded");
936 937
        continueStart();
        return;
938
    }
939
    showError(tr("Unexpected run control state %1 when worker %2 started.")
940
              .arg(stateName(state))
941
              .arg(worker->d->id));
942 943
}

944
void RunControlPrivate::onWorkerFailed(RunWorker *worker, const QString &msg)
945
{
946
    worker->d->state = RunWorkerState::Failed;
947

948
    showError(msg);
949
    initiateStop();
950
}
951

952
void RunControlPrivate::onWorkerStopped(RunWorker *worker)
953
{
954
    const QString &workerId = worker->d->id;
hjk's avatar
hjk committed
955 956 957 958
    switch (worker->d->state) {
    case RunWorkerState::Running:
        // That was a spontaneous stop.
        worker->d->state = RunWorkerState::Done;
959
        debugMessage(workerId + " stopped spontaneously.");
hjk's avatar
hjk committed
960 961 962
        break;
    case RunWorkerState::Stopping:
        worker->d->state = RunWorkerState::Done;
963
        debugMessage(workerId + " stopped expectedly.");
hjk's avatar
hjk committed
964
        break;
965 966 967 968
    case RunWorkerState::Done:
        worker->d->state = RunWorkerState::Done;
        debugMessage(workerId + " stopped twice. Huh? But harmless.");
        return; // Sic!
hjk's avatar
hjk committed
969
    default:
970
        debugMessage(workerId + " stopped unexpectedly in state"
hjk's avatar
hjk committed
971 972 973 974
                     + stateName(worker->d->state));
        worker->d->state = RunWorkerState::Failed;
        break;
    }
975 976 977 978 979 980 981 982 983

    debugMessage("Checking whether all stopped");
    bool allDone = true;
    for (RunWorker *worker : m_workers) {
        if (worker) {
            const QString &workerId = worker->d->id;
            debugMessage("  Examining worker " + workerId);
            switch (worker->d->state) {
                case RunWorkerState::Initialized:
984
                    debugMessage("  " + workerId + " was Initialized.");
985 986
                    break;
                case RunWorkerState::Starting:
987
                    debugMessage("  " + workerId + " was Starting, waiting for its response");
988 989 990
                    allDone = false;
                    break;
                case RunWorkerState::Running:
991
                    debugMessage("  " + workerId + " was Running, waiting for its response");
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
                    allDone = false;
                    break;
                case RunWorkerState::Stopping:
                    debugMessage("  " + workerId + " was already Stopping. Keeping it that way");
                    allDone = false;
                    break;
                case RunWorkerState::Done:
                    debugMessage("  " + workerId + " was Done. Good.");
                    break;
                case RunWorkerState::Failed:
                    debugMessage("  " + workerId + " was Failed. Good");
                    break;
            }
        } else {
            debugMessage("Found unknown deleted worker");
        }
    }
    if (state == RunControlState::Finishing) {
        if (allDone) {
            debugMessage("All finished. Deleting myself");
            setState(RunControlState::Finished);
        } else {
            debugMessage("Not all workers finished. Waiting...");
        }
    } else {
        if (allDone) {
            if (state == RunControlState::Stopped) {
                debugMessage("All workers stopped, but runControl was already stopped.");
            } else {
                debugMessage("All workers stopped. Set runControl to Stopped");
                setState(RunControlState::Stopped);
            }
        } else {
            debugMessage("Not all workers stopped. Waiting...");
        }
    }
1028 1029
}

1030 1031 1032
void RunControlPrivate::showError(const QString &msg)
{
    if (!msg.isEmpty())
1033
        q->appendMessage(msg + '\n', ErrorMessageFormat);
1034 1035
}

1036
Utils::OutputFormatter *RunControl::outputFormatter() const
dt's avatar
dt committed
1037
{
hjk's avatar
hjk committed
1038
    return d->outputFormatter;
con's avatar
con committed
1039 1040
}

1041
Core::Id RunControl::runMode() const
dt's avatar
dt committed
1042
{
hjk's avatar
hjk committed
1043 1044 1045 1046 1047 1048
    return d->runMode;
}

const Runnable &RunControl::runnable() const
{
    return d->runnable;
dt's avatar
dt committed
1049 1050
}

1051 1052
void RunControl::setRunnable(const Runnable &runnable)
{
hjk's avatar
hjk committed
1053 1054 1055
    d->runnable = runnable;
}

1056 1057
QString RunControl::displayName() const
{
hjk's avatar
hjk committed
1058
    return d->displayName;
1059 1060
}

1061 1062
void RunControl::setDisplayName(const QString &displayName)
{
hjk's avatar
hjk committed
1063
    d->displayName = displayName;
1064 1065
}

1066 1067
void RunControl::setIcon(const Utils::Icon &icon)
{
hjk's avatar
hjk committed
1068
    d->icon = icon;
1069 1070 1071 1072
}

Utils::Icon RunControl::icon() const
{
hjk's avatar
hjk committed
1073
    return d->icon;
1074 1075
}

1076 1077
Abi RunControl::abi() const
{
hjk's avatar
hjk committed
1078
    if (const RunConfiguration *rc = d->runConfiguration.data())
1079 1080 1081 1082
        return rc->abi();
    return Abi();
}

hjk's avatar
hjk committed
1083 1084 1085 1086 1087
IDevice::ConstPtr RunControl::device() const
{
   return d->device;
}

1088 1089
RunConfiguration *RunControl::runConfiguration() const
{
hjk's avatar
hjk committed
1090
    return d->runConfiguration.data();
1091 1092
}

1093 1094
Project *RunControl::project() const
{
hjk's avatar
hjk committed
1095