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