obs-app-theming.cpp 25 KB

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