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