# 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->SetTimeout();
    00541         this->LowerWidget(WID_STL_SORTBY);
    00542         this->SetDirty();
    00543         break;
    00544
    00545       case WID_STL_SORTDROPBTN: // select sorting criteria dropdown menu
    00546         ShowDropDownMenu(this, this->sorter_names, this->stations.SortType(), WID_STL_SORTDROPBTN, 0, 0);
    00547         break;
    00548
    00549       case WID_STL_NOCARGOWAITING:
    00550         if (_ctrl_pressed) {
    00551           this->include_empty = !this->include_empty;
    00552           this->ToggleWidgetLoweredState(WID_STL_NOCARGOWAITING);
    00553         } else {
    00554           for (uint i = 0; i < _sorted_standard_cargo_specs_size; i++) {
    00555             this->RaiseWidget(WID_STL_CARGOSTART + i);
    00556           }
    00557
    00558           this->cargo_filter = 0;
    00559           this->include_empty = true;
    00560
    00561           this->LowerWidget(WID_STL_NOCARGOWAITING);
    00562         }
    00563         this->stations.ForceRebuild();
    00564         this->SetDirty();
    00565         break;
    00566
    00567       default:
    00568         if (widget >= WID_STL_CARGOSTART) { // change cargo_filter
    00569           /* Determine the selected cargo type */
    00570           const CargoSpec *cs = _sorted_cargo_specs[widget - WID_STL_CARGOSTART];
    00571
    00572           if (_ctrl_pressed) {
    00573             ToggleBit(this->cargo_filter, cs->Index());
    00574             this->ToggleWidgetLoweredState(widget);
    00575           } else {
    00576             for (uint i = 0; i < _sorted_standard_cargo_specs_size; i++) {
    00577               this->RaiseWidget(WID_STL_CARGOSTART + i);
    00578             }
    00579             this->RaiseWidget(WID_STL_NOCARGOWAITING);
    00580
    00581             this->cargo_filter = 0;
    00582             this->include_empty = false;
    00583
    00584             SetBit(this->cargo_filter, cs->Index());
    00585             this->LowerWidget(widget);
    00586           }
    00587           this->stations.ForceRebuild();
    00588           this->SetDirty();
    00589         }
    00590         break;
    00591     }
    00592   }
    00593
    00594   virtual void OnDropdownSelect(int widget, int index)
    00595   {
    00596     if (this->stations.SortType() != index) {
    00597       this->stations.SetSortType(index);
    00598
    00599       /* Display the current sort variant */
    00600       this->GetWidget<NWidgetCore>(WID_STL_SORTDROPBTN)->widget_data = this->sorter_names[this->stations.SortType()];
    00601
    00602       this->SetDirty();
    00603     }
    00604   }
    00605
    00606   virtual void OnTick()
    00607   {
    00608     if (_pause_mode != PM_UNPAUSED) return;
    00609     if (this->stations.NeedResort()) {
    00610       DEBUG(misc, 3, "Periodic rebuild station list company %d", this->window_number);
    00611       this->SetDirty();
    00612     }
    00613   }
    00614
    00615   virtual void OnTimeout()
    00616   {
    00617     this->RaiseWidget(WID_STL_SORTBY);
    00618     this->SetDirty();
    00619   }
    00620
    00621   virtual void OnResize()
    00622   {
    00623     this->vscroll->SetCapacityFromWidget(this, WID_STL_LIST, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
    00624   }
    00625
    00631   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
    00632   {
    00633     if (data == 0) {
    00634       /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
    00635       this->stations.ForceRebuild();
    00636     } else {
    00637       this->stations.ForceResort();
    00638     }
    00639   }
    00640 };
    00641
    00642 Listing CompanyStationsWindow::last_sorting = {false, 0};
    00643 byte CompanyStationsWindow::facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK;
    00644 bool CompanyStationsWindow::include_empty = true;
    00645 const uint32 CompanyStationsWindow::cargo_filter_max = UINT32_MAX;
    00646 uint32 CompanyStationsWindow::cargo_filter = UINT32_MAX;
    00647 const Station *CompanyStationsWindow::last_station = NULL;
    00648
    00649 /* Availible station sorting functions */
    00650 GUIStationList::SortFunction * const CompanyStationsWindow::sorter_funcs[] = {
    00651   &StationNameSorter,
    00652   &StationTypeSorter,
    00653   &StationWaitingSorter,
    00654   &StationRatingMaxSorter,
    00655   &StationRatingMinSorter
    00656 };
    00657
    00658 /* Names of the sorting functions */
    00659 const StringID CompanyStationsWindow::sorter_names[] = {
    00660   STR_SORT_BY_NAME,
    00661   STR_SORT_BY_FACILITY,
    00662   STR_SORT_BY_WAITING,
    00663   STR_SORT_BY_RATING_MAX,
    00664   STR_SORT_BY_RATING_MIN,
    00665   INVALID_STRING_ID
    00666 };
    00667
    00673 static NWidgetBase *CargoWidgets(int *biggest_index)
    00674 {
    00675   NWidgetHorizontal *container = new NWidgetHorizontal();
    00676
    00677   for (uint i = 0; i < _sorted_standard_cargo_specs_size; i++) {
    00678     NWidgetBackground *panel = new NWidgetBackground(WWT_PANEL, COLOUR_GREY, WID_STL_CARGOSTART + i);
    00679     panel->SetMinimalSize(14, 11);
    00680     panel->SetResize(0, 0);
    00681     panel->SetFill(0, 1);
    00682     panel->SetDataTip(0, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE);
    00683     container->Add(panel);
    00684   }
    00685   *biggest_index = WID_STL_CARGOSTART + _sorted_standard_cargo_specs_size;
    00686   return container;
    00687 }
    00688
    00689 static const NWidgetPart _nested_company_stations_widgets[] = {
    00690   NWidget(NWID_HORIZONTAL),
    00691     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
    00692     NWidget(WWT_CAPTION, COLOUR_GREY, WID_STL_CAPTION), SetDataTip(STR_STATION_LIST_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
    00693     NWidget(WWT_SHADEBOX, COLOUR_GREY),
    00694     NWidget(WWT_STICKYBOX, COLOUR_GREY),
    00695   EndContainer(),
    00696   NWidget(NWID_HORIZONTAL),
    00697     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),
    00698     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),
    00699     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),
    00700     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),
    00701     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),
    00702     NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_STL_FACILALL), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_SELECT_ALL_FACILITIES), SetFill(0, 1),
    00703     NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(5, 11), SetFill(0, 1), EndContainer(),
    00704     NWidgetFunction(CargoWidgets),
    00705     NWidget(WWT_PANEL, COLOUR_GREY, WID_STL_NOCARGOWAITING), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_NO_WAITING_CARGO), SetFill(0, 1), EndContainer(),
    00706     NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_STL_CARGOALL), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_SELECT_ALL_TYPES), SetFill(0, 1),
    00707     NWidget(WWT_PANEL, COLOUR_GREY), SetDataTip(0x0, STR_NULL), SetResize(1, 0), SetFill(1, 1), EndContainer(),
    00708   EndContainer(),
    00709   NWidget(NWID_HORIZONTAL),
    00710     NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_STL_SORTBY), SetMinimalSize(81, 12), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
    00711     NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_STL_SORTDROPBTN), SetMinimalSize(163, 12), SetDataTip(STR_SORT_BY_NAME, STR_TOOLTIP_SORT_CRITERIA), // widget_data gets overwritten.
    00712     NWidget(WWT_PANEL, COLOUR_GREY), SetDataTip(0x0, STR_NULL), SetResize(1, 0), SetFill(1, 1), EndContainer(),
    00713   EndContainer(),
    00714   NWidget(NWID_HORIZONTAL),
    00715     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(),
    00716     NWidget(NWID_VERTICAL),
    00717       NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_STL_SCROLLBAR),
    00718       NWidget(WWT_RESIZEBOX, COLOUR_GREY),
    00719     EndContainer(),
    00720   EndContainer(),
    00721 };
    00722
    00723 static const WindowDesc _company_stations_desc(
    00724   WDP_AUTO, 358, 162,
    00725   WC_STATION_LIST, WC_NONE,
    00726   WDF_UNCLICK_BUTTONS,
    00727   _nested_company_stations_widgets, lengthof(_nested_company_stations_widgets)
    00728 );
    00729
    00735 void ShowCompanyStations(CompanyID company)
    00736 {
    00737   if (!Company::IsValidID(company)) return;
    00738
    00739   AllocateWindowDescFront<CompanyStationsWindow>(&_company_stations_desc, company);
    00740 }
    00741
    00742 static const NWidgetPart _nested_station_view_widgets[] = {
    00743   NWidget(NWID_HORIZONTAL),
    00744     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
    00745     NWidget(WWT_CAPTION, COLOUR_GREY, WID_SV_CAPTION), SetDataTip(STR_STATION_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
    00746     NWidget(WWT_SHADEBOX, COLOUR_GREY),
    00747     NWidget(WWT_STICKYBOX, COLOUR_GREY),
    00748   EndContainer(),
    00749   NWidget(NWID_HORIZONTAL),
    00750     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_SORT_ORDER), SetMinimalSize(81, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
    00751     NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_SV_SORT_BY), SetMinimalSize(168, 12), SetResize(1, 0), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
    00752   EndContainer(),
    00753   NWidget(NWID_HORIZONTAL),
    00754     NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_SV_GROUP), SetMinimalSize(81, 12), SetFill(1, 1), SetDataTip(STR_STATION_VIEW_GROUP, 0x0),
    00755     NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_SV_GROUP_BY), SetMinimalSize(168, 12), SetResize(1, 0), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_GROUP_ORDER),
    00756   EndContainer(),
    00757   NWidget(NWID_HORIZONTAL),
    00758     NWidget(WWT_PANEL, COLOUR_GREY, WID_SV_WAITING), SetMinimalSize(237, 44), SetResize(1, 10), SetScrollbar(WID_SV_SCROLLBAR), EndContainer(),
    00759     NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_SV_SCROLLBAR),
    00760   EndContainer(),
    00761   NWidget(WWT_PANEL, COLOUR_GREY, WID_SV_ACCEPT_RATING_LIST), SetMinimalSize(249, 23), SetResize(1, 0), EndContainer(),
    00762   NWidget(NWID_HORIZONTAL),
    00763     NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
    00764       NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_LOCATION), SetMinimalSize(45, 12), SetResize(1, 0), SetFill(1, 1),
    00765           SetDataTip(STR_BUTTON_LOCATION, STR_STATION_VIEW_CENTER_TOOLTIP),
    00766       NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_ACCEPTS_RATINGS), SetMinimalSize(46, 12), SetResize(1, 0), SetFill(1, 1),
    00767           SetDataTip(STR_STATION_VIEW_RATINGS_BUTTON, STR_STATION_VIEW_RATINGS_TOOLTIP),
    00768       NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_RENAME), SetMinimalSize(45, 12), SetResize(1, 0), SetFill(1, 1),
    00769           SetDataTip(STR_BUTTON_RENAME, STR_STATION_VIEW_RENAME_TOOLTIP),
    00770     EndContainer(),
    00771     NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_SV_CLOSE_AIRPORT), SetMinimalSize(45, 12), SetResize(1, 0), SetFill(1, 1),
    00772         SetDataTip(STR_STATION_VIEW_CLOSE_AIRPORT, STR_STATION_VIEW_CLOSE_AIRPORT_TOOLTIP),
    00773     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_TRAINS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_TRAIN, STR_STATION_VIEW_SCHEDULED_TRAINS_TOOLTIP),
    00774     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_ROADVEHS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_LORRY, STR_STATION_VIEW_SCHEDULED_ROAD_VEHICLES_TOOLTIP),
    00775     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_SHIPS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_SHIP, STR_STATION_VIEW_SCHEDULED_SHIPS_TOOLTIP),
    00776     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_PLANES),  SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_PLANE, STR_STATION_VIEW_SCHEDULED_AIRCRAFT_TOOLTIP),
    00777     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
    00778   EndContainer(),
    00779 };
    00780
    00791 static void DrawCargoIcons(CargoID i, uint waiting, int left, int right, int y)
    00792 {
    00793   uint num = min((waiting + 5) / 10, (right - left) / 10); // maximum is width / 10 icons so it won't overflow
    00794   if (num == 0) return;
    00795
    00796   SpriteID sprite = CargoSpec::Get(i)->GetCargoIcon();
    00797
    00798   int x = _current_text_dir == TD_RTL ? left : right - num * 10;
    00799   do {
    00800     DrawSprite(sprite, PAL_NONE, x, y);
    00801     x += 10;
    00802   } while (--num);
    00803 }
    00804
    00805 CargoDataEntry::CargoDataEntry() :
    00806   parent(NULL),
    00807   station(INVALID_STATION),
    00808   num_children(0),
    00809   count(0),
    00810   children(new CargoDataSet(CargoSorter(ST_CARGO_ID)))
    00811 {}
    00812
    00813 CargoDataEntry::CargoDataEntry(CargoID cargo, uint count, CargoDataEntry *parent) :
    00814   parent(parent),
    00815   cargo(cargo),
    00816   num_children(0),
    00817   count(count),
    00818   children(new CargoDataSet)
    00819 {}
    00820
    00821 CargoDataEntry::CargoDataEntry(StationID station, uint count, CargoDataEntry *parent) :
    00822   parent(parent),
    00823   station(station),
    00824   num_children(0),
    00825   count(count),
    00826   children(new CargoDataSet)
    00827 {}
    00828
    00829 CargoDataEntry::CargoDataEntry(StationID station) :
    00830   parent(NULL),
    00831   station(station),
    00832   num_children(0),
    00833   count(0),
    00834   children(NULL)
    00835 {}
    00836
    00837 CargoDataEntry::CargoDataEntry(CargoID cargo) :
    00838   parent(NULL),
    00839   cargo(cargo),
    00840   num_children(0),
    00841   count(0),
    00842   children(NULL)
    00843 {}
    00844
    00845 CargoDataEntry::~CargoDataEntry()
    00846 {
    00847   this->Clear();
    00848   delete this->children;
    00849 }
    00850
    00854 void CargoDataEntry::Clear()
    00855 {
    00856   if (this->children != NULL) {
    00857     for (CargoDataSet::iterator i = this->children->begin(); i != this->children->end(); ++i) {
    00858       assert(*i != this);
    00859       delete *i;
    00860     }
    00861     this->children->clear();
    00862   }
    00863   if (this->parent != NULL) this->parent->count -= this->count;
    00864   this->count = 0;
    00865   this->num_children = 0;
    00866 }
    00867
    00874 void CargoDataEntry::Remove(CargoDataEntry *child)
    00875 {
    00876   CargoDataSet::iterator i = this->children->find(child);
    00877   if (i != this->children->end()) {
    00878     delete *i;
    00879     this->children->erase(i);
    00880   }
    00881 }
    00882
    00889 template<class ID>
    00890 CargoDataEntry *CargoDataEntry::InsertOrRetrieve(ID child_id)
    00891 {
    00892   CargoDataEntry tmp(child_id);
    00893   CargoDataSet::iterator i = this->children->find(&tmp);
    00894   if (i == this->children->end()) {
    00895     IncrementSize();
    00896     return *(this->children->insert(new CargoDataEntry(child_id, 0, this)).first);
    00897   } else {
    00898     CargoDataEntry *ret = *i;
    00899     assert(this->children->value_comp().GetSortType() != ST_COUNT);
    00900     return ret;
    00901   }
    00902 }
    00903
    00909 void CargoDataEntry::Update(uint count)
    00910 {
    00911   this->count += count;
    00912   if (this->parent != NULL) this->parent->Update(count);
    00913 }
    00914
    00918 void CargoDataEntry::IncrementSize()
    00919 {
    00920    ++this->num_children;
    00921    if (this->parent != NULL) this->parent->IncrementSize();
    00922 }
    00923
    00924 void CargoDataEntry::Resort(CargoSortType type, SortOrder order)
    00925 {
    00926   CargoDataSet *new_subs = new CargoDataSet(this->children->begin(), this->children->end(), CargoSorter(type, order));
    00927   delete this->children;
    00928   this->children = new_subs;
    00929 }
    00930
    00931 CargoDataEntry *CargoDataEntry::Retrieve(CargoDataSet::iterator i) const
    00932 {
    00933   if (i == this->children->end()) {
    00934     return NULL;
    00935   } else {
    00936     assert(this->children->value_comp().GetSortType() != ST_COUNT);
    00937     return *i;
    00938   }
    00939 }
    00940
    00941 bool CargoSorter::operator()(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const
    00942 {
    00943   switch (this->type) {
    00944     case ST_STATION_ID:
    00945       return this->SortId<StationID>(cd1->GetStation(), cd2->GetStation());
    00946       break;
    00947     case ST_CARGO_ID:
    00948       return this->SortId<CargoID>(cd1->GetCargo(), cd2->GetCargo());
    00949       break;
    00950     case ST_COUNT:
    00951       return this->SortCount(cd1, cd2);
    00952       break;
    00953     case ST_STATION_STRING:
    00954       return this->SortStation(cd1->GetStation(), cd2->GetStation());
    00955       break;
    00956     default:
    00957       NOT_REACHED();
    00958   }
    00959 }
    00960
    00961 template<class ID>
    00962 bool CargoSorter::SortId(ID st1, ID st2) const
    00963 {
    00964   return (this->order == SO_ASCENDING) ? st1 < st2 : st2 < st1;
    00965 }
    00966
    00967 bool CargoSorter::SortCount(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const
    00968 {
    00969   uint c1 = cd1->GetCount();
    00970   uint c2 = cd2->GetCount();
    00971   if (c1 == c2) {
    00972     return this->SortStation(cd1->GetStation(), cd2->GetStation());
    00973   } else if (this->order == SO_ASCENDING) {
    00974     return c1 < c2;
    00975   } else {
    00976     return c2 < c1;
    00977   }
    00978 }
    00979
    00980 bool CargoSorter::SortStation(StationID st1, StationID st2) const
    00981 {
    00982   static char buf1[MAX_LENGTH_STATION_NAME_CHARS];
    00983   static char buf2[MAX_LENGTH_STATION_NAME_CHARS];
    00984
    00985   if (!Station::IsValidID(st1)) {
    00986     return Station::IsValidID(st2) ? this->order == SO_ASCENDING : this->SortId(st1, st2);
    00987   } else if (!Station::IsValidID(st2)) {
    00988     return order == SO_DESCENDING;
    00989   }
    00990
    00991   SetDParam(0, st1);
    00992   GetString(buf1, STR_STATION_NAME, lastof(buf1));
    00993   SetDParam(0, st2);
    00994   GetString(buf2, STR_STATION_NAME, lastof(buf2));
    00995
    00996   int res = strcmp(buf1, buf2);
    00997   if (res == 0) {
    00998     return this->SortId(st1, st2);
    00999   } else {
    01000     return (this->order == SO_ASCENDING) ? res < 0 : res > 0;
    01001   }
    01002 }
    01003
    01007 struct StationViewWindow : public Window {
    01011   struct RowDisplay {
    01012     RowDisplay(CargoDataEntry *f, StationID n) : filter(f), next_station(n) {}
    01013     RowDisplay(CargoDataEntry *f, CargoID n) : filter(f), next_cargo(n) {}
    01014
    01018     CargoDataEntry *filter;
    01019     union {
    01023       StationID next_station;
    01024
    01028       CargoID next_cargo;
    01029     };
    01030   };
    01031
    01032   typedef std::vector<RowDisplay> CargoDataVector;
    01033
    01034   static const int NUM_COLUMNS = 4;
    01035
    01039   enum Invalidation {
    01040     INV_FLOWS = 0x100,
    01041     INV_CARGO = 0x200
    01042   };
    01043
    01047   enum Grouping {
    01048     GR_SOURCE,
    01049     GR_NEXT,
    01050     GR_DESTINATION,
    01051     GR_CARGO,
    01052   };
    01053
    01057   enum Mode {
    01058     MODE_WAITING,
    01059     MODE_PLANNED
    01060   };
    01061
    01062   uint expand_shrink_width;
    01063   int rating_lines;
    01064   int accepts_lines;
    01065   Scrollbar *vscroll;
    01066
    01068   enum AcceptListHeight {
    01069     ALH_RATING  = 13,
    01070     ALH_ACCEPTS = 3,
    01071   };
    01072
    01073   static const StringID _sort_names[];
    01074   static const StringID _group_names[];
    01075
    01082   CargoSortType sortings[NUM_COLUMNS];
    01083
    01085   SortOrder sort_orders[NUM_COLUMNS];
    01086
    01087   int scroll_to_row;
    01088   int grouping_index;
    01089   Mode current_mode;
    01090   Grouping groupings[NUM_COLUMNS];
    01091
    01092   CargoDataEntry expanded_rows;
    01093   CargoDataEntry cached_destinations;
    01094   CargoDataVector displayed_rows;
    01095
    01096   StationViewWindow(const WindowDesc *desc, WindowNumber window_number) : Window(),
    01097     scroll_to_row(INT_MAX), grouping_index(0)
    01098   {
    01099     this->rating_lines  = ALH_RATING;
    01100     this->accepts_lines = ALH_ACCEPTS;
    01101
    01102     this->CreateNestedTree(desc);
    01103     this->vscroll = this->GetScrollbar(WID_SV_SCROLLBAR);
    01104     /* Nested widget tree creation is done in two steps to ensure that this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS) exists in UpdateWidgetSize(). */
    01105     this->FinishInitNested(desc, window_number);
    01106
    01107     this->groupings[0] = GR_CARGO;
    01108     this->sortings[0] = ST_AS_GROUPING;
    01109     this->SelectGroupBy(_settings_client.gui.station_gui_group_order);
    01110     this->SelectSortBy(_settings_client.gui.station_gui_sort_by);
    01111     this->sort_orders[0] = SO_ASCENDING;
    01112     this->SelectSortOrder((SortOrder)_settings_client.gui.station_gui_sort_order);
    01113     Owner owner = Station::Get(window_number)->owner;
    01114     if (owner != OWNER_NONE) this->owner = owner;
    01115   }
    01116
    01117   ~StationViewWindow()
    01118   {
    01119     Owner owner = Station::Get(this->window_number)->owner;
    01120     DeleteWindowById(WC_TRAINS_LIST,   VehicleListIdentifier(VL_STATION_LIST, VEH_TRAIN,    owner, this->window_number).Pack(), false);
    01121     DeleteWindowById(WC_ROADVEH_LIST,  VehicleListIdentifier(VL_STATION_LIST, VEH_ROAD,     owner, this->window_number).Pack(), false);
    01122     DeleteWindowById(WC_SHIPS_LIST,    VehicleListIdentifier(VL_STATION_LIST, VEH_SHIP,     owner, this->window_number).Pack(), false);
    01123     DeleteWindowById(WC_AIRCRAFT_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_AIRCRAFT, owner, this->window_number).Pack(), false);
    01124   }
    01125
    01136   void ShowCargo(CargoDataEntry *data, CargoID cargo, StationID source, StationID next, StationID dest, uint count)
    01137   {
    01138     if (count == 0) return;
    01139     const CargoDataEntry *expand = &this->expanded_rows;
    01140     for (int i = 0; i < NUM_COLUMNS && expand != NULL; ++i) {
    01141       switch (groupings[i]) {
    01142         case GR_CARGO:
    01143           assert(i == 0);
    01144           data = data->InsertOrRetrieve(cargo);
    01145           expand = expand->Retrieve(cargo);
    01146           break;
    01147         case GR_SOURCE:
    01148           data = data->InsertOrRetrieve(source);
    01149           expand = expand->Retrieve(source);
    01150           break;
    01151         case GR_NEXT:
    01152           data = data->InsertOrRetrieve(next);
    01153           expand = expand->Retrieve(next);
    01154           break;
    01155         case GR_DESTINATION:
    01156           data = data->InsertOrRetrieve(dest);
    01157           expand = expand->Retrieve(dest);
    01158           break;
    01159       }
    01160     }
    01161     data->Update(count);
    01162   }
    01163
    01164   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    01165   {
    01166     switch (widget) {
    01167       case WID_SV_WAITING:
    01168         resize->height = FONT_HEIGHT_NORMAL;
    01169         size->height = WD_FRAMERECT_TOP + 4 * resize->height + WD_FRAMERECT_BOTTOM;
    01170         this->expand_shrink_width = max(GetStringBoundingBox("-").width, GetStringBoundingBox("+").width) + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
    01171         break;
    01172
    01173       case WID_SV_ACCEPT_RATING_LIST:
    01174         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;
    01175         break;
    01176
    01177       case WID_SV_CLOSE_AIRPORT:
    01178         if (!(Station::Get(this->window_number)->facilities & FACIL_AIRPORT)) {
    01179           /* Hide 'Close Airport' button if no airport present. */
    01180           size->width = 0;
    01181           resize->width = 0;
    01182           fill->width = 0;
    01183         }
    01184         break;
    01185     }
    01186   }
    01187
    01188   virtual void OnPaint()
    01189   {
    01190     const Station *st = Station::Get(this->window_number);
    01191     CargoDataEntry cargo;
    01192     BuildCargoList(&cargo, st);
    01193
    01194     this->vscroll->SetCount(cargo.GetNumChildren()); // update scrollbar
    01195
    01196     /* disable some buttons */
    01197     this->SetWidgetDisabledState(WID_SV_RENAME,   st->owner != _local_company);
    01198     this->SetWidgetDisabledState(WID_SV_TRAINS,   !(st->facilities & FACIL_TRAIN));
    01199     this->SetWidgetDisabledState(WID_SV_ROADVEHS, !(st->facilities & FACIL_TRUCK_STOP) && !(st->facilities & FACIL_BUS_STOP));
    01200     this->SetWidgetDisabledState(WID_SV_SHIPS,    !(st->facilities & FACIL_DOCK));
    01201     this->SetWidgetDisabledState(WID_SV_PLANES,   !(st->facilities & FACIL_AIRPORT));
    01202     this->SetWidgetDisabledState(WID_SV_CLOSE_AIRPORT, !(st->facilities & FACIL_AIRPORT) || st->owner != _local_company);
    01203     this->SetWidgetLoweredState(WID_SV_CLOSE_AIRPORT, (st->facilities & FACIL_AIRPORT) && (st->airport.flags & AIRPORT_CLOSED_block) != 0);
    01204
    01205     SetDParam(0, st->index);
    01206     SetDParam(1, st->facilities);
    01207     this->DrawWidgets();
    01208
    01209     if (!this->IsShaded()) {
    01210       /* Draw 'accepted cargo' or 'cargo ratings'. */
    01211       const NWidgetBase *wid = this->GetWidget<NWidgetBase>(WID_SV_ACCEPT_RATING_LIST);
    01212       const Rect r = {wid->pos_x, wid->pos_y, wid->pos_x + wid->current_x - 1, wid->pos_y + wid->current_y - 1};
    01213       if (this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) {
    01214         int lines = this->DrawAcceptedCargo(r);
    01215         if (lines > this->accepts_lines) { // Resize the widget, and perform re-initialization of the window.
    01216           this->accepts_lines = lines;
    01217           this->ReInit();
    01218           return;
    01219         }
    01220       } else {
    01221         int lines = this->DrawCargoRatings(r);
    01222         if (lines > this->rating_lines) { // Resize the widget, and perform re-initialization of the window.
    01223           this->rating_lines = lines;
    01224           this->ReInit();
    01225           return;
    01226         }
    01227       }
    01228
    01229       /* draw arrow pointing up/down for ascending/descending sorting */
    01230       this->DrawSortButtonState(WID_SV_SORT_ORDER, sort_orders[1] == SO_ASCENDING ? SBS_UP : SBS_DOWN);
    01231
    01232       int pos = this->vscroll->GetPosition();
    01233
    01234       int maxrows = this->vscroll->GetCapacity();
    01235
    01236       displayed_rows.clear();
    01237
    01238       /* Draw waiting cargo. */
    01239       NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_SV_WAITING);
    01240       Rect waiting_rect = {nwi->pos_x, nwi->pos_y, nwi->pos_x + nwi->current_x - 1, nwi->pos_y + nwi->current_y - 1};
    01241       this->DrawEntries(&cargo, waiting_rect, pos, maxrows, 0);
    01242       scroll_to_row = INT_MAX;
    01243     }
    01244   }
    01245
    01246   virtual void SetStringParameters(int widget) const
    01247   {
    01248     if (widget == WID_SV_CAPTION) {
    01249       const Station *st = Station::Get(this->window_number);
    01250       SetDParam(0, st->index);
    01251       SetDParam(1, st->facilities);
    01252     }
    01253   }
    01254
    01260   void RecalcDestinations(CargoID i)
    01261   {
    01262     const Station *st = Station::Get(this->window_number);
    01263     CargoDataEntry *cargo_entry = cached_destinations.InsertOrRetrieve(i);
    01264     cargo_entry->Clear();
    01265
    01266     const FlowStatMap &flows = st->goods[i].flows;
    01267     for (FlowStatMap::const_iterator it = flows.begin(); it != flows.end(); ++it) {
    01268       StationID from = it->first;
    01269       CargoDataEntry *source_entry = cargo_entry->InsertOrRetrieve(from);
    01270       const FlowStat::SharesMap *shares = it->second.GetShares();
    01271       uint32 prev_count = 0;
    01272       for (FlowStat::SharesMap::const_iterator flow_it = shares->begin(); flow_it != shares->end(); ++flow_it) {
    01273         StationID via = flow_it->second;
    01274         CargoDataEntry *via_entry = source_entry->InsertOrRetrieve(via);
    01275         if (via == this->window_number) {
    01276           via_entry->InsertOrRetrieve(via)->Update(flow_it->first - prev_count);
    01277         } else {
    01278           EstimateDestinations(i, from, via, flow_it->first - prev_count, via_entry);
    01279         }
    01280         prev_count = flow_it->first;
    01281       }
    01282     }
    01283   }
    01284
    01294   void EstimateDestinations(CargoID cargo, StationID source, StationID next, uint count, CargoDataEntry *dest)
    01295   {
    01296     if (Station::IsValidID(next) && Station::IsValidID(source)) {
    01297       CargoDataEntry tmp;
    01298       const FlowStatMap &flowmap = Station::Get(next)->goods[cargo].flows;
    01299       FlowStatMap::const_iterator map_it = flowmap.find(source);
    01300       if (map_it != flowmap.end()) {
    01301         const FlowStat::SharesMap *shares = map_it->second.GetShares();
    01302         uint32 prev_count = 0;
    01303         for (FlowStat::SharesMap::const_iterator i = shares->begin(); i != shares->end(); ++i) {
    01304           tmp.InsertOrRetrieve(i->second)->Update(i->first - prev_count);
    01305           prev_count = i->first;
    01306         }
    01307       }
    01308
    01309       if (tmp.GetCount() == 0) {
    01310         dest->InsertOrRetrieve(INVALID_STATION)->Update(count);
    01311       } else {
    01312         uint sum_estimated = 0;
    01313         while (sum_estimated < count) {
    01314           for (CargoDataSet::iterator i = tmp.Begin(); i != tmp.End() && sum_estimated < count; ++i) {
    01315             CargoDataEntry *child = *i;
    01316             uint estimate = DivideApprox(child->GetCount() * count, tmp.GetCount());
    01317             if (estimate == 0) estimate = 1;
    01318
    01319             sum_estimated += estimate;
    01320             if (sum_estimated > count) {
    01321               estimate -= sum_estimated - count;
    01322               sum_estimated = count;
    01323             }
    01324
    01325             if (estimate > 0) {
    01326               if (child->GetStation() == next) {
    01327                 dest->InsertOrRetrieve(next)->Update(estimate);
    01328               } else {
    01329                 EstimateDestinations(cargo, source, child->GetStation(), estimate, dest);
    01330               }
    01331             }
    01332           }
    01333
    01334         }
    01335       }
    01336     } else {
    01337       dest->InsertOrRetrieve(INVALID_STATION)->Update(count);
    01338     }
    01339   }
    01340
    01347   void BuildFlowList(CargoID i, const FlowStatMap &flows, CargoDataEntry *cargo)
    01348   {
    01349     const CargoDataEntry *source_dest = this->cached_destinations.Retrieve(i);
    01350     for (FlowStatMap::const_iterator it = flows.begin(); it != flows.end(); ++it) {
    01351       StationID from = it->first;
    01352       const CargoDataEntry *source_entry = source_dest->Retrieve(from);
    01353       const FlowStat::SharesMap *shares = it->second.GetShares();
    01354       for (FlowStat::SharesMap::const_iterator flow_it = shares->begin(); flow_it != shares->end(); ++flow_it) {
    01355         const CargoDataEntry *via_entry = source_entry->Retrieve(flow_it->second);
    01356         for (CargoDataSet::iterator dest_it = via_entry->Begin(); dest_it != via_entry->End(); ++dest_it) {
    01357           CargoDataEntry *dest_entry = *dest_it;
    01358           ShowCargo(cargo, i, from, flow_it->second, dest_entry->GetStation(), dest_entry->GetCount());
    01359         }
    01360       }
    01361     }
    01362   }
    01363
    01370   void BuildCargoList(CargoID i, const StationCargoList &packets, CargoDataEntry *cargo)
    01371   {
    01372     const CargoDataEntry *source_dest = this->cached_destinations.Retrieve(i);
    01373     for (StationCargoList::ConstIterator it = packets.Packets()->begin(); it != packets.Packets()->end(); it++) {
    01374       const CargoPacket *cp = *it;
    01375       StationID next = it.GetKey();
    01376
    01377       const CargoDataEntry *source_entry = source_dest->Retrieve(cp->SourceStation());
    01378       if (source_entry == NULL) {
    01379         ShowCargo(cargo, i, cp->SourceStation(), next, INVALID_STATION, cp->Count());
    01380         continue;
    01381       }
    01382
    01383       const CargoDataEntry *via_entry = source_entry->Retrieve(next);
    01384       if (via_entry == NULL) {
    01385         ShowCargo(cargo, i, cp->SourceStation(), next, INVALID_STATION, cp->Count());
    01386         continue;
    01387       }
    01388
    01389       for (CargoDataSet::iterator dest_it = via_entry->Begin(); dest_it != via_entry->End(); ++dest_it) {
    01390         CargoDataEntry *dest_entry = *dest_it;
    01391         uint val = DivideApprox(cp->Count() * dest_entry->GetCount(), via_entry->GetCount());
    01392         ShowCargo(cargo, i, cp->SourceStation(), next, dest_entry->GetStation(), val);
    01393       }
    01394     }
    01395   }
    01396
    01402   void BuildCargoList(CargoDataEntry *cargo, const Station *st)
    01403   {
    01404     for (CargoID i = 0; i < NUM_CARGO; i++) {
    01405
    01406       if (this->cached_destinations.Retrieve(i) == NULL) {
    01407         this->RecalcDestinations(i);
    01408       }
    01409
    01410       if (this->current_mode == MODE_WAITING) {
    01411         this->BuildCargoList(i, st->goods[i].cargo, cargo);
    01412       } else {
    01413         this->BuildFlowList(i, st->goods[i].flows, cargo);
    01414       }
    01415     }
    01416   }
    01417
    01422   void SetDisplayedRow(const CargoDataEntry *data)
    01423   {
    01424     std::list<StationID> stations;
    01425     const CargoDataEntry *parent = data->GetParent();
    01426     if (parent->GetParent() == NULL) {
    01427       this->displayed_rows.push_back(RowDisplay(&this->expanded_rows, data->GetCargo()));
    01428       return;
    01429     }
    01430
    01431     StationID next = data->GetStation();
    01432     while (parent->GetParent()->GetParent() != NULL) {
    01433       stations.push_back(parent->GetStation());
    01434       parent = parent->GetParent();
    01435     }
    01436
    01437     CargoID cargo = parent->GetCargo();
    01438     CargoDataEntry *filter = this->expanded_rows.Retrieve(cargo);
    01439     while (!stations.empty()) {
    01440       filter = filter->Retrieve(stations.back());
    01441       stations.pop_back();
    01442     }
    01443
    01444     this->displayed_rows.push_back(RowDisplay(filter, next));
    01445   }
    01446
    01455   StringID GetEntryString(StationID station, StringID here, StringID other_station, StringID any)
    01456   {
    01457     if (station == this->window_number) {
    01458       return here;
    01459     } else if (station != INVALID_STATION) {
    01460       SetDParam(2, station);
    01461       return other_station;
    01462     } else {
    01463       return any;
    01464     }
    01465   }
    01466
    01474   StringID SearchNonStop(CargoDataEntry *cd, StationID station, int column)
    01475   {
    01476     CargoDataEntry *parent = cd->GetParent();
    01477     for (int i = column - 1; i > 0; --i) {
    01478       if (this->groupings[i] == GR_DESTINATION) {
    01479         if (parent->GetStation() == station) {
    01480           return STR_STATION_VIEW_NONSTOP;
    01481         } else {
    01482           return STR_STATION_VIEW_VIA;
    01483         }
    01484       }
    01485       parent = parent->GetParent();
    01486     }
    01487
    01488     if (this->groupings[column + 1] == GR_DESTINATION) {
    01489       CargoDataSet::iterator begin = cd->Begin();
    01490       CargoDataSet::iterator end = cd->End();
    01491       if (begin != end && ++(cd->Begin()) == end && (*(begin))->GetStation() == station) {
    01492         return STR_STATION_VIEW_NONSTOP;
    01493       } else {
    01494         return STR_STATION_VIEW_VIA;
    01495       }
    01496     }
    01497
    01498     return STR_STATION_VIEW_VIA;
    01499   }
    01500
    01511   int DrawEntries(CargoDataEntry *entry, Rect &r, int pos, int maxrows, int column, CargoID cargo = CT_INVALID)
    01512   {
    01513     if (this->sortings[column] == ST_AS_GROUPING) {
    01514       if (this->groupings[column] != GR_CARGO) {
    01515         entry->Resort(ST_STATION_STRING, this->sort_orders[column]);
    01516       }
    01517     } else {
    01518       entry->Resort(ST_COUNT, this->sort_orders[column]);
    01519     }
    01520     for (CargoDataSet::iterator i = entry->Begin(); i != entry->End(); ++i) {
    01521       CargoDataEntry *cd = *i;
    01522
    01523       if (this->groupings[column] == GR_CARGO) cargo = cd->GetCargo();
    01524
    01525       if (pos > -maxrows && pos <= 0) {
    01526         StringID str = STR_EMPTY;
    01527         int y = r.top + WD_FRAMERECT_TOP - pos * FONT_HEIGHT_NORMAL;
    01528         SetDParam(0, cargo);
    01529         SetDParam(1, cd->GetCount());
    01530
    01531         if (this->groupings[column] == GR_CARGO) {
    01532           str = STR_STATION_VIEW_WAITING_CARGO;
    01533           DrawCargoIcons(cd->GetCargo(), cd->GetCount(), r.left + WD_FRAMERECT_LEFT + this->expand_shrink_width, r.right - WD_FRAMERECT_RIGHT - this->expand_shrink_width, y);
    01534         } else {
    01535           StationID station = cd->GetStation();
    01536
    01537           switch (this->groupings[column]) {
    01538             case GR_SOURCE:
    01539               str = this->GetEntryString(station, STR_STATION_VIEW_FROM_HERE, STR_STATION_VIEW_FROM, STR_STATION_VIEW_FROM_ANY);
    01540               break;
    01541             case GR_NEXT:
    01542               str = this->GetEntryString(station, STR_STATION_VIEW_VIA_HERE, STR_STATION_VIEW_VIA, STR_STATION_VIEW_VIA_ANY);
    01543               if (str == STR_STATION_VIEW_VIA) str = SearchNonStop(cd, station, column);
    01544               break;
    01545             case GR_DESTINATION:
    01546               str = this->GetEntryString(station, STR_STATION_VIEW_TO_HERE, STR_STATION_VIEW_TO, STR_STATION_VIEW_TO_ANY);
    01547               break;
    01548             default:
    01549               NOT_REACHED();
    01550           }
    01551           if (pos == -this->scroll_to_row && Station::IsValidID(station)) {
    01552             ScrollMainWindowToTile(Station::Get(station)->xy);
    01553           }
    01554         }
    01555
    01556         bool rtl = _current_text_dir == TD_RTL;
    01557         int text_left    = rtl ? r.left + this->expand_shrink_width : r.left + WD_FRAMERECT_LEFT + column * this->expand_shrink_width;
    01558         int text_right   = rtl ? r.right - WD_FRAMERECT_LEFT - column * this->expand_shrink_width : r.right - this->expand_shrink_width;
    01559         int shrink_left  = rtl ? r.left + WD_FRAMERECT_LEFT : r.right - this->expand_shrink_width + WD_FRAMERECT_LEFT;
    01560         int shrink_right = rtl ? r.left + this->expand_shrink_width - WD_FRAMERECT_RIGHT : r.right - WD_FRAMERECT_RIGHT;
    01561
    01562         DrawString(text_left, text_right, y, str);
    01563
    01564         if (column < NUM_COLUMNS - 1) {
    01565           const char *sym = cd->GetNumChildren() > 0 ? "-" : "+";
    01566           DrawString(shrink_left, shrink_right, y, sym, TC_YELLOW);
    01567         }
    01568         SetDisplayedRow(cd);
    01569       }
    01570       pos = DrawEntries(cd, r, --pos, maxrows, column + 1, cargo);
    01571     }
    01572     return pos;
    01573   }
    01574
    01580   int DrawAcceptedCargo(const Rect &r) const
    01581   {
    01582     const Station *st = Station::Get(this->window_number);
    01583
    01584     uint32 cargo_mask = 0;
    01585     for (CargoID i = 0; i < NUM_CARGO; i++) {
    01586       if (HasBit(st->goods[i].acceptance_pickup, GoodsEntry::GES_ACCEPTANCE)) SetBit(cargo_mask, i);
    01587     }
    01588     SetDParam(0, cargo_mask);
    01589     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);
    01590     return CeilDiv(bottom - r.top - WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL);
    01591   }
    01592
    01598   int DrawCargoRatings(const Rect &r) const
    01599   {
    01600     const Station *st = Station::Get(this->window_number);
    01601     int y = r.top + WD_FRAMERECT_TOP;
    01602
    01603     if (st->town->exclusive_counter > 0) {
    01604       SetDParam(0, st->town->exclusivity);
    01605       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);
    01606       y += WD_PAR_VSEP_WIDE;
    01607     }
    01608
    01609     DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_VIEW_CARGO_RATINGS_TITLE);
    01610     y += FONT_HEIGHT_NORMAL;
    01611
    01612     const CargoSpec *cs;
    01613     FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
    01614       const GoodsEntry *ge = &st->goods[cs->Index()];
    01615       if (!HasBit(ge->acceptance_pickup, GoodsEntry::GES_PICKUP)) continue;
    01616
    01617       SetDParam(0, cs->name);
    01618       SetDParam(1, ge->supply);
    01619       SetDParam(3, ToPercent8(ge->rating));
    01620       SetDParam(2, STR_CARGO_RATING_APPALLING + (ge->rating >> 5));
    01621       DrawString(r.left + WD_FRAMERECT_LEFT + 6, r.right - WD_FRAMERECT_RIGHT - 6, y, STR_STATION_VIEW_CARGO_SUPPLY_RATING);
    01622       y += FONT_HEIGHT_NORMAL;
    01623     }
    01624     return CeilDiv(y - r.top - WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL);
    01625   }
    01626
    01632   template<class ID>
    01633   void HandleCargoWaitingClick(CargoDataEntry *filter, ID next)
    01634   {
    01635     if (filter->Retrieve(next) != NULL) {
    01636       filter->Remove(next);
    01637     } else {
    01638       filter->InsertOrRetrieve(next);
    01639     }
    01640   }
    01641
    01646   void HandleCargoWaitingClick(int row)
    01647   {
    01648     if (row < 0 || (uint)row >= this->displayed_rows.size()) return;
    01649     if (_ctrl_pressed) {
    01650       this->scroll_to_row = row;
    01651     } else {
    01652       RowDisplay &display = this->displayed_rows[row];
    01653       if (display.filter == &this->expanded_rows) {
    01654         this->HandleCargoWaitingClick<CargoID>(display.filter, display.next_cargo);
    01655       } else {
    01656         this->HandleCargoWaitingClick<StationID>(display.filter, display.next_station);
    01657       }
    01658     }
    01659     this->SetWidgetDirty(WID_SV_WAITING);
    01660   }
    01661
    01662   virtual void OnClick(Point pt, int widget, int click_count)
    01663   {
    01664     switch (widget) {
    01665       case WID_SV_WAITING:
    01666         this->HandleCargoWaitingClick(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_SV_WAITING, WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL) - this->vscroll->GetPosition());
    01667         break;
    01668
    01669       case WID_SV_LOCATION:
    01670         if (_ctrl_pressed) {
    01671           ShowExtraViewPortWindow(Station::Get(this->window_number)->xy);
    01672         } else {
    01673           ScrollMainWindowToTile(Station::Get(this->window_number)->xy);
    01674         }
    01675         break;
    01676
    01677       case WID_SV_ACCEPTS_RATINGS: {
    01678         /* Swap between 'accepts' and 'ratings' view. */
    01679         int height_change;
    01680         NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS);
    01681         if (this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) {
    01682           nwi->SetDataTip(STR_STATION_VIEW_ACCEPTS_BUTTON, STR_STATION_VIEW_ACCEPTS_TOOLTIP); // Switch to accepts view.
    01683           height_change = this->rating_lines - this->accepts_lines;
    01684         } else {
    01685           nwi->SetDataTip(STR_STATION_VIEW_RATINGS_BUTTON, STR_STATION_VIEW_RATINGS_TOOLTIP); // Switch to ratings view.
    01686           height_change = this->accepts_lines - this->rating_lines;
    01687         }
    01688         this->ReInit(0, height_change * FONT_HEIGHT_NORMAL);
    01689         break;
    01690       }
    01691
    01692       case WID_SV_RENAME:
    01693         SetDParam(0, this->window_number);
    01694         ShowQueryString(STR_STATION_NAME, STR_STATION_VIEW_RENAME_STATION_CAPTION, MAX_LENGTH_STATION_NAME_CHARS,
    01695             this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
    01696         break;
    01697
    01698       case WID_SV_CLOSE_AIRPORT:
    01699         DoCommandP(0, this->window_number, 0, CMD_OPEN_CLOSE_AIRPORT);
    01700         break;
    01701
    01702       case WID_SV_TRAINS:   // Show list of scheduled trains to this station
    01703       case WID_SV_ROADVEHS: // Show list of scheduled road-vehicles to this station
    01704       case WID_SV_SHIPS:    // Show list of scheduled ships to this station
    01705       case WID_SV_PLANES: { // Show list of scheduled aircraft to this station
    01706         Owner owner = Station::Get(this->window_number)->owner;
    01707         ShowVehicleListWindow(owner, (VehicleType)(widget - WID_SV_TRAINS), (StationID)this->window_number);
    01708         break;
    01709       }
    01710
    01711       case WID_SV_SORT_BY: {
    01712         ShowDropDownMenu(this, _sort_names, this->current_mode, WID_SV_SORT_BY, 0, 0);
    01713         break;
    01714       }
    01715
    01716       case WID_SV_GROUP_BY: {
    01717         ShowDropDownMenu(this, _group_names, this->grouping_index, WID_SV_GROUP_BY, 0, 0);
    01718         break;
    01719       }
    01720
    01721       case WID_SV_SORT_ORDER: { // flip sorting method asc/desc
    01722         this->SelectSortOrder(this->sort_orders[1] == SO_ASCENDING ? SO_DESCENDING : SO_ASCENDING);
    01723         this->SetTimeout();
    01724         this->LowerWidget(WID_SV_SORT_ORDER);
    01725         break;
    01726       }
    01727     }
    01728   }
    01729
    01734   void SelectSortOrder(SortOrder order)
    01735   {
    01736     this->sort_orders[1] = this->sort_orders[2] = this->sort_orders[3] = order;
    01737     _settings_client.gui.station_gui_sort_order = this->sort_orders[1];
    01738     this->SetDirty();
    01739   }
    01740
    01745   void SelectSortBy(int index)
    01746   {
    01747     _settings_client.gui.station_gui_sort_by = index;
    01748     switch (_sort_names[index]) {
    01749       case STR_STATION_VIEW_WAITING_STATION:
    01750         this->current_mode = MODE_WAITING;
    01751         this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_AS_GROUPING;
    01752         break;
    01753       case STR_STATION_VIEW_WAITING_AMOUNT:
    01754         this->current_mode = MODE_WAITING;
    01755         this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_COUNT;
    01756         break;
    01757       case STR_STATION_VIEW_PLANNED_STATION:
    01758         this->current_mode = MODE_PLANNED;
    01759         this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_AS_GROUPING;
    01760         break;
    01761       case STR_STATION_VIEW_PLANNED_AMOUNT:
    01762         this->current_mode = MODE_PLANNED;
    01763         this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_COUNT;
    01764         break;
    01765       default:
    01766         NOT_REACHED();
    01767     }
    01768     /* Display the current sort variant */
    01769     this->GetWidget<NWidgetCore>(WID_SV_SORT_BY)->widget_data = _sort_names[index];
    01770     this->SetDirty();
    01771   }
    01772
    01777   void SelectGroupBy(int index)
    01778   {
    01779     this->grouping_index = index;
    01780     _settings_client.gui.station_gui_group_order = index;
    01781     this->GetWidget<NWidgetCore>(WID_SV_GROUP_BY)->widget_data = _group_names[index];
    01782     switch (_group_names[index]) {
    01783       case STR_STATION_VIEW_GROUP_S_V_D:
    01784         this->groupings[1] = GR_SOURCE;
    01785         this->groupings[2] = GR_NEXT;
    01786         this->groupings[3] = GR_DESTINATION;
    01787         break;
    01788       case STR_STATION_VIEW_GROUP_S_D_V:
    01789         this->groupings[1] = GR_SOURCE;
    01790         this->groupings[2] = GR_DESTINATION;
    01791         this->groupings[3] = GR_NEXT;
    01792         break;
    01793       case STR_STATION_VIEW_GROUP_V_S_D:
    01794         this->groupings[1] = GR_NEXT;
    01795         this->groupings[2] = GR_SOURCE;
    01796         this->groupings[3] = GR_DESTINATION;
    01797         break;
    01798       case STR_STATION_VIEW_GROUP_V_D_S:
    01799         this->groupings[1] = GR_NEXT;
    01800         this->groupings[2] = GR_DESTINATION;
    01801         this->groupings[3] = GR_SOURCE;
    01802         break;
    01803       case STR_STATION_VIEW_GROUP_D_S_V:
    01804         this->groupings[1] = GR_DESTINATION;
    01805         this->groupings[2] = GR_SOURCE;
    01806         this->groupings[3] = GR_NEXT;
    01807         break;
    01808       case STR_STATION_VIEW_GROUP_D_V_S:
    01809         this->groupings[1] = GR_DESTINATION;
    01810         this->groupings[2] = GR_NEXT;
    01811         this->groupings[3] = GR_SOURCE;
    01812         break;
    01813     }
    01814     this->SetDirty();
    01815   }
    01816
    01817   virtual void OnDropdownSelect(int widget, int index)
    01818   {
    01819     if (widget == WID_SV_SORT_BY) {
    01820       this->SelectSortBy(index);
    01821     } else {
    01822       this->SelectGroupBy(index);
    01823     }
    01824   }
    01825
    01826   virtual void OnQueryTextFinished(char *str)
    01827   {
    01828     if (str == NULL) return;
    01829
    01830     DoCommandP(0, this->window_number, 0, CMD_RENAME_STATION | CMD_MSG(STR_ERROR_CAN_T_RENAME_STATION), NULL, str);
    01831   }
    01832
    01833   virtual void OnResize()
    01834   {
    01835     this->vscroll->SetCapacityFromWidget(this, WID_SV_WAITING, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
    01836   }
    01837
    01843   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
    01844   {
    01845     if (gui_scope) {
    01846       if (data >= 0 && data < NUM_CARGO) {
    01847         this->cached_destinations.Remove((CargoID)data);
    01848       } else {
    01849         this->ReInit();
    01850       }
    01851     }
    01852   }
    01853 };
    01854
    01855 const StringID StationViewWindow::_sort_names[] = {
    01856   STR_STATION_VIEW_WAITING_STATION,
    01857   STR_STATION_VIEW_WAITING_AMOUNT,
    01858   STR_STATION_VIEW_PLANNED_STATION,
    01859   STR_STATION_VIEW_PLANNED_AMOUNT,
    01860   INVALID_STRING_ID
    01861 };
    01862
    01863 const StringID StationViewWindow::_group_names[] = {
    01864   STR_STATION_VIEW_GROUP_S_V_D,
    01865   STR_STATION_VIEW_GROUP_S_D_V,
    01866   STR_STATION_VIEW_GROUP_V_S_D,
    01867   STR_STATION_VIEW_GROUP_V_D_S,
    01868   STR_STATION_VIEW_GROUP_D_S_V,
    01869   STR_STATION_VIEW_GROUP_D_V_S,
    01870   INVALID_STRING_ID
    01871 };
    01872
    01873 static const WindowDesc _station_view_desc(
    01874   WDP_AUTO, 249, 117,
    01875   WC_STATION_VIEW, WC_NONE,
    01876   WDF_UNCLICK_BUTTONS,
    01877   _nested_station_view_widgets, lengthof(_nested_station_view_widgets)
    01878 );
    01879
    01885 void ShowStationViewWindow(StationID station)
    01886 {
    01887   AllocateWindowDescFront<StationViewWindow>(&_station_view_desc, station);
    01888 }
    01889
    01891 struct TileAndStation {
    01892   TileIndex tile;
    01893   StationID station;
    01894 };
    01895
    01896 static SmallVector<TileAndStation, 8> _deleted_stations_nearby;
    01897 static SmallVector<StationID, 8> _stations_nearby_list;
    01898
    01906 template <class T>
    01907 static bool AddNearbyStation(TileIndex tile, void *user_data)
    01908 {
    01909   TileArea *ctx = (TileArea *)user_data;
    01910
    01911   /* First check if there were deleted stations here */
    01912   for (uint i = 0; i < _deleted_stations_nearby.Length(); i++) {
    01913     TileAndStation *ts = _deleted_stations_nearby.Get(i);
    01914     if (ts->tile == tile) {
    01915       *_stations_nearby_list.Append() = _deleted_stations_nearby[i].station;
    01916       _deleted_stations_nearby.Erase(ts);
    01917       i--;
    01918     }
    01919   }
    01920
    01921   /* Check if own station and if we stay within station spread */
    01922   if (!IsTileType(tile, MP_STATION)) return false;
    01923
    01924   StationID sid = GetStationIndex(tile);
    01925
    01926   /* This station is (likely) a waypoint */
    01927   if (!T::IsValidID(sid)) return false;
    01928
    01929   T *st = T::Get(sid);
    01930   if (st->owner != _local_company || _stations_nearby_list.Contains(sid)) return false;
    01931
    01932   if (st->rect.BeforeAddRect(ctx->tile, ctx->w, ctx->h, StationRect::ADD_TEST).Succeeded()) {
    01933     *_stations_nearby_list.Append() = sid;
    01934   }
    01935
    01936   return false; // We want to include *all* nearby stations
    01937 }
    01938
    01948 template <class T>
    01949 static const T *FindStationsNearby(TileArea ta, bool distant_join)
    01950 {
    01951   TileArea ctx = ta;
    01952
    01953   _stations_nearby_list.Clear();
    01954   _deleted_stations_nearby.Clear();
    01955
    01956   /* Check the inside, to return, if we sit on another station */
    01957   TILE_AREA_LOOP(t, ta) {
    01958     if (t < MapSize() && IsTileType(t, MP_STATION) && T::IsValidID(GetStationIndex(t))) return T::GetByTile(t);
    01959   }
    01960
    01961   /* Look for deleted stations */
    01962   const BaseStation *st;
    01963   FOR_ALL_BASE_STATIONS(st) {
    01964     if (T::IsExpected(st) && !st->IsInUse() && st->owner == _local_company) {
    01965       /* Include only within station spread (yes, it is strictly less than) */
    01966       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) {
    01967         TileAndStation *ts = _deleted_stations_nearby.Append();
    01968         ts->tile = st->xy;
    01969         ts->station = st->index;
    01970
    01971         /* Add the station when it's within where we're going to build */
    01972         if (IsInsideBS(TileX(st->xy), TileX(ctx.tile), ctx.w) &&
    01973             IsInsideBS(TileY(st->xy), TileY(ctx.tile), ctx.h)) {
    01974           AddNearbyStation<T>(st->xy, &ctx);
    01975         }
    01976       }
    01977     }
    01978   }
    01979
    01980   /* Only search tiles where we have a chance to stay within the station spread.
    01981    * The complete check needs to be done in the callback as we don't know the
    01982    * extent of the found station, yet. */
    01983   if (distant_join && min(ta.w, ta.h) >= _settings_game.station.station_spread) return NULL;
    01984   uint max_dist = distant_join ? _settings_game.station.station_spread - min(ta.w, ta.h) : 1;
    01985
    01986   TileIndex tile = TILE_ADD(ctx.tile, TileOffsByDir(DIR_N));
    01987   CircularTileSearch(&tile, max_dist, ta.w, ta.h, AddNearbyStation<T>, &ctx);
    01988
    01989   return NULL;
    01990 }
    01991
    01992 static const NWidgetPart _nested_select_station_widgets[] = {
    01993   NWidget(NWID_HORIZONTAL),
    01994     NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
    01995     NWidget(WWT_CAPTION, COLOUR_DARK_GREEN, WID_JS_CAPTION), SetDataTip(STR_JOIN_STATION_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
    01996   EndContainer(),
    01997   NWidget(NWID_HORIZONTAL),
    01998     NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_JS_PANEL), SetResize(1, 0), SetScrollbar(WID_JS_SCROLLBAR), EndContainer(),
    01999     NWidget(NWID_VERTICAL),
    02000       NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, WID_JS_SCROLLBAR),
    02001       NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
    02002     EndContainer(),
    02003   EndContainer(),
    02004 };
    02005
    02010 template <class T>
    02011 struct SelectStationWindow : Window {
    02012   CommandContainer select_station_cmd;
    02013   TileArea area;
    02014   Scrollbar *vscroll;
    02015
    02016   SelectStationWindow(const WindowDesc *desc, CommandContainer cmd, TileArea ta) :
    02017     Window(),
    02018     select_station_cmd(cmd),
    02019     area(ta)
    02020   {
    02021     this->CreateNestedTree(desc);
    02022     this->vscroll = this->GetScrollbar(WID_JS_SCROLLBAR);
    02023     this->GetWidget<NWidgetCore>(WID_JS_CAPTION)->widget_data = T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_JOIN_WAYPOINT_CAPTION : STR_JOIN_STATION_CAPTION;
    02024     this->FinishInitNested(desc, 0);
    02025     this->OnInvalidateData(0);
    02026   }
    02027
    02028   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    02029   {
    02030     if (widget != WID_JS_PANEL) return;
    02031
    02032     /* Determine the widest string */
    02033     Dimension d = GetStringBoundingBox(T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_JOIN_WAYPOINT_CREATE_SPLITTED_WAYPOINT : STR_JOIN_STATION_CREATE_SPLITTED_STATION);
    02034     for (uint i = 0; i < _stations_nearby_list.Length(); i++) {
    02035       const T *st = T::Get(_stations_nearby_list[i]);
    02036       SetDParam(0, st->index);
    02037       SetDParam(1, st->facilities);
    02038       d = maxdim(d, GetStringBoundingBox(T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_STATION_LIST_WAYPOINT : STR_STATION_LIST_STATION));
    02039     }
    02040
    02041     resize->height = d.height;
    02042     d.height *= 5;
    02043     d.width += WD_FRAMERECT_RIGHT + WD_FRAMERECT_LEFT;
    02044     d.height += WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
    02045     *size = d;
    02046   }
    02047
    02048   virtual void DrawWidget(const Rect &r, int widget) const
    02049   {
    02050     if (widget != WID_JS_PANEL) return;
    02051
    02052     uint y = r.top + WD_FRAMERECT_TOP;
    02053     if (this->vscroll->GetPosition() == 0) {
    02054       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);
    02055       y += this->resize.step_height;
    02056     }
    02057
    02058     for (uint i = max<uint>(1, this->vscroll->GetPosition()); i <= _stations_nearby_list.Length(); ++i, y += this->resize.step_height) {
    02059       /* Don't draw anything if it extends past the end of the window. */
    02060       if (i - this->vscroll->GetPosition() >= this->vscroll->GetCapacity()) break;
    02061
    02062       const T *st = T::Get(_stations_nearby_list[i - 1]);
    02063       SetDParam(0, st->index);
    02064       SetDParam(1, st->facilities);
    02065       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);
    02066     }
    02067   }
    02068
    02069   virtual void OnClick(Point pt, int widget, int click_count)
    02070   {
    02071     if (widget != WID_JS_PANEL) return;
    02072
    02073     uint st_index = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_JS_PANEL, WD_FRAMERECT_TOP);
    02074     bool distant_join = (st_index > 0);
    02075     if (distant_join) st_index--;
    02076
    02077     if (distant_join && st_index >= _stations_nearby_list.Length()) return;
    02078
    02079     /* Insert station to be joined into stored command */
    02080     SB(this->select_station_cmd.p2, 16, 16,
    02081        (distant_join ? _stations_nearby_list[st_index] : NEW_STATION));
    02082
    02083     /* Execute stored Command */
    02084     DoCommandP(&this->select_station_cmd);
    02085
    02086     /* Close Window; this might cause double frees! */
    02087     DeleteWindowById(WC_SELECT_STATION, 0);
    02088   }
    02089
    02090   virtual void OnTick()
    02091   {
    02092     if (_thd.dirty & 2) {
    02093       _thd.dirty &= ~2;
    02094       this->SetDirty();
    02095     }
    02096   }
    02097
    02098   virtual void OnResize()
    02099   {
    02100     this->vscroll->SetCapacityFromWidget(this, WID_JS_PANEL, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
    02101   }
    02102
    02108   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
    02109   {
    02110     if (!gui_scope) return;
    02111     FindStationsNearby<T>(this->area, true);
    02112     this->vscroll->SetCount(_stations_nearby_list.Length() + 1);
    02113     this->SetDirty();
    02114   }
    02115 };
    02116
    02117 static const WindowDesc _select_station_desc(
    02118   WDP_AUTO, 200, 180,
    02119   WC_SELECT_STATION, WC_NONE,
    02120   WDF_CONSTRUCTION,
    02121   _nested_select_station_widgets, lengthof(_nested_select_station_widgets)
    02122 );
    02123
    02124
    02132 template <class T>
    02133 static bool StationJoinerNeeded(CommandContainer cmd, TileArea ta)
    02134 {
    02135   /* Only show selection if distant join is enabled in the settings */
    02136   if (!_settings_game.station.distant_join_stations) return false;
    02137
    02138   /* If a window is already opened and we didn't ctrl-click,
    02139    * return true (i.e. just flash the old window) */
    02140   Window *selection_window = FindWindowById(WC_SELECT_STATION, 0);
    02141   if (selection_window != NULL) {
    02142     /* Abort current distant-join and start new one */
    02143     delete selection_window;
    02144     UpdateTileSelection();
    02145   }
    02146
    02147   /* only show the popup, if we press ctrl */
    02148   if (!_ctrl_pressed) return false;
    02149
    02150   /* Now check if we could build there */
    02151   if (DoCommand(&cmd, CommandFlagsToDCFlags(GetCommandFlags(cmd.cmd))).Failed()) return false;
    02152
    02153   /* Test for adjacent station or station below selection.
    02154    * If adjacent-stations is disabled and we are building next to a station, do not show the selection window.
    02155    * but join the other station immediately. */
    02156   const T *st = FindStationsNearby<T>(ta, false);
    02157   return st == NULL && (_settings_game.station.adjacent_stations || _stations_nearby_list.Length() == 0);
    02158 }
    02159
    02166 template <class T>
    02167 void ShowSelectBaseStationIfNeeded(CommandContainer cmd, TileArea ta)
    02168 {
    02169   if (StationJoinerNeeded<T>(cmd, ta)) {
    02170     if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
    02171     new SelectStationWindow<T>(&_select_station_desc, cmd, ta);
    02172   } else {
    02173     DoCommandP(&cmd);
    02174   }
    02175 }
    02176
    02182 void ShowSelectStationIfNeeded(CommandContainer cmd, TileArea ta)
    02183 {
    02184   ShowSelectBaseStationIfNeeded<Station>(cmd, ta);
    02185 }
    02186
    02192 void ShowSelectWaypointIfNeeded(CommandContainer cmd, TileArea ta)
    02193 {
    02194   ShowSelectBaseStationIfNeeded<Waypoint>(cmd, ta);
    02195 }