Fix session-open after selecting new, template, then back
[ardour.git] / gtk2_ardour / template_dialog.cc
1 /*
2     Copyright (C) 2010 Paul Davis
3     Author: Johannes Mueller
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19 */
20
21 #include <map>
22 #include <vector>
23 #include <cerrno>
24
25 #include <glib/gstdio.h>
26
27 #include <gtkmm/filechooserdialog.h>
28 #include <gtkmm/frame.h>
29 #include <gtkmm/liststore.h>
30 #include <gtkmm/notebook.h>
31 #include <gtkmm/progressbar.h>
32 #include <gtkmm/separator.h>
33 #include <gtkmm/scrolledwindow.h>
34 #include <gtkmm/stock.h>
35 #include <gtkmm/textview.h>
36 #include <gtkmm/treeiter.h>
37 #include <gtkmm/treeview.h>
38
39 #include "pbd/basename.h"
40 #include "pbd/error.h"
41 #include "pbd/file_archive.h"
42 #include "pbd/file_utils.h"
43 #include "pbd/i18n.h"
44 #include "pbd/xml++.h"
45
46 #include "gtkmm2ext/gui_thread.h"
47
48 #include "ardour/filesystem_paths.h"
49 #include "ardour/template_utils.h"
50
51 #include "progress_reporter.h"
52
53 #include "template_dialog.h"
54
55 using namespace std;
56 using namespace Gtk;
57 using namespace PBD;
58 using namespace ARDOUR;
59
60 class TemplateManager : public Gtk::HBox,
61                         public ProgressReporter
62 {
63 public:
64         virtual ~TemplateManager () {}
65
66         void init ();
67         void handle_dirty_description ();
68
69         PBD::Signal0<void> TemplatesImported;
70
71 protected:
72         TemplateManager ();
73
74         void setup_model (const std::vector<ARDOUR::TemplateInfo>& templates);
75
76         void row_selection_changed ();
77
78         virtual void delete_selected_template () = 0;
79         bool adjust_plugin_paths (XMLNode* node, const std::string& name, const std::string& new_name) const;
80
81         struct SessionTemplateColumns : public Gtk::TreeModel::ColumnRecord {
82                 SessionTemplateColumns () {
83                         add (name);
84                         add (path);
85                         add (description);
86                 }
87
88                 Gtk::TreeModelColumn<std::string> name;
89                 Gtk::TreeModelColumn<std::string> path;
90                 Gtk::TreeModelColumn<std::string> description;
91         };
92
93         Glib::RefPtr<Gtk::ListStore>  _template_model;
94         SessionTemplateColumns _template_columns;
95
96         Gtk::TreeModel::const_iterator _current_selection;
97
98         Gtk::ProgressBar _progress_bar;
99         std::string _current_action;
100
101 private:
102         void render_template_names (Gtk::CellRenderer* rnd, const Gtk::TreeModel::iterator& it);
103         void validate_edit (const Glib::ustring& path_string, const Glib::ustring& new_name);
104         void start_edit ();
105
106         void set_desc_dirty ();
107
108         bool key_event (GdkEventKey* ev);
109
110         virtual void get_templates (vector<TemplateInfo>& templates) const = 0;
111
112         virtual void rename_template (Gtk::TreeModel::iterator& item, const Glib::ustring& new_name) = 0;
113
114         virtual void save_template_desc ();
115
116         void export_all_templates ();
117         void import_template_set ();
118
119         virtual std::string templates_dir () const = 0;
120         virtual std::string template_file (const Gtk::TreeModel::const_iterator& item) const = 0;
121
122         virtual bool adjust_xml_tree (XMLTree& tree, const std::string& old_name, const std::string& new_name) const = 0;
123
124         Gtk::TreeView _template_treeview;
125         Gtk::CellRendererText _validating_cellrenderer;
126         Gtk::TreeView::Column _validated_column;
127
128         Gtk::TextView _description_editor;
129         Gtk::Button _save_desc;
130         bool _desc_dirty;
131
132         Gtk::Button _remove_button;
133         Gtk::Button _rename_button;
134
135         Gtk::Button _export_all_templates_button;
136         Gtk::Button _import_template_set_button;
137
138         sigc::connection _cursor_changed_connection;
139
140         void update_progress_gui (float p);
141 };
142
143 class SessionTemplateManager : public TemplateManager
144 {
145 public:
146         SessionTemplateManager () : TemplateManager () {}
147         ~SessionTemplateManager () {}
148
149         void get_templates (vector<TemplateInfo>& templates) const;
150
151 private:
152         void rename_template (Gtk::TreeModel::iterator& item, const Glib::ustring& new_name);
153         void delete_selected_template ();
154
155         std::string templates_dir () const;
156         std::string template_file (const Gtk::TreeModel::const_iterator& item) const;
157
158         bool adjust_xml_tree (XMLTree& tree, const std::string& old_name, const std::string& new_name) const;
159 };
160
161
162 class RouteTemplateManager : public TemplateManager
163 {
164 public:
165         RouteTemplateManager () : TemplateManager () {}
166         ~RouteTemplateManager () {}
167
168         void get_templates (vector<TemplateInfo>& templates) const;
169
170 private:
171         void rename_template (Gtk::TreeModel::iterator& item, const Glib::ustring& new_name);
172         void delete_selected_template ();
173
174         std::string templates_dir () const;
175         std::string template_file (const Gtk::TreeModel::const_iterator& item) const;
176
177         bool adjust_xml_tree (XMLTree& tree, const std::string& old_name, const std::string& new_name) const;
178 };
179
180
181
182 TemplateDialog::TemplateDialog ()
183         : ArdourDialog ("Manage Templates")
184 {
185         Notebook* nb = manage (new Notebook);
186
187         SessionTemplateManager* session_tm = manage (new SessionTemplateManager);
188         nb->append_page (*session_tm, _("Session Templates"));
189
190         RouteTemplateManager* route_tm = manage (new RouteTemplateManager);
191         nb->append_page (*route_tm, _("Track Templates"));
192
193         get_vbox()->pack_start (*nb);
194         add_button (_("Done"), Gtk::RESPONSE_OK);
195
196         get_vbox()->show_all();
197
198         session_tm->init ();
199         route_tm->init ();
200
201         session_tm->TemplatesImported.connect (*this, invalidator (*this), boost::bind (&RouteTemplateManager::init, route_tm), gui_context ());
202         route_tm->TemplatesImported.connect (*this, invalidator (*this), boost::bind (&SessionTemplateManager::init, session_tm), gui_context ());
203
204         signal_hide().connect (sigc::mem_fun (session_tm, &TemplateManager::handle_dirty_description));
205         signal_hide().connect (sigc::mem_fun (route_tm, &TemplateManager::handle_dirty_description));
206         nb->signal_switch_page().connect (boost::bind (&TemplateManager::handle_dirty_description, session_tm));
207         nb->signal_switch_page().connect (boost::bind (&TemplateManager::handle_dirty_description, route_tm));
208 }
209
210 TemplateManager::TemplateManager ()
211         : HBox ()
212         , ProgressReporter ()
213         , _save_desc (_("Save Description"))
214         , _desc_dirty (false)
215         , _remove_button (_("Remove"))
216         , _rename_button (_("Rename"))
217         , _export_all_templates_button (_("Export all"))
218         , _import_template_set_button (_("Import"))
219 {
220         _template_model = ListStore::create (_template_columns);
221         _template_treeview.set_model (_template_model);
222
223         _validated_column.set_title (_("Template Name"));
224         _validated_column.pack_start (_validating_cellrenderer);
225         _template_treeview.append_column (_validated_column);
226         _validating_cellrenderer.property_editable() = true;
227
228         _validated_column.set_cell_data_func (_validating_cellrenderer, sigc::mem_fun (*this, &TemplateManager::render_template_names));
229         _validating_cellrenderer.signal_edited().connect (sigc::mem_fun (*this, &TemplateManager::validate_edit));
230         _cursor_changed_connection = _template_treeview.signal_cursor_changed().connect (sigc::mem_fun (*this, &TemplateManager::row_selection_changed));
231         _template_treeview.signal_key_press_event().connect (sigc::mem_fun (*this, &TemplateManager::key_event));
232
233         ScrolledWindow* sw = manage (new ScrolledWindow);
234         sw->property_hscrollbar_policy() = POLICY_AUTOMATIC;
235         sw->add (_template_treeview);
236         sw->set_size_request (300, 200);
237
238         VBox* vb_btns = manage (new VBox);
239         vb_btns->set_spacing (4);
240         vb_btns->pack_start (_rename_button, false, false);
241         vb_btns->pack_start (_remove_button, false, false);
242         vb_btns->pack_start (_save_desc, false, false);
243
244         _rename_button.set_sensitive (false);
245         _rename_button.signal_clicked().connect (sigc::mem_fun (*this, &TemplateManager::start_edit));
246         _remove_button.set_sensitive (false);
247         _remove_button.signal_clicked().connect (sigc::mem_fun (*this, &TemplateManager::delete_selected_template));
248
249         vb_btns->pack_start (*(manage (new VSeparator ())));
250
251         vb_btns->pack_start (_export_all_templates_button, false, false);
252         vb_btns->pack_start (_import_template_set_button, false, false);
253
254         _export_all_templates_button.set_sensitive (false);
255         _export_all_templates_button.signal_clicked().connect (sigc::mem_fun (*this, &TemplateManager::export_all_templates));
256
257         _import_template_set_button.set_sensitive (true);
258         _import_template_set_button.signal_clicked().connect (sigc::mem_fun (*this, &TemplateManager::import_template_set));
259
260         set_spacing (6);
261
262         VBox* vb = manage (new VBox);
263         vb->pack_start (*sw);
264         vb->pack_start (_progress_bar);
265
266         Frame* desc_frame = manage (new Frame (_("Description")));
267
268         _description_editor.set_wrap_mode (Gtk::WRAP_WORD);
269         _description_editor.set_size_request (300,400);
270         _description_editor.set_border_width (6);
271
272         _save_desc.set_sensitive (false);
273         _save_desc.signal_clicked().connect (sigc::mem_fun (*this, &TemplateManager::save_template_desc));
274
275         _description_editor.get_buffer()->signal_changed().connect (sigc::mem_fun (*this, &TemplateManager::set_desc_dirty));
276
277         desc_frame->add (_description_editor);
278
279         pack_start (*vb);
280         pack_start (*desc_frame);
281         pack_start (*vb_btns);
282
283         show_all_children ();
284         _progress_bar.hide ();
285 }
286
287 void
288 TemplateManager::init ()
289 {
290         vector<TemplateInfo> templates;
291         get_templates (templates);
292         setup_model (templates);
293
294         _progress_bar.hide ();
295         _description_editor.set_sensitive (false);
296         _save_desc.set_sensitive (false);
297 }
298
299 void
300 TemplateManager::setup_model (const vector<TemplateInfo>& templates)
301 {
302         _template_model->clear ();
303
304         for (vector<TemplateInfo>::const_iterator it = templates.begin(); it != templates.end(); ++it) {
305                 TreeModel::Row row;
306                 row = *(_template_model->append ());
307
308                 row[_template_columns.name] = it->name;
309                 row[_template_columns.path] = it->path;
310                 row[_template_columns.description] = it->description;
311         }
312
313         _export_all_templates_button.set_sensitive (!templates.empty ());
314 }
315
316 void
317 TemplateManager::handle_dirty_description ()
318 {
319         if (_desc_dirty && _current_selection) {
320                 ArdourDialog dlg (_("Description not saved"), true);
321                 const string name = _current_selection->get_value (_template_columns.name);
322                 Label msg (string_compose (_("The discription of template \"%1\" has been modfied but has not been saved yet.\n"
323                                              "Do you want to save it?"), name));
324                 dlg.get_vbox()->pack_start (msg);
325                 msg.show ();
326                 dlg.add_button (_("Save"), RESPONSE_ACCEPT);
327                 dlg.add_button (_("Discard"), RESPONSE_REJECT);
328                 dlg.set_default_response (RESPONSE_REJECT);
329
330                 int response = dlg.run ();
331
332                 if (response == RESPONSE_ACCEPT) {
333                         save_template_desc ();
334                 } else {
335                         _description_editor.get_buffer()->set_text (_current_selection->get_value (_template_columns.description));
336                 }
337         }
338 }
339
340 void
341 TemplateManager::row_selection_changed ()
342 {
343         if (_current_selection) {
344                 handle_dirty_description ();
345         } else {
346                 _description_editor.get_buffer()->set_text ("");
347         }
348
349         _current_selection = _template_treeview.get_selection()->get_selected ();
350         if (_current_selection) {
351                 const string desc = _current_selection->get_value (_template_columns.description);
352                 _description_editor.get_buffer()->set_text (desc);
353         }
354
355         _desc_dirty = false;
356         _save_desc.set_sensitive (false);
357
358         _description_editor.set_sensitive (_current_selection);
359         _rename_button.set_sensitive (_current_selection);
360         _remove_button.set_sensitive (_current_selection);
361 }
362
363 void
364 TemplateManager::render_template_names (Gtk::CellRenderer*, const Gtk::TreeModel::iterator& it)
365 {
366         if (it) {
367                 _validating_cellrenderer.property_text () = it->get_value (_template_columns.name);
368         }
369 }
370
371 void
372 TemplateManager::validate_edit (const Glib::ustring& path_string, const Glib::ustring& new_name)
373 {
374         const TreePath path (path_string);
375         TreeModel::iterator current = _template_model->get_iter (path);
376
377         if (current->get_value (_template_columns.name) == new_name) {
378                 return;
379         }
380
381         TreeModel::Children rows = _template_model->children ();
382
383         bool found = false;
384         for (TreeModel::Children::const_iterator it = rows.begin(); it != rows.end(); ++it) {
385                 if (it->get_value (_template_columns.name) == new_name) {
386                         found = true;
387                         break;
388                 }
389         }
390
391         if (found) {
392                 error << string_compose (_("Template of name \"%1\" already exists"), new_name) << endmsg;
393                 return;
394         }
395
396
397         rename_template (current, new_name);
398 }
399
400 void
401 TemplateManager::start_edit ()
402 {
403         TreeModel::Path path;
404         TreeViewColumn* col;
405         _template_treeview.get_cursor (path, col);
406         _cursor_changed_connection.block ();
407         _template_treeview.set_cursor (path, *col, /*set_editing =*/ true);
408         _cursor_changed_connection.unblock ();
409 }
410
411 void
412 TemplateManager::set_desc_dirty ()
413 {
414         _desc_dirty = true;
415         _save_desc.set_sensitive (true);
416 }
417
418 void
419 TemplateManager::save_template_desc ()
420 {
421         const string file_path = template_file (_current_selection);
422
423         string desc_txt = _description_editor.get_buffer()->get_text ();
424         string::reverse_iterator wss = desc_txt.rbegin();
425         while (wss != desc_txt.rend() && isspace (*wss)) {
426                 desc_txt.erase (--(wss++).base());
427         }
428
429         _current_selection->set_value (_template_columns.description, desc_txt);
430
431         XMLTree tree;
432
433         if (!tree.read(file_path)) {
434                 error << string_compose (_("Could not parse template file \"%1\"."), file_path) << endmsg;
435                 return;
436         }
437
438         tree.root()->remove_nodes_and_delete (X_("description"));
439         XMLNode* desc = new XMLNode (X_("description"));
440
441         XMLNode* dn = new XMLNode (X_("content"), desc_txt);
442         desc->add_child_nocopy (*dn);
443
444         tree.root()->add_child_nocopy (*desc);
445
446         if (!tree.write ()) {
447                 error << string_compose(X_("Could not write to template file \"%1\"."), file_path) << endmsg;
448                 return;
449         }
450
451         _save_desc.set_sensitive (false);
452         _desc_dirty = false;
453 }
454
455 bool
456 TemplateManager::key_event (GdkEventKey* ev)
457 {
458         if (ev->keyval == GDK_KEY_F2) {
459                 start_edit ();
460                 return true;
461         }
462         if (ev->keyval == GDK_KEY_Delete) {
463                 delete_selected_template ();
464                 return true;
465         }
466
467         return false;
468 }
469
470 static
471 bool accept_all_files (string const &, void *)
472 {
473         return true;
474 }
475
476 static void _set_progress (Progress* p, size_t n, size_t t)
477 {
478         p->set_progress (float (n) / float(t));
479 }
480
481
482 void
483 TemplateManager::export_all_templates ()
484 {
485         GError* err = NULL;
486         char* td = g_dir_make_tmp ("ardour-templates-XXXXXX", &err);
487
488         if (!td) {
489                 error << string_compose(_("Could not make tmpdir: %1"), err->message) << endmsg;
490                 return;
491         }
492         const string tmpdir (td);
493         g_free (td);
494         g_clear_error (&err);
495
496         FileChooserDialog dialog(_("Save Exported Template Archive"), FILE_CHOOSER_ACTION_SAVE);
497         dialog.set_filename (X_("templates.tar.xz"));
498
499         dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
500         dialog.add_button(Gtk::Stock::OK, Gtk::RESPONSE_OK);
501
502         FileFilter archive_filter;
503         archive_filter.add_pattern (X_("*.tar.xz"));
504         archive_filter.set_name (_("Template archives"));
505         dialog.add_filter (archive_filter);
506
507         int result = dialog.run ();
508
509         if (result != RESPONSE_OK || !dialog.get_filename().length()) {
510                 PBD::remove_directory (tmpdir);
511                 return;
512         }
513
514         string filename = dialog.get_filename ();
515         if (filename.compare (filename.size () - 7, 7, ".tar.xz")) {
516                 filename += ".tar.xz";
517         }
518
519         if (g_file_test (filename.c_str(), G_FILE_TEST_EXISTS)) {
520                 ArdourDialog dlg (_("File exists"), true);
521                 Label msg (string_compose (_("The file %1 already exists."), filename));
522                 dlg.get_vbox()->pack_start (msg);
523                 msg.show ();
524                 dlg.add_button (_("Overwrite"), RESPONSE_ACCEPT);
525                 dlg.add_button (_("Cancel"), RESPONSE_REJECT);
526                 dlg.set_default_response (RESPONSE_REJECT);
527
528                 result = dlg.run ();
529
530                 if (result == RESPONSE_REJECT) {
531                         PBD::remove_directory (tmpdir);
532                         return;
533                 }
534         }
535
536         PBD::copy_recurse (templates_dir (), Glib::build_filename (tmpdir, Glib::path_get_basename (templates_dir ())));
537
538         vector<string> files;
539         PBD::find_files_matching_regex (files, tmpdir, string ("\\.template$"), /* recurse = */ true);
540
541         vector<string>::const_iterator it;
542         for (it = files.begin(); it != files.end(); ++it) {
543                 const string bn = PBD::basename_nosuffix (*it);
544                 const string old_path = Glib::build_filename (templates_dir (), bn);
545                 const string new_path = Glib::build_filename ("$TEMPLATEDIR", bn);
546
547                 XMLTree tree;
548                 if (!tree.read (*it)) {
549                         continue;
550                 }
551                 if (adjust_xml_tree (tree, old_path, new_path)) {
552                         tree.write (*it);
553                 }
554         }
555
556         find_files_matching_filter (files, tmpdir, accept_all_files, 0, false, true, true);
557
558         std::map<std::string, std::string> filemap;
559         for (it = files.begin(); it != files.end(); ++it) {
560                 filemap[*it] = it->substr (tmpdir.size()+1, it->size() - tmpdir.size() - 1);
561         }
562
563         _current_action = _("Exporting templates");
564
565         PBD::FileArchive ar (filename);
566         PBD::ScopedConnectionList progress_connection;
567         ar.progress.connect_same_thread (progress_connection, boost::bind (&_set_progress, this, _1, _2));
568         ar.create (filemap);
569
570         PBD::remove_directory (tmpdir);
571 }
572
573 void
574 TemplateManager::import_template_set ()
575 {
576         FileChooserDialog dialog (_("Import template archives"));
577         dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
578         dialog.add_button(Gtk::Stock::OK, Gtk::RESPONSE_OK);
579
580         FileFilter archive_filter;
581         archive_filter.add_pattern (X_("*.tar.xz"));
582         archive_filter.set_name (_("Template archives"));
583         dialog.add_filter (archive_filter);
584
585         int result = dialog.run ();
586
587         if (result != RESPONSE_OK || !dialog.get_filename().length()) {
588                 return;
589         }
590
591         _current_action = _("Importing templates");
592
593         FileArchive ar (dialog.get_filename ());
594         PBD::ScopedConnectionList progress_connection;
595         ar.progress.connect_same_thread (progress_connection, boost::bind (&_set_progress, this, _1, _2));
596         ar.inflate (user_config_directory ());
597
598         vector<string> files;
599         PBD::find_files_matching_regex (files, templates_dir (), string ("\\.template$"), /* recurse = */ true);
600
601         vector<string>::const_iterator it;
602         for (it = files.begin(); it != files.end(); ++it) {
603                 const string bn = PBD::basename_nosuffix (*it);
604                 const string old_path = Glib::build_filename ("$TEMPLATEDIR", bn);
605                 const string new_path = Glib::build_filename (templates_dir (), bn);
606
607                 XMLTree tree;
608                 if (!tree.read (*it)) {
609                         continue;
610                 }
611                 if (adjust_xml_tree (tree, old_path, new_path)) {
612                         tree.write (*it);
613                 }
614         }
615
616         init ();
617         TemplatesImported (); /* emit signal */
618 }
619
620 bool
621 TemplateManager::adjust_plugin_paths (XMLNode* node, const string& name, const string& new_name) const
622 {
623         bool adjusted = false;
624
625         const XMLNodeList& procs = node->children (X_("Processor"));
626         XMLNodeConstIterator pit;
627         for (pit = procs.begin(); pit != procs.end(); ++pit) {
628                 XMLNode* lv2_node = (*pit)->child (X_("lv2"));
629                 if (!lv2_node) {
630                         continue;
631                 }
632                 string template_dir;
633
634                 if (!lv2_node->get_property (X_("template-dir"), template_dir)) {
635                         continue;
636                 }
637
638                 const int suffix_pos = template_dir.size() - name.size();
639                 if (suffix_pos < 0) {
640                         cerr << "Template name\"" << name << "\" longer than template-dir \"" << template_dir << "\", WTH?" << endl;
641                         continue;
642                 }
643
644                 if (template_dir.compare (suffix_pos, template_dir.size(), name)) {
645                         cerr << "Template name \"" << name << "\" no suffix of template-dir \"" << template_dir << "\"" << endl;
646                         continue;
647                 }
648
649                 const string new_template_dir = template_dir.substr (0, suffix_pos) + new_name;
650                 lv2_node->set_property (X_("template-dir"), new_template_dir);
651
652                 adjusted = true;
653         }
654
655         return adjusted;
656 }
657
658 void
659 TemplateManager::update_progress_gui (float p)
660 {
661         if (p >= 1.0) {
662                 _progress_bar.hide ();
663                 return;
664         }
665
666         _progress_bar.show ();
667         _progress_bar.set_text (_current_action);
668         _progress_bar.set_fraction (p);
669 }
670
671 void
672 SessionTemplateManager::get_templates (vector<TemplateInfo>& templates) const
673 {
674         find_session_templates (templates, /* read_xml = */ true);
675 }
676
677 void RouteTemplateManager::get_templates (vector<TemplateInfo>& templates) const
678 {
679         find_route_templates (templates);
680 }
681
682 #include <cerrno>
683
684 void
685 SessionTemplateManager::rename_template (TreeModel::iterator& item, const Glib::ustring& new_name_)
686 {
687         const string old_path = item->get_value (_template_columns.path);
688         const string old_name = item->get_value (_template_columns.name);
689         const string new_name = string (new_name_);
690
691         const string old_file_old_path = Glib::build_filename (old_path, old_name+".template");
692
693         XMLTree tree;
694
695         if (!tree.read(old_file_old_path)) {
696                 error << string_compose (_("Could not parse template file \"%1\"."), old_file_old_path) << endmsg;
697                 return;
698         }
699         XMLNode* root = tree.root();
700
701         const XMLNode* const routes_node = root->child (X_("Routes"));
702         if (routes_node) {
703                 const XMLNodeList& routes = routes_node->children (X_("Route"));
704                 XMLNodeConstIterator rit;
705                 for (rit = routes.begin(); rit != routes.end(); ++rit) {
706                         adjust_plugin_paths (*rit, old_name, new_name);
707                 }
708         }
709
710         const string new_file_old_path = Glib::build_filename (old_path, new_name+".template");
711
712         tree.set_filename (new_file_old_path);
713
714         if (!tree.write ()) {
715                 error << string_compose(_("Could not write to new template file \"%1\"."), new_file_old_path);
716                 return;
717         }
718
719         const string new_path = Glib::build_filename (user_template_directory (), new_name);
720
721         if (g_rename (old_path.c_str(), new_path.c_str()) != 0) {
722                 error << string_compose (_("Could not rename template directory from \"%1\" to \"%2\": %3"),
723                                          old_path, new_path, strerror (errno)) << endmsg;
724                 g_unlink (new_file_old_path.c_str());
725                 return;
726         }
727
728         const string old_file_new_path = Glib::build_filename (new_path, old_name+".template");
729         if (g_unlink (old_file_new_path.c_str())) {
730                 error << string_compose (X_("Could not delete old template file \"%1\": %2"),
731                                          old_file_new_path, strerror (errno)) << endmsg;
732         }
733
734         item->set_value (_template_columns.name, new_name);
735         item->set_value (_template_columns.path, new_path);
736 }
737
738 void
739 SessionTemplateManager::delete_selected_template ()
740 {
741         if (!_current_selection) {
742                 return;
743         }
744
745         PBD::remove_directory (_current_selection->get_value (_template_columns.path));
746
747         _template_model->erase (_current_selection);
748         _current_selection = TreeIter ();
749         row_selection_changed ();
750 }
751
752 string
753 SessionTemplateManager::templates_dir () const
754 {
755         return user_template_directory ();
756 }
757
758
759 string
760 SessionTemplateManager::template_file (const TreeModel::const_iterator& item) const
761 {
762         const string path = item->get_value (_template_columns.path);
763         const string name = item->get_value (_template_columns.name);
764         return Glib::build_filename (path, name+".template");
765 }
766
767 bool
768 SessionTemplateManager::adjust_xml_tree (XMLTree& tree, const std::string& old_name, const std::string& new_name) const
769 {
770         bool adjusted = false;
771         XMLNode* root = tree.root();
772
773         const XMLNode* const routes_node = root->child (X_("Routes"));
774         if (routes_node) {
775                 const XMLNodeList& routes = routes_node->children (X_("Route"));
776                 XMLNodeConstIterator rit;
777                 for (rit = routes.begin(); rit != routes.end(); ++rit) {
778                         if (adjust_plugin_paths (*rit, old_name, new_name)) {
779                                 adjusted = true;
780                         }
781                 }
782         }
783
784         return adjusted;
785 }
786
787
788 void
789 RouteTemplateManager::rename_template (TreeModel::iterator& item, const Glib::ustring& new_name)
790 {
791         const string old_name = item->get_value (_template_columns.name);
792         const string old_filepath = item->get_value (_template_columns.path);
793         const string new_filepath = Glib::build_filename (user_route_template_directory(), new_name+".template");
794
795         XMLTree tree;
796         if (!tree.read (old_filepath)) {
797                 error << string_compose (_("Could not parse template file \"%1\"."), old_filepath) << endmsg;
798                 return;
799         }
800         tree.root()->set_property (X_("name"), new_name);
801         tree.root()->children().front()->set_property (X_("name"), new_name);
802
803         const bool adjusted = adjust_plugin_paths (tree.root(), old_name, string (new_name));
804
805         const string old_state_dir = Glib::build_filename (user_route_template_directory(), old_name);
806         const string new_state_dir = Glib::build_filename (user_route_template_directory(), new_name);
807
808         if (adjusted) {
809                 if (g_file_test (old_state_dir.c_str(), G_FILE_TEST_EXISTS)) {
810                         if (g_rename (old_state_dir.c_str(), new_state_dir.c_str()) != 0) {
811                                 error << string_compose (_("Could not rename state dir \"%1\" to \"%22\": %3"), old_state_dir, new_state_dir, strerror (errno)) << endmsg;
812                                 return;
813                         }
814                 }
815         }
816
817         tree.set_filename (new_filepath);
818
819         if (!tree.write ()) {
820                 error << string_compose(_("Could not write new template file \"%1\"."), new_filepath) << endmsg;
821                 if (adjusted) {
822                         g_rename (new_state_dir.c_str(), old_state_dir.c_str());
823                 }
824                 return;
825         }
826
827         if (g_unlink (old_filepath.c_str()) != 0) {
828                 error << string_compose (_("Could not remove old template file \"%1\": %2"), old_filepath, strerror (errno)) << endmsg;
829         }
830
831         item->set_value (_template_columns.name, string (new_name));
832         item->set_value (_template_columns.path, new_filepath);
833 }
834
835 void
836 RouteTemplateManager::delete_selected_template ()
837 {
838         if (!_current_selection) {
839                 return;
840         }
841
842         const string file_path = _current_selection->get_value (_template_columns.path);
843
844         if (g_unlink (file_path.c_str()) != 0) {
845                 error << string_compose(_("Could not delete template file \"%1\": %2"), file_path, strerror (errno)) << endmsg;
846                 return;
847         }
848         PBD::remove_directory (Glib::build_filename (user_route_template_directory (),
849                                                      _current_selection->get_value (_template_columns.name)));
850
851         _template_model->erase (_current_selection);
852         row_selection_changed ();
853 }
854
855 string
856 RouteTemplateManager::templates_dir () const
857 {
858         return user_route_template_directory ();
859 }
860
861
862 string
863 RouteTemplateManager::template_file (const TreeModel::const_iterator& item) const
864 {
865         return item->get_value (_template_columns.path);
866 }
867
868 bool
869 RouteTemplateManager::adjust_xml_tree (XMLTree& tree, const std::string& old_name, const std::string& new_name) const
870 {
871         return adjust_plugin_paths (tree.root(), old_name, string (new_name));
872 }