| 1 | // Copyright 2021 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #include "DolphinQt/CheatSearchWidget.h" |
| 5 | |
| 6 | #include <algorithm> |
| 7 | #include <optional> |
| 8 | #include <ranges> |
| 9 | #include <string> |
| 10 | #include <unordered_map> |
| 11 | #include <utility> |
| 12 | #include <vector> |
| 13 | |
| 14 | #include <QCheckBox> |
| 15 | #include <QComboBox> |
| 16 | #include <QCursor> |
| 17 | #include <QHBoxLayout> |
| 18 | #include <QInputDialog> |
| 19 | #include <QLabel> |
| 20 | #include <QLineEdit> |
| 21 | #include <QMenu> |
| 22 | #include <QPushButton> |
| 23 | #include <QSettings> |
| 24 | #include <QSignalBlocker> |
| 25 | #include <QString> |
| 26 | #include <QTableWidget> |
| 27 | #include <QVBoxLayout> |
| 28 | |
| 29 | #include <fmt/format.h> |
| 30 | |
| 31 | #include "Core/ActionReplay.h" |
| 32 | #include "Core/CheatGeneration.h" |
| 33 | #include "Core/CheatSearch.h" |
| 34 | #include "Core/ConfigManager.h" |
| 35 | #include "Core/Core.h" |
| 36 | #include "Core/PowerPC/BreakPoints.h" |
| 37 | #include "Core/PowerPC/PowerPC.h" |
| 38 | #include "Core/System.h" |
| 39 | |
| 40 | #include "DolphinQt/Config/CheatCodeEditor.h" |
| 41 | #include "DolphinQt/Config/CheatWarningWidget.h" |
| 42 | #include "DolphinQt/Host.h" |
| 43 | #include "DolphinQt/QtUtils/WrapInScrollArea.h" |
| 44 | #include "DolphinQt/Settings.h" |
| 45 | |
| 46 | constexpr size_t TABLE_MAX_ROWS = 1000; |
| 47 | |
| 48 | constexpr int ADDRESS_TABLE_ADDRESS_ROLE = Qt::UserRole; |
| 49 | constexpr int ADDRESS_TABLE_RESULT_INDEX_ROLE = Qt::UserRole + 1; |
| 50 | constexpr int ADDRESS_TABLE_COLUMN_INDEX_DESCRIPTION = 0; |
| 51 | constexpr int ADDRESS_TABLE_COLUMN_INDEX_ADDRESS = 1; |
| 52 | constexpr int ADDRESS_TABLE_COLUMN_INDEX_LAST_VALUE = 2; |
| 53 | constexpr int ADDRESS_TABLE_COLUMN_INDEX_CURRENT_VALUE = 3; |
| 54 | |
| 55 | namespace |
| 56 | { |
| 57 | int GetDataTypeByteSize(Cheats::DataType data_type) |
| 58 | { |
| 59 | switch (data_type) |
| 60 | { |
| 61 | case Cheats::DataType::U8: |
| 62 | case Cheats::DataType::S8: |
| 63 | return 1; |
| 64 | case Cheats::DataType::U16: |
| 65 | case Cheats::DataType::S16: |
| 66 | return 2; |
| 67 | case Cheats::DataType::U32: |
| 68 | case Cheats::DataType::S32: |
| 69 | case Cheats::DataType::F32: |
| 70 | return 4; |
| 71 | case Cheats::DataType::U64: |
| 72 | case Cheats::DataType::S64: |
| 73 | case Cheats::DataType::F64: |
| 74 | return 8; |
| 75 | default: |
| 76 | return 1; |
| 77 | } |
| 78 | } |
| 79 | } // namespace |
| 80 | |
| 81 | CheatSearchWidget::CheatSearchWidget(Core::System& system, |
| 82 | std::unique_ptr<Cheats::CheatSearchSessionBase> session, |
| 83 | QWidget* parent) |
| 84 | : QWidget(parent), m_system(system), m_last_value_session(std::move(session)) |
| 85 | { |
| 86 | setAttribute(Qt::WA_DeleteOnClose); |
| 87 | CreateWidgets(); |
| 88 | ConnectWidgets(); |
| 89 | OnValueSourceChanged(); |
| 90 | RecreateGUITable(); |
| 91 | } |
| 92 | |
| 93 | CheatSearchWidget::~CheatSearchWidget() |
| 94 | { |
| 95 | auto& settings = Settings::GetQSettings(); |
| 96 | settings.setValue(QStringLiteral("cheatsearchwidget/displayhex"), |
| 97 | m_display_values_in_hex_checkbox->isChecked()); |
| 98 | settings.setValue(QStringLiteral("cheatsearchwidget/autoupdatecurrentvalues"), |
| 99 | m_autoupdate_current_values->isChecked()); |
| 100 | |
| 101 | if (m_last_value_session->IsIntegerType()) |
| 102 | { |
| 103 | settings.setValue(QStringLiteral("cheatsearchwidget/parsehex"), |
| 104 | m_parse_values_as_hex_checkbox->isChecked()); |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | Q_DECLARE_METATYPE(Cheats::CompareType); |
| 109 | Q_DECLARE_METATYPE(Cheats::FilterType); |
| 110 | |
| 111 | void CheatSearchWidget::CreateWidgets() |
| 112 | { |
| 113 | QLabel* session_info_label = new QLabel(); |
| 114 | { |
| 115 | QString ranges; |
| 116 | const size_t range_count = m_last_value_session->GetMemoryRangeCount(); |
| 117 | switch (range_count) |
| 118 | { |
| 119 | case 1: |
| 120 | { |
| 121 | const auto m = m_last_value_session->GetMemoryRange(0); |
| 122 | ranges = |
| 123 | tr("[%1, %2]") |
| 124 | .arg(QString::fromStdString(fmt::format("0x{0:08x}", m.m_start))) |
| 125 | .arg(QString::fromStdString(fmt::format("0x{0:08x}", m.m_start + m.m_length - 1))); |
| 126 | break; |
| 127 | } |
| 128 | case 2: |
| 129 | { |
| 130 | const auto m0 = m_last_value_session->GetMemoryRange(0); |
| 131 | const auto m1 = m_last_value_session->GetMemoryRange(1); |
| 132 | ranges = |
| 133 | tr("[%1, %2] and [%3, %4]") |
| 134 | .arg(QString::fromStdString(fmt::format("0x{0:08x}", m0.m_start))) |
| 135 | .arg(QString::fromStdString(fmt::format("0x{0:08x}", m0.m_start + m0.m_length - 1))) |
| 136 | .arg(QString::fromStdString(fmt::format("0x{0:08x}", m1.m_start))) |
| 137 | .arg(QString::fromStdString(fmt::format("0x{0:08x}", m1.m_start + m1.m_length - 1))); |
| 138 | break; |
| 139 | } |
| 140 | default: |
| 141 | ranges = tr("%1 memory ranges").arg(range_count); |
| 142 | break; |
| 143 | } |
| 144 | |
| 145 | QString space; |
| 146 | switch (m_last_value_session->GetAddressSpace()) |
| 147 | { |
| 148 | case PowerPC::RequestedAddressSpace::Effective: |
| 149 | space = tr("Address space by CPU state"); |
| 150 | break; |
| 151 | case PowerPC::RequestedAddressSpace::Physical: |
| 152 | space = tr("Physical address space"); |
| 153 | break; |
| 154 | case PowerPC::RequestedAddressSpace::Virtual: |
| 155 | space = tr("Virtual address space"); |
| 156 | break; |
| 157 | default: |
| 158 | space = tr("Unknown address space"); |
| 159 | break; |
| 160 | } |
| 161 | |
| 162 | QString type; |
| 163 | switch (m_last_value_session->GetDataType()) |
| 164 | { |
| 165 | case Cheats::DataType::U8: |
| 166 | type = tr("8-bit Unsigned Integer"); |
| 167 | break; |
| 168 | case Cheats::DataType::U16: |
| 169 | type = tr("16-bit Unsigned Integer"); |
| 170 | break; |
| 171 | case Cheats::DataType::U32: |
| 172 | type = tr("32-bit Unsigned Integer"); |
| 173 | break; |
| 174 | case Cheats::DataType::U64: |
| 175 | type = tr("64-bit Unsigned Integer"); |
| 176 | break; |
| 177 | case Cheats::DataType::S8: |
| 178 | type = tr("8-bit Signed Integer"); |
| 179 | break; |
| 180 | case Cheats::DataType::S16: |
| 181 | type = tr("16-bit Signed Integer"); |
| 182 | break; |
| 183 | case Cheats::DataType::S32: |
| 184 | type = tr("32-bit Signed Integer"); |
| 185 | break; |
| 186 | case Cheats::DataType::S64: |
| 187 | type = tr("64-bit Signed Integer"); |
| 188 | break; |
| 189 | case Cheats::DataType::F32: |
| 190 | type = tr("32-bit Float"); |
| 191 | break; |
| 192 | case Cheats::DataType::F64: |
| 193 | type = tr("64-bit Float"); |
| 194 | break; |
| 195 | default: |
| 196 | type = tr("Unknown data type"); |
| 197 | break; |
| 198 | } |
| 199 | const QString aligned = m_last_value_session->GetAligned() ? tr("aligned") : tr("unaligned"); |
| 200 | session_info_label->setText(tr("%1, %2, %3, %4").arg(ranges).arg(space).arg(type).arg(aligned)); |
| 201 | session_info_label->setWordWrap(true); |
| 202 | } |
| 203 | |
| 204 | // i18n: This label is followed by a dropdown where the user can select things like "is equal to" |
| 205 | // or "is less than or equal to", followed by another dropdown where the user can select "any |
| 206 | // value", "last value", or "this value:". These three UI elements are intended to form a sentence |
| 207 | // together. Because the UI elements can't be reordered by a translation, you may have to give |
| 208 | // up on the idea of having them form a sentence depending on the grammar of your target language. |
| 209 | auto* instructions_label = new QLabel(tr("Keep addresses where value in memory")); |
| 210 | |
| 211 | auto* value_layout = new QHBoxLayout(); |
| 212 | m_compare_type_dropdown = new QComboBox(); |
| 213 | m_compare_type_dropdown->addItem(tr("is equal to"), |
| 214 | QVariant::fromValue(Cheats::CompareType::Equal)); |
| 215 | m_compare_type_dropdown->addItem(tr("is not equal to"), |
| 216 | QVariant::fromValue(Cheats::CompareType::NotEqual)); |
| 217 | m_compare_type_dropdown->addItem(tr("is less than"), |
| 218 | QVariant::fromValue(Cheats::CompareType::Less)); |
| 219 | m_compare_type_dropdown->addItem(tr("is less than or equal to"), |
| 220 | QVariant::fromValue(Cheats::CompareType::LessOrEqual)); |
| 221 | m_compare_type_dropdown->addItem(tr("is greater than"), |
| 222 | QVariant::fromValue(Cheats::CompareType::Greater)); |
| 223 | m_compare_type_dropdown->addItem(tr("is greater than or equal to"), |
| 224 | QVariant::fromValue(Cheats::CompareType::GreaterOrEqual)); |
| 225 | value_layout->addWidget(m_compare_type_dropdown); |
| 226 | |
| 227 | m_value_source_dropdown = new QComboBox(); |
| 228 | m_value_source_dropdown->addItem( |
| 229 | tr("this value:"), QVariant::fromValue(Cheats::FilterType::CompareAgainstSpecificValue)); |
| 230 | m_value_source_dropdown->addItem( |
| 231 | tr("last value"), QVariant::fromValue(Cheats::FilterType::CompareAgainstLastValue)); |
| 232 | m_value_source_dropdown->addItem(tr("any value"), |
| 233 | QVariant::fromValue(Cheats::FilterType::DoNotFilter)); |
| 234 | value_layout->addWidget(m_value_source_dropdown); |
| 235 | |
| 236 | m_given_value_text = new QLineEdit(); |
| 237 | value_layout->addWidget(m_given_value_text); |
| 238 | |
| 239 | auto& settings = Settings::GetQSettings(); |
| 240 | m_parse_values_as_hex_checkbox = new QCheckBox(tr("Parse as Hex")); |
| 241 | if (m_last_value_session->IsIntegerType()) |
| 242 | { |
| 243 | m_parse_values_as_hex_checkbox->setChecked( |
| 244 | settings.value(QStringLiteral("cheatsearchwidget/parsehex")).toBool()); |
| 245 | value_layout->addWidget(m_parse_values_as_hex_checkbox); |
| 246 | } |
| 247 | |
| 248 | auto* button_layout = new QHBoxLayout(); |
| 249 | m_next_scan_button = new QPushButton(tr("Search and Filter")); |
| 250 | button_layout->addWidget(m_next_scan_button); |
| 251 | m_refresh_values_button = new QPushButton(tr("Refresh Current Values")); |
| 252 | button_layout->addWidget(m_refresh_values_button); |
| 253 | m_reset_button = new QPushButton(tr("Reset Results")); |
| 254 | button_layout->addWidget(m_reset_button); |
| 255 | |
| 256 | m_address_table = new QTableWidget(); |
| 257 | m_address_table->setContextMenuPolicy(Qt::CustomContextMenu); |
| 258 | m_address_table->setSelectionBehavior(QAbstractItemView::SelectRows); |
| 259 | |
| 260 | m_info_label_1 = new QLabel(tr("Waiting for first scan...")); |
| 261 | m_info_label_2 = new QLabel(); |
| 262 | |
| 263 | auto* const checkboxes_layout = new QHBoxLayout(); |
| 264 | m_display_values_in_hex_checkbox = new QCheckBox(tr("Display values in Hex")); |
| 265 | m_display_values_in_hex_checkbox->setChecked( |
| 266 | settings.value(QStringLiteral("cheatsearchwidget/displayhex")).toBool()); |
| 267 | checkboxes_layout->addWidget(m_display_values_in_hex_checkbox); |
| 268 | checkboxes_layout->setStretchFactor(m_display_values_in_hex_checkbox, 1); |
| 269 | |
| 270 | m_autoupdate_current_values = new QCheckBox(tr("Automatically update Current Values")); |
| 271 | m_autoupdate_current_values->setChecked( |
| 272 | settings.value(QStringLiteral("cheatsearchwidget/autoupdatecurrentvalues"), true).toBool()); |
| 273 | checkboxes_layout->addWidget(m_autoupdate_current_values); |
| 274 | checkboxes_layout->setStretchFactor(m_autoupdate_current_values, 2); |
| 275 | |
| 276 | auto* const layout = new QVBoxLayout{this}; |
| 277 | layout->addWidget(session_info_label); |
| 278 | layout->addWidget(instructions_label); |
| 279 | layout->addLayout(value_layout); |
| 280 | layout->addLayout(button_layout); |
| 281 | layout->addLayout(checkboxes_layout); |
| 282 | layout->addWidget(m_info_label_1); |
| 283 | layout->addWidget(m_info_label_2); |
| 284 | layout->addWidget(m_address_table); |
| 285 | } |
| 286 | |
| 287 | void CheatSearchWidget::ConnectWidgets() |
| 288 | { |
| 289 | connect(m_next_scan_button, &QPushButton::clicked, this, &CheatSearchWidget::OnNextScanClicked); |
| 290 | connect(m_refresh_values_button, &QPushButton::clicked, this, |
| 291 | &CheatSearchWidget::OnRefreshClicked); |
| 292 | connect(m_reset_button, &QPushButton::clicked, this, &CheatSearchWidget::OnResetClicked); |
| 293 | connect(m_address_table, &QTableWidget::itemChanged, this, |
| 294 | &CheatSearchWidget::OnAddressTableItemChanged); |
| 295 | connect(m_address_table, &QTableWidget::customContextMenuRequested, this, |
| 296 | &CheatSearchWidget::OnAddressTableContextMenu); |
| 297 | connect(m_value_source_dropdown, &QComboBox::currentTextChanged, this, |
| 298 | &CheatSearchWidget::OnValueSourceChanged); |
| 299 | connect(m_display_values_in_hex_checkbox, &QCheckBox::toggled, this, |
| 300 | &CheatSearchWidget::OnDisplayHexCheckboxStateChanged); |
| 301 | } |
| 302 | |
| 303 | void CheatSearchWidget::OnNextScanClicked() |
| 304 | { |
| 305 | Core::CPUThreadGuard guard{m_system}; |
| 306 | |
| 307 | const bool had_old_results = m_last_value_session->WasFirstSearchDone(); |
| 308 | |
| 309 | const auto filter_type = m_value_source_dropdown->currentData().value<Cheats::FilterType>(); |
| 310 | if (filter_type == Cheats::FilterType::CompareAgainstLastValue && !had_old_results) |
| 311 | { |
| 312 | m_info_label_1->setText(tr("Cannot compare against last value on first search.")); |
| 313 | return; |
| 314 | } |
| 315 | m_last_value_session->SetFilterType(filter_type); |
| 316 | m_last_value_session->SetCompareType( |
| 317 | m_compare_type_dropdown->currentData().value<Cheats::CompareType>()); |
| 318 | if (filter_type == Cheats::FilterType::CompareAgainstSpecificValue) |
| 319 | { |
| 320 | QString search_value = m_given_value_text->text(); |
| 321 | if (m_last_value_session->IsIntegerType() || m_last_value_session->IsFloatingType()) |
| 322 | search_value = search_value.simplified().remove(QLatin1Char(' ')); |
| 323 | if (!m_last_value_session->SetValueFromString(search_value.toStdString(), |
| 324 | m_parse_values_as_hex_checkbox->isChecked())) |
| 325 | { |
| 326 | m_info_label_1->setText(tr("Failed to parse given value into target data type.")); |
| 327 | return; |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | const size_t old_count = m_last_value_session->GetResultCount(); |
| 332 | const Cheats::SearchErrorCode error_code = m_last_value_session->RunSearch(guard); |
| 333 | |
| 334 | if (error_code == Cheats::SearchErrorCode::Success) |
| 335 | { |
| 336 | const size_t new_count = m_last_value_session->GetResultCount(); |
| 337 | const size_t new_valid_count = m_last_value_session->GetValidValueCount(); |
| 338 | m_info_label_1->setText(tr("Scan succeeded.")); |
| 339 | |
| 340 | if (had_old_results) |
| 341 | { |
| 342 | const QString removed_str = |
| 343 | tr("%n address(es) were removed.", "", static_cast<int>(old_count - new_count)); |
| 344 | const QString remain_str = tr("%n address(es) remain.", "", static_cast<int>(new_count)); |
| 345 | |
| 346 | if (new_valid_count == new_count) |
| 347 | { |
| 348 | m_info_label_2->setText(tr("%1 %2").arg(removed_str).arg(remain_str)); |
| 349 | } |
| 350 | else |
| 351 | { |
| 352 | const QString inaccessible_str = |
| 353 | tr("%n address(es) could not be accessed in emulated memory.", "", |
| 354 | static_cast<int>(new_count - new_valid_count)); |
| 355 | |
| 356 | m_info_label_2->setText( |
| 357 | tr("%1 %2 %3").arg(removed_str).arg(remain_str).arg(inaccessible_str)); |
| 358 | } |
| 359 | } |
| 360 | else |
| 361 | { |
| 362 | const QString found_str = tr("Found %n address(es).", "", static_cast<int>(new_count)); |
| 363 | |
| 364 | if (new_valid_count == new_count) |
| 365 | { |
| 366 | m_info_label_2->setText(found_str); |
| 367 | } |
| 368 | else |
| 369 | { |
| 370 | const QString inaccessible_str = |
| 371 | tr("%n address(es) could not be accessed in emulated memory.", "", |
| 372 | static_cast<int>(new_count - new_valid_count)); |
| 373 | |
| 374 | m_info_label_2->setText(tr("%1 %2").arg(found_str).arg(inaccessible_str)); |
| 375 | } |
| 376 | } |
| 377 | |
| 378 | m_address_table_current_values.clear(); |
| 379 | const bool show_in_hex = m_display_values_in_hex_checkbox->isChecked(); |
| 380 | const size_t row_count = GetTableRowCount(); |
| 381 | for (size_t i = 0; i < row_count; ++i) |
| 382 | { |
| 383 | m_address_table_current_values[m_last_value_session->GetResultAddress(i)] = |
| 384 | m_last_value_session->GetResultValueAsString(i, show_in_hex); |
| 385 | } |
| 386 | |
| 387 | RecreateGUITable(); |
| 388 | } |
| 389 | else |
| 390 | { |
| 391 | switch (error_code) |
| 392 | { |
| 393 | case Cheats::SearchErrorCode::NoEmulationActive: |
| 394 | m_info_label_1->setText(tr("No game is running.")); |
| 395 | break; |
| 396 | case Cheats::SearchErrorCode::InvalidParameters: |
| 397 | m_info_label_1->setText(tr("Invalid parameters given to search.")); |
| 398 | break; |
| 399 | case Cheats::SearchErrorCode::VirtualAddressesCurrentlyNotAccessible: |
| 400 | m_info_label_1->setText( |
| 401 | tr("Search currently not possible in virtual address space. Please run " |
| 402 | "the game for a bit and try again.")); |
| 403 | break; |
| 404 | default: |
| 405 | m_info_label_1->setText(tr("Unknown error occurred.")); |
| 406 | break; |
| 407 | } |
| 408 | } |
| 409 | } |
| 410 | |
| 411 | bool CheatSearchWidget::UpdateTableRows(const Core::CPUThreadGuard& guard, const size_t begin_index, |
| 412 | const size_t end_index, const UpdateSource source) |
| 413 | { |
| 414 | const bool update_status_text = source == UpdateSource::User; |
| 415 | |
| 416 | const auto tmp = m_last_value_session->ClonePartial(begin_index, end_index); |
| 417 | tmp->SetFilterType(Cheats::FilterType::DoNotFilter); |
| 418 | |
| 419 | const Cheats::SearchErrorCode error_code = tmp->RunSearch(guard); |
| 420 | if (error_code != Cheats::SearchErrorCode::Success) |
| 421 | { |
| 422 | if (update_status_text) |
| 423 | m_info_label_1->setText(tr("Refresh failed. Please run the game for a bit and try again.")); |
| 424 | return false; |
| 425 | } |
| 426 | |
| 427 | const bool show_in_hex = m_display_values_in_hex_checkbox->isChecked(); |
| 428 | const size_t result_count_to_display = tmp->GetResultCount(); |
| 429 | for (size_t i = 0; i < result_count_to_display; ++i) |
| 430 | { |
| 431 | m_address_table_current_values[tmp->GetResultAddress(i)] = |
| 432 | tmp->GetResultValueAsString(i, show_in_hex); |
| 433 | } |
| 434 | |
| 435 | RefreshGUICurrentValues(begin_index, end_index); |
| 436 | if (update_status_text) |
| 437 | m_info_label_1->setText(tr("Refreshed current values.")); |
| 438 | return true; |
| 439 | } |
| 440 | |
| 441 | void CheatSearchWidget::UpdateTableVisibleCurrentValues(const UpdateSource source) |
| 442 | { |
| 443 | if (source == UpdateSource::Auto && !m_autoupdate_current_values->isChecked()) |
| 444 | return; |
| 445 | |
| 446 | if (m_address_table->rowCount() == 0) |
| 447 | return; |
| 448 | |
| 449 | UpdateTableRows(Core::CPUThreadGuard{m_system}, GetVisibleRowsBeginIndex(), |
| 450 | GetVisibleRowsEndIndex(), source); |
| 451 | } |
| 452 | |
| 453 | bool CheatSearchWidget::UpdateTableAllCurrentValues(const UpdateSource source) |
| 454 | { |
| 455 | if (source == UpdateSource::Auto && !m_autoupdate_current_values->isChecked()) |
| 456 | return false; |
| 457 | |
| 458 | const size_t result_count = m_address_table->rowCount(); |
| 459 | if (result_count == 0) |
| 460 | { |
| 461 | if (source == UpdateSource::User) |
| 462 | m_info_label_1->setText(tr("Cannot refresh without results.")); |
| 463 | return false; |
| 464 | } |
| 465 | |
| 466 | return UpdateTableRows(Core::CPUThreadGuard{m_system}, 0, result_count, source); |
| 467 | } |
| 468 | |
| 469 | void CheatSearchWidget::OnRefreshClicked() |
| 470 | { |
| 471 | UpdateTableAllCurrentValues(UpdateSource::User); |
| 472 | } |
| 473 | |
| 474 | void CheatSearchWidget::OnResetClicked() |
| 475 | { |
| 476 | m_last_value_session->ResetResults(); |
| 477 | m_address_table_current_values.clear(); |
| 478 | |
| 479 | RecreateGUITable(); |
| 480 | m_info_label_1->setText(tr("Waiting for first scan...")); |
| 481 | m_info_label_2->clear(); |
| 482 | } |
| 483 | |
| 484 | void CheatSearchWidget::OnAddressTableItemChanged(QTableWidgetItem* item) |
| 485 | { |
| 486 | const u32 address = item->data(ADDRESS_TABLE_ADDRESS_ROLE).toUInt(); |
| 487 | const int column = item->column(); |
| 488 | |
| 489 | switch (column) |
| 490 | { |
| 491 | case ADDRESS_TABLE_COLUMN_INDEX_DESCRIPTION: |
| 492 | { |
| 493 | m_address_table_user_data[address].m_description = item->text().toStdString(); |
| 494 | break; |
| 495 | } |
| 496 | default: |
| 497 | break; |
| 498 | } |
| 499 | } |
| 500 | |
| 501 | int CheatSearchWidget::GetVisibleRowsBeginIndex() const |
| 502 | { |
| 503 | return m_address_table->rowAt(0); |
| 504 | } |
| 505 | |
| 506 | int CheatSearchWidget::GetVisibleRowsEndIndex() const |
| 507 | { |
| 508 | const int row_at_bottom_of_viewport = m_address_table->rowAt(m_address_table->height()); |
| 509 | const int end_index = m_address_table->rowCount(); |
| 510 | return row_at_bottom_of_viewport == -1 ? end_index : row_at_bottom_of_viewport + 1; |
| 511 | } |
| 512 | |
| 513 | void CheatSearchWidget::OnAddressTableContextMenu() |
| 514 | { |
| 515 | if (m_address_table->selectedItems().isEmpty()) |
| 516 | return; |
| 517 | |
| 518 | std::vector<const QTableWidgetItem*> selected_items = GetSelectedAddressTableItems(); |
| 519 | |
| 520 | QMenu* menu = new QMenu(this); |
| 521 | menu->setAttribute(Qt::WA_DeleteOnClose, true); |
| 522 | |
| 523 | menu->addAction(tr("Show in memory"), this, [this] { |
| 524 | auto* item = m_address_table->selectedItems()[0]; |
| 525 | const u32 address = item->data(ADDRESS_TABLE_ADDRESS_ROLE).toUInt(); |
| 526 | emit ShowMemory(address); |
| 527 | }); |
| 528 | menu->addAction(tr("Add to watch"), this, [this, selected_items] { |
| 529 | for (auto* const item : selected_items) |
| 530 | { |
| 531 | const u32 address = item->data(ADDRESS_TABLE_ADDRESS_ROLE).toUInt(); |
| 532 | const QString name = QStringLiteral("mem_%1").arg(address, 8, 16, QLatin1Char('0')); |
| 533 | emit RequestWatch(name, address); |
| 534 | } |
| 535 | }); |
| 536 | menu->addAction(tr("Generate Action Replay Code(s)"), this, &CheatSearchWidget::GenerateARCodes); |
| 537 | menu->addAction(tr("Write value"), this, &CheatSearchWidget::WriteValue); |
| 538 | menu->addAction(tr("Delete Address"), this, [this, selected_items] { |
| 539 | // Process in reverse so removal won't change the index of items about to be processed. |
| 540 | for (auto* const item : selected_items | std::views::reverse) |
| 541 | { |
| 542 | const u32 index = item->data(ADDRESS_TABLE_RESULT_INDEX_ROLE).toUInt(); |
| 543 | m_last_value_session->RemoveResult(index); |
| 544 | } |
| 545 | RecreateGUITable(); |
| 546 | }); |
| 547 | |
| 548 | if (m_last_value_session->GetAddressSpace() == PowerPC::RequestedAddressSpace::Virtual) |
| 549 | { |
| 550 | menu->addAction(tr("Add Read/Write Breakpoint(s)"), this, |
| 551 | [this]() { AddMemoryBreakpoints("rw"); }); |
| 552 | menu->addAction(tr("Add Write Breakpoint(s)"), this, [this]() { AddMemoryBreakpoints("w"); }); |
| 553 | menu->addAction(tr("Add Read Breakpoint(s)"), this, [this]() { AddMemoryBreakpoints("r"); }); |
| 554 | } |
| 555 | |
| 556 | menu->exec(QCursor::pos()); |
| 557 | } |
| 558 | |
| 559 | void CheatSearchWidget::AddMemoryBreakpoints(std::string_view type) |
| 560 | { |
| 561 | if (m_last_value_session->GetAddressSpace() != PowerPC::RequestedAddressSpace::Virtual) |
| 562 | return; |
| 563 | |
| 564 | const int last_byte_offset = GetDataTypeByteSize(m_last_value_session->GetDataType()) - 1; |
| 565 | |
| 566 | MemChecks::TMemChecksStr bps; |
| 567 | |
| 568 | for (auto& item : GetSelectedAddressTableItems()) |
| 569 | { |
| 570 | const u32 addr = item->data(ADDRESS_TABLE_ADDRESS_ROLE).toUInt(); |
| 571 | std::string bp = fmt::format("{:08x} {:08x} nbl{}", addr, addr + last_byte_offset, type); |
| 572 | bps.push_back(bp); |
| 573 | } |
| 574 | |
| 575 | auto& memchecks = m_system.GetPowerPC().GetMemChecks(); |
| 576 | memchecks.AddFromStrings(bps); |
| 577 | emit Host::GetInstance()->PPCBreakpointsChanged(); |
| 578 | } |
| 579 | |
| 580 | void CheatSearchWidget::OnValueSourceChanged() |
| 581 | { |
| 582 | const auto filter_type = m_value_source_dropdown->currentData().value<Cheats::FilterType>(); |
| 583 | const bool is_value_search = filter_type == Cheats::FilterType::CompareAgainstSpecificValue; |
| 584 | m_given_value_text->setEnabled(is_value_search); |
| 585 | m_parse_values_as_hex_checkbox->setEnabled(is_value_search && |
| 586 | m_last_value_session->IsIntegerType()); |
| 587 | } |
| 588 | |
| 589 | void CheatSearchWidget::OnDisplayHexCheckboxStateChanged() |
| 590 | { |
| 591 | if (!m_last_value_session->WasFirstSearchDone()) |
| 592 | return; |
| 593 | |
| 594 | // If the game is running CheatsManager::OnFrameEnd will update values automatically. |
| 595 | if (Core::GetState(m_system) != Core::State::Running) |
| 596 | UpdateTableAllCurrentValues(UpdateSource::User); |
| 597 | } |
| 598 | |
| 599 | void CheatSearchWidget::GenerateARCodes() |
| 600 | { |
| 601 | if (m_address_table->selectedItems().isEmpty()) |
| 602 | return; |
| 603 | |
| 604 | bool had_success = false; |
| 605 | bool had_multiple_errors = false; |
| 606 | std::optional<Cheats::GenerateActionReplayCodeErrorCode> error_code; |
| 607 | |
| 608 | for (auto* const item : GetSelectedAddressTableItems()) |
| 609 | { |
| 610 | const u32 index = item->data(ADDRESS_TABLE_RESULT_INDEX_ROLE).toUInt(); |
| 611 | const auto result = Cheats::GenerateActionReplayCode(*m_last_value_session, index); |
| 612 | if (result) |
| 613 | { |
| 614 | emit ActionReplayCodeGenerated(*result); |
| 615 | had_success = true; |
| 616 | } |
| 617 | else |
| 618 | { |
| 619 | const auto new_error_code = result.error(); |
| 620 | if (!error_code.has_value()) |
| 621 | { |
| 622 | error_code = new_error_code; |
| 623 | } |
| 624 | else if (error_code != new_error_code) |
| 625 | { |
| 626 | had_multiple_errors = true; |
| 627 | } |
| 628 | } |
| 629 | } |
| 630 | |
| 631 | if (error_code.has_value()) |
| 632 | { |
| 633 | if (had_multiple_errors) |
| 634 | { |
| 635 | m_info_label_1->setText(tr("Multiple errors occurred while generating AR codes.")); |
| 636 | } |
| 637 | else |
| 638 | { |
| 639 | switch (*error_code) |
| 640 | { |
| 641 | case Cheats::GenerateActionReplayCodeErrorCode::NotVirtualMemory: |
| 642 | m_info_label_1->setText(tr("Can only generate AR code for values in virtual memory.")); |
| 643 | break; |
| 644 | case Cheats::GenerateActionReplayCodeErrorCode::InvalidAddress: |
| 645 | m_info_label_1->setText(tr("Cannot generate AR code for this address.")); |
| 646 | break; |
| 647 | default: |
| 648 | m_info_label_1->setText(tr("Internal error while generating AR code.")); |
| 649 | break; |
| 650 | } |
| 651 | } |
| 652 | } |
| 653 | else if (had_success) |
| 654 | { |
| 655 | m_info_label_1->setText(tr("Generated AR code(s).")); |
| 656 | } |
| 657 | } |
| 658 | |
| 659 | void CheatSearchWidget::WriteValue() |
| 660 | { |
| 661 | if (m_address_table->selectedItems().isEmpty()) |
| 662 | return; |
| 663 | |
| 664 | bool ok{}; |
| 665 | QString text = QInputDialog::getText(this, tr("Write value"), tr("Value:"), QLineEdit::Normal, |
| 666 | QString{}, &ok); |
| 667 | |
| 668 | if (!ok || !m_last_value_session->SetValueFromString(text.toStdString(), |
| 669 | m_parse_values_as_hex_checkbox->isChecked())) |
| 670 | { |
| 671 | m_info_label_1->setText(tr("Invalid value.")); |
| 672 | return; |
| 673 | } |
| 674 | |
| 675 | auto items = GetSelectedAddressTableItems(); |
| 676 | std::vector<u32> addresses(items.size()); |
| 677 | std::transform(items.begin(), items.end(), addresses.begin(), [](const QTableWidgetItem* item) { |
| 678 | return item->data(ADDRESS_TABLE_ADDRESS_ROLE).toUInt(); |
| 679 | }); |
| 680 | Core::CPUThreadGuard guard{m_system}; |
| 681 | if (!m_last_value_session->WriteValue(guard, std::span<u32>(addresses))) |
| 682 | { |
| 683 | m_info_label_1->setText(tr("There was an error writing (some) values.")); |
| 684 | } |
| 685 | UpdateTableAllCurrentValues(UpdateSource::User); |
| 686 | } |
| 687 | |
| 688 | size_t CheatSearchWidget::GetTableRowCount() const |
| 689 | { |
| 690 | return std::min(TABLE_MAX_ROWS, m_last_value_session->GetResultCount()); |
| 691 | } |
| 692 | |
| 693 | void CheatSearchWidget::RefreshCurrentValueTableItem( |
| 694 | QTableWidgetItem* const current_value_table_item) |
| 695 | { |
| 696 | const auto address = current_value_table_item->data(ADDRESS_TABLE_ADDRESS_ROLE).toUInt(); |
| 697 | const auto curr_val_iter = m_address_table_current_values.find(address); |
| 698 | if (curr_val_iter != m_address_table_current_values.end()) |
| 699 | current_value_table_item->setText(QString::fromStdString(curr_val_iter->second)); |
| 700 | else |
| 701 | current_value_table_item->setText(QStringLiteral("---")); |
| 702 | } |
| 703 | |
| 704 | void CheatSearchWidget::RefreshGUICurrentValues(const size_t begin_index, const size_t end_index) |
| 705 | { |
| 706 | for (size_t i = begin_index; i < end_index; ++i) |
| 707 | { |
| 708 | QTableWidgetItem* const current_value_table_item = |
| 709 | m_address_table->item(static_cast<int>(i), ADDRESS_TABLE_COLUMN_INDEX_CURRENT_VALUE); |
| 710 | RefreshCurrentValueTableItem(current_value_table_item); |
| 711 | } |
| 712 | } |
| 713 | |
| 714 | const std::vector<const QTableWidgetItem*> CheatSearchWidget::GetSelectedAddressTableItems() const |
| 715 | { |
| 716 | // Don't process each selectedItems(), as it can produce duplicate commands for one address when |
| 717 | // multiple items in the same row are selected. Instead, uses rows and gets one item from each |
| 718 | // row. All row items have identical data. |
| 719 | auto selected_rows = m_address_table->selectionModel()->selectedRows(); |
| 720 | |
| 721 | // Ascending address order. |
| 722 | std::sort(selected_rows.begin(), selected_rows.end(), |
| 723 | [](const QModelIndex& a, const QModelIndex& b) { return a.row() < b.row(); }); |
| 724 | |
| 725 | std::vector<const QTableWidgetItem*> selected_items; |
| 726 | for (const auto& index : selected_rows) |
| 727 | { |
| 728 | const int row = index.row(); |
| 729 | selected_items.push_back(m_address_table->item(row, 0)); |
| 730 | } |
| 731 | return selected_items; |
| 732 | } |
| 733 | |
| 734 | void CheatSearchWidget::RecreateGUITable() |
| 735 | { |
| 736 | const QSignalBlocker blocker(m_address_table); |
| 737 | |
| 738 | m_address_table->clear(); |
| 739 | m_address_table->setColumnCount(4); |
| 740 | m_address_table->setHorizontalHeaderLabels( |
| 741 | {tr("Description"), tr("Address"), tr("Last Value"), tr("Current Value")}); |
| 742 | |
| 743 | const int row_count = static_cast<int>(GetTableRowCount()); |
| 744 | m_address_table->setRowCount(row_count); |
| 745 | |
| 746 | for (int i = 0; i < row_count; ++i) |
| 747 | { |
| 748 | const u32 address = m_last_value_session->GetResultAddress(i); |
| 749 | const auto user_data_it = m_address_table_user_data.find(address); |
| 750 | const bool has_user_data = user_data_it != m_address_table_user_data.end(); |
| 751 | |
| 752 | auto* description_item = new QTableWidgetItem(); |
| 753 | description_item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable); |
| 754 | if (has_user_data) |
| 755 | description_item->setText(QString::fromStdString(user_data_it->second.m_description)); |
| 756 | description_item->setData(ADDRESS_TABLE_ADDRESS_ROLE, address); |
| 757 | description_item->setData(ADDRESS_TABLE_RESULT_INDEX_ROLE, static_cast<u32>(i)); |
| 758 | m_address_table->setItem(i, ADDRESS_TABLE_COLUMN_INDEX_DESCRIPTION, description_item); |
| 759 | |
| 760 | auto* address_item = new QTableWidgetItem(); |
| 761 | address_item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); |
| 762 | address_item->setText(QStringLiteral("0x%1").arg(address, 8, 16, QLatin1Char('0'))); |
| 763 | address_item->setData(ADDRESS_TABLE_ADDRESS_ROLE, address); |
| 764 | address_item->setData(ADDRESS_TABLE_RESULT_INDEX_ROLE, static_cast<u32>(i)); |
| 765 | m_address_table->setItem(i, ADDRESS_TABLE_COLUMN_INDEX_ADDRESS, address_item); |
| 766 | |
| 767 | const bool show_in_hex = m_display_values_in_hex_checkbox->isChecked(); |
| 768 | auto* last_value_item = new QTableWidgetItem(); |
| 769 | last_value_item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); |
| 770 | last_value_item->setText( |
| 771 | QString::fromStdString(m_last_value_session->GetResultValueAsString(i, show_in_hex))); |
| 772 | last_value_item->setData(ADDRESS_TABLE_ADDRESS_ROLE, address); |
| 773 | last_value_item->setData(ADDRESS_TABLE_RESULT_INDEX_ROLE, static_cast<u32>(i)); |
| 774 | m_address_table->setItem(i, ADDRESS_TABLE_COLUMN_INDEX_LAST_VALUE, last_value_item); |
| 775 | |
| 776 | auto* current_value_item = new QTableWidgetItem(); |
| 777 | current_value_item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); |
| 778 | current_value_item->setData(ADDRESS_TABLE_ADDRESS_ROLE, address); |
| 779 | current_value_item->setData(ADDRESS_TABLE_RESULT_INDEX_ROLE, static_cast<u32>(i)); |
| 780 | m_address_table->setItem(i, ADDRESS_TABLE_COLUMN_INDEX_CURRENT_VALUE, current_value_item); |
| 781 | RefreshCurrentValueTableItem(current_value_item); |
| 782 | } |
| 783 | } |