station_gui.cpp

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

Generated on Thu Jan 20 22:57:41 2011 for OpenTTD by  doxygen 1.6.1