fix a bad transition in the transportFSM.
[ardour.git] / libs / ardour / control_protocol_manager.cc
1 /*
2  * Copyright (C) 2006-2012 David Robillard <d@drobilla.net>
3  * Copyright (C) 2006-2017 Paul Davis <paul@linuxaudiosystems.com>
4  * Copyright (C) 2007-2016 Tim Mayberry <mojofunk@gmail.com>
5  * Copyright (C) 2009-2011 Carl Hetherington <carl@carlh.net>
6  * Copyright (C) 2014 John Emmas <john@creativepost.co.uk>
7  * Copyright (C) 2015-2018 Robin Gareus <robin@gareus.org>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License along
20  * with this program; if not, write to the Free Software Foundation, Inc.,
21  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22  */
23
24 #include <glibmm/module.h>
25
26 #include <glibmm/fileutils.h>
27
28 #include "pbd/compose.h"
29 #include "pbd/event_loop.h"
30 #include "pbd/file_utils.h"
31 #include "pbd/error.h"
32
33 #include "control_protocol/control_protocol.h"
34
35 #include "ardour/debug.h"
36 #include "ardour/control_protocol_manager.h"
37
38 #include "ardour/search_paths.h"
39 #include "ardour/selection.h"
40 #include "ardour/session.h"
41
42 using namespace ARDOUR;
43 using namespace std;
44 using namespace PBD;
45
46 #include "pbd/i18n.h"
47
48 ControlProtocolManager* ControlProtocolManager::_instance = 0;
49 const string ControlProtocolManager::state_node_name = X_("ControlProtocols");
50 PBD::Signal1<void,StripableNotificationListPtr> ControlProtocolManager::StripableSelectionChanged;
51
52 ControlProtocolInfo::~ControlProtocolInfo ()
53 {
54         if (protocol && descriptor) {
55                 descriptor->destroy (descriptor, protocol);
56                 protocol = 0;
57         }
58
59         delete state; state = 0;
60
61         if (descriptor) {
62                 delete (Glib::Module*) descriptor->module;
63                 descriptor = 0;
64         }
65 }
66
67 ControlProtocolManager::ControlProtocolManager ()
68 {
69 }
70
71 ControlProtocolManager::~ControlProtocolManager()
72 {
73         Glib::Threads::RWLock::WriterLock lm (protocols_lock);
74
75         for (list<ControlProtocol*>::iterator i = control_protocols.begin(); i != control_protocols.end(); ++i) {
76                 delete (*i);
77         }
78
79         control_protocols.clear ();
80
81
82         for (list<ControlProtocolInfo*>::iterator p = control_protocol_info.begin(); p != control_protocol_info.end(); ++p) {
83                 (*p)->protocol = 0; // protocol was already destroyed above.
84                 delete (*p);
85         }
86
87         control_protocol_info.clear();
88 }
89
90 void
91 ControlProtocolManager::set_session (Session* s)
92 {
93         SessionHandlePtr::set_session (s);
94
95         if (!_session) {
96                 return;
97         }
98
99         {
100                 Glib::Threads::RWLock::ReaderLock lm (protocols_lock);
101
102                 for (list<ControlProtocolInfo*>::iterator i = control_protocol_info.begin(); i != control_protocol_info.end(); ++i) {
103                         if ((*i)->requested || (*i)->mandatory) {
104                                 (void) activate (**i);
105                         }
106                 }
107         }
108
109         CoreSelection::StripableAutomationControls sac;
110         _session->selection().get_stripables (sac);
111
112         if (!sac.empty()) {
113                 StripableNotificationListPtr v (new StripableNotificationList);
114                 for (CoreSelection::StripableAutomationControls::iterator i = sac.begin(); i != sac.end(); ++i) {
115                         if ((*i).stripable) {
116                                 v->push_back (boost::weak_ptr<Stripable> ((*i).stripable));
117                         }
118                 }
119                 if (!v->empty()) {
120                         StripableSelectionChanged (v); /* EMIT SIGNAL */
121                 }
122         }
123 }
124
125 int
126 ControlProtocolManager::activate (ControlProtocolInfo& cpi)
127 {
128         ControlProtocol* cp;
129
130         cpi.requested = true;
131
132         if (cpi.protocol && cpi.protocol->active()) {
133                 warning << string_compose (_("Control protocol %1 was already active."), cpi.name) << endmsg;
134                 return 0;
135         }
136
137         if ((cp = instantiate (cpi)) == 0) {
138                 return -1;
139         }
140
141         /* we split the set_state() and set_active() operations so that
142            protocols that need state to configure themselves (e.g. "What device
143            is connected, or supposed to be connected?") can get it before
144            actually starting any interaction.
145         */
146
147         if (cpi.state) {
148                 /* force this by tweaking the internals of the state
149                  * XMLNode. Ugh.
150                  */
151                 cp->set_state (*cpi.state, Stateful::loading_state_version);
152         } else {
153                 /* guarantee a call to
154                    set_state() whether we have
155                    existing state or not
156                 */
157                 cp->set_state (XMLNode(""), Stateful::loading_state_version);
158         }
159
160         if (cp->set_active (true)) {
161                 error << string_compose (_("Control protocol support for %1 failed to activate"), cpi.name) << endmsg;
162                 teardown (cpi, false);
163         }
164
165         return 0;
166 }
167
168 int
169 ControlProtocolManager::deactivate (ControlProtocolInfo& cpi)
170 {
171         cpi.requested = false;
172         return teardown (cpi, true);
173 }
174
175 void
176 ControlProtocolManager::session_going_away()
177 {
178         SessionHandlePtr::session_going_away ();
179         /* Session::destroy() will explicitly call drop_protocols() so we don't
180          * have to worry about that here.
181          */
182 }
183
184 void
185 ControlProtocolManager::drop_protocols ()
186 {
187         /* called explicitly by Session::destroy() so that we can clean up
188          * before the process cycle stops and ports vanish.
189          */
190
191         Glib::Threads::RWLock::WriterLock lm (protocols_lock);
192
193         for (list<ControlProtocolInfo*>::iterator p = control_protocol_info.begin(); p != control_protocol_info.end(); ++p) {
194                 // mark existing protocols as requested
195                 // otherwise the ControlProtocol instances are not recreated in set_session
196                 if ((*p)->protocol) {
197                         (*p)->requested = true;
198                         (*p)->protocol = 0;
199                         ProtocolStatusChange (*p); /* EMIT SIGNAL */
200                 }
201         }
202
203         for (list<ControlProtocol*>::iterator p = control_protocols.begin(); p != control_protocols.end(); ++p) {
204                 delete *p;
205         }
206
207         control_protocols.clear ();
208 }
209
210 ControlProtocol*
211 ControlProtocolManager::instantiate (ControlProtocolInfo& cpi)
212 {
213         /* CALLER MUST HOLD LOCK */
214
215         if (_session == 0) {
216                 return 0;
217         }
218
219         cpi.descriptor = get_descriptor (cpi.path);
220
221         DEBUG_TRACE (DEBUG::ControlProtocols, string_compose ("instantiating %1\n", cpi.name));
222
223         if (cpi.descriptor == 0) {
224                 error << string_compose (_("control protocol name \"%1\" has no descriptor"), cpi.name) << endmsg;
225                 return 0;
226         }
227
228         DEBUG_TRACE (DEBUG::ControlProtocols, string_compose ("initializing %1\n", cpi.name));
229
230         if ((cpi.protocol = cpi.descriptor->initialize (cpi.descriptor, _session)) == 0) {
231                 error << string_compose (_("control protocol name \"%1\" could not be initialized"), cpi.name) << endmsg;
232                 return 0;
233         }
234
235         control_protocols.push_back (cpi.protocol);
236
237         ProtocolStatusChange (&cpi);
238
239         return cpi.protocol;
240 }
241
242 int
243 ControlProtocolManager::teardown (ControlProtocolInfo& cpi, bool lock_required)
244 {
245         if (!cpi.protocol) {
246
247                 /* we could still have a descriptor even if the protocol was
248                    never instantiated. Close the associated module (shared
249                    object/DLL) and make sure we forget about it.
250                 */
251
252                 if (cpi.descriptor) {
253                         cerr << "Closing descriptor for CPI anyway\n";
254                         delete (Glib::Module*) cpi.descriptor->module;
255                         cpi.descriptor = 0;
256                 }
257
258                 return 0;
259         }
260
261         if (!cpi.descriptor) {
262                 return 0;
263         }
264
265         if (cpi.mandatory) {
266                 return 0;
267         }
268
269         /* save current state */
270
271         delete cpi.state;
272         cpi.state = new XMLNode (cpi.protocol->get_state());
273         cpi.state->set_property (X_("active"), false);
274
275         cpi.descriptor->destroy (cpi.descriptor, cpi.protocol);
276
277         if (lock_required) {
278                 /* the lock is required when the protocol is torn down by a user from the GUI. */
279                 Glib::Threads::RWLock::WriterLock lm (protocols_lock);
280                 list<ControlProtocol*>::iterator p = find (control_protocols.begin(), control_protocols.end(), cpi.protocol);
281                 if (p != control_protocols.end()) {
282                         control_protocols.erase (p);
283                 } else {
284                         cerr << "Programming error: ControlProtocolManager::teardown() called for " << cpi.name << ", but it was not found in control_protocols" << endl;
285                 }
286         } else {
287                 list<ControlProtocol*>::iterator p = find (control_protocols.begin(), control_protocols.end(), cpi.protocol);
288                 if (p != control_protocols.end()) {
289                         control_protocols.erase (p);
290                 } else {
291                         cerr << "Programming error: ControlProtocolManager::teardown() called for " << cpi.name << ", but it was not found in control_protocols" << endl;
292                 }
293         }
294
295         cpi.protocol = 0;
296
297         delete (Glib::Module*) cpi.descriptor->module;
298         /* cpi->descriptor is now inaccessible since dlclose() or equivalent
299          * has been performed, and the descriptor is (or could be) a static
300          * object made accessible by dlopen().
301          */
302         cpi.descriptor = 0;
303
304         ProtocolStatusChange (&cpi);
305
306         return 0;
307 }
308
309 void
310 ControlProtocolManager::load_mandatory_protocols ()
311 {
312         if (_session == 0) {
313                 return;
314         }
315
316         Glib::Threads::RWLock::ReaderLock lm (protocols_lock);
317
318         for (list<ControlProtocolInfo*>::iterator i = control_protocol_info.begin(); i != control_protocol_info.end(); ++i) {
319                 if ((*i)->mandatory && ((*i)->protocol == 0)) {
320                         DEBUG_TRACE (DEBUG::ControlProtocols,
321                                      string_compose (_("Instantiating mandatory control protocol %1"), (*i)->name));
322                         instantiate (**i);
323                 }
324         }
325 }
326
327 void
328 ControlProtocolManager::discover_control_protocols ()
329 {
330         vector<std::string> cp_modules;
331
332 #ifdef COMPILER_MSVC
333    /**
334     * Different build targets (Debug / Release etc) use different versions
335     * of the 'C' runtime (which can't be 'mixed & matched'). Therefore, in
336     * case the supplied search path contains multiple version(s) of a given
337     * module, only select the one(s) which match the current build target
338     */
339         #if defined (_DEBUG)
340                 Glib::PatternSpec dll_extension_pattern("*D.dll");
341         #elif defined (RDC_BUILD)
342                 Glib::PatternSpec dll_extension_pattern("*RDC.dll");
343         #elif defined (_WIN64)
344                 Glib::PatternSpec dll_extension_pattern("*64.dll");
345         #else
346                 Glib::PatternSpec dll_extension_pattern("*32.dll");
347         #endif
348 #else
349         Glib::PatternSpec dll_extension_pattern("*.dll");
350 #endif
351
352         Glib::PatternSpec so_extension_pattern("*.so");
353         Glib::PatternSpec dylib_extension_pattern("*.dylib");
354
355         find_files_matching_pattern (cp_modules, control_protocol_search_path (),
356                                      dll_extension_pattern);
357
358         find_files_matching_pattern (cp_modules, control_protocol_search_path (),
359                                      so_extension_pattern);
360
361         find_files_matching_pattern (cp_modules, control_protocol_search_path (),
362                                      dylib_extension_pattern);
363
364         DEBUG_TRACE (DEBUG::ControlProtocols,
365                      string_compose (_("looking for control protocols in %1\n"), control_protocol_search_path().to_string()));
366
367         for (vector<std::string>::iterator i = cp_modules.begin(); i != cp_modules.end(); ++i) {
368                 control_protocol_discover (*i);
369         }
370 }
371
372 int
373 ControlProtocolManager::control_protocol_discover (string path)
374 {
375         ControlProtocolDescriptor* descriptor;
376
377 #ifdef __APPLE__
378         /* don't load OS X shared objects that are just symlinks to the real thing.
379          */
380
381         if (path.find (".dylib") && Glib::file_test (path, Glib::FILE_TEST_IS_SYMLINK)) {
382                 return 0;
383         }
384 #endif
385
386         if ((descriptor = get_descriptor (path)) != 0) {
387
388                 if (!descriptor->probe (descriptor)) {
389                         warning << string_compose (_("Control protocol %1 not usable"), descriptor->name) << endmsg;
390                 } else {
391
392                         ControlProtocolInfo* cpi = new ControlProtocolInfo ();
393
394                         cpi->descriptor = descriptor;
395                         cpi->name = descriptor->name;
396                         cpi->path = path;
397                         cpi->protocol = 0;
398                         cpi->requested = false;
399                         cpi->mandatory = descriptor->mandatory;
400                         cpi->supports_feedback = descriptor->supports_feedback;
401                         cpi->state = 0;
402
403                         control_protocol_info.push_back (cpi);
404
405                         DEBUG_TRACE (DEBUG::ControlProtocols,
406                                      string_compose(_("Control surface protocol discovered: \"%1\"\n"), cpi->name));
407                 }
408         }
409
410         return 0;
411 }
412
413 ControlProtocolDescriptor*
414 ControlProtocolManager::get_descriptor (string path)
415 {
416         Glib::Module* module = new Glib::Module(path);
417         ControlProtocolDescriptor *descriptor = 0;
418         ControlProtocolDescriptor* (*dfunc)(void);
419         void* func = 0;
420
421         if (!(*module)) {
422                 error << string_compose(_("ControlProtocolManager: cannot load module \"%1\" (%2)"), path, Glib::Module::get_last_error()) << endmsg;
423                 delete module;
424                 return 0;
425         }
426
427         if (!module->get_symbol("protocol_descriptor", func)) {
428                 error << string_compose(_("ControlProtocolManager: module \"%1\" has no descriptor function."), path) << endmsg;
429                 error << Glib::Module::get_last_error() << endmsg;
430                 delete module;
431                 return 0;
432         }
433
434         dfunc = (ControlProtocolDescriptor* (*)(void))func;
435         descriptor = dfunc();
436
437         if (descriptor) {
438                 descriptor->module = (void*)module;
439         }
440
441         return descriptor;
442 }
443
444 void
445 ControlProtocolManager::foreach_known_protocol (boost::function<void(const ControlProtocolInfo*)> method)
446 {
447         for (list<ControlProtocolInfo*>::iterator i = control_protocol_info.begin(); i != control_protocol_info.end(); ++i) {
448                 method (*i);
449         }
450 }
451
452 ControlProtocolInfo*
453 ControlProtocolManager::cpi_by_name (string name)
454 {
455         for (list<ControlProtocolInfo*>::iterator i = control_protocol_info.begin(); i != control_protocol_info.end(); ++i) {
456                 if (name == (*i)->name) {
457                         return *i;
458                 }
459         }
460         return 0;
461 }
462
463 int
464 ControlProtocolManager::set_state (const XMLNode& node, int session_specific_state /* here: not version */)
465 {
466         XMLNodeList clist;
467         XMLNodeConstIterator citer;
468
469         Glib::Threads::RWLock::WriterLock lm (protocols_lock);
470
471         clist = node.children();
472
473         for (citer = clist.begin(); citer != clist.end(); ++citer) {
474                 XMLNode const * child = *citer;
475
476                 if (child->name() == X_("Protocol")) {
477
478                         bool active;
479                         std::string name;
480                         if (!child->get_property (X_("active"), active) ||
481                             !child->get_property (X_("name"), name)) {
482                                 continue;
483                         }
484
485                         ControlProtocolInfo* cpi = cpi_by_name (name);
486
487                         if (cpi) {
488                                 DEBUG_TRACE (DEBUG::ControlProtocols, string_compose ("Protocolstate %1 %2\n", name, active ? "active" : "inactive"));
489
490                                 if (active) {
491                                         delete cpi->state;
492                                         cpi->state = new XMLNode (**citer);
493                                         cpi->state->set_property (X_("session-state"), session_specific_state ? true : false);
494                                         if (_session) {
495                                                 instantiate (*cpi);
496                                         } else {
497                                                 cpi->requested = true;
498                                         }
499                                 } else {
500                                         if (!cpi->state) {
501                                                 cpi->state = new XMLNode (**citer);
502                                                 cpi->state->set_property (X_("active"), false);
503                                                 cpi->state->set_property (X_("session-state"), session_specific_state ? true : false);
504                                         }
505                                         cpi->requested = false;
506                                         if (_session) {
507                                                 teardown (*cpi, false);
508                                         }
509                                 }
510                         } else {
511                                 std::cerr << "protocol " << name << " not found\n";
512                         }
513                 }
514         }
515
516         return 0;
517 }
518
519 XMLNode&
520 ControlProtocolManager::get_state ()
521 {
522         XMLNode* root = new XMLNode (state_node_name);
523         Glib::Threads::RWLock::ReaderLock lm (protocols_lock);
524
525         for (list<ControlProtocolInfo*>::iterator i = control_protocol_info.begin(); i != control_protocol_info.end(); ++i) {
526
527                 if ((*i)->protocol) {
528                         XMLNode& child_state ((*i)->protocol->get_state());
529                         child_state.set_property (X_("active"), true);
530                         delete ((*i)->state);
531                         (*i)->state = new XMLNode (child_state);
532                         root->add_child_nocopy (child_state);
533                 } else if ((*i)->state) {
534                         XMLNode* child_state = new XMLNode (*(*i)->state);
535                         child_state->set_property (X_("active"), false);
536                         root->add_child_nocopy (*child_state);
537                 } else {
538                         XMLNode* child_state = new XMLNode (X_("Protocol"));
539                         child_state->set_property (X_("name"), (*i)->name);
540                         child_state->set_property (X_("active"), false);
541                         root->add_child_nocopy (*child_state);
542                 }
543
544         }
545
546         return *root;
547 }
548
549
550 ControlProtocolManager&
551 ControlProtocolManager::instance ()
552 {
553         if (_instance == 0) {
554                 _instance = new ControlProtocolManager ();
555         }
556
557         return *_instance;
558 }
559
560 void
561 ControlProtocolManager::midi_connectivity_established ()
562 {
563         Glib::Threads::RWLock::ReaderLock lm (protocols_lock);
564
565         for (list<ControlProtocol*>::iterator p = control_protocols.begin(); p != control_protocols.end(); ++p) {
566                 (*p)->midi_connectivity_established ();
567         }
568 }
569
570 void
571 ControlProtocolManager::register_request_buffer_factories ()
572 {
573         Glib::Threads::RWLock::ReaderLock lm (protocols_lock);
574
575         for (list<ControlProtocolInfo*>::iterator i = control_protocol_info.begin(); i != control_protocol_info.end(); ++i) {
576
577                 if ((*i)->descriptor == 0) {
578                         warning << string_compose (_("Control protocol \"%1\" has no descriptor"), (*i)->name) << endmsg;
579                         continue;
580                 }
581
582                 if ((*i)->descriptor->request_buffer_factory) {
583                         EventLoop::register_request_buffer_factory ((*i)->descriptor->name, (*i)->descriptor->request_buffer_factory);
584                 }
585         }
586 }
587
588 void
589 ControlProtocolManager::stripable_selection_changed (StripableNotificationListPtr sp)
590 {
591         /* this sets up the (static) data structures owned by ControlProtocol
592            that are "shared" across all control protocols.
593         */
594
595         DEBUG_TRACE (DEBUG::Selection, string_compose ("Surface manager: selection changed, now %1 stripables\n", sp ? sp->size() : -1));
596         StripableSelectionChanged (sp); /* EMIT SIGNAL */
597
598         /* now give each protocol the chance to respond to the selection change
599          */
600
601         {
602                 Glib::Threads::RWLock::ReaderLock lm (protocols_lock);
603
604                 for (list<ControlProtocol*>::iterator p = control_protocols.begin(); p != control_protocols.end(); ++p) {
605                         DEBUG_TRACE (DEBUG::Selection, string_compose ("selection change notification for surface \"%1\"\n", (*p)->name()));
606                         (*p)->stripable_selection_changed ();
607                 }
608         }
609 }