Add a PianoKeyboard to GenericUI (on a MIDI track)
[ardour.git] / gtk2_ardour / session_dialog.cc
1 /*
2   Copyright (C) 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
26 #include <glib.h>
27 #include "pbd/gstdio_compat.h"
28
29 #include <glibmm.h>
30 #include <glibmm/datetime.h>
31
32 #include <gtkmm/filechooser.h>
33 #include <gtkmm/stock.h>
34
35 #include "pbd/basename.h"
36 #include "pbd/failed_constructor.h"
37 #include "pbd/file_utils.h"
38 #include "pbd/replace_all.h"
39 #include "pbd/whitespace.h"
40 #include "pbd/stacktrace.h"
41 #include "pbd/stl_delete.h"
42 #include "pbd/openuri.h"
43
44 #include "gtkmm2ext/utils.h"
45 #include "gtkmm2ext/keyboard.h"
46
47 #include "widgets/tooltips.h"
48
49 #include "ardour/audioengine.h"
50 #include "ardour/filesystem_paths.h"
51 #include "ardour/luascripting.h"
52 #include "ardour/recent_sessions.h"
53 #include "ardour/session.h"
54 #include "ardour/session_state_utils.h"
55 #include "ardour/template_utils.h"
56 #include "ardour/filename_extensions.h"
57
58 #include "LuaBridge/LuaBridge.h"
59
60 #include "ardour_ui.h"
61 #include "session_dialog.h"
62 #include "opts.h"
63 #include "engine_dialog.h"
64 #include "pbd/i18n.h"
65 #include "ui_config.h"
66 #include "utils.h"
67
68 using namespace std;
69 using namespace Gtk;
70 using namespace Gdk;
71 using namespace Glib;
72 using namespace PBD;
73 using namespace ARDOUR;
74 using namespace ArdourWidgets;
75 using namespace ARDOUR_UI_UTILS;
76
77 SessionDialog::SessionDialog (bool require_new, const std::string& session_name, const std::string& session_path, const std::string& template_name, bool cancel_not_quit)
78         : ArdourDialog (_("Session Setup"), true, true)
79         , new_only (require_new)
80         , _provided_session_name (session_name)
81         , _provided_session_path (session_path)
82         , new_folder_chooser (FILE_CHOOSER_ACTION_SELECT_FOLDER)
83         , _existing_session_chooser_used (false)
84 {
85         set_position (WIN_POS_CENTER);
86         get_vbox()->set_spacing (6);
87
88         cancel_button = add_button ((cancel_not_quit ? Stock::CANCEL : Stock::QUIT), RESPONSE_CANCEL);
89         back_button = add_button (Stock::GO_BACK, RESPONSE_NO);
90         open_button = add_button (Stock::OPEN, RESPONSE_ACCEPT);
91
92         back_button->signal_button_press_event().connect (sigc::mem_fun (*this, &SessionDialog::back_button_pressed), false);
93         open_button->signal_button_press_event().connect (sigc::mem_fun (*this, &SessionDialog::open_button_pressed), false);
94
95         open_button->set_sensitive (false);
96         back_button->set_sensitive (false);
97
98         /* this is where announcements will be displayed, but it may be empty
99          * and invisible most of the time.
100          */
101
102         info_frame.set_shadow_type(SHADOW_ETCHED_OUT);
103         info_frame.set_no_show_all (true);
104         info_frame.set_border_width (12);
105         get_vbox()->pack_start (info_frame, false, false);
106
107         setup_new_session_page ();
108
109         if (!new_only) {
110                 setup_initial_choice_box ();
111                 get_vbox()->pack_start (ic_vbox, true, true);
112         } else {
113                 get_vbox()->pack_start (session_new_vbox, true, true);
114         }
115
116         if (!template_name.empty()) {
117                 load_template_override = template_name;
118         }
119
120         get_vbox()->show_all ();
121
122         /* fill data models and show/hide accordingly */
123
124         populate_session_templates ();
125
126         if (recent_session_model) {
127                 int cnt = redisplay_recent_sessions ();
128                 if (cnt > 0) {
129                         recent_scroller.show();
130                         recent_label.show ();
131
132                         if (cnt > 4) {
133                                 recent_scroller.set_size_request (-1, 300);
134                         } else {
135                                 recent_scroller.set_size_request (-1, 80);
136                         }
137                 } else {
138                         recent_scroller.hide();
139                         recent_label.hide ();
140                 }
141         }
142
143         /* possibly get out of here immediately if everything is ready to go.
144            We still need to set up the whole dialog because of the way
145            ARDOUR_UI::get_session_parameters() might skip it on a first
146            pass then require it for a second pass (e.g. when there
147            is an error with session loading and we have to ask the user
148            what to do next).
149         */
150
151         if (!session_name.empty() && !require_new) {
152                 response (RESPONSE_OK);
153                 return;
154         }
155 }
156
157 SessionDialog::SessionDialog ()
158         : ArdourDialog (_("Recent Sessions"), true, true)
159         , new_only (false)
160         , _provided_session_name ("")
161         , _provided_session_path ("")
162         , _existing_session_chooser_used (false) // caller must check should_be_new
163 {
164         get_vbox()->set_spacing (6);
165
166         cancel_button = add_button (Stock::CANCEL, RESPONSE_CANCEL);
167         open_button = add_button (Stock::OPEN, RESPONSE_ACCEPT);
168         open_button->set_sensitive (false);
169
170         setup_recent_sessions ();
171
172         get_vbox()->pack_start (recent_scroller, true, true);
173         get_vbox()->show_all ();
174
175         recent_scroller.show();
176
177         int cnt = redisplay_recent_sessions ();
178         if (cnt > 4) {
179                 recent_scroller.set_size_request (-1, 300);
180         } else {
181                 recent_scroller.set_size_request (-1, 80);
182         }
183
184 }
185
186
187
188 SessionDialog::~SessionDialog()
189 {
190 }
191
192 void
193 SessionDialog::clear_given ()
194 {
195         _provided_session_path = "";
196         _provided_session_name = "";
197 }
198
199 uint32_t
200 SessionDialog::meta_master_bus_profile (std::string script_path) const
201 {
202         if (!Glib::file_test (script_path, Glib::FILE_TEST_EXISTS | Glib::FILE_TEST_IS_REGULAR)) {
203                 return UINT32_MAX;
204         }
205
206         LuaState lua;
207         lua.sandbox (true);
208         lua_State* L = lua.getState();
209
210         lua.do_command (
211                         "ardourluainfo = {}"
212                         "function ardour (entry)"
213                         "  ardourluainfo['type'] = assert(entry['type'])"
214                         "  ardourluainfo['master_bus'] = entry['master_bus'] or 2"
215                         " end"
216                         );
217
218         int err = -1;
219
220         try {
221                 err = lua.do_file (script_path);
222         } catch (luabridge::LuaException const& e) {
223                 err = -1;
224         }  catch (...) {
225                 err = -1;
226         }
227
228
229         if (err) {
230                 return UINT32_MAX;
231         }
232
233         luabridge::LuaRef nfo = luabridge::getGlobal (L, "ardourluainfo");
234         if (nfo.type() != LUA_TTABLE) {
235                 return UINT32_MAX;
236         }
237
238         if (nfo["master_bus"].type() != LUA_TNUMBER || nfo["type"].type() != LUA_TSTRING) {
239                 return UINT32_MAX;
240         }
241
242         LuaScriptInfo::ScriptType type = LuaScriptInfo::str2type (nfo["type"].cast<std::string>());
243         if (type != LuaScriptInfo::SessionInit) {
244                 return UINT32_MAX;
245         }
246
247         return nfo["master_bus"].cast<uint32_t>();
248 }
249
250 uint32_t
251 SessionDialog::master_channel_count ()
252 {
253         if (use_session_template ()) {
254                 std::string tn = session_template_name();
255                 if (tn.substr (0, 11) == "urn:ardour:") {
256                         uint32_t mc = meta_master_bus_profile (tn.substr (11));
257                         if (mc != UINT32_MAX) {
258                                 return mc;
259                         }
260                 }
261         }
262         return 2;
263 }
264
265 bool
266 SessionDialog::use_session_template () const
267 {
268         if (!back_button->sensitive () && !new_only) {
269                 /* open session -- not create a new one */
270                 return false;
271         }
272
273         if (!load_template_override.empty()) {
274                 return true;
275         }
276
277         if (template_chooser.get_selection()->count_selected_rows() > 0) {
278                 return true;
279         }
280
281         return false;
282 }
283
284 std::string
285 SessionDialog::session_template_name ()
286 {
287         if (!load_template_override.empty()) {
288                 string the_path (ARDOUR::user_template_directory());
289                 return Glib::build_filename (the_path, load_template_override + ARDOUR::template_suffix);
290         }
291
292         if (template_chooser.get_selection()->count_selected_rows() > 0) {
293
294                 TreeIter const iter = template_chooser.get_selection()->get_selected();
295
296                 if (iter) {
297                         string s = (*iter)[session_template_columns.path];
298                         return s;
299                 }
300         }
301
302         return string();
303 }
304
305 std::string
306 SessionDialog::session_name (bool& should_be_new)
307 {
308         if (!_provided_session_name.empty() && !new_only) {
309                 should_be_new = false;
310                 return _provided_session_name;
311         }
312
313         /* Try recent session selection */
314
315         TreeIter iter = recent_session_display.get_selection()->get_selected();
316
317         if (iter) {
318                 should_be_new = false;
319                 string s = (*iter)[recent_session_columns.fullpath];
320                 if (Glib::file_test (s, Glib::FILE_TEST_IS_REGULAR)) {
321                         return PBD::basename_nosuffix (s);
322                 }
323                 return (*iter)[recent_session_columns.visible_name];
324         }
325
326         if (_existing_session_chooser_used) {
327                 /* existing session chosen from file chooser */
328                 should_be_new = false;
329                 return existing_session_chooser.get_filename ();
330         } else {
331                 should_be_new = true;
332                 string val = new_name_entry.get_text ();
333                 strip_whitespace_edges (val);
334                 return val;
335         }
336 }
337
338 std::string
339 SessionDialog::session_folder ()
340 {
341         if (!_provided_session_path.empty() && !new_only) {
342                 return _provided_session_path;
343         }
344
345         /* Try recent session selection */
346
347         TreeIter iter = recent_session_display.get_selection()->get_selected();
348
349         if (iter) {
350                 string s = (*iter)[recent_session_columns.fullpath];
351                 if (Glib::file_test (s, Glib::FILE_TEST_IS_REGULAR)) {
352                         return Glib::path_get_dirname (s);
353                 }
354                 return s;
355         }
356
357         if (_existing_session_chooser_used) {
358                 /* existing session chosen from file chooser */
359                 return Glib::path_get_dirname (existing_session_chooser.get_current_folder ());
360         } else {
361                 std::string val = new_name_entry.get_text();
362                 strip_whitespace_edges (val);
363                 std::string legal_session_folder_name = legalize_for_path (val);
364                 return Glib::build_filename (new_folder_chooser.get_filename (), legal_session_folder_name);
365         }
366 }
367
368 void
369 SessionDialog::setup_recent_sessions ()
370 {
371         recent_session_model = TreeStore::create (recent_session_columns);
372         recent_session_model->signal_sort_column_changed().connect (sigc::mem_fun (*this, &SessionDialog::recent_session_sort_changed));
373
374         recent_session_display.set_model (recent_session_model);
375         recent_session_display.append_column (_("Session Name"), recent_session_columns.visible_name);
376         recent_session_display.append_column (_("Sample Rate"), recent_session_columns.sample_rate);
377         recent_session_display.append_column (_("File Resolution"), recent_session_columns.disk_format);
378         recent_session_display.append_column (_("Last Modified"), recent_session_columns.time_formatted);
379         recent_session_display.set_headers_visible (true);
380         recent_session_display.get_selection()->set_mode (SELECTION_SINGLE);
381
382         recent_session_display.get_selection()->signal_changed().connect (sigc::mem_fun (*this, &SessionDialog::recent_session_row_selected));
383
384         recent_scroller.add (recent_session_display);
385         recent_scroller.set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
386         recent_scroller.set_shadow_type (Gtk::SHADOW_IN);
387
388         recent_session_display.show();
389         recent_session_display.signal_row_activated().connect (sigc::mem_fun (*this, &SessionDialog::recent_row_activated));
390         recent_session_display.signal_button_press_event().connect (sigc::mem_fun (*this, &SessionDialog::recent_button_press), false);
391 }
392
393 void
394 SessionDialog::setup_initial_choice_box ()
395 {
396         ic_vbox.set_spacing (6);
397
398         HBox* centering_hbox = manage (new HBox);
399         VBox* centering_vbox = manage (new VBox);
400
401         centering_vbox->set_spacing (6);
402
403         Label* new_label = manage (new Label);
404         new_label->set_markup (string_compose ("<span weight=\"bold\" size=\"large\">%1</span>", _("New Session")));
405         new_label->set_justify (JUSTIFY_CENTER);
406
407         ic_new_session_button.add (*new_label);
408         ic_new_session_button.signal_clicked().connect (sigc::mem_fun (*this, &SessionDialog::new_session_button_clicked));
409
410         Gtk::HBox* hbox = manage (new HBox);
411         Gtk::VBox* vbox = manage (new VBox);
412         hbox->set_spacing (12);
413         vbox->set_spacing (12);
414
415         string image_path;
416
417         Searchpath rc (ARDOUR::ardour_data_search_path());
418         rc.add_subdirectory_to_paths ("resources");
419
420         if (find_file (rc, PROGRAM_NAME "-small-splash.png", image_path)) {
421                 Gtk::Image* image;
422                 if ((image = manage (new Gtk::Image (image_path))) != 0) {
423                         hbox->pack_start (*image, false, false);
424                 }
425         }
426
427         vbox->pack_start (ic_new_session_button, true, true, 20);
428         hbox->pack_start (*vbox, true, true, 20);
429
430         centering_vbox->pack_start (*hbox, false, false);
431
432         /* Possible update message */
433
434         if (ARDOUR_UI::instance()->announce_string() != "" ) {
435
436                 Box *info_box = manage (new VBox);
437                 info_box->set_border_width (12);
438                 info_box->set_spacing (6);
439
440                 info_box->pack_start (info_scroller_label, false, false);
441
442                 info_scroller_count = 0;
443                 info_scroller_connection = Glib::signal_timeout().connect (mem_fun(*this, &SessionDialog::info_scroller_update), 50);
444
445                 Gtk::Button *updates_button = manage (new Gtk::Button (_("Check the website for more...")));
446
447                 updates_button->signal_clicked().connect (mem_fun(*this, &SessionDialog::updates_button_clicked) );
448                 set_tooltip (*updates_button, _("Click to open the program website in your web browser"));
449
450                 info_box->pack_start (*updates_button, false, false);
451
452                 info_frame.add (*info_box);
453                 info_box->show_all ();
454                 info_frame.show ();
455         }
456
457         /* recent session scroller */
458         setup_recent_sessions ();
459
460         recent_label.set_no_show_all (true);
461         recent_scroller.set_no_show_all (true);
462
463         recent_label.set_markup (string_compose ("<span weight=\"bold\" size=\"large\">%1</span>", _("Recent Sessions")));
464
465         centering_vbox->pack_start (recent_label, false, false, 12);
466         centering_vbox->pack_start (recent_scroller, true, true);
467
468         /* Browse button */
469
470         existing_session_chooser.set_title (_("Select session file"));
471         existing_session_chooser.signal_file_set().connect (sigc::mem_fun (*this, &SessionDialog::existing_session_selected));
472         existing_session_chooser.set_current_folder(poor_mans_glob (Config->get_default_session_parent_dir()));
473
474         FileFilter session_filter;
475         session_filter.add_pattern (string_compose(X_("*%1"), ARDOUR::statefile_suffix));
476         session_filter.set_name (string_compose (_("%1 sessions"), PROGRAM_NAME));
477         existing_session_chooser.add_filter (session_filter);
478
479         FileFilter archive_filter;
480         archive_filter.add_pattern (X_("*.tar.xz"));
481         archive_filter.set_name (_("Session Archives"));
482         existing_session_chooser.add_filter (archive_filter);
483
484         existing_session_chooser.set_filter (session_filter);
485
486         Gtkmm2ext::add_volume_shortcuts (existing_session_chooser);
487
488         Label* browse_label = manage (new Label);
489         browse_label->set_markup (string_compose ("<span weight=\"bold\" size=\"large\">%1</span>", _("Other Sessions")));
490
491         centering_vbox->pack_start (*browse_label, false, false, 12);
492         centering_vbox->pack_start (existing_session_chooser, false, false);
493
494         /* --disable plugins UI */
495
496         _disable_plugins.set_label (_("Safe Mode: Disable all Plugins"));
497         _disable_plugins.set_flags (Gtk::CAN_FOCUS);
498         _disable_plugins.set_relief (Gtk::RELIEF_NORMAL);
499         _disable_plugins.set_mode (true);
500         _disable_plugins.set_active (ARDOUR::Session::get_disable_all_loaded_plugins());
501         _disable_plugins.set_border_width(0);
502         _disable_plugins.signal_clicked().connect (sigc::mem_fun (*this, &SessionDialog::disable_plugins_clicked));
503         centering_vbox->pack_start (_disable_plugins, false, false);
504
505         /* pack it all up */
506
507         centering_hbox->pack_start (*centering_vbox, true, true);
508         ic_vbox.pack_start (*centering_hbox, true, true);
509         ic_vbox.show_all ();
510 }
511
512 void
513 SessionDialog::session_selected ()
514 {
515         /* HACK HACK HACK ... change the "Apply" button label
516            to say "Open"
517         */
518
519         Gtk::Widget* tl = ic_vbox.get_toplevel();
520         Gtk::Window* win;
521         if ((win = dynamic_cast<Gtk::Window*>(tl)) != 0) {
522                 /* ::get_default_widget() is not wrapped in gtkmm */
523                 Gtk::Widget* def = wrap (gtk_window_get_default_widget (win->gobj()));
524                 Gtk::Button* button;
525                 if ((button = dynamic_cast<Gtk::Button*>(def)) != 0) {
526                         button->set_label (_("Open"));
527                 }
528         }
529 }
530
531 void
532 SessionDialog::new_session_button_clicked ()
533 {
534         _existing_session_chooser_used = false;
535         recent_session_display.get_selection()->unselect_all ();
536
537         get_vbox()->remove (ic_vbox);
538         get_vbox()->pack_start (session_new_vbox, true, true);
539         back_button->set_sensitive (true);
540         new_name_entry.grab_focus ();
541 }
542
543 bool
544 SessionDialog::back_button_pressed (GdkEventButton*)
545 {
546         get_vbox()->remove (session_new_vbox);
547         back_button->set_sensitive (false);
548         get_vbox()->pack_start (ic_vbox);
549
550         return true;
551 }
552
553 bool
554 SessionDialog::open_button_pressed (GdkEventButton* ev)
555 {
556         if (Gtkmm2ext::Keyboard::modifier_state_equals (ev->state, Gtkmm2ext::Keyboard::PrimaryModifier)) {
557                 _disable_plugins.set_active();
558         }
559         response (RESPONSE_ACCEPT);
560         return true;
561 }
562
563 void
564 SessionDialog::populate_session_templates ()
565 {
566         vector<TemplateInfo> templates;
567
568         find_session_templates (templates, true);
569
570         template_model->clear ();
571
572         /* Add Lua Scripts dedicated to session-setup */
573         LuaScriptList& ms (LuaScripting::instance ().scripts (LuaScriptInfo::SessionInit));
574         for (LuaScriptList::const_iterator s = ms.begin(); s != ms.end(); ++s) {
575                 TreeModel::Row row = *(template_model->append ());
576                 row[session_template_columns.name] = (*s)->name;
577                 row[session_template_columns.path] = "urn:ardour:" + (*s)->path;
578                 row[session_template_columns.description] = (*s)->description;
579                 row[session_template_columns.created_with_short] = _("{Factory Template}");
580                 row[session_template_columns.created_with_long] = _("{Factory Template}");
581         }
582
583         /* Add Lua Action Scripts which can also be used for session-setup */
584         LuaScriptList& as (LuaScripting::instance ().scripts (LuaScriptInfo::EditorAction));
585         for (LuaScriptList::const_iterator s = as.begin(); s != as.end(); ++s) {
586                 if (!((*s)->subtype & LuaScriptInfo::SessionSetup)) {
587                         continue;
588                 }
589                 TreeModel::Row row = *(template_model->append ());
590                 row[session_template_columns.name] = (*s)->name;
591                 row[session_template_columns.path] = "urn:ardour:" + (*s)->path;
592                 row[session_template_columns.description] = (*s)->description;
593                 row[session_template_columns.created_with_short] = _("{Factory Template}");
594                 row[session_template_columns.created_with_long] = _("{Factory Template}");
595         }
596
597
598         //Add any "template sessions" found in the user's preferences folder
599         for (vector<TemplateInfo>::iterator x = templates.begin(); x != templates.end(); ++x) {
600                 TreeModel::Row row;
601
602                 row = *(template_model->append ());
603
604                 row[session_template_columns.name] = (*x).name;
605                 row[session_template_columns.path] = (*x).path;
606                 row[session_template_columns.description] = (*x).description;
607                 row[session_template_columns.created_with_long] = (*x).created_with;
608                 row[session_template_columns.created_with_short] = (*x).created_with.substr(0, (*x).created_with.find(" "));
609         }
610
611         //Add an explicit 'Empty Template' item
612         TreeModel::Row row = *template_model->prepend ();
613         row[session_template_columns.name] = (_("Empty Template"));
614         row[session_template_columns.path] = string();
615         row[session_template_columns.description] = _("An empty session with factory default settings.");
616         row[session_template_columns.created_with_short] = _("");
617         row[session_template_columns.created_with_long] = _("");
618
619         //auto-select the first item in the list
620         Gtk::TreeModel::Row first = template_model->children()[0];
621         if(first) {
622                 template_chooser.get_selection()->select(first);
623         }
624 }
625
626 void
627 SessionDialog::setup_new_session_page ()
628 {
629         session_new_vbox.set_border_width (8);
630         session_new_vbox.set_spacing (8);
631
632         Label* name_label = manage (new Label);
633         name_label->set_text (_("Session name:"));
634
635         HBox* name_hbox = manage (new HBox);
636         name_hbox->set_spacing (8);
637         name_hbox->pack_start (*name_label, false, true);
638         name_hbox->pack_start (new_name_entry, true, true);
639
640         //check to see if a session name was provided on command line
641         if (!ARDOUR_COMMAND_LINE::session_name.empty()) {
642                 new_name_entry.set_text  (Glib::path_get_basename (ARDOUR_COMMAND_LINE::session_name));
643                 open_button->set_sensitive (true);
644         }
645
646         new_name_entry.signal_changed().connect (sigc::mem_fun (*this, &SessionDialog::new_name_changed));
647         new_name_entry.signal_activate().connect (sigc::mem_fun (*this, &SessionDialog::new_name_activated));
648
649         //Folder location for the new session
650         Label* new_folder_label = manage (new Label);
651         new_folder_label->set_text (_("Create session folder in:"));
652         HBox* folder_box = manage (new HBox);
653         folder_box->set_spacing (8);
654         folder_box->pack_start (*new_folder_label, false, false);
655         folder_box->pack_start (new_folder_chooser, true, true);
656
657         //determine the text in the new folder selector
658         if (!ARDOUR_COMMAND_LINE::session_name.empty()) {
659                 new_folder_chooser.set_current_folder (poor_mans_glob (Glib::path_get_dirname (ARDOUR_COMMAND_LINE::session_name)));
660         } else if (ARDOUR_UI::instance()->session_loaded) {
661                 // point the new session file chooser at the parent directory of the current session
662                 string session_parent_dir = Glib::path_get_dirname(ARDOUR_UI::instance()->the_session()->path());
663                 new_folder_chooser.set_current_folder (session_parent_dir);
664                 string default_session_folder = poor_mans_glob (Config->get_default_session_parent_dir());
665
666                 try {
667                         /* add_shortcut_folder throws an exception if the folder being added already has a shortcut */
668                         new_folder_chooser.add_shortcut_folder (default_session_folder);
669                 }
670                 catch (Glib::Error & e) {
671                         std::cerr << "new_folder_chooser.add_shortcut_folder (" << default_session_folder << ") threw Glib::Error " << e.what() << std::endl;
672                 }
673         } else {
674                 new_folder_chooser.set_current_folder (poor_mans_glob (Config->get_default_session_parent_dir()));
675         }
676         new_folder_chooser.show ();
677         new_folder_chooser.set_title (_("Select folder for session"));
678         Gtkmm2ext::add_volume_shortcuts (new_folder_chooser);
679
680         //Template & Template Description area
681         HBox* template_hbox = manage (new HBox);
682
683         //if the "template override" is provided, don't give the user any template selections   (?)
684         if ( load_template_override.empty() ) {
685                 template_hbox->set_spacing (8);
686
687                 Gtk::ScrolledWindow *template_scroller = manage (new Gtk::ScrolledWindow());
688                 template_scroller->set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
689                 template_scroller->add (template_chooser);
690
691                 Gtk::ScrolledWindow *desc_scroller = manage (new Gtk::ScrolledWindow());
692                 desc_scroller->set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
693                 desc_scroller->add (template_desc);
694
695                 template_hbox->pack_start (*template_scroller, true, true);
696
697                 template_desc_frame.set_name (X_("TextHighlightFrame"));
698                 template_desc_frame.add (*desc_scroller);
699                 template_hbox->pack_start (template_desc_frame, true, true);
700         }
701
702         //template_desc is the textview that displays the currently selected template's description
703         template_desc.set_editable (false);
704         template_desc.set_wrap_mode (Gtk::WRAP_WORD);
705         template_desc.set_size_request (300,400);
706         template_desc.set_name (X_("TextOnBackground"));
707         template_desc.set_border_width (6);
708
709         //template_chooser is the treeview showing available templates
710         template_model = TreeStore::create (session_template_columns);
711         template_chooser.set_model (template_model);
712         template_chooser.append_column (_("Template"), session_template_columns.name);
713 #ifdef MIXBUS
714         template_chooser.append_column (_("Created With"), session_template_columns.created_with_short);
715 #endif
716         template_chooser.set_tooltip_column(4); // created_with_long
717         template_chooser.set_headers_visible (true);
718         template_chooser.get_selection()->set_mode (SELECTION_SINGLE);
719         template_chooser.get_selection()->signal_changed().connect (sigc::mem_fun (*this, &SessionDialog::template_row_selected));
720         template_chooser.set_sensitive (true);
721
722         session_new_vbox.pack_start (*template_hbox, true, true);
723         session_new_vbox.pack_start (*folder_box, false, true);
724         session_new_vbox.pack_start (*name_hbox, false, true);
725         session_new_vbox.show_all ();
726 }
727
728 void
729 SessionDialog::new_name_changed ()
730 {
731         if (!new_name_entry.get_text().empty()) {
732                 session_selected ();
733                 open_button->set_sensitive (true);
734         } else {
735                 open_button->set_sensitive (false);
736         }
737 }
738
739 void
740 SessionDialog::new_name_activated ()
741 {
742         response (RESPONSE_ACCEPT);
743 }
744
745 int
746 SessionDialog::redisplay_recent_sessions ()
747 {
748         std::vector<std::string> session_directories;
749         RecentSessionsSorter cmp;
750
751         recent_session_display.set_model (Glib::RefPtr<TreeModel>(0));
752         recent_session_model->clear ();
753
754         ARDOUR::RecentSessions rs;
755         ARDOUR::read_recent_sessions (rs);
756
757         if (rs.empty()) {
758                 recent_session_display.set_model (recent_session_model);
759                 return 0;
760         }
761
762         // sort them alphabetically
763         sort (rs.begin(), rs.end(), cmp);
764
765         for (ARDOUR::RecentSessions::iterator i = rs.begin(); i != rs.end(); ++i) {
766                 session_directories.push_back ((*i).second);
767         }
768
769         int session_snapshot_count = 0;
770
771         for (vector<std::string>::const_iterator i = session_directories.begin(); i != session_directories.end(); ++i)
772         {
773                 std::vector<std::string> state_file_paths;
774
775                 // now get available states for this session
776
777                 get_state_files_in_directory (*i, state_file_paths);
778
779                 vector<string> states;
780                 vector<const gchar*> item;
781                 string dirname = *i;
782
783                 /* remove any trailing / */
784
785                 if (dirname[dirname.length()-1] == '/') {
786                         dirname = dirname.substr (0, dirname.length()-1);
787                 }
788
789                 /* check whether session still exists */
790                 if (!Glib::file_test(dirname.c_str(), Glib::FILE_TEST_EXISTS)) {
791                         /* session doesn't exist */
792                         continue;
793                 }
794
795                 /* now get available states for this session */
796
797                 states = Session::possible_states (dirname);
798
799                 if (states.empty()) {
800                         /* no state file? */
801                         continue;
802                 }
803
804                 std::vector<string> state_file_names(get_file_names_no_extension (state_file_paths));
805
806                 if (state_file_names.empty()) {
807                         continue;
808                 }
809
810                 float sr;
811                 SampleFormat sf;
812                 std::string program_version;
813
814                 std::string state_file_basename;
815
816                 if (state_file_names.size() > 1) {
817                         state_file_basename = Session::get_snapshot_from_instant (dirname);
818                         std::string s = Glib::build_filename (dirname, state_file_basename + statefile_suffix);
819                         if (!Glib::file_test (s, Glib::FILE_TEST_IS_REGULAR)) {
820                                 state_file_basename = "";
821                         }
822                 }
823
824                 if (state_file_basename.empty()) {
825                         state_file_basename = state_file_names.front();
826                 }
827
828                 std::string s = Glib::build_filename (dirname, state_file_basename + statefile_suffix);
829
830                 int err = Session::get_info_from_path (s, sr, sf, program_version);
831                 if (err < 0) {
832                         // XML cannot be parsed, or unsuppored version
833                         continue;
834                 }
835
836                 GStatBuf gsb;
837                 g_stat (s.c_str(), &gsb);
838
839                 Gtk::TreeModel::Row row = *(recent_session_model->append());
840                 row[recent_session_columns.fullpath] = s;
841                 row[recent_session_columns.time_modified] = gsb.st_mtime;
842
843
844                 if (err == 0) {
845                         row[recent_session_columns.sample_rate] = rate_as_string (sr);
846                         switch (sf) {
847                         case FormatFloat:
848                                 row[recent_session_columns.disk_format] = _("32-bit float");
849                                 break;
850                         case FormatInt24:
851                                 row[recent_session_columns.disk_format] = _("24-bit");
852                                 break;
853                         case FormatInt16:
854                                 row[recent_session_columns.disk_format] = _("16-bit");
855                                 break;
856                         }
857                 } else {
858                         row[recent_session_columns.sample_rate] = "??";
859                         row[recent_session_columns.disk_format] = "--";
860                 }
861
862                 if (program_version.empty()) {
863                         row[recent_session_columns.tip] = Gtkmm2ext::markup_escape_text (dirname);
864                 } else {
865                         row[recent_session_columns.tip] = Gtkmm2ext::markup_escape_text (dirname + "\n" + string_compose (_("Last modified with: %1"), program_version));
866                 }
867
868                 ++session_snapshot_count;
869
870                 if (state_file_names.size() > 1) {
871                         // multiple session files in the session directory - show the directory name.
872                         // if there's not a session file with the same name as the session directory,
873                         // opening the parent item will fail, but expanding it will show the session
874                         // files that actually exist, and the right one can then be opened.
875                         row[recent_session_columns.visible_name] = Glib::path_get_basename (dirname);
876                         int64_t most_recent = 0;
877
878                         // add the children
879                         int kidcount = 0;
880                         for (std::vector<std::string>::iterator i2 = state_file_names.begin(); i2 != state_file_names.end(); ++i2) {
881
882                                 s = Glib::build_filename (dirname, *i2 + statefile_suffix);
883                                 Gtk::TreeModel::Row child_row = *(recent_session_model->append (row.children()));
884
885                                 child_row[recent_session_columns.visible_name] = *i2;
886                                 child_row[recent_session_columns.fullpath] = s;
887                                 child_row[recent_session_columns.tip] = Gtkmm2ext::markup_escape_text (dirname);
888                                 g_stat (s.c_str(), &gsb);
889                                 child_row[recent_session_columns.time_modified] = gsb.st_mtime;
890
891                                 Glib::DateTime gdt(Glib::DateTime::create_now_local (gsb.st_mtime));
892                                 child_row[recent_session_columns.time_formatted] = gdt.format ("%F %H:%M");
893
894                                 if (gsb.st_mtime > most_recent) {
895                                         most_recent = gsb.st_mtime;
896                                 }
897
898                                 if (++kidcount < 5) {
899                                         // parse "modified with" for the first 5 snapshots
900                                         if (Session::get_info_from_path (s, sr, sf, program_version) == 0) {
901 #if 0
902                                                 child_row[recent_session_columns.sample_rate] = rate_as_string (sr);
903                                                 switch (sf) {
904                                                 case FormatFloat:
905                                                         child_row[recent_session_columns.disk_format] = _("32-bit float");
906                                                         break;
907                                                 case FormatInt24:
908                                                         child_row[recent_session_columns.disk_format] = _("24-bit");
909                                                         break;
910                                                 case FormatInt16:
911                                                         child_row[recent_session_columns.disk_format] = _("16-bit");
912                                                         break;
913                                                 }
914 #else
915                                                 child_row[recent_session_columns.sample_rate] = "";
916                                                 child_row[recent_session_columns.disk_format] = "";
917 #endif
918                                         } else {
919                                                 child_row[recent_session_columns.sample_rate] = "??";
920                                                 child_row[recent_session_columns.disk_format] = "--";
921                                         }
922                                         if (!program_version.empty()) {
923                                                 child_row[recent_session_columns.tip] = Gtkmm2ext::markup_escape_text (string_compose (_("Last modified with: %1"), program_version));
924                                         }
925                                 } else {
926                                         child_row[recent_session_columns.sample_rate] = "";
927                                         child_row[recent_session_columns.disk_format] = "";
928                                 }
929
930                                 ++session_snapshot_count;
931                         }
932
933                         assert (most_recent >= row[recent_session_columns.time_modified]);
934                         row[recent_session_columns.time_modified] = most_recent;
935
936                 } else {
937                         // only a single session file in the directory - show its actual name.
938                         row[recent_session_columns.visible_name] = state_file_basename;
939                 }
940
941                 Glib::DateTime gdt(Glib::DateTime::create_now_local (row[recent_session_columns.time_modified]));
942                 row[recent_session_columns.time_formatted] = gdt.format ("%F %H:%M");
943         }
944
945         recent_session_display.set_tooltip_column(1); // recent_session_columns.tip
946         recent_session_display.set_model (recent_session_model);
947
948         // custom sort
949         Gtk::TreeView::Column* pColumn;
950         if ((pColumn = recent_session_display.get_column (0))) { // name
951                 pColumn->set_sort_column (recent_session_columns.visible_name);
952         }
953         if ((pColumn = recent_session_display.get_column (3))) { // date
954                 pColumn->set_sort_column (recent_session_columns.time_modified); // unixtime
955         }
956
957         int32_t sort = UIConfiguration::instance().get_recent_session_sort();
958         if (abs(sort) != 1 + recent_session_columns.visible_name.index () &&
959             abs(sort) != 1 + recent_session_columns.time_modified.index ()) {
960                 sort = 1 + recent_session_columns.visible_name.index();
961         }
962         recent_session_model->set_sort_column (abs (sort) -1, sort < 0 ? Gtk::SORT_DESCENDING : Gtk::SORT_ASCENDING);
963
964         return session_snapshot_count;
965 }
966
967 void
968 SessionDialog::recent_session_sort_changed ()
969 {
970         int column;
971         SortType order;
972         if (recent_session_model->get_sort_column_id (column, order)) {
973                 int32_t sort = (column + 1) * (order == Gtk::SORT_DESCENDING ? -1 : 1);
974                 if (sort != UIConfiguration::instance().get_recent_session_sort()) {
975                         UIConfiguration::instance().set_recent_session_sort(sort);
976                 }
977         }
978 }
979
980 void
981 SessionDialog::recent_session_row_selected ()
982 {
983         if (recent_session_display.get_selection()->count_selected_rows() > 0) {
984                 open_button->set_sensitive (true);
985                 session_selected ();
986         } else {
987                 open_button->set_sensitive (false);
988         }
989 }
990
991 void
992 SessionDialog::template_row_selected ()
993 {
994         if (template_chooser.get_selection()->count_selected_rows() > 0) {
995                 TreeIter iter = template_chooser.get_selection()->get_selected();
996
997                 if (iter) {
998                         string s = (*iter)[session_template_columns.description];
999                         template_desc.get_buffer()->set_text (s);
1000                 }
1001         }
1002 }
1003
1004 void
1005 SessionDialog::recent_row_activated (const Gtk::TreePath&, Gtk::TreeViewColumn*)
1006 {
1007         response (RESPONSE_ACCEPT);
1008 }
1009
1010 bool
1011 SessionDialog::recent_button_press (GdkEventButton* ev)
1012 {
1013         if ((ev->type == GDK_BUTTON_PRESS) && (ev->button == 3) ) {
1014
1015                 TreeModel::Path path;
1016                 TreeViewColumn* column;
1017                 int cellx, celly;
1018                 if (recent_session_display.get_path_at_pos ((int)ev->x, (int)ev->y, path, column, cellx, celly)) {
1019                         Glib::RefPtr<Gtk::TreeView::Selection> selection = recent_session_display.get_selection();
1020                         if (selection) {
1021                                 selection->unselect_all();
1022                                 selection->select(path);
1023                         }
1024                 }
1025
1026                 if (recent_session_display.get_selection()->count_selected_rows() > 0) {
1027                         recent_context_mennu (ev);
1028                 }
1029         }
1030         return false;
1031 }
1032
1033 void
1034 SessionDialog::recent_context_mennu (GdkEventButton *ev)
1035 {
1036         using namespace Gtk::Menu_Helpers;
1037
1038         TreeIter iter = recent_session_display.get_selection()->get_selected();
1039         assert (iter);
1040         string s = (*iter)[recent_session_columns.fullpath];
1041         if (Glib::file_test (s, Glib::FILE_TEST_IS_REGULAR)) {
1042                 s = Glib::path_get_dirname (s);
1043         }
1044         if (!Glib::file_test (s, Glib::FILE_TEST_IS_DIR)) {
1045                 return;
1046         }
1047
1048         Gtk::TreeModel::Path tpath = recent_session_model->get_path(iter);
1049         const bool is_child = tpath.up () && tpath.up ();
1050
1051         Gtk::Menu* m = manage (new Menu);
1052         MenuList& items = m->items ();
1053         items.push_back (MenuElem (s, sigc::bind (sigc::hide_return (sigc::ptr_fun (&PBD::open_folder)), s)));
1054         if (!is_child) {
1055                 items.push_back (SeparatorElem());
1056                 items.push_back (MenuElem (_("Remove session from recent list"), sigc::mem_fun (*this, &SessionDialog::recent_remove_selected)));
1057         }
1058         m->popup (ev->button, ev->time);
1059 }
1060
1061 void
1062 SessionDialog::recent_remove_selected ()
1063 {
1064         TreeIter iter = recent_session_display.get_selection()->get_selected();
1065         assert (iter);
1066         string s = (*iter)[recent_session_columns.fullpath];
1067         if (Glib::file_test (s, Glib::FILE_TEST_IS_REGULAR)) {
1068                 s = Glib::path_get_dirname (s);
1069         }
1070         ARDOUR::remove_recent_sessions (s);
1071         redisplay_recent_sessions ();
1072 }
1073
1074 void
1075 SessionDialog::disable_plugins_clicked ()
1076 {
1077         ARDOUR::Session::set_disable_all_loaded_plugins (_disable_plugins.get_active());
1078 }
1079
1080 void
1081 SessionDialog::existing_session_selected ()
1082 {
1083         _existing_session_chooser_used = true;
1084         recent_session_display.get_selection()->unselect_all();
1085         /* mark this sensitive in case we come back here after a failed open
1086          * attempt and the user has hacked up the fix. sigh.
1087          */
1088         open_button->set_sensitive (true);
1089         response (RESPONSE_ACCEPT);
1090 }
1091
1092 void
1093 SessionDialog::updates_button_clicked ()
1094 {
1095         //now open a browser window so user can see more
1096         PBD::open_uri (Config->get_updates_url());
1097 }
1098
1099 bool
1100 SessionDialog::info_scroller_update()
1101 {
1102         info_scroller_count++;
1103
1104         char buf[512];
1105         snprintf (buf, std::min(info_scroller_count,sizeof(buf)-1), "%s", ARDOUR_UI::instance()->announce_string().c_str() );
1106         buf[info_scroller_count] = 0;
1107         info_scroller_label.set_text (buf);
1108         info_scroller_label.show();
1109
1110         if (info_scroller_count > ARDOUR_UI::instance()->announce_string().length()) {
1111                 info_scroller_connection.disconnect();
1112         }
1113
1114         return true;
1115 }
1116
1117 bool
1118 SessionDialog::on_delete_event (GdkEventAny* ev)
1119 {
1120         response (RESPONSE_CANCEL);
1121         return ArdourDialog::on_delete_event (ev);
1122 }