File: network_connection_menu.cpp

package info (click to toggle)
warmux 1%3A11.04.1%2Brepack2-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster, sid
  • size: 126,388 kB
  • sloc: cpp: 186,040; xml: 8,909; sh: 3,358; makefile: 1,052; ansic: 713
file content (621 lines) | stat: -rw-r--r-- 19,627 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
/******************************************************************************
 *  Warmux is a convivial mass murder game.
 *  Copyright (C) 2001-2011 Warmux Team.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 ******************************************************************************
 * Network connection menu: this menu allows the user to choose between
 * hosting a game or connecting to a server.
 *****************************************************************************/
#include "game/config.h"
#include "graphic/video.h"
#include "gui/button.h"
#include "gui/box.h"
#include "gui/vertical_box.h"
#include "gui/check_box.h"
#include "gui/msg_box.h"
#include "gui/null_widget.h"
#include "gui/picture_widget.h"
#include "gui/select_box.h"
#include "gui/tabs.h"
#include "gui/text_box.h"
#include "include/app.h"
#include "include/constant.h"
#include "network/net_error_msg.h"
#include "menu/network_connection_menu.h"
#include "menu/network_menu.h"
#include "team/teams_list.h"
#include "tool/resource_manager.h"
#include "tool/string_tools.h"

class GameInfoBox : public HBox
{
public:
  bool password;
  std::string port, ip_address;
  GameInfoBox(uint width, bool pwd, const std::string& ip,
              const std::string& port, const std::string& name)
    : HBox(width, false, false, false)
    , password(pwd)
    , port(port)
    , ip_address(ip)
  {
    if (pwd) {
      AddWidget(new PictureWidget(Point2i(16, 16), "menu/password_lock",
                                  PictureWidget::FIT_SCALING));
    } else {
      AddWidget(new NullWidget(Point2i(16, 16)));
    }
    width -= 20;
    AddWidget(new Label(ip, 0.3f*width));
    AddWidget(new Label(port, 0.2f*width));
    AddWidget(new Label(name, 0.5f*width));
    SetNoBorder();
    Pack();
  }
};

class GameListBox : public SelectBox
{
public:
  GameListBox(const Point2i &size) : SelectBox(size, false) { }
  void Select(uint index) { SelectBox::Select(index); }
  void AddItem(bool selected, bool pwd, const std::string& ip_address,
               const std::string& port, const std::string& name)
  {
    AddWidgetItem(selected, new GameInfoBox(size.x-10, pwd, ip_address, port, name));
  }
  const std::string& GetAddress() { return ((GameInfoBox*)GetSelectedWidget())->ip_address; }
  const std::string& GetPort() { return ((GameInfoBox*)GetSelectedWidget())->port; }
};

struct shared_net_info {
  SDL_Thread* thread_refresh;
  SDL_sem* lock;
  std::list<GameServerInfo> lst_games;
  connection_state_t index_conn_state;
  bool todisplay;
  bool finished;
} net_info;

static void InitNetInfo()
{
  net_info.thread_refresh = NULL;
  net_info.index_conn_state = CONNECTED;
  net_info.lock = SDL_CreateSemaphore(1);
  net_info.todisplay = false;
  net_info.finished = true;
}

static void CleanNetInfo()
{
  SDL_SemWait(net_info.lock);
  SDL_DestroySemaphore(net_info.lock);
  int status;
  if (net_info.thread_refresh)
    SDL_WaitThread(net_info.thread_refresh, &status);
  net_info.thread_refresh = NULL;
  net_info.finished = true;
  net_info.lst_games.clear();
}

static int RefreshNetInfo(void *)
{
  MSG_DEBUG("network.refresh_games_list", "Begin");

  // Connect to the index server
  connection_state_t conn = IndexServer::GetInstance()->Connect(Constants::WARMUX_VERSION);
  if (conn != CONNECTED) {
    SDL_SemWait(net_info.lock);
    net_info.index_conn_state = conn;
    net_info.finished = true;
    SDL_SemPost(net_info.lock);
    return -1;
  }

  std::list<GameServerInfo> lst = IndexServer::GetInstance()->GetHostList(false);
  IndexServer::GetInstance()->Disconnect();

  SDL_SemWait(net_info.lock);
  net_info.lst_games = lst;
  net_info.todisplay = true;
  net_info.finished = true;
  SDL_SemPost(net_info.lock);

  // make sure the list will be updated right now
  Menu::WakeUpOnCallback();

  MSG_DEBUG("network.refresh_games_list", "End");
  return 0;
}

