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