obs-app-theming.cpp 25 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  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. string themeDir;
  326. QStringList filters;
  327. filters << "*.obt" // OBS Base Theme
  328. << "*.ovt" // OBS Variant Theme
  329. << "*.oha" // OBS High-contrast Adjustment layer
  330. ;
  331. GetDataFilePath("themes/", themeDir);
  332. QDirIterator it(QString::fromStdString(themeDir), filters, QDir::Files);
  333. while (it.hasNext()) {
  334. auto theme = ParseThemeMeta(it.next());
  335. if (theme && !themes.contains(theme->id))
  336. themes[theme->id] = std::move(*theme);
  337. }
  338. themeDir.resize(1024);
  339. if (GetConfigPath(themeDir.data(), themeDir.capacity(),
  340. "obs-studio/themes/") > 0) {
  341. QDirIterator it(QT_UTF8(themeDir.c_str()), filters,
  342. QDir::Files);
  343. while (it.hasNext()) {
  344. auto theme = ParseThemeMeta(it.next());
  345. if (theme && !themes.contains(theme->id))
  346. themes[theme->id] = std::move(*theme);
  347. }
  348. }
  349. /* Build dependency tree for all themes, removing ones that have items missing. */
  350. QSet<QString> invalid;
  351. for (OBSTheme &theme : themes) {
  352. if (theme.extends.isEmpty()) {
  353. if (!theme.isBaseTheme) {
  354. blog(LOG_ERROR,
  355. R"(Theme "%s" is not base, but does not specify parent!)",
  356. QT_TO_UTF8(theme.id));
  357. invalid.insert(theme.id);
  358. }
  359. continue;
  360. }
  361. QString parentId = theme.extends;
  362. while (!parentId.isEmpty()) {
  363. OBSTheme *parent = GetTheme(parentId);
  364. if (!parent) {
  365. blog(LOG_ERROR,
  366. R"(Theme "%s" is missing ancestor "%s"!)",
  367. QT_TO_UTF8(theme.id),
  368. QT_TO_UTF8(parentId));
  369. invalid.insert(theme.id);
  370. break;
  371. }
  372. if (theme.isBaseTheme && !parent->isBaseTheme) {
  373. blog(LOG_ERROR,
  374. R"(Ancestor "%s" of base theme "%s" is not a base theme!)",
  375. QT_TO_UTF8(parent->id),
  376. QT_TO_UTF8(theme.id));
  377. invalid.insert(theme.id);
  378. break;
  379. }
  380. if (parent->id == theme.id ||
  381. theme.dependencies.contains(parent->id)) {
  382. blog(LOG_ERROR,
  383. R"(Dependency chain of "%s" ("%s") contains recursion!)",
  384. QT_TO_UTF8(theme.id),
  385. QT_TO_UTF8(parent->id));
  386. invalid.insert(theme.id);
  387. break;
  388. }
  389. /* Mark this theme as a variant of first parent that is a base theme. */
  390. if (!theme.isBaseTheme && parent->isBaseTheme &&
  391. theme.parent.isEmpty())
  392. theme.parent = parent->id;
  393. theme.dependencies.push_front(parent->id);
  394. parentId = parent->extends;
  395. if (parentId.isEmpty() && !parent->isBaseTheme) {
  396. blog(LOG_ERROR,
  397. R"(Final ancestor of "%s" ("%s") is not a base theme!)",
  398. QT_TO_UTF8(theme.id),
  399. QT_TO_UTF8(parent->id));
  400. invalid.insert(theme.id);
  401. break;
  402. }
  403. }
  404. }
  405. for (const QString &name : invalid) {
  406. themes.remove(name);
  407. }
  408. }
  409. static bool ResolveVariable(const QHash<QString, OBSThemeVariable> &vars,
  410. OBSThemeVariable &var)
  411. {
  412. const OBSThemeVariable *varPtr = &var;
  413. const OBSThemeVariable *realVar = varPtr;
  414. while (realVar->type == OBSThemeVariable::Alias) {
  415. QString newKey = realVar->value.toString();
  416. if (!vars.contains(newKey)) {
  417. blog(LOG_ERROR,
  418. R"(Variable "%s" (aliased by "%s") does not exist!)",
  419. QT_TO_UTF8(newKey), QT_TO_UTF8(var.name));
  420. return false;
  421. }
  422. const OBSThemeVariable &newVar = vars[newKey];
  423. realVar = &newVar;
  424. }
  425. if (realVar != varPtr)
  426. var = *realVar;
  427. return true;
  428. }
  429. static QString EvalCalc(const QHash<QString, OBSThemeVariable> &vars,
  430. const OBSThemeVariable &var, const int recursion = 0);
  431. static OBSThemeVariable
  432. ParseCalcVariable(const QHash<QString, OBSThemeVariable> &vars,
  433. const QString &value, const int recursion = 0)
  434. {
  435. OBSThemeVariable var;
  436. const QByteArray utf8 = value.toUtf8();
  437. const char *data = utf8.constData();
  438. if (isdigit(*data)) {
  439. double f = os_strtod(data);
  440. var.type = OBSThemeVariable::Number;
  441. var.value = f;
  442. const char *dataEnd = data + utf8.size();
  443. while (data < dataEnd) {
  444. if (*data && !isdigit(*data) && *data != '.') {
  445. var.suffix =
  446. QString::fromUtf8(data, dataEnd - data);
  447. var.type = OBSThemeVariable::Size;
  448. break;
  449. }
  450. data++;
  451. }
  452. } else {
  453. /* Treat value as an alias/key and resolve it */
  454. var.type = OBSThemeVariable::Alias;
  455. var.value = value;
  456. ResolveVariable(vars, var);
  457. /* Handle nested calc()s */
  458. if (var.type == OBSThemeVariable::Calc) {
  459. QString val = EvalCalc(vars, var, recursion + 1);
  460. var = ParseCalcVariable(vars, val);
  461. }
  462. /* Only number or size would be valid here */
  463. if (var.type != OBSThemeVariable::Number &&
  464. var.type != OBSThemeVariable::Size) {
  465. blog(LOG_ERROR,
  466. "calc() operand is not a size or number: %s",
  467. QT_TO_UTF8(var.value.toString()));
  468. throw invalid_argument("Operand not of numeric type");
  469. }
  470. }
  471. return var;
  472. }
  473. static QString EvalCalc(const QHash<QString, OBSThemeVariable> &vars,
  474. const OBSThemeVariable &var, const int recursion)
  475. {
  476. if (recursion >= 10) {
  477. /* Abort after 10 levels of recursion */
  478. blog(LOG_ERROR, "Maximum calc() recursion levels hit!");
  479. return "'Invalid expression'";
  480. }
  481. QStringList args = var.value.toStringList();
  482. if (args.length() != 3) {
  483. blog(LOG_ERROR,
  484. "calc() had invalid number of arguments: %lld (%s)",
  485. args.length(), QT_TO_UTF8(args.join(", ")));
  486. return "'Invalid expression'";
  487. }
  488. QString &opt = args[1];
  489. if (opt != '*' && opt != '+' && opt != '-' && opt != '/') {
  490. blog(LOG_ERROR, "Unknown/invalid calc() operator: %s",
  491. QT_TO_UTF8(opt));
  492. return "'Invalid expression'";
  493. }
  494. OBSThemeVariable val1, val2;
  495. try {
  496. val1 = ParseCalcVariable(vars, args[0], recursion);
  497. val2 = ParseCalcVariable(vars, args[2], recursion);
  498. } catch (...) {
  499. return "'Invalid expression'";
  500. }
  501. /* Ensure that suffixes match (if any) */
  502. if (!val1.suffix.isEmpty() && !val2.suffix.isEmpty() &&
  503. val1.suffix != val2.suffix) {
  504. blog(LOG_ERROR,
  505. "calc() requires suffixes to match or only one to be present! %s != %s",
  506. QT_TO_UTF8(val1.suffix), QT_TO_UTF8(val2.suffix));
  507. return "'Invalid expression'";
  508. }
  509. double val = numeric_limits<double>::quiet_NaN();
  510. double d1 = val1.userValue.isValid() ? val1.userValue.toDouble()
  511. : val1.value.toDouble();
  512. double d2 = val2.userValue.isValid() ? val2.userValue.toDouble()
  513. : val2.value.toDouble();
  514. if (!isfinite(d1) || !isfinite(d2)) {
  515. blog(LOG_ERROR,
  516. "calc() received at least one invalid value:"
  517. " op1: %f, op2: %f",
  518. d1, d2);
  519. return "'Invalid expression'";
  520. }
  521. if (opt == "+")
  522. val = d1 + d2;
  523. else if (opt == "-")
  524. val = d1 - d2;
  525. else if (opt == "*")
  526. val = d1 * d2;
  527. else if (opt == "/")
  528. val = d1 / d2;
  529. if (!isnormal(val)) {
  530. blog(LOG_ERROR,
  531. "Invalid calc() math resulted in non-normal number:"
  532. " %f %s %f = %f",
  533. d1, QT_TO_UTF8(opt), d2, val);
  534. return "'Invalid expression'";
  535. }
  536. bool isInteger = ceill(val) == val;
  537. QString result = QString::number(val, 'f', isInteger ? 0 : -1);
  538. /* Carry-over suffix */
  539. if (!val1.suffix.isEmpty())
  540. result += val1.suffix;
  541. else if (!val2.suffix.isEmpty())
  542. result += val2.suffix;
  543. return result;
  544. }
  545. static qsizetype FindEndOfOBSMetadata(const QString &content)
  546. {
  547. /* Find end of last OBS-specific section and strip it, kinda jank but should work */
  548. qsizetype end = 0;
  549. for (auto section : {"OBSThemeMeta", "OBSThemeVars", "OBSTheme"}) {
  550. qsizetype idx = content.indexOf(section, 0);
  551. if (idx > end) {
  552. end = content.indexOf('}', idx) + 1;
  553. }
  554. }
  555. return end;
  556. }
  557. static QString PrepareQSS(const QHash<QString, OBSThemeVariable> &vars,
  558. const QStringList &contents)
  559. {
  560. QString stylesheet;
  561. QString needleTemplate("var(--%1)");
  562. for (const QString &content : contents) {
  563. qsizetype offset = FindEndOfOBSMetadata(content);
  564. if (offset >= 0) {
  565. stylesheet += "\n";
  566. stylesheet += content.sliced(offset);
  567. }
  568. }
  569. for (const OBSThemeVariable &var_ : vars) {
  570. OBSThemeVariable var(var_);
  571. if (!ResolveVariable(vars, var))
  572. continue;
  573. QString needle = needleTemplate.arg(var_.name);
  574. QString replace;
  575. QVariant value = var.userValue.isValid() ? var.userValue
  576. : var.value;
  577. if (var.type == OBSThemeVariable::Color) {
  578. replace = value.value<QColor>().name(QColor::HexRgb);
  579. } else if (var.type == OBSThemeVariable::Calc) {
  580. replace = EvalCalc(vars, var);
  581. } else if (var.type == OBSThemeVariable::Size ||
  582. var.type == OBSThemeVariable::Number) {
  583. double val = value.toDouble();
  584. bool isInteger = ceill(val) == val;
  585. replace = QString::number(val, 'f', isInteger ? 0 : -1);
  586. if (!var.suffix.isEmpty())
  587. replace += var.suffix;
  588. } else {
  589. replace = value.toString();
  590. }
  591. stylesheet = stylesheet.replace(needle, replace);
  592. }
  593. return stylesheet;
  594. }
  595. template<typename T> static void FillEnumMap(QHash<QString, T> &map)
  596. {
  597. QMetaEnum meta = QMetaEnum::fromType<T>();
  598. int numKeys = meta.keyCount();
  599. for (int i = 0; i < numKeys; i++) {
  600. const char *key = meta.key(i);
  601. QString keyName(key);
  602. map[keyName.toLower()] = static_cast<T>(meta.keyToValue(key));
  603. }
  604. }
  605. static QPalette PreparePalette(const QHash<QString, OBSThemeVariable> &vars,
  606. const QPalette &defaultPalette)
  607. {
  608. static QHash<QString, QPalette::ColorRole> roleMap;
  609. static QHash<QString, QPalette::ColorGroup> groupMap;
  610. if (roleMap.empty())
  611. FillEnumMap<QPalette::ColorRole>(roleMap);
  612. if (groupMap.empty())
  613. FillEnumMap<QPalette::ColorGroup>(groupMap);
  614. QPalette pal(defaultPalette);
  615. for (const OBSThemeVariable &var_ : vars) {
  616. if (!var_.name.startsWith("palette_"))
  617. continue;
  618. if (var_.name.count("_") < 1 || var_.name.count("_") > 2)
  619. continue;
  620. OBSThemeVariable var(var_);
  621. if (!ResolveVariable(vars, var) ||
  622. var.type != OBSThemeVariable::Color)
  623. continue;
  624. /* Determine role and optionally group based on name.
  625. * Format is: palette_<role>[_<group>] */
  626. QPalette::ColorRole role = QPalette::NoRole;
  627. QPalette::ColorGroup group = QPalette::All;
  628. QStringList parts = var_.name.split("_");
  629. if (parts.length() >= 2) {
  630. QString key = parts[1].toLower();
  631. if (!roleMap.contains(key)) {
  632. blog(LOG_WARNING,
  633. "Palette role \"%s\" is not valid!",
  634. QT_TO_UTF8(parts[1]));
  635. continue;
  636. }
  637. role = roleMap[key];
  638. }
  639. if (parts.length() == 3) {
  640. QString key = parts[2].toLower();
  641. if (!groupMap.contains(key)) {
  642. blog(LOG_WARNING,
  643. "Palette group \"%s\" is not valid!",
  644. QT_TO_UTF8(parts[2]));
  645. continue;
  646. }
  647. group = groupMap[key];
  648. }
  649. QVariant value = var.userValue.isValid() ? var.userValue
  650. : var.value;
  651. QColor color = value.value<QColor>().name(QColor::HexRgb);
  652. pal.setColor(group, role, color);
  653. }
  654. return pal;
  655. }
  656. OBSTheme *OBSApp::GetTheme(const QString &name)
  657. {
  658. if (!themes.contains(name))
  659. return nullptr;
  660. return &themes[name];
  661. }
  662. bool OBSApp::SetTheme(const QString &name)
  663. {
  664. OBSTheme *theme = GetTheme(name);
  665. if (!theme)
  666. return false;
  667. if (themeWatcher) {
  668. themeWatcher->blockSignals(true);
  669. themeWatcher->removePaths(themeWatcher->files());
  670. }
  671. setStyleSheet("");
  672. currentTheme = theme;
  673. QStringList contents;
  674. QHash<QString, OBSThemeVariable> vars;
  675. /* Build list of themes to load (in order) */
  676. QStringList themeIds(theme->dependencies);
  677. themeIds << theme->id;
  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 :
  698. ParseThemeVariables(content.constData())) {
  699. vars[var.name] = std::move(var);
  700. }
  701. contents.emplaceBack(content.constData());
  702. }
  703. const QString stylesheet = PrepareQSS(vars, contents);
  704. const QPalette palette = PreparePalette(vars, defaultPalette);
  705. setPalette(palette);
  706. setStyleSheet(stylesheet);
  707. #ifdef _DEBUG
  708. /* Write resulting QSS to file in config dir "themes" folder. */
  709. string filename("obs-studio/themes/");
  710. filename += theme->id.toStdString();
  711. filename += ".out";
  712. filesystem::path debugOut;
  713. char configPath[512];
  714. if (GetConfigPath(configPath, sizeof(configPath), filename.c_str())) {
  715. debugOut = absolute(filesystem::u8path(configPath));
  716. filesystem::create_directories(debugOut.parent_path());
  717. }
  718. QFile debugFile(debugOut);
  719. if (debugFile.open(QIODeviceBase::WriteOnly)) {
  720. debugFile.write(stylesheet.toUtf8());
  721. debugFile.flush();
  722. }
  723. #endif
  724. #ifdef __APPLE__
  725. SetMacOSDarkMode(theme->isDark);
  726. #endif
  727. emit StyleChanged();
  728. if (themeWatcher) {
  729. themeWatcher->addPaths(filenames);
  730. /* Give it 250 ms before re-enabling the watcher to prevent too
  731. * many reloads when edited with an auto-saving IDE. */
  732. QTimer::singleShot(250, this,
  733. [&] { themeWatcher->blockSignals(false); });
  734. }
  735. return true;
  736. }
  737. void OBSApp::themeFileChanged(const QString &path)
  738. {
  739. themeWatcher->blockSignals(true);
  740. blog(LOG_INFO, "Theme file \"%s\" changed, reloading...",
  741. QT_TO_UTF8(path));
  742. SetTheme(currentTheme->id);
  743. }
  744. static map<string, string> themeMigrations = {
  745. {"Yami", DEFAULT_THEME},
  746. {"Grey", "com.obsproject.Yami.Grey"},
  747. {"Rachni", "com.obsproject.Yami.Rachni"},
  748. {"Light", "com.obsproject.Yami.Light"},
  749. {"Dark", "com.obsproject.Yami.Classic"},
  750. {"Acri", "com.obsproject.Yami.Acri"},
  751. {"System", "com.obsproject.System"},
  752. };
  753. bool OBSApp::InitTheme()
  754. {
  755. defaultPalette = palette();
  756. #if !defined(_WIN32) && !defined(__APPLE__)
  757. setStyle(new OBSProxyStyle("Fusion"));
  758. #else
  759. setStyle(new OBSProxyStyle());
  760. #endif
  761. /* Set search paths for custom 'theme:' URI prefix */
  762. string searchDir;
  763. if (GetDataFilePath("themes", searchDir)) {
  764. auto installSearchDir = filesystem::u8path(searchDir);
  765. QDir::addSearchPath("theme", absolute(installSearchDir));
  766. }
  767. char userDir[512];
  768. if (GetConfigPath(userDir, sizeof(userDir), "obs-studio/themes")) {
  769. auto configSearchDir = filesystem::u8path(userDir);
  770. QDir::addSearchPath("theme", absolute(configSearchDir));
  771. }
  772. /* Load list of themes and read their metadata */
  773. FindThemes();
  774. if (config_get_bool(globalConfig, "Appearance", "AutoReload")) {
  775. /* Set up Qt file watcher to automatically reload themes */
  776. themeWatcher = new QFileSystemWatcher(this);
  777. connect(themeWatcher.get(), &QFileSystemWatcher::fileChanged,
  778. this, &OBSApp::themeFileChanged);
  779. }
  780. /* Migrate old theme config key */
  781. if (config_has_user_value(globalConfig, "General", "CurrentTheme3") &&
  782. !config_has_user_value(globalConfig, "Appearance", "Theme")) {
  783. const char *old = config_get_string(globalConfig, "General",
  784. "CurrentTheme3");
  785. if (themeMigrations.count(old)) {
  786. config_set_string(globalConfig, "Appearance", "Theme",
  787. themeMigrations[old].c_str());
  788. }
  789. }
  790. QString themeName =
  791. config_get_string(globalConfig, "Appearance", "Theme");
  792. if (themeName.isEmpty() || !GetTheme(themeName)) {
  793. if (!themeName.isEmpty()) {
  794. blog(LOG_WARNING,
  795. "Loading theme \"%s\" failed, falling back to "
  796. "default theme (\"%s\").",
  797. QT_TO_UTF8(themeName), DEFAULT_THEME);
  798. }
  799. #ifdef _WIN32
  800. themeName = HighContrastEnabled() ? "com.obsproject.System"
  801. : DEFAULT_THEME;
  802. #else
  803. themeName = DEFAULT_THEME;
  804. #endif
  805. }
  806. if (!SetTheme(themeName)) {
  807. blog(LOG_ERROR,
  808. "Loading default theme \"%s\" failed, falling back to "
  809. "system theme as last resort.",
  810. QT_TO_UTF8(themeName));
  811. return SetTheme("com.obsproject.System");
  812. }
  813. return true;
  814. }