The Battle for Wesnoth  1.19.0-dev
match_history.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2021 - 2024
3  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
4 
5  This program is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9  This program is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY.
11 
12  See the COPYING file for more details.
13 */
14 
16 
17 #include "desktop/open.hpp"
18 #include "formula/string_utils.hpp"
20 #include "gettext.hpp"
21 #include "filesystem.hpp"
23 #include "gui/dialogs/message.hpp"
24 #include "gui/widgets/button.hpp"
25 #include "gui/widgets/label.hpp"
26 #include "gui/widgets/listbox.hpp"
28 #include "gui/widgets/text_box.hpp"
29 #include "gui/widgets/window.hpp"
32 #include "wesnothd_connection.hpp"
33 
34 using namespace std::chrono_literals;
35 
36 static lg::log_domain log_network("network");
37 #define DBG_NW LOG_STREAM(debug, log_network)
38 #define ERR_NW LOG_STREAM(err, log_network)
39 
40 namespace gui2::dialogs
41 {
42 REGISTER_DIALOG(mp_match_history)
43 
44 mp_match_history::mp_match_history(const std::string& player_name, wesnothd_connection& connection, bool wait_for_response)
45  : modal_dialog(window_id())
46  , player_name_(player_name)
47  , connection_(connection)
48  , offset_(0)
49  , wait_for_response_(wait_for_response)
50 {
51  register_label("title", true, VGETTEXT("Match History — $player", {{"player", player_name_}}));
52 }
53 
54 void mp_match_history::pre_show(window& win)
55 {
56  win.set_enter_disabled(true);
57 
58  button& newer_history = find_widget<button>(&win, "newer_history", false);
59  button& older_history = find_widget<button>(&win, "older_history", false);
60  connect_signal_mouse_left_click(newer_history, std::bind(&mp_match_history::newer_history_offset, this));
61  connect_signal_mouse_left_click(older_history, std::bind(&mp_match_history::older_history_offset, this));
62 
63  button& search = find_widget<button>(&win, "search", false);
64  connect_signal_mouse_left_click(search, std::bind(&mp_match_history::new_search, this));
65 
66  text_box& search_player = find_widget<text_box>(&win, "search_player", false);
67  search_player.set_value(player_name_);
68 
69  std::vector<config> content_types;
70  content_types.emplace_back("label", _("Scenario"));
71  content_types.emplace_back("label", _("Era"));
72  content_types.emplace_back("label", _("Modification"));
73 
74  find_widget<menu_button>(&win, "search_content_type", false).set_values(content_types);
75 
76  update_display();
77 }
78 
79 void mp_match_history::new_search()
80 {
81  int old_offset = offset_;
82  std::string old_player_name = player_name_;
83  text_box& search_player = find_widget<text_box>(get_window(), "search_player", false);
84  player_name_ = search_player.get_value();
85 
86  // display update failed, set the offset back to what it was before
87  if(!update_display()) {
88  offset_ = old_offset;
89  player_name_ = old_player_name;
90  } else {
91  label& title = find_widget<label>(get_window(), "title", false);
92  title.set_label(VGETTEXT("Match History — $player", {{"player", player_name_}}));
93  }
94 }
95 
96 void mp_match_history::newer_history_offset()
97 {
98  offset_ -= 10;
99  // display update failed, set the offset back to what it was before
100  if(!update_display()) {
101  offset_ += 10;
102  }
103 }
104 
105 void mp_match_history::older_history_offset()
106 {
107  offset_ += 10;
108  // display update failed, set the offset back to what it was before
109  if(!update_display()) {
110  offset_ -= 10;
111  }
112 }
113 
114 namespace
115 {
116 std::string key_with_fallback(const config::attribute_value& val)
117 {
118  // Note that using the fallback arg of str() doesn't work since the value is set,
119  // it's just set as an empty string, and the fallback is only returned if the value
120  // is actually unset.
121  if(std::string s = val.str(); !s.empty()) {
122  return s;
123  } else {
124  return font::unicode_em_dash;
125  }
126 }
127 };
128 
129 bool mp_match_history::update_display()
130 {
131  const config history = request_history();
132 
133  // request failed, nothing to do
134  if(history.child_count("game_history_results") == 0) {
135  return false;
136  }
137 
138  listbox* history_box = find_widget<listbox>(get_window(), "history", false, true);
139  history_box->clear();
140 
141  listbox* tab_bar = find_widget<listbox>(get_window(), "tab_bar", false, true);
142  connect_signal_notify_modified(*tab_bar, std::bind(&mp_match_history::tab_switch_callback, this));
143 
144  int i = 0;
145  for(const config& game : history.mandatory_child("game_history_results").child_range("game_history_result")) {
146  widget_data row;
147  grid& history_grid = history_box->add_row(row);
148 
149  dynamic_cast<label*>(history_grid.find("game_name", false))->set_label(key_with_fallback(game["game_name"]));
150  dynamic_cast<label*>(history_grid.find("scenario_name", false))->set_label(key_with_fallback(game["scenario_name"]));
151  dynamic_cast<label*>(history_grid.find("era_name", false))->set_label("<span color='#baac7d'>" + _("Era: ") + "</span>" + key_with_fallback(game["era_name"]));
152  dynamic_cast<label*>(history_grid.find("game_start", false))->set_label(key_with_fallback(game["game_start"]) + _(" UTC+0"));
153  dynamic_cast<label*>(history_grid.find("version", false))->set_label(key_with_fallback(game["version"]));
154 
155  button* replay_download = dynamic_cast<button*>(history_grid.find("replay_download", false));
156  std::string replay_url = game["replay_url"].str();
157  if(!replay_url.empty()) {
158  std::string filename = utils::split(replay_url, '/').back();
159  std::string local_save = filesystem::get_saves_dir()+"/"+filename;
160 
161  connect_signal_mouse_left_click(*replay_download, std::bind(&network::download, replay_url, local_save));
162  } else {
163  replay_download->set_active(false);
164  }
165 
166  std::vector<std::string> player_list;
167  std::vector<std::string> player_faction_list;
168  for(const config& player : game.child_range("player")) {
169  player_list.emplace_back(font::unicode_bullet + " " + player["name"].str() + ":");
170  player_faction_list.emplace_back(player["faction"].str());
171  }
172 
173  label* players = dynamic_cast<label*>(history_grid.find("players", false));
174  players->set_label(utils::join(player_list, "\n"));
175 
176  label* factions = dynamic_cast<label*>(history_grid.find("player_factions", false));
177  factions->set_label(utils::join(player_faction_list, "\n"));
178 
179  history_grid.find("player_grid", false)->set_visible(gui2::widget::visibility::invisible);
180 
181  label* modifications = dynamic_cast<label*>(history_grid.find("modifications", false));
182  const auto& children = game.child_range("modification");
183  if(!children.empty()) {
184  std::vector<std::string> modifications_list;
185 
186  for(const config& modification : game.child_range("modification")) {
187  modifications_list.emplace_back(font::unicode_bullet + " " + modification["name"].str());
188  }
189 
190  modifications->set_label(utils::join(modifications_list, "\n"));
191  }
193 
194  i++;
195  if(i == 10) {
196  break;
197  }
198  }
199 
200  // this is already the most recent history, can't get anything newer
201  if(offset_ == 0) {
202  button* newer_history = find_widget<button>(get_window(), "newer_history", false, true);
203  newer_history->set_active(false);
204  } else {
205  button* newer_history = find_widget<button>(get_window(), "newer_history", false, true);
206  newer_history->set_active(true);
207  }
208 
209  // the server returns up to 11 and the client displays at most 10
210  // if fewer than 11 rows are returned, then there are no older rows left to get next
211  if(history.child_count("game_history_result") < 11) {
212  button* older_history = find_widget<button>(get_window(), "older_history", false, true);
213  older_history->set_active(false);
214  } else {
215  button* older_history = find_widget<button>(get_window(), "older_history", false, true);
216  older_history->set_active(true);
217  }
218 
219  return true;
220 }
221 
222 const config mp_match_history::request_history()
223 {
224  config request;
225  config& child = request.add_child("game_history_request");
226  child["offset"] = offset_;
227  child["search_player"] = player_name_;
228  child["search_game_name"] = find_widget<text_box>(get_window(), "search_game_name", false).get_value();
229  child["search_content_type"] = find_widget<menu_button>(get_window(), "search_content_type", false).get_value();
230  child["search_content"] = find_widget<text_box>(get_window(), "search_content", false).get_value();
231  DBG_NW << request.debug();
232  connection_.send_data(request);
233 
234  int times_waited = 0;
235  while(true) {
236  config response;
237 
238  // I'm not really sure why this works to be honest
239  // I would've expected that there would be a risk of regular lobby responses showing up here since it's a reference to the lobby's network connection
240  // however testing has resulted in showing that this is not the case
241  // lobby responses are received in the lobby's network_handler() method when this method is not running
242  // lobby responses are not received while this method is running, and are handled in the lobby after it completes
243  // history results are never received in the lobby
244  if(connection_.receive_data(response)) {
245  if(response.child_count("game_history_results") == 0) {
246  DBG_NW << "Received non-history data: " << response.debug();
247  if(!response["error"].str().empty()) {
248  ERR_NW << "Received error from server: " << response["error"].str();
249  gui2::show_error_message(_("The server responded with an error:")+" "+response["error"].str());
250  return {};
251  }
252  } else if(response.mandatory_child("game_history_results").child_count("game_history_result") == 0) {
253  DBG_NW << "Player has no game history data.";
254  gui2::show_error_message(_("No game history found."));
255  return {};
256  } else {
257  DBG_NW << "Received history data: " << response.debug();
258  return response;
259  }
260  } else {
261  DBG_NW << "Received no data";
262  }
263 
264  if(times_waited > 20 || !wait_for_response_) {
265  ERR_NW << "Timed out waiting for history data, returning nothing";
266  if(wait_for_response_) {
267  gui2::show_error_message(_("Request timed out."));
268  }
269  return {};
270  }
271 
272  times_waited++;
273  std::this_thread::sleep_for(250ms);
274  }
275 
276  DBG_NW << "Something else happened while waiting for history data, returning nothing";
277  gui2::show_error_message(_("Request encountered an unexpected error, please check the logs."));
278  return {};
279 }
280 
281 void mp_match_history::tab_switch_callback()
282 {
283  listbox* history_box = find_widget<listbox>(get_window(), "history", false, true);
284  listbox* tab_bar = find_widget<listbox>(get_window(), "tab_bar", false, true);
285  int tab = tab_bar->get_selected_row();
286 
287  for(unsigned i = 0; i < history_box->get_item_count(); i++) {
288  grid* history_grid = history_box->get_row_grid(i);
289  if(tab == 0) {
290  history_grid->find("player_grid", false)->set_visible(gui2::widget::visibility::invisible);
291  history_grid->find("modifications", false)->set_visible(gui2::widget::visibility::invisible);
292  } else if(tab == 1) {
293  history_grid->find("player_grid", false)->set_visible(gui2::widget::visibility::visible);
294  history_grid->find("modifications", false)->set_visible(gui2::widget::visibility::invisible);
295  } else if(tab == 2) {
296  history_grid->find("player_grid", false)->set_visible(gui2::widget::visibility::invisible);
297  history_grid->find("modifications", false)->set_visible(gui2::widget::visibility::visible);
298  }
299  }
300 }
301 
302 } // namespace dialogs
Variant for storing WML attributes.
std::string str(const std::string &fallback="") const
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:159
config & mandatory_child(config_key_type key, int n=0)
Returns the nth child with the given key, or throws an error if there is none.
Definition: config.cpp:368
std::size_t child_count(config_key_type key) const
Definition: config.cpp:298
child_itors child_range(config_key_type key)
Definition: config.cpp:274
std::string debug() const
Definition: config.cpp:1245
config & add_child(config_key_type key)
Definition: config.cpp:442
Simple push button.
Definition: button.hpp:36
virtual void set_active(const bool active) override
See styled_widget::set_active.
Definition: button.cpp:64
Abstract base class for all modal dialogs.
Base container class.
Definition: grid.hpp:32
widget * find(const std::string &id, const bool must_be_active) override
See widget::find.
Definition: grid.cpp:645
A label displays text that can be wrapped but no scrollbars are provided.
Definition: label.hpp:56
The listbox class.
Definition: listbox.hpp:43
grid & add_row(const widget_item &item, const int index=-1)
When an item in the list is selected by the user we need to update the state.
Definition: listbox.cpp:59
const grid * get_row_grid(const unsigned row) const
Returns the grid of the wanted row.
Definition: listbox.cpp:230
void clear()
Removes all the rows in the listbox, clearing it.
Definition: listbox.cpp:118
int get_selected_row() const
Returns the first selected row.
Definition: listbox.cpp:268
unsigned get_item_count() const
Returns the number of items in the listbox.
Definition: listbox.cpp:124
virtual void set_label(const t_string &text)
std::string get_value() const
virtual void set_value(const std::string &text)
The set_value is virtual for the password_box class.
Class for a single line text area.
Definition: text_box.hpp:142
void set_visible(const visibility visible)
Definition: widget.cpp:471
@ visible
The user sets the widget visible, that means:
@ invisible
The user set the widget invisible, that means:
base class of top level items, the only item which needs to store the final canvases to draw on.
Definition: window.hpp:67
void set_enter_disabled(const bool enter_disabled)
Disable the enter key.
Definition: window.hpp:331
A class that represents a TCP/IP connection to the wesnothd server.
Declarations for File-IO.
#define VGETTEXT(msgid,...)
Handy wrappers around interpolate_variables_into_string and gettext.
std::size_t i
Definition: function.cpp:968
static std::string _(const char *str)
Definition: gettext.hpp:93
This file contains the window object, this object is a top level container which has the event manage...
#define ERR_NW
static lg::log_domain log_network("network")
#define DBG_NW
#define REGISTER_DIALOG(window_id)
Wrapper for REGISTER_DIALOG2.
std::string get_saves_dir()
const std::string unicode_em_dash
Definition: constants.cpp:44
const std::string unicode_bullet
Definition: constants.cpp:47
void connect_signal_notify_modified(dispatcher &dispatcher, const signal_notification &signal)
Connects a signal handler for getting a notification upon modification.
Definition: dispatcher.cpp:205
void connect_signal_mouse_left_click(dispatcher &dispatcher, const signal &signal)
Connects a signal handler for a left mouse button click.
Definition: dispatcher.cpp:179
std::map< std::string, widget_item > widget_data
Definition: widget.hpp:35
void show_error_message(const std::string &msg, bool message_use_markup)
Shows an error message to the user.
Definition: message.cpp:204
void download(const std::string &url, const std::string &local_path)
Initiates a standalone download of a single file from an HTTPS URL.
const std::vector< std::string > & modifications(bool mp)
Definition: game.cpp:711
std::string join(const T &v, const std::string &s=",")
Generates a new string joining container items in a list.
std::vector< std::string > split(const config_attribute_value &val)
SDL_Window * get_window()
Definition: video.cpp:659
Desktop environment interaction functions.
static map_location::DIRECTION s