replace a few creeping instances of the string "Ardour" with PROGRAM_NAME
[ardour.git] / gtk2_ardour / ardour_ui.cc
1 /*
2     Copyright (C) 1999-2013 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #ifdef WAF_BUILD
21 #include "gtk2ardour-config.h"
22 #endif
23
24 #include <algorithm>
25 #include <cmath>
26 #include <iostream>
27 #include <cerrno>
28 #include <fstream>
29
30 #ifndef PLATFORM_WINDOWS
31 #include <sys/resource.h>
32 #endif
33
34 #include <stdint.h>
35 #include <fcntl.h>
36 #include <signal.h>
37 #include <unistd.h>
38 #include <time.h>
39
40 #include <glib.h>
41 #include <glib/gstdio.h>
42
43 #include <gtkmm/messagedialog.h>
44 #include <gtkmm/accelmap.h>
45
46 #include "pbd/error.h"
47 #include "pbd/basename.h"
48 #include "pbd/compose.h"
49 #include "pbd/failed_constructor.h"
50 #include "pbd/enumwriter.h"
51 #include "pbd/memento_command.h"
52 #include "pbd/openuri.h"
53 #include "pbd/file_utils.h"
54 #include "pbd/localtime_r.h"
55
56 #include "gtkmm2ext/application.h"
57 #include "gtkmm2ext/bindings.h"
58 #include "gtkmm2ext/gtk_ui.h"
59 #include "gtkmm2ext/utils.h"
60 #include "gtkmm2ext/click_box.h"
61 #include "gtkmm2ext/fastmeter.h"
62 #include "gtkmm2ext/popup.h"
63 #include "gtkmm2ext/window_title.h"
64
65 #include "ardour/ardour.h"
66 #include "ardour/audio_backend.h"
67 #include "ardour/audioengine.h"
68 #include "ardour/audiofilesource.h"
69 #include "ardour/automation_watch.h"
70 #include "ardour/diskstream.h"
71 #include "ardour/filename_extensions.h"
72 #include "ardour/filesystem_paths.h"
73 #include "ardour/port.h"
74 #include "ardour/process_thread.h"
75 #include "ardour/profile.h"
76 #include "ardour/recent_sessions.h"
77 #include "ardour/session_directory.h"
78 #include "ardour/session_route.h"
79 #include "ardour/session_state_utils.h"
80 #include "ardour/session_utils.h"
81 #include "ardour/slave.h"
82
83 #include "timecode/time.h"
84
85 typedef uint64_t microseconds_t;
86
87 #include "about.h"
88 #include "actions.h"
89 #include "add_route_dialog.h"
90 #include "ambiguous_file_dialog.h"
91 #include "ardour_ui.h"
92 #include "audio_clock.h"
93 #include "big_clock_window.h"
94 #include "bundle_manager.h"
95 #include "engine_dialog.h"
96 #include "gain_meter.h"
97 #include "global_port_matrix.h"
98 #include "gui_object.h"
99 #include "gui_thread.h"
100 #include "keyboard.h"
101 #include "keyeditor.h"
102 #include "location_ui.h"
103 #include "main_clock.h"
104 #include "missing_file_dialog.h"
105 #include "missing_plugin_dialog.h"
106 #include "mixer_ui.h"
107 #include "mouse_cursors.h"
108 #include "nsm.h"
109 #include "opts.h"
110 #include "pingback.h"
111 #include "processor_box.h"
112 #include "prompter.h"
113 #include "public_editor.h"
114 #include "rc_option_editor.h"
115 #include "route_time_axis.h"
116 #include "route_params_ui.h"
117 #include "session_dialog.h"
118 #include "session_metadata_dialog.h"
119 #include "session_option_editor.h"
120 #include "shuttle_control.h"
121 #include "speaker_dialog.h"
122 #include "splash.h"
123 #include "startup.h"
124 #include "theme_manager.h"
125 #include "time_axis_view_item.h"
126 #include "utils.h"
127 #include "video_server_dialog.h"
128 #include "add_video_dialog.h"
129 #include "transcode_video_dialog.h"
130 #include "system_exec.h"
131
132 #include "i18n.h"
133
134 using namespace ARDOUR;
135 using namespace PBD;
136 using namespace Gtkmm2ext;
137 using namespace Gtk;
138 using namespace std;
139
140 ARDOUR_UI *ARDOUR_UI::theArdourUI = 0;
141 UIConfiguration *ARDOUR_UI::ui_config = 0;
142
143 sigc::signal<void,bool> ARDOUR_UI::Blink;
144 sigc::signal<void>      ARDOUR_UI::RapidScreenUpdate;
145 sigc::signal<void>      ARDOUR_UI::SuperRapidScreenUpdate;
146 sigc::signal<void, framepos_t, bool, framepos_t> ARDOUR_UI::Clock;
147 sigc::signal<void>      ARDOUR_UI::CloseAllDialogs;
148
149 ARDOUR_UI::ARDOUR_UI (int *argcp, char **argvp[], const char* localedir)
150
151         : Gtkmm2ext::UI (PROGRAM_NAME, argcp, argvp)
152         
153         , gui_object_state (new GUIObjectState)
154
155         , primary_clock (new MainClock (X_("primary"), false, X_("transport"), true, true, true, false, true))
156         , secondary_clock (new MainClock (X_("secondary"), false, X_("secondary"), true, true, false, false, true))
157
158           /* big clock */
159
160         , big_clock (new AudioClock (X_("bigclock"), false, "big", true, true, false, false))
161         , video_timeline(0)
162
163           /* start of private members */
164
165         , nsm (0)
166         , _was_dirty (false)
167         , _mixer_on_top (false)
168         , first_time_engine_run (true)
169         , blink_timeout_tag (-1)
170
171           /* transport */
172
173         , roll_controllable (new TransportControllable ("transport roll", *this, TransportControllable::Roll))
174         , stop_controllable (new TransportControllable ("transport stop", *this, TransportControllable::Stop))
175         , goto_start_controllable (new TransportControllable ("transport goto start", *this, TransportControllable::GotoStart))
176         , goto_end_controllable (new TransportControllable ("transport goto end", *this, TransportControllable::GotoEnd))
177         , auto_loop_controllable (new TransportControllable ("transport auto loop", *this, TransportControllable::AutoLoop))
178         , play_selection_controllable (new TransportControllable ("transport play selection", *this, TransportControllable::PlaySelection))
179         , rec_controllable (new TransportControllable ("transport rec-enable", *this, TransportControllable::RecordEnable))
180
181         , auto_return_button (ArdourButton::led_default_elements)
182         , follow_edits_button (ArdourButton::led_default_elements)
183         , auto_input_button (ArdourButton::led_default_elements)
184
185         , auditioning_alert_button (_("audition"))
186         , solo_alert_button (_("solo"))
187         , feedback_alert_button (_("feedback"))
188
189         , editor_meter(0)
190         , editor_meter_peak_display()
191
192         , speaker_config_window (X_("speaker-config"), _("Speaker Configuration"))
193         , theme_manager (X_("theme-manager"), _("Theme Manager"))
194         , key_editor (X_("key-editor"), _("Key Bindings"))
195         , rc_option_editor (X_("rc-options-editor"), _("Preferences"))
196         , add_route_dialog (X_("add-routes"), _("Add Tracks/Busses"))
197         , about (X_("about"), _("About"))
198         , location_ui (X_("locations"), _("Locations"))
199         , route_params (X_("inspector"), _("Tracks and Busses"))
200         , audio_midi_setup (X_("audio-midi-setup"), _("Audio/MIDI Setup"))
201         , session_option_editor (X_("session-options-editor"), _("Properties"), boost::bind (&ARDOUR_UI::create_session_option_editor, this))
202         , add_video_dialog (X_("add-video"), _("Add Tracks/Busses"), boost::bind (&ARDOUR_UI::create_add_video_dialog, this))
203         , bundle_manager (X_("bundle-manager"), _("Bundle Manager"), boost::bind (&ARDOUR_UI::create_bundle_manager, this))
204         , big_clock_window (X_("big-clock"), _("Big Clock"), boost::bind (&ARDOUR_UI::create_big_clock_window, this))
205         , audio_port_matrix (X_("audio-connection-manager"), _("Audio Connections"), boost::bind (&ARDOUR_UI::create_global_port_matrix, this, ARDOUR::DataType::AUDIO))
206         , midi_port_matrix (X_("midi-connection-manager"), _("MIDI Connections"), boost::bind (&ARDOUR_UI::create_global_port_matrix, this, ARDOUR::DataType::MIDI))
207
208         , error_log_button (_("Errors"))
209
210         , _status_bar_visibility (X_("status-bar"))
211         , _feedback_exists (false)
212 {
213         Gtkmm2ext::init(localedir);
214
215         splash = 0;
216
217         if (theArdourUI == 0) {
218                 theArdourUI = this;
219         }
220
221         ui_config = new UIConfiguration();
222
223         ui_config->ParameterChanged.connect (sigc::mem_fun (*this, &ARDOUR_UI::parameter_changed));
224         boost::function<void (string)> pc (boost::bind (&ARDOUR_UI::parameter_changed, this, _1));
225         ui_config->map_parameters (pc);
226
227         editor = 0;
228         mixer = 0;
229         meterbridge = 0;
230         editor = 0;
231         _session_is_new = false;
232         session_selector_window = 0;
233         last_key_press_time = 0;
234         video_server_process = 0;
235         open_session_selector = 0;
236         have_configure_timeout = false;
237         have_disk_speed_dialog_displayed = false;
238         session_loaded = false;
239         ignore_dual_punch = false;
240
241         roll_button.set_controllable (roll_controllable);
242         stop_button.set_controllable (stop_controllable);
243         goto_start_button.set_controllable (goto_start_controllable);
244         goto_end_button.set_controllable (goto_end_controllable);
245         auto_loop_button.set_controllable (auto_loop_controllable);
246         play_selection_button.set_controllable (play_selection_controllable);
247         rec_button.set_controllable (rec_controllable);
248
249         roll_button.set_name ("transport button");
250         stop_button.set_name ("transport button");
251         goto_start_button.set_name ("transport button");
252         goto_end_button.set_name ("transport button");
253         auto_loop_button.set_name ("transport button");
254         play_selection_button.set_name ("transport button");
255         rec_button.set_name ("transport recenable button");
256         midi_panic_button.set_name ("transport button");
257
258         goto_start_button.set_tweaks (ArdourButton::ShowClick);
259         goto_end_button.set_tweaks (ArdourButton::ShowClick);
260         midi_panic_button.set_tweaks (ArdourButton::ShowClick);
261         
262         last_configure_time= 0;
263         last_peak_grab = 0;
264
265         ARDOUR::Diskstream::DiskOverrun.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::disk_overrun_handler, this), gui_context());
266         ARDOUR::Diskstream::DiskUnderrun.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::disk_underrun_handler, this), gui_context());
267
268         ARDOUR::Session::VersionMismatch.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::session_format_mismatch, this, _1, _2), gui_context());
269
270         /* handle dialog requests */
271
272         ARDOUR::Session::Dialog.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::session_dialog, this, _1), gui_context());
273
274         /* handle pending state with a dialog (PROBLEM: needs to return a value and thus cannot be x-thread) */
275
276         ARDOUR::Session::AskAboutPendingState.connect_same_thread (forever_connections, boost::bind (&ARDOUR_UI::pending_state_dialog, this));
277
278         /* handle Audio/MIDI setup when session requires it */
279
280         ARDOUR::Session::AudioEngineSetupRequired.connect_same_thread (forever_connections, boost::bind (&ARDOUR_UI::do_audio_midi_setup, this, _1));
281
282         /* handle sr mismatch with a dialog (PROBLEM: needs to return a value and thus cannot be x-thread) */
283
284         ARDOUR::Session::AskAboutSampleRateMismatch.connect_same_thread (forever_connections, boost::bind (&ARDOUR_UI::sr_mismatch_dialog, this, _1, _2));
285
286         /* handle requests to quit (coming from JACK session) */
287
288         ARDOUR::Session::Quit.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::finish, this), gui_context ());
289
290         /* tell the user about feedback */
291
292         ARDOUR::Session::FeedbackDetected.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::feedback_detected, this), gui_context ());
293         ARDOUR::Session::SuccessfulGraphSort.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::successful_graph_sort, this), gui_context ());
294
295         /* handle requests to deal with missing files */
296
297         ARDOUR::Session::MissingFile.connect_same_thread (forever_connections, boost::bind (&ARDOUR_UI::missing_file, this, _1, _2, _3));
298
299         /* and ambiguous files */
300
301         ARDOUR::FileSource::AmbiguousFileName.connect_same_thread (forever_connections, boost::bind (&ARDOUR_UI::ambiguous_file, this, _1, _2));
302
303         /* lets get this party started */
304
305         setup_gtk_ardour_enums ();
306         setup_profile ();
307
308         SessionEvent::create_per_thread_pool ("GUI", 512);
309
310         /* we like keyboards */
311
312         keyboard = new ArdourKeyboard(*this);
313
314         XMLNode* node = ARDOUR_UI::instance()->keyboard_settings();
315         if (node) {
316                 keyboard->set_state (*node, Stateful::loading_state_version);
317         }
318
319         /* we don't like certain modifiers */
320         Bindings::set_ignored_state (GDK_LOCK_MASK|GDK_MOD2_MASK|GDK_MOD3_MASK);
321
322         reset_dpi();
323
324         TimeAxisViewItem::set_constant_heights ();
325
326         /* Set this up so that our window proxies can register actions */
327
328         ActionManager::init ();
329
330         /* The following must happen after ARDOUR::init() so that Config is set up */
331
332         const XMLNode* ui_xml = Config->extra_xml (X_("UI"));
333
334         if (ui_xml) {
335                 theme_manager.set_state (*ui_xml);
336                 key_editor.set_state (*ui_xml);
337                 rc_option_editor.set_state (*ui_xml);
338                 session_option_editor.set_state (*ui_xml);
339                 speaker_config_window.set_state (*ui_xml);
340                 about.set_state (*ui_xml);
341                 add_route_dialog.set_state (*ui_xml);
342                 add_video_dialog.set_state (*ui_xml);
343                 route_params.set_state (*ui_xml);
344                 bundle_manager.set_state (*ui_xml);
345                 location_ui.set_state (*ui_xml);
346                 big_clock_window.set_state (*ui_xml);
347                 audio_port_matrix.set_state (*ui_xml);
348                 midi_port_matrix.set_state (*ui_xml);
349         }
350
351         WM::Manager::instance().register_window (&theme_manager);
352         WM::Manager::instance().register_window (&key_editor);
353         WM::Manager::instance().register_window (&rc_option_editor);
354         WM::Manager::instance().register_window (&session_option_editor);
355         WM::Manager::instance().register_window (&speaker_config_window);
356         WM::Manager::instance().register_window (&about);
357         WM::Manager::instance().register_window (&add_route_dialog);
358         WM::Manager::instance().register_window (&add_video_dialog);
359         WM::Manager::instance().register_window (&route_params);
360         WM::Manager::instance().register_window (&audio_midi_setup);
361         WM::Manager::instance().register_window (&bundle_manager);
362         WM::Manager::instance().register_window (&location_ui);
363         WM::Manager::instance().register_window (&big_clock_window);
364         WM::Manager::instance().register_window (&audio_port_matrix);
365         WM::Manager::instance().register_window (&midi_port_matrix);
366
367         /* We need to instantiate the theme manager because it loads our
368            theme files. This should really change so that its window
369            and its functionality are separate 
370         */
371         
372         (void) theme_manager.get (true);
373         
374         _process_thread = new ProcessThread ();
375         _process_thread->init ();
376
377         DPIReset.connect (sigc::mem_fun (*this, &ARDOUR_UI::resize_text_widgets));
378
379         attach_to_engine ();
380 }
381
382 GlobalPortMatrixWindow*
383 ARDOUR_UI::create_global_port_matrix (ARDOUR::DataType type)
384 {
385         if (!_session) {
386                 return 0;
387         }
388         return new GlobalPortMatrixWindow (_session, type);
389 }
390
391 void
392 ARDOUR_UI::attach_to_engine ()
393 {
394         AudioEngine::instance()->Running.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::engine_running, this), gui_context());
395         ARDOUR::Port::set_connecting_blocked (ARDOUR_COMMAND_LINE::no_connect_ports);
396 }
397
398 void
399 ARDOUR_UI::engine_stopped ()
400 {
401         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::engine_stopped)
402         ActionManager::set_sensitive (ActionManager::engine_sensitive_actions, false);
403         ActionManager::set_sensitive (ActionManager::engine_opposite_sensitive_actions, true);
404 }
405
406 void
407 ARDOUR_UI::engine_running ()
408 {
409         if (first_time_engine_run) {
410                 post_engine();
411                 first_time_engine_run = false;
412         } 
413         
414         update_disk_space ();
415         update_cpu_load ();
416         update_sample_rate (AudioEngine::instance()->sample_rate());
417         update_timecode_format ();
418 }
419
420 void
421 ARDOUR_UI::engine_halted (const char* reason, bool free_reason)
422 {
423         if (!Gtkmm2ext::UI::instance()->caller_is_ui_thread()) {
424                 /* we can't rely on the original string continuing to exist when we are called
425                    again in the GUI thread, so make a copy and note that we need to
426                    free it later.
427                 */
428                 char *copy = strdup (reason);
429                 Gtkmm2ext::UI::instance()->call_slot (invalidator (*this), boost::bind (&ARDOUR_UI::engine_halted, this, copy, true));
430                 return;
431         }
432
433         ActionManager::set_sensitive (ActionManager::engine_sensitive_actions, false);
434         ActionManager::set_sensitive (ActionManager::engine_opposite_sensitive_actions, true);
435
436         update_sample_rate (0);
437
438         string msgstr;
439
440         /* if the reason is a non-empty string, it means that the backend was shutdown
441            rather than just Ardour.
442         */
443
444         if (strlen (reason)) {
445                 msgstr = string_compose (_("The audio backend was shutdown because:\n\n%1"), reason);
446         } else {
447                 msgstr = string_compose (_("\
448 The audio backend has either been shutdown or it\n\
449 disconnected %1 because %1\n\
450 was not fast enough. Try to restart\n\
451 the audio backend and save the session."), PROGRAM_NAME);
452         }
453
454         MessageDialog msg (*editor, msgstr);
455         pop_back_splash (msg);
456         msg.set_keep_above (true);
457         msg.run ();
458         
459         if (free_reason) {
460                 free (const_cast<char*> (reason));
461         }
462 }
463
464 void
465 ARDOUR_UI::post_engine ()
466 {
467         /* Things to be done once (and once ONLY) after we have a backend running in the AudioEngine
468          */
469
470         ARDOUR::init_post_engine ();
471         
472         /* connect to important signals */
473
474         AudioEngine::instance()->Stopped.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::engine_stopped, this), gui_context());
475         AudioEngine::instance()->SampleRateChanged.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::update_sample_rate, this, _1), gui_context());
476         AudioEngine::instance()->Halted.connect_same_thread (halt_connection, boost::bind (&ARDOUR_UI::engine_halted, this, _1, false));
477
478         _tooltips.enable();
479
480         ActionManager::load_menus ();
481
482         if (setup_windows ()) {
483                 throw failed_constructor ();
484         }
485
486         /* Do this after setup_windows (), as that's when the _status_bar_visibility is created */
487         XMLNode* n = Config->extra_xml (X_("UI"));
488         if (n) {
489                 _status_bar_visibility.set_state (*n);
490         }
491         
492         check_memory_locking();
493
494         /* this is the first point at which all the keybindings are available */
495
496         if (ARDOUR_COMMAND_LINE::show_key_actions) {
497                 vector<string> names;
498                 vector<string> paths;
499                 vector<string> tooltips;
500                 vector<string> keys;
501                 vector<AccelKey> bindings;
502
503                 ActionManager::get_all_actions (names, paths, tooltips, keys, bindings);
504
505                 vector<string>::iterator n;
506                 vector<string>::iterator k;
507                 for (n = names.begin(), k = keys.begin(); n != names.end(); ++n, ++k) {
508                         cout << "Action: " << (*n) << " bound to " << (*k) << endl;
509                 }
510
511                 exit (0);
512         }
513
514         blink_timeout_tag = -1;
515
516         /* this being a GUI and all, we want peakfiles */
517
518         AudioFileSource::set_build_peakfiles (true);
519         AudioFileSource::set_build_missing_peakfiles (true);
520
521         /* set default clock modes */
522
523         if (Profile->get_sae()) {
524                 primary_clock->set_mode (AudioClock::BBT);
525                 secondary_clock->set_mode (AudioClock::MinSec);
526         }  else {
527                 primary_clock->set_mode (AudioClock::Timecode);
528                 secondary_clock->set_mode (AudioClock::BBT);
529         }
530
531         /* start the time-of-day-clock */
532
533 #ifndef GTKOSX
534         /* OS X provides a nearly-always visible wallclock, so don't be stupid */
535         update_wall_clock ();
536         Glib::signal_timeout().connect_seconds (sigc::mem_fun(*this, &ARDOUR_UI::update_wall_clock), 1);
537 #endif
538
539         Config->ParameterChanged.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::parameter_changed, this, _1), gui_context());
540         boost::function<void (string)> pc (boost::bind (&ARDOUR_UI::parameter_changed, this, _1));
541         Config->map_parameters (pc);
542 }
543
544 ARDOUR_UI::~ARDOUR_UI ()
545 {
546         if (ui_config->dirty()) {
547                 ui_config->save_state();
548         }
549
550         delete keyboard;
551         delete editor;
552         delete mixer;
553         delete meterbridge;
554
555         stop_video_server();
556 }
557
558 void
559 ARDOUR_UI::pop_back_splash (Gtk::Window& win)
560 {
561         if (Splash::instance()) {
562                 Splash::instance()->pop_back_for (win);
563         }
564 }
565
566 gint
567 ARDOUR_UI::configure_timeout ()
568 {
569         if (last_configure_time == 0) {
570                 /* no configure events yet */
571                 return true;
572         }
573
574         /* force a gap of 0.5 seconds since the last configure event
575          */
576
577         if (get_microseconds() - last_configure_time < 500000) {
578                 return true;
579         } else {
580                 have_configure_timeout = false;
581                 save_ardour_state ();
582                 return false;
583         }
584 }
585
586 gboolean
587 ARDOUR_UI::configure_handler (GdkEventConfigure* /*conf*/)
588 {
589         if (have_configure_timeout) {
590                 last_configure_time = get_microseconds();
591         } else {
592                 Glib::signal_timeout().connect (sigc::mem_fun(*this, &ARDOUR_UI::configure_timeout), 100);
593                 have_configure_timeout = true;
594         }
595
596         return FALSE;
597 }
598
599 void
600 ARDOUR_UI::set_transport_controllable_state (const XMLNode& node)
601 {
602         const XMLProperty* prop;
603
604         if ((prop = node.property ("roll")) != 0) {
605                 roll_controllable->set_id (prop->value());
606         }
607         if ((prop = node.property ("stop")) != 0) {
608                 stop_controllable->set_id (prop->value());
609         }
610         if ((prop = node.property ("goto-start")) != 0) {
611                 goto_start_controllable->set_id (prop->value());
612         }
613         if ((prop = node.property ("goto-end")) != 0) {
614                 goto_end_controllable->set_id (prop->value());
615         }
616         if ((prop = node.property ("auto-loop")) != 0) {
617                 auto_loop_controllable->set_id (prop->value());
618         }
619         if ((prop = node.property ("play-selection")) != 0) {
620                 play_selection_controllable->set_id (prop->value());
621         }
622         if ((prop = node.property ("rec")) != 0) {
623                 rec_controllable->set_id (prop->value());
624         }
625         if ((prop = node.property ("shuttle")) != 0) {
626                 shuttle_box->controllable()->set_id (prop->value());
627         }
628 }
629
630 XMLNode&
631 ARDOUR_UI::get_transport_controllable_state ()
632 {
633         XMLNode* node = new XMLNode(X_("TransportControllables"));
634         char buf[64];
635
636         roll_controllable->id().print (buf, sizeof (buf));
637         node->add_property (X_("roll"), buf);
638         stop_controllable->id().print (buf, sizeof (buf));
639         node->add_property (X_("stop"), buf);
640         goto_start_controllable->id().print (buf, sizeof (buf));
641         node->add_property (X_("goto_start"), buf);
642         goto_end_controllable->id().print (buf, sizeof (buf));
643         node->add_property (X_("goto_end"), buf);
644         auto_loop_controllable->id().print (buf, sizeof (buf));
645         node->add_property (X_("auto_loop"), buf);
646         play_selection_controllable->id().print (buf, sizeof (buf));
647         node->add_property (X_("play_selection"), buf);
648         rec_controllable->id().print (buf, sizeof (buf));
649         node->add_property (X_("rec"), buf);
650         shuttle_box->controllable()->id().print (buf, sizeof (buf));
651         node->add_property (X_("shuttle"), buf);
652
653         return *node;
654 }
655
656
657 gint
658 ARDOUR_UI::autosave_session ()
659 {
660         if (g_main_depth() > 1) {
661                 /* inside a recursive main loop,
662                    give up because we may not be able to
663                    take a lock.
664                 */
665                 return 1;
666         }
667
668         if (!Config->get_periodic_safety_backups()) {
669                 return 1;
670         }
671
672         if (_session) {
673                 _session->maybe_write_autosave();
674         }
675
676         return 1;
677 }
678
679 void
680 ARDOUR_UI::update_autosave ()
681 {
682         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::update_autosave)
683
684         if (_session && _session->dirty()) {
685                 if (_autosave_connection.connected()) {
686                         _autosave_connection.disconnect();
687                 }
688
689                 _autosave_connection = Glib::signal_timeout().connect (sigc::mem_fun (*this, &ARDOUR_UI::autosave_session),
690                                 Config->get_periodic_safety_backup_interval() * 1000);
691
692         } else {
693                 if (_autosave_connection.connected()) {
694                         _autosave_connection.disconnect();
695                 }
696         }
697 }
698
699 void
700 ARDOUR_UI::check_announcements ()
701 {
702 #ifdef PHONE_HOME
703         string _annc_filename;
704
705 #ifdef __APPLE__
706         _annc_filename = PROGRAM_NAME "_announcements_osx_";
707 #else
708         _annc_filename = PROGRAM_NAME "_announcements_linux_";
709 #endif
710         _annc_filename.append (VERSIONSTRING);
711
712         std::string path = Glib::build_filename (user_config_directory(), _annc_filename);
713         std::ifstream announce_file (path.c_str());
714         if ( announce_file.fail() )
715                 _announce_string = "";
716         else {
717                 std::stringstream oss;
718                 oss << announce_file.rdbuf();
719                 _announce_string = oss.str();
720         }
721
722         pingback (VERSIONSTRING, path);
723 #endif
724 }
725
726 int
727 ARDOUR_UI::starting ()
728 {
729         Application* app = Application::instance ();
730         const char *nsm_url;
731         bool brand_new_user = ArdourStartup::required ();
732
733         app->ShouldQuit.connect (sigc::mem_fun (*this, &ARDOUR_UI::queue_finish));
734         app->ShouldLoad.connect (sigc::mem_fun (*this, &ARDOUR_UI::idle_load));
735
736         if (ARDOUR_COMMAND_LINE::check_announcements) {
737                 check_announcements ();
738         }
739
740         app->ready ();
741
742         /* we need to create this early because it may need to set the
743          *  audio backend end up.
744          */
745         
746         try {
747                 audio_midi_setup.get (true);
748         } catch (...) {
749                 return -1;
750         }
751
752         if ((nsm_url = g_getenv ("NSM_URL")) != 0) {
753                 nsm = new NSM_Client;
754                 if (!nsm->init (nsm_url)) {
755                         nsm->announce (PROGRAM_NAME, ":dirty:", "ardour3");
756
757                         unsigned int i = 0;
758                         // wait for announce reply from nsm server
759                         for ( i = 0; i < 5000; ++i) {
760                                 nsm->check ();
761
762                                 Glib::usleep (i);
763                                 if (nsm->is_active()) {
764                                         break;
765                                 }
766                         }
767                         if (i == 5000) {
768                                 error << _("NSM server did not announce itself") << endmsg;
769                                 return -1;
770                         }
771                         // wait for open command from nsm server
772                         for ( i = 0; i < 5000; ++i) {
773                                 nsm->check ();
774                                 Glib::usleep (1000);
775                                 if (nsm->client_id ()) {
776                                         break;
777                                 }
778                         }
779
780                         if (i == 5000) {
781                                 error << _("NSM: no client ID provided") << endmsg;
782                                 return -1;
783                         }
784
785                         if (_session && nsm) {
786                                 _session->set_nsm_state( nsm->is_active() );
787                         } else {
788                                 error << _("NSM: no session created") << endmsg;
789                                 return -1;
790                         }
791
792                         // nsm requires these actions disabled
793                         vector<string> action_names;
794                         action_names.push_back("SaveAs");
795                         action_names.push_back("Rename");
796                         action_names.push_back("New");
797                         action_names.push_back("Open");
798                         action_names.push_back("Recent");
799                         action_names.push_back("Close");
800
801                         for (vector<string>::const_iterator n = action_names.begin(); n != action_names.end(); ++n) {
802                                 Glib::RefPtr<Action> act = ActionManager::get_action (X_("Main"), (*n).c_str());
803                                 if (act) {
804                                         act->set_sensitive (false);
805                                 }
806                         }
807
808                 } else {
809                         delete nsm;
810                         nsm = 0;
811                         error << _("NSM: initialization failed") << endmsg;
812                         return -1;
813                 }
814
815         } else  {
816                 
817                 if (brand_new_user) {
818                         ArdourStartup s;
819                         s.present ();
820                         main().run();
821                         s.hide ();
822                         switch (s.response ()) {
823                         case Gtk::RESPONSE_OK:
824                                 break;
825                         default:
826                                 return -1;
827                         }
828                 }
829
830                 /* go get a session */
831
832                 const bool new_session_required = (ARDOUR_COMMAND_LINE::new_session || brand_new_user);
833
834                 if (get_session_parameters (false, new_session_required, ARDOUR_COMMAND_LINE::load_template)) {
835                         return -1;
836                 }
837         }
838
839         use_config ();
840
841         goto_editor_window ();
842
843         WM::Manager::instance().show_visible ();
844
845         /* We have to do this here since goto_editor_window() ends up calling show_all() on the
846          * editor window, and we may want stuff to be hidden.
847          */
848         _status_bar_visibility.update ();
849
850         BootMessage (string_compose (_("%1 is ready for use"), PROGRAM_NAME));
851         return 0;
852 }
853
854 void
855 ARDOUR_UI::check_memory_locking ()
856 {
857 #if defined(__APPLE__) || defined(PLATFORM_WINDOWS)
858         /* OS X doesn't support mlockall(2), and so testing for memory locking capability there is pointless */
859         return;
860 #else // !__APPLE__
861
862         XMLNode* memory_warning_node = Config->instant_xml (X_("no-memory-warning"));
863
864         if (AudioEngine::instance()->is_realtime() && memory_warning_node == 0) {
865
866                 struct rlimit limits;
867                 int64_t ram;
868                 long pages, page_size;
869 #ifdef __FreeBSD__
870                 size_t pages_len=sizeof(pages);
871                 if ((page_size = getpagesize()) < 0 ||
872                                 sysctlbyname("hw.availpages", &pages, &pages_len, NULL, 0))
873 #else
874                 if ((page_size = sysconf (_SC_PAGESIZE)) < 0 ||(pages = sysconf (_SC_PHYS_PAGES)) < 0)
875 #endif
876                 {
877                         ram = 0;
878                 } else {
879                         ram = (int64_t) pages * (int64_t) page_size;
880                 }
881
882                 if (getrlimit (RLIMIT_MEMLOCK, &limits)) {
883                         return;
884                 }
885
886                 if (limits.rlim_cur != RLIM_INFINITY) {
887
888                         if (ram == 0 || ((double) limits.rlim_cur / ram) < 0.75) {
889
890                                 MessageDialog msg (
891                                         string_compose (
892                                                 _("WARNING: Your system has a limit for maximum amount of locked memory. "
893                                                   "This might cause %1 to run out of memory before your system "
894                                                   "runs out of memory. \n\n"
895                                                   "You can view the memory limit with 'ulimit -l', "
896                                                   "and it is normally controlled by %2"),
897                                                 PROGRAM_NAME, 
898 #ifdef __FreeBSD__
899                                                 X_("/etc/login.conf")
900 #else
901                                                 X_(" /etc/security/limits.conf")
902 #endif
903                                         ).c_str());
904
905                                 msg.set_default_response (RESPONSE_OK);
906
907                                 VBox* vbox = msg.get_vbox();
908                                 HBox hbox;
909                                 CheckButton cb (_("Do not show this window again"));
910                                 hbox.pack_start (cb, true, false);
911                                 vbox->pack_start (hbox);
912                                 cb.show();
913                                 vbox->show();
914                                 hbox.show ();
915
916                                 pop_back_splash (msg);
917
918                                 editor->ensure_float (msg);
919                                 msg.run ();
920
921                                 if (cb.get_active()) {
922                                         XMLNode node (X_("no-memory-warning"));
923                                         Config->add_instant_xml (node);
924                                 }
925                         }
926                 }
927         }
928 #endif // !__APPLE__
929 }
930
931
932 void
933 ARDOUR_UI::queue_finish ()
934 {
935         Glib::signal_idle().connect (mem_fun (*this, &ARDOUR_UI::idle_finish));
936 }
937
938 bool
939 ARDOUR_UI::idle_finish ()
940 {
941         finish ();
942         return false; /* do not call again */
943 }
944
945 void
946 ARDOUR_UI::finish()
947 {
948         if (_session) {
949                 ARDOUR_UI::instance()->video_timeline->sync_session_state();
950
951                 if (_session->dirty()) {
952                         vector<string> actions;
953                         actions.push_back (_("Don't quit"));
954                         actions.push_back (_("Just quit"));
955                         actions.push_back (_("Save and quit"));
956                         switch (ask_about_saving_session(actions)) {
957                         case -1:
958                                 return;
959                                 break;
960                         case 1:
961                                 /* use the default name */
962                                 if (save_state_canfail ("")) {
963                                         /* failed - don't quit */
964                                         MessageDialog msg (*editor,
965                                                            string_compose (_("\
966 %1 was unable to save your session.\n\n\
967 If you still wish to quit, please use the\n\n\
968 \"Just quit\" option."), PROGRAM_NAME));
969                                         pop_back_splash(msg);
970                                         msg.run ();
971                                         return;
972                                 }
973                                 break;
974                         case 0:
975                                 break;
976                         }
977                 }
978
979                 second_connection.disconnect ();
980                 point_one_second_connection.disconnect ();
981                 point_zero_something_second_connection.disconnect();
982         }
983
984         delete ARDOUR_UI::instance()->video_timeline;
985         ARDOUR_UI::instance()->video_timeline = NULL;
986         stop_video_server();
987
988         /* Save state before deleting the session, as that causes some
989            windows to be destroyed before their visible state can be
990            saved.
991         */
992         save_ardour_state ();
993
994         close_all_dialogs ();
995
996         loading_message (string_compose (_("Please wait while %1 cleans up..."), PROGRAM_NAME));
997
998         if (_session) {
999                 // _session->set_deletion_in_progress ();
1000                 _session->set_clean ();
1001                 _session->remove_pending_capture_state ();
1002                 delete _session;
1003                 _session = 0;
1004         }
1005
1006         halt_connection.disconnect ();
1007         AudioEngine::instance()->stop ();
1008         quit ();
1009 }
1010
1011 int
1012 ARDOUR_UI::ask_about_saving_session (const vector<string>& actions)
1013 {
1014         ArdourDialog window (_("Unsaved Session"));
1015         Gtk::HBox dhbox;  // the hbox for the image and text
1016         Gtk::Label  prompt_label;
1017         Gtk::Image* dimage = manage (new Gtk::Image(Stock::DIALOG_WARNING,  Gtk::ICON_SIZE_DIALOG));
1018
1019         string msg;
1020
1021         assert (actions.size() >= 3);
1022
1023         window.add_button (actions[0], RESPONSE_REJECT);
1024         window.add_button (actions[1], RESPONSE_APPLY);
1025         window.add_button (actions[2], RESPONSE_ACCEPT);
1026
1027         window.set_default_response (RESPONSE_ACCEPT);
1028
1029         Gtk::Button noquit_button (msg);
1030         noquit_button.set_name ("EditorGTKButton");
1031
1032         string prompt;
1033
1034         if (_session->snap_name() == _session->name()) {
1035                 prompt = string_compose(_("The session \"%1\"\nhas not been saved.\n\nAny changes made this time\nwill be lost unless you save it.\n\nWhat do you want to do?"),
1036                                         _session->snap_name());
1037         } else {
1038                 prompt = string_compose(_("The snapshot \"%1\"\nhas not been saved.\n\nAny changes made this time\nwill be lost unless you save it.\n\nWhat do you want to do?"),
1039                                         _session->snap_name());
1040         }
1041
1042         prompt_label.set_text (prompt);
1043         prompt_label.set_name (X_("PrompterLabel"));
1044         prompt_label.set_alignment(ALIGN_LEFT, ALIGN_TOP);
1045
1046         dimage->set_alignment(ALIGN_CENTER, ALIGN_TOP);
1047         dhbox.set_homogeneous (false);
1048         dhbox.pack_start (*dimage, false, false, 5);
1049         dhbox.pack_start (prompt_label, true, false, 5);
1050         window.get_vbox()->pack_start (dhbox);
1051
1052         window.set_name (_("Prompter"));
1053         window.set_modal (true);
1054         window.set_resizable (false);
1055
1056         dhbox.show();
1057         prompt_label.show();
1058         dimage->show();
1059         window.show();
1060         window.set_keep_above (true);
1061         window.present ();
1062
1063         ResponseType r = (ResponseType) window.run();
1064
1065         window.hide ();
1066
1067         switch (r) {
1068         case RESPONSE_ACCEPT: // save and get out of here
1069                 return 1;
1070         case RESPONSE_APPLY:  // get out of here
1071                 return 0;
1072         default:
1073                 break;
1074         }
1075
1076         return -1;
1077 }
1078
1079
1080 gint
1081 ARDOUR_UI::every_second ()
1082 {
1083         update_cpu_load ();
1084         update_buffer_load ();
1085         update_disk_space ();
1086         update_timecode_format ();
1087
1088         if (nsm && nsm->is_active ()) {
1089                 nsm->check ();
1090
1091                 if (!_was_dirty && _session->dirty ()) {
1092                         nsm->is_dirty ();
1093                         _was_dirty = true;
1094                 }
1095                 else if (_was_dirty && !_session->dirty ()){
1096                         nsm->is_clean ();
1097                         _was_dirty = false;
1098                 }
1099         }
1100         return TRUE;
1101 }
1102
1103 gint
1104 ARDOUR_UI::every_point_one_seconds ()
1105 {
1106         shuttle_box->update_speed_display ();
1107         RapidScreenUpdate(); /* EMIT_SIGNAL */
1108         return TRUE;
1109 }
1110
1111 gint
1112 ARDOUR_UI::every_point_zero_something_seconds ()
1113 {
1114         // august 2007: actual update frequency: 25Hz (40ms), not 100Hz
1115
1116         SuperRapidScreenUpdate(); /* EMIT_SIGNAL */
1117         if (editor_meter && Config->get_show_editor_meter()) {
1118                 float mpeak = editor_meter->update_meters();
1119                 if (mpeak > editor_meter_max_peak) {
1120                         if (mpeak >= Config->get_meter_peak()) {
1121                                 editor_meter_peak_display.set_name ("meterbridge peakindicator on");
1122                                 editor_meter_peak_display.set_elements((ArdourButton::Element) (ArdourButton::Edge|ArdourButton::Body));
1123                         }
1124                 }
1125         }
1126         return TRUE;
1127 }
1128
1129 void
1130 ARDOUR_UI::update_sample_rate (framecnt_t)
1131 {
1132         char buf[64];
1133
1134         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::update_sample_rate, ignored)
1135
1136         if (!AudioEngine::instance()->connected()) {
1137
1138                 snprintf (buf, sizeof (buf), _("Audio: <span foreground=\"red\">none</span>"));
1139
1140         } else {
1141
1142                 framecnt_t rate = AudioEngine::instance()->sample_rate();
1143
1144                 if (rate == 0) {
1145                         /* no sample rate available */
1146                         snprintf (buf, sizeof (buf), _("Audio: <span foreground=\"red\">none</span>"));
1147                 } else {
1148
1149                         if (fmod (rate, 1000.0) != 0.0) {
1150                                 snprintf (buf, sizeof (buf), _("Audio: <span foreground=\"green\">%.1f kHz / %4.1f ms</span>"),
1151                                           (float) rate / 1000.0f,
1152                                           (AudioEngine::instance()->usecs_per_cycle() / 1000.0f));
1153                         } else {
1154                                 snprintf (buf, sizeof (buf), _("Audio: <span foreground=\"green\">%" PRId64 " kHz / %4.1f ms</span>"),
1155                                           rate/1000,
1156                                           (AudioEngine::instance()->usecs_per_cycle() / 1000.0f));
1157                         }
1158                 }
1159         }
1160         sample_rate_label.set_markup (buf);
1161 }
1162
1163 void
1164 ARDOUR_UI::update_format ()
1165 {
1166         if (!_session) {
1167                 format_label.set_text ("");
1168                 return;
1169         }
1170
1171         stringstream s;
1172         s << _("File:") << X_(" <span foreground=\"green\">");
1173
1174         switch (_session->config.get_native_file_header_format ()) {
1175         case BWF:
1176                 s << _("BWF");
1177                 break;
1178         case WAVE:
1179                 s << _("WAV");
1180                 break;
1181         case WAVE64:
1182                 s << _("WAV64");
1183                 break;
1184         case CAF:
1185                 s << _("CAF");
1186                 break;
1187         case AIFF:
1188                 s << _("AIFF");
1189                 break;
1190         case iXML:
1191                 s << _("iXML");
1192                 break;
1193         case RF64:
1194                 s << _("RF64");
1195                 break;
1196         }
1197
1198         s << " ";
1199         
1200         switch (_session->config.get_native_file_data_format ()) {
1201         case FormatFloat:
1202                 s << _("32-float");
1203                 break;
1204         case FormatInt24:
1205                 s << _("24-int");
1206                 break;
1207         case FormatInt16:
1208                 s << _("16-int");
1209                 break;
1210         }
1211
1212         s << X_("</span>");
1213
1214         format_label.set_markup (s.str ());
1215 }
1216
1217 void
1218 ARDOUR_UI::update_cpu_load ()
1219 {
1220         char buf[64];
1221
1222         /* If this text is changed, the set_size_request_to_display_given_text call in ARDOUR_UI::resize_text_widgets
1223            should also be changed.
1224         */
1225
1226         float const c = AudioEngine::instance()->get_dsp_load ();
1227         snprintf (buf, sizeof (buf), _("DSP: <span foreground=\"%s\">%5.1f%%</span>"), c >= 90 ? X_("red") : X_("green"), c);
1228         cpu_load_label.set_markup (buf);
1229 }
1230
1231 void
1232 ARDOUR_UI::update_buffer_load ()
1233 {
1234         char buf[256];
1235
1236         uint32_t const playback = _session ? _session->playback_load () : 100;
1237         uint32_t const capture = _session ? _session->capture_load () : 100;
1238
1239         /* If this text is changed, the set_size_request_to_display_given_text call in ARDOUR_UI::resize_text_widgets
1240            should also be changed.
1241         */
1242         
1243         if (_session) {
1244                 snprintf (
1245                         buf, sizeof (buf),
1246                         _("Buffers: <span foreground=\"green\">p:</span><span foreground=\"%s\">%" PRIu32 "%%</span> "
1247                                    "<span foreground=\"green\">c:</span><span foreground=\"%s\">%" PRIu32 "%%</span>"),
1248                         playback <= 5 ? X_("red") : X_("green"),
1249                         playback,
1250                         capture <= 5 ? X_("red") : X_("green"),
1251                         capture
1252                         );
1253
1254                 buffer_load_label.set_markup (buf);
1255         } else {
1256                 buffer_load_label.set_text ("");
1257         }
1258 }
1259
1260 void
1261 ARDOUR_UI::count_recenabled_streams (Route& route)
1262 {
1263         Track* track = dynamic_cast<Track*>(&route);
1264         if (track && track->record_enabled()) {
1265                 rec_enabled_streams += track->n_inputs().n_total();
1266         }
1267 }
1268
1269 void
1270 ARDOUR_UI::update_disk_space()
1271 {
1272         if (_session == 0) {
1273                 return;
1274         }
1275
1276         boost::optional<framecnt_t> opt_frames = _session->available_capture_duration();
1277         char buf[64];
1278         framecnt_t fr = _session->frame_rate();
1279
1280         if (fr == 0) {
1281                 /* skip update - no SR available */
1282                 return;
1283         }
1284
1285         if (!opt_frames) {
1286                 /* Available space is unknown */
1287                 snprintf (buf, sizeof (buf), "%s", _("Disk: <span foreground=\"green\">Unknown</span>"));
1288         } else if (opt_frames.get_value_or (0) == max_framecnt) {
1289                 snprintf (buf, sizeof (buf), "%s", _("Disk: <span foreground=\"green\">24hrs+</span>"));
1290         } else {
1291                 rec_enabled_streams = 0;
1292                 _session->foreach_route (this, &ARDOUR_UI::count_recenabled_streams);
1293
1294                 framecnt_t frames = opt_frames.get_value_or (0);
1295
1296                 if (rec_enabled_streams) {
1297                         frames /= rec_enabled_streams;
1298                 }
1299
1300                 int hrs;
1301                 int mins;
1302                 int secs;
1303
1304                 hrs  = frames / (fr * 3600);
1305
1306                 if (hrs > 24) {
1307                         snprintf (buf, sizeof (buf), "%s", _("Disk: <span foreground=\"green\">&gt;24 hrs</span>"));
1308                 } else {
1309                         frames -= hrs * fr * 3600;
1310                         mins = frames / (fr * 60);
1311                         frames -= mins * fr * 60;
1312                         secs = frames / fr;
1313                         
1314                         bool const low = (hrs == 0 && mins <= 30);
1315                         
1316                         snprintf (
1317                                 buf, sizeof(buf),
1318                                 _("Disk: <span foreground=\"%s\">%02dh:%02dm:%02ds</span>"),
1319                                 low ? X_("red") : X_("green"),
1320                                 hrs, mins, secs
1321                                 );
1322                 }
1323         }
1324
1325         disk_space_label.set_markup (buf);
1326 }
1327
1328 void
1329 ARDOUR_UI::update_timecode_format ()
1330 {
1331         char buf[64];
1332
1333         if (_session) {
1334                 bool matching;
1335                 TimecodeSlave* tcslave;
1336                 SyncSource sync_src = Config->get_sync_source();
1337
1338                 if ((sync_src == LTC || sync_src == MTC) && (tcslave = dynamic_cast<TimecodeSlave*>(_session->slave())) != 0) {
1339                         matching = (tcslave->apparent_timecode_format() == _session->config.get_timecode_format());
1340                 } else {
1341                         matching = true;
1342                 }
1343                         
1344                 snprintf (buf, sizeof (buf), S_("Timecode|TC: <span foreground=\"%s\">%s</span>"),
1345                           matching ? X_("green") : X_("red"),
1346                           Timecode::timecode_format_name (_session->config.get_timecode_format()).c_str());
1347         } else {
1348                 snprintf (buf, sizeof (buf), "TC: n/a");
1349         }
1350
1351         timecode_format_label.set_markup (buf);
1352 }       
1353
1354 gint
1355 ARDOUR_UI::update_wall_clock ()
1356 {
1357         time_t now;
1358         struct tm *tm_now;
1359         static int last_min = -1;
1360
1361         time (&now);
1362         tm_now = localtime (&now);
1363         if (last_min != tm_now->tm_min) {
1364                 char buf[16];
1365                 sprintf (buf, "%02d:%02d", tm_now->tm_hour, tm_now->tm_min);
1366                 wall_clock_label.set_text (buf);
1367                 last_min = tm_now->tm_min;
1368         }
1369
1370         return TRUE;
1371 }
1372
1373 void
1374 ARDOUR_UI::redisplay_recent_sessions ()
1375 {
1376         std::vector<std::string> session_directories;
1377         RecentSessionsSorter cmp;
1378
1379         recent_session_display.set_model (Glib::RefPtr<TreeModel>(0));
1380         recent_session_model->clear ();
1381
1382         ARDOUR::RecentSessions rs;
1383         ARDOUR::read_recent_sessions (rs);
1384
1385         if (rs.empty()) {
1386                 recent_session_display.set_model (recent_session_model);
1387                 return;
1388         }
1389
1390         // sort them alphabetically
1391         sort (rs.begin(), rs.end(), cmp);
1392
1393         for (ARDOUR::RecentSessions::iterator i = rs.begin(); i != rs.end(); ++i) {
1394                 session_directories.push_back ((*i).second);
1395         }
1396
1397         for (vector<std::string>::const_iterator i = session_directories.begin();
1398                         i != session_directories.end(); ++i)
1399         {
1400                 std::vector<std::string> state_file_paths;
1401
1402                 // now get available states for this session
1403
1404                 get_state_files_in_directory (*i, state_file_paths);
1405
1406                 vector<string*>* states;
1407                 vector<const gchar*> item;
1408                 string fullpath = *i;
1409
1410                 /* remove any trailing / */
1411
1412                 if (fullpath[fullpath.length() - 1] == '/') {
1413                         fullpath = fullpath.substr (0, fullpath.length() - 1);
1414                 }
1415
1416                 /* check whether session still exists */
1417                 if (!Glib::file_test(fullpath.c_str(), Glib::FILE_TEST_EXISTS)) {
1418                         /* session doesn't exist */
1419                         continue;
1420                 }
1421
1422                 /* now get available states for this session */
1423
1424                 if ((states = Session::possible_states (fullpath)) == 0) {
1425                         /* no state file? */
1426                         continue;
1427                 }
1428
1429                 std::vector<string> state_file_names(get_file_names_no_extension (state_file_paths));
1430
1431                 Gtk::TreeModel::Row row = *(recent_session_model->append());
1432
1433                 row[recent_session_columns.visible_name] = Glib::path_get_basename (fullpath);
1434                 row[recent_session_columns.fullpath] = fullpath;
1435                 row[recent_session_columns.tip] = Glib::Markup::escape_text (fullpath);
1436
1437                 if (state_file_names.size() > 1) {
1438
1439                         // add the children
1440
1441                         for (std::vector<std::string>::iterator i2 = state_file_names.begin();
1442                                         i2 != state_file_names.end(); ++i2)
1443                         {
1444
1445                                 Gtk::TreeModel::Row child_row = *(recent_session_model->append (row.children()));
1446
1447                                 child_row[recent_session_columns.visible_name] = *i2;
1448                                 child_row[recent_session_columns.fullpath] = fullpath;
1449                                 child_row[recent_session_columns.tip] = Glib::Markup::escape_text (fullpath);
1450                         }
1451                 }
1452         }
1453
1454         recent_session_display.set_tooltip_column(1); // recent_session_columns.tip
1455         recent_session_display.set_model (recent_session_model);
1456 }
1457
1458 void
1459 ARDOUR_UI::build_session_selector ()
1460 {
1461         session_selector_window = new ArdourDialog (_("Recent Sessions"));
1462
1463         Gtk::ScrolledWindow *scroller = manage (new Gtk::ScrolledWindow);
1464
1465         session_selector_window->add_button (Stock::CANCEL, RESPONSE_CANCEL);
1466         session_selector_window->add_button (Stock::OPEN, RESPONSE_ACCEPT);
1467         session_selector_window->set_default_response (RESPONSE_ACCEPT);
1468         recent_session_model = TreeStore::create (recent_session_columns);
1469         recent_session_display.set_model (recent_session_model);
1470         recent_session_display.append_column (_("Recent Sessions"), recent_session_columns.visible_name);
1471         recent_session_display.set_headers_visible (false);
1472         recent_session_display.get_selection()->set_mode (SELECTION_BROWSE);
1473         recent_session_display.signal_row_activated().connect (sigc::mem_fun (*this, &ARDOUR_UI::recent_session_row_activated));
1474
1475         scroller->add (recent_session_display);
1476         scroller->set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
1477
1478         session_selector_window->set_name ("SessionSelectorWindow");
1479         session_selector_window->set_size_request (200, 400);
1480         session_selector_window->get_vbox()->pack_start (*scroller);
1481
1482         recent_session_display.show();
1483         scroller->show();
1484 }
1485
1486 void
1487 ARDOUR_UI::recent_session_row_activated (const TreePath& /*path*/, TreeViewColumn* /*col*/)
1488 {
1489         session_selector_window->response (RESPONSE_ACCEPT);
1490 }
1491
1492 void
1493 ARDOUR_UI::open_recent_session ()
1494 {
1495         bool can_return = (_session != 0);
1496
1497         if (session_selector_window == 0) {
1498                 build_session_selector ();
1499         }
1500
1501         redisplay_recent_sessions ();
1502
1503         while (true) {
1504
1505                 ResponseType r = (ResponseType) session_selector_window->run ();
1506
1507                 switch (r) {
1508                 case RESPONSE_ACCEPT:
1509                         break;
1510                 default:
1511                         if (can_return) {
1512                                 session_selector_window->hide();
1513                                 return;
1514                         } else {
1515                                 exit (1);
1516                         }
1517                 }
1518
1519                 if (recent_session_display.get_selection()->count_selected_rows() == 0) {
1520                         continue;
1521                 }
1522
1523                 session_selector_window->hide();
1524
1525                 Gtk::TreeModel::iterator i = recent_session_display.get_selection()->get_selected();
1526
1527                 if (i == recent_session_model->children().end()) {
1528                         return;
1529                 }
1530
1531                 std::string path = (*i)[recent_session_columns.fullpath];
1532                 std::string state = (*i)[recent_session_columns.visible_name];
1533
1534                 _session_is_new = false;
1535
1536                 if (load_session (path, state) == 0) {
1537                         break;
1538                 }
1539
1540                 can_return = false;
1541         }
1542 }
1543
1544 bool
1545 ARDOUR_UI::check_audioengine ()
1546 {
1547         if (!AudioEngine::instance()->connected()) {
1548                 MessageDialog msg (string_compose (
1549                                            _("%1 is not connected to any audio backend.\n"
1550                                              "You cannot open or close sessions in this condition"),
1551                                            PROGRAM_NAME));
1552                 pop_back_splash (msg);
1553                 msg.run ();
1554                 return false;
1555         }
1556         return true;
1557 }
1558
1559 void
1560 ARDOUR_UI::open_session ()
1561 {
1562         if (!check_audioengine()) {
1563                 return;
1564
1565         }
1566
1567         /* popup selector window */
1568
1569         if (open_session_selector == 0) {
1570
1571                 /* ardour sessions are folders */
1572
1573                 open_session_selector = new Gtk::FileChooserDialog (_("Open Session"), FILE_CHOOSER_ACTION_OPEN);
1574                 open_session_selector->add_button (Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
1575                 open_session_selector->add_button (Gtk::Stock::OPEN, Gtk::RESPONSE_ACCEPT);
1576                 open_session_selector->set_default_response(Gtk::RESPONSE_ACCEPT);
1577                 
1578                 if (_session) {
1579                         string session_parent_dir = Glib::path_get_dirname(_session->path());
1580                         string::size_type last_dir_sep = session_parent_dir.rfind(G_DIR_SEPARATOR);
1581                         session_parent_dir = session_parent_dir.substr(0, last_dir_sep);
1582                         open_session_selector->set_current_folder(session_parent_dir);
1583                 } else {
1584                         open_session_selector->set_current_folder(Config->get_default_session_parent_dir());
1585                 }
1586
1587                 string default_session_folder = Config->get_default_session_parent_dir();
1588                 try {
1589                         /* add_shortcut_folder throws an exception if the folder being added already has a shortcut */
1590                         open_session_selector->add_shortcut_folder (default_session_folder);
1591                 }
1592                 catch (Glib::Error & e) {
1593                         std::cerr << "open_session_selector->add_shortcut_folder (" << default_session_folder << ") threw Glib::Error " << e.what() << std::endl;
1594                 }
1595
1596                 FileFilter session_filter;
1597                 session_filter.add_pattern ("*.ardour");
1598                 session_filter.set_name (string_compose (_("%1 sessions"), PROGRAM_NAME));
1599                 open_session_selector->add_filter (session_filter);
1600                 open_session_selector->set_filter (session_filter);
1601         }
1602
1603         int response = open_session_selector->run();
1604         open_session_selector->hide ();
1605
1606         switch (response) {
1607         case RESPONSE_ACCEPT:
1608                 break;
1609         default:
1610                 open_session_selector->hide();
1611                 return;
1612         }
1613
1614         open_session_selector->hide();
1615         string session_path = open_session_selector->get_filename();
1616         string path, name;
1617         bool isnew;
1618
1619         if (session_path.length() > 0) {
1620                 if (ARDOUR::find_session (session_path, path, name, isnew) == 0) {
1621                         _session_is_new = isnew;
1622                         load_session (path, name);
1623                 }
1624         }
1625 }
1626
1627
1628 void
1629 ARDOUR_UI::session_add_mixed_track (const ChanCount& input, const ChanCount& output, RouteGroup* route_group, 
1630                                     uint32_t how_many, const string& name_template, PluginInfoPtr instrument)
1631 {
1632         list<boost::shared_ptr<MidiTrack> > tracks;
1633
1634         if (_session == 0) {
1635                 warning << _("You cannot add a track without a session already loaded.") << endmsg;
1636                 return;
1637         }
1638
1639         try {
1640                 tracks = _session->new_midi_track (input, output, instrument, ARDOUR::Normal, route_group, how_many, name_template);
1641                 
1642                 if (tracks.size() != how_many) {
1643                         error << string_compose(P_("could not create %1 new mixed track", "could not create %1 new mixed tracks", how_many), how_many) << endmsg;
1644                 }
1645         }
1646
1647         catch (...) {
1648                 MessageDialog msg (*editor,
1649                                    string_compose (_("There are insufficient JACK ports available\n\
1650 to create a new track or bus.\n\
1651 You should save %1, exit and\n\
1652 restart JACK with more ports."), PROGRAM_NAME));
1653                 msg.run ();
1654         }
1655 }
1656         
1657
1658 void
1659 ARDOUR_UI::session_add_midi_route (bool disk, RouteGroup* route_group, uint32_t how_many, const string& name_template, PluginInfoPtr instrument)
1660 {
1661         ChanCount one_midi_channel;
1662         one_midi_channel.set (DataType::MIDI, 1);
1663
1664         if (disk) {
1665                 session_add_mixed_track (one_midi_channel, one_midi_channel, route_group, how_many, name_template, instrument);
1666         }
1667 }
1668
1669 void
1670 ARDOUR_UI::session_add_audio_route (
1671         bool track,
1672         int32_t input_channels,
1673         int32_t output_channels,
1674         ARDOUR::TrackMode mode,
1675         RouteGroup* route_group,
1676         uint32_t how_many,
1677         string const & name_template
1678         )
1679 {
1680         list<boost::shared_ptr<AudioTrack> > tracks;
1681         RouteList routes;
1682
1683         if (_session == 0) {
1684                 warning << _("You cannot add a track or bus without a session already loaded.") << endmsg;
1685                 return;
1686         }
1687
1688         try {
1689                 if (track) {
1690                         tracks = _session->new_audio_track (input_channels, output_channels, mode, route_group, how_many, name_template);
1691
1692                         if (tracks.size() != how_many) {
1693                                 error << string_compose (P_("could not create %1 new audio track", "could not create %1 new audio tracks", how_many), how_many) 
1694                                       << endmsg;
1695                         }
1696
1697                 } else {
1698
1699                         routes = _session->new_audio_route (input_channels, output_channels, route_group, how_many, name_template);
1700
1701                         if (routes.size() != how_many) {
1702                                 error << string_compose (P_("could not create %1 new audio bus", "could not create %1 new audio busses", how_many), how_many)
1703                                       << endmsg;
1704                         }
1705                 }
1706         }
1707
1708         catch (...) {
1709                 MessageDialog msg (*editor,
1710                                    string_compose (_("There are insufficient JACK ports available\n\
1711 to create a new track or bus.\n\
1712 You should save %1, exit and\n\
1713 restart JACK with more ports."), PROGRAM_NAME));
1714                 pop_back_splash (msg);
1715                 msg.run ();
1716         }
1717 }
1718
1719 void
1720 ARDOUR_UI::transport_goto_start ()
1721 {
1722         if (_session) {
1723                 _session->goto_start();
1724
1725                 /* force displayed area in editor to start no matter
1726                    what "follow playhead" setting is.
1727                 */
1728
1729                 if (editor) {
1730                         editor->center_screen (_session->current_start_frame ());
1731                 }
1732         }
1733 }
1734
1735 void
1736 ARDOUR_UI::transport_goto_zero ()
1737 {
1738         if (_session) {
1739                 _session->request_locate (0);
1740
1741                 /* force displayed area in editor to start no matter
1742                    what "follow playhead" setting is.
1743                 */
1744
1745                 if (editor) {
1746                         editor->reset_x_origin (0);
1747                 }
1748         }
1749 }
1750
1751 void
1752 ARDOUR_UI::transport_goto_wallclock ()
1753 {
1754         if (_session && editor) {
1755
1756                 time_t now;
1757                 struct tm tmnow;
1758                 framepos_t frames;
1759
1760                 time (&now);
1761                 localtime_r (&now, &tmnow);
1762                 
1763                 int frame_rate = _session->frame_rate();
1764                 
1765                 if (frame_rate == 0) {
1766                         /* no frame rate available */
1767                         return;
1768                 }
1769
1770                 frames = tmnow.tm_hour * (60 * 60 * frame_rate);
1771                 frames += tmnow.tm_min * (60 * frame_rate);
1772                 frames += tmnow.tm_sec * frame_rate;
1773
1774                 _session->request_locate (frames, _session->transport_rolling ());
1775
1776                 /* force displayed area in editor to start no matter
1777                    what "follow playhead" setting is.
1778                 */
1779
1780                 if (editor) {
1781                         editor->center_screen (frames);
1782                 }
1783         }
1784 }
1785
1786 void
1787 ARDOUR_UI::transport_goto_end ()
1788 {
1789         if (_session) {
1790                 framepos_t const frame = _session->current_end_frame();
1791                 _session->request_locate (frame);
1792
1793                 /* force displayed area in editor to start no matter
1794                    what "follow playhead" setting is.
1795                 */
1796
1797                 if (editor) {
1798                         editor->center_screen (frame);
1799                 }
1800         }
1801 }
1802
1803 void
1804 ARDOUR_UI::transport_stop ()
1805 {
1806         if (!_session) {
1807                 return;
1808         }
1809
1810         if (_session->is_auditioning()) {
1811                 _session->cancel_audition ();
1812                 return;
1813         }
1814
1815         _session->request_stop (false, true);
1816 }
1817
1818 void
1819 ARDOUR_UI::transport_record (bool roll)
1820 {
1821
1822         if (_session) {
1823                 switch (_session->record_status()) {
1824                 case Session::Disabled:
1825                         if (_session->ntracks() == 0) {
1826                                 MessageDialog msg (*editor, _("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."));
1827                                 msg.run ();
1828                                 return;
1829                         }
1830                         _session->maybe_enable_record ();
1831                         if (roll) {
1832                                 transport_roll ();
1833                         }
1834                         break;
1835                 case Session::Recording:
1836                         if (roll) {
1837                                 _session->request_stop();
1838                         } else {
1839                                 _session->disable_record (false, true);
1840                         }
1841                         break;
1842
1843                 case Session::Enabled:
1844                         _session->disable_record (false, true);
1845                 }
1846         }
1847 }
1848
1849 void
1850 ARDOUR_UI::transport_roll ()
1851 {
1852         if (!_session) {
1853                 return;
1854         }
1855
1856         if (_session->is_auditioning()) {
1857                 return;
1858         }
1859
1860 #if 0
1861         if (_session->config.get_external_sync()) {
1862                 switch (Config->get_sync_source()) {
1863                 case Engine:
1864                         break;
1865                 default:
1866                         /* transport controlled by the master */
1867                         return;
1868                 }
1869         }
1870 #endif
1871
1872         bool rolling = _session->transport_rolling();
1873
1874         if (_session->get_play_loop()) {
1875                 /* XXX it is not possible to just leave seamless loop and keep
1876                    playing at present (nov 4th 2009)
1877                 */
1878                 if (!Config->get_seamless_loop()) {
1879                         _session->request_play_loop (false, true);
1880                 }
1881         } else if (_session->get_play_range () && !Config->get_always_play_range()) {
1882                 /* stop playing a range if we currently are */
1883                 _session->request_play_range (0, true);
1884         }
1885
1886         if (!rolling) {
1887                 _session->request_transport_speed (1.0f);
1888         }
1889 }
1890
1891 bool
1892 ARDOUR_UI::get_smart_mode() const
1893 {
1894         return ( editor->get_smart_mode() );
1895 }
1896
1897
1898 void
1899 ARDOUR_UI::toggle_roll (bool with_abort, bool roll_out_of_bounded_mode)
1900 {
1901
1902         if (!_session) {
1903                 return;
1904         }
1905
1906         if (_session->is_auditioning()) {
1907                 _session->cancel_audition ();
1908                 return;
1909         }
1910
1911         if (_session->config.get_external_sync()) {
1912                 switch (Config->get_sync_source()) {
1913                 case Engine:
1914                         break;
1915                 default:
1916                         /* transport controlled by the master */
1917                         return;
1918                 }
1919         }
1920
1921         bool rolling = _session->transport_rolling();
1922         bool affect_transport = true;
1923
1924         if (rolling && roll_out_of_bounded_mode) {
1925                 /* drop out of loop/range playback but leave transport rolling */
1926                 if (_session->get_play_loop()) {
1927                         if (Config->get_seamless_loop()) {
1928                                 /* the disk buffers contain copies of the loop - we can't
1929                                    just keep playing, so stop the transport. the user
1930                                    can restart as they wish.
1931                                 */
1932                                 affect_transport = true;
1933                         } else {
1934                                 /* disk buffers are normal, so we can keep playing */
1935                                 affect_transport = false;
1936                         }
1937                         _session->request_play_loop (false, true);
1938                 } else if (_session->get_play_range ()) {
1939                         affect_transport = false;
1940                         _session->request_play_range (0, true);
1941                 }
1942         }
1943
1944         if (affect_transport) {
1945                 if (rolling) {
1946                         _session->request_stop (with_abort, true);
1947                 } else {
1948                         if ( Config->get_always_play_range() ) {
1949                                 _session->request_play_range (&editor->get_selection().time, true);
1950                         }
1951
1952                         _session->request_transport_speed (1.0f);
1953                 }
1954         }
1955 }
1956
1957 void
1958 ARDOUR_UI::toggle_session_auto_loop ()
1959 {
1960         Location * looploc = _session->locations()->auto_loop_location();
1961
1962         if (!_session || !looploc) {
1963                 return;
1964         }
1965
1966         if (_session->get_play_loop()) {
1967
1968                 if (_session->transport_rolling()) {
1969
1970                         _session->request_locate (looploc->start(), true);
1971                         _session->request_play_loop (false);
1972
1973                 } else {
1974                         _session->request_play_loop (false);
1975                 }
1976         } else {
1977                 _session->request_play_loop (true);
1978         }
1979         
1980         //show the loop markers
1981         looploc->set_hidden (false, this);
1982 }
1983
1984 void
1985 ARDOUR_UI::transport_play_selection ()
1986 {
1987         if (!_session) {
1988                 return;
1989         }
1990
1991         editor->play_selection ();
1992 }
1993
1994 void
1995 ARDOUR_UI::transport_play_preroll ()
1996 {
1997         if (!_session) {
1998                 return;
1999         }
2000         editor->play_with_preroll ();
2001 }
2002
2003 void
2004 ARDOUR_UI::transport_rewind (int option)
2005 {
2006         float current_transport_speed;
2007
2008         if (_session) {
2009                 current_transport_speed = _session->transport_speed();
2010
2011                 if (current_transport_speed >= 0.0f) {
2012                         switch (option) {
2013                         case 0:
2014                                 _session->request_transport_speed (-1.0f);
2015                                 break;
2016                         case 1:
2017                                 _session->request_transport_speed (-4.0f);
2018                                 break;
2019                         case -1:
2020                                 _session->request_transport_speed (-0.5f);
2021                                 break;
2022                         }
2023                 } else {
2024                         /* speed up */
2025                         _session->request_transport_speed (current_transport_speed * 1.5f);
2026                 }
2027         }
2028 }
2029
2030 void
2031 ARDOUR_UI::transport_forward (int option)
2032 {
2033         if (!_session) {
2034                 return;
2035         }
2036         
2037         float current_transport_speed = _session->transport_speed();
2038         
2039         if (current_transport_speed <= 0.0f) {
2040                 switch (option) {
2041                 case 0:
2042                         _session->request_transport_speed (1.0f);
2043                         break;
2044                 case 1:
2045                         _session->request_transport_speed (4.0f);
2046                         break;
2047                 case -1:
2048                         _session->request_transport_speed (0.5f);
2049                         break;
2050                 }
2051         } else {
2052                 /* speed up */
2053                 _session->request_transport_speed (current_transport_speed * 1.5f);
2054         }
2055 }
2056
2057 void
2058 ARDOUR_UI::toggle_record_enable (uint32_t rid)
2059 {
2060         if (!_session) {
2061                 return;
2062         }
2063
2064         boost::shared_ptr<Route> r;
2065
2066         if ((r = _session->route_by_remote_id (rid)) != 0) {
2067
2068                 Track* t;
2069
2070                 if ((t = dynamic_cast<Track*>(r.get())) != 0) {
2071                         t->set_record_enabled (!t->record_enabled(), this);
2072                 }
2073         }
2074 }
2075
2076 void
2077 ARDOUR_UI::map_transport_state ()
2078 {
2079         if (!_session) {
2080                 auto_loop_button.unset_active_state ();
2081                 play_selection_button.unset_active_state ();
2082                 roll_button.unset_active_state ();
2083                 stop_button.set_active_state (Gtkmm2ext::ExplicitActive);
2084                 return;
2085         }
2086
2087         shuttle_box->map_transport_state ();
2088
2089         float sp = _session->transport_speed();
2090
2091         if (sp != 0.0f) {
2092
2093                 /* we're rolling */
2094
2095                 if (_session->get_play_range()) {
2096
2097                         play_selection_button.set_active_state (Gtkmm2ext::ExplicitActive);
2098                         roll_button.unset_active_state ();
2099                         auto_loop_button.unset_active_state ();
2100
2101                 } else if (_session->get_play_loop ()) {
2102
2103                         auto_loop_button.set_active (true);
2104                         play_selection_button.set_active (false);
2105                         roll_button.set_active (false);
2106
2107                 } else {
2108
2109                         roll_button.set_active (true);
2110                         play_selection_button.set_active (false);
2111                         auto_loop_button.set_active (false);
2112                 }
2113
2114                 if (Config->get_always_play_range()) {
2115                         /* light up both roll and play-selection if they are joined */
2116                         roll_button.set_active (true);
2117                         play_selection_button.set_active (true);
2118                 }
2119
2120                 stop_button.set_active (false);
2121
2122         } else {
2123
2124                 stop_button.set_active (true);
2125                 roll_button.set_active (false);
2126                 play_selection_button.set_active (false);
2127                 auto_loop_button.set_active (false);
2128                 update_disk_space ();
2129         }
2130 }
2131
2132 void
2133 ARDOUR_UI::update_clocks ()
2134 {
2135         if (!editor || !editor->dragging_playhead()) {
2136                 Clock (_session->audible_frame(), false, editor->get_preferred_edit_position()); /* EMIT_SIGNAL */
2137         }
2138 }
2139
2140 void
2141 ARDOUR_UI::start_clocking ()
2142 {
2143         if (Config->get_super_rapid_clock_update()) {
2144                 clock_signal_connection = SuperRapidScreenUpdate.connect (sigc::mem_fun(*this, &ARDOUR_UI::update_clocks));
2145         } else {
2146                 clock_signal_connection = RapidScreenUpdate.connect (sigc::mem_fun(*this, &ARDOUR_UI::update_clocks));
2147         }
2148 }
2149
2150 void
2151 ARDOUR_UI::stop_clocking ()
2152 {
2153         clock_signal_connection.disconnect ();
2154 }
2155
2156 gint
2157 ARDOUR_UI::_blink (void *arg)
2158 {
2159         ((ARDOUR_UI *) arg)->blink ();
2160         return TRUE;
2161 }
2162
2163 void
2164 ARDOUR_UI::blink ()
2165 {
2166         Blink (blink_on = !blink_on); /* EMIT_SIGNAL */
2167 }
2168
2169 void
2170 ARDOUR_UI::start_blinking ()
2171 {
2172         /* Start the blink signal. Everybody with a blinking widget
2173            uses Blink to drive the widget's state.
2174         */
2175
2176         if (blink_timeout_tag < 0) {
2177                 blink_on = false;
2178                 blink_timeout_tag = g_timeout_add (240, _blink, this);
2179         }
2180 }
2181
2182 void
2183 ARDOUR_UI::stop_blinking ()
2184 {
2185         if (blink_timeout_tag >= 0) {
2186                 g_source_remove (blink_timeout_tag);
2187                 blink_timeout_tag = -1;
2188         }
2189 }
2190
2191
2192 /** Ask the user for the name of a new snapshot and then take it.
2193  */
2194
2195 void
2196 ARDOUR_UI::snapshot_session (bool switch_to_it)
2197 {
2198         ArdourPrompter prompter (true);
2199         string snapname;
2200
2201         prompter.set_name ("Prompter");
2202         prompter.add_button (Gtk::Stock::SAVE, Gtk::RESPONSE_ACCEPT);
2203         if (switch_to_it) {
2204                 prompter.set_title (_("Save as..."));
2205                 prompter.set_prompt (_("New session name"));
2206         } else {
2207                 prompter.set_title (_("Take Snapshot"));
2208                 prompter.set_prompt (_("Name of new snapshot"));
2209         }
2210
2211         if (!switch_to_it) {
2212                 char timebuf[128];
2213                 time_t n;
2214                 struct tm local_time;
2215
2216                 time (&n);
2217                 localtime_r (&n, &local_time);
2218                 strftime (timebuf, sizeof(timebuf), "%FT%H.%M.%S", &local_time);
2219                 prompter.set_initial_text (timebuf);
2220         }
2221
2222   again:
2223         switch (prompter.run()) {
2224         case RESPONSE_ACCEPT:
2225         {
2226                 prompter.get_result (snapname);
2227
2228                 bool do_save = (snapname.length() != 0);
2229
2230                 if (do_save) {
2231                         char illegal = Session::session_name_is_legal(snapname);
2232                         if (illegal) {
2233                                 MessageDialog msg (string_compose (_("To ensure compatibility with various systems\n"
2234                                                      "snapshot names may not contain a '%1' character"), illegal));
2235                                 msg.run ();
2236                                 goto again;
2237                         }
2238                 }
2239
2240                 vector<std::string> p;
2241                 get_state_files_in_directory (_session->session_directory().root_path(), p);
2242                 vector<string> n = get_file_names_no_extension (p);
2243                 if (find (n.begin(), n.end(), snapname) != n.end()) {
2244
2245                         ArdourDialog confirm (_("Confirm Snapshot Overwrite"), true);
2246                         Label m (_("A snapshot already exists with that name.  Do you want to overwrite it?"));
2247                         confirm.get_vbox()->pack_start (m, true, true);
2248                         confirm.add_button (Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2249                         confirm.add_button (_("Overwrite"), Gtk::RESPONSE_ACCEPT);
2250                         confirm.show_all ();
2251                         switch (confirm.run()) {
2252                         case RESPONSE_CANCEL:
2253                                 do_save = false;
2254                         }
2255                 }
2256
2257                 if (do_save) {
2258                         save_state (snapname, switch_to_it);
2259                 }
2260                 break;
2261         }
2262
2263         default:
2264                 break;
2265         }
2266 }
2267
2268 /** Ask the user for a new session name and then rename the session to it.
2269  */
2270
2271 void
2272 ARDOUR_UI::rename_session ()
2273 {
2274         if (!_session) {
2275                 return;
2276         }
2277
2278         ArdourPrompter prompter (true);
2279         string name;
2280
2281         prompter.set_name ("Prompter");
2282         prompter.add_button (Gtk::Stock::SAVE, Gtk::RESPONSE_ACCEPT);
2283         prompter.set_title (_("Rename Session"));
2284         prompter.set_prompt (_("New session name"));
2285
2286   again:
2287         switch (prompter.run()) {
2288         case RESPONSE_ACCEPT:
2289         {
2290                 prompter.get_result (name);
2291
2292                 bool do_rename = (name.length() != 0);
2293
2294                 if (do_rename) {
2295                         char illegal = Session::session_name_is_legal (name);
2296
2297                         if (illegal) {
2298                                 MessageDialog msg (string_compose (_("To ensure compatibility with various systems\n"
2299                                                                      "session names may not contain a '%1' character"), illegal));
2300                                 msg.run ();
2301                                 goto again;
2302                         }
2303
2304                         switch (_session->rename (name)) {
2305                         case -1: {
2306                                 MessageDialog msg (_("That name is already in use by another directory/folder. Please try again."));
2307                                 msg.set_position (WIN_POS_MOUSE);
2308                                 msg.run ();
2309                                 goto again;
2310                                 break;
2311                         }
2312                         case 0:
2313                                 break;
2314                         default: {
2315                                 MessageDialog msg (_("Renaming this session failed.\nThings could be seriously messed up at this point"));
2316                                 msg.set_position (WIN_POS_MOUSE);
2317                                 msg.run ();
2318                                 break;
2319                         }
2320                         }
2321                 }
2322                 
2323                 break;
2324         }
2325
2326         default:
2327                 break;
2328         }
2329 }
2330
2331 void
2332 ARDOUR_UI::save_state (const string & name, bool switch_to_it)
2333 {
2334         XMLNode* node = new XMLNode (X_("UI"));
2335
2336         WM::Manager::instance().add_state (*node);
2337
2338         node->add_child_nocopy (gui_object_state->get_state());
2339
2340         _session->add_extra_xml (*node);
2341
2342         save_state_canfail (name, switch_to_it);
2343 }
2344
2345 int
2346 ARDOUR_UI::save_state_canfail (string name, bool switch_to_it)
2347 {
2348         if (_session) {
2349                 int ret;
2350
2351                 if (name.length() == 0) {
2352                         name = _session->snap_name();
2353                 }
2354
2355                 if ((ret = _session->save_state (name, false, switch_to_it)) != 0) {
2356                         return ret;
2357                 }
2358         }
2359
2360         save_ardour_state (); /* XXX cannot fail? yeah, right ... */
2361         return 0;
2362 }
2363
2364 void
2365 ARDOUR_UI::primary_clock_value_changed ()
2366 {
2367         if (_session) {
2368                 _session->request_locate (primary_clock->current_time ());
2369         }
2370 }
2371
2372 void
2373 ARDOUR_UI::big_clock_value_changed ()
2374 {
2375         if (_session) {
2376                 _session->request_locate (big_clock->current_time ());
2377         }
2378 }
2379
2380 void
2381 ARDOUR_UI::secondary_clock_value_changed ()
2382 {
2383         if (_session) {
2384                 _session->request_locate (secondary_clock->current_time ());
2385         }
2386 }
2387
2388 void
2389 ARDOUR_UI::transport_rec_enable_blink (bool onoff)
2390 {
2391         if (_session == 0) {
2392                 return;
2393         }
2394
2395         if (_session->step_editing()) {
2396                 return;
2397         }
2398
2399         Session::RecordState const r = _session->record_status ();
2400         bool const h = _session->have_rec_enabled_track ();
2401
2402         if (r == Session::Enabled || (r == Session::Recording && !h)) {
2403                 if (onoff) {
2404                         rec_button.set_active_state (Gtkmm2ext::ExplicitActive);
2405                 } else {
2406                         rec_button.set_active_state (Gtkmm2ext::ImplicitActive);
2407                 }
2408         } else if (r == Session::Recording && h) {
2409                 rec_button.set_active_state (Gtkmm2ext::ExplicitActive);
2410         } else {
2411                 rec_button.unset_active_state ();
2412         }
2413 }
2414
2415 void
2416 ARDOUR_UI::save_template ()
2417 {
2418         ArdourPrompter prompter (true);
2419         string name;
2420
2421         if (!check_audioengine()) {
2422                 return;
2423         }
2424
2425         prompter.set_name (X_("Prompter"));
2426         prompter.set_title (_("Save Template"));
2427         prompter.set_prompt (_("Name for template:"));
2428         prompter.set_initial_text(_session->name() + _("-template"));
2429         prompter.add_button (Gtk::Stock::SAVE, Gtk::RESPONSE_ACCEPT);
2430
2431         switch (prompter.run()) {
2432         case RESPONSE_ACCEPT:
2433                 prompter.get_result (name);
2434
2435                 if (name.length()) {
2436                         _session->save_template (name);
2437                 }
2438                 break;
2439
2440         default:
2441                 break;
2442         }
2443 }
2444
2445 void
2446 ARDOUR_UI::edit_metadata ()
2447 {
2448         SessionMetadataEditor dialog;
2449         dialog.set_session (_session);
2450         editor->ensure_float (dialog);
2451         dialog.run ();
2452 }
2453
2454 void
2455 ARDOUR_UI::import_metadata ()
2456 {
2457         SessionMetadataImporter dialog;
2458         dialog.set_session (_session);
2459         editor->ensure_float (dialog);
2460         dialog.run ();
2461 }
2462
2463 bool
2464 ARDOUR_UI::ask_about_loading_existing_session (const std::string& session_path)
2465 {
2466         std::string str = string_compose (_("This session\n%1\nalready exists. Do you want to open it?"), session_path);
2467
2468         MessageDialog msg (str,
2469                            false,
2470                            Gtk::MESSAGE_WARNING,
2471                            Gtk::BUTTONS_YES_NO,
2472                            true);
2473
2474
2475         msg.set_name (X_("OpenExistingDialog"));
2476         msg.set_title (_("Open Existing Session"));
2477         msg.set_wmclass (X_("existing_session"), PROGRAM_NAME);
2478         msg.set_position (Gtk::WIN_POS_MOUSE);
2479         pop_back_splash (msg);
2480
2481         switch (msg.run()) {
2482         case RESPONSE_YES:
2483                 return true;
2484                 break;
2485         }
2486         return false;
2487 }
2488
2489 int
2490 ARDOUR_UI::build_session_from_dialog (SessionDialog& sd, const std::string& session_path, const std::string& session_name)
2491 {
2492         BusProfile bus_profile;
2493
2494         if (nsm || Profile->get_sae()) {
2495
2496                 bus_profile.master_out_channels = 2;
2497                 bus_profile.input_ac = AutoConnectPhysical;
2498                 bus_profile.output_ac = AutoConnectMaster;
2499                 bus_profile.requested_physical_in = 0; // use all available
2500                 bus_profile.requested_physical_out = 0; // use all available
2501
2502         } else {
2503
2504                 /* get settings from advanced section of NSD */
2505
2506                 if (sd.create_master_bus()) {
2507                         bus_profile.master_out_channels = (uint32_t) sd.master_channel_count();
2508                 } else {
2509                         bus_profile.master_out_channels = 0;
2510                 }
2511
2512                 if (sd.connect_inputs()) {
2513                         bus_profile.input_ac = AutoConnectPhysical;
2514                 } else {
2515                         bus_profile.input_ac = AutoConnectOption (0);
2516                 }
2517
2518                 bus_profile.output_ac = AutoConnectOption (0);
2519
2520                 if (sd.connect_outputs ()) {
2521                         if (sd.connect_outs_to_master()) {
2522                                 bus_profile.output_ac = AutoConnectMaster;
2523                         } else if (sd.connect_outs_to_physical()) {
2524                                 bus_profile.output_ac = AutoConnectPhysical;
2525                         }
2526                 }
2527
2528                 bus_profile.requested_physical_in = (uint32_t) sd.input_limit_count();
2529                 bus_profile.requested_physical_out = (uint32_t) sd.output_limit_count();
2530         }
2531
2532         if (build_session (session_path, session_name, bus_profile)) {
2533                 return -1;
2534         }
2535
2536         return 0;
2537 }
2538
2539 void
2540 ARDOUR_UI::idle_load (const std::string& path)
2541 {
2542         if (_session) {
2543                 if (Glib::file_test (path, Glib::FILE_TEST_IS_DIR)) {
2544                         /* /path/to/foo => /path/to/foo, foo */
2545                         load_session (path, basename_nosuffix (path));
2546                 } else {
2547                         /* /path/to/foo/foo.ardour => /path/to/foo, foo */
2548                         load_session (Glib::path_get_dirname (path), basename_nosuffix (path));
2549                 }
2550
2551         } else {
2552                 ARDOUR_COMMAND_LINE::session_name = path;
2553         }
2554 }
2555
2556 /** @param quit_on_cancel true if exit() should be called if the user clicks `cancel' in the new session dialog */
2557 int
2558 ARDOUR_UI::get_session_parameters (bool quit_on_cancel, bool should_be_new, string load_template)
2559 {
2560         string session_name;
2561         string session_path;
2562         string template_name;
2563         int ret = -1;
2564         bool likely_new = false;
2565         bool cancel_not_quit;
2566
2567         /* deal with any existing DIRTY session now, rather than later. don't
2568          * treat a non-dirty session this way, so that it stays visible 
2569          * as we bring up the new session dialog.
2570          */
2571
2572         if (_session && ARDOUR_UI::instance()->video_timeline) {
2573                 ARDOUR_UI::instance()->video_timeline->sync_session_state();
2574         }
2575
2576         /* if there is already a session, relabel the button
2577            on the SessionDialog so that we don't Quit directly
2578         */
2579         cancel_not_quit = (_session != 0);
2580
2581         if (_session && _session->dirty()) {
2582                 if (unload_session (false)) {
2583                         /* unload cancelled by user */
2584                         return 0;
2585                 }
2586                 ARDOUR_COMMAND_LINE::session_name = "";
2587         }
2588
2589         if (!load_template.empty()) {
2590                 should_be_new = true;
2591                 template_name = load_template;
2592         }
2593
2594         session_name = basename_nosuffix (ARDOUR_COMMAND_LINE::session_name);
2595         session_path = ARDOUR_COMMAND_LINE::session_name;
2596         
2597         if (!session_path.empty()) {
2598                 if (Glib::file_test (session_path.c_str(), Glib::FILE_TEST_EXISTS)) {
2599                         if (Glib::file_test (session_path.c_str(), Glib::FILE_TEST_IS_REGULAR)) {
2600                                 /* session/snapshot file, change path to be dir */
2601                                 session_path = Glib::path_get_dirname (session_path);
2602                         }
2603                 }
2604         }
2605
2606         SessionDialog session_dialog (should_be_new, session_name, session_path, load_template, cancel_not_quit);
2607
2608         while (ret != 0) {
2609
2610                 if (!ARDOUR_COMMAND_LINE::session_name.empty()) {
2611
2612                         /* if they named a specific statefile, use it, otherwise they are
2613                            just giving a session folder, and we want to use it as is
2614                            to find the session.
2615                         */
2616
2617                         string::size_type suffix = ARDOUR_COMMAND_LINE::session_name.find (statefile_suffix);
2618
2619                         if (suffix != string::npos) {
2620                                 session_path = Glib::path_get_dirname (ARDOUR_COMMAND_LINE::session_name);
2621                                 session_name = ARDOUR_COMMAND_LINE::session_name.substr (0, suffix);
2622                                 session_name = Glib::path_get_basename (session_name);
2623                         } else {
2624                                 session_path = ARDOUR_COMMAND_LINE::session_name;
2625                                 session_name = Glib::path_get_basename (ARDOUR_COMMAND_LINE::session_name);
2626                         }
2627                 } else {
2628                         session_path = "";
2629                         session_name = "";
2630                         session_dialog.clear_given ();
2631                 }
2632                 
2633                 if (should_be_new || session_name.empty()) {
2634                         /* need the dialog to get info from user */
2635
2636                         cerr << "run dialog\n";
2637
2638                         switch (session_dialog.run()) {
2639                         case RESPONSE_ACCEPT:
2640                                 break;
2641                         default:
2642                                 if (quit_on_cancel) {
2643                                         exit (1);
2644                                 } else {
2645                                         return ret;
2646                                 }
2647                         }
2648
2649                         session_dialog.hide ();
2650                 }
2651
2652                 /* if we run the startup dialog again, offer more than just "new session" */
2653                 
2654                 should_be_new = false;
2655                 
2656                 session_name = session_dialog.session_name (likely_new);
2657                 session_path = session_dialog.session_folder ();
2658
2659                 if (nsm) {
2660                         likely_new = true;
2661                 }
2662
2663                 string::size_type suffix = session_name.find (statefile_suffix);
2664                 
2665                 if (suffix != string::npos) {
2666                         session_name = session_name.substr (0, suffix);
2667                 }
2668                 
2669                 /* this shouldn't happen, but we catch it just in case it does */
2670                 
2671                 if (session_name.empty()) {
2672                         continue;
2673                 }
2674                 
2675                 if (session_dialog.use_session_template()) {
2676                         template_name = session_dialog.session_template_name();
2677                         _session_is_new = true;
2678                 }
2679                 
2680                 if (session_name[0] == G_DIR_SEPARATOR ||
2681                     (session_name.length() > 2 && session_name[0] == '.' && session_name[1] == G_DIR_SEPARATOR) ||
2682                     (session_name.length() > 3 && session_name[0] == '.' && session_name[1] == '.' && session_name[2] == G_DIR_SEPARATOR)) {
2683                         
2684                         /* absolute path or cwd-relative path specified for session name: infer session folder
2685                            from what was given.
2686                         */
2687                         
2688                         session_path = Glib::path_get_dirname (session_name);
2689                         session_name = Glib::path_get_basename (session_name);
2690                         
2691                 } else {
2692
2693                         session_path = session_dialog.session_folder();
2694                         
2695                         char illegal = Session::session_name_is_legal (session_name);
2696                         
2697                         if (illegal) {
2698                                 MessageDialog msg (session_dialog,
2699                                                    string_compose (_("To ensure compatibility with various systems\n"
2700                                                                      "session names may not contain a '%1' character"),
2701                                                                    illegal));
2702                                 msg.run ();
2703                                 ARDOUR_COMMAND_LINE::session_name = ""; // cancel that
2704                                 continue;
2705                         }
2706                 }
2707         
2708                 if (Glib::file_test (session_path, Glib::FileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) {
2709
2710
2711                         if (likely_new && !nsm) {
2712
2713                                 std::string existing = Glib::build_filename (session_path, session_name);
2714
2715                                 if (!ask_about_loading_existing_session (existing)) {
2716                                         ARDOUR_COMMAND_LINE::session_name = ""; // cancel that
2717                                         continue;
2718                                 }
2719                         }
2720
2721                         _session_is_new = false;
2722
2723                 } else {
2724
2725                         if (!likely_new) {
2726                                 pop_back_splash (session_dialog);
2727                                 MessageDialog msg (string_compose (_("There is no existing session at \"%1\""), session_path));
2728                                 msg.run ();
2729                                 ARDOUR_COMMAND_LINE::session_name = ""; // cancel that
2730                                 continue;
2731                         }
2732
2733                         char illegal = Session::session_name_is_legal(session_name);
2734
2735                         if (illegal) {
2736                                 pop_back_splash (session_dialog);
2737                                 MessageDialog msg (session_dialog, string_compose(_("To ensure compatibility with various systems\n"
2738                                                                                     "session names may not contain a '%1' character"), illegal));
2739                                 msg.run ();
2740                                 ARDOUR_COMMAND_LINE::session_name = ""; // cancel that
2741                                 continue;
2742                         }
2743
2744                         _session_is_new = true;
2745                 }
2746
2747                 if (likely_new && template_name.empty()) {
2748
2749                         ret = build_session_from_dialog (session_dialog, session_path, session_name);
2750
2751                 } else {
2752
2753                         ret = load_session (session_path, session_name, template_name);
2754
2755                         if (ret == -2) {
2756                                 /* not connected to the AudioEngine, so quit to avoid an infinite loop */
2757                                 exit (1);
2758                         }
2759
2760                         if (!ARDOUR_COMMAND_LINE::immediate_save.empty()) {
2761                                 _session->save_state (ARDOUR_COMMAND_LINE::immediate_save, false);
2762                                 exit (1);
2763                         }
2764
2765                         /* clear this to avoid endless attempts to load the
2766                            same session.
2767                         */
2768
2769                         ARDOUR_COMMAND_LINE::session_name = "";
2770                 }
2771         }
2772
2773         return ret;
2774 }
2775
2776 void
2777 ARDOUR_UI::close_session()
2778 {
2779         if (!check_audioengine()) {
2780                 return;
2781         }
2782
2783         if (unload_session (true)) {
2784                 return;
2785         }
2786
2787         ARDOUR_COMMAND_LINE::session_name = "";
2788
2789         if (get_session_parameters (true, false)) {
2790                 exit (1);
2791         }
2792
2793         goto_editor_window ();
2794 }
2795
2796 /** @param snap_name Snapshot name (without .ardour suffix).
2797  *  @return -2 if the load failed because we are not connected to the AudioEngine.
2798  */
2799 int
2800 ARDOUR_UI::load_session (const std::string& path, const std::string& snap_name, std::string mix_template)
2801 {
2802         Session *new_session;
2803         int unload_status;
2804         int retval = -1;
2805
2806         if (_session) {
2807                 unload_status = unload_session ();
2808                 
2809                 if (unload_status < 0) {
2810                         goto out;
2811                 } else if (unload_status > 0) {
2812                         retval = 0;
2813                         goto out;
2814                 }
2815         }
2816
2817         session_loaded = false;
2818
2819         loading_message (string_compose (_("Please wait while %1 loads your session"), PROGRAM_NAME));
2820
2821         try {
2822                 new_session = new Session (*AudioEngine::instance(), path, snap_name, 0, mix_template);
2823         }
2824
2825         /* this one is special */
2826
2827         catch (AudioEngine::PortRegistrationFailure& err) {
2828
2829                 MessageDialog msg (err.what(),
2830                                    true,
2831                                    Gtk::MESSAGE_INFO,
2832                                    Gtk::BUTTONS_CLOSE);
2833
2834                 msg.set_title (_("Port Registration Error"));
2835                 msg.set_secondary_text (_("Click the Close button to try again."));
2836                 msg.set_position (Gtk::WIN_POS_CENTER);
2837                 pop_back_splash (msg);
2838                 msg.present ();
2839
2840                 int response = msg.run ();
2841
2842                 msg.hide ();
2843
2844                 switch (response) {
2845                 case RESPONSE_CANCEL:
2846                         exit (1);
2847                 default:
2848                         break;
2849                 }
2850                 goto out;
2851         }
2852
2853         catch (...) {
2854
2855                 MessageDialog msg (string_compose(
2856                                            _("Session \"%1 (snapshot %2)\" did not load successfully"),
2857                                            path, snap_name),
2858                                    true,
2859                                    Gtk::MESSAGE_INFO,
2860                                    BUTTONS_OK);
2861
2862                 msg.set_keep_above (true);
2863                 msg.set_title (_("Loading Error"));
2864                 msg.set_position (Gtk::WIN_POS_CENTER);
2865                 pop_back_splash (msg);
2866                 msg.present ();
2867                 (void) msg.run ();
2868                 msg.hide ();
2869
2870                 goto out;
2871         }
2872
2873         {
2874                 list<string> const u = new_session->unknown_processors ();
2875                 if (!u.empty()) {
2876                         MissingPluginDialog d (_session, u);
2877                         d.run ();
2878                 }
2879         }
2880
2881         if (!new_session->writable()) {
2882                 MessageDialog msg (_("This session has been opened in read-only mode.\n\nYou will not be able to record or save."),
2883                                    true,
2884                                    Gtk::MESSAGE_INFO,
2885                                    BUTTONS_OK);
2886                 
2887                 msg.set_keep_above (true);
2888                 msg.set_title (_("Read-only Session"));
2889                 msg.set_position (Gtk::WIN_POS_CENTER);
2890                 pop_back_splash (msg);
2891                 msg.present ();
2892                 (void) msg.run ();
2893                 msg.hide ();
2894         }
2895         
2896
2897         /* Now the session been created, add the transport controls */
2898         new_session->add_controllable(roll_controllable);
2899         new_session->add_controllable(stop_controllable);
2900         new_session->add_controllable(goto_start_controllable);
2901         new_session->add_controllable(goto_end_controllable);
2902         new_session->add_controllable(auto_loop_controllable);
2903         new_session->add_controllable(play_selection_controllable);
2904         new_session->add_controllable(rec_controllable);
2905
2906         set_session (new_session);
2907
2908         session_loaded = true;
2909
2910         goto_editor_window ();
2911
2912         if (_session) {
2913                 _session->set_clean ();
2914         }
2915
2916         flush_pending ();
2917         retval = 0;
2918
2919   out:
2920         return retval;
2921 }
2922
2923 int
2924 ARDOUR_UI::build_session (const std::string& path, const std::string& snap_name, BusProfile& bus_profile)
2925 {
2926         Session *new_session;
2927         int x;
2928
2929         session_loaded = false;
2930         x = unload_session ();
2931
2932         if (x < 0) {
2933                 return -1;
2934         } else if (x > 0) {
2935                 return 0;
2936         }
2937
2938         _session_is_new = true;
2939
2940         try {
2941                 new_session = new Session (*AudioEngine::instance(), path, snap_name, &bus_profile);
2942         }
2943
2944         catch (...) {
2945
2946                 MessageDialog msg (string_compose(_("Could not create session in \"%1\""), path));
2947                 pop_back_splash (msg);
2948                 msg.run ();
2949                 return -1;
2950         }
2951
2952         /* Give the new session the default GUI state, if such things exist */
2953
2954         XMLNode* n;
2955         n = Config->instant_xml (X_("Editor"));
2956         if (n) {
2957                 new_session->add_instant_xml (*n, false);
2958         }
2959         n = Config->instant_xml (X_("Mixer"));
2960         if (n) {
2961                 new_session->add_instant_xml (*n, false);
2962         }
2963
2964         /* Put the playhead at 0 and scroll fully left */
2965         n = new_session->instant_xml (X_("Editor"));
2966         if (n) {
2967                 n->add_property (X_("playhead"), X_("0"));
2968                 n->add_property (X_("left-frame"), X_("0"));
2969         }
2970
2971         set_session (new_session);
2972
2973         session_loaded = true;
2974
2975         new_session->save_state(new_session->name());
2976
2977         return 0;
2978 }
2979
2980 void
2981 ARDOUR_UI::launch_chat ()
2982 {
2983 #ifdef __APPLE__
2984         open_uri("http://webchat.freenode.net/?channels=ardour-osx");
2985 #else
2986         open_uri("http://webchat.freenode.net/?channels=ardour");
2987 #endif
2988 }
2989
2990 void
2991 ARDOUR_UI::launch_manual ()
2992 {
2993         PBD::open_uri (Config->get_tutorial_manual_url());
2994 }
2995
2996 void
2997 ARDOUR_UI::launch_reference ()
2998 {
2999         PBD::open_uri (Config->get_reference_manual_url());
3000 }
3001
3002 void
3003 ARDOUR_UI::loading_message (const std::string& msg)
3004 {
3005         if (ARDOUR_COMMAND_LINE::no_splash) {
3006                 return;
3007         }
3008
3009         if (!splash) {
3010                 show_splash ();
3011         }
3012
3013         splash->message (msg);
3014 }
3015
3016 void
3017 ARDOUR_UI::show_splash ()
3018 {
3019         if (splash == 0) {
3020                 try {
3021                         splash = new Splash;
3022                 } catch (...) {
3023                         return;
3024                 }
3025         }
3026
3027         splash->display ();
3028 }
3029
3030 void
3031 ARDOUR_UI::hide_splash ()
3032 {
3033         delete splash;
3034         splash = 0;
3035 }
3036
3037 void
3038 ARDOUR_UI::display_cleanup_results (ARDOUR::CleanupReport& rep, const gchar* list_title, const bool msg_delete)
3039 {
3040         size_t removed;
3041
3042         removed = rep.paths.size();
3043
3044         if (removed == 0) {
3045                 MessageDialog msgd (*editor,
3046                                     _("No files were ready for clean-up"),
3047                                     true,
3048                                     Gtk::MESSAGE_INFO,
3049                                     Gtk::BUTTONS_OK);
3050                 msgd.set_title (_("Clean-up"));
3051                 msgd.set_secondary_text (_("If this seems suprising, \n\
3052 check for any existing snapshots.\n\
3053 These may still include regions that\n\
3054 require some unused files to continue to exist."));
3055
3056                 msgd.run ();
3057                 return;
3058         }
3059
3060         ArdourDialog results (_("Clean-up"), true, false);
3061
3062         struct CleanupResultsModelColumns : public Gtk::TreeModel::ColumnRecord {
3063             CleanupResultsModelColumns() {
3064                     add (visible_name);
3065                     add (fullpath);
3066             }
3067             Gtk::TreeModelColumn<std::string> visible_name;
3068             Gtk::TreeModelColumn<std::string> fullpath;
3069         };
3070
3071
3072         CleanupResultsModelColumns results_columns;
3073         Glib::RefPtr<Gtk::ListStore> results_model;
3074         Gtk::TreeView results_display;
3075
3076         results_model = ListStore::create (results_columns);
3077         results_display.set_model (results_model);
3078         results_display.append_column (list_title, results_columns.visible_name);
3079
3080         results_display.set_name ("CleanupResultsList");
3081         results_display.set_headers_visible (true);
3082         results_display.set_headers_clickable (false);
3083         results_display.set_reorderable (false);
3084
3085         Gtk::ScrolledWindow list_scroller;
3086         Gtk::Label txt;
3087         Gtk::VBox dvbox;
3088         Gtk::HBox dhbox;  // the hbox for the image and text
3089         Gtk::HBox ddhbox; // the hbox we eventually pack into the dialog's vbox
3090         Gtk::Image* dimage = manage (new Gtk::Image(Stock::DIALOG_INFO,  Gtk::ICON_SIZE_DIALOG));
3091
3092         dimage->set_alignment(ALIGN_LEFT, ALIGN_TOP);
3093
3094         const string dead_directory = _session->session_directory().dead_path();
3095
3096         /* subst:
3097            %1 - number of files removed
3098            %2 - location of "dead"
3099            %3 - size of files affected
3100            %4 - prefix for "bytes" to produce sensible results (e.g. mega, kilo, giga)
3101         */
3102
3103         const char* bprefix;
3104         double space_adjusted = 0;
3105
3106         if (rep.space < 1000) {
3107                 bprefix = X_("");
3108                 space_adjusted = rep.space;
3109         } else if (rep.space < 1000000) {
3110                 bprefix = _("kilo");
3111                 space_adjusted = floorf((float)rep.space / 1000.0);
3112         } else if (rep.space < 1000000 * 1000) {
3113                 bprefix = _("mega");
3114                 space_adjusted = floorf((float)rep.space / (1000.0 * 1000.0));
3115         } else {
3116                 bprefix = _("giga");
3117                 space_adjusted = floorf((float)rep.space / (1000.0 * 1000 * 1000.0));
3118         }
3119
3120         if (msg_delete) {
3121                 txt.set_markup (string_compose (P_("\
3122 The following file was deleted from %2,\n\
3123 releasing %3 %4bytes of disk space", "\
3124 The following %1 files were deleted from %2,\n\
3125 releasing %3 %4bytes of disk space", removed),
3126                                         removed, Glib::Markup::escape_text (dead_directory), space_adjusted, bprefix, PROGRAM_NAME));
3127         } else {
3128                 txt.set_markup (string_compose (P_("\
3129 The following file was not in use and \n\
3130 has been moved to: %2\n\n\
3131 After a restart of %5\n\n\
3132 <span face=\"mono\">Session -> Clean-up -> Flush Wastebasket</span>\n\n\
3133 will release an additional %3 %4bytes of disk space.\n", "\
3134 The following %1 files were not in use and \n\
3135 have been moved to: %2\n\n\
3136 After a restart of %5\n\n\
3137 <span face=\"mono\">Session -> Clean-up -> Flush Wastebasket</span>\n\n\
3138 will release an additional %3 %4bytes of disk space.\n", removed),
3139                                         removed, Glib::Markup::escape_text (dead_directory), space_adjusted, bprefix, PROGRAM_NAME));
3140         }
3141
3142         dhbox.pack_start (*dimage, true, false, 5);
3143         dhbox.pack_start (txt, true, false, 5);
3144
3145         for (vector<string>::iterator i = rep.paths.begin(); i != rep.paths.end(); ++i) {
3146                 TreeModel::Row row = *(results_model->append());
3147                 row[results_columns.visible_name] = *i;
3148                 row[results_columns.fullpath] = *i;
3149         }
3150
3151         list_scroller.add (results_display);
3152         list_scroller.set_size_request (-1, 150);
3153         list_scroller.set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
3154
3155         dvbox.pack_start (dhbox, true, false, 5);
3156         dvbox.pack_start (list_scroller, true, false, 5);
3157         ddhbox.pack_start (dvbox, true, false, 5);
3158
3159         results.get_vbox()->pack_start (ddhbox, true, false, 5);
3160         results.add_button (Stock::CLOSE, RESPONSE_CLOSE);
3161         results.set_default_response (RESPONSE_CLOSE);
3162         results.set_position (Gtk::WIN_POS_MOUSE);
3163
3164         results_display.show();
3165         list_scroller.show();
3166         txt.show();
3167         dvbox.show();
3168         dhbox.show();
3169         ddhbox.show();
3170         dimage->show();
3171
3172         //results.get_vbox()->show();
3173         results.set_resizable (false);
3174
3175         results.run ();
3176
3177 }
3178
3179 void
3180 ARDOUR_UI::cleanup ()
3181 {
3182         if (_session == 0) {
3183                 /* shouldn't happen: menu item is insensitive */
3184                 return;
3185         }
3186
3187
3188         MessageDialog checker (_("Are you sure you want to clean-up?"),
3189                                 true,
3190                                 Gtk::MESSAGE_QUESTION,
3191                                 Gtk::BUTTONS_NONE);
3192
3193         checker.set_title (_("Clean-up"));
3194
3195         checker.set_secondary_text(_("Clean-up is a destructive operation.\n\
3196 ALL undo/redo information will be lost if you clean-up.\n\
3197 Clean-up will move all unused files to a \"dead\" location."));
3198
3199         checker.add_button (Stock::CANCEL, RESPONSE_CANCEL);
3200         checker.add_button (_("Clean-up"), RESPONSE_ACCEPT);
3201         checker.set_default_response (RESPONSE_CANCEL);
3202
3203         checker.set_name (_("CleanupDialog"));
3204         checker.set_wmclass (X_("ardour_cleanup"), PROGRAM_NAME);
3205         checker.set_position (Gtk::WIN_POS_MOUSE);
3206
3207         switch (checker.run()) {
3208         case RESPONSE_ACCEPT:
3209                 break;
3210         default:
3211                 return;
3212         }
3213
3214         ARDOUR::CleanupReport rep;
3215
3216         editor->prepare_for_cleanup ();
3217
3218         /* do not allow flush until a session is reloaded */
3219
3220         Glib::RefPtr<Action> act = ActionManager::get_action (X_("Main"), X_("FlushWastebasket"));
3221         if (act) {
3222                 act->set_sensitive (false);
3223         }
3224
3225         if (_session->cleanup_sources (rep)) {
3226                 editor->finish_cleanup ();
3227                 return;
3228         }
3229
3230         editor->finish_cleanup ();
3231
3232         checker.hide();
3233         display_cleanup_results (rep, _("Cleaned Files"), false);
3234 }
3235
3236 void
3237 ARDOUR_UI::flush_trash ()
3238 {
3239         if (_session == 0) {
3240                 /* shouldn't happen: menu item is insensitive */
3241                 return;
3242         }
3243
3244         ARDOUR::CleanupReport rep;
3245
3246         if (_session->cleanup_trash_sources (rep)) {
3247                 return;
3248         }
3249
3250         display_cleanup_results (rep, _("deleted file"), true);
3251 }
3252
3253 void
3254 ARDOUR_UI::setup_order_hint ()
3255 {
3256         uint32_t order_hint = 0;
3257
3258         /*
3259           we want the new routes to have their order keys set starting from 
3260           the highest order key in the selection + 1 (if available).
3261         */
3262         if (add_route_dialog->get_transient_for () == mixer->get_toplevel()) {
3263                 for (RouteUISelection::iterator s = mixer->selection().routes.begin(); s != mixer->selection().routes.end(); ++s) {
3264                         if ((*s)->route()->order_key() > order_hint) {
3265                                 order_hint = (*s)->route()->order_key();
3266                         }
3267                 }
3268
3269                 if (!mixer->selection().routes.empty()) {
3270                         order_hint++;
3271                 }
3272
3273         } else {
3274                 for (TrackSelection::iterator s = editor->get_selection().tracks.begin(); s != editor->get_selection().tracks.end(); ++s) {
3275                         RouteTimeAxisView* tav = dynamic_cast<RouteTimeAxisView*> (*s);
3276                         if (tav && tav->route() && tav->route()->order_key() > order_hint) {
3277                                 order_hint = tav->route()->order_key();
3278                         }
3279                 }
3280
3281                 if (!editor->get_selection().tracks.empty()) {
3282                         order_hint++;
3283                 }
3284         }
3285
3286         _session->set_order_hint (order_hint);
3287
3288         /* create a gap in the existing route order keys to accomodate new routes.*/
3289
3290         boost::shared_ptr <RouteList> rd = _session->get_routes();
3291         for (RouteList::iterator ri = rd->begin(); ri != rd->end(); ++ri) {
3292                 boost::shared_ptr<Route> rt (*ri);
3293                         
3294                 if (rt->is_monitor()) {
3295                         continue;
3296                 }
3297
3298                 if (rt->order_key () >= order_hint) {
3299                         rt->set_order_key (rt->order_key () + add_route_dialog->count());
3300                 }
3301         }
3302 }
3303
3304 void
3305 ARDOUR_UI::add_route (Gtk::Window* float_window)
3306 {
3307         int count;
3308
3309         if (!_session) {
3310                 return;
3311         }
3312
3313         if (add_route_dialog->is_visible()) {
3314                 /* we're already doing this */
3315                 return;
3316         }
3317
3318         if (float_window) {
3319                 add_route_dialog->unset_transient_for ();
3320                 add_route_dialog->set_transient_for (*float_window);
3321         }
3322
3323         ResponseType r = (ResponseType) add_route_dialog->run ();
3324
3325         add_route_dialog->hide();
3326
3327         switch (r) {
3328                 case RESPONSE_ACCEPT:
3329                         break;
3330                 default:
3331                         return;
3332                         break;
3333         }
3334
3335         if ((count = add_route_dialog->count()) <= 0) {
3336                 return;
3337         }
3338
3339         setup_order_hint();
3340
3341         PBD::ScopedConnection idle_connection;
3342
3343         if (count > 8) {
3344                 ARDOUR::GUIIdle.connect (idle_connection, MISSING_INVALIDATOR, boost::bind (&Gtkmm2ext::UI::flush_pending, this), gui_context());
3345         }
3346
3347         string template_path = add_route_dialog->track_template();
3348
3349         if (!template_path.empty()) {
3350                 if (add_route_dialog->name_template_is_default())  {
3351                         _session->new_route_from_template (count, template_path, string());
3352                 } else {
3353                         _session->new_route_from_template (count, template_path, add_route_dialog->name_template());
3354                 }
3355                 return;
3356         }
3357
3358         ChanCount input_chan= add_route_dialog->channels ();
3359         ChanCount output_chan;
3360         string name_template = add_route_dialog->name_template ();
3361         PluginInfoPtr instrument = add_route_dialog->requested_instrument ();
3362         RouteGroup* route_group = add_route_dialog->route_group ();
3363         AutoConnectOption oac = Config->get_output_auto_connect();
3364
3365         if (oac & AutoConnectMaster) {
3366                 output_chan.set (DataType::AUDIO, (_session->master_out() ? _session->master_out()->n_inputs().n_audio() : input_chan.n_audio()));
3367                 output_chan.set (DataType::MIDI, 0);
3368         } else {
3369                 output_chan = input_chan;
3370         }
3371
3372         /* XXX do something with name template */
3373
3374         switch (add_route_dialog->type_wanted()) {
3375         case AddRouteDialog::AudioTrack:
3376                 session_add_audio_track (input_chan.n_audio(), output_chan.n_audio(), add_route_dialog->mode(), route_group, count, name_template);
3377                 break;
3378         case AddRouteDialog::MidiTrack:
3379                 session_add_midi_track (route_group, count, name_template, instrument);
3380                 break;
3381         case AddRouteDialog::MixedTrack:
3382                 session_add_mixed_track (input_chan, output_chan, route_group, count, name_template, instrument);
3383                 break;
3384         case AddRouteDialog::AudioBus:
3385                 session_add_audio_bus (input_chan.n_audio(), output_chan.n_audio(), route_group, count, name_template);
3386                 break;
3387         }
3388
3389         /* idle connection will end at scope end */
3390 }
3391
3392 void
3393 ARDOUR_UI::stop_video_server (bool ask_confirm)
3394 {
3395         if (!video_server_process && ask_confirm) {
3396                 warning << string_compose (_("Video-Server was not launched by %1. The request to stop it is ignored."), PROGRAM_NAME) << endmsg;
3397         }
3398         if (video_server_process) {
3399                 if(ask_confirm) {
3400                         ArdourDialog confirm (_("Stop Video-Server"), true);
3401                         Label m (_("Do you really want to stop the Video Server?"));
3402                         confirm.get_vbox()->pack_start (m, true, true);
3403                         confirm.add_button (Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
3404                         confirm.add_button (_("Yes, Stop It"), Gtk::RESPONSE_ACCEPT);
3405                         confirm.show_all ();
3406                         if (confirm.run() == RESPONSE_CANCEL) {
3407                                 return;
3408                         }
3409                 }
3410                 delete video_server_process;
3411                 video_server_process =0;
3412         }
3413 }
3414
3415 void
3416 ARDOUR_UI::start_video_server_menu (Gtk::Window* float_window)
3417 {
3418   ARDOUR_UI::start_video_server( float_window, true);
3419 }
3420
3421 bool
3422 ARDOUR_UI::start_video_server (Gtk::Window* float_window, bool popup_msg)
3423 {
3424         if (!_session) {
3425                 return false;
3426         }
3427         if (popup_msg) {
3428                 if (ARDOUR_UI::instance()->video_timeline->check_server()) {
3429                         if (video_server_process) {
3430                                 popup_error(_("The Video Server is already started."));
3431                         } else {
3432                                 popup_error(_("An external Video Server is configured and can be reached. Not starting a new instance."));
3433                         }
3434                 }
3435         }
3436
3437         int firsttime = 0;
3438         while (!ARDOUR_UI::instance()->video_timeline->check_server()) {
3439                 if (firsttime++) {
3440                         warning << _("Could not connect to the Video Server. Start it or configure its access URL in Edit -> Preferences.") << endmsg;
3441                 }
3442                 VideoServerDialog *video_server_dialog = new VideoServerDialog (_session);
3443                 if (float_window) {
3444                         video_server_dialog->set_transient_for (*float_window);
3445                 }
3446
3447                 if (!Config->get_show_video_server_dialog() && firsttime < 2) {
3448                         video_server_dialog->hide();
3449                 } else {
3450                         ResponseType r = (ResponseType) video_server_dialog->run ();
3451                         video_server_dialog->hide();
3452                         if (r != RESPONSE_ACCEPT) { return false; }
3453                         if (video_server_dialog->show_again()) {
3454                                 Config->set_show_video_server_dialog(false);
3455                         }
3456                 }
3457
3458                 std::string icsd_exec = video_server_dialog->get_exec_path();
3459                 std::string icsd_docroot = video_server_dialog->get_docroot();
3460                 if (icsd_docroot.empty()) {icsd_docroot = X_("/");}
3461
3462                 GStatBuf sb;
3463                 if (!g_lstat (icsd_docroot.c_str(), &sb) == 0 || !S_ISDIR(sb.st_mode)) {
3464                         warning << _("Specified docroot is not an existing directory.") << endmsg;
3465                         continue;
3466                 }
3467 #ifndef PLATFORM_WINDOWS
3468                 if ( (!g_lstat (icsd_exec.c_str(), &sb) == 0)
3469                      || (sb.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0 ) {
3470                         warning << _("Given Video Server is not an executable file.") << endmsg;
3471                         continue;
3472                 }
3473 #else
3474                 if ( (!g_lstat (icsd_exec.c_str(), &sb) == 0)
3475                      || (sb.st_mode & (S_IXUSR)) == 0 ) {
3476                         warning << _("Given Video Server is not an executable file.") << endmsg;
3477                         continue;
3478                 }
3479 #endif
3480
3481                 char **argp;
3482                 argp=(char**) calloc(9,sizeof(char*));
3483                 argp[0] = strdup(icsd_exec.c_str());
3484                 argp[1] = strdup("-P");
3485                 argp[2] = (char*) calloc(16,sizeof(char)); snprintf(argp[2], 16, "%s", video_server_dialog->get_listenaddr().c_str());
3486                 argp[3] = strdup("-p");
3487                 argp[4] = (char*) calloc(6,sizeof(char)); snprintf(argp[4], 6, "%i", video_server_dialog->get_listenport());
3488                 argp[5] = strdup("-C");
3489                 argp[6] = (char*) calloc(6,sizeof(char)); snprintf(argp[6], 6, "%i", video_server_dialog->get_cachesize());
3490                 argp[7] = strdup(icsd_docroot.c_str());
3491                 argp[8] = 0;
3492                 stop_video_server();
3493
3494                 if (icsd_docroot == X_("/")) {
3495                         Config->set_video_advanced_setup(false);
3496                 } else {
3497                         std::ostringstream osstream;
3498                         osstream << "http://localhost:" << video_server_dialog->get_listenport() << "/";
3499                         Config->set_video_server_url(osstream.str());
3500                         Config->set_video_server_docroot(icsd_docroot);
3501                         Config->set_video_advanced_setup(true);
3502                 }
3503
3504                 if (video_server_process) {
3505                         delete video_server_process;
3506                 }
3507
3508                 video_server_process = new SystemExec(icsd_exec, argp);
3509                 if (video_server_process->start()) {
3510                         warning << _("Cannot launch the video-server") << endmsg;
3511                         continue;
3512                 }
3513                 int timeout = 120; // 6 sec
3514                 while (!ARDOUR_UI::instance()->video_timeline->check_server()) {
3515                         Glib::usleep (50000);
3516                         if (--timeout <= 0 || !video_server_process->is_running()) break;
3517                 }
3518                 if (timeout <= 0) {
3519                         warning << _("Video-server was started but does not respond to requests...") << endmsg;
3520                 } else {
3521                         if (!ARDOUR_UI::instance()->video_timeline->check_server_docroot()) {
3522                                 delete video_server_process;
3523                                 video_server_process = 0;
3524                         }
3525                 }
3526         }
3527         return true;
3528 }
3529
3530 void
3531 ARDOUR_UI::add_video (Gtk::Window* float_window)
3532 {
3533         if (!_session) {
3534                 return;
3535         }
3536
3537         if (!start_video_server(float_window, false)) {
3538                 warning << _("Could not connect to the Video Server. Start it or configure its access URL in Edit -> Preferences.") << endmsg;
3539                 return;
3540         }
3541
3542         if (float_window) {
3543                 add_video_dialog->set_transient_for (*float_window);
3544         }
3545
3546         if (add_video_dialog->is_visible()) {
3547                 /* we're already doing this */
3548                 return;
3549         }
3550
3551         ResponseType r = (ResponseType) add_video_dialog->run ();
3552         add_video_dialog->hide();
3553         if (r != RESPONSE_ACCEPT) { return; }
3554
3555         bool local_file, orig_local_file;
3556         std::string path = add_video_dialog->file_name(local_file);
3557
3558         std::string orig_path = path;
3559         orig_local_file = local_file;
3560
3561         bool auto_set_session_fps = add_video_dialog->auto_set_session_fps();
3562
3563         if (local_file && !Glib::file_test(path, Glib::FILE_TEST_EXISTS)) {
3564                 warning << string_compose(_("could not open %1"), path) << endmsg;
3565                 return;
3566         }
3567         if (!local_file && path.length() == 0) {
3568                 warning << _("no video-file selected") << endmsg;
3569                 return;
3570         }
3571
3572         switch (add_video_dialog->import_option()) {
3573                 case VTL_IMPORT_TRANSCODE:
3574                         {
3575                                 TranscodeVideoDialog *transcode_video_dialog;
3576                                 transcode_video_dialog = new TranscodeVideoDialog (_session, path);
3577                                 ResponseType r = (ResponseType) transcode_video_dialog->run ();
3578                                 transcode_video_dialog->hide();
3579                                 if (r != RESPONSE_ACCEPT) {
3580                                         delete transcode_video_dialog;
3581                                         return;
3582                                 }
3583                                 if (!transcode_video_dialog->get_audiofile().empty()) {
3584                                         editor->embed_audio_from_video(
3585                                                         transcode_video_dialog->get_audiofile(),
3586                                                         video_timeline->get_offset(),
3587                                                         (transcode_video_dialog->import_option() != VTL_IMPORT_NO_VIDEO)
3588                                                         );
3589                                 }
3590                                 switch (transcode_video_dialog->import_option()) {
3591                                         case VTL_IMPORT_TRANSCODED:
3592                                                 path = transcode_video_dialog->get_filename();
3593                                                 local_file = true;
3594                                                 break;
3595                                         case VTL_IMPORT_REFERENCE:
3596                                                 break;
3597                                         default:
3598                                                 delete transcode_video_dialog;
3599                                                 return;
3600                                 }
3601                                 delete transcode_video_dialog;
3602                         }
3603                         break;
3604                 default:
3605                 case VTL_IMPORT_NONE:
3606                         break;
3607         }
3608
3609         /* strip _session->session_directory().video_path() from video file if possible */
3610         if (local_file && !path.compare(0, _session->session_directory().video_path().size(), _session->session_directory().video_path())) {
3611                  path=path.substr(_session->session_directory().video_path().size());
3612                  if (path.at(0) == G_DIR_SEPARATOR) {
3613                          path=path.substr(1);
3614                  }
3615         }
3616
3617         video_timeline->set_update_session_fps(auto_set_session_fps);
3618         if (video_timeline->video_file_info(path, local_file)) {
3619                 XMLNode* node = new XMLNode(X_("Videotimeline"));
3620                 node->add_property (X_("Filename"), path);
3621                 node->add_property (X_("AutoFPS"), auto_set_session_fps?X_("1"):X_("0"));
3622                 node->add_property (X_("LocalFile"), local_file?X_("1"):X_("0"));
3623                 if (orig_local_file) {
3624                         node->add_property (X_("OriginalVideoFile"), orig_path);
3625                 } else {
3626                         node->remove_property (X_("OriginalVideoFile"));
3627                 }
3628                 _session->add_extra_xml (*node);
3629                 _session->set_dirty ();
3630
3631                 _session->maybe_update_session_range(
3632                         std::max(video_timeline->get_offset(), (ARDOUR::frameoffset_t) 0),
3633                         std::max(video_timeline->get_offset() + video_timeline->get_duration(), (ARDOUR::frameoffset_t) 0));
3634
3635
3636                 if (add_video_dialog->launch_xjadeo() && local_file) {
3637                         editor->set_xjadeo_sensitive(true);
3638                         editor->toggle_xjadeo_proc(1);
3639                 } else {
3640                         editor->toggle_xjadeo_proc(0);
3641                 }
3642                 editor->toggle_ruler_video(true);
3643         }
3644 }
3645
3646 void
3647 ARDOUR_UI::remove_video ()
3648 {
3649         video_timeline->close_session();
3650         editor->toggle_ruler_video(false);
3651
3652         /* reset state */
3653         video_timeline->set_offset_locked(false);
3654         video_timeline->set_offset(0);
3655
3656         /* delete session state */
3657         XMLNode* node = new XMLNode(X_("Videotimeline"));
3658         _session->add_extra_xml(*node);
3659         node = new XMLNode(X_("Videomonitor"));
3660         _session->add_extra_xml(*node);
3661         stop_video_server();
3662 }
3663
3664 void
3665 ARDOUR_UI::flush_videotimeline_cache (bool localcacheonly)
3666 {
3667         if (localcacheonly) {
3668                 video_timeline->vmon_update();
3669         } else {
3670                 video_timeline->flush_cache();
3671         }
3672         editor->queue_visual_videotimeline_update();
3673 }
3674
3675 XMLNode*
3676 ARDOUR_UI::mixer_settings () const
3677 {
3678         XMLNode* node = 0;
3679
3680         if (_session) {
3681                 node = _session->instant_xml(X_("Mixer"));
3682         } else {
3683                 node = Config->instant_xml(X_("Mixer"));
3684         }
3685
3686         if (!node) {
3687                 node = new XMLNode (X_("Mixer"));
3688         }
3689
3690         return node;
3691 }
3692
3693 XMLNode*
3694 ARDOUR_UI::editor_settings () const
3695 {
3696         XMLNode* node = 0;
3697
3698         if (_session) {
3699                 node = _session->instant_xml(X_("Editor"));
3700         } else {
3701                 node = Config->instant_xml(X_("Editor"));
3702         }
3703
3704         if (!node) {
3705                 if (getenv("ARDOUR_INSTANT_XML_PATH")) {
3706                         node = Config->instant_xml(getenv("ARDOUR_INSTANT_XML_PATH"));
3707                 }
3708         }
3709
3710         if (!node) {
3711                 node = new XMLNode (X_("Editor"));
3712         }
3713
3714         return node;
3715 }
3716
3717 XMLNode*
3718 ARDOUR_UI::keyboard_settings () const
3719 {
3720         XMLNode* node = 0;
3721
3722         node = Config->extra_xml(X_("Keyboard"));
3723
3724         if (!node) {
3725                 node = new XMLNode (X_("Keyboard"));
3726         }
3727
3728         return node;
3729 }
3730
3731 void
3732 ARDOUR_UI::create_xrun_marker (framepos_t where)
3733 {
3734         editor->mouse_add_new_marker (where, false, true);
3735 }
3736
3737 void
3738 ARDOUR_UI::halt_on_xrun_message ()
3739 {
3740         MessageDialog msg (*editor,
3741                            _("Recording was stopped because your system could not keep up."));
3742         msg.run ();
3743 }
3744
3745 void
3746 ARDOUR_UI::xrun_handler (framepos_t where)
3747 {
3748         if (!_session) {
3749                 return;
3750         }
3751
3752         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::xrun_handler, where)
3753
3754         if (_session && Config->get_create_xrun_marker() && _session->actively_recording()) {
3755                 create_xrun_marker(where);
3756         }
3757
3758         if (_session && Config->get_stop_recording_on_xrun() && _session->actively_recording()) {
3759                 halt_on_xrun_message ();
3760         }
3761 }
3762
3763 void
3764 ARDOUR_UI::disk_overrun_handler ()
3765 {
3766         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::disk_overrun_handler)
3767
3768         if (!have_disk_speed_dialog_displayed) {
3769                 have_disk_speed_dialog_displayed = true;
3770                 MessageDialog* msg = new MessageDialog (*editor, string_compose (_("\
3771 The disk system on your computer\n\
3772 was not able to keep up with %1.\n\
3773 \n\
3774 Specifically, it failed to write data to disk\n\
3775 quickly enough to keep up with recording.\n"), PROGRAM_NAME));
3776                 msg->signal_response().connect (sigc::bind (sigc::mem_fun (*this, &ARDOUR_UI::disk_speed_dialog_gone), msg));
3777                 msg->show ();
3778         }
3779 }
3780
3781 void
3782 ARDOUR_UI::disk_underrun_handler ()
3783 {
3784         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::disk_underrun_handler)
3785
3786         if (!have_disk_speed_dialog_displayed) {
3787                 have_disk_speed_dialog_displayed = true;
3788                 MessageDialog* msg = new MessageDialog (
3789                         *editor, string_compose (_("The disk system on your computer\n\
3790 was not able to keep up with %1.\n\
3791 \n\
3792 Specifically, it failed to read data from disk\n\
3793 quickly enough to keep up with playback.\n"), PROGRAM_NAME));
3794                 msg->signal_response().connect (sigc::bind (sigc::mem_fun (*this, &ARDOUR_UI::disk_speed_dialog_gone), msg));
3795                 msg->show ();
3796         }
3797 }
3798
3799 void
3800 ARDOUR_UI::disk_speed_dialog_gone (int /*ignored_response*/, MessageDialog* msg)
3801 {
3802         have_disk_speed_dialog_displayed = false;
3803         delete msg;
3804 }
3805
3806 void
3807 ARDOUR_UI::session_dialog (std::string msg)
3808 {
3809         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::session_dialog, msg)
3810
3811         MessageDialog* d;
3812
3813         if (editor) {
3814                 d = new MessageDialog (*editor, msg, false, MESSAGE_INFO, BUTTONS_OK, true);
3815         } else {
3816                 d = new MessageDialog (msg, false, MESSAGE_INFO, BUTTONS_OK, true);
3817         }
3818
3819         d->show_all ();
3820         d->run ();
3821         delete d;
3822 }
3823
3824 int
3825 ARDOUR_UI::pending_state_dialog ()
3826 {
3827         HBox* hbox = manage (new HBox());
3828         Image* image = manage (new Image (Stock::DIALOG_QUESTION, ICON_SIZE_DIALOG));
3829         ArdourDialog dialog (_("Crash Recovery"), true);
3830         Label  message (string_compose (_("\
3831 This session appears to have been in the\n\
3832 middle of recording when %1 or\n\
3833 the computer was shutdown.\n\
3834 \n\
3835 %1 can recover any captured audio for\n\
3836 you, or it can ignore it. Please decide\n\
3837 what you would like to do.\n"), PROGRAM_NAME));
3838         image->set_alignment(ALIGN_CENTER, ALIGN_TOP);
3839         hbox->pack_start (*image, PACK_EXPAND_WIDGET, 12);
3840         hbox->pack_end (message, PACK_EXPAND_PADDING, 12);
3841         dialog.get_vbox()->pack_start(*hbox, PACK_EXPAND_PADDING, 6);
3842         dialog.add_button (_("Ignore crash data"), RESPONSE_REJECT);
3843         dialog.add_button (_("Recover from crash"), RESPONSE_ACCEPT);
3844         dialog.set_default_response (RESPONSE_ACCEPT);
3845         dialog.set_position (WIN_POS_CENTER);
3846         message.show();
3847         image->show();
3848         hbox->show();
3849
3850         switch (dialog.run ()) {
3851         case RESPONSE_ACCEPT:
3852                 return 1;
3853         default:
3854                 return 0;
3855         }
3856 }
3857
3858 int
3859 ARDOUR_UI::sr_mismatch_dialog (framecnt_t desired, framecnt_t actual)
3860 {
3861         HBox* hbox = new HBox();
3862         Image* image = new Image (Stock::DIALOG_WARNING, ICON_SIZE_DIALOG);
3863         ArdourDialog dialog (_("Sample Rate Mismatch"), true);
3864         Label  message (string_compose (_("\
3865 This session was created with a sample rate of %1 Hz, but\n\
3866 %2 is currently running at %3 Hz.  If you load this session,\n\
3867 audio may be played at the wrong sample rate.\n"), desired, PROGRAM_NAME, actual));
3868
3869         image->set_alignment(ALIGN_CENTER, ALIGN_TOP);
3870         hbox->pack_start (*image, PACK_EXPAND_WIDGET, 12);
3871         hbox->pack_end (message, PACK_EXPAND_PADDING, 12);
3872         dialog.get_vbox()->pack_start(*hbox, PACK_EXPAND_PADDING, 6);
3873         dialog.add_button (_("Do not load session"), RESPONSE_REJECT);
3874         dialog.add_button (_("Load session anyway"), RESPONSE_ACCEPT);
3875         dialog.set_default_response (RESPONSE_ACCEPT);
3876         dialog.set_position (WIN_POS_CENTER);
3877         message.show();
3878         image->show();
3879         hbox->show();
3880
3881         switch (dialog.run()) {
3882         case RESPONSE_ACCEPT:
3883                 return 0;
3884         default:
3885                 break;
3886         }
3887
3888         return 1;
3889 }
3890
3891 int
3892 ARDOUR_UI::disconnect_from_engine ()
3893 {
3894         /* drop connection to AudioEngine::Halted so that we don't act
3895          *  as if the engine unexpectedly shut down
3896          */
3897
3898         halt_connection.disconnect ();
3899         
3900         if (AudioEngine::instance()->stop ()) {
3901                 MessageDialog msg (*editor, _("Could not disconnect from Audio/MIDI engine"));
3902                 msg.run ();
3903                 return -1;
3904         } else {
3905                 AudioEngine::instance()->Halted.connect_same_thread (halt_connection, boost::bind (&ARDOUR_UI::engine_halted, this, _1, false));
3906         }
3907         
3908         update_sample_rate (0);
3909         return 0;
3910 }
3911
3912 int
3913 ARDOUR_UI::reconnect_to_engine ()
3914 {
3915         if (AudioEngine::instance()->start ()) {
3916                 if (editor) {
3917                         MessageDialog msg (*editor,  _("Could not reconnect to the Audio/MIDI engine"));
3918                         msg.run ();
3919                 } else {
3920                         MessageDialog msg (_("Could not reconnect to the Audio/MIDI engine"));
3921                         msg.run ();
3922                 }
3923                 return -1;
3924         }
3925         
3926         update_sample_rate (0);
3927         return 0;
3928 }
3929
3930 void
3931 ARDOUR_UI::use_config ()
3932 {
3933         XMLNode* node = Config->extra_xml (X_("TransportControllables"));
3934         if (node) {
3935                 set_transport_controllable_state (*node);
3936         }
3937 }
3938
3939 void
3940 ARDOUR_UI::update_transport_clocks (framepos_t pos)
3941 {
3942         if (Config->get_primary_clock_delta_edit_cursor()) {
3943                 primary_clock->set (pos, false, editor->get_preferred_edit_position());
3944         } else {
3945                 primary_clock->set (pos);
3946         }
3947
3948         if (Config->get_secondary_clock_delta_edit_cursor()) {
3949                 secondary_clock->set (pos, false, editor->get_preferred_edit_position());
3950         } else {
3951                 secondary_clock->set (pos);
3952         }
3953
3954         if (big_clock_window) {
3955                 big_clock->set (pos);
3956         }
3957         ARDOUR_UI::instance()->video_timeline->manual_seek_video_monitor(pos);
3958 }
3959
3960 void
3961 ARDOUR_UI::step_edit_status_change (bool yn)
3962 {
3963         // XXX should really store pre-step edit status of things
3964         // we make insensitive
3965
3966         if (yn) {
3967                 rec_button.set_active_state (Gtkmm2ext::ImplicitActive);
3968                 rec_button.set_sensitive (false);
3969         } else {
3970                 rec_button.unset_active_state ();;
3971                 rec_button.set_sensitive (true);
3972         }
3973 }
3974
3975 void
3976 ARDOUR_UI::record_state_changed ()
3977 {
3978         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::record_state_changed);
3979
3980         if (!_session || !big_clock_window) {
3981                 /* why bother - the clock isn't visible */
3982                 return;
3983         }
3984
3985         if (_session->record_status () == Session::Recording && _session->have_rec_enabled_track ()) {
3986                 big_clock->set_active (true);
3987         } else {
3988                 big_clock->set_active (false);
3989         }
3990 }
3991
3992 bool
3993 ARDOUR_UI::first_idle ()
3994 {
3995         if (_session) {
3996                 _session->allow_auto_play (true);
3997         }
3998
3999         if (editor) {
4000                 editor->first_idle();
4001         }
4002
4003         Keyboard::set_can_save_keybindings (true);
4004         return false;
4005 }
4006
4007 void
4008 ARDOUR_UI::store_clock_modes ()
4009 {
4010         XMLNode* node = new XMLNode(X_("ClockModes"));
4011
4012         for (vector<AudioClock*>::iterator x = AudioClock::clocks.begin(); x != AudioClock::clocks.end(); ++x) {
4013                 XMLNode* child = new XMLNode (X_("Clock"));
4014                 
4015                 child->add_property (X_("name"), (*x)->name());
4016                 child->add_property (X_("mode"), enum_2_string ((*x)->mode()));
4017                 child->add_property (X_("on"), ((*x)->off() ? X_("no") : X_("yes")));
4018
4019                 node->add_child_nocopy (*child);
4020         }
4021
4022         _session->add_extra_xml (*node);
4023         _session->set_dirty ();
4024 }
4025
4026 ARDOUR_UI::TransportControllable::TransportControllable (std::string name, ARDOUR_UI& u, ToggleType tp)
4027         : Controllable (name), ui (u), type(tp)
4028 {
4029
4030 }
4031
4032 void
4033 ARDOUR_UI::TransportControllable::set_value (double val)
4034 {
4035         if (val < 0.5) {
4036                 /* do nothing: these are radio-style actions */
4037                 return;
4038         }
4039
4040         const char *action = 0;
4041
4042         switch (type) {
4043         case Roll:
4044                 action = X_("Roll");
4045                 break;
4046         case Stop:
4047                 action = X_("Stop");
4048                 break;
4049         case GotoStart:
4050                 action = X_("GotoStart");
4051                 break;
4052         case GotoEnd:
4053                 action = X_("GotoEnd");
4054                 break;
4055         case AutoLoop:
4056                 action = X_("Loop");
4057                 break;
4058         case PlaySelection:
4059                 action = X_("PlaySelection");
4060                 break;
4061         case RecordEnable:
4062                 action = X_("Record");
4063                 break;
4064         default:
4065                 break;
4066         }
4067
4068         if (action == 0) {
4069                 return;
4070         }
4071
4072         Glib::RefPtr<Action> act = ActionManager::get_action ("Transport", action);
4073
4074         if (act) {
4075                 act->activate ();
4076         }
4077 }
4078
4079 double
4080 ARDOUR_UI::TransportControllable::get_value (void) const
4081 {
4082         float val = 0.0;
4083
4084         switch (type) {
4085         case Roll:
4086                 break;
4087         case Stop:
4088                 break;
4089         case GotoStart:
4090                 break;
4091         case GotoEnd:
4092                 break;
4093         case AutoLoop:
4094                 break;
4095         case PlaySelection:
4096                 break;
4097         case RecordEnable:
4098                 break;
4099         default:
4100                 break;
4101         }
4102
4103         return val;
4104 }
4105
4106 void
4107 ARDOUR_UI::setup_profile ()
4108 {
4109         if (gdk_screen_width() < 1200 || getenv ("ARDOUR_NARROW_SCREEN")) {
4110                 Profile->set_small_screen ();
4111         }
4112
4113         if (getenv ("ARDOUR_SAE")) {
4114                 Profile->set_sae ();
4115                 Profile->set_single_package ();
4116         }
4117 }
4118
4119 int
4120 ARDOUR_UI::missing_file (Session*s, std::string str, DataType type)
4121 {
4122         MissingFileDialog dialog (s, str, type);
4123
4124         dialog.show ();
4125         dialog.present ();
4126
4127         int result = dialog.run ();
4128         dialog.hide ();
4129
4130         switch (result) {
4131         case RESPONSE_OK:
4132                 break;
4133         default:
4134                 return 1; // quit entire session load
4135         }
4136
4137         result = dialog.get_action ();
4138
4139         return result;
4140 }
4141
4142 int
4143 ARDOUR_UI::ambiguous_file (std::string file, std::vector<std::string> hits)
4144 {
4145         AmbiguousFileDialog dialog (file, hits);
4146
4147         dialog.show ();
4148         dialog.present ();
4149
4150         dialog.run ();
4151         return dialog.get_which ();
4152 }
4153
4154 /** Allocate our thread-local buffers */
4155 void
4156 ARDOUR_UI::get_process_buffers ()
4157 {
4158         _process_thread->get_buffers ();
4159 }
4160
4161 /** Drop our thread-local buffers */
4162 void
4163 ARDOUR_UI::drop_process_buffers ()
4164 {
4165         _process_thread->drop_buffers ();
4166 }
4167
4168 void
4169 ARDOUR_UI::feedback_detected ()
4170 {
4171         _feedback_exists = true;
4172 }
4173
4174 void
4175 ARDOUR_UI::successful_graph_sort ()
4176 {
4177         _feedback_exists = false;
4178 }
4179
4180 void
4181 ARDOUR_UI::midi_panic ()
4182 {
4183         if (_session) {
4184                 _session->midi_panic();
4185         }
4186 }
4187
4188 void
4189 ARDOUR_UI::session_format_mismatch (std::string xml_path, std::string backup_path)
4190 {
4191         const char* start_big = "<span size=\"x-large\" weight=\"bold\">";
4192         const char* end_big = "</span>";
4193         const char* start_mono = "<tt>";
4194         const char* end_mono = "</tt>";
4195
4196         MessageDialog msg (string_compose (_("%4This is a session from an older version of %3%5\n\n"
4197                                              "%3 has copied the old session file\n\n%6%1%7\n\nto\n\n%6%2%7\n\n"
4198                                              "From now on, use the -2000 version with older versions of %3"),
4199                                            xml_path, backup_path, PROGRAM_NAME,
4200                                            start_big, end_big,
4201                                            start_mono, end_mono), true);
4202
4203         msg.run ();
4204 }
4205
4206
4207 void
4208 ARDOUR_UI::reset_peak_display ()
4209 {
4210         if (!_session || !_session->master_out() || !editor_meter) return;
4211         editor_meter->clear_meters();
4212         editor_meter_max_peak = -INFINITY;
4213         editor_meter_peak_display.set_name ("meterbridge peakindicator");
4214         editor_meter_peak_display.set_elements((ArdourButton::Element) (ArdourButton::Edge|ArdourButton::Body));
4215 }
4216
4217 void
4218 ARDOUR_UI::reset_group_peak_display (RouteGroup* group)
4219 {
4220         if (!_session || !_session->master_out()) return;
4221         if (group == _session->master_out()->route_group()) {
4222                 reset_peak_display ();
4223         }
4224 }
4225
4226 void
4227 ARDOUR_UI::reset_route_peak_display (Route* route)
4228 {
4229         if (!_session || !_session->master_out()) return;
4230         if (_session->master_out().get() == route) {
4231                 reset_peak_display ();
4232         }
4233 }
4234
4235 int
4236 ARDOUR_UI::do_audio_midi_setup (uint32_t desired_sample_rate)
4237 {
4238         audio_midi_setup->set_desired_sample_rate (desired_sample_rate);
4239         audio_midi_setup->set_position (WIN_POS_CENTER);
4240
4241         switch (audio_midi_setup->run()) {
4242         case Gtk::RESPONSE_OK:
4243                 return 0;
4244         case Gtk::RESPONSE_APPLY:
4245                 return 0;
4246         default:
4247                 return -1;
4248         }
4249 }
4250
4251