# station_gui.cpp

Go to the documentation of this file.

    00001 /* $Id$ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
    00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
    00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
    00008  */
    00009
    00012 #include "stdafx.h"
    00013 #include "debug.h"
    00014 #include "gui.h"
    00015 #include "textbuf_gui.h"
    00016 #include "company_func.h"
    00017 #include "command_func.h"
    00018 #include "vehicle_gui.h"
    00019 #include "cargotype.h"
    00020 #include "station_gui.h"
    00021 #include "strings_func.h"
    00022 #include "window_func.h"
    00023 #include "viewport_func.h"
    00024 #include "widgets/dropdown_func.h"
    00025 #include "station_base.h"
    00026 #include "waypoint_base.h"
    00027 #include "tilehighlight_func.h"
    00028 #include "company_base.h"
    00029 #include "sortlist_type.h"
    00030 #include "core/geometry_func.hpp"
    00031 #include "vehiclelist.h"
    00032
    00033 #include "widgets/station_widget.h"
    00034
    00035 #include "table/strings.h"
    00036
    00037 #include <vector>
    00038
    00049 int DrawStationCoverageAreaText(int left, int right, int top, StationCoverageType sct, int rad, bool supplies)
    00050 {
    00051   TileIndex tile = TileVirtXY(_thd.pos.x, _thd.pos.y);
    00052   uint32 cargo_mask = 0;
    00053   if (_thd.drawstyle == HT_RECT && tile < MapSize()) {
    00054     CargoArray cargoes;
    00055     if (supplies) {
    00056       cargoes = GetProductionAroundTiles(tile, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE, rad);
    00057     } else {
    00058       cargoes = GetAcceptanceAroundTiles(tile, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE, rad);
    00059     }
    00060
    00061     /* Convert cargo counts to a set of cargo bits, and draw the result. */
    00062     for (CargoID i = 0; i < NUM_CARGO; i++) {
    00063       switch (sct) {
    00064         case SCT_PASSENGERS_ONLY: if (!IsCargoInClass(i, CC_PASSENGERS)) continue; break;
    00065         case SCT_NON_PASSENGERS_ONLY: if (IsCargoInClass(i, CC_PASSENGERS)) continue; break;
    00066         case SCT_ALL: break;
    00067         default: NOT_REACHED();
    00068       }
    00069       if (cargoes[i] >= (supplies ? 1U : 8U)) SetBit(cargo_mask, i);
    00070     }
    00071   }
    00072   SetDParam(0, cargo_mask);
    00073   return DrawStringMultiLine(left, right, top, INT32_MAX, supplies ? STR_STATION_BUILD_SUPPLIES_CARGO : STR_STATION_BUILD_ACCEPTS_CARGO);
    00074 }
    00075
    00081 void CheckRedrawStationCoverage(const Window *w)
    00082 {
    00083   if (_thd.dirty & 1) {
    00084     _thd.dirty &= ~1;
    00085     w->SetDirty();
    00086   }
    00087 }
    00088
    00104 static void StationsWndShowStationRating(int left, int right, int y, CargoID type, uint amount, byte rating)
    00105 {
    00106   static const uint units_full  = 576;
    00107   static const uint rating_full = 224;
    00108
    00109   const CargoSpec *cs = CargoSpec::Get(type);
    00110   if (!cs->IsValid()) return;
    00111
    00112   int colour = cs->rating_colour;
    00113   uint w = (minu(amount, units_full) + 5) / 36;
    00114
    00115   int height = GetCharacterHeight(FS_SMALL);
    00116
    00117   /* Draw total cargo (limited) on station (fits into 16 pixels) */
    00118   if (w != 0) GfxFillRect(left, y, left + w - 1, y + height, colour);
    00119
    00120   /* Draw a one pixel-wide bar of additional cargo meter, useful
    00121    * for stations with only a small amount (<=30) */
    00122   if (w == 0) {
    00123     uint rest = amount / 5;
    00124     if (rest != 0) {
    00125       w += left;
    00126       GfxFillRect(w, y + height - rest, w, y + height, colour);
    00127     }
    00128   }
    00129
    00130   DrawString(left + 1, right, y, cs->abbrev, TC_BLACK);
    00131
    00132   /* Draw green/red ratings bar (fits into 14 pixels) */
    00133   y += height + 2;
    00134   GfxFillRect(left + 1, y, left + 14, y, PC_RED);
    00135   rating = minu(rating, rating_full) / 16;
    00136   if (rating != 0) GfxFillRect(left + 1, y, left + rating, y, PC_GREEN);
    00137 }
    00138
    00139 typedef GUIList<const Station*> GUIStationList;
    00140
    00144 class CompanyStationsWindow : public Window
    00145 {
    00146 protected:
    00147   /* Runtime saved values */
    00148   static Listing last_sorting;
    00149   static byte facilities;               // types of stations of interest
    00150   static bool include_empty;            // whether we should include stations without waiting cargo
    00151   static const uint32 cargo_filter_max;
    00152   static uint32 cargo_filter;           // bitmap of cargo types to include
    00153   static const Station *last_station;
    00154
    00155   /* Constants for sorting stations */
    00156   static const StringID sorter_names[];
    00157   static GUIStationList::SortFunction * const sorter_funcs[];
    00158
    00159   GUIStationList stations;
    00160   Scrollbar *vscroll;
    00161
    00167   void BuildStationsList(const Owner owner)
    00168   {
    00169     if (!this->stations.NeedRebuild()) return;
    00170
    00171     DEBUG(misc, 3, "Building station list for company %d", owner);
    00172
    00173     this->stations.Clear();
    00174
    00175     const Station *st;
    00176     FOR_ALL_STATIONS(st) {
    00177       if (st->owner == owner || (st->owner == OWNER_NONE && HasStationInUse(st->index, true, owner))) {
    00178         if (this->facilities & st->facilities) { // only stations with selected facilities
    00179           int num_waiting_cargo = 0;
    00180           for (CargoID j = 0; j < NUM_CARGO; j++) {
    00181             if (HasBit(st->goods[j].acceptance_pickup, GoodsEntry::GES_PICKUP)) {
    00182               num_waiting_cargo++; // count number of waiting cargo
    00183               if (HasBit(this->cargo_filter, j)) {
    00184                 *this->stations.Append() = st;
    00185                 break;
    00186               }
    00187             }
    00188           }
    00189           /* stations without waiting cargo */
    00190           if (num_waiting_cargo == 0 && this->include_empty) {
    00191             *this->stations.Append() = st;
    00192           }
    00193         }
    00194       }
    00195     }
    00196
    00197     this->stations.Compact();
    00198     this->stations.RebuildDone();
    00199
    00200     this->vscroll->SetCount(this->stations.Length()); // Update the scrollbar
    00201   }
    00202
    00204   static int CDECL StationNameSorter(const Station * const *a, const Station * const *b)
    00205   {
    00206     static char buf_cache[64];
    00207     char buf[64];
    00208
    00209     SetDParam(0, (*a)->index);
    00210     GetString(buf, STR_STATION_NAME, lastof(buf));
    00211
    00212     if (*b != last_station) {
    00213       last_station = *b;
    00214       SetDParam(0, (*b)->index);
    00215       GetString(buf_cache, STR_STATION_NAME, lastof(buf_cache));
    00216     }
    00217
    00218     return strcmp(buf, buf_cache);
    00219   }
    00220
    00222   static int CDECL StationTypeSorter(const Station * const *a, const Station * const *b)
    00223   {
    00224     return (*a)->facilities - (*b)->facilities;
    00225   }
    00226
    00228   static int CDECL StationWaitingSorter(const Station * const *a, const Station * const *b)
    00229   {
    00230     Money diff = 0;
    00231
    00232     CargoID j;
    00233     FOR_EACH_SET_CARGO_ID(j, cargo_filter) {
    00234       if (!(*a)->goods[j].cargo.Empty()) diff += GetTransportedGoodsIncome((*a)->goods[j].cargo.Count(), 20, 50, j);
    00235       if (!(*b)->goods[j].cargo.Empty()) diff -= GetTransportedGoodsIncome((*b)->goods[j].cargo.Count(), 20, 50, j);
    00236     }
    00237
    00238     return ClampToI32(diff);
    00239   }
    00240
    00242   static int CDECL StationRatingMaxSorter(const Station * const *a, const Station * const *b)
    00243   {
    00244     byte maxr1 = 0;
    00245     byte maxr2 = 0;
    00246
    00247     CargoID j;
    00248     FOR_EACH_SET_CARGO_ID(j, cargo_filter) {
    00249       if (HasBit((*a)->goods[j].acceptance_pickup, GoodsEntry::GES_PICKUP)) maxr1 = max(maxr1, (*a)->goods[j].rating);
    00250       if (HasBit((*b)->goods[j].acceptance_pickup, GoodsEntry::GES_PICKUP)) maxr2 = max(maxr2, (*b)->goods[j].rating);
    00251     }
    00252
    00253     return maxr1 - maxr2;
    00254   }
    00255
    00257   static int CDECL StationRatingMinSorter(const Station * const *a, const Station * const *b)
    00258   {
    00259     byte minr1 = 255;
    00260     byte minr2 = 255;
    00261
    00262     for (CargoID j = 0; j < NUM_CARGO; j++) {
    00263       if (!HasBit(cargo_filter, j)) continue;
    00264       if (HasBit((*a)->goods[j].acceptance_pickup, GoodsEntry::GES_PICKUP)) minr1 = min(minr1, (*a)->goods[j].rating);
    00265       if (HasBit((*b)->goods[j].acceptance_pickup, GoodsEntry::GES_PICKUP)) minr2 = min(minr2, (*b)->goods[j].rating);
    00266     }
    00267
    00268     return -(minr1 - minr2);
    00269   }
    00270
    00272   void SortStationsList()
    00273   {
    00274     if (!this->stations.Sort()) return;
    00275
    00276     /* Reset name sorter sort cache */
    00277     this->last_station = NULL;
    00278
    00279     /* Set the modified widget dirty */
    00280     this->SetWidgetDirty(WID_STL_LIST);
    00281   }
    00282
    00283 public:
    00284   CompanyStationsWindow(const WindowDesc *desc, WindowNumber window_number) : Window()
    00285   {
    00286     this->stations.SetListing(this->last_sorting);
    00287     this->stations.SetSortFuncs(this->sorter_funcs);
    00288     this->stations.ForceRebuild();
    00289     this->stations.NeedResort();
    00290     this->SortStationsList();
    00291
    00292     this->CreateNestedTree(desc);
    00293     this->vscroll = this->GetScrollbar(WID_STL_SCROLLBAR);
    00294     this->FinishInitNested(desc, window_number);
    00295     this->owner = (Owner)this->window_number;
    00296
    00297     CargoID cid;
    00298     FOR_EACH_SET_CARGO_ID(cid, this->cargo_filter) {
    00299       if (CargoSpec::Get(cid)->IsValid()) this->LowerWidget(WID_STL_CARGOSTART + cid);
    00300     }
    00301
    00302     if (this->cargo_filter == this->cargo_filter_max) this->cargo_filter = _cargo_mask;
    00303
    00304     for (uint i = 0; i < 5; i++) {
    00305       if (HasBit(this->facilities, i)) this->LowerWidget(i + WID_STL_TRAIN);
    00306     }
    00307     this->SetWidgetLoweredState(WID_STL_NOCARGOWAITING, this->include_empty);
    00308
    00309     this->GetWidget<NWidgetCore>(WID_STL_SORTDROPBTN)->widget_data = this->sorter_names[this->stations.SortType()];
    00310   }
    00311
    00312   ~CompanyStationsWindow()
    00313   {
    00314     this->last_sorting = this->stations.GetListing();
    00315   }
    00316
    00317   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    00318   {
    00319     switch (widget) {
    00320       case WID_STL_SORTBY: {
    00321         Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
    00322         d.width += padding.width + WD_SORTBUTTON_ARROW_WIDTH * 2; // Doubled since the string is centred and it also looks better.
    00323         d.height += padding.height;
    00324         *size = maxdim(*size, d);
    00325         break;
    00326       }
    00327
    00328       case WID_STL_SORTDROPBTN: {
    00329         Dimension d = {0, 0};
    00330         for (int i = 0; this->sorter_names[i] != INVALID_STRING_ID; i++) {
    00331           d = maxdim(d, GetStringBoundingBox(this->sorter_names[i]));
    00332         }
    00333         d.width += padding.width;
    00334         d.height += padding.height;
    00335         *size = maxdim(*size, d);
    00336         break;
    00337       }
    00338
    00339       case WID_STL_LIST:
    00340         resize->height = FONT_HEIGHT_NORMAL;
    00341         size->height = WD_FRAMERECT_TOP + 5 * resize->height + WD_FRAMERECT_BOTTOM;
    00342         break;
    00343
    00344       case WID_STL_TRAIN:
    00345       case WID_STL_TRUCK:
    00346       case WID_STL_BUS:
    00347       case WID_STL_AIRPLANE:
    00348       case WID_STL_SHIP:
    00349         size->height = max<uint>(FONT_HEIGHT_SMALL, 10) + padding.height;
    00350         break;
    00351
    00352       case WID_STL_CARGOALL:
    00353       case WID_STL_FACILALL:
    00354       case WID_STL_NOCARGOWAITING: {
    00355         Dimension d = GetStringBoundingBox(widget == WID_STL_NOCARGOWAITING ? STR_ABBREV_NONE : STR_ABBREV_ALL);
    00356         d.width  += padding.width + 2;
    00357         d.height += padding.height;
    00358         *size = maxdim(*size, d);
    00359         break;
    00360       }
    00361
    00362       default:
    00363         if (widget >= WID_STL_CARGOSTART) {
    00364           const CargoSpec *cs = CargoSpec::Get(widget - WID_STL_CARGOSTART);
    00365           if (cs->IsValid()) {
    00366             Dimension d = GetStringBoundingBox(cs->abbrev);
    00367             d.width  += padding.width + 2;
    00368             d.height += padding.height;
    00369             *size = maxdim(*size, d);
    00370           }
    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 (CargoID j = 0; j < NUM_CARGO; j++) {
    00411             if (!st->goods[j].cargo.Empty()) {
    00412               /* For RTL we work in exactly the opposite direction. So
    00413                * decrement the space needed first, then draw to the left
    00414                * instead of drawing to the left and then incrementing
    00415                * the space. */
    00416               if (rtl) {
    00417                 x -= 20;
    00418                 if (x < r.left + WD_FRAMERECT_LEFT) break;
    00419               }
    00420               StationsWndShowStationRating(x, x + 16, y, j, st->goods[j].cargo.Count(), st->goods[j].rating);
    00421               if (!rtl) {
    00422                 x += 20;
    00423                 if (x > r.right - WD_FRAMERECT_RIGHT) break;
    00424               }
    00425             }
    00426           }
    00427           y += FONT_HEIGHT_NORMAL;
    00428         }
    00429
    00430         if (this->vscroll->GetCount() == 0) { // company has no stations
    00431           DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_LIST_NONE);
    00432           return;
    00433         }
    00434         break;
    00435       }
    00436
    00437       case WID_STL_NOCARGOWAITING: {
    00438         int cg_ofst = this->IsWidgetLowered(widget) ? 2 : 1;
    00439         DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, STR_ABBREV_NONE, TC_BLACK, SA_HOR_CENTER);
    00440         break;
    00441       }
    00442
    00443       case WID_STL_CARGOALL: {
    00444         int cg_ofst = this->IsWidgetLowered(widget) ? 2 : 1;
    00445         DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, STR_ABBREV_ALL, TC_BLACK, SA_HOR_CENTER);
    00446         break;
    00447       }
    00448
    00449       case WID_STL_FACILALL: {
    00450         int cg_ofst = this->IsWidgetLowered(widget) ? 2 : 1;
    00451         DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, STR_ABBREV_ALL, TC_BLACK);
    00452         break;
    00453       }
    00454
    00455       default:
    00456         if (widget >= WID_STL_CARGOSTART) {
    00457           const CargoSpec *cs = CargoSpec::Get(widget - WID_STL_CARGOSTART);
    00458           if (cs->IsValid()) {
    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             DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, cs->abbrev, TC_BLACK, SA_HOR_CENTER);
    00462           }
    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 < NUM_CARGO; i++) {
    00527           const CargoSpec *cs = CargoSpec::Get(i);
    00528           if (cs->IsValid()) this->LowerWidget(WID_STL_CARGOSTART + i);
    00529         }
    00530         this->LowerWidget(WID_STL_NOCARGOWAITING);
    00531
    00532         this->cargo_filter = _cargo_mask;
    00533         this->include_empty = true;
    00534         this->stations.ForceRebuild();
    00535         this->SetDirty();
    00536         break;
    00537       }
    00538
    00539       case WID_STL_SORTBY: // flip sorting method asc/desc
    00540         this->stations.ToggleSortOrder();
    00541         this->SetTimeout();
    00542         this->LowerWidget(WID_STL_SORTBY);
    00543         this->SetDirty();
    00544         break;
    00545
    00546       case WID_STL_SORTDROPBTN: // select sorting criteria dropdown menu
    00547         ShowDropDownMenu(this, this->sorter_names, this->stations.SortType(), WID_STL_SORTDROPBTN, 0, 0);
    00548         break;
    00549
    00550       case WID_STL_NOCARGOWAITING:
    00551         if (_ctrl_pressed) {
    00552           this->include_empty = !this->include_empty;
    00553           this->ToggleWidgetLoweredState(WID_STL_NOCARGOWAITING);
    00554         } else {
    00555           for (uint i = 0; i < NUM_CARGO; i++) {
    00556             const CargoSpec *cs = CargoSpec::Get(i);
    00557             if (cs->IsValid()) this->RaiseWidget(WID_STL_CARGOSTART + i);
    00558           }
    00559
    00560           this->cargo_filter = 0;
    00561           this->include_empty = true;
    00562
    00563           this->LowerWidget(WID_STL_NOCARGOWAITING);
    00564         }
    00565         this->stations.ForceRebuild();
    00566         this->SetDirty();
    00567         break;
    00568
    00569       default:
    00570         if (widget >= WID_STL_CARGOSTART) { // change cargo_filter
    00571           /* Determine the selected cargo type */
    00572           const CargoSpec *cs = CargoSpec::Get(widget - WID_STL_CARGOSTART);
    00573           if (!cs->IsValid()) break;
    00574
    00575           if (_ctrl_pressed) {
    00576             ToggleBit(this->cargo_filter, cs->Index());
    00577             this->ToggleWidgetLoweredState(widget);
    00578           } else {
    00579             for (uint i = 0; i < NUM_CARGO; i++) {
    00580               const CargoSpec *cs = CargoSpec::Get(i);
    00581               if (cs->IsValid()) this->RaiseWidget(WID_STL_CARGOSTART + i);
    00582             }
    00583             this->RaiseWidget(WID_STL_NOCARGOWAITING);
    00584
    00585             this->cargo_filter = 0;
    00586             this->include_empty = false;
    00587
    00588             SetBit(this->cargo_filter, cs->Index());
    00589             this->LowerWidget(widget);
    00590           }
    00591           this->stations.ForceRebuild();
    00592           this->SetDirty();
    00593         }
    00594         break;
    00595     }
    00596   }
    00597
    00598   virtual void OnDropdownSelect(int widget, int index)
    00599   {
    00600     if (this->stations.SortType() != index) {
    00601       this->stations.SetSortType(index);
    00602
    00603       /* Display the current sort variant */
    00604       this->GetWidget<NWidgetCore>(WID_STL_SORTDROPBTN)->widget_data = this->sorter_names[this->stations.SortType()];
    00605
    00606       this->SetDirty();
    00607     }
    00608   }
    00609
    00610   virtual void OnTick()
    00611   {
    00612     if (_pause_mode != PM_UNPAUSED) return;
    00613     if (this->stations.NeedResort()) {
    00614       DEBUG(misc, 3, "Periodic rebuild station list company %d", this->window_number);
    00615       this->SetDirty();
    00616     }
    00617   }
    00618
    00619   virtual void OnTimeout()
    00620   {
    00621     this->RaiseWidget(WID_STL_SORTBY);
    00622     this->SetDirty();
    00623   }
    00624
    00625   virtual void OnResize()
    00626   {
    00627     this->vscroll->SetCapacityFromWidget(this, WID_STL_LIST, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
    00628   }
    00629
    00635   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
    00636   {
    00637     if (data == 0) {
    00638       /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
    00639       this->stations.ForceRebuild();
    00640     } else {
    00641       this->stations.ForceResort();
    00642     }
    00643   }
    00644 };
    00645
    00646 Listing CompanyStationsWindow::last_sorting = {false, 0};
    00647 byte CompanyStationsWindow::facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK;
    00648 bool CompanyStationsWindow::include_empty = true;
    00649 const uint32 CompanyStationsWindow::cargo_filter_max = UINT32_MAX;
    00650 uint32 CompanyStationsWindow::cargo_filter = UINT32_MAX;
    00651 const Station *CompanyStationsWindow::last_station = NULL;
    00652
    00653 /* Availible station sorting functions */
    00654 GUIStationList::SortFunction * const CompanyStationsWindow::sorter_funcs[] = {
    00655   &StationNameSorter,
    00656   &StationTypeSorter,
    00657   &StationWaitingSorter,
    00658   &StationRatingMaxSorter,
    00659   &StationRatingMinSorter
    00660 };
    00661
    00662 /* Names of the sorting functions */
    00663 const StringID CompanyStationsWindow::sorter_names[] = {
    00664   STR_SORT_BY_NAME,
    00665   STR_SORT_BY_FACILITY,
    00666   STR_SORT_BY_WAITING,
    00667   STR_SORT_BY_RATING_MAX,
    00668   STR_SORT_BY_RATING_MIN,
    00669   INVALID_STRING_ID
    00670 };
    00671
    00677 static NWidgetBase *CargoWidgets(int *biggest_index)
    00678 {
    00679   NWidgetHorizontal *container = new NWidgetHorizontal();
    00680
    00681   for (uint i = 0; i < NUM_CARGO; i++) {
    00682     const CargoSpec *cs = CargoSpec::Get(i);
    00683     if (cs->IsValid()) {
    00684       NWidgetBackground *panel = new NWidgetBackground(WWT_PANEL, COLOUR_GREY, WID_STL_CARGOSTART + i);
    00685       panel->SetMinimalSize(14, 11);
    00686       panel->SetResize(0, 0);
    00687       panel->SetFill(0, 1);
    00688       panel->SetDataTip(0, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE);
    00689       container->Add(panel);
    00690     } else {
    00691       NWidgetLeaf *nwi = new NWidgetLeaf(WWT_EMPTY, COLOUR_GREY, WID_STL_CARGOSTART + i, 0x0, STR_NULL);
    00692       nwi->SetMinimalSize(0, 11);
    00693       nwi->SetResize(0, 0);
    00694       nwi->SetFill(0, 1);
    00695       container->Add(nwi);
    00696     }
    00697   }
    00698   *biggest_index = WID_STL_CARGOSTART + NUM_CARGO;
    00699   return container;
    00700 }
    00701
    00702 static const NWidgetPart _nested_company_stations_widgets[] = {
    00703   NWidget(NWID_HORIZONTAL),
    00704     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
    00705     NWidget(WWT_CAPTION, COLOUR_GREY, WID_STL_CAPTION), SetDataTip(STR_STATION_LIST_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
    00706     NWidget(WWT_SHADEBOX, COLOUR_GREY),
    00707     NWidget(WWT_STICKYBOX, COLOUR_GREY),
    00708   EndContainer(),
    00709   NWidget(NWID_HORIZONTAL),
    00710     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),
    00711     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),
    00712     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),
    00713     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),
    00714     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),
    00715     NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_STL_FACILALL), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_SELECT_ALL_FACILITIES), SetFill(0, 1),
    00716     NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(5, 11), SetFill(0, 1), EndContainer(),
    00717     NWidgetFunction(CargoWidgets),
    00718     NWidget(WWT_PANEL, COLOUR_GREY, WID_STL_NOCARGOWAITING), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_NO_WAITING_CARGO), SetFill(0, 1), EndContainer(),
    00719     NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_STL_CARGOALL), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_SELECT_ALL_TYPES), SetFill(0, 1),
    00720     NWidget(WWT_PANEL, COLOUR_GREY), SetDataTip(0x0, STR_NULL), SetResize(1, 0), SetFill(1, 1), EndContainer(),
    00721   EndContainer(),
    00722   NWidget(NWID_HORIZONTAL),
    00723     NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_STL_SORTBY), SetMinimalSize(81, 12), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
    00724     NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_STL_SORTDROPBTN), SetMinimalSize(163, 12), SetDataTip(STR_SORT_BY_NAME, STR_TOOLTIP_SORT_CRITERIA), // widget_data gets overwritten.
    00725     NWidget(WWT_PANEL, COLOUR_GREY), SetDataTip(0x0, STR_NULL), SetResize(1, 0), SetFill(1, 1), EndContainer(),
    00726   EndContainer(),
    00727   NWidget(NWID_HORIZONTAL),
    00728     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(),
    00729     NWidget(NWID_VERTICAL),
    00730       NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_STL_SCROLLBAR),
    00731       NWidget(WWT_RESIZEBOX, COLOUR_GREY),
    00732     EndContainer(),
    00733   EndContainer(),
    00734 };
    00735
    00736 static const WindowDesc _company_stations_desc(
    00737   WDP_AUTO, 358, 162,
    00738   WC_STATION_LIST, WC_NONE,
    00739   WDF_UNCLICK_BUTTONS,
    00740   _nested_company_stations_widgets, lengthof(_nested_company_stations_widgets)
    00741 );
    00742
    00748 void ShowCompanyStations(CompanyID company)
    00749 {
    00750   if (!Company::IsValidID(company)) return;
    00751
    00752   AllocateWindowDescFront<CompanyStationsWindow>(&_company_stations_desc, company);
    00753 }
    00754
    00755 static const NWidgetPart _nested_station_view_widgets[] = {
    00756   NWidget(NWID_HORIZONTAL),
    00757     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
    00758     NWidget(WWT_CAPTION, COLOUR_GREY, WID_SV_CAPTION), SetDataTip(STR_STATION_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
    00759     NWidget(WWT_SHADEBOX, COLOUR_GREY),
    00760     NWidget(WWT_STICKYBOX, COLOUR_GREY),
    00761   EndContainer(),
    00762   NWidget(NWID_HORIZONTAL),
    00763     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_SORT_ORDER), SetMinimalSize(81, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
    00764     NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_SV_SORT_BY), SetMinimalSize(168, 12), SetResize(1, 0), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
    00765   EndContainer(),
    00766   NWidget(NWID_HORIZONTAL),
    00767     NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_SV_GROUP), SetMinimalSize(81, 12), SetFill(1, 1), SetDataTip(STR_STATION_VIEW_GROUP, 0x0),
    00768     NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_SV_GROUP_BY), SetMinimalSize(168, 12), SetResize(1, 0), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_GROUP_ORDER),
    00769   EndContainer(),
    00770   NWidget(NWID_HORIZONTAL),
    00771     NWidget(WWT_PANEL, COLOUR_GREY, WID_SV_WAITING), SetMinimalSize(237, 44), SetResize(1, 10), SetScrollbar(WID_SV_SCROLLBAR), EndContainer(),
    00772     NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_SV_SCROLLBAR),
    00773   EndContainer(),
    00774   NWidget(WWT_PANEL, COLOUR_GREY, WID_SV_ACCEPT_RATING_LIST), SetMinimalSize(249, 23), SetResize(1, 0), EndContainer(),
    00775   NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
    00776     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_LOCATION), SetMinimalSize(60, 12), SetResize(1, 0), SetFill(1, 1),
    00777         SetDataTip(STR_BUTTON_LOCATION, STR_STATION_VIEW_CENTER_TOOLTIP),
    00778     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_ACCEPTS_RATINGS), SetMinimalSize(61, 12), SetResize(1, 0), SetFill(1, 1),
    00779         SetDataTip(STR_STATION_VIEW_RATINGS_BUTTON, STR_STATION_VIEW_RATINGS_TOOLTIP),
    00780     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_RENAME), SetMinimalSize(60, 12), SetResize(1, 0), SetFill(1, 1),
    00781         SetDataTip(STR_BUTTON_RENAME, STR_STATION_VIEW_RENAME_TOOLTIP),
    00782     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_TRAINS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_TRAIN, STR_STATION_VIEW_SCHEDULED_TRAINS_TOOLTIP),
    00783     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_ROADVEHS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_LORRY, STR_STATION_VIEW_SCHEDULED_ROAD_VEHICLES_TOOLTIP),
    00784     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_SHIPS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_SHIP, STR_STATION_VIEW_SCHEDULED_SHIPS_TOOLTIP),
    00785     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_PLANES),  SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_PLANE, STR_STATION_VIEW_SCHEDULED_AIRCRAFT_TOOLTIP),
    00786     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
    00787   EndContainer(),
    00788 };
    00789
    00800 static void DrawCargoIcons(CargoID i, uint waiting, int left, int right, int y)
    00801 {
    00802   uint num = min((waiting + 5) / 10, (right - left) / 10); // maximum is width / 10 icons so it won't overflow
    00803   if (num == 0) return;
    00804
    00805   SpriteID sprite = CargoSpec::Get(i)->GetCargoIcon();
    00806
    00807   int x = _current_text_dir == TD_RTL ? left : right - num * 10;
    00808   do {
    00809     DrawSprite(sprite, PAL_NONE, x, y);
    00810     x += 10;
    00811   } while (--num);
    00812 }
    00813
    00814 CargoDataEntry::CargoDataEntry() :
    00815   parent(NULL),
    00816   station(INVALID_STATION),
    00817   num_children(0),
    00818   count(0),
    00819   children(new CargoDataSet(CargoSorter(ST_CARGO_ID)))
    00820 {}
    00821
    00822 CargoDataEntry::CargoDataEntry(CargoID cargo, uint count, CargoDataEntry *parent) :
    00823   parent(parent),
    00824   cargo(cargo),
    00825   num_children(0),
    00826   count(count),
    00827   children(new CargoDataSet)
    00828 {}
    00829
    00830 CargoDataEntry::CargoDataEntry(StationID station, uint count, CargoDataEntry *parent) :
    00831   parent(parent),
    00832   station(station),
    00833   num_children(0),
    00834   count(count),
    00835   children(new CargoDataSet)
    00836 {}
    00837
    00838 CargoDataEntry::CargoDataEntry(StationID station) :
    00839   parent(NULL),
    00840   station(station),
    00841   num_children(0),
    00842   count(0),
    00843   children(NULL)
    00844 {}
    00845
    00846 CargoDataEntry::CargoDataEntry(CargoID cargo) :
    00847   parent(NULL),
    00848   cargo(cargo),
    00849   num_children(0),
    00850   count(0),
    00851   children(NULL)
    00852 {}
    00853
    00854 CargoDataEntry::~CargoDataEntry()
    00855 {
    00856   this->Clear();
    00857   delete this->children;
    00858 }
    00859
    00863 void CargoDataEntry::Clear()
    00864 {
    00865   if (this->children != NULL) {
    00866     for (CargoDataSet::iterator i = this->children->begin(); i != this->children->end(); ++i) {
    00867       assert(*i != this);
    00868       delete *i;
    00869     }
    00870     this->children->clear();
    00871   }
    00872   if (this->parent != NULL) this->parent->count -= this->count;
    00873   this->count = 0;
    00874   this->num_children = 0;
    00875 }
    00876
    00883 void CargoDataEntry::Remove(CargoDataEntry *child)
    00884 {
    00885   CargoDataSet::iterator i = this->children->find(child);
    00886   if (i != this->children->end()) {
    00887     delete *i;
    00888     this->children->erase(i);
    00889   }
    00890 }
    00891
    00898 template<class ID>
    00899 CargoDataEntry *CargoDataEntry::InsertOrRetrieve(ID child_id)
    00900 {
    00901   CargoDataEntry tmp(child_id);
    00902   CargoDataSet::iterator i = this->children->find(&tmp);
    00903   if (i == this->children->end()) {
    00904     IncrementSize();
    00905     return *(this->children->insert(new CargoDataEntry(child_id, 0, this)).first);
    00906   } else {
    00907     CargoDataEntry *ret = *i;
    00908     assert(this->children->value_comp().GetSortType() != ST_COUNT);
    00909     return ret;
    00910   }
    00911 }
    00912
    00918 void CargoDataEntry::Update(uint count)
    00919 {
    00920   this->count += count;
    00921   if (this->parent != NULL) this->parent->Update(count);
    00922 }
    00923
    00927 void CargoDataEntry::IncrementSize()
    00928 {
    00929    ++this->num_children;
    00930    if (this->parent != NULL) this->parent->IncrementSize();
    00931 }
    00932
    00933 void CargoDataEntry::Resort(CargoSortType type, SortOrder order)
    00934 {
    00935   CargoDataSet *new_subs = new CargoDataSet(this->children->begin(), this->children->end(), CargoSorter(type, order));
    00936   delete this->children;
    00937   this->children = new_subs;
    00938 }
    00939
    00940 CargoDataEntry *CargoDataEntry::Retrieve(CargoDataSet::iterator i) const
    00941 {
    00942   if (i == this->children->end()) {
    00943     return NULL;
    00944   } else {
    00945     assert(this->children->value_comp().GetSortType() != ST_COUNT);
    00946     return *i;
    00947   }
    00948 }
    00949
    00950 bool CargoSorter::operator()(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const
    00951 {
    00952   switch (this->type) {
    00953     case ST_STATION_ID:
    00954       return this->SortId<StationID>(cd1->GetStation(), cd2->GetStation());
    00955       break;
    00956     case ST_CARGO_ID:
    00957       return this->SortId<CargoID>(cd1->GetCargo(), cd2->GetCargo());
    00958       break;
    00959     case ST_COUNT:
    00960       return this->SortCount(cd1, cd2);
    00961       break;
    00962     case ST_STATION_STRING:
    00963       return this->SortStation(cd1->GetStation(), cd2->GetStation());
    00964       break;
    00965     default:
    00966       NOT_REACHED();
    00967   }
    00968 }
    00969
    00970 template<class ID>
    00971 bool CargoSorter::SortId(ID st1, ID st2) const
    00972 {
    00973   return (this->order == SO_ASCENDING) ? st1 < st2 : st2 < st1;
    00974 }
    00975
    00976 bool CargoSorter::SortCount(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const
    00977 {
    00978   uint c1 = cd1->GetCount();
    00979   uint c2 = cd2->GetCount();
    00980   if (c1 == c2) {
    00981     return this->SortStation(cd1->GetStation(), cd2->GetStation());
    00982   } else if (this->order == SO_ASCENDING) {
    00983     return c1 < c2;
    00984   } else {
    00985     return c2 < c1;
    00986   }
    00987 }
    00988
    00989 bool CargoSorter::SortStation(StationID st1, StationID st2) const
    00990 {
    00991   static char buf1[MAX_LENGTH_STATION_NAME_CHARS];
    00992   static char buf2[MAX_LENGTH_STATION_NAME_CHARS];
    00993
    00994   if (!Station::IsValidID(st1)) {
    00995     return Station::IsValidID(st2) ? this->order == SO_ASCENDING : this->SortId(st1, st2);
    00996   } else if (!Station::IsValidID(st2)) {
    00997     return order == SO_DESCENDING;
    00998   }
    00999
    01000   SetDParam(0, st1);
    01001   GetString(buf1, STR_STATION_NAME, lastof(buf1));
    01002   SetDParam(0, st2);
    01003   GetString(buf2, STR_STATION_NAME, lastof(buf2));
    01004
    01005   int res = strcmp(buf1, buf2);
    01006   if (res == 0) {
    01007     return this->SortId(st1, st2);
    01008   } else {
    01009     return (this->order == SO_ASCENDING) ? res < 0 : res > 0;
    01010   }
    01011 }
    01012
    01016 struct StationViewWindow : public Window {
    01020   struct RowDisplay {
    01021     RowDisplay(CargoDataEntry *f, StationID n) : filter(f), next_station(n) {}
    01022     RowDisplay(CargoDataEntry *f, CargoID n) : filter(f), next_cargo(n) {}
    01023
    01027     CargoDataEntry *filter;
    01028     union {
    01032       StationID next_station;
    01033
    01037       CargoID next_cargo;
    01038     };
    01039   };
    01040
    01041   typedef std::vector<RowDisplay> CargoDataVector;
    01042
    01043   static const int NUM_COLUMNS = 4;
    01044
    01048   enum Invalidation {
    01049     INV_FLOWS = 0x100,
    01050     INV_CARGO = 0x200
    01051   };
    01052
    01056   enum Grouping {
    01057     GR_SOURCE,
    01058     GR_NEXT,
    01059     GR_DESTINATION,
    01060     GR_CARGO,
    01061   };
    01062
    01066   enum Mode {
    01067     MODE_WAITING,
    01068     MODE_PLANNED
    01069   };
    01070
    01071   uint expand_shrink_width;
    01072   int rating_lines;
    01073   int accepts_lines;
    01074   Scrollbar *vscroll;
    01075
    01077   enum AcceptListHeight {
    01078     ALH_RATING  = 13,
    01079     ALH_ACCEPTS = 3,
    01080   };
    01081
    01082   static const StringID _sort_names[];
    01083   static const StringID _group_names[];
    01084
    01091   CargoSortType sortings[NUM_COLUMNS];
    01092
    01094   SortOrder sort_orders[NUM_COLUMNS];
    01095
    01096   int scroll_to_row;
    01097   int grouping_index;
    01098   Mode current_mode;
    01099   Grouping groupings[NUM_COLUMNS];
    01100
    01101   CargoDataEntry expanded_rows;
    01102   CargoDataEntry cached_destinations;
    01103   CargoDataVector displayed_rows;
    01104
    01105   StationViewWindow(const WindowDesc *desc, WindowNumber window_number) : Window(),
    01106     scroll_to_row(INT_MAX), grouping_index(0)
    01107   {
    01108     this->rating_lines  = ALH_RATING;
    01109     this->accepts_lines = ALH_ACCEPTS;
    01110
    01111     this->CreateNestedTree(desc);
    01112     this->vscroll = this->GetScrollbar(WID_SV_SCROLLBAR);
    01113     /* Nested widget tree creation is done in two steps to ensure that this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS) exists in UpdateWidgetSize(). */
    01114     this->FinishInitNested(desc, window_number);
    01115
    01116     this->groupings[0] = GR_CARGO;
    01117     this->sortings[0] = ST_AS_GROUPING;
    01118     this->SelectGroupBy(_settings_client.gui.station_gui_group_order);
    01119     this->SelectSortBy(_settings_client.gui.station_gui_sort_by);
    01120     this->sort_orders[0] = SO_ASCENDING;
    01121     this->SelectSortOrder((SortOrder)_settings_client.gui.station_gui_sort_order);
    01122     Owner owner = Station::Get(window_number)->owner;
    01123     if (owner != OWNER_NONE) this->owner = owner;
    01124   }
    01125
    01126   ~StationViewWindow()
    01127   {
    01128     Owner owner = Station::Get(this->window_number)->owner;
    01129     if (!Company::IsValidID(owner)) owner = _local_company;
    01130     if (!Company::IsValidID(owner)) return; // Spectators
    01131     DeleteWindowById(WC_TRAINS_LIST,   VehicleListIdentifier(VL_STATION_LIST, VEH_TRAIN,    owner, this->window_number).Pack(), false);
    01132     DeleteWindowById(WC_ROADVEH_LIST,  VehicleListIdentifier(VL_STATION_LIST, VEH_ROAD,     owner, this->window_number).Pack(), false);
    01133     DeleteWindowById(WC_SHIPS_LIST,    VehicleListIdentifier(VL_STATION_LIST, VEH_SHIP,     owner, this->window_number).Pack(), false);
    01134     DeleteWindowById(WC_AIRCRAFT_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_AIRCRAFT, owner, this->window_number).Pack(), false);
    01135   }
    01136
    01147   void ShowCargo(CargoDataEntry *data, CargoID cargo, StationID source, StationID next, StationID dest, uint count)
    01148   {
    01149     if (count == 0) return;
    01150     const CargoDataEntry *expand = &this->expanded_rows;
    01151     for (int i = 0; i < NUM_COLUMNS && expand != NULL; ++i) {
    01152       switch (groupings[i]) {
    01153         case GR_CARGO:
    01154           assert(i == 0);
    01155           data = data->InsertOrRetrieve(cargo);
    01156           expand = expand->Retrieve(cargo);
    01157           break;
    01158         case GR_SOURCE:
    01159           data = data->InsertOrRetrieve(source);
    01160           expand = expand->Retrieve(source);
    01161           break;
    01162         case GR_NEXT:
    01163           data = data->InsertOrRetrieve(next);
    01164           expand = expand->Retrieve(next);
    01165           break;
    01166         case GR_DESTINATION:
    01167           data = data->InsertOrRetrieve(dest);
    01168           expand = expand->Retrieve(dest);
    01169           break;
    01170       }
    01171     }
    01172     data->Update(count);
    01173   }
    01174
    01175   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    01176   {
    01177     switch (widget) {
    01178       case WID_SV_WAITING:
    01179         resize->height = FONT_HEIGHT_NORMAL;
    01180         size->height = WD_FRAMERECT_TOP + 4 * resize->height + WD_FRAMERECT_BOTTOM;
    01181         this->expand_shrink_width = max(GetStringBoundingBox("-").width, GetStringBoundingBox("+").width) + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
    01182         break;
    01183
    01184       case WID_SV_ACCEPT_RATING_LIST:
    01185         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;
    01186         break;
    01187     }
    01188   }
    01189
    01190   virtual void OnPaint()
    01191   {
    01192     const Station *st = Station::Get(this->window_number);
    01193     CargoDataEntry cargo;
    01194     BuildCargoList(&cargo, st);
    01195
    01196     this->vscroll->SetCount(cargo.GetNumChildren()); // update scrollbar
    01197
    01198     /* disable some buttons */
    01199     this->SetWidgetDisabledState(WID_SV_RENAME,   st->owner != _local_company);
    01200     this->SetWidgetDisabledState(WID_SV_TRAINS,   !(st->facilities & FACIL_TRAIN));
    01201     this->SetWidgetDisabledState(WID_SV_ROADVEHS, !(st->facilities & FACIL_TRUCK_STOP) && !(st->facilities & FACIL_BUS_STOP));
    01202     this->SetWidgetDisabledState(WID_SV_SHIPS,    !(st->facilities & FACIL_DOCK));
    01203     this->SetWidgetDisabledState(WID_SV_PLANES,   !(st->facilities & FACIL_AIRPORT));
    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         BuildCargoList(i, st->goods[i].cargo, cargo);
    01412       } else {
    01413         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   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
    01581   {
    01582     if (!gui_scope) return;
    01583     this->cached_destinations.Remove((CargoID)data);
    01584   }
    01585
    01591   int DrawAcceptedCargo(const Rect &r) const
    01592   {
    01593     const Station *st = Station::Get(this->window_number);
    01594
    01595     uint32 cargo_mask = 0;
    01596     for (CargoID i = 0; i < NUM_CARGO; i++) {
    01597       if (HasBit(st->goods[i].acceptance_pickup, GoodsEntry::GES_ACCEPTANCE)) SetBit(cargo_mask, i);
    01598     }
    01599     SetDParam(0, cargo_mask);
    01600     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);
    01601     return CeilDiv(bottom - r.top - WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL);
    01602   }
    01603
    01609   int DrawCargoRatings(const Rect &r) const
    01610   {
    01611     const Station *st = Station::Get(this->window_number);
    01612     int y = r.top + WD_FRAMERECT_TOP;
    01613
    01614     DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_VIEW_CARGO_RATINGS_TITLE);
    01615     y += FONT_HEIGHT_NORMAL;
    01616
    01617     const CargoSpec *cs;
    01618     FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
    01619       const GoodsEntry *ge = &st->goods[cs->Index()];
    01620       if (!HasBit(ge->acceptance_pickup, GoodsEntry::GES_PICKUP)) continue;
    01621
    01622       SetDParam(0, cs->name);
    01623       SetDParam(1, ge->supply);
    01624       SetDParam(3, ToPercent8(ge->rating));
    01625       SetDParam(2, STR_CARGO_RATING_APPALLING + (ge->rating >> 5));
    01626       DrawString(r.left + WD_FRAMERECT_LEFT + 6, r.right - WD_FRAMERECT_RIGHT - 6, y, STR_STATION_VIEW_CARGO_SUPPLY_RATING);
    01627       y += FONT_HEIGHT_NORMAL;
    01628     }
    01629     return CeilDiv(y - r.top - WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL);
    01630   }
    01631
    01637   template<class ID>
    01638   void HandleCargoWaitingClick(CargoDataEntry *filter, ID next)
    01639   {
    01640     if (filter->Retrieve(next) != NULL) {
    01641       filter->Remove(next);
    01642     } else {
    01643       filter->InsertOrRetrieve(next);
    01644     }
    01645   }
    01646
    01651   void HandleCargoWaitingClick(int row)
    01652   {
    01653     if (row < 0 || (uint)row >= this->displayed_rows.size()) return;
    01654     if (_ctrl_pressed) {
    01655       this->scroll_to_row = row;
    01656     } else {
    01657       RowDisplay &display = this->displayed_rows[row];
    01658       if (display.filter == &this->expanded_rows) {
    01659         this->HandleCargoWaitingClick<CargoID>(display.filter, display.next_cargo);
    01660       } else {
    01661         this->HandleCargoWaitingClick<StationID>(display.filter, display.next_station);
    01662       }
    01663     }
    01664     this->SetWidgetDirty(WID_SV_WAITING);
    01665   }
    01666
    01667   virtual void OnClick(Point pt, int widget, int click_count)
    01668   {
    01669     switch (widget) {
    01670       case WID_SV_WAITING:
    01671         this->HandleCargoWaitingClick(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_SV_WAITING, WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL) - this->vscroll->GetPosition());
    01672         break;
    01673
    01674       case WID_SV_LOCATION:
    01675         if (_ctrl_pressed) {
    01676           ShowExtraViewPortWindow(Station::Get(this->window_number)->xy);
    01677         } else {
    01678           ScrollMainWindowToTile(Station::Get(this->window_number)->xy);
    01679         }
    01680         break;
    01681
    01682       case WID_SV_ACCEPTS_RATINGS: {
    01683         /* Swap between 'accepts' and 'ratings' view. */
    01684         int height_change;
    01685         NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS);
    01686         if (this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) {
    01687           nwi->SetDataTip(STR_STATION_VIEW_ACCEPTS_BUTTON, STR_STATION_VIEW_ACCEPTS_TOOLTIP); // Switch to accepts view.
    01688           height_change = this->rating_lines - this->accepts_lines;
    01689         } else {
    01690           nwi->SetDataTip(STR_STATION_VIEW_RATINGS_BUTTON, STR_STATION_VIEW_RATINGS_TOOLTIP); // Switch to ratings view.
    01691           height_change = this->accepts_lines - this->rating_lines;
    01692         }
    01693         this->ReInit(0, height_change * FONT_HEIGHT_NORMAL);
    01694         break;
    01695       }
    01696
    01697       case WID_SV_RENAME:
    01698         SetDParam(0, this->window_number);
    01699         ShowQueryString(STR_STATION_NAME, STR_STATION_VIEW_RENAME_STATION_CAPTION, MAX_LENGTH_STATION_NAME_CHARS,
    01700             this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
    01701         break;
    01702
    01703       case WID_SV_TRAINS:   // Show list of scheduled trains to this station
    01704       case WID_SV_ROADVEHS: // Show list of scheduled road-vehicles to this station
    01705       case WID_SV_SHIPS:    // Show list of scheduled ships to this station
    01706       case WID_SV_PLANES:   // Show list of scheduled aircraft to this station
    01707         ShowVehicleListWindow(this->owner, (VehicleType)(widget - WID_SV_TRAINS), (StationID)this->window_number);
    01708         break;
    01709
    01710       case WID_SV_SORT_BY: {
    01711         ShowDropDownMenu(this, _sort_names, this->current_mode, WID_SV_SORT_BY, 0, 0);
    01712         break;
    01713       }
    01714
    01715       case WID_SV_GROUP_BY: {
    01716         ShowDropDownMenu(this, _group_names, this->grouping_index, WID_SV_GROUP_BY, 0, 0);
    01717         break;
    01718       }
    01719
    01720       case WID_SV_SORT_ORDER: { // flip sorting method asc/desc
    01721         this->SelectSortOrder(this->sort_orders[1] == SO_ASCENDING ? SO_DESCENDING : SO_ASCENDING);
    01722         this->SetTimeout();
    01723         this->LowerWidget(WID_SV_SORT_ORDER);
    01724         break;
    01725       }
    01726     }
    01727   }
    01728
    01733   void SelectSortOrder(SortOrder order)
    01734   {
    01735     this->sort_orders[1] = this->sort_orders[2] = this->sort_orders[3] = order;
    01736     _settings_client.gui.station_gui_sort_order = this->sort_orders[1];
    01737     this->SetDirty();
    01738   }
    01739
    01744   void SelectSortBy(int index)
    01745   {
    01746     _settings_client.gui.station_gui_sort_by = index;
    01747     switch (_sort_names[index]) {
    01748       case STR_STATION_VIEW_WAITING_STATION:
    01749         this->current_mode = MODE_WAITING;
    01750         this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_AS_GROUPING;
    01751         break;
    01752       case STR_STATION_VIEW_WAITING_AMOUNT:
    01753         this->current_mode = MODE_WAITING;
    01754         this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_COUNT;
    01755         break;
    01756       case STR_STATION_VIEW_PLANNED_STATION:
    01757         this->current_mode = MODE_PLANNED;
    01758         this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_AS_GROUPING;
    01759         break;
    01760       case STR_STATION_VIEW_PLANNED_AMOUNT:
    01761         this->current_mode = MODE_PLANNED;
    01762         this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_COUNT;
    01763         break;
    01764       default:
    01765         NOT_REACHED();
    01766     }
    01767     /* Display the current sort variant */
    01768     this->GetWidget<NWidgetCore>(WID_SV_SORT_BY)->widget_data = _sort_names[index];
    01769     this->SetDirty();
    01770   }
    01771
    01776   void SelectGroupBy(int index)
    01777   {
    01778     this->grouping_index = index;
    01779     _settings_client.gui.station_gui_group_order = index;
    01780     this->GetWidget<NWidgetCore>(WID_SV_GROUP_BY)->widget_data = _group_names[index];
    01781     switch (_group_names[index]) {
    01782       case STR_STATION_VIEW_GROUP_S_V_D:
    01783         this->groupings[1] = GR_SOURCE;
    01784         this->groupings[2] = GR_NEXT;
    01785         this->groupings[3] = GR_DESTINATION;
    01786         break;
    01787       case STR_STATION_VIEW_GROUP_S_D_V:
    01788         this->groupings[1] = GR_SOURCE;
    01789         this->groupings[2] = GR_DESTINATION;
    01790         this->groupings[3] = GR_NEXT;
    01791         break;
    01792       case STR_STATION_VIEW_GROUP_V_S_D:
    01793         this->groupings[1] = GR_NEXT;
    01794         this->groupings[2] = GR_SOURCE;
    01795         this->groupings[3] = GR_DESTINATION;
    01796         break;
    01797       case STR_STATION_VIEW_GROUP_V_D_S:
    01798         this->groupings[1] = GR_NEXT;
    01799         this->groupings[2] = GR_DESTINATION;
    01800         this->groupings[3] = GR_SOURCE;
    01801         break;
    01802       case STR_STATION_VIEW_GROUP_D_S_V:
    01803         this->groupings[1] = GR_DESTINATION;
    01804         this->groupings[2] = GR_SOURCE;
    01805         this->groupings[3] = GR_NEXT;
    01806         break;
    01807       case STR_STATION_VIEW_GROUP_D_V_S:
    01808         this->groupings[1] = GR_DESTINATION;
    01809         this->groupings[2] = GR_NEXT;
    01810         this->groupings[3] = GR_SOURCE;
    01811         break;
    01812     }
    01813     this->SetDirty();
    01814   }
    01815
    01816   virtual void OnDropdownSelect(int widget, int index)
    01817   {
    01818     if (widget == WID_SV_SORT_BY) {
    01819       this->SelectSortBy(index);
    01820     } else {
    01821       this->SelectGroupBy(index);
    01822     }
    01823   }
    01824
    01825   virtual void OnQueryTextFinished(char *str)
    01826   {
    01827     if (str == NULL) return;
    01828
    01829     DoCommandP(0, this->window_number, 0, CMD_RENAME_STATION | CMD_MSG(STR_ERROR_CAN_T_RENAME_STATION), NULL, str);
    01830   }
    01831
    01832   virtual void OnResize()
    01833   {
    01834     this->vscroll->SetCapacityFromWidget(this, WID_SV_WAITING, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
    01835   }
    01836 };
    01837
    01838 const StringID StationViewWindow::_sort_names[] = {
    01839   STR_STATION_VIEW_WAITING_STATION,
    01840   STR_STATION_VIEW_WAITING_AMOUNT,
    01841   STR_STATION_VIEW_PLANNED_STATION,
    01842   STR_STATION_VIEW_PLANNED_AMOUNT,
    01843   INVALID_STRING_ID
    01844 };
    01845
    01846 const StringID StationViewWindow::_group_names[] = {
    01847   STR_STATION_VIEW_GROUP_S_V_D,
    01848   STR_STATION_VIEW_GROUP_S_D_V,
    01849   STR_STATION_VIEW_GROUP_V_S_D,
    01850   STR_STATION_VIEW_GROUP_V_D_S,
    01851   STR_STATION_VIEW_GROUP_D_S_V,
    01852   STR_STATION_VIEW_GROUP_D_V_S,
    01853   INVALID_STRING_ID
    01854 };
    01855
    01856 static const WindowDesc _station_view_desc(
    01857   WDP_AUTO, 249, 117,
    01858   WC_STATION_VIEW, WC_NONE,
    01859   WDF_UNCLICK_BUTTONS,
    01860   _nested_station_view_widgets, lengthof(_nested_station_view_widgets)
    01861 );
    01862
    01868 void ShowStationViewWindow(StationID station)
    01869 {
    01870   AllocateWindowDescFront<StationViewWindow>(&_station_view_desc, station);
    01871 }
    01872
    01874 struct TileAndStation {
    01875   TileIndex tile;
    01876   StationID station;
    01877 };
    01878
    01879 static SmallVector<TileAndStation, 8> _deleted_stations_nearby;
    01880 static SmallVector<StationID, 8> _stations_nearby_list;
    01881
    01889 template <class T>
    01890 static bool AddNearbyStation(TileIndex tile, void *user_data)
    01891 {
    01892   TileArea *ctx = (TileArea *)user_data;
    01893
    01894   /* First check if there were deleted stations here */
    01895   for (uint i = 0; i < _deleted_stations_nearby.Length(); i++) {
    01896     TileAndStation *ts = _deleted_stations_nearby.Get(i);
    01897     if (ts->tile == tile) {
    01898       *_stations_nearby_list.Append() = _deleted_stations_nearby[i].station;
    01899       _deleted_stations_nearby.Erase(ts);
    01900       i--;
    01901     }
    01902   }
    01903
    01904   /* Check if own station and if we stay within station spread */
    01905   if (!IsTileType(tile, MP_STATION)) return false;
    01906
    01907   StationID sid = GetStationIndex(tile);
    01908
    01909   /* This station is (likely) a waypoint */
    01910   if (!T::IsValidID(sid)) return false;
    01911
    01912   T *st = T::Get(sid);
    01913   if (st->owner != _local_company || _stations_nearby_list.Contains(sid)) return false;
    01914
    01915   if (st->rect.BeforeAddRect(ctx->tile, ctx->w, ctx->h, StationRect::ADD_TEST).Succeeded()) {
    01916     *_stations_nearby_list.Append() = sid;
    01917   }
    01918
    01919   return false; // We want to include *all* nearby stations
    01920 }
    01921
    01931 template <class T>
    01932 static const T *FindStationsNearby(TileArea ta, bool distant_join)
    01933 {
    01934   TileArea ctx = ta;
    01935
    01936   _stations_nearby_list.Clear();
    01937   _deleted_stations_nearby.Clear();
    01938
    01939   /* Check the inside, to return, if we sit on another station */
    01940   TILE_AREA_LOOP(t, ta) {
    01941     if (t < MapSize() && IsTileType(t, MP_STATION) && T::IsValidID(GetStationIndex(t))) return T::GetByTile(t);
    01942   }
    01943
    01944   /* Look for deleted stations */
    01945   const BaseStation *st;
    01946   FOR_ALL_BASE_STATIONS(st) {
    01947     if (T::IsExpected(st) && !st->IsInUse() && st->owner == _local_company) {
    01948       /* Include only within station spread (yes, it is strictly less than) */
    01949       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) {
    01950         TileAndStation *ts = _deleted_stations_nearby.Append();
    01951         ts->tile = st->xy;
    01952         ts->station = st->index;
    01953
    01954         /* Add the station when it's within where we're going to build */
    01955         if (IsInsideBS(TileX(st->xy), TileX(ctx.tile), ctx.w) &&
    01956             IsInsideBS(TileY(st->xy), TileY(ctx.tile), ctx.h)) {
    01957           AddNearbyStation<T>(st->xy, &ctx);
    01958         }
    01959       }
    01960     }
    01961   }
    01962
    01963   /* Only search tiles where we have a chance to stay within the station spread.
    01964    * The complete check needs to be done in the callback as we don't know the
    01965    * extent of the found station, yet. */
    01966   if (distant_join && min(ta.w, ta.h) >= _settings_game.station.station_spread) return NULL;
    01967   uint max_dist = distant_join ? _settings_game.station.station_spread - min(ta.w, ta.h) : 1;
    01968
    01969   TileIndex tile = TILE_ADD(ctx.tile, TileOffsByDir(DIR_N));
    01970   CircularTileSearch(&tile, max_dist, ta.w, ta.h, AddNearbyStation<T>, &ctx);
    01971
    01972   return NULL;
    01973 }
    01974
    01975 static const NWidgetPart _nested_select_station_widgets[] = {
    01976   NWidget(NWID_HORIZONTAL),
    01977     NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
    01978     NWidget(WWT_CAPTION, COLOUR_DARK_GREEN, WID_JS_CAPTION), SetDataTip(STR_JOIN_STATION_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
    01979   EndContainer(),
    01980   NWidget(NWID_HORIZONTAL),
    01981     NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_JS_PANEL), SetResize(1, 0), SetScrollbar(WID_JS_SCROLLBAR), EndContainer(),
    01982     NWidget(NWID_VERTICAL),
    01983       NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, WID_JS_SCROLLBAR),
    01984       NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
    01985     EndContainer(),
    01986   EndContainer(),
    01987 };
    01988
    01993 template <class T>
    01994 struct SelectStationWindow : Window {
    01995   CommandContainer select_station_cmd;
    01996   TileArea area;
    01997   Scrollbar *vscroll;
    01998
    01999   SelectStationWindow(const WindowDesc *desc, CommandContainer cmd, TileArea ta) :
    02000     Window(),
    02001     select_station_cmd(cmd),
    02002     area(ta)
    02003   {
    02004     this->CreateNestedTree(desc);
    02005     this->vscroll = this->GetScrollbar(WID_JS_SCROLLBAR);
    02006     this->GetWidget<NWidgetCore>(WID_JS_CAPTION)->widget_data = T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_JOIN_WAYPOINT_CAPTION : STR_JOIN_STATION_CAPTION;
    02007     this->FinishInitNested(desc, 0);
    02008     this->OnInvalidateData(0);
    02009   }
    02010
    02011   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    02012   {
    02013     if (widget != WID_JS_PANEL) return;
    02014
    02015     /* Determine the widest string */
    02016     Dimension d = GetStringBoundingBox(T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_JOIN_WAYPOINT_CREATE_SPLITTED_WAYPOINT : STR_JOIN_STATION_CREATE_SPLITTED_STATION);
    02017     for (uint i = 0; i < _stations_nearby_list.Length(); i++) {
    02018       const T *st = T::Get(_stations_nearby_list[i]);
    02019       SetDParam(0, st->index);
    02020       SetDParam(1, st->facilities);
    02021       d = maxdim(d, GetStringBoundingBox(T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_STATION_LIST_WAYPOINT : STR_STATION_LIST_STATION));
    02022     }
    02023
    02024     resize->height = d.height;
    02025     d.height *= 5;
    02026     d.width += WD_FRAMERECT_RIGHT + WD_FRAMERECT_LEFT;
    02027     d.height += WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
    02028     *size = d;
    02029   }
    02030
    02031   virtual void DrawWidget(const Rect &r, int widget) const
    02032   {
    02033     if (widget != WID_JS_PANEL) return;
    02034
    02035     uint y = r.top + WD_FRAMERECT_TOP;
    02036     if (this->vscroll->GetPosition() == 0) {
    02037       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);
    02038       y += this->resize.step_height;
    02039     }
    02040
    02041     for (uint i = max<uint>(1, this->vscroll->GetPosition()); i <= _stations_nearby_list.Length(); ++i, y += this->resize.step_height) {
    02042       /* Don't draw anything if it extends past the end of the window. */
    02043       if (i - this->vscroll->GetPosition() >= this->vscroll->GetCapacity()) break;
    02044
    02045       const T *st = T::Get(_stations_nearby_list[i - 1]);
    02046       SetDParam(0, st->index);
    02047       SetDParam(1, st->facilities);
    02048       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);
    02049     }
    02050   }
    02051
    02052   virtual void OnClick(Point pt, int widget, int click_count)
    02053   {
    02054     if (widget != WID_JS_PANEL) return;
    02055
    02056     uint st_index = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_JS_PANEL, WD_FRAMERECT_TOP);
    02057     bool distant_join = (st_index > 0);
    02058     if (distant_join) st_index--;
    02059
    02060     if (distant_join && st_index >= _stations_nearby_list.Length()) return;
    02061
    02062     /* Insert station to be joined into stored command */
    02063     SB(this->select_station_cmd.p2, 16, 16,
    02064        (distant_join ? _stations_nearby_list[st_index] : NEW_STATION));
    02065
    02066     /* Execute stored Command */
    02067     DoCommandP(&this->select_station_cmd);
    02068
    02069     /* Close Window; this might cause double frees! */
    02070     DeleteWindowById(WC_SELECT_STATION, 0);
    02071   }
    02072
    02073   virtual void OnTick()
    02074   {
    02075     if (_thd.dirty & 2) {
    02076       _thd.dirty &= ~2;
    02077       this->SetDirty();
    02078     }
    02079   }
    02080
    02081   virtual void OnResize()
    02082   {
    02083     this->vscroll->SetCapacityFromWidget(this, WID_JS_PANEL, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
    02084   }
    02085
    02091   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
    02092   {
    02093     if (!gui_scope) return;
    02094     FindStationsNearby<T>(this->area, true);
    02095     this->vscroll->SetCount(_stations_nearby_list.Length() + 1);
    02096     this->SetDirty();
    02097   }
    02098 };
    02099
    02100 static const WindowDesc _select_station_desc(
    02101   WDP_AUTO, 200, 180,
    02102   WC_SELECT_STATION, WC_NONE,
    02103   WDF_CONSTRUCTION,
    02104   _nested_select_station_widgets, lengthof(_nested_select_station_widgets)
    02105 );
    02106
    02107
    02115 template <class T>
    02116 static bool StationJoinerNeeded(CommandContainer cmd, TileArea ta)
    02117 {
    02118   /* Only show selection if distant join is enabled in the settings */
    02119   if (!_settings_game.station.distant_join_stations) return false;
    02120
    02121   /* If a window is already opened and we didn't ctrl-click,
    02122    * return true (i.e. just flash the old window) */
    02123   Window *selection_window = FindWindowById(WC_SELECT_STATION, 0);
    02124   if (selection_window != NULL) {
    02125     /* Abort current distant-join and start new one */
    02126     delete selection_window;
    02127     UpdateTileSelection();
    02128   }
    02129
    02130   /* only show the popup, if we press ctrl */
    02131   if (!_ctrl_pressed) return false;
    02132
    02133   /* Now check if we could build there */
    02134   if (DoCommand(&cmd, CommandFlagsToDCFlags(GetCommandFlags(cmd.cmd))).Failed()) return false;
    02135
    02136   /* Test for adjacent station or station below selection.
    02137    * If adjacent-stations is disabled and we are building next to a station, do not show the selection window.
    02138    * but join the other station immediately. */
    02139   const T *st = FindStationsNearby<T>(ta, false);
    02140   return st == NULL && (_settings_game.station.adjacent_stations || _stations_nearby_list.Length() == 0);
    02141 }
    02142
    02149 template <class T>
    02150 void ShowSelectBaseStationIfNeeded(CommandContainer cmd, TileArea ta)
    02151 {
    02152   if (StationJoinerNeeded<T>(cmd, ta)) {
    02153     if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
    02154     new SelectStationWindow<T>(&_select_station_desc, cmd, ta);
    02155   } else {
    02156     DoCommandP(&cmd);
    02157   }
    02158 }
    02159
    02165 void ShowSelectStationIfNeeded(CommandContainer cmd, TileArea ta)
    02166 {
    02167   ShowSelectBaseStationIfNeeded<Station>(cmd, ta);
    02168 }
    02169
    02175 void ShowSelectWaypointIfNeeded(CommandContainer cmd, TileArea ta)
    02176 {
    02177   ShowSelectBaseStationIfNeeded<Waypoint>(cmd, ta);
    02178 }