Translations update
[openttd/fttd.git] / src / vehicle_gui.cpp
blob9c96cf70a324debc79b2c9bef905f2434103f20e
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
10 /** @file vehicle_gui.cpp The base GUI for all vehicles. */
12 #include "stdafx.h"
13 #include "debug.h"
14 #include "company_func.h"
15 #include "gui.h"
16 #include "textbuf_gui.h"
17 #include "command_func.h"
18 #include "vehicle_gui_base.h"
19 #include "viewport_func.h"
20 #include "newgrf_text.h"
21 #include "newgrf_debug.h"
22 #include "roadveh.h"
23 #include "train.h"
24 #include "aircraft.h"
25 #include "group_gui.h"
26 #include "strings_func.h"
27 #include "vehicle_func.h"
28 #include "autoreplace_gui.h"
29 #include "string.h"
30 #include "widgets/dropdown_func.h"
31 #include "timetable.h"
32 #include "articulated_vehicles.h"
33 #include "spritecache.h"
34 #include "core/geometry_func.hpp"
35 #include "company_base.h"
36 #include "engine_func.h"
37 #include "station_base.h"
38 #include "tilehighlight_func.h"
39 #include "zoom_func.h"
42 Sorting _sorting;
44 static GUIVehicleList::SortFunction VehicleNumberSorter;
45 static GUIVehicleList::SortFunction VehicleNameSorter;
46 static GUIVehicleList::SortFunction VehicleAgeSorter;
47 static GUIVehicleList::SortFunction VehicleProfitThisYearSorter;
48 static GUIVehicleList::SortFunction VehicleProfitLastYearSorter;
49 static GUIVehicleList::SortFunction VehicleCargoSorter;
50 static GUIVehicleList::SortFunction VehicleReliabilitySorter;
51 static GUIVehicleList::SortFunction VehicleMaxSpeedSorter;
52 static GUIVehicleList::SortFunction VehicleModelSorter;
53 static GUIVehicleList::SortFunction VehicleValueSorter;
54 static GUIVehicleList::SortFunction VehicleLengthSorter;
55 static GUIVehicleList::SortFunction VehicleTimeToLiveSorter;
56 static GUIVehicleList::SortFunction VehicleTimetableDelaySorter;
58 GUIVehicleList::SortFunction * const BaseVehicleListWindow::vehicle_sorter_funcs[] = {
59 &VehicleNumberSorter,
60 &VehicleNameSorter,
61 &VehicleAgeSorter,
62 &VehicleProfitThisYearSorter,
63 &VehicleProfitLastYearSorter,
64 &VehicleCargoSorter,
65 &VehicleReliabilitySorter,
66 &VehicleMaxSpeedSorter,
67 &VehicleModelSorter,
68 &VehicleValueSorter,
69 &VehicleLengthSorter,
70 &VehicleTimeToLiveSorter,
71 &VehicleTimetableDelaySorter,
74 const StringID BaseVehicleListWindow::vehicle_sorter_names[] = {
75 STR_SORT_BY_NUMBER,
76 STR_SORT_BY_NAME,
77 STR_SORT_BY_AGE,
78 STR_SORT_BY_PROFIT_THIS_YEAR,
79 STR_SORT_BY_PROFIT_LAST_YEAR,
80 STR_SORT_BY_TOTAL_CAPACITY_PER_CARGOTYPE,
81 STR_SORT_BY_RELIABILITY,
82 STR_SORT_BY_MAX_SPEED,
83 STR_SORT_BY_MODEL,
84 STR_SORT_BY_VALUE,
85 STR_SORT_BY_LENGTH,
86 STR_SORT_BY_LIFE_TIME,
87 STR_SORT_BY_TIMETABLE_DELAY,
88 INVALID_STRING_ID
91 const StringID BaseVehicleListWindow::vehicle_depot_name[] = {
92 STR_VEHICLE_LIST_SEND_TRAIN_TO_DEPOT,
93 STR_VEHICLE_LIST_SEND_ROAD_VEHICLE_TO_DEPOT,
94 STR_VEHICLE_LIST_SEND_SHIP_TO_DEPOT,
95 STR_VEHICLE_LIST_SEND_AIRCRAFT_TO_HANGAR
98 /**
99 * Get the number of digits the biggest unit number of a set of vehicles has.
100 * @param vehicles The list of vehicles.
101 * @return The number of digits to allocate space for.
103 uint GetUnitNumberDigits(VehicleList &vehicles)
105 uint unitnumber = 0;
106 for (const Vehicle **v = vehicles.Begin(); v != vehicles.End(); v++) {
107 unitnumber = max<uint>(unitnumber, (*v)->unitnumber);
110 if (unitnumber >= 10000) return 5;
111 if (unitnumber >= 1000) return 4;
112 if (unitnumber >= 100) return 3;
115 * When the smallest unit number is less than 10, it is
116 * quite likely that it will expand to become more than
117 * 10 quite soon.
119 return 2;
122 void BaseVehicleListWindow::BuildVehicleList()
124 if (!this->vehicles.NeedRebuild()) return;
126 DEBUG(misc, 3, "Building vehicle list type %d for company %d given index %d", this->vli.type, this->vli.company, this->vli.index);
128 GenerateVehicleSortList(&this->vehicles, this->vli);
130 this->unitnumber_digits = GetUnitNumberDigits(this->vehicles);
132 this->vehicles.RebuildDone();
133 this->vscroll->SetCount(this->vehicles.Length());
137 * Compute the size for the Action dropdown.
138 * @param show_autoreplace If true include the autoreplace item.
139 * @param show_group If true include group-related stuff.
140 * @return Required size.
142 Dimension BaseVehicleListWindow::GetActionDropdownSize(bool show_autoreplace, bool show_group)
144 Dimension d = {0, 0};
146 if (show_autoreplace) d = maxdim(d, GetStringBoundingBox(STR_VEHICLE_LIST_REPLACE_VEHICLES));
147 d = maxdim(d, GetStringBoundingBox(STR_VEHICLE_LIST_SEND_FOR_SERVICING));
148 d = maxdim(d, GetStringBoundingBox(this->vehicle_depot_name[this->vli.vtype]));
150 if (show_group) {
151 d = maxdim(d, GetStringBoundingBox(STR_GROUP_ADD_SHARED_VEHICLE));
152 d = maxdim(d, GetStringBoundingBox(STR_GROUP_REMOVE_ALL_VEHICLES));
155 return d;
159 * Display the Action dropdown window.
160 * @param show_autoreplace If true include the autoreplace item.
161 * @param show_group If true include group-related stuff.
162 * @return Itemlist for dropdown
164 DropDownList *BaseVehicleListWindow::BuildActionDropdownList(bool show_autoreplace, bool show_group)
166 DropDownList *list = new DropDownList();
168 if (show_autoreplace) *list->Append() = new DropDownListStringItem(STR_VEHICLE_LIST_REPLACE_VEHICLES, ADI_REPLACE, false);
169 *list->Append() = new DropDownListStringItem(STR_VEHICLE_LIST_SEND_FOR_SERVICING, ADI_SERVICE, false);
170 *list->Append() = new DropDownListStringItem(this->vehicle_depot_name[this->vli.vtype], ADI_DEPOT, false);
172 if (show_group) {
173 *list->Append() = new DropDownListStringItem(STR_GROUP_ADD_SHARED_VEHICLE, ADI_ADD_SHARED, false);
174 *list->Append() = new DropDownListStringItem(STR_GROUP_REMOVE_ALL_VEHICLES, ADI_REMOVE_ALL, false);
177 return list;
180 /* cached values for VehicleNameSorter to spare many GetString() calls */
181 static const Vehicle *_last_vehicle[2] = { NULL, NULL };
183 void BaseVehicleListWindow::SortVehicleList()
185 if (this->vehicles.Sort()) return;
187 /* invalidate cached values for name sorter - vehicle names could change */
188 _last_vehicle[0] = _last_vehicle[1] = NULL;
191 void DepotSortList(VehicleList *list)
193 if (list->Length() < 2) return;
194 QSortT(list->Begin(), list->Length(), &VehicleNumberSorter);
197 /** draw the vehicle profit button in the vehicle list window. */
198 static void DrawVehicleProfitButton(const Vehicle *v, int x, int y)
200 SpriteID spr;
202 /* draw profit-based coloured icons */
203 if (v->age <= VEHICLE_PROFIT_MIN_AGE) {
204 spr = SPR_PROFIT_NA;
205 } else if (v->GetDisplayProfitLastYear() < 0) {
206 spr = SPR_PROFIT_NEGATIVE;
207 } else if (v->GetDisplayProfitLastYear() < VEHICLE_PROFIT_THRESHOLD) {
208 spr = SPR_PROFIT_SOME;
209 } else {
210 spr = SPR_PROFIT_LOT;
212 DrawSprite(spr, PAL_NONE, x, y);
215 /** Maximum number of refit cycles we try, to prevent infinite loops. And we store only a byte anyway */
216 static const uint MAX_REFIT_CYCLE = 256;
219 * Get the best fitting subtype when 'cloning'/'replacing' \a v_from with \a v_for.
220 * All articulated parts of both vehicles are tested to find a possibly shared subtype.
221 * For \a v_for only vehicle refittable to \a dest_cargo_type are considered.
222 * @param v_from the vehicle to match the subtype from
223 * @param v_for the vehicle to get the subtype for
224 * @param dest_cargo_type Destination cargo type.
225 * @return the best sub type
227 byte GetBestFittingSubType(Vehicle *v_from, Vehicle *v_for, CargoID dest_cargo_type)
229 v_from = v_from->GetFirstEnginePart();
230 v_for = v_for->GetFirstEnginePart();
232 /* Create a list of subtypes used by the various parts of v_for */
233 static SmallVector<StringID, 4> subtypes;
234 subtypes.Clear();
235 for (; v_from != NULL; v_from = v_from->HasArticulatedPart() ? v_from->GetNextArticulatedPart() : NULL) {
236 const Engine *e_from = v_from->GetEngine();
237 if (!e_from->CanCarryCargo() || !HasBit(e_from->info.callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) continue;
238 subtypes.Include(GetCargoSubtypeText(v_from));
241 byte ret_refit_cyc = 0;
242 bool success = false;
243 if (subtypes.Length() > 0) {
244 /* Check whether any articulated part is refittable to 'dest_cargo_type' with a subtype listed in 'subtypes' */
245 for (Vehicle *v = v_for; v != NULL; v = v->HasArticulatedPart() ? v->GetNextArticulatedPart() : NULL) {
246 const Engine *e = v->GetEngine();
247 if (!e->CanCarryCargo() || !HasBit(e->info.callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) continue;
248 if (!HasBit(e->info.refit_mask, dest_cargo_type) && v->cargo_type != dest_cargo_type) continue;
250 CargoID old_cargo_type = v->cargo_type;
251 byte old_cargo_subtype = v->cargo_subtype;
253 /* Set the 'destination' cargo */
254 v->cargo_type = dest_cargo_type;
256 /* Cycle through the refits */
257 for (uint refit_cyc = 0; refit_cyc < MAX_REFIT_CYCLE; refit_cyc++) {
258 v->cargo_subtype = refit_cyc;
260 /* Make sure we don't pick up anything cached. */
261 v->First()->InvalidateNewGRFCache();
262 v->InvalidateNewGRFCache();
264 StringID subtype = GetCargoSubtypeText(v);
265 if (subtype == STR_EMPTY) break;
267 if (!subtypes.Contains(subtype)) continue;
269 /* We found something matching. */
270 ret_refit_cyc = refit_cyc;
271 success = true;
272 break;
275 /* Reset the vehicle's cargo type */
276 v->cargo_type = old_cargo_type;
277 v->cargo_subtype = old_cargo_subtype;
279 /* Make sure we don't taint the vehicle. */
280 v->First()->InvalidateNewGRFCache();
281 v->InvalidateNewGRFCache();
283 if (success) break;
287 return ret_refit_cyc;
290 /** Refit cargo window. */
291 struct RefitWindow : public Window {
292 /** Option to refit a vehicle chain */
293 struct RefitOption {
294 CargoID cargo; ///< Cargo to refit to
295 byte subtype; ///< Subcargo to use
296 StringID string; ///< GRF-local String to display for the cargo
299 * Inequality operator for #RefitOption.
300 * @param other Compare to this #RefitOption.
301 * @return True if both #RefitOption are different.
303 inline bool operator != (const RefitOption &other) const
305 return other.cargo != this->cargo || other.string != this->string;
309 * Equality operator for #RefitOption.
310 * @param other Compare to this #RefitOption.
311 * @return True if both #RefitOption are equal.
313 inline bool operator == (const RefitOption &other) const
315 return other.cargo == this->cargo && other.string == this->string;
319 typedef SmallVector<RefitOption, 32> SubtypeList; ///< List of refit subtypes associated to a cargo.
321 CargoID sel_cargo; ///< Selected cargo, or CT_INVALID for none
322 byte sel_subcargo; ///< Selected subcargo
323 RefitOption *cargo; ///< Refit option selected by #sel.
324 SubtypeList list[NUM_CARGO]; ///< List of refit subtypes available for each sorted cargo.
325 VehicleOrderID order; ///< If not #INVALID_VEH_ORDER_ID, selection is part of a refit order (rather than execute directly).
326 uint information_width; ///< Width required for correctly displaying all cargoes in the information panel.
327 Scrollbar *vscroll; ///< The main scrollbar.
328 Scrollbar *hscroll; ///< Only used for long vehicles.
329 int vehicle_width; ///< Width of the vehicle being drawn.
330 int sprite_left; ///< Left position of the vehicle sprite.
331 int sprite_right; ///< Right position of the vehicle sprite.
332 uint vehicle_margin; ///< Margin to use while selecting vehicles when the vehicle image is centered.
333 int click_x; ///< Position of the first click while dragging.
334 VehicleID selected_vehicle; ///< First vehicle in the current selection.
335 uint8 num_vehicles; ///< Number of selected vehicles.
336 bool auto_refit; ///< Select cargo for auto-refitting.
337 CargoMask cargo_mask; ///< Selected cargoes, when auto-refitting.
340 * Collects all (cargo, subcargo) refit options of a vehicle chain.
342 void BuildRefitList()
344 for (uint i = 0; i < NUM_CARGO; i++) this->list[i].Clear();
345 Vehicle *v = Vehicle::Get(this->window_number);
347 /* Check only the selected vehicles. */
348 VehicleSet vehicles_to_refit;
349 GetVehicleSet(vehicles_to_refit, Vehicle::Get(this->selected_vehicle), this->num_vehicles);
351 do {
352 if (v->type == VEH_TRAIN && !vehicles_to_refit.Contains(v->index)) continue;
353 const Engine *e = v->GetEngine();
354 uint32 cmask = e->info.refit_mask;
355 byte callback_mask = e->info.callback_mask;
357 /* Skip this engine if it does not carry anything */
358 if (!e->CanCarryCargo()) continue;
359 /* Skip this engine if we build the list for auto-refitting and engine doesn't allow it. */
360 if (this->auto_refit && !HasBit(e->info.misc_flags, EF_AUTO_REFIT)) continue;
362 /* Loop through all cargoes in the refit mask */
363 int current_index = 0;
364 const CargoSpec *cs;
365 FOR_ALL_SORTED_CARGOSPECS(cs) {
366 CargoID cid = cs->Index();
367 /* Skip cargo type if it's not listed */
368 if (!HasBit(cmask, cid)) {
369 current_index++;
370 continue;
373 bool first_vehicle = this->list[current_index].Length() == 0;
374 if (first_vehicle) {
375 /* Keeping the current subtype is always an option. It also serves as the option in case of no subtypes */
376 RefitOption *option = this->list[current_index].Append();
377 option->cargo = cid;
378 option->subtype = 0xFF;
379 option->string = STR_EMPTY;
382 /* Check the vehicle's callback mask for cargo suffixes.
383 * This is not supported for ordered refits, since subtypes only have a meaning
384 * for a specific vehicle at a specific point in time, which conflicts with shared orders,
385 * autoreplace, autorenew, clone, order restoration, ... */
386 if (this->order == INVALID_VEH_ORDER_ID && HasBit(callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) {
387 /* Make a note of the original cargo type. It has to be
388 * changed to test the cargo & subtype... */
389 CargoID temp_cargo = v->cargo_type;
390 byte temp_subtype = v->cargo_subtype;
392 v->cargo_type = cid;
394 for (uint refit_cyc = 0; refit_cyc < MAX_REFIT_CYCLE; refit_cyc++) {
395 v->cargo_subtype = refit_cyc;
397 /* Make sure we don't pick up anything cached. */
398 v->First()->InvalidateNewGRFCache();
399 v->InvalidateNewGRFCache();
401 StringID subtype = GetCargoSubtypeText(v);
403 if (first_vehicle) {
404 /* Append new subtype (don't add duplicates though) */
405 if (subtype == STR_EMPTY) break;
407 RefitOption option;
408 option.cargo = cid;
409 option.subtype = refit_cyc;
410 option.string = subtype;
411 this->list[current_index].Include(option);
412 } else {
413 /* Intersect the subtypes of earlier vehicles with the subtypes of this vehicle */
414 if (subtype == STR_EMPTY) {
415 /* No more subtypes for this vehicle, delete all subtypes >= refit_cyc */
416 SubtypeList &l = this->list[current_index];
417 /* 0xFF item is in front, other subtypes are sorted. So just truncate the list in the right spot */
418 for (uint i = 1; i < l.Length(); i++) {
419 if (l[i].subtype >= refit_cyc) {
420 l.Resize(i);
421 break;
424 break;
425 } else {
426 /* Check whether the subtype matches with the subtype of earlier vehicles. */
427 uint pos = 1;
428 SubtypeList &l = this->list[current_index];
429 while (pos < l.Length() && l[pos].subtype != refit_cyc) pos++;
430 if (pos < l.Length() && l[pos].string != subtype) {
431 /* String mismatch, remove item keeping the order */
432 l.ErasePreservingOrder(pos);
438 /* Reset the vehicle's cargo type */
439 v->cargo_type = temp_cargo;
440 v->cargo_subtype = temp_subtype;
442 /* And make sure we haven't tainted the cache */
443 v->First()->InvalidateNewGRFCache();
444 v->InvalidateNewGRFCache();
446 current_index++;
448 } while (v->IsGroundVehicle() && (v = v->Next()) != NULL);
452 * Refresh scrollbar after selection changed
454 void RefreshScrollbar()
456 uint scroll_row = 0;
457 uint row = 0;
459 for (uint i = 0; i < NUM_CARGO; i++) {
460 for (uint j = 0; j < this->list[i].Length(); j++) {
461 const RefitOption &refit = this->list[i][j];
463 /* Hide subtypes if sel_cargo does not match */
464 if (this->sel_cargo != i && refit.subtype != 0xFF) continue;
466 if (this->sel_cargo == i && this->sel_subcargo == j) scroll_row = row;
468 row++;
472 this->vscroll->SetCount(row);
473 if (scroll_row < row) this->vscroll->ScrollTowards(scroll_row);
477 * Select a row.
478 * @param click_row Clicked row
479 * @return Selected cargo id
481 CargoID SetSelection(uint click_row)
483 uint row = 0;
485 for (uint i = 0; i < NUM_CARGO; i++) {
486 for (uint j = 0; j < this->list[i].Length(); j++) {
487 const RefitOption &refit = this->list[i][j];
489 /* Hide subtypes if sel_cargo does not match */
490 if (this->sel_cargo != i && refit.subtype != 0xFF) continue;
492 if (row == click_row) {
493 this->sel_cargo = i;
494 this->sel_subcargo = j;
495 return refit.cargo;
498 row++;
502 this->sel_cargo = CT_INVALID;
503 this->sel_subcargo = 0;
504 return CT_INVALID;
508 * Gets the #RefitOption placed in the selected index.
509 * @return Pointer to the #RefitOption currently in use.
511 RefitOption *GetRefitOption()
513 if (this->sel_cargo == CT_INVALID) return NULL;
515 SubtypeList &l = this->list[this->sel_cargo];
516 if (this->sel_subcargo >= l.Length()) return NULL;
518 return &l[this->sel_subcargo];
521 RefitWindow (WindowDesc *desc, const Vehicle *v, VehicleOrderID order,
522 bool auto_refit, CargoMask cargo_mask = 0) : Window(desc)
524 assert (!auto_refit || (order != INVALID_VEH_ORDER_ID));
526 this->sel_cargo = CT_INVALID;
527 this->sel_subcargo = 0;
528 this->auto_refit = auto_refit;
529 this->cargo_mask = cargo_mask;
530 this->order = order;
531 this->CreateNestedTree();
533 this->vscroll = this->GetScrollbar(WID_VR_SCROLLBAR);
534 this->hscroll = (v->IsGroundVehicle() ? this->GetScrollbar(WID_VR_HSCROLLBAR) : NULL);
535 this->GetWidget<NWidgetCore>(WID_VR_SELECT_HEADER)->tool_tip = STR_REFIT_TRAIN_LIST_TOOLTIP + v->type;
536 this->GetWidget<NWidgetCore>(WID_VR_MATRIX)->tool_tip = STR_REFIT_TRAIN_LIST_TOOLTIP + v->type;
537 NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_VR_REFIT);
538 nwi->widget_data = STR_REFIT_TRAIN_REFIT_BUTTON + v->type;
539 nwi->tool_tip = STR_REFIT_TRAIN_REFIT_TOOLTIP + v->type;
540 this->GetWidget<NWidgetStacked>(WID_VR_SHOW_HSCROLLBAR)->SetDisplayedPlane(v->IsGroundVehicle() ? 0 : SZSP_HORIZONTAL);
541 this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY)->tool_tip = (v->type == VEH_TRAIN) ? STR_REFIT_SELECT_VEHICLES_TOOLTIP : STR_NULL;
543 this->FinishInitNested(v->index);
544 this->owner = v->owner;
546 this->SetWidgetDisabledState (WID_VR_REFIT, !auto_refit && (this->sel_cargo == CT_INVALID));
549 virtual void OnInit()
551 if (this->cargo != NULL) {
552 /* Store the RefitOption currently in use. */
553 RefitOption current_refit_option = *(this->cargo);
555 /* Rebuild the refit list */
556 this->BuildRefitList();
557 this->sel_cargo = CT_INVALID;
558 this->sel_subcargo = 0;
559 this->cargo = NULL;
560 for (uint i = 0; this->cargo == NULL && i < NUM_CARGO; i++) {
561 for (uint j = 0; j < list[i].Length(); j++) {
562 if (list[i][j] == current_refit_option) {
563 this->sel_cargo = i;
564 this->sel_subcargo = j;
565 this->cargo = &list[i][j];
566 break;
571 this->SetWidgetDisabledState (WID_VR_REFIT, !this->auto_refit && (this->sel_cargo == CT_INVALID));
572 this->RefreshScrollbar();
573 } else {
574 /* Rebuild the refit list */
575 this->OnInvalidateData(VIWD_CONSIST_CHANGED);
579 virtual void OnPaint()
581 /* Determine amount of items for scroller. */
582 if (this->hscroll != NULL) this->hscroll->SetCount(this->vehicle_width);
584 /* Calculate sprite position. */
585 NWidgetCore *vehicle_panel_display = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY);
586 int sprite_width = max(0, ((int)vehicle_panel_display->current_x - this->vehicle_width) / 2);
587 this->sprite_left = vehicle_panel_display->pos_x;
588 this->sprite_right = vehicle_panel_display->pos_x + vehicle_panel_display->current_x - 1;
589 if (_current_text_dir == TD_RTL) {
590 this->sprite_right -= sprite_width;
591 this->vehicle_margin = vehicle_panel_display->current_x - sprite_right;
592 } else {
593 this->sprite_left += sprite_width;
594 this->vehicle_margin = sprite_left;
597 this->DrawWidgets();
600 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
602 switch (widget) {
603 case WID_VR_MATRIX:
604 resize->height = WD_MATRIX_TOP + FONT_HEIGHT_NORMAL + WD_MATRIX_BOTTOM;
605 size->height = resize->height * 8;
606 break;
608 case WID_VR_VEHICLE_PANEL_DISPLAY:
609 size->height = ScaleGUITrad(GetVehicleHeight(Vehicle::Get(this->window_number)->type));
610 break;
612 case WID_VR_INFO:
613 size->width = WD_FRAMERECT_LEFT + this->information_width + WD_FRAMERECT_RIGHT;
614 break;
616 case WID_VR_CLEAR:
617 if (!auto_refit) {
618 size->width = 0;
619 resize->width = 0;
620 fill->width = 0;
622 break;
626 virtual void SetStringParameters(int widget) const
628 if (widget == WID_VR_CAPTION) SetDParam(0, Vehicle::Get(this->window_number)->index);
632 * Gets the #StringID to use for displaying capacity.
633 * @param Cargo and cargo subtype to check for capacity.
634 * @return INVALID_STRING_ID if there is no capacity. StringID to use in any other case.
635 * @post String parameters have been set.
637 StringID GetCapacityString(RefitOption *option) const
639 assert(_current_company == _local_company);
640 Vehicle *v = Vehicle::Get(this->window_number);
641 CommandCost cost = DoCommand(v->tile, this->selected_vehicle, option->cargo | (int)this->auto_refit << 6 | option->subtype << 8 |
642 this->num_vehicles << 16, DC_QUERY_COST, CMD_REFIT_VEHICLE);
644 if (cost.Failed()) return INVALID_STRING_ID;
646 SetDParam(0, option->cargo);
647 SetDParam(1, _returned_refit_capacity);
649 Money money = cost.GetCost();
650 if (_returned_mail_refit_capacity > 0) {
651 SetDParam(2, CT_MAIL);
652 SetDParam(3, _returned_mail_refit_capacity);
653 if (money <= 0) {
654 SetDParam(4, -money);
655 return STR_REFIT_NEW_CAPACITY_INCOME_FROM_AIRCRAFT_REFIT;
656 } else {
657 SetDParam(4, money);
658 return STR_REFIT_NEW_CAPACITY_COST_OF_AIRCRAFT_REFIT;
660 } else {
661 if (money <= 0) {
662 SetDParam(2, -money);
663 return STR_REFIT_NEW_CAPACITY_INCOME_FROM_REFIT;
664 } else {
665 SetDParam(2, money);
666 return STR_REFIT_NEW_CAPACITY_COST_OF_REFIT;
672 * Draw the list of available refit options for a consist and highlight the selected refit option (if any).
673 * @param r Rectangle of the matrix widget.
675 void DrawRefitWidget (const Rect &r) const
677 const SubtypeList *list = this->list;
678 CargoID sel_cargo = this->sel_cargo;
679 uint pos = this->vscroll->GetPosition();
680 uint limit = pos + this->vscroll->GetCapacity();
681 uint delta = this->resize.step_height;
683 uint y = r.top + WD_MATRIX_TOP;
684 uint current = 0;
686 SpriteID spr1, spr2;
687 if (this->auto_refit) {
688 spr1 = SPR_BOX_EMPTY;
689 spr2 = SPR_BOX_CHECKED;
690 } else {
691 spr1 = SPR_CIRCLE_FOLDED;
692 spr2 = SPR_CIRCLE_UNFOLDED;
694 uint iconwidth = max (GetSpriteSize(spr1).width, GetSpriteSize(spr2).width);
695 uint iconheight = GetSpriteSize(spr1).height;
696 int linecolour = _colour_gradient[COLOUR_ORANGE][4];
698 bool rtl = _current_text_dir == TD_RTL;
700 int iconleft = rtl ? r.right - WD_MATRIX_RIGHT - iconwidth : r.left + WD_MATRIX_LEFT;
701 int iconcenter = rtl ? r.right - WD_MATRIX_RIGHT - iconwidth / 2 : r.left + WD_MATRIX_LEFT + iconwidth / 2;
702 int iconinner = rtl ? r.right - WD_MATRIX_RIGHT - iconwidth : r.left + WD_MATRIX_LEFT + iconwidth;
704 int textleft = r.left + WD_MATRIX_LEFT + (rtl ? 0 : iconwidth + 4);
705 int textright = r.right - WD_MATRIX_RIGHT - (rtl ? iconwidth + 4 : 0);
707 /* Draw the list of subtypes for each cargo, and find the selected refit option (by its position). */
708 for (uint i = 0; current < limit && i < NUM_CARGO; i++) {
709 for (uint j = 0; current < limit && j < list[i].Length(); j++) {
710 const RefitOption &refit = list[i][j];
712 /* Hide subtypes if sel_cargo does not match */
713 if (sel_cargo != i && refit.subtype != 0xFF) continue;
715 /* Refit options with a position smaller than pos don't have to be drawn. */
716 if (current < pos) {
717 current++;
718 continue;
721 if (this->auto_refit) {
722 assert (list[i].Length() == 1);
723 assert (refit.subtype == 0xFF);
724 /* Draw checkbox */
725 DrawSprite (HasBit (this->cargo_mask, refit.cargo) ? SPR_BOX_CHECKED : SPR_BOX_EMPTY, PAL_NONE, iconleft, y + (FONT_HEIGHT_NORMAL - iconheight) / 2);
726 } else if (list[i].Length() > 1) {
727 if (refit.subtype != 0xFF) {
728 /* Draw tree lines */
729 int ycenter = y + FONT_HEIGHT_NORMAL / 2;
730 GfxDrawLine(iconcenter, y - WD_MATRIX_TOP, iconcenter, j == list[i].Length() - 1 ? ycenter : y - WD_MATRIX_TOP + delta - 1, linecolour);
731 GfxDrawLine(iconcenter, ycenter, iconinner, ycenter, linecolour);
732 } else {
733 /* Draw expand/collapse icon */
734 DrawSprite(sel_cargo == i ? SPR_CIRCLE_UNFOLDED : SPR_CIRCLE_FOLDED, PAL_NONE, iconleft, y + (FONT_HEIGHT_NORMAL - iconheight) / 2);
738 TextColour colour = (sel_cargo == i && this->sel_subcargo == j) ? TC_WHITE : TC_BLACK;
739 /* Get the cargo name. */
740 SetDParam(0, CargoSpec::Get(refit.cargo)->name);
741 SetDParam(1, refit.string);
742 DrawString(textleft, textright, y, STR_JUST_STRING_STRING, colour);
744 y += delta;
745 current++;
750 virtual void DrawWidget(const Rect &r, int widget) const
752 switch (widget) {
753 case WID_VR_VEHICLE_PANEL_DISPLAY: {
754 Vehicle *v = Vehicle::Get(this->window_number);
755 DrawVehicleImage(v, this->sprite_left + WD_FRAMERECT_LEFT, this->sprite_right - WD_FRAMERECT_RIGHT,
756 r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, this->hscroll != NULL ? this->hscroll->GetPosition() : 0);
758 /* Highlight selected vehicles. */
759 if (this->order != INVALID_VEH_ORDER_ID) break;
760 int x = 0;
761 switch (v->type) {
762 case VEH_TRAIN: {
763 VehicleSet vehicles_to_refit;
764 GetVehicleSet(vehicles_to_refit, Vehicle::Get(this->selected_vehicle), this->num_vehicles);
766 int left = INT32_MIN;
767 int width = 0;
769 for (Train *u = Train::From(v); u != NULL; u = u->Next()) {
770 /* Start checking. */
771 if (vehicles_to_refit.Contains(u->index) && left == INT32_MIN) {
772 left = x - this->hscroll->GetPosition() + r.left + this->vehicle_margin;
773 width = 0;
776 /* Draw a selection. */
777 if ((!vehicles_to_refit.Contains(u->index) || u->Next() == NULL) && left != INT32_MIN) {
778 if (u->Next() == NULL && vehicles_to_refit.Contains(u->index)) {
779 int current_width = u->GetDisplayImageWidth();
780 width += current_width;
781 x += current_width;
784 int right = Clamp(left + width, 0, r.right);
785 left = max(0, left);
787 if (_current_text_dir == TD_RTL) {
788 right = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY)->current_x - left;
789 left = right - width;
792 if (left != right) {
793 DrawFrameRect(left, r.top + WD_FRAMERECT_TOP, right, r.top + WD_FRAMERECT_TOP + ScaleGUITrad(14) - 1, COLOUR_WHITE, FR_BORDERONLY);
796 left = INT32_MIN;
799 int current_width = u->GetDisplayImageWidth();
800 width += current_width;
801 x += current_width;
803 break;
806 default: break;
808 break;
811 case WID_VR_MATRIX:
812 this->DrawRefitWidget (r);
813 break;
815 case WID_VR_INFO:
816 if (this->cargo != NULL) {
817 StringID string = this->GetCapacityString(this->cargo);
818 if (string != INVALID_STRING_ID) {
819 DrawStringMultiLine(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT,
820 r.top + WD_FRAMERECT_TOP, r.bottom - WD_FRAMERECT_BOTTOM, string);
823 break;
828 * Some data on this window has become invalid.
829 * @param data Information about the changed data.
830 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
832 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
834 switch (data) {
835 case VIWD_AUTOREPLACE: // Autoreplace replaced the vehicle; selected_vehicle became invalid.
836 case VIWD_CONSIST_CHANGED: { // The consist has changed; rebuild the entire list.
837 /* Clear the selection. */
838 Vehicle *v = Vehicle::Get(this->window_number);
839 this->selected_vehicle = v->index;
840 this->num_vehicles = UINT8_MAX;
841 /* FALL THROUGH */
844 case 2: { // The vehicle selection has changed; rebuild the entire list.
845 if (!gui_scope) break;
846 this->BuildRefitList();
848 /* The vehicle width has changed too. */
849 this->vehicle_width = GetVehicleWidth(Vehicle::Get(this->window_number), EIT_IN_DETAILS);
850 uint max_width = 0;
852 /* Check the width of all cargo information strings. */
853 for (uint i = 0; i < NUM_CARGO; i++) {
854 for (uint j = 0; j < this->list[i].Length(); j++) {
855 StringID string = this->GetCapacityString(&list[i][j]);
856 if (string != INVALID_STRING_ID) {
857 Dimension dim = GetStringBoundingBox(string);
858 max_width = max(dim.width, max_width);
863 if (this->information_width < max_width) {
864 this->information_width = max_width;
865 this->ReInit();
867 /* FALL THROUGH */
870 case 1: // A new cargo has been selected.
871 if (!gui_scope) break;
872 this->cargo = GetRefitOption();
873 this->RefreshScrollbar();
874 break;
878 int GetClickPosition(int click_x)
880 const NWidgetCore *matrix_widget = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY);
881 if (_current_text_dir == TD_RTL) click_x = matrix_widget->current_x - click_x;
882 click_x -= this->vehicle_margin;
883 if (this->hscroll != NULL) click_x += this->hscroll->GetPosition();
885 return click_x;
888 void SetSelectedVehicles(int drag_x)
890 drag_x = GetClickPosition(drag_x);
892 int left_x = min(this->click_x, drag_x);
893 int right_x = max(this->click_x, drag_x);
894 this->num_vehicles = 0;
896 Vehicle *v = Vehicle::Get(this->window_number);
897 /* Find the vehicle part that was clicked. */
898 switch (v->type) {
899 case VEH_TRAIN: {
900 /* Don't select anything if we are not clicking in the vehicle. */
901 if (left_x >= 0) {
902 const Train *u = Train::From(v);
903 bool start_counting = false;
904 for (; u != NULL; u = u->Next()) {
905 int current_width = u->GetDisplayImageWidth();
906 left_x -= current_width;
907 right_x -= current_width;
909 if (left_x < 0 && !start_counting) {
910 this->selected_vehicle = u->index;
911 start_counting = true;
913 /* Count the first vehicle, even if articulated part */
914 this->num_vehicles++;
915 } else if (start_counting && !u->IsArticulatedPart()) {
916 /* Do not count articulated parts */
917 this->num_vehicles++;
920 if (right_x < 0) break;
924 /* If the selection is not correct, clear it. */
925 if (this->num_vehicles != 0) {
926 if (_ctrl_pressed) this->num_vehicles = UINT8_MAX;
927 break;
929 /* FALL THROUGH */
932 default:
933 /* Clear the selection. */
934 this->selected_vehicle = v->index;
935 this->num_vehicles = UINT8_MAX;
936 break;
940 virtual void OnClick(Point pt, int widget, int click_count)
942 switch (widget) {
943 case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
944 if (this->order != INVALID_VEH_ORDER_ID) break;
945 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
946 this->click_x = GetClickPosition(pt.x - nwi->pos_x);
947 this->SetSelectedVehicles(pt.x - nwi->pos_x);
948 this->SetWidgetDirty(WID_VR_VEHICLE_PANEL_DISPLAY);
949 if (!_ctrl_pressed) {
950 SetObjectToPlaceWnd(SPR_CURSOR_MOUSE, PAL_NONE, HT_DRAG, this);
951 } else {
952 /* The vehicle selection has changed. */
953 this->InvalidateData(2);
955 break;
958 case WID_VR_MATRIX: { // listbox
959 uint row = this->vscroll->GetScrolledRowFromWidget (pt.y, this, WID_VR_MATRIX);
960 CargoID c = this->SetSelection(row);
962 if (this->auto_refit) {
963 if (c != CT_INVALID) {
964 const NWidgetBase *wid = this->GetWidget<NWidgetBase> (WID_VR_MATRIX);
965 uint offset = pt.x - wid->pos_x;
966 uint width = max (GetSpriteSize(SPR_BOX_EMPTY).width, GetSpriteSize(SPR_BOX_CHECKED).width) + 5;
967 if (_current_text_dir == TD_RTL ? offset > wid->current_x - width : offset < width) {
968 ToggleBit (this->cargo_mask, c);
971 this->InvalidateData (1);
972 break;
975 /* not auto-refit */
976 this->SetWidgetDisabledState(WID_VR_REFIT, this->sel_cargo == CT_INVALID);
977 this->InvalidateData(1);
979 if (click_count == 1) break;
980 /* FALL THROUGH */
983 case WID_VR_REFIT: // refit button
984 if (this->auto_refit) {
985 const Vehicle *v = Vehicle::Get(this->window_number);
986 if (DoCommandP(v->tile, v->index | this->order << 24, this->cargo_mask, CMD_ORDER_REFIT)) delete this;
987 } else if (this->cargo != NULL) {
988 const Vehicle *v = Vehicle::Get(this->window_number);
990 if (this->order == INVALID_VEH_ORDER_ID) {
991 bool delete_window = this->selected_vehicle == v->index && this->num_vehicles == UINT8_MAX;
992 if (DoCommandP(v->tile, this->selected_vehicle, this->cargo->cargo | this->cargo->subtype << 8 | this->num_vehicles << 16, CMD_REFIT_VEHICLE) && delete_window) delete this;
993 } else {
994 if (DoCommandP(v->tile, v->index | this->order << 24, 1 << this->cargo->cargo, CMD_ORDER_REFIT)) delete this;
997 break;
999 case WID_VR_CLEAR: // clear button
1000 assert (this->auto_refit);
1001 this->cargo_mask = 0;
1002 this->InvalidateData (1);
1003 break;
1007 virtual void OnMouseDrag(Point pt, int widget)
1009 switch (widget) {
1010 case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
1011 if (this->order != INVALID_VEH_ORDER_ID) break;
1012 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
1013 this->SetSelectedVehicles(pt.x - nwi->pos_x);
1014 this->SetWidgetDirty(WID_VR_VEHICLE_PANEL_DISPLAY);
1015 break;
1020 virtual void OnDragDrop(Point pt, int widget)
1022 switch (widget) {
1023 case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
1024 if (this->order != INVALID_VEH_ORDER_ID) break;
1025 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
1026 this->SetSelectedVehicles(pt.x - nwi->pos_x);
1027 this->InvalidateData(2);
1028 break;
1033 virtual void OnResize()
1035 this->vehicle_width = GetVehicleWidth(Vehicle::Get(this->window_number), EIT_IN_DETAILS);
1036 this->vscroll->SetCapacityFromWidget(this, WID_VR_MATRIX);
1037 if (this->hscroll != NULL) this->hscroll->SetCapacityFromWidget(this, WID_VR_VEHICLE_PANEL_DISPLAY);
1041 static const NWidgetPart _nested_vehicle_refit_widgets[] = {
1042 NWidget(NWID_HORIZONTAL),
1043 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1044 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VR_CAPTION), SetDataTip(STR_REFIT_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1045 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
1046 EndContainer(),
1047 /* Vehicle display + scrollbar. */
1048 NWidget(NWID_VERTICAL),
1049 NWidget(WWT_PANEL, COLOUR_GREY, WID_VR_VEHICLE_PANEL_DISPLAY), SetMinimalSize(228, 14), SetResize(1, 0), SetScrollbar(WID_VR_HSCROLLBAR), EndContainer(),
1050 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VR_SHOW_HSCROLLBAR),
1051 NWidget(NWID_HSCROLLBAR, COLOUR_GREY, WID_VR_HSCROLLBAR),
1052 EndContainer(),
1053 EndContainer(),
1054 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_VR_SELECT_HEADER), SetDataTip(STR_REFIT_TITLE, STR_NULL), SetResize(1, 0),
1055 /* Matrix + scrollbar. */
1056 NWidget(NWID_HORIZONTAL),
1057 NWidget(WWT_MATRIX, COLOUR_GREY, WID_VR_MATRIX), SetMinimalSize(228, 112), SetResize(1, 14), SetFill(1, 1), SetMatrixDataTip(1, 0, STR_NULL), SetScrollbar(WID_VR_SCROLLBAR),
1058 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VR_SCROLLBAR),
1059 EndContainer(),
1060 NWidget(WWT_PANEL, COLOUR_GREY, WID_VR_INFO), SetMinimalTextLines(2, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM), SetResize(1, 0), EndContainer(),
1061 NWidget(NWID_HORIZONTAL),
1062 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
1063 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VR_CLEAR), SetDataTip(STR_REFIT_CLEAR, STR_REFIT_CLEAR_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
1064 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VR_REFIT), SetFill(1, 0), SetResize(1, 0),
1065 EndContainer(),
1066 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
1067 EndContainer(),
1070 static WindowDesc _vehicle_refit_desc(
1071 WDP_AUTO, "view_vehicle_refit", 240, 174,
1072 WC_VEHICLE_REFIT, WC_VEHICLE_VIEW,
1073 WDF_CONSTRUCTION,
1074 _nested_vehicle_refit_widgets, lengthof(_nested_vehicle_refit_widgets)
1078 * Show the refit window for a vehicle
1079 * @param parent the parent window of the refit window
1080 * @param *v The vehicle to show the refit window for
1081 * @param order of the vehicle to assign refit to, or INVALID_VEH_ORDER_ID to refit the vehicle now
1082 * @param auto_refit Choose cargo for auto-refitting
1083 * @param mask Initial cargo mask of allowed refits for auto-refitting
1085 void ShowVehicleRefitWindow (Window *parent, const Vehicle *v,
1086 VehicleOrderID order, bool auto_refit, CargoMask mask)
1088 DeleteWindowById(WC_VEHICLE_REFIT, v->index);
1089 RefitWindow *w = new RefitWindow (&_vehicle_refit_desc, v, order,
1090 auto_refit, mask);
1091 w->parent = parent;
1094 /** Display list of cargo types of the engine, for the purchase information window */
1095 uint ShowRefitOptionsList(int left, int right, int y, EngineID engine)
1097 /* List of cargo types of this engine */
1098 uint32 cmask = GetUnionOfArticulatedRefitMasks(engine, false);
1099 /* List of cargo types available in this climate */
1100 uint32 lmask = _cargo_mask;
1102 /* Draw nothing if the engine is not refittable */
1103 if (HasAtMostOneBit(cmask)) return y;
1105 if (cmask == lmask) {
1106 /* Engine can be refitted to all types in this climate */
1107 SetDParam(0, STR_PURCHASE_INFO_ALL_TYPES);
1108 } else {
1109 /* Check if we are able to refit to more cargo types and unable to. If
1110 * so, invert the cargo types to list those that we can't refit to. */
1111 if (CountBits(cmask ^ lmask) < CountBits(cmask) && CountBits(cmask ^ lmask) <= 7) {
1112 cmask ^= lmask;
1113 SetDParam(0, STR_PURCHASE_INFO_ALL_BUT);
1114 } else {
1115 SetDParam(0, STR_JUST_CARGO_LIST);
1117 SetDParam(1, cmask);
1120 return DrawStringMultiLine(left, right, y, INT32_MAX, STR_PURCHASE_INFO_REFITTABLE_TO);
1123 /** Get the cargo subtype text from NewGRF for the vehicle details window. */
1124 StringID GetCargoSubtypeText(const Vehicle *v)
1126 if (HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) {
1127 uint16 cb = GetVehicleCallback(CBID_VEHICLE_CARGO_SUFFIX, 0, 0, v->engine_type, v);
1128 if (cb != CALLBACK_FAILED) {
1129 if (cb > 0x400) ErrorUnknownCallbackResult(v->GetGRFID(), CBID_VEHICLE_CARGO_SUFFIX, cb);
1130 if (cb >= 0x400 || (v->GetGRF()->grf_version < 8 && cb == 0xFF)) cb = CALLBACK_FAILED;
1132 if (cb != CALLBACK_FAILED) {
1133 return GetGRFStringID(v->GetGRFID(), 0xD000 + cb);
1136 return STR_EMPTY;
1139 /** Sort vehicles by their number */
1140 static int CDECL VehicleNumberSorter(const Vehicle * const *a, const Vehicle * const *b)
1142 return (*a)->unitnumber - (*b)->unitnumber;
1145 /** Sort vehicles by their name */
1146 static int CDECL VehicleNameSorter(const Vehicle * const *a, const Vehicle * const *b)
1148 static char last_name[2][64];
1150 if (*a != _last_vehicle[0]) {
1151 _last_vehicle[0] = *a;
1152 SetDParam(0, (*a)->index);
1153 GetString (last_name[0], STR_VEHICLE_NAME);
1156 if (*b != _last_vehicle[1]) {
1157 _last_vehicle[1] = *b;
1158 SetDParam(0, (*b)->index);
1159 GetString (last_name[1], STR_VEHICLE_NAME);
1162 int r = strnatcmp(last_name[0], last_name[1]); // Sort by name (natural sorting).
1163 return (r != 0) ? r : VehicleNumberSorter(a, b);
1166 /** Sort vehicles by their age */
1167 static int CDECL VehicleAgeSorter(const Vehicle * const *a, const Vehicle * const *b)
1169 int r = (*a)->age - (*b)->age;
1170 return (r != 0) ? r : VehicleNumberSorter(a, b);
1173 /** Sort vehicles by this year profit */
1174 static int CDECL VehicleProfitThisYearSorter(const Vehicle * const *a, const Vehicle * const *b)
1176 int r = ClampToI32((*a)->GetDisplayProfitThisYear() - (*b)->GetDisplayProfitThisYear());
1177 return (r != 0) ? r : VehicleNumberSorter(a, b);
1180 /** Sort vehicles by last year profit */
1181 static int CDECL VehicleProfitLastYearSorter(const Vehicle * const *a, const Vehicle * const *b)
1183 int r = ClampToI32((*a)->GetDisplayProfitLastYear() - (*b)->GetDisplayProfitLastYear());
1184 return (r != 0) ? r : VehicleNumberSorter(a, b);
1187 /** Sort vehicles by their cargo */
1188 static int CDECL VehicleCargoSorter(const Vehicle * const *a, const Vehicle * const *b)
1190 const Vehicle *v;
1191 CargoArray diff;
1193 /* Append the cargo of the connected waggons */
1194 for (v = *a; v != NULL; v = v->Next()) diff[v->cargo_type] += v->cargo_cap;
1195 for (v = *b; v != NULL; v = v->Next()) diff[v->cargo_type] -= v->cargo_cap;
1197 int r = 0;
1198 for (CargoID i = 0; i < NUM_CARGO; i++) {
1199 r = diff[i];
1200 if (r != 0) break;
1203 return (r != 0) ? r : VehicleNumberSorter(a, b);
1206 /** Sort vehicles by their reliability */
1207 static int CDECL VehicleReliabilitySorter(const Vehicle * const *a, const Vehicle * const *b)
1209 int r = (*a)->reliability - (*b)->reliability;
1210 return (r != 0) ? r : VehicleNumberSorter(a, b);
1213 /** Sort vehicles by their max speed */
1214 static int CDECL VehicleMaxSpeedSorter(const Vehicle * const *a, const Vehicle * const *b)
1216 int r = (*a)->vcache.cached_max_speed - (*b)->vcache.cached_max_speed;
1217 return (r != 0) ? r : VehicleNumberSorter(a, b);
1220 /** Sort vehicles by model */
1221 static int CDECL VehicleModelSorter(const Vehicle * const *a, const Vehicle * const *b)
1223 int r = (*a)->engine_type - (*b)->engine_type;
1224 return (r != 0) ? r : VehicleNumberSorter(a, b);
1227 /** Sort vehicles by their value */
1228 static int CDECL VehicleValueSorter(const Vehicle * const *a, const Vehicle * const *b)
1230 const Vehicle *u;
1231 Money diff = 0;
1233 for (u = *a; u != NULL; u = u->Next()) diff += u->value;
1234 for (u = *b; u != NULL; u = u->Next()) diff -= u->value;
1236 int r = ClampToI32(diff);
1237 return (r != 0) ? r : VehicleNumberSorter(a, b);
1240 /** Sort vehicles by their length */
1241 static int CDECL VehicleLengthSorter(const Vehicle * const *a, const Vehicle * const *b)
1243 int r = (*a)->GetGroundVehicleCache()->cached_total_length - (*b)->GetGroundVehicleCache()->cached_total_length;
1244 return (r != 0) ? r : VehicleNumberSorter(a, b);
1247 /** Sort vehicles by the time they can still live */
1248 static int CDECL VehicleTimeToLiveSorter(const Vehicle * const *a, const Vehicle * const *b)
1250 int r = ClampToI32(((*a)->max_age - (*a)->age) - ((*b)->max_age - (*b)->age));
1251 return (r != 0) ? r : VehicleNumberSorter(a, b);
1254 /** Sort vehicles by the timetable delay */
1255 static int CDECL VehicleTimetableDelaySorter(const Vehicle * const *a, const Vehicle * const *b)
1257 int r = (*a)->lateness_counter - (*b)->lateness_counter;
1258 return (r != 0) ? r : VehicleNumberSorter(a, b);
1261 void InitializeGUI()
1263 MemSetT(&_sorting, 0);
1267 * Assign a vehicle window a new vehicle
1268 * @param window_class WindowClass to search for
1269 * @param from_index the old vehicle ID
1270 * @param to_index the new vehicle ID
1272 static inline void ChangeVehicleWindow(WindowClass window_class, VehicleID from_index, VehicleID to_index)
1274 Window *w = FindWindowById(window_class, from_index);
1275 if (w != NULL) {
1276 /* Update window_number */
1277 w->window_number = to_index;
1278 if (w->viewport != NULL) w->viewport->follow_vehicle = to_index;
1280 /* Update vehicle drag data */
1281 if (_thd.window_class == window_class && _thd.window_number == (WindowNumber)from_index) {
1282 _thd.window_number = to_index;
1285 /* Notify the window. */
1286 w->InvalidateData(VIWD_AUTOREPLACE, false);
1291 * Report a change in vehicle IDs (due to autoreplace) to affected vehicle windows.
1292 * @param from_index the old vehicle ID
1293 * @param to_index the new vehicle ID
1295 void ChangeVehicleViewWindow(VehicleID from_index, VehicleID to_index)
1297 ChangeVehicleWindow(WC_VEHICLE_VIEW, from_index, to_index);
1298 ChangeVehicleWindow(WC_VEHICLE_ORDERS, from_index, to_index);
1299 ChangeVehicleWindow(WC_VEHICLE_REFIT, from_index, to_index);
1300 ChangeVehicleWindow(WC_VEHICLE_DETAILS, from_index, to_index);
1301 ChangeVehicleWindow(WC_VEHICLE_TIMETABLE, from_index, to_index);
1304 static const NWidgetPart _nested_vehicle_list[] = {
1305 NWidget(NWID_HORIZONTAL),
1306 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1307 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VL_CAPTION),
1308 NWidget(WWT_SHADEBOX, COLOUR_GREY),
1309 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
1310 NWidget(WWT_STICKYBOX, COLOUR_GREY),
1311 EndContainer(),
1313 NWidget(NWID_HORIZONTAL),
1314 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VL_SORT_ORDER), SetMinimalSize(81, 12), SetFill(0, 1), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
1315 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_SORT_BY_PULLDOWN), SetMinimalSize(167, 12), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
1316 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(12, 12), SetFill(1, 1), SetResize(1, 0),
1317 EndContainer(),
1318 EndContainer(),
1320 NWidget(NWID_HORIZONTAL),
1321 NWidget(WWT_MATRIX, COLOUR_GREY, WID_VL_LIST), SetMinimalSize(248, 0), SetFill(1, 0), SetResize(1, 1), SetMatrixDataTip(1, 0, STR_NULL), SetScrollbar(WID_VL_SCROLLBAR),
1322 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VL_SCROLLBAR),
1323 EndContainer(),
1325 NWidget(NWID_HORIZONTAL),
1326 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VL_HIDE_BUTTONS),
1327 NWidget(NWID_HORIZONTAL),
1328 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VL_AVAILABLE_VEHICLES), SetMinimalSize(106, 12), SetFill(0, 1),
1329 SetDataTip(STR_BLACK_STRING, STR_VEHICLE_LIST_AVAILABLE_ENGINES_TOOLTIP),
1330 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(0, 12), SetResize(1, 0), SetFill(1, 1), EndContainer(),
1331 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_MANAGE_VEHICLES_DROPDOWN), SetMinimalSize(118, 12), SetFill(0, 1),
1332 SetDataTip(STR_VEHICLE_LIST_MANAGE_LIST, STR_VEHICLE_LIST_MANAGE_LIST_TOOLTIP),
1333 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VL_STOP_ALL), SetMinimalSize(12, 12), SetFill(0, 1),
1334 SetDataTip(SPR_FLAG_VEH_STOPPED, STR_VEHICLE_LIST_MASS_STOP_LIST_TOOLTIP),
1335 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VL_START_ALL), SetMinimalSize(12, 12), SetFill(0, 1),
1336 SetDataTip(SPR_FLAG_VEH_RUNNING, STR_VEHICLE_LIST_MASS_START_LIST_TOOLTIP),
1337 EndContainer(),
1338 /* Widget to be shown for other companies hiding the previous 5 widgets. */
1339 NWidget(WWT_PANEL, COLOUR_GREY), SetFill(1, 1), SetResize(1, 0), EndContainer(),
1340 EndContainer(),
1341 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
1342 EndContainer(),
1345 static void DrawSmallOrderList(const Vehicle *v, int left, int right, int y, VehicleOrderID start = 0)
1347 const Order *order = v->GetOrder(start);
1348 if (order == NULL) return;
1350 bool rtl = _current_text_dir == TD_RTL;
1351 int l_offset = rtl ? 0 : ScaleGUITrad(6);
1352 int r_offset = rtl ? ScaleGUITrad(6) : 0;
1353 int i = 0;
1354 VehicleOrderID oid = start;
1356 do {
1357 if (oid == v->cur_real_order_index) DrawString(left, right, y, STR_TINY_RIGHT_ARROW, TC_BLACK);
1359 if (order->IsType(OT_GOTO_STATION)) {
1360 SetDParam(0, order->GetDestination());
1361 DrawString(left + l_offset, right - r_offset, y, STR_TINY_BLACK_STATION);
1363 y += FONT_HEIGHT_SMALL;
1364 if (++i == 4) break;
1367 oid++;
1368 order = order->next;
1369 if (order == NULL) {
1370 order = v->orders.list->GetFirstOrder();
1371 oid = 0;
1373 } while (oid != start);
1377 * Draws an image of a vehicle chain
1378 * @param v Front vehicle
1379 * @param left The minimum horizontal position
1380 * @param right The maximum horizontal position
1381 * @param y Vertical position to draw at
1382 * @param selection Selected vehicle to draw a frame around
1383 * @param skip Number of pixels to skip at the front (for scrolling)
1385 void DrawVehicleImage(const Vehicle *v, int left, int right, int y, VehicleID selection, EngineImageType image_type, int skip)
1387 switch (v->type) {
1388 case VEH_TRAIN: DrawTrainImage(Train::From(v), left, right, y, selection, image_type, skip); break;
1389 case VEH_ROAD: DrawRoadVehImage(v, left, right, y, selection, image_type, skip); break;
1390 case VEH_SHIP: DrawShipImage(v, left, right, y, selection, image_type); break;
1391 case VEH_AIRCRAFT: DrawAircraftImage(v, left, right, y, selection, image_type); break;
1392 default: NOT_REACHED();
1397 * Get the height of a vehicle in the vehicle list GUIs.
1398 * @param type the vehicle type to look at
1399 * @param divisor the resulting height must be dividable by this
1400 * @return the height
1402 uint GetVehicleListHeight(VehicleType type, uint divisor)
1404 /* Name + vehicle + profit */
1405 uint base = ScaleGUITrad(GetVehicleHeight(type)) + 2 * FONT_HEIGHT_SMALL;
1406 /* Drawing of the 4 small orders + profit*/
1407 if (type >= VEH_SHIP) base = max(base, 5U * FONT_HEIGHT_SMALL);
1409 if (divisor == 1) return base;
1411 /* Make sure the height is dividable by divisor */
1412 uint rem = base % divisor;
1413 return base + (rem == 0 ? 0 : divisor - rem);
1417 * Draw all the vehicle list items.
1418 * @param selected_vehicle The vehicle that is to be highlighted.
1419 * @param line_height Height of a single item line.
1420 * @param r Rectangle with edge positions of the matrix widget.
1422 void BaseVehicleListWindow::DrawVehicleListItems(VehicleID selected_vehicle, int line_height, const Rect &r) const
1424 int left = r.left + WD_MATRIX_LEFT;
1425 int right = r.right - WD_MATRIX_RIGHT;
1426 int width = right - left;
1427 bool rtl = _current_text_dir == TD_RTL;
1429 int text_offset = max<int>(GetSpriteSize(SPR_PROFIT_LOT).width, GetDigitWidth() * this->unitnumber_digits) + WD_FRAMERECT_RIGHT;
1430 int text_left = left + (rtl ? 0 : text_offset);
1431 int text_right = right - (rtl ? text_offset : 0);
1433 bool show_orderlist = this->vli.vtype >= VEH_SHIP;
1434 int orderlist_left = left + (rtl ? 0 : max(ScaleGUITrad(100) + text_offset, width / 2));
1435 int orderlist_right = right - (rtl ? max(ScaleGUITrad(100) + text_offset, width / 2) : 0);
1437 int image_left = (rtl && show_orderlist) ? orderlist_right : text_left;
1438 int image_right = (!rtl && show_orderlist) ? orderlist_left : text_right;
1440 int vehicle_button_x = rtl ? right - GetSpriteSize(SPR_PROFIT_LOT).width : left;
1442 int y = r.top;
1443 uint max = min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->vehicles.Length());
1444 for (uint i = this->vscroll->GetPosition(); i < max; ++i) {
1445 const Vehicle *v = this->vehicles[i];
1446 StringID str;
1448 SetDParam(0, v->GetDisplayProfitThisYear());
1449 SetDParam(1, v->GetDisplayProfitLastYear());
1451 DrawVehicleImage(v, image_left, image_right, y + FONT_HEIGHT_SMALL - 1, selected_vehicle, EIT_IN_LIST, 0);
1452 DrawString(text_left, text_right, y + line_height - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1, STR_VEHICLE_LIST_PROFIT_THIS_YEAR_LAST_YEAR);
1454 if (v->name != NULL) {
1455 /* The vehicle got a name so we will print it */
1456 SetDParam(0, v->index);
1457 DrawString(text_left, text_right, y, STR_TINY_BLACK_VEHICLE);
1458 } else if (v->group_id != DEFAULT_GROUP) {
1459 /* The vehicle has no name, but is member of a group, so print group name */
1460 SetDParam(0, v->group_id);
1461 DrawString(text_left, text_right, y, STR_TINY_GROUP, TC_BLACK);
1464 if (show_orderlist) DrawSmallOrderList(v, orderlist_left, orderlist_right, y, v->cur_real_order_index);
1466 if (v->IsChainInDepot()) {
1467 str = STR_BLUE_COMMA;
1468 } else {
1469 str = (v->age > v->max_age - DAYS_IN_LEAP_YEAR) ? STR_RED_COMMA : STR_BLACK_COMMA;
1472 SetDParam(0, v->unitnumber);
1473 DrawString(left, right, y + 2, str);
1475 DrawVehicleProfitButton(v, vehicle_button_x, y + FONT_HEIGHT_NORMAL + 3);
1477 y += line_height;
1482 * Window for the (old) vehicle listing.
1484 * bitmask for w->window_number
1485 * 0-7 CompanyID (owner)
1486 * 8-10 window type (use flags in vehicle_gui.h)
1487 * 11-15 vehicle type (using VEH_, but can be compressed to fewer bytes if needed)
1488 * 16-31 StationID or OrderID depending on window type (bit 8-10)
1490 struct VehicleListWindow : public BaseVehicleListWindow {
1491 private:
1492 /** Enumeration of planes of the button row at the bottom. */
1493 enum ButtonPlanes {
1494 BP_SHOW_BUTTONS, ///< Show the buttons.
1495 BP_HIDE_BUTTONS, ///< Show the empty panel.
1498 public:
1499 VehicleListWindow(WindowDesc *desc, WindowNumber window_number) : BaseVehicleListWindow(desc, window_number)
1501 /* Set up sorting. Make the window-specific _sorting variable
1502 * point to the correct global _sorting struct so we are freed
1503 * from having conditionals during window operation */
1504 switch (this->vli.vtype) {
1505 case VEH_TRAIN: this->sorting = &_sorting.train; break;
1506 case VEH_ROAD: this->sorting = &_sorting.roadveh; break;
1507 case VEH_SHIP: this->sorting = &_sorting.ship; break;
1508 case VEH_AIRCRAFT: this->sorting = &_sorting.aircraft; break;
1509 default: NOT_REACHED();
1512 this->CreateNestedTree();
1514 this->vscroll = this->GetScrollbar(WID_VL_SCROLLBAR);
1516 this->vehicles.SetListing(*this->sorting);
1517 this->vehicles.ForceRebuild();
1518 this->vehicles.NeedResort();
1519 this->BuildVehicleList();
1520 this->SortVehicleList();
1522 /* Set up the window widgets */
1523 this->GetWidget<NWidgetCore>(WID_VL_LIST)->tool_tip = STR_VEHICLE_LIST_TRAIN_LIST_TOOLTIP + this->vli.vtype;
1525 if (this->vli.type == VL_SHARED_ORDERS) {
1526 this->GetWidget<NWidgetCore>(WID_VL_CAPTION)->widget_data = STR_VEHICLE_LIST_SHARED_ORDERS_LIST_CAPTION;
1527 } else {
1528 this->GetWidget<NWidgetCore>(WID_VL_CAPTION)->widget_data = STR_VEHICLE_LIST_TRAIN_CAPTION + this->vli.vtype;
1531 this->FinishInitNested(window_number);
1532 if (this->vli.company != OWNER_NONE) this->owner = this->vli.company;
1535 ~VehicleListWindow()
1537 *this->sorting = this->vehicles.GetListing();
1540 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
1542 switch (widget) {
1543 case WID_VL_LIST:
1544 resize->height = GetVehicleListHeight(this->vli.vtype, 1);
1546 switch (this->vli.vtype) {
1547 case VEH_TRAIN:
1548 case VEH_ROAD:
1549 size->height = 6 * resize->height;
1550 break;
1551 case VEH_SHIP:
1552 case VEH_AIRCRAFT:
1553 size->height = 4 * resize->height;
1554 break;
1555 default: NOT_REACHED();
1557 break;
1559 case WID_VL_SORT_ORDER: {
1560 Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
1561 d.width += padding.width + Window::SortButtonWidth() * 2; // Doubled since the string is centred and it also looks better.
1562 d.height += padding.height;
1563 *size = maxdim(*size, d);
1564 break;
1567 case WID_VL_MANAGE_VEHICLES_DROPDOWN: {
1568 Dimension d = this->GetActionDropdownSize(this->vli.type == VL_STANDARD, false);
1569 d.height += padding.height;
1570 d.width += padding.width;
1571 *size = maxdim(*size, d);
1572 break;
1577 virtual void SetStringParameters(int widget) const
1579 switch (widget) {
1580 case WID_VL_AVAILABLE_VEHICLES:
1581 SetDParam(0, STR_VEHICLE_LIST_AVAILABLE_TRAINS + this->vli.vtype);
1582 break;
1584 case WID_VL_CAPTION: {
1585 switch (this->vli.type) {
1586 case VL_SHARED_ORDERS: // Shared Orders
1587 if (this->vehicles.Length() == 0) {
1588 /* We can't open this window without vehicles using this order
1589 * and we should close the window when deleting the order. */
1590 NOT_REACHED();
1592 SetDParam(0, this->vscroll->GetCount());
1593 break;
1595 case VL_STANDARD: // Company Name
1596 SetDParam(0, STR_COMPANY_NAME);
1597 SetDParam(1, this->vli.index);
1598 SetDParam(3, this->vscroll->GetCount());
1599 break;
1601 case VL_STATION_LIST: // Station/Waypoint Name
1602 SetDParam(0, BaseStation::Get(this->vli.index)->IsWaypoint() ? STR_WAYPOINT_NAME : STR_STATION_NAME);
1603 SetDParam(1, this->vli.index);
1604 SetDParam(3, this->vscroll->GetCount());
1605 break;
1607 case VL_DEPOT_LIST:
1608 SetDParam(0, STR_DEPOT_CAPTION);
1609 SetDParam(1, this->vli.vtype);
1610 SetDParam(2, this->vli.index);
1611 SetDParam(3, this->vscroll->GetCount());
1612 break;
1613 default: NOT_REACHED();
1615 break;
1620 virtual void DrawWidget(const Rect &r, int widget) const
1622 switch (widget) {
1623 case WID_VL_SORT_ORDER:
1624 /* draw arrow pointing up/down for ascending/descending sorting */
1625 this->DrawSortButtonState(widget, this->vehicles.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
1626 break;
1628 case WID_VL_LIST:
1629 this->DrawVehicleListItems(INVALID_VEHICLE, this->resize.step_height, r);
1630 break;
1634 virtual void OnPaint()
1636 this->BuildVehicleList();
1637 this->SortVehicleList();
1639 if (this->vehicles.Length() == 0 && this->IsWidgetLowered(WID_VL_MANAGE_VEHICLES_DROPDOWN)) {
1640 HideDropDownMenu(this);
1643 /* Hide the widgets that we will not use in this window
1644 * Some windows contains actions only fit for the owner */
1645 int plane_to_show = (this->owner == _local_company) ? BP_SHOW_BUTTONS : BP_HIDE_BUTTONS;
1646 NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VL_HIDE_BUTTONS);
1647 if (plane_to_show != nwi->shown_plane) {
1648 nwi->SetDisplayedPlane(plane_to_show);
1649 nwi->SetDirty(this);
1651 if (this->owner == _local_company) {
1652 this->SetWidgetDisabledState(WID_VL_AVAILABLE_VEHICLES, this->vli.type != VL_STANDARD);
1653 this->SetWidgetsDisabledState(this->vehicles.Length() == 0,
1654 WID_VL_MANAGE_VEHICLES_DROPDOWN,
1655 WID_VL_STOP_ALL,
1656 WID_VL_START_ALL,
1657 WIDGET_LIST_END);
1660 /* Set text of sort by dropdown widget. */
1661 this->GetWidget<NWidgetCore>(WID_VL_SORT_BY_PULLDOWN)->widget_data = this->vehicle_sorter_names[this->vehicles.SortType()];
1663 this->DrawWidgets();
1666 virtual void OnClick(Point pt, int widget, int click_count)
1668 switch (widget) {
1669 case WID_VL_SORT_ORDER: // Flip sorting method ascending/descending
1670 this->vehicles.ToggleSortOrder();
1671 this->SetDirty();
1672 break;
1674 case WID_VL_SORT_BY_PULLDOWN:// Select sorting criteria dropdown menu
1675 ShowDropDownMenu(this, this->vehicle_sorter_names, this->vehicles.SortType(), WID_VL_SORT_BY_PULLDOWN, 0,
1676 (this->vli.vtype == VEH_TRAIN || this->vli.vtype == VEH_ROAD) ? 0 : (1 << 10));
1677 return;
1679 case WID_VL_LIST: { // Matrix to show vehicles
1680 uint id_v = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_VL_LIST);
1681 if (id_v >= this->vehicles.Length()) return; // click out of list bound
1683 const Vehicle *v = this->vehicles[id_v];
1684 if (!VehicleClicked(v)) ShowVehicleViewWindow(v);
1685 break;
1688 case WID_VL_AVAILABLE_VEHICLES:
1689 ShowBuildVehicleWindow(INVALID_TILE, this->vli.vtype);
1690 break;
1692 case WID_VL_MANAGE_VEHICLES_DROPDOWN: {
1693 DropDownList *list = this->BuildActionDropdownList(VehicleListIdentifier(this->window_number).type == VL_STANDARD, false);
1694 ShowDropDownList(this, list, 0, WID_VL_MANAGE_VEHICLES_DROPDOWN);
1695 break;
1698 case WID_VL_STOP_ALL:
1699 case WID_VL_START_ALL:
1700 DoCommandP(0, (1 << 1) | (widget == WID_VL_START_ALL ? (1 << 0) : 0), this->window_number, CMD_MASS_START_STOP);
1701 break;
1705 virtual void OnDropdownSelect(int widget, int index)
1707 switch (widget) {
1708 case WID_VL_SORT_BY_PULLDOWN:
1709 this->vehicles.SetSortType(index);
1710 break;
1711 case WID_VL_MANAGE_VEHICLES_DROPDOWN:
1712 assert(this->vehicles.Length() != 0);
1714 switch (index) {
1715 case ADI_REPLACE: // Replace window
1716 ShowReplaceGroupVehicleWindow(ALL_GROUP, this->vli.vtype);
1717 break;
1718 case ADI_SERVICE: // Send for servicing
1719 case ADI_DEPOT: // Send to Depots
1720 DoCommandP(0, DEPOT_MASS_SEND | (index == ADI_SERVICE ? DEPOT_SERVICE : (DepotCommand)0), this->window_number, CMD_SEND_VEHICLE_TO_DEPOT);
1721 break;
1723 default: NOT_REACHED();
1725 break;
1726 default: NOT_REACHED();
1728 this->SetDirty();
1731 virtual void OnTick()
1733 if (_pause_mode != PM_UNPAUSED) return;
1734 if (this->vehicles.NeedResort()) {
1735 StationID station = (this->vli.type == VL_STATION_LIST) ? this->vli.index : INVALID_STATION;
1737 DEBUG(misc, 3, "Periodic resort %d list company %d at station %d", this->vli.vtype, this->owner, station);
1738 this->SetDirty();
1742 virtual void OnResize()
1744 this->vscroll->SetCapacityFromWidget(this, WID_VL_LIST);
1748 * Some data on this window has become invalid.
1749 * @param data Information about the changed data.
1750 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
1752 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
1754 if (!gui_scope && HasBit(data, 31) && this->vli.type == VL_SHARED_ORDERS) {
1755 /* Needs to be done in command-scope, so everything stays valid */
1756 this->vli.index = GB(data, 0, 20);
1757 this->window_number = this->vli.Pack();
1758 this->vehicles.ForceRebuild();
1759 return;
1762 if (data == 0) {
1763 /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
1764 this->vehicles.ForceRebuild();
1765 } else {
1766 this->vehicles.ForceResort();
1771 static WindowDesc _vehicle_list_other_desc(
1772 WDP_AUTO, "list_vehicles", 260, 246,
1773 WC_INVALID, WC_NONE,
1775 _nested_vehicle_list, lengthof(_nested_vehicle_list)
1778 static WindowDesc _vehicle_list_train_desc(
1779 WDP_AUTO, "list_vehicles_train", 325, 246,
1780 WC_TRAINS_LIST, WC_NONE,
1782 _nested_vehicle_list, lengthof(_nested_vehicle_list)
1785 static void ShowVehicleListWindowLocal(CompanyID company, VehicleListType vlt, VehicleType vehicle_type, uint32 unique_number)
1787 if (!Company::IsValidID(company) && company != OWNER_NONE) return;
1789 WindowNumber num = VehicleListIdentifier(vlt, vehicle_type, company, unique_number).Pack();
1790 if (vehicle_type == VEH_TRAIN) {
1791 AllocateWindowDescFront<VehicleListWindow>(&_vehicle_list_train_desc, num);
1792 } else {
1793 _vehicle_list_other_desc.cls = GetWindowClassForVehicleType(vehicle_type);
1794 AllocateWindowDescFront<VehicleListWindow>(&_vehicle_list_other_desc, num);
1798 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type)
1800 /* If _settings_client.gui.advanced_vehicle_list > 1, display the Advanced list
1801 * if _settings_client.gui.advanced_vehicle_list == 1, display Advanced list only for local company
1802 * if _ctrl_pressed, do the opposite action (Advanced list x Normal list)
1805 if ((_settings_client.gui.advanced_vehicle_list > (uint)(company != _local_company)) != _ctrl_pressed) {
1806 ShowCompanyGroup(company, vehicle_type);
1807 } else {
1808 ShowVehicleListWindowLocal(company, VL_STANDARD, vehicle_type, company);
1812 void ShowVehicleListWindow(const Vehicle *v)
1814 ShowVehicleListWindowLocal(v->owner, VL_SHARED_ORDERS, v->type, v->FirstShared()->index);
1817 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, StationID station)
1819 ShowVehicleListWindowLocal(company, VL_STATION_LIST, vehicle_type, station);
1822 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, TileIndex depot_tile)
1824 uint16 depot_airport_index;
1826 if (vehicle_type == VEH_AIRCRAFT) {
1827 depot_airport_index = GetStationIndex(depot_tile);
1828 } else {
1829 depot_airport_index = GetDepotIndex(depot_tile);
1831 ShowVehicleListWindowLocal(company, VL_DEPOT_LIST, vehicle_type, depot_airport_index);
1835 /* Unified vehicle GUI - Vehicle Details Window */
1837 assert_compile(WID_VD_DETAILS_CARGO_CARRIED == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_CARGO );
1838 assert_compile(WID_VD_DETAILS_TRAIN_VEHICLES == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_INFO );
1839 assert_compile(WID_VD_DETAILS_CAPACITY_OF_EACH == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_CAPACITY);
1840 assert_compile(WID_VD_DETAILS_TOTAL_CARGO == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_TOTALS );
1842 /** Vehicle details widgets (other than train). */
1843 static const NWidgetPart _nested_nontrain_vehicle_details_widgets[] = {
1844 NWidget(NWID_HORIZONTAL),
1845 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1846 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VD_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1847 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 */),
1848 NWidget(WWT_SHADEBOX, COLOUR_GREY),
1849 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
1850 NWidget(WWT_STICKYBOX, COLOUR_GREY),
1851 EndContainer(),
1852 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_TOP_DETAILS), SetMinimalSize(405, 42), SetResize(1, 0), EndContainer(),
1853 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_MIDDLE_DETAILS), SetMinimalSize(405, 45), SetResize(1, 0), EndContainer(),
1854 NWidget(NWID_HORIZONTAL),
1855 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_DECREASE_SERVICING_INTERVAL), SetFill(0, 1),
1856 SetDataTip(AWV_DECREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
1857 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_INCREASE_SERVICING_INTERVAL), SetFill(0, 1),
1858 SetDataTip(AWV_INCREASE, STR_VEHICLE_DETAILS_INCREASE_SERVICING_INTERVAL_TOOLTIP),
1859 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VD_SERVICE_INTERVAL_DROPDOWN), SetFill(0, 1),
1860 SetDataTip(STR_EMPTY, STR_SERVICE_INTERVAL_DROPDOWN_TOOLTIP),
1861 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_SERVICING_INTERVAL), SetFill(1, 1), SetResize(1, 0), EndContainer(),
1862 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
1863 EndContainer(),
1866 /** Train details widgets. */
1867 static const NWidgetPart _nested_train_vehicle_details_widgets[] = {
1868 NWidget(NWID_HORIZONTAL),
1869 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1870 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VD_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1871 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 */),
1872 NWidget(WWT_SHADEBOX, COLOUR_GREY),
1873 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
1874 NWidget(WWT_STICKYBOX, COLOUR_GREY),
1875 EndContainer(),
1876 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_TOP_DETAILS), SetResize(1, 0), SetMinimalSize(405, 42), EndContainer(),
1877 NWidget(NWID_HORIZONTAL),
1878 NWidget(WWT_MATRIX, COLOUR_GREY, WID_VD_MATRIX), SetResize(1, 1), SetMinimalSize(393, 45), SetMatrixDataTip(1, 0, STR_NULL), SetFill(1, 0), SetScrollbar(WID_VD_SCROLLBAR),
1879 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VD_SCROLLBAR),
1880 EndContainer(),
1881 NWidget(NWID_HORIZONTAL),
1882 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_DECREASE_SERVICING_INTERVAL), SetFill(0, 1),
1883 SetDataTip(AWV_DECREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
1884 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_INCREASE_SERVICING_INTERVAL), SetFill(0, 1),
1885 SetDataTip(AWV_INCREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
1886 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VD_SERVICE_INTERVAL_DROPDOWN), SetFill(0, 1),
1887 SetDataTip(STR_EMPTY, STR_SERVICE_INTERVAL_DROPDOWN_TOOLTIP),
1888 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_SERVICING_INTERVAL), SetFill(1, 1), SetResize(1, 0), EndContainer(),
1889 EndContainer(),
1890 NWidget(NWID_HORIZONTAL),
1891 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_CARGO_CARRIED), SetMinimalSize(96, 12),
1892 SetDataTip(STR_VEHICLE_DETAIL_TAB_CARGO, STR_VEHICLE_DETAILS_TRAIN_CARGO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
1893 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_TRAIN_VEHICLES), SetMinimalSize(99, 12),
1894 SetDataTip(STR_VEHICLE_DETAIL_TAB_INFORMATION, STR_VEHICLE_DETAILS_TRAIN_INFORMATION_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
1895 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_CAPACITY_OF_EACH), SetMinimalSize(99, 12),
1896 SetDataTip(STR_VEHICLE_DETAIL_TAB_CAPACITIES, STR_VEHICLE_DETAILS_TRAIN_CAPACITIES_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
1897 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_TOTAL_CARGO), SetMinimalSize(99, 12),
1898 SetDataTip(STR_VEHICLE_DETAIL_TAB_TOTAL_CARGO, STR_VEHICLE_DETAILS_TRAIN_TOTAL_CARGO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
1899 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
1900 EndContainer(),
1904 extern int GetTrainDetailsWndVScroll(VehicleID veh_id, TrainDetailsWindowTabs det_tab);
1905 extern void DrawTrainDetails(const Train *v, int left, int right, int y, int vscroll_pos, uint16 vscroll_cap, TrainDetailsWindowTabs det_tab);
1906 extern void DrawRoadVehDetails(const Vehicle *v, int left, int right, int y);
1907 extern void DrawShipDetails(const Vehicle *v, int left, int right, int y);
1908 extern void DrawAircraftDetails(const Aircraft *v, int left, int right, int y);
1910 static StringID _service_interval_dropdown[] = {
1911 STR_VEHICLE_DETAILS_DEFAULT,
1912 STR_VEHICLE_DETAILS_DAYS,
1913 STR_VEHICLE_DETAILS_PERCENT,
1914 INVALID_STRING_ID,
1917 /** Class for managing the vehicle details window. */
1918 struct VehicleDetailsWindow : Window {
1919 TrainDetailsWindowTabs tab; ///< For train vehicles: which tab is displayed.
1920 Scrollbar *vscroll;
1922 /** Initialize a newly created vehicle details window */
1923 VehicleDetailsWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
1925 const Vehicle *v = Vehicle::Get(window_number);
1927 this->CreateNestedTree();
1928 this->vscroll = (v->type == VEH_TRAIN ? this->GetScrollbar(WID_VD_SCROLLBAR) : NULL);
1929 this->FinishInitNested(window_number);
1931 this->GetWidget<NWidgetCore>(WID_VD_RENAME_VEHICLE)->tool_tip = STR_VEHICLE_DETAILS_TRAIN_RENAME + v->type;
1933 this->owner = v->owner;
1934 this->tab = TDW_TAB_CARGO;
1938 * Some data on this window has become invalid.
1939 * @param data Information about the changed data.
1940 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
1942 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
1944 if (data == VIWD_AUTOREPLACE) {
1945 /* Autoreplace replaced the vehicle.
1946 * Nothing to do for this window. */
1947 return;
1949 if (!gui_scope) return;
1950 const Vehicle *v = Vehicle::Get(this->window_number);
1951 if (v->type == VEH_ROAD) {
1952 const NWidgetBase *nwid_info = this->GetWidget<NWidgetBase>(WID_VD_MIDDLE_DETAILS);
1953 uint aimed_height = this->GetRoadVehDetailsHeight(v);
1954 /* If the number of articulated parts changes, the size of the window must change too. */
1955 if (aimed_height != nwid_info->current_y) {
1956 this->ReInit();
1962 * Gets the desired height for the road vehicle details panel.
1963 * @param v Road vehicle being shown.
1964 * @return Desired height in pixels.
1966 uint GetRoadVehDetailsHeight(const Vehicle *v)
1968 uint desired_height;
1969 if (v->HasArticulatedPart()) {
1970 /* An articulated RV has its text drawn under the sprite instead of after it, hence 15 pixels extra. */
1971 desired_height = WD_FRAMERECT_TOP + ScaleGUITrad(15) + 3 * FONT_HEIGHT_NORMAL + 2 + WD_FRAMERECT_BOTTOM;
1972 /* Add space for the cargo amount for each part. */
1973 for (const Vehicle *u = v; u != NULL; u = u->Next()) {
1974 if (u->cargo_cap != 0) desired_height += FONT_HEIGHT_NORMAL + 1;
1976 } else {
1977 desired_height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + 3 + WD_FRAMERECT_BOTTOM;
1979 return desired_height;
1982 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
1984 switch (widget) {
1985 case WID_VD_TOP_DETAILS: {
1986 Dimension dim = { 0, 0 };
1987 size->height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
1989 for (uint i = 0; i < 4; i++) SetDParamMaxValue(i, INT16_MAX);
1990 static const StringID info_strings[] = {
1991 STR_VEHICLE_INFO_MAX_SPEED,
1992 STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED,
1993 STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE,
1994 STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR,
1995 STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS
1997 for (uint i = 0; i < lengthof(info_strings); i++) {
1998 dim = maxdim(dim, GetStringBoundingBox(info_strings[i]));
2000 SetDParam(0, STR_VEHICLE_INFO_AGE);
2001 dim = maxdim(dim, GetStringBoundingBox(STR_VEHICLE_INFO_AGE_RUNNING_COST_YR));
2002 size->width = dim.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
2003 break;
2006 case WID_VD_MIDDLE_DETAILS: {
2007 const Vehicle *v = Vehicle::Get(this->window_number);
2008 switch (v->type) {
2009 case VEH_ROAD:
2010 size->height = this->GetRoadVehDetailsHeight(v);
2011 break;
2013 case VEH_SHIP:
2014 size->height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + 3 + WD_FRAMERECT_BOTTOM;
2015 break;
2017 case VEH_AIRCRAFT:
2018 size->height = WD_FRAMERECT_TOP + 5 * FONT_HEIGHT_NORMAL + 4 + WD_FRAMERECT_BOTTOM;
2019 break;
2021 default:
2022 NOT_REACHED(); // Train uses WID_VD_MATRIX instead.
2024 break;
2027 case WID_VD_MATRIX:
2028 resize->height = max(ScaleGUITrad(14), WD_MATRIX_TOP + FONT_HEIGHT_NORMAL + WD_MATRIX_BOTTOM);
2029 size->height = 4 * resize->height;
2030 break;
2032 case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
2033 StringID *strs = _service_interval_dropdown;
2034 while (*strs != INVALID_STRING_ID) {
2035 *size = maxdim(*size, GetStringBoundingBox(*strs++));
2037 size->width += padding.width;
2038 size->height = FONT_HEIGHT_NORMAL + WD_DROPDOWNTEXT_TOP + WD_DROPDOWNTEXT_BOTTOM;
2039 break;
2042 case WID_VD_SERVICING_INTERVAL:
2043 SetDParamMaxValue(0, MAX_SERVINT_DAYS); // Roughly the maximum interval
2044 SetDParamMaxValue(1, MAX_YEAR * DAYS_IN_YEAR); // Roughly the maximum year
2045 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;
2046 size->height = WD_FRAMERECT_TOP + FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
2047 break;
2051 /** Checks whether service interval is enabled for the vehicle. */
2052 static bool IsVehicleServiceIntervalEnabled(const VehicleType vehicle_type, CompanyID company_id)
2054 const VehicleDefaultSettings *vds = &Company::Get(company_id)->settings.vehicle;
2055 switch (vehicle_type) {
2056 default: NOT_REACHED();
2057 case VEH_TRAIN: return vds->servint_trains != 0;
2058 case VEH_ROAD: return vds->servint_roadveh != 0;
2059 case VEH_SHIP: return vds->servint_ships != 0;
2060 case VEH_AIRCRAFT: return vds->servint_aircraft != 0;
2065 * Draw the details for the given vehicle at the position of the Details windows
2067 * @param v current vehicle
2068 * @param left The left most coordinate to draw
2069 * @param right The right most coordinate to draw
2070 * @param y The y coordinate
2071 * @param vscroll_pos Position of scrollbar (train only)
2072 * @param vscroll_cap Number of lines currently displayed (train only)
2073 * @param det_tab Selected details tab (train only)
2075 static void DrawVehicleDetails(const Vehicle *v, int left, int right, int y, int vscroll_pos, uint vscroll_cap, TrainDetailsWindowTabs det_tab)
2077 switch (v->type) {
2078 case VEH_TRAIN: DrawTrainDetails(Train::From(v), left, right, y, vscroll_pos, vscroll_cap, det_tab); break;
2079 case VEH_ROAD: DrawRoadVehDetails(v, left, right, y); break;
2080 case VEH_SHIP: DrawShipDetails(v, left, right, y); break;
2081 case VEH_AIRCRAFT: DrawAircraftDetails(Aircraft::From(v), left, right, y); break;
2082 default: NOT_REACHED();
2086 virtual void SetStringParameters(int widget) const
2088 if (widget == WID_VD_CAPTION) SetDParam(0, Vehicle::Get(this->window_number)->index);
2091 virtual void DrawWidget(const Rect &r, int widget) const
2093 const Vehicle *v = Vehicle::Get(this->window_number);
2095 switch (widget) {
2096 case WID_VD_TOP_DETAILS: {
2097 int y = r.top + WD_FRAMERECT_TOP;
2099 /* Draw running cost */
2100 SetDParam(1, v->age / DAYS_IN_LEAP_YEAR);
2101 SetDParam(0, (v->age + DAYS_IN_YEAR < v->max_age) ? STR_VEHICLE_INFO_AGE : STR_VEHICLE_INFO_AGE_RED);
2102 SetDParam(2, v->max_age / DAYS_IN_LEAP_YEAR);
2103 SetDParam(3, v->GetDisplayRunningCost());
2104 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_AGE_RUNNING_COST_YR);
2105 y += FONT_HEIGHT_NORMAL;
2107 /* Draw max speed */
2108 StringID string;
2109 if (v->type == VEH_TRAIN ||
2110 (v->type == VEH_ROAD && _settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL)) {
2111 const GroundVehicleCache *gcache = v->GetGroundVehicleCache();
2112 SetDParam(2, v->GetDisplayMaxSpeed());
2113 SetDParam(1, gcache->cached_power);
2114 SetDParam(0, gcache->cached_weight);
2115 SetDParam(3, gcache->cached_max_te / 1000);
2116 if (v->type == VEH_TRAIN && (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ||
2117 GetRailTypeInfo(Train::From(v)->railtype)->acceleration_type == 2)) {
2118 string = STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED;
2119 } else {
2120 string = STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE;
2122 } else {
2123 SetDParam(0, v->GetDisplayMaxSpeed());
2124 if (v->type == VEH_AIRCRAFT && Aircraft::From(v)->GetRange() > 0) {
2125 SetDParam(1, Aircraft::From(v)->GetRange());
2126 string = STR_VEHICLE_INFO_MAX_SPEED_RANGE;
2127 } else {
2128 string = STR_VEHICLE_INFO_MAX_SPEED;
2131 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, string);
2132 y += FONT_HEIGHT_NORMAL;
2134 /* Draw profit */
2135 SetDParam(0, v->GetDisplayProfitThisYear());
2136 SetDParam(1, v->GetDisplayProfitLastYear());
2137 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR);
2138 y += FONT_HEIGHT_NORMAL;
2140 /* Draw breakdown & reliability */
2141 SetDParam(0, ToPercent16(v->reliability));
2142 SetDParam(1, v->breakdowns_since_last_service);
2143 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS);
2144 break;
2147 case WID_VD_MATRIX:
2148 /* For trains only. */
2149 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);
2150 break;
2152 case WID_VD_MIDDLE_DETAILS: {
2153 /* For other vehicles, at the place of the matrix. */
2154 bool rtl = _current_text_dir == TD_RTL;
2155 uint sprite_width = UnScaleGUI(
2156 max<uint>(GetSprite(v->GetImage(rtl ? DIR_E : DIR_W, EIT_IN_DETAILS), ST_NORMAL)->width, 70U)) +
2157 WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
2159 uint text_left = r.left + (rtl ? 0 : sprite_width);
2160 uint text_right = r.right - (rtl ? sprite_width : 0);
2162 /* Articulated road vehicles use a complete line. */
2163 if (v->type == VEH_ROAD && v->HasArticulatedPart()) {
2164 DrawVehicleImage(v, r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, 0);
2165 } else {
2166 uint sprite_left = rtl ? text_right : r.left;
2167 uint sprite_right = rtl ? r.right : text_left;
2169 DrawVehicleImage(v, sprite_left + WD_FRAMERECT_LEFT, sprite_right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, 0);
2171 DrawVehicleDetails(v, text_left + WD_FRAMERECT_LEFT, text_right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, 0, 0, this->tab);
2172 break;
2175 case WID_VD_SERVICING_INTERVAL:
2176 /* Draw service interval text */
2177 SetDParam(0, v->GetServiceInterval());
2178 SetDParam(1, v->date_of_last_service);
2179 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + (r.bottom - r.top + 1 - FONT_HEIGHT_NORMAL) / 2,
2180 v->ServiceIntervalIsPercent() ? STR_VEHICLE_DETAILS_SERVICING_INTERVAL_PERCENT : STR_VEHICLE_DETAILS_SERVICING_INTERVAL_DAYS);
2181 break;
2185 /** Repaint vehicle details window. */
2186 virtual void OnPaint()
2188 const Vehicle *v = Vehicle::Get(this->window_number);
2190 this->SetWidgetDisabledState(WID_VD_RENAME_VEHICLE, v->owner != _local_company);
2192 if (v->type == VEH_TRAIN) {
2193 this->DisableWidget(this->tab + WID_VD_DETAILS_CARGO_CARRIED);
2194 this->vscroll->SetCount(GetTrainDetailsWndVScroll(v->index, this->tab));
2197 /* Disable service-scroller when interval is set to disabled */
2198 this->SetWidgetsDisabledState(!IsVehicleServiceIntervalEnabled(v->type, v->owner),
2199 WID_VD_INCREASE_SERVICING_INTERVAL,
2200 WID_VD_DECREASE_SERVICING_INTERVAL,
2201 WIDGET_LIST_END);
2203 StringID str = v->ServiceIntervalIsCustom() ?
2204 (v->ServiceIntervalIsPercent() ? STR_VEHICLE_DETAILS_PERCENT : STR_VEHICLE_DETAILS_DAYS) :
2205 STR_VEHICLE_DETAILS_DEFAULT;
2206 this->GetWidget<NWidgetCore>(WID_VD_SERVICE_INTERVAL_DROPDOWN)->widget_data = str;
2208 this->DrawWidgets();
2211 virtual void OnClick(Point pt, int widget, int click_count)
2213 switch (widget) {
2214 case WID_VD_RENAME_VEHICLE: { // rename
2215 const Vehicle *v = Vehicle::Get(this->window_number);
2216 SetDParam(0, v->index);
2217 ShowQueryString(STR_VEHICLE_NAME, STR_QUERY_RENAME_TRAIN_CAPTION + v->type,
2218 MAX_LENGTH_VEHICLE_NAME_CHARS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
2219 break;
2222 case WID_VD_INCREASE_SERVICING_INTERVAL: // increase int
2223 case WID_VD_DECREASE_SERVICING_INTERVAL: { // decrease int
2224 int mod = _ctrl_pressed ? 5 : 10;
2225 const Vehicle *v = Vehicle::Get(this->window_number);
2227 mod = (widget == WID_VD_DECREASE_SERVICING_INTERVAL) ? -mod : mod;
2228 mod = GetServiceIntervalClamped(mod + v->GetServiceInterval(), v->ServiceIntervalIsPercent());
2229 if (mod == v->GetServiceInterval()) return;
2231 DoCommandP(v->tile, v->index, mod | (1 << 16) | (v->ServiceIntervalIsPercent() << 17), CMD_CHANGE_SERVICE_INT);
2232 break;
2235 case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
2236 const Vehicle *v = Vehicle::Get(this->window_number);
2237 ShowDropDownMenu(this, _service_interval_dropdown, v->ServiceIntervalIsCustom() ? (v->ServiceIntervalIsPercent() ? 2 : 1) : 0, widget, 0, 0);
2238 break;
2241 case WID_VD_DETAILS_CARGO_CARRIED:
2242 case WID_VD_DETAILS_TRAIN_VEHICLES:
2243 case WID_VD_DETAILS_CAPACITY_OF_EACH:
2244 case WID_VD_DETAILS_TOTAL_CARGO:
2245 this->SetWidgetsDisabledState(false,
2246 WID_VD_DETAILS_CARGO_CARRIED,
2247 WID_VD_DETAILS_TRAIN_VEHICLES,
2248 WID_VD_DETAILS_CAPACITY_OF_EACH,
2249 WID_VD_DETAILS_TOTAL_CARGO,
2250 widget,
2251 WIDGET_LIST_END);
2253 this->tab = (TrainDetailsWindowTabs)(widget - WID_VD_DETAILS_CARGO_CARRIED);
2254 this->SetDirty();
2255 break;
2259 virtual void OnDropdownSelect(int widget, int index)
2261 switch (widget) {
2262 case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
2263 const Vehicle *v = Vehicle::Get(this->window_number);
2264 bool iscustom = index != 0;
2265 bool ispercent = iscustom ? (index == 2) : Company::Get(v->owner)->settings.vehicle.servint_ispercent;
2266 uint16 interval = GetServiceIntervalClamped(v->GetServiceInterval(), ispercent);
2267 DoCommandP(v->tile, v->index, interval | (iscustom << 16) | (ispercent << 17), CMD_CHANGE_SERVICE_INT);
2268 break;
2273 virtual void OnQueryTextFinished(char *str)
2275 if (str == NULL) return;
2277 DoCommandP(0, this->window_number, 0, CMD_RENAME_VEHICLE, str);
2280 virtual void OnResize()
2282 NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_VD_MATRIX);
2283 if (nwi != NULL) {
2284 this->vscroll->SetCapacityFromWidget(this, WID_VD_MATRIX);
2289 /** Vehicle details window descriptor. */
2290 static WindowDesc _train_vehicle_details_desc(
2291 WDP_AUTO, "view_vehicle_details_train", 405, 178,
2292 WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
2294 _nested_train_vehicle_details_widgets, lengthof(_nested_train_vehicle_details_widgets)
2297 /** Vehicle details window descriptor for other vehicles than a train. */
2298 static WindowDesc _nontrain_vehicle_details_desc(
2299 WDP_AUTO, "view_vehicle_details", 405, 113,
2300 WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
2302 _nested_nontrain_vehicle_details_widgets, lengthof(_nested_nontrain_vehicle_details_widgets)
2305 /** Shows the vehicle details window of the given vehicle. */
2306 static void ShowVehicleDetailsWindow(const Vehicle *v)
2308 DeleteWindowById(WC_VEHICLE_ORDERS, v->index, false);
2309 DeleteWindowById(WC_VEHICLE_TIMETABLE, v->index, false);
2310 AllocateWindowDescFront<VehicleDetailsWindow>((v->type == VEH_TRAIN) ? &_train_vehicle_details_desc : &_nontrain_vehicle_details_desc, v->index);
2314 /* Unified vehicle GUI - Vehicle View Window */
2316 /** Vehicle view widgets. */
2317 static const NWidgetPart _nested_vehicle_view_widgets[] = {
2318 NWidget(NWID_HORIZONTAL),
2319 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
2320 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VV_CAPTION), SetDataTip(STR_VEHICLE_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2321 NWidget(WWT_DEBUGBOX, COLOUR_GREY),
2322 NWidget(WWT_SHADEBOX, COLOUR_GREY),
2323 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
2324 NWidget(WWT_STICKYBOX, COLOUR_GREY),
2325 EndContainer(),
2326 NWidget(NWID_HORIZONTAL),
2327 NWidget(WWT_PANEL, COLOUR_GREY),
2328 NWidget(WWT_INSET, COLOUR_GREY), SetPadding(2, 2, 2, 2),
2329 NWidget(NWID_VIEWPORT, INVALID_COLOUR, WID_VV_VIEWPORT), SetMinimalSize(226, 84), SetResize(1, 1), SetPadding(1, 1, 1, 1),
2330 EndContainer(),
2331 EndContainer(),
2332 NWidget(NWID_VERTICAL),
2333 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_CENTER_MAIN_VIEW), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(SPR_CENTRE_VIEW_VEHICLE, 0x0 /* filled later */),
2334 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VV_SELECT_DEPOT_CLONE),
2335 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_GOTO_DEPOT), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
2336 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_CLONE), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
2337 EndContainer(),
2338 /* For trains only, 'ignore signal' button. */
2339 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_FORCE_PROCEED), SetMinimalSize(18, 18), SetFill(1, 1),
2340 SetDataTip(SPR_IGNORE_SIGNALS, STR_VEHICLE_VIEW_TRAIN_IGNORE_SIGNAL_TOOLTIP),
2341 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VV_SELECT_REFIT_TURN),
2342 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_REFIT), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(SPR_REFIT_VEHICLE, 0x0 /* filled later */),
2343 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_TURN_AROUND), SetMinimalSize(18, 18), SetFill(1, 1),
2344 SetDataTip(SPR_FORCE_VEHICLE_TURN, STR_VEHICLE_VIEW_ROAD_VEHICLE_REVERSE_TOOLTIP),
2345 EndContainer(),
2346 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_SHOW_ORDERS), SetFill(1, 1), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_ORDERS, 0x0 /* filled later */),
2347 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_SHOW_DETAILS), SetFill(1, 1), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_VEHICLE_DETAILS, 0x0 /* filled later */),
2348 NWidget(WWT_PANEL, COLOUR_GREY), SetFill(1, 1), SetMinimalSize(18, 0), SetResize(0, 1), EndContainer(),
2349 EndContainer(),
2350 EndContainer(),
2351 NWidget(NWID_HORIZONTAL),
2352 NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_VV_START_STOP), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetResize(1, 0), SetFill(1, 0),
2353 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
2354 EndContainer(),
2357 /** Vehicle view window descriptor for all vehicles but trains. */
2358 static WindowDesc _vehicle_view_desc(
2359 WDP_AUTO, "view_vehicle", 250, 116,
2360 WC_VEHICLE_VIEW, WC_NONE,
2362 _nested_vehicle_view_widgets, lengthof(_nested_vehicle_view_widgets)
2366 * Vehicle view window descriptor for trains. Only minimum_height and
2367 * default_height are different for train view.
2369 static WindowDesc _train_view_desc(
2370 WDP_AUTO, "view_vehicle_train", 250, 134,
2371 WC_VEHICLE_VIEW, WC_NONE,
2373 _nested_vehicle_view_widgets, lengthof(_nested_vehicle_view_widgets)
2377 /* Just to make sure, nobody has changed the vehicle type constants, as we are
2378 using them for array indexing in a number of places here. */
2379 assert_compile(VEH_TRAIN == 0);
2380 assert_compile(VEH_ROAD == 1);
2381 assert_compile(VEH_SHIP == 2);
2382 assert_compile(VEH_AIRCRAFT == 3);
2384 /** Zoom levels for vehicle views indexed by vehicle type. */
2385 static const ZoomLevel _vehicle_view_zoom_levels[] = {
2386 ZOOM_LVL_TRAIN,
2387 ZOOM_LVL_ROADVEH,
2388 ZOOM_LVL_SHIP,
2389 ZOOM_LVL_AIRCRAFT,
2392 /* Constants for geometry of vehicle view viewport */
2393 static const int VV_INITIAL_VIEWPORT_WIDTH = 226;
2394 static const int VV_INITIAL_VIEWPORT_HEIGHT = 84;
2395 static const int VV_INITIAL_VIEWPORT_HEIGHT_TRAIN = 102;
2397 /** Error strings when starting/stopping a vehicle indexed by vehicle type. */
2398 static const StringID _vehicle_string_startstop_table[4] = {
2399 STR_ERROR_CAN_T_STOP_START_TRAIN,
2400 STR_ERROR_CAN_T_STOP_START_ROAD_VEHICLE,
2401 STR_ERROR_CAN_T_STOP_START_SHIP,
2402 STR_ERROR_CAN_T_STOP_START_AIRCRAFT,
2406 * This is the Callback method after the cloning attempt of a vehicle
2407 * @param result the result of the cloning command
2408 * @param tile unused
2409 * @param p1 vehicle ID
2410 * @param p2 unused
2412 void CcStartStopVehicle(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
2414 if (result.Failed()) return;
2416 if (p2 == 0) return;
2418 const Vehicle *v = Vehicle::GetIfValid(p1);
2419 if (v == NULL || !v->IsPrimaryVehicle() || v->owner != _local_company) return;
2421 StringID msg = (v->vehstatus & VS_STOPPED) ? STR_VEHICLE_COMMAND_STOPPED : STR_VEHICLE_COMMAND_STARTED;
2422 Point pt = RemapCoords(v->x_pos, v->y_pos, v->z_pos);
2423 AddTextEffect(msg, pt.x, pt.y, DAY_TICKS, TE_RISING);
2427 * Executes #CMD_START_STOP_VEHICLE for given vehicle.
2428 * @param v Vehicle to start/stop
2429 * @param texteffect Should a texteffect be shown?
2431 void StartStopVehicle(const Vehicle *v, bool texteffect)
2433 assert(v->IsPrimaryVehicle());
2434 DoCommandP(v->tile, v->index, texteffect ? 1 : 0, CMD_START_STOP_VEHICLE);
2437 /** Checks whether the vehicle may be refitted at the moment.*/
2438 static bool IsVehicleRefitable(const Vehicle *v)
2440 if (!v->IsStoppedInDepot()) return false;
2442 do {
2443 if (IsEngineRefittable(v->engine_type)) return true;
2444 } while (v->IsGroundVehicle() && (v = v->Next()) != NULL);
2446 return false;
2449 /** Window manager class for viewing a vehicle. */
2450 struct VehicleViewWindow : Window {
2451 private:
2452 /** Display planes available in the vehicle view window. */
2453 enum PlaneSelections {
2454 SEL_DC_GOTO_DEPOT, ///< Display 'goto depot' button in #WID_VV_SELECT_DEPOT_CLONE stacked widget.
2455 SEL_DC_CLONE, ///< Display 'clone vehicle' button in #WID_VV_SELECT_DEPOT_CLONE stacked widget.
2457 SEL_RT_REFIT, ///< Display 'refit' button in #WID_VV_SELECT_REFIT_TURN stacked widget.
2458 SEL_RT_TURN_AROUND, ///< Display 'turn around' button in #WID_VV_SELECT_REFIT_TURN stacked widget.
2460 SEL_DC_BASEPLANE = SEL_DC_GOTO_DEPOT, ///< First plane of the #WID_VV_SELECT_DEPOT_CLONE stacked widget.
2461 SEL_RT_BASEPLANE = SEL_RT_REFIT, ///< First plane of the #WID_VV_SELECT_REFIT_TURN stacked widget.
2465 * Display a plane in the window.
2466 * @param plane Plane to show.
2468 void SelectPlane(PlaneSelections plane)
2470 switch (plane) {
2471 case SEL_DC_GOTO_DEPOT:
2472 case SEL_DC_CLONE:
2473 this->GetWidget<NWidgetStacked>(WID_VV_SELECT_DEPOT_CLONE)->SetDisplayedPlane(plane - SEL_DC_BASEPLANE);
2474 break;
2476 case SEL_RT_REFIT:
2477 case SEL_RT_TURN_AROUND:
2478 this->GetWidget<NWidgetStacked>(WID_VV_SELECT_REFIT_TURN)->SetDisplayedPlane(plane - SEL_RT_BASEPLANE);
2479 break;
2481 default:
2482 NOT_REACHED();
2486 public:
2487 VehicleViewWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
2489 this->CreateNestedTree();
2491 /* Sprites for the 'send to depot' button indexed by vehicle type. */
2492 static const SpriteID vehicle_view_goto_depot_sprites[] = {
2493 SPR_SEND_TRAIN_TODEPOT,
2494 SPR_SEND_ROADVEH_TODEPOT,
2495 SPR_SEND_SHIP_TODEPOT,
2496 SPR_SEND_AIRCRAFT_TODEPOT,
2498 const Vehicle *v = Vehicle::Get(window_number);
2499 this->GetWidget<NWidgetCore>(WID_VV_GOTO_DEPOT)->widget_data = vehicle_view_goto_depot_sprites[v->type];
2501 /* Sprites for the 'clone vehicle' button indexed by vehicle type. */
2502 static const SpriteID vehicle_view_clone_sprites[] = {
2503 SPR_CLONE_TRAIN,
2504 SPR_CLONE_ROADVEH,
2505 SPR_CLONE_SHIP,
2506 SPR_CLONE_AIRCRAFT,
2508 this->GetWidget<NWidgetCore>(WID_VV_CLONE)->widget_data = vehicle_view_clone_sprites[v->type];
2510 switch (v->type) {
2511 case VEH_TRAIN:
2512 this->GetWidget<NWidgetCore>(WID_VV_TURN_AROUND)->tool_tip = STR_VEHICLE_VIEW_TRAIN_REVERSE_TOOLTIP;
2513 break;
2515 case VEH_ROAD:
2516 break;
2518 case VEH_SHIP:
2519 case VEH_AIRCRAFT:
2520 this->SelectPlane(SEL_RT_REFIT);
2521 break;
2523 default: NOT_REACHED();
2525 this->FinishInitNested(window_number);
2526 this->owner = v->owner;
2527 this->GetWidget<NWidgetViewport>(WID_VV_VIEWPORT)->InitializeViewport(this, this->window_number | (1 << 31), _vehicle_view_zoom_levels[v->type]);
2529 this->GetWidget<NWidgetCore>(WID_VV_START_STOP)->tool_tip = STR_VEHICLE_VIEW_TRAIN_STATE_START_STOP_TOOLTIP + v->type;
2530 this->GetWidget<NWidgetCore>(WID_VV_CENTER_MAIN_VIEW)->tool_tip = STR_VEHICLE_VIEW_TRAIN_LOCATION_TOOLTIP + v->type;
2531 this->GetWidget<NWidgetCore>(WID_VV_REFIT)->tool_tip = STR_VEHICLE_VIEW_TRAIN_REFIT_TOOLTIP + v->type;
2532 this->GetWidget<NWidgetCore>(WID_VV_GOTO_DEPOT)->tool_tip = STR_VEHICLE_VIEW_TRAIN_SEND_TO_DEPOT_TOOLTIP + v->type;
2533 this->GetWidget<NWidgetCore>(WID_VV_SHOW_ORDERS)->tool_tip = STR_VEHICLE_VIEW_TRAIN_ORDERS_TOOLTIP + v->type;
2534 this->GetWidget<NWidgetCore>(WID_VV_SHOW_DETAILS)->tool_tip = STR_VEHICLE_VIEW_TRAIN_SHOW_DETAILS_TOOLTIP + v->type;
2535 this->GetWidget<NWidgetCore>(WID_VV_CLONE)->tool_tip = STR_VEHICLE_VIEW_CLONE_TRAIN_INFO + v->type;
2538 ~VehicleViewWindow()
2540 DeleteWindowById(WC_VEHICLE_ORDERS, this->window_number, false);
2541 DeleteWindowById(WC_VEHICLE_REFIT, this->window_number, false);
2542 DeleteWindowById(WC_VEHICLE_DETAILS, this->window_number, false);
2543 DeleteWindowById(WC_VEHICLE_TIMETABLE, this->window_number, false);
2546 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
2548 const Vehicle *v = Vehicle::Get(this->window_number);
2549 switch (widget) {
2550 case WID_VV_START_STOP:
2551 size->height = max(size->height, max(GetSpriteSize(SPR_FLAG_VEH_STOPPED).height, GetSpriteSize(SPR_FLAG_VEH_RUNNING).height) + WD_IMGBTN_TOP + WD_IMGBTN_BOTTOM);
2552 break;
2554 case WID_VV_FORCE_PROCEED:
2555 if (v->type != VEH_TRAIN) {
2556 size->height = 0;
2557 size->width = 0;
2559 break;
2561 case WID_VV_VIEWPORT:
2562 size->width = VV_INITIAL_VIEWPORT_WIDTH;
2563 size->height = (v->type == VEH_TRAIN) ? VV_INITIAL_VIEWPORT_HEIGHT_TRAIN : VV_INITIAL_VIEWPORT_HEIGHT;
2564 break;
2568 virtual void OnPaint()
2570 const Vehicle *v = Vehicle::Get(this->window_number);
2571 bool is_localcompany = v->owner == _local_company;
2572 bool refitable_and_stopped_in_depot = IsVehicleRefitable(v);
2574 this->SetWidgetDisabledState(WID_VV_GOTO_DEPOT, !is_localcompany);
2575 this->SetWidgetDisabledState(WID_VV_REFIT, !refitable_and_stopped_in_depot || !is_localcompany);
2576 this->SetWidgetDisabledState(WID_VV_CLONE, !is_localcompany);
2578 if (v->type == VEH_TRAIN) {
2579 this->SetWidgetLoweredState(WID_VV_FORCE_PROCEED, Train::From(v)->force_proceed == TFP_SIGNAL);
2580 this->SetWidgetDisabledState(WID_VV_FORCE_PROCEED, !is_localcompany);
2581 this->SetWidgetDisabledState(WID_VV_TURN_AROUND, !is_localcompany);
2584 this->DrawWidgets();
2587 virtual void SetStringParameters(int widget) const
2589 if (widget != WID_VV_CAPTION) return;
2591 const Vehicle *v = Vehicle::Get(this->window_number);
2592 SetDParam(0, v->index);
2595 virtual void DrawWidget(const Rect &r, int widget) const
2597 if (widget != WID_VV_START_STOP) return;
2599 const Vehicle *v = Vehicle::Get(this->window_number);
2600 StringID str;
2601 if (v->vehstatus & VS_CRASHED) {
2602 str = STR_VEHICLE_STATUS_CRASHED;
2603 } else if (v->type != VEH_AIRCRAFT && v->breakdown_ctr == 1) { // check for aircraft necessary?
2604 str = STR_VEHICLE_STATUS_BROKEN_DOWN;
2605 } else if (v->vehstatus & VS_STOPPED) {
2606 if (v->type == VEH_TRAIN) {
2607 if (v->cur_speed == 0) {
2608 if (Train::From(v)->gcache.cached_power == 0) {
2609 str = STR_VEHICLE_STATUS_TRAIN_NO_POWER;
2610 } else {
2611 str = STR_VEHICLE_STATUS_STOPPED;
2613 } else {
2614 SetDParam(0, v->GetDisplaySpeed());
2615 str = STR_VEHICLE_STATUS_TRAIN_STOPPING_VEL;
2617 } else { // no train
2618 str = STR_VEHICLE_STATUS_STOPPED;
2620 } else if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_TRAIN_STUCK) && !v->current_order.IsType(OT_LOADING)) {
2621 str = STR_VEHICLE_STATUS_TRAIN_STUCK;
2622 } else if (v->type == VEH_AIRCRAFT && HasBit(Aircraft::From(v)->flags, VAF_DEST_TOO_FAR) && !v->current_order.IsType(OT_LOADING)) {
2623 str = STR_VEHICLE_STATUS_AIRCRAFT_TOO_FAR;
2624 } else { // vehicle is in a "normal" state, show current order
2625 switch (v->current_order.GetType()) {
2626 case OT_GOTO_STATION: {
2627 SetDParam(0, v->current_order.GetDestination());
2628 SetDParam(1, v->GetDisplaySpeed());
2629 str = STR_VEHICLE_STATUS_HEADING_FOR_STATION_VEL;
2630 break;
2633 case OT_GOTO_DEPOT: {
2634 SetDParam(0, v->type);
2635 SetDParam(1, v->current_order.GetDestination());
2636 SetDParam(2, v->GetDisplaySpeed());
2637 if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
2638 /* This case *only* happens when multiple nearest depot orders
2639 * follow each other (including an order list only one order: a
2640 * nearest depot order) and there are no reachable depots.
2641 * It is primarily to guard for the case that there is no
2642 * depot with index 0, which would be used as fallback for
2643 * evaluating the string in the status bar. */
2644 str = STR_EMPTY;
2645 } else if (v->current_order.GetDepotActionType() & ODATFB_HALT) {
2646 str = STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_VEL;
2647 } else {
2648 str = STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_SERVICE_VEL;
2650 break;
2653 case OT_LOADING:
2654 str = STR_VEHICLE_STATUS_LOADING_UNLOADING;
2655 break;
2657 case OT_GOTO_WAYPOINT: {
2658 assert(v->type == VEH_TRAIN || v->type == VEH_SHIP);
2659 SetDParam(0, v->current_order.GetDestination());
2660 str = STR_VEHICLE_STATUS_HEADING_FOR_WAYPOINT_VEL;
2661 SetDParam(1, v->GetDisplaySpeed());
2662 break;
2665 case OT_LEAVESTATION:
2666 if (v->type != VEH_AIRCRAFT) {
2667 str = STR_VEHICLE_STATUS_LEAVING;
2668 break;
2670 /* FALL THROUGH, if aircraft. Does this even happen? */
2672 default:
2673 if (v->GetNumManualOrders() == 0) {
2674 str = STR_VEHICLE_STATUS_NO_ORDERS_VEL;
2675 SetDParam(0, v->GetDisplaySpeed());
2676 } else {
2677 str = STR_EMPTY;
2679 break;
2683 /* Draw the flag plus orders. */
2684 bool rtl = (_current_text_dir == TD_RTL);
2685 uint text_offset = max(GetSpriteSize(SPR_FLAG_VEH_STOPPED).width, GetSpriteSize(SPR_FLAG_VEH_RUNNING).width) + WD_IMGBTN_LEFT + WD_IMGBTN_RIGHT;
2686 int text_left = r.left + (rtl ? (uint)WD_FRAMERECT_LEFT : text_offset);
2687 int text_right = r.right - (rtl ? text_offset : (uint)WD_FRAMERECT_RIGHT);
2688 int image_left = (rtl ? text_right + 1 : r.left) + WD_IMGBTN_LEFT;
2689 int image = ((v->vehstatus & VS_STOPPED) != 0) ? SPR_FLAG_VEH_STOPPED : SPR_FLAG_VEH_RUNNING;
2690 int lowered = this->IsWidgetLowered(WID_VV_START_STOP) ? 1 : 0;
2691 DrawSprite(image, PAL_NONE, image_left + lowered, r.top + WD_IMGBTN_TOP + lowered);
2692 DrawString(text_left + lowered, text_right + lowered, r.top + WD_FRAMERECT_TOP + lowered, str, TC_FROMSTRING, SA_HOR_CENTER);
2695 virtual void OnClick(Point pt, int widget, int click_count)
2697 const Vehicle *v = Vehicle::Get(this->window_number);
2699 switch (widget) {
2700 case WID_VV_START_STOP: // start stop
2701 if (_ctrl_pressed) {
2702 /* Scroll to current order destination */
2703 TileIndex tile = v->current_order.GetLocation(v);
2704 if (tile != INVALID_TILE) ScrollMainWindowToTile(tile);
2705 } else {
2706 /* Start/Stop */
2707 StartStopVehicle(v, false);
2709 break;
2710 case WID_VV_CENTER_MAIN_VIEW: {// center main view
2711 const Window *mainwindow = FindWindowById(WC_MAIN_WINDOW, 0);
2712 /* code to allow the main window to 'follow' the vehicle if the ctrl key is pressed */
2713 if (_ctrl_pressed && mainwindow->viewport->zoom <= ZOOM_LVL_OUT_4X) {
2714 mainwindow->viewport->follow_vehicle = v->index;
2715 } else {
2716 ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos);
2718 break;
2721 case WID_VV_GOTO_DEPOT: // goto hangar
2722 DoCommandP(v->tile, v->index | (_ctrl_pressed ? DEPOT_SERVICE : 0U), 0, CMD_SEND_VEHICLE_TO_DEPOT);
2723 break;
2724 case WID_VV_REFIT: // refit
2725 ShowVehicleRefitWindow (this, v);
2726 break;
2727 case WID_VV_SHOW_ORDERS: // show orders
2728 if (_ctrl_pressed) {
2729 ShowTimetableWindow(v);
2730 } else {
2731 ShowOrdersWindow(v);
2733 break;
2734 case WID_VV_SHOW_DETAILS: // show details
2735 ShowVehicleDetailsWindow(v);
2736 break;
2737 case WID_VV_CLONE: // clone vehicle
2738 /* Suppress the vehicle GUI when share-cloning.
2739 * There is no point to it except for starting the vehicle.
2740 * For starting the vehicle the player has to open the depot GUI, which is
2741 * most likely already open, but is also visible in the vehicle viewport. */
2742 DoCommandP(v->tile, v->index, _ctrl_pressed ? (1 | (1 << 31)) : 0, CMD_CLONE_VEHICLE);
2743 break;
2744 case WID_VV_TURN_AROUND: // turn around
2745 assert(v->IsGroundVehicle());
2746 if (v->type == VEH_TRAIN) {
2747 DoCommandP(v->tile, v->index, 0, CMD_REVERSE_TRAIN_DIRECTION);
2748 } else {
2749 DoCommandP(v->tile, v->index, 0, CMD_TURN_ROADVEH);
2751 break;
2752 case WID_VV_FORCE_PROCEED: // force proceed
2753 assert(v->type == VEH_TRAIN);
2754 DoCommandP(v->tile, v->index, 0, CMD_FORCE_TRAIN_PROCEED);
2755 break;
2759 virtual void OnResize()
2761 if (this->viewport != NULL) {
2762 NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_VV_VIEWPORT);
2763 nvp->UpdateViewportCoordinates(this);
2767 virtual void OnTick()
2769 const Vehicle *v = Vehicle::Get(this->window_number);
2770 bool veh_stopped = v->IsStoppedInDepot();
2772 /* Widget WID_VV_GOTO_DEPOT must be hidden if the vehicle is already stopped in depot.
2773 * Widget WID_VV_CLONE_VEH should then be shown, since cloning is allowed only while in depot and stopped.
2775 PlaneSelections plane = veh_stopped ? SEL_DC_CLONE : SEL_DC_GOTO_DEPOT;
2776 NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VV_SELECT_DEPOT_CLONE); // Selection widget 'send to depot' / 'clone'.
2777 if (nwi->shown_plane + SEL_DC_BASEPLANE != plane) {
2778 this->SelectPlane(plane);
2779 this->SetWidgetDirty(WID_VV_SELECT_DEPOT_CLONE);
2781 /* The same system applies to widget WID_VV_REFIT_VEH and VVW_WIDGET_TURN_AROUND.*/
2782 if (v->IsGroundVehicle()) {
2783 PlaneSelections plane = veh_stopped ? SEL_RT_REFIT : SEL_RT_TURN_AROUND;
2784 NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VV_SELECT_REFIT_TURN);
2785 if (nwi->shown_plane + SEL_RT_BASEPLANE != plane) {
2786 this->SelectPlane(plane);
2787 this->SetWidgetDirty(WID_VV_SELECT_REFIT_TURN);
2793 * Some data on this window has become invalid.
2794 * @param data Information about the changed data.
2795 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
2797 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
2799 if (data == VIWD_AUTOREPLACE) {
2800 /* Autoreplace replaced the vehicle.
2801 * Nothing to do for this window. */
2802 return;
2806 virtual bool IsNewGRFInspectable() const
2808 return ::IsNewGRFInspectable(GetGrfSpecFeature(Vehicle::Get(this->window_number)->type), this->window_number);
2811 virtual void ShowNewGRFInspectWindow() const
2813 ::ShowNewGRFInspectWindow(GetGrfSpecFeature(Vehicle::Get(this->window_number)->type), this->window_number);
2818 /** Shows the vehicle view window of the given vehicle. */
2819 void ShowVehicleViewWindow(const Vehicle *v)
2821 AllocateWindowDescFront<VehicleViewWindow>((v->type == VEH_TRAIN) ? &_train_view_desc : &_vehicle_view_desc, v->index);
2825 * Dispatch a "vehicle selected" event if any window waits for it.
2826 * @param v selected vehicle;
2827 * @return did any window accept vehicle selection?
2829 bool VehicleClicked(const Vehicle *v)
2831 assert(v != NULL);
2832 if (!(_thd.place_mode & HT_VEHICLE)) return false;
2834 v = v->First();
2835 if (!v->IsPrimaryVehicle()) return false;
2837 return _thd.GetCallbackWnd()->OnVehicleSelect(v);
2840 void StopGlobalFollowVehicle(const Vehicle *v)
2842 Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
2843 if (w != NULL && w->viewport->follow_vehicle == v->index) {
2844 ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos, true); // lock the main view on the vehicle's last position
2845 w->viewport->follow_vehicle = INVALID_VEHICLE;
2851 * Callback for building a vehicle
2852 * @param result The result of the command.
2853 * @param tile The tile the command was executed on.
2854 * @param p1 Additional data for the command (for the #CommandProc)
2855 * @param p2 Additional data for the command (for the #CommandProc)
2857 void CcBuildVehicle(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
2859 if (result.Failed()) return;
2861 if (!IsRailDepotTile(tile) || RailVehInfo(p1)->railveh_type != RAILVEH_WAGON) {
2862 /* not a wagon */
2863 const Vehicle *v = Vehicle::Get(_new_vehicle_id);
2864 ShowVehicleViewWindow(v);
2865 return;
2868 /* find a locomotive in the depot. */
2869 const Vehicle *found = NULL;
2870 const Train *t;
2871 FOR_ALL_TRAINS(t) {
2872 if (t->IsFrontEngine() && t->tile == tile && t->IsStoppedInDepot()) {
2873 if (found != NULL) return; // must be exactly one.
2874 found = t;
2878 /* if we found a loco, */
2879 if (found != NULL) {
2880 found = found->Last();
2881 /* put the new wagon at the end of the loco. */
2882 DoCommandP(0, _new_vehicle_id | (1 << 31), found->index, CMD_MOVE_RAIL_VEHICLE);
2883 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
2888 * Get the error string to show for building a vehicle
2889 * @param tile The tile the command was executed on.
2890 * @param p1 Additional data for the command (for the #CommandProc)
2891 * @param p2 Additional data for the command (for the #CommandProc)
2892 * @param text Unused
2894 StringID GetErrBuildVehicle (TileIndex tile, uint32 p1, uint32 p2, const char *text)
2896 return GetErrBuildVeh(Engine::Get(GB(p1, 0, 16))->type);
2900 * Get the error string to show for building a vehicle
2901 * @param tile The tile the command was executed on.
2902 * @param p1 Additional data for the command (for the #CommandProc)
2903 * @param p2 Additional data for the command (for the #CommandProc)
2904 * @param text Unused
2906 StringID GetErrSellVehicle (TileIndex tile, uint32 p1, uint32 p2, const char *text)
2908 return GetErrSellVeh(Vehicle::Get(GB(p1, 0, 20)));
2912 * Get the error string to show for refitting a vehicle
2913 * @param tile The tile the command was executed on.
2914 * @param p1 Additional data for the command (for the #CommandProc)
2915 * @param p2 Additional data for the command (for the #CommandProc)
2916 * @param text Unused
2918 StringID GetErrRefitVehicle (TileIndex tile, uint32 p1, uint32 p2, const char *text)
2920 return GetErrRefitVeh(Vehicle::Get(p1));
2924 * Get the error string to show for cloning a vehicle
2925 * @param tile The tile the command was executed on.
2926 * @param p1 Additional data for the command (for the #CommandProc)
2927 * @param p2 Additional data for the command (for the #CommandProc)
2928 * @param text Unused
2930 StringID GetErrCloneVehicle (TileIndex tile, uint32 p1, uint32 p2, const char *text)
2932 return GetErrBuildVeh(Vehicle::Get(p1));
2936 * Get the error string to show for renaming a vehicle
2937 * @param tile The tile the command was executed on.
2938 * @param p1 Additional data for the command (for the #CommandProc)
2939 * @param p2 Additional data for the command (for the #CommandProc)
2940 * @param text Unused
2942 StringID GetErrRenameVehicle (TileIndex tile, uint32 p1, uint32 p2, const char *text)
2944 return STR_ERROR_CAN_T_RENAME_TRAIN + Vehicle::Get(p1)->type;
2948 * Get the error string to show for starting/stopping a vehicle
2949 * @param tile The tile the command was executed on.
2950 * @param p1 Additional data for the command (for the #CommandProc)
2951 * @param p2 Additional data for the command (for the #CommandProc)
2952 * @param text Unused
2954 StringID GetErrStartStopVehicle (TileIndex tile, uint32 p1, uint32 p2, const char *text)
2956 return _vehicle_string_startstop_table[Vehicle::Get(p1)->type];
2960 * Get the error string to show for sending a vehicle to the depot
2961 * @param tile The tile the command was executed on.
2962 * @param p1 Additional data for the command (for the #CommandProc)
2963 * @param p2 Additional data for the command (for the #CommandProc)
2964 * @param text Unused
2966 StringID GetErrSendVehicleToDepot (TileIndex tile, uint32 p1, uint32 p2, const char *text)
2968 VehicleType type;
2970 if (p1 & DEPOT_MASS_SEND) {
2971 /* Mass goto depot requested */
2972 VehicleListIdentifier vli;
2973 if (!vli.Unpack(p2)) return 0;
2974 type = vli.vtype;
2975 } else {
2976 type = Vehicle::Get(GB(p1, 0, 20))->type;
2979 return GetErrSendToDepot(type);
2983 * Get the error string to show for reversing a train
2984 * @param tile The tile the command was executed on.
2985 * @param p1 Additional data for the command (for the #CommandProc)
2986 * @param p2 Additional data for the command (for the #CommandProc)
2987 * @param text Unused
2989 StringID GetErrReverseTrain (TileIndex tile, uint32 p1, uint32 p2, const char *text)
2991 return p2 ? STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE : STR_ERROR_CAN_T_REVERSE_DIRECTION_TRAIN;
2995 * Get the width of a vehicle (including all parts of the consist) in pixels.
2996 * @param v Vehicle to get the width for.
2997 * @return Width of the vehicle.
2999 int GetVehicleWidth(Vehicle *v, EngineImageType image_type)
3001 int vehicle_width = 0;
3003 switch (v->type) {
3004 case VEH_TRAIN:
3005 for (const Train *u = Train::From(v); u != NULL; u = u->Next()) {
3006 vehicle_width += u->GetDisplayImageWidth();
3008 break;
3010 case VEH_ROAD:
3011 for (const RoadVehicle *u = RoadVehicle::From(v); u != NULL; u = u->Next()) {
3012 vehicle_width += u->GetDisplayImageWidth();
3014 break;
3016 default:
3017 bool rtl = _current_text_dir == TD_RTL;
3018 SpriteID sprite = v->GetImage(rtl ? DIR_E : DIR_W, image_type);
3019 const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
3020 vehicle_width = UnScaleGUI(real_sprite->width);
3022 break;
3025 return vehicle_width;