1
0

auto-scene-switcher.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. #include <obs-frontend-api.h>
  2. #include <obs-module.h>
  3. #include <obs.hpp>
  4. #include <util/util.hpp>
  5. #include <QMainWindow>
  6. #include <QMessageBox>
  7. #include <QAction>
  8. #include "auto-scene-switcher.hpp"
  9. #include "tool-helpers.hpp"
  10. #include <condition_variable>
  11. #include <chrono>
  12. #include <string>
  13. #include <vector>
  14. #include <thread>
  15. #include <regex>
  16. #include <mutex>
  17. using namespace std;
  18. #define DEFAULT_INTERVAL 300
  19. struct SceneSwitch {
  20. OBSWeakSource scene;
  21. string window;
  22. regex re;
  23. inline SceneSwitch(OBSWeakSource scene_, const char *window_) : scene(scene_), window(window_), re(window_) {}
  24. };
  25. static inline bool WeakSourceValid(obs_weak_source_t *ws)
  26. {
  27. OBSSourceAutoRelease source = obs_weak_source_get_source(ws);
  28. return !!source;
  29. }
  30. struct SwitcherData {
  31. thread th;
  32. condition_variable cv;
  33. mutex m;
  34. bool stop = false;
  35. vector<SceneSwitch> switches;
  36. OBSWeakSource nonMatchingScene;
  37. int interval = DEFAULT_INTERVAL;
  38. bool switchIfNotMatching = false;
  39. void Thread();
  40. void Start();
  41. void Stop();
  42. void Prune()
  43. {
  44. for (size_t i = 0; i < switches.size(); i++) {
  45. SceneSwitch &s = switches[i];
  46. if (!WeakSourceValid(s.scene))
  47. switches.erase(switches.begin() + i--);
  48. }
  49. if (nonMatchingScene && !WeakSourceValid(nonMatchingScene)) {
  50. switchIfNotMatching = false;
  51. nonMatchingScene = nullptr;
  52. }
  53. }
  54. inline ~SwitcherData() { Stop(); }
  55. };
  56. static SwitcherData *switcher = nullptr;
  57. static inline QString MakeSwitchName(const QString &scene, const QString &window)
  58. {
  59. return QStringLiteral("[") + scene + QStringLiteral("]: ") + window;
  60. }
  61. SceneSwitcher::SceneSwitcher(QWidget *parent) : QDialog(parent), ui(new Ui_SceneSwitcher)
  62. {
  63. ui->setupUi(this);
  64. setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
  65. lock_guard<mutex> lock(switcher->m);
  66. switcher->Prune();
  67. BPtr<char *> scenes = obs_frontend_get_scene_names();
  68. char **temp = scenes;
  69. while (*temp) {
  70. const char *name = *temp;
  71. ui->scenes->addItem(name);
  72. ui->noMatchSwitchScene->addItem(name);
  73. temp++;
  74. }
  75. if (switcher->switchIfNotMatching)
  76. ui->noMatchSwitch->setChecked(true);
  77. else
  78. ui->noMatchDontSwitch->setChecked(true);
  79. ui->noMatchSwitchScene->setCurrentText(GetWeakSourceName(switcher->nonMatchingScene).c_str());
  80. ui->checkInterval->setValue(switcher->interval);
  81. vector<string> windows;
  82. GetWindowList(windows);
  83. for (string &window : windows)
  84. ui->windows->addItem(window.c_str());
  85. for (auto &s : switcher->switches) {
  86. string sceneName = GetWeakSourceName(s.scene);
  87. QString text = MakeSwitchName(sceneName.c_str(), s.window.c_str());
  88. QListWidgetItem *item = new QListWidgetItem(text, ui->switches);
  89. item->setData(Qt::UserRole, s.window.c_str());
  90. }
  91. if (switcher->th.joinable())
  92. SetStarted();
  93. else
  94. SetStopped();
  95. loading = false;
  96. connect(this, &QDialog::finished, this, &SceneSwitcher::finished);
  97. }
  98. void SceneSwitcher::finished()
  99. {
  100. obs_frontend_save();
  101. }
  102. int SceneSwitcher::FindByData(const QString &window)
  103. {
  104. int count = ui->switches->count();
  105. int idx = -1;
  106. for (int i = 0; i < count; i++) {
  107. QListWidgetItem *item = ui->switches->item(i);
  108. QString itemWindow = item->data(Qt::UserRole).toString();
  109. if (itemWindow == window) {
  110. idx = i;
  111. break;
  112. }
  113. }
  114. return idx;
  115. }
  116. void SceneSwitcher::on_switches_currentRowChanged(int idx)
  117. {
  118. if (loading)
  119. return;
  120. if (idx == -1)
  121. return;
  122. QListWidgetItem *item = ui->switches->item(idx);
  123. QString window = item->data(Qt::UserRole).toString();
  124. lock_guard<mutex> lock(switcher->m);
  125. for (auto &s : switcher->switches) {
  126. if (window.compare(s.window.c_str()) == 0) {
  127. string name = GetWeakSourceName(s.scene);
  128. ui->scenes->setCurrentText(name.c_str());
  129. ui->windows->setCurrentText(window);
  130. break;
  131. }
  132. }
  133. }
  134. void SceneSwitcher::on_close_clicked()
  135. {
  136. done(0);
  137. }
  138. void SceneSwitcher::on_add_clicked()
  139. {
  140. QString sceneName = ui->scenes->currentText();
  141. QString windowName = ui->windows->currentText();
  142. if (windowName.isEmpty())
  143. return;
  144. OBSWeakSource source = GetWeakSourceByQString(sceneName);
  145. QVariant v = QVariant::fromValue(windowName);
  146. QString text = MakeSwitchName(sceneName, windowName);
  147. int idx = FindByData(windowName);
  148. if (idx == -1) {
  149. try {
  150. lock_guard<mutex> lock(switcher->m);
  151. switcher->switches.emplace_back(source, windowName.toUtf8().constData());
  152. QListWidgetItem *item = new QListWidgetItem(text, ui->switches);
  153. item->setData(Qt::UserRole, v);
  154. } catch (const regex_error &) {
  155. QMessageBox::warning(this, obs_module_text("InvalidRegex.Title"),
  156. obs_module_text("InvalidRegex.Text"));
  157. }
  158. } else {
  159. QListWidgetItem *item = ui->switches->item(idx);
  160. item->setText(text);
  161. string window = windowName.toUtf8().constData();
  162. {
  163. lock_guard<mutex> lock(switcher->m);
  164. for (auto &s : switcher->switches) {
  165. if (s.window == window) {
  166. s.scene = source;
  167. break;
  168. }
  169. }
  170. }
  171. ui->switches->sortItems();
  172. }
  173. }
  174. void SceneSwitcher::on_remove_clicked()
  175. {
  176. QListWidgetItem *item = ui->switches->currentItem();
  177. if (!item)
  178. return;
  179. string window = item->data(Qt::UserRole).toString().toUtf8().constData();
  180. {
  181. lock_guard<mutex> lock(switcher->m);
  182. auto &switches = switcher->switches;
  183. for (auto it = switches.begin(); it != switches.end(); ++it) {
  184. auto &s = *it;
  185. if (s.window == window) {
  186. switches.erase(it);
  187. break;
  188. }
  189. }
  190. }
  191. delete item;
  192. }
  193. void SceneSwitcher::UpdateNonMatchingScene(const QString &name)
  194. {
  195. OBSSourceAutoRelease scene = obs_get_source_by_name(name.toUtf8().constData());
  196. OBSWeakSourceAutoRelease ws = obs_source_get_weak_source(scene);
  197. switcher->nonMatchingScene = ws.Get();
  198. }
  199. void SceneSwitcher::on_noMatchDontSwitch_clicked()
  200. {
  201. if (loading)
  202. return;
  203. lock_guard<mutex> lock(switcher->m);
  204. switcher->switchIfNotMatching = false;
  205. }
  206. void SceneSwitcher::on_noMatchSwitch_clicked()
  207. {
  208. if (loading)
  209. return;
  210. lock_guard<mutex> lock(switcher->m);
  211. switcher->switchIfNotMatching = true;
  212. UpdateNonMatchingScene(ui->noMatchSwitchScene->currentText());
  213. }
  214. void SceneSwitcher::on_noMatchSwitchScene_currentTextChanged(const QString &text)
  215. {
  216. if (loading)
  217. return;
  218. lock_guard<mutex> lock(switcher->m);
  219. UpdateNonMatchingScene(text);
  220. }
  221. void SceneSwitcher::on_checkInterval_valueChanged(int value)
  222. {
  223. if (loading)
  224. return;
  225. lock_guard<mutex> lock(switcher->m);
  226. switcher->interval = value;
  227. }
  228. void SceneSwitcher::SetStarted()
  229. {
  230. ui->toggleStartButton->setText(obs_module_text("Stop"));
  231. ui->pluginRunningText->setText(obs_module_text("Active"));
  232. }
  233. void SceneSwitcher::SetStopped()
  234. {
  235. ui->toggleStartButton->setText(obs_module_text("Start"));
  236. ui->pluginRunningText->setText(obs_module_text("Inactive"));
  237. }
  238. void SceneSwitcher::on_toggleStartButton_clicked()
  239. {
  240. if (switcher->th.joinable()) {
  241. switcher->Stop();
  242. SetStopped();
  243. } else {
  244. switcher->Start();
  245. SetStarted();
  246. }
  247. }
  248. static void SaveSceneSwitcher(obs_data_t *save_data, bool saving, void *)
  249. {
  250. if (saving) {
  251. lock_guard<mutex> lock(switcher->m);
  252. OBSDataAutoRelease obj = obs_data_create();
  253. OBSDataArrayAutoRelease array = obs_data_array_create();
  254. switcher->Prune();
  255. for (SceneSwitch &s : switcher->switches) {
  256. OBSDataAutoRelease array_obj = obs_data_create();
  257. OBSSourceAutoRelease source = obs_weak_source_get_source(s.scene);
  258. if (source) {
  259. const char *n = obs_source_get_name(source);
  260. obs_data_set_string(array_obj, "scene", n);
  261. obs_data_set_string(array_obj, "window_title", s.window.c_str());
  262. obs_data_array_push_back(array, array_obj);
  263. }
  264. }
  265. string nonMatchingSceneName = GetWeakSourceName(switcher->nonMatchingScene);
  266. obs_data_set_int(obj, "interval", switcher->interval);
  267. obs_data_set_string(obj, "non_matching_scene", nonMatchingSceneName.c_str());
  268. obs_data_set_bool(obj, "switch_if_not_matching", switcher->switchIfNotMatching);
  269. obs_data_set_bool(obj, "active", switcher->th.joinable());
  270. obs_data_set_array(obj, "switches", array);
  271. obs_data_set_obj(save_data, "auto-scene-switcher", obj);
  272. } else {
  273. switcher->m.lock();
  274. OBSDataAutoRelease obj = obs_data_get_obj(save_data, "auto-scene-switcher");
  275. OBSDataArrayAutoRelease array = obs_data_get_array(obj, "switches");
  276. size_t count = obs_data_array_count(array);
  277. if (!obj)
  278. obj = obs_data_create();
  279. obs_data_set_default_int(obj, "interval", DEFAULT_INTERVAL);
  280. switcher->interval = obs_data_get_int(obj, "interval");
  281. switcher->switchIfNotMatching = obs_data_get_bool(obj, "switch_if_not_matching");
  282. string nonMatchingScene = obs_data_get_string(obj, "non_matching_scene");
  283. bool active = obs_data_get_bool(obj, "active");
  284. switcher->nonMatchingScene = GetWeakSourceByName(nonMatchingScene.c_str());
  285. switcher->switches.clear();
  286. for (size_t i = 0; i < count; i++) {
  287. OBSDataAutoRelease array_obj = obs_data_array_item(array, i);
  288. const char *scene = obs_data_get_string(array_obj, "scene");
  289. const char *window = obs_data_get_string(array_obj, "window_title");
  290. switcher->switches.emplace_back(GetWeakSourceByName(scene), window);
  291. }
  292. switcher->m.unlock();
  293. if (active)
  294. switcher->Start();
  295. else
  296. switcher->Stop();
  297. }
  298. }
  299. void SwitcherData::Thread()
  300. {
  301. chrono::duration<long long, milli> duration = chrono::milliseconds(interval);
  302. string lastTitle;
  303. string title;
  304. for (;;) {
  305. unique_lock<mutex> lock(m);
  306. OBSWeakSource scene;
  307. bool match = false;
  308. cv.wait_for(lock, duration);
  309. if (switcher->stop) {
  310. switcher->stop = false;
  311. break;
  312. }
  313. duration = chrono::milliseconds(interval);
  314. GetCurrentWindowTitle(title);
  315. if (lastTitle != title) {
  316. switcher->Prune();
  317. for (SceneSwitch &s : switches) {
  318. if (s.window == title) {
  319. match = true;
  320. scene = s.scene;
  321. break;
  322. }
  323. }
  324. /* try regex */
  325. if (!match) {
  326. for (SceneSwitch &s : switches) {
  327. try {
  328. bool matches = regex_match(title, s.re);
  329. if (matches) {
  330. match = true;
  331. scene = s.scene;
  332. break;
  333. }
  334. } catch (const regex_error &) {
  335. }
  336. }
  337. }
  338. if (!match && switchIfNotMatching && nonMatchingScene) {
  339. match = true;
  340. scene = nonMatchingScene;
  341. }
  342. if (match) {
  343. OBSSourceAutoRelease source = obs_weak_source_get_source(scene);
  344. OBSSourceAutoRelease currentSource = obs_frontend_get_current_scene();
  345. if (source && source != currentSource)
  346. obs_frontend_set_current_scene(source);
  347. }
  348. }
  349. lastTitle = title;
  350. }
  351. }
  352. void SwitcherData::Start()
  353. {
  354. if (!switcher->th.joinable())
  355. switcher->th = thread([]() { switcher->Thread(); });
  356. }
  357. void SwitcherData::Stop()
  358. {
  359. if (th.joinable()) {
  360. {
  361. lock_guard<mutex> lock(m);
  362. stop = true;
  363. }
  364. cv.notify_one();
  365. th.join();
  366. }
  367. }
  368. extern "C" void FreeSceneSwitcher()
  369. {
  370. CleanupSceneSwitcher();
  371. delete switcher;
  372. switcher = nullptr;
  373. }
  374. static void OBSEvent(enum obs_frontend_event event, void *)
  375. {
  376. if (event == OBS_FRONTEND_EVENT_EXIT)
  377. FreeSceneSwitcher();
  378. }
  379. extern "C" void InitSceneSwitcher()
  380. {
  381. #if !defined(__APPLE__) && !defined(_WIN32)
  382. if (QApplication::platformName().contains("wayland"))
  383. return;
  384. #endif
  385. QAction *action = (QAction *)obs_frontend_add_tools_menu_qaction(obs_module_text("SceneSwitcher"));
  386. switcher = new SwitcherData;
  387. auto cb = []() {
  388. obs_frontend_push_ui_translation(obs_module_get_string);
  389. QMainWindow *window = (QMainWindow *)obs_frontend_get_main_window();
  390. SceneSwitcher ss(window);
  391. ss.exec();
  392. obs_frontend_pop_ui_translation();
  393. };
  394. obs_frontend_add_save_callback(SaveSceneSwitcher, nullptr);
  395. obs_frontend_add_event_callback(OBSEvent, nullptr);
  396. action->connect(action, &QAction::triggered, cb);
  397. }