Preferences.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. #include "core/Preferences.h"
  2. #include <algorithm>
  3. #include <cctype>
  4. #include <cmath>
  5. #include <cstdio>
  6. #include <sstream>
  7. namespace lynx::prefs
  8. {
  9. namespace
  10. {
  11. std::string trim (const std::string& s)
  12. {
  13. auto a = s.find_first_not_of (" \t\r\n");
  14. if (a == std::string::npos)
  15. return {};
  16. auto b = s.find_last_not_of (" \t\r\n");
  17. return s.substr (a, b - a + 1);
  18. }
  19. std::string lower (std::string s)
  20. {
  21. for (auto& c : s)
  22. c = (char) std::tolower ((unsigned char) c);
  23. return s;
  24. }
  25. int toInt (const std::string& s, int fallback)
  26. {
  27. try
  28. {
  29. std::size_t used = 0;
  30. const auto v = std::stoi (s, &used);
  31. return used > 0 ? v : fallback;
  32. }
  33. catch (...)
  34. {
  35. return fallback;
  36. }
  37. }
  38. } // namespace
  39. std::map<std::string, std::string> parseKeyValues (const std::string& text)
  40. {
  41. std::map<std::string, std::string> out;
  42. std::istringstream in (text);
  43. std::string line;
  44. while (std::getline (in, line))
  45. {
  46. const auto eq = line.find ('=');
  47. if (eq == std::string::npos)
  48. continue;
  49. const auto key = trim (line.substr (0, eq));
  50. if (! key.empty())
  51. out[key] = trim (line.substr (eq + 1));
  52. }
  53. return out;
  54. }
  55. // --- autosave ---------------------------------------------------------------------------------------------------
  56. const std::vector<int>& autosaveIntervals()
  57. {
  58. static const std::vector<int> list { 0, 1, 2, 5, 10, 15, 30 };
  59. return list;
  60. }
  61. int clampAutosaveMinutes (int minutes)
  62. {
  63. if (minutes <= 0)
  64. return 0;
  65. auto best = autosaveIntervals()[1];
  66. for (auto m : autosaveIntervals())
  67. if (m > 0 && std::abs (m - minutes) < std::abs (best - minutes))
  68. best = m;
  69. return best;
  70. }
  71. int clampAutosaveKeep (int keep) { return std::clamp (keep, 1, 100); }
  72. std::string backupName (const std::string& stem, int year, int month, int day, int hour, int minute, int second)
  73. {
  74. char stamp[48];
  75. std::snprintf (stamp, sizeof (stamp), " (%04d-%02d-%02d %02d.%02d.%02d)", year, month, day, hour, minute, second);
  76. return stem + stamp;
  77. }
  78. bool isBackupOf (const std::string& name, const std::string& stem)
  79. {
  80. if (name == stem)
  81. return true;
  82. // stem + " (YYYY-MM-DD HH.MM.SS)"
  83. constexpr std::size_t stampLength = 22;
  84. if (name.size() != stem.size() + stampLength || name.compare (0, stem.size(), stem) != 0)
  85. return false;
  86. const auto stamp = name.substr (stem.size());
  87. const char* pattern = " (dddd-dd-dd dd.dd.dd)";
  88. for (std::size_t i = 0; i < stampLength; ++i)
  89. if (pattern[i] == 'd' ? ! std::isdigit ((unsigned char) stamp[i]) : stamp[i] != pattern[i])
  90. return false;
  91. return true;
  92. }
  93. std::vector<std::string> backupsToRemove (const std::vector<std::string>& names, const std::string& stem, int keep)
  94. {
  95. std::vector<std::string> mine;
  96. for (const auto& n : names)
  97. if (isBackupOf (n, stem))
  98. mine.push_back (n);
  99. // the plain "stem" (an older version's single backup) counts as the oldest
  100. std::sort (mine.begin(), mine.end(), [&stem] (const std::string& a, const std::string& b) {
  101. if ((a == stem) != (b == stem))
  102. return a == stem;
  103. return a < b;
  104. });
  105. const auto k = (std::size_t) clampAutosaveKeep (keep);
  106. if (mine.size() <= k)
  107. return {};
  108. mine.resize (mine.size() - k);
  109. return mine;
  110. }
  111. int clampUndoLevels (int levels) { return std::clamp (levels, 10, 1000); }
  112. double bufferLatencyMs (int bufferSamples, double sampleRate)
  113. {
  114. return sampleRate > 0.0 ? 1000.0 * bufferSamples / sampleRate : 0.0;
  115. }
  116. DriverKind driverKind (const std::string& typeName)
  117. {
  118. if (typeName == "Windows Audio")
  119. return DriverKind::wasapiShared;
  120. if (typeName == "Windows Audio (Low Latency Mode)")
  121. return DriverKind::wasapiLowLatency;
  122. if (typeName == "Windows Audio (Exclusive Mode)")
  123. return DriverKind::wasapiExclusive;
  124. if (typeName == "DirectSound")
  125. return DriverKind::directSound;
  126. if (typeName == "ASIO")
  127. return DriverKind::asio;
  128. if (typeName == "LYNX ASIO")
  129. return DriverKind::lynxAsio;
  130. if (typeName == "CoreAudio")
  131. return DriverKind::coreAudio;
  132. if (typeName == "ALSA")
  133. return DriverKind::alsa;
  134. if (typeName == "JACK")
  135. return DriverKind::jack;
  136. return DriverKind::other;
  137. }
  138. std::vector<int> usableBufferSizes (DriverKind kind, const std::vector<int>& offered, int devicePeriod)
  139. {
  140. if (kind != DriverKind::wasapiShared || devicePeriod <= 0)
  141. return offered;
  142. std::vector<int> kept;
  143. for (const auto size : offered)
  144. if (size >= devicePeriod)
  145. kept.push_back (size);
  146. return kept.empty() ? offered : kept;
  147. }
  148. int safeBufferSize (const std::vector<int>& available, int current, double sampleRate)
  149. {
  150. const int target = sampleRate > 50000.0 ? (sampleRate > 100000.0 ? 2048 : 1024) : 512;
  151. if (current >= target)
  152. return current;
  153. int best = 0, largest = 0;
  154. for (const auto b : available)
  155. {
  156. largest = std::max (largest, b);
  157. if (b >= target && (best == 0 || b < best))
  158. best = b;
  159. }
  160. if (best == 0)
  161. best = std::max (largest, current);
  162. return best;
  163. }
  164. // --- MIDI -------------------------------------------------------------------------------------------------------
  165. float mapVelocity (float velocity, VelocityCurve curve) noexcept
  166. {
  167. const auto v = std::clamp (velocity, 0.0f, 1.0f);
  168. if (v <= 0.0f)
  169. return 0.0f;
  170. switch (curve)
  171. {
  172. case VelocityCurve::soft: return std::pow (v, 0.6f);
  173. case VelocityCurve::hard: return std::pow (v, 1.7f);
  174. case VelocityCurve::fixed: return 1.0f;
  175. case VelocityCurve::linear: break;
  176. }
  177. return v;
  178. }
  179. MidiInputPrefs MidiPrefs::input (const std::string& name) const
  180. {
  181. for (const auto& i : inputs)
  182. if (i.name == name)
  183. return i;
  184. MidiInputPrefs d;
  185. d.name = name;
  186. return d;
  187. }
  188. void MidiPrefs::setInput (const MidiInputPrefs& in)
  189. {
  190. MidiInputPrefs defaults;
  191. defaults.name = in.name;
  192. inputs.erase (std::remove_if (inputs.begin(), inputs.end(), [&] (const MidiInputPrefs& i) { return i.name == in.name; }), inputs.end());
  193. if (! (in == defaults)) // only the changed devices are kept
  194. inputs.push_back (in);
  195. }
  196. bool MidiPrefs::accepts (const std::string& device, int channel) const
  197. {
  198. const auto i = input (device);
  199. return i.enabled && (i.midiChannel == 0 || i.midiChannel == channel);
  200. }
  201. namespace
  202. {
  203. const char* curveName (VelocityCurve c)
  204. {
  205. switch (c)
  206. {
  207. case VelocityCurve::soft: return "soft";
  208. case VelocityCurve::hard: return "hard";
  209. case VelocityCurve::fixed: return "fixed";
  210. case VelocityCurve::linear: break;
  211. }
  212. return "linear";
  213. }
  214. // device names may hold '=' or '|'; they are written last on the line
  215. std::vector<std::string> split (const std::string& s, char sep, std::size_t maxParts)
  216. {
  217. std::vector<std::string> parts;
  218. std::size_t start = 0;
  219. while (parts.size() + 1 < maxParts)
  220. {
  221. const auto p = s.find (sep, start);
  222. if (p == std::string::npos)
  223. break;
  224. parts.push_back (s.substr (start, p - start));
  225. start = p + 1;
  226. }
  227. parts.push_back (s.substr (start));
  228. return parts;
  229. }
  230. } // namespace
  231. std::string MidiPrefs::toText() const
  232. {
  233. std::string out = "velocity=" + std::string (curveName (velocity)) + "\npickup=" + (pickup ? "1" : "0") + "\n";
  234. // input=<enabled>|<midi channel>|<target>|<device name>
  235. for (const auto& i : inputs)
  236. out += "input=" + std::string (i.enabled ? "1" : "0") + "|" + std::to_string (i.midiChannel) + "|" + std::to_string (i.target) + "|" + i.name + "\n";
  237. return out;
  238. }
  239. MidiPrefs MidiPrefs::fromText (const std::string& text)
  240. {
  241. MidiPrefs p;
  242. std::istringstream in (text);
  243. std::string line;
  244. while (std::getline (in, line))
  245. {
  246. if (! line.empty() && line.back() == '\r')
  247. line.pop_back();
  248. const auto eq = line.find ('=');
  249. if (eq == std::string::npos)
  250. continue;
  251. const auto key = trim (line.substr (0, eq));
  252. const auto value = line.substr (eq + 1);
  253. if (key == "velocity")
  254. {
  255. const auto v = trim (value);
  256. p.velocity = v == "soft" ? VelocityCurve::soft : v == "hard" ? VelocityCurve::hard : v == "fixed" ? VelocityCurve::fixed : VelocityCurve::linear;
  257. }
  258. else if (key == "pickup")
  259. p.pickup = trim (value) == "1";
  260. else if (key == "input")
  261. {
  262. const auto parts = split (value, '|', 4);
  263. if (parts.size() != 4 || parts[3].empty())
  264. continue;
  265. MidiInputPrefs i;
  266. i.enabled = trim (parts[0]) != "0";
  267. i.midiChannel = std::clamp (toInt (trim (parts[1]), 0), 0, 16);
  268. i.target = std::max (-1, toInt (trim (parts[2]), -1));
  269. i.name = parts[3];
  270. p.setInput (i);
  271. }
  272. }
  273. return p;
  274. }
  275. bool pickupReached (float parameter, float previous, float incoming, float tolerance) noexcept
  276. {
  277. if (std::abs (incoming - parameter) <= tolerance)
  278. return true;
  279. if (previous < 0.0f)
  280. return false;
  281. // crossed it between the last value and this one
  282. return (previous - parameter) * (incoming - parameter) < 0.0f;
  283. }
  284. bool pickupUpdate (PickupState& state, float parameter, float incoming, float tolerance) noexcept
  285. {
  286. if (state.caught && std::abs (parameter - state.lastSet) > tolerance)
  287. state.caught = false; // moved by the mouse, automation or an undo
  288. if (! state.caught)
  289. state.caught = pickupReached (parameter, state.lastController, incoming, tolerance);
  290. state.lastController = incoming;
  291. if (state.caught)
  292. state.lastSet = incoming;
  293. return state.caught;
  294. }
  295. // --- plugin manager ---------------------------------------------------------------------------------------------
  296. std::vector<int> visiblePlugins (const std::vector<PluginRow>& rows, const std::string& query, PluginFilter filter, PluginSort sort, bool descending)
  297. {
  298. std::vector<std::string> words;
  299. {
  300. std::istringstream in (lower (query));
  301. std::string w;
  302. while (in >> w)
  303. words.push_back (w);
  304. }
  305. std::vector<int> out;
  306. for (int i = 0; i < (int) rows.size(); ++i)
  307. {
  308. const auto& r = rows[(std::size_t) i];
  309. switch (filter)
  310. {
  311. case PluginFilter::instruments: if (! r.instrument || r.status == PluginStatus::failed) continue; break;
  312. case PluginFilter::effects: if (r.instrument || r.status == PluginStatus::failed) continue; break;
  313. case PluginFilter::favourites: if (! r.favourite) continue; break;
  314. case PluginFilter::failed: if (r.status == PluginStatus::ok) continue; break;
  315. case PluginFilter::all: break;
  316. }
  317. const auto hay = lower (r.name + "\n" + r.vendor + "\n" + r.format + "\n" + r.category + "\n" + r.file);
  318. if (std::all_of (words.begin(), words.end(), [&hay] (const std::string& w) { return hay.find (w) != std::string::npos; }))
  319. out.push_back (i);
  320. }
  321. auto key = [&rows, sort] (int i) -> std::string {
  322. const auto& r = rows[(std::size_t) i];
  323. switch (sort)
  324. {
  325. case PluginSort::vendor: return lower (r.vendor);
  326. case PluginSort::format: return lower (r.format);
  327. case PluginSort::type: return r.instrument ? "0" : "1";
  328. case PluginSort::status: return std::to_string ((int) r.status);
  329. case PluginSort::name: break;
  330. }
  331. return lower (r.name);
  332. };
  333. std::stable_sort (out.begin(), out.end(), [&] (int a, int b) {
  334. const auto ka = key (a), kb = key (b);
  335. if (ka != kb)
  336. return descending ? ka > kb : ka < kb;
  337. return lower (rows[(std::size_t) a].name) < lower (rows[(std::size_t) b].name);
  338. });
  339. return out;
  340. }
  341. std::set<std::string> parseFavourites (const std::string& text)
  342. {
  343. std::set<std::string> out;
  344. std::istringstream in (text);
  345. std::string line;
  346. while (std::getline (in, line))
  347. if (const auto t = trim (line); ! t.empty())
  348. out.insert (t);
  349. return out;
  350. }
  351. std::string formatFavourites (const std::set<std::string>& ids)
  352. {
  353. std::string out;
  354. for (const auto& id : ids)
  355. out += id + "\n";
  356. return out;
  357. }
  358. } // namespace lynx::prefs