# vehicle_gui.cpp

Go to the documentation of this file.

    00001 /* $Id$ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
    00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
    00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
    00008  */
    00009
    00012 #include "stdafx.h"
    00013 #include "debug.h"
    00014 #include "company_func.h"
    00015 #include "gui.h"
    00016 #include "textbuf_gui.h"
    00017 #include "command_func.h"
    00018 #include "vehicle_gui.h"
    00019 #include "vehicle_gui_base.h"
    00020 #include "viewport_func.h"
    00021 #include "newgrf_text.h"
    00022 #include "newgrf_debug.h"
    00023 #include "roadveh.h"
    00024 #include "train.h"
    00025 #include "aircraft.h"
    00026 #include "depot_map.h"
    00027 #include "group_gui.h"
    00028 #include "strings_func.h"
    00029 #include "window_func.h"
    00030 #include "vehicle_func.h"
    00031 #include "autoreplace_gui.h"
    00032 #include "string_func.h"
    00033 #include "widgets/dropdown_func.h"
    00034 #include "timetable.h"
    00035 #include "articulated_vehicles.h"
    00036 #include "spritecache.h"
    00037 #include "core/geometry_func.hpp"
    00038 #include "company_base.h"
    00039 #include "engine_func.h"
    00040 #include "station_base.h"
    00041 #include "tilehighlight_func.h"
    00042 #include "infrastructure_func.h"
    00043 #include "train.h"
    00044
    00045 #include "table/strings.h"
    00046
    00047 Sorting _sorting;
    00048
    00049 static GUIVehicleList::SortFunction VehicleNumberSorter;
    00050 static GUIVehicleList::SortFunction VehicleNameSorter;
    00051 static GUIVehicleList::SortFunction VehicleAgeSorter;
    00052 static GUIVehicleList::SortFunction VehicleProfitThisYearSorter;
    00053 static GUIVehicleList::SortFunction VehicleProfitLastYearSorter;
    00054 static GUIVehicleList::SortFunction VehicleCargoSorter;
    00055 static GUIVehicleList::SortFunction VehicleReliabilitySorter;
    00056 static GUIVehicleList::SortFunction VehicleMaxSpeedSorter;
    00057 static GUIVehicleList::SortFunction VehicleModelSorter;
    00058 static GUIVehicleList::SortFunction VehicleValueSorter;
    00059 static GUIVehicleList::SortFunction VehicleLengthSorter;
    00060 static GUIVehicleList::SortFunction VehicleTimeToLiveSorter;
    00061 static GUIVehicleList::SortFunction VehicleTimetableDelaySorter;
    00062
    00063 GUIVehicleList::SortFunction * const BaseVehicleListWindow::vehicle_sorter_funcs[] = {
    00064   &VehicleNumberSorter,
    00065   &VehicleNameSorter,
    00066   &VehicleAgeSorter,
    00067   &VehicleProfitThisYearSorter,
    00068   &VehicleProfitLastYearSorter,
    00069   &VehicleCargoSorter,
    00070   &VehicleReliabilitySorter,
    00071   &VehicleMaxSpeedSorter,
    00072   &VehicleModelSorter,
    00073   &VehicleValueSorter,
    00074   &VehicleLengthSorter,
    00075   &VehicleTimeToLiveSorter,
    00076   &VehicleTimetableDelaySorter,
    00077 };
    00078
    00079 const StringID BaseVehicleListWindow::vehicle_sorter_names[] = {
    00080   STR_SORT_BY_NUMBER,
    00081   STR_SORT_BY_NAME,
    00082   STR_SORT_BY_AGE,
    00083   STR_SORT_BY_PROFIT_THIS_YEAR,
    00084   STR_SORT_BY_PROFIT_LAST_YEAR,
    00085   STR_SORT_BY_TOTAL_CAPACITY_PER_CARGOTYPE,
    00086   STR_SORT_BY_RELIABILITY,
    00087   STR_SORT_BY_MAX_SPEED,
    00088   STR_SORT_BY_MODEL,
    00089   STR_SORT_BY_VALUE,
    00090   STR_SORT_BY_LENGTH,
    00091   STR_SORT_BY_LIFE_TIME,
    00092   STR_SORT_BY_TIMETABLE_DELAY,
    00093   INVALID_STRING_ID
    00094 };
    00095
    00096 const StringID BaseVehicleListWindow::vehicle_depot_name[] = {
    00097   STR_VEHICLE_LIST_SEND_TRAIN_TO_DEPOT,
    00098   STR_VEHICLE_LIST_SEND_ROAD_VEHICLE_TO_DEPOT,
    00099   STR_VEHICLE_LIST_SEND_SHIP_TO_DEPOT,
    00100   STR_VEHICLE_LIST_SEND_AIRCRAFT_TO_HANGAR
    00101 };
    00102
    00103 void BaseVehicleListWindow::BuildVehicleList()
    00104 {
    00105   if (!this->vehicles.NeedRebuild()) return;
    00106
    00107   DEBUG(misc, 3, "Building vehicle list type %d for company %d given index %d", this->vli.type, this->vli.company, this->vli.index);
    00108
    00109   GenerateVehicleSortList(&this->vehicles, this->vli);
    00110
    00111   uint unitnumber = 0;
    00112   for (const Vehicle **v = this->vehicles.Begin(); v != this->vehicles.End(); v++) {
    00113     unitnumber = max<uint>(unitnumber, (*v)->unitnumber);
    00114   }
    00115
    00116   /* Because 111 is much less wide than e.g. 999 we use the
    00117    * wider numbers to determine the width instead of just
    00118    * the random number that it seems to be. */
    00119   if (unitnumber >= 1000) {
    00120     this->unitnumber_digits = 4;
    00121   } else if (unitnumber >= 100) {
    00122     this->unitnumber_digits = 3;
    00123   } else {
    00124     this->unitnumber_digits = 2;
    00125   }
    00126
    00127   this->vehicles.RebuildDone();
    00128   this->vscroll->SetCount(this->vehicles.Length());
    00129 }
    00130
    00137 Dimension BaseVehicleListWindow::GetActionDropdownSize(bool show_autoreplace, bool show_group)
    00138 {
    00139   Dimension d = {0, 0};
    00140
    00141   if (show_autoreplace) d = maxdim(d, GetStringBoundingBox(STR_VEHICLE_LIST_REPLACE_VEHICLES));
    00142   d = maxdim(d, GetStringBoundingBox(STR_VEHICLE_LIST_SEND_FOR_SERVICING));
    00143   d = maxdim(d, GetStringBoundingBox(this->vehicle_depot_name[this->vli.vtype]));
    00144
    00145   if (show_group) {
    00146     d = maxdim(d, GetStringBoundingBox(STR_GROUP_ADD_SHARED_VEHICLE));
    00147     d = maxdim(d, GetStringBoundingBox(STR_GROUP_REMOVE_ALL_VEHICLES));
    00148   }
    00149
    00150   return d;
    00151 }
    00152
    00159 DropDownList *BaseVehicleListWindow::BuildActionDropdownList(bool show_autoreplace, bool show_group)
    00160 {
    00161   DropDownList *list = new DropDownList();
    00162
    00163   if (show_autoreplace) list->push_back(new DropDownListStringItem(STR_VEHICLE_LIST_REPLACE_VEHICLES, ADI_REPLACE, false));
    00164   list->push_back(new DropDownListStringItem(STR_VEHICLE_LIST_SEND_FOR_SERVICING, ADI_SERVICE, false));
    00165   list->push_back(new DropDownListStringItem(this->vehicle_depot_name[this->vli.vtype], ADI_DEPOT, false));
    00166
    00167   if (show_group) {
    00168     list->push_back(new DropDownListStringItem(STR_GROUP_ADD_SHARED_VEHICLE, ADI_ADD_SHARED, false));
    00169     list->push_back(new DropDownListStringItem(STR_GROUP_REMOVE_ALL_VEHICLES, ADI_REMOVE_ALL, false));
    00170   }
    00171
    00172   return list;
    00173 }
    00174
    00175 /* cached values for VehicleNameSorter to spare many GetString() calls */
    00176 static const Vehicle *_last_vehicle[2] = { NULL, NULL };
    00177
    00178 void BaseVehicleListWindow::SortVehicleList()
    00179 {
    00180   if (this->vehicles.Sort()) return;
    00181
    00182   /* invalidate cached values for name sorter - vehicle names could change */
    00183   _last_vehicle[0] = _last_vehicle[1] = NULL;
    00184 }
    00185
    00186 void DepotSortList(VehicleList *list)
    00187 {
    00188   if (list->Length() < 2) return;
    00189   QSortT(list->Begin(), list->Length(), &VehicleNumberSorter);
    00190 }
    00191
    00193 static void DrawVehicleProfitButton(const Vehicle *v, int x, int y)
    00194 {
    00195   SpriteID spr;
    00196
    00197   /* draw profit-based coloured icons */
    00198   if (v->age <= DAYS_IN_YEAR * 2) {
    00199     spr = SPR_PROFIT_NA;
    00200   } else if (v->GetDisplayProfitLastYear() < 0) {
    00201     spr = SPR_PROFIT_NEGATIVE;
    00202   } else if (v->GetDisplayProfitLastYear() < 10000) {
    00203     spr = SPR_PROFIT_SOME;
    00204   } else {
    00205     spr = SPR_PROFIT_LOT;
    00206   }
    00207   DrawSprite(spr, PAL_NONE, x, y);
    00208 }
    00209
    00211 static const uint MAX_REFIT_CYCLE = 256;
    00212
    00220 byte GetBestFittingSubType(Vehicle *v_from, Vehicle *v_for)
    00221 {
    00222   const Engine *e_from = Engine::Get(v_from->engine_type);
    00223   const Engine *e_for  = Engine::Get(v_for->engine_type);
    00224
    00225   /* If one them doesn't carry cargo, there's no need to find a sub type */
    00226   if (!e_from->CanCarryCargo() || !e_for->CanCarryCargo()) return 0;
    00227
    00228   if (!HasBit(e_from->info.callback_mask, CBM_VEHICLE_CARGO_SUFFIX) ||
    00229       !HasBit(e_for->info.callback_mask,  CBM_VEHICLE_CARGO_SUFFIX)) {
    00230     /* One of the engines doesn't have cargo suffixes, i.e. sub types. */
    00231     return 0;
    00232   }
    00233
    00234   /* It has to be possible for v_for to carry the cargo of v_from. */
    00235   if (!HasBit(e_for->info.refit_mask, v_from->cargo_type)) return 0;
    00236
    00237   StringID expected_string = GetCargoSubtypeText(v_from);
    00238
    00239   CargoID old_cargo_type = v_for->cargo_type;
    00240   byte old_cargo_subtype = v_for->cargo_subtype;
    00241   byte ret_refit_cyc = 0;
    00242
    00243   /* Set the 'destination' cargo */
    00244   v_for->cargo_type = v_from->cargo_type;
    00245
    00246   /* Cycle through the refits */
    00247   for (uint refit_cyc = 0; refit_cyc < MAX_REFIT_CYCLE; refit_cyc++) {
    00248     v_for->cargo_subtype = refit_cyc;
    00249
    00250     /* Make sure we don't pick up anything cached. */
    00251     v_for->First()->InvalidateNewGRFCache();
    00252     v_for->InvalidateNewGRFCache();
    00253     uint16 callback = GetVehicleCallback(CBID_VEHICLE_CARGO_SUFFIX, 0, 0, v_for->engine_type, v_for);
    00254
    00255     if (callback == 0xFF) callback = CALLBACK_FAILED;
    00256     if (callback == CALLBACK_FAILED) break;
    00257
    00258     if (GetCargoSubtypeText(v_for) != expected_string) continue;
    00259
    00260     /* We found something matching. */
    00261     ret_refit_cyc = refit_cyc;
    00262     break;
    00263   }
    00264
    00265   /* Reset the vehicle's cargo type */
    00266   v_for->cargo_type    = old_cargo_type;
    00267   v_for->cargo_subtype = old_cargo_subtype;
    00268
    00269   /* Make sure we don't taint the vehicle. */
    00270   v_for->First()->InvalidateNewGRFCache();
    00271   v_for->InvalidateNewGRFCache();
    00272
    00273   return ret_refit_cyc;
    00274 }
    00275
    00283 const Vehicle *GetMostSeverelyBrokenEngine(const Train *v)
    00284 {
    00285   assert(v->IsFrontEngine());
    00286   const Vehicle *w = v;
    00287   byte most_severe_type = 255;
    00288   for (const Vehicle *u = v; u != NULL; u = u->Next()) {
    00289     if (u->breakdown_ctr == 1) {
    00290       if (u->breakdown_type < most_severe_type) {
    00291         most_severe_type = u->breakdown_type;
    00292         w = u;
    00293       } else if (u->breakdown_type == most_severe_type && u->breakdown_severity < w->breakdown_severity) {
    00294         w = u;
    00295       }
    00296     }
    00297   }
    00298   return w;
    00299 }
    00300
    00302 struct RefitOption {
    00303   CargoID cargo;
    00304   byte subtype;
    00305   uint16 value;
    00306   EngineID engine;
    00307
    00313   FORCEINLINE bool operator != (const RefitOption &other) const
    00314   {
    00315     return other.cargo != this->cargo || other.value != this->value;
    00316   }
    00317
    00323   FORCEINLINE bool operator == (const RefitOption &other) const
    00324   {
    00325     return other.cargo == this->cargo && other.value == this->value;
    00326   }
    00327 };
    00328
    00329 typedef SmallVector<RefitOption, 32> SubtypeList;
    00330
    00340 static void DrawVehicleRefitWindow(const SubtypeList list[NUM_CARGO], int sel, uint pos, uint rows, uint delta, const Rect &r)
    00341 {
    00342   uint y = r.top + WD_MATRIX_TOP;
    00343   uint current = 0;
    00344
    00345   /* Draw the list of subtypes for each cargo, and find the selected refit option (by its position). */
    00346   for (uint i = 0; current < pos + rows && i < NUM_CARGO; i++) {
    00347     for (uint j = 0; current < pos + rows && j < list[i].Length(); j++) {
    00348       /* Refit options with a position smaller than pos don't have to be drawn. */
    00349       if (current < pos) {
    00350         current++;
    00351         continue;
    00352       }
    00353
    00354       TextColour colour = (sel == (int)current) ? TC_WHITE : TC_BLACK;
    00355       const RefitOption refit = list[i][j];
    00356       /* Get the cargo name. */
    00357       SetDParam(0, CargoSpec::Get(refit.cargo)->name);
    00358       /* If the callback succeeded, draw the cargo suffix. */
    00359       if (refit.value != CALLBACK_FAILED) {
    00360         SetDParam(1, GetGRFStringID(GetEngineGRFID(refit.engine), 0xD000 + refit.value));
    00361         DrawString(r.left + WD_MATRIX_LEFT, r.right - WD_MATRIX_RIGHT, y, STR_JUST_STRING_SPACE_STRING, colour);
    00362       } else {
    00363         DrawString(r.left + WD_MATRIX_LEFT, r.right - WD_MATRIX_RIGHT, y, STR_JUST_STRING, colour);
    00364       }
    00365
    00366       y += delta;
    00367       current++;
    00368     }
    00369   }
    00370 }
    00371
    00373 enum VehicleRefitWidgets {
    00374   VRW_CAPTION,
    00375   VRW_SHOW_VEHICLEHEADER,
    00376   VRW_VEHICLEHEADER,
    00377   VRW_VEHICLE_SELECT_ALL,
    00378   VRW_VEHICLE_PANEL_DISPLAY,
    00379   VRW_SHOW_HSCROLLBAR,
    00380   VRW_HSCROLLBAR,
    00381   VRW_SELECTHEADER,
    00382   VRW_MATRIX,
    00383   VRW_SCROLLBAR,
    00384   VRW_INFOPANEL,
    00385   VRW_REFITBUTTON,
    00386 };
    00387
    00389 struct RefitWindow : public Window {
    00390   int sel;
    00391   RefitOption *cargo;
    00392   SubtypeList list[NUM_CARGO];
    00393   VehicleOrderID order;
    00394   uint information_width;
    00395   Scrollbar *vscroll;
    00396   Scrollbar *hscroll;
    00397   int vehicle_width;
    00398   int sprite_left;
    00399   int sprite_right;
    00400   uint vehicle_margin;
    00401   int click_x;
    00402   VehicleID selected_vehicle;
    00403   uint8 num_vehicles;
    00404
    00408   void BuildRefitList()
    00409   {
    00410     for (uint i = 0; i < NUM_CARGO; i++) this->list[i].Clear();
    00411     Vehicle *v = Vehicle::Get(this->window_number);
    00412
    00413     /* Check only the selected vehicles. */
    00414     VehicleSet vehicles_to_refit;
    00415     GetVehicleSet(vehicles_to_refit, Vehicle::Get(this->selected_vehicle), this->num_vehicles);
    00416
    00417     do {
    00418       if (v->type == VEH_TRAIN && !vehicles_to_refit.Contains(v->index)) continue;
    00419       const Engine *e = Engine::Get(v->engine_type);
    00420       uint32 cmask = e->info.refit_mask;
    00421       byte callback_mask = e->info.callback_mask;
    00422
    00423       /* Skip this engine if it does not carry anything */
    00424       if (!e->CanCarryCargo()) continue;
    00425
    00426       /* Loop through all cargos in the refit mask */
    00427       int current_index = 0;
    00428       const CargoSpec *cs;
    00429       FOR_ALL_SORTED_CARGOSPECS(cs) {
    00430         CargoID cid = cs->Index();
    00431         /* Skip cargo type if it's not listed */
    00432         if (!HasBit(cmask, cid)) {
    00433           current_index++;
    00434           continue;
    00435         }
    00436
    00437         /* Check the vehicle's callback mask for cargo suffixes */
    00438         if (HasBit(callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) {
    00439           /* Make a note of the original cargo type. It has to be
    00440            * changed to test the cargo & subtype... */
    00441           CargoID temp_cargo = v->cargo_type;
    00442           byte temp_subtype  = v->cargo_subtype;
    00443
    00444           v->cargo_type = cid;
    00445
    00446           for (uint refit_cyc = 0; refit_cyc < MAX_REFIT_CYCLE; refit_cyc++) {
    00447             v->cargo_subtype = refit_cyc;
    00448
    00449             /* Make sure we don't pick up anything cached. */
    00450             v->First()->InvalidateNewGRFCache();
    00451             v->InvalidateNewGRFCache();
    00452             uint16 callback = GetVehicleCallback(CBID_VEHICLE_CARGO_SUFFIX, 0, 0, v->engine_type, v);
    00453
    00454             if (callback == 0xFF) callback = CALLBACK_FAILED;
    00455             if (refit_cyc != 0 && callback == CALLBACK_FAILED) break;
    00456
    00457             RefitOption option;
    00458             option.cargo   = cid;
    00459             option.subtype = refit_cyc;
    00460             option.value   = callback;
    00461             option.engine  = v->engine_type;
    00462             this->list[current_index].Include(option);
    00463           }
    00464
    00465           /* Reset the vehicle's cargo type */
    00466           v->cargo_type    = temp_cargo;
    00467           v->cargo_subtype = temp_subtype;
    00468
    00469           /* And make sure we haven't tainted the cache */
    00470           v->First()->InvalidateNewGRFCache();
    00471           v->InvalidateNewGRFCache();
    00472         } else {
    00473           /* No cargo suffix callback -- use no subtype */
    00474           RefitOption option;
    00475           option.cargo   = cid;
    00476           option.subtype = 0;
    00477           option.value   = CALLBACK_FAILED;
    00478           option.engine  = INVALID_ENGINE;
    00479           this->list[current_index].Include(option);
    00480         }
    00481         current_index++;
    00482       }
    00483     } while (v->IsGroundVehicle() && (v = v->Next()) != NULL);
    00484
    00485     int scroll_size = 0;
    00486     for (uint i = 0; i < NUM_CARGO; i++) {
    00487       scroll_size += (this->list[i].Length());
    00488     }
    00489     this->vscroll->SetCount(scroll_size);
    00490   }
    00491
    00496   RefitOption *GetRefitOption()
    00497   {
    00498     if (this->sel < 0) return NULL;
    00499     int subtype = 0;
    00500     for (uint i = 0; subtype <= this->sel && i < NUM_CARGO; i++) {
    00501       for (uint j = 0; subtype <= this->sel && j < this->list[i].Length(); j++) {
    00502         if (subtype == this->sel) {
    00503           return &this->list[i][j];
    00504         }
    00505         subtype++;
    00506       }
    00507     }
    00508
    00509     return NULL;
    00510   }
    00511
    00512   RefitWindow(const WindowDesc *desc, const Vehicle *v, VehicleOrderID order) : Window()
    00513   {
    00514     this->sel = -1;
    00515     this->CreateNestedTree(desc);
    00516
    00517     this->vscroll = this->GetScrollbar(VRW_SCROLLBAR);
    00518     this->hscroll = (v->IsGroundVehicle() ? this->GetScrollbar(VRW_HSCROLLBAR) : NULL);
    00519     this->GetWidget<NWidgetCore>(VRW_SELECTHEADER)->tool_tip = STR_REFIT_TRAIN_LIST_TOOLTIP + v->type;
    00520     this->GetWidget<NWidgetCore>(VRW_MATRIX)->tool_tip       = STR_REFIT_TRAIN_LIST_TOOLTIP + v->type;
    00521     NWidgetCore *nwi = this->GetWidget<NWidgetCore>(VRW_REFITBUTTON);
    00522     nwi->widget_data = STR_REFIT_TRAIN_REFIT_BUTTON + v->type;
    00523     nwi->tool_tip    = STR_REFIT_TRAIN_REFIT_TOOLTIP + v->type;
    00524     this->GetWidget<NWidgetStacked>(VRW_SHOW_HSCROLLBAR)->SetDisplayedPlane(v->IsGroundVehicle() ? 0 : SZSP_HORIZONTAL);
    00525     this->GetWidget<NWidgetCore>(VRW_VEHICLE_PANEL_DISPLAY)->tool_tip = (v->type == VEH_TRAIN) ? STR_REFIT_SELECT_VEHICLES_TOOLTIP : STR_NULL;
    00526     this->GetWidget<NWidgetStacked>(VRW_SHOW_VEHICLEHEADER)->SetDisplayedPlane(v->type == VEH_TRAIN ? 0 : SZSP_HORIZONTAL);
    00527
    00528     this->FinishInitNested(desc, v->index);
    00529     this->owner = v->owner;
    00530
    00531     this->order = order;
    00532     this->SetWidgetDisabledState(VRW_REFITBUTTON, this->sel == -1);
    00533   }
    00534
    00535   virtual void OnInit()
    00536   {
    00537     if (this->cargo != NULL) {
    00538       /* Store the RefitOption currently in use. */
    00539       RefitOption current_refit_option = *(this->cargo);
    00540
    00541       /* Rebuild the refit list */
    00542       this->BuildRefitList();
    00543       this->sel = -1;
    00544       this->cargo = NULL;
    00545       int current = 0;
    00546       for (uint i = 0; this->cargo == NULL && i < NUM_CARGO; i++) {
    00547         for (uint j = 0; j < list[i].Length(); j++) {
    00548           if (list[i][j] == current_refit_option) {
    00549             this->sel = current;
    00550             this->cargo = &list[i][j];
    00551             this->vscroll->ScrollTowards(current);
    00552             break;
    00553           }
    00554           current++;
    00555         }
    00556       }
    00557
    00558       this->SetWidgetDisabledState(VRW_REFITBUTTON, this->sel == -1);
    00559       /* If the selected refit option was not found, scroll the window to the initial position. */
    00560       if (this->sel == -1) this->vscroll->ScrollTowards(0);
    00561     } else {
    00562       /* Rebuild the refit list */
    00563       this->OnInvalidateData(0);
    00564     }
    00565   }
    00566
    00567   virtual void OnPaint()
    00568   {
    00569     /* Determine amount of items for scroller. */
    00570     if (this->hscroll != NULL) this->hscroll->SetCount(this->vehicle_width);
    00571
    00572     /* Calculate sprite position. */
    00573     NWidgetCore *vehicle_panel_display = this->GetWidget<NWidgetCore>(VRW_VEHICLE_PANEL_DISPLAY);
    00574     int sprite_width = max(0, ((int)vehicle_panel_display->current_x - this->vehicle_width) / 2);
    00575     this->sprite_left = vehicle_panel_display->pos_x;
    00576     this->sprite_right = vehicle_panel_display->pos_x + vehicle_panel_display->current_x - 1;
    00577     if (_current_text_dir == TD_RTL) {
    00578       this->sprite_right -= sprite_width;
    00579       this->vehicle_margin = vehicle_panel_display->current_x - sprite_right;
    00580     } else {
    00581       this->sprite_left += sprite_width;
    00582       this->vehicle_margin = sprite_left;
    00583     }
    00584
    00585     this->DrawWidgets();
    00586   }
    00587
    00588   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    00589   {
    00590     switch (widget) {
    00591       case VRW_MATRIX:
    00592         resize->height = WD_MATRIX_TOP + FONT_HEIGHT_NORMAL + WD_MATRIX_BOTTOM;
    00593         size->height = resize->height * 8;
    00594         break;
    00595
    00596       case VRW_VEHICLE_PANEL_DISPLAY:
    00597         size->height = GetVehicleHeight(Vehicle::Get(this->window_number)->type);
    00598         break;
    00599
    00600       case VRW_INFOPANEL:
    00601         size->width = WD_FRAMERECT_LEFT + this->information_width + WD_FRAMERECT_RIGHT;
    00602         break;
    00603     }
    00604   }
    00605
    00606   virtual void SetStringParameters(int widget) const
    00607   {
    00608     if (widget == VRW_CAPTION) SetDParam(0, Vehicle::Get(this->window_number)->index);
    00609   }
    00610
    00617   StringID GetCapacityString(RefitOption *option) const
    00618   {
    00619     assert(_current_company == _local_company);
    00620     Vehicle *v = Vehicle::Get(this->window_number);
    00621     CommandCost cost = DoCommand(v->tile, this->selected_vehicle, option->cargo | option->subtype << 8 |
    00622         this->num_vehicles << 16, DC_QUERY_COST, GetCmdRefitVeh(v->type));
    00623
    00624     if (cost.Failed()) return INVALID_STRING_ID;
    00625
    00626     SetDParam(0, option->cargo);
    00627     SetDParam(1, _returned_refit_capacity);
    00628
    00629     if (_returned_mail_refit_capacity > 0) {
    00630       SetDParam(2, CT_MAIL);
    00631       SetDParam(3, _returned_mail_refit_capacity);
    00632       SetDParam(4, cost.GetCost());
    00633       return STR_REFIT_NEW_CAPACITY_COST_OF_AIRCRAFT_REFIT;
    00634     } else {
    00635       SetDParam(2, cost.GetCost());
    00636       return STR_REFIT_NEW_CAPACITY_COST_OF_REFIT;
    00637     }
    00638   }
    00639
    00640   virtual void DrawWidget(const Rect &r, int widget) const
    00641   {
    00642     switch (widget) {
    00643       case VRW_VEHICLE_PANEL_DISPLAY: {
    00644         Vehicle *v = Vehicle::Get(this->window_number);
    00645         DrawVehicleImage(v, this->sprite_left + WD_FRAMERECT_LEFT, this->sprite_right - WD_FRAMERECT_RIGHT,
    00646           r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, this->hscroll != NULL ? this->hscroll->GetPosition() : 0);
    00647
    00648         /* Highlight selected vehicles. */
    00649         if (this->order != INVALID_VEH_ORDER_ID) break;
    00650         int x = 0;
    00651         switch (v->type) {
    00652           case VEH_TRAIN: {
    00653             VehicleSet vehicles_to_refit;
    00654             GetVehicleSet(vehicles_to_refit, Vehicle::Get(this->selected_vehicle), this->num_vehicles);
    00655
    00656             int left = INT32_MIN;
    00657             int width = 0;
    00658
    00659             for (Train *u = Train::From(v); u != NULL; u = u->Next()) {
    00660               /* Start checking. */
    00661               if (vehicles_to_refit.Contains(u->index) && left == INT32_MIN) {
    00662                 left = x - this->hscroll->GetPosition() + r.left + this->vehicle_margin;
    00663                 width = 0;
    00664               }
    00665
    00666               /* Draw a selection. */
    00667               if ((!vehicles_to_refit.Contains(u->index) || u->Next() == NULL) && left != INT32_MIN) {
    00668                 if (u->Next() == NULL && vehicles_to_refit.Contains(u->index)) {
    00669                   int current_width = u->GetDisplayImageWidth();
    00670                   width += current_width;
    00671                   x += current_width;
    00672                 }
    00673
    00674                 int right = Clamp(left + width, 0, r.right);
    00675                 left = max(0, left);
    00676
    00677                 if (_current_text_dir == TD_RTL) {
    00678                   right = this->GetWidget<NWidgetCore>(VRW_VEHICLE_PANEL_DISPLAY)->current_x - left;
    00679                   left = right - width;
    00680                 }
    00681
    00682                 if (left != right) {
    00683                   DrawFrameRect(left, r.top + WD_FRAMERECT_TOP, right, r.top + WD_FRAMERECT_TOP + 13, COLOUR_WHITE, FR_BORDERONLY);
    00684                 }
    00685
    00686                 left = INT32_MIN;
    00687               }
    00688
    00689               int current_width = u->GetDisplayImageWidth();
    00690               width += current_width;
    00691               x += current_width;
    00692             }
    00693             break;
    00694           }
    00695
    00696           default: break;
    00697         }
    00698         break;
    00699       }
    00700
    00701       case VRW_MATRIX:
    00702         DrawVehicleRefitWindow(this->list, this->sel, this->vscroll->GetPosition(), this->vscroll->GetCapacity(), this->resize.step_height, r);
    00703         break;
    00704
    00705       case VRW_INFOPANEL:
    00706         if (this->cargo != NULL) {
    00707           StringID string = this->GetCapacityString(this->cargo);
    00708           if (string != INVALID_STRING_ID) {
    00709             DrawStringMultiLine(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT,
    00710                 r.top + WD_FRAMERECT_TOP, r.bottom - WD_FRAMERECT_BOTTOM, string);
    00711           }
    00712         }
    00713         break;
    00714     }
    00715   }
    00716
    00722   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
    00723   {
    00724     switch (data) {
    00725       case -666: // Autoreplace replaced the vehicle; selected_vehicle became invalid.
    00726       case 0: { // The consist has changed; rebuild the entire list.
    00727         /* Clear the selection. */
    00728         Vehicle *v = Vehicle::Get(this->window_number);
    00729         this->selected_vehicle = v->index;
    00730         this->num_vehicles = UINT8_MAX;
    00731         /* FALL THROUGH */
    00732       }
    00733
    00734       case 2: { // The vehicle selection has changed; rebuild the entire list.
    00735         if (!gui_scope) break;
    00736         this->BuildRefitList();
    00737
    00738         /* The vehicle width has changed too. */
    00739         this->vehicle_width = GetVehicleWidth(Vehicle::Get(this->window_number));
    00740         uint max_width = 0;
    00741
    00742         /* Check the width of all cargo information strings. */
    00743         for (uint i = 0; i < NUM_CARGO; i++) {
    00744           for (uint j = 0; j < this->list[i].Length(); j++) {
    00745             StringID string = this->GetCapacityString(&list[i][j]);
    00746             if (string != INVALID_STRING_ID) {
    00747               Dimension dim = GetStringBoundingBox(string);
    00748               max_width = max(dim.width, max_width);
    00749             }
    00750           }
    00751         }
    00752
    00753         if (this->information_width < max_width) {
    00754           this->information_width = max_width;
    00755           this->ReInit();
    00756         }
    00757         /* FALL THROUGH */
    00758       }
    00759
    00760       case 1: // A new cargo has been selected.
    00761         if (!gui_scope) break;
    00762         this->cargo = GetRefitOption();
    00763         break;
    00764     }
    00765   }
    00766
    00767   int GetClickPosition(int click_x)
    00768   {
    00769     const NWidgetCore *matrix_widget = this->GetWidget<NWidgetCore>(VRW_VEHICLE_PANEL_DISPLAY);
    00770     if (_current_text_dir == TD_RTL) click_x = matrix_widget->current_x - click_x;
    00771     click_x -= this->vehicle_margin;
    00772     if (this->hscroll != NULL) click_x += this->hscroll->GetPosition();
    00773
    00774     return click_x;
    00775   }
    00776
    00777   void SetSelectedVehicles(int drag_x)
    00778   {
    00779     drag_x = GetClickPosition(drag_x);
    00780
    00781     int left_x  = min(this->click_x, drag_x);
    00782     int right_x = max(this->click_x, drag_x);
    00783     this->num_vehicles = 0;
    00784
    00785     Vehicle *v = Vehicle::Get(this->window_number);
    00786     /* Find the vehicle part that was clicked. */
    00787     switch (v->type) {
    00788       case VEH_TRAIN: {
    00789         /* Don't select anything if we are not clicking in the vehicle. */
    00790         if (left_x >= 0) {
    00791           const Train *u = Train::From(v);
    00792           bool start_counting = false;
    00793           for (; u != NULL; u = u->Next()) {
    00794             int current_width = u->GetDisplayImageWidth();
    00795             left_x  -= current_width;
    00796             right_x -= current_width;
    00797
    00798             if (left_x < 0 && !start_counting) {
    00799               this->selected_vehicle = u->index;
    00800               start_counting = true;
    00801
    00802               /* Count the first vehicle, even if articulated part */
    00803               this->num_vehicles++;
    00804             } else if (start_counting && !u->IsArticulatedPart()) {
    00805               /* Do not count articulated parts */
    00806               this->num_vehicles++;
    00807             }
    00808
    00809             if (right_x < 0) break;
    00810           }
    00811         }
    00812
    00813         /* If the selection is not correct, clear it. */
    00814         if (this->num_vehicles != 0) {
    00815           if (_ctrl_pressed) this->num_vehicles = UINT8_MAX;
    00816           break;
    00817         }
    00818         /* FALL THROUGH */
    00819       }
    00820
    00821       default:
    00822         /* Clear the selection. */
    00823         this->selected_vehicle = v->index;
    00824         this->num_vehicles = UINT8_MAX;
    00825         break;
    00826     }
    00827   }
    00828
    00829   virtual void OnClick(Point pt, int widget, int click_count)
    00830   {
    00831     switch (widget) {
    00832       case VRW_VEHICLE_SELECT_ALL: {
    00833         /* Clear the selection. */
    00834         Vehicle *v = Vehicle::Get(this->window_number);
    00835         this->selected_vehicle = v->index;
    00836         this->num_vehicles = UINT8_MAX;
    00837         this->SetWidgetDirty(VRW_VEHICLE_PANEL_DISPLAY);
    00838         break;
    00839       }
    00840
    00841       case VRW_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
    00842         if (this->order != INVALID_VEH_ORDER_ID) break;
    00843         NWidgetBase *nwi = this->GetWidget<NWidgetBase>(VRW_VEHICLE_PANEL_DISPLAY);
    00844         this->click_x = GetClickPosition(pt.x - nwi->pos_x);
    00845         this->SetSelectedVehicles(pt.x - nwi->pos_x);
    00846         this->SetWidgetDirty(VRW_VEHICLE_PANEL_DISPLAY);
    00847         if (!_ctrl_pressed) {
    00848           SetObjectToPlaceWnd(SPR_CURSOR_MOUSE, PAL_NONE, HT_DRAG, this);
    00849         } else {
    00850           /* The vehicle selection has changed. */
    00851           this->InvalidateData(2);
    00852         }
    00853         break;
    00854       }
    00855
    00856       case VRW_MATRIX: { // listbox
    00857         this->sel = this->vscroll->GetScrolledRowFromWidget(pt.y, this, VRW_MATRIX);
    00858         if (this->sel == INT_MAX) this->sel = -1;
    00859         this->SetWidgetDisabledState(VRW_REFITBUTTON, this->sel == -1);
    00860         this->InvalidateData(1);
    00861
    00862         if (click_count == 1) break;
    00863         /* FALL THROUGH */
    00864       }
    00865
    00866       case VRW_REFITBUTTON: // refit button
    00867         if (this->cargo != NULL) {
    00868           const Vehicle *v = Vehicle::Get(this->window_number);
    00869
    00870           if (this->order == INVALID_VEH_ORDER_ID) {
    00871             bool delete_window = this->selected_vehicle == v->index && this->num_vehicles == UINT8_MAX;
    00872             if (DoCommandP(v->tile, this->selected_vehicle, this->cargo->cargo | this->cargo->subtype << 8 | this->num_vehicles << 16, GetCmdRefitVeh(v)) && delete_window) delete this;
    00873           } else {
    00874             if (DoCommandP(v->tile, v->index, this->cargo->cargo | this->cargo->subtype << 8 | this->order << 16, CMD_ORDER_REFIT)) delete this;
    00875           }
    00876         }
    00877         break;
    00878     }
    00879   }
    00880
    00881   virtual void OnMouseDrag(Point pt, int widget)
    00882   {
    00883     switch (widget) {
    00884       case VRW_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
    00885         if (this->order != INVALID_VEH_ORDER_ID) break;
    00886         NWidgetBase *nwi = this->GetWidget<NWidgetBase>(VRW_VEHICLE_PANEL_DISPLAY);
    00887         this->SetSelectedVehicles(pt.x - nwi->pos_x);
    00888         this->SetWidgetDirty(VRW_VEHICLE_PANEL_DISPLAY);
    00889         break;
    00890       }
    00891     }
    00892   }
    00893
    00894   virtual void OnDragDrop(Point pt, int widget)
    00895   {
    00896     switch (widget) {
    00897       case VRW_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
    00898         if (this->order != INVALID_VEH_ORDER_ID) break;
    00899         NWidgetBase *nwi = this->GetWidget<NWidgetBase>(VRW_VEHICLE_PANEL_DISPLAY);
    00900         this->SetSelectedVehicles(pt.x - nwi->pos_x);
    00901         this->InvalidateData(2);
    00902         break;
    00903       }
    00904     }
    00905   }
    00906
    00907   virtual void OnResize()
    00908   {
    00909     this->vehicle_width = GetVehicleWidth(Vehicle::Get(this->window_number));
    00910     this->vscroll->SetCapacityFromWidget(this, VRW_MATRIX);
    00911     if (this->hscroll != NULL) this->hscroll->SetCapacityFromWidget(this, VRW_VEHICLE_PANEL_DISPLAY);
    00912     this->GetWidget<NWidgetCore>(VRW_MATRIX)->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
    00913   }
    00914 };
    00915
    00916 static const NWidgetPart _nested_vehicle_refit_widgets[] = {
    00917   NWidget(NWID_HORIZONTAL),
    00918     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
    00919     NWidget(WWT_CAPTION, COLOUR_GREY, VRW_CAPTION), SetDataTip(STR_REFIT_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
    00920   EndContainer(),
    00921   NWidget(NWID_SELECTION, INVALID_COLOUR, VRW_SHOW_VEHICLEHEADER),
    00922     NWidget(NWID_HORIZONTAL),
    00923       NWidget(WWT_TEXTBTN, COLOUR_GREY, VRW_VEHICLEHEADER), SetDataTip(STR_REFIT_VEHICLE_SELECTION_TITLE, STR_NULL), SetFill(1, 0), SetResize(1, 0),
    00924       NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, VRW_VEHICLE_SELECT_ALL), SetDataTip(STR_REFIT_VEHICLE_SELECT_ALL, STR_REFIT_VEHICLE_SELECT_ALL_TOOLTIP),
    00925     EndContainer(),
    00926   EndContainer(),
    00927   /* Vehicle display + scrollbar. */
    00928   NWidget(NWID_VERTICAL),
    00929     NWidget(WWT_PANEL, COLOUR_GREY, VRW_VEHICLE_PANEL_DISPLAY), SetMinimalSize(228, 14), SetResize(1, 0), SetScrollbar(VRW_HSCROLLBAR), EndContainer(),
    00930     NWidget(NWID_SELECTION, INVALID_COLOUR, VRW_SHOW_HSCROLLBAR),
    00931       NWidget(NWID_HSCROLLBAR, COLOUR_GREY, VRW_HSCROLLBAR),
    00932     EndContainer(),
    00933   EndContainer(),
    00934   NWidget(WWT_TEXTBTN, COLOUR_GREY, VRW_SELECTHEADER), SetDataTip(STR_REFIT_TITLE, STR_NULL), SetResize(1, 0),
    00935   /* Matrix + scrollbar. */
    00936   NWidget(NWID_HORIZONTAL),
    00937     NWidget(WWT_MATRIX, COLOUR_GREY, VRW_MATRIX), SetMinimalSize(228, 112), SetResize(1, 14), SetFill(1, 1), SetDataTip(0x801, STR_NULL), SetScrollbar(VRW_SCROLLBAR),
    00938     NWidget(NWID_VSCROLLBAR, COLOUR_GREY, VRW_SCROLLBAR),
    00939   EndContainer(),
    00940   NWidget(WWT_PANEL, COLOUR_GREY, VRW_INFOPANEL), SetMinimalTextLines(2, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM), SetResize(1, 0), EndContainer(),
    00941   NWidget(NWID_HORIZONTAL),
    00942     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, VRW_REFITBUTTON), SetFill(1, 0), SetResize(1, 0),
    00943     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
    00944   EndContainer(),
    00945 };
    00946
    00947 static const WindowDesc _vehicle_refit_desc(
    00948   WDP_AUTO, 240, 174,
    00949   WC_VEHICLE_REFIT, WC_VEHICLE_VIEW,
    00950   WDF_UNCLICK_BUTTONS | WDF_CONSTRUCTION,
    00951   _nested_vehicle_refit_widgets, lengthof(_nested_vehicle_refit_widgets)
    00952 );
    00953
    00960 void ShowVehicleRefitWindow(const Vehicle *v, VehicleOrderID order, Window *parent)
    00961 {
    00962   DeleteWindowById(WC_VEHICLE_REFIT, v->index);
    00963   RefitWindow *w = new RefitWindow(&_vehicle_refit_desc, v, order);
    00964   w->parent = parent;
    00965 }
    00966
    00968 uint ShowRefitOptionsList(int left, int right, int y, EngineID engine)
    00969 {
    00970   /* List of cargo types of this engine */
    00971   uint32 cmask = GetUnionOfArticulatedRefitMasks(engine, false);
    00972   /* List of cargo types available in this climate */
    00973   uint32 lmask = _cargo_mask;
    00974   char string[512];
    00975   char *b = string;
    00976
    00977   /* Draw nothing if the engine is not refittable */
    00978   if (HasAtMostOneBit(cmask)) return y;
    00979
    00980   b = InlineString(b, STR_PURCHASE_INFO_REFITTABLE_TO);
    00981
    00982   if (cmask == lmask) {
    00983     /* Engine can be refitted to all types in this climate */
    00984     b = InlineString(b, STR_PURCHASE_INFO_ALL_TYPES);
    00985   } else {
    00986     /* Check if we are able to refit to more cargo types and unable to. If
    00987      * so, invert the cargo types to list those that we can't refit to. */
    00988     if (CountBits(cmask ^ lmask) < CountBits(cmask) && CountBits(cmask ^ lmask) <= 7) {
    00989       cmask ^= lmask;
    00990       b = InlineString(b, STR_PURCHASE_INFO_ALL_BUT);
    00991     }
    00992
    00993     bool first = true;
    00994
    00995     /* Add each cargo type to the list */
    00996     const CargoSpec *cs;
    00997     FOR_ALL_SORTED_CARGOSPECS(cs) {
    00998       if (!HasBit(cmask, cs->Index())) continue;
    00999
    01000       if (b >= lastof(string) - (2 + 2 * 4)) break; // ", " and two calls to Utf8Encode()
    01001
    01002       if (!first) b = strecpy(b, ", ", lastof(string));
    01003       first = false;
    01004
    01005       b = InlineString(b, cs->name);
    01006     }
    01007   }
    01008
    01009   /* Terminate and display the completed string */
    01010   *b = '\0';
    01011
    01012   /* Make sure we detect any buffer overflow */
    01013   assert(b < endof(string));
    01014
    01015   SetDParamStr(0, string);
    01016   return DrawStringMultiLine(left, right, y, INT32_MAX, STR_JUST_RAW_STRING);
    01017 }
    01018
    01020 StringID GetCargoSubtypeText(const Vehicle *v)
    01021 {
    01022   if (HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) {
    01023     uint16 cb = GetVehicleCallback(CBID_VEHICLE_CARGO_SUFFIX, 0, 0, v->engine_type, v);
    01024     if (cb != CALLBACK_FAILED) {
    01025       return GetGRFStringID(GetEngineGRFID(v->engine_type), 0xD000 + cb);
    01026     }
    01027   }
    01028   return STR_EMPTY;
    01029 }
    01030
    01032 static int CDECL VehicleNumberSorter(const Vehicle * const *a, const Vehicle * const *b)
    01033 {
    01034   return (*a)->unitnumber - (*b)->unitnumber;
    01035 }
    01036
    01038 static int CDECL VehicleNameSorter(const Vehicle * const *a, const Vehicle * const *b)
    01039 {
    01040   static char last_name[2][64];
    01041
    01042   if (*a != _last_vehicle[0]) {
    01043     _last_vehicle[0] = *a;
    01044     SetDParam(0, (*a)->index);
    01045     GetString(last_name[0], STR_VEHICLE_NAME, lastof(last_name[0]));
    01046   }
    01047
    01048   if (*b != _last_vehicle[1]) {
    01049     _last_vehicle[1] = *b;
    01050     SetDParam(0, (*b)->index);
    01051     GetString(last_name[1], STR_VEHICLE_NAME, lastof(last_name[1]));
    01052   }
    01053
    01054   int r = strnatcmp(last_name[0], last_name[1]); // Sort by name (natural sorting).
    01055   return (r != 0) ? r : VehicleNumberSorter(a, b);
    01056 }
    01057
    01059 static int CDECL VehicleAgeSorter(const Vehicle * const *a, const Vehicle * const *b)
    01060 {
    01061   int r = (*a)->age - (*b)->age;
    01062   return (r != 0) ? r : VehicleNumberSorter(a, b);
    01063 }
    01064
    01066 static int CDECL VehicleProfitThisYearSorter(const Vehicle * const *a, const Vehicle * const *b)
    01067 {
    01068   int r = ClampToI32((*a)->GetDisplayProfitThisYear() - (*b)->GetDisplayProfitThisYear());
    01069   return (r != 0) ? r : VehicleNumberSorter(a, b);
    01070 }
    01071
    01073 static int CDECL VehicleProfitLastYearSorter(const Vehicle * const *a, const Vehicle * const *b)
    01074 {
    01075   int r = ClampToI32((*a)->GetDisplayProfitLastYear() - (*b)->GetDisplayProfitLastYear());
    01076   return (r != 0) ? r : VehicleNumberSorter(a, b);
    01077 }
    01078
    01080 static int CDECL VehicleCargoSorter(const Vehicle * const *a, const Vehicle * const *b)
    01081 {
    01082   const Vehicle *v;
    01083   CargoArray diff;
    01084
    01085   /* Append the cargo of the connected weagons */
    01086   for (v = *a; v != NULL; v = v->Next()) diff[v->cargo_type] += v->cargo_cap;
    01087   for (v = *b; v != NULL; v = v->Next()) diff[v->cargo_type] -= v->cargo_cap;
    01088
    01089   int r = 0;
    01090   for (CargoID i = 0; i < NUM_CARGO; i++) {
    01091     r = diff[i];
    01092     if (r != 0) break;
    01093   }
    01094
    01095   return (r != 0) ? r : VehicleNumberSorter(a, b);
    01096 }
    01097
    01099 static int CDECL VehicleReliabilitySorter(const Vehicle * const *a, const Vehicle * const *b)
    01100 {
    01101   int r = (*a)->reliability - (*b)->reliability;
    01102   return (r != 0) ? r : VehicleNumberSorter(a, b);
    01103 }
    01104
    01106 static int CDECL VehicleMaxSpeedSorter(const Vehicle * const *a, const Vehicle * const *b)
    01107 {
    01108   int r = (*a)->vcache.cached_max_speed - (*b)->vcache.cached_max_speed;
    01109   return (r != 0) ? r : VehicleNumberSorter(a, b);
    01110 }
    01111
    01113 static int CDECL VehicleModelSorter(const Vehicle * const *a, const Vehicle * const *b)
    01114 {
    01115   int r = (*a)->engine_type - (*b)->engine_type;
    01116   return (r != 0) ? r : VehicleNumberSorter(a, b);
    01117 }
    01118
    01120 static int CDECL VehicleValueSorter(const Vehicle * const *a, const Vehicle * const *b)
    01121 {
    01122   const Vehicle *u;
    01123   Money diff = 0;
    01124
    01125   for (u = *a; u != NULL; u = u->Next()) diff += u->value;
    01126   for (u = *b; u != NULL; u = u->Next()) diff -= u->value;
    01127
    01128   int r = ClampToI32(diff);
    01129   return (r != 0) ? r : VehicleNumberSorter(a, b);
    01130 }
    01131
    01133 static int CDECL VehicleLengthSorter(const Vehicle * const *a, const Vehicle * const *b)
    01134 {
    01135   int r = (*a)->GetGroundVehicleCache()->cached_total_length - (*b)->GetGroundVehicleCache()->cached_total_length;
    01136   return (r != 0) ? r : VehicleNumberSorter(a, b);
    01137 }
    01138
    01140 static int CDECL VehicleTimeToLiveSorter(const Vehicle * const *a, const Vehicle * const *b)
    01141 {
    01142   int r = ClampToI32(((*a)->max_age - (*a)->age) - ((*b)->max_age - (*b)->age));
    01143   return (r != 0) ? r : VehicleNumberSorter(a, b);
    01144 }
    01145
    01147 static int CDECL VehicleTimetableDelaySorter(const Vehicle * const *a, const Vehicle * const *b)
    01148 {
    01149   int r = (*a)->lateness_counter - (*b)->lateness_counter;
    01150   return (r != 0) ? r : VehicleNumberSorter(a, b);
    01151 }
    01152
    01153 void InitializeGUI()
    01154 {
    01155   MemSetT(&_sorting, 0);
    01156 }
    01157
    01164 static inline void ChangeVehicleWindow(WindowClass window_class, VehicleID from_index, VehicleID to_index)
    01165 {
    01166   Window *w = FindWindowById(window_class, from_index);
    01167   if (w != NULL) {
    01168     /* Update window_number */
    01169     w->window_number = to_index;
    01170     if (w->viewport != NULL) w->viewport->follow_vehicle = to_index;
    01171
    01172     /* Update vehicle drag data */
    01173     if (_thd.window_class == window_class && _thd.window_number == (WindowNumber)from_index) {
    01174       _thd.window_number = to_index;
    01175     }
    01176
    01177     /* Notify the window. */
    01178     w->InvalidateData(-666, false);
    01179   }
    01180 }
    01181
    01187 void ChangeVehicleViewWindow(VehicleID from_index, VehicleID to_index)
    01188 {
    01189   ChangeVehicleWindow(WC_VEHICLE_VIEW,      from_index, to_index);
    01190   ChangeVehicleWindow(WC_VEHICLE_ORDERS,    from_index, to_index);
    01191   ChangeVehicleWindow(WC_VEHICLE_REFIT,     from_index, to_index);
    01192   ChangeVehicleWindow(WC_VEHICLE_DETAILS,   from_index, to_index);
    01193   ChangeVehicleWindow(WC_VEHICLE_TIMETABLE, from_index, to_index);
    01194 }
    01195
    01196 enum VehicleListWindowWidgets {
    01197   VLW_WIDGET_CAPTION,
    01198   VLW_WIDGET_SORT_ORDER,
    01199   VLW_WIDGET_SORT_BY_PULLDOWN,
    01200   VLW_WIDGET_LIST,
    01201   VLW_WIDGET_SCROLLBAR,
    01202   VLW_WIDGET_HIDE_BUTTONS,
    01203   VLW_WIDGET_AVAILABLE_VEHICLES,
    01204   VLW_WIDGET_MANAGE_VEHICLES_DROPDOWN,
    01205   VLW_WIDGET_STOP_ALL,
    01206   VLW_WIDGET_START_ALL,
    01207 };
    01208
    01209 static const NWidgetPart _nested_vehicle_list[] = {
    01210   NWidget(NWID_HORIZONTAL),
    01211     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
    01212     NWidget(WWT_CAPTION, COLOUR_GREY, VLW_WIDGET_CAPTION),
    01213     NWidget(WWT_SHADEBOX, COLOUR_GREY),
    01214     NWidget(WWT_STICKYBOX, COLOUR_GREY),
    01215   EndContainer(),
    01216
    01217   NWidget(NWID_HORIZONTAL),
    01218     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, VLW_WIDGET_SORT_ORDER), SetMinimalSize(81, 12), SetFill(0, 1), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
    01219     NWidget(WWT_DROPDOWN, COLOUR_GREY, VLW_WIDGET_SORT_BY_PULLDOWN), SetMinimalSize(167, 12), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
    01220     NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(12, 12), SetFill(1, 1), SetResize(1, 0),
    01221     EndContainer(),
    01222   EndContainer(),
    01223
    01224   NWidget(NWID_HORIZONTAL),
    01225     NWidget(WWT_MATRIX, COLOUR_GREY, VLW_WIDGET_LIST), SetMinimalSize(248, 0), SetFill(1, 0), SetResize(1, 1), SetScrollbar(VLW_WIDGET_SCROLLBAR),
    01226     NWidget(NWID_VSCROLLBAR, COLOUR_GREY, VLW_WIDGET_SCROLLBAR),
    01227   EndContainer(),
    01228
    01229   NWidget(NWID_HORIZONTAL),
    01230     NWidget(NWID_SELECTION, INVALID_COLOUR, VLW_WIDGET_HIDE_BUTTONS),
    01231       NWidget(NWID_HORIZONTAL),
    01232         NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, VLW_WIDGET_AVAILABLE_VEHICLES), SetMinimalSize(106, 12), SetFill(0, 1),
    01233                 SetDataTip(STR_BLACK_STRING, STR_VEHICLE_LIST_AVAILABLE_ENGINES_TOOLTIP),
    01234         NWidget(WWT_DROPDOWN, COLOUR_GREY, VLW_WIDGET_MANAGE_VEHICLES_DROPDOWN), SetMinimalSize(118, 12), SetFill(0, 1),
    01235                 SetDataTip(STR_VEHICLE_LIST_MANAGE_LIST, STR_VEHICLE_LIST_MANAGE_LIST_TOOLTIP),
    01236         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VLW_WIDGET_STOP_ALL), SetMinimalSize(12, 12), SetFill(0, 1),
    01237                 SetDataTip(SPR_FLAG_VEH_STOPPED, STR_VEHICLE_LIST_MASS_STOP_LIST_TOOLTIP),
    01238         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VLW_WIDGET_START_ALL), SetMinimalSize(12, 12), SetFill(0, 1),
    01239                 SetDataTip(SPR_FLAG_VEH_RUNNING, STR_VEHICLE_LIST_MASS_START_LIST_TOOLTIP),
    01240         NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(0, 12), SetResize(1, 0), SetFill(1, 1), EndContainer(),
    01241       EndContainer(),
    01242       /* Widget to be shown for other companies hiding the previous 5 widgets. */
    01243       NWidget(WWT_PANEL, COLOUR_GREY), SetFill(1, 1), SetResize(1, 0), EndContainer(),
    01244     EndContainer(),
    01245     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
    01246   EndContainer(),
    01247 };
    01248
    01249 static void DrawSmallOrderList(const Vehicle *v, int left, int right, int y, VehicleOrderID start = 0)
    01250 {
    01251   const Order *order = v->GetOrder(start);
    01252   if (order == NULL) return;
    01253
    01254   int i = 0;
    01255   VehicleOrderID oid = start;
    01256
    01257   do {
    01258     if (oid == v->cur_real_order_index) DrawString(left, right, y, STR_TINY_RIGHT_ARROW, TC_BLACK);
    01259
    01260     if (order->IsType(OT_GOTO_STATION)) {
    01261       SetDParam(0, order->GetDestination());
    01262       DrawString(left + 6, right - 6, y, STR_TINY_BLACK_STATION);
    01263
    01264       y += FONT_HEIGHT_SMALL;
    01265       if (++i == 4) break;
    01266     }
    01267
    01268     oid++;
    01269     order = order->next;
    01270     if (order == NULL) {
    01271       order = v->orders.list->GetFirstOrder();
    01272       oid = 0;
    01273     }
    01274   } while (oid != start);
    01275 }
    01276
    01286 void DrawVehicleImage(const Vehicle *v, int left, int right, int y, VehicleID selection, int skip)
    01287 {
    01288   switch (v->type) {
    01289     case VEH_TRAIN:    DrawTrainImage(Train::From(v), left, right, y, selection, skip); break;
    01290     case VEH_ROAD:     DrawRoadVehImage(v, left, right, y, selection, skip);  break;
    01291     case VEH_SHIP:     DrawShipImage(v, left, right, y, selection);     break;
    01292     case VEH_AIRCRAFT: DrawAircraftImage(v, left, right, y, selection); break;
    01293     default: NOT_REACHED();
    01294   }
    01295 }
    01296
    01303 uint GetVehicleListHeight(VehicleType type, uint divisor)
    01304 {
    01305   /* Name + vehicle + profit */
    01306   uint base = GetVehicleHeight(type) + 2 * FONT_HEIGHT_SMALL;
    01307   /* Drawing of the 4 small orders + profit*/
    01308   if (type >= VEH_SHIP) base = max(base, 5U * FONT_HEIGHT_SMALL);
    01309
    01310   if (divisor == 1) return base;
    01311
    01312   /* Make sure the height is dividable by divisor */
    01313   uint rem = base % divisor;
    01314   return base + (rem == 0 ? 0 : divisor - rem);
    01315 }
    01316
    01323 void BaseVehicleListWindow::DrawVehicleListItems(VehicleID selected_vehicle, int line_height, const Rect &r) const
    01324 {
    01325   int left = r.left + WD_MATRIX_LEFT;
    01326   int right = r.right - WD_MATRIX_RIGHT;
    01327   int width = right - left;
    01328   bool rtl = _current_text_dir == TD_RTL;
    01329
    01330   int text_offset = GetDigitWidth() * this->unitnumber_digits + WD_FRAMERECT_RIGHT;
    01331   int text_left  = left  + (rtl ?           0 : text_offset);
    01332   int text_right = right - (rtl ? text_offset :           0);
    01333
    01334   bool show_orderlist = this->vli.vtype >= VEH_SHIP;
    01335   int orderlist_left  = left  + (rtl ? 0 : max(100 + text_offset, width / 2));
    01336   int orderlist_right = right - (rtl ? max(100 + text_offset, width / 2) : 0);
    01337
    01338   int image_left  = (rtl && show_orderlist) ? orderlist_right : text_left;
    01339   int image_right = (!rtl && show_orderlist) ? orderlist_left : text_right;
    01340
    01341   int vehicle_button_x = rtl ? right - GetSpriteSize(SPR_PROFIT_LOT).width : left;
    01342
    01343   int y = r.top;
    01344   uint max = min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->vehicles.Length());
    01345   for (uint i = this->vscroll->GetPosition(); i < max; ++i) {
    01346     const Vehicle *v = this->vehicles[i];
    01347     StringID str;
    01348
    01349     SetDParam(0, v->GetDisplayProfitThisYear());
    01350     SetDParam(1, v->GetDisplayProfitLastYear());
    01351
    01352     DrawVehicleImage(v, image_left, image_right, y + FONT_HEIGHT_SMALL - 1, selected_vehicle, 0);
    01353     DrawString(text_left, text_right, y + line_height - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1, STR_VEHICLE_LIST_PROFIT_THIS_YEAR_LAST_YEAR);
    01354
    01355     if (v->name != NULL) {
    01356       /* The vehicle got a name so we will print it */
    01357       SetDParam(0, v->index);
    01358       DrawString(text_left, text_right, y, STR_TINY_BLACK_VEHICLE);
    01359     } else if (v->group_id != DEFAULT_GROUP) {
    01360       /* The vehicle has no name, but is member of a group, so print group name */
    01361       SetDParam(0, v->group_id);
    01362       DrawString(text_left, text_right, y, STR_TINY_GROUP, TC_BLACK);
    01363     }
    01364
    01365     if (show_orderlist) DrawSmallOrderList(v, orderlist_left, orderlist_right, y, v->cur_real_order_index);
    01366
    01367     if (v->IsInDepot()) {
    01368       str = STR_BLUE_COMMA;
    01369     } else {
    01370       str = (v->age > v->max_age - DAYS_IN_LEAP_YEAR) ? STR_RED_COMMA : STR_BLACK_COMMA;
    01371     }
    01372
    01373     SetDParam(0, v->unitnumber);
    01374     DrawString(left, right, y + 2, str);
    01375
    01376     DrawVehicleProfitButton(v, vehicle_button_x, y + FONT_HEIGHT_NORMAL + 3);
    01377
    01378     y += line_height;
    01379   }
    01380 }
    01381
    01391 struct VehicleListWindow : public BaseVehicleListWindow {
    01392 private:
    01394   enum ButtonPlanes {
    01395     BP_SHOW_BUTTONS,
    01396     BP_HIDE_BUTTONS,
    01397   };
    01398
    01399 public:
    01400   VehicleListWindow(const WindowDesc *desc, WindowNumber window_number) : BaseVehicleListWindow(window_number)
    01401   {
    01402     /* Set up sorting. Make the window-specific _sorting variable
    01403      * point to the correct global _sorting struct so we are freed
    01404      * from having conditionals during window operation */
    01405     switch (this->vli.vtype) {
    01406       case VEH_TRAIN:    this->sorting = &_sorting.train; break;
    01407       case VEH_ROAD:     this->sorting = &_sorting.roadveh; break;
    01408       case VEH_SHIP:     this->sorting = &_sorting.ship; break;
    01409       case VEH_AIRCRAFT: this->sorting = &_sorting.aircraft; break;
    01410       default: NOT_REACHED();
    01411     }
    01412
    01413     this->CreateNestedTree(desc);
    01414
    01415     this->vscroll = this->GetScrollbar(VLW_WIDGET_SCROLLBAR);
    01416
    01417     this->vehicles.SetListing(*this->sorting);
    01418     this->vehicles.ForceRebuild();
    01419     this->vehicles.NeedResort();
    01420     this->BuildVehicleList();
    01421     this->SortVehicleList();
    01422
    01423     /* Set up the window widgets */
    01424     this->GetWidget<NWidgetCore>(VLW_WIDGET_LIST)->tool_tip = STR_VEHICLE_LIST_TRAIN_LIST_TOOLTIP + this->vli.vtype;
    01425
    01426     if (this->vli.type == VL_SHARED_ORDERS) {
    01427       this->GetWidget<NWidgetCore>(VLW_WIDGET_CAPTION)->widget_data = STR_VEHICLE_LIST_SHARED_ORDERS_LIST_CAPTION;
    01428     } else {
    01429       this->GetWidget<NWidgetCore>(VLW_WIDGET_CAPTION)->widget_data = STR_VEHICLE_LIST_TRAIN_CAPTION + this->vli.vtype;
    01430     }
    01431
    01432     this->FinishInitNested(desc, window_number);
    01433     this->owner = this->vli.company;
    01434
    01435     if (this->vli.vtype == VEH_TRAIN) ResizeWindow(this, 65, 0);
    01436   }
    01437
    01438   ~VehicleListWindow()
    01439   {
    01440     *this->sorting = this->vehicles.GetListing();
    01441   }
    01442
    01443   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    01444   {
    01445     switch (widget) {
    01446       case VLW_WIDGET_LIST:
    01447         resize->height = GetVehicleListHeight(this->vli.vtype, 1);
    01448
    01449         switch (this->vli.vtype) {
    01450           case VEH_TRAIN:
    01451           case VEH_ROAD:
    01452             size->height = 6 * resize->height;
    01453             break;
    01454           case VEH_SHIP:
    01455           case VEH_AIRCRAFT:
    01456             size->height = 4 * resize->height;
    01457             break;
    01458           default: NOT_REACHED();
    01459         }
    01460         break;
    01461
    01462       case VLW_WIDGET_SORT_ORDER: {
    01463         Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
    01464         d.width += padding.width + WD_SORTBUTTON_ARROW_WIDTH * 2; // Doubled since the string is centred and it also looks better.
    01465         d.height += padding.height;
    01466         *size = maxdim(*size, d);
    01467         break;
    01468       }
    01469
    01470       case VLW_WIDGET_MANAGE_VEHICLES_DROPDOWN: {
    01471         Dimension d = this->GetActionDropdownSize(this->vli.type == VL_STANDARD, false);
    01472         d.height += padding.height;
    01473         d.width  += padding.width;
    01474         *size = maxdim(*size, d);
    01475         break;
    01476       }
    01477     }
    01478   }
    01479
    01480   virtual void SetStringParameters(int widget) const
    01481   {
    01482     switch (widget) {
    01483       case VLW_WIDGET_AVAILABLE_VEHICLES:
    01484         SetDParam(0, STR_VEHICLE_LIST_AVAILABLE_TRAINS + this->vli.vtype);
    01485         break;
    01486
    01487       case VLW_WIDGET_CAPTION: {
    01488         switch (this->vli.type) {
    01489           case VL_SHARED_ORDERS: // Shared Orders
    01490             if (this->vehicles.Length() == 0) {
    01491               /* We can't open this window without vehicles using this order
    01492                * and we should close the window when deleting the order. */
    01493               NOT_REACHED();
    01494             }
    01495             SetDParam(0, this->vscroll->GetCount());
    01496             break;
    01497
    01498           case VL_STANDARD: // Company Name
    01499             SetDParam(0, STR_COMPANY_NAME);
    01500             SetDParam(1, this->vli.index);
    01501             SetDParam(3, this->vscroll->GetCount());
    01502             break;
    01503
    01504           case VL_STATION_LIST: // Station/Waypoint Name
    01505             SetDParam(0, Station::IsExpected(BaseStation::Get(this->vli.index)) ? STR_STATION_NAME : STR_WAYPOINT_NAME);
    01506             SetDParam(1, this->vli.index);
    01507             SetDParam(3, this->vscroll->GetCount());
    01508             break;
    01509
    01510           case VL_DEPOT_LIST:
    01511             SetDParam(0, STR_DEPOT_CAPTION);
    01512             SetDParam(1, this->vli.vtype);
    01513             SetDParam(2, this->vli.index);
    01514             SetDParam(3, this->vscroll->GetCount());
    01515             break;
    01516           default: NOT_REACHED();
    01517         }
    01518         break;
    01519       }
    01520     }
    01521   }
    01522
    01523   virtual void DrawWidget(const Rect &r, int widget) const
    01524   {
    01525     switch (widget) {
    01526       case VLW_WIDGET_SORT_ORDER:
    01527         /* draw arrow pointing up/down for ascending/descending sorting */
    01528         this->DrawSortButtonState(widget, this->vehicles.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
    01529         break;
    01530
    01531       case VLW_WIDGET_LIST:
    01532         this->DrawVehicleListItems(INVALID_VEHICLE, this->resize.step_height, r);
    01533         break;
    01534     }
    01535   }
    01536
    01537   virtual void OnPaint()
    01538   {
    01539     this->BuildVehicleList();
    01540     this->SortVehicleList();
    01541
    01542     if (this->vehicles.Length() == 0 && this->IsWidgetLowered(VLW_WIDGET_MANAGE_VEHICLES_DROPDOWN)) {
    01543       HideDropDownMenu(this);
    01544     }
    01545
    01546     /* Hide the widgets that we will not use in this window
    01547      * Some windows contains actions only fit for the owner */
    01548     int plane_to_show = (this->owner == _local_company) ? BP_SHOW_BUTTONS : BP_HIDE_BUTTONS;
    01549     NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(VLW_WIDGET_HIDE_BUTTONS);
    01550     if (plane_to_show != nwi->shown_plane) {
    01551       nwi->SetDisplayedPlane(plane_to_show);
    01552       nwi->SetDirty(this);
    01553     }
    01554     if (this->owner == _local_company) {
    01555       this->SetWidgetDisabledState(VLW_WIDGET_AVAILABLE_VEHICLES, this->vli.type != VL_STANDARD);
    01556       this->SetWidgetsDisabledState(this->vehicles.Length() == 0,
    01557         VLW_WIDGET_MANAGE_VEHICLES_DROPDOWN,
    01558         VLW_WIDGET_STOP_ALL,
    01559         VLW_WIDGET_START_ALL,
    01560         WIDGET_LIST_END);
    01561     }
    01562
    01563     /* Set text of sort by dropdown widget. */
    01564     this->GetWidget<NWidgetCore>(VLW_WIDGET_SORT_BY_PULLDOWN)->widget_data = this->vehicle_sorter_names[this->vehicles.SortType()];
    01565
    01566     this->DrawWidgets();
    01567   }
    01568
    01569   virtual void OnClick(Point pt, int widget, int click_count)
    01570   {
    01571     switch (widget) {
    01572       case VLW_WIDGET_SORT_ORDER: // Flip sorting method ascending/descending
    01573         this->vehicles.ToggleSortOrder();
    01574         this->SetDirty();
    01575         break;
    01576
    01577       case VLW_WIDGET_SORT_BY_PULLDOWN:// Select sorting criteria dropdown menu
    01578         ShowDropDownMenu(this, this->vehicle_sorter_names, this->vehicles.SortType(), VLW_WIDGET_SORT_BY_PULLDOWN, 0,
    01579             (this->vli.vtype == VEH_TRAIN || this->vli.vtype == VEH_ROAD) ? 0 : (1 << 10));
    01580         return;
    01581
    01582       case VLW_WIDGET_LIST: { // Matrix to show vehicles
    01583         uint id_v = this->vscroll->GetScrolledRowFromWidget(pt.y, this, VLW_WIDGET_LIST);
    01584         if (id_v >= this->vehicles.Length()) return; // click out of list bound
    01585
    01586         const Vehicle *v = this->vehicles[id_v];
    01587         if (!VehicleClicked(v)) ShowVehicleViewWindow(v);
    01588         break;
    01589       }
    01590
    01591       case VLW_WIDGET_AVAILABLE_VEHICLES:
    01592         ShowBuildVehicleWindow(INVALID_TILE, this->vli.vtype);
    01593         break;
    01594
    01595       case VLW_WIDGET_MANAGE_VEHICLES_DROPDOWN: {
    01596         DropDownList *list = this->BuildActionDropdownList(VehicleListIdentifier(this->window_number).type == VL_STANDARD, false);
    01597         ShowDropDownList(this, list, 0, VLW_WIDGET_MANAGE_VEHICLES_DROPDOWN);
    01598         break;
    01599       }
    01600
    01601       case VLW_WIDGET_STOP_ALL:
    01602       case VLW_WIDGET_START_ALL:
    01603         DoCommandP(0, (1 << 1) | (widget == VLW_WIDGET_START_ALL ? (1 << 0) : 0), this->window_number, CMD_MASS_START_STOP);
    01604         break;
    01605     }
    01606   }
    01607
    01608   virtual void OnDropdownSelect(int widget, int index)
    01609   {
    01610     switch (widget) {
    01611       case VLW_WIDGET_SORT_BY_PULLDOWN:
    01612         this->vehicles.SetSortType(index);
    01613         break;
    01614       case VLW_WIDGET_MANAGE_VEHICLES_DROPDOWN:
    01615         assert(this->vehicles.Length() != 0);
    01616
    01617         switch (index) {
    01618           case ADI_REPLACE: // Replace window
    01619             ShowReplaceGroupVehicleWindow(DEFAULT_GROUP, this->vli.vtype);
    01620             break;
    01621           case ADI_SERVICE: // Send for servicing
    01622           case ADI_DEPOT: // Send to Depots
    01623             DoCommandP(0, DEPOT_MASS_SEND | (index == ADI_SERVICE ? DEPOT_SERVICE : (DepotCommand)0), this->window_number, GetCmdSendToDepot(this->vli.vtype));
    01624             break;
    01625
    01626           default: NOT_REACHED();
    01627         }
    01628         break;
    01629       default: NOT_REACHED();
    01630     }
    01631     this->SetDirty();
    01632   }
    01633
    01634   virtual void OnTick()
    01635   {
    01636     if (_pause_mode != PM_UNPAUSED) return;
    01637     if (this->vehicles.NeedResort()) {
    01638       StationID station = (this->vli.type == VL_STATION_LIST) ? this->vli.index : INVALID_STATION;
    01639
    01640       DEBUG(misc, 3, "Periodic resort %d list company %d at station %d", this->vli.vtype, this->owner, station);
    01641       this->SetDirty();
    01642     }
    01643   }
    01644
    01645   virtual void OnResize()
    01646   {
    01647     this->vscroll->SetCapacityFromWidget(this, VLW_WIDGET_LIST);
    01648     this->GetWidget<NWidgetCore>(VLW_WIDGET_LIST)->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
    01649   }
    01650
    01656   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
    01657   {
    01658     if (!gui_scope && HasBit(data, 31) && this->vli.type == VL_SHARED_ORDERS) {
    01659       /* Needs to be done in command-scope, so everything stays valid */
    01660       this->vli.index = GB(data, 0, 20);
    01661       this->window_number = this->vli.Pack();
    01662       this->vehicles.ForceRebuild();
    01663       return;
    01664     }
    01665
    01666     if (data == 0) {
    01667       /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
    01668       this->vehicles.ForceRebuild();
    01669     } else {
    01670       this->vehicles.ForceResort();
    01671     }
    01672   }
    01673 };
    01674
    01675 static WindowDesc _vehicle_list_desc(
    01676   WDP_AUTO, 260, 246,
    01677   WC_INVALID, WC_NONE,
    01678   WDF_UNCLICK_BUTTONS,
    01679   _nested_vehicle_list, lengthof(_nested_vehicle_list)
    01680 );
    01681
    01682 static void ShowVehicleListWindowLocal(CompanyID company, VehicleListType vlt, VehicleType vehicle_type, uint16 unique_number)
    01683 {
    01684   if (!Company::IsValidID(company)) return;
    01685
    01686   _vehicle_list_desc.cls = GetWindowClassForVehicleType(vehicle_type);
    01687   AllocateWindowDescFront<VehicleListWindow>(&_vehicle_list_desc, VehicleListIdentifier(vlt, vehicle_type, company, unique_number).Pack());
    01688 }
    01689
    01690 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type)
    01691 {
    01692   /* If _settings_client.gui.advanced_vehicle_list > 1, display the Advanced list
    01693    * if _settings_client.gui.advanced_vehicle_list == 1, display Advanced list only for local company
    01694    * if _ctrl_pressed, do the opposite action (Advanced list x Normal list)
    01695    */
    01696
    01697   if ((_settings_client.gui.advanced_vehicle_list > (uint)(company != _local_company)) != _ctrl_pressed) {
    01698     ShowCompanyGroup(company, vehicle_type);
    01699   } else {
    01700     ShowVehicleListWindowLocal(company, VL_STANDARD, vehicle_type, company);
    01701   }
    01702 }
    01703
    01704 void ShowVehicleListWindow(const Vehicle *v)
    01705 {
    01706   ShowVehicleListWindowLocal(v->owner, VL_SHARED_ORDERS, v->type, v->FirstShared()->index);
    01707 }
    01708
    01709 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, StationID station)
    01710 {
    01711   if (!Company::IsValidID(company)) {
    01712     company = _local_company;
    01713     /* This can happen when opening the vehicle list as a spectator. */
    01714     if (!Company::IsValidID(company)) return;
    01715     _vehicle_list_desc.flags |= WDF_CONSTRUCTION;
    01716   } else {
    01717     _vehicle_list_desc.flags &= ~WDF_CONSTRUCTION;
    01718   }
    01719
    01720   ShowVehicleListWindowLocal(company, VL_STATION_LIST, vehicle_type, station);
    01721 }
    01722
    01723 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, TileIndex depot_tile)
    01724 {
    01725   uint16 depot_airport_index;
    01726
    01727   if (vehicle_type == VEH_AIRCRAFT) {
    01728     depot_airport_index = GetStationIndex(depot_tile);
    01729   } else {
    01730     depot_airport_index = GetDepotIndex(depot_tile);
    01731   }
    01732   ShowVehicleListWindowLocal(company, VL_DEPOT_LIST, vehicle_type, depot_airport_index);
    01733 }
    01734
    01735
    01736 /* Unified vehicle GUI - Vehicle Details Window */
    01737
    01739 enum VehicleDetailsWindowWidgets {
    01740   VLD_WIDGET_CAPTION,
    01741   VLD_WIDGET_RENAME_VEHICLE,
    01742   VLD_WIDGET_TOP_DETAILS,
    01743   VLD_WIDGET_INCREASE_SERVICING_INTERVAL,
    01744   VLD_WIDGET_DECREASE_SERVICING_INTERVAL,
    01745   VLD_WIDGET_SERVICING_INTERVAL,
    01746   VLD_WIDGET_MIDDLE_DETAILS,
    01747   VLD_WIDGET_MATRIX,
    01748   VLD_WIDGET_SCROLLBAR,
    01749   VLD_WIDGET_DETAILS_CARGO_CARRIED,
    01750   VLD_WIDGET_DETAILS_TRAIN_VEHICLES,
    01751   VLD_WIDGET_DETAILS_CAPACITY_OF_EACH,
    01752   VLD_WIDGET_DETAILS_TOTAL_CARGO,
    01753 };
    01754
    01755 assert_compile(VLD_WIDGET_DETAILS_CARGO_CARRIED    == VLD_WIDGET_DETAILS_CARGO_CARRIED + TDW_TAB_CARGO   );
    01756 assert_compile(VLD_WIDGET_DETAILS_TRAIN_VEHICLES   == VLD_WIDGET_DETAILS_CARGO_CARRIED + TDW_TAB_INFO    );
    01757 assert_compile(VLD_WIDGET_DETAILS_CAPACITY_OF_EACH == VLD_WIDGET_DETAILS_CARGO_CARRIED + TDW_TAB_CAPACITY);
    01758 assert_compile(VLD_WIDGET_DETAILS_TOTAL_CARGO      == VLD_WIDGET_DETAILS_CARGO_CARRIED + TDW_TAB_TOTALS  );
    01759
    01761 static const NWidgetPart _nested_nontrain_vehicle_details_widgets[] = {
    01762   NWidget(NWID_HORIZONTAL),
    01763     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
    01764     NWidget(WWT_CAPTION, COLOUR_GREY, VLD_WIDGET_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
    01765     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 */),
    01766     NWidget(WWT_SHADEBOX, COLOUR_GREY),
    01767     NWidget(WWT_STICKYBOX, COLOUR_GREY),
    01768   EndContainer(),
    01769   NWidget(WWT_PANEL, COLOUR_GREY, VLD_WIDGET_TOP_DETAILS), SetMinimalSize(405, 42), SetResize(1, 0), EndContainer(),
    01770   NWidget(WWT_PANEL, COLOUR_GREY, VLD_WIDGET_MIDDLE_DETAILS), SetMinimalSize(405, 45), SetResize(1, 0), EndContainer(),
    01771   NWidget(NWID_HORIZONTAL),
    01772     NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, VLD_WIDGET_DECREASE_SERVICING_INTERVAL), SetFill(0, 1),
    01773         SetDataTip(AWV_DECREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
    01774     NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, VLD_WIDGET_INCREASE_SERVICING_INTERVAL), SetFill(0, 1),
    01775         SetDataTip(AWV_INCREASE, STR_VEHICLE_DETAILS_INCREASE_SERVICING_INTERVAL_TOOLTIP),
    01776     NWidget(WWT_PANEL, COLOUR_GREY, VLD_WIDGET_SERVICING_INTERVAL), SetFill(1, 1), SetResize(1, 0), EndContainer(),
    01777     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
    01778   EndContainer(),
    01779 };
    01780
    01782 static const NWidgetPart _nested_train_vehicle_details_widgets[] = {
    01783   NWidget(NWID_HORIZONTAL),
    01784     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
    01785     NWidget(WWT_CAPTION, COLOUR_GREY, VLD_WIDGET_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
    01786     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 */),
    01787     NWidget(WWT_SHADEBOX, COLOUR_GREY),
    01788     NWidget(WWT_STICKYBOX, COLOUR_GREY),
    01789   EndContainer(),
    01790   NWidget(WWT_PANEL, COLOUR_GREY, VLD_WIDGET_TOP_DETAILS), SetResize(1, 0), SetMinimalSize(405, 42), EndContainer(),
    01791   NWidget(NWID_HORIZONTAL),
    01792     NWidget(WWT_MATRIX, COLOUR_GREY, VLD_WIDGET_MATRIX), SetResize(1, 1), SetMinimalSize(393, 45), SetDataTip(0x701, STR_NULL), SetFill(1, 0), SetScrollbar(VLD_WIDGET_SCROLLBAR),
    01793     NWidget(NWID_VSCROLLBAR, COLOUR_GREY, VLD_WIDGET_SCROLLBAR),
    01794   EndContainer(),
    01795   NWidget(NWID_HORIZONTAL),
    01796     NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, VLD_WIDGET_DECREASE_SERVICING_INTERVAL), SetFill(0, 1),
    01797         SetDataTip(AWV_DECREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
    01798     NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, VLD_WIDGET_INCREASE_SERVICING_INTERVAL), SetFill(0, 1),
    01799         SetDataTip(AWV_INCREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
    01800     NWidget(WWT_PANEL, COLOUR_GREY, VLD_WIDGET_SERVICING_INTERVAL), SetFill(1, 1), SetResize(1, 0), EndContainer(),
    01801   EndContainer(),
    01802   NWidget(NWID_HORIZONTAL),
    01803     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, VLD_WIDGET_DETAILS_CARGO_CARRIED), SetMinimalSize(96, 12),
    01804         SetDataTip(STR_VEHICLE_DETAIL_TAB_CARGO, STR_VEHICLE_DETAILS_TRAIN_CARGO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
    01805     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, VLD_WIDGET_DETAILS_TRAIN_VEHICLES), SetMinimalSize(99, 12),
    01806         SetDataTip(STR_VEHICLE_DETAIL_TAB_INFORMATION, STR_VEHICLE_DETAILS_TRAIN_INFORMATION_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
    01807     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, VLD_WIDGET_DETAILS_CAPACITY_OF_EACH), SetMinimalSize(99, 12),
    01808         SetDataTip(STR_VEHICLE_DETAIL_TAB_CAPACITIES, STR_VEHICLE_DETAILS_TRAIN_CAPACITIES_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
    01809     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, VLD_WIDGET_DETAILS_TOTAL_CARGO), SetMinimalSize(99, 12),
    01810         SetDataTip(STR_VEHICLE_DETAIL_TAB_TOTAL_CARGO, STR_VEHICLE_DETAILS_TRAIN_TOTAL_CARGO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
    01811     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
    01812   EndContainer(),
    01813 };
    01814
    01815
    01816 extern int GetTrainDetailsWndVScroll(VehicleID veh_id, TrainDetailsWindowTabs det_tab);
    01817 extern void DrawTrainDetails(const Train *v, int left, int right, int y, int vscroll_pos, uint16 vscroll_cap, TrainDetailsWindowTabs det_tab);
    01818 extern void DrawRoadVehDetails(const Vehicle *v, int left, int right, int y);
    01819 extern void DrawShipDetails(const Vehicle *v, int left, int right, int y);
    01820 extern void DrawAircraftDetails(const Aircraft *v, int left, int right, int y);
    01821
    01823 struct VehicleDetailsWindow : Window {
    01824   TrainDetailsWindowTabs tab;
    01825   Scrollbar *vscroll;
    01826
    01828   VehicleDetailsWindow(const WindowDesc *desc, WindowNumber window_number) : Window()
    01829   {
    01830     const Vehicle *v = Vehicle::Get(window_number);
    01831
    01832     this->CreateNestedTree(desc);
    01833     this->vscroll = (v->type == VEH_TRAIN ? this->GetScrollbar(VLD_WIDGET_SCROLLBAR) : NULL);
    01834     this->FinishInitNested(desc, window_number);
    01835
    01836     this->GetWidget<NWidgetCore>(VLD_WIDGET_RENAME_VEHICLE)->tool_tip = STR_VEHICLE_DETAILS_TRAIN_RENAME + v->type;
    01837
    01838     this->owner = v->owner;
    01839     this->tab = TDW_TAB_CARGO;
    01840   }
    01841
    01847   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
    01848   {
    01849     if (data == -666) {
    01850       /* Autoreplace replaced the vehicle.
    01851        * Nothing to do for this window. */
    01852       return;
    01853     }
    01854     if (!gui_scope) return;
    01855     const Vehicle *v = Vehicle::Get(this->window_number);
    01856     if (v->type == VEH_ROAD) {
    01857       const NWidgetBase *nwid_info = this->GetWidget<NWidgetBase>(VLD_WIDGET_MIDDLE_DETAILS);
    01858       uint aimed_height = this->GetRoadVehDetailsHeight(v);
    01859       /* If the number of articulated parts changes, the size of the window must change too. */
    01860       if (aimed_height != nwid_info->current_y) {
    01861         this->ReInit();
    01862       }
    01863     }
    01864   }
    01865
    01871   uint GetRoadVehDetailsHeight(const Vehicle *v)
    01872   {
    01873     uint desired_height;
    01874     if (v->HasArticulatedPart()) {
    01875       /* An articulated RV has its text drawn under the sprite instead of after it, hence 15 pixels extra. */
    01876       desired_height = WD_FRAMERECT_TOP + 15 + 3 * FONT_HEIGHT_NORMAL + 2 + WD_FRAMERECT_BOTTOM;
    01877       /* Add space for the cargo amount for each part. */
    01878       for (const Vehicle *u = v; u != NULL; u = u->Next()) {
    01879         if (u->cargo_cap != 0) desired_height += FONT_HEIGHT_NORMAL + 1;
    01880       }
    01881     } else {
    01882       desired_height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + 3 + WD_FRAMERECT_BOTTOM;
    01883     }
    01884     return desired_height;
    01885   }
    01886
    01887   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    01888   {
    01889     switch (widget) {
    01890       case VLD_WIDGET_TOP_DETAILS: {
    01891         Dimension dim = { 0, 0 };
    01892         size->height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
    01893
    01894         for (uint i = 0; i < 4; i++) SetDParam(i, INT16_MAX);
    01895         static const StringID info_strings[] = {
    01896           STR_VEHICLE_INFO_MAX_SPEED,
    01897           STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED,
    01898           STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE,
    01899           STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR,
    01900           STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS
    01901         };
    01902         for (uint i = 0; i < lengthof(info_strings); i++) {
    01903           dim = maxdim(dim, GetStringBoundingBox(info_strings[i]));
    01904         }
    01905         SetDParam(0, STR_VEHICLE_INFO_AGE);
    01906         dim = maxdim(dim, GetStringBoundingBox(STR_VEHICLE_INFO_AGE_RUNNING_COST_YR));
    01907         size->width = dim.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
    01908         break;
    01909       }
    01910
    01911       case VLD_WIDGET_MIDDLE_DETAILS: {
    01912         const Vehicle *v = Vehicle::Get(this->window_number);
    01913         switch (v->type) {
    01914           case VEH_ROAD:
    01915             size->height = this->GetRoadVehDetailsHeight(v);
    01916             break;
    01917
    01918           case VEH_SHIP:
    01919             size->height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + 3 + WD_FRAMERECT_BOTTOM;
    01920             break;
    01921
    01922           case VEH_AIRCRAFT:
    01923             size->height = WD_FRAMERECT_TOP + 5 * FONT_HEIGHT_NORMAL + 4 + WD_FRAMERECT_BOTTOM;
    01924             break;
    01925
    01926           default:
    01927             NOT_REACHED(); // Train uses VLD_WIDGET_MATRIX instead.
    01928         }
    01929         break;
    01930       }
    01931
    01932       case VLD_WIDGET_MATRIX:
    01933         resize->height = WD_MATRIX_TOP + FONT_HEIGHT_NORMAL + WD_MATRIX_BOTTOM;
    01934         size->height = 4 * resize->height;
    01935         break;
    01936
    01937       case VLD_WIDGET_SERVICING_INTERVAL:
    01938         SetDParam(0, 9999); // Roughly the maximum interval
    01939         SetDParam(1, MAX_YEAR * DAYS_IN_YEAR); // Roughly the maximum year
    01940         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;
    01941         size->height = WD_FRAMERECT_TOP + FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
    01942         break;
    01943     }
    01944   }
    01945
    01947   static bool IsVehicleServiceIntervalEnabled(const VehicleType vehicle_type, CompanyID company_id)
    01948   {
    01949     const VehicleDefaultSettings *vds = &Company::Get(company_id)->settings.vehicle;
    01950     switch (vehicle_type) {
    01951       default: NOT_REACHED();
    01952       case VEH_TRAIN:    return vds->servint_trains   != 0;
    01953       case VEH_ROAD:     return vds->servint_roadveh  != 0;
    01954       case VEH_SHIP:     return vds->servint_ships    != 0;
    01955       case VEH_AIRCRAFT: return vds->servint_aircraft != 0;
    01956     }
    01957   }
    01958
    01970   static void DrawVehicleDetails(const Vehicle *v, int left, int right, int y, int vscroll_pos, uint vscroll_cap, TrainDetailsWindowTabs det_tab)
    01971   {
    01972     switch (v->type) {
    01973       case VEH_TRAIN:    DrawTrainDetails(Train::From(v), left, right, y, vscroll_pos, vscroll_cap, det_tab);  break;
    01974       case VEH_ROAD:     DrawRoadVehDetails(v, left, right, y);  break;
    01975       case VEH_SHIP:     DrawShipDetails(v, left, right, y);     break;
    01976       case VEH_AIRCRAFT: DrawAircraftDetails(Aircraft::From(v), left, right, y); break;
    01977       default: NOT_REACHED();
    01978     }
    01979   }
    01980
    01981   virtual void SetStringParameters(int widget) const
    01982   {
    01983     if (widget == VLD_WIDGET_CAPTION) SetDParam(0, Vehicle::Get(this->window_number)->index);
    01984   }
    01985
    01986   virtual void DrawWidget(const Rect &r, int widget) const
    01987   {
    01988     const Vehicle *v = Vehicle::Get(this->window_number);
    01989
    01990     switch (widget) {
    01991       case VLD_WIDGET_TOP_DETAILS: {
    01992         int y = r.top + WD_FRAMERECT_TOP;
    01993
    01994         /* Draw running cost */
    01995         SetDParam(1, v->age / DAYS_IN_LEAP_YEAR);
    01996         SetDParam(0, (v->age + DAYS_IN_YEAR < v->max_age) ? STR_VEHICLE_INFO_AGE : STR_VEHICLE_INFO_AGE_RED);
    01997         SetDParam(2, v->max_age / DAYS_IN_LEAP_YEAR);
    01998         SetDParam(3, v->GetDisplayRunningCost());
    01999         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_AGE_RUNNING_COST_YR);
    02000         y += FONT_HEIGHT_NORMAL;
    02001
    02002         /* Draw max speed */
    02003         StringID string;
    02004         if (v->type == VEH_TRAIN ||
    02005             (v->type == VEH_ROAD && _settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL)) {
    02006           const GroundVehicleCache *gcache = v->GetGroundVehicleCache();
    02007           SetDParam(2, v->GetDisplayMaxSpeed());
    02008           SetDParam(1, gcache->cached_power);
    02009           SetDParam(0, gcache->cached_weight);
    02010           SetDParam(3, gcache->cached_max_te / 1000);
    02011           if (v->type == VEH_TRAIN && (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ||
    02012               GetRailTypeInfo(Train::From(v)->railtype)->acceleration_type == 2)) {
    02013             string = STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED;
    02014           } else {
    02015             string = STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE;
    02016           }
    02017         } else {
    02018           SetDParam(0, v->GetDisplayMaxSpeed());
    02019           string = STR_VEHICLE_INFO_MAX_SPEED;
    02020         }
    02021         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, string);
    02022         y += FONT_HEIGHT_NORMAL;
    02023
    02024         /* Draw profit */
    02025         SetDParam(0, v->GetDisplayProfitThisYear());
    02026         SetDParam(1, v->GetDisplayProfitLastYear());
    02027         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR);
    02028         y += FONT_HEIGHT_NORMAL;
    02029
    02030         /* Draw breakdown & reliability */
    02031         byte total_engines = 0;
    02032         if (v->type == VEH_TRAIN) {
    02033           /* We want to draw the average reliability and total number of breakdowns. */
    02034           uint32 total_reliability = 0;
    02035           uint16 total_breakdowns  = 0;
    02036           for (const Vehicle *w = v; w != NULL; w = w->Next()) {
    02037             if (Train::From(w)->IsEngine() || Train::From(w)->IsMultiheaded()) {
    02038               total_reliability += w->reliability;
    02039               total_breakdowns += w->breakdowns_since_last_service;
    02040             }
    02041           }
    02042           total_engines = Train::From(v)->tcache.cached_num_engines;
    02043           assert(total_engines > 0);
    02044           SetDParam(0, ToPercent16(total_reliability / total_engines));
    02045           SetDParam(1, total_breakdowns);
    02046         } else {
    02047           SetDParam(0, ToPercent16(v->reliability));
    02048           SetDParam(1, v->breakdowns_since_last_service);
    02049         }
    02050         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS);
    02051         break;
    02052       }
    02053
    02054       case VLD_WIDGET_MATRIX:
    02055         /* For trains only. */
    02056         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);
    02057         break;
    02058
    02059       case VLD_WIDGET_MIDDLE_DETAILS: {
    02060         /* For other vehicles, at the place of the matrix. */
    02061         bool rtl = _current_text_dir == TD_RTL;
    02062         uint sprite_width = max<uint>(GetSprite(v->GetImage(rtl ? DIR_E : DIR_W), ST_NORMAL)->width, 70U) + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
    02063
    02064         uint text_left  = r.left  + (rtl ? 0 : sprite_width);
    02065         uint text_right = r.right - (rtl ? sprite_width : 0);
    02066
    02067         /* Articulated road vehicles use a complete line. */
    02068         if (v->type == VEH_ROAD && v->HasArticulatedPart()) {
    02069           DrawVehicleImage(v, r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, 0);
    02070         } else {
    02071           uint sprite_left  = rtl ? text_right : r.left;
    02072           uint sprite_right = rtl ? r.right : text_left;
    02073
    02074           DrawVehicleImage(v, sprite_left + WD_FRAMERECT_LEFT, sprite_right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, 0);
    02075         }
    02076         DrawVehicleDetails(v, text_left + WD_FRAMERECT_LEFT, text_right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, 0, 0, this->tab);
    02077         break;
    02078       }
    02079
    02080       case VLD_WIDGET_SERVICING_INTERVAL:
    02081         /* Draw service interval text */
    02082         SetDParam(0, v->service_interval);
    02083         SetDParam(1, v->date_of_last_service);
    02084         DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + (r.bottom - r.top + 1 - FONT_HEIGHT_NORMAL) / 2,
    02085             Company::Get(v->owner)->settings.vehicle.servint_ispercent ? STR_VEHICLE_DETAILS_SERVICING_INTERVAL_PERCENT : STR_VEHICLE_DETAILS_SERVICING_INTERVAL_DAYS);
    02086         break;
    02087     }
    02088   }
    02089
    02091   virtual void OnPaint()
    02092   {
    02093     const Vehicle *v = Vehicle::Get(this->window_number);
    02094
    02095     this->SetWidgetDisabledState(VLD_WIDGET_RENAME_VEHICLE, v->owner != _local_company);
    02096
    02097     if (v->type == VEH_TRAIN) {
    02098       this->DisableWidget(this->tab + VLD_WIDGET_DETAILS_CARGO_CARRIED);
    02099       this->vscroll->SetCount(GetTrainDetailsWndVScroll(v->index, this->tab));
    02100     }
    02101
    02102     /* Disable service-scroller when interval is set to disabled */
    02103     this->SetWidgetsDisabledState(!IsVehicleServiceIntervalEnabled(v->type, v->owner),
    02104       VLD_WIDGET_INCREASE_SERVICING_INTERVAL,
    02105       VLD_WIDGET_DECREASE_SERVICING_INTERVAL,
    02106       WIDGET_LIST_END);
    02107
    02108     this->DrawWidgets();
    02109   }
    02110
    02111   virtual void OnClick(Point pt, int widget, int click_count)
    02112   {
    02113     switch (widget) {
    02114       case VLD_WIDGET_RENAME_VEHICLE: { // rename
    02115         const Vehicle *v = Vehicle::Get(this->window_number);
    02116         SetDParam(0, v->index);
    02117         ShowQueryString(STR_VEHICLE_NAME, STR_QUERY_RENAME_TRAIN_CAPTION + v->type,
    02118             MAX_LENGTH_VEHICLE_NAME_CHARS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
    02119         break;
    02120       }
    02121
    02122       case VLD_WIDGET_INCREASE_SERVICING_INTERVAL:   // increase int
    02123       case VLD_WIDGET_DECREASE_SERVICING_INTERVAL: { // decrease int
    02124         int mod = _ctrl_pressed ? 5 : 10;
    02125         const Vehicle *v = Vehicle::Get(this->window_number);
    02126
    02127         mod = (widget == VLD_WIDGET_DECREASE_SERVICING_INTERVAL) ? -mod : mod;
    02128         mod = GetServiceIntervalClamped(mod + v->service_interval, v->owner);
    02129         if (mod == v->service_interval) return;
    02130
    02131         DoCommandP(v->tile, v->index, mod, CMD_CHANGE_SERVICE_INT | CMD_MSG(STR_ERROR_CAN_T_CHANGE_SERVICING));
    02132         break;
    02133       }
    02134
    02135       case VLD_WIDGET_DETAILS_CARGO_CARRIED:
    02136       case VLD_WIDGET_DETAILS_TRAIN_VEHICLES:
    02137       case VLD_WIDGET_DETAILS_CAPACITY_OF_EACH:
    02138       case VLD_WIDGET_DETAILS_TOTAL_CARGO:
    02139         this->SetWidgetsDisabledState(false,
    02140           VLD_WIDGET_DETAILS_CARGO_CARRIED,
    02141           VLD_WIDGET_DETAILS_TRAIN_VEHICLES,
    02142           VLD_WIDGET_DETAILS_CAPACITY_OF_EACH,
    02143           VLD_WIDGET_DETAILS_TOTAL_CARGO,
    02144           widget,
    02145           WIDGET_LIST_END);
    02146
    02147         this->tab = (TrainDetailsWindowTabs)(widget - VLD_WIDGET_DETAILS_CARGO_CARRIED);
    02148         this->SetDirty();
    02149         break;
    02150     }
    02151   }
    02152
    02153   virtual void OnQueryTextFinished(char *str)
    02154   {
    02155     if (str == NULL) return;
    02156
    02157     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);
    02158   }
    02159
    02160   virtual void OnResize()
    02161   {
    02162     NWidgetCore *nwi = this->GetWidget<NWidgetCore>(VLD_WIDGET_MATRIX);
    02163     if (nwi != NULL) {
    02164       this->vscroll->SetCapacityFromWidget(this, VLD_WIDGET_MATRIX);
    02165       nwi->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
    02166     }
    02167   }
    02168 };
    02169
    02171 static const WindowDesc _train_vehicle_details_desc(
    02172   WDP_AUTO, 405, 178,
    02173   WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
    02174   WDF_UNCLICK_BUTTONS,
    02175   _nested_train_vehicle_details_widgets, lengthof(_nested_train_vehicle_details_widgets)
    02176 );
    02177
    02179 static const WindowDesc _nontrain_vehicle_details_desc(
    02180   WDP_AUTO, 405, 113,
    02181   WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
    02182   WDF_UNCLICK_BUTTONS,
    02183   _nested_nontrain_vehicle_details_widgets, lengthof(_nested_nontrain_vehicle_details_widgets)
    02184 );
    02185
    02187 static void ShowVehicleDetailsWindow(const Vehicle *v)
    02188 {
    02189   DeleteWindowById(WC_VEHICLE_ORDERS, v->index, false);
    02190   DeleteWindowById(WC_VEHICLE_TIMETABLE, v->index, false);
    02191   AllocateWindowDescFront<VehicleDetailsWindow>((v->type == VEH_TRAIN) ? &_train_vehicle_details_desc : &_nontrain_vehicle_details_desc, v->index);
    02192 }
    02193
    02194
    02195 /* Unified vehicle GUI - Vehicle View Window */
    02196
    02198 static const NWidgetPart _nested_vehicle_view_widgets[] = {
    02199   NWidget(NWID_HORIZONTAL),
    02200     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
    02201     NWidget(WWT_CAPTION, COLOUR_GREY, VVW_WIDGET_CAPTION), SetDataTip(STR_VEHICLE_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
    02202     NWidget(WWT_DEBUGBOX, COLOUR_GREY),
    02203     NWidget(WWT_SHADEBOX, COLOUR_GREY),
    02204     NWidget(WWT_STICKYBOX, COLOUR_GREY),
    02205   EndContainer(),
    02206   NWidget(NWID_HORIZONTAL),
    02207     NWidget(WWT_PANEL, COLOUR_GREY),
    02208       NWidget(WWT_INSET, COLOUR_GREY), SetPadding(2, 2, 2, 2),
    02209         NWidget(NWID_VIEWPORT, INVALID_COLOUR, VVW_WIDGET_VIEWPORT), SetMinimalSize(226, 84), SetResize(1, 1), SetPadding(1, 1, 1, 1),
    02210       EndContainer(),
    02211     EndContainer(),
    02212     NWidget(NWID_VERTICAL),
    02213       NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VVW_WIDGET_CENTER_MAIN_VIEH), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(SPR_CENTRE_VIEW_VEHICLE, 0x0 /* filled later */),
    02214       NWidget(NWID_SELECTION, INVALID_COLOUR, VVW_WIDGET_SELECT_DEPOT_CLONE),
    02215         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VVW_WIDGET_GOTO_DEPOT), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
    02216         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VVW_WIDGET_CLONE_VEH), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
    02217       EndContainer(),
    02218       /* For trains only, 'ignore signal' button. */
    02219       NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VVW_WIDGET_FORCE_PROCEED), SetMinimalSize(18, 18), SetFill(1, 1),
    02220                       SetDataTip(SPR_IGNORE_SIGNALS, STR_VEHICLE_VIEW_TRAIN_IGNORE_SIGNAL_TOOLTIP),
    02221       NWidget(NWID_SELECTION, INVALID_COLOUR, VVW_WIDGET_SELECT_REFIT_TURN),
    02222         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VVW_WIDGET_REFIT_VEH), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(SPR_REFIT_VEHICLE, 0x0 /* filled later */),
    02223         NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VVW_WIDGET_TURN_AROUND), SetMinimalSize(18, 18), SetFill(1, 1),
    02224                         SetDataTip(SPR_FORCE_VEHICLE_TURN, STR_VEHICLE_VIEW_ROAD_VEHICLE_REVERSE_TOOLTIP),
    02225       EndContainer(),
    02226       NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VVW_WIDGET_SHOW_ORDERS), SetFill(1, 1), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_ORDERS, 0x0 /* filled later */),
    02227       NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, VVW_WIDGET_SHOW_DETAILS), SetFill(1, 1), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_VEHICLE_DETAILS, 0x0 /* filled later */),
    02228       NWidget(WWT_PANEL, COLOUR_GREY), SetFill(1, 1), SetMinimalSize(18, 0), SetResize(0, 1), EndContainer(),
    02229     EndContainer(),
    02230   EndContainer(),
    02231   NWidget(NWID_HORIZONTAL),
    02232     NWidget(WWT_PUSHBTN, COLOUR_GREY, VVW_WIDGET_START_STOP_VEH), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM), SetResize(1, 0), SetFill(1, 0),
    02233     NWidget(WWT_RESIZEBOX, COLOUR_GREY),
    02234   EndContainer(),
    02235 };
    02236
    02238 static const WindowDesc _vehicle_view_desc(
    02239   WDP_AUTO, 250, 116,
    02240   WC_VEHICLE_VIEW, WC_NONE,
    02241   WDF_UNCLICK_BUTTONS,
    02242   _nested_vehicle_view_widgets, lengthof(_nested_vehicle_view_widgets)
    02243 );
    02244
    02249 static const WindowDesc _train_view_desc(
    02250   WDP_AUTO, 250, 134,
    02251   WC_VEHICLE_VIEW, WC_NONE,
    02252   WDF_UNCLICK_BUTTONS,
    02253   _nested_vehicle_view_widgets, lengthof(_nested_vehicle_view_widgets)
    02254 );
    02255
    02256
    02257 /* Just to make sure, nobody has changed the vehicle type constants, as we are
    02258    using them for array indexing in a number of places here. */
    02259 assert_compile(VEH_TRAIN == 0);
    02260 assert_compile(VEH_ROAD == 1);
    02261 assert_compile(VEH_SHIP == 2);
    02262 assert_compile(VEH_AIRCRAFT == 3);
    02263
    02265 static const ZoomLevel _vehicle_view_zoom_levels[] = {
    02266   ZOOM_LVL_TRAIN,
    02267   ZOOM_LVL_ROADVEH,
    02268   ZOOM_LVL_SHIP,
    02269   ZOOM_LVL_AIRCRAFT,
    02270 };
    02271
    02272 /* Constants for geometry of vehicle view viewport */
    02273 static const int VV_INITIAL_VIEWPORT_WIDTH = 226;
    02274 static const int VV_INITIAL_VIEWPORT_HEIGHT = 84;
    02275 static const int VV_INITIAL_VIEWPORT_HEIGHT_TRAIN = 102;
    02276
    02278 enum VehicleCommandTranslation {
    02279   VCT_CMD_START_STOP = 0,
    02280   VCT_CMD_CLONE_VEH,
    02281   VCT_CMD_TURN_AROUND,
    02282 };
    02283
    02285 static const uint32 _vehicle_command_translation_table[][4] = {
    02286   { // VCT_CMD_START_STOP
    02287     CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_TRAIN),
    02288     CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_ROAD_VEHICLE),
    02289     CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_SHIP),
    02290     CMD_START_STOP_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_STOP_START_AIRCRAFT)
    02291   },
    02292   { // VCT_CMD_CLONE_VEH
    02293     CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_TRAIN),
    02294     CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_ROAD_VEHICLE),
    02295     CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_SHIP),
    02296     CMD_CLONE_VEHICLE | CMD_MSG(STR_ERROR_CAN_T_BUY_AIRCRAFT)
    02297   },
    02298   { // VCT_CMD_TURN_AROUND
    02299     CMD_REVERSE_TRAIN_DIRECTION | CMD_MSG(STR_ERROR_CAN_T_REVERSE_DIRECTION_TRAIN),
    02300     CMD_TURN_ROADVEH            | CMD_MSG(STR_ERROR_CAN_T_MAKE_ROAD_VEHICLE_TURN),
    02301     0xffffffff, // invalid for ships
    02302     0xffffffff  // invalid for aircrafts
    02303   },
    02304 };
    02305
    02313 void CcStartStopVehicle(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
    02314 {
    02315   if (result.Failed()) return;
    02316
    02317   const Vehicle *v = Vehicle::GetIfValid(p1);
    02318   if (v == NULL || !v->IsPrimaryVehicle() || v->owner != _local_company) return;
    02319
    02320   StringID msg = (v->vehstatus & VS_STOPPED) ? STR_VEHICLE_COMMAND_STOPPED : STR_VEHICLE_COMMAND_STARTED;
    02321   Point pt = RemapCoords(v->x_pos, v->y_pos, v->z_pos);
    02322   AddTextEffect(msg, pt.x, pt.y, DAY_TICKS, TE_RISING);
    02323 }
    02324
    02330 void StartStopVehicle(const Vehicle *v, bool texteffect)
    02331 {
    02332   assert(v->IsPrimaryVehicle());
    02333   DoCommandP(v->tile, v->index, 0, _vehicle_command_translation_table[VCT_CMD_START_STOP][v->type], texteffect ? CcStartStopVehicle : NULL);
    02334 }
    02335
    02337 static const StringID _aircraft_breakdown_strings[] = {
    02338   STR_BREAKDOWN_TYPE_LOW_SPEED,
    02339   STR_BREAKDOWN_TYPE_DEPOT,
    02340   STR_BREAKDOWN_TYPE_LANDING,
    02341 };
    02342
    02344 static bool IsVehicleRefitable(const Vehicle *v)
    02345 {
    02346   if (!v->IsStoppedInDepot()) return false;
    02347
    02348   do {
    02349     if (IsEngineRefittable(v->engine_type)) return true;
    02350   } while (v->IsGroundVehicle() && (v = v->Next()) != NULL);
    02351
    02352   return false;
    02353 }
    02354
    02356 struct VehicleViewWindow : Window {
    02357 private:
    02359   enum PlaneSelections {
    02360     SEL_DC_GOTO_DEPOT,
    02361     SEL_DC_CLONE,
    02362
    02363     SEL_RT_REFIT,
    02364     SEL_RT_TURN_AROUND,
    02365
    02366     SEL_DC_BASEPLANE = SEL_DC_GOTO_DEPOT,
    02367     SEL_RT_BASEPLANE = SEL_RT_REFIT,
    02368   };
    02369
    02374   void SelectPlane(PlaneSelections plane)
    02375   {
    02376     switch (plane) {
    02377       case SEL_DC_GOTO_DEPOT:
    02378       case SEL_DC_CLONE:
    02379         this->GetWidget<NWidgetStacked>(VVW_WIDGET_SELECT_DEPOT_CLONE)->SetDisplayedPlane(plane - SEL_DC_BASEPLANE);
    02380         break;
    02381
    02382       case SEL_RT_REFIT:
    02383       case SEL_RT_TURN_AROUND:
    02384         this->GetWidget<NWidgetStacked>(VVW_WIDGET_SELECT_REFIT_TURN)->SetDisplayedPlane(plane - SEL_RT_BASEPLANE);
    02385         break;
    02386
    02387       default:
    02388         NOT_REACHED();
    02389     }
    02390   }
    02391
    02392 public:
    02393   VehicleViewWindow(const WindowDesc *desc, WindowNumber window_number) : Window()
    02394   {
    02395     this->CreateNestedTree(desc);
    02396
    02397     /* Sprites for the 'send to depot' button indexed by vehicle type. */
    02398     static const SpriteID vehicle_view_goto_depot_sprites[] = {
    02399       SPR_SEND_TRAIN_TODEPOT,
    02400       SPR_SEND_ROADVEH_TODEPOT,
    02401       SPR_SEND_SHIP_TODEPOT,
    02402       SPR_SEND_AIRCRAFT_TODEPOT,
    02403     };
    02404     const Vehicle *v = Vehicle::Get(window_number);
    02405     this->GetWidget<NWidgetCore>(VVW_WIDGET_GOTO_DEPOT)->widget_data = vehicle_view_goto_depot_sprites[v->type];
    02406
    02407     /* Sprites for the 'clone vehicle' button indexed by vehicle type. */
    02408     static const SpriteID vehicle_view_clone_sprites[] = {
    02409       SPR_CLONE_TRAIN,
    02410       SPR_CLONE_ROADVEH,
    02411       SPR_CLONE_SHIP,
    02412       SPR_CLONE_AIRCRAFT,
    02413     };
    02414     this->GetWidget<NWidgetCore>(VVW_WIDGET_CLONE_VEH)->widget_data = vehicle_view_clone_sprites[v->type];
    02415
    02416     switch (v->type) {
    02417       case VEH_TRAIN:
    02418         this->GetWidget<NWidgetCore>(VVW_WIDGET_TURN_AROUND)->tool_tip = STR_VEHICLE_VIEW_TRAIN_REVERSE_TOOLTIP;
    02419         break;
    02420
    02421       case VEH_ROAD:
    02422         break;
    02423
    02424       case VEH_SHIP:
    02425       case VEH_AIRCRAFT:
    02426         this->SelectPlane(SEL_RT_REFIT);
    02427         break;
    02428
    02429       default: NOT_REACHED();
    02430     }
    02431     this->FinishInitNested(desc, window_number);
    02432     this->owner = v->owner;
    02433     this->GetWidget<NWidgetViewport>(VVW_WIDGET_VIEWPORT)->InitializeViewport(this, this->window_number | (1 << 31), _vehicle_view_zoom_levels[v->type]);
    02434
    02435     this->GetWidget<NWidgetCore>(VVW_WIDGET_START_STOP_VEH)->tool_tip   = STR_VEHICLE_VIEW_TRAIN_STATE_START_STOP_TOOLTIP + v->type;
    02436     this->GetWidget<NWidgetCore>(VVW_WIDGET_CENTER_MAIN_VIEH)->tool_tip = STR_VEHICLE_VIEW_TRAIN_LOCATION_TOOLTIP + v->type;
    02437     this->GetWidget<NWidgetCore>(VVW_WIDGET_REFIT_VEH)->tool_tip        = STR_VEHICLE_VIEW_TRAIN_REFIT_TOOLTIP + v->type;
    02438     this->GetWidget<NWidgetCore>(VVW_WIDGET_GOTO_DEPOT)->tool_tip       = STR_VEHICLE_VIEW_TRAIN_SEND_TO_DEPOT_TOOLTIP + v->type;
    02439     this->GetWidget<NWidgetCore>(VVW_WIDGET_SHOW_ORDERS)->tool_tip      = STR_VEHICLE_VIEW_TRAIN_ORDERS_TOOLTIP + v->type;
    02440     this->GetWidget<NWidgetCore>(VVW_WIDGET_SHOW_DETAILS)->tool_tip     = STR_VEHICLE_VIEW_TRAIN_SHOW_DETAILS_TOOLTIP + v->type;
    02441     this->GetWidget<NWidgetCore>(VVW_WIDGET_CLONE_VEH)->tool_tip        = STR_VEHICLE_VIEW_CLONE_TRAIN_INFO + v->type;
    02442   }
    02443
    02444   ~VehicleViewWindow()
    02445   {
    02446     DeleteWindowById(WC_VEHICLE_ORDERS, this->window_number, false);
    02447     DeleteWindowById(WC_VEHICLE_REFIT, this->window_number, false);
    02448     DeleteWindowById(WC_VEHICLE_DETAILS, this->window_number, false);
    02449     DeleteWindowById(WC_VEHICLE_TIMETABLE, this->window_number, false);
    02450   }
    02451
    02452   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
    02453   {
    02454     const Vehicle *v = Vehicle::Get(this->window_number);
    02455     switch (widget) {
    02456       case VVW_WIDGET_FORCE_PROCEED:
    02457         if (v->type != VEH_TRAIN) {
    02458           size->height = 0;
    02459           size->width = 0;
    02460         }
    02461         break;
    02462
    02463       case VVW_WIDGET_VIEWPORT:
    02464         size->width = VV_INITIAL_VIEWPORT_WIDTH;
    02465         size->height = (v->type == VEH_TRAIN) ? VV_INITIAL_VIEWPORT_HEIGHT_TRAIN : VV_INITIAL_VIEWPORT_HEIGHT;
    02466         break;
    02467     }
    02468   }
    02469
    02470   virtual void OnPaint()
    02471   {
    02472     const Vehicle *v = Vehicle::Get(this->window_number);
    02473     bool is_localcompany = v->owner == _local_company;
    02474     bool can_control = IsVehicleControlAllowed(v, _local_company);
    02475     bool refitable_and_stopped_in_depot = IsVehicleRefitable(v);
    02476
    02477     this->SetWidgetDisabledState(VVW_WIDGET_GOTO_DEPOT, !is_localcompany);
    02478     this->SetWidgetDisabledState(VVW_WIDGET_REFIT_VEH, !refitable_and_stopped_in_depot || !is_localcompany);
    02479     this->SetWidgetDisabledState(VVW_WIDGET_CLONE_VEH, !is_localcompany);
    02480
    02481     if (v->type == VEH_TRAIN) {
    02482       this->SetWidgetLoweredState(VVW_WIDGET_FORCE_PROCEED, Train::From(v)->force_proceed == TFP_SIGNAL);
    02483       this->SetWidgetDisabledState(VVW_WIDGET_FORCE_PROCEED, !can_control);
    02484       this->SetWidgetDisabledState(VVW_WIDGET_TURN_AROUND, !can_control);
    02485     }
    02486
    02487     this->DrawWidgets();
    02488   }
    02489
    02490   virtual void SetStringParameters(int widget) const
    02491   {
    02492     if (widget != VVW_WIDGET_CAPTION) return;
    02493
    02494     const Vehicle *v = Vehicle::Get(this->window_number);
    02495     SetDParam(0, v->index);
    02496   }
    02497
    02498   virtual void DrawWidget(const Rect &r, int widget) const
    02499   {
    02500     if (widget != VVW_WIDGET_START_STOP_VEH) return;
    02501
    02502     const Vehicle *v = Vehicle::Get(this->window_number);
    02503     StringID str;
    02504     if (v->vehstatus & VS_CRASHED) {
    02505       str = STR_VEHICLE_STATUS_CRASHED;
    02506     } else if (v->breakdown_ctr == 1 || (v->type == VEH_TRAIN && Train::From(v)->flags & VRF_IS_BROKEN)) {
    02507       if (_settings_game.vehicle.improved_breakdowns) {
    02508         str = STR_VEHICLE_STATUS_BROKEN_DOWN_VEL;
    02509         SetDParam(2, v->GetDisplaySpeed());
    02510       } else {
    02511         str = STR_VEHICLE_STATUS_BROKEN_DOWN;
    02512       }
    02513
    02514       if (v->type == VEH_AIRCRAFT) {
    02515         SetDParam(0, _aircraft_breakdown_strings[v->breakdown_type]);
    02516         if (v->breakdown_type == BREAKDOWN_AIRCRAFT_SPEED) {
    02517           SetDParam(1, v->breakdown_severity << 3);
    02518         } else {
    02519           SetDParam(1, v->current_order.GetDestination());
    02520         }
    02521       } else {
    02522         const Vehicle *w = (v->type == VEH_TRAIN) ? GetMostSeverelyBrokenEngine(Train::From(v)) : v;
    02523         SetDParam(0, STR_BREAKDOWN_TYPE_CRITICAL + w->breakdown_type);
    02524
    02525         if (w->breakdown_type == BREAKDOWN_LOW_SPEED) {
    02526           SetDParam(1, min( w->First()->GetDisplayMaxSpeed(), w->breakdown_severity >> (v->type == VEH_TRAIN ? 0 : 1 )));
    02527         } else if (w->breakdown_type == BREAKDOWN_LOW_POWER) {
    02528           SetDParam(1, w->breakdown_severity * 100 / 256);
    02529         }
    02530       }
    02531     } else if (v->vehstatus & VS_STOPPED) {
    02532       if (v->type == VEH_TRAIN) {
    02533         if (v->cur_speed == 0) {
    02534           if (Train::From(v)->gcache.cached_power == 0) {
    02535             str = STR_VEHICLE_STATUS_TRAIN_NO_POWER;
    02536           } else {
    02537             str = STR_VEHICLE_STATUS_STOPPED;
    02538           }
    02539         } else {
    02540           SetDParam(0, v->GetDisplaySpeed());
    02541           str = STR_VEHICLE_STATUS_TRAIN_STOPPING + _settings_client.gui.vehicle_speed;
    02542         }
    02543       } else { // no train
    02544         str = STR_VEHICLE_STATUS_STOPPED;
    02545       }
    02546     } else if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_TRAIN_STUCK) && !v->current_order.IsType(OT_LOADING)) {
    02547       str = STR_VEHICLE_STATUS_TRAIN_STUCK;
    02548     } else { // vehicle is in a "normal" state, show current order
    02549       switch (v->current_order.GetType()) {
    02550         case OT_GOTO_STATION: {
    02551           SetDParam(0, v->current_order.GetDestination());
    02552           SetDParam(1, v->GetDisplaySpeed());
    02553           str = STR_VEHICLE_STATUS_HEADING_FOR_STATION + _settings_client.gui.vehicle_speed;
    02554           break;
    02555         }
    02556
    02557         case OT_GOTO_DEPOT: {
    02558           SetDParam(0, v->type);
    02559           SetDParam(1, v->current_order.GetDestination());
    02560           SetDParam(2, v->GetDisplaySpeed());
    02561           if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
    02562             /* This case *only* happens when multiple nearest depot orders
    02563              * follow eachother (including an order list only one order: a
    02564              * nearest depot order) and there are no reachable depots.
    02565              * It is primarily to guard for the case that there is no
    02566              * depot with index 0, which would be used as fallback for
    02567              * evaluating the string in the status bar. */
    02568             str = STR_EMPTY;
    02569           } else if (v->current_order.GetDepotActionType() & ODATFB_HALT) {
    02570             str = STR_VEHICLE_STATUS_HEADING_FOR_DEPOT + _settings_client.gui.vehicle_speed;
    02571           } else {
    02572             str = STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_SERVICE + _settings_client.gui.vehicle_speed;
    02573           }
    02574           break;
    02575         }
    02576
    02577         case OT_LOADING:
    02578           str = STR_VEHICLE_STATUS_LOADING_UNLOADING;
    02579           break;
    02580
    02581         case OT_GOTO_WAYPOINT: {
    02582           assert(v->type == VEH_TRAIN || v->type == VEH_SHIP);
    02583           SetDParam(0, v->current_order.GetDestination());
    02584           str = STR_VEHICLE_STATUS_HEADING_FOR_WAYPOINT + _settings_client.gui.vehicle_speed;
    02585           SetDParam(1, v->GetDisplaySpeed());
    02586           break;
    02587         }
    02588
    02589         case OT_LEAVESTATION:
    02590           if (v->type != VEH_AIRCRAFT) {
    02591             str = STR_VEHICLE_STATUS_LEAVING;
    02592             break;
    02593           }
    02594           /* FALL THROUGH, if aircraft. Does this even happen? */
    02595
    02596         default:
    02597           if (v->GetNumManualOrders() == 0) {
    02598             str = STR_VEHICLE_STATUS_NO_ORDERS + _settings_client.gui.vehicle_speed;
    02599             SetDParam(0, v->GetDisplaySpeed());
    02600           } else {
    02601             str = STR_EMPTY;
    02602           }
    02603           break;
    02604       }
    02605     }
    02606
    02607     /* draw the flag plus orders */
    02608     DrawSprite(v->vehstatus & VS_STOPPED ? SPR_FLAG_VEH_STOPPED : SPR_FLAG_VEH_RUNNING, PAL_NONE, WD_FRAMERECT_LEFT, r.top + WD_FRAMERECT_TOP);
    02609     DrawString(r.left + WD_FRAMERECT_LEFT + 6, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, str, TC_FROMSTRING, SA_HOR_CENTER);
    02610   }
    02611
    02612   virtual void OnClick(Point pt, int widget, int click_count)
    02613   {
    02614     const Vehicle *v = Vehicle::Get(this->window_number);
    02615
    02616     switch (widget) {
    02617       case VVW_WIDGET_START_STOP_VEH: // start stop
    02618         if (_ctrl_pressed) {
    02619           /* Scroll to current order destination */
    02620           TileIndex tile = v->current_order.GetLocation(v);
    02621           if (tile != INVALID_TILE) ScrollMainWindowToTile(tile);
    02622         } else {
    02623           /* Start/Stop */
    02624           StartStopVehicle(v, false);
    02625         }
    02626         break;
    02627       case VVW_WIDGET_CENTER_MAIN_VIEH: {// center main view
    02628         const Window *mainwindow = FindWindowById(WC_MAIN_WINDOW, 0);
    02629         /* code to allow the main window to 'follow' the vehicle if the ctrl key is pressed */
    02630         if (_ctrl_pressed && mainwindow->viewport->zoom == ZOOM_LVL_NORMAL) {
    02631           mainwindow->viewport->follow_vehicle = v->index;
    02632         } else {
    02633           ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos);
    02634         }
    02635         break;
    02636       }
    02637
    02638       case VVW_WIDGET_GOTO_DEPOT: // goto hangar
    02639         DoCommandP(v->tile, v->index | (_ctrl_pressed ? DEPOT_SERVICE : 0U), 0, GetCmdSendToDepot(v));
    02640         break;
    02641       case VVW_WIDGET_REFIT_VEH: // refit
    02642         ShowVehicleRefitWindow(v, INVALID_VEH_ORDER_ID, this);
    02643         break;
    02644       case VVW_WIDGET_SHOW_ORDERS: // show orders
    02645         if (_ctrl_pressed) {
    02646           ShowTimetableWindow(v);
    02647         } else {
    02648           ShowOrdersWindow(v);
    02649         }
    02650         break;
    02651       case VVW_WIDGET_SHOW_DETAILS: // show details
    02652         ShowVehicleDetailsWindow(v);
    02653         break;
    02654       case VVW_WIDGET_CLONE_VEH: // clone vehicle
    02655         DoCommandP(v->tile, v->index, _ctrl_pressed ? 1 : 0,
    02656                     _vehicle_command_translation_table[VCT_CMD_CLONE_VEH][v->type],
    02657                     CcCloneVehicle);
    02658         break;
    02659       case VVW_WIDGET_TURN_AROUND: // turn around
    02660         assert(v->IsGroundVehicle());
    02661         DoCommandP(v->tile, v->index, 0,
    02662                     _vehicle_command_translation_table[VCT_CMD_TURN_AROUND][v->type]);
    02663         break;
    02664       case VVW_WIDGET_FORCE_PROCEED: // force proceed
    02665         assert(v->type == VEH_TRAIN);
    02666         DoCommandP(v->tile, v->index, 0, CMD_FORCE_TRAIN_PROCEED | CMD_MSG(STR_ERROR_CAN_T_MAKE_TRAIN_PASS_SIGNAL));
    02667         break;
    02668     }
    02669   }
    02670
    02671   virtual void OnResize()
    02672   {
    02673     if (this->viewport != NULL) {
    02674       NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(VVW_WIDGET_VIEWPORT);
    02675       nvp->UpdateViewportCoordinates(this);
    02676     }
    02677   }
    02678
    02679   virtual void OnTick()
    02680   {
    02681     const Vehicle *v = Vehicle::Get(this->window_number);
    02682     bool veh_stopped = v->IsStoppedInDepot();
    02683
    02684     /* Widget VVW_WIDGET_GOTO_DEPOT must be hidden if the vehicle is already stopped in depot.
    02685      * Widget VVW_WIDGET_CLONE_VEH should then be shown, since cloning is allowed only while in depot and stopped.
    02686      */
    02687     PlaneSelections plane = veh_stopped ? SEL_DC_CLONE : SEL_DC_GOTO_DEPOT;
    02688     NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(VVW_WIDGET_SELECT_DEPOT_CLONE); // Selection widget 'send to depot' / 'clone'.
    02689     if (nwi->shown_plane + SEL_DC_BASEPLANE != plane) {
    02690       this->SelectPlane(plane);
    02691       this->SetWidgetDirty(VVW_WIDGET_SELECT_DEPOT_CLONE);
    02692     }
    02693     /* The same system applies to widget VVW_WIDGET_REFIT_VEH and VVW_WIDGET_TURN_AROUND.*/
    02694     if (v->IsGroundVehicle()) {
    02695       PlaneSelections plane = veh_stopped ? SEL_RT_REFIT : SEL_RT_TURN_AROUND;
    02696       NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(VVW_WIDGET_SELECT_REFIT_TURN);
    02697       if (nwi->shown_plane + SEL_RT_BASEPLANE != plane) {
    02698         this->SelectPlane(plane);
    02699         this->SetWidgetDirty(VVW_WIDGET_SELECT_REFIT_TURN);
    02700       }
    02701     }
    02702   }
    02703
    02709   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
    02710   {
    02711     if (data == -666) {
    02712       /* Autoreplace replaced the vehicle.
    02713        * Nothing to do for this window. */
    02714       return;
    02715     }
    02716   }
    02717
    02718   virtual bool IsNewGRFInspectable() const
    02719   {
    02720     return ::IsNewGRFInspectable(GetGrfSpecFeature(Vehicle::Get(this->window_number)->type), this->window_number);
    02721   }
    02722
    02723   virtual void ShowNewGRFInspectWindow() const
    02724   {
    02725 		::ShowNewGRFInspectWindow(GetGrfSpecFeature(Vehicle::Get(this->window_number)->type), this->window_number);
    02726   }
    02727 };
    02728
    02729
    02731 void ShowVehicleViewWindow(const Vehicle *v)
    02732 {
    02733   AllocateWindowDescFront<VehicleViewWindow>((v->type == VEH_TRAIN) ? &_train_view_desc : &_vehicle_view_desc, v->index);
    02734 }
    02735
    02741 bool VehicleClicked(const Vehicle *v)
    02742 {
    02743   assert(v != NULL);
    02744   if (!(_thd.place_mode & HT_VEHICLE)) return false;
    02745
    02746   v = v->First();
    02747   if (!v->IsPrimaryVehicle()) return false;
    02748
    02749   _thd.GetCallbackWnd()->OnVehicleSelect(v);
    02750   return true;
    02751 }
    02752
    02753 void StopGlobalFollowVehicle(const Vehicle *v)
    02754 {
    02755   Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
    02756   if (w != NULL && w->viewport->follow_vehicle == v->index) {
    02757     ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos, true); // lock the main view on the vehicle's last position
    02758     w->viewport->follow_vehicle = INVALID_VEHICLE;
    02759   }
    02760 }
    02761
    02762
    02770 void CcBuildPrimaryVehicle(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
    02771 {
    02772   if (result.Failed()) return;
    02773
    02774   const Vehicle *v = Vehicle::Get(_new_vehicle_id);
    02775   ShowVehicleViewWindow(v);
    02776 }
    02777
    02783 int GetVehicleWidth(Vehicle *v)
    02784 {
    02785   int vehicle_width = 0;
    02786
    02787   switch (v->type) {
    02788     case VEH_TRAIN:
    02789       for (const Train *u = Train::From(v); u != NULL; u = u->Next()) {
    02790         vehicle_width += u->GetDisplayImageWidth();
    02791       }
    02792       break;
    02793
    02794     case VEH_ROAD:
    02795       for (const RoadVehicle *u = RoadVehicle::From(v); u != NULL; u = u->Next()) {
    02796         vehicle_width += u->GetDisplayImageWidth();
    02797       }
    02798       break;
    02799
    02800     default:
    02801       bool rtl = _current_text_dir == TD_RTL;
    02802       SpriteID sprite = v->GetImage(rtl ? DIR_E : DIR_W);
    02803       const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
    02804       vehicle_width = real_sprite->width;
    02805
    02806       break;
    02807   }
    02808
    02809   return vehicle_width;
    02810 }