#define TAB_MANUAL_ID   "TAB_manual"
#define TAB_CLIENT_ID   "TAB_client"
#define TAB_SERVER_ID   "TAB_server"

NetworkConnectionMenu::NetworkConnectionMenu(network_menu_action_t action) :
  Menu("menu/bg_network", vOkCancel)
{
  Profile *res = GetResourceManager().LoadXMLProfile("graphism.xml",false);

  uint max_width = 0.95f*GetMainWindow().GetWidth();
  uint offset    = (GetMainWindow().GetWidth() - max_width)/2;
  uint width     = max_width - 10;

  /* Tabs */
  tabs = new MultiTabs(Point2i(max_width,
                               GetMainWindow().GetHeight()-140));
  tabs->SetPosition(offset, offset);

  // #############################
  /* client connection related widgets */
  Box * cl_connection_box = new VBox(W_UNDEF, false, false, false);
  cl_connection_box->SetNoBorder();
  tabs->AddNewTab(TAB_CLIENT_ID, _("Connect to game"), cl_connection_box);

  // Public battles
  Box * cl_tmp_box = new HBox(W_UNDEF, false, false, false);
  cl_tmp_box->SetMargin(0);
  cl_tmp_box->SetNoBorder();

  cl_refresh_net_games = new Button(res, "menu/refresh_small", false);
  cl_tmp_box->AddWidget(cl_refresh_net_games);
  refresh_net_games_label = new Label(_("Public battles"), width - cl_refresh_net_games->GetSizeX(),
                                      Font::FONT_MEDIUM, Font::FONT_BOLD, c_red,
                                      Text::ALIGN_LEFT_TOP, true);
  cl_tmp_box->AddWidget(refresh_net_games_label);
  cl_connection_box->AddWidget(cl_tmp_box);

  cl_net_games_lst = new GameListBox(Point2i(width, 30));
  cl_connection_box->AddWidget(cl_net_games_lst);

  // Server password
  cl_tmp_box = new HBox(W_UNDEF, false, false, false);
  cl_tmp_box->SetMargin(0);
  cl_tmp_box->SetNoBorder();

  cl_tmp_box->AddWidget(new Label(_("Password:"), width/4));
  cl_net_server_pwd = new PasswordBox("", (3*width)/4);
  cl_tmp_box->AddWidget(cl_net_server_pwd);

  cl_connection_box->AddWidget(cl_tmp_box);

  // #############################
  // Manual connection
  Box *manual_connection_box;
  if (GetMainWindow().GetHeight() < 480) {
    manual_connection_box = new VBox(W_UNDEF, false, false, false);
    manual_connection_box->SetNoBorder();
    tabs->AddNewTab(TAB_MANUAL_ID, _("Manual connection"), manual_connection_box);
  } else {
    cl_connection_box->AddWidget(new Label(_("Manual connection"), width,
                                           Font::FONT_MEDIUM, Font::FONT_BOLD, c_red,
                                           Text::ALIGN_LEFT_TOP, true));
    manual_connection_box = cl_connection_box;
  }

  // Server address
  cl_tmp_box = new HBox(W_UNDEF, false, false, false);
  cl_tmp_box->SetMargin(0);
  cl_tmp_box->SetNoBorder();

  cl_tmp_box->AddWidget(new Label(_("Server address:"), width/4));
  cl_server_address = new TextBox(Config::GetInstance()->GetNetworkClientHost(), (3*width)/4);
  cl_tmp_box->AddWidget(cl_server_address);

  manual_connection_box->AddWidget(cl_tmp_box);

  // Server port
  cl_tmp_box = new HBox(W_UNDEF, false, false, false);
  cl_tmp_box->SetMargin(0);
  cl_tmp_box->SetNoBorder();

  cl_tmp_box->AddWidget(new Label(_("Port:"), width/4));
  cl_port_number = new TextBox(Config::GetInstance()->GetNetworkClientPort(), (3*width)/4);
  cl_tmp_box->AddWidget(cl_port_number);

  manual_connection_box->AddWidget(cl_tmp_box);

  // Server password
  cl_tmp_box = new HBox(W_UNDEF, false, false, false);
  cl_tmp_box->SetMargin(0);
  cl_tmp_box->SetNoBorder();

  cl_tmp_box->AddWidget(new Label(_("Password:"), width/4));
  cl_server_pwd = new PasswordBox("", (3*width)/4);
  cl_tmp_box->AddWidget(cl_server_pwd);

  manual_connection_box->AddWidget(cl_tmp_box);

  // #############################
  /* server connection related widgets */
  Box * srv_connection_box = new VBox(W_UNDEF, false, false, false);
  srv_connection_box->SetNoBorder();

  // Server port
  Box * srv_tmp_box = new HBox(W_UNDEF, false, false, false);
  srv_tmp_box->SetMargin(0);
  srv_tmp_box->SetNoBorder();

  srv_tmp_box->AddWidget(new Label(_("Port:"), width/4));
  srv_port_number = new TextBox(Config::GetInstance()->GetNetworkServerPort(), (3*width)/4);
  srv_tmp_box->AddWidget(srv_port_number);

  srv_connection_box->AddWidget(srv_tmp_box);

  // Game name
  srv_tmp_box = new HBox(W_UNDEF, false, false, false);
  srv_tmp_box->SetMargin(0);
  srv_tmp_box->SetNoBorder();

  srv_tmp_box->AddWidget(new Label(_("Game name:"), width/4));
  srv_game_name = new TextBox(Config::GetInstance()->GetNetworkServerGameName(), (3*width)/4);
  srv_game_name->SetMaxNbChars(15);
  srv_tmp_box->AddWidget(srv_game_name);

  srv_connection_box->AddWidget(srv_tmp_box);

  // Server password
  srv_tmp_box = new HBox(W_UNDEF, false, false, false);
  srv_tmp_box->SetMargin(0);
  srv_tmp_box->SetNoBorder();

  srv_tmp_box->AddWidget(new Label(_("Password:"), width/4));
  srv_game_pwd = new PasswordBox("", (3*width)/4);
  srv_game_pwd->SetMaxNbChars(15);
  srv_tmp_box->AddWidget(srv_game_pwd);

  srv_connection_box->AddWidget(srv_tmp_box);

  // Available on internet ?
  srv_internet_server = new CheckBox(_("Server available on Internet"), width,
                                     Config::GetInstance()->GetNetworkServerPublic());
  srv_connection_box->AddWidget(srv_internet_server);

  tabs->AddNewTab(TAB_SERVER_ID, _("Host a game"), srv_connection_box);

  // #############################
  widgets.AddWidget(tabs);
  widgets.Pack();

  // Optimize height of public net games table
  uint net_games_lst_width = tabs->GetSizeX() - 2*(cl_connection_box->GetPositionX()-tabs->GetPositionX());
  uint net_games_lst_height = cl_net_games_lst->GetSizeY() +
    (tabs->GetPositionY() + tabs->GetSizeY()) -
    (cl_connection_box->GetPositionY() + cl_connection_box->GetSizeY()) - 10;
  cl_net_games_lst->SetSize(net_games_lst_width, net_games_lst_height);

  // Warning about experimental networking
  Point2i msg_box_pos(offset, tabs->GetPositionY() + tabs->GetSizeY() + 10);
  Point2i msg_box_size(max_width,
                       GetMainWindow().GetHeight() - 50 - msg_box_pos.y);

  msg_box = new MsgBox(msg_box_size, Font::FONT_SMALL, Font::FONT_BOLD);
  msg_box->SetPosition(msg_box_pos);

  widgets.AddWidget(msg_box);
  widgets.Pack();

  msg_box->NewMessage(_("Have a good game!"));
  msg_box->NewMessage(""); // Skip a line

  //Double click
  m_last_click_on_games_lst = 0;
  m_Double_click_interval = 400;
  // ************************************************************************
  InitNetInfo();

  switch (action) {
  case NET_HOST:
    tabs->SelectTab(1);
    break;
  case NET_CONNECT:
    tabs->SelectTab(0);
    break;
  default:
    ThreadRefreshList();
    break;
  }
}

