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