lobby.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. // SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <QInputDialog>
  4. #include <QList>
  5. #include <QtConcurrent/QtConcurrentRun>
  6. #include "common/logging/log.h"
  7. #include "common/settings.h"
  8. #include "core/core.h"
  9. #include "core/hle/service/acc/profile_manager.h"
  10. #include "core/internal_network/network_interface.h"
  11. #include "network/network.h"
  12. #include "ui_lobby.h"
  13. #include "yuzu/game_list_p.h"
  14. #include "yuzu/main.h"
  15. #include "yuzu/multiplayer/client_room.h"
  16. #include "yuzu/multiplayer/lobby.h"
  17. #include "yuzu/multiplayer/lobby_p.h"
  18. #include "yuzu/multiplayer/message.h"
  19. #include "yuzu/multiplayer/state.h"
  20. #include "yuzu/multiplayer/validation.h"
  21. #include "yuzu/uisettings.h"
  22. #ifdef ENABLE_WEB_SERVICE
  23. #include "web_service/web_backend.h"
  24. #endif
  25. Lobby::Lobby(QWidget* parent, QStandardItemModel* list,
  26. std::shared_ptr<Core::AnnounceMultiplayerSession> session, Core::System& system_)
  27. : QDialog(parent, Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint),
  28. ui(std::make_unique<Ui::Lobby>()),
  29. announce_multiplayer_session(session), system{system_}, room_network{
  30. system.GetRoomNetwork()} {
  31. ui->setupUi(this);
  32. // setup the watcher for background connections
  33. watcher = new QFutureWatcher<void>;
  34. model = new QStandardItemModel(ui->room_list);
  35. // Create a proxy to the game list to get the list of games owned
  36. game_list = new QStandardItemModel;
  37. UpdateGameList(list);
  38. proxy = new LobbyFilterProxyModel(this, game_list);
  39. proxy->setSourceModel(model);
  40. proxy->setDynamicSortFilter(true);
  41. proxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
  42. proxy->setSortLocaleAware(true);
  43. ui->room_list->setModel(proxy);
  44. ui->room_list->header()->setSectionResizeMode(QHeaderView::Interactive);
  45. ui->room_list->header()->stretchLastSection();
  46. ui->room_list->setAlternatingRowColors(true);
  47. ui->room_list->setSelectionMode(QHeaderView::SingleSelection);
  48. ui->room_list->setSelectionBehavior(QHeaderView::SelectRows);
  49. ui->room_list->setVerticalScrollMode(QHeaderView::ScrollPerPixel);
  50. ui->room_list->setHorizontalScrollMode(QHeaderView::ScrollPerPixel);
  51. ui->room_list->setSortingEnabled(true);
  52. ui->room_list->setEditTriggers(QHeaderView::NoEditTriggers);
  53. ui->room_list->setExpandsOnDoubleClick(false);
  54. ui->room_list->setContextMenuPolicy(Qt::CustomContextMenu);
  55. ui->nickname->setValidator(validation.GetNickname());
  56. ui->nickname->setText(
  57. QString::fromStdString(UISettings::values.multiplayer_nickname.GetValue()));
  58. // Try find the best nickname by default
  59. if (ui->nickname->text().isEmpty() || ui->nickname->text() == QStringLiteral("yuzu")) {
  60. if (!Settings::values.yuzu_username.GetValue().empty()) {
  61. ui->nickname->setText(
  62. QString::fromStdString(Settings::values.yuzu_username.GetValue()));
  63. } else if (!GetProfileUsername().empty()) {
  64. ui->nickname->setText(QString::fromStdString(GetProfileUsername()));
  65. } else {
  66. ui->nickname->setText(QStringLiteral("yuzu"));
  67. }
  68. }
  69. // UI Buttons
  70. connect(ui->refresh_list, &QPushButton::clicked, this, &Lobby::RefreshLobby);
  71. connect(ui->search, &QLineEdit::textChanged, proxy, &LobbyFilterProxyModel::SetFilterSearch);
  72. connect(ui->games_owned, &QCheckBox::toggled, proxy, &LobbyFilterProxyModel::SetFilterOwned);
  73. connect(ui->hide_empty, &QCheckBox::toggled, proxy, &LobbyFilterProxyModel::SetFilterEmpty);
  74. connect(ui->hide_full, &QCheckBox::toggled, proxy, &LobbyFilterProxyModel::SetFilterFull);
  75. connect(ui->room_list, &QTreeView::doubleClicked, this, &Lobby::OnJoinRoom);
  76. connect(ui->room_list, &QTreeView::clicked, this, &Lobby::OnExpandRoom);
  77. // Actions
  78. connect(&room_list_watcher, &QFutureWatcher<AnnounceMultiplayerRoom::RoomList>::finished, this,
  79. &Lobby::OnRefreshLobby);
  80. // Load persistent filters after events are connected to make sure they apply
  81. ui->search->setText(
  82. QString::fromStdString(UISettings::values.multiplayer_filter_text.GetValue()));
  83. ui->games_owned->setChecked(UISettings::values.multiplayer_filter_games_owned.GetValue());
  84. ui->hide_empty->setChecked(UISettings::values.multiplayer_filter_hide_empty.GetValue());
  85. ui->hide_full->setChecked(UISettings::values.multiplayer_filter_hide_full.GetValue());
  86. }
  87. Lobby::~Lobby() = default;
  88. void Lobby::UpdateGameList(QStandardItemModel* list) {
  89. game_list->clear();
  90. for (int i = 0; i < list->rowCount(); i++) {
  91. auto parent = list->item(i, 0);
  92. for (int j = 0; j < parent->rowCount(); j++) {
  93. game_list->appendRow(parent->child(j)->clone());
  94. }
  95. }
  96. if (proxy)
  97. proxy->UpdateGameList(game_list);
  98. ui->room_list->sortByColumn(Column::GAME_NAME, Qt::AscendingOrder);
  99. }
  100. void Lobby::RetranslateUi() {
  101. ui->retranslateUi(this);
  102. }
  103. QString Lobby::PasswordPrompt() {
  104. bool ok;
  105. const QString text =
  106. QInputDialog::getText(this, tr("Password Required to Join"), tr("Password:"),
  107. QLineEdit::Password, QString(), &ok);
  108. return ok ? text : QString();
  109. }
  110. void Lobby::OnExpandRoom(const QModelIndex& index) {
  111. QModelIndex member_index = proxy->index(index.row(), Column::MEMBER);
  112. auto member_list = proxy->data(member_index, LobbyItemMemberList::MemberListRole).toList();
  113. }
  114. void Lobby::OnJoinRoom(const QModelIndex& source) {
  115. if (!Network::GetSelectedNetworkInterface()) {
  116. LOG_INFO(WebService, "Automatically selected network interface for room network.");
  117. Network::SelectFirstNetworkInterface();
  118. }
  119. if (!Network::GetSelectedNetworkInterface()) {
  120. NetworkMessage::ErrorManager::ShowError(
  121. NetworkMessage::ErrorManager::NO_INTERFACE_SELECTED);
  122. return;
  123. }
  124. if (system.IsPoweredOn()) {
  125. if (!NetworkMessage::WarnGameRunning()) {
  126. return;
  127. }
  128. }
  129. if (const auto member = room_network.GetRoomMember().lock()) {
  130. // Prevent the user from trying to join a room while they are already joining.
  131. if (member->GetState() == Network::RoomMember::State::Joining) {
  132. return;
  133. } else if (member->IsConnected()) {
  134. // And ask if they want to leave the room if they are already in one.
  135. if (!NetworkMessage::WarnDisconnect()) {
  136. return;
  137. }
  138. }
  139. }
  140. QModelIndex index = source;
  141. // If the user double clicks on a child row (aka the player list) then use the parent instead
  142. if (source.parent() != QModelIndex()) {
  143. index = source.parent();
  144. }
  145. if (!ui->nickname->hasAcceptableInput()) {
  146. NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::USERNAME_NOT_VALID);
  147. return;
  148. }
  149. // Get a password to pass if the room is password protected
  150. QModelIndex password_index = proxy->index(index.row(), Column::ROOM_NAME);
  151. bool has_password = proxy->data(password_index, LobbyItemName::PasswordRole).toBool();
  152. const std::string password = has_password ? PasswordPrompt().toStdString() : "";
  153. if (has_password && password.empty()) {
  154. return;
  155. }
  156. QModelIndex connection_index = proxy->index(index.row(), Column::HOST);
  157. const std::string nickname = ui->nickname->text().toStdString();
  158. const std::string ip =
  159. proxy->data(connection_index, LobbyItemHost::HostIPRole).toString().toStdString();
  160. int port = proxy->data(connection_index, LobbyItemHost::HostPortRole).toInt();
  161. const std::string verify_uid =
  162. proxy->data(connection_index, LobbyItemHost::HostVerifyUIDRole).toString().toStdString();
  163. // attempt to connect in a different thread
  164. QFuture<void> f = QtConcurrent::run([nickname, ip, port, password, verify_uid, this] {
  165. std::string token;
  166. #ifdef ENABLE_WEB_SERVICE
  167. if (!Settings::values.yuzu_username.GetValue().empty() &&
  168. !Settings::values.yuzu_token.GetValue().empty()) {
  169. WebService::Client client(Settings::values.web_api_url.GetValue(),
  170. Settings::values.yuzu_username.GetValue(),
  171. Settings::values.yuzu_token.GetValue());
  172. token = client.GetExternalJWT(verify_uid).returned_data;
  173. if (token.empty()) {
  174. LOG_ERROR(WebService, "Could not get external JWT, verification may fail");
  175. } else {
  176. LOG_INFO(WebService, "Successfully requested external JWT: size={}", token.size());
  177. }
  178. }
  179. #endif
  180. if (auto room_member = room_network.GetRoomMember().lock()) {
  181. room_member->Join(nickname, ip.c_str(), port, 0, Network::NoPreferredIP, password,
  182. token);
  183. }
  184. });
  185. watcher->setFuture(f);
  186. // TODO(jroweboy): disable widgets and display a connecting while we wait
  187. // Save settings
  188. UISettings::values.multiplayer_nickname = ui->nickname->text().toStdString();
  189. UISettings::values.multiplayer_filter_text = ui->search->text().toStdString();
  190. UISettings::values.multiplayer_filter_games_owned = ui->games_owned->isChecked();
  191. UISettings::values.multiplayer_filter_hide_empty = ui->hide_empty->isChecked();
  192. UISettings::values.multiplayer_filter_hide_full = ui->hide_full->isChecked();
  193. UISettings::values.multiplayer_ip =
  194. proxy->data(connection_index, LobbyItemHost::HostIPRole).value<QString>().toStdString();
  195. UISettings::values.multiplayer_port =
  196. proxy->data(connection_index, LobbyItemHost::HostPortRole).toInt();
  197. emit SaveConfig();
  198. }
  199. void Lobby::ResetModel() {
  200. model->clear();
  201. model->insertColumns(0, Column::TOTAL);
  202. model->setHeaderData(Column::MEMBER, Qt::Horizontal, tr("Players"), Qt::DisplayRole);
  203. model->setHeaderData(Column::ROOM_NAME, Qt::Horizontal, tr("Room Name"), Qt::DisplayRole);
  204. model->setHeaderData(Column::GAME_NAME, Qt::Horizontal, tr("Preferred Game"), Qt::DisplayRole);
  205. model->setHeaderData(Column::HOST, Qt::Horizontal, tr("Host"), Qt::DisplayRole);
  206. }
  207. void Lobby::RefreshLobby() {
  208. if (auto session = announce_multiplayer_session.lock()) {
  209. ResetModel();
  210. ui->refresh_list->setEnabled(false);
  211. ui->refresh_list->setText(tr("Refreshing"));
  212. room_list_watcher.setFuture(
  213. QtConcurrent::run([session]() { return session->GetRoomList(); }));
  214. } else {
  215. // TODO(jroweboy): Display an error box about announce couldn't be started
  216. }
  217. }
  218. void Lobby::OnRefreshLobby() {
  219. AnnounceMultiplayerRoom::RoomList new_room_list = room_list_watcher.result();
  220. for (auto room : new_room_list) {
  221. // find the icon for the game if this person owns that game.
  222. QPixmap smdh_icon;
  223. for (int r = 0; r < game_list->rowCount(); ++r) {
  224. auto index = game_list->index(r, 0);
  225. auto game_id = game_list->data(index, GameListItemPath::ProgramIdRole).toULongLong();
  226. if (game_id != 0 && room.information.preferred_game.id == game_id) {
  227. smdh_icon = game_list->data(index, Qt::DecorationRole).value<QPixmap>();
  228. }
  229. }
  230. QList<QVariant> members;
  231. for (auto member : room.members) {
  232. QVariant var;
  233. var.setValue(LobbyMember{QString::fromStdString(member.username),
  234. QString::fromStdString(member.nickname), member.game.id,
  235. QString::fromStdString(member.game.name)});
  236. members.append(var);
  237. }
  238. auto first_item = new LobbyItemGame(
  239. room.information.preferred_game.id,
  240. QString::fromStdString(room.information.preferred_game.name), smdh_icon);
  241. auto row = QList<QStandardItem*>({
  242. first_item,
  243. new LobbyItemName(room.has_password, QString::fromStdString(room.information.name)),
  244. new LobbyItemMemberList(members, room.information.member_slots),
  245. new LobbyItemHost(QString::fromStdString(room.information.host_username),
  246. QString::fromStdString(room.ip), room.information.port,
  247. QString::fromStdString(room.verify_uid)),
  248. });
  249. model->appendRow(row);
  250. // To make the rows expandable, add the member data as a child of the first column of the
  251. // rows with people in them and have qt set them to colspan after the model is finished
  252. // resetting
  253. if (!room.information.description.empty()) {
  254. first_item->appendRow(
  255. new LobbyItemDescription(QString::fromStdString(room.information.description)));
  256. }
  257. if (!room.members.empty()) {
  258. first_item->appendRow(new LobbyItemExpandedMemberList(members));
  259. }
  260. }
  261. // Re-enable the refresh button and resize the columns
  262. ui->refresh_list->setEnabled(true);
  263. ui->refresh_list->setText(tr("Refresh List"));
  264. ui->room_list->header()->stretchLastSection();
  265. for (int i = 0; i < Column::TOTAL - 1; ++i) {
  266. ui->room_list->resizeColumnToContents(i);
  267. }
  268. // Set the member list child items to span all columns
  269. for (int i = 0; i < proxy->rowCount(); i++) {
  270. auto parent = model->item(i, 0);
  271. for (int j = 0; j < parent->rowCount(); j++) {
  272. ui->room_list->setFirstColumnSpanned(j, proxy->index(i, 0), true);
  273. }
  274. }
  275. ui->room_list->sortByColumn(Column::GAME_NAME, Qt::AscendingOrder);
  276. }
  277. std::string Lobby::GetProfileUsername() {
  278. const auto& current_user =
  279. system.GetProfileManager().GetUser(Settings::values.current_user.GetValue());
  280. Service::Account::ProfileBase profile{};
  281. if (!current_user.has_value()) {
  282. return "";
  283. }
  284. if (!system.GetProfileManager().GetProfileBase(*current_user, profile)) {
  285. return "";
  286. }
  287. const auto text = Common::StringFromFixedZeroTerminatedBuffer(
  288. reinterpret_cast<const char*>(profile.username.data()), profile.username.size());
  289. return text;
  290. }
  291. LobbyFilterProxyModel::LobbyFilterProxyModel(QWidget* parent, QStandardItemModel* list)
  292. : QSortFilterProxyModel(parent), game_list(list) {}
  293. void LobbyFilterProxyModel::UpdateGameList(QStandardItemModel* list) {
  294. game_list = list;
  295. }
  296. bool LobbyFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const {
  297. // Prioritize filters by fastest to compute
  298. // pass over any child rows (aka row that shows the players in the room)
  299. if (sourceParent != QModelIndex()) {
  300. return true;
  301. }
  302. // filter by empty rooms
  303. if (filter_empty) {
  304. QModelIndex member_list = sourceModel()->index(sourceRow, Column::MEMBER, sourceParent);
  305. int player_count =
  306. sourceModel()->data(member_list, LobbyItemMemberList::MemberListRole).toList().size();
  307. if (player_count == 0) {
  308. return false;
  309. }
  310. }
  311. // filter by filled rooms
  312. if (filter_full) {
  313. QModelIndex member_list = sourceModel()->index(sourceRow, Column::MEMBER, sourceParent);
  314. int player_count =
  315. sourceModel()->data(member_list, LobbyItemMemberList::MemberListRole).toList().size();
  316. int max_players =
  317. sourceModel()->data(member_list, LobbyItemMemberList::MaxPlayerRole).toInt();
  318. if (player_count >= max_players) {
  319. return false;
  320. }
  321. }
  322. // filter by search parameters
  323. if (!filter_search.isEmpty()) {
  324. QModelIndex game_name = sourceModel()->index(sourceRow, Column::GAME_NAME, sourceParent);
  325. QModelIndex room_name = sourceModel()->index(sourceRow, Column::ROOM_NAME, sourceParent);
  326. QModelIndex host_name = sourceModel()->index(sourceRow, Column::HOST, sourceParent);
  327. bool preferred_game_match = sourceModel()
  328. ->data(game_name, LobbyItemGame::GameNameRole)
  329. .toString()
  330. .contains(filter_search, filterCaseSensitivity());
  331. bool room_name_match = sourceModel()
  332. ->data(room_name, LobbyItemName::NameRole)
  333. .toString()
  334. .contains(filter_search, filterCaseSensitivity());
  335. bool username_match = sourceModel()
  336. ->data(host_name, LobbyItemHost::HostUsernameRole)
  337. .toString()
  338. .contains(filter_search, filterCaseSensitivity());
  339. if (!preferred_game_match && !room_name_match && !username_match) {
  340. return false;
  341. }
  342. }
  343. // filter by game owned
  344. if (filter_owned) {
  345. QModelIndex game_name = sourceModel()->index(sourceRow, Column::GAME_NAME, sourceParent);
  346. QList<QModelIndex> owned_games;
  347. for (int r = 0; r < game_list->rowCount(); ++r) {
  348. owned_games.append(QModelIndex(game_list->index(r, 0)));
  349. }
  350. auto current_id = sourceModel()->data(game_name, LobbyItemGame::TitleIDRole).toLongLong();
  351. if (current_id == 0) {
  352. // TODO(jroweboy): homebrew often doesn't have a game id and this hides them
  353. return false;
  354. }
  355. bool owned = false;
  356. for (const auto& game : owned_games) {
  357. auto game_id = game_list->data(game, GameListItemPath::ProgramIdRole).toLongLong();
  358. if (current_id == game_id) {
  359. owned = true;
  360. }
  361. }
  362. if (!owned) {
  363. return false;
  364. }
  365. }
  366. return true;
  367. }
  368. void LobbyFilterProxyModel::sort(int column, Qt::SortOrder order) {
  369. sourceModel()->sort(column, order);
  370. }
  371. void LobbyFilterProxyModel::SetFilterOwned(bool filter) {
  372. filter_owned = filter;
  373. invalidate();
  374. }
  375. void LobbyFilterProxyModel::SetFilterEmpty(bool filter) {
  376. filter_empty = filter;
  377. invalidate();
  378. }
  379. void LobbyFilterProxyModel::SetFilterFull(bool filter) {
  380. filter_full = filter;
  381. invalidate();
  382. }
  383. void LobbyFilterProxyModel::SetFilterSearch(const QString& filter) {
  384. filter_search = filter;
  385. invalidate();
  386. }