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
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") {} 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" }; cfg::string selected_usr{ this, "Selected User", "00000001" };
} usr{this}; } usr{this};

View file

@ -1269,7 +1269,7 @@ void main_window::CreateConnects()
connect(ui->actionManage_Users, &QAction::triggered, [=] 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(); user_manager->show();
}); });

View file

@ -1,27 +1,26 @@
#include "user_account.h" #include "user_account.h"
UserAccount::UserAccount(const std::string& userId) UserAccount::UserAccount(const std::string& user_id)
{ {
// Setting userId. // Setting userId.
m_userId = userId; m_user_id = user_id;
// Setting userDir. // Setting userDir.
m_userDir = Emu.GetHddDir() + "home/" + m_userId + "/"; m_user_dir = Emu.GetHddDir() + "home/" + m_user_id + "/";
// Setting userName. // Setting userName.
fs::file file; 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(); file.close();
} }
else 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() UserAccount::~UserAccount()
{ {
} }

View file

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

View file

@ -1,4 +1,5 @@
#include "user_manager_dialog.h" #include "user_manager_dialog.h"
#include "table_item_delegate.h"
#include "Utilities/StrUtil.h" #include "Utilities/StrUtil.h"
@ -13,57 +14,56 @@ namespace
// I believe this gets the folder list sorted alphabetically by default, // I believe this gets the folder list sorted alphabetically by default,
// but I can't find proof of this always being true. // 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; continue;
} }
// Is the folder name exactly 8 all-numerical characters long? // Is the folder name exactly 8 all-numerical characters long?
// We use strtol to find any non-numeric characters in folder name. // We use strtol to find any non-numeric characters in folder name.
char* nonNumericChar; char* non_numeric_char;
std::strtol(userFolder.name.c_str(), &nonNumericChar, 10); std::strtol(user_folder.name.c_str(), &non_numeric_char, 10);
if (userFolder.name.length() != 8 || *nonNumericChar != '\0') if (user_folder.name.length() != 8 || *non_numeric_char != '\0')
{ {
continue; continue;
} }
// Does the localusername file exist? // 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; continue;
} }
UserAccount* user_entry = new UserAccount(userFolder.name); user_list.emplace_back(new UserAccount(user_folder.name));
user_list.emplace_back(user_entry);
} }
return user_list; 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) 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_dir(dir), m_sort_column(1), m_sort_ascending(true), m_gui_settings(gui_settings), m_emu_settings(emu_settings) : 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")); setWindowTitle(tr("User Manager"));
setMinimumSize(QSize(400, 400)); setMinimumSize(QSize(400, 400));
setModal(true); setModal(true);
m_emu_settings->LoadSettings(); m_emu_settings->LoadSettings();
Init(dir); Init();
} }
void user_manager_dialog::Init(const std::string& dir) void user_manager_dialog::Init()
{ {
// Table // Table
m_table = new QTableWidget(this); m_table = new QTableWidget(this);
m_table->setItemDelegate(new table_item_delegate(this)); // to get rid of cell selection rectangles
//m_table->setItemDelegate(new table_item_delegate(this)); // to get rid of cell selection rectangles include "table_item_delegate.h"
m_table->setSelectionMode(QAbstractItemView::SelectionMode::SingleSelection); m_table->setSelectionMode(QAbstractItemView::SelectionMode::SingleSelection);
m_table->setSelectionBehavior(QAbstractItemView::SelectRows); m_table->setSelectionBehavior(QAbstractItemView::SelectRows);
m_table->setContextMenuPolicy(Qt::CustomContextMenu); m_table->setContextMenuPolicy(Qt::CustomContextMenu);
m_table->setColumnCount(2); m_table->setColumnCount(2);
m_table->setHorizontalHeaderLabels(QStringList() << tr("User ID") << tr("User Name")); 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_remove_user = new QPushButton(tr("Delete User"), this);
QPushButton* push_create_user = new QPushButton(tr("Create 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->addStretch();
hbox_buttons->addWidget(push_close); hbox_buttons->addWidget(push_close);
// main layout // Main Layout
QVBoxLayout* vbox_main = new QVBoxLayout(); QVBoxLayout* vbox_main = new QVBoxLayout();
vbox_main->setAlignment(Qt::AlignCenter); vbox_main->setAlignment(Qt::AlignCenter);
vbox_main->addWidget(m_table); vbox_main->addWidget(m_table);
vbox_main->addLayout(hbox_buttons); vbox_main->addLayout(hbox_buttons);
setLayout(vbox_main); setLayout(vbox_main);
m_selected_user = m_emu_settings->GetSetting(emu_settings::SelectedUser); m_active_user = m_emu_settings->GetSetting(emu_settings::SelectedUser);
UpdateTable(); UpdateTable();
restoreGeometry(m_gui_settings->GetValue(gui::um_geometry).toByteArray()); 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(); int idx = m_table->currentRow();
if (idx < 0) if (idx < 0)
{ {
push_rename_user->setEnabled(false);
push_remove_user->setEnabled(false);
return; return;
} }
int idx_real = m_table->item(idx, 0)->data(Qt::UserRole).toInt(); int idx_real = m_table->item(idx, 0)->data(Qt::UserRole).toInt();
std::string idx_user = m_user_list[idx_real]->GetUserId(); 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_rename_user->setEnabled(enable);
push_remove_user->setEnabled(enable); push_remove_user->setEnabled(enable);
}; };
enableButtons();
// Connects and events // Connects and events
connect(push_close, &QAbstractButton::clicked, this, &user_manager_dialog::close); connect(push_close, &QAbstractButton::clicked, this, &user_manager_dialog::close);
connect(push_remove_user, &QAbstractButton::clicked, this, &user_manager_dialog::OnUserRemove); 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_create_user, &QAbstractButton::clicked, this, &user_manager_dialog::OnUserCreate);
connect(push_login_user, &QAbstractButton::clicked, this, &user_manager_dialog::OnUserLogin); connect(push_login_user, &QAbstractButton::clicked, this, &user_manager_dialog::OnUserLogin);
connect(this, &user_manager_dialog::OnUserLoginSuccess, this, enableButtons); 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->horizontalHeader(), &QHeaderView::sectionClicked, this, &user_manager_dialog::OnSort);
connect(m_table, &QTableWidget::customContextMenuRequested, this, &user_manager_dialog::ShowContextMenu); 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); connect(m_table, &QTableWidget::itemSelectionChanged, this, enableButtons);
} }
void user_manager_dialog::UpdateTable() 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. // Get the user folders in the home directory and the currently logged in user.
m_user_list.clear(); 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. // Clear and then repopulate the table with the list gathered above.
m_table->setRowCount(static_cast<int>(m_user_list.size())); m_table->setRowCount(static_cast<int>(m_user_list.size()));
// For indicating logged-in user. // For indicating logged-in user.
QFont boldFont; QFont bold_font;
boldFont.setBold(true); bold_font.setBold(true);
int row = 0; int row = 0;
for (UserAccount* user : m_user_list) for (UserAccount* user : m_user_list)
{ {
QString userId = qstr(user->GetUserId()); QTableWidgetItem* user_id_item = new QTableWidgetItem(qstr(user->GetUserId()));
QString userName = qstr(user->GetUserName()); 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); QTableWidgetItem* username_item = new QTableWidgetItem(qstr(user->GetUserName()));
userIdItem->setData(Qt::UserRole, row); // For sorting to work properly username_item->setData(Qt::UserRole, row); // For sorting to work properly
userIdItem->setFlags(userIdItem->flags() & ~Qt::ItemIsEditable); username_item->setFlags(username_item->flags() & ~Qt::ItemIsEditable);
m_table->setItem(row, 0, userIdItem); m_table->setItem(row, 1, username_item);
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);
// Compare current config value with the one in this user (only 8 digits in userId) // 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); user_id_item->setFont(bold_font);
userNameItem->setFont(boldFont); username_item->setFont(bold_font);
} }
++row; ++row;
} }
@ -171,83 +166,103 @@ void user_manager_dialog::UpdateTable()
m_table->horizontalHeader()->resizeSections(QHeaderView::ResizeToContents); m_table->horizontalHeader()->resizeSections(QHeaderView::ResizeToContents);
m_table->verticalHeader()->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->verticalHeader()->width() + m_table->horizontalHeader()->length() + m_table->frameWidth() * 2,
m_table->horizontalHeader()->height() + m_table->verticalHeader()->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 preferred_size = minimumSize().expandedTo(sizeHint() - m_table->sizeHint() + table_size).expandedTo(size());
QSize maxSize = QSize(preferredSize.width(), static_cast<int>(QApplication::desktop()->screenGeometry().height()*.6)); 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() void user_manager_dialog::OnUserRemove()
{ {
int idx = m_table->currentRow(); const int idx = m_table->currentRow();
int idx_real = m_table->item(idx, 0)->data(Qt::UserRole).toInt(); if (idx < 0)
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)
{ {
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(); 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. // Create user folders and such.
const std::string homeDir = Emu.GetHddDir() + "home/"; const std::string home_dir = Emu.GetHddDir() + "home/";
const std::string userDir = homeDir + nextUserId; const std::string user_dir = home_dir + user_id;
fs::create_dir(homeDir); fs::create_dir(home_dir);
fs::create_dir(userDir + "/"); fs::create_dir(user_dir + "/");
fs::create_dir(userDir + "/exdata/"); fs::create_dir(user_dir + "/exdata/");
fs::create_dir(userDir + "/savedata/"); fs::create_dir(user_dir + "/savedata/");
fs::create_dir(userDir + "/trophy/"); fs::create_dir(user_dir + "/trophy/");
fs::write_file(userDir + "/localusername", fs::create + fs::excl + fs::write, username); 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 // "Entire string (^...$) must be between 3 and 16 characters
// and only consist of letters, numbers, underscores, and hyphens." // and only consist of letters, numbers, underscores, and hyphens."
QRegExpValidator validator(QRegExp("^[A-Za-z0-9_-]{3,16}$")); QRegExpValidator validator(QRegExp("^[A-Za-z0-9_-]{3,16}$"));
int pos = 0; int pos = 0;
QString text = textToValidate; QString text = text_to_validate;
return (validator.validate(text, pos) == QValidator::Acceptable); return (validator.validate(text, pos) == QValidator::Acceptable);
} }
void user_manager_dialog::OnUserRename() 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); QInputDialog* dialog = new QInputDialog(this);
dialog->setWindowTitle(tr("Rename User")); 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); dialog->resize(200, 100);
while (dialog->exec() != QDialog::Rejected) while (dialog->exec() != QDialog::Rejected)
{ {
dialog->resize(200, 100); 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.")); QMessageBox::warning(this, tr("Error"), tr("Name must be between 3 and 16 characters and only consist of letters, numbers, underscores, and hyphens."));
continue; 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 username_file = Emu.GetHddDir() + "home/" + user_id + "/localusername";
const std::string usernameFile = Emu.GetHddDir() + "home/" + userId + "/localusername"; const std::string new_username = text_to_validate.toStdString();
fs::write_file(usernameFile, fs::rewrite, textToValidate.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(); UpdateTable();
break; break;
} }
@ -255,21 +270,30 @@ void user_manager_dialog::OnUserRename()
void user_manager_dialog::OnUserCreate() 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); QInputDialog* dialog = new QInputDialog(this);
dialog->setWindowTitle(tr("New User")); 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); dialog->resize(200, 100);
while (dialog->exec() != QDialog::Rejected) while (dialog->exec() != QDialog::Rejected)
{ {
dialog->resize(200, 100); 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.")); QMessageBox::warning(this, tr("Error"), tr("Name must be between 3 and 16 characters and only consist of letters, numbers, underscores, and hyphens."));
continue; continue;
} }
GenerateUser(textToValidate.toStdString());
GenerateUser(next_user_id, text_to_validate.toStdString());
UpdateTable(); UpdateTable();
break; break;
} }
@ -278,11 +302,16 @@ void user_manager_dialog::OnUserCreate()
void user_manager_dialog::OnUserLogin() void user_manager_dialog::OnUserLogin()
{ {
int idx = m_table->currentRow(); int idx = m_table->currentRow();
int idx_real = m_table->item(idx, 0)->data(Qt::UserRole).toInt(); if (idx < 0)
std::string selectedUserId = m_user_list[idx_real]->GetUserId(); {
return;
}
m_selected_user = selectedUserId; int idx_real = m_table->item(idx, 0)->data(Qt::UserRole).toInt();
m_emu_settings->SetSetting(emu_settings::SelectedUser, m_selected_user); 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(); m_emu_settings->SaveSettings();
UpdateTable(); UpdateTable();
Q_EMIT OnUserLoginSuccess(); Q_EMIT OnUserLoginSuccess();
@ -302,9 +331,9 @@ void user_manager_dialog::OnSort(int logicalIndex)
{ {
m_sort_ascending = true; m_sort_ascending = true;
} }
m_sort_column = logicalIndex;
Qt::SortOrder sort_order = m_sort_ascending ? Qt::AscendingOrder : Qt::DescendingOrder; Qt::SortOrder sort_order = m_sort_ascending ? Qt::AscendingOrder : Qt::DescendingOrder;
m_table->sortByColumn(m_sort_column, sort_order); m_table->sortByColumn(m_sort_column, sort_order);
m_sort_column = logicalIndex;
} }
void user_manager_dialog::ShowContextMenu(const QPoint &pos) void user_manager_dialog::ShowContextMenu(const QPoint &pos)
@ -314,54 +343,43 @@ void user_manager_dialog::ShowContextMenu(const QPoint &pos)
{ {
return; return;
} }
QPoint globalPos = m_table->mapToGlobal(pos);
QPoint global_pos = m_table->mapToGlobal(pos);
QMenu* menu = new QMenu(); QMenu* menu = new QMenu();
// Create all the actions before adding them to the menu/submenus. // Create submenu for sort options.
QAction* userIdAct = new QAction(tr("User ID"), this); QMenu* sort_menu = menu->addMenu(tr("&Sort By"));
QAction* userNameAct = new QAction(tr("User Name"), this); 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* remove_act = menu->addAction(tr("&Remove"));
QAction* renameAct = new QAction(tr("&Rename"), this); QAction* rename_act = menu->addAction(tr("&Rename"));
QAction* loginAct = new QAction(tr("&Login"), this); QAction* login_act = menu->addAction(tr("&Login"));
QAction* showDirAct = new QAction(tr("&Open User Directory"), this); QAction* show_dir_act = menu->addAction(tr("&Open User Directory"));
//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);
// Only enable actions if selected user is not logged in user. // Only enable actions if selected user is not logged in user.
int idx_real = m_table->item(idx, 0)->data(Qt::UserRole).toInt(); int idx_real = m_table->item(idx, 0)->data(Qt::UserRole).toInt();
std::string idx_user = m_user_list[idx_real]->GetUserId(); 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); remove_act->setEnabled(enable);
renameAct->setEnabled(enable); rename_act->setEnabled(enable);
// Connects and Events // Connects and Events
connect(removeAct, &QAction::triggered, this, &user_manager_dialog::OnUserRemove); connect(remove_act, &QAction::triggered, this, &user_manager_dialog::OnUserRemove);
connect(renameAct, &QAction::triggered, this, &user_manager_dialog::OnUserRename); connect(rename_act, &QAction::triggered, this, &user_manager_dialog::OnUserRename);
connect(loginAct, &QAction::triggered, this, &user_manager_dialog::OnUserLogin); connect(login_act, &QAction::triggered, this, &user_manager_dialog::OnUserLogin);
connect(showDirAct, &QAction::triggered, [=]() connect(show_dir_act, &QAction::triggered, [=]()
{ {
int idx_real = m_table->item(idx, 0)->data(Qt::UserRole).toInt(); int idx_real = m_table->item(idx, 0)->data(Qt::UserRole).toInt();
QString path = qstr(m_user_list[idx_real]->GetUserDir()); QString path = qstr(m_user_list[idx_real]->GetUserDir());
QDesktopServices::openUrl(QUrl("file:///" + path)); QDesktopServices::openUrl(QUrl("file:///" + path));
}); });
connect(userIdAct, &QAction::triggered, this, [=] {OnSort(0); }); connect(user_id_act, &QAction::triggered, this, [=] {OnSort(0); });
connect(userNameAct, &QAction::triggered, this, [=] {OnSort(1); }); connect(username_act, &QAction::triggered, this, [=] {OnSort(1); });
menu->exec(globalPos); menu->exec(global_pos);
} }
void user_manager_dialog::closeEvent(QCloseEvent *event) void user_manager_dialog::closeEvent(QCloseEvent *event)

View file

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