# vehicle_gui.cpp

Go to the documentation of this file.

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