# vehicle_gui.cpp

Go to the documentation of this file.

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