4b3b9ca9a41549c058b95ab4a67d7212f2cb58ae
[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
23 #include <glib/gstdio.h>
24
25 #include <gtkmm/filechooserdialog.h>
26 #include <gtkmm/notebook.h>
27 #include <gtkmm/separator.h>
28 #include <gtkmm/scrolledwindow.h>
29 #include <gtkmm/stock.h>
30 #include <gtkmm/treeiter.h>
31
32 #include "pbd/basename.h"
33 #include "pbd/error.h"
34 #include "pbd/file_archive.h"
35 #include "pbd/file_utils.h"
36 #include "pbd/i18n.h"
37 #include "pbd/xml++.h"
38
39 #include "ardour/template_utils.h"
40
41 #include "template_dialog.h"
42
43 using namespace std;
44 using namespace Gtk;
45 using namespace PBD;
46 using namespace ARDOUR;
47
48
49 TemplateDialog::TemplateDialog ()
50         : ArdourDialog ("Manage Templates")
51 {
52         Notebook* nb = manage (new Notebook);
53
54         SessionTemplateManager* session_tm = manage (new SessionTemplateManager);
55         nb->append_page (*session_tm, _("Session Templates"));
56
57         RouteTemplateManager* route_tm = manage (new RouteTemplateManager);
58         nb->append_page (*route_tm, _("Track Templates"));
59
60         get_vbox()->pack_start (*nb);
61         add_button (_("Ok"), Gtk::RESPONSE_OK);
62
63         get_vbox()->show_all();
64
65         session_tm->init ();
66         route_tm->init ();
67 }
68
69 TemplateManager::TemplateManager ()
70         : HBox ()
71         , ProgressReporter ()
72         , _remove_button (_("Remove"))
73         , _rename_button (_("Rename"))
74         , _export_all_templates_button (_("Export all"))
75         , _import_template_set_button (_("Import"))
76 {
77         _template_model = ListStore::create (_template_columns);
78         _template_treeview.set_model (_template_model);
79
80         _validated_column.set_title (_("Template Name"));
81         _validated_column.pack_start (_validating_cellrenderer);
82         _template_treeview.append_column (_validated_column);
83         _validating_cellrenderer.property_editable() = true;
84
85         _validated_column.set_cell_data_func (_validating_cellrenderer, sigc::mem_fun (*this, &TemplateManager::render_template_names));
86         _validating_cellrenderer.signal_edited().connect (sigc::mem_fun (*this, &TemplateManager::validate_edit));
87         _template_treeview.signal_cursor_changed().connect (sigc::mem_fun (*this, &TemplateManager::row_selection_changed));
88         _template_treeview.signal_key_press_event().connect (sigc::mem_fun (*this, &TemplateManager::key_event));
89
90         ScrolledWindow* sw = manage (new ScrolledWindow);
91         sw->property_hscrollbar_policy() = POLICY_AUTOMATIC;
92         sw->add (_template_treeview);
93         sw->set_size_request (300, 200);
94
95
96         VBox* vb_btns = manage (new VBox);
97         vb_btns->set_spacing (4);
98         vb_btns->pack_start (_rename_button, false, false);
99         vb_btns->pack_start (_remove_button, false, false);
100
101         _rename_button.set_sensitive (false);
102         _rename_button.signal_clicked().connect (sigc::mem_fun (*this, &TemplateManager::start_edit));
103         _remove_button.set_sensitive (false);
104         _remove_button.signal_clicked().connect (sigc::mem_fun (*this, &TemplateManager::delete_selected_template));
105
106         vb_btns->pack_start (*(manage (new VSeparator ())));
107
108         vb_btns->pack_start (_export_all_templates_button, false, false);
109         vb_btns->pack_start (_import_template_set_button, false, false);
110
111         _export_all_templates_button.set_sensitive (true);
112         _export_all_templates_button.signal_clicked().connect (sigc::mem_fun (*this, &TemplateManager::export_all_templates));
113
114         _import_template_set_button.set_sensitive (true);
115         _import_template_set_button.signal_clicked().connect (sigc::mem_fun (*this, &TemplateManager::import_template_set));
116
117         set_spacing (6);
118
119         VBox* vb = manage (new VBox);
120         vb->pack_start (*sw);
121         vb->pack_start (_progress_bar);
122
123         pack_start (*vb);
124         pack_start (*vb_btns);
125
126         show_all_children ();
127         _progress_bar.hide ();
128 }
129
130 void
131 TemplateManager::setup_model (const vector<TemplateInfo>& templates)
132 {
133         _template_model->clear ();
134
135         for (vector<TemplateInfo>::const_iterator it = templates.begin(); it != templates.end(); ++it) {
136                 TreeModel::Row row;
137                 row = *(_template_model->append ());
138
139                 row[_template_columns.name] = it->name;
140                 row[_template_columns.path] = it->path;
141         }
142 }
143
144 void
145 TemplateManager::row_selection_changed ()
146 {
147         bool has_selection = false;
148         if (_template_treeview.get_selection()->count_selected_rows () != 0) {
149                 Gtk::TreeModel::const_iterator it = _template_treeview.get_selection()->get_selected ();
150                 if (it) {
151                         has_selection = true;
152                 }
153         }
154
155         _rename_button.set_sensitive (has_selection);
156         _remove_button.set_sensitive (has_selection);
157 }
158
159 void
160 TemplateManager::render_template_names (Gtk::CellRenderer*, const Gtk::TreeModel::iterator& it)
161 {
162         if (it) {
163                 _validating_cellrenderer.property_text () = it->get_value (_template_columns.name);
164         }
165 }
166
167 void
168 TemplateManager::validate_edit (const Glib::ustring& path_string, const Glib::ustring& new_name)
169 {
170         const TreePath path (path_string);
171         TreeModel::iterator current = _template_model->get_iter (path);
172
173         if (current->get_value (_template_columns.name) == new_name) {
174                 return;
175         }
176
177         TreeModel::Children rows = _template_model->children ();
178
179         bool found = false;
180         for (TreeModel::Children::const_iterator it = rows.begin(); it != rows.end(); ++it) {
181                 if (it->get_value (_template_columns.name) == new_name) {
182                         found = true;
183                         break;
184                 }
185         }
186
187         if (found) {
188                 error << string_compose (_("Template of name \"%1\" already exists"), new_name) << endmsg;
189                 return;
190         }
191
192
193         rename_template (current, new_name);
194 }
195
196 void
197 TemplateManager::start_edit ()
198 {
199         TreeModel::Path path;
200         TreeViewColumn* col;
201         _template_treeview.get_cursor (path, col);
202         _template_treeview.set_cursor (path, *col, /*set_editing =*/ true);
203 }
204
205 bool
206 TemplateManager::key_event (GdkEventKey* ev)
207 {
208         if (ev->keyval == GDK_KEY_F2) {
209                 start_edit ();
210                 return true;
211         }
212         if (ev->keyval == GDK_KEY_Delete) {
213                 delete_selected_template ();
214                 return true;
215         }
216
217         return false;
218 }
219
220 static
221 bool accept_all_files (string const &, void *)
222 {
223         return true;
224 }
225
226 static void _set_progress (Progress* p, size_t n, size_t t)
227 {
228         p->set_progress (float (n) / float(t));
229 }
230
231
232 void
233 TemplateManager::export_all_templates ()
234 {
235         GError* err = NULL;
236         char* td = g_dir_make_tmp ("ardour-templates-XXXXXX", &err);
237
238         if (!td) {
239                 error << string_compose(_("Could not make tmpdir: %1"), err->message) << endmsg;
240                 return;
241         }
242         const string tmpdir (td);
243         g_free (td);
244         g_clear_error (&err);
245
246         FileChooserDialog dialog(_("Save Exported Template Archive"), FILE_CHOOSER_ACTION_SAVE);
247         dialog.set_filename (X_("templates.tar.xz"));
248
249         dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
250         dialog.add_button(Gtk::Stock::OK, Gtk::RESPONSE_OK);
251
252         FileFilter archive_filter;
253         archive_filter.add_pattern (X_("*.tar.xz"));
254         archive_filter.set_name (_("Template archives"));
255         dialog.add_filter (archive_filter);
256
257         int result = dialog.run ();
258
259         if (result != RESPONSE_OK || !dialog.get_filename().length()) {
260                 return;
261         }
262
263         PBD::copy_recurse (templates_dir (), tmpdir);
264
265         vector<string> files;
266         PBD::find_files_matching_regex (files, tmpdir, string ("\\.template$"), /* recurse = */ true);
267
268         vector<string>::const_iterator it;
269         for (it = files.begin(); it != files.end(); ++it) {
270                 const string bn = PBD::basename_nosuffix (*it);
271                 const string old_path = Glib::build_filename (templates_dir (), bn);
272                 const string new_path = Glib::build_filename ("$TEMPLATEDIR", bn);
273
274                 XMLTree tree;
275                 if (!tree.read (*it)) {
276                         continue;
277                 }
278                 if (adjust_xml_tree (tree, old_path, new_path)) {
279                         tree.write (*it);
280                 }
281         }
282
283         find_files_matching_filter (files, tmpdir, accept_all_files, 0, false, true, true);
284
285         std::map<std::string, std::string> filemap;
286         for (it = files.begin(); it != files.end(); ++it) {
287                 filemap[*it] = it->substr (tmpdir.size()+1, it->size() - tmpdir.size() - 1);
288         }
289
290         _current_action = _("Exporting templates");
291
292         PBD::FileArchive ar (dialog.get_filename());
293         PBD::ScopedConnectionList progress_connection;
294         ar.progress.connect_same_thread (progress_connection, boost::bind (&_set_progress, this, _1, _2));
295         ar.create (filemap);
296
297         PBD::remove_directory (tmpdir);
298 }
299
300 void
301 TemplateManager::import_template_set ()
302 {
303         FileChooserDialog dialog (_("Import template archives"));
304         dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
305         dialog.add_button(Gtk::Stock::OK, Gtk::RESPONSE_OK);
306
307         FileFilter archive_filter;
308         archive_filter.add_pattern (X_("*.tar.xz"));
309         archive_filter.set_name (_("Template archives"));
310         dialog.add_filter (archive_filter);
311
312         int result = dialog.run ();
313
314         if (result != RESPONSE_OK || !dialog.get_filename().length()) {
315                 return;
316         }
317
318         if (!g_file_test (templates_dir().c_str(), G_FILE_TEST_IS_DIR)) {
319                 cout << "making " << templates_dir() << endl;
320                 g_mkdir (templates_dir().c_str(), 0755);
321         }
322
323         _current_action = _("Importing templates");
324
325         FileArchive ar (dialog.get_filename ());
326         PBD::ScopedConnectionList progress_connection;
327         ar.progress.connect_same_thread (progress_connection, boost::bind (&_set_progress, this, _1, _2));
328         ar.inflate (templates_dir());
329
330         vector<string> files;
331         PBD::find_files_matching_regex (files, templates_dir (), string ("\\.template$"), /* recurse = */ true);
332
333         vector<string>::const_iterator it;
334         for (it = files.begin(); it != files.end(); ++it) {
335                 const string bn = PBD::basename_nosuffix (*it);
336                 const string old_path = Glib::build_filename ("$TEMPLATEDIR", bn);
337                 const string new_path = Glib::build_filename (templates_dir (), bn);
338
339                 XMLTree tree;
340                 if (!tree.read (*it)) {
341                         continue;
342                 }
343                 if (adjust_xml_tree (tree, old_path, new_path)) {
344                         tree.write (*it);
345                 }
346         }
347
348         init ();
349 }
350
351 bool
352 TemplateManager::adjust_plugin_paths (XMLNode* node, const string& name, const string& new_name) const
353 {
354         bool adjusted = false;
355
356         const XMLNodeList& procs = node->children (X_("Processor"));
357         XMLNodeConstIterator pit;
358         for (pit = procs.begin(); pit != procs.end(); ++pit) {
359                 XMLNode* lv2_node = (*pit)->child (X_("lv2"));
360                 if (!lv2_node) {
361                         continue;
362                 }
363                 string template_dir;
364
365                 if (!lv2_node->get_property (X_("template-dir"), template_dir)) {
366                         continue;
367                 }
368
369                 const int suffix_pos = template_dir.size() - name.size();
370                 if (suffix_pos < 0) {
371                         cerr << "Template name\"" << name << "\" longer than template-dir \"" << template_dir << "\", WTH?" << endl;
372                         continue;
373                 }
374
375                 if (template_dir.compare (suffix_pos, template_dir.size(), name)) {
376                         cerr << "Template name \"" << name << "\" no suffix of template-dir \"" << template_dir << "\"" << endl;
377                         continue;
378                 }
379
380                 const string new_template_dir = template_dir.substr (0, suffix_pos) + new_name;
381                 lv2_node->set_property (X_("template-dir"), new_template_dir);
382
383                 adjusted = true;
384         }
385
386         return adjusted;
387 }
388
389 void
390 TemplateManager::update_progress_gui (float p)
391 {
392         if (p >= 1.0) {
393                 _progress_bar.hide ();
394                 return;
395         }
396
397         _progress_bar.show ();
398         _progress_bar.set_text (_current_action);
399         _progress_bar.set_fraction (p);
400 }
401
402
403 void SessionTemplateManager::init ()
404 {
405         vector<TemplateInfo> templates;
406         find_session_templates (templates);
407         setup_model (templates);
408
409         _progress_bar.hide ();
410 }
411
412 void RouteTemplateManager::init ()
413 {
414         vector<TemplateInfo> templates;
415         find_route_templates (templates);
416         setup_model (templates);
417
418         _progress_bar.hide ();
419 }
420
421
422 void
423 SessionTemplateManager::rename_template (TreeModel::iterator& item, const Glib::ustring& new_name_)
424 {
425         const string old_path = item->get_value (_template_columns.path);
426         const string old_name = item->get_value (_template_columns.name);
427         const string new_name = string (new_name_);
428
429         const string old_file_old_path = Glib::build_filename (old_path, old_name+".template");
430
431         XMLTree tree;
432
433         if (!tree.read(old_file_old_path)) {
434                 error << string_compose (_("Could not parse template file \"%1\"."), old_file_old_path) << endmsg;
435                 return;
436         }
437         XMLNode* root = tree.root();
438
439         const XMLNode* const routes_node = root->child (X_("Routes"));
440         if (routes_node) {
441                 const XMLNodeList& routes = routes_node->children (X_("Route"));
442                 XMLNodeConstIterator rit;
443                 for (rit = routes.begin(); rit != routes.end(); ++rit) {
444                         adjust_plugin_paths (*rit, old_name, new_name);
445                 }
446         }
447
448         const string new_file_old_path = Glib::build_filename (old_path, new_name+".template");
449
450         tree.set_filename (new_file_old_path);
451
452         if (!tree.write ()) {
453                 error << string_compose(_("Could not write to new template file \"%1\"."), new_file_old_path);
454                 return;
455         }
456
457         const string new_path = Glib::build_filename (user_template_directory (), new_name);
458
459         if (g_rename (old_path.c_str(), new_path.c_str()) != 0) {
460                 error << string_compose (_("Could not rename template directory from \"%1\" to \"%2\": %3"),
461                                          old_path, new_path, strerror (errno)) << endmsg;
462                 g_unlink (new_file_old_path.c_str());
463                 return;
464         }
465
466         const string old_file_new_path = Glib::build_filename (new_path, old_name+".template");
467         if (g_unlink (old_file_new_path.c_str())) {
468                 error << string_compose (X_("Could not delete old template file \"%1\": %2"),
469                                          old_file_new_path, strerror (errno)) << endmsg;
470         }
471
472         item->set_value (_template_columns.name, new_name);
473         item->set_value (_template_columns.path, new_path);
474 }
475
476 void
477 SessionTemplateManager::delete_selected_template ()
478 {
479         if (_template_treeview.get_selection()->count_selected_rows() == 0) {
480                 return;
481         }
482
483         Gtk::TreeModel::const_iterator it = _template_treeview.get_selection()->get_selected();
484
485         if (!it) {
486                 return;
487         }
488
489         PBD::remove_directory (it->get_value (_template_columns.path));
490
491         _template_model->erase (it);
492         row_selection_changed ();
493 }
494
495
496 string
497 SessionTemplateManager::templates_dir () const
498 {
499         return user_template_directory ();
500 }
501
502 bool
503 SessionTemplateManager::adjust_xml_tree (XMLTree& tree, const std::string& old_name, const std::string& new_name) const
504 {
505         bool adjusted = false;
506         XMLNode* root = tree.root();
507
508         const XMLNode* const routes_node = root->child (X_("Routes"));
509         if (routes_node) {
510                 const XMLNodeList& routes = routes_node->children (X_("Route"));
511                 XMLNodeConstIterator rit;
512                 for (rit = routes.begin(); rit != routes.end(); ++rit) {
513                         if (adjust_plugin_paths (*rit, old_name, new_name)) {
514                                 adjusted = true;
515                         }
516                 }
517         }
518
519         return adjusted;
520 }
521
522
523 void
524 RouteTemplateManager::rename_template (TreeModel::iterator& item, const Glib::ustring& new_name)
525 {
526         const string old_name = item->get_value (_template_columns.name);
527         const string old_filepath = item->get_value (_template_columns.path);
528         const string new_filepath = Glib::build_filename (user_route_template_directory(), new_name+".template");
529
530         XMLTree tree;
531         if (!tree.read (old_filepath)) {
532                 error << string_compose (_("Could not parse template file \"%1\"."), old_filepath) << endmsg;
533                 return;
534         }
535         tree.root()->children().front()->set_property (X_("name"), new_name);
536
537         const bool adjusted = adjust_plugin_paths (tree.root(), old_name, string (new_name));
538
539         const string old_state_dir = Glib::build_filename (user_route_template_directory(), old_name);
540         const string new_state_dir = Glib::build_filename (user_route_template_directory(), new_name);
541
542         if (adjusted) {
543                 if (g_rename (old_state_dir.c_str(), new_state_dir.c_str()) != 0) {
544                         error << string_compose (_("Could not rename state dir \"%1\" to \"%22\": %3"), old_state_dir, new_state_dir, strerror (errno)) << endmsg;
545                         return;
546                 }
547         }
548
549         tree.set_filename (new_filepath);
550
551         if (!tree.write ()) {
552                 error << string_compose(_("Could not write new template file \"%1\"."), new_filepath) << endmsg;
553                 if (adjusted) {
554                         g_rename (new_state_dir.c_str(), old_state_dir.c_str());
555                 }
556                 return;
557         }
558
559         if (g_unlink (old_filepath.c_str()) != 0) {
560                 error << string_compose (_("Could not remove old template file \"%1\": %2"), old_filepath, strerror (errno)) << endmsg;
561         }
562
563         item->set_value (_template_columns.name, string (new_name));
564         item->set_value (_template_columns.path, new_filepath);
565 }
566
567 void
568 RouteTemplateManager::delete_selected_template ()
569 {
570         if (_template_treeview.get_selection()->count_selected_rows() == 0) {
571                 return;
572         }
573
574         Gtk::TreeModel::const_iterator it = _template_treeview.get_selection()->get_selected();
575
576         if (!it) {
577                 return;
578         }
579
580         const string file_path = it->get_value (_template_columns.path);
581
582         if (g_unlink (file_path.c_str()) != 0) {
583                 error << string_compose(_("Could not delete template file \"%1\": %2"), file_path, strerror (errno)) << endmsg;
584                 return;
585         }
586         PBD::remove_directory (Glib::build_filename (user_route_template_directory (), it->get_value (_template_columns.name)));
587
588         _template_model->erase (it);
589         row_selection_changed ();
590 }
591
592 string
593 RouteTemplateManager::templates_dir () const
594 {
595         return user_route_template_directory ();
596 }
597
598 bool
599 RouteTemplateManager::adjust_xml_tree (XMLTree& tree, const std::string& old_name, const std::string& new_name) const
600 {
601         return adjust_plugin_paths (tree.root(), old_name, string (new_name));
602 }