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