NetworkConnectionMenu::~NetworkConnectionMenu()
{
  CleanNetInfo();
}

void NetworkConnectionMenu::OnClickUp(const Point2i &mousePosition, int button)
{
  Widget* w = widgets.ClickUp(mousePosition, button);

  if (w == cl_refresh_net_games || w == refresh_net_games_label)
    ThreadRefreshList();

  if (w == cl_server_address || w == cl_port_number || w == cl_server_pwd)
    cl_net_games_lst->Deselect();

  //Hack to handle Double click
  if (w == cl_net_games_lst)
  {
    if (m_last_click_on_games_lst + m_Double_click_interval > SDL_GetTicks()) {
      if (cl_net_games_lst->GetSelectedItem() == -1) {
        cl_net_games_lst->Select(cl_net_games_lst->MouseIsOnWhichItem(mousePosition));
      }
      signal_ok();
    }
    else
    {
      m_last_click_on_games_lst = SDL_GetTicks();
    }
  }
}

void NetworkConnectionMenu::__RefreshList()
{
  SDL_SemWait(net_info.lock);
  if (!net_info.todisplay) {
    SDL_SemPost(net_info.lock);
    return;
  }

  net_info.todisplay = false;

  // Save the currently selected address
  int current = cl_net_games_lst->GetSelectedItem();
  if (current == -1)
    current = 0;

  // Empty the list:
  cl_net_games_lst->Clear();

  if (net_info.index_conn_state != CONNECTED) {
    DisplayNetError(net_info.index_conn_state);
    SDL_SemPost(net_info.lock);
    msg_box->NewMessage(_("Error: Unable to contact the index server to search for an internet game"), c_red);
    return;
  }

  if (net_info.lst_games.empty()) {
      Menu::DisplayError(_("Sorry, currently, no game is waiting for players"));
      SDL_SemPost(net_info.lock);
      return;
  }

  for (std::list<GameServerInfo>::iterator it = net_info.lst_games.begin();
       it != net_info.lst_games.end(); ++it) {
    cl_net_games_lst->AddItem(false, it->passworded, it->ip_address,
                              it->port, it->game_name);
  }
  SDL_SemPost(net_info.lock);

  if (cl_net_games_lst->Size()) {
    if (current+1 > cl_net_games_lst->Size()) {
      current = 0;
    }
    cl_net_games_lst->Select(current);
  }

  cl_net_games_lst->Pack();
}

