File: statemachineviewerwidget.cpp

package info (click to toggle)
gammaray 3.3.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 21,612 kB
  • sloc: cpp: 94,643; ansic: 2,227; sh: 336; python: 164; yacc: 90; lex: 82; xml: 61; makefile: 26
file content (450 lines) | stat: -rw-r--r-- 17,325 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
/*
  statemachineviewerwidget.cpp

  This file is part of GammaRay, the Qt application inspection and manipulation tool.

  SPDX-FileCopyrightText: 2014 Klarälvdalens Datakonsult AB, a KDAB Group company <info@kdab.com>
  Author: Kevin Funk <kevin.funk@kdab.com>

  SPDX-License-Identifier: GPL-2.0-or-later

  Contact KDAB at <info@kdab.com> for commercial licensing options.
*/

#include "statemachineviewerwidget.h"
#include "ui_statemachineviewerwidget.h"

#include "statemachineviewerclient.h"
#include "statemodeldelegate.h"
#include "statemodel.h"
#include "statemachinedebuginterface.h"

#include <common/objectbroker.h>
#include <common/objectmodel.h>
#include <common/probecontrollerinterface.h>
#include <ui/contextmenuextension.h>
#include <ui/clientdecorationidentityproxymodel.h>

#include <elementmodel.h>
#include <layoutproperties.h>
#include <state.h>
#include <transition.h>
#include <runtimecontroller.h>
#include <statemachinescene.h>
#include <statemachinetoolbar.h>
#include <statemachineview.h>

#include <QDebug>
#include <QMenu>
#include <QLayout>
#include <QScopedValueRollback>
#include <QScrollBar>
#include <QSettings>

#define IF_DEBUG(x)

using namespace GammaRay;

namespace {
class SelectionModelSyncer : public QObject
{
public:
    SelectionModelSyncer(StateMachineViewerWidget *widget);

private Q_SLOTS:
    void handle_objectInspector_currentChanged(const QModelIndex &index);
    void handle_stateMachineView_currentChanged(const QModelIndex &index);

    StateMachineViewerWidget *m_widget;
    bool m_updatesEnabled;
};

SelectionModelSyncer::SelectionModelSyncer(StateMachineViewerWidget *widget)
    : QObject(widget)
    , m_widget(widget)
    , m_updatesEnabled(true)
{
    connect(widget->objectInspector()->selectionModel(), &QItemSelectionModel::currentChanged,
            this, &SelectionModelSyncer::handle_objectInspector_currentChanged);
    connect(
        widget->stateMachineView()->scene()->selectionModel(), &QItemSelectionModel::currentChanged,
        this, &SelectionModelSyncer::handle_stateMachineView_currentChanged);
}

void SelectionModelSyncer::handle_objectInspector_currentChanged(const QModelIndex &index)
{
    if (!m_updatesEnabled)
        return;

    QScopedValueRollback<bool> block(m_updatesEnabled);
    m_updatesEnabled = false;

    const auto stateId = index.data(StateModel::StateIdRole).value<StateId>();

    const auto model = m_widget->stateMachineView()->scene()->model();
    const auto matches = model->match(model->index(0, 0), KDSME::StateModel::InternalIdRole,
                                      static_cast<quintptr>(stateId), 1,
                                      Qt::MatchExactly | Qt::MatchRecursive | Qt::MatchWrap);
    auto selectionModel = m_widget->stateMachineView()->scene()->selectionModel();
    selectionModel->setCurrentIndex(matches.value(0), QItemSelectionModel::SelectCurrent);
}

void SelectionModelSyncer::handle_stateMachineView_currentChanged(const QModelIndex &index)
{
    if (!m_updatesEnabled)
        return;

    QScopedValueRollback<bool> block(m_updatesEnabled);
    m_updatesEnabled = false;

    const auto internalId = index.data(KDSME::StateModel::InternalIdRole).value<quintptr>();
    const auto model = m_widget->objectInspector()->model();
    const auto matches = model->match(model->index(0, 0), StateModel::StateIdRole,
                                      QVariant::fromValue(StateId(internalId)), 1,
                                      Qt::MatchExactly | Qt::MatchRecursive | Qt::MatchWrap);
    auto selectionModel = m_widget->objectInspector()->selectionModel();
    selectionModel->setCurrentIndex(matches.value(
                                        0),
                                    QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows);
}

QObject *createStateMachineViewerClient(const QString & /*name*/, QObject *parent)
{
    return new StateMachineViewerClient(parent);
}

KDSME::RuntimeController::Configuration toSmeConfiguration(const StateMachineConfiguration &config,
                                                           const QHash<StateId,
                                                                       KDSME::State *> &map)
{
    KDSME::RuntimeController::Configuration result;
    for (const StateId &id : config) {
        if (auto state = map.value(id))
            result << state;
    }
    return result;
}
}

