Rename ENABLE_GSTREAMERMM to ENABLE_FLOW.
[pulseview.git] / main.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> /* First, so we avoid a _POSIX_C_SOURCE warning. */
22 #endif
23
24 #include <cstdint>
25 #include <fstream>
26 #include <getopt.h>
27 #include <vector>
28
29 #ifdef ENABLE_FLOW
30 #include <gstreamermm.h>
31 #include <libsigrokflow/libsigrokflow.hpp>
32 #endif
33
34 #include <libsigrokcxx/libsigrokcxx.hpp>
35
36 #include <QCheckBox>
37 #include <QDebug>
38 #include <QFile>
39 #include <QFileInfo>
40 #include <QMessageBox>
41 #include <QSettings>
42 #include <QTextStream>
43
44 #include "config.h"
45
46 #ifdef ENABLE_SIGNALS
47 #include "signalhandler.hpp"
48 #endif
49
50 #ifdef ENABLE_STACKTRACE
51 #include <signal.h>
52 #include <boost/stacktrace.hpp>
53 #include <QStandardPaths>
54 #endif
55
56 #include "pv/application.hpp"
57 #include "pv/devicemanager.hpp"
58 #include "pv/globalsettings.hpp"
59 #include "pv/logging.hpp"
60 #include "pv/mainwindow.hpp"
61 #include "pv/session.hpp"
62 #include "pv/util.hpp"
63
64 #ifdef ANDROID
65 #include <libsigrokandroidutils/libsigrokandroidutils.h>
66 #include "android/assetreader.hpp"
67 #include "android/loghandler.hpp"
68 #endif
69
70 #ifdef _WIN32
71 #include <QtPlugin>
72 Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)
73 Q_IMPORT_PLUGIN(QSvgPlugin)
74 #endif
75
76 using std::exception;
77 using std::ifstream;
78 using std::ofstream;
79 using std::shared_ptr;
80 using std::string;
81
82 #if ENABLE_STACKTRACE
83 QString stacktrace_filename;
84
85 void signal_handler(int signum)
86 {
87         ::signal(signum, SIG_DFL);
88         boost::stacktrace::safe_dump_to(stacktrace_filename.toLocal8Bit().data());
89         ::raise(SIGABRT);
90 }
91
92 void process_stacktrace(QString temp_path)
93 {
94         const QString stacktrace_outfile = temp_path + "/pv_stacktrace.txt";
95
96         ifstream ifs(stacktrace_filename.toLocal8Bit().data());
97         ofstream ofs(stacktrace_outfile.toLocal8Bit().data(),
98                 ofstream::out | ofstream::trunc);
99
100         boost::stacktrace::stacktrace st =
101                 boost::stacktrace::stacktrace::from_dump(ifs);
102         ofs << st;
103
104         ofs.close();
105         ifs.close();
106
107         QFile f(stacktrace_outfile);
108         f.open(QFile::ReadOnly | QFile::Text);
109         QTextStream fs(&f);
110         QString stacktrace = fs.readAll();
111         stacktrace = stacktrace.trimmed().replace('\n', "<br />");
112
113         qDebug() << QObject::tr("Stack trace of previous crash:");
114         qDebug() << "---------------------------------------------------------";
115         // Note: qDebug() prints quotation marks for QString output, so we feed it char*
116         qDebug() << stacktrace.toLocal8Bit().data();
117         qDebug() << "---------------------------------------------------------";
118
119         f.close();
120
121         // Remove stack trace so we don't process it again the next time we run
122         QFile::remove(stacktrace_filename.toLocal8Bit().data());
123
124         // Show notification dialog if permitted
125         pv::GlobalSettings settings;
126         if (settings.value(pv::GlobalSettings::Key_Log_NotifyOfStacktrace).toBool()) {
127                 QCheckBox *cb = new QCheckBox(QObject::tr("Don't show this message again"));
128
129                 QMessageBox msgbox;
130                 msgbox.setText(QObject::tr("When %1 last crashed, it created a stack trace.\n" \
131                         "A human-readable form has been saved to disk and was written to " \
132                         "the log. You may access it from the settings dialog.").arg(PV_TITLE));
133                 msgbox.setIcon(QMessageBox::Icon::Information);
134                 msgbox.addButton(QMessageBox::Ok);
135                 msgbox.setCheckBox(cb);
136
137                 QObject::connect(cb, &QCheckBox::stateChanged, [](int state){
138                         pv::GlobalSettings settings;
139                         settings.setValue(pv::GlobalSettings::Key_Log_NotifyOfStacktrace,
140                                 !state); });
141
142                 msgbox.exec();
143         }
144 }
145 #endif
146
147 void usage()
148 {
149         fprintf(stdout,
150                 "Usage:\n"
151                 "  %s [OPTIONS] [FILE]\n"
152                 "\n"
153                 "Help Options:\n"
154                 "  -h, -?, --help                  Show help option\n"
155                 "\n"
156                 "Application Options:\n"
157                 "  -V, --version                   Show release version\n"
158                 "  -l, --loglevel                  Set libsigrok/libsigrokdecode loglevel\n"
159                 "  -d, --driver                    Specify the device driver to use\n"
160                 "  -D, --dont-scan                 Don't auto-scan for devices, use -d spec only\n"
161                 "  -i, --input-file                Load input from file\n"
162                 "  -I, --input-format              Input format\n"
163                 "  -c, --clean                     Don't restore previous sessions on startup\n"
164                 "\n", PV_BIN_NAME);
165 }
166
167 int main(int argc, char *argv[])
168 {
169         int ret = 0;
170         shared_ptr<sigrok::Context> context;
171         string open_file_format, driver;
172         vector<string> open_files;
173         bool restore_sessions = true;
174         bool do_scan = true;
175         bool show_version = false;
176
177 #ifdef ENABLE_FLOW
178         // Initialise gstreamermm. Must be called before any other GLib stuff.
179         Gst::init();
180 #endif
181
182         Application a(argc, argv);
183
184 #ifdef ANDROID
185         srau_init_environment();
186         pv::AndroidLogHandler::install_callbacks();
187         pv::AndroidAssetReader asset_reader;
188 #endif
189
190         // Parse arguments
191         while (true) {
192                 static const struct option long_options[] = {
193                         {"help", no_argument, nullptr, 'h'},
194                         {"version", no_argument, nullptr, 'V'},
195                         {"loglevel", required_argument, nullptr, 'l'},
196                         {"driver", required_argument, nullptr, 'd'},
197                         {"dont-scan", no_argument, nullptr, 'D'},
198                         {"input-file", required_argument, nullptr, 'i'},
199                         {"input-format", required_argument, nullptr, 'I'},
200                         {"clean", no_argument, nullptr, 'c'},
201                         {"log-to-stdout", no_argument, nullptr, 's'},
202                         {nullptr, 0, nullptr, 0}
203                 };
204
205                 const int c = getopt_long(argc, argv,
206                         "h?VDcl:d:i:I:", long_options, nullptr);
207                 if (c == -1)
208                         break;
209
210                 switch (c) {
211                 case 'h':
212                 case '?':
213                         usage();
214                         return 0;
215
216                 case 'V':
217                         show_version = true;
218                         break;
219
220                 case 'l':
221                 {
222                         const int loglevel = atoi(optarg);
223                         if (loglevel < 0 || loglevel > 5) {
224                                 qDebug() << "ERROR: invalid log level spec.";
225                                 break;
226                         }
227                         context->set_log_level(sigrok::LogLevel::get(loglevel));
228
229 #ifdef ENABLE_DECODE
230                         srd_log_loglevel_set(loglevel);
231 #endif
232
233                         if (loglevel >= 5) {
234                                 const QSettings settings;
235                                 qDebug() << "Settings:" << settings.fileName()
236                                         << "format" << settings.format();
237                         }
238                         break;
239                 }
240
241                 case 'd':
242                         driver = optarg;
243                         break;
244
245                 case 'D':
246                         do_scan = false;
247                         break;
248
249                 case 'i':
250                         open_files.emplace_back(optarg);
251                         break;
252
253                 case 'I':
254                         open_file_format = optarg;
255                         break;
256
257                 case 'c':
258                         restore_sessions = false;
259                         break;
260                 }
261         }
262         argc -= optind;
263         argv += optind;
264
265         for (int i = 0; i < argc; i++)
266                 open_files.emplace_back(argv[i]);
267
268         qRegisterMetaType<pv::util::Timestamp>("util::Timestamp");
269         qRegisterMetaType<uint64_t>("uint64_t");
270
271         // Prepare the global settings since logging needs them early on
272         pv::GlobalSettings settings;
273         settings.save_internal_defaults();
274         settings.set_defaults_where_needed();
275         settings.apply_theme();
276
277         pv::logging.init();
278
279         // Initialise libsigrok
280         context = sigrok::Context::create();
281         pv::Session::sr_context = context;
282
283 #if ENABLE_STACKTRACE
284         QString temp_path = QStandardPaths::standardLocations(
285                 QStandardPaths::TempLocation).at(0);
286         stacktrace_filename = temp_path + "/pv_stacktrace.dmp";
287         qDebug() << "Stack trace file is" << stacktrace_filename;
288
289         ::signal(SIGSEGV, &signal_handler);
290         ::signal(SIGABRT, &signal_handler);
291
292         if (QFileInfo::exists(stacktrace_filename))
293                 process_stacktrace(temp_path);
294 #endif
295
296 #ifdef ANDROID
297         context->set_resource_reader(&asset_reader);
298 #endif
299         do {
300
301 #ifdef ENABLE_DECODE
302                 // Initialise libsigrokdecode
303                 if (srd_init(nullptr) != SRD_OK) {
304                         qDebug() << "ERROR: libsigrokdecode init failed.";
305                         break;
306                 }
307
308                 // Load the protocol decoders
309                 srd_decoder_load_all();
310 #endif
311
312 #ifndef ENABLE_STACKTRACE
313                 try {
314 #endif
315
316                 // Create the device manager, initialise the drivers
317                 pv::DeviceManager device_manager(context, driver, do_scan);
318
319                 a.collect_version_info(context);
320                 if (show_version) {
321                         a.print_version_info();
322                 } else {
323                         // Initialise the main window
324                         pv::MainWindow w(device_manager);
325                         w.show();
326
327                         if (restore_sessions)
328                                 w.restore_sessions();
329
330                         if (open_files.empty())
331                                 w.add_default_session();
332                         else
333                                 for (string& open_file : open_files)
334                                         w.add_session_with_file(open_file, open_file_format);
335
336 #ifdef ENABLE_SIGNALS
337                         if (SignalHandler::prepare_signals()) {
338                                 SignalHandler *const handler = new SignalHandler(&w);
339                                 QObject::connect(handler, SIGNAL(int_received()),
340                                         &w, SLOT(close()));
341                                 QObject::connect(handler, SIGNAL(term_received()),
342                                         &w, SLOT(close()));
343                         } else
344                                 qWarning() << "Could not prepare signal handler.";
345 #endif
346
347                         // Run the application
348                         ret = a.exec();
349                 }
350
351 #ifndef ENABLE_STACKTRACE
352                 } catch (exception& e) {
353                         qDebug() << "Exception:" << e.what();
354                 }
355 #endif
356
357 #ifdef ENABLE_DECODE
358                 // Destroy libsigrokdecode
359                 srd_exit();
360 #endif
361
362         } while (false);
363
364         return ret;
365 }