user-manager: megamouse fixes

(cherry picked from commit 949807c1cc689e12e5f0cea367564306ea36a759)
This commit is contained in:
Megamouse 2018-06-20 02:11:50 +02:00 committed by Ivan
parent 68202eb2b7
commit eef900ef41
6 changed files with 156 additions and 144 deletions

View file

@ -509,7 +509,6 @@ struct cfg_root : cfg::node
{
node_usr(cfg::node* _this) : cfg::node(_this, "User") {}
// This is only a default, will get read from existing config.yml.
cfg::string selected_usr{ this, "Selected User", "00000001" };
} usr{this};

View file

@ -1269,7 +1269,7 @@ void main_window::CreateConnects()
connect(ui->actionManage_Users, &QAction::triggered, [=]
{
user_manager_dialog* user_manager = new user_manager_dialog(guiSettings, emuSettings, "", this);
user_manager_dialog* user_manager = new user_manager_dialog(guiSettings, emuSettings, this);
user_manager->show();
});

View file

@ -1,27 +1,26 @@
#include "user_account.h"
UserAccount::UserAccount(const std::string& userId)
UserAccount::UserAccount(const std::string& user_id)
{
// Setting userId.
m_userId = userId;
m_user_id = user_id;
// Setting userDir.
m_userDir = Emu.GetHddDir() + "home/" + m_userId + "/";
m_user_dir = Emu.GetHddDir() + "home/" + m_user_id + "/";
// Setting userName.
fs::file file;
if (file.open(m_userDir + "localusername", fs::read))
if (file.open(m_user_dir + "localusername", fs::read))
{
file.read(m_userName, 16*sizeof(char)); //max of 16 chars on real PS3
file.read(m_username, 16*sizeof(char)); // max of 16 chars on real PS3
file.close();
}
else
{
LOG_WARNING(GENERAL, "UserAccount: localusername file read error (userId=%s, userDir=%s).", m_userId, m_userDir);
LOG_WARNING(GENERAL, "UserAccount: localusername file read error (userId=%s, userDir=%s).", m_user_id, m_user_dir);
}
}
UserAccount::~UserAccount()
{
}

View file

@ -11,16 +11,15 @@
class UserAccount
{
public:
explicit UserAccount(const std::string& userId);
explicit UserAccount(const std::string& user_id);
std::string GetUserId() { return m_userId; };
std::string GetUserDir() { return m_userDir; };
std::string GetUserName() { return m_userName; };
std::string GetUserId() { return m_user_id; };
std::string GetUserDir() { return m_user_dir; };
std::string GetUserName() { return m_username; };
~UserAccount();
private:
std::string m_userId;
std::string m_userDir;
std::string m_userName;
std::string m_user_id;
std::string m_user_dir;
std::string m_username;
};

View file

