summaryrefslogtreecommitdiff
path: root/Source/Core/DolphinQt/CheatSearchWidget.cpp
blob: 1160b06247c48226d87408157a5d219a66027548 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
// Copyright 2021 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "DolphinQt/CheatSearchWidget.h"

#include <algorithm>
#include <optional>
#include <ranges>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>

#include <QCheckBox>
#include <QComboBox>
#include <QCursor>
#include <QHBoxLayout>
#include <QInputDialog>
#include <QLabel>
#include <QLineEdit>
#include <QMenu>
#include <QPushButton>
#include <QSettings>
#include <QSignalBlocker>
#include <QString>
#include <QTableWidget>
#include <QVBoxLayout>

#include <fmt/format.h>

#include "Core/ActionReplay.h"
#include "Core/CheatGeneration.h"
#include "Core/CheatSearch.h"
#include "Core/ConfigManager.h"
#include "Core/Core.h"
#include "Core/PowerPC/BreakPoints.h"
#include "Core/PowerPC/PowerPC.h"
#include "Core/System.h"

#include "DolphinQt/Config/CheatCodeEditor.h"
#include "DolphinQt/Config/CheatWarningWidget.h"
#include "DolphinQt/Host.h"
#include "DolphinQt/QtUtils/WrapInScrollArea.h"
#include "DolphinQt/Settings.h"

constexpr size_t TABLE_MAX_ROWS = 1000;

constexpr int ADDRESS_TABLE_ADDRESS_ROLE = Qt::UserRole;
constexpr int ADDRESS_TABLE_RESULT_INDEX_ROLE = Qt::UserRole + 1;
constexpr int ADDRESS_TABLE_COLUMN_INDEX_DESCRIPTION = 0;
constexpr int ADDRESS_TABLE_COLUMN_INDEX_ADDRESS = 1;
constexpr int ADDRESS_TABLE_COLUMN_INDEX_LAST_VALUE = 2;
constexpr int ADDRESS_TABLE_COLUMN_INDEX_CURRENT_VALUE = 3;

namespace
{
int GetDataTypeByteSize(Cheats::DataType data_type)
{
  switch (data_type)
  {
  case Cheats::DataType::U8:
  case Cheats::DataType::S8:
    return 1;
  case Cheats::DataType::U16:
  case Cheats::DataType::S16:
    return 2;
  case Cheats::DataType::U32:
  case Cheats::DataType::S32:
  case Cheats::DataType::F32:
    return 4;
  case Cheats::DataType::U64:
  case Cheats::DataType::S64:
  case Cheats::DataType::F64:
    return 8;
  default:
    return 1;
  }
}
}  // namespace

CheatSearchWidget::CheatSearchWidget(Core::System& system,
                                     std::unique_ptr<Cheats::CheatSearchSessionBase> session,
                                     QWidget* parent)
    : QWidget(parent), m_system(system), m_last_value_session(std::move(session))
{
  setAttribute(Qt::WA_DeleteOnClose);
  CreateWidgets();
  ConnectWidgets();
  OnValueSourceChanged();
  RecreateGUITable();
}

CheatSearchWidget::~CheatSearchWidget()
{
  auto& settings = Settings::GetQSettings();
  settings.setValue(QStringLiteral("cheatsearchwidget/displayhex"),
                    m_display_values_in_hex_checkbox->isChecked());
  settings.setValue(QStringLiteral("cheatsearchwidget/autoupdatecurrentvalues"),
                    m_autoupdate_current_values->isChecked());

  if (m_last_value_session->IsIntegerType())
  {
    settings.setValue(QStringLiteral("cheatsearchwidget/parsehex"),
                      m_parse_values_as_hex_checkbox->isChecked());
  }
}

Q_DECLARE_METATYPE(Cheats::CompareType);
Q_DECLARE_METATYPE(Cheats::FilterType);

