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