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