void CheatSearchWidget::CreateWidgets()
{
  QLabel* session_info_label = new QLabel();
  {
    QString ranges;
    const size_t range_count = m_last_value_session->GetMemoryRangeCount();
    switch (range_count)
    {
    case 1:
    {
      const auto m = m_last_value_session->GetMemoryRange(0);
      ranges =
          tr("[%1, %2]")
              .arg(QString::fromStdString(fmt::format("0x{0:08x}", m.m_start)))
              .arg(QString::fromStdString(fmt::format("0x{0:08x}", m.m_start + m.m_length - 1)));
      break;
    }
    case 2:
    {
      const auto m0 = m_last_value_session->GetMemoryRange(0);
      const auto m1 = m_last_value_session->GetMemoryRange(1);
      ranges =
          tr("[%1, %2] and [%3, %4]")
              .arg(QString::fromStdString(fmt::format("0x{0:08x}", m0.m_start)))
              .arg(QString::fromStdString(fmt::format("0x{0:08x}", m0.m_start + m0.m_length - 1)))
              .arg(QString::fromStdString(fmt::format("0x{0:08x}", m1.m_start)))
              .arg(QString::fromStdString(fmt::format("0x{0:08x}", m1.m_start + m1.m_length - 1)));
      break;
    }
    default:
      ranges = tr("%1 memory ranges").arg(range_count);
      break;
    }

    QString space;
    switch (m_last_value_session->GetAddressSpace())
    {
    case PowerPC::RequestedAddressSpace::Effective:
      space = tr("Address space by CPU state");
      break;
    case PowerPC::RequestedAddressSpace::Physical:
      space = tr("Physical address space");
      break;
    case PowerPC::RequestedAddressSpace::Virtual:
      space = tr("Virtual address space");
      break;
    default:
      space = tr("Unknown address space");
      break;
    }

    QString type;
    switch (m_last_value_session->GetDataType())
    {
    case Cheats::DataType::U8:
      type = tr("8-bit Unsigned Integer");
      break;
    case Cheats::DataType::U16:
      type = tr("16-bit Unsigned Integer");
      break;
    case Cheats::DataType::U32:
      type = tr("32-bit Unsigned Integer");
      break;
    case Cheats::DataType::U64:
      type = tr("64-bit Unsigned Integer");
      break;
    case Cheats::DataType::S8:
      type = tr("8-bit Signed Integer");
      break;
    case Cheats::DataType::S16:
      type = tr("16-bit Signed Integer");
      break;
    case Cheats::DataType::S32:
      type = tr("32-bit Signed Integer");
      break;
    case Cheats::DataType::S64:
      type = tr("64-bit Signed Integer");
      break;
    case Cheats::DataType::F32:
      type = tr("32-bit Float");
      break;
    case Cheats::DataType::F64:
      type = tr("64-bit Float");
      break;
    default:
      type = tr("Unknown data type");
      break;
    }
    const QString aligned = m_last_value_session->GetAligned() ? tr("aligned") : tr("unaligned");
    session_info_label->setText(tr("%1, %2, %3, %4").arg(ranges).arg(space).arg(type).arg(aligned));
    session_info_label->setWordWrap(true);
  }

  // i18n: This label is followed by a dropdown where the user can select things like "is equal to"
  // or "is less than or equal to", followed by another dropdown where the user can select "any
  // value", "last value", or "this value:". These three UI elements are intended to form a sentence
  // together. Because the UI elements can't be reordered by a translation, you may have to give
  // up on the idea of having them form a sentence depending on the grammar of your target language.
  auto* instructions_label = new QLabel(tr("Keep addresses where value in memory"));

  auto* value_layout = new QHBoxLayout();
  m_compare_type_dropdown = new QComboBox();
  m_compare_type_dropdown->addItem(tr("is equal to"),
                                   QVariant::fromValue(Cheats::CompareType::Equal));
  m_compare_type_dropdown->addItem(tr("is not equal to"),
                                   QVariant::fromValue(Cheats::CompareType::NotEqual));
  m_compare_type_dropdown->addItem(tr("is less than"),
                                   QVariant::fromValue(Cheats::CompareType::Less));
  m_compare_type_dropdown->addItem(tr("is less than or equal to"),
                                   QVariant::fromValue(Cheats::CompareType::LessOrEqual));
  m_compare_type_dropdown->addItem(tr("is greater than"),
                                   QVariant::fromValue(Cheats::CompareType::Greater));
  m_compare_type_dropdown->addItem(tr("is greater than or equal to"),
                                   QVariant::fromValue(Cheats::CompareType::GreaterOrEqual));
  value_layout->addWidget(m_compare_type_dropdown);

  m_value_source_dropdown = new QComboBox();
  m_value_source_dropdown->addItem(
      tr("this value:"), QVariant::fromValue(Cheats::FilterType::CompareAgainstSpecificValue));
  m_value_source_dropdown->addItem(
      tr("last value"), QVariant::fromValue(Cheats::FilterType::CompareAgainstLastValue));
  m_value_source_dropdown->addItem(tr("any value"),
                                   QVariant::fromValue(Cheats::FilterType::DoNotFilter));
  value_layout->addWidget(m_value_source_dropdown);

  m_given_value_text = new QLineEdit();
  value_layout->addWidget(m_given_value_text);

  auto& settings = Settings::GetQSettings();
  m_parse_values_as_hex_checkbox = new QCheckBox(tr("Parse as Hex"));
  if (m_last_value_session->IsIntegerType())
  {
    m_parse_values_as_hex_checkbox->setChecked(
        settings.value(QStringLiteral("cheatsearchwidget/parsehex")).toBool());
    value_layout->addWidget(m_parse_values_as_hex_checkbox);
  }

  auto* button_layout = new QHBoxLayout();
  m_next_scan_button = new QPushButton(tr("Search and Filter"));
  button_layout->addWidget(m_next_scan_button);
  m_refresh_values_button = new QPushButton(tr("Refresh Current Values"));
  button_layout->addWidget(m_refresh_values_button);
  m_reset_button = new QPushButton(tr("Reset Results"));
  button_layout->addWidget(m_reset_button);

  m_address_table = new QTableWidget();
  m_address_table->setContextMenuPolicy(Qt::CustomContextMenu);
  m_address_table->setSelectionBehavior(QAbstractItemView::SelectRows);

  m_info_label_1 = new QLabel(tr("Waiting for first scan..."));
  m_info_label_2 = new QLabel();

  auto* const checkboxes_layout = new QHBoxLayout();
  m_display_values_in_hex_checkbox = new QCheckBox(tr("Display values in Hex"));
  m_display_values_in_hex_checkbox->setChecked(
      settings.value(QStringLiteral("cheatsearchwidget/displayhex")).toBool());
  checkboxes_layout->addWidget(m_display_values_in_hex_checkbox);
  checkboxes_layout->setStretchFactor(m_display_values_in_hex_checkbox, 1);

  m_autoupdate_current_values = new QCheckBox(tr("Automatically update Current Values"));
  m_autoupdate_current_values->setChecked(
      settings.value(QStringLiteral("cheatsearchwidget/autoupdatecurrentvalues"), true).toBool());
  checkboxes_layout->addWidget(m_autoupdate_current_values);
  checkboxes_layout->setStretchFactor(m_autoupdate_current_values, 2);

  auto* const layout = new QVBoxLayout{this};
  layout->addWidget(session_info_label);
  layout->addWidget(instructions_label);
  layout->addLayout(value_layout);
  layout->addLayout(button_layout);
  layout->addLayout(checkboxes_layout);
  layout->addWidget(m_info_label_1);
  layout->addWidget(m_info_label_2);
  layout->addWidget(m_address_table);
}

