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