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