void CheatSearchWidget::ConnectWidgets()
{
  connect(m_next_scan_button, &QPushButton::clicked, this, &CheatSearchWidget::OnNextScanClicked);
  connect(m_refresh_values_button, &QPushButton::clicked, this,
          &CheatSearchWidget::OnRefreshClicked);
  connect(m_reset_button, &QPushButton::clicked, this, &CheatSearchWidget::OnResetClicked);
  connect(m_address_table, &QTableWidget::itemChanged, this,
          &CheatSearchWidget::OnAddressTableItemChanged);
  connect(m_address_table, &QTableWidget::customContextMenuRequested, this,
          &CheatSearchWidget::OnAddressTableContextMenu);
  connect(m_value_source_dropdown, &QComboBox::currentTextChanged, this,
          &CheatSearchWidget::OnValueSourceChanged);
  connect(m_display_values_in_hex_checkbox, &QCheckBox::toggled, this,
          &CheatSearchWidget::OnDisplayHexCheckboxStateChanged);
}

void CheatSearchWidget::OnNextScanClicked()
{
  Core::CPUThreadGuard guard{m_system};

  const bool had_old_results = m_last_value_session->WasFirstSearchDone();

  const auto filter_type = m_value_source_dropdown->currentData().value<Cheats::FilterType>();
  if (filter_type == Cheats::FilterType::CompareAgainstLastValue && !had_old_results)
  {
    m_info_label_1->setText(tr("Cannot compare against last value on first search."));
    return;
  }
  m_last_value_session->SetFilterType(filter_type);
  m_last_value_session->SetCompareType(
      m_compare_type_dropdown->currentData().value<Cheats::CompareType>());
  if (filter_type == Cheats::FilterType::CompareAgainstSpecificValue)
  {
    QString search_value = m_given_value_text->text();
    if (m_last_value_session->IsIntegerType() || m_last_value_session->IsFloatingType())
      search_value = search_value.simplified().remove(QLatin1Char(' '));
    if (!m_last_value_session->SetValueFromString(search_value.toStdString(),
                                                  m_parse_values_as_hex_checkbox->isChecked()))
    {
      m_info_label_1->setText(tr("Failed to parse given value into target data type."));
      return;
    }
  }

  const size_t old_count = m_last_value_session->GetResultCount();
  const Cheats::SearchErrorCode error_code = m_last_value_session->RunSearch(guard);

  if (error_code == Cheats::SearchErrorCode::Success)
  {
    const size_t new_count = m_last_value_session->GetResultCount();
    const size_t new_valid_count = m_last_value_session->GetValidValueCount();
    m_info_label_1->setText(tr("Scan succeeded."));

    if (had_old_results)
    {
      const QString removed_str =
          tr("%n address(es) were removed.", "", static_cast<int>(old_count - new_count));
      const QString remain_str = tr("%n address(es) remain.", "", static_cast<int>(new_count));

      if (new_valid_count == new_count)
      {
        m_info_label_2->setText(tr("%1 %2").arg(removed_str).arg(remain_str));
      }
      else
      {
        const QString inaccessible_str =
            tr("%n address(es) could not be accessed in emulated memory.", "",
               static_cast<int>(new_count - new_valid_count));

        m_info_label_2->setText(
            tr("%1 %2 %3").arg(removed_str).arg(remain_str).arg(inaccessible_str));
      }
    }
    else
    {
      const QString found_str = tr("Found %n address(es).", "", static_cast<int>(new_count));

      if (new_valid_count == new_count)
      {
        m_info_label_2->setText(found_str);
      }
      else
      {
        const QString inaccessible_str =
            tr("%n address(es) could not be accessed in emulated memory.", "",
               static_cast<int>(new_count - new_valid_count));

        m_info_label_2->setText(tr("%1 %2").arg(found_str).arg(inaccessible_str));
      }
    }

    m_address_table_current_values.clear();
    const bool show_in_hex = m_display_values_in_hex_checkbox->isChecked();
    const size_t row_count = GetTableRowCount();
    for (size_t i = 0; i < row_count; ++i)
    {
      m_address_table_current_values[m_last_value_session->GetResultAddress(i)] =
          m_last_value_session->GetResultValueAsString(i, show_in_hex);
    }

    RecreateGUITable();
  }
  else
  {
    switch (error_code)
    {
    case Cheats::SearchErrorCode::NoEmulationActive:
      m_info_label_1->setText(tr("No game is running."));
      break;
    case Cheats::SearchErrorCode::InvalidParameters:
      m_info_label_1->setText(tr("Invalid parameters given to search."));
      break;
    case Cheats::SearchErrorCode::VirtualAddressesCurrentlyNotAccessible:
      m_info_label_1->setText(
          tr("Search currently not possible in virtual address space. Please run "
             "the game for a bit and try again."));
      break;
    default:
      m_info_label_1->setText(tr("Unknown error occurred."));
      break;
    }
  }
}

