From 5464423667dedc0f09d48f85fc7871a3e56127a4 Mon Sep 17 00:00:00 2001 From: Mario Date: Sat, 26 Aug 2023 21:19:00 -0400 Subject: yuzu-qt: Track play time --- src/common/fs/fs_paths.h | 1 + src/common/fs/path_util.cpp | 1 + src/common/fs/path_util.h | 1 + src/yuzu/CMakeLists.txt | 2 + src/yuzu/configuration/configure_ui.cpp | 5 + src/yuzu/configuration/configure_ui.ui | 7 ++ src/yuzu/game_list.cpp | 6 ++ src/yuzu/game_list.h | 2 + src/yuzu/game_list_p.h | 26 +++++ src/yuzu/game_list_worker.cpp | 2 + src/yuzu/main.cpp | 26 +++++ src/yuzu/main.h | 7 ++ src/yuzu/play_time.cpp | 177 ++++++++++++++++++++++++++++++++ src/yuzu/play_time.h | 68 ++++++++++++ src/yuzu/uisettings.h | 3 + 15 files changed, 334 insertions(+) create mode 100644 src/yuzu/play_time.cpp create mode 100644 src/yuzu/play_time.h diff --git a/src/common/fs/fs_paths.h b/src/common/fs/fs_paths.h index 61bac9eba..59d66f71e 100644 --- a/src/common/fs/fs_paths.h +++ b/src/common/fs/fs_paths.h @@ -18,6 +18,7 @@ #define LOAD_DIR "load" #define LOG_DIR "log" #define NAND_DIR "nand" +#define PLAY_TIME_DIR "play_time" #define SCREENSHOTS_DIR "screenshots" #define SDMC_DIR "sdmc" #define SHADER_DIR "shader" diff --git a/src/common/fs/path_util.cpp b/src/common/fs/path_util.cpp index d71cfacc6..3bbe9ff87 100644 --- a/src/common/fs/path_util.cpp +++ b/src/common/fs/path_util.cpp @@ -122,6 +122,7 @@ public: GenerateYuzuPath(YuzuPath::LoadDir, yuzu_path / LOAD_DIR); GenerateYuzuPath(YuzuPath::LogDir, yuzu_path / LOG_DIR); GenerateYuzuPath(YuzuPath::NANDDir, yuzu_path / NAND_DIR); + GenerateYuzuPath(YuzuPath::PlayTimeDir, yuzu_path / PLAY_TIME_DIR); GenerateYuzuPath(YuzuPath::ScreenshotsDir, yuzu_path / SCREENSHOTS_DIR); GenerateYuzuPath(YuzuPath::SDMCDir, yuzu_path / SDMC_DIR); GenerateYuzuPath(YuzuPath::ShaderDir, yuzu_path / SHADER_DIR); diff --git a/src/common/fs/path_util.h b/src/common/fs/path_util.h index ba28964d0..289974e32 100644 --- a/src/common/fs/path_util.h +++ b/src/common/fs/path_util.h @@ -20,6 +20,7 @@ enum class YuzuPath { LoadDir, // Where cheat/mod files are stored. LogDir, // Where log files are stored. NANDDir, // Where the emulated NAND is stored. + PlayTimeDir, // Where play time data is stored. ScreenshotsDir, // Where yuzu screenshots are stored. SDMCDir, // Where the emulated SDMC is stored. ShaderDir, // Where shaders are stored. diff --git a/src/yuzu/CMakeLists.txt b/src/yuzu/CMakeLists.txt index 8f86a1553..89763f64f 100644 --- a/src/yuzu/CMakeLists.txt +++ b/src/yuzu/CMakeLists.txt @@ -195,6 +195,8 @@ add_executable(yuzu multiplayer/state.cpp multiplayer/state.h multiplayer/validation.h + play_time.cpp + play_time.h precompiled_headers.h qt_common.cpp qt_common.h diff --git a/src/yuzu/configuration/configure_ui.cpp b/src/yuzu/configuration/configure_ui.cpp index 34ab01617..058bd9f4d 100644 --- a/src/yuzu/configuration/configure_ui.cpp +++ b/src/yuzu/configuration/configure_ui.cpp @@ -126,6 +126,8 @@ ConfigureUi::ConfigureUi(Core::System& system_, QWidget* parent) connect(ui->show_compat, &QCheckBox::stateChanged, this, &ConfigureUi::RequestGameListUpdate); connect(ui->show_size, &QCheckBox::stateChanged, this, &ConfigureUi::RequestGameListUpdate); connect(ui->show_types, &QCheckBox::stateChanged, this, &ConfigureUi::RequestGameListUpdate); + connect(ui->show_play_time, &QCheckBox::stateChanged, this, + &ConfigureUi::RequestGameListUpdate); connect(ui->game_icon_size_combobox, QOverload::of(&QComboBox::currentIndexChanged), this, &ConfigureUi::RequestGameListUpdate); connect(ui->folder_icon_size_combobox, QOverload::of(&QComboBox::currentIndexChanged), @@ -170,6 +172,7 @@ void ConfigureUi::ApplyConfiguration() { UISettings::values.show_compat = ui->show_compat->isChecked(); UISettings::values.show_size = ui->show_size->isChecked(); UISettings::values.show_types = ui->show_types->isChecked(); + UISettings::values.show_play_time = ui->show_play_time->isChecked(); UISettings::values.game_icon_size = ui->game_icon_size_combobox->currentData().toUInt(); UISettings::values.folder_icon_size = ui->folder_icon_size_combobox->currentData().toUInt(); UISettings::values.row_1_text_id = ui->row_1_text_combobox->currentData().toUInt(); @@ -182,6 +185,7 @@ void ConfigureUi::ApplyConfiguration() { const u32 height = ScreenshotDimensionToInt(ui->screenshot_height->currentText()); UISettings::values.screenshot_height.SetValue(height); + RequestGameListUpdate(); system.ApplySettings(); } @@ -197,6 +201,7 @@ void ConfigureUi::SetConfiguration() { ui->show_compat->setChecked(UISettings::values.show_compat.GetValue()); ui->show_size->setChecked(UISettings::values.show_size.GetValue()); ui->show_types->setChecked(UISettings::values.show_types.GetValue()); + ui->show_play_time->setChecked(UISettings::values.show_play_time.GetValue()); ui->game_icon_size_combobox->setCurrentIndex( ui->game_icon_size_combobox->findData(UISettings::values.game_icon_size.GetValue())); ui->folder_icon_size_combobox->setCurrentIndex( diff --git a/src/yuzu/configuration/configure_ui.ui b/src/yuzu/configuration/configure_ui.ui index cb66ef104..b8e648381 100644 --- a/src/yuzu/configuration/configure_ui.ui +++ b/src/yuzu/configuration/configure_ui.ui @@ -104,6 +104,13 @@ + + + + Show Play Time Column + + + diff --git a/src/yuzu/game_list.cpp b/src/yuzu/game_list.cpp index b5a02700d..98e410e0f 100644 --- a/src/yuzu/game_list.cpp +++ b/src/yuzu/game_list.cpp @@ -340,6 +340,7 @@ GameList::GameList(FileSys::VirtualFilesystem vfs_, FileSys::ManualContentProvid tree_view->setColumnHidden(COLUMN_ADD_ONS, !UISettings::values.show_add_ons); tree_view->setColumnHidden(COLUMN_COMPATIBILITY, !UISettings::values.show_compat); + tree_view->setColumnHidden(COLUMN_PLAY_TIME, !UISettings::values.show_play_time); item_model->setSortRole(GameListItemPath::SortRole); connect(main_window, &GMainWindow::UpdateThemedIcons, this, &GameList::OnUpdateThemedIcons); @@ -548,6 +549,7 @@ void GameList::AddGamePopup(QMenu& context_menu, u64 program_id, const std::stri QAction* remove_update = remove_menu->addAction(tr("Remove Installed Update")); QAction* remove_dlc = remove_menu->addAction(tr("Remove All Installed DLC")); QAction* remove_custom_config = remove_menu->addAction(tr("Remove Custom Configuration")); + QAction* remove_play_time_data = remove_menu->addAction(tr("Remove Play Time Data")); QAction* remove_cache_storage = remove_menu->addAction(tr("Remove Cache Storage")); QAction* remove_gl_shader_cache = remove_menu->addAction(tr("Remove OpenGL Pipeline Cache")); QAction* remove_vk_shader_cache = remove_menu->addAction(tr("Remove Vulkan Pipeline Cache")); @@ -619,6 +621,8 @@ void GameList::AddGamePopup(QMenu& context_menu, u64 program_id, const std::stri connect(remove_custom_config, &QAction::triggered, [this, program_id, path]() { emit RemoveFileRequested(program_id, GameListRemoveTarget::CustomConfiguration, path); }); + connect(remove_play_time_data, &QAction::triggered, + [this, program_id]() { emit RemovePlayTimeRequested(program_id); }); connect(remove_cache_storage, &QAction::triggered, [this, program_id, path] { emit RemoveFileRequested(program_id, GameListRemoveTarget::CacheStorage, path); }); @@ -785,6 +789,7 @@ void GameList::RetranslateUI() { item_model->setHeaderData(COLUMN_ADD_ONS, Qt::Horizontal, tr("Add-ons")); item_model->setHeaderData(COLUMN_FILE_TYPE, Qt::Horizontal, tr("File type")); item_model->setHeaderData(COLUMN_SIZE, Qt::Horizontal, tr("Size")); + item_model->setHeaderData(COLUMN_PLAY_TIME, Qt::Horizontal, tr("Play time")); } void GameListSearchField::changeEvent(QEvent* event) { @@ -812,6 +817,7 @@ void GameList::PopulateAsync(QVector& game_dirs) { tree_view->setColumnHidden(COLUMN_COMPATIBILITY, !UISettings::values.show_compat); tree_view->setColumnHidden(COLUMN_FILE_TYPE, !UISettings::values.show_types); tree_view->setColumnHidden(COLUMN_SIZE, !UISettings::values.show_size); + tree_view->setColumnHidden(COLUMN_PLAY_TIME, !UISettings::values.show_play_time); // Delete any rows that might already exist if we're repopulating item_model->removeRows(0, item_model->rowCount()); diff --git a/src/yuzu/game_list.h b/src/yuzu/game_list.h index 6c2f75e53..cde6f1e1f 100644 --- a/src/yuzu/game_list.h +++ b/src/yuzu/game_list.h @@ -74,6 +74,7 @@ public: COLUMN_ADD_ONS, COLUMN_FILE_TYPE, COLUMN_SIZE, + COLUMN_PLAY_TIME, COLUMN_COUNT, // Number of columns }; @@ -112,6 +113,7 @@ signals: void RemoveInstalledEntryRequested(u64 program_id, InstalledEntryType type); void RemoveFileRequested(u64 program_id, GameListRemoveTarget target, const std::string& game_path); + void RemovePlayTimeRequested(u64 program_id); void DumpRomFSRequested(u64 program_id, const std::string& game_path, DumpRomFSTarget target); void CopyTIDRequested(u64 program_id); void CreateShortcut(u64 program_id, const std::string& game_path, diff --git a/src/yuzu/game_list_p.h b/src/yuzu/game_list_p.h index 1800f090f..33a929aae 100644 --- a/src/yuzu/game_list_p.h +++ b/src/yuzu/game_list_p.h @@ -18,6 +18,7 @@ #include "common/common_types.h" #include "common/logging/log.h" #include "common/string_util.h" +#include "yuzu/play_time.h" #include "yuzu/uisettings.h" #include "yuzu/util/util.h" @@ -221,6 +222,31 @@ public: } }; +/** + * GameListItem for Play Time values. + * This object stores the play time of a game in seconds, and its readable + * representation in minutes/hours + */ +class GameListItemPlayTime : public GameListItem { +public: + static constexpr int PlayTimeRole = SortRole; + + GameListItemPlayTime() = default; + explicit GameListItemPlayTime(const qulonglong time_seconds) { + setData(time_seconds, PlayTimeRole); + } + + void setData(const QVariant& value, int role) override { + qulonglong time_seconds = value.toULongLong(); + GameListItem::setData(PlayTime::ReadablePlayTime(time_seconds), Qt::DisplayRole); + GameListItem::setData(value, PlayTimeRole); + } + + bool operator<(const QStandardItem& other) const override { + return data(PlayTimeRole).toULongLong() < other.data(PlayTimeRole).toULongLong(); + } +}; + class GameListDir : public GameListItem { public: static constexpr int GameDirRole = Qt::UserRole + 2; diff --git a/src/yuzu/game_list_worker.cpp b/src/yuzu/game_list_worker.cpp index e7fb8a282..b15ed730e 100644 --- a/src/yuzu/game_list_worker.cpp +++ b/src/yuzu/game_list_worker.cpp @@ -27,6 +27,7 @@ #include "yuzu/game_list.h" #include "yuzu/game_list_p.h" #include "yuzu/game_list_worker.h" +#include "yuzu/play_time.h" #include "yuzu/uisettings.h" namespace { @@ -212,6 +213,7 @@ QList MakeGameListEntry(const std::string& path, const std::stri new GameListItemCompat(compatibility), new GameListItem(file_type_string), new GameListItemSize(size), + new GameListItemPlayTime(PlayTime::GetPlayTime(program_id)), }; const auto patch_versions = GetGameListCachedObject( diff --git a/src/yuzu/main.cpp b/src/yuzu/main.cpp index 33c9fd0af..53ab7ada9 100644 --- a/src/yuzu/main.cpp +++ b/src/yuzu/main.cpp @@ -146,6 +146,7 @@ static FileSys::VirtualFile VfsDirectoryCreateFileWrapper(const FileSys::Virtual #include "yuzu/install_dialog.h" #include "yuzu/loading_screen.h" #include "yuzu/main.h" +#include "yuzu/play_time.h" #include "yuzu/startup_checks.h" #include "yuzu/uisettings.h" #include "yuzu/util/clickable_label.h" @@ -334,6 +335,8 @@ GMainWindow::GMainWindow(std::unique_ptr config_, bool has_broken_vulkan SetDiscordEnabled(UISettings::values.enable_discord_presence.GetValue()); discord_rpc->Update(); + play_time_manager = std::make_unique(); + system->GetRoomNetwork().Init(); RegisterMetaTypes(); @@ -1446,6 +1449,8 @@ void GMainWindow::ConnectWidgetEvents() { connect(game_list, &GameList::RemoveInstalledEntryRequested, this, &GMainWindow::OnGameListRemoveInstalledEntry); connect(game_list, &GameList::RemoveFileRequested, this, &GMainWindow::OnGameListRemoveFile); + connect(game_list, &GameList::RemovePlayTimeRequested, this, + &GMainWindow::OnGameListRemovePlayTimeData); connect(game_list, &GameList::DumpRomFSRequested, this, &GMainWindow::OnGameListDumpRomFS); connect(game_list, &GameList::CopyTIDRequested, this, &GMainWindow::OnGameListCopyTID); connect(game_list, &GameList::NavigateToGamedbEntryRequested, this, @@ -2458,6 +2463,20 @@ void GMainWindow::OnGameListRemoveFile(u64 program_id, GameListRemoveTarget targ } } +void GMainWindow::OnGameListRemovePlayTimeData(u64 program_id) { + if (QMessageBox::question(this, tr("Remove Play Time Data"), tr("Reset play time?"), + QMessageBox::Yes | QMessageBox::No, + QMessageBox::No) != QMessageBox::Yes) { + return; + } + if (!play_time_manager->ResetProgramPlayTime(program_id)) { + QMessageBox::warning(this, tr("Error Resetting Play Time Data"), + tr("Play time couldn't be cleared")); + return; + } + game_list->PopulateAsync(UISettings::values.game_dirs); +} + void GMainWindow::RemoveTransferableShaderCache(u64 program_id, GameListRemoveTarget target) { const auto target_file_name = [target] { switch (target) { @@ -3230,6 +3249,9 @@ void GMainWindow::OnStartGame() { UpdateMenuState(); OnTasStateChanged(); + play_time_manager->SetProgramId(system->GetApplicationProcessProgramID()); + play_time_manager->Start(); + discord_rpc->Update(); } @@ -3245,6 +3267,7 @@ void GMainWindow::OnRestartGame() { void GMainWindow::OnPauseGame() { emu_thread->SetRunning(false); + play_time_manager->Stop(); UpdateMenuState(); AllowOSSleep(); } @@ -3265,6 +3288,9 @@ void GMainWindow::OnStopGame() { return; } + play_time_manager->Stop(); + // Update game list to show new play time + game_list->PopulateAsync(UISettings::values.game_dirs); if (OnShutdownBegin()) { OnShutdownBeginDialog(); } else { diff --git a/src/yuzu/main.h b/src/yuzu/main.h index 1b7055122..c3003f8d9 100644 --- a/src/yuzu/main.h +++ b/src/yuzu/main.h @@ -76,6 +76,10 @@ namespace DiscordRPC { class DiscordInterface; } +namespace PlayTime { +class PlayTimeManager; +} + namespace FileSys { class ContentProvider; class ManualContentProvider; @@ -312,6 +316,7 @@ private slots: void OnGameListRemoveInstalledEntry(u64 program_id, InstalledEntryType type); void OnGameListRemoveFile(u64 program_id, GameListRemoveTarget target, const std::string& game_path); + void OnGameListRemovePlayTimeData(u64 program_id); void OnGameListDumpRomFS(u64 program_id, const std::string& game_path, DumpRomFSTarget target); void OnGameListCopyTID(u64 program_id); void OnGameListNavigateToGamedbEntry(u64 program_id, @@ -374,6 +379,7 @@ private: void RemoveVulkanDriverPipelineCache(u64 program_id); void RemoveAllTransferableShaderCaches(u64 program_id); void RemoveCustomConfiguration(u64 program_id, const std::string& game_path); + void RemovePlayTimeData(u64 program_id); void RemoveCacheStorage(u64 program_id); std::optional SelectRomFSDumpTarget(const FileSys::ContentProvider&, u64 program_id); InstallResult InstallNSPXCI(const QString& filename); @@ -411,6 +417,7 @@ private: std::unique_ptr system; std::unique_ptr discord_rpc; + std::unique_ptr play_time_manager; std::shared_ptr input_subsystem; MultiplayerState* multiplayer_state = nullptr; diff --git a/src/yuzu/play_time.cpp b/src/yuzu/play_time.cpp new file mode 100644 index 000000000..6be0327b2 --- /dev/null +++ b/src/yuzu/play_time.cpp @@ -0,0 +1,177 @@ +// SPDX-FileCopyrightText: 2023 yuzu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "common/fs/file.h" +#include "common/fs/path_util.h" +#include "common/logging/log.h" +#include "common/settings.h" +#include "common/thread.h" +#include "core/hle/service/acc/profile_manager.h" + +#include "yuzu/play_time.h" + +namespace PlayTime { + +void PlayTimeManager::SetProgramId(u64 program_id) { + this->running_program_id = program_id; +} + +inline void PlayTimeManager::UpdateTimestamp() { + this->last_timestamp = std::chrono::steady_clock::now(); +} + +void PlayTimeManager::Start() { + UpdateTimestamp(); + play_time_thread = + std::jthread([&](std::stop_token stop_token) { this->AutoTimestamp(stop_token); }); +} + +void PlayTimeManager::Stop() { + play_time_thread.request_stop(); +} + +void PlayTimeManager::AutoTimestamp(std::stop_token stop_token) { + Common::SetCurrentThreadName("PlayTimeReport"); + + using namespace std::literals::chrono_literals; + + const auto duration = 30s; + while (Common::StoppableTimedWait(stop_token, duration)) { + Save(); + } + + Save(); +} + +void PlayTimeManager::Save() { + const auto now = std::chrono::steady_clock::now(); + const auto duration = + static_cast(std::chrono::duration_cast( + std::chrono::steady_clock::duration(now - this->last_timestamp)) + .count()); + UpdateTimestamp(); + if (!UpdatePlayTime(running_program_id, duration)) { + LOG_ERROR(Common, "Failed to update play time"); + } +} + +bool UpdatePlayTime(u64 program_id, u64 add_play_time) { + std::vector play_time_elements; + if (!ReadPlayTimeFile(play_time_elements)) { + return false; + } + const auto it = std::find(play_time_elements.begin(), play_time_elements.end(), program_id); + + if (it == play_time_elements.end()) { + play_time_elements.push_back({.program_id = program_id, .play_time = add_play_time}); + } else { + play_time_elements.at(it - play_time_elements.begin()).play_time += add_play_time; + } + if (!WritePlayTimeFile(play_time_elements)) { + return false; + } + return true; +} + +u64 GetPlayTime(u64 program_id) { + std::vector play_time_elements; + + if (!ReadPlayTimeFile(play_time_elements)) { + return 0; + } + const auto it = std::find(play_time_elements.begin(), play_time_elements.end(), program_id); + if (it == play_time_elements.end()) { + return 0; + } + return play_time_elements.at(it - play_time_elements.begin()).play_time; +} + +bool PlayTimeManager::ResetProgramPlayTime(u64 program_id) { + std::vector play_time_elements; + + if (!ReadPlayTimeFile(play_time_elements)) { + return false; + } + const auto it = std::find(play_time_elements.begin(), play_time_elements.end(), program_id); + if (it == play_time_elements.end()) { + return false; + } + play_time_elements.erase(it); + if (!WritePlayTimeFile(play_time_elements)) { + return false; + } + return true; +} + +std::optional GetCurrentUserPlayTimePath() { + const Service::Account::ProfileManager manager; + const auto uuid = manager.GetUser(static_cast(Settings::values.current_user)); + if (!uuid.has_value()) { + return std::nullopt; + } + return Common::FS::GetYuzuPath(Common::FS::YuzuPath::PlayTimeDir) / + uuid->RawString().append(".bin"); +} + +[[nodiscard]] bool ReadPlayTimeFile(std::vector& out_play_time_elements) { + const auto filename = GetCurrentUserPlayTimePath(); + if (!filename.has_value()) { + LOG_ERROR(Common, "Failed to get current user path"); + return false; + } + + if (Common::FS::Exists(filename.value())) { + Common::FS::IOFile file{filename.value(), Common::FS::FileAccessMode::Read, + Common::FS::FileType::BinaryFile}; + if (!file.IsOpen()) { + LOG_ERROR(Common, "Failed to open play time file: {}", + Common::FS::PathToUTF8String(filename.value())); + return false; + } + const size_t elem_num = file.GetSize() / sizeof(PlayTimeElement); + out_play_time_elements.resize(elem_num); + const bool success = file.ReadSpan(out_play_time_elements) == elem_num; + file.Close(); + return success; + } else { + out_play_time_elements.clear(); + return true; + } +} + +[[nodiscard]] bool WritePlayTimeFile(const std::vector& play_time_elements) { + const auto filename = GetCurrentUserPlayTimePath(); + if (!filename.has_value()) { + LOG_ERROR(Common, "Failed to get current user path"); + return false; + } + Common::FS::IOFile file{filename.value(), Common::FS::FileAccessMode::Write, + Common::FS::FileType::BinaryFile}; + + if (!file.IsOpen()) { + LOG_ERROR(Common, "Failed to open play time file: {}", + Common::FS::PathToUTF8String(filename.value())); + return false; + } + const bool success = + file.WriteSpan(play_time_elements) == play_time_elements.size(); + file.Close(); + return success; +} + +QString ReadablePlayTime(qulonglong time_seconds) { + static constexpr std::array units{"m", "h"}; + if (time_seconds == 0) { + return QLatin1String(""); + } + const auto time_minutes = std::max(static_cast(time_seconds) / 60, 1.0); + const auto time_hours = static_cast(time_seconds) / 3600; + const int unit = time_minutes < 60 ? 0 : 1; + const auto value = unit == 0 ? time_minutes : time_hours; + + return QStringLiteral("%L1 %2") + .arg(value, 0, 'f', unit && time_seconds % 60 != 0) + .arg(QString::fromUtf8(units[unit])); +} + +} // namespace PlayTime diff --git a/src/yuzu/play_time.h b/src/yuzu/play_time.h new file mode 100644 index 000000000..68e40955c --- /dev/null +++ b/src/yuzu/play_time.h @@ -0,0 +1,68 @@ +// SPDX-FileCopyrightText: 2023 yuzu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include + +#include +#include +#include +#include +#include + +#include "common/common_types.h" +#include "common/fs/fs.h" +#include "common/polyfill_thread.h" +#include "core/core.h" + +namespace PlayTime { +struct PlayTimeElement { + u64 program_id; + u64 play_time; + + inline bool operator==(const PlayTimeElement& other) const { + return program_id == other.program_id; + } + + inline bool operator==(const u64 _program_id) const { + return program_id == _program_id; + } +}; + +class PlayTimeManager { +public: + explicit PlayTimeManager() = default; + ~PlayTimeManager() = default; + +public: + YUZU_NON_COPYABLE(PlayTimeManager); + YUZU_NON_MOVEABLE(PlayTimeManager); + +public: + bool ResetProgramPlayTime(u64 program_id); + void SetProgramId(u64 program_id); + inline void UpdateTimestamp(); + void Start(); + void Stop(); + +private: + u64 running_program_id; + std::chrono::steady_clock::time_point last_timestamp; + std::jthread play_time_thread; + void AutoTimestamp(std::stop_token stop_token); + void Save(); +}; + +std::optional GetCurrentUserPlayTimePath(); + +bool UpdatePlayTime(u64 program_id, u64 add_play_time); + +[[nodiscard]] bool ReadPlayTimeFile(std::vector& out_play_time_elements); +[[nodiscard]] bool WritePlayTimeFile(const std::vector& play_time_elements); + +u64 GetPlayTime(u64 program_id); + +QString ReadablePlayTime(qulonglong time_seconds); + +} // namespace PlayTime diff --git a/src/yuzu/uisettings.h b/src/yuzu/uisettings.h index 8efd63f31..848631a9e 100644 --- a/src/yuzu/uisettings.h +++ b/src/yuzu/uisettings.h @@ -183,6 +183,9 @@ struct Values { Setting show_size{linkage, true, "show_size", Category::UiGameList}; Setting show_types{linkage, true, "show_types", Category::UiGameList}; + // Play time + Setting show_play_time{linkage, true, "show_play_time", Category::UiGameList}; + bool configuration_applied; bool reset_to_defaults; bool shortcut_already_warned{false}; -- cgit v1.2.3 From 667ec286970560d3a5b12b987010082657aec7c3 Mon Sep 17 00:00:00 2001 From: Liam Date: Sun, 27 Aug 2023 18:41:42 -0400 Subject: Address review comments --- src/yuzu/CMakeLists.txt | 4 +- src/yuzu/game_list.cpp | 8 +- src/yuzu/game_list.h | 5 +- src/yuzu/game_list_p.h | 2 +- src/yuzu/game_list_worker.cpp | 25 +++--- src/yuzu/game_list_worker.h | 6 +- src/yuzu/main.cpp | 11 +-- src/yuzu/play_time.cpp | 177 ---------------------------------------- src/yuzu/play_time.h | 68 ---------------- src/yuzu/play_time_manager.cpp | 179 +++++++++++++++++++++++++++++++++++++++++ src/yuzu/play_time_manager.h | 44 ++++++++++ 11 files changed, 259 insertions(+), 270 deletions(-) delete mode 100644 src/yuzu/play_time.cpp delete mode 100644 src/yuzu/play_time.h create mode 100644 src/yuzu/play_time_manager.cpp create mode 100644 src/yuzu/play_time_manager.h diff --git a/src/yuzu/CMakeLists.txt b/src/yuzu/CMakeLists.txt index 89763f64f..9ebece907 100644 --- a/src/yuzu/CMakeLists.txt +++ b/src/yuzu/CMakeLists.txt @@ -195,8 +195,8 @@ add_executable(yuzu multiplayer/state.cpp multiplayer/state.h multiplayer/validation.h - play_time.cpp - play_time.h + play_time_manager.cpp + play_time_manager.h precompiled_headers.h qt_common.cpp qt_common.h diff --git a/src/yuzu/game_list.cpp b/src/yuzu/game_list.cpp index 98e410e0f..0b7415526 100644 --- a/src/yuzu/game_list.cpp +++ b/src/yuzu/game_list.cpp @@ -312,8 +312,10 @@ void GameList::OnFilterCloseClicked() { } GameList::GameList(FileSys::VirtualFilesystem vfs_, FileSys::ManualContentProvider* provider_, - Core::System& system_, GMainWindow* parent) - : QWidget{parent}, vfs{std::move(vfs_)}, provider{provider_}, system{system_} { + PlayTime::PlayTimeManager& play_time_manager_, Core::System& system_, + GMainWindow* parent) + : QWidget{parent}, vfs{std::move(vfs_)}, provider{provider_}, + play_time_manager{play_time_manager_}, system{system_} { watcher = new QFileSystemWatcher(this); connect(watcher, &QFileSystemWatcher::directoryChanged, this, &GameList::RefreshGameDirectory); @@ -826,7 +828,7 @@ void GameList::PopulateAsync(QVector& game_dirs) { emit ShouldCancelWorker(); GameListWorker* worker = - new GameListWorker(vfs, provider, game_dirs, compatibility_list, system); + new GameListWorker(vfs, provider, game_dirs, compatibility_list, play_time_manager, system); connect(worker, &GameListWorker::EntryReady, this, &GameList::AddEntry, Qt::QueuedConnection); connect(worker, &GameListWorker::DirEntryReady, this, &GameList::AddDirEntry, diff --git a/src/yuzu/game_list.h b/src/yuzu/game_list.h index cde6f1e1f..6e8382c0f 100644 --- a/src/yuzu/game_list.h +++ b/src/yuzu/game_list.h @@ -18,6 +18,7 @@ #include "core/core.h" #include "uisettings.h" #include "yuzu/compatibility_list.h" +#include "yuzu/play_time_manager.h" namespace Core { class System; @@ -79,7 +80,8 @@ public: }; explicit GameList(std::shared_ptr vfs_, - FileSys::ManualContentProvider* provider_, Core::System& system_, + FileSys::ManualContentProvider* provider_, + PlayTime::PlayTimeManager& play_time_manager_, Core::System& system_, GMainWindow* parent = nullptr); ~GameList() override; @@ -168,6 +170,7 @@ private: friend class GameListSearchField; + const PlayTime::PlayTimeManager& play_time_manager; Core::System& system; }; diff --git a/src/yuzu/game_list_p.h b/src/yuzu/game_list_p.h index 33a929aae..86a0c41d9 100644 --- a/src/yuzu/game_list_p.h +++ b/src/yuzu/game_list_p.h @@ -18,7 +18,7 @@ #include "common/common_types.h" #include "common/logging/log.h" #include "common/string_util.h" -#include "yuzu/play_time.h" +#include "yuzu/play_time_manager.h" #include "yuzu/uisettings.h" #include "yuzu/util/util.h" diff --git a/src/yuzu/game_list_worker.cpp b/src/yuzu/game_list_worker.cpp index b15ed730e..588f1dd6e 100644 --- a/src/yuzu/game_list_worker.cpp +++ b/src/yuzu/game_list_worker.cpp @@ -27,7 +27,6 @@ #include "yuzu/game_list.h" #include "yuzu/game_list_p.h" #include "yuzu/game_list_worker.h" -#include "yuzu/play_time.h" #include "yuzu/uisettings.h" namespace { @@ -195,6 +194,7 @@ QList MakeGameListEntry(const std::string& path, const std::stri const std::size_t size, const std::vector& icon, Loader::AppLoader& loader, u64 program_id, const CompatibilityList& compatibility_list, + const PlayTime::PlayTimeManager& play_time_manager, const FileSys::PatchManager& patch) { const auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id); @@ -213,7 +213,7 @@ QList MakeGameListEntry(const std::string& path, const std::stri new GameListItemCompat(compatibility), new GameListItem(file_type_string), new GameListItemSize(size), - new GameListItemPlayTime(PlayTime::GetPlayTime(program_id)), + new GameListItemPlayTime(play_time_manager.GetPlayTime(program_id)), }; const auto patch_versions = GetGameListCachedObject( @@ -229,9 +229,12 @@ QList MakeGameListEntry(const std::string& path, const std::stri GameListWorker::GameListWorker(FileSys::VirtualFilesystem vfs_, FileSys::ManualContentProvider* provider_, QVector& game_dirs_, - const CompatibilityList& compatibility_list_, Core::System& system_) + const CompatibilityList& compatibility_list_, + const PlayTime::PlayTimeManager& play_time_manager_, + Core::System& system_) : vfs{std::move(vfs_)}, provider{provider_}, game_dirs{game_dirs_}, - compatibility_list{compatibility_list_}, system{system_} {} + compatibility_list{compatibility_list_}, + play_time_manager{play_time_manager_}, system{system_} {} GameListWorker::~GameListWorker() = default; @@ -282,7 +285,7 @@ void GameListWorker::AddTitlesToGameList(GameListDir* parent_dir) { } emit EntryReady(MakeGameListEntry(file->GetFullPath(), name, file->GetSize(), icon, *loader, - program_id, compatibility_list, patch), + program_id, compatibility_list, play_time_manager, patch), parent_dir); } } @@ -359,7 +362,8 @@ void GameListWorker::ScanFileSystem(ScanTarget target, const std::string& dir_pa emit EntryReady(MakeGameListEntry(physical_name, name, Common::FS::GetSize(physical_name), icon, - *loader, id, compatibility_list, patch), + *loader, id, compatibility_list, + play_time_manager, patch), parent_dir); } } else { @@ -372,10 +376,11 @@ void GameListWorker::ScanFileSystem(ScanTarget target, const std::string& dir_pa const FileSys::PatchManager patch{program_id, system.GetFileSystemController(), system.GetContentProvider()}; - emit EntryReady( - MakeGameListEntry(physical_name, name, Common::FS::GetSize(physical_name), - icon, *loader, program_id, compatibility_list, patch), - parent_dir); + emit EntryReady(MakeGameListEntry(physical_name, name, + Common::FS::GetSize(physical_name), icon, + *loader, program_id, compatibility_list, + play_time_manager, patch), + parent_dir); } } } else if (is_dir) { diff --git a/src/yuzu/game_list_worker.h b/src/yuzu/game_list_worker.h index 24a4e92c3..2bb0a0cb6 100644 --- a/src/yuzu/game_list_worker.h +++ b/src/yuzu/game_list_worker.h @@ -13,6 +13,7 @@ #include #include "yuzu/compatibility_list.h" +#include "yuzu/play_time_manager.h" namespace Core { class System; @@ -36,7 +37,9 @@ public: explicit GameListWorker(std::shared_ptr vfs_, FileSys::ManualContentProvider* provider_, QVector& game_dirs_, - const CompatibilityList& compatibility_list_, Core::System& system_); + const CompatibilityList& compatibility_list_, + const PlayTime::PlayTimeManager& play_time_manager_, + Core::System& system_); ~GameListWorker() override; /// Starts the processing of directory tree information. @@ -76,6 +79,7 @@ private: FileSys::ManualContentProvider* provider; QVector& game_dirs; const CompatibilityList& compatibility_list; + const PlayTime::PlayTimeManager& play_time_manager; QStringList watch_list; std::atomic_bool stop_processing; diff --git a/src/yuzu/main.cpp b/src/yuzu/main.cpp index 53ab7ada9..bfa4787e1 100644 --- a/src/yuzu/main.cpp +++ b/src/yuzu/main.cpp @@ -146,7 +146,7 @@ static FileSys::VirtualFile VfsDirectoryCreateFileWrapper(const FileSys::Virtual #include "yuzu/install_dialog.h" #include "yuzu/loading_screen.h" #include "yuzu/main.h" -#include "yuzu/play_time.h" +#include "yuzu/play_time_manager.h" #include "yuzu/startup_checks.h" #include "yuzu/uisettings.h" #include "yuzu/util/clickable_label.h" @@ -980,7 +980,7 @@ void GMainWindow::InitializeWidgets() { render_window = new GRenderWindow(this, emu_thread.get(), input_subsystem, *system); render_window->hide(); - game_list = new GameList(vfs, provider.get(), *system, this); + game_list = new GameList(vfs, provider.get(), *play_time_manager, *system, this); ui->horizontalLayout->addWidget(game_list); game_list_placeholder = new GameListPlaceholder(this); @@ -2469,11 +2469,8 @@ void GMainWindow::OnGameListRemovePlayTimeData(u64 program_id) { QMessageBox::No) != QMessageBox::Yes) { return; } - if (!play_time_manager->ResetProgramPlayTime(program_id)) { - QMessageBox::warning(this, tr("Error Resetting Play Time Data"), - tr("Play time couldn't be cleared")); - return; - } + + play_time_manager->ResetProgramPlayTime(program_id); game_list->PopulateAsync(UISettings::values.game_dirs); } diff --git a/src/yuzu/play_time.cpp b/src/yuzu/play_time.cpp deleted file mode 100644 index 6be0327b2..000000000 --- a/src/yuzu/play_time.cpp +++ /dev/null @@ -1,177 +0,0 @@ -// SPDX-FileCopyrightText: 2023 yuzu Emulator Project -// SPDX-License-Identifier: GPL-2.0-or-later - -#include "common/fs/file.h" -#include "common/fs/path_util.h" -#include "common/logging/log.h" -#include "common/settings.h" -#include "common/thread.h" -#include "core/hle/service/acc/profile_manager.h" - -#include "yuzu/play_time.h" - -namespace PlayTime { - -void PlayTimeManager::SetProgramId(u64 program_id) { - this->running_program_id = program_id; -} - -inline void PlayTimeManager::UpdateTimestamp() { - this->last_timestamp = std::chrono::steady_clock::now(); -} - -void PlayTimeManager::Start() { - UpdateTimestamp(); - play_time_thread = - std::jthread([&](std::stop_token stop_token) { this->AutoTimestamp(stop_token); }); -} - -void PlayTimeManager::Stop() { - play_time_thread.request_stop(); -} - -void PlayTimeManager::AutoTimestamp(std::stop_token stop_token) { - Common::SetCurrentThreadName("PlayTimeReport"); - - using namespace std::literals::chrono_literals; - - const auto duration = 30s; - while (Common::StoppableTimedWait(stop_token, duration)) { - Save(); - } - - Save(); -} - -void PlayTimeManager::Save() { - const auto now = std::chrono::steady_clock::now(); - const auto duration = - static_cast(std::chrono::duration_cast( - std::chrono::steady_clock::duration(now - this->last_timestamp)) - .count()); - UpdateTimestamp(); - if (!UpdatePlayTime(running_program_id, duration)) { - LOG_ERROR(Common, "Failed to update play time"); - } -} - -bool UpdatePlayTime(u64 program_id, u64 add_play_time) { - std::vector play_time_elements; - if (!ReadPlayTimeFile(play_time_elements)) { - return false; - } - const auto it = std::find(play_time_elements.begin(), play_time_elements.end(), program_id); - - if (it == play_time_elements.end()) { - play_time_elements.push_back({.program_id = program_id, .play_time = add_play_time}); - } else { - play_time_elements.at(it - play_time_elements.begin()).play_time += add_play_time; - } - if (!WritePlayTimeFile(play_time_elements)) { - return false; - } - return true; -} - -u64 GetPlayTime(u64 program_id) { - std::vector play_time_elements; - - if (!ReadPlayTimeFile(play_time_elements)) { - return 0; - } - const auto it = std::find(play_time_elements.begin(), play_time_elements.end(), program_id); - if (it == play_time_elements.end()) { - return 0; - } - return play_time_elements.at(it - play_time_elements.begin()).play_time; -} - -bool PlayTimeManager::ResetProgramPlayTime(u64 program_id) { - std::vector play_time_elements; - - if (!ReadPlayTimeFile(play_time_elements)) { - return false; - } - const auto it = std::find(play_time_elements.begin(), play_time_elements.end(), program_id); - if (it == play_time_elements.end()) { - return false; - } - play_time_elements.erase(it); - if (!WritePlayTimeFile(play_time_elements)) { - return false; - } - return true; -} - -std::optional GetCurrentUserPlayTimePath() { - const Service::Account::ProfileManager manager; - const auto uuid = manager.GetUser(static_cast(Settings::values.current_user)); - if (!uuid.has_value()) { - return std::nullopt; - } - return Common::FS::GetYuzuPath(Common::FS::YuzuPath::PlayTimeDir) / - uuid->RawString().append(".bin"); -} - -[[nodiscard]] bool ReadPlayTimeFile(std::vector& out_play_time_elements) { - const auto filename = GetCurrentUserPlayTimePath(); - if (!filename.has_value()) { - LOG_ERROR(Common, "Failed to get current user path"); - return false; - } - - if (Common::FS::Exists(filename.value())) { - Common::FS::IOFile file{filename.value(), Common::FS::FileAccessMode::Read, - Common::FS::FileType::BinaryFile}; - if (!file.IsOpen()) { - LOG_ERROR(Common, "Failed to open play time file: {}", - Common::FS::PathToUTF8String(filename.value())); - return false; - } - const size_t elem_num = file.GetSize() / sizeof(PlayTimeElement); - out_play_time_elements.resize(elem_num); - const bool success = file.ReadSpan(out_play_time_elements) == elem_num; - file.Close(); - return success; - } else { - out_play_time_elements.clear(); - return true; - } -} - -[[nodiscard]] bool WritePlayTimeFile(const std::vector& play_time_elements) { - const auto filename = GetCurrentUserPlayTimePath(); - if (!filename.has_value()) { - LOG_ERROR(Common, "Failed to get current user path"); - return false; - } - Common::FS::IOFile file{filename.value(), Common::FS::FileAccessMode::Write, - Common::FS::FileType::BinaryFile}; - - if (!file.IsOpen()) { - LOG_ERROR(Common, "Failed to open play time file: {}", - Common::FS::PathToUTF8String(filename.value())); - return false; - } - const bool success = - file.WriteSpan(play_time_elements) == play_time_elements.size(); - file.Close(); - return success; -} - -QString ReadablePlayTime(qulonglong time_seconds) { - static constexpr std::array units{"m", "h"}; - if (time_seconds == 0) { - return QLatin1String(""); - } - const auto time_minutes = std::max(static_cast(time_seconds) / 60, 1.0); - const auto time_hours = static_cast(time_seconds) / 3600; - const int unit = time_minutes < 60 ? 0 : 1; - const auto value = unit == 0 ? time_minutes : time_hours; - - return QStringLiteral("%L1 %2") - .arg(value, 0, 'f', unit && time_seconds % 60 != 0) - .arg(QString::fromUtf8(units[unit])); -} - -} // namespace PlayTime diff --git a/src/yuzu/play_time.h b/src/yuzu/play_time.h deleted file mode 100644 index 68e40955c..000000000 --- a/src/yuzu/play_time.h +++ /dev/null @@ -1,68 +0,0 @@ -// SPDX-FileCopyrightText: 2023 yuzu Emulator Project -// SPDX-License-Identifier: GPL-2.0-or-later - -#pragma once - -#include - -#include -#include -#include -#include -#include - -#include "common/common_types.h" -#include "common/fs/fs.h" -#include "common/polyfill_thread.h" -#include "core/core.h" - -namespace PlayTime { -struct PlayTimeElement { - u64 program_id; - u64 play_time; - - inline bool operator==(const PlayTimeElement& other) const { - return program_id == other.program_id; - } - - inline bool operator==(const u64 _program_id) const { - return program_id == _program_id; - } -}; - -class PlayTimeManager { -public: - explicit PlayTimeManager() = default; - ~PlayTimeManager() = default; - -public: - YUZU_NON_COPYABLE(PlayTimeManager); - YUZU_NON_MOVEABLE(PlayTimeManager); - -public: - bool ResetProgramPlayTime(u64 program_id); - void SetProgramId(u64 program_id); - inline void UpdateTimestamp(); - void Start(); - void Stop(); - -private: - u64 running_program_id; - std::chrono::steady_clock::time_point last_timestamp; - std::jthread play_time_thread; - void AutoTimestamp(std::stop_token stop_token); - void Save(); -}; - -std::optional GetCurrentUserPlayTimePath(); - -bool UpdatePlayTime(u64 program_id, u64 add_play_time); - -[[nodiscard]] bool ReadPlayTimeFile(std::vector& out_play_time_elements); -[[nodiscard]] bool WritePlayTimeFile(const std::vector& play_time_elements); - -u64 GetPlayTime(u64 program_id); - -QString ReadablePlayTime(qulonglong time_seconds); - -} // namespace PlayTime diff --git a/src/yuzu/play_time_manager.cpp b/src/yuzu/play_time_manager.cpp new file mode 100644 index 000000000..155c36b7d --- /dev/null +++ b/src/yuzu/play_time_manager.cpp @@ -0,0 +1,179 @@ +// SPDX-FileCopyrightText: 2023 yuzu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "common/alignment.h" +#include "common/fs/file.h" +#include "common/fs/fs.h" +#include "common/fs/path_util.h" +#include "common/logging/log.h" +#include "common/settings.h" +#include "common/thread.h" +#include "core/hle/service/acc/profile_manager.h" +#include "yuzu/play_time_manager.h" + +namespace PlayTime { + +namespace { + +struct PlayTimeElement { + ProgramId program_id; + PlayTime play_time; +}; + +std::optional GetCurrentUserPlayTimePath() { + const Service::Account::ProfileManager manager; + const auto uuid = manager.GetUser(static_cast(Settings::values.current_user)); + if (!uuid.has_value()) { + return std::nullopt; + } + return Common::FS::GetYuzuPath(Common::FS::YuzuPath::PlayTimeDir) / + uuid->RawString().append(".bin"); +} + +[[nodiscard]] bool ReadPlayTimeFile(PlayTimeDatabase& out_play_time_db) { + const auto filename = GetCurrentUserPlayTimePath(); + + if (!filename.has_value()) { + LOG_ERROR(Frontend, "Failed to get current user path"); + return false; + } + + out_play_time_db.clear(); + + if (Common::FS::Exists(filename.value())) { + Common::FS::IOFile file{filename.value(), Common::FS::FileAccessMode::Read, + Common::FS::FileType::BinaryFile}; + if (!file.IsOpen()) { + LOG_ERROR(Frontend, "Failed to open play time file: {}", + Common::FS::PathToUTF8String(filename.value())); + return false; + } + + const size_t num_elements = file.GetSize() / sizeof(PlayTimeElement); + std::vector elements(num_elements); + + if (file.ReadSpan(elements) != num_elements) { + return false; + } + + for (const auto& [program_id, play_time] : elements) { + if (program_id != 0) { + out_play_time_db[program_id] = play_time; + } + } + } + + return true; +} + +[[nodiscard]] bool WritePlayTimeFile(const PlayTimeDatabase& play_time_db) { + const auto filename = GetCurrentUserPlayTimePath(); + + if (!filename.has_value()) { + LOG_ERROR(Frontend, "Failed to get current user path"); + return false; + } + + Common::FS::IOFile file{filename.value(), Common::FS::FileAccessMode::Write, + Common::FS::FileType::BinaryFile}; + if (!file.IsOpen()) { + LOG_ERROR(Frontend, "Failed to open play time file: {}", + Common::FS::PathToUTF8String(filename.value())); + return false; + } + + std::vector elements; + elements.reserve(play_time_db.size()); + + for (auto& [program_id, play_time] : play_time_db) { + if (program_id != 0) { + elements.push_back(PlayTimeElement{program_id, play_time}); + } + } + + return file.WriteSpan(elements) == elements.size(); +} + +} // namespace + +PlayTimeManager::PlayTimeManager() { + if (!ReadPlayTimeFile(database)) { + LOG_ERROR(Frontend, "Failed to read play time database! Resetting to default."); + } +} + +PlayTimeManager::~PlayTimeManager() { + Save(); +} + +void PlayTimeManager::SetProgramId(u64 program_id) { + running_program_id = program_id; +} + +void PlayTimeManager::Start() { + play_time_thread = std::jthread([&](std::stop_token stop_token) { AutoTimestamp(stop_token); }); +} + +void PlayTimeManager::Stop() { + play_time_thread = {}; +} + +void PlayTimeManager::AutoTimestamp(std::stop_token stop_token) { + Common::SetCurrentThreadName("PlayTimeReport"); + + using namespace std::literals::chrono_literals; + using std::chrono::seconds; + using std::chrono::steady_clock; + + auto timestamp = steady_clock::now(); + + const auto GetDuration = [&]() -> u64 { + const auto last_timestamp = std::exchange(timestamp, steady_clock::now()); + const auto duration = std::chrono::duration_cast(timestamp - last_timestamp); + return static_cast(duration.count()); + }; + + while (!stop_token.stop_requested()) { + Common::StoppableTimedWait(stop_token, 30s); + + database[running_program_id] += GetDuration(); + Save(); + } +} + +void PlayTimeManager::Save() { + if (!WritePlayTimeFile(database)) { + LOG_ERROR(Frontend, "Failed to update play time database!"); + } +} + +u64 PlayTimeManager::GetPlayTime(u64 program_id) const { + auto it = database.find(program_id); + if (it != database.end()) { + return it->second; + } else { + return 0; + } +} + +void PlayTimeManager::ResetProgramPlayTime(u64 program_id) { + database.erase(program_id); + Save(); +} + +QString ReadablePlayTime(qulonglong time_seconds) { + if (time_seconds == 0) { + return {}; + } + const auto time_minutes = std::max(static_cast(time_seconds) / 60, 1.0); + const auto time_hours = static_cast(time_seconds) / 3600; + const bool is_minutes = time_minutes < 60; + const char* unit = is_minutes ? "m" : "h"; + const auto value = is_minutes ? time_minutes : time_hours; + + return QStringLiteral("%L1 %2") + .arg(value, 0, 'f', !is_minutes && time_seconds % 60 != 0) + .arg(QString::fromUtf8(unit)); +} + +} // namespace PlayTime diff --git a/src/yuzu/play_time_manager.h b/src/yuzu/play_time_manager.h new file mode 100644 index 000000000..5f96f3447 --- /dev/null +++ b/src/yuzu/play_time_manager.h @@ -0,0 +1,44 @@ +// SPDX-FileCopyrightText: 2023 yuzu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include + +#include + +#include "common/common_funcs.h" +#include "common/common_types.h" +#include "common/polyfill_thread.h" + +namespace PlayTime { + +using ProgramId = u64; +using PlayTime = u64; +using PlayTimeDatabase = std::map; + +class PlayTimeManager { +public: + explicit PlayTimeManager(); + ~PlayTimeManager(); + + YUZU_NON_COPYABLE(PlayTimeManager); + YUZU_NON_MOVEABLE(PlayTimeManager); + + u64 GetPlayTime(u64 program_id) const; + void ResetProgramPlayTime(u64 program_id); + void SetProgramId(u64 program_id); + void Start(); + void Stop(); + +private: + PlayTimeDatabase database; + u64 running_program_id; + std::jthread play_time_thread; + void AutoTimestamp(std::stop_token stop_token); + void Save(); +}; + +QString ReadablePlayTime(qulonglong time_seconds); + +} // namespace PlayTime -- cgit v1.2.3