configure_touch_from_button.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. // Copyright 2020 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <QInputDialog>
  5. #include <QKeyEvent>
  6. #include <QMessageBox>
  7. #include <QMouseEvent>
  8. #include <QResizeEvent>
  9. #include <QStandardItemModel>
  10. #include <QTimer>
  11. #include "common/param_package.h"
  12. #include "common/settings.h"
  13. #include "core/frontend/framebuffer_layout.h"
  14. #include "input_common/main.h"
  15. #include "ui_configure_touch_from_button.h"
  16. #include "yuzu/configuration/configure_touch_from_button.h"
  17. #include "yuzu/configuration/configure_touch_widget.h"
  18. static QString GetKeyName(int key_code) {
  19. switch (key_code) {
  20. case Qt::Key_Shift:
  21. return QObject::tr("Shift");
  22. case Qt::Key_Control:
  23. return QObject::tr("Ctrl");
  24. case Qt::Key_Alt:
  25. return QObject::tr("Alt");
  26. case Qt::Key_Meta:
  27. return QString{};
  28. default:
  29. return QKeySequence(key_code).toString();
  30. }
  31. }
  32. static QString ButtonToText(const Common::ParamPackage& param) {
  33. if (!param.Has("engine")) {
  34. return QObject::tr("[not set]");
  35. }
  36. if (param.Get("engine", "") == "keyboard") {
  37. return GetKeyName(param.Get("code", 0));
  38. }
  39. if (param.Get("engine", "") == "sdl") {
  40. if (param.Has("hat")) {
  41. const QString hat_str = QString::fromStdString(param.Get("hat", ""));
  42. const QString direction_str = QString::fromStdString(param.Get("direction", ""));
  43. return QObject::tr("Hat %1 %2").arg(hat_str, direction_str);
  44. }
  45. if (param.Has("axis")) {
  46. const QString axis_str = QString::fromStdString(param.Get("axis", ""));
  47. const QString direction_str = QString::fromStdString(param.Get("direction", ""));
  48. return QObject::tr("Axis %1%2").arg(axis_str, direction_str);
  49. }
  50. if (param.Has("button")) {
  51. const QString button_str = QString::fromStdString(param.Get("button", ""));
  52. return QObject::tr("Button %1").arg(button_str);
  53. }
  54. return {};
  55. }
  56. return QObject::tr("[unknown]");
  57. }
  58. ConfigureTouchFromButton::ConfigureTouchFromButton(
  59. QWidget* parent, const std::vector<Settings::TouchFromButtonMap>& touch_maps,
  60. InputCommon::InputSubsystem* input_subsystem_, const int default_index)
  61. : QDialog(parent), ui(std::make_unique<Ui::ConfigureTouchFromButton>()),
  62. touch_maps(touch_maps), input_subsystem{input_subsystem_}, selected_index(default_index),
  63. timeout_timer(std::make_unique<QTimer>()), poll_timer(std::make_unique<QTimer>()) {
  64. ui->setupUi(this);
  65. binding_list_model = new QStandardItemModel(0, 3, this);
  66. binding_list_model->setHorizontalHeaderLabels(
  67. {tr("Button"), tr("X", "X axis"), tr("Y", "Y axis")});
  68. ui->binding_list->setModel(binding_list_model);
  69. ui->bottom_screen->SetCoordLabel(ui->coord_label);
  70. SetConfiguration();
  71. UpdateUiDisplay();
  72. ConnectEvents();
  73. }
  74. ConfigureTouchFromButton::~ConfigureTouchFromButton() = default;
  75. void ConfigureTouchFromButton::showEvent(QShowEvent* ev) {
  76. QWidget::showEvent(ev);
  77. // width values are not valid in the constructor
  78. const int w =
  79. ui->binding_list->viewport()->contentsRect().width() / binding_list_model->columnCount();
  80. if (w <= 0) {
  81. return;
  82. }
  83. ui->binding_list->setColumnWidth(0, w);
  84. ui->binding_list->setColumnWidth(1, w);
  85. ui->binding_list->setColumnWidth(2, w);
  86. }
  87. void ConfigureTouchFromButton::SetConfiguration() {
  88. for (const auto& touch_map : touch_maps) {
  89. ui->mapping->addItem(QString::fromStdString(touch_map.name));
  90. }
  91. ui->mapping->setCurrentIndex(selected_index);
  92. }
  93. void ConfigureTouchFromButton::UpdateUiDisplay() {
  94. ui->button_delete->setEnabled(touch_maps.size() > 1);
  95. ui->button_delete_bind->setEnabled(false);
  96. binding_list_model->removeRows(0, binding_list_model->rowCount());
  97. for (const auto& button_str : touch_maps[selected_index].buttons) {
  98. Common::ParamPackage package{button_str};
  99. QStandardItem* button = new QStandardItem(ButtonToText(package));
  100. button->setData(QString::fromStdString(button_str));
  101. button->setEditable(false);
  102. QStandardItem* xcoord = new QStandardItem(QString::number(package.Get("x", 0)));
  103. QStandardItem* ycoord = new QStandardItem(QString::number(package.Get("y", 0)));
  104. binding_list_model->appendRow({button, xcoord, ycoord});
  105. const int dot = ui->bottom_screen->AddDot(package.Get("x", 0), package.Get("y", 0));
  106. button->setData(dot, DataRoleDot);
  107. }
  108. }
  109. void ConfigureTouchFromButton::ConnectEvents() {
  110. connect(ui->mapping, qOverload<int>(&QComboBox::currentIndexChanged), this, [this](int index) {
  111. SaveCurrentMapping();
  112. selected_index = index;
  113. UpdateUiDisplay();
  114. });
  115. connect(ui->button_new, &QPushButton::clicked, this, &ConfigureTouchFromButton::NewMapping);
  116. connect(ui->button_delete, &QPushButton::clicked, this,
  117. &ConfigureTouchFromButton::DeleteMapping);
  118. connect(ui->button_rename, &QPushButton::clicked, this,
  119. &ConfigureTouchFromButton::RenameMapping);
  120. connect(ui->button_delete_bind, &QPushButton::clicked, this,
  121. &ConfigureTouchFromButton::DeleteBinding);
  122. connect(ui->binding_list, &QTreeView::doubleClicked, this,
  123. &ConfigureTouchFromButton::EditBinding);
  124. connect(ui->binding_list->selectionModel(), &QItemSelectionModel::selectionChanged, this,
  125. &ConfigureTouchFromButton::OnBindingSelection);
  126. connect(binding_list_model, &QStandardItemModel::itemChanged, this,
  127. &ConfigureTouchFromButton::OnBindingChanged);
  128. connect(ui->binding_list->model(), &QStandardItemModel::rowsAboutToBeRemoved, this,
  129. &ConfigureTouchFromButton::OnBindingDeleted);
  130. connect(ui->bottom_screen, &TouchScreenPreview::DotAdded, this,
  131. &ConfigureTouchFromButton::NewBinding);
  132. connect(ui->bottom_screen, &TouchScreenPreview::DotSelected, this,
  133. &ConfigureTouchFromButton::SetActiveBinding);
  134. connect(ui->bottom_screen, &TouchScreenPreview::DotMoved, this,
  135. &ConfigureTouchFromButton::SetCoordinates);
  136. connect(ui->buttonBox, &QDialogButtonBox::accepted, this,
  137. &ConfigureTouchFromButton::ApplyConfiguration);
  138. connect(timeout_timer.get(), &QTimer::timeout, [this]() { SetPollingResult({}, true); });
  139. connect(poll_timer.get(), &QTimer::timeout, [this]() {
  140. Common::ParamPackage params;
  141. for (auto& poller : device_pollers) {
  142. params = poller->GetNextInput();
  143. if (params.Has("engine")) {
  144. SetPollingResult(params, false);
  145. return;
  146. }
  147. }
  148. });
  149. }
  150. void ConfigureTouchFromButton::SaveCurrentMapping() {
  151. auto& map = touch_maps[selected_index];
  152. map.buttons.clear();
  153. for (int i = 0, rc = binding_list_model->rowCount(); i < rc; ++i) {
  154. const auto bind_str = binding_list_model->index(i, 0)
  155. .data(Qt::ItemDataRole::UserRole + 1)
  156. .toString()
  157. .toStdString();
  158. if (bind_str.empty()) {
  159. continue;
  160. }
  161. Common::ParamPackage params{bind_str};
  162. if (!params.Has("engine")) {
  163. continue;
  164. }
  165. params.Set("x", binding_list_model->index(i, 1).data().toInt());
  166. params.Set("y", binding_list_model->index(i, 2).data().toInt());
  167. map.buttons.emplace_back(params.Serialize());
  168. }
  169. }
  170. void ConfigureTouchFromButton::NewMapping() {
  171. const QString name =
  172. QInputDialog::getText(this, tr("New Profile"), tr("Enter the name for the new profile."));
  173. if (name.isEmpty()) {
  174. return;
  175. }
  176. touch_maps.emplace_back(Settings::TouchFromButtonMap{name.toStdString(), {}});
  177. ui->mapping->addItem(name);
  178. ui->mapping->setCurrentIndex(ui->mapping->count() - 1);
  179. }
  180. void ConfigureTouchFromButton::DeleteMapping() {
  181. const auto answer = QMessageBox::question(
  182. this, tr("Delete Profile"), tr("Delete profile %1?").arg(ui->mapping->currentText()));
  183. if (answer != QMessageBox::Yes) {
  184. return;
  185. }
  186. const bool blocked = ui->mapping->blockSignals(true);
  187. ui->mapping->removeItem(selected_index);
  188. ui->mapping->blockSignals(blocked);
  189. touch_maps.erase(touch_maps.begin() + selected_index);
  190. selected_index = ui->mapping->currentIndex();
  191. UpdateUiDisplay();
  192. }
  193. void ConfigureTouchFromButton::RenameMapping() {
  194. const QString new_name = QInputDialog::getText(this, tr("Rename Profile"), tr("New name:"));
  195. if (new_name.isEmpty()) {
  196. return;
  197. }
  198. ui->mapping->setItemText(selected_index, new_name);
  199. touch_maps[selected_index].name = new_name.toStdString();
  200. }
  201. void ConfigureTouchFromButton::GetButtonInput(const int row_index, const bool is_new) {
  202. binding_list_model->item(row_index, 0)->setText(tr("[press key]"));
  203. input_setter = [this, row_index, is_new](const Common::ParamPackage& params,
  204. const bool cancel) {
  205. auto* cell = binding_list_model->item(row_index, 0);
  206. if (cancel) {
  207. if (is_new) {
  208. binding_list_model->removeRow(row_index);
  209. } else {
  210. cell->setText(
  211. ButtonToText(Common::ParamPackage{cell->data().toString().toStdString()}));
  212. }
  213. } else {
  214. cell->setText(ButtonToText(params));
  215. cell->setData(QString::fromStdString(params.Serialize()));
  216. }
  217. };
  218. device_pollers = input_subsystem->GetPollers(InputCommon::Polling::DeviceType::Button);
  219. for (auto& poller : device_pollers) {
  220. poller->Start();
  221. }
  222. grabKeyboard();
  223. grabMouse();
  224. qApp->setOverrideCursor(QCursor(Qt::CursorShape::ArrowCursor));
  225. timeout_timer->start(5000); // Cancel after 5 seconds
  226. poll_timer->start(200); // Check for new inputs every 200ms
  227. }
  228. void ConfigureTouchFromButton::NewBinding(const QPoint& pos) {
  229. auto* button = new QStandardItem();
  230. button->setEditable(false);
  231. auto* x_coord = new QStandardItem(QString::number(pos.x()));
  232. auto* y_coord = new QStandardItem(QString::number(pos.y()));
  233. const int dot_id = ui->bottom_screen->AddDot(pos.x(), pos.y());
  234. button->setData(dot_id, DataRoleDot);
  235. binding_list_model->appendRow({button, x_coord, y_coord});
  236. ui->binding_list->setFocus();
  237. ui->binding_list->setCurrentIndex(button->index());
  238. GetButtonInput(binding_list_model->rowCount() - 1, true);
  239. }
  240. void ConfigureTouchFromButton::EditBinding(const QModelIndex& qi) {
  241. if (qi.row() >= 0 && qi.column() == 0) {
  242. GetButtonInput(qi.row(), false);
  243. }
  244. }
  245. void ConfigureTouchFromButton::DeleteBinding() {
  246. const int row_index = ui->binding_list->currentIndex().row();
  247. if (row_index < 0) {
  248. return;
  249. }
  250. ui->bottom_screen->RemoveDot(binding_list_model->index(row_index, 0).data(DataRoleDot).toInt());
  251. binding_list_model->removeRow(row_index);
  252. }
  253. void ConfigureTouchFromButton::OnBindingSelection(const QItemSelection& selected,
  254. const QItemSelection& deselected) {
  255. ui->button_delete_bind->setEnabled(!selected.isEmpty());
  256. if (!selected.isEmpty()) {
  257. const auto dot_data = selected.indexes().first().data(DataRoleDot);
  258. if (dot_data.isValid()) {
  259. ui->bottom_screen->HighlightDot(dot_data.toInt());
  260. }
  261. }
  262. if (!deselected.isEmpty()) {
  263. const auto dot_data = deselected.indexes().first().data(DataRoleDot);
  264. if (dot_data.isValid()) {
  265. ui->bottom_screen->HighlightDot(dot_data.toInt(), false);
  266. }
  267. }
  268. }
  269. void ConfigureTouchFromButton::OnBindingChanged(QStandardItem* item) {
  270. if (item->column() == 0) {
  271. return;
  272. }
  273. const bool blocked = binding_list_model->blockSignals(true);
  274. item->setText(QString::number(
  275. std::clamp(item->text().toInt(), 0,
  276. static_cast<int>((item->column() == 1 ? Layout::ScreenUndocked::Width
  277. : Layout::ScreenUndocked::Height) -
  278. 1))));
  279. binding_list_model->blockSignals(blocked);
  280. const auto dot_data = binding_list_model->index(item->row(), 0).data(DataRoleDot);
  281. if (dot_data.isValid()) {
  282. ui->bottom_screen->MoveDot(dot_data.toInt(),
  283. binding_list_model->item(item->row(), 1)->text().toInt(),
  284. binding_list_model->item(item->row(), 2)->text().toInt());
  285. }
  286. }
  287. void ConfigureTouchFromButton::OnBindingDeleted(const QModelIndex& parent, int first, int last) {
  288. for (int i = first; i <= last; ++i) {
  289. const auto ix = binding_list_model->index(i, 0);
  290. if (!ix.isValid()) {
  291. return;
  292. }
  293. const auto dot_data = ix.data(DataRoleDot);
  294. if (dot_data.isValid()) {
  295. ui->bottom_screen->RemoveDot(dot_data.toInt());
  296. }
  297. }
  298. }
  299. void ConfigureTouchFromButton::SetActiveBinding(const int dot_id) {
  300. for (int i = 0; i < binding_list_model->rowCount(); ++i) {
  301. if (binding_list_model->index(i, 0).data(DataRoleDot) == dot_id) {
  302. ui->binding_list->setCurrentIndex(binding_list_model->index(i, 0));
  303. ui->binding_list->setFocus();
  304. return;
  305. }
  306. }
  307. }
  308. void ConfigureTouchFromButton::SetCoordinates(const int dot_id, const QPoint& pos) {
  309. for (int i = 0; i < binding_list_model->rowCount(); ++i) {
  310. if (binding_list_model->item(i, 0)->data(DataRoleDot) == dot_id) {
  311. binding_list_model->item(i, 1)->setText(QString::number(pos.x()));
  312. binding_list_model->item(i, 2)->setText(QString::number(pos.y()));
  313. return;
  314. }
  315. }
  316. }
  317. void ConfigureTouchFromButton::SetPollingResult(const Common::ParamPackage& params,
  318. const bool cancel) {
  319. releaseKeyboard();
  320. releaseMouse();
  321. qApp->restoreOverrideCursor();
  322. timeout_timer->stop();
  323. poll_timer->stop();
  324. for (auto& poller : device_pollers) {
  325. poller->Stop();
  326. }
  327. if (input_setter) {
  328. (*input_setter)(params, cancel);
  329. input_setter.reset();
  330. }
  331. }
  332. void ConfigureTouchFromButton::keyPressEvent(QKeyEvent* event) {
  333. if (!input_setter && event->key() == Qt::Key_Delete) {
  334. DeleteBinding();
  335. return;
  336. }
  337. if (!input_setter) {
  338. return QDialog::keyPressEvent(event);
  339. }
  340. if (event->key() != Qt::Key_Escape) {
  341. SetPollingResult(Common::ParamPackage{InputCommon::GenerateKeyboardParam(event->key())},
  342. false);
  343. } else {
  344. SetPollingResult({}, true);
  345. }
  346. }
  347. void ConfigureTouchFromButton::ApplyConfiguration() {
  348. SaveCurrentMapping();
  349. accept();
  350. }
  351. int ConfigureTouchFromButton::GetSelectedIndex() const {
  352. return selected_index;
  353. }
  354. std::vector<Settings::TouchFromButtonMap> ConfigureTouchFromButton::GetMaps() const {
  355. return touch_maps;
  356. }
  357. TouchScreenPreview::TouchScreenPreview(QWidget* parent) : QFrame(parent) {
  358. setBackgroundRole(QPalette::ColorRole::Base);
  359. }
  360. TouchScreenPreview::~TouchScreenPreview() = default;
  361. void TouchScreenPreview::SetCoordLabel(QLabel* const label) {
  362. coord_label = label;
  363. }
  364. int TouchScreenPreview::AddDot(const int device_x, const int device_y) {
  365. QFont dot_font{QStringLiteral("monospace")};
  366. dot_font.setStyleHint(QFont::Monospace);
  367. dot_font.setPointSize(20);
  368. auto* dot = new QLabel(this);
  369. dot->setAttribute(Qt::WA_TranslucentBackground);
  370. dot->setFont(dot_font);
  371. dot->setText(QChar(0xD7)); // U+00D7 Multiplication Sign
  372. dot->setAlignment(Qt::AlignmentFlag::AlignCenter);
  373. dot->setProperty(PropId, ++max_dot_id);
  374. dot->setProperty(PropX, device_x);
  375. dot->setProperty(PropY, device_y);
  376. dot->setCursor(Qt::CursorShape::PointingHandCursor);
  377. dot->setMouseTracking(true);
  378. dot->installEventFilter(this);
  379. dot->show();
  380. PositionDot(dot, device_x, device_y);
  381. dots.emplace_back(max_dot_id, dot);
  382. return max_dot_id;
  383. }
  384. void TouchScreenPreview::RemoveDot(const int id) {
  385. const auto iter = std::find_if(dots.begin(), dots.end(),
  386. [id](const auto& entry) { return entry.first == id; });
  387. if (iter == dots.cend()) {
  388. return;
  389. }
  390. iter->second->deleteLater();
  391. dots.erase(iter);
  392. }
  393. void TouchScreenPreview::HighlightDot(const int id, const bool active) const {
  394. for (const auto& dot : dots) {
  395. if (dot.first == id) {
  396. // use color property from the stylesheet, or fall back to the default palette
  397. if (dot_highlight_color.isValid()) {
  398. dot.second->setStyleSheet(
  399. active ? QStringLiteral("color: %1").arg(dot_highlight_color.name())
  400. : QString{});
  401. } else {
  402. dot.second->setForegroundRole(active ? QPalette::ColorRole::LinkVisited
  403. : QPalette::ColorRole::NoRole);
  404. }
  405. if (active) {
  406. dot.second->raise();
  407. }
  408. return;
  409. }
  410. }
  411. }
  412. void TouchScreenPreview::MoveDot(const int id, const int device_x, const int device_y) const {
  413. const auto iter = std::find_if(dots.begin(), dots.end(),
  414. [id](const auto& entry) { return entry.first == id; });
  415. if (iter == dots.cend()) {
  416. return;
  417. }
  418. iter->second->setProperty(PropX, device_x);
  419. iter->second->setProperty(PropY, device_y);
  420. PositionDot(iter->second, device_x, device_y);
  421. }
  422. void TouchScreenPreview::resizeEvent(QResizeEvent* event) {
  423. if (ignore_resize) {
  424. return;
  425. }
  426. const int target_width = std::min(width(), height() * 4 / 3);
  427. const int target_height = std::min(height(), width() * 3 / 4);
  428. if (target_width == width() && target_height == height()) {
  429. return;
  430. }
  431. ignore_resize = true;
  432. setGeometry((parentWidget()->contentsRect().width() - target_width) / 2, y(), target_width,
  433. target_height);
  434. ignore_resize = false;
  435. if (event->oldSize().width() != target_width || event->oldSize().height() != target_height) {
  436. for (const auto& dot : dots) {
  437. PositionDot(dot.second);
  438. }
  439. }
  440. }
  441. void TouchScreenPreview::mouseMoveEvent(QMouseEvent* event) {
  442. if (!coord_label) {
  443. return;
  444. }
  445. const auto pos = MapToDeviceCoords(event->x(), event->y());
  446. if (pos) {
  447. coord_label->setText(QStringLiteral("X: %1, Y: %2").arg(pos->x()).arg(pos->y()));
  448. } else {
  449. coord_label->clear();
  450. }
  451. }
  452. void TouchScreenPreview::leaveEvent(QEvent* event) {
  453. if (coord_label) {
  454. coord_label->clear();
  455. }
  456. }
  457. void TouchScreenPreview::mousePressEvent(QMouseEvent* event) {
  458. if (event->button() != Qt::MouseButton::LeftButton) {
  459. return;
  460. }
  461. const auto pos = MapToDeviceCoords(event->x(), event->y());
  462. if (pos) {
  463. emit DotAdded(*pos);
  464. }
  465. }
  466. bool TouchScreenPreview::eventFilter(QObject* obj, QEvent* event) {
  467. switch (event->type()) {
  468. case QEvent::Type::MouseButtonPress: {
  469. const auto mouse_event = static_cast<QMouseEvent*>(event);
  470. if (mouse_event->button() != Qt::MouseButton::LeftButton) {
  471. break;
  472. }
  473. emit DotSelected(obj->property(PropId).toInt());
  474. drag_state.dot = qobject_cast<QLabel*>(obj);
  475. drag_state.start_pos = mouse_event->globalPos();
  476. return true;
  477. }
  478. case QEvent::Type::MouseMove: {
  479. if (!drag_state.dot) {
  480. break;
  481. }
  482. const auto mouse_event = static_cast<QMouseEvent*>(event);
  483. if (!drag_state.active) {
  484. drag_state.active =
  485. (mouse_event->globalPos() - drag_state.start_pos).manhattanLength() >=
  486. QApplication::startDragDistance();
  487. if (!drag_state.active) {
  488. break;
  489. }
  490. }
  491. auto current_pos = mapFromGlobal(mouse_event->globalPos());
  492. current_pos.setX(std::clamp(current_pos.x(), contentsMargins().left(),
  493. contentsMargins().left() + contentsRect().width() - 1));
  494. current_pos.setY(std::clamp(current_pos.y(), contentsMargins().top(),
  495. contentsMargins().top() + contentsRect().height() - 1));
  496. const auto device_coord = MapToDeviceCoords(current_pos.x(), current_pos.y());
  497. if (device_coord) {
  498. drag_state.dot->setProperty(PropX, device_coord->x());
  499. drag_state.dot->setProperty(PropY, device_coord->y());
  500. PositionDot(drag_state.dot, device_coord->x(), device_coord->y());
  501. emit DotMoved(drag_state.dot->property(PropId).toInt(), *device_coord);
  502. if (coord_label) {
  503. coord_label->setText(
  504. QStringLiteral("X: %1, Y: %2").arg(device_coord->x()).arg(device_coord->y()));
  505. }
  506. }
  507. return true;
  508. }
  509. case QEvent::Type::MouseButtonRelease: {
  510. drag_state.dot.clear();
  511. drag_state.active = false;
  512. return true;
  513. }
  514. default:
  515. break;
  516. }
  517. return obj->eventFilter(obj, event);
  518. }
  519. std::optional<QPoint> TouchScreenPreview::MapToDeviceCoords(const int screen_x,
  520. const int screen_y) const {
  521. const float t_x = 0.5f + static_cast<float>(screen_x - contentsMargins().left()) *
  522. (Layout::ScreenUndocked::Width - 1) / (contentsRect().width() - 1);
  523. const float t_y = 0.5f + static_cast<float>(screen_y - contentsMargins().top()) *
  524. (Layout::ScreenUndocked::Height - 1) /
  525. (contentsRect().height() - 1);
  526. if (t_x >= 0.5f && t_x < Layout::ScreenUndocked::Width && t_y >= 0.5f &&
  527. t_y < Layout::ScreenUndocked::Height) {
  528. return QPoint{static_cast<int>(t_x), static_cast<int>(t_y)};
  529. }
  530. return std::nullopt;
  531. }
  532. void TouchScreenPreview::PositionDot(QLabel* const dot, const int device_x,
  533. const int device_y) const {
  534. const float device_coord_x =
  535. static_cast<float>(device_x >= 0 ? device_x : dot->property(PropX).toInt());
  536. int x_coord = static_cast<int>(
  537. device_coord_x * (contentsRect().width() - 1) / (Layout::ScreenUndocked::Width - 1) +
  538. contentsMargins().left() - static_cast<float>(dot->width()) / 2 + 0.5f);
  539. const float device_coord_y =
  540. static_cast<float>(device_y >= 0 ? device_y : dot->property(PropY).toInt());
  541. const int y_coord = static_cast<int>(
  542. device_coord_y * (contentsRect().height() - 1) / (Layout::ScreenUndocked::Height - 1) +
  543. contentsMargins().top() - static_cast<float>(dot->height()) / 2 + 0.5f);
  544. dot->move(x_coord, y_coord);
  545. }