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