2 * This file is part of the PulseView project.
4 * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk>
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.
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.
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/>.
21 #include <libsigrokdecode/libsigrokdecode.h>
31 #include <QApplication>
32 #include <QCloseEvent>
33 #include <QDockWidget>
34 #include <QHBoxLayout>
35 #include <QMessageBox>
40 #include "mainwindow.hpp"
42 #include "devicemanager.hpp"
43 #include "globalsettings.hpp"
45 #include "devices/hardwaredevice.hpp"
46 #include "dialogs/about.hpp"
47 #include "dialogs/settings.hpp"
48 #include "toolbars/mainbar.hpp"
49 #include "view/view.hpp"
50 #include "views/trace/standardbar.hpp"
52 #include <libsigrokcxx/libsigrokcxx.hpp>
54 using std::dynamic_pointer_cast;
56 using std::make_shared;
58 using std::shared_ptr;
67 using toolbars::MainBar;
70 using std::placeholders::_1;
72 const QString MainWindow::WindowTitle = tr("PulseView");
74 MainWindow::MainWindow(DeviceManager &device_manager,
75 string open_file_name, string open_file_format,
78 device_manager_(device_manager),
79 session_selector_(this),
80 session_state_mapper_(this),
81 action_about_(new QAction(this)),
82 icon_red_(":/icons/status-red.svg"),
83 icon_green_(":/icons/status-green.svg"),
84 icon_grey_(":/icons/status-grey.svg")
86 qRegisterMetaType<util::Timestamp>("util::Timestamp");
87 qRegisterMetaType<uint64_t>("uint64_t");
89 GlobalSettings::register_change_handler(GlobalSettings::Key_View_ColouredBG,
90 bind(&MainWindow::on_settingViewColouredBg_changed, this, _1));
93 restore_ui_settings();
95 if (!open_file_name.empty()) {
96 shared_ptr<Session> session = add_session();
97 session->load_init_file(open_file_name, open_file_format);
100 // Add empty default session if there aren't any sessions
101 if (sessions_.size() == 0) {
102 shared_ptr<Session> session = add_session();
104 map<string, string> dev_info;
105 shared_ptr<devices::HardwareDevice> other_device, demo_device;
107 // Use any available device that's not demo
108 for (shared_ptr<devices::HardwareDevice> dev : device_manager_.devices()) {
109 if (dev->hardware_device()->driver()->name() == "demo") {
116 // ...and if there isn't any, just use demo then
117 session->select_device(other_device ? other_device : demo_device);
121 MainWindow::~MainWindow()
123 while (!sessions_.empty())
124 remove_session(sessions_.front());
127 QAction* MainWindow::action_about() const
129 return action_about_;
132 shared_ptr<views::ViewBase> MainWindow::get_active_view() const
134 // If there's only one view, use it...
135 if (view_docks_.size() == 1)
136 return view_docks_.begin()->second;
138 // ...otherwise find the dock widget the widget with focus is contained in
139 QObject *w = QApplication::focusWidget();
140 QDockWidget *dock = nullptr;
143 dock = qobject_cast<QDockWidget*>(w);
149 // Get the view contained in the dock widget
150 for (auto entry : view_docks_)
151 if (entry.first == dock)
157 shared_ptr<views::ViewBase> MainWindow::add_view(const QString &title,
158 views::ViewType type, Session &session)
160 GlobalSettings settings;
161 shared_ptr<views::ViewBase> v;
163 QMainWindow *main_window = nullptr;
164 for (auto entry : session_windows_)
165 if (entry.first.get() == &session)
166 main_window = entry.second;
170 shared_ptr<MainBar> main_bar = session.main_bar();
172 QDockWidget* dock = new QDockWidget(title, main_window);
173 dock->setObjectName(title);
174 main_window->addDockWidget(Qt::TopDockWidgetArea, dock);
176 // Insert a QMainWindow into the dock widget to allow for a tool bar
177 QMainWindow *dock_main = new QMainWindow(dock);
178 dock_main->setWindowFlags(Qt::Widget); // Remove Qt::Window flag
180 if (type == views::ViewTypeTrace)
181 // This view will be the main view if there's no main bar yet
182 v = make_shared<views::TraceView::View>(session,
183 (main_bar ? false : true), dock_main);
188 view_docks_[dock] = v;
189 session.register_view(v);
191 dock_main->setCentralWidget(v.get());
192 dock->setWidget(dock_main);
194 dock->setFeatures(QDockWidget::DockWidgetMovable |
195 QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetClosable);
197 QAbstractButton *close_btn =
198 dock->findChildren<QAbstractButton*>
199 ("qt_dockwidget_closebutton").front();
201 connect(close_btn, SIGNAL(clicked(bool)),
202 this, SLOT(on_view_close_clicked()));
204 connect(&session, SIGNAL(trigger_event(util::Timestamp)),
205 qobject_cast<views::ViewBase*>(v.get()),
206 SLOT(trigger_event(util::Timestamp)));
208 if (type == views::ViewTypeTrace) {
209 views::TraceView::View *tv =
210 qobject_cast<views::TraceView::View*>(v.get());
212 tv->enable_sticky_scrolling(true);
213 tv->enable_coloured_bg(settings.value(GlobalSettings::Key_View_ColouredBG).toBool());
216 /* Initial view, create the main bar */
217 main_bar = make_shared<MainBar>(session, this, tv);
218 dock_main->addToolBar(main_bar.get());
219 session.set_main_bar(main_bar);
221 connect(main_bar.get(), SIGNAL(new_view(Session*)),
222 this, SLOT(on_new_view(Session*)));
224 main_bar->action_view_show_cursors()->setChecked(tv->cursors_shown());
226 /* For the main view we need to prevent the dock widget from
227 * closing itself when its close button is clicked. This is
228 * so we can confirm with the user first. Regular views don't
230 close_btn->disconnect(SIGNAL(clicked()), dock, SLOT(close()));
232 /* Additional view, create a standard bar */
233 pv::views::trace::StandardBar *standard_bar =
234 new pv::views::trace::StandardBar(session, this, tv);
235 dock_main->addToolBar(standard_bar);
237 standard_bar->action_view_show_cursors()->setChecked(tv->cursors_shown());
244 void MainWindow::remove_view(shared_ptr<views::ViewBase> view)
246 for (shared_ptr<Session> session : sessions_) {
247 if (!session->has_view(view))
250 // Find the dock the view is contained in and remove it
251 for (auto entry : view_docks_)
252 if (entry.second == view) {
253 // Remove the view from the session
254 session->deregister_view(view);
256 // Remove the view from its parent; otherwise, Qt will
257 // call deleteLater() on it, which causes a double free
258 // since the shared_ptr in view_docks_ doesn't know
259 // that Qt keeps a pointer to the view around
260 view->setParent(nullptr);
262 // Delete the view's dock widget and all widgets inside it
263 entry.first->deleteLater();
265 // Remove the dock widget from the list and stop iterating
266 view_docks_.erase(entry.first);
272 shared_ptr<Session> MainWindow::add_session()
274 static int last_session_id = 1;
275 QString name = tr("Session %1").arg(last_session_id++);
277 shared_ptr<Session> session = make_shared<Session>(device_manager_, name);
279 connect(session.get(), SIGNAL(add_view(const QString&, views::ViewType, Session*)),
280 this, SLOT(on_add_view(const QString&, views::ViewType, Session*)));
281 connect(session.get(), SIGNAL(name_changed()),
282 this, SLOT(on_session_name_changed()));
283 session_state_mapper_.setMapping(session.get(), session.get());
284 connect(session.get(), SIGNAL(capture_state_changed(int)),
285 &session_state_mapper_, SLOT(map()));
287 sessions_.push_back(session);
289 QMainWindow *window = new QMainWindow();
290 window->setWindowFlags(Qt::Widget); // Remove Qt::Window flag
291 session_windows_[session] = window;
293 int index = session_selector_.addTab(window, name);
294 session_selector_.setCurrentIndex(index);
295 last_focused_session_ = session;
297 window->setDockNestingEnabled(true);
299 shared_ptr<views::ViewBase> main_view =
300 add_view(name, views::ViewTypeTrace, *session);
305 void MainWindow::remove_session(shared_ptr<Session> session)
307 int h = new_session_button_->height();
309 for (shared_ptr<views::ViewBase> view : session->views())
312 QMainWindow *window = session_windows_.at(session);
313 session_selector_.removeTab(session_selector_.indexOf(window));
315 session_windows_.erase(session);
317 if (last_focused_session_ == session)
318 last_focused_session_.reset();
320 sessions_.remove_if([&](shared_ptr<Session> s) {
321 return s == session; });
323 if (sessions_.empty()) {
324 // When there are no more tabs, the height of the QTabWidget
325 // drops to zero. We must prevent this to keep the static
327 for (QWidget *w : static_tab_widget_->findChildren<QWidget*>())
328 w->setMinimumHeight(h);
330 int margin = static_tab_widget_->layout()->contentsMargins().bottom();
331 static_tab_widget_->setMinimumHeight(h + 2 * margin);
332 session_selector_.setMinimumHeight(h + 2 * margin);
334 // Update the window title if there is no view left to
335 // generate focus change events
336 setWindowTitle(WindowTitle);
340 void MainWindow::setup_ui()
342 setObjectName(QString::fromUtf8("MainWindow"));
344 setCentralWidget(&session_selector_);
346 // Set the window icon
348 icon.addFile(QString(":/icons/sigrok-logo-notext.png"));
351 view_sticky_scrolling_shortcut_ = new QShortcut(QKeySequence(Qt::Key_S), this, SLOT(on_view_sticky_scrolling_shortcut()));
352 view_sticky_scrolling_shortcut_->setAutoRepeat(false);
354 view_coloured_bg_shortcut_ = new QShortcut(QKeySequence(Qt::Key_B), this, SLOT(on_view_coloured_bg_shortcut()));
355 view_coloured_bg_shortcut_->setAutoRepeat(false);
357 action_about_->setObjectName(QString::fromUtf8("actionAbout"));
358 action_about_->setToolTip(tr("&About..."));
360 // Set up the tab area
361 new_session_button_ = new QToolButton();
362 new_session_button_->setIcon(QIcon::fromTheme("document-new",
363 QIcon(":/icons/document-new.png")));
364 new_session_button_->setToolTip(tr("Create New Session"));
365 new_session_button_->setAutoRaise(true);
367 run_stop_button_ = new QToolButton();
368 run_stop_button_->setAutoRaise(true);
369 run_stop_button_->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
370 run_stop_button_->setToolTip(tr("Start/Stop Acquisition"));
372 run_stop_shortcut_ = new QShortcut(QKeySequence(Qt::Key_Space), run_stop_button_, SLOT(click()));
373 run_stop_shortcut_->setAutoRepeat(false);
375 settings_button_ = new QToolButton();
376 settings_button_->setIcon(QIcon::fromTheme("configure",
377 QIcon(":/icons/configure.png")));
378 settings_button_->setToolTip(tr("Settings"));
379 settings_button_->setAutoRaise(true);
381 QFrame *separator1 = new QFrame();
382 separator1->setFrameStyle(QFrame::VLine | QFrame::Raised);
383 QFrame *separator2 = new QFrame();
384 separator2->setFrameStyle(QFrame::VLine | QFrame::Raised);
386 QHBoxLayout* layout = new QHBoxLayout();
387 layout->setContentsMargins(2, 2, 2, 2);
388 layout->addWidget(new_session_button_);
389 layout->addWidget(separator1);
390 layout->addWidget(run_stop_button_);
391 layout->addWidget(separator2);
392 layout->addWidget(settings_button_);
394 static_tab_widget_ = new QWidget();
395 static_tab_widget_->setLayout(layout);
397 session_selector_.setCornerWidget(static_tab_widget_, Qt::TopLeftCorner);
398 session_selector_.setTabsClosable(true);
400 close_application_shortcut_ = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q), this, SLOT(close()));
401 close_application_shortcut_->setAutoRepeat(false);
403 close_current_tab_shortcut_ = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_W), this, SLOT(on_close_current_tab()));
405 connect(new_session_button_, SIGNAL(clicked(bool)),
406 this, SLOT(on_new_session_clicked()));
407 connect(run_stop_button_, SIGNAL(clicked(bool)),
408 this, SLOT(on_run_stop_clicked()));
409 connect(&session_state_mapper_, SIGNAL(mapped(QObject*)),
410 this, SLOT(on_capture_state_changed(QObject*)));
411 connect(settings_button_, SIGNAL(clicked(bool)),
412 this, SLOT(on_settings_clicked()));
414 connect(&session_selector_, SIGNAL(tabCloseRequested(int)),
415 this, SLOT(on_tab_close_requested(int)));
416 connect(&session_selector_, SIGNAL(currentChanged(int)),
417 this, SLOT(on_tab_changed(int)));
420 connect(static_cast<QApplication *>(QCoreApplication::instance()),
421 SIGNAL(focusChanged(QWidget*, QWidget*)),
422 this, SLOT(on_focus_changed()));
425 void MainWindow::save_ui_settings()
430 settings.beginGroup("MainWindow");
431 settings.setValue("state", saveState());
432 settings.setValue("geometry", saveGeometry());
435 for (shared_ptr<Session> session : sessions_) {
436 // Ignore sessions using the demo device or no device at all
437 if (session->device()) {
438 shared_ptr<devices::HardwareDevice> device =
439 dynamic_pointer_cast< devices::HardwareDevice >
443 device->hardware_device()->driver()->name() == "demo")
446 settings.beginGroup("Session" + QString::number(id++));
447 settings.remove(""); // Remove all keys in this group
448 session->save_settings(settings);
453 settings.setValue("sessions", id);
456 void MainWindow::restore_ui_settings()
459 int i, session_count;
461 settings.beginGroup("MainWindow");
463 if (settings.contains("geometry")) {
464 restoreGeometry(settings.value("geometry").toByteArray());
465 restoreState(settings.value("state").toByteArray());
471 session_count = settings.value("sessions", 0).toInt();
473 for (i = 0; i < session_count; i++) {
474 settings.beginGroup("Session" + QString::number(i));
475 shared_ptr<Session> session = add_session();
476 session->restore_settings(settings);
481 std::shared_ptr<Session> MainWindow::get_tab_session(int index) const
483 // Find the session that belongs to the tab's main window
484 for (auto entry : session_windows_)
485 if (entry.second == session_selector_.widget(index))
491 void MainWindow::closeEvent(QCloseEvent *event)
493 bool data_saved = true;
495 for (auto entry : session_windows_)
496 if (!entry.first->data_saved())
499 if (!data_saved && (QMessageBox::question(this, tr("Confirmation"),
500 tr("There is unsaved data. Close anyway?"),
501 QMessageBox::Yes | QMessageBox::No) == QMessageBox::No)) {
509 QMenu* MainWindow::createPopupMenu()
514 bool MainWindow::restoreState(const QByteArray &state, int version)
519 // Do nothing. We don't want Qt to handle this, or else it
520 // will try to restore all the dock widgets and create havoc.
525 void MainWindow::session_error(const QString text, const QString info_text)
527 QMetaObject::invokeMethod(this, "show_session_error",
528 Qt::QueuedConnection, Q_ARG(QString, text),
529 Q_ARG(QString, info_text));
532 void MainWindow::show_session_error(const QString text, const QString info_text)
534 QMessageBox msg(this);
536 msg.setInformativeText(info_text);
537 msg.setStandardButtons(QMessageBox::Ok);
538 msg.setIcon(QMessageBox::Warning);
542 void MainWindow::on_add_view(const QString &title, views::ViewType type,
545 // We get a pointer and need a reference
546 for (std::shared_ptr<Session> s : sessions_)
547 if (s.get() == session)
548 add_view(title, type, *s);
551 void MainWindow::on_focus_changed()
553 shared_ptr<views::ViewBase> view = get_active_view();
556 for (shared_ptr<Session> session : sessions_) {
557 if (session->has_view(view)) {
558 if (session != last_focused_session_) {
559 // Activate correct tab if necessary
560 shared_ptr<Session> tab_session = get_tab_session(
561 session_selector_.currentIndex());
562 if (tab_session != session)
563 session_selector_.setCurrentWidget(
564 session_windows_.at(session));
566 on_focused_session_changed(session);
574 if (sessions_.empty())
575 setWindowTitle(WindowTitle);
578 void MainWindow::on_focused_session_changed(shared_ptr<Session> session)
580 last_focused_session_ = session;
582 setWindowTitle(session->name() + " - " + WindowTitle);
584 // Update the state of the run/stop button, too
585 on_capture_state_changed(session.get());
588 void MainWindow::on_new_session_clicked()
593 void MainWindow::on_run_stop_clicked()
595 shared_ptr<Session> session = last_focused_session_;
600 switch (session->get_capture_state()) {
601 case Session::Stopped:
602 session->start_capture([&](QString message) {
603 session_error("Capture failed", message); });
605 case Session::AwaitingTrigger:
606 case Session::Running:
607 session->stop_capture();
612 void MainWindow::on_settings_clicked()
614 dialogs::Settings dlg;
618 void MainWindow::on_session_name_changed()
620 // Update the corresponding dock widget's name(s)
621 Session *session = qobject_cast<Session*>(QObject::sender());
624 for (shared_ptr<views::ViewBase> view : session->views()) {
625 // Get the dock that contains the view
626 for (auto entry : view_docks_)
627 if (entry.second == view) {
628 entry.first->setObjectName(session->name());
629 entry.first->setWindowTitle(session->name());
633 // Update the tab widget by finding the main window and the tab from that
634 for (auto entry : session_windows_)
635 if (entry.first.get() == session) {
636 QMainWindow *window = entry.second;
637 const int index = session_selector_.indexOf(window);
638 session_selector_.setTabText(index, session->name());
641 // Refresh window title if the affected session has focus
642 if (session == last_focused_session_.get())
643 setWindowTitle(session->name() + " - " + WindowTitle);
646 void MainWindow::on_capture_state_changed(QObject *obj)
648 Session *caller = qobject_cast<Session*>(obj);
650 // Ignore if caller is not the currently focused session
651 // unless there is only one session
652 if ((sessions_.size() > 1) && (caller != last_focused_session_.get()))
655 int state = caller->get_capture_state();
657 const QIcon *icons[] = {&icon_grey_, &icon_red_, &icon_green_};
658 run_stop_button_->setIcon(*icons[state]);
659 run_stop_button_->setText((state == pv::Session::Stopped) ?
660 tr("Run") : tr("Stop"));
663 void MainWindow::on_new_view(Session *session)
665 // We get a pointer and need a reference
666 for (std::shared_ptr<Session> s : sessions_)
667 if (s.get() == session)
668 add_view(session->name(), views::ViewTypeTrace, *s);
671 void MainWindow::on_view_close_clicked()
673 // Find the dock widget that contains the close button that was clicked
674 QObject *w = QObject::sender();
675 QDockWidget *dock = nullptr;
678 dock = qobject_cast<QDockWidget*>(w);
684 // Get the view contained in the dock widget
685 shared_ptr<views::ViewBase> view;
687 for (auto entry : view_docks_)
688 if (entry.first == dock)
691 // Deregister the view
692 for (shared_ptr<Session> session : sessions_) {
693 if (!session->has_view(view))
696 // Also destroy the entire session if its main view is closing...
697 if (view == session->main_view()) {
698 // ...but only if data is saved or the user confirms closing
699 if (session->data_saved() || (QMessageBox::question(this, tr("Confirmation"),
700 tr("This session contains unsaved data. Close it anyway?"),
701 QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes))
702 remove_session(session);
705 // All other views can be closed at any time as no data will be lost
710 void MainWindow::on_tab_changed(int index)
712 shared_ptr<Session> session = get_tab_session(index);
715 on_focused_session_changed(session);
718 void MainWindow::on_tab_close_requested(int index)
720 shared_ptr<Session> session = get_tab_session(index);
724 if (session->data_saved() || (QMessageBox::question(this, tr("Confirmation"),
725 tr("This session contains unsaved data. Close it anyway?"),
726 QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes))
727 remove_session(session);
730 void MainWindow::on_view_sticky_scrolling_shortcut()
732 shared_ptr<views::ViewBase> viewbase = get_active_view();
733 views::TraceView::View* view =
734 qobject_cast<views::TraceView::View*>(viewbase.get());
736 view->toggle_sticky_scrolling();
739 void MainWindow::on_view_coloured_bg_shortcut()
741 GlobalSettings settings;
743 bool state = settings.value(GlobalSettings::Key_View_ColouredBG).toBool();
744 settings.setValue(GlobalSettings::Key_View_ColouredBG, !state);
747 void MainWindow::on_settingViewColouredBg_changed(const QVariant new_value)
749 bool state = new_value.toBool();
751 for (auto entry : view_docks_) {
752 shared_ptr<views::ViewBase> viewbase = entry.second;
754 // Only trace views have this setting
755 views::TraceView::View* view =
756 qobject_cast<views::TraceView::View*>(viewbase.get());
758 view->enable_coloured_bg(state);
762 void MainWindow::on_actionAbout_triggered()
764 dialogs::About dlg(device_manager_.context(), this);
768 void MainWindow::on_close_current_tab()
770 int tab = session_selector_.currentIndex();
772 on_tab_close_requested(tab);