StateMachineViewerWidget::StateMachineViewerWidget(QWidget *parent, Qt::WindowFlags f)
    : QWidget(parent, f)
    , m_ui(new Ui::StateMachineViewerWidget)
    , m_stateManager(this)
    , m_machine(nullptr)
    , m_showLog(false)
{
    ObjectBroker::registerClientObjectFactoryCallback<StateMachineViewerInterface *>(
        createStateMachineViewerClient);
    m_interface = ObjectBroker::object<StateMachineViewerInterface *>();

    m_ui->setupUi(this);

    // set up log expanding widget
    connect(m_ui->hideLogPushButton, &QPushButton::clicked, this, [this]() {
        setShowLog(false);
    });
    connect(m_ui->showLogPushButton, &QPushButton::clicked, this, [this]() {
        setShowLog(true);
    });
    setShowLog(false);

    QAbstractItemModel *stateMachineModel = ObjectBroker::model(QStringLiteral("com.kdab.GammaRay.StateMachineModel"));
    m_ui->stateMachinesView->setModel(stateMachineModel);
    connect(m_ui->stateMachinesView, SIGNAL(currentIndexChanged(int)), m_interface,
            SLOT(selectStateMachine(int)));

    QAbstractItemModel *stateModel = ObjectBroker::model(QStringLiteral("com.kdab.GammaRay.StateModel"));
    ClientDecorationIdentityProxyModel *stateProxyModel = new ClientDecorationIdentityProxyModel(this);
    stateProxyModel->setSourceModel(stateModel);
    connect(stateProxyModel, SIGNAL(modelReset()), this, SLOT(stateModelReset()));

    m_ui->singleStateMachineView->header()->setObjectName("singleStateMachineViewHeader");
    m_ui->singleStateMachineView->setExpandNewContent(true);
    m_ui->singleStateMachineView->setDeferredResizeMode(0, QHeaderView::Stretch);
    m_ui->singleStateMachineView->setDeferredResizeMode(1, QHeaderView::ResizeToContents);
    m_ui->singleStateMachineView->setItemDelegate(new StateModelDelegate(this));
    m_ui->singleStateMachineView->setModel(stateProxyModel);
    m_ui->singleStateMachineView->setSelectionModel(ObjectBroker::selectionModel(stateProxyModel));
    connect(m_ui->singleStateMachineView, &QWidget::customContextMenuRequested, this,
            &StateMachineViewerWidget::objectInspectorContextMenu);

    connect(m_ui->actionStartStopStateMachine, SIGNAL(triggered()), m_interface,
            SLOT(toggleRunning()));
    addAction(m_ui->actionStartStopStateMachine);

    auto separatorAction = new QAction(this);
    separatorAction->setSeparator(true);
    addAction(separatorAction);

    m_stateMachineView = new KDSME::StateMachineView;
    m_ui->horizontalSplitter->addWidget(m_stateMachineView);

    m_stateMachineView->scene()->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(m_stateMachineView->scene(), &KDSME::StateMachineScene::customContextMenuEvent,
            this, [this](KDSME::AbstractSceneContextMenuEvent *event) {
                const auto objectId = ObjectId(reinterpret_cast<QObject *>(event->elementUnderCursor()->internalId()));
                const auto model = objectInspector()->model();
                const auto matches = model->match(
                    model->index(0, 0), ObjectModel::ObjectIdRole,
                    QVariant::fromValue(objectId), 1,
                    Qt::MatchExactly | Qt::MatchRecursive | Qt::MatchWrap);
                showContextMenuForObject(matches.value(0), event->globalPos());
            });

    connect(m_interface, SIGNAL(message(QString)), this, SLOT(showMessage(QString)));
    connect(m_interface, SIGNAL(stateConfigurationChanged(GammaRay::StateMachineConfiguration)),
            this, SLOT(stateConfigurationChanged(GammaRay::StateMachineConfiguration)));
    connect(m_interface,
            SIGNAL(stateAdded(GammaRay::StateId, GammaRay::StateId, bool, QString, GammaRay::StateType, bool)),
            this,
            SLOT(stateAdded(GammaRay::StateId, GammaRay::StateId, bool, QString, GammaRay::StateType, bool)));
    connect(m_interface,
            SIGNAL(transitionAdded(GammaRay::TransitionId, GammaRay::StateId, GammaRay::StateId, QString)),
            this,
            SLOT(transitionAdded(GammaRay::TransitionId, GammaRay::StateId, GammaRay::StateId, QString)));
    connect(m_interface, SIGNAL(statusChanged(bool, bool)), this, SLOT(statusChanged(bool, bool)));
    connect(m_interface, SIGNAL(transitionTriggered(GammaRay::TransitionId, QString)),
            this, SLOT(transitionTriggered(GammaRay::TransitionId, QString)));

    connect(m_interface, SIGNAL(aboutToRepopulateGraph()), this, SLOT(clearGraph()));
    connect(m_interface, SIGNAL(graphRepopulated()), this, SLOT(repopulateView()));

    // append actions for the state machine view
    KDSME::StateMachineToolBar *toolBar = new KDSME::StateMachineToolBar(m_stateMachineView, this);
    toolBar->setHidden(true);
    addActions(toolBar->actions());

    m_interface->repopulateGraph();

    // share selection model
    new SelectionModelSyncer(this);

    m_stateManager.setDefaultSizes(m_ui->verticalSplitter, UISizeVector() << "50%"
                                                                          << "50%");
    m_stateManager.setDefaultSizes(m_ui->horizontalSplitter, UISizeVector() << "30%"
                                                                            << "70%");

    loadSettings();
}

