OBSApp.cpp 49 KB

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