lobby.cpp 15 KB

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