0164366f746e34dcaf2e2c8d97bf23b955df5a2b
[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_sample.set_shadow_type(SHADOW_ETCHED_OUT);
103         info_sample.set_no_show_all (true);
104         info_sample.set_border_width (12);
105         get_vbox()->pack_start (info_sample, 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 #ifdef MIXBUS
378         recent_session_display.append_column (_("Created With"), recent_session_columns.created_with);
379 #else
380         recent_session_display.append_column (_("File Resolution"), recent_session_columns.disk_format);
381 #endif
382         recent_session_display.append_column (_("Last Modified"), recent_session_columns.time_formatted);
383         recent_session_display.set_headers_visible (true);
384         recent_session_display.get_selection()->set_mode (SELECTION_SINGLE);
385
386         recent_session_display.get_selection()->signal_changed().connect (sigc::mem_fun (*this, &SessionDialog::recent_session_row_selected));
387
388         recent_scroller.add (recent_session_display);
389         recent_scroller.set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
390         recent_scroller.set_shadow_type (Gtk::SHADOW_IN);
391
392         recent_session_display.show();
393         recent_session_display.signal_row_activated().connect (sigc::mem_fun (*this, &SessionDialog::recent_row_activated));
394         recent_session_display.signal_button_press_event().connect (sigc::mem_fun (*this, &SessionDialog::recent_button_press), false);
395 }
396
397 void
398 SessionDialog::setup_initial_choice_box ()
399 {
400         ic_vbox.set_spacing (6);
401
402         HBox* centering_hbox = manage (new HBox);
403         VBox* centering_vbox = manage (new VBox);
404
405         centering_vbox->set_spacing (6);
406
407         Label* new_label = manage (new Label);
408         new_label->set_markup (string_compose ("<span weight=\"bold\" size=\"large\">%1</span>", _("New Session")));
409         new_label->set_justify (JUSTIFY_CENTER);
410
411         ic_new_session_button.add (*new_label);
412         ic_new_session_button.signal_clicked().connect (sigc::mem_fun (*this, &SessionDialog::new_session_button_clicked));
413
414         Gtk::HBox* hbox = manage (new HBox);
415         Gtk::VBox* vbox = manage (new VBox);
416         hbox->set_spacing (12);
417         vbox->set_spacing (12);
418
419         string image_path;
420
421         Searchpath rc (ARDOUR::ardour_data_search_path());
422         rc.add_subdirectory_to_paths ("resources");
423
424         if (find_file (rc, PROGRAM_NAME "-small-splash.png", image_path)) {
425                 Gtk::Image* image;
426                 if ((image = manage (new Gtk::Image (image_path))) != 0) {
427                         hbox->pack_start (*image, false, false);
428                 }
429         }
430
431         vbox->pack_start (ic_new_session_button, true, true, 20);
432         hbox->pack_start (*vbox, true, true, 20);
433
434         centering_vbox->pack_start (*hbox, false, false);
435
436         /* Possible update message */
437
438         if (ARDOUR_UI::instance()->announce_string() != "" ) {
439
440                 Box *info_box = manage (new VBox);
441                 info_box->set_border_width (12);
442                 info_box->set_spacing (6);
443
444                 info_box->pack_start (info_scroller_label, false, false);
445
446                 info_scroller_count = 0;
447                 info_scroller_connection = Glib::signal_timeout().connect (mem_fun(*this, &SessionDialog::info_scroller_update), 50);
448
449                 Gtk::Button *updates_button = manage (new Gtk::Button (_("Check the website for more...")));
450
451                 updates_button->signal_clicked().connect (mem_fun(*this, &SessionDialog::updates_button_clicked) );
452                 set_tooltip (*updates_button, _("Click to open the program website in your web browser"));
453
454                 info_box->pack_start (*updates_button, false, false);
455
456                 info_sample.add (*info_box);
457                 info_box->show_all ();
458                 info_sample.show ();
459         }
460
461         /* recent session scroller */
462         setup_recent_sessions ();
463
464         recent_label.set_no_show_all (true);
465         recent_scroller.set_no_show_all (true);
466
467         recent_label.set_markup (string_compose ("<span weight=\"bold\" size=\"large\">%1</span>", _("Recent Sessions")));
468
469         centering_vbox->pack_start (recent_label, false, false, 12);
470         centering_vbox->pack_start (recent_scroller, true, true);
471
472         /* Browse button */
473
474         existing_session_chooser.set_title (_("Select session file"));
475         existing_session_chooser.signal_file_set().connect (sigc::mem_fun (*this, &SessionDialog::existing_session_selected));
476         existing_session_chooser.set_current_folder(poor_mans_glob (Config->get_default_session_parent_dir()));
477
478         FileFilter session_filter;
479         session_filter.add_pattern (string_compose(X_("*%1"), ARDOUR::statefile_suffix));
480         session_filter.set_name (string_compose (_("%1 sessions"), PROGRAM_NAME));
481         existing_session_chooser.add_filter (session_filter);
482
483         FileFilter archive_filter;
484         archive_filter.add_pattern (X_("*.tar.xz"));
485         archive_filter.set_name (_("Session Archives"));
486         existing_session_chooser.add_filter (archive_filter);
487
488         existing_session_chooser.set_filter (session_filter);
489
490         Gtkmm2ext::add_volume_shortcuts (existing_session_chooser);
491
492         Label* browse_label = manage (new Label);
493         browse_label->set_markup (string_compose ("<span weight=\"bold\" size=\"large\">%1</span>", _("Other Sessions")));
494
495         centering_vbox->pack_start (*browse_label, false, false, 12);
496         centering_vbox->pack_start (existing_session_chooser, false, false);
497
498         /* --disable plugins UI */
499
500         _disable_plugins.set_label (_("Safe Mode: Disable all Plugins"));
501         _disable_plugins.set_flags (Gtk::CAN_FOCUS);
502         _disable_plugins.set_relief (Gtk::RELIEF_NORMAL);
503         _disable_plugins.set_mode (true);
504         _disable_plugins.set_active (ARDOUR::Session::get_disable_all_loaded_plugins());
505         _disable_plugins.set_border_width(0);
506         _disable_plugins.signal_clicked().connect (sigc::mem_fun (*this, &SessionDialog::disable_plugins_clicked));
507         centering_vbox->pack_start (_disable_plugins, false, false);
508
509         /* pack it all up */
510
511         centering_hbox->pack_start (*centering_vbox, true, true);
512         ic_vbox.pack_start (*centering_hbox, true, true);
513         ic_vbox.show_all ();
514 }
515
516 void
517 SessionDialog::session_selected ()
518 {
519         /* HACK HACK HACK ... change the "Apply" button label
520            to say "Open"
521         */
522
523         Gtk::Widget* tl = ic_vbox.get_toplevel();
524         Gtk::Window* win;
525         if ((win = dynamic_cast<Gtk::Window*>(tl)) != 0) {
526                 /* ::get_default_widget() is not wrapped in gtkmm */
527                 Gtk::Widget* def = wrap (gtk_window_get_default_widget (win->gobj()));
528                 Gtk::Button* button;
529                 if ((button = dynamic_cast<Gtk::Button*>(def)) != 0) {
530                         button->set_label (_("Open"));
531                 }
532         }
533 }
534
535 void
536 SessionDialog::new_session_button_clicked ()
537 {
538         _existing_session_chooser_used = false;
539         recent_session_display.get_selection()->unselect_all ();
540
541         get_vbox()->remove (ic_vbox);
542         get_vbox()->pack_start (session_new_vbox, true, true);
543         back_button->set_sensitive (true);
544         new_name_entry.grab_focus ();
545 }
546
547 bool
548 SessionDialog::back_button_pressed (GdkEventButton*)
549 {
550         get_vbox()->remove (session_new_vbox);
551         back_button->set_sensitive (false);
552         get_vbox()->pack_start (ic_vbox);
553
554         return true;
555 }
556
557 bool
558 SessionDialog::open_button_pressed (GdkEventButton* ev)
559 {
560         if (Gtkmm2ext::Keyboard::modifier_state_equals (ev->state, Gtkmm2ext::Keyboard::PrimaryModifier)) {
561                 _disable_plugins.set_active();
562         }
563         response (RESPONSE_ACCEPT);
564         return true;
565 }
566
567 void
568 SessionDialog::populate_session_templates ()
569 {
570         vector<TemplateInfo> templates;
571
572         find_session_templates (templates, true);
573
574         template_model->clear ();
575
576         /* Add Lua Scripts dedicated to session-setup */
577         LuaScriptList& ms (LuaScripting::instance ().scripts (LuaScriptInfo::SessionInit));
578         for (LuaScriptList::const_iterator s = ms.begin(); s != ms.end(); ++s) {
579                 TreeModel::Row row = *(template_model->append ());
580                 row[session_template_columns.name] = (*s)->name;
581                 row[session_template_columns.path] = "urn:ardour:" + (*s)->path;
582                 row[session_template_columns.description] = (*s)->description;
583                 row[session_template_columns.created_with_short] = _("{Factory Template}");
584                 row[session_template_columns.created_with_long] = _("{Factory Template}");
585         }
586
587         /* Add Lua Action Scripts which can also be used for session-setup */
588         LuaScriptList& as (LuaScripting::instance ().scripts (LuaScriptInfo::EditorAction));
589         for (LuaScriptList::const_iterator s = as.begin(); s != as.end(); ++s) {
590                 if (!((*s)->subtype & LuaScriptInfo::SessionSetup)) {
591                         continue;
592                 }
593                 TreeModel::Row row = *(template_model->append ());
594                 row[session_template_columns.name] = (*s)->name;
595                 row[session_template_columns.path] = "urn:ardour:" + (*s)->path;
596                 row[session_template_columns.description] = (*s)->description;
597                 row[session_template_columns.created_with_short] = _("{Factory Template}");
598                 row[session_template_columns.created_with_long] = _("{Factory Template}");
599         }
600
601
602         //Add any "template sessions" found in the user's preferences folder
603         for (vector<TemplateInfo>::iterator x = templates.begin(); x != templates.end(); ++x) {
604                 TreeModel::Row row;
605
606                 row = *(template_model->append ());
607
608                 row[session_template_columns.name] = (*x).name;
609                 row[session_template_columns.path] = (*x).path;
610                 row[session_template_columns.description] = (*x).description;
611                 row[session_template_columns.created_with_long] = (*x).created_with;
612                 row[session_template_columns.created_with_short] = (*x).created_with.substr(0, (*x).created_with.find(" "));
613         }
614
615         //Add an explicit 'Empty Template' item
616         TreeModel::Row row = *template_model->prepend ();
617         row[session_template_columns.name] = (_("Empty Template"));
618         row[session_template_columns.path] = string();
619         row[session_template_columns.description] = _("An empty session with factory default settings.");
620         row[session_template_columns.created_with_short] = _("");
621         row[session_template_columns.created_with_long] = _("");
622
623         //auto-select the first item in the list
624         Gtk::TreeModel::Row first = template_model->children()[0];
625         if(first) {
626                 template_chooser.get_selection()->select(first);
627         }
628 }
629
630 void
631 SessionDialog::setup_new_session_page ()
632 {
633         session_new_vbox.set_border_width (8);
634         session_new_vbox.set_spacing (8);
635
636         Label* name_label = manage (new Label);
637         name_label->set_text (_("Session name:"));
638
639         HBox* name_hbox = manage (new HBox);
640         name_hbox->set_spacing (8);
641         name_hbox->pack_start (*name_label, false, true);
642         name_hbox->pack_start (new_name_entry, true, true);
643
644         //check to see if a session name was provided on command line
645         if (!ARDOUR_COMMAND_LINE::session_name.empty()) {
646                 new_name_entry.set_text  (Glib::path_get_basename (ARDOUR_COMMAND_LINE::session_name));
647                 open_button->set_sensitive (true);
648         }
649
650         new_name_entry.signal_changed().connect (sigc::mem_fun (*this, &SessionDialog::new_name_changed));
651         new_name_entry.signal_activate().connect (sigc::mem_fun (*this, &SessionDialog::new_name_activated));
652
653         //Folder location for the new session
654         Label* new_folder_label = manage (new Label);
655         new_folder_label->set_text (_("Create session folder in:"));
656         HBox* folder_box = manage (new HBox);
657         folder_box->set_spacing (8);
658         folder_box->pack_start (*new_folder_label, false, false);
659         folder_box->pack_start (new_folder_chooser, true, true);
660
661         //determine the text in the new folder selector
662         if (!ARDOUR_COMMAND_LINE::session_name.empty()) {
663                 new_folder_chooser.set_current_folder (poor_mans_glob (Glib::path_get_dirname (ARDOUR_COMMAND_LINE::session_name)));
664         } else if (ARDOUR_UI::instance()->session_loaded) {
665                 // point the new session file chooser at the parent directory of the current session
666                 string session_parent_dir = Glib::path_get_dirname(ARDOUR_UI::instance()->the_session()->path());
667                 new_folder_chooser.set_current_folder (session_parent_dir);
668                 string default_session_folder = poor_mans_glob (Config->get_default_session_parent_dir());
669
670                 try {
671                         /* add_shortcut_folder throws an exception if the folder being added already has a shortcut */
672                         new_folder_chooser.add_shortcut_folder (default_session_folder);
673                 }
674                 catch (Glib::Error & e) {
675                         std::cerr << "new_folder_chooser.add_shortcut_folder (" << default_session_folder << ") threw Glib::Error " << e.what() << std::endl;
676                 }
677         } else {
678                 new_folder_chooser.set_current_folder (poor_mans_glob (Config->get_default_session_parent_dir()));
679         }
680         new_folder_chooser.show ();
681         new_folder_chooser.set_title (_("Select folder for session"));
682         Gtkmm2ext::add_volume_shortcuts (new_folder_chooser);
683
684         //Template & Template Description area
685         HBox* template_hbox = manage (new HBox);
686
687         //if the "template override" is provided, don't give the user any template selections   (?)
688         if ( load_template_override.empty() ) {
689                 template_hbox->set_spacing (8);
690
691                 Gtk::ScrolledWindow *template_scroller = manage (new Gtk::ScrolledWindow());
692                 template_scroller->set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
693                 template_scroller->add (template_chooser);
694
695                 Gtk::ScrolledWindow *desc_scroller = manage (new Gtk::ScrolledWindow());
696                 desc_scroller->set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
697                 desc_scroller->add (template_desc);
698
699                 template_hbox->pack_start (*template_scroller, true, true);
700
701                 template_desc_sample.set_name (X_("TextHighlightFrame"));
702                 template_desc_sample.add (*desc_scroller);
703                 template_hbox->pack_start (template_desc_sample, true, true);
704         }
705
706         //template_desc is the textview that displays the currently selected template's description
707         template_desc.set_editable (false);
708         template_desc.set_wrap_mode (Gtk::WRAP_WORD);
709         template_desc.set_size_request (300,400);
710         template_desc.set_name (X_("TextOnBackground"));
711         template_desc.set_border_width (6);
712
713         //template_chooser is the treeview showing available templates
714         template_model = TreeStore::create (session_template_columns);
715         template_chooser.set_model (template_model);
716         template_chooser.append_column (_("Template"), session_template_columns.name);
717 #ifdef MIXBUS
718         template_chooser.append_column (_("Created With"), session_template_columns.created_with_short);
719 #endif
720         template_chooser.set_tooltip_column(4); // created_with_long
721         template_chooser.set_headers_visible (true);
722         template_chooser.get_selection()->set_mode (SELECTION_SINGLE);
723         template_chooser.get_selection()->signal_changed().connect (sigc::mem_fun (*this, &SessionDialog::template_row_selected));
724         template_chooser.set_sensitive (true);
725
726         session_new_vbox.pack_start (*template_hbox, true, true);
727         session_new_vbox.pack_start (*folder_box, false, true);
728         session_new_vbox.pack_start (*name_hbox, false, true);
729         session_new_vbox.show_all ();
730 }
731
732 void
733 SessionDialog::new_name_changed ()
734 {
735         if (!new_name_entry.get_text().empty()) {
736                 session_selected ();
737                 open_button->set_sensitive (true);
738         } else {
739                 open_button->set_sensitive (false);
740         }
741 }
742
743 void
744 SessionDialog::new_name_activated ()
745 {
746         response (RESPONSE_ACCEPT);
747 }
748
749 int
750 SessionDialog::redisplay_recent_sessions ()
751 {
752         std::vector<std::string> session_directories;
753         RecentSessionsSorter cmp;
754
755         recent_session_display.set_model (Glib::RefPtr<TreeModel>(0));
756         recent_session_model->clear ();
757
758         ARDOUR::RecentSessions rs;
759         ARDOUR::read_recent_sessions (rs);
760
761         if (rs.empty()) {
762                 recent_session_display.set_model (recent_session_model);
763                 return 0;
764         }
765
766         // sort them alphabetically
767         sort (rs.begin(), rs.end(), cmp);
768
769         for (ARDOUR::RecentSessions::iterator i = rs.begin(); i != rs.end(); ++i) {
770                 session_directories.push_back ((*i).second);
771         }
772
773         int session_snapshot_count = 0;
774
775         for (vector<std::string>::const_iterator i = session_directories.begin(); i != session_directories.end(); ++i)
776         {
777                 std::vector<std::string> state_file_paths;
778
779                 // now get available states for this session
780
781                 get_state_files_in_directory (*i, state_file_paths);
782
783                 vector<string> states;
784                 vector<const gchar*> item;
785                 string dirname = *i;
786
787                 /* remove any trailing / */
788
789                 if (dirname[dirname.length()-1] == '/') {
790                         dirname = dirname.substr (0, dirname.length()-1);
791                 }
792
793                 /* check whether session still exists */
794                 if (!Glib::file_test(dirname.c_str(), Glib::FILE_TEST_EXISTS)) {
795                         /* session doesn't exist */
796                         continue;
797                 }
798
799                 /* now get available states for this session */
800
801                 states = Session::possible_states (dirname);
802
803                 if (states.empty()) {
804                         /* no state file? */
805                         continue;
806                 }
807
808                 std::vector<string> state_file_names(get_file_names_no_extension (state_file_paths));
809
810                 if (state_file_names.empty()) {
811                         continue;
812                 }
813
814                 float sr;
815                 SampleFormat sf;
816                 std::string program_version;
817
818                 std::string state_file_basename;
819
820                 if (state_file_names.size() > 1) {
821                         state_file_basename = Session::get_snapshot_from_instant (dirname);
822                         std::string s = Glib::build_filename (dirname, state_file_basename + statefile_suffix);
823                         if (!Glib::file_test (s, Glib::FILE_TEST_IS_REGULAR)) {
824                                 state_file_basename = "";
825                         }
826                 }
827
828                 if (state_file_basename.empty()) {
829                         state_file_basename = state_file_names.front();
830                 }
831
832                 std::string s = Glib::build_filename (dirname, state_file_basename + statefile_suffix);
833
834                 int err = Session::get_info_from_path (s, sr, sf, program_version);
835                 if (err < 0) {
836                         // XML cannot be parsed, or unsuppored version
837                         continue;
838                 }
839
840                 GStatBuf gsb;
841                 g_stat (s.c_str(), &gsb);
842
843                 Gtk::TreeModel::Row row = *(recent_session_model->append());
844                 row[recent_session_columns.fullpath] = s;
845                 row[recent_session_columns.time_modified] = gsb.st_mtime;
846
847
848                 if (err == 0) {
849                         row[recent_session_columns.sample_rate] = rate_as_string (sr);
850                         switch (sf) {
851                         case FormatFloat:
852                                 row[recent_session_columns.disk_format] = _("32-bit float");
853                                 break;
854                         case FormatInt24:
855                                 row[recent_session_columns.disk_format] = _("24-bit");
856                                 break;
857                         case FormatInt16:
858                                 row[recent_session_columns.disk_format] = _("16-bit");
859                                 break;
860                         }
861                 } else {
862                         row[recent_session_columns.sample_rate] = "??";
863                         row[recent_session_columns.disk_format] = "--";
864                 }
865
866                 if (program_version.empty()) {
867                         row[recent_session_columns.tip] = Gtkmm2ext::markup_escape_text (dirname);
868                 } else {
869                         row[recent_session_columns.tip] = Gtkmm2ext::markup_escape_text (dirname + "\n" + string_compose (_("Last modified with: %1"), program_version));
870                         row[recent_session_columns.created_with] = program_version;
871                 }
872
873                 ++session_snapshot_count;
874
875                 if (state_file_names.size() > 1) {
876                         // multiple session files in the session directory - show the directory name.
877                         // if there's not a session file with the same name as the session directory,
878                         // opening the parent item will fail, but expanding it will show the session
879                         // files that actually exist, and the right one can then be opened.
880                         row[recent_session_columns.visible_name] = Glib::path_get_basename (dirname);
881                         int64_t most_recent = 0;
882
883                         // add the children
884                         int kidcount = 0;
885                         for (std::vector<std::string>::iterator i2 = state_file_names.begin(); i2 != state_file_names.end(); ++i2) {
886
887                                 s = Glib::build_filename (dirname, *i2 + statefile_suffix);
888                                 Gtk::TreeModel::Row child_row = *(recent_session_model->append (row.children()));
889
890                                 child_row[recent_session_columns.visible_name] = *i2;
891                                 child_row[recent_session_columns.fullpath] = s;
892                                 child_row[recent_session_columns.tip] = Gtkmm2ext::markup_escape_text (dirname);
893                                 g_stat (s.c_str(), &gsb);
894                                 child_row[recent_session_columns.time_modified] = gsb.st_mtime;
895
896                                 Glib::DateTime gdt(Glib::DateTime::create_now_local (gsb.st_mtime));
897                                 child_row[recent_session_columns.time_formatted] = gdt.format ("%F %H:%M");
898
899                                 if (gsb.st_mtime > most_recent) {
900                                         most_recent = gsb.st_mtime;
901                                 }
902
903                                 if (++kidcount < 5) {
904                                         // parse "modified with" for the first 5 snapshots
905                                         if (Session::get_info_from_path (s, sr, sf, program_version) == 0) {
906 #if 0
907                                                 child_row[recent_session_columns.sample_rate] = rate_as_string (sr);
908                                                 switch (sf) {
909                                                 case FormatFloat:
910                                                         child_row[recent_session_columns.disk_format] = _("32-bit float");
911                                                         break;
912                                                 case FormatInt24:
913                                                         child_row[recent_session_columns.disk_format] = _("24-bit");
914                                                         break;
915                                                 case FormatInt16:
916                                                         child_row[recent_session_columns.disk_format] = _("16-bit");
917                                                         break;
918                                                 }
919 #else
920                                                 child_row[recent_session_columns.sample_rate] = "";
921                                                 child_row[recent_session_columns.disk_format] = "";
922 #endif
923                                         } else {
924                                                 child_row[recent_session_columns.sample_rate] = "??";
925                                                 child_row[recent_session_columns.disk_format] = "--";
926                                         }
927                                         if (!program_version.empty()) {
928                                                 child_row[recent_session_columns.tip] = Gtkmm2ext::markup_escape_text (string_compose (_("Last modified with: %1"), program_version));
929                                         }
930                                 } else {
931                                         child_row[recent_session_columns.sample_rate] = "";
932                                         child_row[recent_session_columns.disk_format] = "";
933                                 }
934
935                                 ++session_snapshot_count;
936                         }
937
938                         assert (most_recent >= row[recent_session_columns.time_modified]);
939                         row[recent_session_columns.time_modified] = most_recent;
940
941                 } else {
942                         // only a single session file in the directory - show its actual name.
943                         row[recent_session_columns.visible_name] = state_file_basename;
944                 }
945
946                 Glib::DateTime gdt(Glib::DateTime::create_now_local (row[recent_session_columns.time_modified]));
947                 row[recent_session_columns.time_formatted] = gdt.format ("%F %H:%M");
948         }
949
950         recent_session_display.set_tooltip_column(1); // recent_session_columns.tip
951         recent_session_display.set_model (recent_session_model);
952
953         // custom sort
954         Gtk::TreeView::Column* pColumn;
955         if ((pColumn = recent_session_display.get_column (0))) { // name
956                 pColumn->set_sort_column (recent_session_columns.visible_name);
957         }
958         if ((pColumn = recent_session_display.get_column (3))) { // date
959                 pColumn->set_sort_column (recent_session_columns.time_modified); // unixtime
960         }
961
962         int32_t sort = UIConfiguration::instance().get_recent_session_sort();
963         if (abs(sort) != 1 + recent_session_columns.visible_name.index () &&
964             abs(sort) != 1 + recent_session_columns.time_modified.index ()) {
965                 sort = 1 + recent_session_columns.visible_name.index();
966         }
967         recent_session_model->set_sort_column (abs (sort) -1, sort < 0 ? Gtk::SORT_DESCENDING : Gtk::SORT_ASCENDING);
968
969         return session_snapshot_count;
970 }
971
972 void
973 SessionDialog::recent_session_sort_changed ()
974 {
975         int column;
976         SortType order;
977         if (recent_session_model->get_sort_column_id (column, order)) {
978                 int32_t sort = (column + 1) * (order == Gtk::SORT_DESCENDING ? -1 : 1);
979                 if (sort != UIConfiguration::instance().get_recent_session_sort()) {
980                         UIConfiguration::instance().set_recent_session_sort(sort);
981                 }
982         }
983 }
984
985 void
986 SessionDialog::recent_session_row_selected ()
987 {
988         if (recent_session_display.get_selection()->count_selected_rows() > 0) {
989                 open_button->set_sensitive (true);
990                 session_selected ();
991         } else {
992                 open_button->set_sensitive (false);
993         }
994 }
995
996 void
997 SessionDialog::template_row_selected ()
998 {
999         if (template_chooser.get_selection()->count_selected_rows() > 0) {
1000                 TreeIter iter = template_chooser.get_selection()->get_selected();
1001
1002                 if (iter) {
1003                         string s = (*iter)[session_template_columns.description];
1004                         template_desc.get_buffer()->set_text (s);
1005                 }
1006         }
1007 }
1008
1009 void
1010 SessionDialog::recent_row_activated (const Gtk::TreePath&, Gtk::TreeViewColumn*)
1011 {
1012         response (RESPONSE_ACCEPT);
1013 }
1014
1015 bool
1016 SessionDialog::recent_button_press (GdkEventButton* ev)
1017 {
1018         if ((ev->type == GDK_BUTTON_PRESS) && (ev->button == 3) ) {
1019
1020                 TreeModel::Path path;
1021                 TreeViewColumn* column;
1022                 int cellx, celly;
1023                 if (recent_session_display.get_path_at_pos ((int)ev->x, (int)ev->y, path, column, cellx, celly)) {
1024                         Glib::RefPtr<Gtk::TreeView::Selection> selection = recent_session_display.get_selection();
1025                         if (selection) {
1026                                 selection->unselect_all();
1027                                 selection->select(path);
1028                         }
1029                 }
1030
1031                 if (recent_session_display.get_selection()->count_selected_rows() > 0) {
1032                         recent_context_mennu (ev);
1033                 }
1034         }
1035         return false;
1036 }
1037
1038 void
1039 SessionDialog::recent_context_mennu (GdkEventButton *ev)
1040 {
1041         using namespace Gtk::Menu_Helpers;
1042
1043         TreeIter iter = recent_session_display.get_selection()->get_selected();
1044         assert (iter);
1045         string s = (*iter)[recent_session_columns.fullpath];
1046         if (Glib::file_test (s, Glib::FILE_TEST_IS_REGULAR)) {
1047                 s = Glib::path_get_dirname (s);
1048         }
1049         if (!Glib::file_test (s, Glib::FILE_TEST_IS_DIR)) {
1050                 return;
1051         }
1052
1053         Gtk::TreeModel::Path tpath = recent_session_model->get_path(iter);
1054         const bool is_child = tpath.up () && tpath.up ();
1055
1056         Gtk::Menu* m = manage (new Menu);
1057         MenuList& items = m->items ();
1058         items.push_back (MenuElem (s, sigc::bind (sigc::hide_return (sigc::ptr_fun (&PBD::open_folder)), s)));
1059         if (!is_child) {
1060                 items.push_back (SeparatorElem());
1061                 items.push_back (MenuElem (_("Remove session from recent list"), sigc::mem_fun (*this, &SessionDialog::recent_remove_selected)));
1062         }
1063         m->popup (ev->button, ev->time);
1064 }
1065
1066 void
1067 SessionDialog::recent_remove_selected ()
1068 {
1069         TreeIter iter = recent_session_display.get_selection()->get_selected();
1070         assert (iter);
1071         string s = (*iter)[recent_session_columns.fullpath];
1072         if (Glib::file_test (s, Glib::FILE_TEST_IS_REGULAR)) {
1073                 s = Glib::path_get_dirname (s);
1074         }
1075         ARDOUR::remove_recent_sessions (s);
1076         redisplay_recent_sessions ();
1077 }
1078
1079 void
1080 SessionDialog::disable_plugins_clicked ()
1081 {
1082         ARDOUR::Session::set_disable_all_loaded_plugins (_disable_plugins.get_active());
1083 }
1084
1085 void
1086 SessionDialog::existing_session_selected ()
1087 {
1088         _existing_session_chooser_used = true;
1089         recent_session_display.get_selection()->unselect_all();
1090         /* mark this sensitive in case we come back here after a failed open
1091          * attempt and the user has hacked up the fix. sigh.
1092          */
1093         open_button->set_sensitive (true);
1094         response (RESPONSE_ACCEPT);
1095 }
1096
1097 void
1098 SessionDialog::updates_button_clicked ()
1099 {
1100         //now open a browser window so user can see more
1101         PBD::open_uri (Config->get_updates_url());
1102 }
1103
1104 bool
1105 SessionDialog::info_scroller_update()
1106 {
1107         info_scroller_count++;
1108
1109         char buf[512];
1110         snprintf (buf, std::min(info_scroller_count,sizeof(buf)-1), "%s", ARDOUR_UI::instance()->announce_string().c_str() );
1111         buf[info_scroller_count] = 0;
1112         info_scroller_label.set_text (buf);
1113         info_scroller_label.show();
1114
1115         if (info_scroller_count > ARDOUR_UI::instance()->announce_string().length()) {
1116                 info_scroller_connection.disconnect();
1117         }
1118
1119         return true;
1120 }
1121
1122 bool
1123 SessionDialog::on_delete_event (GdkEventAny* ev)
1124 {
1125         response (RESPONSE_CANCEL);
1126         return ArdourDialog::on_delete_event (ev);
1127 }