bool CheatSearchWidget::UpdateTableRows(const Core::CPUThreadGuard& guard, const size_t begin_index,
                                        const size_t end_index, const UpdateSource source)
{
  const bool update_status_text = source == UpdateSource::User;

  const auto tmp = m_last_value_session->ClonePartial(begin_index, end_index);
  tmp->SetFilterType(Cheats::FilterType::DoNotFilter);

  const Cheats::SearchErrorCode error_code = tmp->RunSearch(guard);
  if (error_code != Cheats::SearchErrorCode::Success)
  {
    if (update_status_text)
      m_info_label_1->setText(tr("Refresh failed. Please run the game for a bit and try again."));
    return false;
  }

  const bool show_in_hex = m_display_values_in_hex_checkbox->isChecked();
  const size_t result_count_to_display = tmp->GetResultCount();
  for (size_t i = 0; i < result_count_to_display; ++i)
  {
    m_address_table_current_values[tmp->GetResultAddress(i)] =
        tmp->GetResultValueAsString(i, show_in_hex);
  }

  RefreshGUICurrentValues(begin_index, end_index);
  if (update_status_text)
    m_info_label_1->setText(tr("Refreshed current values."));
  return true;
}

void CheatSearchWidget::UpdateTableVisibleCurrentValues(const UpdateSource source)
{
  if (source == UpdateSource::Auto && !m_autoupdate_current_values->isChecked())
    return;

  if (m_address_table->rowCount() == 0)
    return;

  UpdateTableRows(Core::CPUThreadGuard{m_system}, GetVisibleRowsBeginIndex(),
                  GetVisibleRowsEndIndex(), source);
}

