# station_gui.cpp

Go to the documentation of this file.

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