OBSApp_Themes.cpp 24 KB

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