OBSApp.cpp 47 KB

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