b4399b03fa932817bc2d2663ba0028bd6fd3bb15
[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         fst_stop_threading();
1017 #endif
1018         quit ();
1019 }
1020
1021 int
1022 ARDOUR_UI::ask_about_saving_session (const vector<string>& actions)
1023 {
1024         ArdourDialog window (_("Unsaved Session"));
1025         Gtk::HBox dhbox;  // the hbox for the image and text
1026         Gtk::Label  prompt_label;
1027         Gtk::Image* dimage = manage (new Gtk::Image(Stock::DIALOG_WARNING,  Gtk::ICON_SIZE_DIALOG));
1028
1029         string msg;
1030
1031         assert (actions.size() >= 3);
1032
1033         window.add_button (actions[0], RESPONSE_REJECT);
1034         window.add_button (actions[1], RESPONSE_APPLY);
1035         window.add_button (actions[2], RESPONSE_ACCEPT);
1036
1037         window.set_default_response (RESPONSE_ACCEPT);
1038
1039         Gtk::Button noquit_button (msg);
1040         noquit_button.set_name ("EditorGTKButton");
1041
1042         string prompt;
1043
1044         if (_session->snap_name() == _session->name()) {
1045                 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?"),
1046                                         _session->snap_name());
1047         } else {
1048                 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?"),
1049                                         _session->snap_name());
1050         }
1051
1052         prompt_label.set_text (prompt);
1053         prompt_label.set_name (X_("PrompterLabel"));
1054         prompt_label.set_alignment(ALIGN_LEFT, ALIGN_TOP);
1055
1056         dimage->set_alignment(ALIGN_CENTER, ALIGN_TOP);
1057         dhbox.set_homogeneous (false);
1058         dhbox.pack_start (*dimage, false, false, 5);
1059         dhbox.pack_start (prompt_label, true, false, 5);
1060         window.get_vbox()->pack_start (dhbox);
1061
1062         window.set_name (_("Prompter"));
1063         window.set_modal (true);
1064         window.set_resizable (false);
1065
1066         dhbox.show();
1067         prompt_label.show();
1068         dimage->show();
1069         window.show();
1070         window.set_keep_above (true);
1071         window.present ();
1072
1073         ResponseType r = (ResponseType) window.run();
1074
1075         window.hide ();
1076
1077         switch (r) {
1078         case RESPONSE_ACCEPT: // save and get out of here
1079                 return 1;
1080         case RESPONSE_APPLY:  // get out of here
1081                 return 0;
1082         default:
1083                 break;
1084         }
1085
1086         return -1;
1087 }
1088
1089
1090 gint
1091 ARDOUR_UI::every_second ()
1092 {
1093         update_cpu_load ();
1094         update_buffer_load ();
1095         update_disk_space ();
1096         update_timecode_format ();
1097
1098         if (nsm && nsm->is_active ()) {
1099                 nsm->check ();
1100
1101                 if (!_was_dirty && _session->dirty ()) {
1102                         nsm->is_dirty ();
1103                         _was_dirty = true;
1104                 }
1105                 else if (_was_dirty && !_session->dirty ()){
1106                         nsm->is_clean ();
1107                         _was_dirty = false;
1108                 }
1109         }
1110         return TRUE;
1111 }
1112
1113 gint
1114 ARDOUR_UI::every_point_one_seconds ()
1115 {
1116         shuttle_box->update_speed_display ();
1117         RapidScreenUpdate(); /* EMIT_SIGNAL */
1118         return TRUE;
1119 }
1120
1121 gint
1122 ARDOUR_UI::every_point_zero_something_seconds ()
1123 {
1124         // august 2007: actual update frequency: 25Hz (40ms), not 100Hz
1125
1126         SuperRapidScreenUpdate(); /* EMIT_SIGNAL */
1127         if (editor_meter && Config->get_show_editor_meter()) {
1128                 float mpeak = editor_meter->update_meters();
1129                 if (mpeak > editor_meter_max_peak) {
1130                         if (mpeak >= Config->get_meter_peak()) {
1131                                 editor_meter_peak_display.set_name ("meterbridge peakindicator on");
1132                                 editor_meter_peak_display.set_elements((ArdourButton::Element) (ArdourButton::Edge|ArdourButton::Body));
1133                         }
1134                 }
1135         }
1136         return TRUE;
1137 }
1138
1139 void
1140 ARDOUR_UI::update_sample_rate (framecnt_t)
1141 {
1142         char buf[64];
1143
1144         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::update_sample_rate, ignored)
1145
1146         if (!AudioEngine::instance()->connected()) {
1147
1148                 snprintf (buf, sizeof (buf), _("Audio: <span foreground=\"red\">none</span>"));
1149
1150         } else {
1151
1152                 framecnt_t rate = AudioEngine::instance()->sample_rate();
1153
1154                 if (rate == 0) {
1155                         /* no sample rate available */
1156                         snprintf (buf, sizeof (buf), _("Audio: <span foreground=\"red\">none</span>"));
1157                 } else {
1158
1159                         if (fmod (rate, 1000.0) != 0.0) {
1160                                 snprintf (buf, sizeof (buf), _("Audio: <span foreground=\"green\">%.1f kHz / %4.1f ms</span>"),
1161                                           (float) rate / 1000.0f,
1162                                           (AudioEngine::instance()->usecs_per_cycle() / 1000.0f));
1163                         } else {
1164                                 snprintf (buf, sizeof (buf), _("Audio: <span foreground=\"green\">%" PRId64 " kHz / %4.1f ms</span>"),
1165                                           rate/1000,
1166                                           (AudioEngine::instance()->usecs_per_cycle() / 1000.0f));
1167                         }
1168                 }
1169         }
1170         sample_rate_label.set_markup (buf);
1171 }
1172
1173 void
1174 ARDOUR_UI::update_format ()
1175 {
1176         if (!_session) {
1177                 format_label.set_text ("");
1178                 return;
1179         }
1180
1181         stringstream s;
1182         s << _("File:") << X_(" <span foreground=\"green\">");
1183
1184         switch (_session->config.get_native_file_header_format ()) {
1185         case BWF:
1186                 s << _("BWF");
1187                 break;
1188         case WAVE:
1189                 s << _("WAV");
1190                 break;
1191         case WAVE64:
1192                 s << _("WAV64");
1193                 break;
1194         case CAF:
1195                 s << _("CAF");
1196                 break;
1197         case AIFF:
1198                 s << _("AIFF");
1199                 break;
1200         case iXML:
1201                 s << _("iXML");
1202                 break;
1203         case RF64:
1204                 s << _("RF64");
1205                 break;
1206         }
1207
1208         s << " ";
1209         
1210         switch (_session->config.get_native_file_data_format ()) {
1211         case FormatFloat:
1212                 s << _("32-float");
1213                 break;
1214         case FormatInt24:
1215                 s << _("24-int");
1216                 break;
1217         case FormatInt16:
1218                 s << _("16-int");
1219                 break;
1220         }
1221
1222         s << X_("</span>");
1223
1224         format_label.set_markup (s.str ());
1225 }
1226
1227 void
1228 ARDOUR_UI::update_cpu_load ()
1229 {
1230         char buf[64];
1231
1232         /* If this text is changed, the set_size_request_to_display_given_text call in ARDOUR_UI::resize_text_widgets
1233            should also be changed.
1234         */
1235
1236         float const c = AudioEngine::instance()->get_dsp_load ();
1237         snprintf (buf, sizeof (buf), _("DSP: <span foreground=\"%s\">%5.1f%%</span>"), c >= 90 ? X_("red") : X_("green"), c);
1238         cpu_load_label.set_markup (buf);
1239 }
1240
1241 void
1242 ARDOUR_UI::update_buffer_load ()
1243 {
1244         char buf[256];
1245
1246         uint32_t const playback = _session ? _session->playback_load () : 100;
1247         uint32_t const capture = _session ? _session->capture_load () : 100;
1248
1249         /* If this text is changed, the set_size_request_to_display_given_text call in ARDOUR_UI::resize_text_widgets
1250            should also be changed.
1251         */
1252         
1253         if (_session) {
1254                 snprintf (
1255                         buf, sizeof (buf),
1256                         _("Buffers: <span foreground=\"green\">p:</span><span foreground=\"%s\">%" PRIu32 "%%</span> "
1257                                    "<span foreground=\"green\">c:</span><span foreground=\"%s\">%" PRIu32 "%%</span>"),
1258                         playback <= 5 ? X_("red") : X_("green"),
1259                         playback,
1260                         capture <= 5 ? X_("red") : X_("green"),
1261                         capture
1262                         );
1263
1264                 buffer_load_label.set_markup (buf);
1265         } else {
1266                 buffer_load_label.set_text ("");
1267         }
1268 }
1269
1270 void
1271 ARDOUR_UI::count_recenabled_streams (Route& route)
1272 {
1273         Track* track = dynamic_cast<Track*>(&route);
1274         if (track && track->record_enabled()) {
1275                 rec_enabled_streams += track->n_inputs().n_total();
1276         }
1277 }
1278
1279 void
1280 ARDOUR_UI::update_disk_space()
1281 {
1282         if (_session == 0) {
1283                 return;
1284         }
1285
1286         boost::optional<framecnt_t> opt_frames = _session->available_capture_duration();
1287         char buf[64];
1288         framecnt_t fr = _session->frame_rate();
1289
1290         if (fr == 0) {
1291                 /* skip update - no SR available */
1292                 return;
1293         }
1294
1295         if (!opt_frames) {
1296                 /* Available space is unknown */
1297                 snprintf (buf, sizeof (buf), "%s", _("Disk: <span foreground=\"green\">Unknown</span>"));
1298         } else if (opt_frames.get_value_or (0) == max_framecnt) {
1299                 snprintf (buf, sizeof (buf), "%s", _("Disk: <span foreground=\"green\">24hrs+</span>"));
1300         } else {
1301                 rec_enabled_streams = 0;
1302                 _session->foreach_route (this, &ARDOUR_UI::count_recenabled_streams);
1303
1304                 framecnt_t frames = opt_frames.get_value_or (0);
1305
1306                 if (rec_enabled_streams) {
1307                         frames /= rec_enabled_streams;
1308                 }
1309
1310                 int hrs;
1311                 int mins;
1312                 int secs;
1313
1314                 hrs  = frames / (fr * 3600);
1315
1316                 if (hrs > 24) {
1317                         snprintf (buf, sizeof (buf), "%s", _("Disk: <span foreground=\"green\">&gt;24 hrs</span>"));
1318                 } else {
1319                         frames -= hrs * fr * 3600;
1320                         mins = frames / (fr * 60);
1321                         frames -= mins * fr * 60;
1322                         secs = frames / fr;
1323                         
1324                         bool const low = (hrs == 0 && mins <= 30);
1325                         
1326                         snprintf (
1327                                 buf, sizeof(buf),
1328                                 _("Disk: <span foreground=\"%s\">%02dh:%02dm:%02ds</span>"),
1329                                 low ? X_("red") : X_("green"),
1330                                 hrs, mins, secs
1331                                 );
1332                 }
1333         }
1334
1335         disk_space_label.set_markup (buf);
1336 }
1337
1338 void
1339 ARDOUR_UI::update_timecode_format ()
1340 {
1341         char buf[64];
1342
1343         if (_session) {
1344                 bool matching;
1345                 TimecodeSlave* tcslave;
1346                 SyncSource sync_src = Config->get_sync_source();
1347
1348                 if ((sync_src == LTC || sync_src == MTC) && (tcslave = dynamic_cast<TimecodeSlave*>(_session->slave())) != 0) {
1349                         matching = (tcslave->apparent_timecode_format() == _session->config.get_timecode_format());
1350                 } else {
1351                         matching = true;
1352                 }
1353                         
1354                 snprintf (buf, sizeof (buf), S_("Timecode|TC: <span foreground=\"%s\">%s</span>"),
1355                           matching ? X_("green") : X_("red"),
1356                           Timecode::timecode_format_name (_session->config.get_timecode_format()).c_str());
1357         } else {
1358                 snprintf (buf, sizeof (buf), "TC: n/a");
1359         }
1360
1361         timecode_format_label.set_markup (buf);
1362 }       
1363
1364 gint
1365 ARDOUR_UI::update_wall_clock ()
1366 {
1367         time_t now;
1368         struct tm *tm_now;
1369         static int last_min = -1;
1370
1371         time (&now);
1372         tm_now = localtime (&now);
1373         if (last_min != tm_now->tm_min) {
1374                 char buf[16];
1375                 sprintf (buf, "%02d:%02d", tm_now->tm_hour, tm_now->tm_min);
1376                 wall_clock_label.set_text (buf);
1377                 last_min = tm_now->tm_min;
1378         }
1379
1380         return TRUE;
1381 }
1382
1383 void
1384 ARDOUR_UI::redisplay_recent_sessions ()
1385 {
1386         std::vector<std::string> session_directories;
1387         RecentSessionsSorter cmp;
1388
1389         recent_session_display.set_model (Glib::RefPtr<TreeModel>(0));
1390         recent_session_model->clear ();
1391
1392         ARDOUR::RecentSessions rs;
1393         ARDOUR::read_recent_sessions (rs);
1394
1395         if (rs.empty()) {
1396                 recent_session_display.set_model (recent_session_model);
1397                 return;
1398         }
1399
1400         // sort them alphabetically
1401         sort (rs.begin(), rs.end(), cmp);
1402
1403         for (ARDOUR::RecentSessions::iterator i = rs.begin(); i != rs.end(); ++i) {
1404                 session_directories.push_back ((*i).second);
1405         }
1406
1407         for (vector<std::string>::const_iterator i = session_directories.begin();
1408                         i != session_directories.end(); ++i)
1409         {
1410                 std::vector<std::string> state_file_paths;
1411
1412                 // now get available states for this session
1413
1414                 get_state_files_in_directory (*i, state_file_paths);
1415
1416                 vector<string*>* states;
1417                 vector<const gchar*> item;
1418                 string fullpath = *i;
1419
1420                 /* remove any trailing / */
1421
1422                 if (fullpath[fullpath.length() - 1] == '/') {
1423                         fullpath = fullpath.substr (0, fullpath.length() - 1);
1424                 }
1425
1426                 /* check whether session still exists */
1427                 if (!Glib::file_test(fullpath.c_str(), Glib::FILE_TEST_EXISTS)) {
1428                         /* session doesn't exist */
1429                         continue;
1430                 }
1431
1432                 /* now get available states for this session */
1433
1434                 if ((states = Session::possible_states (fullpath)) == 0) {
1435                         /* no state file? */
1436                         continue;
1437                 }
1438
1439                 std::vector<string> state_file_names(get_file_names_no_extension (state_file_paths));
1440
1441                 Gtk::TreeModel::Row row = *(recent_session_model->append());
1442
1443                 row[recent_session_columns.visible_name] = Glib::path_get_basename (fullpath);
1444                 row[recent_session_columns.fullpath] = fullpath;
1445                 row[recent_session_columns.tip] = Glib::Markup::escape_text (fullpath);
1446
1447                 if (state_file_names.size() > 1) {
1448
1449                         // add the children
1450
1451                         for (std::vector<std::string>::iterator i2 = state_file_names.begin();
1452                                         i2 != state_file_names.end(); ++i2)
1453                         {
1454
1455                                 Gtk::TreeModel::Row child_row = *(recent_session_model->append (row.children()));
1456
1457                                 child_row[recent_session_columns.visible_name] = *i2;
1458                                 child_row[recent_session_columns.fullpath] = fullpath;
1459                                 child_row[recent_session_columns.tip] = Glib::Markup::escape_text (fullpath);
1460                         }
1461                 }
1462         }
1463
1464         recent_session_display.set_tooltip_column(1); // recent_session_columns.tip
1465         recent_session_display.set_model (recent_session_model);
1466 }
1467
1468 void
1469 ARDOUR_UI::build_session_selector ()
1470 {
1471         session_selector_window = new ArdourDialog (_("Recent Sessions"));
1472
1473         Gtk::ScrolledWindow *scroller = manage (new Gtk::ScrolledWindow);
1474
1475         session_selector_window->add_button (Stock::CANCEL, RESPONSE_CANCEL);
1476         session_selector_window->add_button (Stock::OPEN, RESPONSE_ACCEPT);
1477         session_selector_window->set_default_response (RESPONSE_ACCEPT);
1478         recent_session_model = TreeStore::create (recent_session_columns);
1479         recent_session_display.set_model (recent_session_model);
1480         recent_session_display.append_column (_("Recent Sessions"), recent_session_columns.visible_name);
1481         recent_session_display.set_headers_visible (false);
1482         recent_session_display.get_selection()->set_mode (SELECTION_BROWSE);
1483         recent_session_display.signal_row_activated().connect (sigc::mem_fun (*this, &ARDOUR_UI::recent_session_row_activated));
1484
1485         scroller->add (recent_session_display);
1486         scroller->set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
1487
1488         session_selector_window->set_name ("SessionSelectorWindow");
1489         session_selector_window->set_size_request (200, 400);
1490         session_selector_window->get_vbox()->pack_start (*scroller);
1491
1492         recent_session_display.show();
1493         scroller->show();
1494 }
1495
1496 void
1497 ARDOUR_UI::recent_session_row_activated (const TreePath& /*path*/, TreeViewColumn* /*col*/)
1498 {
1499         session_selector_window->response (RESPONSE_ACCEPT);
1500 }
1501
1502 void
1503 ARDOUR_UI::open_recent_session ()
1504 {
1505         bool can_return = (_session != 0);
1506
1507         if (session_selector_window == 0) {
1508                 build_session_selector ();
1509         }
1510
1511         redisplay_recent_sessions ();
1512
1513         while (true) {
1514
1515                 ResponseType r = (ResponseType) session_selector_window->run ();
1516
1517                 switch (r) {
1518                 case RESPONSE_ACCEPT:
1519                         break;
1520                 default:
1521                         if (can_return) {
1522                                 session_selector_window->hide();
1523                                 return;
1524                         } else {
1525                                 exit (1);
1526                         }
1527                 }
1528
1529                 if (recent_session_display.get_selection()->count_selected_rows() == 0) {
1530                         continue;
1531                 }
1532
1533                 session_selector_window->hide();
1534
1535                 Gtk::TreeModel::iterator i = recent_session_display.get_selection()->get_selected();
1536
1537                 if (i == recent_session_model->children().end()) {
1538                         return;
1539                 }
1540
1541                 std::string path = (*i)[recent_session_columns.fullpath];
1542                 std::string state = (*i)[recent_session_columns.visible_name];
1543
1544                 _session_is_new = false;
1545
1546                 if (load_session (path, state) == 0) {
1547                         break;
1548                 }
1549
1550                 can_return = false;
1551         }
1552 }
1553
1554 bool
1555 ARDOUR_UI::check_audioengine ()
1556 {
1557         if (!AudioEngine::instance()->connected()) {
1558                 MessageDialog msg (string_compose (
1559                                            _("%1 is not connected to any audio backend.\n"
1560                                              "You cannot open or close sessions in this condition"),
1561                                            PROGRAM_NAME));
1562                 pop_back_splash (msg);
1563                 msg.run ();
1564                 return false;
1565         }
1566         return true;
1567 }
1568
1569 void
1570 ARDOUR_UI::open_session ()
1571 {
1572         if (!check_audioengine()) {
1573                 return;
1574
1575         }
1576
1577         /* popup selector window */
1578
1579         if (open_session_selector == 0) {
1580
1581                 /* ardour sessions are folders */
1582
1583                 open_session_selector = new Gtk::FileChooserDialog (_("Open Session"), FILE_CHOOSER_ACTION_OPEN);
1584                 open_session_selector->add_button (Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
1585                 open_session_selector->add_button (Gtk::Stock::OPEN, Gtk::RESPONSE_ACCEPT);
1586                 open_session_selector->set_default_response(Gtk::RESPONSE_ACCEPT);
1587                 
1588                 if (_session) {
1589                         string session_parent_dir = Glib::path_get_dirname(_session->path());
1590                         string::size_type last_dir_sep = session_parent_dir.rfind(G_DIR_SEPARATOR);
1591                         session_parent_dir = session_parent_dir.substr(0, last_dir_sep);
1592                         open_session_selector->set_current_folder(session_parent_dir);
1593                 } else {
1594                         open_session_selector->set_current_folder(Config->get_default_session_parent_dir());
1595                 }
1596
1597                 string default_session_folder = Config->get_default_session_parent_dir();
1598                 try {
1599                         /* add_shortcut_folder throws an exception if the folder being added already has a shortcut */
1600                         open_session_selector->add_shortcut_folder (default_session_folder);
1601                 }
1602                 catch (Glib::Error & e) {
1603                         std::cerr << "open_session_selector->add_shortcut_folder (" << default_session_folder << ") threw Glib::Error " << e.what() << std::endl;
1604                 }
1605
1606                 FileFilter session_filter;
1607                 session_filter.add_pattern ("*.ardour");
1608                 session_filter.set_name (string_compose (_("%1 sessions"), PROGRAM_NAME));
1609                 open_session_selector->add_filter (session_filter);
1610                 open_session_selector->set_filter (session_filter);
1611         }
1612
1613         int response = open_session_selector->run();
1614         open_session_selector->hide ();
1615
1616         switch (response) {
1617         case RESPONSE_ACCEPT:
1618                 break;
1619         default:
1620                 open_session_selector->hide();
1621                 return;
1622         }
1623
1624         open_session_selector->hide();
1625         string session_path = open_session_selector->get_filename();
1626         string path, name;
1627         bool isnew;
1628
1629         if (session_path.length() > 0) {
1630                 if (ARDOUR::find_session (session_path, path, name, isnew) == 0) {
1631                         _session_is_new = isnew;
1632                         load_session (path, name);
1633                 }
1634         }
1635 }
1636
1637
1638 void
1639 ARDOUR_UI::session_add_mixed_track (const ChanCount& input, const ChanCount& output, RouteGroup* route_group, 
1640                                     uint32_t how_many, const string& name_template, PluginInfoPtr instrument)
1641 {
1642         list<boost::shared_ptr<MidiTrack> > tracks;
1643
1644         if (_session == 0) {
1645                 warning << _("You cannot add a track without a session already loaded.") << endmsg;
1646                 return;
1647         }
1648
1649         try {
1650                 tracks = _session->new_midi_track (input, output, instrument, ARDOUR::Normal, route_group, how_many, name_template);
1651                 
1652                 if (tracks.size() != how_many) {
1653                         error << string_compose(P_("could not create %1 new mixed track", "could not create %1 new mixed tracks", how_many), how_many) << endmsg;
1654                 }
1655         }
1656
1657         catch (...) {
1658                 MessageDialog msg (*editor,
1659                                    string_compose (_("There are insufficient ports available\n\
1660 to create a new track or bus.\n\
1661 You should save %1, exit and\n\
1662 restart with more ports."), PROGRAM_NAME));
1663                 msg.run ();
1664         }
1665 }
1666         
1667
1668 void
1669 ARDOUR_UI::session_add_midi_route (bool disk, RouteGroup* route_group, uint32_t how_many, const string& name_template, PluginInfoPtr instrument)
1670 {
1671         ChanCount one_midi_channel;
1672         one_midi_channel.set (DataType::MIDI, 1);
1673
1674         if (disk) {
1675                 session_add_mixed_track (one_midi_channel, one_midi_channel, route_group, how_many, name_template, instrument);
1676         }
1677 }
1678
1679 void
1680 ARDOUR_UI::session_add_audio_route (
1681         bool track,
1682         int32_t input_channels,
1683         int32_t output_channels,
1684         ARDOUR::TrackMode mode,
1685         RouteGroup* route_group,
1686         uint32_t how_many,
1687         string const & name_template
1688         )
1689 {
1690         list<boost::shared_ptr<AudioTrack> > tracks;
1691         RouteList routes;
1692
1693         if (_session == 0) {
1694                 warning << _("You cannot add a track or bus without a session already loaded.") << endmsg;
1695                 return;
1696         }
1697
1698         try {
1699                 if (track) {
1700                         tracks = _session->new_audio_track (input_channels, output_channels, mode, route_group, how_many, name_template);
1701
1702                         if (tracks.size() != how_many) {
1703                                 error << string_compose (P_("could not create %1 new audio track", "could not create %1 new audio tracks", how_many), how_many) 
1704                                       << endmsg;
1705                         }
1706
1707                 } else {
1708
1709                         routes = _session->new_audio_route (input_channels, output_channels, route_group, how_many, name_template);
1710
1711                         if (routes.size() != how_many) {
1712                                 error << string_compose (P_("could not create %1 new audio bus", "could not create %1 new audio busses", how_many), how_many)
1713                                       << endmsg;
1714                         }
1715                 }
1716         }
1717
1718         catch (...) {
1719                 MessageDialog msg (*editor,
1720                                    string_compose (_("There are insufficient ports available\n\
1721 to create a new track or bus.\n\
1722 You should save %1, exit and\n\
1723 restart with more ports."), PROGRAM_NAME));
1724                 pop_back_splash (msg);
1725                 msg.run ();
1726         }
1727 }
1728
1729 void
1730 ARDOUR_UI::transport_goto_start ()
1731 {
1732         if (_session) {
1733                 _session->goto_start();
1734
1735                 /* force displayed area in editor to start no matter
1736                    what "follow playhead" setting is.
1737                 */
1738
1739                 if (editor) {
1740                         editor->center_screen (_session->current_start_frame ());
1741                 }
1742         }
1743 }
1744
1745 void
1746 ARDOUR_UI::transport_goto_zero ()
1747 {
1748         if (_session) {
1749                 _session->request_locate (0);
1750
1751                 /* force displayed area in editor to start no matter
1752                    what "follow playhead" setting is.
1753                 */
1754
1755                 if (editor) {
1756                         editor->reset_x_origin (0);
1757                 }
1758         }
1759 }
1760
1761 void
1762 ARDOUR_UI::transport_goto_wallclock ()
1763 {
1764         if (_session && editor) {
1765
1766                 time_t now;
1767                 struct tm tmnow;
1768                 framepos_t frames;
1769
1770                 time (&now);
1771                 localtime_r (&now, &tmnow);
1772                 
1773                 int frame_rate = _session->frame_rate();
1774                 
1775                 if (frame_rate == 0) {
1776                         /* no frame rate available */
1777                         return;
1778                 }
1779
1780                 frames = tmnow.tm_hour * (60 * 60 * frame_rate);
1781                 frames += tmnow.tm_min * (60 * frame_rate);
1782                 frames += tmnow.tm_sec * frame_rate;
1783
1784                 _session->request_locate (frames, _session->transport_rolling ());
1785
1786                 /* force displayed area in editor to start no matter
1787                    what "follow playhead" setting is.
1788                 */
1789
1790                 if (editor) {
1791                         editor->center_screen (frames);
1792                 }
1793         }
1794 }
1795
1796 void
1797 ARDOUR_UI::transport_goto_end ()
1798 {
1799         if (_session) {
1800                 framepos_t const frame = _session->current_end_frame();
1801                 _session->request_locate (frame);
1802
1803                 /* force displayed area in editor to start no matter
1804                    what "follow playhead" setting is.
1805                 */
1806
1807                 if (editor) {
1808                         editor->center_screen (frame);
1809                 }
1810         }
1811 }
1812
1813 void
1814 ARDOUR_UI::transport_stop ()
1815 {
1816         if (!_session) {
1817                 return;
1818         }
1819
1820         if (_session->is_auditioning()) {
1821                 _session->cancel_audition ();
1822                 return;
1823         }
1824
1825         _session->request_stop (false, true);
1826 }
1827
1828 void
1829 ARDOUR_UI::transport_record (bool roll)
1830 {
1831
1832         if (_session) {
1833                 switch (_session->record_status()) {
1834                 case Session::Disabled:
1835                         if (_session->ntracks() == 0) {
1836                                 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."));
1837                                 msg.run ();
1838                                 return;
1839                         }
1840                         _session->maybe_enable_record ();
1841                         if (roll) {
1842                                 transport_roll ();
1843                         }
1844                         break;
1845                 case Session::Recording:
1846                         if (roll) {
1847                                 _session->request_stop();
1848                         } else {
1849                                 _session->disable_record (false, true);
1850                         }
1851                         break;
1852
1853                 case Session::Enabled:
1854                         _session->disable_record (false, true);
1855                 }
1856         }
1857 }
1858
1859 void
1860 ARDOUR_UI::transport_roll ()
1861 {
1862         if (!_session) {
1863                 return;
1864         }
1865
1866         if (_session->is_auditioning()) {
1867                 return;
1868         }
1869
1870 #if 0
1871         if (_session->config.get_external_sync()) {
1872                 switch (Config->get_sync_source()) {
1873                 case Engine:
1874                         break;
1875                 default:
1876                         /* transport controlled by the master */
1877                         return;
1878                 }
1879         }
1880 #endif
1881
1882         bool rolling = _session->transport_rolling();
1883
1884         if (_session->get_play_loop()) {
1885                 /* XXX it is not possible to just leave seamless loop and keep
1886                    playing at present (nov 4th 2009)
1887                 */
1888                 if (!Config->get_seamless_loop()) {
1889                         _session->request_play_loop (false, true);
1890                 }
1891         } else if (_session->get_play_range () && !Config->get_always_play_range()) {
1892                 /* stop playing a range if we currently are */
1893                 _session->request_play_range (0, true);
1894         }
1895
1896         if (!rolling) {
1897                 _session->request_transport_speed (1.0f);
1898         }
1899 }
1900
1901 bool
1902 ARDOUR_UI::get_smart_mode() const
1903 {
1904         return ( editor->get_smart_mode() );
1905 }
1906
1907
1908 void
1909 ARDOUR_UI::toggle_roll (bool with_abort, bool roll_out_of_bounded_mode)
1910 {
1911
1912         if (!_session) {
1913                 return;
1914         }
1915
1916         if (_session->is_auditioning()) {
1917                 _session->cancel_audition ();
1918                 return;
1919         }
1920
1921         if (_session->config.get_external_sync()) {
1922                 switch (Config->get_sync_source()) {
1923                 case Engine:
1924                         break;
1925                 default:
1926                         /* transport controlled by the master */
1927                         return;
1928                 }
1929         }
1930
1931         bool rolling = _session->transport_rolling();
1932         bool affect_transport = true;
1933
1934         if (rolling && roll_out_of_bounded_mode) {
1935                 /* drop out of loop/range playback but leave transport rolling */
1936                 if (_session->get_play_loop()) {
1937                         if (Config->get_seamless_loop()) {
1938                                 /* the disk buffers contain copies of the loop - we can't
1939                                    just keep playing, so stop the transport. the user
1940                                    can restart as they wish.
1941                                 */
1942                                 affect_transport = true;
1943                         } else {
1944                                 /* disk buffers are normal, so we can keep playing */
1945                                 affect_transport = false;
1946                         }
1947                         _session->request_play_loop (false, true);
1948                 } else if (_session->get_play_range ()) {
1949                         affect_transport = false;
1950                         _session->request_play_range (0, true);
1951                 }
1952         }
1953
1954         if (affect_transport) {
1955                 if (rolling) {
1956                         _session->request_stop (with_abort, true);
1957                 } else {
1958                         if ( Config->get_always_play_range() ) {
1959                                 _session->request_play_range (&editor->get_selection().time, true);
1960                         }
1961
1962                         _session->request_transport_speed (1.0f);
1963                 }
1964         }
1965 }
1966
1967 void
1968 ARDOUR_UI::toggle_session_auto_loop ()
1969 {
1970         Location * looploc = _session->locations()->auto_loop_location();
1971
1972         if (!_session || !looploc) {
1973                 return;
1974         }
1975
1976         if (_session->get_play_loop()) {
1977
1978                 if (_session->transport_rolling()) {
1979
1980                         _session->request_locate (looploc->start(), true);
1981                         _session->request_play_loop (false);
1982
1983                 } else {
1984                         _session->request_play_loop (false);
1985                 }
1986         } else {
1987                 _session->request_play_loop (true);
1988         }
1989         
1990         //show the loop markers
1991         looploc->set_hidden (false, this);
1992 }
1993
1994 void
1995 ARDOUR_UI::transport_play_selection ()
1996 {
1997         if (!_session) {
1998                 return;
1999         }
2000
2001         editor->play_selection ();
2002 }
2003
2004 void
2005 ARDOUR_UI::transport_play_preroll ()
2006 {
2007         if (!_session) {
2008                 return;
2009         }
2010         editor->play_with_preroll ();
2011 }
2012
2013 void
2014 ARDOUR_UI::transport_rewind (int option)
2015 {
2016         float current_transport_speed;
2017
2018         if (_session) {
2019                 current_transport_speed = _session->transport_speed();
2020
2021                 if (current_transport_speed >= 0.0f) {
2022                         switch (option) {
2023                         case 0:
2024                                 _session->request_transport_speed (-1.0f);
2025                                 break;
2026                         case 1:
2027                                 _session->request_transport_speed (-4.0f);
2028                                 break;
2029                         case -1:
2030                                 _session->request_transport_speed (-0.5f);
2031                                 break;
2032                         }
2033                 } else {
2034                         /* speed up */
2035                         _session->request_transport_speed (current_transport_speed * 1.5f);
2036                 }
2037         }
2038 }
2039
2040 void
2041 ARDOUR_UI::transport_forward (int option)
2042 {
2043         if (!_session) {
2044                 return;
2045         }
2046         
2047         float current_transport_speed = _session->transport_speed();
2048         
2049         if (current_transport_speed <= 0.0f) {
2050                 switch (option) {
2051                 case 0:
2052                         _session->request_transport_speed (1.0f);
2053                         break;
2054                 case 1:
2055                         _session->request_transport_speed (4.0f);
2056                         break;
2057                 case -1:
2058                         _session->request_transport_speed (0.5f);
2059                         break;
2060                 }
2061         } else {
2062                 /* speed up */
2063                 _session->request_transport_speed (current_transport_speed * 1.5f);
2064         }
2065 }
2066
2067 void
2068 ARDOUR_UI::toggle_record_enable (uint32_t rid)
2069 {
2070         if (!_session) {
2071                 return;
2072         }
2073
2074         boost::shared_ptr<Route> r;
2075
2076         if ((r = _session->route_by_remote_id (rid)) != 0) {
2077
2078                 Track* t;
2079
2080                 if ((t = dynamic_cast<Track*>(r.get())) != 0) {
2081                         t->set_record_enabled (!t->record_enabled(), this);
2082                 }
2083         }
2084 }
2085
2086 void
2087 ARDOUR_UI::map_transport_state ()
2088 {
2089         if (!_session) {
2090                 auto_loop_button.unset_active_state ();
2091                 play_selection_button.unset_active_state ();
2092                 roll_button.unset_active_state ();
2093                 stop_button.set_active_state (Gtkmm2ext::ExplicitActive);
2094                 return;
2095         }
2096
2097         shuttle_box->map_transport_state ();
2098
2099         float sp = _session->transport_speed();
2100
2101         if (sp != 0.0f) {
2102
2103                 /* we're rolling */
2104
2105                 if (_session->get_play_range()) {
2106
2107                         play_selection_button.set_active_state (Gtkmm2ext::ExplicitActive);
2108                         roll_button.unset_active_state ();
2109                         auto_loop_button.unset_active_state ();
2110
2111                 } else if (_session->get_play_loop ()) {
2112
2113                         auto_loop_button.set_active (true);
2114                         play_selection_button.set_active (false);
2115                         roll_button.set_active (false);
2116
2117                 } else {
2118
2119                         roll_button.set_active (true);
2120                         play_selection_button.set_active (false);
2121                         auto_loop_button.set_active (false);
2122                 }
2123
2124                 if (Config->get_always_play_range()) {
2125                         /* light up both roll and play-selection if they are joined */
2126                         roll_button.set_active (true);
2127                         play_selection_button.set_active (true);
2128                 }
2129
2130                 stop_button.set_active (false);
2131
2132         } else {
2133
2134                 stop_button.set_active (true);
2135                 roll_button.set_active (false);
2136                 play_selection_button.set_active (false);
2137                 auto_loop_button.set_active (false);
2138                 update_disk_space ();
2139         }
2140 }
2141
2142 void
2143 ARDOUR_UI::update_clocks ()
2144 {
2145         if (!editor || !editor->dragging_playhead()) {
2146                 Clock (_session->audible_frame(), false, editor->get_preferred_edit_position()); /* EMIT_SIGNAL */
2147         }
2148 }
2149
2150 void
2151 ARDOUR_UI::start_clocking ()
2152 {
2153         if (Config->get_super_rapid_clock_update()) {
2154                 clock_signal_connection = SuperRapidScreenUpdate.connect (sigc::mem_fun(*this, &ARDOUR_UI::update_clocks));
2155         } else {
2156                 clock_signal_connection = RapidScreenUpdate.connect (sigc::mem_fun(*this, &ARDOUR_UI::update_clocks));
2157         }
2158 }
2159
2160 void
2161 ARDOUR_UI::stop_clocking ()
2162 {
2163         clock_signal_connection.disconnect ();
2164 }
2165
2166 gint
2167 ARDOUR_UI::_blink (void *arg)
2168 {
2169         ((ARDOUR_UI *) arg)->blink ();
2170         return TRUE;
2171 }
2172
2173 void
2174 ARDOUR_UI::blink ()
2175 {
2176         Blink (blink_on = !blink_on); /* EMIT_SIGNAL */
2177 }
2178
2179 void
2180 ARDOUR_UI::start_blinking ()
2181 {
2182         /* Start the blink signal. Everybody with a blinking widget
2183            uses Blink to drive the widget's state.
2184         */
2185
2186         if (blink_timeout_tag < 0) {
2187                 blink_on = false;
2188                 blink_timeout_tag = g_timeout_add (240, _blink, this);
2189         }
2190 }
2191
2192 void
2193 ARDOUR_UI::stop_blinking ()
2194 {
2195         if (blink_timeout_tag >= 0) {
2196                 g_source_remove (blink_timeout_tag);
2197                 blink_timeout_tag = -1;
2198         }
2199 }
2200
2201
2202 /** Ask the user for the name of a new snapshot and then take it.
2203  */
2204
2205 void
2206 ARDOUR_UI::snapshot_session (bool switch_to_it)
2207 {
2208         ArdourPrompter prompter (true);
2209         string snapname;
2210
2211         prompter.set_name ("Prompter");
2212         prompter.add_button (Gtk::Stock::SAVE, Gtk::RESPONSE_ACCEPT);
2213         if (switch_to_it) {
2214                 prompter.set_title (_("Save as..."));
2215                 prompter.set_prompt (_("New session name"));
2216         } else {
2217                 prompter.set_title (_("Take Snapshot"));
2218                 prompter.set_prompt (_("Name of new snapshot"));
2219         }
2220
2221         if (!switch_to_it) {
2222                 char timebuf[128];
2223                 time_t n;
2224                 struct tm local_time;
2225
2226                 time (&n);
2227                 localtime_r (&n, &local_time);
2228                 strftime (timebuf, sizeof(timebuf), "%FT%H.%M.%S", &local_time);
2229                 prompter.set_initial_text (timebuf);
2230         }
2231
2232   again:
2233         switch (prompter.run()) {
2234         case RESPONSE_ACCEPT:
2235         {
2236                 prompter.get_result (snapname);
2237
2238                 bool do_save = (snapname.length() != 0);
2239
2240                 if (do_save) {
2241                         char illegal = Session::session_name_is_legal(snapname);
2242                         if (illegal) {
2243                                 MessageDialog msg (string_compose (_("To ensure compatibility with various systems\n"
2244                                                      "snapshot names may not contain a '%1' character"), illegal));
2245                                 msg.run ();
2246                                 goto again;
2247                         }
2248                 }
2249
2250                 vector<std::string> p;
2251                 get_state_files_in_directory (_session->session_directory().root_path(), p);
2252                 vector<string> n = get_file_names_no_extension (p);
2253                 if (find (n.begin(), n.end(), snapname) != n.end()) {
2254
2255                         ArdourDialog confirm (_("Confirm Snapshot Overwrite"), true);
2256                         Label m (_("A snapshot already exists with that name.  Do you want to overwrite it?"));
2257                         confirm.get_vbox()->pack_start (m, true, true);
2258                         confirm.add_button (Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2259                         confirm.add_button (_("Overwrite"), Gtk::RESPONSE_ACCEPT);
2260                         confirm.show_all ();
2261                         switch (confirm.run()) {
2262                         case RESPONSE_CANCEL:
2263                                 do_save = false;
2264                         }
2265                 }
2266
2267                 if (do_save) {
2268                         save_state (snapname, switch_to_it);
2269                 }
2270                 break;
2271         }
2272
2273         default:
2274                 break;
2275         }
2276 }
2277
2278 /** Ask the user for a new session name and then rename the session to it.
2279  */
2280
2281 void
2282 ARDOUR_UI::rename_session ()
2283 {
2284         if (!_session) {
2285                 return;
2286         }
2287
2288         ArdourPrompter prompter (true);
2289         string name;
2290
2291         prompter.set_name ("Prompter");
2292         prompter.add_button (Gtk::Stock::SAVE, Gtk::RESPONSE_ACCEPT);
2293         prompter.set_title (_("Rename Session"));
2294         prompter.set_prompt (_("New session name"));
2295
2296   again:
2297         switch (prompter.run()) {
2298         case RESPONSE_ACCEPT:
2299         {
2300                 prompter.get_result (name);
2301
2302                 bool do_rename = (name.length() != 0);
2303
2304                 if (do_rename) {
2305                         char illegal = Session::session_name_is_legal (name);
2306
2307                         if (illegal) {
2308                                 MessageDialog msg (string_compose (_("To ensure compatibility with various systems\n"
2309                                                                      "session names may not contain a '%1' character"), illegal));
2310                                 msg.run ();
2311                                 goto again;
2312                         }
2313
2314                         switch (_session->rename (name)) {
2315                         case -1: {
2316                                 MessageDialog msg (_("That name is already in use by another directory/folder. Please try again."));
2317                                 msg.set_position (WIN_POS_MOUSE);
2318                                 msg.run ();
2319                                 goto again;
2320                                 break;
2321                         }
2322                         case 0:
2323                                 break;
2324                         default: {
2325                                 MessageDialog msg (_("Renaming this session failed.\nThings could be seriously messed up at this point"));
2326                                 msg.set_position (WIN_POS_MOUSE);
2327                                 msg.run ();
2328                                 break;
2329                         }
2330                         }
2331                 }
2332                 
2333                 break;
2334         }
2335
2336         default:
2337                 break;
2338         }
2339 }
2340
2341 void
2342 ARDOUR_UI::save_state (const string & name, bool switch_to_it)
2343 {
2344         XMLNode* node = new XMLNode (X_("UI"));
2345
2346         WM::Manager::instance().add_state (*node);
2347
2348         node->add_child_nocopy (gui_object_state->get_state());
2349
2350         _session->add_extra_xml (*node);
2351
2352         save_state_canfail (name, switch_to_it);
2353 }
2354
2355 int
2356 ARDOUR_UI::save_state_canfail (string name, bool switch_to_it)
2357 {
2358         if (_session) {
2359                 int ret;
2360
2361                 if (name.length() == 0) {
2362                         name = _session->snap_name();
2363                 }
2364
2365                 if ((ret = _session->save_state (name, false, switch_to_it)) != 0) {
2366                         return ret;
2367                 }
2368         }
2369
2370         save_ardour_state (); /* XXX cannot fail? yeah, right ... */
2371         return 0;
2372 }
2373
2374 void
2375 ARDOUR_UI::primary_clock_value_changed ()
2376 {
2377         if (_session) {
2378                 _session->request_locate (primary_clock->current_time ());
2379         }
2380 }
2381
2382 void
2383 ARDOUR_UI::big_clock_value_changed ()
2384 {
2385         if (_session) {
2386                 _session->request_locate (big_clock->current_time ());
2387         }
2388 }
2389
2390 void
2391 ARDOUR_UI::secondary_clock_value_changed ()
2392 {
2393         if (_session) {
2394                 _session->request_locate (secondary_clock->current_time ());
2395         }
2396 }
2397
2398 void
2399 ARDOUR_UI::transport_rec_enable_blink (bool onoff)
2400 {
2401         if (_session == 0) {
2402                 return;
2403         }
2404
2405         if (_session->step_editing()) {
2406                 return;
2407         }
2408
2409         Session::RecordState const r = _session->record_status ();
2410         bool const h = _session->have_rec_enabled_track ();
2411
2412         if (r == Session::Enabled || (r == Session::Recording && !h)) {
2413                 if (onoff) {
2414                         rec_button.set_active_state (Gtkmm2ext::ExplicitActive);
2415                 } else {
2416                         rec_button.set_active_state (Gtkmm2ext::ImplicitActive);
2417                 }
2418         } else if (r == Session::Recording && h) {
2419                 rec_button.set_active_state (Gtkmm2ext::ExplicitActive);
2420         } else {
2421                 rec_button.unset_active_state ();
2422         }
2423 }
2424
2425 void
2426 ARDOUR_UI::save_template ()
2427 {
2428         ArdourPrompter prompter (true);
2429         string name;
2430
2431         if (!check_audioengine()) {
2432                 return;
2433         }
2434
2435         prompter.set_name (X_("Prompter"));
2436         prompter.set_title (_("Save Template"));
2437         prompter.set_prompt (_("Name for template:"));
2438         prompter.set_initial_text(_session->name() + _("-template"));
2439         prompter.add_button (Gtk::Stock::SAVE, Gtk::RESPONSE_ACCEPT);
2440
2441         switch (prompter.run()) {
2442         case RESPONSE_ACCEPT:
2443                 prompter.get_result (name);
2444
2445                 if (name.length()) {
2446                         _session->save_template (name);
2447                 }
2448                 break;
2449
2450         default:
2451                 break;
2452         }
2453 }
2454
2455 void
2456 ARDOUR_UI::edit_metadata ()
2457 {
2458         SessionMetadataEditor dialog;
2459         dialog.set_session (_session);
2460         editor->ensure_float (dialog);
2461         dialog.run ();
2462 }
2463
2464 void
2465 ARDOUR_UI::import_metadata ()
2466 {
2467         SessionMetadataImporter dialog;
2468         dialog.set_session (_session);
2469         editor->ensure_float (dialog);
2470         dialog.run ();
2471 }
2472
2473 bool
2474 ARDOUR_UI::ask_about_loading_existing_session (const std::string& session_path)
2475 {
2476         std::string str = string_compose (_("This session\n%1\nalready exists. Do you want to open it?"), session_path);
2477
2478         MessageDialog msg (str,
2479                            false,
2480                            Gtk::MESSAGE_WARNING,
2481                            Gtk::BUTTONS_YES_NO,
2482                            true);
2483
2484
2485         msg.set_name (X_("OpenExistingDialog"));
2486         msg.set_title (_("Open Existing Session"));
2487         msg.set_wmclass (X_("existing_session"), PROGRAM_NAME);
2488         msg.set_position (Gtk::WIN_POS_MOUSE);
2489         pop_back_splash (msg);
2490
2491         switch (msg.run()) {
2492         case RESPONSE_YES:
2493                 return true;
2494                 break;
2495         }
2496         return false;
2497 }
2498
2499 int
2500 ARDOUR_UI::build_session_from_dialog (SessionDialog& sd, const std::string& session_path, const std::string& session_name)
2501 {
2502         BusProfile bus_profile;
2503
2504         if (nsm || Profile->get_sae()) {
2505
2506                 bus_profile.master_out_channels = 2;
2507                 bus_profile.input_ac = AutoConnectPhysical;
2508                 bus_profile.output_ac = AutoConnectMaster;
2509                 bus_profile.requested_physical_in = 0; // use all available
2510                 bus_profile.requested_physical_out = 0; // use all available
2511
2512         } else {
2513
2514                 /* get settings from advanced section of NSD */
2515
2516                 if (sd.create_master_bus()) {
2517                         bus_profile.master_out_channels = (uint32_t) sd.master_channel_count();
2518                 } else {
2519                         bus_profile.master_out_channels = 0;
2520                 }
2521
2522                 if (sd.connect_inputs()) {
2523                         bus_profile.input_ac = AutoConnectPhysical;
2524                 } else {
2525                         bus_profile.input_ac = AutoConnectOption (0);
2526                 }
2527
2528                 bus_profile.output_ac = AutoConnectOption (0);
2529
2530                 if (sd.connect_outputs ()) {
2531                         if (sd.connect_outs_to_master()) {
2532                                 bus_profile.output_ac = AutoConnectMaster;
2533                         } else if (sd.connect_outs_to_physical()) {
2534                                 bus_profile.output_ac = AutoConnectPhysical;
2535                         }
2536                 }
2537
2538                 bus_profile.requested_physical_in = (uint32_t) sd.input_limit_count();
2539                 bus_profile.requested_physical_out = (uint32_t) sd.output_limit_count();
2540         }
2541
2542         if (build_session (session_path, session_name, bus_profile)) {
2543                 return -1;
2544         }
2545
2546         return 0;
2547 }
2548
2549 void
2550 ARDOUR_UI::idle_load (const std::string& path)
2551 {
2552         if (_session) {
2553                 if (Glib::file_test (path, Glib::FILE_TEST_IS_DIR)) {
2554                         /* /path/to/foo => /path/to/foo, foo */
2555                         load_session (path, basename_nosuffix (path));
2556                 } else {
2557                         /* /path/to/foo/foo.ardour => /path/to/foo, foo */
2558                         load_session (Glib::path_get_dirname (path), basename_nosuffix (path));
2559                 }
2560
2561         } else {
2562                 ARDOUR_COMMAND_LINE::session_name = path;
2563         }
2564 }
2565
2566 /** @param quit_on_cancel true if exit() should be called if the user clicks `cancel' in the new session dialog */
2567 int
2568 ARDOUR_UI::get_session_parameters (bool quit_on_cancel, bool should_be_new, string load_template)
2569 {
2570         string session_name;
2571         string session_path;
2572         string template_name;
2573         int ret = -1;
2574         bool likely_new = false;
2575         bool cancel_not_quit;
2576
2577         /* deal with any existing DIRTY session now, rather than later. don't
2578          * treat a non-dirty session this way, so that it stays visible 
2579          * as we bring up the new session dialog.
2580          */
2581
2582         if (_session && ARDOUR_UI::instance()->video_timeline) {
2583                 ARDOUR_UI::instance()->video_timeline->sync_session_state();
2584         }
2585
2586         /* if there is already a session, relabel the button
2587            on the SessionDialog so that we don't Quit directly
2588         */
2589         cancel_not_quit = (_session != 0);
2590
2591         if (_session && _session->dirty()) {
2592                 if (unload_session (false)) {
2593                         /* unload cancelled by user */
2594                         return 0;
2595                 }
2596                 ARDOUR_COMMAND_LINE::session_name = "";
2597         }
2598
2599         if (!load_template.empty()) {
2600                 should_be_new = true;
2601                 template_name = load_template;
2602         }
2603
2604         session_name = basename_nosuffix (ARDOUR_COMMAND_LINE::session_name);
2605         session_path = ARDOUR_COMMAND_LINE::session_name;
2606         
2607         if (!session_path.empty()) {
2608                 if (Glib::file_test (session_path.c_str(), Glib::FILE_TEST_EXISTS)) {
2609                         if (Glib::file_test (session_path.c_str(), Glib::FILE_TEST_IS_REGULAR)) {
2610                                 /* session/snapshot file, change path to be dir */
2611                                 session_path = Glib::path_get_dirname (session_path);
2612                         }
2613                 }
2614         }
2615
2616         SessionDialog session_dialog (should_be_new, session_name, session_path, load_template, cancel_not_quit);
2617
2618         while (ret != 0) {
2619
2620                 if (!ARDOUR_COMMAND_LINE::session_name.empty()) {
2621
2622                         /* if they named a specific statefile, use it, otherwise they are
2623                            just giving a session folder, and we want to use it as is
2624                            to find the session.
2625                         */
2626
2627                         string::size_type suffix = ARDOUR_COMMAND_LINE::session_name.find (statefile_suffix);
2628
2629                         if (suffix != string::npos) {
2630                                 session_path = Glib::path_get_dirname (ARDOUR_COMMAND_LINE::session_name);
2631                                 session_name = ARDOUR_COMMAND_LINE::session_name.substr (0, suffix);
2632                                 session_name = Glib::path_get_basename (session_name);
2633                         } else {
2634                                 session_path = ARDOUR_COMMAND_LINE::session_name;
2635                                 session_name = Glib::path_get_basename (ARDOUR_COMMAND_LINE::session_name);
2636                         }
2637                 } else {
2638                         session_path = "";
2639                         session_name = "";
2640                         session_dialog.clear_given ();
2641                 }
2642                 
2643                 if (should_be_new || session_name.empty()) {
2644                         /* need the dialog to get info from user */
2645
2646                         cerr << "run dialog\n";
2647
2648                         switch (session_dialog.run()) {
2649                         case RESPONSE_ACCEPT:
2650                                 break;
2651                         default:
2652                                 if (quit_on_cancel) {
2653                                         exit (1);
2654                                 } else {
2655                                         return ret;
2656                                 }
2657                         }
2658
2659                         session_dialog.hide ();
2660                 }
2661
2662                 /* if we run the startup dialog again, offer more than just "new session" */
2663                 
2664                 should_be_new = false;
2665                 
2666                 session_name = session_dialog.session_name (likely_new);
2667                 session_path = session_dialog.session_folder ();
2668
2669                 if (nsm) {
2670                         likely_new = true;
2671                 }
2672
2673                 string::size_type suffix = session_name.find (statefile_suffix);
2674                 
2675                 if (suffix != string::npos) {
2676                         session_name = session_name.substr (0, suffix);
2677                 }
2678                 
2679                 /* this shouldn't happen, but we catch it just in case it does */
2680                 
2681                 if (session_name.empty()) {
2682                         continue;
2683                 }
2684                 
2685                 if (session_dialog.use_session_template()) {
2686                         template_name = session_dialog.session_template_name();
2687                         _session_is_new = true;
2688                 }
2689                 
2690                 if (session_name[0] == G_DIR_SEPARATOR ||
2691                     (session_name.length() > 2 && session_name[0] == '.' && session_name[1] == G_DIR_SEPARATOR) ||
2692                     (session_name.length() > 3 && session_name[0] == '.' && session_name[1] == '.' && session_name[2] == G_DIR_SEPARATOR)) {
2693                         
2694                         /* absolute path or cwd-relative path specified for session name: infer session folder
2695                            from what was given.
2696                         */
2697                         
2698                         session_path = Glib::path_get_dirname (session_name);
2699                         session_name = Glib::path_get_basename (session_name);
2700                         
2701                 } else {
2702
2703                         session_path = session_dialog.session_folder();
2704                         
2705                         char illegal = Session::session_name_is_legal (session_name);
2706                         
2707                         if (illegal) {
2708                                 MessageDialog msg (session_dialog,
2709                                                    string_compose (_("To ensure compatibility with various systems\n"
2710                                                                      "session names may not contain a '%1' character"),
2711                                                                    illegal));
2712                                 msg.run ();
2713                                 ARDOUR_COMMAND_LINE::session_name = ""; // cancel that
2714                                 continue;
2715                         }
2716                 }
2717         
2718                 if (Glib::file_test (session_path, Glib::FileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) {
2719
2720
2721                         if (likely_new && !nsm) {
2722
2723                                 std::string existing = Glib::build_filename (session_path, session_name);
2724
2725                                 if (!ask_about_loading_existing_session (existing)) {
2726                                         ARDOUR_COMMAND_LINE::session_name = ""; // cancel that
2727                                         continue;
2728                                 }
2729                         }
2730
2731                         _session_is_new = false;
2732
2733                 } else {
2734
2735                         if (!likely_new) {
2736                                 pop_back_splash (session_dialog);
2737                                 MessageDialog msg (string_compose (_("There is no existing session at \"%1\""), session_path));
2738                                 msg.run ();
2739                                 ARDOUR_COMMAND_LINE::session_name = ""; // cancel that
2740                                 continue;
2741                         }
2742
2743                         char illegal = Session::session_name_is_legal(session_name);
2744
2745                         if (illegal) {
2746                                 pop_back_splash (session_dialog);
2747                                 MessageDialog msg (session_dialog, string_compose(_("To ensure compatibility with various systems\n"
2748                                                                                     "session names may not contain a '%1' character"), illegal));
2749                                 msg.run ();
2750                                 ARDOUR_COMMAND_LINE::session_name = ""; // cancel that
2751                                 continue;
2752                         }
2753
2754                         _session_is_new = true;
2755                 }
2756
2757                 if (likely_new && template_name.empty()) {
2758
2759                         ret = build_session_from_dialog (session_dialog, session_path, session_name);
2760
2761                 } else {
2762
2763                         ret = load_session (session_path, session_name, template_name);
2764
2765                         if (ret == -2) {
2766                                 /* not connected to the AudioEngine, so quit to avoid an infinite loop */
2767                                 exit (1);
2768                         }
2769
2770                         if (!ARDOUR_COMMAND_LINE::immediate_save.empty()) {
2771                                 _session->save_state (ARDOUR_COMMAND_LINE::immediate_save, false);
2772                                 exit (1);
2773                         }
2774
2775                         /* clear this to avoid endless attempts to load the
2776                            same session.
2777                         */
2778
2779                         ARDOUR_COMMAND_LINE::session_name = "";
2780                 }
2781         }
2782
2783         return ret;
2784 }
2785
2786 void
2787 ARDOUR_UI::close_session()
2788 {
2789         if (!check_audioengine()) {
2790                 return;
2791         }
2792
2793         if (unload_session (true)) {
2794                 return;
2795         }
2796
2797         ARDOUR_COMMAND_LINE::session_name = "";
2798
2799         if (get_session_parameters (true, false)) {
2800                 exit (1);
2801         }
2802
2803         goto_editor_window ();
2804 }
2805
2806 /** @param snap_name Snapshot name (without .ardour suffix).
2807  *  @return -2 if the load failed because we are not connected to the AudioEngine.
2808  */
2809 int
2810 ARDOUR_UI::load_session (const std::string& path, const std::string& snap_name, std::string mix_template)
2811 {
2812         Session *new_session;
2813         int unload_status;
2814         int retval = -1;
2815
2816         if (_session) {
2817                 unload_status = unload_session ();
2818                 
2819                 if (unload_status < 0) {
2820                         goto out;
2821                 } else if (unload_status > 0) {
2822                         retval = 0;
2823                         goto out;
2824                 }
2825         }
2826
2827         session_loaded = false;
2828
2829         loading_message (string_compose (_("Please wait while %1 loads your session"), PROGRAM_NAME));
2830
2831         try {
2832                 new_session = new Session (*AudioEngine::instance(), path, snap_name, 0, mix_template);
2833         }
2834
2835         /* this one is special */
2836
2837         catch (AudioEngine::PortRegistrationFailure& err) {
2838
2839                 MessageDialog msg (err.what(),
2840                                    true,
2841                                    Gtk::MESSAGE_INFO,
2842                                    Gtk::BUTTONS_CLOSE);
2843
2844                 msg.set_title (_("Port Registration Error"));
2845                 msg.set_secondary_text (_("Click the Close button to try again."));
2846                 msg.set_position (Gtk::WIN_POS_CENTER);
2847                 pop_back_splash (msg);
2848                 msg.present ();
2849
2850                 int response = msg.run ();
2851
2852                 msg.hide ();
2853
2854                 switch (response) {
2855                 case RESPONSE_CANCEL:
2856                         exit (1);
2857                 default:
2858                         break;
2859                 }
2860                 goto out;
2861         }
2862
2863         catch (...) {
2864
2865                 MessageDialog msg (string_compose(
2866                                            _("Session \"%1 (snapshot %2)\" did not load successfully"),
2867                                            path, snap_name),
2868                                    true,
2869                                    Gtk::MESSAGE_INFO,
2870                                    BUTTONS_OK);
2871
2872                 msg.set_keep_above (true);
2873                 msg.set_title (_("Loading Error"));
2874                 msg.set_position (Gtk::WIN_POS_CENTER);
2875                 pop_back_splash (msg);
2876                 msg.present ();
2877                 (void) msg.run ();
2878                 msg.hide ();
2879
2880                 goto out;
2881         }
2882
2883         {
2884                 list<string> const u = new_session->unknown_processors ();
2885                 if (!u.empty()) {
2886                         MissingPluginDialog d (_session, u);
2887                         d.run ();
2888                 }
2889         }
2890
2891         if (!new_session->writable()) {
2892                 MessageDialog msg (_("This session has been opened in read-only mode.\n\nYou will not be able to record or save."),
2893                                    true,
2894                                    Gtk::MESSAGE_INFO,
2895                                    BUTTONS_OK);
2896                 
2897                 msg.set_keep_above (true);
2898                 msg.set_title (_("Read-only Session"));
2899                 msg.set_position (Gtk::WIN_POS_CENTER);
2900                 pop_back_splash (msg);
2901                 msg.present ();
2902                 (void) msg.run ();
2903                 msg.hide ();
2904         }
2905         
2906
2907         /* Now the session been created, add the transport controls */
2908         new_session->add_controllable(roll_controllable);
2909         new_session->add_controllable(stop_controllable);
2910         new_session->add_controllable(goto_start_controllable);
2911         new_session->add_controllable(goto_end_controllable);
2912         new_session->add_controllable(auto_loop_controllable);
2913         new_session->add_controllable(play_selection_controllable);
2914         new_session->add_controllable(rec_controllable);
2915
2916         set_session (new_session);
2917
2918         session_loaded = true;
2919
2920         goto_editor_window ();
2921
2922         if (_session) {
2923                 _session->set_clean ();
2924         }
2925
2926 #ifdef WINDOWS_VST_SUPPORT
2927         fst_stop_threading();
2928 #endif
2929
2930         flush_pending ();
2931
2932 #ifdef WINDOWS_VST_SUPPORT
2933         fst_start_threading();
2934 #endif
2935         retval = 0;
2936
2937   out:
2938         return retval;
2939 }
2940
2941 int
2942 ARDOUR_UI::build_session (const std::string& path, const std::string& snap_name, BusProfile& bus_profile)
2943 {
2944         Session *new_session;
2945         int x;
2946
2947         session_loaded = false;
2948         x = unload_session ();
2949
2950         if (x < 0) {
2951                 return -1;
2952         } else if (x > 0) {
2953                 return 0;
2954         }
2955
2956         _session_is_new = true;
2957
2958         try {
2959                 new_session = new Session (*AudioEngine::instance(), path, snap_name, &bus_profile);
2960         }
2961
2962         catch (...) {
2963
2964                 MessageDialog msg (string_compose(_("Could not create session in \"%1\""), path));
2965                 pop_back_splash (msg);
2966                 msg.run ();
2967                 return -1;
2968         }
2969
2970         /* Give the new session the default GUI state, if such things exist */
2971
2972         XMLNode* n;
2973         n = Config->instant_xml (X_("Editor"));
2974         if (n) {
2975                 new_session->add_instant_xml (*n, false);
2976         }
2977         n = Config->instant_xml (X_("Mixer"));
2978         if (n) {
2979                 new_session->add_instant_xml (*n, false);
2980         }
2981
2982         /* Put the playhead at 0 and scroll fully left */
2983         n = new_session->instant_xml (X_("Editor"));
2984         if (n) {
2985                 n->add_property (X_("playhead"), X_("0"));
2986                 n->add_property (X_("left-frame"), X_("0"));
2987         }
2988
2989         set_session (new_session);
2990
2991         session_loaded = true;
2992
2993         new_session->save_state(new_session->name());
2994
2995         return 0;
2996 }
2997
2998 void
2999 ARDOUR_UI::launch_chat ()
3000 {
3001 #ifdef __APPLE__
3002         open_uri("http://webchat.freenode.net/?channels=ardour-osx");
3003 #else
3004         open_uri("http://webchat.freenode.net/?channels=ardour");
3005 #endif
3006 }
3007
3008 void
3009 ARDOUR_UI::launch_manual ()
3010 {
3011         PBD::open_uri (Config->get_tutorial_manual_url());
3012 }
3013
3014 void
3015 ARDOUR_UI::launch_reference ()
3016 {
3017         PBD::open_uri (Config->get_reference_manual_url());
3018 }
3019
3020 void
3021 ARDOUR_UI::loading_message (const std::string& msg)
3022 {
3023         if (ARDOUR_COMMAND_LINE::no_splash) {
3024                 return;
3025         }
3026
3027         if (!splash) {
3028                 show_splash ();
3029         }
3030
3031         splash->message (msg);
3032 }
3033
3034 void
3035 ARDOUR_UI::show_splash ()
3036 {
3037         if (splash == 0) {
3038                 try {
3039                         splash = new Splash;
3040                 } catch (...) {
3041                         return;
3042                 }
3043         }
3044
3045         splash->display ();
3046 }
3047
3048 void
3049 ARDOUR_UI::hide_splash ()
3050 {
3051         delete splash;
3052         splash = 0;
3053 }
3054
3055 void
3056 ARDOUR_UI::display_cleanup_results (ARDOUR::CleanupReport& rep, const gchar* list_title, const bool msg_delete)
3057 {
3058         size_t removed;
3059
3060         removed = rep.paths.size();
3061
3062         if (removed == 0) {
3063                 MessageDialog msgd (*editor,
3064                                     _("No files were ready for clean-up"),
3065                                     true,
3066                                     Gtk::MESSAGE_INFO,
3067                                     Gtk::BUTTONS_OK);
3068                 msgd.set_title (_("Clean-up"));
3069                 msgd.set_secondary_text (_("If this seems suprising, \n\
3070 check for any existing snapshots.\n\
3071 These may still include regions that\n\
3072 require some unused files to continue to exist."));
3073
3074                 msgd.run ();
3075                 return;
3076         }
3077
3078         ArdourDialog results (_("Clean-up"), true, false);
3079
3080         struct CleanupResultsModelColumns : public Gtk::TreeModel::ColumnRecord {
3081             CleanupResultsModelColumns() {
3082                     add (visible_name);
3083                     add (fullpath);
3084             }
3085             Gtk::TreeModelColumn<std::string> visible_name;
3086             Gtk::TreeModelColumn<std::string> fullpath;
3087         };
3088
3089
3090         CleanupResultsModelColumns results_columns;
3091         Glib::RefPtr<Gtk::ListStore> results_model;
3092         Gtk::TreeView results_display;
3093
3094         results_model = ListStore::create (results_columns);
3095         results_display.set_model (results_model);
3096         results_display.append_column (list_title, results_columns.visible_name);
3097
3098         results_display.set_name ("CleanupResultsList");
3099         results_display.set_headers_visible (true);
3100         results_display.set_headers_clickable (false);
3101         results_display.set_reorderable (false);
3102
3103         Gtk::ScrolledWindow list_scroller;
3104         Gtk::Label txt;
3105         Gtk::VBox dvbox;
3106         Gtk::HBox dhbox;  // the hbox for the image and text
3107         Gtk::HBox ddhbox; // the hbox we eventually pack into the dialog's vbox
3108         Gtk::Image* dimage = manage (new Gtk::Image(Stock::DIALOG_INFO,  Gtk::ICON_SIZE_DIALOG));
3109
3110         dimage->set_alignment(ALIGN_LEFT, ALIGN_TOP);
3111
3112         const string dead_directory = _session->session_directory().dead_path();
3113
3114         /* subst:
3115            %1 - number of files removed
3116            %2 - location of "dead"
3117            %3 - size of files affected
3118            %4 - prefix for "bytes" to produce sensible results (e.g. mega, kilo, giga)
3119         */
3120
3121         const char* bprefix;
3122         double space_adjusted = 0;
3123
3124         if (rep.space < 1000) {
3125                 bprefix = X_("");
3126                 space_adjusted = rep.space;
3127         } else if (rep.space < 1000000) {
3128                 bprefix = _("kilo");
3129                 space_adjusted = floorf((float)rep.space / 1000.0);
3130         } else if (rep.space < 1000000 * 1000) {
3131                 bprefix = _("mega");
3132                 space_adjusted = floorf((float)rep.space / (1000.0 * 1000.0));
3133         } else {
3134                 bprefix = _("giga");
3135                 space_adjusted = floorf((float)rep.space / (1000.0 * 1000 * 1000.0));
3136         }
3137
3138         if (msg_delete) {
3139                 txt.set_markup (string_compose (P_("\
3140 The following file was deleted from %2,\n\
3141 releasing %3 %4bytes of disk space", "\
3142 The following %1 files were deleted from %2,\n\
3143 releasing %3 %4bytes of disk space", removed),
3144                                         removed, Glib::Markup::escape_text (dead_directory), space_adjusted, bprefix, PROGRAM_NAME));
3145         } else {
3146                 txt.set_markup (string_compose (P_("\
3147 The following file was not in use and \n\
3148 has been moved to: %2\n\n\
3149 After a restart of %5\n\n\
3150 <span face=\"mono\">Session -> Clean-up -> Flush Wastebasket</span>\n\n\
3151 will release an additional %3 %4bytes of disk space.\n", "\
3152 The following %1 files were not in use and \n\
3153 have been moved to: %2\n\n\
3154 After a restart of %5\n\n\
3155 <span face=\"mono\">Session -> Clean-up -> Flush Wastebasket</span>\n\n\
3156 will release an additional %3 %4bytes of disk space.\n", removed),
3157                                         removed, Glib::Markup::escape_text (dead_directory), space_adjusted, bprefix, PROGRAM_NAME));
3158         }
3159
3160         dhbox.pack_start (*dimage, true, false, 5);
3161         dhbox.pack_start (txt, true, false, 5);
3162
3163         for (vector<string>::iterator i = rep.paths.begin(); i != rep.paths.end(); ++i) {
3164                 TreeModel::Row row = *(results_model->append());
3165                 row[results_columns.visible_name] = *i;
3166                 row[results_columns.fullpath] = *i;
3167         }
3168
3169         list_scroller.add (results_display);
3170         list_scroller.set_size_request (-1, 150);
3171         list_scroller.set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
3172
3173         dvbox.pack_start (dhbox, true, false, 5);
3174         dvbox.pack_start (list_scroller, true, false, 5);
3175         ddhbox.pack_start (dvbox, true, false, 5);
3176
3177         results.get_vbox()->pack_start (ddhbox, true, false, 5);
3178         results.add_button (Stock::CLOSE, RESPONSE_CLOSE);
3179         results.set_default_response (RESPONSE_CLOSE);
3180         results.set_position (Gtk::WIN_POS_MOUSE);
3181
3182         results_display.show();
3183         list_scroller.show();
3184         txt.show();
3185         dvbox.show();
3186         dhbox.show();
3187         ddhbox.show();
3188         dimage->show();
3189
3190         //results.get_vbox()->show();
3191         results.set_resizable (false);
3192
3193         results.run ();
3194
3195 }
3196
3197 void
3198 ARDOUR_UI::cleanup ()
3199 {
3200         if (_session == 0) {
3201                 /* shouldn't happen: menu item is insensitive */
3202                 return;
3203         }
3204
3205
3206         MessageDialog checker (_("Are you sure you want to clean-up?"),
3207                                 true,
3208                                 Gtk::MESSAGE_QUESTION,
3209                                 Gtk::BUTTONS_NONE);
3210
3211         checker.set_title (_("Clean-up"));
3212
3213         checker.set_secondary_text(_("Clean-up is a destructive operation.\n\
3214 ALL undo/redo information will be lost if you clean-up.\n\
3215 Clean-up will move all unused files to a \"dead\" location."));
3216
3217         checker.add_button (Stock::CANCEL, RESPONSE_CANCEL);
3218         checker.add_button (_("Clean-up"), RESPONSE_ACCEPT);
3219         checker.set_default_response (RESPONSE_CANCEL);
3220
3221         checker.set_name (_("CleanupDialog"));
3222         checker.set_wmclass (X_("ardour_cleanup"), PROGRAM_NAME);
3223         checker.set_position (Gtk::WIN_POS_MOUSE);
3224
3225         switch (checker.run()) {
3226         case RESPONSE_ACCEPT:
3227                 break;
3228         default:
3229                 return;
3230         }
3231
3232         ARDOUR::CleanupReport rep;
3233
3234         editor->prepare_for_cleanup ();
3235
3236         /* do not allow flush until a session is reloaded */
3237
3238         Glib::RefPtr<Action> act = ActionManager::get_action (X_("Main"), X_("FlushWastebasket"));
3239         if (act) {
3240                 act->set_sensitive (false);
3241         }
3242
3243         if (_session->cleanup_sources (rep)) {
3244                 editor->finish_cleanup ();
3245                 return;
3246         }
3247
3248         editor->finish_cleanup ();
3249
3250         checker.hide();
3251         display_cleanup_results (rep, _("Cleaned Files"), false);
3252 }
3253
3254 void
3255 ARDOUR_UI::flush_trash ()
3256 {
3257         if (_session == 0) {
3258                 /* shouldn't happen: menu item is insensitive */
3259                 return;
3260         }
3261
3262         ARDOUR::CleanupReport rep;
3263
3264         if (_session->cleanup_trash_sources (rep)) {
3265                 return;
3266         }
3267
3268         display_cleanup_results (rep, _("deleted file"), true);
3269 }
3270
3271 void
3272 ARDOUR_UI::setup_order_hint ()
3273 {
3274         uint32_t order_hint = 0;
3275
3276         /*
3277           we want the new routes to have their order keys set starting from 
3278           the highest order key in the selection + 1 (if available).
3279         */
3280         if (add_route_dialog->get_transient_for () == mixer->get_toplevel()) {
3281                 for (RouteUISelection::iterator s = mixer->selection().routes.begin(); s != mixer->selection().routes.end(); ++s) {
3282                         if ((*s)->route()->order_key() > order_hint) {
3283                                 order_hint = (*s)->route()->order_key();
3284                         }
3285                 }
3286
3287                 if (!mixer->selection().routes.empty()) {
3288                         order_hint++;
3289                 }
3290
3291         } else {
3292                 for (TrackSelection::iterator s = editor->get_selection().tracks.begin(); s != editor->get_selection().tracks.end(); ++s) {
3293                         RouteTimeAxisView* tav = dynamic_cast<RouteTimeAxisView*> (*s);
3294                         if (tav && tav->route() && tav->route()->order_key() > order_hint) {
3295                                 order_hint = tav->route()->order_key();
3296                         }
3297                 }
3298
3299                 if (!editor->get_selection().tracks.empty()) {
3300                         order_hint++;
3301                 }
3302         }
3303
3304         _session->set_order_hint (order_hint);
3305
3306         /* create a gap in the existing route order keys to accomodate new routes.*/
3307
3308         boost::shared_ptr <RouteList> rd = _session->get_routes();
3309         for (RouteList::iterator ri = rd->begin(); ri != rd->end(); ++ri) {
3310                 boost::shared_ptr<Route> rt (*ri);
3311                         
3312                 if (rt->is_monitor()) {
3313                         continue;
3314                 }
3315
3316                 if (rt->order_key () >= order_hint) {
3317                         rt->set_order_key (rt->order_key () + add_route_dialog->count());
3318                 }
3319         }
3320 }
3321
3322 void
3323 ARDOUR_UI::add_route (Gtk::Window* float_window)
3324 {
3325         int count;
3326
3327         if (!_session) {
3328                 return;
3329         }
3330
3331         if (add_route_dialog->is_visible()) {
3332                 /* we're already doing this */
3333                 return;
3334         }
3335
3336         if (float_window) {
3337                 add_route_dialog->unset_transient_for ();
3338                 add_route_dialog->set_transient_for (*float_window);
3339         }
3340
3341         ResponseType r = (ResponseType) add_route_dialog->run ();
3342
3343         add_route_dialog->hide();
3344
3345         switch (r) {
3346                 case RESPONSE_ACCEPT:
3347                         break;
3348                 default:
3349                         return;
3350                         break;
3351         }
3352
3353         if ((count = add_route_dialog->count()) <= 0) {
3354                 return;
3355         }
3356
3357         setup_order_hint();
3358
3359         PBD::ScopedConnection idle_connection;
3360
3361         string template_path = add_route_dialog->track_template();
3362
3363         if (!template_path.empty()) {
3364                 if (add_route_dialog->name_template_is_default())  {
3365                         _session->new_route_from_template (count, template_path, string());
3366                 } else {
3367                         _session->new_route_from_template (count, template_path, add_route_dialog->name_template());
3368                 }
3369                 return;
3370         }
3371
3372         ChanCount input_chan= add_route_dialog->channels ();
3373         ChanCount output_chan;
3374         string name_template = add_route_dialog->name_template ();
3375         PluginInfoPtr instrument = add_route_dialog->requested_instrument ();
3376         RouteGroup* route_group = add_route_dialog->route_group ();
3377         AutoConnectOption oac = Config->get_output_auto_connect();
3378
3379         if (oac & AutoConnectMaster) {
3380                 output_chan.set (DataType::AUDIO, (_session->master_out() ? _session->master_out()->n_inputs().n_audio() : input_chan.n_audio()));
3381                 output_chan.set (DataType::MIDI, 0);
3382         } else {
3383                 output_chan = input_chan;
3384         }
3385
3386         /* XXX do something with name template */
3387
3388         switch (add_route_dialog->type_wanted()) {
3389         case AddRouteDialog::AudioTrack:
3390                 session_add_audio_track (input_chan.n_audio(), output_chan.n_audio(), add_route_dialog->mode(), route_group, count, name_template);
3391                 break;
3392         case AddRouteDialog::MidiTrack:
3393                 session_add_midi_track (route_group, count, name_template, instrument);
3394                 break;
3395         case AddRouteDialog::MixedTrack:
3396                 session_add_mixed_track (input_chan, output_chan, route_group, count, name_template, instrument);
3397                 break;
3398         case AddRouteDialog::AudioBus:
3399                 session_add_audio_bus (input_chan.n_audio(), output_chan.n_audio(), route_group, count, name_template);
3400                 break;
3401         }
3402
3403         /* idle connection will end at scope end */
3404 }
3405
3406 void
3407 ARDOUR_UI::stop_video_server (bool ask_confirm)
3408 {
3409         if (!video_server_process && ask_confirm) {
3410                 warning << string_compose (_("Video-Server was not launched by %1. The request to stop it is ignored."), PROGRAM_NAME) << endmsg;
3411         }
3412         if (video_server_process) {
3413                 if(ask_confirm) {
3414                         ArdourDialog confirm (_("Stop Video-Server"), true);
3415                         Label m (_("Do you really want to stop the Video Server?"));
3416                         confirm.get_vbox()->pack_start (m, true, true);
3417                         confirm.add_button (Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
3418                         confirm.add_button (_("Yes, Stop It"), Gtk::RESPONSE_ACCEPT);
3419                         confirm.show_all ();
3420                         if (confirm.run() == RESPONSE_CANCEL) {
3421                                 return;
3422                         }
3423                 }
3424                 delete video_server_process;
3425                 video_server_process =0;
3426         }
3427 }
3428
3429 void
3430 ARDOUR_UI::start_video_server_menu (Gtk::Window* float_window)
3431 {
3432   ARDOUR_UI::start_video_server( float_window, true);
3433 }
3434
3435 bool
3436 ARDOUR_UI::start_video_server (Gtk::Window* float_window, bool popup_msg)
3437 {
3438         if (!_session) {
3439                 return false;
3440         }
3441         if (popup_msg) {
3442                 if (ARDOUR_UI::instance()->video_timeline->check_server()) {
3443                         if (video_server_process) {
3444                                 popup_error(_("The Video Server is already started."));
3445                         } else {
3446                                 popup_error(_("An external Video Server is configured and can be reached. Not starting a new instance."));
3447                         }
3448                 }
3449         }
3450
3451         int firsttime = 0;
3452         while (!ARDOUR_UI::instance()->video_timeline->check_server()) {
3453                 if (firsttime++) {
3454                         warning << _("Could not connect to the Video Server. Start it or configure its access URL in Edit -> Preferences.") << endmsg;
3455                 }
3456                 VideoServerDialog *video_server_dialog = new VideoServerDialog (_session);
3457                 if (float_window) {
3458                         video_server_dialog->set_transient_for (*float_window);
3459                 }
3460
3461                 if (!Config->get_show_video_server_dialog() && firsttime < 2) {
3462                         video_server_dialog->hide();
3463                 } else {
3464                         ResponseType r = (ResponseType) video_server_dialog->run ();
3465                         video_server_dialog->hide();
3466                         if (r != RESPONSE_ACCEPT) { return false; }
3467                         if (video_server_dialog->show_again()) {
3468                                 Config->set_show_video_server_dialog(false);
3469                         }
3470                 }
3471
3472                 std::string icsd_exec = video_server_dialog->get_exec_path();
3473                 std::string icsd_docroot = video_server_dialog->get_docroot();
3474                 if (icsd_docroot.empty()) {icsd_docroot = X_("/");}
3475
3476                 GStatBuf sb;
3477                 if (!g_lstat (icsd_docroot.c_str(), &sb) == 0 || !S_ISDIR(sb.st_mode)) {
3478                         warning << _("Specified docroot is not an existing directory.") << endmsg;
3479                         continue;
3480                 }
3481 #ifndef PLATFORM_WINDOWS
3482                 if ( (!g_lstat (icsd_exec.c_str(), &sb) == 0)
3483                      || (sb.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0 ) {
3484                         warning << _("Given Video Server is not an executable file.") << endmsg;
3485                         continue;
3486                 }
3487 #else
3488                 if ( (!g_lstat (icsd_exec.c_str(), &sb) == 0)
3489                      || (sb.st_mode & (S_IXUSR)) == 0 ) {
3490                         warning << _("Given Video Server is not an executable file.") << endmsg;
3491                         continue;
3492                 }
3493 #endif
3494
3495                 char **argp;
3496                 argp=(char**) calloc(9,sizeof(char*));
3497                 argp[0] = strdup(icsd_exec.c_str());
3498                 argp[1] = strdup("-P");
3499                 argp[2] = (char*) calloc(16,sizeof(char)); snprintf(argp[2], 16, "%s", video_server_dialog->get_listenaddr().c_str());
3500                 argp[3] = strdup("-p");
3501                 argp[4] = (char*) calloc(6,sizeof(char)); snprintf(argp[4], 6, "%i", video_server_dialog->get_listenport());
3502                 argp[5] = strdup("-C");
3503                 argp[6] = (char*) calloc(6,sizeof(char)); snprintf(argp[6], 6, "%i", video_server_dialog->get_cachesize());
3504                 argp[7] = strdup(icsd_docroot.c_str());
3505                 argp[8] = 0;
3506                 stop_video_server();
3507
3508                 if (icsd_docroot == X_("/")) {
3509                         Config->set_video_advanced_setup(false);
3510                 } else {
3511                         std::ostringstream osstream;
3512                         osstream << "http://localhost:" << video_server_dialog->get_listenport() << "/";
3513                         Config->set_video_server_url(osstream.str());
3514                         Config->set_video_server_docroot(icsd_docroot);
3515                         Config->set_video_advanced_setup(true);
3516                 }
3517
3518                 if (video_server_process) {
3519                         delete video_server_process;
3520                 }
3521
3522                 video_server_process = new ARDOUR::SystemExec(icsd_exec, argp);
3523                 if (video_server_process->start()) {
3524                         warning << _("Cannot launch the video-server") << endmsg;
3525                         continue;
3526                 }
3527                 int timeout = 120; // 6 sec
3528                 while (!ARDOUR_UI::instance()->video_timeline->check_server()) {
3529                         Glib::usleep (50000);
3530                         if (--timeout <= 0 || !video_server_process->is_running()) break;
3531                 }
3532                 if (timeout <= 0) {
3533                         warning << _("Video-server was started but does not respond to requests...") << endmsg;
3534                 } else {
3535                         if (!ARDOUR_UI::instance()->video_timeline->check_server_docroot()) {
3536                                 delete video_server_process;
3537                                 video_server_process = 0;
3538                         }
3539                 }
3540         }
3541         return true;
3542 }
3543
3544 void
3545 ARDOUR_UI::add_video (Gtk::Window* float_window)
3546 {
3547         if (!_session) {
3548                 return;
3549         }
3550
3551         if (!start_video_server(float_window, false)) {
3552                 warning << _("Could not connect to the Video Server. Start it or configure its access URL in Edit -> Preferences.") << endmsg;
3553                 return;
3554         }
3555
3556         if (float_window) {
3557                 add_video_dialog->set_transient_for (*float_window);
3558         }
3559
3560         if (add_video_dialog->is_visible()) {
3561                 /* we're already doing this */
3562                 return;
3563         }
3564
3565         ResponseType r = (ResponseType) add_video_dialog->run ();
3566         add_video_dialog->hide();
3567         if (r != RESPONSE_ACCEPT) { return; }
3568
3569         bool local_file, orig_local_file;
3570         std::string path = add_video_dialog->file_name(local_file);
3571
3572         std::string orig_path = path;
3573         orig_local_file = local_file;
3574
3575         bool auto_set_session_fps = add_video_dialog->auto_set_session_fps();
3576
3577         if (local_file && !Glib::file_test(path, Glib::FILE_TEST_EXISTS)) {
3578                 warning << string_compose(_("could not open %1"), path) << endmsg;
3579                 return;
3580         }
3581         if (!local_file && path.length() == 0) {
3582                 warning << _("no video-file selected") << endmsg;
3583                 return;
3584         }
3585
3586         switch (add_video_dialog->import_option()) {
3587                 case VTL_IMPORT_TRANSCODE:
3588                         {
3589                                 TranscodeVideoDialog *transcode_video_dialog;
3590                                 transcode_video_dialog = new TranscodeVideoDialog (_session, path);
3591                                 ResponseType r = (ResponseType) transcode_video_dialog->run ();
3592                                 transcode_video_dialog->hide();
3593                                 if (r != RESPONSE_ACCEPT) {
3594                                         delete transcode_video_dialog;
3595                                         return;
3596                                 }
3597                                 if (!transcode_video_dialog->get_audiofile().empty()) {
3598                                         editor->embed_audio_from_video(
3599                                                         transcode_video_dialog->get_audiofile(),
3600                                                         video_timeline->get_offset(),
3601                                                         (transcode_video_dialog->import_option() != VTL_IMPORT_NO_VIDEO)
3602                                                         );
3603                                 }
3604                                 switch (transcode_video_dialog->import_option()) {
3605                                         case VTL_IMPORT_TRANSCODED:
3606                                                 path = transcode_video_dialog->get_filename();
3607                                                 local_file = true;
3608                                                 break;
3609                                         case VTL_IMPORT_REFERENCE:
3610                                                 break;
3611                                         default:
3612                                                 delete transcode_video_dialog;
3613                                                 return;
3614                                 }
3615                                 delete transcode_video_dialog;
3616                         }
3617                         break;
3618                 default:
3619                 case VTL_IMPORT_NONE:
3620                         break;
3621         }
3622
3623         /* strip _session->session_directory().video_path() from video file if possible */
3624         if (local_file && !path.compare(0, _session->session_directory().video_path().size(), _session->session_directory().video_path())) {
3625                  path=path.substr(_session->session_directory().video_path().size());
3626                  if (path.at(0) == G_DIR_SEPARATOR) {
3627                          path=path.substr(1);
3628                  }
3629         }
3630
3631         video_timeline->set_update_session_fps(auto_set_session_fps);
3632         if (video_timeline->video_file_info(path, local_file)) {
3633                 XMLNode* node = new XMLNode(X_("Videotimeline"));
3634                 node->add_property (X_("Filename"), path);
3635                 node->add_property (X_("AutoFPS"), auto_set_session_fps?X_("1"):X_("0"));
3636                 node->add_property (X_("LocalFile"), local_file?X_("1"):X_("0"));
3637                 if (orig_local_file) {
3638                         node->add_property (X_("OriginalVideoFile"), orig_path);
3639                 } else {
3640                         node->remove_property (X_("OriginalVideoFile"));
3641                 }
3642                 _session->add_extra_xml (*node);
3643                 _session->set_dirty ();
3644
3645                 _session->maybe_update_session_range(
3646                         std::max(video_timeline->get_offset(), (ARDOUR::frameoffset_t) 0),
3647                         std::max(video_timeline->get_offset() + video_timeline->get_duration(), (ARDOUR::frameoffset_t) 0));
3648
3649
3650                 if (add_video_dialog->launch_xjadeo() && local_file) {
3651                         editor->set_xjadeo_sensitive(true);
3652                         editor->toggle_xjadeo_proc(1);
3653                 } else {
3654                         editor->toggle_xjadeo_proc(0);
3655                 }
3656                 editor->toggle_ruler_video(true);
3657         }
3658 }
3659
3660 void
3661 ARDOUR_UI::remove_video ()
3662 {
3663         video_timeline->close_session();
3664         editor->toggle_ruler_video(false);
3665
3666         /* reset state */
3667         video_timeline->set_offset_locked(false);
3668         video_timeline->set_offset(0);
3669
3670         /* delete session state */
3671         XMLNode* node = new XMLNode(X_("Videotimeline"));
3672         _session->add_extra_xml(*node);
3673         node = new XMLNode(X_("Videomonitor"));
3674         _session->add_extra_xml(*node);
3675         stop_video_server();
3676 }
3677
3678 void
3679 ARDOUR_UI::flush_videotimeline_cache (bool localcacheonly)
3680 {
3681         if (localcacheonly) {
3682                 video_timeline->vmon_update();
3683         } else {
3684                 video_timeline->flush_cache();
3685         }
3686         editor->queue_visual_videotimeline_update();
3687 }
3688
3689 XMLNode*
3690 ARDOUR_UI::mixer_settings () const
3691 {
3692         XMLNode* node = 0;
3693
3694         if (_session) {
3695                 node = _session->instant_xml(X_("Mixer"));
3696         } else {
3697                 node = Config->instant_xml(X_("Mixer"));
3698         }
3699
3700         if (!node) {
3701                 node = new XMLNode (X_("Mixer"));
3702         }
3703
3704         return node;
3705 }
3706
3707 XMLNode*
3708 ARDOUR_UI::editor_settings () const
3709 {
3710         XMLNode* node = 0;
3711
3712         if (_session) {
3713                 node = _session->instant_xml(X_("Editor"));
3714         } else {
3715                 node = Config->instant_xml(X_("Editor"));
3716         }
3717
3718         if (!node) {
3719                 if (getenv("ARDOUR_INSTANT_XML_PATH")) {
3720                         node = Config->instant_xml(getenv("ARDOUR_INSTANT_XML_PATH"));
3721                 }
3722         }
3723
3724         if (!node) {
3725                 node = new XMLNode (X_("Editor"));
3726         }
3727
3728         return node;
3729 }
3730
3731 XMLNode*
3732 ARDOUR_UI::keyboard_settings () const
3733 {
3734         XMLNode* node = 0;
3735
3736         node = Config->extra_xml(X_("Keyboard"));
3737
3738         if (!node) {
3739                 node = new XMLNode (X_("Keyboard"));
3740         }
3741
3742         return node;
3743 }
3744
3745 void
3746 ARDOUR_UI::create_xrun_marker (framepos_t where)
3747 {
3748         editor->mouse_add_new_marker (where, false, true);
3749 }
3750
3751 void
3752 ARDOUR_UI::halt_on_xrun_message ()
3753 {
3754         MessageDialog msg (*editor,
3755                            _("Recording was stopped because your system could not keep up."));
3756         msg.run ();
3757 }
3758
3759 void
3760 ARDOUR_UI::xrun_handler (framepos_t where)
3761 {
3762         if (!_session) {
3763                 return;
3764         }
3765
3766         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::xrun_handler, where)
3767
3768         if (_session && Config->get_create_xrun_marker() && _session->actively_recording()) {
3769                 create_xrun_marker(where);
3770         }
3771
3772         if (_session && Config->get_stop_recording_on_xrun() && _session->actively_recording()) {
3773                 halt_on_xrun_message ();
3774         }
3775 }
3776
3777 void
3778 ARDOUR_UI::disk_overrun_handler ()
3779 {
3780         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::disk_overrun_handler)
3781
3782         if (!have_disk_speed_dialog_displayed) {
3783                 have_disk_speed_dialog_displayed = true;
3784                 MessageDialog* msg = new MessageDialog (*editor, string_compose (_("\
3785 The disk system on your computer\n\
3786 was not able to keep up with %1.\n\
3787 \n\
3788 Specifically, it failed to write data to disk\n\
3789 quickly enough to keep up with recording.\n"), PROGRAM_NAME));
3790                 msg->signal_response().connect (sigc::bind (sigc::mem_fun (*this, &ARDOUR_UI::disk_speed_dialog_gone), msg));
3791                 msg->show ();
3792         }
3793 }
3794
3795
3796 /* TODO: this is getting elaborate enough to warrant being split into a dedicated class */
3797 static MessageDialog *scan_dlg = NULL;
3798 static ProgressBar   *scan_pbar = NULL;
3799 static HBox          *scan_tbox = NULL;
3800
3801 void
3802 ARDOUR_UI::cancel_plugin_scan ()
3803 {
3804         PluginManager::instance().cancel_plugin_scan();
3805 }
3806
3807 void
3808 ARDOUR_UI::cancel_plugin_timeout ()
3809 {
3810         PluginManager::instance().cancel_plugin_timeout();
3811         scan_tbox->hide();
3812 }
3813
3814 void
3815 ARDOUR_UI::plugin_scan_timeout (int timeout)
3816 {
3817         if (!scan_dlg || !scan_dlg->is_mapped() || !scan_pbar) {
3818                 return;
3819         }
3820         if (timeout > 0) {
3821                 scan_pbar->set_fraction ((float) timeout / (float) Config->get_vst_scan_timeout());
3822                 scan_tbox->show();
3823         } else {
3824                 scan_tbox->hide();
3825         }
3826         gui_idle_handler();
3827 }
3828
3829 void
3830 ARDOUR_UI::plugin_scan_dialog (std::string type, std::string plugin, bool can_cancel)
3831 {
3832         if (type == X_("closeme") && !(scan_dlg && scan_dlg->is_mapped())) {
3833                 return;
3834         }
3835
3836         const bool cancelled = PluginManager::instance().cancelled();
3837         if (type != X_("closeme") && !Config->get_show_plugin_scan_window()) {
3838                 if (cancelled && scan_dlg->is_mapped()) {
3839                         scan_dlg->hide();
3840                         gui_idle_handler();
3841                         return;
3842                 }
3843                 if (cancelled || !can_cancel) {
3844                         return;
3845                 }
3846         }
3847
3848         static Gtk::Button *cancel_button;
3849         static Gtk::Button *timeout_button;
3850         if (!scan_dlg) {
3851                 scan_dlg = new MessageDialog("", false, MESSAGE_INFO, BUTTONS_NONE); // TODO manage
3852                 VBox* vbox = scan_dlg->get_vbox();
3853                 vbox->set_size_request(400,-1);
3854                 scan_dlg->set_title (_("Scanning for plugins"));
3855
3856                 cancel_button = manage(new Gtk::Button(_("Cancel plugin scan")));
3857                 cancel_button->set_name ("EditorGTKButton");
3858                 cancel_button->signal_clicked().connect ( mem_fun (*this, &ARDOUR_UI::cancel_plugin_scan) );
3859                 cancel_button->show();
3860
3861                 scan_dlg->get_vbox()->pack_start ( *cancel_button, PACK_SHRINK);
3862
3863                 scan_tbox = manage( new HBox() );
3864
3865                 timeout_button = manage(new Gtk::Button(_("Stop Timeout")));
3866                 timeout_button->set_name ("EditorGTKButton");
3867                 timeout_button->signal_clicked().connect ( mem_fun (*this, &ARDOUR_UI::cancel_plugin_timeout) );
3868                 timeout_button->show();
3869
3870                 scan_pbar = manage(new ProgressBar());
3871                 scan_pbar->set_orientation(Gtk::PROGRESS_RIGHT_TO_LEFT);
3872                 scan_pbar->set_text(_("Scan Timeout"));
3873                 scan_pbar->show();
3874
3875                 scan_tbox->pack_start (*scan_pbar, PACK_EXPAND_WIDGET, 4);
3876                 scan_tbox->pack_start (*timeout_button, PACK_SHRINK, 4);
3877
3878                 scan_dlg->get_vbox()->pack_start (*scan_tbox, PACK_SHRINK, 4);
3879         }
3880
3881         if (type == X_("closeme")) {
3882                 scan_dlg->hide();
3883         } else {
3884                 scan_dlg->set_message(type + ": " + Glib::path_get_basename(plugin));
3885                 scan_dlg->show();
3886         }
3887         if (!can_cancel || !cancelled) {
3888                 scan_tbox->hide();
3889         }
3890         cancel_button->set_sensitive(can_cancel && !cancelled);
3891
3892         gui_idle_handler();
3893 }
3894
3895 void
3896 ARDOUR_UI::gui_idle_handler ()
3897 {
3898         int timeout = 30;
3899         /* due to idle calls, gtk_events_pending() may always return true */
3900         while (gtk_events_pending() && --timeout) {
3901                 gtk_main_iteration ();
3902         }
3903 }
3904
3905 void
3906 ARDOUR_UI::disk_underrun_handler ()
3907 {
3908         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::disk_underrun_handler)
3909
3910         if (!have_disk_speed_dialog_displayed) {
3911                 have_disk_speed_dialog_displayed = true;
3912                 MessageDialog* msg = new MessageDialog (
3913                         *editor, string_compose (_("The disk system on your computer\n\
3914 was not able to keep up with %1.\n\
3915 \n\
3916 Specifically, it failed to read data from disk\n\
3917 quickly enough to keep up with playback.\n"), PROGRAM_NAME));
3918                 msg->signal_response().connect (sigc::bind (sigc::mem_fun (*this, &ARDOUR_UI::disk_speed_dialog_gone), msg));
3919                 msg->show ();
3920         }
3921 }
3922
3923 void
3924 ARDOUR_UI::disk_speed_dialog_gone (int /*ignored_response*/, MessageDialog* msg)
3925 {
3926         have_disk_speed_dialog_displayed = false;
3927         delete msg;
3928 }
3929
3930 void
3931 ARDOUR_UI::session_dialog (std::string msg)
3932 {
3933         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::session_dialog, msg)
3934
3935         MessageDialog* d;
3936
3937         if (editor) {
3938                 d = new MessageDialog (*editor, msg, false, MESSAGE_INFO, BUTTONS_OK, true);
3939         } else {
3940                 d = new MessageDialog (msg, false, MESSAGE_INFO, BUTTONS_OK, true);
3941         }
3942
3943         d->show_all ();
3944         d->run ();
3945         delete d;
3946 }
3947
3948 int
3949 ARDOUR_UI::pending_state_dialog ()
3950 {
3951         HBox* hbox = manage (new HBox());
3952         Image* image = manage (new Image (Stock::DIALOG_QUESTION, ICON_SIZE_DIALOG));
3953         ArdourDialog dialog (_("Crash Recovery"), true);
3954         Label  message (string_compose (_("\
3955 This session appears to have been in the\n\
3956 middle of recording when %1 or\n\
3957 the computer was shutdown.\n\
3958 \n\
3959 %1 can recover any captured audio for\n\
3960 you, or it can ignore it. Please decide\n\
3961 what you would like to do.\n"), PROGRAM_NAME));
3962         image->set_alignment(ALIGN_CENTER, ALIGN_TOP);
3963         hbox->pack_start (*image, PACK_EXPAND_WIDGET, 12);
3964         hbox->pack_end (message, PACK_EXPAND_PADDING, 12);
3965         dialog.get_vbox()->pack_start(*hbox, PACK_EXPAND_PADDING, 6);
3966         dialog.add_button (_("Ignore crash data"), RESPONSE_REJECT);
3967         dialog.add_button (_("Recover from crash"), RESPONSE_ACCEPT);
3968         dialog.set_default_response (RESPONSE_ACCEPT);
3969         dialog.set_position (WIN_POS_CENTER);
3970         message.show();
3971         image->show();
3972         hbox->show();
3973
3974         switch (dialog.run ()) {
3975         case RESPONSE_ACCEPT:
3976                 return 1;
3977         default:
3978                 return 0;
3979         }
3980 }
3981
3982 int
3983 ARDOUR_UI::sr_mismatch_dialog (framecnt_t desired, framecnt_t actual)
3984 {
3985         HBox* hbox = new HBox();
3986         Image* image = new Image (Stock::DIALOG_WARNING, ICON_SIZE_DIALOG);
3987         ArdourDialog dialog (_("Sample Rate Mismatch"), true);
3988         Label  message (string_compose (_("\
3989 This session was created with a sample rate of %1 Hz, but\n\
3990 %2 is currently running at %3 Hz.  If you load this session,\n\
3991 audio may be played at the wrong sample rate.\n"), desired, PROGRAM_NAME, actual));
3992
3993         image->set_alignment(ALIGN_CENTER, ALIGN_TOP);
3994         hbox->pack_start (*image, PACK_EXPAND_WIDGET, 12);
3995         hbox->pack_end (message, PACK_EXPAND_PADDING, 12);
3996         dialog.get_vbox()->pack_start(*hbox, PACK_EXPAND_PADDING, 6);
3997         dialog.add_button (_("Do not load session"), RESPONSE_REJECT);
3998         dialog.add_button (_("Load session anyway"), RESPONSE_ACCEPT);
3999         dialog.set_default_response (RESPONSE_ACCEPT);
4000         dialog.set_position (WIN_POS_CENTER);
4001         message.show();
4002         image->show();
4003         hbox->show();
4004
4005         switch (dialog.run()) {
4006         case RESPONSE_ACCEPT:
4007                 return 0;
4008         default:
4009                 break;
4010         }
4011
4012         return 1;
4013 }
4014
4015 int
4016 ARDOUR_UI::disconnect_from_engine ()
4017 {
4018         /* drop connection to AudioEngine::Halted so that we don't act
4019          *  as if the engine unexpectedly shut down
4020          */
4021
4022         halt_connection.disconnect ();
4023         
4024         if (AudioEngine::instance()->stop ()) {
4025                 MessageDialog msg (*editor, _("Could not disconnect from Audio/MIDI engine"));
4026                 msg.run ();
4027                 return -1;
4028         } else {
4029                 AudioEngine::instance()->Halted.connect_same_thread (halt_connection, boost::bind (&ARDOUR_UI::engine_halted, this, _1, false));
4030         }
4031         
4032         update_sample_rate (0);
4033         return 0;
4034 }
4035
4036 int
4037 ARDOUR_UI::reconnect_to_engine ()
4038 {
4039         if (AudioEngine::instance()->start ()) {
4040                 if (editor) {
4041                         MessageDialog msg (*editor,  _("Could not reconnect to the Audio/MIDI engine"));
4042                         msg.run ();
4043                 } else {
4044                         MessageDialog msg (_("Could not reconnect to the Audio/MIDI engine"));
4045                         msg.run ();
4046                 }
4047                 return -1;
4048         }
4049         
4050         update_sample_rate (0);
4051         return 0;
4052 }
4053
4054 void
4055 ARDOUR_UI::use_config ()
4056 {
4057         XMLNode* node = Config->extra_xml (X_("TransportControllables"));
4058         if (node) {
4059                 set_transport_controllable_state (*node);
4060         }
4061 }
4062
4063 void
4064 ARDOUR_UI::update_transport_clocks (framepos_t pos)
4065 {
4066         if (Config->get_primary_clock_delta_edit_cursor()) {
4067                 primary_clock->set (pos, false, editor->get_preferred_edit_position());
4068         } else {
4069                 primary_clock->set (pos);
4070         }
4071
4072         if (Config->get_secondary_clock_delta_edit_cursor()) {
4073                 secondary_clock->set (pos, false, editor->get_preferred_edit_position());
4074         } else {
4075                 secondary_clock->set (pos);
4076         }
4077
4078         if (big_clock_window) {
4079                 big_clock->set (pos);
4080         }
4081         ARDOUR_UI::instance()->video_timeline->manual_seek_video_monitor(pos);
4082 }
4083
4084 void
4085 ARDOUR_UI::step_edit_status_change (bool yn)
4086 {
4087         // XXX should really store pre-step edit status of things
4088         // we make insensitive
4089
4090         if (yn) {
4091                 rec_button.set_active_state (Gtkmm2ext::ImplicitActive);
4092                 rec_button.set_sensitive (false);
4093         } else {
4094                 rec_button.unset_active_state ();;
4095                 rec_button.set_sensitive (true);
4096         }
4097 }
4098
4099 void
4100 ARDOUR_UI::record_state_changed ()
4101 {
4102         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::record_state_changed);
4103
4104         if (!_session || !big_clock_window) {
4105                 /* why bother - the clock isn't visible */
4106                 return;
4107         }
4108
4109         if (_session->record_status () == Session::Recording && _session->have_rec_enabled_track ()) {
4110                 big_clock->set_active (true);
4111         } else {
4112                 big_clock->set_active (false);
4113         }
4114 }
4115
4116 bool
4117 ARDOUR_UI::first_idle ()
4118 {
4119         if (_session) {
4120                 _session->allow_auto_play (true);
4121         }
4122
4123         if (editor) {
4124                 editor->first_idle();
4125         }
4126
4127         Keyboard::set_can_save_keybindings (true);
4128         return false;
4129 }
4130
4131 void
4132 ARDOUR_UI::store_clock_modes ()
4133 {
4134         XMLNode* node = new XMLNode(X_("ClockModes"));
4135
4136         for (vector<AudioClock*>::iterator x = AudioClock::clocks.begin(); x != AudioClock::clocks.end(); ++x) {
4137                 XMLNode* child = new XMLNode (X_("Clock"));
4138                 
4139                 child->add_property (X_("name"), (*x)->name());
4140                 child->add_property (X_("mode"), enum_2_string ((*x)->mode()));
4141                 child->add_property (X_("on"), ((*x)->off() ? X_("no") : X_("yes")));
4142
4143                 node->add_child_nocopy (*child);
4144         }
4145
4146         _session->add_extra_xml (*node);
4147         _session->set_dirty ();
4148 }
4149
4150 ARDOUR_UI::TransportControllable::TransportControllable (std::string name, ARDOUR_UI& u, ToggleType tp)
4151         : Controllable (name), ui (u), type(tp)
4152 {
4153
4154 }
4155
4156 void
4157 ARDOUR_UI::TransportControllable::set_value (double val)
4158 {
4159         if (val < 0.5) {
4160                 /* do nothing: these are radio-style actions */
4161                 return;
4162         }
4163
4164         const char *action = 0;
4165
4166         switch (type) {
4167         case Roll:
4168                 action = X_("Roll");
4169                 break;
4170         case Stop:
4171                 action = X_("Stop");
4172                 break;
4173         case GotoStart:
4174                 action = X_("GotoStart");
4175                 break;
4176         case GotoEnd:
4177                 action = X_("GotoEnd");
4178                 break;
4179         case AutoLoop:
4180                 action = X_("Loop");
4181                 break;
4182         case PlaySelection:
4183                 action = X_("PlaySelection");
4184                 break;
4185         case RecordEnable:
4186                 action = X_("Record");
4187                 break;
4188         default:
4189                 break;
4190         }
4191
4192         if (action == 0) {
4193                 return;
4194         }
4195
4196         Glib::RefPtr<Action> act = ActionManager::get_action ("Transport", action);
4197
4198         if (act) {
4199                 act->activate ();
4200         }
4201 }
4202
4203 double
4204 ARDOUR_UI::TransportControllable::get_value (void) const
4205 {
4206         float val = 0.0;
4207
4208         switch (type) {
4209         case Roll:
4210                 break;
4211         case Stop:
4212                 break;
4213         case GotoStart:
4214                 break;
4215         case GotoEnd:
4216                 break;
4217         case AutoLoop:
4218                 break;
4219         case PlaySelection:
4220                 break;
4221         case RecordEnable:
4222                 break;
4223         default:
4224                 break;
4225         }
4226
4227         return val;
4228 }
4229
4230 void
4231 ARDOUR_UI::setup_profile ()
4232 {
4233         if (gdk_screen_width() < 1200 || getenv ("ARDOUR_NARROW_SCREEN")) {
4234                 Profile->set_small_screen ();
4235         }
4236
4237         if (g_getenv ("ARDOUR_SAE")) {
4238                 Profile->set_sae ();
4239                 Profile->set_single_package ();
4240         }
4241
4242         if (g_getenv ("TRX")) {
4243                 Profile->set_trx ();
4244         }
4245 }
4246
4247 int
4248 ARDOUR_UI::missing_file (Session*s, std::string str, DataType type)
4249 {
4250         MissingFileDialog dialog (s, str, type);
4251
4252         dialog.show ();
4253         dialog.present ();
4254
4255         int result = dialog.run ();
4256         dialog.hide ();
4257
4258         switch (result) {
4259         case RESPONSE_OK:
4260                 break;
4261         default:
4262                 return 1; // quit entire session load
4263         }
4264
4265         result = dialog.get_action ();
4266
4267         return result;
4268 }
4269
4270 int
4271 ARDOUR_UI::ambiguous_file (std::string file, std::vector<std::string> hits)
4272 {
4273         AmbiguousFileDialog dialog (file, hits);
4274
4275         dialog.show ();
4276         dialog.present ();
4277
4278         dialog.run ();
4279         return dialog.get_which ();
4280 }
4281
4282 /** Allocate our thread-local buffers */
4283 void
4284 ARDOUR_UI::get_process_buffers ()
4285 {
4286         _process_thread->get_buffers ();
4287 }
4288
4289 /** Drop our thread-local buffers */
4290 void
4291 ARDOUR_UI::drop_process_buffers ()
4292 {
4293         _process_thread->drop_buffers ();
4294 }
4295
4296 void
4297 ARDOUR_UI::feedback_detected ()
4298 {
4299         _feedback_exists = true;
4300 }
4301
4302 void
4303 ARDOUR_UI::successful_graph_sort ()
4304 {
4305         _feedback_exists = false;
4306 }
4307
4308 void
4309 ARDOUR_UI::midi_panic ()
4310 {
4311         if (_session) {
4312                 _session->midi_panic();
4313         }
4314 }
4315
4316 void
4317 ARDOUR_UI::session_format_mismatch (std::string xml_path, std::string backup_path)
4318 {
4319         const char* start_big = "<span size=\"x-large\" weight=\"bold\">";
4320         const char* end_big = "</span>";
4321         const char* start_mono = "<tt>";
4322         const char* end_mono = "</tt>";
4323
4324         MessageDialog msg (string_compose (_("%4This is a session from an older version of %3%5\n\n"
4325                                              "%3 has copied the old session file\n\n%6%1%7\n\nto\n\n%6%2%7\n\n"
4326                                              "From now on, use the -2000 version with older versions of %3"),
4327                                            xml_path, backup_path, PROGRAM_NAME,
4328                                            start_big, end_big,
4329                                            start_mono, end_mono), true);
4330
4331         msg.run ();
4332 }
4333
4334
4335 void
4336 ARDOUR_UI::reset_peak_display ()
4337 {
4338         if (!_session || !_session->master_out() || !editor_meter) return;
4339         editor_meter->clear_meters();
4340         editor_meter_max_peak = -INFINITY;
4341         editor_meter_peak_display.set_name ("meterbridge peakindicator");
4342         editor_meter_peak_display.set_elements((ArdourButton::Element) (ArdourButton::Edge|ArdourButton::Body));
4343 }
4344
4345 void
4346 ARDOUR_UI::reset_group_peak_display (RouteGroup* group)
4347 {
4348         if (!_session || !_session->master_out()) return;
4349         if (group == _session->master_out()->route_group()) {
4350                 reset_peak_display ();
4351         }
4352 }
4353
4354 void
4355 ARDOUR_UI::reset_route_peak_display (Route* route)
4356 {
4357         if (!_session || !_session->master_out()) return;
4358         if (_session->master_out().get() == route) {
4359                 reset_peak_display ();
4360         }
4361 }
4362
4363 int
4364 ARDOUR_UI::do_audio_midi_setup (uint32_t desired_sample_rate)
4365 {
4366         audio_midi_setup->set_desired_sample_rate (desired_sample_rate);
4367         audio_midi_setup->set_position (WIN_POS_CENTER);
4368
4369         switch (audio_midi_setup->run()) {
4370         case Gtk::RESPONSE_OK:
4371                 return 0;
4372         case Gtk::RESPONSE_APPLY:
4373                 return 0;
4374         default:
4375                 return -1;
4376         }
4377 }
4378
4379