# station_gui.cpp

Go to the documentation of this file.

    00001 /* $Id: station_gui.cpp 22601 2011-06-18 19:43:51Z rubidium $ */
    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
    00042 static int DrawCargoListText(uint32 cargo_mask, const Rect &r, StringID prefix)
    00043 {
    00044   bool first = true;
    00045   char string[512];
    00046   char *b = string;
    00047
    00048   CargoID i;
    00049   FOR_EACH_SET_CARGO_ID(i, cargo_mask) {
    00050     if (b >= lastof(string) - (1 + 2 * 4)) break; // ',' or ' ' and two calls to Utf8Encode()
    00051
    00052     if (first) {
    00053       first = false;
    00054     } else {
    00055       /* Add a comma if this is not the first item */
    00056       *b++ = ',';
    00057       *b++ = ' ';
    00058     }
    00059     b = InlineString(b, CargoSpec::Get(i)->name);
    00060   }
    00061
    00062   /* If first is still true then no cargo is accepted */
    00063   if (first) b = InlineString(b, STR_JUST_NOTHING);
    00064
    00065   *b = '\0';
    00066
    00067   /* Make sure we detect any buffer overflow */
    00068   assert(b < endof(string));
    00069
    00070   SetDParamStr(0, string);
    00071   return DrawStringMultiLine(r.left, r.right, r.top, r.bottom, prefix);
    00072 }
    00073
    00084 int DrawStationCoverageAreaText(int left, int right, int top, StationCoverageType sct, int rad, bool supplies)
    00085 {
    00086   TileIndex tile = TileVirtXY(_thd.pos.x, _thd.pos.y);
    00087   uint32 cargo_mask = 0;
    00088   if (_thd.drawstyle == HT_RECT && tile < MapSize()) {
    00089     CargoArray cargos;
    00090     if (supplies) {
    00091       cargos = GetProductionAroundTiles(tile, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE, rad);
    00092     } else {
    00093       cargos = GetAcceptanceAroundTiles(tile, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE, rad);
    00094     }
    00095
    00096     /* Convert cargo counts to a set of cargo bits, and draw the result. */
    00097     for (CargoID i = 0; i < NUM_CARGO; i++) {
    00098       switch (sct) {
    00099         case SCT_PASSENGERS_ONLY: if (!IsCargoInClass(i, CC_PASSENGERS)) continue; break;
    00100         case SCT_NON_PASSENGERS_ONLY: if (IsCargoInClass(i, CC_PASSENGERS)) continue; break;
    00101         case SCT_ALL: break;
    00102         default: NOT_REACHED();
    00103       }
    00104       if (cargos[i] >= (supplies ? 1U : 8U)) SetBit(cargo_mask, i);
    00105     }
    00106   }
    00107   Rect r = {left, top, right, INT32_MAX};
    00108   return DrawCargoListText(cargo_mask, r, supplies ? STR_STATION_BUILD_SUPPLIES_CARGO : STR_STATION_BUILD_ACCEPTS_CARGO);
    00109 }
    00110
    00116 void CheckRedrawStationCoverage(const Window *w)
    00117 {
    00118   if (_thd.dirty & 1) {
    00119     _thd.dirty &= ~1;
    00120     w->SetDirty();
    00121   }
    00122 }
    00123
    00139 static void StationsWndShowStationRating(int left, int right, int y, CargoID type, uint amount, byte rating)
    00140 {
    00141   static const uint units_full  = 576;
    00142   static const uint rating_full = 224;
    00143
    00144   const CargoSpec *cs = CargoSpec::Get(type);
    00145   if (!cs->IsValid()) return;
    00146
    00147   int colour = cs->rating_colour;
    00148   uint w = (minu(amount, units_full) + 5) / 36;
    00149
    00150   int height = GetCharacterHeight(FS_SMALL);
    00151
    00152   /* Draw total cargo (limited) on station (fits into 16 pixels) */
    00153   if (w != 0) GfxFillRect(left, y, left + w - 1, y + height, colour);
    00154
    00155   /* Draw a one pixel-wide bar of additional cargo meter, useful
    00156    * for stations with only a small amount (<=30) */
    00157   if (w == 0) {
    00158     uint rest = amount / 5;
    00159     if (rest != 0) {
    00160       w += left;
    00161       GfxFillRect(w, y + height - rest, w, y + height, colour);
    00162     }
    00163   }
    00164
    00165   DrawString(left + 1, right, y, cs->abbrev, TC_BLACK);
    00166
    00167   /* Draw green/red ratings bar (fits into 14 pixels) */
    00168   y += height + 2;
    00169   GfxFillRect(left + 1, y, left + 14, y, 0xB8);
    00170   rating = minu(rating, rating_full) / 16;
    00171   if (rating != 0) GfxFillRect(left + 1, y, left + rating, y, 0xD0);
    00172 }
    00173
    00174 typedef GUIList<const Station*> GUIStationList;
    00175
    00177 enum StationListWidgets {
    00178   SLW_CAPTION,
    00179   SLW_LIST,
    00180   SLW_SCROLLBAR,
    00181
    00182   /* Vehicletypes need to be in order of StationFacility due to bit magic */
    00183   SLW_TRAIN,
    00184   SLW_TRUCK,
    00185   SLW_BUS,
    00186   SLW_AIRPLANE,
    00187   SLW_SHIP,
    00188   SLW_FACILALL,
    00189
    00190   SLW_NOCARGOWAITING,
    00191   SLW_CARGOALL,
    00192
    00193   SLW_SORTBY,
    00194   SLW_SORTDROPBTN,
    00195
    00196   SLW_CARGOSTART,
    00197 };
    00198
    00202 class CompanyStationsWindow : public Window
    00203 {
    00204 protected:
    00205   /* Runtime saved values */
    00206   static Listing last_sorting;
    00207   static byte facilities;               // types of stations of interest
    00208   static bool include_empty;            // whether we should include stations without waiting cargo
    00209   static const uint32 cargo_filter_max;
    00210   static uint32 cargo_filter;           // bitmap of cargo types to include
    00211   static const Station *last_station;
    00212
    00213   /* Constants for sorting stations */
    00214   static const StringID sorter_names[];
    00215   static GUIStationList::SortFunction * const sorter_funcs[];
    00216
    00217   GUIStationList stations;
    00218   Scrollbar *vscroll;
    00219
    00225   void BuildStationsList(const Owner owner)
    00226   {
    00227     if (!this->stations.NeedRebuild()) return;
    00228
    00229     DEBUG(misc, 3, "Building station list for company %d", owner);
    00230
    00231     this->stations.Clear();
    00232
    00233     const Station *st;
    00234     FOR_ALL_STATIONS(st) {
    00235       if (st->owner == owner || (st->owner == OWNER_NONE && HasStationInUse(st->index, true, owner))) {
    00236         if (this->facilities & st->facilities) { // only stations with selected facilities
    00237           int num_waiting_cargo = 0;
    00238           for (CargoID j = 0; j < NUM_CARGO; j++) {
    00239             if (HasBit(st->goods[j].acceptance_pickup, GoodsEntry::PICKUP)) {
    00240               num_waiting_cargo++; // count number of waiting cargo
    00241               if (HasBit(this->cargo_filter, j)) {
    00242                 *this->stations.Append() = st;
    00243                 break;
    00244               }
    00245             }
    00246           }
    00247           /* stations without waiting cargo */
    00248           if (num_waiting_cargo == 0 && this->include_empty) {
    00249             *this->stations.Append() = st;
    00250           }
    00251         }
    00252       }
    00253     }
    00254
    00255     this->stations.Compact();
    00256     this->stations.RebuildDone();
    00257
    00258     this->vscroll->SetCount(this->stations.Length()); // Update the scrollbar
    00259   }
    00260
    00262   static int CDECL StationNameSorter(const Station * const *a, const Station * const *b)
    00263   {
    00264     static char buf_cache[64];
    00265     char buf[64];
    00266
    00267     SetDParam(0, (*a)->index);
    00268     GetString(buf, STR_STATION_NAME, lastof(buf));
    00269
    00270     if (*b != last_station) {
    00271       last_station = *b;
    00272       SetDParam(0, (*b)->index);
    00273       GetString(buf_cache, STR_STATION_NAME, lastof(buf_cache));
    00274     }
    00275
    00276     return strcmp(buf, buf_cache);
    00277   }
    00278
    00280   static int CDECL StationTypeSorter(const Station * const *a, const Station * const *b)
    00281   {
    00282     return (*a)->facilities - (*b)->facilities;
    00283   }
    00284
    00286   static int CDECL StationWaitingSorter(const Station * const *a, const Station * const *b)
    00287   {
    00288     Money diff = 0;
    00289
    00290     CargoID j;
    00291     FOR_EACH_SET_CARGO_ID(j, cargo_filter) {
    00292       if (!(*a)->goods[j].cargo.Empty()) diff += GetTransportedGoodsIncome((*a)->goods[j].cargo.Count(), 20, 50, j);
    00293       if (!(*b)->goods[j].cargo.Empty()) diff -= GetTransportedGoodsIncome((*b)->goods[j].cargo.Count(), 20, 50, j);
    00294     }
    00295
    00296     return ClampToI32(diff);
    00297   }
    00298
    00300   static int CDECL StationRatingMaxSorter(const Station * const *a, const Station * const *b)
    00301   {
    00302     byte maxr1 = 0;
    00303     byte maxr2 = 0;
    00304
    00305     CargoID j;
    00306     FOR_EACH_SET_CARGO_ID(j, cargo_filter) {
    00307       if (HasBit((*a)->goods[j].acceptance_pickup, GoodsEntry::PICKUP)) maxr1 = max(maxr1, (*a)->goods[j].rating);
    00308       if (HasBit((*b)->goods[j].acceptance_pickup, GoodsEntry::PICKUP)) maxr2 = max(maxr2, (*b)->goods[j].rating);
    00309     }
    00310
    00311     return maxr1 - maxr2;
    00312   }
    00313
    00315   static int CDECL StationRatingMinSorter(const Station * const *a, const Station * const *b)
    00316   {
    00317     byte minr1 = 255;
    00318     byte minr2 = 255;
    00319
    00320     for (CargoID j = 0; j < NUM_CARGO; j++) {
    00321       if (!HasBit(cargo_filter, j)) continue;
    00322       if (HasBit((*a)->goods[j].acceptance_pickup, GoodsEntry::PICKUP)) minr1 = min(minr1, (*a)->goods[j].rating);
    00323       if (HasBit((*b)->goods[j].acceptance_pickup, GoodsEntry::PICKUP)) minr2 = min(minr2, (*b)->goods[j].rating);
    00324     }
    00325
    00326     return -(minr1 - minr2);
    00327   }
    00328
    00330   void SortStationsList()
    00331   {
    00332     if (!this->stations.Sort()) return;
    00333
    00334     /* Reset name sorter sort cache */
    00335     this->last_station = NULL;
    00336
    00337     /* Set the modified widget dirty */
    00338     this->SetWidgetDirty(SLW_LIST);
    00339   }
    00340
    00341 public:
    00342   CompanyStationsWindow(const WindowDesc *desc, WindowNumber window_number) : Window()
    00343   {
    00344     this->stations.SetListing(this->last_sorting);
    00345     this->stations.SetSortFuncs(this->sorter_funcs);
    00346     this->stations.ForceRebuild();
    00347     this->stations.NeedResort();
    00348     this->SortStationsList();
    00349
    00350     this->CreateNestedTree(desc);
    00351     this->vscroll = this->GetScrollbar(SLW_SCROLLBAR);
    00352     this->FinishInitNested(desc, window_number);
    00353     this->owner = (Owner)this->window_number;
    00354
    00355     CargoID cid;
    00356     FOR_EACH_SET_CARGO_ID(cid, this->cargo_filter) {
    00357       if (CargoSpec::Get(cid)->IsValid()) this->LowerWidget(SLW_CARGOSTART + cid);
    00358     }
    00359
    00360     if (this->cargo_filter == this->cargo_filter_max) this->cargo_filter = _cargo_mask;
    00361
    00362     for (uint i = 0; i < 5; i++) {
    00363       if (HasBit(this->facilities, i)) this->LowerWidget(i + SLW_TRAIN);
    00364     }
    00365     this->SetWidgetLoweredState(SLW_NOCARGOWAITING, this->include_empty);
    00366
    00367     this->GetWidget<NWidgetCore>(SLW_SORTDROPBTN)->widget_data = this->sorter_names[this->stations.SortType()];
    00368   }
    00369
    00370   ~CompanyStationsWindow()
    00371   {
    00372     this->last_sorting = this->stations.GetListing();
    00373   }
    00374
    00375   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    00376   {
    00377     switch (widget) {
    00378       case SLW_SORTBY: {
    00379         Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
    00380         d.width += padding.width + WD_SORTBUTTON_ARROW_WIDTH * 2; // Doubled since the string is centred and it also looks better.
    00381         d.height += padding.height;
    00382         *size = maxdim(*size, d);
    00383         break;
    00384       }
    00385
    00386       case SLW_SORTDROPBTN: {
    00387         Dimension d = {0, 0};
    00388         for (int i = 0; this->sorter_names[i] != INVALID_STRING_ID; i++) {
    00389           d = maxdim(d, GetStringBoundingBox(this->sorter_names[i]));
    00390         }
    00391         d.width += padding.width;
    00392         d.height += padding.height;
    00393         *size = maxdim(*size, d);
    00394         break;
    00395       }
    00396
    00397       case SLW_LIST:
    00398         resize->height = FONT_HEIGHT_NORMAL;
    00399         size->height = WD_FRAMERECT_TOP + 5 * resize->height + WD_FRAMERECT_BOTTOM;
    00400         break;
    00401
    00402       case SLW_TRAIN:
    00403       case SLW_TRUCK:
    00404       case SLW_BUS:
    00405       case SLW_AIRPLANE:
    00406       case SLW_SHIP:
    00407         size->height = max<uint>(FONT_HEIGHT_SMALL, 10) + padding.height;
    00408         break;
    00409
    00410       case SLW_CARGOALL:
    00411       case SLW_FACILALL:
    00412       case SLW_NOCARGOWAITING: {
    00413         Dimension d = GetStringBoundingBox(widget == SLW_NOCARGOWAITING ? STR_ABBREV_NONE : STR_ABBREV_ALL);
    00414         d.width  += padding.width + 2;
    00415         d.height += padding.height;
    00416         *size = maxdim(*size, d);
    00417         break;
    00418       }
    00419
    00420       default:
    00421         if (widget >= SLW_CARGOSTART) {
    00422           const CargoSpec *cs = CargoSpec::Get(widget - SLW_CARGOSTART);
    00423           if (cs->IsValid()) {
    00424             Dimension d = GetStringBoundingBox(cs->abbrev);
    00425             d.width  += padding.width + 2;
    00426             d.height += padding.height;
    00427             *size = maxdim(*size, d);
    00428           }
    00429         }
    00430         break;
    00431     }
    00432   }
    00433
    00434   virtual void OnPaint()
    00435   {
    00436     this->BuildStationsList((Owner)this->window_number);
    00437     this->SortStationsList();
    00438
    00439     this->DrawWidgets();
    00440   }
    00441
    00442   virtual void DrawWidget(const Rect &r, int widget) const
    00443   {
    00444     switch (widget) {
    00445       case SLW_SORTBY:
    00446         /* draw arrow pointing up/down for ascending/descending sorting */
    00447         this->DrawSortButtonState(SLW_SORTBY, this->stations.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
    00448         break;
    00449
    00450       case SLW_LIST: {
    00451         bool rtl = _current_text_dir == TD_RTL;
    00452         int max = min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->stations.Length());
    00453         int y = r.top + WD_FRAMERECT_TOP;
    00454         for (int i = this->vscroll->GetPosition(); i < max; ++i) { // do until max number of stations of owner
    00455           const Station *st = this->stations[i];
    00456           assert(st->xy != INVALID_TILE);
    00457
    00458           /* Do not do the complex check HasStationInUse here, it may be even false
    00459            * when the order had been removed and the station list hasn't been removed yet */
    00460           assert(st->owner == owner || st->owner == OWNER_NONE);
    00461
    00462           SetDParam(0, st->index);
    00463           SetDParam(1, st->facilities);
    00464           int x = DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_LIST_STATION);
    00465           x += rtl ? -5 : 5;
    00466
    00467           /* show cargo waiting and station ratings */
    00468           for (CargoID j = 0; j < NUM_CARGO; j++) {
    00469             if (!st->goods[j].cargo.Empty()) {
    00470               /* For RTL we work in exactly the opposite direction. So
    00471                * decrement the space needed first, then draw to the left
    00472                * instead of drawing to the left and then incrementing
    00473                * the space. */
    00474               if (rtl) {
    00475                 x -= 20;
    00476                 if (x < r.left + WD_FRAMERECT_LEFT) break;
    00477               }
    00478               StationsWndShowStationRating(x, x + 16, y, j, st->goods[j].cargo.Count(), st->goods[j].rating);
    00479               if (!rtl) {
    00480                 x += 20;
    00481                 if (x > r.right - WD_FRAMERECT_RIGHT) break;
    00482               }
    00483             }
    00484           }
    00485           y += FONT_HEIGHT_NORMAL;
    00486         }
    00487
    00488         if (this->vscroll->GetCount() == 0) { // company has no stations
    00489           DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_LIST_NONE);
    00490           return;
    00491         }
    00492         break;
    00493       }
    00494
    00495       case SLW_NOCARGOWAITING: {
    00496         int cg_ofst = this->IsWidgetLowered(widget) ? 2 : 1;
    00497         DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, STR_ABBREV_NONE, TC_BLACK, SA_HOR_CENTER);
    00498         break;
    00499       }
    00500
    00501       case SLW_CARGOALL: {
    00502         int cg_ofst = this->IsWidgetLowered(widget) ? 2 : 1;
    00503         DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, STR_ABBREV_ALL, TC_BLACK, SA_HOR_CENTER);
    00504         break;
    00505       }
    00506
    00507       case SLW_FACILALL: {
    00508         int cg_ofst = this->IsWidgetLowered(widget) ? 2 : 1;
    00509         DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, STR_ABBREV_ALL, TC_BLACK);
    00510         break;
    00511       }
    00512
    00513       default:
    00514         if (widget >= SLW_CARGOSTART) {
    00515           const CargoSpec *cs = CargoSpec::Get(widget - SLW_CARGOSTART);
    00516           if (cs->IsValid()) {
    00517             int cg_ofst = HasBit(this->cargo_filter, cs->Index()) ? 2 : 1;
    00518             GfxFillRect(r.left + cg_ofst, r.top + cg_ofst, r.right - 2 + cg_ofst, r.bottom - 2 + cg_ofst, cs->rating_colour);
    00519             DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, cs->abbrev, TC_BLACK, SA_HOR_CENTER);
    00520           }
    00521         }
    00522         break;
    00523     }
    00524   }
    00525
    00526   virtual void SetStringParameters(int widget) const
    00527   {
    00528     if (widget == SLW_CAPTION) {
    00529       SetDParam(0, this->window_number);
    00530       SetDParam(1, this->vscroll->GetCount());
    00531     }
    00532   }
    00533
    00534   virtual void OnClick(Point pt, int widget, int click_count)
    00535   {
    00536     switch (widget) {
    00537       case SLW_LIST: {
    00538         uint id_v = this->vscroll->GetScrolledRowFromWidget(pt.y, this, SLW_LIST, 0, FONT_HEIGHT_NORMAL);
    00539         if (id_v >= this->stations.Length()) return; // click out of list bound
    00540
    00541         const Station *st = this->stations[id_v];
    00542         /* do not check HasStationInUse - it is slow and may be invalid */
    00543         assert(st->owner == (Owner)this->window_number || st->owner == OWNER_NONE);
    00544
    00545         if (_ctrl_pressed) {
    00546           ShowExtraViewPortWindow(st->xy);
    00547         } else {
    00548           ScrollMainWindowToTile(st->xy);
    00549         }
    00550         break;
    00551       }
    00552
    00553       case SLW_TRAIN:
    00554       case SLW_TRUCK:
    00555       case SLW_BUS:
    00556       case SLW_AIRPLANE:
    00557       case SLW_SHIP:
    00558         if (_ctrl_pressed) {
    00559           ToggleBit(this->facilities, widget - SLW_TRAIN);
    00560           this->ToggleWidgetLoweredState(widget);
    00561         } else {
    00562           uint i;
    00563           FOR_EACH_SET_BIT(i, this->facilities) {
    00564             this->RaiseWidget(i + SLW_TRAIN);
    00565           }
    00566           this->facilities = 1 << (widget - SLW_TRAIN);
    00567           this->LowerWidget(widget);
    00568         }
    00569         this->stations.ForceRebuild();
    00570         this->SetDirty();
    00571         break;
    00572
    00573       case SLW_FACILALL:
    00574         for (uint i = SLW_TRAIN; i <= SLW_SHIP; i++) {
    00575           this->LowerWidget(i);
    00576         }
    00577
    00578         this->facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK;
    00579         this->stations.ForceRebuild();
    00580         this->SetDirty();
    00581         break;
    00582
    00583       case SLW_CARGOALL: {
    00584         for (uint i = 0; i < NUM_CARGO; i++) {
    00585           const CargoSpec *cs = CargoSpec::Get(i);
    00586           if (cs->IsValid()) this->LowerWidget(SLW_CARGOSTART + i);
    00587         }
    00588         this->LowerWidget(SLW_NOCARGOWAITING);
    00589
    00590         this->cargo_filter = _cargo_mask;
    00591         this->include_empty = true;
    00592         this->stations.ForceRebuild();
    00593         this->SetDirty();
    00594         break;
    00595       }
    00596
    00597       case SLW_SORTBY: // flip sorting method asc/desc
    00598         this->stations.ToggleSortOrder();
    00599         this->flags4 |= WF_TIMEOUT_BEGIN;
    00600         this->LowerWidget(SLW_SORTBY);
    00601         this->SetDirty();
    00602         break;
    00603
    00604       case SLW_SORTDROPBTN: // select sorting criteria dropdown menu
    00605         ShowDropDownMenu(this, this->sorter_names, this->stations.SortType(), SLW_SORTDROPBTN, 0, 0);
    00606         break;
    00607
    00608       case SLW_NOCARGOWAITING:
    00609         if (_ctrl_pressed) {
    00610           this->include_empty = !this->include_empty;
    00611           this->ToggleWidgetLoweredState(SLW_NOCARGOWAITING);
    00612         } else {
    00613           for (uint i = 0; i < NUM_CARGO; i++) {
    00614             const CargoSpec *cs = CargoSpec::Get(i);
    00615             if (cs->IsValid()) this->RaiseWidget(SLW_CARGOSTART + i);
    00616           }
    00617
    00618           this->cargo_filter = 0;
    00619           this->include_empty = true;
    00620
    00621           this->LowerWidget(SLW_NOCARGOWAITING);
    00622         }
    00623         this->stations.ForceRebuild();
    00624         this->SetDirty();
    00625         break;
    00626
    00627       default:
    00628         if (widget >= SLW_CARGOSTART) { // change cargo_filter
    00629           /* Determine the selected cargo type */
    00630           const CargoSpec *cs = CargoSpec::Get(widget - SLW_CARGOSTART);
    00631           if (!cs->IsValid()) break;
    00632
    00633           if (_ctrl_pressed) {
    00634             ToggleBit(this->cargo_filter, cs->Index());
    00635             this->ToggleWidgetLoweredState(widget);
    00636           } else {
    00637             for (uint i = 0; i < NUM_CARGO; i++) {
    00638               const CargoSpec *cs = CargoSpec::Get(i);
    00639               if (cs->IsValid()) this->RaiseWidget(SLW_CARGOSTART + i);
    00640             }
    00641             this->RaiseWidget(SLW_NOCARGOWAITING);
    00642
    00643             this->cargo_filter = 0;
    00644             this->include_empty = false;
    00645
    00646             SetBit(this->cargo_filter, cs->Index());
    00647             this->LowerWidget(widget);
    00648           }
    00649           this->stations.ForceRebuild();
    00650           this->SetDirty();
    00651         }
    00652         break;
    00653     }
    00654   }
    00655
    00656   virtual void OnDropdownSelect(int widget, int index)
    00657   {
    00658     if (this->stations.SortType() != index) {
    00659       this->stations.SetSortType(index);
    00660
    00661       /* Display the current sort variant */
    00662       this->GetWidget<NWidgetCore>(SLW_SORTDROPBTN)->widget_data = this->sorter_names[this->stations.SortType()];
    00663
    00664       this->SetDirty();
    00665     }
    00666   }
    00667
    00668   virtual void OnTick()
    00669   {
    00670     if (_pause_mode != PM_UNPAUSED) return;
    00671     if (this->stations.NeedResort()) {
    00672       DEBUG(misc, 3, "Periodic rebuild station list company %d", this->window_number);
    00673       this->SetDirty();
    00674     }
    00675   }
    00676
    00677   virtual void OnTimeout()
    00678   {
    00679     this->RaiseWidget(SLW_SORTBY);
    00680     this->SetDirty();
    00681   }
    00682
    00683   virtual void OnResize()
    00684   {
    00685     this->vscroll->SetCapacityFromWidget(this, SLW_LIST, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
    00686   }
    00687
    00693   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
    00694   {
    00695     if (data == 0) {
    00696       /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
    00697       this->stations.ForceRebuild();
    00698     } else {
    00699       this->stations.ForceResort();
    00700     }
    00701   }
    00702 };
    00703
    00704 Listing CompanyStationsWindow::last_sorting = {false, 0};
    00705 byte CompanyStationsWindow::facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK;
    00706 bool CompanyStationsWindow::include_empty = true;
    00707 const uint32 CompanyStationsWindow::cargo_filter_max = UINT32_MAX;
    00708 uint32 CompanyStationsWindow::cargo_filter = UINT32_MAX;
    00709 const Station *CompanyStationsWindow::last_station = NULL;
    00710
    00711 /* Availible station sorting functions */
    00712 GUIStationList::SortFunction * const CompanyStationsWindow::sorter_funcs[] = {
    00713   &StationNameSorter,
    00714   &StationTypeSorter,
    00715   &StationWaitingSorter,
    00716   &StationRatingMaxSorter,
    00717   &StationRatingMinSorter
    00718 };
    00719
    00720 /* Names of the sorting functions */
    00721 const StringID CompanyStationsWindow::sorter_names[] = {
    00722   STR_SORT_BY_NAME,
    00723   STR_SORT_BY_FACILITY,
    00724   STR_SORT_BY_WAITING,
    00725   STR_SORT_BY_RATING_MAX,
    00726   STR_SORT_BY_RATING_MIN,
    00727   INVALID_STRING_ID
    00728 };
    00729
    00735 static NWidgetBase *CargoWidgets(int *biggest_index)
    00736 {
    00737   NWidgetHorizontal *container = new NWidgetHorizontal();
    00738
    00739   for (uint i = 0; i < NUM_CARGO; i++) {
    00740     const CargoSpec *cs = CargoSpec::Get(i);
    00741     if (cs->IsValid()) {
    00742       NWidgetBackground *panel = new NWidgetBackground(WWT_PANEL, COLOUR_GREY, SLW_CARGOSTART + i);
    00743       panel->SetMinimalSize(14, 11);
    00744       panel->SetResize(0, 0);
    00745       panel->SetFill(0, 1);
    00746       panel->SetDataTip(0, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE);
    00747       container->Add(panel);
    00748     } else {
    00749       NWidgetLeaf *nwi = new NWidgetLeaf(WWT_EMPTY, COLOUR_GREY, SLW_CARGOSTART + i, 0x0, STR_NULL);
    00750       nwi->SetMinimalSize(0, 11);
    00751       nwi->SetResize(0, 0);
    00752       nwi->SetFill(0, 1);
    00753       container->Add(nwi);
    00754     }
    00755   }
    00756   *biggest_index = SLW_CARGOSTART + NUM_CARGO;
    00757   return container;
    00758 }
    00759
    00760 static const NWidgetPart _nested_company_stations_widgets[] = {
    00761   NWidget(NWID_HORIZONTAL),
    00762     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
    00763     NWidget(WWT_CAPTION, COLOUR_GREY, SLW_CAPTION), SetDataTip(STR_STATION_LIST_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
    00764     NWidget(WWT_SHADEBOX, COLOUR_GREY),
    00765     NWidget(WWT_STICKYBOX, COLOUR_GREY),
    00766   EndContainer(),
    00767   NWidget(NWID_HORIZONTAL),
    00768     NWidget(WWT_TEXTBTN, COLOUR_GREY, SLW_TRAIN), SetMinimalSize(14, 11), SetDataTip(STR_TRAIN, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
    00769     NWidget(WWT_TEXTBTN, COLOUR_GREY, SLW_TRUCK), SetMinimalSize(14, 11), SetDataTip(STR_LORRY, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
    00770     NWidget(WWT_TEXTBTN, COLOUR_GREY, SLW_BUS), SetMinimalSize(14, 11), SetDataTip(STR_BUS, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
    00771     NWidget(WWT_TEXTBTN, COLOUR_GREY, SLW_SHIP), SetMinimalSize(14, 11), SetDataTip(STR_SHIP, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
    00772     NWidget(WWT_TEXTBTN, COLOUR_GREY, SLW_AIRPLANE), SetMinimalSize(14, 11), SetDataTip(STR_PLANE, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
    00773     NWidget(WWT_PUSHBTN, COLOUR_GREY, SLW_FACILALL), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_SELECT_ALL_FACILITIES), SetFill(0, 1),
    00774     NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(5, 11), SetFill(0, 1), EndContainer(),
    00775     NWidgetFunction(CargoWidgets),
    00776     NWidget(WWT_PANEL, COLOUR_GREY, SLW_NOCARGOWAITING), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_NO_WAITING_CARGO), SetFill(0, 1), EndContainer(),
    00777     NWidget(WWT_PUSHBTN, COLOUR_GREY, SLW_CARGOALL), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_SELECT_ALL_TYPES), SetFill(0, 1),
    00778     NWidget(WWT_PANEL, COLOUR_GREY), SetDataTip(0x0, STR_NULL), SetResize(1, 0), SetFill(1, 1), EndContainer(),
    00779   EndContainer(),
    00780   NWidget(NWID_HORIZONTAL),
    00781     NWidget(WWT_TEXTBTN, COLOUR_GREY, SLW_SORTBY), SetMinimalSize(81, 12), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
    00782     NWidget(WWT_DROPDOWN, COLOUR_GREY, SLW_SORTDROPBTN), SetMinimalSize(163, 12), SetDataTip(STR_SORT_BY_NAME, STR_TOOLTIP_SORT_CRITERIA), // widget_data gets overwritten.
    00783     NWidget(WWT_PANEL, COLOUR_GREY), SetDataTip(0x0, STR_NULL), SetResize(1, 0), SetFill(1, 1), EndContainer(),
    00784   EndContainer(),
    00785   NWidget(NWID_HORIZONTAL),
    00786     NWidget(WWT_PANEL, COLOUR_GREY, SLW_LIST), SetMinimalSize(346, 125), SetResize(1, 10), SetDataTip(0x0, STR_STATION_LIST_TOOLTIP), SetScrollbar(SLW_SCROLLBAR), EndContainer(),
    00787     NWidget(NWID_VERTICAL),
    00788       NWidget(NWID_VSCROLLBAR, COLOUR_GREY, SLW_SCROLLBAR),
    00789       NWidget(WWT_RESIZEBOX, COLOUR_GREY),
    00790     EndContainer(),
    00791   EndContainer(),
    00792 };
    00793
    00794 static const WindowDesc _company_stations_desc(
    00795   WDP_AUTO, 358, 162,
    00796   WC_STATION_LIST, WC_NONE,
    00797   WDF_UNCLICK_BUTTONS,
    00798   _nested_company_stations_widgets, lengthof(_nested_company_stations_widgets)
    00799 );
    00800
    00806 void ShowCompanyStations(CompanyID company)
    00807 {
    00808   if (!Company::IsValidID(company)) return;
    00809
    00810   AllocateWindowDescFront<CompanyStationsWindow>(&_company_stations_desc, company);
    00811 }
    00812
    00813 static const NWidgetPart _nested_station_view_widgets[] = {
    00814   NWidget(NWID_HORIZONTAL),
    00815     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
    00816     NWidget(WWT_CAPTION, COLOUR_GREY, SVW_CAPTION), SetDataTip(STR_STATION_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
    00817     NWidget(WWT_SHADEBOX, COLOUR_GREY),
    00818     NWidget(WWT_STICKYBOX, COLOUR_GREY),
    00819   EndContainer(),
    00820   NWidget(NWID_HORIZONTAL),
    00821     NWidget(WWT_PANEL, COLOUR_GREY, SVW_WAITING), SetMinimalSize(237, 52), SetResize(1, 10), SetScrollbar(SVW_SCROLLBAR), EndContainer(),
    00822     NWidget(NWID_VSCROLLBAR, COLOUR_GREY, SVW_SCROLLBAR),
    00823   EndContainer(),
    00824   NWidget(WWT_PANEL, COLOUR_GREY, SVW_ACCEPTLIST), SetMinimalSize(249, 32), SetResize(1, 0), EndContainer(),
    00825   NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
    00826     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SVW_LOCATION), SetMinimalSize(60, 12), SetResize(1, 0), SetFill(1, 1),
    00827         SetDataTip(STR_BUTTON_LOCATION, STR_STATION_VIEW_CENTER_TOOLTIP),
    00828     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SVW_ACCEPTS), SetMinimalSize(61, 12), SetResize(1, 0), SetFill(1, 1),
    00829         SetDataTip(STR_STATION_VIEW_RATINGS_BUTTON, STR_STATION_VIEW_RATINGS_TOOLTIP),
    00830     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SVW_RENAME), SetMinimalSize(60, 12), SetResize(1, 0), SetFill(1, 1),
    00831         SetDataTip(STR_BUTTON_RENAME, STR_STATION_VIEW_RENAME_TOOLTIP),
    00832     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SVW_TRAINS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_TRAIN, STR_STATION_VIEW_SCHEDULED_TRAINS_TOOLTIP),
    00833     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SVW_ROADVEHS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_LORRY, STR_STATION_VIEW_SCHEDULED_ROAD_VEHICLES_TOOLTIP),
    00834     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SVW_SHIPS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_SHIP, STR_STATION_VIEW_SCHEDULED_SHIPS_TOOLTIP),
    00835     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SVW_PLANES),  SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_PLANE, STR_STATION_VIEW_SCHEDULED_AIRCRAFT_TOOLTIP),
    00836     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
    00837   EndContainer(),
    00838 };
    00839
    00850 static void DrawCargoIcons(CargoID i, uint waiting, int left, int right, int y)
    00851 {
    00852   uint num = min((waiting + 5) / 10, (right - left) / 10); // maximum is width / 10 icons so it won't overflow
    00853   if (num == 0) return;
    00854
    00855   SpriteID sprite = CargoSpec::Get(i)->GetCargoIcon();
    00856
    00857   int x = _current_text_dir == TD_RTL ? right - num * 10 : left;
    00858   do {
    00859     DrawSprite(sprite, PAL_NONE, x, y);
    00860     x += 10;
    00861   } while (--num);
    00862 }
    00863
    00864 struct CargoData {
    00865   CargoID cargo;
    00866   StationID source;
    00867   uint count;
    00868
    00869   CargoData(CargoID cargo, StationID source, uint count) :
    00870     cargo(cargo),
    00871     source(source),
    00872     count(count)
    00873   { }
    00874 };
    00875
    00876 typedef std::list<CargoData> CargoDataList;
    00877
    00881 struct StationViewWindow : public Window {
    00882   uint32 cargo;
    00883   uint16 cargo_rows[NUM_CARGO];
    00884   uint expand_shrink_width;
    00885   int rating_lines;
    00886   int accepts_lines;
    00887   Scrollbar *vscroll;
    00888
    00890   enum AcceptListHeight {
    00891     ALH_RATING  = 13,
    00892     ALH_ACCEPTS = 3,
    00893   };
    00894
    00895   StationViewWindow(const WindowDesc *desc, WindowNumber window_number) : Window()
    00896   {
    00897     this->rating_lines  = ALH_RATING;
    00898     this->accepts_lines = ALH_ACCEPTS;
    00899
    00900     this->CreateNestedTree(desc);
    00901     this->vscroll = this->GetScrollbar(SVW_SCROLLBAR);
    00902     /* Nested widget tree creation is done in two steps to ensure that this->GetWidget<NWidgetCore>(SVW_ACCEPTS) exists in UpdateWidgetSize(). */
    00903     this->FinishInitNested(desc, window_number);
    00904
    00905     Owner owner = Station::Get(window_number)->owner;
    00906     if (owner != OWNER_NONE) this->owner = owner;
    00907   }
    00908
    00909   ~StationViewWindow()
    00910   {
    00911     Owner owner = Station::Get(this->window_number)->owner;
    00912     if (!Company::IsValidID(owner)) owner = _local_company;
    00913     if (!Company::IsValidID(owner)) return; // Spectators
    00914     DeleteWindowById(WC_TRAINS_LIST,   VehicleListIdentifier(VL_STATION_LIST, VEH_TRAIN,    owner, this->window_number).Pack(), false);
    00915     DeleteWindowById(WC_ROADVEH_LIST,  VehicleListIdentifier(VL_STATION_LIST, VEH_ROAD,     owner, this->window_number).Pack(), false);
    00916     DeleteWindowById(WC_SHIPS_LIST,    VehicleListIdentifier(VL_STATION_LIST, VEH_SHIP,     owner, this->window_number).Pack(), false);
    00917     DeleteWindowById(WC_AIRCRAFT_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_AIRCRAFT, owner, this->window_number).Pack(), false);
    00918   }
    00919
    00920   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    00921   {
    00922     switch (widget) {
    00923       case SVW_WAITING:
    00924         resize->height = FONT_HEIGHT_NORMAL;
    00925         size->height = WD_FRAMERECT_TOP + 5 * resize->height + WD_FRAMERECT_BOTTOM;
    00926         this->expand_shrink_width = max(GetStringBoundingBox("-").width, GetStringBoundingBox("+").width) + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
    00927         break;
    00928
    00929       case SVW_ACCEPTLIST:
    00930         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;
    00931         break;
    00932     }
    00933   }
    00934
    00935   virtual void OnPaint()
    00936   {
    00937     CargoDataList cargolist;
    00938     uint32 transfers = 0;
    00939     this->OrderWaitingCargo(&cargolist, &transfers);
    00940
    00941     this->vscroll->SetCount((int)cargolist.size() + 1); // update scrollbar
    00942
    00943     /* disable some buttons */
    00944     const Station *st = Station::Get(this->window_number);
    00945     this->SetWidgetDisabledState(SVW_RENAME,   st->owner != _local_company);
    00946     this->SetWidgetDisabledState(SVW_TRAINS,   !(st->facilities & FACIL_TRAIN));
    00947     this->SetWidgetDisabledState(SVW_ROADVEHS, !(st->facilities & FACIL_TRUCK_STOP) && !(st->facilities & FACIL_BUS_STOP));
    00948     this->SetWidgetDisabledState(SVW_SHIPS,    !(st->facilities & FACIL_DOCK));
    00949     this->SetWidgetDisabledState(SVW_PLANES,   !(st->facilities & FACIL_AIRPORT));
    00950
    00951     this->DrawWidgets();
    00952
    00953     if (!this->IsShaded()) {
    00954       /* Draw 'accepted cargo' or 'cargo ratings'. */
    00955       const NWidgetBase *wid = this->GetWidget<NWidgetBase>(SVW_ACCEPTLIST);
    00956       const Rect r = {wid->pos_x, wid->pos_y, wid->pos_x + wid->current_x - 1, wid->pos_y + wid->current_y - 1};
    00957       if (this->GetWidget<NWidgetCore>(SVW_ACCEPTS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) {
    00958         int lines = this->DrawAcceptedCargo(r);
    00959         if (lines > this->accepts_lines) { // Resize the widget, and perform re-initialization of the window.
    00960           this->accepts_lines = lines;
    00961           this->ReInit();
    00962           return;
    00963         }
    00964       } else {
    00965         int lines = this->DrawCargoRatings(r);
    00966         if (lines > this->rating_lines) { // Resize the widget, and perform re-initialization of the window.
    00967           this->rating_lines = lines;
    00968           this->ReInit();
    00969           return;
    00970         }
    00971       }
    00972
    00973       /* Draw waiting cargo. */
    00974       NWidgetBase *nwi = this->GetWidget<NWidgetBase>(SVW_WAITING);
    00975       Rect waiting_rect = {nwi->pos_x, nwi->pos_y, nwi->pos_x + nwi->current_x - 1, nwi->pos_y + nwi->current_y - 1};
    00976       this->DrawWaitingCargo(waiting_rect, cargolist, transfers);
    00977     }
    00978   }
    00979
    00980   virtual void SetStringParameters(int widget) const
    00981   {
    00982     if (widget == SVW_CAPTION) {
    00983       const Station *st = Station::Get(this->window_number);
    00984       SetDParam(0, st->index);
    00985       SetDParam(1, st->facilities);
    00986     }
    00987   }
    00988
    00995   void OrderWaitingCargo(CargoDataList *cargolist, uint32 *transfers)
    00996   {
    00997     assert(cargolist->size() == 0);
    00998     *transfers = 0;
    00999
    01000     StationID station_id = this->window_number;
    01001     const Station *st = Station::Get(station_id);
    01002
    01003     /* count types of cargos waiting in station */
    01004     for (CargoID i = 0; i < NUM_CARGO; i++) {
    01005       if (st->goods[i].cargo.Empty()) {
    01006         this->cargo_rows[i] = 0;
    01007       } else {
    01008         /* Add an entry for total amount of cargo of this type waiting. */
    01009         cargolist->push_back(CargoData(i, INVALID_STATION, st->goods[i].cargo.Count()));
    01010
    01011         /* Set the row for this cargo entry for the expand/hide button */
    01012         this->cargo_rows[i] = (uint16)cargolist->size();
    01013
    01014         /* Add an entry for each distinct cargo source. */
    01015         const StationCargoList::List *packets = st->goods[i].cargo.Packets();
    01016         for (StationCargoList::ConstIterator it(packets->begin()); it != packets->end(); it++) {
    01017           const CargoPacket *cp = *it;
    01018           if (cp->SourceStation() != station_id) {
    01019             bool added = false;
    01020
    01021             /* Enable the expand/hide button for this cargo type */
    01022             SetBit(*transfers, i);
    01023
    01024             /* Don't add cargo lines if not expanded */
    01025             if (!HasBit(this->cargo, i)) break;
    01026
    01027             /* Check if we already have this source in the list */
    01028             for (CargoDataList::iterator jt(cargolist->begin()); jt != cargolist->end(); jt++) {
    01029               CargoData *cd = &(*jt);
    01030               if (cd->cargo == i && cd->source == cp->SourceStation()) {
    01031                 cd->count += cp->Count();
    01032                 added = true;
    01033                 break;
    01034               }
    01035             }
    01036
    01037             if (!added) cargolist->push_back(CargoData(i, cp->SourceStation(), cp->Count()));
    01038           }
    01039         }
    01040       }
    01041     }
    01042   }
    01043
    01050   void DrawWaitingCargo(const Rect &r, const CargoDataList &cargolist, uint32 transfers) const
    01051   {
    01052     int y = r.top + WD_FRAMERECT_TOP;
    01053     int pos = this->vscroll->GetPosition();
    01054
    01055     const Station *st = Station::Get(this->window_number);
    01056     if (--pos < 0) {
    01057       StringID str = STR_JUST_NOTHING;
    01058       for (CargoID i = 0; i < NUM_CARGO; i++) {
    01059         if (!st->goods[i].cargo.Empty()) str = STR_EMPTY;
    01060       }
    01061       SetDParam(0, str);
    01062       DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_VIEW_WAITING_TITLE);
    01063       y += FONT_HEIGHT_NORMAL;
    01064     }
    01065
    01066     bool rtl = _current_text_dir == TD_RTL;
    01067     int text_left    = rtl ? r.left + this->expand_shrink_width : r.left + WD_FRAMERECT_LEFT;
    01068     int text_right   = rtl ? r.right - WD_FRAMERECT_LEFT : r.right - this->expand_shrink_width;
    01069     int shrink_left  = rtl ? r.left + WD_FRAMERECT_LEFT : r.right - this->expand_shrink_width + WD_FRAMERECT_LEFT;
    01070     int shrink_right = rtl ? r.left + this->expand_shrink_width - WD_FRAMERECT_RIGHT : r.right - WD_FRAMERECT_RIGHT;
    01071
    01072
    01073     int maxrows = this->vscroll->GetCapacity();
    01074     for (CargoDataList::const_iterator it = cargolist.begin(); it != cargolist.end() && pos > -maxrows; ++it) {
    01075       if (--pos < 0) {
    01076         const CargoData *cd = &(*it);
    01077         if (cd->source == INVALID_STATION) {
    01078           /* Heading */
    01079           DrawCargoIcons(cd->cargo, cd->count, r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y);
    01080           SetDParam(0, cd->cargo);
    01081           SetDParam(1, cd->count);
    01082           if (HasBit(transfers, cd->cargo)) {
    01083             /* This cargo has transfers waiting so show the expand or shrink 'button' */
    01084             const char *sym = HasBit(this->cargo, cd->cargo) ? "-" : "+";
    01085             DrawString(text_left, text_right, y, STR_STATION_VIEW_WAITING_CARGO, TC_FROMSTRING, SA_RIGHT);
    01086             DrawString(shrink_left, shrink_right, y, sym, TC_YELLOW, SA_RIGHT);
    01087           } else {
    01088             DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_VIEW_WAITING_CARGO, TC_FROMSTRING, SA_RIGHT);
    01089           }
    01090         } else {
    01091           SetDParam(0, cd->cargo);
    01092           SetDParam(1, cd->count);
    01093           SetDParam(2, cd->source);
    01094           DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_VIEW_EN_ROUTE_FROM, TC_FROMSTRING, SA_RIGHT);
    01095         }
    01096
    01097         y += FONT_HEIGHT_NORMAL;
    01098       }
    01099     }
    01100   }
    01101
    01107   int DrawAcceptedCargo(const Rect &r) const
    01108   {
    01109     const Station *st = Station::Get(this->window_number);
    01110
    01111     uint32 cargo_mask = 0;
    01112     for (CargoID i = 0; i < NUM_CARGO; i++) {
    01113       if (HasBit(st->goods[i].acceptance_pickup, GoodsEntry::ACCEPTANCE)) SetBit(cargo_mask, i);
    01114     }
    01115     Rect s = {r.left + WD_FRAMERECT_LEFT, r.top + WD_FRAMERECT_TOP, r.right - WD_FRAMERECT_RIGHT, INT32_MAX};
    01116     int bottom = DrawCargoListText(cargo_mask, s, STR_STATION_VIEW_ACCEPTS_CARGO);
    01117     return CeilDiv(bottom - r.top - WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL);
    01118   }
    01119
    01125   int DrawCargoRatings(const Rect &r) const
    01126   {
    01127     const Station *st = Station::Get(this->window_number);
    01128     int y = r.top + WD_FRAMERECT_TOP;
    01129
    01130     DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_VIEW_CARGO_RATINGS_TITLE);
    01131     y += FONT_HEIGHT_NORMAL;
    01132
    01133     const CargoSpec *cs;
    01134     FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
    01135       const GoodsEntry *ge = &st->goods[cs->Index()];
    01136       if (!HasBit(ge->acceptance_pickup, GoodsEntry::PICKUP)) continue;
    01137
    01138       SetDParam(0, cs->name);
    01139       SetDParam(2, ToPercent8(ge->rating));
    01140       SetDParam(1, STR_CARGO_RATING_APPALLING + (ge->rating >> 5));
    01141       DrawString(r.left + WD_FRAMERECT_LEFT + 6, r.right - WD_FRAMERECT_RIGHT - 6, y, STR_STATION_VIEW_CARGO_RATING);
    01142       y += FONT_HEIGHT_NORMAL;
    01143     }
    01144     return CeilDiv(y - r.top - WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL);
    01145   }
    01146
    01147   void HandleCargoWaitingClick(int row)
    01148   {
    01149     if (row == 0) return;
    01150
    01151     for (CargoID c = 0; c < NUM_CARGO; c++) {
    01152       if (this->cargo_rows[c] == row) {
    01153         ToggleBit(this->cargo, c);
    01154         this->SetWidgetDirty(SVW_WAITING);
    01155         break;
    01156       }
    01157     }
    01158   }
    01159
    01160   virtual void OnClick(Point pt, int widget, int click_count)
    01161   {
    01162     switch (widget) {
    01163       case SVW_WAITING:
    01164         this->HandleCargoWaitingClick(this->vscroll->GetScrolledRowFromWidget(pt.y, this, SVW_WAITING, WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL));
    01165         break;
    01166
    01167       case SVW_LOCATION:
    01168         if (_ctrl_pressed) {
    01169           ShowExtraViewPortWindow(Station::Get(this->window_number)->xy);
    01170         } else {
    01171           ScrollMainWindowToTile(Station::Get(this->window_number)->xy);
    01172         }
    01173         break;
    01174
    01175       case SVW_RATINGS: {
    01176         /* Swap between 'accepts' and 'ratings' view. */
    01177         int height_change;
    01178         NWidgetCore *nwi = this->GetWidget<NWidgetCore>(SVW_RATINGS);
    01179         if (this->GetWidget<NWidgetCore>(SVW_RATINGS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) {
    01180           nwi->SetDataTip(STR_STATION_VIEW_ACCEPTS_BUTTON, STR_STATION_VIEW_ACCEPTS_TOOLTIP); // Switch to accepts view.
    01181           height_change = this->rating_lines - this->accepts_lines;
    01182         } else {
    01183           nwi->SetDataTip(STR_STATION_VIEW_RATINGS_BUTTON, STR_STATION_VIEW_RATINGS_TOOLTIP); // Switch to ratings view.
    01184           height_change = this->accepts_lines - this->rating_lines;
    01185         }
    01186         this->ReInit(0, height_change * FONT_HEIGHT_NORMAL);
    01187         break;
    01188       }
    01189
    01190       case SVW_RENAME:
    01191         SetDParam(0, this->window_number);
    01192         ShowQueryString(STR_STATION_NAME, STR_STATION_VIEW_RENAME_STATION_CAPTION, MAX_LENGTH_STATION_NAME_CHARS, MAX_LENGTH_STATION_NAME_PIXELS,
    01193             this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
    01194         break;
    01195
    01196       case SVW_TRAINS:   // Show list of scheduled trains to this station
    01197       case SVW_ROADVEHS: // Show list of scheduled road-vehicles to this station
    01198       case SVW_SHIPS:    // Show list of scheduled ships to this station
    01199       case SVW_PLANES:   // Show list of scheduled aircraft to this station
    01200         ShowVehicleListWindow(this->owner, (VehicleType)(widget - SVW_TRAINS), (StationID)this->window_number);
    01201         break;
    01202     }
    01203   }
    01204
    01205   virtual void OnQueryTextFinished(char *str)
    01206   {
    01207     if (str == NULL) return;
    01208
    01209     DoCommandP(0, this->window_number, 0, CMD_RENAME_STATION | CMD_MSG(STR_ERROR_CAN_T_RENAME_STATION), NULL, str);
    01210   }
    01211
    01212   virtual void OnResize()
    01213   {
    01214     this->vscroll->SetCapacityFromWidget(this, SVW_WAITING, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
    01215   }
    01216 };
    01217
    01218
    01219 static const WindowDesc _station_view_desc(
    01220   WDP_AUTO, 249, 110,
    01221   WC_STATION_VIEW, WC_NONE,
    01222   WDF_UNCLICK_BUTTONS,
    01223   _nested_station_view_widgets, lengthof(_nested_station_view_widgets)
    01224 );
    01225
    01231 void ShowStationViewWindow(StationID station)
    01232 {
    01233   AllocateWindowDescFront<StationViewWindow>(&_station_view_desc, station);
    01234 }
    01235
    01237 struct TileAndStation {
    01238   TileIndex tile;
    01239   StationID station;
    01240 };
    01241
    01242 static SmallVector<TileAndStation, 8> _deleted_stations_nearby;
    01243 static SmallVector<StationID, 8> _stations_nearby_list;
    01244
    01252 template <class T>
    01253 static bool AddNearbyStation(TileIndex tile, void *user_data)
    01254 {
    01255   TileArea *ctx = (TileArea *)user_data;
    01256
    01257   /* First check if there were deleted stations here */
    01258   for (uint i = 0; i < _deleted_stations_nearby.Length(); i++) {
    01259     TileAndStation *ts = _deleted_stations_nearby.Get(i);
    01260     if (ts->tile == tile) {
    01261       *_stations_nearby_list.Append() = _deleted_stations_nearby[i].station;
    01262       _deleted_stations_nearby.Erase(ts);
    01263       i--;
    01264     }
    01265   }
    01266
    01267   /* Check if own station and if we stay within station spread */
    01268   if (!IsTileType(tile, MP_STATION)) return false;
    01269
    01270   StationID sid = GetStationIndex(tile);
    01271
    01272   /* This station is (likely) a waypoint */
    01273   if (!T::IsValidID(sid)) return false;
    01274
    01275   T *st = T::Get(sid);
    01276   if (st->owner != _local_company || _stations_nearby_list.Contains(sid)) return false;
    01277
    01278   if (st->rect.BeforeAddRect(ctx->tile, ctx->w, ctx->h, StationRect::ADD_TEST).Succeeded()) {
    01279     *_stations_nearby_list.Append() = sid;
    01280   }
    01281
    01282   return false; // We want to include *all* nearby stations
    01283 }
    01284
    01294 template <class T>
    01295 static const T *FindStationsNearby(TileArea ta, bool distant_join)
    01296 {
    01297   TileArea ctx = ta;
    01298
    01299   _stations_nearby_list.Clear();
    01300   _deleted_stations_nearby.Clear();
    01301
    01302   /* Check the inside, to return, if we sit on another station */
    01303   TILE_AREA_LOOP(t, ta) {
    01304     if (t < MapSize() && IsTileType(t, MP_STATION) && T::IsValidID(GetStationIndex(t))) return T::GetByTile(t);
    01305   }
    01306
    01307   /* Look for deleted stations */
    01308   const BaseStation *st;
    01309   FOR_ALL_BASE_STATIONS(st) {
    01310     if (T::IsExpected(st) && !st->IsInUse() && st->owner == _local_company) {
    01311       /* Include only within station spread (yes, it is strictly less than) */
    01312       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) {
    01313         TileAndStation *ts = _deleted_stations_nearby.Append();
    01314         ts->tile = st->xy;
    01315         ts->station = st->index;
    01316
    01317         /* Add the station when it's within where we're going to build */
    01318         if (IsInsideBS(TileX(st->xy), TileX(ctx.tile), ctx.w) &&
    01319             IsInsideBS(TileY(st->xy), TileY(ctx.tile), ctx.h)) {
    01320           AddNearbyStation<T>(st->xy, &ctx);
    01321         }
    01322       }
    01323     }
    01324   }
    01325
    01326   /* Only search tiles where we have a chance to stay within the station spread.
    01327    * The complete check needs to be done in the callback as we don't know the
    01328    * extent of the found station, yet. */
    01329   if (distant_join && min(ta.w, ta.h) >= _settings_game.station.station_spread) return NULL;
    01330   uint max_dist = distant_join ? _settings_game.station.station_spread - min(ta.w, ta.h) : 1;
    01331
    01332   TileIndex tile = TILE_ADD(ctx.tile, TileOffsByDir(DIR_N));
    01333   CircularTileSearch(&tile, max_dist, ta.w, ta.h, AddNearbyStation<T>, &ctx);
    01334
    01335   return NULL;
    01336 }
    01337
    01338 enum JoinStationWidgets {
    01339   JSW_WIDGET_CAPTION,
    01340   JSW_PANEL,
    01341   JSW_SCROLLBAR,
    01342 };
    01343
    01344 static const NWidgetPart _nested_select_station_widgets[] = {
    01345   NWidget(NWID_HORIZONTAL),
    01346     NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
    01347     NWidget(WWT_CAPTION, COLOUR_DARK_GREEN, JSW_WIDGET_CAPTION), SetDataTip(STR_JOIN_STATION_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
    01348   EndContainer(),
    01349   NWidget(NWID_HORIZONTAL),
    01350     NWidget(WWT_PANEL, COLOUR_DARK_GREEN, JSW_PANEL), SetResize(1, 0), SetScrollbar(JSW_SCROLLBAR), EndContainer(),
    01351     NWidget(NWID_VERTICAL),
    01352       NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, JSW_SCROLLBAR),
    01353       NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
    01354     EndContainer(),
    01355   EndContainer(),
    01356 };
    01357
    01362 template <class T>
    01363 struct SelectStationWindow : Window {
    01364   CommandContainer select_station_cmd;
    01365   TileArea area;
    01366   Scrollbar *vscroll;
    01367
    01368   SelectStationWindow(const WindowDesc *desc, CommandContainer cmd, TileArea ta) :
    01369     Window(),
    01370     select_station_cmd(cmd),
    01371     area(ta)
    01372   {
    01373     this->CreateNestedTree(desc);
    01374     this->vscroll = this->GetScrollbar(JSW_SCROLLBAR);
    01375     this->GetWidget<NWidgetCore>(JSW_WIDGET_CAPTION)->widget_data = T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_JOIN_WAYPOINT_CAPTION : STR_JOIN_STATION_CAPTION;
    01376     this->FinishInitNested(desc, 0);
    01377     this->OnInvalidateData(0);
    01378   }
    01379
    01380   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    01381   {
    01382     if (widget != JSW_PANEL) return;
    01383
    01384     /* Determine the widest string */
    01385     Dimension d = GetStringBoundingBox(T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_JOIN_WAYPOINT_CREATE_SPLITTED_WAYPOINT : STR_JOIN_STATION_CREATE_SPLITTED_STATION);
    01386     for (uint i = 0; i < _stations_nearby_list.Length(); i++) {
    01387       const T *st = T::Get(_stations_nearby_list[i]);
    01388       SetDParam(0, st->index);
    01389       SetDParam(1, st->facilities);
    01390       d = maxdim(d, GetStringBoundingBox(T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_STATION_LIST_WAYPOINT : STR_STATION_LIST_STATION));
    01391     }
    01392
    01393     resize->height = d.height;
    01394     d.height *= 5;
    01395     d.width += WD_FRAMERECT_RIGHT + WD_FRAMERECT_LEFT;
    01396     d.height += WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
    01397     *size = d;
    01398   }
    01399
    01400   virtual void DrawWidget(const Rect &r, int widget) const
    01401   {
    01402     if (widget != JSW_PANEL) return;
    01403
    01404     uint y = r.top + WD_FRAMERECT_TOP;
    01405     if (this->vscroll->GetPosition() == 0) {
    01406       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);
    01407       y += this->resize.step_height;
    01408     }
    01409
    01410     for (uint i = max<uint>(1, this->vscroll->GetPosition()); i <= _stations_nearby_list.Length(); ++i, y += this->resize.step_height) {
    01411       /* Don't draw anything if it extends past the end of the window. */
    01412       if (i - this->vscroll->GetPosition() >= this->vscroll->GetCapacity()) break;
    01413
    01414       const T *st = T::Get(_stations_nearby_list[i - 1]);
    01415       SetDParam(0, st->index);
    01416       SetDParam(1, st->facilities);
    01417       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);
    01418     }
    01419   }
    01420
    01421   virtual void OnClick(Point pt, int widget, int click_count)
    01422   {
    01423     if (widget != JSW_PANEL) return;
    01424
    01425     uint st_index = this->vscroll->GetScrolledRowFromWidget(pt.y, this, JSW_PANEL, WD_FRAMERECT_TOP);
    01426     bool distant_join = (st_index > 0);
    01427     if (distant_join) st_index--;
    01428
    01429     if (distant_join && st_index >= _stations_nearby_list.Length()) return;
    01430
    01431     /* Insert station to be joined into stored command */
    01432     SB(this->select_station_cmd.p2, 16, 16,
    01433        (distant_join ? _stations_nearby_list[st_index] : NEW_STATION));
    01434
    01435     /* Execute stored Command */
    01436     DoCommandP(&this->select_station_cmd);
    01437
    01438     /* Close Window; this might cause double frees! */
    01439     DeleteWindowById(WC_SELECT_STATION, 0);
    01440   }
    01441
    01442   virtual void OnTick()
    01443   {
    01444     if (_thd.dirty & 2) {
    01445       _thd.dirty &= ~2;
    01446       this->SetDirty();
    01447     }
    01448   }
    01449
    01450   virtual void OnResize()
    01451   {
    01452     this->vscroll->SetCapacityFromWidget(this, JSW_PANEL, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
    01453   }
    01454
    01460   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
    01461   {
    01462     if (!gui_scope) return;
    01463     FindStationsNearby<T>(this->area, true);
    01464     this->vscroll->SetCount(_stations_nearby_list.Length() + 1);
    01465     this->SetDirty();
    01466   }
    01467 };
    01468
    01469 static const WindowDesc _select_station_desc(
    01470   WDP_AUTO, 200, 180,
    01471   WC_SELECT_STATION, WC_NONE,
    01472   WDF_CONSTRUCTION,
    01473   _nested_select_station_widgets, lengthof(_nested_select_station_widgets)
    01474 );
    01475
    01476
    01484 template <class T>
    01485 static bool StationJoinerNeeded(CommandContainer cmd, TileArea ta)
    01486 {
    01487   /* Only show selection if distant join is enabled in the settings */
    01488   if (!_settings_game.station.distant_join_stations) return false;
    01489
    01490   /* If a window is already opened and we didn't ctrl-click,
    01491    * return true (i.e. just flash the old window) */
    01492   Window *selection_window = FindWindowById(WC_SELECT_STATION, 0);
    01493   if (selection_window != NULL) {
    01494     /* Abort current distant-join and start new one */
    01495     delete selection_window;
    01496     UpdateTileSelection();
    01497   }
    01498
    01499   /* only show the popup, if we press ctrl */
    01500   if (!_ctrl_pressed) return false;
    01501
    01502   /* Now check if we could build there */
    01503   if (DoCommand(&cmd, CommandFlagsToDCFlags(GetCommandFlags(cmd.cmd))).Failed()) return false;
    01504
    01505   /* Test for adjacent station or station below selection.
    01506    * If adjacent-stations is disabled and we are building next to a station, do not show the selection window.
    01507    * but join the other station immediately. */
    01508   const T *st = FindStationsNearby<T>(ta, false);
    01509   return st == NULL && (_settings_game.station.adjacent_stations || _stations_nearby_list.Length() == 0);
    01510 }
    01511
    01518 template <class T>
    01519 void ShowSelectBaseStationIfNeeded(CommandContainer cmd, TileArea ta)
    01520 {
    01521   if (StationJoinerNeeded<T>(cmd, ta)) {
    01522     if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
    01523     new SelectStationWindow<T>(&_select_station_desc, cmd, ta);
    01524   } else {
    01525     DoCommandP(&cmd);
    01526   }
    01527 }
    01528
    01534 void ShowSelectStationIfNeeded(CommandContainer cmd, TileArea ta)
    01535 {
    01536   ShowSelectBaseStationIfNeeded<Station>(cmd, ta);
    01537 }
    01538
    01544 void ShowSelectWaypointIfNeeded(CommandContainer cmd, TileArea ta)
    01545 {
    01546   ShowSelectBaseStationIfNeeded<Waypoint>(cmd, ta);
    01547 }