network_gui.cpp

Go to the documentation of this file.
00001 /* $Id$ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * OpenTTD 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, version 2.
00006  * OpenTTD 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.
00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
00008  */
00009 
00012 #ifdef ENABLE_NETWORK
00013 #include "../stdafx.h"
00014 #include "../strings_func.h"
00015 #include "../date_func.h"
00016 #include "../fios.h"
00017 #include "network_client.h"
00018 #include "network_gui.h"
00019 #include "network_gamelist.h"
00020 #include "network.h"
00021 #include "network_base.h"
00022 #include "network_content.h"
00023 #include "../gui.h"
00024 #include "network_udp.h"
00025 #include "../window_func.h"
00026 #include "../gfx_func.h"
00027 #include "../widgets/dropdown_func.h"
00028 #include "../querystring_gui.h"
00029 #include "../sortlist_type.h"
00030 #include "../company_func.h"
00031 #include "../core/geometry_func.hpp"
00032 #include "../newgrf_text.h"
00033 #include "../genworld.h"
00034 
00035 #include "../widgets/network_widget.h"
00036 
00037 #include "table/strings.h"
00038 #include "../table/sprites.h"
00039 
00040 
00041 static void ShowNetworkStartServerWindow();
00042 static void ShowNetworkLobbyWindow(NetworkGameList *ngl);
00043 
00044 static const StringID _connection_types_dropdown[] = {
00045   STR_NETWORK_START_SERVER_LAN_INTERNET,
00046   STR_NETWORK_START_SERVER_INTERNET_ADVERTISE,
00047   INVALID_STRING_ID
00048 };
00049 
00050 static const StringID _lan_internet_types_dropdown[] = {
00051   STR_NETWORK_SERVER_LIST_LAN,
00052   STR_NETWORK_SERVER_LIST_INTERNET,
00053   INVALID_STRING_ID
00054 };
00055 
00056 static StringID _language_dropdown[NETLANG_COUNT + 1] = {STR_NULL};
00057 
00058 void SortNetworkLanguages()
00059 {
00060   /* Init the strings */
00061   if (_language_dropdown[0] == STR_NULL) {
00062     for (int i = 0; i < NETLANG_COUNT; i++) _language_dropdown[i] = STR_NETWORK_LANG_ANY + i;
00063     _language_dropdown[NETLANG_COUNT] = INVALID_STRING_ID;
00064   }
00065 
00066   /* Sort the strings (we don't move 'any' and the 'invalid' one) */
00067   QSortT(_language_dropdown + 1, NETLANG_COUNT - 1, &StringIDSorter);
00068 }
00069 
00075 void UpdateNetworkGameWindow(bool unselect)
00076 {
00077   InvalidateWindowData(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_GAME, unselect ? 1 : 0);
00078 }
00079 
00080 typedef GUIList<NetworkGameList*> GUIGameServerList;
00081 typedef uint16 ServerListPosition;
00082 static const ServerListPosition SLP_INVALID = 0xFFFF;
00083 
00085 class NWidgetServerListHeader : public NWidgetContainer {
00086   static const uint MINIMUM_NAME_WIDTH_BEFORE_NEW_HEADER = 150; 
00087   bool visible[6]; 
00088 public:
00089   NWidgetServerListHeader() : NWidgetContainer(NWID_HORIZONTAL)
00090   {
00091     NWidgetLeaf *leaf = new NWidgetLeaf(WWT_PUSHTXTBTN, COLOUR_WHITE, WID_NG_NAME, STR_NETWORK_SERVER_LIST_GAME_NAME, STR_NETWORK_SERVER_LIST_GAME_NAME_TOOLTIP);
00092     leaf->SetResize(1, 0);
00093     leaf->SetFill(1, 0);
00094     this->Add(leaf);
00095 
00096     this->Add(new NWidgetLeaf(WWT_PUSHTXTBTN, COLOUR_WHITE, WID_NG_CLIENTS, STR_NETWORK_SERVER_LIST_CLIENTS_CAPTION, STR_NETWORK_SERVER_LIST_CLIENTS_CAPTION_TOOLTIP));
00097     this->Add(new NWidgetLeaf(WWT_PUSHTXTBTN, COLOUR_WHITE, WID_NG_MAPSIZE, STR_NETWORK_SERVER_LIST_MAP_SIZE_CAPTION, STR_NETWORK_SERVER_LIST_MAP_SIZE_CAPTION_TOOLTIP));
00098     this->Add(new NWidgetLeaf(WWT_PUSHTXTBTN, COLOUR_WHITE, WID_NG_DATE, STR_NETWORK_SERVER_LIST_DATE_CAPTION, STR_NETWORK_SERVER_LIST_DATE_CAPTION_TOOLTIP));
00099     this->Add(new NWidgetLeaf(WWT_PUSHTXTBTN, COLOUR_WHITE, WID_NG_YEARS, STR_NETWORK_SERVER_LIST_YEARS_CAPTION, STR_NETWORK_SERVER_LIST_YEARS_CAPTION_TOOLTIP));
00100 
00101     leaf = new NWidgetLeaf(WWT_PUSHTXTBTN, COLOUR_WHITE, WID_NG_INFO, STR_EMPTY, STR_NETWORK_SERVER_LIST_INFO_ICONS_TOOLTIP);
00102     leaf->SetMinimalSize(40, 12);
00103     leaf->SetFill(0, 1);
00104     this->Add(leaf);
00105 
00106     /* First and last are always visible, the rest is implicitly zeroed */
00107     this->visible[0] = true;
00108     *lastof(this->visible) = true;
00109   }
00110 
00111   void SetupSmallestSize(Window *w, bool init_array)
00112   {
00113     /* Oh yeah, we ought to be findable! */
00114     w->nested_array[WID_NG_HEADER] = this;
00115 
00116     this->smallest_y = 0; // Biggest child.
00117     this->fill_x = 1;
00118     this->fill_y = 0;
00119     this->resize_x = 1; // We only resize in this direction
00120     this->resize_y = 0; // We never resize in this direction
00121 
00122     /* First initialise some variables... */
00123     for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
00124       child_wid->SetupSmallestSize(w, init_array);
00125       this->smallest_y = max(this->smallest_y, child_wid->smallest_y + child_wid->padding_top + child_wid->padding_bottom);
00126     }
00127 
00128     /* ... then in a second pass make sure the 'current' sizes are set. Won't change for most widgets. */
00129     for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
00130       child_wid->current_x = child_wid->smallest_x;
00131       child_wid->current_y = this->smallest_y;
00132     }
00133 
00134     this->smallest_x = this->head->smallest_x + this->tail->smallest_x; // First and last are always shown, rest not
00135   }
00136 
00137   void AssignSizePosition(SizingType sizing, uint x, uint y, uint given_width, uint given_height, bool rtl)
00138   {
00139     assert(given_width >= this->smallest_x && given_height >= this->smallest_y);
00140 
00141     this->pos_x = x;
00142     this->pos_y = y;
00143     this->current_x = given_width;
00144     this->current_y = given_height;
00145 
00146     given_width -= this->tail->smallest_x;
00147     NWidgetBase *child_wid = this->head->next;
00148     /* The first and last widget are always visible, determine which other should be visible */
00149     for (uint i = 1; i < lengthof(this->visible) - 1; i++) {
00150       if (given_width > MINIMUM_NAME_WIDTH_BEFORE_NEW_HEADER + child_wid->smallest_x && this->visible[i - 1]) {
00151         this->visible[i] = true;
00152         given_width -= child_wid->smallest_x;
00153       } else {
00154         this->visible[i] = false;
00155       }
00156       child_wid = child_wid->next;
00157     }
00158 
00159     /* All remaining space goes to the first (name) widget */
00160     this->head->current_x = given_width;
00161 
00162     /* Now assign the widgets to their rightful place */
00163     uint position = 0; // Place to put next child relative to origin of the container.
00164     uint i = rtl ? lengthof(this->visible) - 1 : 0;
00165     child_wid = rtl ? this->tail : this->head;
00166     while (child_wid != NULL) {
00167       if (this->visible[i]) {
00168         child_wid->AssignSizePosition(sizing, x + position, y, child_wid->current_x, this->current_y, rtl);
00169         position += child_wid->current_x;
00170       }
00171 
00172       child_wid = rtl ? child_wid->prev : child_wid->next;
00173       i += rtl ? -1 : 1;
00174     }
00175   }
00176 
00177   /* virtual */ void Draw(const Window *w)
00178   {
00179     int i = 0;
00180     for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
00181       if (!this->visible[i++]) continue;
00182 
00183       child_wid->Draw(w);
00184     }
00185   }
00186 
00187   /* virtual */ NWidgetCore *GetWidgetFromPos(int x, int y)
00188   {
00189     if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return NULL;
00190 
00191     int i = 0;
00192     for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
00193       if (!this->visible[i++]) continue;
00194       NWidgetCore *nwid = child_wid->GetWidgetFromPos(x, y);
00195       if (nwid != NULL) return nwid;
00196     }
00197     return NULL;
00198   }
00199 
00205   bool IsWidgetVisible(NetworkGameWidgets widget) const
00206   {
00207     assert((uint)(widget - WID_NG_NAME) < lengthof(this->visible));
00208     return this->visible[widget - WID_NG_NAME];
00209   }
00210 };
00211 
00212 class NetworkGameWindow : public QueryStringBaseWindow {
00213 protected:
00214   /* Runtime saved values */
00215   static Listing last_sorting;
00216 
00217   /* Constants for sorting servers */
00218   static GUIGameServerList::SortFunction * const sorter_funcs[];
00219 
00220   byte field;                   
00221   NetworkGameList *server;      
00222   NetworkGameList *last_joined; 
00223   GUIGameServerList servers;    
00224   ServerListPosition list_pos;  
00225   Scrollbar *vscroll;
00226 
00231   void BuildNetworkGameList()
00232   {
00233     if (!this->servers.NeedRebuild()) return;
00234 
00235     /* Create temporary array of games to use for listing */
00236     this->servers.Clear();
00237 
00238     for (NetworkGameList *ngl = _network_game_list; ngl != NULL; ngl = ngl->next) {
00239       *this->servers.Append() = ngl;
00240     }
00241 
00242     this->servers.Compact();
00243     this->servers.RebuildDone();
00244     this->vscroll->SetCount(this->servers.Length());
00245   }
00246 
00255   static const char *SkipGarbage(const char *str)
00256   {
00257     while (*str != '\0' && (*str < 'A' || IsInsideMM(*str, '[', '`' + 1) || IsInsideMM(*str, '{', '~' + 1))) str++;
00258     return str;
00259   }
00260 
00262   static int CDECL NGameNameSorter(NetworkGameList * const *a, NetworkGameList * const *b)
00263   {
00264     int r = strnatcmp(SkipGarbage((*a)->info.server_name), SkipGarbage((*b)->info.server_name)); // Sort by name (natural sorting).
00265     return r == 0 ? (*a)->address.CompareTo((*b)->address) : r;
00266   }
00267 
00273   static int CDECL NGameClientSorter(NetworkGameList * const *a, NetworkGameList * const *b)
00274   {
00275     /* Reverse as per default we are interested in most-clients first */
00276     int r = (*a)->info.clients_on - (*b)->info.clients_on;
00277 
00278     if (r == 0) r = (*a)->info.clients_max - (*b)->info.clients_max;
00279     if (r == 0) r = NGameNameSorter(a, b);
00280 
00281     return r;
00282   }
00283 
00285   static int CDECL NGameMapSizeSorter(NetworkGameList * const *a, NetworkGameList * const *b)
00286   {
00287     /* Sort by the area of the map. */
00288     int r = ((*a)->info.map_height) * ((*a)->info.map_width) - ((*b)->info.map_height) * ((*b)->info.map_width);
00289 
00290     if (r == 0) r = (*a)->info.map_width - (*b)->info.map_width;
00291     return (r != 0) ? r : NGameClientSorter(a, b);
00292   }
00293 
00295   static int CDECL NGameDateSorter(NetworkGameList * const *a, NetworkGameList * const *b)
00296   {
00297     int r = (*a)->info.game_date - (*b)->info.game_date;
00298     return (r != 0) ? r : NGameClientSorter(a, b);
00299   }
00300 
00302   static int CDECL NGameYearsSorter(NetworkGameList * const *a, NetworkGameList * const *b)
00303   {
00304     int r = (*a)->info.game_date - (*a)->info.start_date - (*b)->info.game_date + (*b)->info.start_date;
00305     return (r != 0) ? r : NGameDateSorter(a, b);
00306   }
00307 
00312   static int CDECL NGameAllowedSorter(NetworkGameList * const *a, NetworkGameList * const *b)
00313   {
00314     /* The servers we do not know anything about (the ones that did not reply) should be at the bottom) */
00315     int r = StrEmpty((*a)->info.server_revision) - StrEmpty((*b)->info.server_revision);
00316 
00317     /* Reverse default as we are interested in version-compatible clients first */
00318     if (r == 0) r = (*b)->info.version_compatible - (*a)->info.version_compatible;
00319     /* The version-compatible ones are then sorted with NewGRF compatible first, incompatible last */
00320     if (r == 0) r = (*b)->info.compatible - (*a)->info.compatible;
00321     /* Passworded servers should be below unpassworded servers */
00322     if (r == 0) r = (*a)->info.use_password - (*b)->info.use_password;
00323     /* Finally sort on the number of clients of the server */
00324     if (r == 0) r = -NGameClientSorter(a, b);
00325 
00326     return r;
00327   }
00328 
00330   void SortNetworkGameList()
00331   {
00332     bool did_sort = this->servers.Sort();
00333     /* In case of 0 or 1 servers there is no sorting, thus this->list_pos
00334      * isn't set to a "sane" value. So, we only take the short way out
00335      * when we did not (re)sort and we have a valid this->list_pos, or
00336      * there are no servers to actually select. */
00337     if (!did_sort && (this->list_pos != SLP_INVALID || this->servers.Length() == 0)) return;
00338 
00339     /* After sorting ngl->sort_list contains the sorted items. Put these back
00340      * into the original list. Basically nothing has changed, we are only
00341      * shuffling the ->next pointers. While iterating, look for the
00342      * currently selected server and set list_pos to its position */
00343     this->list_pos = SLP_INVALID;
00344     _network_game_list = this->servers[0];
00345     NetworkGameList *item = _network_game_list;
00346     if (item == this->server) this->list_pos = 0;
00347     for (uint i = 1; i != this->servers.Length(); i++) {
00348       item->next = this->servers[i];
00349       item = item->next;
00350       if (item == this->server) this->list_pos = i;
00351     }
00352     item->next = NULL;
00353   }
00354 
00361   void DrawServerLine(const NetworkGameList *cur_item, uint y, bool highlight) const
00362   {
00363     const NWidgetBase *nwi_name = this->GetWidget<NWidgetBase>(WID_NG_NAME);
00364     const NWidgetBase *nwi_info = this->GetWidget<NWidgetBase>(WID_NG_INFO);
00365 
00366     /* show highlighted item with a different colour */
00367     if (highlight) GfxFillRect(nwi_name->pos_x + 1, y - 2, nwi_info->pos_x + nwi_info->current_x - 2, y + FONT_HEIGHT_NORMAL - 1, PC_GREY);
00368 
00369     DrawString(nwi_name->pos_x + WD_FRAMERECT_LEFT, nwi_name->pos_x + nwi_name->current_x - WD_FRAMERECT_RIGHT, y, cur_item->info.server_name, TC_BLACK);
00370 
00371     /* only draw details if the server is online */
00372     if (cur_item->online) {
00373       const NWidgetServerListHeader *nwi_header = this->GetWidget<NWidgetServerListHeader>(WID_NG_HEADER);
00374 
00375       if (nwi_header->IsWidgetVisible(WID_NG_CLIENTS)) {
00376         const NWidgetBase *nwi_clients = this->GetWidget<NWidgetBase>(WID_NG_CLIENTS);
00377         SetDParam(0, cur_item->info.clients_on);
00378         SetDParam(1, cur_item->info.clients_max);
00379         SetDParam(2, cur_item->info.companies_on);
00380         SetDParam(3, cur_item->info.companies_max);
00381         DrawString(nwi_clients->pos_x, nwi_clients->pos_x + nwi_clients->current_x - 1, y, STR_NETWORK_SERVER_LIST_GENERAL_ONLINE, TC_FROMSTRING, SA_HOR_CENTER);
00382       }
00383 
00384       if (nwi_header->IsWidgetVisible(WID_NG_MAPSIZE)) {
00385         /* map size */
00386         const NWidgetBase *nwi_mapsize = this->GetWidget<NWidgetBase>(WID_NG_MAPSIZE);
00387         SetDParam(0, cur_item->info.map_width);
00388         SetDParam(1, cur_item->info.map_height);
00389         DrawString(nwi_mapsize->pos_x, nwi_mapsize->pos_x + nwi_mapsize->current_x - 1, y, STR_NETWORK_SERVER_LIST_MAP_SIZE_SHORT, TC_FROMSTRING, SA_HOR_CENTER);
00390       }
00391 
00392       if (nwi_header->IsWidgetVisible(WID_NG_DATE)) {
00393         /* current date */
00394         const NWidgetBase *nwi_date = this->GetWidget<NWidgetBase>(WID_NG_DATE);
00395         YearMonthDay ymd;
00396         ConvertDateToYMD(cur_item->info.game_date, &ymd);
00397         SetDParam(0, ymd.year);
00398         DrawString(nwi_date->pos_x, nwi_date->pos_x + nwi_date->current_x - 1, y, STR_JUST_INT, TC_BLACK, SA_HOR_CENTER);
00399       }
00400 
00401       if (nwi_header->IsWidgetVisible(WID_NG_YEARS)) {
00402         /* number of years the game is running */
00403         const NWidgetBase *nwi_years = this->GetWidget<NWidgetBase>(WID_NG_YEARS);
00404         YearMonthDay ymd_cur, ymd_start;
00405         ConvertDateToYMD(cur_item->info.game_date, &ymd_cur);
00406         ConvertDateToYMD(cur_item->info.start_date, &ymd_start);
00407         SetDParam(0, ymd_cur.year - ymd_start.year);
00408         DrawString(nwi_years->pos_x, nwi_years->pos_x + nwi_years->current_x - 1, y, STR_JUST_INT, TC_BLACK, SA_HOR_CENTER);
00409       }
00410 
00411       /* Align the sprites */
00412       y += (FONT_HEIGHT_NORMAL - 10) / 2;
00413 
00414       /* draw a lock if the server is password protected */
00415       if (cur_item->info.use_password) DrawSprite(SPR_LOCK, PAL_NONE, nwi_info->pos_x + 5, y - 1);
00416 
00417       /* draw red or green icon, depending on compatibility with server */
00418       DrawSprite(SPR_BLOT, (cur_item->info.compatible ? PALETTE_TO_GREEN : (cur_item->info.version_compatible ? PALETTE_TO_YELLOW : PALETTE_TO_RED)), nwi_info->pos_x + 15, y);
00419 
00420       /* draw flag according to server language */
00421       DrawSprite(SPR_FLAGS_BASE + cur_item->info.server_lang, PAL_NONE, nwi_info->pos_x + 25, y);
00422     }
00423   }
00424 
00432   void ScrollToSelectedServer()
00433   {
00434     if (this->list_pos == SLP_INVALID) return; // no server selected
00435     this->vscroll->ScrollTowards(this->list_pos);
00436   }
00437 
00438 public:
00439   NetworkGameWindow(const WindowDesc *desc) : QueryStringBaseWindow(NETWORK_CLIENT_NAME_LENGTH)
00440   {
00441     this->CreateNestedTree(desc);
00442     this->vscroll = this->GetScrollbar(WID_NG_SCROLLBAR);
00443     this->FinishInitNested(desc, WN_NETWORK_WINDOW_GAME);
00444 
00445     ttd_strlcpy(this->edit_str_buf, _settings_client.network.client_name, this->edit_str_size);
00446     this->afilter = CS_ALPHANUMERAL;
00447     InitializeTextBuffer(&this->text, this->edit_str_buf, this->edit_str_size, 120);
00448     this->SetFocusedWidget(WID_NG_CLIENT);
00449 
00450     UpdateNetworkGameWindow(true);
00451 
00452     this->field = WID_NG_CLIENT;
00453     this->last_joined = NetworkGameListAddItem(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port));
00454     this->server = this->last_joined;
00455 
00456     this->servers.SetListing(this->last_sorting);
00457     this->servers.SetSortFuncs(this->sorter_funcs);
00458     this->servers.ForceRebuild();
00459     this->SortNetworkGameList();
00460   }
00461 
00462   ~NetworkGameWindow()
00463   {
00464     this->last_sorting = this->servers.GetListing();
00465   }
00466 
00467   virtual void SetStringParameters(int widget) const
00468   {
00469     switch (widget) {
00470       case WID_NG_CONN_BTN:
00471         SetDParam(0, _lan_internet_types_dropdown[_settings_client.network.lan_internet]);
00472         break;
00473     }
00474   }
00475 
00476   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00477   {
00478     switch (widget) {
00479       case WID_NG_CONN_BTN:
00480         *size = maxdim(GetStringBoundingBox(_lan_internet_types_dropdown[0]), GetStringBoundingBox(_lan_internet_types_dropdown[1]));
00481         size->width += padding.width;
00482         size->height += padding.height;
00483         break;
00484 
00485       case WID_NG_MATRIX:
00486         resize->height = WD_MATRIX_TOP + FONT_HEIGHT_NORMAL + WD_MATRIX_BOTTOM;
00487         size->height = 10 * resize->height;
00488         break;
00489 
00490       case WID_NG_LASTJOINED:
00491         size->height = WD_MATRIX_TOP + FONT_HEIGHT_NORMAL + WD_MATRIX_BOTTOM;
00492         break;
00493 
00494       case WID_NG_LASTJOINED_SPACER:
00495         size->width = NWidgetScrollbar::GetVerticalDimension().width;
00496         break;
00497 
00498       case WID_NG_NAME:
00499         size->width += 2 * WD_SORTBUTTON_ARROW_WIDTH; // Make space for the arrow
00500         break;
00501 
00502       case WID_NG_CLIENTS:
00503         size->width += 2 * WD_SORTBUTTON_ARROW_WIDTH; // Make space for the arrow
00504         SetDParam(0, 255);
00505         SetDParam(1, 255);
00506         SetDParam(2, 15);
00507         SetDParam(3, 15);
00508         *size = maxdim(*size, GetStringBoundingBox(STR_NETWORK_SERVER_LIST_GENERAL_ONLINE));
00509         break;
00510 
00511       case WID_NG_MAPSIZE:
00512         size->width += 2 * WD_SORTBUTTON_ARROW_WIDTH; // Make space for the arrow
00513         SetDParam(0, 2048);
00514         SetDParam(1, 2048);
00515         *size = maxdim(*size, GetStringBoundingBox(STR_NETWORK_SERVER_LIST_MAP_SIZE_SHORT));
00516         break;
00517 
00518       case WID_NG_DATE:
00519       case WID_NG_YEARS:
00520         size->width += 2 * WD_SORTBUTTON_ARROW_WIDTH; // Make space for the arrow
00521         SetDParam(0, 99999);
00522         *size = maxdim(*size, GetStringBoundingBox(STR_JUST_INT));
00523         break;
00524 
00525       case WID_NG_DETAILS_SPACER:
00526         size->height = 20 + 12 * FONT_HEIGHT_NORMAL;
00527         break;
00528     }
00529   }
00530 
00531   virtual void DrawWidget(const Rect &r, int widget) const
00532   {
00533     switch (widget) {
00534       case WID_NG_MATRIX: {
00535         uint16 y = r.top + WD_MATRIX_TOP;
00536 
00537         const int max = min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), (int)this->servers.Length());
00538 
00539         for (int i = this->vscroll->GetPosition(); i < max; ++i) {
00540           const NetworkGameList *ngl = this->servers[i];
00541           this->DrawServerLine(ngl, y, ngl == this->server);
00542           y += this->resize.step_height;
00543         }
00544         break;
00545       }
00546 
00547       case WID_NG_LASTJOINED:
00548         /* Draw the last joined server, if any */
00549         if (this->last_joined != NULL) this->DrawServerLine(this->last_joined, r.top + WD_MATRIX_TOP, this->last_joined == this->server);
00550         break;
00551 
00552       case WID_NG_DETAILS:
00553         this->DrawDetails(r);
00554         break;
00555 
00556       case WID_NG_NAME:
00557       case WID_NG_CLIENTS:
00558       case WID_NG_MAPSIZE:
00559       case WID_NG_DATE:
00560       case WID_NG_YEARS:
00561       case WID_NG_INFO:
00562         if (widget - WID_NG_NAME == this->servers.SortType()) this->DrawSortButtonState(widget, this->servers.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
00563         break;
00564     }
00565   }
00566 
00567 
00568   virtual void OnPaint()
00569   {
00570     if (this->servers.NeedRebuild()) {
00571       this->BuildNetworkGameList();
00572     }
00573     this->SortNetworkGameList();
00574 
00575     NetworkGameList *sel = this->server;
00576     /* 'Refresh' button invisible if no server selected */
00577     this->SetWidgetDisabledState(WID_NG_REFRESH, sel == NULL);
00578     /* 'Join' button disabling conditions */
00579     this->SetWidgetDisabledState(WID_NG_JOIN, sel == NULL || // no Selected Server
00580         !sel->online || // Server offline
00581         sel->info.clients_on >= sel->info.clients_max || // Server full
00582         !sel->info.compatible); // Revision mismatch
00583 
00584     /* 'NewGRF Settings' button invisible if no NewGRF is used */
00585     this->GetWidget<NWidgetStacked>(WID_NG_NEWGRF_SEL)->SetDisplayedPlane(sel == NULL || !sel->online || sel->info.grfconfig == NULL);
00586     this->GetWidget<NWidgetStacked>(WID_NG_NEWGRF_MISSING_SEL)->SetDisplayedPlane(sel == NULL || !sel->online || sel->info.grfconfig == NULL || !sel->info.version_compatible || sel->info.compatible);
00587 
00588     this->DrawWidgets();
00589     /* Edit box to set client name */
00590     this->DrawEditBox(WID_NG_CLIENT);
00591   }
00592 
00593   void DrawDetails(const Rect &r) const
00594   {
00595     NetworkGameList *sel = this->server;
00596 
00597     const int detail_height = 6 + 8 + 6 + 3 * FONT_HEIGHT_NORMAL;
00598 
00599     /* Draw the right menu */
00600     GfxFillRect(r.left + 1, r.top + 1, r.right - 1, r.top + detail_height - 1, PC_DARK_BLUE);
00601     if (sel == NULL) {
00602       DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + 6 + 4 + FONT_HEIGHT_NORMAL, STR_NETWORK_SERVER_LIST_GAME_INFO, TC_FROMSTRING, SA_HOR_CENTER);
00603     } else if (!sel->online) {
00604       DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + 6 + 4 + FONT_HEIGHT_NORMAL, sel->info.server_name, TC_ORANGE, SA_HOR_CENTER); // game name
00605 
00606       DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + detail_height + 4, STR_NETWORK_SERVER_LIST_SERVER_OFFLINE, TC_FROMSTRING, SA_HOR_CENTER); // server offline
00607     } else { // show game info
00608 
00609       DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + 6, STR_NETWORK_SERVER_LIST_GAME_INFO, TC_FROMSTRING, SA_HOR_CENTER);
00610       DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + 6 + 4 + FONT_HEIGHT_NORMAL, sel->info.server_name, TC_ORANGE, SA_HOR_CENTER); // game name
00611       DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + 6 + 8 + 2 * FONT_HEIGHT_NORMAL, sel->info.map_name, TC_BLACK, SA_HOR_CENTER); // map name
00612 
00613       uint16 y = r.top + detail_height + 4;
00614 
00615       SetDParam(0, sel->info.clients_on);
00616       SetDParam(1, sel->info.clients_max);
00617       SetDParam(2, sel->info.companies_on);
00618       SetDParam(3, sel->info.companies_max);
00619       DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_NETWORK_SERVER_LIST_CLIENTS);
00620       y += FONT_HEIGHT_NORMAL;
00621 
00622       SetDParam(0, STR_NETWORK_LANG_ANY + sel->info.server_lang);
00623       DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_NETWORK_SERVER_LIST_LANGUAGE); // server language
00624       y += FONT_HEIGHT_NORMAL;
00625 
00626       SetDParam(0, STR_CHEAT_SWITCH_CLIMATE_TEMPERATE_LANDSCAPE + sel->info.map_set);
00627       DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_NETWORK_SERVER_LIST_LANDSCAPE); // landscape
00628       y += FONT_HEIGHT_NORMAL;
00629 
00630       SetDParam(0, sel->info.map_width);
00631       SetDParam(1, sel->info.map_height);
00632       DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_NETWORK_SERVER_LIST_MAP_SIZE); // map size
00633       y += FONT_HEIGHT_NORMAL;
00634 
00635       SetDParamStr(0, sel->info.server_revision);
00636       DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_NETWORK_SERVER_LIST_SERVER_VERSION); // server version
00637       y += FONT_HEIGHT_NORMAL;
00638 
00639       SetDParamStr(0, sel->address.GetAddressAsString());
00640       DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_NETWORK_SERVER_LIST_SERVER_ADDRESS); // server address
00641       y += FONT_HEIGHT_NORMAL;
00642 
00643       SetDParam(0, sel->info.start_date);
00644       DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_NETWORK_SERVER_LIST_START_DATE); // start date
00645       y += FONT_HEIGHT_NORMAL;
00646 
00647       SetDParam(0, sel->info.game_date);
00648       DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_NETWORK_SERVER_LIST_CURRENT_DATE); // current date
00649       y += FONT_HEIGHT_NORMAL;
00650 
00651       y += WD_PAR_VSEP_NORMAL;
00652 
00653       if (!sel->info.compatible) {
00654         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, sel->info.version_compatible ? STR_NETWORK_SERVER_LIST_GRF_MISMATCH : STR_NETWORK_SERVER_LIST_VERSION_MISMATCH, TC_FROMSTRING, SA_HOR_CENTER); // server mismatch
00655       } else if (sel->info.clients_on == sel->info.clients_max) {
00656         /* Show: server full, when clients_on == max_clients */
00657         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_NETWORK_SERVER_LIST_SERVER_FULL, TC_FROMSTRING, SA_HOR_CENTER); // server full
00658       } else if (sel->info.use_password) {
00659         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_NETWORK_SERVER_LIST_PASSWORD, TC_FROMSTRING, SA_HOR_CENTER); // password warning
00660       }
00661     }
00662   }
00663 
00664   virtual void OnClick(Point pt, int widget, int click_count)
00665   {
00666     this->field = widget;
00667     switch (widget) {
00668       case WID_NG_CANCEL: // Cancel button
00669         DeleteWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_GAME);
00670         break;
00671 
00672       case WID_NG_CONN_BTN: // 'Connection' droplist
00673         ShowDropDownMenu(this, _lan_internet_types_dropdown, _settings_client.network.lan_internet, WID_NG_CONN_BTN, 0, 0); // do it for widget WID_NSS_CONN_BTN
00674         break;
00675 
00676       case WID_NG_NAME:    // Sort by name
00677       case WID_NG_CLIENTS: // Sort by connected clients
00678       case WID_NG_MAPSIZE: // Sort by map size
00679       case WID_NG_DATE:    // Sort by date
00680       case WID_NG_YEARS:   // Sort by years
00681       case WID_NG_INFO:    // Connectivity (green dot)
00682         if (this->servers.SortType() == widget - WID_NG_NAME) {
00683           this->servers.ToggleSortOrder();
00684           if (this->list_pos != SLP_INVALID) this->list_pos = this->servers.Length() - this->list_pos - 1;
00685         } else {
00686           this->servers.SetSortType(widget - WID_NG_NAME);
00687           this->servers.ForceResort();
00688           this->SortNetworkGameList();
00689         }
00690         this->ScrollToSelectedServer();
00691         this->SetDirty();
00692         break;
00693 
00694       case WID_NG_MATRIX: { // Matrix to show networkgames
00695         uint id_v = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NG_MATRIX);
00696         this->server = (id_v < this->servers.Length()) ? this->servers[id_v] : NULL;
00697         this->list_pos = (server == NULL) ? SLP_INVALID : id_v;
00698         this->SetDirty();
00699 
00700         /* FIXME the disabling should go into some InvalidateData, which is called instead of the SetDirty */
00701         if (click_count > 1 && !this->IsWidgetDisabled(WID_NG_JOIN)) this->OnClick(pt, WID_NG_JOIN, 1);
00702         break;
00703       }
00704 
00705       case WID_NG_LASTJOINED: {
00706         if (this->last_joined != NULL) {
00707           this->server = this->last_joined;
00708 
00709           /* search the position of the newly selected server */
00710           for (uint i = 0; i < this->servers.Length(); i++) {
00711             if (this->servers[i] == this->server) {
00712               this->list_pos = i;
00713               break;
00714             }
00715           }
00716           this->ScrollToSelectedServer();
00717           this->SetDirty();
00718 
00719           /* FIXME the disabling should go into some InvalidateData, which is called instead of the SetDirty */
00720           if (click_count > 1 && !this->IsWidgetDisabled(WID_NG_JOIN)) this->OnClick(pt, WID_NG_JOIN, 1);
00721         }
00722         break;
00723       }
00724 
00725       case WID_NG_FIND: // Find server automatically
00726         switch (_settings_client.network.lan_internet) {
00727           case 0: NetworkUDPSearchGame(); break;
00728           case 1: NetworkUDPQueryMasterServer(); break;
00729         }
00730         break;
00731 
00732       case WID_NG_ADD: // Add a server
00733         SetDParamStr(0, _settings_client.network.connect_to_ip);
00734         ShowQueryString(
00735           STR_JUST_RAW_STRING,
00736           STR_NETWORK_SERVER_LIST_ENTER_IP,
00737           NETWORK_HOSTNAME_LENGTH,  // maximum number of characters including '\0'
00738           this, CS_ALPHANUMERAL, QSF_ACCEPT_UNCHANGED);
00739         break;
00740 
00741       case WID_NG_START: // Start server
00742         ShowNetworkStartServerWindow();
00743         break;
00744 
00745       case WID_NG_JOIN: // Join Game
00746         if (this->server != NULL) {
00747           snprintf(_settings_client.network.last_host, sizeof(_settings_client.network.last_host), "%s", this->server->address.GetHostname());
00748           _settings_client.network.last_port = this->server->address.GetPort();
00749           ShowNetworkLobbyWindow(this->server);
00750         }
00751         break;
00752 
00753       case WID_NG_REFRESH: // Refresh
00754         if (this->server != NULL) NetworkUDPQueryServer(this->server->address);
00755         break;
00756 
00757       case WID_NG_NEWGRF: // NewGRF Settings
00758         if (this->server != NULL) ShowNewGRFSettings(false, false, false, &this->server->info.grfconfig);
00759         break;
00760 
00761       case WID_NG_NEWGRF_MISSING: // Find missing content online
00762         if (this->server != NULL) ShowMissingContentWindow(this->server->info.grfconfig);
00763         break;
00764     }
00765   }
00766 
00767   virtual void OnDropdownSelect(int widget, int index)
00768   {
00769     switch (widget) {
00770       case WID_NG_CONN_BTN:
00771         _settings_client.network.lan_internet = index;
00772         break;
00773 
00774       default:
00775         NOT_REACHED();
00776     }
00777 
00778     this->SetDirty();
00779   }
00780 
00781   virtual void OnMouseLoop()
00782   {
00783     if (this->field == WID_NG_CLIENT) this->HandleEditBox(WID_NG_CLIENT);
00784   }
00785 
00791   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
00792   {
00793     if (data == 1) {
00794       this->server = NULL;
00795       this->list_pos = SLP_INVALID;
00796     }
00797     this->servers.ForceRebuild();
00798     this->SetDirty();
00799   }
00800 
00801   virtual EventState OnKeyPress(uint16 key, uint16 keycode)
00802   {
00803     EventState state = ES_NOT_HANDLED;
00804 
00805     /* handle up, down, pageup, pagedown, home and end */
00806     if (keycode == WKC_UP || keycode == WKC_DOWN || keycode == WKC_PAGEUP || keycode == WKC_PAGEDOWN || keycode == WKC_HOME || keycode == WKC_END) {
00807       if (this->servers.Length() == 0) return ES_HANDLED;
00808       switch (keycode) {
00809         case WKC_UP:
00810           /* scroll up by one */
00811           if (this->server == NULL) return ES_HANDLED;
00812           if (this->list_pos > 0) this->list_pos--;
00813           break;
00814         case WKC_DOWN:
00815           /* scroll down by one */
00816           if (this->server == NULL) return ES_HANDLED;
00817           if (this->list_pos < this->servers.Length() - 1) this->list_pos++;
00818           break;
00819         case WKC_PAGEUP:
00820           /* scroll up a page */
00821           if (this->server == NULL) return ES_HANDLED;
00822           this->list_pos = (this->list_pos < this->vscroll->GetCapacity()) ? 0 : this->list_pos - this->vscroll->GetCapacity();
00823           break;
00824         case WKC_PAGEDOWN:
00825           /* scroll down a page */
00826           if (this->server == NULL) return ES_HANDLED;
00827           this->list_pos = min(this->list_pos + this->vscroll->GetCapacity(), (int)this->servers.Length() - 1);
00828           break;
00829         case WKC_HOME:
00830           /* jump to beginning */
00831           this->list_pos = 0;
00832           break;
00833         case WKC_END:
00834           /* jump to end */
00835           this->list_pos = this->servers.Length() - 1;
00836           break;
00837         default: break;
00838       }
00839 
00840       this->server = this->servers[this->list_pos];
00841 
00842       /* scroll to the new server if it is outside the current range */
00843       this->ScrollToSelectedServer();
00844 
00845       /* redraw window */
00846       this->SetDirty();
00847       return ES_HANDLED;
00848     }
00849 
00850     if (this->field != WID_NG_CLIENT) {
00851       if (this->server != NULL) {
00852         if (keycode == WKC_DELETE) { // Press 'delete' to remove servers
00853           NetworkGameListRemoveItem(this->server);
00854           if (this->server == this->last_joined) this->last_joined = NULL;
00855           this->server = NULL;
00856           this->list_pos = SLP_INVALID;
00857         }
00858       }
00859       return state;
00860     }
00861 
00862     if (this->HandleEditBoxKey(WID_NG_CLIENT, key, keycode, state) == HEBR_CONFIRM) return state;
00863 
00864     /* The name is only allowed when it starts with a letter! */
00865     if (!StrEmpty(this->edit_str_buf) && this->edit_str_buf[0] != ' ') {
00866       strecpy(_settings_client.network.client_name, this->edit_str_buf, lastof(_settings_client.network.client_name));
00867     } else {
00868       strecpy(_settings_client.network.client_name, "Player", lastof(_settings_client.network.client_name));
00869     }
00870     return state;
00871   }
00872 
00873   virtual void OnQueryTextFinished(char *str)
00874   {
00875     if (!StrEmpty(str)) NetworkAddServer(str);
00876   }
00877 
00878   virtual void OnResize()
00879   {
00880     this->vscroll->SetCapacityFromWidget(this, WID_NG_MATRIX);
00881     this->GetWidget<NWidgetCore>(WID_NG_MATRIX)->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
00882   }
00883 
00884   virtual void OnTick()
00885   {
00886     NetworkGameListRequery();
00887   }
00888 };
00889 
00890 Listing NetworkGameWindow::last_sorting = {false, 5};
00891 GUIGameServerList::SortFunction * const NetworkGameWindow::sorter_funcs[] = {
00892   &NGameNameSorter,
00893   &NGameClientSorter,
00894   &NGameMapSizeSorter,
00895   &NGameDateSorter,
00896   &NGameYearsSorter,
00897   &NGameAllowedSorter
00898 };
00899 
00900 static NWidgetBase *MakeResizableHeader(int *biggest_index)
00901 {
00902   *biggest_index = max<int>(*biggest_index, WID_NG_INFO);
00903   return new NWidgetServerListHeader();
00904 }
00905 
00906 static const NWidgetPart _nested_network_game_widgets[] = {
00907   /* TOP */
00908   NWidget(NWID_HORIZONTAL),
00909     NWidget(WWT_CLOSEBOX, COLOUR_LIGHT_BLUE),
00910     NWidget(WWT_CAPTION, COLOUR_LIGHT_BLUE), SetDataTip(STR_NETWORK_SERVER_LIST_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00911   EndContainer(),
00912   NWidget(WWT_PANEL, COLOUR_LIGHT_BLUE, WID_NG_MAIN),
00913     NWidget(NWID_VERTICAL), SetPIP(10, 7, 0),
00914       NWidget(NWID_HORIZONTAL), SetPIP(10, 7, 10),
00915         NWidget(WWT_TEXT, COLOUR_LIGHT_BLUE, WID_NG_CONNECTION), SetDataTip(STR_NETWORK_SERVER_LIST_CONNECTION, STR_NULL),
00916         NWidget(WWT_DROPDOWN, COLOUR_LIGHT_BLUE, WID_NG_CONN_BTN),
00917                     SetDataTip(STR_BLACK_STRING, STR_NETWORK_SERVER_LIST_CONNECTION_TOOLTIP),
00918         NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
00919         NWidget(WWT_TEXT, COLOUR_LIGHT_BLUE, WID_NG_CLIENT_LABEL), SetDataTip(STR_NETWORK_SERVER_LIST_PLAYER_NAME, STR_NULL),
00920         NWidget(WWT_EDITBOX, COLOUR_LIGHT_BLUE, WID_NG_CLIENT), SetMinimalSize(151, 12),
00921                     SetDataTip(STR_NETWORK_SERVER_LIST_PLAYER_NAME_OSKTITLE, STR_NETWORK_SERVER_LIST_ENTER_NAME_TOOLTIP),
00922       EndContainer(),
00923       NWidget(NWID_HORIZONTAL), SetPIP(10, 7, 10),
00924         /* LEFT SIDE */
00925         NWidget(NWID_VERTICAL),
00926           NWidget(NWID_HORIZONTAL),
00927             NWidget(NWID_VERTICAL),
00928               NWidgetFunction(MakeResizableHeader),
00929               NWidget(WWT_MATRIX, COLOUR_LIGHT_BLUE, WID_NG_MATRIX), SetResize(1, 1), SetFill(1, 0),
00930                         SetDataTip(0, STR_NETWORK_SERVER_LIST_CLICK_GAME_TO_SELECT), SetScrollbar(WID_NG_SCROLLBAR),
00931             EndContainer(),
00932             NWidget(NWID_VSCROLLBAR, COLOUR_LIGHT_BLUE, WID_NG_SCROLLBAR),
00933           EndContainer(),
00934           NWidget(NWID_SPACER), SetMinimalSize(0, 7), SetResize(1, 0), SetFill(1, 1),
00935           NWidget(WWT_TEXT, COLOUR_LIGHT_BLUE, WID_NG_LASTJOINED_LABEL), SetFill(1, 0),
00936                     SetDataTip(STR_NETWORK_SERVER_LIST_LAST_JOINED_SERVER, STR_NULL), SetResize(1, 0),
00937           NWidget(NWID_HORIZONTAL),
00938             NWidget(WWT_PANEL, COLOUR_LIGHT_BLUE, WID_NG_LASTJOINED), SetFill(1, 0), SetResize(1, 0),
00939                       SetDataTip(0x0, STR_NETWORK_SERVER_LIST_CLICK_TO_SELECT_LAST),
00940             EndContainer(),
00941             NWidget(WWT_EMPTY, INVALID_COLOUR, WID_NG_LASTJOINED_SPACER), SetFill(0, 0),
00942           EndContainer(),
00943         EndContainer(),
00944         /* RIGHT SIDE */
00945         NWidget(WWT_PANEL, COLOUR_LIGHT_BLUE, WID_NG_DETAILS),
00946           NWidget(NWID_VERTICAL, NC_EQUALSIZE), SetPIP(5, 5, 5),
00947             NWidget(WWT_EMPTY, INVALID_COLOUR, WID_NG_DETAILS_SPACER), SetMinimalSize(140, 155), SetResize(0, 1), SetFill(1, 1), // Make sure it's at least this wide
00948             NWidget(NWID_HORIZONTAL, NC_NONE), SetPIP(5, 5, 5),
00949               NWidget(NWID_SELECTION, INVALID_COLOUR, WID_NG_NEWGRF_MISSING_SEL),
00950                 NWidget(WWT_PUSHTXTBTN, COLOUR_WHITE, WID_NG_NEWGRF_MISSING), SetFill(1, 0), SetDataTip(STR_NEWGRF_SETTINGS_FIND_MISSING_CONTENT_BUTTON, STR_NEWGRF_SETTINGS_FIND_MISSING_CONTENT_TOOLTIP),
00951                 NWidget(NWID_SPACER), SetFill(1, 0),
00952               EndContainer(),
00953             EndContainer(),
00954             NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(5, 5, 5),
00955               NWidget(NWID_SPACER), SetFill(1, 0),
00956               NWidget(NWID_SELECTION, INVALID_COLOUR, WID_NG_NEWGRF_SEL),
00957                 NWidget(WWT_PUSHTXTBTN, COLOUR_WHITE, WID_NG_NEWGRF), SetFill(1, 0), SetDataTip(STR_INTRO_NEWGRF_SETTINGS, STR_NULL),
00958                 NWidget(NWID_SPACER), SetFill(1, 0),
00959               EndContainer(),
00960             EndContainer(),
00961             NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(5, 5, 5),
00962               NWidget(WWT_PUSHTXTBTN, COLOUR_WHITE, WID_NG_JOIN), SetFill(1, 0), SetDataTip(STR_NETWORK_SERVER_LIST_JOIN_GAME, STR_NULL),
00963               NWidget(WWT_PUSHTXTBTN, COLOUR_WHITE, WID_NG_REFRESH), SetFill(1, 0), SetDataTip(STR_NETWORK_SERVER_LIST_REFRESH, STR_NETWORK_SERVER_LIST_REFRESH_TOOLTIP),
00964             EndContainer(),
00965           EndContainer(),
00966         EndContainer(),
00967       EndContainer(),
00968       /* BOTTOM */
00969       NWidget(NWID_HORIZONTAL),
00970         NWidget(NWID_VERTICAL),
00971           NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(10, 7, 4),
00972             NWidget(WWT_PUSHTXTBTN, COLOUR_WHITE, WID_NG_FIND), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_NETWORK_SERVER_LIST_FIND_SERVER, STR_NETWORK_SERVER_LIST_FIND_SERVER_TOOLTIP),
00973             NWidget(WWT_PUSHTXTBTN, COLOUR_WHITE, WID_NG_ADD), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_NETWORK_SERVER_LIST_ADD_SERVER, STR_NETWORK_SERVER_LIST_ADD_SERVER_TOOLTIP),
00974             NWidget(WWT_PUSHTXTBTN, COLOUR_WHITE, WID_NG_START), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_NETWORK_SERVER_LIST_START_SERVER, STR_NETWORK_SERVER_LIST_START_SERVER_TOOLTIP),
00975             NWidget(WWT_PUSHTXTBTN, COLOUR_WHITE, WID_NG_CANCEL), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_BUTTON_CANCEL, STR_NULL),
00976           EndContainer(),
00977           NWidget(NWID_SPACER), SetMinimalSize(0, 6), SetResize(1, 0), SetFill(1, 0),
00978         EndContainer(),
00979         NWidget(NWID_VERTICAL),
00980           NWidget(NWID_SPACER), SetFill(0, 1),
00981           NWidget(WWT_RESIZEBOX, COLOUR_LIGHT_BLUE),
00982         EndContainer(),
00983       EndContainer(),
00984     EndContainer(),
00985   EndContainer(),
00986 };
00987 
00988 static const WindowDesc _network_game_window_desc(
00989   WDP_CENTER, 1000, 730,
00990   WC_NETWORK_WINDOW, WC_NONE,
00991   WDF_UNCLICK_BUTTONS,
00992   _nested_network_game_widgets, lengthof(_nested_network_game_widgets)
00993 );
00994 
00995 void ShowNetworkGameWindow()
00996 {
00997   static bool first = true;
00998   DeleteWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_LOBBY);
00999   DeleteWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_START);
01000 
01001   /* Only show once */
01002   if (first) {
01003     first = false;
01004     /* add all servers from the config file to our list */
01005     for (char **iter = _network_host_list.Begin(); iter != _network_host_list.End(); iter++) {
01006       NetworkAddServer(*iter);
01007     }
01008   }
01009 
01010   new NetworkGameWindow(&_network_game_window_desc);
01011 }
01012 
01013 struct NetworkStartServerWindow : public QueryStringBaseWindow {
01014   byte field;                  
01015   byte widget_id;              
01016 
01017   NetworkStartServerWindow(const WindowDesc *desc) : QueryStringBaseWindow(NETWORK_NAME_LENGTH)
01018   {
01019     this->InitNested(desc, WN_NETWORK_WINDOW_START);
01020 
01021     ttd_strlcpy(this->edit_str_buf, _settings_client.network.server_name, this->edit_str_size);
01022 
01023     this->afilter = CS_ALPHANUMERAL;
01024     InitializeTextBuffer(&this->text, this->edit_str_buf, this->edit_str_size, 160);
01025     this->SetFocusedWidget(WID_NSS_GAMENAME);
01026 
01027     this->field = WID_NSS_GAMENAME;
01028   }
01029 
01030   virtual void SetStringParameters(int widget) const
01031   {
01032     switch (widget) {
01033       case WID_NSS_CONNTYPE_BTN:
01034         SetDParam(0, _connection_types_dropdown[_settings_client.network.server_advertise]);
01035         break;
01036 
01037       case WID_NSS_CLIENTS_TXT:
01038         SetDParam(0, _settings_client.network.max_clients);
01039         break;
01040 
01041       case WID_NSS_COMPANIES_TXT:
01042         SetDParam(0, _settings_client.network.max_companies);
01043         break;
01044 
01045       case WID_NSS_SPECTATORS_TXT:
01046         SetDParam(0, _settings_client.network.max_spectators);
01047         break;
01048 
01049       case WID_NSS_LANGUAGE_BTN:
01050         SetDParam(0, STR_NETWORK_LANG_ANY + _settings_client.network.server_lang);
01051         break;
01052     }
01053   }
01054 
01055   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01056   {
01057     switch (widget) {
01058       case WID_NSS_CONNTYPE_BTN:
01059         *size = maxdim(GetStringBoundingBox(_connection_types_dropdown[0]), GetStringBoundingBox(_connection_types_dropdown[1]));
01060         size->width += padding.width;
01061         size->height += padding.height;
01062         break;
01063     }
01064   }
01065 
01066   virtual void DrawWidget(const Rect &r, int widget) const
01067   {
01068     switch (widget) {
01069       case WID_NSS_SETPWD:
01070         /* if password is set, draw red '*' next to 'Set password' button */
01071         if (!StrEmpty(_settings_client.network.server_password)) DrawString(r.right + WD_FRAMERECT_LEFT, this->width - WD_FRAMERECT_RIGHT, r.top, "*", TC_RED);
01072     }
01073   }
01074 
01075   virtual void OnPaint()
01076   {
01077     /* draw basic widgets */
01078     this->DrawWidgets();
01079 
01080     /* editbox to set game name */
01081     this->DrawEditBox(WID_NSS_GAMENAME);
01082   }
01083 
01084   virtual void OnClick(Point pt, int widget, int click_count)
01085   {
01086     this->field = widget;
01087     switch (widget) {
01088       case WID_NSS_CANCEL: // Cancel button
01089         ShowNetworkGameWindow();
01090         break;
01091 
01092       case WID_NSS_SETPWD: // Set password button
01093         this->widget_id = WID_NSS_SETPWD;
01094         SetDParamStr(0, _settings_client.network.server_password);
01095         ShowQueryString(STR_JUST_RAW_STRING, STR_NETWORK_START_SERVER_SET_PASSWORD, 20, this, CS_ALPHANUMERAL, QSF_NONE);
01096         break;
01097 
01098       case WID_NSS_CONNTYPE_BTN: // Connection type
01099         ShowDropDownMenu(this, _connection_types_dropdown, _settings_client.network.server_advertise, WID_NSS_CONNTYPE_BTN, 0, 0); // do it for widget WID_NSS_CONNTYPE_BTN
01100         break;
01101 
01102       case WID_NSS_CLIENTS_BTND:    case WID_NSS_CLIENTS_BTNU:    // Click on up/down button for number of clients
01103       case WID_NSS_COMPANIES_BTND:  case WID_NSS_COMPANIES_BTNU:  // Click on up/down button for number of companies
01104       case WID_NSS_SPECTATORS_BTND: case WID_NSS_SPECTATORS_BTNU: // Click on up/down button for number of spectators
01105         /* Don't allow too fast scrolling */
01106         if (!(this->flags & WF_TIMEOUT) || this->timeout_timer <= 1) {
01107           this->HandleButtonClick(widget);
01108           this->SetDirty();
01109           switch (widget) {
01110             default: NOT_REACHED();
01111             case WID_NSS_CLIENTS_BTND: case WID_NSS_CLIENTS_BTNU:
01112               _settings_client.network.max_clients    = Clamp(_settings_client.network.max_clients    + widget - WID_NSS_CLIENTS_TXT,    2, MAX_CLIENTS);
01113               break;
01114             case WID_NSS_COMPANIES_BTND: case WID_NSS_COMPANIES_BTNU:
01115               _settings_client.network.max_companies  = Clamp(_settings_client.network.max_companies  + widget - WID_NSS_COMPANIES_TXT,  1, MAX_COMPANIES);
01116               break;
01117             case WID_NSS_SPECTATORS_BTND: case WID_NSS_SPECTATORS_BTNU:
01118               _settings_client.network.max_spectators = Clamp(_settings_client.network.max_spectators + widget - WID_NSS_SPECTATORS_TXT, 0, MAX_CLIENTS);
01119               break;
01120           }
01121         }
01122         _left_button_clicked = false;
01123         break;
01124 
01125       case WID_NSS_CLIENTS_TXT:    // Click on number of clients
01126         this->widget_id = WID_NSS_CLIENTS_TXT;
01127         SetDParam(0, _settings_client.network.max_clients);
01128         ShowQueryString(STR_JUST_INT, STR_NETWORK_START_SERVER_NUMBER_OF_CLIENTS,    4, this, CS_NUMERAL, QSF_NONE);
01129         break;
01130 
01131       case WID_NSS_COMPANIES_TXT:  // Click on number of companies
01132         this->widget_id = WID_NSS_COMPANIES_TXT;
01133         SetDParam(0, _settings_client.network.max_companies);
01134         ShowQueryString(STR_JUST_INT, STR_NETWORK_START_SERVER_NUMBER_OF_COMPANIES,  3, this, CS_NUMERAL, QSF_NONE);
01135         break;
01136 
01137       case WID_NSS_SPECTATORS_TXT: // Click on number of spectators
01138         this->widget_id = WID_NSS_SPECTATORS_TXT;
01139         SetDParam(0, _settings_client.network.max_spectators);
01140         ShowQueryString(STR_JUST_INT, STR_NETWORK_START_SERVER_NUMBER_OF_SPECTATORS, 4, this, CS_NUMERAL, QSF_NONE);
01141         break;
01142 
01143       case WID_NSS_LANGUAGE_BTN: { // Language
01144         uint sel = 0;
01145         for (uint i = 0; i < lengthof(_language_dropdown) - 1; i++) {
01146           if (_language_dropdown[i] == STR_NETWORK_LANG_ANY + _settings_client.network.server_lang) {
01147             sel = i;
01148             break;
01149           }
01150         }
01151         ShowDropDownMenu(this, _language_dropdown, sel, WID_NSS_LANGUAGE_BTN, 0, 0);
01152         break;
01153       }
01154 
01155       case WID_NSS_GENERATE_GAME: // Start game
01156         _is_network_server = true;
01157         if (_ctrl_pressed) {
01158           StartNewGameWithoutGUI(GENERATE_NEW_SEED);
01159         } else {
01160           ShowGenerateLandscape();
01161         }
01162         break;
01163 
01164       case WID_NSS_LOAD_GAME:
01165         _is_network_server = true;
01166         ShowSaveLoadDialog(SLD_LOAD_GAME);
01167         break;
01168 
01169       case WID_NSS_PLAY_SCENARIO:
01170         _is_network_server = true;
01171         ShowSaveLoadDialog(SLD_LOAD_SCENARIO);
01172         break;
01173 
01174       case WID_NSS_PLAY_HEIGHTMAP:
01175         _is_network_server = true;
01176         ShowSaveLoadDialog(SLD_LOAD_HEIGHTMAP);
01177         break;
01178     }
01179   }
01180 
01181   virtual void OnDropdownSelect(int widget, int index)
01182   {
01183     switch (widget) {
01184       case WID_NSS_CONNTYPE_BTN:
01185         _settings_client.network.server_advertise = (index != 0);
01186         break;
01187       case WID_NSS_LANGUAGE_BTN:
01188         _settings_client.network.server_lang = _language_dropdown[index] - STR_NETWORK_LANG_ANY;
01189         break;
01190       default:
01191         NOT_REACHED();
01192     }
01193 
01194     this->SetDirty();
01195   }
01196 
01197   virtual void OnMouseLoop()
01198   {
01199     if (this->field == WID_NSS_GAMENAME) this->HandleEditBox(WID_NSS_GAMENAME);
01200   }
01201 
01202   virtual EventState OnKeyPress(uint16 key, uint16 keycode)
01203   {
01204     EventState state = ES_NOT_HANDLED;
01205     if (this->field == WID_NSS_GAMENAME) {
01206       if (this->HandleEditBoxKey(WID_NSS_GAMENAME, key, keycode, state) == HEBR_CONFIRM) return state;
01207 
01208       strecpy(_settings_client.network.server_name, this->text.buf, lastof(_settings_client.network.server_name));
01209     }
01210 
01211     return state;
01212   }
01213 
01214   virtual void OnTimeout()
01215   {
01216     static const int raise_widgets[] = {WID_NSS_CLIENTS_BTND, WID_NSS_CLIENTS_BTNU, WID_NSS_COMPANIES_BTND, WID_NSS_COMPANIES_BTNU, WID_NSS_SPECTATORS_BTND, WID_NSS_SPECTATORS_BTNU, WIDGET_LIST_END};
01217     for (const int *widget = raise_widgets; *widget != WIDGET_LIST_END; widget++) {
01218       if (this->IsWidgetLowered(*widget)) {
01219         this->RaiseWidget(*widget);
01220         this->SetWidgetDirty(*widget);
01221       }
01222     }
01223   }
01224 
01225   virtual void OnQueryTextFinished(char *str)
01226   {
01227     if (str == NULL) return;
01228 
01229     if (this->widget_id == WID_NSS_SETPWD) {
01230       strecpy(_settings_client.network.server_password, str, lastof(_settings_client.network.server_password));
01231     } else {
01232       int32 value = atoi(str);
01233       this->SetWidgetDirty(this->widget_id);
01234       switch (this->widget_id) {
01235         default: NOT_REACHED();
01236         case WID_NSS_CLIENTS_TXT:    _settings_client.network.max_clients    = Clamp(value, 2, MAX_CLIENTS); break;
01237         case WID_NSS_COMPANIES_TXT:  _settings_client.network.max_companies  = Clamp(value, 1, MAX_COMPANIES); break;
01238         case WID_NSS_SPECTATORS_TXT: _settings_client.network.max_spectators = Clamp(value, 0, MAX_CLIENTS); break;
01239       }
01240     }
01241 
01242     this->SetDirty();
01243   }
01244 };
01245 
01246 static const NWidgetPart _nested_network_start_server_window_widgets[] = {
01247   NWidget(NWID_HORIZONTAL),
01248     NWidget(WWT_CLOSEBOX, COLOUR_LIGHT_BLUE),
01249     NWidget(WWT_CAPTION, COLOUR_LIGHT_BLUE), SetDataTip(STR_NETWORK_START_SERVER_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
01250   EndContainer(),
01251   NWidget(WWT_PANEL, COLOUR_LIGHT_BLUE, WID_NSS_BACKGROUND),
01252     NWidget(NWID_VERTICAL), SetPIP(10, 6, 10),
01253       NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(10, 6, 10),
01254         NWidget(NWID_VERTICAL), SetPIP(0, 1, 0),
01255           /* Game name widgets */
01256           NWidget(WWT_TEXT, COLOUR_LIGHT_BLUE, WID_NSS_GAMENAME_LABEL), SetFill(1, 0), SetDataTip(STR_NETWORK_START_SERVER_NEW_GAME_NAME, STR_NULL),
01257           NWidget(WWT_EDITBOX, COLOUR_LIGHT_BLUE, WID_NSS_GAMENAME), SetMinimalSize(10, 12), SetFill(1, 0), SetDataTip(STR_NETWORK_START_SERVER_NEW_GAME_NAME_OSKTITLE, STR_NETWORK_START_SERVER_NEW_GAME_NAME_TOOLTIP),
01258         EndContainer(),
01259       EndContainer(),
01260 
01261       NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(10, 6, 10),
01262         NWidget(NWID_VERTICAL), SetPIP(0, 1, 0),
01263           NWidget(WWT_TEXT, COLOUR_LIGHT_BLUE, WID_NSS_CONNTYPE_LABEL), SetFill(1, 0), SetDataTip(STR_NETWORK_SERVER_LIST_CONNECTION, STR_NULL),
01264           NWidget(WWT_DROPDOWN, COLOUR_LIGHT_BLUE, WID_NSS_CONNTYPE_BTN), SetFill(1, 0), SetDataTip(STR_BLACK_STRING, STR_NETWORK_SERVER_LIST_CONNECTION_TOOLTIP),
01265         EndContainer(),
01266         NWidget(NWID_VERTICAL), SetPIP(0, 1, 0),
01267           NWidget(WWT_TEXT, COLOUR_LIGHT_BLUE, WID_NSS_LANGUAGE_LABEL), SetFill(1, 0), SetDataTip(STR_NETWORK_START_SERVER_LANGUAGE_SPOKEN, STR_NULL),
01268           NWidget(WWT_DROPDOWN, COLOUR_LIGHT_BLUE, WID_NSS_LANGUAGE_BTN), SetFill(1, 0), SetDataTip(STR_BLACK_STRING, STR_NETWORK_START_SERVER_LANGUAGE_TOOLTIP),
01269         EndContainer(),
01270         NWidget(NWID_VERTICAL), SetPIP(0, 1, 0),
01271           NWidget(NWID_SPACER), SetFill(1, 1),
01272           NWidget(WWT_PUSHTXTBTN, COLOUR_WHITE, WID_NSS_SETPWD), SetFill(1, 0), SetDataTip(STR_NETWORK_START_SERVER_SET_PASSWORD, STR_NETWORK_START_SERVER_PASSWORD_TOOLTIP),
01273         EndContainer(),
01274       EndContainer(),
01275 
01276       NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(10, 6, 10),
01277         NWidget(NWID_VERTICAL), SetPIP(0, 1, 0),
01278           NWidget(WWT_TEXT, COLOUR_LIGHT_BLUE, WID_NSS_CLIENTS_LABEL), SetFill(1, 0), SetDataTip(STR_NETWORK_START_SERVER_NUMBER_OF_CLIENTS, STR_NULL),
01279           NWidget(NWID_HORIZONTAL),
01280             NWidget(WWT_IMGBTN, COLOUR_LIGHT_BLUE, WID_NSS_CLIENTS_BTND), SetMinimalSize(12, 12), SetFill(0, 1), SetDataTip(SPR_ARROW_DOWN, STR_NETWORK_START_SERVER_NUMBER_OF_CLIENTS_TOOLTIP),
01281             NWidget(WWT_PUSHTXTBTN, COLOUR_LIGHT_BLUE, WID_NSS_CLIENTS_TXT), SetFill(1, 0), SetDataTip(STR_NETWORK_START_SERVER_CLIENTS_SELECT, STR_NETWORK_START_SERVER_NUMBER_OF_CLIENTS_TOOLTIP),
01282             NWidget(WWT_IMGBTN, COLOUR_LIGHT_BLUE, WID_NSS_CLIENTS_BTNU), SetMinimalSize(12, 12), SetFill(0, 1), SetDataTip(SPR_ARROW_UP, STR_NETWORK_START_SERVER_NUMBER_OF_CLIENTS_TOOLTIP),
01283           EndContainer(),
01284         EndContainer(),
01285 
01286         NWidget(NWID_VERTICAL), SetPIP(0, 1, 0),
01287           NWidget(WWT_TEXT, COLOUR_LIGHT_BLUE, WID_NSS_COMPANIES_LABEL), SetFill(1, 0), SetDataTip(STR_NETWORK_START_SERVER_NUMBER_OF_COMPANIES, STR_NULL),
01288           NWidget(NWID_HORIZONTAL),
01289             NWidget(WWT_IMGBTN, COLOUR_LIGHT_BLUE, WID_NSS_COMPANIES_BTND), SetMinimalSize(12, 12), SetFill(0, 1), SetDataTip(SPR_ARROW_DOWN, STR_NETWORK_START_SERVER_NUMBER_OF_COMPANIES_TOOLTIP),
01290             NWidget(WWT_PUSHTXTBTN, COLOUR_LIGHT_BLUE, WID_NSS_COMPANIES_TXT), SetFill(1, 0), SetDataTip(STR_NETWORK_START_SERVER_COMPANIES_SELECT, STR_NETWORK_START_SERVER_NUMBER_OF_COMPANIES_TOOLTIP),
01291             NWidget(WWT_IMGBTN, COLOUR_LIGHT_BLUE, WID_NSS_COMPANIES_BTNU), SetMinimalSize(12, 12), SetFill(0, 1), SetDataTip(SPR_ARROW_UP, STR_NETWORK_START_SERVER_NUMBER_OF_COMPANIES_TOOLTIP),
01292           EndContainer(),
01293         EndContainer(),
01294 
01295         NWidget(NWID_VERTICAL), SetPIP(0, 1, 0),
01296           NWidget(WWT_TEXT, COLOUR_LIGHT_BLUE, WID_NSS_SPECTATORS_LABEL), SetFill(1, 0), SetDataTip(STR_NETWORK_START_SERVER_NUMBER_OF_SPECTATORS, STR_NULL),
01297           NWidget(NWID_HORIZONTAL),
01298             NWidget(WWT_IMGBTN, COLOUR_LIGHT_BLUE, WID_NSS_SPECTATORS_BTND), SetMinimalSize(12, 12), SetFill(0, 1), SetDataTip(SPR_ARROW_DOWN, STR_NETWORK_START_SERVER_NUMBER_OF_SPECTATORS_TOOLTIP),
01299             NWidget(WWT_PUSHTXTBTN, COLOUR_LIGHT_BLUE, WID_NSS_SPECTATORS_TXT), SetFill(1, 0), SetDataTip(STR_NETWORK_START_SERVER_SPECTATORS_SELECT, STR_NETWORK_START_SERVER_NUMBER_OF_SPECTATORS_TOOLTIP),
01300             NWidget(WWT_IMGBTN, COLOUR_LIGHT_BLUE, WID_NSS_SPECTATORS_BTNU), SetMinimalSize(12, 12), SetFill(0, 1), SetDataTip(SPR_ARROW_UP, STR_NETWORK_START_SERVER_NUMBER_OF_SPECTATORS_TOOLTIP),
01301           EndContainer(),
01302         EndContainer(),
01303       EndContainer(),
01304 
01305       /* 'generate game' and 'load game' buttons */
01306       NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(10, 6, 10),
01307         NWidget(WWT_PUSHTXTBTN, COLOUR_WHITE, WID_NSS_GENERATE_GAME), SetDataTip(STR_INTRO_NEW_GAME, STR_INTRO_TOOLTIP_NEW_GAME), SetFill(1, 0),
01308         NWidget(WWT_PUSHTXTBTN, COLOUR_WHITE, WID_NSS_LOAD_GAME), SetDataTip(STR_INTRO_LOAD_GAME, STR_INTRO_TOOLTIP_LOAD_GAME), SetFill(1, 0),
01309       EndContainer(),
01310 
01311       /* 'play scenario' and 'play heightmap' buttons */
01312       NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(10, 6, 10),
01313         NWidget(WWT_PUSHTXTBTN, COLOUR_WHITE, WID_NSS_PLAY_SCENARIO), SetDataTip(STR_INTRO_PLAY_SCENARIO, STR_INTRO_TOOLTIP_PLAY_SCENARIO), SetFill(1, 0),
01314         NWidget(WWT_PUSHTXTBTN, COLOUR_WHITE, WID_NSS_PLAY_HEIGHTMAP), SetDataTip(STR_INTRO_PLAY_HEIGHTMAP, STR_INTRO_TOOLTIP_PLAY_HEIGHTMAP), SetFill(1, 0),
01315       EndContainer(),
01316 
01317       NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(10, 0, 10),
01318         NWidget(NWID_SPACER), SetFill(1, 0),
01319         NWidget(WWT_PUSHTXTBTN, COLOUR_WHITE, WID_NSS_CANCEL), SetDataTip(STR_BUTTON_CANCEL, STR_NULL), SetMinimalSize(128, 12),
01320         NWidget(NWID_SPACER), SetFill(1, 0),
01321       EndContainer(),
01322     EndContainer(),
01323   EndContainer(),
01324 };
01325 
01326 static const WindowDesc _network_start_server_window_desc(
01327   WDP_CENTER, 0, 0,
01328   WC_NETWORK_WINDOW, WC_NONE,
01329   WDF_UNCLICK_BUTTONS,
01330   _nested_network_start_server_window_widgets, lengthof(_nested_network_start_server_window_widgets)
01331 );
01332 
01333 static void ShowNetworkStartServerWindow()
01334 {
01335   DeleteWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_GAME);
01336   DeleteWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_LOBBY);
01337 
01338   new NetworkStartServerWindow(&_network_start_server_window_desc);
01339 }
01340 
01341 struct NetworkLobbyWindow : public Window {
01342   CompanyID company;       
01343   NetworkGameList *server; 
01344   NetworkCompanyInfo company_info[MAX_COMPANIES];
01345   Scrollbar *vscroll;
01346 
01347   NetworkLobbyWindow(const WindowDesc *desc, NetworkGameList *ngl) :
01348       Window(), company(INVALID_COMPANY), server(ngl)
01349   {
01350     this->CreateNestedTree(desc);
01351     this->vscroll = this->GetScrollbar(WID_NL_SCROLLBAR);
01352     this->FinishInitNested(desc, WN_NETWORK_WINDOW_LOBBY);
01353     this->OnResize();
01354   }
01355 
01356   CompanyID NetworkLobbyFindCompanyIndex(byte pos) const
01357   {
01358     /* Scroll through all this->company_info and get the 'pos' item that is not empty */
01359     for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) {
01360       if (!StrEmpty(this->company_info[i].company_name)) {
01361         if (pos-- == 0) return i;
01362       }
01363     }
01364 
01365     return COMPANY_FIRST;
01366   }
01367 
01368   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01369   {
01370     switch (widget) {
01371       case WID_NL_HEADER:
01372         size->height = WD_MATRIX_TOP + FONT_HEIGHT_NORMAL + WD_MATRIX_BOTTOM;
01373         break;
01374 
01375       case WID_NL_MATRIX:
01376         resize->height = WD_MATRIX_TOP + FONT_HEIGHT_NORMAL + WD_MATRIX_BOTTOM;
01377         size->height = 10 * resize->height;
01378         break;
01379 
01380       case WID_NL_DETAILS:
01381         size->height = 30 + 11 * FONT_HEIGHT_NORMAL;
01382         break;
01383     }
01384   }
01385 
01386   virtual void SetStringParameters(int widget) const
01387   {
01388     switch (widget) {
01389       case WID_NL_TEXT:
01390         SetDParamStr(0, this->server->info.server_name);
01391         break;
01392     }
01393   }
01394 
01395   virtual void DrawWidget(const Rect &r, int widget) const
01396   {
01397     switch (widget) {
01398       case WID_NL_DETAILS:
01399         this->DrawDetails(r);
01400         break;
01401 
01402       case WID_NL_MATRIX:
01403         this->DrawMatrix(r);
01404         break;
01405     }
01406   }
01407 
01408   virtual void OnPaint()
01409   {
01410     const NetworkGameInfo *gi = &this->server->info;
01411 
01412     /* Join button is disabled when no company is selected and for AI companies*/
01413     this->SetWidgetDisabledState(WID_NL_JOIN, this->company == INVALID_COMPANY || GetLobbyCompanyInfo(this->company)->ai);
01414     /* Cannot start new company if there are too many */
01415     this->SetWidgetDisabledState(WID_NL_NEW, gi->companies_on >= gi->companies_max);
01416     /* Cannot spectate if there are too many spectators */
01417     this->SetWidgetDisabledState(WID_NL_SPECTATE, gi->spectators_on >= gi->spectators_max);
01418 
01419     this->vscroll->SetCount(gi->companies_on);
01420 
01421     /* Draw window widgets */
01422     this->DrawWidgets();
01423   }
01424 
01425   void DrawMatrix(const Rect &r) const
01426   {
01427     bool rtl = _current_text_dir == TD_RTL;
01428     uint left = r.left + WD_FRAMERECT_LEFT;
01429     uint right = r.right - WD_FRAMERECT_RIGHT;
01430 
01431     Dimension lock_size = GetSpriteSize(SPR_LOCK);
01432     int lock_width      = lock_size.width;
01433     int lock_y_offset   = (this->resize.step_height - WD_MATRIX_TOP - WD_MATRIX_BOTTOM - lock_size.height) / 2;
01434 
01435     Dimension profit_size = GetSpriteSize(SPR_PROFIT_LOT);
01436     int profit_width      = lock_size.width;
01437     int profit_y_offset   = (this->resize.step_height - WD_MATRIX_TOP - WD_MATRIX_BOTTOM - profit_size.height) / 2;
01438 
01439     uint text_left   = left  + (rtl ? lock_width + profit_width + 4 : 0);
01440     uint text_right  = right - (rtl ? 0 : lock_width + profit_width + 4);
01441     uint profit_left = rtl ? left : right - profit_width;
01442     uint lock_left   = rtl ? left + profit_width + 2 : right - profit_width - lock_width - 2;
01443 
01444     int y = r.top + WD_MATRIX_TOP;
01445     /* Draw company list */
01446     int pos = this->vscroll->GetPosition();
01447     while (pos < this->server->info.companies_on) {
01448       byte company = NetworkLobbyFindCompanyIndex(pos);
01449       bool income = false;
01450       if (this->company == company) {
01451         GfxFillRect(r.left + 1, y - 2, r.right - 1, y + FONT_HEIGHT_NORMAL, PC_GREY); // show highlighted item with a different colour
01452       }
01453 
01454       DrawString(text_left, text_right, y, this->company_info[company].company_name, TC_BLACK);
01455       if (this->company_info[company].use_password != 0) DrawSprite(SPR_LOCK, PAL_NONE, lock_left, y + lock_y_offset);
01456 
01457       /* If the company's income was positive puts a green dot else a red dot */
01458       if (this->company_info[company].income >= 0) income = true;
01459       DrawSprite(income ? SPR_PROFIT_LOT : SPR_PROFIT_NEGATIVE, PAL_NONE, profit_left, y + profit_y_offset);
01460 
01461       pos++;
01462       y += this->resize.step_height;
01463       if (pos >= this->vscroll->GetPosition() + this->vscroll->GetCapacity()) break;
01464     }
01465   }
01466 
01467   void DrawDetails(const Rect &r) const
01468   {
01469     const int detail_height = 12 + FONT_HEIGHT_NORMAL + 12;
01470     /* Draw info about selected company when it is selected in the left window */
01471     GfxFillRect(r.left + 1, r.top + 1, r.right - 1, r.top + detail_height - 1, PC_DARK_BLUE);
01472     DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + 12, STR_NETWORK_GAME_LOBBY_COMPANY_INFO, TC_FROMSTRING, SA_HOR_CENTER);
01473 
01474     if (this->company == INVALID_COMPANY || StrEmpty(this->company_info[this->company].company_name)) return;
01475 
01476     int y = r.top + detail_height + 4;
01477     const NetworkGameInfo *gi = &this->server->info;
01478 
01479     SetDParam(0, gi->clients_on);
01480     SetDParam(1, gi->clients_max);
01481     SetDParam(2, gi->companies_on);
01482     SetDParam(3, gi->companies_max);
01483     DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_NETWORK_SERVER_LIST_CLIENTS);
01484     y += FONT_HEIGHT_NORMAL;
01485 
01486     SetDParamStr(0, this->company_info[this->company].company_name);
01487     DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_NETWORK_GAME_LOBBY_COMPANY_NAME);
01488     y += FONT_HEIGHT_NORMAL;
01489 
01490     SetDParam(0, this->company_info[this->company].inaugurated_year);
01491     DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_NETWORK_GAME_LOBBY_INAUGURATION_YEAR); // inauguration year
01492     y += FONT_HEIGHT_NORMAL;
01493 
01494     SetDParam(0, this->company_info[this->company].company_value);
01495     DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_NETWORK_GAME_LOBBY_VALUE); // company value
01496     y += FONT_HEIGHT_NORMAL;
01497 
01498     SetDParam(0, this->company_info[this->company].money);
01499     DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_NETWORK_GAME_LOBBY_CURRENT_BALANCE); // current balance
01500     y += FONT_HEIGHT_NORMAL;
01501 
01502     SetDParam(0, this->company_info[this->company].income);
01503     DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_NETWORK_GAME_LOBBY_LAST_YEARS_INCOME); // last year's income
01504     y += FONT_HEIGHT_NORMAL;
01505 
01506     SetDParam(0, this->company_info[this->company].performance);
01507     DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_NETWORK_GAME_LOBBY_PERFORMANCE); // performance
01508     y += FONT_HEIGHT_NORMAL;
01509 
01510     SetDParam(0, this->company_info[this->company].num_vehicle[NETWORK_VEH_TRAIN]);
01511     SetDParam(1, this->company_info[this->company].num_vehicle[NETWORK_VEH_LORRY]);
01512     SetDParam(2, this->company_info[this->company].num_vehicle[NETWORK_VEH_BUS]);
01513     SetDParam(3, this->company_info[this->company].num_vehicle[NETWORK_VEH_SHIP]);
01514     SetDParam(4, this->company_info[this->company].num_vehicle[NETWORK_VEH_PLANE]);
01515     DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_NETWORK_GAME_LOBBY_VEHICLES); // vehicles
01516     y += FONT_HEIGHT_NORMAL;
01517 
01518     SetDParam(0, this->company_info[this->company].num_station[NETWORK_VEH_TRAIN]);
01519     SetDParam(1, this->company_info[this->company].num_station[NETWORK_VEH_LORRY]);
01520     SetDParam(2, this->company_info[this->company].num_station[NETWORK_VEH_BUS]);
01521     SetDParam(3, this->company_info[this->company].num_station[NETWORK_VEH_SHIP]);
01522     SetDParam(4, this->company_info[this->company].num_station[NETWORK_VEH_PLANE]);
01523     DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_NETWORK_GAME_LOBBY_STATIONS); // stations
01524     y += FONT_HEIGHT_NORMAL;
01525 
01526     SetDParamStr(0, this->company_info[this->company].clients);
01527     DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_NETWORK_GAME_LOBBY_PLAYERS); // players
01528   }
01529 
01530   virtual void OnClick(Point pt, int widget, int click_count)
01531   {
01532     switch (widget) {
01533       case WID_NL_CANCEL:   // Cancel button
01534         ShowNetworkGameWindow();
01535         break;
01536 
01537       case WID_NL_MATRIX: { // Company list
01538         uint id_v = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NL_MATRIX);
01539         this->company = (id_v >= this->server->info.companies_on) ? INVALID_COMPANY : NetworkLobbyFindCompanyIndex(id_v);
01540         this->SetDirty();
01541 
01542         /* FIXME the disabling should go into some InvalidateData, which is called instead of the SetDirty */
01543         if (click_count > 1 && !this->IsWidgetDisabled(WID_NL_JOIN)) this->OnClick(pt, WID_NL_JOIN, 1);
01544         break;
01545       }
01546 
01547       case WID_NL_JOIN:     // Join company
01548         /* Button can be clicked only when it is enabled */
01549         NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port), this->company);
01550         break;
01551 
01552       case WID_NL_NEW:      // New company
01553         NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port), COMPANY_NEW_COMPANY);
01554         break;
01555 
01556       case WID_NL_SPECTATE: // Spectate game
01557         NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port), COMPANY_SPECTATOR);
01558         break;
01559 
01560       case WID_NL_REFRESH:  // Refresh
01561         NetworkTCPQueryServer(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port)); // company info
01562         NetworkUDPQueryServer(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port)); // general data
01563         /* Clear the information so removed companies don't remain */
01564         memset(this->company_info, 0, sizeof(this->company_info));
01565         break;
01566     }
01567   }
01568 
01569   virtual void OnResize()
01570   {
01571     this->vscroll->SetCapacityFromWidget(this, WID_NL_MATRIX);
01572     this->GetWidget<NWidgetCore>(WID_NL_MATRIX)->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
01573   }
01574 };
01575 
01576 static const NWidgetPart _nested_network_lobby_window_widgets[] = {
01577   NWidget(NWID_HORIZONTAL),
01578     NWidget(WWT_CLOSEBOX, COLOUR_LIGHT_BLUE),
01579     NWidget(WWT_CAPTION, COLOUR_LIGHT_BLUE), SetDataTip(STR_NETWORK_GAME_LOBBY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
01580   EndContainer(),
01581   NWidget(WWT_PANEL, COLOUR_LIGHT_BLUE, WID_NL_BACKGROUND),
01582     NWidget(WWT_TEXT, COLOUR_LIGHT_BLUE, WID_NL_TEXT), SetDataTip(STR_NETWORK_GAME_LOBBY_PREPARE_TO_JOIN, STR_NULL), SetResize(1, 0), SetPadding(10, 10, 0, 10),
01583     NWidget(NWID_SPACER), SetMinimalSize(0, 3),
01584     NWidget(NWID_HORIZONTAL), SetPIP(10, 0, 10),
01585       /* Company list. */
01586       NWidget(NWID_VERTICAL),
01587         NWidget(WWT_PANEL, COLOUR_WHITE, WID_NL_HEADER), SetMinimalSize(146, 0), SetResize(1, 0), SetFill(1, 0), EndContainer(),
01588         NWidget(WWT_MATRIX, COLOUR_LIGHT_BLUE, WID_NL_MATRIX), SetMinimalSize(146, 0), SetResize(1, 1), SetFill(1, 1), SetDataTip(0, STR_NETWORK_GAME_LOBBY_COMPANY_LIST_TOOLTIP), SetScrollbar(WID_NL_SCROLLBAR),
01589       EndContainer(),
01590       NWidget(NWID_VSCROLLBAR, COLOUR_LIGHT_BLUE, WID_NL_SCROLLBAR),
01591       NWidget(NWID_SPACER), SetMinimalSize(5, 0), SetResize(0, 1),
01592       /* Company info. */
01593       NWidget(WWT_PANEL, COLOUR_LIGHT_BLUE, WID_NL_DETAILS), SetMinimalSize(232, 0), SetResize(1, 1), SetFill(1, 1), EndContainer(),
01594     EndContainer(),
01595     NWidget(NWID_SPACER), SetMinimalSize(0, 9),
01596     /* Buttons. */
01597     NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(10, 3, 10),
01598       NWidget(NWID_VERTICAL, NC_EQUALSIZE), SetPIP(0, 3, 0),
01599         NWidget(WWT_PUSHTXTBTN, COLOUR_WHITE, WID_NL_JOIN), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_NETWORK_GAME_LOBBY_JOIN_COMPANY, STR_NETWORK_GAME_LOBBY_JOIN_COMPANY_TOOLTIP),
01600         NWidget(WWT_PUSHTXTBTN, COLOUR_WHITE, WID_NL_NEW), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_NETWORK_GAME_LOBBY_NEW_COMPANY, STR_NETWORK_GAME_LOBBY_NEW_COMPANY_TOOLTIP),
01601       EndContainer(),
01602       NWidget(NWID_VERTICAL, NC_EQUALSIZE), SetPIP(0, 3, 0),
01603         NWidget(WWT_PUSHTXTBTN, COLOUR_WHITE, WID_NL_SPECTATE), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_NETWORK_GAME_LOBBY_SPECTATE_GAME, STR_NETWORK_GAME_LOBBY_SPECTATE_GAME_TOOLTIP),
01604         NWidget(WWT_PUSHTXTBTN, COLOUR_WHITE, WID_NL_REFRESH), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_NETWORK_SERVER_LIST_REFRESH, STR_NETWORK_SERVER_LIST_REFRESH_TOOLTIP),
01605       EndContainer(),
01606       NWidget(NWID_VERTICAL, NC_EQUALSIZE), SetPIP(0, 3, 0),
01607         NWidget(WWT_PUSHTXTBTN, COLOUR_WHITE, WID_NL_CANCEL), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_BUTTON_CANCEL, STR_NULL),
01608         NWidget(NWID_SPACER), SetFill(1, 1),
01609       EndContainer(),
01610     EndContainer(),
01611     NWidget(NWID_SPACER), SetMinimalSize(0, 8),
01612   EndContainer(),
01613 };
01614 
01615 static const WindowDesc _network_lobby_window_desc(
01616   WDP_CENTER, 0, 0,
01617   WC_NETWORK_WINDOW, WC_NONE,
01618   WDF_UNCLICK_BUTTONS,
01619   _nested_network_lobby_window_widgets, lengthof(_nested_network_lobby_window_widgets)
01620 );
01621 
01626 static void ShowNetworkLobbyWindow(NetworkGameList *ngl)
01627 {
01628   DeleteWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_START);
01629   DeleteWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_GAME);
01630 
01631   NetworkTCPQueryServer(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port)); // company info
01632   NetworkUDPQueryServer(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port)); // general data
01633 
01634   new NetworkLobbyWindow(&_network_lobby_window_desc, ngl);
01635 }
01636 
01642 NetworkCompanyInfo *GetLobbyCompanyInfo(CompanyID company)
01643 {
01644   NetworkLobbyWindow *lobby = dynamic_cast<NetworkLobbyWindow*>(FindWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_LOBBY));
01645   return (lobby != NULL && company < MAX_COMPANIES) ? &lobby->company_info[company] : NULL;
01646 }
01647 
01648 /* The window below gives information about the connected clients
01649  *  and also makes able to give money to them, kick them (if server)
01650  *  and stuff like that. */
01651 
01652 extern void DrawCompanyIcon(CompanyID cid, int x, int y);
01653 
01658 typedef void ClientList_Action_Proc(const NetworkClientInfo *ci);
01659 
01660 static const NWidgetPart _nested_client_list_popup_widgets[] = {
01661   NWidget(WWT_PANEL, COLOUR_GREY, WID_CLP_PANEL), EndContainer(),
01662 };
01663 
01664 static const WindowDesc _client_list_popup_desc(
01665   WDP_AUTO, 0, 0,
01666   WC_CLIENT_LIST_POPUP, WC_CLIENT_LIST,
01667   0,
01668   _nested_client_list_popup_widgets, lengthof(_nested_client_list_popup_widgets)
01669 );
01670 
01671 /* Here we start to define the options out of the menu */
01672 static void ClientList_Kick(const NetworkClientInfo *ci)
01673 {
01674   NetworkServerKickClient(ci->client_id);
01675 }
01676 
01677 static void ClientList_Ban(const NetworkClientInfo *ci)
01678 {
01679   NetworkServerKickOrBanIP(ci->client_id, true);
01680 }
01681 
01682 static void ClientList_GiveMoney(const NetworkClientInfo *ci)
01683 {
01684   ShowNetworkGiveMoneyWindow(ci->client_playas);
01685 }
01686 
01687 static void ClientList_SpeakToClient(const NetworkClientInfo *ci)
01688 {
01689   ShowNetworkChatQueryWindow(DESTTYPE_CLIENT,ci->client_id);
01690 }
01691 
01692 static void ClientList_SpeakToCompany(const NetworkClientInfo *ci)
01693 {
01694   ShowNetworkChatQueryWindow(DESTTYPE_TEAM, ci->client_playas);
01695 }
01696 
01697 static void ClientList_SpeakToAll(const NetworkClientInfo *ci)
01698 {
01699   ShowNetworkChatQueryWindow(DESTTYPE_BROADCAST, 0);
01700 }
01701 
01703 struct NetworkClientListPopupWindow : Window {
01705   struct ClientListAction {
01706     StringID name;                
01707     ClientList_Action_Proc *proc; 
01708   };
01709 
01710   uint sel_index;
01711   ClientID client_id;
01712   Point desired_location;
01713   SmallVector<ClientListAction, 2> actions; 
01714 
01720   inline void AddAction(StringID name, ClientList_Action_Proc *proc)
01721   {
01722     ClientListAction *action = this->actions.Append();
01723     action->name = name;
01724     action->proc = proc;
01725   }
01726 
01727   NetworkClientListPopupWindow(const WindowDesc *desc, int x, int y, ClientID client_id) :
01728       Window(),
01729       sel_index(0), client_id(client_id)
01730   {
01731     this->desired_location.x = x;
01732     this->desired_location.y = y;
01733 
01734     const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
01735 
01736     if (_network_own_client_id != ci->client_id) {
01737       this->AddAction(STR_NETWORK_CLIENTLIST_SPEAK_TO_CLIENT, &ClientList_SpeakToClient);
01738     }
01739 
01740     if (Company::IsValidID(ci->client_playas) || ci->client_playas == COMPANY_SPECTATOR) {
01741       this->AddAction(STR_NETWORK_CLIENTLIST_SPEAK_TO_COMPANY, &ClientList_SpeakToCompany);
01742     }
01743     this->AddAction(STR_NETWORK_CLIENTLIST_SPEAK_TO_ALL, &ClientList_SpeakToAll);
01744 
01745     if (_network_own_client_id != ci->client_id) {
01746       /* We are no spectator and the company we want to give money to is no spectator and money gifts are allowed */
01747       if (Company::IsValidID(_local_company) && Company::IsValidID(ci->client_playas) && _settings_game.economy.give_money) {
01748         this->AddAction(STR_NETWORK_CLIENTLIST_GIVE_MONEY, &ClientList_GiveMoney);
01749       }
01750     }
01751 
01752     /* A server can kick clients (but not himself) */
01753     if (_network_server && _network_own_client_id != ci->client_id) {
01754       this->AddAction(STR_NETWORK_CLIENTLIST_KICK, &ClientList_Kick);
01755       this->AddAction(STR_NETWORK_CLIENTLIST_BAN, &ClientList_Ban);
01756     }
01757 
01758     this->InitNested(desc, client_id);
01759     CLRBITS(this->flags, WF_WHITE_BORDER);
01760   }
01761 
01762   virtual Point OnInitialPosition(const WindowDesc *desc, int16 sm_width, int16 sm_height, int window_number)
01763   {
01764     return this->desired_location;
01765   }
01766 
01767   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01768   {
01769     Dimension d = *size;
01770     for (const ClientListAction *action = this->actions.Begin(); action != this->actions.End(); action++) {
01771       d = maxdim(GetStringBoundingBox(action->name), d);
01772     }
01773 
01774     d.height *= this->actions.Length();
01775     d.width += WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
01776     d.height += WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
01777     *size = d;
01778   }
01779 
01780   virtual void DrawWidget(const Rect &r, int widget) const
01781   {
01782     /* Draw the actions */
01783     int sel = this->sel_index;
01784     int y = r.top + WD_FRAMERECT_TOP;
01785     for (const ClientListAction *action = this->actions.Begin(); action != this->actions.End(); action++, y += FONT_HEIGHT_NORMAL) {
01786       TextColour colour;
01787       if (sel-- == 0) { // Selected item, highlight it
01788         GfxFillRect(r.left + 1, y, r.right - 1, y + FONT_HEIGHT_NORMAL - 1, PC_BLACK);
01789         colour = TC_WHITE;
01790       } else {
01791         colour = TC_BLACK;
01792       }
01793 
01794       DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, action->name, colour);
01795     }
01796   }
01797 
01798   virtual void OnMouseLoop()
01799   {
01800     /* We selected an action */
01801     uint index = (_cursor.pos.y - this->top - WD_FRAMERECT_TOP) / FONT_HEIGHT_NORMAL;
01802 
01803     if (_left_button_down) {
01804       if (index == this->sel_index || index >= this->actions.Length()) return;
01805 
01806       this->sel_index = index;
01807       this->SetDirty();
01808     } else {
01809       if (index < this->actions.Length() && _cursor.pos.y >= this->top) {
01810         const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(this->client_id);
01811         if (ci != NULL) this->actions[index].proc(ci);
01812       }
01813 
01814       DeleteWindowByClass(WC_CLIENT_LIST_POPUP);
01815     }
01816   }
01817 };
01818 
01822 static void PopupClientList(ClientID client_id, int x, int y)
01823 {
01824   DeleteWindowByClass(WC_CLIENT_LIST_POPUP);
01825 
01826   if (NetworkClientInfo::GetByClientID(client_id) == NULL) return;
01827 
01828   new NetworkClientListPopupWindow(&_client_list_popup_desc, x, y, client_id);
01829 }
01830 
01831 static const NWidgetPart _nested_client_list_widgets[] = {
01832   NWidget(NWID_HORIZONTAL),
01833     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
01834     NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_NETWORK_COMPANY_LIST_CLIENT_LIST, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
01835     NWidget(WWT_STICKYBOX, COLOUR_GREY),
01836   EndContainer(),
01837   NWidget(WWT_PANEL, COLOUR_GREY, WID_CL_PANEL), SetMinimalSize(250, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM), SetResize(1, 1), EndContainer(),
01838 };
01839 
01840 static const WindowDesc _client_list_desc(
01841   WDP_AUTO, 0, 0,
01842   WC_CLIENT_LIST, WC_NONE,
01843   0,
01844   _nested_client_list_widgets, lengthof(_nested_client_list_widgets)
01845 );
01846 
01850 struct NetworkClientListWindow : Window {
01851   int selected_item;
01852 
01853   uint server_client_width;
01854   uint company_icon_width;
01855 
01856   NetworkClientListWindow(const WindowDesc *desc, WindowNumber window_number) :
01857       Window(),
01858       selected_item(-1)
01859   {
01860     this->InitNested(desc, window_number);
01861   }
01862 
01866   bool CheckClientListHeight()
01867   {
01868     int num = 0;
01869     const NetworkClientInfo *ci;
01870 
01871     /* Should be replaced with a loop through all clients */
01872     FOR_ALL_CLIENT_INFOS(ci) {
01873       if (ci->client_playas != COMPANY_INACTIVE_CLIENT) num++;
01874     }
01875 
01876     num *= FONT_HEIGHT_NORMAL;
01877 
01878     int diff = (num + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM) - (this->GetWidget<NWidgetBase>(WID_CL_PANEL)->current_y);
01879     /* If height is changed */
01880     if (diff != 0) {
01881       ResizeWindow(this, 0, diff);
01882       return false;
01883     }
01884     return true;
01885   }
01886 
01887   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01888   {
01889     if (widget != WID_CL_PANEL) return;
01890 
01891     this->server_client_width = max(GetStringBoundingBox(STR_NETWORK_SERVER).width, GetStringBoundingBox(STR_NETWORK_CLIENT).width) + WD_FRAMERECT_RIGHT;
01892     this->company_icon_width = GetSpriteSize(SPR_COMPANY_ICON).width + WD_FRAMERECT_LEFT;
01893 
01894     uint width = 100; // Default width
01895     const NetworkClientInfo *ci;
01896     FOR_ALL_CLIENT_INFOS(ci) {
01897       width = max(width, GetStringBoundingBox(ci->client_name).width);
01898     }
01899 
01900     size->width = WD_FRAMERECT_LEFT + this->server_client_width + this->company_icon_width + width + WD_FRAMERECT_RIGHT;
01901   }
01902 
01903   virtual void OnPaint()
01904   {
01905     /* Check if we need to reset the height */
01906     if (!this->CheckClientListHeight()) return;
01907 
01908     this->DrawWidgets();
01909   }
01910 
01911   virtual void DrawWidget(const Rect &r, int widget) const
01912   {
01913     if (widget != WID_CL_PANEL) return;
01914 
01915     bool rtl = _current_text_dir == TD_RTL;
01916     int icon_y_offset = 1 + (FONT_HEIGHT_NORMAL - 10) / 2;
01917     uint y = r.top + WD_FRAMERECT_TOP;
01918     uint left = r.left + WD_FRAMERECT_LEFT;
01919     uint right = r.right - WD_FRAMERECT_RIGHT;
01920     uint type_icon_width = this->server_client_width + this->company_icon_width;
01921 
01922 
01923     uint type_left  = rtl ? right - this->server_client_width : left;
01924     uint type_right = rtl ? right : left + this->server_client_width - 1;
01925     uint icon_left  = rtl ? right - type_icon_width + WD_FRAMERECT_LEFT : left + this->server_client_width;
01926     uint name_left  = rtl ? left : left + type_icon_width;
01927     uint name_right = rtl ? right - type_icon_width : right;
01928 
01929     int i = 0;
01930     const NetworkClientInfo *ci;
01931     FOR_ALL_CLIENT_INFOS(ci) {
01932       TextColour colour;
01933       if (this->selected_item == i++) { // Selected item, highlight it
01934         GfxFillRect(r.left + 1, y, r.right - 1, y + FONT_HEIGHT_NORMAL - 1, PC_BLACK);
01935         colour = TC_WHITE;
01936       } else {
01937         colour = TC_BLACK;
01938       }
01939 
01940       if (ci->client_id == CLIENT_ID_SERVER) {
01941         DrawString(type_left, type_right, y, STR_NETWORK_SERVER, colour);
01942       } else {
01943         DrawString(type_left, type_right, y, STR_NETWORK_CLIENT, colour);
01944       }
01945 
01946       /* Filter out spectators */
01947       if (Company::IsValidID(ci->client_playas)) DrawCompanyIcon(ci->client_playas, icon_left, y + icon_y_offset);
01948 
01949       DrawString(name_left, name_right, y, ci->client_name, colour);
01950 
01951       y += FONT_HEIGHT_NORMAL;
01952     }
01953   }
01954 
01955   virtual void OnClick(Point pt, int widget, int click_count)
01956   {
01957     /* Show the popup with option */
01958     if (this->selected_item != -1) {
01959       NetworkClientInfo *ci;
01960 
01961       int client_no = this->selected_item;
01962       FOR_ALL_CLIENT_INFOS(ci) {
01963         if (client_no == 0) break;
01964         client_no--;
01965       }
01966 
01967       if (ci != NULL) PopupClientList(ci->client_id, pt.x + this->left, pt.y + this->top);
01968     }
01969   }
01970 
01971   virtual void OnMouseOver(Point pt, int widget)
01972   {
01973     /* -1 means we left the current window */
01974     if (pt.y == -1) {
01975       this->selected_item = -1;
01976       this->SetDirty();
01977       return;
01978     }
01979 
01980     /* Find the new selected item (if any) */
01981     pt.y -= this->GetWidget<NWidgetBase>(WID_CL_PANEL)->pos_y;
01982     int item = -1;
01983     if (IsInsideMM(pt.y, WD_FRAMERECT_TOP, this->GetWidget<NWidgetBase>(WID_CL_PANEL)->current_y - WD_FRAMERECT_BOTTOM)) {
01984       item = (pt.y - WD_FRAMERECT_TOP) / FONT_HEIGHT_NORMAL;
01985     }
01986 
01987     /* It did not change.. no update! */
01988     if (item == this->selected_item) return;
01989     this->selected_item = item;
01990 
01991     /* Repaint */
01992     this->SetDirty();
01993   }
01994 };
01995 
01996 void ShowClientList()
01997 {
01998   AllocateWindowDescFront<NetworkClientListWindow>(&_client_list_desc, 0);
01999 }
02000 
02001 NetworkJoinStatus _network_join_status; 
02002 uint8 _network_join_waiting;            
02003 uint32 _network_join_bytes;             
02004 uint32 _network_join_bytes_total;       
02005 
02006 struct NetworkJoinStatusWindow : Window {
02007   NetworkPasswordType password_type;
02008 
02009   NetworkJoinStatusWindow(const WindowDesc *desc) : Window()
02010   {
02011     this->parent = FindWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_GAME);
02012     this->InitNested(desc, WN_NETWORK_STATUS_WINDOW_JOIN);
02013   }
02014 
02015   virtual void DrawWidget(const Rect &r, int widget) const
02016   {
02017     if (widget != WID_NJS_BACKGROUND) return;
02018 
02019     uint8 progress; // used for progress bar
02020     DrawString(r.left + 2, r.right - 2, r.top + 20, STR_NETWORK_CONNECTING_1 + _network_join_status, TC_FROMSTRING, SA_HOR_CENTER);
02021     switch (_network_join_status) {
02022       case NETWORK_JOIN_STATUS_CONNECTING: case NETWORK_JOIN_STATUS_AUTHORIZING:
02023       case NETWORK_JOIN_STATUS_GETTING_COMPANY_INFO:
02024         progress = 10; // first two stages 10%
02025         break;
02026       case NETWORK_JOIN_STATUS_WAITING:
02027         SetDParam(0, _network_join_waiting);
02028         DrawString(r.left + 2, r.right - 2, r.top + 20 + FONT_HEIGHT_NORMAL, STR_NETWORK_CONNECTING_WAITING, TC_FROMSTRING, SA_HOR_CENTER);
02029         progress = 15; // third stage is 15%
02030         break;
02031       case NETWORK_JOIN_STATUS_DOWNLOADING:
02032         SetDParam(0, _network_join_bytes);
02033         SetDParam(1, _network_join_bytes_total);
02034         DrawString(r.left + 2, r.right - 2, r.top + 20 + FONT_HEIGHT_NORMAL, _network_join_bytes_total == 0 ? STR_NETWORK_CONNECTING_DOWNLOADING_1 : STR_NETWORK_CONNECTING_DOWNLOADING_2, TC_FROMSTRING, SA_HOR_CENTER);
02035         if (_network_join_bytes_total == 0) {
02036           progress = 15; // We don't have the final size yet; the server is still compressing!
02037           break;
02038         }
02039         /* FALL THROUGH */
02040       default: // Waiting is 15%, so the resting receivement of map is maximum 70%
02041         progress = 15 + _network_join_bytes * (100 - 15) / _network_join_bytes_total;
02042     }
02043 
02044     /* Draw nice progress bar :) */
02045     DrawFrameRect(r.left + 20, r.top + 5, (int)((this->width - 20) * progress / 100), r.top + 15, COLOUR_MAUVE, FR_NONE);
02046   }
02047 
02048   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
02049   {
02050     if (widget != WID_NJS_BACKGROUND) return;
02051 
02052     size->height = 25 + 2 * FONT_HEIGHT_NORMAL;
02053 
02054     /* Account for the statuses */
02055     uint width = 0;
02056     for (uint i = 0; i < NETWORK_JOIN_STATUS_END; i++) {
02057       width = max(width, GetStringBoundingBox(STR_NETWORK_CONNECTING_1 + i).width);
02058     }
02059 
02060     /* For the number of waiting (other) players */
02061     SetDParam(0, 255);
02062     width = max(width, GetStringBoundingBox(STR_NETWORK_CONNECTING_WAITING).width);
02063 
02064     /* Account for downloading ~ 10 MiB */
02065     SetDParam(0, 10000000);
02066     SetDParam(1, 10000000);
02067     width = max(width, GetStringBoundingBox(STR_NETWORK_CONNECTING_DOWNLOADING_1).width);
02068     width = max(width, GetStringBoundingBox(STR_NETWORK_CONNECTING_DOWNLOADING_2).width);
02069 
02070     /* Give a bit more clearing for the widest strings than strictly needed */
02071     size->width = width + WD_FRAMERECT_LEFT + WD_FRAMERECT_BOTTOM + 10;
02072   }
02073 
02074   virtual void OnClick(Point pt, int widget, int click_count)
02075   {
02076     if (widget == WID_NJS_CANCELOK) { // Disconnect button
02077       NetworkDisconnect();
02078       SwitchToMode(SM_MENU);
02079       ShowNetworkGameWindow();
02080     }
02081   }
02082 
02083   virtual void OnQueryTextFinished(char *str)
02084   {
02085     if (StrEmpty(str)) {
02086       NetworkDisconnect();
02087       ShowNetworkGameWindow();
02088       return;
02089     }
02090 
02091     switch (this->password_type) {
02092       case NETWORK_GAME_PASSWORD:    MyClient::SendGamePassword   (str); break;
02093       case NETWORK_COMPANY_PASSWORD: MyClient::SendCompanyPassword(str); break;
02094       default: NOT_REACHED();
02095     }
02096   }
02097 };
02098 
02099 static const NWidgetPart _nested_network_join_status_window_widgets[] = {
02100   NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_NETWORK_CONNECTING_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
02101   NWidget(WWT_PANEL, COLOUR_GREY),
02102     NWidget(WWT_EMPTY, COLOUR_GREY, WID_NJS_BACKGROUND),
02103     NWidget(NWID_HORIZONTAL),
02104       NWidget(NWID_SPACER), SetMinimalSize(75, 0), SetFill(1, 0),
02105       NWidget(WWT_PUSHTXTBTN, COLOUR_WHITE, WID_NJS_CANCELOK), SetMinimalSize(101, 12), SetDataTip(STR_NETWORK_CONNECTION_DISCONNECT, STR_NULL),
02106       NWidget(NWID_SPACER), SetMinimalSize(75, 0), SetFill(1, 0),
02107     EndContainer(),
02108     NWidget(NWID_SPACER), SetMinimalSize(0, 4),
02109   EndContainer(),
02110 };
02111 
02112 static const WindowDesc _network_join_status_window_desc(
02113   WDP_CENTER, 0, 0,
02114   WC_NETWORK_STATUS_WINDOW, WC_NONE,
02115   WDF_MODAL,
02116   _nested_network_join_status_window_widgets, lengthof(_nested_network_join_status_window_widgets)
02117 );
02118 
02119 void ShowJoinStatusWindow()
02120 {
02121   DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
02122   new NetworkJoinStatusWindow(&_network_join_status_window_desc);
02123 }
02124 
02125 void ShowNetworkNeedPassword(NetworkPasswordType npt)
02126 {
02127   NetworkJoinStatusWindow *w = (NetworkJoinStatusWindow *)FindWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
02128   if (w == NULL) return;
02129   w->password_type = npt;
02130 
02131   StringID caption;
02132   switch (npt) {
02133     default: NOT_REACHED();
02134     case NETWORK_GAME_PASSWORD:    caption = STR_NETWORK_NEED_GAME_PASSWORD_CAPTION; break;
02135     case NETWORK_COMPANY_PASSWORD: caption = STR_NETWORK_NEED_COMPANY_PASSWORD_CAPTION; break;
02136   }
02137   ShowQueryString(STR_EMPTY, caption, NETWORK_PASSWORD_LENGTH, w, CS_ALPHANUMERAL, QSF_NONE);
02138 }
02139 
02140 struct NetworkCompanyPasswordWindow : public QueryStringBaseWindow {
02141   NetworkCompanyPasswordWindow(const WindowDesc *desc, Window *parent) : QueryStringBaseWindow(lengthof(_settings_client.network.default_company_pass))
02142   {
02143     this->InitNested(desc, 0);
02144 
02145     this->parent = parent;
02146     this->afilter = CS_ALPHANUMERAL;
02147     InitializeTextBuffer(&this->text, this->edit_str_buf, this->edit_str_size);
02148     this->SetFocusedWidget(WID_NCP_PASSWORD);
02149   }
02150 
02151   void OnOk()
02152   {
02153     if (this->IsWidgetLowered(WID_NCP_SAVE_AS_DEFAULT_PASSWORD)) {
02154       snprintf(_settings_client.network.default_company_pass, lengthof(_settings_client.network.default_company_pass), "%s", this->edit_str_buf);
02155     }
02156 
02157     NetworkChangeCompanyPassword(_local_company, this->edit_str_buf);
02158   }
02159 
02160   virtual void OnPaint()
02161   {
02162     this->DrawWidgets();
02163     this->DrawEditBox(WID_NCP_PASSWORD);
02164   }
02165 
02166   virtual void OnClick(Point pt, int widget, int click_count)
02167   {
02168     switch (widget) {
02169       case WID_NCP_OK:
02170         this->OnOk();
02171         /* FALL THROUGH */
02172 
02173       case WID_NCP_CANCEL:
02174         delete this;
02175         break;
02176 
02177       case WID_NCP_SAVE_AS_DEFAULT_PASSWORD:
02178         this->ToggleWidgetLoweredState(WID_NCP_SAVE_AS_DEFAULT_PASSWORD);
02179         this->SetDirty();
02180         break;
02181     }
02182   }
02183 
02184   virtual void OnMouseLoop()
02185   {
02186     this->HandleEditBox(4);
02187   }
02188 
02189   virtual EventState OnKeyPress(uint16 key, uint16 keycode)
02190   {
02191     EventState state = ES_NOT_HANDLED;
02192     switch (this->HandleEditBoxKey(WID_NCP_PASSWORD, key, keycode, state)) {
02193       default: break;
02194 
02195       case HEBR_CONFIRM:
02196         this->OnOk();
02197         /* FALL THROUGH */
02198 
02199       case HEBR_CANCEL:
02200         delete this;
02201         break;
02202     }
02203     return state;
02204   }
02205 
02206   virtual void OnOpenOSKWindow(int wid)
02207   {
02208     ShowOnScreenKeyboard(this, wid, WID_NCP_CANCEL, WID_NCP_OK);
02209   }
02210 };
02211 
02212 static const NWidgetPart _nested_network_company_password_window_widgets[] = {
02213   NWidget(NWID_HORIZONTAL),
02214     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
02215     NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_COMPANY_PASSWORD_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
02216   EndContainer(),
02217   NWidget(WWT_PANEL, COLOUR_GREY, WID_NCP_BACKGROUND),
02218     NWidget(NWID_VERTICAL), SetPIP(5, 5, 5),
02219       NWidget(NWID_HORIZONTAL), SetPIP(5, 5, 5),
02220         NWidget(WWT_TEXT, COLOUR_GREY, WID_NCP_LABEL), SetDataTip(STR_COMPANY_VIEW_PASSWORD, STR_NULL),
02221         NWidget(WWT_EDITBOX, COLOUR_GREY, WID_NCP_PASSWORD), SetMinimalSize(194, 12), SetDataTip(STR_COMPANY_VIEW_SET_PASSWORD, STR_NULL),
02222       EndContainer(),
02223       NWidget(NWID_HORIZONTAL), SetPIP(5, 0, 5),
02224         NWidget(NWID_SPACER), SetFill(1, 0),
02225         NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_NCP_SAVE_AS_DEFAULT_PASSWORD), SetMinimalSize(194, 12),
02226                       SetDataTip(STR_COMPANY_PASSWORD_MAKE_DEFAULT, STR_COMPANY_PASSWORD_MAKE_DEFAULT_TOOLTIP),
02227       EndContainer(),
02228     EndContainer(),
02229   EndContainer(),
02230   NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
02231     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_NCP_CANCEL), SetFill(1, 0), SetDataTip(STR_BUTTON_CANCEL, STR_COMPANY_PASSWORD_CANCEL),
02232     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_NCP_OK), SetFill(1, 0), SetDataTip(STR_BUTTON_OK, STR_COMPANY_PASSWORD_OK),
02233   EndContainer(),
02234 };
02235 
02236 static const WindowDesc _network_company_password_window_desc(
02237   WDP_AUTO, 0, 0,
02238   WC_COMPANY_PASSWORD_WINDOW, WC_NONE,
02239   WDF_UNCLICK_BUTTONS,
02240   _nested_network_company_password_window_widgets, lengthof(_nested_network_company_password_window_widgets)
02241 );
02242 
02243 void ShowNetworkCompanyPasswordWindow(Window *parent)
02244 {
02245   DeleteWindowById(WC_COMPANY_PASSWORD_WINDOW, 0);
02246 
02247   new NetworkCompanyPasswordWindow(&_network_company_password_window_desc, parent);
02248 }
02249 
02250 #endif /* ENABLE_NETWORK */