@ -1,4 +1,5 @@
#include "user_manager_dialog.h"
#include "table_item_delegate.h"
#include "Utilities/StrUtil.h"
@ -13,57 +14,56 @@ namespace
// I believe this gets the folder list sorted alphabetically by default,
// but I can't find proof of this always being true.
for (const auto& userFolder : fs::dir(base_dir))
for (const auto& user_folder : fs::dir(base_dir))
{
if (!userFolder.is_directory)
if (!user_folder.is_directory)
{
continue;
}
// Is the folder name exactly 8 all-numerical characters long?
// We use strtol to find any non-numeric characters in folder name.
char* nonNumericChar;
std::strtol(userFolder.name.c_str(), &nonNumericChar, 10);
if (userFolder.name.length() != 8 || *nonNumericChar != '\0')
char* non_numeric_char;
std::strtol(user_folder.name.c_str(), &non_numeric_char, 10);
if (user_folder.name.length() != 8 || *non_numeric_char != '\0')
{
continue;
}
// Does the localusername file exist?
if (!fs::is_file(fmt::format("%s/%s/localusername", base_dir, userFolder.name)))
if (!fs::is_file(base_dir + "/" + user_folder.name + "/localusername"))
{
continue;
}
UserAccount* user_entry = new UserAccount(userFolder.name);
user_list.emplace_back(user_entry);
user_list.emplace_back(new UserAccount(user_folder.name));
}
return user_list;
}
}
user_manager_dialog::user_manager_dialog(std::shared_ptr<gui_settings> gui_settings, std::shared_ptr<emu_settings> emu_settings, const std::string& dir, QWidget* parent)
: QDialog(parent), m_user_list(), m_dir(dir), m_sort_column(1), m_sort_ascending(true), m_gui_settings(gui_settings), m_emu_settings(emu_settings)
user_manager_dialog::user_manager_dialog(std::shared_ptr<gui_settings> gui_settings, std::shared_ptr<emu_settings> emu_settings, QWidget* parent)
: QDialog(parent), m_user_list(), m_sort_column(1), m_sort_ascending(true), m_gui_settings(gui_settings), m_emu_settings(emu_settings)
{
setWindowTitle(tr("User Manager"));
setMinimumSize(QSize(400, 400));
setModal(true);
m_emu_settings->LoadSettings();
Init(dir);
Init();
}
void user_manager_dialog::Init(const std::string& dir)
void user_manager_dialog::Init()
{
// Table
m_table = new QTableWidget(this);
//m_table->setItemDelegate(new table_item_delegate(this)); // to get rid of cell selection rectangles include "table_item_delegate.h"
m_table->setItemDelegate(new table_item_delegate(this)); // to get rid of cell selection rectangles
m_table->setSelectionMode(QAbstractItemView::SelectionMode::SingleSelection);
m_table->setSelectionBehavior(QAbstractItemView::SelectRows);
m_table->setContextMenuPolicy(Qt::CustomContextMenu);
m_table->setColumnCount(2);
m_table->setHorizontalHeaderLabels(QStringList() << tr("User ID") << tr("User Name"));
m_table->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
QPushButton* push_remove_user = new QPushButton(tr("Delete User"), this);
QPushButton* push_create_user = new QPushButton(tr("Create User"), this);
@ -82,14 +82,14 @@ void user_manager_dialog::Init(const std::string& dir)
hbox_buttons->addStretch();
hbox_buttons->addWidget(push_close);
// main layout
// Main Layout
QVBoxLayout* vbox_main = new QVBoxLayout();
vbox_main->setAlignment(Qt::AlignCenter);
vbox_main->addWidget(m_table);
vbox_main->addLayout(hbox_buttons);
setLayout(vbox_main);
m_selected_user = m_emu_settings->GetSetting(emu_settings::SelectedUser);
m_active_user = m_emu_settings->GetSetting(emu_settings::SelectedUser);
UpdateTable();
restoreGeometry(m_gui_settings->GetValue(gui::um_geometry).toByteArray());
@ -100,16 +100,21 @@ void user_manager_dialog::Init(const std::string& dir)
int idx = m_table->currentRow();
if (idx < 0)
{
push_rename_user->setEnabled(false);
push_remove_user->setEnabled(false);
return;
}
int idx_real = m_table->item(idx, 0)->data(Qt::UserRole).toInt();
std::string idx_user = m_user_list[idx_real]->GetUserId();
bool enable = idx_user != m_selected_user;
bool enable = idx_user != m_active_user;
push_rename_user->setEnabled(enable);
push_remove_user->setEnabled(enable);
};
enableButtons();
// Connects and events
connect(push_close, &QAbstractButton::clicked, this, &user_manager_dialog::close);
connect(push_remove_user, &QAbstractButton::clicked, this, &user_manager_dialog::OnUserRemove);
@ -117,53 +122,43 @@ void user_manager_dialog::Init(const std::string& dir)
connect(push_create_user, &QAbstractButton::clicked, this, &user_manager_dialog::OnUserCreate);
connect(push_login_user, &QAbstractButton::clicked, this, &user_manager_dialog::OnUserLogin);
connect(this, &user_manager_dialog::OnUserLoginSuccess, this, enableButtons);
connect(m_table, &QTableWidget::itemDoubleClicked, this, &user_manager_dialog::OnUserLogin);
connect(m_table->horizontalHeader(), &QHeaderView::sectionClicked, this, &user_manager_dialog::OnSort);
connect(m_table, &QTableWidget::customContextMenuRequested, this, &user_manager_dialog::ShowContextMenu);
connect(m_table, &QTableWidget::itemClicked, this, enableButtons);
connect(m_table, &QTableWidget::itemDoubleClicked, this, &user_manager_dialog::OnUserLogin);
connect(m_table, &QTableWidget::itemSelectionChanged, this, enableButtons);
}
void user_manager_dialog::UpdateTable()
{
if (m_dir == "")
{
// fmt::format(%shome ... is harder to read than straight concatenation.
m_dir = Emu.GetHddDir() + "home";
}
// Get the user folders in the home directory and the currently logged in user.
m_user_list.clear();
m_user_list = GetUserAccounts(m_dir);
m_user_list = GetUserAccounts(Emu.GetHddDir() + "home");
// Clear and then repopulate the table with the list gathered above.
m_table->setRowCount(static_cast<int>(m_user_list.size()));
// For indicating logged-in user.
QFont boldFont;
boldFont.setBold(true);
QFont bold_font;
bold_font.setBold(true);
int row = 0;
for (UserAccount* user : m_user_list)
{
QString userId = qstr(user->GetUserId());
QString userName = qstr(user->GetUserName());
QTableWidgetItem* user_id_item = new QTableWidgetItem(qstr(user->GetUserId()));
user_id_item->setData(Qt::UserRole, row); // For sorting to work properly
user_id_item->setFlags(user_id_item->flags() & ~Qt::ItemIsEditable);
m_table->setItem(row, 0, user_id_item);
QTableWidgetItem* userIdItem = new QTableWidgetItem(userId);
userIdItem->setData(Qt::UserRole, row); // For sorting to work properly
userIdItem->setFlags(userIdItem->flags() & ~Qt::ItemIsEditable);
m_table->setItem(row, 0, userIdItem);
QTableWidgetItem* userNameItem = new QTableWidgetItem(userName);
userNameItem->setData(Qt::UserRole, row); // For sorting to work properly
userNameItem->setFlags(userNameItem->flags() & ~Qt::ItemIsEditable);
m_table->setItem(row, 1, userNameItem);
QTableWidgetItem* username_item = new QTableWidgetItem(qstr(user->GetUserName()));
username_item->setData(Qt::UserRole, row); // For sorting to work properly
username_item->setFlags(username_item->flags() & ~Qt::ItemIsEditable);
m_table->setItem(row, 1, username_item);
// Compare current config value with the one in this user (only 8 digits in userId)
if (m_selected_user.compare(0, 8, user->GetUserId()) == 0)
if (m_active_user.compare(0, 8, user->GetUserId()) == 0)
{
userIdItem->setFont(boldFont);
userNameItem->setFont(boldFont);
user_id_item->setFont(bold_font);
username_item->setFont(bold_font);
}
++row;
}
@ -171,83 +166,103 @@ void user_manager_dialog::UpdateTable()
m_table->horizontalHeader()->resizeSections(QHeaderView::ResizeToContents);
m_table->verticalHeader()->resizeSections(QHeaderView::ResizeToContents);
QSize tableSize = QSize(
QSize table_size = QSize(
m_table->verticalHeader()->width() + m_table->horizontalHeader()->length() + m_table->frameWidth() * 2,
m_table->horizontalHeader()->height() + m_table->verticalHeader()->length() + m_table->frameWidth() * 2);
QSize preferredSize = minimumSize().expandedTo(sizeHint() - m_table->sizeHint() + tableSize).expandedTo(size());
QSize maxSize = QSize(preferredSize.width(), static_cast<int>(QApplication::desktop()->screenGeometry().height()*.6));
QSize preferred_size = minimumSize().expandedTo(sizeHint() - m_table->sizeHint() + table_size).expandedTo(size());
QSize max_size = QSize(preferred_size.width(), static_cast<int>(QApplication::desktop()->screenGeometry().height()*.6));
resize(preferredSize.boundedTo(maxSize));
resize(preferred_size.boundedTo(max_size));
}
//Remove a user folder, needs to be confirmed.
// Remove a user folder, needs to be confirmed.
void user_manager_dialog::OnUserRemove()
{
int idx = m_table->currentRow();
int idx_real = m_table->item(idx, 0)->data(Qt::UserRole).toInt();
if (QMessageBox::question(this, tr("Delete Confirmation"), tr("Are you sure you want to delete:\n%1?").arg(qstr(m_user_list[idx_real]->GetUserName())), QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes)
const int idx = m_table->currentRow();
if (idx < 0)
{
fs::remove_all(m_user_list[idx_real]->GetUserDir());
return;
}
const int idx_real = m_table->item(idx, 0)->data(Qt::UserRole).toInt();
const QString username = qstr(m_user_list[idx_real]->GetUserName());
const QString user_id = qstr(m_user_list[idx_real]->GetUserId());
const std::string user_dir = m_user_list[idx_real]->GetUserDir();
if (QMessageBox::question(this, tr("Delete Confirmation"), tr("Are you sure you want to delete the following user?\n\nUser ID: %0\nUsername: %1\n\n"
"This will remove all files in:\n%2").arg(user_id).arg(username).arg(qstr(user_dir)), QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes)
{
LOG_WARNING(GENERAL, "Deleting user: %s", user_dir);
fs::remove_all(user_dir);
UpdateTable();
}
}
void user_manager_dialog::GenerateUser(const std::string& username)
void user_manager_dialog::GenerateUser(const std::string& user_id, const std::string& username)
{
// If the user list is sorted by defult from fs::dir, then we just need the last one in the list.
std::string largestUserId = m_user_list[m_user_list.size() - 1]->GetUserId();
// Add one to the largest user id, then reformat the result into an 8-digit string.
u8 nextLargest = static_cast<u8>(std::stoul(largestUserId) + 1u);
char* buf;
sprintf(buf, "%08d", nextLargest);
std::string nextUserId(buf);
// Create user folders and such.
const std::string homeDir = Emu.GetHddDir() + "home/";
const std::string userDir = homeDir + nextUserId;
fs::create_dir(homeDir);
fs::create_dir(userDir + "/");
fs::create_dir(userDir + "/exdata/");
fs::create_dir(userDir + "/savedata/");
fs::create_dir(userDir + "/trophy/");
fs::write_file(userDir + "/localusername", fs::create + fs::excl + fs::write, username);
const std::string home_dir = Emu.GetHddDir() + "home/";
const std::string user_dir = home_dir + user_id;
fs::create_dir(home_dir);
fs::create_dir(user_dir + "/");
fs::create_dir(user_dir + "/exdata/");
fs::create_dir(user_dir + "/savedata/");
fs::create_dir(user_dir + "/trophy/");
fs::write_file(user_dir + "/localusername", fs::create + fs::excl + fs::write, username);
}
bool user_manager_dialog::ValidateUsername(const QString& textToValidate)
bool user_manager_dialog::ValidateUsername(const QString& text_to_validate)
{
// "Entire string (^...$) must be between 3 and 16 characters
// and only consist of letters, numbers, underscores, and hyphens."
QRegExpValidator validator(QRegExp("^[A-Za-z0-9_-]{3,16}$"));
int pos = 0;
QString text = textToValidate;
QString text = text_to_validate;
return (validator.validate(text, pos) == QValidator::Acceptable);
}
void user_manager_dialog::OnUserRename()
{
const int idx = m_table->currentRow();
if (idx < 0)
{
return;
}
const int idx_real = m_table->item(idx, 0)->data(Qt::UserRole).toInt();
const std::string user_id = m_user_list[idx_real]->GetUserId();
const std::string username = m_user_list[idx_real]->GetUserName();
QInputDialog* dialog = new QInputDialog(this);
dialog->setWindowTitle(tr("Rename User"));
dialog->setLabelText(tr("New Username: "));
dialog->setLabelText(tr("User Id: %0\nOld Username: %1\n\nNew Username: ").arg(qstr(user_id)).arg(qstr(username)));
dialog->resize(200, 100);
while (dialog->exec() != QDialog::Rejected)
{
dialog->resize(200, 100);
QString textToValidate = dialog->textValue();
if (!ValidateUsername(textToValidate))
QString text_to_validate = dialog->textValue();
if (!ValidateUsername(text_to_validate))
{
QMessageBox::warning(this, tr("Error"), tr("Name must be between 3 and 16 characters and only consist of letters, numbers, underscores, and hyphens."));
continue;
}
int idx = m_table->currentRow();
int idx_real = m_table->item(idx, 0)->data(Qt::UserRole).toInt();
const std::string userId = m_user_list[idx_real]->GetUserId();
const std::string usernameFile = Emu.GetHddDir() + "home/" + userId + "/localusername";
fs::write_file(usernameFile, fs::rewrite, textToValidate.toStdString());
const std::string username_file = Emu.GetHddDir() + "home/" + user_id + "/localusername";
const std::string new_username = text_to_validate.toStdString();
if (fs::write_file(username_file, fs::rewrite, new_username))
{
LOG_SUCCESS(GENERAL, "Renamed user %s with id %s to %s", username, user_id, new_username);
}
else
{
LOG_FATAL(GENERAL, "Could not rename user %s with id %s to %s", username, user_id, new_username);
}
UpdateTable();
break;
}
@ -255,21 +270,30 @@ void user_manager_dialog::OnUserRename()
void user_manager_dialog::OnUserCreate()
{
// If the user list is sorted by default from fs::dir, then we just need the last one in the list.
std::string largest_user_id = m_user_list[m_user_list.size() - 1]->GetUserId();
// Add one to the largest user id, then reformat the result into an 8-digit string.
u8 next_largest = static_cast<u8>(std::stoul(largest_user_id) + 1u);
const std::string next_user_id = fmt::format("%08d", next_largest);
QInputDialog* dialog = new QInputDialog(this);
dialog->setWindowTitle(tr("New User"));
dialog->setLabelText(tr("New Username: "));
dialog->setLabelText(tr("New User ID: %0\n\nNew Username: ").arg(qstr(next_user_id)));
dialog->resize(200, 100);
while (dialog->exec() != QDialog::Rejected)
{
dialog->resize(200, 100);
QString textToValidate = dialog->textValue();
if (!ValidateUsername(textToValidate))
QString text_to_validate = dialog->textValue();
if (!ValidateUsername(text_to_validate))
{
QMessageBox::warning(this, tr("Error"), tr("Name must be between 3 and 16 characters and only consist of letters, numbers, underscores, and hyphens."));
continue;
}
GenerateUser(textToValidate.toStdString());
GenerateUser(next_user_id, text_to_validate.toStdString());
UpdateTable();
break;
}
@ -278,11 +302,16 @@ void user_manager_dialog::OnUserCreate()
void user_manager_dialog::OnUserLogin()
{
int idx = m_table->currentRow();
int idx_real = m_table->item(idx, 0)->data(Qt::UserRole).toInt();
std::string selectedUserId = m_user_list[idx_real]->GetUserId();
if (idx < 0)
{
return;
}
m_selected_user = selectedUserId;
m_emu_settings->SetSetting(emu_settings::SelectedUser, m_selected_user);
int idx_real = m_table->item(idx, 0)->data(Qt::UserRole).toInt();
std::string selected_user_id = m_user_list[idx_real]->GetUserId();
m_active_user = selected_user_id;
m_emu_settings->SetSetting(emu_settings::SelectedUser, m_active_user);
m_emu_settings->SaveSettings();
UpdateTable();
Q_EMIT OnUserLoginSuccess();
@ -302,9 +331,9 @@ void user_manager_dialog::OnSort(int logicalIndex)
{
m_sort_ascending = true;
}
m_sort_column = logicalIndex;
Qt::SortOrder sort_order = m_sort_ascending ? Qt::AscendingOrder : Qt::DescendingOrder;
m_table->sortByColumn(m_sort_column, sort_order);
m_sort_column = logicalIndex;
}
void user_manager_dialog::ShowContextMenu(const QPoint &pos)
@ -314,54 +343,43 @@ void user_manager_dialog::ShowContextMenu(const QPoint &pos)
{
return;
}
QPoint globalPos = m_table->mapToGlobal(pos);
QPoint global_pos = m_table->mapToGlobal(pos);
QMenu* menu = new QMenu();
// Create all the actions before adding them to the menu/submenus.
QAction* userIdAct = new QAction(tr("User ID"), this);
QAction* userNameAct = new QAction(tr("User Name"), this);
// Create submenu for sort options.
QMenu* sort_menu = menu->addMenu(tr("&Sort By"));
QAction* user_id_act = sort_menu->addAction(tr("User ID"));
QAction* username_act = sort_menu->addAction(tr("User Name"));
QAction* removeAct = new QAction(tr("&Remove"), this);
QAction* renameAct = new QAction(tr("&Rename"), this);
QAction* loginAct = new QAction(tr("&Login"), this);
QAction* showDirAct = new QAction(tr("&Open User Directory"), this);
//Create submenu for sort options.
m_sort_options = new QMenu(tr("&Sort By"));
m_sort_options->addAction(userIdAct);
m_sort_options->addAction(userNameAct);
// Add all options and submenus to the context menu.
menu->addMenu(m_sort_options);
menu->addSeparator();
menu->addAction(removeAct);
menu->addAction(renameAct);
menu->addAction(loginAct);
menu->addAction(showDirAct);
QAction* remove_act = menu->addAction(tr("&Remove"));
QAction* rename_act = menu->addAction(tr("&Rename"));
QAction* login_act = menu->addAction(tr("&Login"));
QAction* show_dir_act = menu->addAction(tr("&Open User Directory"));
// Only enable actions if selected user is not logged in user.
int idx_real = m_table->item(idx, 0)->data(Qt::UserRole).toInt();
std::string idx_user = m_user_list[idx_real]->GetUserId();
bool enable = idx_user != m_selected_user;
bool enable = idx_user != m_active_user;
removeAct->setEnabled(enable);
renameAct->setEnabled(enable);
remove_act->setEnabled(enable);
rename_act->setEnabled(enable);
// Connects and Events
connect(removeAct, &QAction::triggered, this, &user_manager_dialog::OnUserRemove);
connect(renameAct, &QAction::triggered, this, &user_manager_dialog::OnUserRename);
connect(loginAct, &QAction::triggered, this, &user_manager_dialog::OnUserLogin);
connect(showDirAct, &QAction::triggered, [=]()
connect(remove_act, &QAction::triggered, this, &user_manager_dialog::OnUserRemove);
connect(rename_act, &QAction::triggered, this, &user_manager_dialog::OnUserRename);
connect(login_act, &QAction::triggered, this, &user_manager_dialog::OnUserLogin);
connect(show_dir_act, &QAction::triggered, [=]()
{
int idx_real = m_table->item(idx, 0)->data(Qt::UserRole).toInt();
QString path = qstr(m_user_list[idx_real]->GetUserDir());
QDesktopServices::openUrl(QUrl("file:///" + path));
});
connect(userIdAct, &QAction::triggered, this, [=] {OnSort(0); });
connect(userNameAct, &QAction::triggered, this, [=] {OnSort(1); });
connect(user_id_act, &QAction::triggered, this, [=] {OnSort(0); });
connect(username_act, &QAction::triggered, this, [=] {OnSort(1); });
menu->exec(globalPos);
menu->exec(global_pos);
}
void user_manager_dialog::closeEvent(QCloseEvent *event)

View file

@ -24,7 +24,7 @@ class user_manager_dialog : public QDialog
{
Q_OBJECT
public:
explicit user_manager_dialog(std::shared_ptr<gui_settings> gui_settings, std::shared_ptr<emu_settings> emu_settings, const std::string& dir = "", QWidget* parent = nullptr);
explicit user_manager_dialog(std::shared_ptr<gui_settings> gui_settings, std::shared_ptr<emu_settings> emu_settings, QWidget* parent = nullptr);
Q_SIGNALS:
void OnUserLoginSuccess();
private Q_SLOTS:
@ -34,25 +34,22 @@ private Q_SLOTS:
void OnUserRename();
void OnSort(int logicalIndex);
private:
void Init(const std::string& dir);
void Init();
void UpdateTable();
void GenerateUser(const std::string& username);
bool ValidateUsername(const QString& textToValidate);
void GenerateUser(const std::string& user_id, const std::string& username);
bool ValidateUsername(const QString& text_to_validate);
void ShowContextMenu(const QPoint &pos);
void closeEvent(QCloseEvent* event) override;
QTableWidget* m_table;
std::string m_dir;
std::string m_selected_user;
std::string m_active_user;
std::vector<UserAccount*> m_user_list;
std::shared_ptr<gui_settings> m_gui_settings;
std::shared_ptr<emu_settings> m_emu_settings;
QMenu* m_sort_options;
int m_sort_column;
bool m_sort_ascending;
};