station_gui.cpp

Go to the documentation of this file.
00001 /* $Id$ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 #include "debug.h"
00014 #include "gui.h"
00015 #include "textbuf_gui.h"
00016 #include "company_func.h"
00017 #include "command_func.h"
00018 #include "vehicle_gui.h"
00019 #include "cargotype.h"
00020 #include "station_gui.h"
00021 #include "strings_func.h"
00022 #include "window_func.h"
00023 #include "viewport_func.h"
00024 #include "widgets/dropdown_func.h"
00025 #include "station_base.h"
00026 #include "waypoint_base.h"
00027 #include "tilehighlight_func.h"
00028 #include "company_base.h"
00029 #include "sortlist_type.h"
00030 #include "core/geometry_func.hpp"
00031 #include "vehiclelist.h"
00032 
00033 #include "table/strings.h"
00034 
00035 #include <vector>
00036 
00044 static int DrawCargoListText(uint32 cargo_mask, const Rect &r, StringID prefix)
00045 {
00046   bool first = true;
00047   char string[512];
00048   char *b = string;
00049 
00050   CargoID i;
00051   FOR_EACH_SET_CARGO_ID(i, cargo_mask) {
00052     if (b >= lastof(string) - (1 + 2 * 4)) break; // ',' or ' ' and two calls to Utf8Encode()
00053 
00054     if (first) {
00055       first = false;
00056     } else {
00057       /* Add a comma if this is not the first item */
00058       *b++ = ',';
00059       *b++ = ' ';
00060     }
00061     b = InlineString(b, CargoSpec::Get(i)->name);
00062   }
00063 
00064   /* If first is still true then no cargo is accepted */
00065   if (first) b = InlineString(b, STR_JUST_NOTHING);
00066 
00067   *b = '\0';
00068 
00069   /* Make sure we detect any buffer overflow */
00070   assert(b < endof(string));
00071 
00072   SetDParamStr(0, string);
00073   return DrawStringMultiLine(r.left, r.right, r.top, r.bottom, prefix);
00074 }
00075 
00086 int DrawStationCoverageAreaText(int left, int right, int top, StationCoverageType sct, int rad, bool supplies)
00087 {
00088   TileIndex tile = TileVirtXY(_thd.pos.x, _thd.pos.y);
00089   uint32 cargo_mask = 0;
00090   if (_thd.drawstyle == HT_RECT && tile < MapSize()) {
00091     CargoArray cargos;
00092     if (supplies) {
00093       cargos = GetProductionAroundTiles(tile, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE, rad);
00094     } else {
00095       cargos = GetAcceptanceAroundTiles(tile, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE, rad);
00096     }
00097 
00098     /* Convert cargo counts to a set of cargo bits, and draw the result. */
00099     for (CargoID i = 0; i < NUM_CARGO; i++) {
00100       switch (sct) {
00101         case SCT_PASSENGERS_ONLY: if (!IsCargoInClass(i, CC_PASSENGERS)) continue; break;
00102         case SCT_NON_PASSENGERS_ONLY: if (IsCargoInClass(i, CC_PASSENGERS)) continue; break;
00103         case SCT_ALL: break;
00104         default: NOT_REACHED();
00105       }
00106       if (cargos[i] >= (supplies ? 1U : 8U)) SetBit(cargo_mask, i);
00107     }
00108   }
00109   Rect r = {left, top, right, INT32_MAX};
00110   return DrawCargoListText(cargo_mask, r, supplies ? STR_STATION_BUILD_SUPPLIES_CARGO : STR_STATION_BUILD_ACCEPTS_CARGO);
00111 }
00112 
00118 void CheckRedrawStationCoverage(const Window *w)
00119 {
00120   if (_thd.dirty & 1) {
00121     _thd.dirty &= ~1;
00122     w->SetDirty();
00123   }
00124 }
00125 
00141 static void StationsWndShowStationRating(int left, int right, int y, CargoID type, uint amount, byte rating)
00142 {
00143   static const uint units_full  = 576; 
00144   static const uint rating_full = 224; 
00145 
00146   const CargoSpec *cs = CargoSpec::Get(type);
00147   if (!cs->IsValid()) return;
00148 
00149   int colour = cs->rating_colour;
00150   uint w = (minu(amount, units_full) + 5) / 36;
00151 
00152   int height = GetCharacterHeight(FS_SMALL);
00153 
00154   /* Draw total cargo (limited) on station (fits into 16 pixels) */
00155   if (w != 0) GfxFillRect(left, y, left + w - 1, y + height, colour);
00156 
00157   /* Draw a one pixel-wide bar of additional cargo meter, useful
00158    * for stations with only a small amount (<=30) */
00159   if (w == 0) {
00160     uint rest = amount / 5;
00161     if (rest != 0) {
00162       w += left;
00163       GfxFillRect(w, y + height - rest, w, y + height, colour);
00164     }
00165   }
00166 
00167   DrawString(left + 1, right, y, cs->abbrev, TC_BLACK);
00168 
00169   /* Draw green/red ratings bar (fits into 14 pixels) */
00170   y += height + 2;
00171   GfxFillRect(left + 1, y, left + 14, y, PC_RED);
00172   rating = minu(rating, rating_full) / 16;
00173   if (rating != 0) GfxFillRect(left + 1, y, left + rating, y, PC_GREEN);
00174 }
00175 
00176 typedef GUIList<const Station*> GUIStationList;
00177 
00179 enum StationListWidgets {
00180   SLW_CAPTION,        
00181   SLW_LIST,           
00182   SLW_SCROLLBAR,      
00183 
00184   /* Vehicletypes need to be in order of StationFacility due to bit magic */
00185   SLW_TRAIN,          
00186   SLW_TRUCK,          
00187   SLW_BUS,            
00188   SLW_AIRPLANE,       
00189   SLW_SHIP,           
00190   SLW_FACILALL,       
00191 
00192   SLW_NOCARGOWAITING, 
00193   SLW_CARGOALL,       
00194 
00195   SLW_SORTBY,         
00196   SLW_SORTDROPBTN,    
00197 
00198   SLW_CARGOSTART,     
00199 };
00200 
00204 class CompanyStationsWindow : public Window
00205 {
00206 protected:
00207   /* Runtime saved values */
00208   static Listing last_sorting;
00209   static byte facilities;               // types of stations of interest
00210   static bool include_empty;            // whether we should include stations without waiting cargo
00211   static const uint32 cargo_filter_max;
00212   static uint32 cargo_filter;           // bitmap of cargo types to include
00213   static const Station *last_station;
00214 
00215   /* Constants for sorting stations */
00216   static const StringID sorter_names[];
00217   static GUIStationList::SortFunction * const sorter_funcs[];
00218 
00219   GUIStationList stations;
00220   Scrollbar *vscroll;
00221 
00227   void BuildStationsList(const Owner owner)
00228   {
00229     if (!this->stations.NeedRebuild()) return;
00230 
00231     DEBUG(misc, 3, "Building station list for company %d", owner);
00232 
00233     this->stations.Clear();
00234 
00235     const Station *st;
00236     FOR_ALL_STATIONS(st) {
00237       if (st->owner == owner || (st->owner == OWNER_NONE && HasStationInUse(st->index, true, owner))) {
00238         if (this->facilities & st->facilities) { // only stations with selected facilities
00239           int num_waiting_cargo = 0;
00240           for (CargoID j = 0; j < NUM_CARGO; j++) {
00241             if (HasBit(st->goods[j].acceptance_pickup, GoodsEntry::GES_PICKUP)) {
00242               num_waiting_cargo++; // count number of waiting cargo
00243               if (HasBit(this->cargo_filter, j)) {
00244                 *this->stations.Append() = st;
00245                 break;
00246               }
00247             }
00248           }
00249           /* stations without waiting cargo */
00250           if (num_waiting_cargo == 0 && this->include_empty) {
00251             *this->stations.Append() = st;
00252           }
00253         }
00254       }
00255     }
00256 
00257     this->stations.Compact();
00258     this->stations.RebuildDone();
00259 
00260     this->vscroll->SetCount(this->stations.Length()); // Update the scrollbar
00261   }
00262 
00264   static int CDECL StationNameSorter(const Station * const *a, const Station * const *b)
00265   {
00266     static char buf_cache[64];
00267     char buf[64];
00268 
00269     SetDParam(0, (*a)->index);
00270     GetString(buf, STR_STATION_NAME, lastof(buf));
00271 
00272     if (*b != last_station) {
00273       last_station = *b;
00274       SetDParam(0, (*b)->index);
00275       GetString(buf_cache, STR_STATION_NAME, lastof(buf_cache));
00276     }
00277 
00278     return strcmp(buf, buf_cache);
00279   }
00280 
00282   static int CDECL StationTypeSorter(const Station * const *a, const Station * const *b)
00283   {
00284     return (*a)->facilities - (*b)->facilities;
00285   }
00286 
00288   static int CDECL StationWaitingSorter(const Station * const *a, const Station * const *b)
00289   {
00290     Money diff = 0;
00291 
00292     CargoID j;
00293     FOR_EACH_SET_CARGO_ID(j, cargo_filter) {
00294       if (!(*a)->goods[j].cargo.Empty()) diff += GetTransportedGoodsIncome((*a)->goods[j].cargo.Count(), 20, 50, j);
00295       if (!(*b)->goods[j].cargo.Empty()) diff -= GetTransportedGoodsIncome((*b)->goods[j].cargo.Count(), 20, 50, j);
00296     }
00297 
00298     return ClampToI32(diff);
00299   }
00300 
00302   static int CDECL StationRatingMaxSorter(const Station * const *a, const Station * const *b)
00303   {
00304     byte maxr1 = 0;
00305     byte maxr2 = 0;
00306 
00307     CargoID j;
00308     FOR_EACH_SET_CARGO_ID(j, cargo_filter) {
00309       if (HasBit((*a)->goods[j].acceptance_pickup, GoodsEntry::GES_PICKUP)) maxr1 = max(maxr1, (*a)->goods[j].rating);
00310       if (HasBit((*b)->goods[j].acceptance_pickup, GoodsEntry::GES_PICKUP)) maxr2 = max(maxr2, (*b)->goods[j].rating);
00311     }
00312 
00313     return maxr1 - maxr2;
00314   }
00315 
00317   static int CDECL StationRatingMinSorter(const Station * const *a, const Station * const *b)
00318   {
00319     byte minr1 = 255;
00320     byte minr2 = 255;
00321 
00322     for (CargoID j = 0; j < NUM_CARGO; j++) {
00323       if (!HasBit(cargo_filter, j)) continue;
00324       if (HasBit((*a)->goods[j].acceptance_pickup, GoodsEntry::GES_PICKUP)) minr1 = min(minr1, (*a)->goods[j].rating);
00325       if (HasBit((*b)->goods[j].acceptance_pickup, GoodsEntry::GES_PICKUP)) minr2 = min(minr2, (*b)->goods[j].rating);
00326     }
00327 
00328     return -(minr1 - minr2);
00329   }
00330 
00332   void SortStationsList()
00333   {
00334     if (!this->stations.Sort()) return;
00335 
00336     /* Reset name sorter sort cache */
00337     this->last_station = NULL;
00338 
00339     /* Set the modified widget dirty */
00340     this->SetWidgetDirty(SLW_LIST);
00341   }
00342 
00343 public:
00344   CompanyStationsWindow(const WindowDesc *desc, WindowNumber window_number) : Window()
00345   {
00346     this->stations.SetListing(this->last_sorting);
00347     this->stations.SetSortFuncs(this->sorter_funcs);
00348     this->stations.ForceRebuild();
00349     this->stations.NeedResort();
00350     this->SortStationsList();
00351 
00352     this->CreateNestedTree(desc);
00353     this->vscroll = this->GetScrollbar(SLW_SCROLLBAR);
00354     this->FinishInitNested(desc, window_number);
00355     this->owner = (Owner)this->window_number;
00356 
00357     CargoID cid;
00358     FOR_EACH_SET_CARGO_ID(cid, this->cargo_filter) {
00359       if (CargoSpec::Get(cid)->IsValid()) this->LowerWidget(SLW_CARGOSTART + cid);
00360     }
00361 
00362     if (this->cargo_filter == this->cargo_filter_max) this->cargo_filter = _cargo_mask;
00363 
00364     for (uint i = 0; i < 5; i++) {
00365       if (HasBit(this->facilities, i)) this->LowerWidget(i + SLW_TRAIN);
00366     }
00367     this->SetWidgetLoweredState(SLW_NOCARGOWAITING, this->include_empty);
00368 
00369     this->GetWidget<NWidgetCore>(SLW_SORTDROPBTN)->widget_data = this->sorter_names[this->stations.SortType()];
00370   }
00371 
00372   ~CompanyStationsWindow()
00373   {
00374     this->last_sorting = this->stations.GetListing();
00375   }
00376 
00377   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00378   {
00379     switch (widget) {
00380       case SLW_SORTBY: {
00381         Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
00382         d.width += padding.width + WD_SORTBUTTON_ARROW_WIDTH * 2; // Doubled since the string is centred and it also looks better.
00383         d.height += padding.height;
00384         *size = maxdim(*size, d);
00385         break;
00386       }
00387 
00388       case SLW_SORTDROPBTN: {
00389         Dimension d = {0, 0};
00390         for (int i = 0; this->sorter_names[i] != INVALID_STRING_ID; i++) {
00391           d = maxdim(d, GetStringBoundingBox(this->sorter_names[i]));
00392         }
00393         d.width += padding.width;
00394         d.height += padding.height;
00395         *size = maxdim(*size, d);
00396         break;
00397       }
00398 
00399       case SLW_LIST:
00400         resize->height = FONT_HEIGHT_NORMAL;
00401         size->height = WD_FRAMERECT_TOP + 5 * resize->height + WD_FRAMERECT_BOTTOM;
00402         break;
00403 
00404       case SLW_TRAIN:
00405       case SLW_TRUCK:
00406       case SLW_BUS:
00407       case SLW_AIRPLANE:
00408       case SLW_SHIP:
00409         size->height = max<uint>(FONT_HEIGHT_SMALL, 10) + padding.height;
00410         break;
00411 
00412       case SLW_CARGOALL:
00413       case SLW_FACILALL:
00414       case SLW_NOCARGOWAITING: {
00415         Dimension d = GetStringBoundingBox(widget == SLW_NOCARGOWAITING ? STR_ABBREV_NONE : STR_ABBREV_ALL);
00416         d.width  += padding.width + 2;
00417         d.height += padding.height;
00418         *size = maxdim(*size, d);
00419         break;
00420       }
00421 
00422       default:
00423         if (widget >= SLW_CARGOSTART) {
00424           const CargoSpec *cs = CargoSpec::Get(widget - SLW_CARGOSTART);
00425           if (cs->IsValid()) {
00426             Dimension d = GetStringBoundingBox(cs->abbrev);
00427             d.width  += padding.width + 2;
00428             d.height += padding.height;
00429             *size = maxdim(*size, d);
00430           }
00431         }
00432         break;
00433     }
00434   }
00435 
00436   virtual void OnPaint()
00437   {
00438     this->BuildStationsList((Owner)this->window_number);
00439     this->SortStationsList();
00440 
00441     this->DrawWidgets();
00442   }
00443 
00444   virtual void DrawWidget(const Rect &r, int widget) const
00445   {
00446     switch (widget) {
00447       case SLW_SORTBY:
00448         /* draw arrow pointing up/down for ascending/descending sorting */
00449         this->DrawSortButtonState(SLW_SORTBY, this->stations.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
00450         break;
00451 
00452       case SLW_LIST: {
00453         bool rtl = _current_text_dir == TD_RTL;
00454         int max = min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->stations.Length());
00455         int y = r.top + WD_FRAMERECT_TOP;
00456         for (int i = this->vscroll->GetPosition(); i < max; ++i) { // do until max number of stations of owner
00457           const Station *st = this->stations[i];
00458           assert(st->xy != INVALID_TILE);
00459 
00460           /* Do not do the complex check HasStationInUse here, it may be even false
00461            * when the order had been removed and the station list hasn't been removed yet */
00462           assert(st->owner == owner || st->owner == OWNER_NONE);
00463 
00464           SetDParam(0, st->index);
00465           SetDParam(1, st->facilities);
00466           int x = DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_LIST_STATION);
00467           x += rtl ? -5 : 5;
00468 
00469           /* show cargo waiting and station ratings */
00470           for (CargoID j = 0; j < NUM_CARGO; j++) {
00471             if (!st->goods[j].cargo.Empty()) {
00472               /* For RTL we work in exactly the opposite direction. So
00473                * decrement the space needed first, then draw to the left
00474                * instead of drawing to the left and then incrementing
00475                * the space. */
00476               if (rtl) {
00477                 x -= 20;
00478                 if (x < r.left + WD_FRAMERECT_LEFT) break;
00479               }
00480               StationsWndShowStationRating(x, x + 16, y, j, st->goods[j].cargo.Count(), st->goods[j].rating);
00481               if (!rtl) {
00482                 x += 20;
00483                 if (x > r.right - WD_FRAMERECT_RIGHT) break;
00484               }
00485             }
00486           }
00487           y += FONT_HEIGHT_NORMAL;
00488         }
00489 
00490         if (this->vscroll->GetCount() == 0) { // company has no stations
00491           DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_LIST_NONE);
00492           return;
00493         }
00494         break;
00495       }
00496 
00497       case SLW_NOCARGOWAITING: {
00498         int cg_ofst = this->IsWidgetLowered(widget) ? 2 : 1;
00499         DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, STR_ABBREV_NONE, TC_BLACK, SA_HOR_CENTER);
00500         break;
00501       }
00502 
00503       case SLW_CARGOALL: {
00504         int cg_ofst = this->IsWidgetLowered(widget) ? 2 : 1;
00505         DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, STR_ABBREV_ALL, TC_BLACK, SA_HOR_CENTER);
00506         break;
00507       }
00508 
00509       case SLW_FACILALL: {
00510         int cg_ofst = this->IsWidgetLowered(widget) ? 2 : 1;
00511         DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, STR_ABBREV_ALL, TC_BLACK);
00512         break;
00513       }
00514 
00515       default:
00516         if (widget >= SLW_CARGOSTART) {
00517           const CargoSpec *cs = CargoSpec::Get(widget - SLW_CARGOSTART);
00518           if (cs->IsValid()) {
00519             int cg_ofst = HasBit(this->cargo_filter, cs->Index()) ? 2 : 1;
00520             GfxFillRect(r.left + cg_ofst, r.top + cg_ofst, r.right - 2 + cg_ofst, r.bottom - 2 + cg_ofst, cs->rating_colour);
00521             DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, cs->abbrev, TC_BLACK, SA_HOR_CENTER);
00522           }
00523         }
00524         break;
00525     }
00526   }
00527 
00528   virtual void SetStringParameters(int widget) const
00529   {
00530     if (widget == SLW_CAPTION) {
00531       SetDParam(0, this->window_number);
00532       SetDParam(1, this->vscroll->GetCount());
00533     }
00534   }
00535 
00536   virtual void OnClick(Point pt, int widget, int click_count)
00537   {
00538     switch (widget) {
00539       case SLW_LIST: {
00540         uint id_v = this->vscroll->GetScrolledRowFromWidget(pt.y, this, SLW_LIST, 0, FONT_HEIGHT_NORMAL);
00541         if (id_v >= this->stations.Length()) return; // click out of list bound
00542 
00543         const Station *st = this->stations[id_v];
00544         /* do not check HasStationInUse - it is slow and may be invalid */
00545         assert(st->owner == (Owner)this->window_number || st->owner == OWNER_NONE);
00546 
00547         if (_ctrl_pressed) {
00548           ShowExtraViewPortWindow(st->xy);
00549         } else {
00550           ScrollMainWindowToTile(st->xy);
00551         }
00552         break;
00553       }
00554 
00555       case SLW_TRAIN:
00556       case SLW_TRUCK:
00557       case SLW_BUS:
00558       case SLW_AIRPLANE:
00559       case SLW_SHIP:
00560         if (_ctrl_pressed) {
00561           ToggleBit(this->facilities, widget - SLW_TRAIN);
00562           this->ToggleWidgetLoweredState(widget);
00563         } else {
00564           uint i;
00565           FOR_EACH_SET_BIT(i, this->facilities) {
00566             this->RaiseWidget(i + SLW_TRAIN);
00567           }
00568           this->facilities = 1 << (widget - SLW_TRAIN);
00569           this->LowerWidget(widget);
00570         }
00571         this->stations.ForceRebuild();
00572         this->SetDirty();
00573         break;
00574 
00575       case SLW_FACILALL:
00576         for (uint i = SLW_TRAIN; i <= SLW_SHIP; i++) {
00577           this->LowerWidget(i);
00578         }
00579 
00580         this->facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK;
00581         this->stations.ForceRebuild();
00582         this->SetDirty();
00583         break;
00584 
00585       case SLW_CARGOALL: {
00586         for (uint i = 0; i < NUM_CARGO; i++) {
00587           const CargoSpec *cs = CargoSpec::Get(i);
00588           if (cs->IsValid()) this->LowerWidget(SLW_CARGOSTART + i);
00589         }
00590         this->LowerWidget(SLW_NOCARGOWAITING);
00591 
00592         this->cargo_filter = _cargo_mask;
00593         this->include_empty = true;
00594         this->stations.ForceRebuild();
00595         this->SetDirty();
00596         break;
00597       }
00598 
00599       case SLW_SORTBY: // flip sorting method asc/desc
00600         this->stations.ToggleSortOrder();
00601         this->flags4 |= WF_TIMEOUT_BEGIN;
00602         this->LowerWidget(SLW_SORTBY);
00603         this->SetDirty();
00604         break;
00605 
00606       case SLW_SORTDROPBTN: // select sorting criteria dropdown menu
00607         ShowDropDownMenu(this, this->sorter_names, this->stations.SortType(), SLW_SORTDROPBTN, 0, 0);
00608         break;
00609 
00610       case SLW_NOCARGOWAITING:
00611         if (_ctrl_pressed) {
00612           this->include_empty = !this->include_empty;
00613           this->ToggleWidgetLoweredState(SLW_NOCARGOWAITING);
00614         } else {
00615           for (uint i = 0; i < NUM_CARGO; i++) {
00616             const CargoSpec *cs = CargoSpec::Get(i);
00617             if (cs->IsValid()) this->RaiseWidget(SLW_CARGOSTART + i);
00618           }
00619 
00620           this->cargo_filter = 0;
00621           this->include_empty = true;
00622 
00623           this->LowerWidget(SLW_NOCARGOWAITING);
00624         }
00625         this->stations.ForceRebuild();
00626         this->SetDirty();
00627         break;
00628 
00629       default:
00630         if (widget >= SLW_CARGOSTART) { // change cargo_filter
00631           /* Determine the selected cargo type */
00632           const CargoSpec *cs = CargoSpec::Get(widget - SLW_CARGOSTART);
00633           if (!cs->IsValid()) break;
00634 
00635           if (_ctrl_pressed) {
00636             ToggleBit(this->cargo_filter, cs->Index());
00637             this->ToggleWidgetLoweredState(widget);
00638           } else {
00639             for (uint i = 0; i < NUM_CARGO; i++) {
00640               const CargoSpec *cs = CargoSpec::Get(i);
00641               if (cs->IsValid()) this->RaiseWidget(SLW_CARGOSTART + i);
00642             }
00643             this->RaiseWidget(SLW_NOCARGOWAITING);
00644 
00645             this->cargo_filter = 0;
00646             this->include_empty = false;
00647 
00648             SetBit(this->cargo_filter, cs->Index());
00649             this->LowerWidget(widget);
00650           }
00651           this->stations.ForceRebuild();
00652           this->SetDirty();
00653         }
00654         break;
00655     }
00656   }
00657 
00658   virtual void OnDropdownSelect(int widget, int index)
00659   {
00660     if (this->stations.SortType() != index) {
00661       this->stations.SetSortType(index);
00662 
00663       /* Display the current sort variant */
00664       this->GetWidget<NWidgetCore>(SLW_SORTDROPBTN)->widget_data = this->sorter_names[this->stations.SortType()];
00665 
00666       this->SetDirty();
00667     }
00668   }
00669 
00670   virtual void OnTick()
00671   {
00672     if (_pause_mode != PM_UNPAUSED) return;
00673     if (this->stations.NeedResort()) {
00674       DEBUG(misc, 3, "Periodic rebuild station list company %d", this->window_number);
00675       this->SetDirty();
00676     }
00677   }
00678 
00679   virtual void OnTimeout()
00680   {
00681     this->RaiseWidget(SLW_SORTBY);
00682     this->SetDirty();
00683   }
00684 
00685   virtual void OnResize()
00686   {
00687     this->vscroll->SetCapacityFromWidget(this, SLW_LIST, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
00688   }
00689 
00695   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
00696   {
00697     if (data == 0) {
00698       /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
00699       this->stations.ForceRebuild();
00700     } else {
00701       this->stations.ForceResort();
00702     }
00703   }
00704 };
00705 
00706 Listing CompanyStationsWindow::last_sorting = {false, 0};
00707 byte CompanyStationsWindow::facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK;
00708 bool CompanyStationsWindow::include_empty = true;
00709 const uint32 CompanyStationsWindow::cargo_filter_max = UINT32_MAX;
00710 uint32 CompanyStationsWindow::cargo_filter = UINT32_MAX;
00711 const Station *CompanyStationsWindow::last_station = NULL;
00712 
00713 /* Availible station sorting functions */
00714 GUIStationList::SortFunction * const CompanyStationsWindow::sorter_funcs[] = {
00715   &StationNameSorter,
00716   &StationTypeSorter,
00717   &StationWaitingSorter,
00718   &StationRatingMaxSorter,
00719   &StationRatingMinSorter
00720 };
00721 
00722 /* Names of the sorting functions */
00723 const StringID CompanyStationsWindow::sorter_names[] = {
00724   STR_SORT_BY_NAME,
00725   STR_SORT_BY_FACILITY,
00726   STR_SORT_BY_WAITING,
00727   STR_SORT_BY_RATING_MAX,
00728   STR_SORT_BY_RATING_MIN,
00729   INVALID_STRING_ID
00730 };
00731 
00737 static NWidgetBase *CargoWidgets(int *biggest_index)
00738 {
00739   NWidgetHorizontal *container = new NWidgetHorizontal();
00740 
00741   for (uint i = 0; i < NUM_CARGO; i++) {
00742     const CargoSpec *cs = CargoSpec::Get(i);
00743     if (cs->IsValid()) {
00744       NWidgetBackground *panel = new NWidgetBackground(WWT_PANEL, COLOUR_GREY, SLW_CARGOSTART + i);
00745       panel->SetMinimalSize(14, 11);
00746       panel->SetResize(0, 0);
00747       panel->SetFill(0, 1);
00748       panel->SetDataTip(0, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE);
00749       container->Add(panel);
00750     } else {
00751       NWidgetLeaf *nwi = new NWidgetLeaf(WWT_EMPTY, COLOUR_GREY, SLW_CARGOSTART + i, 0x0, STR_NULL);
00752       nwi->SetMinimalSize(0, 11);
00753       nwi->SetResize(0, 0);
00754       nwi->SetFill(0, 1);
00755       container->Add(nwi);
00756     }
00757   }
00758   *biggest_index = SLW_CARGOSTART + NUM_CARGO;
00759   return container;
00760 }
00761 
00762 static const NWidgetPart _nested_company_stations_widgets[] = {
00763   NWidget(NWID_HORIZONTAL),
00764     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
00765     NWidget(WWT_CAPTION, COLOUR_GREY, SLW_CAPTION), SetDataTip(STR_STATION_LIST_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00766     NWidget(WWT_SHADEBOX, COLOUR_GREY),
00767     NWidget(WWT_STICKYBOX, COLOUR_GREY),
00768   EndContainer(),
00769   NWidget(NWID_HORIZONTAL),
00770     NWidget(WWT_TEXTBTN, COLOUR_GREY, SLW_TRAIN), SetMinimalSize(14, 11), SetDataTip(STR_TRAIN, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
00771     NWidget(WWT_TEXTBTN, COLOUR_GREY, SLW_TRUCK), SetMinimalSize(14, 11), SetDataTip(STR_LORRY, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
00772     NWidget(WWT_TEXTBTN, COLOUR_GREY, SLW_BUS), SetMinimalSize(14, 11), SetDataTip(STR_BUS, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
00773     NWidget(WWT_TEXTBTN, COLOUR_GREY, SLW_SHIP), SetMinimalSize(14, 11), SetDataTip(STR_SHIP, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
00774     NWidget(WWT_TEXTBTN, COLOUR_GREY, SLW_AIRPLANE), SetMinimalSize(14, 11), SetDataTip(STR_PLANE, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
00775     NWidget(WWT_PUSHBTN, COLOUR_GREY, SLW_FACILALL), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_SELECT_ALL_FACILITIES), SetFill(0, 1),
00776     NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(5, 11), SetFill(0, 1), EndContainer(),
00777     NWidgetFunction(CargoWidgets),
00778     NWidget(WWT_PANEL, COLOUR_GREY, SLW_NOCARGOWAITING), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_NO_WAITING_CARGO), SetFill(0, 1), EndContainer(),
00779     NWidget(WWT_PUSHBTN, COLOUR_GREY, SLW_CARGOALL), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_SELECT_ALL_TYPES), SetFill(0, 1),
00780     NWidget(WWT_PANEL, COLOUR_GREY), SetDataTip(0x0, STR_NULL), SetResize(1, 0), SetFill(1, 1), EndContainer(),
00781   EndContainer(),
00782   NWidget(NWID_HORIZONTAL),
00783     NWidget(WWT_TEXTBTN, COLOUR_GREY, SLW_SORTBY), SetMinimalSize(81, 12), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
00784     NWidget(WWT_DROPDOWN, COLOUR_GREY, SLW_SORTDROPBTN), SetMinimalSize(163, 12), SetDataTip(STR_SORT_BY_NAME, STR_TOOLTIP_SORT_CRITERIA), // widget_data gets overwritten.
00785     NWidget(WWT_PANEL, COLOUR_GREY), SetDataTip(0x0, STR_NULL), SetResize(1, 0), SetFill(1, 1), EndContainer(),
00786   EndContainer(),
00787   NWidget(NWID_HORIZONTAL),
00788     NWidget(WWT_PANEL, COLOUR_GREY, SLW_LIST), SetMinimalSize(346, 125), SetResize(1, 10), SetDataTip(0x0, STR_STATION_LIST_TOOLTIP), SetScrollbar(SLW_SCROLLBAR), EndContainer(),
00789     NWidget(NWID_VERTICAL),
00790       NWidget(NWID_VSCROLLBAR, COLOUR_GREY, SLW_SCROLLBAR),
00791       NWidget(WWT_RESIZEBOX, COLOUR_GREY),
00792     EndContainer(),
00793   EndContainer(),
00794 };
00795 
00796 static const WindowDesc _company_stations_desc(
00797   WDP_AUTO, 358, 162,
00798   WC_STATION_LIST, WC_NONE,
00799   WDF_UNCLICK_BUTTONS,
00800   _nested_company_stations_widgets, lengthof(_nested_company_stations_widgets)
00801 );
00802 
00808 void ShowCompanyStations(CompanyID company)
00809 {
00810   if (!Company::IsValidID(company)) return;
00811 
00812   AllocateWindowDescFront<CompanyStationsWindow>(&_company_stations_desc, company);
00813 }
00814 
00815 static const NWidgetPart _nested_station_view_widgets[] = {
00816   NWidget(NWID_HORIZONTAL),
00817     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
00818     NWidget(WWT_CAPTION, COLOUR_GREY, SVW_CAPTION), SetDataTip(STR_STATION_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00819     NWidget(WWT_SHADEBOX, COLOUR_GREY),
00820     NWidget(WWT_STICKYBOX, COLOUR_GREY),
00821   EndContainer(),
00822   NWidget(NWID_HORIZONTAL),
00823     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SVW_SORT_ORDER), SetMinimalSize(81, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
00824     NWidget(WWT_DROPDOWN, COLOUR_GREY, SVW_SORT_BY), SetMinimalSize(168, 12), SetResize(1, 0), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
00825   EndContainer(),
00826   NWidget(NWID_HORIZONTAL),
00827     NWidget(WWT_TEXTBTN, COLOUR_GREY, SVW_GROUP), SetMinimalSize(81, 12), SetFill(1, 1), SetDataTip(STR_STATION_VIEW_GROUP, 0x0),
00828     NWidget(WWT_DROPDOWN, COLOUR_GREY, SVW_GROUP_BY), SetMinimalSize(168, 12), SetResize(1, 0), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_GROUP_ORDER),
00829   EndContainer(),
00830   NWidget(NWID_HORIZONTAL),
00831     NWidget(WWT_PANEL, COLOUR_GREY, SVW_WAITING), SetMinimalSize(237, 44), SetResize(1, 10), SetScrollbar(SVW_SCROLLBAR), EndContainer(),
00832     NWidget(NWID_VSCROLLBAR, COLOUR_GREY, SVW_SCROLLBAR),
00833   EndContainer(),
00834   NWidget(WWT_PANEL, COLOUR_GREY, SVW_ACCEPTLIST), SetMinimalSize(249, 23), SetResize(1, 0), EndContainer(),
00835   NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
00836     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SVW_LOCATION), SetMinimalSize(60, 12), SetResize(1, 0), SetFill(1, 1),
00837         SetDataTip(STR_BUTTON_LOCATION, STR_STATION_VIEW_CENTER_TOOLTIP),
00838     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SVW_ACCEPTS), SetMinimalSize(61, 12), SetResize(1, 0), SetFill(1, 1),
00839         SetDataTip(STR_STATION_VIEW_RATINGS_BUTTON, STR_STATION_VIEW_RATINGS_TOOLTIP),
00840     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SVW_RENAME), SetMinimalSize(60, 12), SetResize(1, 0), SetFill(1, 1),
00841         SetDataTip(STR_BUTTON_RENAME, STR_STATION_VIEW_RENAME_TOOLTIP),
00842     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SVW_TRAINS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_TRAIN, STR_STATION_VIEW_SCHEDULED_TRAINS_TOOLTIP),
00843     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SVW_ROADVEHS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_LORRY, STR_STATION_VIEW_SCHEDULED_ROAD_VEHICLES_TOOLTIP),
00844     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SVW_SHIPS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_SHIP, STR_STATION_VIEW_SCHEDULED_SHIPS_TOOLTIP),
00845     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SVW_PLANES),  SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_PLANE, STR_STATION_VIEW_SCHEDULED_AIRCRAFT_TOOLTIP),
00846     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
00847   EndContainer(),
00848 };
00849 
00860 static void DrawCargoIcons(CargoID i, uint waiting, int left, int right, int y)
00861 {
00862   uint num = min((waiting + 5) / 10, (right - left) / 10); // maximum is width / 10 icons so it won't overflow
00863   if (num == 0) return;
00864 
00865   SpriteID sprite = CargoSpec::Get(i)->GetCargoIcon();
00866 
00867   int x = _current_text_dir == TD_RTL ? left : right - num * 10;
00868   do {
00869     DrawSprite(sprite, PAL_NONE, x, y);
00870     x += 10;
00871   } while (--num);
00872 }
00873 
00874 CargoDataEntry::CargoDataEntry() :
00875   parent(NULL),
00876   station(INVALID_STATION),
00877   num_children(0),
00878   count(0),
00879   children(new CargoDataSet(CargoSorter(ST_CARGO_ID)))
00880 {}
00881 
00882 CargoDataEntry::CargoDataEntry(CargoID cargo, uint count, CargoDataEntry *parent) :
00883   parent(parent),
00884   cargo(cargo),
00885   num_children(0),
00886   count(count),
00887   children(new CargoDataSet)
00888 {}
00889 
00890 CargoDataEntry::CargoDataEntry(StationID station, uint count, CargoDataEntry *parent) :
00891   parent(parent),
00892   station(station),
00893   num_children(0),
00894   count(count),
00895   children(new CargoDataSet)
00896 {}
00897 
00898 CargoDataEntry::CargoDataEntry(StationID station) :
00899   parent(NULL),
00900   station(station),
00901   num_children(0),
00902   count(0),
00903   children(NULL)
00904 {}
00905 
00906 CargoDataEntry::CargoDataEntry(CargoID cargo) :
00907   parent(NULL),
00908   cargo(cargo),
00909   num_children(0),
00910   count(0),
00911   children(NULL)
00912 {}
00913 
00914 CargoDataEntry::~CargoDataEntry()
00915 {
00916   this->Clear();
00917   delete this->children;
00918 }
00919 
00923 void CargoDataEntry::Clear()
00924 {
00925   if (this->children != NULL) {
00926     for (CargoDataSet::iterator i = this->children->begin(); i != this->children->end(); ++i) {
00927       assert(*i != this);
00928       delete *i;
00929     }
00930     this->children->clear();
00931   }
00932   if (this->parent != NULL) this->parent->count -= this->count;
00933   this->count = 0;
00934   this->num_children = 0;
00935 }
00936 
00943 void CargoDataEntry::Remove(CargoDataEntry *child)
00944 {
00945   CargoDataSet::iterator i = this->children->find(child);
00946   if (i != this->children->end()) {
00947     delete *i;
00948     this->children->erase(i);
00949   }
00950 }
00951 
00958 template<class ID>
00959 CargoDataEntry *CargoDataEntry::InsertOrRetrieve(ID child_id)
00960 {
00961   CargoDataEntry tmp(child_id);
00962   CargoDataSet::iterator i = this->children->find(&tmp);
00963   if (i == this->children->end()) {
00964     IncrementSize();
00965     return *(this->children->insert(new CargoDataEntry(child_id, 0, this)).first);
00966   } else {
00967     CargoDataEntry *ret = *i;
00968     assert(this->children->value_comp().GetSortType() != ST_COUNT);
00969     return ret;
00970   }
00971 }
00972 
00978 void CargoDataEntry::Update(uint count)
00979 {
00980   this->count += count;
00981   if (this->parent != NULL) this->parent->Update(count);
00982 }
00983 
00987 void CargoDataEntry::IncrementSize()
00988 {
00989    ++this->num_children;
00990    if (this->parent != NULL) this->parent->IncrementSize();
00991 }
00992 
00993 void CargoDataEntry::Resort(CargoSortType type, SortOrder order)
00994 {
00995   CargoDataSet *new_subs = new CargoDataSet(this->children->begin(), this->children->end(), CargoSorter(type, order));
00996   delete this->children;
00997   this->children = new_subs;
00998 }
00999 
01000 CargoDataEntry *CargoDataEntry::Retrieve(CargoDataSet::iterator i) const
01001 {
01002   if (i == this->children->end()) {
01003     return NULL;
01004   } else {
01005     assert(this->children->value_comp().GetSortType() != ST_COUNT);
01006     return *i;
01007   }
01008 }
01009 
01010 bool CargoSorter::operator()(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const
01011 {
01012   switch (this->type) {
01013     case ST_STATION_ID:
01014       return this->SortId<StationID>(cd1->GetStation(), cd2->GetStation());
01015       break;
01016     case ST_CARGO_ID:
01017       return this->SortId<CargoID>(cd1->GetCargo(), cd2->GetCargo());
01018       break;
01019     case ST_COUNT:
01020       return this->SortCount(cd1, cd2);
01021       break;
01022     case ST_STATION_STRING:
01023       return this->SortStation(cd1->GetStation(), cd2->GetStation());
01024       break;
01025     default:
01026       NOT_REACHED();
01027   }
01028 }
01029 
01030 template<class ID>
01031 bool CargoSorter::SortId(ID st1, ID st2) const
01032 {
01033   return (this->order == SO_ASCENDING) ? st1 < st2 : st2 < st1;
01034 }
01035 
01036 bool CargoSorter::SortCount(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const
01037 {
01038   uint c1 = cd1->GetCount();
01039   uint c2 = cd2->GetCount();
01040   if (c1 == c2) {
01041     return this->SortStation(cd1->GetStation(), cd2->GetStation());
01042   } else if (this->order == SO_ASCENDING) {
01043     return c1 < c2;
01044   } else {
01045     return c2 < c1;
01046   }
01047 }
01048 
01049 bool CargoSorter::SortStation(StationID st1, StationID st2) const
01050 {
01051   static char buf1[MAX_LENGTH_STATION_NAME_CHARS];
01052   static char buf2[MAX_LENGTH_STATION_NAME_CHARS];
01053 
01054   if (!Station::IsValidID(st1)) {
01055     return Station::IsValidID(st2) ? this->order == SO_ASCENDING : this->SortId(st1, st2);
01056   } else if (!Station::IsValidID(st2)) {
01057     return order == SO_DESCENDING;
01058   }
01059 
01060   SetDParam(0, st1);
01061   GetString(buf1, STR_STATION_NAME, lastof(buf1));
01062   SetDParam(0, st2);
01063   GetString(buf2, STR_STATION_NAME, lastof(buf2));
01064 
01065   int res = strcmp(buf1, buf2);
01066   if (res == 0) {
01067     return this->SortId(st1, st2);
01068   } else {
01069     return (this->order == SO_ASCENDING) ? res < 0 : res > 0;
01070   }
01071 }
01072 
01076 struct StationViewWindow : public Window {
01080   struct RowDisplay {
01081     RowDisplay(CargoDataEntry *f, StationID n) : filter(f), next_station(n) {}
01082     RowDisplay(CargoDataEntry *f, CargoID n) : filter(f), next_cargo(n) {}
01083 
01087     CargoDataEntry *filter;
01088     union {
01092       StationID next_station;
01093 
01097       CargoID next_cargo;
01098     };
01099   };
01100 
01101   typedef std::vector<RowDisplay> CargoDataVector;
01102 
01103   static const int NUM_COLUMNS = 4; 
01104 
01108   enum Invalidation {
01109     INV_FLOWS = 0x100, 
01110     INV_CARGO = 0x200  
01111   };
01112 
01116   enum Grouping {
01117     GR_SOURCE,      
01118     GR_NEXT,        
01119     GR_DESTINATION, 
01120     GR_CARGO,       
01121   };
01122 
01126   enum Mode {
01127     MODE_WAITING, 
01128     MODE_PLANNED  
01129   };
01130 
01131   uint expand_shrink_width;     
01132   int rating_lines;             
01133   int accepts_lines;            
01134   Scrollbar *vscroll;
01135 
01137   enum AcceptListHeight {
01138     ALH_RATING  = 13, 
01139     ALH_ACCEPTS = 3,  
01140   };
01141 
01142   static const StringID _sort_names[];  
01143   static const StringID _group_names[]; 
01144 
01151   CargoSortType sortings[NUM_COLUMNS];
01152 
01154   SortOrder sort_orders[NUM_COLUMNS];
01155 
01156   int scroll_to_row;                  
01157   int grouping_index;                 
01158   Mode current_mode;                  
01159   Grouping groupings[NUM_COLUMNS];    
01160 
01161   CargoDataEntry expanded_rows;       
01162   CargoDataEntry cached_destinations; 
01163   CargoDataVector displayed_rows;     
01164 
01165   StationViewWindow(const WindowDesc *desc, WindowNumber window_number) : Window(),
01166     scroll_to_row(INT_MAX), grouping_index(0)
01167   {
01168     this->rating_lines  = ALH_RATING;
01169     this->accepts_lines = ALH_ACCEPTS;
01170 
01171     this->CreateNestedTree(desc);
01172     this->vscroll = this->GetScrollbar(SVW_SCROLLBAR);
01173     /* Nested widget tree creation is done in two steps to ensure that this->GetWidget<NWidgetCore>(SVW_ACCEPTS) exists in UpdateWidgetSize(). */
01174     this->FinishInitNested(desc, window_number);
01175 
01176     this->groupings[0] = GR_CARGO;
01177     this->sortings[0] = ST_AS_GROUPING;
01178     this->SelectGroupBy(_settings_client.gui.station_gui_group_order);
01179     this->SelectSortBy(_settings_client.gui.station_gui_sort_by);
01180     this->sort_orders[0] = SO_ASCENDING;
01181     this->SelectSortOrder((SortOrder)_settings_client.gui.station_gui_sort_order);
01182     Owner owner = Station::Get(window_number)->owner;
01183     if (owner != OWNER_NONE) this->owner = owner;
01184   }
01185 
01186   ~StationViewWindow()
01187   {
01188     Owner owner = Station::Get(this->window_number)->owner;
01189     if (!Company::IsValidID(owner)) owner = _local_company;
01190     if (!Company::IsValidID(owner)) return; // Spectators
01191     DeleteWindowById(WC_TRAINS_LIST,   VehicleListIdentifier(VL_STATION_LIST, VEH_TRAIN,    owner, this->window_number).Pack(), false);
01192     DeleteWindowById(WC_ROADVEH_LIST,  VehicleListIdentifier(VL_STATION_LIST, VEH_ROAD,     owner, this->window_number).Pack(), false);
01193     DeleteWindowById(WC_SHIPS_LIST,    VehicleListIdentifier(VL_STATION_LIST, VEH_SHIP,     owner, this->window_number).Pack(), false);
01194     DeleteWindowById(WC_AIRCRAFT_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_AIRCRAFT, owner, this->window_number).Pack(), false);
01195   }
01196 
01207   void ShowCargo(CargoDataEntry *data, CargoID cargo, StationID source, StationID next, StationID dest, uint count)
01208   {
01209     if (count == 0) return;
01210     const CargoDataEntry *expand = &this->expanded_rows;
01211     for (int i = 0; i < NUM_COLUMNS && expand != NULL; ++i) {
01212       switch (groupings[i]) {
01213         case GR_CARGO:
01214           assert(i == 0);
01215           data = data->InsertOrRetrieve(cargo);
01216           expand = expand->Retrieve(cargo);
01217           break;
01218         case GR_SOURCE:
01219           data = data->InsertOrRetrieve(source);
01220           expand = expand->Retrieve(source);
01221           break;
01222         case GR_NEXT:
01223           data = data->InsertOrRetrieve(next);
01224           expand = expand->Retrieve(next);
01225           break;
01226         case GR_DESTINATION:
01227           data = data->InsertOrRetrieve(dest);
01228           expand = expand->Retrieve(dest);
01229           break;
01230       }
01231     }
01232     data->Update(count);
01233   }
01234 
01235   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01236   {
01237     switch (widget) {
01238       case SVW_WAITING:
01239         resize->height = FONT_HEIGHT_NORMAL;
01240         size->height = WD_FRAMERECT_TOP + 4 * resize->height + WD_FRAMERECT_BOTTOM;
01241         this->expand_shrink_width = max(GetStringBoundingBox("-").width, GetStringBoundingBox("+").width) + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
01242         break;
01243 
01244       case SVW_ACCEPTLIST:
01245         size->height = WD_FRAMERECT_TOP + ((this->GetWidget<NWidgetCore>(SVW_ACCEPTS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) ? this->accepts_lines : this->rating_lines) * FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
01246         break;
01247     }
01248   }
01249 
01250   virtual void OnPaint()
01251   {
01252     const Station *st = Station::Get(this->window_number);
01253     CargoDataEntry cargo;
01254     BuildCargoList(&cargo, st);
01255 
01256     this->vscroll->SetCount(cargo.GetNumChildren()); // update scrollbar
01257 
01258     /* disable some buttons */
01259     this->SetWidgetDisabledState(SVW_RENAME,   st->owner != _local_company);
01260     this->SetWidgetDisabledState(SVW_TRAINS,   !(st->facilities & FACIL_TRAIN));
01261     this->SetWidgetDisabledState(SVW_ROADVEHS, !(st->facilities & FACIL_TRUCK_STOP) && !(st->facilities & FACIL_BUS_STOP));
01262     this->SetWidgetDisabledState(SVW_SHIPS,    !(st->facilities & FACIL_DOCK));
01263     this->SetWidgetDisabledState(SVW_PLANES,   !(st->facilities & FACIL_AIRPORT));
01264 
01265     SetDParam(0, st->index);
01266     SetDParam(1, st->facilities);
01267     this->DrawWidgets();
01268 
01269     if (!this->IsShaded()) {
01270       /* Draw 'accepted cargo' or 'cargo ratings'. */
01271       const NWidgetBase *wid = this->GetWidget<NWidgetBase>(SVW_ACCEPTLIST);
01272       const Rect r = {wid->pos_x, wid->pos_y, wid->pos_x + wid->current_x - 1, wid->pos_y + wid->current_y - 1};
01273       if (this->GetWidget<NWidgetCore>(SVW_ACCEPTS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) {
01274         int lines = this->DrawAcceptedCargo(r);
01275         if (lines > this->accepts_lines) { // Resize the widget, and perform re-initialization of the window.
01276           this->accepts_lines = lines;
01277           this->ReInit();
01278           return;
01279         }
01280       } else {
01281         int lines = this->DrawCargoRatings(r);
01282         if (lines > this->rating_lines) { // Resize the widget, and perform re-initialization of the window.
01283           this->rating_lines = lines;
01284           this->ReInit();
01285           return;
01286         }
01287       }
01288 
01289       /* draw arrow pointing up/down for ascending/descending sorting */
01290       this->DrawSortButtonState(SVW_SORT_ORDER, sort_orders[1] == SO_ASCENDING ? SBS_UP : SBS_DOWN);
01291 
01292       int pos = this->vscroll->GetPosition();
01293 
01294       int maxrows = this->vscroll->GetCapacity();
01295 
01296       displayed_rows.clear();
01297 
01298       /* Draw waiting cargo. */
01299       NWidgetBase *nwi = this->GetWidget<NWidgetBase>(SVW_WAITING);
01300       Rect waiting_rect = {nwi->pos_x, nwi->pos_y, nwi->pos_x + nwi->current_x - 1, nwi->pos_y + nwi->current_y - 1};
01301       this->DrawEntries(&cargo, waiting_rect, pos, maxrows, 0);
01302       scroll_to_row = INT_MAX;
01303     }
01304   }
01305 
01306   virtual void SetStringParameters(int widget) const
01307   {
01308     if (widget == SVW_CAPTION) {
01309       const Station *st = Station::Get(this->window_number);
01310       SetDParam(0, st->index);
01311       SetDParam(1, st->facilities);
01312     }
01313   }
01314 
01320   void RecalcDestinations(CargoID i)
01321   {
01322     const Station *st = Station::Get(this->window_number);
01323     CargoDataEntry *cargo_entry = cached_destinations.InsertOrRetrieve(i);
01324     cargo_entry->Clear();
01325 
01326     const FlowStatMap &flows = st->goods[i].flows;
01327     for (FlowStatMap::const_iterator it = flows.begin(); it != flows.end(); ++it) {
01328       StationID from = it->first;
01329       CargoDataEntry *source_entry = cargo_entry->InsertOrRetrieve(from);
01330       const FlowStatSet &flow_set = it->second;
01331       for (FlowStatSet::const_iterator flow_it = flow_set.begin(); flow_it != flow_set.end(); ++flow_it) {
01332         const FlowStat &stat = *flow_it;
01333         StationID via = stat.Via();
01334         CargoDataEntry *via_entry = source_entry->InsertOrRetrieve(via);
01335         if (via == this->window_number) {
01336           via_entry->InsertOrRetrieve(via)->Update(stat.Planned());
01337         } else {
01338           EstimateDestinations(i, from, via, stat.Planned(), via_entry);
01339         }
01340       }
01341     }
01342   }
01343 
01353   void EstimateDestinations(CargoID cargo, StationID source, StationID next, uint count, CargoDataEntry *dest)
01354   {
01355     if (Station::IsValidID(next) && Station::IsValidID(source)) {
01356       CargoDataEntry tmp;
01357       const FlowStatMap &flowmap = Station::Get(next)->goods[cargo].flows;
01358       FlowStatMap::const_iterator map_it = flowmap.find(source);
01359       if (map_it != flowmap.end()) {
01360         const FlowStatSet &flows = map_it->second;
01361         for (FlowStatSet::const_iterator i = flows.begin(); i != flows.end(); ++i) {
01362           tmp.InsertOrRetrieve(i->Via())->Update(i->Planned());
01363         }
01364       }
01365 
01366       if (tmp.GetCount() == 0) {
01367         dest->InsertOrRetrieve(INVALID_STATION)->Update(count);
01368       } else {
01369         uint sum_estimated = 0;
01370         while (sum_estimated < count) {
01371           for (CargoDataSet::iterator i = tmp.Begin(); i != tmp.End() && sum_estimated < count; ++i) {
01372             CargoDataEntry *child = *i;
01373             uint estimate = DivideApprox(child->GetCount() * count, tmp.GetCount());
01374             if (estimate == 0) estimate = 1;
01375 
01376             sum_estimated += estimate;
01377             if (sum_estimated > count) {
01378               estimate -= sum_estimated - count;
01379               sum_estimated = count;
01380             }
01381 
01382             if (estimate > 0) {
01383               if (child->GetStation() == next) {
01384                 dest->InsertOrRetrieve(next)->Update(estimate);
01385               } else {
01386                 EstimateDestinations(cargo, source, child->GetStation(), estimate, dest);
01387               }
01388             }
01389           }
01390 
01391         }
01392       }
01393     } else {
01394       dest->InsertOrRetrieve(INVALID_STATION)->Update(count);
01395     }
01396   }
01397 
01404   void BuildFlowList(CargoID i, const FlowStatMap &flows, CargoDataEntry *cargo)
01405   {
01406     const CargoDataEntry *source_dest = this->cached_destinations.Retrieve(i);
01407     for (FlowStatMap::const_iterator it = flows.begin(); it != flows.end(); ++it) {
01408       StationID from = it->first;
01409       const CargoDataEntry *source_entry = source_dest->Retrieve(from);
01410       const FlowStatSet &flow_set = it->second;
01411       for (FlowStatSet::const_iterator flow_it = flow_set.begin(); flow_it != flow_set.end(); ++flow_it) {
01412         const FlowStat &stat = *flow_it;
01413         const CargoDataEntry *via_entry = source_entry->Retrieve(stat.Via());
01414         for (CargoDataSet::iterator dest_it = via_entry->Begin(); dest_it != via_entry->End(); ++dest_it) {
01415           CargoDataEntry *dest_entry = *dest_it;
01416           ShowCargo(cargo, i, from, stat.Via(), dest_entry->GetStation(), dest_entry->GetCount());
01417         }
01418       }
01419     }
01420   }
01421 
01428   void BuildCargoList(CargoID i, const StationCargoList &packets, CargoDataEntry *cargo)
01429   {
01430     const CargoDataEntry *source_dest = this->cached_destinations.Retrieve(i);
01431     for (StationCargoList::ConstIterator it = packets.Packets()->begin(); it != packets.Packets()->end(); it++) {
01432       const CargoPacket *cp = *it;
01433       StationID next = it.GetKey();
01434 
01435       const CargoDataEntry *source_entry = source_dest->Retrieve(cp->SourceStation());
01436       if (source_entry == NULL) {
01437         ShowCargo(cargo, i, cp->SourceStation(), next, INVALID_STATION, cp->Count());
01438         continue;
01439       }
01440 
01441       const CargoDataEntry *via_entry = source_entry->Retrieve(next);
01442       if (via_entry == NULL) {
01443         ShowCargo(cargo, i, cp->SourceStation(), next, INVALID_STATION, cp->Count());
01444         continue;
01445       }
01446 
01447       for (CargoDataSet::iterator dest_it = via_entry->Begin(); dest_it != via_entry->End(); ++dest_it) {
01448         CargoDataEntry *dest_entry = *dest_it;
01449         uint val = DivideApprox(cp->Count() * dest_entry->GetCount(), via_entry->GetCount());
01450         ShowCargo(cargo, i, cp->SourceStation(), next, dest_entry->GetStation(), val);
01451       }
01452     }
01453   }
01454 
01460   void BuildCargoList(CargoDataEntry *cargo, const Station *st)
01461   {
01462     for (CargoID i = 0; i < NUM_CARGO; i++) {
01463 
01464       if (this->cached_destinations.Retrieve(i) == NULL) {
01465         this->RecalcDestinations(i);
01466       }
01467 
01468       if (this->current_mode == MODE_WAITING) {
01469         BuildCargoList(i, st->goods[i].cargo, cargo);
01470       } else {
01471         BuildFlowList(i, st->goods[i].flows, cargo);
01472       }
01473     }
01474   }
01475 
01480   void SetDisplayedRow(const CargoDataEntry *data)
01481   {
01482     std::list<StationID> stations;
01483     const CargoDataEntry *parent = data->GetParent();
01484     if (parent->GetParent() == NULL) {
01485       this->displayed_rows.push_back(RowDisplay(&this->expanded_rows, data->GetCargo()));
01486       return;
01487     }
01488 
01489     StationID next = data->GetStation();
01490     while (parent->GetParent()->GetParent() != NULL) {
01491       stations.push_back(parent->GetStation());
01492       parent = parent->GetParent();
01493     }
01494 
01495     CargoID cargo = parent->GetCargo();
01496     CargoDataEntry *filter = this->expanded_rows.Retrieve(cargo);
01497     while (!stations.empty()) {
01498       filter = filter->Retrieve(stations.back());
01499       stations.pop_back();
01500     }
01501 
01502     this->displayed_rows.push_back(RowDisplay(filter, next));
01503   }
01504 
01513   StringID GetEntryString(StationID station, StringID here, StringID other_station, StringID any)
01514   {
01515     if (station == this->window_number) {
01516       return here;
01517     } else if (station != INVALID_STATION) {
01518       SetDParam(2, station);
01519       return other_station;
01520     } else {
01521       return any;
01522     }
01523   }
01524 
01532   StringID SearchNonStop(CargoDataEntry *cd, StationID station, int column)
01533   {
01534     CargoDataEntry *parent = cd->GetParent();
01535     for (int i = column - 1; i > 0; --i) {
01536       if (this->groupings[i] == GR_DESTINATION) {
01537         if (parent->GetStation() == station) {
01538           return STR_STATION_VIEW_NONSTOP;
01539         } else {
01540           return STR_STATION_VIEW_VIA;
01541         }
01542       }
01543       parent = parent->GetParent();
01544     }
01545 
01546     if (this->groupings[column + 1] == GR_DESTINATION) {
01547       CargoDataSet::iterator begin = cd->Begin();
01548       CargoDataSet::iterator end = cd->End();
01549       if (begin != end && ++(cd->Begin()) == end && (*(begin))->GetStation() == station) {
01550         return STR_STATION_VIEW_NONSTOP;
01551       } else {
01552         return STR_STATION_VIEW_VIA;
01553       }
01554     }
01555 
01556     return STR_STATION_VIEW_VIA;
01557   }
01558 
01569   int DrawEntries(CargoDataEntry *entry, Rect &r, int pos, int maxrows, int column, CargoID cargo = CT_INVALID)
01570   {
01571     if (this->sortings[column] == ST_AS_GROUPING) {
01572       if (this->groupings[column] != GR_CARGO) {
01573         entry->Resort(ST_STATION_STRING, this->sort_orders[column]);
01574       }
01575     } else {
01576       entry->Resort(ST_COUNT, this->sort_orders[column]);
01577     }
01578     for (CargoDataSet::iterator i = entry->Begin(); i != entry->End(); ++i) {
01579       CargoDataEntry *cd = *i;
01580 
01581       if (this->groupings[column] == GR_CARGO) cargo = cd->GetCargo();
01582 
01583       if (pos > -maxrows && pos <= 0) {
01584         StringID str = STR_EMPTY;
01585         int y = r.top + WD_FRAMERECT_TOP - pos * FONT_HEIGHT_NORMAL;
01586         SetDParam(0, cargo);
01587         SetDParam(1, cd->GetCount());
01588 
01589         if (this->groupings[column] == GR_CARGO) {
01590           str = STR_STATION_VIEW_WAITING_CARGO;
01591           DrawCargoIcons(cd->GetCargo(), cd->GetCount(), r.left + WD_FRAMERECT_LEFT + this->expand_shrink_width, r.right - WD_FRAMERECT_RIGHT - this->expand_shrink_width, y);
01592         } else {
01593           StationID station = cd->GetStation();
01594 
01595           switch (this->groupings[column]) {
01596             case GR_SOURCE:
01597               str = this->GetEntryString(station, STR_STATION_VIEW_FROM_HERE, STR_STATION_VIEW_FROM, STR_STATION_VIEW_FROM_ANY);
01598               break;
01599             case GR_NEXT:
01600               str = this->GetEntryString(station, STR_STATION_VIEW_VIA_HERE, STR_STATION_VIEW_VIA, STR_STATION_VIEW_VIA_ANY);
01601               if (str == STR_STATION_VIEW_VIA) str = SearchNonStop(cd, station, column);
01602               break;
01603             case GR_DESTINATION:
01604               str = this->GetEntryString(station, STR_STATION_VIEW_TO_HERE, STR_STATION_VIEW_TO, STR_STATION_VIEW_TO_ANY);
01605               break;
01606             default:
01607               NOT_REACHED();
01608           }
01609           if (pos == -this->scroll_to_row && Station::IsValidID(station)) {
01610             ScrollMainWindowToTile(Station::Get(station)->xy);
01611           }
01612         }
01613 
01614         bool rtl = _current_text_dir == TD_RTL;
01615         int text_left    = rtl ? r.left + this->expand_shrink_width : r.left + WD_FRAMERECT_LEFT + column * this->expand_shrink_width;
01616         int text_right   = rtl ? r.right - WD_FRAMERECT_LEFT - column * this->expand_shrink_width : r.right - this->expand_shrink_width;
01617         int shrink_left  = rtl ? r.left + WD_FRAMERECT_LEFT : r.right - this->expand_shrink_width + WD_FRAMERECT_LEFT;
01618         int shrink_right = rtl ? r.left + this->expand_shrink_width - WD_FRAMERECT_RIGHT : r.right - WD_FRAMERECT_RIGHT;
01619 
01620         DrawString(text_left, text_right, y, str);
01621 
01622         if (column < NUM_COLUMNS - 1) {
01623           const char *sym = cd->GetNumChildren() > 0 ? "-" : "+";
01624           DrawString(shrink_left, shrink_right, y, sym, TC_YELLOW);
01625         }
01626         SetDisplayedRow(cd);
01627       }
01628       pos = DrawEntries(cd, r, --pos, maxrows, column + 1, cargo);
01629     }
01630     return pos;
01631   }
01632 
01638   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
01639   {
01640     if (!gui_scope) return;
01641     this->cached_destinations.Remove((CargoID)data);
01642   }
01643 
01649   int DrawAcceptedCargo(const Rect &r) const
01650   {
01651     const Station *st = Station::Get(this->window_number);
01652 
01653     uint32 cargo_mask = 0;
01654     for (CargoID i = 0; i < NUM_CARGO; i++) {
01655       if (HasBit(st->goods[i].acceptance_pickup, GoodsEntry::GES_ACCEPTANCE)) SetBit(cargo_mask, i);
01656     }
01657     Rect s = {r.left + WD_FRAMERECT_LEFT, r.top + WD_FRAMERECT_TOP, r.right - WD_FRAMERECT_RIGHT, INT32_MAX};
01658     int bottom = DrawCargoListText(cargo_mask, s, STR_STATION_VIEW_ACCEPTS_CARGO);
01659     return CeilDiv(bottom - r.top - WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL);
01660   }
01661 
01667   int DrawCargoRatings(const Rect &r) const
01668   {
01669     const Station *st = Station::Get(this->window_number);
01670     int y = r.top + WD_FRAMERECT_TOP;
01671 
01672     DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_VIEW_CARGO_RATINGS_TITLE);
01673     y += FONT_HEIGHT_NORMAL;
01674 
01675     const CargoSpec *cs;
01676     FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
01677       const GoodsEntry *ge = &st->goods[cs->Index()];
01678       if (!HasBit(ge->acceptance_pickup, GoodsEntry::GES_PICKUP)) continue;
01679 
01680       SetDParam(0, cs->name);
01681       SetDParam(1, ge->supply);
01682       SetDParam(3, ToPercent8(ge->rating));
01683       SetDParam(2, STR_CARGO_RATING_APPALLING + (ge->rating >> 5));
01684       DrawString(r.left + WD_FRAMERECT_LEFT + 6, r.right - WD_FRAMERECT_RIGHT - 6, y, STR_STATION_VIEW_CARGO_SUPPLY_RATING);
01685       y += FONT_HEIGHT_NORMAL;
01686     }
01687     return CeilDiv(y - r.top - WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL);
01688   }
01689 
01695   template<class ID>
01696   void HandleCargoWaitingClick(CargoDataEntry *filter, ID next)
01697   {
01698     if (filter->Retrieve(next) != NULL) {
01699       filter->Remove(next);
01700     } else {
01701       filter->InsertOrRetrieve(next);
01702     }
01703   }
01704 
01709   void HandleCargoWaitingClick(int row)
01710   {
01711     if (row < 0 || (uint)row >= this->displayed_rows.size()) return;
01712     if (_ctrl_pressed) {
01713       this->scroll_to_row = row;
01714     } else {
01715       RowDisplay &display = this->displayed_rows[row];
01716       if (display.filter == &this->expanded_rows) {
01717         this->HandleCargoWaitingClick<CargoID>(display.filter, display.next_cargo);
01718       } else {
01719         this->HandleCargoWaitingClick<StationID>(display.filter, display.next_station);
01720       }
01721     }
01722     this->SetWidgetDirty(SVW_WAITING);
01723   }
01724 
01725   virtual void OnClick(Point pt, int widget, int click_count)
01726   {
01727     switch (widget) {
01728       case SVW_WAITING:
01729         this->HandleCargoWaitingClick(this->vscroll->GetScrolledRowFromWidget(pt.y, this, SVW_WAITING, WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL) - this->vscroll->GetPosition());
01730         break;
01731 
01732       case SVW_LOCATION:
01733         if (_ctrl_pressed) {
01734           ShowExtraViewPortWindow(Station::Get(this->window_number)->xy);
01735         } else {
01736           ScrollMainWindowToTile(Station::Get(this->window_number)->xy);
01737         }
01738         break;
01739 
01740       case SVW_RATINGS: {
01741         /* Swap between 'accepts' and 'ratings' view. */
01742         int height_change;
01743         NWidgetCore *nwi = this->GetWidget<NWidgetCore>(SVW_RATINGS);
01744         if (this->GetWidget<NWidgetCore>(SVW_RATINGS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) {
01745           nwi->SetDataTip(STR_STATION_VIEW_ACCEPTS_BUTTON, STR_STATION_VIEW_ACCEPTS_TOOLTIP); // Switch to accepts view.
01746           height_change = this->rating_lines - this->accepts_lines;
01747         } else {
01748           nwi->SetDataTip(STR_STATION_VIEW_RATINGS_BUTTON, STR_STATION_VIEW_RATINGS_TOOLTIP); // Switch to ratings view.
01749           height_change = this->accepts_lines - this->rating_lines;
01750         }
01751         this->ReInit(0, height_change * FONT_HEIGHT_NORMAL);
01752         break;
01753       }
01754 
01755       case SVW_RENAME:
01756         SetDParam(0, this->window_number);
01757         ShowQueryString(STR_STATION_NAME, STR_STATION_VIEW_RENAME_STATION_CAPTION, MAX_LENGTH_STATION_NAME_CHARS,
01758             this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
01759         break;
01760 
01761       case SVW_TRAINS:   // Show list of scheduled trains to this station
01762       case SVW_ROADVEHS: // Show list of scheduled road-vehicles to this station
01763       case SVW_SHIPS:    // Show list of scheduled ships to this station
01764       case SVW_PLANES:   // Show list of scheduled aircraft to this station
01765         ShowVehicleListWindow(this->owner, (VehicleType)(widget - SVW_TRAINS), (StationID)this->window_number);
01766         break;
01767 
01768       case SVW_SORT_BY: {
01769         ShowDropDownMenu(this, _sort_names, this->current_mode, SVW_SORT_BY, 0, 0);
01770         break;
01771       }
01772 
01773       case SVW_GROUP_BY: {
01774         ShowDropDownMenu(this, _group_names, this->grouping_index, SVW_GROUP_BY, 0, 0);
01775         break;
01776       }
01777 
01778       case SVW_SORT_ORDER: { // flip sorting method asc/desc
01779         this->SelectSortOrder(this->sort_orders[1] == SO_ASCENDING ? SO_DESCENDING : SO_ASCENDING);
01780         this->flags4 |= WF_TIMEOUT_BEGIN;
01781         this->LowerWidget(SVW_SORT_ORDER);
01782         break;
01783       }
01784     }
01785   }
01786 
01791   void SelectSortOrder(SortOrder order)
01792   {
01793     this->sort_orders[1] = this->sort_orders[2] = this->sort_orders[3] = order;
01794     _settings_client.gui.station_gui_sort_order = this->sort_orders[1];
01795     this->SetDirty();
01796   }
01797 
01802   void SelectSortBy(int index)
01803   {
01804     _settings_client.gui.station_gui_sort_by = index;
01805     switch (_sort_names[index]) {
01806       case STR_STATION_VIEW_WAITING_STATION:
01807         this->current_mode = MODE_WAITING;
01808         this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_AS_GROUPING;
01809         break;
01810       case STR_STATION_VIEW_WAITING_AMOUNT:
01811         this->current_mode = MODE_WAITING;
01812         this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_COUNT;
01813         break;
01814       case STR_STATION_VIEW_PLANNED_STATION:
01815         this->current_mode = MODE_PLANNED;
01816         this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_AS_GROUPING;
01817         break;
01818       case STR_STATION_VIEW_PLANNED_AMOUNT:
01819         this->current_mode = MODE_PLANNED;
01820         this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_COUNT;
01821         break;
01822       default:
01823         NOT_REACHED();
01824     }
01825     /* Display the current sort variant */
01826     this->GetWidget<NWidgetCore>(SVW_SORT_BY)->widget_data = _sort_names[index];
01827     this->SetDirty();
01828   }
01829 
01834   void SelectGroupBy(int index)
01835   {
01836     this->grouping_index = index;
01837     _settings_client.gui.station_gui_group_order = index;
01838     this->GetWidget<NWidgetCore>(SVW_GROUP_BY)->widget_data = _group_names[index];
01839     switch (_group_names[index]) {
01840       case STR_STATION_VIEW_GROUP_S_V_D:
01841         this->groupings[1] = GR_SOURCE;
01842         this->groupings[2] = GR_NEXT;
01843         this->groupings[3] = GR_DESTINATION;
01844         break;
01845       case STR_STATION_VIEW_GROUP_S_D_V:
01846         this->groupings[1] = GR_SOURCE;
01847         this->groupings[2] = GR_DESTINATION;
01848         this->groupings[3] = GR_NEXT;
01849         break;
01850       case STR_STATION_VIEW_GROUP_V_S_D:
01851         this->groupings[1] = GR_NEXT;
01852         this->groupings[2] = GR_SOURCE;
01853         this->groupings[3] = GR_DESTINATION;
01854         break;
01855       case STR_STATION_VIEW_GROUP_V_D_S:
01856         this->groupings[1] = GR_NEXT;
01857         this->groupings[2] = GR_DESTINATION;
01858         this->groupings[3] = GR_SOURCE;
01859         break;
01860       case STR_STATION_VIEW_GROUP_D_S_V:
01861         this->groupings[1] = GR_DESTINATION;
01862         this->groupings[2] = GR_SOURCE;
01863         this->groupings[3] = GR_NEXT;
01864         break;
01865       case STR_STATION_VIEW_GROUP_D_V_S:
01866         this->groupings[1] = GR_DESTINATION;
01867         this->groupings[2] = GR_NEXT;
01868         this->groupings[3] = GR_SOURCE;
01869         break;
01870     }
01871     this->SetDirty();
01872   }
01873 
01874   virtual void OnDropdownSelect(int widget, int index)
01875   {
01876     if (widget == SVW_SORT_BY) {
01877       this->SelectSortBy(index);
01878     } else {
01879       this->SelectGroupBy(index);
01880     }
01881   }
01882 
01883   virtual void OnQueryTextFinished(char *str)
01884   {
01885     if (str == NULL) return;
01886 
01887     DoCommandP(0, this->window_number, 0, CMD_RENAME_STATION | CMD_MSG(STR_ERROR_CAN_T_RENAME_STATION), NULL, str);
01888   }
01889 
01890   virtual void OnResize()
01891   {
01892     this->vscroll->SetCapacityFromWidget(this, SVW_WAITING, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
01893   }
01894 };
01895 
01896 const StringID StationViewWindow::_sort_names[] = {
01897   STR_STATION_VIEW_WAITING_STATION,
01898   STR_STATION_VIEW_WAITING_AMOUNT,
01899   STR_STATION_VIEW_PLANNED_STATION,
01900   STR_STATION_VIEW_PLANNED_AMOUNT,
01901   INVALID_STRING_ID
01902 };
01903 
01904 const StringID StationViewWindow::_group_names[] = {
01905   STR_STATION_VIEW_GROUP_S_V_D,
01906   STR_STATION_VIEW_GROUP_S_D_V,
01907   STR_STATION_VIEW_GROUP_V_S_D,
01908   STR_STATION_VIEW_GROUP_V_D_S,
01909   STR_STATION_VIEW_GROUP_D_S_V,
01910   STR_STATION_VIEW_GROUP_D_V_S,
01911   INVALID_STRING_ID
01912 };
01913 
01914 static const WindowDesc _station_view_desc(
01915   WDP_AUTO, 249, 117,
01916   WC_STATION_VIEW, WC_NONE,
01917   WDF_UNCLICK_BUTTONS,
01918   _nested_station_view_widgets, lengthof(_nested_station_view_widgets)
01919 );
01920 
01926 void ShowStationViewWindow(StationID station)
01927 {
01928   AllocateWindowDescFront<StationViewWindow>(&_station_view_desc, station);
01929 }
01930 
01932 struct TileAndStation {
01933   TileIndex tile;    
01934   StationID station; 
01935 };
01936 
01937 static SmallVector<TileAndStation, 8> _deleted_stations_nearby;
01938 static SmallVector<StationID, 8> _stations_nearby_list;
01939 
01947 template <class T>
01948 static bool AddNearbyStation(TileIndex tile, void *user_data)
01949 {
01950   TileArea *ctx = (TileArea *)user_data;
01951 
01952   /* First check if there were deleted stations here */
01953   for (uint i = 0; i < _deleted_stations_nearby.Length(); i++) {
01954     TileAndStation *ts = _deleted_stations_nearby.Get(i);
01955     if (ts->tile == tile) {
01956       *_stations_nearby_list.Append() = _deleted_stations_nearby[i].station;
01957       _deleted_stations_nearby.Erase(ts);
01958       i--;
01959     }
01960   }
01961 
01962   /* Check if own station and if we stay within station spread */
01963   if (!IsTileType(tile, MP_STATION)) return false;
01964 
01965   StationID sid = GetStationIndex(tile);
01966 
01967   /* This station is (likely) a waypoint */
01968   if (!T::IsValidID(sid)) return false;
01969 
01970   T *st = T::Get(sid);
01971   if (st->owner != _local_company || _stations_nearby_list.Contains(sid)) return false;
01972 
01973   if (st->rect.BeforeAddRect(ctx->tile, ctx->w, ctx->h, StationRect::ADD_TEST).Succeeded()) {
01974     *_stations_nearby_list.Append() = sid;
01975   }
01976 
01977   return false; // We want to include *all* nearby stations
01978 }
01979 
01989 template <class T>
01990 static const T *FindStationsNearby(TileArea ta, bool distant_join)
01991 {
01992   TileArea ctx = ta;
01993 
01994   _stations_nearby_list.Clear();
01995   _deleted_stations_nearby.Clear();
01996 
01997   /* Check the inside, to return, if we sit on another station */
01998   TILE_AREA_LOOP(t, ta) {
01999     if (t < MapSize() && IsTileType(t, MP_STATION) && T::IsValidID(GetStationIndex(t))) return T::GetByTile(t);
02000   }
02001 
02002   /* Look for deleted stations */
02003   const BaseStation *st;
02004   FOR_ALL_BASE_STATIONS(st) {
02005     if (T::IsExpected(st) && !st->IsInUse() && st->owner == _local_company) {
02006       /* Include only within station spread (yes, it is strictly less than) */
02007       if (max(DistanceMax(ta.tile, st->xy), DistanceMax(TILE_ADDXY(ta.tile, ta.w - 1, ta.h - 1), st->xy)) < _settings_game.station.station_spread) {
02008         TileAndStation *ts = _deleted_stations_nearby.Append();
02009         ts->tile = st->xy;
02010         ts->station = st->index;
02011 
02012         /* Add the station when it's within where we're going to build */
02013         if (IsInsideBS(TileX(st->xy), TileX(ctx.tile), ctx.w) &&
02014             IsInsideBS(TileY(st->xy), TileY(ctx.tile), ctx.h)) {
02015           AddNearbyStation<T>(st->xy, &ctx);
02016         }
02017       }
02018     }
02019   }
02020 
02021   /* Only search tiles where we have a chance to stay within the station spread.
02022    * The complete check needs to be done in the callback as we don't know the
02023    * extent of the found station, yet. */
02024   if (distant_join && min(ta.w, ta.h) >= _settings_game.station.station_spread) return NULL;
02025   uint max_dist = distant_join ? _settings_game.station.station_spread - min(ta.w, ta.h) : 1;
02026 
02027   TileIndex tile = TILE_ADD(ctx.tile, TileOffsByDir(DIR_N));
02028   CircularTileSearch(&tile, max_dist, ta.w, ta.h, AddNearbyStation<T>, &ctx);
02029 
02030   return NULL;
02031 }
02032 
02033 enum JoinStationWidgets {
02034   JSW_WIDGET_CAPTION,
02035   JSW_PANEL,
02036   JSW_SCROLLBAR,
02037 };
02038 
02039 static const NWidgetPart _nested_select_station_widgets[] = {
02040   NWidget(NWID_HORIZONTAL),
02041     NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
02042     NWidget(WWT_CAPTION, COLOUR_DARK_GREEN, JSW_WIDGET_CAPTION), SetDataTip(STR_JOIN_STATION_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
02043   EndContainer(),
02044   NWidget(NWID_HORIZONTAL),
02045     NWidget(WWT_PANEL, COLOUR_DARK_GREEN, JSW_PANEL), SetResize(1, 0), SetScrollbar(JSW_SCROLLBAR), EndContainer(),
02046     NWidget(NWID_VERTICAL),
02047       NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, JSW_SCROLLBAR),
02048       NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
02049     EndContainer(),
02050   EndContainer(),
02051 };
02052 
02057 template <class T>
02058 struct SelectStationWindow : Window {
02059   CommandContainer select_station_cmd; 
02060   TileArea area; 
02061   Scrollbar *vscroll;
02062 
02063   SelectStationWindow(const WindowDesc *desc, CommandContainer cmd, TileArea ta) :
02064     Window(),
02065     select_station_cmd(cmd),
02066     area(ta)
02067   {
02068     this->CreateNestedTree(desc);
02069     this->vscroll = this->GetScrollbar(JSW_SCROLLBAR);
02070     this->GetWidget<NWidgetCore>(JSW_WIDGET_CAPTION)->widget_data = T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_JOIN_WAYPOINT_CAPTION : STR_JOIN_STATION_CAPTION;
02071     this->FinishInitNested(desc, 0);
02072     this->OnInvalidateData(0);
02073   }
02074 
02075   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
02076   {
02077     if (widget != JSW_PANEL) return;
02078 
02079     /* Determine the widest string */
02080     Dimension d = GetStringBoundingBox(T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_JOIN_WAYPOINT_CREATE_SPLITTED_WAYPOINT : STR_JOIN_STATION_CREATE_SPLITTED_STATION);
02081     for (uint i = 0; i < _stations_nearby_list.Length(); i++) {
02082       const T *st = T::Get(_stations_nearby_list[i]);
02083       SetDParam(0, st->index);
02084       SetDParam(1, st->facilities);
02085       d = maxdim(d, GetStringBoundingBox(T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_STATION_LIST_WAYPOINT : STR_STATION_LIST_STATION));
02086     }
02087 
02088     resize->height = d.height;
02089     d.height *= 5;
02090     d.width += WD_FRAMERECT_RIGHT + WD_FRAMERECT_LEFT;
02091     d.height += WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
02092     *size = d;
02093   }
02094 
02095   virtual void DrawWidget(const Rect &r, int widget) const
02096   {
02097     if (widget != JSW_PANEL) return;
02098 
02099     uint y = r.top + WD_FRAMERECT_TOP;
02100     if (this->vscroll->GetPosition() == 0) {
02101       DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_JOIN_WAYPOINT_CREATE_SPLITTED_WAYPOINT : STR_JOIN_STATION_CREATE_SPLITTED_STATION);
02102       y += this->resize.step_height;
02103     }
02104 
02105     for (uint i = max<uint>(1, this->vscroll->GetPosition()); i <= _stations_nearby_list.Length(); ++i, y += this->resize.step_height) {
02106       /* Don't draw anything if it extends past the end of the window. */
02107       if (i - this->vscroll->GetPosition() >= this->vscroll->GetCapacity()) break;
02108 
02109       const T *st = T::Get(_stations_nearby_list[i - 1]);
02110       SetDParam(0, st->index);
02111       SetDParam(1, st->facilities);
02112       DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_STATION_LIST_WAYPOINT : STR_STATION_LIST_STATION);
02113     }
02114   }
02115 
02116   virtual void OnClick(Point pt, int widget, int click_count)
02117   {
02118     if (widget != JSW_PANEL) return;
02119 
02120     uint st_index = this->vscroll->GetScrolledRowFromWidget(pt.y, this, JSW_PANEL, WD_FRAMERECT_TOP);
02121     bool distant_join = (st_index > 0);
02122     if (distant_join) st_index--;
02123 
02124     if (distant_join && st_index >= _stations_nearby_list.Length()) return;
02125 
02126     /* Insert station to be joined into stored command */
02127     SB(this->select_station_cmd.p2, 16, 16,
02128        (distant_join ? _stations_nearby_list[st_index] : NEW_STATION));
02129 
02130     /* Execute stored Command */
02131     DoCommandP(&this->select_station_cmd);
02132 
02133     /* Close Window; this might cause double frees! */
02134     DeleteWindowById(WC_SELECT_STATION, 0);
02135   }
02136 
02137   virtual void OnTick()
02138   {
02139     if (_thd.dirty & 2) {
02140       _thd.dirty &= ~2;
02141       this->SetDirty();
02142     }
02143   }
02144 
02145   virtual void OnResize()
02146   {
02147     this->vscroll->SetCapacityFromWidget(this, JSW_PANEL, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
02148   }
02149 
02155   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
02156   {
02157     if (!gui_scope) return;
02158     FindStationsNearby<T>(this->area, true);
02159     this->vscroll->SetCount(_stations_nearby_list.Length() + 1);
02160     this->SetDirty();
02161   }
02162 };
02163 
02164 static const WindowDesc _select_station_desc(
02165   WDP_AUTO, 200, 180,
02166   WC_SELECT_STATION, WC_NONE,
02167   WDF_CONSTRUCTION,
02168   _nested_select_station_widgets, lengthof(_nested_select_station_widgets)
02169 );
02170 
02171 
02179 template <class T>
02180 static bool StationJoinerNeeded(CommandContainer cmd, TileArea ta)
02181 {
02182   /* Only show selection if distant join is enabled in the settings */
02183   if (!_settings_game.station.distant_join_stations) return false;
02184 
02185   /* If a window is already opened and we didn't ctrl-click,
02186    * return true (i.e. just flash the old window) */
02187   Window *selection_window = FindWindowById(WC_SELECT_STATION, 0);
02188   if (selection_window != NULL) {
02189     /* Abort current distant-join and start new one */
02190     delete selection_window;
02191     UpdateTileSelection();
02192   }
02193 
02194   /* only show the popup, if we press ctrl */
02195   if (!_ctrl_pressed) return false;
02196 
02197   /* Now check if we could build there */
02198   if (DoCommand(&cmd, CommandFlagsToDCFlags(GetCommandFlags(cmd.cmd))).Failed()) return false;
02199 
02200   /* Test for adjacent station or station below selection.
02201    * If adjacent-stations is disabled and we are building next to a station, do not show the selection window.
02202    * but join the other station immediately. */
02203   const T *st = FindStationsNearby<T>(ta, false);
02204   return st == NULL && (_settings_game.station.adjacent_stations || _stations_nearby_list.Length() == 0);
02205 }
02206 
02213 template <class T>
02214 void ShowSelectBaseStationIfNeeded(CommandContainer cmd, TileArea ta)
02215 {
02216   if (StationJoinerNeeded<T>(cmd, ta)) {
02217     if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
02218     new SelectStationWindow<T>(&_select_station_desc, cmd, ta);
02219   } else {
02220     DoCommandP(&cmd);
02221   }
02222 }
02223 
02229 void ShowSelectStationIfNeeded(CommandContainer cmd, TileArea ta)
02230 {
02231   ShowSelectBaseStationIfNeeded<Station>(cmd, ta);
02232 }
02233 
02239 void ShowSelectWaypointIfNeeded(CommandContainer cmd, TileArea ta)
02240 {
02241   ShowSelectBaseStationIfNeeded<Waypoint>(cmd, ta);
02242 }