obs-app-theming.cpp 24 KB

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