obs-app-theming.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  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. #ifdef _WIN32
  251. const QString osPrefix = "os_win_";
  252. #elif __APPLE__
  253. const QString osPrefix = "os_mac_";
  254. #else
  255. const QString osPrefix = "os_lin_";
  256. #endif
  257. if (key.startsWith(osPrefix) &&
  258. key.length() > osPrefix.length()) {
  259. var.name = key.sliced(osPrefix.length());
  260. }
  261. ret = cf_next_token_should_be(cfp, ":", ";", nullptr);
  262. if (ret != PARSE_SUCCESS)
  263. continue;
  264. if (!cf_next_token(cfp))
  265. return vars;
  266. if (cfp->cur_token->type == CFTOKEN_NUM) {
  267. const char *ch = cfp->cur_token->str.array;
  268. const char *end = ch + cfp->cur_token->str.len;
  269. double f = os_strtod(ch);
  270. var.value = f;
  271. var.type = OBSThemeVariable::Number;
  272. /* Look for a suffix and mark variable as size if it exists */
  273. while (ch < end) {
  274. if (!isdigit(*ch) && !isspace(*ch) &&
  275. *ch != '.') {
  276. var.suffix =
  277. QString::fromUtf8(ch, end - ch);
  278. var.type = OBSThemeVariable::Size;
  279. break;
  280. }
  281. ch++;
  282. }
  283. } else if (cf_token_is(cfp, "rgb") || cf_token_is(cfp, "#") ||
  284. cf_token_is(cfp, "bikeshed")) {
  285. QColor color = ParseColor(cfp);
  286. if (!color.isValid())
  287. continue;
  288. var.value = color;
  289. var.type = OBSThemeVariable::Color;
  290. } else if (cf_token_is(cfp, "var")) {
  291. QString value;
  292. if (!ParseVarName(cfp, value))
  293. continue;
  294. var.value = value;
  295. var.type = OBSThemeVariable::Alias;
  296. } else if (cf_token_is(cfp, "calc")) {
  297. QStringList calc;
  298. if (!ParseCalc(cfp, calc, vars))
  299. continue;
  300. var.type = OBSThemeVariable::Calc;
  301. var.value = calc;
  302. } else {
  303. var.type = OBSThemeVariable::String;
  304. BPtr strVal =
  305. cf_literal_to_str(cfp->cur_token->str.array,
  306. cfp->cur_token->str.len);
  307. var.value = QString::fromUtf8(strVal.Get());
  308. }
  309. if (!cf_next_token(cfp))
  310. return vars;
  311. if (cf_token_is(cfp, "!") &&
  312. cf_next_token_should_be(cfp, "editable", nullptr,
  313. nullptr) == PARSE_SUCCESS) {
  314. if (var.type == OBSThemeVariable::Calc ||
  315. var.type == OBSThemeVariable::Alias) {
  316. blog(LOG_WARNING,
  317. "Variable of calc/alias type cannot be editable: %s",
  318. QT_TO_UTF8(var.name));
  319. } else {
  320. var.editable = true;
  321. }
  322. }
  323. vars.push_back(std::move(var));
  324. if (!cf_token_is(cfp, ";") &&
  325. !cf_go_to_token(cfp, ";", nullptr))
  326. return vars;
  327. }
  328. return vars;
  329. }
  330. void OBSApp::FindThemes()
  331. {
  332. string themeDir;
  333. themeDir.resize(512);
  334. QStringList filters;
  335. filters << "*.obt" // OBS Base Theme
  336. << "*.ovt" // OBS Variant Theme
  337. << "*.oha" // OBS High-contrast Adjustment layer
  338. ;
  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. OBSTheme *theme = ParseThemeMeta(it.next());
  345. if (theme && !themes.contains(theme->id))
  346. themes[theme->id] = std::move(*theme);
  347. else
  348. delete theme;
  349. }
  350. }
  351. GetDataFilePath("themes/", themeDir);
  352. QDirIterator it(QString::fromStdString(themeDir), filters, QDir::Files);
  353. while (it.hasNext()) {
  354. OBSTheme *theme = ParseThemeMeta(it.next());
  355. if (theme && !themes.contains(theme->id))
  356. themes[theme->id] = std::move(*theme);
  357. else
  358. delete theme;
  359. }
  360. /* Build dependency tree for all themes, removing ones that have items missing. */
  361. QSet<QString> invalid;
  362. for (OBSTheme &theme : themes) {
  363. if (theme.extends.isEmpty()) {
  364. if (!theme.isBaseTheme) {
  365. blog(LOG_ERROR,
  366. R"(Theme "%s" is not base, but does not specify parent!)",
  367. QT_TO_UTF8(theme.id));
  368. invalid.insert(theme.id);
  369. }
  370. continue;
  371. }
  372. QString parentId = theme.extends;
  373. while (!parentId.isEmpty()) {
  374. OBSTheme *parent = GetTheme(parentId);
  375. if (!parent) {
  376. blog(LOG_ERROR,
  377. R"(Theme "%s" is missing ancestor "%s"!)",
  378. QT_TO_UTF8(theme.id),
  379. QT_TO_UTF8(parentId));
  380. invalid.insert(theme.id);
  381. break;
  382. }
  383. if (theme.isBaseTheme && !parent->isBaseTheme) {
  384. blog(LOG_ERROR,
  385. R"(Ancestor "%s" of base theme "%s" is not a base theme!)",
  386. QT_TO_UTF8(parent->id),
  387. QT_TO_UTF8(theme.id));
  388. invalid.insert(theme.id);
  389. break;
  390. }
  391. /* Mark this theme as a variant of first parent that is a base theme. */
  392. if (!theme.isBaseTheme && parent->isBaseTheme &&
  393. theme.parent.isEmpty())
  394. theme.parent = parent->id;
  395. theme.dependencies.push_front(parent->id);
  396. parentId = parent->extends;
  397. if (parentId.isEmpty() && !parent->isBaseTheme) {
  398. blog(LOG_ERROR,
  399. R"(Final ancestor of "%s" ("%s") is not a base theme!)",
  400. QT_TO_UTF8(theme.id),
  401. QT_TO_UTF8(parent->id));
  402. invalid.insert(theme.id);
  403. break;
  404. }
  405. }
  406. }
  407. for (const QString &name : invalid) {
  408. themes.remove(name);
  409. }
  410. }
  411. static bool ResolveVariable(const QHash<QString, OBSThemeVariable> &vars,
  412. OBSThemeVariable &var)
  413. {
  414. const OBSThemeVariable *varPtr = &var;
  415. const OBSThemeVariable *realVar = varPtr;
  416. while (realVar->type == OBSThemeVariable::Alias) {
  417. QString newKey = realVar->value.toString();
  418. if (!vars.contains(newKey)) {
  419. blog(LOG_ERROR,
  420. R"(Variable "%s" (aliased by "%s") does not exist!)",
  421. QT_TO_UTF8(newKey), QT_TO_UTF8(var.name));
  422. return false;
  423. }
  424. const OBSThemeVariable &newVar = vars[newKey];
  425. realVar = &newVar;
  426. }
  427. if (realVar != varPtr)
  428. var = *realVar;
  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 (GetConfigPath(configPath, sizeof(configPath), filename.c_str())) {
  717. debugOut = absolute(filesystem::u8path(configPath));
  718. filesystem::create_directories(debugOut.parent_path());
  719. }
  720. QFile debugFile(debugOut);
  721. if (debugFile.open(QIODeviceBase::WriteOnly)) {
  722. debugFile.write(stylesheet.toUtf8());
  723. debugFile.flush();
  724. }
  725. #endif
  726. #ifdef __APPLE__
  727. SetMacOSDarkMode(theme->isDark);
  728. #endif
  729. emit StyleChanged();
  730. if (themeWatcher) {
  731. themeWatcher->addPaths(filenames);
  732. /* Give it 250 ms before re-enabling the watcher to prevent too
  733. * many reloads when edited with an auto-saving IDE. */
  734. QTimer::singleShot(250, this,
  735. [&] { themeWatcher->blockSignals(false); });
  736. }
  737. return true;
  738. }
  739. void OBSApp::themeFileChanged(const QString &path)
  740. {
  741. themeWatcher->blockSignals(true);
  742. blog(LOG_INFO, "Theme file \"%s\" changed, reloading...",
  743. QT_TO_UTF8(path));
  744. SetTheme(currentTheme->id);
  745. }
  746. static map<string, string> themeMigrations = {
  747. {"Yami", DEFAULT_THEME},
  748. {"Grey", "com.obsproject.Yami.Grey"},
  749. {"Rachni", "com.obsproject.Yami.Rachni"},
  750. {"Light", "com.obsproject.Yami.Light"},
  751. {"Dark", "com.obsproject.Yami.Classic"},
  752. {"Acri", "com.obsproject.Yami.Acri"},
  753. {"System", "com.obsproject.System"},
  754. };
  755. bool OBSApp::InitTheme()
  756. {
  757. defaultPalette = palette();
  758. setStyle(new OBSProxyStyle());
  759. /* Set search paths for custom 'theme:' URI prefix */
  760. string searchDir;
  761. if (GetDataFilePath("themes", searchDir)) {
  762. auto installSearchDir = filesystem::u8path(searchDir);
  763. QDir::addSearchPath("theme", absolute(installSearchDir));
  764. }
  765. char userDir[512];
  766. if (GetConfigPath(userDir, sizeof(userDir), "obs-studio/themes")) {
  767. auto configSearchDir = filesystem::u8path(userDir);
  768. QDir::addSearchPath("theme", absolute(configSearchDir));
  769. }
  770. /* Load list of themes and read their metadata */
  771. FindThemes();
  772. if (config_get_bool(globalConfig, "Appearance", "AutoReload")) {
  773. /* Set up Qt file watcher to automatically reload themes */
  774. themeWatcher = new QFileSystemWatcher(this);
  775. connect(themeWatcher.get(), &QFileSystemWatcher::fileChanged,
  776. this, &OBSApp::themeFileChanged);
  777. }
  778. /* Migrate old theme config key */
  779. if (config_has_user_value(globalConfig, "General", "CurrentTheme3") &&
  780. !config_has_user_value(globalConfig, "Appearance", "Theme")) {
  781. const char *old = config_get_string(globalConfig, "General",
  782. "CurrentTheme3");
  783. if (themeMigrations.count(old)) {
  784. config_set_string(globalConfig, "Appearance", "Theme",
  785. themeMigrations[old].c_str());
  786. }
  787. }
  788. QString themeName =
  789. config_get_string(globalConfig, "Appearance", "Theme");
  790. if (themeName.isEmpty() || !GetTheme(themeName)) {
  791. if (!themeName.isEmpty()) {
  792. blog(LOG_WARNING,
  793. "Loading theme \"%s\" failed, falling back to "
  794. "default theme (\"%s\").",
  795. QT_TO_UTF8(themeName), DEFAULT_THEME);
  796. }
  797. #ifdef _WIN32
  798. themeName = HighContrastEnabled() ? "com.obsproject.System"
  799. : DEFAULT_THEME;
  800. #else
  801. themeName = DEFAULT_THEME;
  802. #endif
  803. }
  804. if (!SetTheme(themeName)) {
  805. blog(LOG_ERROR,
  806. "Loading default theme \"%s\" failed, falling back to "
  807. "system theme as last resort.",
  808. QT_TO_UTF8(themeName));
  809. return SetTheme("com.obsproject.System");
  810. }
  811. return true;
  812. }