# vehicle_gui.cpp

Go to the documentation of this file.

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