Merge branch 'master' into windows
[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 WIN32
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 "opts.h"
109 #include "pingback.h"
110 #include "processor_box.h"
111 #include "prompter.h"
112 #include "public_editor.h"
113 #include "rc_option_editor.h"
114 #include "route_time_axis.h"
115 #include "route_params_ui.h"
116 #include "session_metadata_dialog.h"
117 #include "session_option_editor.h"
118 #include "shuttle_control.h"
119 #include "speaker_dialog.h"
120 #include "splash.h"
121 #include "startup.h"
122 #include "theme_manager.h"
123 #include "time_axis_view_item.h"
124 #include "utils.h"
125 #include "video_server_dialog.h"
126 #include "add_video_dialog.h"
127 #include "transcode_video_dialog.h"
128 #include "system_exec.h"
129
130 #include "i18n.h"
131
132 using namespace ARDOUR;
133 using namespace PBD;
134 using namespace Gtkmm2ext;
135 using namespace Gtk;
136 using namespace std;
137
138 ARDOUR_UI *ARDOUR_UI::theArdourUI = 0;
139 UIConfiguration *ARDOUR_UI::ui_config = 0;
140
141 sigc::signal<void,bool> ARDOUR_UI::Blink;
142 sigc::signal<void>      ARDOUR_UI::RapidScreenUpdate;
143 sigc::signal<void>      ARDOUR_UI::SuperRapidScreenUpdate;
144 sigc::signal<void, framepos_t, bool, framepos_t> ARDOUR_UI::Clock;
145 sigc::signal<void>      ARDOUR_UI::CloseAllDialogs;
146
147 ARDOUR_UI::ARDOUR_UI (int *argcp, char **argvp[], const char* localedir)
148
149         : Gtkmm2ext::UI (PROGRAM_NAME, argcp, argvp)
150         
151         , gui_object_state (new GUIObjectState)
152
153         , primary_clock (new MainClock (X_("primary"), false, X_("transport"), true, true, true, false, true))
154         , secondary_clock (new MainClock (X_("secondary"), false, X_("secondary"), true, true, false, false, true))
155
156           /* big clock */
157
158         , big_clock (new AudioClock (X_("bigclock"), false, "big", true, true, false, false))
159         , video_timeline(0)
160
161           /* start of private members */
162
163         , _startup (0)
164         , nsm (0)
165         , _was_dirty (false)
166         , _mixer_on_top (false)
167         , first_time_engine_run (true)
168
169           /* transport */
170
171         , roll_controllable (new TransportControllable ("transport roll", *this, TransportControllable::Roll))
172         , stop_controllable (new TransportControllable ("transport stop", *this, TransportControllable::Stop))
173         , goto_start_controllable (new TransportControllable ("transport goto start", *this, TransportControllable::GotoStart))
174         , goto_end_controllable (new TransportControllable ("transport goto end", *this, TransportControllable::GotoEnd))
175         , auto_loop_controllable (new TransportControllable ("transport auto loop", *this, TransportControllable::AutoLoop))
176         , play_selection_controllable (new TransportControllable ("transport play selection", *this, TransportControllable::PlaySelection))
177         , rec_controllable (new TransportControllable ("transport rec-enable", *this, TransportControllable::RecordEnable))
178
179         , auto_return_button (ArdourButton::led_default_elements)
180         , follow_edits_button (ArdourButton::led_default_elements)
181         , auto_input_button (ArdourButton::led_default_elements)
182
183         , auditioning_alert_button (_("audition"))
184         , solo_alert_button (_("solo"))
185         , feedback_alert_button (_("feedback"))
186
187         , editor_meter(0)
188         , editor_meter_peak_display()
189
190         , speaker_config_window (X_("speaker-config"), _("Speaker Configuration"))
191         , theme_manager (X_("theme-manager"), _("Theme Manager"))
192         , key_editor (X_("key-editor"), _("Key Bindings"))
193         , rc_option_editor (X_("rc-options-editor"), _("Preferences"))
194         , add_route_dialog (X_("add-routes"), _("Add Tracks/Busses"))
195         , about (X_("about"), _("About"))
196         , location_ui (X_("locations"), _("Locations"))
197         , route_params (X_("inspector"), _("Tracks and Busses"))
198         , session_option_editor (X_("session-options-editor"), _("Properties"), boost::bind (&ARDOUR_UI::create_session_option_editor, this))
199         , add_video_dialog (X_("add-video"), _("Add Tracks/Busses"), boost::bind (&ARDOUR_UI::create_add_video_dialog, this))
200         , bundle_manager (X_("bundle-manager"), _("Bundle Manager"), boost::bind (&ARDOUR_UI::create_bundle_manager, this))
201         , big_clock_window (X_("big-clock"), _("Big Clock"), boost::bind (&ARDOUR_UI::create_big_clock_window, this))
202         , audio_port_matrix (X_("audio-connection-manager"), _("Audio Connections"), boost::bind (&ARDOUR_UI::create_global_port_matrix, this, ARDOUR::DataType::AUDIO))
203         , midi_port_matrix (X_("midi-connection-manager"), _("MIDI Connections"), boost::bind (&ARDOUR_UI::create_global_port_matrix, this, ARDOUR::DataType::MIDI))
204
205         , error_log_button (_("Errors"))
206
207         , _status_bar_visibility (X_("status-bar"))
208         , _feedback_exists (false)
209         , _audio_midi_setup (0)
210 {
211         Gtkmm2ext::init(localedir);
212
213         splash = 0;
214
215         if (theArdourUI == 0) {
216                 theArdourUI = this;
217         }
218
219         ui_config = new UIConfiguration();
220         _audio_midi_setup = new EngineControl;
221
222         editor = 0;
223         mixer = 0;
224         meterbridge = 0;
225         editor = 0;
226         _session_is_new = false;
227         session_selector_window = 0;
228         last_key_press_time = 0;
229         video_server_process = 0;
230         open_session_selector = 0;
231         have_configure_timeout = false;
232         have_disk_speed_dialog_displayed = false;
233         session_loaded = false;
234         ignore_dual_punch = false;
235
236         roll_button.set_controllable (roll_controllable);
237         stop_button.set_controllable (stop_controllable);
238         goto_start_button.set_controllable (goto_start_controllable);
239         goto_end_button.set_controllable (goto_end_controllable);
240         auto_loop_button.set_controllable (auto_loop_controllable);
241         play_selection_button.set_controllable (play_selection_controllable);
242         rec_button.set_controllable (rec_controllable);
243
244         roll_button.set_name ("transport button");
245         stop_button.set_name ("transport button");
246         goto_start_button.set_name ("transport button");
247         goto_end_button.set_name ("transport button");
248         auto_loop_button.set_name ("transport button");
249         play_selection_button.set_name ("transport button");
250         rec_button.set_name ("transport recenable button");
251         midi_panic_button.set_name ("transport button");
252
253         goto_start_button.set_tweaks (ArdourButton::ShowClick);
254         goto_end_button.set_tweaks (ArdourButton::ShowClick);
255         midi_panic_button.set_tweaks (ArdourButton::ShowClick);
256         
257         last_configure_time= 0;
258         last_peak_grab = 0;
259
260         ARDOUR::Diskstream::DiskOverrun.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::disk_overrun_handler, this), gui_context());
261         ARDOUR::Diskstream::DiskUnderrun.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::disk_underrun_handler, this), gui_context());
262
263         ARDOUR::Session::VersionMismatch.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::session_format_mismatch, this, _1, _2), gui_context());
264
265         /* handle dialog requests */
266
267         ARDOUR::Session::Dialog.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::session_dialog, this, _1), gui_context());
268
269         /* handle pending state with a dialog (PROBLEM: needs to return a value and thus cannot be x-thread) */
270
271         ARDOUR::Session::AskAboutPendingState.connect_same_thread (forever_connections, boost::bind (&ARDOUR_UI::pending_state_dialog, this));
272
273         /* handle Audio/MIDI setup when session requires it */
274
275         ARDOUR::Session::AudioEngineSetupRequired.connect_same_thread (forever_connections, boost::bind (&ARDOUR_UI::do_audio_midi_setup, this, _1));
276
277         /* handle sr mismatch with a dialog (PROBLEM: needs to return a value and thus cannot be x-thread) */
278
279         ARDOUR::Session::AskAboutSampleRateMismatch.connect_same_thread (forever_connections, boost::bind (&ARDOUR_UI::sr_mismatch_dialog, this, _1, _2));
280
281         /* handle requests to quit (coming from JACK session) */
282
283         ARDOUR::Session::Quit.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::finish, this), gui_context ());
284
285         /* tell the user about feedback */
286
287         ARDOUR::Session::FeedbackDetected.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::feedback_detected, this), gui_context ());
288         ARDOUR::Session::SuccessfulGraphSort.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::successful_graph_sort, this), gui_context ());
289
290         /* handle requests to deal with missing files */
291
292         ARDOUR::Session::MissingFile.connect_same_thread (forever_connections, boost::bind (&ARDOUR_UI::missing_file, this, _1, _2, _3));
293
294         /* and ambiguous files */
295
296         ARDOUR::FileSource::AmbiguousFileName.connect_same_thread (forever_connections, boost::bind (&ARDOUR_UI::ambiguous_file, this, _1, _2));
297
298         /* lets get this party started */
299
300         setup_gtk_ardour_enums ();
301         setup_profile ();
302
303         SessionEvent::create_per_thread_pool ("GUI", 512);
304
305         /* we like keyboards */
306
307         keyboard = new ArdourKeyboard(*this);
308
309         XMLNode* node = ARDOUR_UI::instance()->keyboard_settings();
310         if (node) {
311                 keyboard->set_state (*node, Stateful::loading_state_version);
312         }
313
314         /* we don't like certain modifiers */
315         Bindings::set_ignored_state (GDK_LOCK_MASK|GDK_MOD2_MASK|GDK_MOD3_MASK);
316
317         reset_dpi();
318
319         TimeAxisViewItem::set_constant_heights ();
320
321         /* Set this up so that our window proxies can register actions */
322
323         ActionManager::init ();
324
325         /* The following must happen after ARDOUR::init() so that Config is set up */
326
327         const XMLNode* ui_xml = Config->extra_xml (X_("UI"));
328
329         if (ui_xml) {
330                 theme_manager.set_state (*ui_xml);
331                 key_editor.set_state (*ui_xml);
332                 rc_option_editor.set_state (*ui_xml);
333                 session_option_editor.set_state (*ui_xml);
334                 speaker_config_window.set_state (*ui_xml);
335                 about.set_state (*ui_xml);
336                 add_route_dialog.set_state (*ui_xml);
337                 add_video_dialog.set_state (*ui_xml);
338                 route_params.set_state (*ui_xml);
339                 bundle_manager.set_state (*ui_xml);
340                 location_ui.set_state (*ui_xml);
341                 big_clock_window.set_state (*ui_xml);
342                 audio_port_matrix.set_state (*ui_xml);
343                 midi_port_matrix.set_state (*ui_xml);
344         }
345
346         WM::Manager::instance().register_window (&theme_manager);
347         WM::Manager::instance().register_window (&key_editor);
348         WM::Manager::instance().register_window (&rc_option_editor);
349         WM::Manager::instance().register_window (&session_option_editor);
350         WM::Manager::instance().register_window (&speaker_config_window);
351         WM::Manager::instance().register_window (&about);
352         WM::Manager::instance().register_window (&add_route_dialog);
353         WM::Manager::instance().register_window (&add_video_dialog);
354         WM::Manager::instance().register_window (&route_params);
355         WM::Manager::instance().register_window (&bundle_manager);
356         WM::Manager::instance().register_window (&location_ui);
357         WM::Manager::instance().register_window (&big_clock_window);
358         WM::Manager::instance().register_window (&audio_port_matrix);
359         WM::Manager::instance().register_window (&midi_port_matrix);
360
361         /* We need to instantiate the theme manager because it loads our
362            theme files. This should really change so that its window
363            and its functionality are separate 
364         */
365         
366         (void) theme_manager.get (true);
367         
368         starting.connect (sigc::mem_fun(*this, &ARDOUR_UI::startup));
369         stopping.connect (sigc::mem_fun(*this, &ARDOUR_UI::shutdown));
370
371         _process_thread = new ProcessThread ();
372         _process_thread->init ();
373
374         DPIReset.connect (sigc::mem_fun (*this, &ARDOUR_UI::resize_text_widgets));
375
376         attach_to_engine ();
377 }
378
379 GlobalPortMatrixWindow*
380 ARDOUR_UI::create_global_port_matrix (ARDOUR::DataType type)
381 {
382         if (!_session) {
383                 return 0;
384         }
385         return new GlobalPortMatrixWindow (_session, type);
386 }
387
388 void
389 ARDOUR_UI::attach_to_engine ()
390 {
391         AudioEngine::instance()->Running.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::engine_running, this), gui_context());
392         ARDOUR::Port::set_connecting_blocked (ARDOUR_COMMAND_LINE::no_connect_ports);
393 }
394
395 void
396 ARDOUR_UI::engine_stopped ()
397 {
398         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::engine_stopped)
399         ActionManager::set_sensitive (ActionManager::engine_sensitive_actions, false);
400         ActionManager::set_sensitive (ActionManager::engine_opposite_sensitive_actions, true);
401 }
402
403 void
404 ARDOUR_UI::engine_running ()
405 {
406         if (first_time_engine_run) {
407                 post_engine();
408                 first_time_engine_run = false;
409         }
410         
411         ActionManager::set_sensitive (ActionManager::engine_sensitive_actions, true);
412         ActionManager::set_sensitive (ActionManager::engine_opposite_sensitive_actions, false);
413
414         Glib::RefPtr<Action> action;
415         const char* action_name = 0;
416
417         switch (AudioEngine::instance()->samples_per_cycle()) {
418         case 32:
419                 action_name = X_("JACKLatency32");
420                 break;
421         case 64:
422                 action_name = X_("JACKLatency64");
423                 break;
424         case 128:
425                 action_name = X_("JACKLatency128");
426                 break;
427         case 512:
428                 action_name = X_("JACKLatency512");
429                 break;
430         case 1024:
431                 action_name = X_("JACKLatency1024");
432                 break;
433         case 2048:
434                 action_name = X_("JACKLatency2048");
435                 break;
436         case 4096:
437                 action_name = X_("JACKLatency4096");
438                 break;
439         case 8192:
440                 action_name = X_("JACKLatency8192");
441                 break;
442         default:
443                 /* XXX can we do anything useful ? */
444                 break;
445         }
446
447         if (action_name) {
448
449                 action = ActionManager::get_action (X_("JACK"), action_name);
450
451                 if (action) {
452                         Glib::RefPtr<RadioAction> ract = Glib::RefPtr<RadioAction>::cast_dynamic (action);
453                         ract->set_active ();
454                 }
455
456                 update_disk_space ();
457                 update_cpu_load ();
458                 update_sample_rate (AudioEngine::instance()->sample_rate());
459                 update_timecode_format ();
460         }
461 }
462
463 void
464 ARDOUR_UI::engine_halted (const char* reason, bool free_reason)
465 {
466         if (!Gtkmm2ext::UI::instance()->caller_is_ui_thread()) {
467                 /* we can't rely on the original string continuing to exist when we are called
468                    again in the GUI thread, so make a copy and note that we need to
469                    free it later.
470                 */
471                 char *copy = strdup (reason);
472                 Gtkmm2ext::UI::instance()->call_slot (invalidator (*this), boost::bind (&ARDOUR_UI::engine_halted, this, copy, true));
473                 return;
474         }
475
476         ActionManager::set_sensitive (ActionManager::engine_sensitive_actions, false);
477         ActionManager::set_sensitive (ActionManager::engine_opposite_sensitive_actions, true);
478
479         update_sample_rate (0);
480
481         string msgstr;
482
483         /* if the reason is a non-empty string, it means that the backend was shutdown
484            rather than just Ardour.
485         */
486
487         if (strlen (reason)) {
488                 msgstr = string_compose (_("The audio backend (JACK) was shutdown because:\n\n%1"), reason);
489         } else {
490                 msgstr = string_compose (_("\
491 JACK has either been shutdown or it\n\
492 disconnected %1 because %1\n\
493 was not fast enough. Try to restart\n\
494 JACK, reconnect and save the session."), PROGRAM_NAME);
495         }
496
497         MessageDialog msg (*editor, msgstr);
498         pop_back_splash (msg);
499         msg.set_keep_above (true);
500         msg.run ();
501         
502         if (free_reason) {
503                 free (const_cast<char*> (reason));
504         }
505 }
506
507 void
508 ARDOUR_UI::post_engine ()
509 {
510         /* Things to be done once (and once ONLY) after we have a backend running in the AudioEngine
511          */
512
513         ARDOUR::init_post_engine ();
514         
515         /* connect to important signals */
516
517         AudioEngine::instance()->Stopped.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::engine_stopped, this), gui_context());
518         AudioEngine::instance()->SampleRateChanged.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::update_sample_rate, this, _1), gui_context());
519         AudioEngine::instance()->Halted.connect_same_thread (halt_connection, boost::bind (&ARDOUR_UI::engine_halted, this, _1, false));
520
521         _tooltips.enable();
522
523         ActionManager::load_menus ();
524
525         if (setup_windows ()) {
526                 throw failed_constructor ();
527         }
528
529         /* Do this after setup_windows (), as that's when the _status_bar_visibility is created */
530         XMLNode* n = Config->extra_xml (X_("UI"));
531         if (n) {
532                 _status_bar_visibility.set_state (*n);
533         }
534         
535         check_memory_locking();
536
537         /* this is the first point at which all the keybindings are available */
538
539         if (ARDOUR_COMMAND_LINE::show_key_actions) {
540                 vector<string> names;
541                 vector<string> paths;
542                 vector<string> tooltips;
543                 vector<string> keys;
544                 vector<AccelKey> bindings;
545
546                 ActionManager::get_all_actions (names, paths, tooltips, keys, bindings);
547
548                 vector<string>::iterator n;
549                 vector<string>::iterator k;
550                 for (n = names.begin(), k = keys.begin(); n != names.end(); ++n, ++k) {
551                         cout << "Action: " << (*n) << " bound to " << (*k) << endl;
552                 }
553
554                 exit (0);
555         }
556
557         blink_timeout_tag = -1;
558
559         /* this being a GUI and all, we want peakfiles */
560
561         AudioFileSource::set_build_peakfiles (true);
562         AudioFileSource::set_build_missing_peakfiles (true);
563
564         /* set default clock modes */
565
566         if (Profile->get_sae()) {
567                 primary_clock->set_mode (AudioClock::BBT);
568                 secondary_clock->set_mode (AudioClock::MinSec);
569         }  else {
570                 primary_clock->set_mode (AudioClock::Timecode);
571                 secondary_clock->set_mode (AudioClock::BBT);
572         }
573
574         /* start the time-of-day-clock */
575
576 #ifndef GTKOSX
577         /* OS X provides a nearly-always visible wallclock, so don't be stupid */
578         update_wall_clock ();
579         Glib::signal_timeout().connect_seconds (sigc::mem_fun(*this, &ARDOUR_UI::update_wall_clock), 1);
580 #endif
581
582         Config->ParameterChanged.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::parameter_changed, this, _1), gui_context());
583         boost::function<void (string)> pc (boost::bind (&ARDOUR_UI::parameter_changed, this, _1));
584         Config->map_parameters (pc);
585 }
586
587 ARDOUR_UI::~ARDOUR_UI ()
588 {
589         delete keyboard;
590         delete editor;
591         delete mixer;
592         delete meterbridge;
593
594         stop_video_server();
595 }
596
597 void
598 ARDOUR_UI::pop_back_splash (Gtk::Window& win)
599 {
600         if (Splash::instance()) {
601                 Splash::instance()->pop_back_for (win);
602         }
603 }
604
605 gint
606 ARDOUR_UI::configure_timeout ()
607 {
608         if (last_configure_time == 0) {
609                 /* no configure events yet */
610                 return true;
611         }
612
613         /* force a gap of 0.5 seconds since the last configure event
614          */
615
616         if (get_microseconds() - last_configure_time < 500000) {
617                 return true;
618         } else {
619                 have_configure_timeout = false;
620                 save_ardour_state ();
621                 return false;
622         }
623 }
624
625 gboolean
626 ARDOUR_UI::configure_handler (GdkEventConfigure* /*conf*/)
627 {
628         if (have_configure_timeout) {
629                 last_configure_time = get_microseconds();
630         } else {
631                 Glib::signal_timeout().connect (sigc::mem_fun(*this, &ARDOUR_UI::configure_timeout), 100);
632                 have_configure_timeout = true;
633         }
634
635         return FALSE;
636 }
637
638 void
639 ARDOUR_UI::set_transport_controllable_state (const XMLNode& node)
640 {
641         const XMLProperty* prop;
642
643         if ((prop = node.property ("roll")) != 0) {
644                 roll_controllable->set_id (prop->value());
645         }
646         if ((prop = node.property ("stop")) != 0) {
647                 stop_controllable->set_id (prop->value());
648         }
649         if ((prop = node.property ("goto-start")) != 0) {
650                 goto_start_controllable->set_id (prop->value());
651         }
652         if ((prop = node.property ("goto-end")) != 0) {
653                 goto_end_controllable->set_id (prop->value());
654         }
655         if ((prop = node.property ("auto-loop")) != 0) {
656                 auto_loop_controllable->set_id (prop->value());
657         }
658         if ((prop = node.property ("play-selection")) != 0) {
659                 play_selection_controllable->set_id (prop->value());
660         }
661         if ((prop = node.property ("rec")) != 0) {
662                 rec_controllable->set_id (prop->value());
663         }
664         if ((prop = node.property ("shuttle")) != 0) {
665                 shuttle_box->controllable()->set_id (prop->value());
666         }
667 }
668
669 XMLNode&
670 ARDOUR_UI::get_transport_controllable_state ()
671 {
672         XMLNode* node = new XMLNode(X_("TransportControllables"));
673         char buf[64];
674
675         roll_controllable->id().print (buf, sizeof (buf));
676         node->add_property (X_("roll"), buf);
677         stop_controllable->id().print (buf, sizeof (buf));
678         node->add_property (X_("stop"), buf);
679         goto_start_controllable->id().print (buf, sizeof (buf));
680         node->add_property (X_("goto_start"), buf);
681         goto_end_controllable->id().print (buf, sizeof (buf));
682         node->add_property (X_("goto_end"), buf);
683         auto_loop_controllable->id().print (buf, sizeof (buf));
684         node->add_property (X_("auto_loop"), buf);
685         play_selection_controllable->id().print (buf, sizeof (buf));
686         node->add_property (X_("play_selection"), buf);
687         rec_controllable->id().print (buf, sizeof (buf));
688         node->add_property (X_("rec"), buf);
689         shuttle_box->controllable()->id().print (buf, sizeof (buf));
690         node->add_property (X_("shuttle"), buf);
691
692         return *node;
693 }
694
695
696 gint
697 ARDOUR_UI::autosave_session ()
698 {
699         if (g_main_depth() > 1) {
700                 /* inside a recursive main loop,
701                    give up because we may not be able to
702                    take a lock.
703                 */
704                 return 1;
705         }
706
707         if (!Config->get_periodic_safety_backups()) {
708                 return 1;
709         }
710
711         if (_session) {
712                 _session->maybe_write_autosave();
713         }
714
715         return 1;
716 }
717
718 void
719 ARDOUR_UI::update_autosave ()
720 {
721         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::update_autosave)
722
723         if (_session && _session->dirty()) {
724                 if (_autosave_connection.connected()) {
725                         _autosave_connection.disconnect();
726                 }
727
728                 _autosave_connection = Glib::signal_timeout().connect (sigc::mem_fun (*this, &ARDOUR_UI::autosave_session),
729                                 Config->get_periodic_safety_backup_interval() * 1000);
730
731         } else {
732                 if (_autosave_connection.connected()) {
733                         _autosave_connection.disconnect();
734                 }
735         }
736 }
737
738 void
739 ARDOUR_UI::check_announcements ()
740 {
741 #ifdef PHONE_HOME
742         string _annc_filename;
743
744 #ifdef __APPLE__
745         _annc_filename = PROGRAM_NAME "_announcements_osx_";
746 #else
747         _annc_filename = PROGRAM_NAME "_announcements_linux_";
748 #endif
749         _annc_filename.append (VERSIONSTRING);
750
751         std::string path = Glib::build_filename (user_config_directory(), _annc_filename);
752         std::ifstream announce_file (path.c_str());
753         if ( announce_file.fail() )
754                 _announce_string = "";
755         else {
756                 std::stringstream oss;
757                 oss << announce_file.rdbuf();
758                 _announce_string = oss.str();
759         }
760
761         pingback (VERSIONSTRING, path);
762 #endif
763 }
764
765 void
766 ARDOUR_UI::startup ()
767 {
768         Application* app = Application::instance ();
769         char *nsm_url;
770
771         app->ShouldQuit.connect (sigc::mem_fun (*this, &ARDOUR_UI::queue_finish));
772         app->ShouldLoad.connect (sigc::mem_fun (*this, &ARDOUR_UI::idle_load));
773
774         if (ARDOUR_COMMAND_LINE::check_announcements) {
775                 check_announcements ();
776         }
777
778         app->ready ();
779
780         nsm_url = getenv ("NSM_URL");
781
782         if (nsm_url) {
783                 nsm = new NSM_Client;
784                 if (!nsm->init (nsm_url)) {
785                         nsm->announce (PROGRAM_NAME, ":dirty:", "ardour3");
786
787                         unsigned int i = 0;
788                         // wait for announce reply from nsm server
789                         for ( i = 0; i < 5000; ++i) {
790                                 nsm->check ();
791                                 usleep (i);
792                                 if (nsm->is_active())
793                                         break;
794                         }
795                         // wait for open command from nsm server
796                         for ( i = 0; i < 5000; ++i) {
797                                 nsm->check ();
798                                 usleep (1000);
799                                 if (nsm->client_id ())
800                                         break;
801                         }
802
803                         if (_session && nsm) {
804                                 _session->set_nsm_state( nsm->is_active() );
805                         }
806
807                         // nsm requires these actions disabled
808                         vector<string> action_names;
809                         action_names.push_back("SaveAs");
810                         action_names.push_back("Rename");
811                         action_names.push_back("New");
812                         action_names.push_back("Open");
813                         action_names.push_back("Recent");
814                         action_names.push_back("Close");
815
816                         for (vector<string>::const_iterator n = action_names.begin(); n != action_names.end(); ++n) {
817                                 Glib::RefPtr<Action> act = ActionManager::get_action (X_("Main"), (*n).c_str());
818                                 if (act) {
819                                         act->set_sensitive (false);
820                                 }
821                         }
822
823                 }
824                 else {
825                         delete nsm;
826                         nsm = 0;
827                 }
828         }
829
830         else if (get_session_parameters (true, ARDOUR_COMMAND_LINE::new_session, ARDOUR_COMMAND_LINE::load_template)) {
831                 exit (1);
832         }
833
834         use_config ();
835
836         goto_editor_window ();
837
838         WM::Manager::instance().show_visible ();
839
840         /* We have to do this here since goto_editor_window() ends up calling show_all() on the
841          * editor window, and we may want stuff to be hidden.
842          */
843         _status_bar_visibility.update ();
844
845         BootMessage (string_compose (_("%1 is ready for use"), PROGRAM_NAME));
846 }
847
848 void
849 ARDOUR_UI::no_memory_warning ()
850 {
851         XMLNode node (X_("no-memory-warning"));
852         Config->add_instant_xml (node);
853 }
854
855 void
856 ARDOUR_UI::check_memory_locking ()
857 {
858 #if defined(__APPLE__) || defined(WIN32)
859         /* OS X doesn't support mlockall(2), and so testing for memory locking capability there is pointless */
860         return;
861 #else // !__APPLE__
862
863         XMLNode* memory_warning_node = Config->instant_xml (X_("no-memory-warning"));
864
865         if (AudioEngine::instance()->is_realtime() && memory_warning_node == 0) {
866
867                 struct rlimit limits;
868                 int64_t ram;
869                 long pages, page_size;
870 #ifdef __FreeBSD__
871                 size_t pages_len=sizeof(pages);
872                 if ((page_size = getpagesize()) < 0 ||
873                                 sysctlbyname("hw.availpages", &pages, &pages_len, NULL, 0))
874 #else
875                 if ((page_size = sysconf (_SC_PAGESIZE)) < 0 ||(pages = sysconf (_SC_PHYS_PAGES)) < 0)
876 #endif
877                 {
878                         ram = 0;
879                 } else {
880                         ram = (int64_t) pages * (int64_t) page_size;
881                 }
882
883                 if (getrlimit (RLIMIT_MEMLOCK, &limits)) {
884                         return;
885                 }
886
887                 if (limits.rlim_cur != RLIM_INFINITY) {
888
889                         if (ram == 0 || ((double) limits.rlim_cur / ram) < 0.75) {
890
891                                 MessageDialog msg (
892                                         string_compose (
893                                                 _("WARNING: Your system has a limit for maximum amount of locked memory. "
894                                                   "This might cause %1 to run out of memory before your system "
895                                                   "runs out of memory. \n\n"
896                                                   "You can view the memory limit with 'ulimit -l', "
897                                                   "and it is normally controlled by %2"),
898                                                 PROGRAM_NAME, 
899 #ifdef __FreeBSD__
900                                                 X_("/etc/login.conf")
901 #else
902                                                 X_(" /etc/security/limits.conf")
903 #endif
904                                         ).c_str());
905
906                                 msg.set_default_response (RESPONSE_OK);
907
908                                 VBox* vbox = msg.get_vbox();
909                                 HBox hbox;
910                                 CheckButton cb (_("Do not show this window again"));
911
912                                 cb.signal_toggled().connect (sigc::mem_fun (*this, &ARDOUR_UI::no_memory_warning));
913                                 
914                                 hbox.pack_start (cb, true, false);
915                                 vbox->pack_start (hbox);
916                                 cb.show();
917                                 vbox->show();
918                                 hbox.show ();
919
920                                 pop_back_splash (msg);
921
922                                 editor->ensure_float (msg);
923                                 msg.run ();
924                         }
925                 }
926         }
927 #endif // !__APPLE__
928 }
929
930
931 void
932 ARDOUR_UI::queue_finish ()
933 {
934         Glib::signal_idle().connect (mem_fun (*this, &ARDOUR_UI::idle_finish));
935 }
936
937 bool
938 ARDOUR_UI::idle_finish ()
939 {
940         finish ();
941         return false; /* do not call again */
942 }
943
944 void
945 ARDOUR_UI::finish()
946 {
947         if (_session) {
948                 ARDOUR_UI::instance()->video_timeline->sync_session_state();
949
950                 if (_session->dirty()) {
951                         vector<string> actions;
952                         actions.push_back (_("Don't quit"));
953                         actions.push_back (_("Just quit"));
954                         actions.push_back (_("Save and quit"));
955                         switch (ask_about_saving_session(actions)) {
956                         case -1:
957                                 return;
958                                 break;
959                         case 1:
960                                 /* use the default name */
961                                 if (save_state_canfail ("")) {
962                                         /* failed - don't quit */
963                                         MessageDialog msg (*editor,
964                                                            string_compose (_("\
965 %1 was unable to save your session.\n\n\
966 If you still wish to quit, please use the\n\n\
967 \"Just quit\" option."), PROGRAM_NAME));
968                                         pop_back_splash(msg);
969                                         msg.run ();
970                                         return;
971                                 }
972                                 break;
973                         case 0:
974                                 break;
975                         }
976                 }
977
978                 second_connection.disconnect ();
979                 point_one_second_connection.disconnect ();
980                 point_zero_something_second_connection.disconnect();
981         }
982
983         delete ARDOUR_UI::instance()->video_timeline;
984         ARDOUR_UI::instance()->video_timeline = NULL;
985         stop_video_server();
986
987         /* Save state before deleting the session, as that causes some
988            windows to be destroyed before their visible state can be
989            saved.
990         */
991         save_ardour_state ();
992
993         close_all_dialogs ();
994
995         loading_message (string_compose (_("Please wait while %1 cleans up..."), PROGRAM_NAME));
996
997         if (_session) {
998                 // _session->set_deletion_in_progress ();
999                 _session->set_clean ();
1000                 _session->remove_pending_capture_state ();
1001                 delete _session;
1002                 _session = 0;
1003         }
1004
1005         halt_connection.disconnect ();
1006         AudioEngine::instance()->stop ();
1007         quit ();
1008 }
1009
1010 int
1011 ARDOUR_UI::ask_about_saving_session (const vector<string>& actions)
1012 {
1013         ArdourDialog window (_("Unsaved Session"));
1014         Gtk::HBox dhbox;  // the hbox for the image and text
1015         Gtk::Label  prompt_label;
1016         Gtk::Image* dimage = manage (new Gtk::Image(Stock::DIALOG_WARNING,  Gtk::ICON_SIZE_DIALOG));
1017
1018         string msg;
1019
1020         assert (actions.size() >= 3);
1021
1022         window.add_button (actions[0], RESPONSE_REJECT);
1023         window.add_button (actions[1], RESPONSE_APPLY);
1024         window.add_button (actions[2], RESPONSE_ACCEPT);
1025
1026         window.set_default_response (RESPONSE_ACCEPT);
1027
1028         Gtk::Button noquit_button (msg);
1029         noquit_button.set_name ("EditorGTKButton");
1030
1031         string prompt;
1032
1033         if (_session->snap_name() == _session->name()) {
1034                 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?"),
1035                                         _session->snap_name());
1036         } else {
1037                 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?"),
1038                                         _session->snap_name());
1039         }
1040
1041         prompt_label.set_text (prompt);
1042         prompt_label.set_name (X_("PrompterLabel"));
1043         prompt_label.set_alignment(ALIGN_LEFT, ALIGN_TOP);
1044
1045         dimage->set_alignment(ALIGN_CENTER, ALIGN_TOP);
1046         dhbox.set_homogeneous (false);
1047         dhbox.pack_start (*dimage, false, false, 5);
1048         dhbox.pack_start (prompt_label, true, false, 5);
1049         window.get_vbox()->pack_start (dhbox);
1050
1051         window.set_name (_("Prompter"));
1052         window.set_modal (true);
1053         window.set_resizable (false);
1054
1055         dhbox.show();
1056         prompt_label.show();
1057         dimage->show();
1058         window.show();
1059         window.set_keep_above (true);
1060         window.present ();
1061
1062         ResponseType r = (ResponseType) window.run();
1063
1064         window.hide ();
1065
1066         switch (r) {
1067         case RESPONSE_ACCEPT: // save and get out of here
1068                 return 1;
1069         case RESPONSE_APPLY:  // get out of here
1070                 return 0;
1071         default:
1072                 break;
1073         }
1074
1075         return -1;
1076 }
1077
1078
1079 gint
1080 ARDOUR_UI::every_second ()
1081 {
1082         update_cpu_load ();
1083         update_buffer_load ();
1084         update_disk_space ();
1085         update_timecode_format ();
1086
1087         if (nsm && nsm->is_active ()) {
1088                 nsm->check ();
1089
1090                 if (!_was_dirty && _session->dirty ()) {
1091                         nsm->is_dirty ();
1092                         _was_dirty = true;
1093                 }
1094                 else if (_was_dirty && !_session->dirty ()){
1095                         nsm->is_clean ();
1096                         _was_dirty = false;
1097                 }
1098         }
1099         return TRUE;
1100 }
1101
1102 gint
1103 ARDOUR_UI::every_point_one_seconds ()
1104 {
1105         shuttle_box->update_speed_display ();
1106         RapidScreenUpdate(); /* EMIT_SIGNAL */
1107         return TRUE;
1108 }
1109
1110 gint
1111 ARDOUR_UI::every_point_zero_something_seconds ()
1112 {
1113         // august 2007: actual update frequency: 25Hz (40ms), not 100Hz
1114
1115         SuperRapidScreenUpdate(); /* EMIT_SIGNAL */
1116         if (editor_meter && Config->get_show_editor_meter()) {
1117                 float mpeak = editor_meter->update_meters();
1118                 if (mpeak > editor_meter_max_peak) {
1119                         if (mpeak >= Config->get_meter_peak()) {
1120                                 editor_meter_peak_display.set_name ("meterbridge peakindicator on");
1121                                 editor_meter_peak_display.set_elements((ArdourButton::Element) (ArdourButton::Edge|ArdourButton::Body));
1122                         }
1123                 }
1124         }
1125         return TRUE;
1126 }
1127
1128 void
1129 ARDOUR_UI::update_sample_rate (framecnt_t)
1130 {
1131         char buf[64];
1132
1133         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::update_sample_rate, ignored)
1134
1135         if (!AudioEngine::instance()->connected()) {
1136
1137                 snprintf (buf, sizeof (buf), _("Audio: <span foreground=\"red\">none</span>"));
1138
1139         } else {
1140
1141                 framecnt_t rate = AudioEngine::instance()->sample_rate();
1142
1143                 if (rate == 0) {
1144                         /* no sample rate available */
1145                         snprintf (buf, sizeof (buf), _("Audio: <span foreground=\"red\">none</span>"));
1146                 } else {
1147
1148                         if (fmod (rate, 1000.0) != 0.0) {
1149                                 snprintf (buf, sizeof (buf), _("Audio: <span foreground=\"green\">%.1f kHz / %4.1f ms</span>"),
1150                                           (float) rate / 1000.0f,
1151                                           (AudioEngine::instance()->usecs_per_cycle() / 1000.0f));
1152                         } else {
1153                                 snprintf (buf, sizeof (buf), _("Audio: <span foreground=\"green\">%" PRId64 " kHz / %4.1f ms</span>"),
1154                                           rate/1000,
1155                                           (AudioEngine::instance()->usecs_per_cycle() / 1000.0f));
1156                         }
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_cpu_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 JACK:
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 JACK:
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         prompter.set_title (_("Take Snapshot"));
2204         prompter.set_prompt (_("Name of new snapshot"));
2205
2206         if (!switch_to_it) {
2207                 char timebuf[128];
2208                 time_t n;
2209                 struct tm local_time;
2210
2211                 time (&n);
2212                 localtime_r (&n, &local_time);
2213                 strftime (timebuf, sizeof(timebuf), "%FT%H.%M.%S", &local_time);
2214                 prompter.set_initial_text (timebuf);
2215         }
2216
2217   again:
2218         switch (prompter.run()) {
2219         case RESPONSE_ACCEPT:
2220         {
2221                 prompter.get_result (snapname);
2222
2223                 bool do_save = (snapname.length() != 0);
2224
2225                 if (do_save) {
2226                         char illegal = Session::session_name_is_legal(snapname);
2227                         if (illegal) {
2228                                 MessageDialog msg (string_compose (_("To ensure compatibility with various systems\n"
2229                                                      "snapshot names may not contain a '%1' character"), illegal));
2230                                 msg.run ();
2231                                 goto again;
2232                         }
2233                 }
2234
2235                 vector<std::string> p;
2236                 get_state_files_in_directory (_session->session_directory().root_path(), p);
2237                 vector<string> n = get_file_names_no_extension (p);
2238                 if (find (n.begin(), n.end(), snapname) != n.end()) {
2239
2240                         ArdourDialog confirm (_("Confirm Snapshot Overwrite"), true);
2241                         Label m (_("A snapshot already exists with that name.  Do you want to overwrite it?"));
2242                         confirm.get_vbox()->pack_start (m, true, true);
2243                         confirm.add_button (Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2244                         confirm.add_button (_("Overwrite"), Gtk::RESPONSE_ACCEPT);
2245                         confirm.show_all ();
2246                         switch (confirm.run()) {
2247                         case RESPONSE_CANCEL:
2248                                 do_save = false;
2249                         }
2250                 }
2251
2252                 if (do_save) {
2253                         save_state (snapname, switch_to_it);
2254                 }
2255                 break;
2256         }
2257
2258         default:
2259                 break;
2260         }
2261 }
2262
2263 /** Ask the user for a new session name and then rename the session to it.
2264  */
2265
2266 void
2267 ARDOUR_UI::rename_session ()
2268 {
2269         if (!_session) {
2270                 return;
2271         }
2272
2273         ArdourPrompter prompter (true);
2274         string name;
2275
2276         prompter.set_name ("Prompter");
2277         prompter.add_button (Gtk::Stock::SAVE, Gtk::RESPONSE_ACCEPT);
2278         prompter.set_title (_("Rename Session"));
2279         prompter.set_prompt (_("New session name"));
2280
2281   again:
2282         switch (prompter.run()) {
2283         case RESPONSE_ACCEPT:
2284         {
2285                 prompter.get_result (name);
2286
2287                 bool do_rename = (name.length() != 0);
2288
2289                 if (do_rename) {
2290                         char illegal = Session::session_name_is_legal (name);
2291
2292                         if (illegal) {
2293                                 MessageDialog msg (string_compose (_("To ensure compatibility with various systems\n"
2294                                                                      "session names may not contain a '%1' character"), illegal));
2295                                 msg.run ();
2296                                 goto again;
2297                         }
2298
2299                         switch (_session->rename (name)) {
2300                         case -1: {
2301                                 MessageDialog msg (_("That name is already in use by another directory/folder. Please try again."));
2302                                 msg.set_position (WIN_POS_MOUSE);
2303                                 msg.run ();
2304                                 goto again;
2305                                 break;
2306                         }
2307                         case 0:
2308                                 break;
2309                         default: {
2310                                 MessageDialog msg (_("Renaming this session failed.\nThings could be seriously messed up at this point"));
2311                                 msg.set_position (WIN_POS_MOUSE);
2312                                 msg.run ();
2313                                 break;
2314                         }
2315                         }
2316                 }
2317                 
2318                 break;
2319         }
2320
2321         default:
2322                 break;
2323         }
2324 }
2325
2326 void
2327 ARDOUR_UI::save_state (const string & name, bool switch_to_it)
2328 {
2329         XMLNode* node = new XMLNode (X_("UI"));
2330
2331         WM::Manager::instance().add_state (*node);
2332
2333         node->add_child_nocopy (gui_object_state->get_state());
2334
2335         _session->add_extra_xml (*node);
2336
2337         save_state_canfail (name, switch_to_it);
2338 }
2339
2340 int
2341 ARDOUR_UI::save_state_canfail (string name, bool switch_to_it)
2342 {
2343         if (_session) {
2344                 int ret;
2345
2346                 if (name.length() == 0) {
2347                         name = _session->snap_name();
2348                 }
2349
2350                 if ((ret = _session->save_state (name, false, switch_to_it)) != 0) {
2351                         return ret;
2352                 }
2353         }
2354
2355         save_ardour_state (); /* XXX cannot fail? yeah, right ... */
2356         return 0;
2357 }
2358
2359 void
2360 ARDOUR_UI::primary_clock_value_changed ()
2361 {
2362         if (_session) {
2363                 _session->request_locate (primary_clock->current_time ());
2364         }
2365 }
2366
2367 void
2368 ARDOUR_UI::big_clock_value_changed ()
2369 {
2370         if (_session) {
2371                 _session->request_locate (big_clock->current_time ());
2372         }
2373 }
2374
2375 void
2376 ARDOUR_UI::secondary_clock_value_changed ()
2377 {
2378         if (_session) {
2379                 _session->request_locate (secondary_clock->current_time ());
2380         }
2381 }
2382
2383 void
2384 ARDOUR_UI::transport_rec_enable_blink (bool onoff)
2385 {
2386         if (_session == 0) {
2387                 return;
2388         }
2389
2390         if (_session->step_editing()) {
2391                 return;
2392         }
2393
2394         Session::RecordState const r = _session->record_status ();
2395         bool const h = _session->have_rec_enabled_track ();
2396
2397         if (r == Session::Enabled || (r == Session::Recording && !h)) {
2398                 if (onoff) {
2399                         rec_button.set_active_state (Gtkmm2ext::ExplicitActive);
2400                 } else {
2401                         rec_button.set_active_state (Gtkmm2ext::ImplicitActive);
2402                 }
2403         } else if (r == Session::Recording && h) {
2404                 rec_button.set_active_state (Gtkmm2ext::ExplicitActive);
2405         } else {
2406                 rec_button.unset_active_state ();
2407         }
2408 }
2409
2410 void
2411 ARDOUR_UI::save_template ()
2412 {
2413         ArdourPrompter prompter (true);
2414         string name;
2415
2416         if (!check_audioengine()) {
2417                 return;
2418         }
2419
2420         prompter.set_name (X_("Prompter"));
2421         prompter.set_title (_("Save Template"));
2422         prompter.set_prompt (_("Name for template:"));
2423         prompter.set_initial_text(_session->name() + _("-template"));
2424         prompter.add_button (Gtk::Stock::SAVE, Gtk::RESPONSE_ACCEPT);
2425
2426         switch (prompter.run()) {
2427         case RESPONSE_ACCEPT:
2428                 prompter.get_result (name);
2429
2430                 if (name.length()) {
2431                         _session->save_template (name);
2432                 }
2433                 break;
2434
2435         default:
2436                 break;
2437         }
2438 }
2439
2440 void
2441 ARDOUR_UI::edit_metadata ()
2442 {
2443         SessionMetadataEditor dialog;
2444         dialog.set_session (_session);
2445         editor->ensure_float (dialog);
2446         dialog.run ();
2447 }
2448
2449 void
2450 ARDOUR_UI::import_metadata ()
2451 {
2452         SessionMetadataImporter dialog;
2453         dialog.set_session (_session);
2454         editor->ensure_float (dialog);
2455         dialog.run ();
2456 }
2457
2458 bool
2459 ARDOUR_UI::ask_about_loading_existing_session (const std::string& session_path)
2460 {
2461         std::string str = string_compose (_("This session\n%1\nalready exists. Do you want to open it?"), session_path);
2462
2463         MessageDialog msg (str,
2464                            false,
2465                            Gtk::MESSAGE_WARNING,
2466                            Gtk::BUTTONS_YES_NO,
2467                            true);
2468
2469
2470         msg.set_name (X_("OpenExistingDialog"));
2471         msg.set_title (_("Open Existing Session"));
2472         msg.set_wmclass (X_("existing_session"), PROGRAM_NAME);
2473         msg.set_position (Gtk::WIN_POS_MOUSE);
2474         pop_back_splash (msg);
2475
2476         switch (msg.run()) {
2477         case RESPONSE_YES:
2478                 return true;
2479                 break;
2480         }
2481         return false;
2482 }
2483
2484 int
2485 ARDOUR_UI::build_session_from_nsd (const std::string& session_path, const std::string& session_name)
2486 {
2487         BusProfile bus_profile;
2488
2489         if (nsm || Profile->get_sae()) {
2490
2491                 bus_profile.master_out_channels = 2;
2492                 bus_profile.input_ac = AutoConnectPhysical;
2493                 bus_profile.output_ac = AutoConnectMaster;
2494                 bus_profile.requested_physical_in = 0; // use all available
2495                 bus_profile.requested_physical_out = 0; // use all available
2496
2497         } else {
2498
2499                 /* get settings from advanced section of NSD */
2500
2501                 if (_startup->create_master_bus()) {
2502                         bus_profile.master_out_channels = (uint32_t) _startup->master_channel_count();
2503                 } else {
2504                         bus_profile.master_out_channels = 0;
2505                 }
2506
2507                 if (_startup->connect_inputs()) {
2508                         bus_profile.input_ac = AutoConnectPhysical;
2509                 } else {
2510                         bus_profile.input_ac = AutoConnectOption (0);
2511                 }
2512
2513                 bus_profile.output_ac = AutoConnectOption (0);
2514
2515                 if (_startup->connect_outputs ()) {
2516                         if (_startup->connect_outs_to_master()) {
2517                                 bus_profile.output_ac = AutoConnectMaster;
2518                         } else if (_startup->connect_outs_to_physical()) {
2519                                 bus_profile.output_ac = AutoConnectPhysical;
2520                         }
2521                 }
2522
2523                 bus_profile.requested_physical_in = (uint32_t) _startup->input_limit_count();
2524                 bus_profile.requested_physical_out = (uint32_t) _startup->output_limit_count();
2525         }
2526
2527         if (build_session (session_path, session_name, bus_profile)) {
2528                 return -1;
2529         }
2530
2531         return 0;
2532 }
2533
2534 void
2535 ARDOUR_UI::idle_load (const std::string& path)
2536 {
2537         if (_session) {
2538                 if (Glib::file_test (path, Glib::FILE_TEST_IS_DIR)) {
2539                         /* /path/to/foo => /path/to/foo, foo */
2540                         load_session (path, basename_nosuffix (path));
2541                 } else {
2542                         /* /path/to/foo/foo.ardour => /path/to/foo, foo */
2543                         load_session (Glib::path_get_dirname (path), basename_nosuffix (path));
2544                 }
2545
2546         } else {
2547                 ARDOUR_COMMAND_LINE::session_name = path;
2548         }
2549 }
2550
2551 /** @param quit_on_cancel true if exit() should be called if the user clicks `cancel' in the new session dialog */
2552 int
2553 ARDOUR_UI::get_session_parameters (bool quit_on_cancel, bool should_be_new, string load_template)
2554 {
2555         string session_name;
2556         string session_path;
2557         string template_name;
2558         int ret = -1;
2559         bool likely_new = false;
2560
2561         /* deal with any existing DIRTY session now, rather than later. don't
2562          * treat a non-dirty session this way, so that it stays visible 
2563          * as we bring up the new session dialog.
2564          */
2565
2566         if (_session && ARDOUR_UI::instance()->video_timeline) {
2567                 ARDOUR_UI::instance()->video_timeline->sync_session_state();
2568         }
2569
2570         if (_session && _session->dirty()) {
2571                 if (unload_session (false)) {
2572                         /* unload cancelled by user */
2573                         return 0;
2574                 }
2575                 ARDOUR_COMMAND_LINE::session_name = "";
2576         }
2577
2578         if (!load_template.empty()) {
2579                 should_be_new = true;
2580                 template_name = load_template;
2581         }
2582
2583         while (ret != 0) {
2584
2585                 if (!ARDOUR_COMMAND_LINE::session_name.empty()) {
2586
2587                         /* if they named a specific statefile, use it, otherwise they are
2588                            just giving a session folder, and we want to use it as is
2589                            to find the session.
2590                         */
2591
2592                         string::size_type suffix = ARDOUR_COMMAND_LINE::session_name.find (statefile_suffix);
2593
2594                         if (suffix != string::npos) {
2595                                 session_path = Glib::path_get_dirname (ARDOUR_COMMAND_LINE::session_name);
2596                                 session_name = ARDOUR_COMMAND_LINE::session_name.substr (0, suffix);
2597                                 session_name = Glib::path_get_basename (session_name);
2598                         } else {
2599                                 session_path = ARDOUR_COMMAND_LINE::session_name;
2600                                 session_name = Glib::path_get_basename (ARDOUR_COMMAND_LINE::session_name);
2601                         }
2602                 } else {
2603                         session_path = "";
2604                         session_name = "";
2605                 }
2606
2607                 delete _startup;
2608                 _startup = new ArdourStartup (should_be_new, session_name, session_path, load_template);
2609                 
2610                 if (!_startup->ready_without_display()) {
2611                         _startup->present ();
2612                         main().run();
2613                         _startup->hide ();
2614                 }
2615                 
2616                 switch (_startup->response()) {
2617                 case RESPONSE_OK:
2618                         break;
2619                 default:
2620                         if (quit_on_cancel) {
2621                                 exit (1);
2622                         } else {
2623                                 return ret;
2624                         }
2625                 }
2626
2627                 /* if we run the startup dialog again, offer more than just "new session" */
2628                 
2629                 should_be_new = false;
2630                 
2631                 session_name = _startup->session_name (likely_new);
2632                 
2633                 if (nsm) {
2634                         likely_new = true;
2635                 }
2636
2637                 string::size_type suffix = session_name.find (statefile_suffix);
2638                 
2639                 if (suffix != string::npos) {
2640                         session_name = session_name.substr (0, suffix);
2641                 }
2642                 
2643                 /* this shouldn't happen, but we catch it just in case it does */
2644                 
2645                 if (session_name.empty()) {
2646                         continue;
2647                 }
2648                 
2649                 if (_startup->use_session_template()) {
2650                         template_name = _startup->session_template_name();
2651                         _session_is_new = true;
2652                 }
2653                 
2654                 if (session_name[0] == G_DIR_SEPARATOR ||
2655                     (session_name.length() > 2 && session_name[0] == '.' && session_name[1] == G_DIR_SEPARATOR) ||
2656                     (session_name.length() > 3 && session_name[0] == '.' && session_name[1] == '.' && session_name[2] == G_DIR_SEPARATOR)) {
2657                         
2658                         /* absolute path or cwd-relative path specified for session name: infer session folder
2659                            from what was given.
2660                         */
2661                         
2662                         session_path = Glib::path_get_dirname (session_name);
2663                         session_name = Glib::path_get_basename (session_name);
2664                         
2665                 } else {
2666
2667                         session_path = _startup->session_folder();
2668                         
2669                         char illegal = Session::session_name_is_legal (session_name);
2670                         
2671                         if (illegal) {
2672                                 MessageDialog msg (*_startup,
2673                                                    string_compose (_("To ensure compatibility with various systems\n"
2674                                                                      "session names may not contain a '%1' character"),
2675                                                                    illegal));
2676                                 msg.run ();
2677                                 ARDOUR_COMMAND_LINE::session_name = ""; // cancel that
2678                                 continue;
2679                         }
2680                 }
2681         
2682                 if (Glib::file_test (session_path, Glib::FileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) {
2683
2684                         if (likely_new && !nsm) {
2685
2686                                 std::string existing = Glib::build_filename (session_path, session_name);
2687
2688                                 if (!ask_about_loading_existing_session (existing)) {
2689                                         ARDOUR_COMMAND_LINE::session_name = ""; // cancel that
2690                                         continue;
2691                                 }
2692                         }
2693
2694                         _session_is_new = false;
2695
2696                 } else {
2697
2698                         if (!likely_new) {
2699                                 if (_startup) {
2700                                         pop_back_splash (*_startup);
2701                                 } else {
2702                                         hide_splash ();
2703                                 }
2704
2705                                 MessageDialog msg (string_compose (_("There is no existing session at \"%1\""), session_path));
2706                                 msg.run ();
2707                                 ARDOUR_COMMAND_LINE::session_name = ""; // cancel that
2708                                 continue;
2709                         }
2710
2711                         char illegal = Session::session_name_is_legal(session_name);
2712                         if (illegal) {
2713                                 pop_back_splash (*_startup);
2714                                 MessageDialog msg (*_startup, string_compose(_("To ensure compatibility with various systems\n"
2715                                                      "session names may not contain a '%1' character"), illegal));
2716                                 msg.run ();
2717                                 ARDOUR_COMMAND_LINE::session_name = ""; // cancel that
2718                                 continue;
2719                         }
2720
2721                         _session_is_new = true;
2722                 }
2723
2724                 if (likely_new && template_name.empty()) {
2725
2726                         ret = build_session_from_nsd (session_path, session_name);
2727
2728                 } else {
2729
2730                         ret = load_session (session_path, session_name, template_name);
2731
2732                         if (ret == -2) {
2733                                 /* not connected to the AudioEngine, so quit to avoid an infinite loop */
2734                                 exit (1);
2735                         }
2736
2737                         if (!ARDOUR_COMMAND_LINE::immediate_save.empty()) {
2738                                 _session->save_state (ARDOUR_COMMAND_LINE::immediate_save, false);
2739                                 exit (1);
2740                         }
2741                 }
2742         }
2743
2744         return ret;
2745 }
2746
2747 void
2748 ARDOUR_UI::close_session()
2749 {
2750         if (!check_audioengine()) {
2751                 return;
2752         }
2753
2754         if (unload_session (true)) {
2755                 return;
2756         }
2757
2758         ARDOUR_COMMAND_LINE::session_name = "";
2759
2760         if (get_session_parameters (true, false)) {
2761                 exit (1);
2762         }
2763
2764         goto_editor_window ();
2765 }
2766
2767 /** @param snap_name Snapshot name (without .ardour suffix).
2768  *  @return -2 if the load failed because we are not connected to the AudioEngine.
2769  */
2770 int
2771 ARDOUR_UI::load_session (const std::string& path, const std::string& snap_name, std::string mix_template)
2772 {
2773         Session *new_session;
2774         int unload_status;
2775         int retval = -1;
2776
2777         if (_session) {
2778                 unload_status = unload_session ();
2779                 
2780                 if (unload_status < 0) {
2781                         goto out;
2782                 } else if (unload_status > 0) {
2783                         retval = 0;
2784                         goto out;
2785                 }
2786         }
2787
2788         session_loaded = false;
2789
2790         loading_message (string_compose (_("Please wait while %1 loads your session"), PROGRAM_NAME));
2791
2792         try {
2793                 new_session = new Session (*AudioEngine::instance(), path, snap_name, 0, mix_template);
2794         }
2795
2796         /* this one is special */
2797
2798         catch (AudioEngine::PortRegistrationFailure& err) {
2799
2800                 MessageDialog msg (err.what(),
2801                                    true,
2802                                    Gtk::MESSAGE_INFO,
2803                                    Gtk::BUTTONS_CLOSE);
2804
2805                 msg.set_title (_("Port Registration Error"));
2806                 msg.set_secondary_text (_("Click the Close button to try again."));
2807                 msg.set_position (Gtk::WIN_POS_CENTER);
2808                 pop_back_splash (msg);
2809                 msg.present ();
2810
2811                 int response = msg.run ();
2812
2813                 msg.hide ();
2814
2815                 switch (response) {
2816                 case RESPONSE_CANCEL:
2817                         exit (1);
2818                 default:
2819                         break;
2820                 }
2821                 goto out;
2822         }
2823
2824         catch (...) {
2825
2826                 MessageDialog msg (string_compose(
2827                                            _("Session \"%1 (snapshot %2)\" did not load successfully"),
2828                                            path, snap_name),
2829                                    true,
2830                                    Gtk::MESSAGE_INFO,
2831                                    BUTTONS_OK);
2832
2833                 msg.set_title (_("Loading Error"));
2834                 msg.set_secondary_text (_("Click the Refresh button to try again."));
2835                 msg.add_button (Stock::REFRESH, 1);
2836                 msg.set_position (Gtk::WIN_POS_CENTER);
2837                 pop_back_splash (msg);
2838                 msg.present ();
2839
2840                 int response = msg.run ();
2841
2842                 switch (response) {
2843                 case 1:
2844                         break;
2845                 default:
2846                         exit (1);
2847                 }
2848
2849                 msg.hide ();
2850
2851                 goto out;
2852         }
2853
2854         {
2855                 list<string> const u = new_session->unknown_processors ();
2856                 if (!u.empty()) {
2857                         MissingPluginDialog d (_session, u);
2858                         d.run ();
2859                 }
2860         }
2861
2862         /* Now the session been created, add the transport controls */
2863         new_session->add_controllable(roll_controllable);
2864         new_session->add_controllable(stop_controllable);
2865         new_session->add_controllable(goto_start_controllable);
2866         new_session->add_controllable(goto_end_controllable);
2867         new_session->add_controllable(auto_loop_controllable);
2868         new_session->add_controllable(play_selection_controllable);
2869         new_session->add_controllable(rec_controllable);
2870
2871         set_session (new_session);
2872
2873         session_loaded = true;
2874
2875         goto_editor_window ();
2876
2877         if (_session) {
2878                 _session->set_clean ();
2879         }
2880
2881         flush_pending ();
2882         retval = 0;
2883
2884   out:
2885         return retval;
2886 }
2887
2888 int
2889 ARDOUR_UI::build_session (const std::string& path, const std::string& snap_name, BusProfile& bus_profile)
2890 {
2891         Session *new_session;
2892         int x;
2893
2894         session_loaded = false;
2895         x = unload_session ();
2896
2897         if (x < 0) {
2898                 return -1;
2899         } else if (x > 0) {
2900                 return 0;
2901         }
2902
2903         _session_is_new = true;
2904
2905         try {
2906                 new_session = new Session (*AudioEngine::instance(), path, snap_name, &bus_profile);
2907         }
2908
2909         catch (...) {
2910
2911                 MessageDialog msg (string_compose(_("Could not create session in \"%1\""), path));
2912                 pop_back_splash (msg);
2913                 msg.run ();
2914                 return -1;
2915         }
2916
2917         /* Give the new session the default GUI state, if such things exist */
2918
2919         XMLNode* n;
2920         n = Config->instant_xml (X_("Editor"));
2921         if (n) {
2922                 new_session->add_instant_xml (*n, false);
2923         }
2924         n = Config->instant_xml (X_("Mixer"));
2925         if (n) {
2926                 new_session->add_instant_xml (*n, false);
2927         }
2928
2929         /* Put the playhead at 0 and scroll fully left */
2930         n = new_session->instant_xml (X_("Editor"));
2931         if (n) {
2932                 n->add_property (X_("playhead"), X_("0"));
2933                 n->add_property (X_("left-frame"), X_("0"));
2934         }
2935
2936         set_session (new_session);
2937
2938         session_loaded = true;
2939
2940         new_session->save_state(new_session->name());
2941
2942         return 0;
2943 }
2944
2945 void
2946 ARDOUR_UI::launch_chat ()
2947 {
2948 #ifdef __APPLE__
2949         open_uri("http://webchat.freenode.net/?channels=ardour-osx");
2950 #else
2951         open_uri("http://webchat.freenode.net/?channels=ardour");
2952 #endif
2953 }
2954
2955 void
2956 ARDOUR_UI::launch_manual ()
2957 {
2958         PBD::open_uri (Config->get_tutorial_manual_url());
2959 }
2960
2961 void
2962 ARDOUR_UI::launch_reference ()
2963 {
2964         PBD::open_uri (Config->get_reference_manual_url());
2965 }
2966
2967 void
2968 ARDOUR_UI::loading_message (const std::string& msg)
2969 {
2970         if (ARDOUR_COMMAND_LINE::no_splash) {
2971                 return;
2972         }
2973
2974         if (!splash) {
2975                 show_splash ();
2976         }
2977
2978         splash->message (msg);
2979 }
2980
2981 void
2982 ARDOUR_UI::show_splash ()
2983 {
2984         if (splash == 0) {
2985                 try {
2986                         splash = new Splash;
2987                 } catch (...) {
2988                         return;
2989                 }
2990         }
2991
2992         splash->display ();
2993 }
2994
2995 void
2996 ARDOUR_UI::hide_splash ()
2997 {
2998         delete splash;
2999         splash = 0;
3000 }
3001
3002 void
3003 ARDOUR_UI::display_cleanup_results (ARDOUR::CleanupReport& rep, const gchar* list_title, const bool msg_delete)
3004 {
3005         size_t removed;
3006
3007         removed = rep.paths.size();
3008
3009         if (removed == 0) {
3010                 MessageDialog msgd (*editor,
3011                                     _("No files were ready for clean-up"),
3012                                     true,
3013                                     Gtk::MESSAGE_INFO,
3014                                     Gtk::BUTTONS_OK);
3015                 msgd.set_title (_("Clean-up"));
3016                 msgd.set_secondary_text (_("If this seems suprising, \n\
3017 check for any existing snapshots.\n\
3018 These may still include regions that\n\
3019 require some unused files to continue to exist."));
3020
3021                 msgd.run ();
3022                 return;
3023         }
3024
3025         ArdourDialog results (_("Clean-up"), true, false);
3026
3027         struct CleanupResultsModelColumns : public Gtk::TreeModel::ColumnRecord {
3028             CleanupResultsModelColumns() {
3029                     add (visible_name);
3030                     add (fullpath);
3031             }
3032             Gtk::TreeModelColumn<std::string> visible_name;
3033             Gtk::TreeModelColumn<std::string> fullpath;
3034         };
3035
3036
3037         CleanupResultsModelColumns results_columns;
3038         Glib::RefPtr<Gtk::ListStore> results_model;
3039         Gtk::TreeView results_display;
3040
3041         results_model = ListStore::create (results_columns);
3042         results_display.set_model (results_model);
3043         results_display.append_column (list_title, results_columns.visible_name);
3044
3045         results_display.set_name ("CleanupResultsList");
3046         results_display.set_headers_visible (true);
3047         results_display.set_headers_clickable (false);
3048         results_display.set_reorderable (false);
3049
3050         Gtk::ScrolledWindow list_scroller;
3051         Gtk::Label txt;
3052         Gtk::VBox dvbox;
3053         Gtk::HBox dhbox;  // the hbox for the image and text
3054         Gtk::HBox ddhbox; // the hbox we eventually pack into the dialog's vbox
3055         Gtk::Image* dimage = manage (new Gtk::Image(Stock::DIALOG_INFO,  Gtk::ICON_SIZE_DIALOG));
3056
3057         dimage->set_alignment(ALIGN_LEFT, ALIGN_TOP);
3058
3059         const string dead_directory = _session->session_directory().dead_path();
3060
3061         /* subst:
3062            %1 - number of files removed
3063            %2 - location of "dead"
3064            %3 - size of files affected
3065            %4 - prefix for "bytes" to produce sensible results (e.g. mega, kilo, giga)
3066         */
3067
3068         const char* bprefix;
3069         double space_adjusted = 0;
3070
3071         if (rep.space < 1000) {
3072                 bprefix = X_("");
3073                 space_adjusted = rep.space;
3074         } else if (rep.space < 1000000) {
3075                 bprefix = _("kilo");
3076                 space_adjusted = truncf((float)rep.space / 1000.0);
3077         } else if (rep.space < 1000000 * 1000) {
3078                 bprefix = _("mega");
3079                 space_adjusted = truncf((float)rep.space / (1000.0 * 1000.0));
3080         } else {
3081                 bprefix = _("giga");
3082                 space_adjusted = truncf((float)rep.space / (1000.0 * 1000 * 1000.0));
3083         }
3084
3085         if (msg_delete) {
3086                 txt.set_markup (string_compose (P_("\
3087 The following file was deleted from %2,\n\
3088 releasing %3 %4bytes of disk space", "\
3089 The following %1 files were deleted from %2,\n\
3090 releasing %3 %4bytes of disk space", removed),
3091                                         removed, Glib::Markup::escape_text (dead_directory), space_adjusted, bprefix, PROGRAM_NAME));
3092         } else {
3093                 txt.set_markup (string_compose (P_("\
3094 The following file was not in use and \n\
3095 has been moved to: %2\n\n\
3096 After a restart of %5\n\n\
3097 <span face=\"mono\">Session -> Clean-up -> Flush Wastebasket</span>\n\n\
3098 will release an additional %3 %4bytes of disk space.\n", "\
3099 The following %1 files were not in use and \n\
3100 have been moved to: %2\n\n\
3101 After a restart of %5\n\n\
3102 <span face=\"mono\">Session -> Clean-up -> Flush Wastebasket</span>\n\n\
3103 will release an additional %3 %4bytes of disk space.\n", removed),
3104                                         removed, Glib::Markup::escape_text (dead_directory), space_adjusted, bprefix, PROGRAM_NAME));
3105         }
3106
3107         dhbox.pack_start (*dimage, true, false, 5);
3108         dhbox.pack_start (txt, true, false, 5);
3109
3110         for (vector<string>::iterator i = rep.paths.begin(); i != rep.paths.end(); ++i) {
3111                 TreeModel::Row row = *(results_model->append());
3112                 row[results_columns.visible_name] = *i;
3113                 row[results_columns.fullpath] = *i;
3114         }
3115
3116         list_scroller.add (results_display);
3117         list_scroller.set_size_request (-1, 150);
3118         list_scroller.set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
3119
3120         dvbox.pack_start (dhbox, true, false, 5);
3121         dvbox.pack_start (list_scroller, true, false, 5);
3122         ddhbox.pack_start (dvbox, true, false, 5);
3123
3124         results.get_vbox()->pack_start (ddhbox, true, false, 5);
3125         results.add_button (Stock::CLOSE, RESPONSE_CLOSE);
3126         results.set_default_response (RESPONSE_CLOSE);
3127         results.set_position (Gtk::WIN_POS_MOUSE);
3128
3129         results_display.show();
3130         list_scroller.show();
3131         txt.show();
3132         dvbox.show();
3133         dhbox.show();
3134         ddhbox.show();
3135         dimage->show();
3136
3137         //results.get_vbox()->show();
3138         results.set_resizable (false);
3139
3140         results.run ();
3141
3142 }
3143
3144 void
3145 ARDOUR_UI::cleanup ()
3146 {
3147         if (_session == 0) {
3148                 /* shouldn't happen: menu item is insensitive */
3149                 return;
3150         }
3151
3152
3153         MessageDialog checker (_("Are you sure you want to clean-up?"),
3154                                 true,
3155                                 Gtk::MESSAGE_QUESTION,
3156                                 Gtk::BUTTONS_NONE);
3157
3158         checker.set_title (_("Clean-up"));
3159
3160         checker.set_secondary_text(_("Clean-up is a destructive operation.\n\
3161 ALL undo/redo information will be lost if you clean-up.\n\
3162 Clean-up will move all unused files to a \"dead\" location."));
3163
3164         checker.add_button (Stock::CANCEL, RESPONSE_CANCEL);
3165         checker.add_button (_("Clean-up"), RESPONSE_ACCEPT);
3166         checker.set_default_response (RESPONSE_CANCEL);
3167
3168         checker.set_name (_("CleanupDialog"));
3169         checker.set_wmclass (X_("ardour_cleanup"), PROGRAM_NAME);
3170         checker.set_position (Gtk::WIN_POS_MOUSE);
3171
3172         switch (checker.run()) {
3173         case RESPONSE_ACCEPT:
3174                 break;
3175         default:
3176                 return;
3177         }
3178
3179         ARDOUR::CleanupReport rep;
3180
3181         editor->prepare_for_cleanup ();
3182
3183         /* do not allow flush until a session is reloaded */
3184
3185         Glib::RefPtr<Action> act = ActionManager::get_action (X_("Main"), X_("FlushWastebasket"));
3186         if (act) {
3187                 act->set_sensitive (false);
3188         }
3189
3190         if (_session->cleanup_sources (rep)) {
3191                 editor->finish_cleanup ();
3192                 return;
3193         }
3194
3195         editor->finish_cleanup ();
3196
3197         checker.hide();
3198         display_cleanup_results (rep, _("Cleaned Files"), false);
3199 }
3200
3201 void
3202 ARDOUR_UI::flush_trash ()
3203 {
3204         if (_session == 0) {
3205                 /* shouldn't happen: menu item is insensitive */
3206                 return;
3207         }
3208
3209         ARDOUR::CleanupReport rep;
3210
3211         if (_session->cleanup_trash_sources (rep)) {
3212                 return;
3213         }
3214
3215         display_cleanup_results (rep, _("deleted file"), true);
3216 }
3217
3218 void
3219 ARDOUR_UI::add_route (Gtk::Window* float_window)
3220 {
3221         int count;
3222
3223         if (!_session) {
3224                 return;
3225         }
3226
3227         if (add_route_dialog->is_visible()) {
3228                 /* we're already doing this */
3229                 return;
3230         }
3231
3232         if (float_window) {
3233                 add_route_dialog->set_transient_for (*float_window);
3234         }
3235
3236         ResponseType r = (ResponseType) add_route_dialog->run ();
3237
3238         add_route_dialog->hide();
3239
3240         switch (r) {
3241                 case RESPONSE_ACCEPT:
3242                         break;
3243                 default:
3244                         return;
3245                         break;
3246         }
3247
3248         if ((count = add_route_dialog->count()) <= 0) {
3249                 return;
3250         }
3251
3252         PBD::ScopedConnection idle_connection;
3253
3254         if (count > 8) {
3255                 ARDOUR::GUIIdle.connect (idle_connection, MISSING_INVALIDATOR, boost::bind (&Gtkmm2ext::UI::flush_pending, this), gui_context());
3256         }
3257
3258         string template_path = add_route_dialog->track_template();
3259
3260         if (!template_path.empty()) {
3261                 if (add_route_dialog->name_template_is_default())  {
3262                         _session->new_route_from_template (count, template_path, string());
3263                 } else {
3264                         _session->new_route_from_template (count, template_path, add_route_dialog->name_template());
3265                 }
3266                 return;
3267         }
3268
3269         ChanCount input_chan= add_route_dialog->channels ();
3270         ChanCount output_chan;
3271         string name_template = add_route_dialog->name_template ();
3272         PluginInfoPtr instrument = add_route_dialog->requested_instrument ();
3273         RouteGroup* route_group = add_route_dialog->route_group ();
3274         AutoConnectOption oac = Config->get_output_auto_connect();
3275
3276         if (oac & AutoConnectMaster) {
3277                 output_chan.set (DataType::AUDIO, (_session->master_out() ? _session->master_out()->n_inputs().n_audio() : input_chan.n_audio()));
3278                 output_chan.set (DataType::MIDI, 0);
3279         } else {
3280                 output_chan = input_chan;
3281         }
3282
3283         /* XXX do something with name template */
3284
3285         switch (add_route_dialog->type_wanted()) {
3286         case AddRouteDialog::AudioTrack:
3287                 session_add_audio_track (input_chan.n_audio(), output_chan.n_audio(), add_route_dialog->mode(), route_group, count, name_template);
3288                 break;
3289         case AddRouteDialog::MidiTrack:
3290                 session_add_midi_track (route_group, count, name_template, instrument);
3291                 break;
3292         case AddRouteDialog::MixedTrack:
3293                 session_add_mixed_track (input_chan, output_chan, route_group, count, name_template, instrument);
3294                 break;
3295         case AddRouteDialog::AudioBus:
3296                 session_add_audio_bus (input_chan.n_audio(), output_chan.n_audio(), route_group, count, name_template);
3297                 break;
3298         }
3299
3300         /* idle connection will end at scope end */
3301 }
3302
3303 void
3304 ARDOUR_UI::stop_video_server (bool ask_confirm)
3305 {
3306         if (!video_server_process && ask_confirm) {
3307                 warning << _("Video-Server was not launched by Ardour. The request to stop it is ignored.") << endmsg;
3308         }
3309         if (video_server_process) {
3310                 if(ask_confirm) {
3311                         ArdourDialog confirm (_("Stop Video-Server"), true);
3312                         Label m (_("Do you really want to stop the Video Server?"));
3313                         confirm.get_vbox()->pack_start (m, true, true);
3314                         confirm.add_button (Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
3315                         confirm.add_button (_("Yes, Stop It"), Gtk::RESPONSE_ACCEPT);
3316                         confirm.show_all ();
3317                         if (confirm.run() == RESPONSE_CANCEL) {
3318                                 return;
3319                         }
3320                 }
3321                 delete video_server_process;
3322                 video_server_process =0;
3323         }
3324 }
3325
3326 void
3327 ARDOUR_UI::start_video_server_menu (Gtk::Window* float_window)
3328 {
3329   ARDOUR_UI::start_video_server( float_window, true);
3330 }
3331
3332 bool
3333 ARDOUR_UI::start_video_server (Gtk::Window* float_window, bool popup_msg)
3334 {
3335         if (!_session) {
3336                 return false;
3337         }
3338         if (popup_msg) {
3339                 if (ARDOUR_UI::instance()->video_timeline->check_server()) {
3340                         if (video_server_process) {
3341                                 popup_error(_("The Video Server is already started."));
3342                         } else {
3343                                 popup_error(_("An external Video Server is configured and can be reached. Not starting a new instance."));
3344                         }
3345                 }
3346         }
3347
3348         int firsttime = 0;
3349         while (!ARDOUR_UI::instance()->video_timeline->check_server()) {
3350                 if (firsttime++) {
3351                         warning << _("Could not connect to the Video Server. Start it or configure its access URL in Edit -> Preferences.") << endmsg;
3352                 }
3353                 VideoServerDialog *video_server_dialog = new VideoServerDialog (_session);
3354                 if (float_window) {
3355                         video_server_dialog->set_transient_for (*float_window);
3356                 }
3357
3358                 if (!Config->get_show_video_server_dialog() && firsttime < 2) {
3359                         video_server_dialog->hide();
3360                 } else {
3361                         ResponseType r = (ResponseType) video_server_dialog->run ();
3362                         video_server_dialog->hide();
3363                         if (r != RESPONSE_ACCEPT) { return false; }
3364                         if (video_server_dialog->show_again()) {
3365                                 Config->set_show_video_server_dialog(false);
3366                         }
3367                 }
3368
3369                 std::string icsd_exec = video_server_dialog->get_exec_path();
3370                 std::string icsd_docroot = video_server_dialog->get_docroot();
3371                 if (icsd_docroot.empty()) {icsd_docroot = X_("/");}
3372
3373                 struct stat sb;
3374                 if (!g_lstat (icsd_docroot.c_str(), &sb) == 0 || !S_ISDIR(sb.st_mode)) {
3375                         warning << _("Specified docroot is not an existing directory.") << endmsg;
3376                         continue;
3377                 }
3378 #ifndef WIN32
3379                 if ( (!g_lstat (icsd_exec.c_str(), &sb) == 0)
3380                      || (sb.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0 ) {
3381                         warning << _("Given Video Server is not an executable file.") << endmsg;
3382                         continue;
3383                 }
3384 #else
3385                 if ( (!g_lstat (icsd_exec.c_str(), &sb) == 0)
3386                      || (sb.st_mode & (S_IXUSR)) == 0 ) {
3387                         warning << _("Given Video Server is not an executable file.") << endmsg;
3388                         continue;
3389                 }
3390 #endif
3391
3392                 char **argp;
3393                 argp=(char**) calloc(9,sizeof(char*));
3394                 argp[0] = strdup(icsd_exec.c_str());
3395                 argp[1] = strdup("-P");
3396                 argp[2] = (char*) calloc(16,sizeof(char)); snprintf(argp[2], 16, "%s", video_server_dialog->get_listenaddr().c_str());
3397                 argp[3] = strdup("-p");
3398                 argp[4] = (char*) calloc(6,sizeof(char)); snprintf(argp[4], 6, "%i", video_server_dialog->get_listenport());
3399                 argp[5] = strdup("-C");
3400                 argp[6] = (char*) calloc(6,sizeof(char)); snprintf(argp[6], 6, "%i", video_server_dialog->get_cachesize());
3401                 argp[7] = strdup(icsd_docroot.c_str());
3402                 argp[8] = 0;
3403                 stop_video_server();
3404
3405                 if (icsd_docroot == X_("/")) {
3406                         Config->set_video_advanced_setup(false);
3407                 } else {
3408                         std::ostringstream osstream;
3409                         osstream << "http://localhost:" << video_server_dialog->get_listenport() << "/";
3410                         Config->set_video_server_url(osstream.str());
3411                         Config->set_video_server_docroot(icsd_docroot);
3412                         Config->set_video_advanced_setup(true);
3413                 }
3414
3415                 if (video_server_process) {
3416                         delete video_server_process;
3417                 }
3418
3419                 video_server_process = new SystemExec(icsd_exec, argp);
3420                 if (video_server_process->start()) {
3421                         warning << _("Cannot launch the video-server") << endmsg;
3422                         continue;
3423                 }
3424                 int timeout = 120; // 6 sec
3425                 while (!ARDOUR_UI::instance()->video_timeline->check_server()) {
3426                         usleep (50000);
3427                         if (--timeout <= 0 || !video_server_process->is_running()) break;
3428                 }
3429                 if (timeout <= 0) {
3430                         warning << _("Video-server was started but does not respond to requests...") << endmsg;
3431                 } else {
3432                         if (!ARDOUR_UI::instance()->video_timeline->check_server_docroot()) {
3433                                 delete video_server_process;
3434                                 video_server_process = 0;
3435                         }
3436                 }
3437         }
3438         return true;
3439 }
3440
3441 void
3442 ARDOUR_UI::add_video (Gtk::Window* float_window)
3443 {
3444         if (!_session) {
3445                 return;
3446         }
3447
3448         if (!start_video_server(float_window, false)) {
3449                 warning << _("Could not connect to the Video Server. Start it or configure its access URL in Edit -> Preferences.") << endmsg;
3450                 return;
3451         }
3452
3453         if (float_window) {
3454                 add_video_dialog->set_transient_for (*float_window);
3455         }
3456
3457         if (add_video_dialog->is_visible()) {
3458                 /* we're already doing this */
3459                 return;
3460         }
3461
3462         ResponseType r = (ResponseType) add_video_dialog->run ();
3463         add_video_dialog->hide();
3464         if (r != RESPONSE_ACCEPT) { return; }
3465
3466         bool local_file, orig_local_file;
3467         std::string path = add_video_dialog->file_name(local_file);
3468
3469         std::string orig_path = path;
3470         orig_local_file = local_file;
3471
3472         bool auto_set_session_fps = add_video_dialog->auto_set_session_fps();
3473
3474         if (local_file && !Glib::file_test(path, Glib::FILE_TEST_EXISTS)) {
3475                 warning << string_compose(_("could not open %1"), path) << endmsg;
3476                 return;
3477         }
3478         if (!local_file && path.length() == 0) {
3479                 warning << _("no video-file selected") << endmsg;
3480                 return;
3481         }
3482
3483         switch (add_video_dialog->import_option()) {
3484                 case VTL_IMPORT_TRANSCODE:
3485                         {
3486                                 TranscodeVideoDialog *transcode_video_dialog;
3487                                 transcode_video_dialog = new TranscodeVideoDialog (_session, path);
3488                                 ResponseType r = (ResponseType) transcode_video_dialog->run ();
3489                                 transcode_video_dialog->hide();
3490                                 if (r != RESPONSE_ACCEPT) {
3491                                         delete transcode_video_dialog;
3492                                         return;
3493                                 }
3494                                 if (!transcode_video_dialog->get_audiofile().empty()) {
3495                                         editor->embed_audio_from_video(
3496                                                         transcode_video_dialog->get_audiofile(),
3497                                                         video_timeline->get_offset()
3498                                                         );
3499                                 }
3500                                 switch (transcode_video_dialog->import_option()) {
3501                                         case VTL_IMPORT_TRANSCODED:
3502                                                 path = transcode_video_dialog->get_filename();
3503                                                 local_file = true;
3504                                                 break;
3505                                         case VTL_IMPORT_REFERENCE:
3506                                                 break;
3507                                         default:
3508                                                 delete transcode_video_dialog;
3509                                                 return;
3510                                 }
3511                                 delete transcode_video_dialog;
3512                         }
3513                         break;
3514                 default:
3515                 case VTL_IMPORT_NONE:
3516                         break;
3517         }
3518
3519         /* strip _session->session_directory().video_path() from video file if possible */
3520         if (local_file && !path.compare(0, _session->session_directory().video_path().size(), _session->session_directory().video_path())) {
3521                  path=path.substr(_session->session_directory().video_path().size());
3522                  if (path.at(0) == G_DIR_SEPARATOR) {
3523                          path=path.substr(1);
3524                  }
3525         }
3526
3527         video_timeline->set_update_session_fps(auto_set_session_fps);
3528         if (video_timeline->video_file_info(path, local_file)) {
3529                 XMLNode* node = new XMLNode(X_("Videotimeline"));
3530                 node->add_property (X_("Filename"), path);
3531                 node->add_property (X_("AutoFPS"), auto_set_session_fps?X_("1"):X_("0"));
3532                 node->add_property (X_("LocalFile"), local_file?X_("1"):X_("0"));
3533                 if (orig_local_file) {
3534                         node->add_property (X_("OriginalVideoFile"), orig_path);
3535                 } else {
3536                         node->remove_property (X_("OriginalVideoFile"));
3537                 }
3538                 _session->add_extra_xml (*node);
3539                 _session->set_dirty ();
3540
3541                 _session->maybe_update_session_range(
3542                         std::max(video_timeline->get_offset(), (ARDOUR::frameoffset_t) 0),
3543                         std::max(video_timeline->get_offset() + video_timeline->get_duration(), (ARDOUR::frameoffset_t) 0));
3544
3545
3546                 if (add_video_dialog->launch_xjadeo() && local_file) {
3547                         editor->set_xjadeo_sensitive(true);
3548                         editor->toggle_xjadeo_proc(1);
3549                 } else {
3550                         editor->toggle_xjadeo_proc(0);
3551                 }
3552                 editor->toggle_ruler_video(true);
3553         }
3554 }
3555
3556 void
3557 ARDOUR_UI::remove_video ()
3558 {
3559         video_timeline->close_session();
3560         editor->toggle_ruler_video(false);
3561
3562         /* reset state */
3563         video_timeline->set_offset_locked(false);
3564         video_timeline->set_offset(0);
3565
3566         /* delete session state */
3567         XMLNode* node = new XMLNode(X_("Videotimeline"));
3568         _session->add_extra_xml(*node);
3569         node = new XMLNode(X_("Videomonitor"));
3570         _session->add_extra_xml(*node);
3571         stop_video_server();
3572 }
3573
3574 void
3575 ARDOUR_UI::flush_videotimeline_cache (bool localcacheonly)
3576 {
3577         if (localcacheonly) {
3578                 video_timeline->vmon_update();
3579         } else {
3580                 video_timeline->flush_cache();
3581         }
3582         editor->queue_visual_videotimeline_update();
3583 }
3584
3585 XMLNode*
3586 ARDOUR_UI::mixer_settings () const
3587 {
3588         XMLNode* node = 0;
3589
3590         if (_session) {
3591                 node = _session->instant_xml(X_("Mixer"));
3592         } else {
3593                 node = Config->instant_xml(X_("Mixer"));
3594         }
3595
3596         if (!node) {
3597                 node = new XMLNode (X_("Mixer"));
3598         }
3599
3600         return node;
3601 }
3602
3603 XMLNode*
3604 ARDOUR_UI::editor_settings () const
3605 {
3606         XMLNode* node = 0;
3607
3608         if (_session) {
3609                 node = _session->instant_xml(X_("Editor"));
3610         } else {
3611                 node = Config->instant_xml(X_("Editor"));
3612         }
3613
3614         if (!node) {
3615                 if (getenv("ARDOUR_INSTANT_XML_PATH")) {
3616                         node = Config->instant_xml(getenv("ARDOUR_INSTANT_XML_PATH"));
3617                 }
3618         }
3619
3620         if (!node) {
3621                 node = new XMLNode (X_("Editor"));
3622         }
3623
3624         return node;
3625 }
3626
3627 XMLNode*
3628 ARDOUR_UI::keyboard_settings () const
3629 {
3630         XMLNode* node = 0;
3631
3632         node = Config->extra_xml(X_("Keyboard"));
3633
3634         if (!node) {
3635                 node = new XMLNode (X_("Keyboard"));
3636         }
3637
3638         return node;
3639 }
3640
3641 void
3642 ARDOUR_UI::create_xrun_marker (framepos_t where)
3643 {
3644         editor->mouse_add_new_marker (where, false, true);
3645 }
3646
3647 void
3648 ARDOUR_UI::halt_on_xrun_message ()
3649 {
3650         MessageDialog msg (*editor,
3651                            _("Recording was stopped because your system could not keep up."));
3652         msg.run ();
3653 }
3654
3655 void
3656 ARDOUR_UI::xrun_handler (framepos_t where)
3657 {
3658         if (!_session) {
3659                 return;
3660         }
3661
3662         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::xrun_handler, where)
3663
3664         if (_session && Config->get_create_xrun_marker() && _session->actively_recording()) {
3665                 create_xrun_marker(where);
3666         }
3667
3668         if (_session && Config->get_stop_recording_on_xrun() && _session->actively_recording()) {
3669                 halt_on_xrun_message ();
3670         }
3671 }
3672
3673 void
3674 ARDOUR_UI::disk_overrun_handler ()
3675 {
3676         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::disk_overrun_handler)
3677
3678         if (!have_disk_speed_dialog_displayed) {
3679                 have_disk_speed_dialog_displayed = true;
3680                 MessageDialog* msg = new MessageDialog (*editor, string_compose (_("\
3681 The disk system on your computer\n\
3682 was not able to keep up with %1.\n\
3683 \n\
3684 Specifically, it failed to write data to disk\n\
3685 quickly enough to keep up with recording.\n"), PROGRAM_NAME));
3686                 msg->signal_response().connect (sigc::bind (sigc::mem_fun (*this, &ARDOUR_UI::disk_speed_dialog_gone), msg));
3687                 msg->show ();
3688         }
3689 }
3690
3691 void
3692 ARDOUR_UI::disk_underrun_handler ()
3693 {
3694         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::disk_underrun_handler)
3695
3696         if (!have_disk_speed_dialog_displayed) {
3697                 have_disk_speed_dialog_displayed = true;
3698                 MessageDialog* msg = new MessageDialog (
3699                         *editor, string_compose (_("The disk system on your computer\n\
3700 was not able to keep up with %1.\n\
3701 \n\
3702 Specifically, it failed to read data from disk\n\
3703 quickly enough to keep up with playback.\n"), PROGRAM_NAME));
3704                 msg->signal_response().connect (sigc::bind (sigc::mem_fun (*this, &ARDOUR_UI::disk_speed_dialog_gone), msg));
3705                 msg->show ();
3706         }
3707 }
3708
3709 void
3710 ARDOUR_UI::disk_speed_dialog_gone (int /*ignored_response*/, MessageDialog* msg)
3711 {
3712         have_disk_speed_dialog_displayed = false;
3713         delete msg;
3714 }
3715
3716 void
3717 ARDOUR_UI::session_dialog (std::string msg)
3718 {
3719         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::session_dialog, msg)
3720
3721         MessageDialog* d;
3722
3723         if (editor) {
3724                 d = new MessageDialog (*editor, msg, false, MESSAGE_INFO, BUTTONS_OK, true);
3725         } else {
3726                 d = new MessageDialog (msg, false, MESSAGE_INFO, BUTTONS_OK, true);
3727         }
3728
3729         d->show_all ();
3730         d->run ();
3731         delete d;
3732 }
3733
3734 int
3735 ARDOUR_UI::pending_state_dialog ()
3736 {
3737         HBox* hbox = new HBox();
3738         Image* image = new Image (Stock::DIALOG_QUESTION, ICON_SIZE_DIALOG);
3739         ArdourDialog dialog (_("Crash Recovery"), true);
3740         Label  message (string_compose (_("\
3741 This session appears to have been in the\n\
3742 middle of recording when %1 or\n\
3743 the computer was shutdown.\n\
3744 \n\
3745 %1 can recover any captured audio for\n\
3746 you, or it can ignore it. Please decide\n\
3747 what you would like to do.\n"), PROGRAM_NAME));
3748         image->set_alignment(ALIGN_CENTER, ALIGN_TOP);
3749         hbox->pack_start (*image, PACK_EXPAND_WIDGET, 12);
3750         hbox->pack_end (message, PACK_EXPAND_PADDING, 12);
3751         dialog.get_vbox()->pack_start(*hbox, PACK_EXPAND_PADDING, 6);
3752         dialog.add_button (_("Ignore crash data"), RESPONSE_REJECT);
3753         dialog.add_button (_("Recover from crash"), RESPONSE_ACCEPT);
3754         dialog.set_default_response (RESPONSE_ACCEPT);
3755         dialog.set_position (WIN_POS_CENTER);
3756         message.show();
3757         image->show();
3758         hbox->show();
3759
3760         switch (dialog.run ()) {
3761         case RESPONSE_ACCEPT:
3762                 return 1;
3763         default:
3764                 return 0;
3765         }
3766 }
3767
3768 int
3769 ARDOUR_UI::sr_mismatch_dialog (framecnt_t desired, framecnt_t actual)
3770 {
3771         HBox* hbox = new HBox();
3772         Image* image = new Image (Stock::DIALOG_WARNING, ICON_SIZE_DIALOG);
3773         ArdourDialog dialog (_("Sample Rate Mismatch"), true);
3774         Label  message (string_compose (_("\
3775 This session was created with a sample rate of %1 Hz, but\n\
3776 %2 is currently running at %3 Hz.  If you load this session,\n\
3777 audio may be played at the wrong sample rate.\n"), desired, PROGRAM_NAME, actual));
3778
3779         image->set_alignment(ALIGN_CENTER, ALIGN_TOP);
3780         hbox->pack_start (*image, PACK_EXPAND_WIDGET, 12);
3781         hbox->pack_end (message, PACK_EXPAND_PADDING, 12);
3782         dialog.get_vbox()->pack_start(*hbox, PACK_EXPAND_PADDING, 6);
3783         dialog.add_button (_("Do not load session"), RESPONSE_REJECT);
3784         dialog.add_button (_("Load session anyway"), RESPONSE_ACCEPT);
3785         dialog.set_default_response (RESPONSE_ACCEPT);
3786         dialog.set_position (WIN_POS_CENTER);
3787         message.show();
3788         image->show();
3789         hbox->show();
3790
3791         switch (dialog.run()) {
3792         case RESPONSE_ACCEPT:
3793                 return 0;
3794         default:
3795                 break;
3796         }
3797
3798         return 1;
3799 }
3800
3801 void
3802 ARDOUR_UI::disconnect_from_engine ()
3803 {
3804         /* drop connection to AudioEngine::Halted so that we don't act
3805          *  as if the engine unexpectedly shut down
3806          */
3807         halt_connection.disconnect ();
3808         
3809         if (AudioEngine::instance()->stop ()) {
3810                 MessageDialog msg (*editor, _("Could not disconnect from JACK"));
3811                 msg.run ();
3812         } else {
3813                 AudioEngine::instance()->Halted.connect_same_thread (halt_connection, boost::bind (&ARDOUR_UI::engine_halted, this, _1, false));
3814         }
3815         
3816         update_sample_rate (0);
3817 }
3818
3819 void
3820 ARDOUR_UI::reconnect_to_engine ()
3821 {
3822         if (AudioEngine::instance()->start ()) {
3823                 MessageDialog msg (*editor,  _("Could not reconnect to JACK"));
3824                 msg.run ();
3825         }
3826         
3827         update_sample_rate (0);
3828 }
3829
3830 void
3831 ARDOUR_UI::use_config ()
3832 {
3833         XMLNode* node = Config->extra_xml (X_("TransportControllables"));
3834         if (node) {
3835                 set_transport_controllable_state (*node);
3836         }
3837 }
3838
3839 void
3840 ARDOUR_UI::update_transport_clocks (framepos_t pos)
3841 {
3842         if (Config->get_primary_clock_delta_edit_cursor()) {
3843                 primary_clock->set (pos, false, editor->get_preferred_edit_position());
3844         } else {
3845                 primary_clock->set (pos);
3846         }
3847
3848         if (Config->get_secondary_clock_delta_edit_cursor()) {
3849                 secondary_clock->set (pos, false, editor->get_preferred_edit_position());
3850         } else {
3851                 secondary_clock->set (pos);
3852         }
3853
3854         if (big_clock_window) {
3855                 big_clock->set (pos);
3856         }
3857         ARDOUR_UI::instance()->video_timeline->manual_seek_video_monitor(pos);
3858 }
3859
3860 void
3861 ARDOUR_UI::step_edit_status_change (bool yn)
3862 {
3863         // XXX should really store pre-step edit status of things
3864         // we make insensitive
3865
3866         if (yn) {
3867                 rec_button.set_active_state (Gtkmm2ext::ImplicitActive);
3868                 rec_button.set_sensitive (false);
3869         } else {
3870                 rec_button.unset_active_state ();;
3871                 rec_button.set_sensitive (true);
3872         }
3873 }
3874
3875 void
3876 ARDOUR_UI::record_state_changed ()
3877 {
3878         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::record_state_changed);
3879
3880         if (!_session || !big_clock_window) {
3881                 /* why bother - the clock isn't visible */
3882                 return;
3883         }
3884
3885         if (_session->record_status () == Session::Recording && _session->have_rec_enabled_track ()) {
3886                 big_clock->set_active (true);
3887         } else {
3888                 big_clock->set_active (false);
3889         }
3890 }
3891
3892 bool
3893 ARDOUR_UI::first_idle ()
3894 {
3895         if (_session) {
3896                 _session->allow_auto_play (true);
3897         }
3898
3899         if (editor) {
3900                 editor->first_idle();
3901         }
3902
3903         Keyboard::set_can_save_keybindings (true);
3904         return false;
3905 }
3906
3907 void
3908 ARDOUR_UI::store_clock_modes ()
3909 {
3910         XMLNode* node = new XMLNode(X_("ClockModes"));
3911
3912         for (vector<AudioClock*>::iterator x = AudioClock::clocks.begin(); x != AudioClock::clocks.end(); ++x) {
3913                 XMLNode* child = new XMLNode (X_("Clock"));
3914                 
3915                 child->add_property (X_("name"), (*x)->name());
3916                 child->add_property (X_("mode"), enum_2_string ((*x)->mode()));
3917                 child->add_property (X_("on"), ((*x)->off() ? X_("no") : X_("yes")));
3918
3919                 node->add_child_nocopy (*child);
3920         }
3921
3922         _session->add_extra_xml (*node);
3923         _session->set_dirty ();
3924 }
3925
3926 ARDOUR_UI::TransportControllable::TransportControllable (std::string name, ARDOUR_UI& u, ToggleType tp)
3927         : Controllable (name), ui (u), type(tp)
3928 {
3929
3930 }
3931
3932 void
3933 ARDOUR_UI::TransportControllable::set_value (double val)
3934 {
3935         if (val < 0.5) {
3936                 /* do nothing: these are radio-style actions */
3937                 return;
3938         }
3939
3940         const char *action = 0;
3941
3942         switch (type) {
3943         case Roll:
3944                 action = X_("Roll");
3945                 break;
3946         case Stop:
3947                 action = X_("Stop");
3948                 break;
3949         case GotoStart:
3950                 action = X_("GotoStart");
3951                 break;
3952         case GotoEnd:
3953                 action = X_("GotoEnd");
3954                 break;
3955         case AutoLoop:
3956                 action = X_("Loop");
3957                 break;
3958         case PlaySelection:
3959                 action = X_("PlaySelection");
3960                 break;
3961         case RecordEnable:
3962                 action = X_("Record");
3963                 break;
3964         default:
3965                 break;
3966         }
3967
3968         if (action == 0) {
3969                 return;
3970         }
3971
3972         Glib::RefPtr<Action> act = ActionManager::get_action ("Transport", action);
3973
3974         if (act) {
3975                 act->activate ();
3976         }
3977 }
3978
3979 double
3980 ARDOUR_UI::TransportControllable::get_value (void) const
3981 {
3982         float val = 0.0;
3983
3984         switch (type) {
3985         case Roll:
3986                 break;
3987         case Stop:
3988                 break;
3989         case GotoStart:
3990                 break;
3991         case GotoEnd:
3992                 break;
3993         case AutoLoop:
3994                 break;
3995         case PlaySelection:
3996                 break;
3997         case RecordEnable:
3998                 break;
3999         default:
4000                 break;
4001         }
4002
4003         return val;
4004 }
4005
4006 void
4007 ARDOUR_UI::setup_profile ()
4008 {
4009         if (gdk_screen_width() < 1200 || getenv ("ARDOUR_NARROW_SCREEN")) {
4010                 Profile->set_small_screen ();
4011         }
4012
4013         if (getenv ("ARDOUR_SAE")) {
4014                 Profile->set_sae ();
4015                 Profile->set_single_package ();
4016         }
4017 }
4018
4019 int
4020 ARDOUR_UI::missing_file (Session*s, std::string str, DataType type)
4021 {
4022         MissingFileDialog dialog (s, str, type);
4023
4024         dialog.show ();
4025         dialog.present ();
4026
4027         int result = dialog.run ();
4028         dialog.hide ();
4029
4030         switch (result) {
4031         case RESPONSE_OK:
4032                 break;
4033         default:
4034                 return 1; // quit entire session load
4035         }
4036
4037         result = dialog.get_action ();
4038
4039         return result;
4040 }
4041
4042 int
4043 ARDOUR_UI::ambiguous_file (std::string file, std::vector<std::string> hits)
4044 {
4045         AmbiguousFileDialog dialog (file, hits);
4046
4047         dialog.show ();
4048         dialog.present ();
4049
4050         dialog.run ();
4051         return dialog.get_which ();
4052 }
4053
4054 /** Allocate our thread-local buffers */
4055 void
4056 ARDOUR_UI::get_process_buffers ()
4057 {
4058         _process_thread->get_buffers ();
4059 }
4060
4061 /** Drop our thread-local buffers */
4062 void
4063 ARDOUR_UI::drop_process_buffers ()
4064 {
4065         _process_thread->drop_buffers ();
4066 }
4067
4068 void
4069 ARDOUR_UI::feedback_detected ()
4070 {
4071         _feedback_exists = true;
4072 }
4073
4074 void
4075 ARDOUR_UI::successful_graph_sort ()
4076 {
4077         _feedback_exists = false;
4078 }
4079
4080 void
4081 ARDOUR_UI::midi_panic ()
4082 {
4083         if (_session) {
4084                 _session->midi_panic();
4085         }
4086 }
4087
4088 void
4089 ARDOUR_UI::session_format_mismatch (std::string xml_path, std::string backup_path)
4090 {
4091         const char* start_big = "<span size=\"x-large\" weight=\"bold\">";
4092         const char* end_big = "</span>";
4093         const char* start_mono = "<tt>";
4094         const char* end_mono = "</tt>";
4095
4096         MessageDialog msg (string_compose (_("%4This is a session from an older version of %3%5\n\n"
4097                                              "%3 has copied the old session file\n\n%6%1%7\n\nto\n\n%6%2%7\n\n"
4098                                              "From now on, use the -2000 version with older versions of %3"),
4099                                            xml_path, backup_path, PROGRAM_NAME,
4100                                            start_big, end_big,
4101                                            start_mono, end_mono), true);
4102
4103         msg.run ();
4104 }
4105
4106
4107 void
4108 ARDOUR_UI::reset_peak_display ()
4109 {
4110         if (!_session || !_session->master_out() || !editor_meter) return;
4111         editor_meter->clear_meters();
4112         editor_meter_max_peak = -INFINITY;
4113         editor_meter_peak_display.set_name ("meterbridge peakindicator");
4114         editor_meter_peak_display.set_elements((ArdourButton::Element) (ArdourButton::Edge|ArdourButton::Body));
4115 }
4116
4117 void
4118 ARDOUR_UI::reset_group_peak_display (RouteGroup* group)
4119 {
4120         if (!_session || !_session->master_out()) return;
4121         if (group == _session->master_out()->route_group()) {
4122                 reset_peak_display ();
4123         }
4124 }
4125
4126 void
4127 ARDOUR_UI::reset_route_peak_display (Route* route)
4128 {
4129         if (!_session || !_session->master_out()) return;
4130         if (_session->master_out().get() == route) {
4131                 reset_peak_display ();
4132         }
4133 }
4134
4135 void
4136 ARDOUR_UI::toggle_audio_midi_setup ()
4137 {
4138         Glib::RefPtr<Action> act = ActionManager::get_action (X_("Common"), X_("toggle-audio-midi-setup"));
4139         if (!act) {
4140                 return;
4141         }
4142
4143         Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic (act);
4144
4145         if (tact->get_active()) {
4146                 launch_audio_midi_setup ();
4147         } else {
4148                 _audio_midi_setup->hide ();
4149         }
4150 }
4151
4152 void
4153 ARDOUR_UI::launch_audio_midi_setup ()
4154 {
4155         if (!_audio_midi_setup) {
4156                 _audio_midi_setup = new EngineControl ();
4157         }
4158
4159         _audio_midi_setup->present ();
4160 }
4161                                                 
4162 int
4163 ARDOUR_UI::do_audio_midi_setup (uint32_t desired_sample_rate)
4164 {
4165         launch_audio_midi_setup ();
4166
4167         _audio_midi_setup->set_desired_sample_rate (desired_sample_rate);
4168
4169         int r = _audio_midi_setup->run ();
4170
4171         switch (r) {
4172         case Gtk::RESPONSE_OK:
4173                 return 0;
4174         case Gtk::RESPONSE_APPLY:
4175                 return 0;
4176         default:
4177                 return -1;
4178         }
4179 }