vehicle_gui.cpp

Go to the documentation of this file.
00001 /* $Id: vehicle_gui.cpp 23740 2012-01-03 21:32:51Z rubidium $ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 #include "debug.h"
00014 #include "company_func.h"
00015 #include "gui.h"
00016 #include "textbuf_gui.h"
00017 #include "command_func.h"
00018 #include "vehicle_gui_base.h"
00019 #include "viewport_func.h"
00020 #include "newgrf_text.h"
00021 #include "newgrf_debug.h"
00022 #include "roadveh.h"
00023 #include "train.h"
00024 #include "aircraft.h"
00025 #include "depot_map.h"
00026 #include "group_gui.h"
00027 #include "strings_func.h"
00028 #include "vehicle_func.h"
00029 #include "autoreplace_gui.h"
00030 #include "string_func.h"
00031 #include "widgets/dropdown_func.h"
00032 #include "timetable.h"
00033 #include "articulated_vehicles.h"
00034 #include "spritecache.h"
00035 #include "core/geometry_func.hpp"
00036 #include "company_base.h"
00037 #include "engine_func.h"
00038 #include "station_base.h"
00039 #include "tilehighlight_func.h"
00040 #include "zoom_func.h"
00041 
00042 
00043 Sorting _sorting;
00044 
00045 static GUIVehicleList::SortFunction VehicleNumberSorter;
00046 static GUIVehicleList::SortFunction VehicleNameSorter;
00047 static GUIVehicleList::SortFunction VehicleAgeSorter;
00048 static GUIVehicleList::SortFunction VehicleProfitThisYearSorter;
00049 static GUIVehicleList::SortFunction VehicleProfitLastYearSorter;
00050 static GUIVehicleList::SortFunction VehicleCargoSorter;
00051 static GUIVehicleList::SortFunction VehicleReliabilitySorter;
00052 static GUIVehicleList::SortFunction VehicleMaxSpeedSorter;
00053 static GUIVehicleList::SortFunction VehicleModelSorter;
00054 static GUIVehicleList::SortFunction VehicleValueSorter;
00055 static GUIVehicleList::SortFunction VehicleLengthSorter;
00056 static GUIVehicleList::SortFunction VehicleTimeToLiveSorter;
00057 static GUIVehicleList::SortFunction VehicleTimetableDelaySorter;
00058 
00059 GUIVehicleList::SortFunction * const BaseVehicleListWindow::vehicle_sorter_funcs[] = {
00060   &VehicleNumberSorter,
00061   &VehicleNameSorter,
00062   &VehicleAgeSorter,
00063   &VehicleProfitThisYearSorter,
00064   &VehicleProfitLastYearSorter,
00065   &VehicleCargoSorter,
00066   &VehicleReliabilitySorter,
00067   &VehicleMaxSpeedSorter,
00068   &VehicleModelSorter,
00069   &VehicleValueSorter,
00070   &VehicleLengthSorter,
00071   &VehicleTimeToLiveSorter,
00072   &VehicleTimetableDelaySorter,
00073 };
00074 
00075 const StringID BaseVehicleListWindow::vehicle_sorter_names[] = {
00076   STR_SORT_BY_NUMBER,
00077   STR_SORT_BY_NAME,
00078   STR_SORT_BY_AGE,
00079   STR_SORT_BY_PROFIT_THIS_YEAR,
00080   STR_SORT_BY_PROFIT_LAST_YEAR,
00081   STR_SORT_BY_TOTAL_CAPACITY_PER_CARGOTYPE,
00082   STR_SORT_BY_RELIABILITY,
00083   STR_SORT_BY_MAX_SPEED,
00084   STR_SORT_BY_MODEL,
00085   STR_SORT_BY_VALUE,
00086   STR_SORT_BY_LENGTH,
00087   STR_SORT_BY_LIFE_TIME,
00088   STR_SORT_BY_TIMETABLE_DELAY,
00089   INVALID_STRING_ID
00090 };
00091 
00092 const StringID BaseVehicleListWindow::vehicle_depot_name[] = {
00093   STR_VEHICLE_LIST_SEND_TRAIN_TO_DEPOT,
00094   STR_VEHICLE_LIST_SEND_ROAD_VEHICLE_TO_DEPOT,
00095   STR_VEHICLE_LIST_SEND_SHIP_TO_DEPOT,
00096   STR_VEHICLE_LIST_SEND_AIRCRAFT_TO_HANGAR
00097 };
00098 
00099 void BaseVehicleListWindow::BuildVehicleList()
00100 {
00101   if (!this->vehicles.NeedRebuild()) return;
00102 
00103   DEBUG(misc, 3, "Building vehicle list type %d for company %d given index %d", this->vli.type, this->vli.company, this->vli.index);
00104 
00105   GenerateVehicleSortList(&this->vehicles, this->vli);
00106 
00107   uint unitnumber = 0;
00108   for (const Vehicle **v = this->vehicles.Begin(); v != this->vehicles.End(); v++) {
00109     unitnumber = max<uint>(unitnumber, (*v)->unitnumber);
00110   }
00111 
00112   /* Because 111 is much less wide than e.g. 999 we use the
00113    * wider numbers to determine the width instead of just
00114    * the random number that it seems to be. */
00115   if (unitnumber >= 1000) {
00116     this->unitnumber_digits = 4;
00117   } else if (unitnumber >= 100) {
00118     this->unitnumber_digits = 3;
00119   } else {
00120     this->unitnumber_digits = 2;
00121   }
00122 
00123   this->vehicles.RebuildDone();
00124   this->vscroll->SetCount(this->vehicles.Length());
00125 }
00126 
00133 Dimension BaseVehicleListWindow::GetActionDropdownSize(bool show_autoreplace, bool show_group)
00134 {
00135   Dimension d = {0, 0};
00136 
00137   if (show_autoreplace) d = maxdim(d, GetStringBoundingBox(STR_VEHICLE_LIST_REPLACE_VEHICLES));
00138   d = maxdim(d, GetStringBoundingBox(STR_VEHICLE_LIST_SEND_FOR_SERVICING));
00139   d = maxdim(d, GetStringBoundingBox(this->vehicle_depot_name[this->vli.vtype]));
00140 
00141   if (show_group) {
00142     d = maxdim(d, GetStringBoundingBox(STR_GROUP_ADD_SHARED_VEHICLE));
00143     d = maxdim(d, GetStringBoundingBox(STR_GROUP_REMOVE_ALL_VEHICLES));
00144   }
00145 
00146   return d;
00147 }
00148 
00155 DropDownList *BaseVehicleListWindow::BuildActionDropdownList(bool show_autoreplace, bool show_group)
00156 {
00157   DropDownList *list = new DropDownList();
00158 
00159   if (show_autoreplace) list->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_SPACE_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(0);
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     if (_returned_mail_refit_capacity > 0) {
00604       SetDParam(2, CT_MAIL);
00605       SetDParam(3, _returned_mail_refit_capacity);
00606       SetDParam(4, cost.GetCost());
00607       return STR_REFIT_NEW_CAPACITY_COST_OF_AIRCRAFT_REFIT;
00608     } else {
00609       SetDParam(2, cost.GetCost());
00610       return STR_REFIT_NEW_CAPACITY_COST_OF_REFIT;
00611     }
00612   }
00613 
00614   virtual void DrawWidget(const Rect &r, int widget) const
00615   {
00616     switch (widget) {
00617       case WID_VR_VEHICLE_PANEL_DISPLAY: {
00618         Vehicle *v = Vehicle::Get(this->window_number);
00619         DrawVehicleImage(v, this->sprite_left + WD_FRAMERECT_LEFT, this->sprite_right - WD_FRAMERECT_RIGHT,
00620           r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, this->hscroll != NULL ? this->hscroll->GetPosition() : 0);
00621 
00622         /* Highlight selected vehicles. */
00623         if (this->order != INVALID_VEH_ORDER_ID) break;
00624         int x = 0;
00625         switch (v->type) {
00626           case VEH_TRAIN: {
00627             VehicleSet vehicles_to_refit;
00628             GetVehicleSet(vehicles_to_refit, Vehicle::Get(this->selected_vehicle), this->num_vehicles);
00629 
00630             int left = INT32_MIN;
00631             int width = 0;
00632 
00633             for (Train *u = Train::From(v); u != NULL; u = u->Next()) {
00634               /* Start checking. */
00635               if (vehicles_to_refit.Contains(u->index) && left == INT32_MIN) {
00636                 left = x - this->hscroll->GetPosition() + r.left + this->vehicle_margin;
00637                 width = 0;
00638               }
00639 
00640               /* Draw a selection. */
00641               if ((!vehicles_to_refit.Contains(u->index) || u->Next() == NULL) && left != INT32_MIN) {
00642                 if (u->Next() == NULL && vehicles_to_refit.Contains(u->index)) {
00643                   int current_width = u->GetDisplayImageWidth();
00644                   width += current_width;
00645                   x += current_width;
00646                 }
00647 
00648                 int right = Clamp(left + width, 0, r.right);
00649                 left = max(0, left);
00650 
00651                 if (_current_text_dir == TD_RTL) {
00652                   right = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY)->current_x - left;
00653                   left = right - width;
00654                 }
00655 
00656                 if (left != right) {
00657                   DrawFrameRect(left, r.top + WD_FRAMERECT_TOP, right, r.top + WD_FRAMERECT_TOP + 13, COLOUR_WHITE, FR_BORDERONLY);
00658                 }
00659 
00660                 left = INT32_MIN;
00661               }
00662 
00663               int current_width = u->GetDisplayImageWidth();
00664               width += current_width;
00665               x += current_width;
00666             }
00667             break;
00668           }
00669 
00670           default: break;
00671         }
00672         break;
00673       }
00674 
00675       case WID_VR_MATRIX:
00676         DrawVehicleRefitWindow(this->list, this->sel, this->vscroll->GetPosition(), this->vscroll->GetCapacity(), this->resize.step_height, r);
00677         break;
00678 
00679       case WID_VR_INFO:
00680         if (this->cargo != NULL) {
00681           StringID string = this->GetCapacityString(this->cargo);
00682           if (string != INVALID_STRING_ID) {
00683             DrawStringMultiLine(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT,
00684                 r.top + WD_FRAMERECT_TOP, r.bottom - WD_FRAMERECT_BOTTOM, string);
00685           }
00686         }
00687         break;
00688     }
00689   }
00690 
00696   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
00697   {
00698     switch (data) {
00699       case -666: // Autoreplace replaced the vehicle; selected_vehicle became invalid.
00700       case 0: { // The consist has changed; rebuild the entire list.
00701         /* Clear the selection. */
00702         Vehicle *v = Vehicle::Get(this->window_number);
00703         this->selected_vehicle = v->index;
00704         this->num_vehicles = UINT8_MAX;
00705         /* FALL THROUGH */
00706       }
00707 
00708       case 2: { // The vehicle selection has changed; rebuild the entire list.
00709         if (!gui_scope) break;
00710         this->BuildRefitList();
00711 
00712         /* The vehicle width has changed too. */
00713         this->vehicle_width = GetVehicleWidth(Vehicle::Get(this->window_number), EIT_IN_DETAILS);
00714         uint max_width = 0;
00715 
00716         /* Check the width of all cargo information strings. */
00717         for (uint i = 0; i < NUM_CARGO; i++) {
00718           for (uint j = 0; j < this->list[i].Length(); j++) {
00719             StringID string = this->GetCapacityString(&list[i][j]);
00720             if (string != INVALID_STRING_ID) {
00721               Dimension dim = GetStringBoundingBox(string);
00722               max_width = max(dim.width, max_width);
00723             }
00724           }
00725         }
00726 
00727         if (this->information_width < max_width) {
00728           this->information_width = max_width;
00729           this->ReInit();
00730         }
00731         /* FALL THROUGH */
00732       }
00733 
00734       case 1: // A new cargo has been selected.
00735         if (!gui_scope) break;
00736         this->cargo = GetRefitOption();
00737         break;
00738     }
00739   }
00740 
00741   int GetClickPosition(int click_x)
00742   {
00743     const NWidgetCore *matrix_widget = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY);
00744     if (_current_text_dir == TD_RTL) click_x = matrix_widget->current_x - click_x;
00745     click_x -= this->vehicle_margin;
00746     if (this->hscroll != NULL) click_x += this->hscroll->GetPosition();
00747 
00748     return click_x;
00749   }
00750 
00751   void SetSelectedVehicles(int drag_x)
00752   {
00753     drag_x = GetClickPosition(drag_x);
00754 
00755     int left_x  = min(this->click_x, drag_x);
00756     int right_x = max(this->click_x, drag_x);
00757     this->num_vehicles = 0;
00758 
00759     Vehicle *v = Vehicle::Get(this->window_number);
00760     /* Find the vehicle part that was clicked. */
00761     switch (v->type) {
00762       case VEH_TRAIN: {
00763         /* Don't select anything if we are not clicking in the vehicle. */
00764         if (left_x >= 0) {
00765           const Train *u = Train::From(v);
00766           bool start_counting = false;
00767           for (; u != NULL; u = u->Next()) {
00768             int current_width = u->GetDisplayImageWidth();
00769             left_x  -= current_width;
00770             right_x -= current_width;
00771 
00772             if (left_x < 0 && !start_counting) {
00773               this->selected_vehicle = u->index;
00774               start_counting = true;
00775 
00776               /* Count the first vehicle, even if articulated part */
00777               this->num_vehicles++;
00778             } else if (start_counting && !u->IsArticulatedPart()) {
00779               /* Do not count articulated parts */
00780               this->num_vehicles++;
00781             }
00782 
00783             if (right_x < 0) break;
00784           }
00785         }
00786 
00787         /* If the selection is not correct, clear it. */
00788         if (this->num_vehicles != 0) {
00789           if (_ctrl_pressed) this->num_vehicles = UINT8_MAX;
00790           break;
00791         }
00792         /* FALL THROUGH */
00793       }
00794 
00795       default:
00796         /* Clear the selection. */
00797         this->selected_vehicle = v->index;
00798         this->num_vehicles = UINT8_MAX;
00799         break;
00800     }
00801   }
00802 
00803   virtual void OnClick(Point pt, int widget, int click_count)
00804   {
00805     switch (widget) {
00806       case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
00807         if (this->order != INVALID_VEH_ORDER_ID) break;
00808         NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
00809         this->click_x = GetClickPosition(pt.x - nwi->pos_x);
00810         this->SetSelectedVehicles(pt.x - nwi->pos_x);
00811         this->SetWidgetDirty(WID_VR_VEHICLE_PANEL_DISPLAY);
00812         if (!_ctrl_pressed) {
00813           SetObjectToPlaceWnd(SPR_CURSOR_MOUSE, PAL_NONE, HT_DRAG, this);
00814         } else {
00815           /* The vehicle selection has changed. */
00816           this->InvalidateData(2);
00817         }
00818         break;
00819       }
00820 
00821       case WID_VR_MATRIX: { // listbox
00822         this->sel = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_VR_MATRIX);
00823         if (this->sel == INT_MAX) this->sel = -1;
00824         this->SetWidgetDisabledState(WID_VR_REFIT, this->sel == -1);
00825         this->InvalidateData(1);
00826 
00827         if (click_count == 1) break;
00828         /* FALL THROUGH */
00829       }
00830 
00831       case WID_VR_REFIT: // refit button
00832         if (this->cargo != NULL) {
00833           const Vehicle *v = Vehicle::Get(this->window_number);
00834 
00835           if (this->order == INVALID_VEH_ORDER_ID) {
00836             bool delete_window = this->selected_vehicle == v->index && this->num_vehicles == UINT8_MAX;
00837             if (DoCommandP(v->tile, this->selected_vehicle, this->cargo->cargo | this->cargo->subtype << 8 | this->num_vehicles << 16, GetCmdRefitVeh(v)) && delete_window) delete this;
00838           } else {
00839             if (DoCommandP(v->tile, v->index, this->cargo->cargo | this->cargo->subtype << 8 | this->order << 16, CMD_ORDER_REFIT)) delete this;
00840           }
00841         }
00842         break;
00843     }
00844   }
00845 
00846   virtual void OnMouseDrag(Point pt, int widget)
00847   {
00848     switch (widget) {
00849       case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
00850         if (this->order != INVALID_VEH_ORDER_ID) break;
00851         NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
00852         this->SetSelectedVehicles(pt.x - nwi->pos_x);
00853         this->SetWidgetDirty(WID_VR_VEHICLE_PANEL_DISPLAY);
00854         break;
00855       }
00856     }
00857   }
00858 
00859   virtual void OnDragDrop(Point pt, int widget)
00860   {
00861     switch (widget) {
00862       case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
00863         if (this->order != INVALID_VEH_ORDER_ID) break;
00864         NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
00865         this->SetSelectedVehicles(pt.x - nwi->pos_x);
00866         this->InvalidateData(2);
00867         break;
00868       }
00869     }
00870   }
00871 
00872   virtual void OnResize()
00873   {
00874     this->vehicle_width = GetVehicleWidth(Vehicle::Get(this->window_number), EIT_IN_DETAILS);
00875     this->vscroll->SetCapacityFromWidget(this, WID_VR_MATRIX);
00876     if (this->hscroll != NULL) this->hscroll->SetCapacityFromWidget(this, WID_VR_VEHICLE_PANEL_DISPLAY);
00877     this->GetWidget<NWidgetCore>(WID_VR_MATRIX)->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
00878   }
00879 };
00880 
00881 static const NWidgetPart _nested_vehicle_refit_widgets[] = {
00882   NWidget(NWID_HORIZONTAL),
00883     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
00884     NWidget(WWT_CAPTION, COLOUR_GREY, WID_VR_CAPTION), SetDataTip(STR_REFIT_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00885   EndContainer(),
00886   /* Vehicle display + scrollbar. */
00887   NWidget(NWID_VERTICAL),
00888     NWidget(WWT_PANEL, COLOUR_GREY, WID_VR_VEHICLE_PANEL_DISPLAY), SetMinimalSize(228, 14), SetResize(1, 0), SetScrollbar(WID_VR_HSCROLLBAR), EndContainer(),
00889     NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VR_SHOW_HSCROLLBAR),
00890       NWidget(NWID_HSCROLLBAR, COLOUR_GREY, WID_VR_HSCROLLBAR),
00891     EndContainer(),
00892   EndContainer(),
00893   NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_VR_SELECT_HEADER), SetDataTip(STR_REFIT_TITLE, STR_NULL), SetResize(1, 0),
00894   /* Matrix + scrollbar. */
00895   NWidget(NWID_HORIZONTAL),
00896     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),
00897     NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VR_SCROLLBAR),
00898   EndContainer(),
00899   NWidget(WWT_PANEL, COLOUR_GREY, WID_VR_INFO), SetMinimalTextLines(2, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM), SetResize(1, 0), EndContainer(),
00900   NWidget(NWID_HORIZONTAL),
00901     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VR_REFIT), SetFill(1, 0), SetResize(1, 0),
00902     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
00903   EndContainer(),
00904 };
00905 
00906 static const WindowDesc _vehicle_refit_desc(
00907   WDP_AUTO, 240, 174,
00908   WC_VEHICLE_REFIT, WC_VEHICLE_VIEW,
00909   WDF_UNCLICK_BUTTONS | WDF_CONSTRUCTION,
00910   _nested_vehicle_refit_widgets, lengthof(_nested_vehicle_refit_widgets)
00911 );
00912 
00920 void ShowVehicleRefitWindow(const Vehicle *v, VehicleOrderID order, Window *parent, bool auto_refit)
00921 {
00922   DeleteWindowById(WC_VEHICLE_REFIT, v->index);
00923   RefitWindow *w = new RefitWindow(&_vehicle_refit_desc, v, order, auto_refit);
00924   w->parent = parent;
00925 }
00926 
00928 uint ShowRefitOptionsList(int left, int right, int y, EngineID engine)
00929 {
00930   /* List of cargo types of this engine */
00931   uint32 cmask = GetUnionOfArticulatedRefitMasks(engine, false);
00932   /* List of cargo types available in this climate */
00933   uint32 lmask = _cargo_mask;
00934   char string[512];
00935   char *b = string;
00936 
00937   /* Draw nothing if the engine is not refittable */
00938   if (HasAtMostOneBit(cmask)) return y;
00939 
00940   b = InlineString(b, STR_PURCHASE_INFO_REFITTABLE_TO);
00941 
00942   if (cmask == lmask) {
00943     /* Engine can be refitted to all types in this climate */
00944     b = InlineString(b, STR_PURCHASE_INFO_ALL_TYPES);
00945   } else {
00946     /* Check if we are able to refit to more cargo types and unable to. If
00947      * so, invert the cargo types to list those that we can't refit to. */
00948     if (CountBits(cmask ^ lmask) < CountBits(cmask) && CountBits(cmask ^ lmask) <= 7) {
00949       cmask ^= lmask;
00950       b = InlineString(b, STR_PURCHASE_INFO_ALL_BUT);
00951     }
00952 
00953     bool first = true;
00954 
00955     /* Add each cargo type to the list */
00956     const CargoSpec *cs;
00957     FOR_ALL_SORTED_CARGOSPECS(cs) {
00958       if (!HasBit(cmask, cs->Index())) continue;
00959 
00960       if (b >= lastof(string) - (2 + 2 * 4)) break; // ", " and two calls to Utf8Encode()
00961 
00962       if (!first) b = strecpy(b, ", ", lastof(string));
00963       first = false;
00964 
00965       b = InlineString(b, cs->name);
00966     }
00967   }
00968 
00969   /* Terminate and display the completed string */
00970   *b = '\0';
00971 
00972   /* Make sure we detect any buffer overflow */
00973   assert(b < endof(string));
00974 
00975   SetDParamStr(0, string);
00976   return DrawStringMultiLine(left, right, y, INT32_MAX, STR_JUST_RAW_STRING);
00977 }
00978 
00980 StringID GetCargoSubtypeText(const Vehicle *v)
00981 {
00982   if (HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) {
00983     uint16 cb = GetVehicleCallback(CBID_VEHICLE_CARGO_SUFFIX, 0, 0, v->engine_type, v);
00984     if (cb != CALLBACK_FAILED) {
00985       if (cb > 0x400) ErrorUnknownCallbackResult(v->GetGRFID(), CBID_VEHICLE_CARGO_SUFFIX, cb);
00986       if (cb >= 0x400 || (v->GetGRF()->grf_version < 8 && cb == 0xFF)) cb = CALLBACK_FAILED;
00987     }
00988     if (cb != CALLBACK_FAILED) {
00989       return GetGRFStringID(v->GetGRFID(), 0xD000 + cb);
00990     }
00991   }
00992   return STR_EMPTY;
00993 }
00994 
00996 static int CDECL VehicleNumberSorter(const Vehicle * const *a, const Vehicle * const *b)
00997 {
00998   return (*a)->unitnumber - (*b)->unitnumber;
00999 }
01000 
01002 static int CDECL VehicleNameSorter(const Vehicle * const *a, const Vehicle * const *b)
01003 {
01004   static char last_name[2][64];
01005 
01006   if (*a != _last_vehicle[0]) {
01007     _last_vehicle[0] = *a;
01008     SetDParam(0, (*a)->index);
01009     GetString(last_name[0], STR_VEHICLE_NAME, lastof(last_name[0]));
01010   }
01011 
01012   if (*b != _last_vehicle[1]) {
01013     _last_vehicle[1] = *b;
01014     SetDParam(0, (*b)->index);
01015     GetString(last_name[1], STR_VEHICLE_NAME, lastof(last_name[1]));
01016   }
01017 
01018   int r = strnatcmp(last_name[0], last_name[1]); // Sort by name (natural sorting).
01019   return (r != 0) ? r : VehicleNumberSorter(a, b);
01020 }
01021 
01023 static int CDECL VehicleAgeSorter(const Vehicle * const *a, const Vehicle * const *b)
01024 {
01025   int r = (*a)->age - (*b)->age;
01026   return (r != 0) ? r : VehicleNumberSorter(a, b);
01027 }
01028 
01030 static int CDECL VehicleProfitThisYearSorter(const Vehicle * const *a, const Vehicle * const *b)
01031 {
01032   int r = ClampToI32((*a)->GetDisplayProfitThisYear() - (*b)->GetDisplayProfitThisYear());
01033   return (r != 0) ? r : VehicleNumberSorter(a, b);
01034 }
01035 
01037 static int CDECL VehicleProfitLastYearSorter(const Vehicle * const *a, const Vehicle * const *b)
01038 {
01039   int r = ClampToI32((*a)->GetDisplayProfitLastYear() - (*b)->GetDisplayProfitLastYear());
01040   return (r != 0) ? r : VehicleNumberSorter(a, b);
01041 }
01042 
01044 static int CDECL VehicleCargoSorter(const Vehicle * const *a, const Vehicle * const *b)
01045 {
01046   const Vehicle *v;
01047   CargoArray diff;
01048 
01049   /* Append the cargo of the connected weagons */
01050   for (v = *a; v != NULL; v = v->Next()) diff[v->cargo_type] += v->cargo_cap;
01051   for (v = *b; v != NULL; v = v->Next()) diff[v->cargo_type] -= v->cargo_cap;
01052 
01053   int r = 0;
01054   for (CargoID i = 0; i < NUM_CARGO; i++) {
01055     r = diff[i];
01056     if (r != 0) break;
01057   }
01058 
01059   return (r != 0) ? r : VehicleNumberSorter(a, b);
01060 }
01061 
01063 static int CDECL VehicleReliabilitySorter(const Vehicle * const *a, const Vehicle * const *b)
01064 {
01065   int r = (*a)->reliability - (*b)->reliability;
01066   return (r != 0) ? r : VehicleNumberSorter(a, b);
01067 }
01068 
01070 static int CDECL VehicleMaxSpeedSorter(const Vehicle * const *a, const Vehicle * const *b)
01071 {
01072   int r = (*a)->vcache.cached_max_speed - (*b)->vcache.cached_max_speed;
01073   return (r != 0) ? r : VehicleNumberSorter(a, b);
01074 }
01075 
01077 static int CDECL VehicleModelSorter(const Vehicle * const *a, const Vehicle * const *b)
01078 {
01079   int r = (*a)->engine_type - (*b)->engine_type;
01080   return (r != 0) ? r : VehicleNumberSorter(a, b);
01081 }
01082 
01084 static int CDECL VehicleValueSorter(const Vehicle * const *a, const Vehicle * const *b)
01085 {
01086   const Vehicle *u;
01087   Money diff = 0;
01088 
01089   for (u = *a; u != NULL; u = u->Next()) diff += u->value;
01090   for (u = *b; u != NULL; u = u->Next()) diff -= u->value;
01091 
01092   int r = ClampToI32(diff);
01093   return (r != 0) ? r : VehicleNumberSorter(a, b);
01094 }
01095 
01097 static int CDECL VehicleLengthSorter(const Vehicle * const *a, const Vehicle * const *b)
01098 {
01099   int r = (*a)->GetGroundVehicleCache()->cached_total_length - (*b)->GetGroundVehicleCache()->cached_total_length;
01100   return (r != 0) ? r : VehicleNumberSorter(a, b);
01101 }
01102 
01104 static int CDECL VehicleTimeToLiveSorter(const Vehicle * const *a, const Vehicle * const *b)
01105 {
01106   int r = ClampToI32(((*a)->max_age - (*a)->age) - ((*b)->max_age - (*b)->age));
01107   return (r != 0) ? r : VehicleNumberSorter(a, b);
01108 }
01109 
01111 static int CDECL VehicleTimetableDelaySorter(const Vehicle * const *a, const Vehicle * const *b)
01112 {
01113   int r = (*a)->lateness_counter - (*b)->lateness_counter;
01114   return (r != 0) ? r : VehicleNumberSorter(a, b);
01115 }
01116 
01117 void InitializeGUI()
01118 {
01119   MemSetT(&_sorting, 0);
01120 }
01121 
01128 static inline void ChangeVehicleWindow(WindowClass window_class, VehicleID from_index, VehicleID to_index)
01129 {
01130   Window *w = FindWindowById(window_class, from_index);
01131   if (w != NULL) {
01132     /* Update window_number */
01133     w->window_number = to_index;
01134     if (w->viewport != NULL) w->viewport->follow_vehicle = to_index;
01135 
01136     /* Update vehicle drag data */
01137     if (_thd.window_class == window_class && _thd.window_number == (WindowNumber)from_index) {
01138       _thd.window_number = to_index;
01139     }
01140 
01141     /* Notify the window. */
01142     w->InvalidateData(-666, false);
01143   }
01144 }
01145 
01151 void ChangeVehicleViewWindow(VehicleID from_index, VehicleID to_index)
01152 {
01153   ChangeVehicleWindow(WC_VEHICLE_VIEW,      from_index, to_index);
01154   ChangeVehicleWindow(WC_VEHICLE_ORDERS,    from_index, to_index);
01155   ChangeVehicleWindow(WC_VEHICLE_REFIT,     from_index, to_index);
01156   ChangeVehicleWindow(WC_VEHICLE_DETAILS,   from_index, to_index);
01157   ChangeVehicleWindow(WC_VEHICLE_TIMETABLE, from_index, to_index);
01158 }
01159 
01160 static const NWidgetPart _nested_vehicle_list[] = {
01161   NWidget(NWID_HORIZONTAL),
01162     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
01163     NWidget(WWT_CAPTION, COLOUR_GREY, WID_VL_CAPTION),
01164     NWidget(WWT_SHADEBOX, COLOUR_GREY),
01165     NWidget(WWT_STICKYBOX, COLOUR_GREY),
01166   EndContainer(),
01167 
01168   NWidget(NWID_HORIZONTAL),
01169     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VL_SORT_ORDER), SetMinimalSize(81, 12), SetFill(0, 1), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
01170     NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_SORT_BY_PULLDOWN), SetMinimalSize(167, 12), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
01171     NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(12, 12), SetFill(1, 1), SetResize(1, 0),
01172     EndContainer(),
01173   EndContainer(),
01174 
01175   NWidget(NWID_HORIZONTAL),
01176     NWidget(WWT_MATRIX, COLOUR_GREY, WID_VL_LIST), SetMinimalSize(248, 0), SetFill(1, 0), SetResize(1, 1), SetScrollbar(WID_VL_SCROLLBAR),
01177     NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VL_SCROLLBAR),
01178   EndContainer(),
01179 
01180   NWidget(NWID_HORIZONTAL),
01181     NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VL_HIDE_BUTTONS),
01182       NWidget(NWID_HORIZONTAL),
01183         NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VL_AVAILABLE_VEHICLES), SetMinimalSize(106, 12), SetFill(0, 1),
01184                 SetDataTip(STR_BLACK_STRING, STR_VEHICLE_LIST_AVAILABLE_ENGINES_TOOLTIP),
01185         NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_MANAGE_VEHICLES_DROPDOWN), SetMinimalSize(118, 12), SetFill(0, 1),
01186                 SetDataTip(STR_VEHICLE_LIST_MANAGE_LIST, STR_VEHICLE_LIST_MANAGE_LIST_TOOLTIP),
01187         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VL_STOP_ALL), SetMinimalSize(12, 12), SetFill(0, 1),
01188                 SetDataTip(SPR_FLAG_VEH_STOPPED, STR_VEHICLE_LIST_MASS_STOP_LIST_TOOLTIP),
01189         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VL_START_ALL), SetMinimalSize(12, 12), SetFill(0, 1),
01190                 SetDataTip(SPR_FLAG_VEH_RUNNING, STR_VEHICLE_LIST_MASS_START_LIST_TOOLTIP),
01191         NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(0, 12), SetResize(1, 0), SetFill(1, 1), EndContainer(),
01192       EndContainer(),
01193       /* Widget to be shown for other companies hiding the previous 5 widgets. */
01194       NWidget(WWT_PANEL, COLOUR_GREY), SetFill(1, 1), SetResize(1, 0), EndContainer(),
01195     EndContainer(),
01196     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
01197   EndContainer(),
01198 };
01199 
01200 static void DrawSmallOrderList(const Vehicle *v, int left, int right, int y, VehicleOrderID start = 0)
01201 {
01202   const Order *order = v->GetOrder(start);
01203   if (order == NULL) return;
01204 
01205   int i = 0;
01206   VehicleOrderID oid = start;
01207 
01208   do {
01209     if (oid == v->cur_real_order_index) DrawString(left, right, y, STR_TINY_RIGHT_ARROW, TC_BLACK);
01210 
01211     if (order->IsType(OT_GOTO_STATION)) {
01212       SetDParam(0, order->GetDestination());
01213       DrawString(left + 6, right - 6, y, STR_TINY_BLACK_STATION);
01214 
01215       y += FONT_HEIGHT_SMALL;
01216       if (++i == 4) break;
01217     }
01218 
01219     oid++;
01220     order = order->next;
01221     if (order == NULL) {
01222       order = v->orders.list->GetFirstOrder();
01223       oid = 0;
01224     }
01225   } while (oid != start);
01226 }
01227 
01237 void DrawVehicleImage(const Vehicle *v, int left, int right, int y, VehicleID selection, EngineImageType image_type, int skip)
01238 {
01239   switch (v->type) {
01240     case VEH_TRAIN:    DrawTrainImage(Train::From(v), left, right, y, selection, image_type, skip); break;
01241     case VEH_ROAD:     DrawRoadVehImage(v, left, right, y, selection, image_type, skip);  break;
01242     case VEH_SHIP:     DrawShipImage(v, left, right, y, selection, image_type);     break;
01243     case VEH_AIRCRAFT: DrawAircraftImage(v, left, right, y, selection, image_type); break;
01244     default: NOT_REACHED();
01245   }
01246 }
01247 
01254 uint GetVehicleListHeight(VehicleType type, uint divisor)
01255 {
01256   /* Name + vehicle + profit */
01257   uint base = GetVehicleHeight(type) + 2 * FONT_HEIGHT_SMALL;
01258   /* Drawing of the 4 small orders + profit*/
01259   if (type >= VEH_SHIP) base = max(base, 5U * FONT_HEIGHT_SMALL);
01260 
01261   if (divisor == 1) return base;
01262 
01263   /* Make sure the height is dividable by divisor */
01264   uint rem = base % divisor;
01265   return base + (rem == 0 ? 0 : divisor - rem);
01266 }
01267 
01274 void BaseVehicleListWindow::DrawVehicleListItems(VehicleID selected_vehicle, int line_height, const Rect &r) const
01275 {
01276   int left = r.left + WD_MATRIX_LEFT;
01277   int right = r.right - WD_MATRIX_RIGHT;
01278   int width = right - left;
01279   bool rtl = _current_text_dir == TD_RTL;
01280 
01281   int text_offset = GetDigitWidth() * this->unitnumber_digits + WD_FRAMERECT_RIGHT;
01282   int text_left  = left  + (rtl ?           0 : text_offset);
01283   int text_right = right - (rtl ? text_offset :           0);
01284 
01285   bool show_orderlist = this->vli.vtype >= VEH_SHIP;
01286   int orderlist_left  = left  + (rtl ? 0 : max(100 + text_offset, width / 2));
01287   int orderlist_right = right - (rtl ? max(100 + text_offset, width / 2) : 0);
01288 
01289   int image_left  = (rtl && show_orderlist) ? orderlist_right : text_left;
01290   int image_right = (!rtl && show_orderlist) ? orderlist_left : text_right;
01291 
01292   int vehicle_button_x = rtl ? right - GetSpriteSize(SPR_PROFIT_LOT).width : left;
01293 
01294   int y = r.top;
01295   uint max = min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->vehicles.Length());
01296   for (uint i = this->vscroll->GetPosition(); i < max; ++i) {
01297     const Vehicle *v = this->vehicles[i];
01298     StringID str;
01299 
01300     SetDParam(0, v->GetDisplayProfitThisYear());
01301     SetDParam(1, v->GetDisplayProfitLastYear());
01302 
01303     DrawVehicleImage(v, image_left, image_right, y + FONT_HEIGHT_SMALL - 1, selected_vehicle, EIT_IN_LIST, 0);
01304     DrawString(text_left, text_right, y + line_height - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1, STR_VEHICLE_LIST_PROFIT_THIS_YEAR_LAST_YEAR);
01305 
01306     if (v->name != NULL) {
01307       /* The vehicle got a name so we will print it */
01308       SetDParam(0, v->index);
01309       DrawString(text_left, text_right, y, STR_TINY_BLACK_VEHICLE);
01310     } else if (v->group_id != DEFAULT_GROUP) {
01311       /* The vehicle has no name, but is member of a group, so print group name */
01312       SetDParam(0, v->group_id);
01313       DrawString(text_left, text_right, y, STR_TINY_GROUP, TC_BLACK);
01314     }
01315 
01316     if (show_orderlist) DrawSmallOrderList(v, orderlist_left, orderlist_right, y, v->cur_real_order_index);
01317 
01318     if (v->IsInDepot()) {
01319       str = STR_BLUE_COMMA;
01320     } else {
01321       str = (v->age > v->max_age - DAYS_IN_LEAP_YEAR) ? STR_RED_COMMA : STR_BLACK_COMMA;
01322     }
01323 
01324     SetDParam(0, v->unitnumber);
01325     DrawString(left, right, y + 2, str);
01326 
01327     DrawVehicleProfitButton(v, vehicle_button_x, y + FONT_HEIGHT_NORMAL + 3);
01328 
01329     y += line_height;
01330   }
01331 }
01332 
01342 struct VehicleListWindow : public BaseVehicleListWindow {
01343 private:
01345   enum ButtonPlanes {
01346     BP_SHOW_BUTTONS, 
01347     BP_HIDE_BUTTONS, 
01348   };
01349 
01350 public:
01351   VehicleListWindow(const WindowDesc *desc, WindowNumber window_number) : BaseVehicleListWindow(window_number)
01352   {
01353     /* Set up sorting. Make the window-specific _sorting variable
01354      * point to the correct global _sorting struct so we are freed
01355      * from having conditionals during window operation */
01356     switch (this->vli.vtype) {
01357       case VEH_TRAIN:    this->sorting = &_sorting.train; break;
01358       case VEH_ROAD:     this->sorting = &_sorting.roadveh; break;
01359       case VEH_SHIP:     this->sorting = &_sorting.ship; break;
01360       case VEH_AIRCRAFT: this->sorting = &_sorting.aircraft; break;
01361       default: NOT_REACHED();
01362     }
01363 
01364     this->CreateNestedTree(desc);
01365 
01366     this->vscroll = this->GetScrollbar(WID_VL_SCROLLBAR);
01367 
01368     this->vehicles.SetListing(*this->sorting);
01369     this->vehicles.ForceRebuild();
01370     this->vehicles.NeedResort();
01371     this->BuildVehicleList();
01372     this->SortVehicleList();
01373 
01374     /* Set up the window widgets */
01375     this->GetWidget<NWidgetCore>(WID_VL_LIST)->tool_tip = STR_VEHICLE_LIST_TRAIN_LIST_TOOLTIP + this->vli.vtype;
01376 
01377     if (this->vli.type == VL_SHARED_ORDERS) {
01378       this->GetWidget<NWidgetCore>(WID_VL_CAPTION)->widget_data = STR_VEHICLE_LIST_SHARED_ORDERS_LIST_CAPTION;
01379     } else {
01380       this->GetWidget<NWidgetCore>(WID_VL_CAPTION)->widget_data = STR_VEHICLE_LIST_TRAIN_CAPTION + this->vli.vtype;
01381     }
01382 
01383     this->FinishInitNested(desc, window_number);
01384     this->owner = this->vli.company;
01385 
01386     if (this->vli.vtype == VEH_TRAIN) ResizeWindow(this, 65, 0);
01387   }
01388 
01389   ~VehicleListWindow()
01390   {
01391     *this->sorting = this->vehicles.GetListing();
01392   }
01393 
01394   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01395   {
01396     switch (widget) {
01397       case WID_VL_LIST:
01398         resize->height = GetVehicleListHeight(this->vli.vtype, 1);
01399 
01400         switch (this->vli.vtype) {
01401           case VEH_TRAIN:
01402           case VEH_ROAD:
01403             size->height = 6 * resize->height;
01404             break;
01405           case VEH_SHIP:
01406           case VEH_AIRCRAFT:
01407             size->height = 4 * resize->height;
01408             break;
01409           default: NOT_REACHED();
01410         }
01411         break;
01412 
01413       case WID_VL_SORT_ORDER: {
01414         Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
01415         d.width += padding.width + WD_SORTBUTTON_ARROW_WIDTH * 2; // Doubled since the string is centred and it also looks better.
01416         d.height += padding.height;
01417         *size = maxdim(*size, d);
01418         break;
01419       }
01420 
01421       case WID_VL_MANAGE_VEHICLES_DROPDOWN: {
01422         Dimension d = this->GetActionDropdownSize(this->vli.type == VL_STANDARD, false);
01423         d.height += padding.height;
01424         d.width  += padding.width;
01425         *size = maxdim(*size, d);
01426         break;
01427       }
01428     }
01429   }
01430 
01431   virtual void SetStringParameters(int widget) const
01432   {
01433     switch (widget) {
01434       case WID_VL_AVAILABLE_VEHICLES:
01435         SetDParam(0, STR_VEHICLE_LIST_AVAILABLE_TRAINS + this->vli.vtype);
01436         break;
01437 
01438       case WID_VL_CAPTION: {
01439         switch (this->vli.type) {
01440           case VL_SHARED_ORDERS: // Shared Orders
01441             if (this->vehicles.Length() == 0) {
01442               /* We can't open this window without vehicles using this order
01443                * and we should close the window when deleting the order. */
01444               NOT_REACHED();
01445             }
01446             SetDParam(0, this->vscroll->GetCount());
01447             break;
01448 
01449           case VL_STANDARD: // Company Name
01450             SetDParam(0, STR_COMPANY_NAME);
01451             SetDParam(1, this->vli.index);
01452             SetDParam(3, this->vscroll->GetCount());
01453             break;
01454 
01455           case VL_STATION_LIST: // Station/Waypoint Name
01456             SetDParam(0, Station::IsExpected(BaseStation::Get(this->vli.index)) ? STR_STATION_NAME : STR_WAYPOINT_NAME);
01457             SetDParam(1, this->vli.index);
01458             SetDParam(3, this->vscroll->GetCount());
01459             break;
01460 
01461           case VL_DEPOT_LIST:
01462             SetDParam(0, STR_DEPOT_CAPTION);
01463             SetDParam(1, this->vli.vtype);
01464             SetDParam(2, this->vli.index);
01465             SetDParam(3, this->vscroll->GetCount());
01466             break;
01467           default: NOT_REACHED();
01468         }
01469         break;
01470       }
01471     }
01472   }
01473 
01474   virtual void DrawWidget(const Rect &r, int widget) const
01475   {
01476     switch (widget) {
01477       case WID_VL_SORT_ORDER:
01478         /* draw arrow pointing up/down for ascending/descending sorting */
01479         this->DrawSortButtonState(widget, this->vehicles.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
01480         break;
01481 
01482       case WID_VL_LIST:
01483         this->DrawVehicleListItems(INVALID_VEHICLE, this->resize.step_height, r);
01484         break;
01485     }
01486   }
01487 
01488   virtual void OnPaint()
01489   {
01490     this->BuildVehicleList();
01491     this->SortVehicleList();
01492 
01493     if (this->vehicles.Length() == 0 && this->IsWidgetLowered(WID_VL_MANAGE_VEHICLES_DROPDOWN)) {
01494       HideDropDownMenu(this);
01495     }
01496 
01497     /* Hide the widgets that we will not use in this window
01498      * Some windows contains actions only fit for the owner */
01499     int plane_to_show = (this->owner == _local_company) ? BP_SHOW_BUTTONS : BP_HIDE_BUTTONS;
01500     NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VL_HIDE_BUTTONS);
01501     if (plane_to_show != nwi->shown_plane) {
01502       nwi->SetDisplayedPlane(plane_to_show);
01503       nwi->SetDirty(this);
01504     }
01505     if (this->owner == _local_company) {
01506       this->SetWidgetDisabledState(WID_VL_AVAILABLE_VEHICLES, this->vli.type != VL_STANDARD);
01507       this->SetWidgetsDisabledState(this->vehicles.Length() == 0,
01508         WID_VL_MANAGE_VEHICLES_DROPDOWN,
01509         WID_VL_STOP_ALL,
01510         WID_VL_START_ALL,
01511         WIDGET_LIST_END);
01512     }
01513 
01514     /* Set text of sort by dropdown widget. */
01515     this->GetWidget<NWidgetCore>(WID_VL_SORT_BY_PULLDOWN)->widget_data = this->vehicle_sorter_names[this->vehicles.SortType()];
01516 
01517     this->DrawWidgets();
01518   }
01519 
01520   virtual void OnClick(Point pt, int widget, int click_count)
01521   {
01522     switch (widget) {
01523       case WID_VL_SORT_ORDER: // Flip sorting method ascending/descending
01524         this->vehicles.ToggleSortOrder();
01525         this->SetDirty();
01526         break;
01527 
01528       case WID_VL_SORT_BY_PULLDOWN:// Select sorting criteria dropdown menu
01529         ShowDropDownMenu(this, this->vehicle_sorter_names, this->vehicles.SortType(), WID_VL_SORT_BY_PULLDOWN, 0,
01530             (this->vli.vtype == VEH_TRAIN || this->vli.vtype == VEH_ROAD) ? 0 : (1 << 10));
01531         return;
01532 
01533       case WID_VL_LIST: { // Matrix to show vehicles
01534         uint id_v = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_VL_LIST);
01535         if (id_v >= this->vehicles.Length()) return; // click out of list bound
01536 
01537         const Vehicle *v = this->vehicles[id_v];
01538         if (!VehicleClicked(v)) ShowVehicleViewWindow(v);
01539         break;
01540       }
01541 
01542       case WID_VL_AVAILABLE_VEHICLES:
01543         ShowBuildVehicleWindow(INVALID_TILE, this->vli.vtype);
01544         break;
01545 
01546       case WID_VL_MANAGE_VEHICLES_DROPDOWN: {
01547         DropDownList *list = this->BuildActionDropdownList(VehicleListIdentifier(this->window_number).type == VL_STANDARD, false);
01548         ShowDropDownList(this, list, 0, WID_VL_MANAGE_VEHICLES_DROPDOWN);
01549         break;
01550       }
01551 
01552       case WID_VL_STOP_ALL:
01553       case WID_VL_START_ALL:
01554         DoCommandP(0, (1 << 1) | (widget == WID_VL_START_ALL ? (1 << 0) : 0), this->window_number, CMD_MASS_START_STOP);
01555         break;
01556     }
01557   }
01558 
01559   virtual void OnDropdownSelect(int widget, int index)
01560   {
01561     switch (widget) {
01562       case WID_VL_SORT_BY_PULLDOWN:
01563         this->vehicles.SetSortType(index);
01564         break;
01565       case WID_VL_MANAGE_VEHICLES_DROPDOWN:
01566         assert(this->vehicles.Length() != 0);
01567 
01568         switch (index) {
01569           case ADI_REPLACE: // Replace window
01570             ShowReplaceGroupVehicleWindow(DEFAULT_GROUP, this->vli.vtype);
01571             break;
01572           case ADI_SERVICE: // Send for servicing
01573           case ADI_DEPOT: // Send to Depots
01574             DoCommandP(0, DEPOT_MASS_SEND | (index == ADI_SERVICE ? DEPOT_SERVICE : (DepotCommand)0), this->window_number, GetCmdSendToDepot(this->vli.vtype));
01575             break;
01576 
01577           default: NOT_REACHED();
01578         }
01579         break;
01580       default: NOT_REACHED();
01581     }
01582     this->SetDirty();
01583   }
01584 
01585   virtual void OnTick()
01586   {
01587     if (_pause_mode != PM_UNPAUSED) return;
01588     if (this->vehicles.NeedResort()) {
01589       StationID station = (this->vli.type == VL_STATION_LIST) ? this->vli.index : INVALID_STATION;
01590 
01591       DEBUG(misc, 3, "Periodic resort %d list company %d at station %d", this->vli.vtype, this->owner, station);
01592       this->SetDirty();
01593     }
01594   }
01595 
01596   virtual void OnResize()
01597   {
01598     this->vscroll->SetCapacityFromWidget(this, WID_VL_LIST);
01599     this->GetWidget<NWidgetCore>(WID_VL_LIST)->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
01600   }
01601 
01607   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
01608   {
01609     if (!gui_scope && HasBit(data, 31) && this->vli.type == VL_SHARED_ORDERS) {
01610       /* Needs to be done in command-scope, so everything stays valid */
01611       this->vli.index = GB(data, 0, 20);
01612       this->window_number = this->vli.Pack();
01613       this->vehicles.ForceRebuild();
01614       return;
01615     }
01616 
01617     if (data == 0) {
01618       /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
01619       this->vehicles.ForceRebuild();
01620     } else {
01621       this->vehicles.ForceResort();
01622     }
01623   }
01624 };
01625 
01626 static WindowDesc _vehicle_list_desc(
01627   WDP_AUTO, 260, 246,
01628   WC_INVALID, WC_NONE,
01629   WDF_UNCLICK_BUTTONS,
01630   _nested_vehicle_list, lengthof(_nested_vehicle_list)
01631 );
01632 
01633 static void ShowVehicleListWindowLocal(CompanyID company, VehicleListType vlt, VehicleType vehicle_type, uint16 unique_number)
01634 {
01635   if (!Company::IsValidID(company)) return;
01636 
01637   _vehicle_list_desc.cls = GetWindowClassForVehicleType(vehicle_type);
01638   AllocateWindowDescFront<VehicleListWindow>(&_vehicle_list_desc, VehicleListIdentifier(vlt, vehicle_type, company, unique_number).Pack());
01639 }
01640 
01641 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type)
01642 {
01643   /* If _settings_client.gui.advanced_vehicle_list > 1, display the Advanced list
01644    * if _settings_client.gui.advanced_vehicle_list == 1, display Advanced list only for local company
01645    * if _ctrl_pressed, do the opposite action (Advanced list x Normal list)
01646    */
01647 
01648   if ((_settings_client.gui.advanced_vehicle_list > (uint)(company != _local_company)) != _ctrl_pressed) {
01649     ShowCompanyGroup(company, vehicle_type);
01650   } else {
01651     ShowVehicleListWindowLocal(company, VL_STANDARD, vehicle_type, company);
01652   }
01653 }
01654 
01655 void ShowVehicleListWindow(const Vehicle *v)
01656 {
01657   ShowVehicleListWindowLocal(v->owner, VL_SHARED_ORDERS, v->type, v->FirstShared()->index);
01658 }
01659 
01660 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, StationID station)
01661 {
01662   if (!Company::IsValidID(company)) {
01663     company = _local_company;
01664     /* This can happen when opening the vehicle list as a spectator. */
01665     if (!Company::IsValidID(company)) return;
01666     _vehicle_list_desc.flags |= WDF_CONSTRUCTION;
01667   } else {
01668     _vehicle_list_desc.flags &= ~WDF_CONSTRUCTION;
01669   }
01670 
01671   ShowVehicleListWindowLocal(company, VL_STATION_LIST, vehicle_type, station);
01672 }
01673 
01674 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, TileIndex depot_tile)
01675 {
01676   uint16 depot_airport_index;
01677 
01678   if (vehicle_type == VEH_AIRCRAFT) {
01679     depot_airport_index = GetStationIndex(depot_tile);
01680   } else {
01681     depot_airport_index = GetDepotIndex(depot_tile);
01682   }
01683   ShowVehicleListWindowLocal(company, VL_DEPOT_LIST, vehicle_type, depot_airport_index);
01684 }
01685 
01686 
01687 /* Unified vehicle GUI - Vehicle Details Window */
01688 
01689 assert_compile(WID_VD_DETAILS_CARGO_CARRIED    == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_CARGO   );
01690 assert_compile(WID_VD_DETAILS_TRAIN_VEHICLES   == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_INFO    );
01691 assert_compile(WID_VD_DETAILS_CAPACITY_OF_EACH == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_CAPACITY);
01692 assert_compile(WID_VD_DETAILS_TOTAL_CARGO      == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_TOTALS  );
01693 
01695 static const NWidgetPart _nested_nontrain_vehicle_details_widgets[] = {
01696   NWidget(NWID_HORIZONTAL),
01697     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
01698     NWidget(WWT_CAPTION, COLOUR_GREY, WID_VD_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
01699     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 */),
01700     NWidget(WWT_SHADEBOX, COLOUR_GREY),
01701     NWidget(WWT_STICKYBOX, COLOUR_GREY),
01702   EndContainer(),
01703   NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_TOP_DETAILS), SetMinimalSize(405, 42), SetResize(1, 0), EndContainer(),
01704   NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_MIDDLE_DETAILS), SetMinimalSize(405, 45), SetResize(1, 0), EndContainer(),
01705   NWidget(NWID_HORIZONTAL),
01706     NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_DECREASE_SERVICING_INTERVAL), SetFill(0, 1),
01707         SetDataTip(AWV_DECREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
01708     NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_INCREASE_SERVICING_INTERVAL), SetFill(0, 1),
01709         SetDataTip(AWV_INCREASE, STR_VEHICLE_DETAILS_INCREASE_SERVICING_INTERVAL_TOOLTIP),
01710     NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_SERVICING_INTERVAL), SetFill(1, 1), SetResize(1, 0), EndContainer(),
01711     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
01712   EndContainer(),
01713 };
01714 
01716 static const NWidgetPart _nested_train_vehicle_details_widgets[] = {
01717   NWidget(NWID_HORIZONTAL),
01718     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
01719     NWidget(WWT_CAPTION, COLOUR_GREY, WID_VD_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
01720     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 */),
01721     NWidget(WWT_SHADEBOX, COLOUR_GREY),
01722     NWidget(WWT_STICKYBOX, COLOUR_GREY),
01723   EndContainer(),
01724   NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_TOP_DETAILS), SetResize(1, 0), SetMinimalSize(405, 42), EndContainer(),
01725   NWidget(NWID_HORIZONTAL),
01726     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),
01727     NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VD_SCROLLBAR),
01728   EndContainer(),
01729   NWidget(NWID_HORIZONTAL),
01730     NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_DECREASE_SERVICING_INTERVAL), SetFill(0, 1),
01731         SetDataTip(AWV_DECREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
01732     NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_INCREASE_SERVICING_INTERVAL), SetFill(0, 1),
01733         SetDataTip(AWV_INCREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
01734     NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_SERVICING_INTERVAL), SetFill(1, 1), SetResize(1, 0), EndContainer(),
01735   EndContainer(),
01736   NWidget(NWID_HORIZONTAL),
01737     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_CARGO_CARRIED), SetMinimalSize(96, 12),
01738         SetDataTip(STR_VEHICLE_DETAIL_TAB_CARGO, STR_VEHICLE_DETAILS_TRAIN_CARGO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
01739     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_TRAIN_VEHICLES), SetMinimalSize(99, 12),
01740         SetDataTip(STR_VEHICLE_DETAIL_TAB_INFORMATION, STR_VEHICLE_DETAILS_TRAIN_INFORMATION_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
01741     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_CAPACITY_OF_EACH), SetMinimalSize(99, 12),
01742         SetDataTip(STR_VEHICLE_DETAIL_TAB_CAPACITIES, STR_VEHICLE_DETAILS_TRAIN_CAPACITIES_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
01743     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_TOTAL_CARGO), SetMinimalSize(99, 12),
01744         SetDataTip(STR_VEHICLE_DETAIL_TAB_TOTAL_CARGO, STR_VEHICLE_DETAILS_TRAIN_TOTAL_CARGO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
01745     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
01746   EndContainer(),
01747 };
01748 
01749 
01750 extern int GetTrainDetailsWndVScroll(VehicleID veh_id, TrainDetailsWindowTabs det_tab);
01751 extern void DrawTrainDetails(const Train *v, int left, int right, int y, int vscroll_pos, uint16 vscroll_cap, TrainDetailsWindowTabs det_tab);
01752 extern void DrawRoadVehDetails(const Vehicle *v, int left, int right, int y);
01753 extern void DrawShipDetails(const Vehicle *v, int left, int right, int y);
01754 extern void DrawAircraftDetails(const Aircraft *v, int left, int right, int y);
01755 
01757 struct VehicleDetailsWindow : Window {
01758   TrainDetailsWindowTabs tab; 
01759   Scrollbar *vscroll;
01760 
01762   VehicleDetailsWindow(const WindowDesc *desc, WindowNumber window_number) : Window()
01763   {
01764     const Vehicle *v = Vehicle::Get(window_number);
01765 
01766     this->CreateNestedTree(desc);
01767     this->vscroll = (v->type == VEH_TRAIN ? this->GetScrollbar(WID_VD_SCROLLBAR) : NULL);
01768     this->FinishInitNested(desc, window_number);
01769 
01770     this->GetWidget<NWidgetCore>(WID_VD_RENAME_VEHICLE)->tool_tip = STR_VEHICLE_DETAILS_TRAIN_RENAME + v->type;
01771 
01772     this->owner = v->owner;
01773     this->tab = TDW_TAB_CARGO;
01774   }
01775 
01781   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
01782   {
01783     if (data == -666) {
01784       /* Autoreplace replaced the vehicle.
01785        * Nothing to do for this window. */
01786       return;
01787     }
01788     if (!gui_scope) return;
01789     const Vehicle *v = Vehicle::Get(this->window_number);
01790     if (v->type == VEH_ROAD) {
01791       const NWidgetBase *nwid_info = this->GetWidget<NWidgetBase>(WID_VD_MIDDLE_DETAILS);
01792       uint aimed_height = this->GetRoadVehDetailsHeight(v);
01793       /* If the number of articulated parts changes, the size of the window must change too. */
01794       if (aimed_height != nwid_info->current_y) {
01795         this->ReInit();
01796       }
01797     }
01798   }
01799 
01805   uint GetRoadVehDetailsHeight(const Vehicle *v)
01806   {
01807     uint desired_height;
01808     if (v->HasArticulatedPart()) {
01809       /* An articulated RV has its text drawn under the sprite instead of after it, hence 15 pixels extra. */
01810       desired_height = WD_FRAMERECT_TOP + 15 + 3 * FONT_HEIGHT_NORMAL + 2 + WD_FRAMERECT_BOTTOM;
01811       /* Add space for the cargo amount for each part. */
01812       for (const Vehicle *u = v; u != NULL; u = u->Next()) {
01813         if (u->cargo_cap != 0) desired_height += FONT_HEIGHT_NORMAL + 1;
01814       }
01815     } else {
01816       desired_height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + 3 + WD_FRAMERECT_BOTTOM;
01817     }
01818     return desired_height;
01819   }
01820 
01821   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01822   {
01823     switch (widget) {
01824       case WID_VD_TOP_DETAILS: {
01825         Dimension dim = { 0, 0 };
01826         size->height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
01827 
01828         for (uint i = 0; i < 4; i++) SetDParam(i, INT16_MAX);
01829         static const StringID info_strings[] = {
01830           STR_VEHICLE_INFO_MAX_SPEED,
01831           STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED,
01832           STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE,
01833           STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR,
01834           STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS
01835         };
01836         for (uint i = 0; i < lengthof(info_strings); i++) {
01837           dim = maxdim(dim, GetStringBoundingBox(info_strings[i]));
01838         }
01839         SetDParam(0, STR_VEHICLE_INFO_AGE);
01840         dim = maxdim(dim, GetStringBoundingBox(STR_VEHICLE_INFO_AGE_RUNNING_COST_YR));
01841         size->width = dim.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
01842         break;
01843       }
01844 
01845       case WID_VD_MIDDLE_DETAILS: {
01846         const Vehicle *v = Vehicle::Get(this->window_number);
01847         switch (v->type) {
01848           case VEH_ROAD:
01849             size->height = this->GetRoadVehDetailsHeight(v);
01850             break;
01851 
01852           case VEH_SHIP:
01853             size->height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + 3 + WD_FRAMERECT_BOTTOM;
01854             break;
01855 
01856           case VEH_AIRCRAFT:
01857             size->height = WD_FRAMERECT_TOP + 5 * FONT_HEIGHT_NORMAL + 4 + WD_FRAMERECT_BOTTOM;
01858             break;
01859 
01860           default:
01861             NOT_REACHED(); // Train uses WID_VD_MATRIX instead.
01862         }
01863         break;
01864       }
01865 
01866       case WID_VD_MATRIX:
01867         resize->height = WD_MATRIX_TOP + FONT_HEIGHT_NORMAL + WD_MATRIX_BOTTOM;
01868         size->height = 4 * resize->height;
01869         break;
01870 
01871       case WID_VD_SERVICING_INTERVAL:
01872         SetDParam(0, 9999); // Roughly the maximum interval
01873         SetDParam(1, MAX_YEAR * DAYS_IN_YEAR); // Roughly the maximum year
01874         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;
01875         size->height = WD_FRAMERECT_TOP + FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
01876         break;
01877     }
01878   }
01879 
01881   static bool IsVehicleServiceIntervalEnabled(const VehicleType vehicle_type, CompanyID company_id)
01882   {
01883     const VehicleDefaultSettings *vds = &Company::Get(company_id)->settings.vehicle;
01884     switch (vehicle_type) {
01885       default: NOT_REACHED();
01886       case VEH_TRAIN:    return vds->servint_trains   != 0;
01887       case VEH_ROAD:     return vds->servint_roadveh  != 0;
01888       case VEH_SHIP:     return vds->servint_ships    != 0;
01889       case VEH_AIRCRAFT: return vds->servint_aircraft != 0;
01890     }
01891   }
01892 
01904   static void DrawVehicleDetails(const Vehicle *v, int left, int right, int y, int vscroll_pos, uint vscroll_cap, TrainDetailsWindowTabs det_tab)
01905   {
01906     switch (v->type) {
01907       case VEH_TRAIN:    DrawTrainDetails(Train::From(v), left, right, y, vscroll_pos, vscroll_cap, det_tab);  break;
01908       case VEH_ROAD:     DrawRoadVehDetails(v, left, right, y);  break;
01909       case VEH_SHIP:     DrawShipDetails(v, left, right, y);     break;
01910       case VEH_AIRCRAFT: DrawAircraftDetails(Aircraft::From(v), left, right, y); break;
01911       default: NOT_REACHED();
01912     }
01913   }
01914 
01915   virtual void SetStringParameters(int widget) const
01916   {
01917     if (widget == WID_VD_CAPTION) SetDParam(0, Vehicle::Get(this->window_number)->index);
01918   }
01919 
01920   virtual void DrawWidget(const Rect &r, int widget) const
01921   {
01922     const Vehicle *v = Vehicle::Get(this->window_number);
01923 
01924     switch (widget) {
01925       case WID_VD_TOP_DETAILS: {
01926         int y = r.top + WD_FRAMERECT_TOP;
01927 
01928         /* Draw running cost */
01929         SetDParam(1, v->age / DAYS_IN_LEAP_YEAR);
01930         SetDParam(0, (v->age + DAYS_IN_YEAR < v->max_age) ? STR_VEHICLE_INFO_AGE : STR_VEHICLE_INFO_AGE_RED);
01931         SetDParam(2, v->max_age / DAYS_IN_LEAP_YEAR);
01932         SetDParam(3, v->GetDisplayRunningCost());
01933         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_AGE_RUNNING_COST_YR);
01934         y += FONT_HEIGHT_NORMAL;
01935 
01936         /* Draw max speed */
01937         StringID string;
01938         if (v->type == VEH_TRAIN ||
01939             (v->type == VEH_ROAD && _settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL)) {
01940           const GroundVehicleCache *gcache = v->GetGroundVehicleCache();
01941           SetDParam(2, v->GetDisplayMaxSpeed());
01942           SetDParam(1, gcache->cached_power);
01943           SetDParam(0, gcache->cached_weight);
01944           SetDParam(3, gcache->cached_max_te / 1000);
01945           if (v->type == VEH_TRAIN && (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ||
01946               GetRailTypeInfo(Train::From(v)->railtype)->acceleration_type == 2)) {
01947             string = STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED;
01948           } else {
01949             string = STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE;
01950           }
01951         } else {
01952           SetDParam(0, v->GetDisplayMaxSpeed());
01953           if (v->type == VEH_AIRCRAFT && Aircraft::From(v)->GetRange() > 0) {
01954             SetDParam(1, Aircraft::From(v)->GetRange());
01955             string = STR_VEHICLE_INFO_MAX_SPEED_RANGE;
01956           } else {
01957             string = STR_VEHICLE_INFO_MAX_SPEED;
01958           }
01959         }
01960         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, string);
01961         y += FONT_HEIGHT_NORMAL;
01962 
01963         /* Draw profit */
01964         SetDParam(0, v->GetDisplayProfitThisYear());
01965         SetDParam(1, v->GetDisplayProfitLastYear());
01966         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR);
01967         y += FONT_HEIGHT_NORMAL;
01968 
01969         /* Draw breakdown & reliability */
01970         SetDParam(0, ToPercent16(v->reliability));
01971         SetDParam(1, v->breakdowns_since_last_service);
01972         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS);
01973         break;
01974       }
01975 
01976       case WID_VD_MATRIX:
01977         /* For trains only. */
01978         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);
01979         break;
01980 
01981       case WID_VD_MIDDLE_DETAILS: {
01982         /* For other vehicles, at the place of the matrix. */
01983         bool rtl = _current_text_dir == TD_RTL;
01984         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;
01985 
01986         uint text_left  = r.left  + (rtl ? 0 : sprite_width);
01987         uint text_right = r.right - (rtl ? sprite_width : 0);
01988 
01989         /* Articulated road vehicles use a complete line. */
01990         if (v->type == VEH_ROAD && v->HasArticulatedPart()) {
01991           DrawVehicleImage(v, r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, 0);
01992         } else {
01993           uint sprite_left  = rtl ? text_right : r.left;
01994           uint sprite_right = rtl ? r.right : text_left;
01995 
01996           DrawVehicleImage(v, sprite_left + WD_FRAMERECT_LEFT, sprite_right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, 0);
01997         }
01998         DrawVehicleDetails(v, text_left + WD_FRAMERECT_LEFT, text_right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, 0, 0, this->tab);
01999         break;
02000       }
02001 
02002       case WID_VD_SERVICING_INTERVAL:
02003         /* Draw service interval text */
02004         SetDParam(0, v->service_interval);
02005         SetDParam(1, v->date_of_last_service);
02006         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + (r.bottom - r.top + 1 - FONT_HEIGHT_NORMAL) / 2,
02007             Company::Get(v->owner)->settings.vehicle.servint_ispercent ? STR_VEHICLE_DETAILS_SERVICING_INTERVAL_PERCENT : STR_VEHICLE_DETAILS_SERVICING_INTERVAL_DAYS);
02008         break;
02009     }
02010   }
02011 
02013   virtual void OnPaint()
02014   {
02015     const Vehicle *v = Vehicle::Get(this->window_number);
02016 
02017     this->SetWidgetDisabledState(WID_VD_RENAME_VEHICLE, v->owner != _local_company);
02018 
02019     if (v->type == VEH_TRAIN) {
02020       this->DisableWidget(this->tab + WID_VD_DETAILS_CARGO_CARRIED);
02021       this->vscroll->SetCount(GetTrainDetailsWndVScroll(v->index, this->tab));
02022     }
02023 
02024     /* Disable service-scroller when interval is set to disabled */
02025     this->SetWidgetsDisabledState(!IsVehicleServiceIntervalEnabled(v->type, v->owner),
02026       WID_VD_INCREASE_SERVICING_INTERVAL,
02027       WID_VD_DECREASE_SERVICING_INTERVAL,
02028       WIDGET_LIST_END);
02029 
02030     this->DrawWidgets();
02031   }
02032 
02033   virtual void OnClick(Point pt, int widget, int click_count)
02034   {
02035     switch (widget) {
02036       case WID_VD_RENAME_VEHICLE: { // rename
02037         const Vehicle *v = Vehicle::Get(this->window_number);
02038         SetDParam(0, v->index);
02039         ShowQueryString(STR_VEHICLE_NAME, STR_QUERY_RENAME_TRAIN_CAPTION + v->type,
02040             MAX_LENGTH_VEHICLE_NAME_CHARS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
02041         break;
02042       }
02043 
02044       case WID_VD_INCREASE_SERVICING_INTERVAL:   // increase int
02045       case WID_VD_DECREASE_SERVICING_INTERVAL: { // decrease int
02046         int mod = _ctrl_pressed ? 5 : 10;
02047         const Vehicle *v = Vehicle::Get(this->window_number);
02048 
02049         mod = (widget == WID_VD_DECREASE_SERVICING_INTERVAL) ? -mod : mod;
02050         mod = GetServiceIntervalClamped(mod + v->service_interval, v->owner);
02051         if (mod == v->service_interval) return;
02052 
02053         DoCommandP(v->tile, v->index, mod, CMD_CHANGE_SERVICE_INT | CMD_MSG(STR_ERROR_CAN_T_CHANGE_SERVICING));
02054         break;
02055       }
02056 
02057       case WID_VD_DETAILS_CARGO_CARRIED:
02058       case WID_VD_DETAILS_TRAIN_VEHICLES:
02059       case WID_VD_DETAILS_CAPACITY_OF_EACH:
02060       case WID_VD_DETAILS_TOTAL_CARGO:
02061         this->SetWidgetsDisabledState(false,
02062           WID_VD_DETAILS_CARGO_CARRIED,
02063           WID_VD_DETAILS_TRAIN_VEHICLES,
02064           WID_VD_DETAILS_CAPACITY_OF_EACH,
02065           WID_VD_DETAILS_TOTAL_CARGO,
02066           widget,
02067           WIDGET_LIST_END);
02068 
02069         this->tab = (TrainDetailsWindowTabs)(widget - WID_VD_DETAILS_CARGO_CARRIED);
02070         this->SetDirty();
02071         break;
02072     }
02073   }
02074 
02075   virtual void OnQueryTextFinished(char *str)
02076   {
02077     if (str == NULL) return;
02078 
02079     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);
02080   }
02081 
02082   virtual void OnResize()
02083   {
02084     NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_VD_MATRIX);
02085     if (nwi != NULL) {
02086       this->vscroll->SetCapacityFromWidget(this, WID_VD_MATRIX);
02087       nwi->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
02088     }
02089   }
02090 };
02091 
02093 static const WindowDesc _train_vehicle_details_desc(
02094   WDP_AUTO, 405, 178,
02095   WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
02096   WDF_UNCLICK_BUTTONS,
02097   _nested_train_vehicle_details_widgets, lengthof(_nested_train_vehicle_details_widgets)
02098 );
02099 
02101 static const WindowDesc _nontrain_vehicle_details_desc(
02102   WDP_AUTO, 405, 113,
02103   WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
02104   WDF_UNCLICK_BUTTONS,
02105   _nested_nontrain_vehicle_details_widgets, lengthof(_nested_nontrain_vehicle_details_widgets)
02106 );
02107 
02109 static void ShowVehicleDetailsWindow(const Vehicle *v)
02110 {
02111   DeleteWindowById(WC_VEHICLE_ORDERS, v->index, false);
02112   DeleteWindowById(WC_VEHICLE_TIMETABLE, v->index, false);
02113   AllocateWindowDescFront<VehicleDetailsWindow>((v->type == VEH_TRAIN) ? &_train_vehicle_details_desc : &_nontrain_vehicle_details_desc, v->index);
02114 }
02115 
02116 
02117 /* Unified vehicle GUI - Vehicle View Window */
02118 
02120 static const NWidgetPart _nested_vehicle_view_widgets[] = {
02121   NWidget(NWID_HORIZONTAL),
02122     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
02123     NWidget(WWT_CAPTION, COLOUR_GREY, WID_VV_CAPTION), SetDataTip(STR_VEHICLE_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
02124     NWidget(WWT_DEBUGBOX, COLOUR_GREY),
02125     NWidget(WWT_SHADEBOX, COLOUR_GREY),
02126     NWidget(WWT_STICKYBOX, COLOUR_GREY),
02127   EndContainer(),
02128   NWidget(NWID_HORIZONTAL),
02129     NWidget(WWT_PANEL, COLOUR_GREY),
02130       NWidget(WWT_INSET, COLOUR_GREY), SetPadding(2, 2, 2, 2),
02131         NWidget(NWID_VIEWPORT, INVALID_COLOUR, WID_VV_VIEWPORT), SetMinimalSize(226, 84), SetResize(1, 1), SetPadding(1, 1, 1, 1),
02132       EndContainer(),
02133     EndContainer(),
02134     NWidget(NWID_VERTICAL),
02135       NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_CENTER_MAIN_VIEW), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(SPR_CENTRE_VIEW_VEHICLE, 0x0 /* filled later */),
02136       NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VV_SELECT_DEPOT_CLONE),
02137         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_GOTO_DEPOT), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
02138         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_CLONE), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
02139       EndContainer(),
02140       /* For trains only, 'ignore signal' button. */
02141       NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_FORCE_PROCEED), SetMinimalSize(18, 18), SetFill(1, 1),
02142                       SetDataTip(SPR_IGNORE_SIGNALS, STR_VEHICLE_VIEW_TRAIN_IGNORE_SIGNAL_TOOLTIP),
02143       NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VV_SELECT_REFIT_TURN),
02144         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_REFIT), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(SPR_REFIT_VEHICLE, 0x0 /* filled later */),
02145         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_TURN_AROUND), SetMinimalSize(18, 18), SetFill(1, 1),
02146                         SetDataTip(SPR_FORCE_VEHICLE_TURN, STR_VEHICLE_VIEW_ROAD_VEHICLE_REVERSE_TOOLTIP),
02147       EndContainer(),
02148       NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_SHOW_ORDERS), SetFill(1, 1), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_ORDERS, 0x0 /* filled later */),
02149       NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_SHOW_DETAILS), SetFill(1, 1), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_VEHICLE_DETAILS, 0x0 /* filled later */),
02150       NWidget(WWT_PANEL, COLOUR_GREY), SetFill(1, 1), SetMinimalSize(18, 0), SetResize(0, 1), EndContainer(),
02151     EndContainer(),
02152   EndContainer(),
02153   NWidget(NWID_HORIZONTAL),
02154     NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_VV_START_STOP), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetResize(1, 0), SetFill(1, 0),
02155     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
02156   EndContainer(),
02157 };
02158 
02160 static const WindowDesc _vehicle_view_desc(
02161   WDP_AUTO, 250, 116,
02162   WC_VEHICLE_VIEW, WC_NONE,
02163   WDF_UNCLICK_BUTTONS,
02164   _nested_vehicle_view_widgets, lengthof(_nested_vehicle_view_widgets)
02165 );
02166 
02171 static const WindowDesc _train_view_desc(
02172   WDP_AUTO, 250, 134,
02173   WC_VEHICLE_VIEW, WC_NONE,
02174   WDF_UNCLICK_BUTTONS,
02175   _nested_vehicle_view_widgets, lengthof(_nested_vehicle_view_widgets)
02176 );
02177 
02178 
02179 /* Just to make sure, nobody has changed the vehicle type constants, as we are
02180    using them for array indexing in a number of places here. */
02181 assert_compile(VEH_TRAIN == 0);
02182 assert_compile(VEH_ROAD == 1);
02183 assert_compile(VEH_SHIP == 2);
02184 assert_compile(VEH_AIRCRAFT == 3);
02185 
02187 static const ZoomLevel _vehicle_view_zoom_levels[] = {
02188   ZOOM_LVL_TRAIN,
02189   ZOOM_LVL_ROADVEH,
02190   ZOOM_LVL_SHIP,
02191   ZOOM_LVL_AIRCRAFT,
02192 };
02193 
02194 /* Constants for geometry of vehicle view viewport */
02195 static const int VV_INITIAL_VIEWPORT_WIDTH = 226;
02196 static const int VV_INITIAL_VIEWPORT_HEIGHT = 84;
02197 static const int VV_INITIAL_VIEWPORT_HEIGHT_TRAIN = 102;
02198 
02200 enum VehicleCommandTranslation {
02201   VCT_CMD_START_STOP = 0,
02202   VCT_CMD_CLONE_VEH,
02203   VCT_CMD_TURN_AROUND,
02204 };
02205 
02207 static const uint32 _vehicle_command_translation_table[][4] = {
02208   { // VCT_CMD_START_STOP
02209     CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_TRAIN),
02210     CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_ROAD_VEHICLE),
02211     CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_SHIP),
02212     CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_AIRCRAFT)
02213   },
02214   { // VCT_CMD_CLONE_VEH
02215     CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_TRAIN),
02216     CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_ROAD_VEHICLE),
02217     CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_SHIP),
02218     CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_AIRCRAFT)
02219   },
02220   { // VCT_CMD_TURN_AROUND
02221     CMD_REVERSE_TRAIN_DIRECTION | CMD_MSG(STR_ERROR_CAN_T_REVERSE_DIRECTION_TRAIN),
02222     CMD_TURN_ROADVEH            | CMD_MSG(STR_ERROR_CAN_T_MAKE_ROAD_VEHICLE_TURN),
02223     0xffffffff, // invalid for ships
02224     0xffffffff  // invalid for aircrafts
02225   },
02226 };
02227 
02235 void CcStartStopVehicle(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
02236 {
02237   if (result.Failed()) return;
02238 
02239   const Vehicle *v = Vehicle::GetIfValid(p1);
02240   if (v == NULL || !v->IsPrimaryVehicle() || v->owner != _local_company) return;
02241 
02242   StringID msg = (v->vehstatus & VS_STOPPED) ? STR_VEHICLE_COMMAND_STOPPED : STR_VEHICLE_COMMAND_STARTED;
02243   Point pt = RemapCoords(v->x_pos, v->y_pos, v->z_pos);
02244   AddTextEffect(msg, pt.x, pt.y, DAY_TICKS, TE_RISING);
02245 }
02246 
02252 void StartStopVehicle(const Vehicle *v, bool texteffect)
02253 {
02254   assert(v->IsPrimaryVehicle());
02255   DoCommandP(v->tile, v->index, 0, _vehicle_command_translation_table[VCT_CMD_START_STOP][v->type], texteffect ? CcStartStopVehicle : NULL);
02256 }
02257 
02259 static bool IsVehicleRefitable(const Vehicle *v)
02260 {
02261   if (!v->IsStoppedInDepot()) return false;
02262 
02263   do {
02264     if (IsEngineRefittable(v->engine_type)) return true;
02265   } while (v->IsGroundVehicle() && (v = v->Next()) != NULL);
02266 
02267   return false;
02268 }
02269 
02271 struct VehicleViewWindow : Window {
02272 private:
02274   enum PlaneSelections {
02275     SEL_DC_GOTO_DEPOT,  
02276     SEL_DC_CLONE,       
02277 
02278     SEL_RT_REFIT,       
02279     SEL_RT_TURN_AROUND, 
02280 
02281     SEL_DC_BASEPLANE = SEL_DC_GOTO_DEPOT, 
02282     SEL_RT_BASEPLANE = SEL_RT_REFIT,      
02283   };
02284 
02289   void SelectPlane(PlaneSelections plane)
02290   {
02291     switch (plane) {
02292       case SEL_DC_GOTO_DEPOT:
02293       case SEL_DC_CLONE:
02294         this->GetWidget<NWidgetStacked>(WID_VV_SELECT_DEPOT_CLONE)->SetDisplayedPlane(plane - SEL_DC_BASEPLANE);
02295         break;
02296 
02297       case SEL_RT_REFIT:
02298       case SEL_RT_TURN_AROUND:
02299         this->GetWidget<NWidgetStacked>(WID_VV_SELECT_REFIT_TURN)->SetDisplayedPlane(plane - SEL_RT_BASEPLANE);
02300         break;
02301 
02302       default:
02303         NOT_REACHED();
02304     }
02305   }
02306 
02307 public:
02308   VehicleViewWindow(const WindowDesc *desc, WindowNumber window_number) : Window()
02309   {
02310     this->CreateNestedTree(desc);
02311 
02312     /* Sprites for the 'send to depot' button indexed by vehicle type. */
02313     static const SpriteID vehicle_view_goto_depot_sprites[] = {
02314       SPR_SEND_TRAIN_TODEPOT,
02315       SPR_SEND_ROADVEH_TODEPOT,
02316       SPR_SEND_SHIP_TODEPOT,
02317       SPR_SEND_AIRCRAFT_TODEPOT,
02318     };
02319     const Vehicle *v = Vehicle::Get(window_number);
02320     this->GetWidget<NWidgetCore>(WID_VV_GOTO_DEPOT)->widget_data = vehicle_view_goto_depot_sprites[v->type];
02321 
02322     /* Sprites for the 'clone vehicle' button indexed by vehicle type. */
02323     static const SpriteID vehicle_view_clone_sprites[] = {
02324       SPR_CLONE_TRAIN,
02325       SPR_CLONE_ROADVEH,
02326       SPR_CLONE_SHIP,
02327       SPR_CLONE_AIRCRAFT,
02328     };
02329     this->GetWidget<NWidgetCore>(WID_VV_CLONE)->widget_data = vehicle_view_clone_sprites[v->type];
02330 
02331     switch (v->type) {
02332       case VEH_TRAIN:
02333         this->GetWidget<NWidgetCore>(WID_VV_TURN_AROUND)->tool_tip = STR_VEHICLE_VIEW_TRAIN_REVERSE_TOOLTIP;
02334         break;
02335 
02336       case VEH_ROAD:
02337         break;
02338 
02339       case VEH_SHIP:
02340       case VEH_AIRCRAFT:
02341         this->SelectPlane(SEL_RT_REFIT);
02342         break;
02343 
02344       default: NOT_REACHED();
02345     }
02346     this->FinishInitNested(desc, window_number);
02347     this->owner = v->owner;
02348     this->GetWidget<NWidgetViewport>(WID_VV_VIEWPORT)->InitializeViewport(this, this->window_number | (1 << 31), _vehicle_view_zoom_levels[v->type]);
02349 
02350     this->GetWidget<NWidgetCore>(WID_VV_START_STOP)->tool_tip       = STR_VEHICLE_VIEW_TRAIN_STATE_START_STOP_TOOLTIP + v->type;
02351     this->GetWidget<NWidgetCore>(WID_VV_CENTER_MAIN_VIEW)->tool_tip = STR_VEHICLE_VIEW_TRAIN_LOCATION_TOOLTIP + v->type;
02352     this->GetWidget<NWidgetCore>(WID_VV_REFIT)->tool_tip            = STR_VEHICLE_VIEW_TRAIN_REFIT_TOOLTIP + v->type;
02353     this->GetWidget<NWidgetCore>(WID_VV_GOTO_DEPOT)->tool_tip       = STR_VEHICLE_VIEW_TRAIN_SEND_TO_DEPOT_TOOLTIP + v->type;
02354     this->GetWidget<NWidgetCore>(WID_VV_SHOW_ORDERS)->tool_tip      = STR_VEHICLE_VIEW_TRAIN_ORDERS_TOOLTIP + v->type;
02355     this->GetWidget<NWidgetCore>(WID_VV_SHOW_DETAILS)->tool_tip     = STR_VEHICLE_VIEW_TRAIN_SHOW_DETAILS_TOOLTIP + v->type;
02356     this->GetWidget<NWidgetCore>(WID_VV_CLONE)->tool_tip            = STR_VEHICLE_VIEW_CLONE_TRAIN_INFO + v->type;
02357   }
02358 
02359   ~VehicleViewWindow()
02360   {
02361     DeleteWindowById(WC_VEHICLE_ORDERS, this->window_number, false);
02362     DeleteWindowById(WC_VEHICLE_REFIT, this->window_number, false);
02363     DeleteWindowById(WC_VEHICLE_DETAILS, this->window_number, false);
02364     DeleteWindowById(WC_VEHICLE_TIMETABLE, this->window_number, false);
02365   }
02366 
02367   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
02368   {
02369     const Vehicle *v = Vehicle::Get(this->window_number);
02370     switch (widget) {
02371       case WID_VV_FORCE_PROCEED:
02372         if (v->type != VEH_TRAIN) {
02373           size->height = 0;
02374           size->width = 0;
02375         }
02376         break;
02377 
02378       case WID_VV_VIEWPORT:
02379         size->width = VV_INITIAL_VIEWPORT_WIDTH;
02380         size->height = (v->type == VEH_TRAIN) ? VV_INITIAL_VIEWPORT_HEIGHT_TRAIN : VV_INITIAL_VIEWPORT_HEIGHT;
02381         break;
02382     }
02383   }
02384 
02385   virtual void OnPaint()
02386   {
02387     const Vehicle *v = Vehicle::Get(this->window_number);
02388     bool is_localcompany = v->owner == _local_company;
02389     bool refitable_and_stopped_in_depot = IsVehicleRefitable(v);
02390 
02391     this->SetWidgetDisabledState(WID_VV_GOTO_DEPOT, !is_localcompany);
02392     this->SetWidgetDisabledState(WID_VV_REFIT, !refitable_and_stopped_in_depot || !is_localcompany);
02393     this->SetWidgetDisabledState(WID_VV_CLONE, !is_localcompany);
02394 
02395     if (v->type == VEH_TRAIN) {
02396       this->SetWidgetLoweredState(WID_VV_FORCE_PROCEED, Train::From(v)->force_proceed == TFP_SIGNAL);
02397       this->SetWidgetDisabledState(WID_VV_FORCE_PROCEED, !is_localcompany);
02398       this->SetWidgetDisabledState(WID_VV_TURN_AROUND, !is_localcompany);
02399     }
02400 
02401     this->DrawWidgets();
02402   }
02403 
02404   virtual void SetStringParameters(int widget) const
02405   {
02406     if (widget != WID_VV_CAPTION) return;
02407 
02408     const Vehicle *v = Vehicle::Get(this->window_number);
02409     SetDParam(0, v->index);
02410   }
02411 
02412   virtual void DrawWidget(const Rect &r, int widget) const
02413   {
02414     if (widget != WID_VV_START_STOP) return;
02415 
02416     const Vehicle *v = Vehicle::Get(this->window_number);
02417     StringID str;
02418     if (v->vehstatus & VS_CRASHED) {
02419       str = STR_VEHICLE_STATUS_CRASHED;
02420     } else if (v->type != VEH_AIRCRAFT && v->breakdown_ctr == 1) { // check for aircraft necessary?
02421       str = STR_VEHICLE_STATUS_BROKEN_DOWN;
02422     } else if (v->vehstatus & VS_STOPPED) {
02423       if (v->type == VEH_TRAIN) {
02424         if (v->cur_speed == 0) {
02425           if (Train::From(v)->gcache.cached_power == 0) {
02426             str = STR_VEHICLE_STATUS_TRAIN_NO_POWER;
02427           } else {
02428             str = STR_VEHICLE_STATUS_STOPPED;
02429           }
02430         } else {
02431           SetDParam(0, v->GetDisplaySpeed());
02432           str = STR_VEHICLE_STATUS_TRAIN_STOPPING_VEL;
02433         }
02434       } else { // no train
02435         str = STR_VEHICLE_STATUS_STOPPED;
02436       }
02437     } else if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_TRAIN_STUCK) && !v->current_order.IsType(OT_LOADING)) {
02438       str = STR_VEHICLE_STATUS_TRAIN_STUCK;
02439     } else if (v->type == VEH_AIRCRAFT && HasBit(Aircraft::From(v)->flags, VAF_DEST_TOO_FAR) && !v->current_order.IsType(OT_LOADING)) {
02440       str = STR_VEHICLE_STATUS_AIRCRAFT_TOO_FAR;
02441     } else { // vehicle is in a "normal" state, show current order
02442       switch (v->current_order.GetType()) {
02443         case OT_GOTO_STATION: {
02444           SetDParam(0, v->current_order.GetDestination());
02445           SetDParam(1, v->GetDisplaySpeed());
02446           str = STR_VEHICLE_STATUS_HEADING_FOR_STATION_VEL;
02447           break;
02448         }
02449 
02450         case OT_GOTO_DEPOT: {
02451           SetDParam(0, v->type);
02452           SetDParam(1, v->current_order.GetDestination());
02453           SetDParam(2, v->GetDisplaySpeed());
02454           if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
02455             /* This case *only* happens when multiple nearest depot orders
02456              * follow eachother (including an order list only one order: a
02457              * nearest depot order) and there are no reachable depots.
02458              * It is primarily to guard for the case that there is no
02459              * depot with index 0, which would be used as fallback for
02460              * evaluating the string in the status bar. */
02461             str = STR_EMPTY;
02462           } else if (v->current_order.GetDepotActionType() & ODATFB_HALT) {
02463             str = STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_VEL;
02464           } else {
02465             str = STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_SERVICE_VEL;
02466           }
02467           break;
02468         }
02469 
02470         case OT_LOADING:
02471           str = STR_VEHICLE_STATUS_LOADING_UNLOADING;
02472           break;
02473 
02474         case OT_GOTO_WAYPOINT: {
02475           assert(v->type == VEH_TRAIN || v->type == VEH_SHIP);
02476           SetDParam(0, v->current_order.GetDestination());
02477           str = STR_VEHICLE_STATUS_HEADING_FOR_WAYPOINT_VEL;
02478           SetDParam(1, v->GetDisplaySpeed());
02479           break;
02480         }
02481 
02482         case OT_LEAVESTATION:
02483           if (v->type != VEH_AIRCRAFT) {
02484             str = STR_VEHICLE_STATUS_LEAVING;
02485             break;
02486           }
02487           /* FALL THROUGH, if aircraft. Does this even happen? */
02488 
02489         default:
02490           if (v->GetNumManualOrders() == 0) {
02491             str = STR_VEHICLE_STATUS_NO_ORDERS_VEL;
02492             SetDParam(0, v->GetDisplaySpeed());
02493           } else {
02494             str = STR_EMPTY;
02495           }
02496           break;
02497       }
02498     }
02499 
02500     /* draw the flag plus orders */
02501     DrawSprite(v->vehstatus & VS_STOPPED ? SPR_FLAG_VEH_STOPPED : SPR_FLAG_VEH_RUNNING, PAL_NONE, WD_FRAMERECT_LEFT, r.top + WD_FRAMERECT_TOP);
02502     DrawString(r.left + WD_FRAMERECT_LEFT + 6, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, str, TC_FROMSTRING, SA_HOR_CENTER);
02503   }
02504 
02505   virtual void OnClick(Point pt, int widget, int click_count)
02506   {
02507     const Vehicle *v = Vehicle::Get(this->window_number);
02508 
02509     switch (widget) {
02510       case WID_VV_START_STOP: // start stop
02511         if (_ctrl_pressed) {
02512           /* Scroll to current order destination */
02513           TileIndex tile = v->current_order.GetLocation(v);
02514           if (tile != INVALID_TILE) ScrollMainWindowToTile(tile);
02515         } else {
02516           /* Start/Stop */
02517           StartStopVehicle(v, false);
02518         }
02519         break;
02520       case WID_VV_CENTER_MAIN_VIEW: {// center main view
02521         const Window *mainwindow = FindWindowById(WC_MAIN_WINDOW, 0);
02522         /* code to allow the main window to 'follow' the vehicle if the ctrl key is pressed */
02523         if (_ctrl_pressed && mainwindow->viewport->zoom <= ZOOM_LVL_OUT_4X) {
02524           mainwindow->viewport->follow_vehicle = v->index;
02525         } else {
02526           ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos);
02527         }
02528         break;
02529       }
02530 
02531       case WID_VV_GOTO_DEPOT: // goto hangar
02532         DoCommandP(v->tile, v->index | (_ctrl_pressed ? DEPOT_SERVICE : 0U), 0, GetCmdSendToDepot(v));
02533         break;
02534       case WID_VV_REFIT: // refit
02535         ShowVehicleRefitWindow(v, INVALID_VEH_ORDER_ID, this);
02536         break;
02537       case WID_VV_SHOW_ORDERS: // show orders
02538         if (_ctrl_pressed) {
02539           ShowTimetableWindow(v);
02540         } else {
02541           ShowOrdersWindow(v);
02542         }
02543         break;
02544       case WID_VV_SHOW_DETAILS: // show details
02545         ShowVehicleDetailsWindow(v);
02546         break;
02547       case WID_VV_CLONE: // clone vehicle
02548         DoCommandP(v->tile, v->index, _ctrl_pressed ? 1 : 0,
02549                     _vehicle_command_translation_table[VCT_CMD_CLONE_VEH][v->type],
02550                     CcCloneVehicle);
02551         break;
02552       case WID_VV_TURN_AROUND: // turn around
02553         assert(v->IsGroundVehicle());
02554         DoCommandP(v->tile, v->index, 0,
02555                     _vehicle_command_translation_table[VCT_CMD_TURN_AROUND][v->type]);
02556         break;
02557       case WID_VV_FORCE_PROCEED: // force proceed
02558         assert(v->type == VEH_TRAIN);
02559         DoCommandP(v->tile, v->index, 0, CMD_FORCE_TRAIN_PROCEED | CMD_MSG(STR_ERROR_CAN_T_MAKE_TRAIN_PASS_SIGNAL));
02560         break;
02561     }
02562   }
02563 
02564   virtual void OnResize()
02565   {
02566     if (this->viewport != NULL) {
02567       NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_VV_VIEWPORT);
02568       nvp->UpdateViewportCoordinates(this);
02569     }
02570   }
02571 
02572   virtual void OnTick()
02573   {
02574     const Vehicle *v = Vehicle::Get(this->window_number);
02575     bool veh_stopped = v->IsStoppedInDepot();
02576 
02577     /* Widget WID_VV_GOTO_DEPOT must be hidden if the vehicle is already stopped in depot.
02578      * Widget WID_VV_CLONE_VEH should then be shown, since cloning is allowed only while in depot and stopped.
02579      */
02580     PlaneSelections plane = veh_stopped ? SEL_DC_CLONE : SEL_DC_GOTO_DEPOT;
02581     NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VV_SELECT_DEPOT_CLONE); // Selection widget 'send to depot' / 'clone'.
02582     if (nwi->shown_plane + SEL_DC_BASEPLANE != plane) {
02583       this->SelectPlane(plane);
02584       this->SetWidgetDirty(WID_VV_SELECT_DEPOT_CLONE);
02585     }
02586     /* The same system applies to widget WID_VV_REFIT_VEH and VVW_WIDGET_TURN_AROUND.*/
02587     if (v->IsGroundVehicle()) {
02588       PlaneSelections plane = veh_stopped ? SEL_RT_REFIT : SEL_RT_TURN_AROUND;
02589       NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VV_SELECT_REFIT_TURN);
02590       if (nwi->shown_plane + SEL_RT_BASEPLANE != plane) {
02591         this->SelectPlane(plane);
02592         this->SetWidgetDirty(WID_VV_SELECT_REFIT_TURN);
02593       }
02594     }
02595   }
02596 
02602   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
02603   {
02604     if (data == -666) {
02605       /* Autoreplace replaced the vehicle.
02606        * Nothing to do for this window. */
02607       return;
02608     }
02609   }
02610 
02611   virtual bool IsNewGRFInspectable() const
02612   {
02613     return ::IsNewGRFInspectable(GetGrfSpecFeature(Vehicle::Get(this->window_number)->type), this->window_number);
02614   }
02615 
02616   virtual void ShowNewGRFInspectWindow() const
02617   {
02618 		::ShowNewGRFInspectWindow(GetGrfSpecFeature(Vehicle::Get(this->window_number)->type), this->window_number);
02619   }
02620 };
02621 
02622 
02624 void ShowVehicleViewWindow(const Vehicle *v)
02625 {
02626   AllocateWindowDescFront<VehicleViewWindow>((v->type == VEH_TRAIN) ? &_train_view_desc : &_vehicle_view_desc, v->index);
02627 }
02628 
02634 bool VehicleClicked(const Vehicle *v)
02635 {
02636   assert(v != NULL);
02637   if (!(_thd.place_mode & HT_VEHICLE)) return false;
02638 
02639   v = v->First();
02640   if (!v->IsPrimaryVehicle()) return false;
02641 
02642   return _thd.GetCallbackWnd()->OnVehicleSelect(v);
02643 }
02644 
02645 void StopGlobalFollowVehicle(const Vehicle *v)
02646 {
02647   Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
02648   if (w != NULL && w->viewport->follow_vehicle == v->index) {
02649     ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos, true); // lock the main view on the vehicle's last position
02650     w->viewport->follow_vehicle = INVALID_VEHICLE;
02651   }
02652 }
02653 
02654 
02662 void CcBuildPrimaryVehicle(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
02663 {
02664   if (result.Failed()) return;
02665 
02666   const Vehicle *v = Vehicle::Get(_new_vehicle_id);
02667   ShowVehicleViewWindow(v);
02668 }
02669 
02675 int GetVehicleWidth(Vehicle *v, EngineImageType image_type)
02676 {
02677   int vehicle_width = 0;
02678 
02679   switch (v->type) {
02680     case VEH_TRAIN:
02681       for (const Train *u = Train::From(v); u != NULL; u = u->Next()) {
02682         vehicle_width += u->GetDisplayImageWidth();
02683       }
02684       break;
02685 
02686     case VEH_ROAD:
02687       for (const RoadVehicle *u = RoadVehicle::From(v); u != NULL; u = u->Next()) {
02688         vehicle_width += u->GetDisplayImageWidth();
02689       }
02690       break;
02691 
02692     default:
02693       bool rtl = _current_text_dir == TD_RTL;
02694       SpriteID sprite = v->GetImage(rtl ? DIR_E : DIR_W, image_type);
02695       const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
02696       vehicle_width = UnScaleByZoom(real_sprite->width, ZOOM_LVL_GUI);
02697 
02698       break;
02699   }
02700 
02701   return vehicle_width;
02702 }