Debian Codegraph @

Source/Core/DolphinQt/GameList/GameListModel.cpp

raw symbols SCIP
1 // Copyright 2015 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "DolphinQt/GameList/GameListModel.h"
5
6 #include <QDir>
7 #include <QFileInfo>
8 #include <QPixmap>
9 #include <QRegularExpression>
10
11 #include "Core/Config/MainSettings.h"
12 #include "Core/Core.h"
13 #include "Core/TimePlayed.h"
14
15 #include "DiscIO/Enums.h"
16
17 #include "DolphinQt/QtUtils/ImageConverter.h"
18 #include "DolphinQt/Resources.h"
19 #include "DolphinQt/Settings.h"
20
21 #include "UICommon/GameFile.h"
22 #include "UICommon/UICommon.h"
23
24 const QSize GAMECUBE_BANNER_SIZE(96, 32);
25
26 GameListModel::GameListModel(QObject* parent) : QAbstractTableModel(parent)
27 {
28 connect(&m_tracker, &GameTracker::GameLoaded, this, &GameListModel::AddGame);
29 connect(&m_tracker, &GameTracker::GameUpdated, this, &GameListModel::UpdateGame);
30 connect(&m_tracker, &GameTracker::GameRemoved, this, &GameListModel::RemoveGame);
31 connect(&Settings::Instance(), &Settings::PathAdded, &m_tracker, &GameTracker::AddDirectory);
32 connect(&Settings::Instance(), &Settings::PathRemoved, &m_tracker, &GameTracker::RemoveDirectory);
33 connect(&Settings::Instance(), &Settings::GameListRefreshRequested, &m_tracker,
34 &GameTracker::RefreshAll);
35 connect(&Settings::Instance(), &Settings::TitleDBReloadRequested,
36 [this] { m_title_database = Core::TitleDatabase(); });
37 connect(&Settings::Instance(), &Settings::EmulationStateChanged, this,
38 &GameListModel::OnEmulationStateChanged);
39
40 for (const QString& dir : Settings::Instance().GetPaths())
41 m_tracker.AddDirectory(dir);
42
43 m_tracker.Start();
44
45 connect(&Settings::Instance(), &Settings::ThemeChanged, [this] {
46 // Tell the view to repaint. The signal 'dataChanged' also seems like it would work here, but
47 // unfortunately it won't cause a repaint until the view is focused.
48 emit layoutAboutToBeChanged();
49 emit layoutChanged();
50 });
51
52 auto& settings = Settings::GetQSettings();
53
54 m_tag_list = settings.value(QStringLiteral("gamelist/tags")).toStringList();
55 m_game_tags = settings.value(QStringLiteral("gamelist/game_tags")).toMap();
56 }
57
58 QVariant GameListModel::data(const QModelIndex& index, int role) const
59 {
60 if (!index.isValid())
61 return QVariant();
62
63 const UICommon::GameFile& game = *m_games[index.row()];
64
65 switch (static_cast<Column>(index.column()))
66 {
67 case Column::Platform:
68 if (role == Qt::DecorationRole)
69 return Resources::GetPlatform(game.GetPlatform()).pixmap(32, 32);
70 if (role == SORT_ROLE)
71 return static_cast<int>(game.GetPlatform());
72 break;
73 case Column::Country:
74 if (role == Qt::DecorationRole)
75 return Resources::GetCountry(game.GetCountry()).pixmap(32, 22);
76 if (role == SORT_ROLE)
77 return static_cast<int>(game.GetCountry());
78 break;
79 case Column::Banner:
80 if (role == Qt::DecorationRole)
81 {
82 // GameCube banners are 96x32, but Wii banners are 192x64.
83 QPixmap banner = ToQPixmap(game.GetBannerImage());
84 if (banner.isNull())
85 banner = Resources::GetMisc(Resources::MiscID::BannerMissing).pixmap(GAMECUBE_BANNER_SIZE);
86
87 banner.setDevicePixelRatio(
88 std::max(static_cast<qreal>(banner.width()) / GAMECUBE_BANNER_SIZE.width(),
89 static_cast<qreal>(banner.height()) / GAMECUBE_BANNER_SIZE.height()));
90
91 return banner;
92 }
93 break;
94 case Column::Title:
95 if (role == Qt::DisplayRole || role == SORT_ROLE)
96 {
97 QString name = QString::fromStdString(game.GetName(m_title_database));
98
99 const int disc_number = game.GetDiscNumber() + 1;
100 if (disc_number > 1 || game.IsTwoDiscGame())
101 {
102 // Add disc number to title if not present.
103 if (!name.contains(QRegularExpression(QStringLiteral("disc ?%1").arg(disc_number),
104 QRegularExpression::CaseInsensitiveOption)))
105 {
106 name.append(tr(" (Disc %1)").arg(disc_number));
107 }
108 }
109
110 // For natural sorting, pad all numbers to the same length.
111 if (SORT_ROLE == role)
112 {
113 constexpr int MAX_NUMBER_LENGTH = 10;
114
115 const QRegularExpression rx(QStringLiteral("\\d+"));
116 QRegularExpressionMatch match;
117 int pos = 0;
118 while ((match = rx.match(name, pos)).hasMatch())
119 {
120 pos = match.capturedStart();
121 name.replace(pos, match.capturedLength(),
122 match.captured().rightJustified(MAX_NUMBER_LENGTH));
123 pos += MAX_NUMBER_LENGTH;
124 }
125 }
126
127 return name;
128 }
129 break;
130 case Column::ID:
131 if (role == Qt::DisplayRole || role == SORT_ROLE)
132 return QString::fromStdString(game.GetGameID());
133 break;
134 case Column::Description:
135 if (role == Qt::DisplayRole || role == SORT_ROLE)
136 {
137 return QString::fromStdString(
138 game.GetDescription(UICommon::GameFile::Variant::LongAndPossiblyCustom))
139 .replace(QLatin1Char('\n'), QLatin1Char(' '));
140 }
141 break;
142 case Column::Maker:
143 if (role == Qt::DisplayRole || role == SORT_ROLE)
144 {
145 return QString::fromStdString(
146 game.GetMaker(UICommon::GameFile::Variant::LongAndPossiblyCustom));
147 }
148 break;
149 case Column::FileName:
150 if (role == Qt::DisplayRole || role == SORT_ROLE)
151 return QString::fromStdString(game.GetFileName());
152 break;
153 case Column::FilePath:
154 if (role == Qt::DisplayRole || role == SORT_ROLE)
155 {
156 QString file_path = QDir::toNativeSeparators(
157 QFileInfo(QString::fromStdString(game.GetFilePath())).absolutePath());
158 if (!file_path.endsWith(QDir::separator()))
159 file_path.append(QDir::separator());
160 return file_path;
161 }
162 break;
163 case Column::Size:
164 if (role == Qt::DisplayRole)
165 {
166 std::string str = UICommon::FormatSize(game.GetFileSize());
167
168 // Add asterisk to size of compressed files.
169 if (game.GetFileSize() != game.GetVolumeSize())
170 str += '*';
171
172 return QString::fromStdString(str);
173 }
174 if (role == SORT_ROLE)
175 return static_cast<quint64>(game.GetFileSize());
176 break;
177 case Column::FileFormat:
178 if (role == Qt::DisplayRole || role == SORT_ROLE)
179 return QString::fromStdString(game.GetFileFormatName());
180 break;
181 case Column::BlockSize:
182 if (role == Qt::DisplayRole)
183 return QString::fromStdString(UICommon::FormatSize(game.GetBlockSize()));
184 if (role == SORT_ROLE)
185 return static_cast<quint64>(game.GetBlockSize());
186 break;
187 case Column::Compression:
188 if (role == Qt::DisplayRole || role == SORT_ROLE)
189 {
190 const QString compression = QString::fromStdString(game.GetCompressionMethod());
191 return compression.isEmpty() ? tr("No Compression") : compression;
192 }
193 break;
194 case Column::TimePlayed:
195 if (role == Qt::DisplayRole)
196 {
197 const std::string game_id = game.GetGameID();
198 const std::chrono::milliseconds total_time = m_timer.GetTimePlayed(game_id);
199 const auto total_minutes = std::chrono::duration_cast<std::chrono::minutes>(total_time);
200 const auto total_hours = std::chrono::duration_cast<std::chrono::hours>(total_time);
201
202 // i18n: A time displayed as hours and minutes
203 QString formatted_time =
204 tr("%1h %2m").arg(total_hours.count()).arg(total_minutes.count() % 60);
205 return formatted_time;
206 }
207 if (role == SORT_ROLE)
208 {
209 const std::string game_id = game.GetGameID();
210 return static_cast<qlonglong>(m_timer.GetTimePlayed(game_id).count());
211 }
212 break;
213 case Column::Tags:
214 if (role == Qt::DisplayRole || role == SORT_ROLE)
215 {
216 auto tags = GetGameTags(game.GetFilePath());
217 tags.sort();
218
219 return tags.join(QStringLiteral(", "));
220 }
221 break;
222 default:
223 break;
224 }
225
226 return QVariant();
227 }
228
229 QVariant GameListModel::headerData(int section, Qt::Orientation orientation, int role) const
230 {
231 if (orientation == Qt::Vertical || role != Qt::DisplayRole)
232 return QVariant();
233
234 switch (static_cast<Column>(section))
235 {
236 case Column::Title:
237 return tr("Title");
238 case Column::ID:
239 return tr("ID");
240 case Column::Banner:
241 return tr("Banner");
242 case Column::Description:
243 return tr("Description");
244 case Column::Maker:
245 return tr("Maker");
246 case Column::FileName:
247 return tr("File Name");
248 case Column::FilePath:
249 return tr("File Path");
250 case Column::Size:
251 return tr("Size");
252 case Column::FileFormat:
253 return tr("File Format");
254 case Column::BlockSize:
255 return tr("Block Size");
256 case Column::Compression:
257 return tr("Compression");
258 case Column::TimePlayed:
259 return tr("Time Played");
260 case Column::Tags:
261 return tr("Tags");
262 default:
263 break;
264 }
265 return QVariant();
266 }
267
268 int GameListModel::rowCount(const QModelIndex& parent) const
269 {
270 if (parent.isValid())
271 return 0;
272 return m_games.size();
273 }
274
275 int GameListModel::columnCount(const QModelIndex& parent) const
276 {
277 if (parent.isValid())
278 return 0;
279 return static_cast<int>(Column::Count);
280 }
281
282 bool GameListModel::ShouldDisplayGameListItem(int index) const
283 {
284 const UICommon::GameFile& game = *m_games[index];
285
286 if (!m_term.isEmpty())
287 {
288 const bool matches_title = QString::fromStdString(game.GetName(m_title_database))
289 .contains(m_term, Qt::CaseInsensitive);
290 const bool filename_visible = Config::Get(Config::MAIN_GAMELIST_COLUMN_FILE_NAME);
291 const bool list_view_selected = Settings::Instance().GetPreferredView();
292 const bool matches_filename =
293 filename_visible && list_view_selected &&
294 QString::fromStdString(game.GetFileName()).contains(m_term, Qt::CaseInsensitive);
295 if (!(matches_title || matches_filename))
296 {
297 return false;
298 }
299 }
300
301 const bool show_platform = [&game] {
302 switch (game.GetPlatform())
303 {
304 case DiscIO::Platform::GameCubeDisc:
305 return Config::Get(Config::MAIN_GAMELIST_LIST_GC);
306 case DiscIO::Platform::Triforce:
307 return Config::Get(Config::MAIN_GAMELIST_LIST_TRI);
308 case DiscIO::Platform::WiiDisc:
309 return Config::Get(Config::MAIN_GAMELIST_LIST_WII);
310 case DiscIO::Platform::WiiWAD:
311 return Config::Get(Config::MAIN_GAMELIST_LIST_WAD);
312 case DiscIO::Platform::ELFOrDOL:
313 return Config::Get(Config::MAIN_GAMELIST_LIST_ELF_DOL);
314 default:
315 return false;
316 }
317 }();
318
319 if (!show_platform)
320 return false;
321
322 switch (game.GetCountry())
323 {
324 case DiscIO::Country::Australia:
325 return Config::Get(Config::MAIN_GAMELIST_LIST_AUSTRALIA);
326 case DiscIO::Country::Europe:
327 return Config::Get(Config::MAIN_GAMELIST_LIST_PAL);
328 case DiscIO::Country::France:
329 return Config::Get(Config::MAIN_GAMELIST_LIST_FRANCE);
330 case DiscIO::Country::Germany:
331 return Config::Get(Config::MAIN_GAMELIST_LIST_GERMANY);
332 case DiscIO::Country::Italy:
333 return Config::Get(Config::MAIN_GAMELIST_LIST_ITALY);
334 case DiscIO::Country::Japan:
335 return Config::Get(Config::MAIN_GAMELIST_LIST_JPN);
336 case DiscIO::Country::Korea:
337 return Config::Get(Config::MAIN_GAMELIST_LIST_KOREA);
338 case DiscIO::Country::Netherlands:
339 return Config::Get(Config::MAIN_GAMELIST_LIST_NETHERLANDS);
340 case DiscIO::Country::Russia:
341 return Config::Get(Config::MAIN_GAMELIST_LIST_RUSSIA);
342 case DiscIO::Country::Spain:
343 return Config::Get(Config::MAIN_GAMELIST_LIST_SPAIN);
344 case DiscIO::Country::Taiwan:
345 return Config::Get(Config::MAIN_GAMELIST_LIST_TAIWAN);
346 case DiscIO::Country::USA:
347 return Config::Get(Config::MAIN_GAMELIST_LIST_USA);
348 case DiscIO::Country::World:
349 return Config::Get(Config::MAIN_GAMELIST_LIST_WORLD);
350 case DiscIO::Country::Unknown:
351 default:
352 return Config::Get(Config::MAIN_GAMELIST_LIST_UNKNOWN);
353 }
354 }
355
356 std::shared_ptr<const UICommon::GameFile> GameListModel::GetGameFile(int index) const
357 {
358 return m_games[index];
359 }
360
361 std::string GameListModel::GetNetPlayName(const UICommon::GameFile& game) const
362 {
363 return game.GetNetPlayName(m_title_database);
364 }
365
366 void GameListModel::AddGame(const std::shared_ptr<const UICommon::GameFile>& game)
367 {
368 beginInsertRows(QModelIndex(), m_games.size(), m_games.size());
369 m_games.push_back(game);
370 endInsertRows();
371 }
372
373 void GameListModel::UpdateGame(const std::shared_ptr<const UICommon::GameFile>& game)
374 {
375 int index = FindGameIndex(game->GetFilePath());
376 if (index < 0)
377 {
378 AddGame(game);
379 }
380 else
381 {
382 m_games[index] = game;
383 emit dataChanged(createIndex(index, 0), createIndex(index, columnCount(QModelIndex()) - 1));
384 }
385 }
386
387 void GameListModel::RemoveGame(const std::string& path)
388 {
389 int entry = FindGameIndex(path);
390 if (entry < 0)
391 return;
392
393 beginRemoveRows(QModelIndex(), entry, entry);
394 m_games.removeAt(entry);
395 endRemoveRows();
396 }
397
398 std::shared_ptr<const UICommon::GameFile> GameListModel::FindGame(const std::string& path) const
399 {
400 const int index = FindGameIndex(path);
401 return index < 0 ? nullptr : m_games[index];
402 }
403
404 int GameListModel::FindGameIndex(const std::string& path) const
405 {
406 for (int i = 0; i < m_games.size(); i++)
407 {
408 if (m_games[i]->GetFilePath() == path)
409 return i;
410 }
411 return -1;
412 }
413
414 std::shared_ptr<const UICommon::GameFile>
415 GameListModel::FindSecondDisc(const UICommon::GameFile& game) const
416 {
417 std::shared_ptr<const UICommon::GameFile> match_without_revision = nullptr;
418
419 if (DiscIO::IsDisc(game.GetPlatform()))
420 {
421 for (auto& other_game : m_games)
422 {
423 if (game.GetGameID() == other_game->GetGameID() &&
424 game.GetDiscNumber() != other_game->GetDiscNumber())
425 {
426 if (game.GetRevision() == other_game->GetRevision())
427 return other_game;
428 else
429 match_without_revision = other_game;
430 }
431 }
432 }
433
434 return match_without_revision;
435 }
436
437 void GameListModel::SetSearchTerm(const QString& term)
438 {
439 m_term = term;
440 }
441
442 void GameListModel::SetScale(float scale)
443 {
444 m_scale = scale;
445 }
446
447 float GameListModel::GetScale() const
448 {
449 return m_scale;
450 }
451
452 const QStringList& GameListModel::GetAllTags() const
453 {
454 return m_tag_list;
455 }
456
457 const QStringList GameListModel::GetGameTags(const std::string& path) const
458 {
459 return m_game_tags[QString::fromStdString(path)].toStringList();
460 }
461
462 void GameListModel::AddGameTag(const std::string& path, const QString& name)
463 {
464 auto tags = GetGameTags(path);
465
466 if (tags.contains(name))
467 return;
468
469 tags << name;
470
471 m_game_tags[QString::fromStdString(path)] = tags;
472 Settings::GetQSettings().setValue(QStringLiteral("gamelist/game_tags"), m_game_tags);
473
474 const int row = FindGameIndex(path);
475 if (row >= 0)
476 {
477 const QModelIndex index = createIndex(row, static_cast<int>(Column::Tags));
478 emit dataChanged(index, index);
479 }
480 }
481
482 void GameListModel::RemoveGameTag(const std::string& path, const QString& name)
483 {
484 auto tags = GetGameTags(path);
485
486 tags.removeAll(name);
487
488 m_game_tags[QString::fromStdString(path)] = tags;
489
490 Settings::GetQSettings().setValue(QStringLiteral("gamelist/game_tags"), m_game_tags);
491
492 const int row = FindGameIndex(path);
493 if (row >= 0)
494 {
495 const QModelIndex index = createIndex(row, static_cast<int>(Column::Tags));
496 emit dataChanged(index, index);
497 }
498 }
499
500 void GameListModel::NewTag(const QString& name)
501 {
502 if (m_tag_list.contains(name))
503 return;
504
505 m_tag_list << name;
506
507 Settings::GetQSettings().setValue(QStringLiteral("gamelist/tags"), m_tag_list);
508 }
509
510 void GameListModel::DeleteTag(const QString& name)
511 {
512 m_tag_list.removeAll(name);
513
514 for (const auto& file : m_game_tags.keys())
515 RemoveGameTag(file.toStdString(), name);
516
517 Settings::GetQSettings().setValue(QStringLiteral("gamelist/tags"), m_tag_list);
518 }
519
520 void GameListModel::PurgeCache()
521 {
522 m_tracker.PurgeCache();
523 }
524
525 void GameListModel::OnEmulationStateChanged(Core::State state)
526 {
527 if (state == Core::State::Uninitialized)
528 {
529 m_timer.Reload();
530 }
531 }