OBSApp.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608
  1. /******************************************************************************
  2. Copyright (C) 2023 by Lain Bailey <[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 <components/Multiview.hpp>
  16. #include <utility/OBSEventFilter.hpp>
  17. #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER)
  18. #include <utility/models/branches.hpp>
  19. #endif
  20. #include <widgets/OBSBasic.hpp>
  21. #if !defined(_WIN32) && !defined(__APPLE__)
  22. #include <obs-nix-platform.h>
  23. #if QT_VERSION < QT_VERSION_CHECK(6, 5, 0)
  24. #include <qpa/qplatformnativeinterface.h>
  25. #endif
  26. #endif
  27. #include <qt-wrappers.hpp>
  28. #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER)
  29. #include <QFile>
  30. #endif
  31. #ifdef _WIN32
  32. #include <QSessionManager>
  33. #else
  34. #include <QSocketNotifier>
  35. #endif
  36. #ifdef _WIN32
  37. #include <sstream>
  38. #define WIN32_LEAN_AND_MEAN
  39. #include <windows.h>
  40. #else
  41. #include <unistd.h>
  42. #include <sys/socket.h>
  43. #endif
  44. #include "moc_OBSApp.cpp"
  45. using namespace std;
  46. string currentLogFile;
  47. string lastLogFile;
  48. string lastCrashLogFile;
  49. extern bool portable_mode;
  50. extern bool safe_mode;
  51. extern bool disable_3p_plugins;
  52. extern bool opt_disable_updater;
  53. extern bool opt_disable_missing_files_check;
  54. extern string opt_starting_collection;
  55. extern string opt_starting_profile;
  56. extern QPointer<OBSLogViewer> obsLogViewer;
  57. #ifndef _WIN32
  58. int OBSApp::sigintFd[2];
  59. #endif
  60. // GPU hint exports for AMD/NVIDIA laptops
  61. #ifdef _MSC_VER
  62. extern "C" __declspec(dllexport) DWORD NvOptimusEnablement = 1;
  63. extern "C" __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  64. #endif
  65. QObject *CreateShortcutFilter()
  66. {
  67. return new OBSEventFilter([](QObject *obj, QEvent *event) {
  68. auto mouse_event = [](QMouseEvent &event) {
  69. if (!App()->HotkeysEnabledInFocus() && event.button() != Qt::LeftButton)
  70. return true;
  71. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  72. bool pressed = event.type() == QEvent::MouseButtonPress;
  73. switch (event.button()) {
  74. case Qt::NoButton:
  75. case Qt::LeftButton:
  76. case Qt::RightButton:
  77. case Qt::AllButtons:
  78. case Qt::MouseButtonMask:
  79. return false;
  80. case Qt::MiddleButton:
  81. hotkey.key = OBS_KEY_MOUSE3;
  82. break;
  83. #define MAP_BUTTON(i, j) \
  84. case Qt::ExtraButton##i: \
  85. hotkey.key = OBS_KEY_MOUSE##j; \
  86. break;
  87. MAP_BUTTON(1, 4);
  88. MAP_BUTTON(2, 5);
  89. MAP_BUTTON(3, 6);
  90. MAP_BUTTON(4, 7);
  91. MAP_BUTTON(5, 8);
  92. MAP_BUTTON(6, 9);
  93. MAP_BUTTON(7, 10);
  94. MAP_BUTTON(8, 11);
  95. MAP_BUTTON(9, 12);
  96. MAP_BUTTON(10, 13);
  97. MAP_BUTTON(11, 14);
  98. MAP_BUTTON(12, 15);
  99. MAP_BUTTON(13, 16);
  100. MAP_BUTTON(14, 17);
  101. MAP_BUTTON(15, 18);
  102. MAP_BUTTON(16, 19);
  103. MAP_BUTTON(17, 20);
  104. MAP_BUTTON(18, 21);
  105. MAP_BUTTON(19, 22);
  106. MAP_BUTTON(20, 23);
  107. MAP_BUTTON(21, 24);
  108. MAP_BUTTON(22, 25);
  109. MAP_BUTTON(23, 26);
  110. MAP_BUTTON(24, 27);
  111. #undef MAP_BUTTON
  112. }
  113. hotkey.modifiers = TranslateQtKeyboardEventModifiers(event.modifiers());
  114. obs_hotkey_inject_event(hotkey, pressed);
  115. return true;
  116. };
  117. auto key_event = [&](QKeyEvent *event) {
  118. int key = event->key();
  119. bool enabledInFocus = App()->HotkeysEnabledInFocus();
  120. if (key != Qt::Key_Enter && key != Qt::Key_Escape && key != Qt::Key_Return && !enabledInFocus)
  121. return true;
  122. QDialog *dialog = qobject_cast<QDialog *>(obj);
  123. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  124. bool pressed = event->type() == QEvent::KeyPress;
  125. switch (key) {
  126. case Qt::Key_Shift:
  127. case Qt::Key_Control:
  128. case Qt::Key_Alt:
  129. case Qt::Key_Meta:
  130. break;
  131. #ifdef __APPLE__
  132. case Qt::Key_CapsLock:
  133. // kVK_CapsLock == 57
  134. hotkey.key = obs_key_from_virtual_key(57);
  135. pressed = true;
  136. break;
  137. #endif
  138. case Qt::Key_Enter:
  139. case Qt::Key_Escape:
  140. case Qt::Key_Return:
  141. if (dialog && pressed)
  142. return false;
  143. if (!enabledInFocus)
  144. return true;
  145. /* Falls through. */
  146. default:
  147. hotkey.key = obs_key_from_virtual_key(event->nativeVirtualKey());
  148. }
  149. if (event->isAutoRepeat())
  150. return true;
  151. hotkey.modifiers = TranslateQtKeyboardEventModifiers(event->modifiers());
  152. obs_hotkey_inject_event(hotkey, pressed);
  153. return true;
  154. };
  155. switch (event->type()) {
  156. case QEvent::MouseButtonPress:
  157. case QEvent::MouseButtonRelease:
  158. return mouse_event(*static_cast<QMouseEvent *>(event));
  159. /*case QEvent::MouseButtonDblClick:
  160. case QEvent::Wheel:*/
  161. case QEvent::KeyPress:
  162. case QEvent::KeyRelease:
  163. return key_event(static_cast<QKeyEvent *>(event));
  164. default:
  165. return false;
  166. }
  167. });
  168. }
  169. string CurrentDateTimeString()
  170. {
  171. time_t now = time(0);
  172. struct tm tstruct;
  173. char buf[80];
  174. tstruct = *localtime(&now);
  175. strftime(buf, sizeof(buf), "%Y-%m-%d, %X", &tstruct);
  176. return buf;
  177. }
  178. #define DEFAULT_LANG "en-US"
  179. bool OBSApp::InitGlobalConfigDefaults()
  180. {
  181. config_set_default_uint(appConfig, "General", "MaxLogs", 10);
  182. config_set_default_int(appConfig, "General", "InfoIncrement", -1);
  183. config_set_default_string(appConfig, "General", "ProcessPriority", "Normal");
  184. config_set_default_bool(appConfig, "General", "EnableAutoUpdates", true);
  185. #if _WIN32
  186. config_set_default_string(appConfig, "Video", "Renderer", "Direct3D 11");
  187. #else
  188. config_set_default_string(appConfig, "Video", "Renderer", "OpenGL");
  189. #endif
  190. #ifdef _WIN32
  191. config_set_default_bool(appConfig, "Audio", "DisableAudioDucking", true);
  192. config_set_default_bool(appConfig, "General", "BrowserHWAccel", true);
  193. #endif
  194. #ifdef __APPLE__
  195. config_set_default_bool(appConfig, "General", "BrowserHWAccel", true);
  196. config_set_default_bool(appConfig, "Video", "DisableOSXVSync", true);
  197. config_set_default_bool(appConfig, "Video", "ResetOSXVSyncOnExit", true);
  198. #endif
  199. return true;
  200. }
  201. bool OBSApp::InitGlobalLocationDefaults()
  202. {
  203. char path[512];
  204. int len = GetAppConfigPath(path, sizeof(path), nullptr);
  205. if (len <= 0) {
  206. OBSErrorBox(NULL, "Unable to get global configuration path.");
  207. return false;
  208. }
  209. config_set_default_string(appConfig, "Locations", "Configuration", path);
  210. config_set_default_string(appConfig, "Locations", "SceneCollections", path);
  211. config_set_default_string(appConfig, "Locations", "Profiles", path);
  212. return true;
  213. }
  214. void OBSApp::InitUserConfigDefaults()
  215. {
  216. config_set_default_bool(userConfig, "General", "ConfirmOnExit", true);
  217. config_set_default_string(userConfig, "General", "HotkeyFocusType", "NeverDisableHotkeys");
  218. config_set_default_bool(userConfig, "BasicWindow", "PreviewEnabled", true);
  219. config_set_default_bool(userConfig, "BasicWindow", "PreviewProgramMode", false);
  220. config_set_default_bool(userConfig, "BasicWindow", "SceneDuplicationMode", true);
  221. config_set_default_bool(userConfig, "BasicWindow", "SwapScenesMode", true);
  222. config_set_default_bool(userConfig, "BasicWindow", "SnappingEnabled", true);
  223. config_set_default_bool(userConfig, "BasicWindow", "ScreenSnapping", true);
  224. config_set_default_bool(userConfig, "BasicWindow", "SourceSnapping", true);
  225. config_set_default_bool(userConfig, "BasicWindow", "CenterSnapping", false);
  226. config_set_default_double(userConfig, "BasicWindow", "SnapDistance", 10.0);
  227. config_set_default_bool(userConfig, "BasicWindow", "SpacingHelpersEnabled", true);
  228. config_set_default_bool(userConfig, "BasicWindow", "RecordWhenStreaming", false);
  229. config_set_default_bool(userConfig, "BasicWindow", "KeepRecordingWhenStreamStops", false);
  230. config_set_default_bool(userConfig, "BasicWindow", "SysTrayEnabled", true);
  231. config_set_default_bool(userConfig, "BasicWindow", "SysTrayWhenStarted", false);
  232. config_set_default_bool(userConfig, "BasicWindow", "SaveProjectors", false);
  233. config_set_default_bool(userConfig, "BasicWindow", "ShowTransitions", true);
  234. config_set_default_bool(userConfig, "BasicWindow", "ShowListboxToolbars", true);
  235. config_set_default_bool(userConfig, "BasicWindow", "ShowStatusBar", true);
  236. config_set_default_bool(userConfig, "BasicWindow", "ShowSourceIcons", true);
  237. config_set_default_bool(userConfig, "BasicWindow", "ShowContextToolbars", true);
  238. config_set_default_bool(userConfig, "BasicWindow", "StudioModeLabels", true);
  239. config_set_default_bool(userConfig, "BasicWindow", "VerticalVolControl", false);
  240. config_set_default_bool(userConfig, "BasicWindow", "MultiviewMouseSwitch", true);
  241. config_set_default_bool(userConfig, "BasicWindow", "MultiviewDrawNames", true);
  242. config_set_default_bool(userConfig, "BasicWindow", "MultiviewDrawAreas", true);
  243. config_set_default_bool(userConfig, "BasicWindow", "MediaControlsCountdownTimer", true);
  244. config_set_default_int(userConfig, "Appearance", "FontScale", 10);
  245. config_set_default_int(userConfig, "Appearance", "Density", 1);
  246. }
  247. static bool do_mkdir(const char *path)
  248. {
  249. if (os_mkdirs(path) == MKDIR_ERROR) {
  250. OBSErrorBox(NULL, "Failed to create directory %s", path);
  251. return false;
  252. }
  253. return true;
  254. }
  255. static bool MakeUserDirs()
  256. {
  257. char path[512];
  258. if (GetAppConfigPath(path, sizeof(path), "obs-studio/basic") <= 0)
  259. return false;
  260. if (!do_mkdir(path))
  261. return false;
  262. if (GetAppConfigPath(path, sizeof(path), "obs-studio/logs") <= 0)
  263. return false;
  264. if (!do_mkdir(path))
  265. return false;
  266. if (GetAppConfigPath(path, sizeof(path), "obs-studio/profiler_data") <= 0)
  267. return false;
  268. if (!do_mkdir(path))
  269. return false;
  270. #ifdef _WIN32
  271. if (GetAppConfigPath(path, sizeof(path), "obs-studio/crashes") <= 0)
  272. return false;
  273. if (!do_mkdir(path))
  274. return false;
  275. #endif
  276. #ifdef WHATSNEW_ENABLED
  277. if (GetAppConfigPath(path, sizeof(path), "obs-studio/updates") <= 0)
  278. return false;
  279. if (!do_mkdir(path))
  280. return false;
  281. #endif
  282. if (GetAppConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
  283. return false;
  284. if (!do_mkdir(path))
  285. return false;
  286. return true;
  287. }
  288. constexpr std::string_view OBSProfileSubDirectory = "obs-studio/basic/profiles";
  289. constexpr std::string_view OBSScenesSubDirectory = "obs-studio/basic/scenes";
  290. static bool MakeUserProfileDirs()
  291. {
  292. const std::filesystem::path userProfilePath =
  293. App()->userProfilesLocation / std::filesystem::u8path(OBSProfileSubDirectory);
  294. const std::filesystem::path userScenesPath =
  295. App()->userScenesLocation / std::filesystem::u8path(OBSScenesSubDirectory);
  296. if (!std::filesystem::exists(userProfilePath)) {
  297. try {
  298. std::filesystem::create_directories(userProfilePath);
  299. } catch (const std::filesystem::filesystem_error &error) {
  300. blog(LOG_ERROR, "Failed to create user profile directory '%s'\n%s",
  301. userProfilePath.u8string().c_str(), error.what());
  302. return false;
  303. }
  304. }
  305. if (!std::filesystem::exists(userScenesPath)) {
  306. try {
  307. std::filesystem::create_directories(userScenesPath);
  308. } catch (const std::filesystem::filesystem_error &error) {
  309. blog(LOG_ERROR, "Failed to create user scene collection directory '%s'\n%s",
  310. userScenesPath.u8string().c_str(), error.what());
  311. return false;
  312. }
  313. }
  314. return true;
  315. }
  316. bool OBSApp::UpdatePre22MultiviewLayout(const char *layout)
  317. {
  318. if (!layout)
  319. return false;
  320. if (astrcmpi(layout, "horizontaltop") == 0) {
  321. config_set_int(userConfig, "BasicWindow", "MultiviewLayout",
  322. static_cast<int>(MultiviewLayout::HORIZONTAL_TOP_8_SCENES));
  323. return true;
  324. }
  325. if (astrcmpi(layout, "horizontalbottom") == 0) {
  326. config_set_int(userConfig, "BasicWindow", "MultiviewLayout",
  327. static_cast<int>(MultiviewLayout::HORIZONTAL_BOTTOM_8_SCENES));
  328. return true;
  329. }
  330. if (astrcmpi(layout, "verticalleft") == 0) {
  331. config_set_int(userConfig, "BasicWindow", "MultiviewLayout",
  332. static_cast<int>(MultiviewLayout::VERTICAL_LEFT_8_SCENES));
  333. return true;
  334. }
  335. if (astrcmpi(layout, "verticalright") == 0) {
  336. config_set_int(userConfig, "BasicWindow", "MultiviewLayout",
  337. static_cast<int>(MultiviewLayout::VERTICAL_RIGHT_8_SCENES));
  338. return true;
  339. }
  340. return false;
  341. }
  342. bool OBSApp::InitGlobalConfig()
  343. {
  344. char path[512];
  345. int len = GetAppConfigPath(path, sizeof(path), "obs-studio/global.ini");
  346. if (len <= 0) {
  347. return false;
  348. }
  349. int errorcode = appConfig.Open(path, CONFIG_OPEN_ALWAYS);
  350. if (errorcode != CONFIG_SUCCESS) {
  351. OBSErrorBox(NULL, "Failed to open global.ini: %d", errorcode);
  352. return false;
  353. }
  354. uint32_t lastVersion = config_get_int(appConfig, "General", "LastVersion");
  355. if (lastVersion && lastVersion < MAKE_SEMANTIC_VERSION(31, 0, 0)) {
  356. bool migratedUserSettings = config_get_bool(appConfig, "General", "Pre31Migrated");
  357. if (!migratedUserSettings) {
  358. bool migrated = MigrateGlobalSettings();
  359. config_set_bool(appConfig, "General", "Pre31Migrated", migrated);
  360. config_save_safe(appConfig, "tmp", nullptr);
  361. }
  362. }
  363. InitGlobalConfigDefaults();
  364. InitGlobalLocationDefaults();
  365. std::filesystem::path defaultUserConfigLocation =
  366. std::filesystem::u8path(config_get_default_string(appConfig, "Locations", "Configuration"));
  367. std::filesystem::path defaultUserScenesLocation =
  368. std::filesystem::u8path(config_get_default_string(appConfig, "Locations", "SceneCollections"));
  369. std::filesystem::path defaultUserProfilesLocation =
  370. std::filesystem::u8path(config_get_default_string(appConfig, "Locations", "Profiles"));
  371. if (IsPortableMode()) {
  372. userConfigLocation = std::move(defaultUserConfigLocation);
  373. userScenesLocation = std::move(defaultUserScenesLocation);
  374. userProfilesLocation = std::move(defaultUserProfilesLocation);
  375. } else {
  376. std::filesystem::path currentUserConfigLocation =
  377. std::filesystem::u8path(config_get_string(appConfig, "Locations", "Configuration"));
  378. std::filesystem::path currentUserScenesLocation =
  379. std::filesystem::u8path(config_get_string(appConfig, "Locations", "SceneCollections"));
  380. std::filesystem::path currentUserProfilesLocation =
  381. std::filesystem::u8path(config_get_string(appConfig, "Locations", "Profiles"));
  382. userConfigLocation = (std::filesystem::exists(currentUserConfigLocation))
  383. ? std::move(currentUserConfigLocation)
  384. : std::move(defaultUserConfigLocation);
  385. userScenesLocation = (std::filesystem::exists(currentUserScenesLocation))
  386. ? std::move(currentUserScenesLocation)
  387. : std::move(defaultUserScenesLocation);
  388. userProfilesLocation = (std::filesystem::exists(currentUserProfilesLocation))
  389. ? std::move(currentUserProfilesLocation)
  390. : std::move(defaultUserProfilesLocation);
  391. }
  392. bool userConfigResult = InitUserConfig(userConfigLocation, lastVersion);
  393. return userConfigResult;
  394. }
  395. bool OBSApp::InitUserConfig(std::filesystem::path &userConfigLocation, uint32_t lastVersion)
  396. {
  397. const std::string userConfigFile = userConfigLocation.u8string() + "/obs-studio/user.ini";
  398. int errorCode = userConfig.Open(userConfigFile.c_str(), CONFIG_OPEN_ALWAYS);
  399. if (errorCode != CONFIG_SUCCESS) {
  400. OBSErrorBox(nullptr, "Failed to open user.ini: %d", errorCode);
  401. return false;
  402. }
  403. MigrateLegacySettings(lastVersion);
  404. InitUserConfigDefaults();
  405. return true;
  406. }
  407. void OBSApp::MigrateLegacySettings(const uint32_t lastVersion)
  408. {
  409. bool hasChanges = false;
  410. const uint32_t v19 = MAKE_SEMANTIC_VERSION(19, 0, 0);
  411. const uint32_t v21 = MAKE_SEMANTIC_VERSION(21, 0, 0);
  412. const uint32_t v23 = MAKE_SEMANTIC_VERSION(23, 0, 0);
  413. const uint32_t v24 = MAKE_SEMANTIC_VERSION(24, 0, 0);
  414. const uint32_t v24_1 = MAKE_SEMANTIC_VERSION(24, 1, 0);
  415. const map<uint32_t, string> defaultsMap{
  416. {{v19, "Pre19Defaults"}, {v21, "Pre21Defaults"}, {v23, "Pre23Defaults"}, {v24_1, "Pre24.1Defaults"}}};
  417. for (auto &[version, configKey] : defaultsMap) {
  418. if (!config_has_user_value(userConfig, "General", configKey.c_str())) {
  419. bool useOldDefaults = lastVersion && lastVersion < version;
  420. config_set_bool(userConfig, "General", configKey.c_str(), useOldDefaults);
  421. hasChanges = true;
  422. }
  423. }
  424. if (config_has_user_value(userConfig, "BasicWindow", "MultiviewLayout")) {
  425. const char *layout = config_get_string(userConfig, "BasicWindow", "MultiviewLayout");
  426. bool layoutUpdated = UpdatePre22MultiviewLayout(layout);
  427. hasChanges = hasChanges | layoutUpdated;
  428. }
  429. if (lastVersion && lastVersion < v24) {
  430. bool disableHotkeysInFocus = config_get_bool(userConfig, "General", "DisableHotkeysInFocus");
  431. if (disableHotkeysInFocus) {
  432. config_set_string(userConfig, "General", "HotkeyFocusType", "DisableHotkeysInFocus");
  433. }
  434. hasChanges = true;
  435. }
  436. if (hasChanges) {
  437. userConfig.SaveSafe("tmp");
  438. }
  439. }
  440. static constexpr string_view OBSGlobalIniPath = "/obs-studio/global.ini";
  441. static constexpr string_view OBSUserIniPath = "/obs-studio/user.ini";
  442. bool OBSApp::MigrateGlobalSettings()
  443. {
  444. char path[512];
  445. int len = GetAppConfigPath(path, sizeof(path), nullptr);
  446. if (len <= 0) {
  447. OBSErrorBox(nullptr, "Unable to get global configuration path.");
  448. return false;
  449. }
  450. std::string legacyConfigFileString;
  451. legacyConfigFileString.reserve(strlen(path) + OBSGlobalIniPath.size());
  452. legacyConfigFileString.append(path).append(OBSGlobalIniPath);
  453. const std::filesystem::path legacyGlobalConfigFile = std::filesystem::u8path(legacyConfigFileString);
  454. std::string configFileString;
  455. configFileString.reserve(strlen(path) + OBSUserIniPath.size());
  456. configFileString.append(path).append(OBSUserIniPath);
  457. const std::filesystem::path userConfigFile = std::filesystem::u8path(configFileString);
  458. if (std::filesystem::exists(userConfigFile)) {
  459. OBSErrorBox(nullptr,
  460. "Unable to migrate global configuration - user configuration file already exists.");
  461. return false;
  462. }
  463. try {
  464. std::filesystem::copy(legacyGlobalConfigFile, userConfigFile);
  465. } catch (const std::filesystem::filesystem_error &) {
  466. OBSErrorBox(nullptr, "Unable to migrate global configuration - copy failed.");
  467. return false;
  468. }
  469. return true;
  470. }
  471. bool OBSApp::InitLocale()
  472. {
  473. ProfileScope("OBSApp::InitLocale");
  474. const char *lang = config_get_string(userConfig, "General", "Language");
  475. bool userLocale = config_has_user_value(userConfig, "General", "Language");
  476. if (!userLocale || !lang || lang[0] == '\0')
  477. lang = DEFAULT_LANG;
  478. locale = lang;
  479. // set basic default application locale
  480. if (!locale.empty())
  481. QLocale::setDefault(QLocale(QString::fromStdString(locale).replace('-', '_')));
  482. string englishPath;
  483. if (!GetDataFilePath("locale/" DEFAULT_LANG ".ini", englishPath)) {
  484. OBSErrorBox(NULL, "Failed to find locale/" DEFAULT_LANG ".ini");
  485. return false;
  486. }
  487. textLookup = text_lookup_create(englishPath.c_str());
  488. if (!textLookup) {
  489. OBSErrorBox(NULL, "Failed to create locale from file '%s'", englishPath.c_str());
  490. return false;
  491. }
  492. bool defaultLang = astrcmpi(lang, DEFAULT_LANG) == 0;
  493. if (userLocale && defaultLang)
  494. return true;
  495. if (!userLocale && defaultLang) {
  496. for (auto &locale_ : GetPreferredLocales()) {
  497. if (locale_ == lang)
  498. return true;
  499. stringstream file;
  500. file << "locale/" << locale_ << ".ini";
  501. string path;
  502. if (!GetDataFilePath(file.str().c_str(), path))
  503. continue;
  504. if (!text_lookup_add(textLookup, path.c_str()))
  505. continue;
  506. blog(LOG_INFO, "Using preferred locale '%s'", locale_.c_str());
  507. locale = locale_;
  508. // set application default locale to the new choosen one
  509. if (!locale.empty())
  510. QLocale::setDefault(QLocale(QString::fromStdString(locale).replace('-', '_')));
  511. return true;
  512. }
  513. return true;
  514. }
  515. stringstream file;
  516. file << "locale/" << lang << ".ini";
  517. string path;
  518. if (GetDataFilePath(file.str().c_str(), path)) {
  519. if (!text_lookup_add(textLookup, path.c_str()))
  520. blog(LOG_ERROR, "Failed to add locale file '%s'", path.c_str());
  521. } else {
  522. blog(LOG_ERROR, "Could not find locale file '%s'", file.str().c_str());
  523. }
  524. return true;
  525. }
  526. #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER)
  527. void ParseBranchesJson(const std::string &jsonString, vector<UpdateBranch> &out, std::string &error)
  528. {
  529. JsonBranches branches;
  530. try {
  531. nlohmann::json json = nlohmann::json::parse(jsonString);
  532. branches = json.get<JsonBranches>();
  533. } catch (nlohmann::json::exception &e) {
  534. error = e.what();
  535. return;
  536. }
  537. for (const JsonBranch &json_branch : branches) {
  538. #ifdef _WIN32
  539. if (!json_branch.windows)
  540. continue;
  541. #elif defined(__APPLE__)
  542. if (!json_branch.macos)
  543. continue;
  544. #endif
  545. UpdateBranch branch = {
  546. QString::fromStdString(json_branch.name),
  547. QString::fromStdString(json_branch.display_name),
  548. QString::fromStdString(json_branch.description),
  549. json_branch.enabled,
  550. json_branch.visible,
  551. };
  552. out.push_back(branch);
  553. }
  554. }
  555. bool LoadBranchesFile(vector<UpdateBranch> &out)
  556. {
  557. string error;
  558. string branchesText;
  559. BPtr<char> branchesFilePath = GetAppConfigPathPtr("obs-studio/updates/branches.json");
  560. QFile branchesFile(branchesFilePath.Get());
  561. if (!branchesFile.open(QIODevice::ReadOnly)) {
  562. error = "Opening file failed.";
  563. goto fail;
  564. }
  565. branchesText = branchesFile.readAll();
  566. if (branchesText.empty()) {
  567. error = "File empty.";
  568. goto fail;
  569. }
  570. ParseBranchesJson(branchesText, out, error);
  571. if (error.empty())
  572. return !out.empty();
  573. fail:
  574. blog(LOG_WARNING, "Loading branches from file failed: %s", error.c_str());
  575. return false;
  576. }
  577. #endif
  578. void OBSApp::SetBranchData(const string &data)
  579. {
  580. #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER)
  581. string error;
  582. vector<UpdateBranch> result;
  583. ParseBranchesJson(data, result, error);
  584. if (!error.empty()) {
  585. blog(LOG_WARNING, "Reading branches JSON response failed: %s", error.c_str());
  586. return;
  587. }
  588. if (!result.empty())
  589. updateBranches = result;
  590. branches_loaded = true;
  591. #else
  592. UNUSED_PARAMETER(data);
  593. #endif
  594. }
  595. std::vector<UpdateBranch> OBSApp::GetBranches()
  596. {
  597. vector<UpdateBranch> out;
  598. /* Always ensure the default branch exists */
  599. out.push_back(UpdateBranch{"stable", "", "", true, true});
  600. #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER)
  601. if (!branches_loaded) {
  602. vector<UpdateBranch> result;
  603. if (LoadBranchesFile(result))
  604. updateBranches = result;
  605. branches_loaded = true;
  606. }
  607. #endif
  608. /* Copy additional branches to result (if any) */
  609. if (!updateBranches.empty())
  610. out.insert(out.end(), updateBranches.begin(), updateBranches.end());
  611. return out;
  612. }
  613. OBSApp::OBSApp(int &argc, char **argv, profiler_name_store_t *store)
  614. : QApplication(argc, argv),
  615. profilerNameStore(store)
  616. {
  617. /* fix float handling */
  618. #if defined(Q_OS_UNIX)
  619. if (!setlocale(LC_NUMERIC, "C"))
  620. blog(LOG_WARNING, "Failed to set LC_NUMERIC to C locale");
  621. #endif
  622. #ifndef _WIN32
  623. /* Handle SIGINT properly */
  624. socketpair(AF_UNIX, SOCK_STREAM, 0, sigintFd);
  625. snInt = new QSocketNotifier(sigintFd[1], QSocketNotifier::Read, this);
  626. connect(snInt, &QSocketNotifier::activated, this, &OBSApp::ProcessSigInt);
  627. #else
  628. connect(qApp, &QGuiApplication::commitDataRequest, this, &OBSApp::commitData);
  629. #endif
  630. sleepInhibitor = os_inhibit_sleep_create("OBS Video/audio");
  631. #ifndef __APPLE__
  632. setWindowIcon(QIcon::fromTheme("obs", QIcon(":/res/images/obs.png")));
  633. #endif
  634. setDesktopFileName("com.obsproject.Studio");
  635. }
  636. OBSApp::~OBSApp()
  637. {
  638. #ifdef _WIN32
  639. bool disableAudioDucking = config_get_bool(appConfig, "Audio", "DisableAudioDucking");
  640. if (disableAudioDucking)
  641. DisableAudioDucking(false);
  642. #else
  643. delete snInt;
  644. close(sigintFd[0]);
  645. close(sigintFd[1]);
  646. #endif
  647. #ifdef __APPLE__
  648. bool vsyncDisabled = config_get_bool(appConfig, "Video", "DisableOSXVSync");
  649. bool resetVSync = config_get_bool(appConfig, "Video", "ResetOSXVSyncOnExit");
  650. if (vsyncDisabled && resetVSync)
  651. EnableOSXVSync(true);
  652. #endif
  653. os_inhibit_sleep_set_active(sleepInhibitor, false);
  654. os_inhibit_sleep_destroy(sleepInhibitor);
  655. if (libobs_initialized)
  656. obs_shutdown();
  657. }
  658. static void move_basic_to_profiles(void)
  659. {
  660. char path[512];
  661. if (GetAppConfigPath(path, 512, "obs-studio/basic") <= 0) {
  662. return;
  663. }
  664. const std::filesystem::path basicPath = std::filesystem::u8path(path);
  665. if (!std::filesystem::exists(basicPath)) {
  666. return;
  667. }
  668. const std::filesystem::path profilesPath =
  669. App()->userProfilesLocation / std::filesystem::u8path("obs-studio/basic/profiles");
  670. if (std::filesystem::exists(profilesPath)) {
  671. return;
  672. }
  673. try {
  674. std::filesystem::create_directories(profilesPath);
  675. } catch (const std::filesystem::filesystem_error &error) {
  676. blog(LOG_ERROR, "Failed to create profiles directory for migration from basic profile\n%s",
  677. error.what());
  678. return;
  679. }
  680. const std::filesystem::path newProfilePath = profilesPath / std::filesystem::u8path(Str("Untitled"));
  681. for (auto &entry : std::filesystem::directory_iterator(basicPath)) {
  682. if (entry.is_directory()) {
  683. continue;
  684. }
  685. if (entry.path().filename().u8string() == "scenes.json") {
  686. continue;
  687. }
  688. if (!std::filesystem::exists(newProfilePath)) {
  689. try {
  690. std::filesystem::create_directory(newProfilePath);
  691. } catch (const std::filesystem::filesystem_error &error) {
  692. blog(LOG_ERROR, "Failed to create profile directory for 'Untitled'\n%s", error.what());
  693. return;
  694. }
  695. }
  696. const filesystem::path destinationFile = newProfilePath / entry.path().filename();
  697. const auto copyOptions = std::filesystem::copy_options::overwrite_existing;
  698. try {
  699. std::filesystem::copy(entry.path(), destinationFile, copyOptions);
  700. } catch (const std::filesystem::filesystem_error &error) {
  701. blog(LOG_ERROR, "Failed to copy basic profile file '%s' to new profile 'Untitled'\n%s",
  702. entry.path().filename().u8string().c_str(), error.what());
  703. return;
  704. }
  705. }
  706. }
  707. static void move_basic_to_scene_collections(void)
  708. {
  709. char path[512];
  710. if (GetAppConfigPath(path, 512, "obs-studio/basic") <= 0) {
  711. return;
  712. }
  713. const std::filesystem::path basicPath = std::filesystem::u8path(path);
  714. if (!std::filesystem::exists(basicPath)) {
  715. return;
  716. }
  717. const std::filesystem::path sceneCollectionPath =
  718. App()->userScenesLocation / std::filesystem::u8path("obs-studio/basic/scenes");
  719. if (std::filesystem::exists(sceneCollectionPath)) {
  720. return;
  721. }
  722. try {
  723. std::filesystem::create_directories(sceneCollectionPath);
  724. } catch (const std::filesystem::filesystem_error &error) {
  725. blog(LOG_ERROR,
  726. "Failed to create scene collection directory for migration from basic scene collection\n%s",
  727. error.what());
  728. return;
  729. }
  730. const std::filesystem::path sourceFile = basicPath / std::filesystem::u8path("scenes.json");
  731. const std::filesystem::path destinationFile =
  732. (sceneCollectionPath / std::filesystem::u8path(Str("Untitled"))).replace_extension(".json");
  733. try {
  734. std::filesystem::rename(sourceFile, destinationFile);
  735. } catch (const std::filesystem::filesystem_error &error) {
  736. blog(LOG_ERROR, "Failed to rename basic scene collection file:\n%s", error.what());
  737. return;
  738. }
  739. }
  740. void OBSApp::AppInit()
  741. {
  742. ProfileScope("OBSApp::AppInit");
  743. if (!MakeUserDirs())
  744. throw "Failed to create required user directories";
  745. if (!InitGlobalConfig())
  746. throw "Failed to initialize global config";
  747. if (!InitLocale())
  748. throw "Failed to load locale";
  749. if (!InitTheme())
  750. throw "Failed to load theme";
  751. config_set_default_string(userConfig, "Basic", "Profile", Str("Untitled"));
  752. config_set_default_string(userConfig, "Basic", "ProfileDir", Str("Untitled"));
  753. config_set_default_string(userConfig, "Basic", "SceneCollection", Str("Untitled"));
  754. config_set_default_string(userConfig, "Basic", "SceneCollectionFile", Str("Untitled"));
  755. config_set_default_bool(userConfig, "Basic", "ConfigOnNewProfile", true);
  756. const std::string_view profileName{config_get_string(userConfig, "Basic", "Profile")};
  757. if (profileName.empty()) {
  758. config_set_string(userConfig, "Basic", "Profile", Str("Untitled"));
  759. config_set_string(userConfig, "Basic", "ProfileDir", Str("Untitled"));
  760. }
  761. const std::string_view sceneCollectionName{config_get_string(userConfig, "Basic", "SceneCollection")};
  762. if (sceneCollectionName.empty()) {
  763. config_set_string(userConfig, "Basic", "SceneCollection", Str("Untitled"));
  764. config_set_string(userConfig, "Basic", "SceneCollectionFile", Str("Untitled"));
  765. }
  766. #ifdef _WIN32
  767. bool disableAudioDucking = config_get_bool(appConfig, "Audio", "DisableAudioDucking");
  768. if (disableAudioDucking)
  769. DisableAudioDucking(true);
  770. #endif
  771. #ifdef __APPLE__
  772. if (config_get_bool(appConfig, "Video", "DisableOSXVSync"))
  773. EnableOSXVSync(false);
  774. #endif
  775. UpdateHotkeyFocusSetting(false);
  776. move_basic_to_profiles();
  777. move_basic_to_scene_collections();
  778. if (!MakeUserProfileDirs())
  779. throw "Failed to create profile directories";
  780. }
  781. const char *OBSApp::GetRenderModule() const
  782. {
  783. const char *renderer = config_get_string(appConfig, "Video", "Renderer");
  784. return (astrcmpi(renderer, "Direct3D 11") == 0) ? DL_D3D11 : DL_OPENGL;
  785. }
  786. static bool StartupOBS(const char *locale, profiler_name_store_t *store)
  787. {
  788. char path[512];
  789. if (GetAppConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
  790. return false;
  791. return obs_startup(locale, path, store);
  792. }
  793. inline void OBSApp::ResetHotkeyState(bool inFocus)
  794. {
  795. obs_hotkey_enable_background_press((inFocus && enableHotkeysInFocus) || (!inFocus && enableHotkeysOutOfFocus));
  796. }
  797. void OBSApp::UpdateHotkeyFocusSetting(bool resetState)
  798. {
  799. enableHotkeysInFocus = true;
  800. enableHotkeysOutOfFocus = true;
  801. const char *hotkeyFocusType = config_get_string(userConfig, "General", "HotkeyFocusType");
  802. if (astrcmpi(hotkeyFocusType, "DisableHotkeysInFocus") == 0) {
  803. enableHotkeysInFocus = false;
  804. } else if (astrcmpi(hotkeyFocusType, "DisableHotkeysOutOfFocus") == 0) {
  805. enableHotkeysOutOfFocus = false;
  806. }
  807. if (resetState)
  808. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  809. }
  810. void OBSApp::DisableHotkeys()
  811. {
  812. enableHotkeysInFocus = false;
  813. enableHotkeysOutOfFocus = false;
  814. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  815. }
  816. void OBSApp::Exec(VoidFunc func)
  817. {
  818. func();
  819. }
  820. static void ui_task_handler(obs_task_t task, void *param, bool wait)
  821. {
  822. auto doTask = [=]() {
  823. /* to get clang-format to behave */
  824. task(param);
  825. };
  826. QMetaObject::invokeMethod(App(), "Exec", wait ? WaitConnection() : Qt::AutoConnection, Q_ARG(VoidFunc, doTask));
  827. }
  828. bool OBSApp::OBSInit()
  829. {
  830. ProfileScope("OBSApp::OBSInit");
  831. qRegisterMetaType<VoidFunc>("VoidFunc");
  832. #if !defined(_WIN32) && !defined(__APPLE__)
  833. if (QApplication::platformName() == "xcb") {
  834. #if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0)
  835. auto native = qGuiApp->nativeInterface<QNativeInterface::QX11Application>();
  836. obs_set_nix_platform_display(native->display());
  837. #endif
  838. obs_set_nix_platform(OBS_NIX_PLATFORM_X11_EGL);
  839. blog(LOG_INFO, "Using EGL/X11");
  840. }
  841. #ifdef ENABLE_WAYLAND
  842. if (QApplication::platformName().contains("wayland")) {
  843. #if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0)
  844. auto native = qGuiApp->nativeInterface<QNativeInterface::QWaylandApplication>();
  845. obs_set_nix_platform_display(native->display());
  846. #endif
  847. obs_set_nix_platform(OBS_NIX_PLATFORM_WAYLAND);
  848. setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
  849. blog(LOG_INFO, "Platform: Wayland");
  850. }
  851. #endif
  852. #if QT_VERSION < QT_VERSION_CHECK(6, 5, 0)
  853. QPlatformNativeInterface *native = QGuiApplication::platformNativeInterface();
  854. obs_set_nix_platform_display(native->nativeResourceForIntegration("display"));
  855. #endif
  856. #endif
  857. #ifdef __APPLE__
  858. setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
  859. #endif
  860. if (!StartupOBS(locale.c_str(), GetProfilerNameStore()))
  861. return false;
  862. libobs_initialized = true;
  863. obs_set_ui_task_handler(ui_task_handler);
  864. #if defined(_WIN32) || defined(__APPLE__)
  865. bool browserHWAccel = config_get_bool(appConfig, "General", "BrowserHWAccel");
  866. OBSDataAutoRelease settings = obs_data_create();
  867. obs_data_set_bool(settings, "BrowserHWAccel", browserHWAccel);
  868. obs_apply_private_data(settings);
  869. blog(LOG_INFO, "Current Date/Time: %s", CurrentDateTimeString().c_str());
  870. blog(LOG_INFO, "Browser Hardware Acceleration: %s", browserHWAccel ? "true" : "false");
  871. #endif
  872. #ifdef _WIN32
  873. bool hideFromCapture = config_get_bool(userConfig, "BasicWindow", "HideOBSWindowsFromCapture");
  874. blog(LOG_INFO, "Hide OBS windows from screen capture: %s", hideFromCapture ? "true" : "false");
  875. #endif
  876. blog(LOG_INFO, "Qt Version: %s (runtime), %s (compiled)", qVersion(), QT_VERSION_STR);
  877. blog(LOG_INFO, "Portable mode: %s", portable_mode ? "true" : "false");
  878. if (safe_mode) {
  879. blog(LOG_WARNING, "Safe Mode enabled.");
  880. } else if (disable_3p_plugins) {
  881. blog(LOG_WARNING, "Third-party plugins disabled.");
  882. }
  883. setQuitOnLastWindowClosed(false);
  884. mainWindow = new OBSBasic();
  885. mainWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  886. connect(mainWindow, &OBSBasic::destroyed, this, &OBSApp::quit);
  887. mainWindow->OBSInit();
  888. connect(this, &QGuiApplication::applicationStateChanged,
  889. [this](Qt::ApplicationState state) { ResetHotkeyState(state == Qt::ApplicationActive); });
  890. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  891. return true;
  892. }
  893. string OBSApp::GetVersionString(bool platform) const
  894. {
  895. stringstream ver;
  896. ver << obs_get_version_string();
  897. if (platform) {
  898. ver << " (";
  899. #ifdef _WIN32
  900. if (sizeof(void *) == 8)
  901. ver << "64-bit, ";
  902. else
  903. ver << "32-bit, ";
  904. ver << "windows)";
  905. #elif __APPLE__
  906. ver << "mac)";
  907. #elif __OpenBSD__
  908. ver << "openbsd)";
  909. #elif __FreeBSD__
  910. ver << "freebsd)";
  911. #else /* assume linux for the time being */
  912. ver << "linux)";
  913. #endif
  914. }
  915. return ver.str();
  916. }
  917. bool OBSApp::IsPortableMode()
  918. {
  919. return portable_mode;
  920. }
  921. bool OBSApp::IsUpdaterDisabled()
  922. {
  923. return opt_disable_updater;
  924. }
  925. bool OBSApp::IsMissingFilesCheckDisabled()
  926. {
  927. return opt_disable_missing_files_check;
  928. }
  929. #ifdef __APPLE__
  930. #define INPUT_AUDIO_SOURCE "coreaudio_input_capture"
  931. #define OUTPUT_AUDIO_SOURCE "coreaudio_output_capture"
  932. #elif _WIN32
  933. #define INPUT_AUDIO_SOURCE "wasapi_input_capture"
  934. #define OUTPUT_AUDIO_SOURCE "wasapi_output_capture"
  935. #else
  936. #define INPUT_AUDIO_SOURCE "pulse_input_capture"
  937. #define OUTPUT_AUDIO_SOURCE "pulse_output_capture"
  938. #endif
  939. const char *OBSApp::InputAudioSource() const
  940. {
  941. return INPUT_AUDIO_SOURCE;
  942. }
  943. const char *OBSApp::OutputAudioSource() const
  944. {
  945. return OUTPUT_AUDIO_SOURCE;
  946. }
  947. const char *OBSApp::GetLastLog() const
  948. {
  949. return lastLogFile.c_str();
  950. }
  951. const char *OBSApp::GetCurrentLog() const
  952. {
  953. return currentLogFile.c_str();
  954. }
  955. const char *OBSApp::GetLastCrashLog() const
  956. {
  957. return lastCrashLogFile.c_str();
  958. }
  959. bool OBSApp::TranslateString(const char *lookupVal, const char **out) const
  960. {
  961. for (obs_frontend_translate_ui_cb cb : translatorHooks) {
  962. if (cb(lookupVal, out))
  963. return true;
  964. }
  965. return text_lookup_getstr(App()->GetTextLookup(), lookupVal, out);
  966. }
  967. // Global handler to receive all QEvent::Show events so we can apply
  968. // display affinity on any newly created windows and dialogs without
  969. // caring where they are coming from (e.g. plugins).
  970. bool OBSApp::notify(QObject *receiver, QEvent *e)
  971. {
  972. QWidget *w;
  973. QWindow *window;
  974. int windowType;
  975. if (!receiver->isWidgetType())
  976. goto skip;
  977. if (e->type() != QEvent::Show)
  978. goto skip;
  979. w = qobject_cast<QWidget *>(receiver);
  980. if (!w->isWindow())
  981. goto skip;
  982. window = w->windowHandle();
  983. if (!window)
  984. goto skip;
  985. windowType = window->flags() & Qt::WindowType::WindowType_Mask;
  986. if (windowType == Qt::WindowType::Dialog || windowType == Qt::WindowType::Window ||
  987. windowType == Qt::WindowType::Tool) {
  988. OBSBasic *main = OBSBasic::Get();
  989. if (main)
  990. main->SetDisplayAffinity(window);
  991. }
  992. skip:
  993. return QApplication::notify(receiver, e);
  994. }
  995. string GenerateTimeDateFilename(const char *extension, bool noSpace)
  996. {
  997. time_t now = time(0);
  998. char file[256] = {};
  999. struct tm *cur_time;
  1000. cur_time = localtime(&now);
  1001. snprintf(file, sizeof(file), "%d-%02d-%02d%c%02d-%02d-%02d.%s", cur_time->tm_year + 1900, cur_time->tm_mon + 1,
  1002. cur_time->tm_mday, noSpace ? '_' : ' ', cur_time->tm_hour, cur_time->tm_min, cur_time->tm_sec,
  1003. extension);
  1004. return string(file);
  1005. }
  1006. string GenerateSpecifiedFilename(const char *extension, bool noSpace, const char *format)
  1007. {
  1008. BPtr<char> filename = os_generate_formatted_filename(extension, !noSpace, format);
  1009. return string(filename);
  1010. }
  1011. static void FindBestFilename(string &strPath, bool noSpace)
  1012. {
  1013. int num = 2;
  1014. if (!os_file_exists(strPath.c_str()))
  1015. return;
  1016. const char *ext = strrchr(strPath.c_str(), '.');
  1017. if (!ext)
  1018. return;
  1019. int extStart = int(ext - strPath.c_str());
  1020. for (;;) {
  1021. string testPath = strPath;
  1022. string numStr;
  1023. numStr = noSpace ? "_" : " (";
  1024. numStr += to_string(num++);
  1025. if (!noSpace)
  1026. numStr += ")";
  1027. testPath.insert(extStart, numStr);
  1028. if (!os_file_exists(testPath.c_str())) {
  1029. strPath = testPath;
  1030. break;
  1031. }
  1032. }
  1033. }
  1034. static void ensure_directory_exists(string &path)
  1035. {
  1036. replace(path.begin(), path.end(), '\\', '/');
  1037. size_t last = path.rfind('/');
  1038. if (last == string::npos)
  1039. return;
  1040. string directory = path.substr(0, last);
  1041. os_mkdirs(directory.c_str());
  1042. }
  1043. static void remove_reserved_file_characters(string &s)
  1044. {
  1045. replace(s.begin(), s.end(), '\\', '/');
  1046. replace(s.begin(), s.end(), '*', '_');
  1047. replace(s.begin(), s.end(), '?', '_');
  1048. replace(s.begin(), s.end(), '"', '_');
  1049. replace(s.begin(), s.end(), '|', '_');
  1050. replace(s.begin(), s.end(), ':', '_');
  1051. replace(s.begin(), s.end(), '>', '_');
  1052. replace(s.begin(), s.end(), '<', '_');
  1053. }
  1054. string GetFormatString(const char *format, const char *prefix, const char *suffix)
  1055. {
  1056. string f;
  1057. f = format;
  1058. if (prefix && *prefix) {
  1059. string str_prefix = prefix;
  1060. if (str_prefix.back() != ' ')
  1061. str_prefix += " ";
  1062. size_t insert_pos = 0;
  1063. size_t tmp;
  1064. tmp = f.find_last_of('/');
  1065. if (tmp != string::npos && tmp > insert_pos)
  1066. insert_pos = tmp + 1;
  1067. tmp = f.find_last_of('\\');
  1068. if (tmp != string::npos && tmp > insert_pos)
  1069. insert_pos = tmp + 1;
  1070. f.insert(insert_pos, str_prefix);
  1071. }
  1072. if (suffix && *suffix) {
  1073. if (*suffix != ' ')
  1074. f += " ";
  1075. f += suffix;
  1076. }
  1077. remove_reserved_file_characters(f);
  1078. return f;
  1079. }
  1080. string GetFormatExt(const char *container)
  1081. {
  1082. string ext = container;
  1083. if (ext == "fragmented_mp4")
  1084. ext = "mp4";
  1085. if (ext == "hybrid_mp4")
  1086. ext = "mp4";
  1087. else if (ext == "fragmented_mov")
  1088. ext = "mov";
  1089. else if (ext == "hls")
  1090. ext = "m3u8";
  1091. else if (ext == "mpegts")
  1092. ext = "ts";
  1093. return ext;
  1094. }
  1095. string GetOutputFilename(const char *path, const char *container, bool noSpace, bool overwrite, const char *format)
  1096. {
  1097. OBSBasic *main = OBSBasic::Get();
  1098. os_dir_t *dir = path && path[0] ? os_opendir(path) : nullptr;
  1099. if (!dir) {
  1100. if (main->isVisible())
  1101. OBSMessageBox::warning(main, QTStr("Output.BadPath.Title"), QTStr("Output.BadPath.Text"));
  1102. else
  1103. main->SysTrayNotify(QTStr("Output.BadPath.Text"), QSystemTrayIcon::Warning);
  1104. return "";
  1105. }
  1106. os_closedir(dir);
  1107. string strPath;
  1108. strPath += path;
  1109. char lastChar = strPath.back();
  1110. if (lastChar != '/' && lastChar != '\\')
  1111. strPath += "/";
  1112. string ext = GetFormatExt(container);
  1113. strPath += GenerateSpecifiedFilename(ext.c_str(), noSpace, format);
  1114. ensure_directory_exists(strPath);
  1115. if (!overwrite)
  1116. FindBestFilename(strPath, noSpace);
  1117. return strPath;
  1118. }
  1119. vector<pair<string, string>> GetLocaleNames()
  1120. {
  1121. string path;
  1122. if (!GetDataFilePath("locale.ini", path))
  1123. throw "Could not find locale.ini path";
  1124. ConfigFile ini;
  1125. if (ini.Open(path.c_str(), CONFIG_OPEN_EXISTING) != 0)
  1126. throw "Could not open locale.ini";
  1127. size_t sections = config_num_sections(ini);
  1128. vector<pair<string, string>> names;
  1129. names.reserve(sections);
  1130. for (size_t i = 0; i < sections; i++) {
  1131. const char *tag = config_get_section(ini, i);
  1132. const char *name = config_get_string(ini, tag, "Name");
  1133. names.emplace_back(tag, name);
  1134. }
  1135. return names;
  1136. }
  1137. #if defined(__APPLE__) || defined(__linux__)
  1138. #define BASE_PATH ".."
  1139. #else
  1140. #define BASE_PATH "../.."
  1141. #endif
  1142. #define CONFIG_PATH BASE_PATH "/config"
  1143. #if defined(ENABLE_PORTABLE_CONFIG) || defined(_WIN32)
  1144. #define ALLOW_PORTABLE_MODE 1
  1145. #else
  1146. #define ALLOW_PORTABLE_MODE 0
  1147. #endif
  1148. int GetAppConfigPath(char *path, size_t size, const char *name)
  1149. {
  1150. #if ALLOW_PORTABLE_MODE
  1151. if (portable_mode) {
  1152. if (name && *name) {
  1153. return snprintf(path, size, CONFIG_PATH "/%s", name);
  1154. } else {
  1155. return snprintf(path, size, CONFIG_PATH);
  1156. }
  1157. } else {
  1158. return os_get_config_path(path, size, name);
  1159. }
  1160. #else
  1161. return os_get_config_path(path, size, name);
  1162. #endif
  1163. }
  1164. char *GetAppConfigPathPtr(const char *name)
  1165. {
  1166. #if ALLOW_PORTABLE_MODE
  1167. if (portable_mode) {
  1168. char path[512];
  1169. if (snprintf(path, sizeof(path), CONFIG_PATH "/%s", name) > 0) {
  1170. return bstrdup(path);
  1171. } else {
  1172. return NULL;
  1173. }
  1174. } else {
  1175. return os_get_config_path_ptr(name);
  1176. }
  1177. #else
  1178. return os_get_config_path_ptr(name);
  1179. #endif
  1180. }
  1181. int GetProgramDataPath(char *path, size_t size, const char *name)
  1182. {
  1183. return os_get_program_data_path(path, size, name);
  1184. }
  1185. char *GetProgramDataPathPtr(const char *name)
  1186. {
  1187. return os_get_program_data_path_ptr(name);
  1188. }
  1189. bool GetFileSafeName(const char *name, std::string &file)
  1190. {
  1191. size_t base_len = strlen(name);
  1192. size_t len = os_utf8_to_wcs(name, base_len, nullptr, 0);
  1193. std::wstring wfile;
  1194. if (!len)
  1195. return false;
  1196. wfile.resize(len);
  1197. os_utf8_to_wcs(name, base_len, &wfile[0], len + 1);
  1198. for (size_t i = wfile.size(); i > 0; i--) {
  1199. size_t im1 = i - 1;
  1200. if (iswspace(wfile[im1])) {
  1201. wfile[im1] = '_';
  1202. } else if (wfile[im1] != '_' && !iswalnum(wfile[im1])) {
  1203. wfile.erase(im1, 1);
  1204. }
  1205. }
  1206. if (wfile.size() == 0)
  1207. wfile = L"characters_only";
  1208. len = os_wcs_to_utf8(wfile.c_str(), wfile.size(), nullptr, 0);
  1209. if (!len)
  1210. return false;
  1211. file.resize(len);
  1212. os_wcs_to_utf8(wfile.c_str(), wfile.size(), &file[0], len + 1);
  1213. return true;
  1214. }
  1215. bool GetClosestUnusedFileName(std::string &path, const char *extension)
  1216. {
  1217. size_t len = path.size();
  1218. if (extension) {
  1219. path += ".";
  1220. path += extension;
  1221. }
  1222. if (!os_file_exists(path.c_str()))
  1223. return true;
  1224. int index = 1;
  1225. do {
  1226. path.resize(len);
  1227. path += std::to_string(++index);
  1228. if (extension) {
  1229. path += ".";
  1230. path += extension;
  1231. }
  1232. } while (os_file_exists(path.c_str()));
  1233. return true;
  1234. }
  1235. bool WindowPositionValid(QRect rect)
  1236. {
  1237. for (QScreen *screen : QGuiApplication::screens()) {
  1238. if (screen->availableGeometry().intersects(rect))
  1239. return true;
  1240. }
  1241. return false;
  1242. }
  1243. #ifndef _WIN32
  1244. void OBSApp::SigIntSignalHandler(int s)
  1245. {
  1246. /* Handles SIGINT and writes to a socket. Qt will read
  1247. * from the socket in the main thread event loop and trigger
  1248. * a call to the ProcessSigInt slot, where we can safely run
  1249. * shutdown code without signal safety issues. */
  1250. UNUSED_PARAMETER(s);
  1251. char a = 1;
  1252. send(sigintFd[0], &a, sizeof(a), 0);
  1253. }
  1254. #endif
  1255. void OBSApp::ProcessSigInt(void)
  1256. {
  1257. /* This looks weird, but we can't ifdef a Qt slot function so
  1258. * the SIGINT handler simply does nothing on Windows. */
  1259. #ifndef _WIN32
  1260. char tmp;
  1261. recv(sigintFd[1], &tmp, sizeof(tmp), 0);
  1262. OBSBasic *main = OBSBasic::Get();
  1263. if (main)
  1264. main->close();
  1265. #endif
  1266. }
  1267. #ifdef _WIN32
  1268. void OBSApp::commitData(QSessionManager &manager)
  1269. {
  1270. if (auto main = App()->GetMainWindow()) {
  1271. QMetaObject::invokeMethod(main, "close", Qt::QueuedConnection);
  1272. manager.cancel();
  1273. }
  1274. }
  1275. #endif