station_gui.cpp

Go to the documentation of this file.
00001 /* $Id: station_gui.cpp 24703 2012-11-12 18:09:33Z frosch $ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 #include "debug.h"
00014 #include "gui.h"
00015 #include "textbuf_gui.h"
00016 #include "company_func.h"
00017 #include "command_func.h"
00018 #include "vehicle_gui.h"
00019 #include "cargotype.h"
00020 #include "station_gui.h"
00021 #include "strings_func.h"
00022 #include "window_func.h"
00023 #include "viewport_func.h"
00024 #include "widgets/dropdown_func.h"
00025 #include "station_base.h"
00026 #include "waypoint_base.h"
00027 #include "tilehighlight_func.h"
00028 #include "company_base.h"
00029 #include "sortlist_type.h"
00030 #include "core/geometry_func.hpp"
00031 #include "vehiclelist.h"
00032 #include "town.h"
00033 
00034 #include "widgets/station_widget.h"
00035 
00036 #include "table/strings.h"
00037 
00048 int DrawStationCoverageAreaText(int left, int right, int top, StationCoverageType sct, int rad, bool supplies)
00049 {
00050   TileIndex tile = TileVirtXY(_thd.pos.x, _thd.pos.y);
00051   uint32 cargo_mask = 0;
00052   if (_thd.drawstyle == HT_RECT && tile < MapSize()) {
00053     CargoArray cargoes;
00054     if (supplies) {
00055       cargoes = GetProductionAroundTiles(tile, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE, rad);
00056     } else {
00057       cargoes = GetAcceptanceAroundTiles(tile, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE, rad);
00058     }
00059 
00060     /* Convert cargo counts to a set of cargo bits, and draw the result. */
00061     for (CargoID i = 0; i < NUM_CARGO; i++) {
00062       switch (sct) {
00063         case SCT_PASSENGERS_ONLY: if (!IsCargoInClass(i, CC_PASSENGERS)) continue; break;
00064         case SCT_NON_PASSENGERS_ONLY: if (IsCargoInClass(i, CC_PASSENGERS)) continue; break;
00065         case SCT_ALL: break;
00066         default: NOT_REACHED();
00067       }
00068       if (cargoes[i] >= (supplies ? 1U : 8U)) SetBit(cargo_mask, i);
00069     }
00070   }
00071   SetDParam(0, cargo_mask);
00072   return DrawStringMultiLine(left, right, top, INT32_MAX, supplies ? STR_STATION_BUILD_SUPPLIES_CARGO : STR_STATION_BUILD_ACCEPTS_CARGO);
00073 }
00074 
00080 void CheckRedrawStationCoverage(const Window *w)
00081 {
00082   if (_thd.dirty & 1) {
00083     _thd.dirty &= ~1;
00084     w->SetDirty();
00085   }
00086 }
00087 
00103 static void StationsWndShowStationRating(int left, int right, int y, CargoID type, uint amount, byte rating)
00104 {
00105   static const uint units_full  = 576; 
00106   static const uint rating_full = 224; 
00107 
00108   const CargoSpec *cs = CargoSpec::Get(type);
00109   if (!cs->IsValid()) return;
00110 
00111   int colour = cs->rating_colour;
00112   TextColour tc = GetContrastColour(colour);
00113   uint w = (minu(amount, units_full) + 5) / 36;
00114 
00115   int height = GetCharacterHeight(FS_SMALL);
00116 
00117   /* Draw total cargo (limited) on station (fits into 16 pixels) */
00118   if (w != 0) GfxFillRect(left, y, left + w - 1, y + height, colour);
00119 
00120   /* Draw a one pixel-wide bar of additional cargo meter, useful
00121    * for stations with only a small amount (<=30) */
00122   if (w == 0) {
00123     uint rest = amount / 5;
00124     if (rest != 0) {
00125       w += left;
00126       GfxFillRect(w, y + height - rest, w, y + height, colour);
00127     }
00128   }
00129 
00130   DrawString(left + 1, right, y, cs->abbrev, tc);
00131 
00132   /* Draw green/red ratings bar (fits into 14 pixels) */
00133   y += height + 2;
00134   GfxFillRect(left + 1, y, left + 14, y, PC_RED);
00135   rating = minu(rating, rating_full) / 16;
00136   if (rating != 0) GfxFillRect(left + 1, y, left + rating, y, PC_GREEN);
00137 }
00138 
00139 typedef GUIList<const Station*> GUIStationList;
00140 
00144 class CompanyStationsWindow : public Window
00145 {
00146 protected:
00147   /* Runtime saved values */
00148   static Listing last_sorting;
00149   static byte facilities;               // types of stations of interest
00150   static bool include_empty;            // whether we should include stations without waiting cargo
00151   static const uint32 cargo_filter_max;
00152   static uint32 cargo_filter;           // bitmap of cargo types to include
00153   static const Station *last_station;
00154 
00155   /* Constants for sorting stations */
00156   static const StringID sorter_names[];
00157   static GUIStationList::SortFunction * const sorter_funcs[];
00158 
00159   GUIStationList stations;
00160   Scrollbar *vscroll;
00161 
00167   void BuildStationsList(const Owner owner)
00168   {
00169     if (!this->stations.NeedRebuild()) return;
00170 
00171     DEBUG(misc, 3, "Building station list for company %d", owner);
00172 
00173     this->stations.Clear();
00174 
00175     const Station *st;
00176     FOR_ALL_STATIONS(st) {
00177       if (st->owner == owner || (st->owner == OWNER_NONE && HasStationInUse(st->index, true, owner))) {
00178         if (this->facilities & st->facilities) { // only stations with selected facilities
00179           int num_waiting_cargo = 0;
00180           for (CargoID j = 0; j < NUM_CARGO; j++) {
00181             if (HasBit(st->goods[j].acceptance_pickup, GoodsEntry::GES_PICKUP)) {
00182               num_waiting_cargo++; // count number of waiting cargo
00183               if (HasBit(this->cargo_filter, j)) {
00184                 *this->stations.Append() = st;
00185                 break;
00186               }
00187             }
00188           }
00189           /* stations without waiting cargo */
00190           if (num_waiting_cargo == 0 && this->include_empty) {
00191             *this->stations.Append() = st;
00192           }
00193         }
00194       }
00195     }
00196 
00197     this->stations.Compact();
00198     this->stations.RebuildDone();
00199 
00200     this->vscroll->SetCount(this->stations.Length()); // Update the scrollbar
00201   }
00202 
00204   static int CDECL StationNameSorter(const Station * const *a, const Station * const *b)
00205   {
00206     static char buf_cache[64];
00207     char buf[64];
00208 
00209     SetDParam(0, (*a)->index);
00210     GetString(buf, STR_STATION_NAME, lastof(buf));
00211 
00212     if (*b != last_station) {
00213       last_station = *b;
00214       SetDParam(0, (*b)->index);
00215       GetString(buf_cache, STR_STATION_NAME, lastof(buf_cache));
00216     }
00217 
00218     return strcmp(buf, buf_cache);
00219   }
00220 
00222   static int CDECL StationTypeSorter(const Station * const *a, const Station * const *b)
00223   {
00224     return (*a)->facilities - (*b)->facilities;
00225   }
00226 
00228   static int CDECL StationWaitingSorter(const Station * const *a, const Station * const *b)
00229   {
00230     Money diff = 0;
00231 
00232     CargoID j;
00233     FOR_EACH_SET_CARGO_ID(j, cargo_filter) {
00234       if (!(*a)->goods[j].cargo.Empty()) diff += GetTransportedGoodsIncome((*a)->goods[j].cargo.Count(), 20, 50, j);
00235       if (!(*b)->goods[j].cargo.Empty()) diff -= GetTransportedGoodsIncome((*b)->goods[j].cargo.Count(), 20, 50, j);
00236     }
00237 
00238     return ClampToI32(diff);
00239   }
00240 
00242   static int CDECL StationRatingMaxSorter(const Station * const *a, const Station * const *b)
00243   {
00244     byte maxr1 = 0;
00245     byte maxr2 = 0;
00246 
00247     CargoID j;
00248     FOR_EACH_SET_CARGO_ID(j, cargo_filter) {
00249       if (HasBit((*a)->goods[j].acceptance_pickup, GoodsEntry::GES_PICKUP)) maxr1 = max(maxr1, (*a)->goods[j].rating);
00250       if (HasBit((*b)->goods[j].acceptance_pickup, GoodsEntry::GES_PICKUP)) maxr2 = max(maxr2, (*b)->goods[j].rating);
00251     }
00252 
00253     return maxr1 - maxr2;
00254   }
00255 
00257   static int CDECL StationRatingMinSorter(const Station * const *a, const Station * const *b)
00258   {
00259     byte minr1 = 255;
00260     byte minr2 = 255;
00261 
00262     for (CargoID j = 0; j < NUM_CARGO; j++) {
00263       if (!HasBit(cargo_filter, j)) continue;
00264       if (HasBit((*a)->goods[j].acceptance_pickup, GoodsEntry::GES_PICKUP)) minr1 = min(minr1, (*a)->goods[j].rating);
00265       if (HasBit((*b)->goods[j].acceptance_pickup, GoodsEntry::GES_PICKUP)) minr2 = min(minr2, (*b)->goods[j].rating);
00266     }
00267 
00268     return -(minr1 - minr2);
00269   }
00270 
00272   void SortStationsList()
00273   {
00274     if (!this->stations.Sort()) return;
00275 
00276     /* Reset name sorter sort cache */
00277     this->last_station = NULL;
00278 
00279     /* Set the modified widget dirty */
00280     this->SetWidgetDirty(WID_STL_LIST);
00281   }
00282 
00283 public:
00284   CompanyStationsWindow(const WindowDesc *desc, WindowNumber window_number) : Window()
00285   {
00286     this->stations.SetListing(this->last_sorting);
00287     this->stations.SetSortFuncs(this->sorter_funcs);
00288     this->stations.ForceRebuild();
00289     this->stations.NeedResort();
00290     this->SortStationsList();
00291 
00292     this->CreateNestedTree(desc);
00293     this->vscroll = this->GetScrollbar(WID_STL_SCROLLBAR);
00294     this->FinishInitNested(desc, window_number);
00295     this->owner = (Owner)this->window_number;
00296 
00297     const CargoSpec *cs;
00298     FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
00299       if (!HasBit(this->cargo_filter, cs->Index())) continue;
00300       this->LowerWidget(WID_STL_CARGOSTART + index);
00301     }
00302 
00303     if (this->cargo_filter == this->cargo_filter_max) this->cargo_filter = _cargo_mask;
00304 
00305     for (uint i = 0; i < 5; i++) {
00306       if (HasBit(this->facilities, i)) this->LowerWidget(i + WID_STL_TRAIN);
00307     }
00308     this->SetWidgetLoweredState(WID_STL_NOCARGOWAITING, this->include_empty);
00309 
00310     this->GetWidget<NWidgetCore>(WID_STL_SORTDROPBTN)->widget_data = this->sorter_names[this->stations.SortType()];
00311   }
00312 
00313   ~CompanyStationsWindow()
00314   {
00315     this->last_sorting = this->stations.GetListing();
00316   }
00317 
00318   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00319   {
00320     switch (widget) {
00321       case WID_STL_SORTBY: {
00322         Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
00323         d.width += padding.width + WD_SORTBUTTON_ARROW_WIDTH * 2; // Doubled since the string is centred and it also looks better.
00324         d.height += padding.height;
00325         *size = maxdim(*size, d);
00326         break;
00327       }
00328 
00329       case WID_STL_SORTDROPBTN: {
00330         Dimension d = {0, 0};
00331         for (int i = 0; this->sorter_names[i] != INVALID_STRING_ID; i++) {
00332           d = maxdim(d, GetStringBoundingBox(this->sorter_names[i]));
00333         }
00334         d.width += padding.width;
00335         d.height += padding.height;
00336         *size = maxdim(*size, d);
00337         break;
00338       }
00339 
00340       case WID_STL_LIST:
00341         resize->height = FONT_HEIGHT_NORMAL;
00342         size->height = WD_FRAMERECT_TOP + 5 * resize->height + WD_FRAMERECT_BOTTOM;
00343         break;
00344 
00345       case WID_STL_TRAIN:
00346       case WID_STL_TRUCK:
00347       case WID_STL_BUS:
00348       case WID_STL_AIRPLANE:
00349       case WID_STL_SHIP:
00350         size->height = max<uint>(FONT_HEIGHT_SMALL, 10) + padding.height;
00351         break;
00352 
00353       case WID_STL_CARGOALL:
00354       case WID_STL_FACILALL:
00355       case WID_STL_NOCARGOWAITING: {
00356         Dimension d = GetStringBoundingBox(widget == WID_STL_NOCARGOWAITING ? STR_ABBREV_NONE : STR_ABBREV_ALL);
00357         d.width  += padding.width + 2;
00358         d.height += padding.height;
00359         *size = maxdim(*size, d);
00360         break;
00361       }
00362 
00363       default:
00364         if (widget >= WID_STL_CARGOSTART) {
00365           Dimension d = GetStringBoundingBox(_sorted_cargo_specs[widget - WID_STL_CARGOSTART]->abbrev);
00366           d.width  += padding.width + 2;
00367           d.height += padding.height;
00368           *size = maxdim(*size, d);
00369         }
00370         break;
00371     }
00372   }
00373 
00374   virtual void OnPaint()
00375   {
00376     this->BuildStationsList((Owner)this->window_number);
00377     this->SortStationsList();
00378 
00379     this->DrawWidgets();
00380   }
00381 
00382   virtual void DrawWidget(const Rect &r, int widget) const
00383   {
00384     switch (widget) {
00385       case WID_STL_SORTBY:
00386         /* draw arrow pointing up/down for ascending/descending sorting */
00387         this->DrawSortButtonState(WID_STL_SORTBY, this->stations.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
00388         break;
00389 
00390       case WID_STL_LIST: {
00391         bool rtl = _current_text_dir == TD_RTL;
00392         int max = min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->stations.Length());
00393         int y = r.top + WD_FRAMERECT_TOP;
00394         for (int i = this->vscroll->GetPosition(); i < max; ++i) { // do until max number of stations of owner
00395           const Station *st = this->stations[i];
00396           assert(st->xy != INVALID_TILE);
00397 
00398           /* Do not do the complex check HasStationInUse here, it may be even false
00399            * when the order had been removed and the station list hasn't been removed yet */
00400           assert(st->owner == owner || st->owner == OWNER_NONE);
00401 
00402           SetDParam(0, st->index);
00403           SetDParam(1, st->facilities);
00404           int x = DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_LIST_STATION);
00405           x += rtl ? -5 : 5;
00406 
00407           /* show cargo waiting and station ratings */
00408           for (uint j = 0; j < _sorted_standard_cargo_specs_size; j++) {
00409             CargoID cid = _sorted_cargo_specs[j]->Index();
00410             if (!st->goods[cid].cargo.Empty()) {
00411               /* For RTL we work in exactly the opposite direction. So
00412                * decrement the space needed first, then draw to the left
00413                * instead of drawing to the left and then incrementing
00414                * the space. */
00415               if (rtl) {
00416                 x -= 20;
00417                 if (x < r.left + WD_FRAMERECT_LEFT) break;
00418               }
00419               StationsWndShowStationRating(x, x + 16, y, cid, st->goods[cid].cargo.Count(), st->goods[cid].rating);
00420               if (!rtl) {
00421                 x += 20;
00422                 if (x > r.right - WD_FRAMERECT_RIGHT) break;
00423               }
00424             }
00425           }
00426           y += FONT_HEIGHT_NORMAL;
00427         }
00428 
00429         if (this->vscroll->GetCount() == 0) { // company has no stations
00430           DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_LIST_NONE);
00431           return;
00432         }
00433         break;
00434       }
00435 
00436       case WID_STL_NOCARGOWAITING: {
00437         int cg_ofst = this->IsWidgetLowered(widget) ? 2 : 1;
00438         DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, STR_ABBREV_NONE, TC_BLACK, SA_HOR_CENTER);
00439         break;
00440       }
00441 
00442       case WID_STL_CARGOALL: {
00443         int cg_ofst = this->IsWidgetLowered(widget) ? 2 : 1;
00444         DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, STR_ABBREV_ALL, TC_BLACK, SA_HOR_CENTER);
00445         break;
00446       }
00447 
00448       case WID_STL_FACILALL: {
00449         int cg_ofst = this->IsWidgetLowered(widget) ? 2 : 1;
00450         DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, STR_ABBREV_ALL, TC_BLACK);
00451         break;
00452       }
00453 
00454       default:
00455         if (widget >= WID_STL_CARGOSTART) {
00456           const CargoSpec *cs = _sorted_cargo_specs[widget - WID_STL_CARGOSTART];
00457           int cg_ofst = HasBit(this->cargo_filter, cs->Index()) ? 2 : 1;
00458           GfxFillRect(r.left + cg_ofst, r.top + cg_ofst, r.right - 2 + cg_ofst, r.bottom - 2 + cg_ofst, cs->rating_colour);
00459           TextColour tc = GetContrastColour(cs->rating_colour);
00460           DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, cs->abbrev, tc, SA_HOR_CENTER);
00461         }
00462         break;
00463     }
00464   }
00465 
00466   virtual void SetStringParameters(int widget) const
00467   {
00468     if (widget == WID_STL_CAPTION) {
00469       SetDParam(0, this->window_number);
00470       SetDParam(1, this->vscroll->GetCount());
00471     }
00472   }
00473 
00474   virtual void OnClick(Point pt, int widget, int click_count)
00475   {
00476     switch (widget) {
00477       case WID_STL_LIST: {
00478         uint id_v = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_STL_LIST, 0, FONT_HEIGHT_NORMAL);
00479         if (id_v >= this->stations.Length()) return; // click out of list bound
00480 
00481         const Station *st = this->stations[id_v];
00482         /* do not check HasStationInUse - it is slow and may be invalid */
00483         assert(st->owner == (Owner)this->window_number || st->owner == OWNER_NONE);
00484 
00485         if (_ctrl_pressed) {
00486           ShowExtraViewPortWindow(st->xy);
00487         } else {
00488           ScrollMainWindowToTile(st->xy);
00489         }
00490         break;
00491       }
00492 
00493       case WID_STL_TRAIN:
00494       case WID_STL_TRUCK:
00495       case WID_STL_BUS:
00496       case WID_STL_AIRPLANE:
00497       case WID_STL_SHIP:
00498         if (_ctrl_pressed) {
00499           ToggleBit(this->facilities, widget - WID_STL_TRAIN);
00500           this->ToggleWidgetLoweredState(widget);
00501         } else {
00502           uint i;
00503           FOR_EACH_SET_BIT(i, this->facilities) {
00504             this->RaiseWidget(i + WID_STL_TRAIN);
00505           }
00506           this->facilities = 1 << (widget - WID_STL_TRAIN);
00507           this->LowerWidget(widget);
00508         }
00509         this->stations.ForceRebuild();
00510         this->SetDirty();
00511         break;
00512 
00513       case WID_STL_FACILALL:
00514         for (uint i = WID_STL_TRAIN; i <= WID_STL_SHIP; i++) {
00515           this->LowerWidget(i);
00516         }
00517 
00518         this->facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK;
00519         this->stations.ForceRebuild();
00520         this->SetDirty();
00521         break;
00522 
00523       case WID_STL_CARGOALL: {
00524         for (uint i = 0; i < _sorted_standard_cargo_specs_size; i++) {
00525           this->LowerWidget(WID_STL_CARGOSTART + i);
00526         }
00527         this->LowerWidget(WID_STL_NOCARGOWAITING);
00528 
00529         this->cargo_filter = _cargo_mask;
00530         this->include_empty = true;
00531         this->stations.ForceRebuild();
00532         this->SetDirty();
00533         break;
00534       }
00535 
00536       case WID_STL_SORTBY: // flip sorting method asc/desc
00537         this->stations.ToggleSortOrder();
00538         this->SetDirty();
00539         break;
00540 
00541       case WID_STL_SORTDROPBTN: // select sorting criteria dropdown menu
00542         ShowDropDownMenu(this, this->sorter_names, this->stations.SortType(), WID_STL_SORTDROPBTN, 0, 0);
00543         break;
00544 
00545       case WID_STL_NOCARGOWAITING:
00546         if (_ctrl_pressed) {
00547           this->include_empty = !this->include_empty;
00548           this->ToggleWidgetLoweredState(WID_STL_NOCARGOWAITING);
00549         } else {
00550           for (uint i = 0; i < _sorted_standard_cargo_specs_size; i++) {
00551             this->RaiseWidget(WID_STL_CARGOSTART + i);
00552           }
00553 
00554           this->cargo_filter = 0;
00555           this->include_empty = true;
00556 
00557           this->LowerWidget(WID_STL_NOCARGOWAITING);
00558         }
00559         this->stations.ForceRebuild();
00560         this->SetDirty();
00561         break;
00562 
00563       default:
00564         if (widget >= WID_STL_CARGOSTART) { // change cargo_filter
00565           /* Determine the selected cargo type */
00566           const CargoSpec *cs = _sorted_cargo_specs[widget - WID_STL_CARGOSTART];
00567 
00568           if (_ctrl_pressed) {
00569             ToggleBit(this->cargo_filter, cs->Index());
00570             this->ToggleWidgetLoweredState(widget);
00571           } else {
00572             for (uint i = 0; i < _sorted_standard_cargo_specs_size; i++) {
00573               this->RaiseWidget(WID_STL_CARGOSTART + i);
00574             }
00575             this->RaiseWidget(WID_STL_NOCARGOWAITING);
00576 
00577             this->cargo_filter = 0;
00578             this->include_empty = false;
00579 
00580             SetBit(this->cargo_filter, cs->Index());
00581             this->LowerWidget(widget);
00582           }
00583           this->stations.ForceRebuild();
00584           this->SetDirty();
00585         }
00586         break;
00587     }
00588   }
00589 
00590   virtual void OnDropdownSelect(int widget, int index)
00591   {
00592     if (this->stations.SortType() != index) {
00593       this->stations.SetSortType(index);
00594 
00595       /* Display the current sort variant */
00596       this->GetWidget<NWidgetCore>(WID_STL_SORTDROPBTN)->widget_data = this->sorter_names[this->stations.SortType()];
00597 
00598       this->SetDirty();
00599     }
00600   }
00601 
00602   virtual void OnTick()
00603   {
00604     if (_pause_mode != PM_UNPAUSED) return;
00605     if (this->stations.NeedResort()) {
00606       DEBUG(misc, 3, "Periodic rebuild station list company %d", this->window_number);
00607       this->SetDirty();
00608     }
00609   }
00610 
00611   virtual void OnResize()
00612   {
00613     this->vscroll->SetCapacityFromWidget(this, WID_STL_LIST, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
00614   }
00615 
00621   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
00622   {
00623     if (data == 0) {
00624       /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
00625       this->stations.ForceRebuild();
00626     } else {
00627       this->stations.ForceResort();
00628     }
00629   }
00630 };
00631 
00632 Listing CompanyStationsWindow::last_sorting = {false, 0};
00633 byte CompanyStationsWindow::facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK;
00634 bool CompanyStationsWindow::include_empty = true;
00635 const uint32 CompanyStationsWindow::cargo_filter_max = UINT32_MAX;
00636 uint32 CompanyStationsWindow::cargo_filter = UINT32_MAX;
00637 const Station *CompanyStationsWindow::last_station = NULL;
00638 
00639 /* Availible station sorting functions */
00640 GUIStationList::SortFunction * const CompanyStationsWindow::sorter_funcs[] = {
00641   &StationNameSorter,
00642   &StationTypeSorter,
00643   &StationWaitingSorter,
00644   &StationRatingMaxSorter,
00645   &StationRatingMinSorter
00646 };
00647 
00648 /* Names of the sorting functions */
00649 const StringID CompanyStationsWindow::sorter_names[] = {
00650   STR_SORT_BY_NAME,
00651   STR_SORT_BY_FACILITY,
00652   STR_SORT_BY_WAITING,
00653   STR_SORT_BY_RATING_MAX,
00654   STR_SORT_BY_RATING_MIN,
00655   INVALID_STRING_ID
00656 };
00657 
00663 static NWidgetBase *CargoWidgets(int *biggest_index)
00664 {
00665   NWidgetHorizontal *container = new NWidgetHorizontal();
00666 
00667   for (uint i = 0; i < _sorted_standard_cargo_specs_size; i++) {
00668     NWidgetBackground *panel = new NWidgetBackground(WWT_PANEL, COLOUR_GREY, WID_STL_CARGOSTART + i);
00669     panel->SetMinimalSize(14, 11);
00670     panel->SetResize(0, 0);
00671     panel->SetFill(0, 1);
00672     panel->SetDataTip(0, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE);
00673     container->Add(panel);
00674   }
00675   *biggest_index = WID_STL_CARGOSTART + _sorted_standard_cargo_specs_size;
00676   return container;
00677 }
00678 
00679 static const NWidgetPart _nested_company_stations_widgets[] = {
00680   NWidget(NWID_HORIZONTAL),
00681     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
00682     NWidget(WWT_CAPTION, COLOUR_GREY, WID_STL_CAPTION), SetDataTip(STR_STATION_LIST_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00683     NWidget(WWT_SHADEBOX, COLOUR_GREY),
00684     NWidget(WWT_STICKYBOX, COLOUR_GREY),
00685   EndContainer(),
00686   NWidget(NWID_HORIZONTAL),
00687     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),
00688     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),
00689     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),
00690     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),
00691     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),
00692     NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_STL_FACILALL), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_SELECT_ALL_FACILITIES), SetFill(0, 1),
00693     NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(5, 11), SetFill(0, 1), EndContainer(),
00694     NWidgetFunction(CargoWidgets),
00695     NWidget(WWT_PANEL, COLOUR_GREY, WID_STL_NOCARGOWAITING), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_NO_WAITING_CARGO), SetFill(0, 1), EndContainer(),
00696     NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_STL_CARGOALL), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_SELECT_ALL_TYPES), SetFill(0, 1),
00697     NWidget(WWT_PANEL, COLOUR_GREY), SetDataTip(0x0, STR_NULL), SetResize(1, 0), SetFill(1, 1), EndContainer(),
00698   EndContainer(),
00699   NWidget(NWID_HORIZONTAL),
00700     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_STL_SORTBY), SetMinimalSize(81, 12), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
00701     NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_STL_SORTDROPBTN), SetMinimalSize(163, 12), SetDataTip(STR_SORT_BY_NAME, STR_TOOLTIP_SORT_CRITERIA), // widget_data gets overwritten.
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_PANEL, COLOUR_GREY, WID_STL_LIST), SetMinimalSize(346, 125), SetResize(1, 10), SetDataTip(0x0, STR_STATION_LIST_TOOLTIP), SetScrollbar(WID_STL_SCROLLBAR), EndContainer(),
00706     NWidget(NWID_VERTICAL),
00707       NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_STL_SCROLLBAR),
00708       NWidget(WWT_RESIZEBOX, COLOUR_GREY),
00709     EndContainer(),
00710   EndContainer(),
00711 };
00712 
00713 static const WindowDesc _company_stations_desc(
00714   WDP_AUTO, 358, 162,
00715   WC_STATION_LIST, WC_NONE,
00716   0,
00717   _nested_company_stations_widgets, lengthof(_nested_company_stations_widgets)
00718 );
00719 
00725 void ShowCompanyStations(CompanyID company)
00726 {
00727   if (!Company::IsValidID(company)) return;
00728 
00729   AllocateWindowDescFront<CompanyStationsWindow>(&_company_stations_desc, company);
00730 }
00731 
00732 static const NWidgetPart _nested_station_view_widgets[] = {
00733   NWidget(NWID_HORIZONTAL),
00734     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
00735     NWidget(WWT_CAPTION, COLOUR_GREY, WID_SV_CAPTION), SetDataTip(STR_STATION_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00736     NWidget(WWT_SHADEBOX, COLOUR_GREY),
00737     NWidget(WWT_STICKYBOX, COLOUR_GREY),
00738   EndContainer(),
00739   NWidget(NWID_HORIZONTAL),
00740     NWidget(WWT_PANEL, COLOUR_GREY, WID_SV_WAITING), SetMinimalSize(237, 52), SetResize(1, 10), SetScrollbar(WID_SV_SCROLLBAR), EndContainer(),
00741     NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_SV_SCROLLBAR),
00742   EndContainer(),
00743   NWidget(WWT_PANEL, COLOUR_GREY, WID_SV_ACCEPT_RATING_LIST), SetMinimalSize(249, 32), SetResize(1, 0), EndContainer(),
00744   NWidget(NWID_HORIZONTAL),
00745     NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
00746       NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_LOCATION), SetMinimalSize(45, 12), SetResize(1, 0), SetFill(1, 1),
00747           SetDataTip(STR_BUTTON_LOCATION, STR_STATION_VIEW_CENTER_TOOLTIP),
00748       NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_ACCEPTS_RATINGS), SetMinimalSize(46, 12), SetResize(1, 0), SetFill(1, 1),
00749           SetDataTip(STR_STATION_VIEW_RATINGS_BUTTON, STR_STATION_VIEW_RATINGS_TOOLTIP),
00750       NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_RENAME), SetMinimalSize(45, 12), SetResize(1, 0), SetFill(1, 1),
00751           SetDataTip(STR_BUTTON_RENAME, STR_STATION_VIEW_RENAME_TOOLTIP),
00752     EndContainer(),
00753     NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_SV_CLOSE_AIRPORT), SetMinimalSize(45, 12), SetResize(1, 0), SetFill(1, 1),
00754         SetDataTip(STR_STATION_VIEW_CLOSE_AIRPORT, STR_STATION_VIEW_CLOSE_AIRPORT_TOOLTIP),
00755     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_TRAINS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_TRAIN, STR_STATION_VIEW_SCHEDULED_TRAINS_TOOLTIP),
00756     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_ROADVEHS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_LORRY, STR_STATION_VIEW_SCHEDULED_ROAD_VEHICLES_TOOLTIP),
00757     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_SHIPS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_SHIP, STR_STATION_VIEW_SCHEDULED_SHIPS_TOOLTIP),
00758     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_PLANES),  SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_PLANE, STR_STATION_VIEW_SCHEDULED_AIRCRAFT_TOOLTIP),
00759     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
00760   EndContainer(),
00761 };
00762 
00773 static void DrawCargoIcons(CargoID i, uint waiting, int left, int right, int y)
00774 {
00775   uint num = min((waiting + 5) / 10, (right - left) / 10); // maximum is width / 10 icons so it won't overflow
00776   if (num == 0) return;
00777 
00778   SpriteID sprite = CargoSpec::Get(i)->GetCargoIcon();
00779 
00780   int x = _current_text_dir == TD_RTL ? right - num * 10 : left;
00781   do {
00782     DrawSprite(sprite, PAL_NONE, x, y);
00783     x += 10;
00784   } while (--num);
00785 }
00786 
00787 struct CargoData {
00788   CargoID cargo;
00789   StationID source;
00790   uint count;
00791 
00792   CargoData(CargoID cargo, StationID source, uint count) :
00793     cargo(cargo),
00794     source(source),
00795     count(count)
00796   { }
00797 };
00798 
00799 typedef std::list<CargoData> CargoDataList;
00800 
00804 struct StationViewWindow : public Window {
00805   uint32 cargo;                 
00806   uint16 cargo_rows[NUM_CARGO]; 
00807   uint expand_shrink_width;     
00808   int rating_lines;             
00809   int accepts_lines;            
00810   Scrollbar *vscroll;
00811 
00813   enum AcceptListHeight {
00814     ALH_RATING  = 13, 
00815     ALH_ACCEPTS = 3,  
00816   };
00817 
00818   StationViewWindow(const WindowDesc *desc, WindowNumber window_number) : Window()
00819   {
00820     this->rating_lines  = ALH_RATING;
00821     this->accepts_lines = ALH_ACCEPTS;
00822 
00823     this->CreateNestedTree(desc);
00824     this->vscroll = this->GetScrollbar(WID_SV_SCROLLBAR);
00825     /* Nested widget tree creation is done in two steps to ensure that this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS) exists in UpdateWidgetSize(). */
00826     this->FinishInitNested(desc, window_number);
00827 
00828     Owner owner = Station::Get(window_number)->owner;
00829     if (owner != OWNER_NONE) this->owner = owner;
00830   }
00831 
00832   ~StationViewWindow()
00833   {
00834     Owner owner = Station::Get(this->window_number)->owner;
00835     DeleteWindowById(WC_TRAINS_LIST,   VehicleListIdentifier(VL_STATION_LIST, VEH_TRAIN,    owner, this->window_number).Pack(), false);
00836     DeleteWindowById(WC_ROADVEH_LIST,  VehicleListIdentifier(VL_STATION_LIST, VEH_ROAD,     owner, this->window_number).Pack(), false);
00837     DeleteWindowById(WC_SHIPS_LIST,    VehicleListIdentifier(VL_STATION_LIST, VEH_SHIP,     owner, this->window_number).Pack(), false);
00838     DeleteWindowById(WC_AIRCRAFT_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_AIRCRAFT, owner, this->window_number).Pack(), false);
00839   }
00840 
00841   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00842   {
00843     switch (widget) {
00844       case WID_SV_WAITING:
00845         resize->height = FONT_HEIGHT_NORMAL;
00846         size->height = WD_FRAMERECT_TOP + 5 * resize->height + WD_FRAMERECT_BOTTOM;
00847         this->expand_shrink_width = max(GetStringBoundingBox("-").width, GetStringBoundingBox("+").width) + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
00848         break;
00849 
00850       case WID_SV_ACCEPT_RATING_LIST:
00851         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;
00852         break;
00853 
00854       case WID_SV_CLOSE_AIRPORT:
00855         if (!(Station::Get(this->window_number)->facilities & FACIL_AIRPORT)) {
00856           /* Hide 'Close Airport' button if no airport present. */
00857           size->width = 0;
00858           resize->width = 0;
00859           fill->width = 0;
00860         }
00861         break;
00862     }
00863   }
00864 
00865   virtual void OnPaint()
00866   {
00867     CargoDataList cargolist;
00868     uint32 transfers = 0;
00869     this->OrderWaitingCargo(&cargolist, &transfers);
00870 
00871     this->vscroll->SetCount((int)cargolist.size() + 1); // update scrollbar
00872 
00873     /* disable some buttons */
00874     const Station *st = Station::Get(this->window_number);
00875     this->SetWidgetDisabledState(WID_SV_RENAME,   st->owner != _local_company);
00876     this->SetWidgetDisabledState(WID_SV_TRAINS,   !(st->facilities & FACIL_TRAIN));
00877     this->SetWidgetDisabledState(WID_SV_ROADVEHS, !(st->facilities & FACIL_TRUCK_STOP) && !(st->facilities & FACIL_BUS_STOP));
00878     this->SetWidgetDisabledState(WID_SV_SHIPS,    !(st->facilities & FACIL_DOCK));
00879     this->SetWidgetDisabledState(WID_SV_PLANES,   !(st->facilities & FACIL_AIRPORT));
00880     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
00881     this->SetWidgetLoweredState(WID_SV_CLOSE_AIRPORT, (st->facilities & FACIL_AIRPORT) && (st->airport.flags & AIRPORT_CLOSED_block) != 0);
00882 
00883     this->DrawWidgets();
00884 
00885     if (!this->IsShaded()) {
00886       /* Draw 'accepted cargo' or 'cargo ratings'. */
00887       const NWidgetBase *wid = this->GetWidget<NWidgetBase>(WID_SV_ACCEPT_RATING_LIST);
00888       const Rect r = {wid->pos_x, wid->pos_y, wid->pos_x + wid->current_x - 1, wid->pos_y + wid->current_y - 1};
00889       if (this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) {
00890         int lines = this->DrawAcceptedCargo(r);
00891         if (lines > this->accepts_lines) { // Resize the widget, and perform re-initialization of the window.
00892           this->accepts_lines = lines;
00893           this->ReInit();
00894           return;
00895         }
00896       } else {
00897         int lines = this->DrawCargoRatings(r);
00898         if (lines > this->rating_lines) { // Resize the widget, and perform re-initialization of the window.
00899           this->rating_lines = lines;
00900           this->ReInit();
00901           return;
00902         }
00903       }
00904 
00905       /* Draw waiting cargo. */
00906       NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_SV_WAITING);
00907       Rect waiting_rect = {nwi->pos_x, nwi->pos_y, nwi->pos_x + nwi->current_x - 1, nwi->pos_y + nwi->current_y - 1};
00908       this->DrawWaitingCargo(waiting_rect, cargolist, transfers);
00909     }
00910   }
00911 
00912   virtual void SetStringParameters(int widget) const
00913   {
00914     if (widget == WID_SV_CAPTION) {
00915       const Station *st = Station::Get(this->window_number);
00916       SetDParam(0, st->index);
00917       SetDParam(1, st->facilities);
00918     }
00919   }
00920 
00927   void OrderWaitingCargo(CargoDataList *cargolist, uint32 *transfers)
00928   {
00929     assert(cargolist->size() == 0);
00930     *transfers = 0;
00931 
00932     StationID station_id = this->window_number;
00933     const Station *st = Station::Get(station_id);
00934 
00935     /* count types of cargoes waiting in station */
00936     for (CargoID i = 0; i < NUM_CARGO; i++) {
00937       if (st->goods[i].cargo.Empty()) {
00938         this->cargo_rows[i] = 0;
00939       } else {
00940         /* Add an entry for total amount of cargo of this type waiting. */
00941         cargolist->push_back(CargoData(i, INVALID_STATION, st->goods[i].cargo.Count()));
00942 
00943         /* Set the row for this cargo entry for the expand/hide button */
00944         this->cargo_rows[i] = (uint16)cargolist->size();
00945 
00946         /* Add an entry for each distinct cargo source. */
00947         const StationCargoList::List *packets = st->goods[i].cargo.Packets();
00948         for (StationCargoList::ConstIterator it(packets->begin()); it != packets->end(); it++) {
00949           const CargoPacket *cp = *it;
00950           if (cp->SourceStation() != station_id) {
00951             bool added = false;
00952 
00953             /* Enable the expand/hide button for this cargo type */
00954             SetBit(*transfers, i);
00955 
00956             /* Don't add cargo lines if not expanded */
00957             if (!HasBit(this->cargo, i)) break;
00958 
00959             /* Check if we already have this source in the list */
00960             for (CargoDataList::iterator jt(cargolist->begin()); jt != cargolist->end(); jt++) {
00961               CargoData *cd = &(*jt);
00962               if (cd->cargo == i && cd->source == cp->SourceStation()) {
00963                 cd->count += cp->Count();
00964                 added = true;
00965                 break;
00966               }
00967             }
00968 
00969             if (!added) cargolist->push_back(CargoData(i, cp->SourceStation(), cp->Count()));
00970           }
00971         }
00972       }
00973     }
00974   }
00975 
00982   void DrawWaitingCargo(const Rect &r, const CargoDataList &cargolist, uint32 transfers) const
00983   {
00984     int y = r.top + WD_FRAMERECT_TOP;
00985     int pos = this->vscroll->GetPosition();
00986 
00987     const Station *st = Station::Get(this->window_number);
00988     if (--pos < 0) {
00989       StringID str = STR_JUST_NOTHING;
00990       for (CargoID i = 0; i < NUM_CARGO; i++) {
00991         if (!st->goods[i].cargo.Empty()) str = STR_EMPTY;
00992       }
00993       SetDParam(0, str);
00994       DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_VIEW_WAITING_TITLE);
00995       y += FONT_HEIGHT_NORMAL;
00996     }
00997 
00998     bool rtl = _current_text_dir == TD_RTL;
00999     int text_left    = rtl ? r.left + this->expand_shrink_width : r.left + WD_FRAMERECT_LEFT;
01000     int text_right   = rtl ? r.right - WD_FRAMERECT_LEFT : r.right - this->expand_shrink_width;
01001     int shrink_left  = rtl ? r.left + WD_FRAMERECT_LEFT : r.right - this->expand_shrink_width + WD_FRAMERECT_LEFT;
01002     int shrink_right = rtl ? r.left + this->expand_shrink_width - WD_FRAMERECT_RIGHT : r.right - WD_FRAMERECT_RIGHT;
01003 
01004 
01005     int maxrows = this->vscroll->GetCapacity();
01006     for (CargoDataList::const_iterator it = cargolist.begin(); it != cargolist.end() && pos > -maxrows; ++it) {
01007       if (--pos < 0) {
01008         const CargoData *cd = &(*it);
01009         if (cd->source == INVALID_STATION) {
01010           /* Heading */
01011           DrawCargoIcons(cd->cargo, cd->count, r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y);
01012           SetDParam(0, cd->cargo);
01013           SetDParam(1, cd->count);
01014           if (HasBit(transfers, cd->cargo)) {
01015             /* This cargo has transfers waiting so show the expand or shrink 'button' */
01016             const char *sym = HasBit(this->cargo, cd->cargo) ? "-" : "+";
01017             DrawString(text_left, text_right, y, STR_STATION_VIEW_WAITING_CARGO, TC_FROMSTRING, SA_RIGHT);
01018             DrawString(shrink_left, shrink_right, y, sym, TC_YELLOW, SA_RIGHT);
01019           } else {
01020             DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_VIEW_WAITING_CARGO, TC_FROMSTRING, SA_RIGHT);
01021           }
01022         } else {
01023           SetDParam(0, cd->cargo);
01024           SetDParam(1, cd->count);
01025           SetDParam(2, cd->source);
01026           DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_VIEW_EN_ROUTE_FROM, TC_FROMSTRING, SA_RIGHT);
01027         }
01028 
01029         y += FONT_HEIGHT_NORMAL;
01030       }
01031     }
01032   }
01033 
01039   int DrawAcceptedCargo(const Rect &r) const
01040   {
01041     const Station *st = Station::Get(this->window_number);
01042 
01043     uint32 cargo_mask = 0;
01044     for (CargoID i = 0; i < NUM_CARGO; i++) {
01045       if (HasBit(st->goods[i].acceptance_pickup, GoodsEntry::GES_ACCEPTANCE)) SetBit(cargo_mask, i);
01046     }
01047     SetDParam(0, cargo_mask);
01048     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);
01049     return CeilDiv(bottom - r.top - WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL);
01050   }
01051 
01057   int DrawCargoRatings(const Rect &r) const
01058   {
01059     const Station *st = Station::Get(this->window_number);
01060     int y = r.top + WD_FRAMERECT_TOP;
01061 
01062     if (st->town->exclusive_counter > 0) {
01063       SetDParam(0, st->town->exclusivity);
01064       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);
01065       y += WD_PAR_VSEP_WIDE;
01066     }
01067 
01068     DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_VIEW_CARGO_RATINGS_TITLE);
01069     y += FONT_HEIGHT_NORMAL;
01070 
01071     const CargoSpec *cs;
01072     FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
01073       const GoodsEntry *ge = &st->goods[cs->Index()];
01074       if (!HasBit(ge->acceptance_pickup, GoodsEntry::GES_PICKUP)) continue;
01075 
01076       SetDParam(0, cs->name);
01077       SetDParam(2, ToPercent8(ge->rating));
01078       SetDParam(1, STR_CARGO_RATING_APPALLING + (ge->rating >> 5));
01079       DrawString(r.left + WD_FRAMERECT_LEFT + 6, r.right - WD_FRAMERECT_RIGHT - 6, y, STR_STATION_VIEW_CARGO_RATING);
01080       y += FONT_HEIGHT_NORMAL;
01081     }
01082     return CeilDiv(y - r.top - WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL);
01083   }
01084 
01085   void HandleCargoWaitingClick(int row)
01086   {
01087     if (row == 0) return;
01088 
01089     for (CargoID c = 0; c < NUM_CARGO; c++) {
01090       if (this->cargo_rows[c] == row) {
01091         ToggleBit(this->cargo, c);
01092         this->SetWidgetDirty(WID_SV_WAITING);
01093         break;
01094       }
01095     }
01096   }
01097 
01098   virtual void OnClick(Point pt, int widget, int click_count)
01099   {
01100     switch (widget) {
01101       case WID_SV_WAITING:
01102         this->HandleCargoWaitingClick(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_SV_WAITING, WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL));
01103         break;
01104 
01105       case WID_SV_LOCATION:
01106         if (_ctrl_pressed) {
01107           ShowExtraViewPortWindow(Station::Get(this->window_number)->xy);
01108         } else {
01109           ScrollMainWindowToTile(Station::Get(this->window_number)->xy);
01110         }
01111         break;
01112 
01113       case WID_SV_ACCEPTS_RATINGS: {
01114         /* Swap between 'accepts' and 'ratings' view. */
01115         int height_change;
01116         NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS);
01117         if (this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) {
01118           nwi->SetDataTip(STR_STATION_VIEW_ACCEPTS_BUTTON, STR_STATION_VIEW_ACCEPTS_TOOLTIP); // Switch to accepts view.
01119           height_change = this->rating_lines - this->accepts_lines;
01120         } else {
01121           nwi->SetDataTip(STR_STATION_VIEW_RATINGS_BUTTON, STR_STATION_VIEW_RATINGS_TOOLTIP); // Switch to ratings view.
01122           height_change = this->accepts_lines - this->rating_lines;
01123         }
01124         this->ReInit(0, height_change * FONT_HEIGHT_NORMAL);
01125         break;
01126       }
01127 
01128       case WID_SV_RENAME:
01129         SetDParam(0, this->window_number);
01130         ShowQueryString(STR_STATION_NAME, STR_STATION_VIEW_RENAME_STATION_CAPTION, MAX_LENGTH_STATION_NAME_CHARS,
01131             this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
01132         break;
01133 
01134       case WID_SV_CLOSE_AIRPORT:
01135         DoCommandP(0, this->window_number, 0, CMD_OPEN_CLOSE_AIRPORT);
01136         break;
01137 
01138       case WID_SV_TRAINS:   // Show list of scheduled trains to this station
01139       case WID_SV_ROADVEHS: // Show list of scheduled road-vehicles to this station
01140       case WID_SV_SHIPS:    // Show list of scheduled ships to this station
01141       case WID_SV_PLANES: { // Show list of scheduled aircraft to this station
01142         Owner owner = Station::Get(this->window_number)->owner;
01143         ShowVehicleListWindow(owner, (VehicleType)(widget - WID_SV_TRAINS), (StationID)this->window_number);
01144         break;
01145       }
01146     }
01147   }
01148 
01149   virtual void OnQueryTextFinished(char *str)
01150   {
01151     if (str == NULL) return;
01152 
01153     DoCommandP(0, this->window_number, 0, CMD_RENAME_STATION | CMD_MSG(STR_ERROR_CAN_T_RENAME_STATION), NULL, str);
01154   }
01155 
01156   virtual void OnResize()
01157   {
01158     this->vscroll->SetCapacityFromWidget(this, WID_SV_WAITING, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
01159   }
01160 
01166   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
01167   {
01168     if (gui_scope) this->ReInit();
01169   }
01170 };
01171 
01172 
01173 static const WindowDesc _station_view_desc(
01174   WDP_AUTO, 249, 110,
01175   WC_STATION_VIEW, WC_NONE,
01176   0,
01177   _nested_station_view_widgets, lengthof(_nested_station_view_widgets)
01178 );
01179 
01185 void ShowStationViewWindow(StationID station)
01186 {
01187   AllocateWindowDescFront<StationViewWindow>(&_station_view_desc, station);
01188 }
01189 
01191 struct TileAndStation {
01192   TileIndex tile;    
01193   StationID station; 
01194 };
01195 
01196 static SmallVector<TileAndStation, 8> _deleted_stations_nearby;
01197 static SmallVector<StationID, 8> _stations_nearby_list;
01198 
01206 template <class T>
01207 static bool AddNearbyStation(TileIndex tile, void *user_data)
01208 {
01209   TileArea *ctx = (TileArea *)user_data;
01210 
01211   /* First check if there were deleted stations here */
01212   for (uint i = 0; i < _deleted_stations_nearby.Length(); i++) {
01213     TileAndStation *ts = _deleted_stations_nearby.Get(i);
01214     if (ts->tile == tile) {
01215       *_stations_nearby_list.Append() = _deleted_stations_nearby[i].station;
01216       _deleted_stations_nearby.Erase(ts);
01217       i--;
01218     }
01219   }
01220 
01221   /* Check if own station and if we stay within station spread */
01222   if (!IsTileType(tile, MP_STATION)) return false;
01223 
01224   StationID sid = GetStationIndex(tile);
01225 
01226   /* This station is (likely) a waypoint */
01227   if (!T::IsValidID(sid)) return false;
01228 
01229   T *st = T::Get(sid);
01230   if (st->owner != _local_company || _stations_nearby_list.Contains(sid)) return false;
01231 
01232   if (st->rect.BeforeAddRect(ctx->tile, ctx->w, ctx->h, StationRect::ADD_TEST).Succeeded()) {
01233     *_stations_nearby_list.Append() = sid;
01234   }
01235 
01236   return false; // We want to include *all* nearby stations
01237 }
01238 
01248 template <class T>
01249 static const T *FindStationsNearby(TileArea ta, bool distant_join)
01250 {
01251   TileArea ctx = ta;
01252 
01253   _stations_nearby_list.Clear();
01254   _deleted_stations_nearby.Clear();
01255 
01256   /* Check the inside, to return, if we sit on another station */
01257   TILE_AREA_LOOP(t, ta) {
01258     if (t < MapSize() && IsTileType(t, MP_STATION) && T::IsValidID(GetStationIndex(t))) return T::GetByTile(t);
01259   }
01260 
01261   /* Look for deleted stations */
01262   const BaseStation *st;
01263   FOR_ALL_BASE_STATIONS(st) {
01264     if (T::IsExpected(st) && !st->IsInUse() && st->owner == _local_company) {
01265       /* Include only within station spread (yes, it is strictly less than) */
01266       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) {
01267         TileAndStation *ts = _deleted_stations_nearby.Append();
01268         ts->tile = st->xy;
01269         ts->station = st->index;
01270 
01271         /* Add the station when it's within where we're going to build */
01272         if (IsInsideBS(TileX(st->xy), TileX(ctx.tile), ctx.w) &&
01273             IsInsideBS(TileY(st->xy), TileY(ctx.tile), ctx.h)) {
01274           AddNearbyStation<T>(st->xy, &ctx);
01275         }
01276       }
01277     }
01278   }
01279 
01280   /* Only search tiles where we have a chance to stay within the station spread.
01281    * The complete check needs to be done in the callback as we don't know the
01282    * extent of the found station, yet. */
01283   if (distant_join && min(ta.w, ta.h) >= _settings_game.station.station_spread) return NULL;
01284   uint max_dist = distant_join ? _settings_game.station.station_spread - min(ta.w, ta.h) : 1;
01285 
01286   TileIndex tile = TILE_ADD(ctx.tile, TileOffsByDir(DIR_N));
01287   CircularTileSearch(&tile, max_dist, ta.w, ta.h, AddNearbyStation<T>, &ctx);
01288 
01289   return NULL;
01290 }
01291 
01292 static const NWidgetPart _nested_select_station_widgets[] = {
01293   NWidget(NWID_HORIZONTAL),
01294     NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
01295     NWidget(WWT_CAPTION, COLOUR_DARK_GREEN, WID_JS_CAPTION), SetDataTip(STR_JOIN_STATION_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
01296   EndContainer(),
01297   NWidget(NWID_HORIZONTAL),
01298     NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_JS_PANEL), SetResize(1, 0), SetScrollbar(WID_JS_SCROLLBAR), EndContainer(),
01299     NWidget(NWID_VERTICAL),
01300       NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, WID_JS_SCROLLBAR),
01301       NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
01302     EndContainer(),
01303   EndContainer(),
01304 };
01305 
01310 template <class T>
01311 struct SelectStationWindow : Window {
01312   CommandContainer select_station_cmd; 
01313   TileArea area; 
01314   Scrollbar *vscroll;
01315 
01316   SelectStationWindow(const WindowDesc *desc, CommandContainer cmd, TileArea ta) :
01317     Window(),
01318     select_station_cmd(cmd),
01319     area(ta)
01320   {
01321     this->CreateNestedTree(desc);
01322     this->vscroll = this->GetScrollbar(WID_JS_SCROLLBAR);
01323     this->GetWidget<NWidgetCore>(WID_JS_CAPTION)->widget_data = T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_JOIN_WAYPOINT_CAPTION : STR_JOIN_STATION_CAPTION;
01324     this->FinishInitNested(desc, 0);
01325     this->OnInvalidateData(0);
01326   }
01327 
01328   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01329   {
01330     if (widget != WID_JS_PANEL) return;
01331 
01332     /* Determine the widest string */
01333     Dimension d = GetStringBoundingBox(T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_JOIN_WAYPOINT_CREATE_SPLITTED_WAYPOINT : STR_JOIN_STATION_CREATE_SPLITTED_STATION);
01334     for (uint i = 0; i < _stations_nearby_list.Length(); i++) {
01335       const T *st = T::Get(_stations_nearby_list[i]);
01336       SetDParam(0, st->index);
01337       SetDParam(1, st->facilities);
01338       d = maxdim(d, GetStringBoundingBox(T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_STATION_LIST_WAYPOINT : STR_STATION_LIST_STATION));
01339     }
01340 
01341     resize->height = d.height;
01342     d.height *= 5;
01343     d.width += WD_FRAMERECT_RIGHT + WD_FRAMERECT_LEFT;
01344     d.height += WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
01345     *size = d;
01346   }
01347 
01348   virtual void DrawWidget(const Rect &r, int widget) const
01349   {
01350     if (widget != WID_JS_PANEL) return;
01351 
01352     uint y = r.top + WD_FRAMERECT_TOP;
01353     if (this->vscroll->GetPosition() == 0) {
01354       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);
01355       y += this->resize.step_height;
01356     }
01357 
01358     for (uint i = max<uint>(1, this->vscroll->GetPosition()); i <= _stations_nearby_list.Length(); ++i, y += this->resize.step_height) {
01359       /* Don't draw anything if it extends past the end of the window. */
01360       if (i - this->vscroll->GetPosition() >= this->vscroll->GetCapacity()) break;
01361 
01362       const T *st = T::Get(_stations_nearby_list[i - 1]);
01363       SetDParam(0, st->index);
01364       SetDParam(1, st->facilities);
01365       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);
01366     }
01367   }
01368 
01369   virtual void OnClick(Point pt, int widget, int click_count)
01370   {
01371     if (widget != WID_JS_PANEL) return;
01372 
01373     uint st_index = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_JS_PANEL, WD_FRAMERECT_TOP);
01374     bool distant_join = (st_index > 0);
01375     if (distant_join) st_index--;
01376 
01377     if (distant_join && st_index >= _stations_nearby_list.Length()) return;
01378 
01379     /* Insert station to be joined into stored command */
01380     SB(this->select_station_cmd.p2, 16, 16,
01381        (distant_join ? _stations_nearby_list[st_index] : NEW_STATION));
01382 
01383     /* Execute stored Command */
01384     DoCommandP(&this->select_station_cmd);
01385 
01386     /* Close Window; this might cause double frees! */
01387     DeleteWindowById(WC_SELECT_STATION, 0);
01388   }
01389 
01390   virtual void OnTick()
01391   {
01392     if (_thd.dirty & 2) {
01393       _thd.dirty &= ~2;
01394       this->SetDirty();
01395     }
01396   }
01397 
01398   virtual void OnResize()
01399   {
01400     this->vscroll->SetCapacityFromWidget(this, WID_JS_PANEL, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
01401   }
01402 
01408   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
01409   {
01410     if (!gui_scope) return;
01411     FindStationsNearby<T>(this->area, true);
01412     this->vscroll->SetCount(_stations_nearby_list.Length() + 1);
01413     this->SetDirty();
01414   }
01415 };
01416 
01417 static const WindowDesc _select_station_desc(
01418   WDP_AUTO, 200, 180,
01419   WC_SELECT_STATION, WC_NONE,
01420   WDF_CONSTRUCTION,
01421   _nested_select_station_widgets, lengthof(_nested_select_station_widgets)
01422 );
01423 
01424 
01432 template <class T>
01433 static bool StationJoinerNeeded(CommandContainer cmd, TileArea ta)
01434 {
01435   /* Only show selection if distant join is enabled in the settings */
01436   if (!_settings_game.station.distant_join_stations) return false;
01437 
01438   /* If a window is already opened and we didn't ctrl-click,
01439    * return true (i.e. just flash the old window) */
01440   Window *selection_window = FindWindowById(WC_SELECT_STATION, 0);
01441   if (selection_window != NULL) {
01442     /* Abort current distant-join and start new one */
01443     delete selection_window;
01444     UpdateTileSelection();
01445   }
01446 
01447   /* only show the popup, if we press ctrl */
01448   if (!_ctrl_pressed) return false;
01449 
01450   /* Now check if we could build there */
01451   if (DoCommand(&cmd, CommandFlagsToDCFlags(GetCommandFlags(cmd.cmd))).Failed()) return false;
01452 
01453   /* Test for adjacent station or station below selection.
01454    * If adjacent-stations is disabled and we are building next to a station, do not show the selection window.
01455    * but join the other station immediately. */
01456   const T *st = FindStationsNearby<T>(ta, false);
01457   return st == NULL && (_settings_game.station.adjacent_stations || _stations_nearby_list.Length() == 0);
01458 }
01459 
01466 template <class T>
01467 void ShowSelectBaseStationIfNeeded(CommandContainer cmd, TileArea ta)
01468 {
01469   if (StationJoinerNeeded<T>(cmd, ta)) {
01470     if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
01471     new SelectStationWindow<T>(&_select_station_desc, cmd, ta);
01472   } else {
01473     DoCommandP(&cmd);
01474   }
01475 }
01476 
01482 void ShowSelectStationIfNeeded(CommandContainer cmd, TileArea ta)
01483 {
01484   ShowSelectBaseStationIfNeeded<Station>(cmd, ta);
01485 }
01486 
01492 void ShowSelectWaypointIfNeeded(CommandContainer cmd, TileArea ta)
01493 {
01494   ShowSelectBaseStationIfNeeded<Waypoint>(cmd, ta);
01495 }