obs-app-theming.cpp 24 KB

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