fix crash caused by storing clock modes while loading a session
[ardour.git] / gtk2_ardour / ardour_ui.cc
1 /*
2  * Copyright (C) 2005-2007 Doug McLain <doug@nostar.net>
3  * Copyright (C) 2005-2017 Tim Mayberry <mojofunk@gmail.com>
4  * Copyright (C) 2005-2019 Paul Davis <paul@linuxaudiosystems.com>
5  * Copyright (C) 2005 Karsten Wiese <fzuuzf@googlemail.com>
6  * Copyright (C) 2005 Taybin Rutkin <taybin@taybin.com>
7  * Copyright (C) 2006-2015 David Robillard <d@drobilla.net>
8  * Copyright (C) 2007-2012 Carl Hetherington <carl@carlh.net>
9  * Copyright (C) 2008-2010 Sakari Bergen <sakari.bergen@beatwaves.net>
10  * Copyright (C) 2012-2019 Robin Gareus <robin@gareus.org>
11  * Copyright (C) 2013-2015 Colin Fletcher <colin.m.fletcher@googlemail.com>
12  * Copyright (C) 2013-2016 John Emmas <john@creativepost.co.uk>
13  * Copyright (C) 2013-2016 Nick Mainsbridge <mainsbridge@gmail.com>
14  * Copyright (C) 2014-2018 Ben Loftis <ben@harrisonconsoles.com>
15  * Copyright (C) 2015 AndrĂ© Nusser <andre.nusser@googlemail.com>
16  * Copyright (C) 2016-2018 Len Ovens <len@ovenwerks.net>
17  * Copyright (C) 2017 Johannes Mueller <github@johannes-mueller.org>
18  *
19  * This program is free software; you can redistribute it and/or modify
20  * it under the terms of the GNU General Public License as published by
21  * the Free Software Foundation; either version 2 of the License, or
22  * (at your option) any later version.
23  *
24  * This program is distributed in the hope that it will be useful,
25  * but WITHOUT ANY WARRANTY; without even the implied warranty of
26  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27  * GNU General Public License for more details.
28  *
29  * You should have received a copy of the GNU General Public License along
30  * with this program; if not, write to the Free Software Foundation, Inc.,
31  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
32  */
33
34 #ifdef WAF_BUILD
35 #include "gtk2ardour-config.h"
36 #include "gtk2ardour-version.h"
37 #endif
38
39 #include <algorithm>
40 #include <cmath>
41 #include <iostream>
42 #include <cerrno>
43
44 #include <stdarg.h>
45
46 #ifndef PLATFORM_WINDOWS
47 #include <sys/resource.h>
48 #endif
49
50 #ifdef __FreeBSD__
51 #include <sys/types.h>
52 #include <sys/sysctl.h>
53 #endif
54
55 #include <stdint.h>
56 #include <fcntl.h>
57 #include <signal.h>
58 #include <unistd.h>
59 #include <time.h>
60
61 #include <glib.h>
62 #include "pbd/gstdio_compat.h"
63
64 #include <gtkmm/accelmap.h>
65 #include <gtkmm/messagedialog.h>
66 #include <gtkmm/stock.h>
67 #include <gtkmm/uimanager.h>
68
69 #include "pbd/error.h"
70 #include "pbd/basename.h"
71 #include "pbd/compose.h"
72 #include "pbd/convert.h"
73 #include "pbd/failed_constructor.h"
74 #include "pbd/file_archive.h"
75 #include "pbd/enumwriter.h"
76 #include "pbd/memento_command.h"
77 #include "pbd/openuri.h"
78 #include "pbd/stl_delete.h"
79 #include "pbd/types_convert.h"
80 #include "pbd/unwind.h"
81 #include "pbd/file_utils.h"
82 #include "pbd/localtime_r.h"
83 #include "pbd/pthread_utils.h"
84 #include "pbd/replace_all.h"
85 #include "pbd/scoped_file_descriptor.h"
86 #include "pbd/xml++.h"
87
88 #include "gtkmm2ext/application.h"
89 #include "gtkmm2ext/bindings.h"
90 #include "gtkmm2ext/gtk_ui.h"
91 #include "gtkmm2ext/utils.h"
92 #include "gtkmm2ext/window_title.h"
93
94 #include "widgets/fastmeter.h"
95 #include "widgets/prompter.h"
96 #include "widgets/tooltips.h"
97
98 #include "ardour/ardour.h"
99 #include "ardour/audio_backend.h"
100 #include "ardour/audio_track.h"
101 #include "ardour/audioengine.h"
102 #include "ardour/audiofilesource.h"
103 #include "ardour/automation_watch.h"
104 #include "ardour/disk_reader.h"
105 #include "ardour/disk_writer.h"
106 #include "ardour/filename_extensions.h"
107 #include "ardour/filesystem_paths.h"
108 #include "ardour/ltc_file_reader.h"
109 #include "ardour/monitor_control.h"
110 #include "ardour/midi_track.h"
111 #include "ardour/port.h"
112 #include "ardour/plugin_manager.h"
113 #include "ardour/process_thread.h"
114 #include "ardour/profile.h"
115 #include "ardour/recent_sessions.h"
116 #include "ardour/record_enable_control.h"
117 #include "ardour/revision.h"
118 #include "ardour/session_directory.h"
119 #include "ardour/session_route.h"
120 #include "ardour/session_state_utils.h"
121 #include "ardour/session_utils.h"
122 #include "ardour/source_factory.h"
123 #include "ardour/transport_master.h"
124 #include "ardour/transport_master_manager.h"
125 #include "ardour/system_exec.h"
126 #include "ardour/track.h"
127 #include "ardour/vca_manager.h"
128 #include "ardour/utils.h"
129
130 #include "LuaBridge/LuaBridge.h"
131
132 #ifdef WINDOWS_VST_SUPPORT
133 #include <fst.h>
134 #endif
135 #ifdef AUDIOUNIT_SUPPORT
136 #include "ardour/audio_unit.h"
137 #endif
138
139 // fix for OSX (nsm.h has a check function, AU/Apple defines check)
140 #ifdef check
141 #undef check
142 #endif
143
144 #include "temporal/time.h"
145
146 typedef uint64_t microseconds_t;
147
148 #include "about.h"
149 #include "editing.h"
150 #include "enums_convert.h"
151 #include "actions.h"
152 #include "add_route_dialog.h"
153 #include "ambiguous_file_dialog.h"
154 #include "ardour_ui.h"
155 #include "audio_clock.h"
156 #include "audio_region_view.h"
157 #include "big_clock_window.h"
158 #include "big_transport_window.h"
159 #include "bundle_manager.h"
160 #include "duplicate_routes_dialog.h"
161 #include "debug.h"
162 #include "engine_dialog.h"
163 #include "export_video_dialog.h"
164 #include "export_video_infobox.h"
165 #include "gain_meter.h"
166 #include "global_port_matrix.h"
167 #include "gui_object.h"
168 #include "gui_thread.h"
169 #include "idleometer.h"
170 #include "keyboard.h"
171 #include "keyeditor.h"
172 #include "location_ui.h"
173 #include "lua_script_manager.h"
174 #include "luawindow.h"
175 #include "main_clock.h"
176 #include "missing_file_dialog.h"
177 #include "missing_plugin_dialog.h"
178 #include "mixer_ui.h"
179 #include "meterbridge.h"
180 #include "meter_patterns.h"
181 #include "mouse_cursors.h"
182 #include "nsm.h"
183 #include "opts.h"
184 #include "pingback.h"
185 #include "plugin_dspload_window.h"
186 #include "processor_box.h"
187 #include "public_editor.h"
188 #include "rc_option_editor.h"
189 #include "route_time_axis.h"
190 #include "route_params_ui.h"
191 #include "save_as_dialog.h"
192 #include "save_template_dialog.h"
193 #include "script_selector.h"
194 #include "session_archive_dialog.h"
195 #include "session_dialog.h"
196 #include "session_metadata_dialog.h"
197 #include "session_option_editor.h"
198 #include "speaker_dialog.h"
199 #include "splash.h"
200 #include "template_dialog.h"
201 #include "time_axis_view_item.h"
202 #include "time_info_box.h"
203 #include "timers.h"
204 #include "transport_masters_dialog.h"
205 #include "utils.h"
206 #include "utils_videotl.h"
207 #include "video_server_dialog.h"
208 #include "virtual_keyboard_window.h"
209 #include "add_video_dialog.h"
210 #include "transcode_video_dialog.h"
211
212 #include "pbd/i18n.h"
213
214 using namespace ARDOUR;
215 using namespace ARDOUR_UI_UTILS;
216 using namespace PBD;
217 using namespace Gtkmm2ext;
218 using namespace ArdourWidgets;
219 using namespace Gtk;
220 using namespace std;
221 using namespace Editing;
222
223 ARDOUR_UI *ARDOUR_UI::theArdourUI = 0;
224
225 sigc::signal<void, samplepos_t> ARDOUR_UI::Clock;
226 sigc::signal<void> ARDOUR_UI::CloseAllDialogs;
227
228 static bool
229 ask_about_configuration_copy (string const & old_dir, string const & new_dir, int version)
230 {
231         MessageDialog msg (string_compose (_("%1 %2.x has discovered configuration files from %1 %3.x.\n\n"
232                                              "Would you like these files to be copied and used for %1 %2.x?\n\n"
233                                              "(This will require you to restart %1.)"),
234                                            PROGRAM_NAME, PROGRAM_VERSION, version),
235                            false, /* no markup */
236                            Gtk::MESSAGE_INFO,
237                            Gtk::BUTTONS_YES_NO,
238                            true /* modal, though it hardly matters since it is the only window */
239         );
240
241         msg.set_default_response (Gtk::RESPONSE_YES);
242         msg.show_all ();
243
244         return (msg.run() == Gtk::RESPONSE_YES);
245 }
246
247 static void
248 libxml_generic_error_func (void* /* parsing_context*/,
249                            const char* msg,
250                            ...)
251 {
252         va_list ap;
253         char buf[2048];
254
255         va_start (ap, msg);
256         vsnprintf (buf, sizeof (buf), msg, ap);
257         error << buf << endmsg;
258         va_end (ap);
259 }
260
261 static void
262 libxml_structured_error_func (void* /* parsing_context*/,
263                               xmlErrorPtr err)
264 {
265         string msg;
266
267         if (err->message)
268                 msg = err->message;
269
270         replace_all (msg, "\n", "");
271
272         if (!msg.empty()) {
273                 if (err->file && err->line) {
274                         error << X_("XML error: ") << msg << " in " << err->file << " at line " << err->line;
275
276                         if (err->int2) {
277                                 error << ':' << err->int2;
278                         }
279
280                         error << endmsg;
281                 } else {
282                         error << X_("XML error: ") << msg << endmsg;
283                 }
284         }
285 }
286
287
288 ARDOUR_UI::ARDOUR_UI (int *argcp, char **argvp[], const char* localedir)
289         : Gtkmm2ext::UI (PROGRAM_NAME, X_("gui"), argcp, argvp)
290         , session_load_in_progress (false)
291         , gui_object_state (new GUIObjectState)
292         , primary_clock   (new MainClock (X_("primary"),   X_("transport"), true ))
293         , secondary_clock (new MainClock (X_("secondary"), X_("secondary"), false))
294         , big_clock (new AudioClock (X_("bigclock"), false, "big", true, true, false, false))
295         , video_timeline(0)
296         , ignore_dual_punch (false)
297         , main_window_visibility (0)
298         , editor (0)
299         , mixer (0)
300         , nsm (0)
301         , _was_dirty (false)
302         , _mixer_on_top (false)
303         , _shared_popup_menu (0)
304         , startup_fsm (0)
305         , secondary_clock_spacer (0)
306         , auto_input_button (ArdourButton::led_default_elements)
307         , latency_disable_button (ArdourButton::led_default_elements)
308         , time_info_box (0)
309         , auto_return_button (ArdourButton::led_default_elements)
310         , follow_edits_button (ArdourButton::led_default_elements)
311         , auditioning_alert_button (_("Audition"))
312         , solo_alert_button (_("Solo"))
313         , feedback_alert_button (_("Feedback"))
314         , error_alert_button ( ArdourButton::just_led_default_elements )
315         , editor_meter_peak_display()
316         , editor_meter(0)
317         , _numpad_locate_happening (false)
318         , _session_is_new (false)
319         , last_key_press_time (0)
320         , save_as_dialog (0)
321         , meterbridge (0)
322         , luawindow (0)
323         , rc_option_editor (0)
324         , speaker_config_window (X_("speaker-config"), _("Speaker Configuration"))
325         , add_route_dialog (X_("add-routes"), _("Add Tracks/Busses"))
326         , about (X_("about"), _("About"))
327         , location_ui (X_("locations"), S_("Ranges|Locations"))
328         , route_params (X_("inspector"), _("Tracks and Busses"))
329         , audio_midi_setup (X_("audio-midi-setup"), _("Audio/MIDI Setup"))
330         , export_video_dialog (X_("video-export"), _("Video Export Dialog"))
331         , lua_script_window (X_("script-manager"), _("Script Manager"))
332         , idleometer (X_("idle-o-meter"), _("Idle'o'Meter"))
333         , plugin_dsp_load_window (X_("plugin-dsp-load"), _("Plugin DSP Load"))
334         , transport_masters_window (X_("transport-masters"), _("Transport Masters"))
335         , session_option_editor (X_("session-options-editor"), _("Properties"), boost::bind (&ARDOUR_UI::create_session_option_editor, this))
336         , add_video_dialog (X_("add-video"), _("Add Video"), boost::bind (&ARDOUR_UI::create_add_video_dialog, this))
337         , bundle_manager (X_("bundle-manager"), _("Bundle Manager"), boost::bind (&ARDOUR_UI::create_bundle_manager, this))
338         , big_clock_window (X_("big-clock"), _("Big Clock"), boost::bind (&ARDOUR_UI::create_big_clock_window, this))
339         , big_transport_window (X_("big-transport"), _("Transport Controls"), boost::bind (&ARDOUR_UI::create_big_transport_window, this))
340         , virtual_keyboard_window (X_("virtual-keyboard"), _("Virtual Keyboard"), boost::bind (&ARDOUR_UI::create_virtual_keyboard_window, this))
341         , audio_port_matrix (X_("audio-connection-manager"), _("Audio Connections"), boost::bind (&ARDOUR_UI::create_global_port_matrix, this, ARDOUR::DataType::AUDIO))
342         , midi_port_matrix (X_("midi-connection-manager"), _("MIDI Connections"), boost::bind (&ARDOUR_UI::create_global_port_matrix, this, ARDOUR::DataType::MIDI))
343         , key_editor (X_("key-editor"), _("Keyboard Shortcuts"), boost::bind (&ARDOUR_UI::create_key_editor, this))
344         , video_server_process (0)
345         , have_configure_timeout (false)
346         , last_configure_time (0)
347         , last_peak_grab (0)
348         , have_disk_speed_dialog_displayed (false)
349         , _status_bar_visibility (X_("status-bar"))
350         , _feedback_exists (false)
351         , _log_not_acknowledged (LogLevelNone)
352         , duplicate_routes_dialog (0)
353         , editor_visibility_button (S_("Window|Editor"))
354         , mixer_visibility_button (S_("Window|Mixer"))
355         , prefs_visibility_button (S_("Window|Preferences"))
356 {
357         Gtkmm2ext::init (localedir);
358
359         UIConfiguration::instance().post_gui_init ();
360
361         if (ARDOUR::handle_old_configuration_files (boost::bind (ask_about_configuration_copy, _1, _2, _3))) {
362                 {
363                         /* "touch" the been-here-before path now that config has been migrated */
364                         PBD::ScopedFileDescriptor fout (g_open (been_here_before_path ().c_str(), O_CREAT|O_TRUNC|O_RDWR, 0666));
365                 }
366                 MessageDialog msg (string_compose (_("Your configuration files were copied. You can now restart %1."), PROGRAM_NAME), true);
367                 msg.run ();
368                 /* configuration was modified, exit immediately */
369                 _exit (EXIT_SUCCESS);
370         }
371
372
373         if (theArdourUI == 0) {
374                 theArdourUI = this;
375         }
376
377         /* track main window visibility */
378
379         main_window_visibility = new VisibilityTracker (_main_window);
380
381         /* stop libxml from spewing to stdout/stderr */
382
383         xmlSetGenericErrorFunc (this, libxml_generic_error_func);
384         xmlSetStructuredErrorFunc (this, libxml_structured_error_func);
385
386         /* Set this up early */
387
388         ActionManager::init ();
389
390         /* we like keyboards */
391
392         keyboard = new ArdourKeyboard(*this);
393
394         XMLNode* node = ARDOUR_UI::instance()->keyboard_settings();
395         if (node) {
396                 keyboard->set_state (*node, Stateful::loading_state_version);
397         }
398
399         /* actions do not need to be defined when we load keybindings. They
400          * will be lazily discovered. But bindings do need to exist when we
401          * create windows/tabs with their own binding sets.
402          */
403
404         keyboard->setup_keybindings ();
405
406         if ((global_bindings = Bindings::get_bindings (X_("Global"))) == 0) {
407                 error << _("Global keybindings are missing") << endmsg;
408         }
409
410         install_actions ();
411
412         UIConfiguration::instance().ParameterChanged.connect (sigc::mem_fun (*this, &ARDOUR_UI::parameter_changed));
413         boost::function<void (string)> pc (boost::bind (&ARDOUR_UI::parameter_changed, this, _1));
414         UIConfiguration::instance().map_parameters (pc);
415
416         transport_ctrl.setup (this);
417
418         ARDOUR::DiskWriter::Overrun.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::disk_overrun_handler, this), gui_context());
419         ARDOUR::DiskReader::Underrun.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::disk_underrun_handler, this), gui_context());
420
421         ARDOUR::Session::VersionMismatch.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::session_format_mismatch, this, _1, _2), gui_context());
422
423         /* handle dialog requests */
424
425         ARDOUR::Session::Dialog.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::session_dialog, this, _1), gui_context());
426
427         /* handle pending state with a dialog (PROBLEM: needs to return a value and thus cannot be x-thread) */
428
429         ARDOUR::Session::AskAboutPendingState.connect_same_thread (forever_connections, boost::bind (&ARDOUR_UI::pending_state_dialog, this));
430
431         /* handle sr mismatch with a dialog (PROBLEM: needs to return a value and thus cannot be x-thread) */
432
433         ARDOUR::Session::AskAboutSampleRateMismatch.connect_same_thread (forever_connections, boost::bind (&ARDOUR_UI::sr_mismatch_dialog, this, _1, _2));
434
435         /* handle sr mismatch with a dialog - cross-thread from engine */
436         ARDOUR::Session::NotifyAboutSampleRateMismatch.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::sr_mismatch_message, this, _1, _2), gui_context ());
437
438         /* handle requests to quit (coming from JACK session) */
439
440         ARDOUR::Session::Quit.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::finish, this), gui_context ());
441
442         /* tell the user about feedback */
443
444         ARDOUR::Session::FeedbackDetected.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::feedback_detected, this), gui_context ());
445         ARDOUR::Session::SuccessfulGraphSort.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::successful_graph_sort, this), gui_context ());
446
447         /* indicate global latency compensation en/disable */
448         ARDOUR::Latent::DisableSwitchChanged.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::latency_switch_changed, this), gui_context ());
449
450         /* handle requests to deal with missing files */
451
452         ARDOUR::Session::MissingFile.connect_same_thread (forever_connections, boost::bind (&ARDOUR_UI::missing_file, this, _1, _2, _3));
453
454         /* and ambiguous files */
455
456         ARDOUR::FileSource::AmbiguousFileName.connect_same_thread (forever_connections, boost::bind (&ARDOUR_UI::ambiguous_file, this, _1, _2));
457
458         ARDOUR::GUIIdle.connect (forever_connections, MISSING_INVALIDATOR, boost::bind(&ARDOUR_UI::gui_idle_handler, this), gui_context());
459
460         Config->ParameterChanged.connect ( forever_connections, MISSING_INVALIDATOR, boost::bind(&ARDOUR_UI::set_flat_buttons, this), gui_context() );
461         set_flat_buttons();
462
463         theme_changed.connect (sigc::mem_fun(*this, &ARDOUR_UI::on_theme_changed));
464         UIConfiguration::instance().ColorsChanged.connect (sigc::mem_fun (*this, &ARDOUR_UI::on_theme_changed));
465         UIConfiguration::instance().DPIReset.connect (sigc::mem_fun (*this, &ARDOUR_UI::on_theme_changed));
466
467         /* lets get this party started */
468
469         setup_gtk_ardour_enums ();
470         setup_profile ();
471
472         SessionEvent::create_per_thread_pool ("GUI", 4096);
473
474         UIConfiguration::instance().reset_dpi ();
475
476         TimeAxisViewItem::set_constant_heights ();
477
478         /* The following must happen after ARDOUR::init() so that Config is set up */
479
480         const XMLNode* ui_xml = Config->extra_xml (X_("UI"));
481
482         if (ui_xml) {
483                 key_editor.set_state (*ui_xml, 0);
484                 session_option_editor.set_state (*ui_xml, 0);
485                 speaker_config_window.set_state (*ui_xml, 0);
486                 about.set_state (*ui_xml, 0);
487                 add_route_dialog.set_state (*ui_xml, 0);
488                 add_video_dialog.set_state (*ui_xml, 0);
489                 route_params.set_state (*ui_xml, 0);
490                 bundle_manager.set_state (*ui_xml, 0);
491                 location_ui.set_state (*ui_xml, 0);
492                 big_clock_window.set_state (*ui_xml, 0);
493                 big_transport_window.set_state (*ui_xml, 0);
494                 virtual_keyboard_window.set_state (*ui_xml, 0);
495                 audio_port_matrix.set_state (*ui_xml, 0);
496                 midi_port_matrix.set_state (*ui_xml, 0);
497                 export_video_dialog.set_state (*ui_xml, 0);
498                 lua_script_window.set_state (*ui_xml, 0);
499                 idleometer.set_state (*ui_xml, 0);
500                 plugin_dsp_load_window.set_state (*ui_xml, 0);
501                 transport_masters_window.set_state (*ui_xml, 0);
502         }
503
504         /* Separate windows */
505
506         WM::Manager::instance().register_window (&key_editor);
507         WM::Manager::instance().register_window (&session_option_editor);
508         WM::Manager::instance().register_window (&speaker_config_window);
509         WM::Manager::instance().register_window (&about);
510         WM::Manager::instance().register_window (&add_route_dialog);
511         WM::Manager::instance().register_window (&add_video_dialog);
512         WM::Manager::instance().register_window (&route_params);
513         WM::Manager::instance().register_window (&audio_midi_setup);
514         WM::Manager::instance().register_window (&export_video_dialog);
515         WM::Manager::instance().register_window (&lua_script_window);
516         WM::Manager::instance().register_window (&bundle_manager);
517         WM::Manager::instance().register_window (&location_ui);
518         WM::Manager::instance().register_window (&big_clock_window);
519         WM::Manager::instance().register_window (&big_transport_window);
520         WM::Manager::instance().register_window (&virtual_keyboard_window);
521         WM::Manager::instance().register_window (&audio_port_matrix);
522         WM::Manager::instance().register_window (&midi_port_matrix);
523         WM::Manager::instance().register_window (&idleometer);
524         WM::Manager::instance().register_window (&plugin_dsp_load_window);
525         WM::Manager::instance().register_window (&transport_masters_window);
526
527         /* do not retain position for add route dialog */
528         add_route_dialog.set_state_mask (WindowProxy::Size);
529
530         /* Trigger setting up the color scheme and loading the GTK RC file */
531
532         UIConfiguration::instance().load_rc_file (false);
533
534         _process_thread = new ProcessThread ();
535
536         ARDOUR::Port::set_connecting_blocked (ARDOUR_COMMAND_LINE::no_connect_ports);
537 }
538
539 GlobalPortMatrixWindow*
540 ARDOUR_UI::create_global_port_matrix (ARDOUR::DataType type)
541 {
542         if (!_session) {
543                 return 0;
544         }
545         return new GlobalPortMatrixWindow (_session, type);
546 }
547
548 void
549 ARDOUR_UI::attach_to_engine ()
550 {
551         AudioEngine::instance()->Running.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::engine_running, this, _1), gui_context());
552         engine_running (0);
553 }
554
555 void
556 ARDOUR_UI::engine_stopped ()
557 {
558         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::engine_stopped)
559         ActionManager::set_sensitive (ActionManager::engine_sensitive_actions, false);
560         ActionManager::set_sensitive (ActionManager::engine_opposite_sensitive_actions, true);
561         update_sample_rate (0);
562         update_cpu_load ();
563 }
564
565 void
566 ARDOUR_UI::engine_running (uint32_t cnt)
567 {
568         if (cnt == 0) {
569                 post_engine();
570         }
571
572         if (_session) {
573                 _session->reset_xrun_count ();
574         }
575         update_disk_space ();
576         update_cpu_load ();
577         update_sample_rate (AudioEngine::instance()->sample_rate());
578         update_timecode_format ();
579         update_peak_thread_work ();
580         ActionManager::set_sensitive (ActionManager::engine_sensitive_actions, true);
581         ActionManager::set_sensitive (ActionManager::engine_opposite_sensitive_actions, false);
582 }
583
584 void
585 ARDOUR_UI::engine_halted (const char* reason, bool free_reason)
586 {
587         if (!Gtkmm2ext::UI::instance()->caller_is_ui_thread()) {
588                 /* we can't rely on the original string continuing to exist when we are called
589                    again in the GUI thread, so make a copy and note that we need to
590                    free it later.
591                 */
592                 char *copy = strdup (reason);
593                 Gtkmm2ext::UI::instance()->call_slot (MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::engine_halted, this, copy, true));
594                 return;
595         }
596
597         ActionManager::set_sensitive (ActionManager::engine_sensitive_actions, false);
598         ActionManager::set_sensitive (ActionManager::engine_opposite_sensitive_actions, true);
599
600         update_sample_rate (0);
601
602         string msgstr;
603
604         /* if the reason is a non-empty string, it means that the backend was shutdown
605            rather than just Ardour.
606         */
607
608         if (strlen (reason)) {
609                 msgstr = string_compose (_("The audio backend was shutdown because:\n\n%1"), reason);
610         } else {
611                 msgstr = string_compose (_("\
612 The audio backend has either been shutdown or it\n\
613 disconnected %1 because %1\n\
614 was not fast enough. Try to restart\n\
615 the audio backend and save the session."), PROGRAM_NAME);
616         }
617
618         MessageDialog msg (_main_window, msgstr);
619         pop_back_splash (msg);
620         msg.run ();
621
622         if (free_reason) {
623                 free (const_cast<char*> (reason));
624         }
625 }
626
627 void
628 ARDOUR_UI::post_engine ()
629 {
630         /* Things to be done once (and once ONLY) after we have a backend running in the AudioEngine
631          */
632 #ifdef AUDIOUNIT_SUPPORT
633         std::string au_msg;
634         if (AUPluginInfo::au_get_crashlog(au_msg)) {
635                 popup_error(_("Audio Unit Plugin Scan Failed. Automatic AU scanning has been disabled. Please see the log window for further details."));
636                 error << _("Audio Unit Plugin Scan Failed:") << endmsg;
637                 info << au_msg << endmsg;
638         }
639 #endif
640
641         /* connect to important signals */
642
643         AudioEngine::instance()->Stopped.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::engine_stopped, this), gui_context());
644         AudioEngine::instance()->SampleRateChanged.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::update_sample_rate, this, _1), gui_context());
645         AudioEngine::instance()->BufferSizeChanged.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::update_sample_rate, this, _1), gui_context());
646         AudioEngine::instance()->Halted.connect_same_thread (halt_connection, boost::bind (&ARDOUR_UI::engine_halted, this, _1, false));
647         AudioEngine::instance()->BecameSilent.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::audioengine_became_silent, this), gui_context());
648
649         if (setup_windows ()) {
650                 throw failed_constructor ();
651         }
652
653         transport_ctrl.map_actions ();
654
655         /* Do this after setup_windows (), as that's when the _status_bar_visibility is created */
656         XMLNode* n = Config->extra_xml (X_("UI"));
657         if (n) {
658                 _status_bar_visibility.set_state (*n);
659         }
660
661         check_memory_locking();
662
663         /* this is the first point at which all the possible actions are
664          * available, because some of the available actions are dependent on
665          * aspects of the engine/backend.
666          */
667
668         if (ARDOUR_COMMAND_LINE::show_key_actions) {
669                 stringstream sstr;
670                 Bindings::save_all_bindings_as_html (sstr);
671
672                 if (sstr.str().empty()) {
673                         return;
674                 }
675                 gchar* file_name;
676                 GError *err = NULL;
677                 gint fd;
678
679                 if ((fd = g_file_open_tmp ("akprintXXXXXX.html", &file_name, &err)) < 0) {
680                         if (err) {
681                                 error << string_compose (_("Could not open temporary file to print bindings (%1)"), err->message) << endmsg;
682                                 g_error_free (err);
683                         }
684                         return;
685                 }
686
687 #ifdef PLATFORM_WINDOWS
688                 ::close (fd);
689 #endif
690
691                 err = NULL;
692
693                 if (!g_file_set_contents (file_name, sstr.str().c_str(), sstr.str().size(), &err)) {
694 #ifndef PLATFORM_WINDOWS
695                         ::close (fd);
696 #endif
697                         g_unlink (file_name);
698                         if (err) {
699                                 error << string_compose (_("Could not save bindings to file (%1)"), err->message) << endmsg;
700                                 g_error_free (err);
701                         }
702                         return;
703                 }
704
705 #ifndef PLATFORM_WINDOWS
706                 ::close (fd);
707 #endif
708
709                 PBD::open_uri (string_compose ("file:///%1", file_name));
710
711                 halt_connection.disconnect ();
712                 AudioEngine::instance()->stop ();
713                 exit (EXIT_SUCCESS);
714
715         }
716
717         if (ARDOUR_COMMAND_LINE::show_actions) {
718
719
720                 vector<string> paths;
721                 vector<string> labels;
722                 vector<string> tooltips;
723                 vector<string> keys;
724                 vector<Glib::RefPtr<Gtk::Action> > actions;
725                 string ver_in = revision;
726                 string ver = ver_in.substr(0, ver_in.find("-"));
727
728                 stringstream output;
729                 output << "\n<h2>Menu actions</h2>" << endl;
730                 output << "<p>\n  Every single menu item in " << PROGRAM_NAME << "'s GUI is accessible by control" << endl;
731                 output << "  surfaces or scripts.\n</p>\n" << endl;
732                 output << "<p>\n  The list below shows all available values of <em>action-name</em> as of" << endl;
733                 output << "  " << PROGRAM_NAME << " " << ver << ". You can get the current list at any" << endl;
734                 output << "  time by running " << PROGRAM_NAME << " with the -A flag.\n</p>\n" << endl;
735                 output << "<table class=\"dl\">\n  <thead>" << endl;
736                 output << "      <tr><th>Action Name</th><th>Menu Name</th></tr>" << endl;
737                 output << "  </thead>\n  <tbody>" << endl;
738
739                 ActionManager::get_all_actions (paths, labels, tooltips, keys, actions);
740
741                 vector<string>::iterator p;
742                 vector<string>::iterator l;
743
744                 for (p = paths.begin(), l = labels.begin(); p != paths.end(); ++p, ++l) {
745                         output << " <tr><th><kbd class=\"osc\">" << *p << "</kbd></th><td>" << *l << "</td></tr>" << endl;
746                 }
747                 output << "  </tbody>\n  </table>" << endl;
748
749                 // output this mess to a browser for easiest X-platform use
750                 // it is not pretty HTML, but it works and it's main purpose
751                 // is to create raw html to fit in Ardour's manual with no editing
752                 gchar* file_name;
753                 GError *err = NULL;
754                 gint fd;
755
756                 if ((fd = g_file_open_tmp ("list-of-menu-actionsXXXXXX.html", &file_name, &err)) < 0) {
757                         if (err) {
758                                 error << string_compose (_("Could not open temporary file to print bindings (%1)"), err->message) << endmsg;
759                                 g_error_free (err);
760                         }
761                         return;
762                 }
763
764 #ifdef PLATFORM_WINDOWS
765                 ::close (fd);
766 #endif
767
768                 err = NULL;
769
770                 if (!g_file_set_contents (file_name, output.str().c_str(), output.str().size(), &err)) {
771 #ifndef PLATFORM_WINDOWS
772                         ::close (fd);
773 #endif
774                         g_unlink (file_name);
775                         if (err) {
776                                 error << string_compose (_("Could not save bindings to file (%1)"), err->message) << endmsg;
777                                 g_error_free (err);
778                         }
779                         return;
780                 }
781
782 #ifndef PLATFORM_WINDOWS
783                 ::close (fd);
784 #endif
785
786                 PBD::open_uri (string_compose ("file:///%1", file_name));
787
788                 halt_connection.disconnect ();
789                 AudioEngine::instance()->stop ();
790                 exit (EXIT_SUCCESS);
791         }
792
793         /* this being a GUI and all, we want peakfiles */
794
795         AudioFileSource::set_build_peakfiles (true);
796         AudioFileSource::set_build_missing_peakfiles (true);
797
798         /* set default clock modes */
799
800         primary_clock->set_mode (AudioClock::Timecode);
801         secondary_clock->set_mode (AudioClock::BBT);
802
803         /* start the time-of-day-clock */
804
805 #ifndef __APPLE__
806         /* OS X provides a nearly-always visible wallclock, so don't be stupid */
807         update_wall_clock ();
808         Glib::signal_timeout().connect_seconds (sigc::mem_fun(*this, &ARDOUR_UI::update_wall_clock), 1);
809 #endif
810
811         {
812                 DisplaySuspender ds;
813                 Config->ParameterChanged.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::parameter_changed, this, _1), gui_context());
814                 boost::function<void (string)> pc (boost::bind (&ARDOUR_UI::parameter_changed, this, _1));
815                 Config->map_parameters (pc);
816
817                 UIConfiguration::instance().map_parameters (pc);
818         }
819 }
820
821 ARDOUR_UI::~ARDOUR_UI ()
822 {
823         UIConfiguration::instance().save_state();
824
825         ARDOUR_UI_UTILS::inhibit_screensaver (false);
826
827         stop_video_server();
828
829         if (getenv ("ARDOUR_RUNNING_UNDER_VALGRIND")) {
830                 // don't bother at 'real' exit. the OS cleans up for us.
831                 delete big_clock; big_clock = 0;
832                 delete primary_clock; primary_clock = 0;
833                 delete secondary_clock; secondary_clock = 0;
834                 delete _process_thread; _process_thread = 0;
835                 delete time_info_box; time_info_box = 0;
836                 delete meterbridge; meterbridge = 0;
837                 delete luawindow; luawindow = 0;
838                 delete editor; editor = 0;
839                 delete mixer; mixer = 0;
840                 delete rc_option_editor; rc_option_editor = 0; // failed to wrap object warning
841                 delete nsm; nsm = 0;
842                 delete gui_object_state; gui_object_state = 0;
843                 delete _shared_popup_menu ; _shared_popup_menu = 0;
844                 delete main_window_visibility;
845                 FastMeter::flush_pattern_cache ();
846                 ArdourFader::flush_pattern_cache ();
847         }
848
849 #ifndef NDEBUG
850         /* Small trick to flush main-thread event pool.
851          * Other thread-pools are destroyed at pthread_exit(),
852          * but tmain thread termination is too late to trigger Pool::~Pool()
853          */
854         SessionEvent* ev = new SessionEvent (SessionEvent::SetTransportSpeed, SessionEvent::Clear, SessionEvent::Immediate, 0, 0); // get the pool reference, values don't matter since the event is never queued.
855         delete ev->event_pool();
856 #endif
857 }
858
859 void
860 ARDOUR_UI::pop_back_splash (Gtk::Window& win)
861 {
862         if (Splash::exists()) {
863                 Splash::instance()->pop_back_for (win);
864         }
865 }
866
867 gint
868 ARDOUR_UI::configure_timeout ()
869 {
870         if (last_configure_time == 0) {
871                 /* no configure events yet */
872                 return true;
873         }
874
875         /* force a gap of 0.5 seconds since the last configure event
876          */
877
878         if (get_microseconds() - last_configure_time < 500000) {
879                 return true;
880         } else {
881                 have_configure_timeout = false;
882                 save_ardour_state ();
883                 return false;
884         }
885 }
886
887 gboolean
888 ARDOUR_UI::configure_handler (GdkEventConfigure* /*conf*/)
889 {
890         if (have_configure_timeout) {
891                 last_configure_time = get_microseconds();
892         } else {
893                 Glib::signal_timeout().connect (sigc::mem_fun(*this, &ARDOUR_UI::configure_timeout), 100);
894                 have_configure_timeout = true;
895         }
896
897         return FALSE;
898 }
899
900 void
901 ARDOUR_UI::set_transport_controllable_state (const XMLNode& node)
902 {
903         std::string str;
904
905         if (node.get_property ("roll", str)){
906                 roll_controllable->set_id (str);
907         }
908         if (node.get_property ("stop", str)) {
909                 stop_controllable->set_id (str);
910         }
911         if (node.get_property ("goto-start", str)) {
912                 goto_start_controllable->set_id (str);
913         }
914         if (node.get_property ("goto-end", str)) {
915                 goto_end_controllable->set_id (str);
916         }
917         if (node.get_property ("auto-loop", str)) {
918                 auto_loop_controllable->set_id (str);
919         }
920         if (node.get_property ("play-selection", str)) {
921                 play_selection_controllable->set_id (str);
922         }
923         if (node.get_property ("rec", str)) {
924                 rec_controllable->set_id (str);
925         }
926         if (node.get_property ("shuttle", str)) {
927                 shuttle_box.controllable()->set_id (str);
928         }
929 }
930
931 XMLNode&
932 ARDOUR_UI::get_transport_controllable_state ()
933 {
934         XMLNode* node = new XMLNode(X_("TransportControllables"));
935
936         node->set_property (X_("roll"), roll_controllable->id());
937         node->set_property (X_("stop"), stop_controllable->id());
938         node->set_property (X_("goto-start"), goto_start_controllable->id());
939         node->set_property (X_("goto-end"), goto_end_controllable->id());
940         node->set_property (X_("auto-loop"), auto_loop_controllable->id());
941         node->set_property (X_("play-selection"), play_selection_controllable->id());
942         node->set_property (X_("rec"), rec_controllable->id());
943         node->set_property (X_("shuttle"), shuttle_box.controllable()->id());
944
945         return *node;
946 }
947
948 void
949 ARDOUR_UI::session_dirty_changed ()
950 {
951         update_autosave ();
952         update_title ();
953 }
954
955 void
956 ARDOUR_UI::update_autosave ()
957 {
958         if (_session && _session->dirty()) {
959                 if (_autosave_connection.connected()) {
960                         _autosave_connection.disconnect();
961                 }
962
963                 _autosave_connection = Glib::signal_timeout().connect (sigc::mem_fun (*this, &ARDOUR_UI::autosave_session),
964                                 Config->get_periodic_safety_backup_interval() * 1000);
965
966         } else {
967                 if (_autosave_connection.connected()) {
968                         _autosave_connection.disconnect();
969                 }
970         }
971 }
972
973 void
974 ARDOUR_UI::queue_finish ()
975 {
976         Glib::signal_idle().connect (mem_fun (*this, &ARDOUR_UI::idle_finish));
977 }
978
979 bool
980 ARDOUR_UI::idle_finish ()
981 {
982         finish ();
983         return false; /* do not call again */
984 }
985
986 void
987 ARDOUR_UI::finish()
988 {
989         if (_session) {
990                 ARDOUR_UI::instance()->video_timeline->sync_session_state();
991
992                 if (_session->dirty()) {
993                         vector<string> actions;
994                         actions.push_back (_("Don't quit"));
995                         actions.push_back (_("Just quit"));
996                         actions.push_back (_("Save and quit"));
997                         switch (ask_about_saving_session(actions)) {
998                         case -1:
999                                 return;
1000                                 break;
1001                         case 1:
1002                                 /* use the default name */
1003                                 if (save_state_canfail ("")) {
1004                                         /* failed - don't quit */
1005                                         MessageDialog msg (_main_window,
1006                                                            string_compose (_("\
1007 %1 was unable to save your session.\n\n\
1008 If you still wish to quit, please use the\n\n\
1009 \"Just quit\" option."), PROGRAM_NAME));
1010                                         pop_back_splash(msg);
1011                                         msg.run ();
1012                                         return;
1013                                 }
1014                                 break;
1015                         case 0:
1016                                 break;
1017                         }
1018                 }
1019
1020                 second_connection.disconnect ();
1021                 point_one_second_connection.disconnect ();
1022                 point_zero_something_second_connection.disconnect();
1023                 fps_connection.disconnect();
1024         }
1025
1026         delete ARDOUR_UI::instance()->video_timeline;
1027         ARDOUR_UI::instance()->video_timeline = NULL;
1028         stop_video_server();
1029
1030         /* Save state before deleting the session, as that causes some
1031            windows to be destroyed before their visible state can be
1032            saved.
1033         */
1034         save_ardour_state ();
1035
1036         if (key_editor.get (false)) {
1037                 key_editor->disconnect ();
1038         }
1039
1040         close_all_dialogs ();
1041
1042         if (_session) {
1043                 _session->set_clean ();
1044                 delete _session;
1045                 _session = 0;
1046         }
1047
1048         halt_connection.disconnect ();
1049         AudioEngine::instance()->stop ();
1050 #ifdef WINDOWS_VST_SUPPORT
1051         fst_stop_threading();
1052 #endif
1053         quit ();
1054 }
1055
1056 void
1057 ARDOUR_UI::every_second ()
1058 {
1059         update_cpu_load ();
1060         update_disk_space ();
1061         update_timecode_format ();
1062         update_peak_thread_work ();
1063
1064         if (nsm && nsm->is_active ()) {
1065                 nsm->check ();
1066
1067                 if (!_was_dirty && _session->dirty ()) {
1068                         nsm->is_dirty ();
1069                         _was_dirty = true;
1070                 }
1071                 else if (_was_dirty && !_session->dirty ()){
1072                         nsm->is_clean ();
1073                         _was_dirty = false;
1074                 }
1075         }
1076 }
1077
1078 void
1079 ARDOUR_UI::every_point_one_seconds ()
1080 {
1081         if (editor) editor->build_region_boundary_cache();
1082 }
1083
1084 void
1085 ARDOUR_UI::every_point_zero_something_seconds ()
1086 {
1087         // august 2007: actual update frequency: 25Hz (40ms), not 100Hz
1088
1089         if (editor_meter && UIConfiguration::instance().get_show_editor_meter() && editor_meter_peak_display.is_mapped ()) {
1090                 float mpeak = editor_meter->update_meters();
1091                 if (mpeak > editor_meter_max_peak) {
1092                         if (mpeak >= UIConfiguration::instance().get_meter_peak()) {
1093                                 editor_meter_peak_display.set_active_state ( Gtkmm2ext::ExplicitActive );
1094                         }
1095                 }
1096         }
1097 }
1098
1099 void
1100 ARDOUR_UI::set_fps_timeout_connection ()
1101 {
1102         unsigned int interval = 40;
1103         if (!_session) return;
1104         if (_session->timecode_frames_per_second() != 0) {
1105                 /* ideally we'll use a select() to sleep and not accumulate
1106                  * idle time to provide a regular periodic signal.
1107                  * See linux_vst_gui_support.cc 'elapsed_time_ms'.
1108                  * However, that'll require a dedicated thread and cross-thread
1109                  * signals to the GUI Thread..
1110                  */
1111                 interval = floor(500. /* update twice per FPS, since Glib::signal_timeout is very irregular */
1112                                 * _session->sample_rate() / _session->nominal_sample_rate()
1113                                 / _session->timecode_frames_per_second()
1114                                 );
1115 #ifdef PLATFORM_WINDOWS
1116                 // the smallest windows scheduler time-slice is ~15ms.
1117                 // periodic GUI timeouts shorter than that will cause
1118                 // WaitForSingleObject to spinlock (100% of one CPU Core)
1119                 // and gtk never enters idle mode.
1120                 // also changing timeBeginPeriod(1) does not affect that in
1121                 // any beneficial way, so we just limit the max rate for now.
1122                 interval = std::max(30u, interval); // at most ~33Hz.
1123 #else
1124                 interval = std::max(8u, interval); // at most 120Hz.
1125 #endif
1126         }
1127         fps_connection.disconnect();
1128         Timers::set_fps_interval (interval);
1129 }
1130
1131 void
1132 ARDOUR_UI::update_sample_rate (samplecnt_t)
1133 {
1134         char buf[64];
1135
1136         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::update_sample_rate, ignored)
1137
1138         if (!AudioEngine::instance()->running()) {
1139
1140                 snprintf (buf, sizeof (buf), "%s", _("Audio: <span foreground=\"red\">none</span>"));
1141
1142         } else {
1143
1144                 samplecnt_t rate = AudioEngine::instance()->sample_rate();
1145
1146                 if (rate == 0) {
1147                         /* no sample rate available */
1148                         snprintf (buf, sizeof (buf), "%s", _("Audio: <span foreground=\"red\">none</span>"));
1149                 } else {
1150
1151                         if (fmod (rate, 1000.0) != 0.0) {
1152                                 snprintf (buf, sizeof (buf), _("Audio: <span foreground=\"green\">%.1f kHz / %4.1f ms</span>"),
1153                                           (float) rate / 1000.0f,
1154                                           (AudioEngine::instance()->usecs_per_cycle() / 1000.0f));
1155                         } else {
1156                                 snprintf (buf, sizeof (buf), _("Audio: <span foreground=\"green\">%" PRId64 " kHz / %4.1f ms</span>"),
1157                                           rate/1000,
1158                                           (AudioEngine::instance()->usecs_per_cycle() / 1000.0f));
1159                         }
1160                 }
1161         }
1162         sample_rate_label.set_markup (buf);
1163 }
1164
1165 void
1166 ARDOUR_UI::update_format ()
1167 {
1168         if (!_session) {
1169                 format_label.set_text ("");
1170                 return;
1171         }
1172
1173         stringstream s;
1174         s << _("File:") << X_(" <span foreground=\"green\">");
1175
1176         switch (_session->config.get_native_file_header_format ()) {
1177         case BWF:
1178                 s << _("BWF");
1179                 break;
1180         case WAVE:
1181                 s << _("WAV");
1182                 break;
1183         case WAVE64:
1184                 s << _("WAV64");
1185                 break;
1186         case CAF:
1187                 s << _("CAF");
1188                 break;
1189         case AIFF:
1190                 s << _("AIFF");
1191                 break;
1192         case iXML:
1193                 s << _("iXML");
1194                 break;
1195         case RF64:
1196                 s << _("RF64");
1197                 break;
1198         case RF64_WAV:
1199                 s << _("RF64/WAV");
1200                 break;
1201         case MBWF:
1202                 s << _("MBWF");
1203                 break;
1204         case FLAC:
1205                 s << _("FLAC");
1206                 break;
1207         }
1208
1209         s << " ";
1210
1211         switch (_session->config.get_native_file_data_format ()) {
1212         case FormatFloat:
1213                 s << _("32-float");
1214                 break;
1215         case FormatInt24:
1216                 s << _("24-int");
1217                 break;
1218         case FormatInt16:
1219                 s << _("16-int");
1220                 break;
1221         }
1222
1223         s << X_("</span>");
1224
1225         format_label.set_markup (s.str ());
1226 }
1227
1228 void
1229 ARDOUR_UI::update_cpu_load ()
1230 {
1231         const unsigned int x = _session ? _session->get_xrun_count () : 0;
1232         double const c = AudioEngine::instance()->get_dsp_load ();
1233
1234         const char* const bg = c > 90 ? " background=\"red\"" : "";
1235
1236         char buf[64];
1237         if (x > 9999) {
1238                 snprintf (buf, sizeof (buf), "DSP: <span%s>%.0f%%</span> (>10k)", bg, c);
1239         } else if (x > 0) {
1240                 snprintf (buf, sizeof (buf), "DSP: <span%s>%.0f%%</span> (%d)", bg, c, x);
1241         } else {
1242                 snprintf (buf, sizeof (buf), "DSP: <span%s>%.0f%%</span>", bg, c);
1243         }
1244
1245         dsp_load_label.set_markup (buf);
1246
1247         if (x > 9999) {
1248                 snprintf (buf, sizeof (buf), _("DSP: %.1f%% X: >10k\n%s"), c, _("Shift+Click to clear xruns."));
1249         } else if (x > 0) {
1250                 snprintf (buf, sizeof (buf), _("DSP: %.1f%% X: %u\n%s"), c, x, _("Shift+Click to clear xruns."));
1251         } else {
1252                 snprintf (buf, sizeof (buf), _("DSP: %.1f%%"), c);
1253         }
1254
1255         ArdourWidgets::set_tooltip (dsp_load_label, buf);
1256 }
1257
1258 void
1259 ARDOUR_UI::update_peak_thread_work ()
1260 {
1261         char buf[64];
1262         const int c = SourceFactory::peak_work_queue_length ();
1263         if (c > 0) {
1264                 snprintf (buf, sizeof (buf), _("PkBld: <span foreground=\"%s\">%d</span>"), c >= 2 ? X_("red") : X_("green"), c);
1265                 peak_thread_work_label.set_markup (buf);
1266         } else {
1267                 peak_thread_work_label.set_markup (X_(""));
1268         }
1269 }
1270
1271 void
1272 ARDOUR_UI::count_recenabled_streams (Route& route)
1273 {
1274         Track* track = dynamic_cast<Track*>(&route);
1275         if (track && track->rec_enable_control()->get_value()) {
1276                 rec_enabled_streams += track->n_inputs().n_total();
1277         }
1278 }
1279
1280 void
1281 ARDOUR_UI::format_disk_space_label (float remain_sec)
1282 {
1283         if (remain_sec < 0) {
1284                 disk_space_label.set_text (_("N/A"));
1285                 ArdourWidgets::set_tooltip (disk_space_label, _("Unknown"));
1286                 return;
1287         }
1288
1289         char buf[64];
1290
1291         int sec = floor (remain_sec);
1292         int hrs  = sec / 3600;
1293         int mins = (sec / 60) % 60;
1294         int secs = sec % 60;
1295         snprintf (buf, sizeof(buf), _("%02dh:%02dm:%02ds"), hrs, mins, secs);
1296         ArdourWidgets::set_tooltip (disk_space_label, buf);
1297
1298         if (remain_sec > 86400) {
1299                 disk_space_label.set_text (_("Rec: >24h"));
1300                 return;
1301         } else if (remain_sec > 32400 /* 9 hours */) {
1302                 snprintf (buf, sizeof (buf), "Rec: %.0fh", remain_sec / 3600.f);
1303         } else if (remain_sec > 5940 /* 99 mins */) {
1304                 snprintf (buf, sizeof (buf), "Rec: %.1fh", remain_sec / 3600.f);
1305         } else {
1306                 snprintf (buf, sizeof (buf), "Rec: %.0fm", remain_sec / 60.f);
1307         }
1308         disk_space_label.set_text (buf);
1309
1310 }
1311
1312 void
1313 ARDOUR_UI::update_disk_space()
1314 {
1315         if (_session == 0) {
1316                 format_disk_space_label (-1);
1317                 return;
1318         }
1319
1320         boost::optional<samplecnt_t> opt_samples = _session->available_capture_duration();
1321         samplecnt_t fr = _session->sample_rate();
1322
1323         if (fr == 0) {
1324                 /* skip update - no SR available */
1325                 format_disk_space_label (-1);
1326                 return;
1327         }
1328
1329         if (!opt_samples) {
1330                 /* Available space is unknown */
1331                 format_disk_space_label (-1);
1332         } else if (opt_samples.get_value_or (0) == max_samplecnt) {
1333                 format_disk_space_label (max_samplecnt);
1334         } else {
1335                 rec_enabled_streams = 0;
1336                 _session->foreach_route (this, &ARDOUR_UI::count_recenabled_streams, false);
1337
1338                 samplecnt_t samples = opt_samples.get_value_or (0);
1339
1340                 if (rec_enabled_streams) {
1341                         samples /= rec_enabled_streams;
1342                 }
1343
1344                 format_disk_space_label (samples / (float)fr);
1345         }
1346
1347 }
1348
1349 void
1350 ARDOUR_UI::update_timecode_format ()
1351 {
1352         char buf[64];
1353
1354         if (_session) {
1355                 bool matching;
1356                 boost::shared_ptr<TimecodeTransportMaster> tcmaster;
1357                 boost::shared_ptr<TransportMaster> tm = TransportMasterManager::instance().current();
1358
1359                 if ((tm->type() == LTC || tm->type() == MTC) && (tcmaster = boost::dynamic_pointer_cast<TimecodeTransportMaster>(tm)) != 0) {
1360                         matching = (tcmaster->apparent_timecode_format() == _session->config.get_timecode_format());
1361                 } else {
1362                         matching = true;
1363                 }
1364
1365                 snprintf (buf, sizeof (buf), S_("Timecode|TC: <span foreground=\"%s\">%s</span>"),
1366                           matching ? X_("green") : X_("red"),
1367                           Timecode::timecode_format_name (_session->config.get_timecode_format()).c_str());
1368         } else {
1369                 snprintf (buf, sizeof (buf), "TC: n/a");
1370         }
1371
1372         timecode_format_label.set_markup (buf);
1373 }
1374
1375 gint
1376 ARDOUR_UI::update_wall_clock ()
1377 {
1378         time_t now;
1379         struct tm *tm_now;
1380         static int last_min = -1;
1381
1382         time (&now);
1383         tm_now = localtime (&now);
1384         if (last_min != tm_now->tm_min) {
1385                 char buf[16];
1386                 sprintf (buf, "%02d:%02d", tm_now->tm_hour, tm_now->tm_min);
1387                 wall_clock_label.set_text (buf);
1388                 last_min = tm_now->tm_min;
1389         }
1390
1391         return TRUE;
1392 }
1393
1394 void
1395 ARDOUR_UI::session_add_mixed_track (
1396                 const ChanCount& input,
1397                 const ChanCount& output,
1398                 RouteGroup* route_group,
1399                 uint32_t how_many,
1400                 const string& name_template,
1401                 bool strict_io,
1402                 PluginInfoPtr instrument,
1403                 Plugin::PresetRecord* pset,
1404                 ARDOUR::PresentationInfo::order_t order)
1405 {
1406         assert (_session);
1407
1408         if (Profile->get_mixbus ()) {
1409                 strict_io = true;
1410         }
1411
1412         try {
1413                 list<boost::shared_ptr<MidiTrack> > tracks;
1414                 tracks = _session->new_midi_track (input, output, strict_io, instrument, pset, route_group, how_many, name_template, order, ARDOUR::Normal);
1415
1416                 if (tracks.size() != how_many) {
1417                         error << string_compose(P_("could not create %1 new mixed track", "could not create %1 new mixed tracks", how_many), how_many) << endmsg;
1418                 }
1419         }
1420
1421         catch (...) {
1422                 display_insufficient_ports_message ();
1423                 return;
1424         }
1425 }
1426
1427 void
1428 ARDOUR_UI::session_add_midi_bus (
1429                 RouteGroup* route_group,
1430                 uint32_t how_many,
1431                 const string& name_template,
1432                 bool strict_io,
1433                 PluginInfoPtr instrument,
1434                 Plugin::PresetRecord* pset,
1435                 ARDOUR::PresentationInfo::order_t order)
1436 {
1437         if (_session == 0) {
1438                 warning << _("You cannot add a track without a session already loaded.") << endmsg;
1439                 return;
1440         }
1441
1442         if (Profile->get_mixbus ()) {
1443                 strict_io = true;
1444         }
1445
1446         try {
1447                 RouteList routes;
1448                 routes = _session->new_midi_route (route_group, how_many, name_template, strict_io, instrument, pset, PresentationInfo::MidiBus, order);
1449                 if (routes.size() != how_many) {
1450                         error << string_compose(P_("could not create %1 new Midi Bus", "could not create %1 new Midi Busses", how_many), how_many) << endmsg;
1451                 }
1452
1453         }
1454         catch (...) {
1455                 display_insufficient_ports_message ();
1456                 return;
1457         }
1458 }
1459
1460 void
1461 ARDOUR_UI::session_add_midi_route (
1462                 bool disk,
1463                 RouteGroup* route_group,
1464                 uint32_t how_many,
1465                 const string& name_template,
1466                 bool strict_io,
1467                 PluginInfoPtr instrument,
1468                 Plugin::PresetRecord* pset,
1469                 ARDOUR::PresentationInfo::order_t order)
1470 {
1471         ChanCount one_midi_channel;
1472         one_midi_channel.set (DataType::MIDI, 1);
1473
1474         if (disk) {
1475                 session_add_mixed_track (one_midi_channel, one_midi_channel, route_group, how_many, name_template, strict_io, instrument, pset, order);
1476         } else {
1477                 session_add_midi_bus (route_group, how_many, name_template, strict_io, instrument, pset, order);
1478         }
1479 }
1480
1481 void
1482 ARDOUR_UI::session_add_audio_route (
1483         bool track,
1484         int32_t input_channels,
1485         int32_t output_channels,
1486         ARDOUR::TrackMode mode,
1487         RouteGroup* route_group,
1488         uint32_t how_many,
1489         string const & name_template,
1490         bool strict_io,
1491         ARDOUR::PresentationInfo::order_t order)
1492 {
1493         list<boost::shared_ptr<AudioTrack> > tracks;
1494         RouteList routes;
1495
1496         assert (_session);
1497
1498         try {
1499                 if (track) {
1500                         tracks = _session->new_audio_track (input_channels, output_channels, route_group, how_many, name_template, order, mode);
1501
1502                         if (tracks.size() != how_many) {
1503                                 error << string_compose (P_("could not create %1 new audio track", "could not create %1 new audio tracks", how_many), how_many)
1504                                       << endmsg;
1505                         }
1506
1507                 } else {
1508
1509                         routes = _session->new_audio_route (input_channels, output_channels, route_group, how_many, name_template, PresentationInfo::AudioBus, order);
1510
1511                         if (routes.size() != how_many) {
1512                                 error << string_compose (P_("could not create %1 new audio bus", "could not create %1 new audio busses", how_many), how_many)
1513                                       << endmsg;
1514                         }
1515                 }
1516         }
1517
1518         catch (...) {
1519                 display_insufficient_ports_message ();
1520                 return;
1521         }
1522
1523         if (strict_io) {
1524                 for (list<boost::shared_ptr<AudioTrack> >::iterator i = tracks.begin(); i != tracks.end(); ++i) {
1525                         (*i)->set_strict_io (true);
1526                 }
1527                 for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
1528                         (*i)->set_strict_io (true);
1529                 }
1530         }
1531 }
1532
1533 void
1534 ARDOUR_UI::session_add_foldback_bus (int32_t channels, uint32_t how_many, string const & name_template)
1535 {
1536         RouteList routes;
1537
1538         assert (_session);
1539
1540         try {
1541                 routes = _session->new_audio_route (channels, channels, 0, how_many, name_template, PresentationInfo::FoldbackBus, -1);
1542
1543                 if (routes.size() != how_many) {
1544                         error << string_compose (P_("could not create %1 new foldback bus", "could not create %1 new foldback busses", how_many), how_many)
1545                               << endmsg;
1546                 }
1547         }
1548
1549         catch (...) {
1550                 display_insufficient_ports_message ();
1551                 return;
1552         }
1553 }
1554
1555 void
1556 ARDOUR_UI::display_insufficient_ports_message ()
1557 {
1558         MessageDialog msg (_main_window,
1559                         string_compose (_("There are insufficient ports available\n\
1560 to create a new track or bus.\n\
1561 You should save %1, exit and\n\
1562 restart with more ports."), PROGRAM_NAME));
1563         pop_back_splash (msg);
1564         msg.run ();
1565 }
1566
1567 void
1568 ARDOUR_UI::transport_goto_start ()
1569 {
1570         if (_session) {
1571                 _session->goto_start ();
1572
1573                 /* force displayed area in editor to start no matter
1574                    what "follow playhead" setting is.
1575                 */
1576
1577                 if (editor) {
1578                         editor->center_screen (_session->current_start_sample ());
1579                 }
1580         }
1581 }
1582
1583 void
1584 ARDOUR_UI::transport_goto_zero ()
1585 {
1586         if (_session) {
1587                 _session->request_locate (0);
1588
1589                 /* force displayed area in editor to start no matter
1590                    what "follow playhead" setting is.
1591                 */
1592
1593                 if (editor) {
1594                         editor->reset_x_origin (0);
1595                 }
1596         }
1597 }
1598
1599 void
1600 ARDOUR_UI::transport_goto_wallclock ()
1601 {
1602         if (_session && editor) {
1603
1604                 time_t now;
1605                 struct tm tmnow;
1606                 samplepos_t samples;
1607
1608                 time (&now);
1609                 localtime_r (&now, &tmnow);
1610
1611                 samplecnt_t sample_rate = _session->sample_rate();
1612
1613                 if (sample_rate == 0) {
1614                         /* no frame rate available */
1615                         return;
1616                 }
1617
1618                 samples = tmnow.tm_hour * (60 * 60 * sample_rate);
1619                 samples += tmnow.tm_min * (60 * sample_rate);
1620                 samples += tmnow.tm_sec * sample_rate;
1621
1622                 _session->request_locate (samples, _session->transport_rolling ());
1623
1624                 /* force displayed area in editor to start no matter
1625                    what "follow playhead" setting is.
1626                 */
1627
1628                 if (editor) {
1629                         editor->center_screen (samples);
1630                 }
1631         }
1632 }
1633
1634 void
1635 ARDOUR_UI::transport_goto_end ()
1636 {
1637         if (_session) {
1638                 samplepos_t const sample = _session->current_end_sample();
1639                 _session->request_locate (sample);
1640
1641                 /* force displayed area in editor to start no matter
1642                    what "follow playhead" setting is.
1643                 */
1644
1645                 if (editor) {
1646                         editor->center_screen (sample);
1647                 }
1648         }
1649 }
1650
1651 void
1652 ARDOUR_UI::transport_stop ()
1653 {
1654         if (!_session) {
1655                 return;
1656         }
1657
1658         if (_session->is_auditioning()) {
1659                 _session->cancel_audition ();
1660                 return;
1661         }
1662
1663         _session->request_stop (false, true);
1664 }
1665
1666 /** Check if any tracks are record enabled. If none are, record enable all of them.
1667  * @return true if track record-enabled status was changed, false otherwise.
1668  */
1669 bool
1670 ARDOUR_UI::trx_record_enable_all_tracks ()
1671 {
1672         if (!_session) {
1673                 return false;
1674         }
1675
1676         boost::shared_ptr<RouteList> rl = _session->get_tracks ();
1677         bool none_record_enabled = true;
1678
1679         for (RouteList::iterator r = rl->begin(); r != rl->end(); ++r) {
1680                 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*r);
1681                 assert (t);
1682
1683                 if (t->rec_enable_control()->get_value()) {
1684                         none_record_enabled = false;
1685                         break;
1686                 }
1687         }
1688
1689         if (none_record_enabled) {
1690                 _session->set_controls (route_list_to_control_list (rl, &Stripable::rec_enable_control), 1.0, Controllable::NoGroup);
1691         }
1692
1693         return none_record_enabled;
1694 }
1695
1696 void
1697 ARDOUR_UI::transport_record (bool roll)
1698 {
1699         if (_session) {
1700                 switch (_session->record_status()) {
1701                 case Session::Disabled:
1702                         if (_session->ntracks() == 0) {
1703                                 MessageDialog msg (_main_window, _("Please create one or more tracks before trying to record.\nYou can do this with the \"Add Track or Bus\" option in the Session menu."));
1704                                 msg.run ();
1705                                 return;
1706                         }
1707                         _session->maybe_enable_record ();
1708                         if (roll) {
1709                                 transport_roll ();
1710                         }
1711                         break;
1712                 case Session::Recording:
1713                         if (roll) {
1714                                 _session->request_stop();
1715                         } else {
1716                                 _session->disable_record (false, true);
1717                         }
1718                         break;
1719
1720                 case Session::Enabled:
1721                         _session->disable_record (false, true);
1722                 }
1723         }
1724 }
1725
1726 void
1727 ARDOUR_UI::transport_roll ()
1728 {
1729         if (!_session) {
1730                 return;
1731         }
1732
1733         if (_session->is_auditioning()) {
1734                 return;
1735         }
1736
1737         if (_session->config.get_external_sync()) {
1738                 switch (TransportMasterManager::instance().current()->type()) {
1739                 case Engine:
1740                         break;
1741                 default:
1742                         /* transport controlled by the master */
1743                         return;
1744                 }
1745         }
1746
1747         bool rolling = _session->transport_rolling();
1748
1749         if (_session->get_play_loop()) {
1750
1751                 /* If loop playback is not a mode, then we should cancel
1752                    it when this action is requested. If it is a mode
1753                    we just leave it in place.
1754                 */
1755
1756                 if (!Config->get_loop_is_mode()) {
1757                         /* stop loop playback but keep transport state */
1758                         _session->request_play_loop (false, false);
1759                 }
1760
1761         } else if (_session->get_play_range () ) {
1762                 /* stop playing a range if we currently are */
1763                 _session->request_play_range (0, true);
1764         }
1765
1766         if (!rolling) {
1767                 _session->request_transport_speed (1.0f);
1768         }
1769 }
1770
1771 bool
1772 ARDOUR_UI::get_smart_mode() const
1773 {
1774         return ( editor->get_smart_mode() );
1775 }
1776
1777
1778 void
1779 ARDOUR_UI::toggle_roll (bool with_abort, bool roll_out_of_bounded_mode)
1780 {
1781         if (!_session) {
1782                 return;
1783         }
1784
1785         if (_session->is_auditioning()) {
1786                 _session->cancel_audition ();
1787                 return;
1788         }
1789
1790         if (_session->config.get_external_sync()) {
1791                 switch (TransportMasterManager::instance().current()->type()) {
1792                 case Engine:
1793                         break;
1794                 default:
1795                         /* transport controlled by the master */
1796                         return;
1797                 }
1798         }
1799
1800         bool rolling = _session->transport_rolling();
1801
1802         if (rolling) {
1803
1804                 if (roll_out_of_bounded_mode) {
1805                         /* drop out of loop/range playback but leave transport rolling */
1806
1807                         if (_session->get_play_loop()) {
1808
1809                                 if (_session->actively_recording()) {
1810                                         /* actually stop transport because
1811                                            otherwise the captured data will make
1812                                            no sense.
1813                                         */
1814                                         _session->request_play_loop (false, true);
1815
1816                                 } else {
1817                                         _session->request_play_loop (false, false);
1818                                 }
1819
1820                         } else if (_session->get_play_range ()) {
1821
1822                                 _session->request_cancel_play_range ();
1823                         }
1824
1825                 } else {
1826                         _session->request_stop (with_abort, true);
1827                 }
1828
1829         } else { /* not rolling */
1830
1831                 if (with_abort) { /* with_abort == true means the command was intended to stop transport, not start. */
1832                         return;
1833                 }
1834
1835                 if (_session->get_play_loop() && Config->get_loop_is_mode()) {
1836                         _session->request_locate (_session->locations()->auto_loop_location()->start(), true);
1837                 } else {
1838                         if (UIConfiguration::instance().get_follow_edits()) {
1839                                 list<AudioRange>& range = editor->get_selection().time;
1840                                 if (range.front().start == _session->transport_sample()) { // if playhead is exactly at the start of a range, we assume it was placed there by follow_edits
1841                                         _session->request_play_range (&range, true);
1842                                         _session->set_requested_return_sample (range.front().start);  //force an auto-return here
1843                                 }
1844                         }
1845                         _session->request_transport_speed (1.0f);
1846                 }
1847         }
1848 }
1849
1850 void
1851 ARDOUR_UI::toggle_session_auto_loop ()
1852 {
1853         if (!_session) {
1854                 return;
1855         }
1856
1857         Location * looploc = _session->locations()->auto_loop_location();
1858
1859         if (!looploc) {
1860                 return;
1861         }
1862
1863         if (_session->get_play_loop()) {
1864
1865                 /* looping enabled, our job is to disable it */
1866
1867                 _session->request_play_loop (false);
1868
1869         } else {
1870
1871                 /* looping not enabled, our job is to enable it.
1872
1873                    loop-is-NOT-mode: this action always starts the transport rolling.
1874                    loop-IS-mode:     this action simply sets the loop play mechanism, but
1875                                         does not start transport.
1876                 */
1877                 if (Config->get_loop_is_mode()) {
1878                         _session->request_play_loop (true, false);
1879                 } else {
1880                         _session->request_play_loop (true, true);
1881                 }
1882         }
1883
1884         //show the loop markers
1885         looploc->set_hidden (false, this);
1886 }
1887
1888 void
1889 ARDOUR_UI::transport_play_selection ()
1890 {
1891         if (!_session) {
1892                 return;
1893         }
1894
1895         editor->play_selection ();
1896 }
1897
1898 void
1899 ARDOUR_UI::transport_play_preroll ()
1900 {
1901         if (!_session) {
1902                 return;
1903         }
1904         editor->play_with_preroll ();
1905 }
1906
1907 void
1908 ARDOUR_UI::transport_rec_preroll ()
1909 {
1910         if (!_session) {
1911                 return;
1912         }
1913         editor->rec_with_preroll ();
1914 }
1915
1916 void
1917 ARDOUR_UI::transport_rec_count_in ()
1918 {
1919         if (!_session) {
1920                 return;
1921         }
1922         editor->rec_with_count_in ();
1923 }
1924
1925 void
1926 ARDOUR_UI::transport_rewind (int option)
1927 {
1928         float current_transport_speed;
1929
1930         if (_session) {
1931                 current_transport_speed = _session->transport_speed();
1932
1933                 if (current_transport_speed >= 0.0f) {
1934                         switch (option) {
1935                         case 0:
1936                                 _session->request_transport_speed (-1.0f);
1937                                 break;
1938                         case 1:
1939                                 _session->request_transport_speed (-4.0f);
1940                                 break;
1941                         case -1:
1942                                 _session->request_transport_speed (-0.5f);
1943                                 break;
1944                         }
1945                 } else {
1946                         /* speed up */
1947                         _session->request_transport_speed (current_transport_speed * 1.5f);
1948                 }
1949         }
1950 }
1951
1952 void
1953 ARDOUR_UI::transport_forward (int option)
1954 {
1955         if (!_session) {
1956                 return;
1957         }
1958
1959         float current_transport_speed = _session->transport_speed();
1960
1961         if (current_transport_speed <= 0.0f) {
1962                 switch (option) {
1963                 case 0:
1964                         _session->request_transport_speed (1.0f);
1965                         break;
1966                 case 1:
1967                         _session->request_transport_speed (4.0f);
1968                         break;
1969                 case -1:
1970                         _session->request_transport_speed (0.5f);
1971                         break;
1972                 }
1973         } else {
1974                 /* speed up */
1975                 _session->request_transport_speed (current_transport_speed * 1.5f);
1976         }
1977 }
1978
1979 void
1980 ARDOUR_UI::toggle_record_enable (uint16_t rid)
1981 {
1982         if (!_session) {
1983                 return;
1984         }
1985
1986         boost::shared_ptr<Route> r;
1987
1988         if ((r = _session->get_remote_nth_route (rid)) != 0) {
1989
1990                 boost::shared_ptr<Track> t;
1991
1992                 if ((t = boost::dynamic_pointer_cast<Track>(r)) != 0) {
1993                         t->rec_enable_control()->set_value (!t->rec_enable_control()->get_value(), Controllable::UseGroup);
1994                 }
1995         }
1996 }
1997
1998 void
1999 ARDOUR_UI::map_transport_state ()
2000 {
2001         if (!_session) {
2002                 layered_button.set_sensitive (false);
2003                 return;
2004         }
2005
2006         shuttle_box.map_transport_state ();
2007
2008         float sp = _session->transport_speed();
2009
2010         if (sp != 0.0f) {
2011                 layered_button.set_sensitive (!_session->actively_recording ());
2012         } else {
2013                 layered_button.set_sensitive (true);
2014                 update_disk_space ();
2015         }
2016         if (UIConfiguration::instance().get_screen_saver_mode () == InhibitWhileRecording) {
2017                 inhibit_screensaver (_session->actively_recording ());
2018         }
2019 }
2020
2021 void
2022 ARDOUR_UI::blink_handler (bool blink_on)
2023 {
2024         sync_blink (blink_on);
2025
2026         if (!UIConfiguration::instance().get_blink_alert_indicators()) {
2027                 blink_on = true;
2028         }
2029         error_blink (blink_on);
2030         solo_blink (blink_on);
2031         audition_blink (blink_on);
2032         feedback_blink (blink_on);
2033 }
2034
2035 void
2036 ARDOUR_UI::update_clocks ()
2037 {
2038         if (!_session) return;
2039
2040         if (editor && !editor->dragging_playhead()) {
2041                 Clock (_session->audible_sample()); /* EMIT_SIGNAL */
2042         }
2043 }
2044
2045 void
2046 ARDOUR_UI::start_clocking ()
2047 {
2048         if (UIConfiguration::instance().get_super_rapid_clock_update()) {
2049                 clock_signal_connection = Timers::fps_connect (sigc::mem_fun(*this, &ARDOUR_UI::update_clocks));
2050         } else {
2051                 clock_signal_connection = Timers::rapid_connect (sigc::mem_fun(*this, &ARDOUR_UI::update_clocks));
2052         }
2053 }
2054
2055 void
2056 ARDOUR_UI::stop_clocking ()
2057 {
2058         clock_signal_connection.disconnect ();
2059 }
2060
2061 void
2062 ARDOUR_UI::save_state (const string & name, bool switch_to_it)
2063 {
2064         if (!_session || _session->deletion_in_progress()) {
2065                 return;
2066         }
2067
2068         XMLNode* node = new XMLNode (X_("UI"));
2069
2070         WM::Manager::instance().add_state (*node);
2071
2072         node->add_child_nocopy (gui_object_state->get_state());
2073
2074         _session->add_extra_xml (*node);
2075
2076         if (export_video_dialog) {
2077                 _session->add_extra_xml (export_video_dialog->get_state());
2078         }
2079
2080         save_state_canfail (name, switch_to_it);
2081 }
2082
2083 int
2084 ARDOUR_UI::save_state_canfail (string name, bool switch_to_it)
2085 {
2086         if (_session) {
2087                 int ret;
2088
2089                 if ((ret = _session->save_state (name, false, switch_to_it)) != 0) {
2090                         return ret;
2091                 }
2092         }
2093
2094         save_ardour_state (); /* XXX cannot fail? yeah, right ... */
2095         return 0;
2096 }
2097
2098 void
2099 ARDOUR_UI::primary_clock_value_changed ()
2100 {
2101         if (_session) {
2102                 _session->request_locate (primary_clock->current_time ());
2103         }
2104 }
2105
2106 void
2107 ARDOUR_UI::big_clock_value_changed ()
2108 {
2109         if (_session) {
2110                 _session->request_locate (big_clock->current_time ());
2111         }
2112 }
2113
2114 void
2115 ARDOUR_UI::secondary_clock_value_changed ()
2116 {
2117         if (_session) {
2118                 _session->request_locate (secondary_clock->current_time ());
2119         }
2120 }
2121 void
2122 ARDOUR_UI::save_template_dialog_response (int response, SaveTemplateDialog* d)
2123 {
2124         if (response == RESPONSE_ACCEPT) {
2125                 const string name = d->get_template_name ();
2126                 const string desc = d->get_description ();
2127
2128                 int failed = _session->save_template (name, desc);
2129
2130                 if (failed == -2) { /* file already exists. */
2131                         bool overwrite = overwrite_file_dialog (*d,
2132                                                                 _("Confirm Template Overwrite"),
2133                                                                 _("A template already exists with that name. Do you want to overwrite it?"));
2134
2135                         if (overwrite) {
2136                                 _session->save_template (name, desc, true);
2137                         }
2138                         else {
2139                                 d->show ();
2140                                 return;
2141                         }
2142                 }
2143         }
2144         delete d;
2145 }
2146
2147 void
2148 ARDOUR_UI::save_template ()
2149 {
2150         if (!check_audioengine (_main_window)) {
2151                 return;
2152         }
2153
2154         const std::string desc = SessionMetadata::Metadata()->description ();
2155         SaveTemplateDialog* d = new SaveTemplateDialog (_session->name (), desc);
2156         d->signal_response().connect (sigc::bind (sigc::mem_fun (*this, &ARDOUR_UI::save_template_dialog_response), d));
2157         d->show ();
2158 }
2159
2160 void ARDOUR_UI::manage_templates ()
2161 {
2162         TemplateDialog td;
2163         td.run();
2164 }
2165
2166 void
2167 ARDOUR_UI::edit_metadata ()
2168 {
2169         SessionMetadataEditor dialog;
2170         dialog.set_session (_session);
2171         dialog.grab_focus ();
2172         dialog.run ();
2173 }
2174
2175 void
2176 ARDOUR_UI::import_metadata ()
2177 {
2178         SessionMetadataImporter dialog;
2179         dialog.set_session (_session);
2180         dialog.run ();
2181 }
2182
2183 static void _lua_print (std::string s) {
2184 #ifndef NDEBUG
2185         std::cout << "LuaInstance: " << s << "\n";
2186 #endif
2187         PBD::info << "LuaInstance: " << s << endmsg;
2188 }
2189
2190 std::map<std::string, std::string>
2191 ARDOUR_UI::route_setup_info (const std::string& script_path)
2192 {
2193         std::map<std::string, std::string> rv;
2194
2195         if (!Glib::file_test (script_path, Glib::FILE_TEST_EXISTS | Glib::FILE_TEST_IS_REGULAR)) {
2196                 return rv;
2197         }
2198
2199         LuaState lua;
2200         lua.Print.connect (&_lua_print);
2201         lua.sandbox (true);
2202
2203         lua_State* L = lua.getState();
2204         LuaInstance::register_classes (L);
2205         LuaBindings::set_session (L, _session);
2206         luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
2207         lua_setglobal (L, "Editor");
2208
2209         lua.do_command ("function ardour () end");
2210         lua.do_file (script_path);
2211
2212         try {
2213                 luabridge::LuaRef fn = luabridge::getGlobal (L, "route_setup");
2214                 if (!fn.isFunction ()) {
2215                         return rv;
2216                 }
2217                 luabridge::LuaRef rs = fn ();
2218                 if (!rs.isTable ()) {
2219                         return rv;
2220                 }
2221                 for (luabridge::Iterator i(rs); !i.isNil (); ++i) {
2222                         if (!i.key().isString()) {
2223                                 continue;
2224                         }
2225                         std::string key = i.key().tostring();
2226                         if (i.value().isString() || i.value().isNumber() || i.value().isBoolean()) {
2227                                 rv[key] = i.value().tostring();
2228                         }
2229                 }
2230         } catch (luabridge::LuaException const& e) {
2231                 cerr << "LuaException:" << e.what () << endl;
2232         } catch (...) { }
2233         return rv;
2234 }
2235
2236 void
2237 ARDOUR_UI::meta_route_setup (const std::string& script_path)
2238 {
2239         if (!Glib::file_test (script_path, Glib::FILE_TEST_EXISTS | Glib::FILE_TEST_IS_REGULAR)) {
2240                 return;
2241         }
2242         assert (add_route_dialog);
2243
2244         int count;
2245         if ((count = add_route_dialog->count()) <= 0) {
2246                 return;
2247         }
2248
2249         LuaState lua;
2250         lua.Print.connect (&_lua_print);
2251         lua.sandbox (true);
2252
2253         lua_State* L = lua.getState();
2254         LuaInstance::register_classes (L);
2255         LuaBindings::set_session (L, _session);
2256         luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
2257         lua_setglobal (L, "Editor");
2258
2259         lua.do_command ("function ardour () end");
2260         lua.do_file (script_path);
2261
2262         luabridge::LuaRef args (luabridge::newTable (L));
2263
2264         args["name"]       = add_route_dialog->name_template ();
2265         args["insert_at"]  = translate_order (add_route_dialog->insert_at());
2266         args["group"]      = add_route_dialog->route_group ();
2267         args["strict_io"]  = add_route_dialog->use_strict_io ();
2268         args["instrument"] = add_route_dialog->requested_instrument ();
2269         args["track_mode"] = add_route_dialog->mode ();
2270         args["channels"]   = add_route_dialog->channel_count ();
2271         args["how_many"]   = count;
2272
2273         try {
2274                 luabridge::LuaRef fn = luabridge::getGlobal (L, "factory");
2275                 if (fn.isFunction()) {
2276                         fn (args)();
2277                 }
2278         } catch (luabridge::LuaException const& e) {
2279                 cerr << "LuaException:" << e.what () << endl;
2280         } catch (...) {
2281                 display_insufficient_ports_message ();
2282         }
2283 }
2284
2285 void
2286 ARDOUR_UI::meta_session_setup (const std::string& script_path)
2287 {
2288         if (!Glib::file_test (script_path, Glib::FILE_TEST_EXISTS | Glib::FILE_TEST_IS_REGULAR)) {
2289                 return;
2290         }
2291
2292         LuaState lua;
2293         lua.Print.connect (&_lua_print);
2294         lua.sandbox (true);
2295
2296         lua_State* L = lua.getState();
2297         LuaInstance::register_classes (L);
2298         LuaBindings::set_session (L, _session);
2299         luabridge::push <PublicEditor *> (L, &PublicEditor::instance());
2300         lua_setglobal (L, "Editor");
2301
2302         lua.do_command ("function ardour () end");
2303         lua.do_file (script_path);
2304
2305         try {
2306                 luabridge::LuaRef fn = luabridge::getGlobal (L, "factory");
2307                 if (fn.isFunction()) {
2308                         fn ()();
2309                 }
2310         } catch (luabridge::LuaException const& e) {
2311                 cerr << "LuaException:" << e.what () << endl;
2312         } catch (...) {
2313                 display_insufficient_ports_message ();
2314         }
2315 }
2316
2317 void
2318 ARDOUR_UI::display_cleanup_results (ARDOUR::CleanupReport& rep, const gchar* list_title, const bool msg_delete)
2319 {
2320         size_t removed;
2321
2322         removed = rep.paths.size();
2323
2324         if (removed == 0) {
2325                 MessageDialog msgd (_main_window,
2326                                     _("No files were ready for clean-up"),
2327                                     true,
2328                                     Gtk::MESSAGE_INFO,
2329                                     Gtk::BUTTONS_OK);
2330                 msgd.set_title (_("Clean-up"));
2331                 msgd.set_secondary_text (_("If this seems surprising, \n\
2332 check for any existing snapshots.\n\
2333 These may still include regions that\n\
2334 require some unused files to continue to exist."));
2335
2336                 msgd.run ();
2337                 return;
2338         }
2339
2340         ArdourDialog results (_("Clean-up"), true, false);
2341
2342         struct CleanupResultsModelColumns : public Gtk::TreeModel::ColumnRecord {
2343                 CleanupResultsModelColumns() {
2344                         add (visible_name);
2345                         add (fullpath);
2346                 }
2347                 Gtk::TreeModelColumn<std::string> visible_name;
2348                 Gtk::TreeModelColumn<std::string> fullpath;
2349         };
2350
2351
2352         CleanupResultsModelColumns results_columns;
2353         Glib::RefPtr<Gtk::ListStore> results_model;
2354         Gtk::TreeView results_display;
2355
2356         results_model = ListStore::create (results_columns);
2357         results_display.set_model (results_model);
2358         results_display.append_column (list_title, results_columns.visible_name);
2359
2360         results_display.set_name ("CleanupResultsList");
2361         results_display.set_headers_visible (true);
2362         results_display.set_headers_clickable (false);
2363         results_display.set_reorderable (false);
2364
2365         Gtk::ScrolledWindow list_scroller;
2366         Gtk::Label txt;
2367         Gtk::VBox dvbox;
2368         Gtk::HBox dhbox;  // the hbox for the image and text
2369         Gtk::HBox ddhbox; // the hbox we eventually pack into the dialog's vbox
2370         Gtk::Image* dimage = manage (new Gtk::Image(Stock::DIALOG_INFO,  Gtk::ICON_SIZE_DIALOG));
2371
2372         dimage->set_alignment(ALIGN_LEFT, ALIGN_TOP);
2373
2374         const string dead_directory = _session->session_directory().dead_path();
2375
2376         /* subst:
2377            %1 - number of files removed
2378            %2 - location of "dead"
2379            %3 - size of files affected
2380            %4 - prefix for "bytes" to produce sensible results (e.g. mega, kilo, giga)
2381         */
2382
2383         const char* bprefix;
2384         double space_adjusted = 0;
2385
2386         if (rep.space < 1000) {
2387                 bprefix = X_("");
2388                 space_adjusted = rep.space;
2389         } else if (rep.space < 1000000) {
2390                 bprefix = _("kilo");
2391                 space_adjusted = floorf((float)rep.space / 1000.0);
2392         } else if (rep.space < 1000000 * 1000) {
2393                 bprefix = _("mega");
2394                 space_adjusted = floorf((float)rep.space / (1000.0 * 1000.0));
2395         } else {
2396                 bprefix = _("giga");
2397                 space_adjusted = floorf((float)rep.space / (1000.0 * 1000 * 1000.0));
2398         }
2399
2400         if (msg_delete) {
2401                 txt.set_markup (string_compose (P_("\
2402 The following file was deleted from %2,\n\
2403 releasing %3 %4bytes of disk space", "\
2404 The following %1 files were deleted from %2,\n\
2405 releasing %3 %4bytes of disk space", removed),
2406                                         removed, Gtkmm2ext::markup_escape_text (dead_directory), space_adjusted, bprefix, PROGRAM_NAME));
2407         } else {
2408                 txt.set_markup (string_compose (P_("\
2409 The following file was not in use and \n\
2410 has been moved to: %2\n\n\
2411 After a restart of %5\n\n\
2412 <span face=\"mono\">Session -> Clean-up -> Flush Wastebasket</span>\n\n\
2413 will release an additional %3 %4bytes of disk space.\n", "\
2414 The following %1 files were not in use and \n\
2415 have been moved to: %2\n\n\
2416 After a restart of %5\n\n\
2417 <span face=\"mono\">Session -> Clean-up -> Flush Wastebasket</span>\n\n\
2418 will release an additional %3 %4bytes of disk space.\n", removed),
2419                                         removed, Gtkmm2ext::markup_escape_text (dead_directory), space_adjusted, bprefix, PROGRAM_NAME));
2420         }
2421
2422         dhbox.pack_start (*dimage, true, false, 5);
2423         dhbox.pack_start (txt, true, false, 5);
2424
2425         for (vector<string>::iterator i = rep.paths.begin(); i != rep.paths.end(); ++i) {
2426                 TreeModel::Row row = *(results_model->append());
2427                 row[results_columns.visible_name] = *i;
2428                 row[results_columns.fullpath] = *i;
2429         }
2430
2431         list_scroller.add (results_display);
2432         list_scroller.set_size_request (-1, 150);
2433         list_scroller.set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
2434
2435         dvbox.pack_start (dhbox, true, false, 5);
2436         dvbox.pack_start (list_scroller, true, false, 5);
2437         ddhbox.pack_start (dvbox, true, false, 5);
2438
2439         results.get_vbox()->pack_start (ddhbox, true, false, 5);
2440         results.add_button (Stock::CLOSE, RESPONSE_CLOSE);
2441         results.set_default_response (RESPONSE_CLOSE);
2442         results.set_position (Gtk::WIN_POS_MOUSE);
2443
2444         results_display.show();
2445         list_scroller.show();
2446         txt.show();
2447         dvbox.show();
2448         dhbox.show();
2449         ddhbox.show();
2450         dimage->show();
2451
2452         //results.get_vbox()->show();
2453         results.set_resizable (false);
2454
2455         results.run ();
2456
2457 }
2458
2459 void
2460 ARDOUR_UI::cleanup ()
2461 {
2462         if (_session == 0) {
2463                 /* shouldn't happen: menu item is insensitive */
2464                 return;
2465         }
2466
2467
2468         MessageDialog checker (_("Are you sure you want to clean-up?"),
2469                                 true,
2470                                 Gtk::MESSAGE_QUESTION,
2471                                 Gtk::BUTTONS_NONE);
2472
2473         checker.set_title (_("Clean-up"));
2474
2475         checker.set_secondary_text(_("Clean-up is a destructive operation.\n\
2476 ALL undo/redo information will be lost if you clean-up.\n\
2477 Clean-up will move all unused files to a \"dead\" location."));
2478
2479         checker.add_button (Stock::CANCEL, RESPONSE_CANCEL);
2480         checker.add_button (_("Clean-up"), RESPONSE_ACCEPT);
2481         checker.set_default_response (RESPONSE_CANCEL);
2482
2483         checker.set_name (_("CleanupDialog"));
2484         checker.set_wmclass (X_("ardour_cleanup"), PROGRAM_NAME);
2485         checker.set_position (Gtk::WIN_POS_MOUSE);
2486
2487         switch (checker.run()) {
2488         case RESPONSE_ACCEPT:
2489                 break;
2490         default:
2491                 return;
2492         }
2493         checker.hide();
2494
2495         ARDOUR::CleanupReport rep;
2496
2497         editor->prepare_for_cleanup ();
2498
2499         /* do not allow flush until a session is reloaded */
2500         ActionManager::get_action (X_("Main"), X_("FlushWastebasket"))->set_sensitive (false);
2501
2502         if (_session->cleanup_sources (rep)) {
2503                 editor->finish_cleanup ();
2504                 return;
2505         }
2506
2507         editor->finish_cleanup ();
2508
2509         display_cleanup_results (rep, _("Cleaned Files"), false);
2510 }
2511
2512 void
2513 ARDOUR_UI::flush_trash ()
2514 {
2515         if (_session == 0) {
2516                 /* shouldn't happen: menu item is insensitive */
2517                 return;
2518         }
2519
2520         ARDOUR::CleanupReport rep;
2521
2522         if (_session->cleanup_trash_sources (rep)) {
2523                 return;
2524         }
2525
2526         display_cleanup_results (rep, _("deleted file"), true);
2527 }
2528
2529 void
2530 ARDOUR_UI::cleanup_peakfiles ()
2531 {
2532         if (_session == 0) {
2533                 /* shouldn't happen: menu item is insensitive */
2534                 return;
2535         }
2536
2537         if (! _session->can_cleanup_peakfiles ()) {
2538                 return;
2539         }
2540
2541         // get all region-views in this session
2542         RegionSelection rs;
2543         TrackViewList empty;
2544         empty.clear();
2545         editor->get_regions_after(rs, (samplepos_t) 0, empty);
2546         std::list<RegionView*> views = rs.by_layer();
2547
2548         // remove displayed audio-region-views waveforms
2549         for (list<RegionView*>::iterator i = views.begin(); i != views.end(); ++i) {
2550                 AudioRegionView* arv = dynamic_cast<AudioRegionView*> (*i);
2551                 if (!arv) { continue ; }
2552                 arv->delete_waves();
2553         }
2554
2555         // cleanup peak files:
2556         // - stop pending peakfile threads
2557         // - close peakfiles if any
2558         // - remove peak dir in session
2559         // - setup peakfiles (background thread)
2560         _session->cleanup_peakfiles ();
2561
2562         // re-add waves to ARV
2563         for (list<RegionView*>::iterator i = views.begin(); i != views.end(); ++i) {
2564                 AudioRegionView* arv = dynamic_cast<AudioRegionView*> (*i);
2565                 if (!arv) { continue ; }
2566                 arv->create_waves();
2567         }
2568 }
2569
2570 PresentationInfo::order_t
2571 ARDOUR_UI::translate_order (RouteDialogs::InsertAt place)
2572 {
2573         if (editor->get_selection().tracks.empty()) {
2574                 return place == RouteDialogs::First ? 0 : PresentationInfo::max_order;
2575         }
2576
2577         PresentationInfo::order_t order_hint = PresentationInfo::max_order;
2578
2579         /*
2580           we want the new routes to have their order keys set starting from
2581           the highest order key in the selection + 1 (if available).
2582         */
2583
2584         if (place == RouteDialogs::AfterSelection) {
2585                 RouteTimeAxisView *rtav = dynamic_cast<RouteTimeAxisView*> (editor->get_selection().tracks.back());
2586                 if (rtav) {
2587                         order_hint = rtav->route()->presentation_info().order();
2588                         order_hint++;
2589                 }
2590         } else if (place == RouteDialogs::BeforeSelection) {
2591                 RouteTimeAxisView *rtav = dynamic_cast<RouteTimeAxisView*> (editor->get_selection().tracks.front());
2592                 if (rtav) {
2593                         order_hint = rtav->route()->presentation_info().order();
2594                 }
2595         } else if (place == RouteDialogs::First) {
2596                 order_hint = 0;
2597         } else {
2598                 /* leave order_hint at max_order */
2599         }
2600
2601         return order_hint;
2602 }
2603
2604 void
2605 ARDOUR_UI::start_duplicate_routes ()
2606 {
2607         if (!duplicate_routes_dialog) {
2608                 duplicate_routes_dialog = new DuplicateRouteDialog;
2609         }
2610
2611         if (duplicate_routes_dialog->restart (_session)) {
2612                 return;
2613         }
2614
2615         duplicate_routes_dialog->present ();
2616 }
2617
2618 void
2619 ARDOUR_UI::add_route ()
2620 {
2621         if (!add_route_dialog.get (false)) {
2622                 add_route_dialog->signal_response().connect (sigc::mem_fun (*this, &ARDOUR_UI::add_route_dialog_response));
2623         }
2624
2625         if (!_session) {
2626                 return;
2627         }
2628
2629         if (add_route_dialog->is_visible()) {
2630                 /* we're already doing this */
2631                 return;
2632         }
2633
2634         add_route_dialog->set_position (WIN_POS_MOUSE);
2635         add_route_dialog->present();
2636 }
2637
2638 void
2639 ARDOUR_UI::add_route_dialog_response (int r)
2640 {
2641         if (!_session) {
2642                 warning << _("You cannot add tracks or busses without a session already loaded.") << endmsg;
2643                 return;
2644         }
2645
2646         if (!AudioEngine::instance()->running ()) {
2647                 switch (r) {
2648                         case AddRouteDialog::Add:
2649                         case AddRouteDialog::AddAndClose:
2650                                 break;
2651                         default:
2652                                 return;
2653                 }
2654                 add_route_dialog->ArdourDialog::on_response (r);
2655                 ARDOUR_UI_UTILS::engine_is_running ();
2656                 return;
2657         }
2658
2659         int count;
2660
2661         switch (r) {
2662         case AddRouteDialog::Add:
2663                 add_route_dialog->reset_name_edited ();
2664                 break;
2665         case AddRouteDialog::AddAndClose:
2666                 add_route_dialog->ArdourDialog::on_response (r);
2667                 break;
2668         default:
2669                 add_route_dialog->ArdourDialog::on_response (r);
2670                 return;
2671         }
2672
2673         std::string template_path = add_route_dialog->get_template_path();
2674         if (!template_path.empty() && template_path.substr (0, 11) == "urn:ardour:") {
2675                 meta_route_setup (template_path.substr (11));
2676                 return;
2677         }
2678
2679         if ((count = add_route_dialog->count()) <= 0) {
2680                 return;
2681         }
2682
2683         PresentationInfo::order_t order = translate_order (add_route_dialog->insert_at());
2684         const string name_template = add_route_dialog->name_template ();
2685         DisplaySuspender ds;
2686
2687         if (!template_path.empty ()) {
2688                 if (add_route_dialog->name_template_is_default ()) {
2689                         _session->new_route_from_template (count, order, template_path, string ());
2690                 } else {
2691                         _session->new_route_from_template (count, order, template_path, name_template);
2692                 }
2693                 return;
2694         }
2695
2696         ChanCount input_chan= add_route_dialog->channels ();
2697         ChanCount output_chan;
2698         PluginInfoPtr instrument = add_route_dialog->requested_instrument ();
2699         RouteGroup* route_group = add_route_dialog->route_group ();
2700         AutoConnectOption oac = Config->get_output_auto_connect();
2701         bool strict_io = add_route_dialog->use_strict_io ();
2702
2703         if (oac & AutoConnectMaster) {
2704                 output_chan.set (DataType::AUDIO, (_session->master_out() ? _session->master_out()->n_inputs().n_audio() : input_chan.n_audio()));
2705                 output_chan.set (DataType::MIDI, 0);
2706         } else {
2707                 output_chan = input_chan;
2708         }
2709
2710         /* XXX do something with name template */
2711
2712         Session::ProcessorChangeBlocker pcb (_session);
2713
2714         switch (add_route_dialog->type_wanted()) {
2715         case AddRouteDialog::AudioTrack:
2716                 session_add_audio_route (true, input_chan.n_audio(), output_chan.n_audio(), add_route_dialog->mode(), route_group, count, name_template, strict_io, order);
2717                 break;
2718         case AddRouteDialog::MidiTrack:
2719                 session_add_midi_route (true, route_group, count, name_template, strict_io, instrument, 0, order);
2720                 break;
2721         case AddRouteDialog::MixedTrack:
2722                 session_add_mixed_track (input_chan, output_chan, route_group, count, name_template, strict_io, instrument, 0, order);
2723                 break;
2724         case AddRouteDialog::AudioBus:
2725                 session_add_audio_route (false, input_chan.n_audio(), output_chan.n_audio(), ARDOUR::Normal, route_group, count, name_template, strict_io, order);
2726                 break;
2727         case AddRouteDialog::MidiBus:
2728                 session_add_midi_bus (route_group, count, name_template, strict_io, instrument, 0, order);
2729                 break;
2730         case AddRouteDialog::VCAMaster:
2731                 _session->vca_manager().create_vca (count, name_template);
2732                 break;
2733         case AddRouteDialog::FoldbackBus:
2734                 session_add_foldback_bus (input_chan.n_audio(), count, name_template);
2735                 ActionManager::get_toggle_action (X_("Mixer"), X_("ToggleFoldbackStrip"))->set_active (true);
2736                 break;
2737         }
2738 }
2739
2740 void
2741 ARDOUR_UI::disk_overrun_handler ()
2742 {
2743         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::disk_overrun_handler)
2744
2745         if (!have_disk_speed_dialog_displayed) {
2746                 have_disk_speed_dialog_displayed = true;
2747                 MessageDialog* msg = new MessageDialog (_main_window, string_compose (_("\
2748 The disk system on your computer\n\
2749 was not able to keep up with %1.\n\
2750 \n\
2751 Specifically, it failed to write data to disk\n\
2752 quickly enough to keep up with recording.\n"), PROGRAM_NAME));
2753                 msg->signal_response().connect (sigc::bind (sigc::mem_fun (*this, &ARDOUR_UI::disk_speed_dialog_gone), msg));
2754                 msg->show ();
2755         }
2756 }
2757
2758 void
2759 ARDOUR_UI::gui_idle_handler ()
2760 {
2761         int timeout = 30;
2762         /* due to idle calls, gtk_events_pending() may always return true */
2763         while (gtk_events_pending() && --timeout) {
2764                 gtk_main_iteration ();
2765         }
2766 }
2767
2768 void
2769 ARDOUR_UI::disk_underrun_handler ()
2770 {
2771         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::disk_underrun_handler)
2772
2773         if (!have_disk_speed_dialog_displayed) {
2774                 have_disk_speed_dialog_displayed = true;
2775                 MessageDialog* msg = new MessageDialog (
2776                         _main_window, string_compose (_("The disk system on your computer\n\
2777 was not able to keep up with %1.\n\
2778 \n\
2779 Specifically, it failed to read data from disk\n\
2780 quickly enough to keep up with playback.\n"), PROGRAM_NAME));
2781                 msg->signal_response().connect (sigc::bind (sigc::mem_fun (*this, &ARDOUR_UI::disk_speed_dialog_gone), msg));
2782                 msg->show ();
2783         }
2784 }
2785
2786 void
2787 ARDOUR_UI::disk_speed_dialog_gone (int /*ignored_response*/, MessageDialog* msg)
2788 {
2789         have_disk_speed_dialog_displayed = false;
2790         delete msg;
2791 }
2792
2793 void
2794 ARDOUR_UI::session_dialog (std::string msg)
2795 {
2796         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::session_dialog, msg)
2797
2798         MessageDialog* d;
2799
2800         d = new MessageDialog (msg, false, MESSAGE_INFO, BUTTONS_OK, true);
2801         d->show_all ();
2802         d->run ();
2803         delete d;
2804 }
2805
2806 int
2807 ARDOUR_UI::pending_state_dialog ()
2808 {
2809         HBox* hbox = manage (new HBox());
2810         Image* image = manage (new Image (Stock::DIALOG_QUESTION, ICON_SIZE_DIALOG));
2811         ArdourDialog dialog (_("Crash Recovery"), true);
2812         Label  message (string_compose (_("\
2813 This session appears to have been in the\n\
2814 middle of recording when %1 or\n\
2815 the computer was shutdown.\n\
2816 \n\
2817 %1 can recover any captured audio for\n\
2818 you, or it can ignore it. Please decide\n\
2819 what you would like to do.\n"), PROGRAM_NAME));
2820         image->set_alignment(ALIGN_CENTER, ALIGN_TOP);
2821         hbox->pack_start (*image, PACK_EXPAND_WIDGET, 12);
2822         hbox->pack_end (message, PACK_EXPAND_PADDING, 12);
2823         dialog.get_vbox()->pack_start(*hbox, PACK_EXPAND_PADDING, 6);
2824         dialog.add_button (_("Ignore crash data"), RESPONSE_REJECT);
2825         dialog.add_button (_("Recover from crash"), RESPONSE_ACCEPT);
2826         dialog.set_default_response (RESPONSE_ACCEPT);
2827         dialog.set_position (WIN_POS_CENTER);
2828         message.show();
2829         image->show();
2830         hbox->show();
2831
2832         switch (dialog.run ()) {
2833         case RESPONSE_ACCEPT:
2834                 return 1;
2835         default:
2836                 return 0;
2837         }
2838 }
2839
2840 void
2841 ARDOUR_UI::store_clock_modes ()
2842 {
2843         if (session_load_in_progress) {
2844                 /* Do not overwrite clock modes while loading them (with a session) */
2845                 return;
2846         }
2847
2848         XMLNode* node = new XMLNode(X_("ClockModes"));
2849
2850         for (vector<AudioClock*>::iterator x = AudioClock::clocks.begin(); x != AudioClock::clocks.end(); ++x) {
2851                 XMLNode* child = new XMLNode (X_("Clock"));
2852
2853                 child->set_property (X_("name"), (*x)->name());
2854                 child->set_property (X_("mode"), (*x)->mode());
2855                 child->set_property (X_("on"), (*x)->on());
2856
2857                 node->add_child_nocopy (*child);
2858         }
2859
2860         _session->add_extra_xml (*node);
2861         _session->set_dirty ();
2862 }
2863
2864 /** Allocate our thread-local buffers */
2865 void
2866 ARDOUR_UI::get_process_buffers ()
2867 {
2868         _process_thread->get_buffers ();
2869 }
2870
2871 /** Drop our thread-local buffers */
2872 void
2873 ARDOUR_UI::drop_process_buffers ()
2874 {
2875         _process_thread->drop_buffers ();
2876 }
2877
2878 void
2879 ARDOUR_UI::feedback_detected ()
2880 {
2881         _feedback_exists = true;
2882 }
2883
2884 void
2885 ARDOUR_UI::successful_graph_sort ()
2886 {
2887         _feedback_exists = false;
2888 }
2889
2890 void
2891 ARDOUR_UI::midi_panic ()
2892 {
2893         if (_session) {
2894                 _session->midi_panic();
2895         }
2896 }
2897
2898 void
2899 ARDOUR_UI::reset_peak_display ()
2900 {
2901         if (!_session || !_session->master_out() || !editor_meter) return;
2902         editor_meter->clear_meters();
2903         editor_meter_max_peak = -INFINITY;
2904         editor_meter_peak_display.set_active_state ( Gtkmm2ext::Off );
2905 }
2906
2907 void
2908 ARDOUR_UI::reset_group_peak_display (RouteGroup* group)
2909 {
2910         if (!_session || !_session->master_out()) return;
2911         if (group == _session->master_out()->route_group()) {
2912                 reset_peak_display ();
2913         }
2914 }
2915
2916 void
2917 ARDOUR_UI::reset_route_peak_display (Route* route)
2918 {
2919         if (!_session || !_session->master_out()) return;
2920         if (_session->master_out().get() == route) {
2921                 reset_peak_display ();
2922         }
2923 }
2924
2925 void
2926 ARDOUR_UI::hide_application ()
2927 {
2928         Application::instance ()-> hide ();
2929 }
2930
2931 void
2932 ARDOUR_UI::setup_toplevel_window (Gtk::Window& window, const string& name, void* owner)
2933 {
2934         /* icons, titles, WM stuff */
2935
2936         static list<Glib::RefPtr<Gdk::Pixbuf> > window_icons;
2937
2938         if (window_icons.empty()) {
2939                 Glib::RefPtr<Gdk::Pixbuf> icon;
2940                 if ((icon = ::get_icon (PROGRAM_NAME "-icon_16px"))) {
2941                         window_icons.push_back (icon);
2942                 }
2943                 if ((icon = ::get_icon (PROGRAM_NAME "-icon_22px"))) {
2944                         window_icons.push_back (icon);
2945                 }
2946                 if ((icon = ::get_icon (PROGRAM_NAME "-icon_32px"))) {
2947                         window_icons.push_back (icon);
2948                 }
2949                 if ((icon = ::get_icon (PROGRAM_NAME "-icon_48px"))) {
2950                         window_icons.push_back (icon);
2951                 }
2952         }
2953
2954         if (!window_icons.empty()) {
2955                 window.set_default_icon_list (window_icons);
2956         }
2957
2958         Gtkmm2ext::WindowTitle title (Glib::get_application_name());
2959
2960         if (!name.empty()) {
2961                 title += name;
2962         }
2963
2964         window.set_title (title.get_string());
2965         window.set_wmclass (string_compose (X_("%1_%1"), downcase (std::string(PROGRAM_NAME)), downcase (name)), PROGRAM_NAME);
2966
2967         window.set_flags (CAN_FOCUS);
2968         window.add_events (Gdk::KEY_PRESS_MASK|Gdk::KEY_RELEASE_MASK);
2969
2970         /* This is a hack to ensure that GTK-accelerators continue to
2971          * work. Once we switch over to entirely native bindings, this will be
2972          * unnecessary and should be removed
2973          */
2974         window.add_accel_group (ActionManager::ui_manager->get_accel_group());
2975
2976         window.signal_configure_event().connect (sigc::mem_fun (*this, &ARDOUR_UI::configure_handler));
2977         window.signal_window_state_event().connect (sigc::bind (sigc::mem_fun (*this, &ARDOUR_UI::tabbed_window_state_event_handler), owner));
2978         window.signal_key_press_event().connect (sigc::bind (sigc::mem_fun (*this, &ARDOUR_UI::key_event_handler), &window), false);
2979         window.signal_key_release_event().connect (sigc::bind (sigc::mem_fun (*this, &ARDOUR_UI::key_event_handler), &window), false);
2980 }