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