OBSApp.cpp 48 KB

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