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 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. if (var.type != OBSThemeVariable::Alias)
  413. return true;
  414. QString key = var.value.toString();
  415. while (vars[key].type == OBSThemeVariable::Alias) {
  416. key = vars[key].value.toString();
  417. if (!vars.contains(key)) {
  418. blog(LOG_ERROR,
  419. R"(Variable "%s" (aliased by "%s") does not exist!)",
  420. QT_TO_UTF8(key), QT_TO_UTF8(var.name));
  421. return false;
  422. }
  423. }
  424. var = vars[key];
  425. return true;
  426. }
  427. static QString EvalCalc(const QHash<QString, OBSThemeVariable> &vars,
  428. const OBSThemeVariable &var, const int recursion = 0);
  429. static OBSThemeVariable
  430. ParseCalcVariable(const QHash<QString, OBSThemeVariable> &vars,
  431. const QString &value, const int recursion = 0)
  432. {
  433. OBSThemeVariable var;
  434. const QByteArray utf8 = value.toUtf8();
  435. const char *data = utf8.constData();
  436. if (isdigit(*data)) {
  437. double f = os_strtod(data);
  438. var.type = OBSThemeVariable::Number;
  439. var.value = f;
  440. const char *dataEnd = data + utf8.size();
  441. while (data < dataEnd) {
  442. if (*data && !isdigit(*data) && *data != '.') {
  443. var.suffix =
  444. QString::fromUtf8(data, dataEnd - data);
  445. var.type = OBSThemeVariable::Size;
  446. break;
  447. }
  448. data++;
  449. }
  450. } else {
  451. /* Treat value as an alias/key and resolve it */
  452. var.type = OBSThemeVariable::Alias;
  453. var.value = value;
  454. ResolveVariable(vars, var);
  455. /* Handle nested calc()s */
  456. if (var.type == OBSThemeVariable::Calc) {
  457. QString val = EvalCalc(vars, var, recursion + 1);
  458. var = ParseCalcVariable(vars, val);
  459. }
  460. /* Only number or size would be valid here */
  461. if (var.type != OBSThemeVariable::Number &&
  462. var.type != OBSThemeVariable::Size) {
  463. blog(LOG_ERROR,
  464. "calc() operand is not a size or number: %s",
  465. QT_TO_UTF8(var.value.toString()));
  466. throw invalid_argument("Operand not of numeric type");
  467. }
  468. }
  469. return var;
  470. }
  471. static QString EvalCalc(const QHash<QString, OBSThemeVariable> &vars,
  472. const OBSThemeVariable &var, const int recursion)
  473. {
  474. if (recursion >= 10) {
  475. /* Abort after 10 levels of recursion */
  476. blog(LOG_ERROR, "Maximum calc() recursion levels hit!");
  477. return "'Invalid expression'";
  478. }
  479. QStringList args = var.value.toStringList();
  480. if (args.length() != 3) {
  481. blog(LOG_ERROR,
  482. "calc() had invalid number of arguments: %lld (%s)",
  483. args.length(), QT_TO_UTF8(args.join(", ")));
  484. return "'Invalid expression'";
  485. }
  486. QString &opt = args[1];
  487. if (opt != '*' && opt != '+' && opt != '-' && opt != '/') {
  488. blog(LOG_ERROR, "Unknown/invalid calc() operator: %s",
  489. QT_TO_UTF8(opt));
  490. return "'Invalid expression'";
  491. }
  492. OBSThemeVariable val1, val2;
  493. try {
  494. val1 = ParseCalcVariable(vars, args[0], recursion);
  495. val2 = ParseCalcVariable(vars, args[2], recursion);
  496. } catch (...) {
  497. return "'Invalid expression'";
  498. }
  499. /* Ensure that suffixes match (if any) */
  500. if (!val1.suffix.isEmpty() && !val2.suffix.isEmpty() &&
  501. val1.suffix != val2.suffix) {
  502. blog(LOG_ERROR,
  503. "calc() requires suffixes to match or only one to be present! %s != %s",
  504. QT_TO_UTF8(val1.suffix), QT_TO_UTF8(val2.suffix));
  505. return "'Invalid expression'";
  506. }
  507. double val = numeric_limits<double>::quiet_NaN();
  508. double d1 = val1.userValue.isValid() ? val1.userValue.toDouble()
  509. : val1.value.toDouble();
  510. double d2 = val2.userValue.isValid() ? val2.userValue.toDouble()
  511. : val2.value.toDouble();
  512. if (!isfinite(d1) || !isfinite(d2)) {
  513. blog(LOG_ERROR,
  514. "calc() received at least one invalid value:"
  515. " op1: %f, op2: %f",
  516. d1, d2);
  517. return "'Invalid expression'";
  518. }
  519. if (opt == "+")
  520. val = d1 + d2;
  521. else if (opt == "-")
  522. val = d1 - d2;
  523. else if (opt == "*")
  524. val = d1 * d2;
  525. else if (opt == "/")
  526. val = d1 / d2;
  527. if (!isnormal(val)) {
  528. blog(LOG_ERROR,
  529. "Invalid calc() math resulted in non-normal number:"
  530. " %f %s %f = %f",
  531. d1, QT_TO_UTF8(opt), d2, val);
  532. return "'Invalid expression'";
  533. }
  534. bool isInteger = ceill(val) == val;
  535. QString result = QString::number(val, 'f', isInteger ? 0 : -1);
  536. /* Carry-over suffix */
  537. if (!val1.suffix.isEmpty())
  538. result += val1.suffix;
  539. else if (!val2.suffix.isEmpty())
  540. result += val2.suffix;
  541. return result;
  542. }
  543. static qsizetype FindEndOfOBSMetadata(const QString &content)
  544. {
  545. /* Find end of last OBS-specific section and strip it, kinda jank but should work */
  546. qsizetype end = 0;
  547. for (auto section : {"OBSThemeMeta", "OBSThemeVars", "OBSTheme"}) {
  548. qsizetype idx = content.indexOf(section, 0);
  549. if (idx > end) {
  550. end = content.indexOf('}', idx) + 1;
  551. }
  552. }
  553. return end;
  554. }
  555. static QString PrepareQSS(const QHash<QString, OBSThemeVariable> &vars,
  556. const QStringList &contents)
  557. {
  558. QString stylesheet;
  559. QString needleTemplate("var(--%1)");
  560. for (const QString &content : contents) {
  561. qsizetype offset = FindEndOfOBSMetadata(content);
  562. if (offset >= 0) {
  563. stylesheet += "\n";
  564. stylesheet += content.sliced(offset);
  565. }
  566. }
  567. for (const OBSThemeVariable &var_ : vars) {
  568. OBSThemeVariable var(var_);
  569. if (!ResolveVariable(vars, var))
  570. continue;
  571. QString needle = needleTemplate.arg(var_.name);
  572. QString replace;
  573. QVariant value = var.userValue.isValid() ? var.userValue
  574. : var.value;
  575. if (var.type == OBSThemeVariable::Color) {
  576. replace = value.value<QColor>().name(QColor::HexRgb);
  577. } else if (var.type == OBSThemeVariable::Calc) {
  578. replace = EvalCalc(vars, var);
  579. } else if (var.type == OBSThemeVariable::Size ||
  580. var.type == OBSThemeVariable::Number) {
  581. double val = value.toDouble();
  582. bool isInteger = ceill(val) == val;
  583. replace = QString::number(val, 'f', isInteger ? 0 : -1);
  584. if (!var.suffix.isEmpty())
  585. replace += var.suffix;
  586. } else {
  587. replace = value.toString();
  588. }
  589. stylesheet = stylesheet.replace(needle, replace);
  590. }
  591. return stylesheet;
  592. }
  593. template<typename T> static void FillEnumMap(QHash<QString, T> &map)
  594. {
  595. QMetaEnum meta = QMetaEnum::fromType<T>();
  596. int numKeys = meta.keyCount();
  597. for (int i = 0; i < numKeys; i++) {
  598. const char *key = meta.key(i);
  599. QString keyName(key);
  600. map[keyName.toLower()] = static_cast<T>(meta.keyToValue(key));
  601. }
  602. }
  603. static QPalette PreparePalette(const QHash<QString, OBSThemeVariable> &vars,
  604. const QPalette &defaultPalette)
  605. {
  606. static QHash<QString, QPalette::ColorRole> roleMap;
  607. static QHash<QString, QPalette::ColorGroup> groupMap;
  608. if (roleMap.empty())
  609. FillEnumMap<QPalette::ColorRole>(roleMap);
  610. if (groupMap.empty())
  611. FillEnumMap<QPalette::ColorGroup>(groupMap);
  612. QPalette pal(defaultPalette);
  613. for (const OBSThemeVariable &var_ : vars) {
  614. if (!var_.name.startsWith("palette_"))
  615. continue;
  616. if (var_.name.count("_") < 1 || var_.name.count("_") > 2)
  617. continue;
  618. OBSThemeVariable var(var_);
  619. if (!ResolveVariable(vars, var) ||
  620. var.type != OBSThemeVariable::Color)
  621. continue;
  622. /* Determine role and optionally group based on name.
  623. * Format is: palette_<role>[_<group>] */
  624. QPalette::ColorRole role = QPalette::NoRole;
  625. QPalette::ColorGroup group = QPalette::All;
  626. QStringList parts = var_.name.split("_");
  627. if (parts.length() >= 2) {
  628. QString key = parts[1].toLower();
  629. if (!roleMap.contains(key)) {
  630. blog(LOG_WARNING,
  631. "Palette role \"%s\" is not valid!",
  632. QT_TO_UTF8(parts[1]));
  633. continue;
  634. }
  635. role = roleMap[key];
  636. }
  637. if (parts.length() == 3) {
  638. QString key = parts[2].toLower();
  639. if (!groupMap.contains(key)) {
  640. blog(LOG_WARNING,
  641. "Palette group \"%s\" is not valid!",
  642. QT_TO_UTF8(parts[2]));
  643. continue;
  644. }
  645. group = groupMap[key];
  646. }
  647. QVariant value = var.userValue.isValid() ? var.userValue
  648. : var.value;
  649. QColor color = value.value<QColor>().name(QColor::HexRgb);
  650. pal.setColor(group, role, color);
  651. }
  652. return pal;
  653. }
  654. OBSTheme *OBSApp::GetTheme(const QString &name)
  655. {
  656. if (!themes.contains(name))
  657. return nullptr;
  658. return &themes[name];
  659. }
  660. bool OBSApp::SetTheme(const QString &name)
  661. {
  662. OBSTheme *theme = GetTheme(name);
  663. if (!theme)
  664. return false;
  665. if (themeWatcher) {
  666. themeWatcher->blockSignals(true);
  667. themeWatcher->removePaths(themeWatcher->files());
  668. }
  669. setStyleSheet("");
  670. currentTheme = theme;
  671. QStringList contents;
  672. QHash<QString, OBSThemeVariable> vars;
  673. /* Build list of themes to load (in order) */
  674. QStringList themeIds(theme->dependencies);
  675. themeIds << theme->id;
  676. /* Find and add high contrast adjustment layer if available */
  677. if (HighContrastEnabled()) {
  678. for (const OBSTheme &theme_ : themes) {
  679. if (!theme_.isHighContrast)
  680. continue;
  681. if (theme_.parent != theme->id)
  682. continue;
  683. themeIds << theme_.id;
  684. break;
  685. }
  686. }
  687. QStringList filenames;
  688. for (const QString &themeId : themeIds) {
  689. OBSTheme *cur = GetTheme(themeId);
  690. QFile file(cur->location);
  691. filenames << file.fileName();
  692. if (!file.open(QIODeviceBase::ReadOnly))
  693. return false;
  694. const QByteArray content = file.readAll();
  695. for (OBSThemeVariable &var :
  696. ParseThemeVariables(content.constData())) {
  697. vars[var.name] = std::move(var);
  698. }
  699. contents.emplaceBack(content.constData());
  700. }
  701. const QString stylesheet = PrepareQSS(vars, contents);
  702. const QPalette palette = PreparePalette(vars, defaultPalette);
  703. setPalette(palette);
  704. setStyleSheet(stylesheet);
  705. #ifdef _DEBUG
  706. /* Write resulting QSS to file in config dir "themes" folder. */
  707. string filename("obs-studio/themes/");
  708. filename += theme->id.toStdString();
  709. filename += ".out";
  710. filesystem::path debugOut;
  711. char configPath[512];
  712. if (GetConfigPath(configPath, sizeof(configPath), filename.c_str())) {
  713. debugOut = absolute(filesystem::u8path(configPath));
  714. filesystem::create_directories(debugOut.parent_path());
  715. }
  716. QFile debugFile(debugOut);
  717. if (debugFile.open(QIODeviceBase::WriteOnly)) {
  718. debugFile.write(stylesheet.toUtf8());
  719. debugFile.flush();
  720. }
  721. #endif
  722. #ifdef __APPLE__
  723. SetMacOSDarkMode(theme->isDark);
  724. #endif
  725. emit StyleChanged();
  726. if (themeWatcher) {
  727. themeWatcher->addPaths(filenames);
  728. /* Give it 250 ms before re-enabling the watcher to prevent too
  729. * many reloads when edited with an auto-saving IDE. */
  730. QTimer::singleShot(250, this,
  731. [&] { themeWatcher->blockSignals(false); });
  732. }
  733. return true;
  734. }
  735. void OBSApp::themeFileChanged(const QString &path)
  736. {
  737. themeWatcher->blockSignals(true);
  738. blog(LOG_INFO, "Theme file \"%s\" changed, reloading...",
  739. QT_TO_UTF8(path));
  740. SetTheme(currentTheme->id);
  741. }
  742. static map<string, string> themeMigrations = {
  743. {"Yami", DEFAULT_THEME},
  744. {"Grey", "com.obsproject.Yami.Grey"},
  745. {"Rachni", "com.obsproject.Yami.Rachni"},
  746. {"Light", "com.obsproject.Yami.Light"},
  747. {"Dark", "com.obsproject.Yami.Classic"},
  748. {"Acri", "com.obsproject.Yami.Acri"},
  749. {"System", "com.obsproject.System"},
  750. };
  751. bool OBSApp::InitTheme()
  752. {
  753. defaultPalette = palette();
  754. #if !defined(_WIN32) && !defined(__APPLE__)
  755. setStyle(new OBSProxyStyle("Fusion"));
  756. #else
  757. setStyle(new OBSProxyStyle());
  758. #endif
  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. }