Make an empty-string non-affirmative so that AxisView::set_marked_for_display works...
[ardour2.git] / libs / ardour / utils.cc
blob4b7fdc2f9118325eddf2c9e10fdd8fbfc62248a8
1 /*
2 Copyright (C) 2000-2003 Paul Davis
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.
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.
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.
20 #ifdef WAF_BUILD
21 #include "libardour-config.h"
22 #endif
24 #include <stdint.h>
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>
40 #include <glibmm/miscutils.h>
41 #include <glibmm/fileutils.h>
43 #ifdef HAVE_WORDEXP
44 #include <wordexp.h>
45 #endif
47 #include "pbd/cpus.h"
48 #include "pbd/error.h"
49 #include "pbd/stacktrace.h"
50 #include "pbd/xml++.h"
51 #include "pbd/basename.h"
52 #include "pbd/strsplit.h"
54 #include "ardour/utils.h"
55 #include "ardour/rc_configuration.h"
57 #include "i18n.h"
59 using namespace ARDOUR;
60 using namespace std;
61 using namespace PBD;
63 string
64 legalize_for_path (const string& str)
66 string::size_type pos;
67 string illegal_chars = "/\\"; /* DOS, POSIX. Yes, we're going to ignore HFS */
68 string legal;
70 legal = str;
71 pos = 0;
73 while ((pos = legal.find_first_of (illegal_chars, pos)) != string::npos) {
74 legal.replace (pos, 1, "_");
75 pos += 1;
78 return legal;
81 string
82 bump_name_once (const std::string& name, char delimiter)
84 string::size_type delim;
85 string newname;
87 if ((delim = name.find_last_of (delimiter)) == string::npos) {
88 newname = name;
89 newname += delimiter;
90 newname += "1";
91 } else {
92 int isnumber = 1;
93 const char *last_element = name.c_str() + delim + 1;
94 for (size_t i = 0; i < strlen(last_element); i++) {
95 if (!isdigit(last_element[i])) {
96 isnumber = 0;
97 break;
101 errno = 0;
102 int32_t version = strtol (name.c_str()+delim+1, (char **)NULL, 10);
104 if (isnumber == 0 || errno != 0) {
105 // last_element is not a number, or is too large
106 newname = name;
107 newname += delimiter;
108 newname += "1";
109 } else {
110 char buf[32];
112 snprintf (buf, sizeof(buf), "%d", version+1);
114 newname = name.substr (0, delim+1);
115 newname += buf;
119 return newname;
123 bool
124 could_be_a_valid_path (const string& path)
126 vector<string> posix_dirs;
127 vector<string> dos_dirs;
128 string testpath;
130 split (path, posix_dirs, '/');
131 split (path, dos_dirs, '\\');
133 /* remove the last component of each */
135 posix_dirs.erase (--posix_dirs.end());
136 dos_dirs.erase (--dos_dirs.end());
138 if (G_DIR_SEPARATOR == '/') {
139 for (vector<string>::iterator x = posix_dirs.begin(); x != posix_dirs.end(); ++x) {
140 testpath = Glib::build_filename (testpath, *x);
141 cerr << "Testing " << testpath << endl;
142 if (!Glib::file_test (testpath, Glib::FILE_TEST_IS_DIR|Glib::FILE_TEST_EXISTS)) {
143 return false;
148 if (G_DIR_SEPARATOR == '\\') {
149 testpath = "";
150 for (vector<string>::iterator x = dos_dirs.begin(); x != dos_dirs.end(); ++x) {
151 testpath = Glib::build_filename (testpath, *x);
152 cerr << "Testing " << testpath << endl;
153 if (!Glib::file_test (testpath, Glib::FILE_TEST_IS_DIR|Glib::FILE_TEST_EXISTS)) {
154 return false;
159 return true;
163 XMLNode *
164 find_named_node (const XMLNode& node, string name)
166 XMLNodeList nlist;
167 XMLNodeConstIterator niter;
168 XMLNode* child;
170 nlist = node.children();
172 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
174 child = *niter;
176 if (child->name() == name) {
177 return child;
181 return 0;
185 cmp_nocase (const string& s, const string& s2)
187 string::const_iterator p = s.begin();
188 string::const_iterator p2 = s2.begin();
190 while (p != s.end() && p2 != s2.end()) {
191 if (toupper(*p) != toupper(*p2)) {
192 return (toupper(*p) < toupper(*p2)) ? -1 : 1;
194 ++p;
195 ++p2;
198 return (s2.size() == s.size()) ? 0 : (s.size() < s2.size()) ? -1 : 1;
202 touch_file (string path)
204 int fd = open (path.c_str(), O_RDWR|O_CREAT, 0660);
205 if (fd >= 0) {
206 close (fd);
207 return 0;
209 return 1;
212 string
213 region_name_from_path (string path, bool strip_channels, bool add_channel_suffix, uint32_t total, uint32_t this_one)
215 path = PBD::basename_nosuffix (path);
217 if (strip_channels) {
219 /* remove any "?R", "?L" or "?[a-z]" channel identifier */
221 string::size_type len = path.length();
223 if (len > 3 && (path[len-2] == '%' || path[len-2] == '?' || path[len-2] == '.') &&
224 (path[len-1] == 'R' || path[len-1] == 'L' || (islower (path[len-1])))) {
226 path = path.substr (0, path.length() - 2);
230 if (add_channel_suffix) {
232 path += '%';
234 if (total > 2) {
235 path += (char) ('a' + this_one);
236 } else {
237 path += (char) (this_one == 0 ? 'L' : 'R');
241 return path;
244 bool
245 path_is_paired (string path, string& pair_base)
247 string::size_type pos;
249 /* remove any leading path */
251 if ((pos = path.find_last_of (G_DIR_SEPARATOR)) != string::npos) {
252 path = path.substr(pos+1);
255 /* remove filename suffixes etc. */
257 if ((pos = path.find_last_of ('.')) != string::npos) {
258 path = path.substr (0, pos);
261 string::size_type len = path.length();
263 /* look for possible channel identifier: "?R", "%R", ".L" etc. */
265 if (len > 3 && (path[len-2] == '%' || path[len-2] == '?' || path[len-2] == '.') &&
266 (path[len-1] == 'R' || path[len-1] == 'L' || (islower (path[len-1])))) {
268 pair_base = path.substr (0, len-2);
269 return true;
273 return false;
276 string
277 path_expand (string path)
279 if (path.empty()) {
280 return path;
283 #ifdef HAVE_WORDEXP
284 /* Handle tilde and environment variable expansion in session path */
285 string ret = path;
287 wordexp_t expansion;
288 switch (wordexp (path.c_str(), &expansion, WRDE_NOCMD|WRDE_UNDEF)) {
289 case 0:
290 break;
291 default:
292 error << string_compose (_("illegal or badly-formed string used for path (%1)"), path) << endmsg;
293 goto out;
296 if (expansion.we_wordc > 1) {
297 error << string_compose (_("path (%1) is ambiguous"), path) << endmsg;
298 goto out;
301 ret = expansion.we_wordv[0];
302 out:
303 wordfree (&expansion);
304 return ret;
306 #else
307 return path;
308 #endif
311 #if __APPLE__
312 string
313 CFStringRefToStdString(CFStringRef stringRef)
315 CFIndex size =
316 CFStringGetMaximumSizeForEncoding(CFStringGetLength(stringRef) ,
317 kCFStringEncodingUTF8);
318 char *buf = new char[size];
320 std::string result;
322 if(CFStringGetCString(stringRef, buf, size, kCFStringEncodingUTF8)) {
323 result = buf;
325 delete [] buf;
326 return result;
328 #endif // __APPLE__
330 void
331 compute_equal_power_fades (framecnt_t nframes, float* in, float* out)
333 double step;
335 step = 1.0/(nframes-1);
337 in[0] = 0.0f;
339 for (framecnt_t i = 1; i < nframes - 1; ++i) {
340 in[i] = in[i-1] + step;
343 in[nframes-1] = 1.0;
345 const float pan_law_attenuation = -3.0f;
346 const float scale = 2.0f - 4.0f * powf (10.0f,pan_law_attenuation/20.0f);
348 for (framecnt_t n = 0; n < nframes; ++n) {
349 float inVal = in[n];
350 float outVal = 1 - inVal;
351 out[n] = outVal * (scale * outVal + 1.0f - scale);
352 in[n] = inVal * (scale * inVal + 1.0f - scale);
356 EditMode
357 string_to_edit_mode (string str)
359 if (str == _("Splice")) {
360 return Splice;
361 } else if (str == _("Slide")) {
362 return Slide;
363 } else if (str == _("Lock")) {
364 return Lock;
366 fatal << string_compose (_("programming error: unknown edit mode string \"%1\""), str) << endmsg;
367 /*NOTREACHED*/
368 return Slide;
371 const char*
372 edit_mode_to_string (EditMode mode)
374 switch (mode) {
375 case Slide:
376 return _("Slide");
378 case Lock:
379 return _("Lock");
381 default:
382 case Splice:
383 return _("Splice");
387 SyncSource
388 string_to_sync_source (string str)
390 if (str == _("MIDI Timecode") || str == _("MTC")) {
391 return MTC;
394 if (str == _("MIDI Clock")) {
395 return MIDIClock;
398 if (str == _("JACK")) {
399 return JACK;
402 fatal << string_compose (_("programming error: unknown sync source string \"%1\""), str) << endmsg;
403 /*NOTREACHED*/
404 return JACK;
407 /** @param sh Return a short version of the string */
408 const char*
409 sync_source_to_string (SyncSource src, bool sh)
411 switch (src) {
412 case JACK:
413 return _("JACK");
415 case MTC:
416 if (sh) {
417 return _("MTC");
418 } else {
419 return _("MIDI Timecode");
422 case MIDIClock:
423 return _("MIDI Clock");
425 /* GRRRR .... stupid, stupid gcc - you can't get here from there, all enum values are handled */
426 return _("JACK");
429 float
430 meter_falloff_to_float (MeterFalloff falloff)
432 switch (falloff) {
433 case MeterFalloffOff:
434 return METER_FALLOFF_OFF;
435 case MeterFalloffSlowest:
436 return METER_FALLOFF_SLOWEST;
437 case MeterFalloffSlow:
438 return METER_FALLOFF_SLOW;
439 case MeterFalloffMedium:
440 return METER_FALLOFF_MEDIUM;
441 case MeterFalloffFast:
442 return METER_FALLOFF_FAST;
443 case MeterFalloffFaster:
444 return METER_FALLOFF_FASTER;
445 case MeterFalloffFastest:
446 return METER_FALLOFF_FASTEST;
447 default:
448 return METER_FALLOFF_FAST;
452 MeterFalloff
453 meter_falloff_from_float (float val)
455 if (val == METER_FALLOFF_OFF) {
456 return MeterFalloffOff;
458 else if (val <= METER_FALLOFF_SLOWEST) {
459 return MeterFalloffSlowest;
461 else if (val <= METER_FALLOFF_SLOW) {
462 return MeterFalloffSlow;
464 else if (val <= METER_FALLOFF_MEDIUM) {
465 return MeterFalloffMedium;
467 else if (val <= METER_FALLOFF_FAST) {
468 return MeterFalloffFast;
470 else if (val <= METER_FALLOFF_FASTER) {
471 return MeterFalloffFaster;
473 else {
474 return MeterFalloffFastest;
478 AutoState
479 ARDOUR::string_to_auto_state (std::string str)
481 if (str == X_("Off")) {
482 return Off;
483 } else if (str == X_("Play")) {
484 return Play;
485 } else if (str == X_("Write")) {
486 return Write;
487 } else if (str == X_("Touch")) {
488 return Touch;
491 fatal << string_compose (_("programming error: %1 %2"), "illegal AutoState string: ", str) << endmsg;
492 /*NOTREACHED*/
493 return Touch;
496 string
497 ARDOUR::auto_state_to_string (AutoState as)
499 /* to be used only for XML serialization, no i18n done */
501 switch (as) {
502 case Off:
503 return X_("Off");
504 break;
505 case Play:
506 return X_("Play");
507 break;
508 case Write:
509 return X_("Write");
510 break;
511 case Touch:
512 return X_("Touch");
515 fatal << string_compose (_("programming error: %1 %2"), "illegal AutoState type: ", as) << endmsg;
516 /*NOTREACHED*/
517 return "";
520 AutoStyle
521 ARDOUR::string_to_auto_style (std::string str)
523 if (str == X_("Absolute")) {
524 return Absolute;
525 } else if (str == X_("Trim")) {
526 return Trim;
529 fatal << string_compose (_("programming error: %1 %2"), "illegal AutoStyle string: ", str) << endmsg;
530 /*NOTREACHED*/
531 return Trim;
534 string
535 ARDOUR::auto_style_to_string (AutoStyle as)
537 /* to be used only for XML serialization, no i18n done */
539 switch (as) {
540 case Absolute:
541 return X_("Absolute");
542 break;
543 case Trim:
544 return X_("Trim");
545 break;
548 fatal << string_compose (_("programming error: %1 %2"), "illegal AutoStyle type: ", as) << endmsg;
549 /*NOTREACHED*/
550 return "";
553 std::string
554 bool_as_string (bool yn)
556 return (yn ? "yes" : "no");
559 bool
560 string_is_affirmative (const std::string& str)
562 /* to be used only with XML data - not intended to handle user input */
564 if (str.empty ()) {
565 return false;
568 return str == "1" || str == "y" || str == "Y" || (!g_strncasecmp(str.c_str(), "yes", str.length()));
571 const char*
572 native_header_format_extension (HeaderFormat hf, const DataType& type)
574 if (type == DataType::MIDI) {
575 return ".mid";
578 switch (hf) {
579 case BWF:
580 return ".wav";
581 case WAVE:
582 return ".wav";
583 case WAVE64:
584 return ".w64";
585 case CAF:
586 return ".caf";
587 case AIFF:
588 return ".aif";
589 case iXML:
590 return ".ixml";
591 case RF64:
592 return ".rf64";
595 fatal << string_compose (_("programming error: unknown native header format: %1"), hf);
596 /*NOTREACHED*/
597 return ".wav";
600 bool
601 matching_unsuffixed_filename_exists_in (const string& dir, const string& path)
603 string bws = basename_nosuffix (path);
604 struct dirent* dentry;
605 struct stat statbuf;
606 DIR* dead;
607 bool ret = false;
609 if ((dead = ::opendir (dir.c_str())) == 0) {
610 error << string_compose (_("cannot open directory %1 (%2)"), dir, strerror (errno)) << endl;
611 return false;
614 while ((dentry = ::readdir (dead)) != 0) {
616 /* avoid '.' and '..' */
618 if ((dentry->d_name[0] == '.' && dentry->d_name[1] == '\0') ||
619 (dentry->d_name[2] == '\0' && dentry->d_name[0] == '.' && dentry->d_name[1] == '.')) {
620 continue;
623 string fullpath = Glib::build_filename (dir, dentry->d_name);
625 if (::stat (fullpath.c_str(), &statbuf)) {
626 continue;
629 if (!S_ISREG (statbuf.st_mode)) {
630 continue;
633 string bws2 = basename_nosuffix (dentry->d_name);
635 if (bws2 == bws) {
636 ret = true;
637 break;
641 ::closedir (dead);
642 return ret;
645 uint32_t
646 how_many_dsp_threads ()
648 /* CALLER MUST HOLD PROCESS LOCK */
650 int num_cpu = hardware_concurrency();
651 int pu = Config->get_processor_usage ();
652 uint32_t num_threads = max (num_cpu - 1, 2); // default to number of cpus minus one, or 2, whichever is larger
654 if (pu < 0) {
655 /* pu is negative: use "pu" less cores for DSP than appear to be available
658 if (-pu < num_cpu) {
659 num_threads = num_cpu + pu;
662 } else if (pu == 0) {
664 /* use all available CPUs
667 num_threads = num_cpu;
669 } else {
670 /* use "pu" cores, if available
673 num_threads = min (num_cpu, pu);
676 return num_threads;
679 double gain_to_slider_position_with_max (double g, double max_gain)
681 return gain_to_slider_position (g * 2.0/max_gain);
684 double slider_position_to_gain_with_max (double g, double max_gain)
686 return slider_position_to_gain (g * max_gain/2.0);
689 extern "C" {
690 void c_stacktrace() { stacktrace (cerr); }