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