Fix crash when X11 is not available for VST UIs
[ardour.git] / gtk2_ardour / port_group.cc
1 /*
2  * Copyright (C) 2009-2012 Carl Hetherington <carl@carlh.net>
3  * Copyright (C) 2009-2012 David Robillard <d@drobilla.net>
4  * Copyright (C) 2009-2018 Paul Davis <paul@linuxaudiosystems.com>
5  * Copyright (C) 2012-2016 Robin Gareus <robin@gareus.org>
6  * Copyright (C) 2016 Julien "_FrnchFrgg_" RIVAUD <frnchfrgg@free.fr>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with this program; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22
23 #include <cstring>
24 #include <boost/shared_ptr.hpp>
25 #include <boost/algorithm/string.hpp>
26
27 #include "midi++/mmc.h"
28
29 #include "ardour/async_midi_port.h"
30 #include "ardour/audioengine.h"
31 #include "ardour/auditioner.h"
32 #include "ardour/bundle.h"
33 #include "ardour/control_protocol_manager.h"
34 #include "ardour/io_processor.h"
35 #include "ardour/midi_port.h"
36 #include "ardour/midiport_manager.h"
37 #include "ardour/plugin_insert.h"
38 #include "ardour/port.h"
39 #include "ardour/profile.h"
40 #include "ardour/session.h"
41 #include "ardour/sidechain.h"
42 #include "ardour/user_bundle.h"
43
44 #include "control_protocol/control_protocol.h"
45
46 #include "gui_thread.h"
47 #include "port_group.h"
48 #include "port_matrix.h"
49 #include "time_axis_view.h"
50 #include "public_editor.h"
51
52 #include "pbd/i18n.h"
53
54 using namespace std;
55 using namespace Gtk;
56 using namespace ARDOUR;
57
58 /** PortGroup constructor.
59  * @param n Name.
60  */
61 PortGroup::PortGroup (std::string const & n)
62         : name (n)
63 {
64
65 }
66
67 PortGroup::~PortGroup()
68 {
69         for (BundleList::iterator i = _bundles.begin(); i != _bundles.end(); ++i) {
70                 delete *i;
71         }
72         _bundles.clear ();
73 }
74
75 /** Add a bundle to a group.
76  *  @param b Bundle.
77  *  @param allow_dups true to allow the group to contain more than one bundle with the same port, otherwise false.
78  */
79 void
80 PortGroup::add_bundle (boost::shared_ptr<Bundle> b, bool allow_dups)
81 {
82         add_bundle_internal (b, boost::shared_ptr<IO> (), false, Gdk::Color (), allow_dups);
83 }
84
85 /** Add a bundle to a group.
86  *  @param b Bundle.
87  *  @param io IO whose ports are in the bundle.
88  */
89 void
90 PortGroup::add_bundle (boost::shared_ptr<Bundle> b, boost::shared_ptr<IO> io)
91 {
92         add_bundle_internal (b, io, false, Gdk::Color (), false);
93 }
94
95 /** Add a bundle to a group.
96  *  @param b Bundle.
97  *  @param c Colour to represent the bundle with.
98  */
99 void
100 PortGroup::add_bundle (boost::shared_ptr<Bundle> b, boost::shared_ptr<IO> io, Gdk::Color c)
101 {
102         add_bundle_internal (b, io, true, c, false);
103 }
104
105 PortGroup::BundleRecord::BundleRecord (boost::shared_ptr<ARDOUR::Bundle> b, boost::shared_ptr<ARDOUR::IO> iop, Gdk::Color c, bool has_c)
106         : bundle (b)
107         , io (iop)
108         , colour (c)
109         , has_colour (has_c)
110 {
111 }
112
113 void
114 PortGroup::add_bundle_internal (boost::shared_ptr<Bundle> b, boost::shared_ptr<IO> io, bool has_colour, Gdk::Color colour, bool allow_dups)
115 {
116         assert (b.get());
117
118         if (!allow_dups) {
119
120                 /* don't add this bundle if we already have one with the same ports */
121
122                 BundleList::iterator i = _bundles.begin ();
123                 while (i != _bundles.end() && b->has_same_ports ((*i)->bundle) == false) {
124                         ++i;
125                 }
126
127                 if (i != _bundles.end ()) {
128                         return;
129                 }
130         }
131
132         BundleRecord* br = new BundleRecord (b, io, colour, has_colour);
133         b->Changed.connect (br->changed_connection, invalidator (*this), boost::bind (&PortGroup::bundle_changed, this, _1), gui_context());
134         _bundles.push_back (br);
135
136         Changed ();
137 }
138
139 void
140 PortGroup::remove_bundle (boost::shared_ptr<Bundle> b)
141 {
142         assert (b.get());
143
144         BundleList::iterator i = _bundles.begin ();
145         while (i != _bundles.end() && (*i)->bundle != b) {
146                 ++i;
147         }
148
149         if (i == _bundles.end()) {
150                 return;
151         }
152
153         delete *i;
154         _bundles.erase (i);
155
156         Changed ();
157 }
158
159 void
160 PortGroup::bundle_changed (Bundle::Change c)
161 {
162         BundleChanged (c);
163 }
164
165
166 void
167 PortGroup::clear ()
168 {
169         for (BundleList::iterator i = _bundles.begin(); i != _bundles.end(); ++i) {
170                 delete *i;
171         }
172
173         _bundles.clear ();
174         Changed ();
175 }
176
177 bool
178 PortGroup::has_port (std::string const& p) const
179 {
180         for (BundleList::const_iterator i = _bundles.begin(); i != _bundles.end(); ++i) {
181                 if ((*i)->bundle->offers_port_alone (p)) {
182                         return true;
183                 }
184         }
185
186         return false;
187 }
188
189 boost::shared_ptr<Bundle>
190 PortGroup::only_bundle ()
191 {
192         assert (_bundles.size() == 1);
193         return _bundles.front()->bundle;
194 }
195
196
197 ChanCount
198 PortGroup::total_channels () const
199 {
200         ChanCount n;
201         for (BundleList::const_iterator i = _bundles.begin(); i != _bundles.end(); ++i) {
202                 n += (*i)->bundle->nchannels ();
203         }
204
205         return n;
206 }
207
208 boost::shared_ptr<IO>
209 PortGroup::io_from_bundle (boost::shared_ptr<ARDOUR::Bundle> b) const
210 {
211         BundleList::const_iterator i = _bundles.begin ();
212         while (i != _bundles.end() && (*i)->bundle != b) {
213                 ++i;
214         }
215
216         if (i == _bundles.end()) {
217                 return boost::shared_ptr<IO> ();
218         }
219
220         boost::shared_ptr<IO> io ((*i)->io.lock ());
221         return io;
222 }
223
224 /** Remove bundles whose channels are already represented by other, larger bundles */
225 void
226 PortGroup::remove_duplicates ()
227 {
228         BundleList::iterator i = _bundles.begin();
229         while (i != _bundles.end()) {
230
231                 BundleList::iterator tmp = i;
232                 ++tmp;
233
234                 bool remove = false;
235
236                 for (BundleList::iterator j = _bundles.begin(); j != _bundles.end(); ++j) {
237
238                         if ((*j)->bundle->nchannels() > (*i)->bundle->nchannels()) {
239                                 /* this bundle is larger */
240
241                                 uint32_t k = 0;
242                                 while (k < (*i)->bundle->nchannels().n_total()) {
243                                         /* see if this channel on *i has an equivalent on *j */
244                                         uint32_t l = 0;
245                                         while (l < (*j)->bundle->nchannels().n_total() && (*i)->bundle->channel_ports (k) != (*j)->bundle->channel_ports (l)) {
246                                                 ++l;
247                                         }
248
249                                         if (l == (*j)->bundle->nchannels().n_total()) {
250                                                 /* it does not */
251                                                 break;
252                                         }
253
254                                         ++k;
255                                 }
256
257                                 if (k == (*i)->bundle->nchannels().n_total()) {
258                                         /* all channels on *i are represented by the larger bundle *j, so remove *i */
259                                         remove = true;
260                                         break;
261                                 }
262                         }
263                 }
264
265                 if (remove) {
266                         _bundles.erase (i);
267                 }
268
269                 i = tmp;
270         }
271 }
272
273
274 /** PortGroupList constructor.
275  */
276 PortGroupList::PortGroupList ()
277         : _signals_suspended (false), _pending_change (false), _pending_bundle_change ((Bundle::Change) 0)
278 {
279
280 }
281
282 PortGroupList::~PortGroupList()
283 {
284         /* XXX need to clean up bundles, but ownership shared with PortGroups */
285 }
286
287 void
288 PortGroupList::maybe_add_processor_to_list (
289         boost::weak_ptr<Processor> wp, list<boost::shared_ptr<IO> >* route_ios, bool inputs, set<boost::shared_ptr<IO> >& used_io
290         )
291 {
292         boost::shared_ptr<Processor> p (wp.lock());
293
294         if (!p) {
295                 return;
296         }
297
298         boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor> (p);
299
300         if (iop) {
301
302                 boost::shared_ptr<IO> io = inputs ? iop->input() : iop->output();
303
304                 if (io && used_io.find (io) == used_io.end()) {
305                         route_ios->push_back (io);
306                         used_io.insert (io);
307                 }
308         }
309 }
310
311 struct RouteIOs {
312         RouteIOs (boost::shared_ptr<Route> r, boost::shared_ptr<IO> i) {
313                 route = r;
314                 ios.push_back (i);
315         }
316
317         boost::shared_ptr<Route> route;
318         /* it's ok to use a shared_ptr here as RouteIOs structs are only used during ::gather () */
319         std::list<boost::shared_ptr<IO> > ios;
320 };
321
322 class RouteIOsComparator {
323 public:
324         bool operator() (RouteIOs const & a, RouteIOs const & b) {
325                 return a.route->presentation_info ().order() < b.route->presentation_info().order();
326         }
327 };
328
329 /** Gather ports from around the system and put them in this PortGroupList.
330  *  @param type Type of ports to collect, or NIL for all types.
331  *  @param use_session_bundles true to use the session's non-user bundles.  Doing this will mean that
332  *  hardware ports will be gathered into stereo pairs, as the session sets up bundles for these pairs.
333  *  Not using the session bundles will mean that all hardware IO will be presented separately.
334  */
335 void
336 PortGroupList::gather (ARDOUR::Session* session, ARDOUR::DataType type, bool inputs, bool allow_dups, bool use_session_bundles)
337 {
338         clear ();
339
340         if (session == 0) {
341                 return;
342         }
343
344         boost::shared_ptr<PortGroup> bus (new PortGroup (string_compose (_("%1 Busses"), PROGRAM_NAME)));
345         boost::shared_ptr<PortGroup> track (new PortGroup (string_compose (_("%1 Tracks"), PROGRAM_NAME)));
346         boost::shared_ptr<PortGroup> sidechain (new PortGroup (string_compose (_("%1 Sidechains"), PROGRAM_NAME)));
347         boost::shared_ptr<PortGroup> system (new PortGroup (_("Hardware")));
348         boost::shared_ptr<PortGroup> program (new PortGroup (string_compose (_("%1 Misc"), PROGRAM_NAME)));
349         boost::shared_ptr<PortGroup> other (new PortGroup (_("Other")));
350
351         /* Find the IOs which have bundles for routes and their processors.  We store
352            these IOs in a RouteIOs class so that we can then sort the results by route
353            order key.
354         */
355
356         boost::shared_ptr<RouteList> routes = session->get_routes ();
357         list<RouteIOs> route_ios;
358
359         for (RouteList::const_iterator i = routes->begin(); i != routes->end(); ++i) {
360
361                 /* we never show the monitor bus inputs */
362
363                 if (inputs && (*i)->is_monitor()) {
364                         continue;
365                 }
366
367                 /* keep track of IOs that we have taken bundles from,
368                    so that we can avoid taking the same IO from both
369                    Route::output() and the main_outs Delivery
370                 */
371
372                 set<boost::shared_ptr<IO> > used_io;
373                 boost::shared_ptr<IO> io = inputs ? (*i)->input() : (*i)->output();
374                 used_io.insert (io);
375
376                 RouteIOs rb (*i, io);
377                 (*i)->foreach_processor (boost::bind (&PortGroupList::maybe_add_processor_to_list, this, _1, &rb.ios, inputs, used_io));
378
379                 route_ios.push_back (rb);
380         }
381
382         /* Sort RouteIOs by the routes' editor order keys */
383         route_ios.sort (RouteIOsComparator ());
384
385         /* Now put the bundles that belong to these sorted RouteIOs into the PortGroup. */
386
387         for (list<RouteIOs>::iterator i = route_ios.begin(); i != route_ios.end(); ++i) {
388                 TimeAxisView* tv = PublicEditor::instance().time_axis_view_from_stripable (i->route);
389
390                 /* Work out which group to put these IOs' bundles in */
391                 boost::shared_ptr<PortGroup> g;
392                 if (boost::dynamic_pointer_cast<Track> (i->route)) {
393                         g = track;
394                 } else {
395                         g = bus;
396                 }
397
398                 for (list<boost::shared_ptr<IO> >::iterator j = i->ios.begin(); j != i->ios.end(); ++j) {
399                         /* Only add the bundle if there is at least one port
400                          * with a type that's been asked for */
401                         if (type == DataType::NIL || (*j)->bundle()->nchannels().n(type) > 0) {
402                                 if (tv) {
403                                         g->add_bundle ((*j)->bundle(), *j, tv->color ());
404                                 } else {
405                                         g->add_bundle ((*j)->bundle(), *j);
406                                 }
407                         }
408                 }
409
410                 /* When on input side, let's look for sidechains in the route's plugins
411                    to display them right next to their route */
412                 for (uint32_t n = 0; inputs; ++n) {
413                         boost::shared_ptr<Processor> p = (i->route)->nth_plugin (n);
414                         if (!p) {
415                                 break;
416                         }
417                         boost::shared_ptr<SideChain> sc = boost::static_pointer_cast<PluginInsert> (p)->sidechain ();
418
419                         if (sc) {
420                                 boost::shared_ptr<IO> io = sc->input();
421                                 if (tv) {
422                                         sidechain->add_bundle (io->bundle(), io, tv->color ());
423                                 } else {
424                                         sidechain->add_bundle (io->bundle(), io);
425                                 }
426                         }
427                 }
428         }
429
430         /* Bundles owned by the session; add user bundles first, then normal ones, so
431            that UserBundles that offer the same ports as a normal bundle get priority
432         */
433
434         boost::shared_ptr<BundleList> b = session->bundles ();
435
436         for (BundleList::iterator i = b->begin(); i != b->end(); ++i) {
437                 if (boost::dynamic_pointer_cast<UserBundle> (*i) && (*i)->ports_are_inputs() == inputs) {
438                         system->add_bundle (*i, allow_dups);
439                 }
440         }
441
442         /* Only look for non-user bundles if instructed to do so */
443         if (use_session_bundles) {
444                 for (BundleList::iterator i = b->begin(); i != b->end(); ++i) {
445                         if (boost::dynamic_pointer_cast<UserBundle> (*i) == 0 && (*i)->ports_are_inputs() == inputs) {
446                                 system->add_bundle (*i, allow_dups);
447                         }
448                 }
449         }
450
451         /* miscellany */
452
453         if (type == DataType::AUDIO || type == DataType::NIL) {
454                 if (!inputs) {
455                         program->add_bundle (session->the_auditioner()->output()->bundle());
456                         program->add_bundle (session->click_io()->bundle());
457                         /* Note: the LTC ports do not have the usual ":audio_out 1" postfix, so
458                          *  program->add_bundle (session->ltc_output_io()->bundle());
459                          *  won't work
460                          */
461                         boost::shared_ptr<Bundle> ltc (new Bundle (_("LTC Out"), inputs));
462                         ltc->add_channel (_("LTC Out"), DataType::AUDIO, session->engine().make_port_name_non_relative (session->ltc_output_port()->name()));
463                         program->add_bundle (ltc);
464                 } else {
465                         // XXX TRANSPORTMASTERS
466                         //boost::shared_ptr<Bundle> ltc (new Bundle (_("LTC In"), inputs));
467                         // ltc->add_channel (_("LTC In"), DataType::AUDIO, session->engine().make_port_name_non_relative (session->ltc_input_port()->name()));
468                         // program->add_bundle (ltc);
469                 }
470         }
471
472         /* our control surfaces */
473
474         /* XXX assume for now that all control protocols with ports use
475          * MIDI. If anyone created a control protocol that used audio ports,
476          * this will break.
477          */
478
479         if ((type == DataType::MIDI || type == DataType::NIL)) {
480                 ControlProtocolManager& m = ControlProtocolManager::instance ();
481                 for (list<ControlProtocolInfo*>::iterator i = m.control_protocol_info.begin(); i != m.control_protocol_info.end(); ++i) {
482                         if ((*i)->protocol) {
483                                 list<boost::shared_ptr<Bundle> > b = (*i)->protocol->bundles ();
484                                 for (list<boost::shared_ptr<Bundle> >::iterator j = b.begin(); j != b.end(); ++j) {
485                                         if ((*j)->ports_are_inputs() == inputs) {
486                                                 program->add_bundle (*j);
487                                         }
488                                 }
489                         }
490                 }
491         }
492
493         /* virtual keyboard */
494         if (!inputs && (type == DataType::MIDI || type == DataType::NIL)) {
495                 boost::shared_ptr<ARDOUR::Port> ap = boost::dynamic_pointer_cast<ARDOUR::Port> (session->vkbd_output_port());
496                 AudioEngine* ae = AudioEngine::instance();
497                 boost::shared_ptr<Bundle> vm (new Bundle (_("Virtual MIDI"), inputs));
498                 vm->add_channel (_("Virtual Keyboard"), DataType::MIDI, ae->make_port_name_non_relative (ap->name()));
499                 program->add_bundle (vm);
500         }
501
502         /* our sync ports */
503
504         if ((type == DataType::MIDI || type == DataType::NIL)) {
505                 boost::shared_ptr<Bundle> sync (new Bundle (_("Sync"), inputs));
506                 AudioEngine* ae = AudioEngine::instance();
507
508                 if (inputs) {
509                         // XXX TRANSPORTMASTER
510                         // sync->add_channel (
511                         // _("MTC in"), DataType::MIDI, ae->make_port_name_non_relative (session->mtc_input_port()->name())
512                         // );
513                         // sync->add_channel (
514                         // _("MIDI clock in"), DataType::MIDI, ae->make_port_name_non_relative (session->midi_clock_input_port()->name())
515                         //);
516                         sync->add_channel (
517                                 _("MMC in"), DataType::MIDI, ae->make_port_name_non_relative (session->mmc_input_port()->name())
518                                 );
519                 } else {
520                         sync->add_channel (
521                                 _("MTC out"), DataType::MIDI, ae->make_port_name_non_relative (session->mtc_output_port()->name())
522                                 );
523                         sync->add_channel (
524                                 _("MIDI clock out"), DataType::MIDI, ae->make_port_name_non_relative (session->midi_clock_output_port()->name())
525                                 );
526                         sync->add_channel (
527                                 _("MMC out"), DataType::MIDI, ae->make_port_name_non_relative (session->mmc_output_port()->name())
528                                 );
529                 }
530
531                 program->add_bundle (sync);
532         }
533
534         /* Now find all other ports that we haven't thought of yet */
535
536         std::vector<std::string> extra_system[DataType::num_types];
537         std::vector<std::string> extra_program[DataType::num_types];
538         std::vector<std::string> extra_other[DataType::num_types];
539
540         string lpn (PROGRAM_NAME);
541         boost::to_lower (lpn);
542         string lpnc = lpn;
543         lpnc += ':';
544
545         vector<string> ports;
546         if (type == DataType::NIL) {
547                 vector<string> p1;
548                 AudioEngine::instance()->get_ports ("", DataType::AUDIO, inputs ? IsInput : IsOutput, ports);
549                 AudioEngine::instance()->get_ports ("", DataType::MIDI, inputs ? IsInput : IsOutput, p1);
550                 for (vector<string>::const_iterator s = p1.begin(); s != p1.end(); ++s) {
551                         ports.push_back (*s);
552                 }
553         } else {
554                 AudioEngine::instance()->get_ports ("", type, inputs ? IsInput : IsOutput, ports);
555         }
556
557         if (ports.size () > 0) {
558
559                 for (vector<string>::const_iterator s = ports.begin(); s != ports.end(); ) {
560
561                         std::string const p = *s;
562
563                         if (!system->has_port(p) &&
564                             !bus->has_port(p) &&
565                             !track->has_port(p) &&
566                             !sidechain->has_port(p) &&
567                             !program->has_port(p) &&
568                             !other->has_port(p)) {
569
570                                 /* special hack: ignore MIDI ports labelled Midi-Through. these
571                                    are basically useless and mess things up for default
572                                    connections.
573                                 */
574
575                                 if (p.find ("Midi-Through") != string::npos || p.find ("Midi Through") != string::npos) {
576                                         ++s;
577                                         continue;
578                                 }
579
580                                 /* special hack: ignore our monitor inputs (which show up here because
581                                    we excluded them earlier.
582                                 */
583
584                                 string lp = p;
585                                 string monitor = _("Monitor");
586
587                                 boost::to_lower (lp);
588                                 boost::to_lower (monitor);
589
590                                 if ((lp.find (monitor) != string::npos) &&
591                                     (lp.find (lpn) != string::npos)) {
592                                         ++s;
593                                         continue;
594                                 }
595
596                                 /* can't use the audio engine for this as we
597                                  * are looking at ports not owned by the
598                                  * application, and the audio engine/port
599                                  * manager doesn't seem them.
600                                  */
601
602                                 PortEngine::PortHandle ph = AudioEngine::instance()->port_engine().get_port_by_name (p);
603
604                                 if (!ph) {
605                                         continue;
606                                 }
607
608                                 DataType t (AudioEngine::instance()->port_engine().port_data_type (ph));
609
610                                 if (t != DataType::NIL) {
611
612                                         PortFlags flags (AudioEngine::instance()->port_engine().get_port_flags (ph));
613
614                                         if (port_has_prefix (p, lpnc)) {
615
616                                                 /* we own this port (named after the program) */
617
618                                                 /* Hide scene ports for now */
619                                                 if (p.find (_("Scene ")) != string::npos) {
620                                                         ++s;
621                                                         continue;
622                                                 }
623
624                                                 extra_program[t].push_back (p);
625
626                                         } else if (flags & IsPhysical) {
627
628                                                 extra_system[t].push_back (p);
629
630                                         } else {
631                                                 extra_other[t].push_back (p);
632                                         }
633                                 }
634                         }
635
636                         ++s;
637                 }
638         }
639
640         for (DataType::iterator i = DataType::begin(); i != DataType::end(); ++i) {
641                 if (!extra_system[*i].empty()) {
642                         boost::shared_ptr<Bundle> b = make_bundle_from_ports (extra_system[*i], *i, inputs);
643                         system->add_bundle (b);
644                 }
645         }
646
647         for (DataType::iterator i = DataType::begin(); i != DataType::end(); ++i) {
648                 if (!extra_program[*i].empty()) {
649                         /* used program name as bundle name */
650                         boost::shared_ptr<Bundle> b = make_bundle_from_ports (extra_program[*i], *i, inputs, lpn);
651                         program->add_bundle (b);
652                 }
653         }
654
655         for (DataType::iterator i = DataType::begin(); i != DataType::end(); ++i) {
656                 if (extra_other[*i].empty()) continue;
657                 std::string cp;
658                 std::vector<std::string> nb;
659                 for (uint32_t j = 0; j < extra_other[*i].size(); ++j) {
660                         std::string nn = extra_other[*i][j];
661                         std::string pf = nn.substr (0, nn.find_first_of (":") + 1);
662                         if (pf != cp && !nb.empty()) {
663                                 boost::shared_ptr<Bundle> b = make_bundle_from_ports (nb, *i, inputs);
664                                 other->add_bundle (b);
665                                 nb.clear();
666                         }
667                         cp = pf;
668                         nb.push_back(extra_other[*i][j]);
669                 }
670                 if (!nb.empty()) {
671                         boost::shared_ptr<Bundle> b = make_bundle_from_ports (nb, *i, inputs);
672                         other->add_bundle (b);
673                 }
674         }
675
676         if (!allow_dups) {
677                 system->remove_duplicates ();
678         }
679
680         add_group_if_not_empty (other);
681         add_group_if_not_empty (bus);
682         add_group_if_not_empty (track);
683         add_group_if_not_empty (sidechain);
684         add_group_if_not_empty (program);
685         add_group_if_not_empty (system);
686
687         emit_changed ();
688 }
689
690 boost::shared_ptr<Bundle>
691 PortGroupList::make_bundle_from_ports (std::vector<std::string> const & p, ARDOUR::DataType type, bool inputs, std::string const& bundle_name) const
692 {
693         boost::shared_ptr<Bundle> b (new Bundle ("", inputs));
694         std::string const pre = common_prefix (p);
695
696         if (!bundle_name.empty()) {
697                 b->set_name (bundle_name);
698         } else {
699                 if (!pre.empty()) {
700                         b->set_name (pre.substr (0, pre.length() - 1));
701                 }
702         }
703
704         for (uint32_t j = 0; j < p.size(); ++j) {
705                 std::string n = p[j].substr (pre.length());
706                 std::string pn = AudioEngine::instance()->get_pretty_name_by_name (p[j]);
707                 if (!pn.empty()) {
708                         n = pn;
709                 }
710                 b->add_channel (n, type);
711                 b->set_port (j, p[j]);
712         }
713
714         return b;
715 }
716
717 bool
718 PortGroupList::port_has_prefix (const std::string& n, const std::string& p) const
719 {
720         return n.substr (0, p.length()) == p;
721 }
722
723 std::string
724 PortGroupList::common_prefix_before (std::vector<std::string> const & p, std::string const & s) const
725 {
726         /* we must have some strings and the first must contain the separator string */
727         if (p.empty() || p[0].find_first_of (s) == std::string::npos) {
728                 return "";
729         }
730
731         /* prefix of the first string */
732         std::string const fp = p[0].substr (0, p[0].find_first_of (s) + 1);
733
734         /* see if the other strings also start with fp */
735         uint32_t j = 1;
736         while (j < p.size()) {
737                 if (p[j].substr (0, fp.length()) != fp) {
738                         break;
739                 }
740                 ++j;
741         }
742
743         if (j != p.size()) {
744                 return "";
745         }
746
747         return fp;
748 }
749
750
751 std::string
752 PortGroupList::common_prefix (std::vector<std::string> const & p) const
753 {
754         /* common prefix before '/' ? */
755         std::string cp = common_prefix_before (p, "/");
756         if (!cp.empty()) {
757                 return cp;
758         }
759
760         cp = common_prefix_before (p, ":");
761         if (!cp.empty()) {
762                 return cp;
763         }
764
765         return "";
766 }
767
768 void
769 PortGroupList::clear ()
770 {
771         _groups.clear ();
772         _bundle_changed_connections.drop_connections ();
773         emit_changed ();
774 }
775
776
777 PortGroup::BundleList const &
778 PortGroupList::bundles () const
779 {
780         _bundles.clear ();
781
782         for (PortGroupList::List::const_iterator i = begin (); i != end (); ++i) {
783                 std::copy ((*i)->bundles().begin(), (*i)->bundles().end(), std::back_inserter (_bundles));
784         }
785
786         return _bundles;
787 }
788
789 ChanCount
790 PortGroupList::total_channels () const
791 {
792         ChanCount n;
793
794         for (PortGroupList::List::const_iterator i = begin(); i != end(); ++i) {
795                 n += (*i)->total_channels ();
796         }
797
798         return n;
799 }
800
801 void
802 PortGroupList::add_group_if_not_empty (boost::shared_ptr<PortGroup> g)
803 {
804         if (!g->bundles().empty ()) {
805                 add_group (g);
806         }
807 }
808
809 void
810 PortGroupList::add_group (boost::shared_ptr<PortGroup> g)
811 {
812         _groups.push_back (g);
813
814         g->Changed.connect (_changed_connections, invalidator (*this), boost::bind (&PortGroupList::emit_changed, this), gui_context());
815         g->BundleChanged.connect (_bundle_changed_connections, invalidator (*this), boost::bind (&PortGroupList::emit_bundle_changed, this, _1), gui_context());
816
817         emit_changed ();
818 }
819
820 void
821 PortGroupList::remove_bundle (boost::shared_ptr<Bundle> b)
822 {
823         for (List::iterator i = _groups.begin(); i != _groups.end(); ++i) {
824                 (*i)->remove_bundle (b);
825         }
826
827         emit_changed ();
828 }
829
830 void
831 PortGroupList::emit_changed ()
832 {
833         if (_signals_suspended) {
834                 _pending_change = true;
835         } else {
836                 Changed ();
837         }
838 }
839
840 void
841 PortGroupList::emit_bundle_changed (Bundle::Change c)
842 {
843         if (_signals_suspended) {
844                 _pending_bundle_change = c;
845         } else {
846                 BundleChanged (c);
847         }
848 }
849 void
850 PortGroupList::suspend_signals ()
851 {
852         _signals_suspended = true;
853 }
854
855 void
856 PortGroupList::resume_signals ()
857 {
858         if (_pending_change) {
859                 Changed ();
860                 _pending_change = false;
861         }
862
863         if (_pending_bundle_change != 0) {
864                 BundleChanged (_pending_bundle_change);
865                 _pending_bundle_change = (ARDOUR::Bundle::Change) 0;
866         }
867
868         _signals_suspended = false;
869 }
870
871 boost::shared_ptr<IO>
872 PortGroupList::io_from_bundle (boost::shared_ptr<ARDOUR::Bundle> b) const
873 {
874         List::const_iterator i = _groups.begin ();
875         while (i != _groups.end()) {
876                 boost::shared_ptr<IO> io = (*i)->io_from_bundle (b);
877                 if (io) {
878                         return io;
879                 }
880                 ++i;
881         }
882
883         return boost::shared_ptr<IO> ();
884 }
885
886 bool
887 PortGroupList::empty () const
888 {
889         return _groups.empty ();
890 }