ViewItemPaintParams: Added vertical layout information
[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 <QButtonGroup>
33 #include <QCloseEvent>
34 #include <QFileDialog>
35 #include <QMessageBox>
36 #include <QMenu>
37 #include <QMenuBar>
38 #include <QSettings>
39 #include <QStatusBar>
40 #include <QVBoxLayout>
41 #include <QWidget>
42
43 #include "mainwindow.hpp"
44
45 #include "devicemanager.hpp"
46 #include "dialogs/about.hpp"
47 #include "dialogs/connect.hpp"
48 #include "dialogs/storeprogress.hpp"
49 #include "toolbars/samplingbar.hpp"
50 #include "view/logicsignal.hpp"
51 #include "view/view.hpp"
52 #ifdef ENABLE_DECODE
53 #include "widgets/decodermenu.hpp"
54 #endif
55
56 #include <inttypes.h>
57 #include <stdint.h>
58 #include <stdarg.h>
59 #include <glib.h>
60 #include <libsigrok/libsigrok.hpp>
61
62 using std::list;
63 using std::map;
64 using std::shared_ptr;
65 using std::string;
66
67 using sigrok::Device;
68 using sigrok::Error;
69 using sigrok::HardwareDevice;
70
71 namespace pv {
72
73 namespace view {
74 class ViewItem;
75 }
76
77 const char *MainWindow::SettingOpenDirectory = "MainWindow/OpenDirectory";
78 const char *MainWindow::SettingSaveDirectory = "MainWindow/SaveDirectory";
79
80 MainWindow::MainWindow(DeviceManager &device_manager,
81         const char *open_file_name,
82         QWidget *parent) :
83         QMainWindow(parent),
84         device_manager_(device_manager),
85         session_(device_manager)
86 {
87         setup_ui();
88         restore_ui_settings();
89         if (open_file_name) {
90                 const QString s(QString::fromUtf8(open_file_name));
91                 QMetaObject::invokeMethod(this, "load_file",
92                         Qt::QueuedConnection,
93                         Q_ARG(QString, s));
94         }
95 }
96
97 void MainWindow::run_stop()
98 {
99         switch(session_.get_capture_state()) {
100         case Session::Stopped:
101                 session_.start_capture([&](QString message) {
102                         session_error("Capture failed", message); });
103                 break;
104
105         case Session::AwaitingTrigger:
106         case Session::Running:
107                 session_.stop_capture();
108                 break;
109         }
110 }
111
112 void MainWindow::select_device(shared_ptr<Device> device)
113 {
114         try {
115                 session_.set_device(device);
116         } catch(const QString &e) {
117                 QMessageBox msg(this);
118                 msg.setText(e);
119                 msg.setInformativeText(tr("Failed to Select Device"));
120                 msg.setStandardButtons(QMessageBox::Ok);
121                 msg.setIcon(QMessageBox::Warning);
122                 msg.exec();
123         }
124 }
125
126 void MainWindow::setup_ui()
127 {
128         setObjectName(QString::fromUtf8("MainWindow"));
129
130         // Set the window icon
131         QIcon icon;
132         icon.addFile(QString::fromUtf8(":/icons/sigrok-logo-notext.png"),
133                 QSize(), QIcon::Normal, QIcon::Off);
134         setWindowIcon(icon);
135
136         // Setup the central widget
137         central_widget_ = new QWidget(this);
138         vertical_layout_ = new QVBoxLayout(central_widget_);
139         vertical_layout_->setSpacing(6);
140         vertical_layout_->setContentsMargins(0, 0, 0, 0);
141         setCentralWidget(central_widget_);
142
143         view_ = new pv::view::View(session_, this);
144
145         vertical_layout_->addWidget(view_);
146
147         // Setup the menu bar
148         QMenuBar *const menu_bar = new QMenuBar(this);
149         menu_bar->setGeometry(QRect(0, 0, 400, 25));
150
151         // File Menu
152         QMenu *const menu_file = new QMenu;
153         menu_file->setTitle(tr("&File"));
154
155         QAction *const action_open = new QAction(this);
156         action_open->setText(tr("&Open..."));
157         action_open->setIcon(QIcon::fromTheme("document-open",
158                 QIcon(":/icons/document-open.png")));
159         action_open->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_O));
160         action_open->setObjectName(QString::fromUtf8("actionOpen"));
161         menu_file->addAction(action_open);
162
163         QAction *const action_save_as = new QAction(this);
164         action_save_as->setText(tr("&Save As..."));
165         action_save_as->setIcon(QIcon::fromTheme("document-save-as",
166                 QIcon(":/icons/document-save-as.png")));
167         action_save_as->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_S));
168         action_save_as->setObjectName(QString::fromUtf8("actionSaveAs"));
169         menu_file->addAction(action_save_as);
170
171         menu_file->addSeparator();
172
173         QAction *const action_connect = new QAction(this);
174         action_connect->setText(tr("&Connect to Device..."));
175         action_connect->setObjectName(QString::fromUtf8("actionConnect"));
176         menu_file->addAction(action_connect);
177
178         menu_file->addSeparator();
179
180         QAction *action_quit = new QAction(this);
181         action_quit->setText(tr("&Quit"));
182         action_quit->setIcon(QIcon::fromTheme("application-exit",
183                 QIcon(":/icons/application-exit.png")));
184         action_quit->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
185         action_quit->setObjectName(QString::fromUtf8("actionQuit"));
186         menu_file->addAction(action_quit);
187
188         // View Menu
189         QMenu *menu_view = new QMenu;
190         menu_view->setTitle(tr("&View"));
191
192         QAction *const action_view_zoom_in = new QAction(this);
193         action_view_zoom_in->setText(tr("Zoom &In"));
194         action_view_zoom_in->setIcon(QIcon::fromTheme("zoom-in",
195                 QIcon(":/icons/zoom-in.png")));
196         // simply using Qt::Key_Plus shows no + in the menu
197         action_view_zoom_in->setShortcut(QKeySequence::ZoomIn);
198         action_view_zoom_in->setObjectName(
199                 QString::fromUtf8("actionViewZoomIn"));
200         menu_view->addAction(action_view_zoom_in);
201
202         QAction *const action_view_zoom_out = new QAction(this);
203         action_view_zoom_out->setText(tr("Zoom &Out"));
204         action_view_zoom_out->setIcon(QIcon::fromTheme("zoom-out",
205                 QIcon(":/icons/zoom-out.png")));
206         action_view_zoom_out->setShortcut(QKeySequence::ZoomOut);
207         action_view_zoom_out->setObjectName(
208                 QString::fromUtf8("actionViewZoomOut"));
209         menu_view->addAction(action_view_zoom_out);
210
211         QAction *const action_view_zoom_fit = new QAction(this);
212         action_view_zoom_fit->setText(tr("Zoom to &Fit"));
213         action_view_zoom_fit->setIcon(QIcon::fromTheme("zoom-fit",
214                 QIcon(":/icons/zoom-fit.png")));
215         action_view_zoom_fit->setShortcut(QKeySequence(Qt::Key_F));
216         action_view_zoom_fit->setObjectName(
217                 QString::fromUtf8("actionViewZoomFit"));
218         menu_view->addAction(action_view_zoom_fit);
219
220         QAction *const action_view_zoom_one_to_one = new QAction(this);
221         action_view_zoom_one_to_one->setText(tr("Zoom to &One-to-One"));
222         action_view_zoom_one_to_one->setIcon(QIcon::fromTheme("zoom-original",
223                 QIcon(":/icons/zoom-original.png")));
224         action_view_zoom_one_to_one->setShortcut(QKeySequence(Qt::Key_O));
225         action_view_zoom_one_to_one->setObjectName(
226                 QString::fromUtf8("actionViewZoomOneToOne"));
227         menu_view->addAction(action_view_zoom_one_to_one);
228
229         menu_view->addSeparator();
230
231         QAction *action_view_show_cursors = new QAction(this);
232         action_view_show_cursors->setCheckable(true);
233         action_view_show_cursors->setChecked(view_->cursors_shown());
234         action_view_show_cursors->setShortcut(QKeySequence(Qt::Key_C));
235         action_view_show_cursors->setObjectName(
236                 QString::fromUtf8("actionViewShowCursors"));
237         action_view_show_cursors->setText(tr("Show &Cursors"));
238         menu_view->addAction(action_view_show_cursors);
239
240         // Decoders Menu
241 #ifdef ENABLE_DECODE
242         QMenu *const menu_decoders = new QMenu;
243         menu_decoders->setTitle(tr("&Decoders"));
244
245         pv::widgets::DecoderMenu *const menu_decoders_add =
246                 new pv::widgets::DecoderMenu(menu_decoders, true);
247         menu_decoders_add->setTitle(tr("&Add"));
248         connect(menu_decoders_add, SIGNAL(decoder_selected(srd_decoder*)),
249                 this, SLOT(add_decoder(srd_decoder*)));
250
251         menu_decoders->addMenu(menu_decoders_add);
252 #endif
253
254         // Help Menu
255         QMenu *const menu_help = new QMenu;
256         menu_help->setTitle(tr("&Help"));
257
258         QAction *const action_about = new QAction(this);
259         action_about->setObjectName(QString::fromUtf8("actionAbout"));
260         action_about->setText(tr("&About..."));
261         menu_help->addAction(action_about);
262
263         menu_bar->addAction(menu_file->menuAction());
264         menu_bar->addAction(menu_view->menuAction());
265 #ifdef ENABLE_DECODE
266         menu_bar->addAction(menu_decoders->menuAction());
267 #endif
268         menu_bar->addAction(menu_help->menuAction());
269
270         setMenuBar(menu_bar);
271         QMetaObject::connectSlotsByName(this);
272
273         // Setup the toolbar
274         QToolBar *const toolbar = new QToolBar(tr("Main Toolbar"), this);
275         toolbar->setObjectName(QString::fromUtf8("MainToolbar"));
276         toolbar->addAction(action_open);
277         toolbar->addAction(action_save_as);
278         toolbar->addSeparator();
279         toolbar->addAction(action_view_zoom_in);
280         toolbar->addAction(action_view_zoom_out);
281         toolbar->addAction(action_view_zoom_fit);
282         toolbar->addAction(action_view_zoom_one_to_one);
283         addToolBar(toolbar);
284
285         // Setup the sampling bar
286         sampling_bar_ = new toolbars::SamplingBar(session_, *this);
287
288         // Populate the device list and select the initially selected device
289         update_device_list();
290
291         addToolBar(sampling_bar_);
292
293         // Set the title
294         setWindowTitle(tr("PulseView"));
295
296         // Setup session_ events
297         connect(&session_, SIGNAL(capture_state_changed(int)), this,
298                 SLOT(capture_state_changed(int)));
299         connect(&session_, SIGNAL(device_selected()), this,
300                 SLOT(device_selected()));
301 }
302
303 void MainWindow::save_ui_settings()
304 {
305         QSettings settings;
306
307         map<string, string> dev_info;
308         list<string> key_list;
309
310         settings.beginGroup("MainWindow");
311         settings.setValue("state", saveState());
312         settings.setValue("geometry", saveGeometry());
313         settings.endGroup();
314
315         if (session_.device()) {
316                 settings.beginGroup("Device");
317                 key_list.push_back("vendor");
318                 key_list.push_back("model");
319                 key_list.push_back("version");
320                 key_list.push_back("serial_num");
321                 key_list.push_back("connection_id");
322
323                 dev_info = device_manager_.get_device_info(
324                         session_.device());
325
326                 for (string key : key_list) {
327
328                         if (dev_info.count(key))
329                                 settings.setValue(QString::fromUtf8(key.c_str()),
330                                                 QString::fromUtf8(dev_info.at(key).c_str()));
331                         else
332                                 settings.remove(QString::fromUtf8(key.c_str()));
333                 }
334
335                 settings.endGroup();
336         }
337 }
338
339 void MainWindow::restore_ui_settings()
340 {
341         QSettings settings;
342
343         shared_ptr<HardwareDevice> device;
344
345         map<string, string> dev_info;
346         list<string> key_list;
347         string value;
348
349         settings.beginGroup("MainWindow");
350
351         if (settings.contains("geometry")) {
352                 restoreGeometry(settings.value("geometry").toByteArray());
353                 restoreState(settings.value("state").toByteArray());
354         } else
355                 resize(1000, 720);
356
357         settings.endGroup();
358
359         // Re-select last used device if possible.
360         settings.beginGroup("Device");
361         key_list.push_back("vendor");
362         key_list.push_back("model");
363         key_list.push_back("version");
364         key_list.push_back("serial_num");
365         key_list.push_back("connection_id");
366
367         for (string key : key_list) {
368                 if (!settings.contains(QString::fromUtf8(key.c_str())))
369                         continue;
370
371                 value = settings.value(QString::fromUtf8(key.c_str())).toString().toStdString();
372
373                 if (value.size() > 0)
374                         dev_info.insert(std::make_pair(key, value));
375         }
376
377         device = device_manager_.find_device_from_info(dev_info);
378
379         if (device) {
380                 select_device(device);
381                 update_device_list();
382         }
383
384         settings.endGroup();
385 }
386
387 void MainWindow::session_error(
388         const QString text, const QString info_text)
389 {
390         QMetaObject::invokeMethod(this, "show_session_error",
391                 Qt::QueuedConnection, Q_ARG(QString, text),
392                 Q_ARG(QString, info_text));
393 }
394
395 void MainWindow::update_device_list()
396 {
397         assert(sampling_bar_);
398
399         shared_ptr<Device> selected_device = session_.device();
400         list< shared_ptr<Device> > devices;
401
402         if (device_manager_.devices().size() == 0)
403                 return;
404
405         std::copy(device_manager_.devices().begin(),
406                 device_manager_.devices().end(), std::back_inserter(devices));
407
408         if (std::find(devices.begin(), devices.end(), selected_device) ==
409                 devices.end())
410                 devices.push_back(selected_device);
411         assert(selected_device);
412
413         sampling_bar_->set_device_list(devices, selected_device);
414 }
415
416 void MainWindow::closeEvent(QCloseEvent *event)
417 {
418         save_ui_settings();
419         event->accept();
420 }
421
422 void MainWindow::load_file(QString file_name)
423 {
424         const QString errorMessage(
425                 QString("Failed to load file %1").arg(file_name));
426         const QString infoMessage;
427
428         try {
429                 session_.set_file(file_name.toStdString());
430         } catch(Error e) {
431                 show_session_error(tr("Failed to load ") + file_name, e.what());
432                 session_.set_default_device();
433                 update_device_list();
434                 return;
435         }
436
437         update_device_list();
438
439         session_.start_capture([&, errorMessage, infoMessage](QString) {
440                 session_error(errorMessage, infoMessage); });
441 }
442
443 void MainWindow::show_session_error(
444         const QString text, const QString info_text)
445 {
446         QMessageBox msg(this);
447         msg.setText(text);
448         msg.setInformativeText(info_text);
449         msg.setStandardButtons(QMessageBox::Ok);
450         msg.setIcon(QMessageBox::Warning);
451         msg.exec();
452 }
453
454 void MainWindow::on_actionOpen_triggered()
455 {
456         QSettings settings;
457         const QString dir = settings.value(SettingOpenDirectory).toString();
458
459         // Show the dialog
460         const QString file_name = QFileDialog::getOpenFileName(
461                 this, tr("Open File"), dir, tr(
462                         "Sigrok Sessions (*.sr);;"
463                         "All Files (*.*)"));
464
465         if (!file_name.isEmpty()) {
466                 load_file(file_name);
467
468                 const QString abs_path = QFileInfo(file_name).absolutePath();
469                 settings.setValue(SettingOpenDirectory, abs_path);
470         }
471 }
472
473 void MainWindow::on_actionSaveAs_triggered()
474 {
475         using pv::dialogs::StoreProgress;
476
477         // Stop any currently running capture session
478         session_.stop_capture();
479
480         QSettings settings;
481         const QString dir = settings.value(SettingSaveDirectory).toString();
482
483         // Show the dialog
484         const QString file_name = QFileDialog::getSaveFileName(
485                 this, tr("Save File"), dir, tr("Sigrok Sessions (*.sr)"));
486
487         if (file_name.isEmpty())
488                 return;
489
490         const QString abs_path = QFileInfo(file_name).absolutePath();
491         settings.setValue(SettingSaveDirectory, abs_path);
492
493         StoreProgress *dlg = new StoreProgress(file_name, session_, this);
494         dlg->run();
495 }
496
497 void MainWindow::on_actionConnect_triggered()
498 {
499         // Stop any currently running capture session
500         session_.stop_capture();
501
502         dialogs::Connect dlg(this, device_manager_);
503
504         // If the user selected a device, select it in the device list. Select the
505         // current device otherwise.
506         if (dlg.exec())
507                 select_device(dlg.get_selected_device());
508
509         update_device_list();
510 }
511
512 void MainWindow::on_actionQuit_triggered()
513 {
514         close();
515 }
516
517 void MainWindow::on_actionViewZoomIn_triggered()
518 {
519         view_->zoom(1);
520 }
521
522 void MainWindow::on_actionViewZoomOut_triggered()
523 {
524         view_->zoom(-1);
525 }
526
527 void MainWindow::on_actionViewZoomFit_triggered()
528 {
529         view_->zoom_fit();
530 }
531
532 void MainWindow::on_actionViewZoomOneToOne_triggered()
533 {
534         view_->zoom_one_to_one();
535 }
536
537 void MainWindow::on_actionViewShowCursors_triggered()
538 {
539         assert(view_);
540
541         const bool show = !view_->cursors_shown();
542         if(show)
543                 view_->centre_cursors();
544
545         view_->show_cursors(show);
546 }
547
548 void MainWindow::on_actionAbout_triggered()
549 {
550         dialogs::About dlg(device_manager_.context(), this);
551         dlg.exec();
552 }
553
554 void MainWindow::add_decoder(srd_decoder *decoder)
555 {
556 #ifdef ENABLE_DECODE
557         assert(decoder);
558         session_.add_decoder(decoder);
559 #else
560         (void)decoder;
561 #endif
562 }
563
564 void MainWindow::capture_state_changed(int state)
565 {
566         sampling_bar_->set_capture_state((pv::Session::capture_state)state);
567 }
568
569 void MainWindow::device_selected()
570 {
571         // Set the title to include the device/file name
572         const shared_ptr<sigrok::Device> device = session_.device();
573         if (!device)
574                 return;
575
576         const string display_name = device_manager_.get_display_name(device);
577         setWindowTitle(tr("%1 - PulseView").arg(display_name.c_str()));
578 }
579
580 } // namespace pv