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