vehicle_gui.cpp

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