bool CheatSearchWidget::UpdateTableAllCurrentValues(const UpdateSource source)
{
  if (source == UpdateSource::Auto && !m_autoupdate_current_values->isChecked())
    return false;

  const size_t result_count = m_address_table->rowCount();
  if (result_count == 0)
  {
    if (source == UpdateSource::User)
      m_info_label_1->setText(tr("Cannot refresh without results."));
    return false;
  }

  return UpdateTableRows(Core::CPUThreadGuard{m_system}, 0, result_count, source);
}

void CheatSearchWidget::OnRefreshClicked()
{
  UpdateTableAllCurrentValues(UpdateSource::User);
}

void CheatSearchWidget::OnResetClicked()
{
  m_last_value_session->ResetResults();
  m_address_table_current_values.clear();

  RecreateGUITable();
  m_info_label_1->setText(tr("Waiting for first scan..."));
  m_info_label_2->clear();
}

void CheatSearchWidget::OnAddressTableItemChanged(QTableWidgetItem* item)
{
  const u32 address = item->data(ADDRESS_TABLE_ADDRESS_ROLE).toUInt();
  const int column = item->column();

  switch (column)
  {
  case ADDRESS_TABLE_COLUMN_INDEX_DESCRIPTION:
  {
    m_address_table_user_data[address].m_description = item->text().toStdString();
    break;
  }
  default:
    break;
  }
}

int CheatSearchWidget::GetVisibleRowsBeginIndex() const
{
  return m_address_table->rowAt(0);
}

