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