GCMemcardManager.cpp 29 KB

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