network_gui.cpp

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