station_gui.cpp

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

Generated on Fri May 27 04:19:49 2011 for OpenTTD by  doxygen 1.6.1