Handle export presets from config dirs properly. Removed some debug output.
[ardour.git] / libs / ardour / export_profile_manager.cc
1 /*
2     Copyright (C) 2008 Paul Davis
3     Author: Sakari Bergen
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 <ardour/export_profile_manager.h>
22
23 #include <cassert>
24 #include <stdexcept>
25
26 #include <glibmm/fileutils.h>
27
28 #include <pbd/enumwriter.h>
29 #include <pbd/xml++.h>
30 #include <pbd/convert.h>
31
32 #include <ardour/export_failed.h>
33 #include <ardour/export_file_io.h>
34 #include <ardour/export_format_specification.h>
35 #include <ardour/export_timespan.h>
36 #include <ardour/export_channel_configuration.h>
37 #include <ardour/export_filename.h>
38 #include <ardour/export_preset.h>
39 #include <ardour/export_handler.h>
40 #include <ardour/filename_extensions.h>
41 #include <ardour/session.h>
42
43 #include "i18n.h"
44
45 using namespace PBD;
46
47 namespace ARDOUR
48 {
49
50 ExportProfileManager::ExportProfileManager (Session & s) :
51   handler (s.get_export_handler()),
52   session (s),
53
54   session_range (new Location ()),
55   ranges (new LocationList ()),
56   single_range_mode (false),
57
58   format_list (new FormatList ())
59 {
60
61         /* Initialize path variables */
62
63         export_config_dir = user_config_directory();
64         export_config_dir /= "export";
65         search_path += export_config_dir;
66         
67         search_path += ardour_search_path().add_subdirectory_to_paths("export");
68         search_path += system_config_search_path().add_subdirectory_to_paths("export");;
69         
70         /* create export config directory if necessary */
71
72         if (!sys::exists (export_config_dir)) {
73                 sys::create_directory (export_config_dir);
74         }
75         
76         load_presets ();
77         load_formats ();
78         
79         /* Initialize all lists with an empty config */
80         
81         XMLNodeList dummy;
82         init_timespans (dummy);
83         init_channel_configs (dummy);
84         init_formats (dummy);
85         init_filenames (dummy);
86 }
87
88 ExportProfileManager::~ExportProfileManager ()
89 {
90         if (single_range_mode) { return; }
91         
92         XMLNode * instant_xml (new XMLNode ("ExportProfile"));
93         serialize_profile (*instant_xml);
94         session.add_instant_xml (*instant_xml, false);
95 }
96
97 void
98 ExportProfileManager::load_profile ()
99 {
100         XMLNode * instant_node = session.instant_xml ("ExportProfile");
101         if (instant_node) {
102                 set_state (*instant_node);
103         } else {
104                 XMLNode empty_node ("ExportProfile");
105                 set_state (empty_node);
106         }
107 }
108
109 void
110 ExportProfileManager::prepare_for_export ()
111 {
112         ChannelConfigPtr channel_config = channel_configs.front()->config;
113         TimespanListPtr ts_list = timespans.front()->timespans;
114         
115         FormatStateList::const_iterator format_it;
116         FilenameStateList::const_iterator filename_it;
117         
118         for (TimespanList::iterator ts_it = ts_list->begin(); ts_it != ts_list->end(); ++ts_it) {
119                 for (format_it = formats.begin(), filename_it = filenames.begin();
120                      format_it != formats.end() && filename_it != filenames.end();
121                      ++format_it, ++filename_it) {
122                 
123 //                      filename->include_timespan = (ts_list->size() > 1); Disabled for now...
124                         handler->add_export_config (*ts_it, channel_config, (*format_it)->format, (*filename_it)->filename);
125                 }
126         }
127 }
128
129 bool
130 ExportProfileManager::load_preset (PresetPtr preset)
131 {
132         bool ok = true;
133
134         current_preset = preset;
135         if (!preset) { return false; }
136
137         XMLNode const * state;
138         if ((state = preset->get_local_state())) {
139                 set_local_state (*state);
140         } else { ok = false; }
141         
142         if ((state = preset->get_global_state())) {
143                 if (!set_global_state (*state)) {
144                         ok = false;
145                 }
146         } else { ok = false; }
147         
148         return ok;
149 }
150
151 void
152 ExportProfileManager::load_presets ()
153 {
154         vector<sys::path> found = find_file (string_compose (X_("*%1"),export_preset_suffix));
155
156         for (vector<sys::path>::iterator it = found.begin(); it != found.end(); ++it) {
157                 load_preset_from_disk (*it);
158         }
159 }
160
161 ExportProfileManager::PresetPtr
162 ExportProfileManager::save_preset (string const & name)
163 {
164         string filename = export_config_dir.to_string() + "/" + name + export_preset_suffix;
165
166         if (!current_preset) {
167                 current_preset.reset (new ExportPreset (filename, session));
168                 preset_list.push_back (current_preset);
169         }
170         
171         XMLNode * global_preset = new XMLNode ("ExportPreset");
172         XMLNode * local_preset = new XMLNode ("ExportPreset");
173
174         serialize_global_profile (*global_preset);
175         serialize_local_profile (*local_preset);
176
177         current_preset->set_name (name);
178         current_preset->set_global_state (*global_preset);
179         current_preset->set_local_state (*local_preset);
180         
181         current_preset->save (filename);
182         
183         return current_preset;
184 }
185
186 void
187 ExportProfileManager::remove_preset ()
188 {
189         if (!current_preset) { return; }
190
191         for (PresetList::iterator it = preset_list.begin(); it != preset_list.end(); ++it) {
192                 if (*it == current_preset) {
193                         preset_list.erase (it);
194                         break;
195                 }
196         }
197
198         FileMap::iterator it = preset_file_map.find (current_preset->id());
199         if (it != preset_file_map.end()) {
200                 sys::remove (it->second);
201                 preset_file_map.erase (it);
202         }
203         
204         current_preset->remove_local();
205         current_preset.reset();
206 }
207
208 void
209 ExportProfileManager::load_preset_from_disk (PBD::sys::path const & path)
210 {
211         PresetPtr preset (new ExportPreset (path.to_string(), session));
212         
213         /* Handle id to filename mapping and don't add duplicates to list */
214         
215         FilePair pair (preset->id(), path);
216         if (preset_file_map.insert (pair).second) {
217                 preset_list.push_back (preset);
218         }
219 }
220
221 bool
222 ExportProfileManager::set_state (XMLNode const & root)
223 {
224         return set_global_state (root) && set_local_state (root);
225 }
226
227 bool
228 ExportProfileManager::set_global_state (XMLNode const & root)
229 {
230         return init_filenames (root.children ("ExportFilename")) &&
231                init_formats (root.children ("ExportFormat"));
232 }
233
234 bool
235 ExportProfileManager::set_local_state (XMLNode const & root)
236 {
237         return init_timespans (root.children ("ExportTimespan")) &&
238                init_channel_configs (root.children ("ExportChannelConfiguration"));
239 }
240
241 void
242 ExportProfileManager::serialize_profile (XMLNode & root)
243 {
244         serialize_local_profile (root);
245         serialize_global_profile (root);
246 }
247
248 void
249 ExportProfileManager::serialize_global_profile (XMLNode & root)
250 {
251         for (FormatStateList::iterator it = formats.begin(); it != formats.end(); ++it) {
252                 root.add_child_nocopy (serialize_format (*it));
253         }
254
255         for (FilenameStateList::iterator it = filenames.begin(); it != filenames.end(); ++it) {
256                 root.add_child_nocopy ((*it)->filename->get_state());
257         }
258 }
259
260 void
261 ExportProfileManager::serialize_local_profile (XMLNode & root)
262 {
263         for (TimespanStateList::iterator it = timespans.begin(); it != timespans.end(); ++it) {
264                 root.add_child_nocopy (serialize_timespan (*it));
265         }
266         
267         for (ChannelConfigStateList::iterator it = channel_configs.begin(); it != channel_configs.end(); ++it) {
268                 root.add_child_nocopy ((*it)->config->get_state());
269         }
270 }
271
272 std::vector<sys::path>
273 ExportProfileManager::find_file (std::string const & pattern)
274 {
275         vector<sys::path> found;
276
277         Glib::PatternSpec pattern_spec (pattern);
278         find_matching_files_in_search_path (search_path, pattern_spec, found);
279
280         return found;
281 }
282
283 void
284 ExportProfileManager::set_selection_range (nframes_t start, nframes_t end)
285 {
286
287         if (start || end) {
288                 selection_range.reset (new Location());
289                 selection_range->set_name (_("Selection"));
290                 selection_range->set (start, end);
291         } else {
292                 selection_range.reset();
293         }
294         
295         for (TimespanStateList::iterator it = timespans.begin(); it != timespans.end(); ++it) {
296                 (*it)->selection_range = selection_range;
297         }
298 }
299
300 std::string
301 ExportProfileManager::set_single_range (nframes_t start, nframes_t end, Glib::ustring name)
302 {
303         single_range_mode = true;
304         
305         single_range.reset (new Location());
306         single_range->set_name (name);
307         single_range->set (start, end);
308         
309         update_ranges ();
310         
311         return single_range->id().to_s();
312 }
313
314 bool
315 ExportProfileManager::init_timespans (XMLNodeList nodes)
316 {
317         timespans.clear ();
318         update_ranges ();
319         
320         bool ok = true;
321         for (XMLNodeList::const_iterator it = nodes.begin(); it != nodes.end(); ++it) {
322                 TimespanStatePtr span = deserialize_timespan (**it);
323                 if (span) {
324                         timespans.push_back (span);
325                 } else { ok = false; }
326         }
327         
328         if (timespans.empty()) {
329                 TimespanStatePtr timespan (new TimespanState (session_range, selection_range, ranges));
330                 timespans.push_back (timespan);
331                 return false;
332         }
333         
334         return ok;
335 }
336
337 ExportProfileManager::TimespanStatePtr
338 ExportProfileManager::deserialize_timespan (XMLNode & root)
339 {
340         TimespanStatePtr state (new TimespanState (session_range, selection_range, ranges));
341         XMLProperty const * prop;
342         
343         XMLNodeList spans = root.children ("Range");
344         for (XMLNodeList::iterator node_it = spans.begin(); node_it != spans.end(); ++node_it) {
345                 
346                 prop = (*node_it)->property ("id");
347                 if (!prop) { continue; }
348                 ustring id = prop->value();
349         
350                 for (LocationList::iterator it = ranges->begin(); it != ranges->end(); ++it) {
351                         if ((!id.compare ("session") && *it == session_range.get()) ||
352                             (!id.compare ("selection") && *it == selection_range.get()) ||
353                             (!id.compare ((*it)->id().to_s()))) {
354                                 TimespanPtr timespan = handler->add_timespan();
355                                 timespan->set_name ((*it)->name());
356                                 timespan->set_range_id (id);
357                                 timespan->set_range ((*it)->start(), (*it)->end());
358                                 state->timespans->push_back (timespan);
359                         }
360                 }
361         }
362         
363         if ((prop = root.property ("format"))) {
364                 state->time_format = (TimeFormat) string_2_enum (prop->value(), TimeFormat);
365         }
366         
367         return state;
368 }
369
370 XMLNode &
371 ExportProfileManager::serialize_timespan (TimespanStatePtr state)
372 {
373         XMLNode & root = *(new XMLNode ("ExportTimespan"));
374         XMLNode * span;
375         
376         update_ranges ();
377         
378         for (TimespanList::iterator it = state->timespans->begin(); it != state->timespans->end(); ++it) {
379                 if ((span = root.add_child ("Range"))) {
380                         span->add_property ("id", (*it)->range_id());
381                 }
382         }
383         
384         root.add_property ("format", enum_2_string (state->time_format));
385         
386         return root;
387 }
388
389 void
390 ExportProfileManager::update_ranges () {
391         ranges->clear();
392         
393         if (single_range_mode) {
394                 ranges->push_back (single_range.get());
395                 return;
396         }
397
398         /* Session */
399
400         session_range->set_name (_("Session"));
401         session_range->set (session.current_start_frame(), session.current_end_frame());
402         ranges->push_back (session_range.get());
403         
404         /* Selection */
405         
406         if (selection_range) {
407                 ranges->push_back (selection_range.get());
408         }
409         
410         /* ranges */
411         
412         LocationList const & list (session.locations()->list());
413         for (LocationList::const_iterator it = list.begin(); it != list.end(); ++it) {
414                 if ((*it)->is_range_marker()) {
415                         ranges->push_back (*it);
416                 }
417         }
418 }
419
420 bool
421 ExportProfileManager::init_channel_configs (XMLNodeList nodes)
422 {
423         channel_configs.clear();
424
425         if (nodes.empty()) {    
426                 ChannelConfigStatePtr config (new ChannelConfigState (handler->add_channel_config()));
427                 channel_configs.push_back (config);
428                 return false;
429         }
430         
431         for (XMLNodeList::const_iterator it = nodes.begin(); it != nodes.end(); ++it) {
432                 ChannelConfigStatePtr config (new ChannelConfigState (handler->add_channel_config()));
433                 config->config->set_state (**it);
434                 channel_configs.push_back (config);
435         }
436         
437         return true;
438 }
439
440 ExportProfileManager::FormatStatePtr
441 ExportProfileManager::duplicate_format_state (FormatStatePtr state)
442 {
443         /* Note: The pointer in the new FormatState should point to the same format spec
444                  as the original state's pointer. The spec itself should not be copied!   */
445
446         FormatStatePtr format (new FormatState (format_list, state->format));
447         formats.push_back (format);
448         return format;
449 }
450
451 void
452 ExportProfileManager::remove_format_state (FormatStatePtr state)
453 {
454         for (FormatStateList::iterator it = formats.begin(); it != formats.end(); ++it) {
455                 if (*it == state) {
456                         formats.erase (it);
457                         return;
458                 }
459         }
460 }
461
462 sys::path
463 ExportProfileManager::save_format_to_disk (FormatPtr format)
464 {
465         // TODO filename character stripping
466
467         /* Get filename for file */
468
469         Glib::ustring new_name = format->name();
470         new_name += export_format_suffix;
471         
472         sys::path new_path (export_config_dir);
473         new_path /= new_name;
474
475         /* Check if format is on disk already */
476         FileMap::iterator it;
477         if ((it = format_file_map.find (format->id())) != format_file_map.end()) {
478                 
479                 /* Check if config is not in user config dir */
480                 if (it->second.branch_path().to_string().compare (export_config_dir.to_string())) {
481                 
482                         /* Write new file */
483                 
484                         XMLTree tree (new_path.to_string());
485                         tree.set_root (&format->get_state());
486                         tree.write();
487                 
488                 } else {
489                 
490                         /* Update file and rename if necessary */
491                 
492                         XMLTree tree (it->second.to_string());
493                         tree.set_root (&format->get_state());
494                         tree.write();
495                         
496                         if (new_name.compare (it->second.leaf())) {
497                                 sys::rename (it->second, new_path);
498                         }
499                 }
500                 
501                 it->second = new_path;
502                 
503         } else {
504                 /* Write new file */
505                 
506                 XMLTree tree (new_path.to_string());
507                 tree.set_root (&format->get_state());
508                 tree.write();
509         }
510         
511         FormatListChanged ();
512         return new_path;
513 }
514
515 void
516 ExportProfileManager::remove_format_profile (FormatPtr format)
517 {
518         for (FormatList::iterator it = format_list->begin(); it != format_list->end(); ++it) {
519                 if (*it == format) {
520                         format_list->erase (it);
521                         break;
522                 }
523         }
524
525         FileMap::iterator it = format_file_map.find (format->id());
526         if (it != format_file_map.end()) {
527                 sys::remove (it->second);
528                 format_file_map.erase (it);
529         }
530         
531         FormatListChanged ();
532 }
533
534 ExportProfileManager::FormatPtr
535 ExportProfileManager::get_new_format (FormatPtr original)
536 {       
537         FormatPtr format;
538         if (original) {
539                 format.reset (new ExportFormatSpecification (*original));
540         } else {
541                 format = handler->add_format();
542                 format->set_name ("empty format");
543         }
544         
545         sys::path path = save_format_to_disk (format);
546         FilePair pair (format->id(), path);
547         format_file_map.insert (pair);
548         
549         format_list->push_back (format);
550         FormatListChanged ();
551         
552         return format;
553 }
554
555 bool
556 ExportProfileManager::init_formats (XMLNodeList nodes)
557 {
558         formats.clear();
559
560         bool ok = true;
561         for (XMLNodeList::const_iterator it = nodes.begin(); it != nodes.end(); ++it) {
562                 FormatStatePtr format = deserialize_format (**it);
563                 if (format) {
564                         formats.push_back (format);
565                 } else { ok = false; }
566         }
567         
568         if (formats.empty ()) {
569                 FormatStatePtr format (new FormatState (format_list, FormatPtr ()));
570                 formats.push_back (format);
571                 return false;
572         }
573         
574         return ok;
575 }
576
577 ExportProfileManager::FormatStatePtr
578 ExportProfileManager::deserialize_format (XMLNode & root)
579 {
580         XMLProperty * prop;
581         UUID id;
582         
583         if ((prop = root.property ("id"))) {
584                 id = prop->value();
585         }
586         
587         for (FormatList::iterator it = format_list->begin(); it != format_list->end(); ++it) {
588                 if ((*it)->id() == id) {
589                         return FormatStatePtr (new FormatState (format_list, *it));
590                 }
591         }
592
593         return FormatStatePtr ();
594 }
595
596 XMLNode &
597 ExportProfileManager::serialize_format (FormatStatePtr state)
598 {
599         XMLNode * root = new XMLNode ("ExportFormat");
600         
601         string id = state->format ? state->format->id().to_s() : "";
602         root->add_property ("id", id);
603         
604         return *root;
605 }
606
607 void
608 ExportProfileManager::load_formats ()
609 {
610         vector<sys::path> found = find_file (string_compose ("*%1", export_format_suffix));
611
612         for (vector<sys::path>::iterator it = found.begin(); it != found.end(); ++it) {
613                 load_format_from_disk (*it);
614         }
615 }
616
617 void
618 ExportProfileManager::load_format_from_disk (PBD::sys::path const & path)
619 {
620         XMLTree const tree (path.to_string());
621         FormatPtr format = handler->add_format (*tree.root());
622         
623         /* Handle id to filename mapping and don't add duplicates to list */
624         
625         FilePair pair (format->id(), path);
626         if (format_file_map.insert (pair).second) {
627                 format_list->push_back (format);
628         }
629         
630         FormatListChanged ();
631 }
632
633 ExportProfileManager::FilenameStatePtr
634 ExportProfileManager::duplicate_filename_state (FilenameStatePtr state)
635 {
636         FilenameStatePtr filename (new FilenameState (handler->add_filename_copy (state->filename)));
637         filenames.push_back (filename);
638         return filename;
639 }
640
641 void
642 ExportProfileManager::remove_filename_state (FilenameStatePtr state)
643 {
644         for (FilenameStateList::iterator it = filenames.begin(); it != filenames.end(); ++it) {
645                 if (*it == state) {
646                         filenames.erase (it);
647                         return;
648                 }
649         }
650 }
651
652 bool
653 ExportProfileManager::init_filenames (XMLNodeList nodes)
654 {
655         filenames.clear ();
656
657         for (XMLNodeList::const_iterator it = nodes.begin(); it != nodes.end(); ++it) {
658                 FilenamePtr filename = handler->add_filename();
659                 filename->set_state (**it);
660                 filenames.push_back (FilenameStatePtr (new FilenameState (filename)));
661         }
662         
663         if (filenames.empty()) {
664                 FilenameStatePtr filename (new FilenameState (handler->add_filename()));
665                 filenames.push_back (filename);
666                 return false;
667         }
668         
669         return true;
670 }
671
672 boost::shared_ptr<ExportProfileManager::Warnings>
673 ExportProfileManager::get_warnings ()
674 {
675         boost::shared_ptr<Warnings> warnings (new Warnings ());
676
677         ChannelConfigStatePtr channel_config_state = channel_configs.front();
678         TimespanStatePtr timespan_state = timespans.front();
679         
680         /*** Check "global" config ***/
681         
682         TimespanListPtr timespans = timespan_state->timespans;
683         ChannelConfigPtr channel_config = channel_config_state->config;
684
685         /* Check Timespans are not empty */
686         
687         if (timespans->empty()) {
688                 warnings->errors.push_back (_("No timespan has been selected!"));
689         }
690
691         /* Check channel config ports */
692         
693         if (!channel_config->all_channels_have_ports ()) {
694                 warnings->warnings.push_back (_("Some channels are empty"));
695         }
696         
697         /*** Check files ***/
698         
699         FormatStateList::const_iterator format_it;
700         FilenameStateList::const_iterator filename_it;
701         for (format_it = formats.begin(), filename_it = filenames.begin();
702              format_it != formats.end() && filename_it != filenames.end();
703              ++format_it, ++filename_it) {
704                         check_config (warnings, timespan_state, channel_config_state, *format_it, *filename_it);
705         }
706         
707         return warnings;
708 }
709
710 void
711 ExportProfileManager::check_config (boost::shared_ptr<Warnings> warnings,
712                                     TimespanStatePtr timespan_state,
713                                     ChannelConfigStatePtr channel_config_state,
714                                     FormatStatePtr format_state,
715                                     FilenameStatePtr filename_state)
716 {
717         TimespanListPtr timespans = timespan_state->timespans;
718         ChannelConfigPtr channel_config = channel_config_state->config;
719         FormatPtr format = format_state->format;
720         FilenamePtr filename = filename_state->filename;
721
722         /* Check format and maximum channel count */
723         if (!format || !format->type()) {
724                 warnings->errors.push_back (_("No format selected!"));
725         } else if (!ExportFileFactory::check (format, channel_config->get_n_chans())) {
726                 warnings->errors.push_back (_("One or more of the selected formats is not compatible with this system!"));
727         } else if (format->channel_limit() < channel_config->get_n_chans()) {
728                 warnings->errors.push_back
729                   (string_compose (_("%1 supports only %2 channels, but you have %3 channels in your channel configuration"),
730                                      format->format_name(),
731                                      format->channel_limit(),
732                                      channel_config->get_n_chans()));
733         }
734         
735         if (!warnings->errors.empty()) { return; }
736         
737         /* Check filenames */
738         
739 //      filename->include_timespan = (timespans->size() > 1); Disabled for now...
740         
741         for (std::list<TimespanPtr>::iterator timespan_it = timespans->begin(); timespan_it != timespans->end(); ++timespan_it) {
742                 filename->set_timespan (*timespan_it);
743         
744                 if (channel_config->get_split()) {
745                         filename->include_channel = true;
746                         
747                         for (uint32_t chan = 1; chan <= channel_config->get_n_chans(); ++chan) {
748                                 filename->set_channel (chan);
749                                 
750                                 Glib::ustring path = filename->get_path (format);
751                                 
752                                 if (sys::exists (sys::path (path))) {
753                                         warnings->conflicting_filenames.push_back (path);
754                                 }
755                         }
756                         
757                 } else {
758                         Glib::ustring path = filename->get_path (format);
759                         
760                         if (sys::exists (sys::path (path))) {
761                                 warnings->conflicting_filenames.push_back (path);
762                         }
763                 }
764         }
765 }
766
767 }; // namespace ARDOUR