OBSApp_Themes.cpp 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  1. /******************************************************************************
  2. Copyright (C) 2023 by Dennis Sädtler <[email protected]>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ******************************************************************************/
  14. #include "OBSApp.hpp"
  15. #include <utility/OBSProxyStyle.hpp>
  16. #include <utility/OBSThemeVariable.hpp>
  17. #include <utility/platform.hpp>
  18. #include <qt-wrappers.hpp>
  19. #include <ui-config.h>
  20. #include <util/cf-parser.h>
  21. #include <QDir>
  22. #include <QDirIterator>
  23. #include <QFile>
  24. #include <QFileSystemWatcher>
  25. #include <QMetaEnum>
  26. #include <QRandomGenerator>
  27. #include <QTimer>
  28. using namespace std;
  29. struct CFParser {
  30. cf_parser cfp = {};
  31. ~CFParser() { cf_parser_free(&cfp); }
  32. operator cf_parser *() { return &cfp; }
  33. cf_parser *operator->() { return &cfp; }
  34. };
  35. static optional<OBSTheme> ParseThemeMeta(const QString &path)
  36. {
  37. QFile themeFile(path);
  38. if (!themeFile.open(QIODeviceBase::ReadOnly))
  39. return nullopt;
  40. OBSTheme meta;
  41. const QByteArray data = themeFile.readAll();
  42. CFParser cfp;
  43. int ret;
  44. if (!cf_parser_parse(cfp, data.constData(), QT_TO_UTF8(path)))
  45. return nullopt;
  46. if (cf_token_is(cfp, "@") || cf_go_to_token(cfp, "@", nullptr)) {
  47. while (cf_next_token(cfp)) {
  48. if (cf_token_is(cfp, "OBSThemeMeta")) {
  49. break;
  50. }
  51. if (!cf_go_to_token(cfp, "@", nullptr))
  52. return nullopt;
  53. }
  54. if (!cf_token_is(cfp, "OBSThemeMeta"))
  55. return nullopt;
  56. if (!cf_next_token(cfp))
  57. return nullopt;
  58. if (!cf_token_is(cfp, "{"))
  59. return nullopt;
  60. for (;;) {
  61. if (!cf_next_token(cfp))
  62. return nullopt;
  63. ret = cf_token_is_type(cfp, CFTOKEN_NAME, "name", nullptr);
  64. if (ret != PARSE_SUCCESS)
  65. break;
  66. string name(cfp->cur_token->str.array, cfp->cur_token->str.len);
  67. ret = cf_next_token_should_be(cfp, ":", ";", nullptr);
  68. if (ret != PARSE_SUCCESS)
  69. continue;
  70. if (!cf_next_token(cfp))
  71. return nullopt;
  72. ret = cf_token_is_type(cfp, CFTOKEN_STRING, "value", ";");
  73. if (ret != PARSE_SUCCESS)
  74. continue;
  75. BPtr str = cf_literal_to_str(cfp->cur_token->str.array, cfp->cur_token->str.len);
  76. if (str) {
  77. if (name == "dark")
  78. meta.isDark = strcmp(str, "true") == 0;
  79. else if (name == "extends")
  80. meta.extends = str;
  81. else if (name == "author")
  82. meta.author = str;
  83. else if (name == "id")
  84. meta.id = str;
  85. else if (name == "name")
  86. meta.name = str;
  87. }
  88. if (!cf_go_to_token(cfp, ";", nullptr))
  89. return nullopt;
  90. }
  91. }
  92. auto filepath = filesystem::u8path(path.toStdString());
  93. meta.isBaseTheme = filepath.extension() == ".obt";
  94. meta.filename = filepath.stem();
  95. if (meta.id.isEmpty() || meta.name.isEmpty() || (!meta.isBaseTheme && meta.extends.isEmpty())) {
  96. /* Theme is invalid */
  97. return nullopt;
  98. } else {
  99. meta.location = absolute(filepath);
  100. meta.isHighContrast = path.endsWith(".oha");
  101. meta.isVisible = !path.contains("System");
  102. }
  103. return meta;
  104. }
  105. static bool ParseVarName(CFParser &cfp, QString &value)
  106. {
  107. int ret;
  108. ret = cf_next_token_should_be(cfp, "(", ";", nullptr);
  109. if (ret != PARSE_SUCCESS)
  110. return false;
  111. ret = cf_next_token_should_be(cfp, "-", ";", nullptr);
  112. if (ret != PARSE_SUCCESS)
  113. return false;
  114. ret = cf_next_token_should_be(cfp, "-", ";", nullptr);
  115. if (ret != PARSE_SUCCESS)
  116. return false;
  117. if (!cf_next_token(cfp))
  118. return false;
  119. value = QString::fromUtf8(cfp->cur_token->str.array, cfp->cur_token->str.len);
  120. ret = cf_next_token_should_be(cfp, ")", ";", nullptr);
  121. if (ret != PARSE_SUCCESS)
  122. return false;
  123. return !value.isEmpty();
  124. }
  125. static QColor ParseColor(CFParser &cfp)
  126. {
  127. const char *array;
  128. uint32_t color = 0;
  129. QColor res(QColor::Invalid);
  130. if (cf_token_is(cfp, "#")) {
  131. if (!cf_next_token(cfp))
  132. return res;
  133. color = strtol(cfp->cur_token->str.array, nullptr, 16);
  134. } else if (cf_token_is(cfp, "rgb")) {
  135. int ret = cf_next_token_should_be(cfp, "(", ";", nullptr);
  136. if (ret != PARSE_SUCCESS || !cf_next_token(cfp))
  137. return res;
  138. array = cfp->cur_token->str.array;
  139. color |= strtol(array, nullptr, 10) << 16;
  140. ret = cf_next_token_should_be(cfp, ",", ";", nullptr);
  141. if (ret != PARSE_SUCCESS || !cf_next_token(cfp))
  142. return res;
  143. array = cfp->cur_token->str.array;
  144. color |= strtol(array, nullptr, 10) << 8;
  145. ret = cf_next_token_should_be(cfp, ",", ";", nullptr);
  146. if (ret != PARSE_SUCCESS || !cf_next_token(cfp))
  147. return res;
  148. array = cfp->cur_token->str.array;
  149. color |= strtol(array, nullptr, 10);
  150. ret = cf_next_token_should_be(cfp, ")", ";", nullptr);
  151. if (ret != PARSE_SUCCESS)
  152. return res;
  153. } else if (cf_token_is(cfp, "bikeshed")) {
  154. color |= QRandomGenerator::global()->bounded(INT8_MAX) << 16;
  155. color |= QRandomGenerator::global()->bounded(INT8_MAX) << 8;
  156. color |= QRandomGenerator::global()->bounded(INT8_MAX);
  157. }
  158. res = color;
  159. return res;
  160. }
  161. static bool ParseMath(CFParser &cfp, QStringList &values, vector<OBSThemeVariable> &vars)
  162. {
  163. int ret = cf_next_token_should_be(cfp, "(", ";", nullptr);
  164. if (ret != PARSE_SUCCESS)
  165. return false;
  166. if (!cf_next_token(cfp))
  167. return false;
  168. while (!cf_token_is(cfp, ")")) {
  169. if (cf_token_is(cfp, ";"))
  170. break;
  171. if (cf_token_is(cfp, "calc") || cf_token_is(cfp, "max") || cf_token_is(cfp, "min")) {
  172. /* Internal math operations do not have proper names.
  173. * They are anonymous variables */
  174. OBSThemeVariable var;
  175. QStringList subvalues;
  176. var.name = QString("__unnamed_%1").arg(QRandomGenerator::global()->generate64());
  177. OBSThemeVariable::VariableType varType;
  178. if (cf_token_is(cfp, "calc"))
  179. varType = OBSThemeVariable::Calc;
  180. else if (cf_token_is(cfp, "max"))
  181. varType = OBSThemeVariable::Max;
  182. else if (cf_token_is(cfp, "min"))
  183. varType = OBSThemeVariable::Min;
  184. if (!ParseMath(cfp, subvalues, vars))
  185. return false;
  186. var.type = varType;
  187. var.value = subvalues;
  188. values << var.name;
  189. vars.push_back(std::move(var));
  190. } else if (cf_token_is(cfp, "var")) {
  191. QString value;
  192. if (!ParseVarName(cfp, value))
  193. return false;
  194. values << value;
  195. } else {
  196. values << QString::fromUtf8(cfp->cur_token->str.array, cfp->cur_token->str.len);
  197. }
  198. if (!cf_next_token(cfp))
  199. return false;
  200. }
  201. return !values.isEmpty();
  202. }
  203. static vector<OBSThemeVariable> ParseThemeVariables(const char *themeData)
  204. {
  205. CFParser cfp;
  206. int ret;
  207. std::vector<OBSThemeVariable> vars;
  208. if (!cf_parser_parse(cfp, themeData, nullptr))
  209. return vars;
  210. if (!cf_token_is(cfp, "@") && !cf_go_to_token(cfp, "@", nullptr))
  211. return vars;
  212. while (cf_next_token(cfp)) {
  213. if (cf_token_is(cfp, "OBSThemeVars"))
  214. break;
  215. if (!cf_go_to_token(cfp, "@", nullptr))
  216. return vars;
  217. }
  218. if (!cf_next_token(cfp))
  219. return {};
  220. if (!cf_token_is(cfp, "{"))
  221. return {};
  222. for (;;) {
  223. if (!cf_next_token(cfp))
  224. return vars;
  225. if (!cf_token_is(cfp, "-"))
  226. return vars;
  227. ret = cf_next_token_should_be(cfp, "-", ";", nullptr);
  228. if (ret != PARSE_SUCCESS)
  229. continue;
  230. if (!cf_next_token(cfp))
  231. return vars;
  232. ret = cf_token_is_type(cfp, CFTOKEN_NAME, "key", nullptr);
  233. if (ret != PARSE_SUCCESS)
  234. break;
  235. QString key = QString::fromUtf8(cfp->cur_token->str.array, cfp->cur_token->str.len);
  236. OBSThemeVariable var;
  237. var.name = key;
  238. #ifdef _WIN32
  239. const QString osPrefix = "os_win_";
  240. #elif __APPLE__
  241. const QString osPrefix = "os_mac_";
  242. #else
  243. const QString osPrefix = "os_lin_";
  244. #endif
  245. if (key.startsWith(osPrefix) && key.length() > osPrefix.length()) {
  246. var.name = key.sliced(osPrefix.length());
  247. }
  248. ret = cf_next_token_should_be(cfp, ":", ";", nullptr);
  249. if (ret != PARSE_SUCCESS)
  250. continue;
  251. if (!cf_next_token(cfp))
  252. return vars;
  253. /* Special values passed to the theme by OBS are prefixed with 'obs', so we
  254. * prevent theme variables from using it as a prefix. */
  255. if (key.startsWith("obs"))
  256. continue;
  257. if (cfp->cur_token->type == CFTOKEN_NUM) {
  258. const char *ch = cfp->cur_token->str.array;
  259. const char *end = ch + cfp->cur_token->str.len;
  260. double f = os_strtod(ch);
  261. var.value = f;
  262. var.type = OBSThemeVariable::Number;
  263. /* Look for a suffix and mark variable as size if it exists */
  264. while (ch < end) {
  265. if (!isdigit(*ch) && !isspace(*ch) && *ch != '.') {
  266. var.suffix = QString::fromUtf8(ch, end - ch);
  267. var.type = OBSThemeVariable::Size;
  268. break;
  269. }
  270. ch++;
  271. }
  272. } else if (cf_token_is(cfp, "rgb") || cf_token_is(cfp, "#") || cf_token_is(cfp, "bikeshed")) {
  273. QColor color = ParseColor(cfp);
  274. if (!color.isValid())
  275. continue;
  276. var.value = color;
  277. var.type = OBSThemeVariable::Color;
  278. } else if (cf_token_is(cfp, "var")) {
  279. QString value;
  280. if (!ParseVarName(cfp, value))
  281. continue;
  282. var.value = value;
  283. var.type = OBSThemeVariable::Alias;
  284. } else if (cf_token_is(cfp, "calc") || cf_token_is(cfp, "max") || cf_token_is(cfp, "min")) {
  285. QStringList values;
  286. if (cf_token_is(cfp, "calc"))
  287. var.type = OBSThemeVariable::Calc;
  288. else if (cf_token_is(cfp, "max"))
  289. var.type = OBSThemeVariable::Max;
  290. else if (cf_token_is(cfp, "min"))
  291. var.type = OBSThemeVariable::Min;
  292. if (!ParseMath(cfp, values, vars))
  293. continue;
  294. var.value = values;
  295. } else {
  296. var.type = OBSThemeVariable::String;
  297. BPtr strVal = cf_literal_to_str(cfp->cur_token->str.array, cfp->cur_token->str.len);
  298. var.value = QString::fromUtf8(strVal.Get());
  299. }
  300. if (!cf_next_token(cfp))
  301. return vars;
  302. if (cf_token_is(cfp, "!") &&
  303. cf_next_token_should_be(cfp, "editable", nullptr, nullptr) == PARSE_SUCCESS) {
  304. if (var.type == OBSThemeVariable::Calc || var.type == OBSThemeVariable::Max ||
  305. var.type == OBSThemeVariable::Min || var.type == OBSThemeVariable::Alias) {
  306. blog(LOG_WARNING, "Math or alias variable type cannot be editable: %s",
  307. QT_TO_UTF8(var.name));
  308. } else {
  309. var.editable = true;
  310. }
  311. }
  312. vars.push_back(std::move(var));
  313. if (!cf_token_is(cfp, ";") && !cf_go_to_token(cfp, ";", nullptr))
  314. return vars;
  315. }
  316. return vars;
  317. }
  318. void OBSApp::FindThemes()
  319. {
  320. QStringList filters;
  321. filters << "*.obt" // OBS Base Theme
  322. << "*.ovt" // OBS Variant Theme
  323. << "*.oha" // OBS High-contrast Adjustment layer
  324. ;
  325. {
  326. string themeDir;
  327. GetDataFilePath("themes/", themeDir);
  328. QDirIterator it(QString::fromStdString(themeDir), filters, QDir::Files);
  329. while (it.hasNext()) {
  330. auto theme = ParseThemeMeta(it.next());
  331. if (theme && !themes.contains(theme->id))
  332. themes[theme->id] = std::move(*theme);
  333. }
  334. }
  335. {
  336. const std::string themeDir = App()->userConfigLocation.u8string() + "/obs-studio/themes";
  337. QDirIterator it(QString::fromStdString(themeDir), filters, QDir::Files);
  338. while (it.hasNext()) {
  339. auto theme = ParseThemeMeta(it.next());
  340. if (theme && !themes.contains(theme->id))
  341. themes[theme->id] = std::move(*theme);
  342. }
  343. }
  344. /* Build dependency tree for all themes, removing ones that have items missing. */
  345. QSet<QString> invalid;
  346. for (OBSTheme &theme : themes) {
  347. if (theme.extends.isEmpty()) {
  348. if (!theme.isBaseTheme) {
  349. blog(LOG_ERROR, R"(Theme "%s" is not base, but does not specify parent!)",
  350. QT_TO_UTF8(theme.id));
  351. invalid.insert(theme.id);
  352. }
  353. continue;
  354. }
  355. QString parentId = theme.extends;
  356. while (!parentId.isEmpty()) {
  357. OBSTheme *parent = GetTheme(parentId);
  358. if (!parent) {
  359. blog(LOG_ERROR, R"(Theme "%s" is missing ancestor "%s"!)", QT_TO_UTF8(theme.id),
  360. QT_TO_UTF8(parentId));
  361. invalid.insert(theme.id);
  362. break;
  363. }
  364. if (theme.isBaseTheme && !parent->isBaseTheme) {
  365. blog(LOG_ERROR, R"(Ancestor "%s" of base theme "%s" is not a base theme!)",
  366. QT_TO_UTF8(parent->id), QT_TO_UTF8(theme.id));
  367. invalid.insert(theme.id);
  368. break;
  369. }
  370. if (parent->id == theme.id || theme.dependencies.contains(parent->id)) {
  371. blog(LOG_ERROR, R"(Dependency chain of "%s" ("%s") contains recursion!)",
  372. QT_TO_UTF8(theme.id), QT_TO_UTF8(parent->id));
  373. invalid.insert(theme.id);
  374. break;
  375. }
  376. /* Mark this theme as a variant of first parent that is a base theme. */
  377. if (!theme.isBaseTheme && parent->isBaseTheme && theme.parent.isEmpty())
  378. theme.parent = parent->id;
  379. theme.dependencies.push_front(parent->id);
  380. parentId = parent->extends;
  381. if (parentId.isEmpty() && !parent->isBaseTheme) {
  382. blog(LOG_ERROR, R"(Final ancestor of "%s" ("%s") is not a base theme!)",
  383. QT_TO_UTF8(theme.id), QT_TO_UTF8(parent->id));
  384. invalid.insert(theme.id);
  385. break;
  386. }
  387. }
  388. }
  389. for (const QString &name : invalid) {
  390. themes.remove(name);
  391. }
  392. }
  393. static bool ResolveVariable(const QHash<QString, OBSThemeVariable> &vars, OBSThemeVariable &var)
  394. {
  395. if (var.type != OBSThemeVariable::Alias)
  396. return true;
  397. QString key = var.value.toString();
  398. while (vars[key].type == OBSThemeVariable::Alias) {
  399. key = vars[key].value.toString();
  400. if (!vars.contains(key)) {
  401. blog(LOG_ERROR, R"(Variable "%s" (aliased by "%s") does not exist!)", QT_TO_UTF8(key),
  402. QT_TO_UTF8(var.name));
  403. return false;
  404. }
  405. }
  406. var = vars[key];
  407. return true;
  408. }
  409. static QString EvalMath(const QHash<QString, OBSThemeVariable> &vars, const OBSThemeVariable &var,
  410. const OBSThemeVariable::VariableType type, const int recursion = 0);
  411. static OBSThemeVariable ParseMathVariable(const QHash<QString, OBSThemeVariable> &vars, const QString &value,
  412. const int recursion = 0)
  413. {
  414. OBSThemeVariable var;
  415. const QByteArray utf8 = value.toUtf8();
  416. const char *data = utf8.constData();
  417. if (isdigit(*data)) {
  418. double f = os_strtod(data);
  419. var.type = OBSThemeVariable::Number;
  420. var.value = f;
  421. const char *dataEnd = data + utf8.size();
  422. while (data < dataEnd) {
  423. if (*data && !isdigit(*data) && *data != '.') {
  424. var.suffix = QString::fromUtf8(data, dataEnd - data);
  425. var.type = OBSThemeVariable::Size;
  426. break;
  427. }
  428. data++;
  429. }
  430. } else {
  431. /* Treat value as an alias/key and resolve it */
  432. var.type = OBSThemeVariable::Alias;
  433. var.value = value;
  434. ResolveVariable(vars, var);
  435. /* Handle nested math calculations */
  436. if (var.type == OBSThemeVariable::Calc || var.type == OBSThemeVariable::Max ||
  437. var.type == OBSThemeVariable::Min) {
  438. QString val = EvalMath(vars, var, var.type, recursion + 1);
  439. var = ParseMathVariable(vars, val);
  440. }
  441. /* Only number or size would be valid here */
  442. if (var.type != OBSThemeVariable::Number && var.type != OBSThemeVariable::Size) {
  443. blog(LOG_ERROR, "Math operand is not a size or number: %s %s %d", QT_TO_UTF8(var.name),
  444. QT_TO_UTF8(var.value.toString()), var.type);
  445. throw invalid_argument("Operand not of numeric type");
  446. }
  447. }
  448. return var;
  449. }
  450. static QString EvalMath(const QHash<QString, OBSThemeVariable> &vars, const OBSThemeVariable &var,
  451. const OBSThemeVariable::VariableType type, const int recursion)
  452. {
  453. if (recursion >= 10) {
  454. /* Abort after 10 levels of recursion */
  455. blog(LOG_ERROR, "Maximum recursion levels hit!");
  456. return "'Invalid expression'";
  457. }
  458. if (type != OBSThemeVariable::Calc && type != OBSThemeVariable::Max && type != OBSThemeVariable::Min) {
  459. blog(LOG_ERROR, "Invalid type for math operation!");
  460. return "'Invalid expression'";
  461. }
  462. QStringList args = var.value.toStringList();
  463. QString &opt = args[1];
  464. if (type == OBSThemeVariable::Calc && (opt != '*' && opt != '+' && opt != '-' && opt != '/')) {
  465. blog(LOG_ERROR, "Unknown/invalid calc() operator: %s", QT_TO_UTF8(opt));
  466. return "'Invalid expression'";
  467. }
  468. if ((type == OBSThemeVariable::Max || type == OBSThemeVariable::Min) && opt != ',') {
  469. blog(LOG_ERROR, "Invalid math separator: %s", QT_TO_UTF8(opt));
  470. return "'Invalid expression'";
  471. }
  472. if (args.length() != 3) {
  473. blog(LOG_ERROR, "Math parse had invalid number of arguments: %lld (%s)", args.length(),
  474. QT_TO_UTF8(args.join(", ")));
  475. return "'Invalid expression'";
  476. }
  477. OBSThemeVariable val1, val2;
  478. try {
  479. val1 = ParseMathVariable(vars, args[0], 0);
  480. val2 = ParseMathVariable(vars, args[2], 0);
  481. } catch (...) {
  482. return "'Invalid expression'";
  483. }
  484. /* Ensure that suffixes match (if any) */
  485. if (!val1.suffix.isEmpty() && !val2.suffix.isEmpty() && val1.suffix != val2.suffix) {
  486. blog(LOG_ERROR, "Math operation requires suffixes to match or only one to be present! %s != %s",
  487. QT_TO_UTF8(val1.suffix), QT_TO_UTF8(val2.suffix));
  488. return "'Invalid expression'";
  489. }
  490. double d1 = val1.userValue.isValid() ? val1.userValue.toDouble() : val1.value.toDouble();
  491. double d2 = val2.userValue.isValid() ? val2.userValue.toDouble() : val2.value.toDouble();
  492. if (!isfinite(d1) || !isfinite(d2)) {
  493. blog(LOG_ERROR,
  494. "At least one invalid math value:"
  495. " op1: %f, op2: %f",
  496. d1, d2);
  497. return "'Invalid expression'";
  498. }
  499. double val = numeric_limits<double>::quiet_NaN();
  500. if (type == OBSThemeVariable::Calc) {
  501. if (opt == "+")
  502. val = d1 + d2;
  503. else if (opt == "-")
  504. val = d1 - d2;
  505. else if (opt == "*")
  506. val = d1 * d2;
  507. else if (opt == "/")
  508. val = d1 / d2;
  509. if (!isnormal(val)) {
  510. blog(LOG_ERROR, "Invalid calc() resulted in non-normal number: %f %s %f = %f", d1,
  511. QT_TO_UTF8(opt), d2, val);
  512. return "'Invalid expression'";
  513. }
  514. } else if (type == OBSThemeVariable::Max) {
  515. val = d1 > d2 ? d1 : d2;
  516. } else if (type == OBSThemeVariable::Min) {
  517. val = d1 < d2 ? d1 : d2;
  518. }
  519. bool isInteger = ceill(val) == val;
  520. QString result = QString::number(val, 'f', isInteger ? 0 : -1);
  521. /* Carry-over suffix */
  522. if (!val1.suffix.isEmpty())
  523. result += val1.suffix;
  524. else if (!val2.suffix.isEmpty())
  525. result += val2.suffix;
  526. return result;
  527. }
  528. static qsizetype FindEndOfOBSMetadata(const QString &content)
  529. {
  530. /* Find end of last OBS-specific section and strip it, kinda jank but should work */
  531. qsizetype end = 0;
  532. for (auto section : {"OBSThemeMeta", "OBSThemeVars", "OBSTheme"}) {
  533. qsizetype idx = content.indexOf(section, 0);
  534. if (idx > end) {
  535. end = content.indexOf('}', idx) + 1;
  536. }
  537. }
  538. return end;
  539. }
  540. static QString PrepareQSS(const QHash<QString, OBSThemeVariable> &vars, const QStringList &contents)
  541. {
  542. QString stylesheet;
  543. QString needleTemplate("var(--%1)");
  544. for (const QString &content : contents) {
  545. qsizetype offset = FindEndOfOBSMetadata(content);
  546. if (offset >= 0) {
  547. stylesheet += "\n";
  548. stylesheet += content.sliced(offset);
  549. }
  550. }
  551. for (const OBSThemeVariable &var_ : vars) {
  552. OBSThemeVariable var(var_);
  553. if (!ResolveVariable(vars, var))
  554. continue;
  555. QString needle = needleTemplate.arg(var_.name);
  556. QString replace;
  557. QVariant value = var.userValue.isValid() ? var.userValue : var.value;
  558. if (var.type == OBSThemeVariable::Color) {
  559. replace = value.value<QColor>().name(QColor::HexRgb);
  560. } else if (var.type == OBSThemeVariable::Calc || var.type == OBSThemeVariable::Max ||
  561. var.type == OBSThemeVariable::Min) {
  562. replace = EvalMath(vars, var, var.type);
  563. } else if (var.type == OBSThemeVariable::Size || var.type == OBSThemeVariable::Number) {
  564. double val = value.toDouble();
  565. bool isInteger = ceill(val) == val;
  566. replace = QString::number(val, 'f', isInteger ? 0 : -1);
  567. if (!var.suffix.isEmpty())
  568. replace += var.suffix;
  569. } else {
  570. replace = value.toString();
  571. }
  572. stylesheet = stylesheet.replace(needle, replace);
  573. }
  574. return stylesheet;
  575. }
  576. template<typename T> static void FillEnumMap(QHash<QString, T> &map)
  577. {
  578. QMetaEnum meta = QMetaEnum::fromType<T>();
  579. int numKeys = meta.keyCount();
  580. for (int i = 0; i < numKeys; i++) {
  581. const char *key = meta.key(i);
  582. QString keyName(key);
  583. map[keyName.toLower()] = static_cast<T>(meta.keyToValue(key));
  584. }
  585. }
  586. static QPalette PreparePalette(const QHash<QString, OBSThemeVariable> &vars, const QPalette &defaultPalette)
  587. {
  588. static QHash<QString, QPalette::ColorRole> roleMap;
  589. static QHash<QString, QPalette::ColorGroup> groupMap;
  590. if (roleMap.empty())
  591. FillEnumMap<QPalette::ColorRole>(roleMap);
  592. if (groupMap.empty())
  593. FillEnumMap<QPalette::ColorGroup>(groupMap);
  594. QPalette pal(defaultPalette);
  595. for (const OBSThemeVariable &var_ : vars) {
  596. if (!var_.name.startsWith("palette_"))
  597. continue;
  598. if (var_.name.count("_") < 1 || var_.name.count("_") > 2)
  599. continue;
  600. OBSThemeVariable var(var_);
  601. if (!ResolveVariable(vars, var) || var.type != OBSThemeVariable::Color)
  602. continue;
  603. /* Determine role and optionally group based on name.
  604. * Format is: palette_<role>[_<group>] */
  605. QPalette::ColorRole role = QPalette::NoRole;
  606. QPalette::ColorGroup group = QPalette::All;
  607. QStringList parts = var_.name.split("_");
  608. if (parts.length() >= 2) {
  609. QString key = parts[1].toLower();
  610. if (!roleMap.contains(key)) {
  611. blog(LOG_WARNING, "Palette role \"%s\" is not valid!", QT_TO_UTF8(parts[1]));
  612. continue;
  613. }
  614. role = roleMap[key];
  615. }
  616. if (parts.length() == 3) {
  617. QString key = parts[2].toLower();
  618. if (!groupMap.contains(key)) {
  619. blog(LOG_WARNING, "Palette group \"%s\" is not valid!", QT_TO_UTF8(parts[2]));
  620. continue;
  621. }
  622. group = groupMap[key];
  623. }
  624. QVariant value = var.userValue.isValid() ? var.userValue : var.value;
  625. QColor color = value.value<QColor>().name(QColor::HexRgb);
  626. pal.setColor(group, role, color);
  627. }
  628. return pal;
  629. }
  630. static double getPaddingForDensityId(int id)
  631. {
  632. double paddingValue = 4;
  633. if (id == -2) {
  634. paddingValue = 0.25;
  635. } else if (id == -3) {
  636. paddingValue = 2;
  637. } else if (id == -4) {
  638. paddingValue = 4;
  639. } else if (id == -5) {
  640. paddingValue = 6;
  641. }
  642. return paddingValue;
  643. }
  644. OBSTheme *OBSApp::GetTheme(const QString &name)
  645. {
  646. if (!themes.contains(name))
  647. return nullptr;
  648. return &themes[name];
  649. }
  650. bool OBSApp::SetTheme(const QString &name)
  651. {
  652. OBSTheme *theme = GetTheme(name);
  653. if (!theme)
  654. return false;
  655. if (themeWatcher) {
  656. themeWatcher->blockSignals(true);
  657. themeWatcher->removePaths(themeWatcher->files());
  658. }
  659. setStyleSheet("");
  660. currentTheme = theme;
  661. QStringList contents;
  662. QHash<QString, OBSThemeVariable> vars;
  663. /* Build list of themes to load (in order) */
  664. QStringList themeIds(theme->dependencies);
  665. themeIds << theme->id;
  666. /* Inject Appearance settings into theme vars */
  667. OBSThemeVariable fontScale;
  668. fontScale.name = "obsFontScale";
  669. fontScale.type = OBSThemeVariable::Number;
  670. fontScale.value = QVariant::fromValue(config_get_int(App()->GetUserConfig(), "Appearance", "FontScale"));
  671. const int density = config_get_int(App()->GetUserConfig(), "Appearance", "Density");
  672. OBSThemeVariable padding;
  673. padding.name = "obsPadding";
  674. padding.type = OBSThemeVariable::Number;
  675. padding.value = QVariant::fromValue(getPaddingForDensityId(density));
  676. vars[fontScale.name] = std::move(fontScale);
  677. vars[padding.name] = std::move(padding);
  678. /* Find and add high contrast adjustment layer if available */
  679. if (HighContrastEnabled()) {
  680. for (const OBSTheme &theme_ : themes) {
  681. if (!theme_.isHighContrast)
  682. continue;
  683. if (theme_.parent != theme->id)
  684. continue;
  685. themeIds << theme_.id;
  686. break;
  687. }
  688. }
  689. QStringList filenames;
  690. for (const QString &themeId : themeIds) {
  691. OBSTheme *cur = GetTheme(themeId);
  692. QFile file(cur->location);
  693. filenames << file.fileName();
  694. if (!file.open(QIODeviceBase::ReadOnly))
  695. return false;
  696. const QByteArray content = file.readAll();
  697. for (OBSThemeVariable &var : ParseThemeVariables(content.constData())) {
  698. vars[var.name] = std::move(var);
  699. }
  700. contents.emplaceBack(content.constData());
  701. }
  702. /* Check if OBS appearance settings are used in the theme */
  703. currentTheme->usesFontScale = false;
  704. currentTheme->usesDensity = false;
  705. for (const OBSThemeVariable &var : vars) {
  706. switch (var.type) {
  707. case OBSThemeVariable::Color:
  708. case OBSThemeVariable::Size:
  709. case OBSThemeVariable::Number:
  710. case OBSThemeVariable::String:
  711. continue;
  712. case OBSThemeVariable::Alias:
  713. if (var.value.toString() == "obsFontScale") {
  714. currentTheme->usesFontScale = true;
  715. }
  716. if (var.value.toString() == "obsPadding") {
  717. currentTheme->usesDensity = true;
  718. }
  719. break;
  720. case OBSThemeVariable::Calc:
  721. case OBSThemeVariable::Max:
  722. case OBSThemeVariable::Min:
  723. if (var.value.toStringList().contains("obsFontScale")) {
  724. currentTheme->usesFontScale = true;
  725. }
  726. if (var.value.toStringList().contains("obsPadding")) {
  727. currentTheme->usesDensity = true;
  728. }
  729. break;
  730. }
  731. }
  732. const QString stylesheet = PrepareQSS(vars, contents);
  733. const QPalette palette = PreparePalette(vars, defaultPalette);
  734. setPalette(palette);
  735. setStyleSheet(stylesheet);
  736. #ifdef _DEBUG
  737. /* Write resulting QSS to file in config dir "themes" folder. */
  738. string filename("obs-studio/themes/");
  739. filename += theme->id.toStdString();
  740. filename += ".out";
  741. filesystem::path debugOut;
  742. char configPath[512];
  743. if (GetAppConfigPath(configPath, sizeof(configPath), filename.c_str())) {
  744. debugOut = absolute(filesystem::u8path(configPath));
  745. filesystem::create_directories(debugOut.parent_path());
  746. }
  747. QFile debugFile(debugOut);
  748. if (debugFile.open(QIODeviceBase::WriteOnly)) {
  749. debugFile.write(stylesheet.toUtf8());
  750. debugFile.flush();
  751. }
  752. #endif
  753. #ifdef __APPLE__
  754. SetMacOSDarkMode(theme->isDark);
  755. #endif
  756. emit StyleChanged();
  757. if (themeWatcher) {
  758. themeWatcher->addPaths(filenames);
  759. /* Give it 250 ms before re-enabling the watcher to prevent too
  760. * many reloads when edited with an auto-saving IDE. */
  761. QTimer::singleShot(250, this, [&] { themeWatcher->blockSignals(false); });
  762. }
  763. return true;
  764. }
  765. void OBSApp::themeFileChanged(const QString &path)
  766. {
  767. themeWatcher->blockSignals(true);
  768. blog(LOG_INFO, "Theme file \"%s\" changed, reloading...", QT_TO_UTF8(path));
  769. SetTheme(currentTheme->id);
  770. }
  771. static map<string, string> themeMigrations = {
  772. {"Yami", DEFAULT_THEME},
  773. {"Grey", "com.obsproject.Yami.Grey"},
  774. {"Rachni", "com.obsproject.Yami.Rachni"},
  775. {"Light", "com.obsproject.Yami.Light"},
  776. {"Dark", "com.obsproject.Yami.Classic"},
  777. {"Acri", "com.obsproject.Yami.Acri"},
  778. {"System", "com.obsproject.System"},
  779. };
  780. bool OBSApp::InitTheme()
  781. {
  782. defaultPalette = palette();
  783. #if !defined(_WIN32) && !defined(__APPLE__)
  784. setStyle(new OBSProxyStyle("Fusion"));
  785. #else
  786. setStyle(new OBSProxyStyle());
  787. #endif
  788. /* Set search paths for custom 'theme:' URI prefix */
  789. string searchDir;
  790. if (GetDataFilePath("themes", searchDir)) {
  791. auto installSearchDir = filesystem::u8path(searchDir);
  792. QDir::addSearchPath("theme", absolute(installSearchDir));
  793. }
  794. char userDir[512];
  795. if (GetAppConfigPath(userDir, sizeof(userDir), "obs-studio/themes")) {
  796. auto configSearchDir = filesystem::u8path(userDir);
  797. QDir::addSearchPath("theme", absolute(configSearchDir));
  798. }
  799. /* Load list of themes and read their metadata */
  800. FindThemes();
  801. if (config_get_bool(userConfig, "Appearance", "AutoReload")) {
  802. /* Set up Qt file watcher to automatically reload themes */
  803. themeWatcher = new QFileSystemWatcher(this);
  804. connect(themeWatcher.get(), &QFileSystemWatcher::fileChanged, this, &OBSApp::themeFileChanged);
  805. }
  806. /* Migrate old theme config key */
  807. if (config_has_user_value(userConfig, "General", "CurrentTheme3") &&
  808. !config_has_user_value(userConfig, "Appearance", "Theme")) {
  809. const char *old = config_get_string(userConfig, "General", "CurrentTheme3");
  810. if (themeMigrations.count(old)) {
  811. config_set_string(userConfig, "Appearance", "Theme", themeMigrations[old].c_str());
  812. }
  813. }
  814. QString themeName = config_get_string(userConfig, "Appearance", "Theme");
  815. if (themeName.isEmpty() || !GetTheme(themeName)) {
  816. if (!themeName.isEmpty()) {
  817. blog(LOG_WARNING,
  818. "Loading theme \"%s\" failed, falling back to "
  819. "default theme (\"%s\").",
  820. QT_TO_UTF8(themeName), DEFAULT_THEME);
  821. }
  822. #ifdef _WIN32
  823. themeName = HighContrastEnabled() ? "com.obsproject.System" : DEFAULT_THEME;
  824. #else
  825. themeName = DEFAULT_THEME;
  826. #endif
  827. }
  828. if (!SetTheme(themeName)) {
  829. blog(LOG_ERROR,
  830. "Loading default theme \"%s\" failed, falling back to "
  831. "system theme as last resort.",
  832. QT_TO_UTF8(themeName));
  833. return SetTheme("com.obsproject.System");
  834. }
  835. return true;
  836. }