void NetworkConnectionMenu::ThreadRefreshList()
{
  SDL_SemWait(net_info.lock);

  if (net_info.thread_refresh != NULL) {
    // Check if the thread finished
    if (net_info.finished) {
      int status;
      SDL_WaitThread(net_info.thread_refresh, &status);
    } else {
      MSG_DEBUG("network.refresh_games_list", "A thread is already running");
      SDL_SemPost(net_info.lock);
      return;
    }
  }
  SDL_SemPost(net_info.lock);

  net_info.finished = false;
  net_info.thread_refresh = SDL_CreateThread(RefreshNetInfo, NULL);
}

void NetworkConnectionMenu::HandleEvent(const SDL_Event& evnt)
{
  __RefreshList();
  Menu::HandleEvent(evnt);
}

void NetworkConnectionMenu::DisplayNetError(connection_state_t conn)
{
  std::string error_msg;

  if (conn == CONN_WRONG_VERSION) {
    error_msg = Format(_("Sorry, your version is not supported anymore. "
                         "Supported versions are %s. "
                         "You can download an updated version "
                         "from http://www.warmux.org/wiki/download.php"),
                       IndexServer::GetInstance()->GetSupportedVersions().c_str());
  } else {
    error_msg = NetworkErrorToString(conn);
  }

  Menu::DisplayError(error_msg);
}

