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