]> sigrok.org Git - pulseview.git/blob - pv/session.cpp
Refactor channel/signal handling
[pulseview.git] / pv / session.cpp
1 /*
2  * This file is part of the PulseView project.
3  *
4  * Copyright (C) 2012-14 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 #include <cassert>
21 #include <memory>
22 #include <mutex>
23 #include <stdexcept>
24
25 #include <sys/stat.h>
26
27 #include <QDebug>
28 #include <QFileInfo>
29
30 #include "devicemanager.hpp"
31 #include "mainwindow.hpp"
32 #include "session.hpp"
33 #include "util.hpp"
34
35 #include "data/analog.hpp"
36 #include "data/analogsegment.hpp"
37 #include "data/decode/decoder.hpp"
38 #include "data/logic.hpp"
39 #include "data/logicsegment.hpp"
40 #include "data/signalbase.hpp"
41
42 #include "devices/hardwaredevice.hpp"
43 #include "devices/inputfile.hpp"
44 #include "devices/sessionfile.hpp"
45
46 #include "toolbars/mainbar.hpp"
47
48 #include "views/trace/analogsignal.hpp"
49 #include "views/trace/decodetrace.hpp"
50 #include "views/trace/logicsignal.hpp"
51 #include "views/trace/signal.hpp"
52 #include "views/trace/view.hpp"
53
54 #include <libsigrokcxx/libsigrokcxx.hpp>
55
56 #ifdef ENABLE_FLOW
57 #include <gstreamermm.h>
58 #include <libsigrokflow/libsigrokflow.hpp>
59 #endif
60
61 #ifdef ENABLE_DECODE
62 #include <libsigrokdecode/libsigrokdecode.h>
63 #include "data/decodesignal.hpp"
64 #endif
65
66 using std::bad_alloc;
67 using std::dynamic_pointer_cast;
68 using std::find_if;
69 using std::function;
70 using std::list;
71 using std::lock_guard;
72 using std::make_pair;
73 using std::make_shared;
74 using std::map;
75 using std::max;
76 using std::move;
77 using std::mutex;
78 using std::pair;
79 using std::recursive_mutex;
80 using std::runtime_error;
81 using std::shared_ptr;
82 using std::string;
83 #ifdef ENABLE_FLOW
84 using std::unique_lock;
85 #endif
86 using std::unique_ptr;
87 using std::vector;
88
89 using sigrok::Analog;
90 using sigrok::Channel;
91 using sigrok::ConfigKey;
92 using sigrok::DatafeedCallbackFunction;
93 using sigrok::Error;
94 using sigrok::InputFormat;
95 using sigrok::Logic;
96 using sigrok::Meta;
97 using sigrok::Packet;
98 using sigrok::Session;
99
100 using Glib::VariantBase;
101
102 #ifdef ENABLE_FLOW
103 using Gst::Bus;
104 using Gst::ElementFactory;
105 using Gst::Pipeline;
106 #endif
107
108 using pv::util::Timestamp;
109 using pv::views::trace::Signal;
110 using pv::views::trace::AnalogSignal;
111 using pv::views::trace::LogicSignal;
112
113 namespace pv {
114
115 shared_ptr<sigrok::Context> Session::sr_context;
116
117 Session::Session(DeviceManager &device_manager, QString name) :
118         device_manager_(device_manager),
119         default_name_(name),
120         name_(name),
121         capture_state_(Stopped),
122         cur_samplerate_(0),
123         data_saved_(true)
124 {
125 }
126
127 Session::~Session()
128 {
129         // Stop and join to the thread
130         stop_capture();
131 }
132
133 DeviceManager& Session::device_manager()
134 {
135         return device_manager_;
136 }
137
138 const DeviceManager& Session::device_manager() const
139 {
140         return device_manager_;
141 }
142
143 shared_ptr<sigrok::Session> Session::session() const
144 {
145         if (!device_)
146                 return shared_ptr<sigrok::Session>();
147         return device_->session();
148 }
149
150 shared_ptr<devices::Device> Session::device() const
151 {
152         return device_;
153 }
154
155 QString Session::name() const
156 {
157         return name_;
158 }
159
160 void Session::set_name(QString name)
161 {
162         if (default_name_.isEmpty())
163                 default_name_ = name;
164
165         name_ = name;
166
167         name_changed();
168 }
169
170 const vector< shared_ptr<views::ViewBase> > Session::views() const
171 {
172         return views_;
173 }
174
175 shared_ptr<views::ViewBase> Session::main_view() const
176 {
177         return main_view_;
178 }
179
180 void Session::set_main_bar(shared_ptr<pv::toolbars::MainBar> main_bar)
181 {
182         main_bar_ = main_bar;
183 }
184
185 shared_ptr<pv::toolbars::MainBar> Session::main_bar() const
186 {
187         return main_bar_;
188 }
189
190 bool Session::data_saved() const
191 {
192         return data_saved_;
193 }
194
195 void Session::save_setup(QSettings &settings) const
196 {
197         int i = 0;
198
199         // Save channels and decoders
200         for (const shared_ptr<data::SignalBase>& base : signalbases_) {
201 #ifdef ENABLE_DECODE
202                 if (base->is_decode_signal()) {
203                         settings.beginGroup("decode_signal" + QString::number(i++));
204                         base->save_settings(settings);
205                         settings.endGroup();
206                 } else
207 #endif
208                 {
209                         settings.beginGroup(base->internal_name());
210                         base->save_settings(settings);
211                         settings.endGroup();
212                 }
213         }
214
215         settings.setValue("decode_signals", i);
216
217         // Save view states and their signal settings
218         // Note: main_view must be saved as view0
219         i = 0;
220         settings.beginGroup("view" + QString::number(i++));
221         main_view_->save_settings(settings);
222         settings.endGroup();
223
224         for (const shared_ptr<views::ViewBase>& view : views_) {
225                 if (view != main_view_) {
226                         settings.beginGroup("view" + QString::number(i++));
227                         settings.setValue("type", view->get_type());
228                         view->save_settings(settings);
229                         settings.endGroup();
230                 }
231         }
232
233         settings.setValue("views", i);
234
235         int view_id = 0;
236         i = 0;
237         for (const shared_ptr<views::ViewBase>& vb : views_) {
238                 shared_ptr<views::trace::View> tv = dynamic_pointer_cast<views::trace::View>(vb);
239                 if (tv) {
240                         for (const shared_ptr<views::trace::TimeItem>& time_item : tv->time_items()) {
241
242                                 const shared_ptr<views::trace::Flag> flag =
243                                         dynamic_pointer_cast<views::trace::Flag>(time_item);
244                                 if (flag) {
245                                         if (!flag->enabled())
246                                                 continue;
247
248                                         settings.beginGroup("meta_obj" + QString::number(i++));
249                                         settings.setValue("type", "time_marker");
250                                         settings.setValue("assoc_view", view_id);
251                                         GlobalSettings::store_timestamp(settings, "time", flag->time());
252                                         settings.setValue("text", flag->get_text());
253                                         settings.endGroup();
254                                 }
255                         }
256
257                         if (tv->cursors_shown()) {
258                                 settings.beginGroup("meta_obj" + QString::number(i++));
259                                 settings.setValue("type", "selection");
260                                 settings.setValue("assoc_view", view_id);
261                                 const shared_ptr<views::trace::CursorPair> cp = tv->cursors();
262                                 GlobalSettings::store_timestamp(settings, "start_time", cp->first()->time());
263                                 GlobalSettings::store_timestamp(settings, "end_time", cp->second()->time());
264                                 settings.endGroup();
265                         }
266                 }
267
268                 view_id++;
269         }
270
271         settings.setValue("meta_objs", i);
272 }
273
274 void Session::save_settings(QSettings &settings) const
275 {
276         map<string, string> dev_info;
277         list<string> key_list;
278
279         if (device_) {
280                 shared_ptr<devices::HardwareDevice> hw_device =
281                         dynamic_pointer_cast< devices::HardwareDevice >(device_);
282
283                 if (hw_device) {
284                         settings.setValue("device_type", "hardware");
285                         settings.beginGroup("device");
286
287                         key_list.emplace_back("vendor");
288                         key_list.emplace_back("model");
289                         key_list.emplace_back("version");
290                         key_list.emplace_back("serial_num");
291                         key_list.emplace_back("connection_id");
292
293                         dev_info = device_manager_.get_device_info(device_);
294
295                         for (string& key : key_list) {
296                                 if (dev_info.count(key))
297                                         settings.setValue(QString::fromUtf8(key.c_str()),
298                                                         QString::fromUtf8(dev_info.at(key).c_str()));
299                                 else
300                                         settings.remove(QString::fromUtf8(key.c_str()));
301                         }
302
303                         settings.endGroup();
304                 }
305
306                 shared_ptr<devices::SessionFile> sessionfile_device =
307                         dynamic_pointer_cast<devices::SessionFile>(device_);
308
309                 if (sessionfile_device) {
310                         settings.setValue("device_type", "sessionfile");
311                         settings.beginGroup("device");
312                         settings.setValue("filename", QString::fromStdString(
313                                 sessionfile_device->full_name()));
314                         settings.endGroup();
315                 }
316
317                 shared_ptr<devices::InputFile> inputfile_device =
318                         dynamic_pointer_cast<devices::InputFile>(device_);
319
320                 if (inputfile_device) {
321                         settings.setValue("device_type", "inputfile");
322                         settings.beginGroup("device");
323                         inputfile_device->save_meta_to_settings(settings);
324                         settings.endGroup();
325                 }
326
327                 save_setup(settings);
328         }
329 }
330
331 void Session::restore_setup(QSettings &settings)
332 {
333         // Restore channels
334         for (shared_ptr<data::SignalBase> base : signalbases_) {
335                 settings.beginGroup(base->internal_name());
336                 base->restore_settings(settings);
337                 settings.endGroup();
338         }
339
340         // Restore decoders
341 #ifdef ENABLE_DECODE
342         int decode_signals = settings.value("decode_signals").toInt();
343
344         for (int i = 0; i < decode_signals; i++) {
345                 settings.beginGroup("decode_signal" + QString::number(i));
346                 shared_ptr<data::DecodeSignal> signal = add_decode_signal();
347                 signal->restore_settings(settings);
348                 settings.endGroup();
349         }
350 #endif
351
352         // Restore views
353         int views = settings.value("views").toInt();
354
355         for (int i = 0; i < views; i++) {
356                 settings.beginGroup("view" + QString::number(i));
357
358                 if (i > 0) {
359                         views::ViewType type = (views::ViewType)settings.value("type").toInt();
360                         add_view(type, this);
361                         views_.back()->restore_settings(settings);
362                 } else
363                         main_view_->restore_settings(settings);
364
365                 settings.endGroup();
366         }
367
368         // Restore meta objects like markers and cursors
369         int meta_objs = settings.value("meta_objs").toInt();
370
371         for (int i = 0; i < meta_objs; i++) {
372                 settings.beginGroup("meta_obj" + QString::number(i));
373
374                 shared_ptr<views::ViewBase> vb;
375                 shared_ptr<views::trace::View> tv;
376                 if (settings.contains("assoc_view"))
377                         vb = views_.at(settings.value("assoc_view").toInt());
378
379                 if (vb)
380                         tv = dynamic_pointer_cast<views::trace::View>(vb);
381
382                 const QString type = settings.value("type").toString();
383
384                 if ((type == "time_marker") && tv) {
385                         Timestamp ts = GlobalSettings::restore_timestamp(settings, "time");
386                         shared_ptr<views::trace::Flag> flag = tv->add_flag(ts);
387                         flag->set_text(settings.value("text").toString());
388                 }
389
390                 if ((type == "selection") && tv) {
391                         Timestamp start = GlobalSettings::restore_timestamp(settings, "start_time");
392                         Timestamp end = GlobalSettings::restore_timestamp(settings, "end_time");
393                         tv->set_cursors(start, end);
394                         tv->show_cursors();
395                 }
396
397                 settings.endGroup();
398         }
399 }
400
401 void Session::restore_settings(QSettings &settings)
402 {
403         shared_ptr<devices::Device> device;
404
405         const QString device_type = settings.value("device_type").toString();
406
407         if (device_type == "hardware") {
408                 map<string, string> dev_info;
409                 list<string> key_list;
410
411                 // Re-select last used device if possible but only if it's not demo
412                 settings.beginGroup("device");
413                 key_list.emplace_back("vendor");
414                 key_list.emplace_back("model");
415                 key_list.emplace_back("version");
416                 key_list.emplace_back("serial_num");
417                 key_list.emplace_back("connection_id");
418
419                 for (string key : key_list) {
420                         const QString k = QString::fromStdString(key);
421                         if (!settings.contains(k))
422                                 continue;
423
424                         const string value = settings.value(k).toString().toStdString();
425                         if (!value.empty())
426                                 dev_info.insert(make_pair(key, value));
427                 }
428
429                 if (dev_info.count("model") > 0)
430                         device = device_manager_.find_device_from_info(dev_info);
431
432                 if (device)
433                         set_device(device);
434
435                 settings.endGroup();
436         }
437
438         if ((device_type == "sessionfile") || (device_type == "inputfile")) {
439                 if (device_type == "sessionfile") {
440                         settings.beginGroup("device");
441                         const QString filename = settings.value("filename").toString();
442                         settings.endGroup();
443
444                         if (QFileInfo(filename).isReadable()) {
445                                 device = make_shared<devices::SessionFile>(device_manager_.context(),
446                                         filename.toStdString());
447                         }
448                 }
449
450                 if (device_type == "inputfile") {
451                         settings.beginGroup("device");
452                         device = make_shared<devices::InputFile>(device_manager_.context(),
453                                 settings);
454                         settings.endGroup();
455                 }
456
457                 if (device) {
458                         set_device(device);
459
460                         start_capture([](QString infoMessage) {
461                                 // TODO Emulate noquote()
462                                 qDebug() << "Session error:" << infoMessage; });
463
464                         set_name(QString::fromStdString(
465                                 dynamic_pointer_cast<devices::File>(device)->display_name(device_manager_)));
466                 }
467         }
468
469         if (device)
470                 restore_setup(settings);
471 }
472
473 void Session::select_device(shared_ptr<devices::Device> device)
474 {
475         try {
476                 if (device)
477                         set_device(device);
478                 else
479                         set_default_device();
480         } catch (const QString &e) {
481                 MainWindow::show_session_error(tr("Failed to select device"), e);
482         }
483 }
484
485 void Session::set_device(shared_ptr<devices::Device> device)
486 {
487         assert(device);
488
489         // Ensure we are not capturing before setting the device
490         stop_capture();
491
492         if (device_)
493                 device_->close();
494
495         device_.reset();
496
497         // Revert name back to default name (e.g. "Session 1") as the data is gone
498         name_ = default_name_;
499         name_changed();
500
501         // Remove all stored data and reset all views
502         for (shared_ptr<views::ViewBase> view : views_) {
503                 view->clear_signalbases();
504 #ifdef ENABLE_DECODE
505                 view->clear_decode_signals();
506 #endif
507                 view->reset_view_state();
508         }
509         for (const shared_ptr<data::SignalData>& d : all_signal_data_)
510                 d->clear();
511         all_signal_data_.clear();
512         signalbases_.clear();
513         cur_logic_segment_.reset();
514
515         for (auto& entry : cur_analog_segments_) {
516                 shared_ptr<sigrok::Channel>(entry.first).reset();
517                 shared_ptr<data::AnalogSegment>(entry.second).reset();
518         }
519
520         logic_data_.reset();
521
522         signals_changed();
523
524         device_ = move(device);
525
526         try {
527                 device_->open();
528         } catch (const QString &e) {
529                 device_.reset();
530                 MainWindow::show_session_error(tr("Failed to open device"), e);
531         }
532
533         if (device_) {
534                 device_->session()->add_datafeed_callback([=]
535                         (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
536                                 data_feed_in(device, packet);
537                         });
538
539                 update_signals();
540         }
541
542         device_changed();
543 }
544
545 void Session::set_default_device()
546 {
547         const list< shared_ptr<devices::HardwareDevice> > &devices =
548                 device_manager_.devices();
549
550         if (devices.empty())
551                 return;
552
553         // Try and find the demo device and select that by default
554         const auto iter = find_if(devices.begin(), devices.end(),
555                 [] (const shared_ptr<devices::HardwareDevice> &d) {
556                         return d->hardware_device()->driver()->name() == "demo"; });
557         set_device((iter == devices.end()) ? devices.front() : *iter);
558 }
559
560 bool Session::using_file_device() const
561 {
562         shared_ptr<devices::SessionFile> sessionfile_device =
563                 dynamic_pointer_cast<devices::SessionFile>(device_);
564
565         shared_ptr<devices::InputFile> inputfile_device =
566                 dynamic_pointer_cast<devices::InputFile>(device_);
567
568         return (sessionfile_device || inputfile_device);
569 }
570
571 /**
572  * Convert generic options to data types that are specific to InputFormat.
573  *
574  * @param[in] user_spec Vector of tokenized words, string format.
575  * @param[in] fmt_opts Input format's options, result of InputFormat::options().
576  *
577  * @return Map of options suitable for InputFormat::create_input().
578  */
579 map<string, Glib::VariantBase>
580 Session::input_format_options(vector<string> user_spec,
581                 map<string, shared_ptr<Option>> fmt_opts)
582 {
583         map<string, Glib::VariantBase> result;
584
585         for (auto& entry : user_spec) {
586                 /*
587                  * Split key=value specs. Accept entries without separator
588                  * (for simplified boolean specifications).
589                  */
590                 string key, val;
591                 size_t pos = entry.find("=");
592                 if (pos == std::string::npos) {
593                         key = entry;
594                         val = "";
595                 } else {
596                         key = entry.substr(0, pos);
597                         val = entry.substr(pos + 1);
598                 }
599
600                 /*
601                  * Skip user specifications that are not a member of the
602                  * format's set of supported options. Have the text input
603                  * spec converted to the required input format specific
604                  * data type.
605                  */
606                 auto found = fmt_opts.find(key);
607                 if (found == fmt_opts.end())
608                         continue;
609                 shared_ptr<Option> opt = found->second;
610                 result[key] = opt->parse_string(val);
611         }
612
613         return result;
614 }
615
616 void Session::load_init_file(const string &file_name,
617         const string &format, const string &setup_file_name)
618 {
619         shared_ptr<InputFormat> input_format;
620         map<string, Glib::VariantBase> input_opts;
621
622         if (!format.empty()) {
623                 const map<string, shared_ptr<InputFormat> > formats =
624                         device_manager_.context()->input_formats();
625                 auto user_opts = pv::util::split_string(format, ":");
626                 string user_name = user_opts.front();
627                 user_opts.erase(user_opts.begin());
628                 const auto iter = find_if(formats.begin(), formats.end(),
629                         [&](const pair<string, shared_ptr<InputFormat> > f) {
630                                 return f.first == user_name; });
631                 if (iter == formats.end()) {
632                         MainWindow::show_session_error(tr("Error"),
633                                 tr("Unexpected input format: %s").arg(QString::fromStdString(format)));
634                         return;
635                 }
636                 input_format = (*iter).second;
637                 input_opts = input_format_options(user_opts,
638                         input_format->options());
639         }
640
641         load_file(QString::fromStdString(file_name), QString::fromStdString(setup_file_name),
642                 input_format, input_opts);
643 }
644
645 void Session::load_file(QString file_name, QString setup_file_name,
646         shared_ptr<sigrok::InputFormat> format, const map<string, Glib::VariantBase> &options)
647 {
648         const QString errorMessage(
649                 QString("Failed to load file %1").arg(file_name));
650
651         // In the absence of a caller's format spec, try to auto detect.
652         // Assume "sigrok session file" upon lookup miss.
653         if (!format)
654                 format = device_manager_.context()->input_format_match(file_name.toStdString());
655         try {
656                 if (format)
657                         set_device(shared_ptr<devices::Device>(
658                                 new devices::InputFile(
659                                         device_manager_.context(),
660                                         file_name.toStdString(),
661                                         format, options)));
662                 else
663                         set_device(shared_ptr<devices::Device>(
664                                 new devices::SessionFile(
665                                         device_manager_.context(),
666                                         file_name.toStdString())));
667         } catch (Error& e) {
668                 MainWindow::show_session_error(tr("Failed to load %1").arg(file_name), e.what());
669                 set_default_device();
670                 main_bar_->update_device_list();
671                 return;
672         }
673
674         // Use the input file with .pvs extension if no setup file was given
675         if (setup_file_name.isEmpty()) {
676                 setup_file_name = file_name;
677                 setup_file_name.truncate(setup_file_name.lastIndexOf('.'));
678                 setup_file_name.append(".pvs");
679         }
680
681         if (QFileInfo::exists(setup_file_name) && QFileInfo(setup_file_name).isReadable()) {
682                 QSettings settings_storage(setup_file_name, QSettings::IniFormat);
683                 restore_setup(settings_storage);
684         }
685
686         main_bar_->update_device_list();
687
688         start_capture([&, errorMessage](QString infoMessage) {
689                 MainWindow::show_session_error(errorMessage, infoMessage); });
690
691         set_name(QFileInfo(file_name).fileName());
692 }
693
694 Session::capture_state Session::get_capture_state() const
695 {
696         lock_guard<mutex> lock(sampling_mutex_);
697         return capture_state_;
698 }
699
700 void Session::start_capture(function<void (const QString)> error_handler)
701 {
702         if (!device_) {
703                 error_handler(tr("No active device set, can't start acquisition."));
704                 return;
705         }
706
707         stop_capture();
708
709         // Check that at least one channel is enabled
710         const shared_ptr<sigrok::Device> sr_dev = device_->device();
711         if (sr_dev) {
712                 const auto channels = sr_dev->channels();
713                 if (!any_of(channels.begin(), channels.end(),
714                         [](shared_ptr<Channel> channel) {
715                                 return channel->enabled(); })) {
716                         error_handler(tr("No channels enabled."));
717                         return;
718                 }
719         }
720
721         // Clear signal data
722         for (const shared_ptr<data::SignalData>& d : all_signal_data_)
723                 d->clear();
724
725         trigger_list_.clear();
726
727         // Revert name back to default name (e.g. "Session 1") for real devices
728         // as the (possibly saved) data is gone. File devices keep their name.
729         shared_ptr<devices::HardwareDevice> hw_device =
730                 dynamic_pointer_cast< devices::HardwareDevice >(device_);
731
732         if (hw_device) {
733                 name_ = default_name_;
734                 name_changed();
735         }
736
737         // Begin the session
738         sampling_thread_ = std::thread(
739                 &Session::sample_thread_proc, this, error_handler);
740 }
741
742 void Session::stop_capture()
743 {
744         if (get_capture_state() != Stopped)
745                 device_->stop();
746
747         // Check that sampling stopped
748         if (sampling_thread_.joinable())
749                 sampling_thread_.join();
750 }
751
752 void Session::register_view(shared_ptr<views::ViewBase> view)
753 {
754         if (views_.empty())
755                 main_view_ = view;
756
757         views_.push_back(view);
758
759         // Add all device signals
760         update_signals();
761
762         // Add all other signals
763         vector< shared_ptr<data::SignalBase> > view_signalbases = view->signalbases();
764
765         for (const shared_ptr<data::SignalBase>& signalbase : signalbases_) {
766                 const int sb_exists = count_if(
767                         view_signalbases.cbegin(), view_signalbases.cend(),
768                         [&](const shared_ptr<data::SignalBase> &sb) {
769                                 return sb == signalbase;
770                         });
771
772                 // Add the signal to the view if it doesn't have it yet
773                 if (!sb_exists)
774                         switch (signalbase->type()) {
775                         case data::SignalBase::AnalogChannel:
776                         case data::SignalBase::LogicChannel:
777                         case data::SignalBase::MathChannel:
778                                 view->add_signalbase(signalbase);
779                                 break;
780                         case data::SignalBase::DecodeChannel:
781 #ifdef ENABLE_DECODE
782                                 view->add_decode_signal(dynamic_pointer_cast<data::DecodeSignal>(signalbase));
783 #endif
784                                 break;
785                         }
786         }
787
788         signals_changed();
789 }
790
791 void Session::deregister_view(shared_ptr<views::ViewBase> view)
792 {
793         views_.erase(std::remove_if(views_.begin(), views_.end(),
794                 [&](shared_ptr<views::ViewBase> v) { return v == view; }),
795                 views_.end());
796
797         if (views_.empty()) {
798                 main_view_.reset();
799
800                 // Without a view there can be no main bar
801                 main_bar_.reset();
802         }
803 }
804
805 bool Session::has_view(shared_ptr<views::ViewBase> view)
806 {
807         for (shared_ptr<views::ViewBase>& v : views_)
808                 if (v == view)
809                         return true;
810
811         return false;
812 }
813
814 double Session::get_samplerate() const
815 {
816         double samplerate = 0.0;
817
818         for (const shared_ptr<pv::data::SignalData>& d : all_signal_data_) {
819                 assert(d);
820                 const vector< shared_ptr<pv::data::Segment> > segments =
821                         d->segments();
822                 for (const shared_ptr<pv::data::Segment>& s : segments)
823                         samplerate = max(samplerate, s->samplerate());
824         }
825         // If there is no sample rate given we use samples as unit
826         if (samplerate == 0.0)
827                 samplerate = 1.0;
828
829         return samplerate;
830 }
831
832 uint32_t Session::get_segment_count() const
833 {
834         uint32_t value = 0;
835
836         // Find the highest number of segments
837         for (const shared_ptr<data::SignalData>& data : all_signal_data_)
838                 if (data->get_segment_count() > value)
839                         value = data->get_segment_count();
840
841         return value;
842 }
843
844 vector<util::Timestamp> Session::get_triggers(uint32_t segment_id) const
845 {
846         vector<util::Timestamp> result;
847
848         for (const pair<uint32_t, util::Timestamp>& entry : trigger_list_)
849                 if (entry.first == segment_id)
850                         result.push_back(entry.second);
851
852         return result;
853 }
854
855 const vector< shared_ptr<data::SignalBase> > Session::signalbases() const
856 {
857         return signalbases_;
858 }
859
860 bool Session::all_segments_complete(uint32_t segment_id) const
861 {
862         bool all_complete = true;
863
864         for (const shared_ptr<data::SignalBase>& base : signalbases_)
865                 if (!base->segment_is_complete(segment_id))
866                         all_complete = false;
867
868         return all_complete;
869 }
870
871 #ifdef ENABLE_DECODE
872 shared_ptr<data::DecodeSignal> Session::add_decode_signal()
873 {
874         shared_ptr<data::DecodeSignal> signal;
875
876         try {
877                 // Create the decode signal
878                 signal = make_shared<data::DecodeSignal>(*this);
879
880                 signalbases_.push_back(signal);
881
882                 // Add the decode signal to all views
883                 for (shared_ptr<views::ViewBase>& view : views_)
884                         view->add_decode_signal(signal);
885         } catch (runtime_error& e) {
886                 remove_decode_signal(signal);
887                 return nullptr;
888         }
889
890         signals_changed();
891
892         return signal;
893 }
894
895 void Session::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
896 {
897         signalbases_.erase(std::remove_if(signalbases_.begin(), signalbases_.end(),
898                 [&](shared_ptr<data::SignalBase> s) { return s == signal; }),
899                 signalbases_.end());
900
901         for (shared_ptr<views::ViewBase>& view : views_)
902                 view->remove_decode_signal(signal);
903
904         signals_changed();
905 }
906 #endif
907
908 MetadataObjManager* Session::metadata_obj_manager()
909 {
910         return &metadata_obj_manager_;
911 }
912
913 void Session::set_capture_state(capture_state state)
914 {
915         bool changed;
916
917         if (state == Running)
918                 acq_time_.restart();
919         if (state == Stopped)
920                 qDebug("Acquisition took %.2f s", acq_time_.elapsed() / 1000.);
921
922         {
923                 lock_guard<mutex> lock(sampling_mutex_);
924                 changed = capture_state_ != state;
925                 capture_state_ = state;
926         }
927
928         if (changed)
929                 capture_state_changed(state);
930 }
931
932 void Session::update_signals()
933 {
934         if (!device_) {
935                 signalbases_.clear();
936                 logic_data_.reset();
937                 for (shared_ptr<views::ViewBase>& view : views_) {
938                         view->clear_signalbases();
939 #ifdef ENABLE_DECODE
940                         view->clear_decode_signals();
941 #endif
942                 }
943                 return;
944         }
945
946         lock_guard<recursive_mutex> lock(data_mutex_);
947
948         const shared_ptr<sigrok::Device> sr_dev = device_->device();
949         if (!sr_dev) {
950                 signalbases_.clear();
951                 logic_data_.reset();
952                 for (shared_ptr<views::ViewBase>& view : views_) {
953                         view->clear_signalbases();
954 #ifdef ENABLE_DECODE
955                         view->clear_decode_signals();
956 #endif
957                 }
958                 return;
959         }
960
961         // Detect what data types we will receive
962         auto channels = sr_dev->channels();
963         unsigned int logic_channel_count = count_if(
964                 channels.begin(), channels.end(),
965                 [] (shared_ptr<Channel> channel) {
966                         return channel->type() == sigrok::ChannelType::LOGIC; });
967
968         // Create a common data container for the logic signalbases
969         {
970                 lock_guard<recursive_mutex> data_lock(data_mutex_);
971
972                 if (logic_channel_count == 0) {
973                         logic_data_.reset();
974                 } else if (!logic_data_ ||
975                         logic_data_->num_channels() != logic_channel_count) {
976                         logic_data_.reset(new data::Logic(logic_channel_count));
977                         assert(logic_data_);
978                 }
979         }
980
981         // Create signalbases if necessary
982         for (auto channel : sr_dev->channels()) {
983
984                 // Try to find the channel in the list of existing signalbases
985                 const auto iter = find_if(signalbases_.cbegin(), signalbases_.cend(),
986                         [&](const shared_ptr<SignalBase> &sb) { return sb->channel() == channel; });
987
988                 // Not found, let's make a signalbase for it
989                 if (iter == signalbases_.cend()) {
990                         shared_ptr<SignalBase> signalbase;
991                         switch(channel->type()->id()) {
992                         case SR_CHANNEL_LOGIC:
993                                 signalbase = make_shared<data::SignalBase>(channel, data::SignalBase::LogicChannel);
994                                 signalbases_.push_back(signalbase);
995
996                                 all_signal_data_.insert(logic_data_);
997                                 signalbase->set_data(logic_data_);
998
999                                 connect(this, SIGNAL(capture_state_changed(int)),
1000                                                 signalbase.get(), SLOT(on_capture_state_changed(int)));
1001                                 break;
1002
1003                         case SR_CHANNEL_ANALOG:
1004                                 signalbase = make_shared<data::SignalBase>(channel, data::SignalBase::AnalogChannel);
1005                                 signalbases_.push_back(signalbase);
1006
1007                                 shared_ptr<data::Analog> data(new data::Analog());
1008                                 all_signal_data_.insert(data);
1009                                 signalbase->set_data(data);
1010
1011                                 connect(this, SIGNAL(capture_state_changed(int)),
1012                                                 signalbase.get(), SLOT(on_capture_state_changed(int)));
1013                                 break;
1014                         }
1015                 }
1016         }
1017
1018         for (shared_ptr<views::ViewBase>& viewbase : views_) {
1019                 vector< shared_ptr<SignalBase> > view_signalbases =
1020                                 viewbase->signalbases();
1021
1022                 // Add all non-decode signalbases that don't yet exist in the view
1023                 for (shared_ptr<SignalBase>& session_sb : signalbases_) {
1024                         if (session_sb->type() == SignalBase::DecodeChannel)
1025                                 continue;
1026
1027                         const auto iter = find_if(view_signalbases.cbegin(), view_signalbases.cend(),
1028                                 [&](const shared_ptr<SignalBase> &sb) { return sb == session_sb; });
1029
1030                         if (iter == view_signalbases.cend())
1031                                 viewbase->add_signalbase(session_sb);
1032                 }
1033
1034                 // Remove all non-decode signalbases that no longer exist
1035                 for (shared_ptr<SignalBase>& view_sb : view_signalbases) {
1036                         if (view_sb->type() == SignalBase::DecodeChannel)
1037                                 continue;
1038
1039                         const auto iter = find_if(signalbases_.cbegin(), signalbases_.cend(),
1040                                 [&](const shared_ptr<SignalBase> &sb) { return sb == view_sb; });
1041
1042                         if (iter == signalbases_.cend())
1043                                 viewbase->remove_signalbase(view_sb);
1044                 }
1045         }
1046
1047         signals_changed();
1048 }
1049
1050 shared_ptr<data::SignalBase> Session::signalbase_from_channel(
1051         shared_ptr<sigrok::Channel> channel) const
1052 {
1053         for (shared_ptr<data::SignalBase> sig : signalbases_) {
1054                 assert(sig);
1055                 if (sig->channel() == channel)
1056                         return sig;
1057         }
1058         return shared_ptr<data::SignalBase>();
1059 }
1060
1061 void Session::sample_thread_proc(function<void (const QString)> error_handler)
1062 {
1063         assert(error_handler);
1064
1065 #ifdef ENABLE_FLOW
1066         pipeline_ = Pipeline::create();
1067
1068         source_ = ElementFactory::create_element("filesrc", "source");
1069         sink_ = RefPtr<AppSink>::cast_dynamic(ElementFactory::create_element("appsink", "sink"));
1070
1071         pipeline_->add(source_)->add(sink_);
1072         source_->link(sink_);
1073
1074         source_->set_property("location", Glib::ustring("/tmp/dummy_binary"));
1075
1076         sink_->set_property("emit-signals", TRUE);
1077         sink_->signal_new_sample().connect(sigc::mem_fun(*this, &Session::on_gst_new_sample));
1078
1079         // Get the bus from the pipeline and add a bus watch to the default main context
1080         RefPtr<Bus> bus = pipeline_->get_bus();
1081         bus->add_watch(sigc::mem_fun(this, &Session::on_gst_bus_message));
1082
1083         // Start pipeline and Wait until it finished processing
1084         pipeline_done_interrupt_ = false;
1085         pipeline_->set_state(Gst::STATE_PLAYING);
1086
1087         unique_lock<mutex> pipeline_done_lock_(pipeline_done_mutex_);
1088         pipeline_done_cond_.wait(pipeline_done_lock_);
1089
1090         // Let the pipeline free all resources
1091         pipeline_->set_state(Gst::STATE_NULL);
1092
1093 #else
1094         if (!device_)
1095                 return;
1096
1097         try {
1098                 cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1099         } catch (Error& e) {
1100                 cur_samplerate_ = 0;
1101         }
1102
1103         out_of_memory_ = false;
1104
1105         {
1106                 lock_guard<recursive_mutex> lock(data_mutex_);
1107                 cur_logic_segment_.reset();
1108                 cur_analog_segments_.clear();
1109         }
1110         highest_segment_id_ = -1;
1111         frame_began_ = false;
1112
1113         try {
1114                 device_->start();
1115         } catch (Error& e) {
1116                 error_handler(e.what());
1117                 return;
1118         }
1119
1120         set_capture_state(device_->session()->trigger() ?
1121                 AwaitingTrigger : Running);
1122
1123         try {
1124                 device_->run();
1125         } catch (Error& e) {
1126                 error_handler(e.what());
1127                 set_capture_state(Stopped);
1128                 return;
1129         } catch (QString& e) {
1130                 error_handler(e);
1131                 set_capture_state(Stopped);
1132                 return;
1133         }
1134
1135         set_capture_state(Stopped);
1136
1137         // Confirm that SR_DF_END was received
1138         if (cur_logic_segment_)
1139                 qDebug() << "WARNING: SR_DF_END was not received.";
1140 #endif
1141
1142         // Optimize memory usage
1143         free_unused_memory();
1144
1145         // We now have unsaved data unless we just "captured" from a file
1146         shared_ptr<devices::File> file_device =
1147                 dynamic_pointer_cast<devices::File>(device_);
1148
1149         if (!file_device)
1150                 data_saved_ = false;
1151
1152         if (out_of_memory_)
1153                 error_handler(tr("Out of memory, acquisition stopped."));
1154 }
1155
1156 void Session::free_unused_memory()
1157 {
1158         for (const shared_ptr<data::SignalData>& data : all_signal_data_) {
1159                 const vector< shared_ptr<data::Segment> > segments = data->segments();
1160
1161                 for (const shared_ptr<data::Segment>& segment : segments)
1162                         segment->free_unused_memory();
1163         }
1164 }
1165
1166 void Session::signal_new_segment()
1167 {
1168         int new_segment_id = 0;
1169
1170         if ((cur_logic_segment_ != nullptr) || !cur_analog_segments_.empty()) {
1171
1172                 // Determine new frame/segment number, assuming that all
1173                 // signals have the same number of frames/segments
1174                 if (cur_logic_segment_) {
1175                         new_segment_id = logic_data_->get_segment_count() - 1;
1176                 } else {
1177                         shared_ptr<sigrok::Channel> any_channel =
1178                                 (*cur_analog_segments_.begin()).first;
1179
1180                         shared_ptr<data::SignalBase> base = signalbase_from_channel(any_channel);
1181                         assert(base);
1182
1183                         shared_ptr<data::Analog> data(base->analog_data());
1184                         assert(data);
1185
1186                         new_segment_id = data->get_segment_count() - 1;
1187                 }
1188         }
1189
1190         if (new_segment_id > highest_segment_id_) {
1191                 highest_segment_id_ = new_segment_id;
1192                 new_segment(highest_segment_id_);
1193         }
1194 }
1195
1196 void Session::signal_segment_completed()
1197 {
1198         int segment_id = 0;
1199
1200         for (const shared_ptr<data::SignalBase>& signalbase : signalbases_) {
1201                 // We only care about analog and logic channels, not derived ones
1202                 if (signalbase->type() == data::SignalBase::AnalogChannel) {
1203                         segment_id = signalbase->analog_data()->get_segment_count() - 1;
1204                         break;
1205                 }
1206
1207                 if (signalbase->type() == data::SignalBase::LogicChannel) {
1208                         segment_id = signalbase->logic_data()->get_segment_count() - 1;
1209                         break;
1210                 }
1211         }
1212
1213         if (segment_id >= 0)
1214                 segment_completed(segment_id);
1215 }
1216
1217 #ifdef ENABLE_FLOW
1218 bool Session::on_gst_bus_message(const Glib::RefPtr<Gst::Bus>& bus, const Glib::RefPtr<Gst::Message>& message)
1219 {
1220         (void)bus;
1221
1222         if ((message->get_source() == pipeline_) && \
1223                 ((message->get_message_type() == Gst::MESSAGE_EOS)))
1224                 pipeline_done_cond_.notify_one();
1225
1226         // TODO Also evaluate MESSAGE_STREAM_STATUS to receive error notifications
1227
1228         return true;
1229 }
1230
1231 Gst::FlowReturn Session::on_gst_new_sample()
1232 {
1233         RefPtr<Gst::Sample> sample = sink_->pull_sample();
1234         RefPtr<Gst::Buffer> buf = sample->get_buffer();
1235
1236         for (uint32_t block_id = 0; block_id < buf->n_memory(); block_id++) {
1237                 RefPtr<Gst::Memory> buf_mem = buf->get_memory(block_id);
1238                 Gst::MapInfo mapinfo;
1239                 buf_mem->map(mapinfo, Gst::MAP_READ);
1240
1241                 shared_ptr<sigrok::Packet> logic_packet =
1242                         sr_context->create_logic_packet(mapinfo.get_data(), buf->get_size(), 1);
1243
1244                 try {
1245                         feed_in_logic(dynamic_pointer_cast<sigrok::Logic>(logic_packet->payload()));
1246                 } catch (bad_alloc&) {
1247                         out_of_memory_ = true;
1248                         device_->stop();
1249                         buf_mem->unmap(mapinfo);
1250                         return Gst::FLOW_ERROR;
1251                 }
1252
1253                 buf_mem->unmap(mapinfo);
1254         }
1255
1256         return Gst::FLOW_OK;
1257 }
1258 #endif
1259
1260 void Session::feed_in_header()
1261 {
1262         // Nothing to do here for now
1263 }
1264
1265 void Session::feed_in_meta(shared_ptr<Meta> meta)
1266 {
1267         for (auto& entry : meta->config()) {
1268                 switch (entry.first->id()) {
1269                 case SR_CONF_SAMPLERATE:
1270                         cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
1271                         break;
1272                 default:
1273                         qDebug() << "Received meta data key" << entry.first->id() << ", ignoring.";
1274                         break;
1275                 }
1276         }
1277
1278         signals_changed();
1279 }
1280
1281 void Session::feed_in_trigger()
1282 {
1283         // The channel containing most samples should be most accurate
1284         uint64_t sample_count = 0;
1285
1286         {
1287                 for (const shared_ptr<pv::data::SignalData>& d : all_signal_data_) {
1288                         assert(d);
1289                         uint64_t temp_count = 0;
1290
1291                         const vector< shared_ptr<pv::data::Segment> > segments =
1292                                 d->segments();
1293                         for (const shared_ptr<pv::data::Segment> &s : segments)
1294                                 temp_count += s->get_sample_count();
1295
1296                         if (temp_count > sample_count)
1297                                 sample_count = temp_count;
1298                 }
1299         }
1300
1301         uint32_t segment_id = 0;  // Default segment when no frames are used
1302
1303         // If a frame began, we'd ideally be able to use the highest segment ID for
1304         // the trigger. However, as new segments are only created when logic or
1305         // analog data comes in, this doesn't work if the trigger appears right
1306         // after the beginning of the frame, before any sample data.
1307         // For this reason, we use highest segment ID + 1 if no sample data came in
1308         // yet and the highest segment ID otherwise.
1309         if (frame_began_) {
1310                 segment_id = highest_segment_id_;
1311                 if (!cur_logic_segment_ && (cur_analog_segments_.size() == 0))
1312                         segment_id++;
1313         }
1314
1315         // TODO Create timestamp from segment start time + segment's current sample count
1316         util::Timestamp timestamp = sample_count / get_samplerate();
1317         trigger_list_.emplace_back(segment_id, timestamp);
1318         trigger_event(segment_id, timestamp);
1319 }
1320
1321 void Session::feed_in_frame_begin()
1322 {
1323         frame_began_ = true;
1324 }
1325
1326 void Session::feed_in_frame_end()
1327 {
1328         if (!frame_began_)
1329                 return;
1330
1331         {
1332                 lock_guard<recursive_mutex> lock(data_mutex_);
1333
1334                 if (cur_logic_segment_)
1335                         cur_logic_segment_->set_complete();
1336
1337                 for (auto& entry : cur_analog_segments_) {
1338                         shared_ptr<data::AnalogSegment> segment = entry.second;
1339                         segment->set_complete();
1340                 }
1341
1342                 cur_logic_segment_.reset();
1343                 cur_analog_segments_.clear();
1344         }
1345
1346         frame_began_ = false;
1347
1348         signal_segment_completed();
1349 }
1350
1351 void Session::feed_in_logic(shared_ptr<Logic> logic)
1352 {
1353         if (logic->data_length() == 0) {
1354                 qDebug() << "WARNING: Received logic packet with 0 samples.";
1355                 return;
1356         }
1357
1358         if (logic->unit_size() > 8)
1359                 throw QString(tr("Can't handle more than 64 logic channels."));
1360
1361         if (!cur_samplerate_)
1362                 try {
1363                         cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1364                 } catch (Error& e) {
1365                         // Do nothing
1366                 }
1367
1368         lock_guard<recursive_mutex> lock(data_mutex_);
1369
1370         if (!logic_data_) {
1371                 // The only reason logic_data_ would not have been created is
1372                 // if it was not possible to determine the signals when the
1373                 // device was created.
1374                 update_signals();
1375         }
1376
1377         if (!cur_logic_segment_) {
1378                 // This could be the first packet after a trigger
1379                 set_capture_state(Running);
1380
1381                 // Create a new data segment
1382                 cur_logic_segment_ = make_shared<data::LogicSegment>(
1383                         *logic_data_, logic_data_->get_segment_count(),
1384                         logic->unit_size(), cur_samplerate_);
1385                 logic_data_->push_segment(cur_logic_segment_);
1386
1387                 signal_new_segment();
1388         }
1389
1390         cur_logic_segment_->append_payload(logic);
1391
1392         data_received();
1393 }
1394
1395 void Session::feed_in_analog(shared_ptr<Analog> analog)
1396 {
1397         if (analog->num_samples() == 0) {
1398                 qDebug() << "WARNING: Received analog packet with 0 samples.";
1399                 return;
1400         }
1401
1402         if (!cur_samplerate_)
1403                 try {
1404                         cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
1405                 } catch (Error& e) {
1406                         // Do nothing
1407                 }
1408
1409         lock_guard<recursive_mutex> lock(data_mutex_);
1410
1411         const vector<shared_ptr<Channel>> channels = analog->channels();
1412         bool sweep_beginning = false;
1413
1414         unique_ptr<float[]> data(new float[analog->num_samples() * channels.size()]);
1415         analog->get_data_as_float(data.get());
1416
1417         if (signalbases_.empty())
1418                 update_signals();
1419
1420         float *channel_data = data.get();
1421         for (auto& channel : channels) {
1422                 shared_ptr<data::AnalogSegment> segment;
1423
1424                 // Try to get the segment of the channel
1425                 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
1426                         iterator iter = cur_analog_segments_.find(channel);
1427                 if (iter != cur_analog_segments_.end())
1428                         segment = (*iter).second;
1429                 else {
1430                         // If no segment was found, this means we haven't
1431                         // created one yet. i.e. this is the first packet
1432                         // in the sweep containing this segment.
1433                         sweep_beginning = true;
1434
1435                         // Find the analog data associated with the channel
1436                         shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
1437                         assert(base);
1438
1439                         shared_ptr<data::Analog> data(base->analog_data());
1440                         assert(data);
1441
1442                         // Create a segment, keep it in the maps of channels
1443                         segment = make_shared<data::AnalogSegment>(
1444                                 *data, data->get_segment_count(), cur_samplerate_);
1445                         cur_analog_segments_[channel] = segment;
1446
1447                         // Push the segment into the analog data.
1448                         data->push_segment(segment);
1449
1450                         signal_new_segment();
1451                 }
1452
1453                 assert(segment);
1454
1455                 // Append the samples in the segment
1456                 segment->append_interleaved_samples(channel_data++, analog->num_samples(),
1457                         channels.size());
1458         }
1459
1460         if (sweep_beginning) {
1461                 // This could be the first packet after a trigger
1462                 set_capture_state(Running);
1463         }
1464
1465         data_received();
1466 }
1467
1468 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
1469         shared_ptr<Packet> packet)
1470 {
1471         (void)device;
1472
1473         assert(device);
1474         assert(device == device_->device());
1475         assert(packet);
1476
1477         switch (packet->type()->id()) {
1478         case SR_DF_HEADER:
1479                 feed_in_header();
1480                 break;
1481
1482         case SR_DF_META:
1483                 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
1484                 break;
1485
1486         case SR_DF_TRIGGER:
1487                 feed_in_trigger();
1488                 break;
1489
1490         case SR_DF_LOGIC:
1491                 try {
1492                         feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
1493                 } catch (bad_alloc&) {
1494                         out_of_memory_ = true;
1495                         device_->stop();
1496                 }
1497                 break;
1498
1499         case SR_DF_ANALOG:
1500                 try {
1501                         feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
1502                 } catch (bad_alloc&) {
1503                         out_of_memory_ = true;
1504                         device_->stop();
1505                 }
1506                 break;
1507
1508         case SR_DF_FRAME_BEGIN:
1509                 feed_in_frame_begin();
1510                 break;
1511
1512         case SR_DF_FRAME_END:
1513                 feed_in_frame_end();
1514                 break;
1515
1516         case SR_DF_END:
1517                 // Strictly speaking, this is performed when a frame end marker was
1518                 // received, so there's no point doing this again. However, not all
1519                 // devices use frames, and for those devices, we need to do it here.
1520                 {
1521                         lock_guard<recursive_mutex> lock(data_mutex_);
1522
1523                         if (cur_logic_segment_)
1524                                 cur_logic_segment_->set_complete();
1525
1526                         for (auto& entry : cur_analog_segments_) {
1527                                 shared_ptr<data::AnalogSegment> segment = entry.second;
1528                                 segment->set_complete();
1529                         }
1530
1531                         cur_logic_segment_.reset();
1532                         cur_analog_segments_.clear();
1533                 }
1534                 break;
1535
1536         default:
1537                 break;
1538         }
1539 }
1540
1541 void Session::on_data_saved()
1542 {
1543         data_saved_ = true;
1544 }
1545
1546 #ifdef ENABLE_DECODE
1547 void Session::on_new_decoders_selected(vector<const srd_decoder*> decoders)
1548 {
1549         assert(decoders.size() > 0);
1550
1551         shared_ptr<data::DecodeSignal> signal = add_decode_signal();
1552
1553         if (signal)
1554                 for (unsigned int i = 0; i < decoders.size(); i++) {
1555                         const srd_decoder* d = decoders[i];
1556                         signal->stack_decoder(d, !(i < decoders.size() - 1));
1557                 }
1558 }
1559 #endif
1560
1561 } // namespace pv