window-basic-main-profiles.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  1. /******************************************************************************
  2. Copyright (C) 2023 by Lain Bailey <lain@obsproject.com>
  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 <filesystem>
  15. #include <functional>
  16. #include <string>
  17. #include <map>
  18. #include <tuple>
  19. #include <obs.hpp>
  20. #include <util/platform.h>
  21. #include <util/util.hpp>
  22. #include <QMessageBox>
  23. #include <QVariant>
  24. #include <QFileDialog>
  25. #include <qt-wrappers.hpp>
  26. #include "window-basic-main.hpp"
  27. #include "window-basic-auto-config.hpp"
  28. #include "window-namedialog.hpp"
  29. // MARK: Constant Expressions
  30. constexpr std::string_view OBSProfilePath = "/obs-studio/basic/profiles/";
  31. constexpr std::string_view OBSProfileSettingsFile = "basic.ini";
  32. // MARK: Forward Declarations
  33. extern void DestroyPanelCookieManager();
  34. extern void DuplicateCurrentCookieProfile(ConfigFile &config);
  35. extern void CheckExistingCookieId();
  36. extern void DeleteCookies();
  37. // MARK: - Anonymous Namespace
  38. namespace {
  39. QList<QString> sortedProfiles{};
  40. void updateSortedProfiles(const OBSProfileCache &profiles)
  41. {
  42. const QLocale locale = QLocale::system();
  43. QList<QString> newList{};
  44. for (auto [profileName, _] : profiles) {
  45. QString entry = QString::fromStdString(profileName);
  46. newList.append(entry);
  47. }
  48. std::sort(newList.begin(), newList.end(), [&locale](const QString &lhs, const QString &rhs) -> bool {
  49. int result = QString::localeAwareCompare(locale.toLower(lhs), locale.toLower(rhs));
  50. return (result < 0);
  51. });
  52. sortedProfiles.swap(newList);
  53. }
  54. } // namespace
  55. // MARK: - Main Profile Management Functions
  56. void OBSBasic::SetupNewProfile(const std::string &profileName, bool useWizard)
  57. {
  58. const OBSProfile &newProfile = CreateProfile(profileName);
  59. config_set_bool(App()->GetUserConfig(), "Basic", "ConfigOnNewProfile", useWizard);
  60. ActivateProfile(newProfile, true);
  61. blog(LOG_INFO, "Created profile '%s' (clean, %s)", newProfile.name.c_str(), newProfile.directoryName.c_str());
  62. blog(LOG_INFO, "------------------------------------------------");
  63. if (useWizard) {
  64. AutoConfig wizard(this);
  65. wizard.setModal(true);
  66. wizard.show();
  67. wizard.exec();
  68. }
  69. }
  70. void OBSBasic::SetupDuplicateProfile(const std::string &profileName)
  71. {
  72. const OBSProfile &newProfile = CreateProfile(profileName);
  73. const OBSProfile &currentProfile = GetCurrentProfile();
  74. const auto copyOptions = std::filesystem::copy_options::recursive |
  75. std::filesystem::copy_options::overwrite_existing;
  76. try {
  77. std::filesystem::copy(currentProfile.path, newProfile.path, copyOptions);
  78. } catch (const std::filesystem::filesystem_error &error) {
  79. blog(LOG_DEBUG, "%s", error.what());
  80. throw std::logic_error("Failed to copy files for cloned profile: " + newProfile.name);
  81. }
  82. ActivateProfile(newProfile);
  83. blog(LOG_INFO, "Created profile '%s' (duplicate, %s)", newProfile.name.c_str(),
  84. newProfile.directoryName.c_str());
  85. blog(LOG_INFO, "------------------------------------------------");
  86. }
  87. void OBSBasic::SetupRenameProfile(const std::string &profileName)
  88. {
  89. const OBSProfile &newProfile = CreateProfile(profileName);
  90. const OBSProfile currentProfile = GetCurrentProfile();
  91. const auto copyOptions = std::filesystem::copy_options::recursive |
  92. std::filesystem::copy_options::overwrite_existing;
  93. try {
  94. std::filesystem::copy(currentProfile.path, newProfile.path, copyOptions);
  95. } catch (const std::filesystem::filesystem_error &error) {
  96. blog(LOG_DEBUG, "%s", error.what());
  97. throw std::logic_error("Failed to copy files for profile: " + currentProfile.name);
  98. }
  99. profiles.erase(currentProfile.name);
  100. ActivateProfile(newProfile);
  101. RemoveProfile(currentProfile);
  102. blog(LOG_INFO, "Renamed profile '%s' to '%s' (%s)", currentProfile.name.c_str(), newProfile.name.c_str(),
  103. newProfile.directoryName.c_str());
  104. blog(LOG_INFO, "------------------------------------------------");
  105. OnEvent(OBS_FRONTEND_EVENT_PROFILE_RENAMED);
  106. }
  107. // MARK: - Profile File Management Functions
  108. const OBSProfile &OBSBasic::CreateProfile(const std::string &profileName)
  109. {
  110. if (const auto &foundProfile = GetProfileByName(profileName)) {
  111. throw std::invalid_argument("Profile already exists: " + profileName);
  112. }
  113. std::string directoryName;
  114. if (!GetFileSafeName(profileName.c_str(), directoryName)) {
  115. throw std::invalid_argument("Failed to create safe directory for new profile: " + profileName);
  116. }
  117. std::string profileDirectory;
  118. profileDirectory.reserve(App()->userProfilesLocation.u8string().size() + OBSProfilePath.size() +
  119. directoryName.size());
  120. profileDirectory.append(App()->userProfilesLocation.u8string()).append(OBSProfilePath).append(directoryName);
  121. if (!GetClosestUnusedFileName(profileDirectory, nullptr)) {
  122. throw std::invalid_argument("Failed to get closest directory name for new profile: " + profileName);
  123. }
  124. const std::filesystem::path profileDirectoryPath = std::filesystem::u8path(profileDirectory);
  125. try {
  126. std::filesystem::create_directory(profileDirectoryPath);
  127. } catch (const std::filesystem::filesystem_error error) {
  128. throw std::logic_error("Failed to create directory for new profile: " + profileDirectory);
  129. }
  130. const std::filesystem::path profileFile =
  131. profileDirectoryPath / std::filesystem::u8path(OBSProfileSettingsFile);
  132. auto [iterator, success] =
  133. profiles.try_emplace(profileName, OBSProfile{profileName, profileDirectoryPath.filename().u8string(),
  134. profileDirectoryPath, profileFile});
  135. OnEvent(OBS_FRONTEND_EVENT_PROFILE_LIST_CHANGED);
  136. return iterator->second;
  137. }
  138. void OBSBasic::RemoveProfile(OBSProfile profile)
  139. {
  140. try {
  141. std::filesystem::remove_all(profile.path);
  142. } catch (const std::filesystem::filesystem_error &error) {
  143. blog(LOG_DEBUG, "%s", error.what());
  144. throw std::logic_error("Failed to remove profile directory: " + profile.directoryName);
  145. }
  146. blog(LOG_INFO, "------------------------------------------------");
  147. blog(LOG_INFO, "Removed profile '%s' (%s)", profile.name.c_str(), profile.directoryName.c_str());
  148. blog(LOG_INFO, "------------------------------------------------");
  149. }
  150. // MARK: - Profile UI Handling Functions
  151. bool OBSBasic::CreateNewProfile(const QString &name)
  152. {
  153. try {
  154. SetupNewProfile(name.toStdString());
  155. return true;
  156. } catch (const std::invalid_argument &error) {
  157. blog(LOG_ERROR, "%s", error.what());
  158. return false;
  159. } catch (const std::logic_error &error) {
  160. blog(LOG_ERROR, "%s", error.what());
  161. return false;
  162. }
  163. }
  164. bool OBSBasic::CreateDuplicateProfile(const QString &name)
  165. {
  166. try {
  167. SetupDuplicateProfile(name.toStdString());
  168. return true;
  169. } catch (const std::invalid_argument &error) {
  170. blog(LOG_ERROR, "%s", error.what());
  171. return false;
  172. } catch (const std::logic_error &error) {
  173. blog(LOG_ERROR, "%s", error.what());
  174. return false;
  175. }
  176. }
  177. void OBSBasic::DeleteProfile(const QString &name)
  178. {
  179. const std::string_view currentProfileName{config_get_string(App()->GetUserConfig(), "Basic", "Profile")};
  180. if (currentProfileName == name.toStdString()) {
  181. on_actionRemoveProfile_triggered();
  182. return;
  183. }
  184. auto foundProfile = GetProfileByName(name.toStdString());
  185. if (!foundProfile) {
  186. blog(LOG_ERROR, "Invalid profile name: %s", QT_TO_UTF8(name));
  187. return;
  188. }
  189. RemoveProfile(foundProfile.value());
  190. profiles.erase(name.toStdString());
  191. RefreshProfiles();
  192. config_save_safe(App()->GetUserConfig(), "tmp", nullptr);
  193. OnEvent(OBS_FRONTEND_EVENT_PROFILE_LIST_CHANGED);
  194. }
  195. void OBSBasic::ChangeProfile()
  196. {
  197. QAction *action = reinterpret_cast<QAction *>(sender());
  198. if (!action) {
  199. return;
  200. }
  201. const std::string_view currentProfileName{config_get_string(App()->GetUserConfig(), "Basic", "Profile")};
  202. const QVariant qProfileName = action->property("profile_name");
  203. const std::string selectedProfileName{qProfileName.toString().toStdString()};
  204. if (currentProfileName == selectedProfileName) {
  205. action->setChecked(true);
  206. return;
  207. }
  208. const std::optional<OBSProfile> foundProfile = GetProfileByName(selectedProfileName);
  209. if (!foundProfile) {
  210. const std::string errorMessage{"Selected profile not found: "};
  211. throw std::invalid_argument(errorMessage + selectedProfileName.data());
  212. }
  213. const OBSProfile &selectedProfile = foundProfile.value();
  214. OnEvent(OBS_FRONTEND_EVENT_PROFILE_CHANGING);
  215. ActivateProfile(selectedProfile, true);
  216. blog(LOG_INFO, "Switched to profile '%s' (%s)", selectedProfile.name.c_str(),
  217. selectedProfile.directoryName.c_str());
  218. blog(LOG_INFO, "------------------------------------------------");
  219. }
  220. void OBSBasic::RefreshProfiles(bool refreshCache)
  221. {
  222. std::string_view currentProfileName{config_get_string(App()->GetUserConfig(), "Basic", "Profile")};
  223. QList<QAction *> menuActions = ui->profileMenu->actions();
  224. for (auto &action : menuActions) {
  225. QVariant variant = action->property("file_name");
  226. if (variant.typeName() != nullptr) {
  227. delete action;
  228. }
  229. }
  230. if (refreshCache) {
  231. RefreshProfileCache();
  232. }
  233. updateSortedProfiles(profiles);
  234. size_t numAddedProfiles = 0;
  235. for (auto &name : sortedProfiles) {
  236. const std::string profileName = name.toStdString();
  237. try {
  238. const OBSProfile &profile = profiles.at(profileName);
  239. const QString qProfileName = QString().fromStdString(profileName);
  240. QAction *action = new QAction(qProfileName, this);
  241. action->setProperty("profile_name", qProfileName);
  242. action->setProperty("file_name", QString().fromStdString(profile.directoryName));
  243. connect(action, &QAction::triggered, this, &OBSBasic::ChangeProfile);
  244. action->setCheckable(true);
  245. action->setChecked(profileName == currentProfileName);
  246. ui->profileMenu->addAction(action);
  247. numAddedProfiles += 1;
  248. } catch (const std::out_of_range &error) {
  249. blog(LOG_ERROR, "No profile with name %s found in profile cache.\n%s", profileName.c_str(),
  250. error.what());
  251. }
  252. }
  253. ui->actionRemoveProfile->setEnabled(numAddedProfiles > 1);
  254. }
  255. // MARK: - Profile Cache Functions
  256. /// Refreshes profile cache data with profile state found on local file system.
  257. void OBSBasic::RefreshProfileCache()
  258. {
  259. std::map<std::string, OBSProfile> foundProfiles{};
  260. const std::filesystem::path profilesPath =
  261. App()->userProfilesLocation / std::filesystem::u8path(OBSProfilePath.substr(1));
  262. const std::filesystem::path profileSettingsFile = std::filesystem::u8path(OBSProfileSettingsFile);
  263. if (!std::filesystem::exists(profilesPath)) {
  264. blog(LOG_WARNING, "Failed to get profiles config path");
  265. return;
  266. }
  267. for (const auto &entry : std::filesystem::directory_iterator(profilesPath)) {
  268. if (!entry.is_directory()) {
  269. continue;
  270. }
  271. const auto profileCandidate = entry.path() / profileSettingsFile;
  272. ConfigFile config;
  273. if (config.Open(profileCandidate.u8string().c_str(), CONFIG_OPEN_EXISTING) != CONFIG_SUCCESS) {
  274. continue;
  275. }
  276. std::string candidateName;
  277. const char *configName = config_get_string(config, "General", "Name");
  278. if (configName) {
  279. candidateName = configName;
  280. } else {
  281. candidateName = entry.path().filename().u8string();
  282. }
  283. foundProfiles.try_emplace(candidateName, OBSProfile{candidateName, entry.path().filename().u8string(),
  284. entry.path(), profileCandidate});
  285. }
  286. profiles.swap(foundProfiles);
  287. }
  288. const OBSProfile &OBSBasic::GetCurrentProfile() const
  289. {
  290. std::string currentProfileName{config_get_string(App()->GetUserConfig(), "Basic", "Profile")};
  291. if (currentProfileName.empty()) {
  292. throw std::invalid_argument("No valid profile name in configuration Basic->Profile");
  293. }
  294. const auto &foundProfile = profiles.find(currentProfileName);
  295. if (foundProfile != profiles.end()) {
  296. return foundProfile->second;
  297. } else {
  298. throw std::invalid_argument("Profile not found in profile list: " + currentProfileName);
  299. }
  300. }
  301. std::optional<OBSProfile> OBSBasic::GetProfileByName(const std::string &profileName) const
  302. {
  303. auto foundProfile = profiles.find(profileName);
  304. if (foundProfile == profiles.end()) {
  305. return {};
  306. } else {
  307. return foundProfile->second;
  308. }
  309. }
  310. std::optional<OBSProfile> OBSBasic::GetProfileByDirectoryName(const std::string &directoryName) const
  311. {
  312. for (auto &[iterator, profile] : profiles) {
  313. if (profile.directoryName == directoryName) {
  314. return profile;
  315. }
  316. }
  317. return {};
  318. }
  319. // MARK: - Qt Slot Functions
  320. void OBSBasic::on_actionNewProfile_triggered()
  321. {
  322. bool useProfileWizard = config_get_bool(App()->GetUserConfig(), "Basic", "ConfigOnNewProfile");
  323. const OBSPromptCallback profilePromptCallback = [this](const OBSPromptResult &result) {
  324. if (GetProfileByName(result.promptValue)) {
  325. return false;
  326. }
  327. return true;
  328. };
  329. const OBSPromptRequest request{Str("AddProfile.Title"), Str("AddProfile.Text"), "", true,
  330. Str("AddProfile.WizardCheckbox"), useProfileWizard};
  331. OBSPromptResult result = PromptForName(request, profilePromptCallback);
  332. if (!result.success) {
  333. return;
  334. }
  335. try {
  336. SetupNewProfile(result.promptValue, result.optionValue);
  337. } catch (const std::invalid_argument &error) {
  338. blog(LOG_ERROR, "%s", error.what());
  339. } catch (const std::logic_error &error) {
  340. blog(LOG_ERROR, "%s", error.what());
  341. }
  342. }
  343. void OBSBasic::on_actionDupProfile_triggered()
  344. {
  345. const OBSPromptCallback profilePromptCallback = [this](const OBSPromptResult &result) {
  346. if (GetProfileByName(result.promptValue)) {
  347. return false;
  348. }
  349. return true;
  350. };
  351. const OBSPromptRequest request{Str("AddProfile.Title"), Str("AddProfile.Text")};
  352. OBSPromptResult result = PromptForName(request, profilePromptCallback);
  353. if (!result.success) {
  354. return;
  355. }
  356. try {
  357. SetupDuplicateProfile(result.promptValue);
  358. } catch (const std::invalid_argument &error) {
  359. blog(LOG_ERROR, "%s", error.what());
  360. } catch (const std::logic_error &error) {
  361. blog(LOG_ERROR, "%s", error.what());
  362. }
  363. }
  364. void OBSBasic::on_actionRenameProfile_triggered()
  365. {
  366. const std::string currentProfileName = config_get_string(App()->GetUserConfig(), "Basic", "Profile");
  367. const OBSPromptCallback profilePromptCallback = [this](const OBSPromptResult &result) {
  368. if (GetProfileByName(result.promptValue)) {
  369. return false;
  370. }
  371. return true;
  372. };
  373. const OBSPromptRequest request{Str("RenameProfile.Title"), Str("AddProfile.Text"), currentProfileName};
  374. OBSPromptResult result = PromptForName(request, profilePromptCallback);
  375. if (!result.success) {
  376. return;
  377. }
  378. try {
  379. SetupRenameProfile(result.promptValue);
  380. } catch (const std::invalid_argument &error) {
  381. blog(LOG_ERROR, "%s", error.what());
  382. } catch (const std::logic_error &error) {
  383. blog(LOG_ERROR, "%s", error.what());
  384. }
  385. }
  386. void OBSBasic::on_actionRemoveProfile_triggered(bool skipConfirmation)
  387. {
  388. if (profiles.size() < 2) {
  389. return;
  390. }
  391. OBSProfile currentProfile;
  392. try {
  393. currentProfile = GetCurrentProfile();
  394. if (!skipConfirmation) {
  395. const QString confirmationText =
  396. QTStr("ConfirmRemove.Text").arg(QString::fromStdString(currentProfile.name));
  397. const QMessageBox::StandardButton button =
  398. OBSMessageBox::question(this, QTStr("ConfirmRemove.Title"), confirmationText);
  399. if (button == QMessageBox::No) {
  400. return;
  401. }
  402. }
  403. OnEvent(OBS_FRONTEND_EVENT_PROFILE_CHANGING);
  404. profiles.erase(currentProfile.name);
  405. } catch (const std::invalid_argument &error) {
  406. blog(LOG_ERROR, "%s", error.what());
  407. } catch (const std::logic_error &error) {
  408. blog(LOG_ERROR, "%s", error.what());
  409. }
  410. const OBSProfile &newProfile = profiles.begin()->second;
  411. ActivateProfile(newProfile, true);
  412. RemoveProfile(currentProfile);
  413. #ifdef YOUTUBE_ENABLED
  414. if (YouTubeAppDock::IsYTServiceSelected() && !youtubeAppDock)
  415. NewYouTubeAppDock();
  416. #endif
  417. blog(LOG_INFO, "Switched to profile '%s' (%s)", newProfile.name.c_str(), newProfile.directoryName.c_str());
  418. blog(LOG_INFO, "------------------------------------------------");
  419. }
  420. void OBSBasic::on_actionImportProfile_triggered()
  421. {
  422. const QString home = QDir::homePath();
  423. const QString sourceDirectory = SelectDirectory(this, QTStr("Basic.MainMenu.Profile.Import"), home);
  424. if (!sourceDirectory.isEmpty() && !sourceDirectory.isNull()) {
  425. const std::filesystem::path sourcePath = std::filesystem::u8path(sourceDirectory.toStdString());
  426. const std::string directoryName = sourcePath.filename().string();
  427. if (auto profile = GetProfileByDirectoryName(directoryName)) {
  428. OBSMessageBox::warning(this, QTStr("Basic.MainMenu.Profile.Import"),
  429. QTStr("Basic.MainMenu.Profile.Exists"));
  430. return;
  431. }
  432. std::string destinationPathString;
  433. destinationPathString.reserve(App()->userProfilesLocation.u8string().size() + OBSProfilePath.size() +
  434. directoryName.size());
  435. destinationPathString.append(App()->userProfilesLocation.u8string())
  436. .append(OBSProfilePath)
  437. .append(directoryName);
  438. const std::filesystem::path destinationPath = std::filesystem::u8path(destinationPathString);
  439. try {
  440. std::filesystem::create_directory(destinationPath);
  441. } catch (const std::filesystem::filesystem_error &error) {
  442. blog(LOG_WARNING, "Failed to create profile directory '%s':\n%s", directoryName.c_str(),
  443. error.what());
  444. return;
  445. }
  446. const std::array<std::pair<std::string, bool>, 4> profileFiles{{
  447. {"basic.ini", true},
  448. {"service.json", false},
  449. {"streamEncoder.json", false},
  450. {"recordEncoder.json", false},
  451. }};
  452. for (auto &[file, isMandatory] : profileFiles) {
  453. const std::filesystem::path sourceFile = sourcePath / std::filesystem::u8path(file);
  454. if (!std::filesystem::exists(sourceFile)) {
  455. if (isMandatory) {
  456. blog(LOG_ERROR,
  457. "Failed to import profile from directory '%s' - necessary file '%s' not found",
  458. directoryName.c_str(), file.c_str());
  459. return;
  460. }
  461. continue;
  462. }
  463. const std::filesystem::path destinationFile = destinationPath / std::filesystem::u8path(file);
  464. try {
  465. std::filesystem::copy(sourceFile, destinationFile);
  466. } catch (const std::filesystem::filesystem_error &error) {
  467. blog(LOG_WARNING, "Failed to copy import file '%s' for profile '%s':\n%s", file.c_str(),
  468. directoryName.c_str(), error.what());
  469. return;
  470. }
  471. }
  472. RefreshProfiles(true);
  473. }
  474. }
  475. void OBSBasic::on_actionExportProfile_triggered()
  476. {
  477. const OBSProfile &currentProfile = GetCurrentProfile();
  478. const QString home = QDir::homePath();
  479. const QString destinationDirectory = SelectDirectory(this, QTStr("Basic.MainMenu.Profile.Export"), home);
  480. const std::array<std::string, 4> profileFiles{"basic.ini", "service.json", "streamEncoder.json",
  481. "recordEncoder.json"};
  482. if (!destinationDirectory.isEmpty() && !destinationDirectory.isNull()) {
  483. const std::filesystem::path sourcePath = currentProfile.path;
  484. const std::filesystem::path destinationPath =
  485. std::filesystem::u8path(destinationDirectory.toStdString()) /
  486. std::filesystem::u8path(currentProfile.directoryName);
  487. if (!std::filesystem::exists(destinationPath)) {
  488. std::filesystem::create_directory(destinationPath);
  489. }
  490. std::filesystem::copy_options copyOptions = std::filesystem::copy_options::overwrite_existing;
  491. for (auto &file : profileFiles) {
  492. const std::filesystem::path sourceFile = sourcePath / std::filesystem::u8path(file);
  493. if (!std::filesystem::exists(sourceFile)) {
  494. continue;
  495. }
  496. const std::filesystem::path destinationFile = destinationPath / std::filesystem::u8path(file);
  497. try {
  498. std::filesystem::copy(sourceFile, destinationFile, copyOptions);
  499. } catch (const std::filesystem::filesystem_error &error) {
  500. blog(LOG_WARNING, "Failed to copy export file '%s' for profile '%s'\n%s", file.c_str(),
  501. currentProfile.name.c_str(), error.what());
  502. return;
  503. }
  504. }
  505. }
  506. }
  507. // MARK: - Profile Management Helper Functions
  508. void OBSBasic::ActivateProfile(const OBSProfile &profile, bool reset)
  509. {
  510. ConfigFile config;
  511. if (config.Open(profile.profileFile.u8string().c_str(), CONFIG_OPEN_ALWAYS) != CONFIG_SUCCESS) {
  512. throw std::logic_error("failed to open configuration file of new profile: " +
  513. profile.profileFile.string());
  514. }
  515. config_set_string(config, "General", "Name", profile.name.c_str());
  516. config.SaveSafe("tmp");
  517. std::vector<std::string> restartRequirements;
  518. if (activeConfiguration) {
  519. Auth::Save();
  520. if (reset) {
  521. auth.reset();
  522. DestroyPanelCookieManager();
  523. #ifdef YOUTUBE_ENABLED
  524. if (youtubeAppDock) {
  525. DeleteYouTubeAppDock();
  526. }
  527. #endif
  528. }
  529. restartRequirements = GetRestartRequirements(config);
  530. activeConfiguration.SaveSafe("tmp");
  531. }
  532. activeConfiguration.Swap(config);
  533. config_set_string(App()->GetUserConfig(), "Basic", "Profile", profile.name.c_str());
  534. config_set_string(App()->GetUserConfig(), "Basic", "ProfileDir", profile.directoryName.c_str());
  535. config_save_safe(App()->GetUserConfig(), "tmp", nullptr);
  536. InitBasicConfigDefaults();
  537. InitBasicConfigDefaults2();
  538. if (reset) {
  539. ResetProfileData();
  540. }
  541. CheckForSimpleModeX264Fallback();
  542. RefreshProfiles();
  543. UpdateTitleBar();
  544. UpdateVolumeControlsDecayRate();
  545. Auth::Load();
  546. OnEvent(OBS_FRONTEND_EVENT_PROFILE_CHANGED);
  547. if (!restartRequirements.empty()) {
  548. std::string requirements = std::accumulate(
  549. std::next(restartRequirements.begin()), restartRequirements.end(), restartRequirements[0],
  550. [](std::string a, std::string b) { return std::move(a) + "\n" + b; });
  551. QMessageBox::StandardButton button = OBSMessageBox::question(
  552. this, QTStr("Restart"), QTStr("LoadProfileNeedsRestart").arg(requirements.c_str()));
  553. if (button == QMessageBox::Yes) {
  554. restart = true;
  555. close();
  556. }
  557. }
  558. }
  559. void OBSBasic::ResetProfileData()
  560. {
  561. ResetVideo();
  562. service = nullptr;
  563. InitService();
  564. ResetOutputs();
  565. ClearHotkeys();
  566. CreateHotkeys();
  567. /* load audio monitoring */
  568. if (obs_audio_monitoring_available()) {
  569. const char *device_name = config_get_string(activeConfiguration, "Audio", "MonitoringDeviceName");
  570. const char *device_id = config_get_string(activeConfiguration, "Audio", "MonitoringDeviceId");
  571. obs_set_audio_monitoring_device(device_name, device_id);
  572. blog(LOG_INFO, "Audio monitoring device:\n\tname: %s\n\tid: %s", device_name, device_id);
  573. }
  574. }
  575. std::vector<std::string> OBSBasic::GetRestartRequirements(const ConfigFile &config) const
  576. {
  577. std::vector<std::string> result;
  578. const char *oldSpeakers = config_get_string(activeConfiguration, "Audio", "ChannelSetup");
  579. const char *newSpeakers = config_get_string(config, "Audio", "ChannelSetup");
  580. uint64_t oldSampleRate = config_get_uint(activeConfiguration, "Audio", "SampleRate");
  581. uint64_t newSampleRate = config_get_uint(config, "Audio", "SampleRate");
  582. if (oldSpeakers != NULL && newSpeakers != NULL) {
  583. if (std::string_view{oldSpeakers} != std::string_view{newSpeakers}) {
  584. result.emplace_back(Str("Basic.Settings.Audio.Channels"));
  585. }
  586. }
  587. if (oldSampleRate != 0 && newSampleRate != 0) {
  588. if (oldSampleRate != newSampleRate) {
  589. result.emplace_back(Str("Basic.Settings.Audio.SampleRate"));
  590. }
  591. }
  592. return result;
  593. }
  594. void OBSBasic::CheckForSimpleModeX264Fallback()
  595. {
  596. const char *curStreamEncoder = config_get_string(activeConfiguration, "SimpleOutput", "StreamEncoder");
  597. const char *curRecEncoder = config_get_string(activeConfiguration, "SimpleOutput", "RecEncoder");
  598. bool qsv_supported = false;
  599. bool qsv_av1_supported = false;
  600. bool amd_supported = false;
  601. bool nve_supported = false;
  602. #ifdef ENABLE_HEVC
  603. bool amd_hevc_supported = false;
  604. bool nve_hevc_supported = false;
  605. bool apple_hevc_supported = false;
  606. #endif
  607. bool amd_av1_supported = false;
  608. bool apple_supported = false;
  609. bool changed = false;
  610. size_t idx = 0;
  611. const char *id;
  612. while (obs_enum_encoder_types(idx++, &id)) {
  613. if (strcmp(id, "h264_texture_amf") == 0)
  614. amd_supported = true;
  615. else if (strcmp(id, "obs_qsv11") == 0)
  616. qsv_supported = true;
  617. else if (strcmp(id, "obs_qsv11_av1") == 0)
  618. qsv_av1_supported = true;
  619. else if (strcmp(id, "ffmpeg_nvenc") == 0)
  620. nve_supported = true;
  621. #ifdef ENABLE_HEVC
  622. else if (strcmp(id, "h265_texture_amf") == 0)
  623. amd_hevc_supported = true;
  624. else if (strcmp(id, "ffmpeg_hevc_nvenc") == 0)
  625. nve_hevc_supported = true;
  626. #endif
  627. else if (strcmp(id, "av1_texture_amf") == 0)
  628. amd_av1_supported = true;
  629. else if (strcmp(id, "com.apple.videotoolbox.videoencoder.ave.avc") == 0)
  630. apple_supported = true;
  631. #ifdef ENABLE_HEVC
  632. else if (strcmp(id, "com.apple.videotoolbox.videoencoder.ave.hevc") == 0)
  633. apple_hevc_supported = true;
  634. #endif
  635. }
  636. auto CheckEncoder = [&](const char *&name) {
  637. if (strcmp(name, SIMPLE_ENCODER_QSV) == 0) {
  638. if (!qsv_supported) {
  639. changed = true;
  640. name = SIMPLE_ENCODER_X264;
  641. return false;
  642. }
  643. } else if (strcmp(name, SIMPLE_ENCODER_QSV_AV1) == 0) {
  644. if (!qsv_av1_supported) {
  645. changed = true;
  646. name = SIMPLE_ENCODER_X264;
  647. return false;
  648. }
  649. } else if (strcmp(name, SIMPLE_ENCODER_NVENC) == 0) {
  650. if (!nve_supported) {
  651. changed = true;
  652. name = SIMPLE_ENCODER_X264;
  653. return false;
  654. }
  655. } else if (strcmp(name, SIMPLE_ENCODER_NVENC_AV1) == 0) {
  656. if (!nve_supported) {
  657. changed = true;
  658. name = SIMPLE_ENCODER_X264;
  659. return false;
  660. }
  661. #ifdef ENABLE_HEVC
  662. } else if (strcmp(name, SIMPLE_ENCODER_AMD_HEVC) == 0) {
  663. if (!amd_hevc_supported) {
  664. changed = true;
  665. name = SIMPLE_ENCODER_X264;
  666. return false;
  667. }
  668. } else if (strcmp(name, SIMPLE_ENCODER_NVENC_HEVC) == 0) {
  669. if (!nve_hevc_supported) {
  670. changed = true;
  671. name = SIMPLE_ENCODER_X264;
  672. return false;
  673. }
  674. #endif
  675. } else if (strcmp(name, SIMPLE_ENCODER_AMD) == 0) {
  676. if (!amd_supported) {
  677. changed = true;
  678. name = SIMPLE_ENCODER_X264;
  679. return false;
  680. }
  681. } else if (strcmp(name, SIMPLE_ENCODER_AMD_AV1) == 0) {
  682. if (!amd_av1_supported) {
  683. changed = true;
  684. name = SIMPLE_ENCODER_X264;
  685. return false;
  686. }
  687. } else if (strcmp(name, SIMPLE_ENCODER_APPLE_H264) == 0) {
  688. if (!apple_supported) {
  689. changed = true;
  690. name = SIMPLE_ENCODER_X264;
  691. return false;
  692. }
  693. #ifdef ENABLE_HEVC
  694. } else if (strcmp(name, SIMPLE_ENCODER_APPLE_HEVC) == 0) {
  695. if (!apple_hevc_supported) {
  696. changed = true;
  697. name = SIMPLE_ENCODER_X264;
  698. return false;
  699. }
  700. #endif
  701. }
  702. return true;
  703. };
  704. if (!CheckEncoder(curStreamEncoder))
  705. config_set_string(activeConfiguration, "SimpleOutput", "StreamEncoder", curStreamEncoder);
  706. if (!CheckEncoder(curRecEncoder))
  707. config_set_string(activeConfiguration, "SimpleOutput", "RecEncoder", curRecEncoder);
  708. if (changed) {
  709. activeConfiguration.SaveSafe("tmp");
  710. }
  711. }