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