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