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