OBSApp.cpp 42 KB

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