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