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