configure_touch_from_button.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  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. const auto& params = input_subsystem->GetNextInput();
  141. if (params.Has("engine")) {
  142. SetPollingResult(params, false);
  143. return;
  144. }
  145. });
  146. }
  147. void ConfigureTouchFromButton::SaveCurrentMapping() {
  148. auto& map = touch_maps[selected_index];
  149. map.buttons.clear();
  150. for (int i = 0, rc = binding_list_model->rowCount(); i < rc; ++i) {
  151. const auto bind_str = binding_list_model->index(i, 0)
  152. .data(Qt::ItemDataRole::UserRole + 1)
  153. .toString()
  154. .toStdString();
  155. if (bind_str.empty()) {
  156. continue;
  157. }
  158. Common::ParamPackage params{bind_str};
  159. if (!params.Has("engine")) {
  160. continue;
  161. }
  162. params.Set("x", binding_list_model->index(i, 1).data().toInt());
  163. params.Set("y", binding_list_model->index(i, 2).data().toInt());
  164. map.buttons.emplace_back(params.Serialize());
  165. }
  166. }
  167. void ConfigureTouchFromButton::NewMapping() {
  168. const QString name =
  169. QInputDialog::getText(this, tr("New Profile"), tr("Enter the name for the new profile."));
  170. if (name.isEmpty()) {
  171. return;
  172. }
  173. touch_maps.emplace_back(Settings::TouchFromButtonMap{name.toStdString(), {}});
  174. ui->mapping->addItem(name);
  175. ui->mapping->setCurrentIndex(ui->mapping->count() - 1);
  176. }
  177. void ConfigureTouchFromButton::DeleteMapping() {
  178. const auto answer = QMessageBox::question(
  179. this, tr("Delete Profile"), tr("Delete profile %1?").arg(ui->mapping->currentText()));
  180. if (answer != QMessageBox::Yes) {
  181. return;
  182. }
  183. const bool blocked = ui->mapping->blockSignals(true);
  184. ui->mapping->removeItem(selected_index);
  185. ui->mapping->blockSignals(blocked);
  186. touch_maps.erase(touch_maps.begin() + selected_index);
  187. selected_index = ui->mapping->currentIndex();
  188. UpdateUiDisplay();
  189. }
  190. void ConfigureTouchFromButton::RenameMapping() {
  191. const QString new_name = QInputDialog::getText(this, tr("Rename Profile"), tr("New name:"));
  192. if (new_name.isEmpty()) {
  193. return;
  194. }
  195. ui->mapping->setItemText(selected_index, new_name);
  196. touch_maps[selected_index].name = new_name.toStdString();
  197. }
  198. void ConfigureTouchFromButton::GetButtonInput(const int row_index, const bool is_new) {
  199. if (timeout_timer->isActive()) {
  200. return;
  201. }
  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. input_subsystem->BeginMapping(InputCommon::Polling::InputType::Button);
  219. grabKeyboard();
  220. grabMouse();
  221. qApp->setOverrideCursor(QCursor(Qt::CursorShape::ArrowCursor));
  222. timeout_timer->start(5000); // Cancel after 5 seconds
  223. poll_timer->start(200); // Check for new inputs every 200ms
  224. }
  225. void ConfigureTouchFromButton::NewBinding(const QPoint& pos) {
  226. auto* button = new QStandardItem();
  227. button->setEditable(false);
  228. auto* x_coord = new QStandardItem(QString::number(pos.x()));
  229. auto* y_coord = new QStandardItem(QString::number(pos.y()));
  230. const int dot_id = ui->bottom_screen->AddDot(pos.x(), pos.y());
  231. button->setData(dot_id, DataRoleDot);
  232. binding_list_model->appendRow({button, x_coord, y_coord});
  233. ui->binding_list->setFocus();
  234. ui->binding_list->setCurrentIndex(button->index());
  235. GetButtonInput(binding_list_model->rowCount() - 1, true);
  236. }
  237. void ConfigureTouchFromButton::EditBinding(const QModelIndex& qi) {
  238. if (qi.row() >= 0 && qi.column() == 0) {
  239. GetButtonInput(qi.row(), false);
  240. }
  241. }
  242. void ConfigureTouchFromButton::DeleteBinding() {
  243. const int row_index = ui->binding_list->currentIndex().row();
  244. if (row_index < 0) {
  245. return;
  246. }
  247. ui->bottom_screen->RemoveDot(binding_list_model->index(row_index, 0).data(DataRoleDot).toInt());
  248. binding_list_model->removeRow(row_index);
  249. }
  250. void ConfigureTouchFromButton::OnBindingSelection(const QItemSelection& selected,
  251. const QItemSelection& deselected) {
  252. ui->button_delete_bind->setEnabled(!selected.isEmpty());
  253. if (!selected.isEmpty()) {
  254. const auto dot_data = selected.indexes().first().data(DataRoleDot);
  255. if (dot_data.isValid()) {
  256. ui->bottom_screen->HighlightDot(dot_data.toInt());
  257. }
  258. }
  259. if (!deselected.isEmpty()) {
  260. const auto dot_data = deselected.indexes().first().data(DataRoleDot);
  261. if (dot_data.isValid()) {
  262. ui->bottom_screen->HighlightDot(dot_data.toInt(), false);
  263. }
  264. }
  265. }
  266. void ConfigureTouchFromButton::OnBindingChanged(QStandardItem* item) {
  267. if (item->column() == 0) {
  268. return;
  269. }
  270. const bool blocked = binding_list_model->blockSignals(true);
  271. item->setText(QString::number(
  272. std::clamp(item->text().toInt(), 0,
  273. static_cast<int>((item->column() == 1 ? Layout::ScreenUndocked::Width
  274. : Layout::ScreenUndocked::Height) -
  275. 1))));
  276. binding_list_model->blockSignals(blocked);
  277. const auto dot_data = binding_list_model->index(item->row(), 0).data(DataRoleDot);
  278. if (dot_data.isValid()) {
  279. ui->bottom_screen->MoveDot(dot_data.toInt(),
  280. binding_list_model->item(item->row(), 1)->text().toInt(),
  281. binding_list_model->item(item->row(), 2)->text().toInt());
  282. }
  283. }
  284. void ConfigureTouchFromButton::OnBindingDeleted(const QModelIndex& parent, int first, int last) {
  285. for (int i = first; i <= last; ++i) {
  286. const auto ix = binding_list_model->index(i, 0);
  287. if (!ix.isValid()) {
  288. return;
  289. }
  290. const auto dot_data = ix.data(DataRoleDot);
  291. if (dot_data.isValid()) {
  292. ui->bottom_screen->RemoveDot(dot_data.toInt());
  293. }
  294. }
  295. }
  296. void ConfigureTouchFromButton::SetActiveBinding(const int dot_id) {
  297. for (int i = 0; i < binding_list_model->rowCount(); ++i) {
  298. if (binding_list_model->index(i, 0).data(DataRoleDot) == dot_id) {
  299. ui->binding_list->setCurrentIndex(binding_list_model->index(i, 0));
  300. ui->binding_list->setFocus();
  301. return;
  302. }
  303. }
  304. }
  305. void ConfigureTouchFromButton::SetCoordinates(const int dot_id, const QPoint& pos) {
  306. for (int i = 0; i < binding_list_model->rowCount(); ++i) {
  307. if (binding_list_model->item(i, 0)->data(DataRoleDot) == dot_id) {
  308. binding_list_model->item(i, 1)->setText(QString::number(pos.x()));
  309. binding_list_model->item(i, 2)->setText(QString::number(pos.y()));
  310. return;
  311. }
  312. }
  313. }
  314. void ConfigureTouchFromButton::SetPollingResult(const Common::ParamPackage& params,
  315. const bool cancel) {
  316. timeout_timer->stop();
  317. poll_timer->stop();
  318. input_subsystem->StopMapping();
  319. releaseKeyboard();
  320. releaseMouse();
  321. qApp->restoreOverrideCursor();
  322. if (input_setter) {
  323. (*input_setter)(params, cancel);
  324. input_setter.reset();
  325. }
  326. }
  327. void ConfigureTouchFromButton::keyPressEvent(QKeyEvent* event) {
  328. if (!input_setter && event->key() == Qt::Key_Delete) {
  329. DeleteBinding();
  330. return;
  331. }
  332. if (!input_setter) {
  333. return QDialog::keyPressEvent(event);
  334. }
  335. if (event->key() != Qt::Key_Escape) {
  336. SetPollingResult(Common::ParamPackage{InputCommon::GenerateKeyboardParam(event->key())},
  337. false);
  338. } else {
  339. SetPollingResult({}, true);
  340. }
  341. }
  342. void ConfigureTouchFromButton::ApplyConfiguration() {
  343. SaveCurrentMapping();
  344. accept();
  345. }
  346. int ConfigureTouchFromButton::GetSelectedIndex() const {
  347. return selected_index;
  348. }
  349. std::vector<Settings::TouchFromButtonMap> ConfigureTouchFromButton::GetMaps() const {
  350. return touch_maps;
  351. }
  352. TouchScreenPreview::TouchScreenPreview(QWidget* parent) : QFrame(parent) {
  353. setBackgroundRole(QPalette::ColorRole::Base);
  354. }
  355. TouchScreenPreview::~TouchScreenPreview() = default;
  356. void TouchScreenPreview::SetCoordLabel(QLabel* const label) {
  357. coord_label = label;
  358. }
  359. int TouchScreenPreview::AddDot(const int device_x, const int device_y) {
  360. QFont dot_font{QStringLiteral("monospace")};
  361. dot_font.setStyleHint(QFont::Monospace);
  362. dot_font.setPointSize(20);
  363. auto* dot = new QLabel(this);
  364. dot->setAttribute(Qt::WA_TranslucentBackground);
  365. dot->setFont(dot_font);
  366. dot->setText(QChar(0xD7)); // U+00D7 Multiplication Sign
  367. dot->setAlignment(Qt::AlignmentFlag::AlignCenter);
  368. dot->setProperty(PropId, ++max_dot_id);
  369. dot->setProperty(PropX, device_x);
  370. dot->setProperty(PropY, device_y);
  371. dot->setCursor(Qt::CursorShape::PointingHandCursor);
  372. dot->setMouseTracking(true);
  373. dot->installEventFilter(this);
  374. dot->show();
  375. PositionDot(dot, device_x, device_y);
  376. dots.emplace_back(max_dot_id, dot);
  377. return max_dot_id;
  378. }
  379. void TouchScreenPreview::RemoveDot(const int id) {
  380. const auto iter = std::find_if(dots.begin(), dots.end(),
  381. [id](const auto& entry) { return entry.first == id; });
  382. if (iter == dots.cend()) {
  383. return;
  384. }
  385. iter->second->deleteLater();
  386. dots.erase(iter);
  387. }
  388. void TouchScreenPreview::HighlightDot(const int id, const bool active) const {
  389. for (const auto& dot : dots) {
  390. if (dot.first == id) {
  391. // use color property from the stylesheet, or fall back to the default palette
  392. if (dot_highlight_color.isValid()) {
  393. dot.second->setStyleSheet(
  394. active ? QStringLiteral("color: %1").arg(dot_highlight_color.name())
  395. : QString{});
  396. } else {
  397. dot.second->setForegroundRole(active ? QPalette::ColorRole::LinkVisited
  398. : QPalette::ColorRole::NoRole);
  399. }
  400. if (active) {
  401. dot.second->raise();
  402. }
  403. return;
  404. }
  405. }
  406. }
  407. void TouchScreenPreview::MoveDot(const int id, const int device_x, const int device_y) const {
  408. const auto iter = std::find_if(dots.begin(), dots.end(),
  409. [id](const auto& entry) { return entry.first == id; });
  410. if (iter == dots.cend()) {
  411. return;
  412. }
  413. iter->second->setProperty(PropX, device_x);
  414. iter->second->setProperty(PropY, device_y);
  415. PositionDot(iter->second, device_x, device_y);
  416. }
  417. void TouchScreenPreview::resizeEvent(QResizeEvent* event) {
  418. if (ignore_resize) {
  419. return;
  420. }
  421. const int target_width = std::min(width(), height() * 4 / 3);
  422. const int target_height = std::min(height(), width() * 3 / 4);
  423. if (target_width == width() && target_height == height()) {
  424. return;
  425. }
  426. ignore_resize = true;
  427. setGeometry((parentWidget()->contentsRect().width() - target_width) / 2, y(), target_width,
  428. target_height);
  429. ignore_resize = false;
  430. if (event->oldSize().width() != target_width || event->oldSize().height() != target_height) {
  431. for (const auto& dot : dots) {
  432. PositionDot(dot.second);
  433. }
  434. }
  435. }
  436. void TouchScreenPreview::mouseMoveEvent(QMouseEvent* event) {
  437. if (!coord_label) {
  438. return;
  439. }
  440. const auto pos = MapToDeviceCoords(event->x(), event->y());
  441. if (pos) {
  442. coord_label->setText(QStringLiteral("X: %1, Y: %2").arg(pos->x()).arg(pos->y()));
  443. } else {
  444. coord_label->clear();
  445. }
  446. }
  447. void TouchScreenPreview::leaveEvent(QEvent* event) {
  448. if (coord_label) {
  449. coord_label->clear();
  450. }
  451. }
  452. void TouchScreenPreview::mousePressEvent(QMouseEvent* event) {
  453. if (event->button() != Qt::MouseButton::LeftButton) {
  454. return;
  455. }
  456. const auto pos = MapToDeviceCoords(event->x(), event->y());
  457. if (pos) {
  458. emit DotAdded(*pos);
  459. }
  460. }
  461. bool TouchScreenPreview::eventFilter(QObject* obj, QEvent* event) {
  462. switch (event->type()) {
  463. case QEvent::Type::MouseButtonPress: {
  464. const auto mouse_event = static_cast<QMouseEvent*>(event);
  465. if (mouse_event->button() != Qt::MouseButton::LeftButton) {
  466. break;
  467. }
  468. emit DotSelected(obj->property(PropId).toInt());
  469. drag_state.dot = qobject_cast<QLabel*>(obj);
  470. drag_state.start_pos = mouse_event->globalPos();
  471. return true;
  472. }
  473. case QEvent::Type::MouseMove: {
  474. if (!drag_state.dot) {
  475. break;
  476. }
  477. const auto mouse_event = static_cast<QMouseEvent*>(event);
  478. if (!drag_state.active) {
  479. drag_state.active =
  480. (mouse_event->globalPos() - drag_state.start_pos).manhattanLength() >=
  481. QApplication::startDragDistance();
  482. if (!drag_state.active) {
  483. break;
  484. }
  485. }
  486. auto current_pos = mapFromGlobal(mouse_event->globalPos());
  487. current_pos.setX(std::clamp(current_pos.x(), contentsMargins().left(),
  488. contentsMargins().left() + contentsRect().width() - 1));
  489. current_pos.setY(std::clamp(current_pos.y(), contentsMargins().top(),
  490. contentsMargins().top() + contentsRect().height() - 1));
  491. const auto device_coord = MapToDeviceCoords(current_pos.x(), current_pos.y());
  492. if (device_coord) {
  493. drag_state.dot->setProperty(PropX, device_coord->x());
  494. drag_state.dot->setProperty(PropY, device_coord->y());
  495. PositionDot(drag_state.dot, device_coord->x(), device_coord->y());
  496. emit DotMoved(drag_state.dot->property(PropId).toInt(), *device_coord);
  497. if (coord_label) {
  498. coord_label->setText(
  499. QStringLiteral("X: %1, Y: %2").arg(device_coord->x()).arg(device_coord->y()));
  500. }
  501. }
  502. return true;
  503. }
  504. case QEvent::Type::MouseButtonRelease: {
  505. drag_state.dot.clear();
  506. drag_state.active = false;
  507. return true;
  508. }
  509. default:
  510. break;
  511. }
  512. return obj->eventFilter(obj, event);
  513. }
  514. std::optional<QPoint> TouchScreenPreview::MapToDeviceCoords(const int screen_x,
  515. const int screen_y) const {
  516. const float t_x = 0.5f + static_cast<float>(screen_x - contentsMargins().left()) *
  517. (Layout::ScreenUndocked::Width - 1) / (contentsRect().width() - 1);
  518. const float t_y = 0.5f + static_cast<float>(screen_y - contentsMargins().top()) *
  519. (Layout::ScreenUndocked::Height - 1) /
  520. (contentsRect().height() - 1);
  521. if (t_x >= 0.5f && t_x < Layout::ScreenUndocked::Width && t_y >= 0.5f &&
  522. t_y < Layout::ScreenUndocked::Height) {
  523. return QPoint{static_cast<int>(t_x), static_cast<int>(t_y)};
  524. }
  525. return std::nullopt;
  526. }
  527. void TouchScreenPreview::PositionDot(QLabel* const dot, const int device_x,
  528. const int device_y) const {
  529. const float device_coord_x =
  530. static_cast<float>(device_x >= 0 ? device_x : dot->property(PropX).toInt());
  531. int x_coord = static_cast<int>(
  532. device_coord_x * (contentsRect().width() - 1) / (Layout::ScreenUndocked::Width - 1) +
  533. contentsMargins().left() - static_cast<float>(dot->width()) / 2 + 0.5f);
  534. const float device_coord_y =
  535. static_cast<float>(device_y >= 0 ? device_y : dot->property(PropY).toInt());
  536. const int y_coord = static_cast<int>(
  537. device_coord_y * (contentsRect().height() - 1) / (Layout::ScreenUndocked::Height - 1) +
  538. contentsMargins().top() - static_cast<float>(dot->height()) / 2 + 0.5f);
  539. dot->move(x_coord, y_coord);
  540. }