| 1 | // Copyright 2018 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #include "DolphinQt/GCMemcardManager.h" |
| 5 | |
| 6 | #include <algorithm> |
| 7 | #include <string> |
| 8 | #include <vector> |
| 9 | |
| 10 | #include <fmt/format.h> |
| 11 | |
| 12 | #include <QDialogButtonBox> |
| 13 | #include <QDir> |
| 14 | #include <QGridLayout> |
| 15 | #include <QGroupBox> |
| 16 | #include <QHeaderView> |
| 17 | #include <QImage> |
| 18 | #include <QLabel> |
| 19 | #include <QLineEdit> |
| 20 | #include <QMenu> |
| 21 | #include <QPixmap> |
| 22 | #include <QPushButton> |
| 23 | #include <QString> |
| 24 | #include <QStringList> |
| 25 | #include <QTableWidget> |
| 26 | #include <QTimer> |
| 27 | #include <QToolButton> |
| 28 | |
| 29 | #include "Common/Assert.h" |
| 30 | #include "Common/CommonPaths.h" |
| 31 | #include "Common/Config/Config.h" |
| 32 | #include "Common/FileUtil.h" |
| 33 | #include "Common/VariantUtil.h" |
| 34 | |
| 35 | #include "Core/Config/MainSettings.h" |
| 36 | #include "Core/HW/GCMemcard/GCMemcard.h" |
| 37 | #include "Core/HW/GCMemcard/GCMemcardUtils.h" |
| 38 | |
| 39 | #include "DolphinQt/GCMemcardCreateNewDialog.h" |
| 40 | #include "DolphinQt/QtUtils/DolphinFileDialog.h" |
| 41 | #include "DolphinQt/QtUtils/ModalMessageBox.h" |
| 42 | #include "DolphinQt/QtUtils/NonDefaultQPushButton.h" |
| 43 | |
| 44 | using namespace ExpansionInterface; |
| 45 | |
| 46 | constexpr int ROW_HEIGHT = 36; |
| 47 | constexpr int COLUMN_WIDTH_FILENAME = 100; |
| 48 | constexpr int COLUMN_WIDTH_BANNER = Memcard::MEMORY_CARD_BANNER_WIDTH + 6; |
| 49 | constexpr int COLUMN_WIDTH_TEXT = 160; |
| 50 | constexpr int COLUMN_WIDTH_ICON = Memcard::MEMORY_CARD_ICON_WIDTH + 6; |
| 51 | constexpr int COLUMN_WIDTH_BLOCKS = 40; |
| 52 | constexpr int COLUMN_INDEX_FILENAME = 0; |
| 53 | constexpr int COLUMN_INDEX_BANNER = 1; |
| 54 | constexpr int COLUMN_INDEX_TEXT = 2; |
| 55 | constexpr int COLUMN_INDEX_ICON = 3; |
| 56 | constexpr int COLUMN_INDEX_BLOCKS = 4; |
| 57 | constexpr int COLUMN_COUNT = 5; |
| 58 | |
| 59 | namespace |
| 60 | { |
| 61 | Slot OtherSlot(Slot slot) |
| 62 | { |
| 63 | return slot == Slot::A ? Slot::B : Slot::A; |
| 64 | } |
| 65 | } // namespace |
| 66 | |
| 67 | struct GCMemcardManager::IconAnimationData |
| 68 | { |
| 69 | // the individual frames |
| 70 | std::vector<QPixmap> m_frames; |
| 71 | |
| 72 | // vector containing a list of frame indices that indicate, for each time unit, |
| 73 | // the frame that should be displayed when at that time unit |
| 74 | std::vector<u8> m_frame_timing; |
| 75 | }; |
| 76 | |
| 77 | GCMemcardManager::GCMemcardManager(QWidget* parent) : QDialog(parent) |
| 78 | { |
| 79 | CreateWidgets(); |
| 80 | ConnectWidgets(); |
| 81 | |
| 82 | SetActiveSlot(Slot::A); |
| 83 | UpdateActions(); |
| 84 | |
| 85 | m_timer = new QTimer(this); |
| 86 | connect(m_timer, &QTimer::timeout, this, &GCMemcardManager::DrawIcons); |
| 87 | |
| 88 | // individual frames of icon animations can stay on screen for 4, 8, or 12 frames at 60 FPS, |
| 89 | // which means the fastest animation and common denominator is 15 FPS or 66 milliseconds per frame |
| 90 | m_timer->start(1000 / 15); |
| 91 | |
| 92 | LoadDefaultMemcards(); |
| 93 | |
| 94 | // Make the dimensions more reasonable on startup |
| 95 | resize(650, 500); |
| 96 | |
| 97 | setWindowTitle(tr("GameCube Memory Card Manager")); |
| 98 | } |
| 99 | |
| 100 | GCMemcardManager::~GCMemcardManager() = default; |
| 101 | |
| 102 | void GCMemcardManager::CreateWidgets() |
| 103 | { |
| 104 | m_button_box = new QDialogButtonBox(QDialogButtonBox::Close); |
| 105 | |
| 106 | // Actions |
| 107 | m_select_button = new NonDefaultQPushButton; |
| 108 | m_copy_button = new NonDefaultQPushButton; |
| 109 | m_delete_button = new NonDefaultQPushButton(tr("&Delete")); |
| 110 | |
| 111 | m_export_button = new QToolButton(this); |
| 112 | m_export_menu = new QMenu(m_export_button); |
| 113 | m_export_gci_action = new QAction(tr("&Export as .gci..."), m_export_menu); |
| 114 | m_export_gcs_action = new QAction(tr("Export as .&gcs..."), m_export_menu); |
| 115 | m_export_sav_action = new QAction(tr("Export as .&sav..."), m_export_menu); |
| 116 | m_export_menu->addAction(m_export_gci_action); |
| 117 | m_export_menu->addAction(m_export_gcs_action); |
| 118 | m_export_menu->addAction(m_export_sav_action); |
| 119 | m_export_button->setDefaultAction(m_export_gci_action); |
| 120 | m_export_button->setPopupMode(QToolButton::MenuButtonPopup); |
| 121 | m_export_button->setMenu(m_export_menu); |
| 122 | |
| 123 | m_import_button = new NonDefaultQPushButton(tr("&Import...")); |
| 124 | m_fix_checksums_button = new NonDefaultQPushButton(tr("Fix Checksums")); |
| 125 | |
| 126 | auto* layout = new QGridLayout; |
| 127 | |
| 128 | for (Slot slot : MEMCARD_SLOTS) |
| 129 | { |
| 130 | m_slot_group[slot] = new QGroupBox(slot == Slot::A ? tr("Slot A") : tr("Slot B")); |
| 131 | m_slot_file_edit[slot] = new QLineEdit; |
| 132 | m_slot_open_button[slot] = new NonDefaultQPushButton(tr("&Open...")); |
| 133 | m_slot_create_button[slot] = new NonDefaultQPushButton(tr("&Create...")); |
| 134 | m_slot_table[slot] = new QTableWidget; |
| 135 | m_slot_table[slot]->setTabKeyNavigation(false); |
| 136 | m_slot_table[slot]->setHorizontalScrollMode(QAbstractItemView::ScrollMode::ScrollPerPixel); |
| 137 | m_slot_table[slot]->setVerticalScrollMode(QAbstractItemView::ScrollMode::ScrollPerPixel); |
| 138 | m_slot_stat_label[slot] = new QLabel; |
| 139 | |
| 140 | m_slot_table[slot]->setSelectionMode(QAbstractItemView::ExtendedSelection); |
| 141 | m_slot_table[slot]->setSelectionBehavior(QAbstractItemView::SelectRows); |
| 142 | m_slot_table[slot]->setSortingEnabled(true); |
| 143 | m_slot_table[slot]->horizontalHeader()->setHighlightSections(false); |
| 144 | m_slot_table[slot]->horizontalHeader()->setMinimumSectionSize(0); |
| 145 | m_slot_table[slot]->horizontalHeader()->setSortIndicatorShown(true); |
| 146 | m_slot_table[slot]->setColumnCount(COLUMN_COUNT); |
| 147 | m_slot_table[slot]->setHorizontalHeaderItem(COLUMN_INDEX_FILENAME, |
| 148 | new QTableWidgetItem(tr("Filename"))); |
| 149 | m_slot_table[slot]->setHorizontalHeaderItem(COLUMN_INDEX_BANNER, |
| 150 | new QTableWidgetItem(tr("Banner"))); |
| 151 | m_slot_table[slot]->setHorizontalHeaderItem(COLUMN_INDEX_TEXT, |
| 152 | new QTableWidgetItem(tr("Title"))); |
| 153 | m_slot_table[slot]->setHorizontalHeaderItem(COLUMN_INDEX_ICON, |
| 154 | new QTableWidgetItem(tr("Icon"))); |
| 155 | m_slot_table[slot]->setHorizontalHeaderItem(COLUMN_INDEX_BLOCKS, |
| 156 | new QTableWidgetItem(tr("Blocks"))); |
| 157 | m_slot_table[slot]->setColumnWidth(COLUMN_INDEX_FILENAME, COLUMN_WIDTH_FILENAME); |
| 158 | m_slot_table[slot]->setColumnWidth(COLUMN_INDEX_BANNER, COLUMN_WIDTH_BANNER); |
| 159 | m_slot_table[slot]->setColumnWidth(COLUMN_INDEX_TEXT, COLUMN_WIDTH_TEXT); |
| 160 | m_slot_table[slot]->setColumnWidth(COLUMN_INDEX_ICON, COLUMN_WIDTH_ICON); |
| 161 | m_slot_table[slot]->setColumnWidth(COLUMN_INDEX_BLOCKS, COLUMN_WIDTH_BLOCKS); |
| 162 | m_slot_table[slot]->verticalHeader()->setDefaultSectionSize(ROW_HEIGHT); |
| 163 | m_slot_table[slot]->verticalHeader()->hide(); |
| 164 | m_slot_table[slot]->setShowGrid(false); |
| 165 | |
| 166 | auto* slot_layout = new QGridLayout; |
| 167 | m_slot_group[slot]->setLayout(slot_layout); |
| 168 | |
| 169 | slot_layout->addWidget(m_slot_file_edit[slot], 0, 0); |
| 170 | slot_layout->addWidget(m_slot_open_button[slot], 0, 1); |
| 171 | slot_layout->addWidget(m_slot_create_button[slot], 0, 2); |
| 172 | slot_layout->addWidget(m_slot_table[slot], 1, 0, 1, 3); |
| 173 | slot_layout->addWidget(m_slot_stat_label[slot], 2, 0); |
| 174 | |
| 175 | layout->addWidget(m_slot_group[slot], 0, slot == Slot::A ? 0 : 2, 8, 1); |
| 176 | |
| 177 | UpdateSlotTable(slot); |
| 178 | } |
| 179 | |
| 180 | layout->addWidget(m_select_button, 1, 1); |
| 181 | layout->addWidget(m_copy_button, 2, 1); |
| 182 | layout->addWidget(m_delete_button, 3, 1); |
| 183 | layout->addWidget(m_export_button, 4, 1); |
| 184 | layout->addWidget(m_import_button, 5, 1); |
| 185 | layout->addWidget(m_fix_checksums_button, 6, 1); |
| 186 | layout->addWidget(m_button_box, 8, 2); |
| 187 | |
| 188 | setLayout(layout); |
| 189 | } |
| 190 | |
| 191 | void GCMemcardManager::ConnectWidgets() |
| 192 | { |
| 193 | connect(m_button_box, &QDialogButtonBox::rejected, this, &QDialog::reject); |
| 194 | connect(m_select_button, &QPushButton::clicked, |
| 195 | [this] { SetActiveSlot(OtherSlot(m_active_slot)); }); |
| 196 | connect(m_export_gci_action, &QAction::triggered, |
| 197 | [this] { ExportFiles(Memcard::SavefileFormat::GCI); }); |
| 198 | connect(m_export_gcs_action, &QAction::triggered, |
| 199 | [this] { ExportFiles(Memcard::SavefileFormat::GCS); }); |
| 200 | connect(m_export_sav_action, &QAction::triggered, |
| 201 | [this] { ExportFiles(Memcard::SavefileFormat::SAV); }); |
| 202 | connect(m_delete_button, &QPushButton::clicked, this, &GCMemcardManager::DeleteFiles); |
| 203 | connect(m_import_button, &QPushButton::clicked, this, &GCMemcardManager::ImportFile); |
| 204 | connect(m_copy_button, &QPushButton::clicked, this, &GCMemcardManager::CopyFiles); |
| 205 | connect(m_fix_checksums_button, &QPushButton::clicked, this, &GCMemcardManager::FixChecksums); |
| 206 | |
| 207 | for (Slot slot : MEMCARD_SLOTS) |
| 208 | { |
| 209 | connect(m_slot_file_edit[slot], &QLineEdit::textChanged, |
| 210 | [this, slot](const QString& path) { SetSlotFile(slot, path); }); |
| 211 | connect(m_slot_open_button[slot], &QPushButton::clicked, |
| 212 | [this, slot] { SetSlotFileInteractive(slot); }); |
| 213 | connect(m_slot_create_button[slot], &QPushButton::clicked, |
| 214 | [this, slot] { CreateNewCard(slot); }); |
| 215 | connect(m_slot_table[slot], &QTableWidget::itemSelectionChanged, this, |
| 216 | &GCMemcardManager::UpdateActions); |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | void GCMemcardManager::LoadDefaultMemcards() |
| 221 | { |
| 222 | for (ExpansionInterface::Slot slot : ExpansionInterface::MEMCARD_SLOTS) |
| 223 | { |
| 224 | if (Config::Get(Config::GetInfoForEXIDevice(slot)) != |
| 225 | ExpansionInterface::EXIDeviceType::MemoryCard) |
| 226 | { |
| 227 | continue; |
| 228 | } |
| 229 | |
| 230 | const QString path = QString::fromStdString( |
| 231 | Config::GetMemcardPath(slot, Config::Get(Config::MAIN_FALLBACK_REGION))); |
| 232 | SetSlotFile(slot, path); |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | void GCMemcardManager::SetActiveSlot(Slot slot) |
| 237 | { |
| 238 | for (Slot slot2 : MEMCARD_SLOTS) |
| 239 | m_slot_table[slot2]->setEnabled(slot2 == slot); |
| 240 | |
| 241 | m_select_button->setText(slot == Slot::A ? tr("Switch to B") : tr("Switch to A")); |
| 242 | m_copy_button->setText(slot == Slot::A ? tr("Copy to B") : tr("Copy to A")); |
| 243 | |
| 244 | m_active_slot = slot; |
| 245 | |
| 246 | UpdateActions(); |
| 247 | } |
| 248 | |
| 249 | void GCMemcardManager::UpdateSlotTable(Slot slot) |
| 250 | { |
| 251 | m_slot_active_icons[slot].clear(); |
| 252 | |
| 253 | if (m_slot_memcard[slot] == nullptr) |
| 254 | { |
| 255 | m_slot_table[slot]->setRowCount(0); |
| 256 | m_slot_stat_label[slot]->clear(); |
| 257 | return; |
| 258 | } |
| 259 | |
| 260 | auto& memcard = m_slot_memcard[slot]; |
| 261 | auto* table = m_slot_table[slot]; |
| 262 | table->setSortingEnabled(false); |
| 263 | |
| 264 | const u8 num_files = memcard->GetNumFiles(); |
| 265 | const u8 free_files = Memcard::DIRLEN - num_files; |
| 266 | const u16 free_blocks = memcard->GetFreeBlocks(); |
| 267 | table->setRowCount(num_files); |
| 268 | for (int i = 0; i < num_files; i++) |
| 269 | { |
| 270 | const u8 file_index = memcard->GetFileIndex(i); |
| 271 | |
| 272 | const auto file_comments = memcard->GetSaveComments(file_index); |
| 273 | const u16 block_count = memcard->DEntry_BlockCount(file_index); |
| 274 | const auto entry = memcard->GetDEntry(file_index); |
| 275 | const std::string filename = entry ? Memcard::GenerateFilename(*entry) : ""; |
| 276 | |
| 277 | const QString title = |
| 278 | file_comments ? QString::fromStdString(file_comments->first).trimmed() : QString(); |
| 279 | const QString comment = |
| 280 | file_comments ? QString::fromStdString(file_comments->second).trimmed() : QString(); |
| 281 | auto banner = GetBannerFromSaveFile(file_index, slot); |
| 282 | auto icon_data = GetIconFromSaveFile(file_index, slot); |
| 283 | |
| 284 | auto* item_filename = new QTableWidgetItem(QString::fromStdString(filename)); |
| 285 | auto* item_banner = new QTableWidgetItem(); |
| 286 | auto* item_text = new QTableWidgetItem(QStringLiteral("%1\n%2").arg(title, comment)); |
| 287 | auto* item_icon = new QTableWidgetItem(); |
| 288 | auto* item_blocks = new QTableWidgetItem(); |
| 289 | |
| 290 | item_banner->setData(Qt::DecorationRole, banner); |
| 291 | item_icon->setData(Qt::DecorationRole, icon_data.m_frames[0]); |
| 292 | item_blocks->setData(Qt::DisplayRole, block_count); |
| 293 | |
| 294 | for (auto* item : {item_filename, item_banner, item_text, item_icon, item_blocks}) |
| 295 | { |
| 296 | item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); |
| 297 | item->setData(Qt::UserRole, static_cast<int>(file_index)); |
| 298 | } |
| 299 | |
| 300 | m_slot_active_icons[slot].emplace(file_index, std::move(icon_data)); |
| 301 | |
| 302 | table->setItem(i, COLUMN_INDEX_FILENAME, item_filename); |
| 303 | table->setItem(i, COLUMN_INDEX_BANNER, item_banner); |
| 304 | table->setItem(i, COLUMN_INDEX_TEXT, item_text); |
| 305 | table->setItem(i, COLUMN_INDEX_ICON, item_icon); |
| 306 | table->setItem(i, COLUMN_INDEX_BLOCKS, item_blocks); |
| 307 | } |
| 308 | |
| 309 | const QString free_blocks_string = tr("Free Blocks: %1").arg(free_blocks); |
| 310 | const QString free_files_string = tr("Free Files: %1").arg(free_files); |
| 311 | m_slot_stat_label[slot]->setText( |
| 312 | QStringLiteral("%1 %2").arg(free_blocks_string, free_files_string)); |
| 313 | |
| 314 | table->setSortingEnabled(true); |
| 315 | } |
| 316 | |
| 317 | void GCMemcardManager::UpdateActions() |
| 318 | { |
| 319 | auto selection = m_slot_table[m_active_slot]->selectedItems(); |
| 320 | bool have_selection = selection.count(); |
| 321 | bool have_memcard = m_slot_memcard[m_active_slot] != nullptr; |
| 322 | bool have_memcard_other = m_slot_memcard[OtherSlot(m_active_slot)] != nullptr; |
| 323 | |
| 324 | m_copy_button->setEnabled(have_selection && have_memcard_other); |
| 325 | m_export_button->setEnabled(have_selection); |
| 326 | m_import_button->setEnabled(have_memcard); |
| 327 | m_delete_button->setEnabled(have_selection); |
| 328 | m_fix_checksums_button->setEnabled(have_memcard); |
| 329 | } |
| 330 | |
| 331 | void GCMemcardManager::SetSlotFile(Slot slot, const QString& path) |
| 332 | { |
| 333 | auto [error_code, memcard] = Memcard::GCMemcard::Open(path.toStdString()); |
| 334 | |
| 335 | if (!error_code.HasCriticalErrors() && memcard && memcard->IsValid()) |
| 336 | { |
| 337 | m_slot_file_edit[slot]->setText(path); |
| 338 | m_slot_memcard[slot] = std::make_unique<Memcard::GCMemcard>(std::move(*memcard)); |
| 339 | } |
| 340 | else |
| 341 | { |
| 342 | m_slot_memcard[slot] = nullptr; |
| 343 | ModalMessageBox::warning( |
| 344 | this, tr("Error"), |
| 345 | tr("Failed opening memory card:\n%1").arg(GetErrorMessagesForErrorCode(error_code))); |
| 346 | } |
| 347 | |
| 348 | UpdateSlotTable(slot); |
| 349 | UpdateActions(); |
| 350 | } |
| 351 | |
| 352 | void GCMemcardManager::SetSlotFileInteractive(Slot slot) |
| 353 | { |
| 354 | QString path = QDir::toNativeSeparators( |
| 355 | DolphinFileDialog::getOpenFileName(this, |
| 356 | slot == Slot::A ? tr("Set Memory Card File for Slot A") : |
| 357 | tr("Set Memory Card File for Slot B"), |
| 358 | QString::fromStdString(File::GetUserPath(D_GCUSER_IDX)), |
| 359 | QStringLiteral("%1 (*.raw *.gcp);;%2 (*)") |
| 360 | .arg(tr("GameCube Memory Cards"), tr("All Files")))); |
| 361 | if (!path.isEmpty()) |
| 362 | m_slot_file_edit[slot]->setText(path); |
| 363 | } |
| 364 | |
| 365 | std::vector<u8> GCMemcardManager::GetSelectedFileIndices() |
| 366 | { |
| 367 | const auto selection = m_slot_table[m_active_slot]->selectedItems(); |
| 368 | std::vector<bool> lookup(Memcard::DIRLEN); |
| 369 | for (const auto* item : selection) |
| 370 | { |
| 371 | const int index = item->data(Qt::UserRole).toInt(); |
| 372 | if (index < 0 || index >= static_cast<int>(Memcard::DIRLEN)) |
| 373 | { |
| 374 | ModalMessageBox::warning(this, tr("Error"), |
| 375 | tr("Data inconsistency in GCMemcardManager, aborting action.")); |
| 376 | return {}; |
| 377 | } |
| 378 | lookup[index] = true; |
| 379 | } |
| 380 | |
| 381 | std::vector<u8> selected_indices; |
| 382 | for (u8 i = 0; i < Memcard::DIRLEN; ++i) |
| 383 | { |
| 384 | if (lookup[i]) |
| 385 | selected_indices.push_back(i); |
| 386 | } |
| 387 | |
| 388 | return selected_indices; |
| 389 | } |
| 390 | |
| 391 | static QString GetFormatDescription(Memcard::SavefileFormat format) |
| 392 | { |
| 393 | switch (format) |
| 394 | { |
| 395 | case Memcard::SavefileFormat::GCI: |
| 396 | return QObject::tr("Native GCI File"); |
| 397 | case Memcard::SavefileFormat::GCS: |
| 398 | return QObject::tr("MadCatz Gameshark files"); |
| 399 | case Memcard::SavefileFormat::SAV: |
| 400 | return QObject::tr("Datel MaxDrive/Pro files"); |
| 401 | default: |
| 402 | ASSERT(false); |
| 403 | return QObject::tr("Native GCI File"); |
| 404 | } |
| 405 | } |
| 406 | |
| 407 | void GCMemcardManager::ExportFiles(Memcard::SavefileFormat format) |
| 408 | { |
| 409 | const auto& memcard = m_slot_memcard[m_active_slot]; |
| 410 | if (!memcard) |
| 411 | return; |
| 412 | |
| 413 | const auto selected_indices = GetSelectedFileIndices(); |
| 414 | if (selected_indices.empty()) |
| 415 | return; |
| 416 | |
| 417 | const auto savefiles = Memcard::GetSavefiles(*memcard, selected_indices); |
| 418 | if (savefiles.empty()) |
| 419 | { |
| 420 | ModalMessageBox::warning(this, tr("Export Failed"), |
| 421 | tr("Failed to read selected savefile(s) from memory card.")); |
| 422 | return; |
| 423 | } |
| 424 | |
| 425 | std::string extension = Memcard::GetDefaultExtension(format); |
| 426 | |
| 427 | if (savefiles.size() == 1) |
| 428 | { |
| 429 | // when exporting a single save file, let user specify exact path |
| 430 | const std::string basename = Memcard::GenerateFilename(savefiles[0].dir_entry); |
| 431 | const QString qformatdesc = GetFormatDescription(format); |
| 432 | const std::string default_path = |
| 433 | fmt::format("{}/{}{}", File::GetUserPath(D_GCUSER_IDX), basename, extension); |
| 434 | const QString qfilename = DolphinFileDialog::getSaveFileName( |
| 435 | this, tr("Export Save File"), QString::fromStdString(default_path), |
| 436 | QStringLiteral("%1 (*%2);;%3 (*)") |
| 437 | .arg(qformatdesc, QString::fromStdString(extension), tr("All Files"))); |
| 438 | if (qfilename.isEmpty()) |
| 439 | return; |
| 440 | |
| 441 | const std::string filename = qfilename.toStdString(); |
| 442 | if (!Memcard::WriteSavefile(filename, savefiles[0], format)) |
| 443 | { |
| 444 | File::Delete(filename); |
| 445 | ModalMessageBox::warning(this, tr("Export Failed"), tr("Failed to write savefile to disk.")); |
| 446 | } |
| 447 | |
| 448 | return; |
| 449 | } |
| 450 | |
| 451 | const QString qdirpath = DolphinFileDialog::getExistingDirectory( |
| 452 | this, QObject::tr("Export Save Files"), |
| 453 | QString::fromStdString(File::GetUserPath(D_GCUSER_IDX))); |
| 454 | if (qdirpath.isEmpty()) |
| 455 | return; |
| 456 | |
| 457 | const std::string dirpath = qdirpath.toStdString(); |
| 458 | size_t failures = 0; |
| 459 | for (const auto& savefile : savefiles) |
| 460 | { |
| 461 | // find a free filename so we don't overwrite anything |
| 462 | const std::string basepath = dirpath + DIR_SEP + Memcard::GenerateFilename(savefile.dir_entry); |
| 463 | std::string filename = basepath + extension; |
| 464 | if (File::Exists(filename)) |
| 465 | { |
| 466 | size_t tmp = 0; |
| 467 | std::string free_name; |
| 468 | do |
| 469 | { |
| 470 | free_name = fmt::format("{}_{}{}", basepath, tmp, extension); |
| 471 | ++tmp; |
| 472 | } while (File::Exists(free_name)); |
| 473 | filename = free_name; |
| 474 | } |
| 475 | |
| 476 | if (!Memcard::WriteSavefile(filename, savefile, format)) |
| 477 | { |
| 478 | File::Delete(filename); |
| 479 | ++failures; |
| 480 | } |
| 481 | } |
| 482 | |
| 483 | if (failures > 0) |
| 484 | { |
| 485 | QString failure_string = |
| 486 | tr("Failed to export %n out of %1 save file(s).", "", static_cast<int>(failures)) |
| 487 | .arg(savefiles.size()); |
| 488 | if (failures == savefiles.size()) |
| 489 | { |
| 490 | ModalMessageBox::warning(this, tr("Export Failed"), failure_string); |
| 491 | } |
| 492 | else |
| 493 | { |
| 494 | QString success_string = tr("Successfully exported %n out of %1 save file(s).", "", |
| 495 | static_cast<int>(savefiles.size() - failures)) |
| 496 | .arg(savefiles.size()); |
| 497 | ModalMessageBox::warning(this, tr("Export Failed"), |
| 498 | QStringLiteral("%1\n%2").arg(failure_string, success_string)); |
| 499 | } |
| 500 | } |
| 501 | } |
| 502 | |
| 503 | void GCMemcardManager::ImportFiles(Slot slot, std::span<const Memcard::Savefile> savefiles) |
| 504 | { |
| 505 | auto& card = m_slot_memcard[slot]; |
| 506 | if (!card) |
| 507 | return; |
| 508 | |
| 509 | const size_t number_of_files = savefiles.size(); |
| 510 | const size_t number_of_blocks = Memcard::GetBlockCount(savefiles); |
| 511 | const size_t free_files = Memcard::DIRLEN - card->GetNumFiles(); |
| 512 | const size_t free_blocks = card->GetFreeBlocks(); |
| 513 | |
| 514 | QStringList error_messages; |
| 515 | |
| 516 | if (number_of_files > free_files) |
| 517 | { |
| 518 | error_messages.push_back( |
| 519 | tr("Not enough free files on the target memory card. At least %n free file(s) required.", |
| 520 | "", static_cast<int>(number_of_files))); |
| 521 | } |
| 522 | |
| 523 | if (number_of_blocks > free_blocks) |
| 524 | { |
| 525 | error_messages.push_back( |
| 526 | tr("Not enough free blocks on the target memory card. At least %n free block(s) required.", |
| 527 | "", static_cast<int>(number_of_blocks))); |
| 528 | } |
| 529 | |
| 530 | if (Memcard::HasDuplicateIdentity(savefiles)) |
| 531 | { |
| 532 | error_messages.push_back( |
| 533 | tr("At least two of the selected save files have the same internal filename.")); |
| 534 | } |
| 535 | |
| 536 | for (const Memcard::Savefile& savefile : savefiles) |
| 537 | { |
| 538 | if (card->TitlePresent(savefile.dir_entry)) |
| 539 | { |
| 540 | const std::string filename = Memcard::GenerateFilename(savefile.dir_entry); |
| 541 | error_messages.push_back(tr("The target memory card already contains a file \"%1\".") |
| 542 | .arg(QString::fromStdString(filename))); |
| 543 | } |
| 544 | } |
| 545 | |
| 546 | if (!error_messages.empty()) |
| 547 | { |
| 548 | ModalMessageBox::warning(this, tr("Import Failed"), error_messages.join(QLatin1Char('\n'))); |
| 549 | return; |
| 550 | } |
| 551 | |
| 552 | for (const Memcard::Savefile& savefile : savefiles) |
| 553 | { |
| 554 | const auto result = card->ImportFile(savefile); |
| 555 | |
| 556 | // we've already checked everything that could realistically fail here, so this should only |
| 557 | // happen if the memory card data is corrupted in some way |
| 558 | if (result != Memcard::GCMemcardImportFileRetVal::SUCCESS) |
| 559 | { |
| 560 | const std::string filename = Memcard::GenerateFilename(savefile.dir_entry); |
| 561 | ModalMessageBox::warning( |
| 562 | this, tr("Import Failed"), |
| 563 | tr("Failed to import \"%1\".").arg(QString::fromStdString(filename))); |
| 564 | break; |
| 565 | } |
| 566 | } |
| 567 | |
| 568 | if (!card->Save()) |
| 569 | { |
| 570 | ModalMessageBox::warning(this, tr("Import Failed"), |
| 571 | tr("Failed to write modified memory card to disk.")); |
| 572 | } |
| 573 | |
| 574 | UpdateSlotTable(slot); |
| 575 | } |
| 576 | |
| 577 | void GCMemcardManager::ImportFile() |
| 578 | { |
| 579 | auto& card = m_slot_memcard[m_active_slot]; |
| 580 | if (!card) |
| 581 | return; |
| 582 | |
| 583 | const QStringList paths = DolphinFileDialog::getOpenFileNames( |
| 584 | this, tr("Import Save File(s)"), QString::fromStdString(File::GetUserPath(D_GCUSER_IDX)), |
| 585 | QStringLiteral("%1 (*.gci *.gcs *.sav);;%2 (*.gci);;%3 (*.gcs);;%4 (*.sav);;%5 (*)") |
| 586 | .arg(tr("Supported file formats"), GetFormatDescription(Memcard::SavefileFormat::GCI), |
| 587 | GetFormatDescription(Memcard::SavefileFormat::GCS), |
| 588 | GetFormatDescription(Memcard::SavefileFormat::SAV), tr("All Files"))); |
| 589 | |
| 590 | if (paths.isEmpty()) |
| 591 | return; |
| 592 | |
| 593 | std::vector<Memcard::Savefile> savefiles; |
| 594 | savefiles.reserve(paths.size()); |
| 595 | QStringList errors; |
| 596 | for (const QString& path : paths) |
| 597 | { |
| 598 | auto read_result = Memcard::ReadSavefile(path.toStdString()); |
| 599 | std::visit(overloaded{ |
| 600 | [&](Memcard::Savefile savefile) { savefiles.emplace_back(std::move(savefile)); }, |
| 601 | [&](Memcard::ReadSavefileErrorCode error_code) { |
| 602 | errors.push_back( |
| 603 | tr("%1: %2").arg(path, GetErrorMessageForErrorCode(error_code))); |
| 604 | }, |
| 605 | }, |
| 606 | std::move(read_result)); |
| 607 | } |
| 608 | |
| 609 | if (!errors.empty()) |
| 610 | { |
| 611 | ModalMessageBox::warning( |
| 612 | this, tr("Import Failed"), |
| 613 | tr("Encountered the following errors while opening save files:\n%1\n\nAborting import.") |
| 614 | .arg(errors.join(QStringLiteral("\n")))); |
| 615 | return; |
| 616 | } |
| 617 | |
| 618 | ImportFiles(m_active_slot, savefiles); |
| 619 | } |
| 620 | |
| 621 | void GCMemcardManager::CopyFiles() |
| 622 | { |
| 623 | const auto& source_card = m_slot_memcard[m_active_slot]; |
| 624 | if (!source_card) |
| 625 | return; |
| 626 | |
| 627 | auto& target_card = m_slot_memcard[OtherSlot(m_active_slot)]; |
| 628 | if (!target_card) |
| 629 | return; |
| 630 | |
| 631 | const auto selected_indices = GetSelectedFileIndices(); |
| 632 | if (selected_indices.empty()) |
| 633 | return; |
| 634 | |
| 635 | const auto savefiles = Memcard::GetSavefiles(*source_card, selected_indices); |
| 636 | if (savefiles.empty()) |
| 637 | { |
| 638 | ModalMessageBox::warning(this, tr("Copy Failed"), |
| 639 | tr("Failed to read selected savefile(s) from memory card.")); |
| 640 | return; |
| 641 | } |
| 642 | |
| 643 | ImportFiles(OtherSlot(m_active_slot), savefiles); |
| 644 | } |
| 645 | |
| 646 | void GCMemcardManager::DeleteFiles() |
| 647 | { |
| 648 | auto& card = m_slot_memcard[m_active_slot]; |
| 649 | if (!card) |
| 650 | return; |
| 651 | |
| 652 | const auto selected_indices = GetSelectedFileIndices(); |
| 653 | if (selected_indices.empty()) |
| 654 | return; |
| 655 | |
| 656 | const QString text = tr("Do you want to delete the %n selected save file(s)?", "", |
| 657 | static_cast<int>(selected_indices.size())); |
| 658 | const auto response = ModalMessageBox::question(this, tr("Question"), text); |
| 659 | if (response != QMessageBox::Yes) |
| 660 | return; |
| 661 | |
| 662 | for (const u8 index : selected_indices) |
| 663 | { |
| 664 | if (card->RemoveFile(index) != Memcard::GCMemcardRemoveFileRetVal::SUCCESS) |
| 665 | { |
| 666 | ModalMessageBox::warning(this, tr("Remove Failed"), tr("Failed to remove file.")); |
| 667 | break; |
| 668 | } |
| 669 | } |
| 670 | |
| 671 | if (!card->Save()) |
| 672 | { |
| 673 | ModalMessageBox::warning(this, tr("Remove Failed"), |
| 674 | tr("Failed to write modified memory card to disk.")); |
| 675 | } |
| 676 | |
| 677 | UpdateSlotTable(m_active_slot); |
| 678 | UpdateActions(); |
| 679 | } |
| 680 | |
| 681 | void GCMemcardManager::FixChecksums() |
| 682 | { |
| 683 | auto& memcard = m_slot_memcard[m_active_slot]; |
| 684 | memcard->FixChecksums(); |
| 685 | |
| 686 | if (!memcard->Save()) |
| 687 | { |
| 688 | ModalMessageBox::warning(this, tr("Fix Checksums Failed"), |
| 689 | tr("Failed to write modified memory card to disk.")); |
| 690 | } |
| 691 | } |
| 692 | |
| 693 | void GCMemcardManager::CreateNewCard(Slot slot) |
| 694 | { |
| 695 | GCMemcardCreateNewDialog dialog(this); |
| 696 | if (dialog.exec() == QDialog::Accepted) |
| 697 | m_slot_file_edit[slot]->setText(QString::fromStdString(dialog.GetMemoryCardPath())); |
| 698 | } |
| 699 | |
| 700 | void GCMemcardManager::DrawIcons() |
| 701 | { |
| 702 | const int column = COLUMN_INDEX_ICON; |
| 703 | for (Slot slot : MEMCARD_SLOTS) |
| 704 | { |
| 705 | QTableWidget* table = m_slot_table[slot]; |
| 706 | const int row_count = table->rowCount(); |
| 707 | |
| 708 | if (row_count <= 0) |
| 709 | continue; |
| 710 | |
| 711 | const auto viewport = table->viewport(); |
| 712 | const int viewport_first_row = table->indexAt(viewport->rect().topLeft()).row(); |
| 713 | if (viewport_first_row >= row_count) |
| 714 | continue; |
| 715 | |
| 716 | const int first_row = viewport_first_row < 0 ? 0 : viewport_first_row; |
| 717 | const int viewport_last_row = table->indexAt(viewport->rect().bottomLeft()).row(); |
| 718 | const int last_row = |
| 719 | viewport_last_row < 0 ? (row_count - 1) : std::min(viewport_last_row, row_count - 1); |
| 720 | |
| 721 | for (int row = first_row; row <= last_row; ++row) |
| 722 | { |
| 723 | auto* item = table->item(row, column); |
| 724 | if (!item) |
| 725 | continue; |
| 726 | |
| 727 | const u8 index = static_cast<u8>(item->data(Qt::UserRole).toInt()); |
| 728 | auto it = m_slot_active_icons[slot].find(index); |
| 729 | if (it == m_slot_active_icons[slot].end()) |
| 730 | continue; |
| 731 | |
| 732 | const auto& icon = it->second; |
| 733 | |
| 734 | // this icon doesn't have an animation |
| 735 | if (icon.m_frames.size() <= 1) |
| 736 | continue; |
| 737 | |
| 738 | const u64 prev_time_in_animation = (m_current_frame - 1) % icon.m_frame_timing.size(); |
| 739 | const u8 prev_frame = icon.m_frame_timing[prev_time_in_animation]; |
| 740 | const u64 current_time_in_animation = m_current_frame % icon.m_frame_timing.size(); |
| 741 | const u8 current_frame = icon.m_frame_timing[current_time_in_animation]; |
| 742 | |
| 743 | if (prev_frame == current_frame) |
| 744 | continue; |
| 745 | |
| 746 | item->setData(Qt::DecorationRole, icon.m_frames[current_frame]); |
| 747 | } |
| 748 | } |
| 749 | |
| 750 | ++m_current_frame; |
| 751 | } |
| 752 | |
| 753 | QPixmap GCMemcardManager::GetBannerFromSaveFile(int file_index, Slot slot) |
| 754 | { |
| 755 | auto& memcard = m_slot_memcard[slot]; |
| 756 | |
| 757 | auto pxdata = memcard->ReadBannerRGBA8(file_index); |
| 758 | |
| 759 | QImage image; |
| 760 | if (pxdata) |
| 761 | { |
| 762 | image = QImage(reinterpret_cast<u8*>(pxdata->data()), Memcard::MEMORY_CARD_BANNER_WIDTH, |
| 763 | Memcard::MEMORY_CARD_BANNER_HEIGHT, QImage::Format_ARGB32); |
| 764 | } |
| 765 | |
| 766 | return QPixmap::fromImage(image); |
| 767 | } |
| 768 | |
| 769 | GCMemcardManager::IconAnimationData GCMemcardManager::GetIconFromSaveFile(int file_index, Slot slot) |
| 770 | { |
| 771 | auto& memcard = m_slot_memcard[slot]; |
| 772 | |
| 773 | IconAnimationData frame_data; |
| 774 | |
| 775 | const auto decoded_data = memcard->ReadAnimRGBA8(file_index); |
| 776 | |
| 777 | // Decode Save File Animation |
| 778 | if (decoded_data && !decoded_data->empty()) |
| 779 | { |
| 780 | frame_data.m_frames.reserve(decoded_data->size()); |
| 781 | |
| 782 | for (size_t f = 0; f < decoded_data->size(); ++f) |
| 783 | { |
| 784 | QImage img(reinterpret_cast<const u8*>((*decoded_data)[f].image_data.data()), |
| 785 | Memcard::MEMORY_CARD_ICON_WIDTH, Memcard::MEMORY_CARD_ICON_HEIGHT, |
| 786 | QImage::Format_ARGB32); |
| 787 | frame_data.m_frames.push_back(QPixmap::fromImage(img)); |
| 788 | for (int i = 0; i < (*decoded_data)[f].delay; ++i) |
| 789 | { |
| 790 | frame_data.m_frame_timing.push_back(static_cast<u8>(f)); |
| 791 | } |
| 792 | } |
| 793 | |
| 794 | const bool is_pingpong = memcard->DEntry_IsPingPong(file_index); |
| 795 | if (is_pingpong && decoded_data->size() >= 3) |
| 796 | { |
| 797 | // if the animation 'ping-pongs' between start and end then the animation frame order is |
| 798 | // something like 'abcdcbabcdcba' instead of the usual 'abcdabcdabcd' |
| 799 | // to display that correctly just append all except the first and last frame in reverse order |
| 800 | // at the end of the animation |
| 801 | for (size_t f = decoded_data->size() - 2; f > 0; --f) |
| 802 | { |
| 803 | for (int i = 0; i < (*decoded_data)[f].delay; ++i) |
| 804 | { |
| 805 | frame_data.m_frame_timing.push_back(static_cast<u8>(f)); |
| 806 | } |
| 807 | } |
| 808 | } |
| 809 | } |
| 810 | else |
| 811 | { |
| 812 | // No Animation found, use an empty placeholder instead. |
| 813 | frame_data.m_frames.emplace_back(); |
| 814 | frame_data.m_frame_timing.push_back(0); |
| 815 | } |
| 816 | |
| 817 | return frame_data; |
| 818 | } |
| 819 | |
| 820 | QString GCMemcardManager::GetErrorMessagesForErrorCode(const Memcard::GCMemcardErrorCode& code) |
| 821 | { |
| 822 | QStringList sl; |
| 823 | |
| 824 | if (code.Test(Memcard::GCMemcardValidityIssues::FAILED_TO_OPEN)) |
| 825 | sl.push_back(tr("Couldn't open file.")); |
| 826 | |
| 827 | if (code.Test(Memcard::GCMemcardValidityIssues::IO_ERROR)) |
| 828 | sl.push_back(tr("Couldn't read file.")); |
| 829 | |
| 830 | if (code.Test(Memcard::GCMemcardValidityIssues::INVALID_CARD_SIZE)) |
| 831 | sl.push_back(tr("Filesize does not match any known GameCube Memory Card size.")); |
| 832 | |
| 833 | if (code.Test(Memcard::GCMemcardValidityIssues::MISMATCHED_CARD_SIZE)) |
| 834 | sl.push_back(tr("Filesize in header mismatches actual card size.")); |
| 835 | |
| 836 | if (code.Test(Memcard::GCMemcardValidityIssues::INVALID_CHECKSUM)) |
| 837 | sl.push_back(tr("Invalid checksums.")); |
| 838 | |
| 839 | if (code.Test(Memcard::GCMemcardValidityIssues::FREE_BLOCK_MISMATCH)) |
| 840 | sl.push_back(tr("Mismatch between free block count in header and actually unused blocks.")); |
| 841 | |
| 842 | if (code.Test(Memcard::GCMemcardValidityIssues::DIR_BAT_INCONSISTENT)) |
| 843 | sl.push_back(tr("Mismatch between internal data structures.")); |
| 844 | |
| 845 | if (code.Test(Memcard::GCMemcardValidityIssues::DATA_IN_UNUSED_AREA)) |
| 846 | sl.push_back(tr("Data in area of file that should be unused.")); |
| 847 | |
| 848 | if (sl.empty()) |
| 849 | return tr("No errors."); |
| 850 | |
| 851 | return sl.join(QLatin1Char{'\n'}); |
| 852 | } |
| 853 | |
| 854 | QString GCMemcardManager::GetErrorMessageForErrorCode(Memcard::ReadSavefileErrorCode code) |
| 855 | { |
| 856 | switch (code) |
| 857 | { |
| 858 | case Memcard::ReadSavefileErrorCode::OpenFileFail: |
| 859 | return tr("Failed to open file."); |
| 860 | case Memcard::ReadSavefileErrorCode::IOError: |
| 861 | return tr("Failed to read from file."); |
| 862 | case Memcard::ReadSavefileErrorCode::DataCorrupted: |
| 863 | return tr("Data in unrecognized format or corrupted."); |
| 864 | default: |
| 865 | return tr("Unknown error."); |
| 866 | } |
| 867 | } |