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