obs-app.cpp 19 KB

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