bool NetworkConnectionMenu::HostingServer(const std::string& port,
                                          const std::string& game_name,
                                          const std::string& password,
                                          bool internet)
{
  bool r = false;
  int net_port;
  connection_state_t conn;

  if (!internet)
    IndexServer::GetInstance()->SetHiddenServer();

  if (internet) {
    SDL_SemWait(net_info.lock);

    conn = IndexServer::GetInstance()->Connect(Constants::WARMUX_VERSION);
    if (conn != CONNECTED) {
      DisplayNetError(conn);
      msg_box->NewMessage(_("Error: Unable to contact the index server to host a game"), c_red);
      goto out;
    }
  }

  conn = Network::ServerStart(port, game_name, password);
  if (conn != CONNECTED) {
    DisplayNetError(conn);
    goto out;
  }

  r = str2int(port, net_port);
  if (false == r) {
    DisplayNetError(CONN_BAD_PORT);
    goto out;
  }

  if (internet) {
    r = IndexServer::GetInstance()->SendServerStatus(game_name, password != "", net_port);
    if (false == r) {
      DisplayNetError(CONN_BAD_PORT);
      msg_box->NewMessage(Format(_("Error: Your server is not reachable from the internet. Check your firewall configuration: TCP Port %s must accept connections from the outside. If you are not directly connected to the internet, check your router configuration: TCP Port %s must be forwarded on your computer."), port.c_str(), port.c_str()),
                          c_red);
      goto out;
    }
  }

  if (!Network::GetInstance()->IsConnected()) {
    msg_box->NewMessage(_("Error: Unable to start the server"), c_red);
    goto out;
  }
  r = true;

 out:
  if (internet)
    SDL_SemPost(net_info.lock);
  return r;
}

bool NetworkConnectionMenu::ConnectToClient(const std::string& srv_address,
                                            const std::string& port,
                                            const std::string& passwd)
{
  bool r = true;

  connection_state_t conn = Network::ClientStart(srv_address, port, passwd);
  if (!Network::IsConnected() || conn != CONNECTED) {
    DisplayNetError(conn);

    // translators: %s:%s will expand to something like "example.org:9999"
    msg_box->NewMessage(Format(_("Error: Unable to connect to %s:%s"),
                               srv_address.c_str(), port.c_str()), c_red);
    r = false;
  }
  return r;
}

bool NetworkConnectionMenu::signal_ok()
{
  bool r = false;
  std::list<GameServerInfo> lst;

  // Hack: force loading of teams before creating threads.
  GetTeamsList();

  // Which tab is displayed ?
  std::string id = tabs->GetCurrentTabId();

  if (id == TAB_SERVER_ID) {
    // Hosting your own server
    r = HostingServer(srv_port_number->GetText(),
                      srv_game_name->GetText(),
                      srv_game_pwd->GetPassword(),
                      srv_internet_server->GetValue());
    if (!r)
      goto out;

    // Remember the parameters
    Config::GetInstance()->SetNetworkServerPort(srv_port_number->GetText());
    Config::GetInstance()->SetNetworkServerGameName(srv_game_name->GetText());
    Config::GetInstance()->SetNetworkServerPublic(srv_internet_server->GetValue());

  } else if (id == TAB_CLIENT_ID) { // Direct connexion to a server

    if (cl_net_games_lst->GetSelectedItem() != -1) {
      // Connect to an internet game!
      r = ConnectToClient(cl_net_games_lst->GetAddress(),
                          cl_net_games_lst->GetPort(),
                          cl_net_server_pwd->GetPassword());
      if (!r)
        goto out;

    } else if (!cl_server_address->GetText().empty()) {
      r = ConnectToClient(cl_server_address->GetText(),
                          cl_port_number->GetText(),
                          cl_server_pwd->GetPassword());
      if (!r)
        goto out;

      // Remember the parameters
      Config::GetInstance()->SetNetworkClientHost(cl_server_address->GetText());
      Config::GetInstance()->SetNetworkClientPort(cl_port_number->GetText());
    } else
      goto out;
  } else if (id == TAB_MANUAL_ID) {
    if (!cl_server_address->GetText().empty()) {
      r = ConnectToClient(cl_server_address->GetText(),
                          cl_port_number->GetText(),
                          cl_server_pwd->GetPassword());
      if (!r)
        goto out;

      // Remember the parameters
      Config::GetInstance()->SetNetworkClientHost(cl_server_address->GetText());
      Config::GetInstance()->SetNetworkClientPort(cl_port_number->GetText());
    }
  }

  if (Network::IsConnected()) {
    play_ok_sound();

    // run the network menu ! :-)
    NetworkMenu nm;
    Network::GetInstance()->network_menu = &nm;
    nm.Run();
    Network::GetInstance()->network_menu = NULL;
    IndexServer::GetInstance()->Disconnect();

    Network::Disconnect();

    // Don't go back to main menu after playing
    Menu::RedrawMenu();
    ThreadRefreshList();

    return false;
  }

 out:
  Network::Disconnect();
  return r;
}

bool NetworkConnectionMenu::signal_cancel()
{
  IndexServer::GetInstance()->Disconnect();
  Network::Disconnect();
  return true;
}