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         uint16 callback = GetVehicleCallback(CBID_VEHICLE_CARGO_SUFFIX, 0, 0, v->engine_type, v);
00255 
00256         if (callback != CALLBACK_FAILED) {
00257           if (callback > 0x400) ErrorUnknownCallbackResult(v->GetGRFID(), CBID_VEHICLE_CARGO_SUFFIX, callback);
00258           if (callback >= 0x400 || (v->GetGRF()->grf_version < 8 && callback == 0xFF)) callback = CALLBACK_FAILED;
00259         }
00260         if (callback == CALLBACK_FAILED) break;
00261 
00262         if (!subtypes.Contains(GetCargoSubtypeText(v))) continue;
00263 
00264         /* We found something matching. */
00265         ret_refit_cyc = refit_cyc;
00266         success = true;
00267         break;
00268       }
00269 
00270       /* Reset the vehicle's cargo type */
00271       v->cargo_type    = old_cargo_type;
00272       v->cargo_subtype = old_cargo_subtype;
00273 
00274       /* Make sure we don't taint the vehicle. */
00275       v->First()->InvalidateNewGRFCache();
00276       v->InvalidateNewGRFCache();
00277 
00278       if (success) break;
00279     }
00280   }
00281 
00282   return ret_refit_cyc;
00283 }
00284 
00286 struct RefitOption {
00287   CargoID cargo;    
00288   byte subtype;     
00289   uint16 value;     
00290   const Engine *engine;  
00291 
00297   inline bool operator != (const RefitOption &other) const
00298   {
00299     return other.cargo != this->cargo || other.value != this->value;
00300   }
00301 
00307   inline bool operator == (const RefitOption &other) const
00308   {
00309     return other.cargo == this->cargo && other.value == this->value;
00310   }
00311 };
00312 
00313 typedef SmallVector<RefitOption, 32> SubtypeList; 
00314 
00324 static void DrawVehicleRefitWindow(const SubtypeList list[NUM_CARGO], int sel, uint pos, uint rows, uint delta, const Rect &r)
00325 {
00326   uint y = r.top + WD_MATRIX_TOP;
00327   uint current = 0;
00328 
00329   /* Draw the list of subtypes for each cargo, and find the selected refit option (by its position). */
00330   for (uint i = 0; current < pos + rows && i < NUM_CARGO; i++) {
00331     for (uint j = 0; current < pos + rows && j < list[i].Length(); j++) {
00332       /* Refit options with a position smaller than pos don't have to be drawn. */
00333       if (current < pos) {
00334         current++;
00335         continue;
00336       }
00337 
00338       TextColour colour = (sel == (int)current) ? TC_WHITE : TC_BLACK;
00339       const RefitOption refit = list[i][j];
00340       /* Get the cargo name. */
00341       SetDParam(0, CargoSpec::Get(refit.cargo)->name);
00342       /* If the callback succeeded, draw the cargo suffix. */
00343       if (refit.value != CALLBACK_FAILED && refit.value < 0x400) {
00344         SetDParam(1, GetGRFStringID(refit.engine->GetGRFID(), 0xD000 + refit.value));
00345         DrawString(r.left + WD_MATRIX_LEFT, r.right - WD_MATRIX_RIGHT, y, STR_JUST_STRING_STRING, colour);
00346       } else {
00347         DrawString(r.left + WD_MATRIX_LEFT, r.right - WD_MATRIX_RIGHT, y, STR_JUST_STRING, colour);
00348       }
00349 
00350       y += delta;
00351       current++;
00352     }
00353   }
00354 }
00355 
00357 struct RefitWindow : public Window {
00358   int sel;                     
00359   RefitOption *cargo;          
00360   SubtypeList list[NUM_CARGO]; 
00361   VehicleOrderID order;        
00362   uint information_width;      
00363   Scrollbar *vscroll;          
00364   Scrollbar *hscroll;          
00365   int vehicle_width;           
00366   int sprite_left;             
00367   int sprite_right;            
00368   uint vehicle_margin;         
00369   int click_x;                 
00370   VehicleID selected_vehicle;  
00371   uint8 num_vehicles;          
00372   bool auto_refit;             
00373 
00377   void BuildRefitList()
00378   {
00379     for (uint i = 0; i < NUM_CARGO; i++) this->list[i].Clear();
00380     Vehicle *v = Vehicle::Get(this->window_number);
00381 
00382     /* Check only the selected vehicles. */
00383     VehicleSet vehicles_to_refit;
00384     GetVehicleSet(vehicles_to_refit, Vehicle::Get(this->selected_vehicle), this->num_vehicles);
00385 
00386     do {
00387       if (v->type == VEH_TRAIN && !vehicles_to_refit.Contains(v->index)) continue;
00388       const Engine *e = v->GetEngine();
00389       uint32 cmask = e->info.refit_mask;
00390       byte callback_mask = e->info.callback_mask;
00391 
00392       /* Skip this engine if it does not carry anything */
00393       if (!e->CanCarryCargo()) continue;
00394       /* Skip this engine if we build the list for auto-refitting and engine doesn't allow it. */
00395       if (this->auto_refit && !HasBit(e->info.misc_flags, EF_AUTO_REFIT)) continue;
00396 
00397       /* Loop through all cargoes in the refit mask */
00398       int current_index = 0;
00399       const CargoSpec *cs;
00400       FOR_ALL_SORTED_CARGOSPECS(cs) {
00401         CargoID cid = cs->Index();
00402         /* Skip cargo type if it's not listed */
00403         if (!HasBit(cmask, cid)) {
00404           current_index++;
00405           continue;
00406         }
00407 
00408         /* Check the vehicle's callback mask for cargo suffixes */
00409         if (HasBit(callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) {
00410           /* Make a note of the original cargo type. It has to be
00411            * changed to test the cargo & subtype... */
00412           CargoID temp_cargo = v->cargo_type;
00413           byte temp_subtype  = v->cargo_subtype;
00414 
00415           v->cargo_type = cid;
00416 
00417           for (uint refit_cyc = 0; refit_cyc < MAX_REFIT_CYCLE; refit_cyc++) {
00418             v->cargo_subtype = refit_cyc;
00419 
00420             /* Make sure we don't pick up anything cached. */
00421             v->First()->InvalidateNewGRFCache();
00422             v->InvalidateNewGRFCache();
00423             uint16 callback = GetVehicleCallback(CBID_VEHICLE_CARGO_SUFFIX, 0, 0, v->engine_type, v);
00424 
00425             if (callback != CALLBACK_FAILED) {
00426               if (callback > 0x400) ErrorUnknownCallbackResult(v->GetGRFID(), CBID_VEHICLE_CARGO_SUFFIX, callback);
00427               if (callback >= 0x400 || (v->GetGRF()->grf_version < 8 && callback == 0xFF)) callback = CALLBACK_FAILED;
00428             }
00429             if (refit_cyc != 0 && callback == CALLBACK_FAILED) break;
00430 
00431             RefitOption option;
00432             option.cargo   = cid;
00433             option.subtype = refit_cyc;
00434             option.value   = callback;
00435             option.engine  = v->GetEngine();
00436             this->list[current_index].Include(option);
00437           }
00438 
00439           /* Reset the vehicle's cargo type */
00440           v->cargo_type    = temp_cargo;
00441           v->cargo_subtype = temp_subtype;
00442 
00443           /* And make sure we haven't tainted the cache */
00444           v->First()->InvalidateNewGRFCache();
00445           v->InvalidateNewGRFCache();
00446         } else {
00447           /* No cargo suffix callback -- use no subtype */
00448           RefitOption option;
00449           option.cargo   = cid;
00450           option.subtype = 0;
00451           option.value   = CALLBACK_FAILED;
00452           option.engine  = NULL;
00453           this->list[current_index].Include(option);
00454         }
00455         current_index++;
00456       }
00457     } while (v->IsGroundVehicle() && (v = v->Next()) != NULL);
00458 
00459     int scroll_size = 0;
00460     for (uint i = 0; i < NUM_CARGO; i++) {
00461       scroll_size += (this->list[i].Length());
00462     }
00463     this->vscroll->SetCount(scroll_size);
00464   }
00465 
00470   RefitOption *GetRefitOption()
00471   {
00472     if (this->sel < 0) return NULL;
00473     int subtype = 0;
00474     for (uint i = 0; subtype <= this->sel && i < NUM_CARGO; i++) {
00475       for (uint j = 0; subtype <= this->sel && j < this->list[i].Length(); j++) {
00476         if (subtype == this->sel) {
00477           return &this->list[i][j];
00478         }
00479         subtype++;
00480       }
00481     }
00482 
00483     return NULL;
00484   }
00485 
00486   RefitWindow(const WindowDesc *desc, const Vehicle *v, VehicleOrderID order, bool auto_refit) : Window()
00487   {
00488     this->sel = -1;
00489     this->auto_refit = auto_refit;
00490     this->CreateNestedTree(desc);
00491 
00492     this->vscroll = this->GetScrollbar(WID_VR_SCROLLBAR);
00493     this->hscroll = (v->IsGroundVehicle() ? this->GetScrollbar(WID_VR_HSCROLLBAR) : NULL);
00494     this->GetWidget<NWidgetCore>(WID_VR_SELECT_HEADER)->tool_tip = STR_REFIT_TRAIN_LIST_TOOLTIP + v->type;
00495     this->GetWidget<NWidgetCore>(WID_VR_MATRIX)->tool_tip        = STR_REFIT_TRAIN_LIST_TOOLTIP + v->type;
00496     NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_VR_REFIT);
00497     nwi->widget_data = STR_REFIT_TRAIN_REFIT_BUTTON + v->type;
00498     nwi->tool_tip    = STR_REFIT_TRAIN_REFIT_TOOLTIP + v->type;
00499     this->GetWidget<NWidgetStacked>(WID_VR_SHOW_HSCROLLBAR)->SetDisplayedPlane(v->IsGroundVehicle() ? 0 : SZSP_HORIZONTAL);
00500     this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY)->tool_tip = (v->type == VEH_TRAIN) ? STR_REFIT_SELECT_VEHICLES_TOOLTIP : STR_NULL;
00501 
00502     this->FinishInitNested(desc, v->index);
00503     this->owner = v->owner;
00504 
00505     this->order = order;
00506     this->SetWidgetDisabledState(WID_VR_REFIT, this->sel == -1);
00507   }
00508 
00509   virtual void OnInit()
00510   {
00511     if (this->cargo != NULL) {
00512       /* Store the RefitOption currently in use. */
00513       RefitOption current_refit_option = *(this->cargo);
00514 
00515       /* Rebuild the refit list */
00516       this->BuildRefitList();
00517       this->sel = -1;
00518       this->cargo = NULL;
00519       int current = 0;
00520       for (uint i = 0; this->cargo == NULL && i < NUM_CARGO; i++) {
00521         for (uint j = 0; j < list[i].Length(); j++) {
00522           if (list[i][j] == current_refit_option) {
00523             this->sel = current;
00524             this->cargo = &list[i][j];
00525             this->vscroll->ScrollTowards(current);
00526             break;
00527           }
00528           current++;
00529         }
00530       }
00531 
00532       this->SetWidgetDisabledState(WID_VR_REFIT, this->sel == -1);
00533       /* If the selected refit option was not found, scroll the window to the initial position. */
00534       if (this->sel == -1) this->vscroll->ScrollTowards(0);
00535     } else {
00536       /* Rebuild the refit list */
00537       this->OnInvalidateData(VIWD_CONSIST_CHANGED);
00538     }
00539   }
00540 
00541   virtual void OnPaint()
00542   {
00543     /* Determine amount of items for scroller. */
00544     if (this->hscroll != NULL) this->hscroll->SetCount(this->vehicle_width);
00545 
00546     /* Calculate sprite position. */
00547     NWidgetCore *vehicle_panel_display = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY);
00548     int sprite_width = max(0, ((int)vehicle_panel_display->current_x - this->vehicle_width) / 2);
00549     this->sprite_left = vehicle_panel_display->pos_x;
00550     this->sprite_right = vehicle_panel_display->pos_x + vehicle_panel_display->current_x - 1;
00551     if (_current_text_dir == TD_RTL) {
00552       this->sprite_right -= sprite_width;
00553       this->vehicle_margin = vehicle_panel_display->current_x - sprite_right;
00554     } else {
00555       this->sprite_left += sprite_width;
00556       this->vehicle_margin = sprite_left;
00557     }
00558 
00559     this->DrawWidgets();
00560   }
00561 
00562   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00563   {
00564     switch (widget) {
00565       case WID_VR_MATRIX:
00566         resize->height = WD_MATRIX_TOP + FONT_HEIGHT_NORMAL + WD_MATRIX_BOTTOM;
00567         size->height = resize->height * 8;
00568         break;
00569 
00570       case WID_VR_VEHICLE_PANEL_DISPLAY:
00571         size->height = GetVehicleHeight(Vehicle::Get(this->window_number)->type);
00572         break;
00573 
00574       case WID_VR_INFO:
00575         size->width = WD_FRAMERECT_LEFT + this->information_width + WD_FRAMERECT_RIGHT;
00576         break;
00577     }
00578   }
00579 
00580   virtual void SetStringParameters(int widget) const
00581   {
00582     if (widget == WID_VR_CAPTION) SetDParam(0, Vehicle::Get(this->window_number)->index);
00583   }
00584 
00591   StringID GetCapacityString(RefitOption *option) const
00592   {
00593     assert(_current_company == _local_company);
00594     Vehicle *v = Vehicle::Get(this->window_number);
00595     CommandCost cost = DoCommand(v->tile, this->selected_vehicle, option->cargo | (int)this->auto_refit << 6 | option->subtype << 8 |
00596         this->num_vehicles << 16, DC_QUERY_COST, GetCmdRefitVeh(v->type));
00597 
00598     if (cost.Failed()) return INVALID_STRING_ID;
00599 
00600     SetDParam(0, option->cargo);
00601     SetDParam(1, _returned_refit_capacity);
00602 
00603     Money money = cost.GetCost();
00604     if (_returned_mail_refit_capacity > 0) {
00605       SetDParam(2, CT_MAIL);
00606       SetDParam(3, _returned_mail_refit_capacity);
00607       if (money <= 0) {
00608         SetDParam(4, -money);
00609         return STR_REFIT_NEW_CAPACITY_INCOME_FROM_AIRCRAFT_REFIT;
00610       } else {
00611         SetDParam(4, money);
00612         return STR_REFIT_NEW_CAPACITY_COST_OF_AIRCRAFT_REFIT;
00613       }
00614     } else {
00615       if (money <= 0) {
00616         SetDParam(2, -money);
00617         return STR_REFIT_NEW_CAPACITY_INCOME_FROM_REFIT;
00618       } else {
00619         SetDParam(2, money);
00620         return STR_REFIT_NEW_CAPACITY_COST_OF_REFIT;
00621       }
00622     }
00623   }
00624 
00625   virtual void DrawWidget(const Rect &r, int widget) const
00626   {
00627     switch (widget) {
00628       case WID_VR_VEHICLE_PANEL_DISPLAY: {
00629         Vehicle *v = Vehicle::Get(this->window_number);
00630         DrawVehicleImage(v, this->sprite_left + WD_FRAMERECT_LEFT, this->sprite_right - WD_FRAMERECT_RIGHT,
00631           r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, this->hscroll != NULL ? this->hscroll->GetPosition() : 0);
00632 
00633         /* Highlight selected vehicles. */
00634         if (this->order != INVALID_VEH_ORDER_ID) break;
00635         int x = 0;
00636         switch (v->type) {
00637           case VEH_TRAIN: {
00638             VehicleSet vehicles_to_refit;
00639             GetVehicleSet(vehicles_to_refit, Vehicle::Get(this->selected_vehicle), this->num_vehicles);
00640 
00641             int left = INT32_MIN;
00642             int width = 0;
00643 
00644             for (Train *u = Train::From(v); u != NULL; u = u->Next()) {
00645               /* Start checking. */
00646               if (vehicles_to_refit.Contains(u->index) && left == INT32_MIN) {
00647                 left = x - this->hscroll->GetPosition() + r.left + this->vehicle_margin;
00648                 width = 0;
00649               }
00650 
00651               /* Draw a selection. */
00652               if ((!vehicles_to_refit.Contains(u->index) || u->Next() == NULL) && left != INT32_MIN) {
00653                 if (u->Next() == NULL && vehicles_to_refit.Contains(u->index)) {
00654                   int current_width = u->GetDisplayImageWidth();
00655                   width += current_width;
00656                   x += current_width;
00657                 }
00658 
00659                 int right = Clamp(left + width, 0, r.right);
00660                 left = max(0, left);
00661 
00662                 if (_current_text_dir == TD_RTL) {
00663                   right = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY)->current_x - left;
00664                   left = right - width;
00665                 }
00666 
00667                 if (left != right) {
00668                   DrawFrameRect(left, r.top + WD_FRAMERECT_TOP, right, r.top + WD_FRAMERECT_TOP + 13, COLOUR_WHITE, FR_BORDERONLY);
00669                 }
00670 
00671                 left = INT32_MIN;
00672               }
00673 
00674               int current_width = u->GetDisplayImageWidth();
00675               width += current_width;
00676               x += current_width;
00677             }
00678             break;
00679           }
00680 
00681           default: break;
00682         }
00683         break;
00684       }
00685 
00686       case WID_VR_MATRIX:
00687         DrawVehicleRefitWindow(this->list, this->sel, this->vscroll->GetPosition(), this->vscroll->GetCapacity(), this->resize.step_height, r);
00688         break;
00689 
00690       case WID_VR_INFO:
00691         if (this->cargo != NULL) {
00692           StringID string = this->GetCapacityString(this->cargo);
00693           if (string != INVALID_STRING_ID) {
00694             DrawStringMultiLine(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT,
00695                 r.top + WD_FRAMERECT_TOP, r.bottom - WD_FRAMERECT_BOTTOM, string);
00696           }
00697         }
00698         break;
00699     }
00700   }
00701 
00707   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
00708   {
00709     switch (data) {
00710       case VIWD_AUTOREPLACE: // Autoreplace replaced the vehicle; selected_vehicle became invalid.
00711       case VIWD_CONSIST_CHANGED: { // The consist has changed; rebuild the entire list.
00712         /* Clear the selection. */
00713         Vehicle *v = Vehicle::Get(this->window_number);
00714         this->selected_vehicle = v->index;
00715         this->num_vehicles = UINT8_MAX;
00716         /* FALL THROUGH */
00717       }
00718 
00719       case 2: { // The vehicle selection has changed; rebuild the entire list.
00720         if (!gui_scope) break;
00721         this->BuildRefitList();
00722 
00723         /* The vehicle width has changed too. */
00724         this->vehicle_width = GetVehicleWidth(Vehicle::Get(this->window_number), EIT_IN_DETAILS);
00725         uint max_width = 0;
00726 
00727         /* Check the width of all cargo information strings. */
00728         for (uint i = 0; i < NUM_CARGO; i++) {
00729           for (uint j = 0; j < this->list[i].Length(); j++) {
00730             StringID string = this->GetCapacityString(&list[i][j]);
00731             if (string != INVALID_STRING_ID) {
00732               Dimension dim = GetStringBoundingBox(string);
00733               max_width = max(dim.width, max_width);
00734             }
00735           }
00736         }
00737 
00738         if (this->information_width < max_width) {
00739           this->information_width = max_width;
00740           this->ReInit();
00741         }
00742         /* FALL THROUGH */
00743       }
00744 
00745       case 1: // A new cargo has been selected.
00746         if (!gui_scope) break;
00747         this->cargo = GetRefitOption();
00748         break;
00749     }
00750   }
00751 
00752   int GetClickPosition(int click_x)
00753   {
00754     const NWidgetCore *matrix_widget = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY);
00755     if (_current_text_dir == TD_RTL) click_x = matrix_widget->current_x - click_x;
00756     click_x -= this->vehicle_margin;
00757     if (this->hscroll != NULL) click_x += this->hscroll->GetPosition();
00758 
00759     return click_x;
00760   }
00761 
00762   void SetSelectedVehicles(int drag_x)
00763   {
00764     drag_x = GetClickPosition(drag_x);
00765 
00766     int left_x  = min(this->click_x, drag_x);
00767     int right_x = max(this->click_x, drag_x);
00768     this->num_vehicles = 0;
00769 
00770     Vehicle *v = Vehicle::Get(this->window_number);
00771     /* Find the vehicle part that was clicked. */
00772     switch (v->type) {
00773       case VEH_TRAIN: {
00774         /* Don't select anything if we are not clicking in the vehicle. */
00775         if (left_x >= 0) {
00776           const Train *u = Train::From(v);
00777           bool start_counting = false;
00778           for (; u != NULL; u = u->Next()) {
00779             int current_width = u->GetDisplayImageWidth();
00780             left_x  -= current_width;
00781             right_x -= current_width;
00782 
00783             if (left_x < 0 && !start_counting) {
00784               this->selected_vehicle = u->index;
00785               start_counting = true;
00786 
00787               /* Count the first vehicle, even if articulated part */
00788               this->num_vehicles++;
00789             } else if (start_counting && !u->IsArticulatedPart()) {
00790               /* Do not count articulated parts */
00791               this->num_vehicles++;
00792             }
00793 
00794             if (right_x < 0) break;
00795           }
00796         }
00797 
00798         /* If the selection is not correct, clear it. */
00799         if (this->num_vehicles != 0) {
00800           if (_ctrl_pressed) this->num_vehicles = UINT8_MAX;
00801           break;
00802         }
00803         /* FALL THROUGH */
00804       }
00805 
00806       default:
00807         /* Clear the selection. */
00808         this->selected_vehicle = v->index;
00809         this->num_vehicles = UINT8_MAX;
00810         break;
00811     }
00812   }
00813 
00814   virtual void OnClick(Point pt, int widget, int click_count)
00815   {
00816     switch (widget) {
00817       case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
00818         if (this->order != INVALID_VEH_ORDER_ID) break;
00819         NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
00820         this->click_x = GetClickPosition(pt.x - nwi->pos_x);
00821         this->SetSelectedVehicles(pt.x - nwi->pos_x);
00822         this->SetWidgetDirty(WID_VR_VEHICLE_PANEL_DISPLAY);
00823         if (!_ctrl_pressed) {
00824           SetObjectToPlaceWnd(SPR_CURSOR_MOUSE, PAL_NONE, HT_DRAG, this);
00825         } else {
00826           /* The vehicle selection has changed. */
00827           this->InvalidateData(2);
00828         }
00829         break;
00830       }
00831 
00832       case WID_VR_MATRIX: { // listbox
00833         this->sel = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_VR_MATRIX);
00834         if (this->sel == INT_MAX) this->sel = -1;
00835         this->SetWidgetDisabledState(WID_VR_REFIT, this->sel == -1);
00836         this->InvalidateData(1);
00837 
00838         if (click_count == 1) break;
00839         /* FALL THROUGH */
00840       }
00841 
00842       case WID_VR_REFIT: // refit button
00843         if (this->cargo != NULL) {
00844           const Vehicle *v = Vehicle::Get(this->window_number);
00845 
00846           if (this->order == INVALID_VEH_ORDER_ID) {
00847             bool delete_window = this->selected_vehicle == v->index && this->num_vehicles == UINT8_MAX;
00848             if (DoCommandP(v->tile, this->selected_vehicle, this->cargo->cargo | this->cargo->subtype << 8 | this->num_vehicles << 16, GetCmdRefitVeh(v)) && delete_window) delete this;
00849           } else {
00850             if (DoCommandP(v->tile, v->index, this->cargo->cargo | this->cargo->subtype << 8 | this->order << 16, CMD_ORDER_REFIT)) delete this;
00851           }
00852         }
00853         break;
00854     }
00855   }
00856 
00857   virtual void OnMouseDrag(Point pt, int widget)
00858   {
00859     switch (widget) {
00860       case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
00861         if (this->order != INVALID_VEH_ORDER_ID) break;
00862         NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
00863         this->SetSelectedVehicles(pt.x - nwi->pos_x);
00864         this->SetWidgetDirty(WID_VR_VEHICLE_PANEL_DISPLAY);
00865         break;
00866       }
00867     }
00868   }
00869 
00870   virtual void OnDragDrop(Point pt, int widget)
00871   {
00872     switch (widget) {
00873       case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
00874         if (this->order != INVALID_VEH_ORDER_ID) break;
00875         NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
00876         this->SetSelectedVehicles(pt.x - nwi->pos_x);
00877         this->InvalidateData(2);
00878         break;
00879       }
00880     }
00881   }
00882 
00883   virtual void OnResize()
00884   {
00885     this->vehicle_width = GetVehicleWidth(Vehicle::Get(this->window_number), EIT_IN_DETAILS);
00886     this->vscroll->SetCapacityFromWidget(this, WID_VR_MATRIX);
00887     if (this->hscroll != NULL) this->hscroll->SetCapacityFromWidget(this, WID_VR_VEHICLE_PANEL_DISPLAY);
00888     this->GetWidget<NWidgetCore>(WID_VR_MATRIX)->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
00889   }
00890 };
00891 
00892 static const NWidgetPart _nested_vehicle_refit_widgets[] = {
00893   NWidget(NWID_HORIZONTAL),
00894     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
00895     NWidget(WWT_CAPTION, COLOUR_GREY, WID_VR_CAPTION), SetDataTip(STR_REFIT_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00896   EndContainer(),
00897   /* Vehicle display + scrollbar. */
00898   NWidget(NWID_VERTICAL),
00899     NWidget(WWT_PANEL, COLOUR_GREY, WID_VR_VEHICLE_PANEL_DISPLAY), SetMinimalSize(228, 14), SetResize(1, 0), SetScrollbar(WID_VR_HSCROLLBAR), EndContainer(),
00900     NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VR_SHOW_HSCROLLBAR),
00901       NWidget(NWID_HSCROLLBAR, COLOUR_GREY, WID_VR_HSCROLLBAR),
00902     EndContainer(),
00903   EndContainer(),
00904   NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_VR_SELECT_HEADER), SetDataTip(STR_REFIT_TITLE, STR_NULL), SetResize(1, 0),
00905   /* Matrix + scrollbar. */
00906   NWidget(NWID_HORIZONTAL),
00907     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),
00908     NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VR_SCROLLBAR),
00909   EndContainer(),
00910   NWidget(WWT_PANEL, COLOUR_GREY, WID_VR_INFO), SetMinimalTextLines(2, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM), SetResize(1, 0), EndContainer(),
00911   NWidget(NWID_HORIZONTAL),
00912     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VR_REFIT), SetFill(1, 0), SetResize(1, 0),
00913     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
00914   EndContainer(),
00915 };
00916 
00917 static const WindowDesc _vehicle_refit_desc(
00918   WDP_AUTO, 240, 174,
00919   WC_VEHICLE_REFIT, WC_VEHICLE_VIEW,
00920   WDF_CONSTRUCTION,
00921   _nested_vehicle_refit_widgets, lengthof(_nested_vehicle_refit_widgets)
00922 );
00923 
00931 void ShowVehicleRefitWindow(const Vehicle *v, VehicleOrderID order, Window *parent, bool auto_refit)
00932 {
00933   DeleteWindowById(WC_VEHICLE_REFIT, v->index);
00934   RefitWindow *w = new RefitWindow(&_vehicle_refit_desc, v, order, auto_refit);
00935   w->parent = parent;
00936 }
00937 
00939 uint ShowRefitOptionsList(int left, int right, int y, EngineID engine)
00940 {
00941   /* List of cargo types of this engine */
00942   uint32 cmask = GetUnionOfArticulatedRefitMasks(engine, false);
00943   /* List of cargo types available in this climate */
00944   uint32 lmask = _cargo_mask;
00945 
00946   /* Draw nothing if the engine is not refittable */
00947   if (HasAtMostOneBit(cmask)) return y;
00948 
00949   if (cmask == lmask) {
00950     /* Engine can be refitted to all types in this climate */
00951     SetDParam(0, STR_PURCHASE_INFO_ALL_TYPES);
00952   } else {
00953     /* Check if we are able to refit to more cargo types and unable to. If
00954      * so, invert the cargo types to list those that we can't refit to. */
00955     if (CountBits(cmask ^ lmask) < CountBits(cmask) && CountBits(cmask ^ lmask) <= 7) {
00956       cmask ^= lmask;
00957       SetDParam(0, STR_PURCHASE_INFO_ALL_BUT);
00958     } else {
00959       SetDParam(0, STR_JUST_CARGO_LIST);
00960     }
00961     SetDParam(1, cmask);
00962   }
00963 
00964   return DrawStringMultiLine(left, right, y, INT32_MAX, STR_PURCHASE_INFO_REFITTABLE_TO);
00965 }
00966 
00968 StringID GetCargoSubtypeText(const Vehicle *v)
00969 {
00970   if (HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) {
00971     uint16 cb = GetVehicleCallback(CBID_VEHICLE_CARGO_SUFFIX, 0, 0, v->engine_type, v);
00972     if (cb != CALLBACK_FAILED) {
00973       if (cb > 0x400) ErrorUnknownCallbackResult(v->GetGRFID(), CBID_VEHICLE_CARGO_SUFFIX, cb);
00974       if (cb >= 0x400 || (v->GetGRF()->grf_version < 8 && cb == 0xFF)) cb = CALLBACK_FAILED;
00975     }
00976     if (cb != CALLBACK_FAILED) {
00977       return GetGRFStringID(v->GetGRFID(), 0xD000 + cb);
00978     }
00979   }
00980   return STR_EMPTY;
00981 }
00982 
00984 static int CDECL VehicleNumberSorter(const Vehicle * const *a, const Vehicle * const *b)
00985 {
00986   return (*a)->unitnumber - (*b)->unitnumber;
00987 }
00988 
00990 static int CDECL VehicleNameSorter(const Vehicle * const *a, const Vehicle * const *b)
00991 {
00992   static char last_name[2][64];
00993 
00994   if (*a != _last_vehicle[0]) {
00995     _last_vehicle[0] = *a;
00996     SetDParam(0, (*a)->index);
00997     GetString(last_name[0], STR_VEHICLE_NAME, lastof(last_name[0]));
00998   }
00999 
01000   if (*b != _last_vehicle[1]) {
01001     _last_vehicle[1] = *b;
01002     SetDParam(0, (*b)->index);
01003     GetString(last_name[1], STR_VEHICLE_NAME, lastof(last_name[1]));
01004   }
01005 
01006   int r = strnatcmp(last_name[0], last_name[1]); // Sort by name (natural sorting).
01007   return (r != 0) ? r : VehicleNumberSorter(a, b);
01008 }
01009 
01011 static int CDECL VehicleAgeSorter(const Vehicle * const *a, const Vehicle * const *b)
01012 {
01013   int r = (*a)->age - (*b)->age;
01014   return (r != 0) ? r : VehicleNumberSorter(a, b);
01015 }
01016 
01018 static int CDECL VehicleProfitThisYearSorter(const Vehicle * const *a, const Vehicle * const *b)
01019 {
01020   int r = ClampToI32((*a)->GetDisplayProfitThisYear() - (*b)->GetDisplayProfitThisYear());
01021   return (r != 0) ? r : VehicleNumberSorter(a, b);
01022 }
01023 
01025 static int CDECL VehicleProfitLastYearSorter(const Vehicle * const *a, const Vehicle * const *b)
01026 {
01027   int r = ClampToI32((*a)->GetDisplayProfitLastYear() - (*b)->GetDisplayProfitLastYear());
01028   return (r != 0) ? r : VehicleNumberSorter(a, b);
01029 }
01030 
01032 static int CDECL VehicleCargoSorter(const Vehicle * const *a, const Vehicle * const *b)
01033 {
01034   const Vehicle *v;
01035   CargoArray diff;
01036 
01037   /* Append the cargo of the connected waggons */
01038   for (v = *a; v != NULL; v = v->Next()) diff[v->cargo_type] += v->cargo_cap;
01039   for (v = *b; v != NULL; v = v->Next()) diff[v->cargo_type] -= v->cargo_cap;
01040 
01041   int r = 0;
01042   for (CargoID i = 0; i < NUM_CARGO; i++) {
01043     r = diff[i];
01044     if (r != 0) break;
01045   }
01046 
01047   return (r != 0) ? r : VehicleNumberSorter(a, b);
01048 }
01049 
01051 static int CDECL VehicleReliabilitySorter(const Vehicle * const *a, const Vehicle * const *b)
01052 {
01053   int r = (*a)->reliability - (*b)->reliability;
01054   return (r != 0) ? r : VehicleNumberSorter(a, b);
01055 }
01056 
01058 static int CDECL VehicleMaxSpeedSorter(const Vehicle * const *a, const Vehicle * const *b)
01059 {
01060   int r = (*a)->vcache.cached_max_speed - (*b)->vcache.cached_max_speed;
01061   return (r != 0) ? r : VehicleNumberSorter(a, b);
01062 }
01063 
01065 static int CDECL VehicleModelSorter(const Vehicle * const *a, const Vehicle * const *b)
01066 {
01067   int r = (*a)->engine_type - (*b)->engine_type;
01068   return (r != 0) ? r : VehicleNumberSorter(a, b);
01069 }
01070 
01072 static int CDECL VehicleValueSorter(const Vehicle * const *a, const Vehicle * const *b)
01073 {
01074   const Vehicle *u;
01075   Money diff = 0;
01076 
01077   for (u = *a; u != NULL; u = u->Next()) diff += u->value;
01078   for (u = *b; u != NULL; u = u->Next()) diff -= u->value;
01079 
01080   int r = ClampToI32(diff);
01081   return (r != 0) ? r : VehicleNumberSorter(a, b);
01082 }
01083 
01085 static int CDECL VehicleLengthSorter(const Vehicle * const *a, const Vehicle * const *b)
01086 {
01087   int r = (*a)->GetGroundVehicleCache()->cached_total_length - (*b)->GetGroundVehicleCache()->cached_total_length;
01088   return (r != 0) ? r : VehicleNumberSorter(a, b);
01089 }
01090 
01092 static int CDECL VehicleTimeToLiveSorter(const Vehicle * const *a, const Vehicle * const *b)
01093 {
01094   int r = ClampToI32(((*a)->max_age - (*a)->age) - ((*b)->max_age - (*b)->age));
01095   return (r != 0) ? r : VehicleNumberSorter(a, b);
01096 }
01097 
01099 static int CDECL VehicleTimetableDelaySorter(const Vehicle * const *a, const Vehicle * const *b)
01100 {
01101   int r = (*a)->lateness_counter - (*b)->lateness_counter;
01102   return (r != 0) ? r : VehicleNumberSorter(a, b);
01103 }
01104 
01105 void InitializeGUI()
01106 {
01107   MemSetT(&_sorting, 0);
01108 }
01109 
01116 static inline void ChangeVehicleWindow(WindowClass window_class, VehicleID from_index, VehicleID to_index)
01117 {
01118   Window *w = FindWindowById(window_class, from_index);
01119   if (w != NULL) {
01120     /* Update window_number */
01121     w->window_number = to_index;
01122     if (w->viewport != NULL) w->viewport->follow_vehicle = to_index;
01123 
01124     /* Update vehicle drag data */
01125     if (_thd.window_class == window_class && _thd.window_number == (WindowNumber)from_index) {
01126       _thd.window_number = to_index;
01127     }
01128 
01129     /* Notify the window. */
01130     w->InvalidateData(VIWD_AUTOREPLACE, false);
01131   }
01132 }
01133 
01139 void ChangeVehicleViewWindow(VehicleID from_index, VehicleID to_index)
01140 {
01141   ChangeVehicleWindow(WC_VEHICLE_VIEW,      from_index, to_index);
01142   ChangeVehicleWindow(WC_VEHICLE_ORDERS,    from_index, to_index);
01143   ChangeVehicleWindow(WC_VEHICLE_REFIT,     from_index, to_index);
01144   ChangeVehicleWindow(WC_VEHICLE_DETAILS,   from_index, to_index);
01145   ChangeVehicleWindow(WC_VEHICLE_TIMETABLE, from_index, to_index);
01146 }
01147 
01148 static const NWidgetPart _nested_vehicle_list[] = {
01149   NWidget(NWID_HORIZONTAL),
01150     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
01151     NWidget(WWT_CAPTION, COLOUR_GREY, WID_VL_CAPTION),
01152     NWidget(WWT_SHADEBOX, COLOUR_GREY),
01153     NWidget(WWT_STICKYBOX, COLOUR_GREY),
01154   EndContainer(),
01155 
01156   NWidget(NWID_HORIZONTAL),
01157     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VL_SORT_ORDER), SetMinimalSize(81, 12), SetFill(0, 1), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
01158     NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_SORT_BY_PULLDOWN), SetMinimalSize(167, 12), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
01159     NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(12, 12), SetFill(1, 1), SetResize(1, 0),
01160     EndContainer(),
01161   EndContainer(),
01162 
01163   NWidget(NWID_HORIZONTAL),
01164     NWidget(WWT_MATRIX, COLOUR_GREY, WID_VL_LIST), SetMinimalSize(248, 0), SetFill(1, 0), SetResize(1, 1), SetScrollbar(WID_VL_SCROLLBAR),
01165     NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VL_SCROLLBAR),
01166   EndContainer(),
01167 
01168   NWidget(NWID_HORIZONTAL),
01169     NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VL_HIDE_BUTTONS),
01170       NWidget(NWID_HORIZONTAL),
01171         NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VL_AVAILABLE_VEHICLES), SetMinimalSize(106, 12), SetFill(0, 1),
01172                 SetDataTip(STR_BLACK_STRING, STR_VEHICLE_LIST_AVAILABLE_ENGINES_TOOLTIP),
01173         NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(0, 12), SetResize(1, 0), SetFill(1, 1), EndContainer(),
01174         NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_MANAGE_VEHICLES_DROPDOWN), SetMinimalSize(118, 12), SetFill(0, 1),
01175                 SetDataTip(STR_VEHICLE_LIST_MANAGE_LIST, STR_VEHICLE_LIST_MANAGE_LIST_TOOLTIP),
01176         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VL_STOP_ALL), SetMinimalSize(12, 12), SetFill(0, 1),
01177                 SetDataTip(SPR_FLAG_VEH_STOPPED, STR_VEHICLE_LIST_MASS_STOP_LIST_TOOLTIP),
01178         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VL_START_ALL), SetMinimalSize(12, 12), SetFill(0, 1),
01179                 SetDataTip(SPR_FLAG_VEH_RUNNING, STR_VEHICLE_LIST_MASS_START_LIST_TOOLTIP),
01180       EndContainer(),
01181       /* Widget to be shown for other companies hiding the previous 5 widgets. */
01182       NWidget(WWT_PANEL, COLOUR_GREY), SetFill(1, 1), SetResize(1, 0), EndContainer(),
01183     EndContainer(),
01184     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
01185   EndContainer(),
01186 };
01187 
01188 static void DrawSmallOrderList(const Vehicle *v, int left, int right, int y, VehicleOrderID start = 0)
01189 {
01190   const Order *order = v->GetOrder(start);
01191   if (order == NULL) return;
01192 
01193   int i = 0;
01194   VehicleOrderID oid = start;
01195 
01196   do {
01197     if (oid == v->cur_real_order_index) DrawString(left, right, y, STR_TINY_RIGHT_ARROW, TC_BLACK);
01198 
01199     if (order->IsType(OT_GOTO_STATION)) {
01200       SetDParam(0, order->GetDestination());
01201       DrawString(left + 6, right - 6, y, STR_TINY_BLACK_STATION);
01202 
01203       y += FONT_HEIGHT_SMALL;
01204       if (++i == 4) break;
01205     }
01206 
01207     oid++;
01208     order = order->next;
01209     if (order == NULL) {
01210       order = v->orders.list->GetFirstOrder();
01211       oid = 0;
01212     }
01213   } while (oid != start);
01214 }
01215 
01225 void DrawVehicleImage(const Vehicle *v, int left, int right, int y, VehicleID selection, EngineImageType image_type, int skip)
01226 {
01227   switch (v->type) {
01228     case VEH_TRAIN:    DrawTrainImage(Train::From(v), left, right, y, selection, image_type, skip); break;
01229     case VEH_ROAD:     DrawRoadVehImage(v, left, right, y, selection, image_type, skip);  break;
01230     case VEH_SHIP:     DrawShipImage(v, left, right, y, selection, image_type);     break;
01231     case VEH_AIRCRAFT: DrawAircraftImage(v, left, right, y, selection, image_type); break;
01232     default: NOT_REACHED();
01233   }
01234 }
01235 
01242 uint GetVehicleListHeight(VehicleType type, uint divisor)
01243 {
01244   /* Name + vehicle + profit */
01245   uint base = GetVehicleHeight(type) + 2 * FONT_HEIGHT_SMALL;
01246   /* Drawing of the 4 small orders + profit*/
01247   if (type >= VEH_SHIP) base = max(base, 5U * FONT_HEIGHT_SMALL);
01248 
01249   if (divisor == 1) return base;
01250 
01251   /* Make sure the height is dividable by divisor */
01252   uint rem = base % divisor;
01253   return base + (rem == 0 ? 0 : divisor - rem);
01254 }
01255 
01262 void BaseVehicleListWindow::DrawVehicleListItems(VehicleID selected_vehicle, int line_height, const Rect &r) const
01263 {
01264   int left = r.left + WD_MATRIX_LEFT;
01265   int right = r.right - WD_MATRIX_RIGHT;
01266   int width = right - left;
01267   bool rtl = _current_text_dir == TD_RTL;
01268 
01269   int text_offset = GetDigitWidth() * this->unitnumber_digits + WD_FRAMERECT_RIGHT;
01270   int text_left  = left  + (rtl ?           0 : text_offset);
01271   int text_right = right - (rtl ? text_offset :           0);
01272 
01273   bool show_orderlist = this->vli.vtype >= VEH_SHIP;
01274   int orderlist_left  = left  + (rtl ? 0 : max(100 + text_offset, width / 2));
01275   int orderlist_right = right - (rtl ? max(100 + text_offset, width / 2) : 0);
01276 
01277   int image_left  = (rtl && show_orderlist) ? orderlist_right : text_left;
01278   int image_right = (!rtl && show_orderlist) ? orderlist_left : text_right;
01279 
01280   int vehicle_button_x = rtl ? right - GetSpriteSize(SPR_PROFIT_LOT).width : left;
01281 
01282   int y = r.top;
01283   uint max = min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->vehicles.Length());
01284   for (uint i = this->vscroll->GetPosition(); i < max; ++i) {
01285     const Vehicle *v = this->vehicles[i];
01286     StringID str;
01287 
01288     SetDParam(0, v->GetDisplayProfitThisYear());
01289     SetDParam(1, v->GetDisplayProfitLastYear());
01290 
01291     DrawVehicleImage(v, image_left, image_right, y + FONT_HEIGHT_SMALL - 1, selected_vehicle, EIT_IN_LIST, 0);
01292     DrawString(text_left, text_right, y + line_height - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1, STR_VEHICLE_LIST_PROFIT_THIS_YEAR_LAST_YEAR);
01293 
01294     if (v->name != NULL) {
01295       /* The vehicle got a name so we will print it */
01296       SetDParam(0, v->index);
01297       DrawString(text_left, text_right, y, STR_TINY_BLACK_VEHICLE);
01298     } else if (v->group_id != DEFAULT_GROUP) {
01299       /* The vehicle has no name, but is member of a group, so print group name */
01300       SetDParam(0, v->group_id);
01301       DrawString(text_left, text_right, y, STR_TINY_GROUP, TC_BLACK);
01302     }
01303 
01304     if (show_orderlist) DrawSmallOrderList(v, orderlist_left, orderlist_right, y, v->cur_real_order_index);
01305 
01306     if (v->IsChainInDepot()) {
01307       str = STR_BLUE_COMMA;
01308     } else {
01309       str = (v->age > v->max_age - DAYS_IN_LEAP_YEAR) ? STR_RED_COMMA : STR_BLACK_COMMA;
01310     }
01311 
01312     SetDParam(0, v->unitnumber);
01313     DrawString(left, right, y + 2, str);
01314 
01315     DrawVehicleProfitButton(v, vehicle_button_x, y + FONT_HEIGHT_NORMAL + 3);
01316 
01317     y += line_height;
01318   }
01319 }
01320 
01330 struct VehicleListWindow : public BaseVehicleListWindow {
01331 private:
01333   enum ButtonPlanes {
01334     BP_SHOW_BUTTONS, 
01335     BP_HIDE_BUTTONS, 
01336   };
01337 
01338 public:
01339   VehicleListWindow(const WindowDesc *desc, WindowNumber window_number) : BaseVehicleListWindow(window_number)
01340   {
01341     /* Set up sorting. Make the window-specific _sorting variable
01342      * point to the correct global _sorting struct so we are freed
01343      * from having conditionals during window operation */
01344     switch (this->vli.vtype) {
01345       case VEH_TRAIN:    this->sorting = &_sorting.train; break;
01346       case VEH_ROAD:     this->sorting = &_sorting.roadveh; break;
01347       case VEH_SHIP:     this->sorting = &_sorting.ship; break;
01348       case VEH_AIRCRAFT: this->sorting = &_sorting.aircraft; break;
01349       default: NOT_REACHED();
01350     }
01351 
01352     this->CreateNestedTree(desc);
01353 
01354     this->vscroll = this->GetScrollbar(WID_VL_SCROLLBAR);
01355 
01356     this->vehicles.SetListing(*this->sorting);
01357     this->vehicles.ForceRebuild();
01358     this->vehicles.NeedResort();
01359     this->BuildVehicleList();
01360     this->SortVehicleList();
01361 
01362     /* Set up the window widgets */
01363     this->GetWidget<NWidgetCore>(WID_VL_LIST)->tool_tip = STR_VEHICLE_LIST_TRAIN_LIST_TOOLTIP + this->vli.vtype;
01364 
01365     if (this->vli.type == VL_SHARED_ORDERS) {
01366       this->GetWidget<NWidgetCore>(WID_VL_CAPTION)->widget_data = STR_VEHICLE_LIST_SHARED_ORDERS_LIST_CAPTION;
01367     } else {
01368       this->GetWidget<NWidgetCore>(WID_VL_CAPTION)->widget_data = STR_VEHICLE_LIST_TRAIN_CAPTION + this->vli.vtype;
01369     }
01370 
01371     this->FinishInitNested(desc, window_number);
01372     if (this->vli.company != OWNER_NONE) this->owner = this->vli.company;
01373 
01374     if (this->vli.vtype == VEH_TRAIN) ResizeWindow(this, 65, 0);
01375   }
01376 
01377   ~VehicleListWindow()
01378   {
01379     *this->sorting = this->vehicles.GetListing();
01380   }
01381 
01382   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01383   {
01384     switch (widget) {
01385       case WID_VL_LIST:
01386         resize->height = GetVehicleListHeight(this->vli.vtype, 1);
01387 
01388         switch (this->vli.vtype) {
01389           case VEH_TRAIN:
01390           case VEH_ROAD:
01391             size->height = 6 * resize->height;
01392             break;
01393           case VEH_SHIP:
01394           case VEH_AIRCRAFT:
01395             size->height = 4 * resize->height;
01396             break;
01397           default: NOT_REACHED();
01398         }
01399         break;
01400 
01401       case WID_VL_SORT_ORDER: {
01402         Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
01403         d.width += padding.width + WD_SORTBUTTON_ARROW_WIDTH * 2; // Doubled since the string is centred and it also looks better.
01404         d.height += padding.height;
01405         *size = maxdim(*size, d);
01406         break;
01407       }
01408 
01409       case WID_VL_MANAGE_VEHICLES_DROPDOWN: {
01410         Dimension d = this->GetActionDropdownSize(this->vli.type == VL_STANDARD, false);
01411         d.height += padding.height;
01412         d.width  += padding.width;
01413         *size = maxdim(*size, d);
01414         break;
01415       }
01416     }
01417   }
01418 
01419   virtual void SetStringParameters(int widget) const
01420   {
01421     switch (widget) {
01422       case WID_VL_AVAILABLE_VEHICLES:
01423         SetDParam(0, STR_VEHICLE_LIST_AVAILABLE_TRAINS + this->vli.vtype);
01424         break;
01425 
01426       case WID_VL_CAPTION: {
01427         switch (this->vli.type) {
01428           case VL_SHARED_ORDERS: // Shared Orders
01429             if (this->vehicles.Length() == 0) {
01430               /* We can't open this window without vehicles using this order
01431                * and we should close the window when deleting the order. */
01432               NOT_REACHED();
01433             }
01434             SetDParam(0, this->vscroll->GetCount());
01435             break;
01436 
01437           case VL_STANDARD: // Company Name
01438             SetDParam(0, STR_COMPANY_NAME);
01439             SetDParam(1, this->vli.index);
01440             SetDParam(3, this->vscroll->GetCount());
01441             break;
01442 
01443           case VL_STATION_LIST: // Station/Waypoint Name
01444             SetDParam(0, Station::IsExpected(BaseStation::Get(this->vli.index)) ? STR_STATION_NAME : STR_WAYPOINT_NAME);
01445             SetDParam(1, this->vli.index);
01446             SetDParam(3, this->vscroll->GetCount());
01447             break;
01448 
01449           case VL_DEPOT_LIST:
01450             SetDParam(0, STR_DEPOT_CAPTION);
01451             SetDParam(1, this->vli.vtype);
01452             SetDParam(2, this->vli.index);
01453             SetDParam(3, this->vscroll->GetCount());
01454             break;
01455           default: NOT_REACHED();
01456         }
01457         break;
01458       }
01459     }
01460   }
01461 
01462   virtual void DrawWidget(const Rect &r, int widget) const
01463   {
01464     switch (widget) {
01465       case WID_VL_SORT_ORDER:
01466         /* draw arrow pointing up/down for ascending/descending sorting */
01467         this->DrawSortButtonState(widget, this->vehicles.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
01468         break;
01469 
01470       case WID_VL_LIST:
01471         this->DrawVehicleListItems(INVALID_VEHICLE, this->resize.step_height, r);
01472         break;
01473     }
01474   }
01475 
01476   virtual void OnPaint()
01477   {
01478     this->BuildVehicleList();
01479     this->SortVehicleList();
01480 
01481     if (this->vehicles.Length() == 0 && this->IsWidgetLowered(WID_VL_MANAGE_VEHICLES_DROPDOWN)) {
01482       HideDropDownMenu(this);
01483     }
01484 
01485     /* Hide the widgets that we will not use in this window
01486      * Some windows contains actions only fit for the owner */
01487     int plane_to_show = (this->owner == _local_company) ? BP_SHOW_BUTTONS : BP_HIDE_BUTTONS;
01488     NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VL_HIDE_BUTTONS);
01489     if (plane_to_show != nwi->shown_plane) {
01490       nwi->SetDisplayedPlane(plane_to_show);
01491       nwi->SetDirty(this);
01492     }
01493     if (this->owner == _local_company) {
01494       this->SetWidgetDisabledState(WID_VL_AVAILABLE_VEHICLES, this->vli.type != VL_STANDARD);
01495       this->SetWidgetsDisabledState(this->vehicles.Length() == 0,
01496         WID_VL_MANAGE_VEHICLES_DROPDOWN,
01497         WID_VL_STOP_ALL,
01498         WID_VL_START_ALL,
01499         WIDGET_LIST_END);
01500     }
01501 
01502     /* Set text of sort by dropdown widget. */
01503     this->GetWidget<NWidgetCore>(WID_VL_SORT_BY_PULLDOWN)->widget_data = this->vehicle_sorter_names[this->vehicles.SortType()];
01504 
01505     this->DrawWidgets();
01506   }
01507 
01508   virtual void OnClick(Point pt, int widget, int click_count)
01509   {
01510     switch (widget) {
01511       case WID_VL_SORT_ORDER: // Flip sorting method ascending/descending
01512         this->vehicles.ToggleSortOrder();
01513         this->SetDirty();
01514         break;
01515 
01516       case WID_VL_SORT_BY_PULLDOWN:// Select sorting criteria dropdown menu
01517         ShowDropDownMenu(this, this->vehicle_sorter_names, this->vehicles.SortType(), WID_VL_SORT_BY_PULLDOWN, 0,
01518             (this->vli.vtype == VEH_TRAIN || this->vli.vtype == VEH_ROAD) ? 0 : (1 << 10));
01519         return;
01520 
01521       case WID_VL_LIST: { // Matrix to show vehicles
01522         uint id_v = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_VL_LIST);
01523         if (id_v >= this->vehicles.Length()) return; // click out of list bound
01524 
01525         const Vehicle *v = this->vehicles[id_v];
01526         if (!VehicleClicked(v)) ShowVehicleViewWindow(v);
01527         break;
01528       }
01529 
01530       case WID_VL_AVAILABLE_VEHICLES:
01531         ShowBuildVehicleWindow(INVALID_TILE, this->vli.vtype);
01532         break;
01533 
01534       case WID_VL_MANAGE_VEHICLES_DROPDOWN: {
01535         DropDownList *list = this->BuildActionDropdownList(VehicleListIdentifier(this->window_number).type == VL_STANDARD, false);
01536         ShowDropDownList(this, list, 0, WID_VL_MANAGE_VEHICLES_DROPDOWN);
01537         break;
01538       }
01539 
01540       case WID_VL_STOP_ALL:
01541       case WID_VL_START_ALL:
01542         DoCommandP(0, (1 << 1) | (widget == WID_VL_START_ALL ? (1 << 0) : 0), this->window_number, CMD_MASS_START_STOP);
01543         break;
01544     }
01545   }
01546 
01547   virtual void OnDropdownSelect(int widget, int index)
01548   {
01549     switch (widget) {
01550       case WID_VL_SORT_BY_PULLDOWN:
01551         this->vehicles.SetSortType(index);
01552         break;
01553       case WID_VL_MANAGE_VEHICLES_DROPDOWN:
01554         assert(this->vehicles.Length() != 0);
01555 
01556         switch (index) {
01557           case ADI_REPLACE: // Replace window
01558             ShowReplaceGroupVehicleWindow(ALL_GROUP, this->vli.vtype);
01559             break;
01560           case ADI_SERVICE: // Send for servicing
01561           case ADI_DEPOT: // Send to Depots
01562             DoCommandP(0, DEPOT_MASS_SEND | (index == ADI_SERVICE ? DEPOT_SERVICE : (DepotCommand)0), this->window_number, GetCmdSendToDepot(this->vli.vtype));
01563             break;
01564 
01565           default: NOT_REACHED();
01566         }
01567         break;
01568       default: NOT_REACHED();
01569     }
01570     this->SetDirty();
01571   }
01572 
01573   virtual void OnTick()
01574   {
01575     if (_pause_mode != PM_UNPAUSED) return;
01576     if (this->vehicles.NeedResort()) {
01577       StationID station = (this->vli.type == VL_STATION_LIST) ? this->vli.index : INVALID_STATION;
01578 
01579       DEBUG(misc, 3, "Periodic resort %d list company %d at station %d", this->vli.vtype, this->owner, station);
01580       this->SetDirty();
01581     }
01582   }
01583 
01584   virtual void OnResize()
01585   {
01586     this->vscroll->SetCapacityFromWidget(this, WID_VL_LIST);
01587     this->GetWidget<NWidgetCore>(WID_VL_LIST)->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
01588   }
01589 
01595   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
01596   {
01597     if (!gui_scope && HasBit(data, 31) && this->vli.type == VL_SHARED_ORDERS) {
01598       /* Needs to be done in command-scope, so everything stays valid */
01599       this->vli.index = GB(data, 0, 20);
01600       this->window_number = this->vli.Pack();
01601       this->vehicles.ForceRebuild();
01602       return;
01603     }
01604 
01605     if (data == 0) {
01606       /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
01607       this->vehicles.ForceRebuild();
01608     } else {
01609       this->vehicles.ForceResort();
01610     }
01611   }
01612 };
01613 
01614 static WindowDesc _vehicle_list_desc(
01615   WDP_AUTO, 260, 246,
01616   WC_INVALID, WC_NONE,
01617   0,
01618   _nested_vehicle_list, lengthof(_nested_vehicle_list)
01619 );
01620 
01621 static void ShowVehicleListWindowLocal(CompanyID company, VehicleListType vlt, VehicleType vehicle_type, uint16 unique_number)
01622 {
01623   if (!Company::IsValidID(company) && company != OWNER_NONE) return;
01624 
01625   _vehicle_list_desc.cls = GetWindowClassForVehicleType(vehicle_type);
01626   AllocateWindowDescFront<VehicleListWindow>(&_vehicle_list_desc, VehicleListIdentifier(vlt, vehicle_type, company, unique_number).Pack());
01627 }
01628 
01629 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type)
01630 {
01631   /* If _settings_client.gui.advanced_vehicle_list > 1, display the Advanced list
01632    * if _settings_client.gui.advanced_vehicle_list == 1, display Advanced list only for local company
01633    * if _ctrl_pressed, do the opposite action (Advanced list x Normal list)
01634    */
01635 
01636   if ((_settings_client.gui.advanced_vehicle_list > (uint)(company != _local_company)) != _ctrl_pressed) {
01637     ShowCompanyGroup(company, vehicle_type);
01638   } else {
01639     ShowVehicleListWindowLocal(company, VL_STANDARD, vehicle_type, company);
01640   }
01641 }
01642 
01643 void ShowVehicleListWindow(const Vehicle *v)
01644 {
01645   ShowVehicleListWindowLocal(v->owner, VL_SHARED_ORDERS, v->type, v->FirstShared()->index);
01646 }
01647 
01648 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, StationID station)
01649 {
01650   _vehicle_list_desc.flags &= ~WDF_CONSTRUCTION;
01651   ShowVehicleListWindowLocal(company, VL_STATION_LIST, vehicle_type, station);
01652 }
01653 
01654 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, TileIndex depot_tile)
01655 {
01656   uint16 depot_airport_index;
01657 
01658   if (vehicle_type == VEH_AIRCRAFT) {
01659     depot_airport_index = GetStationIndex(depot_tile);
01660   } else {
01661     depot_airport_index = GetDepotIndex(depot_tile);
01662   }
01663   ShowVehicleListWindowLocal(company, VL_DEPOT_LIST, vehicle_type, depot_airport_index);
01664 }
01665 
01666 
01667 /* Unified vehicle GUI - Vehicle Details Window */
01668 
01669 assert_compile(WID_VD_DETAILS_CARGO_CARRIED    == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_CARGO   );
01670 assert_compile(WID_VD_DETAILS_TRAIN_VEHICLES   == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_INFO    );
01671 assert_compile(WID_VD_DETAILS_CAPACITY_OF_EACH == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_CAPACITY);
01672 assert_compile(WID_VD_DETAILS_TOTAL_CARGO      == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_TOTALS  );
01673 
01675 static const NWidgetPart _nested_nontrain_vehicle_details_widgets[] = {
01676   NWidget(NWID_HORIZONTAL),
01677     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
01678     NWidget(WWT_CAPTION, COLOUR_GREY, WID_VD_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
01679     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 */),
01680     NWidget(WWT_SHADEBOX, COLOUR_GREY),
01681     NWidget(WWT_STICKYBOX, COLOUR_GREY),
01682   EndContainer(),
01683   NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_TOP_DETAILS), SetMinimalSize(405, 42), SetResize(1, 0), EndContainer(),
01684   NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_MIDDLE_DETAILS), SetMinimalSize(405, 45), SetResize(1, 0), EndContainer(),
01685   NWidget(NWID_HORIZONTAL),
01686     NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_DECREASE_SERVICING_INTERVAL), SetFill(0, 1),
01687         SetDataTip(AWV_DECREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
01688     NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_INCREASE_SERVICING_INTERVAL), SetFill(0, 1),
01689         SetDataTip(AWV_INCREASE, STR_VEHICLE_DETAILS_INCREASE_SERVICING_INTERVAL_TOOLTIP),
01690     NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_SERVICING_INTERVAL), SetFill(1, 1), SetResize(1, 0), EndContainer(),
01691     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
01692   EndContainer(),
01693 };
01694 
01696 static const NWidgetPart _nested_train_vehicle_details_widgets[] = {
01697   NWidget(NWID_HORIZONTAL),
01698     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
01699     NWidget(WWT_CAPTION, COLOUR_GREY, WID_VD_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
01700     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 */),
01701     NWidget(WWT_SHADEBOX, COLOUR_GREY),
01702     NWidget(WWT_STICKYBOX, COLOUR_GREY),
01703   EndContainer(),
01704   NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_TOP_DETAILS), SetResize(1, 0), SetMinimalSize(405, 42), EndContainer(),
01705   NWidget(NWID_HORIZONTAL),
01706     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),
01707     NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VD_SCROLLBAR),
01708   EndContainer(),
01709   NWidget(NWID_HORIZONTAL),
01710     NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_DECREASE_SERVICING_INTERVAL), SetFill(0, 1),
01711         SetDataTip(AWV_DECREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
01712     NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_INCREASE_SERVICING_INTERVAL), SetFill(0, 1),
01713         SetDataTip(AWV_INCREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
01714     NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_SERVICING_INTERVAL), SetFill(1, 1), SetResize(1, 0), EndContainer(),
01715   EndContainer(),
01716   NWidget(NWID_HORIZONTAL),
01717     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_CARGO_CARRIED), SetMinimalSize(96, 12),
01718         SetDataTip(STR_VEHICLE_DETAIL_TAB_CARGO, STR_VEHICLE_DETAILS_TRAIN_CARGO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
01719     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_TRAIN_VEHICLES), SetMinimalSize(99, 12),
01720         SetDataTip(STR_VEHICLE_DETAIL_TAB_INFORMATION, STR_VEHICLE_DETAILS_TRAIN_INFORMATION_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
01721     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_CAPACITY_OF_EACH), SetMinimalSize(99, 12),
01722         SetDataTip(STR_VEHICLE_DETAIL_TAB_CAPACITIES, STR_VEHICLE_DETAILS_TRAIN_CAPACITIES_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
01723     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_TOTAL_CARGO), SetMinimalSize(99, 12),
01724         SetDataTip(STR_VEHICLE_DETAIL_TAB_TOTAL_CARGO, STR_VEHICLE_DETAILS_TRAIN_TOTAL_CARGO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
01725     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
01726   EndContainer(),
01727 };
01728 
01729 
01730 extern int GetTrainDetailsWndVScroll(VehicleID veh_id, TrainDetailsWindowTabs det_tab);
01731 extern void DrawTrainDetails(const Train *v, int left, int right, int y, int vscroll_pos, uint16 vscroll_cap, TrainDetailsWindowTabs det_tab);
01732 extern void DrawRoadVehDetails(const Vehicle *v, int left, int right, int y);
01733 extern void DrawShipDetails(const Vehicle *v, int left, int right, int y);
01734 extern void DrawAircraftDetails(const Aircraft *v, int left, int right, int y);
01735 
01737 struct VehicleDetailsWindow : Window {
01738   TrainDetailsWindowTabs tab; 
01739   Scrollbar *vscroll;
01740 
01742   VehicleDetailsWindow(const WindowDesc *desc, WindowNumber window_number) : Window()
01743   {
01744     const Vehicle *v = Vehicle::Get(window_number);
01745 
01746     this->CreateNestedTree(desc);
01747     this->vscroll = (v->type == VEH_TRAIN ? this->GetScrollbar(WID_VD_SCROLLBAR) : NULL);
01748     this->FinishInitNested(desc, window_number);
01749 
01750     this->GetWidget<NWidgetCore>(WID_VD_RENAME_VEHICLE)->tool_tip = STR_VEHICLE_DETAILS_TRAIN_RENAME + v->type;
01751 
01752     this->owner = v->owner;
01753     this->tab = TDW_TAB_CARGO;
01754   }
01755 
01761   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
01762   {
01763     if (data == VIWD_AUTOREPLACE) {
01764       /* Autoreplace replaced the vehicle.
01765        * Nothing to do for this window. */
01766       return;
01767     }
01768     if (!gui_scope) return;
01769     const Vehicle *v = Vehicle::Get(this->window_number);
01770     if (v->type == VEH_ROAD) {
01771       const NWidgetBase *nwid_info = this->GetWidget<NWidgetBase>(WID_VD_MIDDLE_DETAILS);
01772       uint aimed_height = this->GetRoadVehDetailsHeight(v);
01773       /* If the number of articulated parts changes, the size of the window must change too. */
01774       if (aimed_height != nwid_info->current_y) {
01775         this->ReInit();
01776       }
01777     }
01778   }
01779 
01785   uint GetRoadVehDetailsHeight(const Vehicle *v)
01786   {
01787     uint desired_height;
01788     if (v->HasArticulatedPart()) {
01789       /* An articulated RV has its text drawn under the sprite instead of after it, hence 15 pixels extra. */
01790       desired_height = WD_FRAMERECT_TOP + 15 + 3 * FONT_HEIGHT_NORMAL + 2 + WD_FRAMERECT_BOTTOM;
01791       /* Add space for the cargo amount for each part. */
01792       for (const Vehicle *u = v; u != NULL; u = u->Next()) {
01793         if (u->cargo_cap != 0) desired_height += FONT_HEIGHT_NORMAL + 1;
01794       }
01795     } else {
01796       desired_height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + 3 + WD_FRAMERECT_BOTTOM;
01797     }
01798     return desired_height;
01799   }
01800 
01801   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01802   {
01803     switch (widget) {
01804       case WID_VD_TOP_DETAILS: {
01805         Dimension dim = { 0, 0 };
01806         size->height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
01807 
01808         for (uint i = 0; i < 4; i++) SetDParamMaxValue(i, INT16_MAX);
01809         static const StringID info_strings[] = {
01810           STR_VEHICLE_INFO_MAX_SPEED,
01811           STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED,
01812           STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE,
01813           STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR,
01814           STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS
01815         };
01816         for (uint i = 0; i < lengthof(info_strings); i++) {
01817           dim = maxdim(dim, GetStringBoundingBox(info_strings[i]));
01818         }
01819         SetDParam(0, STR_VEHICLE_INFO_AGE);
01820         dim = maxdim(dim, GetStringBoundingBox(STR_VEHICLE_INFO_AGE_RUNNING_COST_YR));
01821         size->width = dim.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
01822         break;
01823       }
01824 
01825       case WID_VD_MIDDLE_DETAILS: {
01826         const Vehicle *v = Vehicle::Get(this->window_number);
01827         switch (v->type) {
01828           case VEH_ROAD:
01829             size->height = this->GetRoadVehDetailsHeight(v);
01830             break;
01831 
01832           case VEH_SHIP:
01833             size->height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + 3 + WD_FRAMERECT_BOTTOM;
01834             break;
01835 
01836           case VEH_AIRCRAFT:
01837             size->height = WD_FRAMERECT_TOP + 5 * FONT_HEIGHT_NORMAL + 4 + WD_FRAMERECT_BOTTOM;
01838             break;
01839 
01840           default:
01841             NOT_REACHED(); // Train uses WID_VD_MATRIX instead.
01842         }
01843         break;
01844       }
01845 
01846       case WID_VD_MATRIX:
01847         resize->height = WD_MATRIX_TOP + FONT_HEIGHT_NORMAL + WD_MATRIX_BOTTOM;
01848         size->height = 4 * resize->height;
01849         break;
01850 
01851       case WID_VD_SERVICING_INTERVAL:
01852         SetDParamMaxValue(0, MAX_SERVINT_DAYS); // Roughly the maximum interval
01853         SetDParamMaxValue(1, MAX_YEAR * DAYS_IN_YEAR); // Roughly the maximum year
01854         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;
01855         size->height = WD_FRAMERECT_TOP + FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
01856         break;
01857     }
01858   }
01859 
01861   static bool IsVehicleServiceIntervalEnabled(const VehicleType vehicle_type, CompanyID company_id)
01862   {
01863     const VehicleDefaultSettings *vds = &Company::Get(company_id)->settings.vehicle;
01864     switch (vehicle_type) {
01865       default: NOT_REACHED();
01866       case VEH_TRAIN:    return vds->servint_trains   != 0;
01867       case VEH_ROAD:     return vds->servint_roadveh  != 0;
01868       case VEH_SHIP:     return vds->servint_ships    != 0;
01869       case VEH_AIRCRAFT: return vds->servint_aircraft != 0;
01870     }
01871   }
01872 
01884   static void DrawVehicleDetails(const Vehicle *v, int left, int right, int y, int vscroll_pos, uint vscroll_cap, TrainDetailsWindowTabs det_tab)
01885   {
01886     switch (v->type) {
01887       case VEH_TRAIN:    DrawTrainDetails(Train::From(v), left, right, y, vscroll_pos, vscroll_cap, det_tab);  break;
01888       case VEH_ROAD:     DrawRoadVehDetails(v, left, right, y);  break;
01889       case VEH_SHIP:     DrawShipDetails(v, left, right, y);     break;
01890       case VEH_AIRCRAFT: DrawAircraftDetails(Aircraft::From(v), left, right, y); break;
01891       default: NOT_REACHED();
01892     }
01893   }
01894 
01895   virtual void SetStringParameters(int widget) const
01896   {
01897     if (widget == WID_VD_CAPTION) SetDParam(0, Vehicle::Get(this->window_number)->index);
01898   }
01899 
01900   virtual void DrawWidget(const Rect &r, int widget) const
01901   {
01902     const Vehicle *v = Vehicle::Get(this->window_number);
01903 
01904     switch (widget) {
01905       case WID_VD_TOP_DETAILS: {
01906         int y = r.top + WD_FRAMERECT_TOP;
01907 
01908         /* Draw running cost */
01909         SetDParam(1, v->age / DAYS_IN_LEAP_YEAR);
01910         SetDParam(0, (v->age + DAYS_IN_YEAR < v->max_age) ? STR_VEHICLE_INFO_AGE : STR_VEHICLE_INFO_AGE_RED);
01911         SetDParam(2, v->max_age / DAYS_IN_LEAP_YEAR);
01912         SetDParam(3, v->GetDisplayRunningCost());
01913         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_AGE_RUNNING_COST_YR);
01914         y += FONT_HEIGHT_NORMAL;
01915 
01916         /* Draw max speed */
01917         StringID string;
01918         if (v->type == VEH_TRAIN ||
01919             (v->type == VEH_ROAD && _settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL)) {
01920           const GroundVehicleCache *gcache = v->GetGroundVehicleCache();
01921           SetDParam(2, v->GetDisplayMaxSpeed());
01922           SetDParam(1, gcache->cached_power);
01923           SetDParam(0, gcache->cached_weight);
01924           SetDParam(3, gcache->cached_max_te / 1000);
01925           if (v->type == VEH_TRAIN && (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ||
01926               GetRailTypeInfo(Train::From(v)->railtype)->acceleration_type == 2)) {
01927             string = STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED;
01928           } else {
01929             string = STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE;
01930           }
01931         } else {
01932           SetDParam(0, v->GetDisplayMaxSpeed());
01933           if (v->type == VEH_AIRCRAFT && Aircraft::From(v)->GetRange() > 0) {
01934             SetDParam(1, Aircraft::From(v)->GetRange());
01935             string = STR_VEHICLE_INFO_MAX_SPEED_RANGE;
01936           } else {
01937             string = STR_VEHICLE_INFO_MAX_SPEED;
01938           }
01939         }
01940         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, string);
01941         y += FONT_HEIGHT_NORMAL;
01942 
01943         /* Draw profit */
01944         SetDParam(0, v->GetDisplayProfitThisYear());
01945         SetDParam(1, v->GetDisplayProfitLastYear());
01946         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR);
01947         y += FONT_HEIGHT_NORMAL;
01948 
01949         /* Draw breakdown & reliability */
01950         SetDParam(0, ToPercent16(v->reliability));
01951         SetDParam(1, v->breakdowns_since_last_service);
01952         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS);
01953         break;
01954       }
01955 
01956       case WID_VD_MATRIX:
01957         /* For trains only. */
01958         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);
01959         break;
01960 
01961       case WID_VD_MIDDLE_DETAILS: {
01962         /* For other vehicles, at the place of the matrix. */
01963         bool rtl = _current_text_dir == TD_RTL;
01964         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;
01965 
01966         uint text_left  = r.left  + (rtl ? 0 : sprite_width);
01967         uint text_right = r.right - (rtl ? sprite_width : 0);
01968 
01969         /* Articulated road vehicles use a complete line. */
01970         if (v->type == VEH_ROAD && v->HasArticulatedPart()) {
01971           DrawVehicleImage(v, r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, 0);
01972         } else {
01973           uint sprite_left  = rtl ? text_right : r.left;
01974           uint sprite_right = rtl ? r.right : text_left;
01975 
01976           DrawVehicleImage(v, sprite_left + WD_FRAMERECT_LEFT, sprite_right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, 0);
01977         }
01978         DrawVehicleDetails(v, text_left + WD_FRAMERECT_LEFT, text_right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, 0, 0, this->tab);
01979         break;
01980       }
01981 
01982       case WID_VD_SERVICING_INTERVAL:
01983         /* Draw service interval text */
01984         SetDParam(0, v->service_interval);
01985         SetDParam(1, v->date_of_last_service);
01986         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + (r.bottom - r.top + 1 - FONT_HEIGHT_NORMAL) / 2,
01987             Company::Get(v->owner)->settings.vehicle.servint_ispercent ? STR_VEHICLE_DETAILS_SERVICING_INTERVAL_PERCENT : STR_VEHICLE_DETAILS_SERVICING_INTERVAL_DAYS);
01988         break;
01989     }
01990   }
01991 
01993   virtual void OnPaint()
01994   {
01995     const Vehicle *v = Vehicle::Get(this->window_number);
01996 
01997     this->SetWidgetDisabledState(WID_VD_RENAME_VEHICLE, v->owner != _local_company);
01998 
01999     if (v->type == VEH_TRAIN) {
02000       this->DisableWidget(this->tab + WID_VD_DETAILS_CARGO_CARRIED);
02001       this->vscroll->SetCount(GetTrainDetailsWndVScroll(v->index, this->tab));
02002     }
02003 
02004     /* Disable service-scroller when interval is set to disabled */
02005     this->SetWidgetsDisabledState(!IsVehicleServiceIntervalEnabled(v->type, v->owner),
02006       WID_VD_INCREASE_SERVICING_INTERVAL,
02007       WID_VD_DECREASE_SERVICING_INTERVAL,
02008       WIDGET_LIST_END);
02009 
02010     this->DrawWidgets();
02011   }
02012 
02013   virtual void OnClick(Point pt, int widget, int click_count)
02014   {
02015     switch (widget) {
02016       case WID_VD_RENAME_VEHICLE: { // rename
02017         const Vehicle *v = Vehicle::Get(this->window_number);
02018         SetDParam(0, v->index);
02019         ShowQueryString(STR_VEHICLE_NAME, STR_QUERY_RENAME_TRAIN_CAPTION + v->type,
02020             MAX_LENGTH_VEHICLE_NAME_CHARS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
02021         break;
02022       }
02023 
02024       case WID_VD_INCREASE_SERVICING_INTERVAL:   // increase int
02025       case WID_VD_DECREASE_SERVICING_INTERVAL: { // decrease int
02026         int mod = _ctrl_pressed ? 5 : 10;
02027         const Vehicle *v = Vehicle::Get(this->window_number);
02028 
02029         mod = (widget == WID_VD_DECREASE_SERVICING_INTERVAL) ? -mod : mod;
02030         mod = GetServiceIntervalClamped(mod + v->service_interval, v->owner);
02031         if (mod == v->service_interval) return;
02032 
02033         DoCommandP(v->tile, v->index, mod, CMD_CHANGE_SERVICE_INT | CMD_MSG(STR_ERROR_CAN_T_CHANGE_SERVICING));
02034         break;
02035       }
02036 
02037       case WID_VD_DETAILS_CARGO_CARRIED:
02038       case WID_VD_DETAILS_TRAIN_VEHICLES:
02039       case WID_VD_DETAILS_CAPACITY_OF_EACH:
02040       case WID_VD_DETAILS_TOTAL_CARGO:
02041         this->SetWidgetsDisabledState(false,
02042           WID_VD_DETAILS_CARGO_CARRIED,
02043           WID_VD_DETAILS_TRAIN_VEHICLES,
02044           WID_VD_DETAILS_CAPACITY_OF_EACH,
02045           WID_VD_DETAILS_TOTAL_CARGO,
02046           widget,
02047           WIDGET_LIST_END);
02048 
02049         this->tab = (TrainDetailsWindowTabs)(widget - WID_VD_DETAILS_CARGO_CARRIED);
02050         this->SetDirty();
02051         break;
02052     }
02053   }
02054 
02055   virtual void OnQueryTextFinished(char *str)
02056   {
02057     if (str == NULL) return;
02058 
02059     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);
02060   }
02061 
02062   virtual void OnResize()
02063   {
02064     NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_VD_MATRIX);
02065     if (nwi != NULL) {
02066       this->vscroll->SetCapacityFromWidget(this, WID_VD_MATRIX);
02067       nwi->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
02068     }
02069   }
02070 };
02071 
02073 static const WindowDesc _train_vehicle_details_desc(
02074   WDP_AUTO, 405, 178,
02075   WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
02076   0,
02077   _nested_train_vehicle_details_widgets, lengthof(_nested_train_vehicle_details_widgets)
02078 );
02079 
02081 static const WindowDesc _nontrain_vehicle_details_desc(
02082   WDP_AUTO, 405, 113,
02083   WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
02084   0,
02085   _nested_nontrain_vehicle_details_widgets, lengthof(_nested_nontrain_vehicle_details_widgets)
02086 );
02087 
02089 static void ShowVehicleDetailsWindow(const Vehicle *v)
02090 {
02091   DeleteWindowById(WC_VEHICLE_ORDERS, v->index, false);
02092   DeleteWindowById(WC_VEHICLE_TIMETABLE, v->index, false);
02093   AllocateWindowDescFront<VehicleDetailsWindow>((v->type == VEH_TRAIN) ? &_train_vehicle_details_desc : &_nontrain_vehicle_details_desc, v->index);
02094 }
02095 
02096 
02097 /* Unified vehicle GUI - Vehicle View Window */
02098 
02100 static const NWidgetPart _nested_vehicle_view_widgets[] = {
02101   NWidget(NWID_HORIZONTAL),
02102     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
02103     NWidget(WWT_CAPTION, COLOUR_GREY, WID_VV_CAPTION), SetDataTip(STR_VEHICLE_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
02104     NWidget(WWT_DEBUGBOX, COLOUR_GREY),
02105     NWidget(WWT_SHADEBOX, COLOUR_GREY),
02106     NWidget(WWT_STICKYBOX, COLOUR_GREY),
02107   EndContainer(),
02108   NWidget(NWID_HORIZONTAL),
02109     NWidget(WWT_PANEL, COLOUR_GREY),
02110       NWidget(WWT_INSET, COLOUR_GREY), SetPadding(2, 2, 2, 2),
02111         NWidget(NWID_VIEWPORT, INVALID_COLOUR, WID_VV_VIEWPORT), SetMinimalSize(226, 84), SetResize(1, 1), SetPadding(1, 1, 1, 1),
02112       EndContainer(),
02113     EndContainer(),
02114     NWidget(NWID_VERTICAL),
02115       NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_CENTER_MAIN_VIEW), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(SPR_CENTRE_VIEW_VEHICLE, 0x0 /* filled later */),
02116       NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VV_SELECT_DEPOT_CLONE),
02117         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_GOTO_DEPOT), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
02118         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_CLONE), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
02119       EndContainer(),
02120       /* For trains only, 'ignore signal' button. */
02121       NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_FORCE_PROCEED), SetMinimalSize(18, 18), SetFill(1, 1),
02122                       SetDataTip(SPR_IGNORE_SIGNALS, STR_VEHICLE_VIEW_TRAIN_IGNORE_SIGNAL_TOOLTIP),
02123       NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VV_SELECT_REFIT_TURN),
02124         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_REFIT), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(SPR_REFIT_VEHICLE, 0x0 /* filled later */),
02125         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_TURN_AROUND), SetMinimalSize(18, 18), SetFill(1, 1),
02126                         SetDataTip(SPR_FORCE_VEHICLE_TURN, STR_VEHICLE_VIEW_ROAD_VEHICLE_REVERSE_TOOLTIP),
02127       EndContainer(),
02128       NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_SHOW_ORDERS), SetFill(1, 1), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_ORDERS, 0x0 /* filled later */),
02129       NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_SHOW_DETAILS), SetFill(1, 1), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_VEHICLE_DETAILS, 0x0 /* filled later */),
02130       NWidget(WWT_PANEL, COLOUR_GREY), SetFill(1, 1), SetMinimalSize(18, 0), SetResize(0, 1), EndContainer(),
02131     EndContainer(),
02132   EndContainer(),
02133   NWidget(NWID_HORIZONTAL),
02134     NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_VV_START_STOP), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetResize(1, 0), SetFill(1, 0),
02135     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
02136   EndContainer(),
02137 };
02138 
02140 static const WindowDesc _vehicle_view_desc(
02141   WDP_AUTO, 250, 116,
02142   WC_VEHICLE_VIEW, WC_NONE,
02143   0,
02144   _nested_vehicle_view_widgets, lengthof(_nested_vehicle_view_widgets)
02145 );
02146 
02151 static const WindowDesc _train_view_desc(
02152   WDP_AUTO, 250, 134,
02153   WC_VEHICLE_VIEW, WC_NONE,
02154   0,
02155   _nested_vehicle_view_widgets, lengthof(_nested_vehicle_view_widgets)
02156 );
02157 
02158 
02159 /* Just to make sure, nobody has changed the vehicle type constants, as we are
02160    using them for array indexing in a number of places here. */
02161 assert_compile(VEH_TRAIN == 0);
02162 assert_compile(VEH_ROAD == 1);
02163 assert_compile(VEH_SHIP == 2);
02164 assert_compile(VEH_AIRCRAFT == 3);
02165 
02167 static const ZoomLevel _vehicle_view_zoom_levels[] = {
02168   ZOOM_LVL_TRAIN,
02169   ZOOM_LVL_ROADVEH,
02170   ZOOM_LVL_SHIP,
02171   ZOOM_LVL_AIRCRAFT,
02172 };
02173 
02174 /* Constants for geometry of vehicle view viewport */
02175 static const int VV_INITIAL_VIEWPORT_WIDTH = 226;
02176 static const int VV_INITIAL_VIEWPORT_HEIGHT = 84;
02177 static const int VV_INITIAL_VIEWPORT_HEIGHT_TRAIN = 102;
02178 
02180 enum VehicleCommandTranslation {
02181   VCT_CMD_START_STOP = 0,
02182   VCT_CMD_CLONE_VEH,
02183   VCT_CMD_TURN_AROUND,
02184 };
02185 
02187 static const uint32 _vehicle_command_translation_table[][4] = {
02188   { // VCT_CMD_START_STOP
02189     CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_TRAIN),
02190     CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_ROAD_VEHICLE),
02191     CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_SHIP),
02192     CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_AIRCRAFT)
02193   },
02194   { // VCT_CMD_CLONE_VEH
02195     CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_TRAIN),
02196     CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_ROAD_VEHICLE),
02197     CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_SHIP),
02198     CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_AIRCRAFT)
02199   },
02200   { // VCT_CMD_TURN_AROUND
02201     CMD_REVERSE_TRAIN_DIRECTION | CMD_MSG(STR_ERROR_CAN_T_REVERSE_DIRECTION_TRAIN),
02202     CMD_TURN_ROADVEH            | CMD_MSG(STR_ERROR_CAN_T_MAKE_ROAD_VEHICLE_TURN),
02203     0xffffffff, // invalid for ships
02204     0xffffffff  // invalid for aircrafts
02205   },
02206 };
02207 
02215 void CcStartStopVehicle(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
02216 {
02217   if (result.Failed()) return;
02218 
02219   const Vehicle *v = Vehicle::GetIfValid(p1);
02220   if (v == NULL || !v->IsPrimaryVehicle() || v->owner != _local_company) return;
02221 
02222   StringID msg = (v->vehstatus & VS_STOPPED) ? STR_VEHICLE_COMMAND_STOPPED : STR_VEHICLE_COMMAND_STARTED;
02223   Point pt = RemapCoords(v->x_pos, v->y_pos, v->z_pos);
02224   AddTextEffect(msg, pt.x, pt.y, DAY_TICKS, TE_RISING);
02225 }
02226 
02232 void StartStopVehicle(const Vehicle *v, bool texteffect)
02233 {
02234   assert(v->IsPrimaryVehicle());
02235   DoCommandP(v->tile, v->index, 0, _vehicle_command_translation_table[VCT_CMD_START_STOP][v->type], texteffect ? CcStartStopVehicle : NULL);
02236 }
02237 
02239 static bool IsVehicleRefitable(const Vehicle *v)
02240 {
02241   if (!v->IsStoppedInDepot()) return false;
02242 
02243   do {
02244     if (IsEngineRefittable(v->engine_type)) return true;
02245   } while (v->IsGroundVehicle() && (v = v->Next()) != NULL);
02246 
02247   return false;
02248 }
02249 
02251 struct VehicleViewWindow : Window {
02252 private:
02254   enum PlaneSelections {
02255     SEL_DC_GOTO_DEPOT,  
02256     SEL_DC_CLONE,       
02257 
02258     SEL_RT_REFIT,       
02259     SEL_RT_TURN_AROUND, 
02260 
02261     SEL_DC_BASEPLANE = SEL_DC_GOTO_DEPOT, 
02262     SEL_RT_BASEPLANE = SEL_RT_REFIT,      
02263   };
02264 
02269   void SelectPlane(PlaneSelections plane)
02270   {
02271     switch (plane) {
02272       case SEL_DC_GOTO_DEPOT:
02273       case SEL_DC_CLONE:
02274         this->GetWidget<NWidgetStacked>(WID_VV_SELECT_DEPOT_CLONE)->SetDisplayedPlane(plane - SEL_DC_BASEPLANE);
02275         break;
02276 
02277       case SEL_RT_REFIT:
02278       case SEL_RT_TURN_AROUND:
02279         this->GetWidget<NWidgetStacked>(WID_VV_SELECT_REFIT_TURN)->SetDisplayedPlane(plane - SEL_RT_BASEPLANE);
02280         break;
02281 
02282       default:
02283         NOT_REACHED();
02284     }
02285   }
02286 
02287 public:
02288   VehicleViewWindow(const WindowDesc *desc, WindowNumber window_number) : Window()
02289   {
02290     this->CreateNestedTree(desc);
02291 
02292     /* Sprites for the 'send to depot' button indexed by vehicle type. */
02293     static const SpriteID vehicle_view_goto_depot_sprites[] = {
02294       SPR_SEND_TRAIN_TODEPOT,
02295       SPR_SEND_ROADVEH_TODEPOT,
02296       SPR_SEND_SHIP_TODEPOT,
02297       SPR_SEND_AIRCRAFT_TODEPOT,
02298     };
02299     const Vehicle *v = Vehicle::Get(window_number);
02300     this->GetWidget<NWidgetCore>(WID_VV_GOTO_DEPOT)->widget_data = vehicle_view_goto_depot_sprites[v->type];
02301 
02302     /* Sprites for the 'clone vehicle' button indexed by vehicle type. */
02303     static const SpriteID vehicle_view_clone_sprites[] = {
02304       SPR_CLONE_TRAIN,
02305       SPR_CLONE_ROADVEH,
02306       SPR_CLONE_SHIP,
02307       SPR_CLONE_AIRCRAFT,
02308     };
02309     this->GetWidget<NWidgetCore>(WID_VV_CLONE)->widget_data = vehicle_view_clone_sprites[v->type];
02310 
02311     switch (v->type) {
02312       case VEH_TRAIN:
02313         this->GetWidget<NWidgetCore>(WID_VV_TURN_AROUND)->tool_tip = STR_VEHICLE_VIEW_TRAIN_REVERSE_TOOLTIP;
02314         break;
02315 
02316       case VEH_ROAD:
02317         break;
02318 
02319       case VEH_SHIP:
02320       case VEH_AIRCRAFT:
02321         this->SelectPlane(SEL_RT_REFIT);
02322         break;
02323 
02324       default: NOT_REACHED();
02325     }
02326     this->FinishInitNested(desc, window_number);
02327     this->owner = v->owner;
02328     this->GetWidget<NWidgetViewport>(WID_VV_VIEWPORT)->InitializeViewport(this, this->window_number | (1 << 31), _vehicle_view_zoom_levels[v->type]);
02329 
02330     this->GetWidget<NWidgetCore>(WID_VV_START_STOP)->tool_tip       = STR_VEHICLE_VIEW_TRAIN_STATE_START_STOP_TOOLTIP + v->type;
02331     this->GetWidget<NWidgetCore>(WID_VV_CENTER_MAIN_VIEW)->tool_tip = STR_VEHICLE_VIEW_TRAIN_LOCATION_TOOLTIP + v->type;
02332     this->GetWidget<NWidgetCore>(WID_VV_REFIT)->tool_tip            = STR_VEHICLE_VIEW_TRAIN_REFIT_TOOLTIP + v->type;
02333     this->GetWidget<NWidgetCore>(WID_VV_GOTO_DEPOT)->tool_tip       = STR_VEHICLE_VIEW_TRAIN_SEND_TO_DEPOT_TOOLTIP + v->type;
02334     this->GetWidget<NWidgetCore>(WID_VV_SHOW_ORDERS)->tool_tip      = STR_VEHICLE_VIEW_TRAIN_ORDERS_TOOLTIP + v->type;
02335     this->GetWidget<NWidgetCore>(WID_VV_SHOW_DETAILS)->tool_tip     = STR_VEHICLE_VIEW_TRAIN_SHOW_DETAILS_TOOLTIP + v->type;
02336     this->GetWidget<NWidgetCore>(WID_VV_CLONE)->tool_tip            = STR_VEHICLE_VIEW_CLONE_TRAIN_INFO + v->type;
02337   }
02338 
02339   ~VehicleViewWindow()
02340   {
02341     DeleteWindowById(WC_VEHICLE_ORDERS, this->window_number, false);
02342     DeleteWindowById(WC_VEHICLE_REFIT, this->window_number, false);
02343     DeleteWindowById(WC_VEHICLE_DETAILS, this->window_number, false);
02344     DeleteWindowById(WC_VEHICLE_TIMETABLE, this->window_number, false);
02345   }
02346 
02347   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
02348   {
02349     const Vehicle *v = Vehicle::Get(this->window_number);
02350     switch (widget) {
02351       case WID_VV_FORCE_PROCEED:
02352         if (v->type != VEH_TRAIN) {
02353           size->height = 0;
02354           size->width = 0;
02355         }
02356         break;
02357 
02358       case WID_VV_VIEWPORT:
02359         size->width = VV_INITIAL_VIEWPORT_WIDTH;
02360         size->height = (v->type == VEH_TRAIN) ? VV_INITIAL_VIEWPORT_HEIGHT_TRAIN : VV_INITIAL_VIEWPORT_HEIGHT;
02361         break;
02362     }
02363   }
02364 
02365   virtual void OnPaint()
02366   {
02367     const Vehicle *v = Vehicle::Get(this->window_number);
02368     bool is_localcompany = v->owner == _local_company;
02369     bool refitable_and_stopped_in_depot = IsVehicleRefitable(v);
02370 
02371     this->SetWidgetDisabledState(WID_VV_GOTO_DEPOT, !is_localcompany);
02372     this->SetWidgetDisabledState(WID_VV_REFIT, !refitable_and_stopped_in_depot || !is_localcompany);
02373     this->SetWidgetDisabledState(WID_VV_CLONE, !is_localcompany);
02374 
02375     if (v->type == VEH_TRAIN) {
02376       this->SetWidgetLoweredState(WID_VV_FORCE_PROCEED, Train::From(v)->force_proceed == TFP_SIGNAL);
02377       this->SetWidgetDisabledState(WID_VV_FORCE_PROCEED, !is_localcompany);
02378       this->SetWidgetDisabledState(WID_VV_TURN_AROUND, !is_localcompany);
02379     }
02380 
02381     this->DrawWidgets();
02382   }
02383 
02384   virtual void SetStringParameters(int widget) const
02385   {
02386     if (widget != WID_VV_CAPTION) return;
02387 
02388     const Vehicle *v = Vehicle::Get(this->window_number);
02389     SetDParam(0, v->index);
02390   }
02391 
02392   virtual void DrawWidget(const Rect &r, int widget) const
02393   {
02394     if (widget != WID_VV_START_STOP) return;
02395 
02396     const Vehicle *v = Vehicle::Get(this->window_number);
02397     StringID str;
02398     if (v->vehstatus & VS_CRASHED) {
02399       str = STR_VEHICLE_STATUS_CRASHED;
02400     } else if (v->type != VEH_AIRCRAFT && v->breakdown_ctr == 1) { // check for aircraft necessary?
02401       str = STR_VEHICLE_STATUS_BROKEN_DOWN;
02402     } else if (v->vehstatus & VS_STOPPED) {
02403       if (v->type == VEH_TRAIN) {
02404         if (v->cur_speed == 0) {
02405           if (Train::From(v)->gcache.cached_power == 0) {
02406             str = STR_VEHICLE_STATUS_TRAIN_NO_POWER;
02407           } else {
02408             str = STR_VEHICLE_STATUS_STOPPED;
02409           }
02410         } else {
02411           SetDParam(0, v->GetDisplaySpeed());
02412           str = STR_VEHICLE_STATUS_TRAIN_STOPPING_VEL;
02413         }
02414       } else { // no train
02415         str = STR_VEHICLE_STATUS_STOPPED;
02416       }
02417     } else if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_TRAIN_STUCK) && !v->current_order.IsType(OT_LOADING)) {
02418       str = STR_VEHICLE_STATUS_TRAIN_STUCK;
02419     } else if (v->type == VEH_AIRCRAFT && HasBit(Aircraft::From(v)->flags, VAF_DEST_TOO_FAR) && !v->current_order.IsType(OT_LOADING)) {
02420       str = STR_VEHICLE_STATUS_AIRCRAFT_TOO_FAR;
02421     } else { // vehicle is in a "normal" state, show current order
02422       switch (v->current_order.GetType()) {
02423         case OT_GOTO_STATION: {
02424           SetDParam(0, v->current_order.GetDestination());
02425           SetDParam(1, v->GetDisplaySpeed());
02426           str = STR_VEHICLE_STATUS_HEADING_FOR_STATION_VEL;
02427           break;
02428         }
02429 
02430         case OT_GOTO_DEPOT: {
02431           SetDParam(0, v->type);
02432           SetDParam(1, v->current_order.GetDestination());
02433           SetDParam(2, v->GetDisplaySpeed());
02434           if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
02435             /* This case *only* happens when multiple nearest depot orders
02436              * follow each other (including an order list only one order: a
02437              * nearest depot order) and there are no reachable depots.
02438              * It is primarily to guard for the case that there is no
02439              * depot with index 0, which would be used as fallback for
02440              * evaluating the string in the status bar. */
02441             str = STR_EMPTY;
02442           } else if (v->current_order.GetDepotActionType() & ODATFB_HALT) {
02443             str = STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_VEL;
02444           } else {
02445             str = STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_SERVICE_VEL;
02446           }
02447           break;
02448         }
02449 
02450         case OT_LOADING:
02451           str = STR_VEHICLE_STATUS_LOADING_UNLOADING;
02452           break;
02453 
02454         case OT_GOTO_WAYPOINT: {
02455           assert(v->type == VEH_TRAIN || v->type == VEH_SHIP);
02456           SetDParam(0, v->current_order.GetDestination());
02457           str = STR_VEHICLE_STATUS_HEADING_FOR_WAYPOINT_VEL;
02458           SetDParam(1, v->GetDisplaySpeed());
02459           break;
02460         }
02461 
02462         case OT_LEAVESTATION:
02463           if (v->type != VEH_AIRCRAFT) {
02464             str = STR_VEHICLE_STATUS_LEAVING;
02465             break;
02466           }
02467           /* FALL THROUGH, if aircraft. Does this even happen? */
02468 
02469         default:
02470           if (v->GetNumManualOrders() == 0) {
02471             str = STR_VEHICLE_STATUS_NO_ORDERS_VEL;
02472             SetDParam(0, v->GetDisplaySpeed());
02473           } else {
02474             str = STR_EMPTY;
02475           }
02476           break;
02477       }
02478     }
02479 
02480     /* draw the flag plus orders */
02481     DrawSprite(v->vehstatus & VS_STOPPED ? SPR_FLAG_VEH_STOPPED : SPR_FLAG_VEH_RUNNING, PAL_NONE, WD_FRAMERECT_LEFT, r.top + WD_FRAMERECT_TOP);
02482     DrawString(r.left + WD_FRAMERECT_LEFT + 6, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, str, TC_FROMSTRING, SA_HOR_CENTER);
02483   }
02484 
02485   virtual void OnClick(Point pt, int widget, int click_count)
02486   {
02487     const Vehicle *v = Vehicle::Get(this->window_number);
02488 
02489     switch (widget) {
02490       case WID_VV_START_STOP: // start stop
02491         if (_ctrl_pressed) {
02492           /* Scroll to current order destination */
02493           TileIndex tile = v->current_order.GetLocation(v);
02494           if (tile != INVALID_TILE) ScrollMainWindowToTile(tile);
02495         } else {
02496           /* Start/Stop */
02497           StartStopVehicle(v, false);
02498         }
02499         break;
02500       case WID_VV_CENTER_MAIN_VIEW: {// center main view
02501         const Window *mainwindow = FindWindowById(WC_MAIN_WINDOW, 0);
02502         /* code to allow the main window to 'follow' the vehicle if the ctrl key is pressed */
02503         if (_ctrl_pressed && mainwindow->viewport->zoom <= ZOOM_LVL_OUT_4X) {
02504           mainwindow->viewport->follow_vehicle = v->index;
02505         } else {
02506           ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos);
02507         }
02508         break;
02509       }
02510 
02511       case WID_VV_GOTO_DEPOT: // goto hangar
02512         DoCommandP(v->tile, v->index | (_ctrl_pressed ? DEPOT_SERVICE : 0U), 0, GetCmdSendToDepot(v));
02513         break;
02514       case WID_VV_REFIT: // refit
02515         ShowVehicleRefitWindow(v, INVALID_VEH_ORDER_ID, this);
02516         break;
02517       case WID_VV_SHOW_ORDERS: // show orders
02518         if (_ctrl_pressed) {
02519           ShowTimetableWindow(v);
02520         } else {
02521           ShowOrdersWindow(v);
02522         }
02523         break;
02524       case WID_VV_SHOW_DETAILS: // show details
02525         ShowVehicleDetailsWindow(v);
02526         break;
02527       case WID_VV_CLONE: // clone vehicle
02528         /* Suppress the vehicle GUI when share-cloning.
02529          * There is no point to it except for starting the vehicle.
02530          * For starting the vehicle the player has to open the depot GUI, which is
02531          * most likely already open, but is also visible in the vehicle viewport. */
02532         DoCommandP(v->tile, v->index, _ctrl_pressed ? 1 : 0,
02533                     _vehicle_command_translation_table[VCT_CMD_CLONE_VEH][v->type],
02534                     _ctrl_pressed ? NULL : CcCloneVehicle);
02535         break;
02536       case WID_VV_TURN_AROUND: // turn around
02537         assert(v->IsGroundVehicle());
02538         DoCommandP(v->tile, v->index, 0,
02539                     _vehicle_command_translation_table[VCT_CMD_TURN_AROUND][v->type]);
02540         break;
02541       case WID_VV_FORCE_PROCEED: // force proceed
02542         assert(v->type == VEH_TRAIN);
02543         DoCommandP(v->tile, v->index, 0, CMD_FORCE_TRAIN_PROCEED | CMD_MSG(STR_ERROR_CAN_T_MAKE_TRAIN_PASS_SIGNAL));
02544         break;
02545     }
02546   }
02547 
02548   virtual void OnResize()
02549   {
02550     if (this->viewport != NULL) {
02551       NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_VV_VIEWPORT);
02552       nvp->UpdateViewportCoordinates(this);
02553     }
02554   }
02555 
02556   virtual void OnTick()
02557   {
02558     const Vehicle *v = Vehicle::Get(this->window_number);
02559     bool veh_stopped = v->IsStoppedInDepot();
02560 
02561     /* Widget WID_VV_GOTO_DEPOT must be hidden if the vehicle is already stopped in depot.
02562      * Widget WID_VV_CLONE_VEH should then be shown, since cloning is allowed only while in depot and stopped.
02563      */
02564     PlaneSelections plane = veh_stopped ? SEL_DC_CLONE : SEL_DC_GOTO_DEPOT;
02565     NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VV_SELECT_DEPOT_CLONE); // Selection widget 'send to depot' / 'clone'.
02566     if (nwi->shown_plane + SEL_DC_BASEPLANE != plane) {
02567       this->SelectPlane(plane);
02568       this->SetWidgetDirty(WID_VV_SELECT_DEPOT_CLONE);
02569     }
02570     /* The same system applies to widget WID_VV_REFIT_VEH and VVW_WIDGET_TURN_AROUND.*/
02571     if (v->IsGroundVehicle()) {
02572       PlaneSelections plane = veh_stopped ? SEL_RT_REFIT : SEL_RT_TURN_AROUND;
02573       NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VV_SELECT_REFIT_TURN);
02574       if (nwi->shown_plane + SEL_RT_BASEPLANE != plane) {
02575         this->SelectPlane(plane);
02576         this->SetWidgetDirty(WID_VV_SELECT_REFIT_TURN);
02577       }
02578     }
02579   }
02580 
02586   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
02587   {
02588     if (data == VIWD_AUTOREPLACE) {
02589       /* Autoreplace replaced the vehicle.
02590        * Nothing to do for this window. */
02591       return;
02592     }
02593   }
02594 
02595   virtual bool IsNewGRFInspectable() const
02596   {
02597     return ::IsNewGRFInspectable(GetGrfSpecFeature(Vehicle::Get(this->window_number)->type), this->window_number);
02598   }
02599 
02600   virtual void ShowNewGRFInspectWindow() const
02601   {
02602 		::ShowNewGRFInspectWindow(GetGrfSpecFeature(Vehicle::Get(this->window_number)->type), this->window_number);
02603   }
02604 };
02605 
02606 
02608 void ShowVehicleViewWindow(const Vehicle *v)
02609 {
02610   AllocateWindowDescFront<VehicleViewWindow>((v->type == VEH_TRAIN) ? &_train_view_desc : &_vehicle_view_desc, v->index);
02611 }
02612 
02618 bool VehicleClicked(const Vehicle *v)
02619 {
02620   assert(v != NULL);
02621   if (!(_thd.place_mode & HT_VEHICLE)) return false;
02622 
02623   v = v->First();
02624   if (!v->IsPrimaryVehicle()) return false;
02625 
02626   return _thd.GetCallbackWnd()->OnVehicleSelect(v);
02627 }
02628 
02629 void StopGlobalFollowVehicle(const Vehicle *v)
02630 {
02631   Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
02632   if (w != NULL && w->viewport->follow_vehicle == v->index) {
02633     ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos, true); // lock the main view on the vehicle's last position
02634     w->viewport->follow_vehicle = INVALID_VEHICLE;
02635   }
02636 }
02637 
02638 
02646 void CcBuildPrimaryVehicle(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
02647 {
02648   if (result.Failed()) return;
02649 
02650   const Vehicle *v = Vehicle::Get(_new_vehicle_id);
02651   ShowVehicleViewWindow(v);
02652 }
02653 
02659 int GetVehicleWidth(Vehicle *v, EngineImageType image_type)
02660 {
02661   int vehicle_width = 0;
02662 
02663   switch (v->type) {
02664     case VEH_TRAIN:
02665       for (const Train *u = Train::From(v); u != NULL; u = u->Next()) {
02666         vehicle_width += u->GetDisplayImageWidth();
02667       }
02668       break;
02669 
02670     case VEH_ROAD:
02671       for (const RoadVehicle *u = RoadVehicle::From(v); u != NULL; u = u->Next()) {
02672         vehicle_width += u->GetDisplayImageWidth();
02673       }
02674       break;
02675 
02676     default:
02677       bool rtl = _current_text_dir == TD_RTL;
02678       SpriteID sprite = v->GetImage(rtl ? DIR_E : DIR_W, image_type);
02679       const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
02680       vehicle_width = UnScaleByZoom(real_sprite->width, ZOOM_LVL_GUI);
02681 
02682       break;
02683   }
02684 
02685   return vehicle_width;
02686 }