CMakeLists.txt: Only add Qt5PlatformSupport for Qt < 5.8.0.
[pulseview.git] / pv / mainwindow.cpp
1 /*
2  * This file is part of the PulseView project.
3  *
4  * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #ifdef ENABLE_DECODE
21 #include <libsigrokdecode/libsigrokdecode.h>
22 #endif
23
24 #include <algorithm>
25 #include <cassert>
26 #include <cstdarg>
27 #include <cstdint>
28 #include <iterator>
29
30 #include <QAction>
31 #include <QApplication>
32 #include <QCloseEvent>
33 #include <QDockWidget>
34 #include <QHBoxLayout>
35 #include <QMessageBox>
36 #include <QSettings>
37 #include <QShortcut>
38 #include <QWidget>
39
40 #include "mainwindow.hpp"
41
42 #include "devicemanager.hpp"
43 #include "devices/hardwaredevice.hpp"
44 #include "dialogs/settings.hpp"
45 #include "globalsettings.hpp"
46 #include "toolbars/mainbar.hpp"
47 #include "util.hpp"
48 #include "views/trace/view.hpp"
49 #include "views/trace/standardbar.hpp"
50
51 #include <libsigrokcxx/libsigrokcxx.hpp>
52
53 using std::dynamic_pointer_cast;
54 using std::make_shared;
55 using std::shared_ptr;
56 using std::string;
57
58 namespace pv {
59
60 namespace view {
61 class ViewItem;
62 }
63
64 using toolbars::MainBar;
65
66 const QString MainWindow::WindowTitle = tr("PulseView");
67
68 MainWindow::MainWindow(DeviceManager &device_manager, QWidget *parent) :
69         QMainWindow(parent),
70         device_manager_(device_manager),
71         session_selector_(this),
72         session_state_mapper_(this),
73         icon_red_(":/icons/status-red.svg"),
74         icon_green_(":/icons/status-green.svg"),
75         icon_grey_(":/icons/status-grey.svg")
76 {
77         qRegisterMetaType<util::Timestamp>("util::Timestamp");
78         qRegisterMetaType<uint64_t>("uint64_t");
79
80         GlobalSettings::add_change_handler(this);
81
82         GlobalSettings settings;
83         settings.set_defaults_where_needed();
84
85         setup_ui();
86         restore_ui_settings();
87 }
88
89 MainWindow::~MainWindow()
90 {
91         GlobalSettings::remove_change_handler(this);
92
93         while (!sessions_.empty())
94                 remove_session(sessions_.front());
95 }
96
97 shared_ptr<views::ViewBase> MainWindow::get_active_view() const
98 {
99         // If there's only one view, use it...
100         if (view_docks_.size() == 1)
101                 return view_docks_.begin()->second;
102
103         // ...otherwise find the dock widget the widget with focus is contained in
104         QObject *w = QApplication::focusWidget();
105         QDockWidget *dock = nullptr;
106
107         while (w) {
108                 dock = qobject_cast<QDockWidget*>(w);
109                 if (dock)
110                         break;
111                 w = w->parent();
112         }
113
114         // Get the view contained in the dock widget
115         for (auto entry : view_docks_)
116                 if (entry.first == dock)
117                         return entry.second;
118
119         return nullptr;
120 }
121
122 shared_ptr<views::ViewBase> MainWindow::add_view(const QString &title,
123         views::ViewType type, Session &session)
124 {
125         GlobalSettings settings;
126         shared_ptr<views::ViewBase> v;
127
128         QMainWindow *main_window = nullptr;
129         for (auto entry : session_windows_)
130                 if (entry.first.get() == &session)
131                         main_window = entry.second;
132
133         assert(main_window);
134
135         shared_ptr<MainBar> main_bar = session.main_bar();
136
137         QDockWidget* dock = new QDockWidget(title, main_window);
138         dock->setObjectName(title);
139         main_window->addDockWidget(Qt::TopDockWidgetArea, dock);
140
141         // Insert a QMainWindow into the dock widget to allow for a tool bar
142         QMainWindow *dock_main = new QMainWindow(dock);
143         dock_main->setWindowFlags(Qt::Widget);  // Remove Qt::Window flag
144
145         if (type == views::ViewTypeTrace)
146                 // This view will be the main view if there's no main bar yet
147                 v = make_shared<views::trace::View>(session,
148                         (main_bar ? false : true), dock_main);
149
150         if (!v)
151                 return nullptr;
152
153         view_docks_[dock] = v;
154         session.register_view(v);
155
156         dock_main->setCentralWidget(v.get());
157         dock->setWidget(dock_main);
158
159         dock->setContextMenuPolicy(Qt::PreventContextMenu);
160         dock->setFeatures(QDockWidget::DockWidgetMovable |
161                 QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetClosable);
162
163         QAbstractButton *close_btn =
164                 dock->findChildren<QAbstractButton*>
165                         ("qt_dockwidget_closebutton").front();
166
167         connect(close_btn, SIGNAL(clicked(bool)),
168                 this, SLOT(on_view_close_clicked()));
169
170         connect(&session, SIGNAL(trigger_event(int, util::Timestamp)),
171                 qobject_cast<views::ViewBase*>(v.get()),
172                 SLOT(trigger_event(int, util::Timestamp)));
173
174         if (type == views::ViewTypeTrace) {
175                 views::trace::View *tv =
176                         qobject_cast<views::trace::View*>(v.get());
177
178                 tv->enable_coloured_bg(settings.value(GlobalSettings::Key_View_ColouredBG).toBool());
179                 tv->enable_show_sampling_points(settings.value(GlobalSettings::Key_View_ShowSamplingPoints).toBool());
180                 tv->enable_show_analog_minor_grid(settings.value(GlobalSettings::Key_View_ShowAnalogMinorGrid).toBool());
181
182                 if (!main_bar) {
183                         /* Initial view, create the main bar */
184                         main_bar = make_shared<MainBar>(session, this, tv);
185                         dock_main->addToolBar(main_bar.get());
186                         session.set_main_bar(main_bar);
187
188                         connect(main_bar.get(), SIGNAL(new_view(Session*)),
189                                 this, SLOT(on_new_view(Session*)));
190
191                         main_bar->action_view_show_cursors()->setChecked(tv->cursors_shown());
192
193                         /* For the main view we need to prevent the dock widget from
194                          * closing itself when its close button is clicked. This is
195                          * so we can confirm with the user first. Regular views don't
196                          * need this */
197                         close_btn->disconnect(SIGNAL(clicked()), dock, SLOT(close()));
198                 } else {
199                         /* Additional view, create a standard bar */
200                         pv::views::trace::StandardBar *standard_bar =
201                                 new pv::views::trace::StandardBar(session, this, tv);
202                         dock_main->addToolBar(standard_bar);
203
204                         standard_bar->action_view_show_cursors()->setChecked(tv->cursors_shown());
205                 }
206         }
207
208         return v;
209 }
210
211 void MainWindow::remove_view(shared_ptr<views::ViewBase> view)
212 {
213         for (shared_ptr<Session> session : sessions_) {
214                 if (!session->has_view(view))
215                         continue;
216
217                 // Find the dock the view is contained in and remove it
218                 for (auto entry : view_docks_)
219                         if (entry.second == view) {
220                                 // Remove the view from the session
221                                 session->deregister_view(view);
222
223                                 // Remove the view from its parent; otherwise, Qt will
224                                 // call deleteLater() on it, which causes a double free
225                                 // since the shared_ptr in view_docks_ doesn't know
226                                 // that Qt keeps a pointer to the view around
227                                 view->setParent(nullptr);
228
229                                 // Delete the view's dock widget and all widgets inside it
230                                 entry.first->deleteLater();
231
232                                 // Remove the dock widget from the list and stop iterating
233                                 view_docks_.erase(entry.first);
234                                 break;
235                         }
236         }
237 }
238
239 shared_ptr<Session> MainWindow::add_session()
240 {
241         static int last_session_id = 1;
242         QString name = tr("Session %1").arg(last_session_id++);
243
244         shared_ptr<Session> session = make_shared<Session>(device_manager_, name);
245
246         connect(session.get(), SIGNAL(add_view(const QString&, views::ViewType, Session*)),
247                 this, SLOT(on_add_view(const QString&, views::ViewType, Session*)));
248         connect(session.get(), SIGNAL(name_changed()),
249                 this, SLOT(on_session_name_changed()));
250         session_state_mapper_.setMapping(session.get(), session.get());
251         connect(session.get(), SIGNAL(capture_state_changed(int)),
252                 &session_state_mapper_, SLOT(map()));
253
254         sessions_.push_back(session);
255
256         QMainWindow *window = new QMainWindow();
257         window->setWindowFlags(Qt::Widget);  // Remove Qt::Window flag
258         session_windows_[session] = window;
259
260         int index = session_selector_.addTab(window, name);
261         session_selector_.setCurrentIndex(index);
262         last_focused_session_ = session;
263
264         window->setDockNestingEnabled(true);
265
266         shared_ptr<views::ViewBase> main_view =
267                 add_view(name, views::ViewTypeTrace, *session);
268
269         return session;
270 }
271
272 void MainWindow::remove_session(shared_ptr<Session> session)
273 {
274         // Determine the height of the button before it collapses
275         int h = new_session_button_->height();
276
277         // Stop capture while the session still exists so that the UI can be
278         // updated in case we're currently running. If so, this will schedule a
279         // call to our on_capture_state_changed() slot for the next run of the
280         // event loop. We need to have this executed immediately or else it will
281         // be dismissed since the session object will be deleted by the time we
282         // leave this method and the event loop gets a chance to run again.
283         session->stop_capture();
284         QApplication::processEvents();
285
286         for (shared_ptr<views::ViewBase> view : session->views())
287                 remove_view(view);
288
289         QMainWindow *window = session_windows_.at(session);
290         session_selector_.removeTab(session_selector_.indexOf(window));
291
292         session_windows_.erase(session);
293
294         if (last_focused_session_ == session)
295                 last_focused_session_.reset();
296
297         // Remove the session from our list of sessions (which also destroys it)
298         sessions_.remove_if([&](shared_ptr<Session> s) {
299                 return s == session; });
300
301         if (sessions_.empty()) {
302                 // When there are no more tabs, the height of the QTabWidget
303                 // drops to zero. We must prevent this to keep the static
304                 // widgets visible
305                 for (QWidget *w : static_tab_widget_->findChildren<QWidget*>())
306                         w->setMinimumHeight(h);
307
308                 int margin = static_tab_widget_->layout()->contentsMargins().bottom();
309                 static_tab_widget_->setMinimumHeight(h + 2 * margin);
310                 session_selector_.setMinimumHeight(h + 2 * margin);
311
312                 // Update the window title if there is no view left to
313                 // generate focus change events
314                 setWindowTitle(WindowTitle);
315         }
316 }
317
318 void MainWindow::add_session_with_file(string open_file_name,
319         string open_file_format)
320 {
321         shared_ptr<Session> session = add_session();
322         session->load_init_file(open_file_name, open_file_format);
323 }
324
325 void MainWindow::add_default_session()
326 {
327         // Only add the default session if there would be no session otherwise
328         if (sessions_.size() > 0)
329                 return;
330
331         shared_ptr<Session> session = add_session();
332
333         // Check the list of available devices. Prefer the one that was
334         // found with user supplied scan specs (if applicable). Then try
335         // one of the auto detected devices that are not the demo device.
336         // Pick demo in the absence of "genuine" hardware devices.
337         shared_ptr<devices::HardwareDevice> user_device, other_device, demo_device;
338         for (shared_ptr<devices::HardwareDevice> dev : device_manager_.devices()) {
339                 if (dev == device_manager_.user_spec_device()) {
340                         user_device = dev;
341                 } else if (dev->hardware_device()->driver()->name() == "demo") {
342                         demo_device = dev;
343                 } else {
344                         other_device = dev;
345                 }
346         }
347         if (user_device)
348                 session->select_device(user_device);
349         else if (other_device)
350                 session->select_device(other_device);
351         else
352                 session->select_device(demo_device);
353 }
354
355 void MainWindow::save_sessions()
356 {
357         QSettings settings;
358         int id = 0;
359
360         for (shared_ptr<Session> session : sessions_) {
361                 // Ignore sessions using the demo device or no device at all
362                 if (session->device()) {
363                         shared_ptr<devices::HardwareDevice> device =
364                                 dynamic_pointer_cast< devices::HardwareDevice >
365                                 (session->device());
366
367                         if (device &&
368                                 device->hardware_device()->driver()->name() == "demo")
369                                 continue;
370
371                         settings.beginGroup("Session" + QString::number(id++));
372                         settings.remove("");  // Remove all keys in this group
373                         session->save_settings(settings);
374                         settings.endGroup();
375                 }
376         }
377
378         settings.setValue("sessions", id);
379 }
380
381 void MainWindow::restore_sessions()
382 {
383         QSettings settings;
384         int i, session_count;
385
386         session_count = settings.value("sessions", 0).toInt();
387
388         for (i = 0; i < session_count; i++) {
389                 settings.beginGroup("Session" + QString::number(i));
390                 shared_ptr<Session> session = add_session();
391                 session->restore_settings(settings);
392                 settings.endGroup();
393         }
394 }
395
396 void MainWindow::on_setting_changed(const QString &key, const QVariant &value)
397 {
398         if (key == GlobalSettings::Key_View_ColouredBG)
399                 on_settingViewColouredBg_changed(value);
400
401         if (key == GlobalSettings::Key_View_ShowSamplingPoints)
402                 on_settingViewShowSamplingPoints_changed(value);
403
404         if (key == GlobalSettings::Key_View_ShowAnalogMinorGrid)
405                 on_settingViewShowAnalogMinorGrid_changed(value);
406 }
407
408 void MainWindow::setup_ui()
409 {
410         setObjectName(QString::fromUtf8("MainWindow"));
411
412         setCentralWidget(&session_selector_);
413
414         // Set the window icon
415         QIcon icon;
416         icon.addFile(QString(":/icons/pulseview.png"));
417         setWindowIcon(icon);
418
419         view_sticky_scrolling_shortcut_ = new QShortcut(QKeySequence(Qt::Key_S), this, SLOT(on_view_sticky_scrolling_shortcut()));
420         view_sticky_scrolling_shortcut_->setAutoRepeat(false);
421
422         view_show_sampling_points_shortcut_ = new QShortcut(QKeySequence(Qt::Key_Period), this, SLOT(on_view_show_sampling_points_shortcut()));
423         view_show_sampling_points_shortcut_->setAutoRepeat(false);
424
425         view_show_analog_minor_grid_shortcut_ = new QShortcut(QKeySequence(Qt::Key_G), this, SLOT(on_view_show_analog_minor_grid_shortcut()));
426         view_show_analog_minor_grid_shortcut_->setAutoRepeat(false);
427
428         view_coloured_bg_shortcut_ = new QShortcut(QKeySequence(Qt::Key_B), this, SLOT(on_view_coloured_bg_shortcut()));
429         view_coloured_bg_shortcut_->setAutoRepeat(false);
430
431         // Set up the tab area
432         new_session_button_ = new QToolButton();
433         new_session_button_->setIcon(QIcon::fromTheme("document-new",
434                 QIcon(":/icons/document-new.png")));
435         new_session_button_->setToolTip(tr("Create New Session"));
436         new_session_button_->setAutoRaise(true);
437
438         run_stop_button_ = new QToolButton();
439         run_stop_button_->setAutoRaise(true);
440         run_stop_button_->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
441         run_stop_button_->setToolTip(tr("Start/Stop Acquisition"));
442
443         run_stop_shortcut_ = new QShortcut(QKeySequence(Qt::Key_Space), run_stop_button_, SLOT(click()));
444         run_stop_shortcut_->setAutoRepeat(false);
445
446         settings_button_ = new QToolButton();
447         settings_button_->setIcon(QIcon::fromTheme("preferences-system",
448                 QIcon(":/icons/preferences-system.png")));
449         settings_button_->setToolTip(tr("Settings"));
450         settings_button_->setAutoRaise(true);
451
452         QFrame *separator1 = new QFrame();
453         separator1->setFrameStyle(QFrame::VLine | QFrame::Raised);
454         QFrame *separator2 = new QFrame();
455         separator2->setFrameStyle(QFrame::VLine | QFrame::Raised);
456
457         QHBoxLayout* layout = new QHBoxLayout();
458         layout->setContentsMargins(2, 2, 2, 2);
459         layout->addWidget(new_session_button_);
460         layout->addWidget(separator1);
461         layout->addWidget(run_stop_button_);
462         layout->addWidget(separator2);
463         layout->addWidget(settings_button_);
464
465         static_tab_widget_ = new QWidget();
466         static_tab_widget_->setLayout(layout);
467
468         session_selector_.setCornerWidget(static_tab_widget_, Qt::TopLeftCorner);
469         session_selector_.setTabsClosable(true);
470
471         close_application_shortcut_ = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q), this, SLOT(close()));
472         close_application_shortcut_->setAutoRepeat(false);
473
474         close_current_tab_shortcut_ = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_W), this, SLOT(on_close_current_tab()));
475
476         connect(new_session_button_, SIGNAL(clicked(bool)),
477                 this, SLOT(on_new_session_clicked()));
478         connect(run_stop_button_, SIGNAL(clicked(bool)),
479                 this, SLOT(on_run_stop_clicked()));
480         connect(&session_state_mapper_, SIGNAL(mapped(QObject*)),
481                 this, SLOT(on_capture_state_changed(QObject*)));
482         connect(settings_button_, SIGNAL(clicked(bool)),
483                 this, SLOT(on_settings_clicked()));
484
485         connect(&session_selector_, SIGNAL(tabCloseRequested(int)),
486                 this, SLOT(on_tab_close_requested(int)));
487         connect(&session_selector_, SIGNAL(currentChanged(int)),
488                 this, SLOT(on_tab_changed(int)));
489
490
491         connect(static_cast<QApplication *>(QCoreApplication::instance()),
492                 SIGNAL(focusChanged(QWidget*, QWidget*)),
493                 this, SLOT(on_focus_changed()));
494 }
495
496 void MainWindow::save_ui_settings()
497 {
498         QSettings settings;
499
500         settings.beginGroup("MainWindow");
501         settings.setValue("state", saveState());
502         settings.setValue("geometry", saveGeometry());
503         settings.endGroup();
504 }
505
506 void MainWindow::restore_ui_settings()
507 {
508         QSettings settings;
509
510         settings.beginGroup("MainWindow");
511
512         if (settings.contains("geometry")) {
513                 restoreGeometry(settings.value("geometry").toByteArray());
514                 restoreState(settings.value("state").toByteArray());
515         } else
516                 resize(1000, 720);
517
518         settings.endGroup();
519 }
520
521 shared_ptr<Session> MainWindow::get_tab_session(int index) const
522 {
523         // Find the session that belongs to the tab's main window
524         for (auto entry : session_windows_)
525                 if (entry.second == session_selector_.widget(index))
526                         return entry.first;
527
528         return nullptr;
529 }
530
531 void MainWindow::closeEvent(QCloseEvent *event)
532 {
533         bool data_saved = true;
534
535         for (auto entry : session_windows_)
536                 if (!entry.first->data_saved())
537                         data_saved = false;
538
539         if (!data_saved && (QMessageBox::question(this, tr("Confirmation"),
540                 tr("There is unsaved data. Close anyway?"),
541                 QMessageBox::Yes | QMessageBox::No) == QMessageBox::No)) {
542                 event->ignore();
543         } else {
544                 save_ui_settings();
545                 save_sessions();
546                 event->accept();
547         }
548 }
549
550 QMenu* MainWindow::createPopupMenu()
551 {
552         return nullptr;
553 }
554
555 bool MainWindow::restoreState(const QByteArray &state, int version)
556 {
557         (void)state;
558         (void)version;
559
560         // Do nothing. We don't want Qt to handle this, or else it
561         // will try to restore all the dock widgets and create havoc.
562
563         return false;
564 }
565
566 void MainWindow::session_error(const QString text, const QString info_text)
567 {
568         QMetaObject::invokeMethod(this, "show_session_error",
569                 Qt::QueuedConnection, Q_ARG(QString, text),
570                 Q_ARG(QString, info_text));
571 }
572
573 void MainWindow::show_session_error(const QString text, const QString info_text)
574 {
575         QMessageBox msg(this);
576         msg.setText(text);
577         msg.setInformativeText(info_text);
578         msg.setStandardButtons(QMessageBox::Ok);
579         msg.setIcon(QMessageBox::Warning);
580         msg.exec();
581 }
582
583 void MainWindow::on_add_view(const QString &title, views::ViewType type,
584         Session *session)
585 {
586         // We get a pointer and need a reference
587         for (shared_ptr<Session> s : sessions_)
588                 if (s.get() == session)
589                         add_view(title, type, *s);
590 }
591
592 void MainWindow::on_focus_changed()
593 {
594         shared_ptr<views::ViewBase> view = get_active_view();
595
596         if (view) {
597                 for (shared_ptr<Session> session : sessions_) {
598                         if (session->has_view(view)) {
599                                 if (session != last_focused_session_) {
600                                         // Activate correct tab if necessary
601                                         shared_ptr<Session> tab_session = get_tab_session(
602                                                 session_selector_.currentIndex());
603                                         if (tab_session != session)
604                                                 session_selector_.setCurrentWidget(
605                                                         session_windows_.at(session));
606
607                                         on_focused_session_changed(session);
608                                 }
609
610                                 break;
611                         }
612                 }
613         }
614
615         if (sessions_.empty())
616                 setWindowTitle(WindowTitle);
617 }
618
619 void MainWindow::on_focused_session_changed(shared_ptr<Session> session)
620 {
621         last_focused_session_ = session;
622
623         setWindowTitle(session->name() + " - " + WindowTitle);
624
625         // Update the state of the run/stop button, too
626         on_capture_state_changed(session.get());
627 }
628
629 void MainWindow::on_new_session_clicked()
630 {
631         add_session();
632 }
633
634 void MainWindow::on_run_stop_clicked()
635 {
636         shared_ptr<Session> session = last_focused_session_;
637
638         if (!session)
639                 return;
640
641         switch (session->get_capture_state()) {
642         case Session::Stopped:
643                 session->start_capture([&](QString message) {
644                         session_error("Capture failed", message); });
645                 break;
646         case Session::AwaitingTrigger:
647         case Session::Running:
648                 session->stop_capture();
649                 break;
650         }
651 }
652
653 void MainWindow::on_settings_clicked()
654 {
655         dialogs::Settings dlg(device_manager_);
656         dlg.exec();
657 }
658
659 void MainWindow::on_session_name_changed()
660 {
661         // Update the corresponding dock widget's name(s)
662         Session *session = qobject_cast<Session*>(QObject::sender());
663         assert(session);
664
665         for (shared_ptr<views::ViewBase> view : session->views()) {
666                 // Get the dock that contains the view
667                 for (auto entry : view_docks_)
668                         if (entry.second == view) {
669                                 entry.first->setObjectName(session->name());
670                                 entry.first->setWindowTitle(session->name());
671                         }
672         }
673
674         // Update the tab widget by finding the main window and the tab from that
675         for (auto entry : session_windows_)
676                 if (entry.first.get() == session) {
677                         QMainWindow *window = entry.second;
678                         const int index = session_selector_.indexOf(window);
679                         session_selector_.setTabText(index, session->name());
680                 }
681
682         // Refresh window title if the affected session has focus
683         if (session == last_focused_session_.get())
684                 setWindowTitle(session->name() + " - " + WindowTitle);
685 }
686
687 void MainWindow::on_capture_state_changed(QObject *obj)
688 {
689         Session *caller = qobject_cast<Session*>(obj);
690
691         // Ignore if caller is not the currently focused session
692         // unless there is only one session
693         if ((sessions_.size() > 1) && (caller != last_focused_session_.get()))
694                 return;
695
696         int state = caller->get_capture_state();
697
698         const QIcon *icons[] = {&icon_grey_, &icon_red_, &icon_green_};
699         run_stop_button_->setIcon(*icons[state]);
700         run_stop_button_->setText((state == pv::Session::Stopped) ?
701                 tr("Run") : tr("Stop"));
702 }
703
704 void MainWindow::on_new_view(Session *session)
705 {
706         // We get a pointer and need a reference
707         for (shared_ptr<Session> s : sessions_)
708                 if (s.get() == session)
709                         add_view(session->name(), views::ViewTypeTrace, *s);
710 }
711
712 void MainWindow::on_view_close_clicked()
713 {
714         // Find the dock widget that contains the close button that was clicked
715         QObject *w = QObject::sender();
716         QDockWidget *dock = nullptr;
717
718         while (w) {
719             dock = qobject_cast<QDockWidget*>(w);
720             if (dock)
721                 break;
722             w = w->parent();
723         }
724
725         // Get the view contained in the dock widget
726         shared_ptr<views::ViewBase> view;
727
728         for (auto entry : view_docks_)
729                 if (entry.first == dock)
730                         view = entry.second;
731
732         // Deregister the view
733         for (shared_ptr<Session> session : sessions_) {
734                 if (!session->has_view(view))
735                         continue;
736
737                 // Also destroy the entire session if its main view is closing...
738                 if (view == session->main_view()) {
739                         // ...but only if data is saved or the user confirms closing
740                         if (session->data_saved() || (QMessageBox::question(this, tr("Confirmation"),
741                                 tr("This session contains unsaved data. Close it anyway?"),
742                                 QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes))
743                                 remove_session(session);
744                         break;
745                 } else
746                         // All other views can be closed at any time as no data will be lost
747                         remove_view(view);
748         }
749 }
750
751 void MainWindow::on_tab_changed(int index)
752 {
753         shared_ptr<Session> session = get_tab_session(index);
754
755         if (session)
756                 on_focused_session_changed(session);
757 }
758
759 void MainWindow::on_tab_close_requested(int index)
760 {
761         shared_ptr<Session> session = get_tab_session(index);
762
763         if (!session)
764                 return;
765
766         if (session->data_saved() || (QMessageBox::question(this, tr("Confirmation"),
767                 tr("This session contains unsaved data. Close it anyway?"),
768                 QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes))
769                 remove_session(session);
770 }
771
772 void MainWindow::on_view_coloured_bg_shortcut()
773 {
774         GlobalSettings settings;
775
776         bool state = settings.value(GlobalSettings::Key_View_ColouredBG).toBool();
777         settings.setValue(GlobalSettings::Key_View_ColouredBG, !state);
778 }
779
780 void MainWindow::on_view_sticky_scrolling_shortcut()
781 {
782         GlobalSettings settings;
783
784         bool state = settings.value(GlobalSettings::Key_View_StickyScrolling).toBool();
785         settings.setValue(GlobalSettings::Key_View_StickyScrolling, !state);
786 }
787
788 void MainWindow::on_view_show_sampling_points_shortcut()
789 {
790         GlobalSettings settings;
791
792         bool state = settings.value(GlobalSettings::Key_View_ShowSamplingPoints).toBool();
793         settings.setValue(GlobalSettings::Key_View_ShowSamplingPoints, !state);
794 }
795
796 void MainWindow::on_view_show_analog_minor_grid_shortcut()
797 {
798         GlobalSettings settings;
799
800         bool state = settings.value(GlobalSettings::Key_View_ShowAnalogMinorGrid).toBool();
801         settings.setValue(GlobalSettings::Key_View_ShowAnalogMinorGrid, !state);
802 }
803
804 void MainWindow::on_settingViewColouredBg_changed(const QVariant new_value)
805 {
806         bool state = new_value.toBool();
807
808         for (auto entry : view_docks_) {
809                 shared_ptr<views::ViewBase> viewbase = entry.second;
810
811                 // Only trace views have this setting
812                 views::trace::View* view =
813                                 qobject_cast<views::trace::View*>(viewbase.get());
814                 if (view)
815                         view->enable_coloured_bg(state);
816         }
817 }
818
819 void MainWindow::on_settingViewShowSamplingPoints_changed(const QVariant new_value)
820 {
821         bool state = new_value.toBool();
822
823         for (auto entry : view_docks_) {
824                 shared_ptr<views::ViewBase> viewbase = entry.second;
825
826                 // Only trace views have this setting
827                 views::trace::View* view =
828                                 qobject_cast<views::trace::View*>(viewbase.get());
829                 if (view)
830                         view->enable_show_sampling_points(state);
831         }
832 }
833
834 void MainWindow::on_settingViewShowAnalogMinorGrid_changed(const QVariant new_value)
835 {
836         bool state = new_value.toBool();
837
838         for (auto entry : view_docks_) {
839                 shared_ptr<views::ViewBase> viewbase = entry.second;
840
841                 // Only trace views have this setting
842                 views::trace::View* view =
843                                 qobject_cast<views::trace::View*>(viewbase.get());
844                 if (view)
845                         view->enable_show_analog_minor_grid(state);
846         }
847 }
848
849 void MainWindow::on_close_current_tab()
850 {
851         int tab = session_selector_.currentIndex();
852
853         on_tab_close_requested(tab);
854 }
855
856 } // namespace pv