obs-app.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  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 inline void LogString(fstream &logFile, const char *timeString,
  158. char *str)
  159. {
  160. logFile << timeString << str << endl;
  161. }
  162. static inline void LogStringChunk(fstream &logFile, char *str)
  163. {
  164. char *nextLine = str;
  165. string timeString = CurrentTimeString();
  166. timeString += ": ";
  167. while (*nextLine) {
  168. char *nextLine = strchr(str, '\n');
  169. if (!nextLine)
  170. break;
  171. if (nextLine != str && nextLine[-1] == '\r') {
  172. nextLine[-1] = 0;
  173. } else {
  174. nextLine[0] = 0;
  175. }
  176. LogString(logFile, timeString.c_str(), str);
  177. nextLine++;
  178. str = nextLine;
  179. }
  180. LogString(logFile, timeString.c_str(), str);
  181. }
  182. static void do_log(int log_level, const char *msg, va_list args, void *param)
  183. {
  184. fstream &logFile = *static_cast<fstream*>(param);
  185. char str[4096];
  186. #ifndef _WIN32
  187. va_list args2;
  188. va_copy(args2, args);
  189. #endif
  190. vsnprintf(str, 4095, msg, args);
  191. #ifdef _WIN32
  192. OutputDebugStringA(str);
  193. OutputDebugStringA("\n");
  194. #else
  195. def_log_handler(log_level, msg, args2, nullptr);
  196. #endif
  197. if (log_level <= LOG_INFO)
  198. LogStringChunk(logFile, str);
  199. #ifdef _WIN32
  200. if (log_level <= LOG_ERROR && IsDebuggerPresent())
  201. __debugbreak();
  202. #endif
  203. }
  204. #define DEFAULT_LANG "en-US"
  205. bool OBSApp::InitGlobalConfigDefaults()
  206. {
  207. config_set_default_string(globalConfig, "General", "Language",
  208. DEFAULT_LANG);
  209. config_set_default_uint(globalConfig, "General", "MaxLogs", 10);
  210. #if _WIN32
  211. config_set_default_string(globalConfig, "Video", "Renderer",
  212. "Direct3D 11");
  213. #else
  214. config_set_default_string(globalConfig, "Video", "Renderer", "OpenGL");
  215. #endif
  216. config_set_default_bool(globalConfig, "BasicWindow", "PreviewEnabled",
  217. true);
  218. return true;
  219. }
  220. static bool do_mkdir(const char *path)
  221. {
  222. if (os_mkdir(path) == MKDIR_ERROR) {
  223. OBSErrorBox(NULL, "Failed to create directory %s", path);
  224. return false;
  225. }
  226. return true;
  227. }
  228. static bool MakeUserDirs()
  229. {
  230. char path[512];
  231. if (portable_mode) {
  232. if (GetConfigPath(path, sizeof(path), "") <= 0)
  233. return false;
  234. if (!do_mkdir(path))
  235. return false;
  236. }
  237. if (GetConfigPath(path, sizeof(path), "obs-studio") <= 0)
  238. return false;
  239. if (!do_mkdir(path))
  240. return false;
  241. if (GetConfigPath(path, sizeof(path), "obs-studio/basic") <= 0)
  242. return false;
  243. if (!do_mkdir(path))
  244. return false;
  245. if (GetConfigPath(path, sizeof(path), "obs-studio/logs") <= 0)
  246. return false;
  247. if (!do_mkdir(path))
  248. return false;
  249. #ifdef _WIN32
  250. if (GetConfigPath(path, sizeof(path), "obs-studio/crashes") <= 0)
  251. return false;
  252. if (!do_mkdir(path))
  253. return false;
  254. #endif
  255. return true;
  256. }
  257. static bool MakeUserProfileDirs()
  258. {
  259. char path[512];
  260. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/profiles") <= 0)
  261. return false;
  262. if (!do_mkdir(path))
  263. return false;
  264. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/scenes") <= 0)
  265. return false;
  266. if (!do_mkdir(path))
  267. return false;
  268. return true;
  269. }
  270. bool OBSApp::InitGlobalConfig()
  271. {
  272. char path[512];
  273. int len = GetConfigPath(path, sizeof(path),
  274. "obs-studio/global.ini");
  275. if (len <= 0) {
  276. return false;
  277. }
  278. int errorcode = globalConfig.Open(path, CONFIG_OPEN_ALWAYS);
  279. if (errorcode != CONFIG_SUCCESS) {
  280. OBSErrorBox(NULL, "Failed to open global.ini: %d", errorcode);
  281. return false;
  282. }
  283. return InitGlobalConfigDefaults();
  284. }
  285. bool OBSApp::InitLocale()
  286. {
  287. const char *lang = config_get_string(globalConfig, "General",
  288. "Language");
  289. locale = lang;
  290. string englishPath;
  291. if (!GetDataFilePath("locale/" DEFAULT_LANG ".ini", englishPath)) {
  292. OBSErrorBox(NULL, "Failed to find locale/" DEFAULT_LANG ".ini");
  293. return false;
  294. }
  295. textLookup = text_lookup_create(englishPath.c_str());
  296. if (!textLookup) {
  297. OBSErrorBox(NULL, "Failed to create locale from file '%s'",
  298. englishPath.c_str());
  299. return false;
  300. }
  301. bool userLocale = config_has_user_value(globalConfig, "General",
  302. "Language");
  303. bool defaultLang = astrcmpi(lang, DEFAULT_LANG) == 0;
  304. if (userLocale && defaultLang)
  305. return true;
  306. if (!userLocale && defaultLang) {
  307. for (auto &locale_ : GetPreferredLocales()) {
  308. if (locale_ == lang)
  309. return true;
  310. stringstream file;
  311. file << "locale/" << locale_ << ".ini";
  312. string path;
  313. if (!GetDataFilePath(file.str().c_str(), path))
  314. continue;
  315. if (!text_lookup_add(textLookup, path.c_str()))
  316. continue;
  317. blog(LOG_INFO, "Using preferred locale '%s'",
  318. locale_.c_str());
  319. locale = locale_;
  320. return true;
  321. }
  322. return true;
  323. }
  324. stringstream file;
  325. file << "locale/" << lang << ".ini";
  326. string path;
  327. if (GetDataFilePath(file.str().c_str(), path)) {
  328. if (!text_lookup_add(textLookup, path.c_str()))
  329. blog(LOG_ERROR, "Failed to add locale file '%s'",
  330. path.c_str());
  331. } else {
  332. blog(LOG_ERROR, "Could not find locale file '%s'",
  333. file.str().c_str());
  334. }
  335. return true;
  336. }
  337. bool OBSApp::SetTheme(std::string name, std::string path)
  338. {
  339. theme = name;
  340. /* Check user dir first, then preinstalled themes. */
  341. if (path == "") {
  342. char userDir[512];
  343. name = "themes/" + name + ".qss";
  344. string temp = "obs-studio/" + name;
  345. int ret = GetConfigPath(userDir, sizeof(userDir),
  346. temp.c_str());
  347. if (ret > 0 && QFile::exists(userDir)) {
  348. path = string(userDir);
  349. } else if (!GetDataFilePath(name.c_str(), path)) {
  350. OBSErrorBox(NULL, "Failed to find %s.", name.c_str());
  351. return false;
  352. }
  353. }
  354. QString mpath = QString("file:///") + path.c_str();
  355. setStyleSheet(mpath);
  356. return true;
  357. }
  358. bool OBSApp::InitTheme()
  359. {
  360. const char *themeName = config_get_string(globalConfig, "General",
  361. "Theme");
  362. if (!themeName)
  363. themeName = "Default";
  364. stringstream t;
  365. t << themeName;
  366. return SetTheme(t.str());
  367. }
  368. OBSApp::OBSApp(int &argc, char **argv)
  369. : QApplication(argc, argv)
  370. {}
  371. static void move_basic_to_profiles(void)
  372. {
  373. char path[512];
  374. char new_path[512];
  375. os_glob_t *glob;
  376. /* if not first time use */
  377. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  378. return;
  379. if (!os_file_exists(path))
  380. return;
  381. /* if the profiles directory doesn't already exist */
  382. if (GetConfigPath(new_path, 512, "obs-studio/basic/profiles") <= 0)
  383. return;
  384. if (os_file_exists(new_path))
  385. return;
  386. if (os_mkdir(new_path) == MKDIR_ERROR)
  387. return;
  388. strcat(new_path, "/");
  389. strcat(new_path, Str("Untitled"));
  390. if (os_mkdir(new_path) == MKDIR_ERROR)
  391. return;
  392. strcat(path, "/*.*");
  393. if (os_glob(path, 0, &glob) != 0)
  394. return;
  395. strcpy(path, new_path);
  396. for (size_t i = 0; i < glob->gl_pathc; i++) {
  397. struct os_globent ent = glob->gl_pathv[i];
  398. char *file;
  399. if (ent.directory)
  400. continue;
  401. file = strrchr(ent.path, '/');
  402. if (!file++)
  403. continue;
  404. if (astrcmpi(file, "scenes.json") == 0)
  405. continue;
  406. strcpy(new_path, path);
  407. strcat(new_path, "/");
  408. strcat(new_path, file);
  409. os_rename(ent.path, new_path);
  410. }
  411. os_globfree(glob);
  412. }
  413. static void move_basic_to_scene_collections(void)
  414. {
  415. char path[512];
  416. char new_path[512];
  417. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  418. return;
  419. if (!os_file_exists(path))
  420. return;
  421. if (GetConfigPath(new_path, 512, "obs-studio/basic/scenes") <= 0)
  422. return;
  423. if (os_file_exists(new_path))
  424. return;
  425. if (os_mkdir(new_path) == MKDIR_ERROR)
  426. return;
  427. strcat(path, "/scenes.json");
  428. strcat(new_path, "/");
  429. strcat(new_path, Str("Untitled"));
  430. strcat(new_path, ".json");
  431. os_rename(path, new_path);
  432. }
  433. void OBSApp::AppInit()
  434. {
  435. if (!InitApplicationBundle())
  436. throw "Failed to initialize application bundle";
  437. if (!MakeUserDirs())
  438. throw "Failed to create required user directories";
  439. if (!InitGlobalConfig())
  440. throw "Failed to initialize global config";
  441. if (!InitLocale())
  442. throw "Failed to load locale";
  443. if (!InitTheme())
  444. throw "Failed to load theme";
  445. config_set_default_string(globalConfig, "Basic", "Profile",
  446. Str("Untitled"));
  447. config_set_default_string(globalConfig, "Basic", "ProfileDir",
  448. Str("Untitled"));
  449. config_set_default_string(globalConfig, "Basic", "SceneCollection",
  450. Str("Untitled"));
  451. config_set_default_string(globalConfig, "Basic", "SceneCollectionFile",
  452. Str("Untitled"));
  453. move_basic_to_profiles();
  454. move_basic_to_scene_collections();
  455. if (!MakeUserProfileDirs())
  456. throw "Failed to create profile directories";
  457. }
  458. const char *OBSApp::GetRenderModule() const
  459. {
  460. const char *renderer = config_get_string(globalConfig, "Video",
  461. "Renderer");
  462. return (astrcmpi(renderer, "Direct3D 11") == 0) ?
  463. DL_D3D11 : DL_OPENGL;
  464. }
  465. bool OBSApp::OBSInit()
  466. {
  467. bool licenseAccepted = config_get_bool(globalConfig, "General",
  468. "LicenseAccepted");
  469. OBSLicenseAgreement agreement(nullptr);
  470. if (licenseAccepted || agreement.exec() == QDialog::Accepted) {
  471. if (!licenseAccepted) {
  472. config_set_bool(globalConfig, "General",
  473. "LicenseAccepted", true);
  474. config_save(globalConfig);
  475. }
  476. mainWindow = new OBSBasic();
  477. mainWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  478. connect(mainWindow, SIGNAL(destroyed()), this, SLOT(quit()));
  479. mainWindow->OBSInit();
  480. connect(this, &QGuiApplication::applicationStateChanged,
  481. [](Qt::ApplicationState state)
  482. {
  483. obs_hotkey_enable_background_press(
  484. state != Qt::ApplicationActive);
  485. });
  486. obs_hotkey_enable_background_press(
  487. applicationState() != Qt::ApplicationActive);
  488. return true;
  489. } else {
  490. return false;
  491. }
  492. }
  493. string OBSApp::GetVersionString() const
  494. {
  495. stringstream ver;
  496. #ifdef HAVE_OBSCONFIG_H
  497. ver << OBS_VERSION;
  498. #else
  499. ver << LIBOBS_API_MAJOR_VER << "." <<
  500. LIBOBS_API_MINOR_VER << "." <<
  501. LIBOBS_API_PATCH_VER;
  502. #endif
  503. ver << " (";
  504. #ifdef _WIN32
  505. if (sizeof(void*) == 8)
  506. ver << "64bit, ";
  507. ver << "windows)";
  508. #elif __APPLE__
  509. ver << "mac)";
  510. #elif __FreeBSD__
  511. ver << "freebsd)";
  512. #else /* assume linux for the time being */
  513. ver << "linux)";
  514. #endif
  515. return ver.str();
  516. }
  517. #ifdef __APPLE__
  518. #define INPUT_AUDIO_SOURCE "coreaudio_input_capture"
  519. #define OUTPUT_AUDIO_SOURCE "coreaudio_output_capture"
  520. #elif _WIN32
  521. #define INPUT_AUDIO_SOURCE "wasapi_input_capture"
  522. #define OUTPUT_AUDIO_SOURCE "wasapi_output_capture"
  523. #else
  524. #define INPUT_AUDIO_SOURCE "pulse_input_capture"
  525. #define OUTPUT_AUDIO_SOURCE "pulse_output_capture"
  526. #endif
  527. const char *OBSApp::InputAudioSource() const
  528. {
  529. return INPUT_AUDIO_SOURCE;
  530. }
  531. const char *OBSApp::OutputAudioSource() const
  532. {
  533. return OUTPUT_AUDIO_SOURCE;
  534. }
  535. const char *OBSApp::GetLastLog() const
  536. {
  537. return lastLogFile.c_str();
  538. }
  539. const char *OBSApp::GetCurrentLog() const
  540. {
  541. return currentLogFile.c_str();
  542. }
  543. QString OBSTranslator::translate(const char *context, const char *sourceText,
  544. const char *disambiguation, int n) const
  545. {
  546. const char *out = nullptr;
  547. if (!text_lookup_getstr(App()->GetTextLookup(), sourceText, &out))
  548. return QString();
  549. UNUSED_PARAMETER(context);
  550. UNUSED_PARAMETER(disambiguation);
  551. UNUSED_PARAMETER(n);
  552. return QT_UTF8(out);
  553. }
  554. static bool get_token(lexer *lex, string &str, base_token_type type)
  555. {
  556. base_token token;
  557. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  558. return false;
  559. if (token.type != type)
  560. return false;
  561. str.assign(token.text.array, token.text.len);
  562. return true;
  563. }
  564. static bool expect_token(lexer *lex, const char *str, base_token_type type)
  565. {
  566. base_token token;
  567. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  568. return false;
  569. if (token.type != type)
  570. return false;
  571. return strref_cmp(&token.text, str) == 0;
  572. }
  573. static uint64_t convert_log_name(const char *name)
  574. {
  575. BaseLexer lex;
  576. string year, month, day, hour, minute, second;
  577. lexer_start(lex, name);
  578. if (!get_token(lex, year, BASETOKEN_DIGIT)) return 0;
  579. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  580. if (!get_token(lex, month, BASETOKEN_DIGIT)) return 0;
  581. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  582. if (!get_token(lex, day, BASETOKEN_DIGIT)) return 0;
  583. if (!get_token(lex, hour, BASETOKEN_DIGIT)) return 0;
  584. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  585. if (!get_token(lex, minute, BASETOKEN_DIGIT)) return 0;
  586. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  587. if (!get_token(lex, second, BASETOKEN_DIGIT)) return 0;
  588. stringstream timestring;
  589. timestring << year << month << day << hour << minute << second;
  590. return std::stoull(timestring.str());
  591. }
  592. static void delete_oldest_file(const char *location)
  593. {
  594. BPtr<char> logDir(GetConfigPathPtr(location));
  595. string oldestLog;
  596. uint64_t oldest_ts = (uint64_t)-1;
  597. struct os_dirent *entry;
  598. unsigned int maxLogs = (unsigned int)config_get_uint(
  599. App()->GlobalConfig(), "General", "MaxLogs");
  600. os_dir_t *dir = os_opendir(logDir);
  601. if (dir) {
  602. unsigned int count = 0;
  603. while ((entry = os_readdir(dir)) != NULL) {
  604. if (entry->directory || *entry->d_name == '.')
  605. continue;
  606. uint64_t ts = convert_log_name(entry->d_name);
  607. if (ts) {
  608. if (ts < oldest_ts) {
  609. oldestLog = entry->d_name;
  610. oldest_ts = ts;
  611. }
  612. count++;
  613. }
  614. }
  615. os_closedir(dir);
  616. if (count > maxLogs) {
  617. stringstream delPath;
  618. delPath << logDir << "/" << oldestLog;
  619. os_unlink(delPath.str().c_str());
  620. }
  621. }
  622. }
  623. static void get_last_log(void)
  624. {
  625. BPtr<char> logDir(GetConfigPathPtr("obs-studio/logs"));
  626. struct os_dirent *entry;
  627. os_dir_t *dir = os_opendir(logDir);
  628. uint64_t highest_ts = 0;
  629. if (dir) {
  630. while ((entry = os_readdir(dir)) != NULL) {
  631. if (entry->directory || *entry->d_name == '.')
  632. continue;
  633. uint64_t ts = convert_log_name(entry->d_name);
  634. if (ts > highest_ts) {
  635. lastLogFile = entry->d_name;
  636. highest_ts = ts;
  637. }
  638. }
  639. os_closedir(dir);
  640. }
  641. }
  642. string GenerateTimeDateFilename(const char *extension)
  643. {
  644. time_t now = time(0);
  645. char file[256] = {};
  646. struct tm *cur_time;
  647. cur_time = localtime(&now);
  648. snprintf(file, sizeof(file), "%d-%02d-%02d %02d-%02d-%02d.%s",
  649. cur_time->tm_year+1900,
  650. cur_time->tm_mon+1,
  651. cur_time->tm_mday,
  652. cur_time->tm_hour,
  653. cur_time->tm_min,
  654. cur_time->tm_sec,
  655. extension);
  656. return string(file);
  657. }
  658. vector<pair<string, string>> GetLocaleNames()
  659. {
  660. string path;
  661. if (!GetDataFilePath("locale.ini", path))
  662. throw "Could not find locale.ini path";
  663. ConfigFile ini;
  664. if (ini.Open(path.c_str(), CONFIG_OPEN_EXISTING) != 0)
  665. throw "Could not open locale.ini";
  666. size_t sections = config_num_sections(ini);
  667. vector<pair<string, string>> names;
  668. names.reserve(sections);
  669. for (size_t i = 0; i < sections; i++) {
  670. const char *tag = config_get_section(ini, i);
  671. const char *name = config_get_string(ini, tag, "Name");
  672. names.emplace_back(tag, name);
  673. }
  674. return names;
  675. }
  676. static void create_log_file(fstream &logFile)
  677. {
  678. stringstream dst;
  679. get_last_log();
  680. currentLogFile = GenerateTimeDateFilename("txt");
  681. dst << "obs-studio/logs/" << currentLogFile.c_str();
  682. BPtr<char> path(GetConfigPathPtr(dst.str().c_str()));
  683. logFile.open(path,
  684. ios_base::in | ios_base::out | ios_base::trunc);
  685. if (logFile.is_open()) {
  686. delete_oldest_file("obs-studio/logs");
  687. base_set_log_handler(do_log, &logFile);
  688. } else {
  689. blog(LOG_ERROR, "Failed to open log file");
  690. }
  691. }
  692. static int run_program(fstream &logFile, int argc, char *argv[])
  693. {
  694. int ret = -1;
  695. QCoreApplication::addLibraryPath(".");
  696. OBSApp program(argc, argv);
  697. try {
  698. program.AppInit();
  699. OBSTranslator translator;
  700. create_log_file(logFile);
  701. program.installTranslator(&translator);
  702. ret = program.OBSInit() ? program.exec() : 0;
  703. } catch (const char *error) {
  704. blog(LOG_ERROR, "%s", error);
  705. OBSErrorBox(nullptr, "%s", error);
  706. }
  707. return ret;
  708. }
  709. #define MAX_CRASH_REPORT_SIZE (50 * 1024)
  710. #ifdef _WIN32
  711. #define CRASH_MESSAGE \
  712. "Woops, OBS has crashed!\n\nWould you like to copy the crash log " \
  713. "to the clipboard? (Crash logs will still be saved to the " \
  714. "%appdata%\\obs-studio\\crashes directory)"
  715. static void main_crash_handler(const char *format, va_list args, void *param)
  716. {
  717. char *text = new char[MAX_CRASH_REPORT_SIZE];
  718. vsnprintf(text, MAX_CRASH_REPORT_SIZE, format, args);
  719. delete_oldest_file("obs-studio/crashes");
  720. string name = "obs-studio/crashes/Crash ";
  721. name += GenerateTimeDateFilename("txt");
  722. BPtr<char> path(GetConfigPathPtr(name.c_str()));
  723. fstream file;
  724. file.open(path, ios_base::in | ios_base::out | ios_base::trunc);
  725. file << text;
  726. file.close();
  727. int ret = MessageBoxA(NULL, CRASH_MESSAGE, "OBS has crashed!",
  728. MB_YESNO | MB_ICONERROR | MB_TASKMODAL);
  729. if (ret == IDYES) {
  730. size_t len = strlen(text);
  731. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, len);
  732. memcpy(GlobalLock(mem), text, len);
  733. GlobalUnlock(mem);
  734. OpenClipboard(0);
  735. EmptyClipboard();
  736. SetClipboardData(CF_TEXT, mem);
  737. CloseClipboard();
  738. }
  739. exit(-1);
  740. UNUSED_PARAMETER(param);
  741. }
  742. static void load_debug_privilege(void)
  743. {
  744. const DWORD flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY;
  745. TOKEN_PRIVILEGES tp;
  746. HANDLE token;
  747. LUID val;
  748. if (!OpenProcessToken(GetCurrentProcess(), flags, &token)) {
  749. return;
  750. }
  751. if (!!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &val)) {
  752. tp.PrivilegeCount = 1;
  753. tp.Privileges[0].Luid = val;
  754. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  755. AdjustTokenPrivileges(token, false, &tp,
  756. sizeof(tp), NULL, NULL);
  757. }
  758. CloseHandle(token);
  759. }
  760. #endif
  761. #ifdef __APPLE__
  762. #define BASE_PATH ".."
  763. #else
  764. #define BASE_PATH "../.."
  765. #endif
  766. #define CONFIG_PATH BASE_PATH "/config"
  767. #ifndef OBS_UNIX_STRUCTURE
  768. #define OBS_UNIX_STRUCTURE 0
  769. #endif
  770. int GetConfigPath(char *path, size_t size, const char *name)
  771. {
  772. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  773. if (name && *name) {
  774. return snprintf(path, size, CONFIG_PATH "/%s", name);
  775. } else {
  776. return snprintf(path, size, CONFIG_PATH);
  777. }
  778. } else {
  779. return os_get_config_path(path, size, name);
  780. }
  781. }
  782. char *GetConfigPathPtr(const char *name)
  783. {
  784. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  785. char path[512];
  786. if (snprintf(path, sizeof(path), CONFIG_PATH "/%s", name) > 0) {
  787. return bstrdup(path);
  788. } else {
  789. return NULL;
  790. }
  791. } else {
  792. return os_get_config_path_ptr(name);
  793. }
  794. }
  795. bool GetFileSafeName(const char *name, std::string &file)
  796. {
  797. size_t base_len = strlen(name);
  798. size_t len = os_utf8_to_wcs(name, base_len, nullptr, 0);
  799. std::wstring wfile;
  800. if (!len)
  801. return false;
  802. wfile.resize(len);
  803. os_utf8_to_wcs(name, base_len, &wfile[0], len);
  804. for (size_t i = wfile.size(); i > 0; i--) {
  805. size_t im1 = i - 1;
  806. if (iswspace(wfile[im1])) {
  807. wfile[im1] = '_';
  808. } else if (wfile[im1] != '_' && !iswalnum(wfile[im1])) {
  809. wfile.erase(im1, 1);
  810. }
  811. }
  812. if (wfile.size() == 0)
  813. wfile = L"characters_only";
  814. len = os_wcs_to_utf8(wfile.c_str(), wfile.size(), nullptr, 0);
  815. if (!len)
  816. return false;
  817. file.resize(len);
  818. os_wcs_to_utf8(wfile.c_str(), wfile.size(), &file[0], len);
  819. return true;
  820. }
  821. bool GetClosestUnusedFileName(std::string &path, const char *extension)
  822. {
  823. size_t len = path.size();
  824. if (extension) {
  825. path += ".";
  826. path += extension;
  827. }
  828. if (!os_file_exists(path.c_str()))
  829. return true;
  830. int index = 1;
  831. do {
  832. path.resize(len);
  833. path += std::to_string(++index);
  834. if (extension) {
  835. path += ".";
  836. path += extension;
  837. }
  838. } while (os_file_exists(path.c_str()));
  839. return true;
  840. }
  841. static inline bool arg_is(const char *arg,
  842. const char *long_form, const char *short_form)
  843. {
  844. return (long_form && strcmp(arg, long_form) == 0) ||
  845. (short_form && strcmp(arg, short_form) == 0);
  846. }
  847. #if !defined(_WIN32) && !defined(__APPLE__)
  848. #define IS_UNIX 1
  849. #endif
  850. /* if using XDG and was previously using an older build of OBS, move config
  851. * files to XDG directory */
  852. #if defined(USE_XDG) && defined(IS_UNIX)
  853. static void move_to_xdg(void)
  854. {
  855. char old_path[512];
  856. char new_path[512];
  857. char *home = getenv("HOME");
  858. if (!home)
  859. return;
  860. if (snprintf(old_path, 512, "%s/.obs-studio", home) <= 0)
  861. return;
  862. /* make base xdg path if it doesn't already exist */
  863. if (GetConfigPath(new_path, 512, "") <= 0)
  864. return;
  865. if (os_mkdirs(new_path) == MKDIR_ERROR)
  866. return;
  867. if (GetConfigPath(new_path, 512, "obs-studio") <= 0)
  868. return;
  869. if (os_file_exists(old_path) && !os_file_exists(new_path)) {
  870. rename(old_path, new_path);
  871. }
  872. }
  873. #endif
  874. int main(int argc, char *argv[])
  875. {
  876. #ifndef _WIN32
  877. signal(SIGPIPE, SIG_IGN);
  878. #endif
  879. #ifdef _WIN32
  880. load_debug_privilege();
  881. base_set_crash_handler(main_crash_handler, nullptr);
  882. #endif
  883. base_get_log_handler(&def_log_handler, nullptr);
  884. #if defined(USE_XDG) && defined(IS_UNIX)
  885. move_to_xdg();
  886. #endif
  887. for (int i = 1; i < argc; i++) {
  888. if (arg_is(argv[i], "--portable", "-p")) {
  889. portable_mode = true;
  890. }
  891. }
  892. #if !OBS_UNIX_STRUCTURE
  893. if (!portable_mode) {
  894. portable_mode =
  895. os_file_exists(BASE_PATH "/portable_mode") ||
  896. os_file_exists(BASE_PATH "/obs_portable_mode") ||
  897. os_file_exists(BASE_PATH "/portable_mode.txt") ||
  898. os_file_exists(BASE_PATH "/obs_portable_mode.txt");
  899. }
  900. #endif
  901. fstream logFile;
  902. int ret = run_program(logFile, argc, argv);
  903. blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
  904. base_set_log_handler(nullptr, nullptr);
  905. return ret;
  906. }