Disable context menus that could lead to users removing UI parts
[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 <QFileInfo>
21
22 #include <cassert>
23 #include <mutex>
24 #include <stdexcept>
25
26 #include <sys/stat.h>
27
28 #include "devicemanager.hpp"
29 #include "session.hpp"
30
31 #include "data/analog.hpp"
32 #include "data/analogsegment.hpp"
33 #include "data/decode/decoder.hpp"
34 #include "data/decoderstack.hpp"
35 #include "data/logic.hpp"
36 #include "data/logicsegment.hpp"
37 #include "data/signalbase.hpp"
38
39 #include "devices/hardwaredevice.hpp"
40 #include "devices/inputfile.hpp"
41 #include "devices/sessionfile.hpp"
42
43 #include "toolbars/mainbar.hpp"
44
45 #include "view/analogsignal.hpp"
46 #include "view/decodetrace.hpp"
47 #include "view/logicsignal.hpp"
48 #include "view/signal.hpp"
49 #include "view/view.hpp"
50
51 #include <libsigrokcxx/libsigrokcxx.hpp>
52
53 #ifdef ENABLE_DECODE
54 #include <libsigrokdecode/libsigrokdecode.h>
55 #endif
56
57 using std::bad_alloc;
58 using std::dynamic_pointer_cast;
59 using std::find_if;
60 using std::function;
61 using std::lock_guard;
62 using std::list;
63 using std::make_pair;
64 using std::make_shared;
65 using std::map;
66 using std::max;
67 using std::move;
68 using std::mutex;
69 using std::pair;
70 using std::recursive_mutex;
71 using std::runtime_error;
72 using std::shared_ptr;
73 using std::string;
74 using std::unordered_set;
75 using std::vector;
76
77 using sigrok::Analog;
78 using sigrok::Channel;
79 using sigrok::ConfigKey;
80 using sigrok::DatafeedCallbackFunction;
81 using sigrok::Error;
82 using sigrok::InputFormat;
83 using sigrok::Logic;
84 using sigrok::Meta;
85 using sigrok::Packet;
86 using sigrok::Session;
87
88 using Glib::VariantBase;
89
90 namespace pv {
91 Session::Session(DeviceManager &device_manager, QString name) :
92         device_manager_(device_manager),
93         default_name_(name),
94         name_(name),
95         capture_state_(Stopped),
96         cur_samplerate_(0),
97         data_saved_(true)
98 {
99 }
100
101 Session::~Session()
102 {
103         // Stop and join to the thread
104         stop_capture();
105 }
106
107 DeviceManager& Session::device_manager()
108 {
109         return device_manager_;
110 }
111
112 const DeviceManager& Session::device_manager() const
113 {
114         return device_manager_;
115 }
116
117 shared_ptr<sigrok::Session> Session::session() const
118 {
119         if (!device_)
120                 return shared_ptr<sigrok::Session>();
121         return device_->session();
122 }
123
124 shared_ptr<devices::Device> Session::device() const
125 {
126         return device_;
127 }
128
129 QString Session::name() const
130 {
131         return name_;
132 }
133
134 void Session::set_name(QString name)
135 {
136         if (default_name_.isEmpty())
137                 default_name_ = name;
138
139         name_ = name;
140
141         name_changed();
142 }
143
144 const list< shared_ptr<views::ViewBase> > Session::views() const
145 {
146         return views_;
147 }
148
149 shared_ptr<views::ViewBase> Session::main_view() const
150 {
151         return main_view_;
152 }
153
154 void Session::set_main_bar(shared_ptr<pv::toolbars::MainBar> main_bar)
155 {
156         main_bar_ = main_bar;
157 }
158
159 shared_ptr<pv::toolbars::MainBar> Session::main_bar() const
160 {
161         return main_bar_;
162 }
163
164 bool Session::data_saved() const
165 {
166         return data_saved_;
167 }
168
169 void Session::save_settings(QSettings &settings) const
170 {
171         map<string, string> dev_info;
172         list<string> key_list;
173         int stacks = 0, views = 0;
174
175         if (device_) {
176                 shared_ptr<devices::HardwareDevice> hw_device =
177                         dynamic_pointer_cast< devices::HardwareDevice >(device_);
178
179                 if (hw_device) {
180                         settings.setValue("device_type", "hardware");
181                         settings.beginGroup("device");
182
183                         key_list.emplace_back("vendor");
184                         key_list.emplace_back("model");
185                         key_list.emplace_back("version");
186                         key_list.emplace_back("serial_num");
187                         key_list.emplace_back("connection_id");
188
189                         dev_info = device_manager_.get_device_info(device_);
190
191                         for (string key : key_list) {
192                                 if (dev_info.count(key))
193                                         settings.setValue(QString::fromUtf8(key.c_str()),
194                                                         QString::fromUtf8(dev_info.at(key).c_str()));
195                                 else
196                                         settings.remove(QString::fromUtf8(key.c_str()));
197                         }
198
199                         settings.endGroup();
200                 }
201
202                 shared_ptr<devices::SessionFile> sessionfile_device =
203                         dynamic_pointer_cast< devices::SessionFile >(device_);
204
205                 if (sessionfile_device) {
206                         settings.setValue("device_type", "sessionfile");
207                         settings.beginGroup("device");
208                         settings.setValue("filename", QString::fromStdString(
209                                 sessionfile_device->full_name()));
210                         settings.endGroup();
211                 }
212
213                 // Save channels and decoders
214                 for (shared_ptr<data::SignalBase> base : signalbases_) {
215 #ifdef ENABLE_DECODE
216                         if (base->is_decode_signal()) {
217                                 shared_ptr<pv::data::DecoderStack> decoder_stack =
218                                                 base->decoder_stack();
219                                 shared_ptr<data::decode::Decoder> top_decoder =
220                                                 decoder_stack->stack().front();
221
222                                 settings.beginGroup("decoder_stack" + QString::number(stacks++));
223                                 settings.setValue("id", top_decoder->decoder()->id);
224                                 settings.setValue("name", top_decoder->decoder()->name);
225                                 settings.endGroup();
226                         } else
227 #endif
228                         {
229                                 settings.beginGroup(base->internal_name());
230                                 base->save_settings(settings);
231                                 settings.endGroup();
232                         }
233                 }
234
235                 settings.setValue("decoder_stacks", stacks);
236
237                 // Save view states and their signal settings
238                 // Note: main_view must be saved as view0
239                 settings.beginGroup("view" + QString::number(views++));
240                 main_view_->save_settings(settings);
241                 settings.endGroup();
242
243                 for (shared_ptr<views::ViewBase> view : views_) {
244                         if (view != main_view_) {
245                                 settings.beginGroup("view" + QString::number(views++));
246                                 view->save_settings(settings);
247                                 settings.endGroup();
248                         }
249                 }
250
251                 settings.setValue("views", views);
252         }
253 }
254
255 void Session::restore_settings(QSettings &settings)
256 {
257         shared_ptr<devices::Device> device;
258
259         QString device_type = settings.value("device_type").toString();
260
261         if (device_type == "hardware") {
262                 map<string, string> dev_info;
263                 list<string> key_list;
264
265                 // Re-select last used device if possible but only if it's not demo
266                 settings.beginGroup("device");
267                 key_list.emplace_back("vendor");
268                 key_list.emplace_back("model");
269                 key_list.emplace_back("version");
270                 key_list.emplace_back("serial_num");
271                 key_list.emplace_back("connection_id");
272
273                 for (string key : key_list) {
274                         const QString k = QString::fromStdString(key);
275                         if (!settings.contains(k))
276                                 continue;
277
278                         const string value = settings.value(k).toString().toStdString();
279                         if (!value.empty())
280                                 dev_info.insert(make_pair(key, value));
281                 }
282
283                 if (dev_info.count("model") > 0)
284                         device = device_manager_.find_device_from_info(dev_info);
285
286                 if (device)
287                         set_device(device);
288
289                 settings.endGroup();
290         }
291
292         if (device_type == "sessionfile") {
293                 settings.beginGroup("device");
294                 QString filename = settings.value("filename").toString();
295                 settings.endGroup();
296
297                 if (QFileInfo(filename).isReadable()) {
298                         device = make_shared<devices::SessionFile>(device_manager_.context(),
299                                 filename.toStdString());
300                         set_device(device);
301
302                         // TODO Perform error handling
303                         start_capture([](QString infoMessage) { (void)infoMessage; });
304
305                         set_name(QFileInfo(filename).fileName());
306                 }
307         }
308
309         if (device) {
310                 // Restore channels
311                 for (shared_ptr<data::SignalBase> base : signalbases_) {
312                         settings.beginGroup(base->internal_name());
313                         base->restore_settings(settings);
314                         settings.endGroup();
315                 }
316
317                 // Restore decoders
318 #ifdef ENABLE_DECODE
319                 int stacks = settings.value("decoder_stacks").toInt();
320
321                 for (int i = 0; i < stacks; i++) {
322                         settings.beginGroup("decoder_stack" + QString::number(i++));
323
324                         QString id = settings.value("id").toString();
325                         add_decoder(srd_decoder_get_by_id(id.toStdString().c_str()));
326
327                         settings.endGroup();
328                 }
329 #endif
330
331                 // Restore views
332                 int views = settings.value("views").toInt();
333
334                 for (int i = 0; i < views; i++) {
335                         settings.beginGroup("view" + QString::number(i));
336
337                         if (i > 0) {
338                                 views::ViewType type = (views::ViewType)settings.value("type").toInt();
339                                 add_view(name_, type, this);
340                                 views_.back()->restore_settings(settings);
341                         } else
342                                 main_view_->restore_settings(settings);
343
344                         settings.endGroup();
345                 }
346         }
347 }
348
349 void Session::select_device(shared_ptr<devices::Device> device)
350 {
351         try {
352                 if (device)
353                         set_device(device);
354                 else
355                         set_default_device();
356         } catch (const QString &e) {
357                 main_bar_->session_error(tr("Failed to Select Device"),
358                         tr("Failed to Select Device"));
359         }
360 }
361
362 void Session::set_device(shared_ptr<devices::Device> device)
363 {
364         assert(device);
365
366         // Ensure we are not capturing before setting the device
367         stop_capture();
368
369         if (device_)
370                 device_->close();
371
372         device_.reset();
373
374         // Revert name back to default name (e.g. "Session 1") as the data is gone
375         name_ = default_name_;
376         name_changed();
377
378         // Remove all stored data
379         for (shared_ptr<views::ViewBase> view : views_) {
380                 view->clear_signals();
381 #ifdef ENABLE_DECODE
382                 view->clear_decode_signals();
383 #endif
384         }
385         for (const shared_ptr<data::SignalData> d : all_signal_data_)
386                 d->clear();
387         all_signal_data_.clear();
388         signalbases_.clear();
389         cur_logic_segment_.reset();
390
391         for (auto entry : cur_analog_segments_) {
392                 shared_ptr<sigrok::Channel>(entry.first).reset();
393                 shared_ptr<data::AnalogSegment>(entry.second).reset();
394         }
395
396         logic_data_.reset();
397
398         signals_changed();
399
400         device_ = move(device);
401
402         try {
403                 device_->open();
404         } catch (const QString &e) {
405                 device_.reset();
406         }
407
408         if (device_) {
409                 device_->session()->add_datafeed_callback([=]
410                         (shared_ptr<sigrok::Device> device, shared_ptr<Packet> packet) {
411                                 data_feed_in(device, packet);
412                         });
413
414                 update_signals();
415         }
416
417         device_changed();
418 }
419
420 void Session::set_default_device()
421 {
422         const list< shared_ptr<devices::HardwareDevice> > &devices =
423                 device_manager_.devices();
424
425         if (devices.empty())
426                 return;
427
428         // Try and find the demo device and select that by default
429         const auto iter = find_if(devices.begin(), devices.end(),
430                 [] (const shared_ptr<devices::HardwareDevice> &d) {
431                         return d->hardware_device()->driver()->name() == "demo";        });
432         set_device((iter == devices.end()) ? devices.front() : *iter);
433 }
434
435 void Session::load_init_file(const string &file_name, const string &format)
436 {
437         shared_ptr<InputFormat> input_format;
438
439         if (!format.empty()) {
440                 const map<string, shared_ptr<InputFormat> > formats =
441                         device_manager_.context()->input_formats();
442                 const auto iter = find_if(formats.begin(), formats.end(),
443                         [&](const pair<string, shared_ptr<InputFormat> > f) {
444                                 return f.first == format; });
445                 if (iter == formats.end()) {
446                         main_bar_->session_error(tr("Error"),
447                                 tr("Unexpected input format: %s").arg(QString::fromStdString(format)));
448                         return;
449                 }
450
451                 input_format = (*iter).second;
452         }
453
454         load_file(QString::fromStdString(file_name), input_format);
455 }
456
457 void Session::load_file(QString file_name,
458         shared_ptr<sigrok::InputFormat> format,
459         const map<string, Glib::VariantBase> &options)
460 {
461         const QString errorMessage(
462                 QString("Failed to load file %1").arg(file_name));
463
464         try {
465                 if (format)
466                         set_device(shared_ptr<devices::Device>(
467                                 new devices::InputFile(
468                                         device_manager_.context(),
469                                         file_name.toStdString(),
470                                         format, options)));
471                 else
472                         set_device(shared_ptr<devices::Device>(
473                                 new devices::SessionFile(
474                                         device_manager_.context(),
475                                         file_name.toStdString())));
476         } catch (Error e) {
477                 main_bar_->session_error(tr("Failed to load ") + file_name, e.what());
478                 set_default_device();
479                 main_bar_->update_device_list();
480                 return;
481         }
482
483         main_bar_->update_device_list();
484
485         start_capture([&, errorMessage](QString infoMessage) {
486                 main_bar_->session_error(errorMessage, infoMessage); });
487
488         set_name(QFileInfo(file_name).fileName());
489 }
490
491 Session::capture_state Session::get_capture_state() const
492 {
493         lock_guard<mutex> lock(sampling_mutex_);
494         return capture_state_;
495 }
496
497 void Session::start_capture(function<void (const QString)> error_handler)
498 {
499         if (!device_) {
500                 error_handler(tr("No active device set, can't start acquisition."));
501                 return;
502         }
503
504         stop_capture();
505
506         // Check that at least one channel is enabled
507         const shared_ptr<sigrok::Device> sr_dev = device_->device();
508         if (sr_dev) {
509                 const auto channels = sr_dev->channels();
510                 if (!any_of(channels.begin(), channels.end(),
511                         [](shared_ptr<Channel> channel) {
512                                 return channel->enabled(); })) {
513                         error_handler(tr("No channels enabled."));
514                         return;
515                 }
516         }
517
518         // Clear signal data
519         for (const shared_ptr<data::SignalData> d : all_signal_data_)
520                 d->clear();
521
522         // Revert name back to default name (e.g. "Session 1") for real devices
523         // as the (possibly saved) data is gone. File devices keep their name.
524         shared_ptr<devices::HardwareDevice> hw_device =
525                 dynamic_pointer_cast< devices::HardwareDevice >(device_);
526
527         if (hw_device) {
528                 name_ = default_name_;
529                 name_changed();
530         }
531
532         // Begin the session
533         sampling_thread_ = std::thread(
534                 &Session::sample_thread_proc, this, error_handler);
535 }
536
537 void Session::stop_capture()
538 {
539         if (get_capture_state() != Stopped)
540                 device_->stop();
541
542         // Check that sampling stopped
543         if (sampling_thread_.joinable())
544                 sampling_thread_.join();
545 }
546
547 void Session::register_view(shared_ptr<views::ViewBase> view)
548 {
549         if (views_.empty()) {
550                 main_view_ = view;
551         }
552
553         views_.push_back(view);
554
555         update_signals();
556 }
557
558 void Session::deregister_view(shared_ptr<views::ViewBase> view)
559 {
560         views_.remove_if([&](shared_ptr<views::ViewBase> v) { return v == view; });
561
562         if (views_.empty()) {
563                 main_view_.reset();
564
565                 // Without a view there can be no main bar
566                 main_bar_.reset();
567         }
568 }
569
570 bool Session::has_view(shared_ptr<views::ViewBase> view)
571 {
572         for (shared_ptr<views::ViewBase> v : views_)
573                 if (v == view)
574                         return true;
575
576         return false;
577 }
578
579 double Session::get_samplerate() const
580 {
581         double samplerate = 0.0;
582
583         for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
584                 assert(d);
585                 const vector< shared_ptr<pv::data::Segment> > segments =
586                         d->segments();
587                 for (const shared_ptr<pv::data::Segment> &s : segments)
588                         samplerate = max(samplerate, s->samplerate());
589         }
590         // If there is no sample rate given we use samples as unit
591         if (samplerate == 0.0)
592                 samplerate = 1.0;
593
594         return samplerate;
595 }
596
597 const unordered_set< shared_ptr<data::SignalBase> > Session::signalbases() const
598 {
599         return signalbases_;
600 }
601
602 #ifdef ENABLE_DECODE
603 bool Session::add_decoder(srd_decoder *const dec)
604 {
605         if (!dec)
606                 return false;
607
608         map<const srd_channel*, shared_ptr<data::SignalBase> > channels;
609         shared_ptr<data::DecoderStack> decoder_stack;
610
611         try {
612                 // Create the decoder
613                 decoder_stack = make_shared<data::DecoderStack>(*this, dec);
614
615                 // Make a list of all the channels
616                 vector<const srd_channel*> all_channels;
617                 for (const GSList *i = dec->channels; i; i = i->next)
618                         all_channels.push_back((const srd_channel*)i->data);
619                 for (const GSList *i = dec->opt_channels; i; i = i->next)
620                         all_channels.push_back((const srd_channel*)i->data);
621
622                 // Auto select the initial channels
623                 for (const srd_channel *pdch : all_channels)
624                         for (shared_ptr<data::SignalBase> b : signalbases_) {
625                                 if (b->logic_data()) {
626                                         if (QString::fromUtf8(pdch->name).toLower().
627                                                 contains(b->name().toLower()))
628                                                 channels[pdch] = b;
629                                 }
630                         }
631
632                 assert(decoder_stack);
633                 assert(!decoder_stack->stack().empty());
634                 assert(decoder_stack->stack().front());
635                 decoder_stack->stack().front()->set_channels(channels);
636
637                 // Create the decode signal
638                 shared_ptr<data::SignalBase> signalbase =
639                         make_shared<data::SignalBase>(nullptr, data::SignalBase::DecodeChannel);
640
641                 signalbase->set_decoder_stack(decoder_stack);
642                 signalbases_.insert(signalbase);
643
644                 for (shared_ptr<views::ViewBase> view : views_)
645                         view->add_decode_signal(signalbase);
646         } catch (runtime_error e) {
647                 return false;
648         }
649
650         signals_changed();
651
652         // Do an initial decode
653         decoder_stack->begin_decode();
654
655         return true;
656 }
657
658 void Session::remove_decode_signal(shared_ptr<data::SignalBase> signalbase)
659 {
660         signalbases_.erase(signalbase);
661
662         for (shared_ptr<views::ViewBase> view : views_)
663                 view->remove_decode_signal(signalbase);
664
665         signals_changed();
666 }
667 #endif
668
669 void Session::set_capture_state(capture_state state)
670 {
671         bool changed;
672
673         {
674                 lock_guard<mutex> lock(sampling_mutex_);
675                 changed = capture_state_ != state;
676                 capture_state_ = state;
677         }
678
679         if (changed)
680                 capture_state_changed(state);
681 }
682
683 void Session::update_signals()
684 {
685         if (!device_) {
686                 signalbases_.clear();
687                 logic_data_.reset();
688                 for (shared_ptr<views::ViewBase> view : views_) {
689                         view->clear_signals();
690 #ifdef ENABLE_DECODE
691                         view->clear_decode_signals();
692 #endif
693                 }
694                 return;
695         }
696
697         lock_guard<recursive_mutex> lock(data_mutex_);
698
699         const shared_ptr<sigrok::Device> sr_dev = device_->device();
700         if (!sr_dev) {
701                 signalbases_.clear();
702                 logic_data_.reset();
703                 for (shared_ptr<views::ViewBase> view : views_) {
704                         view->clear_signals();
705 #ifdef ENABLE_DECODE
706                         view->clear_decode_signals();
707 #endif
708                 }
709                 return;
710         }
711
712         // Detect what data types we will receive
713         auto channels = sr_dev->channels();
714         unsigned int logic_channel_count = count_if(
715                 channels.begin(), channels.end(),
716                 [] (shared_ptr<Channel> channel) {
717                         return channel->type() == sigrok::ChannelType::LOGIC; });
718
719         // Create data containers for the logic data segments
720         {
721                 lock_guard<recursive_mutex> data_lock(data_mutex_);
722
723                 if (logic_channel_count == 0) {
724                         logic_data_.reset();
725                 } else if (!logic_data_ ||
726                         logic_data_->num_channels() != logic_channel_count) {
727                         logic_data_.reset(new data::Logic(
728                                 logic_channel_count));
729                         assert(logic_data_);
730                 }
731         }
732
733         // Make the signals list
734         for (shared_ptr<views::ViewBase> viewbase : views_) {
735                 views::TraceView::View *trace_view =
736                         qobject_cast<views::TraceView::View*>(viewbase.get());
737
738                 if (trace_view) {
739                         unordered_set< shared_ptr<views::TraceView::Signal> >
740                                 prev_sigs(trace_view->signals());
741                         trace_view->clear_signals();
742
743                         for (auto channel : sr_dev->channels()) {
744                                 shared_ptr<data::SignalBase> signalbase;
745                                 shared_ptr<views::TraceView::Signal> signal;
746
747                                 // Find the channel in the old signals
748                                 const auto iter = find_if(
749                                         prev_sigs.cbegin(), prev_sigs.cend(),
750                                         [&](const shared_ptr<views::TraceView::Signal> &s) {
751                                                 return s->base()->channel() == channel;
752                                         });
753                                 if (iter != prev_sigs.end()) {
754                                         // Copy the signal from the old set to the new
755                                         signal = *iter;
756                                         trace_view->add_signal(signal);
757                                 } else {
758                                         // Find the signalbase for this channel if possible
759                                         signalbase.reset();
760                                         for (const shared_ptr<data::SignalBase> b : signalbases_)
761                                                 if (b->channel() == channel)
762                                                         signalbase = b;
763
764                                         switch(channel->type()->id()) {
765                                         case SR_CHANNEL_LOGIC:
766                                                 if (!signalbase) {
767                                                         signalbase = make_shared<data::SignalBase>(channel,
768                                                                 data::SignalBase::LogicChannel);
769                                                         signalbases_.insert(signalbase);
770
771                                                         all_signal_data_.insert(logic_data_);
772                                                         signalbase->set_data(logic_data_);
773
774                                                         connect(this, SIGNAL(capture_state_changed(int)),
775                                                                 signalbase.get(), SLOT(on_capture_state_changed(int)));
776                                                 }
777
778                                                 signal = shared_ptr<views::TraceView::Signal>(
779                                                         new views::TraceView::LogicSignal(*this,
780                                                                 device_, signalbase));
781                                                 trace_view->add_signal(signal);
782                                                 break;
783
784                                         case SR_CHANNEL_ANALOG:
785                                         {
786                                                 if (!signalbase) {
787                                                         signalbase = make_shared<data::SignalBase>(channel,
788                                                                 data::SignalBase::AnalogChannel);
789                                                         signalbases_.insert(signalbase);
790
791                                                         shared_ptr<data::Analog> data(new data::Analog());
792                                                         all_signal_data_.insert(data);
793                                                         signalbase->set_data(data);
794
795                                                         connect(this, SIGNAL(capture_state_changed(int)),
796                                                                 signalbase.get(), SLOT(on_capture_state_changed(int)));
797                                                 }
798
799                                                 signal = shared_ptr<views::TraceView::Signal>(
800                                                         new views::TraceView::AnalogSignal(
801                                                                 *this, signalbase));
802                                                 trace_view->add_signal(signal);
803                                                 break;
804                                         }
805
806                                         default:
807                                                 assert(false);
808                                                 break;
809                                         }
810                                 }
811                         }
812                 }
813         }
814
815         signals_changed();
816 }
817
818 shared_ptr<data::SignalBase> Session::signalbase_from_channel(
819         shared_ptr<sigrok::Channel> channel) const
820 {
821         for (shared_ptr<data::SignalBase> sig : signalbases_) {
822                 assert(sig);
823                 if (sig->channel() == channel)
824                         return sig;
825         }
826         return shared_ptr<data::SignalBase>();
827 }
828
829 void Session::sample_thread_proc(function<void (const QString)> error_handler)
830 {
831         assert(error_handler);
832
833         if (!device_)
834                 return;
835
836         cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
837
838         out_of_memory_ = false;
839
840         try {
841                 device_->start();
842         } catch (Error e) {
843                 error_handler(e.what());
844                 return;
845         }
846
847         set_capture_state(device_->session()->trigger() ?
848                 AwaitingTrigger : Running);
849
850         device_->run();
851         set_capture_state(Stopped);
852
853         // Confirm that SR_DF_END was received
854         if (cur_logic_segment_) {
855                 qDebug("SR_DF_END was not received.");
856                 assert(false);
857         }
858
859         // Optimize memory usage
860         free_unused_memory();
861
862         // We now have unsaved data unless we just "captured" from a file
863         shared_ptr<devices::File> file_device =
864                 dynamic_pointer_cast<devices::File>(device_);
865
866         if (!file_device)
867                 data_saved_ = false;
868
869         if (out_of_memory_)
870                 error_handler(tr("Out of memory, acquisition stopped."));
871 }
872
873 void Session::free_unused_memory()
874 {
875         for (shared_ptr<data::SignalData> data : all_signal_data_) {
876                 const vector< shared_ptr<data::Segment> > segments = data->segments();
877
878                 for (shared_ptr<data::Segment> segment : segments) {
879                         segment->free_unused_memory();
880                 }
881         }
882 }
883
884 void Session::feed_in_header()
885 {
886         cur_samplerate_ = device_->read_config<uint64_t>(ConfigKey::SAMPLERATE);
887 }
888
889 void Session::feed_in_meta(shared_ptr<Meta> meta)
890 {
891         for (auto entry : meta->config()) {
892                 switch (entry.first->id()) {
893                 case SR_CONF_SAMPLERATE:
894                         // We can't rely on the header to always contain the sample rate,
895                         // so in case it's supplied via a meta packet, we use it.
896                         if (!cur_samplerate_)
897                                 cur_samplerate_ = g_variant_get_uint64(entry.second.gobj());
898
899                         /// @todo handle samplerate changes
900                         break;
901                 default:
902                         // Unknown metadata is not an error.
903                         break;
904                 }
905         }
906
907         signals_changed();
908 }
909
910 void Session::feed_in_trigger()
911 {
912         // The channel containing most samples should be most accurate
913         uint64_t sample_count = 0;
914
915         {
916                 for (const shared_ptr<pv::data::SignalData> d : all_signal_data_) {
917                         assert(d);
918                         uint64_t temp_count = 0;
919
920                         const vector< shared_ptr<pv::data::Segment> > segments =
921                                 d->segments();
922                         for (const shared_ptr<pv::data::Segment> &s : segments)
923                                 temp_count += s->get_sample_count();
924
925                         if (temp_count > sample_count)
926                                 sample_count = temp_count;
927                 }
928         }
929
930         trigger_event(sample_count / get_samplerate());
931 }
932
933 void Session::feed_in_frame_begin()
934 {
935         if (cur_logic_segment_ || !cur_analog_segments_.empty())
936                 frame_began();
937 }
938
939 void Session::feed_in_logic(shared_ptr<Logic> logic)
940 {
941         lock_guard<recursive_mutex> lock(data_mutex_);
942
943         if (!logic_data_) {
944                 // The only reason logic_data_ would not have been created is
945                 // if it was not possible to determine the signals when the
946                 // device was created.
947                 update_signals();
948         }
949
950         if (!cur_logic_segment_) {
951                 // This could be the first packet after a trigger
952                 set_capture_state(Running);
953
954                 // Create a new data segment
955                 cur_logic_segment_ = make_shared<data::LogicSegment>(
956                         *logic_data_, logic->unit_size(), cur_samplerate_);
957                 logic_data_->push_segment(cur_logic_segment_);
958
959                 // @todo Putting this here means that only listeners querying
960                 // for logic will be notified. Currently the only user of
961                 // frame_began is DecoderStack, but in future we need to signal
962                 // this after both analog and logic sweeps have begun.
963                 frame_began();
964         }
965
966         cur_logic_segment_->append_payload(logic);
967
968         data_received();
969 }
970
971 void Session::feed_in_analog(shared_ptr<Analog> analog)
972 {
973         lock_guard<recursive_mutex> lock(data_mutex_);
974
975         const vector<shared_ptr<Channel>> channels = analog->channels();
976         const unsigned int channel_count = channels.size();
977         const size_t sample_count = analog->num_samples() / channel_count;
978         const float *data = static_cast<const float *>(analog->data_pointer());
979         bool sweep_beginning = false;
980
981         if (signalbases_.empty())
982                 update_signals();
983
984         for (auto channel : channels) {
985                 shared_ptr<data::AnalogSegment> segment;
986
987                 // Try to get the segment of the channel
988                 const map< shared_ptr<Channel>, shared_ptr<data::AnalogSegment> >::
989                         iterator iter = cur_analog_segments_.find(channel);
990                 if (iter != cur_analog_segments_.end())
991                         segment = (*iter).second;
992                 else {
993                         // If no segment was found, this means we haven't
994                         // created one yet. i.e. this is the first packet
995                         // in the sweep containing this segment.
996                         sweep_beginning = true;
997
998                         // Find the analog data associated with the channel
999                         shared_ptr<data::SignalBase> base = signalbase_from_channel(channel);
1000                         assert(base);
1001
1002                         shared_ptr<data::Analog> data(base->analog_data());
1003                         assert(data);
1004
1005                         // Create a segment, keep it in the maps of channels
1006                         segment = make_shared<data::AnalogSegment>(
1007                                 *data, cur_samplerate_);
1008                         cur_analog_segments_[channel] = segment;
1009
1010                         // Push the segment into the analog data.
1011                         data->push_segment(segment);
1012                 }
1013
1014                 assert(segment);
1015
1016                 // Append the samples in the segment
1017                 segment->append_interleaved_samples(data++, sample_count,
1018                         channel_count);
1019         }
1020
1021         if (sweep_beginning) {
1022                 // This could be the first packet after a trigger
1023                 set_capture_state(Running);
1024         }
1025
1026         data_received();
1027 }
1028
1029 void Session::data_feed_in(shared_ptr<sigrok::Device> device,
1030         shared_ptr<Packet> packet)
1031 {
1032         static bool frame_began = false;
1033
1034         (void)device;
1035
1036         assert(device);
1037         assert(device == device_->device());
1038         assert(packet);
1039
1040         switch (packet->type()->id()) {
1041         case SR_DF_HEADER:
1042                 feed_in_header();
1043                 break;
1044
1045         case SR_DF_META:
1046                 feed_in_meta(dynamic_pointer_cast<Meta>(packet->payload()));
1047                 break;
1048
1049         case SR_DF_TRIGGER:
1050                 feed_in_trigger();
1051                 break;
1052
1053         case SR_DF_FRAME_BEGIN:
1054                 feed_in_frame_begin();
1055                 frame_began = true;
1056                 break;
1057
1058         case SR_DF_LOGIC:
1059                 try {
1060                         feed_in_logic(dynamic_pointer_cast<Logic>(packet->payload()));
1061                 } catch (bad_alloc) {
1062                         out_of_memory_ = true;
1063                         device_->stop();
1064                 }
1065                 break;
1066
1067         case SR_DF_ANALOG:
1068                 try {
1069                         feed_in_analog(dynamic_pointer_cast<Analog>(packet->payload()));
1070                 } catch (bad_alloc) {
1071                         out_of_memory_ = true;
1072                         device_->stop();
1073                 }
1074                 break;
1075
1076         case SR_DF_FRAME_END:
1077         case SR_DF_END:
1078         {
1079                 {
1080                         lock_guard<recursive_mutex> lock(data_mutex_);
1081                         cur_logic_segment_.reset();
1082                         cur_analog_segments_.clear();
1083                 }
1084                 if (frame_began) {
1085                         frame_began = false;
1086                         frame_ended();
1087                 }
1088                 break;
1089         }
1090         default:
1091                 break;
1092         }
1093 }
1094
1095 void Session::on_data_saved()
1096 {
1097         data_saved_ = true;
1098 }
1099
1100 } // namespace pv