station_gui.cpp

Go to the documentation of this file.
00001 /* $Id: station_gui.cpp 22252 2011-03-14 19:03:17Z 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 
00695   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
00696   {
00697     if (data == 0) {
00698       /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
00699       this->stations.ForceRebuild();
00700     } else {
00701       this->stations.ForceResort();
00702     }
00703   }
00704 };
00705 
00706 Listing CompanyStationsWindow::last_sorting = {false, 0};
00707 byte CompanyStationsWindow::facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK;
00708 bool CompanyStationsWindow::include_empty = true;
00709 const uint32 CompanyStationsWindow::cargo_filter_max = UINT32_MAX;
00710 uint32 CompanyStationsWindow::cargo_filter = UINT32_MAX;
00711 const Station *CompanyStationsWindow::last_station = NULL;
00712 
00713 /* Availible station sorting functions */
00714 GUIStationList::SortFunction * const CompanyStationsWindow::sorter_funcs[] = {
00715   &StationNameSorter,
00716   &StationTypeSorter,
00717   &StationWaitingSorter,
00718   &StationRatingMaxSorter,
00719   &StationRatingMinSorter
00720 };
00721 
00722 /* Names of the sorting functions */
00723 const StringID CompanyStationsWindow::sorter_names[] = {
00724   STR_SORT_BY_NAME,
00725   STR_SORT_BY_FACILITY,
00726   STR_SORT_BY_WAITING,
00727   STR_SORT_BY_RATING_MAX,
00728   STR_SORT_BY_RATING_MIN,
00729   INVALID_STRING_ID
00730 };
00731 
00737 static NWidgetBase *CargoWidgets(int *biggest_index)
00738 {
00739   NWidgetHorizontal *container = new NWidgetHorizontal();
00740 
00741   for (uint i = 0; i < NUM_CARGO; i++) {
00742     const CargoSpec *cs = CargoSpec::Get(i);
00743     if (cs->IsValid()) {
00744       NWidgetBackground *panel = new NWidgetBackground(WWT_PANEL, COLOUR_GREY, SLW_CARGOSTART + i);
00745       panel->SetMinimalSize(14, 11);
00746       panel->SetResize(0, 0);
00747       panel->SetFill(0, 1);
00748       panel->SetDataTip(0, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE);
00749       container->Add(panel);
00750     } else {
00751       NWidgetLeaf *nwi = new NWidgetLeaf(WWT_EMPTY, COLOUR_GREY, SLW_CARGOSTART + i, 0x0, STR_NULL);
00752       nwi->SetMinimalSize(0, 11);
00753       nwi->SetResize(0, 0);
00754       nwi->SetFill(0, 1);
00755       container->Add(nwi);
00756     }
00757   }
00758   *biggest_index = SLW_CARGOSTART + NUM_CARGO;
00759   return container;
00760 }
00761 
00762 static const NWidgetPart _nested_company_stations_widgets[] = {
00763   NWidget(NWID_HORIZONTAL),
00764     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
00765     NWidget(WWT_CAPTION, COLOUR_GREY, SLW_CAPTION), SetDataTip(STR_STATION_LIST_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00766     NWidget(WWT_SHADEBOX, COLOUR_GREY),
00767     NWidget(WWT_STICKYBOX, COLOUR_GREY),
00768   EndContainer(),
00769   NWidget(NWID_HORIZONTAL),
00770     NWidget(WWT_TEXTBTN, COLOUR_GREY, SLW_TRAIN), SetMinimalSize(14, 11), SetDataTip(STR_TRAIN, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
00771     NWidget(WWT_TEXTBTN, COLOUR_GREY, SLW_TRUCK), SetMinimalSize(14, 11), SetDataTip(STR_LORRY, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
00772     NWidget(WWT_TEXTBTN, COLOUR_GREY, SLW_BUS), SetMinimalSize(14, 11), SetDataTip(STR_BUS, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
00773     NWidget(WWT_TEXTBTN, COLOUR_GREY, SLW_SHIP), SetMinimalSize(14, 11), SetDataTip(STR_SHIP, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
00774     NWidget(WWT_TEXTBTN, COLOUR_GREY, SLW_AIRPLANE), SetMinimalSize(14, 11), SetDataTip(STR_PLANE, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
00775     NWidget(WWT_PUSHBTN, COLOUR_GREY, SLW_FACILALL), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_SELECT_ALL_FACILITIES), SetFill(0, 1),
00776     NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(5, 11), SetFill(0, 1), EndContainer(),
00777     NWidgetFunction(CargoWidgets),
00778     NWidget(WWT_PANEL, COLOUR_GREY, SLW_NOCARGOWAITING), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_NO_WAITING_CARGO), SetFill(0, 1), EndContainer(),
00779     NWidget(WWT_PUSHBTN, COLOUR_GREY, SLW_CARGOALL), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_SELECT_ALL_TYPES), SetFill(0, 1),
00780     NWidget(WWT_PANEL, COLOUR_GREY), SetDataTip(0x0, STR_NULL), SetResize(1, 0), SetFill(1, 1), EndContainer(),
00781   EndContainer(),
00782   NWidget(NWID_HORIZONTAL),
00783     NWidget(WWT_TEXTBTN, COLOUR_GREY, SLW_SORTBY), SetMinimalSize(81, 12), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
00784     NWidget(WWT_DROPDOWN, COLOUR_GREY, SLW_SORTDROPBTN), SetMinimalSize(163, 12), SetDataTip(STR_SORT_BY_NAME, STR_TOOLTIP_SORT_CRITERIA), // widget_data gets overwritten.
00785     NWidget(WWT_PANEL, COLOUR_GREY), SetDataTip(0x0, STR_NULL), SetResize(1, 0), SetFill(1, 1), EndContainer(),
00786   EndContainer(),
00787   NWidget(NWID_HORIZONTAL),
00788     NWidget(WWT_PANEL, COLOUR_GREY, SLW_LIST), SetMinimalSize(346, 125), SetResize(1, 10), SetDataTip(0x0, STR_STATION_LIST_TOOLTIP), SetScrollbar(SLW_SCROLLBAR), EndContainer(),
00789     NWidget(NWID_VERTICAL),
00790       NWidget(NWID_VSCROLLBAR, COLOUR_GREY, SLW_SCROLLBAR),
00791       NWidget(WWT_RESIZEBOX, COLOUR_GREY),
00792     EndContainer(),
00793   EndContainer(),
00794 };
00795 
00796 static const WindowDesc _company_stations_desc(
00797   WDP_AUTO, 358, 162,
00798   WC_STATION_LIST, WC_NONE,
00799   WDF_UNCLICK_BUTTONS,
00800   _nested_company_stations_widgets, lengthof(_nested_company_stations_widgets)
00801 );
00802 
00808 void ShowCompanyStations(CompanyID company)
00809 {
00810   if (!Company::IsValidID(company)) return;
00811 
00812   AllocateWindowDescFront<CompanyStationsWindow>(&_company_stations_desc, company);
00813 }
00814 
00815 static const NWidgetPart _nested_station_view_widgets[] = {
00816   NWidget(NWID_HORIZONTAL),
00817     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
00818     NWidget(WWT_CAPTION, COLOUR_GREY, SVW_CAPTION), SetDataTip(STR_STATION_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00819     NWidget(WWT_SHADEBOX, COLOUR_GREY),
00820     NWidget(WWT_STICKYBOX, COLOUR_GREY),
00821   EndContainer(),
00822   NWidget(NWID_HORIZONTAL),
00823     NWidget(WWT_PANEL, COLOUR_GREY, SVW_WAITING), SetMinimalSize(237, 52), SetResize(1, 10), SetScrollbar(SVW_SCROLLBAR), EndContainer(),
00824     NWidget(NWID_VSCROLLBAR, COLOUR_GREY, SVW_SCROLLBAR),
00825   EndContainer(),
00826   NWidget(WWT_PANEL, COLOUR_GREY, SVW_ACCEPTLIST), SetMinimalSize(249, 32), SetResize(1, 0), EndContainer(),
00827   NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
00828     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SVW_LOCATION), SetMinimalSize(60, 12), SetResize(1, 0), SetFill(1, 1),
00829         SetDataTip(STR_BUTTON_LOCATION, STR_STATION_VIEW_CENTER_TOOLTIP),
00830     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SVW_ACCEPTS), SetMinimalSize(61, 12), SetResize(1, 0), SetFill(1, 1),
00831         SetDataTip(STR_STATION_VIEW_RATINGS_BUTTON, STR_STATION_VIEW_RATINGS_TOOLTIP),
00832     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SVW_RENAME), SetMinimalSize(60, 12), SetResize(1, 0), SetFill(1, 1),
00833         SetDataTip(STR_BUTTON_RENAME, STR_STATION_VIEW_RENAME_TOOLTIP),
00834     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SVW_TRAINS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_TRAIN, STR_STATION_VIEW_SCHEDULED_TRAINS_TOOLTIP),
00835     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SVW_ROADVEHS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_LORRY, STR_STATION_VIEW_SCHEDULED_ROAD_VEHICLES_TOOLTIP),
00836     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SVW_SHIPS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_SHIP, STR_STATION_VIEW_SCHEDULED_SHIPS_TOOLTIP),
00837     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, SVW_PLANES),  SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_PLANE, STR_STATION_VIEW_SCHEDULED_AIRCRAFT_TOOLTIP),
00838     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
00839   EndContainer(),
00840 };
00841 
00852 static void DrawCargoIcons(CargoID i, uint waiting, int left, int right, int y)
00853 {
00854   uint num = min((waiting + 5) / 10, (right - left) / 10); // maximum is width / 10 icons so it won't overflow
00855   if (num == 0) return;
00856 
00857   SpriteID sprite = CargoSpec::Get(i)->GetCargoIcon();
00858 
00859   int x = _current_text_dir == TD_RTL ? right - num * 10 : left;
00860   do {
00861     DrawSprite(sprite, PAL_NONE, x, y);
00862     x += 10;
00863   } while (--num);
00864 }
00865 
00866 struct CargoData {
00867   CargoID cargo;
00868   StationID source;
00869   uint count;
00870 
00871   CargoData(CargoID cargo, StationID source, uint count) :
00872     cargo(cargo),
00873     source(source),
00874     count(count)
00875   { }
00876 };
00877 
00878 typedef std::list<CargoData> CargoDataList;
00879 
00883 struct StationViewWindow : public Window {
00884   uint32 cargo;                 
00885   uint16 cargo_rows[NUM_CARGO]; 
00886   uint expand_shrink_width;     
00887   int rating_lines;             
00888   int accepts_lines;            
00889   Scrollbar *vscroll;
00890 
00892   enum AcceptListHeight {
00893     ALH_RATING  = 13, 
00894     ALH_ACCEPTS = 3,  
00895   };
00896 
00897   StationViewWindow(const WindowDesc *desc, WindowNumber window_number) : Window()
00898   {
00899     this->rating_lines  = ALH_RATING;
00900     this->accepts_lines = ALH_ACCEPTS;
00901 
00902     this->CreateNestedTree(desc);
00903     this->vscroll = this->GetScrollbar(SVW_SCROLLBAR);
00904     /* Nested widget tree creation is done in two steps to ensure that this->GetWidget<NWidgetCore>(SVW_ACCEPTS) exists in UpdateWidgetSize(). */
00905     this->FinishInitNested(desc, window_number);
00906 
00907     Owner owner = Station::Get(window_number)->owner;
00908     if (owner != OWNER_NONE) this->owner = owner;
00909   }
00910 
00911   ~StationViewWindow()
00912   {
00913     Owner owner = Station::Get(this->window_number)->owner;
00914     if (!Company::IsValidID(owner)) owner = _local_company;
00915     if (!Company::IsValidID(owner)) return; // Spectators
00916     DeleteWindowById(WC_TRAINS_LIST,   VehicleListIdentifier(VL_STATION_LIST, VEH_TRAIN,    owner, this->window_number).Pack(), false);
00917     DeleteWindowById(WC_ROADVEH_LIST,  VehicleListIdentifier(VL_STATION_LIST, VEH_ROAD,     owner, this->window_number).Pack(), false);
00918     DeleteWindowById(WC_SHIPS_LIST,    VehicleListIdentifier(VL_STATION_LIST, VEH_SHIP,     owner, this->window_number).Pack(), false);
00919     DeleteWindowById(WC_AIRCRAFT_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_AIRCRAFT, owner, this->window_number).Pack(), false);
00920   }
00921 
00922   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00923   {
00924     switch (widget) {
00925       case SVW_WAITING:
00926         resize->height = FONT_HEIGHT_NORMAL;
00927         size->height = WD_FRAMERECT_TOP + 5 * resize->height + WD_FRAMERECT_BOTTOM;
00928         this->expand_shrink_width = max(GetStringBoundingBox("-").width, GetStringBoundingBox("+").width) + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
00929         break;
00930 
00931       case SVW_ACCEPTLIST:
00932         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;
00933         break;
00934     }
00935   }
00936 
00937   virtual void OnPaint()
00938   {
00939     CargoDataList cargolist;
00940     uint32 transfers = 0;
00941     this->OrderWaitingCargo(&cargolist, &transfers);
00942 
00943     this->vscroll->SetCount((int)cargolist.size() + 1); // update scrollbar
00944 
00945     /* disable some buttons */
00946     const Station *st = Station::Get(this->window_number);
00947     this->SetWidgetDisabledState(SVW_RENAME,   st->owner != _local_company);
00948     this->SetWidgetDisabledState(SVW_TRAINS,   !(st->facilities & FACIL_TRAIN));
00949     this->SetWidgetDisabledState(SVW_ROADVEHS, !(st->facilities & FACIL_TRUCK_STOP) && !(st->facilities & FACIL_BUS_STOP));
00950     this->SetWidgetDisabledState(SVW_SHIPS,    !(st->facilities & FACIL_DOCK));
00951     this->SetWidgetDisabledState(SVW_PLANES,   !(st->facilities & FACIL_AIRPORT));
00952 
00953     this->DrawWidgets();
00954 
00955     if (!this->IsShaded()) {
00956       /* Draw 'accepted cargo' or 'cargo ratings'. */
00957       const NWidgetBase *wid = this->GetWidget<NWidgetBase>(SVW_ACCEPTLIST);
00958       const Rect r = {wid->pos_x, wid->pos_y, wid->pos_x + wid->current_x - 1, wid->pos_y + wid->current_y - 1};
00959       if (this->GetWidget<NWidgetCore>(SVW_ACCEPTS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) {
00960         int lines = this->DrawAcceptedCargo(r);
00961         if (lines > this->accepts_lines) { // Resize the widget, and perform re-initialization of the window.
00962           this->accepts_lines = lines;
00963           this->ReInit();
00964           return;
00965         }
00966       } else {
00967         int lines = this->DrawCargoRatings(r);
00968         if (lines > this->rating_lines) { // Resize the widget, and perform re-initialization of the window.
00969           this->rating_lines = lines;
00970           this->ReInit();
00971           return;
00972         }
00973       }
00974 
00975       /* Draw waiting cargo. */
00976       NWidgetBase *nwi = this->GetWidget<NWidgetBase>(SVW_WAITING);
00977       Rect waiting_rect = {nwi->pos_x, nwi->pos_y, nwi->pos_x + nwi->current_x - 1, nwi->pos_y + nwi->current_y - 1};
00978       this->DrawWaitingCargo(waiting_rect, cargolist, transfers);
00979     }
00980   }
00981 
00982   virtual void SetStringParameters(int widget) const
00983   {
00984     if (widget == SVW_CAPTION) {
00985       const Station *st = Station::Get(this->window_number);
00986       SetDParam(0, st->index);
00987       SetDParam(1, st->facilities);
00988     }
00989   }
00990 
00997   void OrderWaitingCargo(CargoDataList *cargolist, uint32 *transfers)
00998   {
00999     assert(cargolist->size() == 0);
01000     *transfers = 0;
01001 
01002     StationID station_id = this->window_number;
01003     const Station *st = Station::Get(station_id);
01004 
01005     /* count types of cargos waiting in station */
01006     for (CargoID i = 0; i < NUM_CARGO; i++) {
01007       if (st->goods[i].cargo.Empty()) {
01008         this->cargo_rows[i] = 0;
01009       } else {
01010         /* Add an entry for total amount of cargo of this type waiting. */
01011         cargolist->push_back(CargoData(i, INVALID_STATION, st->goods[i].cargo.Count()));
01012 
01013         /* Set the row for this cargo entry for the expand/hide button */
01014         this->cargo_rows[i] = (uint16)cargolist->size();
01015 
01016         /* Add an entry for each distinct cargo source. */
01017         const StationCargoList::List *packets = st->goods[i].cargo.Packets();
01018         for (StationCargoList::ConstIterator it(packets->begin()); it != packets->end(); it++) {
01019           const CargoPacket *cp = *it;
01020           if (cp->SourceStation() != station_id) {
01021             bool added = false;
01022 
01023             /* Enable the expand/hide button for this cargo type */
01024             SetBit(*transfers, i);
01025 
01026             /* Don't add cargo lines if not expanded */
01027             if (!HasBit(this->cargo, i)) break;
01028 
01029             /* Check if we already have this source in the list */
01030             for (CargoDataList::iterator jt(cargolist->begin()); jt != cargolist->end(); jt++) {
01031               CargoData *cd = &(*jt);
01032               if (cd->cargo == i && cd->source == cp->SourceStation()) {
01033                 cd->count += cp->Count();
01034                 added = true;
01035                 break;
01036               }
01037             }
01038 
01039             if (!added) cargolist->push_back(CargoData(i, cp->SourceStation(), cp->Count()));
01040           }
01041         }
01042       }
01043     }
01044   }
01045 
01052   void DrawWaitingCargo(const Rect &r, const CargoDataList &cargolist, uint32 transfers) const
01053   {
01054     int y = r.top + WD_FRAMERECT_TOP;
01055     int pos = this->vscroll->GetPosition();
01056 
01057     const Station *st = Station::Get(this->window_number);
01058     if (--pos < 0) {
01059       StringID str = STR_JUST_NOTHING;
01060       for (CargoID i = 0; i < NUM_CARGO; i++) {
01061         if (!st->goods[i].cargo.Empty()) str = STR_EMPTY;
01062       }
01063       SetDParam(0, str);
01064       DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_VIEW_WAITING_TITLE);
01065       y += FONT_HEIGHT_NORMAL;
01066     }
01067 
01068     bool rtl = _current_text_dir == TD_RTL;
01069     int text_left    = rtl ? r.left + this->expand_shrink_width : r.left + WD_FRAMERECT_LEFT;
01070     int text_right   = rtl ? r.right - WD_FRAMERECT_LEFT : r.right - this->expand_shrink_width;
01071     int shrink_left  = rtl ? r.left + WD_FRAMERECT_LEFT : r.right - this->expand_shrink_width + WD_FRAMERECT_LEFT;
01072     int shrink_right = rtl ? r.left + this->expand_shrink_width - WD_FRAMERECT_RIGHT : r.right - WD_FRAMERECT_RIGHT;
01073 
01074 
01075     int maxrows = this->vscroll->GetCapacity();
01076     for (CargoDataList::const_iterator it = cargolist.begin(); it != cargolist.end() && pos > -maxrows; ++it) {
01077       if (--pos < 0) {
01078         const CargoData *cd = &(*it);
01079         if (cd->source == INVALID_STATION) {
01080           /* Heading */
01081           DrawCargoIcons(cd->cargo, cd->count, r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y);
01082           SetDParam(0, cd->cargo);
01083           SetDParam(1, cd->count);
01084           if (HasBit(transfers, cd->cargo)) {
01085             /* This cargo has transfers waiting so show the expand or shrink 'button' */
01086             const char *sym = HasBit(this->cargo, cd->cargo) ? "-" : "+";
01087             DrawString(text_left, text_right, y, STR_STATION_VIEW_WAITING_CARGO, TC_FROMSTRING, SA_RIGHT);
01088             DrawString(shrink_left, shrink_right, y, sym, TC_YELLOW, SA_RIGHT);
01089           } else {
01090             DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_VIEW_WAITING_CARGO, TC_FROMSTRING, SA_RIGHT);
01091           }
01092         } else {
01093           SetDParam(0, cd->cargo);
01094           SetDParam(1, cd->count);
01095           SetDParam(2, cd->source);
01096           DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_VIEW_EN_ROUTE_FROM, TC_FROMSTRING, SA_RIGHT);
01097         }
01098 
01099         y += FONT_HEIGHT_NORMAL;
01100       }
01101     }
01102   }
01103 
01109   int DrawAcceptedCargo(const Rect &r) const
01110   {
01111     const Station *st = Station::Get(this->window_number);
01112 
01113     uint32 cargo_mask = 0;
01114     for (CargoID i = 0; i < NUM_CARGO; i++) {
01115       if (HasBit(st->goods[i].acceptance_pickup, GoodsEntry::ACCEPTANCE)) SetBit(cargo_mask, i);
01116     }
01117     Rect s = {r.left + WD_FRAMERECT_LEFT, r.top + WD_FRAMERECT_TOP, r.right - WD_FRAMERECT_RIGHT, INT32_MAX};
01118     int bottom = DrawCargoListText(cargo_mask, s, STR_STATION_VIEW_ACCEPTS_CARGO);
01119     return CeilDiv(bottom - r.top - WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL);
01120   }
01121 
01127   int DrawCargoRatings(const Rect &r) const
01128   {
01129     const Station *st = Station::Get(this->window_number);
01130     int y = r.top + WD_FRAMERECT_TOP;
01131 
01132     DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_VIEW_CARGO_RATINGS_TITLE);
01133     y += FONT_HEIGHT_NORMAL;
01134 
01135     const CargoSpec *cs;
01136     FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
01137       const GoodsEntry *ge = &st->goods[cs->Index()];
01138       if (!HasBit(ge->acceptance_pickup, GoodsEntry::PICKUP)) continue;
01139 
01140       SetDParam(0, cs->name);
01141       SetDParam(2, ToPercent8(ge->rating));
01142       SetDParam(1, STR_CARGO_RATING_APPALLING + (ge->rating >> 5));
01143       DrawString(r.left + WD_FRAMERECT_LEFT + 6, r.right - WD_FRAMERECT_RIGHT - 6, y, STR_STATION_VIEW_CARGO_RATING);
01144       y += FONT_HEIGHT_NORMAL;
01145     }
01146     return CeilDiv(y - r.top - WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL);
01147   }
01148 
01149   void HandleCargoWaitingClick(int row)
01150   {
01151     if (row == 0) return;
01152 
01153     for (CargoID c = 0; c < NUM_CARGO; c++) {
01154       if (this->cargo_rows[c] == row) {
01155         ToggleBit(this->cargo, c);
01156         this->SetWidgetDirty(SVW_WAITING);
01157         break;
01158       }
01159     }
01160   }
01161 
01162   virtual void OnClick(Point pt, int widget, int click_count)
01163   {
01164     switch (widget) {
01165       case SVW_WAITING:
01166         this->HandleCargoWaitingClick(this->vscroll->GetScrolledRowFromWidget(pt.y, this, SVW_WAITING, WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL));
01167         break;
01168 
01169       case SVW_LOCATION:
01170         if (_ctrl_pressed) {
01171           ShowExtraViewPortWindow(Station::Get(this->window_number)->xy);
01172         } else {
01173           ScrollMainWindowToTile(Station::Get(this->window_number)->xy);
01174         }
01175         break;
01176 
01177       case SVW_RATINGS: {
01178         /* Swap between 'accepts' and 'ratings' view. */
01179         int height_change;
01180         NWidgetCore *nwi = this->GetWidget<NWidgetCore>(SVW_RATINGS);
01181         if (this->GetWidget<NWidgetCore>(SVW_RATINGS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) {
01182           nwi->SetDataTip(STR_STATION_VIEW_ACCEPTS_BUTTON, STR_STATION_VIEW_ACCEPTS_TOOLTIP); // Switch to accepts view.
01183           height_change = this->rating_lines - this->accepts_lines;
01184         } else {
01185           nwi->SetDataTip(STR_STATION_VIEW_RATINGS_BUTTON, STR_STATION_VIEW_RATINGS_TOOLTIP); // Switch to ratings view.
01186           height_change = this->accepts_lines - this->rating_lines;
01187         }
01188         this->ReInit(0, height_change * FONT_HEIGHT_NORMAL);
01189         break;
01190       }
01191 
01192       case SVW_RENAME:
01193         SetDParam(0, this->window_number);
01194         ShowQueryString(STR_STATION_NAME, STR_STATION_VIEW_RENAME_STATION_CAPTION, MAX_LENGTH_STATION_NAME_CHARS, MAX_LENGTH_STATION_NAME_PIXELS,
01195             this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
01196         break;
01197 
01198       case SVW_TRAINS:   // Show list of scheduled trains to this station
01199       case SVW_ROADVEHS: // Show list of scheduled road-vehicles to this station
01200       case SVW_SHIPS:    // Show list of scheduled ships to this station
01201       case SVW_PLANES:   // Show list of scheduled aircraft to this station
01202         ShowVehicleListWindow(this->owner, (VehicleType)(widget - SVW_TRAINS), (StationID)this->window_number);
01203         break;
01204     }
01205   }
01206 
01207   virtual void OnQueryTextFinished(char *str)
01208   {
01209     if (str == NULL) return;
01210 
01211     DoCommandP(0, this->window_number, 0, CMD_RENAME_STATION | CMD_MSG(STR_ERROR_CAN_T_RENAME_STATION), NULL, str);
01212   }
01213 
01214   virtual void OnResize()
01215   {
01216     this->vscroll->SetCapacityFromWidget(this, SVW_WAITING, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
01217   }
01218 };
01219 
01220 
01221 static const WindowDesc _station_view_desc(
01222   WDP_AUTO, 249, 110,
01223   WC_STATION_VIEW, WC_NONE,
01224   WDF_UNCLICK_BUTTONS,
01225   _nested_station_view_widgets, lengthof(_nested_station_view_widgets)
01226 );
01227 
01233 void ShowStationViewWindow(StationID station)
01234 {
01235   AllocateWindowDescFront<StationViewWindow>(&_station_view_desc, station);
01236 }
01237 
01239 struct TileAndStation {
01240   TileIndex tile;    
01241   StationID station; 
01242 };
01243 
01244 static SmallVector<TileAndStation, 8> _deleted_stations_nearby;
01245 static SmallVector<StationID, 8> _stations_nearby_list;
01246 
01254 template <class T>
01255 static bool AddNearbyStation(TileIndex tile, void *user_data)
01256 {
01257   TileArea *ctx = (TileArea *)user_data;
01258 
01259   /* First check if there were deleted stations here */
01260   for (uint i = 0; i < _deleted_stations_nearby.Length(); i++) {
01261     TileAndStation *ts = _deleted_stations_nearby.Get(i);
01262     if (ts->tile == tile) {
01263       *_stations_nearby_list.Append() = _deleted_stations_nearby[i].station;
01264       _deleted_stations_nearby.Erase(ts);
01265       i--;
01266     }
01267   }
01268 
01269   /* Check if own station and if we stay within station spread */
01270   if (!IsTileType(tile, MP_STATION)) return false;
01271 
01272   StationID sid = GetStationIndex(tile);
01273 
01274   /* This station is (likely) a waypoint */
01275   if (!T::IsValidID(sid)) return false;
01276 
01277   T *st = T::Get(sid);
01278   if (st->owner != _local_company || _stations_nearby_list.Contains(sid)) return false;
01279 
01280   if (st->rect.BeforeAddRect(ctx->tile, ctx->w, ctx->h, StationRect::ADD_TEST).Succeeded()) {
01281     *_stations_nearby_list.Append() = sid;
01282   }
01283 
01284   return false; // We want to include *all* nearby stations
01285 }
01286 
01296 template <class T>
01297 static const T *FindStationsNearby(TileArea ta, bool distant_join)
01298 {
01299   TileArea ctx = ta;
01300 
01301   _stations_nearby_list.Clear();
01302   _deleted_stations_nearby.Clear();
01303 
01304   /* Check the inside, to return, if we sit on another station */
01305   TILE_AREA_LOOP(t, ta) {
01306     if (t < MapSize() && IsTileType(t, MP_STATION) && T::IsValidID(GetStationIndex(t))) return T::GetByTile(t);
01307   }
01308 
01309   /* Look for deleted stations */
01310   const BaseStation *st;
01311   FOR_ALL_BASE_STATIONS(st) {
01312     if (T::IsExpected(st) && !st->IsInUse() && st->owner == _local_company) {
01313       /* Include only within station spread (yes, it is strictly less than) */
01314       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) {
01315         TileAndStation *ts = _deleted_stations_nearby.Append();
01316         ts->tile = st->xy;
01317         ts->station = st->index;
01318 
01319         /* Add the station when it's within where we're going to build */
01320         if (IsInsideBS(TileX(st->xy), TileX(ctx.tile), ctx.w) &&
01321             IsInsideBS(TileY(st->xy), TileY(ctx.tile), ctx.h)) {
01322           AddNearbyStation<T>(st->xy, &ctx);
01323         }
01324       }
01325     }
01326   }
01327 
01328   /* Only search tiles where we have a chance to stay within the station spread.
01329    * The complete check needs to be done in the callback as we don't know the
01330    * extent of the found station, yet. */
01331   if (distant_join && min(ta.w, ta.h) >= _settings_game.station.station_spread) return NULL;
01332   uint max_dist = distant_join ? _settings_game.station.station_spread - min(ta.w, ta.h) : 1;
01333 
01334   TileIndex tile = TILE_ADD(ctx.tile, TileOffsByDir(DIR_N));
01335   CircularTileSearch(&tile, max_dist, ta.w, ta.h, AddNearbyStation<T>, &ctx);
01336 
01337   return NULL;
01338 }
01339 
01340 enum JoinStationWidgets {
01341   JSW_WIDGET_CAPTION,
01342   JSW_PANEL,
01343   JSW_SCROLLBAR,
01344 };
01345 
01346 static const NWidgetPart _nested_select_station_widgets[] = {
01347   NWidget(NWID_HORIZONTAL),
01348     NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
01349     NWidget(WWT_CAPTION, COLOUR_DARK_GREEN, JSW_WIDGET_CAPTION), SetDataTip(STR_JOIN_STATION_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
01350   EndContainer(),
01351   NWidget(NWID_HORIZONTAL),
01352     NWidget(WWT_PANEL, COLOUR_DARK_GREEN, JSW_PANEL), SetResize(1, 0), SetScrollbar(JSW_SCROLLBAR), EndContainer(),
01353     NWidget(NWID_VERTICAL),
01354       NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, JSW_SCROLLBAR),
01355       NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
01356     EndContainer(),
01357   EndContainer(),
01358 };
01359 
01364 template <class T>
01365 struct SelectStationWindow : Window {
01366   CommandContainer select_station_cmd; 
01367   TileArea area; 
01368   Scrollbar *vscroll;
01369 
01370   SelectStationWindow(const WindowDesc *desc, CommandContainer cmd, TileArea ta) :
01371     Window(),
01372     select_station_cmd(cmd),
01373     area(ta)
01374   {
01375     this->CreateNestedTree(desc);
01376     this->vscroll = this->GetScrollbar(JSW_SCROLLBAR);
01377     this->GetWidget<NWidgetCore>(JSW_WIDGET_CAPTION)->widget_data = T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_JOIN_WAYPOINT_CAPTION : STR_JOIN_STATION_CAPTION;
01378     this->FinishInitNested(desc, 0);
01379     this->OnInvalidateData(0);
01380   }
01381 
01382   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01383   {
01384     if (widget != JSW_PANEL) return;
01385 
01386     /* Determine the widest string */
01387     Dimension d = GetStringBoundingBox(T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_JOIN_WAYPOINT_CREATE_SPLITTED_WAYPOINT : STR_JOIN_STATION_CREATE_SPLITTED_STATION);
01388     for (uint i = 0; i < _stations_nearby_list.Length(); i++) {
01389       const T *st = T::Get(_stations_nearby_list[i]);
01390       SetDParam(0, st->index);
01391       SetDParam(1, st->facilities);
01392       d = maxdim(d, GetStringBoundingBox(T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_STATION_LIST_WAYPOINT : STR_STATION_LIST_STATION));
01393     }
01394 
01395     resize->height = d.height;
01396     d.height *= 5;
01397     d.width += WD_FRAMERECT_RIGHT + WD_FRAMERECT_LEFT;
01398     d.height += WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
01399     *size = d;
01400   }
01401 
01402   virtual void DrawWidget(const Rect &r, int widget) const
01403   {
01404     if (widget != JSW_PANEL) return;
01405 
01406     uint y = r.top + WD_FRAMERECT_TOP;
01407     if (this->vscroll->GetPosition() == 0) {
01408       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);
01409       y += this->resize.step_height;
01410     }
01411 
01412     for (uint i = max<uint>(1, this->vscroll->GetPosition()); i <= _stations_nearby_list.Length(); ++i, y += this->resize.step_height) {
01413       /* Don't draw anything if it extends past the end of the window. */
01414       if (i - this->vscroll->GetPosition() >= this->vscroll->GetCapacity()) break;
01415 
01416       const T *st = T::Get(_stations_nearby_list[i - 1]);
01417       SetDParam(0, st->index);
01418       SetDParam(1, st->facilities);
01419       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);
01420     }
01421   }
01422 
01423   virtual void OnClick(Point pt, int widget, int click_count)
01424   {
01425     if (widget != JSW_PANEL) return;
01426 
01427     uint st_index = this->vscroll->GetScrolledRowFromWidget(pt.y, this, JSW_PANEL, WD_FRAMERECT_TOP);
01428     bool distant_join = (st_index > 0);
01429     if (distant_join) st_index--;
01430 
01431     if (distant_join && st_index >= _stations_nearby_list.Length()) return;
01432 
01433     /* Insert station to be joined into stored command */
01434     SB(this->select_station_cmd.p2, 16, 16,
01435        (distant_join ? _stations_nearby_list[st_index] : NEW_STATION));
01436 
01437     /* Execute stored Command */
01438     DoCommandP(&this->select_station_cmd);
01439 
01440     /* Close Window; this might cause double frees! */
01441     DeleteWindowById(WC_SELECT_STATION, 0);
01442   }
01443 
01444   virtual void OnTick()
01445   {
01446     if (_thd.dirty & 2) {
01447       _thd.dirty &= ~2;
01448       this->SetDirty();
01449     }
01450   }
01451 
01452   virtual void OnResize()
01453   {
01454     this->vscroll->SetCapacityFromWidget(this, JSW_PANEL, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
01455   }
01456 
01462   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
01463   {
01464     if (!gui_scope) return;
01465     FindStationsNearby<T>(this->area, true);
01466     this->vscroll->SetCount(_stations_nearby_list.Length() + 1);
01467     this->SetDirty();
01468   }
01469 };
01470 
01471 static const WindowDesc _select_station_desc(
01472   WDP_AUTO, 200, 180,
01473   WC_SELECT_STATION, WC_NONE,
01474   WDF_CONSTRUCTION,
01475   _nested_select_station_widgets, lengthof(_nested_select_station_widgets)
01476 );
01477 
01478 
01486 template <class T>
01487 static bool StationJoinerNeeded(CommandContainer cmd, TileArea ta)
01488 {
01489   /* Only show selection if distant join is enabled in the settings */
01490   if (!_settings_game.station.distant_join_stations) return false;
01491 
01492   /* If a window is already opened and we didn't ctrl-click,
01493    * return true (i.e. just flash the old window) */
01494   Window *selection_window = FindWindowById(WC_SELECT_STATION, 0);
01495   if (selection_window != NULL) {
01496     /* Abort current distant-join and start new one */
01497     delete selection_window;
01498     UpdateTileSelection();
01499   }
01500 
01501   /* only show the popup, if we press ctrl */
01502   if (!_ctrl_pressed) return false;
01503 
01504   /* Now check if we could build there */
01505   if (DoCommand(&cmd, CommandFlagsToDCFlags(GetCommandFlags(cmd.cmd))).Failed()) return false;
01506 
01507   /* Test for adjacent station or station below selection.
01508    * If adjacent-stations is disabled and we are building next to a station, do not show the selection window.
01509    * but join the other station immediately. */
01510   const T *st = FindStationsNearby<T>(ta, false);
01511   return st == NULL && (_settings_game.station.adjacent_stations || _stations_nearby_list.Length() == 0);
01512 }
01513 
01520 template <class T>
01521 void ShowSelectBaseStationIfNeeded(CommandContainer cmd, TileArea ta)
01522 {
01523   if (StationJoinerNeeded<T>(cmd, ta)) {
01524     if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
01525     new SelectStationWindow<T>(&_select_station_desc, cmd, ta);
01526   } else {
01527     DoCommandP(&cmd);
01528   }
01529 }
01530 
01536 void ShowSelectStationIfNeeded(CommandContainer cmd, TileArea ta)
01537 {
01538   ShowSelectBaseStationIfNeeded<Station>(cmd, ta);
01539 }
01540 
01546 void ShowSelectWaypointIfNeeded(CommandContainer cmd, TileArea ta)
01547 {
01548   ShowSelectBaseStationIfNeeded<Waypoint>(cmd, ta);
01549 }

Generated on Fri Mar 18 23:17:38 2011 for OpenTTD by  doxygen 1.6.1