mp4chaps Lua script: don't clutter global environment
[ardour.git] / gtk2_ardour / template_dialog.cc
1 /*
2     Copyright (C) 2010 Paul Davis
3     Author: Johannes Mueller
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19 */
20
21 #include <map>
22 #include <vector>
23 #include <cerrno>
24
25 #include <glib/gstdio.h>
26
27 #include <gtkmm/filechooserdialog.h>
28 #include <gtkmm/frame.h>
29 #include <gtkmm/liststore.h>
30 #include <gtkmm/notebook.h>
31 #include <gtkmm/progressbar.h>
32 #include <gtkmm/separator.h>
33 #include <gtkmm/scrolledwindow.h>
34 #include <gtkmm/stock.h>
35 #include <gtkmm/textview.h>
36 #include <gtkmm/treeiter.h>
37 #include <gtkmm/treeview.h>
38
39 #include "pbd/basename.h"
40 #include "pbd/error.h"
41 #include "pbd/file_archive.h"
42 #include "pbd/file_utils.h"
43 #include "pbd/i18n.h"
44 #include "pbd/xml++.h"
45
46 #include "gtkmm2ext/gui_thread.h"
47
48 #include "ardour/filesystem_paths.h"
49 #include "ardour/template_utils.h"
50
51 #include "progress_reporter.h"
52
53 #include "template_dialog.h"
54
55 using namespace std;
56 using namespace Gtk;
57 using namespace PBD;
58 using namespace ARDOUR;
59
60 class TemplateManager : public Gtk::HBox,
61                         public ProgressReporter
62 {
63 public:
64         virtual ~TemplateManager () {}
65
66         virtual void init () = 0;
67         void handle_dirty_description ();
68
69         PBD::Signal0<void> TemplatesImported;
70
71 protected:
72         TemplateManager ();
73
74         Gtk::TextView _description_editor;
75         Gtk::Button _save_desc;
76
77         void setup_model (const std::vector<ARDOUR::TemplateInfo>& templates);
78
79         void row_selection_changed ();
80
81         virtual void delete_selected_template () = 0;
82         bool adjust_plugin_paths (XMLNode* node, const std::string& name, const std::string& new_name) const;
83
84         struct SessionTemplateColumns : public Gtk::TreeModel::ColumnRecord {
85                 SessionTemplateColumns () {
86                         add (name);
87                         add (path);
88                         add (description);
89                 }
90
91                 Gtk::TreeModelColumn<std::string> name;
92                 Gtk::TreeModelColumn<std::string> path;
93                 Gtk::TreeModelColumn<std::string> description;
94         };
95
96         Glib::RefPtr<Gtk::ListStore>  _template_model;
97         SessionTemplateColumns _template_columns;
98
99         Gtk::TreeModel::const_iterator _current_selection;
100
101         Gtk::ProgressBar _progress_bar;
102         std::string _current_action;
103
104 private:
105         void render_template_names (Gtk::CellRenderer* rnd, const Gtk::TreeModel::iterator& it);
106         void validate_edit (const Glib::ustring& path_string, const Glib::ustring& new_name);
107         void start_edit ();
108
109         void set_desc_dirty ();
110
111         bool key_event (GdkEventKey* ev);
112
113         virtual void get_templates (vector<TemplateInfo>& templates) const = 0;
114
115         virtual void rename_template (Gtk::TreeModel::iterator& item, const Glib::ustring& new_name) = 0;
116
117         virtual void save_template_desc ();
118
119         void export_all_templates ();
120         void import_template_set ();
121
122         virtual std::string templates_dir () const = 0;
123         virtual std::string template_file (const Gtk::TreeModel::const_iterator& item) const = 0;
124
125         virtual bool adjust_xml_tree (XMLTree& tree, const std::string& old_name, const std::string& new_name) const = 0;
126
127         Gtk::TreeView _template_treeview;
128         Gtk::CellRendererText _validating_cellrenderer;
129         Gtk::TreeView::Column _validated_column;
130
131         bool _desc_dirty;
132
133         Gtk::Button _remove_button;
134         Gtk::Button _rename_button;
135
136         Gtk::Button _export_all_templates_button;
137         Gtk::Button _import_template_set_button;
138
139         sigc::connection _cursor_changed_connection;
140
141         void update_progress_gui (float p);
142 };
143
144 class SessionTemplateManager : public TemplateManager
145 {
146 public:
147         SessionTemplateManager () : TemplateManager () {}
148         ~SessionTemplateManager () {}
149
150         void init ();
151
152         void get_templates (vector<TemplateInfo>& templates) const;
153
154 private:
155         void rename_template (Gtk::TreeModel::iterator& item, const Glib::ustring& new_name);
156         void delete_selected_template ();
157
158         std::string templates_dir () const;
159         std::string template_file (const Gtk::TreeModel::const_iterator& item) const;
160
161         bool adjust_xml_tree (XMLTree& tree, const std::string& old_name, const std::string& new_name) const;
162 };
163
164
165 class RouteTemplateManager : public TemplateManager
166 {
167 public:
168         RouteTemplateManager () : TemplateManager () {}
169         ~RouteTemplateManager () {}
170
171         void init ();
172
173         void get_templates (vector<TemplateInfo>& templates) const;
174
175 private:
176         void rename_template (Gtk::TreeModel::iterator& item, const Glib::ustring& new_name);
177         void delete_selected_template ();
178
179         std::string templates_dir () const;
180         std::string template_file (const Gtk::TreeModel::const_iterator& item) const;
181
182         bool adjust_xml_tree (XMLTree& tree, const std::string& old_name, const std::string& new_name) const;
183 };
184
185
186
187 TemplateDialog::TemplateDialog ()
188         : ArdourDialog ("Manage Templates")
189 {
190         Notebook* nb = manage (new Notebook);
191
192         SessionTemplateManager* session_tm = manage (new SessionTemplateManager);
193         nb->append_page (*session_tm, _("Session Templates"));
194
195         RouteTemplateManager* route_tm = manage (new RouteTemplateManager);
196         nb->append_page (*route_tm, _("Track Templates"));
197
198         get_vbox()->pack_start (*nb);
199         add_button (_("Done"), Gtk::RESPONSE_OK);
200
201         get_vbox()->show_all();
202
203         session_tm->init ();
204         route_tm->init ();
205
206         session_tm->TemplatesImported.connect (*this, invalidator (*this), boost::bind (&RouteTemplateManager::init, route_tm), gui_context ());
207         route_tm->TemplatesImported.connect (*this, invalidator (*this), boost::bind (&SessionTemplateManager::init, session_tm), gui_context ());
208
209         signal_hide().connect (sigc::mem_fun (session_tm, &TemplateManager::handle_dirty_description));
210         signal_hide().connect (sigc::mem_fun (route_tm, &TemplateManager::handle_dirty_description));
211         nb->signal_switch_page().connect (sigc::hide (sigc::hide (sigc::mem_fun (session_tm, &TemplateManager::handle_dirty_description))));
212         nb->signal_switch_page().connect (sigc::hide (sigc::hide (sigc::mem_fun (route_tm, &TemplateManager::handle_dirty_description))));
213 }
214
215 TemplateManager::TemplateManager ()
216         : HBox ()
217         , ProgressReporter ()
218         , _save_desc (_("Save Description"))
219         , _desc_dirty (false)
220         , _remove_button (_("Remove"))
221         , _rename_button (_("Rename"))
222         , _export_all_templates_button (_("Export all"))
223         , _import_template_set_button (_("Import"))
224 {
225         _template_model = ListStore::create (_template_columns);
226         _template_treeview.set_model (_template_model);
227
228         _validated_column.set_title (_("Template Name"));
229         _validated_column.pack_start (_validating_cellrenderer);
230         _template_treeview.append_column (_validated_column);
231         _validating_cellrenderer.property_editable() = true;
232
233         _validated_column.set_cell_data_func (_validating_cellrenderer, sigc::mem_fun (*this, &TemplateManager::render_template_names));
234         _validating_cellrenderer.signal_edited().connect (sigc::mem_fun (*this, &TemplateManager::validate_edit));
235         _cursor_changed_connection = _template_treeview.signal_cursor_changed().connect (sigc::mem_fun (*this, &TemplateManager::row_selection_changed));
236         _template_treeview.signal_key_press_event().connect (sigc::mem_fun (*this, &TemplateManager::key_event));
237
238         ScrolledWindow* sw = manage (new ScrolledWindow);
239         sw->property_hscrollbar_policy() = POLICY_AUTOMATIC;
240         sw->add (_template_treeview);
241         sw->set_size_request (300, 200);
242
243         VBox* vb_btns = manage (new VBox);
244         vb_btns->set_spacing (4);
245         vb_btns->pack_start (_rename_button, false, false);
246         vb_btns->pack_start (_remove_button, false, false);
247         vb_btns->pack_start (_save_desc, false, false);
248
249         _rename_button.set_sensitive (false);
250         _rename_button.signal_clicked().connect (sigc::mem_fun (*this, &TemplateManager::start_edit));
251         _remove_button.set_sensitive (false);
252         _remove_button.signal_clicked().connect (sigc::mem_fun (*this, &TemplateManager::delete_selected_template));
253
254         vb_btns->pack_start (*(manage (new VSeparator ())));
255
256         vb_btns->pack_start (_export_all_templates_button, false, false);
257         vb_btns->pack_start (_import_template_set_button, false, false);
258
259         _export_all_templates_button.set_sensitive (false);
260         _export_all_templates_button.signal_clicked().connect (sigc::mem_fun (*this, &TemplateManager::export_all_templates));
261
262         _import_template_set_button.set_sensitive (true);
263         _import_template_set_button.signal_clicked().connect (sigc::mem_fun (*this, &TemplateManager::import_template_set));
264
265         set_spacing (6);
266
267         VBox* vb = manage (new VBox);
268         vb->pack_start (*sw);
269         vb->pack_start (_progress_bar);
270
271         Frame* desc_frame = manage (new Frame (_("Description")));
272
273         _description_editor.set_wrap_mode (Gtk::WRAP_WORD);
274         _description_editor.set_size_request (300,400);
275         _description_editor.set_border_width (6);
276
277         _save_desc.set_sensitive (false);
278         _save_desc.signal_clicked().connect (sigc::mem_fun (*this, &TemplateManager::save_template_desc));
279
280         _description_editor.get_buffer()->signal_changed().connect (sigc::mem_fun (*this, &TemplateManager::set_desc_dirty));
281
282         desc_frame->add (_description_editor);
283
284         pack_start (*vb);
285         pack_start (*desc_frame);
286         pack_start (*vb_btns);
287
288         show_all_children ();
289         _progress_bar.hide ();
290 }
291
292 void
293 TemplateManager::setup_model (const vector<TemplateInfo>& templates)
294 {
295         _template_model->clear ();
296
297         for (vector<TemplateInfo>::const_iterator it = templates.begin(); it != templates.end(); ++it) {
298                 TreeModel::Row row;
299                 row = *(_template_model->append ());
300
301                 row[_template_columns.name] = it->name;
302                 row[_template_columns.path] = it->path;
303                 row[_template_columns.description] = it->description;
304         }
305
306         _export_all_templates_button.set_sensitive (!templates.empty ());
307 }
308
309 void
310 TemplateManager::handle_dirty_description ()
311 {
312         if (_desc_dirty && _current_selection) {
313                 ArdourDialog dlg (_("Description not saved"), true);
314                 const string name = _current_selection->get_value (_template_columns.name);
315                 Label msg (string_compose (_("The discription of template \"%1\" has been modfied but has not been saved yet.\n"
316                                              "Do you want to save it?"), name));
317                 dlg.get_vbox()->pack_start (msg);
318                 msg.show ();
319                 dlg.add_button (_("Save"), RESPONSE_ACCEPT);
320                 dlg.add_button (_("Discard"), RESPONSE_REJECT);
321                 dlg.set_default_response (RESPONSE_REJECT);
322
323                 int response = dlg.run ();
324
325                 if (response == RESPONSE_ACCEPT) {
326                         save_template_desc ();
327                 } else {
328                         _description_editor.get_buffer()->set_text (_current_selection->get_value (_template_columns.description));
329                 }
330         }
331 }
332
333 void
334 TemplateManager::row_selection_changed ()
335 {
336         if (_current_selection) {
337                 handle_dirty_description ();
338         } else {
339                 _description_editor.get_buffer()->set_text ("");
340         }
341
342         _current_selection = _template_treeview.get_selection()->get_selected ();
343         if (_current_selection) {
344                 const string desc = _current_selection->get_value (_template_columns.description);
345                 _description_editor.get_buffer()->set_text (desc);
346         }
347
348         _desc_dirty = false;
349         _save_desc.set_sensitive (false);
350
351         _description_editor.set_sensitive (_current_selection);
352         _rename_button.set_sensitive (_current_selection);
353         _remove_button.set_sensitive (_current_selection);
354 }
355
356 void
357 TemplateManager::render_template_names (Gtk::CellRenderer*, const Gtk::TreeModel::iterator& it)
358 {
359         if (it) {
360                 _validating_cellrenderer.property_text () = it->get_value (_template_columns.name);
361         }
362 }
363
364 void
365 TemplateManager::validate_edit (const Glib::ustring& path_string, const Glib::ustring& new_name)
366 {
367         const TreePath path (path_string);
368         TreeModel::iterator current = _template_model->get_iter (path);
369
370         if (current->get_value (_template_columns.name) == new_name) {
371                 return;
372         }
373
374         TreeModel::Children rows = _template_model->children ();
375
376         bool found = false;
377         for (TreeModel::Children::const_iterator it = rows.begin(); it != rows.end(); ++it) {
378                 if (it->get_value (_template_columns.name) == new_name) {
379                         found = true;
380                         break;
381                 }
382         }
383
384         if (found) {
385                 error << string_compose (_("Template of name \"%1\" already exists"), new_name) << endmsg;
386                 return;
387         }
388
389
390         rename_template (current, new_name);
391 }
392
393 void
394 TemplateManager::start_edit ()
395 {
396         TreeModel::Path path;
397         TreeViewColumn* col;
398         _template_treeview.get_cursor (path, col);
399         _cursor_changed_connection.block ();
400         _template_treeview.set_cursor (path, *col, /*set_editing =*/ true);
401         _cursor_changed_connection.unblock ();
402 }
403
404 void
405 TemplateManager::set_desc_dirty ()
406 {
407         _desc_dirty = true;
408         _save_desc.set_sensitive (true);
409 }
410
411 void
412 TemplateManager::save_template_desc ()
413 {
414         const string file_path = template_file (_current_selection);
415
416         string desc_txt = _description_editor.get_buffer()->get_text ();
417         string::reverse_iterator wss = desc_txt.rbegin();
418         while (wss != desc_txt.rend() && isspace (*wss)) {
419                 desc_txt.erase (--(wss++).base());
420         }
421
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_and_delete (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 bool
464 accept_all_files (string const &, void *)
465 {
466         return true;
467 }
468
469 static void
470 _set_progress (Progress* p, size_t n, size_t t)
471 {
472         p->set_progress (float (n) / float(t));
473 }
474
475
476 void
477 TemplateManager::export_all_templates ()
478 {
479         GError* err = NULL;
480         char* td = g_dir_make_tmp ("ardour-templates-XXXXXX", &err);
481
482         if (!td) {
483                 error << string_compose(_("Could not make tmpdir: %1"), err->message) << endmsg;
484                 return;
485         }
486         const string tmpdir (td);
487         g_free (td);
488         g_clear_error (&err);
489
490         FileChooserDialog dialog(_("Save Exported Template Archive"), FILE_CHOOSER_ACTION_SAVE);
491         dialog.set_filename (X_("templates.tar.xz"));
492
493         dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
494         dialog.add_button(Gtk::Stock::OK, Gtk::RESPONSE_OK);
495
496         FileFilter archive_filter;
497         archive_filter.add_pattern (X_("*.tar.xz"));
498         archive_filter.set_name (_("Template archives"));
499         dialog.add_filter (archive_filter);
500
501         int result = dialog.run ();
502
503         if (result != RESPONSE_OK || !dialog.get_filename().length()) {
504                 PBD::remove_directory (tmpdir);
505                 return;
506         }
507
508         string filename = dialog.get_filename ();
509         if (filename.compare (filename.size () - 7, 7, ".tar.xz")) {
510                 filename += ".tar.xz";
511         }
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 (X_("*.tar.xz"));
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         const string old_file_old_path = Glib::build_filename (old_path, old_name+".template");
711
712         XMLTree tree;
713
714         if (!tree.read(old_file_old_path)) {
715                 error << string_compose (_("Could not parse template file \"%1\"."), old_file_old_path) << endmsg;
716                 return;
717         }
718         XMLNode* root = tree.root();
719
720         const XMLNode* const routes_node = root->child (X_("Routes"));
721         if (routes_node) {
722                 const XMLNodeList& routes = routes_node->children (X_("Route"));
723                 XMLNodeConstIterator rit;
724                 for (rit = routes.begin(); rit != routes.end(); ++rit) {
725                         adjust_plugin_paths (*rit, old_name, new_name);
726                 }
727         }
728
729         const string new_file_old_path = Glib::build_filename (old_path, new_name+".template");
730
731         tree.set_filename (new_file_old_path);
732
733         if (!tree.write ()) {
734                 error << string_compose(_("Could not write to new template file \"%1\"."), new_file_old_path);
735                 return;
736         }
737
738         const string new_path = Glib::build_filename (user_template_directory (), new_name);
739
740         if (g_rename (old_path.c_str(), new_path.c_str()) != 0) {
741                 error << string_compose (_("Could not rename template directory from \"%1\" to \"%2\": %3"),
742                                          old_path, new_path, strerror (errno)) << endmsg;
743                 g_unlink (new_file_old_path.c_str());
744                 return;
745         }
746
747         const string old_file_new_path = Glib::build_filename (new_path, old_name+".template");
748         if (g_unlink (old_file_new_path.c_str())) {
749                 error << string_compose (X_("Could not delete old template file \"%1\": %2"),
750                                          old_file_new_path, strerror (errno)) << endmsg;
751         }
752
753         item->set_value (_template_columns.name, new_name);
754         item->set_value (_template_columns.path, new_path);
755 }
756
757 void
758 SessionTemplateManager::delete_selected_template ()
759 {
760         if (!_current_selection) {
761                 return;
762         }
763
764         PBD::remove_directory (_current_selection->get_value (_template_columns.path));
765
766         _template_model->erase (_current_selection);
767         _current_selection = TreeIter ();
768         row_selection_changed ();
769 }
770
771 string
772 SessionTemplateManager::templates_dir () const
773 {
774         return user_template_directory ();
775 }
776
777
778 string
779 SessionTemplateManager::template_file (const TreeModel::const_iterator& item) const
780 {
781         const string path = item->get_value (_template_columns.path);
782         const string name = item->get_value (_template_columns.name);
783         return Glib::build_filename (path, name+".template");
784 }
785
786 bool
787 SessionTemplateManager::adjust_xml_tree (XMLTree& tree, const std::string& old_name, const std::string& new_name) const
788 {
789         bool adjusted = false;
790         XMLNode* root = tree.root();
791
792         const XMLNode* const routes_node = root->child (X_("Routes"));
793         if (routes_node) {
794                 const XMLNodeList& routes = routes_node->children (X_("Route"));
795                 XMLNodeConstIterator rit;
796                 for (rit = routes.begin(); rit != routes.end(); ++rit) {
797                         if (adjust_plugin_paths (*rit, old_name, new_name)) {
798                                 adjusted = true;
799                         }
800                 }
801         }
802
803         return adjusted;
804 }
805
806
807 void
808 RouteTemplateManager::rename_template (TreeModel::iterator& item, const Glib::ustring& new_name)
809 {
810         const string old_name = item->get_value (_template_columns.name);
811         const string old_filepath = item->get_value (_template_columns.path);
812         const string new_filepath = Glib::build_filename (user_route_template_directory(), new_name+".template");
813
814         XMLTree tree;
815         if (!tree.read (old_filepath)) {
816                 error << string_compose (_("Could not parse template file \"%1\"."), old_filepath) << endmsg;
817                 return;
818         }
819         tree.root()->set_property (X_("name"), new_name);
820         tree.root()->children().front()->set_property (X_("name"), new_name);
821
822         const bool adjusted = adjust_plugin_paths (tree.root(), old_name, string (new_name));
823
824         const string old_state_dir = Glib::build_filename (user_route_template_directory(), old_name);
825         const string new_state_dir = Glib::build_filename (user_route_template_directory(), new_name);
826
827         if (adjusted) {
828                 if (g_file_test (old_state_dir.c_str(), G_FILE_TEST_EXISTS)) {
829                         if (g_rename (old_state_dir.c_str(), new_state_dir.c_str()) != 0) {
830                                 error << string_compose (_("Could not rename state dir \"%1\" to \"%22\": %3"), old_state_dir, new_state_dir, strerror (errno)) << endmsg;
831                                 return;
832                         }
833                 }
834         }
835
836         tree.set_filename (new_filepath);
837
838         if (!tree.write ()) {
839                 error << string_compose(_("Could not write new template file \"%1\"."), new_filepath) << endmsg;
840                 if (adjusted) {
841                         g_rename (new_state_dir.c_str(), old_state_dir.c_str());
842                 }
843                 return;
844         }
845
846         if (g_unlink (old_filepath.c_str()) != 0) {
847                 error << string_compose (_("Could not remove old template file \"%1\": %2"), old_filepath, strerror (errno)) << endmsg;
848         }
849
850         item->set_value (_template_columns.name, string (new_name));
851         item->set_value (_template_columns.path, new_filepath);
852 }
853
854 void
855 RouteTemplateManager::delete_selected_template ()
856 {
857         if (!_current_selection) {
858                 return;
859         }
860
861         const string file_path = _current_selection->get_value (_template_columns.path);
862
863         if (g_unlink (file_path.c_str()) != 0) {
864                 error << string_compose(_("Could not delete template file \"%1\": %2"), file_path, strerror (errno)) << endmsg;
865                 return;
866         }
867         PBD::remove_directory (Glib::build_filename (user_route_template_directory (),
868                                                      _current_selection->get_value (_template_columns.name)));
869
870         _template_model->erase (_current_selection);
871         row_selection_changed ();
872 }
873
874 string
875 RouteTemplateManager::templates_dir () const
876 {
877         return user_route_template_directory ();
878 }
879
880
881 string
882 RouteTemplateManager::template_file (const TreeModel::const_iterator& item) const
883 {
884         return item->get_value (_template_columns.path);
885 }
886
887 bool
888 RouteTemplateManager::adjust_xml_tree (XMLTree& tree, const std::string& old_name, const std::string& new_name) const
889 {
890         return adjust_plugin_paths (tree.root(), old_name, string (new_name));
891 }