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