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