Fix stub LV2 persist implementation.
[ardour.git] / libs / ardour / utils.cc
1 /*
2     Copyright (C) 2000-2003 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #ifdef WAF_BUILD
21 #include "libardour-config.h"
22 #endif
23
24 #include <stdint.h>
25
26 #include <cstdio> /* for sprintf */
27 #include <cstring>
28 #include <cmath>
29 #include <cctype>
30 #include <cstring>
31 #include <cerrno>
32 #include <iostream>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <sys/time.h>
36 #include <fcntl.h>
37 #include <dirent.h>
38 #include <errno.h>
39
40 #include <glibmm/miscutils.h>
41 #include <glibmm/fileutils.h>
42
43 #ifdef HAVE_WORDEXP
44 #include <wordexp.h>
45 #endif
46
47 #include "pbd/error.h"
48 #include "pbd/stacktrace.h"
49 #include "pbd/xml++.h"
50 #include "pbd/basename.h"
51 #include "pbd/strsplit.h"
52 #include "ardour/utils.h"
53
54 #include "i18n.h"
55
56 using namespace ARDOUR;
57 using namespace std;
58 using namespace PBD;
59
60 string
61 legalize_for_path (const string& str)
62 {
63 #if OLD_SCHOOL_PROHIBITIVE
64         string::size_type pos;
65         string legal_chars = "abcdefghijklmnopqrtsuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_+=: ";
66         string legal;
67
68         legal = str;
69         pos = 0;
70
71         while ((pos = legal.find_first_not_of (legal_chars, pos)) != string::npos) {
72                 legal.replace (pos, 1, "_");
73                 pos += 1;
74         }
75
76         return legal;
77 #else
78         string::size_type pos;
79         string illegal_chars = "/\\"; /* DOS, POSIX. Yes, we're going to ignore HFS */
80         string legal;
81
82         legal = str;
83         pos = 0;
84
85         while ((pos = legal.find_first_of (illegal_chars, pos)) != string::npos) {
86                 legal.replace (pos, 1, "_");
87                 pos += 1;
88         }
89
90         return legal;
91 #endif
92 }
93
94 string 
95 bump_name_once (const std::string& name, char delimiter)
96 {
97         string::size_type delim;
98         string newname;
99
100         if ((delim = name.find_last_of (delimiter)) == string::npos) {
101                 newname  = name;
102                 newname += delimiter;
103                 newname += "1";
104         } else {
105                 int isnumber = 1;
106                 const char *last_element = name.c_str() + delim + 1;
107                 for (size_t i = 0; i < strlen(last_element); i++) {
108                         if (!isdigit(last_element[i])) {
109                                 isnumber = 0;
110                                 break;
111                         }
112                 }
113
114                 errno = 0;
115                 int32_t version = strtol (name.c_str()+delim+1, (char **)NULL, 10);
116
117                 if (isnumber == 0 || errno != 0) {
118                         // last_element is not a number, or is too large
119                         newname  = name;
120                         newname  += delimiter;
121                         newname += "1";
122                 } else {
123                         char buf[32];
124
125                         snprintf (buf, sizeof(buf), "%d", version+1);
126
127                         newname  = name.substr (0, delim+1);
128                         newname += buf;
129                 }
130         }
131
132         return newname;
133
134 }
135
136 bool
137 could_be_a_valid_path (const string& path)
138 {
139         vector<string> posix_dirs;
140         vector<string> dos_dirs;
141         string testpath;
142
143         split (path, posix_dirs, '/');
144         split (path, dos_dirs, '\\');
145
146         /* remove the last component of each */
147
148         posix_dirs.erase (--posix_dirs.end());
149         dos_dirs.erase (--dos_dirs.end());
150         
151         if (G_DIR_SEPARATOR == '/') {
152                 for (vector<string>::iterator x = posix_dirs.begin(); x != posix_dirs.end(); ++x) {
153                         testpath = Glib::build_filename (testpath, *x);
154                         cerr << "Testing " << testpath << endl;
155                         if (!Glib::file_test (testpath, Glib::FILE_TEST_IS_DIR|Glib::FILE_TEST_EXISTS)) {
156                                 return false;
157                         }
158                 }
159         }
160
161         if (G_DIR_SEPARATOR == '\\') {
162                 testpath = "";
163                 for (vector<string>::iterator x = dos_dirs.begin(); x != dos_dirs.end(); ++x) {
164                         testpath = Glib::build_filename (testpath, *x);
165                         cerr << "Testing " << testpath << endl;
166                         if (!Glib::file_test (testpath, Glib::FILE_TEST_IS_DIR|Glib::FILE_TEST_EXISTS)) {
167                                 return false;
168                         }
169                 }
170         }
171
172         return true;
173 }
174
175
176 XMLNode *
177 find_named_node (const XMLNode& node, string name)
178 {
179         XMLNodeList nlist;
180         XMLNodeConstIterator niter;
181         XMLNode* child;
182
183         nlist = node.children();
184
185         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
186
187                 child = *niter;
188
189                 if (child->name() == name) {
190                         return child;
191                 }
192         }
193
194         return 0;
195 }
196
197 int
198 cmp_nocase (const string& s, const string& s2)
199 {
200         string::const_iterator p = s.begin();
201         string::const_iterator p2 = s2.begin();
202
203         while (p != s.end() && p2 != s2.end()) {
204                 if (toupper(*p) != toupper(*p2)) {
205                         return (toupper(*p) < toupper(*p2)) ? -1 : 1;
206                 }
207                 ++p;
208                 ++p2;
209         }
210
211         return (s2.size() == s.size()) ? 0 : (s.size() < s2.size()) ? -1 : 1;
212 }
213
214 int
215 touch_file (string path)
216 {
217         int fd = open (path.c_str(), O_RDWR|O_CREAT, 0660);
218         if (fd >= 0) {
219                 close (fd);
220                 return 0;
221         }
222         return 1;
223 }
224
225 string
226 region_name_from_path (string path, bool strip_channels, bool add_channel_suffix, uint32_t total, uint32_t this_one)
227 {
228         path = PBD::basename_nosuffix (path);
229
230         if (strip_channels) {
231
232                 /* remove any "?R", "?L" or "?[a-z]" channel identifier */
233
234                 string::size_type len = path.length();
235
236                 if (len > 3 && (path[len-2] == '%' || path[len-2] == '?' || path[len-2] == '.') &&
237                     (path[len-1] == 'R' || path[len-1] == 'L' || (islower (path[len-1])))) {
238
239                         path = path.substr (0, path.length() - 2);
240                 }
241         }
242
243         if (add_channel_suffix) {
244
245                 path += '%';
246
247                 if (total > 2) {
248                         path += (char) ('a' + this_one);
249                 } else {
250                         path += (char) (this_one == 0 ? 'L' : 'R');
251                 }
252         }
253
254         return path;
255 }
256
257 bool
258 path_is_paired (string path, string& pair_base)
259 {
260         string::size_type pos;
261
262         /* remove any leading path */
263
264         if ((pos = path.find_last_of (G_DIR_SEPARATOR)) != string::npos) {
265                 path = path.substr(pos+1);
266         }
267
268         /* remove filename suffixes etc. */
269
270         if ((pos = path.find_last_of ('.')) != string::npos) {
271                 path = path.substr (0, pos);
272         }
273
274         string::size_type len = path.length();
275
276         /* look for possible channel identifier: "?R", "%R", ".L" etc. */
277
278         if (len > 3 && (path[len-2] == '%' || path[len-2] == '?' || path[len-2] == '.') &&
279             (path[len-1] == 'R' || path[len-1] == 'L' || (islower (path[len-1])))) {
280
281                 pair_base = path.substr (0, len-2);
282                 return true;
283
284         }
285
286         return false;
287 }
288
289 string
290 path_expand (string path)
291 {
292         if (path.empty()) {
293                 return path;
294         }
295
296 #ifdef HAVE_WORDEXP
297         /* Handle tilde and environment variable expansion in session path */
298         string ret = path;
299
300         wordexp_t expansion;
301         switch (wordexp (path.c_str(), &expansion, WRDE_NOCMD|WRDE_UNDEF)) {
302         case 0:
303                 break;
304         default:
305                 error << string_compose (_("illegal or badly-formed string used for path (%1)"), path) << endmsg;
306                 goto out;
307         }
308
309         if (expansion.we_wordc > 1) {
310                 error << string_compose (_("path (%1) is ambiguous"), path) << endmsg;
311                 goto out;
312         }
313
314         ret = expansion.we_wordv[0];
315   out:
316         wordfree (&expansion);
317         return ret;
318
319 #else
320         return path;
321 #endif
322 }
323
324 #if __APPLE__
325 string
326 CFStringRefToStdString(CFStringRef stringRef)
327 {
328         CFIndex size =
329                 CFStringGetMaximumSizeForEncoding(CFStringGetLength(stringRef) ,
330                 kCFStringEncodingUTF8);
331             char *buf = new char[size];
332
333         std::string result;
334
335         if(CFStringGetCString(stringRef, buf, size, kCFStringEncodingUTF8)) {
336             result = buf;
337         }
338         delete [] buf;
339         return result;
340 }
341 #endif // __APPLE__
342
343 void
344 compute_equal_power_fades (nframes_t nframes, float* in, float* out)
345 {
346         double step;
347
348         step = 1.0/(nframes-1);
349
350         in[0] = 0.0f;
351
352         for (nframes_t i = 1; i < nframes - 1; ++i) {
353                 in[i] = in[i-1] + step;
354         }
355
356         in[nframes-1] = 1.0;
357
358         const float pan_law_attenuation = -3.0f;
359         const float scale = 2.0f - 4.0f * powf (10.0f,pan_law_attenuation/20.0f);
360
361         for (nframes_t n = 0; n < nframes; ++n) {
362                 float inVal = in[n];
363                 float outVal = 1 - inVal;
364                 out[n] = outVal * (scale * outVal + 1.0f - scale);
365                 in[n] = inVal * (scale * inVal + 1.0f - scale);
366         }
367 }
368
369 EditMode
370 string_to_edit_mode (string str)
371 {
372         if (str == _("Splice")) {
373                 return Splice;
374         } else if (str == _("Slide")) {
375                 return Slide;
376         } else if (str == _("Lock")) {
377                 return Lock;
378         }
379         fatal << string_compose (_("programming error: unknown edit mode string \"%1\""), str) << endmsg;
380         /*NOTREACHED*/
381         return Slide;
382 }
383
384 const char*
385 edit_mode_to_string (EditMode mode)
386 {
387         switch (mode) {
388         case Slide:
389                 return _("Slide");
390
391         case Lock:
392                 return _("Lock");
393
394         default:
395         case Splice:
396                 return _("Splice");
397         }
398 }
399
400 SyncSource
401 string_to_sync_source (string str)
402 {
403         if (str == _("MIDI Timecode")) {
404                 return MTC;
405         }
406
407         if (str == _("MIDI Clock")) {
408                 return MIDIClock;
409         }
410
411         if (str == _("JACK")) {
412                 return JACK;
413         }
414
415         fatal << string_compose (_("programming error: unknown sync source string \"%1\""), str) << endmsg;
416         /*NOTREACHED*/
417         return JACK;
418 }
419
420 const char*
421 sync_source_to_string (SyncSource src)
422 {
423         switch (src) {
424         case JACK:
425                 return _("JACK");
426
427         case MTC:
428                 return _("MIDI Timecode");
429
430         case MIDIClock:
431                 return _("MIDI Clock");
432         }
433         /* GRRRR .... stupid, stupid gcc - you can't get here from there, all enum values are handled */
434         return _("JACK");
435 }
436
437 float
438 meter_falloff_to_float (MeterFalloff falloff)
439 {
440         switch (falloff) {
441         case MeterFalloffOff:
442                 return METER_FALLOFF_OFF;
443         case MeterFalloffSlowest:
444                 return METER_FALLOFF_SLOWEST;
445         case MeterFalloffSlow:
446                 return METER_FALLOFF_SLOW;
447         case MeterFalloffMedium:
448                 return METER_FALLOFF_MEDIUM;
449         case MeterFalloffFast:
450                 return METER_FALLOFF_FAST;
451         case MeterFalloffFaster:
452                 return METER_FALLOFF_FASTER;
453         case MeterFalloffFastest:
454                 return METER_FALLOFF_FASTEST;
455         default:
456                 return METER_FALLOFF_FAST;
457         }
458 }
459
460 MeterFalloff
461 meter_falloff_from_float (float val)
462 {
463         if (val == METER_FALLOFF_OFF) {
464                 return MeterFalloffOff;
465         }
466         else if (val <= METER_FALLOFF_SLOWEST) {
467                 return MeterFalloffSlowest;
468         }
469         else if (val <= METER_FALLOFF_SLOW) {
470                 return MeterFalloffSlow;
471         }
472         else if (val <= METER_FALLOFF_MEDIUM) {
473                 return MeterFalloffMedium;
474         }
475         else if (val <= METER_FALLOFF_FAST) {
476                 return MeterFalloffFast;
477         }
478         else if (val <= METER_FALLOFF_FASTER) {
479                 return MeterFalloffFaster;
480         }
481         else {
482                 return MeterFalloffFastest;
483         }
484 }
485
486 AutoState
487 ARDOUR::string_to_auto_state (std::string str)
488 {
489         if (str == X_("Off")) {
490                 return Off;
491         } else if (str == X_("Play")) {
492                 return Play;
493         } else if (str == X_("Write")) {
494                 return Write;
495         } else if (str == X_("Touch")) {
496                 return Touch;
497         }
498
499         fatal << string_compose (_("programming error: %1 %2"), "illegal AutoState string: ", str) << endmsg;
500         /*NOTREACHED*/
501         return Touch;
502 }
503
504 string
505 ARDOUR::auto_state_to_string (AutoState as)
506 {
507         /* to be used only for XML serialization, no i18n done */
508
509         switch (as) {
510         case Off:
511                 return X_("Off");
512                 break;
513         case Play:
514                 return X_("Play");
515                 break;
516         case Write:
517                 return X_("Write");
518                 break;
519         case Touch:
520                 return X_("Touch");
521         }
522
523         fatal << string_compose (_("programming error: %1 %2"), "illegal AutoState type: ", as) << endmsg;
524         /*NOTREACHED*/
525         return "";
526 }
527
528 AutoStyle
529 ARDOUR::string_to_auto_style (std::string str)
530 {
531         if (str == X_("Absolute")) {
532                 return Absolute;
533         } else if (str == X_("Trim")) {
534                 return Trim;
535         }
536
537         fatal << string_compose (_("programming error: %1 %2"), "illegal AutoStyle string: ", str) << endmsg;
538         /*NOTREACHED*/
539         return Trim;
540 }
541
542 string
543 ARDOUR::auto_style_to_string (AutoStyle as)
544 {
545         /* to be used only for XML serialization, no i18n done */
546
547         switch (as) {
548         case Absolute:
549                 return X_("Absolute");
550                 break;
551         case Trim:
552                 return X_("Trim");
553                 break;
554         }
555
556         fatal << string_compose (_("programming error: %1 %2"), "illegal AutoStyle type: ", as) << endmsg;
557         /*NOTREACHED*/
558         return "";
559 }
560
561 std::string
562 bool_as_string (bool yn)
563 {
564         return (yn ? "yes" : "no");
565 }
566
567 bool
568 string_is_affirmative (const std::string& str)
569 {
570         /* to be used only with XML data - not intended to handle user input */
571
572         return str == "1" || str == "y" || str == "Y" || (!g_strncasecmp(str.c_str(), "yes", str.length()));
573 }
574
575 const char*
576 native_header_format_extension (HeaderFormat hf, const DataType& type)
577 {
578         if (type == DataType::MIDI) {
579                 return ".mid";
580         }
581         
582         switch (hf) {
583         case BWF:
584                 return ".wav";
585         case WAVE:
586                 return ".wav";
587         case WAVE64:
588                 return ".w64";
589         case CAF:
590                 return ".caf";
591         case AIFF:
592                 return ".aif";
593         case iXML:
594                 return ".ixml";
595         case RF64:
596                 return ".rf64";
597         }
598
599         fatal << string_compose (_("programming error: unknown native header format: %1"), hf);
600         /*NOTREACHED*/
601         return ".wav";
602 }
603
604 bool
605 matching_unsuffixed_filename_exists_in (const string& dir, const string& path)
606 {
607         string bws = basename_nosuffix (path);
608         struct dirent* dentry;
609         struct stat statbuf;
610         DIR* dead;
611         bool ret = false;
612
613         if ((dead = ::opendir (dir.c_str())) == 0) {
614                 error << string_compose (_("cannot open directory %1 (%2)"), dir, strerror (errno)) << endl;
615                 return false;
616         }
617         
618         while ((dentry = ::readdir (dead)) != 0) {
619                 
620                 /* avoid '.' and '..' */
621                 
622                 if ((dentry->d_name[0] == '.' && dentry->d_name[1] == '\0') ||
623                     (dentry->d_name[2] == '\0' && dentry->d_name[0] == '.' && dentry->d_name[1] == '.')) {
624                         continue;
625                 }
626         
627                 string fullpath = Glib::build_filename (dir, dentry->d_name);
628
629                 if (::stat (fullpath.c_str(), &statbuf)) {
630                         continue;
631                 }
632                 
633                 if (!S_ISREG (statbuf.st_mode)) {
634                         continue;
635                 }
636
637                 string bws2 = basename_nosuffix (dentry->d_name);
638                 
639                 if (bws2 == bws) {
640                         ret = true;
641                         break;
642                 }
643         }
644
645         ::closedir (dead);
646         return ret;
647 }
648
649 extern "C" {
650         void c_stacktrace() { stacktrace (cerr); }
651 }