int CheatSearchWidget::GetVisibleRowsEndIndex() const
{
  const int row_at_bottom_of_viewport = m_address_table->rowAt(m_address_table->height());
  const int end_index = m_address_table->rowCount();
  return row_at_bottom_of_viewport == -1 ? end_index : row_at_bottom_of_viewport + 1;
}

void CheatSearchWidget::OnAddressTableContextMenu()
{
  if (m_address_table->selectedItems().isEmpty())
    return;

  std::vector<const QTableWidgetItem*> selected_items = GetSelectedAddressTableItems();

  QMenu* menu = new QMenu(this);
  menu->setAttribute(Qt::WA_DeleteOnClose, true);

  menu->addAction(tr("Show in memory"), this, [this] {
    auto* item = m_address_table->selectedItems()[0];
    const u32 address = item->data(ADDRESS_TABLE_ADDRESS_ROLE).toUInt();
    emit ShowMemory(address);
  });
  menu->addAction(tr("Add to watch"), this, [this, selected_items] {
    for (auto* const item : selected_items)
    {
      const u32 address = item->data(ADDRESS_TABLE_ADDRESS_ROLE).toUInt();
      const QString name = QStringLiteral("mem_%1").arg(address, 8, 16, QLatin1Char('0'));
      emit RequestWatch(name, address);
    }
  });
  menu->addAction(tr("Generate Action Replay Code(s)"), this, &CheatSearchWidget::GenerateARCodes);
  menu->addAction(tr("Write value"), this, &CheatSearchWidget::WriteValue);
  menu->addAction(tr("Delete Address"), this, [this, selected_items] {
    // Process in reverse so removal won't change the index of items about to be processed.
    for (auto* const item : selected_items | std::views::reverse)
    {
      const u32 index = item->data(ADDRESS_TABLE_RESULT_INDEX_ROLE).toUInt();
      m_last_value_session->RemoveResult(index);
    }
    RecreateGUITable();
  });

  if (m_last_value_session->GetAddressSpace() == PowerPC::RequestedAddressSpace::Virtual)
  {
    menu->addAction(tr("Add Read/Write Breakpoint(s)"), this,
                    [this]() { AddMemoryBreakpoints("rw"); });
    menu->addAction(tr("Add Write Breakpoint(s)"), this, [this]() { AddMemoryBreakpoints("w"); });
    menu->addAction(tr("Add Read Breakpoint(s)"), this, [this]() { AddMemoryBreakpoints("r"); });
  }

  menu->exec(QCursor::pos());
}

void CheatSearchWidget::AddMemoryBreakpoints(std::string_view type)
{
  if (m_last_value_session->GetAddressSpace() != PowerPC::RequestedAddressSpace::Virtual)
    return;

  const int last_byte_offset = GetDataTypeByteSize(m_last_value_session->GetDataType()) - 1;

  MemChecks::TMemChecksStr bps;

  for (auto& item : GetSelectedAddressTableItems())
  {
    const u32 addr = item->data(ADDRESS_TABLE_ADDRESS_ROLE).toUInt();
    std::string bp = fmt::format("{:08x} {:08x} nbl{}", addr, addr + last_byte_offset, type);
    bps.push_back(bp);
  }

  auto& memchecks = m_system.GetPowerPC().GetMemChecks();
  memchecks.AddFromStrings(bps);
  emit Host::GetInstance()->PPCBreakpointsChanged();
}

void CheatSearchWidget::OnValueSourceChanged()
{
  const auto filter_type = m_value_source_dropdown->currentData().value<Cheats::FilterType>();
  const bool is_value_search = filter_type == Cheats::FilterType::CompareAgainstSpecificValue;
  m_given_value_text->setEnabled(is_value_search);
  m_parse_values_as_hex_checkbox->setEnabled(is_value_search &&
                                             m_last_value_session->IsIntegerType());
}

