# 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 #include "linkgraph/linkgraph.h"
    00034
    00035 #include "widgets/station_widget.h"
    00036
    00037 #include "table/strings.h"
    00038
    00039 #include <set>
    00040 #include <vector>
    00041
    00052 int DrawStationCoverageAreaText(int left, int right, int top, StationCoverageType sct, int rad, bool supplies)
    00053 {
    00054   TileIndex tile = TileVirtXY(_thd.pos.x, _thd.pos.y);
    00055   uint32 cargo_mask = 0;
    00056   if (_thd.drawstyle == HT_RECT && tile < MapSize()) {
    00057     CargoArray cargoes;
    00058     if (supplies) {
    00059       cargoes = GetProductionAroundTiles(tile, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE, rad);
    00060     } else {
    00061       cargoes = GetAcceptanceAroundTiles(tile, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE, rad);
    00062     }
    00063
    00064     /* Convert cargo counts to a set of cargo bits, and draw the result. */
    00065     for (CargoID i = 0; i < NUM_CARGO; i++) {
    00066       switch (sct) {
    00067         case SCT_PASSENGERS_ONLY: if (!IsCargoInClass(i, CC_PASSENGERS)) continue; break;
    00068         case SCT_NON_PASSENGERS_ONLY: if (IsCargoInClass(i, CC_PASSENGERS)) continue; break;
    00069         case SCT_ALL: break;
    00070         default: NOT_REACHED();
    00071       }
    00072       if (cargoes[i] >= (supplies ? 1U : 8U)) SetBit(cargo_mask, i);
    00073     }
    00074   }
    00075   SetDParam(0, cargo_mask);
    00076   return DrawStringMultiLine(left, right, top, INT32_MAX, supplies ? STR_STATION_BUILD_SUPPLIES_CARGO : STR_STATION_BUILD_ACCEPTS_CARGO);
    00077 }
    00078
    00084 void CheckRedrawStationCoverage(const Window *w)
    00085 {
    00086   if (_thd.dirty & 1) {
    00087     _thd.dirty &= ~1;
    00088     w->SetDirty();
    00089   }
    00090 }
    00091
    00107 static void StationsWndShowStationRating(int left, int right, int y, CargoID type, uint amount, byte rating)
    00108 {
    00109   static const uint units_full  = 576;
    00110   static const uint rating_full = 224;
    00111
    00112   const CargoSpec *cs = CargoSpec::Get(type);
    00113   if (!cs->IsValid()) return;
    00114
    00115   int colour = cs->rating_colour;
    00116   TextColour tc = GetContrastColour(colour);
    00117   uint w = (minu(amount, units_full) + 5) / 36;
    00118
    00119   int height = GetCharacterHeight(FS_SMALL);
    00120
    00121   /* Draw total cargo (limited) on station (fits into 16 pixels) */
    00122   if (w != 0) GfxFillRect(left, y, left + w - 1, y + height, colour);
    00123
    00124   /* Draw a one pixel-wide bar of additional cargo meter, useful
    00125    * for stations with only a small amount (<=30) */
    00126   if (w == 0) {
    00127     uint rest = amount / 5;
    00128     if (rest != 0) {
    00129       w += left;
    00130       GfxFillRect(w, y + height - rest, w, y + height, colour);
    00131     }
    00132   }
    00133
    00134   DrawString(left + 1, right, y, cs->abbrev, tc);
    00135
    00136   /* Draw green/red ratings bar (fits into 14 pixels) */
    00137   y += height + 2;
    00138   GfxFillRect(left + 1, y, left + 14, y, PC_RED);
    00139   rating = minu(rating, rating_full) / 16;
    00140   if (rating != 0) GfxFillRect(left + 1, y, left + rating, y, PC_GREEN);
    00141 }
    00142
    00143 typedef GUIList<const Station*> GUIStationList;
    00144
    00148 class CompanyStationsWindow : public Window
    00149 {
    00150 protected:
    00151   /* Runtime saved values */
    00152   static Listing last_sorting;
    00153   static byte facilities;               // types of stations of interest
    00154   static bool include_empty;            // whether we should include stations without waiting cargo
    00155   static const uint32 cargo_filter_max;
    00156   static uint32 cargo_filter;           // bitmap of cargo types to include
    00157   static const Station *last_station;
    00158
    00159   /* Constants for sorting stations */
    00160   static const StringID sorter_names[];
    00161   static GUIStationList::SortFunction * const sorter_funcs[];
    00162
    00163   GUIStationList stations;
    00164   Scrollbar *vscroll;
    00165
    00171   void BuildStationsList(const Owner owner)
    00172   {
    00173     if (!this->stations.NeedRebuild()) return;
    00174
    00175     DEBUG(misc, 3, "Building station list for company %d", owner);
    00176
    00177     this->stations.Clear();
    00178
    00179     const Station *st;
    00180     FOR_ALL_STATIONS(st) {
    00181       if (st->owner == owner || (st->owner == OWNER_NONE && HasStationInUse(st->index, true, owner))) {
    00182         if (this->facilities & st->facilities) { // only stations with selected facilities
    00183           int num_waiting_cargo = 0;
    00184           for (CargoID j = 0; j < NUM_CARGO; j++) {
    00185             if (HasBit(st->goods[j].acceptance_pickup, GoodsEntry::GES_PICKUP)) {
    00186               num_waiting_cargo++; // count number of waiting cargo
    00187               if (HasBit(this->cargo_filter, j)) {
    00188                 *this->stations.Append() = st;
    00189                 break;
    00190               }
    00191             }
    00192           }
    00193           /* stations without waiting cargo */
    00194           if (num_waiting_cargo == 0 && this->include_empty) {
    00195             *this->stations.Append() = st;
    00196           }
    00197         }
    00198       }
    00199     }
    00200
    00201     this->stations.Compact();
    00202     this->stations.RebuildDone();
    00203
    00204     this->vscroll->SetCount(this->stations.Length()); // Update the scrollbar
    00205   }
    00206
    00208   static int CDECL StationNameSorter(const Station * const *a, const Station * const *b)
    00209   {
    00210     static char buf_cache[64];
    00211     char buf[64];
    00212
    00213     SetDParam(0, (*a)->index);
    00214     GetString(buf, STR_STATION_NAME, lastof(buf));
    00215
    00216     if (*b != last_station) {
    00217       last_station = *b;
    00218       SetDParam(0, (*b)->index);
    00219       GetString(buf_cache, STR_STATION_NAME, lastof(buf_cache));
    00220     }
    00221
    00222     return strcmp(buf, buf_cache);
    00223   }
    00224
    00226   static int CDECL StationTypeSorter(const Station * const *a, const Station * const *b)
    00227   {
    00228     return (*a)->facilities - (*b)->facilities;
    00229   }
    00230
    00232   static int CDECL StationWaitingSorter(const Station * const *a, const Station * const *b)
    00233   {
    00234     Money diff = 0;
    00235
    00236     CargoID j;
    00237     FOR_EACH_SET_CARGO_ID(j, cargo_filter) {
    00238       if (!(*a)->goods[j].cargo.Empty()) diff += GetTransportedGoodsIncome((*a)->goods[j].cargo.Count(), 20, 50, j);
    00239       if (!(*b)->goods[j].cargo.Empty()) diff -= GetTransportedGoodsIncome((*b)->goods[j].cargo.Count(), 20, 50, j);
    00240     }
    00241
    00242     return ClampToI32(diff);
    00243   }
    00244
    00246   static int CDECL StationRatingMaxSorter(const Station * const *a, const Station * const *b)
    00247   {
    00248     byte maxr1 = 0;
    00249     byte maxr2 = 0;
    00250
    00251     CargoID j;
    00252     FOR_EACH_SET_CARGO_ID(j, cargo_filter) {
    00253       if (HasBit((*a)->goods[j].acceptance_pickup, GoodsEntry::GES_PICKUP)) maxr1 = max(maxr1, (*a)->goods[j].rating);
    00254       if (HasBit((*b)->goods[j].acceptance_pickup, GoodsEntry::GES_PICKUP)) maxr2 = max(maxr2, (*b)->goods[j].rating);
    00255     }
    00256
    00257     return maxr1 - maxr2;
    00258   }
    00259
    00261   static int CDECL StationRatingMinSorter(const Station * const *a, const Station * const *b)
    00262   {
    00263     byte minr1 = 255;
    00264     byte minr2 = 255;
    00265
    00266     for (CargoID j = 0; j < NUM_CARGO; j++) {
    00267       if (!HasBit(cargo_filter, j)) continue;
    00268       if (HasBit((*a)->goods[j].acceptance_pickup, GoodsEntry::GES_PICKUP)) minr1 = min(minr1, (*a)->goods[j].rating);
    00269       if (HasBit((*b)->goods[j].acceptance_pickup, GoodsEntry::GES_PICKUP)) minr2 = min(minr2, (*b)->goods[j].rating);
    00270     }
    00271
    00272     return -(minr1 - minr2);
    00273   }
    00274
    00276   void SortStationsList()
    00277   {
    00278     if (!this->stations.Sort()) return;
    00279
    00280     /* Reset name sorter sort cache */
    00281     this->last_station = NULL;
    00282
    00283     /* Set the modified widget dirty */
    00284     this->SetWidgetDirty(WID_STL_LIST);
    00285   }
    00286
    00287 public:
    00288   CompanyStationsWindow(const WindowDesc *desc, WindowNumber window_number) : Window()
    00289   {
    00290     this->stations.SetListing(this->last_sorting);
    00291     this->stations.SetSortFuncs(this->sorter_funcs);
    00292     this->stations.ForceRebuild();
    00293     this->stations.NeedResort();
    00294     this->SortStationsList();
    00295
    00296     this->CreateNestedTree(desc);
    00297     this->vscroll = this->GetScrollbar(WID_STL_SCROLLBAR);
    00298     this->FinishInitNested(desc, window_number);
    00299     this->owner = (Owner)this->window_number;
    00300
    00301     const CargoSpec *cs;
    00302     FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
    00303       if (!HasBit(this->cargo_filter, cs->Index())) continue;
    00304       this->LowerWidget(WID_STL_CARGOSTART + index);
    00305     }
    00306
    00307     if (this->cargo_filter == this->cargo_filter_max) this->cargo_filter = _cargo_mask;
    00308
    00309     for (uint i = 0; i < 5; i++) {
    00310       if (HasBit(this->facilities, i)) this->LowerWidget(i + WID_STL_TRAIN);
    00311     }
    00312     this->SetWidgetLoweredState(WID_STL_NOCARGOWAITING, this->include_empty);
    00313
    00314     this->GetWidget<NWidgetCore>(WID_STL_SORTDROPBTN)->widget_data = this->sorter_names[this->stations.SortType()];
    00315   }
    00316
    00317   ~CompanyStationsWindow()
    00318   {
    00319     this->last_sorting = this->stations.GetListing();
    00320   }
    00321
    00322   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    00323   {
    00324     switch (widget) {
    00325       case WID_STL_SORTBY: {
    00326         Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
    00327         d.width += padding.width + WD_SORTBUTTON_ARROW_WIDTH * 2; // Doubled since the string is centred and it also looks better.
    00328         d.height += padding.height;
    00329         *size = maxdim(*size, d);
    00330         break;
    00331       }
    00332
    00333       case WID_STL_SORTDROPBTN: {
    00334         Dimension d = {0, 0};
    00335         for (int i = 0; this->sorter_names[i] != INVALID_STRING_ID; i++) {
    00336           d = maxdim(d, GetStringBoundingBox(this->sorter_names[i]));
    00337         }
    00338         d.width += padding.width;
    00339         d.height += padding.height;
    00340         *size = maxdim(*size, d);
    00341         break;
    00342       }
    00343
    00344       case WID_STL_LIST:
    00345         resize->height = FONT_HEIGHT_NORMAL;
    00346         size->height = WD_FRAMERECT_TOP + 5 * resize->height + WD_FRAMERECT_BOTTOM;
    00347         break;
    00348
    00349       case WID_STL_TRAIN:
    00350       case WID_STL_TRUCK:
    00351       case WID_STL_BUS:
    00352       case WID_STL_AIRPLANE:
    00353       case WID_STL_SHIP:
    00354         size->height = max<uint>(FONT_HEIGHT_SMALL, 10) + padding.height;
    00355         break;
    00356
    00357       case WID_STL_CARGOALL:
    00358       case WID_STL_FACILALL:
    00359       case WID_STL_NOCARGOWAITING: {
    00360         Dimension d = GetStringBoundingBox(widget == WID_STL_NOCARGOWAITING ? STR_ABBREV_NONE : STR_ABBREV_ALL);
    00361         d.width  += padding.width + 2;
    00362         d.height += padding.height;
    00363         *size = maxdim(*size, d);
    00364         break;
    00365       }
    00366
    00367       default:
    00368         if (widget >= WID_STL_CARGOSTART) {
    00369           Dimension d = GetStringBoundingBox(_sorted_cargo_specs[widget - WID_STL_CARGOSTART]->abbrev);
    00370           d.width  += padding.width + 2;
    00371           d.height += padding.height;
    00372           *size = maxdim(*size, d);
    00373         }
    00374         break;
    00375     }
    00376   }
    00377
    00378   virtual void OnPaint()
    00379   {
    00380     this->BuildStationsList((Owner)this->window_number);
    00381     this->SortStationsList();
    00382
    00383     this->DrawWidgets();
    00384   }
    00385
    00386   virtual void DrawWidget(const Rect &r, int widget) const
    00387   {
    00388     switch (widget) {
    00389       case WID_STL_SORTBY:
    00390         /* draw arrow pointing up/down for ascending/descending sorting */
    00391         this->DrawSortButtonState(WID_STL_SORTBY, this->stations.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
    00392         break;
    00393
    00394       case WID_STL_LIST: {
    00395         bool rtl = _current_text_dir == TD_RTL;
    00396         int max = min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->stations.Length());
    00397         int y = r.top + WD_FRAMERECT_TOP;
    00398         for (int i = this->vscroll->GetPosition(); i < max; ++i) { // do until max number of stations of owner
    00399           const Station *st = this->stations[i];
    00400           assert(st->xy != INVALID_TILE);
    00401
    00402           /* Do not do the complex check HasStationInUse here, it may be even false
    00403            * when the order had been removed and the station list hasn't been removed yet */
    00404           assert(st->owner == owner || st->owner == OWNER_NONE);
    00405
    00406           SetDParam(0, st->index);
    00407           SetDParam(1, st->facilities);
    00408           int x = DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_LIST_STATION);
    00409           x += rtl ? -5 : 5;
    00410
    00411           /* show cargo waiting and station ratings */
    00412           for (uint j = 0; j < _sorted_standard_cargo_specs_size; j++) {
    00413             CargoID cid = _sorted_cargo_specs[j]->Index();
    00414             if (!st->goods[cid].cargo.Empty()) {
    00415               /* For RTL we work in exactly the opposite direction. So
    00416                * decrement the space needed first, then draw to the left
    00417                * instead of drawing to the left and then incrementing
    00418                * the space. */
    00419               if (rtl) {
    00420                 x -= 20;
    00421                 if (x < r.left + WD_FRAMERECT_LEFT) break;
    00422               }
    00423               StationsWndShowStationRating(x, x + 16, y, cid, st->goods[cid].cargo.Count(), st->goods[cid].rating);
    00424               if (!rtl) {
    00425                 x += 20;
    00426                 if (x > r.right - WD_FRAMERECT_RIGHT) break;
    00427               }
    00428             }
    00429           }
    00430           y += FONT_HEIGHT_NORMAL;
    00431         }
    00432
    00433         if (this->vscroll->GetCount() == 0) { // company has no stations
    00434           DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_LIST_NONE);
    00435           return;
    00436         }
    00437         break;
    00438       }
    00439
    00440       case WID_STL_NOCARGOWAITING: {
    00441         int cg_ofst = this->IsWidgetLowered(widget) ? 2 : 1;
    00442         DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, STR_ABBREV_NONE, TC_BLACK, SA_HOR_CENTER);
    00443         break;
    00444       }
    00445
    00446       case WID_STL_CARGOALL: {
    00447         int cg_ofst = this->IsWidgetLowered(widget) ? 2 : 1;
    00448         DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, STR_ABBREV_ALL, TC_BLACK, SA_HOR_CENTER);
    00449         break;
    00450       }
    00451
    00452       case WID_STL_FACILALL: {
    00453         int cg_ofst = this->IsWidgetLowered(widget) ? 2 : 1;
    00454         DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, STR_ABBREV_ALL, TC_BLACK);
    00455         break;
    00456       }
    00457
    00458       default:
    00459         if (widget >= WID_STL_CARGOSTART) {
    00460           const CargoSpec *cs = _sorted_cargo_specs[widget - WID_STL_CARGOSTART];
    00461           int cg_ofst = HasBit(this->cargo_filter, cs->Index()) ? 2 : 1;
    00462           GfxFillRect(r.left + cg_ofst, r.top + cg_ofst, r.right - 2 + cg_ofst, r.bottom - 2 + cg_ofst, cs->rating_colour);
    00463           TextColour tc = GetContrastColour(cs->rating_colour);
    00464           DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, cs->abbrev, tc, SA_HOR_CENTER);
    00465         }
    00466         break;
    00467     }
    00468   }
    00469
    00470   virtual void SetStringParameters(int widget) const
    00471   {
    00472     if (widget == WID_STL_CAPTION) {
    00473       SetDParam(0, this->window_number);
    00474       SetDParam(1, this->vscroll->GetCount());
    00475     }
    00476   }
    00477
    00478   virtual void OnClick(Point pt, int widget, int click_count)
    00479   {
    00480     switch (widget) {
    00481       case WID_STL_LIST: {
    00482         uint id_v = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_STL_LIST, 0, FONT_HEIGHT_NORMAL);
    00483         if (id_v >= this->stations.Length()) return; // click out of list bound
    00484
    00485         const Station *st = this->stations[id_v];
    00486         /* do not check HasStationInUse - it is slow and may be invalid */
    00487         assert(st->owner == (Owner)this->window_number || st->owner == OWNER_NONE);
    00488
    00489         if (_ctrl_pressed) {
    00490           ShowExtraViewPortWindow(st->xy);
    00491         } else {
    00492           ScrollMainWindowToTile(st->xy);
    00493         }
    00494         break;
    00495       }
    00496
    00497       case WID_STL_TRAIN:
    00498       case WID_STL_TRUCK:
    00499       case WID_STL_BUS:
    00500       case WID_STL_AIRPLANE:
    00501       case WID_STL_SHIP:
    00502         if (_ctrl_pressed) {
    00503           ToggleBit(this->facilities, widget - WID_STL_TRAIN);
    00504           this->ToggleWidgetLoweredState(widget);
    00505         } else {
    00506           uint i;
    00507           FOR_EACH_SET_BIT(i, this->facilities) {
    00508             this->RaiseWidget(i + WID_STL_TRAIN);
    00509           }
    00510           this->facilities = 1 << (widget - WID_STL_TRAIN);
    00511           this->LowerWidget(widget);
    00512         }
    00513         this->stations.ForceRebuild();
    00514         this->SetDirty();
    00515         break;
    00516
    00517       case WID_STL_FACILALL:
    00518         for (uint i = WID_STL_TRAIN; i <= WID_STL_SHIP; i++) {
    00519           this->LowerWidget(i);
    00520         }
    00521
    00522         this->facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK;
    00523         this->stations.ForceRebuild();
    00524         this->SetDirty();
    00525         break;
    00526
    00527       case WID_STL_CARGOALL: {
    00528         for (uint i = 0; i < _sorted_standard_cargo_specs_size; i++) {
    00529           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->SetDirty();
    00543         break;
    00544
    00545       case WID_STL_SORTDROPBTN: // select sorting criteria dropdown menu
    00546         ShowDropDownMenu(this, this->sorter_names, this->stations.SortType(), WID_STL_SORTDROPBTN, 0, 0);
    00547         break;
    00548
    00549       case WID_STL_NOCARGOWAITING:
    00550         if (_ctrl_pressed) {
    00551           this->include_empty = !this->include_empty;
    00552           this->ToggleWidgetLoweredState(WID_STL_NOCARGOWAITING);
    00553         } else {
    00554           for (uint i = 0; i < _sorted_standard_cargo_specs_size; i++) {
    00555             this->RaiseWidget(WID_STL_CARGOSTART + i);
    00556           }
    00557
    00558           this->cargo_filter = 0;
    00559           this->include_empty = true;
    00560
    00561           this->LowerWidget(WID_STL_NOCARGOWAITING);
    00562         }
    00563         this->stations.ForceRebuild();
    00564         this->SetDirty();
    00565         break;
    00566
    00567       default:
    00568         if (widget >= WID_STL_CARGOSTART) { // change cargo_filter
    00569           /* Determine the selected cargo type */
    00570           const CargoSpec *cs = _sorted_cargo_specs[widget - WID_STL_CARGOSTART];
    00571
    00572           if (_ctrl_pressed) {
    00573             ToggleBit(this->cargo_filter, cs->Index());
    00574             this->ToggleWidgetLoweredState(widget);
    00575           } else {
    00576             for (uint i = 0; i < _sorted_standard_cargo_specs_size; i++) {
    00577               this->RaiseWidget(WID_STL_CARGOSTART + i);
    00578             }
    00579             this->RaiseWidget(WID_STL_NOCARGOWAITING);
    00580
    00581             this->cargo_filter = 0;
    00582             this->include_empty = false;
    00583
    00584             SetBit(this->cargo_filter, cs->Index());
    00585             this->LowerWidget(widget);
    00586           }
    00587           this->stations.ForceRebuild();
    00588           this->SetDirty();
    00589         }
    00590         break;
    00591     }
    00592   }
    00593
    00594   virtual void OnDropdownSelect(int widget, int index)
    00595   {
    00596     if (this->stations.SortType() != index) {
    00597       this->stations.SetSortType(index);
    00598
    00599       /* Display the current sort variant */
    00600       this->GetWidget<NWidgetCore>(WID_STL_SORTDROPBTN)->widget_data = this->sorter_names[this->stations.SortType()];
    00601
    00602       this->SetDirty();
    00603     }
    00604   }
    00605
    00606   virtual void OnTick()
    00607   {
    00608     if (_pause_mode != PM_UNPAUSED) return;
    00609     if (this->stations.NeedResort()) {
    00610       DEBUG(misc, 3, "Periodic rebuild station list company %d", this->window_number);
    00611       this->SetDirty();
    00612     }
    00613   }
    00614
    00615   virtual void OnResize()
    00616   {
    00617     this->vscroll->SetCapacityFromWidget(this, WID_STL_LIST, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
    00618   }
    00619
    00625   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
    00626   {
    00627     if (data == 0) {
    00628       /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
    00629       this->stations.ForceRebuild();
    00630     } else {
    00631       this->stations.ForceResort();
    00632     }
    00633   }
    00634 };
    00635
    00636 Listing CompanyStationsWindow::last_sorting = {false, 0};
    00637 byte CompanyStationsWindow::facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK;
    00638 bool CompanyStationsWindow::include_empty = true;
    00639 const uint32 CompanyStationsWindow::cargo_filter_max = UINT32_MAX;
    00640 uint32 CompanyStationsWindow::cargo_filter = UINT32_MAX;
    00641 const Station *CompanyStationsWindow::last_station = NULL;
    00642
    00643 /* Availible station sorting functions */
    00644 GUIStationList::SortFunction * const CompanyStationsWindow::sorter_funcs[] = {
    00645   &StationNameSorter,
    00646   &StationTypeSorter,
    00647   &StationWaitingSorter,
    00648   &StationRatingMaxSorter,
    00649   &StationRatingMinSorter
    00650 };
    00651
    00652 /* Names of the sorting functions */
    00653 const StringID CompanyStationsWindow::sorter_names[] = {
    00654   STR_SORT_BY_NAME,
    00655   STR_SORT_BY_FACILITY,
    00656   STR_SORT_BY_WAITING,
    00657   STR_SORT_BY_RATING_MAX,
    00658   STR_SORT_BY_RATING_MIN,
    00659   INVALID_STRING_ID
    00660 };
    00661
    00667 static NWidgetBase *CargoWidgets(int *biggest_index)
    00668 {
    00669   NWidgetHorizontal *container = new NWidgetHorizontal();
    00670
    00671   for (uint i = 0; i < _sorted_standard_cargo_specs_size; i++) {
    00672     NWidgetBackground *panel = new NWidgetBackground(WWT_PANEL, COLOUR_GREY, WID_STL_CARGOSTART + i);
    00673     panel->SetMinimalSize(14, 11);
    00674     panel->SetResize(0, 0);
    00675     panel->SetFill(0, 1);
    00676     panel->SetDataTip(0, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE);
    00677     container->Add(panel);
    00678   }
    00679   *biggest_index = WID_STL_CARGOSTART + _sorted_standard_cargo_specs_size;
    00680   return container;
    00681 }
    00682
    00683 static const NWidgetPart _nested_company_stations_widgets[] = {
    00684   NWidget(NWID_HORIZONTAL),
    00685     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
    00686     NWidget(WWT_CAPTION, COLOUR_GREY, WID_STL_CAPTION), SetDataTip(STR_STATION_LIST_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
    00687     NWidget(WWT_SHADEBOX, COLOUR_GREY),
    00688     NWidget(WWT_STICKYBOX, COLOUR_GREY),
    00689   EndContainer(),
    00690   NWidget(NWID_HORIZONTAL),
    00691     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),
    00692     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),
    00693     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),
    00694     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),
    00695     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),
    00696     NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_STL_FACILALL), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_SELECT_ALL_FACILITIES), SetFill(0, 1),
    00697     NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(5, 11), SetFill(0, 1), EndContainer(),
    00698     NWidgetFunction(CargoWidgets),
    00699     NWidget(WWT_PANEL, COLOUR_GREY, WID_STL_NOCARGOWAITING), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_NO_WAITING_CARGO), SetFill(0, 1), EndContainer(),
    00700     NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_STL_CARGOALL), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_SELECT_ALL_TYPES), SetFill(0, 1),
    00701     NWidget(WWT_PANEL, COLOUR_GREY), SetDataTip(0x0, STR_NULL), SetResize(1, 0), SetFill(1, 1), EndContainer(),
    00702   EndContainer(),
    00703   NWidget(NWID_HORIZONTAL),
    00704     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_STL_SORTBY), SetMinimalSize(81, 12), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
    00705     NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_STL_SORTDROPBTN), SetMinimalSize(163, 12), SetDataTip(STR_SORT_BY_NAME, STR_TOOLTIP_SORT_CRITERIA), // widget_data gets overwritten.
    00706     NWidget(WWT_PANEL, COLOUR_GREY), SetDataTip(0x0, STR_NULL), SetResize(1, 0), SetFill(1, 1), EndContainer(),
    00707   EndContainer(),
    00708   NWidget(NWID_HORIZONTAL),
    00709     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(),
    00710     NWidget(NWID_VERTICAL),
    00711       NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_STL_SCROLLBAR),
    00712       NWidget(WWT_RESIZEBOX, COLOUR_GREY),
    00713     EndContainer(),
    00714   EndContainer(),
    00715 };
    00716
    00717 static const WindowDesc _company_stations_desc(
    00718   WDP_AUTO, 358, 162,
    00719   WC_STATION_LIST, WC_NONE,
    00720   0,
    00721   _nested_company_stations_widgets, lengthof(_nested_company_stations_widgets)
    00722 );
    00723
    00729 void ShowCompanyStations(CompanyID company)
    00730 {
    00731   if (!Company::IsValidID(company)) return;
    00732
    00733   AllocateWindowDescFront<CompanyStationsWindow>(&_company_stations_desc, company);
    00734 }
    00735
    00736 static const NWidgetPart _nested_station_view_widgets[] = {
    00737   NWidget(NWID_HORIZONTAL),
    00738     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
    00739     NWidget(WWT_CAPTION, COLOUR_GREY, WID_SV_CAPTION), SetDataTip(STR_STATION_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
    00740     NWidget(WWT_SHADEBOX, COLOUR_GREY),
    00741     NWidget(WWT_STICKYBOX, COLOUR_GREY),
    00742   EndContainer(),
    00743   NWidget(NWID_HORIZONTAL),
    00744     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_SORT_ORDER), SetMinimalSize(81, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
    00745     NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_SV_SORT_BY), SetMinimalSize(168, 12), SetResize(1, 0), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
    00746   EndContainer(),
    00747   NWidget(NWID_HORIZONTAL),
    00748     NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_SV_GROUP), SetMinimalSize(81, 12), SetFill(1, 1), SetDataTip(STR_STATION_VIEW_GROUP, 0x0),
    00749     NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_SV_GROUP_BY), SetMinimalSize(168, 12), SetResize(1, 0), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_GROUP_ORDER),
    00750   EndContainer(),
    00751   NWidget(NWID_HORIZONTAL),
    00752     NWidget(WWT_PANEL, COLOUR_GREY, WID_SV_WAITING), SetMinimalSize(237, 44), SetResize(1, 10), SetScrollbar(WID_SV_SCROLLBAR), EndContainer(),
    00753     NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_SV_SCROLLBAR),
    00754   EndContainer(),
    00755   NWidget(WWT_PANEL, COLOUR_GREY, WID_SV_ACCEPT_RATING_LIST), SetMinimalSize(249, 23), SetResize(1, 0), EndContainer(),
    00756   NWidget(NWID_HORIZONTAL),
    00757     NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
    00758       NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_LOCATION), SetMinimalSize(45, 12), SetResize(1, 0), SetFill(1, 1),
    00759           SetDataTip(STR_BUTTON_LOCATION, STR_STATION_VIEW_CENTER_TOOLTIP),
    00760       NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_ACCEPTS_RATINGS), SetMinimalSize(46, 12), SetResize(1, 0), SetFill(1, 1),
    00761           SetDataTip(STR_STATION_VIEW_RATINGS_BUTTON, STR_STATION_VIEW_RATINGS_TOOLTIP),
    00762       NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_RENAME), SetMinimalSize(45, 12), SetResize(1, 0), SetFill(1, 1),
    00763           SetDataTip(STR_BUTTON_RENAME, STR_STATION_VIEW_RENAME_TOOLTIP),
    00764     EndContainer(),
    00765     NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_SV_CLOSE_AIRPORT), SetMinimalSize(45, 12), SetResize(1, 0), SetFill(1, 1),
    00766         SetDataTip(STR_STATION_VIEW_CLOSE_AIRPORT, STR_STATION_VIEW_CLOSE_AIRPORT_TOOLTIP),
    00767     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_TRAINS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_TRAIN, STR_STATION_VIEW_SCHEDULED_TRAINS_TOOLTIP),
    00768     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_ROADVEHS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_LORRY, STR_STATION_VIEW_SCHEDULED_ROAD_VEHICLES_TOOLTIP),
    00769     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_SHIPS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_SHIP, STR_STATION_VIEW_SCHEDULED_SHIPS_TOOLTIP),
    00770     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_PLANES),  SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_PLANE, STR_STATION_VIEW_SCHEDULED_AIRCRAFT_TOOLTIP),
    00771     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
    00772   EndContainer(),
    00773 };
    00774
    00785 static void DrawCargoIcons(CargoID i, uint waiting, int left, int right, int y)
    00786 {
    00787   uint num = min((waiting + 5) / 10, (right - left) / 10); // maximum is width / 10 icons so it won't overflow
    00788   if (num == 0) return;
    00789
    00790   SpriteID sprite = CargoSpec::Get(i)->GetCargoIcon();
    00791
    00792   int x = _current_text_dir == TD_RTL ? left : right - num * 10;
    00793   do {
    00794     DrawSprite(sprite, PAL_NONE, x, y);
    00795     x += 10;
    00796   } while (--num);
    00797 }
    00798
    00799 enum SortOrder {
    00800   SO_DESCENDING,
    00801   SO_ASCENDING
    00802 };
    00803
    00804 class CargoDataEntry;
    00805
    00806 enum CargoSortType {
    00807   ST_AS_GROUPING,
    00808   ST_COUNT,
    00809   ST_STATION_STRING,
    00810   ST_STATION_ID,
    00811   ST_CARGO_ID,
    00812 };
    00813
    00814 class CargoSorter {
    00815 public:
    00816   CargoSorter(CargoSortType t = ST_STATION_ID, SortOrder o = SO_ASCENDING) : type(t), order(o) {}
    00817   CargoSortType GetSortType() {return this->type;}
    00818   bool operator()(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const;
    00819
    00820 private:
    00821   CargoSortType type;
    00822   SortOrder order;
    00823
    00824   template<class Tid>
    00825   bool SortId(Tid st1, Tid st2) const;
    00826   bool SortCount(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const;
    00827   bool SortStation (StationID st1, StationID st2) const;
    00828 };
    00829
    00830 typedef std::set<CargoDataEntry *, CargoSorter> CargoDataSet;
    00831
    00837 class CargoDataEntry {
    00838 public:
    00839   CargoDataEntry();
    00840   ~CargoDataEntry();
    00841
    00847   CargoDataEntry *InsertOrRetrieve(StationID station)
    00848   {
    00849     return this->InsertOrRetrieve<StationID>(station);
    00850   }
    00851
    00857   CargoDataEntry *InsertOrRetrieve(CargoID cargo)
    00858   {
    00859     return this->InsertOrRetrieve<CargoID>(cargo);
    00860   }
    00861
    00862   void Update(uint count);
    00863
    00868   void Remove(StationID station)
    00869   {
    00870     CargoDataEntry t(station);
    00871     this->Remove(&t);
    00872   }
    00873
    00878   void Remove(CargoID cargo)
    00879   {
    00880     CargoDataEntry t(cargo);
    00881     this->Remove(&t);
    00882   }
    00883
    00889   CargoDataEntry *Retrieve(StationID station) const
    00890   {
    00891     CargoDataEntry t(station);
    00892     return this->Retrieve(this->children->find(&t));
    00893   }
    00894
    00900   CargoDataEntry *Retrieve(CargoID cargo) const
    00901   {
    00902     CargoDataEntry t(cargo);
    00903     return this->Retrieve(this->children->find(&t));
    00904   }
    00905
    00906   void Resort(CargoSortType type, SortOrder order);
    00907
    00911   StationID GetStation() const { return this->station; }
    00912
    00916   CargoID GetCargo() const { return this->cargo; }
    00917
    00921   uint GetCount() const { return this->count; }
    00922
    00926   CargoDataEntry *GetParent() const { return this->parent; }
    00927
    00931   uint GetNumChildren() const { return this->num_children; }
    00932
    00936   CargoDataSet::iterator Begin() const { return this->children->begin(); }
    00937
    00941   CargoDataSet::iterator End() const { return this->children->end(); }
    00942
    00943   void Clear();
    00944 private:
    00945
    00946   CargoDataEntry(StationID st, uint c, CargoDataEntry *p);
    00947   CargoDataEntry(CargoID car, uint c, CargoDataEntry *p);
    00948   CargoDataEntry(StationID st);
    00949   CargoDataEntry(CargoID car);
    00950
    00951   CargoDataEntry *Retrieve(CargoDataSet::iterator i) const;
    00952
    00953   template<class Tid>
    00954   CargoDataEntry *InsertOrRetrieve(Tid s);
    00955
    00956   void Remove(CargoDataEntry *comp);
    00957   void IncrementSize();
    00958
    00959   CargoDataEntry *parent;
    00960   const union {
    00961     StationID station;
    00962     struct {
    00963       CargoID cargo;
    00964       bool transfers;
    00965     };
    00966   };
    00967   uint num_children;
    00968   uint count;
    00969   CargoDataSet *children;
    00970 };
    00971
    00972 CargoDataEntry::CargoDataEntry() :
    00973   parent(NULL),
    00974   station(INVALID_STATION),
    00975   num_children(0),
    00976   count(0),
    00977   children(new CargoDataSet(CargoSorter(ST_CARGO_ID)))
    00978 {}
    00979
    00980 CargoDataEntry::CargoDataEntry(CargoID cargo, uint count, CargoDataEntry *parent) :
    00981   parent(parent),
    00982   cargo(cargo),
    00983   num_children(0),
    00984   count(count),
    00985   children(new CargoDataSet)
    00986 {}
    00987
    00988 CargoDataEntry::CargoDataEntry(StationID station, uint count, CargoDataEntry *parent) :
    00989   parent(parent),
    00990   station(station),
    00991   num_children(0),
    00992   count(count),
    00993   children(new CargoDataSet)
    00994 {}
    00995
    00996 CargoDataEntry::CargoDataEntry(StationID station) :
    00997   parent(NULL),
    00998   station(station),
    00999   num_children(0),
    01000   count(0),
    01001   children(NULL)
    01002 {}
    01003
    01004 CargoDataEntry::CargoDataEntry(CargoID cargo) :
    01005   parent(NULL),
    01006   cargo(cargo),
    01007   num_children(0),
    01008   count(0),
    01009   children(NULL)
    01010 {}
    01011
    01012 CargoDataEntry::~CargoDataEntry()
    01013 {
    01014   this->Clear();
    01015   delete this->children;
    01016 }
    01017
    01021 void CargoDataEntry::Clear()
    01022 {
    01023   if (this->children != NULL) {
    01024     for (CargoDataSet::iterator i = this->children->begin(); i != this->children->end(); ++i) {
    01025       assert(*i != this);
    01026       delete *i;
    01027     }
    01028     this->children->clear();
    01029   }
    01030   if (this->parent != NULL) this->parent->count -= this->count;
    01031   this->count = 0;
    01032   this->num_children = 0;
    01033 }
    01034
    01041 void CargoDataEntry::Remove(CargoDataEntry *child)
    01042 {
    01043   CargoDataSet::iterator i = this->children->find(child);
    01044   if (i != this->children->end()) {
    01045     delete *i;
    01046     this->children->erase(i);
    01047   }
    01048 }
    01049
    01056 template<class Tid>
    01057 CargoDataEntry *CargoDataEntry::InsertOrRetrieve(Tid child_id)
    01058 {
    01059   CargoDataEntry tmp(child_id);
    01060   CargoDataSet::iterator i = this->children->find(&tmp);
    01061   if (i == this->children->end()) {
    01062     IncrementSize();
    01063     return *(this->children->insert(new CargoDataEntry(child_id, 0, this)).first);
    01064   } else {
    01065     CargoDataEntry *ret = *i;
    01066     assert(this->children->value_comp().GetSortType() != ST_COUNT);
    01067     return ret;
    01068   }
    01069 }
    01070
    01076 void CargoDataEntry::Update(uint count)
    01077 {
    01078   this->count += count;
    01079   if (this->parent != NULL) this->parent->Update(count);
    01080 }
    01081
    01085 void CargoDataEntry::IncrementSize()
    01086 {
    01087    ++this->num_children;
    01088    if (this->parent != NULL) this->parent->IncrementSize();
    01089 }
    01090
    01091 void CargoDataEntry::Resort(CargoSortType type, SortOrder order)
    01092 {
    01093   CargoDataSet *new_subs = new CargoDataSet(this->children->begin(), this->children->end(), CargoSorter(type, order));
    01094   delete this->children;
    01095   this->children = new_subs;
    01096 }
    01097
    01098 CargoDataEntry *CargoDataEntry::Retrieve(CargoDataSet::iterator i) const
    01099 {
    01100   if (i == this->children->end()) {
    01101     return NULL;
    01102   } else {
    01103     assert(this->children->value_comp().GetSortType() != ST_COUNT);
    01104     return *i;
    01105   }
    01106 }
    01107
    01108 bool CargoSorter::operator()(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const
    01109 {
    01110   switch (this->type) {
    01111     case ST_STATION_ID:
    01112       return this->SortId<StationID>(cd1->GetStation(), cd2->GetStation());
    01113     case ST_CARGO_ID:
    01114       return this->SortId<CargoID>(cd1->GetCargo(), cd2->GetCargo());
    01115     case ST_COUNT:
    01116       return this->SortCount(cd1, cd2);
    01117     case ST_STATION_STRING:
    01118       return this->SortStation(cd1->GetStation(), cd2->GetStation());
    01119     default:
    01120       NOT_REACHED();
    01121   }
    01122 }
    01123
    01124 template<class Tid>
    01125 bool CargoSorter::SortId(Tid st1, Tid st2) const
    01126 {
    01127   return (this->order == SO_ASCENDING) ? st1 < st2 : st2 < st1;
    01128 }
    01129
    01130 bool CargoSorter::SortCount(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const
    01131 {
    01132   uint c1 = cd1->GetCount();
    01133   uint c2 = cd2->GetCount();
    01134   if (c1 == c2) {
    01135     return this->SortStation(cd1->GetStation(), cd2->GetStation());
    01136   } else if (this->order == SO_ASCENDING) {
    01137     return c1 < c2;
    01138   } else {
    01139     return c2 < c1;
    01140   }
    01141 }
    01142
    01143 bool CargoSorter::SortStation(StationID st1, StationID st2) const
    01144 {
    01145   static char buf1[MAX_LENGTH_STATION_NAME_CHARS];
    01146   static char buf2[MAX_LENGTH_STATION_NAME_CHARS];
    01147
    01148   if (!Station::IsValidID(st1)) {
    01149     return Station::IsValidID(st2) ? this->order == SO_ASCENDING : this->SortId(st1, st2);
    01150   } else if (!Station::IsValidID(st2)) {
    01151     return order == SO_DESCENDING;
    01152   }
    01153
    01154   SetDParam(0, st1);
    01155   GetString(buf1, STR_STATION_NAME, lastof(buf1));
    01156   SetDParam(0, st2);
    01157   GetString(buf2, STR_STATION_NAME, lastof(buf2));
    01158
    01159   int res = strcmp(buf1, buf2);
    01160   if (res == 0) {
    01161     return this->SortId(st1, st2);
    01162   } else {
    01163     return (this->order == SO_ASCENDING) ? res < 0 : res > 0;
    01164   }
    01165 }
    01166
    01170 struct StationViewWindow : public Window {
    01174   struct RowDisplay {
    01175     RowDisplay(CargoDataEntry *f, StationID n) : filter(f), next_station(n) {}
    01176     RowDisplay(CargoDataEntry *f, CargoID n) : filter(f), next_cargo(n) {}
    01177
    01181     CargoDataEntry *filter;
    01182     union {
    01186       StationID next_station;
    01187
    01191       CargoID next_cargo;
    01192     };
    01193   };
    01194
    01195   typedef std::vector<RowDisplay> CargoDataVector;
    01196
    01197   static const int NUM_COLUMNS = 4;
    01198
    01202   enum Invalidation {
    01203     INV_FLOWS = 0x100,
    01204     INV_CARGO = 0x200
    01205   };
    01206
    01210   enum Grouping {
    01211     GR_SOURCE,
    01212     GR_NEXT,
    01213     GR_DESTINATION,
    01214     GR_CARGO,
    01215   };
    01216
    01220   enum Mode {
    01221     MODE_WAITING,
    01222     MODE_PLANNED
    01223   };
    01224
    01225   uint expand_shrink_width;
    01226   int rating_lines;
    01227   int accepts_lines;
    01228   Scrollbar *vscroll;
    01229
    01231   enum AcceptListHeight {
    01232     ALH_RATING  = 13,
    01233     ALH_ACCEPTS = 3,
    01234   };
    01235
    01236   static const StringID _sort_names[];
    01237   static const StringID _group_names[];
    01238
    01245   CargoSortType sortings[NUM_COLUMNS];
    01246
    01248   SortOrder sort_orders[NUM_COLUMNS];
    01249
    01250   int scroll_to_row;
    01251   int grouping_index;
    01252   Mode current_mode;
    01253   Grouping groupings[NUM_COLUMNS];
    01254
    01255   CargoDataEntry expanded_rows;
    01256   CargoDataEntry cached_destinations;
    01257   CargoDataVector displayed_rows;
    01258
    01259   StationViewWindow(const WindowDesc *desc, WindowNumber window_number) : Window(),
    01260     scroll_to_row(INT_MAX), grouping_index(0)
    01261   {
    01262     this->rating_lines  = ALH_RATING;
    01263     this->accepts_lines = ALH_ACCEPTS;
    01264
    01265     this->CreateNestedTree(desc);
    01266     this->vscroll = this->GetScrollbar(WID_SV_SCROLLBAR);
    01267     /* Nested widget tree creation is done in two steps to ensure that this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS) exists in UpdateWidgetSize(). */
    01268     this->FinishInitNested(desc, window_number);
    01269
    01270     this->groupings[0] = GR_CARGO;
    01271     this->sortings[0] = ST_AS_GROUPING;
    01272     this->SelectGroupBy(_settings_client.gui.station_gui_group_order);
    01273     this->SelectSortBy(_settings_client.gui.station_gui_sort_by);
    01274     this->sort_orders[0] = SO_ASCENDING;
    01275     this->SelectSortOrder((SortOrder)_settings_client.gui.station_gui_sort_order);
    01276     Owner owner = Station::Get(window_number)->owner;
    01277     if (owner != OWNER_NONE) this->owner = owner;
    01278   }
    01279
    01280   ~StationViewWindow()
    01281   {
    01282     Owner owner = Station::Get(this->window_number)->owner;
    01283     DeleteWindowById(WC_TRAINS_LIST,   VehicleListIdentifier(VL_STATION_LIST, VEH_TRAIN,    owner, this->window_number).Pack(), false);
    01284     DeleteWindowById(WC_ROADVEH_LIST,  VehicleListIdentifier(VL_STATION_LIST, VEH_ROAD,     owner, this->window_number).Pack(), false);
    01285     DeleteWindowById(WC_SHIPS_LIST,    VehicleListIdentifier(VL_STATION_LIST, VEH_SHIP,     owner, this->window_number).Pack(), false);
    01286     DeleteWindowById(WC_AIRCRAFT_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_AIRCRAFT, owner, this->window_number).Pack(), false);
    01287   }
    01288
    01299   void ShowCargo(CargoDataEntry *data, CargoID cargo, StationID source, StationID next, StationID dest, uint count)
    01300   {
    01301     if (count == 0) return;
    01302     bool auto_distributed = _settings_game.linkgraph.GetDistributionType(cargo) != DT_MANUAL;
    01303     const CargoDataEntry *expand = &this->expanded_rows;
    01304     for (int i = 0; i < NUM_COLUMNS && expand != NULL; ++i) {
    01305       switch (groupings[i]) {
    01306         case GR_CARGO:
    01307           assert(i == 0);
    01308           data = data->InsertOrRetrieve(cargo);
    01309           data->transfers = (source != this->window_number);
    01310           expand = expand->Retrieve(cargo);
    01311           break;
    01312         case GR_SOURCE:
    01313           if (auto_distributed || source != this->window_number) {
    01314             data = data->InsertOrRetrieve(source);
    01315             expand = expand->Retrieve(source);
    01316           }
    01317           break;
    01318         case GR_NEXT:
    01319           if (auto_distributed) {
    01320             data = data->InsertOrRetrieve(next);
    01321             expand = expand->Retrieve(next);
    01322           }
    01323           break;
    01324         case GR_DESTINATION:
    01325           if (auto_distributed) {
    01326             data = data->InsertOrRetrieve(dest);
    01327             expand = expand->Retrieve(dest);
    01328           }
    01329           break;
    01330       }
    01331     }
    01332     data->Update(count);
    01333   }
    01334
    01335   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    01336   {
    01337     switch (widget) {
    01338       case WID_SV_WAITING:
    01339         resize->height = FONT_HEIGHT_NORMAL;
    01340         size->height = WD_FRAMERECT_TOP + 4 * resize->height + WD_FRAMERECT_BOTTOM;
    01341         this->expand_shrink_width = max(GetStringBoundingBox("-").width, GetStringBoundingBox("+").width) + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
    01342         break;
    01343
    01344       case WID_SV_ACCEPT_RATING_LIST:
    01345         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;
    01346         break;
    01347
    01348       case WID_SV_CLOSE_AIRPORT:
    01349         if (!(Station::Get(this->window_number)->facilities & FACIL_AIRPORT)) {
    01350           /* Hide 'Close Airport' button if no airport present. */
    01351           size->width = 0;
    01352           resize->width = 0;
    01353           fill->width = 0;
    01354         }
    01355         break;
    01356     }
    01357   }
    01358
    01359   virtual void OnPaint()
    01360   {
    01361     const Station *st = Station::Get(this->window_number);
    01362     CargoDataEntry cargo;
    01363     BuildCargoList(&cargo, st);
    01364
    01365     this->vscroll->SetCount(cargo.GetNumChildren()); // update scrollbar
    01366
    01367     /* disable some buttons */
    01368     this->SetWidgetDisabledState(WID_SV_RENAME,   st->owner != _local_company);
    01369     this->SetWidgetDisabledState(WID_SV_TRAINS,   !(st->facilities & FACIL_TRAIN));
    01370     this->SetWidgetDisabledState(WID_SV_ROADVEHS, !(st->facilities & FACIL_TRUCK_STOP) && !(st->facilities & FACIL_BUS_STOP));
    01371     this->SetWidgetDisabledState(WID_SV_SHIPS,    !(st->facilities & FACIL_DOCK));
    01372     this->SetWidgetDisabledState(WID_SV_PLANES,   !(st->facilities & FACIL_AIRPORT));
    01373     this->SetWidgetDisabledState(WID_SV_CLOSE_AIRPORT, !(st->facilities & FACIL_AIRPORT) || st->owner != _local_company || st->owner == OWNER_NONE); // Also consider SE, where _local_company == OWNER_NONE
    01374     this->SetWidgetLoweredState(WID_SV_CLOSE_AIRPORT, (st->facilities & FACIL_AIRPORT) && (st->airport.flags & AIRPORT_CLOSED_block) != 0);
    01375
    01376     this->DrawWidgets();
    01377
    01378     if (!this->IsShaded()) {
    01379       /* Draw 'accepted cargo' or 'cargo ratings'. */
    01380       const NWidgetBase *wid = this->GetWidget<NWidgetBase>(WID_SV_ACCEPT_RATING_LIST);
    01381       const Rect r = {wid->pos_x, wid->pos_y, wid->pos_x + wid->current_x - 1, wid->pos_y + wid->current_y - 1};
    01382       if (this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) {
    01383         int lines = this->DrawAcceptedCargo(r);
    01384         if (lines > this->accepts_lines) { // Resize the widget, and perform re-initialization of the window.
    01385           this->accepts_lines = lines;
    01386           this->ReInit();
    01387           return;
    01388         }
    01389       } else {
    01390         int lines = this->DrawCargoRatings(r);
    01391         if (lines > this->rating_lines) { // Resize the widget, and perform re-initialization of the window.
    01392           this->rating_lines = lines;
    01393           this->ReInit();
    01394           return;
    01395         }
    01396       }
    01397
    01398       /* Draw arrow pointing up/down for ascending/descending sorting */
    01399       this->DrawSortButtonState(WID_SV_SORT_ORDER, sort_orders[1] == SO_ASCENDING ? SBS_UP : SBS_DOWN);
    01400
    01401       int pos = this->vscroll->GetPosition();
    01402
    01403       int maxrows = this->vscroll->GetCapacity();
    01404
    01405       displayed_rows.clear();
    01406
    01407       /* Draw waiting cargo. */
    01408       NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_SV_WAITING);
    01409       Rect waiting_rect = {nwi->pos_x, nwi->pos_y, nwi->pos_x + nwi->current_x - 1, nwi->pos_y + nwi->current_y - 1};
    01410       this->DrawEntries(&cargo, waiting_rect, pos, maxrows, 0);
    01411       scroll_to_row = INT_MAX;
    01412     }
    01413   }
    01414
    01415   virtual void SetStringParameters(int widget) const
    01416   {
    01417     const Station *st = Station::Get(this->window_number);
    01418     SetDParam(0, st->index);
    01419     SetDParam(1, st->facilities);
    01420   }
    01421
    01427   void RecalcDestinations(CargoID i)
    01428   {
    01429     const Station *st = Station::Get(this->window_number);
    01430     CargoDataEntry *cargo_entry = cached_destinations.InsertOrRetrieve(i);
    01431     cargo_entry->Clear();
    01432
    01433     const FlowStatMap &flows = st->goods[i].flows;
    01434     for (FlowStatMap::const_iterator it = flows.begin(); it != flows.end(); ++it) {
    01435       StationID from = it->first;
    01436       CargoDataEntry *source_entry = cargo_entry->InsertOrRetrieve(from);
    01437       const FlowStat::SharesMap *shares = it->second.GetShares();
    01438       uint32 prev_count = 0;
    01439       for (FlowStat::SharesMap::const_iterator flow_it = shares->begin(); flow_it != shares->end(); ++flow_it) {
    01440         StationID via = flow_it->second;
    01441         CargoDataEntry *via_entry = source_entry->InsertOrRetrieve(via);
    01442         if (via == this->window_number) {
    01443           via_entry->InsertOrRetrieve(via)->Update(flow_it->first - prev_count);
    01444         } else {
    01445           EstimateDestinations(i, from, via, flow_it->first - prev_count, via_entry);
    01446         }
    01447         prev_count = flow_it->first;
    01448       }
    01449     }
    01450   }
    01451
    01461   void EstimateDestinations(CargoID cargo, StationID source, StationID next, uint count, CargoDataEntry *dest)
    01462   {
    01463     if (Station::IsValidID(next) && Station::IsValidID(source)) {
    01464       CargoDataEntry tmp;
    01465       const FlowStatMap &flowmap = Station::Get(next)->goods[cargo].flows;
    01466       FlowStatMap::const_iterator map_it = flowmap.find(source);
    01467       if (map_it != flowmap.end()) {
    01468         const FlowStat::SharesMap *shares = map_it->second.GetShares();
    01469         uint32 prev_count = 0;
    01470         for (FlowStat::SharesMap::const_iterator i = shares->begin(); i != shares->end(); ++i) {
    01471           tmp.InsertOrRetrieve(i->second)->Update(i->first - prev_count);
    01472           prev_count = i->first;
    01473         }
    01474       }
    01475
    01476       if (tmp.GetCount() == 0) {
    01477         dest->InsertOrRetrieve(INVALID_STATION)->Update(count);
    01478       } else {
    01479         uint sum_estimated = 0;
    01480         while (sum_estimated < count) {
    01481           for (CargoDataSet::iterator i = tmp.Begin(); i != tmp.End() && sum_estimated < count; ++i) {
    01482             CargoDataEntry *child = *i;
    01483             uint estimate = DivideApprox(child->GetCount() * count, tmp.GetCount());
    01484             if (estimate == 0) estimate = 1;
    01485
    01486             sum_estimated += estimate;
    01487             if (sum_estimated > count) {
    01488               estimate -= sum_estimated - count;
    01489               sum_estimated = count;
    01490             }
    01491
    01492             if (estimate > 0) {
    01493               if (child->GetStation() == next) {
    01494                 dest->InsertOrRetrieve(next)->Update(estimate);
    01495               } else {
    01496                 EstimateDestinations(cargo, source, child->GetStation(), estimate, dest);
    01497               }
    01498             }
    01499           }
    01500
    01501         }
    01502       }
    01503     } else {
    01504       dest->InsertOrRetrieve(INVALID_STATION)->Update(count);
    01505     }
    01506   }
    01507
    01514   void BuildFlowList(CargoID i, const FlowStatMap &flows, CargoDataEntry *cargo)
    01515   {
    01516     const CargoDataEntry *source_dest = this->cached_destinations.Retrieve(i);
    01517     for (FlowStatMap::const_iterator it = flows.begin(); it != flows.end(); ++it) {
    01518       StationID from = it->first;
    01519       const CargoDataEntry *source_entry = source_dest->Retrieve(from);
    01520       const FlowStat::SharesMap *shares = it->second.GetShares();
    01521       for (FlowStat::SharesMap::const_iterator flow_it = shares->begin(); flow_it != shares->end(); ++flow_it) {
    01522         const CargoDataEntry *via_entry = source_entry->Retrieve(flow_it->second);
    01523         for (CargoDataSet::iterator dest_it = via_entry->Begin(); dest_it != via_entry->End(); ++dest_it) {
    01524           CargoDataEntry *dest_entry = *dest_it;
    01525           ShowCargo(cargo, i, from, flow_it->second, dest_entry->GetStation(), dest_entry->GetCount());
    01526         }
    01527       }
    01528     }
    01529   }
    01530
    01537   void BuildCargoList(CargoID i, const StationCargoList &packets, CargoDataEntry *cargo)
    01538   {
    01539     const CargoDataEntry *source_dest = this->cached_destinations.Retrieve(i);
    01540     for (StationCargoList::ConstIterator it = packets.Packets()->begin(); it != packets.Packets()->end(); it++) {
    01541       const CargoPacket *cp = *it;
    01542       StationID next = it.GetKey();
    01543
    01544       const CargoDataEntry *source_entry = source_dest->Retrieve(cp->SourceStation());
    01545       if (source_entry == NULL) {
    01546         this->ShowCargo(cargo, i, cp->SourceStation(), next, INVALID_STATION, cp->Count());
    01547         continue;
    01548       }
    01549
    01550       const CargoDataEntry *via_entry = source_entry->Retrieve(next);
    01551       if (via_entry == NULL) {
    01552         this->ShowCargo(cargo, i, cp->SourceStation(), next, INVALID_STATION, cp->Count());
    01553         continue;
    01554       }
    01555
    01556       for (CargoDataSet::iterator dest_it = via_entry->Begin(); dest_it != via_entry->End(); ++dest_it) {
    01557         CargoDataEntry *dest_entry = *dest_it;
    01558         uint val = DivideApprox(cp->Count() * dest_entry->GetCount(), via_entry->GetCount());
    01559         this->ShowCargo(cargo, i, cp->SourceStation(), next, dest_entry->GetStation(), val);
    01560       }
    01561     }
    01562     this->ShowCargo(cargo, i, NEW_STATION, NEW_STATION, NEW_STATION, packets.ReservedCount());
    01563   }
    01564
    01570   void BuildCargoList(CargoDataEntry *cargo, const Station *st)
    01571   {
    01572     for (CargoID i = 0; i < NUM_CARGO; i++) {
    01573
    01574       if (this->cached_destinations.Retrieve(i) == NULL) {
    01575         this->RecalcDestinations(i);
    01576       }
    01577
    01578       if (this->current_mode == MODE_WAITING) {
    01579         this->BuildCargoList(i, st->goods[i].cargo, cargo);
    01580       } else {
    01581         this->BuildFlowList(i, st->goods[i].flows, cargo);
    01582       }
    01583     }
    01584   }
    01585
    01590   void SetDisplayedRow(const CargoDataEntry *data)
    01591   {
    01592     std::list<StationID> stations;
    01593     const CargoDataEntry *parent = data->GetParent();
    01594     if (parent->GetParent() == NULL) {
    01595       this->displayed_rows.push_back(RowDisplay(&this->expanded_rows, data->GetCargo()));
    01596       return;
    01597     }
    01598
    01599     StationID next = data->GetStation();
    01600     while (parent->GetParent()->GetParent() != NULL) {
    01601       stations.push_back(parent->GetStation());
    01602       parent = parent->GetParent();
    01603     }
    01604
    01605     CargoID cargo = parent->GetCargo();
    01606     CargoDataEntry *filter = this->expanded_rows.Retrieve(cargo);
    01607     while (!stations.empty()) {
    01608       filter = filter->Retrieve(stations.back());
    01609       stations.pop_back();
    01610     }
    01611
    01612     this->displayed_rows.push_back(RowDisplay(filter, next));
    01613   }
    01614
    01623   StringID GetEntryString(StationID station, StringID here, StringID other_station, StringID any)
    01624   {
    01625     if (station == this->window_number) {
    01626       return here;
    01627     } else if (station == INVALID_STATION) {
    01628       return any;
    01629     } else if (station == NEW_STATION) {
    01630       return STR_STATION_VIEW_RESERVED;
    01631     } else {
    01632       SetDParam(2, station);
    01633       return other_station;
    01634     }
    01635   }
    01636
    01644   StringID SearchNonStop(CargoDataEntry *cd, StationID station, int column)
    01645   {
    01646     CargoDataEntry *parent = cd->GetParent();
    01647     for (int i = column - 1; i > 0; --i) {
    01648       if (this->groupings[i] == GR_DESTINATION) {
    01649         if (parent->GetStation() == station) {
    01650           return STR_STATION_VIEW_NONSTOP;
    01651         } else {
    01652           return STR_STATION_VIEW_VIA;
    01653         }
    01654       }
    01655       parent = parent->GetParent();
    01656     }
    01657
    01658     if (this->groupings[column + 1] == GR_DESTINATION) {
    01659       CargoDataSet::iterator begin = cd->Begin();
    01660       CargoDataSet::iterator end = cd->End();
    01661       if (begin != end && ++(cd->Begin()) == end && (*(begin))->GetStation() == station) {
    01662         return STR_STATION_VIEW_NONSTOP;
    01663       } else {
    01664         return STR_STATION_VIEW_VIA;
    01665       }
    01666     }
    01667
    01668     return STR_STATION_VIEW_VIA;
    01669   }
    01670
    01681   int DrawEntries(CargoDataEntry *entry, Rect &r, int pos, int maxrows, int column, CargoID cargo = CT_INVALID)
    01682   {
    01683     if (this->sortings[column] == ST_AS_GROUPING) {
    01684       if (this->groupings[column] != GR_CARGO) {
    01685         entry->Resort(ST_STATION_STRING, this->sort_orders[column]);
    01686       }
    01687     } else {
    01688       entry->Resort(ST_COUNT, this->sort_orders[column]);
    01689     }
    01690     for (CargoDataSet::iterator i = entry->Begin(); i != entry->End(); ++i) {
    01691       CargoDataEntry *cd = *i;
    01692
    01693       Grouping grouping = this->groupings[column];
    01694       if (grouping == GR_CARGO) cargo = cd->GetCargo();
    01695       bool auto_distributed = _settings_game.linkgraph.GetDistributionType(cargo) != DT_MANUAL;
    01696
    01697       if (pos > -maxrows && pos <= 0) {
    01698         StringID str = STR_EMPTY;
    01699         int y = r.top + WD_FRAMERECT_TOP - pos * FONT_HEIGHT_NORMAL;
    01700         SetDParam(0, cargo);
    01701         SetDParam(1, cd->GetCount());
    01702
    01703         if (this->groupings[column] == GR_CARGO) {
    01704           str = STR_STATION_VIEW_WAITING_CARGO;
    01705           DrawCargoIcons(cd->GetCargo(), cd->GetCount(), r.left + WD_FRAMERECT_LEFT + this->expand_shrink_width, r.right - WD_FRAMERECT_RIGHT - this->expand_shrink_width, y);
    01706         } else {
    01707           if (!auto_distributed) grouping = GR_SOURCE;
    01708           StationID station = cd->GetStation();
    01709
    01710           switch (grouping) {
    01711             case GR_SOURCE:
    01712               str = this->GetEntryString(station, STR_STATION_VIEW_FROM_HERE, STR_STATION_VIEW_FROM, STR_STATION_VIEW_FROM_ANY);
    01713               break;
    01714             case GR_NEXT:
    01715               str = this->GetEntryString(station, STR_STATION_VIEW_VIA_HERE, STR_STATION_VIEW_VIA, STR_STATION_VIEW_VIA_ANY);
    01716               if (str == STR_STATION_VIEW_VIA) str = this->SearchNonStop(cd, station, column);
    01717               break;
    01718             case GR_DESTINATION:
    01719               str = this->GetEntryString(station, STR_STATION_VIEW_TO_HERE, STR_STATION_VIEW_TO, STR_STATION_VIEW_TO_ANY);
    01720               break;
    01721             default:
    01722               NOT_REACHED();
    01723           }
    01724           if (pos == -this->scroll_to_row && Station::IsValidID(station)) {
    01725             ScrollMainWindowToTile(Station::Get(station)->xy);
    01726           }
    01727         }
    01728
    01729         bool rtl = _current_text_dir == TD_RTL;
    01730         int text_left    = rtl ? r.left + this->expand_shrink_width : r.left + WD_FRAMERECT_LEFT + column * this->expand_shrink_width;
    01731         int text_right   = rtl ? r.right - WD_FRAMERECT_LEFT - column * this->expand_shrink_width : r.right - this->expand_shrink_width;
    01732         int shrink_left  = rtl ? r.left + WD_FRAMERECT_LEFT : r.right - this->expand_shrink_width + WD_FRAMERECT_LEFT;
    01733         int shrink_right = rtl ? r.left + this->expand_shrink_width - WD_FRAMERECT_RIGHT : r.right - WD_FRAMERECT_RIGHT;
    01734
    01735         DrawString(text_left, text_right, y, str);
    01736
    01737         if (column < NUM_COLUMNS - 1) {
    01738           const char *sym = NULL;
    01739           if (cd->GetNumChildren() > 0) {
    01740             sym = "-";
    01741           } else if (auto_distributed && str != STR_STATION_VIEW_RESERVED) {
    01742             sym = "+";
    01743           } else {
    01744             /* Only draw '+' if there is something to be shown. */
    01745             const StationCargoList &list = Station::Get(this->window_number)->goods[cargo].cargo;
    01746             if (grouping == GR_CARGO && (list.ReservedCount() > 0 || cd->transfers)) {
    01747               sym = "+";
    01748             }
    01749           }
    01750           if (sym) DrawString(shrink_left, shrink_right, y, sym, TC_YELLOW);
    01751         }
    01752         this->SetDisplayedRow(cd);
    01753       }
    01754       --pos;
    01755       if (auto_distributed || column == 0) {
    01756         pos = this->DrawEntries(cd, r, pos, maxrows, column + 1, cargo);
    01757       }
    01758     }
    01759     return pos;
    01760   }
    01761
    01767   int DrawAcceptedCargo(const Rect &r) const
    01768   {
    01769     const Station *st = Station::Get(this->window_number);
    01770
    01771     uint32 cargo_mask = 0;
    01772     for (CargoID i = 0; i < NUM_CARGO; i++) {
    01773       if (HasBit(st->goods[i].acceptance_pickup, GoodsEntry::GES_ACCEPTANCE)) SetBit(cargo_mask, i);
    01774     }
    01775     SetDParam(0, cargo_mask);
    01776     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);
    01777     return CeilDiv(bottom - r.top - WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL);
    01778   }
    01779
    01785   int DrawCargoRatings(const Rect &r) const
    01786   {
    01787     const Station *st = Station::Get(this->window_number);
    01788     int y = r.top + WD_FRAMERECT_TOP;
    01789
    01790     if (st->town->exclusive_counter > 0) {
    01791       SetDParam(0, st->town->exclusivity);
    01792       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);
    01793       y += WD_PAR_VSEP_WIDE;
    01794     }
    01795
    01796     DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_VIEW_SUPPLY_RATINGS_TITLE);
    01797     y += FONT_HEIGHT_NORMAL;
    01798
    01799     const CargoSpec *cs;
    01800     FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
    01801       const GoodsEntry *ge = &st->goods[cs->Index()];
    01802       if (!HasBit(ge->acceptance_pickup, GoodsEntry::GES_PICKUP)) continue;
    01803
    01804       SetDParam(0, cs->name);
    01805       LinkGraph *lg = LinkGraph::GetIfValid(ge->link_graph);
    01806       SetDParam(1, lg != NULL ? lg->Monthly((*lg)[ge->node].Supply()) : 0);
    01807       SetDParam(3, ToPercent8(ge->rating));
    01808       SetDParam(2, STR_CARGO_RATING_APPALLING + (ge->rating >> 5));
    01809       DrawString(r.left + WD_FRAMERECT_LEFT + 6, r.right - WD_FRAMERECT_RIGHT - 6, y, STR_STATION_VIEW_CARGO_SUPPLY_RATING);
    01810       y += FONT_HEIGHT_NORMAL;
    01811     }
    01812     return CeilDiv(y - r.top - WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL);
    01813   }
    01814
    01820   template<class Tid>
    01821   void HandleCargoWaitingClick(CargoDataEntry *filter, Tid next)
    01822   {
    01823     if (filter->Retrieve(next) != NULL) {
    01824       filter->Remove(next);
    01825     } else {
    01826       filter->InsertOrRetrieve(next);
    01827     }
    01828   }
    01829
    01834   void HandleCargoWaitingClick(int row)
    01835   {
    01836     if (row < 0 || (uint)row >= this->displayed_rows.size()) return;
    01837     if (_ctrl_pressed) {
    01838       this->scroll_to_row = row;
    01839     } else {
    01840       RowDisplay &display = this->displayed_rows[row];
    01841       if (display.filter == &this->expanded_rows) {
    01842         this->HandleCargoWaitingClick<CargoID>(display.filter, display.next_cargo);
    01843       } else {
    01844         this->HandleCargoWaitingClick<StationID>(display.filter, display.next_station);
    01845       }
    01846     }
    01847     this->SetWidgetDirty(WID_SV_WAITING);
    01848   }
    01849
    01850   virtual void OnClick(Point pt, int widget, int click_count)
    01851   {
    01852     switch (widget) {
    01853       case WID_SV_WAITING:
    01854         this->HandleCargoWaitingClick(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_SV_WAITING, WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL) - this->vscroll->GetPosition());
    01855         break;
    01856
    01857       case WID_SV_LOCATION:
    01858         if (_ctrl_pressed) {
    01859           ShowExtraViewPortWindow(Station::Get(this->window_number)->xy);
    01860         } else {
    01861           ScrollMainWindowToTile(Station::Get(this->window_number)->xy);
    01862         }
    01863         break;
    01864
    01865       case WID_SV_ACCEPTS_RATINGS: {
    01866         /* Swap between 'accepts' and 'ratings' view. */
    01867         int height_change;
    01868         NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS);
    01869         if (this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) {
    01870           nwi->SetDataTip(STR_STATION_VIEW_ACCEPTS_BUTTON, STR_STATION_VIEW_ACCEPTS_TOOLTIP); // Switch to accepts view.
    01871           height_change = this->rating_lines - this->accepts_lines;
    01872         } else {
    01873           nwi->SetDataTip(STR_STATION_VIEW_RATINGS_BUTTON, STR_STATION_VIEW_RATINGS_TOOLTIP); // Switch to ratings view.
    01874           height_change = this->accepts_lines - this->rating_lines;
    01875         }
    01876         this->ReInit(0, height_change * FONT_HEIGHT_NORMAL);
    01877         break;
    01878       }
    01879
    01880       case WID_SV_RENAME:
    01881         SetDParam(0, this->window_number);
    01882         ShowQueryString(STR_STATION_NAME, STR_STATION_VIEW_RENAME_STATION_CAPTION, MAX_LENGTH_STATION_NAME_CHARS,
    01883             this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
    01884         break;
    01885
    01886       case WID_SV_CLOSE_AIRPORT:
    01887         DoCommandP(0, this->window_number, 0, CMD_OPEN_CLOSE_AIRPORT);
    01888         break;
    01889
    01890       case WID_SV_TRAINS:   // Show list of scheduled trains to this station
    01891       case WID_SV_ROADVEHS: // Show list of scheduled road-vehicles to this station
    01892       case WID_SV_SHIPS:    // Show list of scheduled ships to this station
    01893       case WID_SV_PLANES: { // Show list of scheduled aircraft to this station
    01894         Owner owner = Station::Get(this->window_number)->owner;
    01895         ShowVehicleListWindow(owner, (VehicleType)(widget - WID_SV_TRAINS), (StationID)this->window_number);
    01896         break;
    01897       }
    01898
    01899       case WID_SV_SORT_BY: {
    01900         ShowDropDownMenu(this, _sort_names, this->current_mode, WID_SV_SORT_BY, 0, 0);
    01901         break;
    01902       }
    01903
    01904       case WID_SV_GROUP_BY: {
    01905         ShowDropDownMenu(this, _group_names, this->grouping_index, WID_SV_GROUP_BY, 0, 0);
    01906         break;
    01907       }
    01908
    01909       case WID_SV_SORT_ORDER: { // flip sorting method asc/desc
    01910         this->SelectSortOrder(this->sort_orders[1] == SO_ASCENDING ? SO_DESCENDING : SO_ASCENDING);
    01911         this->SetTimeout();
    01912         this->LowerWidget(WID_SV_SORT_ORDER);
    01913         break;
    01914       }
    01915     }
    01916   }
    01917
    01922   void SelectSortOrder(SortOrder order)
    01923   {
    01924     this->sort_orders[1] = this->sort_orders[2] = this->sort_orders[3] = order;
    01925     _settings_client.gui.station_gui_sort_order = this->sort_orders[1];
    01926     this->SetDirty();
    01927   }
    01928
    01933   void SelectSortBy(int index)
    01934   {
    01935     _settings_client.gui.station_gui_sort_by = index;
    01936     switch (_sort_names[index]) {
    01937       case STR_STATION_VIEW_WAITING_STATION:
    01938         this->current_mode = MODE_WAITING;
    01939         this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_AS_GROUPING;
    01940         break;
    01941       case STR_STATION_VIEW_WAITING_AMOUNT:
    01942         this->current_mode = MODE_WAITING;
    01943         this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_COUNT;
    01944         break;
    01945       case STR_STATION_VIEW_PLANNED_STATION:
    01946         this->current_mode = MODE_PLANNED;
    01947         this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_AS_GROUPING;
    01948         break;
    01949       case STR_STATION_VIEW_PLANNED_AMOUNT:
    01950         this->current_mode = MODE_PLANNED;
    01951         this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_COUNT;
    01952         break;
    01953       default:
    01954         NOT_REACHED();
    01955     }
    01956     /* Display the current sort variant */
    01957     this->GetWidget<NWidgetCore>(WID_SV_SORT_BY)->widget_data = _sort_names[index];
    01958     this->SetDirty();
    01959   }
    01960
    01965   void SelectGroupBy(int index)
    01966   {
    01967     this->grouping_index = index;
    01968     _settings_client.gui.station_gui_group_order = index;
    01969     this->GetWidget<NWidgetCore>(WID_SV_GROUP_BY)->widget_data = _group_names[index];
    01970     switch (_group_names[index]) {
    01971       case STR_STATION_VIEW_GROUP_S_V_D:
    01972         this->groupings[1] = GR_SOURCE;
    01973         this->groupings[2] = GR_NEXT;
    01974         this->groupings[3] = GR_DESTINATION;
    01975         break;
    01976       case STR_STATION_VIEW_GROUP_S_D_V:
    01977         this->groupings[1] = GR_SOURCE;
    01978         this->groupings[2] = GR_DESTINATION;
    01979         this->groupings[3] = GR_NEXT;
    01980         break;
    01981       case STR_STATION_VIEW_GROUP_V_S_D:
    01982         this->groupings[1] = GR_NEXT;
    01983         this->groupings[2] = GR_SOURCE;
    01984         this->groupings[3] = GR_DESTINATION;
    01985         break;
    01986       case STR_STATION_VIEW_GROUP_V_D_S:
    01987         this->groupings[1] = GR_NEXT;
    01988         this->groupings[2] = GR_DESTINATION;
    01989         this->groupings[3] = GR_SOURCE;
    01990         break;
    01991       case STR_STATION_VIEW_GROUP_D_S_V:
    01992         this->groupings[1] = GR_DESTINATION;
    01993         this->groupings[2] = GR_SOURCE;
    01994         this->groupings[3] = GR_NEXT;
    01995         break;
    01996       case STR_STATION_VIEW_GROUP_D_V_S:
    01997         this->groupings[1] = GR_DESTINATION;
    01998         this->groupings[2] = GR_NEXT;
    01999         this->groupings[3] = GR_SOURCE;
    02000         break;
    02001     }
    02002     this->SetDirty();
    02003   }
    02004
    02005   virtual void OnDropdownSelect(int widget, int index)
    02006   {
    02007     if (widget == WID_SV_SORT_BY) {
    02008       this->SelectSortBy(index);
    02009     } else {
    02010       this->SelectGroupBy(index);
    02011     }
    02012   }
    02013
    02014   virtual void OnQueryTextFinished(char *str)
    02015   {
    02016     if (str == NULL) return;
    02017
    02018     DoCommandP(0, this->window_number, 0, CMD_RENAME_STATION | CMD_MSG(STR_ERROR_CAN_T_RENAME_STATION), NULL, str);
    02019   }
    02020
    02021   virtual void OnResize()
    02022   {
    02023     this->vscroll->SetCapacityFromWidget(this, WID_SV_WAITING, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
    02024   }
    02025
    02031   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
    02032   {
    02033     if (gui_scope) {
    02034       if (data >= 0 && data < NUM_CARGO) {
    02035         this->cached_destinations.Remove((CargoID)data);
    02036       } else {
    02037         this->ReInit();
    02038       }
    02039     }
    02040   }
    02041 };
    02042
    02043 const StringID StationViewWindow::_sort_names[] = {
    02044   STR_STATION_VIEW_WAITING_STATION,
    02045   STR_STATION_VIEW_WAITING_AMOUNT,
    02046   STR_STATION_VIEW_PLANNED_STATION,
    02047   STR_STATION_VIEW_PLANNED_AMOUNT,
    02048   INVALID_STRING_ID
    02049 };
    02050
    02051 const StringID StationViewWindow::_group_names[] = {
    02052   STR_STATION_VIEW_GROUP_S_V_D,
    02053   STR_STATION_VIEW_GROUP_S_D_V,
    02054   STR_STATION_VIEW_GROUP_V_S_D,
    02055   STR_STATION_VIEW_GROUP_V_D_S,
    02056   STR_STATION_VIEW_GROUP_D_S_V,
    02057   STR_STATION_VIEW_GROUP_D_V_S,
    02058   INVALID_STRING_ID
    02059 };
    02060
    02061 static const WindowDesc _station_view_desc(
    02062   WDP_AUTO, 249, 117,
    02063   WC_STATION_VIEW, WC_NONE,
    02064   0,
    02065   _nested_station_view_widgets, lengthof(_nested_station_view_widgets)
    02066 );
    02067
    02073 void ShowStationViewWindow(StationID station)
    02074 {
    02075   AllocateWindowDescFront<StationViewWindow>(&_station_view_desc, station);
    02076 }
    02077
    02079 struct TileAndStation {
    02080   TileIndex tile;
    02081   StationID station;
    02082 };
    02083
    02084 static SmallVector<TileAndStation, 8> _deleted_stations_nearby;
    02085 static SmallVector<StationID, 8> _stations_nearby_list;
    02086
    02094 template <class T>
    02095 static bool AddNearbyStation(TileIndex tile, void *user_data)
    02096 {
    02097   TileArea *ctx = (TileArea *)user_data;
    02098
    02099   /* First check if there were deleted stations here */
    02100   for (uint i = 0; i < _deleted_stations_nearby.Length(); i++) {
    02101     TileAndStation *ts = _deleted_stations_nearby.Get(i);
    02102     if (ts->tile == tile) {
    02103       *_stations_nearby_list.Append() = _deleted_stations_nearby[i].station;
    02104       _deleted_stations_nearby.Erase(ts);
    02105       i--;
    02106     }
    02107   }
    02108
    02109   /* Check if own station and if we stay within station spread */
    02110   if (!IsTileType(tile, MP_STATION)) return false;
    02111
    02112   StationID sid = GetStationIndex(tile);
    02113
    02114   /* This station is (likely) a waypoint */
    02115   if (!T::IsValidID(sid)) return false;
    02116
    02117   T *st = T::Get(sid);
    02118   if (st->owner != _local_company || _stations_nearby_list.Contains(sid)) return false;
    02119
    02120   if (st->rect.BeforeAddRect(ctx->tile, ctx->w, ctx->h, StationRect::ADD_TEST).Succeeded()) {
    02121     *_stations_nearby_list.Append() = sid;
    02122   }
    02123
    02124   return false; // We want to include *all* nearby stations
    02125 }
    02126
    02136 template <class T>
    02137 static const T *FindStationsNearby(TileArea ta, bool distant_join)
    02138 {
    02139   TileArea ctx = ta;
    02140
    02141   _stations_nearby_list.Clear();
    02142   _deleted_stations_nearby.Clear();
    02143
    02144   /* Check the inside, to return, if we sit on another station */
    02145   TILE_AREA_LOOP(t, ta) {
    02146     if (t < MapSize() && IsTileType(t, MP_STATION) && T::IsValidID(GetStationIndex(t))) return T::GetByTile(t);
    02147   }
    02148
    02149   /* Look for deleted stations */
    02150   const BaseStation *st;
    02151   FOR_ALL_BASE_STATIONS(st) {
    02152     if (T::IsExpected(st) && !st->IsInUse() && st->owner == _local_company) {
    02153       /* Include only within station spread (yes, it is strictly less than) */
    02154       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) {
    02155         TileAndStation *ts = _deleted_stations_nearby.Append();
    02156         ts->tile = st->xy;
    02157         ts->station = st->index;
    02158
    02159         /* Add the station when it's within where we're going to build */
    02160         if (IsInsideBS(TileX(st->xy), TileX(ctx.tile), ctx.w) &&
    02161             IsInsideBS(TileY(st->xy), TileY(ctx.tile), ctx.h)) {
    02162           AddNearbyStation<T>(st->xy, &ctx);
    02163         }
    02164       }
    02165     }
    02166   }
    02167
    02168   /* Only search tiles where we have a chance to stay within the station spread.
    02169    * The complete check needs to be done in the callback as we don't know the
    02170    * extent of the found station, yet. */
    02171   if (distant_join && min(ta.w, ta.h) >= _settings_game.station.station_spread) return NULL;
    02172   uint max_dist = distant_join ? _settings_game.station.station_spread - min(ta.w, ta.h) : 1;
    02173
    02174   TileIndex tile = TILE_ADD(ctx.tile, TileOffsByDir(DIR_N));
    02175   CircularTileSearch(&tile, max_dist, ta.w, ta.h, AddNearbyStation<T>, &ctx);
    02176
    02177   return NULL;
    02178 }
    02179
    02180 static const NWidgetPart _nested_select_station_widgets[] = {
    02181   NWidget(NWID_HORIZONTAL),
    02182     NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
    02183     NWidget(WWT_CAPTION, COLOUR_DARK_GREEN, WID_JS_CAPTION), SetDataTip(STR_JOIN_STATION_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
    02184   EndContainer(),
    02185   NWidget(NWID_HORIZONTAL),
    02186     NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_JS_PANEL), SetResize(1, 0), SetScrollbar(WID_JS_SCROLLBAR), EndContainer(),
    02187     NWidget(NWID_VERTICAL),
    02188       NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, WID_JS_SCROLLBAR),
    02189       NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
    02190     EndContainer(),
    02191   EndContainer(),
    02192 };
    02193
    02198 template <class T>
    02199 struct SelectStationWindow : Window {
    02200   CommandContainer select_station_cmd;
    02201   TileArea area;
    02202   Scrollbar *vscroll;
    02203
    02204   SelectStationWindow(const WindowDesc *desc, CommandContainer cmd, TileArea ta) :
    02205     Window(),
    02206     select_station_cmd(cmd),
    02207     area(ta)
    02208   {
    02209     this->CreateNestedTree(desc);
    02210     this->vscroll = this->GetScrollbar(WID_JS_SCROLLBAR);
    02211     this->GetWidget<NWidgetCore>(WID_JS_CAPTION)->widget_data = T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_JOIN_WAYPOINT_CAPTION : STR_JOIN_STATION_CAPTION;
    02212     this->FinishInitNested(desc, 0);
    02213     this->OnInvalidateData(0);
    02214   }
    02215
    02216   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    02217   {
    02218     if (widget != WID_JS_PANEL) return;
    02219
    02220     /* Determine the widest string */
    02221     Dimension d = GetStringBoundingBox(T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_JOIN_WAYPOINT_CREATE_SPLITTED_WAYPOINT : STR_JOIN_STATION_CREATE_SPLITTED_STATION);
    02222     for (uint i = 0; i < _stations_nearby_list.Length(); i++) {
    02223       const T *st = T::Get(_stations_nearby_list[i]);
    02224       SetDParam(0, st->index);
    02225       SetDParam(1, st->facilities);
    02226       d = maxdim(d, GetStringBoundingBox(T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_STATION_LIST_WAYPOINT : STR_STATION_LIST_STATION));
    02227     }
    02228
    02229     resize->height = d.height;
    02230     d.height *= 5;
    02231     d.width += WD_FRAMERECT_RIGHT + WD_FRAMERECT_LEFT;
    02232     d.height += WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
    02233     *size = d;
    02234   }
    02235
    02236   virtual void DrawWidget(const Rect &r, int widget) const
    02237   {
    02238     if (widget != WID_JS_PANEL) return;
    02239
    02240     uint y = r.top + WD_FRAMERECT_TOP;
    02241     if (this->vscroll->GetPosition() == 0) {
    02242       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);
    02243       y += this->resize.step_height;
    02244     }
    02245
    02246     for (uint i = max<uint>(1, this->vscroll->GetPosition()); i <= _stations_nearby_list.Length(); ++i, y += this->resize.step_height) {
    02247       /* Don't draw anything if it extends past the end of the window. */
    02248       if (i - this->vscroll->GetPosition() >= this->vscroll->GetCapacity()) break;
    02249
    02250       const T *st = T::Get(_stations_nearby_list[i - 1]);
    02251       SetDParam(0, st->index);
    02252       SetDParam(1, st->facilities);
    02253       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);
    02254     }
    02255   }
    02256
    02257   virtual void OnClick(Point pt, int widget, int click_count)
    02258   {
    02259     if (widget != WID_JS_PANEL) return;
    02260
    02261     uint st_index = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_JS_PANEL, WD_FRAMERECT_TOP);
    02262     bool distant_join = (st_index > 0);
    02263     if (distant_join) st_index--;
    02264
    02265     if (distant_join && st_index >= _stations_nearby_list.Length()) return;
    02266
    02267     /* Insert station to be joined into stored command */
    02268     SB(this->select_station_cmd.p2, 16, 16,
    02269        (distant_join ? _stations_nearby_list[st_index] : NEW_STATION));
    02270
    02271     /* Execute stored Command */
    02272     DoCommandP(&this->select_station_cmd);
    02273
    02274     /* Close Window; this might cause double frees! */
    02275     DeleteWindowById(WC_SELECT_STATION, 0);
    02276   }
    02277
    02278   virtual void OnTick()
    02279   {
    02280     if (_thd.dirty & 2) {
    02281       _thd.dirty &= ~2;
    02282       this->SetDirty();
    02283     }
    02284   }
    02285
    02286   virtual void OnResize()
    02287   {
    02288     this->vscroll->SetCapacityFromWidget(this, WID_JS_PANEL, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
    02289   }
    02290
    02296   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
    02297   {
    02298     if (!gui_scope) return;
    02299     FindStationsNearby<T>(this->area, true);
    02300     this->vscroll->SetCount(_stations_nearby_list.Length() + 1);
    02301     this->SetDirty();
    02302   }
    02303 };
    02304
    02305 static const WindowDesc _select_station_desc(
    02306   WDP_AUTO, 200, 180,
    02307   WC_SELECT_STATION, WC_NONE,
    02308   WDF_CONSTRUCTION,
    02309   _nested_select_station_widgets, lengthof(_nested_select_station_widgets)
    02310 );
    02311
    02312
    02320 template <class T>
    02321 static bool StationJoinerNeeded(CommandContainer cmd, TileArea ta)
    02322 {
    02323   /* Only show selection if distant join is enabled in the settings */
    02324   if (!_settings_game.station.distant_join_stations) return false;
    02325
    02326   /* If a window is already opened and we didn't ctrl-click,
    02327    * return true (i.e. just flash the old window) */
    02328   Window *selection_window = FindWindowById(WC_SELECT_STATION, 0);
    02329   if (selection_window != NULL) {
    02330     /* Abort current distant-join and start new one */
    02331     delete selection_window;
    02332     UpdateTileSelection();
    02333   }
    02334
    02335   /* only show the popup, if we press ctrl */
    02336   if (!_ctrl_pressed) return false;
    02337
    02338   /* Now check if we could build there */
    02339   if (DoCommand(&cmd, CommandFlagsToDCFlags(GetCommandFlags(cmd.cmd))).Failed()) return false;
    02340
    02341   /* Test for adjacent station or station below selection.
    02342    * If adjacent-stations is disabled and we are building next to a station, do not show the selection window.
    02343    * but join the other station immediately. */
    02344   const T *st = FindStationsNearby<T>(ta, false);
    02345   return st == NULL && (_settings_game.station.adjacent_stations || _stations_nearby_list.Length() == 0);
    02346 }
    02347
    02354 template <class T>
    02355 void ShowSelectBaseStationIfNeeded(CommandContainer cmd, TileArea ta)
    02356 {
    02357   if (StationJoinerNeeded<T>(cmd, ta)) {
    02358     if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
    02359     new SelectStationWindow<T>(&_select_station_desc, cmd, ta);
    02360   } else {
    02361     DoCommandP(&cmd);
    02362   }
    02363 }
    02364
    02370 void ShowSelectStationIfNeeded(CommandContainer cmd, TileArea ta)
    02371 {
    02372   ShowSelectBaseStationIfNeeded<Station>(cmd, ta);
    02373 }
    02374
    02380 void ShowSelectWaypointIfNeeded(CommandContainer cmd, TileArea ta)
    02381 {
    02382   ShowSelectBaseStationIfNeeded<Waypoint>(cmd, ta);
    02383 }