station_gui.cpp

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