obs-app.cpp 23 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066
  1. /******************************************************************************
  2. Copyright (C) 2013 by Hugh 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 <time.h>
  15. #include <stdio.h>
  16. #include <wchar.h>
  17. #include <sstream>
  18. #include <util/bmem.h>
  19. #include <util/dstr.h>
  20. #include <util/platform.h>
  21. #include <obs-config.h>
  22. #include <obs.hpp>
  23. #include <QProxyStyle>
  24. #include "qt-wrappers.hpp"
  25. #include "obs-app.hpp"
  26. #include "window-basic-main.hpp"
  27. #include "window-basic-settings.hpp"
  28. #include "window-license-agreement.hpp"
  29. #include "crash-report.hpp"
  30. #include "platform.hpp"
  31. #include <fstream>
  32. #ifdef _WIN32
  33. #include <windows.h>
  34. #else
  35. #include <signal.h>
  36. #endif
  37. using namespace std;
  38. static log_handler_t def_log_handler;
  39. static string currentLogFile;
  40. static string lastLogFile;
  41. static bool portable_mode = false;
  42. QObject *CreateShortcutFilter()
  43. {
  44. return new OBSEventFilter([](QObject *obj, QEvent *event)
  45. {
  46. auto mouse_event = [](QMouseEvent &event)
  47. {
  48. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  49. bool pressed = event.type() == QEvent::MouseButtonPress;
  50. switch (event.button()) {
  51. case Qt::NoButton:
  52. case Qt::LeftButton:
  53. case Qt::RightButton:
  54. case Qt::AllButtons:
  55. case Qt::MouseButtonMask:
  56. return false;
  57. case Qt::MidButton:
  58. hotkey.key = OBS_KEY_MOUSE3;
  59. break;
  60. #define MAP_BUTTON(i, j) case Qt::ExtraButton ## i: \
  61. hotkey.key = OBS_KEY_MOUSE ## j; break;
  62. MAP_BUTTON( 1, 4);
  63. MAP_BUTTON( 2, 5);
  64. MAP_BUTTON( 3, 6);
  65. MAP_BUTTON( 4, 7);
  66. MAP_BUTTON( 5, 8);
  67. MAP_BUTTON( 6, 9);
  68. MAP_BUTTON( 7, 10);
  69. MAP_BUTTON( 8, 11);
  70. MAP_BUTTON( 9, 12);
  71. MAP_BUTTON(10, 13);
  72. MAP_BUTTON(11, 14);
  73. MAP_BUTTON(12, 15);
  74. MAP_BUTTON(13, 16);
  75. MAP_BUTTON(14, 17);
  76. MAP_BUTTON(15, 18);
  77. MAP_BUTTON(16, 19);
  78. MAP_BUTTON(17, 20);
  79. MAP_BUTTON(18, 21);
  80. MAP_BUTTON(19, 22);
  81. MAP_BUTTON(20, 23);
  82. MAP_BUTTON(21, 24);
  83. MAP_BUTTON(22, 25);
  84. MAP_BUTTON(23, 26);
  85. MAP_BUTTON(24, 27);
  86. #undef MAP_BUTTON
  87. }
  88. hotkey.modifiers = TranslateQtKeyboardEventModifiers(
  89. event.modifiers());
  90. obs_hotkey_inject_event(hotkey, pressed);
  91. return true;
  92. };
  93. auto key_event = [&](QKeyEvent *event)
  94. {
  95. QDialog *dialog = qobject_cast<QDialog*>(obj);
  96. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  97. bool pressed = event->type() == QEvent::KeyPress;
  98. switch (event->key()) {
  99. case Qt::Key_Shift:
  100. case Qt::Key_Control:
  101. case Qt::Key_Alt:
  102. case Qt::Key_Meta:
  103. break;
  104. #ifdef __APPLE__
  105. case Qt::Key_CapsLock:
  106. // kVK_CapsLock == 57
  107. hotkey.key = obs_key_from_virtual_key(57);
  108. pressed = true;
  109. break;
  110. #endif
  111. case Qt::Key_Enter:
  112. case Qt::Key_Escape:
  113. case Qt::Key_Return:
  114. if (dialog && pressed)
  115. return false;
  116. default:
  117. hotkey.key = obs_key_from_virtual_key(
  118. event->nativeVirtualKey());
  119. }
  120. hotkey.modifiers = TranslateQtKeyboardEventModifiers(
  121. event->modifiers());
  122. obs_hotkey_inject_event(hotkey, pressed);
  123. return true;
  124. };
  125. switch (event->type()) {
  126. case QEvent::MouseButtonPress:
  127. case QEvent::MouseButtonRelease:
  128. return mouse_event(*static_cast<QMouseEvent*>(event));
  129. /*case QEvent::MouseButtonDblClick:
  130. case QEvent::Wheel:*/
  131. case QEvent::KeyPress:
  132. case QEvent::KeyRelease:
  133. return key_event(static_cast<QKeyEvent*>(event));
  134. default:
  135. return false;
  136. }
  137. });
  138. }
  139. string CurrentTimeString()
  140. {
  141. time_t now = time(0);
  142. struct tm tstruct;
  143. char buf[80];
  144. tstruct = *localtime(&now);
  145. strftime(buf, sizeof(buf), "%X", &tstruct);
  146. return buf;
  147. }
  148. string CurrentDateTimeString()
  149. {
  150. time_t now = time(0);
  151. struct tm tstruct;
  152. char buf[80];
  153. tstruct = *localtime(&now);
  154. strftime(buf, sizeof(buf), "%Y-%m-%d, %X", &tstruct);
  155. return buf;
  156. }
  157. static void do_log(int log_level, const char *msg, va_list args, void *param)
  158. {
  159. fstream &logFile = *static_cast<fstream*>(param);
  160. char str[4096];
  161. #ifndef _WIN32
  162. va_list args2;
  163. va_copy(args2, args);
  164. #endif
  165. vsnprintf(str, 4095, msg, args);
  166. #ifdef _WIN32
  167. OutputDebugStringA(str);
  168. OutputDebugStringA("\n");
  169. #else
  170. def_log_handler(log_level, msg, args2, nullptr);
  171. #endif
  172. if (log_level <= LOG_INFO)
  173. logFile << CurrentTimeString() << ": " << str << endl;
  174. #ifdef _WIN32
  175. if (log_level <= LOG_ERROR && IsDebuggerPresent())
  176. __debugbreak();
  177. #endif
  178. }
  179. #define DEFAULT_LANG "en-US"
  180. bool OBSApp::InitGlobalConfigDefaults()
  181. {
  182. config_set_default_string(globalConfig, "General", "Language",
  183. DEFAULT_LANG);
  184. config_set_default_uint(globalConfig, "General", "MaxLogs", 10);
  185. #if _WIN32
  186. config_set_default_string(globalConfig, "Video", "Renderer",
  187. "Direct3D 11");
  188. #else
  189. config_set_default_string(globalConfig, "Video", "Renderer", "OpenGL");
  190. #endif
  191. config_set_default_bool(globalConfig, "BasicWindow", "PreviewEnabled",
  192. true);
  193. return true;
  194. }
  195. static bool do_mkdir(const char *path)
  196. {
  197. if (os_mkdir(path) == MKDIR_ERROR) {
  198. OBSErrorBox(NULL, "Failed to create directory %s", path);
  199. return false;
  200. }
  201. return true;
  202. }
  203. static bool MakeUserDirs()
  204. {
  205. char path[512];
  206. if (portable_mode) {
  207. if (GetConfigPath(path, sizeof(path), "") <= 0)
  208. return false;
  209. if (!do_mkdir(path))
  210. return false;
  211. }
  212. if (GetConfigPath(path, sizeof(path), "obs-studio") <= 0)
  213. return false;
  214. if (!do_mkdir(path))
  215. return false;
  216. if (GetConfigPath(path, sizeof(path), "obs-studio/basic") <= 0)
  217. return false;
  218. if (!do_mkdir(path))
  219. return false;
  220. if (GetConfigPath(path, sizeof(path), "obs-studio/logs") <= 0)
  221. return false;
  222. if (!do_mkdir(path))
  223. return false;
  224. #ifdef _WIN32
  225. if (GetConfigPath(path, sizeof(path), "obs-studio/crashes") <= 0)
  226. return false;
  227. if (!do_mkdir(path))
  228. return false;
  229. #endif
  230. return true;
  231. }
  232. static bool MakeUserProfileDirs()
  233. {
  234. char path[512];
  235. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/profiles") <= 0)
  236. return false;
  237. if (!do_mkdir(path))
  238. return false;
  239. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/scenes") <= 0)
  240. return false;
  241. if (!do_mkdir(path))
  242. return false;
  243. return true;
  244. }
  245. bool OBSApp::InitGlobalConfig()
  246. {
  247. char path[512];
  248. int len = GetConfigPath(path, sizeof(path),
  249. "obs-studio/global.ini");
  250. if (len <= 0) {
  251. return false;
  252. }
  253. int errorcode = globalConfig.Open(path, CONFIG_OPEN_ALWAYS);
  254. if (errorcode != CONFIG_SUCCESS) {
  255. OBSErrorBox(NULL, "Failed to open global.ini: %d", errorcode);
  256. return false;
  257. }
  258. return InitGlobalConfigDefaults();
  259. }
  260. bool OBSApp::InitLocale()
  261. {
  262. const char *lang = config_get_string(globalConfig, "General",
  263. "Language");
  264. locale = lang;
  265. string englishPath;
  266. if (!GetDataFilePath("locale/" DEFAULT_LANG ".ini", englishPath)) {
  267. OBSErrorBox(NULL, "Failed to find locale/" DEFAULT_LANG ".ini");
  268. return false;
  269. }
  270. textLookup = text_lookup_create(englishPath.c_str());
  271. if (!textLookup) {
  272. OBSErrorBox(NULL, "Failed to create locale from file '%s'",
  273. englishPath.c_str());
  274. return false;
  275. }
  276. bool userLocale = config_has_user_value(globalConfig, "General",
  277. "Language");
  278. bool defaultLang = astrcmpi(lang, DEFAULT_LANG) == 0;
  279. if (userLocale && defaultLang)
  280. return true;
  281. if (!userLocale && defaultLang) {
  282. for (auto &locale_ : GetPreferredLocales()) {
  283. if (locale_ == lang)
  284. return true;
  285. stringstream file;
  286. file << "locale/" << locale_ << ".ini";
  287. string path;
  288. if (!GetDataFilePath(file.str().c_str(), path))
  289. continue;
  290. if (!text_lookup_add(textLookup, path.c_str()))
  291. continue;
  292. blog(LOG_INFO, "Using preferred locale '%s'",
  293. locale_.c_str());
  294. locale = locale_;
  295. return true;
  296. }
  297. return true;
  298. }
  299. stringstream file;
  300. file << "locale/" << lang << ".ini";
  301. string path;
  302. if (GetDataFilePath(file.str().c_str(), path)) {
  303. if (!text_lookup_add(textLookup, path.c_str()))
  304. blog(LOG_ERROR, "Failed to add locale file '%s'",
  305. path.c_str());
  306. } else {
  307. blog(LOG_ERROR, "Could not find locale file '%s'",
  308. file.str().c_str());
  309. }
  310. return true;
  311. }
  312. bool OBSApp::SetTheme(std::string name, std::string path)
  313. {
  314. theme = name;
  315. /* Check user dir first, then preinstalled themes. */
  316. if (path == "") {
  317. char userDir[512];
  318. name = "themes/" + name + ".qss";
  319. string temp = "obs-studio/" + name;
  320. int ret = GetConfigPath(userDir, sizeof(userDir),
  321. temp.c_str());
  322. if (ret > 0 && QFile::exists(userDir)) {
  323. path = string(userDir);
  324. } else if (!GetDataFilePath(name.c_str(), path)) {
  325. OBSErrorBox(NULL, "Failed to find %s.", name.c_str());
  326. return false;
  327. }
  328. }
  329. QString mpath = QString("file:///") + path.c_str();
  330. setStyleSheet(mpath);
  331. return true;
  332. }
  333. bool OBSApp::InitTheme()
  334. {
  335. const char *themeName = config_get_string(globalConfig, "General",
  336. "Theme");
  337. if (!themeName)
  338. themeName = "Default";
  339. stringstream t;
  340. t << themeName;
  341. return SetTheme(t.str());
  342. }
  343. OBSApp::OBSApp(int &argc, char **argv)
  344. : QApplication(argc, argv)
  345. {}
  346. static void move_basic_to_profiles(void)
  347. {
  348. char path[512];
  349. char new_path[512];
  350. os_glob_t *glob;
  351. /* if not first time use */
  352. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  353. return;
  354. if (!os_file_exists(path))
  355. return;
  356. /* if the profiles directory doesn't already exist */
  357. if (GetConfigPath(new_path, 512, "obs-studio/basic/profiles") <= 0)
  358. return;
  359. if (os_file_exists(new_path))
  360. return;
  361. if (os_mkdir(new_path) == MKDIR_ERROR)
  362. return;
  363. strcat(new_path, "/");
  364. strcat(new_path, Str("Untitled"));
  365. if (os_mkdir(new_path) == MKDIR_ERROR)
  366. return;
  367. strcat(path, "/*.*");
  368. if (os_glob(path, 0, &glob) != 0)
  369. return;
  370. strcpy(path, new_path);
  371. for (size_t i = 0; i < glob->gl_pathc; i++) {
  372. struct os_globent ent = glob->gl_pathv[i];
  373. char *file;
  374. if (ent.directory)
  375. continue;
  376. file = strrchr(ent.path, '/');
  377. if (!file++)
  378. continue;
  379. if (astrcmpi(file, "scenes.json") == 0)
  380. continue;
  381. strcpy(new_path, path);
  382. strcat(new_path, "/");
  383. strcat(new_path, file);
  384. os_rename(ent.path, new_path);
  385. }
  386. os_globfree(glob);
  387. }
  388. static void move_basic_to_scene_collections(void)
  389. {
  390. char path[512];
  391. char new_path[512];
  392. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  393. return;
  394. if (!os_file_exists(path))
  395. return;
  396. if (GetConfigPath(new_path, 512, "obs-studio/basic/scenes") <= 0)
  397. return;
  398. if (os_file_exists(new_path))
  399. return;
  400. if (os_mkdir(new_path) == MKDIR_ERROR)
  401. return;
  402. strcat(path, "/scenes.json");
  403. strcat(new_path, "/");
  404. strcat(new_path, Str("Untitled"));
  405. strcat(new_path, ".json");
  406. os_rename(path, new_path);
  407. }
  408. void OBSApp::AppInit()
  409. {
  410. if (!InitApplicationBundle())
  411. throw "Failed to initialize application bundle";
  412. if (!MakeUserDirs())
  413. throw "Failed to create required user directories";
  414. if (!InitGlobalConfig())
  415. throw "Failed to initialize global config";
  416. if (!InitLocale())
  417. throw "Failed to load locale";
  418. if (!InitTheme())
  419. throw "Failed to load theme";
  420. config_set_default_string(globalConfig, "Basic", "Profile",
  421. Str("Untitled"));
  422. config_set_default_string(globalConfig, "Basic", "ProfileDir",
  423. Str("Untitled"));
  424. config_set_default_string(globalConfig, "Basic", "SceneCollection",
  425. Str("Untitled"));
  426. config_set_default_string(globalConfig, "Basic", "SceneCollectionFile",
  427. Str("Untitled"));
  428. move_basic_to_profiles();
  429. move_basic_to_scene_collections();
  430. if (!MakeUserProfileDirs())
  431. throw "Failed to create profile directories";
  432. }
  433. const char *OBSApp::GetRenderModule() const
  434. {
  435. const char *renderer = config_get_string(globalConfig, "Video",
  436. "Renderer");
  437. return (astrcmpi(renderer, "Direct3D 11") == 0) ?
  438. DL_D3D11 : DL_OPENGL;
  439. }
  440. bool OBSApp::OBSInit()
  441. {
  442. bool licenseAccepted = config_get_bool(globalConfig, "General",
  443. "LicenseAccepted");
  444. OBSLicenseAgreement agreement(nullptr);
  445. if (licenseAccepted || agreement.exec() == QDialog::Accepted) {
  446. if (!licenseAccepted) {
  447. config_set_bool(globalConfig, "General",
  448. "LicenseAccepted", true);
  449. config_save(globalConfig);
  450. }
  451. mainWindow = new OBSBasic();
  452. mainWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  453. connect(mainWindow, SIGNAL(destroyed()), this, SLOT(quit()));
  454. mainWindow->OBSInit();
  455. connect(this, &QGuiApplication::applicationStateChanged,
  456. [](Qt::ApplicationState state)
  457. {
  458. obs_hotkey_enable_background_press(
  459. state != Qt::ApplicationActive);
  460. });
  461. obs_hotkey_enable_background_press(
  462. applicationState() != Qt::ApplicationActive);
  463. return true;
  464. } else {
  465. return false;
  466. }
  467. }
  468. string OBSApp::GetVersionString() const
  469. {
  470. stringstream ver;
  471. #ifdef HAVE_OBSCONFIG_H
  472. ver << OBS_VERSION;
  473. #else
  474. ver << LIBOBS_API_MAJOR_VER << "." <<
  475. LIBOBS_API_MINOR_VER << "." <<
  476. LIBOBS_API_PATCH_VER;
  477. #endif
  478. ver << " (";
  479. #ifdef _WIN32
  480. if (sizeof(void*) == 8)
  481. ver << "64bit, ";
  482. ver << "windows)";
  483. #elif __APPLE__
  484. ver << "mac)";
  485. #elif __FreeBSD__
  486. ver << "freebsd)";
  487. #else /* assume linux for the time being */
  488. ver << "linux)";
  489. #endif
  490. return ver.str();
  491. }
  492. #ifdef __APPLE__
  493. #define INPUT_AUDIO_SOURCE "coreaudio_input_capture"
  494. #define OUTPUT_AUDIO_SOURCE "coreaudio_output_capture"
  495. #elif _WIN32
  496. #define INPUT_AUDIO_SOURCE "wasapi_input_capture"
  497. #define OUTPUT_AUDIO_SOURCE "wasapi_output_capture"
  498. #else
  499. #define INPUT_AUDIO_SOURCE "pulse_input_capture"
  500. #define OUTPUT_AUDIO_SOURCE "pulse_output_capture"
  501. #endif
  502. const char *OBSApp::InputAudioSource() const
  503. {
  504. return INPUT_AUDIO_SOURCE;
  505. }
  506. const char *OBSApp::OutputAudioSource() const
  507. {
  508. return OUTPUT_AUDIO_SOURCE;
  509. }
  510. const char *OBSApp::GetLastLog() const
  511. {
  512. return lastLogFile.c_str();
  513. }
  514. const char *OBSApp::GetCurrentLog() const
  515. {
  516. return currentLogFile.c_str();
  517. }
  518. QString OBSTranslator::translate(const char *context, const char *sourceText,
  519. const char *disambiguation, int n) const
  520. {
  521. const char *out = nullptr;
  522. if (!text_lookup_getstr(App()->GetTextLookup(), sourceText, &out))
  523. return QString();
  524. UNUSED_PARAMETER(context);
  525. UNUSED_PARAMETER(disambiguation);
  526. UNUSED_PARAMETER(n);
  527. return QT_UTF8(out);
  528. }
  529. static bool get_token(lexer *lex, string &str, base_token_type type)
  530. {
  531. base_token token;
  532. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  533. return false;
  534. if (token.type != type)
  535. return false;
  536. str.assign(token.text.array, token.text.len);
  537. return true;
  538. }
  539. static bool expect_token(lexer *lex, const char *str, base_token_type type)
  540. {
  541. base_token token;
  542. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  543. return false;
  544. if (token.type != type)
  545. return false;
  546. return strref_cmp(&token.text, str) == 0;
  547. }
  548. static uint64_t convert_log_name(const char *name)
  549. {
  550. BaseLexer lex;
  551. string year, month, day, hour, minute, second;
  552. lexer_start(lex, name);
  553. if (!get_token(lex, year, BASETOKEN_DIGIT)) return 0;
  554. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  555. if (!get_token(lex, month, BASETOKEN_DIGIT)) return 0;
  556. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  557. if (!get_token(lex, day, BASETOKEN_DIGIT)) return 0;
  558. if (!get_token(lex, hour, BASETOKEN_DIGIT)) return 0;
  559. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  560. if (!get_token(lex, minute, BASETOKEN_DIGIT)) return 0;
  561. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  562. if (!get_token(lex, second, BASETOKEN_DIGIT)) return 0;
  563. stringstream timestring;
  564. timestring << year << month << day << hour << minute << second;
  565. return std::stoull(timestring.str());
  566. }
  567. static void delete_oldest_file(const char *location)
  568. {
  569. BPtr<char> logDir(GetConfigPathPtr(location));
  570. string oldestLog;
  571. uint64_t oldest_ts = (uint64_t)-1;
  572. struct os_dirent *entry;
  573. unsigned int maxLogs = (unsigned int)config_get_uint(
  574. App()->GlobalConfig(), "General", "MaxLogs");
  575. os_dir_t *dir = os_opendir(logDir);
  576. if (dir) {
  577. unsigned int count = 0;
  578. while ((entry = os_readdir(dir)) != NULL) {
  579. if (entry->directory || *entry->d_name == '.')
  580. continue;
  581. uint64_t ts = convert_log_name(entry->d_name);
  582. if (ts) {
  583. if (ts < oldest_ts) {
  584. oldestLog = entry->d_name;
  585. oldest_ts = ts;
  586. }
  587. count++;
  588. }
  589. }
  590. os_closedir(dir);
  591. if (count > maxLogs) {
  592. stringstream delPath;
  593. delPath << logDir << "/" << oldestLog;
  594. os_unlink(delPath.str().c_str());
  595. }
  596. }
  597. }
  598. static void get_last_log(void)
  599. {
  600. BPtr<char> logDir(GetConfigPathPtr("obs-studio/logs"));
  601. struct os_dirent *entry;
  602. os_dir_t *dir = os_opendir(logDir);
  603. uint64_t highest_ts = 0;
  604. if (dir) {
  605. while ((entry = os_readdir(dir)) != NULL) {
  606. if (entry->directory || *entry->d_name == '.')
  607. continue;
  608. uint64_t ts = convert_log_name(entry->d_name);
  609. if (ts > highest_ts) {
  610. lastLogFile = entry->d_name;
  611. highest_ts = ts;
  612. }
  613. }
  614. os_closedir(dir);
  615. }
  616. }
  617. string GenerateTimeDateFilename(const char *extension)
  618. {
  619. time_t now = time(0);
  620. char file[256] = {};
  621. struct tm *cur_time;
  622. cur_time = localtime(&now);
  623. snprintf(file, sizeof(file), "%d-%02d-%02d %02d-%02d-%02d.%s",
  624. cur_time->tm_year+1900,
  625. cur_time->tm_mon+1,
  626. cur_time->tm_mday,
  627. cur_time->tm_hour,
  628. cur_time->tm_min,
  629. cur_time->tm_sec,
  630. extension);
  631. return string(file);
  632. }
  633. vector<pair<string, string>> GetLocaleNames()
  634. {
  635. string path;
  636. if (!GetDataFilePath("locale.ini", path))
  637. throw "Could not find locale.ini path";
  638. ConfigFile ini;
  639. if (ini.Open(path.c_str(), CONFIG_OPEN_EXISTING) != 0)
  640. throw "Could not open locale.ini";
  641. size_t sections = config_num_sections(ini);
  642. vector<pair<string, string>> names;
  643. names.reserve(sections);
  644. for (size_t i = 0; i < sections; i++) {
  645. const char *tag = config_get_section(ini, i);
  646. const char *name = config_get_string(ini, tag, "Name");
  647. names.emplace_back(tag, name);
  648. }
  649. return names;
  650. }
  651. static void create_log_file(fstream &logFile)
  652. {
  653. stringstream dst;
  654. get_last_log();
  655. currentLogFile = GenerateTimeDateFilename("txt");
  656. dst << "obs-studio/logs/" << currentLogFile.c_str();
  657. BPtr<char> path(GetConfigPathPtr(dst.str().c_str()));
  658. logFile.open(path,
  659. ios_base::in | ios_base::out | ios_base::trunc);
  660. if (logFile.is_open()) {
  661. delete_oldest_file("obs-studio/logs");
  662. base_set_log_handler(do_log, &logFile);
  663. } else {
  664. blog(LOG_ERROR, "Failed to open log file");
  665. }
  666. }
  667. static int run_program(fstream &logFile, int argc, char *argv[])
  668. {
  669. int ret = -1;
  670. QCoreApplication::addLibraryPath(".");
  671. OBSApp program(argc, argv);
  672. try {
  673. program.AppInit();
  674. OBSTranslator translator;
  675. create_log_file(logFile);
  676. program.installTranslator(&translator);
  677. ret = program.OBSInit() ? program.exec() : 0;
  678. } catch (const char *error) {
  679. blog(LOG_ERROR, "%s", error);
  680. OBSErrorBox(nullptr, "%s", error);
  681. }
  682. return ret;
  683. }
  684. #define MAX_CRASH_REPORT_SIZE (50 * 1024)
  685. #ifdef _WIN32
  686. #define CRASH_MESSAGE \
  687. "Woops, OBS has crashed!\n\nWould you like to copy the crash log " \
  688. "to the clipboard? (Crash logs will still be saved to the " \
  689. "%appdata%\\obs-studio\\crashes directory)"
  690. static void main_crash_handler(const char *format, va_list args, void *param)
  691. {
  692. char *text = new char[MAX_CRASH_REPORT_SIZE];
  693. vsnprintf(text, MAX_CRASH_REPORT_SIZE, format, args);
  694. delete_oldest_file("obs-studio/crashes");
  695. string name = "obs-studio/crashes/Crash ";
  696. name += GenerateTimeDateFilename("txt");
  697. BPtr<char> path(GetConfigPathPtr(name.c_str()));
  698. fstream file;
  699. file.open(path, ios_base::in | ios_base::out | ios_base::trunc);
  700. file << text;
  701. file.close();
  702. int ret = MessageBoxA(NULL, CRASH_MESSAGE, "OBS has crashed!",
  703. MB_YESNO | MB_ICONERROR | MB_TASKMODAL);
  704. if (ret == IDYES) {
  705. size_t len = strlen(text);
  706. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, len);
  707. memcpy(GlobalLock(mem), text, len);
  708. GlobalUnlock(mem);
  709. OpenClipboard(0);
  710. EmptyClipboard();
  711. SetClipboardData(CF_TEXT, mem);
  712. CloseClipboard();
  713. }
  714. exit(-1);
  715. UNUSED_PARAMETER(param);
  716. }
  717. static void load_debug_privilege(void)
  718. {
  719. const DWORD flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY;
  720. TOKEN_PRIVILEGES tp;
  721. HANDLE token;
  722. LUID val;
  723. if (!OpenProcessToken(GetCurrentProcess(), flags, &token)) {
  724. return;
  725. }
  726. if (!!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &val)) {
  727. tp.PrivilegeCount = 1;
  728. tp.Privileges[0].Luid = val;
  729. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  730. AdjustTokenPrivileges(token, false, &tp,
  731. sizeof(tp), NULL, NULL);
  732. }
  733. CloseHandle(token);
  734. }
  735. #endif
  736. #ifdef __APPLE__
  737. #define BASE_PATH ".."
  738. #else
  739. #define BASE_PATH "../.."
  740. #endif
  741. #define CONFIG_PATH BASE_PATH "/config"
  742. #ifndef OBS_UNIX_STRUCTURE
  743. #define OBS_UNIX_STRUCTURE 0
  744. #endif
  745. int GetConfigPath(char *path, size_t size, const char *name)
  746. {
  747. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  748. if (name && *name) {
  749. return snprintf(path, size, CONFIG_PATH "/%s", name);
  750. } else {
  751. return snprintf(path, size, CONFIG_PATH);
  752. }
  753. } else {
  754. return os_get_config_path(path, size, name);
  755. }
  756. }
  757. char *GetConfigPathPtr(const char *name)
  758. {
  759. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  760. char path[512];
  761. if (snprintf(path, sizeof(path), CONFIG_PATH "/%s", name) > 0) {
  762. return bstrdup(path);
  763. } else {
  764. return NULL;
  765. }
  766. } else {
  767. return os_get_config_path_ptr(name);
  768. }
  769. }
  770. bool GetFileSafeName(const char *name, std::string &file)
  771. {
  772. size_t base_len = strlen(name);
  773. size_t len = os_utf8_to_wcs(name, base_len, nullptr, 0);
  774. std::wstring wfile;
  775. if (!len)
  776. return false;
  777. wfile.resize(len);
  778. os_utf8_to_wcs(name, base_len, &wfile[0], len);
  779. for (size_t i = wfile.size(); i > 0; i--) {
  780. size_t im1 = i - 1;
  781. if (iswspace(wfile[im1])) {
  782. wfile[im1] = '_';
  783. } else if (wfile[im1] != '_' && !iswalnum(wfile[im1])) {
  784. wfile.erase(im1, 1);
  785. }
  786. }
  787. if (wfile.size() == 0)
  788. wfile = L"characters_only";
  789. len = os_wcs_to_utf8(wfile.c_str(), wfile.size(), nullptr, 0);
  790. if (!len)
  791. return false;
  792. file.resize(len);
  793. os_wcs_to_utf8(wfile.c_str(), wfile.size(), &file[0], len);
  794. return true;
  795. }
  796. bool GetClosestUnusedFileName(std::string &path, const char *extension)
  797. {
  798. size_t len = path.size();
  799. if (extension) {
  800. path += ".";
  801. path += extension;
  802. }
  803. if (!os_file_exists(path.c_str()))
  804. return true;
  805. int index = 1;
  806. do {
  807. path.resize(len);
  808. path += std::to_string(++index);
  809. if (extension) {
  810. path += ".";
  811. path += extension;
  812. }
  813. } while (os_file_exists(path.c_str()));
  814. return true;
  815. }
  816. static inline bool arg_is(const char *arg,
  817. const char *long_form, const char *short_form)
  818. {
  819. return (long_form && strcmp(arg, long_form) == 0) ||
  820. (short_form && strcmp(arg, short_form) == 0);
  821. }
  822. int main(int argc, char *argv[])
  823. {
  824. #ifndef _WIN32
  825. signal(SIGPIPE, SIG_IGN);
  826. #endif
  827. #ifdef _WIN32
  828. load_debug_privilege();
  829. base_set_crash_handler(main_crash_handler, nullptr);
  830. #endif
  831. base_get_log_handler(&def_log_handler, nullptr);
  832. for (int i = 1; i < argc; i++) {
  833. if (arg_is(argv[i], "--portable", "-p")) {
  834. portable_mode = true;
  835. }
  836. }
  837. #if !OBS_UNIX_STRUCTURE
  838. if (!portable_mode) {
  839. portable_mode =
  840. os_file_exists(BASE_PATH "/portable_mode") ||
  841. os_file_exists(BASE_PATH "/obs_portable_mode") ||
  842. os_file_exists(BASE_PATH "/portable_mode.txt") ||
  843. os_file_exists(BASE_PATH "/obs_portable_mode.txt");
  844. }
  845. #endif
  846. fstream logFile;
  847. int ret = run_program(logFile, argc, argv);
  848. blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
  849. base_set_log_handler(nullptr, nullptr);
  850. return ret;
  851. }