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 #include "town.h"
00033 
00034 #include "widgets/station_widget.h"
00035 
00036 #include "table/strings.h"
00037 
00038 #include <vector>
00039 
00050 int DrawStationCoverageAreaText(int left, int right, int top, StationCoverageType sct, int rad, bool supplies)
00051 {
00052   TileIndex tile = TileVirtXY(_thd.pos.x, _thd.pos.y);
00053   uint32 cargo_mask = 0;
00054   if (_thd.drawstyle == HT_RECT && tile < MapSize()) {
00055     CargoArray cargoes;
00056     if (supplies) {
00057       cargoes = GetProductionAroundTiles(tile, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE, rad);
00058     } else {
00059       cargoes = GetAcceptanceAroundTiles(tile, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE, rad);
00060     }
00061 
00062     /* Convert cargo counts to a set of cargo bits, and draw the result. */
00063     for (CargoID i = 0; i < NUM_CARGO; i++) {
00064       switch (sct) {
00065         case SCT_PASSENGERS_ONLY: if (!IsCargoInClass(i, CC_PASSENGERS)) continue; break;
00066         case SCT_NON_PASSENGERS_ONLY: if (IsCargoInClass(i, CC_PASSENGERS)) continue; break;
00067         case SCT_ALL: break;
00068         default: NOT_REACHED();
00069       }
00070       if (cargoes[i] >= (supplies ? 1U : 8U)) SetBit(cargo_mask, i);
00071     }
00072   }
00073   SetDParam(0, cargo_mask);
00074   return DrawStringMultiLine(left, right, top, INT32_MAX, supplies ? STR_STATION_BUILD_SUPPLIES_CARGO : STR_STATION_BUILD_ACCEPTS_CARGO);
00075 }
00076 
00082 void CheckRedrawStationCoverage(const Window *w)
00083 {
00084   if (_thd.dirty & 1) {
00085     _thd.dirty &= ~1;
00086     w->SetDirty();
00087   }
00088 }
00089 
00105 static void StationsWndShowStationRating(int left, int right, int y, CargoID type, uint amount, byte rating)
00106 {
00107   static const uint units_full  = 576; 
00108   static const uint rating_full = 224; 
00109 
00110   const CargoSpec *cs = CargoSpec::Get(type);
00111   if (!cs->IsValid()) return;
00112 
00113   int colour = cs->rating_colour;
00114   uint w = (minu(amount, units_full) + 5) / 36;
00115 
00116   int height = GetCharacterHeight(FS_SMALL);
00117 
00118   /* Draw total cargo (limited) on station (fits into 16 pixels) */
00119   if (w != 0) GfxFillRect(left, y, left + w - 1, y + height, colour);
00120 
00121   /* Draw a one pixel-wide bar of additional cargo meter, useful
00122    * for stations with only a small amount (<=30) */
00123   if (w == 0) {
00124     uint rest = amount / 5;
00125     if (rest != 0) {
00126       w += left;
00127       GfxFillRect(w, y + height - rest, w, y + height, colour);
00128     }
00129   }
00130 
00131   DrawString(left + 1, right, y, cs->abbrev, TC_BLACK);
00132 
00133   /* Draw green/red ratings bar (fits into 14 pixels) */
00134   y += height + 2;
00135   GfxFillRect(left + 1, y, left + 14, y, PC_RED);
00136   rating = minu(rating, rating_full) / 16;
00137   if (rating != 0) GfxFillRect(left + 1, y, left + rating, y, PC_GREEN);
00138 }
00139 
00140 typedef GUIList<const Station*> GUIStationList;
00141 
00145 class CompanyStationsWindow : public Window
00146 {
00147 protected:
00148   /* Runtime saved values */
00149   static Listing last_sorting;
00150   static byte facilities;               // types of stations of interest
00151   static bool include_empty;            // whether we should include stations without waiting cargo
00152   static const uint32 cargo_filter_max;
00153   static uint32 cargo_filter;           // bitmap of cargo types to include
00154   static const Station *last_station;
00155 
00156   /* Constants for sorting stations */
00157   static const StringID sorter_names[];
00158   static GUIStationList::SortFunction * const sorter_funcs[];
00159 
00160   GUIStationList stations;
00161   Scrollbar *vscroll;
00162 
00168   void BuildStationsList(const Owner owner)
00169   {
00170     if (!this->stations.NeedRebuild()) return;
00171 
00172     DEBUG(misc, 3, "Building station list for company %d", owner);
00173 
00174     this->stations.Clear();
00175 
00176     const Station *st;
00177     FOR_ALL_STATIONS(st) {
00178       if (st->owner == owner || (st->owner == OWNER_NONE && HasStationInUse(st->index, true, owner))) {
00179         if (this->facilities & st->facilities) { // only stations with selected facilities
00180           int num_waiting_cargo = 0;
00181           for (CargoID j = 0; j < NUM_CARGO; j++) {
00182             if (HasBit(st->goods[j].acceptance_pickup, GoodsEntry::GES_PICKUP)) {
00183               num_waiting_cargo++; // count number of waiting cargo
00184               if (HasBit(this->cargo_filter, j)) {
00185                 *this->stations.Append() = st;
00186                 break;
00187               }
00188             }
00189           }
00190           /* stations without waiting cargo */
00191           if (num_waiting_cargo == 0 && this->include_empty) {
00192             *this->stations.Append() = st;
00193           }
00194         }
00195       }
00196     }
00197 
00198     this->stations.Compact();
00199     this->stations.RebuildDone();
00200 
00201     this->vscroll->SetCount(this->stations.Length()); // Update the scrollbar
00202   }
00203 
00205   static int CDECL StationNameSorter(const Station * const *a, const Station * const *b)
00206   {
00207     static char buf_cache[64];
00208     char buf[64];
00209 
00210     SetDParam(0, (*a)->index);
00211     GetString(buf, STR_STATION_NAME, lastof(buf));
00212 
00213     if (*b != last_station) {
00214       last_station = *b;
00215       SetDParam(0, (*b)->index);
00216       GetString(buf_cache, STR_STATION_NAME, lastof(buf_cache));
00217     }
00218 
00219     return strcmp(buf, buf_cache);
00220   }
00221 
00223   static int CDECL StationTypeSorter(const Station * const *a, const Station * const *b)
00224   {
00225     return (*a)->facilities - (*b)->facilities;
00226   }
00227 
00229   static int CDECL StationWaitingSorter(const Station * const *a, const Station * const *b)
00230   {
00231     Money diff = 0;
00232 
00233     CargoID j;
00234     FOR_EACH_SET_CARGO_ID(j, cargo_filter) {
00235       if (!(*a)->goods[j].cargo.Empty()) diff += GetTransportedGoodsIncome((*a)->goods[j].cargo.Count(), 20, 50, j);
00236       if (!(*b)->goods[j].cargo.Empty()) diff -= GetTransportedGoodsIncome((*b)->goods[j].cargo.Count(), 20, 50, j);
00237     }
00238 
00239     return ClampToI32(diff);
00240   }
00241 
00243   static int CDECL StationRatingMaxSorter(const Station * const *a, const Station * const *b)
00244   {
00245     byte maxr1 = 0;
00246     byte maxr2 = 0;
00247 
00248     CargoID j;
00249     FOR_EACH_SET_CARGO_ID(j, cargo_filter) {
00250       if (HasBit((*a)->goods[j].acceptance_pickup, GoodsEntry::GES_PICKUP)) maxr1 = max(maxr1, (*a)->goods[j].rating);
00251       if (HasBit((*b)->goods[j].acceptance_pickup, GoodsEntry::GES_PICKUP)) maxr2 = max(maxr2, (*b)->goods[j].rating);
00252     }
00253 
00254     return maxr1 - maxr2;
00255   }
00256 
00258   static int CDECL StationRatingMinSorter(const Station * const *a, const Station * const *b)
00259   {
00260     byte minr1 = 255;
00261     byte minr2 = 255;
00262 
00263     for (CargoID j = 0; j < NUM_CARGO; j++) {
00264       if (!HasBit(cargo_filter, j)) continue;
00265       if (HasBit((*a)->goods[j].acceptance_pickup, GoodsEntry::GES_PICKUP)) minr1 = min(minr1, (*a)->goods[j].rating);
00266       if (HasBit((*b)->goods[j].acceptance_pickup, GoodsEntry::GES_PICKUP)) minr2 = min(minr2, (*b)->goods[j].rating);
00267     }
00268 
00269     return -(minr1 - minr2);
00270   }
00271 
00273   void SortStationsList()
00274   {
00275     if (!this->stations.Sort()) return;
00276 
00277     /* Reset name sorter sort cache */
00278     this->last_station = NULL;
00279 
00280     /* Set the modified widget dirty */
00281     this->SetWidgetDirty(WID_STL_LIST);
00282   }
00283 
00284 public:
00285   CompanyStationsWindow(const WindowDesc *desc, WindowNumber window_number) : Window()
00286   {
00287     this->stations.SetListing(this->last_sorting);
00288     this->stations.SetSortFuncs(this->sorter_funcs);
00289     this->stations.ForceRebuild();
00290     this->stations.NeedResort();
00291     this->SortStationsList();
00292 
00293     this->CreateNestedTree(desc);
00294     this->vscroll = this->GetScrollbar(WID_STL_SCROLLBAR);
00295     this->FinishInitNested(desc, window_number);
00296     this->owner = (Owner)this->window_number;
00297 
00298     CargoID cid;
00299     FOR_EACH_SET_CARGO_ID(cid, this->cargo_filter) {
00300       if (CargoSpec::Get(cid)->IsValid()) this->LowerWidget(WID_STL_CARGOSTART + cid);
00301     }
00302 
00303     if (this->cargo_filter == this->cargo_filter_max) this->cargo_filter = _cargo_mask;
00304 
00305     for (uint i = 0; i < 5; i++) {
00306       if (HasBit(this->facilities, i)) this->LowerWidget(i + WID_STL_TRAIN);
00307     }
00308     this->SetWidgetLoweredState(WID_STL_NOCARGOWAITING, this->include_empty);
00309 
00310     this->GetWidget<NWidgetCore>(WID_STL_SORTDROPBTN)->widget_data = this->sorter_names[this->stations.SortType()];
00311   }
00312 
00313   ~CompanyStationsWindow()
00314   {
00315     this->last_sorting = this->stations.GetListing();
00316   }
00317 
00318   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00319   {
00320     switch (widget) {
00321       case WID_STL_SORTBY: {
00322         Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
00323         d.width += padding.width + WD_SORTBUTTON_ARROW_WIDTH * 2; // Doubled since the string is centred and it also looks better.
00324         d.height += padding.height;
00325         *size = maxdim(*size, d);
00326         break;
00327       }
00328 
00329       case WID_STL_SORTDROPBTN: {
00330         Dimension d = {0, 0};
00331         for (int i = 0; this->sorter_names[i] != INVALID_STRING_ID; i++) {
00332           d = maxdim(d, GetStringBoundingBox(this->sorter_names[i]));
00333         }
00334         d.width += padding.width;
00335         d.height += padding.height;
00336         *size = maxdim(*size, d);
00337         break;
00338       }
00339 
00340       case WID_STL_LIST:
00341         resize->height = FONT_HEIGHT_NORMAL;
00342         size->height = WD_FRAMERECT_TOP + 5 * resize->height + WD_FRAMERECT_BOTTOM;
00343         break;
00344 
00345       case WID_STL_TRAIN:
00346       case WID_STL_TRUCK:
00347       case WID_STL_BUS:
00348       case WID_STL_AIRPLANE:
00349       case WID_STL_SHIP:
00350         size->height = max<uint>(FONT_HEIGHT_SMALL, 10) + padding.height;
00351         break;
00352 
00353       case WID_STL_CARGOALL:
00354       case WID_STL_FACILALL:
00355       case WID_STL_NOCARGOWAITING: {
00356         Dimension d = GetStringBoundingBox(widget == WID_STL_NOCARGOWAITING ? STR_ABBREV_NONE : STR_ABBREV_ALL);
00357         d.width  += padding.width + 2;
00358         d.height += padding.height;
00359         *size = maxdim(*size, d);
00360         break;
00361       }
00362 
00363       default:
00364         if (widget >= WID_STL_CARGOSTART) {
00365           const CargoSpec *cs = CargoSpec::Get(widget - WID_STL_CARGOSTART);
00366           if (cs->IsValid()) {
00367             Dimension d = GetStringBoundingBox(cs->abbrev);
00368             d.width  += padding.width + 2;
00369             d.height += padding.height;
00370             *size = maxdim(*size, d);
00371           }
00372         }
00373         break;
00374     }
00375   }
00376 
00377   virtual void OnPaint()
00378   {
00379     this->BuildStationsList((Owner)this->window_number);
00380     this->SortStationsList();
00381 
00382     this->DrawWidgets();
00383   }
00384 
00385   virtual void DrawWidget(const Rect &r, int widget) const
00386   {
00387     switch (widget) {
00388       case WID_STL_SORTBY:
00389         /* draw arrow pointing up/down for ascending/descending sorting */
00390         this->DrawSortButtonState(WID_STL_SORTBY, this->stations.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
00391         break;
00392 
00393       case WID_STL_LIST: {
00394         bool rtl = _current_text_dir == TD_RTL;
00395         int max = min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->stations.Length());
00396         int y = r.top + WD_FRAMERECT_TOP;
00397         for (int i = this->vscroll->GetPosition(); i < max; ++i) { // do until max number of stations of owner
00398           const Station *st = this->stations[i];
00399           assert(st->xy != INVALID_TILE);
00400 
00401           /* Do not do the complex check HasStationInUse here, it may be even false
00402            * when the order had been removed and the station list hasn't been removed yet */
00403           assert(st->owner == owner || st->owner == OWNER_NONE);
00404 
00405           SetDParam(0, st->index);
00406           SetDParam(1, st->facilities);
00407           int x = DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_LIST_STATION);
00408           x += rtl ? -5 : 5;
00409 
00410           /* show cargo waiting and station ratings */
00411           for (CargoID j = 0; j < NUM_CARGO; j++) {
00412             if (!st->goods[j].cargo.Empty()) {
00413               /* For RTL we work in exactly the opposite direction. So
00414                * decrement the space needed first, then draw to the left
00415                * instead of drawing to the left and then incrementing
00416                * the space. */
00417               if (rtl) {
00418                 x -= 20;
00419                 if (x < r.left + WD_FRAMERECT_LEFT) break;
00420               }
00421               StationsWndShowStationRating(x, x + 16, y, j, st->goods[j].cargo.Count(), st->goods[j].rating);
00422               if (!rtl) {
00423                 x += 20;
00424                 if (x > r.right - WD_FRAMERECT_RIGHT) break;
00425               }
00426             }
00427           }
00428           y += FONT_HEIGHT_NORMAL;
00429         }
00430 
00431         if (this->vscroll->GetCount() == 0) { // company has no stations
00432           DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_LIST_NONE);
00433           return;
00434         }
00435         break;
00436       }
00437 
00438       case WID_STL_NOCARGOWAITING: {
00439         int cg_ofst = this->IsWidgetLowered(widget) ? 2 : 1;
00440         DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, STR_ABBREV_NONE, TC_BLACK, SA_HOR_CENTER);
00441         break;
00442       }
00443 
00444       case WID_STL_CARGOALL: {
00445         int cg_ofst = this->IsWidgetLowered(widget) ? 2 : 1;
00446         DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, STR_ABBREV_ALL, TC_BLACK, SA_HOR_CENTER);
00447         break;
00448       }
00449 
00450       case WID_STL_FACILALL: {
00451         int cg_ofst = this->IsWidgetLowered(widget) ? 2 : 1;
00452         DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, STR_ABBREV_ALL, TC_BLACK);
00453         break;
00454       }
00455 
00456       default:
00457         if (widget >= WID_STL_CARGOSTART) {
00458           const CargoSpec *cs = CargoSpec::Get(widget - WID_STL_CARGOSTART);
00459           if (cs->IsValid()) {
00460             int cg_ofst = HasBit(this->cargo_filter, cs->Index()) ? 2 : 1;
00461             GfxFillRect(r.left + cg_ofst, r.top + cg_ofst, r.right - 2 + cg_ofst, r.bottom - 2 + cg_ofst, cs->rating_colour);
00462             DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, cs->abbrev, TC_BLACK, SA_HOR_CENTER);
00463           }
00464         }
00465         break;
00466     }
00467   }
00468 
00469   virtual void SetStringParameters(int widget) const
00470   {
00471     if (widget == WID_STL_CAPTION) {
00472       SetDParam(0, this->window_number);
00473       SetDParam(1, this->vscroll->GetCount());
00474     }
00475   }
00476 
00477   virtual void OnClick(Point pt, int widget, int click_count)
00478   {
00479     switch (widget) {
00480       case WID_STL_LIST: {
00481         uint id_v = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_STL_LIST, 0, FONT_HEIGHT_NORMAL);
00482         if (id_v >= this->stations.Length()) return; // click out of list bound
00483 
00484         const Station *st = this->stations[id_v];
00485         /* do not check HasStationInUse - it is slow and may be invalid */
00486         assert(st->owner == (Owner)this->window_number || st->owner == OWNER_NONE);
00487 
00488         if (_ctrl_pressed) {
00489           ShowExtraViewPortWindow(st->xy);
00490         } else {
00491           ScrollMainWindowToTile(st->xy);
00492         }
00493         break;
00494       }
00495 
00496       case WID_STL_TRAIN:
00497       case WID_STL_TRUCK:
00498       case WID_STL_BUS:
00499       case WID_STL_AIRPLANE:
00500       case WID_STL_SHIP:
00501         if (_ctrl_pressed) {
00502           ToggleBit(this->facilities, widget - WID_STL_TRAIN);
00503           this->ToggleWidgetLoweredState(widget);
00504         } else {
00505           uint i;
00506           FOR_EACH_SET_BIT(i, this->facilities) {
00507             this->RaiseWidget(i + WID_STL_TRAIN);
00508           }
00509           this->facilities = 1 << (widget - WID_STL_TRAIN);
00510           this->LowerWidget(widget);
00511         }
00512         this->stations.ForceRebuild();
00513         this->SetDirty();
00514         break;
00515 
00516       case WID_STL_FACILALL:
00517         for (uint i = WID_STL_TRAIN; i <= WID_STL_SHIP; i++) {
00518           this->LowerWidget(i);
00519         }
00520 
00521         this->facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK;
00522         this->stations.ForceRebuild();
00523         this->SetDirty();
00524         break;
00525 
00526       case WID_STL_CARGOALL: {
00527         for (uint i = 0; i < NUM_CARGO; i++) {
00528           const CargoSpec *cs = CargoSpec::Get(i);
00529           if (cs->IsValid()) this->LowerWidget(WID_STL_CARGOSTART + i);
00530         }
00531         this->LowerWidget(WID_STL_NOCARGOWAITING);
00532 
00533         this->cargo_filter = _cargo_mask;
00534         this->include_empty = true;
00535         this->stations.ForceRebuild();
00536         this->SetDirty();
00537         break;
00538       }
00539 
00540       case WID_STL_SORTBY: // flip sorting method asc/desc
00541         this->stations.ToggleSortOrder();
00542         this->SetTimeout();
00543         this->LowerWidget(WID_STL_SORTBY);
00544         this->SetDirty();
00545         break;
00546 
00547       case WID_STL_SORTDROPBTN: // select sorting criteria dropdown menu
00548         ShowDropDownMenu(this, this->sorter_names, this->stations.SortType(), WID_STL_SORTDROPBTN, 0, 0);
00549         break;
00550 
00551       case WID_STL_NOCARGOWAITING:
00552         if (_ctrl_pressed) {
00553           this->include_empty = !this->include_empty;
00554           this->ToggleWidgetLoweredState(WID_STL_NOCARGOWAITING);
00555         } else {
00556           for (uint i = 0; i < NUM_CARGO; i++) {
00557             const CargoSpec *cs = CargoSpec::Get(i);
00558             if (cs->IsValid()) this->RaiseWidget(WID_STL_CARGOSTART + i);
00559           }
00560 
00561           this->cargo_filter = 0;
00562           this->include_empty = true;
00563 
00564           this->LowerWidget(WID_STL_NOCARGOWAITING);
00565         }
00566         this->stations.ForceRebuild();
00567         this->SetDirty();
00568         break;
00569 
00570       default:
00571         if (widget >= WID_STL_CARGOSTART) { // change cargo_filter
00572           /* Determine the selected cargo type */
00573           const CargoSpec *cs = CargoSpec::Get(widget - WID_STL_CARGOSTART);
00574           if (!cs->IsValid()) break;
00575 
00576           if (_ctrl_pressed) {
00577             ToggleBit(this->cargo_filter, cs->Index());
00578             this->ToggleWidgetLoweredState(widget);
00579           } else {
00580             for (uint i = 0; i < NUM_CARGO; i++) {
00581               const CargoSpec *cs = CargoSpec::Get(i);
00582               if (cs->IsValid()) this->RaiseWidget(WID_STL_CARGOSTART + i);
00583             }
00584             this->RaiseWidget(WID_STL_NOCARGOWAITING);
00585 
00586             this->cargo_filter = 0;
00587             this->include_empty = false;
00588 
00589             SetBit(this->cargo_filter, cs->Index());
00590             this->LowerWidget(widget);
00591           }
00592           this->stations.ForceRebuild();
00593           this->SetDirty();
00594         }
00595         break;
00596     }
00597   }
00598 
00599   virtual void OnDropdownSelect(int widget, int index)
00600   {
00601     if (this->stations.SortType() != index) {
00602       this->stations.SetSortType(index);
00603 
00604       /* Display the current sort variant */
00605       this->GetWidget<NWidgetCore>(WID_STL_SORTDROPBTN)->widget_data = this->sorter_names[this->stations.SortType()];
00606 
00607       this->SetDirty();
00608     }
00609   }
00610 
00611   virtual void OnTick()
00612   {
00613     if (_pause_mode != PM_UNPAUSED) return;
00614     if (this->stations.NeedResort()) {
00615       DEBUG(misc, 3, "Periodic rebuild station list company %d", this->window_number);
00616       this->SetDirty();
00617     }
00618   }
00619 
00620   virtual void OnTimeout()
00621   {
00622     this->RaiseWidget(WID_STL_SORTBY);
00623     this->SetDirty();
00624   }
00625 
00626   virtual void OnResize()
00627   {
00628     this->vscroll->SetCapacityFromWidget(this, WID_STL_LIST, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
00629   }
00630 
00636   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
00637   {
00638     if (data == 0) {
00639       /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
00640       this->stations.ForceRebuild();
00641     } else {
00642       this->stations.ForceResort();
00643     }
00644   }
00645 };
00646 
00647 Listing CompanyStationsWindow::last_sorting = {false, 0};
00648 byte CompanyStationsWindow::facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK;
00649 bool CompanyStationsWindow::include_empty = true;
00650 const uint32 CompanyStationsWindow::cargo_filter_max = UINT32_MAX;
00651 uint32 CompanyStationsWindow::cargo_filter = UINT32_MAX;
00652 const Station *CompanyStationsWindow::last_station = NULL;
00653 
00654 /* Availible station sorting functions */
00655 GUIStationList::SortFunction * const CompanyStationsWindow::sorter_funcs[] = {
00656   &StationNameSorter,
00657   &StationTypeSorter,
00658   &StationWaitingSorter,
00659   &StationRatingMaxSorter,
00660   &StationRatingMinSorter
00661 };
00662 
00663 /* Names of the sorting functions */
00664 const StringID CompanyStationsWindow::sorter_names[] = {
00665   STR_SORT_BY_NAME,
00666   STR_SORT_BY_FACILITY,
00667   STR_SORT_BY_WAITING,
00668   STR_SORT_BY_RATING_MAX,
00669   STR_SORT_BY_RATING_MIN,
00670   INVALID_STRING_ID
00671 };
00672 
00678 static NWidgetBase *CargoWidgets(int *biggest_index)
00679 {
00680   NWidgetHorizontal *container = new NWidgetHorizontal();
00681 
00682   for (uint i = 0; i < NUM_CARGO; i++) {
00683     const CargoSpec *cs = CargoSpec::Get(i);
00684     if (cs->IsValid()) {
00685       NWidgetBackground *panel = new NWidgetBackground(WWT_PANEL, COLOUR_GREY, WID_STL_CARGOSTART + i);
00686       panel->SetMinimalSize(14, 11);
00687       panel->SetResize(0, 0);
00688       panel->SetFill(0, 1);
00689       panel->SetDataTip(0, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE);
00690       container->Add(panel);
00691     } else {
00692       NWidgetLeaf *nwi = new NWidgetLeaf(WWT_EMPTY, COLOUR_GREY, WID_STL_CARGOSTART + i, 0x0, STR_NULL);
00693       nwi->SetMinimalSize(0, 11);
00694       nwi->SetResize(0, 0);
00695       nwi->SetFill(0, 1);
00696       container->Add(nwi);
00697     }
00698   }
00699   *biggest_index = WID_STL_CARGOSTART + NUM_CARGO;
00700   return container;
00701 }
00702 
00703 static const NWidgetPart _nested_company_stations_widgets[] = {
00704   NWidget(NWID_HORIZONTAL),
00705     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
00706     NWidget(WWT_CAPTION, COLOUR_GREY, WID_STL_CAPTION), SetDataTip(STR_STATION_LIST_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00707     NWidget(WWT_SHADEBOX, COLOUR_GREY),
00708     NWidget(WWT_STICKYBOX, COLOUR_GREY),
00709   EndContainer(),
00710   NWidget(NWID_HORIZONTAL),
00711     NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_STL_TRAIN), SetMinimalSize(14, 11), SetDataTip(STR_TRAIN, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
00712     NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_STL_TRUCK), SetMinimalSize(14, 11), SetDataTip(STR_LORRY, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
00713     NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_STL_BUS), SetMinimalSize(14, 11), SetDataTip(STR_BUS, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
00714     NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_STL_SHIP), SetMinimalSize(14, 11), SetDataTip(STR_SHIP, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
00715     NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_STL_AIRPLANE), SetMinimalSize(14, 11), SetDataTip(STR_PLANE, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
00716     NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_STL_FACILALL), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_SELECT_ALL_FACILITIES), SetFill(0, 1),
00717     NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(5, 11), SetFill(0, 1), EndContainer(),
00718     NWidgetFunction(CargoWidgets),
00719     NWidget(WWT_PANEL, COLOUR_GREY, WID_STL_NOCARGOWAITING), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_NO_WAITING_CARGO), SetFill(0, 1), EndContainer(),
00720     NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_STL_CARGOALL), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_SELECT_ALL_TYPES), SetFill(0, 1),
00721     NWidget(WWT_PANEL, COLOUR_GREY), SetDataTip(0x0, STR_NULL), SetResize(1, 0), SetFill(1, 1), EndContainer(),
00722   EndContainer(),
00723   NWidget(NWID_HORIZONTAL),
00724     NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_STL_SORTBY), SetMinimalSize(81, 12), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
00725     NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_STL_SORTDROPBTN), SetMinimalSize(163, 12), SetDataTip(STR_SORT_BY_NAME, STR_TOOLTIP_SORT_CRITERIA), // widget_data gets overwritten.
00726     NWidget(WWT_PANEL, COLOUR_GREY), SetDataTip(0x0, STR_NULL), SetResize(1, 0), SetFill(1, 1), EndContainer(),
00727   EndContainer(),
00728   NWidget(NWID_HORIZONTAL),
00729     NWidget(WWT_PANEL, COLOUR_GREY, WID_STL_LIST), SetMinimalSize(346, 125), SetResize(1, 10), SetDataTip(0x0, STR_STATION_LIST_TOOLTIP), SetScrollbar(WID_STL_SCROLLBAR), EndContainer(),
00730     NWidget(NWID_VERTICAL),
00731       NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_STL_SCROLLBAR),
00732       NWidget(WWT_RESIZEBOX, COLOUR_GREY),
00733     EndContainer(),
00734   EndContainer(),
00735 };
00736 
00737 static const WindowDesc _company_stations_desc(
00738   WDP_AUTO, 358, 162,
00739   WC_STATION_LIST, WC_NONE,
00740   WDF_UNCLICK_BUTTONS,
00741   _nested_company_stations_widgets, lengthof(_nested_company_stations_widgets)
00742 );
00743 
00749 void ShowCompanyStations(CompanyID company)
00750 {
00751   if (!Company::IsValidID(company)) return;
00752 
00753   AllocateWindowDescFront<CompanyStationsWindow>(&_company_stations_desc, company);
00754 }
00755 
00756 static const NWidgetPart _nested_station_view_widgets[] = {
00757   NWidget(NWID_HORIZONTAL),
00758     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
00759     NWidget(WWT_CAPTION, COLOUR_GREY, WID_SV_CAPTION), SetDataTip(STR_STATION_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00760     NWidget(WWT_SHADEBOX, COLOUR_GREY),
00761     NWidget(WWT_STICKYBOX, COLOUR_GREY),
00762   EndContainer(),
00763   NWidget(NWID_HORIZONTAL),
00764     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_SORT_ORDER), SetMinimalSize(81, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
00765     NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_SV_SORT_BY), SetMinimalSize(168, 12), SetResize(1, 0), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
00766   EndContainer(),
00767   NWidget(NWID_HORIZONTAL),
00768     NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_SV_GROUP), SetMinimalSize(81, 12), SetFill(1, 1), SetDataTip(STR_STATION_VIEW_GROUP, 0x0),
00769     NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_SV_GROUP_BY), SetMinimalSize(168, 12), SetResize(1, 0), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_GROUP_ORDER),
00770   EndContainer(),
00771   NWidget(NWID_HORIZONTAL),
00772     NWidget(WWT_PANEL, COLOUR_GREY, WID_SV_WAITING), SetMinimalSize(237, 44), SetResize(1, 10), SetScrollbar(WID_SV_SCROLLBAR), EndContainer(),
00773     NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_SV_SCROLLBAR),
00774   EndContainer(),
00775   NWidget(WWT_PANEL, COLOUR_GREY, WID_SV_ACCEPT_RATING_LIST), SetMinimalSize(249, 23), SetResize(1, 0), EndContainer(),
00776   NWidget(NWID_HORIZONTAL),
00777     NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
00778       NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_LOCATION), SetMinimalSize(45, 12), SetResize(1, 0), SetFill(1, 1),
00779           SetDataTip(STR_BUTTON_LOCATION, STR_STATION_VIEW_CENTER_TOOLTIP),
00780       NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_ACCEPTS_RATINGS), SetMinimalSize(46, 12), SetResize(1, 0), SetFill(1, 1),
00781           SetDataTip(STR_STATION_VIEW_RATINGS_BUTTON, STR_STATION_VIEW_RATINGS_TOOLTIP),
00782       NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_RENAME), SetMinimalSize(45, 12), SetResize(1, 0), SetFill(1, 1),
00783           SetDataTip(STR_BUTTON_RENAME, STR_STATION_VIEW_RENAME_TOOLTIP),
00784     EndContainer(),
00785     NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_SV_CLOSE_AIRPORT), SetMinimalSize(45, 12), SetResize(1, 0), SetFill(1, 1),
00786         SetDataTip(STR_STATION_VIEW_CLOSE_AIRPORT, STR_STATION_VIEW_CLOSE_AIRPORT_TOOLTIP),
00787     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_TRAINS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_TRAIN, STR_STATION_VIEW_SCHEDULED_TRAINS_TOOLTIP),
00788     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_ROADVEHS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_LORRY, STR_STATION_VIEW_SCHEDULED_ROAD_VEHICLES_TOOLTIP),
00789     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_SHIPS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_SHIP, STR_STATION_VIEW_SCHEDULED_SHIPS_TOOLTIP),
00790     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_PLANES),  SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_PLANE, STR_STATION_VIEW_SCHEDULED_AIRCRAFT_TOOLTIP),
00791     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
00792   EndContainer(),
00793 };
00794 
00805 static void DrawCargoIcons(CargoID i, uint waiting, int left, int right, int y)
00806 {
00807   uint num = min((waiting + 5) / 10, (right - left) / 10); // maximum is width / 10 icons so it won't overflow
00808   if (num == 0) return;
00809 
00810   SpriteID sprite = CargoSpec::Get(i)->GetCargoIcon();
00811 
00812   int x = _current_text_dir == TD_RTL ? left : right - num * 10;
00813   do {
00814     DrawSprite(sprite, PAL_NONE, x, y);
00815     x += 10;
00816   } while (--num);
00817 }
00818 
00819 CargoDataEntry::CargoDataEntry() :
00820   parent(NULL),
00821   station(INVALID_STATION),
00822   num_children(0),
00823   count(0),
00824   children(new CargoDataSet(CargoSorter(ST_CARGO_ID)))
00825 {}
00826 
00827 CargoDataEntry::CargoDataEntry(CargoID cargo, uint count, CargoDataEntry *parent) :
00828   parent(parent),
00829   cargo(cargo),
00830   num_children(0),
00831   count(count),
00832   children(new CargoDataSet)
00833 {}
00834 
00835 CargoDataEntry::CargoDataEntry(StationID station, uint count, CargoDataEntry *parent) :
00836   parent(parent),
00837   station(station),
00838   num_children(0),
00839   count(count),
00840   children(new CargoDataSet)
00841 {}
00842 
00843 CargoDataEntry::CargoDataEntry(StationID station) :
00844   parent(NULL),
00845   station(station),
00846   num_children(0),
00847   count(0),
00848   children(NULL)
00849 {}
00850 
00851 CargoDataEntry::CargoDataEntry(CargoID cargo) :
00852   parent(NULL),
00853   cargo(cargo),
00854   num_children(0),
00855   count(0),
00856   children(NULL)
00857 {}
00858 
00859 CargoDataEntry::~CargoDataEntry()
00860 {
00861   this->Clear();
00862   delete this->children;
00863 }
00864 
00868 void CargoDataEntry::Clear()
00869 {
00870   if (this->children != NULL) {
00871     for (CargoDataSet::iterator i = this->children->begin(); i != this->children->end(); ++i) {
00872       assert(*i != this);
00873       delete *i;
00874     }
00875     this->children->clear();
00876   }
00877   if (this->parent != NULL) this->parent->count -= this->count;
00878   this->count = 0;
00879   this->num_children = 0;
00880 }
00881 
00888 void CargoDataEntry::Remove(CargoDataEntry *child)
00889 {
00890   CargoDataSet::iterator i = this->children->find(child);
00891   if (i != this->children->end()) {
00892     delete *i;
00893     this->children->erase(i);
00894   }
00895 }
00896 
00903 template<class ID>
00904 CargoDataEntry *CargoDataEntry::InsertOrRetrieve(ID child_id)
00905 {
00906   CargoDataEntry tmp(child_id);
00907   CargoDataSet::iterator i = this->children->find(&tmp);
00908   if (i == this->children->end()) {
00909     IncrementSize();
00910     return *(this->children->insert(new CargoDataEntry(child_id, 0, this)).first);
00911   } else {
00912     CargoDataEntry *ret = *i;
00913     assert(this->children->value_comp().GetSortType() != ST_COUNT);
00914     return ret;
00915   }
00916 }
00917 
00923 void CargoDataEntry::Update(uint count)
00924 {
00925   this->count += count;
00926   if (this->parent != NULL) this->parent->Update(count);
00927 }
00928 
00932 void CargoDataEntry::IncrementSize()
00933 {
00934    ++this->num_children;
00935    if (this->parent != NULL) this->parent->IncrementSize();
00936 }
00937 
00938 void CargoDataEntry::Resort(CargoSortType type, SortOrder order)
00939 {
00940   CargoDataSet *new_subs = new CargoDataSet(this->children->begin(), this->children->end(), CargoSorter(type, order));
00941   delete this->children;
00942   this->children = new_subs;
00943 }
00944 
00945 CargoDataEntry *CargoDataEntry::Retrieve(CargoDataSet::iterator i) const
00946 {
00947   if (i == this->children->end()) {
00948     return NULL;
00949   } else {
00950     assert(this->children->value_comp().GetSortType() != ST_COUNT);
00951     return *i;
00952   }
00953 }
00954 
00955 bool CargoSorter::operator()(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const
00956 {
00957   switch (this->type) {
00958     case ST_STATION_ID:
00959       return this->SortId<StationID>(cd1->GetStation(), cd2->GetStation());
00960       break;
00961     case ST_CARGO_ID:
00962       return this->SortId<CargoID>(cd1->GetCargo(), cd2->GetCargo());
00963       break;
00964     case ST_COUNT:
00965       return this->SortCount(cd1, cd2);
00966       break;
00967     case ST_STATION_STRING:
00968       return this->SortStation(cd1->GetStation(), cd2->GetStation());
00969       break;
00970     default:
00971       NOT_REACHED();
00972   }
00973 }
00974 
00975 template<class ID>
00976 bool CargoSorter::SortId(ID st1, ID st2) const
00977 {
00978   return (this->order == SO_ASCENDING) ? st1 < st2 : st2 < st1;
00979 }
00980 
00981 bool CargoSorter::SortCount(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const
00982 {
00983   uint c1 = cd1->GetCount();
00984   uint c2 = cd2->GetCount();
00985   if (c1 == c2) {
00986     return this->SortStation(cd1->GetStation(), cd2->GetStation());
00987   } else if (this->order == SO_ASCENDING) {
00988     return c1 < c2;
00989   } else {
00990     return c2 < c1;
00991   }
00992 }
00993 
00994 bool CargoSorter::SortStation(StationID st1, StationID st2) const
00995 {
00996   static char buf1[MAX_LENGTH_STATION_NAME_CHARS];
00997   static char buf2[MAX_LENGTH_STATION_NAME_CHARS];
00998 
00999   if (!Station::IsValidID(st1)) {
01000     return Station::IsValidID(st2) ? this->order == SO_ASCENDING : this->SortId(st1, st2);
01001   } else if (!Station::IsValidID(st2)) {
01002     return order == SO_DESCENDING;
01003   }
01004 
01005   SetDParam(0, st1);
01006   GetString(buf1, STR_STATION_NAME, lastof(buf1));
01007   SetDParam(0, st2);
01008   GetString(buf2, STR_STATION_NAME, lastof(buf2));
01009 
01010   int res = strcmp(buf1, buf2);
01011   if (res == 0) {
01012     return this->SortId(st1, st2);
01013   } else {
01014     return (this->order == SO_ASCENDING) ? res < 0 : res > 0;
01015   }
01016 }
01017 
01021 struct StationViewWindow : public Window {
01025   struct RowDisplay {
01026     RowDisplay(CargoDataEntry *f, StationID n) : filter(f), next_station(n) {}
01027     RowDisplay(CargoDataEntry *f, CargoID n) : filter(f), next_cargo(n) {}
01028 
01032     CargoDataEntry *filter;
01033     union {
01037       StationID next_station;
01038 
01042       CargoID next_cargo;
01043     };
01044   };
01045 
01046   typedef std::vector<RowDisplay> CargoDataVector;
01047 
01048   static const int NUM_COLUMNS = 4; 
01049 
01053   enum Invalidation {
01054     INV_FLOWS = 0x100, 
01055     INV_CARGO = 0x200  
01056   };
01057 
01061   enum Grouping {
01062     GR_SOURCE,      
01063     GR_NEXT,        
01064     GR_DESTINATION, 
01065     GR_CARGO,       
01066   };
01067 
01071   enum Mode {
01072     MODE_WAITING, 
01073     MODE_PLANNED  
01074   };
01075 
01076   uint expand_shrink_width;     
01077   int rating_lines;             
01078   int accepts_lines;            
01079   Scrollbar *vscroll;
01080 
01082   enum AcceptListHeight {
01083     ALH_RATING  = 13, 
01084     ALH_ACCEPTS = 3,  
01085   };
01086 
01087   static const StringID _sort_names[];  
01088   static const StringID _group_names[]; 
01089 
01096   CargoSortType sortings[NUM_COLUMNS];
01097 
01099   SortOrder sort_orders[NUM_COLUMNS];
01100 
01101   int scroll_to_row;                  
01102   int grouping_index;                 
01103   Mode current_mode;                  
01104   Grouping groupings[NUM_COLUMNS];    
01105 
01106   CargoDataEntry expanded_rows;       
01107   CargoDataEntry cached_destinations; 
01108   CargoDataVector displayed_rows;     
01109 
01110   StationViewWindow(const WindowDesc *desc, WindowNumber window_number) : Window(),
01111     scroll_to_row(INT_MAX), grouping_index(0)
01112   {
01113     this->rating_lines  = ALH_RATING;
01114     this->accepts_lines = ALH_ACCEPTS;
01115 
01116     this->CreateNestedTree(desc);
01117     this->vscroll = this->GetScrollbar(WID_SV_SCROLLBAR);
01118     /* Nested widget tree creation is done in two steps to ensure that this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS) exists in UpdateWidgetSize(). */
01119     this->FinishInitNested(desc, window_number);
01120 
01121     this->groupings[0] = GR_CARGO;
01122     this->sortings[0] = ST_AS_GROUPING;
01123     this->SelectGroupBy(_settings_client.gui.station_gui_group_order);
01124     this->SelectSortBy(_settings_client.gui.station_gui_sort_by);
01125     this->sort_orders[0] = SO_ASCENDING;
01126     this->SelectSortOrder((SortOrder)_settings_client.gui.station_gui_sort_order);
01127     Owner owner = Station::Get(window_number)->owner;
01128     if (owner != OWNER_NONE) this->owner = owner;
01129   }
01130 
01131   ~StationViewWindow()
01132   {
01133     Owner owner = Station::Get(this->window_number)->owner;
01134     DeleteWindowById(WC_TRAINS_LIST,   VehicleListIdentifier(VL_STATION_LIST, VEH_TRAIN,    owner, this->window_number).Pack(), false);
01135     DeleteWindowById(WC_ROADVEH_LIST,  VehicleListIdentifier(VL_STATION_LIST, VEH_ROAD,     owner, this->window_number).Pack(), false);
01136     DeleteWindowById(WC_SHIPS_LIST,    VehicleListIdentifier(VL_STATION_LIST, VEH_SHIP,     owner, this->window_number).Pack(), false);
01137     DeleteWindowById(WC_AIRCRAFT_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_AIRCRAFT, owner, this->window_number).Pack(), false);
01138   }
01139 
01150   void ShowCargo(CargoDataEntry *data, CargoID cargo, StationID source, StationID next, StationID dest, uint count)
01151   {
01152     if (count == 0) return;
01153     const CargoDataEntry *expand = &this->expanded_rows;
01154     for (int i = 0; i < NUM_COLUMNS && expand != NULL; ++i) {
01155       switch (groupings[i]) {
01156         case GR_CARGO:
01157           assert(i == 0);
01158           data = data->InsertOrRetrieve(cargo);
01159           expand = expand->Retrieve(cargo);
01160           break;
01161         case GR_SOURCE:
01162           data = data->InsertOrRetrieve(source);
01163           expand = expand->Retrieve(source);
01164           break;
01165         case GR_NEXT:
01166           data = data->InsertOrRetrieve(next);
01167           expand = expand->Retrieve(next);
01168           break;
01169         case GR_DESTINATION:
01170           data = data->InsertOrRetrieve(dest);
01171           expand = expand->Retrieve(dest);
01172           break;
01173       }
01174     }
01175     data->Update(count);
01176   }
01177 
01178   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01179   {
01180     switch (widget) {
01181       case WID_SV_WAITING:
01182         resize->height = FONT_HEIGHT_NORMAL;
01183         size->height = WD_FRAMERECT_TOP + 4 * resize->height + WD_FRAMERECT_BOTTOM;
01184         this->expand_shrink_width = max(GetStringBoundingBox("-").width, GetStringBoundingBox("+").width) + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
01185         break;
01186 
01187       case WID_SV_ACCEPT_RATING_LIST:
01188         size->height = WD_FRAMERECT_TOP + ((this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) ? this->accepts_lines : this->rating_lines) * FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
01189         break;
01190 
01191       case WID_SV_CLOSE_AIRPORT:
01192         if (!(Station::Get(this->window_number)->facilities & FACIL_AIRPORT)) {
01193           /* Hide 'Close Airport' button if no airport present. */
01194           size->width = 0;
01195           resize->width = 0;
01196           fill->width = 0;
01197         }
01198         break;
01199     }
01200   }
01201 
01202   virtual void OnPaint()
01203   {
01204     const Station *st = Station::Get(this->window_number);
01205     CargoDataEntry cargo;
01206     BuildCargoList(&cargo, st);
01207 
01208     this->vscroll->SetCount(cargo.GetNumChildren()); // update scrollbar
01209 
01210     /* disable some buttons */
01211     this->SetWidgetDisabledState(WID_SV_RENAME,   st->owner != _local_company);
01212     this->SetWidgetDisabledState(WID_SV_TRAINS,   !(st->facilities & FACIL_TRAIN));
01213     this->SetWidgetDisabledState(WID_SV_ROADVEHS, !(st->facilities & FACIL_TRUCK_STOP) && !(st->facilities & FACIL_BUS_STOP));
01214     this->SetWidgetDisabledState(WID_SV_SHIPS,    !(st->facilities & FACIL_DOCK));
01215     this->SetWidgetDisabledState(WID_SV_PLANES,   !(st->facilities & FACIL_AIRPORT));
01216     this->SetWidgetDisabledState(WID_SV_CLOSE_AIRPORT, !(st->facilities & FACIL_AIRPORT) || st->owner != _local_company);
01217     this->SetWidgetLoweredState(WID_SV_CLOSE_AIRPORT, (st->facilities & FACIL_AIRPORT) && (st->airport.flags & AIRPORT_CLOSED_block) != 0);
01218 
01219     SetDParam(0, st->index);
01220     SetDParam(1, st->facilities);
01221     this->DrawWidgets();
01222 
01223     if (!this->IsShaded()) {
01224       /* Draw 'accepted cargo' or 'cargo ratings'. */
01225       const NWidgetBase *wid = this->GetWidget<NWidgetBase>(WID_SV_ACCEPT_RATING_LIST);
01226       const Rect r = {wid->pos_x, wid->pos_y, wid->pos_x + wid->current_x - 1, wid->pos_y + wid->current_y - 1};
01227       if (this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) {
01228         int lines = this->DrawAcceptedCargo(r);
01229         if (lines > this->accepts_lines) { // Resize the widget, and perform re-initialization of the window.
01230           this->accepts_lines = lines;
01231           this->ReInit();
01232           return;
01233         }
01234       } else {
01235         int lines = this->DrawCargoRatings(r);
01236         if (lines > this->rating_lines) { // Resize the widget, and perform re-initialization of the window.
01237           this->rating_lines = lines;
01238           this->ReInit();
01239           return;
01240         }
01241       }
01242 
01243       /* draw arrow pointing up/down for ascending/descending sorting */
01244       this->DrawSortButtonState(WID_SV_SORT_ORDER, sort_orders[1] == SO_ASCENDING ? SBS_UP : SBS_DOWN);
01245 
01246       int pos = this->vscroll->GetPosition();
01247 
01248       int maxrows = this->vscroll->GetCapacity();
01249 
01250       displayed_rows.clear();
01251 
01252       /* Draw waiting cargo. */
01253       NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_SV_WAITING);
01254       Rect waiting_rect = {nwi->pos_x, nwi->pos_y, nwi->pos_x + nwi->current_x - 1, nwi->pos_y + nwi->current_y - 1};
01255       this->DrawEntries(&cargo, waiting_rect, pos, maxrows, 0);
01256       scroll_to_row = INT_MAX;
01257     }
01258   }
01259 
01260   virtual void SetStringParameters(int widget) const
01261   {
01262     if (widget == WID_SV_CAPTION) {
01263       const Station *st = Station::Get(this->window_number);
01264       SetDParam(0, st->index);
01265       SetDParam(1, st->facilities);
01266     }
01267   }
01268 
01274   void RecalcDestinations(CargoID i)
01275   {
01276     const Station *st = Station::Get(this->window_number);
01277     CargoDataEntry *cargo_entry = cached_destinations.InsertOrRetrieve(i);
01278     cargo_entry->Clear();
01279 
01280     const FlowStatMap &flows = st->goods[i].flows;
01281     for (FlowStatMap::const_iterator it = flows.begin(); it != flows.end(); ++it) {
01282       StationID from = it->first;
01283       CargoDataEntry *source_entry = cargo_entry->InsertOrRetrieve(from);
01284       const FlowStat::SharesMap *shares = it->second.GetShares();
01285       uint32 prev_count = 0;
01286       for (FlowStat::SharesMap::const_iterator flow_it = shares->begin(); flow_it != shares->end(); ++flow_it) {
01287         StationID via = flow_it->second;
01288         CargoDataEntry *via_entry = source_entry->InsertOrRetrieve(via);
01289         if (via == this->window_number) {
01290           via_entry->InsertOrRetrieve(via)->Update(flow_it->first - prev_count);
01291         } else {
01292           EstimateDestinations(i, from, via, flow_it->first - prev_count, via_entry);
01293         }
01294         prev_count = flow_it->first;
01295       }
01296     }
01297   }
01298 
01308   void EstimateDestinations(CargoID cargo, StationID source, StationID next, uint count, CargoDataEntry *dest)
01309   {
01310     if (Station::IsValidID(next) && Station::IsValidID(source)) {
01311       CargoDataEntry tmp;
01312       const FlowStatMap &flowmap = Station::Get(next)->goods[cargo].flows;
01313       FlowStatMap::const_iterator map_it = flowmap.find(source);
01314       if (map_it != flowmap.end()) {
01315         const FlowStat::SharesMap *shares = map_it->second.GetShares();
01316         uint32 prev_count = 0;
01317         for (FlowStat::SharesMap::const_iterator i = shares->begin(); i != shares->end(); ++i) {
01318           tmp.InsertOrRetrieve(i->second)->Update(i->first - prev_count);
01319           prev_count = i->first;
01320         }
01321       }
01322 
01323       if (tmp.GetCount() == 0) {
01324         dest->InsertOrRetrieve(INVALID_STATION)->Update(count);
01325       } else {
01326         uint sum_estimated = 0;
01327         while (sum_estimated < count) {
01328           for (CargoDataSet::iterator i = tmp.Begin(); i != tmp.End() && sum_estimated < count; ++i) {
01329             CargoDataEntry *child = *i;
01330             uint estimate = DivideApprox(child->GetCount() * count, tmp.GetCount());
01331             if (estimate == 0) estimate = 1;
01332 
01333             sum_estimated += estimate;
01334             if (sum_estimated > count) {
01335               estimate -= sum_estimated - count;
01336               sum_estimated = count;
01337             }
01338 
01339             if (estimate > 0) {
01340               if (child->GetStation() == next) {
01341                 dest->InsertOrRetrieve(next)->Update(estimate);
01342               } else {
01343                 EstimateDestinations(cargo, source, child->GetStation(), estimate, dest);
01344               }
01345             }
01346           }
01347 
01348         }
01349       }
01350     } else {
01351       dest->InsertOrRetrieve(INVALID_STATION)->Update(count);
01352     }
01353   }
01354 
01361   void BuildFlowList(CargoID i, const FlowStatMap &flows, CargoDataEntry *cargo)
01362   {
01363     const CargoDataEntry *source_dest = this->cached_destinations.Retrieve(i);
01364     for (FlowStatMap::const_iterator it = flows.begin(); it != flows.end(); ++it) {
01365       StationID from = it->first;
01366       const CargoDataEntry *source_entry = source_dest->Retrieve(from);
01367       const FlowStat::SharesMap *shares = it->second.GetShares();
01368       for (FlowStat::SharesMap::const_iterator flow_it = shares->begin(); flow_it != shares->end(); ++flow_it) {
01369         const CargoDataEntry *via_entry = source_entry->Retrieve(flow_it->second);
01370         for (CargoDataSet::iterator dest_it = via_entry->Begin(); dest_it != via_entry->End(); ++dest_it) {
01371           CargoDataEntry *dest_entry = *dest_it;
01372           ShowCargo(cargo, i, from, flow_it->second, dest_entry->GetStation(), dest_entry->GetCount());
01373         }
01374       }
01375     }
01376   }
01377 
01384   void BuildCargoList(CargoID i, const StationCargoList &packets, CargoDataEntry *cargo)
01385   {
01386     const CargoDataEntry *source_dest = this->cached_destinations.Retrieve(i);
01387     for (StationCargoList::ConstIterator it = packets.Packets()->begin(); it != packets.Packets()->end(); it++) {
01388       const CargoPacket *cp = *it;
01389       StationID next = it.GetKey();
01390 
01391       const CargoDataEntry *source_entry = source_dest->Retrieve(cp->SourceStation());
01392       if (source_entry == NULL) {
01393         ShowCargo(cargo, i, cp->SourceStation(), next, INVALID_STATION, cp->Count());
01394         continue;
01395       }
01396 
01397       const CargoDataEntry *via_entry = source_entry->Retrieve(next);
01398       if (via_entry == NULL) {
01399         ShowCargo(cargo, i, cp->SourceStation(), next, INVALID_STATION, cp->Count());
01400         continue;
01401       }
01402 
01403       for (CargoDataSet::iterator dest_it = via_entry->Begin(); dest_it != via_entry->End(); ++dest_it) {
01404         CargoDataEntry *dest_entry = *dest_it;
01405         uint val = DivideApprox(cp->Count() * dest_entry->GetCount(), via_entry->GetCount());
01406         ShowCargo(cargo, i, cp->SourceStation(), next, dest_entry->GetStation(), val);
01407       }
01408     }
01409   }
01410 
01416   void BuildCargoList(CargoDataEntry *cargo, const Station *st)
01417   {
01418     for (CargoID i = 0; i < NUM_CARGO; i++) {
01419 
01420       if (this->cached_destinations.Retrieve(i) == NULL) {
01421         this->RecalcDestinations(i);
01422       }
01423 
01424       if (this->current_mode == MODE_WAITING) {
01425         this->BuildCargoList(i, st->goods[i].cargo, cargo);
01426       } else {
01427         this->BuildFlowList(i, st->goods[i].flows, cargo);
01428       }
01429     }
01430   }
01431 
01436   void SetDisplayedRow(const CargoDataEntry *data)
01437   {
01438     std::list<StationID> stations;
01439     const CargoDataEntry *parent = data->GetParent();
01440     if (parent->GetParent() == NULL) {
01441       this->displayed_rows.push_back(RowDisplay(&this->expanded_rows, data->GetCargo()));
01442       return;
01443     }
01444 
01445     StationID next = data->GetStation();
01446     while (parent->GetParent()->GetParent() != NULL) {
01447       stations.push_back(parent->GetStation());
01448       parent = parent->GetParent();
01449     }
01450 
01451     CargoID cargo = parent->GetCargo();
01452     CargoDataEntry *filter = this->expanded_rows.Retrieve(cargo);
01453     while (!stations.empty()) {
01454       filter = filter->Retrieve(stations.back());
01455       stations.pop_back();
01456     }
01457 
01458     this->displayed_rows.push_back(RowDisplay(filter, next));
01459   }
01460 
01469   StringID GetEntryString(StationID station, StringID here, StringID other_station, StringID any)
01470   {
01471     if (station == this->window_number) {
01472       return here;
01473     } else if (station != INVALID_STATION) {
01474       SetDParam(2, station);
01475       return other_station;
01476     } else {
01477       return any;
01478     }
01479   }
01480 
01488   StringID SearchNonStop(CargoDataEntry *cd, StationID station, int column)
01489   {
01490     CargoDataEntry *parent = cd->GetParent();
01491     for (int i = column - 1; i > 0; --i) {
01492       if (this->groupings[i] == GR_DESTINATION) {
01493         if (parent->GetStation() == station) {
01494           return STR_STATION_VIEW_NONSTOP;
01495         } else {
01496           return STR_STATION_VIEW_VIA;
01497         }
01498       }
01499       parent = parent->GetParent();
01500     }
01501 
01502     if (this->groupings[column + 1] == GR_DESTINATION) {
01503       CargoDataSet::iterator begin = cd->Begin();
01504       CargoDataSet::iterator end = cd->End();
01505       if (begin != end && ++(cd->Begin()) == end && (*(begin))->GetStation() == station) {
01506         return STR_STATION_VIEW_NONSTOP;
01507       } else {
01508         return STR_STATION_VIEW_VIA;
01509       }
01510     }
01511 
01512     return STR_STATION_VIEW_VIA;
01513   }
01514 
01525   int DrawEntries(CargoDataEntry *entry, Rect &r, int pos, int maxrows, int column, CargoID cargo = CT_INVALID)
01526   {
01527     if (this->sortings[column] == ST_AS_GROUPING) {
01528       if (this->groupings[column] != GR_CARGO) {
01529         entry->Resort(ST_STATION_STRING, this->sort_orders[column]);
01530       }
01531     } else {
01532       entry->Resort(ST_COUNT, this->sort_orders[column]);
01533     }
01534     for (CargoDataSet::iterator i = entry->Begin(); i != entry->End(); ++i) {
01535       CargoDataEntry *cd = *i;
01536 
01537       if (this->groupings[column] == GR_CARGO) cargo = cd->GetCargo();
01538 
01539       if (pos > -maxrows && pos <= 0) {
01540         StringID str = STR_EMPTY;
01541         int y = r.top + WD_FRAMERECT_TOP - pos * FONT_HEIGHT_NORMAL;
01542         SetDParam(0, cargo);
01543         SetDParam(1, cd->GetCount());
01544 
01545         if (this->groupings[column] == GR_CARGO) {
01546           str = STR_STATION_VIEW_WAITING_CARGO;
01547           DrawCargoIcons(cd->GetCargo(), cd->GetCount(), r.left + WD_FRAMERECT_LEFT + this->expand_shrink_width, r.right - WD_FRAMERECT_RIGHT - this->expand_shrink_width, y);
01548         } else {
01549           StationID station = cd->GetStation();
01550 
01551           switch (this->groupings[column]) {
01552             case GR_SOURCE:
01553               str = this->GetEntryString(station, STR_STATION_VIEW_FROM_HERE, STR_STATION_VIEW_FROM, STR_STATION_VIEW_FROM_ANY);
01554               break;
01555             case GR_NEXT:
01556               str = this->GetEntryString(station, STR_STATION_VIEW_VIA_HERE, STR_STATION_VIEW_VIA, STR_STATION_VIEW_VIA_ANY);
01557               if (str == STR_STATION_VIEW_VIA) str = SearchNonStop(cd, station, column);
01558               break;
01559             case GR_DESTINATION:
01560               str = this->GetEntryString(station, STR_STATION_VIEW_TO_HERE, STR_STATION_VIEW_TO, STR_STATION_VIEW_TO_ANY);
01561               break;
01562             default:
01563               NOT_REACHED();
01564           }
01565           if (pos == -this->scroll_to_row && Station::IsValidID(station)) {
01566             ScrollMainWindowToTile(Station::Get(station)->xy);
01567           }
01568         }
01569 
01570         bool rtl = _current_text_dir == TD_RTL;
01571         int text_left    = rtl ? r.left + this->expand_shrink_width : r.left + WD_FRAMERECT_LEFT + column * this->expand_shrink_width;
01572         int text_right   = rtl ? r.right - WD_FRAMERECT_LEFT - column * this->expand_shrink_width : r.right - this->expand_shrink_width;
01573         int shrink_left  = rtl ? r.left + WD_FRAMERECT_LEFT : r.right - this->expand_shrink_width + WD_FRAMERECT_LEFT;
01574         int shrink_right = rtl ? r.left + this->expand_shrink_width - WD_FRAMERECT_RIGHT : r.right - WD_FRAMERECT_RIGHT;
01575 
01576         DrawString(text_left, text_right, y, str);
01577 
01578         if (column < NUM_COLUMNS - 1) {
01579           const char *sym = cd->GetNumChildren() > 0 ? "-" : "+";
01580           DrawString(shrink_left, shrink_right, y, sym, TC_YELLOW);
01581         }
01582         SetDisplayedRow(cd);
01583       }
01584       pos = DrawEntries(cd, r, --pos, maxrows, column + 1, cargo);
01585     }
01586     return pos;
01587   }
01588 
01594   int DrawAcceptedCargo(const Rect &r) const
01595   {
01596     const Station *st = Station::Get(this->window_number);
01597 
01598     uint32 cargo_mask = 0;
01599     for (CargoID i = 0; i < NUM_CARGO; i++) {
01600       if (HasBit(st->goods[i].acceptance_pickup, GoodsEntry::GES_ACCEPTANCE)) SetBit(cargo_mask, i);
01601     }
01602     SetDParam(0, cargo_mask);
01603     int bottom = DrawStringMultiLine(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, INT32_MAX, STR_STATION_VIEW_ACCEPTS_CARGO);
01604     return CeilDiv(bottom - r.top - WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL);
01605   }
01606 
01612   int DrawCargoRatings(const Rect &r) const
01613   {
01614     const Station *st = Station::Get(this->window_number);
01615     int y = r.top + WD_FRAMERECT_TOP;
01616 
01617     if (st->town->exclusive_counter > 0) {
01618       SetDParam(0, st->town->exclusivity);
01619       y = DrawStringMultiLine(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, r.bottom, st->town->exclusivity == st->owner ? STR_STATIOV_VIEW_EXCLUSIVE_RIGHTS_SELF : STR_STATIOV_VIEW_EXCLUSIVE_RIGHTS_COMPANY);
01620       y += WD_PAR_VSEP_WIDE;
01621     }
01622 
01623     DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_VIEW_CARGO_RATINGS_TITLE);
01624     y += FONT_HEIGHT_NORMAL;
01625 
01626     const CargoSpec *cs;
01627     FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
01628       const GoodsEntry *ge = &st->goods[cs->Index()];
01629       if (!HasBit(ge->acceptance_pickup, GoodsEntry::GES_PICKUP)) continue;
01630 
01631       SetDParam(0, cs->name);
01632       SetDParam(1, ge->supply);
01633       SetDParam(3, ToPercent8(ge->rating));
01634       SetDParam(2, STR_CARGO_RATING_APPALLING + (ge->rating >> 5));
01635       DrawString(r.left + WD_FRAMERECT_LEFT + 6, r.right - WD_FRAMERECT_RIGHT - 6, y, STR_STATION_VIEW_CARGO_SUPPLY_RATING);
01636       y += FONT_HEIGHT_NORMAL;
01637     }
01638     return CeilDiv(y - r.top - WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL);
01639   }
01640 
01646   template<class ID>
01647   void HandleCargoWaitingClick(CargoDataEntry *filter, ID next)
01648   {
01649     if (filter->Retrieve(next) != NULL) {
01650       filter->Remove(next);
01651     } else {
01652       filter->InsertOrRetrieve(next);
01653     }
01654   }
01655 
01660   void HandleCargoWaitingClick(int row)
01661   {
01662     if (row < 0 || (uint)row >= this->displayed_rows.size()) return;
01663     if (_ctrl_pressed) {
01664       this->scroll_to_row = row;
01665     } else {
01666       RowDisplay &display = this->displayed_rows[row];
01667       if (display.filter == &this->expanded_rows) {
01668         this->HandleCargoWaitingClick<CargoID>(display.filter, display.next_cargo);
01669       } else {
01670         this->HandleCargoWaitingClick<StationID>(display.filter, display.next_station);
01671       }
01672     }
01673     this->SetWidgetDirty(WID_SV_WAITING);
01674   }
01675 
01676   virtual void OnClick(Point pt, int widget, int click_count)
01677   {
01678     switch (widget) {
01679       case WID_SV_WAITING:
01680         this->HandleCargoWaitingClick(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_SV_WAITING, WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL) - this->vscroll->GetPosition());
01681         break;
01682 
01683       case WID_SV_LOCATION:
01684         if (_ctrl_pressed) {
01685           ShowExtraViewPortWindow(Station::Get(this->window_number)->xy);
01686         } else {
01687           ScrollMainWindowToTile(Station::Get(this->window_number)->xy);
01688         }
01689         break;
01690 
01691       case WID_SV_ACCEPTS_RATINGS: {
01692         /* Swap between 'accepts' and 'ratings' view. */
01693         int height_change;
01694         NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS);
01695         if (this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) {
01696           nwi->SetDataTip(STR_STATION_VIEW_ACCEPTS_BUTTON, STR_STATION_VIEW_ACCEPTS_TOOLTIP); // Switch to accepts view.
01697           height_change = this->rating_lines - this->accepts_lines;
01698         } else {
01699           nwi->SetDataTip(STR_STATION_VIEW_RATINGS_BUTTON, STR_STATION_VIEW_RATINGS_TOOLTIP); // Switch to ratings view.
01700           height_change = this->accepts_lines - this->rating_lines;
01701         }
01702         this->ReInit(0, height_change * FONT_HEIGHT_NORMAL);
01703         break;
01704       }
01705 
01706       case WID_SV_RENAME:
01707         SetDParam(0, this->window_number);
01708         ShowQueryString(STR_STATION_NAME, STR_STATION_VIEW_RENAME_STATION_CAPTION, MAX_LENGTH_STATION_NAME_CHARS,
01709             this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
01710         break;
01711 
01712       case WID_SV_CLOSE_AIRPORT:
01713         DoCommandP(0, this->window_number, 0, CMD_OPEN_CLOSE_AIRPORT);
01714         break;
01715 
01716       case WID_SV_TRAINS:   // Show list of scheduled trains to this station
01717       case WID_SV_ROADVEHS: // Show list of scheduled road-vehicles to this station
01718       case WID_SV_SHIPS:    // Show list of scheduled ships to this station
01719       case WID_SV_PLANES: { // Show list of scheduled aircraft to this station
01720         Owner owner = Station::Get(this->window_number)->owner;
01721         ShowVehicleListWindow(owner, (VehicleType)(widget - WID_SV_TRAINS), (StationID)this->window_number);
01722         break;
01723       }
01724 
01725       case WID_SV_SORT_BY: {
01726         ShowDropDownMenu(this, _sort_names, this->current_mode, WID_SV_SORT_BY, 0, 0);
01727         break;
01728       }
01729 
01730       case WID_SV_GROUP_BY: {
01731         ShowDropDownMenu(this, _group_names, this->grouping_index, WID_SV_GROUP_BY, 0, 0);
01732         break;
01733       }
01734 
01735       case WID_SV_SORT_ORDER: { // flip sorting method asc/desc
01736         this->SelectSortOrder(this->sort_orders[1] == SO_ASCENDING ? SO_DESCENDING : SO_ASCENDING);
01737         this->SetTimeout();
01738         this->LowerWidget(WID_SV_SORT_ORDER);
01739         break;
01740       }
01741     }
01742   }
01743 
01748   void SelectSortOrder(SortOrder order)
01749   {
01750     this->sort_orders[1] = this->sort_orders[2] = this->sort_orders[3] = order;
01751     _settings_client.gui.station_gui_sort_order = this->sort_orders[1];
01752     this->SetDirty();
01753   }
01754 
01759   void SelectSortBy(int index)
01760   {
01761     _settings_client.gui.station_gui_sort_by = index;
01762     switch (_sort_names[index]) {
01763       case STR_STATION_VIEW_WAITING_STATION:
01764         this->current_mode = MODE_WAITING;
01765         this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_AS_GROUPING;
01766         break;
01767       case STR_STATION_VIEW_WAITING_AMOUNT:
01768         this->current_mode = MODE_WAITING;
01769         this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_COUNT;
01770         break;
01771       case STR_STATION_VIEW_PLANNED_STATION:
01772         this->current_mode = MODE_PLANNED;
01773         this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_AS_GROUPING;
01774         break;
01775       case STR_STATION_VIEW_PLANNED_AMOUNT:
01776         this->current_mode = MODE_PLANNED;
01777         this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_COUNT;
01778         break;
01779       default:
01780         NOT_REACHED();
01781     }
01782     /* Display the current sort variant */
01783     this->GetWidget<NWidgetCore>(WID_SV_SORT_BY)->widget_data = _sort_names[index];
01784     this->SetDirty();
01785   }
01786 
01791   void SelectGroupBy(int index)
01792   {
01793     this->grouping_index = index;
01794     _settings_client.gui.station_gui_group_order = index;
01795     this->GetWidget<NWidgetCore>(WID_SV_GROUP_BY)->widget_data = _group_names[index];
01796     switch (_group_names[index]) {
01797       case STR_STATION_VIEW_GROUP_S_V_D:
01798         this->groupings[1] = GR_SOURCE;
01799         this->groupings[2] = GR_NEXT;
01800         this->groupings[3] = GR_DESTINATION;
01801         break;
01802       case STR_STATION_VIEW_GROUP_S_D_V:
01803         this->groupings[1] = GR_SOURCE;
01804         this->groupings[2] = GR_DESTINATION;
01805         this->groupings[3] = GR_NEXT;
01806         break;
01807       case STR_STATION_VIEW_GROUP_V_S_D:
01808         this->groupings[1] = GR_NEXT;
01809         this->groupings[2] = GR_SOURCE;
01810         this->groupings[3] = GR_DESTINATION;
01811         break;
01812       case STR_STATION_VIEW_GROUP_V_D_S:
01813         this->groupings[1] = GR_NEXT;
01814         this->groupings[2] = GR_DESTINATION;
01815         this->groupings[3] = GR_SOURCE;
01816         break;
01817       case STR_STATION_VIEW_GROUP_D_S_V:
01818         this->groupings[1] = GR_DESTINATION;
01819         this->groupings[2] = GR_SOURCE;
01820         this->groupings[3] = GR_NEXT;
01821         break;
01822       case STR_STATION_VIEW_GROUP_D_V_S:
01823         this->groupings[1] = GR_DESTINATION;
01824         this->groupings[2] = GR_NEXT;
01825         this->groupings[3] = GR_SOURCE;
01826         break;
01827     }
01828     this->SetDirty();
01829   }
01830 
01831   virtual void OnDropdownSelect(int widget, int index)
01832   {
01833     if (widget == WID_SV_SORT_BY) {
01834       this->SelectSortBy(index);
01835     } else {
01836       this->SelectGroupBy(index);
01837     }
01838   }
01839 
01840   virtual void OnQueryTextFinished(char *str)
01841   {
01842     if (str == NULL) return;
01843 
01844     DoCommandP(0, this->window_number, 0, CMD_RENAME_STATION | CMD_MSG(STR_ERROR_CAN_T_RENAME_STATION), NULL, str);
01845   }
01846 
01847   virtual void OnResize()
01848   {
01849     this->vscroll->SetCapacityFromWidget(this, WID_SV_WAITING, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
01850   }
01851 
01857   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
01858   {
01859     if (gui_scope) {
01860       if (data >= 0 && data < NUM_CARGO) {
01861         this->cached_destinations.Remove((CargoID)data);
01862       } else {
01863         this->ReInit();
01864       }
01865     }
01866   }
01867 };
01868 
01869 const StringID StationViewWindow::_sort_names[] = {
01870   STR_STATION_VIEW_WAITING_STATION,
01871   STR_STATION_VIEW_WAITING_AMOUNT,
01872   STR_STATION_VIEW_PLANNED_STATION,
01873   STR_STATION_VIEW_PLANNED_AMOUNT,
01874   INVALID_STRING_ID
01875 };
01876 
01877 const StringID StationViewWindow::_group_names[] = {
01878   STR_STATION_VIEW_GROUP_S_V_D,
01879   STR_STATION_VIEW_GROUP_S_D_V,
01880   STR_STATION_VIEW_GROUP_V_S_D,
01881   STR_STATION_VIEW_GROUP_V_D_S,
01882   STR_STATION_VIEW_GROUP_D_S_V,
01883   STR_STATION_VIEW_GROUP_D_V_S,
01884   INVALID_STRING_ID
01885 };
01886 
01887 static const WindowDesc _station_view_desc(
01888   WDP_AUTO, 249, 117,
01889   WC_STATION_VIEW, WC_NONE,
01890   WDF_UNCLICK_BUTTONS,
01891   _nested_station_view_widgets, lengthof(_nested_station_view_widgets)
01892 );
01893 
01899 void ShowStationViewWindow(StationID station)
01900 {
01901   AllocateWindowDescFront<StationViewWindow>(&_station_view_desc, station);
01902 }
01903 
01905 struct TileAndStation {
01906   TileIndex tile;    
01907   StationID station; 
01908 };
01909 
01910 static SmallVector<TileAndStation, 8> _deleted_stations_nearby;
01911 static SmallVector<StationID, 8> _stations_nearby_list;
01912 
01920 template <class T>
01921 static bool AddNearbyStation(TileIndex tile, void *user_data)
01922 {
01923   TileArea *ctx = (TileArea *)user_data;
01924 
01925   /* First check if there were deleted stations here */
01926   for (uint i = 0; i < _deleted_stations_nearby.Length(); i++) {
01927     TileAndStation *ts = _deleted_stations_nearby.Get(i);
01928     if (ts->tile == tile) {
01929       *_stations_nearby_list.Append() = _deleted_stations_nearby[i].station;
01930       _deleted_stations_nearby.Erase(ts);
01931       i--;
01932     }
01933   }
01934 
01935   /* Check if own station and if we stay within station spread */
01936   if (!IsTileType(tile, MP_STATION)) return false;
01937 
01938   StationID sid = GetStationIndex(tile);
01939 
01940   /* This station is (likely) a waypoint */
01941   if (!T::IsValidID(sid)) return false;
01942 
01943   T *st = T::Get(sid);
01944   if (st->owner != _local_company || _stations_nearby_list.Contains(sid)) return false;
01945 
01946   if (st->rect.BeforeAddRect(ctx->tile, ctx->w, ctx->h, StationRect::ADD_TEST).Succeeded()) {
01947     *_stations_nearby_list.Append() = sid;
01948   }
01949 
01950   return false; // We want to include *all* nearby stations
01951 }
01952 
01962 template <class T>
01963 static const T *FindStationsNearby(TileArea ta, bool distant_join)
01964 {
01965   TileArea ctx = ta;
01966 
01967   _stations_nearby_list.Clear();
01968   _deleted_stations_nearby.Clear();
01969 
01970   /* Check the inside, to return, if we sit on another station */
01971   TILE_AREA_LOOP(t, ta) {
01972     if (t < MapSize() && IsTileType(t, MP_STATION) && T::IsValidID(GetStationIndex(t))) return T::GetByTile(t);
01973   }
01974 
01975   /* Look for deleted stations */
01976   const BaseStation *st;
01977   FOR_ALL_BASE_STATIONS(st) {
01978     if (T::IsExpected(st) && !st->IsInUse() && st->owner == _local_company) {
01979       /* Include only within station spread (yes, it is strictly less than) */
01980       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) {
01981         TileAndStation *ts = _deleted_stations_nearby.Append();
01982         ts->tile = st->xy;
01983         ts->station = st->index;
01984 
01985         /* Add the station when it's within where we're going to build */
01986         if (IsInsideBS(TileX(st->xy), TileX(ctx.tile), ctx.w) &&
01987             IsInsideBS(TileY(st->xy), TileY(ctx.tile), ctx.h)) {
01988           AddNearbyStation<T>(st->xy, &ctx);
01989         }
01990       }
01991     }
01992   }
01993 
01994   /* Only search tiles where we have a chance to stay within the station spread.
01995    * The complete check needs to be done in the callback as we don't know the
01996    * extent of the found station, yet. */
01997   if (distant_join && min(ta.w, ta.h) >= _settings_game.station.station_spread) return NULL;
01998   uint max_dist = distant_join ? _settings_game.station.station_spread - min(ta.w, ta.h) : 1;
01999 
02000   TileIndex tile = TILE_ADD(ctx.tile, TileOffsByDir(DIR_N));
02001   CircularTileSearch(&tile, max_dist, ta.w, ta.h, AddNearbyStation<T>, &ctx);
02002 
02003   return NULL;
02004 }
02005 
02006 static const NWidgetPart _nested_select_station_widgets[] = {
02007   NWidget(NWID_HORIZONTAL),
02008     NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
02009     NWidget(WWT_CAPTION, COLOUR_DARK_GREEN, WID_JS_CAPTION), SetDataTip(STR_JOIN_STATION_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
02010   EndContainer(),
02011   NWidget(NWID_HORIZONTAL),
02012     NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_JS_PANEL), SetResize(1, 0), SetScrollbar(WID_JS_SCROLLBAR), EndContainer(),
02013     NWidget(NWID_VERTICAL),
02014       NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, WID_JS_SCROLLBAR),
02015       NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
02016     EndContainer(),
02017   EndContainer(),
02018 };
02019 
02024 template <class T>
02025 struct SelectStationWindow : Window {
02026   CommandContainer select_station_cmd; 
02027   TileArea area; 
02028   Scrollbar *vscroll;
02029 
02030   SelectStationWindow(const WindowDesc *desc, CommandContainer cmd, TileArea ta) :
02031     Window(),
02032     select_station_cmd(cmd),
02033     area(ta)
02034   {
02035     this->CreateNestedTree(desc);
02036     this->vscroll = this->GetScrollbar(WID_JS_SCROLLBAR);
02037     this->GetWidget<NWidgetCore>(WID_JS_CAPTION)->widget_data = T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_JOIN_WAYPOINT_CAPTION : STR_JOIN_STATION_CAPTION;
02038     this->FinishInitNested(desc, 0);
02039     this->OnInvalidateData(0);
02040   }
02041 
02042   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
02043   {
02044     if (widget != WID_JS_PANEL) return;
02045 
02046     /* Determine the widest string */
02047     Dimension d = GetStringBoundingBox(T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_JOIN_WAYPOINT_CREATE_SPLITTED_WAYPOINT : STR_JOIN_STATION_CREATE_SPLITTED_STATION);
02048     for (uint i = 0; i < _stations_nearby_list.Length(); i++) {
02049       const T *st = T::Get(_stations_nearby_list[i]);
02050       SetDParam(0, st->index);
02051       SetDParam(1, st->facilities);
02052       d = maxdim(d, GetStringBoundingBox(T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_STATION_LIST_WAYPOINT : STR_STATION_LIST_STATION));
02053     }
02054 
02055     resize->height = d.height;
02056     d.height *= 5;
02057     d.width += WD_FRAMERECT_RIGHT + WD_FRAMERECT_LEFT;
02058     d.height += WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
02059     *size = d;
02060   }
02061 
02062   virtual void DrawWidget(const Rect &r, int widget) const
02063   {
02064     if (widget != WID_JS_PANEL) return;
02065 
02066     uint y = r.top + WD_FRAMERECT_TOP;
02067     if (this->vscroll->GetPosition() == 0) {
02068       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);
02069       y += this->resize.step_height;
02070     }
02071 
02072     for (uint i = max<uint>(1, this->vscroll->GetPosition()); i <= _stations_nearby_list.Length(); ++i, y += this->resize.step_height) {
02073       /* Don't draw anything if it extends past the end of the window. */
02074       if (i - this->vscroll->GetPosition() >= this->vscroll->GetCapacity()) break;
02075 
02076       const T *st = T::Get(_stations_nearby_list[i - 1]);
02077       SetDParam(0, st->index);
02078       SetDParam(1, st->facilities);
02079       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);
02080     }
02081   }
02082 
02083   virtual void OnClick(Point pt, int widget, int click_count)
02084   {
02085     if (widget != WID_JS_PANEL) return;
02086 
02087     uint st_index = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_JS_PANEL, WD_FRAMERECT_TOP);
02088     bool distant_join = (st_index > 0);
02089     if (distant_join) st_index--;
02090 
02091     if (distant_join && st_index >= _stations_nearby_list.Length()) return;
02092 
02093     /* Insert station to be joined into stored command */
02094     SB(this->select_station_cmd.p2, 16, 16,
02095        (distant_join ? _stations_nearby_list[st_index] : NEW_STATION));
02096 
02097     /* Execute stored Command */
02098     DoCommandP(&this->select_station_cmd);
02099 
02100     /* Close Window; this might cause double frees! */
02101     DeleteWindowById(WC_SELECT_STATION, 0);
02102   }
02103 
02104   virtual void OnTick()
02105   {
02106     if (_thd.dirty & 2) {
02107       _thd.dirty &= ~2;
02108       this->SetDirty();
02109     }
02110   }
02111 
02112   virtual void OnResize()
02113   {
02114     this->vscroll->SetCapacityFromWidget(this, WID_JS_PANEL, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
02115   }
02116 
02122   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
02123   {
02124     if (!gui_scope) return;
02125     FindStationsNearby<T>(this->area, true);
02126     this->vscroll->SetCount(_stations_nearby_list.Length() + 1);
02127     this->SetDirty();
02128   }
02129 };
02130 
02131 static const WindowDesc _select_station_desc(
02132   WDP_AUTO, 200, 180,
02133   WC_SELECT_STATION, WC_NONE,
02134   WDF_CONSTRUCTION,
02135   _nested_select_station_widgets, lengthof(_nested_select_station_widgets)
02136 );
02137 
02138 
02146 template <class T>
02147 static bool StationJoinerNeeded(CommandContainer cmd, TileArea ta)
02148 {
02149   /* Only show selection if distant join is enabled in the settings */
02150   if (!_settings_game.station.distant_join_stations) return false;
02151 
02152   /* If a window is already opened and we didn't ctrl-click,
02153    * return true (i.e. just flash the old window) */
02154   Window *selection_window = FindWindowById(WC_SELECT_STATION, 0);
02155   if (selection_window != NULL) {
02156     /* Abort current distant-join and start new one */
02157     delete selection_window;
02158     UpdateTileSelection();
02159   }
02160 
02161   /* only show the popup, if we press ctrl */
02162   if (!_ctrl_pressed) return false;
02163 
02164   /* Now check if we could build there */
02165   if (DoCommand(&cmd, CommandFlagsToDCFlags(GetCommandFlags(cmd.cmd))).Failed()) return false;
02166 
02167   /* Test for adjacent station or station below selection.
02168    * If adjacent-stations is disabled and we are building next to a station, do not show the selection window.
02169    * but join the other station immediately. */
02170   const T *st = FindStationsNearby<T>(ta, false);
02171   return st == NULL && (_settings_game.station.adjacent_stations || _stations_nearby_list.Length() == 0);
02172 }
02173 
02180 template <class T>
02181 void ShowSelectBaseStationIfNeeded(CommandContainer cmd, TileArea ta)
02182 {
02183   if (StationJoinerNeeded<T>(cmd, ta)) {
02184     if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
02185     new SelectStationWindow<T>(&_select_station_desc, cmd, ta);
02186   } else {
02187     DoCommandP(&cmd);
02188   }
02189 }
02190 
02196 void ShowSelectStationIfNeeded(CommandContainer cmd, TileArea ta)
02197 {
02198   ShowSelectBaseStationIfNeeded<Station>(cmd, ta);
02199 }
02200 
02206 void ShowSelectWaypointIfNeeded(CommandContainer cmd, TileArea ta)
02207 {
02208   ShowSelectBaseStationIfNeeded<Waypoint>(cmd, ta);
02209 }