StateMachineViewerWidget::~StateMachineViewerWidget()
{
    saveSettings();
}

void StateMachineViewerWidget::saveTargetState(QSettings *settings) const
{
    settings->setValue("ShowLog", m_showLog);

    const auto scene = m_stateMachineView->scene();
    settings->setValue("ShowTransitionsLabel", scene->layoutProperties()->showTransitionLabels());
    settings->setValue("MaximumDepth", scene->maximumDepth());
}

void StateMachineViewerWidget::restoreTargetState(QSettings *settings)
{
    setShowLog(settings->value("ShowLog", m_showLog).toBool());

    auto scene = m_stateMachineView->scene();
    scene->layoutProperties()->setShowTransitionLabels(settings->value("ShowTransitionsLabel", true).toBool());
    scene->setMaximumDepth(settings->value("MaximumDepth", 3).toInt());
}

void StateMachineViewerWidget::showContextMenuForObject(const QModelIndex &index,
                                                        const QPoint &globalPos)
{
    if (!index.isValid())
        return;

    Q_ASSERT(index.model() == objectInspector()->model());

    const auto objectId = index.data(ObjectModel::ObjectIdRole).value<ObjectId>();

    QMenu menu(tr("Entity @ %1").arg(QLatin1String("0x") + QString::number(objectId.id(), 16)));
    ContextMenuExtension ext(objectId);
    ext.setLocation(ContextMenuExtension::Creation, index.data(ObjectModel::CreationLocationRole).value<SourceLocation>());
    ext.setLocation(ContextMenuExtension::Declaration,
                    index.data(ObjectModel::DeclarationLocationRole).value<SourceLocation>());
    ext.populateMenu(&menu);

    menu.exec(globalPos);
}

KDSME::StateMachineView *StateMachineViewerWidget::stateMachineView() const
{
    return m_stateMachineView;
}

DeferredTreeView *StateMachineViewerWidget::objectInspector() const
{
    return m_ui->singleStateMachineView;
}

void StateMachineViewerWidget::loadSettings()
{
    QSettings settings;
    settings.beginGroup("Plugin_StateMachineViewer");
    m_stateMachineView->setThemeName(settings.value("ThemeName", "SystemTheme").toString());
    settings.endGroup();
    settings.sync();
}

void StateMachineViewerWidget::saveSettings()
{
    QSettings settings;
    settings.beginGroup("Plugin_StateMachineViewer");
    settings.setValue("ThemeName", m_stateMachineView->themeName());
    settings.endGroup();
    settings.sync();
}

void StateMachineViewerWidget::showMessage(const QString &message)
{
    // update log
    auto logTextEdit = m_ui->logTextEdit;
    logTextEdit->appendPlainText(message);

    // auto-scroll hack
    QScrollBar *sb = logTextEdit->verticalScrollBar();
    sb->setValue(sb->maximum());
}

void StateMachineViewerWidget::stateConfigurationChanged(const StateMachineConfiguration &config)
{
    if (m_machine)
        m_machine->runtimeController()->setActiveConfiguration(toSmeConfiguration(config,
                                                                                  m_idToStateMap));
}

