| 1 | // Copyright 2017 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #include "DolphinQt/Config/Mapping/IOWindow.h" |
| 5 | |
| 6 | #include <array> |
| 7 | #include <optional> |
| 8 | |
| 9 | #include <QBrush> |
| 10 | #include <QColor> |
| 11 | #include <QComboBox> |
| 12 | #include <QDialogButtonBox> |
| 13 | #include <QHeaderView> |
| 14 | #include <QItemDelegate> |
| 15 | #include <QLabel> |
| 16 | #include <QLineEdit> |
| 17 | #include <QPainter> |
| 18 | #include <QPlainTextEdit> |
| 19 | #include <QPushButton> |
| 20 | #include <QSlider> |
| 21 | #include <QSpinBox> |
| 22 | #include <QTableWidget> |
| 23 | #include <QTextBlock> |
| 24 | #include <QTimer> |
| 25 | #include <QVBoxLayout> |
| 26 | |
| 27 | #include "DolphinQt/Config/Mapping/MappingCommon.h" |
| 28 | #include "DolphinQt/Config/Mapping/MappingIndicator.h" |
| 29 | #include "DolphinQt/Config/Mapping/MappingWindow.h" |
| 30 | #include "DolphinQt/QtUtils/BlockUserInputFilter.h" |
| 31 | #include "DolphinQt/QtUtils/ModalMessageBox.h" |
| 32 | #include "DolphinQt/Settings.h" |
| 33 | |
| 34 | #include "InputCommon/ControlReference/ControlReference.h" |
| 35 | #include "InputCommon/ControlReference/ExpressionParser.h" |
| 36 | #include "InputCommon/ControllerEmu/ControllerEmu.h" |
| 37 | #include "InputCommon/ControllerInterface/ControllerInterface.h" |
| 38 | #include "InputCommon/ControllerInterface/MappingCommon.h" |
| 39 | |
| 40 | namespace |
| 41 | { |
| 42 | constexpr auto INPUT_DETECT_TIME = std::chrono::seconds(2); |
| 43 | constexpr auto OUTPUT_TEST_TIME = std::chrono::seconds(2); |
| 44 | |
| 45 | QTextCharFormat GetSpecialCharFormat() |
| 46 | { |
| 47 | QTextCharFormat format; |
| 48 | format.setFontWeight(QFont::Weight::Bold); |
| 49 | return format; |
| 50 | } |
| 51 | |
| 52 | QTextCharFormat GetLiteralCharFormat() |
| 53 | { |
| 54 | QTextCharFormat format; |
| 55 | if (Settings::Instance().IsThemeDark()) |
| 56 | format.setForeground(QBrush{QColor(171, 132, 219)}); |
| 57 | else |
| 58 | format.setForeground(QBrush{Qt::darkMagenta}); |
| 59 | return format; |
| 60 | } |
| 61 | |
| 62 | QTextCharFormat GetInvalidCharFormat() |
| 63 | { |
| 64 | QTextCharFormat format; |
| 65 | format.setUnderlineStyle(QTextCharFormat::WaveUnderline); |
| 66 | if (Settings::Instance().IsThemeDark()) |
| 67 | format.setUnderlineColor(QColor(255, 69, 0)); |
| 68 | else |
| 69 | format.setUnderlineColor(Qt::darkRed); |
| 70 | return format; |
| 71 | } |
| 72 | |
| 73 | QTextCharFormat GetControlCharFormat() |
| 74 | { |
| 75 | QTextCharFormat format; |
| 76 | if (Settings::Instance().IsThemeDark()) |
| 77 | format.setForeground(QBrush{QColor(0, 220, 0)}); |
| 78 | else |
| 79 | format.setForeground(QBrush{Qt::darkGreen}); |
| 80 | return format; |
| 81 | } |
| 82 | |
| 83 | QTextCharFormat GetVariableCharFormat() |
| 84 | { |
| 85 | QTextCharFormat format; |
| 86 | if (Settings::Instance().IsThemeDark()) |
| 87 | format.setForeground(QBrush{QColor(226, 226, 0)}); |
| 88 | else |
| 89 | format.setForeground(QBrush{Qt::darkYellow}); |
| 90 | return format; |
| 91 | } |
| 92 | |
| 93 | QTextCharFormat GetBarewordCharFormat() |
| 94 | { |
| 95 | QTextCharFormat format; |
| 96 | if (Settings::Instance().IsThemeDark()) |
| 97 | format.setForeground(QBrush{QColor(66, 138, 255)}); |
| 98 | else |
| 99 | format.setForeground(QBrush{Qt::darkBlue}); |
| 100 | return format; |
| 101 | } |
| 102 | |
| 103 | QTextCharFormat GetCommentCharFormat() |
| 104 | { |
| 105 | QTextCharFormat format; |
| 106 | if (Settings::Instance().IsThemeDark()) |
| 107 | format.setForeground(QBrush{QColor(176, 176, 176)}); |
| 108 | else |
| 109 | format.setForeground(QBrush{Qt::darkGray}); |
| 110 | return format; |
| 111 | } |
| 112 | } // namespace |
| 113 | |
| 114 | ControlExpressionSyntaxHighlighter::ControlExpressionSyntaxHighlighter(QTextDocument* parent) |
| 115 | : QObject(parent) |
| 116 | { |
| 117 | connect(parent, &QTextDocument::contentsChanged, this, [this, parent] { Highlight(parent); }); |
| 118 | } |
| 119 | |
| 120 | void QComboBoxWithMouseWheelDisabled::wheelEvent(QWheelEvent* event) |
| 121 | { |
| 122 | // Do nothing |
| 123 | } |
| 124 | |
| 125 | void ControlExpressionSyntaxHighlighter::Highlight(QTextDocument* document) |
| 126 | { |
| 127 | // toLatin1 converts multi-byte unicode characters to a single-byte character, |
| 128 | // so Token string_position values are the character counts that Qt's FormatRange expects. |
| 129 | ciface::ExpressionParser::Lexer lexer(document->toPlainText().toLatin1().toStdString()); |
| 130 | |
| 131 | std::vector<ciface::ExpressionParser::Token> tokens; |
| 132 | const auto tokenize_status = lexer.Tokenize(tokens); |
| 133 | |
| 134 | if (ciface::ExpressionParser::ParseStatus::Successful == tokenize_status) |
| 135 | { |
| 136 | const auto parse_status = ciface::ExpressionParser::ParseTokens(tokens); |
| 137 | if (ciface::ExpressionParser::ParseStatus::Successful != parse_status.status) |
| 138 | { |
| 139 | auto token = *parse_status.token; |
| 140 | // Add invalid version of token where parsing failed for appropriate error-highlighting. |
| 141 | token.type = ciface::ExpressionParser::TOK_INVALID; |
| 142 | tokens.emplace_back(token); |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | auto get_token_char_format = [](const ciface::ExpressionParser::Token& token) { |
| 147 | std::optional<QTextCharFormat> char_format; |
| 148 | |
| 149 | using ciface::ExpressionParser::TokenType; |
| 150 | |
| 151 | switch (token.type) |
| 152 | { |
| 153 | case TokenType::TOK_INVALID: |
| 154 | char_format = GetInvalidCharFormat(); |
| 155 | break; |
| 156 | case TokenType::TOK_LPAREN: |
| 157 | case TokenType::TOK_RPAREN: |
| 158 | case TokenType::TOK_COMMA: |
| 159 | case TokenType::TOK_QUESTION: |
| 160 | case TokenType::TOK_COLON: |
| 161 | char_format = GetSpecialCharFormat(); |
| 162 | break; |
| 163 | case TokenType::TOK_LITERAL: |
| 164 | char_format = GetLiteralCharFormat(); |
| 165 | break; |
| 166 | case TokenType::TOK_CONTROL: |
| 167 | char_format = GetControlCharFormat(); |
| 168 | break; |
| 169 | case TokenType::TOK_BAREWORD: |
| 170 | char_format = GetBarewordCharFormat(); |
| 171 | break; |
| 172 | case TokenType::TOK_VARIABLE: |
| 173 | char_format = GetVariableCharFormat(); |
| 174 | break; |
| 175 | case TokenType::TOK_COMMENT: |
| 176 | char_format = GetCommentCharFormat(); |
| 177 | break; |
| 178 | default: |
| 179 | if (token.IsBinaryOperator()) |
| 180 | char_format = GetSpecialCharFormat(); |
| 181 | break; |
| 182 | } |
| 183 | |
| 184 | return char_format; |
| 185 | }; |
| 186 | |
| 187 | // FYI, formatting needs to be done at the block level to prevent altering of undo/redo history. |
| 188 | for (QTextBlock block = document->begin(); block.isValid(); block = block.next()) |
| 189 | { |
| 190 | block.layout()->clearFormats(); |
| 191 | |
| 192 | const int block_position = block.position(); |
| 193 | const int block_length = block_position + block.length(); |
| 194 | |
| 195 | QList<QTextLayout::FormatRange> format_ranges; |
| 196 | |
| 197 | for (auto& token : tokens) |
| 198 | { |
| 199 | int token_length = int(token.string_length); |
| 200 | int token_start = int(token.string_position) - block_position; |
| 201 | if (token_start < 0) |
| 202 | { |
| 203 | token_length += token_start; |
| 204 | token_start = 0; |
| 205 | } |
| 206 | |
| 207 | if (token_length <= 0) |
| 208 | { |
| 209 | // Token is in a previous block. |
| 210 | continue; |
| 211 | } |
| 212 | |
| 213 | if (token_start >= block_length) |
| 214 | { |
| 215 | // Token is in a following block. |
| 216 | break; |
| 217 | } |
| 218 | |
| 219 | const auto char_format = get_token_char_format(token); |
| 220 | if (char_format.has_value()) |
| 221 | { |
| 222 | format_ranges.emplace_back(QTextLayout::FormatRange{ |
| 223 | .start = token_start, .length = token_length, .format = *char_format}); |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | block.layout()->setFormats(format_ranges); |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | class InputStateDelegate : public QItemDelegate |
| 232 | { |
| 233 | public: |
| 234 | explicit InputStateDelegate(IOWindow* parent, int column, |
| 235 | std::function<ControlState(int row)> state_evaluator); |
| 236 | |
| 237 | void paint(QPainter* painter, const QStyleOptionViewItem& option, |
| 238 | const QModelIndex& index) const override; |
| 239 | |
| 240 | private: |
| 241 | std::function<ControlState(int row)> m_state_evaluator; |
| 242 | int m_column; |
| 243 | }; |
| 244 | |
| 245 | class InputStateLineEdit : public QLineEdit |
| 246 | { |
| 247 | public: |
| 248 | explicit InputStateLineEdit(std::function<ControlState()> state_evaluator); |
| 249 | void SetShouldPaintStateIndicator(bool value); |
| 250 | void paintEvent(QPaintEvent* event) override; |
| 251 | |
| 252 | private: |
| 253 | std::function<ControlState()> m_state_evaluator; |
| 254 | bool m_should_paint_state_indicator = false; |
| 255 | }; |
| 256 | |
| 257 | IOWindow::IOWindow(MappingWindow* window, ControllerEmu::EmulatedController* controller, |
| 258 | ControlReference* ref, IOWindow::Type type) |
| 259 | : QDialog(window), m_reference(ref), m_original_expression(ref->GetExpression()), |
| 260 | m_controller(controller), m_type(type) |
| 261 | { |
| 262 | CreateMainLayout(); |
| 263 | |
| 264 | connect(window, &MappingWindow::Update, this, &IOWindow::Update); |
| 265 | connect(window, &MappingWindow::ConfigChanged, this, &IOWindow::ConfigChanged); |
| 266 | connect(&Settings::Instance(), &Settings::ConfigChanged, this, &IOWindow::ConfigChanged); |
| 267 | |
| 268 | setWindowTitle(type == IOWindow::Type::Input ? tr("Configure Input") : tr("Configure Output")); |
| 269 | |
| 270 | ConfigChanged(); |
| 271 | |
| 272 | ConnectWidgets(); |
| 273 | } |
| 274 | |
| 275 | std::shared_ptr<ciface::Core::Device> IOWindow::GetSelectedDevice() const |
| 276 | { |
| 277 | return m_selected_device; |
| 278 | } |
| 279 | |
| 280 | void IOWindow::CreateMainLayout() |
| 281 | { |
| 282 | m_main_layout = new QVBoxLayout(); |
| 283 | |
| 284 | m_devices_combo = new QComboBox(); |
| 285 | m_option_list = new QTableWidget(); |
| 286 | |
| 287 | m_select_button = |
| 288 | new QPushButton(m_type == IOWindow::Type::Input ? tr("Insert Input") : tr("Insert Output")); |
| 289 | m_detect_button = new QPushButton(tr("Detect Input"), this); |
| 290 | m_test_button = new QPushButton(tr("Test Output"), this); |
| 291 | m_button_box = new QDialogButtonBox(); |
| 292 | m_clear_button = new QPushButton(tr("Clear")); |
| 293 | m_scalar_spinbox = new QSpinBox(); |
| 294 | |
| 295 | if (m_type == Type::Input) |
| 296 | { |
| 297 | m_parse_text = new InputStateLineEdit([this] { |
| 298 | const auto lock = m_controller->GetStateLock(); |
| 299 | return m_reference->GetState<ControlState>(); |
| 300 | }); |
| 301 | } |
| 302 | else |
| 303 | { |
| 304 | m_parse_text = new InputStateLineEdit([this] { |
| 305 | const auto lock = m_controller->GetStateLock(); |
| 306 | return m_output_test_timer->isActive() * m_reference->range; |
| 307 | }); |
| 308 | } |
| 309 | |
| 310 | m_expression_text = new QPlainTextEdit(); |
| 311 | m_expression_text->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont)); |
| 312 | new ControlExpressionSyntaxHighlighter(m_expression_text->document()); |
| 313 | |
| 314 | m_operators_combo = new QComboBoxWithMouseWheelDisabled(this); |
| 315 | m_operators_combo->addItem(tr("Operators")); |
| 316 | m_operators_combo->insertSeparator(1); |
| 317 | if (m_type == Type::Input) |
| 318 | { |
| 319 | m_operators_combo->addItem(tr("! Not")); |
| 320 | m_operators_combo->addItem(tr("* Multiply")); |
| 321 | m_operators_combo->addItem(tr("/ Divide")); |
| 322 | m_operators_combo->addItem(tr("% Modulo")); |
| 323 | m_operators_combo->addItem(tr("+ Add")); |
| 324 | m_operators_combo->addItem(tr("- Subtract")); |
| 325 | m_operators_combo->addItem(tr("> Greater-than")); |
| 326 | m_operators_combo->addItem(tr("< Less-than")); |
| 327 | m_operators_combo->addItem(tr("& And")); |
| 328 | m_operators_combo->addItem(tr("^ Xor")); |
| 329 | m_operators_combo->addItem(tr("? Conditional")); |
| 330 | } |
| 331 | m_operators_combo->addItem(tr("| Or")); |
| 332 | m_operators_combo->addItem(tr("$ User Variable")); |
| 333 | if (m_type == Type::Input) |
| 334 | { |
| 335 | m_operators_combo->addItem(tr(", Comma")); |
| 336 | } |
| 337 | |
| 338 | m_functions_combo = new QComboBoxWithMouseWheelDisabled(this); |
| 339 | m_functions_combo->addItem(tr("Functions")); |
| 340 | m_functions_combo->insertSeparator(1); |
| 341 | m_functions_combo->addItem(QStringLiteral("if")); |
| 342 | m_functions_combo->addItem(QStringLiteral("timer")); |
| 343 | m_functions_combo->addItem(QStringLiteral("toggle")); |
| 344 | m_functions_combo->addItem(QStringLiteral("deadzone")); |
| 345 | m_functions_combo->addItem(QStringLiteral("smooth")); |
| 346 | m_functions_combo->addItem(QStringLiteral("hold")); |
| 347 | m_functions_combo->addItem(QStringLiteral("tap")); |
| 348 | m_functions_combo->addItem(QStringLiteral("relative")); |
| 349 | m_functions_combo->addItem(QStringLiteral("pulse")); |
| 350 | m_functions_combo->addItem(QStringLiteral("sin")); |
| 351 | m_functions_combo->addItem(QStringLiteral("cos")); |
| 352 | m_functions_combo->addItem(QStringLiteral("tan")); |
| 353 | m_functions_combo->addItem(QStringLiteral("asin")); |
| 354 | m_functions_combo->addItem(QStringLiteral("acos")); |
| 355 | m_functions_combo->addItem(QStringLiteral("atan")); |
| 356 | m_functions_combo->addItem(QStringLiteral("atan2")); |
| 357 | m_functions_combo->addItem(QStringLiteral("sqrt")); |
| 358 | m_functions_combo->addItem(QStringLiteral("pow")); |
| 359 | m_functions_combo->addItem(QStringLiteral("min")); |
| 360 | m_functions_combo->addItem(QStringLiteral("max")); |
| 361 | m_functions_combo->addItem(QStringLiteral("clamp")); |
| 362 | m_functions_combo->addItem(QStringLiteral("abs")); |
| 363 | |
| 364 | m_variables_combo = new QComboBoxWithMouseWheelDisabled(this); |
| 365 | m_variables_combo->addItem(tr("User Variables")); |
| 366 | m_variables_combo->setToolTip( |
| 367 | tr("User defined variables usable in the control expression.\nYou can use them to save or " |
| 368 | "retrieve values between\ninputs and outputs of the same parent controller.")); |
| 369 | m_variables_combo->insertSeparator(m_variables_combo->count()); |
| 370 | m_variables_combo->addItem(tr("Reset Values")); |
| 371 | m_variables_combo->insertSeparator(m_variables_combo->count()); |
| 372 | |
| 373 | // Devices |
| 374 | m_main_layout->addWidget(m_devices_combo); |
| 375 | |
| 376 | // Scalar |
| 377 | auto* scalar_hbox = new QHBoxLayout(); |
| 378 | // i18n: Controller input values are multiplied by this percentage value. |
| 379 | scalar_hbox->addWidget(new QLabel(tr("Multiplier"))); |
| 380 | scalar_hbox->addWidget(m_scalar_spinbox); |
| 381 | |
| 382 | // Outputs are not bounds checked and greater than 100% has no use case. |
| 383 | // (incoming values are always 0 or 1) |
| 384 | // Negative 100% can be used to invert force feedback wheel direction. |
| 385 | const int scalar_min_max = (m_type == Type::Input) ? 1000 : 100; |
| 386 | m_scalar_spinbox->setMinimum(-scalar_min_max); |
| 387 | m_scalar_spinbox->setMaximum(scalar_min_max); |
| 388 | // i18n: Percentage symbol. |
| 389 | m_scalar_spinbox->setSuffix(tr("%")); |
| 390 | |
| 391 | // Options (Buttons, Outputs) and action buttons |
| 392 | |
| 393 | m_option_list->setTabKeyNavigation(false); |
| 394 | |
| 395 | if (m_type == Type::Input) |
| 396 | { |
| 397 | m_option_list->setColumnCount(2); |
| 398 | m_option_list->setColumnWidth(1, 64); |
| 399 | m_option_list->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Fixed); |
| 400 | |
| 401 | m_option_list->setItemDelegate(new InputStateDelegate(this, 1, [&](int row) { |
| 402 | std::lock_guard lock(m_selected_device_mutex); |
| 403 | // Clamp off negative values but allow greater than one in the text display. |
| 404 | return std::max(GetSelectedDevice()->Inputs()[row]->GetState(), 0.0); |
| 405 | })); |
| 406 | } |
| 407 | else |
| 408 | { |
| 409 | m_option_list->setColumnCount(1); |
| 410 | } |
| 411 | |
| 412 | m_option_list->horizontalHeader()->hide(); |
| 413 | m_option_list->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); |
| 414 | m_option_list->verticalHeader()->hide(); |
| 415 | m_option_list->verticalHeader()->setDefaultSectionSize( |
| 416 | m_option_list->verticalHeader()->minimumSectionSize()); |
| 417 | m_option_list->setEditTriggers(QAbstractItemView::NoEditTriggers); |
| 418 | m_option_list->setSelectionBehavior(QAbstractItemView::SelectRows); |
| 419 | m_option_list->setSelectionMode(QAbstractItemView::SingleSelection); |
| 420 | |
| 421 | auto* hbox = new QHBoxLayout(); |
| 422 | auto* button_vbox = new QVBoxLayout(); |
| 423 | hbox->addWidget(m_option_list, 8); |
| 424 | hbox->addLayout(button_vbox, 1); |
| 425 | |
| 426 | button_vbox->addWidget(m_select_button); |
| 427 | |
| 428 | if (m_type == Type::Input) |
| 429 | { |
| 430 | m_test_button->hide(); |
| 431 | button_vbox->addWidget(m_detect_button); |
| 432 | } |
| 433 | else |
| 434 | { |
| 435 | m_detect_button->hide(); |
| 436 | button_vbox->addWidget(m_test_button); |
| 437 | } |
| 438 | |
| 439 | button_vbox->addWidget(m_variables_combo); |
| 440 | |
| 441 | button_vbox->addWidget(m_operators_combo); |
| 442 | |
| 443 | if (m_type == Type::Input) |
| 444 | button_vbox->addWidget(m_functions_combo); |
| 445 | else |
| 446 | m_functions_combo->hide(); |
| 447 | |
| 448 | button_vbox->addLayout(scalar_hbox); |
| 449 | |
| 450 | m_main_layout->addLayout(hbox, 2); |
| 451 | m_main_layout->addWidget(m_expression_text, 1); |
| 452 | m_main_layout->addWidget(m_parse_text); |
| 453 | |
| 454 | // Button Box |
| 455 | m_main_layout->addWidget(m_button_box); |
| 456 | m_button_box->addButton(m_clear_button, QDialogButtonBox::ActionRole); |
| 457 | m_button_box->addButton(QDialogButtonBox::Ok); |
| 458 | |
| 459 | m_output_test_timer = new QTimer(this); |
| 460 | m_output_test_timer->setSingleShot(true); |
| 461 | |
| 462 | setLayout(m_main_layout); |
| 463 | } |
| 464 | |
| 465 | void IOWindow::ConfigChanged() |
| 466 | { |
| 467 | emit DetectInputComplete(); |
| 468 | emit TestOutputComplete(); |
| 469 | |
| 470 | const QSignalBlocker blocker(this); |
| 471 | const auto lock = ControllerEmu::EmulatedController::GetStateLock(); |
| 472 | |
| 473 | // ensure m_parse_text is in the right state |
| 474 | UpdateExpression(m_reference->GetExpression(), UpdateMode::Force); |
| 475 | |
| 476 | m_expression_text->setPlainText(QString::fromStdString(m_reference->GetExpression())); |
| 477 | m_expression_text->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor); |
| 478 | m_scalar_spinbox->setValue(m_reference->range * 100.0); |
| 479 | |
| 480 | if (m_devq.ToString().empty()) |
| 481 | m_devq = m_controller->GetDefaultDevice(); |
| 482 | |
| 483 | UpdateDeviceList(); |
| 484 | } |
| 485 | |
| 486 | void IOWindow::Update() |
| 487 | { |
| 488 | m_option_list->viewport()->update(); |
| 489 | m_parse_text->update(); |
| 490 | |
| 491 | if (!m_input_detector) |
| 492 | return; |
| 493 | |
| 494 | if (m_input_detector->IsComplete()) |
| 495 | { |
| 496 | const auto results = m_input_detector->TakeResults(); |
| 497 | |
| 498 | emit DetectInputComplete(); |
| 499 | |
| 500 | if (results.empty()) |
| 501 | return; |
| 502 | |
| 503 | // Select the first detected input. |
| 504 | auto list = m_option_list->findItems(QString::fromStdString(results.front().input->GetName()), |
| 505 | Qt::MatchFixedString); |
| 506 | if (list.empty()) |
| 507 | return; |
| 508 | |
| 509 | m_option_list->setCurrentItem(list.front()); |
| 510 | } |
| 511 | else |
| 512 | { |
| 513 | m_input_detector->Update(INPUT_DETECT_TIME, {}, INPUT_DETECT_TIME); |
| 514 | } |
| 515 | } |
| 516 | |
| 517 | void IOWindow::ConnectWidgets() |
| 518 | { |
| 519 | connect(m_select_button, &QPushButton::clicked, [this] { AppendSelectedOption(); }); |
| 520 | connect(m_option_list, &QTableWidget::cellDoubleClicked, [this] { AppendSelectedOption(); }); |
| 521 | connect(&Settings::Instance(), &Settings::ReleaseDevices, this, &IOWindow::ReleaseDevices); |
| 522 | connect(&Settings::Instance(), &Settings::DevicesChanged, this, &IOWindow::UpdateDeviceList); |
| 523 | |
| 524 | // Input detection: |
| 525 | // Clicking "Detect" button starts a timer before the actual detection. |
| 526 | auto* const input_detect_start_timer = new QTimer(this); |
| 527 | input_detect_start_timer->setSingleShot(true); |
| 528 | connect(m_detect_button, &QPushButton::clicked, [this, input_detect_start_timer] { |
| 529 | m_detect_button->setText(tr("[ ... ]")); |
| 530 | input_detect_start_timer->start(MappingCommon::INPUT_DETECT_INITIAL_DELAY); |
| 531 | }); |
| 532 | connect(input_detect_start_timer, &QTimer::timeout, [this] { |
| 533 | m_detect_button->setText(tr("[ Press Now ]")); |
| 534 | m_input_detector = std::make_unique<ciface::Core::InputDetector>(); |
| 535 | const auto lock = m_controller->GetStateLock(); |
| 536 | m_input_detector->Start(g_controller_interface, std::array{m_devq.ToString()}); |
| 537 | QtUtils::InstallKeyboardBlocker(m_detect_button, this, &IOWindow::DetectInputComplete); |
| 538 | }); |
| 539 | connect(this, &IOWindow::DetectInputComplete, |
| 540 | [this, initial_text = m_detect_button->text(), input_detect_start_timer] { |
| 541 | input_detect_start_timer->stop(); |
| 542 | m_input_detector.reset(); |
| 543 | m_detect_button->setText(initial_text); |
| 544 | }); |
| 545 | |
| 546 | // Rumble testing: |
| 547 | connect(m_test_button, &QPushButton::clicked, [this] { |
| 548 | // Stop if already started. |
| 549 | if (m_output_test_timer->isActive()) |
| 550 | { |
| 551 | emit IOWindow::TestOutputComplete(); |
| 552 | return; |
| 553 | } |
| 554 | m_test_button->setText(QStringLiteral("[ ... ]")); |
| 555 | m_output_test_timer->start(OUTPUT_TEST_TIME); |
| 556 | const auto lock = m_controller->GetStateLock(); |
| 557 | m_reference->State(1.0); |
| 558 | }); |
| 559 | connect(m_output_test_timer, &QTimer::timeout, |
| 560 | [this, initial_text = m_test_button->text()] { emit TestOutputComplete(); }); |
| 561 | connect(this, &IOWindow::TestOutputComplete, [this, initial_text = m_test_button->text()] { |
| 562 | m_output_test_timer->stop(); |
| 563 | m_test_button->setText(initial_text); |
| 564 | const auto lock = m_controller->GetStateLock(); |
| 565 | m_reference->State(0.0); |
| 566 | }); |
| 567 | |
| 568 | connect(m_button_box, &QDialogButtonBox::clicked, this, &IOWindow::OnDialogButtonPressed); |
| 569 | connect(m_devices_combo, &QComboBox::currentTextChanged, this, &IOWindow::OnDeviceChanged); |
| 570 | connect(m_scalar_spinbox, &QSpinBox::valueChanged, this, &IOWindow::OnRangeChanged); |
| 571 | |
| 572 | connect(m_expression_text, &QPlainTextEdit::textChanged, |
| 573 | [this] { UpdateExpression(m_expression_text->toPlainText().toStdString()); }); |
| 574 | |
| 575 | connect(m_variables_combo, &QComboBox::activated, [this](int index) { |
| 576 | if (index == 0) |
| 577 | return; |
| 578 | |
| 579 | // Reset button. 1 and 3 are separators. |
| 580 | if (index == 2) |
| 581 | { |
| 582 | const auto lock = ControllerEmu::EmulatedController::GetStateLock(); |
| 583 | m_controller->ResetExpressionVariables(); |
| 584 | } |
| 585 | else |
| 586 | { |
| 587 | m_expression_text->insertPlainText(QLatin1Char('$') + m_variables_combo->currentText()); |
| 588 | } |
| 589 | |
| 590 | m_variables_combo->setCurrentIndex(0); |
| 591 | }); |
| 592 | |
| 593 | connect(m_operators_combo, &QComboBox::activated, [this](int index) { |
| 594 | if (index == 0) |
| 595 | return; |
| 596 | |
| 597 | m_expression_text->insertPlainText(m_operators_combo->currentText().left(1)); |
| 598 | |
| 599 | m_operators_combo->setCurrentIndex(0); |
| 600 | }); |
| 601 | |
| 602 | connect(m_functions_combo, &QComboBox::activated, [this](int index) { |
| 603 | if (index == 0) |
| 604 | return; |
| 605 | |
| 606 | m_expression_text->insertPlainText(m_functions_combo->currentText() + QStringLiteral("()")); |
| 607 | |
| 608 | m_functions_combo->setCurrentIndex(0); |
| 609 | }); |
| 610 | |
| 611 | // revert the expression when the window closes without using the OK button |
| 612 | // UpdateExpression will also ensure an active rumble test is stopped when the dialog closes. |
| 613 | connect(this, &IOWindow::finished, [this] { UpdateExpression(m_original_expression); }); |
| 614 | } |
| 615 | |
| 616 | void IOWindow::AppendSelectedOption() |
| 617 | { |
| 618 | if (m_option_list->currentRow() < 0) |
| 619 | return; |
| 620 | |
| 621 | m_expression_text->insertPlainText( |
| 622 | QString::fromStdString(ciface::MappingCommon::GetExpressionForControl( |
| 623 | m_option_list->item(m_option_list->currentRow(), 0)->text().toStdString(), m_devq, |
| 624 | m_controller->GetDefaultDevice()))); |
| 625 | } |
| 626 | |
| 627 | void IOWindow::OnDeviceChanged() |
| 628 | { |
| 629 | const std::string device_name = |
| 630 | m_devices_combo->count() > 0 ? m_devices_combo->currentData().toString().toStdString() : ""; |
| 631 | m_devq.FromString(device_name); |
| 632 | UpdateOptionList(); |
| 633 | } |
| 634 | |
| 635 | void IOWindow::OnDialogButtonPressed(QAbstractButton* button) |
| 636 | { |
| 637 | if (button == m_clear_button) |
| 638 | { |
| 639 | m_expression_text->clear(); |
| 640 | return; |
| 641 | } |
| 642 | |
| 643 | const auto lock = ControllerEmu::EmulatedController::GetStateLock(); |
| 644 | |
| 645 | UpdateExpression(m_expression_text->toPlainText().toStdString()); |
| 646 | |
| 647 | if (ciface::ExpressionParser::ParseStatus::SyntaxError == m_reference->GetParseStatus()) |
| 648 | { |
| 649 | ModalMessageBox::warning(this, tr("Error"), tr("The expression contains a syntax error.")); |
| 650 | } |
| 651 | else |
| 652 | { |
| 653 | // must be the OK button |
| 654 | m_original_expression = m_reference->GetExpression(); |
| 655 | accept(); |
| 656 | } |
| 657 | } |
| 658 | |
| 659 | void IOWindow::OnRangeChanged(int value) |
| 660 | { |
| 661 | m_reference->range = value / 100.0; |
| 662 | emit TestOutputComplete(); |
| 663 | } |
| 664 | |
| 665 | void IOWindow::ReleaseDevices() |
| 666 | { |
| 667 | std::lock_guard lock(m_selected_device_mutex); |
| 668 | m_selected_device = nullptr; |
| 669 | } |
| 670 | |
| 671 | void IOWindow::UpdateOptionList() |
| 672 | { |
| 673 | std::lock_guard lock(m_selected_device_mutex); |
| 674 | m_selected_device = g_controller_interface.FindDevice(m_devq); |
| 675 | m_option_list->setRowCount(0); |
| 676 | |
| 677 | if (m_selected_device == nullptr) |
| 678 | return; |
| 679 | |
| 680 | const auto add_rows = [this](auto& container) { |
| 681 | int row = 0; |
| 682 | for (ciface::Core::Device::Control* control : container) |
| 683 | { |
| 684 | m_option_list->insertRow(row); |
| 685 | |
| 686 | if (control->IsHidden()) |
| 687 | m_option_list->hideRow(row); |
| 688 | |
| 689 | m_option_list->setItem(row, 0, |
| 690 | new QTableWidgetItem(QString::fromStdString(control->GetName()))); |
| 691 | ++row; |
| 692 | } |
| 693 | }; |
| 694 | |
| 695 | if (m_reference->IsInput()) |
| 696 | add_rows(m_selected_device->Inputs()); |
| 697 | else |
| 698 | add_rows(m_selected_device->Outputs()); |
| 699 | } |
| 700 | |
| 701 | void IOWindow::UpdateDeviceList() |
| 702 | { |
| 703 | const QSignalBlocker blocker(m_devices_combo); |
| 704 | |
| 705 | const auto previous_device_name = m_devices_combo->currentData().toString().toStdString(); |
| 706 | |
| 707 | m_devices_combo->clear(); |
| 708 | |
| 709 | // Default to the default device or to the first device if there isn't a default. |
| 710 | // Try to the keep the previous selected device, mark it as disconnected if it's gone, as it could |
| 711 | // reconnect soon after if this is a devices refresh and it would be annoying to lose the value. |
| 712 | const auto default_device_name = m_controller->GetDefaultDevice().ToString(); |
| 713 | int default_device_index = -1; |
| 714 | int previous_device_index = -1; |
| 715 | for (const auto& name : g_controller_interface.GetAllDeviceStrings()) |
| 716 | { |
| 717 | QString qname = QString(); |
| 718 | if (name == default_device_name) |
| 719 | { |
| 720 | default_device_index = m_devices_combo->count(); |
| 721 | // Specify "default" even if we only have one device |
| 722 | qname.append(QLatin1Char{'['} + tr("default") + QStringLiteral("] ")); |
| 723 | } |
| 724 | if (name == previous_device_name) |
| 725 | { |
| 726 | previous_device_index = m_devices_combo->count(); |
| 727 | } |
| 728 | qname.append(QString::fromStdString(name)); |
| 729 | m_devices_combo->addItem(qname, QString::fromStdString(name)); |
| 730 | } |
| 731 | |
| 732 | if (previous_device_index >= 0) |
| 733 | { |
| 734 | m_devices_combo->setCurrentIndex(previous_device_index); |
| 735 | } |
| 736 | else if (!previous_device_name.empty()) |
| 737 | { |
| 738 | const QString qname = QString::fromStdString(previous_device_name); |
| 739 | QString adjusted_qname; |
| 740 | if (previous_device_name == default_device_name) |
| 741 | { |
| 742 | adjusted_qname.append(QLatin1Char{'['} + tr("default") + QStringLiteral("] ")); |
| 743 | } |
| 744 | adjusted_qname.append(QLatin1Char{'['} + tr("disconnected") + QStringLiteral("] ")) |
| 745 | .append(qname); |
| 746 | m_devices_combo->addItem(adjusted_qname, qname); |
| 747 | m_devices_combo->setCurrentIndex(m_devices_combo->count() - 1); |
| 748 | } |
| 749 | else if (default_device_index >= 0) |
| 750 | { |
| 751 | m_devices_combo->setCurrentIndex(default_device_index); |
| 752 | } |
| 753 | else if (m_devices_combo->count() > 0) |
| 754 | { |
| 755 | m_devices_combo->setCurrentIndex(0); |
| 756 | } |
| 757 | // The device object might have changed so we need to always refresh it |
| 758 | OnDeviceChanged(); |
| 759 | } |
| 760 | |
| 761 | void IOWindow::UpdateExpression(std::string new_expression, UpdateMode mode) |
| 762 | { |
| 763 | emit TestOutputComplete(); |
| 764 | |
| 765 | const auto lock = m_controller->GetStateLock(); |
| 766 | if (mode != UpdateMode::Force && new_expression == m_reference->GetExpression()) |
| 767 | return; |
| 768 | |
| 769 | const auto error = m_reference->SetExpression(std::move(new_expression)); |
| 770 | const auto status = m_reference->GetParseStatus(); |
| 771 | m_controller->UpdateSingleControlReference(g_controller_interface, m_reference); |
| 772 | |
| 773 | // This is the only place where we need to update the user variables. Keep the first 4 items. |
| 774 | while (m_variables_combo->count() > 4) |
| 775 | { |
| 776 | m_variables_combo->removeItem(m_variables_combo->count() - 1); |
| 777 | } |
| 778 | for (const auto& expression : m_controller->GetExpressionVariables()) |
| 779 | { |
| 780 | m_variables_combo->addItem(QString::fromStdString(expression.first)); |
| 781 | } |
| 782 | |
| 783 | if (error) |
| 784 | { |
| 785 | m_parse_text->SetShouldPaintStateIndicator(false); |
| 786 | m_parse_text->setText(QString::fromStdString(*error)); |
| 787 | } |
| 788 | else if (status == ciface::ExpressionParser::ParseStatus::EmptyExpression) |
| 789 | { |
| 790 | m_parse_text->SetShouldPaintStateIndicator(false); |
| 791 | m_parse_text->setText(QString()); |
| 792 | } |
| 793 | else if (status != ciface::ExpressionParser::ParseStatus::Successful) |
| 794 | { |
| 795 | m_parse_text->SetShouldPaintStateIndicator(false); |
| 796 | m_parse_text->setText(tr("Invalid Expression.")); |
| 797 | } |
| 798 | else |
| 799 | { |
| 800 | m_parse_text->SetShouldPaintStateIndicator(true); |
| 801 | m_parse_text->setText(QString()); |
| 802 | } |
| 803 | } |
| 804 | |
| 805 | InputStateDelegate::InputStateDelegate(IOWindow* parent, int column, |
| 806 | std::function<ControlState(int row)> state_evaluator) |
| 807 | : QItemDelegate(parent), m_state_evaluator(std::move(state_evaluator)), m_column(column) |
| 808 | { |
| 809 | } |
| 810 | |
| 811 | InputStateLineEdit::InputStateLineEdit(std::function<ControlState()> state_evaluator) |
| 812 | : m_state_evaluator(std::move(state_evaluator)) |
| 813 | { |
| 814 | setReadOnly(true); |
| 815 | } |
| 816 | |
| 817 | static void PaintStateIndicator(QPainter& painter, const QRect& region, ControlState state) |
| 818 | { |
| 819 | const QString state_string = QString::number(state, 'g', 4); |
| 820 | |
| 821 | QRect meter_region = region; |
| 822 | meter_region.setWidth(region.width() * std::clamp(state, 0.0, 1.0)); |
| 823 | |
| 824 | // Create a temporary indicator object to retrieve color constants. |
| 825 | MappingIndicator indicator; |
| 826 | |
| 827 | // Normal text. |
| 828 | painter.setPen(indicator.GetTextColor()); |
| 829 | painter.drawText(region, Qt::AlignCenter, state_string); |
| 830 | |
| 831 | // Input state meter. |
| 832 | painter.fillRect(meter_region, indicator.GetAdjustedInputColor()); |
| 833 | |
| 834 | // Text on top of meter. |
| 835 | painter.setPen(indicator.GetAltTextColor()); |
| 836 | painter.setClipping(true); |
| 837 | painter.setClipRect(meter_region); |
| 838 | painter.drawText(region, Qt::AlignCenter, state_string); |
| 839 | } |
| 840 | |
| 841 | void InputStateDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, |
| 842 | const QModelIndex& index) const |
| 843 | { |
| 844 | QItemDelegate::paint(painter, option, index); |
| 845 | |
| 846 | if (index.column() != m_column) |
| 847 | return; |
| 848 | |
| 849 | painter->save(); |
| 850 | PaintStateIndicator(*painter, option.rect, m_state_evaluator(index.row())); |
| 851 | painter->restore(); |
| 852 | } |
| 853 | |
| 854 | void InputStateLineEdit::SetShouldPaintStateIndicator(bool value) |
| 855 | { |
| 856 | m_should_paint_state_indicator = value; |
| 857 | } |
| 858 | |
| 859 | void InputStateLineEdit::paintEvent(QPaintEvent* event) |
| 860 | { |
| 861 | QLineEdit::paintEvent(event); |
| 862 | |
| 863 | if (!m_should_paint_state_indicator) |
| 864 | return; |
| 865 | |
| 866 | QPainter painter(this); |
| 867 | PaintStateIndicator(painter, this->rect(), m_state_evaluator()); |
| 868 | } |