d0f236f84ab951b5f4d3585426f3b13fdbd8f404
[ardour.git] / gtk2_ardour / io_selector.cc
1 /*
2     Copyright (C) 2002-2007 Paul Davis 
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <gtkmm/label.h>
21 #include <gtkmm/enums.h>
22 #include <gtkmm/image.h>
23 #include <gtkmm/stock.h>
24 #include <gtkmm/messagedialog.h>
25 #include <gtkmm/menu.h>
26 #include <gtkmm/menu_elems.h>
27 #include <gtkmm/menuitem.h>
28 #include <gtkmm/menushell.h>
29 #include <glibmm/objectbase.h>
30 #include <gtkmm2ext/doi.h>
31 #include <ardour/port_insert.h>
32 #include "ardour/session.h"
33 #include "ardour/io.h"
34 #include "ardour/audioengine.h"
35 #include "ardour/track.h"
36 #include "ardour/audio_track.h"
37 #include "ardour/midi_track.h"
38 #include "ardour/data_type.h"
39 #include "io_selector.h"
40 #include "utils.h"
41 #include "gui_thread.h"
42 #include "i18n.h"
43
44 /** Add a port to a group.
45  *  @param p Port name, with or without prefix.
46  */
47
48 void
49 PortGroup::add (std::string const & p)
50 {
51         if (prefix.empty() == false && p.substr (0, prefix.length()) == prefix) {
52                 ports.push_back (p.substr (prefix.length()));
53         } else {
54                 ports.push_back (p);
55         }
56 }
57
58
59 PortGroupTable::PortGroupTable (
60         PortGroup& g, boost::shared_ptr<ARDOUR::IO> io, bool for_input
61         )
62         : _port_group (g), _ignore_check_button_toggle (false),
63           _io (io), _for_input (for_input)
64 {
65         ARDOUR::DataType const t = _io->default_type();
66
67         int rows;
68         if (_for_input) {
69                 rows = _io->n_inputs().get(t);
70         } else {
71                 rows = _io->n_outputs().get(t);
72         }       
73         
74         int const ports = _port_group.ports.size();
75
76         if (rows == 0 || ports == 0) {
77                 return;
78         }
79
80         /* Sort out the table and the checkbuttons inside it */
81         
82         _table.resize (rows, ports);
83         _check_buttons.resize (rows);
84         for (int i = 0; i < rows; ++i) {
85                 _check_buttons[i].resize (ports);
86         }
87
88         for (int i = 0; i < rows; ++i) {
89                 for (uint32_t j = 0; j < _port_group.ports.size(); ++j) {
90                         Gtk::CheckButton* b = new Gtk::CheckButton;
91                         b->signal_toggled().connect (sigc::bind (sigc::mem_fun (*this, &PortGroupTable::check_button_toggled), b, i, _port_group.prefix + _port_group.ports[j]));
92                         _check_buttons[i][j] = b;
93                         _table.attach (*b, j, j + 1, i, i + 1);
94                 }
95         }
96
97         _box.add (_table);
98
99         _ignore_check_button_toggle = true;
100
101         /* Set the state of the check boxes according to current connections */
102         for (int i = 0; i < rows; ++i) {
103                 const char **connections = _for_input ? _io->input(i)->get_connections() : _io->output(i)->get_connections();
104                 for (uint32_t j = 0; j < _port_group.ports.size(); ++j) {
105
106                         std::string const t = _port_group.prefix + _port_group.ports[j];
107                         int k = 0;
108                         bool required_state = false;
109
110                         while (connections && connections[k]) {
111                                 if (std::string(connections[k]) == t) {
112                                         required_state = true;
113                                         break;
114                                 }
115                                 ++k;
116                         }
117
118                         _check_buttons[i][j]->set_active (required_state);
119                 }
120         }
121
122         _ignore_check_button_toggle = false;
123 }
124
125 /** @return Width and height of a single check button in a port group table */
126 std::pair<int, int>
127 PortGroupTable::unit_size () const
128 {
129         if (_check_buttons.empty() || _check_buttons[0].empty()) {
130                 return std::pair<int, int> (0, 0);
131         }
132
133         return std::make_pair (
134                 _check_buttons[0][0]->get_width() + _table.get_col_spacing (0),
135                 _check_buttons[0][0]->get_height() + _table.get_row_spacing (0)
136                 );
137 }
138
139 Gtk::Widget&
140 PortGroupTable::get_widget ()
141 {
142         return _box;
143 }
144
145
146 /** Handle a toggle of a check button */
147 void
148 PortGroupTable::check_button_toggled (Gtk::CheckButton* b, int r, std::string const & p)
149 {
150         if (_ignore_check_button_toggle) {
151                 return;
152         }
153         
154         bool const new_state = b->get_active ();
155
156         if (new_state) {
157                 if (_for_input) {
158                         _io->connect_input (_io->input(r), p, 0);
159                 } else {
160                         _io->connect_output (_io->output(r), p, 0);
161                 }
162         } else {
163                 if (_for_input) {
164                         _io->disconnect_input (_io->input(r), p, 0);
165                 } else {
166                         _io->disconnect_output (_io->output(r), p, 0);
167                 }
168         }
169 }
170
171
172 RotatedLabelSet::RotatedLabelSet (PortGroupList& g)
173         : Glib::ObjectBase ("RotatedLabelSet"), Gtk::Widget (), _port_group_list (g), _base_width (128)
174 {
175         set_flags (Gtk::NO_WINDOW);
176         set_angle (30);
177 }
178
179 RotatedLabelSet::~RotatedLabelSet ()
180 {
181         
182 }
183
184
185 /** Set the angle that the labels are drawn at.
186  * @param degrees New angle in degrees.
187  */
188
189 void
190 RotatedLabelSet::set_angle (int degrees)
191 {
192         _angle_degrees = degrees;
193         _angle_radians = M_PI * _angle_degrees / 180;
194
195         queue_resize ();
196 }
197
198 void
199 RotatedLabelSet::on_size_request (Gtk::Requisition* requisition)
200 {
201         *requisition = Gtk::Requisition ();
202
203         if (_pango_layout == 0) {
204                 return;
205         }
206
207         /* Our height is the highest label */
208         requisition->height = 0;
209         for (PortGroupList::const_iterator i = _port_group_list.begin(); i != _port_group_list.end(); ++i) {
210                 for (std::vector<std::string>::const_iterator j = (*i)->ports.begin(); j != (*i)->ports.end(); ++j) {
211                         std::pair<int, int> const d = setup_layout (*j);
212                         if (d.second > requisition->height) {
213                                 requisition->height = d.second;
214                         }
215                 }
216         }
217
218         /* And our width is the base plus the width of the last label */
219         requisition->width = _base_width;
220         int const n = _port_group_list.n_visible_ports ();
221         if (n > 0) {
222                 std::pair<int, int> const d = setup_layout (_port_group_list.get_port_by_index (n - 1, false));
223                 requisition->width += d.first;
224         }
225 }
226
227 void
228 RotatedLabelSet::on_size_allocate (Gtk::Allocation& allocation)
229 {
230         set_allocation (allocation);
231
232         if (_gdk_window) {
233                 _gdk_window->move_resize (
234                         allocation.get_x(), allocation.get_y(), allocation.get_width(), allocation.get_height()
235                         );
236         }
237 }
238
239 void
240 RotatedLabelSet::on_realize ()
241 {
242         Gtk::Widget::on_realize ();
243
244         Glib::RefPtr<Gtk::Style> style = get_style ();
245
246         if (!_gdk_window) {
247                 GdkWindowAttr attributes;
248                 memset (&attributes, 0, sizeof (attributes));
249
250                 Gtk::Allocation allocation = get_allocation ();
251                 attributes.x = allocation.get_x ();
252                 attributes.y = allocation.get_y ();
253                 attributes.width = allocation.get_width ();
254                 attributes.height = allocation.get_height ();
255
256                 attributes.event_mask = get_events () | Gdk::EXPOSURE_MASK; 
257                 attributes.window_type = GDK_WINDOW_CHILD;
258                 attributes.wclass = GDK_INPUT_OUTPUT;
259
260                 _gdk_window = Gdk::Window::create (get_window (), &attributes, GDK_WA_X | GDK_WA_Y);
261                 unset_flags (Gtk::NO_WINDOW);
262                 set_window (_gdk_window);
263
264                 _bg_colour = style->get_bg (Gtk::STATE_NORMAL );
265                 modify_bg (Gtk::STATE_NORMAL, _bg_colour);
266                 _fg_colour = style->get_fg (Gtk::STATE_NORMAL);
267 ;
268                 _gdk_window->set_user_data (gobj ());
269
270                 /* Set up Pango stuff */
271                 _pango_context = create_pango_context ();
272
273                 Pango::Matrix matrix = PANGO_MATRIX_INIT;
274                 pango_matrix_rotate (&matrix, _angle_degrees);
275                 _pango_context->set_matrix (matrix);
276
277                 _pango_layout = Pango::Layout::create (_pango_context);
278                 _gc = Gdk::GC::create (get_window ());
279         }
280 }
281
282 void
283 RotatedLabelSet::on_unrealize()
284 {
285         _gdk_window.clear ();
286
287         Gtk::Widget::on_unrealize ();
288 }
289
290
291 /** Set up our Pango layout to plot a given string, and compute its dimensions once
292  *  it has been rotated.
293  *  @param s String to use.
294  *  @return width and height of the rotated string, in pixels.
295  */
296
297 std::pair<int, int>
298 RotatedLabelSet::setup_layout (std::string const & s)
299 {
300         _pango_layout->set_text (s);
301
302         /* Here's the unrotated size */
303         int w;
304         int h;
305         _pango_layout->get_pixel_size (w, h);
306
307         /* Rotate the width and height as appropriate.  I thought Pango might be able
308            to do this for us, but I can't find out how... */
309         std::pair<int, int> d;
310         d.first = int (w * cos (_angle_radians) - h * sin (_angle_radians));
311         d.second = int (w * sin (_angle_radians) + h * cos (_angle_radians));
312
313         return d;
314 }
315
316 bool
317 RotatedLabelSet::on_expose_event (GdkEventExpose* event)
318 {
319         if (!_gdk_window) {
320                 return true;
321         }
322
323         int const height = get_allocation().get_height ();
324         double const spacing = double (_base_width) / _port_group_list.n_visible_ports();
325
326         /* Plot all the visible labels; really we should clip for efficiency */
327         int n = 0;
328         for (PortGroupList::const_iterator i = _port_group_list.begin(); i != _port_group_list.end(); ++i) {
329                 if ((*i)->visible) {
330                         for (uint32_t j = 0; j < (*i)->ports.size(); ++j) {
331                                 std::pair<int, int> const d = setup_layout ((*i)->ports[j]);
332                                 get_window()->draw_layout (_gc, int ((n + 0.25) * spacing), height - d.second, _pango_layout, _fg_colour, _bg_colour);
333                                 ++n;
334                         }
335                 }
336         }
337
338         return true;
339 }
340
341 /** Set the `base width'.  This is the width of the base of the label set, ie:
342  *
343  *     L L L L
344  *    E E E E
345  *   B B B B
346  *  A A A A
347  * L L L L
348  * <--w-->
349  */
350     
351 void
352 RotatedLabelSet::set_base_width (int w)
353 {
354         _base_width = w;
355         queue_resize ();
356 }
357
358
359 /** Construct an IOSelector.
360  *  @param session Session to operate on.
361  *  @param io IO to operate on.
362  *  @param for_input true if the selector is for an input, otherwise false.
363  */
364  
365 IOSelector::IOSelector (ARDOUR::Session& session, boost::shared_ptr<ARDOUR::IO> io, bool for_input)
366         : _port_group_list (session, io, for_input), _io (io), _for_input (for_input),
367           _column_labels (_port_group_list)
368 {
369         _row_labels_vbox[0] = _row_labels_vbox[1] = 0;
370         _side_vbox_pad[0] = _side_vbox_pad[1] = 0;
371         
372         Gtk::HBox* c = new Gtk::HBox;
373         for (PortGroupList::iterator i = _port_group_list.begin(); i != _port_group_list.end(); ++i) {
374                 Gtk::CheckButton* b = new Gtk::CheckButton ((*i)->name);
375                 b->set_active (true);
376                 b->signal_toggled().connect (sigc::bind (sigc::mem_fun (*this, &IOSelector::group_visible_toggled), b, (*i)->name));
377                 c->pack_start (*Gtk::manage (b), false, false);
378         }
379         pack_start (*Gtk::manage (c));
380         
381         _side_vbox[0].pack_start (*Gtk::manage (new Gtk::Label ("")));
382         _overall_hbox.pack_start (_side_vbox[0], false, false);
383         _scrolled_window.set_policy (Gtk::POLICY_ALWAYS, Gtk::POLICY_NEVER);
384         _scrolled_window.set_shadow_type (Gtk::SHADOW_NONE);
385         Gtk::VBox* b = new Gtk::VBox;
386         b->pack_start (_column_labels, false, false);
387         b->pack_start (_port_group_hbox, false, false);
388         Gtk::Alignment* a = new Gtk::Alignment (0, 1, 0, 0);
389         a->add (*Gtk::manage (b));
390         _scrolled_window.add (*Gtk::manage (a));
391         _overall_hbox.pack_start (_scrolled_window);
392         _side_vbox[1].pack_start (*Gtk::manage (new Gtk::Label ("")));
393         _overall_hbox.pack_start (_side_vbox[1]);
394         pack_start (_overall_hbox);
395
396         _port_group_hbox.signal_size_allocate().connect (sigc::hide (sigc::mem_fun (*this, &IOSelector::setup_dimensions)));
397
398         /* Listen for ports changing on the IO */
399         if (_for_input) {
400                 _io->input_changed.connect (mem_fun(*this, &IOSelector::ports_changed));
401         } else {
402                 _io->output_changed.connect (mem_fun(*this, &IOSelector::ports_changed));
403         }
404         
405 }
406
407 IOSelector::~IOSelector ()
408 {
409         clear ();
410 }
411
412 /** Clear out the things that change when the number of source or destination ports changes */
413 void
414 IOSelector::clear ()
415 {
416         for (int i = 0; i < 2; ++i) {
417
418                 for (std::vector<Gtk::EventBox*>::iterator j = _row_labels[i].begin(); j != _row_labels[i].end(); ++j) {
419                         delete *j;
420                 }
421                 _row_labels[i].clear ();
422                 
423                 if (_row_labels_vbox[i]) {
424                         _side_vbox[i].remove (*_row_labels_vbox[i]);
425                 }
426                 delete _row_labels_vbox[i];
427                 _row_labels_vbox[i] = 0;
428                 
429                 if (_side_vbox_pad[i]) {
430                         _side_vbox[i].remove (*_side_vbox_pad[i]);
431                 }
432                 delete _side_vbox_pad[i];
433                 _side_vbox_pad[i] = 0;
434         }
435
436         for (std::vector<PortGroupTable*>::iterator i = _port_group_tables.begin(); i != _port_group_tables.end(); ++i) {
437                 _port_group_hbox.remove ((*i)->get_widget());
438                 delete *i;
439         }
440
441         _port_group_tables.clear ();
442 }
443
444
445 /** Set up dimensions of some of our widgets which depend on other dimensions
446  *  within the dialogue.
447  */
448 void
449 IOSelector::setup_dimensions ()
450 {
451         /* Get some dimensions from various places */
452         int const scrollbar_height = _scrolled_window.get_hscrollbar()->get_height();
453
454         std::pair<int, int> unit_size (0, 0);
455         int port_group_tables_height = 0;
456         for (std::vector<PortGroupTable*>::iterator i = _port_group_tables.begin(); i != _port_group_tables.end(); ++i) {
457                 std::pair<int, int> const u = (*i)->unit_size ();
458                 unit_size.first = std::max (unit_size.first, u.first);
459                 unit_size.second = std::max (unit_size.second, u.second);
460                 port_group_tables_height = std::max (
461                         port_group_tables_height, (*i)->get_widget().get_height()
462                         );
463         }
464
465         /* Column labels */
466         _column_labels.set_base_width (_port_group_list.n_visible_ports () * unit_size.first);
467
468         /* Scrolled window */
469         /* XXX: really shouldn't set a minimum horizontal size here, but if we don't
470            the window starts up very small */
471         _scrolled_window.set_size_request (
472                 std::min (_column_labels.get_width(), 640),
473                 _column_labels.get_height() + port_group_tables_height + scrollbar_height + 16
474                 );
475         
476         /* Row labels */
477         for (int i = 0; i < 2; ++i) {
478                 for (std::vector<Gtk::EventBox*>::iterator j = _row_labels[i].begin(); j != _row_labels[i].end(); ++j) {
479                         (*j)->get_child()->set_size_request (-1, unit_size.second);
480                 }
481
482                 if (_side_vbox_pad[i]) {
483                         _side_vbox_pad[i]->set_size_request (-1, scrollbar_height + unit_size.second / 4);
484                 }
485         }
486 }
487
488
489 /** Set up the dialogue */
490 void
491 IOSelector::setup ()
492 {
493         clear ();
494
495         /* Work out how many rows we have */
496         ARDOUR::DataType const t = _io->default_type();
497
498         int rows;
499         if (_for_input) {
500                 rows = _io->n_inputs().get(t);
501         } else {
502                 rows = _io->n_outputs().get(t);
503         }       
504         
505         /* Row labels */
506         for (int i = 0; i < 2; ++i) {
507                 _row_labels_vbox[i] = new Gtk::VBox;
508                 for (int j = 0; j < rows; ++j) {
509                         Gtk::Label* label = new Gtk::Label (_for_input ? _io->input(j)->name() : _io->output(j)->name());
510                         Gtk::EventBox* b = new Gtk::EventBox;
511                         b->set_events (Gdk::BUTTON_PRESS_MASK);
512                         b->signal_button_press_event().connect (sigc::bind (sigc::mem_fun (*this, &IOSelector::row_label_button_pressed), j));
513                         b->add (*Gtk::manage (label));
514                         _row_labels[i].push_back (b);
515                         _row_labels_vbox[i]->pack_start (*b, false, false);
516                 }
517
518                 _side_vbox[i].pack_start (*_row_labels_vbox[i], false, false);
519                 _side_vbox_pad[i] = new Gtk::Label ("");
520                 _side_vbox[i].pack_start (*_side_vbox_pad[i], false, false);
521         }
522
523         /* Checkbutton tables */
524         int n = 0;
525         for (PortGroupList::iterator i = _port_group_list.begin(); i != _port_group_list.end(); ++i) {
526                 PortGroupTable* t = new PortGroupTable (**i, _io, _for_input);
527
528                 /* XXX: this is a bit of a hack; should probably use a configurable colour here */
529                 Gdk::Color alt_bg = get_style()->get_bg (Gtk::STATE_NORMAL);
530                 alt_bg.set_rgb (alt_bg.get_red() + 4096, alt_bg.get_green() + 4096, alt_bg.get_blue () + 4096);
531                 if ((n % 2) == 0) {
532                         t->get_widget().modify_bg (Gtk::STATE_NORMAL, alt_bg);
533                 }
534
535                 _port_group_tables.push_back (t);
536                 _port_group_hbox.pack_start (t->get_widget(), false, false);
537                 ++n;
538         }
539
540         show_all ();
541         
542         set_port_group_table_visibility ();
543 }
544
545 void
546 IOSelector::ports_changed (ARDOUR::IOChange change, void *src)
547 {
548         ENSURE_GUI_THREAD (bind (mem_fun (*this, &IOSelector::ports_changed), change, src));
549
550         redisplay ();
551 }
552
553
554 void
555 IOSelector::redisplay ()
556 {
557         _port_group_list.refresh ();
558         setup ();
559 }
560
561
562 /** Handle a button press on a row label */
563 bool
564 IOSelector::row_label_button_pressed (GdkEventButton* e, int r)
565 {
566         if (e->type != GDK_BUTTON_PRESS || e->button != 3) {
567                 return false;
568         }
569
570         Gtk::Menu* menu = Gtk::manage (new Gtk::Menu);
571         Gtk::Menu_Helpers::MenuList& items = menu->items ();
572         menu->set_name ("ArdourContextMenu");
573
574         bool can_add;
575         bool can_remove;
576         std::string name;
577         ARDOUR::DataType const t = _io->default_type();
578
579         if (_for_input) {
580                 can_add = _io->input_maximum().get(t) > _io->n_inputs().get(t);
581                 can_remove = _io->input_minimum().get(t) < _io->n_inputs().get(t);
582                 name = _io->input(r)->name();
583         } else {
584                 can_add = _io->output_maximum().get(t) > _io->n_outputs().get(t);
585                 can_remove = _io->output_minimum().get(t) < _io->n_outputs().get(t);
586                 name = _io->output(r)->name();
587         }
588         
589         items.push_back (
590                 Gtk::Menu_Helpers::MenuElem (_("Add port"), sigc::mem_fun (*this, &IOSelector::add_port))
591                 );
592
593         items.back().set_sensitive (can_add);
594
595         items.push_back (
596                 Gtk::Menu_Helpers::MenuElem (_("Remove port '") + name + _("'"), sigc::bind (sigc::mem_fun (*this, &IOSelector::remove_port), r))
597                 );
598
599         items.back().set_sensitive (can_remove);
600
601         menu->popup (e->button, e->time);
602         
603         return true;
604 }
605
606 void
607 IOSelector::add_port ()
608 {
609         // The IO selector only works for single typed IOs
610         const ARDOUR::DataType t = _io->default_type ();
611
612         if (_for_input) {
613
614                 try {
615                         _io->add_input_port ("", this);
616                 }
617
618                 catch (ARDOUR::AudioEngine::PortRegistrationFailure& err) {
619                         Gtk::MessageDialog msg (0,  _("There are no more JACK ports available."));
620                         msg.run ();
621                 }
622
623         } else {
624
625                 try {
626                         _io->add_output_port ("", this);
627                 }
628
629                 catch (ARDOUR::AudioEngine::PortRegistrationFailure& err) {
630                         Gtk::MessageDialog msg (0, _("There are no more JACK ports available."));
631                         msg.run ();
632                 }
633         }
634 }
635
636 void
637 IOSelector::remove_port (int r)
638 {
639         // The IO selector only works for single typed IOs
640         const ARDOUR::DataType t = _io->default_type ();
641         
642         if (_for_input) {
643                 _io->remove_input_port (_io->input (r), this);
644         } else {
645                 _io->remove_output_port (_io->output (r), this);
646         }
647 }
648
649 void
650 IOSelector::group_visible_toggled (Gtk::CheckButton* b, std::string const & n)
651 {
652         PortGroupList::iterator i = _port_group_list.begin();
653         while (i != _port_group_list.end() & (*i)->name != n) {
654                 ++i;
655         }
656
657         if (i == _port_group_list.end()) {
658                 return;
659         }
660
661         (*i)->visible = b->get_active ();
662
663         set_port_group_table_visibility ();
664
665         _column_labels.queue_draw ();
666 }
667
668 void
669 IOSelector::set_port_group_table_visibility ()
670 {
671         for (std::vector<PortGroupTable*>::iterator j = _port_group_tables.begin(); j != _port_group_tables.end(); ++j) {
672                 if ((*j)->port_group().visible) {
673                         (*j)->get_widget().show();
674                 } else {
675                         (*j)->get_widget().hide();
676                 }
677         }
678 }
679
680
681 PortGroupList::PortGroupList (ARDOUR::Session & session, boost::shared_ptr<ARDOUR::IO> io, bool for_input)
682         : _session (session), _io (io), _for_input (for_input),
683           buss (_("Buss"), "ardour:"),
684           track (_("Track"), "ardour:"),
685           system (_("System"), "system:"),
686           other (_("Other"), "")
687 {
688         refresh ();
689 }
690
691 void
692 PortGroupList::refresh ()
693 {
694         clear ();
695         
696         buss.ports.clear ();
697         track.ports.clear ();
698         system.ports.clear ();
699         other.ports.clear ();
700
701         /* Find the ports provided by ardour; we can't derive their type just from their
702            names, so we'll have to be more devious. */
703
704         boost::shared_ptr<ARDOUR::Session::RouteList> routes = _session.get_routes ();
705
706         for (ARDOUR::Session::RouteList::const_iterator i = routes->begin(); i != routes->end(); ++i) {
707
708                 PortGroup* g = 0;
709                 if (_io->default_type() == ARDOUR::DataType::AUDIO && dynamic_cast<ARDOUR::AudioTrack*> ((*i).get())) {
710                         /* Audio track for an audio IO */
711                         g = &track;
712                 } else if (_io->default_type() == ARDOUR::DataType::MIDI && dynamic_cast<ARDOUR::MidiTrack*> ((*i).get())) {
713                         /* Midi track for a MIDI IO */
714                         g = &track;
715                 } else if (_io->default_type() == ARDOUR::DataType::AUDIO && dynamic_cast<ARDOUR::MidiTrack*> ((*i).get()) == 0) {
716                         /* Non-MIDI track for an Audio IO; must be an audio buss */
717                         g = &buss;
718                 }
719
720                 if (g) {
721                         ARDOUR::PortSet const & p = _for_input ? ((*i)->outputs()) : ((*i)->inputs());
722                         for (uint32_t j = 0; j < p.num_ports(); ++j) {
723                                 g->add (p.port(j)->name ());
724                         }
725
726                         std::sort (g->ports.begin(), g->ports.end());
727                 }
728         }
729         
730
731         /* XXX: inserts, sends, plugin inserts? */
732         
733         /* Now we need to find the non-ardour ports; we do this by first
734            finding all the ports that we can connect to. */
735         const char **ports = _session.engine().get_ports (
736                 "", _io->default_type().to_jack_type(), _for_input ? JackPortIsOutput : JackPortIsInput
737                 );
738
739         if (ports) {
740
741                 int n = 0;
742                 while (ports[n]) {
743                         std::string const p = ports[n];
744
745                         if (p.substr(0, strlen ("system:")) == "system:") {
746                                 /* system: prefix */
747                                 system.add (p);
748                         } else {
749                                 if (p.substr(0, strlen("ardour:")) != "ardour:") {
750                                         /* other (non-ardour) prefix */
751                                         other.add (p);
752                                 }
753                         }
754
755                         ++n;
756                 }
757         }
758
759         push_back (&buss);
760         push_back (&track);
761         push_back (&system);
762         push_back (&other);
763 }
764
765 int
766 PortGroupList::n_visible_ports () const
767 {
768         int n = 0;
769         
770         for (const_iterator i = begin(); i != end(); ++i) {
771                 if ((*i)->visible) {
772                         n += (*i)->ports.size();
773                 }
774         }
775
776         return n;
777 }
778
779 std::string
780 PortGroupList::get_port_by_index (int n, bool with_prefix) const
781 {
782         /* XXX: slightly inefficient algorithm */
783
784         for (const_iterator i = begin(); i != end(); ++i) {
785                 for (std::vector<std::string>::const_iterator j = (*i)->ports.begin(); j != (*i)->ports.end(); ++j) {
786                         if (n == 0) {
787                                 if (with_prefix) {
788                                         return (*i)->prefix + *j;
789                                 } else {
790                                         return *j;
791                                 }
792                         }
793                         --n;
794                 }
795         }
796
797         return "";
798 }
799
800
801 IOSelectorWindow::IOSelectorWindow (
802         ARDOUR::Session& session, boost::shared_ptr<ARDOUR::IO> io, bool for_input, bool can_cancel
803         )
804         : ArdourDialog ("I/O selector"),
805           _selector (session, io, for_input),
806           ok_button (can_cancel ? _("OK"): _("Close")),
807           cancel_button (_("Cancel")),
808           rescan_button (_("Rescan"))
809
810 {
811         add_events (Gdk::KEY_PRESS_MASK | Gdk::KEY_RELEASE_MASK);
812         set_name ("IOSelectorWindow2");
813
814         string title;
815         if (for_input) {
816                 title = string_compose(_("%1 input"), io->name());
817         } else {
818                 title = string_compose(_("%1 output"), io->name());
819         }
820
821         ok_button.set_name ("IOSelectorButton");
822         if (!can_cancel) {
823                 ok_button.set_image (*Gtk::manage (new Gtk::Image (Gtk::Stock::CLOSE, Gtk::ICON_SIZE_BUTTON)));
824         }
825         cancel_button.set_name ("IOSelectorButton");
826         rescan_button.set_name ("IOSelectorButton");
827         rescan_button.set_image (*Gtk::manage (new Gtk::Image (Gtk::Stock::REFRESH, Gtk::ICON_SIZE_BUTTON)));
828
829         get_action_area()->pack_start (rescan_button, false, false);
830
831         if (can_cancel) {
832                 cancel_button.set_image (*Gtk::manage (new Gtk::Image (Gtk::Stock::CANCEL, Gtk::ICON_SIZE_BUTTON)));
833                 get_action_area()->pack_start (cancel_button, false, false);
834         } else {
835                 cancel_button.hide();
836         }
837                 
838         get_action_area()->pack_start (ok_button, false, false);
839
840         get_vbox()->set_spacing (8);
841         get_vbox()->pack_start (_selector);
842
843         ok_button.signal_clicked().connect (mem_fun(*this, &IOSelectorWindow::accept));
844         cancel_button.signal_clicked().connect (mem_fun(*this, &IOSelectorWindow::cancel));
845         rescan_button.signal_clicked().connect (mem_fun(*this, &IOSelectorWindow::rescan));
846
847         set_title (title);
848         set_position (Gtk::WIN_POS_MOUSE);
849
850         show_all ();
851
852         signal_delete_event().connect (bind (sigc::ptr_fun (just_hide_it), reinterpret_cast<Window *> (this)));
853 }
854
855 IOSelectorWindow::~IOSelectorWindow()
856 {
857         
858 }
859
860 void
861 IOSelectorWindow::rescan ()
862 {
863         _selector.redisplay ();
864 }
865
866 void
867 IOSelectorWindow::cancel ()
868 {
869         _selector.Finished (IOSelector::Cancelled);
870         hide ();
871 }
872
873 void
874 IOSelectorWindow::accept ()
875 {
876         _selector.Finished (IOSelector::Accepted);
877         hide ();
878 }
879
880 void
881 IOSelectorWindow::on_map ()
882 {
883         _selector.redisplay ();
884         Window::on_map ();
885 }
886
887
888 PortInsertUI::PortInsertUI (ARDOUR::Session& sess, boost::shared_ptr<ARDOUR::PortInsert> pi)
889         : input_selector (sess, pi->io(), true),
890           output_selector (sess, pi->io(), false)
891 {
892         hbox.pack_start (output_selector, true, true);
893         hbox.pack_start (input_selector, true, true);
894
895         pack_start (hbox);
896 }
897
898 void
899 PortInsertUI::redisplay ()
900 {
901         input_selector.redisplay();
902         output_selector.redisplay();
903 }
904
905 void
906 PortInsertUI::finished (IOSelector::Result r)
907 {
908         input_selector.Finished (r);
909         output_selector.Finished (r);
910 }
911
912
913 PortInsertWindow::PortInsertWindow (ARDOUR::Session& sess, boost::shared_ptr<ARDOUR::PortInsert> pi, bool can_cancel)
914         : ArdourDialog ("port insert dialog"),
915           _portinsertui (sess, pi),
916           ok_button (can_cancel ? _("OK"): _("Close")),
917           cancel_button (_("Cancel")),
918           rescan_button (_("Rescan"))
919 {
920
921         set_name ("IOSelectorWindow");
922         string title = _("ardour: ");
923         title += pi->name();
924         set_title (title);
925         
926         ok_button.set_name ("IOSelectorButton");
927         if (!can_cancel) {
928                 ok_button.set_image (*Gtk::manage (new Gtk::Image (Gtk::Stock::CLOSE, Gtk::ICON_SIZE_BUTTON)));
929         }
930         cancel_button.set_name ("IOSelectorButton");
931         rescan_button.set_name ("IOSelectorButton");
932         rescan_button.set_image (*Gtk::manage (new Gtk::Image (Gtk::Stock::REFRESH, Gtk::ICON_SIZE_BUTTON)));
933
934         get_action_area()->pack_start (rescan_button, false, false);
935         if (can_cancel) {
936                 cancel_button.set_image (*Gtk::manage (new Gtk::Image (Gtk::Stock::CANCEL, Gtk::ICON_SIZE_BUTTON)));
937                 get_action_area()->pack_start (cancel_button, false, false);
938         } else {
939                 cancel_button.hide();
940         }
941         get_action_area()->pack_start (ok_button, false, false);
942
943         get_vbox()->pack_start (_portinsertui);
944
945         ok_button.signal_clicked().connect (mem_fun (*this, &PortInsertWindow::accept));
946         cancel_button.signal_clicked().connect (mem_fun (*this, &PortInsertWindow::cancel));
947         rescan_button.signal_clicked().connect (mem_fun (*this, &PortInsertWindow::rescan));
948
949         signal_delete_event().connect (bind (sigc::ptr_fun (just_hide_it), reinterpret_cast<Window *> (this))); 
950
951         going_away_connection = pi->GoingAway.connect (mem_fun (*this, &PortInsertWindow::plugin_going_away));
952 }
953
954 void
955 PortInsertWindow::plugin_going_away ()
956 {
957         ENSURE_GUI_THREAD (mem_fun (*this, &PortInsertWindow::plugin_going_away));
958         
959         going_away_connection.disconnect ();
960         delete_when_idle (this);
961 }
962
963 void
964 PortInsertWindow::on_map ()
965 {
966         _portinsertui.redisplay ();
967         Window::on_map ();
968 }
969
970
971 void
972 PortInsertWindow::rescan ()
973 {
974         _portinsertui.redisplay ();
975 }
976
977 void
978 PortInsertWindow::cancel ()
979 {
980         _portinsertui.finished (IOSelector::Cancelled);
981         hide ();
982 }
983
984 void
985 PortInsertWindow::accept ()
986 {
987         _portinsertui.finished (IOSelector::Accepted);
988         hide ();
989 }