OBSApp.cpp 46 KB

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