void CheatSearchWidget::OnDisplayHexCheckboxStateChanged()
{
  if (!m_last_value_session->WasFirstSearchDone())
    return;

  // If the game is running CheatsManager::OnFrameEnd will update values automatically.
  if (Core::GetState(m_system) != Core::State::Running)
    UpdateTableAllCurrentValues(UpdateSource::User);
}

void CheatSearchWidget::GenerateARCodes()
{
  if (m_address_table->selectedItems().isEmpty())
    return;

  bool had_success = false;
  bool had_multiple_errors = false;
  std::optional<Cheats::GenerateActionReplayCodeErrorCode> error_code;

  for (auto* const item : GetSelectedAddressTableItems())
  {
    const u32 index = item->data(ADDRESS_TABLE_RESULT_INDEX_ROLE).toUInt();
    const auto result = Cheats::GenerateActionReplayCode(*m_last_value_session, index);
    if (result)
    {
      emit ActionReplayCodeGenerated(*result);
      had_success = true;
    }
    else
    {
      const auto new_error_code = result.error();
      if (!error_code.has_value())
      {
        error_code = new_error_code;
      }
      else if (error_code != new_error_code)
      {
        had_multiple_errors = true;
      }
    }
  }

  if (error_code.has_value())
  {
    if (had_multiple_errors)
    {
      m_info_label_1->setText(tr("Multiple errors occurred while generating AR codes."));
    }
    else
    {
      switch (*error_code)
      {
      case Cheats::GenerateActionReplayCodeErrorCode::NotVirtualMemory:
        m_info_label_1->setText(tr("Can only generate AR code for values in virtual memory."));
        break;
      case Cheats::GenerateActionReplayCodeErrorCode::InvalidAddress:
        m_info_label_1->setText(tr("Cannot generate AR code for this address."));
        break;
      default:
        m_info_label_1->setText(tr("Internal error while generating AR code."));
        break;
      }
    }
  }
  else if (had_success)
  {
    m_info_label_1->setText(tr("Generated AR code(s)."));
  }
}

void CheatSearchWidget::WriteValue()
{
  if (m_address_table->selectedItems().isEmpty())
    return;

  bool ok{};
  QString text = QInputDialog::getText(this, tr("Write value"), tr("Value:"), QLineEdit::Normal,
                                       QString{}, &ok);

  if (!ok || !m_last_value_session->SetValueFromString(text.toStdString(),
                                                       m_parse_values_as_hex_checkbox->isChecked()))
  {
    m_info_label_1->setText(tr("Invalid value."));
    return;
  }

  auto items = GetSelectedAddressTableItems();
  std::vector<u32> addresses(items.size());
  std::transform(items.begin(), items.end(), addresses.begin(), [](const QTableWidgetItem* item) {
    return item->data(ADDRESS_TABLE_ADDRESS_ROLE).toUInt();
  });
  Core::CPUThreadGuard guard{m_system};
  if (!m_last_value_session->WriteValue(guard, std::span<u32>(addresses)))
  {
    m_info_label_1->setText(tr("There was an error writing (some) values."));
  }
  UpdateTableAllCurrentValues(UpdateSource::User);
}

size_t CheatSearchWidget::GetTableRowCount() const
{
  return std::min(TABLE_MAX_ROWS, m_last_value_session->GetResultCount());
}

void CheatSearchWidget::RefreshCurrentValueTableItem(
    QTableWidgetItem* const current_value_table_item)
{
  const auto address = current_value_table_item->data(ADDRESS_TABLE_ADDRESS_ROLE).toUInt();
  const auto curr_val_iter = m_address_table_current_values.find(address);
  if (curr_val_iter != m_address_table_current_values.end())
    current_value_table_item->setText(QString::fromStdString(curr_val_iter->second));
  else
    current_value_table_item->setText(QStringLiteral("---"));
}

