Remove ZeroedMemoryAllocator as a base class of Window
[openttd/fttd.git] / src / vehicle_gui.cpp
blob99d9f40effa8445fc8869ba9abadf35ffa58bf75
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 (const WindowDesc *desc, const Vehicle *v, VehicleOrderID order,
522 bool auto_refit, CargoMask cargo_mask = 0) :
523 Window (desc),
524 sel_cargo (CT_INVALID), sel_subcargo (0), cargo (NULL),
525 order (order), information_width (0),
526 vscroll (NULL), hscroll (NULL), vehicle_width (0),
527 sprite_left (0), sprite_right (0), vehicle_margin (0),
528 click_x (0), selected_vehicle (0), num_vehicles (0),
529 auto_refit (auto_refit), cargo_mask (cargo_mask)
531 assert (!auto_refit || (order != INVALID_VEH_ORDER_ID));
533 memset (this->list, 0, sizeof(this->list));
535 this->CreateNestedTree();
537 this->vscroll = this->GetScrollbar(WID_VR_SCROLLBAR);
538 this->hscroll = (v->IsGroundVehicle() ? this->GetScrollbar(WID_VR_HSCROLLBAR) : NULL);
539 this->GetWidget<NWidgetCore>(WID_VR_SELECT_HEADER)->tool_tip = STR_REFIT_TRAIN_LIST_TOOLTIP + v->type;
540 this->GetWidget<NWidgetCore>(WID_VR_MATRIX)->tool_tip = STR_REFIT_TRAIN_LIST_TOOLTIP + v->type;
541 NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_VR_REFIT);
542 nwi->widget_data = STR_REFIT_TRAIN_REFIT_BUTTON + v->type;
543 nwi->tool_tip = STR_REFIT_TRAIN_REFIT_TOOLTIP + v->type;
544 this->GetWidget<NWidgetStacked>(WID_VR_SHOW_HSCROLLBAR)->SetDisplayedPlane(v->IsGroundVehicle() ? 0 : SZSP_HORIZONTAL);
545 this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY)->tool_tip = (v->type == VEH_TRAIN) ? STR_REFIT_SELECT_VEHICLES_TOOLTIP : STR_NULL;
547 this->FinishInitNested(v->index);
548 this->owner = v->owner;
550 this->SetWidgetDisabledState (WID_VR_REFIT, !auto_refit && (this->sel_cargo == CT_INVALID));
553 virtual void OnInit()
555 if (this->cargo != NULL) {
556 /* Store the RefitOption currently in use. */
557 RefitOption current_refit_option = *(this->cargo);
559 /* Rebuild the refit list */
560 this->BuildRefitList();
561 this->sel_cargo = CT_INVALID;
562 this->sel_subcargo = 0;
563 this->cargo = NULL;
564 for (uint i = 0; this->cargo == NULL && i < NUM_CARGO; i++) {
565 for (uint j = 0; j < list[i].Length(); j++) {
566 if (list[i][j] == current_refit_option) {
567 this->sel_cargo = i;
568 this->sel_subcargo = j;
569 this->cargo = &list[i][j];
570 break;
575 this->SetWidgetDisabledState (WID_VR_REFIT, !this->auto_refit && (this->sel_cargo == CT_INVALID));
576 this->RefreshScrollbar();
577 } else {
578 /* Rebuild the refit list */
579 this->OnInvalidateData(VIWD_CONSIST_CHANGED);
583 virtual void OnPaint()
585 /* Determine amount of items for scroller. */
586 if (this->hscroll != NULL) this->hscroll->SetCount(this->vehicle_width);
588 /* Calculate sprite position. */
589 NWidgetCore *vehicle_panel_display = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY);
590 int sprite_width = max(0, ((int)vehicle_panel_display->current_x - this->vehicle_width) / 2);
591 this->sprite_left = vehicle_panel_display->pos_x;
592 this->sprite_right = vehicle_panel_display->pos_x + vehicle_panel_display->current_x - 1;
593 if (_current_text_dir == TD_RTL) {
594 this->sprite_right -= sprite_width;
595 this->vehicle_margin = vehicle_panel_display->current_x - sprite_right;
596 } else {
597 this->sprite_left += sprite_width;
598 this->vehicle_margin = sprite_left;
601 this->DrawWidgets();
604 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
606 switch (widget) {
607 case WID_VR_MATRIX:
608 resize->height = WD_MATRIX_TOP + FONT_HEIGHT_NORMAL + WD_MATRIX_BOTTOM;
609 size->height = resize->height * 8;
610 break;
612 case WID_VR_VEHICLE_PANEL_DISPLAY:
613 size->height = ScaleGUITrad(GetVehicleHeight(Vehicle::Get(this->window_number)->type));
614 break;
616 case WID_VR_INFO:
617 size->width = WD_FRAMERECT_LEFT + this->information_width + WD_FRAMERECT_RIGHT;
618 break;
620 case WID_VR_CLEAR:
621 if (!auto_refit) {
622 size->width = 0;
623 resize->width = 0;
624 fill->width = 0;
626 break;
630 virtual void SetStringParameters(int widget) const
632 if (widget == WID_VR_CAPTION) SetDParam(0, Vehicle::Get(this->window_number)->index);
636 * Gets the #StringID to use for displaying capacity.
637 * @param Cargo and cargo subtype to check for capacity.
638 * @return INVALID_STRING_ID if there is no capacity. StringID to use in any other case.
639 * @post String parameters have been set.
641 StringID GetCapacityString(RefitOption *option) const
643 assert(_current_company == _local_company);
644 Vehicle *v = Vehicle::Get(this->window_number);
645 CommandCost cost = DoCommand(v->tile, this->selected_vehicle, option->cargo | (int)this->auto_refit << 6 | option->subtype << 8 |
646 this->num_vehicles << 16, DC_QUERY_COST, CMD_REFIT_VEHICLE);
648 if (cost.Failed()) return INVALID_STRING_ID;
650 SetDParam(0, option->cargo);
651 SetDParam(1, _returned_refit_capacity);
653 Money money = cost.GetCost();
654 if (_returned_mail_refit_capacity > 0) {
655 SetDParam(2, CT_MAIL);
656 SetDParam(3, _returned_mail_refit_capacity);
657 if (this->order != INVALID_VEH_ORDER_ID) {
658 /* No predictable cost */
659 return STR_PURCHASE_INFO_AIRCRAFT_CAPACITY;
660 } else if (money <= 0) {
661 SetDParam(4, -money);
662 return STR_REFIT_NEW_CAPACITY_INCOME_FROM_AIRCRAFT_REFIT;
663 } else {
664 SetDParam(4, money);
665 return STR_REFIT_NEW_CAPACITY_COST_OF_AIRCRAFT_REFIT;
667 } else {
668 if (this->order != INVALID_VEH_ORDER_ID) {
669 /* No predictable cost */
670 SetDParam(2, STR_EMPTY);
671 return STR_PURCHASE_INFO_CAPACITY;
672 } else if (money <= 0) {
673 SetDParam(2, -money);
674 return STR_REFIT_NEW_CAPACITY_INCOME_FROM_REFIT;
675 } else {
676 SetDParam(2, money);
677 return STR_REFIT_NEW_CAPACITY_COST_OF_REFIT;
683 * Draw the list of available refit options for a consist and highlight the selected refit option (if any).
684 * @param r Rectangle of the matrix widget.
686 void DrawRefitWidget (const Rect &r) const
688 const SubtypeList *list = this->list;
689 CargoID sel_cargo = this->sel_cargo;
690 uint pos = this->vscroll->GetPosition();
691 uint limit = pos + this->vscroll->GetCapacity();
692 uint delta = this->resize.step_height;
694 uint y = r.top + WD_MATRIX_TOP;
695 uint current = 0;
697 SpriteID spr1, spr2;
698 if (this->auto_refit) {
699 spr1 = SPR_BOX_EMPTY;
700 spr2 = SPR_BOX_CHECKED;
701 } else {
702 spr1 = SPR_CIRCLE_FOLDED;
703 spr2 = SPR_CIRCLE_UNFOLDED;
705 uint iconwidth = max (GetSpriteSize(spr1).width, GetSpriteSize(spr2).width);
706 uint iconheight = GetSpriteSize(spr1).height;
707 int linecolour = _colour_gradient[COLOUR_ORANGE][4];
709 bool rtl = _current_text_dir == TD_RTL;
711 int iconleft = rtl ? r.right - WD_MATRIX_RIGHT - iconwidth : r.left + WD_MATRIX_LEFT;
712 int iconcenter = rtl ? r.right - WD_MATRIX_RIGHT - iconwidth / 2 : r.left + WD_MATRIX_LEFT + iconwidth / 2;
713 int iconinner = rtl ? r.right - WD_MATRIX_RIGHT - iconwidth : r.left + WD_MATRIX_LEFT + iconwidth;
715 int textleft = r.left + WD_MATRIX_LEFT + (rtl ? 0 : iconwidth + 4);
716 int textright = r.right - WD_MATRIX_RIGHT - (rtl ? iconwidth + 4 : 0);
718 /* Draw the list of subtypes for each cargo, and find the selected refit option (by its position). */
719 for (uint i = 0; current < limit && i < NUM_CARGO; i++) {
720 for (uint j = 0; current < limit && j < list[i].Length(); j++) {
721 const RefitOption &refit = list[i][j];
723 /* Hide subtypes if sel_cargo does not match */
724 if (sel_cargo != i && refit.subtype != 0xFF) continue;
726 /* Refit options with a position smaller than pos don't have to be drawn. */
727 if (current < pos) {
728 current++;
729 continue;
732 if (this->auto_refit) {
733 assert (list[i].Length() == 1);
734 assert (refit.subtype == 0xFF);
735 /* Draw checkbox */
736 DrawSprite (HasBit (this->cargo_mask, refit.cargo) ? SPR_BOX_CHECKED : SPR_BOX_EMPTY, PAL_NONE, iconleft, y + (FONT_HEIGHT_NORMAL - iconheight) / 2);
737 } else if (list[i].Length() > 1) {
738 if (refit.subtype != 0xFF) {
739 /* Draw tree lines */
740 int ycenter = y + FONT_HEIGHT_NORMAL / 2;
741 GfxDrawLine(iconcenter, y - WD_MATRIX_TOP, iconcenter, j == list[i].Length() - 1 ? ycenter : y - WD_MATRIX_TOP + delta - 1, linecolour);
742 GfxDrawLine(iconcenter, ycenter, iconinner, ycenter, linecolour);
743 } else {
744 /* Draw expand/collapse icon */
745 DrawSprite(sel_cargo == i ? SPR_CIRCLE_UNFOLDED : SPR_CIRCLE_FOLDED, PAL_NONE, iconleft, y + (FONT_HEIGHT_NORMAL - iconheight) / 2);
749 TextColour colour = (sel_cargo == i && this->sel_subcargo == j) ? TC_WHITE : TC_BLACK;
750 /* Get the cargo name. */
751 SetDParam(0, CargoSpec::Get(refit.cargo)->name);
752 SetDParam(1, refit.string);
753 DrawString(textleft, textright, y, STR_JUST_STRING_STRING, colour);
755 y += delta;
756 current++;
761 virtual void DrawWidget(const Rect &r, int widget) const
763 switch (widget) {
764 case WID_VR_VEHICLE_PANEL_DISPLAY: {
765 Vehicle *v = Vehicle::Get(this->window_number);
766 DrawVehicleImage(v, this->sprite_left + WD_FRAMERECT_LEFT, this->sprite_right - WD_FRAMERECT_RIGHT,
767 r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, this->hscroll != NULL ? this->hscroll->GetPosition() : 0);
769 /* Highlight selected vehicles. */
770 if (this->order != INVALID_VEH_ORDER_ID) break;
771 int x = 0;
772 switch (v->type) {
773 case VEH_TRAIN: {
774 VehicleSet vehicles_to_refit;
775 GetVehicleSet(vehicles_to_refit, Vehicle::Get(this->selected_vehicle), this->num_vehicles);
777 int left = INT32_MIN;
778 int width = 0;
780 for (Train *u = Train::From(v); u != NULL; u = u->Next()) {
781 /* Start checking. */
782 if (vehicles_to_refit.Contains(u->index) && left == INT32_MIN) {
783 left = x - this->hscroll->GetPosition() + r.left + this->vehicle_margin;
784 width = 0;
787 /* Draw a selection. */
788 if ((!vehicles_to_refit.Contains(u->index) || u->Next() == NULL) && left != INT32_MIN) {
789 if (u->Next() == NULL && vehicles_to_refit.Contains(u->index)) {
790 int current_width = u->GetDisplayImageWidth();
791 width += current_width;
792 x += current_width;
795 int right = Clamp(left + width, 0, r.right);
796 left = max(0, left);
798 if (_current_text_dir == TD_RTL) {
799 right = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY)->current_x - left;
800 left = right - width;
803 if (left != right) {
804 DrawFrameRect(left, r.top + WD_FRAMERECT_TOP, right, r.top + WD_FRAMERECT_TOP + ScaleGUITrad(14) - 1, COLOUR_WHITE, FR_BORDERONLY);
807 left = INT32_MIN;
810 int current_width = u->GetDisplayImageWidth();
811 width += current_width;
812 x += current_width;
814 break;
817 default: break;
819 break;
822 case WID_VR_MATRIX:
823 this->DrawRefitWidget (r);
824 break;
826 case WID_VR_INFO:
827 if (this->cargo != NULL) {
828 StringID string = this->GetCapacityString(this->cargo);
829 if (string != INVALID_STRING_ID) {
830 DrawStringMultiLine(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT,
831 r.top + WD_FRAMERECT_TOP, r.bottom - WD_FRAMERECT_BOTTOM, string);
834 break;
839 * Some data on this window has become invalid.
840 * @param data Information about the changed data.
841 * @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.
843 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
845 switch (data) {
846 case VIWD_AUTOREPLACE: // Autoreplace replaced the vehicle; selected_vehicle became invalid.
847 case VIWD_CONSIST_CHANGED: { // The consist has changed; rebuild the entire list.
848 /* Clear the selection. */
849 Vehicle *v = Vehicle::Get(this->window_number);
850 this->selected_vehicle = v->index;
851 this->num_vehicles = UINT8_MAX;
852 /* FALL THROUGH */
855 case 2: { // The vehicle selection has changed; rebuild the entire list.
856 if (!gui_scope) break;
857 this->BuildRefitList();
859 /* The vehicle width has changed too. */
860 this->vehicle_width = GetVehicleWidth(Vehicle::Get(this->window_number), EIT_IN_DETAILS);
861 uint max_width = 0;
863 /* Check the width of all cargo information strings. */
864 for (uint i = 0; i < NUM_CARGO; i++) {
865 for (uint j = 0; j < this->list[i].Length(); j++) {
866 StringID string = this->GetCapacityString(&list[i][j]);
867 if (string != INVALID_STRING_ID) {
868 Dimension dim = GetStringBoundingBox(string);
869 max_width = max(dim.width, max_width);
874 if (this->information_width < max_width) {
875 this->information_width = max_width;
876 this->ReInit();
878 /* FALL THROUGH */
881 case 1: // A new cargo has been selected.
882 if (!gui_scope) break;
883 this->cargo = GetRefitOption();
884 this->RefreshScrollbar();
885 break;
889 int GetClickPosition(int click_x)
891 const NWidgetCore *matrix_widget = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY);
892 if (_current_text_dir == TD_RTL) click_x = matrix_widget->current_x - click_x;
893 click_x -= this->vehicle_margin;
894 if (this->hscroll != NULL) click_x += this->hscroll->GetPosition();
896 return click_x;
899 void SetSelectedVehicles(int drag_x)
901 drag_x = GetClickPosition(drag_x);
903 int left_x = min(this->click_x, drag_x);
904 int right_x = max(this->click_x, drag_x);
905 this->num_vehicles = 0;
907 Vehicle *v = Vehicle::Get(this->window_number);
908 /* Find the vehicle part that was clicked. */
909 switch (v->type) {
910 case VEH_TRAIN: {
911 /* Don't select anything if we are not clicking in the vehicle. */
912 if (left_x >= 0) {
913 const Train *u = Train::From(v);
914 bool start_counting = false;
915 for (; u != NULL; u = u->Next()) {
916 int current_width = u->GetDisplayImageWidth();
917 left_x -= current_width;
918 right_x -= current_width;
920 if (left_x < 0 && !start_counting) {
921 this->selected_vehicle = u->index;
922 start_counting = true;
924 /* Count the first vehicle, even if articulated part */
925 this->num_vehicles++;
926 } else if (start_counting && !u->IsArticulatedPart()) {
927 /* Do not count articulated parts */
928 this->num_vehicles++;
931 if (right_x < 0) break;
935 /* If the selection is not correct, clear it. */
936 if (this->num_vehicles != 0) {
937 if (_ctrl_pressed) this->num_vehicles = UINT8_MAX;
938 break;
940 /* FALL THROUGH */
943 default:
944 /* Clear the selection. */
945 this->selected_vehicle = v->index;
946 this->num_vehicles = UINT8_MAX;
947 break;
951 virtual void OnClick(Point pt, int widget, int click_count)
953 switch (widget) {
954 case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
955 if (this->order != INVALID_VEH_ORDER_ID) break;
956 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
957 this->click_x = GetClickPosition(pt.x - nwi->pos_x);
958 this->SetSelectedVehicles(pt.x - nwi->pos_x);
959 this->SetWidgetDirty(WID_VR_VEHICLE_PANEL_DISPLAY);
960 if (!_ctrl_pressed) {
961 SetPointerMode (POINTER_DRAG, this, SPR_CURSOR_MOUSE);
962 } else {
963 /* The vehicle selection has changed. */
964 this->InvalidateData(2);
966 break;
969 case WID_VR_MATRIX: { // listbox
970 uint row = this->vscroll->GetScrolledRowFromWidget (pt.y, this, WID_VR_MATRIX);
971 CargoID c = this->SetSelection(row);
973 if (this->auto_refit) {
974 if (c != CT_INVALID) {
975 const NWidgetBase *wid = this->GetWidget<NWidgetBase> (WID_VR_MATRIX);
976 uint offset = pt.x - wid->pos_x;
977 uint width = max (GetSpriteSize(SPR_BOX_EMPTY).width, GetSpriteSize(SPR_BOX_CHECKED).width) + 5;
978 if (_current_text_dir == TD_RTL ? offset > wid->current_x - width : offset < width) {
979 ToggleBit (this->cargo_mask, c);
982 this->InvalidateData (1);
983 break;
986 /* not auto-refit */
987 this->SetWidgetDisabledState(WID_VR_REFIT, this->sel_cargo == CT_INVALID);
988 this->InvalidateData(1);
990 if (click_count == 1) break;
991 /* FALL THROUGH */
994 case WID_VR_REFIT: // refit button
995 if (this->auto_refit) {
996 const Vehicle *v = Vehicle::Get(this->window_number);
997 if (DoCommandP(v->tile, v->index | this->order << 24, this->cargo_mask, CMD_ORDER_REFIT)) this->Delete();
998 } else if (this->cargo != NULL) {
999 const Vehicle *v = Vehicle::Get(this->window_number);
1001 if (this->order == INVALID_VEH_ORDER_ID) {
1002 bool delete_window = this->selected_vehicle == v->index && this->num_vehicles == UINT8_MAX;
1003 if (DoCommandP(v->tile, this->selected_vehicle, this->cargo->cargo | this->cargo->subtype << 8 | this->num_vehicles << 16, CMD_REFIT_VEHICLE) && delete_window) this->Delete();
1004 } else {
1005 if (DoCommandP(v->tile, v->index | this->order << 24, 1 << this->cargo->cargo, CMD_ORDER_REFIT)) this->Delete();
1008 break;
1010 case WID_VR_CLEAR: // clear button
1011 assert (this->auto_refit);
1012 this->cargo_mask = 0;
1013 this->InvalidateData (1);
1014 break;
1018 virtual void OnMouseDrag(Point pt, int widget)
1020 switch (widget) {
1021 case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
1022 if (this->order != INVALID_VEH_ORDER_ID) break;
1023 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
1024 this->SetSelectedVehicles(pt.x - nwi->pos_x);
1025 this->SetWidgetDirty(WID_VR_VEHICLE_PANEL_DISPLAY);
1026 break;
1031 virtual void OnDragDrop(Point pt, int widget)
1033 switch (widget) {
1034 case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
1035 if (this->order != INVALID_VEH_ORDER_ID) break;
1036 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
1037 this->SetSelectedVehicles(pt.x - nwi->pos_x);
1038 this->InvalidateData(2);
1039 break;
1044 virtual void OnResize()
1046 this->vehicle_width = GetVehicleWidth(Vehicle::Get(this->window_number), EIT_IN_DETAILS);
1047 this->vscroll->SetCapacityFromWidget(this, WID_VR_MATRIX);
1048 if (this->hscroll != NULL) this->hscroll->SetCapacityFromWidget(this, WID_VR_VEHICLE_PANEL_DISPLAY);
1052 static const NWidgetPart _nested_vehicle_refit_widgets[] = {
1053 NWidget(NWID_HORIZONTAL),
1054 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1055 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VR_CAPTION), SetDataTip(STR_REFIT_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1056 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
1057 EndContainer(),
1058 /* Vehicle display + scrollbar. */
1059 NWidget(NWID_VERTICAL),
1060 NWidget(WWT_PANEL, COLOUR_GREY, WID_VR_VEHICLE_PANEL_DISPLAY), SetMinimalSize(228, 14), SetResize(1, 0), SetScrollbar(WID_VR_HSCROLLBAR), EndContainer(),
1061 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VR_SHOW_HSCROLLBAR),
1062 NWidget(NWID_HSCROLLBAR, COLOUR_GREY, WID_VR_HSCROLLBAR),
1063 EndContainer(),
1064 EndContainer(),
1065 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_VR_SELECT_HEADER), SetDataTip(STR_REFIT_TITLE, STR_NULL), SetResize(1, 0),
1066 /* Matrix + scrollbar. */
1067 NWidget(NWID_HORIZONTAL),
1068 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),
1069 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VR_SCROLLBAR),
1070 EndContainer(),
1071 NWidget(WWT_PANEL, COLOUR_GREY, WID_VR_INFO), SetMinimalTextLines(2, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM), SetResize(1, 0), EndContainer(),
1072 NWidget(NWID_HORIZONTAL),
1073 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
1074 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VR_CLEAR), SetDataTip(STR_REFIT_CLEAR, STR_REFIT_CLEAR_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
1075 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VR_REFIT), SetFill(1, 0), SetResize(1, 0),
1076 EndContainer(),
1077 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
1078 EndContainer(),
1081 static WindowDesc::Prefs _vehicle_refit_prefs ("view_vehicle_refit");
1083 static const WindowDesc _vehicle_refit_desc(
1084 WDP_AUTO, 240, 174,
1085 WC_VEHICLE_REFIT, WC_VEHICLE_VIEW,
1086 WDF_CONSTRUCTION,
1087 _nested_vehicle_refit_widgets, lengthof(_nested_vehicle_refit_widgets),
1088 &_vehicle_refit_prefs
1092 * Show the refit window for a vehicle
1093 * @param parent the parent window of the refit window
1094 * @param *v The vehicle to show the refit window for
1095 * @param order of the vehicle to assign refit to, or INVALID_VEH_ORDER_ID to refit the vehicle now
1096 * @param auto_refit Choose cargo for auto-refitting
1097 * @param mask Initial cargo mask of allowed refits for auto-refitting
1099 void ShowVehicleRefitWindow (Window *parent, const Vehicle *v,
1100 VehicleOrderID order, bool auto_refit, CargoMask mask)
1102 DeleteWindowById(WC_VEHICLE_REFIT, v->index);
1103 RefitWindow *w = new RefitWindow (&_vehicle_refit_desc, v, order,
1104 auto_refit, mask);
1105 w->parent = parent;
1108 /** Display list of cargo types of the engine, for the purchase information window */
1109 uint ShowRefitOptionsList(int left, int right, int y, EngineID engine)
1111 /* List of cargo types of this engine */
1112 uint32 cmask = GetUnionOfArticulatedRefitMasks(engine, false);
1113 /* List of cargo types available in this climate */
1114 uint32 lmask = _cargo_mask;
1116 /* Draw nothing if the engine is not refittable */
1117 if (HasAtMostOneBit(cmask)) return y;
1119 if (cmask == lmask) {
1120 /* Engine can be refitted to all types in this climate */
1121 SetDParam(0, STR_PURCHASE_INFO_ALL_TYPES);
1122 } else {
1123 /* Check if we are able to refit to more cargo types and unable to. If
1124 * so, invert the cargo types to list those that we can't refit to. */
1125 if (CountBits(cmask ^ lmask) < CountBits(cmask) && CountBits(cmask ^ lmask) <= 7) {
1126 cmask ^= lmask;
1127 SetDParam(0, STR_PURCHASE_INFO_ALL_BUT);
1128 } else {
1129 SetDParam(0, STR_JUST_CARGO_LIST);
1131 SetDParam(1, cmask);
1134 return DrawStringMultiLine(left, right, y, INT32_MAX, STR_PURCHASE_INFO_REFITTABLE_TO);
1137 /** Get the cargo subtype text from NewGRF for the vehicle details window. */
1138 StringID GetCargoSubtypeText(const Vehicle *v)
1140 if (HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) {
1141 uint16 cb = GetVehicleCallback(CBID_VEHICLE_CARGO_SUFFIX, 0, 0, v->engine_type, v);
1142 if (cb != CALLBACK_FAILED) {
1143 if (cb > 0x400) ErrorUnknownCallbackResult(v->GetGRFID(), CBID_VEHICLE_CARGO_SUFFIX, cb);
1144 if (cb >= 0x400 || (v->GetGRF()->grf_version < 8 && cb == 0xFF)) cb = CALLBACK_FAILED;
1146 if (cb != CALLBACK_FAILED) {
1147 return GetGRFStringID(v->GetGRFID(), 0xD000 + cb);
1150 return STR_EMPTY;
1153 /** Sort vehicles by their number */
1154 static int CDECL VehicleNumberSorter(const Vehicle * const *a, const Vehicle * const *b)
1156 return (*a)->unitnumber - (*b)->unitnumber;
1159 /** Sort vehicles by their name */
1160 static int CDECL VehicleNameSorter(const Vehicle * const *a, const Vehicle * const *b)
1162 static char last_name[2][64];
1164 if (*a != _last_vehicle[0]) {
1165 _last_vehicle[0] = *a;
1166 SetDParam(0, (*a)->index);
1167 GetString (last_name[0], STR_VEHICLE_NAME);
1170 if (*b != _last_vehicle[1]) {
1171 _last_vehicle[1] = *b;
1172 SetDParam(0, (*b)->index);
1173 GetString (last_name[1], STR_VEHICLE_NAME);
1176 int r = strnatcmp(last_name[0], last_name[1]); // Sort by name (natural sorting).
1177 return (r != 0) ? r : VehicleNumberSorter(a, b);
1180 /** Sort vehicles by their age */
1181 static int CDECL VehicleAgeSorter(const Vehicle * const *a, const Vehicle * const *b)
1183 int r = (*a)->age - (*b)->age;
1184 return (r != 0) ? r : VehicleNumberSorter(a, b);
1187 /** Sort vehicles by this year profit */
1188 static int CDECL VehicleProfitThisYearSorter(const Vehicle * const *a, const Vehicle * const *b)
1190 int r = ClampToI32((*a)->GetDisplayProfitThisYear() - (*b)->GetDisplayProfitThisYear());
1191 return (r != 0) ? r : VehicleNumberSorter(a, b);
1194 /** Sort vehicles by last year profit */
1195 static int CDECL VehicleProfitLastYearSorter(const Vehicle * const *a, const Vehicle * const *b)
1197 int r = ClampToI32((*a)->GetDisplayProfitLastYear() - (*b)->GetDisplayProfitLastYear());
1198 return (r != 0) ? r : VehicleNumberSorter(a, b);
1201 /** Sort vehicles by their cargo */
1202 static int CDECL VehicleCargoSorter(const Vehicle * const *a, const Vehicle * const *b)
1204 const Vehicle *v;
1205 CargoArray diff;
1207 /* Append the cargo of the connected waggons */
1208 for (v = *a; v != NULL; v = v->Next()) diff[v->cargo_type] += v->cargo_cap;
1209 for (v = *b; v != NULL; v = v->Next()) diff[v->cargo_type] -= v->cargo_cap;
1211 int r = 0;
1212 for (CargoID i = 0; i < NUM_CARGO; i++) {
1213 r = diff[i];
1214 if (r != 0) break;
1217 return (r != 0) ? r : VehicleNumberSorter(a, b);
1220 /** Sort vehicles by their reliability */
1221 static int CDECL VehicleReliabilitySorter(const Vehicle * const *a, const Vehicle * const *b)
1223 int r = (*a)->reliability - (*b)->reliability;
1224 return (r != 0) ? r : VehicleNumberSorter(a, b);
1227 /** Sort vehicles by their max speed */
1228 static int CDECL VehicleMaxSpeedSorter(const Vehicle * const *a, const Vehicle * const *b)
1230 int r = (*a)->vcache.cached_max_speed - (*b)->vcache.cached_max_speed;
1231 return (r != 0) ? r : VehicleNumberSorter(a, b);
1234 /** Sort vehicles by model */
1235 static int CDECL VehicleModelSorter(const Vehicle * const *a, const Vehicle * const *b)
1237 int r = (*a)->engine_type - (*b)->engine_type;
1238 return (r != 0) ? r : VehicleNumberSorter(a, b);
1241 /** Sort vehicles by their value */
1242 static int CDECL VehicleValueSorter(const Vehicle * const *a, const Vehicle * const *b)
1244 const Vehicle *u;
1245 Money diff = 0;
1247 for (u = *a; u != NULL; u = u->Next()) diff += u->value;
1248 for (u = *b; u != NULL; u = u->Next()) diff -= u->value;
1250 int r = ClampToI32(diff);
1251 return (r != 0) ? r : VehicleNumberSorter(a, b);
1254 /** Sort vehicles by their length */
1255 static int CDECL VehicleLengthSorter(const Vehicle * const *a, const Vehicle * const *b)
1257 int r = (*a)->GetGroundVehicleCache()->cached_total_length - (*b)->GetGroundVehicleCache()->cached_total_length;
1258 return (r != 0) ? r : VehicleNumberSorter(a, b);
1261 /** Sort vehicles by the time they can still live */
1262 static int CDECL VehicleTimeToLiveSorter(const Vehicle * const *a, const Vehicle * const *b)
1264 int r = ClampToI32(((*a)->max_age - (*a)->age) - ((*b)->max_age - (*b)->age));
1265 return (r != 0) ? r : VehicleNumberSorter(a, b);
1268 /** Sort vehicles by the timetable delay */
1269 static int CDECL VehicleTimetableDelaySorter(const Vehicle * const *a, const Vehicle * const *b)
1271 int r = (*a)->lateness_counter - (*b)->lateness_counter;
1272 return (r != 0) ? r : VehicleNumberSorter(a, b);
1275 void InitializeGUI()
1277 MemSetT(&_sorting, 0);
1281 * Assign a vehicle window a new vehicle
1282 * @param window_class WindowClass to search for
1283 * @param from_index the old vehicle ID
1284 * @param to_index the new vehicle ID
1286 static inline void ChangeVehicleWindow(WindowClass window_class, VehicleID from_index, VehicleID to_index)
1288 Window *w = FindWindowById(window_class, from_index);
1289 if (w != NULL) {
1290 /* Update window_number */
1291 w->window_number = to_index;
1292 if (w->viewport != NULL) w->viewport->follow_vehicle = to_index;
1294 /* Update vehicle drag data */
1295 if (_thd.window_class == window_class && _thd.window_number == (WindowNumber)from_index) {
1296 _thd.window_number = to_index;
1299 /* Notify the window. */
1300 w->InvalidateData(VIWD_AUTOREPLACE, false);
1305 * Report a change in vehicle IDs (due to autoreplace) to affected vehicle windows.
1306 * @param from_index the old vehicle ID
1307 * @param to_index the new vehicle ID
1309 void ChangeVehicleViewWindow(VehicleID from_index, VehicleID to_index)
1311 ChangeVehicleWindow(WC_VEHICLE_VIEW, from_index, to_index);
1312 ChangeVehicleWindow(WC_VEHICLE_ORDERS, from_index, to_index);
1313 ChangeVehicleWindow(WC_VEHICLE_REFIT, from_index, to_index);
1314 ChangeVehicleWindow(WC_VEHICLE_DETAILS, from_index, to_index);
1315 ChangeVehicleWindow(WC_VEHICLE_TIMETABLE, from_index, to_index);
1318 static const NWidgetPart _nested_vehicle_list[] = {
1319 NWidget(NWID_HORIZONTAL),
1320 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1321 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VL_CAPTION),
1322 NWidget(WWT_SHADEBOX, COLOUR_GREY),
1323 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
1324 NWidget(WWT_STICKYBOX, COLOUR_GREY),
1325 EndContainer(),
1327 NWidget(NWID_HORIZONTAL),
1328 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VL_SORT_ORDER), SetMinimalSize(81, 12), SetFill(0, 1), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
1329 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_SORT_BY_PULLDOWN), SetMinimalSize(167, 12), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
1330 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(12, 12), SetFill(1, 1), SetResize(1, 0),
1331 EndContainer(),
1332 EndContainer(),
1334 NWidget(NWID_HORIZONTAL),
1335 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),
1336 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VL_SCROLLBAR),
1337 EndContainer(),
1339 NWidget(NWID_HORIZONTAL),
1340 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VL_HIDE_BUTTONS),
1341 NWidget(NWID_HORIZONTAL),
1342 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VL_AVAILABLE_VEHICLES), SetMinimalSize(106, 12), SetFill(0, 1),
1343 SetDataTip(STR_BLACK_STRING, STR_VEHICLE_LIST_AVAILABLE_ENGINES_TOOLTIP),
1344 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(0, 12), SetResize(1, 0), SetFill(1, 1), EndContainer(),
1345 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_MANAGE_VEHICLES_DROPDOWN), SetMinimalSize(118, 12), SetFill(0, 1),
1346 SetDataTip(STR_VEHICLE_LIST_MANAGE_LIST, STR_VEHICLE_LIST_MANAGE_LIST_TOOLTIP),
1347 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VL_STOP_ALL), SetMinimalSize(12, 12), SetFill(0, 1),
1348 SetDataTip(SPR_FLAG_VEH_STOPPED, STR_VEHICLE_LIST_MASS_STOP_LIST_TOOLTIP),
1349 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VL_START_ALL), SetMinimalSize(12, 12), SetFill(0, 1),
1350 SetDataTip(SPR_FLAG_VEH_RUNNING, STR_VEHICLE_LIST_MASS_START_LIST_TOOLTIP),
1351 EndContainer(),
1352 /* Widget to be shown for other companies hiding the previous 5 widgets. */
1353 NWidget(WWT_PANEL, COLOUR_GREY), SetFill(1, 1), SetResize(1, 0), EndContainer(),
1354 EndContainer(),
1355 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
1356 EndContainer(),
1359 static void DrawSmallOrderList(const Vehicle *v, int left, int right, int y, VehicleOrderID start = 0)
1361 const Order *order = v->GetOrder(start);
1362 if (order == NULL) return;
1364 bool rtl = _current_text_dir == TD_RTL;
1365 int l_offset = rtl ? 0 : ScaleGUITrad(6);
1366 int r_offset = rtl ? ScaleGUITrad(6) : 0;
1367 int i = 0;
1368 VehicleOrderID oid = start;
1370 do {
1371 if (oid == v->cur_real_order_index) DrawString(left, right, y, STR_TINY_RIGHT_ARROW, TC_BLACK);
1373 if (order->IsType(OT_GOTO_STATION)) {
1374 SetDParam(0, order->GetDestination());
1375 DrawString(left + l_offset, right - r_offset, y, STR_TINY_BLACK_STATION);
1377 y += FONT_HEIGHT_SMALL;
1378 if (++i == 4) break;
1381 oid++;
1382 order = order->next;
1383 if (order == NULL) {
1384 order = v->orders.list->GetFirstOrder();
1385 oid = 0;
1387 } while (oid != start);
1391 * Draws an image of a vehicle chain
1392 * @param v Front vehicle
1393 * @param left The minimum horizontal position
1394 * @param right The maximum horizontal position
1395 * @param y Vertical position to draw at
1396 * @param selection Selected vehicle to draw a frame around
1397 * @param skip Number of pixels to skip at the front (for scrolling)
1399 void DrawVehicleImage(const Vehicle *v, int left, int right, int y, VehicleID selection, EngineImageType image_type, int skip)
1401 switch (v->type) {
1402 case VEH_TRAIN: DrawTrainImage(Train::From(v), left, right, y, selection, image_type, skip); break;
1403 case VEH_ROAD: DrawRoadVehImage(v, left, right, y, selection, image_type, skip); break;
1404 case VEH_SHIP: DrawShipImage(v, left, right, y, selection, image_type); break;
1405 case VEH_AIRCRAFT: DrawAircraftImage(v, left, right, y, selection, image_type); break;
1406 default: NOT_REACHED();
1411 * Get the height of a vehicle in the vehicle list GUIs.
1412 * @param type the vehicle type to look at
1413 * @param divisor the resulting height must be dividable by this
1414 * @return the height
1416 uint GetVehicleListHeight(VehicleType type, uint divisor)
1418 /* Name + vehicle + profit */
1419 uint base = ScaleGUITrad(GetVehicleHeight(type)) + 2 * FONT_HEIGHT_SMALL;
1420 /* Drawing of the 4 small orders + profit*/
1421 if (type >= VEH_SHIP) base = max(base, 5U * FONT_HEIGHT_SMALL);
1423 if (divisor == 1) return base;
1425 /* Make sure the height is dividable by divisor */
1426 uint rem = base % divisor;
1427 return base + (rem == 0 ? 0 : divisor - rem);
1431 * Draw all the vehicle list items.
1432 * @param selected_vehicle The vehicle that is to be highlighted.
1433 * @param line_height Height of a single item line.
1434 * @param r Rectangle with edge positions of the matrix widget.
1436 void BaseVehicleListWindow::DrawVehicleListItems(VehicleID selected_vehicle, int line_height, const Rect &r) const
1438 int left = r.left + WD_MATRIX_LEFT;
1439 int right = r.right - WD_MATRIX_RIGHT;
1440 int width = right - left;
1441 bool rtl = _current_text_dir == TD_RTL;
1443 int text_offset = max<int>(GetSpriteSize(SPR_PROFIT_LOT).width, GetDigitWidth() * this->unitnumber_digits) + WD_FRAMERECT_RIGHT;
1444 int text_left = left + (rtl ? 0 : text_offset);
1445 int text_right = right - (rtl ? text_offset : 0);
1447 bool show_orderlist = this->vli.vtype >= VEH_SHIP;
1448 int orderlist_left = left + (rtl ? 0 : max(ScaleGUITrad(100) + text_offset, width / 2));
1449 int orderlist_right = right - (rtl ? max(ScaleGUITrad(100) + text_offset, width / 2) : 0);
1451 int image_left = (rtl && show_orderlist) ? orderlist_right : text_left;
1452 int image_right = (!rtl && show_orderlist) ? orderlist_left : text_right;
1454 int vehicle_button_x = rtl ? right - GetSpriteSize(SPR_PROFIT_LOT).width : left;
1456 int y = r.top;
1457 uint max = min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->vehicles.Length());
1458 for (uint i = this->vscroll->GetPosition(); i < max; ++i) {
1459 const Vehicle *v = this->vehicles[i];
1460 StringID str;
1462 SetDParam(0, v->GetDisplayProfitThisYear());
1463 SetDParam(1, v->GetDisplayProfitLastYear());
1465 DrawVehicleImage(v, image_left, image_right, y + FONT_HEIGHT_SMALL - 1, selected_vehicle, EIT_IN_LIST, 0);
1466 DrawString(text_left, text_right, y + line_height - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1, STR_VEHICLE_LIST_PROFIT_THIS_YEAR_LAST_YEAR);
1468 if (v->name != NULL) {
1469 /* The vehicle got a name so we will print it */
1470 SetDParam(0, v->index);
1471 DrawString(text_left, text_right, y, STR_TINY_BLACK_VEHICLE);
1472 } else if (v->group_id != DEFAULT_GROUP) {
1473 /* The vehicle has no name, but is member of a group, so print group name */
1474 SetDParam(0, v->group_id);
1475 DrawString(text_left, text_right, y, STR_TINY_GROUP, TC_BLACK);
1478 if (show_orderlist) DrawSmallOrderList(v, orderlist_left, orderlist_right, y, v->cur_real_order_index);
1480 if (v->IsChainInDepot()) {
1481 str = STR_BLUE_COMMA;
1482 } else {
1483 str = (v->age > v->max_age - DAYS_IN_LEAP_YEAR) ? STR_RED_COMMA : STR_BLACK_COMMA;
1486 SetDParam(0, v->unitnumber);
1487 DrawString(left, right, y + 2, str);
1489 DrawVehicleProfitButton(v, vehicle_button_x, y + FONT_HEIGHT_NORMAL + 3);
1491 y += line_height;
1496 * Window for the (old) vehicle listing.
1498 * bitmask for w->window_number
1499 * 0-7 CompanyID (owner)
1500 * 8-10 window type (use flags in vehicle_gui.h)
1501 * 11-15 vehicle type (using VEH_, but can be compressed to fewer bytes if needed)
1502 * 16-31 StationID or OrderID depending on window type (bit 8-10)
1504 struct VehicleListWindow : public BaseVehicleListWindow {
1505 private:
1506 /** Enumeration of planes of the button row at the bottom. */
1507 enum ButtonPlanes {
1508 BP_SHOW_BUTTONS, ///< Show the buttons.
1509 BP_HIDE_BUTTONS, ///< Show the empty panel.
1512 public:
1513 VehicleListWindow (const WindowDesc *desc, WindowNumber window_number) : BaseVehicleListWindow(desc, window_number)
1515 /* Set up sorting. Make the window-specific _sorting variable
1516 * point to the correct global _sorting struct so we are freed
1517 * from having conditionals during window operation */
1518 switch (this->vli.vtype) {
1519 case VEH_TRAIN: this->sorting = &_sorting.train; break;
1520 case VEH_ROAD: this->sorting = &_sorting.roadveh; break;
1521 case VEH_SHIP: this->sorting = &_sorting.ship; break;
1522 case VEH_AIRCRAFT: this->sorting = &_sorting.aircraft; break;
1523 default: NOT_REACHED();
1526 this->CreateNestedTree();
1528 this->vscroll = this->GetScrollbar(WID_VL_SCROLLBAR);
1530 this->vehicles.SetListing(*this->sorting);
1531 this->vehicles.ForceRebuild();
1532 this->vehicles.NeedResort();
1533 this->BuildVehicleList();
1534 this->SortVehicleList();
1536 /* Set up the window widgets */
1537 this->GetWidget<NWidgetCore>(WID_VL_LIST)->tool_tip = STR_VEHICLE_LIST_TRAIN_LIST_TOOLTIP + this->vli.vtype;
1539 if (this->vli.type == VL_SHARED_ORDERS) {
1540 this->GetWidget<NWidgetCore>(WID_VL_CAPTION)->widget_data = STR_VEHICLE_LIST_SHARED_ORDERS_LIST_CAPTION;
1541 } else {
1542 this->GetWidget<NWidgetCore>(WID_VL_CAPTION)->widget_data = STR_VEHICLE_LIST_TRAIN_CAPTION + this->vli.vtype;
1545 this->FinishInitNested(window_number);
1546 if (this->vli.company != OWNER_NONE) this->owner = this->vli.company;
1549 void OnDelete (void) FINAL_OVERRIDE
1551 *this->sorting = this->vehicles.GetListing();
1554 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
1556 switch (widget) {
1557 case WID_VL_LIST:
1558 resize->height = GetVehicleListHeight(this->vli.vtype, 1);
1560 switch (this->vli.vtype) {
1561 case VEH_TRAIN:
1562 case VEH_ROAD:
1563 size->height = 6 * resize->height;
1564 break;
1565 case VEH_SHIP:
1566 case VEH_AIRCRAFT:
1567 size->height = 4 * resize->height;
1568 break;
1569 default: NOT_REACHED();
1571 break;
1573 case WID_VL_SORT_ORDER: {
1574 Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
1575 d.width += padding.width + Window::SortButtonWidth() * 2; // Doubled since the string is centred and it also looks better.
1576 d.height += padding.height;
1577 *size = maxdim(*size, d);
1578 break;
1581 case WID_VL_MANAGE_VEHICLES_DROPDOWN: {
1582 Dimension d = this->GetActionDropdownSize(this->vli.type == VL_STANDARD, false);
1583 d.height += padding.height;
1584 d.width += padding.width;
1585 *size = maxdim(*size, d);
1586 break;
1591 virtual void SetStringParameters(int widget) const
1593 switch (widget) {
1594 case WID_VL_AVAILABLE_VEHICLES:
1595 SetDParam(0, STR_VEHICLE_LIST_AVAILABLE_TRAINS + this->vli.vtype);
1596 break;
1598 case WID_VL_CAPTION: {
1599 switch (this->vli.type) {
1600 case VL_SHARED_ORDERS: // Shared Orders
1601 if (this->vehicles.Length() == 0) {
1602 /* We can't open this window without vehicles using this order
1603 * and we should close the window when deleting the order. */
1604 NOT_REACHED();
1606 SetDParam(0, this->vscroll->GetCount());
1607 break;
1609 case VL_STANDARD: // Company Name
1610 SetDParam(0, STR_COMPANY_NAME);
1611 SetDParam(1, this->vli.index);
1612 SetDParam(3, this->vscroll->GetCount());
1613 break;
1615 case VL_STATION_LIST: // Station/Waypoint Name
1616 SetDParam(0, BaseStation::Get(this->vli.index)->IsWaypoint() ? STR_WAYPOINT_NAME : STR_STATION_NAME);
1617 SetDParam(1, this->vli.index);
1618 SetDParam(3, this->vscroll->GetCount());
1619 break;
1621 case VL_DEPOT_LIST:
1622 SetDParam(0, STR_DEPOT_CAPTION);
1623 SetDParam(1, this->vli.vtype);
1624 SetDParam(2, this->vli.index);
1625 SetDParam(3, this->vscroll->GetCount());
1626 break;
1627 default: NOT_REACHED();
1629 break;
1634 virtual void DrawWidget(const Rect &r, int widget) const
1636 switch (widget) {
1637 case WID_VL_SORT_ORDER:
1638 /* draw arrow pointing up/down for ascending/descending sorting */
1639 this->DrawSortButtonState(widget, this->vehicles.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
1640 break;
1642 case WID_VL_LIST:
1643 this->DrawVehicleListItems(INVALID_VEHICLE, this->resize.step_height, r);
1644 break;
1648 virtual void OnPaint()
1650 this->BuildVehicleList();
1651 this->SortVehicleList();
1653 if (this->vehicles.Length() == 0 && this->IsWidgetLowered(WID_VL_MANAGE_VEHICLES_DROPDOWN)) {
1654 HideDropDownMenu(this);
1657 /* Hide the widgets that we will not use in this window
1658 * Some windows contains actions only fit for the owner */
1659 int plane_to_show = (this->owner == _local_company) ? BP_SHOW_BUTTONS : BP_HIDE_BUTTONS;
1660 NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VL_HIDE_BUTTONS);
1661 if (plane_to_show != nwi->shown_plane) {
1662 nwi->SetDisplayedPlane(plane_to_show);
1663 nwi->SetDirty(this);
1665 if (this->owner == _local_company) {
1666 this->SetWidgetDisabledState(WID_VL_AVAILABLE_VEHICLES, this->vli.type != VL_STANDARD);
1667 this->SetWidgetsDisabledState(this->vehicles.Length() == 0,
1668 WID_VL_MANAGE_VEHICLES_DROPDOWN,
1669 WID_VL_STOP_ALL,
1670 WID_VL_START_ALL,
1671 WIDGET_LIST_END);
1674 /* Set text of sort by dropdown widget. */
1675 this->GetWidget<NWidgetCore>(WID_VL_SORT_BY_PULLDOWN)->widget_data = this->vehicle_sorter_names[this->vehicles.SortType()];
1677 this->DrawWidgets();
1680 virtual void OnClick(Point pt, int widget, int click_count)
1682 switch (widget) {
1683 case WID_VL_SORT_ORDER: // Flip sorting method ascending/descending
1684 this->vehicles.ToggleSortOrder();
1685 this->SetDirty();
1686 break;
1688 case WID_VL_SORT_BY_PULLDOWN:// Select sorting criteria dropdown menu
1689 ShowDropDownMenu(this, this->vehicle_sorter_names, this->vehicles.SortType(), WID_VL_SORT_BY_PULLDOWN, 0,
1690 (this->vli.vtype == VEH_TRAIN || this->vli.vtype == VEH_ROAD) ? 0 : (1 << 10));
1691 return;
1693 case WID_VL_LIST: { // Matrix to show vehicles
1694 uint id_v = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_VL_LIST);
1695 if (id_v >= this->vehicles.Length()) return; // click out of list bound
1697 const Vehicle *v = this->vehicles[id_v];
1698 if (!VehicleClicked(v)) ShowVehicleViewWindow(v);
1699 break;
1702 case WID_VL_AVAILABLE_VEHICLES:
1703 ShowBuildVehicleWindow(INVALID_TILE, this->vli.vtype);
1704 break;
1706 case WID_VL_MANAGE_VEHICLES_DROPDOWN: {
1707 DropDownList *list = this->BuildActionDropdownList(VehicleListIdentifier(this->window_number).type == VL_STANDARD, false);
1708 ShowDropDownList(this, list, 0, WID_VL_MANAGE_VEHICLES_DROPDOWN);
1709 break;
1712 case WID_VL_STOP_ALL:
1713 case WID_VL_START_ALL:
1714 DoCommandP(0, (1 << 1) | (widget == WID_VL_START_ALL ? (1 << 0) : 0), this->window_number, CMD_MASS_START_STOP);
1715 break;
1719 virtual void OnDropdownSelect(int widget, int index)
1721 switch (widget) {
1722 case WID_VL_SORT_BY_PULLDOWN:
1723 this->vehicles.SetSortType(index);
1724 break;
1725 case WID_VL_MANAGE_VEHICLES_DROPDOWN:
1726 assert(this->vehicles.Length() != 0);
1728 switch (index) {
1729 case ADI_REPLACE: // Replace window
1730 ShowReplaceGroupVehicleWindow(ALL_GROUP, this->vli.vtype);
1731 break;
1732 case ADI_SERVICE: // Send for servicing
1733 case ADI_DEPOT: // Send to Depots
1734 DoCommandP(0, DEPOT_MASS_SEND | (index == ADI_SERVICE ? DEPOT_SERVICE : (DepotCommand)0), this->window_number, CMD_SEND_VEHICLE_TO_DEPOT);
1735 break;
1737 default: NOT_REACHED();
1739 break;
1740 default: NOT_REACHED();
1742 this->SetDirty();
1745 virtual void OnTick()
1747 if (_pause_mode != PM_UNPAUSED) return;
1748 if (this->vehicles.NeedResort()) {
1749 StationID station = (this->vli.type == VL_STATION_LIST) ? this->vli.index : INVALID_STATION;
1751 DEBUG(misc, 3, "Periodic resort %d list company %d at station %d", this->vli.vtype, this->owner, station);
1752 this->SetDirty();
1756 virtual void OnResize()
1758 this->vscroll->SetCapacityFromWidget(this, WID_VL_LIST);
1762 * Some data on this window has become invalid.
1763 * @param data Information about the changed data.
1764 * @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.
1766 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
1768 if (!gui_scope && HasBit(data, 31) && this->vli.type == VL_SHARED_ORDERS) {
1769 /* Needs to be done in command-scope, so everything stays valid */
1770 this->vli.index = GB(data, 0, 20);
1771 this->window_number = this->vli.Pack();
1772 this->vehicles.ForceRebuild();
1773 return;
1776 if (data == 0) {
1777 /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
1778 this->vehicles.ForceRebuild();
1779 } else {
1780 this->vehicles.ForceResort();
1785 static WindowDesc::Prefs _vehicle_list_other_prefs ("list_vehicles");
1787 static WindowDesc::Prefs _vehicle_list_train_prefs ("list_vehicles_train");
1789 static const WindowDesc _vehicle_list_train_desc(
1790 WDP_AUTO, 325, 246,
1791 WC_TRAINS_LIST, WC_NONE,
1793 _nested_vehicle_list, lengthof(_nested_vehicle_list),
1794 &_vehicle_list_train_prefs
1797 static const WindowDesc _vehicle_list_roadveh_desc(
1798 WDP_AUTO, 260, 246,
1799 WC_ROADVEH_LIST, WC_NONE,
1801 _nested_vehicle_list, lengthof(_nested_vehicle_list),
1802 &_vehicle_list_other_prefs
1805 static const WindowDesc _vehicle_list_ship_desc(
1806 WDP_AUTO, 260, 246,
1807 WC_SHIPS_LIST, WC_NONE,
1809 _nested_vehicle_list, lengthof(_nested_vehicle_list),
1810 &_vehicle_list_other_prefs
1813 static const WindowDesc _vehicle_list_aircraft_desc(
1814 WDP_AUTO, 260, 246,
1815 WC_AIRCRAFT_LIST, WC_NONE,
1817 _nested_vehicle_list, lengthof(_nested_vehicle_list),
1818 &_vehicle_list_other_prefs
1821 static void ShowVehicleListWindowLocal(CompanyID company, VehicleListType vlt, VehicleType vehicle_type, uint32 unique_number)
1823 static const WindowDesc *const descs[VEH_COMPANY_END] = {
1824 &_vehicle_list_train_desc, // VEH_TRAIN
1825 &_vehicle_list_roadveh_desc, // VEH_ROAD
1826 &_vehicle_list_ship_desc, // VEH_SHIP
1827 &_vehicle_list_aircraft_desc, // VEH_AIRCRAFT
1830 if (!Company::IsValidID(company) && company != OWNER_NONE) return;
1832 WindowNumber num = VehicleListIdentifier(vlt, vehicle_type, company, unique_number).Pack();
1833 AllocateWindowDescFront<VehicleListWindow> (descs[vehicle_type], num);
1836 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type)
1838 /* If _settings_client.gui.advanced_vehicle_list > 1, display the Advanced list
1839 * if _settings_client.gui.advanced_vehicle_list == 1, display Advanced list only for local company
1840 * if _ctrl_pressed, do the opposite action (Advanced list x Normal list)
1843 if ((_settings_client.gui.advanced_vehicle_list > (uint)(company != _local_company)) != _ctrl_pressed) {
1844 ShowCompanyGroup(company, vehicle_type);
1845 } else {
1846 ShowVehicleListWindowLocal(company, VL_STANDARD, vehicle_type, company);
1850 void ShowVehicleListWindow(const Vehicle *v)
1852 ShowVehicleListWindowLocal(v->owner, VL_SHARED_ORDERS, v->type, v->FirstShared()->index);
1855 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, StationID station)
1857 ShowVehicleListWindowLocal(company, VL_STATION_LIST, vehicle_type, station);
1860 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, TileIndex depot_tile)
1862 uint16 depot_airport_index;
1864 if (vehicle_type == VEH_AIRCRAFT) {
1865 depot_airport_index = GetStationIndex(depot_tile);
1866 } else {
1867 depot_airport_index = GetDepotIndex(depot_tile);
1869 ShowVehicleListWindowLocal(company, VL_DEPOT_LIST, vehicle_type, depot_airport_index);
1873 /* Unified vehicle GUI - Vehicle Details Window */
1875 assert_compile(WID_VD_DETAILS_CARGO_CARRIED == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_CARGO );
1876 assert_compile(WID_VD_DETAILS_TRAIN_VEHICLES == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_INFO );
1877 assert_compile(WID_VD_DETAILS_CAPACITY_OF_EACH == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_CAPACITY);
1878 assert_compile(WID_VD_DETAILS_TOTAL_CARGO == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_TOTALS );
1880 /** Vehicle details widgets (other than train). */
1881 static const NWidgetPart _nested_nontrain_vehicle_details_widgets[] = {
1882 NWidget(NWID_HORIZONTAL),
1883 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1884 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VD_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1885 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 */),
1886 NWidget(WWT_SHADEBOX, COLOUR_GREY),
1887 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
1888 NWidget(WWT_STICKYBOX, COLOUR_GREY),
1889 EndContainer(),
1890 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_TOP_DETAILS), SetMinimalSize(405, 42), SetResize(1, 0), EndContainer(),
1891 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_MIDDLE_DETAILS), SetMinimalSize(405, 45), SetResize(1, 0), EndContainer(),
1892 NWidget(NWID_HORIZONTAL),
1893 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_DECREASE_SERVICING_INTERVAL), SetFill(0, 1),
1894 SetDataTip(AWV_DECREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
1895 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_INCREASE_SERVICING_INTERVAL), SetFill(0, 1),
1896 SetDataTip(AWV_INCREASE, STR_VEHICLE_DETAILS_INCREASE_SERVICING_INTERVAL_TOOLTIP),
1897 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VD_SERVICE_INTERVAL_DROPDOWN), SetFill(0, 1),
1898 SetDataTip(STR_EMPTY, STR_SERVICE_INTERVAL_DROPDOWN_TOOLTIP),
1899 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_SERVICING_INTERVAL), SetFill(1, 1), SetResize(1, 0), EndContainer(),
1900 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
1901 EndContainer(),
1904 /** Train details widgets. */
1905 static const NWidgetPart _nested_train_vehicle_details_widgets[] = {
1906 NWidget(NWID_HORIZONTAL),
1907 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1908 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VD_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1909 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 */),
1910 NWidget(WWT_SHADEBOX, COLOUR_GREY),
1911 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
1912 NWidget(WWT_STICKYBOX, COLOUR_GREY),
1913 EndContainer(),
1914 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_TOP_DETAILS), SetResize(1, 0), SetMinimalSize(405, 42), EndContainer(),
1915 NWidget(NWID_HORIZONTAL),
1916 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),
1917 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VD_SCROLLBAR),
1918 EndContainer(),
1919 NWidget(NWID_HORIZONTAL),
1920 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_DECREASE_SERVICING_INTERVAL), SetFill(0, 1),
1921 SetDataTip(AWV_DECREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
1922 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_INCREASE_SERVICING_INTERVAL), SetFill(0, 1),
1923 SetDataTip(AWV_INCREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
1924 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VD_SERVICE_INTERVAL_DROPDOWN), SetFill(0, 1),
1925 SetDataTip(STR_EMPTY, STR_SERVICE_INTERVAL_DROPDOWN_TOOLTIP),
1926 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_SERVICING_INTERVAL), SetFill(1, 1), SetResize(1, 0), EndContainer(),
1927 EndContainer(),
1928 NWidget(NWID_HORIZONTAL),
1929 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_CARGO_CARRIED), SetMinimalSize(96, 12),
1930 SetDataTip(STR_VEHICLE_DETAIL_TAB_CARGO, STR_VEHICLE_DETAILS_TRAIN_CARGO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
1931 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_TRAIN_VEHICLES), SetMinimalSize(99, 12),
1932 SetDataTip(STR_VEHICLE_DETAIL_TAB_INFORMATION, STR_VEHICLE_DETAILS_TRAIN_INFORMATION_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
1933 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_CAPACITY_OF_EACH), SetMinimalSize(99, 12),
1934 SetDataTip(STR_VEHICLE_DETAIL_TAB_CAPACITIES, STR_VEHICLE_DETAILS_TRAIN_CAPACITIES_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
1935 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_TOTAL_CARGO), SetMinimalSize(99, 12),
1936 SetDataTip(STR_VEHICLE_DETAIL_TAB_TOTAL_CARGO, STR_VEHICLE_DETAILS_TRAIN_TOTAL_CARGO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
1937 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
1938 EndContainer(),
1942 extern int GetTrainDetailsWndVScroll(VehicleID veh_id, TrainDetailsWindowTabs det_tab);
1943 extern void DrawTrainDetails(const Train *v, int left, int right, int y, int vscroll_pos, uint16 vscroll_cap, TrainDetailsWindowTabs det_tab);
1944 extern void DrawRoadVehDetails(const Vehicle *v, int left, int right, int y);
1945 extern void DrawShipDetails(const Vehicle *v, int left, int right, int y);
1946 extern void DrawAircraftDetails(const Aircraft *v, int left, int right, int y);
1948 static StringID _service_interval_dropdown[] = {
1949 STR_VEHICLE_DETAILS_DEFAULT,
1950 STR_VEHICLE_DETAILS_DAYS,
1951 STR_VEHICLE_DETAILS_PERCENT,
1952 INVALID_STRING_ID,
1955 /** Class for managing the vehicle details window. */
1956 struct VehicleDetailsWindow : Window {
1957 TrainDetailsWindowTabs tab; ///< For train vehicles: which tab is displayed.
1958 Scrollbar *vscroll;
1960 /** Initialize a newly created vehicle details window */
1961 VehicleDetailsWindow (const WindowDesc *desc, WindowNumber window_number) :
1962 Window (desc), tab (TDW_TAB_CARGO), vscroll (NULL)
1964 const Vehicle *v = Vehicle::Get(window_number);
1966 this->CreateNestedTree();
1967 this->vscroll = (v->type == VEH_TRAIN ? this->GetScrollbar(WID_VD_SCROLLBAR) : NULL);
1968 this->FinishInitNested(window_number);
1970 this->GetWidget<NWidgetCore>(WID_VD_RENAME_VEHICLE)->tool_tip = STR_VEHICLE_DETAILS_TRAIN_RENAME + v->type;
1972 this->owner = v->owner;
1976 * Some data on this window has become invalid.
1977 * @param data Information about the changed data.
1978 * @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.
1980 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
1982 if (data == VIWD_AUTOREPLACE) {
1983 /* Autoreplace replaced the vehicle.
1984 * Nothing to do for this window. */
1985 return;
1987 if (!gui_scope) return;
1988 const Vehicle *v = Vehicle::Get(this->window_number);
1989 if (v->type == VEH_ROAD) {
1990 const NWidgetBase *nwid_info = this->GetWidget<NWidgetBase>(WID_VD_MIDDLE_DETAILS);
1991 uint aimed_height = this->GetRoadVehDetailsHeight(v);
1992 /* If the number of articulated parts changes, the size of the window must change too. */
1993 if (aimed_height != nwid_info->current_y) {
1994 this->ReInit();
2000 * Gets the desired height for the road vehicle details panel.
2001 * @param v Road vehicle being shown.
2002 * @return Desired height in pixels.
2004 uint GetRoadVehDetailsHeight(const Vehicle *v)
2006 uint desired_height;
2007 if (v->HasArticulatedPart()) {
2008 /* An articulated RV has its text drawn under the sprite instead of after it, hence 15 pixels extra. */
2009 desired_height = WD_FRAMERECT_TOP + ScaleGUITrad(15) + 3 * FONT_HEIGHT_NORMAL + 2 + WD_FRAMERECT_BOTTOM;
2010 /* Add space for the cargo amount for each part. */
2011 for (const Vehicle *u = v; u != NULL; u = u->Next()) {
2012 if (u->cargo_cap != 0) desired_height += FONT_HEIGHT_NORMAL + 1;
2014 } else {
2015 desired_height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + 3 + WD_FRAMERECT_BOTTOM;
2017 return desired_height;
2020 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
2022 switch (widget) {
2023 case WID_VD_TOP_DETAILS: {
2024 Dimension dim = { 0, 0 };
2025 size->height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
2027 for (uint i = 0; i < 4; i++) SetDParamMaxValue(i, INT16_MAX);
2028 static const StringID info_strings[] = {
2029 STR_VEHICLE_INFO_MAX_SPEED,
2030 STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED,
2031 STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE,
2032 STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR,
2033 STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS
2035 for (uint i = 0; i < lengthof(info_strings); i++) {
2036 dim = maxdim(dim, GetStringBoundingBox(info_strings[i]));
2038 SetDParam(0, STR_VEHICLE_INFO_AGE);
2039 dim = maxdim(dim, GetStringBoundingBox(STR_VEHICLE_INFO_AGE_RUNNING_COST_YR));
2040 size->width = dim.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
2041 break;
2044 case WID_VD_MIDDLE_DETAILS: {
2045 const Vehicle *v = Vehicle::Get(this->window_number);
2046 switch (v->type) {
2047 case VEH_ROAD:
2048 size->height = this->GetRoadVehDetailsHeight(v);
2049 break;
2051 case VEH_SHIP:
2052 size->height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + 3 + WD_FRAMERECT_BOTTOM;
2053 break;
2055 case VEH_AIRCRAFT:
2056 size->height = WD_FRAMERECT_TOP + 5 * FONT_HEIGHT_NORMAL + 4 + WD_FRAMERECT_BOTTOM;
2057 break;
2059 default:
2060 NOT_REACHED(); // Train uses WID_VD_MATRIX instead.
2062 break;
2065 case WID_VD_MATRIX:
2066 resize->height = max(ScaleGUITrad(14), WD_MATRIX_TOP + FONT_HEIGHT_NORMAL + WD_MATRIX_BOTTOM);
2067 size->height = 4 * resize->height;
2068 break;
2070 case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
2071 StringID *strs = _service_interval_dropdown;
2072 while (*strs != INVALID_STRING_ID) {
2073 *size = maxdim(*size, GetStringBoundingBox(*strs++));
2075 size->width += padding.width;
2076 size->height = FONT_HEIGHT_NORMAL + WD_DROPDOWNTEXT_TOP + WD_DROPDOWNTEXT_BOTTOM;
2077 break;
2080 case WID_VD_SERVICING_INTERVAL:
2081 SetDParamMaxValue(0, MAX_SERVINT_DAYS); // Roughly the maximum interval
2082 SetDParamMaxValue(1, MAX_YEAR * DAYS_IN_YEAR); // Roughly the maximum year
2083 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;
2084 size->height = WD_FRAMERECT_TOP + FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
2085 break;
2089 /** Checks whether service interval is enabled for the vehicle. */
2090 static bool IsVehicleServiceIntervalEnabled(const VehicleType vehicle_type, CompanyID company_id)
2092 const VehicleDefaultSettings *vds = &Company::Get(company_id)->settings.vehicle;
2093 switch (vehicle_type) {
2094 default: NOT_REACHED();
2095 case VEH_TRAIN: return vds->servint_trains != 0;
2096 case VEH_ROAD: return vds->servint_roadveh != 0;
2097 case VEH_SHIP: return vds->servint_ships != 0;
2098 case VEH_AIRCRAFT: return vds->servint_aircraft != 0;
2103 * Draw the details for the given vehicle at the position of the Details windows
2105 * @param v current vehicle
2106 * @param left The left most coordinate to draw
2107 * @param right The right most coordinate to draw
2108 * @param y The y coordinate
2109 * @param vscroll_pos Position of scrollbar (train only)
2110 * @param vscroll_cap Number of lines currently displayed (train only)
2111 * @param det_tab Selected details tab (train only)
2113 static void DrawVehicleDetails(const Vehicle *v, int left, int right, int y, int vscroll_pos, uint vscroll_cap, TrainDetailsWindowTabs det_tab)
2115 switch (v->type) {
2116 case VEH_TRAIN: DrawTrainDetails(Train::From(v), left, right, y, vscroll_pos, vscroll_cap, det_tab); break;
2117 case VEH_ROAD: DrawRoadVehDetails(v, left, right, y); break;
2118 case VEH_SHIP: DrawShipDetails(v, left, right, y); break;
2119 case VEH_AIRCRAFT: DrawAircraftDetails(Aircraft::From(v), left, right, y); break;
2120 default: NOT_REACHED();
2124 virtual void SetStringParameters(int widget) const
2126 if (widget == WID_VD_CAPTION) SetDParam(0, Vehicle::Get(this->window_number)->index);
2129 virtual void DrawWidget(const Rect &r, int widget) const
2131 const Vehicle *v = Vehicle::Get(this->window_number);
2133 switch (widget) {
2134 case WID_VD_TOP_DETAILS: {
2135 int y = r.top + WD_FRAMERECT_TOP;
2137 /* Draw running cost */
2138 SetDParam(1, v->age / DAYS_IN_LEAP_YEAR);
2139 SetDParam(0, (v->age + DAYS_IN_YEAR < v->max_age) ? STR_VEHICLE_INFO_AGE : STR_VEHICLE_INFO_AGE_RED);
2140 SetDParam(2, v->max_age / DAYS_IN_LEAP_YEAR);
2141 SetDParam(3, v->GetDisplayRunningCost());
2142 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_AGE_RUNNING_COST_YR);
2143 y += FONT_HEIGHT_NORMAL;
2145 /* Draw max speed */
2146 StringID string;
2147 if (v->type == VEH_TRAIN ||
2148 (v->type == VEH_ROAD && _settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL)) {
2149 const GroundVehicleCache *gcache = v->GetGroundVehicleCache();
2150 SetDParam(2, v->GetDisplayMaxSpeed());
2151 SetDParam(1, gcache->cached_power);
2152 SetDParam(0, gcache->cached_weight);
2153 SetDParam(3, gcache->cached_max_te / 1000);
2154 if (v->type == VEH_TRAIN && (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ||
2155 GetRailTypeInfo(Train::From(v)->railtype)->acceleration_type == 2)) {
2156 string = STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED;
2157 } else {
2158 string = STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE;
2160 } else {
2161 SetDParam(0, v->GetDisplayMaxSpeed());
2162 if (v->type == VEH_AIRCRAFT && Aircraft::From(v)->GetRange() > 0) {
2163 SetDParam(1, Aircraft::From(v)->GetRange());
2164 string = STR_VEHICLE_INFO_MAX_SPEED_RANGE;
2165 } else {
2166 string = STR_VEHICLE_INFO_MAX_SPEED;
2169 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, string);
2170 y += FONT_HEIGHT_NORMAL;
2172 /* Draw profit */
2173 SetDParam(0, v->GetDisplayProfitThisYear());
2174 SetDParam(1, v->GetDisplayProfitLastYear());
2175 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR);
2176 y += FONT_HEIGHT_NORMAL;
2178 /* Draw breakdown & reliability */
2179 SetDParam(0, ToPercent16(v->reliability));
2180 SetDParam(1, v->breakdowns_since_last_service);
2181 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS);
2182 break;
2185 case WID_VD_MATRIX:
2186 /* For trains only. */
2187 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);
2188 break;
2190 case WID_VD_MIDDLE_DETAILS: {
2191 /* For other vehicles, at the place of the matrix. */
2192 bool rtl = _current_text_dir == TD_RTL;
2193 uint sprite_width = UnScaleGUI(
2194 max<uint>(GetSprite(v->GetImage(rtl ? DIR_E : DIR_W, EIT_IN_DETAILS), ST_NORMAL)->width, 70U)) +
2195 WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
2197 uint text_left = r.left + (rtl ? 0 : sprite_width);
2198 uint text_right = r.right - (rtl ? sprite_width : 0);
2200 /* Articulated road vehicles use a complete line. */
2201 if (v->type == VEH_ROAD && v->HasArticulatedPart()) {
2202 DrawVehicleImage(v, r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, 0);
2203 } else {
2204 uint sprite_left = rtl ? text_right : r.left;
2205 uint sprite_right = rtl ? r.right : text_left;
2207 DrawVehicleImage(v, sprite_left + WD_FRAMERECT_LEFT, sprite_right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, 0);
2209 DrawVehicleDetails(v, text_left + WD_FRAMERECT_LEFT, text_right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, 0, 0, this->tab);
2210 break;
2213 case WID_VD_SERVICING_INTERVAL:
2214 /* Draw service interval text */
2215 SetDParam(0, v->GetServiceInterval());
2216 SetDParam(1, v->date_of_last_service);
2217 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + (r.bottom - r.top + 1 - FONT_HEIGHT_NORMAL) / 2,
2218 v->ServiceIntervalIsPercent() ? STR_VEHICLE_DETAILS_SERVICING_INTERVAL_PERCENT : STR_VEHICLE_DETAILS_SERVICING_INTERVAL_DAYS);
2219 break;
2223 /** Repaint vehicle details window. */
2224 virtual void OnPaint()
2226 const Vehicle *v = Vehicle::Get(this->window_number);
2228 this->SetWidgetDisabledState(WID_VD_RENAME_VEHICLE, v->owner != _local_company);
2230 if (v->type == VEH_TRAIN) {
2231 this->DisableWidget(this->tab + WID_VD_DETAILS_CARGO_CARRIED);
2232 this->vscroll->SetCount(GetTrainDetailsWndVScroll(v->index, this->tab));
2235 /* Disable service-scroller when interval is set to disabled */
2236 this->SetWidgetsDisabledState(!IsVehicleServiceIntervalEnabled(v->type, v->owner),
2237 WID_VD_INCREASE_SERVICING_INTERVAL,
2238 WID_VD_DECREASE_SERVICING_INTERVAL,
2239 WIDGET_LIST_END);
2241 StringID str = v->ServiceIntervalIsCustom() ?
2242 (v->ServiceIntervalIsPercent() ? STR_VEHICLE_DETAILS_PERCENT : STR_VEHICLE_DETAILS_DAYS) :
2243 STR_VEHICLE_DETAILS_DEFAULT;
2244 this->GetWidget<NWidgetCore>(WID_VD_SERVICE_INTERVAL_DROPDOWN)->widget_data = str;
2246 this->DrawWidgets();
2249 virtual void OnClick(Point pt, int widget, int click_count)
2251 switch (widget) {
2252 case WID_VD_RENAME_VEHICLE: { // rename
2253 const Vehicle *v = Vehicle::Get(this->window_number);
2254 SetDParam(0, v->index);
2255 ShowQueryString(STR_VEHICLE_NAME, STR_QUERY_RENAME_TRAIN_CAPTION + v->type,
2256 MAX_LENGTH_VEHICLE_NAME_CHARS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
2257 break;
2260 case WID_VD_INCREASE_SERVICING_INTERVAL: // increase int
2261 case WID_VD_DECREASE_SERVICING_INTERVAL: { // decrease int
2262 int mod = _ctrl_pressed ? 5 : 10;
2263 const Vehicle *v = Vehicle::Get(this->window_number);
2265 mod = (widget == WID_VD_DECREASE_SERVICING_INTERVAL) ? -mod : mod;
2266 mod = GetServiceIntervalClamped(mod + v->GetServiceInterval(), v->ServiceIntervalIsPercent());
2267 if (mod == v->GetServiceInterval()) return;
2269 DoCommandP(v->tile, v->index, mod | (1 << 16) | (v->ServiceIntervalIsPercent() << 17), CMD_CHANGE_SERVICE_INT);
2270 break;
2273 case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
2274 const Vehicle *v = Vehicle::Get(this->window_number);
2275 ShowDropDownMenu(this, _service_interval_dropdown, v->ServiceIntervalIsCustom() ? (v->ServiceIntervalIsPercent() ? 2 : 1) : 0, widget, 0, 0);
2276 break;
2279 case WID_VD_DETAILS_CARGO_CARRIED:
2280 case WID_VD_DETAILS_TRAIN_VEHICLES:
2281 case WID_VD_DETAILS_CAPACITY_OF_EACH:
2282 case WID_VD_DETAILS_TOTAL_CARGO:
2283 this->SetWidgetsDisabledState(false,
2284 WID_VD_DETAILS_CARGO_CARRIED,
2285 WID_VD_DETAILS_TRAIN_VEHICLES,
2286 WID_VD_DETAILS_CAPACITY_OF_EACH,
2287 WID_VD_DETAILS_TOTAL_CARGO,
2288 widget,
2289 WIDGET_LIST_END);
2291 this->tab = (TrainDetailsWindowTabs)(widget - WID_VD_DETAILS_CARGO_CARRIED);
2292 this->SetDirty();
2293 break;
2297 virtual void OnDropdownSelect(int widget, int index)
2299 switch (widget) {
2300 case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
2301 const Vehicle *v = Vehicle::Get(this->window_number);
2302 bool iscustom = index != 0;
2303 bool ispercent = iscustom ? (index == 2) : Company::Get(v->owner)->settings.vehicle.servint_ispercent;
2304 uint16 interval = GetServiceIntervalClamped(v->GetServiceInterval(), ispercent);
2305 DoCommandP(v->tile, v->index, interval | (iscustom << 16) | (ispercent << 17), CMD_CHANGE_SERVICE_INT);
2306 break;
2311 virtual void OnQueryTextFinished(char *str)
2313 if (str == NULL) return;
2315 DoCommandP(0, this->window_number, 0, CMD_RENAME_VEHICLE, str);
2318 virtual void OnResize()
2320 NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_VD_MATRIX);
2321 if (nwi != NULL) {
2322 this->vscroll->SetCapacityFromWidget(this, WID_VD_MATRIX);
2327 /** Vehicle details window preferences. */
2328 static WindowDesc::Prefs _train_vehicle_details_prefs ("view_vehicle_details_train");
2330 /** Vehicle details window descriptor. */
2331 static const WindowDesc _train_vehicle_details_desc(
2332 WDP_AUTO, 405, 178,
2333 WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
2335 _nested_train_vehicle_details_widgets, lengthof(_nested_train_vehicle_details_widgets),
2336 &_train_vehicle_details_prefs
2339 /** Vehicle details window preferences for other vehicles than a train. */
2340 static WindowDesc::Prefs _nontrain_vehicle_details_prefs ("view_vehicle_details");
2342 /** Vehicle details window descriptor for other vehicles than a train. */
2343 static const WindowDesc _nontrain_vehicle_details_desc(
2344 WDP_AUTO, 405, 113,
2345 WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
2347 _nested_nontrain_vehicle_details_widgets, lengthof(_nested_nontrain_vehicle_details_widgets),
2348 &_nontrain_vehicle_details_prefs
2351 /** Shows the vehicle details window of the given vehicle. */
2352 static void ShowVehicleDetailsWindow(const Vehicle *v)
2354 DeleteWindowById(WC_VEHICLE_ORDERS, v->index, false);
2355 DeleteWindowById(WC_VEHICLE_TIMETABLE, v->index, false);
2356 AllocateWindowDescFront<VehicleDetailsWindow>((v->type == VEH_TRAIN) ? &_train_vehicle_details_desc : &_nontrain_vehicle_details_desc, v->index);
2360 /* Unified vehicle GUI - Vehicle View Window */
2362 /** Vehicle view widgets. */
2363 static const NWidgetPart _nested_vehicle_view_widgets[] = {
2364 NWidget(NWID_HORIZONTAL),
2365 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
2366 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VV_CAPTION), SetDataTip(STR_VEHICLE_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2367 NWidget(WWT_DEBUGBOX, COLOUR_GREY),
2368 NWidget(WWT_SHADEBOX, COLOUR_GREY),
2369 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
2370 NWidget(WWT_STICKYBOX, COLOUR_GREY),
2371 EndContainer(),
2372 NWidget(NWID_HORIZONTAL),
2373 NWidget(WWT_PANEL, COLOUR_GREY),
2374 NWidget(WWT_INSET, COLOUR_GREY), SetPadding(2, 2, 2, 2),
2375 NWidget(NWID_VIEWPORT, INVALID_COLOUR, WID_VV_VIEWPORT), SetMinimalSize(226, 84), SetResize(1, 1), SetPadding(1, 1, 1, 1),
2376 EndContainer(),
2377 EndContainer(),
2378 NWidget(NWID_VERTICAL),
2379 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_CENTER_MAIN_VIEW), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(SPR_CENTRE_VIEW_VEHICLE, 0x0 /* filled later */),
2380 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VV_SELECT_DEPOT_CLONE),
2381 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_GOTO_DEPOT), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
2382 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_CLONE), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
2383 EndContainer(),
2384 /* For trains only, 'ignore signal' button. */
2385 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_FORCE_PROCEED), SetMinimalSize(18, 18), SetFill(1, 1),
2386 SetDataTip(SPR_IGNORE_SIGNALS, STR_VEHICLE_VIEW_TRAIN_IGNORE_SIGNAL_TOOLTIP),
2387 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VV_SELECT_REFIT_TURN),
2388 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_REFIT), SetMinimalSize(18, 18), SetFill(1, 1), SetDataTip(SPR_REFIT_VEHICLE, 0x0 /* filled later */),
2389 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_TURN_AROUND), SetMinimalSize(18, 18), SetFill(1, 1),
2390 SetDataTip(SPR_FORCE_VEHICLE_TURN, STR_VEHICLE_VIEW_ROAD_VEHICLE_REVERSE_TOOLTIP),
2391 EndContainer(),
2392 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_SHOW_ORDERS), SetFill(1, 1), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_ORDERS, 0x0 /* filled later */),
2393 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_SHOW_DETAILS), SetFill(1, 1), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_VEHICLE_DETAILS, 0x0 /* filled later */),
2394 NWidget(WWT_PANEL, COLOUR_GREY), SetFill(1, 1), SetMinimalSize(18, 0), SetResize(0, 1), EndContainer(),
2395 EndContainer(),
2396 EndContainer(),
2397 NWidget(NWID_HORIZONTAL),
2398 NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_VV_START_STOP), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetResize(1, 0), SetFill(1, 0),
2399 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
2400 EndContainer(),
2403 /** Vehicle view window preferences for all vehicles but trains. */
2404 static WindowDesc::Prefs _vehicle_view_prefs ("view_vehicle");
2406 /** Vehicle view window descriptor for all vehicles but trains. */
2407 static const WindowDesc _vehicle_view_desc(
2408 WDP_AUTO, 250, 116,
2409 WC_VEHICLE_VIEW, WC_NONE,
2411 _nested_vehicle_view_widgets, lengthof(_nested_vehicle_view_widgets),
2412 &_vehicle_view_prefs
2415 /** Vehicle view window preferences for trains. */
2416 static WindowDesc::Prefs _train_view_prefs ("view_vehicle_train");
2419 * Vehicle view window descriptor for trains. Only minimum_height and
2420 * default_height are different for train view.
2422 static const WindowDesc _train_view_desc(
2423 WDP_AUTO, 250, 134,
2424 WC_VEHICLE_VIEW, WC_NONE,
2426 _nested_vehicle_view_widgets, lengthof(_nested_vehicle_view_widgets),
2427 &_train_view_prefs
2431 /* Just to make sure, nobody has changed the vehicle type constants, as we are
2432 using them for array indexing in a number of places here. */
2433 assert_compile(VEH_TRAIN == 0);
2434 assert_compile(VEH_ROAD == 1);
2435 assert_compile(VEH_SHIP == 2);
2436 assert_compile(VEH_AIRCRAFT == 3);
2438 /** Zoom levels for vehicle views indexed by vehicle type. */
2439 static const ZoomLevel _vehicle_view_zoom_levels[] = {
2440 ZOOM_LVL_TRAIN,
2441 ZOOM_LVL_ROADVEH,
2442 ZOOM_LVL_SHIP,
2443 ZOOM_LVL_AIRCRAFT,
2446 /* Constants for geometry of vehicle view viewport */
2447 static const int VV_INITIAL_VIEWPORT_WIDTH = 226;
2448 static const int VV_INITIAL_VIEWPORT_HEIGHT = 84;
2449 static const int VV_INITIAL_VIEWPORT_HEIGHT_TRAIN = 102;
2451 /** Error strings when starting/stopping a vehicle indexed by vehicle type. */
2452 static const StringID _vehicle_string_startstop_table[4] = {
2453 STR_ERROR_CAN_T_STOP_START_TRAIN,
2454 STR_ERROR_CAN_T_STOP_START_ROAD_VEHICLE,
2455 STR_ERROR_CAN_T_STOP_START_SHIP,
2456 STR_ERROR_CAN_T_STOP_START_AIRCRAFT,
2460 * This is the Callback method after the cloning attempt of a vehicle
2461 * @param result the result of the cloning command
2462 * @param tile unused
2463 * @param p1 vehicle ID
2464 * @param p2 unused
2466 void CcStartStopVehicle(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
2468 if (result.Failed()) return;
2470 if (p2 == 0) return;
2472 const Vehicle *v = Vehicle::GetIfValid(p1);
2473 if (v == NULL || !v->IsPrimaryVehicle() || v->owner != _local_company) return;
2475 StringID msg = (v->vehstatus & VS_STOPPED) ? STR_VEHICLE_COMMAND_STOPPED : STR_VEHICLE_COMMAND_STARTED;
2476 Point pt = RemapCoords(v->x_pos, v->y_pos, v->z_pos);
2477 AddTextEffect(msg, pt.x, pt.y, DAY_TICKS, TE_RISING);
2481 * Executes #CMD_START_STOP_VEHICLE for given vehicle.
2482 * @param v Vehicle to start/stop
2483 * @param texteffect Should a texteffect be shown?
2485 void StartStopVehicle(const Vehicle *v, bool texteffect)
2487 assert(v->IsPrimaryVehicle());
2488 DoCommandP(v->tile, v->index, texteffect ? 1 : 0, CMD_START_STOP_VEHICLE);
2491 /** Checks whether the vehicle may be refitted at the moment.*/
2492 static bool IsVehicleRefitable(const Vehicle *v)
2494 if (!v->IsStoppedInDepot()) return false;
2496 do {
2497 if (IsEngineRefittable(v->engine_type)) return true;
2498 } while (v->IsGroundVehicle() && (v = v->Next()) != NULL);
2500 return false;
2503 /** Window manager class for viewing a vehicle. */
2504 struct VehicleViewWindow : Window {
2505 private:
2506 /** Display planes available in the vehicle view window. */
2507 enum PlaneSelections {
2508 SEL_DC_GOTO_DEPOT, ///< Display 'goto depot' button in #WID_VV_SELECT_DEPOT_CLONE stacked widget.
2509 SEL_DC_CLONE, ///< Display 'clone vehicle' button in #WID_VV_SELECT_DEPOT_CLONE stacked widget.
2511 SEL_RT_REFIT, ///< Display 'refit' button in #WID_VV_SELECT_REFIT_TURN stacked widget.
2512 SEL_RT_TURN_AROUND, ///< Display 'turn around' button in #WID_VV_SELECT_REFIT_TURN stacked widget.
2514 SEL_DC_BASEPLANE = SEL_DC_GOTO_DEPOT, ///< First plane of the #WID_VV_SELECT_DEPOT_CLONE stacked widget.
2515 SEL_RT_BASEPLANE = SEL_RT_REFIT, ///< First plane of the #WID_VV_SELECT_REFIT_TURN stacked widget.
2519 * Display a plane in the window.
2520 * @param plane Plane to show.
2522 void SelectPlane(PlaneSelections plane)
2524 switch (plane) {
2525 case SEL_DC_GOTO_DEPOT:
2526 case SEL_DC_CLONE:
2527 this->GetWidget<NWidgetStacked>(WID_VV_SELECT_DEPOT_CLONE)->SetDisplayedPlane(plane - SEL_DC_BASEPLANE);
2528 break;
2530 case SEL_RT_REFIT:
2531 case SEL_RT_TURN_AROUND:
2532 this->GetWidget<NWidgetStacked>(WID_VV_SELECT_REFIT_TURN)->SetDisplayedPlane(plane - SEL_RT_BASEPLANE);
2533 break;
2535 default:
2536 NOT_REACHED();
2540 public:
2541 VehicleViewWindow (const WindowDesc *desc, WindowNumber window_number) : Window(desc)
2543 this->CreateNestedTree();
2545 /* Sprites for the 'send to depot' button indexed by vehicle type. */
2546 static const SpriteID vehicle_view_goto_depot_sprites[] = {
2547 SPR_SEND_TRAIN_TODEPOT,
2548 SPR_SEND_ROADVEH_TODEPOT,
2549 SPR_SEND_SHIP_TODEPOT,
2550 SPR_SEND_AIRCRAFT_TODEPOT,
2552 const Vehicle *v = Vehicle::Get(window_number);
2553 this->GetWidget<NWidgetCore>(WID_VV_GOTO_DEPOT)->widget_data = vehicle_view_goto_depot_sprites[v->type];
2555 /* Sprites for the 'clone vehicle' button indexed by vehicle type. */
2556 static const SpriteID vehicle_view_clone_sprites[] = {
2557 SPR_CLONE_TRAIN,
2558 SPR_CLONE_ROADVEH,
2559 SPR_CLONE_SHIP,
2560 SPR_CLONE_AIRCRAFT,
2562 this->GetWidget<NWidgetCore>(WID_VV_CLONE)->widget_data = vehicle_view_clone_sprites[v->type];
2564 switch (v->type) {
2565 case VEH_TRAIN:
2566 this->GetWidget<NWidgetCore>(WID_VV_TURN_AROUND)->tool_tip = STR_VEHICLE_VIEW_TRAIN_REVERSE_TOOLTIP;
2567 break;
2569 case VEH_ROAD:
2570 break;
2572 case VEH_SHIP:
2573 case VEH_AIRCRAFT:
2574 this->SelectPlane(SEL_RT_REFIT);
2575 break;
2577 default: NOT_REACHED();
2579 this->FinishInitNested(window_number);
2580 this->owner = v->owner;
2581 this->GetWidget<NWidgetViewport>(WID_VV_VIEWPORT)->InitializeViewport(this, this->window_number | (1 << 31), _vehicle_view_zoom_levels[v->type]);
2583 this->GetWidget<NWidgetCore>(WID_VV_START_STOP)->tool_tip = STR_VEHICLE_VIEW_TRAIN_STATE_START_STOP_TOOLTIP + v->type;
2584 this->GetWidget<NWidgetCore>(WID_VV_CENTER_MAIN_VIEW)->tool_tip = STR_VEHICLE_VIEW_TRAIN_LOCATION_TOOLTIP + v->type;
2585 this->GetWidget<NWidgetCore>(WID_VV_REFIT)->tool_tip = STR_VEHICLE_VIEW_TRAIN_REFIT_TOOLTIP + v->type;
2586 this->GetWidget<NWidgetCore>(WID_VV_GOTO_DEPOT)->tool_tip = STR_VEHICLE_VIEW_TRAIN_SEND_TO_DEPOT_TOOLTIP + v->type;
2587 this->GetWidget<NWidgetCore>(WID_VV_SHOW_ORDERS)->tool_tip = STR_VEHICLE_VIEW_TRAIN_ORDERS_TOOLTIP + v->type;
2588 this->GetWidget<NWidgetCore>(WID_VV_SHOW_DETAILS)->tool_tip = STR_VEHICLE_VIEW_TRAIN_SHOW_DETAILS_TOOLTIP + v->type;
2589 this->GetWidget<NWidgetCore>(WID_VV_CLONE)->tool_tip = STR_VEHICLE_VIEW_CLONE_TRAIN_INFO + v->type;
2592 void OnDelete (void) FINAL_OVERRIDE
2594 DeleteWindowById(WC_VEHICLE_ORDERS, this->window_number, false);
2595 DeleteWindowById(WC_VEHICLE_REFIT, this->window_number, false);
2596 DeleteWindowById(WC_VEHICLE_DETAILS, this->window_number, false);
2597 DeleteWindowById(WC_VEHICLE_TIMETABLE, this->window_number, false);
2600 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
2602 const Vehicle *v = Vehicle::Get(this->window_number);
2603 switch (widget) {
2604 case WID_VV_START_STOP:
2605 size->height = max(size->height, max(GetSpriteSize(SPR_FLAG_VEH_STOPPED).height, GetSpriteSize(SPR_FLAG_VEH_RUNNING).height) + WD_IMGBTN_TOP + WD_IMGBTN_BOTTOM);
2606 break;
2608 case WID_VV_FORCE_PROCEED:
2609 if (v->type != VEH_TRAIN) {
2610 size->height = 0;
2611 size->width = 0;
2613 break;
2615 case WID_VV_VIEWPORT:
2616 size->width = VV_INITIAL_VIEWPORT_WIDTH;
2617 size->height = (v->type == VEH_TRAIN) ? VV_INITIAL_VIEWPORT_HEIGHT_TRAIN : VV_INITIAL_VIEWPORT_HEIGHT;
2618 break;
2622 virtual void OnPaint()
2624 const Vehicle *v = Vehicle::Get(this->window_number);
2625 bool is_localcompany = v->owner == _local_company;
2626 bool refitable_and_stopped_in_depot = IsVehicleRefitable(v);
2628 this->SetWidgetDisabledState(WID_VV_GOTO_DEPOT, !is_localcompany);
2629 this->SetWidgetDisabledState(WID_VV_REFIT, !refitable_and_stopped_in_depot || !is_localcompany);
2630 this->SetWidgetDisabledState(WID_VV_CLONE, !is_localcompany);
2632 if (v->type == VEH_TRAIN) {
2633 this->SetWidgetLoweredState(WID_VV_FORCE_PROCEED, Train::From(v)->force_proceed == TFP_SIGNAL);
2634 this->SetWidgetDisabledState(WID_VV_FORCE_PROCEED, !is_localcompany);
2635 this->SetWidgetDisabledState(WID_VV_TURN_AROUND, !is_localcompany);
2638 this->DrawWidgets();
2641 virtual void SetStringParameters(int widget) const
2643 if (widget != WID_VV_CAPTION) return;
2645 const Vehicle *v = Vehicle::Get(this->window_number);
2646 SetDParam(0, v->index);
2649 virtual void DrawWidget(const Rect &r, int widget) const
2651 if (widget != WID_VV_START_STOP) return;
2653 const Vehicle *v = Vehicle::Get(this->window_number);
2654 StringID str;
2655 if (v->vehstatus & VS_CRASHED) {
2656 str = STR_VEHICLE_STATUS_CRASHED;
2657 } else if (v->type != VEH_AIRCRAFT && v->breakdown_ctr == 1) { // check for aircraft necessary?
2658 str = STR_VEHICLE_STATUS_BROKEN_DOWN;
2659 } else if (v->vehstatus & VS_STOPPED) {
2660 if (v->type == VEH_TRAIN) {
2661 if (v->cur_speed == 0) {
2662 if (Train::From(v)->gcache.cached_power == 0) {
2663 str = STR_VEHICLE_STATUS_TRAIN_NO_POWER;
2664 } else {
2665 str = STR_VEHICLE_STATUS_STOPPED;
2667 } else {
2668 SetDParam(0, v->GetDisplaySpeed());
2669 str = STR_VEHICLE_STATUS_TRAIN_STOPPING_VEL;
2671 } else { // no train
2672 str = STR_VEHICLE_STATUS_STOPPED;
2674 } else if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_TRAIN_STUCK) && !v->current_order.IsType(OT_LOADING)) {
2675 str = STR_VEHICLE_STATUS_TRAIN_STUCK;
2676 } else if (v->type == VEH_AIRCRAFT && HasBit(Aircraft::From(v)->flags, VAF_DEST_TOO_FAR) && !v->current_order.IsType(OT_LOADING)) {
2677 str = STR_VEHICLE_STATUS_AIRCRAFT_TOO_FAR;
2678 } else { // vehicle is in a "normal" state, show current order
2679 switch (v->current_order.GetType()) {
2680 case OT_GOTO_STATION: {
2681 SetDParam(0, v->current_order.GetDestination());
2682 SetDParam(1, v->GetDisplaySpeed());
2683 str = STR_VEHICLE_STATUS_HEADING_FOR_STATION_VEL;
2684 break;
2687 case OT_GOTO_DEPOT: {
2688 SetDParam(0, v->type);
2689 SetDParam(1, v->current_order.GetDestination());
2690 SetDParam(2, v->GetDisplaySpeed());
2691 if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
2692 /* This case *only* happens when multiple nearest depot orders
2693 * follow each other (including an order list only one order: a
2694 * nearest depot order) and there are no reachable depots.
2695 * It is primarily to guard for the case that there is no
2696 * depot with index 0, which would be used as fallback for
2697 * evaluating the string in the status bar. */
2698 str = STR_EMPTY;
2699 } else if (v->current_order.GetDepotActionType() & ODATFB_HALT) {
2700 str = STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_VEL;
2701 } else {
2702 str = STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_SERVICE_VEL;
2704 break;
2707 case OT_LOADING:
2708 str = STR_VEHICLE_STATUS_LOADING_UNLOADING;
2709 break;
2711 case OT_GOTO_WAYPOINT: {
2712 assert(v->type == VEH_TRAIN || v->type == VEH_SHIP);
2713 SetDParam(0, v->current_order.GetDestination());
2714 str = STR_VEHICLE_STATUS_HEADING_FOR_WAYPOINT_VEL;
2715 SetDParam(1, v->GetDisplaySpeed());
2716 break;
2719 case OT_LEAVESTATION:
2720 if (v->type != VEH_AIRCRAFT) {
2721 str = STR_VEHICLE_STATUS_LEAVING;
2722 break;
2724 /* FALL THROUGH, if aircraft. Does this even happen? */
2726 default:
2727 if (v->GetNumManualOrders() == 0) {
2728 str = STR_VEHICLE_STATUS_NO_ORDERS_VEL;
2729 SetDParam(0, v->GetDisplaySpeed());
2730 } else {
2731 str = STR_EMPTY;
2733 break;
2737 /* Draw the flag plus orders. */
2738 bool rtl = (_current_text_dir == TD_RTL);
2739 uint text_offset = max(GetSpriteSize(SPR_FLAG_VEH_STOPPED).width, GetSpriteSize(SPR_FLAG_VEH_RUNNING).width) + WD_IMGBTN_LEFT + WD_IMGBTN_RIGHT;
2740 int text_left = r.left + (rtl ? (uint)WD_FRAMERECT_LEFT : text_offset);
2741 int text_right = r.right - (rtl ? text_offset : (uint)WD_FRAMERECT_RIGHT);
2742 int image_left = (rtl ? text_right + 1 : r.left) + WD_IMGBTN_LEFT;
2743 int image = ((v->vehstatus & VS_STOPPED) != 0) ? SPR_FLAG_VEH_STOPPED : SPR_FLAG_VEH_RUNNING;
2744 int lowered = this->IsWidgetLowered(WID_VV_START_STOP) ? 1 : 0;
2745 DrawSprite(image, PAL_NONE, image_left + lowered, r.top + WD_IMGBTN_TOP + lowered);
2746 DrawString(text_left + lowered, text_right + lowered, r.top + WD_FRAMERECT_TOP + lowered, str, TC_FROMSTRING, SA_HOR_CENTER);
2749 virtual void OnClick(Point pt, int widget, int click_count)
2751 const Vehicle *v = Vehicle::Get(this->window_number);
2753 switch (widget) {
2754 case WID_VV_START_STOP: // start stop
2755 if (_ctrl_pressed) {
2756 /* Scroll to current order destination */
2757 TileIndex tile = v->current_order.GetLocation(v);
2758 if (tile != INVALID_TILE) ScrollMainWindowToTile(tile);
2759 } else {
2760 /* Start/Stop */
2761 StartStopVehicle(v, false);
2763 break;
2764 case WID_VV_CENTER_MAIN_VIEW: {// center main view
2765 const Window *mainwindow = FindWindowById(WC_MAIN_WINDOW, 0);
2766 /* code to allow the main window to 'follow' the vehicle if the ctrl key is pressed */
2767 if (_ctrl_pressed && mainwindow->viewport->zoom <= ZOOM_LVL_OUT_4X) {
2768 mainwindow->viewport->follow_vehicle = v->index;
2769 } else {
2770 ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos);
2772 break;
2775 case WID_VV_GOTO_DEPOT: // goto hangar
2776 DoCommandP(v->tile, v->index | (_ctrl_pressed ? DEPOT_SERVICE : 0U), 0, CMD_SEND_VEHICLE_TO_DEPOT);
2777 break;
2778 case WID_VV_REFIT: // refit
2779 ShowVehicleRefitWindow (this, v);
2780 break;
2781 case WID_VV_SHOW_ORDERS: // show orders
2782 if (_ctrl_pressed) {
2783 ShowTimetableWindow(v);
2784 } else {
2785 ShowOrdersWindow(v);
2787 break;
2788 case WID_VV_SHOW_DETAILS: // show details
2789 ShowVehicleDetailsWindow(v);
2790 break;
2791 case WID_VV_CLONE: // clone vehicle
2792 /* Suppress the vehicle GUI when share-cloning.
2793 * There is no point to it except for starting the vehicle.
2794 * For starting the vehicle the player has to open the depot GUI, which is
2795 * most likely already open, but is also visible in the vehicle viewport. */
2796 DoCommandP(v->tile, v->index, _ctrl_pressed ? (1 | (1 << 31)) : 0, CMD_CLONE_VEHICLE);
2797 break;
2798 case WID_VV_TURN_AROUND: // turn around
2799 assert(v->IsGroundVehicle());
2800 if (v->type == VEH_TRAIN) {
2801 DoCommandP(v->tile, v->index, 0, CMD_REVERSE_TRAIN_DIRECTION);
2802 } else {
2803 DoCommandP(v->tile, v->index, 0, CMD_TURN_ROADVEH);
2805 break;
2806 case WID_VV_FORCE_PROCEED: // force proceed
2807 assert(v->type == VEH_TRAIN);
2808 DoCommandP(v->tile, v->index, 0, CMD_FORCE_TRAIN_PROCEED);
2809 break;
2813 virtual void OnResize()
2815 if (this->viewport != NULL) {
2816 NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_VV_VIEWPORT);
2817 nvp->UpdateViewportCoordinates(this);
2821 virtual void OnTick()
2823 const Vehicle *v = Vehicle::Get(this->window_number);
2824 bool veh_stopped = v->IsStoppedInDepot();
2826 /* Widget WID_VV_GOTO_DEPOT must be hidden if the vehicle is already stopped in depot.
2827 * Widget WID_VV_CLONE_VEH should then be shown, since cloning is allowed only while in depot and stopped.
2829 PlaneSelections plane = veh_stopped ? SEL_DC_CLONE : SEL_DC_GOTO_DEPOT;
2830 NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VV_SELECT_DEPOT_CLONE); // Selection widget 'send to depot' / 'clone'.
2831 if (nwi->shown_plane + SEL_DC_BASEPLANE != plane) {
2832 this->SelectPlane(plane);
2833 this->SetWidgetDirty(WID_VV_SELECT_DEPOT_CLONE);
2835 /* The same system applies to widget WID_VV_REFIT_VEH and VVW_WIDGET_TURN_AROUND.*/
2836 if (v->IsGroundVehicle()) {
2837 PlaneSelections plane = veh_stopped ? SEL_RT_REFIT : SEL_RT_TURN_AROUND;
2838 NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VV_SELECT_REFIT_TURN);
2839 if (nwi->shown_plane + SEL_RT_BASEPLANE != plane) {
2840 this->SelectPlane(plane);
2841 this->SetWidgetDirty(WID_VV_SELECT_REFIT_TURN);
2847 * Some data on this window has become invalid.
2848 * @param data Information about the changed data.
2849 * @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.
2851 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
2853 if (data == VIWD_AUTOREPLACE) {
2854 /* Autoreplace replaced the vehicle.
2855 * Nothing to do for this window. */
2856 return;
2860 virtual bool IsNewGRFInspectable() const
2862 return ::IsNewGRFInspectable(GetGrfSpecFeature(Vehicle::Get(this->window_number)->type), this->window_number);
2865 virtual void ShowNewGRFInspectWindow() const
2867 ::ShowNewGRFInspectWindow(GetGrfSpecFeature(Vehicle::Get(this->window_number)->type), this->window_number);
2872 /** Shows the vehicle view window of the given vehicle. */
2873 void ShowVehicleViewWindow(const Vehicle *v)
2875 AllocateWindowDescFront<VehicleViewWindow>((v->type == VEH_TRAIN) ? &_train_view_desc : &_vehicle_view_desc, v->index);
2879 * Dispatch a "vehicle selected" event if any window waits for it.
2880 * @param v selected vehicle;
2881 * @return did any window accept vehicle selection?
2883 bool VehicleClicked(const Vehicle *v)
2885 assert(v != NULL);
2886 if (_pointer_mode < POINTER_VEHICLE) return false;
2888 v = v->First();
2889 if (!v->IsPrimaryVehicle()) return false;
2891 return _thd.GetCallbackWnd()->OnVehicleSelect(v);
2894 void StopGlobalFollowVehicle(const Vehicle *v)
2896 Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
2897 if (w != NULL && w->viewport->follow_vehicle == v->index) {
2898 ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos, true); // lock the main view on the vehicle's last position
2899 w->viewport->follow_vehicle = INVALID_VEHICLE;
2905 * Callback for building a vehicle
2906 * @param result The result of the command.
2907 * @param tile The tile the command was executed on.
2908 * @param p1 Additional data for the command (for the #CommandProc)
2909 * @param p2 Additional data for the command (for the #CommandProc)
2911 void CcBuildVehicle(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
2913 if (result.Failed()) return;
2915 if (!IsRailDepotTile(tile) || RailVehInfo(p1)->railveh_type != RAILVEH_WAGON) {
2916 /* not a wagon */
2917 const Vehicle *v = Vehicle::Get(_new_vehicle_id);
2918 ShowVehicleViewWindow(v);
2919 return;
2922 /* find a locomotive in the depot. */
2923 const Vehicle *found = NULL;
2924 const Train *t;
2925 FOR_ALL_TRAINS(t) {
2926 if (t->IsFrontEngine() && t->tile == tile && t->IsStoppedInDepot()) {
2927 if (found != NULL) return; // must be exactly one.
2928 found = t;
2932 /* if we found a loco, */
2933 if (found != NULL) {
2934 found = found->Last();
2935 /* put the new wagon at the end of the loco. */
2936 DoCommandP(0, _new_vehicle_id | (1 << 31), found->index, CMD_MOVE_RAIL_VEHICLE);
2937 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
2942 * Get the error string to show for building a vehicle
2943 * @param tile The tile the command was executed on.
2944 * @param p1 Additional data for the command (for the #CommandProc)
2945 * @param p2 Additional data for the command (for the #CommandProc)
2946 * @param text Unused
2948 StringID GetErrBuildVehicle (TileIndex tile, uint32 p1, uint32 p2, const char *text)
2950 return GetErrBuildVeh(Engine::Get(GB(p1, 0, 16))->type);
2954 * Get the error string to show for building a vehicle
2955 * @param tile The tile the command was executed on.
2956 * @param p1 Additional data for the command (for the #CommandProc)
2957 * @param p2 Additional data for the command (for the #CommandProc)
2958 * @param text Unused
2960 StringID GetErrSellVehicle (TileIndex tile, uint32 p1, uint32 p2, const char *text)
2962 return GetErrSellVeh(Vehicle::Get(GB(p1, 0, 20)));
2966 * Get the error string to show for refitting a vehicle
2967 * @param tile The tile the command was executed on.
2968 * @param p1 Additional data for the command (for the #CommandProc)
2969 * @param p2 Additional data for the command (for the #CommandProc)
2970 * @param text Unused
2972 StringID GetErrRefitVehicle (TileIndex tile, uint32 p1, uint32 p2, const char *text)
2974 return GetErrRefitVeh(Vehicle::Get(p1));
2978 * Get the error string to show for cloning a vehicle
2979 * @param tile The tile the command was executed on.
2980 * @param p1 Additional data for the command (for the #CommandProc)
2981 * @param p2 Additional data for the command (for the #CommandProc)
2982 * @param text Unused
2984 StringID GetErrCloneVehicle (TileIndex tile, uint32 p1, uint32 p2, const char *text)
2986 return GetErrBuildVeh(Vehicle::Get(p1));
2990 * Get the error string to show for renaming a vehicle
2991 * @param tile The tile the command was executed on.
2992 * @param p1 Additional data for the command (for the #CommandProc)
2993 * @param p2 Additional data for the command (for the #CommandProc)
2994 * @param text Unused
2996 StringID GetErrRenameVehicle (TileIndex tile, uint32 p1, uint32 p2, const char *text)
2998 return STR_ERROR_CAN_T_RENAME_TRAIN + Vehicle::Get(p1)->type;
3002 * Get the error string to show for starting/stopping a vehicle
3003 * @param tile The tile the command was executed on.
3004 * @param p1 Additional data for the command (for the #CommandProc)
3005 * @param p2 Additional data for the command (for the #CommandProc)
3006 * @param text Unused
3008 StringID GetErrStartStopVehicle (TileIndex tile, uint32 p1, uint32 p2, const char *text)
3010 return _vehicle_string_startstop_table[Vehicle::Get(p1)->type];
3014 * Get the error string to show for sending a vehicle to the depot
3015 * @param tile The tile the command was executed on.
3016 * @param p1 Additional data for the command (for the #CommandProc)
3017 * @param p2 Additional data for the command (for the #CommandProc)
3018 * @param text Unused
3020 StringID GetErrSendVehicleToDepot (TileIndex tile, uint32 p1, uint32 p2, const char *text)
3022 VehicleType type;
3024 if (p1 & DEPOT_MASS_SEND) {
3025 /* Mass goto depot requested */
3026 VehicleListIdentifier vli;
3027 if (!vli.Unpack(p2)) return 0;
3028 type = vli.vtype;
3029 } else {
3030 type = Vehicle::Get(GB(p1, 0, 20))->type;
3033 return GetErrSendToDepot(type);
3037 * Get the error string to show for reversing a train
3038 * @param tile The tile the command was executed on.
3039 * @param p1 Additional data for the command (for the #CommandProc)
3040 * @param p2 Additional data for the command (for the #CommandProc)
3041 * @param text Unused
3043 StringID GetErrReverseTrain (TileIndex tile, uint32 p1, uint32 p2, const char *text)
3045 return p2 ? STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE : STR_ERROR_CAN_T_REVERSE_DIRECTION_TRAIN;
3049 * Get the width of a vehicle (including all parts of the consist) in pixels.
3050 * @param v Vehicle to get the width for.
3051 * @return Width of the vehicle.
3053 int GetVehicleWidth(Vehicle *v, EngineImageType image_type)
3055 int vehicle_width = 0;
3057 switch (v->type) {
3058 case VEH_TRAIN:
3059 for (const Train *u = Train::From(v); u != NULL; u = u->Next()) {
3060 vehicle_width += u->GetDisplayImageWidth();
3062 break;
3064 case VEH_ROAD:
3065 for (const RoadVehicle *u = RoadVehicle::From(v); u != NULL; u = u->Next()) {
3066 vehicle_width += u->GetDisplayImageWidth();
3068 break;
3070 default:
3071 bool rtl = _current_text_dir == TD_RTL;
3072 SpriteID sprite = v->GetImage(rtl ? DIR_E : DIR_W, image_type);
3073 const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
3074 vehicle_width = UnScaleGUI(real_sprite->width);
3076 break;
3079 return vehicle_width;