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