void CheatSearchWidget::RefreshGUICurrentValues(const size_t begin_index, const size_t end_index)
{
  for (size_t i = begin_index; i < end_index; ++i)
  {
    QTableWidgetItem* const current_value_table_item =
        m_address_table->item(static_cast<int>(i), ADDRESS_TABLE_COLUMN_INDEX_CURRENT_VALUE);
    RefreshCurrentValueTableItem(current_value_table_item);
  }
}

const std::vector<const QTableWidgetItem*> CheatSearchWidget::GetSelectedAddressTableItems() const
{
  // Don't process each selectedItems(), as it can produce duplicate commands for one address when
  // multiple items in the same row are selected. Instead, uses rows and gets one item from each
  // row. All row items have identical data.
  auto selected_rows = m_address_table->selectionModel()->selectedRows();

  // Ascending address order.
  std::sort(selected_rows.begin(), selected_rows.end(),
            [](const QModelIndex& a, const QModelIndex& b) { return a.row() < b.row(); });

  std::vector<const QTableWidgetItem*> selected_items;
  for (const auto& index : selected_rows)
  {
    const int row = index.row();
    selected_items.push_back(m_address_table->item(row, 0));
  }
  return selected_items;
}

void CheatSearchWidget::RecreateGUITable()
{
  const QSignalBlocker blocker(m_address_table);

  m_address_table->clear();
  m_address_table->setColumnCount(4);
  m_address_table->setHorizontalHeaderLabels(
      {tr("Description"), tr("Address"), tr("Last Value"), tr("Current Value")});

  const int row_count = static_cast<int>(GetTableRowCount());
  m_address_table->setRowCount(row_count);

  for (int i = 0; i < row_count; ++i)
  {
    const u32 address = m_last_value_session->GetResultAddress(i);
    const auto user_data_it = m_address_table_user_data.find(address);
    const bool has_user_data = user_data_it != m_address_table_user_data.end();

    auto* description_item = new QTableWidgetItem();
    description_item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable);
    if (has_user_data)
      description_item->setText(QString::fromStdString(user_data_it->second.m_description));
    description_item->setData(ADDRESS_TABLE_ADDRESS_ROLE, address);
    description_item->setData(ADDRESS_TABLE_RESULT_INDEX_ROLE, static_cast<u32>(i));
    m_address_table->setItem(i, ADDRESS_TABLE_COLUMN_INDEX_DESCRIPTION, description_item);

    auto* address_item = new QTableWidgetItem();
    address_item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
    address_item->setText(QStringLiteral("0x%1").arg(address, 8, 16, QLatin1Char('0')));
    address_item->setData(ADDRESS_TABLE_ADDRESS_ROLE, address);
    address_item->setData(ADDRESS_TABLE_RESULT_INDEX_ROLE, static_cast<u32>(i));
    m_address_table->setItem(i, ADDRESS_TABLE_COLUMN_INDEX_ADDRESS, address_item);

    const bool show_in_hex = m_display_values_in_hex_checkbox->isChecked();
    auto* last_value_item = new QTableWidgetItem();
    last_value_item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
    last_value_item->setText(
        QString::fromStdString(m_last_value_session->GetResultValueAsString(i, show_in_hex)));
    last_value_item->setData(ADDRESS_TABLE_ADDRESS_ROLE, address);
    last_value_item->setData(ADDRESS_TABLE_RESULT_INDEX_ROLE, static_cast<u32>(i));
    m_address_table->setItem(i, ADDRESS_TABLE_COLUMN_INDEX_LAST_VALUE, last_value_item);

    auto* current_value_item = new QTableWidgetItem();
    current_value_item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
    current_value_item->setData(ADDRESS_TABLE_ADDRESS_ROLE, address);
    current_value_item->setData(ADDRESS_TABLE_RESULT_INDEX_ROLE, static_cast<u32>(i));
    m_address_table->setItem(i, ADDRESS_TABLE_COLUMN_INDEX_CURRENT_VALUE, current_value_item);
    RefreshCurrentValueTableItem(current_value_item);
  }
}