void StateMachineViewerWidget::stateAdded(const StateId stateId, const StateId parentId,
                                          const bool hasChildren, const QString &label,
                                          const StateType type, const bool connectToInitial)
{
    Q_UNUSED(hasChildren);
    IF_DEBUG(qDebug() << "stateAdded" << stateId << parentId << label << type);

    if (m_idToStateMap.contains(stateId))
        return;

    KDSME::State *parentState = m_idToStateMap.value(parentId);
    KDSME::State *state = nullptr;
    if (type == StateMachineState)
        state = m_machine = new KDSME::StateMachine;
    else if (type == GammaRay::FinalState)
        state = new KDSME::FinalState(parentState);
    else if (type == GammaRay::ShallowHistoryState)
        state = new KDSME::HistoryState(KDSME::HistoryState::ShallowHistory, parentState);
    else if (type == GammaRay::DeepHistoryState)
        state = new KDSME::HistoryState(KDSME::HistoryState::DeepHistory, parentState);
    else
        state = new KDSME::State(parentState);

    if (connectToInitial && parentState) {
        KDSME::State *initialState = new KDSME::PseudoState(KDSME::PseudoState::InitialState,
                                                            parentState);
        initialState->setFlags(KDSME::Element::ElementIsSelectable);
        KDSME::Transition *transition = new KDSME::Transition(initialState);
        transition->setTargetState(state);
        transition->setFlags(KDSME::Element::ElementIsSelectable);
    }

    Q_ASSERT(state);
    state->setLabel(label);
    state->setInternalId(stateId);
    state->setFlags(KDSME::Element::ElementIsSelectable);
    m_idToStateMap[stateId] = state;
}

void StateMachineViewerWidget::transitionAdded(const TransitionId transitionId,
                                               const StateId sourceId, const StateId targetId,
                                               const QString &label)
{
    if (m_idToTransitionMap.contains(transitionId))
        return;

    IF_DEBUG(qDebug() << "transitionAdded" << transitionId << label << sourceId << targetId);

    KDSME::State *source = m_idToStateMap.value(sourceId);
    KDSME::State *target = m_idToStateMap.value(targetId);
    if (!source || !target) {
        qDebug() << "Null source or target for transition:" << transitionId;
        return;
    }

    KDSME::Transition *transition = new KDSME::Transition(source);
    transition->setTargetState(target);
    transition->setLabel(label);
    transition->setFlags(KDSME::Element::ElementIsSelectable);
    m_idToTransitionMap[transitionId] = transition;
}

void StateMachineViewerWidget::statusChanged(const bool haveStateMachine, const bool running)
{
    if (m_machine)
        m_machine->runtimeController()->setIsRunning(running);

    m_ui->actionStartStopStateMachine->setEnabled(haveStateMachine);
    if (!running) {
        m_ui->actionStartStopStateMachine->setText(tr("Start State Machine"));
        m_ui->actionStartStopStateMachine->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));
    } else {
        m_ui->actionStartStopStateMachine->setText(tr("Stop State Machine"));
        m_ui->actionStartStopStateMachine->setIcon(style()->standardIcon(QStyle::SP_MediaStop));
    }
}

void StateMachineViewerWidget::transitionTriggered(TransitionId transitionId, const QString &label)
{
    Q_UNUSED(label);
    if (m_machine)
        m_machine->runtimeController()->setLastTransition(m_idToTransitionMap.value(transitionId));
}

void StateMachineViewerWidget::clearGraph()
{
    IF_DEBUG(qDebug() << Q_FUNC_INFO);

    m_stateMachineView->scene()->setRootState(nullptr);

    m_idToStateMap.clear();
    m_idToTransitionMap.clear();
}

void StateMachineViewerWidget::repopulateView()
{
    IF_DEBUG(qDebug() << Q_FUNC_INFO);

    m_stateMachineView->scene()->setRootState(m_machine);
    if (!m_machine)
        return;
    m_stateMachineView->scene()->layout();

    IF_DEBUG(m_machine->dumpObjectTree();)

    m_stateMachineView->fitInView();
}

void StateMachineViewerWidget::stateModelReset()
{
    m_ui->singleStateMachineView->expandAll();
    if (m_machine)
        m_machine->runtimeController()->clear();
}

void StateMachineViewerWidget::objectInspectorContextMenu(QPoint pos)
{
    const auto index = m_ui->singleStateMachineView->indexAt(pos);
    if (!index.isValid())
        return;

    const auto globalPos = m_ui->singleStateMachineView->viewport()->mapToGlobal(pos);
    showContextMenuForObject(index, globalPos);
}

void StateMachineViewerWidget::setShowLog(bool show)
{
    m_showLog = show;
    m_ui->logExpandingWidget->setVisible(show);
    m_ui->showLogPushButton->setVisible(!show);
    m_ui->verticalSplitter->handle(0)->setEnabled(show);
}