OBSApp.cpp 53 KB

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