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