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