]> sigrok.org Git - pulseview.git/blob - pv/mainwindow.cpp
pv: adjust application source code for Qt6 support
[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 <QDebug>
34 #include <QDockWidget>
35 #include <QHBoxLayout>
36 #include <QMessageBox>
37 #include <QSettings>
38 #include <QShortcut>
39 #include <QWidget>
40
41 #include "mainwindow.hpp"
42
43 #include "application.hpp"
44 #include "devicemanager.hpp"
45 #include "devices/hardwaredevice.hpp"
46 #include "dialogs/settings.hpp"
47 #include "globalsettings.hpp"
48 #include "toolbars/mainbar.hpp"
49 #include "util.hpp"
50 #include "views/trace/view.hpp"
51 #include "views/trace/standardbar.hpp"
52
53 #ifdef ENABLE_DECODE
54 #include "subwindows/decoder_selector/subwindow.hpp"
55 #include "views/decoder_binary/view.hpp"
56 #include "views/tabular_decoder/view.hpp"
57 #endif
58
59 #include <libsigrokcxx/libsigrokcxx.hpp>
60
61 using std::dynamic_pointer_cast;
62 using std::make_shared;
63 using std::shared_ptr;
64 using std::string;
65
66 namespace pv {
67
68 using toolbars::MainBar;
69
70 const QString MainWindow::WindowTitle = tr("PulseView");
71
72 MainWindow::MainWindow(DeviceManager &device_manager, QWidget *parent) :
73         QMainWindow(parent),
74         device_manager_(device_manager),
75         session_selector_(this),
76         icon_red_(":/icons/status-red.svg"),
77         icon_green_(":/icons/status-green.svg"),
78         icon_grey_(":/icons/status-grey.svg")
79 {
80         setup_ui();
81         restore_ui_settings();
82 }
83
84 MainWindow::~MainWindow()
85 {
86         // Make sure we no longer hold any shared pointers to widgets after the
87         // destructor finishes (goes for sessions and sub windows alike)
88
89         while (!sessions_.empty())
90                 remove_session(sessions_.front());
91
92         sub_windows_.clear();
93 }
94
95 void MainWindow::show_session_error(const QString text, const QString info_text)
96 {
97         // TODO Emulate noquote()
98         qDebug() << "Notifying user of session error: " << text << "; " << info_text;
99
100         QMessageBox msg;
101         msg.setText(text + "\n\n" + info_text);
102         msg.setStandardButtons(QMessageBox::Ok);
103         msg.setIcon(QMessageBox::Warning);
104         msg.exec();
105 }
106
107 shared_ptr<views::ViewBase> MainWindow::get_active_view() const
108 {
109         // If there's only one view, use it...
110         if (view_docks_.size() == 1)
111                 return view_docks_.begin()->second;
112
113         // ...otherwise find the dock widget the widget with focus is contained in
114         QObject *w = QApplication::focusWidget();
115         QDockWidget *dock = nullptr;
116
117         while (w) {
118                 dock = qobject_cast<QDockWidget*>(w);
119                 if (dock)
120                         break;
121                 w = w->parent();
122         }
123
124         // Get the view contained in the dock widget
125         for (auto& entry : view_docks_)
126                 if (entry.first == dock)
127                         return entry.second;
128
129         return nullptr;
130 }
131
132 shared_ptr<views::ViewBase> MainWindow::add_view(views::ViewType type,
133         Session &session)
134 {
135         GlobalSettings settings;
136         shared_ptr<views::ViewBase> v;
137
138         QMainWindow *main_window = nullptr;
139         for (auto& entry : session_windows_)
140                 if (entry.first.get() == &session)
141                         main_window = entry.second;
142
143         assert(main_window);
144
145         shared_ptr<MainBar> main_bar = session.main_bar();
146
147         // Only use the view type in the name if it's not the main view
148         QString title;
149         if (main_bar)
150                 title = QString("%1 (%2)").arg(session.name(), views::ViewTypeNames[type]);
151         else
152                 title = session.name();
153
154         QDockWidget* dock = new QDockWidget(title, main_window);
155         dock->setObjectName(title);
156         main_window->addDockWidget(Qt::TopDockWidgetArea, dock);
157
158         // Insert a QMainWindow into the dock widget to allow for a tool bar
159         QMainWindow *dock_main = new QMainWindow(dock);
160         dock_main->setWindowFlags(Qt::Widget);  // Remove Qt::Window flag
161
162         if (type == views::ViewTypeTrace)
163                 // This view will be the main view if there's no main bar yet
164                 v = make_shared<views::trace::View>(session, (main_bar ? false : true), dock_main);
165 #ifdef ENABLE_DECODE
166         if (type == views::ViewTypeDecoderBinary)
167                 v = make_shared<views::decoder_binary::View>(session, false, dock_main);
168         if (type == views::ViewTypeTabularDecoder)
169                 v = make_shared<views::tabular_decoder::View>(session, false, dock_main);
170 #endif
171
172         if (!v)
173                 return nullptr;
174
175         view_docks_[dock] = v;
176         session.register_view(v);
177
178         dock_main->setCentralWidget(v.get());
179         dock->setWidget(dock_main);
180
181         dock->setContextMenuPolicy(Qt::PreventContextMenu);
182         dock->setFeatures(QDockWidget::DockWidgetMovable |
183                 QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetClosable);
184
185         QAbstractButton *close_btn =
186                 dock->findChildren<QAbstractButton*>("qt_dockwidget_closebutton")  // clazy:exclude=detaching-temporary
187                         .front();
188
189         connect(close_btn, SIGNAL(clicked(bool)),
190                 this, SLOT(on_view_close_clicked()));
191
192         connect(&session, SIGNAL(trigger_event(int, util::Timestamp)),
193                 qobject_cast<views::ViewBase*>(v.get()),
194                 SLOT(trigger_event(int, util::Timestamp)));
195
196         if (type == views::ViewTypeTrace) {
197                 views::trace::View *tv =
198                         qobject_cast<views::trace::View*>(v.get());
199
200                 if (!main_bar) {
201                         /* Initial view, create the main bar */
202                         main_bar = make_shared<MainBar>(session, this, tv);
203                         dock_main->addToolBar(main_bar.get());
204                         session.set_main_bar(main_bar);
205
206                         connect(main_bar.get(), SIGNAL(new_view(Session*, int)),
207                                 this, SLOT(on_new_view(Session*, int)));
208                         connect(main_bar.get(), SIGNAL(show_decoder_selector(Session*)),
209                                 this, SLOT(on_show_decoder_selector(Session*)));
210
211                         main_bar->action_view_show_cursors()->setChecked(tv->cursors_shown());
212
213                         /* For the main view we need to prevent the dock widget from
214                          * closing itself when its close button is clicked. This is
215                          * so we can confirm with the user first. Regular views don't
216                          * need this */
217                         close_btn->disconnect(SIGNAL(clicked()), dock, SLOT(close()));
218                 } else {
219                         /* Additional view, create a standard bar */
220                         pv::views::trace::StandardBar *standard_bar =
221                                 new pv::views::trace::StandardBar(session, this, tv);
222                         dock_main->addToolBar(standard_bar);
223
224                         standard_bar->action_view_show_cursors()->setChecked(tv->cursors_shown());
225                 }
226         }
227
228         v->setFocus();
229
230         return v;
231 }
232
233 void MainWindow::remove_view(shared_ptr<views::ViewBase> view)
234 {
235         for (shared_ptr<Session> session : sessions_) {
236                 if (!session->has_view(view))
237                         continue;
238
239                 // Find the dock the view is contained in and remove it
240                 for (auto& entry : view_docks_)
241                         if (entry.second == view) {
242                                 // Remove the view from the session
243                                 session->deregister_view(view);
244
245                                 // Remove the view from its parent; otherwise, Qt will
246                                 // call deleteLater() on it, which causes a double free
247                                 // since the shared_ptr in view_docks_ doesn't know
248                                 // that Qt keeps a pointer to the view around
249                                 view->setParent(nullptr);
250
251                                 // Delete the view's dock widget and all widgets inside it
252                                 entry.first->deleteLater();
253
254                                 // Remove the dock widget from the list and stop iterating
255                                 view_docks_.erase(entry.first);
256                                 break;
257                         }
258         }
259 }
260
261 shared_ptr<subwindows::SubWindowBase> MainWindow::add_subwindow(
262         subwindows::SubWindowType type, Session &session)
263 {
264         GlobalSettings settings;
265         shared_ptr<subwindows::SubWindowBase> w;
266
267         QMainWindow *main_window = nullptr;
268         for (auto& entry : session_windows_)
269                 if (entry.first.get() == &session)
270                         main_window = entry.second;
271
272         assert(main_window);
273
274         QString title = "";
275
276         switch (type) {
277 #ifdef ENABLE_DECODE
278                 case subwindows::SubWindowTypeDecoderSelector:
279                         title = tr("Decoder Selector");
280                         break;
281 #endif
282                 default:
283                         break;
284         }
285
286         QDockWidget* dock = new QDockWidget(title, main_window);
287         dock->setObjectName(title);
288         main_window->addDockWidget(Qt::TopDockWidgetArea, dock);
289
290         // Insert a QMainWindow into the dock widget to allow for a tool bar
291         QMainWindow *dock_main = new QMainWindow(dock);
292         dock_main->setWindowFlags(Qt::Widget);  // Remove Qt::Window flag
293
294 #ifdef ENABLE_DECODE
295         if (type == subwindows::SubWindowTypeDecoderSelector)
296                 w = make_shared<subwindows::decoder_selector::SubWindow>(session, dock_main);
297 #endif
298
299         if (!w)
300                 return nullptr;
301
302         sub_windows_[dock] = w;
303         dock_main->setCentralWidget(w.get());
304         dock->setWidget(dock_main);
305
306         dock->setContextMenuPolicy(Qt::PreventContextMenu);
307         dock->setFeatures(QDockWidget::DockWidgetMovable |
308                 QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetClosable);
309
310         QAbstractButton *close_btn =
311                 dock->findChildren<QAbstractButton*>  // clazy:exclude=detaching-temporary
312                         ("qt_dockwidget_closebutton").front();
313
314         // Allow all subwindows to be closed via ESC.
315         close_btn->setShortcut(QKeySequence(Qt::Key_Escape));
316
317         connect(close_btn, SIGNAL(clicked(bool)),
318                 this, SLOT(on_sub_window_close_clicked()));
319
320         if (w->has_toolbar())
321                 dock_main->addToolBar(w->create_toolbar(dock_main));
322
323         if (w->minimum_width() > 0)
324                 dock->setMinimumSize(w->minimum_width(), 0);
325
326         return w;
327 }
328
329 shared_ptr<Session> MainWindow::add_session()
330 {
331         static int last_session_id = 1;
332         QString name = tr("Session %1").arg(last_session_id++);
333
334         shared_ptr<Session> session = make_shared<Session>(device_manager_, name);
335
336         connect(session.get(), SIGNAL(add_view(ViewType, Session*)),
337                 this, SLOT(on_add_view(ViewType, Session*)));
338         connect(session.get(), SIGNAL(name_changed()),
339                 this, SLOT(on_session_name_changed()));
340         connect(session.get(), SIGNAL(device_changed()),
341                 this, SLOT(on_session_device_changed()));
342         connect(session.get(), SIGNAL(capture_state_changed(int)),
343                 this, SLOT(on_session_capture_state_changed(int)));
344
345         sessions_.push_back(session);
346
347         QMainWindow *window = new QMainWindow();
348         window->setWindowFlags(Qt::Widget);  // Remove Qt::Window flag
349         session_windows_[session] = window;
350
351         int index = session_selector_.addTab(window, name);
352         session_selector_.setCurrentIndex(index);
353         last_focused_session_ = session;
354
355         window->setDockNestingEnabled(true);
356
357         add_view(views::ViewTypeTrace, *session);
358
359         return session;
360 }
361
362 void MainWindow::remove_session(shared_ptr<Session> session)
363 {
364         // Determine the height of the button before it collapses
365         int h = new_session_button_->height();
366
367         // Stop capture while the session still exists so that the UI can be
368         // updated in case we're currently running. If so, this will schedule a
369         // call to our on_capture_state_changed() slot for the next run of the
370         // event loop. We need to have this executed immediately or else it will
371         // be dismissed since the session object will be deleted by the time we
372         // leave this method and the event loop gets a chance to run again.
373         session->stop_capture();
374         QApplication::processEvents();
375
376         for (const shared_ptr<views::ViewBase>& view : session->views())
377                 remove_view(view);
378
379         QMainWindow *window = session_windows_.at(session);
380         session_selector_.removeTab(session_selector_.indexOf(window));
381
382         session_windows_.erase(session);
383
384         if (last_focused_session_ == session)
385                 last_focused_session_.reset();
386
387         // Remove the session from our list of sessions (which also destroys it)
388         sessions_.remove_if([&](shared_ptr<Session> s) {
389                 return s == session; });
390
391         if (sessions_.empty()) {
392                 // When there are no more tabs, the height of the QTabWidget
393                 // drops to zero. We must prevent this to keep the static
394                 // widgets visible
395                 for (QWidget *w : static_tab_widget_->findChildren<QWidget*>())  // clazy:exclude=range-loop
396                         w->setMinimumHeight(h);
397
398                 int margin = static_tab_widget_->layout()->contentsMargins().bottom();
399                 static_tab_widget_->setMinimumHeight(h + 2 * margin);
400                 session_selector_.setMinimumHeight(h + 2 * margin);
401
402                 // Update the window title if there is no view left to
403                 // generate focus change events
404                 setWindowTitle(WindowTitle);
405         }
406 }
407
408 void MainWindow::add_session_with_file(string open_file_name,
409         string open_file_format, string open_setup_file_name)
410 {
411         shared_ptr<Session> session = add_session();
412         session->load_init_file(open_file_name, open_file_format, open_setup_file_name);
413 }
414
415 void MainWindow::add_default_session()
416 {
417         // Only add the default session if there would be no session otherwise
418         if (sessions_.size() > 0)
419                 return;
420
421         shared_ptr<Session> session = add_session();
422
423         // Check the list of available devices. Prefer the one that was
424         // found with user supplied scan specs (if applicable). Then try
425         // one of the auto detected devices that are not the demo device.
426         // Pick demo in the absence of "genuine" hardware devices.
427         shared_ptr<devices::HardwareDevice> user_device, other_device, demo_device;
428         for (const shared_ptr<devices::HardwareDevice>& dev : device_manager_.devices()) {
429                 if (dev == device_manager_.user_spec_device()) {
430                         user_device = dev;
431                 } else if (dev->hardware_device()->driver()->name() == "demo") {
432                         demo_device = dev;
433                 } else {
434                         other_device = dev;
435                 }
436         }
437         if (user_device)
438                 session->select_device(user_device);
439         else if (other_device)
440                 session->select_device(other_device);
441         else
442                 session->select_device(demo_device);
443 }
444
445 void MainWindow::save_sessions()
446 {
447         QSettings settings;
448         int id = 0;
449
450         for (shared_ptr<Session>& session : sessions_) {
451                 // Ignore sessions using the demo device or no device at all
452                 if (session->device()) {
453                         shared_ptr<devices::HardwareDevice> device =
454                                 dynamic_pointer_cast< devices::HardwareDevice >
455                                 (session->device());
456
457                         if (device &&
458                                 device->hardware_device()->driver()->name() == "demo")
459                                 continue;
460
461                         settings.beginGroup("Session" + QString::number(id++));
462                         settings.remove("");  // Remove all keys in this group
463                         session->save_settings(settings);
464                         settings.endGroup();
465                 }
466         }
467
468         settings.setValue("sessions", id);
469 }
470
471 void MainWindow::restore_sessions()
472 {
473         QSettings settings;
474         int i, session_count;
475
476         session_count = settings.value("sessions", 0).toInt();
477
478         for (i = 0; i < session_count; i++) {
479                 settings.beginGroup("Session" + QString::number(i));
480                 shared_ptr<Session> session = add_session();
481                 session->restore_settings(settings);
482                 settings.endGroup();
483         }
484 }
485
486 void MainWindow::setup_ui()
487 {
488         setObjectName(QString::fromUtf8("MainWindow"));
489
490         setCentralWidget(&session_selector_);
491
492         // Set the window icon
493         QIcon icon;
494         icon.addFile(QString(":/icons/pulseview.png"));
495         setWindowIcon(icon);
496
497         // Set up keyboard shortcuts that affect all views at once
498         view_sticky_scrolling_shortcut_ = new QShortcut(QKeySequence(Qt::Key_S), this, SLOT(on_view_sticky_scrolling_shortcut()));
499         view_sticky_scrolling_shortcut_->setAutoRepeat(false);
500
501         view_show_sampling_points_shortcut_ = new QShortcut(QKeySequence(Qt::Key_Period), this, SLOT(on_view_show_sampling_points_shortcut()));
502         view_show_sampling_points_shortcut_->setAutoRepeat(false);
503
504         view_show_analog_minor_grid_shortcut_ = new QShortcut(QKeySequence(Qt::Key_G), this, SLOT(on_view_show_analog_minor_grid_shortcut()));
505         view_show_analog_minor_grid_shortcut_->setAutoRepeat(false);
506
507         view_colored_bg_shortcut_ = new QShortcut(QKeySequence(Qt::Key_B), this, SLOT(on_view_colored_bg_shortcut()));
508         view_colored_bg_shortcut_->setAutoRepeat(false);
509
510         // Set up the tab area
511         new_session_button_ = new QToolButton();
512         new_session_button_->setIcon(QIcon::fromTheme("document-new",
513                 QIcon(":/icons/document-new.png")));
514         new_session_button_->setToolTip(tr("Create New Session"));
515         new_session_button_->setAutoRaise(true);
516
517         run_stop_button_ = new QToolButton();
518         run_stop_button_->setAutoRaise(true);
519         run_stop_button_->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
520         run_stop_button_->setToolTip(tr("Start/Stop Acquisition"));
521
522         run_stop_shortcut_ = new QShortcut(QKeySequence(Qt::Key_Space), run_stop_button_, SLOT(click()));
523         run_stop_shortcut_->setAutoRepeat(false);
524
525         settings_button_ = new QToolButton();
526         settings_button_->setIcon(QIcon::fromTheme("preferences-system",
527                 QIcon(":/icons/preferences-system.png")));
528         settings_button_->setToolTip(tr("Settings"));
529         settings_button_->setAutoRaise(true);
530
531         QFrame *separator1 = new QFrame();
532         separator1->setFrameStyle(QFrame::VLine | QFrame::Raised);
533         QFrame *separator2 = new QFrame();
534         separator2->setFrameStyle(QFrame::VLine | QFrame::Raised);
535
536         QHBoxLayout* layout = new QHBoxLayout();
537         layout->setContentsMargins(2, 2, 2, 2);
538         layout->addWidget(new_session_button_);
539         layout->addWidget(separator1);
540         layout->addWidget(run_stop_button_);
541         layout->addWidget(separator2);
542         layout->addWidget(settings_button_);
543
544         static_tab_widget_ = new QWidget();
545         static_tab_widget_->setLayout(layout);
546
547         session_selector_.setCornerWidget(static_tab_widget_, Qt::TopLeftCorner);
548         session_selector_.setTabsClosable(true);
549
550 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
551         close_application_shortcut_ = new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_Q), this, SLOT(close()));
552         close_current_tab_shortcut_ = new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_W), this, SLOT(on_close_current_tab()));
553 #else
554         close_application_shortcut_ = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q), this, SLOT(close()));
555         close_current_tab_shortcut_ = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_W), this, SLOT(on_close_current_tab()));
556 #endif
557         close_application_shortcut_->setAutoRepeat(false);
558
559         connect(new_session_button_, SIGNAL(clicked(bool)),
560                 this, SLOT(on_new_session_clicked()));
561         connect(run_stop_button_, SIGNAL(clicked(bool)),
562                 this, SLOT(on_run_stop_clicked()));
563         connect(settings_button_, SIGNAL(clicked(bool)),
564                 this, SLOT(on_settings_clicked()));
565
566         connect(&session_selector_, SIGNAL(tabCloseRequested(int)),
567                 this, SLOT(on_tab_close_requested(int)));
568         connect(&session_selector_, SIGNAL(currentChanged(int)),
569                 this, SLOT(on_tab_changed(int)));
570
571
572         connect(static_cast<QApplication *>(QCoreApplication::instance()),
573                 SIGNAL(focusChanged(QWidget*, QWidget*)),
574                 this, SLOT(on_focus_changed()));
575 }
576
577 void MainWindow::update_acq_button(Session *session)
578 {
579         int state;
580         QString run_caption;
581
582         if (session) {
583                 state = session->get_capture_state();
584                 run_caption = session->using_file_device() ? tr("Reload") : tr("Run");
585         } else {
586                 state = Session::Stopped;
587                 run_caption = tr("Run");
588         }
589
590         const QIcon *icons[] = {&icon_grey_, &icon_red_, &icon_green_};
591         run_stop_button_->setIcon(*icons[state]);
592         run_stop_button_->setText((state == pv::Session::Stopped) ?
593                 run_caption : tr("Stop"));
594 }
595
596 void MainWindow::save_ui_settings()
597 {
598         QSettings settings;
599
600         settings.beginGroup("MainWindow");
601         settings.setValue("state", saveState());
602         settings.setValue("geometry", saveGeometry());
603         settings.endGroup();
604 }
605
606 void MainWindow::restore_ui_settings()
607 {
608         QSettings settings;
609
610         settings.beginGroup("MainWindow");
611
612         if (settings.contains("geometry")) {
613                 restoreGeometry(settings.value("geometry").toByteArray());
614                 restoreState(settings.value("state").toByteArray());
615         } else
616                 resize(1000, 720);
617
618         settings.endGroup();
619 }
620
621 shared_ptr<Session> MainWindow::get_tab_session(int index) const
622 {
623         // Find the session that belongs to the tab's main window
624         for (auto& entry : session_windows_)
625                 if (entry.second == session_selector_.widget(index))
626                         return entry.first;
627
628         return nullptr;
629 }
630
631 void MainWindow::closeEvent(QCloseEvent *event)
632 {
633         bool data_saved = true;
634
635         for (auto& entry : session_windows_)
636                 if (!entry.first->data_saved())
637                         data_saved = false;
638
639         if (!data_saved && (QMessageBox::question(this, tr("Confirmation"),
640                 tr("There is unsaved data. Close anyway?"),
641                 QMessageBox::Yes | QMessageBox::No) == QMessageBox::No)) {
642                 event->ignore();
643         } else {
644                 save_ui_settings();
645                 save_sessions();
646                 event->accept();
647         }
648 }
649
650 QMenu* MainWindow::createPopupMenu()
651 {
652         return nullptr;
653 }
654
655 bool MainWindow::restoreState(const QByteArray &state, int version)
656 {
657         (void)state;
658         (void)version;
659
660         // Do nothing. We don't want Qt to handle this, or else it
661         // will try to restore all the dock widgets and create havoc.
662
663         return false;
664 }
665
666 void MainWindow::on_run_stop_clicked()
667 {
668         GlobalSettings settings;
669         bool all_sessions = settings.value(GlobalSettings::Key_General_StartAllSessions).toBool();
670
671         if (all_sessions)
672         {
673                 vector< shared_ptr<Session> > hw_sessions;
674
675                 // Make a list of all sessions where a hardware device is used
676                 for (const shared_ptr<Session>& s : sessions_) {
677                         shared_ptr<devices::HardwareDevice> hw_device =
678                                         dynamic_pointer_cast< devices::HardwareDevice >(s->device());
679                         if (!hw_device)
680                                 continue;
681                         hw_sessions.push_back(s);
682                 }
683
684                 // Stop all acquisitions if there are any running ones, start all otherwise
685                 bool any_running = any_of(hw_sessions.begin(), hw_sessions.end(),
686                                 [](const shared_ptr<Session> &s)
687                                 { return (s->get_capture_state() == Session::AwaitingTrigger) ||
688                                                 (s->get_capture_state() == Session::Running); });
689
690                 for (shared_ptr<Session> s : hw_sessions)
691                         if (any_running)
692                                 s->stop_capture();
693                         else
694                                 s->start_capture([&](QString message) {
695                                         show_session_error("Capture failed", message); });
696         } else {
697
698                 shared_ptr<Session> session = last_focused_session_;
699
700                 if (!session)
701                         return;
702
703                 switch (session->get_capture_state()) {
704                 case Session::Stopped:
705                         session->start_capture([&](QString message) {
706                                 show_session_error("Capture failed", message); });
707                         break;
708                 case Session::AwaitingTrigger:
709                 case Session::Running:
710                         session->stop_capture();
711                         break;
712                 }
713         }
714 }
715
716 void MainWindow::on_add_view(views::ViewType type, Session *session)
717 {
718         // We get a pointer and need a reference
719         for (shared_ptr<Session>& s : sessions_)
720                 if (s.get() == session)
721                         add_view(type, *s);
722 }
723
724 void MainWindow::on_focus_changed()
725 {
726         shared_ptr<views::ViewBase> view = get_active_view();
727
728         if (view) {
729                 for (shared_ptr<Session> session : sessions_) {
730                         if (session->has_view(view)) {
731                                 if (session != last_focused_session_) {
732                                         // Activate correct tab if necessary
733                                         shared_ptr<Session> tab_session = get_tab_session(
734                                                 session_selector_.currentIndex());
735                                         if (tab_session != session)
736                                                 session_selector_.setCurrentWidget(
737                                                         session_windows_.at(session));
738
739                                         on_focused_session_changed(session);
740                                 }
741
742                                 break;
743                         }
744                 }
745         }
746
747         if (sessions_.empty())
748                 setWindowTitle(WindowTitle);
749 }
750
751 void MainWindow::on_focused_session_changed(shared_ptr<Session> session)
752 {
753         last_focused_session_ = session;
754
755         setWindowTitle(session->name() + " - " + WindowTitle);
756
757         // Update the state of the run/stop button, too
758         update_acq_button(session.get());
759 }
760
761 void MainWindow::on_new_session_clicked()
762 {
763         add_session();
764 }
765
766 void MainWindow::on_settings_clicked()
767 {
768         dialogs::Settings dlg(device_manager_);
769         dlg.exec();
770 }
771
772 void MainWindow::on_session_name_changed()
773 {
774         // Update the corresponding dock widget's name(s)
775         Session *session = qobject_cast<Session*>(QObject::sender());
776         assert(session);
777
778         for (const shared_ptr<views::ViewBase>& view : session->views()) {
779                 // Get the dock that contains the view
780                 for (auto& entry : view_docks_)
781                         if (entry.second == view) {
782                                 entry.first->setObjectName(session->name());
783                                 entry.first->setWindowTitle(session->name());
784                         }
785         }
786
787         // Update the tab widget by finding the main window and the tab from that
788         for (auto& entry : session_windows_)
789                 if (entry.first.get() == session) {
790                         QMainWindow *window = entry.second;
791                         const int index = session_selector_.indexOf(window);
792                         session_selector_.setTabText(index, session->name());
793                 }
794
795         // Refresh window title if the affected session has focus
796         if (session == last_focused_session_.get())
797                 setWindowTitle(session->name() + " - " + WindowTitle);
798 }
799
800 void MainWindow::on_session_device_changed()
801 {
802         Session *session = qobject_cast<Session*>(QObject::sender());
803         assert(session);
804
805         // Ignore if caller is not the currently focused session
806         // unless there is only one session
807         if ((sessions_.size() > 1) && (session != last_focused_session_.get()))
808                 return;
809
810         update_acq_button(session);
811 }
812
813 void MainWindow::on_session_capture_state_changed(int state)
814 {
815         (void)state;
816
817         Session *session = qobject_cast<Session*>(QObject::sender());
818         assert(session);
819
820         // Ignore if caller is not the currently focused session
821         // unless there is only one session
822         if ((sessions_.size() > 1) && (session != last_focused_session_.get()))
823                 return;
824
825         update_acq_button(session);
826 }
827
828 void MainWindow::on_new_view(Session *session, int view_type)
829 {
830         // We get a pointer and need a reference
831         for (shared_ptr<Session>& s : sessions_)
832                 if (s.get() == session)
833                         add_view((views::ViewType)view_type, *s);
834 }
835
836 void MainWindow::on_view_close_clicked()
837 {
838         // Find the dock widget that contains the close button that was clicked
839         QObject *w = QObject::sender();
840         QDockWidget *dock = nullptr;
841
842         while (w) {
843             dock = qobject_cast<QDockWidget*>(w);
844             if (dock)
845                 break;
846             w = w->parent();
847         }
848
849         // Get the view contained in the dock widget
850         shared_ptr<views::ViewBase> view;
851
852         for (auto& entry : view_docks_)
853                 if (entry.first == dock)
854                         view = entry.second;
855
856         // Deregister the view
857         for (shared_ptr<Session> session : sessions_) {
858                 if (!session->has_view(view))
859                         continue;
860
861                 // Also destroy the entire session if its main view is closing...
862                 if (view == session->main_view()) {
863                         // ...but only if data is saved or the user confirms closing
864                         if (session->data_saved() || (QMessageBox::question(this, tr("Confirmation"),
865                                 tr("This session contains unsaved data. Close it anyway?"),
866                                 QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes))
867                                 remove_session(session);
868                         break;
869                 } else
870                         // All other views can be closed at any time as no data will be lost
871                         remove_view(view);
872         }
873 }
874
875 void MainWindow::on_tab_changed(int index)
876 {
877         shared_ptr<Session> session = get_tab_session(index);
878
879         if (session)
880                 on_focused_session_changed(session);
881 }
882
883 void MainWindow::on_tab_close_requested(int index)
884 {
885         shared_ptr<Session> session = get_tab_session(index);
886
887         if (!session)
888                 return;
889
890         if (session->data_saved() || (QMessageBox::question(this, tr("Confirmation"),
891                 tr("This session contains unsaved data. Close it anyway?"),
892                 QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes))
893                 remove_session(session);
894
895         if (sessions_.empty())
896                 update_acq_button(nullptr);
897 }
898
899 void MainWindow::on_show_decoder_selector(Session *session)
900 {
901 #ifdef ENABLE_DECODE
902         // Close dock widget if it's already showing and return
903         for (auto& entry : sub_windows_) {
904                 QDockWidget* dock = entry.first;
905                 shared_ptr<subwindows::SubWindowBase> decoder_selector =
906                         dynamic_pointer_cast<subwindows::decoder_selector::SubWindow>(entry.second);
907
908                 if (decoder_selector && (&decoder_selector->session() == session)) {
909                         sub_windows_.erase(dock);
910                         dock->close();
911                         return;
912                 }
913         }
914
915         // We get a pointer and need a reference
916         for (shared_ptr<Session>& s : sessions_)
917                 if (s.get() == session)
918                         add_subwindow(subwindows::SubWindowTypeDecoderSelector, *s);
919 #else
920         (void)session;
921 #endif
922 }
923
924 void MainWindow::on_sub_window_close_clicked()
925 {
926         // Find the dock widget that contains the close button that was clicked
927         QObject *w = QObject::sender();
928         QDockWidget *dock = nullptr;
929
930         while (w) {
931             dock = qobject_cast<QDockWidget*>(w);
932             if (dock)
933                 break;
934             w = w->parent();
935         }
936
937         sub_windows_.erase(dock);
938         dock->close();
939
940         // Restore focus to the last used main view
941         if (last_focused_session_)
942                 last_focused_session_->main_view()->setFocus();
943 }
944
945 void MainWindow::on_view_colored_bg_shortcut()
946 {
947         GlobalSettings settings;
948
949         bool state = settings.value(GlobalSettings::Key_View_ColoredBG).toBool();
950         settings.setValue(GlobalSettings::Key_View_ColoredBG, !state);
951 }
952
953 void MainWindow::on_view_sticky_scrolling_shortcut()
954 {
955         GlobalSettings settings;
956
957         bool state = settings.value(GlobalSettings::Key_View_StickyScrolling).toBool();
958         settings.setValue(GlobalSettings::Key_View_StickyScrolling, !state);
959 }
960
961 void MainWindow::on_view_show_sampling_points_shortcut()
962 {
963         GlobalSettings settings;
964
965         bool state = settings.value(GlobalSettings::Key_View_ShowSamplingPoints).toBool();
966         settings.setValue(GlobalSettings::Key_View_ShowSamplingPoints, !state);
967 }
968
969 void MainWindow::on_view_show_analog_minor_grid_shortcut()
970 {
971         GlobalSettings settings;
972
973         bool state = settings.value(GlobalSettings::Key_View_ShowAnalogMinorGrid).toBool();
974         settings.setValue(GlobalSettings::Key_View_ShowAnalogMinorGrid, !state);
975 }
976
977 void MainWindow::on_close_current_tab()
978 {
979         int tab = session_selector_.currentIndex();
980
981         on_tab_close_requested(tab);
982 }
983
984 } // namespace pv