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