lobby.cpp 17 KB

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