# vehicle_gui.cpp

Go to the documentation of this file.

    00001 /* $Id: vehicle_gui.cpp 21047 2010-10-27 20:15:18Z 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.h"
    00019 #include "vehicle_gui_base.h"
    00020 #include "viewport_func.h"
    00021 #include "newgrf_engine.h"
    00022 #include "newgrf_text.h"
    00023 #include "waypoint_base.h"
    00024 #include "roadveh.h"
    00025 #include "train.h"
    00026 #include "aircraft.h"
    00027 #include "depot_base.h"
    00028 #include "group_gui.h"
    00029 #include "strings_func.h"
    00030 #include "window_func.h"
    00031 #include "vehicle_func.h"
    00032 #include "autoreplace_gui.h"
    00033 #include "string_func.h"
    00034 #include "widgets/dropdown_func.h"
    00035 #include "timetable.h"
    00036 #include "vehiclelist.h"
    00037 #include "articulated_vehicles.h"
    00038 #include "cargotype.h"
    00039 #include "spritecache.h"
    00040 #include "core/geometry_func.hpp"
    00041 #include "company_base.h"
    00042 #include "engine_base.h"
    00043 #include "engine_func.h"
    00044
    00045 #include "table/sprites.h"
    00046 #include "table/strings.h"
    00047
    00048 Sorting _sorting;
    00049
    00050 static GUIVehicleList::SortFunction VehicleNumberSorter;
    00051 static GUIVehicleList::SortFunction VehicleNameSorter;
    00052 static GUIVehicleList::SortFunction VehicleAgeSorter;
    00053 static GUIVehicleList::SortFunction VehicleProfitThisYearSorter;
    00054 static GUIVehicleList::SortFunction VehicleProfitLastYearSorter;
    00055 static GUIVehicleList::SortFunction VehicleCargoSorter;
    00056 static GUIVehicleList::SortFunction VehicleReliabilitySorter;
    00057 static GUIVehicleList::SortFunction VehicleMaxSpeedSorter;
    00058 static GUIVehicleList::SortFunction VehicleModelSorter;
    00059 static GUIVehicleList::SortFunction VehicleValueSorter;
    00060 static GUIVehicleList::SortFunction VehicleLengthSorter;
    00061 static GUIVehicleList::SortFunction VehicleTimeToLiveSorter;
    00062 static GUIVehicleList::SortFunction VehicleTimetableDelaySorter;
    00063
    00064 GUIVehicleList::SortFunction * const BaseVehicleListWindow::vehicle_sorter_funcs[] = {
    00065   &VehicleNumberSorter,
    00066   &VehicleNameSorter,
    00067   &VehicleAgeSorter,
    00068   &VehicleProfitThisYearSorter,
    00069   &VehicleProfitLastYearSorter,
    00070   &VehicleCargoSorter,
    00071   &VehicleReliabilitySorter,
    00072   &VehicleMaxSpeedSorter,
    00073   &VehicleModelSorter,
    00074   &VehicleValueSorter,
    00075   &VehicleLengthSorter,
    00076   &VehicleTimeToLiveSorter,
    00077   &VehicleTimetableDelaySorter,
    00078 };
    00079
    00080 const StringID BaseVehicleListWindow::vehicle_sorter_names[] = {
    00081   STR_SORT_BY_NUMBER,
    00082   STR_SORT_BY_NAME,
    00083   STR_SORT_BY_AGE,
    00084   STR_SORT_BY_PROFIT_THIS_YEAR,
    00085   STR_SORT_BY_PROFIT_LAST_YEAR,
    00086   STR_SORT_BY_TOTAL_CAPACITY_PER_CARGOTYPE,
    00087   STR_SORT_BY_RELIABILITY,
    00088   STR_SORT_BY_MAX_SPEED,
    00089   STR_SORT_BY_MODEL,
    00090   STR_SORT_BY_VALUE,
    00091   STR_SORT_BY_LENGTH,
    00092   STR_SORT_BY_LIFE_TIME,
    00093   STR_SORT_BY_TIMETABLE_DELAY,
    00094   INVALID_STRING_ID
    00095 };
    00096
    00097 void BaseVehicleListWindow::BuildVehicleList(Owner owner, uint16 index, uint16 window_type)
    00098 {
    00099   if (!this->vehicles.NeedRebuild()) return;
    00100
    00101   DEBUG(misc, 3, "Building vehicle list for company %d at station %d", owner, index);
    00102
    00103   GenerateVehicleSortList(&this->vehicles, this->vehicle_type, owner, index, window_type);
    00104
    00105   uint unitnumber = 0;
    00106   for (const Vehicle **v = this->vehicles.Begin(); v != this->vehicles.End(); v++) {
    00107     unitnumber = max<uint>(unitnumber, (*v)->unitnumber);
    00108   }
    00109
    00110   /* Because 111 is much less wide than e.g. 999 we use the
    00111    * wider numbers to determine the width instead of just
    00112    * the random number that it seems to be. */
    00113   if (unitnumber >= 1000) {
    00114     this->unitnumber_digits = 4;
    00115   } else if (unitnumber >= 100) {
    00116     this->unitnumber_digits = 3;
    00117   } else {
    00118     this->unitnumber_digits = 2;
    00119   }
    00120
    00121   this->vehicles.RebuildDone();
    00122   this->vscroll.SetCount(this->vehicles.Length());
    00123 }
    00124
    00125 /* cached values for VehicleNameSorter to spare many GetString() calls */
    00126 static const Vehicle *_last_vehicle[2] = { NULL, NULL };
    00127
    00128 void BaseVehicleListWindow::SortVehicleList()
    00129 {
    00130   if (this->vehicles.Sort()) return;
    00131
    00132   /* invalidate cached values for name sorter - vehicle names could change */
    00133   _last_vehicle[0] = _last_vehicle[1] = NULL;
    00134 }
    00135
    00136 void DepotSortList(VehicleList *list)
    00137 {
    00138   if (list->Length() < 2) return;
    00139   QSortT(list->Begin(), list->Length(), &VehicleNumberSorter);
    00140 }
    00141
    00143 static void DrawVehicleProfitButton(const Vehicle *v, int x, int y)
    00144 {
    00145   PaletteID pal;
    00146
    00147   /* draw profit-based coloured icons */
    00148   if (v->age <= DAYS_IN_YEAR * 2) {
    00149     pal = PALETTE_TO_GREY;
    00150   } else if (v->GetDisplayProfitLastYear() < 0) {
    00151     pal = PALETTE_TO_RED;
    00152   } else if (v->GetDisplayProfitLastYear() < 10000) {
    00153     pal = PALETTE_TO_YELLOW;
    00154   } else {
    00155     pal = PALETTE_TO_GREEN;
    00156   }
    00157   DrawSprite(SPR_BLOT, pal, x, y);
    00158 }
    00159
    00161 static const uint MAX_REFIT_CYCLE = 256;
    00162
    00170 byte GetBestFittingSubType(Vehicle *v_from, Vehicle *v_for)
    00171 {
    00172   const Engine *e_from = Engine::Get(v_from->engine_type);
    00173   const Engine *e_for  = Engine::Get(v_for->engine_type);
    00174
    00175   /* If one them doesn't carry cargo, there's no need to find a sub type */
    00176   if (!e_from->CanCarryCargo() || !e_for->CanCarryCargo()) return 0;
    00177
    00178   if (!HasBit(e_from->info.callback_mask, CBM_VEHICLE_CARGO_SUFFIX) ||
    00179       !HasBit(e_for->info.callback_mask,  CBM_VEHICLE_CARGO_SUFFIX)) {
    00180     /* One of the engines doesn't have cargo suffixes, i.e. sub types. */
    00181     return 0;
    00182   }
    00183
    00184   /* It has to be possible for v_for to carry the cargo of v_from. */
    00185   if (!HasBit(e_for->info.refit_mask, v_from->cargo_type)) return 0;
    00186
    00187   StringID expected_string = GetCargoSubtypeText(v_from);
    00188
    00189   CargoID old_cargo_type = v_for->cargo_type;
    00190   byte old_cargo_subtype = v_for->cargo_subtype;
    00191   byte ret_refit_cyc = 0;
    00192
    00193   /* Set the 'destination' cargo */
    00194   v_for->cargo_type = v_from->cargo_type;
    00195
    00196   /* Cycle through the refits */
    00197   for (uint refit_cyc = 0; refit_cyc < MAX_REFIT_CYCLE; refit_cyc++) {
    00198     v_for->cargo_subtype = refit_cyc;
    00199
    00200     /* Make sure we don't pick up anything cached. */
    00201     v_for->First()->InvalidateNewGRFCache();
    00202     v_for->InvalidateNewGRFCache();
    00203     uint16 callback = GetVehicleCallback(CBID_VEHICLE_CARGO_SUFFIX, 0, 0, v_for->engine_type, v_for);
    00204
    00205     if (callback == 0xFF) callback = CALLBACK_FAILED;
    00206     if (callback == CALLBACK_FAILED) break;
    00207
    00208     if (GetCargoSubtypeText(v_for) != expected_string) continue;
    00209
    00210     /* We found something matching. */
    00211     ret_refit_cyc = refit_cyc;
    00212     break;
    00213   }
    00214
    00215   /* Reset the vehicle's cargo type */
    00216   v_for->cargo_type    = old_cargo_type;
    00217   v_for->cargo_subtype = old_cargo_subtype;
    00218
    00219   /* Make sure we don't taint the vehicle. */
    00220   v_for->First()->InvalidateNewGRFCache();
    00221   v_for->InvalidateNewGRFCache();
    00222
    00223   return ret_refit_cyc;
    00224 }
    00225
    00227 struct RefitOption {
    00228   CargoID cargo;
    00229   byte subtype;
    00230   uint16 value;
    00231   EngineID engine;
    00232
    00233   FORCEINLINE bool operator != (const RefitOption &other) const
    00234   {
    00235     return other.cargo != this->cargo || other.value != this->value;
    00236   }
    00237 };
    00238
    00239 typedef SmallVector<RefitOption, 32> RefitList;
    00240
    00246 static void BuildRefitList(const Vehicle *v, RefitList *refit_list)
    00247 {
    00248   refit_list->Clear();
    00249   Vehicle *u = const_cast<Vehicle *>(v);
    00250
    00251   do {
    00252     const Engine *e = Engine::Get(u->engine_type);
    00253     uint32 cmask = e->info.refit_mask;
    00254     byte callback_mask = e->info.callback_mask;
    00255
    00256     /* Skip this engine if it does not carry anything */
    00257     if (!e->CanCarryCargo()) continue;
    00258
    00259     /* Loop through all cargos in the refit mask */
    00260     const CargoSpec *cs;
    00261     FOR_ALL_CARGOSPECS(cs) {
    00262       CargoID cid = cs->Index();
    00263       /* Skip cargo type if it's not listed */
    00264       if (!HasBit(cmask, cid)) continue;
    00265
    00266       /* Check the vehicle's callback mask for cargo suffixes */
    00267       if (HasBit(callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) {
    00268         /* Make a note of the original cargo type. It has to be
    00269          * changed to test the cargo & subtype... */
    00270         CargoID temp_cargo = u->cargo_type;
    00271         byte temp_subtype  = u->cargo_subtype;
    00272
    00273         u->cargo_type = cid;
    00274
    00275         for (uint refit_cyc = 0; refit_cyc < MAX_REFIT_CYCLE; refit_cyc++) {
    00276           u->cargo_subtype = refit_cyc;
    00277
    00278           /* Make sure we don't pick up anything cached. */
    00279           u->First()->InvalidateNewGRFCache();
    00280           u->InvalidateNewGRFCache();
    00281           uint16 callback = GetVehicleCallback(CBID_VEHICLE_CARGO_SUFFIX, 0, 0, u->engine_type, u);
    00282
    00283           if (callback == 0xFF) callback = CALLBACK_FAILED;
    00284           if (refit_cyc != 0 && callback == CALLBACK_FAILED) break;
    00285
    00286           RefitOption option;
    00287           option.cargo   = cid;
    00288           option.subtype = refit_cyc;
    00289           option.value   = callback;
    00290           option.engine  = u->engine_type;
    00291           refit_list->Include(option);
    00292         }
    00293
    00294         /* Reset the vehicle's cargo type */
    00295         u->cargo_type    = temp_cargo;
    00296         u->cargo_subtype = temp_subtype;
    00297
    00298         /* And make sure we haven't tainted the cache */
    00299         u->First()->InvalidateNewGRFCache();
    00300         u->InvalidateNewGRFCache();
    00301       } else {
    00302         /* No cargo suffix callback -- use no subtype */
    00303         RefitOption option;
    00304         option.cargo   = cid;
    00305         option.subtype = 0;
    00306         option.value   = CALLBACK_FAILED;
    00307         option.engine  = INVALID_ENGINE;
    00308         refit_list->Include(option);
    00309       }
    00310     }
    00311   } while ((v->type == VEH_TRAIN || v->type == VEH_ROAD) && (u = u->Next()) != NULL);
    00312 }
    00313
    00322 static void DrawVehicleRefitWindow(const RefitList &list, int sel, uint pos, uint rows, uint delta, const Rect &r)
    00323 {
    00324   uint y = r.top + WD_MATRIX_TOP;
    00325   /* Draw the list, and find the selected cargo (by its position in list) */
    00326   for (uint i = pos; i < pos + rows && i < list.Length(); i++) {
    00327     TextColour colour = (sel == (int)i) ? TC_WHITE : TC_BLACK;
    00328     const RefitOption *refit = &list[i];
    00329
    00330     /* Get the cargo name */
    00331     SetDParam(0, CargoSpec::Get(refit->cargo)->name);
    00332
    00333     /* If the callback succeeded, draw the cargo suffix */
    00334     if (refit->value != CALLBACK_FAILED) {
    00335       SetDParam(1, GetGRFStringID(GetEngineGRFID(refit->engine), 0xD000 + refit->value));
    00336       DrawString(r.left + WD_MATRIX_LEFT, r.right - WD_MATRIX_RIGHT, y, STR_JUST_STRING_SPACE_STRING, colour);
    00337     } else {
    00338       DrawString(r.left + WD_MATRIX_LEFT, r.right - WD_MATRIX_RIGHT, y, STR_JUST_STRING, colour);
    00339     }
    00340
    00341     y += delta;
    00342   }
    00343 }
    00344
    00346 enum VehicleRefitWidgets {
    00347   VRW_CAPTION,
    00348   VRW_SELECTHEADER,
    00349   VRW_MATRIX,
    00350   VRW_SCROLLBAR,
    00351   VRW_INFOPANEL,
    00352   VRW_REFITBUTTON,
    00353 };
    00354
    00356 struct RefitWindow : public Window {
    00357   int sel;
    00358   RefitOption *cargo;
    00359   RefitList list;
    00360   uint length;
    00361   VehicleOrderID order;
    00362
    00363   RefitWindow(const WindowDesc *desc, const Vehicle *v, VehicleOrderID order) : Window()
    00364   {
    00365     this->CreateNestedTree(desc);
    00366
    00367     this->GetWidget<NWidgetCore>(VRW_SELECTHEADER)->tool_tip = STR_REFIT_TRAIN_LIST_TOOLTIP + v->type;
    00368     this->GetWidget<NWidgetCore>(VRW_MATRIX)->tool_tip       = STR_REFIT_TRAIN_LIST_TOOLTIP + v->type;
    00369     NWidgetCore *nwi = this->GetWidget<NWidgetCore>(VRW_REFITBUTTON);
    00370     nwi->widget_data = STR_REFIT_TRAIN_REFIT_BUTTON + v->type;
    00371     nwi->tool_tip    = STR_REFIT_TRAIN_REFIT_TOOLTIP + v->type;
    00372
    00373     this->FinishInitNested(desc, v->index);
    00374     this->owner = v->owner;
    00375
    00376     this->order = order;
    00377     this->sel  = -1;
    00378     BuildRefitList(v, &this->list);
    00379     if (v->type == VEH_TRAIN) this->length = CountVehiclesInChain(v);
    00380     this->vscroll.SetCount(this->list.Length());
    00381   }
    00382
    00383   virtual void OnPaint()
    00384   {
    00385     Vehicle *v = Vehicle::Get(this->window_number);
    00386
    00387     if (v->type == VEH_TRAIN) {
    00388       uint length = CountVehiclesInChain(v);
    00389
    00390       if (length != this->length) {
    00391         /* Consist length has changed, so rebuild the refit list */
    00392         BuildRefitList(v, &this->list);
    00393         this->length = length;
    00394       }
    00395     }
    00396
    00397     this->vscroll.SetCount(this->list.Length());
    00398
    00399     this->cargo = (this->sel >= 0 && this->sel < (int)this->list.Length()) ? &this->list[this->sel] : NULL;
    00400     this->DrawWidgets();
    00401   }
    00402
    00403   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    00404   {
    00405     switch (widget) {
    00406       case VRW_MATRIX:
    00407         resize->height = WD_MATRIX_TOP + FONT_HEIGHT_NORMAL + WD_MATRIX_BOTTOM;
    00408         size->height = resize->height * 8;
    00409         break;
    00410     }
    00411   }
    00412
    00413   virtual void SetStringParameters(int widget) const
    00414   {
    00415     if (widget == VRW_CAPTION) SetDParam(0, Vehicle::Get(this->window_number)->index);
    00416   }
    00417
    00418   virtual void DrawWidget(const Rect &r, int widget) const
    00419   {
    00420     switch (widget) {
    00421       case VRW_MATRIX:
    00422         DrawVehicleRefitWindow(this->list, this->sel, this->vscroll.GetPosition(), this->vscroll.GetCapacity(), this->resize.step_height, r);
    00423         break;
    00424
    00425       case VRW_INFOPANEL:
    00426         if (this->cargo != NULL) {
    00427           Vehicle *v = Vehicle::Get(this->window_number);
    00428           CommandCost cost = DoCommand(v->tile, v->index, this->cargo->cargo | this->cargo->subtype << 8, DC_QUERY_COST, GetCmdRefitVeh(v->type));
    00429           if (cost.Succeeded()) {
    00430             SetDParam(0, this->cargo->cargo);
    00431             SetDParam(1, _returned_refit_capacity);
    00432             SetDParam(2, cost.GetCost());
    00433             DrawStringMultiLine(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT,
    00434                 r.top + WD_FRAMERECT_TOP, r.bottom - WD_FRAMERECT_BOTTOM, STR_REFIT_NEW_CAPACITY_COST_OF_REFIT);
    00435           }
    00436         }
    00437         break;
    00438     }
    00439   }
    00440
    00441   virtual void OnClick(Point pt, int widget, int click_count)
    00442   {
    00443     switch (widget) {
    00444       case VRW_MATRIX: { // listbox
    00445         int y = pt.y - this->GetWidget<NWidgetBase>(VRW_MATRIX)->pos_y;
    00446         if (y >= 0) {
    00447           this->sel = (y / (int)this->resize.step_height) + this->vscroll.GetPosition();
    00448           this->SetDirty();
    00449         }
    00450         /* FIXME We need to call some InvalidateData to make this->cargo valid */
    00451         if (click_count == 1) break;
    00452       }
    00453       /* FALL THROUGH */
    00454       case VRW_REFITBUTTON: // refit button
    00455         if (this->cargo != NULL) {
    00456           const Vehicle *v = Vehicle::Get(this->window_number);
    00457
    00458           if (this->order == INVALID_VEH_ORDER_ID) {
    00459             if (DoCommandP(v->tile, v->index, this->cargo->cargo | this->cargo->subtype << 8, GetCmdRefitVeh(v))) delete this;
    00460           } else {
    00461             if (DoCommandP(v->tile, v->index, this->cargo->cargo | this->cargo->subtype << 8 | this->order << 16, CMD_ORDER_REFIT)) delete this;
    00462           }
    00463         }
    00464         break;
    00465     }
    00466   }
    00467
    00468   virtual void OnResize()
    00469   {
    00470     this->vscroll.SetCapacityFromWidget(this, VRW_MATRIX);
    00471     this->GetWidget<NWidgetCore>(VRW_MATRIX)->widget_data = (this->vscroll.GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
    00472   }
    00473 };
    00474
    00475 static const NWidgetPart _nested_vehicle_refit_widgets[] = {
    00476   NWidget(NWID_HORIZONTAL),
    00477     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
    00478     NWidget(WWT_CAPTION, COLOUR_GREY, VRW_CAPTION), SetDataTip(STR_REFIT_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
    00479   EndContainer(),
    00480   NWidget(WWT_TEXTBTN, COLOUR_GREY, VRW_SELECTHEADER), SetDataTip(STR_REFIT_TITLE, STR_NULL), SetResize(1, 0),
    00481   /* Matrix + scrollbar. */
    00482   NWidget(NWID_HORIZONTAL),
    00483     NWidget(WWT_MATRIX, COLOUR_GREY, VRW_MATRIX), SetMinimalSize(228, 112), SetResize(1, 14), SetFill(1, 1), SetDataTip(0x801, STR_NULL),
    00484     NWidget(WWT_SCROLLBAR, COLOUR_GREY, VRW_SCROLLBAR),
    00485   EndContainer(),
    00486   NWidget(WWT_PANEL, COLOUR_GREY, VRW_INFOPANEL), SetMinimalTextLines(2, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM), SetResize(1, 0), EndContainer(),
    00487   NWidget(NWID_HORIZONTAL),
    00488     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, VRW_REFITBUTTON), SetFill(1, 0), SetResize(1, 0),
    00489     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
    00490   EndContainer(),
    00491 };
    00492
    00493 static const WindowDesc _vehicle_refit_desc(
    00494   WDP_AUTO, 240, 174,
    00495   WC_VEHICLE_REFIT, WC_VEHICLE_VIEW,
    00496   WDF_UNCLICK_BUTTONS | WDF_CONSTRUCTION,
    00497   _nested_vehicle_refit_widgets, lengthof(_nested_vehicle_refit_widgets)
    00498 );
    00499
    00505 void ShowVehicleRefitWindow(const Vehicle *v, VehicleOrderID order, Window *parent)
    00506 {
    00507   DeleteWindowById(WC_VEHICLE_REFIT, v->index);
    00508   RefitWindow *w = new RefitWindow(&_vehicle_refit_desc, v, order);
    00509   w->parent = parent;
    00510 }
    00511
    00513 uint ShowRefitOptionsList(int left, int right, int y, EngineID engine)
    00514 {
    00515   /* List of cargo types of this engine */
    00516   uint32 cmask = GetUnionOfArticulatedRefitMasks(engine, false);
    00517   /* List of cargo types available in this climate */
    00518   uint32 lmask = _cargo_mask;
    00519   char string[512];
    00520   char *b = string;
    00521
    00522   /* Draw nothing if the engine is not refittable */
    00523   if (HasAtMostOneBit(cmask)) return y;
    00524
    00525   b = InlineString(b, STR_PURCHASE_INFO_REFITTABLE_TO);
    00526
    00527   if (cmask == lmask) {
    00528     /* Engine can be refitted to all types in this climate */
    00529     b = InlineString(b, STR_PURCHASE_INFO_ALL_TYPES);
    00530   } else {
    00531     /* Check if we are able to refit to more cargo types and unable to. If
    00532      * so, invert the cargo types to list those that we can't refit to. */
    00533     if (CountBits(cmask ^ lmask) < CountBits(cmask)) {
    00534       cmask ^= lmask;
    00535       b = InlineString(b, STR_PURCHASE_INFO_ALL_BUT);
    00536     }
    00537
    00538     bool first = true;
    00539
    00540     /* Add each cargo type to the list */
    00541     for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
    00542       if (!HasBit(cmask, cid)) continue;
    00543
    00544       if (b >= lastof(string) - (2 + 2 * 4)) break; // ", " and two calls to Utf8Encode()
    00545
    00546       if (!first) b = strecpy(b, ", ", lastof(string));
    00547       first = false;
    00548
    00549       b = InlineString(b, CargoSpec::Get(cid)->name);
    00550     }
    00551   }
    00552
    00553   /* Terminate and display the completed string */
    00554   *b = '\0';
    00555
    00556   /* Make sure we detect any buffer overflow */
    00557   assert(b < endof(string));
    00558
    00559   SetDParamStr(0, string);
    00560   return DrawStringMultiLine(left, right, y, INT32_MAX, STR_JUST_RAW_STRING);
    00561 }
    00562
    00564 StringID GetCargoSubtypeText(const Vehicle *v)
    00565 {
    00566   if (HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) {
    00567     uint16 cb = GetVehicleCallback(CBID_VEHICLE_CARGO_SUFFIX, 0, 0, v->engine_type, v);
    00568     if (cb != CALLBACK_FAILED) {
    00569       return GetGRFStringID(GetEngineGRFID(v->engine_type), 0xD000 + cb);
    00570     }
    00571   }
    00572   return STR_EMPTY;
    00573 }
    00574
    00576 static int CDECL VehicleNumberSorter(const Vehicle * const *a, const Vehicle * const *b)
    00577 {
    00578   return (*a)->unitnumber - (*b)->unitnumber;
    00579 }
    00580
    00582 static int CDECL VehicleNameSorter(const Vehicle * const *a, const Vehicle * const *b)
    00583 {
    00584   static char last_name[2][64];
    00585
    00586   if (*a != _last_vehicle[0]) {
    00587     _last_vehicle[0] = *a;
    00588     SetDParam(0, (*a)->index);
    00589     GetString(last_name[0], STR_VEHICLE_NAME, lastof(last_name[0]));
    00590   }
    00591
    00592   if (*b != _last_vehicle[1]) {
    00593     _last_vehicle[1] = *b;
    00594     SetDParam(0, (*b)->index);
    00595     GetString(last_name[1], STR_VEHICLE_NAME, lastof(last_name[1]));
    00596   }
    00597
    00598   int r = strcmp(last_name[0], last_name[1]);
    00599   return (r != 0) ? r : VehicleNumberSorter(a, b);
    00600 }
    00601
    00603 static int CDECL VehicleAgeSorter(const Vehicle * const *a, const Vehicle * const *b)
    00604 {
    00605   int r = (*a)->age - (*b)->age;
    00606   return (r != 0) ? r : VehicleNumberSorter(a, b);
    00607 }
    00608
    00610 static int CDECL VehicleProfitThisYearSorter(const Vehicle * const *a, const Vehicle * const *b)
    00611 {
    00612   int r = ClampToI32((*a)->GetDisplayProfitThisYear() - (*b)->GetDisplayProfitThisYear());
    00613   return (r != 0) ? r : VehicleNumberSorter(a, b);
    00614 }
    00615
    00617 static int CDECL VehicleProfitLastYearSorter(const Vehicle * const *a, const Vehicle * const *b)
    00618 {
    00619   int r = ClampToI32((*a)->GetDisplayProfitLastYear() - (*b)->GetDisplayProfitLastYear());
    00620   return (r != 0) ? r : VehicleNumberSorter(a, b);
    00621 }
    00622
    00624 static int CDECL VehicleCargoSorter(const Vehicle * const *a, const Vehicle * const *b)
    00625 {
    00626   const Vehicle *v;
    00627   CargoArray diff;
    00628
    00629   /* Append the cargo of the connected weagons */
    00630   for (v = *a; v != NULL; v = v->Next()) diff[v->cargo_type] += v->cargo_cap;
    00631   for (v = *b; v != NULL; v = v->Next()) diff[v->cargo_type] -= v->cargo_cap;
    00632
    00633   int r = 0;
    00634   for (CargoID i = 0; i < NUM_CARGO; i++) {
    00635     r = diff[i];
    00636     if (r != 0) break;
    00637   }
    00638
    00639   return (r != 0) ? r : VehicleNumberSorter(a, b);
    00640 }
    00641
    00643 static int CDECL VehicleReliabilitySorter(const Vehicle * const *a, const Vehicle * const *b)
    00644 {
    00645   int r = (*a)->reliability - (*b)->reliability;
    00646   return (r != 0) ? r : VehicleNumberSorter(a, b);
    00647 }
    00648
    00650 static int CDECL VehicleMaxSpeedSorter(const Vehicle * const *a, const Vehicle * const *b)
    00651 {
    00652   int r = 0;
    00653   if ((*a)->type == VEH_TRAIN && (*b)->type == VEH_TRAIN) {
    00654     r = Train::From(*a)->tcache.cached_max_speed - Train::From(*b)->tcache.cached_max_speed;
    00655   } else {
    00656     r = (*a)->max_speed - (*b)->max_speed;
    00657   }
    00658   return (r != 0) ? r : VehicleNumberSorter(a, b);
    00659 }
    00660
    00662 static int CDECL VehicleModelSorter(const Vehicle * const *a, const Vehicle * const *b)
    00663 {
    00664   int r = (*a)->engine_type - (*b)->engine_type;
    00665   return (r != 0) ? r : VehicleNumberSorter(a, b);
    00666 }
    00667
    00669 static int CDECL VehicleValueSorter(const Vehicle * const *a, const Vehicle * const *b)
    00670 {
    00671   const Vehicle *u;
    00672   Money diff = 0;
    00673
    00674   for (u = *a; u != NULL; u = u->Next()) diff += u->value;
    00675   for (u = *b; u != NULL; u = u->Next()) diff -= u->value;
    00676
    00677   int r = ClampToI32(diff);
    00678   return (r != 0) ? r : VehicleNumberSorter(a, b);
    00679 }
    00680
    00682 static int CDECL VehicleLengthSorter(const Vehicle * const *a, const Vehicle * const *b)
    00683 {
    00684   int r = 0;
    00685   switch ((*a)->type) {
    00686     case VEH_TRAIN:
    00687       r = Train::From(*a)->tcache.cached_total_length - Train::From(*b)->tcache.cached_total_length;
    00688       break;
    00689
    00690     case VEH_ROAD: {
    00691       const RoadVehicle *u;
    00692       for (u = RoadVehicle::From(*a); u != NULL; u = u->Next()) r += u->rcache.cached_veh_length;
    00693       for (u = RoadVehicle::From(*b); u != NULL; u = u->Next()) r -= u->rcache.cached_veh_length;
    00694     } break;
    00695
    00696     default: NOT_REACHED();
    00697   }
    00698   return (r != 0) ? r : VehicleNumberSorter(a, b);
    00699 }
    00700
    00702 static int CDECL VehicleTimeToLiveSorter(const Vehicle * const *a, const Vehicle * const *b)
    00703 {
    00704   int r = ClampToI32(((*a)->max_age - (*a)->age) - ((*b)->max_age - (*b)->age));
    00705   return (r != 0) ? r : VehicleNumberSorter(a, b);
    00706 }
    00707
    00709 static int CDECL VehicleTimetableDelaySorter(const Vehicle * const *a, const Vehicle * const *b)
    00710 {
    00711   int r = (*a)->lateness_counter - (*b)->lateness_counter;
    00712   return (r != 0) ? r : VehicleNumberSorter(a, b);
    00713 }
    00714
    00715 void InitializeGUI()
    00716 {
    00717   MemSetT(&_sorting, 0);
    00718 }
    00719
    00726 static inline void ChangeVehicleWindow(WindowClass window_class, VehicleID from_index, VehicleID to_index)
    00727 {
    00728   Window *w = FindWindowById(window_class, from_index);
    00729   if (w != NULL) {
    00730     w->window_number = to_index;
    00731     if (w->viewport != NULL) w->viewport->follow_vehicle = to_index;
    00732     if (to_index != INVALID_VEHICLE) w->InvalidateData();
    00733   }
    00734 }
    00735
    00741 void ChangeVehicleViewWindow(VehicleID from_index, VehicleID to_index)
    00742 {
    00743   ChangeVehicleWindow(WC_VEHICLE_VIEW,      from_index, to_index);
    00744   ChangeVehicleWindow(WC_VEHICLE_ORDERS,    from_index, to_index);
    00745   ChangeVehicleWindow(WC_VEHICLE_REFIT,     from_index, to_index);
    00746   ChangeVehicleWindow(WC_VEHICLE_DETAILS,   from_index, to_index);
    00747   ChangeVehicleWindow(WC_VEHICLE_TIMETABLE, from_index, to_index);
    00748 }
    00749
    00750 enum VehicleListWindowWidgets {
    00751   VLW_WIDGET_CAPTION,
    00752   VLW_WIDGET_SORT_ORDER,
    00753   VLW_WIDGET_SORT_BY_PULLDOWN,
    00754   VLW_WIDGET_LIST,
    00755   VLW_WIDGET_SCROLLBAR,
    00756   VLW_WIDGET_HIDE_BUTTONS,
    00757   VLW_WIDGET_AVAILABLE_VEHICLES,
    00758   VLW_WIDGET_MANAGE_VEHICLES_DROPDOWN,
    00759   VLW_WIDGET_STOP_ALL,
    00760   VLW_WIDGET_START_ALL,
    00761 };
    00762
    00763 static const NWidgetPart _nested_vehicle_list[] = {
    00764   NWidget(NWID_HORIZONTAL),
    00765     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
    00766     NWidget(WWT_CAPTION, COLOUR_GREY, VLW_WIDGET_CAPTION),
    00767     NWidget(WWT_SHADEBOX, COLOUR_GREY),
    00768     NWidget(WWT_STICKYBOX, COLOUR_GREY),
    00769   EndContainer(),
    00770
    00771   NWidget(NWID_HORIZONTAL),
    00772     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, VLW_WIDGET_SORT_ORDER), SetMinimalSize(81, 12), SetFill(0, 1), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
    00773     NWidget(WWT_DROPDOWN, COLOUR_GREY, VLW_WIDGET_SORT_BY_PULLDOWN), SetMinimalSize(167, 12), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
    00774     NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(12, 12), SetFill(1, 1), SetResize(1, 0),
    00775     EndContainer(),
    00776   EndContainer(),
    00777
    00778   NWidget(NWID_HORIZONTAL),
    00779     NWidget(WWT_MATRIX, COLOUR_GREY, VLW_WIDGET_LIST), SetMinimalSize(248, 0), SetFill(1, 0), SetResize(1, 1),
    00780     NWidget(WWT_SCROLLBAR, COLOUR_GREY, VLW_WIDGET_SCROLLBAR),
    00781   EndContainer(),
    00782
    00783   NWidget(NWID_HORIZONTAL),
    00784     NWidget(NWID_SELECTION, INVALID_COLOUR, VLW_WIDGET_HIDE_BUTTONS),
    00785       NWidget(NWID_HORIZONTAL),
    00786         NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, VLW_WIDGET_AVAILABLE_VEHICLES), SetMinimalSize(106, 12), SetFill(0, 1),
    00787                 SetDataTip(STR_BLACK_STRING, STR_VEHICLE_LIST_AVAILABLE_ENGINES_TOOLTIP),
    00788         NWidget(WWT_DROPDOWN, COLOUR_GREY, VLW_WIDGET_MANAGE_VEHICLES_DROPDOWN), SetMinimalSize(118, 12), SetFill(0, 1),
    00789                 SetDataTip(STR_VEHICLE_LIST_MANAGE_LIST, STR_VEHICLE_LIST_MANAGE_LIST_TOOLTIP),
    00790         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VLW_WIDGET_STOP_ALL), SetMinimalSize(12, 12), SetFill(0, 1),
    00791                 SetDataTip(SPR_FLAG_VEH_STOPPED, STR_VEHICLE_LIST_MASS_STOP_LIST_TOOLTIP),
    00792         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VLW_WIDGET_START_ALL), SetMinimalSize(12, 12), SetFill(0, 1),
    00793                 SetDataTip(SPR_FLAG_VEH_RUNNING, STR_VEHICLE_LIST_MASS_START_LIST_TOOLTIP),
    00794         NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(0, 12), SetResize(1, 0), SetFill(1, 1), EndContainer(),
    00795       EndContainer(),
    00796       /* Widget to be shown for other companies hiding the previous 5 widgets. */
    00797       NWidget(WWT_PANEL, COLOUR_GREY), SetFill(1, 1), SetResize(1, 0), EndContainer(),
    00798     EndContainer(),
    00799     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
    00800   EndContainer(),
    00801 };
    00802
    00803 static void DrawSmallOrderList(const Vehicle *v, int left, int right, int y, VehicleOrderID start = 0)
    00804 {
    00805   const Order *order = v->GetOrder(start);
    00806   if (order == NULL) return;
    00807
    00808   int i = 0;
    00809   VehicleOrderID oid = start;
    00810
    00811   do {
    00812     if (oid == v->cur_order_index) DrawString(left, right, y, STR_TINY_RIGHT_ARROW, TC_BLACK);
    00813
    00814     if (order->IsType(OT_GOTO_STATION)) {
    00815       SetDParam(0, order->GetDestination());
    00816       DrawString(left + 6, right - 6, y, STR_TINY_BLACK_STATION);
    00817
    00818       y += FONT_HEIGHT_SMALL;
    00819       if (++i == 4) break;
    00820     }
    00821
    00822     oid++;
    00823     order = order->next;
    00824     if (order == NULL) {
    00825       order = v->orders.list->GetFirstOrder();
    00826       oid = 0;
    00827     }
    00828   } while (oid != start);
    00829 }
    00830
    00840 static void DrawVehicleImage(const Vehicle *v, int left, int right, int y, VehicleID selection, int skip)
    00841 {
    00842   switch (v->type) {
    00843     case VEH_TRAIN:    DrawTrainImage(Train::From(v), left, right, y, selection, skip); break;
    00844     case VEH_ROAD:     DrawRoadVehImage(v, left, right, y, selection);  break;
    00845     case VEH_SHIP:     DrawShipImage(v, left, right, y, selection);     break;
    00846     case VEH_AIRCRAFT: DrawAircraftImage(v, left, right, y, selection); break;
    00847     default: NOT_REACHED();
    00848   }
    00849 }
    00850
    00857 uint GetVehicleListHeight(VehicleType type, uint divisor)
    00858 {
    00859   /* Name + vehicle + profit */
    00860   uint base = GetVehicleHeight(type) + 2 * FONT_HEIGHT_SMALL;
    00861   /* Drawing of the 4 small orders + profit*/
    00862   if (type >= VEH_SHIP) base = max(base, 5U * FONT_HEIGHT_SMALL);
    00863
    00864   if (divisor == 1) return base;
    00865
    00866   /* Make sure the height is dividable by divisor */
    00867   uint rem = base % divisor;
    00868   return base + (rem == 0 ? 0 : divisor - rem);
    00869 }
    00870
    00877 void BaseVehicleListWindow::DrawVehicleListItems(VehicleID selected_vehicle, int line_height, const Rect &r) const
    00878 {
    00879   int left = r.left + WD_MATRIX_LEFT;
    00880   int right = r.right - WD_MATRIX_RIGHT;
    00881   int width = right - left;
    00882   bool rtl = _dynlang.text_dir == TD_RTL;
    00883
    00884   int text_offset = GetDigitWidth() * this->unitnumber_digits + WD_FRAMERECT_RIGHT;
    00885   int text_left  = left  + (rtl ?           0 : text_offset);
    00886   int text_right = right - (rtl ? text_offset :           0);
    00887
    00888   bool show_orderlist = vehicle_type >= VEH_SHIP;
    00889   int orderlist_left  = left  + (rtl ? 0 : max(100 + text_offset, width / 2));
    00890   int orderlist_right = right - (rtl ? max(100 + text_offset, width / 2) : 0);
    00891
    00892   int image_left  = (rtl && show_orderlist) ? orderlist_right : text_left;
    00893   int image_right = (!rtl && show_orderlist) ? orderlist_left : text_right;
    00894
    00895   int vehicle_button_x = rtl ? right - 8 : left;
    00896
    00897   int y = r.top;
    00898   uint max = min(this->vscroll.GetPosition() + this->vscroll.GetCapacity(), this->vehicles.Length());
    00899   for (uint i = this->vscroll.GetPosition(); i < max; ++i) {
    00900     const Vehicle *v = this->vehicles[i];
    00901     StringID str;
    00902
    00903     SetDParam(0, v->GetDisplayProfitThisYear());
    00904     SetDParam(1, v->GetDisplayProfitLastYear());
    00905
    00906     DrawVehicleImage(v, image_left, image_right, y + FONT_HEIGHT_SMALL - 1, selected_vehicle, 0);
    00907     DrawString(text_left, text_right, y + line_height - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1, STR_VEHICLE_LIST_PROFIT_THIS_YEAR_LAST_YEAR);
    00908
    00909     if (v->name != NULL) {
    00910       /* The vehicle got a name so we will print it */
    00911       SetDParam(0, v->index);
    00912       DrawString(text_left, text_right, y, STR_TINY_BLACK_VEHICLE);
    00913     } else if (v->group_id != DEFAULT_GROUP) {
    00914       /* The vehicle has no name, but is member of a group, so print group name */
    00915       SetDParam(0, v->group_id);
    00916       DrawString(text_left, text_right, y, STR_TINY_GROUP, TC_BLACK);
    00917     }
    00918
    00919     if (show_orderlist) DrawSmallOrderList(v, orderlist_left, orderlist_right, y, v->cur_order_index);
    00920
    00921     if (v->IsInDepot()) {
    00922       str = STR_BLUE_COMMA;
    00923     } else {
    00924       str = (v->age > v->max_age - DAYS_IN_LEAP_YEAR) ? STR_RED_COMMA : STR_BLACK_COMMA;
    00925     }
    00926
    00927     SetDParam(0, v->unitnumber);
    00928     DrawString(left, right, y + 2, str);
    00929
    00930     DrawVehicleProfitButton(v, vehicle_button_x, y + FONT_HEIGHT_NORMAL + 3);
    00931
    00932     y += line_height;
    00933   }
    00934 }
    00935
    00945 struct VehicleListWindow : public BaseVehicleListWindow {
    00946 private:
    00948   enum ButtonPlanes {
    00949     BP_SHOW_BUTTONS,
    00950     BP_HIDE_BUTTONS,
    00951   };
    00952
    00953 public:
    00954   VehicleListWindow(const WindowDesc *desc, WindowNumber window_number) : BaseVehicleListWindow()
    00955   {
    00956     uint16 window_type = window_number & VLW_MASK;
    00957     CompanyID company = (CompanyID)GB(window_number, 0, 8);
    00958
    00959     this->vehicle_type = (VehicleType)GB(window_number, 11, 5);
    00960
    00961     /* Set up sorting. Make the window-specific _sorting variable
    00962      * point to the correct global _sorting struct so we are freed
    00963      * from having conditionals during window operation */
    00964     switch (this->vehicle_type) {
    00965       case VEH_TRAIN:    this->sorting = &_sorting.train; break;
    00966       case VEH_ROAD:     this->sorting = &_sorting.roadveh; break;
    00967       case VEH_SHIP:     this->sorting = &_sorting.ship; break;
    00968       case VEH_AIRCRAFT: this->sorting = &_sorting.aircraft; break;
    00969       default: NOT_REACHED();
    00970     }
    00971
    00972     this->vehicles.SetListing(*this->sorting);
    00973     this->vehicles.ForceRebuild();
    00974     this->vehicles.NeedResort();
    00975     this->BuildVehicleList(company, GB(window_number, 16, 16), window_type);
    00976     this->SortVehicleList();
    00977
    00978     this->CreateNestedTree(desc);
    00979
    00980     /* Set up the window widgets */
    00981     this->GetWidget<NWidgetCore>(VLW_WIDGET_LIST)->tool_tip = STR_VEHICLE_LIST_TRAIN_LIST_TOOLTIP + this->vehicle_type;
    00982
    00983     if (window_type == VLW_SHARED_ORDERS) {
    00984       this->GetWidget<NWidgetCore>(VLW_WIDGET_CAPTION)->widget_data = STR_VEHICLE_LIST_SHARED_ORDERS_LIST_CAPTION;
    00985     } else {
    00986       this->GetWidget<NWidgetCore>(VLW_WIDGET_CAPTION)->widget_data = STR_VEHICLE_LIST_TRAIN_CAPTION + this->vehicle_type;
    00987     }
    00988
    00989     this->FinishInitNested(desc, window_number);
    00990     this->owner = company;
    00991
    00992     if (this->vehicle_type == VEH_TRAIN) ResizeWindow(this, 65, 0);
    00993   }
    00994
    00995   ~VehicleListWindow()
    00996   {
    00997     *this->sorting = this->vehicles.GetListing();
    00998   }
    00999
    01000   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    01001   {
    01002     switch (widget) {
    01003       case VLW_WIDGET_LIST:
    01004         resize->height = GetVehicleListHeight(this->vehicle_type, 1);
    01005         switch (this->vehicle_type) {
    01006           case VEH_TRAIN:
    01007           case VEH_ROAD:
    01008             size->height = 6 * resize->height;
    01009
    01010             break;
    01011           case VEH_SHIP:
    01012           case VEH_AIRCRAFT:
    01013             size->height = 4 * resize->height;
    01014             break;
    01015           default: NOT_REACHED();
    01016         }
    01017         break;
    01018
    01019       case VLW_WIDGET_SORT_ORDER: {
    01020         Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
    01021         d.width += padding.width + WD_SORTBUTTON_ARROW_WIDTH * 2; // Doubled since the string is centred and it also looks better.
    01022         d.height += padding.height;
    01023         *size = maxdim(*size, d);
    01024         break;
    01025       }
    01026     }
    01027   }
    01028
    01029   virtual void SetStringParameters(int widget) const
    01030   {
    01031     switch (widget) {
    01032       case VLW_WIDGET_AVAILABLE_VEHICLES:
    01033         SetDParam(0, STR_VEHICLE_LIST_AVAILABLE_TRAINS + this->vehicle_type);
    01034         break;
    01035
    01036       case VLW_WIDGET_CAPTION: {
    01037         const uint16 index = GB(this->window_number, 16, 16);
    01038         switch (this->window_number & VLW_MASK) {
    01039           case VLW_SHARED_ORDERS: // Shared Orders
    01040             if (this->vehicles.Length() == 0) {
    01041               /* We can't open this window without vehicles using this order
    01042               * and we should close the window when deleting the order      */
    01043               NOT_REACHED();
    01044             }
    01045             SetDParam(0, this->vscroll.GetCount());
    01046             break;
    01047
    01048           case VLW_STANDARD: // Company Name
    01049             SetDParam(0, STR_COMPANY_NAME);
    01050             SetDParam(1, index);
    01051             SetDParam(2, this->vscroll.GetCount());
    01052             break;
    01053
    01054           case VLW_WAYPOINT_LIST:
    01055             SetDParam(0, STR_WAYPOINT_NAME);
    01056             SetDParam(1, index);
    01057             SetDParam(2, this->vscroll.GetCount());
    01058             break;
    01059
    01060           case VLW_STATION_LIST: // Station Name
    01061             SetDParam(0, STR_STATION_NAME);
    01062             SetDParam(1, index);
    01063             SetDParam(2, this->vscroll.GetCount());
    01064             break;
    01065
    01066           case VLW_DEPOT_LIST:
    01067             SetDParam(0, STR_DEPOT_TRAIN_CAPTION + this->vehicle_type);
    01068             if (this->vehicle_type == VEH_AIRCRAFT) {
    01069               SetDParam(1, index); // Airport name
    01070             } else {
    01071               SetDParam(1, Depot::Get(index)->town_index);
    01072             }
    01073             SetDParam(2, this->vscroll.GetCount());
    01074             break;
    01075           default: NOT_REACHED();
    01076         }
    01077       } break;
    01078     }
    01079   }
    01080
    01081   virtual void DrawWidget(const Rect &r, int widget) const
    01082   {
    01083     switch (widget) {
    01084       case VLW_WIDGET_SORT_ORDER:
    01085         /* draw arrow pointing up/down for ascending/descending sorting */
    01086         this->DrawSortButtonState(widget, this->vehicles.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
    01087         break;
    01088
    01089       case VLW_WIDGET_LIST:
    01090         this->DrawVehicleListItems(INVALID_VEHICLE, this->resize.step_height, r);
    01091         break;
    01092     }
    01093   }
    01094
    01095   virtual void OnPaint()
    01096   {
    01097     const uint16 window_type = this->window_number & VLW_MASK;
    01098
    01099     this->BuildVehicleList(this->owner, GB(this->window_number, 16, 16), window_type);
    01100     this->SortVehicleList();
    01101
    01102     if (this->vehicles.Length() == 0 && this->IsWidgetLowered(VLW_WIDGET_MANAGE_VEHICLES_DROPDOWN)) {
    01103       HideDropDownMenu(this);
    01104     }
    01105
    01106     /* Hide the widgets that we will not use in this window
    01107      * Some windows contains actions only fit for the owner */
    01108     int plane_to_show = (this->owner == _local_company) ? BP_SHOW_BUTTONS : BP_HIDE_BUTTONS;
    01109     NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(VLW_WIDGET_HIDE_BUTTONS);
    01110     if (plane_to_show != nwi->shown_plane) {
    01111       nwi->SetDisplayedPlane(plane_to_show);
    01112       nwi->SetDirty(this);
    01113     }
    01114     if (this->owner == _local_company) {
    01115       this->SetWidgetDisabledState(VLW_WIDGET_AVAILABLE_VEHICLES, window_type != VLW_STANDARD);
    01116       this->SetWidgetsDisabledState(this->vehicles.Length() == 0,
    01117         VLW_WIDGET_MANAGE_VEHICLES_DROPDOWN,
    01118         VLW_WIDGET_STOP_ALL,
    01119         VLW_WIDGET_START_ALL,
    01120         WIDGET_LIST_END);
    01121     }
    01122
    01123     /* Set text of sort by dropdown widget. */
    01124     this->GetWidget<NWidgetCore>(VLW_WIDGET_SORT_BY_PULLDOWN)->widget_data = this->vehicle_sorter_names[this->vehicles.SortType()];
    01125
    01126     this->DrawWidgets();
    01127   }
    01128
    01129   virtual void OnClick(Point pt, int widget, int click_count)
    01130   {
    01131     switch (widget) {
    01132       case VLW_WIDGET_SORT_ORDER: // Flip sorting method ascending/descending
    01133         this->vehicles.ToggleSortOrder();
    01134         this->SetDirty();
    01135         break;
    01136
    01137       case VLW_WIDGET_SORT_BY_PULLDOWN:// Select sorting criteria dropdown menu
    01138         ShowDropDownMenu(this, this->vehicle_sorter_names, this->vehicles.SortType(), VLW_WIDGET_SORT_BY_PULLDOWN, 0,
    01139             (this->vehicle_type == VEH_TRAIN || this->vehicle_type == VEH_ROAD) ? 0 : (1 << 10));
    01140         return;
    01141
    01142       case VLW_WIDGET_LIST: { // Matrix to show vehicles
    01143         uint32 id_v = (pt.y - this->GetWidget<NWidgetBase>(VLW_WIDGET_LIST)->pos_y) / this->resize.step_height;
    01144         const Vehicle *v;
    01145
    01146         if (id_v >= this->vscroll.GetCapacity()) return; // click out of bounds
    01147
    01148         id_v += this->vscroll.GetPosition();
    01149
    01150         if (id_v >= this->vehicles.Length()) return; // click out of list bound
    01151
    01152         v = this->vehicles[id_v];
    01153
    01154         ShowVehicleViewWindow(v);
    01155       } break;
    01156
    01157       case VLW_WIDGET_AVAILABLE_VEHICLES:
    01158         ShowBuildVehicleWindow(INVALID_TILE, this->vehicle_type);
    01159         break;
    01160
    01161       case VLW_WIDGET_MANAGE_VEHICLES_DROPDOWN: {
    01162         static StringID action_str[] = {
    01163           STR_VEHICLE_LIST_REPLACE_VEHICLES,
    01164           STR_VEHICLE_LIST_SEND_FOR_SERVICING,
    01165           STR_NULL,
    01166           INVALID_STRING_ID
    01167         };
    01168
    01169         static const StringID depot_name[] = {
    01170           STR_VEHICLE_LIST_SEND_TRAIN_TO_DEPOT,
    01171           STR_VEHICLE_LIST_SEND_ROAD_VEHICLE_TO_DEPOT,
    01172           STR_VEHICLE_LIST_SEND_SHIP_TO_DEPOT,
    01173           STR_VEHICLE_LIST_SEND_AIRCRAFT_TO_HANGAR
    01174         };
    01175
    01176         /* XXX - Substite string since the dropdown cannot handle dynamic strings */
    01177         action_str[2] = depot_name[this->vehicle_type];
    01178         ShowDropDownMenu(this, action_str, 0, VLW_WIDGET_MANAGE_VEHICLES_DROPDOWN, 0, (this->window_number & VLW_MASK) == VLW_STANDARD ? 0 : 1);
    01179         break;
    01180       }
    01181
    01182       case VLW_WIDGET_STOP_ALL:
    01183       case VLW_WIDGET_START_ALL:
    01184         DoCommandP(0, GB(this->window_number, 16, 16),
    01185             (this->window_number & VLW_MASK) | (1 << 6) | (widget == VLW_WIDGET_START_ALL ? (1 << 5) : 0) | this->vehicle_type, CMD_MASS_START_STOP);
    01186         break;
    01187     }
    01188   }
    01189
    01190   virtual void OnDropdownSelect(int widget, int index)
    01191   {
    01192     switch (widget) {
    01193       case VLW_WIDGET_SORT_BY_PULLDOWN:
    01194         this->vehicles.SetSortType(index);
    01195         break;
    01196       case VLW_WIDGET_MANAGE_VEHICLES_DROPDOWN:
    01197         assert(this->vehicles.Length() != 0);
    01198
    01199         switch (index) {
    01200           case 0: // Replace window
    01201             ShowReplaceGroupVehicleWindow(DEFAULT_GROUP, this->vehicle_type);
    01202             break;
    01203           case 1: // Send for servicing
    01204             DoCommandP(0, GB(this->window_number, 16, 16) /* StationID or OrderID (depending on VLW) */,
    01205               (this->window_number & VLW_MASK) | DEPOT_MASS_SEND | DEPOT_SERVICE, GetCmdSendToDepot(this->vehicle_type));
    01206             break;
    01207           case 2: // Send to Depots
    01208             DoCommandP(0, GB(this->window_number, 16, 16) /* StationID or OrderID (depending on VLW) */,
    01209               (this->window_number & VLW_MASK) | DEPOT_MASS_SEND, GetCmdSendToDepot(this->vehicle_type));
    01210             break;
    01211
    01212           default: NOT_REACHED();
    01213         }
    01214         break;
    01215       default: NOT_REACHED();
    01216     }
    01217     this->SetDirty();
    01218   }
    01219
    01220   virtual void OnTick()
    01221   {
    01222     if (_pause_mode != PM_UNPAUSED) return;
    01223     if (this->vehicles.NeedResort()) {
    01224       StationID station = ((this->window_number & VLW_MASK) == VLW_STATION_LIST) ? GB(this->window_number, 16, 16) : INVALID_STATION;
    01225
    01226       DEBUG(misc, 3, "Periodic resort %d list company %d at station %d", this->vehicle_type, this->owner, station);
    01227       this->SetDirty();
    01228     }
    01229   }
    01230
    01231   virtual void OnResize()
    01232   {
    01233     this->vscroll.SetCapacityFromWidget(this, VLW_WIDGET_LIST);
    01234     this->GetWidget<NWidgetCore>(VLW_WIDGET_LIST)->widget_data = (this->vscroll.GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
    01235   }
    01236
    01237   virtual void OnInvalidateData(int data)
    01238   {
    01239     if (HasBit(data, 15) && (this->window_number & VLW_MASK) == VLW_SHARED_ORDERS) {
    01240       SB(this->window_number, 16, 16, GB(data, 16, 16));
    01241       this->vehicles.ForceRebuild();
    01242       return;
    01243     }
    01244
    01245     if (data == 0) {
    01246       this->vehicles.ForceRebuild();
    01247     } else {
    01248       this->vehicles.ForceResort();
    01249     }
    01250   }
    01251 };
    01252
    01253 static WindowDesc _vehicle_list_desc(
    01254   WDP_AUTO, 260, 246,
    01255   WC_INVALID, WC_NONE,
    01256   WDF_UNCLICK_BUTTONS,
    01257   _nested_vehicle_list, lengthof(_nested_vehicle_list)
    01258 );
    01259
    01260 static void ShowVehicleListWindowLocal(CompanyID company, uint16 VLW_flag, VehicleType vehicle_type, uint16 unique_number)
    01261 {
    01262   if (!Company::IsValidID(company)) {
    01263     company = _local_company;
    01264     /* This can happen when opening the vehicle list as a spectator.
    01265      * While it would be cleaner to check this somewhere else, having
    01266      * it here reduces code duplication */
    01267     if (!Company::IsValidID(company)) return;
    01268     _vehicle_list_desc.flags |= WDF_CONSTRUCTION;
    01269   } else {
    01270     _vehicle_list_desc.flags &= ~WDF_CONSTRUCTION;
    01271   }
    01272
    01273   _vehicle_list_desc.cls = GetWindowClassForVehicleType(vehicle_type);
    01274   WindowNumber num = (unique_number << 16) | (vehicle_type << 11) | VLW_flag | company;
    01275   AllocateWindowDescFront<VehicleListWindow>(&_vehicle_list_desc, num);
    01276 }
    01277
    01278 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type)
    01279 {
    01280   /* If _settings_client.gui.advanced_vehicle_list > 1, display the Advanced list
    01281    * if _settings_client.gui.advanced_vehicle_list == 1, display Advanced list only for local company
    01282    * if _ctrl_pressed, do the opposite action (Advanced list x Normal list)
    01283    */
    01284
    01285   if ((_settings_client.gui.advanced_vehicle_list > (uint)(company != _local_company)) != _ctrl_pressed) {
    01286     ShowCompanyGroup(company, vehicle_type);
    01287   } else {
    01288     ShowVehicleListWindowLocal(company, VLW_STANDARD, vehicle_type, company);
    01289   }
    01290 }
    01291
    01292 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, const Waypoint *wp)
    01293 {
    01294   if (wp == NULL) return;
    01295   ShowVehicleListWindowLocal(company, VLW_WAYPOINT_LIST, vehicle_type, wp->index);
    01296 }
    01297
    01298 void ShowVehicleListWindow(const Vehicle *v)
    01299 {
    01300   ShowVehicleListWindowLocal(v->owner, VLW_SHARED_ORDERS, v->type, v->FirstShared()->index);
    01301 }
    01302
    01303 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, StationID station)
    01304 {
    01305   ShowVehicleListWindowLocal(company, VLW_STATION_LIST, vehicle_type, station);
    01306 }
    01307
    01308 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, TileIndex depot_tile)
    01309 {
    01310   uint16 depot_airport_index;
    01311
    01312   if (vehicle_type == VEH_AIRCRAFT) {
    01313     depot_airport_index = GetStationIndex(depot_tile);
    01314   } else {
    01315     depot_airport_index = GetDepotIndex(depot_tile);
    01316   }
    01317   ShowVehicleListWindowLocal(company, VLW_DEPOT_LIST, vehicle_type, depot_airport_index);
    01318 }
    01319
    01320
    01321 /* Unified vehicle GUI - Vehicle Details Window */
    01322
    01324 enum VehicleDetailsWindowWidgets {
    01325   VLD_WIDGET_CAPTION,
    01326   VLD_WIDGET_RENAME_VEHICLE,
    01327   VLD_WIDGET_TOP_DETAILS,
    01328   VLD_WIDGET_INCREASE_SERVICING_INTERVAL,
    01329   VLD_WIDGET_DECREASE_SERVICING_INTERVAL,
    01330   VLD_WIDGET_SERVICING_INTERVAL,
    01331   VLD_WIDGET_MIDDLE_DETAILS,
    01332   VLD_WIDGET_MATRIX,
    01333   VLD_WIDGET_SCROLLBAR,
    01334   VLD_WIDGET_DETAILS_CARGO_CARRIED,
    01335   VLD_WIDGET_DETAILS_TRAIN_VEHICLES,
    01336   VLD_WIDGET_DETAILS_CAPACITY_OF_EACH,
    01337   VLD_WIDGET_DETAILS_TOTAL_CARGO,
    01338 };
    01339
    01340 assert_compile(VLD_WIDGET_DETAILS_CARGO_CARRIED    == VLD_WIDGET_DETAILS_CARGO_CARRIED + TDW_TAB_CARGO   );
    01341 assert_compile(VLD_WIDGET_DETAILS_TRAIN_VEHICLES   == VLD_WIDGET_DETAILS_CARGO_CARRIED + TDW_TAB_INFO    );
    01342 assert_compile(VLD_WIDGET_DETAILS_CAPACITY_OF_EACH == VLD_WIDGET_DETAILS_CARGO_CARRIED + TDW_TAB_CAPACITY);
    01343 assert_compile(VLD_WIDGET_DETAILS_TOTAL_CARGO      == VLD_WIDGET_DETAILS_CARGO_CARRIED + TDW_TAB_TOTALS  );
    01344
    01346 static const NWidgetPart _nested_nontrain_vehicle_details_widgets[] = {
    01347   NWidget(NWID_HORIZONTAL),
    01348     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
    01349     NWidget(WWT_CAPTION, COLOUR_GREY, VLD_WIDGET_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
    01350     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, VLD_WIDGET_RENAME_VEHICLE), SetMinimalSize(40, 0), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetDataTip(STR_VEHICLE_NAME_BUTTON, STR_NULL /* filled in later */),
    01351     NWidget(WWT_SHADEBOX, COLOUR_GREY),
    01352     NWidget(WWT_STICKYBOX, COLOUR_GREY),
    01353   EndContainer(),
    01354   NWidget(WWT_PANEL, COLOUR_GREY, VLD_WIDGET_TOP_DETAILS), SetMinimalSize(405, 42), SetResize(1, 0), EndContainer(),
    01355   NWidget(WWT_PANEL, COLOUR_GREY, VLD_WIDGET_MIDDLE_DETAILS), SetMinimalSize(405, 45), SetResize(1, 0), EndContainer(),
    01356   NWidget(NWID_HORIZONTAL),
    01357     NWidget(NWID_BUTTON_ARROW, COLOUR_GREY, VLD_WIDGET_DECREASE_SERVICING_INTERVAL), SetFill(0, 1),
    01358         SetDataTip(AWV_DECREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
    01359     NWidget(NWID_BUTTON_ARROW, COLOUR_GREY, VLD_WIDGET_INCREASE_SERVICING_INTERVAL), SetFill(0, 1),
    01360         SetDataTip(AWV_INCREASE, STR_VEHICLE_DETAILS_INCREASE_SERVICING_INTERVAL_TOOLTIP),
    01361     NWidget(WWT_PANEL, COLOUR_GREY, VLD_WIDGET_SERVICING_INTERVAL), SetFill(1, 1), SetResize(1, 0), EndContainer(),
    01362     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
    01363   EndContainer(),
    01364 };
    01365
    01367 static const NWidgetPart _nested_train_vehicle_details_widgets[] = {
    01368   NWidget(NWID_HORIZONTAL),
    01369     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
    01370     NWidget(WWT_CAPTION, COLOUR_GREY, VLD_WIDGET_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
    01371     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, VLD_WIDGET_RENAME_VEHICLE), SetMinimalSize(40, 0), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetDataTip(STR_VEHICLE_NAME_BUTTON, STR_NULL /* filled in later */),
    01372     NWidget(WWT_SHADEBOX, COLOUR_GREY),
    01373     NWidget(WWT_STICKYBOX, COLOUR_GREY),
    01374   EndContainer(),
    01375   NWidget(WWT_PANEL, COLOUR_GREY, VLD_WIDGET_TOP_DETAILS), SetResize(1, 0), SetMinimalSize(405, 42), EndContainer(),
    01376   NWidget(NWID_HORIZONTAL),
    01377     NWidget(WWT_MATRIX, COLOUR_GREY, VLD_WIDGET_MATRIX), SetResize(1, 1), SetMinimalSize(393, 45), SetDataTip(0x701, STR_NULL), SetFill(1, 0),
    01378     NWidget(WWT_SCROLLBAR, COLOUR_GREY, VLD_WIDGET_SCROLLBAR),
    01379   EndContainer(),
    01380   NWidget(NWID_HORIZONTAL),
    01381     NWidget(NWID_BUTTON_ARROW, COLOUR_GREY, VLD_WIDGET_DECREASE_SERVICING_INTERVAL), SetFill(0, 1),
    01382         SetDataTip(AWV_DECREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
    01383     NWidget(NWID_BUTTON_ARROW, COLOUR_GREY, VLD_WIDGET_INCREASE_SERVICING_INTERVAL), SetFill(0, 1),
    01384         SetDataTip(AWV_INCREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
    01385     NWidget(WWT_PANEL, COLOUR_GREY, VLD_WIDGET_SERVICING_INTERVAL), SetFill(1, 1), SetResize(1, 0), EndContainer(),
    01386   EndContainer(),
    01387   NWidget(NWID_HORIZONTAL),
    01388     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, VLD_WIDGET_DETAILS_CARGO_CARRIED), SetMinimalSize(96, 12),
    01389         SetDataTip(STR_VEHICLE_DETAIL_TAB_CARGO, STR_VEHICLE_DETAILS_TRAIN_CARGO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
    01390     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, VLD_WIDGET_DETAILS_TRAIN_VEHICLES), SetMinimalSize(99, 12),
    01391         SetDataTip(STR_VEHICLE_DETAIL_TAB_INFORMATION, STR_VEHICLE_DETAILS_TRAIN_INFORMATION_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
    01392     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, VLD_WIDGET_DETAILS_CAPACITY_OF_EACH), SetMinimalSize(99, 12),
    01393         SetDataTip(STR_VEHICLE_DETAIL_TAB_CAPACITIES, STR_VEHICLE_DETAILS_TRAIN_CAPACITIES_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
    01394     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, VLD_WIDGET_DETAILS_TOTAL_CARGO), SetMinimalSize(99, 12),
    01395         SetDataTip(STR_VEHICLE_DETAIL_TAB_TOTAL_CARGO, STR_VEHICLE_DETAILS_TRAIN_TOTAL_CARGO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
    01396     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
    01397   EndContainer(),
    01398 };
    01399
    01400
    01401 extern int GetTrainDetailsWndVScroll(VehicleID veh_id, TrainDetailsWindowTabs det_tab);
    01402 extern void DrawTrainDetails(const Train *v, int left, int right, int y, int vscroll_pos, uint16 vscroll_cap, TrainDetailsWindowTabs det_tab);
    01403 extern void DrawRoadVehDetails(const Vehicle *v, int left, int right, int y);
    01404 extern void DrawShipDetails(const Vehicle *v, int left, int right, int y);
    01405 extern void DrawAircraftDetails(const Aircraft *v, int left, int right, int y);
    01406
    01408 struct VehicleDetailsWindow : Window {
    01409   TrainDetailsWindowTabs tab;
    01410
    01412   VehicleDetailsWindow(const WindowDesc *desc, WindowNumber window_number) : Window()
    01413   {
    01414     this->InitNested(desc, window_number);
    01415
    01416     const Vehicle *v = Vehicle::Get(this->window_number);
    01417
    01418     this->GetWidget<NWidgetCore>(VLD_WIDGET_RENAME_VEHICLE)->tool_tip = STR_VEHICLE_DETAILS_TRAIN_RENAME + v->type;
    01419
    01420     this->owner = v->owner;
    01421     this->tab = TDW_TAB_CARGO;
    01422   }
    01423
    01424   virtual void OnInvalidateData(int data)
    01425   {
    01426     const Vehicle *v = Vehicle::Get(this->window_number);
    01427     if (v->type == VEH_ROAD) {
    01428       const NWidgetBase *nwid_info = this->GetWidget<NWidgetBase>(VLD_WIDGET_MIDDLE_DETAILS);
    01429       uint aimed_height = this->GetRoadVehDetailsHeight(v);
    01430       /* If the number of articulated parts changes, the size of the window must change too. */
    01431       if (aimed_height != nwid_info->current_y) {
    01432         this->ReInit();
    01433       }
    01434     }
    01435   }
    01436
    01442   uint GetRoadVehDetailsHeight(const Vehicle *v)
    01443   {
    01444     uint desired_height;
    01445     if (RoadVehicle::From(v)->HasArticulatedPart()) {
    01446       /* An articulated RV has its text drawn under the sprite instead of after it, hence 15 pixels extra. */
    01447       desired_height = WD_FRAMERECT_TOP + 15 + 3 * FONT_HEIGHT_NORMAL + 2 + WD_FRAMERECT_BOTTOM;
    01448       /* Add space for the cargo amount for each part. */
    01449       for (const Vehicle *u = v; u != NULL; u = u->Next()) {
    01450         if (u->cargo_cap != 0) desired_height += FONT_HEIGHT_NORMAL + 1;
    01451       }
    01452     } else {
    01453       desired_height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + 3 + WD_FRAMERECT_BOTTOM;
    01454     }
    01455     return desired_height;
    01456   }
    01457
    01458   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    01459   {
    01460     switch (widget) {
    01461       case VLD_WIDGET_TOP_DETAILS: {
    01462         Dimension dim = { 0, 0 };
    01463         size->height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
    01464
    01465         for (uint i = 0; i < 4; i++) SetDParam(i, INT16_MAX);
    01466         static const StringID info_strings[] = {
    01467           STR_VEHICLE_INFO_MAX_SPEED,
    01468           STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED,
    01469           STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE,
    01470           STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR,
    01471           STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS
    01472         };
    01473         for (uint i = 0; i < lengthof(info_strings); i++) {
    01474           dim = maxdim(dim, GetStringBoundingBox(info_strings[i]));
    01475         }
    01476         SetDParam(0, STR_VEHICLE_INFO_AGE);
    01477         dim = maxdim(dim, GetStringBoundingBox(STR_VEHICLE_INFO_AGE_RUNNING_COST_YR));
    01478         size->width = dim.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
    01479       } break;
    01480
    01481       case VLD_WIDGET_MIDDLE_DETAILS: {
    01482         const Vehicle *v = Vehicle::Get(this->window_number);
    01483         switch (v->type) {
    01484           case VEH_ROAD:
    01485             size->height = this->GetRoadVehDetailsHeight(v);
    01486             break;
    01487
    01488           case VEH_SHIP:
    01489             size->height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + 3 + WD_FRAMERECT_BOTTOM;
    01490             break;
    01491
    01492           case VEH_AIRCRAFT:
    01493             size->height = WD_FRAMERECT_TOP + 5 * FONT_HEIGHT_NORMAL + 4 + WD_FRAMERECT_BOTTOM;
    01494             break;
    01495
    01496           default:
    01497             NOT_REACHED(); // Train uses VLD_WIDGET_MATRIX instead.
    01498         }
    01499         break;
    01500       }
    01501
    01502       case VLD_WIDGET_MATRIX:
    01503         resize->height = WD_MATRIX_TOP + FONT_HEIGHT_NORMAL + WD_MATRIX_BOTTOM;
    01504         size->height = 4 * resize->height;
    01505         break;
    01506
    01507       case VLD_WIDGET_SERVICING_INTERVAL:
    01508         SetDParam(0, 9999); // Roughly the maximum interval
    01509         SetDParam(1, MAX_YEAR * DAYS_IN_YEAR); // Roughly the maximum year
    01510         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;
    01511         size->height = WD_FRAMERECT_TOP + FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
    01512         break;
    01513     }
    01514   }
    01515
    01517   static bool IsVehicleServiceIntervalEnabled(const VehicleType vehicle_type, CompanyID company_id)
    01518   {
    01519     const VehicleDefaultSettings *vds = &Company::Get(company_id)->settings.vehicle;
    01520     switch (vehicle_type) {
    01521       default: NOT_REACHED();
    01522       case VEH_TRAIN:    return vds->servint_trains   != 0;
    01523       case VEH_ROAD:     return vds->servint_roadveh  != 0;
    01524       case VEH_SHIP:     return vds->servint_ships    != 0;
    01525       case VEH_AIRCRAFT: return vds->servint_aircraft != 0;
    01526     }
    01527   }
    01528
    01540   static void DrawVehicleDetails(const Vehicle *v, int left, int right, int y, int vscroll_pos, uint vscroll_cap, TrainDetailsWindowTabs det_tab)
    01541   {
    01542     switch (v->type) {
    01543       case VEH_TRAIN:    DrawTrainDetails(Train::From(v), left, right, y, vscroll_pos, vscroll_cap, det_tab);  break;
    01544       case VEH_ROAD:     DrawRoadVehDetails(v, left, right, y);  break;
    01545       case VEH_SHIP:     DrawShipDetails(v, left, right, y);     break;
    01546       case VEH_AIRCRAFT: DrawAircraftDetails(Aircraft::From(v), left, right, y); break;
    01547       default: NOT_REACHED();
    01548     }
    01549   }
    01550
    01551   virtual void SetStringParameters(int widget) const
    01552   {
    01553     if (widget == VLD_WIDGET_CAPTION) SetDParam(0, Vehicle::Get(this->window_number)->index);
    01554   }
    01555
    01556   virtual void DrawWidget(const Rect &r, int widget) const
    01557   {
    01558     const Vehicle *v = Vehicle::Get(this->window_number);
    01559
    01560     switch (widget) {
    01561       case VLD_WIDGET_TOP_DETAILS: {
    01562         int y = r.top + WD_FRAMERECT_TOP;
    01563
    01564         /* Draw running cost */
    01565         SetDParam(1, v->age / DAYS_IN_LEAP_YEAR);
    01566         SetDParam(0, (v->age + DAYS_IN_YEAR < v->max_age) ? STR_VEHICLE_INFO_AGE : STR_VEHICLE_INFO_AGE_RED);
    01567         SetDParam(2, v->max_age / DAYS_IN_LEAP_YEAR);
    01568         SetDParam(3, v->GetDisplayRunningCost());
    01569         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_AGE_RUNNING_COST_YR);
    01570         y += FONT_HEIGHT_NORMAL;
    01571
    01572         /* Draw max speed */
    01573         switch (v->type) {
    01574           case VEH_TRAIN:
    01575             SetDParam(2, v->GetDisplayMaxSpeed());
    01576             SetDParam(1, Train::From(v)->tcache.cached_power);
    01577             SetDParam(0, Train::From(v)->tcache.cached_weight);
    01578             SetDParam(3, Train::From(v)->tcache.cached_max_te / 1000);
    01579             DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && GetRailTypeInfo(Train::From(v)->railtype)->acceleration_type != 2) ?
    01580                 STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE : STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED);
    01581             break;
    01582
    01583           case VEH_ROAD:
    01584           case VEH_SHIP:
    01585           case VEH_AIRCRAFT:
    01586             SetDParam(0, v->GetDisplayMaxSpeed());
    01587             DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_MAX_SPEED);
    01588             break;
    01589
    01590           default: NOT_REACHED();
    01591         }
    01592         y += FONT_HEIGHT_NORMAL;
    01593
    01594         /* Draw profit */
    01595         SetDParam(0, v->GetDisplayProfitThisYear());
    01596         SetDParam(1, v->GetDisplayProfitLastYear());
    01597         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR);
    01598         y += FONT_HEIGHT_NORMAL;
    01599
    01600         /* Draw breakdown & reliability */
    01601         SetDParam(0, ToPercent16(v->reliability));
    01602         SetDParam(1, v->breakdowns_since_last_service);
    01603         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS);
    01604         break;
    01605       }
    01606
    01607       case VLD_WIDGET_MATRIX:
    01608         /* For trains only. */
    01609         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);
    01610         break;
    01611
    01612       case VLD_WIDGET_MIDDLE_DETAILS: {
    01613         /* For other vehicles, at the place of the matrix. */
    01614         bool rtl = _dynlang.text_dir == TD_RTL;
    01615         uint sprite_width = max<uint>(GetSprite(v->GetImage(rtl ? DIR_E : DIR_W), ST_NORMAL)->width, 70U) + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
    01616
    01617         uint text_left  = r.left  + (rtl ? 0 : sprite_width);
    01618         uint text_right = r.right - (rtl ? sprite_width : 0);
    01619
    01620         uint sprite_left  = rtl ? text_right : r.left;
    01621         uint sprite_right = rtl ? r.right : text_left;
    01622
    01623         DrawVehicleImage(v, sprite_left + WD_FRAMERECT_LEFT, sprite_right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, 0);
    01624         DrawVehicleDetails(v, text_left + WD_FRAMERECT_LEFT, text_right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, this->vscroll.GetPosition(), this->vscroll.GetCapacity(), this->tab);
    01625       } break;
    01626
    01627       case VLD_WIDGET_SERVICING_INTERVAL:
    01628         /* Draw service interval text */
    01629         SetDParam(0, v->service_interval);
    01630         SetDParam(1, v->date_of_last_service);
    01631         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + (r.bottom - r.top + 1 - FONT_HEIGHT_NORMAL) / 2,
    01632             Company::Get(v->owner)->settings.vehicle.servint_ispercent ? STR_VEHICLE_DETAILS_SERVICING_INTERVAL_PERCENT : STR_VEHICLE_DETAILS_SERVICING_INTERVAL_DAYS);
    01633         break;
    01634     }
    01635   }
    01636
    01638   virtual void OnPaint()
    01639   {
    01640     const Vehicle *v = Vehicle::Get(this->window_number);
    01641
    01642     this->SetWidgetDisabledState(VLD_WIDGET_RENAME_VEHICLE, v->owner != _local_company);
    01643
    01644     if (v->type == VEH_TRAIN) {
    01645       this->DisableWidget(this->tab + VLD_WIDGET_DETAILS_CARGO_CARRIED);
    01646       this->vscroll.SetCount(GetTrainDetailsWndVScroll(v->index, this->tab));
    01647     }
    01648
    01649     /* Disable service-scroller when interval is set to disabled */
    01650     this->SetWidgetsDisabledState(!IsVehicleServiceIntervalEnabled(v->type, v->owner),
    01651       VLD_WIDGET_INCREASE_SERVICING_INTERVAL,
    01652       VLD_WIDGET_DECREASE_SERVICING_INTERVAL,
    01653       WIDGET_LIST_END);
    01654
    01655     this->DrawWidgets();
    01656   }
    01657
    01658   virtual void OnClick(Point pt, int widget, int click_count)
    01659   {
    01660     switch (widget) {
    01661       case VLD_WIDGET_RENAME_VEHICLE: { // rename
    01662         const Vehicle *v = Vehicle::Get(this->window_number);
    01663         SetDParam(0, v->index);
    01664         ShowQueryString(STR_VEHICLE_NAME, STR_QUERY_RENAME_TRAIN_CAPTION + v->type,
    01665             MAX_LENGTH_VEHICLE_NAME_BYTES, MAX_LENGTH_VEHICLE_NAME_PIXELS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT);
    01666       } break;
    01667
    01668       case VLD_WIDGET_INCREASE_SERVICING_INTERVAL:   // increase int
    01669       case VLD_WIDGET_DECREASE_SERVICING_INTERVAL: { // decrease int
    01670         int mod = _ctrl_pressed ? 5 : 10;
    01671         const Vehicle *v = Vehicle::Get(this->window_number);
    01672
    01673         mod = (widget == VLD_WIDGET_DECREASE_SERVICING_INTERVAL) ? -mod : mod;
    01674         mod = GetServiceIntervalClamped(mod + v->service_interval, v->owner);
    01675         if (mod == v->service_interval) return;
    01676
    01677         DoCommandP(v->tile, v->index, mod, CMD_CHANGE_SERVICE_INT | CMD_MSG(STR_ERROR_CAN_T_CHANGE_SERVICING));
    01678       } break;
    01679
    01680       case VLD_WIDGET_DETAILS_CARGO_CARRIED:
    01681       case VLD_WIDGET_DETAILS_TRAIN_VEHICLES:
    01682       case VLD_WIDGET_DETAILS_CAPACITY_OF_EACH:
    01683       case VLD_WIDGET_DETAILS_TOTAL_CARGO:
    01684         this->SetWidgetsDisabledState(false,
    01685           VLD_WIDGET_DETAILS_CARGO_CARRIED,
    01686           VLD_WIDGET_DETAILS_TRAIN_VEHICLES,
    01687           VLD_WIDGET_DETAILS_CAPACITY_OF_EACH,
    01688           VLD_WIDGET_DETAILS_TOTAL_CARGO,
    01689           widget,
    01690           WIDGET_LIST_END);
    01691
    01692         this->tab = (TrainDetailsWindowTabs)(widget - VLD_WIDGET_DETAILS_CARGO_CARRIED);
    01693         this->SetDirty();
    01694         break;
    01695     }
    01696   }
    01697
    01698   virtual void OnQueryTextFinished(char *str)
    01699   {
    01700     if (str == NULL) return;
    01701
    01702     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);
    01703   }
    01704
    01705   virtual void OnResize()
    01706   {
    01707     NWidgetCore *nwi = this->GetWidget<NWidgetCore>(VLD_WIDGET_MATRIX);
    01708     if (nwi != NULL) {
    01709       this->vscroll.SetCapacityFromWidget(this, VLD_WIDGET_MATRIX);
    01710       nwi->widget_data = (this->vscroll.GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
    01711     }
    01712   }
    01713 };
    01714
    01716 static const WindowDesc _train_vehicle_details_desc(
    01717   WDP_AUTO, 405, 178,
    01718   WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
    01719   WDF_UNCLICK_BUTTONS,
    01720   _nested_train_vehicle_details_widgets, lengthof(_nested_train_vehicle_details_widgets)
    01721 );
    01722
    01724 static const WindowDesc _nontrain_vehicle_details_desc(
    01725   WDP_AUTO, 405, 113,
    01726   WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
    01727   WDF_UNCLICK_BUTTONS,
    01728   _nested_nontrain_vehicle_details_widgets, lengthof(_nested_nontrain_vehicle_details_widgets)
    01729 );
    01730
    01732 static void ShowVehicleDetailsWindow(const Vehicle *v)
    01733 {
    01734   DeleteWindowById(WC_VEHICLE_ORDERS, v->index, false);
    01735   DeleteWindowById(WC_VEHICLE_TIMETABLE, v->index, false);
    01736   AllocateWindowDescFront<VehicleDetailsWindow>((v->type == VEH_TRAIN) ? &_train_vehicle_details_desc : &_nontrain_vehicle_details_desc, v->index);
    01737 }
    01738
    01739
    01740 /* Unified vehicle GUI - Vehicle View Window */
    01741
    01743 static const NWidgetPart _nested_vehicle_view_widgets[] = {
    01744   NWidget(NWID_HORIZONTAL),
    01745     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
    01746     NWidget(WWT_CAPTION, COLOUR_GREY, VVW_WIDGET_CAPTION), SetDataTip(STR_VEHICLE_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
    01747     NWidget(WWT_SHADEBOX, COLOUR_GREY),
    01748     NWidget(WWT_STICKYBOX, COLOUR_GREY),
    01749   EndContainer(),
    01750   NWidget(NWID_HORIZONTAL),
    01751     NWidget(WWT_PANEL, COLOUR_GREY),
    01752       NWidget(WWT_INSET, COLOUR_GREY), SetPadding(2, 2, 2, 2),
    01753         NWidget(NWID_VIEWPORT, INVALID_COLOUR, VVW_WIDGET_VIEWPORT), SetMinimalSize(226, 84), SetResize(1, 1), SetPadding(1, 1, 1, 1),
    01754       EndContainer(),
    01755     EndContainer(),
    01756     NWidget(NWID_VERTICAL),
    01757       NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VVW_WIDGET_CENTER_MAIN_VIEH), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(SPR_CENTRE_VIEW_VEHICLE, 0x0 /* filled later */),
    01758       NWidget(NWID_SELECTION, INVALID_COLOUR, VVW_WIDGET_SELECT_DEPOT_CLONE),
    01759         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VVW_WIDGET_GOTO_DEPOT), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
    01760         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VVW_WIDGET_CLONE_VEH), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
    01761       EndContainer(),
    01762       /* For trains only, 'ignore signal' button. */
    01763       NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VVW_WIDGET_FORCE_PROCEED), SetMinimalSize(18, 18), SetFill(1, 1),
    01764                       SetDataTip(SPR_IGNORE_SIGNALS, STR_VEHICLE_VIEW_TRAIN_IGNORE_SIGNAL_TOOLTIP),
    01765       NWidget(NWID_SELECTION, INVALID_COLOUR, VVW_WIDGET_SELECT_REFIT_TURN),
    01766         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VVW_WIDGET_REFIT_VEH), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(SPR_REFIT_VEHICLE, 0x0 /* filled later */),
    01767         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VVW_WIDGET_TURN_AROUND), SetMinimalSize(18, 18), SetFill(1, 1),
    01768                         SetDataTip(SPR_FORCE_VEHICLE_TURN, STR_VEHICLE_VIEW_ROAD_VEHICLE_REVERSE_TOOLTIP),
    01769       EndContainer(),
    01770       NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VVW_WIDGET_SHOW_ORDERS), SetFill(1, 1), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_ORDERS, 0x0 /* filled later */),
    01771       NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VVW_WIDGET_SHOW_DETAILS), SetFill(1, 1), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_VEHICLE_DETAILS, 0x0 /* filled later */),
    01772       NWidget(WWT_PANEL, COLOUR_GREY), SetFill(1, 1), SetMinimalSize(18, 0), SetResize(0, 1), EndContainer(),
    01773     EndContainer(),
    01774   EndContainer(),
    01775   NWidget(NWID_HORIZONTAL),
    01776     NWidget(WWT_PUSHBTN, COLOUR_GREY, VVW_WIDGET_START_STOP_VEH), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM), SetResize(1, 0), SetFill(1, 0),
    01777     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
    01778   EndContainer(),
    01779 };
    01780
    01782 static const WindowDesc _vehicle_view_desc(
    01783   WDP_AUTO, 250, 116,
    01784   WC_VEHICLE_VIEW, WC_NONE,
    01785   WDF_UNCLICK_BUTTONS,
    01786   _nested_vehicle_view_widgets, lengthof(_nested_vehicle_view_widgets)
    01787 );
    01788
    01792 static const WindowDesc _train_view_desc(
    01793   WDP_AUTO, 250, 134,
    01794   WC_VEHICLE_VIEW, WC_NONE,
    01795   WDF_UNCLICK_BUTTONS,
    01796   _nested_vehicle_view_widgets, lengthof(_nested_vehicle_view_widgets)
    01797 );
    01798
    01799
    01800 /* Just to make sure, nobody has changed the vehicle type constants, as we are
    01801    using them for array indexing in a number of places here. */
    01802 assert_compile(VEH_TRAIN == 0);
    01803 assert_compile(VEH_ROAD == 1);
    01804 assert_compile(VEH_SHIP == 2);
    01805 assert_compile(VEH_AIRCRAFT == 3);
    01806
    01808 static const ZoomLevel _vehicle_view_zoom_levels[] = {
    01809   ZOOM_LVL_TRAIN,
    01810   ZOOM_LVL_ROADVEH,
    01811   ZOOM_LVL_SHIP,
    01812   ZOOM_LVL_AIRCRAFT,
    01813 };
    01814
    01815 /* Constants for geometry of vehicle view viewport */
    01816 static const int VV_INITIAL_VIEWPORT_WIDTH = 226;
    01817 static const int VV_INITIAL_VIEWPORT_HEIGHT = 84;
    01818 static const int VV_INITIAL_VIEWPORT_HEIGHT_TRAIN = 102;
    01819
    01821 enum VehicleCommandTranslation {
    01822   VCT_CMD_START_STOP = 0,
    01823   VCT_CMD_CLONE_VEH,
    01824   VCT_CMD_TURN_AROUND,
    01825 };
    01826
    01828 static const uint32 _vehicle_command_translation_table[][4] = {
    01829   { // VCT_CMD_START_STOP
    01830     CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_TRAIN),
    01831     CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_ROAD_VEHICLE),
    01832     CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_SHIP),
    01833     CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_AIRCRAFT)
    01834   },
    01835   { // VCT_CMD_CLONE_VEH
    01836     CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_TRAIN),
    01837     CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_ROAD_VEHICLE),
    01838     CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_SHIP),
    01839     CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_AIRCRAFT)
    01840   },
    01841   { // VCT_CMD_TURN_AROUND
    01842     CMD_REVERSE_TRAIN_DIRECTION | CMD_MSG(STR_ERROR_CAN_T_REVERSE_DIRECTION_TRAIN),
    01843     CMD_TURN_ROADVEH            | CMD_MSG(STR_ERROR_CAN_T_MAKE_ROAD_VEHICLE_TURN),
    01844     0xffffffff, // invalid for ships
    01845     0xffffffff  // invalid for aircrafts
    01846   },
    01847 };
    01848
    01850 static bool IsVehicleRefitable(const Vehicle *v)
    01851 {
    01852   if (!v->IsStoppedInDepot()) return false;
    01853
    01854   do {
    01855     if (IsEngineRefittable(v->engine_type)) return true;
    01856   } while ((v->type == VEH_TRAIN || v->type == VEH_ROAD) && (v = v->Next()) != NULL);
    01857
    01858   return false;
    01859 }
    01860
    01862 struct VehicleViewWindow : Window {
    01863 private:
    01865   enum PlaneSelections {
    01866     SEL_DC_GOTO_DEPOT,
    01867     SEL_DC_CLONE,
    01868
    01869     SEL_RT_REFIT,
    01870     SEL_RT_TURN_AROUND,
    01871
    01872     SEL_DC_BASEPLANE = SEL_DC_GOTO_DEPOT,
    01873     SEL_RT_BASEPLANE = SEL_RT_REFIT,
    01874   };
    01875
    01879   void SelectPlane(PlaneSelections plane)
    01880   {
    01881     switch (plane) {
    01882       case SEL_DC_GOTO_DEPOT:
    01883       case SEL_DC_CLONE:
    01884         this->GetWidget<NWidgetStacked>(VVW_WIDGET_SELECT_DEPOT_CLONE)->SetDisplayedPlane(plane - SEL_DC_BASEPLANE);
    01885         break;
    01886
    01887       case SEL_RT_REFIT:
    01888       case SEL_RT_TURN_AROUND:
    01889         this->GetWidget<NWidgetStacked>(VVW_WIDGET_SELECT_REFIT_TURN)->SetDisplayedPlane(plane - SEL_RT_BASEPLANE);
    01890         break;
    01891
    01892       default:
    01893         NOT_REACHED();
    01894     }
    01895   }
    01896
    01897 public:
    01898   VehicleViewWindow(const WindowDesc *desc, WindowNumber window_number) : Window()
    01899   {
    01900     this->CreateNestedTree(desc);
    01901
    01902     /* Sprites for the 'send to depot' button indexed by vehicle type. */
    01903     static const SpriteID vehicle_view_goto_depot_sprites[] = {
    01904       SPR_SEND_TRAIN_TODEPOT,
    01905       SPR_SEND_ROADVEH_TODEPOT,
    01906       SPR_SEND_SHIP_TODEPOT,
    01907       SPR_SEND_AIRCRAFT_TODEPOT,
    01908     };
    01909     const Vehicle *v = Vehicle::Get(window_number);
    01910     this->GetWidget<NWidgetCore>(VVW_WIDGET_GOTO_DEPOT)->widget_data = vehicle_view_goto_depot_sprites[v->type];
    01911
    01912     /* Sprites for the 'clone vehicle' button indexed by vehicle type. */
    01913     static const SpriteID vehicle_view_clone_sprites[] = {
    01914       SPR_CLONE_TRAIN,
    01915       SPR_CLONE_ROADVEH,
    01916       SPR_CLONE_SHIP,
    01917       SPR_CLONE_AIRCRAFT,
    01918     };
    01919     this->GetWidget<NWidgetCore>(VVW_WIDGET_CLONE_VEH)->widget_data = vehicle_view_clone_sprites[v->type];
    01920
    01921     switch (v->type) {
    01922       case VEH_TRAIN:
    01923         this->GetWidget<NWidgetCore>(VVW_WIDGET_TURN_AROUND)->tool_tip = STR_VEHICLE_VIEW_TRAIN_REVERSE_TOOLTIP;
    01924         break;
    01925
    01926       case VEH_ROAD:
    01927         break;
    01928
    01929       case VEH_SHIP:
    01930       case VEH_AIRCRAFT:
    01931         this->SelectPlane(SEL_RT_REFIT);
    01932         break;
    01933
    01934       default: NOT_REACHED();
    01935     }
    01936     this->FinishInitNested(desc, window_number);
    01937     this->owner = v->owner;
    01938     this->GetWidget<NWidgetViewport>(VVW_WIDGET_VIEWPORT)->InitializeViewport(this, this->window_number | (1 << 31), _vehicle_view_zoom_levels[v->type]);
    01939
    01940     this->GetWidget<NWidgetCore>(VVW_WIDGET_START_STOP_VEH)->tool_tip   = STR_VEHICLE_VIEW_TRAIN_STATE_START_STOP_TOOLTIP + v->type;
    01941     this->GetWidget<NWidgetCore>(VVW_WIDGET_CENTER_MAIN_VIEH)->tool_tip = STR_VEHICLE_VIEW_TRAIN_LOCATION_TOOLTIP + v->type;
    01942     this->GetWidget<NWidgetCore>(VVW_WIDGET_REFIT_VEH)->tool_tip        = STR_VEHICLE_VIEW_TRAIN_REFIT_TOOLTIP + v->type;
    01943     this->GetWidget<NWidgetCore>(VVW_WIDGET_GOTO_DEPOT)->tool_tip       = STR_VEHICLE_VIEW_TRAIN_SEND_TO_DEPOT_TOOLTIP + v->type;
    01944     this->GetWidget<NWidgetCore>(VVW_WIDGET_SHOW_ORDERS)->tool_tip      = STR_VEHICLE_VIEW_TRAIN_ORDERS_TOOLTIP + v->type;
    01945     this->GetWidget<NWidgetCore>(VVW_WIDGET_SHOW_DETAILS)->tool_tip     = STR_VEHICLE_VIEW_TRAIN_SHOW_DETAILS_TOOLTIP + v->type;
    01946     this->GetWidget<NWidgetCore>(VVW_WIDGET_CLONE_VEH)->tool_tip        = STR_VEHICLE_VIEW_CLONE_TRAIN_INFO + v->type;
    01947   }
    01948
    01949   ~VehicleViewWindow()
    01950   {
    01951     DeleteWindowById(WC_VEHICLE_ORDERS, this->window_number, false);
    01952     DeleteWindowById(WC_VEHICLE_REFIT, this->window_number, false);
    01953     DeleteWindowById(WC_VEHICLE_DETAILS, this->window_number, false);
    01954     DeleteWindowById(WC_VEHICLE_TIMETABLE, this->window_number, false);
    01955   }
    01956
    01957   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    01958   {
    01959     const Vehicle *v = Vehicle::Get(this->window_number);
    01960     switch (widget) {
    01961       case VVW_WIDGET_FORCE_PROCEED:
    01962         if (v->type != VEH_TRAIN) {
    01963           size->height = 0;
    01964           size->width = 0;
    01965         } break;
    01966
    01967       case VVW_WIDGET_VIEWPORT:
    01968         size->width = VV_INITIAL_VIEWPORT_WIDTH;
    01969         size->height = (v->type == VEH_TRAIN) ? VV_INITIAL_VIEWPORT_HEIGHT_TRAIN : VV_INITIAL_VIEWPORT_HEIGHT;
    01970         break;
    01971     }
    01972   }
    01973
    01974   virtual void OnPaint()
    01975   {
    01976     const Vehicle *v = Vehicle::Get(this->window_number);
    01977     bool is_localcompany = v->owner == _local_company;
    01978     bool refitable_and_stopped_in_depot = IsVehicleRefitable(v);
    01979
    01980     this->SetWidgetDisabledState(VVW_WIDGET_GOTO_DEPOT, !is_localcompany);
    01981     this->SetWidgetDisabledState(VVW_WIDGET_REFIT_VEH, !refitable_and_stopped_in_depot || !is_localcompany);
    01982     this->SetWidgetDisabledState(VVW_WIDGET_CLONE_VEH, !is_localcompany);
    01983
    01984     if (v->type == VEH_TRAIN) {
    01985       this->SetWidgetLoweredState(VVW_WIDGET_FORCE_PROCEED, Train::From(v)->force_proceed == 2);
    01986       this->SetWidgetDisabledState(VVW_WIDGET_FORCE_PROCEED, !is_localcompany);
    01987       this->SetWidgetDisabledState(VVW_WIDGET_TURN_AROUND, !is_localcompany);
    01988     }
    01989
    01990     this->DrawWidgets();
    01991   }
    01992
    01993   virtual void SetStringParameters(int widget) const
    01994   {
    01995     if (widget != VVW_WIDGET_CAPTION) return;
    01996
    01997     const Vehicle *v = Vehicle::Get(this->window_number);
    01998     SetDParam(0, v->index);
    01999   }
    02000
    02001   virtual void DrawWidget(const Rect &r, int widget) const
    02002   {
    02003     if (widget != VVW_WIDGET_START_STOP_VEH) return;
    02004
    02005     const Vehicle *v = Vehicle::Get(this->window_number);
    02006     StringID str;
    02007     if (v->vehstatus & VS_CRASHED) {
    02008       str = STR_VEHICLE_STATUS_CRASHED;
    02009     } else if (v->type != VEH_AIRCRAFT && v->breakdown_ctr == 1) { // check for aircraft necessary?
    02010       str = STR_VEHICLE_STATUS_BROKEN_DOWN;
    02011     } else if (v->vehstatus & VS_STOPPED) {
    02012       if (v->type == VEH_TRAIN) {
    02013         if (v->cur_speed == 0) {
    02014           if (Train::From(v)->tcache.cached_power == 0) {
    02015             str = STR_VEHICLE_STATUS_TRAIN_NO_POWER;
    02016           } else {
    02017             str = STR_VEHICLE_STATUS_STOPPED;
    02018           }
    02019         } else {
    02020           SetDParam(0, v->GetDisplaySpeed());
    02021           str = STR_VEHICLE_STATUS_TRAIN_STOPPING + _settings_client.gui.vehicle_speed;
    02022         }
    02023       } else { // no train
    02024         str = STR_VEHICLE_STATUS_STOPPED;
    02025       }
    02026     } else if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_TRAIN_STUCK) && !v->current_order.IsType(OT_LOADING)) {
    02027       str = STR_VEHICLE_STATUS_TRAIN_STUCK;
    02028     } else { // vehicle is in a "normal" state, show current order
    02029       switch (v->current_order.GetType()) {
    02030         case OT_GOTO_STATION: {
    02031           SetDParam(0, v->current_order.GetDestination());
    02032           SetDParam(1, v->GetDisplaySpeed());
    02033           str = STR_VEHICLE_STATUS_HEADING_FOR_STATION + _settings_client.gui.vehicle_speed;
    02034         } break;
    02035
    02036         case OT_GOTO_DEPOT: {
    02037           if (v->type == VEH_AIRCRAFT) {
    02038             /* Aircrafts always go to a station, even if you say depot */
    02039             SetDParam(0, v->current_order.GetDestination());
    02040             SetDParam(1, v->GetDisplaySpeed());
    02041           } else {
    02042             Depot *depot = Depot::Get(v->current_order.GetDestination());
    02043             SetDParam(0, depot->town_index);
    02044             SetDParam(1, v->GetDisplaySpeed());
    02045           }
    02046           if (v->current_order.GetDepotActionType() & ODATFB_HALT) {
    02047             str = STR_VEHICLE_STATUS_HEADING_FOR_TRAIN_DEPOT + 2 * v->type + _settings_client.gui.vehicle_speed;
    02048           } else {
    02049             str = STR_VEHICLE_STATUS_HEADING_FOR_TRAIN_DEPOT_SERVICE + 2 * v->type + _settings_client.gui.vehicle_speed;
    02050           }
    02051         } break;
    02052
    02053         case OT_LOADING:
    02054           str = STR_VEHICLE_STATUS_LOADING_UNLOADING;
    02055           break;
    02056
    02057         case OT_GOTO_WAYPOINT: {
    02058           assert(v->type == VEH_TRAIN || v->type == VEH_SHIP);
    02059           SetDParam(0, v->current_order.GetDestination());
    02060           str = STR_VEHICLE_STATUS_HEADING_FOR_WAYPOINT + _settings_client.gui.vehicle_speed;
    02061           SetDParam(1, v->GetDisplaySpeed());
    02062           break;
    02063         }
    02064
    02065         case OT_LEAVESTATION:
    02066           if (v->type != VEH_AIRCRAFT) {
    02067             str = STR_VEHICLE_STATUS_LEAVING;
    02068             break;
    02069           }
    02070           /* fall-through if aircraft. Does this even happen? */
    02071
    02072         default:
    02073           if (v->GetNumOrders() == 0) {
    02074             str = STR_VEHICLE_STATUS_NO_ORDERS + _settings_client.gui.vehicle_speed;
    02075             SetDParam(0, v->GetDisplaySpeed());
    02076           } else {
    02077             str = STR_EMPTY;
    02078           }
    02079           break;
    02080       }
    02081     }
    02082
    02083     /* draw the flag plus orders */
    02084     DrawSprite(v->vehstatus & VS_STOPPED ? SPR_FLAG_VEH_STOPPED : SPR_FLAG_VEH_RUNNING, PAL_NONE, WD_FRAMERECT_LEFT, r.top + WD_FRAMERECT_TOP);
    02085     DrawString(r.left + WD_FRAMERECT_LEFT + 6, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, str, TC_FROMSTRING, SA_CENTER);
    02086   }
    02087
    02088   virtual void OnClick(Point pt, int widget, int click_count)
    02089   {
    02090     const Vehicle *v = Vehicle::Get(this->window_number);
    02091
    02092     switch (widget) {
    02093       case VVW_WIDGET_START_STOP_VEH: // start stop
    02094         if (_ctrl_pressed) {
    02095           /* Scroll to current order destination */
    02096           TileIndex tile = v->current_order.GetLocation(v);
    02097           if (tile != INVALID_TILE) ScrollMainWindowToTile(tile);
    02098         } else {
    02099           /* Start/Stop */
    02100           DoCommandP(v->tile, v->index, 0,
    02101             _vehicle_command_translation_table[VCT_CMD_START_STOP][v->type]);
    02102         }
    02103         break;
    02104       case VVW_WIDGET_CENTER_MAIN_VIEH: {// center main view
    02105         const Window *mainwindow = FindWindowById(WC_MAIN_WINDOW, 0);
    02106         /* code to allow the main window to 'follow' the vehicle if the ctrl key is pressed */
    02107         if (_ctrl_pressed && mainwindow->viewport->zoom == ZOOM_LVL_NORMAL) {
    02108           mainwindow->viewport->follow_vehicle = v->index;
    02109         } else {
    02110           ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos);
    02111         }
    02112       } break;
    02113
    02114       case VVW_WIDGET_GOTO_DEPOT: // goto hangar
    02115         DoCommandP(v->tile, v->index, _ctrl_pressed ? DEPOT_SERVICE : 0, GetCmdSendToDepot(v));
    02116         break;
    02117       case VVW_WIDGET_REFIT_VEH: // refit
    02118         ShowVehicleRefitWindow(v, INVALID_VEH_ORDER_ID, this);
    02119         break;
    02120       case VVW_WIDGET_SHOW_ORDERS: // show orders
    02121         if (_ctrl_pressed) {
    02122           ShowTimetableWindow(v);
    02123         } else {
    02124           ShowOrdersWindow(v);
    02125         }
    02126         break;
    02127       case VVW_WIDGET_SHOW_DETAILS: // show details
    02128         ShowVehicleDetailsWindow(v);
    02129         break;
    02130       case VVW_WIDGET_CLONE_VEH: // clone vehicle
    02131         DoCommandP(v->tile, v->index, _ctrl_pressed ? 1 : 0,
    02132                     _vehicle_command_translation_table[VCT_CMD_CLONE_VEH][v->type],
    02133                     CcCloneVehicle);
    02134         break;
    02135       case VVW_WIDGET_TURN_AROUND: // turn around
    02136         assert(v->type == VEH_TRAIN || v->type == VEH_ROAD);
    02137         DoCommandP(v->tile, v->index, 0,
    02138                     _vehicle_command_translation_table[VCT_CMD_TURN_AROUND][v->type]);
    02139         break;
    02140       case VVW_WIDGET_FORCE_PROCEED: // force proceed
    02141         assert(v->type == VEH_TRAIN);
    02142         DoCommandP(v->tile, v->index, 0, CMD_FORCE_TRAIN_PROCEED | CMD_MSG(STR_ERROR_CAN_T_MAKE_TRAIN_PASS_SIGNAL));
    02143         break;
    02144     }
    02145   }
    02146
    02147   virtual void OnResize()
    02148   {
    02149     if (this->viewport != NULL) {
    02150       NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(VVW_WIDGET_VIEWPORT);
    02151       nvp->UpdateViewportCoordinates(this);
    02152     }
    02153   }
    02154
    02155   virtual void OnTick()
    02156   {
    02157     const Vehicle *v = Vehicle::Get(this->window_number);
    02158     bool veh_stopped = v->IsStoppedInDepot();
    02159
    02160     /* Widget VVW_WIDGET_GOTO_DEPOT must be hidden if the vehicle is already stopped in depot.
    02161      * Widget VVW_WIDGET_CLONE_VEH should then be shown, since cloning is allowed only while in depot and stopped.
    02162      */
    02163     PlaneSelections plane = veh_stopped ? SEL_DC_CLONE : SEL_DC_GOTO_DEPOT;
    02164     NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(VVW_WIDGET_SELECT_DEPOT_CLONE); // Selection widget 'send to depot' / 'clone'.
    02165     if (nwi->shown_plane + SEL_DC_BASEPLANE != plane) {
    02166       this->SelectPlane(plane);
    02167       this->SetWidgetDirty(VVW_WIDGET_SELECT_DEPOT_CLONE);
    02168     }
    02169     /* The same system applies to widget VVW_WIDGET_REFIT_VEH and VVW_WIDGET_TURN_AROUND.*/
    02170     if (v->type == VEH_ROAD || v->type == VEH_TRAIN) {
    02171       PlaneSelections plane = veh_stopped ? SEL_RT_REFIT : SEL_RT_TURN_AROUND;
    02172       NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(VVW_WIDGET_SELECT_REFIT_TURN);
    02173       if (nwi->shown_plane + SEL_RT_BASEPLANE != plane) {
    02174         this->SelectPlane(plane);
    02175         this->SetWidgetDirty(VVW_WIDGET_SELECT_REFIT_TURN);
    02176       }
    02177     }
    02178   }
    02179 };
    02180
    02181
    02183 void ShowVehicleViewWindow(const Vehicle *v)
    02184 {
    02185   AllocateWindowDescFront<VehicleViewWindow>((v->type == VEH_TRAIN) ? &_train_view_desc : &_vehicle_view_desc, v->index);
    02186 }
    02187
    02188 void StopGlobalFollowVehicle(const Vehicle *v)
    02189 {
    02190   Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
    02191   if (w != NULL && w->viewport->follow_vehicle == v->index) {
    02192     ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos, true); // lock the main view on the vehicle's last position
    02193     w->viewport->follow_vehicle = INVALID_VEHICLE;
    02194   }
    02195 }
    02196
    02197
    02205 void CcBuildPrimaryVehicle(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
    02206 {
    02207   if (result.Failed()) return;
    02208
    02209   const Vehicle *v = Vehicle::Get(_new_vehicle_id);
    02210   if (v->tile == _backup_orders_tile) {
    02211     _backup_orders_tile = 0;
    02212     RestoreVehicleOrders(v);
    02213   }
    02214   ShowVehicleViewWindow(v);
    02215 }