vehicle_gui.cpp

Go to the documentation of this file.
00001 /* $Id: vehicle_gui.cpp 26086 2013-11-24 14:46:26Z 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 "company_func.h"
00015 #include "gui.h"
00016 #include "textbuf_gui.h"
00017 #include "command_func.h"
00018 #include "vehicle_gui_base.h"
00019 #include "viewport_func.h"
00020 #include "newgrf_text.h"
00021 #include "newgrf_debug.h"
00022 #include "roadveh.h"
00023 #include "train.h"
00024 #include "aircraft.h"
00025 #include "depot_map.h"
00026 #include "group_gui.h"
00027 #include "strings_func.h"
00028 #include "vehicle_func.h"
00029 #include "autoreplace_gui.h"
00030 #include "string_func.h"
00031 #include "widgets/dropdown_func.h"
00032 #include "timetable.h"
00033 #include "articulated_vehicles.h"
00034 #include "spritecache.h"
00035 #include "core/geometry_func.hpp"
00036 #include "company_base.h"
00037 #include "engine_func.h"
00038 #include "station_base.h"
00039 #include "tilehighlight_func.h"
00040 #include "zoom_func.h"
00041 
00042 
00043 Sorting _sorting;
00044 
00045 static GUIVehicleList::SortFunction VehicleNumberSorter;
00046 static GUIVehicleList::SortFunction VehicleNameSorter;
00047 static GUIVehicleList::SortFunction VehicleAgeSorter;
00048 static GUIVehicleList::SortFunction VehicleProfitThisYearSorter;
00049 static GUIVehicleList::SortFunction VehicleProfitLastYearSorter;
00050 static GUIVehicleList::SortFunction VehicleCargoSorter;
00051 static GUIVehicleList::SortFunction VehicleReliabilitySorter;
00052 static GUIVehicleList::SortFunction VehicleMaxSpeedSorter;
00053 static GUIVehicleList::SortFunction VehicleModelSorter;
00054 static GUIVehicleList::SortFunction VehicleValueSorter;
00055 static GUIVehicleList::SortFunction VehicleLengthSorter;
00056 static GUIVehicleList::SortFunction VehicleTimeToLiveSorter;
00057 static GUIVehicleList::SortFunction VehicleTimetableDelaySorter;
00058 
00059 GUIVehicleList::SortFunction * const BaseVehicleListWindow::vehicle_sorter_funcs[] = {
00060   &VehicleNumberSorter,
00061   &VehicleNameSorter,
00062   &VehicleAgeSorter,
00063   &VehicleProfitThisYearSorter,
00064   &VehicleProfitLastYearSorter,
00065   &VehicleCargoSorter,
00066   &VehicleReliabilitySorter,
00067   &VehicleMaxSpeedSorter,
00068   &VehicleModelSorter,
00069   &VehicleValueSorter,
00070   &VehicleLengthSorter,
00071   &VehicleTimeToLiveSorter,
00072   &VehicleTimetableDelaySorter,
00073 };
00074 
00075 const StringID BaseVehicleListWindow::vehicle_sorter_names[] = {
00076   STR_SORT_BY_NUMBER,
00077   STR_SORT_BY_NAME,
00078   STR_SORT_BY_AGE,
00079   STR_SORT_BY_PROFIT_THIS_YEAR,
00080   STR_SORT_BY_PROFIT_LAST_YEAR,
00081   STR_SORT_BY_TOTAL_CAPACITY_PER_CARGOTYPE,
00082   STR_SORT_BY_RELIABILITY,
00083   STR_SORT_BY_MAX_SPEED,
00084   STR_SORT_BY_MODEL,
00085   STR_SORT_BY_VALUE,
00086   STR_SORT_BY_LENGTH,
00087   STR_SORT_BY_LIFE_TIME,
00088   STR_SORT_BY_TIMETABLE_DELAY,
00089   INVALID_STRING_ID
00090 };
00091 
00092 const StringID BaseVehicleListWindow::vehicle_depot_name[] = {
00093   STR_VEHICLE_LIST_SEND_TRAIN_TO_DEPOT,
00094   STR_VEHICLE_LIST_SEND_ROAD_VEHICLE_TO_DEPOT,
00095   STR_VEHICLE_LIST_SEND_SHIP_TO_DEPOT,
00096   STR_VEHICLE_LIST_SEND_AIRCRAFT_TO_HANGAR
00097 };
00098 
00099 void BaseVehicleListWindow::BuildVehicleList()
00100 {
00101   if (!this->vehicles.NeedRebuild()) return;
00102 
00103   DEBUG(misc, 3, "Building vehicle list type %d for company %d given index %d", this->vli.type, this->vli.company, this->vli.index);
00104 
00105   GenerateVehicleSortList(&this->vehicles, this->vli);
00106 
00107   uint unitnumber = 0;
00108   for (const Vehicle **v = this->vehicles.Begin(); v != this->vehicles.End(); v++) {
00109     unitnumber = max<uint>(unitnumber, (*v)->unitnumber);
00110   }
00111 
00112   /* Because 111 is much less wide than e.g. 999 we use the
00113    * wider numbers to determine the width instead of just
00114    * the random number that it seems to be. */
00115   if (unitnumber >= 1000) {
00116     this->unitnumber_digits = 4;
00117   } else if (unitnumber >= 100) {
00118     this->unitnumber_digits = 3;
00119   } else {
00120     this->unitnumber_digits = 2;
00121   }
00122 
00123   this->vehicles.RebuildDone();
00124   this->vscroll->SetCount(this->vehicles.Length());
00125 }
00126 
00133 Dimension BaseVehicleListWindow::GetActionDropdownSize(bool show_autoreplace, bool show_group)
00134 {
00135   Dimension d = {0, 0};
00136 
00137   if (show_autoreplace) d = maxdim(d, GetStringBoundingBox(STR_VEHICLE_LIST_REPLACE_VEHICLES));
00138   d = maxdim(d, GetStringBoundingBox(STR_VEHICLE_LIST_SEND_FOR_SERVICING));
00139   d = maxdim(d, GetStringBoundingBox(this->vehicle_depot_name[this->vli.vtype]));
00140 
00141   if (show_group) {
00142     d = maxdim(d, GetStringBoundingBox(STR_GROUP_ADD_SHARED_VEHICLE));
00143     d = maxdim(d, GetStringBoundingBox(STR_GROUP_REMOVE_ALL_VEHICLES));
00144   }
00145 
00146   return d;
00147 }
00148 
00155 DropDownList *BaseVehicleListWindow::BuildActionDropdownList(bool show_autoreplace, bool show_group)
00156 {
00157   DropDownList *list = new DropDownList();
00158 
00159   if (show_autoreplace) *list->Append() = new DropDownListStringItem(STR_VEHICLE_LIST_REPLACE_VEHICLES, ADI_REPLACE, false);
00160   *list->Append() = new DropDownListStringItem(STR_VEHICLE_LIST_SEND_FOR_SERVICING, ADI_SERVICE, false);
00161   *list->Append() = new DropDownListStringItem(this->vehicle_depot_name[this->vli.vtype], ADI_DEPOT, false);
00162 
00163   if (show_group) {
00164     *list->Append() = new DropDownListStringItem(STR_GROUP_ADD_SHARED_VEHICLE, ADI_ADD_SHARED, false);
00165     *list->Append() = new DropDownListStringItem(STR_GROUP_REMOVE_ALL_VEHICLES, ADI_REMOVE_ALL, false);
00166   }
00167 
00168   return list;
00169 }
00170 
00171 /* cached values for VehicleNameSorter to spare many GetString() calls */
00172 static const Vehicle *_last_vehicle[2] = { NULL, NULL };
00173 
00174 void BaseVehicleListWindow::SortVehicleList()
00175 {
00176   if (this->vehicles.Sort()) return;
00177 
00178   /* invalidate cached values for name sorter - vehicle names could change */
00179   _last_vehicle[0] = _last_vehicle[1] = NULL;
00180 }
00181 
00182 void DepotSortList(VehicleList *list)
00183 {
00184   if (list->Length() < 2) return;
00185   QSortT(list->Begin(), list->Length(), &VehicleNumberSorter);
00186 }
00187 
00189 static void DrawVehicleProfitButton(const Vehicle *v, int x, int y)
00190 {
00191   SpriteID spr;
00192 
00193   /* draw profit-based coloured icons */
00194   if (v->age <= VEHICLE_PROFIT_MIN_AGE) {
00195     spr = SPR_PROFIT_NA;
00196   } else if (v->GetDisplayProfitLastYear() < 0) {
00197     spr = SPR_PROFIT_NEGATIVE;
00198   } else if (v->GetDisplayProfitLastYear() < VEHICLE_PROFIT_THRESHOLD) {
00199     spr = SPR_PROFIT_SOME;
00200   } else {
00201     spr = SPR_PROFIT_LOT;
00202   }
00203   DrawSprite(spr, PAL_NONE, x, y);
00204 }
00205 
00207 static const uint MAX_REFIT_CYCLE = 256;
00208 
00218 byte GetBestFittingSubType(Vehicle *v_from, Vehicle *v_for, CargoID dest_cargo_type)
00219 {
00220   v_from = v_from->GetFirstEnginePart();
00221   v_for = v_for->GetFirstEnginePart();
00222 
00223   /* Create a list of subtypes used by the various parts of v_for */
00224   static SmallVector<StringID, 4> subtypes;
00225   subtypes.Clear();
00226   for (; v_from != NULL; v_from = v_from->HasArticulatedPart() ? v_from->GetNextArticulatedPart() : NULL) {
00227     const Engine *e_from = v_from->GetEngine();
00228     if (!e_from->CanCarryCargo() || !HasBit(e_from->info.callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) continue;
00229     subtypes.Include(GetCargoSubtypeText(v_from));
00230   }
00231 
00232   byte ret_refit_cyc = 0;
00233   bool success = false;
00234   if (subtypes.Length() > 0) {
00235     /* Check whether any articulated part is refittable to 'dest_cargo_type' with a subtype listed in 'subtypes' */
00236     for (Vehicle *v = v_for; v != NULL; v = v->HasArticulatedPart() ? v->GetNextArticulatedPart() : NULL) {
00237       const Engine *e = v->GetEngine();
00238       if (!e->CanCarryCargo() || !HasBit(e->info.callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) continue;
00239       if (!HasBit(e->info.refit_mask, dest_cargo_type) && v->cargo_type != dest_cargo_type) continue;
00240 
00241       CargoID old_cargo_type = v->cargo_type;
00242       byte old_cargo_subtype = v->cargo_subtype;
00243 
00244       /* Set the 'destination' cargo */
00245       v->cargo_type = dest_cargo_type;
00246 
00247       /* Cycle through the refits */
00248       for (uint refit_cyc = 0; refit_cyc < MAX_REFIT_CYCLE; refit_cyc++) {
00249         v->cargo_subtype = refit_cyc;
00250 
00251         /* Make sure we don't pick up anything cached. */
00252         v->First()->InvalidateNewGRFCache();
00253         v->InvalidateNewGRFCache();
00254 
00255         StringID subtype = GetCargoSubtypeText(v);
00256         if (subtype == STR_EMPTY) break;
00257 
00258         if (!subtypes.Contains(subtype)) continue;
00259 
00260         /* We found something matching. */
00261         ret_refit_cyc = refit_cyc;
00262         success = true;
00263         break;
00264       }
00265 
00266       /* Reset the vehicle's cargo type */
00267       v->cargo_type    = old_cargo_type;
00268       v->cargo_subtype = old_cargo_subtype;
00269 
00270       /* Make sure we don't taint the vehicle. */
00271       v->First()->InvalidateNewGRFCache();
00272       v->InvalidateNewGRFCache();
00273 
00274       if (success) break;
00275     }
00276   }
00277 
00278   return ret_refit_cyc;
00279 }
00280 
00282 struct RefitOption {
00283   CargoID cargo;    
00284   byte subtype;     
00285   StringID string;  
00286 
00292   inline bool operator != (const RefitOption &other) const
00293   {
00294     return other.cargo != this->cargo || other.string != this->string;
00295   }
00296 
00302   inline bool operator == (const RefitOption &other) const
00303   {
00304     return other.cargo == this->cargo && other.string == this->string;
00305   }
00306 };
00307 
00308 typedef SmallVector<RefitOption, 32> SubtypeList; 
00309 
00319 static void DrawVehicleRefitWindow(const SubtypeList list[NUM_CARGO], const int sel[2], uint pos, uint rows, uint delta, const Rect &r)
00320 {
00321   uint y = r.top + WD_MATRIX_TOP;
00322   uint current = 0;
00323 
00324   bool rtl = _current_text_dir == TD_RTL;
00325   uint iconwidth = max(GetSpriteSize(SPR_CIRCLE_FOLDED).width, GetSpriteSize(SPR_CIRCLE_UNFOLDED).width);
00326   uint iconheight = GetSpriteSize(SPR_CIRCLE_FOLDED).height;
00327   int linecolour = _colour_gradient[COLOUR_ORANGE][4];
00328 
00329   int iconleft   = rtl ? r.right - WD_MATRIX_RIGHT - iconwidth     : r.left + WD_MATRIX_LEFT;
00330   int iconcenter = rtl ? r.right - WD_MATRIX_RIGHT - iconwidth / 2 : r.left + WD_MATRIX_LEFT + iconwidth / 2;
00331   int iconinner  = rtl ? r.right - WD_MATRIX_RIGHT - iconwidth     : r.left + WD_MATRIX_LEFT + iconwidth;
00332 
00333   int textleft   = r.left  + WD_MATRIX_LEFT  + (rtl ? 0 : iconwidth + 4);
00334   int textright  = r.right - WD_MATRIX_RIGHT - (rtl ? iconwidth + 4 : 0);
00335 
00336   /* Draw the list of subtypes for each cargo, and find the selected refit option (by its position). */
00337   for (uint i = 0; current < pos + rows && i < NUM_CARGO; i++) {
00338     for (uint j = 0; current < pos + rows && j < list[i].Length(); j++) {
00339       const RefitOption &refit = list[i][j];
00340 
00341       /* Hide subtypes if sel[0] does not match */
00342       if (sel[0] != (int)i && refit.subtype != 0xFF) continue;
00343 
00344       /* Refit options with a position smaller than pos don't have to be drawn. */
00345       if (current < pos) {
00346         current++;
00347         continue;
00348       }
00349 
00350       if (list[i].Length() > 1) {
00351         if (refit.subtype != 0xFF) {
00352           /* Draw tree lines */
00353           int ycenter = y + FONT_HEIGHT_NORMAL / 2;
00354           GfxDrawLine(iconcenter, y - WD_MATRIX_TOP, iconcenter, j == list[i].Length() - 1 ? ycenter : y - WD_MATRIX_TOP + delta - 1, linecolour);
00355           GfxDrawLine(iconcenter, ycenter, iconinner, ycenter, linecolour);
00356         } else {
00357           /* Draw expand/collapse icon */
00358           DrawSprite(sel[0] == (int)i ? SPR_CIRCLE_UNFOLDED : SPR_CIRCLE_FOLDED, PAL_NONE, iconleft, y + (FONT_HEIGHT_NORMAL - iconheight) / 2);
00359         }
00360       }
00361 
00362       TextColour colour = (sel[0] == (int)i && (uint)sel[1] == j) ? TC_WHITE : TC_BLACK;
00363       /* Get the cargo name. */
00364       SetDParam(0, CargoSpec::Get(refit.cargo)->name);
00365       SetDParam(1, refit.string);
00366       DrawString(textleft, textright, y, STR_JUST_STRING_STRING, colour);
00367 
00368       y += delta;
00369       current++;
00370     }
00371   }
00372 }
00373 
00375 struct RefitWindow : public Window {
00376   int sel[2];                  
00377   RefitOption *cargo;          
00378   SubtypeList list[NUM_CARGO]; 
00379   VehicleOrderID order;        
00380   uint information_width;      
00381   Scrollbar *vscroll;          
00382   Scrollbar *hscroll;          
00383   int vehicle_width;           
00384   int sprite_left;             
00385   int sprite_right;            
00386   uint vehicle_margin;         
00387   int click_x;                 
00388   VehicleID selected_vehicle;  
00389   uint8 num_vehicles;          
00390   bool auto_refit;             
00391 
00395   void BuildRefitList()
00396   {
00397     for (uint i = 0; i < NUM_CARGO; i++) this->list[i].Clear();
00398     Vehicle *v = Vehicle::Get(this->window_number);
00399 
00400     /* Check only the selected vehicles. */
00401     VehicleSet vehicles_to_refit;
00402     GetVehicleSet(vehicles_to_refit, Vehicle::Get(this->selected_vehicle), this->num_vehicles);
00403 
00404     do {
00405       if (v->type == VEH_TRAIN && !vehicles_to_refit.Contains(v->index)) continue;
00406       const Engine *e = v->GetEngine();
00407       uint32 cmask = e->info.refit_mask;
00408       byte callback_mask = e->info.callback_mask;
00409 
00410       /* Skip this engine if it does not carry anything */
00411       if (!e->CanCarryCargo()) continue;
00412       /* Skip this engine if we build the list for auto-refitting and engine doesn't allow it. */
00413       if (this->auto_refit && !HasBit(e->info.misc_flags, EF_AUTO_REFIT)) continue;
00414 
00415       /* Loop through all cargoes in the refit mask */
00416       int current_index = 0;
00417       const CargoSpec *cs;
00418       FOR_ALL_SORTED_CARGOSPECS(cs) {
00419         CargoID cid = cs->Index();
00420         /* Skip cargo type if it's not listed */
00421         if (!HasBit(cmask, cid)) {
00422           current_index++;
00423           continue;
00424         }
00425 
00426         bool first_vehicle = this->list[current_index].Length() == 0;
00427         if (first_vehicle) {
00428           /* Keeping the current subtype is always an option. It also serves as the option in case of no subtypes */
00429           RefitOption *option = this->list[current_index].Append();
00430           option->cargo   = cid;
00431           option->subtype = 0xFF;
00432           option->string  = STR_EMPTY;
00433         }
00434 
00435         /* Check the vehicle's callback mask for cargo suffixes.
00436          * This is not supported for ordered refits, since subtypes only have a meaning
00437          * for a specific vehicle at a specific point in time, which conflicts with shared orders,
00438          * autoreplace, autorenew, clone, order restoration, ... */
00439         if (this->order == INVALID_VEH_ORDER_ID && HasBit(callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) {
00440           /* Make a note of the original cargo type. It has to be
00441            * changed to test the cargo & subtype... */
00442           CargoID temp_cargo = v->cargo_type;
00443           byte temp_subtype  = v->cargo_subtype;
00444 
00445           v->cargo_type = cid;
00446 
00447           for (uint refit_cyc = 0; refit_cyc < MAX_REFIT_CYCLE; refit_cyc++) {
00448             v->cargo_subtype = refit_cyc;
00449 
00450             /* Make sure we don't pick up anything cached. */
00451             v->First()->InvalidateNewGRFCache();
00452             v->InvalidateNewGRFCache();
00453 
00454             StringID subtype = GetCargoSubtypeText(v);
00455 
00456             if (first_vehicle) {
00457               /* Append new subtype (don't add duplicates though) */
00458               if (subtype == STR_EMPTY) break;
00459 
00460               RefitOption option;
00461               option.cargo   = cid;
00462               option.subtype = refit_cyc;
00463               option.string  = subtype;
00464               this->list[current_index].Include(option);
00465             } else {
00466               /* Intersect the subtypes of earlier vehicles with the subtypes of this vehicle */
00467               if (subtype == STR_EMPTY) {
00468                 /* No more subtypes for this vehicle, delete all subtypes >= refit_cyc */
00469                 SubtypeList &l = this->list[current_index];
00470                 /* 0xFF item is in front, other subtypes are sorted. So just truncate the list in the right spot */
00471                 for (uint i = 1; i < l.Length(); i++) {
00472                   if (l[i].subtype >= refit_cyc) {
00473                     l.Resize(i);
00474                     break;
00475                   }
00476                 }
00477                 break;
00478               } else {
00479                 /* Check whether the subtype matches with the subtype of earlier vehicles. */
00480                 uint pos = 1;
00481                 SubtypeList &l = this->list[current_index];
00482                 while (pos < l.Length() && l[pos].subtype != refit_cyc) pos++;
00483                 if (pos < l.Length() && l[pos].string != subtype) {
00484                   /* String mismatch, remove item keeping the order */
00485                   l.ErasePreservingOrder(pos);
00486                 }
00487               }
00488             }
00489           }
00490 
00491           /* Reset the vehicle's cargo type */
00492           v->cargo_type    = temp_cargo;
00493           v->cargo_subtype = temp_subtype;
00494 
00495           /* And make sure we haven't tainted the cache */
00496           v->First()->InvalidateNewGRFCache();
00497           v->InvalidateNewGRFCache();
00498         }
00499         current_index++;
00500       }
00501     } while (v->IsGroundVehicle() && (v = v->Next()) != NULL);
00502   }
00503 
00507   void RefreshScrollbar()
00508   {
00509     uint scroll_row = 0;
00510     uint row = 0;
00511 
00512     for (uint i = 0; i < NUM_CARGO; i++) {
00513       for (uint j = 0; j < this->list[i].Length(); j++) {
00514         const RefitOption &refit = this->list[i][j];
00515 
00516         /* Hide subtypes if sel[0] does not match */
00517         if (this->sel[0] != (int)i && refit.subtype != 0xFF) continue;
00518 
00519         if (this->sel[0] == (int)i && (uint)this->sel[1] == j) scroll_row = row;
00520 
00521         row++;
00522       }
00523     }
00524 
00525     this->vscroll->SetCount(row);
00526     if (scroll_row < row) this->vscroll->ScrollTowards(scroll_row);
00527   }
00528 
00533   void SetSelection(uint click_row)
00534   {
00535     uint row = 0;
00536 
00537     for (uint i = 0; i < NUM_CARGO; i++) {
00538       for (uint j = 0; j < this->list[i].Length(); j++) {
00539         const RefitOption &refit = this->list[i][j];
00540 
00541         /* Hide subtypes if sel[0] does not match */
00542         if (this->sel[0] != (int)i && refit.subtype != 0xFF) continue;
00543 
00544         if (row == click_row) {
00545           this->sel[0] = i;
00546           this->sel[1] = j;
00547           return;
00548         }
00549 
00550         row++;
00551       }
00552     }
00553 
00554     this->sel[0] = -1;
00555     this->sel[1] = 0;
00556   }
00557 
00562   RefitOption *GetRefitOption()
00563   {
00564     if (this->sel[0] < 0) return NULL;
00565 
00566     SubtypeList &l = this->list[this->sel[0]];
00567     if ((uint)this->sel[1] >= l.Length()) return NULL;
00568 
00569     return &l[this->sel[1]];
00570   }
00571 
00572   RefitWindow(WindowDesc *desc, const Vehicle *v, VehicleOrderID order, bool auto_refit) : Window(desc)
00573   {
00574     this->sel[0] = -1;
00575     this->sel[1] = 0;
00576     this->auto_refit = auto_refit;
00577     this->order = order;
00578     this->CreateNestedTree();
00579 
00580     this->vscroll = this->GetScrollbar(WID_VR_SCROLLBAR);
00581     this->hscroll = (v->IsGroundVehicle() ? this->GetScrollbar(WID_VR_HSCROLLBAR) : NULL);
00582     this->GetWidget<NWidgetCore>(WID_VR_SELECT_HEADER)->tool_tip = STR_REFIT_TRAIN_LIST_TOOLTIP + v->type;
00583     this->GetWidget<NWidgetCore>(WID_VR_MATRIX)->tool_tip        = STR_REFIT_TRAIN_LIST_TOOLTIP + v->type;
00584     NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_VR_REFIT);
00585     nwi->widget_data = STR_REFIT_TRAIN_REFIT_BUTTON + v->type;
00586     nwi->tool_tip    = STR_REFIT_TRAIN_REFIT_TOOLTIP + v->type;
00587     this->GetWidget<NWidgetStacked>(WID_VR_SHOW_HSCROLLBAR)->SetDisplayedPlane(v->IsGroundVehicle() ? 0 : SZSP_HORIZONTAL);
00588     this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY)->tool_tip = (v->type == VEH_TRAIN) ? STR_REFIT_SELECT_VEHICLES_TOOLTIP : STR_NULL;
00589 
00590     this->FinishInitNested(v->index);
00591     this->owner = v->owner;
00592 
00593     this->SetWidgetDisabledState(WID_VR_REFIT, this->sel[0] < 0);
00594   }
00595 
00596   virtual void OnInit()
00597   {
00598     if (this->cargo != NULL) {
00599       /* Store the RefitOption currently in use. */
00600       RefitOption current_refit_option = *(this->cargo);
00601 
00602       /* Rebuild the refit list */
00603       this->BuildRefitList();
00604       this->sel[0] = -1;
00605       this->sel[1] = 0;
00606       this->cargo = NULL;
00607       for (uint i = 0; this->cargo == NULL && i < NUM_CARGO; i++) {
00608         for (uint j = 0; j < list[i].Length(); j++) {
00609           if (list[i][j] == current_refit_option) {
00610             this->sel[0] = i;
00611             this->sel[1] = j;
00612             this->cargo = &list[i][j];
00613             break;
00614           }
00615         }
00616       }
00617 
00618       this->SetWidgetDisabledState(WID_VR_REFIT, this->sel[0] < 0);
00619       this->RefreshScrollbar();
00620     } else {
00621       /* Rebuild the refit list */
00622       this->OnInvalidateData(VIWD_CONSIST_CHANGED);
00623     }
00624   }
00625 
00626   virtual void OnPaint()
00627   {
00628     /* Determine amount of items for scroller. */
00629     if (this->hscroll != NULL) this->hscroll->SetCount(this->vehicle_width);
00630 
00631     /* Calculate sprite position. */
00632     NWidgetCore *vehicle_panel_display = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY);
00633     int sprite_width = max(0, ((int)vehicle_panel_display->current_x - this->vehicle_width) / 2);
00634     this->sprite_left = vehicle_panel_display->pos_x;
00635     this->sprite_right = vehicle_panel_display->pos_x + vehicle_panel_display->current_x - 1;
00636     if (_current_text_dir == TD_RTL) {
00637       this->sprite_right -= sprite_width;
00638       this->vehicle_margin = vehicle_panel_display->current_x - sprite_right;
00639     } else {
00640       this->sprite_left += sprite_width;
00641       this->vehicle_margin = sprite_left;
00642     }
00643 
00644     this->DrawWidgets();
00645   }
00646 
00647   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00648   {
00649     switch (widget) {
00650       case WID_VR_MATRIX:
00651         resize->height = WD_MATRIX_TOP + FONT_HEIGHT_NORMAL + WD_MATRIX_BOTTOM;
00652         size->height = resize->height * 8;
00653         break;
00654 
00655       case WID_VR_VEHICLE_PANEL_DISPLAY:
00656         size->height = GetVehicleHeight(Vehicle::Get(this->window_number)->type);
00657         break;
00658 
00659       case WID_VR_INFO:
00660         size->width = WD_FRAMERECT_LEFT + this->information_width + WD_FRAMERECT_RIGHT;
00661         break;
00662     }
00663   }
00664 
00665   virtual void SetStringParameters(int widget) const
00666   {
00667     if (widget == WID_VR_CAPTION) SetDParam(0, Vehicle::Get(this->window_number)->index);
00668   }
00669 
00676   StringID GetCapacityString(RefitOption *option) const
00677   {
00678     assert(_current_company == _local_company);
00679     Vehicle *v = Vehicle::Get(this->window_number);
00680     CommandCost cost = DoCommand(v->tile, this->selected_vehicle, option->cargo | (int)this->auto_refit << 6 | option->subtype << 8 |
00681         this->num_vehicles << 16, DC_QUERY_COST, GetCmdRefitVeh(v->type));
00682 
00683     if (cost.Failed()) return INVALID_STRING_ID;
00684 
00685     SetDParam(0, option->cargo);
00686     SetDParam(1, _returned_refit_capacity);
00687 
00688     Money money = cost.GetCost();
00689     if (_returned_mail_refit_capacity > 0) {
00690       SetDParam(2, CT_MAIL);
00691       SetDParam(3, _returned_mail_refit_capacity);
00692       if (money <= 0) {
00693         SetDParam(4, -money);
00694         return STR_REFIT_NEW_CAPACITY_INCOME_FROM_AIRCRAFT_REFIT;
00695       } else {
00696         SetDParam(4, money);
00697         return STR_REFIT_NEW_CAPACITY_COST_OF_AIRCRAFT_REFIT;
00698       }
00699     } else {
00700       if (money <= 0) {
00701         SetDParam(2, -money);
00702         return STR_REFIT_NEW_CAPACITY_INCOME_FROM_REFIT;
00703       } else {
00704         SetDParam(2, money);
00705         return STR_REFIT_NEW_CAPACITY_COST_OF_REFIT;
00706       }
00707     }
00708   }
00709 
00710   virtual void DrawWidget(const Rect &r, int widget) const
00711   {
00712     switch (widget) {
00713       case WID_VR_VEHICLE_PANEL_DISPLAY: {
00714         Vehicle *v = Vehicle::Get(this->window_number);
00715         DrawVehicleImage(v, this->sprite_left + WD_FRAMERECT_LEFT, this->sprite_right - WD_FRAMERECT_RIGHT,
00716           r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, this->hscroll != NULL ? this->hscroll->GetPosition() : 0);
00717 
00718         /* Highlight selected vehicles. */
00719         if (this->order != INVALID_VEH_ORDER_ID) break;
00720         int x = 0;
00721         switch (v->type) {
00722           case VEH_TRAIN: {
00723             VehicleSet vehicles_to_refit;
00724             GetVehicleSet(vehicles_to_refit, Vehicle::Get(this->selected_vehicle), this->num_vehicles);
00725 
00726             int left = INT32_MIN;
00727             int width = 0;
00728 
00729             for (Train *u = Train::From(v); u != NULL; u = u->Next()) {
00730               /* Start checking. */
00731               if (vehicles_to_refit.Contains(u->index) && left == INT32_MIN) {
00732                 left = x - this->hscroll->GetPosition() + r.left + this->vehicle_margin;
00733                 width = 0;
00734               }
00735 
00736               /* Draw a selection. */
00737               if ((!vehicles_to_refit.Contains(u->index) || u->Next() == NULL) && left != INT32_MIN) {
00738                 if (u->Next() == NULL && vehicles_to_refit.Contains(u->index)) {
00739                   int current_width = u->GetDisplayImageWidth();
00740                   width += current_width;
00741                   x += current_width;
00742                 }
00743 
00744                 int right = Clamp(left + width, 0, r.right);
00745                 left = max(0, left);
00746 
00747                 if (_current_text_dir == TD_RTL) {
00748                   right = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY)->current_x - left;
00749                   left = right - width;
00750                 }
00751 
00752                 if (left != right) {
00753                   DrawFrameRect(left, r.top + WD_FRAMERECT_TOP, right, r.top + WD_FRAMERECT_TOP + 13, COLOUR_WHITE, FR_BORDERONLY);
00754                 }
00755 
00756                 left = INT32_MIN;
00757               }
00758 
00759               int current_width = u->GetDisplayImageWidth();
00760               width += current_width;
00761               x += current_width;
00762             }
00763             break;
00764           }
00765 
00766           default: break;
00767         }
00768         break;
00769       }
00770 
00771       case WID_VR_MATRIX:
00772         DrawVehicleRefitWindow(this->list, this->sel, this->vscroll->GetPosition(), this->vscroll->GetCapacity(), this->resize.step_height, r);
00773         break;
00774 
00775       case WID_VR_INFO:
00776         if (this->cargo != NULL) {
00777           StringID string = this->GetCapacityString(this->cargo);
00778           if (string != INVALID_STRING_ID) {
00779             DrawStringMultiLine(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT,
00780                 r.top + WD_FRAMERECT_TOP, r.bottom - WD_FRAMERECT_BOTTOM, string);
00781           }
00782         }
00783         break;
00784     }
00785   }
00786 
00792   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
00793   {
00794     switch (data) {
00795       case VIWD_AUTOREPLACE: // Autoreplace replaced the vehicle; selected_vehicle became invalid.
00796       case VIWD_CONSIST_CHANGED: { // The consist has changed; rebuild the entire list.
00797         /* Clear the selection. */
00798         Vehicle *v = Vehicle::Get(this->window_number);
00799         this->selected_vehicle = v->index;
00800         this->num_vehicles = UINT8_MAX;
00801         /* FALL THROUGH */
00802       }
00803 
00804       case 2: { // The vehicle selection has changed; rebuild the entire list.
00805         if (!gui_scope) break;
00806         this->BuildRefitList();
00807 
00808         /* The vehicle width has changed too. */
00809         this->vehicle_width = GetVehicleWidth(Vehicle::Get(this->window_number), EIT_IN_DETAILS);
00810         uint max_width = 0;
00811 
00812         /* Check the width of all cargo information strings. */
00813         for (uint i = 0; i < NUM_CARGO; i++) {
00814           for (uint j = 0; j < this->list[i].Length(); j++) {
00815             StringID string = this->GetCapacityString(&list[i][j]);
00816             if (string != INVALID_STRING_ID) {
00817               Dimension dim = GetStringBoundingBox(string);
00818               max_width = max(dim.width, max_width);
00819             }
00820           }
00821         }
00822 
00823         if (this->information_width < max_width) {
00824           this->information_width = max_width;
00825           this->ReInit();
00826         }
00827         /* FALL THROUGH */
00828       }
00829 
00830       case 1: // A new cargo has been selected.
00831         if (!gui_scope) break;
00832         this->cargo = GetRefitOption();
00833         this->RefreshScrollbar();
00834         break;
00835     }
00836   }
00837 
00838   int GetClickPosition(int click_x)
00839   {
00840     const NWidgetCore *matrix_widget = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY);
00841     if (_current_text_dir == TD_RTL) click_x = matrix_widget->current_x - click_x;
00842     click_x -= this->vehicle_margin;
00843     if (this->hscroll != NULL) click_x += this->hscroll->GetPosition();
00844 
00845     return click_x;
00846   }
00847 
00848   void SetSelectedVehicles(int drag_x)
00849   {
00850     drag_x = GetClickPosition(drag_x);
00851 
00852     int left_x  = min(this->click_x, drag_x);
00853     int right_x = max(this->click_x, drag_x);
00854     this->num_vehicles = 0;
00855 
00856     Vehicle *v = Vehicle::Get(this->window_number);
00857     /* Find the vehicle part that was clicked. */
00858     switch (v->type) {
00859       case VEH_TRAIN: {
00860         /* Don't select anything if we are not clicking in the vehicle. */
00861         if (left_x >= 0) {
00862           const Train *u = Train::From(v);
00863           bool start_counting = false;
00864           for (; u != NULL; u = u->Next()) {
00865             int current_width = u->GetDisplayImageWidth();
00866             left_x  -= current_width;
00867             right_x -= current_width;
00868 
00869             if (left_x < 0 && !start_counting) {
00870               this->selected_vehicle = u->index;
00871               start_counting = true;
00872 
00873               /* Count the first vehicle, even if articulated part */
00874               this->num_vehicles++;
00875             } else if (start_counting && !u->IsArticulatedPart()) {
00876               /* Do not count articulated parts */
00877               this->num_vehicles++;
00878             }
00879 
00880             if (right_x < 0) break;
00881           }
00882         }
00883 
00884         /* If the selection is not correct, clear it. */
00885         if (this->num_vehicles != 0) {
00886           if (_ctrl_pressed) this->num_vehicles = UINT8_MAX;
00887           break;
00888         }
00889         /* FALL THROUGH */
00890       }
00891 
00892       default:
00893         /* Clear the selection. */
00894         this->selected_vehicle = v->index;
00895         this->num_vehicles = UINT8_MAX;
00896         break;
00897     }
00898   }
00899 
00900   virtual void OnClick(Point pt, int widget, int click_count)
00901   {
00902     switch (widget) {
00903       case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
00904         if (this->order != INVALID_VEH_ORDER_ID) break;
00905         NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
00906         this->click_x = GetClickPosition(pt.x - nwi->pos_x);
00907         this->SetSelectedVehicles(pt.x - nwi->pos_x);
00908         this->SetWidgetDirty(WID_VR_VEHICLE_PANEL_DISPLAY);
00909         if (!_ctrl_pressed) {
00910           SetObjectToPlaceWnd(SPR_CURSOR_MOUSE, PAL_NONE, HT_DRAG, this);
00911         } else {
00912           /* The vehicle selection has changed. */
00913           this->InvalidateData(2);
00914         }
00915         break;
00916       }
00917 
00918       case WID_VR_MATRIX: { // listbox
00919         this->SetSelection(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_VR_MATRIX));
00920         this->SetWidgetDisabledState(WID_VR_REFIT, this->sel[0] < 0);
00921         this->InvalidateData(1);
00922 
00923         if (click_count == 1) break;
00924         /* FALL THROUGH */
00925       }
00926 
00927       case WID_VR_REFIT: // refit button
00928         if (this->cargo != NULL) {
00929           const Vehicle *v = Vehicle::Get(this->window_number);
00930 
00931           if (this->order == INVALID_VEH_ORDER_ID) {
00932             bool delete_window = this->selected_vehicle == v->index && this->num_vehicles == UINT8_MAX;
00933             if (DoCommandP(v->tile, this->selected_vehicle, this->cargo->cargo | this->cargo->subtype << 8 | this->num_vehicles << 16, GetCmdRefitVeh(v)) && delete_window) delete this;
00934           } else {
00935             if (DoCommandP(v->tile, v->index, this->cargo->cargo | this->order << 16, CMD_ORDER_REFIT)) delete this;
00936           }
00937         }
00938         break;
00939     }
00940   }
00941 
00942   virtual void OnMouseDrag(Point pt, int widget)
00943   {
00944     switch (widget) {
00945       case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
00946         if (this->order != INVALID_VEH_ORDER_ID) break;
00947         NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
00948         this->SetSelectedVehicles(pt.x - nwi->pos_x);
00949         this->SetWidgetDirty(WID_VR_VEHICLE_PANEL_DISPLAY);
00950         break;
00951       }
00952     }
00953   }
00954 
00955   virtual void OnDragDrop(Point pt, int widget)
00956   {
00957     switch (widget) {
00958       case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
00959         if (this->order != INVALID_VEH_ORDER_ID) break;
00960         NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
00961         this->SetSelectedVehicles(pt.x - nwi->pos_x);
00962         this->InvalidateData(2);
00963         break;
00964       }
00965     }
00966   }
00967 
00968   virtual void OnResize()
00969   {
00970     this->vehicle_width = GetVehicleWidth(Vehicle::Get(this->window_number), EIT_IN_DETAILS);
00971     this->vscroll->SetCapacityFromWidget(this, WID_VR_MATRIX);
00972     if (this->hscroll != NULL) this->hscroll->SetCapacityFromWidget(this, WID_VR_VEHICLE_PANEL_DISPLAY);
00973   }
00974 };
00975 
00976 static const NWidgetPart _nested_vehicle_refit_widgets[] = {
00977   NWidget(NWID_HORIZONTAL),
00978     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
00979     NWidget(WWT_CAPTION, COLOUR_GREY, WID_VR_CAPTION), SetDataTip(STR_REFIT_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00980     NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
00981   EndContainer(),
00982   /* Vehicle display + scrollbar. */
00983   NWidget(NWID_VERTICAL),
00984     NWidget(WWT_PANEL, COLOUR_GREY, WID_VR_VEHICLE_PANEL_DISPLAY), SetMinimalSize(228, 14), SetResize(1, 0), SetScrollbar(WID_VR_HSCROLLBAR), EndContainer(),
00985     NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VR_SHOW_HSCROLLBAR),
00986       NWidget(NWID_HSCROLLBAR, COLOUR_GREY, WID_VR_HSCROLLBAR),
00987     EndContainer(),
00988   EndContainer(),
00989   NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_VR_SELECT_HEADER), SetDataTip(STR_REFIT_TITLE, STR_NULL), SetResize(1, 0),
00990   /* Matrix + scrollbar. */
00991   NWidget(NWID_HORIZONTAL),
00992     NWidget(WWT_MATRIX, COLOUR_GREY, WID_VR_MATRIX), SetMinimalSize(228, 112), SetResize(1, 14), SetFill(1, 1), SetMatrixDataTip(1, 0, STR_NULL), SetScrollbar(WID_VR_SCROLLBAR),
00993     NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VR_SCROLLBAR),
00994   EndContainer(),
00995   NWidget(WWT_PANEL, COLOUR_GREY, WID_VR_INFO), SetMinimalTextLines(2, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM), SetResize(1, 0), EndContainer(),
00996   NWidget(NWID_HORIZONTAL),
00997     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VR_REFIT), SetFill(1, 0), SetResize(1, 0),
00998     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
00999   EndContainer(),
01000 };
01001 
01002 static WindowDesc _vehicle_refit_desc(
01003   WDP_AUTO, "view_vehicle_refit", 240, 174,
01004   WC_VEHICLE_REFIT, WC_VEHICLE_VIEW,
01005   WDF_CONSTRUCTION,
01006   _nested_vehicle_refit_widgets, lengthof(_nested_vehicle_refit_widgets)
01007 );
01008 
01016 void ShowVehicleRefitWindow(const Vehicle *v, VehicleOrderID order, Window *parent, bool auto_refit)
01017 {
01018   DeleteWindowById(WC_VEHICLE_REFIT, v->index);
01019   RefitWindow *w = new RefitWindow(&_vehicle_refit_desc, v, order, auto_refit);
01020   w->parent = parent;
01021 }
01022 
01024 uint ShowRefitOptionsList(int left, int right, int y, EngineID engine)
01025 {
01026   /* List of cargo types of this engine */
01027   uint32 cmask = GetUnionOfArticulatedRefitMasks(engine, false);
01028   /* List of cargo types available in this climate */
01029   uint32 lmask = _cargo_mask;
01030 
01031   /* Draw nothing if the engine is not refittable */
01032   if (HasAtMostOneBit(cmask)) return y;
01033 
01034   if (cmask == lmask) {
01035     /* Engine can be refitted to all types in this climate */
01036     SetDParam(0, STR_PURCHASE_INFO_ALL_TYPES);
01037   } else {
01038     /* Check if we are able to refit to more cargo types and unable to. If
01039      * so, invert the cargo types to list those that we can't refit to. */
01040     if (CountBits(cmask ^ lmask) < CountBits(cmask) && CountBits(cmask ^ lmask) <= 7) {
01041       cmask ^= lmask;
01042       SetDParam(0, STR_PURCHASE_INFO_ALL_BUT);
01043     } else {
01044       SetDParam(0, STR_JUST_CARGO_LIST);
01045     }
01046     SetDParam(1, cmask);
01047   }
01048 
01049   return DrawStringMultiLine(left, right, y, INT32_MAX, STR_PURCHASE_INFO_REFITTABLE_TO);
01050 }
01051 
01053 StringID GetCargoSubtypeText(const Vehicle *v)
01054 {
01055   if (HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) {
01056     uint16 cb = GetVehicleCallback(CBID_VEHICLE_CARGO_SUFFIX, 0, 0, v->engine_type, v);
01057     if (cb != CALLBACK_FAILED) {
01058       if (cb > 0x400) ErrorUnknownCallbackResult(v->GetGRFID(), CBID_VEHICLE_CARGO_SUFFIX, cb);
01059       if (cb >= 0x400 || (v->GetGRF()->grf_version < 8 && cb == 0xFF)) cb = CALLBACK_FAILED;
01060     }
01061     if (cb != CALLBACK_FAILED) {
01062       return GetGRFStringID(v->GetGRFID(), 0xD000 + cb);
01063     }
01064   }
01065   return STR_EMPTY;
01066 }
01067 
01069 static int CDECL VehicleNumberSorter(const Vehicle * const *a, const Vehicle * const *b)
01070 {
01071   return (*a)->unitnumber - (*b)->unitnumber;
01072 }
01073 
01075 static int CDECL VehicleNameSorter(const Vehicle * const *a, const Vehicle * const *b)
01076 {
01077   static char last_name[2][64];
01078 
01079   if (*a != _last_vehicle[0]) {
01080     _last_vehicle[0] = *a;
01081     SetDParam(0, (*a)->index);
01082     GetString(last_name[0], STR_VEHICLE_NAME, lastof(last_name[0]));
01083   }
01084 
01085   if (*b != _last_vehicle[1]) {
01086     _last_vehicle[1] = *b;
01087     SetDParam(0, (*b)->index);
01088     GetString(last_name[1], STR_VEHICLE_NAME, lastof(last_name[1]));
01089   }
01090 
01091   int r = strnatcmp(last_name[0], last_name[1]); // Sort by name (natural sorting).
01092   return (r != 0) ? r : VehicleNumberSorter(a, b);
01093 }
01094 
01096 static int CDECL VehicleAgeSorter(const Vehicle * const *a, const Vehicle * const *b)
01097 {
01098   int r = (*a)->age - (*b)->age;
01099   return (r != 0) ? r : VehicleNumberSorter(a, b);
01100 }
01101 
01103 static int CDECL VehicleProfitThisYearSorter(const Vehicle * const *a, const Vehicle * const *b)
01104 {
01105   int r = ClampToI32((*a)->GetDisplayProfitThisYear() - (*b)->GetDisplayProfitThisYear());
01106   return (r != 0) ? r : VehicleNumberSorter(a, b);
01107 }
01108 
01110 static int CDECL VehicleProfitLastYearSorter(const Vehicle * const *a, const Vehicle * const *b)
01111 {
01112   int r = ClampToI32((*a)->GetDisplayProfitLastYear() - (*b)->GetDisplayProfitLastYear());
01113   return (r != 0) ? r : VehicleNumberSorter(a, b);
01114 }
01115 
01117 static int CDECL VehicleCargoSorter(const Vehicle * const *a, const Vehicle * const *b)
01118 {
01119   const Vehicle *v;
01120   CargoArray diff;
01121 
01122   /* Append the cargo of the connected waggons */
01123   for (v = *a; v != NULL; v = v->Next()) diff[v->cargo_type] += v->cargo_cap;
01124   for (v = *b; v != NULL; v = v->Next()) diff[v->cargo_type] -= v->cargo_cap;
01125 
01126   int r = 0;
01127   for (CargoID i = 0; i < NUM_CARGO; i++) {
01128     r = diff[i];
01129     if (r != 0) break;
01130   }
01131 
01132   return (r != 0) ? r : VehicleNumberSorter(a, b);
01133 }
01134 
01136 static int CDECL VehicleReliabilitySorter(const Vehicle * const *a, const Vehicle * const *b)
01137 {
01138   int r = (*a)->reliability - (*b)->reliability;
01139   return (r != 0) ? r : VehicleNumberSorter(a, b);
01140 }
01141 
01143 static int CDECL VehicleMaxSpeedSorter(const Vehicle * const *a, const Vehicle * const *b)
01144 {
01145   int r = (*a)->vcache.cached_max_speed - (*b)->vcache.cached_max_speed;
01146   return (r != 0) ? r : VehicleNumberSorter(a, b);
01147 }
01148 
01150 static int CDECL VehicleModelSorter(const Vehicle * const *a, const Vehicle * const *b)
01151 {
01152   int r = (*a)->engine_type - (*b)->engine_type;
01153   return (r != 0) ? r : VehicleNumberSorter(a, b);
01154 }
01155 
01157 static int CDECL VehicleValueSorter(const Vehicle * const *a, const Vehicle * const *b)
01158 {
01159   const Vehicle *u;
01160   Money diff = 0;
01161 
01162   for (u = *a; u != NULL; u = u->Next()) diff += u->value;
01163   for (u = *b; u != NULL; u = u->Next()) diff -= u->value;
01164 
01165   int r = ClampToI32(diff);
01166   return (r != 0) ? r : VehicleNumberSorter(a, b);
01167 }
01168 
01170 static int CDECL VehicleLengthSorter(const Vehicle * const *a, const Vehicle * const *b)
01171 {
01172   int r = (*a)->GetGroundVehicleCache()->cached_total_length - (*b)->GetGroundVehicleCache()->cached_total_length;
01173   return (r != 0) ? r : VehicleNumberSorter(a, b);
01174 }
01175 
01177 static int CDECL VehicleTimeToLiveSorter(const Vehicle * const *a, const Vehicle * const *b)
01178 {
01179   int r = ClampToI32(((*a)->max_age - (*a)->age) - ((*b)->max_age - (*b)->age));
01180   return (r != 0) ? r : VehicleNumberSorter(a, b);
01181 }
01182 
01184 static int CDECL VehicleTimetableDelaySorter(const Vehicle * const *a, const Vehicle * const *b)
01185 {
01186   int r = (*a)->lateness_counter - (*b)->lateness_counter;
01187   return (r != 0) ? r : VehicleNumberSorter(a, b);
01188 }
01189 
01190 void InitializeGUI()
01191 {
01192   MemSetT(&_sorting, 0);
01193 }
01194 
01201 static inline void ChangeVehicleWindow(WindowClass window_class, VehicleID from_index, VehicleID to_index)
01202 {
01203   Window *w = FindWindowById(window_class, from_index);
01204   if (w != NULL) {
01205     /* Update window_number */
01206     w->window_number = to_index;
01207     if (w->viewport != NULL) w->viewport->follow_vehicle = to_index;
01208 
01209     /* Update vehicle drag data */
01210     if (_thd.window_class == window_class && _thd.window_number == (WindowNumber)from_index) {
01211       _thd.window_number = to_index;
01212     }
01213 
01214     /* Notify the window. */
01215     w->InvalidateData(VIWD_AUTOREPLACE, false);
01216   }
01217 }
01218 
01224 void ChangeVehicleViewWindow(VehicleID from_index, VehicleID to_index)
01225 {
01226   ChangeVehicleWindow(WC_VEHICLE_VIEW,      from_index, to_index);
01227   ChangeVehicleWindow(WC_VEHICLE_ORDERS,    from_index, to_index);
01228   ChangeVehicleWindow(WC_VEHICLE_REFIT,     from_index, to_index);
01229   ChangeVehicleWindow(WC_VEHICLE_DETAILS,   from_index, to_index);
01230   ChangeVehicleWindow(WC_VEHICLE_TIMETABLE, from_index, to_index);
01231 }
01232 
01233 static const NWidgetPart _nested_vehicle_list[] = {
01234   NWidget(NWID_HORIZONTAL),
01235     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
01236     NWidget(WWT_CAPTION, COLOUR_GREY, WID_VL_CAPTION),
01237     NWidget(WWT_SHADEBOX, COLOUR_GREY),
01238     NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
01239     NWidget(WWT_STICKYBOX, COLOUR_GREY),
01240   EndContainer(),
01241 
01242   NWidget(NWID_HORIZONTAL),
01243     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VL_SORT_ORDER), SetMinimalSize(81, 12), SetFill(0, 1), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
01244     NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_SORT_BY_PULLDOWN), SetMinimalSize(167, 12), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
01245     NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(12, 12), SetFill(1, 1), SetResize(1, 0),
01246     EndContainer(),
01247   EndContainer(),
01248 
01249   NWidget(NWID_HORIZONTAL),
01250     NWidget(WWT_MATRIX, COLOUR_GREY, WID_VL_LIST), SetMinimalSize(248, 0), SetFill(1, 0), SetResize(1, 1), SetMatrixDataTip(1, 0, STR_NULL), SetScrollbar(WID_VL_SCROLLBAR),
01251     NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VL_SCROLLBAR),
01252   EndContainer(),
01253 
01254   NWidget(NWID_HORIZONTAL),
01255     NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VL_HIDE_BUTTONS),
01256       NWidget(NWID_HORIZONTAL),
01257         NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VL_AVAILABLE_VEHICLES), SetMinimalSize(106, 12), SetFill(0, 1),
01258                 SetDataTip(STR_BLACK_STRING, STR_VEHICLE_LIST_AVAILABLE_ENGINES_TOOLTIP),
01259         NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(0, 12), SetResize(1, 0), SetFill(1, 1), EndContainer(),
01260         NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_MANAGE_VEHICLES_DROPDOWN), SetMinimalSize(118, 12), SetFill(0, 1),
01261                 SetDataTip(STR_VEHICLE_LIST_MANAGE_LIST, STR_VEHICLE_LIST_MANAGE_LIST_TOOLTIP),
01262         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VL_STOP_ALL), SetMinimalSize(12, 12), SetFill(0, 1),
01263                 SetDataTip(SPR_FLAG_VEH_STOPPED, STR_VEHICLE_LIST_MASS_STOP_LIST_TOOLTIP),
01264         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VL_START_ALL), SetMinimalSize(12, 12), SetFill(0, 1),
01265                 SetDataTip(SPR_FLAG_VEH_RUNNING, STR_VEHICLE_LIST_MASS_START_LIST_TOOLTIP),
01266       EndContainer(),
01267       /* Widget to be shown for other companies hiding the previous 5 widgets. */
01268       NWidget(WWT_PANEL, COLOUR_GREY), SetFill(1, 1), SetResize(1, 0), EndContainer(),
01269     EndContainer(),
01270     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
01271   EndContainer(),
01272 };
01273 
01274 static void DrawSmallOrderList(const Vehicle *v, int left, int right, int y, VehicleOrderID start = 0)
01275 {
01276   const Order *order = v->GetOrder(start);
01277   if (order == NULL) return;
01278 
01279   int i = 0;
01280   VehicleOrderID oid = start;
01281 
01282   do {
01283     if (oid == v->cur_real_order_index) DrawString(left, right, y, STR_TINY_RIGHT_ARROW, TC_BLACK);
01284 
01285     if (order->IsType(OT_GOTO_STATION)) {
01286       SetDParam(0, order->GetDestination());
01287       DrawString(left + 6, right - 6, y, STR_TINY_BLACK_STATION);
01288 
01289       y += FONT_HEIGHT_SMALL;
01290       if (++i == 4) break;
01291     }
01292 
01293     oid++;
01294     order = order->next;
01295     if (order == NULL) {
01296       order = v->orders.list->GetFirstOrder();
01297       oid = 0;
01298     }
01299   } while (oid != start);
01300 }
01301 
01311 void DrawVehicleImage(const Vehicle *v, int left, int right, int y, VehicleID selection, EngineImageType image_type, int skip)
01312 {
01313   switch (v->type) {
01314     case VEH_TRAIN:    DrawTrainImage(Train::From(v), left, right, y, selection, image_type, skip); break;
01315     case VEH_ROAD:     DrawRoadVehImage(v, left, right, y, selection, image_type, skip);  break;
01316     case VEH_SHIP:     DrawShipImage(v, left, right, y, selection, image_type);     break;
01317     case VEH_AIRCRAFT: DrawAircraftImage(v, left, right, y, selection, image_type); break;
01318     default: NOT_REACHED();
01319   }
01320 }
01321 
01328 uint GetVehicleListHeight(VehicleType type, uint divisor)
01329 {
01330   /* Name + vehicle + profit */
01331   uint base = GetVehicleHeight(type) + 2 * FONT_HEIGHT_SMALL;
01332   /* Drawing of the 4 small orders + profit*/
01333   if (type >= VEH_SHIP) base = max(base, 5U * FONT_HEIGHT_SMALL);
01334 
01335   if (divisor == 1) return base;
01336 
01337   /* Make sure the height is dividable by divisor */
01338   uint rem = base % divisor;
01339   return base + (rem == 0 ? 0 : divisor - rem);
01340 }
01341 
01348 void BaseVehicleListWindow::DrawVehicleListItems(VehicleID selected_vehicle, int line_height, const Rect &r) const
01349 {
01350   int left = r.left + WD_MATRIX_LEFT;
01351   int right = r.right - WD_MATRIX_RIGHT;
01352   int width = right - left;
01353   bool rtl = _current_text_dir == TD_RTL;
01354 
01355   int text_offset = GetDigitWidth() * this->unitnumber_digits + WD_FRAMERECT_RIGHT;
01356   int text_left  = left  + (rtl ?           0 : text_offset);
01357   int text_right = right - (rtl ? text_offset :           0);
01358 
01359   bool show_orderlist = this->vli.vtype >= VEH_SHIP;
01360   int orderlist_left  = left  + (rtl ? 0 : max(100 + text_offset, width / 2));
01361   int orderlist_right = right - (rtl ? max(100 + text_offset, width / 2) : 0);
01362 
01363   int image_left  = (rtl && show_orderlist) ? orderlist_right : text_left;
01364   int image_right = (!rtl && show_orderlist) ? orderlist_left : text_right;
01365 
01366   int vehicle_button_x = rtl ? right - GetSpriteSize(SPR_PROFIT_LOT).width : left;
01367 
01368   int y = r.top;
01369   uint max = min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->vehicles.Length());
01370   for (uint i = this->vscroll->GetPosition(); i < max; ++i) {
01371     const Vehicle *v = this->vehicles[i];
01372     StringID str;
01373 
01374     SetDParam(0, v->GetDisplayProfitThisYear());
01375     SetDParam(1, v->GetDisplayProfitLastYear());
01376 
01377     DrawVehicleImage(v, image_left, image_right, y + FONT_HEIGHT_SMALL - 1, selected_vehicle, EIT_IN_LIST, 0);
01378     DrawString(text_left, text_right, y + line_height - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1, STR_VEHICLE_LIST_PROFIT_THIS_YEAR_LAST_YEAR);
01379 
01380     if (v->name != NULL) {
01381       /* The vehicle got a name so we will print it */
01382       SetDParam(0, v->index);
01383       DrawString(text_left, text_right, y, STR_TINY_BLACK_VEHICLE);
01384     } else if (v->group_id != DEFAULT_GROUP) {
01385       /* The vehicle has no name, but is member of a group, so print group name */
01386       SetDParam(0, v->group_id);
01387       DrawString(text_left, text_right, y, STR_TINY_GROUP, TC_BLACK);
01388     }
01389 
01390     if (show_orderlist) DrawSmallOrderList(v, orderlist_left, orderlist_right, y, v->cur_real_order_index);
01391 
01392     if (v->IsChainInDepot()) {
01393       str = STR_BLUE_COMMA;
01394     } else {
01395       str = (v->age > v->max_age - DAYS_IN_LEAP_YEAR) ? STR_RED_COMMA : STR_BLACK_COMMA;
01396     }
01397 
01398     SetDParam(0, v->unitnumber);
01399     DrawString(left, right, y + 2, str);
01400 
01401     DrawVehicleProfitButton(v, vehicle_button_x, y + FONT_HEIGHT_NORMAL + 3);
01402 
01403     y += line_height;
01404   }
01405 }
01406 
01416 struct VehicleListWindow : public BaseVehicleListWindow {
01417 private:
01419   enum ButtonPlanes {
01420     BP_SHOW_BUTTONS, 
01421     BP_HIDE_BUTTONS, 
01422   };
01423 
01424 public:
01425   VehicleListWindow(WindowDesc *desc, WindowNumber window_number) : BaseVehicleListWindow(desc, window_number)
01426   {
01427     /* Set up sorting. Make the window-specific _sorting variable
01428      * point to the correct global _sorting struct so we are freed
01429      * from having conditionals during window operation */
01430     switch (this->vli.vtype) {
01431       case VEH_TRAIN:    this->sorting = &_sorting.train; break;
01432       case VEH_ROAD:     this->sorting = &_sorting.roadveh; break;
01433       case VEH_SHIP:     this->sorting = &_sorting.ship; break;
01434       case VEH_AIRCRAFT: this->sorting = &_sorting.aircraft; break;
01435       default: NOT_REACHED();
01436     }
01437 
01438     this->CreateNestedTree();
01439 
01440     this->vscroll = this->GetScrollbar(WID_VL_SCROLLBAR);
01441 
01442     this->vehicles.SetListing(*this->sorting);
01443     this->vehicles.ForceRebuild();
01444     this->vehicles.NeedResort();
01445     this->BuildVehicleList();
01446     this->SortVehicleList();
01447 
01448     /* Set up the window widgets */
01449     this->GetWidget<NWidgetCore>(WID_VL_LIST)->tool_tip = STR_VEHICLE_LIST_TRAIN_LIST_TOOLTIP + this->vli.vtype;
01450 
01451     if (this->vli.type == VL_SHARED_ORDERS) {
01452       this->GetWidget<NWidgetCore>(WID_VL_CAPTION)->widget_data = STR_VEHICLE_LIST_SHARED_ORDERS_LIST_CAPTION;
01453     } else {
01454       this->GetWidget<NWidgetCore>(WID_VL_CAPTION)->widget_data = STR_VEHICLE_LIST_TRAIN_CAPTION + this->vli.vtype;
01455     }
01456 
01457     this->FinishInitNested(window_number);
01458     if (this->vli.company != OWNER_NONE) this->owner = this->vli.company;
01459   }
01460 
01461   ~VehicleListWindow()
01462   {
01463     *this->sorting = this->vehicles.GetListing();
01464   }
01465 
01466   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01467   {
01468     switch (widget) {
01469       case WID_VL_LIST:
01470         resize->height = GetVehicleListHeight(this->vli.vtype, 1);
01471 
01472         switch (this->vli.vtype) {
01473           case VEH_TRAIN:
01474           case VEH_ROAD:
01475             size->height = 6 * resize->height;
01476             break;
01477           case VEH_SHIP:
01478           case VEH_AIRCRAFT:
01479             size->height = 4 * resize->height;
01480             break;
01481           default: NOT_REACHED();
01482         }
01483         break;
01484 
01485       case WID_VL_SORT_ORDER: {
01486         Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
01487         d.width += padding.width + WD_SORTBUTTON_ARROW_WIDTH * 2; // Doubled since the string is centred and it also looks better.
01488         d.height += padding.height;
01489         *size = maxdim(*size, d);
01490         break;
01491       }
01492 
01493       case WID_VL_MANAGE_VEHICLES_DROPDOWN: {
01494         Dimension d = this->GetActionDropdownSize(this->vli.type == VL_STANDARD, false);
01495         d.height += padding.height;
01496         d.width  += padding.width;
01497         *size = maxdim(*size, d);
01498         break;
01499       }
01500     }
01501   }
01502 
01503   virtual void SetStringParameters(int widget) const
01504   {
01505     switch (widget) {
01506       case WID_VL_AVAILABLE_VEHICLES:
01507         SetDParam(0, STR_VEHICLE_LIST_AVAILABLE_TRAINS + this->vli.vtype);
01508         break;
01509 
01510       case WID_VL_CAPTION: {
01511         switch (this->vli.type) {
01512           case VL_SHARED_ORDERS: // Shared Orders
01513             if (this->vehicles.Length() == 0) {
01514               /* We can't open this window without vehicles using this order
01515                * and we should close the window when deleting the order. */
01516               NOT_REACHED();
01517             }
01518             SetDParam(0, this->vscroll->GetCount());
01519             break;
01520 
01521           case VL_STANDARD: // Company Name
01522             SetDParam(0, STR_COMPANY_NAME);
01523             SetDParam(1, this->vli.index);
01524             SetDParam(3, this->vscroll->GetCount());
01525             break;
01526 
01527           case VL_STATION_LIST: // Station/Waypoint Name
01528             SetDParam(0, Station::IsExpected(BaseStation::Get(this->vli.index)) ? STR_STATION_NAME : STR_WAYPOINT_NAME);
01529             SetDParam(1, this->vli.index);
01530             SetDParam(3, this->vscroll->GetCount());
01531             break;
01532 
01533           case VL_DEPOT_LIST:
01534             SetDParam(0, STR_DEPOT_CAPTION);
01535             SetDParam(1, this->vli.vtype);
01536             SetDParam(2, this->vli.index);
01537             SetDParam(3, this->vscroll->GetCount());
01538             break;
01539           default: NOT_REACHED();
01540         }
01541         break;
01542       }
01543     }
01544   }
01545 
01546   virtual void DrawWidget(const Rect &r, int widget) const
01547   {
01548     switch (widget) {
01549       case WID_VL_SORT_ORDER:
01550         /* draw arrow pointing up/down for ascending/descending sorting */
01551         this->DrawSortButtonState(widget, this->vehicles.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
01552         break;
01553 
01554       case WID_VL_LIST:
01555         this->DrawVehicleListItems(INVALID_VEHICLE, this->resize.step_height, r);
01556         break;
01557     }
01558   }
01559 
01560   virtual void OnPaint()
01561   {
01562     this->BuildVehicleList();
01563     this->SortVehicleList();
01564 
01565     if (this->vehicles.Length() == 0 && this->IsWidgetLowered(WID_VL_MANAGE_VEHICLES_DROPDOWN)) {
01566       HideDropDownMenu(this);
01567     }
01568 
01569     /* Hide the widgets that we will not use in this window
01570      * Some windows contains actions only fit for the owner */
01571     int plane_to_show = (this->owner == _local_company) ? BP_SHOW_BUTTONS : BP_HIDE_BUTTONS;
01572     NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VL_HIDE_BUTTONS);
01573     if (plane_to_show != nwi->shown_plane) {
01574       nwi->SetDisplayedPlane(plane_to_show);
01575       nwi->SetDirty(this);
01576     }
01577     if (this->owner == _local_company) {
01578       this->SetWidgetDisabledState(WID_VL_AVAILABLE_VEHICLES, this->vli.type != VL_STANDARD);
01579       this->SetWidgetsDisabledState(this->vehicles.Length() == 0,
01580         WID_VL_MANAGE_VEHICLES_DROPDOWN,
01581         WID_VL_STOP_ALL,
01582         WID_VL_START_ALL,
01583         WIDGET_LIST_END);
01584     }
01585 
01586     /* Set text of sort by dropdown widget. */
01587     this->GetWidget<NWidgetCore>(WID_VL_SORT_BY_PULLDOWN)->widget_data = this->vehicle_sorter_names[this->vehicles.SortType()];
01588 
01589     this->DrawWidgets();
01590   }
01591 
01592   virtual void OnClick(Point pt, int widget, int click_count)
01593   {
01594     switch (widget) {
01595       case WID_VL_SORT_ORDER: // Flip sorting method ascending/descending
01596         this->vehicles.ToggleSortOrder();
01597         this->SetDirty();
01598         break;
01599 
01600       case WID_VL_SORT_BY_PULLDOWN:// Select sorting criteria dropdown menu
01601         ShowDropDownMenu(this, this->vehicle_sorter_names, this->vehicles.SortType(), WID_VL_SORT_BY_PULLDOWN, 0,
01602             (this->vli.vtype == VEH_TRAIN || this->vli.vtype == VEH_ROAD) ? 0 : (1 << 10));
01603         return;
01604 
01605       case WID_VL_LIST: { // Matrix to show vehicles
01606         uint id_v = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_VL_LIST);
01607         if (id_v >= this->vehicles.Length()) return; // click out of list bound
01608 
01609         const Vehicle *v = this->vehicles[id_v];
01610         if (!VehicleClicked(v)) ShowVehicleViewWindow(v);
01611         break;
01612       }
01613 
01614       case WID_VL_AVAILABLE_VEHICLES:
01615         ShowBuildVehicleWindow(INVALID_TILE, this->vli.vtype);
01616         break;
01617 
01618       case WID_VL_MANAGE_VEHICLES_DROPDOWN: {
01619         DropDownList *list = this->BuildActionDropdownList(VehicleListIdentifier(this->window_number).type == VL_STANDARD, false);
01620         ShowDropDownList(this, list, 0, WID_VL_MANAGE_VEHICLES_DROPDOWN);
01621         break;
01622       }
01623 
01624       case WID_VL_STOP_ALL:
01625       case WID_VL_START_ALL:
01626         DoCommandP(0, (1 << 1) | (widget == WID_VL_START_ALL ? (1 << 0) : 0), this->window_number, CMD_MASS_START_STOP);
01627         break;
01628     }
01629   }
01630 
01631   virtual void OnDropdownSelect(int widget, int index)
01632   {
01633     switch (widget) {
01634       case WID_VL_SORT_BY_PULLDOWN:
01635         this->vehicles.SetSortType(index);
01636         break;
01637       case WID_VL_MANAGE_VEHICLES_DROPDOWN:
01638         assert(this->vehicles.Length() != 0);
01639 
01640         switch (index) {
01641           case ADI_REPLACE: // Replace window
01642             ShowReplaceGroupVehicleWindow(ALL_GROUP, this->vli.vtype);
01643             break;
01644           case ADI_SERVICE: // Send for servicing
01645           case ADI_DEPOT: // Send to Depots
01646             DoCommandP(0, DEPOT_MASS_SEND | (index == ADI_SERVICE ? DEPOT_SERVICE : (DepotCommand)0), this->window_number, GetCmdSendToDepot(this->vli.vtype));
01647             break;
01648 
01649           default: NOT_REACHED();
01650         }
01651         break;
01652       default: NOT_REACHED();
01653     }
01654     this->SetDirty();
01655   }
01656 
01657   virtual void OnTick()
01658   {
01659     if (_pause_mode != PM_UNPAUSED) return;
01660     if (this->vehicles.NeedResort()) {
01661       StationID station = (this->vli.type == VL_STATION_LIST) ? this->vli.index : INVALID_STATION;
01662 
01663       DEBUG(misc, 3, "Periodic resort %d list company %d at station %d", this->vli.vtype, this->owner, station);
01664       this->SetDirty();
01665     }
01666   }
01667 
01668   virtual void OnResize()
01669   {
01670     this->vscroll->SetCapacityFromWidget(this, WID_VL_LIST);
01671   }
01672 
01678   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
01679   {
01680     if (!gui_scope && HasBit(data, 31) && this->vli.type == VL_SHARED_ORDERS) {
01681       /* Needs to be done in command-scope, so everything stays valid */
01682       this->vli.index = GB(data, 0, 20);
01683       this->window_number = this->vli.Pack();
01684       this->vehicles.ForceRebuild();
01685       return;
01686     }
01687 
01688     if (data == 0) {
01689       /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
01690       this->vehicles.ForceRebuild();
01691     } else {
01692       this->vehicles.ForceResort();
01693     }
01694   }
01695 };
01696 
01697 static WindowDesc _vehicle_list_other_desc(
01698   WDP_AUTO, "list_vehicles", 260, 246,
01699   WC_INVALID, WC_NONE,
01700   0,
01701   _nested_vehicle_list, lengthof(_nested_vehicle_list)
01702 );
01703 
01704 static WindowDesc _vehicle_list_train_desc(
01705   WDP_AUTO, "list_vehicles_train", 325, 246,
01706   WC_TRAINS_LIST, WC_NONE,
01707   0,
01708   _nested_vehicle_list, lengthof(_nested_vehicle_list)
01709 );
01710 
01711 static void ShowVehicleListWindowLocal(CompanyID company, VehicleListType vlt, VehicleType vehicle_type, uint32 unique_number)
01712 {
01713   if (!Company::IsValidID(company) && company != OWNER_NONE) return;
01714 
01715   WindowNumber num = VehicleListIdentifier(vlt, vehicle_type, company, unique_number).Pack();
01716   if (vehicle_type == VEH_TRAIN) {
01717     AllocateWindowDescFront<VehicleListWindow>(&_vehicle_list_train_desc, num);
01718   } else {
01719     _vehicle_list_other_desc.cls = GetWindowClassForVehicleType(vehicle_type);
01720     AllocateWindowDescFront<VehicleListWindow>(&_vehicle_list_other_desc, num);
01721   }
01722 }
01723 
01724 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type)
01725 {
01726   /* If _settings_client.gui.advanced_vehicle_list > 1, display the Advanced list
01727    * if _settings_client.gui.advanced_vehicle_list == 1, display Advanced list only for local company
01728    * if _ctrl_pressed, do the opposite action (Advanced list x Normal list)
01729    */
01730 
01731   if ((_settings_client.gui.advanced_vehicle_list > (uint)(company != _local_company)) != _ctrl_pressed) {
01732     ShowCompanyGroup(company, vehicle_type);
01733   } else {
01734     ShowVehicleListWindowLocal(company, VL_STANDARD, vehicle_type, company);
01735   }
01736 }
01737 
01738 void ShowVehicleListWindow(const Vehicle *v)
01739 {
01740   ShowVehicleListWindowLocal(v->owner, VL_SHARED_ORDERS, v->type, v->FirstShared()->index);
01741 }
01742 
01743 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, StationID station)
01744 {
01745   ShowVehicleListWindowLocal(company, VL_STATION_LIST, vehicle_type, station);
01746 }
01747 
01748 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, TileIndex depot_tile)
01749 {
01750   uint16 depot_airport_index;
01751 
01752   if (vehicle_type == VEH_AIRCRAFT) {
01753     depot_airport_index = GetStationIndex(depot_tile);
01754   } else {
01755     depot_airport_index = GetDepotIndex(depot_tile);
01756   }
01757   ShowVehicleListWindowLocal(company, VL_DEPOT_LIST, vehicle_type, depot_airport_index);
01758 }
01759 
01760 
01761 /* Unified vehicle GUI - Vehicle Details Window */
01762 
01763 assert_compile(WID_VD_DETAILS_CARGO_CARRIED    == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_CARGO   );
01764 assert_compile(WID_VD_DETAILS_TRAIN_VEHICLES   == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_INFO    );
01765 assert_compile(WID_VD_DETAILS_CAPACITY_OF_EACH == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_CAPACITY);
01766 assert_compile(WID_VD_DETAILS_TOTAL_CARGO      == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_TOTALS  );
01767 
01769 static const NWidgetPart _nested_nontrain_vehicle_details_widgets[] = {
01770   NWidget(NWID_HORIZONTAL),
01771     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
01772     NWidget(WWT_CAPTION, COLOUR_GREY, WID_VD_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
01773     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_RENAME_VEHICLE), SetMinimalSize(40, 0), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetDataTip(STR_VEHICLE_NAME_BUTTON, STR_NULL /* filled in later */),
01774     NWidget(WWT_SHADEBOX, COLOUR_GREY),
01775     NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
01776     NWidget(WWT_STICKYBOX, COLOUR_GREY),
01777   EndContainer(),
01778   NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_TOP_DETAILS), SetMinimalSize(405, 42), SetResize(1, 0), EndContainer(),
01779   NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_MIDDLE_DETAILS), SetMinimalSize(405, 45), SetResize(1, 0), EndContainer(),
01780   NWidget(NWID_HORIZONTAL),
01781     NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_DECREASE_SERVICING_INTERVAL), SetFill(0, 1),
01782         SetDataTip(AWV_DECREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
01783     NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_INCREASE_SERVICING_INTERVAL), SetFill(0, 1),
01784         SetDataTip(AWV_INCREASE, STR_VEHICLE_DETAILS_INCREASE_SERVICING_INTERVAL_TOOLTIP),
01785     NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VD_SERVICE_INTERVAL_DROPDOWN), SetFill(0, 1),
01786         SetDataTip(STR_EMPTY, STR_SERVICE_INTERVAL_DROPDOWN_TOOLTIP),
01787     NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_SERVICING_INTERVAL), SetFill(1, 1), SetResize(1, 0), EndContainer(),
01788     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
01789   EndContainer(),
01790 };
01791 
01793 static const NWidgetPart _nested_train_vehicle_details_widgets[] = {
01794   NWidget(NWID_HORIZONTAL),
01795     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
01796     NWidget(WWT_CAPTION, COLOUR_GREY, WID_VD_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
01797     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_RENAME_VEHICLE), SetMinimalSize(40, 0), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetDataTip(STR_VEHICLE_NAME_BUTTON, STR_NULL /* filled in later */),
01798     NWidget(WWT_SHADEBOX, COLOUR_GREY),
01799     NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
01800     NWidget(WWT_STICKYBOX, COLOUR_GREY),
01801   EndContainer(),
01802   NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_TOP_DETAILS), SetResize(1, 0), SetMinimalSize(405, 42), EndContainer(),
01803   NWidget(NWID_HORIZONTAL),
01804     NWidget(WWT_MATRIX, COLOUR_GREY, WID_VD_MATRIX), SetResize(1, 1), SetMinimalSize(393, 45), SetMatrixDataTip(1, 0, STR_NULL), SetFill(1, 0), SetScrollbar(WID_VD_SCROLLBAR),
01805     NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VD_SCROLLBAR),
01806   EndContainer(),
01807   NWidget(NWID_HORIZONTAL),
01808     NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_DECREASE_SERVICING_INTERVAL), SetFill(0, 1),
01809         SetDataTip(AWV_DECREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
01810     NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_INCREASE_SERVICING_INTERVAL), SetFill(0, 1),
01811         SetDataTip(AWV_INCREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
01812     NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VD_SERVICE_INTERVAL_DROPDOWN), SetFill(0, 1),
01813         SetDataTip(STR_EMPTY, STR_SERVICE_INTERVAL_DROPDOWN_TOOLTIP),
01814     NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_SERVICING_INTERVAL), SetFill(1, 1), SetResize(1, 0), EndContainer(),
01815   EndContainer(),
01816   NWidget(NWID_HORIZONTAL),
01817     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_CARGO_CARRIED), SetMinimalSize(96, 12),
01818         SetDataTip(STR_VEHICLE_DETAIL_TAB_CARGO, STR_VEHICLE_DETAILS_TRAIN_CARGO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
01819     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_TRAIN_VEHICLES), SetMinimalSize(99, 12),
01820         SetDataTip(STR_VEHICLE_DETAIL_TAB_INFORMATION, STR_VEHICLE_DETAILS_TRAIN_INFORMATION_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
01821     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_CAPACITY_OF_EACH), SetMinimalSize(99, 12),
01822         SetDataTip(STR_VEHICLE_DETAIL_TAB_CAPACITIES, STR_VEHICLE_DETAILS_TRAIN_CAPACITIES_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
01823     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_TOTAL_CARGO), SetMinimalSize(99, 12),
01824         SetDataTip(STR_VEHICLE_DETAIL_TAB_TOTAL_CARGO, STR_VEHICLE_DETAILS_TRAIN_TOTAL_CARGO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
01825     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
01826   EndContainer(),
01827 };
01828 
01829 
01830 extern int GetTrainDetailsWndVScroll(VehicleID veh_id, TrainDetailsWindowTabs det_tab);
01831 extern void DrawTrainDetails(const Train *v, int left, int right, int y, int vscroll_pos, uint16 vscroll_cap, TrainDetailsWindowTabs det_tab);
01832 extern void DrawRoadVehDetails(const Vehicle *v, int left, int right, int y);
01833 extern void DrawShipDetails(const Vehicle *v, int left, int right, int y);
01834 extern void DrawAircraftDetails(const Aircraft *v, int left, int right, int y);
01835 
01836 static StringID _service_interval_dropdown[] = {
01837   STR_VEHICLE_DETAILS_DEFAULT,
01838   STR_VEHICLE_DETAILS_DAYS,
01839   STR_VEHICLE_DETAILS_PERCENT,
01840   INVALID_STRING_ID,
01841 };
01842 
01844 struct VehicleDetailsWindow : Window {
01845   TrainDetailsWindowTabs tab; 
01846   Scrollbar *vscroll;
01847 
01849   VehicleDetailsWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
01850   {
01851     const Vehicle *v = Vehicle::Get(window_number);
01852 
01853     this->CreateNestedTree();
01854     this->vscroll = (v->type == VEH_TRAIN ? this->GetScrollbar(WID_VD_SCROLLBAR) : NULL);
01855     this->FinishInitNested(window_number);
01856 
01857     this->GetWidget<NWidgetCore>(WID_VD_RENAME_VEHICLE)->tool_tip = STR_VEHICLE_DETAILS_TRAIN_RENAME + v->type;
01858 
01859     this->owner = v->owner;
01860     this->tab = TDW_TAB_CARGO;
01861   }
01862 
01868   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
01869   {
01870     if (data == VIWD_AUTOREPLACE) {
01871       /* Autoreplace replaced the vehicle.
01872        * Nothing to do for this window. */
01873       return;
01874     }
01875     if (!gui_scope) return;
01876     const Vehicle *v = Vehicle::Get(this->window_number);
01877     if (v->type == VEH_ROAD) {
01878       const NWidgetBase *nwid_info = this->GetWidget<NWidgetBase>(WID_VD_MIDDLE_DETAILS);
01879       uint aimed_height = this->GetRoadVehDetailsHeight(v);
01880       /* If the number of articulated parts changes, the size of the window must change too. */
01881       if (aimed_height != nwid_info->current_y) {
01882         this->ReInit();
01883       }
01884     }
01885   }
01886 
01892   uint GetRoadVehDetailsHeight(const Vehicle *v)
01893   {
01894     uint desired_height;
01895     if (v->HasArticulatedPart()) {
01896       /* An articulated RV has its text drawn under the sprite instead of after it, hence 15 pixels extra. */
01897       desired_height = WD_FRAMERECT_TOP + 15 + 3 * FONT_HEIGHT_NORMAL + 2 + WD_FRAMERECT_BOTTOM;
01898       /* Add space for the cargo amount for each part. */
01899       for (const Vehicle *u = v; u != NULL; u = u->Next()) {
01900         if (u->cargo_cap != 0) desired_height += FONT_HEIGHT_NORMAL + 1;
01901       }
01902     } else {
01903       desired_height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + 3 + WD_FRAMERECT_BOTTOM;
01904     }
01905     return desired_height;
01906   }
01907 
01908   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01909   {
01910     switch (widget) {
01911       case WID_VD_TOP_DETAILS: {
01912         Dimension dim = { 0, 0 };
01913         size->height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
01914 
01915         for (uint i = 0; i < 4; i++) SetDParamMaxValue(i, INT16_MAX);
01916         static const StringID info_strings[] = {
01917           STR_VEHICLE_INFO_MAX_SPEED,
01918           STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED,
01919           STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE,
01920           STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR,
01921           STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS
01922         };
01923         for (uint i = 0; i < lengthof(info_strings); i++) {
01924           dim = maxdim(dim, GetStringBoundingBox(info_strings[i]));
01925         }
01926         SetDParam(0, STR_VEHICLE_INFO_AGE);
01927         dim = maxdim(dim, GetStringBoundingBox(STR_VEHICLE_INFO_AGE_RUNNING_COST_YR));
01928         size->width = dim.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
01929         break;
01930       }
01931 
01932       case WID_VD_MIDDLE_DETAILS: {
01933         const Vehicle *v = Vehicle::Get(this->window_number);
01934         switch (v->type) {
01935           case VEH_ROAD:
01936             size->height = this->GetRoadVehDetailsHeight(v);
01937             break;
01938 
01939           case VEH_SHIP:
01940             size->height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + 3 + WD_FRAMERECT_BOTTOM;
01941             break;
01942 
01943           case VEH_AIRCRAFT:
01944             size->height = WD_FRAMERECT_TOP + 5 * FONT_HEIGHT_NORMAL + 4 + WD_FRAMERECT_BOTTOM;
01945             break;
01946 
01947           default:
01948             NOT_REACHED(); // Train uses WID_VD_MATRIX instead.
01949         }
01950         break;
01951       }
01952 
01953       case WID_VD_MATRIX:
01954         resize->height = WD_MATRIX_TOP + FONT_HEIGHT_NORMAL + WD_MATRIX_BOTTOM;
01955         size->height = 4 * resize->height;
01956         break;
01957 
01958       case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
01959         StringID *strs = _service_interval_dropdown;
01960         while (*strs != INVALID_STRING_ID) {
01961           *size = maxdim(*size, GetStringBoundingBox(*strs++));
01962         }
01963         size->width += padding.width;
01964         size->height = FONT_HEIGHT_NORMAL + WD_DROPDOWNTEXT_TOP + WD_DROPDOWNTEXT_BOTTOM;
01965         break;
01966       }
01967 
01968       case WID_VD_SERVICING_INTERVAL:
01969         SetDParamMaxValue(0, MAX_SERVINT_DAYS); // Roughly the maximum interval
01970         SetDParamMaxValue(1, MAX_YEAR * DAYS_IN_YEAR); // Roughly the maximum year
01971         size->width = max(GetStringBoundingBox(STR_VEHICLE_DETAILS_SERVICING_INTERVAL_PERCENT).width, GetStringBoundingBox(STR_VEHICLE_DETAILS_SERVICING_INTERVAL_DAYS).width) + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
01972         size->height = WD_FRAMERECT_TOP + FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
01973         break;
01974     }
01975   }
01976 
01978   static bool IsVehicleServiceIntervalEnabled(const VehicleType vehicle_type, CompanyID company_id)
01979   {
01980     const VehicleDefaultSettings *vds = &Company::Get(company_id)->settings.vehicle;
01981     switch (vehicle_type) {
01982       default: NOT_REACHED();
01983       case VEH_TRAIN:    return vds->servint_trains   != 0;
01984       case VEH_ROAD:     return vds->servint_roadveh  != 0;
01985       case VEH_SHIP:     return vds->servint_ships    != 0;
01986       case VEH_AIRCRAFT: return vds->servint_aircraft != 0;
01987     }
01988   }
01989 
02001   static void DrawVehicleDetails(const Vehicle *v, int left, int right, int y, int vscroll_pos, uint vscroll_cap, TrainDetailsWindowTabs det_tab)
02002   {
02003     switch (v->type) {
02004       case VEH_TRAIN:    DrawTrainDetails(Train::From(v), left, right, y, vscroll_pos, vscroll_cap, det_tab);  break;
02005       case VEH_ROAD:     DrawRoadVehDetails(v, left, right, y);  break;
02006       case VEH_SHIP:     DrawShipDetails(v, left, right, y);     break;
02007       case VEH_AIRCRAFT: DrawAircraftDetails(Aircraft::From(v), left, right, y); break;
02008       default: NOT_REACHED();
02009     }
02010   }
02011 
02012   virtual void SetStringParameters(int widget) const
02013   {
02014     if (widget == WID_VD_CAPTION) SetDParam(0, Vehicle::Get(this->window_number)->index);
02015   }
02016 
02017   virtual void DrawWidget(const Rect &r, int widget) const
02018   {
02019     const Vehicle *v = Vehicle::Get(this->window_number);
02020 
02021     switch (widget) {
02022       case WID_VD_TOP_DETAILS: {
02023         int y = r.top + WD_FRAMERECT_TOP;
02024 
02025         /* Draw running cost */
02026         SetDParam(1, v->age / DAYS_IN_LEAP_YEAR);
02027         SetDParam(0, (v->age + DAYS_IN_YEAR < v->max_age) ? STR_VEHICLE_INFO_AGE : STR_VEHICLE_INFO_AGE_RED);
02028         SetDParam(2, v->max_age / DAYS_IN_LEAP_YEAR);
02029         SetDParam(3, v->GetDisplayRunningCost());
02030         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_AGE_RUNNING_COST_YR);
02031         y += FONT_HEIGHT_NORMAL;
02032 
02033         /* Draw max speed */
02034         StringID string;
02035         if (v->type == VEH_TRAIN ||
02036             (v->type == VEH_ROAD && _settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL)) {
02037           const GroundVehicleCache *gcache = v->GetGroundVehicleCache();
02038           SetDParam(2, v->GetDisplayMaxSpeed());
02039           SetDParam(1, gcache->cached_power);
02040           SetDParam(0, gcache->cached_weight);
02041           SetDParam(3, gcache->cached_max_te / 1000);
02042           if (v->type == VEH_TRAIN && (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ||
02043               GetRailTypeInfo(Train::From(v)->railtype)->acceleration_type == 2)) {
02044             string = STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED;
02045           } else {
02046             string = STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE;
02047           }
02048         } else {
02049           SetDParam(0, v->GetDisplayMaxSpeed());
02050           if (v->type == VEH_AIRCRAFT && Aircraft::From(v)->GetRange() > 0) {
02051             SetDParam(1, Aircraft::From(v)->GetRange());
02052             string = STR_VEHICLE_INFO_MAX_SPEED_RANGE;
02053           } else {
02054             string = STR_VEHICLE_INFO_MAX_SPEED;
02055           }
02056         }
02057         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, string);
02058         y += FONT_HEIGHT_NORMAL;
02059 
02060         /* Draw profit */
02061         SetDParam(0, v->GetDisplayProfitThisYear());
02062         SetDParam(1, v->GetDisplayProfitLastYear());
02063         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR);
02064         y += FONT_HEIGHT_NORMAL;
02065 
02066         /* Draw breakdown & reliability */
02067         SetDParam(0, ToPercent16(v->reliability));
02068         SetDParam(1, v->breakdowns_since_last_service);
02069         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS);
02070         break;
02071       }
02072 
02073       case WID_VD_MATRIX:
02074         /* For trains only. */
02075         DrawVehicleDetails(v, r.left + WD_MATRIX_LEFT, r.right - WD_MATRIX_RIGHT, r.top + WD_MATRIX_TOP, this->vscroll->GetPosition(), this->vscroll->GetCapacity(), this->tab);
02076         break;
02077 
02078       case WID_VD_MIDDLE_DETAILS: {
02079         /* For other vehicles, at the place of the matrix. */
02080         bool rtl = _current_text_dir == TD_RTL;
02081         uint sprite_width = max<uint>(UnScaleByZoom(GetSprite(v->GetImage(rtl ? DIR_E : DIR_W, EIT_IN_DETAILS), ST_NORMAL)->width, ZOOM_LVL_GUI), 70U) + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
02082 
02083         uint text_left  = r.left  + (rtl ? 0 : sprite_width);
02084         uint text_right = r.right - (rtl ? sprite_width : 0);
02085 
02086         /* Articulated road vehicles use a complete line. */
02087         if (v->type == VEH_ROAD && v->HasArticulatedPart()) {
02088           DrawVehicleImage(v, r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, 0);
02089         } else {
02090           uint sprite_left  = rtl ? text_right : r.left;
02091           uint sprite_right = rtl ? r.right : text_left;
02092 
02093           DrawVehicleImage(v, sprite_left + WD_FRAMERECT_LEFT, sprite_right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, 0);
02094         }
02095         DrawVehicleDetails(v, text_left + WD_FRAMERECT_LEFT, text_right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, 0, 0, this->tab);
02096         break;
02097       }
02098 
02099       case WID_VD_SERVICING_INTERVAL:
02100         /* Draw service interval text */
02101         SetDParam(0, v->GetServiceInterval());
02102         SetDParam(1, v->date_of_last_service);
02103         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + (r.bottom - r.top + 1 - FONT_HEIGHT_NORMAL) / 2,
02104             v->ServiceIntervalIsPercent() ? STR_VEHICLE_DETAILS_SERVICING_INTERVAL_PERCENT : STR_VEHICLE_DETAILS_SERVICING_INTERVAL_DAYS);
02105         break;
02106     }
02107   }
02108 
02110   virtual void OnPaint()
02111   {
02112     const Vehicle *v = Vehicle::Get(this->window_number);
02113 
02114     this->SetWidgetDisabledState(WID_VD_RENAME_VEHICLE, v->owner != _local_company);
02115 
02116     if (v->type == VEH_TRAIN) {
02117       this->DisableWidget(this->tab + WID_VD_DETAILS_CARGO_CARRIED);
02118       this->vscroll->SetCount(GetTrainDetailsWndVScroll(v->index, this->tab));
02119     }
02120 
02121     /* Disable service-scroller when interval is set to disabled */
02122     this->SetWidgetsDisabledState(!IsVehicleServiceIntervalEnabled(v->type, v->owner),
02123       WID_VD_INCREASE_SERVICING_INTERVAL,
02124       WID_VD_DECREASE_SERVICING_INTERVAL,
02125       WIDGET_LIST_END);
02126 
02127     StringID str = v->ServiceIntervalIsCustom() ?
02128       (v->ServiceIntervalIsPercent() ? STR_VEHICLE_DETAILS_PERCENT : STR_VEHICLE_DETAILS_DAYS) :
02129       STR_VEHICLE_DETAILS_DEFAULT;
02130     this->GetWidget<NWidgetCore>(WID_VD_SERVICE_INTERVAL_DROPDOWN)->widget_data = str;
02131 
02132     this->DrawWidgets();
02133   }
02134 
02135   virtual void OnClick(Point pt, int widget, int click_count)
02136   {
02137     switch (widget) {
02138       case WID_VD_RENAME_VEHICLE: { // rename
02139         const Vehicle *v = Vehicle::Get(this->window_number);
02140         SetDParam(0, v->index);
02141         ShowQueryString(STR_VEHICLE_NAME, STR_QUERY_RENAME_TRAIN_CAPTION + v->type,
02142             MAX_LENGTH_VEHICLE_NAME_CHARS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
02143         break;
02144       }
02145 
02146       case WID_VD_INCREASE_SERVICING_INTERVAL:   // increase int
02147       case WID_VD_DECREASE_SERVICING_INTERVAL: { // decrease int
02148         int mod = _ctrl_pressed ? 5 : 10;
02149         const Vehicle *v = Vehicle::Get(this->window_number);
02150 
02151         mod = (widget == WID_VD_DECREASE_SERVICING_INTERVAL) ? -mod : mod;
02152         mod = GetServiceIntervalClamped(mod + v->GetServiceInterval(), v->ServiceIntervalIsPercent());
02153         if (mod == v->GetServiceInterval()) return;
02154 
02155         DoCommandP(v->tile, v->index, mod | (1 << 16) | (v->ServiceIntervalIsPercent() << 17), CMD_CHANGE_SERVICE_INT | CMD_MSG(STR_ERROR_CAN_T_CHANGE_SERVICING));
02156         break;
02157       }
02158 
02159       case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
02160         const Vehicle *v = Vehicle::Get(this->window_number);
02161         ShowDropDownMenu(this, _service_interval_dropdown, v->ServiceIntervalIsCustom() ? (v->ServiceIntervalIsPercent() ? 2 : 1) : 0, widget, 0, 0);
02162         break;
02163       }
02164 
02165       case WID_VD_DETAILS_CARGO_CARRIED:
02166       case WID_VD_DETAILS_TRAIN_VEHICLES:
02167       case WID_VD_DETAILS_CAPACITY_OF_EACH:
02168       case WID_VD_DETAILS_TOTAL_CARGO:
02169         this->SetWidgetsDisabledState(false,
02170           WID_VD_DETAILS_CARGO_CARRIED,
02171           WID_VD_DETAILS_TRAIN_VEHICLES,
02172           WID_VD_DETAILS_CAPACITY_OF_EACH,
02173           WID_VD_DETAILS_TOTAL_CARGO,
02174           widget,
02175           WIDGET_LIST_END);
02176 
02177         this->tab = (TrainDetailsWindowTabs)(widget - WID_VD_DETAILS_CARGO_CARRIED);
02178         this->SetDirty();
02179         break;
02180     }
02181   }
02182 
02183   virtual void OnDropdownSelect(int widget, int index)
02184   {
02185     switch (widget) {
02186       case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
02187         const Vehicle *v = Vehicle::Get(this->window_number);
02188         bool iscustom = index != 0;
02189         bool ispercent = iscustom ? (index == 2) : Company::Get(v->owner)->settings.vehicle.servint_ispercent;
02190         uint16 interval = GetServiceIntervalClamped(v->GetServiceInterval(), ispercent);
02191         DoCommandP(v->tile, v->index, interval | (iscustom << 16) | (ispercent << 17), CMD_CHANGE_SERVICE_INT | CMD_MSG(STR_ERROR_CAN_T_CHANGE_SERVICING));
02192         break;
02193       }
02194     }
02195   }
02196 
02197   virtual void OnQueryTextFinished(char *str)
02198   {
02199     if (str == NULL) return;
02200 
02201     DoCommandP(0, this->window_number, 0, CMD_RENAME_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_RENAME_TRAIN + Vehicle::Get(this->window_number)->type), NULL, str);
02202   }
02203 
02204   virtual void OnResize()
02205   {
02206     NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_VD_MATRIX);
02207     if (nwi != NULL) {
02208       this->vscroll->SetCapacityFromWidget(this, WID_VD_MATRIX);
02209     }
02210   }
02211 };
02212 
02214 static WindowDesc _train_vehicle_details_desc(
02215   WDP_AUTO, "view_vehicle_details_train", 405, 178,
02216   WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
02217   0,
02218   _nested_train_vehicle_details_widgets, lengthof(_nested_train_vehicle_details_widgets)
02219 );
02220 
02222 static WindowDesc _nontrain_vehicle_details_desc(
02223   WDP_AUTO, "view_vehicle_details", 405, 113,
02224   WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
02225   0,
02226   _nested_nontrain_vehicle_details_widgets, lengthof(_nested_nontrain_vehicle_details_widgets)
02227 );
02228 
02230 static void ShowVehicleDetailsWindow(const Vehicle *v)
02231 {
02232   DeleteWindowById(WC_VEHICLE_ORDERS, v->index, false);
02233   DeleteWindowById(WC_VEHICLE_TIMETABLE, v->index, false);
02234   AllocateWindowDescFront<VehicleDetailsWindow>((v->type == VEH_TRAIN) ? &_train_vehicle_details_desc : &_nontrain_vehicle_details_desc, v->index);
02235 }
02236 
02237 
02238 /* Unified vehicle GUI - Vehicle View Window */
02239 
02241 static const NWidgetPart _nested_vehicle_view_widgets[] = {
02242   NWidget(NWID_HORIZONTAL),
02243     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
02244     NWidget(WWT_CAPTION, COLOUR_GREY, WID_VV_CAPTION), SetDataTip(STR_VEHICLE_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
02245     NWidget(WWT_DEBUGBOX, COLOUR_GREY),
02246     NWidget(WWT_SHADEBOX, COLOUR_GREY),
02247     NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
02248     NWidget(WWT_STICKYBOX, COLOUR_GREY),
02249   EndContainer(),
02250   NWidget(NWID_HORIZONTAL),
02251     NWidget(WWT_PANEL, COLOUR_GREY),
02252       NWidget(WWT_INSET, COLOUR_GREY), SetPadding(2, 2, 2, 2),
02253         NWidget(NWID_VIEWPORT, INVALID_COLOUR, WID_VV_VIEWPORT), SetMinimalSize(226, 84), SetResize(1, 1), SetPadding(1, 1, 1, 1),
02254       EndContainer(),
02255     EndContainer(),
02256     NWidget(NWID_VERTICAL),
02257       NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_CENTER_MAIN_VIEW), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(SPR_CENTRE_VIEW_VEHICLE, 0x0 /* filled later */),
02258       NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VV_SELECT_DEPOT_CLONE),
02259         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_GOTO_DEPOT), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
02260         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_CLONE), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
02261       EndContainer(),
02262       /* For trains only, 'ignore signal' button. */
02263       NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_FORCE_PROCEED), SetMinimalSize(18, 18), SetFill(1, 1),
02264                       SetDataTip(SPR_IGNORE_SIGNALS, STR_VEHICLE_VIEW_TRAIN_IGNORE_SIGNAL_TOOLTIP),
02265       NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VV_SELECT_REFIT_TURN),
02266         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_REFIT), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(SPR_REFIT_VEHICLE, 0x0 /* filled later */),
02267         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_TURN_AROUND), SetMinimalSize(18, 18), SetFill(1, 1),
02268                         SetDataTip(SPR_FORCE_VEHICLE_TURN, STR_VEHICLE_VIEW_ROAD_VEHICLE_REVERSE_TOOLTIP),
02269       EndContainer(),
02270       NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_SHOW_ORDERS), SetFill(1, 1), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_ORDERS, 0x0 /* filled later */),
02271       NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_SHOW_DETAILS), SetFill(1, 1), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_VEHICLE_DETAILS, 0x0 /* filled later */),
02272       NWidget(WWT_PANEL, COLOUR_GREY), SetFill(1, 1), SetMinimalSize(18, 0), SetResize(0, 1), EndContainer(),
02273     EndContainer(),
02274   EndContainer(),
02275   NWidget(NWID_HORIZONTAL),
02276     NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_VV_START_STOP), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetResize(1, 0), SetFill(1, 0),
02277     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
02278   EndContainer(),
02279 };
02280 
02282 static WindowDesc _vehicle_view_desc(
02283   WDP_AUTO, "view_vehicle", 250, 116,
02284   WC_VEHICLE_VIEW, WC_NONE,
02285   0,
02286   _nested_vehicle_view_widgets, lengthof(_nested_vehicle_view_widgets)
02287 );
02288 
02293 static WindowDesc _train_view_desc(
02294   WDP_AUTO, "view_vehicle_train", 250, 134,
02295   WC_VEHICLE_VIEW, WC_NONE,
02296   0,
02297   _nested_vehicle_view_widgets, lengthof(_nested_vehicle_view_widgets)
02298 );
02299 
02300 
02301 /* Just to make sure, nobody has changed the vehicle type constants, as we are
02302    using them for array indexing in a number of places here. */
02303 assert_compile(VEH_TRAIN == 0);
02304 assert_compile(VEH_ROAD == 1);
02305 assert_compile(VEH_SHIP == 2);
02306 assert_compile(VEH_AIRCRAFT == 3);
02307 
02309 static const ZoomLevel _vehicle_view_zoom_levels[] = {
02310   ZOOM_LVL_TRAIN,
02311   ZOOM_LVL_ROADVEH,
02312   ZOOM_LVL_SHIP,
02313   ZOOM_LVL_AIRCRAFT,
02314 };
02315 
02316 /* Constants for geometry of vehicle view viewport */
02317 static const int VV_INITIAL_VIEWPORT_WIDTH = 226;
02318 static const int VV_INITIAL_VIEWPORT_HEIGHT = 84;
02319 static const int VV_INITIAL_VIEWPORT_HEIGHT_TRAIN = 102;
02320 
02322 enum VehicleCommandTranslation {
02323   VCT_CMD_START_STOP = 0,
02324   VCT_CMD_CLONE_VEH,
02325   VCT_CMD_TURN_AROUND,
02326 };
02327 
02329 static const uint32 _vehicle_command_translation_table[][4] = {
02330   { // VCT_CMD_START_STOP
02331     CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_TRAIN),
02332     CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_ROAD_VEHICLE),
02333     CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_SHIP),
02334     CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_AIRCRAFT)
02335   },
02336   { // VCT_CMD_CLONE_VEH
02337     CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_TRAIN),
02338     CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_ROAD_VEHICLE),
02339     CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_SHIP),
02340     CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_AIRCRAFT)
02341   },
02342   { // VCT_CMD_TURN_AROUND
02343     CMD_REVERSE_TRAIN_DIRECTION | CMD_MSG(STR_ERROR_CAN_T_REVERSE_DIRECTION_TRAIN),
02344     CMD_TURN_ROADVEH            | CMD_MSG(STR_ERROR_CAN_T_MAKE_ROAD_VEHICLE_TURN),
02345     0xffffffff, // invalid for ships
02346     0xffffffff  // invalid for aircrafts
02347   },
02348 };
02349 
02357 void CcStartStopVehicle(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
02358 {
02359   if (result.Failed()) return;
02360 
02361   const Vehicle *v = Vehicle::GetIfValid(p1);
02362   if (v == NULL || !v->IsPrimaryVehicle() || v->owner != _local_company) return;
02363 
02364   StringID msg = (v->vehstatus & VS_STOPPED) ? STR_VEHICLE_COMMAND_STOPPED : STR_VEHICLE_COMMAND_STARTED;
02365   Point pt = RemapCoords(v->x_pos, v->y_pos, v->z_pos);
02366   AddTextEffect(msg, pt.x, pt.y, DAY_TICKS, TE_RISING);
02367 }
02368 
02374 void StartStopVehicle(const Vehicle *v, bool texteffect)
02375 {
02376   assert(v->IsPrimaryVehicle());
02377   DoCommandP(v->tile, v->index, 0, _vehicle_command_translation_table[VCT_CMD_START_STOP][v->type], texteffect ? CcStartStopVehicle : NULL);
02378 }
02379 
02381 static bool IsVehicleRefitable(const Vehicle *v)
02382 {
02383   if (!v->IsStoppedInDepot()) return false;
02384 
02385   do {
02386     if (IsEngineRefittable(v->engine_type)) return true;
02387   } while (v->IsGroundVehicle() && (v = v->Next()) != NULL);
02388 
02389   return false;
02390 }
02391 
02393 struct VehicleViewWindow : Window {
02394 private:
02396   enum PlaneSelections {
02397     SEL_DC_GOTO_DEPOT,  
02398     SEL_DC_CLONE,       
02399 
02400     SEL_RT_REFIT,       
02401     SEL_RT_TURN_AROUND, 
02402 
02403     SEL_DC_BASEPLANE = SEL_DC_GOTO_DEPOT, 
02404     SEL_RT_BASEPLANE = SEL_RT_REFIT,      
02405   };
02406 
02411   void SelectPlane(PlaneSelections plane)
02412   {
02413     switch (plane) {
02414       case SEL_DC_GOTO_DEPOT:
02415       case SEL_DC_CLONE:
02416         this->GetWidget<NWidgetStacked>(WID_VV_SELECT_DEPOT_CLONE)->SetDisplayedPlane(plane - SEL_DC_BASEPLANE);
02417         break;
02418 
02419       case SEL_RT_REFIT:
02420       case SEL_RT_TURN_AROUND:
02421         this->GetWidget<NWidgetStacked>(WID_VV_SELECT_REFIT_TURN)->SetDisplayedPlane(plane - SEL_RT_BASEPLANE);
02422         break;
02423 
02424       default:
02425         NOT_REACHED();
02426     }
02427   }
02428 
02429 public:
02430   VehicleViewWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
02431   {
02432     this->CreateNestedTree();
02433 
02434     /* Sprites for the 'send to depot' button indexed by vehicle type. */
02435     static const SpriteID vehicle_view_goto_depot_sprites[] = {
02436       SPR_SEND_TRAIN_TODEPOT,
02437       SPR_SEND_ROADVEH_TODEPOT,
02438       SPR_SEND_SHIP_TODEPOT,
02439       SPR_SEND_AIRCRAFT_TODEPOT,
02440     };
02441     const Vehicle *v = Vehicle::Get(window_number);
02442     this->GetWidget<NWidgetCore>(WID_VV_GOTO_DEPOT)->widget_data = vehicle_view_goto_depot_sprites[v->type];
02443 
02444     /* Sprites for the 'clone vehicle' button indexed by vehicle type. */
02445     static const SpriteID vehicle_view_clone_sprites[] = {
02446       SPR_CLONE_TRAIN,
02447       SPR_CLONE_ROADVEH,
02448       SPR_CLONE_SHIP,
02449       SPR_CLONE_AIRCRAFT,
02450     };
02451     this->GetWidget<NWidgetCore>(WID_VV_CLONE)->widget_data = vehicle_view_clone_sprites[v->type];
02452 
02453     switch (v->type) {
02454       case VEH_TRAIN:
02455         this->GetWidget<NWidgetCore>(WID_VV_TURN_AROUND)->tool_tip = STR_VEHICLE_VIEW_TRAIN_REVERSE_TOOLTIP;
02456         break;
02457 
02458       case VEH_ROAD:
02459         break;
02460 
02461       case VEH_SHIP:
02462       case VEH_AIRCRAFT:
02463         this->SelectPlane(SEL_RT_REFIT);
02464         break;
02465 
02466       default: NOT_REACHED();
02467     }
02468     this->FinishInitNested(window_number);
02469     this->owner = v->owner;
02470     this->GetWidget<NWidgetViewport>(WID_VV_VIEWPORT)->InitializeViewport(this, this->window_number | (1 << 31), _vehicle_view_zoom_levels[v->type]);
02471 
02472     this->GetWidget<NWidgetCore>(WID_VV_START_STOP)->tool_tip       = STR_VEHICLE_VIEW_TRAIN_STATE_START_STOP_TOOLTIP + v->type;
02473     this->GetWidget<NWidgetCore>(WID_VV_CENTER_MAIN_VIEW)->tool_tip = STR_VEHICLE_VIEW_TRAIN_LOCATION_TOOLTIP + v->type;
02474     this->GetWidget<NWidgetCore>(WID_VV_REFIT)->tool_tip            = STR_VEHICLE_VIEW_TRAIN_REFIT_TOOLTIP + v->type;
02475     this->GetWidget<NWidgetCore>(WID_VV_GOTO_DEPOT)->tool_tip       = STR_VEHICLE_VIEW_TRAIN_SEND_TO_DEPOT_TOOLTIP + v->type;
02476     this->GetWidget<NWidgetCore>(WID_VV_SHOW_ORDERS)->tool_tip      = STR_VEHICLE_VIEW_TRAIN_ORDERS_TOOLTIP + v->type;
02477     this->GetWidget<NWidgetCore>(WID_VV_SHOW_DETAILS)->tool_tip     = STR_VEHICLE_VIEW_TRAIN_SHOW_DETAILS_TOOLTIP + v->type;
02478     this->GetWidget<NWidgetCore>(WID_VV_CLONE)->tool_tip            = STR_VEHICLE_VIEW_CLONE_TRAIN_INFO + v->type;
02479   }
02480 
02481   ~VehicleViewWindow()
02482   {
02483     DeleteWindowById(WC_VEHICLE_ORDERS, this->window_number, false);
02484     DeleteWindowById(WC_VEHICLE_REFIT, this->window_number, false);
02485     DeleteWindowById(WC_VEHICLE_DETAILS, this->window_number, false);
02486     DeleteWindowById(WC_VEHICLE_TIMETABLE, this->window_number, false);
02487   }
02488 
02489   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
02490   {
02491     const Vehicle *v = Vehicle::Get(this->window_number);
02492     switch (widget) {
02493       case WID_VV_START_STOP:
02494         size->height = max(size->height, max(GetSpriteSize(SPR_FLAG_VEH_STOPPED).height, GetSpriteSize(SPR_FLAG_VEH_RUNNING).height) + WD_IMGBTN_TOP + WD_IMGBTN_BOTTOM);
02495         break;
02496 
02497       case WID_VV_FORCE_PROCEED:
02498         if (v->type != VEH_TRAIN) {
02499           size->height = 0;
02500           size->width = 0;
02501         }
02502         break;
02503 
02504       case WID_VV_VIEWPORT:
02505         size->width = VV_INITIAL_VIEWPORT_WIDTH;
02506         size->height = (v->type == VEH_TRAIN) ? VV_INITIAL_VIEWPORT_HEIGHT_TRAIN : VV_INITIAL_VIEWPORT_HEIGHT;
02507         break;
02508     }
02509   }
02510 
02511   virtual void OnPaint()
02512   {
02513     const Vehicle *v = Vehicle::Get(this->window_number);
02514     bool is_localcompany = v->owner == _local_company;
02515     bool refitable_and_stopped_in_depot = IsVehicleRefitable(v);
02516 
02517     this->SetWidgetDisabledState(WID_VV_GOTO_DEPOT, !is_localcompany);
02518     this->SetWidgetDisabledState(WID_VV_REFIT, !refitable_and_stopped_in_depot || !is_localcompany);
02519     this->SetWidgetDisabledState(WID_VV_CLONE, !is_localcompany);
02520 
02521     if (v->type == VEH_TRAIN) {
02522       this->SetWidgetLoweredState(WID_VV_FORCE_PROCEED, Train::From(v)->force_proceed == TFP_SIGNAL);
02523       this->SetWidgetDisabledState(WID_VV_FORCE_PROCEED, !is_localcompany);
02524       this->SetWidgetDisabledState(WID_VV_TURN_AROUND, !is_localcompany);
02525     }
02526 
02527     this->DrawWidgets();
02528   }
02529 
02530   virtual void SetStringParameters(int widget) const
02531   {
02532     if (widget != WID_VV_CAPTION) return;
02533 
02534     const Vehicle *v = Vehicle::Get(this->window_number);
02535     SetDParam(0, v->index);
02536   }
02537 
02538   virtual void DrawWidget(const Rect &r, int widget) const
02539   {
02540     if (widget != WID_VV_START_STOP) return;
02541 
02542     const Vehicle *v = Vehicle::Get(this->window_number);
02543     StringID str;
02544     if (v->vehstatus & VS_CRASHED) {
02545       str = STR_VEHICLE_STATUS_CRASHED;
02546     } else if (v->type != VEH_AIRCRAFT && v->breakdown_ctr == 1) { // check for aircraft necessary?
02547       str = STR_VEHICLE_STATUS_BROKEN_DOWN;
02548     } else if (v->vehstatus & VS_STOPPED) {
02549       if (v->type == VEH_TRAIN) {
02550         if (v->cur_speed == 0) {
02551           if (Train::From(v)->gcache.cached_power == 0) {
02552             str = STR_VEHICLE_STATUS_TRAIN_NO_POWER;
02553           } else {
02554             str = STR_VEHICLE_STATUS_STOPPED;
02555           }
02556         } else {
02557           SetDParam(0, v->GetDisplaySpeed());
02558           str = STR_VEHICLE_STATUS_TRAIN_STOPPING_VEL;
02559         }
02560       } else { // no train
02561         str = STR_VEHICLE_STATUS_STOPPED;
02562       }
02563     } else if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_TRAIN_STUCK) && !v->current_order.IsType(OT_LOADING)) {
02564       str = STR_VEHICLE_STATUS_TRAIN_STUCK;
02565     } else if (v->type == VEH_AIRCRAFT && HasBit(Aircraft::From(v)->flags, VAF_DEST_TOO_FAR) && !v->current_order.IsType(OT_LOADING)) {
02566       str = STR_VEHICLE_STATUS_AIRCRAFT_TOO_FAR;
02567     } else { // vehicle is in a "normal" state, show current order
02568       switch (v->current_order.GetType()) {
02569         case OT_GOTO_STATION: {
02570           SetDParam(0, v->current_order.GetDestination());
02571           SetDParam(1, v->GetDisplaySpeed());
02572           str = STR_VEHICLE_STATUS_HEADING_FOR_STATION_VEL;
02573           break;
02574         }
02575 
02576         case OT_GOTO_DEPOT: {
02577           SetDParam(0, v->type);
02578           SetDParam(1, v->current_order.GetDestination());
02579           SetDParam(2, v->GetDisplaySpeed());
02580           if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
02581             /* This case *only* happens when multiple nearest depot orders
02582              * follow each other (including an order list only one order: a
02583              * nearest depot order) and there are no reachable depots.
02584              * It is primarily to guard for the case that there is no
02585              * depot with index 0, which would be used as fallback for
02586              * evaluating the string in the status bar. */
02587             str = STR_EMPTY;
02588           } else if (v->current_order.GetDepotActionType() & ODATFB_HALT) {
02589             str = STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_VEL;
02590           } else {
02591             str = STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_SERVICE_VEL;
02592           }
02593           break;
02594         }
02595 
02596         case OT_LOADING:
02597           str = STR_VEHICLE_STATUS_LOADING_UNLOADING;
02598           break;
02599 
02600         case OT_GOTO_WAYPOINT: {
02601           assert(v->type == VEH_TRAIN || v->type == VEH_SHIP);
02602           SetDParam(0, v->current_order.GetDestination());
02603           str = STR_VEHICLE_STATUS_HEADING_FOR_WAYPOINT_VEL;
02604           SetDParam(1, v->GetDisplaySpeed());
02605           break;
02606         }
02607 
02608         case OT_LEAVESTATION:
02609           if (v->type != VEH_AIRCRAFT) {
02610             str = STR_VEHICLE_STATUS_LEAVING;
02611             break;
02612           }
02613           /* FALL THROUGH, if aircraft. Does this even happen? */
02614 
02615         default:
02616           if (v->GetNumManualOrders() == 0) {
02617             str = STR_VEHICLE_STATUS_NO_ORDERS_VEL;
02618             SetDParam(0, v->GetDisplaySpeed());
02619           } else {
02620             str = STR_EMPTY;
02621           }
02622           break;
02623       }
02624     }
02625 
02626     /* Draw the flag plus orders. */
02627     bool rtl = (_current_text_dir == TD_RTL);
02628     uint text_offset = max(GetSpriteSize(SPR_FLAG_VEH_STOPPED).width, GetSpriteSize(SPR_FLAG_VEH_RUNNING).width) + WD_IMGBTN_LEFT + WD_IMGBTN_RIGHT;
02629     int text_left = r.left + (rtl ? (uint)WD_FRAMERECT_LEFT : text_offset);
02630     int text_right = r.right - (rtl ? text_offset : (uint)WD_FRAMERECT_RIGHT);
02631     int image_left = (rtl ? text_right + 1 : r.left) + WD_IMGBTN_LEFT;
02632     int image = ((v->vehstatus & VS_STOPPED) != 0) ? SPR_FLAG_VEH_STOPPED : SPR_FLAG_VEH_RUNNING;
02633     int lowered = this->IsWidgetLowered(WID_VV_START_STOP) ? 1 : 0;
02634     DrawSprite(image, PAL_NONE, image_left + lowered, r.top + WD_IMGBTN_TOP + lowered);
02635     DrawString(text_left + lowered, text_right + lowered, r.top + WD_FRAMERECT_TOP + lowered, str, TC_FROMSTRING, SA_HOR_CENTER);
02636   }
02637 
02638   virtual void OnClick(Point pt, int widget, int click_count)
02639   {
02640     const Vehicle *v = Vehicle::Get(this->window_number);
02641 
02642     switch (widget) {
02643       case WID_VV_START_STOP: // start stop
02644         if (_ctrl_pressed) {
02645           /* Scroll to current order destination */
02646           TileIndex tile = v->current_order.GetLocation(v);
02647           if (tile != INVALID_TILE) ScrollMainWindowToTile(tile);
02648         } else {
02649           /* Start/Stop */
02650           StartStopVehicle(v, false);
02651         }
02652         break;
02653       case WID_VV_CENTER_MAIN_VIEW: {// center main view
02654         const Window *mainwindow = FindWindowById(WC_MAIN_WINDOW, 0);
02655         /* code to allow the main window to 'follow' the vehicle if the ctrl key is pressed */
02656         if (_ctrl_pressed && mainwindow->viewport->zoom <= ZOOM_LVL_OUT_4X) {
02657           mainwindow->viewport->follow_vehicle = v->index;
02658         } else {
02659           ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos);
02660         }
02661         break;
02662       }
02663 
02664       case WID_VV_GOTO_DEPOT: // goto hangar
02665         DoCommandP(v->tile, v->index | (_ctrl_pressed ? DEPOT_SERVICE : 0U), 0, GetCmdSendToDepot(v));
02666         break;
02667       case WID_VV_REFIT: // refit
02668         ShowVehicleRefitWindow(v, INVALID_VEH_ORDER_ID, this);
02669         break;
02670       case WID_VV_SHOW_ORDERS: // show orders
02671         if (_ctrl_pressed) {
02672           ShowTimetableWindow(v);
02673         } else {
02674           ShowOrdersWindow(v);
02675         }
02676         break;
02677       case WID_VV_SHOW_DETAILS: // show details
02678         ShowVehicleDetailsWindow(v);
02679         break;
02680       case WID_VV_CLONE: // clone vehicle
02681         /* Suppress the vehicle GUI when share-cloning.
02682          * There is no point to it except for starting the vehicle.
02683          * For starting the vehicle the player has to open the depot GUI, which is
02684          * most likely already open, but is also visible in the vehicle viewport. */
02685         DoCommandP(v->tile, v->index, _ctrl_pressed ? 1 : 0,
02686                     _vehicle_command_translation_table[VCT_CMD_CLONE_VEH][v->type],
02687                     _ctrl_pressed ? NULL : CcCloneVehicle);
02688         break;
02689       case WID_VV_TURN_AROUND: // turn around
02690         assert(v->IsGroundVehicle());
02691         DoCommandP(v->tile, v->index, 0,
02692                     _vehicle_command_translation_table[VCT_CMD_TURN_AROUND][v->type]);
02693         break;
02694       case WID_VV_FORCE_PROCEED: // force proceed
02695         assert(v->type == VEH_TRAIN);
02696         DoCommandP(v->tile, v->index, 0, CMD_FORCE_TRAIN_PROCEED | CMD_MSG(STR_ERROR_CAN_T_MAKE_TRAIN_PASS_SIGNAL));
02697         break;
02698     }
02699   }
02700 
02701   virtual void OnResize()
02702   {
02703     if (this->viewport != NULL) {
02704       NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_VV_VIEWPORT);
02705       nvp->UpdateViewportCoordinates(this);
02706     }
02707   }
02708 
02709   virtual void OnTick()
02710   {
02711     const Vehicle *v = Vehicle::Get(this->window_number);
02712     bool veh_stopped = v->IsStoppedInDepot();
02713 
02714     /* Widget WID_VV_GOTO_DEPOT must be hidden if the vehicle is already stopped in depot.
02715      * Widget WID_VV_CLONE_VEH should then be shown, since cloning is allowed only while in depot and stopped.
02716      */
02717     PlaneSelections plane = veh_stopped ? SEL_DC_CLONE : SEL_DC_GOTO_DEPOT;
02718     NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VV_SELECT_DEPOT_CLONE); // Selection widget 'send to depot' / 'clone'.
02719     if (nwi->shown_plane + SEL_DC_BASEPLANE != plane) {
02720       this->SelectPlane(plane);
02721       this->SetWidgetDirty(WID_VV_SELECT_DEPOT_CLONE);
02722     }
02723     /* The same system applies to widget WID_VV_REFIT_VEH and VVW_WIDGET_TURN_AROUND.*/
02724     if (v->IsGroundVehicle()) {
02725       PlaneSelections plane = veh_stopped ? SEL_RT_REFIT : SEL_RT_TURN_AROUND;
02726       NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VV_SELECT_REFIT_TURN);
02727       if (nwi->shown_plane + SEL_RT_BASEPLANE != plane) {
02728         this->SelectPlane(plane);
02729         this->SetWidgetDirty(WID_VV_SELECT_REFIT_TURN);
02730       }
02731     }
02732   }
02733 
02739   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
02740   {
02741     if (data == VIWD_AUTOREPLACE) {
02742       /* Autoreplace replaced the vehicle.
02743        * Nothing to do for this window. */
02744       return;
02745     }
02746   }
02747 
02748   virtual bool IsNewGRFInspectable() const
02749   {
02750     return ::IsNewGRFInspectable(GetGrfSpecFeature(Vehicle::Get(this->window_number)->type), this->window_number);
02751   }
02752 
02753   virtual void ShowNewGRFInspectWindow() const
02754   {
02755 		::ShowNewGRFInspectWindow(GetGrfSpecFeature(Vehicle::Get(this->window_number)->type), this->window_number);
02756   }
02757 };
02758 
02759 
02761 void ShowVehicleViewWindow(const Vehicle *v)
02762 {
02763   AllocateWindowDescFront<VehicleViewWindow>((v->type == VEH_TRAIN) ? &_train_view_desc : &_vehicle_view_desc, v->index);
02764 }
02765 
02771 bool VehicleClicked(const Vehicle *v)
02772 {
02773   assert(v != NULL);
02774   if (!(_thd.place_mode & HT_VEHICLE)) return false;
02775 
02776   v = v->First();
02777   if (!v->IsPrimaryVehicle()) return false;
02778 
02779   return _thd.GetCallbackWnd()->OnVehicleSelect(v);
02780 }
02781 
02782 void StopGlobalFollowVehicle(const Vehicle *v)
02783 {
02784   Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
02785   if (w != NULL && w->viewport->follow_vehicle == v->index) {
02786     ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos, true); // lock the main view on the vehicle's last position
02787     w->viewport->follow_vehicle = INVALID_VEHICLE;
02788   }
02789 }
02790 
02791 
02799 void CcBuildPrimaryVehicle(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
02800 {
02801   if (result.Failed()) return;
02802 
02803   const Vehicle *v = Vehicle::Get(_new_vehicle_id);
02804   ShowVehicleViewWindow(v);
02805 }
02806 
02812 int GetVehicleWidth(Vehicle *v, EngineImageType image_type)
02813 {
02814   int vehicle_width = 0;
02815 
02816   switch (v->type) {
02817     case VEH_TRAIN:
02818       for (const Train *u = Train::From(v); u != NULL; u = u->Next()) {
02819         vehicle_width += u->GetDisplayImageWidth();
02820       }
02821       break;
02822 
02823     case VEH_ROAD:
02824       for (const RoadVehicle *u = RoadVehicle::From(v); u != NULL; u = u->Next()) {
02825         vehicle_width += u->GetDisplayImageWidth();
02826       }
02827       break;
02828 
02829     default:
02830       bool rtl = _current_text_dir == TD_RTL;
02831       SpriteID sprite = v->GetImage(rtl ? DIR_E : DIR_W, image_type);
02832       const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
02833       vehicle_width = UnScaleByZoom(real_sprite->width, ZOOM_LVL_GUI);
02834 
02835       break;
02836   }
02837 
02838   return vehicle_width;
02839 }