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