TemplateDialog: Lable the RESPONSE_OK button "Done" rather than "Ok"
[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         const string desc_txt = _description_editor.get_buffer()->get_text ();
424         _current_selection->set_value (_template_columns.description, desc_txt);
425
426         XMLTree tree;
427
428         if (!tree.read(file_path)) {
429                 error << string_compose (_("Could not parse template file \"%1\"."), file_path) << endmsg;
430                 return;
431         }
432
433         tree.root()->remove_nodes (X_("description"));
434         XMLNode* desc = new XMLNode (X_("description"));
435
436         XMLNode* dn = new XMLNode (X_("content"), desc_txt);
437         desc->add_child_nocopy (*dn);
438
439         tree.root()->add_child_nocopy (*desc);
440
441         if (!tree.write ()) {
442                 error << string_compose(X_("Could not write to template file \"%1\"."), file_path) << endmsg;
443                 return;
444         }
445
446         _save_desc.set_sensitive (false);
447         _desc_dirty = false;
448 }
449
450 bool
451 TemplateManager::key_event (GdkEventKey* ev)
452 {
453         if (ev->keyval == GDK_KEY_F2) {
454                 start_edit ();
455                 return true;
456         }
457         if (ev->keyval == GDK_KEY_Delete) {
458                 delete_selected_template ();
459                 return true;
460         }
461
462         return false;
463 }
464
465 static
466 bool accept_all_files (string const &, void *)
467 {
468         return true;
469 }
470
471 static void _set_progress (Progress* p, size_t n, size_t t)
472 {
473         p->set_progress (float (n) / float(t));
474 }
475
476
477 void
478 TemplateManager::export_all_templates ()
479 {
480         GError* err = NULL;
481         char* td = g_dir_make_tmp ("ardour-templates-XXXXXX", &err);
482
483         if (!td) {
484                 error << string_compose(_("Could not make tmpdir: %1"), err->message) << endmsg;
485                 return;
486         }
487         const string tmpdir (td);
488         g_free (td);
489         g_clear_error (&err);
490
491         FileChooserDialog dialog(_("Save Exported Template Archive"), FILE_CHOOSER_ACTION_SAVE);
492         dialog.set_filename (X_("templates.tar.xz"));
493
494         dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
495         dialog.add_button(Gtk::Stock::OK, Gtk::RESPONSE_OK);
496
497         FileFilter archive_filter;
498         archive_filter.add_pattern (X_("*.tar.xz"));
499         archive_filter.set_name (_("Template archives"));
500         dialog.add_filter (archive_filter);
501
502         int result = dialog.run ();
503
504         if (result != RESPONSE_OK || !dialog.get_filename().length()) {
505                 PBD::remove_directory (tmpdir);
506                 return;
507         }
508
509         string filename = dialog.get_filename ();
510         if (filename.compare (filename.size () - 7, 7, ".tar.xz")) {
511                 filename += ".tar.xz";
512         }
513
514         if (g_file_test (filename.c_str(), G_FILE_TEST_EXISTS)) {
515                 ArdourDialog dlg (_("File exists"), true);
516                 Label msg (string_compose (_("The file %1 already exists."), filename));
517                 dlg.get_vbox()->pack_start (msg);
518                 msg.show ();
519                 dlg.add_button (_("Overwrite"), RESPONSE_ACCEPT);
520                 dlg.add_button (_("Cancel"), RESPONSE_REJECT);
521                 dlg.set_default_response (RESPONSE_REJECT);
522
523                 result = dlg.run ();
524
525                 if (result == RESPONSE_REJECT) {
526                         PBD::remove_directory (tmpdir);
527                         return;
528                 }
529         }
530
531         PBD::copy_recurse (templates_dir (), Glib::build_filename (tmpdir, Glib::path_get_basename (templates_dir ())));
532
533         vector<string> files;
534         PBD::find_files_matching_regex (files, tmpdir, string ("\\.template$"), /* recurse = */ true);
535
536         vector<string>::const_iterator it;
537         for (it = files.begin(); it != files.end(); ++it) {
538                 const string bn = PBD::basename_nosuffix (*it);
539                 const string old_path = Glib::build_filename (templates_dir (), bn);
540                 const string new_path = Glib::build_filename ("$TEMPLATEDIR", bn);
541
542                 XMLTree tree;
543                 if (!tree.read (*it)) {
544                         continue;
545                 }
546                 if (adjust_xml_tree (tree, old_path, new_path)) {
547                         tree.write (*it);
548                 }
549         }
550
551         find_files_matching_filter (files, tmpdir, accept_all_files, 0, false, true, true);
552
553         std::map<std::string, std::string> filemap;
554         for (it = files.begin(); it != files.end(); ++it) {
555                 filemap[*it] = it->substr (tmpdir.size()+1, it->size() - tmpdir.size() - 1);
556         }
557
558         _current_action = _("Exporting templates");
559
560         PBD::FileArchive ar (filename);
561         PBD::ScopedConnectionList progress_connection;
562         ar.progress.connect_same_thread (progress_connection, boost::bind (&_set_progress, this, _1, _2));
563         ar.create (filemap);
564
565         PBD::remove_directory (tmpdir);
566 }
567
568 void
569 TemplateManager::import_template_set ()
570 {
571         FileChooserDialog dialog (_("Import template archives"));
572         dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
573         dialog.add_button(Gtk::Stock::OK, Gtk::RESPONSE_OK);
574
575         FileFilter archive_filter;
576         archive_filter.add_pattern (X_("*.tar.xz"));
577         archive_filter.set_name (_("Template archives"));
578         dialog.add_filter (archive_filter);
579
580         int result = dialog.run ();
581
582         if (result != RESPONSE_OK || !dialog.get_filename().length()) {
583                 return;
584         }
585
586         _current_action = _("Importing templates");
587
588         FileArchive ar (dialog.get_filename ());
589         PBD::ScopedConnectionList progress_connection;
590         ar.progress.connect_same_thread (progress_connection, boost::bind (&_set_progress, this, _1, _2));
591         ar.inflate (user_config_directory ());
592
593         vector<string> files;
594         PBD::find_files_matching_regex (files, templates_dir (), string ("\\.template$"), /* recurse = */ true);
595
596         vector<string>::const_iterator it;
597         for (it = files.begin(); it != files.end(); ++it) {
598                 const string bn = PBD::basename_nosuffix (*it);
599                 const string old_path = Glib::build_filename ("$TEMPLATEDIR", bn);
600                 const string new_path = Glib::build_filename (templates_dir (), bn);
601
602                 XMLTree tree;
603                 if (!tree.read (*it)) {
604                         continue;
605                 }
606                 if (adjust_xml_tree (tree, old_path, new_path)) {
607                         tree.write (*it);
608                 }
609         }
610
611         init ();
612         TemplatesImported (); /* emit signal */
613 }
614
615 bool
616 TemplateManager::adjust_plugin_paths (XMLNode* node, const string& name, const string& new_name) const
617 {
618         bool adjusted = false;
619
620         const XMLNodeList& procs = node->children (X_("Processor"));
621         XMLNodeConstIterator pit;
622         for (pit = procs.begin(); pit != procs.end(); ++pit) {
623                 XMLNode* lv2_node = (*pit)->child (X_("lv2"));
624                 if (!lv2_node) {
625                         continue;
626                 }
627                 string template_dir;
628
629                 if (!lv2_node->get_property (X_("template-dir"), template_dir)) {
630                         continue;
631                 }
632
633                 const int suffix_pos = template_dir.size() - name.size();
634                 if (suffix_pos < 0) {
635                         cerr << "Template name\"" << name << "\" longer than template-dir \"" << template_dir << "\", WTH?" << endl;
636                         continue;
637                 }
638
639                 if (template_dir.compare (suffix_pos, template_dir.size(), name)) {
640                         cerr << "Template name \"" << name << "\" no suffix of template-dir \"" << template_dir << "\"" << endl;
641                         continue;
642                 }
643
644                 const string new_template_dir = template_dir.substr (0, suffix_pos) + new_name;
645                 lv2_node->set_property (X_("template-dir"), new_template_dir);
646
647                 adjusted = true;
648         }
649
650         return adjusted;
651 }
652
653 void
654 TemplateManager::update_progress_gui (float p)
655 {
656         if (p >= 1.0) {
657                 _progress_bar.hide ();
658                 return;
659         }
660
661         _progress_bar.show ();
662         _progress_bar.set_text (_current_action);
663         _progress_bar.set_fraction (p);
664 }
665
666 void
667 SessionTemplateManager::get_templates (vector<TemplateInfo>& templates) const
668 {
669         find_session_templates (templates, /* read_xml = */ true);
670 }
671
672 void RouteTemplateManager::get_templates (vector<TemplateInfo>& templates) const
673 {
674         find_route_templates (templates);
675 }
676
677 #include <cerrno>
678
679 void
680 SessionTemplateManager::rename_template (TreeModel::iterator& item, const Glib::ustring& new_name_)
681 {
682         const string old_path = item->get_value (_template_columns.path);
683         const string old_name = item->get_value (_template_columns.name);
684         const string new_name = string (new_name_);
685
686         const string old_file_old_path = Glib::build_filename (old_path, old_name+".template");
687
688         XMLTree tree;
689
690         if (!tree.read(old_file_old_path)) {
691                 error << string_compose (_("Could not parse template file \"%1\"."), old_file_old_path) << endmsg;
692                 return;
693         }
694         XMLNode* root = tree.root();
695
696         const XMLNode* const routes_node = root->child (X_("Routes"));
697         if (routes_node) {
698                 const XMLNodeList& routes = routes_node->children (X_("Route"));
699                 XMLNodeConstIterator rit;
700                 for (rit = routes.begin(); rit != routes.end(); ++rit) {
701                         adjust_plugin_paths (*rit, old_name, new_name);
702                 }
703         }
704
705         const string new_file_old_path = Glib::build_filename (old_path, new_name+".template");
706
707         tree.set_filename (new_file_old_path);
708
709         if (!tree.write ()) {
710                 error << string_compose(_("Could not write to new template file \"%1\"."), new_file_old_path);
711                 return;
712         }
713
714         const string new_path = Glib::build_filename (user_template_directory (), new_name);
715
716         if (g_rename (old_path.c_str(), new_path.c_str()) != 0) {
717                 error << string_compose (_("Could not rename template directory from \"%1\" to \"%2\": %3"),
718                                          old_path, new_path, strerror (errno)) << endmsg;
719                 g_unlink (new_file_old_path.c_str());
720                 return;
721         }
722
723         const string old_file_new_path = Glib::build_filename (new_path, old_name+".template");
724         if (g_unlink (old_file_new_path.c_str())) {
725                 error << string_compose (X_("Could not delete old template file \"%1\": %2"),
726                                          old_file_new_path, strerror (errno)) << endmsg;
727         }
728
729         item->set_value (_template_columns.name, new_name);
730         item->set_value (_template_columns.path, new_path);
731 }
732
733 void
734 SessionTemplateManager::delete_selected_template ()
735 {
736         if (!_current_selection) {
737                 return;
738         }
739
740         PBD::remove_directory (_current_selection->get_value (_template_columns.path));
741
742         _template_model->erase (_current_selection);
743         _current_selection = TreeIter ();
744         row_selection_changed ();
745 }
746
747 string
748 SessionTemplateManager::templates_dir () const
749 {
750         return user_template_directory ();
751 }
752
753
754 string
755 SessionTemplateManager::template_file (const TreeModel::const_iterator& item) const
756 {
757         const string path = item->get_value (_template_columns.path);
758         const string name = item->get_value (_template_columns.name);
759         return Glib::build_filename (path, name+".template");
760 }
761
762 bool
763 SessionTemplateManager::adjust_xml_tree (XMLTree& tree, const std::string& old_name, const std::string& new_name) const
764 {
765         bool adjusted = false;
766         XMLNode* root = tree.root();
767
768         const XMLNode* const routes_node = root->child (X_("Routes"));
769         if (routes_node) {
770                 const XMLNodeList& routes = routes_node->children (X_("Route"));
771                 XMLNodeConstIterator rit;
772                 for (rit = routes.begin(); rit != routes.end(); ++rit) {
773                         if (adjust_plugin_paths (*rit, old_name, new_name)) {
774                                 adjusted = true;
775                         }
776                 }
777         }
778
779         return adjusted;
780 }
781
782
783 void
784 RouteTemplateManager::rename_template (TreeModel::iterator& item, const Glib::ustring& new_name)
785 {
786         const string old_name = item->get_value (_template_columns.name);
787         const string old_filepath = item->get_value (_template_columns.path);
788         const string new_filepath = Glib::build_filename (user_route_template_directory(), new_name+".template");
789
790         XMLTree tree;
791         if (!tree.read (old_filepath)) {
792                 error << string_compose (_("Could not parse template file \"%1\"."), old_filepath) << endmsg;
793                 return;
794         }
795         tree.root()->set_property (X_("name"), new_name);
796         tree.root()->children().front()->set_property (X_("name"), new_name);
797
798         const bool adjusted = adjust_plugin_paths (tree.root(), old_name, string (new_name));
799
800         const string old_state_dir = Glib::build_filename (user_route_template_directory(), old_name);
801         const string new_state_dir = Glib::build_filename (user_route_template_directory(), new_name);
802
803         if (adjusted) {
804                 if (g_file_test (old_state_dir.c_str(), G_FILE_TEST_EXISTS)) {
805                         if (g_rename (old_state_dir.c_str(), new_state_dir.c_str()) != 0) {
806                                 error << string_compose (_("Could not rename state dir \"%1\" to \"%22\": %3"), old_state_dir, new_state_dir, strerror (errno)) << endmsg;
807                                 return;
808                         }
809                 }
810         }
811
812         tree.set_filename (new_filepath);
813
814         if (!tree.write ()) {
815                 error << string_compose(_("Could not write new template file \"%1\"."), new_filepath) << endmsg;
816                 if (adjusted) {
817                         g_rename (new_state_dir.c_str(), old_state_dir.c_str());
818                 }
819                 return;
820         }
821
822         if (g_unlink (old_filepath.c_str()) != 0) {
823                 error << string_compose (_("Could not remove old template file \"%1\": %2"), old_filepath, strerror (errno)) << endmsg;
824         }
825
826         item->set_value (_template_columns.name, string (new_name));
827         item->set_value (_template_columns.path, new_filepath);
828 }
829
830 void
831 RouteTemplateManager::delete_selected_template ()
832 {
833         if (!_current_selection) {
834                 return;
835         }
836
837         const string file_path = _current_selection->get_value (_template_columns.path);
838
839         if (g_unlink (file_path.c_str()) != 0) {
840                 error << string_compose(_("Could not delete template file \"%1\": %2"), file_path, strerror (errno)) << endmsg;
841                 return;
842         }
843         PBD::remove_directory (Glib::build_filename (user_route_template_directory (),
844                                                      _current_selection->get_value (_template_columns.name)));
845
846         _template_model->erase (_current_selection);
847         row_selection_changed ();
848 }
849
850 string
851 RouteTemplateManager::templates_dir () const
852 {
853         return user_route_template_directory ();
854 }
855
856
857 string
858 RouteTemplateManager::template_file (const TreeModel::const_iterator& item) const
859 {
860         return item->get_value (_template_columns.path);
861 }
862
863 bool
864 RouteTemplateManager::adjust_xml_tree (XMLTree& tree, const std::string& old_name, const std::string& new_name) const
865 {
866         return adjust_plugin_paths (tree.root(), old_name, string (new_name));
867 }