-
-
Notifications
You must be signed in to change notification settings - Fork 622
/
mainwindow.cpp
3546 lines (3012 loc) · 99.6 KB
/
mainwindow.cpp
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
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
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
#include <functional>
#include <stdio.h>
#include <QApplication>
#include <QActionGroup>
#include <QCheckBox>
#include <QCommandLineParser>
#include <QDebug>
#include <QDesktopServices>
#include <QDomDocument>
#include <QDoubleSpinBox>
#include <QElapsedTimer>
#include <QFileDialog>
#include <QInputDialog>
#include <QMenu>
#include <QGroupBox>
#include <QMessageBox>
#include <QMimeData>
#include <QMouseEvent>
#include <QPluginLoader>
#include <QPushButton>
#include <QKeySequence>
#include <QScrollBar>
#include <QSettings>
#include <QStringListModel>
#include <QStringRef>
#include <QThread>
#include <QTextStream>
#include <QWindow>
#include <QHeaderView>
#include <QStandardPaths>
#include <QXmlStreamReader>
#include "mainwindow.h"
#include "curvelist_panel.h"
#include "tabbedplotwidget.h"
#include "PlotJuggler/plotdata.h"
#include "transforms/function_editor.h"
#include "transforms/lua_custom_function.h"
#include "utils.h"
#include "stylesheet.h"
#include "dummy_data.h"
#include "PlotJuggler/svg_util.h"
#include "PlotJuggler/reactive_function.h"
#include "multifile_prefix.h"
#include "ui_aboutdialog.h"
#include "ui_support_dialog.h"
#include "preferences_dialog.h"
#include "nlohmann_parsers.h"
#include "cheatsheet/cheatsheet_dialog.h"
#include "colormap_editor.h"
#ifdef COMPILED_WITH_CATKIN
#endif
#ifdef COMPILED_WITH_AMENT
#include <ament_index_cpp/get_package_prefix.hpp>
#include <ament_index_cpp/get_package_share_directory.hpp>
#endif
MainWindow::MainWindow(const QCommandLineParser& commandline_parser, QWidget* parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
, _undo_shortcut(QKeySequence(Qt::CTRL + Qt::Key_Z), this)
, _redo_shortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_Z), this)
, _fullscreen_shortcut(Qt::Key_F10, this)
, _streaming_shortcut(QKeySequence(Qt::CTRL + Qt::Key_Space), this)
, _playback_shotcut(Qt::Key_Space, this)
, _minimized(false)
, _active_streamer_plugin(nullptr)
, _disable_undo_logging(false)
, _tracker_time(0)
, _tracker_param(CurveTracker::VALUE)
, _labels_status(LabelStatus::RIGHT)
, _recent_data_files(new QMenu())
, _recent_layout_files(new QMenu())
{
QLocale::setDefault(QLocale::c()); // set as default
setAcceptDrops(true);
_test_option = commandline_parser.isSet("test");
_autostart_publishers = commandline_parser.isSet("publish");
if (commandline_parser.isSet("enabled_plugins"))
{
_enabled_plugins =
commandline_parser.value("enabled_plugins").split(";", PJ::SkipEmptyParts);
// Treat the command-line parameter '--enabled_plugins *' to mean all plugings are
// enabled
if ((_enabled_plugins.size() == 1) && (_enabled_plugins.contains("*")))
{
_enabled_plugins.clear();
}
}
if (commandline_parser.isSet("disabled_plugins"))
{
_disabled_plugins =
commandline_parser.value("disabled_plugins").split(";", PJ::SkipEmptyParts);
}
_curvelist_widget = new CurveListPanel(_mapped_plot_data, _transform_functions, this);
ui->setupUi(this);
// setupUi() sets the windowTitle so the skin-based setting must be done after
_skin_path = "://resources/skin";
if (commandline_parser.isSet("skin_path"))
{
QDir path(commandline_parser.value("skin_path"));
if (path.exists())
{
_skin_path = path.absolutePath();
}
}
if (commandline_parser.isSet("window_title"))
{
setWindowTitle(commandline_parser.value("window_title"));
}
else
{
QFile fileTitle(_skin_path + "/mainwindow_title.txt");
if (fileTitle.open(QIODevice::ReadOnly))
{
QString title = fileTitle.readAll().trimmed();
setWindowTitle(title);
}
}
QSettings settings;
ui->playbackLoop->setText("");
ui->buttonZoomOut->setText("");
ui->buttonPlay->setText("");
ui->buttonUseDateTime->setText("");
ui->buttonActivateGrid->setText("");
ui->buttonRatio->setText("");
ui->buttonLink->setText("");
ui->buttonTimeTracker->setText("");
ui->buttonLoadDatafile->setText("");
ui->buttonRemoveTimeOffset->setText("");
ui->buttonLegend->setText("");
ui->widgetStatusBar->setHidden(true);
if (commandline_parser.isSet("buffer_size"))
{
int buffer_size = std::max(10, commandline_parser.value("buffer_size").toInt());
ui->streamingSpinBox->setMaximum(buffer_size);
}
_animated_streaming_movie = new QMovie(":/resources/animated_radio.gif");
_animated_streaming_movie->setScaledSize(ui->labelStreamingAnimation->size());
_animated_streaming_movie->jumpToFrame(0);
_animated_streaming_timer = new QTimer();
_animated_streaming_timer->setSingleShot(true);
connect(_animated_streaming_timer, &QTimer::timeout, this, [this]() {
_animated_streaming_movie->stop();
_animated_streaming_movie->jumpToFrame(0);
});
_tracker_delay.connectCallback([this]() {
updatedDisplayTime();
onUpdateLeftTableValues();
});
ui->labelStreamingAnimation->setMovie(_animated_streaming_movie);
ui->labelStreamingAnimation->setHidden(true);
connect(this, &MainWindow::stylesheetChanged, this, &MainWindow::on_stylesheetChanged);
connect(this, &MainWindow::stylesheetChanged, _curvelist_widget,
&CurveListPanel::on_stylesheetChanged);
connect(_curvelist_widget, &CurveListPanel::hiddenItemsChanged, this,
&MainWindow::onUpdateLeftTableValues);
connect(_curvelist_widget, &CurveListPanel::deleteCurves, this,
&MainWindow::onDeleteMultipleCurves);
connect(_curvelist_widget, &CurveListPanel::createMathPlot, this,
&MainWindow::onAddCustomPlot);
connect(_curvelist_widget, &CurveListPanel::editMathPlot, this,
&MainWindow::onEditCustomPlot);
connect(_curvelist_widget, &CurveListPanel::refreshMathPlot, this,
&MainWindow::onRefreshCustomPlot);
connect(ui->timeSlider, &RealSlider::realValueChanged, this,
&MainWindow::onTimeSlider_valueChanged);
connect(ui->playbackRate, &QDoubleSpinBox::editingFinished, this,
[this]() { ui->playbackRate->clearFocus(); });
connect(ui->playbackStep, &QDoubleSpinBox::editingFinished, this,
[this]() { ui->playbackStep->clearFocus(); });
connect(_curvelist_widget, &CurveListPanel::requestDeleteAll, this, [this](int option) {
if (option == 1)
{
deleteAllData();
}
else if (option == 2)
{
on_actionClearBuffer_triggered();
}
});
_main_tabbed_widget =
new TabbedPlotWidget("Main Window", this, _mapped_plot_data, this);
connect(this, &MainWindow::stylesheetChanged, _main_tabbed_widget,
&TabbedPlotWidget::on_stylesheetChanged);
ui->plottingLayout->insertWidget(0, _main_tabbed_widget, 1);
ui->leftLayout->addWidget(_curvelist_widget, 1);
ui->mainSplitter->setCollapsible(0, true);
ui->mainSplitter->setStretchFactor(0, 2);
ui->mainSplitter->setStretchFactor(1, 6);
ui->layoutTimescale->removeWidget(ui->widgetButtons);
_main_tabbed_widget->tabWidget()->setCornerWidget(ui->widgetButtons);
connect(ui->mainSplitter, SIGNAL(splitterMoved(int, int)),
SLOT(on_splitterMoved(int, int)));
initializeActions();
LoadColorMapFromSettings();
//------------ Load plugins -------------
auto plugin_extra_folders =
commandline_parser.value("plugin_folders").split(";", PJ::SkipEmptyParts);
_default_streamer = commandline_parser.value("start_streamer");
loadAllPlugins(plugin_extra_folders);
//------------------------------------
_undo_timer.start();
// save initial state
onUndoableChange();
_replot_timer = new QTimer(this);
connect(_replot_timer, &QTimer::timeout, this,
[this]() { updateDataAndReplot(false); });
_publish_timer = new QTimer(this);
_publish_timer->setInterval(20);
connect(_publish_timer, &QTimer::timeout, this, &MainWindow::onPlaybackLoop);
ui->menuFile->setToolTipsVisible(true);
this->setMenuBar(ui->menuBar);
ui->menuBar->setNativeMenuBar(false);
if (_test_option)
{
buildDummyData();
}
bool file_loaded = false;
if (commandline_parser.isSet("datafile"))
{
QStringList datafiles = commandline_parser.values("datafile");
file_loaded = loadDataFromFiles(datafiles);
}
if (commandline_parser.isSet("layout"))
{
loadLayoutFromFile(commandline_parser.value("layout"));
}
restoreGeometry(settings.value("MainWindow.geometry").toByteArray());
restoreState(settings.value("MainWindow.state").toByteArray());
// qDebug() << "restoreGeometry";
bool activate_grid = settings.value("MainWindow.activateGrid", false).toBool();
ui->buttonActivateGrid->setChecked(activate_grid);
bool zoom_link_active = settings.value("MainWindow.buttonLink", true).toBool();
ui->buttonLink->setChecked(zoom_link_active);
bool ration_active = settings.value("MainWindow.buttonRatio", true).toBool();
ui->buttonRatio->setChecked(ration_active);
int streaming_buffer_value =
settings.value("MainWindow.streamingBufferValue", 5).toInt();
ui->streamingSpinBox->setValue(streaming_buffer_value);
bool datetime_display = settings.value("MainWindow.dateTimeDisplay", false).toBool();
ui->buttonUseDateTime->setChecked(datetime_display);
bool remove_time_offset = settings.value("MainWindow.removeTimeOffset", true).toBool();
ui->buttonRemoveTimeOffset->setChecked(remove_time_offset);
if (settings.value("MainWindow.hiddenFileFrame", false).toBool())
{
ui->buttonHideFileFrame->setText("+");
ui->frameFile->setHidden(true);
}
if (settings.value("MainWindow.hiddenStreamingFrame", false).toBool())
{
ui->buttonHideStreamingFrame->setText("+");
ui->frameStreaming->setHidden(true);
}
if (settings.value("MainWindow.hiddenPublishersFrame", false).toBool())
{
ui->buttonHidePublishersFrame->setText("+");
ui->framePublishers->setHidden(true);
}
//----------------------------------------------------------
QIcon trackerIconA, trackerIconB, trackerIconC;
trackerIconA.addFile(QStringLiteral(":/style_light/line_tracker.png"), QSize(36, 36));
trackerIconB.addFile(QStringLiteral(":/style_light/line_tracker_1.png"), QSize(36, 36));
trackerIconC.addFile(QStringLiteral(":/style_light/line_tracker_a.png"), QSize(36, 36));
_tracker_button_icons[CurveTracker::LINE_ONLY] = trackerIconA;
_tracker_button_icons[CurveTracker::VALUE] = trackerIconB;
_tracker_button_icons[CurveTracker::VALUE_NAME] = trackerIconC;
int tracker_setting =
settings.value("MainWindow.timeTrackerSetting", (int)CurveTracker::VALUE).toInt();
_tracker_param = static_cast<CurveTracker::Parameter>(tracker_setting);
ui->buttonTimeTracker->setIcon(_tracker_button_icons[_tracker_param]);
forEachWidget([&](PlotWidget* plot) { plot->configureTracker(_tracker_param); });
auto editor_layout = new QVBoxLayout();
editor_layout->setMargin(0);
ui->formulaPage->setLayout(editor_layout);
_function_editor =
new FunctionEditorWidget(_mapped_plot_data, _transform_functions, this);
editor_layout->addWidget(_function_editor);
connect(_function_editor, &FunctionEditorWidget::closed, this,
[this]() { ui->widgetStack->setCurrentIndex(0); });
connect(this, &MainWindow::stylesheetChanged, _function_editor,
&FunctionEditorWidget::on_stylesheetChanged);
connect(_function_editor, &FunctionEditorWidget::accept, this,
&MainWindow::onCustomPlotCreated);
QString theme = settings.value("Preferences::theme", "light").toString();
if (theme != "dark")
{
theme = "light";
}
loadStyleSheet(tr(":/resources/stylesheet_%1.qss").arg(theme));
// builtin messageParsers
auto json_parser = std::make_shared<JSON_ParserFactory>();
_parser_factories.insert({ json_parser->encoding(), json_parser });
auto cbor_parser = std::make_shared<CBOR_ParserFactory>();
_parser_factories.insert({ cbor_parser->encoding(), cbor_parser });
auto bson_parser = std::make_shared<BSON_ParserFactory>();
_parser_factories.insert({ bson_parser->encoding(), bson_parser });
auto msgpack = std::make_shared<MessagePack_ParserFactory>();
_parser_factories.insert({ msgpack->encoding(), msgpack });
if (!_default_streamer.isEmpty())
{
auto index = ui->comboStreaming->findText(_default_streamer);
if (index != -1)
{
ui->comboStreaming->setCurrentIndex(index);
settings.setValue("MainWindow.previousStreamingPlugin", _default_streamer);
}
}
}
MainWindow::~MainWindow()
{
// important: avoid problems with plugins
_mapped_plot_data.user_defined.clear();
delete ui;
}
void MainWindow::onUndoableChange()
{
if (_disable_undo_logging)
return;
int elapsed_ms = _undo_timer.restart();
// overwrite the previous
if (elapsed_ms < 100)
{
if (_undo_states.empty() == false)
_undo_states.pop_back();
}
while (_undo_states.size() >= 100)
_undo_states.pop_front();
_undo_states.push_back(xmlSaveState());
_redo_states.clear();
// qDebug() << "undo " << _undo_states.size();
}
void MainWindow::onRedoInvoked()
{
_disable_undo_logging = true;
if (_redo_states.size() > 0)
{
QDomDocument state_document = _redo_states.back();
while (_undo_states.size() >= 100)
_undo_states.pop_front();
_undo_states.push_back(state_document);
_redo_states.pop_back();
xmlLoadState(state_document);
}
// qDebug() << "undo " << _undo_states.size();
_disable_undo_logging = false;
}
void MainWindow::onUndoInvoked()
{
_disable_undo_logging = true;
if (_undo_states.size() > 1)
{
QDomDocument state_document = _undo_states.back();
while (_redo_states.size() >= 100)
_redo_states.pop_front();
_redo_states.push_back(state_document);
_undo_states.pop_back();
state_document = _undo_states.back();
xmlLoadState(state_document);
}
// qDebug() << "undo " << _undo_states.size();
_disable_undo_logging = false;
}
void MainWindow::onUpdateLeftTableValues()
{
_curvelist_widget->update2ndColumnValues(_tracker_time);
}
void MainWindow::onTrackerMovedFromWidget(QPointF relative_pos)
{
_tracker_time = relative_pos.x() + _time_offset.get();
auto prev = ui->timeSlider->blockSignals(true);
ui->timeSlider->setRealValue(_tracker_time);
ui->timeSlider->blockSignals(prev);
onTrackerTimeUpdated(_tracker_time, true);
}
void MainWindow::onTimeSlider_valueChanged(double abs_time)
{
_tracker_time = abs_time;
onTrackerTimeUpdated(_tracker_time, true);
}
void MainWindow::onTrackerTimeUpdated(double absolute_time, bool do_replot)
{
_tracker_delay.triggerSignal(100);
for (auto& it : _state_publisher)
{
it.second->updateState(absolute_time);
}
updateReactivePlots();
forEachWidget([&](PlotWidget* plot) {
plot->setTrackerPosition(_tracker_time);
if (do_replot)
{
plot->replot();
}
});
}
void MainWindow::initializeActions()
{
_undo_shortcut.setContext(Qt::ApplicationShortcut);
_redo_shortcut.setContext(Qt::ApplicationShortcut);
_fullscreen_shortcut.setContext(Qt::ApplicationShortcut);
connect(&_undo_shortcut, &QShortcut::activated, this, &MainWindow::onUndoInvoked);
connect(&_redo_shortcut, &QShortcut::activated, this, &MainWindow::onRedoInvoked);
connect(&_streaming_shortcut, &QShortcut::activated, this,
&MainWindow::on_streamingToggled);
connect(&_playback_shotcut, &QShortcut::activated, ui->buttonPlay,
&QPushButton::toggle);
connect(&_fullscreen_shortcut, &QShortcut::activated, this,
&MainWindow::onActionFullscreenTriggered);
QShortcut* open_menu_shortcut = new QShortcut(QKeySequence(Qt::ALT + Qt::Key_F), this);
connect(open_menu_shortcut, &QShortcut::activated,
[this]() { ui->menuFile->exec(ui->menuBar->mapToGlobal(QPoint(0, 25))); });
QShortcut* open_help_shortcut = new QShortcut(QKeySequence(Qt::ALT + Qt::Key_H), this);
connect(open_help_shortcut, &QShortcut::activated,
[this]() { ui->menuHelp->exec(ui->menuBar->mapToGlobal(QPoint(230, 25))); });
//---------------------------------------------
QSettings settings;
updateRecentDataMenu(
settings.value("MainWindow.recentlyLoadedDatafile").toStringList());
updateRecentLayoutMenu(
settings.value("MainWindow.recentlyLoadedLayout").toStringList());
}
void MainWindow::loadAllPlugins(QStringList command_line_plugin_folders)
{
QSettings settings;
QStringList loaded;
QStringList plugin_folders;
QStringList builtin_folders;
plugin_folders += command_line_plugin_folders;
plugin_folders +=
settings.value("Preferences::plugin_folders", QStringList()).toStringList();
builtin_folders += QCoreApplication::applicationDirPath();
try
{
#ifdef COMPILED_WITH_CATKIN
builtin_folders += QCoreApplication::applicationDirPath() + "_ros";
const char* env = std::getenv("CMAKE_PREFIX_PATH");
if (env)
{
QString env_catkin_paths = QString::fromStdString(env);
env_catkin_paths.replace(";", ":"); // for windows
auto catkin_paths = env_catkin_paths.split(":");
for (const auto& path : catkin_paths)
{
builtin_folders += path + "/lib/plotjuggler_ros";
}
}
#endif
#ifdef COMPILED_WITH_AMENT
auto ros2_path = QString::fromStdString(ament_index_cpp::get_package_prefix("plotjugg"
"ler_"
"ros"));
ros2_path += "/lib/plotjuggler_ros";
loaded += initializePlugins(ros2_path);
#endif
}
catch (...)
{
QMessageBox::warning(nullptr, "Missing package [plotjuggler-ros]",
"If you just upgraded from PlotJuggler 2.x to 3.x , try "
"installing this package:\n\n"
"sudo apt install ros-${ROS_DISTRO}-plotjuggler-ros",
QMessageBox::Cancel, QMessageBox::Cancel);
}
builtin_folders +=
QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/PlotJuggl"
"er";
builtin_folders.removeDuplicates();
plugin_folders += builtin_folders;
plugin_folders.removeDuplicates();
for (const auto& folder : plugin_folders)
{
loaded += initializePlugins(folder);
}
settings.setValue("Preferences::builtin_plugin_folders", builtin_folders);
}
QStringList MainWindow::initializePlugins(QString directory_name)
{
static std::set<QString> loaded_plugins;
QStringList loaded_out;
qDebug() << "Loading compatible plugins from directory: " << directory_name;
int loaded_count = 0;
QDir pluginsDir(directory_name);
for (const QString& filename : pluginsDir.entryList(QDir::Files))
{
QFileInfo fileinfo(filename);
if (fileinfo.suffix() != "so" && fileinfo.suffix() != "dll" &&
fileinfo.suffix() != "dylib")
{
continue;
}
if (loaded_plugins.find(filename) != loaded_plugins.end())
{
continue;
}
QPluginLoader pluginLoader(pluginsDir.absoluteFilePath(filename), this);
QObject* plugin;
try
{
plugin = pluginLoader.instance();
}
catch (std::runtime_error& err)
{
qDebug() << QString("%1: skipping, because it threw the following exception: %2")
.arg(filename)
.arg(err.what());
continue;
}
if (plugin && dynamic_cast<PlotJugglerPlugin*>(plugin))
{
auto class_name = pluginLoader.metaData().value("className").toString();
loaded_out.push_back(class_name);
DataLoader* loader = qobject_cast<DataLoader*>(plugin);
StatePublisher* publisher = qobject_cast<StatePublisher*>(plugin);
DataStreamer* streamer = qobject_cast<DataStreamer*>(plugin);
ParserFactoryPlugin* message_parser = qobject_cast<ParserFactoryPlugin*>(plugin);
ToolboxPlugin* toolbox = qobject_cast<ToolboxPlugin*>(plugin);
QString plugin_name;
QString plugin_type;
bool is_debug_plugin = dynamic_cast<PlotJugglerPlugin*>(plugin)->isDebugPlugin();
if (loader)
{
plugin_name = loader->name();
plugin_type = "DataLoader";
}
else if (publisher)
{
plugin_name = publisher->name();
plugin_type = "StatePublisher";
}
else if (streamer)
{
plugin_name = streamer->name();
plugin_type = "DataStreamer";
}
else if (message_parser)
{
plugin_name = message_parser->name();
plugin_type = "MessageParser";
}
else if (toolbox)
{
plugin_name = toolbox->name();
plugin_type = "Toolbox";
}
QString message = QString("%1 is a %2 plugin").arg(filename).arg(plugin_type);
if ((_enabled_plugins.size() > 0) &&
(_enabled_plugins.contains(fileinfo.baseName()) == false))
{
qDebug() << message << " ...skipping, because it is not explicitly enabled";
continue;
}
if ((_disabled_plugins.size() > 0) &&
(_disabled_plugins.contains(fileinfo.baseName()) == true))
{
qDebug() << message << " ...skipping, because it is explicitly disabled";
continue;
}
if (!_test_option && is_debug_plugin)
{
qDebug() << message << " ...disabled, unless option -t is used";
continue;
}
if (loaded_plugins.find(plugin_name) != loaded_plugins.end())
{
qDebug() << message << " ...skipping, because already loaded";
continue;
}
qDebug() << message;
loaded_plugins.insert(plugin_name);
loaded_count++;
if (loader)
{
_data_loader.insert(std::make_pair(plugin_name, loader));
}
else if (publisher)
{
publisher->setDataMap(&_mapped_plot_data);
_state_publisher.insert(std::make_pair(plugin_name, publisher));
ui->layoutPublishers->setColumnStretch(0, 1.0);
int row = _state_publisher.size() - 1;
auto label = new QLabel(plugin_name, ui->framePublishers);
ui->layoutPublishers->addWidget(label, row, 0);
auto start_checkbox = new QCheckBox(ui->framePublishers);
ui->layoutPublishers->addWidget(start_checkbox, row, 1);
start_checkbox->setFocusPolicy(Qt::FocusPolicy::NoFocus);
connect(start_checkbox, &QCheckBox::toggled, this,
[=](bool enable) { publisher->setEnabled(enable); });
connect(publisher, &StatePublisher::closed, start_checkbox,
[=]() { start_checkbox->setChecked(false); });
if (publisher->availableActions().empty())
{
QFrame* empty = new QFrame(ui->framePublishers);
empty->setFixedSize({ 22, 22 });
ui->layoutPublishers->addWidget(empty, row, 2);
}
else
{
auto options_button = new QPushButton(ui->framePublishers);
options_button->setFlat(true);
options_button->setFixedSize({ 24, 24 });
ui->layoutPublishers->addWidget(options_button, row, 2);
options_button->setIcon(LoadSvg(":/resources/svg/settings_cog.svg", "light"));
options_button->setIconSize({ 16, 16 });
auto optionsMenu = [=]() {
PopupMenu* menu = new PopupMenu(options_button, this);
for (auto action : publisher->availableActions())
{
menu->addAction(action);
}
menu->exec();
};
connect(options_button, &QPushButton::clicked, options_button, optionsMenu);
connect(this, &MainWindow::stylesheetChanged, options_button,
[=](QString style) {
options_button->setIcon(
LoadSvg(":/resources/svg/settings_cog.svg", style));
});
}
}
else if (message_parser)
{
QStringList encodings = QString(message_parser->encoding()).split(";");
auto parser_ptr = std::shared_ptr<ParserFactoryPlugin>(message_parser);
for (const QString& encoding : encodings)
{
_parser_factories[encoding] = parser_ptr;
}
}
else if (streamer)
{
if (_default_streamer == fileinfo.baseName())
{
_default_streamer = plugin_name;
}
_data_streamer.insert(std::make_pair(plugin_name, streamer));
connect(streamer, &DataStreamer::closed, this,
[this]() { this->stopStreamingPlugin(); });
connect(streamer, &DataStreamer::clearBuffers, this,
&MainWindow::on_actionClearBuffer_triggered);
connect(streamer, &DataStreamer::dataReceived, _animated_streaming_movie,
[this]() {
_animated_streaming_movie->start();
_animated_streaming_timer->start(500);
});
connect(streamer, &DataStreamer::removeGroup, this,
&MainWindow::on_deleteSerieFromGroup);
connect(streamer, &DataStreamer::dataReceived, this, [this]() {
if (isStreamingActive() && !_replot_timer->isActive())
{
_replot_timer->setSingleShot(true);
_replot_timer->start(40);
}
});
connect(streamer, &DataStreamer::notificationsChanged, this,
&MainWindow::on_streamingNotificationsChanged);
}
else if (toolbox)
{
toolbox->init(_mapped_plot_data, _transform_functions);
_toolboxes.insert(std::make_pair(plugin_name, toolbox));
auto action = ui->menuTools->addAction(toolbox->name());
int new_index = ui->widgetStack->count();
auto provided = toolbox->providedWidget();
auto widget = provided.first;
ui->widgetStack->addWidget(widget);
connect(action, &QAction::triggered, toolbox, &ToolboxPlugin::onShowWidget);
connect(action, &QAction::triggered, this,
[=]() { ui->widgetStack->setCurrentIndex(new_index); });
connect(toolbox, &ToolboxPlugin::closed, this,
[=]() { ui->widgetStack->setCurrentIndex(0); });
connect(toolbox, &ToolboxPlugin::importData, this,
[this](PlotDataMapRef& new_data, bool remove_old) {
importPlotDataMap(new_data, remove_old);
updateDataAndReplot(true);
});
connect(toolbox, &ToolboxPlugin::plotCreated, this,
[=](std::string name, bool is_custom) {
if (is_custom)
{
_curvelist_widget->addCustom(QString::fromStdString(name));
}
else
{
_curvelist_widget->addCurve(name);
}
_curvelist_widget->updateAppearance();
_curvelist_widget->clearSelections();
});
}
}
else
{
if (pluginLoader.errorString().contains("is not an ELF object") == false)
{
qDebug() << filename << ": " << pluginLoader.errorString();
}
}
}
for (auto& [name, streamer] : _data_streamer)
{
streamer->setParserFactories(&_parser_factories);
}
for (auto& [name, toolbox] : _toolboxes)
{
toolbox->setParserFactories(&_parser_factories);
}
for (auto& [name, loader] : _data_loader)
{
loader->setParserFactories(&_parser_factories);
}
if (!_data_streamer.empty())
{
QSignalBlocker block(ui->comboStreaming);
ui->comboStreaming->setEnabled(true);
ui->buttonStreamingStart->setEnabled(true);
for (const auto& it : _data_streamer)
{
if (ui->comboStreaming->findText(it.first) == -1)
{
ui->comboStreaming->addItem(it.first);
}
}
// remember the previous one
QSettings settings;
QString streaming_name =
settings
.value("MainWindow.previousStreamingPlugin", ui->comboStreaming->itemText(0))
.toString();
auto streamer_it = _data_streamer.find(streaming_name);
if (streamer_it == _data_streamer.end())
{
streamer_it = _data_streamer.begin();
streaming_name = streamer_it->first;
}
ui->comboStreaming->setCurrentText(streaming_name);
bool contains_options = !streamer_it->second->availableActions().empty();
ui->buttonStreamingOptions->setEnabled(contains_options);
}
qDebug() << "Number of plugins loaded: " << loaded_count << "\n";
return loaded_out;
}
void MainWindow::buildDummyData()
{
PlotDataMapRef datamap;
BuildDummyData(datamap);
importPlotDataMap(datamap, true);
}
void MainWindow::on_splitterMoved(int, int)
{
QList<int> sizes = ui->mainSplitter->sizes();
int max_left_size = _curvelist_widget->maximumWidth();
int totalWidth = sizes[0] + sizes[1];
// this is needed only once to restore the old size
static bool first = true;
if (sizes[0] != 0 && first)
{
first = false;
QSettings settings;
int splitter_width = settings.value("MainWindow.splitterWidth", 200).toInt();
auto sizes = ui->mainSplitter->sizes();
int tot_splitter_width = sizes[0] + sizes[1];
sizes[0] = splitter_width;
sizes[1] = tot_splitter_width - splitter_width;
ui->mainSplitter->setSizes(sizes);
return;
}
if (sizes[0] > max_left_size)
{
sizes[0] = max_left_size;
sizes[1] = totalWidth - max_left_size;
ui->mainSplitter->setSizes(sizes);
}
}
void MainWindow::resizeEvent(QResizeEvent*)
{
on_splitterMoved(0, 0);
}
void MainWindow::onPlotAdded(PlotWidget* plot)
{
connect(plot, &PlotWidget::undoableChange, this, &MainWindow::onUndoableChange);
connect(plot, &PlotWidget::trackerMoved, this, &MainWindow::onTrackerMovedFromWidget);
connect(this, &MainWindow::dataSourceRemoved, plot, &PlotWidget::onDataSourceRemoved);
connect(plot, &PlotWidget::curveListChanged, this, [this]() {
updateTimeOffset();
updateTimeSlider();
});
connect(&_time_offset, SIGNAL(valueChanged(double)), plot,
SLOT(on_changeTimeOffset(double)));
connect(ui->buttonUseDateTime, &QPushButton::toggled, plot,
&PlotWidget::on_changeDateTimeScale);
connect(plot, &PlotWidget::curvesDropped, _curvelist_widget,
&CurveListPanel::clearSelections);
connect(plot, &PlotWidget::legendSizeChanged, this, [=](int point_size) {
auto visitor = [=](PlotWidget* p) {
if (plot != p)
p->setLegendSize(point_size);
};
this->forEachWidget(visitor);
});
connect(plot, &PlotWidget::rectChanged, this, &MainWindow::onPlotZoomChanged);
plot->on_changeTimeOffset(_time_offset.get());
plot->on_changeDateTimeScale(ui->buttonUseDateTime->isChecked());
plot->activateGrid(ui->buttonActivateGrid->isChecked());
plot->enableTracker(!isStreamingActive());
plot->setKeepRatioXY(ui->buttonRatio->isChecked());
plot->configureTracker(_tracker_param);
}
void MainWindow::onPlotZoomChanged(PlotWidget* modified_plot, QRectF new_range)
{
if (ui->buttonLink->isChecked())
{
auto visitor = [=](PlotWidget* plot) {
if (plot != modified_plot && !plot->isEmpty() && !plot->isXYPlot() &&
plot->isZoomLinkEnabled())
{
QRectF bound_act = plot->currentBoundingRect();
bound_act.setLeft(new_range.left());
bound_act.setRight(new_range.right());
plot->setZoomRectangle(bound_act, false);
plot->on_zoomOutVertical_triggered(false);