OBSApp.cpp 41 KB

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