vehicle_gui.cpp

Go to the documentation of this file.
00001 /* $Id$ */
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->push_back(new DropDownListStringItem(STR_VEHICLE_LIST_REPLACE_VEHICLES, ADI_REPLACE, false));
00160   list->push_back(new DropDownListStringItem(STR_VEHICLE_LIST_SEND_FOR_SERVICING, ADI_SERVICE, false));
00161   list->push_back(new DropDownListStringItem(this->vehicle_depot_name[this->vli.vtype], ADI_DEPOT, false));
00162 
00163   if (show_group) {
00164     list->push_back(new DropDownListStringItem(STR_GROUP_ADD_SHARED_VEHICLE, ADI_ADD_SHARED, false));
00165     list->push_back(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     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     this->GetWidget<NWidgetCore>(WID_VR_MATRIX)->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
00974   }
00975 };
00976 
00977 static const NWidgetPart _nested_vehicle_refit_widgets[] = {
00978   NWidget(NWID_HORIZONTAL),
00979     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
00980     NWidget(WWT_CAPTION, COLOUR_GREY, WID_VR_CAPTION), SetDataTip(STR_REFIT_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00981     NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
00982   EndContainer(),
00983   /* Vehicle display + scrollbar. */
00984   NWidget(NWID_VERTICAL),
00985     NWidget(WWT_PANEL, COLOUR_GREY, WID_VR_VEHICLE_PANEL_DISPLAY), SetMinimalSize(228, 14), SetResize(1, 0), SetScrollbar(WID_VR_HSCROLLBAR), EndContainer(),
00986     NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VR_SHOW_HSCROLLBAR),
00987       NWidget(NWID_HSCROLLBAR, COLOUR_GREY, WID_VR_HSCROLLBAR),
00988     EndContainer(),
00989   EndContainer(),
00990   NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_VR_SELECT_HEADER), SetDataTip(STR_REFIT_TITLE, STR_NULL), SetResize(1, 0),
00991   /* Matrix + scrollbar. */
00992   NWidget(NWID_HORIZONTAL),
00993     NWidget(WWT_MATRIX, COLOUR_GREY, WID_VR_MATRIX), SetMinimalSize(228, 112), SetResize(1, 14), SetFill(1, 1), SetDataTip(0x801, STR_NULL), SetScrollbar(WID_VR_SCROLLBAR),
00994     NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VR_SCROLLBAR),
00995   EndContainer(),
00996   NWidget(WWT_PANEL, COLOUR_GREY, WID_VR_INFO), SetMinimalTextLines(2, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM), SetResize(1, 0), EndContainer(),
00997   NWidget(NWID_HORIZONTAL),
00998     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VR_REFIT), SetFill(1, 0), SetResize(1, 0),
00999     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
01000   EndContainer(),
01001 };
01002 
01003 static WindowDesc _vehicle_refit_desc(
01004   WDP_AUTO, "view_vehicle_refit", 240, 174,
01005   WC_VEHICLE_REFIT, WC_VEHICLE_VIEW,
01006   WDF_CONSTRUCTION,
01007   _nested_vehicle_refit_widgets, lengthof(_nested_vehicle_refit_widgets)
01008 );
01009 
01017 void ShowVehicleRefitWindow(const Vehicle *v, VehicleOrderID order, Window *parent, bool auto_refit)
01018 {
01019   DeleteWindowById(WC_VEHICLE_REFIT, v->index);
01020   RefitWindow *w = new RefitWindow(&_vehicle_refit_desc, v, order, auto_refit);
01021   w->parent = parent;
01022 }
01023 
01025 uint ShowRefitOptionsList(int left, int right, int y, EngineID engine)
01026 {
01027   /* List of cargo types of this engine */
01028   uint32 cmask = GetUnionOfArticulatedRefitMasks(engine, false);
01029   /* List of cargo types available in this climate */
01030   uint32 lmask = _cargo_mask;
01031 
01032   /* Draw nothing if the engine is not refittable */
01033   if (HasAtMostOneBit(cmask)) return y;
01034 
01035   if (cmask == lmask) {
01036     /* Engine can be refitted to all types in this climate */
01037     SetDParam(0, STR_PURCHASE_INFO_ALL_TYPES);
01038   } else {
01039     /* Check if we are able to refit to more cargo types and unable to. If
01040      * so, invert the cargo types to list those that we can't refit to. */
01041     if (CountBits(cmask ^ lmask) < CountBits(cmask) && CountBits(cmask ^ lmask) <= 7) {
01042       cmask ^= lmask;
01043       SetDParam(0, STR_PURCHASE_INFO_ALL_BUT);
01044     } else {
01045       SetDParam(0, STR_JUST_CARGO_LIST);
01046     }
01047     SetDParam(1, cmask);
01048   }
01049 
01050   return DrawStringMultiLine(left, right, y, INT32_MAX, STR_PURCHASE_INFO_REFITTABLE_TO);
01051 }
01052 
01054 StringID GetCargoSubtypeText(const Vehicle *v)
01055 {
01056   if (HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) {
01057     uint16 cb = GetVehicleCallback(CBID_VEHICLE_CARGO_SUFFIX, 0, 0, v->engine_type, v);
01058     if (cb != CALLBACK_FAILED) {
01059       if (cb > 0x400) ErrorUnknownCallbackResult(v->GetGRFID(), CBID_VEHICLE_CARGO_SUFFIX, cb);
01060       if (cb >= 0x400 || (v->GetGRF()->grf_version < 8 && cb == 0xFF)) cb = CALLBACK_FAILED;
01061     }
01062     if (cb != CALLBACK_FAILED) {
01063       return GetGRFStringID(v->GetGRFID(), 0xD000 + cb);
01064     }
01065   }
01066   return STR_EMPTY;
01067 }
01068 
01070 static int CDECL VehicleNumberSorter(const Vehicle * const *a, const Vehicle * const *b)
01071 {
01072   return (*a)->unitnumber - (*b)->unitnumber;
01073 }
01074 
01076 static int CDECL VehicleNameSorter(const Vehicle * const *a, const Vehicle * const *b)
01077 {
01078   static char last_name[2][64];
01079 
01080   if (*a != _last_vehicle[0]) {
01081     _last_vehicle[0] = *a;
01082     SetDParam(0, (*a)->index);
01083     GetString(last_name[0], STR_VEHICLE_NAME, lastof(last_name[0]));
01084   }
01085 
01086   if (*b != _last_vehicle[1]) {
01087     _last_vehicle[1] = *b;
01088     SetDParam(0, (*b)->index);
01089     GetString(last_name[1], STR_VEHICLE_NAME, lastof(last_name[1]));
01090   }
01091 
01092   int r = strnatcmp(last_name[0], last_name[1]); // Sort by name (natural sorting).
01093   return (r != 0) ? r : VehicleNumberSorter(a, b);
01094 }
01095 
01097 static int CDECL VehicleAgeSorter(const Vehicle * const *a, const Vehicle * const *b)
01098 {
01099   int r = (*a)->age - (*b)->age;
01100   return (r != 0) ? r : VehicleNumberSorter(a, b);
01101 }
01102 
01104 static int CDECL VehicleProfitThisYearSorter(const Vehicle * const *a, const Vehicle * const *b)
01105 {
01106   int r = ClampToI32((*a)->GetDisplayProfitThisYear() - (*b)->GetDisplayProfitThisYear());
01107   return (r != 0) ? r : VehicleNumberSorter(a, b);
01108 }
01109 
01111 static int CDECL VehicleProfitLastYearSorter(const Vehicle * const *a, const Vehicle * const *b)
01112 {
01113   int r = ClampToI32((*a)->GetDisplayProfitLastYear() - (*b)->GetDisplayProfitLastYear());
01114   return (r != 0) ? r : VehicleNumberSorter(a, b);
01115 }
01116 
01118 static int CDECL VehicleCargoSorter(const Vehicle * const *a, const Vehicle * const *b)
01119 {
01120   const Vehicle *v;
01121   CargoArray diff;
01122 
01123   /* Append the cargo of the connected waggons */
01124   for (v = *a; v != NULL; v = v->Next()) diff[v->cargo_type] += v->cargo_cap;
01125   for (v = *b; v != NULL; v = v->Next()) diff[v->cargo_type] -= v->cargo_cap;
01126 
01127   int r = 0;
01128   for (CargoID i = 0; i < NUM_CARGO; i++) {
01129     r = diff[i];
01130     if (r != 0) break;
01131   }
01132 
01133   return (r != 0) ? r : VehicleNumberSorter(a, b);
01134 }
01135 
01137 static int CDECL VehicleReliabilitySorter(const Vehicle * const *a, const Vehicle * const *b)
01138 {
01139   int r = (*a)->reliability - (*b)->reliability;
01140   return (r != 0) ? r : VehicleNumberSorter(a, b);
01141 }
01142 
01144 static int CDECL VehicleMaxSpeedSorter(const Vehicle * const *a, const Vehicle * const *b)
01145 {
01146   int r = (*a)->vcache.cached_max_speed - (*b)->vcache.cached_max_speed;
01147   return (r != 0) ? r : VehicleNumberSorter(a, b);
01148 }
01149 
01151 static int CDECL VehicleModelSorter(const Vehicle * const *a, const Vehicle * const *b)
01152 {
01153   int r = (*a)->engine_type - (*b)->engine_type;
01154   return (r != 0) ? r : VehicleNumberSorter(a, b);
01155 }
01156 
01158 static int CDECL VehicleValueSorter(const Vehicle * const *a, const Vehicle * const *b)
01159 {
01160   const Vehicle *u;
01161   Money diff = 0;
01162 
01163   for (u = *a; u != NULL; u = u->Next()) diff += u->value;
01164   for (u = *b; u != NULL; u = u->Next()) diff -= u->value;
01165 
01166   int r = ClampToI32(diff);
01167   return (r != 0) ? r : VehicleNumberSorter(a, b);
01168 }
01169 
01171 static int CDECL VehicleLengthSorter(const Vehicle * const *a, const Vehicle * const *b)
01172 {
01173   int r = (*a)->GetGroundVehicleCache()->cached_total_length - (*b)->GetGroundVehicleCache()->cached_total_length;
01174   return (r != 0) ? r : VehicleNumberSorter(a, b);
01175 }
01176 
01178 static int CDECL VehicleTimeToLiveSorter(const Vehicle * const *a, const Vehicle * const *b)
01179 {
01180   int r = ClampToI32(((*a)->max_age - (*a)->age) - ((*b)->max_age - (*b)->age));
01181   return (r != 0) ? r : VehicleNumberSorter(a, b);
01182 }
01183 
01185 static int CDECL VehicleTimetableDelaySorter(const Vehicle * const *a, const Vehicle * const *b)
01186 {
01187   int r = (*a)->lateness_counter - (*b)->lateness_counter;
01188   return (r != 0) ? r : VehicleNumberSorter(a, b);
01189 }
01190 
01191 void InitializeGUI()
01192 {
01193   MemSetT(&_sorting, 0);
01194 }
01195 
01202 static inline void ChangeVehicleWindow(WindowClass window_class, VehicleID from_index, VehicleID to_index)
01203 {
01204   Window *w = FindWindowById(window_class, from_index);
01205   if (w != NULL) {
01206     /* Update window_number */
01207     w->window_number = to_index;
01208     if (w->viewport != NULL) w->viewport->follow_vehicle = to_index;
01209 
01210     /* Update vehicle drag data */
01211     if (_thd.window_class == window_class && _thd.window_number == (WindowNumber)from_index) {
01212       _thd.window_number = to_index;
01213     }
01214 
01215     /* Notify the window. */
01216     w->InvalidateData(VIWD_AUTOREPLACE, false);
01217   }
01218 }
01219 
01225 void ChangeVehicleViewWindow(VehicleID from_index, VehicleID to_index)
01226 {
01227   ChangeVehicleWindow(WC_VEHICLE_VIEW,      from_index, to_index);
01228   ChangeVehicleWindow(WC_VEHICLE_ORDERS,    from_index, to_index);
01229   ChangeVehicleWindow(WC_VEHICLE_REFIT,     from_index, to_index);
01230   ChangeVehicleWindow(WC_VEHICLE_DETAILS,   from_index, to_index);
01231   ChangeVehicleWindow(WC_VEHICLE_TIMETABLE, from_index, to_index);
01232 }
01233 
01234 static const NWidgetPart _nested_vehicle_list[] = {
01235   NWidget(NWID_HORIZONTAL),
01236     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
01237     NWidget(WWT_CAPTION, COLOUR_GREY, WID_VL_CAPTION),
01238     NWidget(WWT_SHADEBOX, COLOUR_GREY),
01239     NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
01240     NWidget(WWT_STICKYBOX, COLOUR_GREY),
01241   EndContainer(),
01242 
01243   NWidget(NWID_HORIZONTAL),
01244     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VL_SORT_ORDER), SetMinimalSize(81, 12), SetFill(0, 1), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
01245     NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_SORT_BY_PULLDOWN), SetMinimalSize(167, 12), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
01246     NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(12, 12), SetFill(1, 1), SetResize(1, 0),
01247     EndContainer(),
01248   EndContainer(),
01249 
01250   NWidget(NWID_HORIZONTAL),
01251     NWidget(WWT_MATRIX, COLOUR_GREY, WID_VL_LIST), SetMinimalSize(248, 0), SetFill(1, 0), SetResize(1, 1), SetScrollbar(WID_VL_SCROLLBAR),
01252     NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VL_SCROLLBAR),
01253   EndContainer(),
01254 
01255   NWidget(NWID_HORIZONTAL),
01256     NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VL_HIDE_BUTTONS),
01257       NWidget(NWID_HORIZONTAL),
01258         NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VL_AVAILABLE_VEHICLES), SetMinimalSize(106, 12), SetFill(0, 1),
01259                 SetDataTip(STR_BLACK_STRING, STR_VEHICLE_LIST_AVAILABLE_ENGINES_TOOLTIP),
01260         NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(0, 12), SetResize(1, 0), SetFill(1, 1), EndContainer(),
01261         NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_MANAGE_VEHICLES_DROPDOWN), SetMinimalSize(118, 12), SetFill(0, 1),
01262                 SetDataTip(STR_VEHICLE_LIST_MANAGE_LIST, STR_VEHICLE_LIST_MANAGE_LIST_TOOLTIP),
01263         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VL_STOP_ALL), SetMinimalSize(12, 12), SetFill(0, 1),
01264                 SetDataTip(SPR_FLAG_VEH_STOPPED, STR_VEHICLE_LIST_MASS_STOP_LIST_TOOLTIP),
01265         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VL_START_ALL), SetMinimalSize(12, 12), SetFill(0, 1),
01266                 SetDataTip(SPR_FLAG_VEH_RUNNING, STR_VEHICLE_LIST_MASS_START_LIST_TOOLTIP),
01267       EndContainer(),
01268       /* Widget to be shown for other companies hiding the previous 5 widgets. */
01269       NWidget(WWT_PANEL, COLOUR_GREY), SetFill(1, 1), SetResize(1, 0), EndContainer(),
01270     EndContainer(),
01271     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
01272   EndContainer(),
01273 };
01274 
01275 static void DrawSmallOrderList(const Vehicle *v, int left, int right, int y, VehicleOrderID start = 0)
01276 {
01277   const Order *order = v->GetOrder(start);
01278   if (order == NULL) return;
01279 
01280   int i = 0;
01281   VehicleOrderID oid = start;
01282 
01283   do {
01284     if (oid == v->cur_real_order_index) DrawString(left, right, y, STR_TINY_RIGHT_ARROW, TC_BLACK);
01285 
01286     if (order->IsType(OT_GOTO_STATION)) {
01287       SetDParam(0, order->GetDestination());
01288       DrawString(left + 6, right - 6, y, STR_TINY_BLACK_STATION);
01289 
01290       y += FONT_HEIGHT_SMALL;
01291       if (++i == 4) break;
01292     }
01293 
01294     oid++;
01295     order = order->next;
01296     if (order == NULL) {
01297       order = v->orders.list->GetFirstOrder();
01298       oid = 0;
01299     }
01300   } while (oid != start);
01301 }
01302 
01312 void DrawVehicleImage(const Vehicle *v, int left, int right, int y, VehicleID selection, EngineImageType image_type, int skip)
01313 {
01314   switch (v->type) {
01315     case VEH_TRAIN:    DrawTrainImage(Train::From(v), left, right, y, selection, image_type, skip); break;
01316     case VEH_ROAD:     DrawRoadVehImage(v, left, right, y, selection, image_type, skip);  break;
01317     case VEH_SHIP:     DrawShipImage(v, left, right, y, selection, image_type);     break;
01318     case VEH_AIRCRAFT: DrawAircraftImage(v, left, right, y, selection, image_type); break;
01319     default: NOT_REACHED();
01320   }
01321 }
01322 
01329 uint GetVehicleListHeight(VehicleType type, uint divisor)
01330 {
01331   /* Name + vehicle + profit */
01332   uint base = GetVehicleHeight(type) + 2 * FONT_HEIGHT_SMALL;
01333   /* Drawing of the 4 small orders + profit*/
01334   if (type >= VEH_SHIP) base = max(base, 5U * FONT_HEIGHT_SMALL);
01335 
01336   if (divisor == 1) return base;
01337 
01338   /* Make sure the height is dividable by divisor */
01339   uint rem = base % divisor;
01340   return base + (rem == 0 ? 0 : divisor - rem);
01341 }
01342 
01349 void BaseVehicleListWindow::DrawVehicleListItems(VehicleID selected_vehicle, int line_height, const Rect &r) const
01350 {
01351   int left = r.left + WD_MATRIX_LEFT;
01352   int right = r.right - WD_MATRIX_RIGHT;
01353   int width = right - left;
01354   bool rtl = _current_text_dir == TD_RTL;
01355 
01356   int text_offset = GetDigitWidth() * this->unitnumber_digits + WD_FRAMERECT_RIGHT;
01357   int text_left  = left  + (rtl ?           0 : text_offset);
01358   int text_right = right - (rtl ? text_offset :           0);
01359 
01360   bool show_orderlist = this->vli.vtype >= VEH_SHIP;
01361   int orderlist_left  = left  + (rtl ? 0 : max(100 + text_offset, width / 2));
01362   int orderlist_right = right - (rtl ? max(100 + text_offset, width / 2) : 0);
01363 
01364   int image_left  = (rtl && show_orderlist) ? orderlist_right : text_left;
01365   int image_right = (!rtl && show_orderlist) ? orderlist_left : text_right;
01366 
01367   int vehicle_button_x = rtl ? right - GetSpriteSize(SPR_PROFIT_LOT).width : left;
01368 
01369   int y = r.top;
01370   uint max = min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->vehicles.Length());
01371   for (uint i = this->vscroll->GetPosition(); i < max; ++i) {
01372     const Vehicle *v = this->vehicles[i];
01373     StringID str;
01374 
01375     SetDParam(0, v->GetDisplayProfitThisYear());
01376     SetDParam(1, v->GetDisplayProfitLastYear());
01377 
01378     DrawVehicleImage(v, image_left, image_right, y + FONT_HEIGHT_SMALL - 1, selected_vehicle, EIT_IN_LIST, 0);
01379     DrawString(text_left, text_right, y + line_height - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1, STR_VEHICLE_LIST_PROFIT_THIS_YEAR_LAST_YEAR);
01380 
01381     if (v->name != NULL) {
01382       /* The vehicle got a name so we will print it */
01383       SetDParam(0, v->index);
01384       DrawString(text_left, text_right, y, STR_TINY_BLACK_VEHICLE);
01385     } else if (v->group_id != DEFAULT_GROUP) {
01386       /* The vehicle has no name, but is member of a group, so print group name */
01387       SetDParam(0, v->group_id);
01388       DrawString(text_left, text_right, y, STR_TINY_GROUP, TC_BLACK);
01389     }
01390 
01391     if (show_orderlist) DrawSmallOrderList(v, orderlist_left, orderlist_right, y, v->cur_real_order_index);
01392 
01393     if (v->IsChainInDepot()) {
01394       str = STR_BLUE_COMMA;
01395     } else {
01396       str = (v->age > v->max_age - DAYS_IN_LEAP_YEAR) ? STR_RED_COMMA : STR_BLACK_COMMA;
01397     }
01398 
01399     SetDParam(0, v->unitnumber);
01400     DrawString(left, right, y + 2, str);
01401 
01402     DrawVehicleProfitButton(v, vehicle_button_x, y + FONT_HEIGHT_NORMAL + 3);
01403 
01404     y += line_height;
01405   }
01406 }
01407 
01417 struct VehicleListWindow : public BaseVehicleListWindow {
01418 private:
01420   enum ButtonPlanes {
01421     BP_SHOW_BUTTONS, 
01422     BP_HIDE_BUTTONS, 
01423   };
01424 
01425 public:
01426   VehicleListWindow(WindowDesc *desc, WindowNumber window_number) : BaseVehicleListWindow(desc, window_number)
01427   {
01428     /* Set up sorting. Make the window-specific _sorting variable
01429      * point to the correct global _sorting struct so we are freed
01430      * from having conditionals during window operation */
01431     switch (this->vli.vtype) {
01432       case VEH_TRAIN:    this->sorting = &_sorting.train; break;
01433       case VEH_ROAD:     this->sorting = &_sorting.roadveh; break;
01434       case VEH_SHIP:     this->sorting = &_sorting.ship; break;
01435       case VEH_AIRCRAFT: this->sorting = &_sorting.aircraft; break;
01436       default: NOT_REACHED();
01437     }
01438 
01439     this->CreateNestedTree();
01440 
01441     this->vscroll = this->GetScrollbar(WID_VL_SCROLLBAR);
01442 
01443     this->vehicles.SetListing(*this->sorting);
01444     this->vehicles.ForceRebuild();
01445     this->vehicles.NeedResort();
01446     this->BuildVehicleList();
01447     this->SortVehicleList();
01448 
01449     /* Set up the window widgets */
01450     this->GetWidget<NWidgetCore>(WID_VL_LIST)->tool_tip = STR_VEHICLE_LIST_TRAIN_LIST_TOOLTIP + this->vli.vtype;
01451 
01452     if (this->vli.type == VL_SHARED_ORDERS) {
01453       this->GetWidget<NWidgetCore>(WID_VL_CAPTION)->widget_data = STR_VEHICLE_LIST_SHARED_ORDERS_LIST_CAPTION;
01454     } else {
01455       this->GetWidget<NWidgetCore>(WID_VL_CAPTION)->widget_data = STR_VEHICLE_LIST_TRAIN_CAPTION + this->vli.vtype;
01456     }
01457 
01458     this->FinishInitNested(window_number);
01459     if (this->vli.company != OWNER_NONE) this->owner = this->vli.company;
01460 
01461     if (this->vli.vtype == VEH_TRAIN) ResizeWindow(this, 65, 0);
01462   }
01463 
01464   ~VehicleListWindow()
01465   {
01466     *this->sorting = this->vehicles.GetListing();
01467   }
01468 
01469   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01470   {
01471     switch (widget) {
01472       case WID_VL_LIST:
01473         resize->height = GetVehicleListHeight(this->vli.vtype, 1);
01474 
01475         switch (this->vli.vtype) {
01476           case VEH_TRAIN:
01477           case VEH_ROAD:
01478             size->height = 6 * resize->height;
01479             break;
01480           case VEH_SHIP:
01481           case VEH_AIRCRAFT:
01482             size->height = 4 * resize->height;
01483             break;
01484           default: NOT_REACHED();
01485         }
01486         break;
01487 
01488       case WID_VL_SORT_ORDER: {
01489         Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
01490         d.width += padding.width + WD_SORTBUTTON_ARROW_WIDTH * 2; // Doubled since the string is centred and it also looks better.
01491         d.height += padding.height;
01492         *size = maxdim(*size, d);
01493         break;
01494       }
01495 
01496       case WID_VL_MANAGE_VEHICLES_DROPDOWN: {
01497         Dimension d = this->GetActionDropdownSize(this->vli.type == VL_STANDARD, false);
01498         d.height += padding.height;
01499         d.width  += padding.width;
01500         *size = maxdim(*size, d);
01501         break;
01502       }
01503     }
01504   }
01505 
01506   virtual void SetStringParameters(int widget) const
01507   {
01508     switch (widget) {
01509       case WID_VL_AVAILABLE_VEHICLES:
01510         SetDParam(0, STR_VEHICLE_LIST_AVAILABLE_TRAINS + this->vli.vtype);
01511         break;
01512 
01513       case WID_VL_CAPTION: {
01514         switch (this->vli.type) {
01515           case VL_SHARED_ORDERS: // Shared Orders
01516             if (this->vehicles.Length() == 0) {
01517               /* We can't open this window without vehicles using this order
01518                * and we should close the window when deleting the order. */
01519               NOT_REACHED();
01520             }
01521             SetDParam(0, this->vscroll->GetCount());
01522             break;
01523 
01524           case VL_STANDARD: // Company Name
01525             SetDParam(0, STR_COMPANY_NAME);
01526             SetDParam(1, this->vli.index);
01527             SetDParam(3, this->vscroll->GetCount());
01528             break;
01529 
01530           case VL_STATION_LIST: // Station/Waypoint Name
01531             SetDParam(0, Station::IsExpected(BaseStation::Get(this->vli.index)) ? STR_STATION_NAME : STR_WAYPOINT_NAME);
01532             SetDParam(1, this->vli.index);
01533             SetDParam(3, this->vscroll->GetCount());
01534             break;
01535 
01536           case VL_DEPOT_LIST:
01537             SetDParam(0, STR_DEPOT_CAPTION);
01538             SetDParam(1, this->vli.vtype);
01539             SetDParam(2, this->vli.index);
01540             SetDParam(3, this->vscroll->GetCount());
01541             break;
01542           default: NOT_REACHED();
01543         }
01544         break;
01545       }
01546     }
01547   }
01548 
01549   virtual void DrawWidget(const Rect &r, int widget) const
01550   {
01551     switch (widget) {
01552       case WID_VL_SORT_ORDER:
01553         /* draw arrow pointing up/down for ascending/descending sorting */
01554         this->DrawSortButtonState(widget, this->vehicles.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
01555         break;
01556 
01557       case WID_VL_LIST:
01558         this->DrawVehicleListItems(INVALID_VEHICLE, this->resize.step_height, r);
01559         break;
01560     }
01561   }
01562 
01563   virtual void OnPaint()
01564   {
01565     this->BuildVehicleList();
01566     this->SortVehicleList();
01567 
01568     if (this->vehicles.Length() == 0 && this->IsWidgetLowered(WID_VL_MANAGE_VEHICLES_DROPDOWN)) {
01569       HideDropDownMenu(this);
01570     }
01571 
01572     /* Hide the widgets that we will not use in this window
01573      * Some windows contains actions only fit for the owner */
01574     int plane_to_show = (this->owner == _local_company) ? BP_SHOW_BUTTONS : BP_HIDE_BUTTONS;
01575     NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VL_HIDE_BUTTONS);
01576     if (plane_to_show != nwi->shown_plane) {
01577       nwi->SetDisplayedPlane(plane_to_show);
01578       nwi->SetDirty(this);
01579     }
01580     if (this->owner == _local_company) {
01581       this->SetWidgetDisabledState(WID_VL_AVAILABLE_VEHICLES, this->vli.type != VL_STANDARD);
01582       this->SetWidgetsDisabledState(this->vehicles.Length() == 0,
01583         WID_VL_MANAGE_VEHICLES_DROPDOWN,
01584         WID_VL_STOP_ALL,
01585         WID_VL_START_ALL,
01586         WIDGET_LIST_END);
01587     }
01588 
01589     /* Set text of sort by dropdown widget. */
01590     this->GetWidget<NWidgetCore>(WID_VL_SORT_BY_PULLDOWN)->widget_data = this->vehicle_sorter_names[this->vehicles.SortType()];
01591 
01592     this->DrawWidgets();
01593   }
01594 
01595   virtual void OnClick(Point pt, int widget, int click_count)
01596   {
01597     switch (widget) {
01598       case WID_VL_SORT_ORDER: // Flip sorting method ascending/descending
01599         this->vehicles.ToggleSortOrder();
01600         this->SetDirty();
01601         break;
01602 
01603       case WID_VL_SORT_BY_PULLDOWN:// Select sorting criteria dropdown menu
01604         ShowDropDownMenu(this, this->vehicle_sorter_names, this->vehicles.SortType(), WID_VL_SORT_BY_PULLDOWN, 0,
01605             (this->vli.vtype == VEH_TRAIN || this->vli.vtype == VEH_ROAD) ? 0 : (1 << 10));
01606         return;
01607 
01608       case WID_VL_LIST: { // Matrix to show vehicles
01609         uint id_v = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_VL_LIST);
01610         if (id_v >= this->vehicles.Length()) return; // click out of list bound
01611 
01612         const Vehicle *v = this->vehicles[id_v];
01613         if (!VehicleClicked(v)) ShowVehicleViewWindow(v);
01614         break;
01615       }
01616 
01617       case WID_VL_AVAILABLE_VEHICLES:
01618         ShowBuildVehicleWindow(INVALID_TILE, this->vli.vtype);
01619         break;
01620 
01621       case WID_VL_MANAGE_VEHICLES_DROPDOWN: {
01622         DropDownList *list = this->BuildActionDropdownList(VehicleListIdentifier(this->window_number).type == VL_STANDARD, false);
01623         ShowDropDownList(this, list, 0, WID_VL_MANAGE_VEHICLES_DROPDOWN);
01624         break;
01625       }
01626 
01627       case WID_VL_STOP_ALL:
01628       case WID_VL_START_ALL:
01629         DoCommandP(0, (1 << 1) | (widget == WID_VL_START_ALL ? (1 << 0) : 0), this->window_number, CMD_MASS_START_STOP);
01630         break;
01631     }
01632   }
01633 
01634   virtual void OnDropdownSelect(int widget, int index)
01635   {
01636     switch (widget) {
01637       case WID_VL_SORT_BY_PULLDOWN:
01638         this->vehicles.SetSortType(index);
01639         break;
01640       case WID_VL_MANAGE_VEHICLES_DROPDOWN:
01641         assert(this->vehicles.Length() != 0);
01642 
01643         switch (index) {
01644           case ADI_REPLACE: // Replace window
01645             ShowReplaceGroupVehicleWindow(ALL_GROUP, this->vli.vtype);
01646             break;
01647           case ADI_SERVICE: // Send for servicing
01648           case ADI_DEPOT: // Send to Depots
01649             DoCommandP(0, DEPOT_MASS_SEND | (index == ADI_SERVICE ? DEPOT_SERVICE : (DepotCommand)0), this->window_number, GetCmdSendToDepot(this->vli.vtype));
01650             break;
01651 
01652           default: NOT_REACHED();
01653         }
01654         break;
01655       default: NOT_REACHED();
01656     }
01657     this->SetDirty();
01658   }
01659 
01660   virtual void OnTick()
01661   {
01662     if (_pause_mode != PM_UNPAUSED) return;
01663     if (this->vehicles.NeedResort()) {
01664       StationID station = (this->vli.type == VL_STATION_LIST) ? this->vli.index : INVALID_STATION;
01665 
01666       DEBUG(misc, 3, "Periodic resort %d list company %d at station %d", this->vli.vtype, this->owner, station);
01667       this->SetDirty();
01668     }
01669   }
01670 
01671   virtual void OnResize()
01672   {
01673     this->vscroll->SetCapacityFromWidget(this, WID_VL_LIST);
01674     this->GetWidget<NWidgetCore>(WID_VL_LIST)->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
01675   }
01676 
01682   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
01683   {
01684     if (!gui_scope && HasBit(data, 31) && this->vli.type == VL_SHARED_ORDERS) {
01685       /* Needs to be done in command-scope, so everything stays valid */
01686       this->vli.index = GB(data, 0, 20);
01687       this->window_number = this->vli.Pack();
01688       this->vehicles.ForceRebuild();
01689       return;
01690     }
01691 
01692     if (data == 0) {
01693       /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
01694       this->vehicles.ForceRebuild();
01695     } else {
01696       this->vehicles.ForceResort();
01697     }
01698   }
01699 };
01700 
01701 static WindowDesc _vehicle_list_desc(
01702   WDP_AUTO, "list_vehicles", 260, 246,
01703   WC_INVALID, WC_NONE,
01704   0,
01705   _nested_vehicle_list, lengthof(_nested_vehicle_list)
01706 );
01707 
01708 static void ShowVehicleListWindowLocal(CompanyID company, VehicleListType vlt, VehicleType vehicle_type, uint16 unique_number)
01709 {
01710   if (!Company::IsValidID(company) && company != OWNER_NONE) return;
01711 
01712   _vehicle_list_desc.cls = GetWindowClassForVehicleType(vehicle_type);
01713   AllocateWindowDescFront<VehicleListWindow>(&_vehicle_list_desc, VehicleListIdentifier(vlt, vehicle_type, company, unique_number).Pack());
01714 }
01715 
01716 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type)
01717 {
01718   /* If _settings_client.gui.advanced_vehicle_list > 1, display the Advanced list
01719    * if _settings_client.gui.advanced_vehicle_list == 1, display Advanced list only for local company
01720    * if _ctrl_pressed, do the opposite action (Advanced list x Normal list)
01721    */
01722 
01723   if ((_settings_client.gui.advanced_vehicle_list > (uint)(company != _local_company)) != _ctrl_pressed) {
01724     ShowCompanyGroup(company, vehicle_type);
01725   } else {
01726     ShowVehicleListWindowLocal(company, VL_STANDARD, vehicle_type, company);
01727   }
01728 }
01729 
01730 void ShowVehicleListWindow(const Vehicle *v)
01731 {
01732   ShowVehicleListWindowLocal(v->owner, VL_SHARED_ORDERS, v->type, v->FirstShared()->index);
01733 }
01734 
01735 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, StationID station)
01736 {
01737   _vehicle_list_desc.flags &= ~WDF_CONSTRUCTION;
01738   ShowVehicleListWindowLocal(company, VL_STATION_LIST, vehicle_type, station);
01739 }
01740 
01741 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, TileIndex depot_tile)
01742 {
01743   uint16 depot_airport_index;
01744 
01745   if (vehicle_type == VEH_AIRCRAFT) {
01746     depot_airport_index = GetStationIndex(depot_tile);
01747   } else {
01748     depot_airport_index = GetDepotIndex(depot_tile);
01749   }
01750   ShowVehicleListWindowLocal(company, VL_DEPOT_LIST, vehicle_type, depot_airport_index);
01751 }
01752 
01753 
01754 /* Unified vehicle GUI - Vehicle Details Window */
01755 
01756 assert_compile(WID_VD_DETAILS_CARGO_CARRIED    == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_CARGO   );
01757 assert_compile(WID_VD_DETAILS_TRAIN_VEHICLES   == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_INFO    );
01758 assert_compile(WID_VD_DETAILS_CAPACITY_OF_EACH == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_CAPACITY);
01759 assert_compile(WID_VD_DETAILS_TOTAL_CARGO      == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_TOTALS  );
01760 
01762 static const NWidgetPart _nested_nontrain_vehicle_details_widgets[] = {
01763   NWidget(NWID_HORIZONTAL),
01764     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
01765     NWidget(WWT_CAPTION, COLOUR_GREY, WID_VD_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
01766     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 */),
01767     NWidget(WWT_SHADEBOX, COLOUR_GREY),
01768     NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
01769     NWidget(WWT_STICKYBOX, COLOUR_GREY),
01770   EndContainer(),
01771   NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_TOP_DETAILS), SetMinimalSize(405, 42), SetResize(1, 0), EndContainer(),
01772   NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_MIDDLE_DETAILS), SetMinimalSize(405, 45), SetResize(1, 0), EndContainer(),
01773   NWidget(NWID_HORIZONTAL),
01774     NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_DECREASE_SERVICING_INTERVAL), SetFill(0, 1),
01775         SetDataTip(AWV_DECREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
01776     NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_INCREASE_SERVICING_INTERVAL), SetFill(0, 1),
01777         SetDataTip(AWV_INCREASE, STR_VEHICLE_DETAILS_INCREASE_SERVICING_INTERVAL_TOOLTIP),
01778     NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VD_SERVICE_INTERVAL_DROPDOWN), SetFill(0, 1),
01779         SetDataTip(STR_EMPTY, STR_SERVICE_INTERVAL_DROPDOWN_TOOLTIP),
01780     NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_SERVICING_INTERVAL), SetFill(1, 1), SetResize(1, 0), EndContainer(),
01781     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
01782   EndContainer(),
01783 };
01784 
01786 static const NWidgetPart _nested_train_vehicle_details_widgets[] = {
01787   NWidget(NWID_HORIZONTAL),
01788     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
01789     NWidget(WWT_CAPTION, COLOUR_GREY, WID_VD_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
01790     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 */),
01791     NWidget(WWT_SHADEBOX, COLOUR_GREY),
01792     NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
01793     NWidget(WWT_STICKYBOX, COLOUR_GREY),
01794   EndContainer(),
01795   NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_TOP_DETAILS), SetResize(1, 0), SetMinimalSize(405, 42), EndContainer(),
01796   NWidget(NWID_HORIZONTAL),
01797     NWidget(WWT_MATRIX, COLOUR_GREY, WID_VD_MATRIX), SetResize(1, 1), SetMinimalSize(393, 45), SetDataTip(0x701, STR_NULL), SetFill(1, 0), SetScrollbar(WID_VD_SCROLLBAR),
01798     NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VD_SCROLLBAR),
01799   EndContainer(),
01800   NWidget(NWID_HORIZONTAL),
01801     NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_DECREASE_SERVICING_INTERVAL), SetFill(0, 1),
01802         SetDataTip(AWV_DECREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
01803     NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_INCREASE_SERVICING_INTERVAL), SetFill(0, 1),
01804         SetDataTip(AWV_INCREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
01805     NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VD_SERVICE_INTERVAL_DROPDOWN), SetFill(0, 1),
01806         SetDataTip(STR_EMPTY, STR_SERVICE_INTERVAL_DROPDOWN_TOOLTIP),
01807     NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_SERVICING_INTERVAL), SetFill(1, 1), SetResize(1, 0), EndContainer(),
01808   EndContainer(),
01809   NWidget(NWID_HORIZONTAL),
01810     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_CARGO_CARRIED), SetMinimalSize(96, 12),
01811         SetDataTip(STR_VEHICLE_DETAIL_TAB_CARGO, STR_VEHICLE_DETAILS_TRAIN_CARGO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
01812     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_TRAIN_VEHICLES), SetMinimalSize(99, 12),
01813         SetDataTip(STR_VEHICLE_DETAIL_TAB_INFORMATION, STR_VEHICLE_DETAILS_TRAIN_INFORMATION_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
01814     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_CAPACITY_OF_EACH), SetMinimalSize(99, 12),
01815         SetDataTip(STR_VEHICLE_DETAIL_TAB_CAPACITIES, STR_VEHICLE_DETAILS_TRAIN_CAPACITIES_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
01816     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_TOTAL_CARGO), SetMinimalSize(99, 12),
01817         SetDataTip(STR_VEHICLE_DETAIL_TAB_TOTAL_CARGO, STR_VEHICLE_DETAILS_TRAIN_TOTAL_CARGO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
01818     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
01819   EndContainer(),
01820 };
01821 
01822 
01823 extern int GetTrainDetailsWndVScroll(VehicleID veh_id, TrainDetailsWindowTabs det_tab);
01824 extern void DrawTrainDetails(const Train *v, int left, int right, int y, int vscroll_pos, uint16 vscroll_cap, TrainDetailsWindowTabs det_tab);
01825 extern void DrawRoadVehDetails(const Vehicle *v, int left, int right, int y);
01826 extern void DrawShipDetails(const Vehicle *v, int left, int right, int y);
01827 extern void DrawAircraftDetails(const Aircraft *v, int left, int right, int y);
01828 
01829 static StringID _service_interval_dropdown[] = {
01830   STR_VEHICLE_DETAILS_DEFAULT,
01831   STR_VEHICLE_DETAILS_DAYS,
01832   STR_VEHICLE_DETAILS_PERCENT,
01833   INVALID_STRING_ID,
01834 };
01835 
01837 struct VehicleDetailsWindow : Window {
01838   TrainDetailsWindowTabs tab; 
01839   Scrollbar *vscroll;
01840 
01842   VehicleDetailsWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
01843   {
01844     const Vehicle *v = Vehicle::Get(window_number);
01845 
01846     this->CreateNestedTree();
01847     this->vscroll = (v->type == VEH_TRAIN ? this->GetScrollbar(WID_VD_SCROLLBAR) : NULL);
01848     this->FinishInitNested(window_number);
01849 
01850     this->GetWidget<NWidgetCore>(WID_VD_RENAME_VEHICLE)->tool_tip = STR_VEHICLE_DETAILS_TRAIN_RENAME + v->type;
01851 
01852     this->owner = v->owner;
01853     this->tab = TDW_TAB_CARGO;
01854   }
01855 
01861   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
01862   {
01863     if (data == VIWD_AUTOREPLACE) {
01864       /* Autoreplace replaced the vehicle.
01865        * Nothing to do for this window. */
01866       return;
01867     }
01868     if (!gui_scope) return;
01869     const Vehicle *v = Vehicle::Get(this->window_number);
01870     if (v->type == VEH_ROAD) {
01871       const NWidgetBase *nwid_info = this->GetWidget<NWidgetBase>(WID_VD_MIDDLE_DETAILS);
01872       uint aimed_height = this->GetRoadVehDetailsHeight(v);
01873       /* If the number of articulated parts changes, the size of the window must change too. */
01874       if (aimed_height != nwid_info->current_y) {
01875         this->ReInit();
01876       }
01877     }
01878   }
01879 
01885   uint GetRoadVehDetailsHeight(const Vehicle *v)
01886   {
01887     uint desired_height;
01888     if (v->HasArticulatedPart()) {
01889       /* An articulated RV has its text drawn under the sprite instead of after it, hence 15 pixels extra. */
01890       desired_height = WD_FRAMERECT_TOP + 15 + 3 * FONT_HEIGHT_NORMAL + 2 + WD_FRAMERECT_BOTTOM;
01891       /* Add space for the cargo amount for each part. */
01892       for (const Vehicle *u = v; u != NULL; u = u->Next()) {
01893         if (u->cargo_cap != 0) desired_height += FONT_HEIGHT_NORMAL + 1;
01894       }
01895     } else {
01896       desired_height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + 3 + WD_FRAMERECT_BOTTOM;
01897     }
01898     return desired_height;
01899   }
01900 
01901   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01902   {
01903     switch (widget) {
01904       case WID_VD_TOP_DETAILS: {
01905         Dimension dim = { 0, 0 };
01906         size->height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
01907 
01908         for (uint i = 0; i < 4; i++) SetDParamMaxValue(i, INT16_MAX);
01909         static const StringID info_strings[] = {
01910           STR_VEHICLE_INFO_MAX_SPEED,
01911           STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED,
01912           STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE,
01913           STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR,
01914           STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS
01915         };
01916         for (uint i = 0; i < lengthof(info_strings); i++) {
01917           dim = maxdim(dim, GetStringBoundingBox(info_strings[i]));
01918         }
01919         SetDParam(0, STR_VEHICLE_INFO_AGE);
01920         dim = maxdim(dim, GetStringBoundingBox(STR_VEHICLE_INFO_AGE_RUNNING_COST_YR));
01921         size->width = dim.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
01922         break;
01923       }
01924 
01925       case WID_VD_MIDDLE_DETAILS: {
01926         const Vehicle *v = Vehicle::Get(this->window_number);
01927         switch (v->type) {
01928           case VEH_ROAD:
01929             size->height = this->GetRoadVehDetailsHeight(v);
01930             break;
01931 
01932           case VEH_SHIP:
01933             size->height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + 3 + WD_FRAMERECT_BOTTOM;
01934             break;
01935 
01936           case VEH_AIRCRAFT:
01937             size->height = WD_FRAMERECT_TOP + 5 * FONT_HEIGHT_NORMAL + 4 + WD_FRAMERECT_BOTTOM;
01938             break;
01939 
01940           default:
01941             NOT_REACHED(); // Train uses WID_VD_MATRIX instead.
01942         }
01943         break;
01944       }
01945 
01946       case WID_VD_MATRIX:
01947         resize->height = WD_MATRIX_TOP + FONT_HEIGHT_NORMAL + WD_MATRIX_BOTTOM;
01948         size->height = 4 * resize->height;
01949         break;
01950 
01951       case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
01952         StringID *strs = _service_interval_dropdown;
01953         while (*strs != INVALID_STRING_ID) {
01954           *size = maxdim(*size, GetStringBoundingBox(*strs++));
01955         }
01956         size->width += padding.width;
01957         size->height = FONT_HEIGHT_NORMAL + WD_DROPDOWNTEXT_TOP + WD_DROPDOWNTEXT_BOTTOM;
01958         break;
01959       }
01960 
01961       case WID_VD_SERVICING_INTERVAL:
01962         SetDParamMaxValue(0, MAX_SERVINT_DAYS); // Roughly the maximum interval
01963         SetDParamMaxValue(1, MAX_YEAR * DAYS_IN_YEAR); // Roughly the maximum year
01964         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;
01965         size->height = WD_FRAMERECT_TOP + FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
01966         break;
01967     }
01968   }
01969 
01971   static bool IsVehicleServiceIntervalEnabled(const VehicleType vehicle_type, CompanyID company_id)
01972   {
01973     const VehicleDefaultSettings *vds = &Company::Get(company_id)->settings.vehicle;
01974     switch (vehicle_type) {
01975       default: NOT_REACHED();
01976       case VEH_TRAIN:    return vds->servint_trains   != 0;
01977       case VEH_ROAD:     return vds->servint_roadveh  != 0;
01978       case VEH_SHIP:     return vds->servint_ships    != 0;
01979       case VEH_AIRCRAFT: return vds->servint_aircraft != 0;
01980     }
01981   }
01982 
01994   static void DrawVehicleDetails(const Vehicle *v, int left, int right, int y, int vscroll_pos, uint vscroll_cap, TrainDetailsWindowTabs det_tab)
01995   {
01996     switch (v->type) {
01997       case VEH_TRAIN:    DrawTrainDetails(Train::From(v), left, right, y, vscroll_pos, vscroll_cap, det_tab);  break;
01998       case VEH_ROAD:     DrawRoadVehDetails(v, left, right, y);  break;
01999       case VEH_SHIP:     DrawShipDetails(v, left, right, y);     break;
02000       case VEH_AIRCRAFT: DrawAircraftDetails(Aircraft::From(v), left, right, y); break;
02001       default: NOT_REACHED();
02002     }
02003   }
02004 
02005   virtual void SetStringParameters(int widget) const
02006   {
02007     if (widget == WID_VD_CAPTION) SetDParam(0, Vehicle::Get(this->window_number)->index);
02008   }
02009 
02010   virtual void DrawWidget(const Rect &r, int widget) const
02011   {
02012     const Vehicle *v = Vehicle::Get(this->window_number);
02013 
02014     switch (widget) {
02015       case WID_VD_TOP_DETAILS: {
02016         int y = r.top + WD_FRAMERECT_TOP;
02017 
02018         /* Draw running cost */
02019         SetDParam(1, v->age / DAYS_IN_LEAP_YEAR);
02020         SetDParam(0, (v->age + DAYS_IN_YEAR < v->max_age) ? STR_VEHICLE_INFO_AGE : STR_VEHICLE_INFO_AGE_RED);
02021         SetDParam(2, v->max_age / DAYS_IN_LEAP_YEAR);
02022         SetDParam(3, v->GetDisplayRunningCost());
02023         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_AGE_RUNNING_COST_YR);
02024         y += FONT_HEIGHT_NORMAL;
02025 
02026         /* Draw max speed */
02027         StringID string;
02028         if (v->type == VEH_TRAIN ||
02029             (v->type == VEH_ROAD && _settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL)) {
02030           const GroundVehicleCache *gcache = v->GetGroundVehicleCache();
02031           SetDParam(2, v->GetDisplayMaxSpeed());
02032           SetDParam(1, gcache->cached_power);
02033           SetDParam(0, gcache->cached_weight);
02034           SetDParam(3, gcache->cached_max_te / 1000);
02035           if (v->type == VEH_TRAIN && (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ||
02036               GetRailTypeInfo(Train::From(v)->railtype)->acceleration_type == 2)) {
02037             string = STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED;
02038           } else {
02039             string = STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE;
02040           }
02041         } else {
02042           SetDParam(0, v->GetDisplayMaxSpeed());
02043           if (v->type == VEH_AIRCRAFT && Aircraft::From(v)->GetRange() > 0) {
02044             SetDParam(1, Aircraft::From(v)->GetRange());
02045             string = STR_VEHICLE_INFO_MAX_SPEED_RANGE;
02046           } else {
02047             string = STR_VEHICLE_INFO_MAX_SPEED;
02048           }
02049         }
02050         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, string);
02051         y += FONT_HEIGHT_NORMAL;
02052 
02053         /* Draw profit */
02054         SetDParam(0, v->GetDisplayProfitThisYear());
02055         SetDParam(1, v->GetDisplayProfitLastYear());
02056         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR);
02057         y += FONT_HEIGHT_NORMAL;
02058 
02059         /* Draw breakdown & reliability */
02060         SetDParam(0, ToPercent16(v->reliability));
02061         SetDParam(1, v->breakdowns_since_last_service);
02062         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS);
02063         break;
02064       }
02065 
02066       case WID_VD_MATRIX:
02067         /* For trains only. */
02068         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);
02069         break;
02070 
02071       case WID_VD_MIDDLE_DETAILS: {
02072         /* For other vehicles, at the place of the matrix. */
02073         bool rtl = _current_text_dir == TD_RTL;
02074         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;
02075 
02076         uint text_left  = r.left  + (rtl ? 0 : sprite_width);
02077         uint text_right = r.right - (rtl ? sprite_width : 0);
02078 
02079         /* Articulated road vehicles use a complete line. */
02080         if (v->type == VEH_ROAD && v->HasArticulatedPart()) {
02081           DrawVehicleImage(v, r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, 0);
02082         } else {
02083           uint sprite_left  = rtl ? text_right : r.left;
02084           uint sprite_right = rtl ? r.right : text_left;
02085 
02086           DrawVehicleImage(v, sprite_left + WD_FRAMERECT_LEFT, sprite_right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, 0);
02087         }
02088         DrawVehicleDetails(v, text_left + WD_FRAMERECT_LEFT, text_right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, 0, 0, this->tab);
02089         break;
02090       }
02091 
02092       case WID_VD_SERVICING_INTERVAL:
02093         /* Draw service interval text */
02094         SetDParam(0, v->GetServiceInterval());
02095         SetDParam(1, v->date_of_last_service);
02096         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + (r.bottom - r.top + 1 - FONT_HEIGHT_NORMAL) / 2,
02097             v->ServiceIntervalIsPercent() ? STR_VEHICLE_DETAILS_SERVICING_INTERVAL_PERCENT : STR_VEHICLE_DETAILS_SERVICING_INTERVAL_DAYS);
02098         break;
02099     }
02100   }
02101 
02103   virtual void OnPaint()
02104   {
02105     const Vehicle *v = Vehicle::Get(this->window_number);
02106 
02107     this->SetWidgetDisabledState(WID_VD_RENAME_VEHICLE, v->owner != _local_company);
02108 
02109     if (v->type == VEH_TRAIN) {
02110       this->DisableWidget(this->tab + WID_VD_DETAILS_CARGO_CARRIED);
02111       this->vscroll->SetCount(GetTrainDetailsWndVScroll(v->index, this->tab));
02112     }
02113 
02114     /* Disable service-scroller when interval is set to disabled */
02115     this->SetWidgetsDisabledState(!IsVehicleServiceIntervalEnabled(v->type, v->owner),
02116       WID_VD_INCREASE_SERVICING_INTERVAL,
02117       WID_VD_DECREASE_SERVICING_INTERVAL,
02118       WIDGET_LIST_END);
02119 
02120     StringID str = v->ServiceIntervalIsCustom() ?
02121       (v->ServiceIntervalIsPercent() ? STR_VEHICLE_DETAILS_PERCENT : STR_VEHICLE_DETAILS_DAYS) :
02122       STR_VEHICLE_DETAILS_DEFAULT;
02123     this->GetWidget<NWidgetCore>(WID_VD_SERVICE_INTERVAL_DROPDOWN)->widget_data = str;
02124 
02125     this->DrawWidgets();
02126   }
02127 
02128   virtual void OnClick(Point pt, int widget, int click_count)
02129   {
02130     switch (widget) {
02131       case WID_VD_RENAME_VEHICLE: { // rename
02132         const Vehicle *v = Vehicle::Get(this->window_number);
02133         SetDParam(0, v->index);
02134         ShowQueryString(STR_VEHICLE_NAME, STR_QUERY_RENAME_TRAIN_CAPTION + v->type,
02135             MAX_LENGTH_VEHICLE_NAME_CHARS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
02136         break;
02137       }
02138 
02139       case WID_VD_INCREASE_SERVICING_INTERVAL:   // increase int
02140       case WID_VD_DECREASE_SERVICING_INTERVAL: { // decrease int
02141         int mod = _ctrl_pressed ? 5 : 10;
02142         const Vehicle *v = Vehicle::Get(this->window_number);
02143 
02144         mod = (widget == WID_VD_DECREASE_SERVICING_INTERVAL) ? -mod : mod;
02145         mod = GetServiceIntervalClamped(mod + v->GetServiceInterval(), v->ServiceIntervalIsPercent());
02146         if (mod == v->GetServiceInterval()) return;
02147 
02148         DoCommandP(v->tile, v->index, mod | (1 << 16) | (v->ServiceIntervalIsPercent() << 17), CMD_CHANGE_SERVICE_INT | CMD_MSG(STR_ERROR_CAN_T_CHANGE_SERVICING));
02149         break;
02150       }
02151 
02152       case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
02153         const Vehicle *v = Vehicle::Get(this->window_number);
02154         ShowDropDownMenu(this, _service_interval_dropdown, v->ServiceIntervalIsCustom() ? (v->ServiceIntervalIsPercent() ? 2 : 1) : 0, widget, 0, 0);
02155         break;
02156       }
02157 
02158       case WID_VD_DETAILS_CARGO_CARRIED:
02159       case WID_VD_DETAILS_TRAIN_VEHICLES:
02160       case WID_VD_DETAILS_CAPACITY_OF_EACH:
02161       case WID_VD_DETAILS_TOTAL_CARGO:
02162         this->SetWidgetsDisabledState(false,
02163           WID_VD_DETAILS_CARGO_CARRIED,
02164           WID_VD_DETAILS_TRAIN_VEHICLES,
02165           WID_VD_DETAILS_CAPACITY_OF_EACH,
02166           WID_VD_DETAILS_TOTAL_CARGO,
02167           widget,
02168           WIDGET_LIST_END);
02169 
02170         this->tab = (TrainDetailsWindowTabs)(widget - WID_VD_DETAILS_CARGO_CARRIED);
02171         this->SetDirty();
02172         break;
02173     }
02174   }
02175 
02176   virtual void OnDropdownSelect(int widget, int index)
02177   {
02178     switch (widget) {
02179       case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
02180         const Vehicle *v = Vehicle::Get(this->window_number);
02181         bool iscustom = index != 0;
02182         bool ispercent = iscustom ? (index == 2) : Company::Get(v->owner)->settings.vehicle.servint_ispercent;
02183         uint16 interval = GetServiceIntervalClamped(v->GetServiceInterval(), ispercent);
02184         DoCommandP(v->tile, v->index, interval | (iscustom << 16) | (ispercent << 17), CMD_CHANGE_SERVICE_INT | CMD_MSG(STR_ERROR_CAN_T_CHANGE_SERVICING));
02185         break;
02186       }
02187     }
02188   }
02189 
02190   virtual void OnQueryTextFinished(char *str)
02191   {
02192     if (str == NULL) return;
02193 
02194     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);
02195   }
02196 
02197   virtual void OnResize()
02198   {
02199     NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_VD_MATRIX);
02200     if (nwi != NULL) {
02201       this->vscroll->SetCapacityFromWidget(this, WID_VD_MATRIX);
02202       nwi->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
02203     }
02204   }
02205 };
02206 
02208 static WindowDesc _train_vehicle_details_desc(
02209   WDP_AUTO, "view_vehicle_details_train", 405, 178,
02210   WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
02211   0,
02212   _nested_train_vehicle_details_widgets, lengthof(_nested_train_vehicle_details_widgets)
02213 );
02214 
02216 static WindowDesc _nontrain_vehicle_details_desc(
02217   WDP_AUTO, "view_vehicle_details", 405, 113,
02218   WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
02219   0,
02220   _nested_nontrain_vehicle_details_widgets, lengthof(_nested_nontrain_vehicle_details_widgets)
02221 );
02222 
02224 static void ShowVehicleDetailsWindow(const Vehicle *v)
02225 {
02226   DeleteWindowById(WC_VEHICLE_ORDERS, v->index, false);
02227   DeleteWindowById(WC_VEHICLE_TIMETABLE, v->index, false);
02228   AllocateWindowDescFront<VehicleDetailsWindow>((v->type == VEH_TRAIN) ? &_train_vehicle_details_desc : &_nontrain_vehicle_details_desc, v->index);
02229 }
02230 
02231 
02232 /* Unified vehicle GUI - Vehicle View Window */
02233 
02235 static const NWidgetPart _nested_vehicle_view_widgets[] = {
02236   NWidget(NWID_HORIZONTAL),
02237     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
02238     NWidget(WWT_CAPTION, COLOUR_GREY, WID_VV_CAPTION), SetDataTip(STR_VEHICLE_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
02239     NWidget(WWT_DEBUGBOX, COLOUR_GREY),
02240     NWidget(WWT_SHADEBOX, COLOUR_GREY),
02241     NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
02242     NWidget(WWT_STICKYBOX, COLOUR_GREY),
02243   EndContainer(),
02244   NWidget(NWID_HORIZONTAL),
02245     NWidget(WWT_PANEL, COLOUR_GREY),
02246       NWidget(WWT_INSET, COLOUR_GREY), SetPadding(2, 2, 2, 2),
02247         NWidget(NWID_VIEWPORT, INVALID_COLOUR, WID_VV_VIEWPORT), SetMinimalSize(226, 84), SetResize(1, 1), SetPadding(1, 1, 1, 1),
02248       EndContainer(),
02249     EndContainer(),
02250     NWidget(NWID_VERTICAL),
02251       NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_CENTER_MAIN_VIEW), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(SPR_CENTRE_VIEW_VEHICLE, 0x0 /* filled later */),
02252       NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VV_SELECT_DEPOT_CLONE),
02253         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_GOTO_DEPOT), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
02254         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_CLONE), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
02255       EndContainer(),
02256       /* For trains only, 'ignore signal' button. */
02257       NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_FORCE_PROCEED), SetMinimalSize(18, 18), SetFill(1, 1),
02258                       SetDataTip(SPR_IGNORE_SIGNALS, STR_VEHICLE_VIEW_TRAIN_IGNORE_SIGNAL_TOOLTIP),
02259       NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VV_SELECT_REFIT_TURN),
02260         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_REFIT), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(SPR_REFIT_VEHICLE, 0x0 /* filled later */),
02261         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_TURN_AROUND), SetMinimalSize(18, 18), SetFill(1, 1),
02262                         SetDataTip(SPR_FORCE_VEHICLE_TURN, STR_VEHICLE_VIEW_ROAD_VEHICLE_REVERSE_TOOLTIP),
02263       EndContainer(),
02264       NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_SHOW_ORDERS), SetFill(1, 1), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_ORDERS, 0x0 /* filled later */),
02265       NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_SHOW_DETAILS), SetFill(1, 1), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_VEHICLE_DETAILS, 0x0 /* filled later */),
02266       NWidget(WWT_PANEL, COLOUR_GREY), SetFill(1, 1), SetMinimalSize(18, 0), SetResize(0, 1), EndContainer(),
02267     EndContainer(),
02268   EndContainer(),
02269   NWidget(NWID_HORIZONTAL),
02270     NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_VV_START_STOP), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetResize(1, 0), SetFill(1, 0),
02271     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
02272   EndContainer(),
02273 };
02274 
02276 static WindowDesc _vehicle_view_desc(
02277   WDP_AUTO, "view_vehicle", 250, 116,
02278   WC_VEHICLE_VIEW, WC_NONE,
02279   0,
02280   _nested_vehicle_view_widgets, lengthof(_nested_vehicle_view_widgets)
02281 );
02282 
02287 static WindowDesc _train_view_desc(
02288   WDP_AUTO, "view_vehicle_train", 250, 134,
02289   WC_VEHICLE_VIEW, WC_NONE,
02290   0,
02291   _nested_vehicle_view_widgets, lengthof(_nested_vehicle_view_widgets)
02292 );
02293 
02294 
02295 /* Just to make sure, nobody has changed the vehicle type constants, as we are
02296    using them for array indexing in a number of places here. */
02297 assert_compile(VEH_TRAIN == 0);
02298 assert_compile(VEH_ROAD == 1);
02299 assert_compile(VEH_SHIP == 2);
02300 assert_compile(VEH_AIRCRAFT == 3);
02301 
02303 static const ZoomLevel _vehicle_view_zoom_levels[] = {
02304   ZOOM_LVL_TRAIN,
02305   ZOOM_LVL_ROADVEH,
02306   ZOOM_LVL_SHIP,
02307   ZOOM_LVL_AIRCRAFT,
02308 };
02309 
02310 /* Constants for geometry of vehicle view viewport */
02311 static const int VV_INITIAL_VIEWPORT_WIDTH = 226;
02312 static const int VV_INITIAL_VIEWPORT_HEIGHT = 84;
02313 static const int VV_INITIAL_VIEWPORT_HEIGHT_TRAIN = 102;
02314 
02316 enum VehicleCommandTranslation {
02317   VCT_CMD_START_STOP = 0,
02318   VCT_CMD_CLONE_VEH,
02319   VCT_CMD_TURN_AROUND,
02320 };
02321 
02323 static const uint32 _vehicle_command_translation_table[][4] = {
02324   { // VCT_CMD_START_STOP
02325     CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_TRAIN),
02326     CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_ROAD_VEHICLE),
02327     CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_SHIP),
02328     CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_AIRCRAFT)
02329   },
02330   { // VCT_CMD_CLONE_VEH
02331     CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_TRAIN),
02332     CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_ROAD_VEHICLE),
02333     CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_SHIP),
02334     CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_AIRCRAFT)
02335   },
02336   { // VCT_CMD_TURN_AROUND
02337     CMD_REVERSE_TRAIN_DIRECTION | CMD_MSG(STR_ERROR_CAN_T_REVERSE_DIRECTION_TRAIN),
02338     CMD_TURN_ROADVEH            | CMD_MSG(STR_ERROR_CAN_T_MAKE_ROAD_VEHICLE_TURN),
02339     0xffffffff, // invalid for ships
02340     0xffffffff  // invalid for aircrafts
02341   },
02342 };
02343 
02351 void CcStartStopVehicle(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
02352 {
02353   if (result.Failed()) return;
02354 
02355   const Vehicle *v = Vehicle::GetIfValid(p1);
02356   if (v == NULL || !v->IsPrimaryVehicle() || v->owner != _local_company) return;
02357 
02358   StringID msg = (v->vehstatus & VS_STOPPED) ? STR_VEHICLE_COMMAND_STOPPED : STR_VEHICLE_COMMAND_STARTED;
02359   Point pt = RemapCoords(v->x_pos, v->y_pos, v->z_pos);
02360   AddTextEffect(msg, pt.x, pt.y, DAY_TICKS, TE_RISING);
02361 }
02362 
02368 void StartStopVehicle(const Vehicle *v, bool texteffect)
02369 {
02370   assert(v->IsPrimaryVehicle());
02371   DoCommandP(v->tile, v->index, 0, _vehicle_command_translation_table[VCT_CMD_START_STOP][v->type], texteffect ? CcStartStopVehicle : NULL);
02372 }
02373 
02375 static bool IsVehicleRefitable(const Vehicle *v)
02376 {
02377   if (!v->IsStoppedInDepot()) return false;
02378 
02379   do {
02380     if (IsEngineRefittable(v->engine_type)) return true;
02381   } while (v->IsGroundVehicle() && (v = v->Next()) != NULL);
02382 
02383   return false;
02384 }
02385 
02387 struct VehicleViewWindow : Window {
02388 private:
02390   enum PlaneSelections {
02391     SEL_DC_GOTO_DEPOT,  
02392     SEL_DC_CLONE,       
02393 
02394     SEL_RT_REFIT,       
02395     SEL_RT_TURN_AROUND, 
02396 
02397     SEL_DC_BASEPLANE = SEL_DC_GOTO_DEPOT, 
02398     SEL_RT_BASEPLANE = SEL_RT_REFIT,      
02399   };
02400 
02405   void SelectPlane(PlaneSelections plane)
02406   {
02407     switch (plane) {
02408       case SEL_DC_GOTO_DEPOT:
02409       case SEL_DC_CLONE:
02410         this->GetWidget<NWidgetStacked>(WID_VV_SELECT_DEPOT_CLONE)->SetDisplayedPlane(plane - SEL_DC_BASEPLANE);
02411         break;
02412 
02413       case SEL_RT_REFIT:
02414       case SEL_RT_TURN_AROUND:
02415         this->GetWidget<NWidgetStacked>(WID_VV_SELECT_REFIT_TURN)->SetDisplayedPlane(plane - SEL_RT_BASEPLANE);
02416         break;
02417 
02418       default:
02419         NOT_REACHED();
02420     }
02421   }
02422 
02423 public:
02424   VehicleViewWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
02425   {
02426     this->CreateNestedTree();
02427 
02428     /* Sprites for the 'send to depot' button indexed by vehicle type. */
02429     static const SpriteID vehicle_view_goto_depot_sprites[] = {
02430       SPR_SEND_TRAIN_TODEPOT,
02431       SPR_SEND_ROADVEH_TODEPOT,
02432       SPR_SEND_SHIP_TODEPOT,
02433       SPR_SEND_AIRCRAFT_TODEPOT,
02434     };
02435     const Vehicle *v = Vehicle::Get(window_number);
02436     this->GetWidget<NWidgetCore>(WID_VV_GOTO_DEPOT)->widget_data = vehicle_view_goto_depot_sprites[v->type];
02437 
02438     /* Sprites for the 'clone vehicle' button indexed by vehicle type. */
02439     static const SpriteID vehicle_view_clone_sprites[] = {
02440       SPR_CLONE_TRAIN,
02441       SPR_CLONE_ROADVEH,
02442       SPR_CLONE_SHIP,
02443       SPR_CLONE_AIRCRAFT,
02444     };
02445     this->GetWidget<NWidgetCore>(WID_VV_CLONE)->widget_data = vehicle_view_clone_sprites[v->type];
02446 
02447     switch (v->type) {
02448       case VEH_TRAIN:
02449         this->GetWidget<NWidgetCore>(WID_VV_TURN_AROUND)->tool_tip = STR_VEHICLE_VIEW_TRAIN_REVERSE_TOOLTIP;
02450         break;
02451 
02452       case VEH_ROAD:
02453         break;
02454 
02455       case VEH_SHIP:
02456       case VEH_AIRCRAFT:
02457         this->SelectPlane(SEL_RT_REFIT);
02458         break;
02459 
02460       default: NOT_REACHED();
02461     }
02462     this->FinishInitNested(window_number);
02463     this->owner = v->owner;
02464     this->GetWidget<NWidgetViewport>(WID_VV_VIEWPORT)->InitializeViewport(this, this->window_number | (1 << 31), _vehicle_view_zoom_levels[v->type]);
02465 
02466     this->GetWidget<NWidgetCore>(WID_VV_START_STOP)->tool_tip       = STR_VEHICLE_VIEW_TRAIN_STATE_START_STOP_TOOLTIP + v->type;
02467     this->GetWidget<NWidgetCore>(WID_VV_CENTER_MAIN_VIEW)->tool_tip = STR_VEHICLE_VIEW_TRAIN_LOCATION_TOOLTIP + v->type;
02468     this->GetWidget<NWidgetCore>(WID_VV_REFIT)->tool_tip            = STR_VEHICLE_VIEW_TRAIN_REFIT_TOOLTIP + v->type;
02469     this->GetWidget<NWidgetCore>(WID_VV_GOTO_DEPOT)->tool_tip       = STR_VEHICLE_VIEW_TRAIN_SEND_TO_DEPOT_TOOLTIP + v->type;
02470     this->GetWidget<NWidgetCore>(WID_VV_SHOW_ORDERS)->tool_tip      = STR_VEHICLE_VIEW_TRAIN_ORDERS_TOOLTIP + v->type;
02471     this->GetWidget<NWidgetCore>(WID_VV_SHOW_DETAILS)->tool_tip     = STR_VEHICLE_VIEW_TRAIN_SHOW_DETAILS_TOOLTIP + v->type;
02472     this->GetWidget<NWidgetCore>(WID_VV_CLONE)->tool_tip            = STR_VEHICLE_VIEW_CLONE_TRAIN_INFO + v->type;
02473   }
02474 
02475   ~VehicleViewWindow()
02476   {
02477     DeleteWindowById(WC_VEHICLE_ORDERS, this->window_number, false);
02478     DeleteWindowById(WC_VEHICLE_REFIT, this->window_number, false);
02479     DeleteWindowById(WC_VEHICLE_DETAILS, this->window_number, false);
02480     DeleteWindowById(WC_VEHICLE_TIMETABLE, this->window_number, false);
02481   }
02482 
02483   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
02484   {
02485     const Vehicle *v = Vehicle::Get(this->window_number);
02486     switch (widget) {
02487       case WID_VV_FORCE_PROCEED:
02488         if (v->type != VEH_TRAIN) {
02489           size->height = 0;
02490           size->width = 0;
02491         }
02492         break;
02493 
02494       case WID_VV_VIEWPORT:
02495         size->width = VV_INITIAL_VIEWPORT_WIDTH;
02496         size->height = (v->type == VEH_TRAIN) ? VV_INITIAL_VIEWPORT_HEIGHT_TRAIN : VV_INITIAL_VIEWPORT_HEIGHT;
02497         break;
02498     }
02499   }
02500 
02501   virtual void OnPaint()
02502   {
02503     const Vehicle *v = Vehicle::Get(this->window_number);
02504     bool is_localcompany = v->owner == _local_company;
02505     bool refitable_and_stopped_in_depot = IsVehicleRefitable(v);
02506 
02507     this->SetWidgetDisabledState(WID_VV_GOTO_DEPOT, !is_localcompany);
02508     this->SetWidgetDisabledState(WID_VV_REFIT, !refitable_and_stopped_in_depot || !is_localcompany);
02509     this->SetWidgetDisabledState(WID_VV_CLONE, !is_localcompany);
02510 
02511     if (v->type == VEH_TRAIN) {
02512       this->SetWidgetLoweredState(WID_VV_FORCE_PROCEED, Train::From(v)->force_proceed == TFP_SIGNAL);
02513       this->SetWidgetDisabledState(WID_VV_FORCE_PROCEED, !is_localcompany);
02514       this->SetWidgetDisabledState(WID_VV_TURN_AROUND, !is_localcompany);
02515     }
02516 
02517     this->DrawWidgets();
02518   }
02519 
02520   virtual void SetStringParameters(int widget) const
02521   {
02522     if (widget != WID_VV_CAPTION) return;
02523 
02524     const Vehicle *v = Vehicle::Get(this->window_number);
02525     SetDParam(0, v->index);
02526   }
02527 
02528   virtual void DrawWidget(const Rect &r, int widget) const
02529   {
02530     if (widget != WID_VV_START_STOP) return;
02531 
02532     const Vehicle *v = Vehicle::Get(this->window_number);
02533     StringID str;
02534     if (v->vehstatus & VS_CRASHED) {
02535       str = STR_VEHICLE_STATUS_CRASHED;
02536     } else if (v->type != VEH_AIRCRAFT && v->breakdown_ctr == 1) { // check for aircraft necessary?
02537       str = STR_VEHICLE_STATUS_BROKEN_DOWN;
02538     } else if (v->vehstatus & VS_STOPPED) {
02539       if (v->type == VEH_TRAIN) {
02540         if (v->cur_speed == 0) {
02541           if (Train::From(v)->gcache.cached_power == 0) {
02542             str = STR_VEHICLE_STATUS_TRAIN_NO_POWER;
02543           } else {
02544             str = STR_VEHICLE_STATUS_STOPPED;
02545           }
02546         } else {
02547           SetDParam(0, v->GetDisplaySpeed());
02548           str = STR_VEHICLE_STATUS_TRAIN_STOPPING_VEL;
02549         }
02550       } else { // no train
02551         str = STR_VEHICLE_STATUS_STOPPED;
02552       }
02553     } else if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_TRAIN_STUCK) && !v->current_order.IsType(OT_LOADING)) {
02554       str = STR_VEHICLE_STATUS_TRAIN_STUCK;
02555     } else if (v->type == VEH_AIRCRAFT && HasBit(Aircraft::From(v)->flags, VAF_DEST_TOO_FAR) && !v->current_order.IsType(OT_LOADING)) {
02556       str = STR_VEHICLE_STATUS_AIRCRAFT_TOO_FAR;
02557     } else { // vehicle is in a "normal" state, show current order
02558       switch (v->current_order.GetType()) {
02559         case OT_GOTO_STATION: {
02560           SetDParam(0, v->current_order.GetDestination());
02561           SetDParam(1, v->GetDisplaySpeed());
02562           str = STR_VEHICLE_STATUS_HEADING_FOR_STATION_VEL;
02563           break;
02564         }
02565 
02566         case OT_GOTO_DEPOT: {
02567           SetDParam(0, v->type);
02568           SetDParam(1, v->current_order.GetDestination());
02569           SetDParam(2, v->GetDisplaySpeed());
02570           if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
02571             /* This case *only* happens when multiple nearest depot orders
02572              * follow each other (including an order list only one order: a
02573              * nearest depot order) and there are no reachable depots.
02574              * It is primarily to guard for the case that there is no
02575              * depot with index 0, which would be used as fallback for
02576              * evaluating the string in the status bar. */
02577             str = STR_EMPTY;
02578           } else if (v->current_order.GetDepotActionType() & ODATFB_HALT) {
02579             str = STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_VEL;
02580           } else {
02581             str = STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_SERVICE_VEL;
02582           }
02583           break;
02584         }
02585 
02586         case OT_LOADING:
02587           str = STR_VEHICLE_STATUS_LOADING_UNLOADING;
02588           break;
02589 
02590         case OT_GOTO_WAYPOINT: {
02591           assert(v->type == VEH_TRAIN || v->type == VEH_SHIP);
02592           SetDParam(0, v->current_order.GetDestination());
02593           str = STR_VEHICLE_STATUS_HEADING_FOR_WAYPOINT_VEL;
02594           SetDParam(1, v->GetDisplaySpeed());
02595           break;
02596         }
02597 
02598         case OT_LEAVESTATION:
02599           if (v->type != VEH_AIRCRAFT) {
02600             str = STR_VEHICLE_STATUS_LEAVING;
02601             break;
02602           }
02603           /* FALL THROUGH, if aircraft. Does this even happen? */
02604 
02605         default:
02606           if (v->GetNumManualOrders() == 0) {
02607             str = STR_VEHICLE_STATUS_NO_ORDERS_VEL;
02608             SetDParam(0, v->GetDisplaySpeed());
02609           } else {
02610             str = STR_EMPTY;
02611           }
02612           break;
02613       }
02614     }
02615 
02616     /* draw the flag plus orders */
02617     DrawSprite(v->vehstatus & VS_STOPPED ? SPR_FLAG_VEH_STOPPED : SPR_FLAG_VEH_RUNNING, PAL_NONE, WD_FRAMERECT_LEFT, r.top + WD_FRAMERECT_TOP);
02618     DrawString(r.left + WD_FRAMERECT_LEFT + 6, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, str, TC_FROMSTRING, SA_HOR_CENTER);
02619   }
02620 
02621   virtual void OnClick(Point pt, int widget, int click_count)
02622   {
02623     const Vehicle *v = Vehicle::Get(this->window_number);
02624 
02625     switch (widget) {
02626       case WID_VV_START_STOP: // start stop
02627         if (_ctrl_pressed) {
02628           /* Scroll to current order destination */
02629           TileIndex tile = v->current_order.GetLocation(v);
02630           if (tile != INVALID_TILE) ScrollMainWindowToTile(tile);
02631         } else {
02632           /* Start/Stop */
02633           StartStopVehicle(v, false);
02634         }
02635         break;
02636       case WID_VV_CENTER_MAIN_VIEW: {// center main view
02637         const Window *mainwindow = FindWindowById(WC_MAIN_WINDOW, 0);
02638         /* code to allow the main window to 'follow' the vehicle if the ctrl key is pressed */
02639         if (_ctrl_pressed && mainwindow->viewport->zoom <= ZOOM_LVL_OUT_4X) {
02640           mainwindow->viewport->follow_vehicle = v->index;
02641         } else {
02642           ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos);
02643         }
02644         break;
02645       }
02646 
02647       case WID_VV_GOTO_DEPOT: // goto hangar
02648         DoCommandP(v->tile, v->index | (_ctrl_pressed ? DEPOT_SERVICE : 0U), 0, GetCmdSendToDepot(v));
02649         break;
02650       case WID_VV_REFIT: // refit
02651         ShowVehicleRefitWindow(v, INVALID_VEH_ORDER_ID, this);
02652         break;
02653       case WID_VV_SHOW_ORDERS: // show orders
02654         if (_ctrl_pressed) {
02655           ShowTimetableWindow(v);
02656         } else {
02657           ShowOrdersWindow(v);
02658         }
02659         break;
02660       case WID_VV_SHOW_DETAILS: // show details
02661         ShowVehicleDetailsWindow(v);
02662         break;
02663       case WID_VV_CLONE: // clone vehicle
02664         /* Suppress the vehicle GUI when share-cloning.
02665          * There is no point to it except for starting the vehicle.
02666          * For starting the vehicle the player has to open the depot GUI, which is
02667          * most likely already open, but is also visible in the vehicle viewport. */
02668         DoCommandP(v->tile, v->index, _ctrl_pressed ? 1 : 0,
02669                     _vehicle_command_translation_table[VCT_CMD_CLONE_VEH][v->type],
02670                     _ctrl_pressed ? NULL : CcCloneVehicle);
02671         break;
02672       case WID_VV_TURN_AROUND: // turn around
02673         assert(v->IsGroundVehicle());
02674         DoCommandP(v->tile, v->index, 0,
02675                     _vehicle_command_translation_table[VCT_CMD_TURN_AROUND][v->type]);
02676         break;
02677       case WID_VV_FORCE_PROCEED: // force proceed
02678         assert(v->type == VEH_TRAIN);
02679         DoCommandP(v->tile, v->index, 0, CMD_FORCE_TRAIN_PROCEED | CMD_MSG(STR_ERROR_CAN_T_MAKE_TRAIN_PASS_SIGNAL));
02680         break;
02681     }
02682   }
02683 
02684   virtual void OnResize()
02685   {
02686     if (this->viewport != NULL) {
02687       NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_VV_VIEWPORT);
02688       nvp->UpdateViewportCoordinates(this);
02689     }
02690   }
02691 
02692   virtual void OnTick()
02693   {
02694     const Vehicle *v = Vehicle::Get(this->window_number);
02695     bool veh_stopped = v->IsStoppedInDepot();
02696 
02697     /* Widget WID_VV_GOTO_DEPOT must be hidden if the vehicle is already stopped in depot.
02698      * Widget WID_VV_CLONE_VEH should then be shown, since cloning is allowed only while in depot and stopped.
02699      */
02700     PlaneSelections plane = veh_stopped ? SEL_DC_CLONE : SEL_DC_GOTO_DEPOT;
02701     NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VV_SELECT_DEPOT_CLONE); // Selection widget 'send to depot' / 'clone'.
02702     if (nwi->shown_plane + SEL_DC_BASEPLANE != plane) {
02703       this->SelectPlane(plane);
02704       this->SetWidgetDirty(WID_VV_SELECT_DEPOT_CLONE);
02705     }
02706     /* The same system applies to widget WID_VV_REFIT_VEH and VVW_WIDGET_TURN_AROUND.*/
02707     if (v->IsGroundVehicle()) {
02708       PlaneSelections plane = veh_stopped ? SEL_RT_REFIT : SEL_RT_TURN_AROUND;
02709       NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VV_SELECT_REFIT_TURN);
02710       if (nwi->shown_plane + SEL_RT_BASEPLANE != plane) {
02711         this->SelectPlane(plane);
02712         this->SetWidgetDirty(WID_VV_SELECT_REFIT_TURN);
02713       }
02714     }
02715   }
02716 
02722   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
02723   {
02724     if (data == VIWD_AUTOREPLACE) {
02725       /* Autoreplace replaced the vehicle.
02726        * Nothing to do for this window. */
02727       return;
02728     }
02729   }
02730 
02731   virtual bool IsNewGRFInspectable() const
02732   {
02733     return ::IsNewGRFInspectable(GetGrfSpecFeature(Vehicle::Get(this->window_number)->type), this->window_number);
02734   }
02735 
02736   virtual void ShowNewGRFInspectWindow() const
02737   {
02738 		::ShowNewGRFInspectWindow(GetGrfSpecFeature(Vehicle::Get(this->window_number)->type), this->window_number);
02739   }
02740 };
02741 
02742 
02744 void ShowVehicleViewWindow(const Vehicle *v)
02745 {
02746   AllocateWindowDescFront<VehicleViewWindow>((v->type == VEH_TRAIN) ? &_train_view_desc : &_vehicle_view_desc, v->index);
02747 }
02748 
02754 bool VehicleClicked(const Vehicle *v)
02755 {
02756   assert(v != NULL);
02757   if (!(_thd.place_mode & HT_VEHICLE)) return false;
02758 
02759   v = v->First();
02760   if (!v->IsPrimaryVehicle()) return false;
02761 
02762   return _thd.GetCallbackWnd()->OnVehicleSelect(v);
02763 }
02764 
02765 void StopGlobalFollowVehicle(const Vehicle *v)
02766 {
02767   Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
02768   if (w != NULL && w->viewport->follow_vehicle == v->index) {
02769     ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos, true); // lock the main view on the vehicle's last position
02770     w->viewport->follow_vehicle = INVALID_VEHICLE;
02771   }
02772 }
02773 
02774 
02782 void CcBuildPrimaryVehicle(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
02783 {
02784   if (result.Failed()) return;
02785 
02786   const Vehicle *v = Vehicle::Get(_new_vehicle_id);
02787   ShowVehicleViewWindow(v);
02788 }
02789 
02795 int GetVehicleWidth(Vehicle *v, EngineImageType image_type)
02796 {
02797   int vehicle_width = 0;
02798 
02799   switch (v->type) {
02800     case VEH_TRAIN:
02801       for (const Train *u = Train::From(v); u != NULL; u = u->Next()) {
02802         vehicle_width += u->GetDisplayImageWidth();
02803       }
02804       break;
02805 
02806     case VEH_ROAD:
02807       for (const RoadVehicle *u = RoadVehicle::From(v); u != NULL; u = u->Next()) {
02808         vehicle_width += u->GetDisplayImageWidth();
02809       }
02810       break;
02811 
02812     default:
02813       bool rtl = _current_text_dir == TD_RTL;
02814       SpriteID sprite = v->GetImage(rtl ? DIR_E : DIR_W, image_type);
02815       const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
02816       vehicle_width = UnScaleByZoom(real_sprite->width, ZOOM_LVL_GUI);
02817 
02818       break;
02819   }
02820 
02821   return vehicle_width;
02822 }