OBSApp.cpp 41 KB

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