auto-scene-switcher.cpp 11 KB

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