vehicle_gui.cpp

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