OBSApp.cpp 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582
  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. #endif
  24. #include <qt-wrappers.hpp>
  25. #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER)
  26. #include <QFile>
  27. #endif
  28. #ifdef _WIN32
  29. #include <QSessionManager>
  30. #else
  31. #include <QSocketNotifier>
  32. #endif
  33. #if !defined(_WIN32) && !defined(__APPLE__)
  34. #include <qpa/qplatformnativeinterface.h>
  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 < 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. if (IsPortableMode()) {
  366. userConfigLocation =
  367. std::filesystem::u8path(config_get_default_string(appConfig, "Locations", "Configuration"));
  368. userScenesLocation =
  369. std::filesystem::u8path(config_get_default_string(appConfig, "Locations", "SceneCollections"));
  370. userProfilesLocation =
  371. std::filesystem::u8path(config_get_default_string(appConfig, "Locations", "Profiles"));
  372. } else {
  373. userConfigLocation =
  374. std::filesystem::u8path(config_get_string(appConfig, "Locations", "Configuration"));
  375. userScenesLocation =
  376. std::filesystem::u8path(config_get_string(appConfig, "Locations", "SceneCollections"));
  377. userProfilesLocation = std::filesystem::u8path(config_get_string(appConfig, "Locations", "Profiles"));
  378. }
  379. bool userConfigResult = InitUserConfig(userConfigLocation, lastVersion);
  380. return userConfigResult;
  381. }
  382. bool OBSApp::InitUserConfig(std::filesystem::path &userConfigLocation, uint32_t lastVersion)
  383. {
  384. const std::string userConfigFile = userConfigLocation.u8string() + "/obs-studio/user.ini";
  385. int errorCode = userConfig.Open(userConfigFile.c_str(), CONFIG_OPEN_ALWAYS);
  386. if (errorCode != CONFIG_SUCCESS) {
  387. OBSErrorBox(nullptr, "Failed to open user.ini: %d", errorCode);
  388. return false;
  389. }
  390. MigrateLegacySettings(lastVersion);
  391. InitUserConfigDefaults();
  392. return true;
  393. }
  394. void OBSApp::MigrateLegacySettings(const uint32_t lastVersion)
  395. {
  396. bool hasChanges = false;
  397. const uint32_t v19 = MAKE_SEMANTIC_VERSION(19, 0, 0);
  398. const uint32_t v21 = MAKE_SEMANTIC_VERSION(21, 0, 0);
  399. const uint32_t v23 = MAKE_SEMANTIC_VERSION(23, 0, 0);
  400. const uint32_t v24 = MAKE_SEMANTIC_VERSION(24, 0, 0);
  401. const uint32_t v24_1 = MAKE_SEMANTIC_VERSION(24, 1, 0);
  402. const map<uint32_t, string> defaultsMap{
  403. {{v19, "Pre19Defaults"}, {v21, "Pre21Defaults"}, {v23, "Pre23Defaults"}, {v24_1, "Pre24.1Defaults"}}};
  404. for (auto &[version, configKey] : defaultsMap) {
  405. if (!config_has_user_value(userConfig, "General", configKey.c_str())) {
  406. bool useOldDefaults = lastVersion && lastVersion < version;
  407. config_set_bool(userConfig, "General", configKey.c_str(), useOldDefaults);
  408. hasChanges = true;
  409. }
  410. }
  411. if (config_has_user_value(userConfig, "BasicWindow", "MultiviewLayout")) {
  412. const char *layout = config_get_string(userConfig, "BasicWindow", "MultiviewLayout");
  413. bool layoutUpdated = UpdatePre22MultiviewLayout(layout);
  414. hasChanges = hasChanges | layoutUpdated;
  415. }
  416. if (lastVersion && lastVersion < v24) {
  417. bool disableHotkeysInFocus = config_get_bool(userConfig, "General", "DisableHotkeysInFocus");
  418. if (disableHotkeysInFocus) {
  419. config_set_string(userConfig, "General", "HotkeyFocusType", "DisableHotkeysInFocus");
  420. }
  421. hasChanges = true;
  422. }
  423. if (hasChanges) {
  424. userConfig.SaveSafe("tmp");
  425. }
  426. }
  427. static constexpr string_view OBSGlobalIniPath = "/obs-studio/global.ini";
  428. static constexpr string_view OBSUserIniPath = "/obs-studio/user.ini";
  429. bool OBSApp::MigrateGlobalSettings()
  430. {
  431. char path[512];
  432. int len = GetAppConfigPath(path, sizeof(path), nullptr);
  433. if (len <= 0) {
  434. OBSErrorBox(nullptr, "Unable to get global configuration path.");
  435. return false;
  436. }
  437. std::string legacyConfigFileString;
  438. legacyConfigFileString.reserve(strlen(path) + OBSGlobalIniPath.size());
  439. legacyConfigFileString.append(path).append(OBSGlobalIniPath);
  440. const std::filesystem::path legacyGlobalConfigFile = std::filesystem::u8path(legacyConfigFileString);
  441. std::string configFileString;
  442. configFileString.reserve(strlen(path) + OBSUserIniPath.size());
  443. configFileString.append(path).append(OBSUserIniPath);
  444. const std::filesystem::path userConfigFile = std::filesystem::u8path(configFileString);
  445. if (std::filesystem::exists(userConfigFile)) {
  446. OBSErrorBox(nullptr,
  447. "Unable to migrate global configuration - user configuration file already exists.");
  448. return false;
  449. }
  450. try {
  451. std::filesystem::copy(legacyGlobalConfigFile, userConfigFile);
  452. } catch (const std::filesystem::filesystem_error &) {
  453. OBSErrorBox(nullptr, "Unable to migrate global configuration - copy failed.");
  454. return false;
  455. }
  456. return true;
  457. }
  458. bool OBSApp::InitLocale()
  459. {
  460. ProfileScope("OBSApp::InitLocale");
  461. const char *lang = config_get_string(userConfig, "General", "Language");
  462. bool userLocale = config_has_user_value(userConfig, "General", "Language");
  463. if (!userLocale || !lang || lang[0] == '\0')
  464. lang = DEFAULT_LANG;
  465. locale = lang;
  466. // set basic default application locale
  467. if (!locale.empty())
  468. QLocale::setDefault(QLocale(QString::fromStdString(locale).replace('-', '_')));
  469. string englishPath;
  470. if (!GetDataFilePath("locale/" DEFAULT_LANG ".ini", englishPath)) {
  471. OBSErrorBox(NULL, "Failed to find locale/" DEFAULT_LANG ".ini");
  472. return false;
  473. }
  474. textLookup = text_lookup_create(englishPath.c_str());
  475. if (!textLookup) {
  476. OBSErrorBox(NULL, "Failed to create locale from file '%s'", englishPath.c_str());
  477. return false;
  478. }
  479. bool defaultLang = astrcmpi(lang, DEFAULT_LANG) == 0;
  480. if (userLocale && defaultLang)
  481. return true;
  482. if (!userLocale && defaultLang) {
  483. for (auto &locale_ : GetPreferredLocales()) {
  484. if (locale_ == lang)
  485. return true;
  486. stringstream file;
  487. file << "locale/" << locale_ << ".ini";
  488. string path;
  489. if (!GetDataFilePath(file.str().c_str(), path))
  490. continue;
  491. if (!text_lookup_add(textLookup, path.c_str()))
  492. continue;
  493. blog(LOG_INFO, "Using preferred locale '%s'", locale_.c_str());
  494. locale = locale_;
  495. // set application default locale to the new choosen one
  496. if (!locale.empty())
  497. QLocale::setDefault(QLocale(QString::fromStdString(locale).replace('-', '_')));
  498. return true;
  499. }
  500. return true;
  501. }
  502. stringstream file;
  503. file << "locale/" << lang << ".ini";
  504. string path;
  505. if (GetDataFilePath(file.str().c_str(), path)) {
  506. if (!text_lookup_add(textLookup, path.c_str()))
  507. blog(LOG_ERROR, "Failed to add locale file '%s'", path.c_str());
  508. } else {
  509. blog(LOG_ERROR, "Could not find locale file '%s'", file.str().c_str());
  510. }
  511. return true;
  512. }
  513. #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER)
  514. void ParseBranchesJson(const std::string &jsonString, vector<UpdateBranch> &out, std::string &error)
  515. {
  516. JsonBranches branches;
  517. try {
  518. nlohmann::json json = nlohmann::json::parse(jsonString);
  519. branches = json.get<JsonBranches>();
  520. } catch (nlohmann::json::exception &e) {
  521. error = e.what();
  522. return;
  523. }
  524. for (const JsonBranch &json_branch : branches) {
  525. #ifdef _WIN32
  526. if (!json_branch.windows)
  527. continue;
  528. #elif defined(__APPLE__)
  529. if (!json_branch.macos)
  530. continue;
  531. #endif
  532. UpdateBranch branch = {
  533. QString::fromStdString(json_branch.name),
  534. QString::fromStdString(json_branch.display_name),
  535. QString::fromStdString(json_branch.description),
  536. json_branch.enabled,
  537. json_branch.visible,
  538. };
  539. out.push_back(branch);
  540. }
  541. }
  542. bool LoadBranchesFile(vector<UpdateBranch> &out)
  543. {
  544. string error;
  545. string branchesText;
  546. BPtr<char> branchesFilePath = GetAppConfigPathPtr("obs-studio/updates/branches.json");
  547. QFile branchesFile(branchesFilePath.Get());
  548. if (!branchesFile.open(QIODevice::ReadOnly)) {
  549. error = "Opening file failed.";
  550. goto fail;
  551. }
  552. branchesText = branchesFile.readAll();
  553. if (branchesText.empty()) {
  554. error = "File empty.";
  555. goto fail;
  556. }
  557. ParseBranchesJson(branchesText, out, error);
  558. if (error.empty())
  559. return !out.empty();
  560. fail:
  561. blog(LOG_WARNING, "Loading branches from file failed: %s", error.c_str());
  562. return false;
  563. }
  564. #endif
  565. void OBSApp::SetBranchData(const string &data)
  566. {
  567. #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER)
  568. string error;
  569. vector<UpdateBranch> result;
  570. ParseBranchesJson(data, result, error);
  571. if (!error.empty()) {
  572. blog(LOG_WARNING, "Reading branches JSON response failed: %s", error.c_str());
  573. return;
  574. }
  575. if (!result.empty())
  576. updateBranches = result;
  577. branches_loaded = true;
  578. #else
  579. UNUSED_PARAMETER(data);
  580. #endif
  581. }
  582. std::vector<UpdateBranch> OBSApp::GetBranches()
  583. {
  584. vector<UpdateBranch> out;
  585. /* Always ensure the default branch exists */
  586. out.push_back(UpdateBranch{"stable", "", "", true, true});
  587. #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER)
  588. if (!branches_loaded) {
  589. vector<UpdateBranch> result;
  590. if (LoadBranchesFile(result))
  591. updateBranches = result;
  592. branches_loaded = true;
  593. }
  594. #endif
  595. /* Copy additional branches to result (if any) */
  596. if (!updateBranches.empty())
  597. out.insert(out.end(), updateBranches.begin(), updateBranches.end());
  598. return out;
  599. }
  600. OBSApp::OBSApp(int &argc, char **argv, profiler_name_store_t *store)
  601. : QApplication(argc, argv),
  602. profilerNameStore(store)
  603. {
  604. /* fix float handling */
  605. #if defined(Q_OS_UNIX)
  606. if (!setlocale(LC_NUMERIC, "C"))
  607. blog(LOG_WARNING, "Failed to set LC_NUMERIC to C locale");
  608. #endif
  609. #ifndef _WIN32
  610. /* Handle SIGINT properly */
  611. socketpair(AF_UNIX, SOCK_STREAM, 0, sigintFd);
  612. snInt = new QSocketNotifier(sigintFd[1], QSocketNotifier::Read, this);
  613. connect(snInt, &QSocketNotifier::activated, this, &OBSApp::ProcessSigInt);
  614. #else
  615. connect(qApp, &QGuiApplication::commitDataRequest, this, &OBSApp::commitData);
  616. #endif
  617. sleepInhibitor = os_inhibit_sleep_create("OBS Video/audio");
  618. #ifndef __APPLE__
  619. setWindowIcon(QIcon::fromTheme("obs", QIcon(":/res/images/obs.png")));
  620. #endif
  621. setDesktopFileName("com.obsproject.Studio");
  622. }
  623. OBSApp::~OBSApp()
  624. {
  625. #ifdef _WIN32
  626. bool disableAudioDucking = config_get_bool(appConfig, "Audio", "DisableAudioDucking");
  627. if (disableAudioDucking)
  628. DisableAudioDucking(false);
  629. #else
  630. delete snInt;
  631. close(sigintFd[0]);
  632. close(sigintFd[1]);
  633. #endif
  634. #ifdef __APPLE__
  635. bool vsyncDisabled = config_get_bool(appConfig, "Video", "DisableOSXVSync");
  636. bool resetVSync = config_get_bool(appConfig, "Video", "ResetOSXVSyncOnExit");
  637. if (vsyncDisabled && resetVSync)
  638. EnableOSXVSync(true);
  639. #endif
  640. os_inhibit_sleep_set_active(sleepInhibitor, false);
  641. os_inhibit_sleep_destroy(sleepInhibitor);
  642. if (libobs_initialized)
  643. obs_shutdown();
  644. }
  645. static void move_basic_to_profiles(void)
  646. {
  647. char path[512];
  648. if (GetAppConfigPath(path, 512, "obs-studio/basic") <= 0) {
  649. return;
  650. }
  651. const std::filesystem::path basicPath = std::filesystem::u8path(path);
  652. if (!std::filesystem::exists(basicPath)) {
  653. return;
  654. }
  655. const std::filesystem::path profilesPath =
  656. App()->userProfilesLocation / std::filesystem::u8path("obs-studio/basic/profiles");
  657. if (std::filesystem::exists(profilesPath)) {
  658. return;
  659. }
  660. try {
  661. std::filesystem::create_directories(profilesPath);
  662. } catch (const std::filesystem::filesystem_error &error) {
  663. blog(LOG_ERROR, "Failed to create profiles directory for migration from basic profile\n%s",
  664. error.what());
  665. return;
  666. }
  667. const std::filesystem::path newProfilePath = profilesPath / std::filesystem::u8path(Str("Untitled"));
  668. for (auto &entry : std::filesystem::directory_iterator(basicPath)) {
  669. if (entry.is_directory()) {
  670. continue;
  671. }
  672. if (entry.path().filename().u8string() == "scenes.json") {
  673. continue;
  674. }
  675. if (!std::filesystem::exists(newProfilePath)) {
  676. try {
  677. std::filesystem::create_directory(newProfilePath);
  678. } catch (const std::filesystem::filesystem_error &error) {
  679. blog(LOG_ERROR, "Failed to create profile directory for 'Untitled'\n%s", error.what());
  680. return;
  681. }
  682. }
  683. const filesystem::path destinationFile = newProfilePath / entry.path().filename();
  684. const auto copyOptions = std::filesystem::copy_options::overwrite_existing;
  685. try {
  686. std::filesystem::copy(entry.path(), destinationFile, copyOptions);
  687. } catch (const std::filesystem::filesystem_error &error) {
  688. blog(LOG_ERROR, "Failed to copy basic profile file '%s' to new profile 'Untitled'\n%s",
  689. entry.path().filename().u8string().c_str(), error.what());
  690. return;
  691. }
  692. }
  693. }
  694. static void move_basic_to_scene_collections(void)
  695. {
  696. char path[512];
  697. if (GetAppConfigPath(path, 512, "obs-studio/basic") <= 0) {
  698. return;
  699. }
  700. const std::filesystem::path basicPath = std::filesystem::u8path(path);
  701. if (!std::filesystem::exists(basicPath)) {
  702. return;
  703. }
  704. const std::filesystem::path sceneCollectionPath =
  705. App()->userScenesLocation / std::filesystem::u8path("obs-studio/basic/scenes");
  706. if (std::filesystem::exists(sceneCollectionPath)) {
  707. return;
  708. }
  709. try {
  710. std::filesystem::create_directories(sceneCollectionPath);
  711. } catch (const std::filesystem::filesystem_error &error) {
  712. blog(LOG_ERROR,
  713. "Failed to create scene collection directory for migration from basic scene collection\n%s",
  714. error.what());
  715. return;
  716. }
  717. const std::filesystem::path sourceFile = basicPath / std::filesystem::u8path("scenes.json");
  718. const std::filesystem::path destinationFile =
  719. (sceneCollectionPath / std::filesystem::u8path(Str("Untitled"))).replace_extension(".json");
  720. try {
  721. std::filesystem::rename(sourceFile, destinationFile);
  722. } catch (const std::filesystem::filesystem_error &error) {
  723. blog(LOG_ERROR, "Failed to rename basic scene collection file:\n%s", error.what());
  724. return;
  725. }
  726. }
  727. void OBSApp::AppInit()
  728. {
  729. ProfileScope("OBSApp::AppInit");
  730. if (!MakeUserDirs())
  731. throw "Failed to create required user directories";
  732. if (!InitGlobalConfig())
  733. throw "Failed to initialize global config";
  734. if (!InitLocale())
  735. throw "Failed to load locale";
  736. if (!InitTheme())
  737. throw "Failed to load theme";
  738. config_set_default_string(userConfig, "Basic", "Profile", Str("Untitled"));
  739. config_set_default_string(userConfig, "Basic", "ProfileDir", Str("Untitled"));
  740. config_set_default_string(userConfig, "Basic", "SceneCollection", Str("Untitled"));
  741. config_set_default_string(userConfig, "Basic", "SceneCollectionFile", Str("Untitled"));
  742. config_set_default_bool(userConfig, "Basic", "ConfigOnNewProfile", true);
  743. const std::string_view profileName{config_get_string(userConfig, "Basic", "Profile")};
  744. if (profileName.empty()) {
  745. config_set_string(userConfig, "Basic", "Profile", Str("Untitled"));
  746. config_set_string(userConfig, "Basic", "ProfileDir", Str("Untitled"));
  747. }
  748. const std::string_view sceneCollectionName{config_get_string(userConfig, "Basic", "SceneCollection")};
  749. if (sceneCollectionName.empty()) {
  750. config_set_string(userConfig, "Basic", "SceneCollection", Str("Untitled"));
  751. config_set_string(userConfig, "Basic", "SceneCollectionFile", Str("Untitled"));
  752. }
  753. #ifdef _WIN32
  754. bool disableAudioDucking = config_get_bool(appConfig, "Audio", "DisableAudioDucking");
  755. if (disableAudioDucking)
  756. DisableAudioDucking(true);
  757. #endif
  758. #ifdef __APPLE__
  759. if (config_get_bool(appConfig, "Video", "DisableOSXVSync"))
  760. EnableOSXVSync(false);
  761. #endif
  762. UpdateHotkeyFocusSetting(false);
  763. move_basic_to_profiles();
  764. move_basic_to_scene_collections();
  765. if (!MakeUserProfileDirs())
  766. throw "Failed to create profile directories";
  767. }
  768. const char *OBSApp::GetRenderModule() const
  769. {
  770. const char *renderer = config_get_string(appConfig, "Video", "Renderer");
  771. return (astrcmpi(renderer, "Direct3D 11") == 0) ? DL_D3D11 : DL_OPENGL;
  772. }
  773. static bool StartupOBS(const char *locale, profiler_name_store_t *store)
  774. {
  775. char path[512];
  776. if (GetAppConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
  777. return false;
  778. return obs_startup(locale, path, store);
  779. }
  780. inline void OBSApp::ResetHotkeyState(bool inFocus)
  781. {
  782. obs_hotkey_enable_background_press((inFocus && enableHotkeysInFocus) || (!inFocus && enableHotkeysOutOfFocus));
  783. }
  784. void OBSApp::UpdateHotkeyFocusSetting(bool resetState)
  785. {
  786. enableHotkeysInFocus = true;
  787. enableHotkeysOutOfFocus = true;
  788. const char *hotkeyFocusType = config_get_string(userConfig, "General", "HotkeyFocusType");
  789. if (astrcmpi(hotkeyFocusType, "DisableHotkeysInFocus") == 0) {
  790. enableHotkeysInFocus = false;
  791. } else if (astrcmpi(hotkeyFocusType, "DisableHotkeysOutOfFocus") == 0) {
  792. enableHotkeysOutOfFocus = false;
  793. }
  794. if (resetState)
  795. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  796. }
  797. void OBSApp::DisableHotkeys()
  798. {
  799. enableHotkeysInFocus = false;
  800. enableHotkeysOutOfFocus = false;
  801. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  802. }
  803. void OBSApp::Exec(VoidFunc func)
  804. {
  805. func();
  806. }
  807. static void ui_task_handler(obs_task_t task, void *param, bool wait)
  808. {
  809. auto doTask = [=]() {
  810. /* to get clang-format to behave */
  811. task(param);
  812. };
  813. QMetaObject::invokeMethod(App(), "Exec", wait ? WaitConnection() : Qt::AutoConnection, Q_ARG(VoidFunc, doTask));
  814. }
  815. bool OBSApp::OBSInit()
  816. {
  817. ProfileScope("OBSApp::OBSInit");
  818. qRegisterMetaType<VoidFunc>("VoidFunc");
  819. #if !defined(_WIN32) && !defined(__APPLE__)
  820. if (QApplication::platformName() == "xcb") {
  821. obs_set_nix_platform(OBS_NIX_PLATFORM_X11_EGL);
  822. blog(LOG_INFO, "Using EGL/X11");
  823. }
  824. #ifdef ENABLE_WAYLAND
  825. if (QApplication::platformName().contains("wayland")) {
  826. obs_set_nix_platform(OBS_NIX_PLATFORM_WAYLAND);
  827. setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
  828. blog(LOG_INFO, "Platform: Wayland");
  829. }
  830. #endif
  831. QPlatformNativeInterface *native = QGuiApplication::platformNativeInterface();
  832. obs_set_nix_platform_display(native->nativeResourceForIntegration("display"));
  833. #endif
  834. #ifdef __APPLE__
  835. setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
  836. #endif
  837. if (!StartupOBS(locale.c_str(), GetProfilerNameStore()))
  838. return false;
  839. libobs_initialized = true;
  840. obs_set_ui_task_handler(ui_task_handler);
  841. #if defined(_WIN32) || defined(__APPLE__)
  842. bool browserHWAccel = config_get_bool(appConfig, "General", "BrowserHWAccel");
  843. OBSDataAutoRelease settings = obs_data_create();
  844. obs_data_set_bool(settings, "BrowserHWAccel", browserHWAccel);
  845. obs_apply_private_data(settings);
  846. blog(LOG_INFO, "Current Date/Time: %s", CurrentDateTimeString().c_str());
  847. blog(LOG_INFO, "Browser Hardware Acceleration: %s", browserHWAccel ? "true" : "false");
  848. #endif
  849. #ifdef _WIN32
  850. bool hideFromCapture = config_get_bool(userConfig, "BasicWindow", "HideOBSWindowsFromCapture");
  851. blog(LOG_INFO, "Hide OBS windows from screen capture: %s", hideFromCapture ? "true" : "false");
  852. #endif
  853. blog(LOG_INFO, "Qt Version: %s (runtime), %s (compiled)", qVersion(), QT_VERSION_STR);
  854. blog(LOG_INFO, "Portable mode: %s", portable_mode ? "true" : "false");
  855. if (safe_mode) {
  856. blog(LOG_WARNING, "Safe Mode enabled.");
  857. } else if (disable_3p_plugins) {
  858. blog(LOG_WARNING, "Third-party plugins disabled.");
  859. }
  860. setQuitOnLastWindowClosed(false);
  861. mainWindow = new OBSBasic();
  862. mainWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  863. connect(mainWindow, &OBSBasic::destroyed, this, &OBSApp::quit);
  864. mainWindow->OBSInit();
  865. connect(this, &QGuiApplication::applicationStateChanged,
  866. [this](Qt::ApplicationState state) { ResetHotkeyState(state == Qt::ApplicationActive); });
  867. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  868. return true;
  869. }
  870. string OBSApp::GetVersionString(bool platform) const
  871. {
  872. stringstream ver;
  873. #ifdef HAVE_OBSCONFIG_H
  874. ver << obs_get_version_string();
  875. #else
  876. ver << LIBOBS_API_MAJOR_VER << "." << LIBOBS_API_MINOR_VER << "." << LIBOBS_API_PATCH_VER;
  877. #endif
  878. if (platform) {
  879. ver << " (";
  880. #ifdef _WIN32
  881. if (sizeof(void *) == 8)
  882. ver << "64-bit, ";
  883. else
  884. ver << "32-bit, ";
  885. ver << "windows)";
  886. #elif __APPLE__
  887. ver << "mac)";
  888. #elif __OpenBSD__
  889. ver << "openbsd)";
  890. #elif __FreeBSD__
  891. ver << "freebsd)";
  892. #else /* assume linux for the time being */
  893. ver << "linux)";
  894. #endif
  895. }
  896. return ver.str();
  897. }
  898. bool OBSApp::IsPortableMode()
  899. {
  900. return portable_mode;
  901. }
  902. bool OBSApp::IsUpdaterDisabled()
  903. {
  904. return opt_disable_updater;
  905. }
  906. bool OBSApp::IsMissingFilesCheckDisabled()
  907. {
  908. return opt_disable_missing_files_check;
  909. }
  910. #ifdef __APPLE__
  911. #define INPUT_AUDIO_SOURCE "coreaudio_input_capture"
  912. #define OUTPUT_AUDIO_SOURCE "coreaudio_output_capture"
  913. #elif _WIN32
  914. #define INPUT_AUDIO_SOURCE "wasapi_input_capture"
  915. #define OUTPUT_AUDIO_SOURCE "wasapi_output_capture"
  916. #else
  917. #define INPUT_AUDIO_SOURCE "pulse_input_capture"
  918. #define OUTPUT_AUDIO_SOURCE "pulse_output_capture"
  919. #endif
  920. const char *OBSApp::InputAudioSource() const
  921. {
  922. return INPUT_AUDIO_SOURCE;
  923. }
  924. const char *OBSApp::OutputAudioSource() const
  925. {
  926. return OUTPUT_AUDIO_SOURCE;
  927. }
  928. const char *OBSApp::GetLastLog() const
  929. {
  930. return lastLogFile.c_str();
  931. }
  932. const char *OBSApp::GetCurrentLog() const
  933. {
  934. return currentLogFile.c_str();
  935. }
  936. const char *OBSApp::GetLastCrashLog() const
  937. {
  938. return lastCrashLogFile.c_str();
  939. }
  940. bool OBSApp::TranslateString(const char *lookupVal, const char **out) const
  941. {
  942. for (obs_frontend_translate_ui_cb cb : translatorHooks) {
  943. if (cb(lookupVal, out))
  944. return true;
  945. }
  946. return text_lookup_getstr(App()->GetTextLookup(), lookupVal, out);
  947. }
  948. // Global handler to receive all QEvent::Show events so we can apply
  949. // display affinity on any newly created windows and dialogs without
  950. // caring where they are coming from (e.g. plugins).
  951. bool OBSApp::notify(QObject *receiver, QEvent *e)
  952. {
  953. QWidget *w;
  954. QWindow *window;
  955. int windowType;
  956. if (!receiver->isWidgetType())
  957. goto skip;
  958. if (e->type() != QEvent::Show)
  959. goto skip;
  960. w = qobject_cast<QWidget *>(receiver);
  961. if (!w->isWindow())
  962. goto skip;
  963. window = w->windowHandle();
  964. if (!window)
  965. goto skip;
  966. windowType = window->flags() & Qt::WindowType::WindowType_Mask;
  967. if (windowType == Qt::WindowType::Dialog || windowType == Qt::WindowType::Window ||
  968. windowType == Qt::WindowType::Tool) {
  969. OBSBasic *main = OBSBasic::Get();
  970. if (main)
  971. main->SetDisplayAffinity(window);
  972. }
  973. skip:
  974. return QApplication::notify(receiver, e);
  975. }
  976. string GenerateTimeDateFilename(const char *extension, bool noSpace)
  977. {
  978. time_t now = time(0);
  979. char file[256] = {};
  980. struct tm *cur_time;
  981. cur_time = localtime(&now);
  982. snprintf(file, sizeof(file), "%d-%02d-%02d%c%02d-%02d-%02d.%s", cur_time->tm_year + 1900, cur_time->tm_mon + 1,
  983. cur_time->tm_mday, noSpace ? '_' : ' ', cur_time->tm_hour, cur_time->tm_min, cur_time->tm_sec,
  984. extension);
  985. return string(file);
  986. }
  987. string GenerateSpecifiedFilename(const char *extension, bool noSpace, const char *format)
  988. {
  989. BPtr<char> filename = os_generate_formatted_filename(extension, !noSpace, format);
  990. return string(filename);
  991. }
  992. static void FindBestFilename(string &strPath, bool noSpace)
  993. {
  994. int num = 2;
  995. if (!os_file_exists(strPath.c_str()))
  996. return;
  997. const char *ext = strrchr(strPath.c_str(), '.');
  998. if (!ext)
  999. return;
  1000. int extStart = int(ext - strPath.c_str());
  1001. for (;;) {
  1002. string testPath = strPath;
  1003. string numStr;
  1004. numStr = noSpace ? "_" : " (";
  1005. numStr += to_string(num++);
  1006. if (!noSpace)
  1007. numStr += ")";
  1008. testPath.insert(extStart, numStr);
  1009. if (!os_file_exists(testPath.c_str())) {
  1010. strPath = testPath;
  1011. break;
  1012. }
  1013. }
  1014. }
  1015. static void ensure_directory_exists(string &path)
  1016. {
  1017. replace(path.begin(), path.end(), '\\', '/');
  1018. size_t last = path.rfind('/');
  1019. if (last == string::npos)
  1020. return;
  1021. string directory = path.substr(0, last);
  1022. os_mkdirs(directory.c_str());
  1023. }
  1024. static void remove_reserved_file_characters(string &s)
  1025. {
  1026. replace(s.begin(), s.end(), '\\', '/');
  1027. replace(s.begin(), s.end(), '*', '_');
  1028. replace(s.begin(), s.end(), '?', '_');
  1029. replace(s.begin(), s.end(), '"', '_');
  1030. replace(s.begin(), s.end(), '|', '_');
  1031. replace(s.begin(), s.end(), ':', '_');
  1032. replace(s.begin(), s.end(), '>', '_');
  1033. replace(s.begin(), s.end(), '<', '_');
  1034. }
  1035. string GetFormatString(const char *format, const char *prefix, const char *suffix)
  1036. {
  1037. string f;
  1038. f = format;
  1039. if (prefix && *prefix) {
  1040. string str_prefix = prefix;
  1041. if (str_prefix.back() != ' ')
  1042. str_prefix += " ";
  1043. size_t insert_pos = 0;
  1044. size_t tmp;
  1045. tmp = f.find_last_of('/');
  1046. if (tmp != string::npos && tmp > insert_pos)
  1047. insert_pos = tmp + 1;
  1048. tmp = f.find_last_of('\\');
  1049. if (tmp != string::npos && tmp > insert_pos)
  1050. insert_pos = tmp + 1;
  1051. f.insert(insert_pos, str_prefix);
  1052. }
  1053. if (suffix && *suffix) {
  1054. if (*suffix != ' ')
  1055. f += " ";
  1056. f += suffix;
  1057. }
  1058. remove_reserved_file_characters(f);
  1059. return f;
  1060. }
  1061. string GetFormatExt(const char *container)
  1062. {
  1063. string ext = container;
  1064. if (ext == "fragmented_mp4")
  1065. ext = "mp4";
  1066. if (ext == "hybrid_mp4")
  1067. ext = "mp4";
  1068. else if (ext == "fragmented_mov")
  1069. ext = "mov";
  1070. else if (ext == "hls")
  1071. ext = "m3u8";
  1072. else if (ext == "mpegts")
  1073. ext = "ts";
  1074. return ext;
  1075. }
  1076. string GetOutputFilename(const char *path, const char *container, bool noSpace, bool overwrite, const char *format)
  1077. {
  1078. OBSBasic *main = OBSBasic::Get();
  1079. os_dir_t *dir = path && path[0] ? os_opendir(path) : nullptr;
  1080. if (!dir) {
  1081. if (main->isVisible())
  1082. OBSMessageBox::warning(main, QTStr("Output.BadPath.Title"), QTStr("Output.BadPath.Text"));
  1083. else
  1084. main->SysTrayNotify(QTStr("Output.BadPath.Text"), QSystemTrayIcon::Warning);
  1085. return "";
  1086. }
  1087. os_closedir(dir);
  1088. string strPath;
  1089. strPath += path;
  1090. char lastChar = strPath.back();
  1091. if (lastChar != '/' && lastChar != '\\')
  1092. strPath += "/";
  1093. string ext = GetFormatExt(container);
  1094. strPath += GenerateSpecifiedFilename(ext.c_str(), noSpace, format);
  1095. ensure_directory_exists(strPath);
  1096. if (!overwrite)
  1097. FindBestFilename(strPath, noSpace);
  1098. return strPath;
  1099. }
  1100. vector<pair<string, string>> GetLocaleNames()
  1101. {
  1102. string path;
  1103. if (!GetDataFilePath("locale.ini", path))
  1104. throw "Could not find locale.ini path";
  1105. ConfigFile ini;
  1106. if (ini.Open(path.c_str(), CONFIG_OPEN_EXISTING) != 0)
  1107. throw "Could not open locale.ini";
  1108. size_t sections = config_num_sections(ini);
  1109. vector<pair<string, string>> names;
  1110. names.reserve(sections);
  1111. for (size_t i = 0; i < sections; i++) {
  1112. const char *tag = config_get_section(ini, i);
  1113. const char *name = config_get_string(ini, tag, "Name");
  1114. names.emplace_back(tag, name);
  1115. }
  1116. return names;
  1117. }
  1118. #if defined(__APPLE__) || defined(__linux__)
  1119. #define BASE_PATH ".."
  1120. #else
  1121. #define BASE_PATH "../.."
  1122. #endif
  1123. #define CONFIG_PATH BASE_PATH "/config"
  1124. #if defined(ENABLE_PORTABLE_CONFIG) || defined(_WIN32)
  1125. #define ALLOW_PORTABLE_MODE 1
  1126. #else
  1127. #define ALLOW_PORTABLE_MODE 0
  1128. #endif
  1129. int GetAppConfigPath(char *path, size_t size, const char *name)
  1130. {
  1131. #if ALLOW_PORTABLE_MODE
  1132. if (portable_mode) {
  1133. if (name && *name) {
  1134. return snprintf(path, size, CONFIG_PATH "/%s", name);
  1135. } else {
  1136. return snprintf(path, size, CONFIG_PATH);
  1137. }
  1138. } else {
  1139. return os_get_config_path(path, size, name);
  1140. }
  1141. #else
  1142. return os_get_config_path(path, size, name);
  1143. #endif
  1144. }
  1145. char *GetAppConfigPathPtr(const char *name)
  1146. {
  1147. #if ALLOW_PORTABLE_MODE
  1148. if (portable_mode) {
  1149. char path[512];
  1150. if (snprintf(path, sizeof(path), CONFIG_PATH "/%s", name) > 0) {
  1151. return bstrdup(path);
  1152. } else {
  1153. return NULL;
  1154. }
  1155. } else {
  1156. return os_get_config_path_ptr(name);
  1157. }
  1158. #else
  1159. return os_get_config_path_ptr(name);
  1160. #endif
  1161. }
  1162. int GetProgramDataPath(char *path, size_t size, const char *name)
  1163. {
  1164. return os_get_program_data_path(path, size, name);
  1165. }
  1166. char *GetProgramDataPathPtr(const char *name)
  1167. {
  1168. return os_get_program_data_path_ptr(name);
  1169. }
  1170. bool GetFileSafeName(const char *name, std::string &file)
  1171. {
  1172. size_t base_len = strlen(name);
  1173. size_t len = os_utf8_to_wcs(name, base_len, nullptr, 0);
  1174. std::wstring wfile;
  1175. if (!len)
  1176. return false;
  1177. wfile.resize(len);
  1178. os_utf8_to_wcs(name, base_len, &wfile[0], len + 1);
  1179. for (size_t i = wfile.size(); i > 0; i--) {
  1180. size_t im1 = i - 1;
  1181. if (iswspace(wfile[im1])) {
  1182. wfile[im1] = '_';
  1183. } else if (wfile[im1] != '_' && !iswalnum(wfile[im1])) {
  1184. wfile.erase(im1, 1);
  1185. }
  1186. }
  1187. if (wfile.size() == 0)
  1188. wfile = L"characters_only";
  1189. len = os_wcs_to_utf8(wfile.c_str(), wfile.size(), nullptr, 0);
  1190. if (!len)
  1191. return false;
  1192. file.resize(len);
  1193. os_wcs_to_utf8(wfile.c_str(), wfile.size(), &file[0], len + 1);
  1194. return true;
  1195. }
  1196. bool GetClosestUnusedFileName(std::string &path, const char *extension)
  1197. {
  1198. size_t len = path.size();
  1199. if (extension) {
  1200. path += ".";
  1201. path += extension;
  1202. }
  1203. if (!os_file_exists(path.c_str()))
  1204. return true;
  1205. int index = 1;
  1206. do {
  1207. path.resize(len);
  1208. path += std::to_string(++index);
  1209. if (extension) {
  1210. path += ".";
  1211. path += extension;
  1212. }
  1213. } while (os_file_exists(path.c_str()));
  1214. return true;
  1215. }
  1216. bool WindowPositionValid(QRect rect)
  1217. {
  1218. for (QScreen *screen : QGuiApplication::screens()) {
  1219. if (screen->availableGeometry().intersects(rect))
  1220. return true;
  1221. }
  1222. return false;
  1223. }
  1224. #ifndef _WIN32
  1225. void OBSApp::SigIntSignalHandler(int s)
  1226. {
  1227. /* Handles SIGINT and writes to a socket. Qt will read
  1228. * from the socket in the main thread event loop and trigger
  1229. * a call to the ProcessSigInt slot, where we can safely run
  1230. * shutdown code without signal safety issues. */
  1231. UNUSED_PARAMETER(s);
  1232. char a = 1;
  1233. send(sigintFd[0], &a, sizeof(a), 0);
  1234. }
  1235. #endif
  1236. void OBSApp::ProcessSigInt(void)
  1237. {
  1238. /* This looks weird, but we can't ifdef a Qt slot function so
  1239. * the SIGINT handler simply does nothing on Windows. */
  1240. #ifndef _WIN32
  1241. char tmp;
  1242. recv(sigintFd[1], &tmp, sizeof(tmp), 0);
  1243. OBSBasic *main = OBSBasic::Get();
  1244. if (main)
  1245. main->close();
  1246. #endif
  1247. }
  1248. #ifdef _WIN32
  1249. void OBSApp::commitData(QSessionManager &manager)
  1250. {
  1251. if (auto main = App()->GetMainWindow()) {
  1252. QMetaObject::invokeMethod(main, "close", Qt::QueuedConnection);
  1253. manager.cancel();
  1254. }
  1255. }
  1256. #endif