MainWindow, View::View: Fix two memory errors reported by valgrind
[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, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19  */
20
21 #include <cassert>
22
23 #ifdef ENABLE_DECODE
24 #include <libsigrokdecode/libsigrokdecode.h>
25 #endif
26
27 #include <algorithm>
28 #include <iterator>
29
30 #include <QAction>
31 #include <QApplication>
32 #include <QCloseEvent>
33 #include <QDockWidget>
34 #include <QHBoxLayout>
35 #include <QMessageBox>
36 #include <QSettings>
37 #include <QWidget>
38
39 #include "mainwindow.hpp"
40
41 #include "devicemanager.hpp"
42 #include "util.hpp"
43 #include "devices/hardwaredevice.hpp"
44 #include "dialogs/about.hpp"
45 #include "toolbars/mainbar.hpp"
46 #include "view/view.hpp"
47 #include "views/trace/standardbar.hpp"
48
49 #include <stdint.h>
50 #include <stdarg.h>
51 #include <libsigrokcxx/libsigrokcxx.hpp>
52
53 using std::dynamic_pointer_cast;
54 using std::list;
55 using std::make_shared;
56 using std::map;
57 using std::shared_ptr;
58 using std::string;
59
60 namespace pv {
61
62 namespace view {
63 class ViewItem;
64 }
65
66 using toolbars::MainBar;
67
68 const QString MainWindow::WindowTitle = tr("PulseView");
69
70 MainWindow::MainWindow(DeviceManager &device_manager,
71         string open_file_name, string open_file_format,
72         QWidget *parent) :
73         QMainWindow(parent),
74         device_manager_(device_manager),
75         session_selector_(this),
76         session_state_mapper_(this),
77         action_view_sticky_scrolling_(new QAction(this)),
78         action_view_coloured_bg_(new QAction(this)),
79         action_about_(new QAction(this)),
80         icon_red_(":/icons/status-red.svg"),
81         icon_green_(":/icons/status-green.svg"),
82         icon_grey_(":/icons/status-grey.svg")
83 {
84         qRegisterMetaType<util::Timestamp>("util::Timestamp");
85
86         setup_ui();
87         restore_ui_settings();
88
89         if (!open_file_name.empty()) {
90                 shared_ptr<Session> session = add_session();
91                 session->load_init_file(open_file_name, open_file_format);
92         }
93
94         // Add empty default session if there aren't any sessions
95         if (sessions_.size() == 0) {
96                 shared_ptr<Session> session = add_session();
97
98                 map<string, string> dev_info;
99                 shared_ptr<devices::HardwareDevice> other_device, demo_device;
100
101                 // Use any available device that's not demo
102                 for (shared_ptr<devices::HardwareDevice> dev : device_manager_.devices()) {
103                         if (dev->hardware_device()->driver()->name() == "demo") {
104                                 demo_device = dev;
105                         } else {
106                                 other_device = dev;
107                         }
108                 }
109
110                 // ...and if there isn't any, just use demo then
111                 session->select_device(other_device ? other_device : demo_device);
112         }
113 }
114
115 MainWindow::~MainWindow()
116 {
117         while (!sessions_.empty())
118                 remove_session(sessions_.front());
119 }
120
121 QAction* MainWindow::action_view_sticky_scrolling() const
122 {
123         return action_view_sticky_scrolling_;
124 }
125
126 QAction* MainWindow::action_view_coloured_bg() const
127 {
128         return action_view_coloured_bg_;
129 }
130
131 QAction* MainWindow::action_about() const
132 {
133         return action_about_;
134 }
135
136 shared_ptr<views::ViewBase> MainWindow::get_active_view() const
137 {
138         // If there's only one view, use it...
139         if (view_docks_.size() == 1)
140                 return view_docks_.begin()->second;
141
142         // ...otherwise find the dock widget the widget with focus is contained in
143         QObject *w = QApplication::focusWidget();
144         QDockWidget *dock = 0;
145
146         while (w) {
147             dock = qobject_cast<QDockWidget*>(w);
148             if (dock)
149                 break;
150             w = w->parent();
151         }
152
153         // Get the view contained in the dock widget
154         for (auto entry : view_docks_)
155                 if (entry.first == dock)
156                         return entry.second;
157
158         return nullptr;
159 }
160
161 shared_ptr<views::ViewBase> MainWindow::add_view(const QString &title,
162         views::ViewType type, Session &session)
163 {
164         QMainWindow *main_window = nullptr;
165         for (auto entry : session_windows_)
166                 if (entry.first.get() == &session)
167                         main_window = entry.second;
168
169         assert(main_window);
170
171         if (type == views::ViewTypeTrace) {
172                 QDockWidget* dock = new QDockWidget(title, main_window);
173                 dock->setObjectName(title);
174                 main_window->addDockWidget(Qt::TopDockWidgetArea, dock);
175
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
179
180                 shared_ptr<views::TraceView::View> v =
181                         make_shared<views::TraceView::View>(session, dock_main);
182                 view_docks_[dock] = v;
183                 session.register_view(v);
184
185                 dock_main->setCentralWidget(v.get());
186                 dock->setWidget(dock_main);
187
188                 dock->setFeatures(QDockWidget::DockWidgetMovable |
189                         QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetClosable);
190
191                 QAbstractButton *close_btn =
192                         dock->findChildren<QAbstractButton*>
193                                 ("qt_dockwidget_closebutton").front();
194
195                 connect(close_btn, SIGNAL(clicked(bool)),
196                         this, SLOT(on_view_close_clicked()));
197
198                 if (type == views::ViewTypeTrace) {
199                         connect(&session, SIGNAL(trigger_event(util::Timestamp)),
200                                 qobject_cast<views::ViewBase*>(v.get()),
201                                 SLOT(trigger_event(util::Timestamp)));
202
203                         v->enable_sticky_scrolling(action_view_sticky_scrolling_->isChecked());
204                         v->enable_coloured_bg(action_view_coloured_bg_->isChecked());
205
206                         shared_ptr<MainBar> main_bar = session.main_bar();
207                         if (!main_bar) {
208                                 /* Initial view, create the main bar */
209                                 main_bar = make_shared<MainBar>(session, this, v.get());
210                                 dock_main->addToolBar(main_bar.get());
211                                 session.set_main_bar(main_bar);
212
213                                 connect(main_bar.get(), SIGNAL(new_view(Session*)),
214                                         this, SLOT(on_new_view(Session*)));
215
216                                 main_bar->action_view_show_cursors()->setChecked(v->cursors_shown());
217                         } else {
218                                 /* Additional view, create a standard bar */
219                                 pv::views::trace::StandardBar *standard_bar =
220                                         new pv::views::trace::StandardBar(session, this, v.get());
221                                 dock_main->addToolBar(standard_bar);
222
223                                 standard_bar->action_view_show_cursors()->setChecked(v->cursors_shown());
224                         }
225                 }
226
227                 return v;
228         }
229
230         return nullptr;
231 }
232
233 shared_ptr<Session> MainWindow::add_session()
234 {
235         static int last_session_id = 1;
236         QString name = tr("Untitled-%1").arg(last_session_id++);
237
238         shared_ptr<Session> session = make_shared<Session>(device_manager_, name);
239
240         connect(session.get(), SIGNAL(add_view(const QString&, views::ViewType, Session*)),
241                 this, SLOT(on_add_view(const QString&, views::ViewType, Session*)));
242         connect(session.get(), SIGNAL(name_changed()),
243                 this, SLOT(on_session_name_changed()));
244         session_state_mapper_.setMapping(session.get(), session.get());
245         connect(session.get(), SIGNAL(capture_state_changed(int)),
246                 &session_state_mapper_, SLOT(map()));
247
248         sessions_.push_back(session);
249
250         QMainWindow *window = new QMainWindow();
251         window->setWindowFlags(Qt::Widget);  // Remove Qt::Window flag
252         session_windows_[session] = window;
253
254         int index = session_selector_.addTab(window, name);
255         session_selector_.setCurrentIndex(index);
256         last_focused_session_ = session;
257
258         window->setDockNestingEnabled(true);
259
260         shared_ptr<views::ViewBase> main_view =
261                 add_view(name, views::ViewTypeTrace, *session);
262
263         return session;
264 }
265
266 void MainWindow::remove_session(shared_ptr<Session> session)
267 {
268         int h = new_session_button_->height();
269
270         for (shared_ptr<views::ViewBase> view : session->views()) {
271                 // Find the dock the view is contained in and remove it
272                 for (auto entry : view_docks_)
273                         if (entry.second == view) {
274                                 // Remove the view from the session
275                                 session->deregister_view(view);
276
277                                 // Remove the view from its parent; otherwise, Qt will
278                                 // call deleteLater() on it, which causes a double free
279                                 // since the shared_ptr in view_docks_ doesn't know
280                                 // that Qt keeps a pointer to the view around
281                                 entry.second->setParent(0);
282
283                                 // Remove this entry from the container and stop iterating.
284                                 view_docks_.erase(entry.first);
285                                 break;
286                         }
287         }
288
289         QMainWindow *window = session_windows_.at(session);
290         session_selector_.removeTab(session_selector_.indexOf(window));
291
292         session_windows_.erase(session);
293
294         if (last_focused_session_ == session)
295                 last_focused_session_.reset();
296
297         sessions_.remove_if([&](shared_ptr<Session> s) {
298                 return s == session; });
299
300         if (sessions_.empty()) {
301                 // When there are no more tabs, the height of the QTabWidget
302                 // drops to zero. We must prevent this to keep the static
303                 // widgets visible
304                 for (QWidget *w : static_tab_widget_->findChildren<QWidget*>())
305                         w->setMinimumHeight(h);
306
307                 int margin = static_tab_widget_->layout()->contentsMargins().bottom();
308                 static_tab_widget_->setMinimumHeight(h + 2 * margin);
309                 session_selector_.setMinimumHeight(h + 2 * margin);
310
311                 // Update the window title if there is no view left to
312                 // generate focus change events
313                 setWindowTitle(WindowTitle);
314         }
315 }
316
317 void MainWindow::setup_ui()
318 {
319         setObjectName(QString::fromUtf8("MainWindow"));
320
321         setCentralWidget(&session_selector_);
322
323         // Set the window icon
324         QIcon icon;
325         icon.addFile(QString(":/icons/sigrok-logo-notext.png"));
326         setWindowIcon(icon);
327
328         action_view_sticky_scrolling_->setCheckable(true);
329         action_view_sticky_scrolling_->setChecked(true);
330         action_view_sticky_scrolling_->setShortcut(QKeySequence(Qt::Key_S));
331         action_view_sticky_scrolling_->setObjectName(
332                 QString::fromUtf8("actionViewStickyScrolling"));
333         action_view_sticky_scrolling_->setText(tr("&Sticky Scrolling"));
334
335         action_view_coloured_bg_->setCheckable(true);
336         action_view_coloured_bg_->setChecked(true);
337         action_view_coloured_bg_->setShortcut(QKeySequence(Qt::Key_B));
338         action_view_coloured_bg_->setObjectName(
339                 QString::fromUtf8("actionViewColouredBg"));
340         action_view_coloured_bg_->setText(tr("Use &Coloured Backgrounds"));
341
342         action_about_->setObjectName(QString::fromUtf8("actionAbout"));
343         action_about_->setToolTip(tr("&About..."));
344
345         // Set up the tab area
346         new_session_button_ = new QToolButton();
347         new_session_button_->setIcon(QIcon::fromTheme("document-new",
348                 QIcon(":/icons/document-new.png")));
349         new_session_button_->setToolTip(tr("Create New Session"));
350         new_session_button_->setAutoRaise(true);
351
352         run_stop_button_ = new QToolButton();
353         run_stop_button_->setAutoRaise(true);
354         run_stop_button_->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
355         run_stop_button_->setShortcut(QKeySequence(Qt::Key_Space));
356         run_stop_button_->setToolTip(tr("Start/Stop Acquisition"));
357
358         settings_button_ = new QToolButton();
359         settings_button_->setIcon(QIcon::fromTheme("configure",
360                 QIcon(":/icons/configure.png")));
361         settings_button_->setToolTip(tr("Settings"));
362         settings_button_->setAutoRaise(true);
363
364         QFrame *separator1 = new QFrame();
365         separator1->setFrameStyle(QFrame::VLine | QFrame::Raised);
366         QFrame *separator2 = new QFrame();
367         separator2->setFrameStyle(QFrame::VLine | QFrame::Raised);
368
369         QHBoxLayout* layout = new QHBoxLayout();
370         layout->setContentsMargins(2, 2, 2, 2);
371         layout->addWidget(new_session_button_);
372         layout->addWidget(separator1);
373         layout->addWidget(run_stop_button_);
374         layout->addWidget(separator2);
375         layout->addWidget(settings_button_);
376
377         static_tab_widget_ = new QWidget();
378         static_tab_widget_->setLayout(layout);
379
380         session_selector_.setCornerWidget(static_tab_widget_, Qt::TopLeftCorner);
381         session_selector_.setTabsClosable(true);
382
383         connect(new_session_button_, SIGNAL(clicked(bool)),
384                 this, SLOT(on_new_session_clicked()));
385         connect(run_stop_button_, SIGNAL(clicked(bool)),
386                 this, SLOT(on_run_stop_clicked()));
387         connect(&session_state_mapper_, SIGNAL(mapped(QObject*)),
388                 this, SLOT(on_capture_state_changed(QObject*)));
389
390         connect(&session_selector_, SIGNAL(tabCloseRequested(int)),
391                 this, SLOT(on_tab_close_requested(int)));
392         connect(&session_selector_, SIGNAL(currentChanged(int)),
393                 this, SLOT(on_tab_changed(int)));
394
395
396         connect(static_cast<QApplication *>(QCoreApplication::instance()),
397                 SIGNAL(focusChanged(QWidget*, QWidget*)),
398                 this, SLOT(on_focus_changed()));
399 }
400
401 void MainWindow::save_ui_settings()
402 {
403         QSettings settings;
404         int id = 0;
405
406         settings.beginGroup("MainWindow");
407         settings.setValue("state", saveState());
408         settings.setValue("geometry", saveGeometry());
409         settings.endGroup();
410
411         for (shared_ptr<Session> session : sessions_) {
412                 // Ignore sessions using the demo device or no device at all
413                 if (session->device()) {
414                         shared_ptr<devices::HardwareDevice> device =
415                                 dynamic_pointer_cast< devices::HardwareDevice >
416                                 (session->device());
417
418                         if (device &&
419                                 device->hardware_device()->driver()->name() == "demo")
420                                 continue;
421
422                         settings.beginGroup("Session" + QString::number(id++));
423                         settings.remove("");  // Remove all keys in this group
424                         session->save_settings(settings);
425                         settings.endGroup();
426                 }
427         }
428
429         settings.setValue("sessions", id);
430 }
431
432 void MainWindow::restore_ui_settings()
433 {
434         QSettings settings;
435         int i, session_count;
436
437         settings.beginGroup("MainWindow");
438
439         if (settings.contains("geometry")) {
440                 restoreGeometry(settings.value("geometry").toByteArray());
441                 restoreState(settings.value("state").toByteArray());
442         } else
443                 resize(1000, 720);
444
445         settings.endGroup();
446
447         session_count = settings.value("sessions", 0).toInt();
448
449         for (i = 0; i < session_count; i++) {
450                 settings.beginGroup("Session" + QString::number(i));
451                 shared_ptr<Session> session = add_session();
452                 session->restore_settings(settings);
453                 settings.endGroup();
454         }
455 }
456
457 std::shared_ptr<Session> MainWindow::get_tab_session(int index) const
458 {
459         // Find the session that belongs to the tab's main window
460         for (auto entry : session_windows_)
461                 if (entry.second == session_selector_.widget(index))
462                         return entry.first;
463
464         return nullptr;
465 }
466
467 void MainWindow::closeEvent(QCloseEvent *event)
468 {
469         save_ui_settings();
470         event->accept();
471 }
472
473 QMenu* MainWindow::createPopupMenu()
474 {
475         return nullptr;
476 }
477
478 bool MainWindow::restoreState(const QByteArray &state, int version)
479 {
480         (void)state;
481         (void)version;
482
483         // Do nothing. We don't want Qt to handle this, or else it
484         // will try to restore all the dock widgets and create havoc.
485
486         return false;
487 }
488
489 void MainWindow::session_error(const QString text, const QString info_text)
490 {
491         QMetaObject::invokeMethod(this, "show_session_error",
492                 Qt::QueuedConnection, Q_ARG(QString, text),
493                 Q_ARG(QString, info_text));
494 }
495
496 void MainWindow::show_session_error(const QString text, const QString info_text)
497 {
498         QMessageBox msg(this);
499         msg.setText(text);
500         msg.setInformativeText(info_text);
501         msg.setStandardButtons(QMessageBox::Ok);
502         msg.setIcon(QMessageBox::Warning);
503         msg.exec();
504 }
505
506 void MainWindow::on_add_view(const QString &title, views::ViewType type,
507         Session *session)
508 {
509         // We get a pointer and need a reference
510         for (std::shared_ptr<Session> s : sessions_)
511                 if (s.get() == session)
512                         add_view(title, type, *s);
513 }
514
515 void MainWindow::on_focus_changed()
516 {
517         shared_ptr<views::ViewBase> view = get_active_view();
518
519         if (view) {
520                 for (shared_ptr<Session> session : sessions_) {
521                         if (session->has_view(view)) {
522                                 if (session != last_focused_session_) {
523                                         // Activate correct tab if necessary
524                                         shared_ptr<Session> tab_session = get_tab_session(
525                                                 session_selector_.currentIndex());
526                                         if (tab_session != session)
527                                                 session_selector_.setCurrentWidget(
528                                                         session_windows_.at(session));
529
530                                         on_focused_session_changed(session);
531                                 }
532
533                                 break;
534                         }
535                 }
536         }
537
538         if (sessions_.empty())
539                 setWindowTitle(WindowTitle);
540 }
541
542 void MainWindow::on_focused_session_changed(shared_ptr<Session> session)
543 {
544         last_focused_session_ = session;
545
546         setWindowTitle(session->name() + " - " + WindowTitle);
547
548         // Update the state of the run/stop button, too
549         on_capture_state_changed(session.get());
550 }
551
552 void MainWindow::on_new_session_clicked()
553 {
554         add_session();
555 }
556
557 void MainWindow::on_run_stop_clicked()
558 {
559         shared_ptr<Session> session = last_focused_session_;
560
561         if (!session)
562                 return;
563
564         switch (session->get_capture_state()) {
565         case Session::Stopped:
566                 session->start_capture([&](QString message) {
567                         session_error("Capture failed", message); });
568                 break;
569         case Session::AwaitingTrigger:
570         case Session::Running:
571                 session->stop_capture();
572                 break;
573         }
574 }
575
576 void MainWindow::on_session_name_changed()
577 {
578         // Update the corresponding dock widget's name(s)
579         Session *session = qobject_cast<Session*>(QObject::sender());
580         assert(session);
581
582         for (shared_ptr<views::ViewBase> view : session->views()) {
583                 // Get the dock that contains the view
584                 for (auto entry : view_docks_)
585                         if (entry.second == view) {
586                                 entry.first->setObjectName(session->name());
587                                 entry.first->setWindowTitle(session->name());
588                         }
589         }
590
591         // Update the tab widget by finding the main window and the tab from that
592         for (auto entry : session_windows_)
593                 if (entry.first.get() == session) {
594                         QMainWindow *window = entry.second;
595                         const int index = session_selector_.indexOf(window);
596                         session_selector_.setTabText(index, session->name());
597                 }
598
599         // Refresh window title if the affected session has focus
600         if (session == last_focused_session_.get())
601                 setWindowTitle(session->name() + " - " + WindowTitle);
602 }
603
604 void MainWindow::on_capture_state_changed(QObject *obj)
605 {
606         Session *caller = qobject_cast<Session*>(obj);
607
608         // Ignore if caller is not the currently focused session
609         // unless there is only one session
610         if ((sessions_.size() > 1) && (caller != last_focused_session_.get()))
611                 return;
612
613         int state = caller->get_capture_state();
614
615         const QIcon *icons[] = {&icon_grey_, &icon_red_, &icon_green_};
616         run_stop_button_->setIcon(*icons[state]);
617         run_stop_button_->setText((state == pv::Session::Stopped) ?
618                 tr("Run") : tr("Stop"));
619 }
620
621 void MainWindow::on_new_view(Session *session)
622 {
623         // We get a pointer and need a reference
624         for (std::shared_ptr<Session> s : sessions_)
625                 if (s.get() == session)
626                         add_view(session->name(), views::ViewTypeTrace, *s);
627 }
628
629 void MainWindow::on_view_close_clicked()
630 {
631         // Find the dock widget that contains the close button that was clicked
632         QObject *w = QObject::sender();
633         QDockWidget *dock = 0;
634
635         while (w) {
636             dock = qobject_cast<QDockWidget*>(w);
637             if (dock)
638                 break;
639             w = w->parent();
640         }
641
642         // Get the view contained in the dock widget
643         shared_ptr<views::ViewBase> view;
644
645         for (auto entry : view_docks_)
646                 if (entry.first == dock)
647                         view = entry.second;
648
649         // Deregister the view
650         for (shared_ptr<Session> session : sessions_) {
651                 if (!session->has_view(view))
652                         continue;
653
654                 // Also destroy the entire session if its main view is closing
655                 if (view == session->main_view()) {
656                         remove_session(session);
657                         break;
658                 } else
659                         session->deregister_view(view);
660         }
661 }
662
663 void MainWindow::on_tab_changed(int index)
664 {
665         shared_ptr<Session> session = get_tab_session(index);
666
667         if (session)
668                 on_focused_session_changed(session);
669 }
670
671 void MainWindow::on_tab_close_requested(int index)
672 {
673         // TODO Ask user if this is intended in case data is unsaved
674
675         shared_ptr<Session> session = get_tab_session(index);
676
677         if (session)
678                 remove_session(session);
679 }
680
681 void MainWindow::on_actionViewStickyScrolling_triggered()
682 {
683         shared_ptr<views::ViewBase> viewbase = get_active_view();
684         views::TraceView::View* view =
685                 qobject_cast<views::TraceView::View*>(viewbase.get());
686         if (view)
687                 view->enable_sticky_scrolling(action_view_sticky_scrolling_->isChecked());
688 }
689
690 void MainWindow::on_actionViewColouredBg_triggered()
691 {
692         shared_ptr<views::ViewBase> viewbase = get_active_view();
693         views::TraceView::View* view =
694                         qobject_cast<views::TraceView::View*>(viewbase.get());
695         if (view)
696                 view->enable_coloured_bg(action_view_coloured_bg_->isChecked());
697 }
698
699 void MainWindow::on_actionAbout_triggered()
700 {
701         dialogs::About dlg(device_manager_.context(), this);
702         dlg.exec();
703 }
704
705 } // namespace pv