1
0

OBSApp.cpp 42 KB

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