Fix: CmdSetAutoReplace didn't validate group type and engine type match (#9950)
[openttd-github.git] / src / vehicle_gui.cpp
blob2fe403391b66d117d33f0b3db3c2cac09d8f8cd2
1 /*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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/>.
6 */
8 /** @file vehicle_gui.cpp The base GUI for all vehicles. */
10 #include "stdafx.h"
11 #include "debug.h"
12 #include "company_func.h"
13 #include "gui.h"
14 #include "textbuf_gui.h"
15 #include "command_func.h"
16 #include "vehicle_gui_base.h"
17 #include "viewport_func.h"
18 #include "newgrf_text.h"
19 #include "newgrf_debug.h"
20 #include "roadveh.h"
21 #include "train.h"
22 #include "aircraft.h"
23 #include "depot_map.h"
24 #include "group_gui.h"
25 #include "strings_func.h"
26 #include "vehicle_func.h"
27 #include "autoreplace_gui.h"
28 #include "string_func.h"
29 #include "widgets/dropdown_func.h"
30 #include "timetable.h"
31 #include "articulated_vehicles.h"
32 #include "spritecache.h"
33 #include "core/geometry_func.hpp"
34 #include "company_base.h"
35 #include "engine_func.h"
36 #include "station_base.h"
37 #include "tilehighlight_func.h"
38 #include "zoom_func.h"
39 #include "depot_cmd.h"
40 #include "vehicle_cmd.h"
41 #include "order_cmd.h"
42 #include "roadveh_cmd.h"
43 #include "train_cmd.h"
45 #include "safeguards.h"
48 BaseVehicleListWindow::GroupBy _grouping[VLT_END][VEH_COMPANY_END];
49 Sorting _sorting[BaseVehicleListWindow::GB_END];
51 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleNumberSorter;
52 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleNameSorter;
53 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleAgeSorter;
54 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleProfitThisYearSorter;
55 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleProfitLastYearSorter;
56 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleCargoSorter;
57 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleReliabilitySorter;
58 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleMaxSpeedSorter;
59 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleModelSorter;
60 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleValueSorter;
61 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleLengthSorter;
62 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleTimeToLiveSorter;
63 static BaseVehicleListWindow::VehicleIndividualSortFunction VehicleTimetableDelaySorter;
64 static BaseVehicleListWindow::VehicleGroupSortFunction VehicleGroupLengthSorter;
65 static BaseVehicleListWindow::VehicleGroupSortFunction VehicleGroupTotalProfitThisYearSorter;
66 static BaseVehicleListWindow::VehicleGroupSortFunction VehicleGroupTotalProfitLastYearSorter;
67 static BaseVehicleListWindow::VehicleGroupSortFunction VehicleGroupAverageProfitThisYearSorter;
68 static BaseVehicleListWindow::VehicleGroupSortFunction VehicleGroupAverageProfitLastYearSorter;
70 /** Wrapper to convert a VehicleIndividualSortFunction to a VehicleGroupSortFunction */
71 template <BaseVehicleListWindow::VehicleIndividualSortFunction func>
72 static bool VehicleIndividualToGroupSorterWrapper(GUIVehicleGroup const &a, GUIVehicleGroup const &b)
74 return func(*(a.vehicles_begin), *(b.vehicles_begin));
77 BaseVehicleListWindow::VehicleGroupSortFunction * const BaseVehicleListWindow::vehicle_group_none_sorter_funcs[] = {
78 &VehicleIndividualToGroupSorterWrapper<VehicleNumberSorter>,
79 &VehicleIndividualToGroupSorterWrapper<VehicleNameSorter>,
80 &VehicleIndividualToGroupSorterWrapper<VehicleAgeSorter>,
81 &VehicleIndividualToGroupSorterWrapper<VehicleProfitThisYearSorter>,
82 &VehicleIndividualToGroupSorterWrapper<VehicleProfitLastYearSorter>,
83 &VehicleIndividualToGroupSorterWrapper<VehicleCargoSorter>,
84 &VehicleIndividualToGroupSorterWrapper<VehicleReliabilitySorter>,
85 &VehicleIndividualToGroupSorterWrapper<VehicleMaxSpeedSorter>,
86 &VehicleIndividualToGroupSorterWrapper<VehicleModelSorter>,
87 &VehicleIndividualToGroupSorterWrapper<VehicleValueSorter>,
88 &VehicleIndividualToGroupSorterWrapper<VehicleLengthSorter>,
89 &VehicleIndividualToGroupSorterWrapper<VehicleTimeToLiveSorter>,
90 &VehicleIndividualToGroupSorterWrapper<VehicleTimetableDelaySorter>,
93 const StringID BaseVehicleListWindow::vehicle_group_none_sorter_names[] = {
94 STR_SORT_BY_NUMBER,
95 STR_SORT_BY_NAME,
96 STR_SORT_BY_AGE,
97 STR_SORT_BY_PROFIT_THIS_YEAR,
98 STR_SORT_BY_PROFIT_LAST_YEAR,
99 STR_SORT_BY_TOTAL_CAPACITY_PER_CARGOTYPE,
100 STR_SORT_BY_RELIABILITY,
101 STR_SORT_BY_MAX_SPEED,
102 STR_SORT_BY_MODEL,
103 STR_SORT_BY_VALUE,
104 STR_SORT_BY_LENGTH,
105 STR_SORT_BY_LIFE_TIME,
106 STR_SORT_BY_TIMETABLE_DELAY,
107 INVALID_STRING_ID
110 BaseVehicleListWindow::VehicleGroupSortFunction * const BaseVehicleListWindow::vehicle_group_shared_orders_sorter_funcs[] = {
111 &VehicleGroupLengthSorter,
112 &VehicleGroupTotalProfitThisYearSorter,
113 &VehicleGroupTotalProfitLastYearSorter,
114 &VehicleGroupAverageProfitThisYearSorter,
115 &VehicleGroupAverageProfitLastYearSorter,
118 const StringID BaseVehicleListWindow::vehicle_group_shared_orders_sorter_names[] = {
119 STR_SORT_BY_NUM_VEHICLES,
120 STR_SORT_BY_TOTAL_PROFIT_THIS_YEAR,
121 STR_SORT_BY_TOTAL_PROFIT_LAST_YEAR,
122 STR_SORT_BY_AVERAGE_PROFIT_THIS_YEAR,
123 STR_SORT_BY_AVERAGE_PROFIT_LAST_YEAR,
124 INVALID_STRING_ID
127 const StringID BaseVehicleListWindow::vehicle_group_by_names[] = {
128 STR_GROUP_BY_NONE,
129 STR_GROUP_BY_SHARED_ORDERS,
130 INVALID_STRING_ID
133 const StringID BaseVehicleListWindow::vehicle_depot_name[] = {
134 STR_VEHICLE_LIST_SEND_TRAIN_TO_DEPOT,
135 STR_VEHICLE_LIST_SEND_ROAD_VEHICLE_TO_DEPOT,
136 STR_VEHICLE_LIST_SEND_SHIP_TO_DEPOT,
137 STR_VEHICLE_LIST_SEND_AIRCRAFT_TO_HANGAR
140 BaseVehicleListWindow::BaseVehicleListWindow(WindowDesc *desc, WindowNumber wno) : Window(desc), vli(VehicleListIdentifier::UnPack(wno))
142 this->grouping = _grouping[vli.type][vli.vtype];
143 this->UpdateSortingFromGrouping();
147 * Get the number of digits of space required for the given number.
148 * @param number The number.
149 * @return The number of digits to allocate space for.
151 uint CountDigitsForAllocatingSpace(uint number)
153 if (number >= 10000) return 5;
154 if (number >= 1000) return 4;
155 if (number >= 100) return 3;
158 * When the smallest unit number is less than 10, it is
159 * quite likely that it will expand to become more than
160 * 10 quite soon.
162 return 2;
166 * Get the number of digits the biggest unit number of a set of vehicles has.
167 * @param vehicles The list of vehicles.
168 * @return The number of digits to allocate space for.
170 uint GetUnitNumberDigits(VehicleList &vehicles)
172 uint unitnumber = 0;
173 for (const Vehicle *v : vehicles) {
174 unitnumber = std::max<uint>(unitnumber, v->unitnumber);
177 return CountDigitsForAllocatingSpace(unitnumber);
180 void BaseVehicleListWindow::BuildVehicleList()
182 if (!this->vehgroups.NeedRebuild()) return;
184 Debug(misc, 3, "Building vehicle list type {} for company {} given index {}", this->vli.type, this->vli.company, this->vli.index);
186 this->vehgroups.clear();
188 GenerateVehicleSortList(&this->vehicles, this->vli);
190 if (this->grouping == GB_NONE) {
191 uint max_unitnumber = 0;
192 for (auto it = this->vehicles.begin(); it != this->vehicles.end(); ++it) {
193 this->vehgroups.emplace_back(it, it + 1);
195 max_unitnumber = std::max<uint>(max_unitnumber, (*it)->unitnumber);
197 this->unitnumber_digits = CountDigitsForAllocatingSpace(max_unitnumber);
198 } else {
199 /* Sort by the primary vehicle; we just want all vehicles that share the same orders to form a contiguous range. */
200 std::stable_sort(this->vehicles.begin(), this->vehicles.end(), [](const Vehicle * const &u, const Vehicle * const &v) {
201 return u->FirstShared() < v->FirstShared();
204 uint max_num_vehicles = 0;
206 VehicleList::const_iterator begin = this->vehicles.begin();
207 while (begin != this->vehicles.end()) {
208 VehicleList::const_iterator end = std::find_if_not(begin, this->vehicles.cend(), [first_shared = (*begin)->FirstShared()](const Vehicle * const &v) {
209 return v->FirstShared() == first_shared;
212 this->vehgroups.emplace_back(begin, end);
214 max_num_vehicles = std::max<uint>(max_num_vehicles, static_cast<uint>(end - begin));
216 begin = end;
219 this->unitnumber_digits = CountDigitsForAllocatingSpace(max_num_vehicles);
222 this->vehgroups.RebuildDone();
223 this->vscroll->SetCount(static_cast<int>(this->vehgroups.size()));
227 * Compute the size for the Action dropdown.
228 * @param show_autoreplace If true include the autoreplace item.
229 * @param show_group If true include group-related stuff.
230 * @return Required size.
232 Dimension BaseVehicleListWindow::GetActionDropdownSize(bool show_autoreplace, bool show_group)
234 Dimension d = {0, 0};
236 if (show_autoreplace) d = maxdim(d, GetStringBoundingBox(STR_VEHICLE_LIST_REPLACE_VEHICLES));
237 d = maxdim(d, GetStringBoundingBox(STR_VEHICLE_LIST_SEND_FOR_SERVICING));
238 d = maxdim(d, GetStringBoundingBox(this->vehicle_depot_name[this->vli.vtype]));
240 if (show_group) {
241 d = maxdim(d, GetStringBoundingBox(STR_GROUP_ADD_SHARED_VEHICLE));
242 d = maxdim(d, GetStringBoundingBox(STR_GROUP_REMOVE_ALL_VEHICLES));
245 return d;
248 void BaseVehicleListWindow::OnInit()
250 this->order_arrow_width = GetStringBoundingBox(STR_TINY_RIGHT_ARROW).width;
254 * Display the Action dropdown window.
255 * @param show_autoreplace If true include the autoreplace item.
256 * @param show_group If true include group-related stuff.
257 * @return Itemlist for dropdown
259 DropDownList BaseVehicleListWindow::BuildActionDropdownList(bool show_autoreplace, bool show_group)
261 DropDownList list;
263 if (show_autoreplace) list.emplace_back(new DropDownListStringItem(STR_VEHICLE_LIST_REPLACE_VEHICLES, ADI_REPLACE, false));
264 list.emplace_back(new DropDownListStringItem(STR_VEHICLE_LIST_SEND_FOR_SERVICING, ADI_SERVICE, false));
265 list.emplace_back(new DropDownListStringItem(this->vehicle_depot_name[this->vli.vtype], ADI_DEPOT, false));
267 if (show_group) {
268 list.emplace_back(new DropDownListStringItem(STR_GROUP_ADD_SHARED_VEHICLE, ADI_ADD_SHARED, false));
269 list.emplace_back(new DropDownListStringItem(STR_GROUP_REMOVE_ALL_VEHICLES, ADI_REMOVE_ALL, false));
272 return list;
275 /* cached values for VehicleNameSorter to spare many GetString() calls */
276 static const Vehicle *_last_vehicle[2] = { nullptr, nullptr };
278 void BaseVehicleListWindow::SortVehicleList()
280 if (this->vehgroups.Sort()) return;
282 /* invalidate cached values for name sorter - vehicle names could change */
283 _last_vehicle[0] = _last_vehicle[1] = nullptr;
286 void DepotSortList(VehicleList *list)
288 if (list->size() < 2) return;
289 std::sort(list->begin(), list->end(), &VehicleNumberSorter);
292 /** draw the vehicle profit button in the vehicle list window. */
293 static void DrawVehicleProfitButton(Date age, Money display_profit_last_year, uint num_vehicles, int x, int y)
295 SpriteID spr;
297 /* draw profit-based coloured icons */
298 if (age <= VEHICLE_PROFIT_MIN_AGE) {
299 spr = SPR_PROFIT_NA;
300 } else if (display_profit_last_year < 0) {
301 spr = SPR_PROFIT_NEGATIVE;
302 } else if (display_profit_last_year < VEHICLE_PROFIT_THRESHOLD * num_vehicles) {
303 spr = SPR_PROFIT_SOME;
304 } else {
305 spr = SPR_PROFIT_LOT;
307 DrawSprite(spr, PAL_NONE, x, y);
310 /** Maximum number of refit cycles we try, to prevent infinite loops. And we store only a byte anyway */
311 static const uint MAX_REFIT_CYCLE = 256;
314 * Get the best fitting subtype when 'cloning'/'replacing' \a v_from with \a v_for.
315 * All articulated parts of both vehicles are tested to find a possibly shared subtype.
316 * For \a v_for only vehicle refittable to \a dest_cargo_type are considered.
317 * @param v_from the vehicle to match the subtype from
318 * @param v_for the vehicle to get the subtype for
319 * @param dest_cargo_type Destination cargo type.
320 * @return the best sub type
322 byte GetBestFittingSubType(Vehicle *v_from, Vehicle *v_for, CargoID dest_cargo_type)
324 v_from = v_from->GetFirstEnginePart();
325 v_for = v_for->GetFirstEnginePart();
327 /* Create a list of subtypes used by the various parts of v_for */
328 static std::vector<StringID> subtypes;
329 subtypes.clear();
330 for (; v_from != nullptr; v_from = v_from->HasArticulatedPart() ? v_from->GetNextArticulatedPart() : nullptr) {
331 const Engine *e_from = v_from->GetEngine();
332 if (!e_from->CanCarryCargo() || !HasBit(e_from->info.callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) continue;
333 include(subtypes, GetCargoSubtypeText(v_from));
336 byte ret_refit_cyc = 0;
337 bool success = false;
338 if (subtypes.size() > 0) {
339 /* Check whether any articulated part is refittable to 'dest_cargo_type' with a subtype listed in 'subtypes' */
340 for (Vehicle *v = v_for; v != nullptr; v = v->HasArticulatedPart() ? v->GetNextArticulatedPart() : nullptr) {
341 const Engine *e = v->GetEngine();
342 if (!e->CanCarryCargo() || !HasBit(e->info.callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) continue;
343 if (!HasBit(e->info.refit_mask, dest_cargo_type) && v->cargo_type != dest_cargo_type) continue;
345 CargoID old_cargo_type = v->cargo_type;
346 byte old_cargo_subtype = v->cargo_subtype;
348 /* Set the 'destination' cargo */
349 v->cargo_type = dest_cargo_type;
351 /* Cycle through the refits */
352 for (uint refit_cyc = 0; refit_cyc < MAX_REFIT_CYCLE; refit_cyc++) {
353 v->cargo_subtype = refit_cyc;
355 /* Make sure we don't pick up anything cached. */
356 v->First()->InvalidateNewGRFCache();
357 v->InvalidateNewGRFCache();
359 StringID subtype = GetCargoSubtypeText(v);
360 if (subtype == STR_EMPTY) break;
362 if (std::find(subtypes.begin(), subtypes.end(), subtype) == subtypes.end()) continue;
364 /* We found something matching. */
365 ret_refit_cyc = refit_cyc;
366 success = true;
367 break;
370 /* Reset the vehicle's cargo type */
371 v->cargo_type = old_cargo_type;
372 v->cargo_subtype = old_cargo_subtype;
374 /* Make sure we don't taint the vehicle. */
375 v->First()->InvalidateNewGRFCache();
376 v->InvalidateNewGRFCache();
378 if (success) break;
382 return ret_refit_cyc;
385 /** Option to refit a vehicle chain */
386 struct RefitOption {
387 CargoID cargo; ///< Cargo to refit to
388 byte subtype; ///< Subcargo to use
389 StringID string; ///< GRF-local String to display for the cargo
392 * Inequality operator for #RefitOption.
393 * @param other Compare to this #RefitOption.
394 * @return True if both #RefitOption are different.
396 inline bool operator != (const RefitOption &other) const
398 return other.cargo != this->cargo || other.string != this->string;
402 * Equality operator for #RefitOption.
403 * @param other Compare to this #RefitOption.
404 * @return True if both #RefitOption are equal.
406 inline bool operator == (const RefitOption &other) const
408 return other.cargo == this->cargo && other.string == this->string;
412 typedef std::vector<RefitOption> SubtypeList; ///< List of refit subtypes associated to a cargo.
415 * Draw the list of available refit options for a consist and highlight the selected refit option (if any).
416 * @param list List of subtype options for each (sorted) cargo.
417 * @param sel Selected refit cargo-type in the window
418 * @param pos Position of the selected item in caller widow
419 * @param rows Number of rows(capacity) in caller window
420 * @param delta Step height in caller window
421 * @param r Rectangle of the matrix widget.
423 static void DrawVehicleRefitWindow(const SubtypeList list[NUM_CARGO], const int sel[2], uint pos, uint rows, uint delta, const Rect &r)
425 uint y = r.top + WD_MATRIX_TOP;
426 uint current = 0;
428 bool rtl = _current_text_dir == TD_RTL;
429 uint iconwidth = std::max(GetSpriteSize(SPR_CIRCLE_FOLDED).width, GetSpriteSize(SPR_CIRCLE_UNFOLDED).width);
430 uint iconheight = GetSpriteSize(SPR_CIRCLE_FOLDED).height;
431 int linecolour = _colour_gradient[COLOUR_ORANGE][4];
433 int iconleft = rtl ? r.right - WD_MATRIX_RIGHT - iconwidth : r.left + WD_MATRIX_LEFT;
434 int iconcenter = rtl ? r.right - WD_MATRIX_RIGHT - iconwidth / 2 : r.left + WD_MATRIX_LEFT + iconwidth / 2;
435 int iconinner = rtl ? r.right - WD_MATRIX_RIGHT - iconwidth : r.left + WD_MATRIX_LEFT + iconwidth;
437 int textleft = r.left + WD_MATRIX_LEFT + (rtl ? 0 : iconwidth + 4);
438 int textright = r.right - WD_MATRIX_RIGHT - (rtl ? iconwidth + 4 : 0);
440 /* Draw the list of subtypes for each cargo, and find the selected refit option (by its position). */
441 for (uint i = 0; current < pos + rows && i < NUM_CARGO; i++) {
442 for (uint j = 0; current < pos + rows && j < list[i].size(); j++) {
443 const RefitOption &refit = list[i][j];
445 /* Hide subtypes if sel[0] does not match */
446 if (sel[0] != (int)i && refit.subtype != 0xFF) continue;
448 /* Refit options with a position smaller than pos don't have to be drawn. */
449 if (current < pos) {
450 current++;
451 continue;
454 if (list[i].size() > 1) {
455 if (refit.subtype != 0xFF) {
456 /* Draw tree lines */
457 int ycenter = y + FONT_HEIGHT_NORMAL / 2;
458 GfxDrawLine(iconcenter, y - WD_MATRIX_TOP, iconcenter, j == list[i].size() - 1 ? ycenter : y - WD_MATRIX_TOP + delta - 1, linecolour);
459 GfxDrawLine(iconcenter, ycenter, iconinner, ycenter, linecolour);
460 } else {
461 /* Draw expand/collapse icon */
462 DrawSprite(sel[0] == (int)i ? SPR_CIRCLE_UNFOLDED : SPR_CIRCLE_FOLDED, PAL_NONE, iconleft, y + (FONT_HEIGHT_NORMAL - iconheight) / 2);
466 TextColour colour = (sel[0] == (int)i && (uint)sel[1] == j) ? TC_WHITE : TC_BLACK;
467 /* Get the cargo name. */
468 SetDParam(0, CargoSpec::Get(refit.cargo)->name);
469 SetDParam(1, refit.string);
470 DrawString(textleft, textright, y, STR_JUST_STRING_STRING, colour);
472 y += delta;
473 current++;
478 /** Refit cargo window. */
479 struct RefitWindow : public Window {
480 int sel[2]; ///< Index in refit options, sel[0] == -1 if nothing is selected.
481 RefitOption *cargo; ///< Refit option selected by #sel.
482 SubtypeList list[NUM_CARGO]; ///< List of refit subtypes available for each sorted cargo.
483 VehicleOrderID order; ///< If not #INVALID_VEH_ORDER_ID, selection is part of a refit order (rather than execute directly).
484 uint information_width; ///< Width required for correctly displaying all cargoes in the information panel.
485 Scrollbar *vscroll; ///< The main scrollbar.
486 Scrollbar *hscroll; ///< Only used for long vehicles.
487 int vehicle_width; ///< Width of the vehicle being drawn.
488 int sprite_left; ///< Left position of the vehicle sprite.
489 int sprite_right; ///< Right position of the vehicle sprite.
490 uint vehicle_margin; ///< Margin to use while selecting vehicles when the vehicle image is centered.
491 int click_x; ///< Position of the first click while dragging.
492 VehicleID selected_vehicle; ///< First vehicle in the current selection.
493 uint8 num_vehicles; ///< Number of selected vehicles.
494 bool auto_refit; ///< Select cargo for auto-refitting.
497 * Collects all (cargo, subcargo) refit options of a vehicle chain.
499 void BuildRefitList()
501 for (uint i = 0; i < NUM_CARGO; i++) this->list[i].clear();
502 Vehicle *v = Vehicle::Get(this->window_number);
504 /* Check only the selected vehicles. */
505 VehicleSet vehicles_to_refit;
506 GetVehicleSet(vehicles_to_refit, Vehicle::Get(this->selected_vehicle), this->num_vehicles);
508 do {
509 if (v->type == VEH_TRAIN && std::find(vehicles_to_refit.begin(), vehicles_to_refit.end(), v->index) == vehicles_to_refit.end()) continue;
510 const Engine *e = v->GetEngine();
511 CargoTypes cmask = e->info.refit_mask;
512 byte callback_mask = e->info.callback_mask;
514 /* Skip this engine if it does not carry anything */
515 if (!e->CanCarryCargo()) continue;
516 /* Skip this engine if we build the list for auto-refitting and engine doesn't allow it. */
517 if (this->auto_refit && !HasBit(e->info.misc_flags, EF_AUTO_REFIT)) continue;
519 /* Loop through all cargoes in the refit mask */
520 int current_index = 0;
521 for (const auto &cs : _sorted_cargo_specs) {
522 CargoID cid = cs->Index();
523 /* Skip cargo type if it's not listed */
524 if (!HasBit(cmask, cid)) {
525 current_index++;
526 continue;
529 bool first_vehicle = this->list[current_index].size() == 0;
530 if (first_vehicle) {
531 /* Keeping the current subtype is always an option. It also serves as the option in case of no subtypes */
532 this->list[current_index].push_back({cid, 0xFF, STR_EMPTY});
535 /* Check the vehicle's callback mask for cargo suffixes.
536 * This is not supported for ordered refits, since subtypes only have a meaning
537 * for a specific vehicle at a specific point in time, which conflicts with shared orders,
538 * autoreplace, autorenew, clone, order restoration, ... */
539 if (this->order == INVALID_VEH_ORDER_ID && HasBit(callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) {
540 /* Make a note of the original cargo type. It has to be
541 * changed to test the cargo & subtype... */
542 CargoID temp_cargo = v->cargo_type;
543 byte temp_subtype = v->cargo_subtype;
545 v->cargo_type = cid;
547 for (uint refit_cyc = 0; refit_cyc < MAX_REFIT_CYCLE; refit_cyc++) {
548 v->cargo_subtype = refit_cyc;
550 /* Make sure we don't pick up anything cached. */
551 v->First()->InvalidateNewGRFCache();
552 v->InvalidateNewGRFCache();
554 StringID subtype = GetCargoSubtypeText(v);
556 if (first_vehicle) {
557 /* Append new subtype (don't add duplicates though) */
558 if (subtype == STR_EMPTY) break;
560 RefitOption option;
561 option.cargo = cid;
562 option.subtype = refit_cyc;
563 option.string = subtype;
564 include(this->list[current_index], option);
565 } else {
566 /* Intersect the subtypes of earlier vehicles with the subtypes of this vehicle */
567 if (subtype == STR_EMPTY) {
568 /* No more subtypes for this vehicle, delete all subtypes >= refit_cyc */
569 SubtypeList &l = this->list[current_index];
570 /* 0xFF item is in front, other subtypes are sorted. So just truncate the list in the right spot */
571 for (uint i = 1; i < l.size(); i++) {
572 if (l[i].subtype >= refit_cyc) {
573 l.resize(i);
574 break;
577 break;
578 } else {
579 /* Check whether the subtype matches with the subtype of earlier vehicles. */
580 uint pos = 1;
581 SubtypeList &l = this->list[current_index];
582 while (pos < l.size() && l[pos].subtype != refit_cyc) pos++;
583 if (pos < l.size() && l[pos].string != subtype) {
584 /* String mismatch, remove item keeping the order */
585 l.erase(l.begin() + pos);
591 /* Reset the vehicle's cargo type */
592 v->cargo_type = temp_cargo;
593 v->cargo_subtype = temp_subtype;
595 /* And make sure we haven't tainted the cache */
596 v->First()->InvalidateNewGRFCache();
597 v->InvalidateNewGRFCache();
599 current_index++;
601 } while (v->IsGroundVehicle() && (v = v->Next()) != nullptr);
605 * Refresh scrollbar after selection changed
607 void RefreshScrollbar()
609 uint scroll_row = 0;
610 uint row = 0;
612 for (uint i = 0; i < NUM_CARGO; i++) {
613 for (uint j = 0; j < this->list[i].size(); j++) {
614 const RefitOption &refit = this->list[i][j];
616 /* Hide subtypes if sel[0] does not match */
617 if (this->sel[0] != (int)i && refit.subtype != 0xFF) continue;
619 if (this->sel[0] == (int)i && (uint)this->sel[1] == j) scroll_row = row;
621 row++;
625 this->vscroll->SetCount(row);
626 if (scroll_row < row) this->vscroll->ScrollTowards(scroll_row);
630 * Select a row.
631 * @param click_row Clicked row
633 void SetSelection(uint click_row)
635 uint row = 0;
637 for (uint i = 0; i < NUM_CARGO; i++) {
638 for (uint j = 0; j < this->list[i].size(); j++) {
639 const RefitOption &refit = this->list[i][j];
641 /* Hide subtypes if sel[0] does not match */
642 if (this->sel[0] != (int)i && refit.subtype != 0xFF) continue;
644 if (row == click_row) {
645 this->sel[0] = i;
646 this->sel[1] = j;
647 return;
650 row++;
654 this->sel[0] = -1;
655 this->sel[1] = 0;
659 * Gets the #RefitOption placed in the selected index.
660 * @return Pointer to the #RefitOption currently in use.
662 RefitOption *GetRefitOption()
664 if (this->sel[0] < 0) return nullptr;
666 SubtypeList &l = this->list[this->sel[0]];
667 if ((uint)this->sel[1] >= l.size()) return nullptr;
669 return &l[this->sel[1]];
672 RefitWindow(WindowDesc *desc, const Vehicle *v, VehicleOrderID order, bool auto_refit) : Window(desc)
674 this->sel[0] = -1;
675 this->sel[1] = 0;
676 this->auto_refit = auto_refit;
677 this->order = order;
678 this->CreateNestedTree();
680 this->vscroll = this->GetScrollbar(WID_VR_SCROLLBAR);
681 this->hscroll = (v->IsGroundVehicle() ? this->GetScrollbar(WID_VR_HSCROLLBAR) : nullptr);
682 this->GetWidget<NWidgetCore>(WID_VR_SELECT_HEADER)->tool_tip = STR_REFIT_TRAIN_LIST_TOOLTIP + v->type;
683 this->GetWidget<NWidgetCore>(WID_VR_MATRIX)->tool_tip = STR_REFIT_TRAIN_LIST_TOOLTIP + v->type;
684 NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_VR_REFIT);
685 nwi->widget_data = STR_REFIT_TRAIN_REFIT_BUTTON + v->type;
686 nwi->tool_tip = STR_REFIT_TRAIN_REFIT_TOOLTIP + v->type;
687 this->GetWidget<NWidgetStacked>(WID_VR_SHOW_HSCROLLBAR)->SetDisplayedPlane(v->IsGroundVehicle() ? 0 : SZSP_HORIZONTAL);
688 this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY)->tool_tip = (v->type == VEH_TRAIN) ? STR_REFIT_SELECT_VEHICLES_TOOLTIP : STR_NULL;
690 this->FinishInitNested(v->index);
691 this->owner = v->owner;
693 this->SetWidgetDisabledState(WID_VR_REFIT, this->sel[0] < 0);
696 void OnInit() override
698 if (this->cargo != nullptr) {
699 /* Store the RefitOption currently in use. */
700 RefitOption current_refit_option = *(this->cargo);
702 /* Rebuild the refit list */
703 this->BuildRefitList();
704 this->sel[0] = -1;
705 this->sel[1] = 0;
706 this->cargo = nullptr;
707 for (uint i = 0; this->cargo == nullptr && i < NUM_CARGO; i++) {
708 for (uint j = 0; j < list[i].size(); j++) {
709 if (list[i][j] == current_refit_option) {
710 this->sel[0] = i;
711 this->sel[1] = j;
712 this->cargo = &list[i][j];
713 break;
718 this->SetWidgetDisabledState(WID_VR_REFIT, this->sel[0] < 0);
719 this->RefreshScrollbar();
720 } else {
721 /* Rebuild the refit list */
722 this->OnInvalidateData(VIWD_CONSIST_CHANGED);
726 void OnPaint() override
728 /* Determine amount of items for scroller. */
729 if (this->hscroll != nullptr) this->hscroll->SetCount(this->vehicle_width);
731 /* Calculate sprite position. */
732 NWidgetCore *vehicle_panel_display = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY);
733 int sprite_width = std::max(0, ((int)vehicle_panel_display->current_x - this->vehicle_width) / 2);
734 this->sprite_left = vehicle_panel_display->pos_x;
735 this->sprite_right = vehicle_panel_display->pos_x + vehicle_panel_display->current_x - 1;
736 if (_current_text_dir == TD_RTL) {
737 this->sprite_right -= sprite_width;
738 this->vehicle_margin = vehicle_panel_display->current_x - sprite_right;
739 } else {
740 this->sprite_left += sprite_width;
741 this->vehicle_margin = sprite_left;
744 this->DrawWidgets();
747 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
749 switch (widget) {
750 case WID_VR_MATRIX:
751 resize->height = WD_MATRIX_TOP + FONT_HEIGHT_NORMAL + WD_MATRIX_BOTTOM;
752 size->height = resize->height * 8;
753 break;
755 case WID_VR_VEHICLE_PANEL_DISPLAY:
756 size->height = ScaleGUITrad(GetVehicleHeight(Vehicle::Get(this->window_number)->type));
757 break;
759 case WID_VR_INFO:
760 size->width = WD_FRAMERECT_LEFT + this->information_width + WD_FRAMERECT_RIGHT;
761 break;
765 void SetStringParameters(int widget) const override
767 if (widget == WID_VR_CAPTION) SetDParam(0, Vehicle::Get(this->window_number)->index);
771 * Gets the #StringID to use for displaying capacity.
772 * @param option Cargo and cargo subtype to check for capacity.
773 * @return INVALID_STRING_ID if there is no capacity. StringID to use in any other case.
774 * @post String parameters have been set.
776 StringID GetCapacityString(RefitOption *option) const
778 assert(_current_company == _local_company);
779 auto [cost, refit_capacity, mail_capacity] = Command<CMD_REFIT_VEHICLE>::Do(DC_QUERY_COST, this->selected_vehicle, option->cargo, option->subtype, this->auto_refit, false, this->num_vehicles);
781 if (cost.Failed()) return INVALID_STRING_ID;
783 SetDParam(0, option->cargo);
784 SetDParam(1, refit_capacity);
786 Money money = cost.GetCost();
787 if (mail_capacity > 0) {
788 SetDParam(2, CT_MAIL);
789 SetDParam(3, mail_capacity);
790 if (this->order != INVALID_VEH_ORDER_ID) {
791 /* No predictable cost */
792 return STR_PURCHASE_INFO_AIRCRAFT_CAPACITY;
793 } else if (money <= 0) {
794 SetDParam(4, -money);
795 return STR_REFIT_NEW_CAPACITY_INCOME_FROM_AIRCRAFT_REFIT;
796 } else {
797 SetDParam(4, money);
798 return STR_REFIT_NEW_CAPACITY_COST_OF_AIRCRAFT_REFIT;
800 } else {
801 if (this->order != INVALID_VEH_ORDER_ID) {
802 /* No predictable cost */
803 SetDParam(2, STR_EMPTY);
804 return STR_PURCHASE_INFO_CAPACITY;
805 } else if (money <= 0) {
806 SetDParam(2, -money);
807 return STR_REFIT_NEW_CAPACITY_INCOME_FROM_REFIT;
808 } else {
809 SetDParam(2, money);
810 return STR_REFIT_NEW_CAPACITY_COST_OF_REFIT;
815 void DrawWidget(const Rect &r, int widget) const override
817 switch (widget) {
818 case WID_VR_VEHICLE_PANEL_DISPLAY: {
819 Vehicle *v = Vehicle::Get(this->window_number);
820 DrawVehicleImage(v, this->sprite_left + WD_FRAMERECT_LEFT, this->sprite_right - WD_FRAMERECT_RIGHT,
821 r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, this->hscroll != nullptr ? this->hscroll->GetPosition() : 0);
823 /* Highlight selected vehicles. */
824 if (this->order != INVALID_VEH_ORDER_ID) break;
825 int x = 0;
826 switch (v->type) {
827 case VEH_TRAIN: {
828 VehicleSet vehicles_to_refit;
829 GetVehicleSet(vehicles_to_refit, Vehicle::Get(this->selected_vehicle), this->num_vehicles);
831 int left = INT32_MIN;
832 int width = 0;
834 for (Train *u = Train::From(v); u != nullptr; u = u->Next()) {
835 /* Start checking. */
836 const bool contained = std::find(vehicles_to_refit.begin(), vehicles_to_refit.end(), u->index) != vehicles_to_refit.end();
837 if (contained && left == INT32_MIN) {
838 left = x - this->hscroll->GetPosition() + r.left + this->vehicle_margin;
839 width = 0;
842 /* Draw a selection. */
843 if ((!contained || u->Next() == nullptr) && left != INT32_MIN) {
844 if (u->Next() == nullptr && contained) {
845 int current_width = u->GetDisplayImageWidth();
846 width += current_width;
847 x += current_width;
850 int right = Clamp(left + width, 0, r.right);
851 left = std::max(0, left);
853 if (_current_text_dir == TD_RTL) {
854 right = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY)->current_x - left;
855 left = right - width;
858 if (left != right) {
859 DrawFrameRect(left, r.top + WD_FRAMERECT_TOP, right, r.top + WD_FRAMERECT_TOP + ScaleGUITrad(14) - 1, COLOUR_WHITE, FR_BORDERONLY);
862 left = INT32_MIN;
865 int current_width = u->GetDisplayImageWidth();
866 width += current_width;
867 x += current_width;
869 break;
872 default: break;
874 break;
877 case WID_VR_MATRIX:
878 DrawVehicleRefitWindow(this->list, this->sel, this->vscroll->GetPosition(), this->vscroll->GetCapacity(), this->resize.step_height, r);
879 break;
881 case WID_VR_INFO:
882 if (this->cargo != nullptr) {
883 StringID string = this->GetCapacityString(this->cargo);
884 if (string != INVALID_STRING_ID) {
885 DrawStringMultiLine(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT,
886 r.top + WD_FRAMERECT_TOP, r.bottom - WD_FRAMERECT_BOTTOM, string);
889 break;
894 * Some data on this window has become invalid.
895 * @param data Information about the changed data.
896 * @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.
898 void OnInvalidateData(int data = 0, bool gui_scope = true) override
900 switch (data) {
901 case VIWD_AUTOREPLACE: // Autoreplace replaced the vehicle; selected_vehicle became invalid.
902 case VIWD_CONSIST_CHANGED: { // The consist has changed; rebuild the entire list.
903 /* Clear the selection. */
904 Vehicle *v = Vehicle::Get(this->window_number);
905 this->selected_vehicle = v->index;
906 this->num_vehicles = UINT8_MAX;
907 FALLTHROUGH;
910 case 2: { // The vehicle selection has changed; rebuild the entire list.
911 if (!gui_scope) break;
912 this->BuildRefitList();
914 /* The vehicle width has changed too. */
915 this->vehicle_width = GetVehicleWidth(Vehicle::Get(this->window_number), EIT_IN_DETAILS);
916 uint max_width = 0;
918 /* Check the width of all cargo information strings. */
919 for (uint i = 0; i < NUM_CARGO; i++) {
920 for (uint j = 0; j < this->list[i].size(); j++) {
921 StringID string = this->GetCapacityString(&list[i][j]);
922 if (string != INVALID_STRING_ID) {
923 Dimension dim = GetStringBoundingBox(string);
924 max_width = std::max(dim.width, max_width);
929 if (this->information_width < max_width) {
930 this->information_width = max_width;
931 this->ReInit();
933 FALLTHROUGH;
936 case 1: // A new cargo has been selected.
937 if (!gui_scope) break;
938 this->cargo = GetRefitOption();
939 this->RefreshScrollbar();
940 break;
944 int GetClickPosition(int click_x)
946 const NWidgetCore *matrix_widget = this->GetWidget<NWidgetCore>(WID_VR_VEHICLE_PANEL_DISPLAY);
947 if (_current_text_dir == TD_RTL) click_x = matrix_widget->current_x - click_x;
948 click_x -= this->vehicle_margin;
949 if (this->hscroll != nullptr) click_x += this->hscroll->GetPosition();
951 return click_x;
954 void SetSelectedVehicles(int drag_x)
956 drag_x = GetClickPosition(drag_x);
958 int left_x = std::min(this->click_x, drag_x);
959 int right_x = std::max(this->click_x, drag_x);
960 this->num_vehicles = 0;
962 Vehicle *v = Vehicle::Get(this->window_number);
963 /* Find the vehicle part that was clicked. */
964 switch (v->type) {
965 case VEH_TRAIN: {
966 /* Don't select anything if we are not clicking in the vehicle. */
967 if (left_x >= 0) {
968 const Train *u = Train::From(v);
969 bool start_counting = false;
970 for (; u != nullptr; u = u->Next()) {
971 int current_width = u->GetDisplayImageWidth();
972 left_x -= current_width;
973 right_x -= current_width;
975 if (left_x < 0 && !start_counting) {
976 this->selected_vehicle = u->index;
977 start_counting = true;
979 /* Count the first vehicle, even if articulated part */
980 this->num_vehicles++;
981 } else if (start_counting && !u->IsArticulatedPart()) {
982 /* Do not count articulated parts */
983 this->num_vehicles++;
986 if (right_x < 0) break;
990 /* If the selection is not correct, clear it. */
991 if (this->num_vehicles != 0) {
992 if (_ctrl_pressed) this->num_vehicles = UINT8_MAX;
993 break;
995 FALLTHROUGH;
998 default:
999 /* Clear the selection. */
1000 this->selected_vehicle = v->index;
1001 this->num_vehicles = UINT8_MAX;
1002 break;
1006 void OnClick(Point pt, int widget, int click_count) override
1008 switch (widget) {
1009 case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
1010 if (this->order != INVALID_VEH_ORDER_ID) break;
1011 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
1012 this->click_x = GetClickPosition(pt.x - nwi->pos_x);
1013 this->SetSelectedVehicles(pt.x - nwi->pos_x);
1014 this->SetWidgetDirty(WID_VR_VEHICLE_PANEL_DISPLAY);
1015 if (!_ctrl_pressed) {
1016 SetObjectToPlaceWnd(SPR_CURSOR_MOUSE, PAL_NONE, HT_DRAG, this);
1017 } else {
1018 /* The vehicle selection has changed. */
1019 this->InvalidateData(2);
1021 break;
1024 case WID_VR_MATRIX: { // listbox
1025 this->SetSelection(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_VR_MATRIX));
1026 this->SetWidgetDisabledState(WID_VR_REFIT, this->sel[0] < 0);
1027 this->InvalidateData(1);
1029 if (click_count == 1) break;
1030 FALLTHROUGH;
1033 case WID_VR_REFIT: // refit button
1034 if (this->cargo != nullptr) {
1035 const Vehicle *v = Vehicle::Get(this->window_number);
1037 if (this->order == INVALID_VEH_ORDER_ID) {
1038 bool delete_window = this->selected_vehicle == v->index && this->num_vehicles == UINT8_MAX;
1039 if (Command<CMD_REFIT_VEHICLE>::Post(GetCmdRefitVehMsg(v), v->tile, this->selected_vehicle, this->cargo->cargo, this->cargo->subtype, false, false, this->num_vehicles) && delete_window) this->Close();
1040 } else {
1041 if (Command<CMD_ORDER_REFIT>::Post(v->tile, v->index, this->order, this->cargo->cargo)) this->Close();
1044 break;
1048 void OnMouseDrag(Point pt, int widget) override
1050 switch (widget) {
1051 case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
1052 if (this->order != INVALID_VEH_ORDER_ID) break;
1053 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
1054 this->SetSelectedVehicles(pt.x - nwi->pos_x);
1055 this->SetWidgetDirty(WID_VR_VEHICLE_PANEL_DISPLAY);
1056 break;
1061 void OnDragDrop(Point pt, int widget) override
1063 switch (widget) {
1064 case WID_VR_VEHICLE_PANEL_DISPLAY: { // Vehicle image.
1065 if (this->order != INVALID_VEH_ORDER_ID) break;
1066 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_VR_VEHICLE_PANEL_DISPLAY);
1067 this->SetSelectedVehicles(pt.x - nwi->pos_x);
1068 this->InvalidateData(2);
1069 break;
1074 void OnResize() override
1076 this->vehicle_width = GetVehicleWidth(Vehicle::Get(this->window_number), EIT_IN_DETAILS);
1077 this->vscroll->SetCapacityFromWidget(this, WID_VR_MATRIX);
1078 if (this->hscroll != nullptr) this->hscroll->SetCapacityFromWidget(this, WID_VR_VEHICLE_PANEL_DISPLAY);
1082 static const NWidgetPart _nested_vehicle_refit_widgets[] = {
1083 NWidget(NWID_HORIZONTAL),
1084 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1085 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VR_CAPTION), SetDataTip(STR_REFIT_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1086 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
1087 EndContainer(),
1088 /* Vehicle display + scrollbar. */
1089 NWidget(NWID_VERTICAL),
1090 NWidget(WWT_PANEL, COLOUR_GREY, WID_VR_VEHICLE_PANEL_DISPLAY), SetMinimalSize(228, 14), SetResize(1, 0), SetScrollbar(WID_VR_HSCROLLBAR), EndContainer(),
1091 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VR_SHOW_HSCROLLBAR),
1092 NWidget(NWID_HSCROLLBAR, COLOUR_GREY, WID_VR_HSCROLLBAR),
1093 EndContainer(),
1094 EndContainer(),
1095 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_VR_SELECT_HEADER), SetDataTip(STR_REFIT_TITLE, STR_NULL), SetResize(1, 0),
1096 /* Matrix + scrollbar. */
1097 NWidget(NWID_HORIZONTAL),
1098 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),
1099 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VR_SCROLLBAR),
1100 EndContainer(),
1101 NWidget(WWT_PANEL, COLOUR_GREY, WID_VR_INFO), SetMinimalTextLines(2, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM), SetResize(1, 0), EndContainer(),
1102 NWidget(NWID_HORIZONTAL),
1103 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VR_REFIT), SetFill(1, 0), SetResize(1, 0),
1104 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
1105 EndContainer(),
1108 static WindowDesc _vehicle_refit_desc(
1109 WDP_AUTO, "view_vehicle_refit", 240, 174,
1110 WC_VEHICLE_REFIT, WC_VEHICLE_VIEW,
1111 WDF_CONSTRUCTION,
1112 _nested_vehicle_refit_widgets, lengthof(_nested_vehicle_refit_widgets)
1116 * Show the refit window for a vehicle
1117 * @param *v The vehicle to show the refit window for
1118 * @param order of the vehicle to assign refit to, or INVALID_VEH_ORDER_ID to refit the vehicle now
1119 * @param parent the parent window of the refit window
1120 * @param auto_refit Choose cargo for auto-refitting
1122 void ShowVehicleRefitWindow(const Vehicle *v, VehicleOrderID order, Window *parent, bool auto_refit)
1124 CloseWindowById(WC_VEHICLE_REFIT, v->index);
1125 RefitWindow *w = new RefitWindow(&_vehicle_refit_desc, v, order, auto_refit);
1126 w->parent = parent;
1129 /** Display list of cargo types of the engine, for the purchase information window */
1130 uint ShowRefitOptionsList(int left, int right, int y, EngineID engine)
1132 /* List of cargo types of this engine */
1133 CargoTypes cmask = GetUnionOfArticulatedRefitMasks(engine, false);
1134 /* List of cargo types available in this climate */
1135 CargoTypes lmask = _cargo_mask;
1137 /* Draw nothing if the engine is not refittable */
1138 if (HasAtMostOneBit(cmask)) return y;
1140 if (cmask == lmask) {
1141 /* Engine can be refitted to all types in this climate */
1142 SetDParam(0, STR_PURCHASE_INFO_ALL_TYPES);
1143 } else {
1144 /* Check if we are able to refit to more cargo types and unable to. If
1145 * so, invert the cargo types to list those that we can't refit to. */
1146 if (CountBits(cmask ^ lmask) < CountBits(cmask) && CountBits(cmask ^ lmask) <= 7) {
1147 cmask ^= lmask;
1148 SetDParam(0, STR_PURCHASE_INFO_ALL_BUT);
1149 } else {
1150 SetDParam(0, STR_JUST_CARGO_LIST);
1152 SetDParam(1, cmask);
1155 return DrawStringMultiLine(left, right, y, INT32_MAX, STR_PURCHASE_INFO_REFITTABLE_TO);
1158 /** Get the cargo subtype text from NewGRF for the vehicle details window. */
1159 StringID GetCargoSubtypeText(const Vehicle *v)
1161 if (HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_CARGO_SUFFIX)) {
1162 uint16 cb = GetVehicleCallback(CBID_VEHICLE_CARGO_SUFFIX, 0, 0, v->engine_type, v);
1163 if (cb != CALLBACK_FAILED) {
1164 if (cb > 0x400) ErrorUnknownCallbackResult(v->GetGRFID(), CBID_VEHICLE_CARGO_SUFFIX, cb);
1165 if (cb >= 0x400 || (v->GetGRF()->grf_version < 8 && cb == 0xFF)) cb = CALLBACK_FAILED;
1167 if (cb != CALLBACK_FAILED) {
1168 return GetGRFStringID(v->GetGRFID(), 0xD000 + cb);
1171 return STR_EMPTY;
1174 /** Sort vehicle groups by the number of vehicles in the group */
1175 static bool VehicleGroupLengthSorter(const GUIVehicleGroup &a, const GUIVehicleGroup &b)
1177 return a.NumVehicles() < b.NumVehicles();
1180 /** Sort vehicle groups by the total profit this year */
1181 static bool VehicleGroupTotalProfitThisYearSorter(const GUIVehicleGroup &a, const GUIVehicleGroup &b)
1183 return a.GetDisplayProfitThisYear() < b.GetDisplayProfitThisYear();
1186 /** Sort vehicle groups by the total profit last year */
1187 static bool VehicleGroupTotalProfitLastYearSorter(const GUIVehicleGroup &a, const GUIVehicleGroup &b)
1189 return a.GetDisplayProfitLastYear() < b.GetDisplayProfitLastYear();
1192 /** Sort vehicle groups by the average profit this year */
1193 static bool VehicleGroupAverageProfitThisYearSorter(const GUIVehicleGroup &a, const GUIVehicleGroup &b)
1195 return a.GetDisplayProfitThisYear() * static_cast<uint>(b.NumVehicles()) < b.GetDisplayProfitThisYear() * static_cast<uint>(a.NumVehicles());
1198 /** Sort vehicle groups by the average profit last year */
1199 static bool VehicleGroupAverageProfitLastYearSorter(const GUIVehicleGroup &a, const GUIVehicleGroup &b)
1201 return a.GetDisplayProfitLastYear() * static_cast<uint>(b.NumVehicles()) < b.GetDisplayProfitLastYear() * static_cast<uint>(a.NumVehicles());
1204 /** Sort vehicles by their number */
1205 static bool VehicleNumberSorter(const Vehicle * const &a, const Vehicle * const &b)
1207 return a->unitnumber < b->unitnumber;
1210 /** Sort vehicles by their name */
1211 static bool VehicleNameSorter(const Vehicle * const &a, const Vehicle * const &b)
1213 static char last_name[2][64];
1215 if (a != _last_vehicle[0]) {
1216 _last_vehicle[0] = a;
1217 SetDParam(0, a->index);
1218 GetString(last_name[0], STR_VEHICLE_NAME, lastof(last_name[0]));
1221 if (b != _last_vehicle[1]) {
1222 _last_vehicle[1] = b;
1223 SetDParam(0, b->index);
1224 GetString(last_name[1], STR_VEHICLE_NAME, lastof(last_name[1]));
1227 int r = strnatcmp(last_name[0], last_name[1]); // Sort by name (natural sorting).
1228 return (r != 0) ? r < 0: VehicleNumberSorter(a, b);
1231 /** Sort vehicles by their age */
1232 static bool VehicleAgeSorter(const Vehicle * const &a, const Vehicle * const &b)
1234 int r = a->age - b->age;
1235 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1238 /** Sort vehicles by this year profit */
1239 static bool VehicleProfitThisYearSorter(const Vehicle * const &a, const Vehicle * const &b)
1241 int r = ClampToI32(a->GetDisplayProfitThisYear() - b->GetDisplayProfitThisYear());
1242 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1245 /** Sort vehicles by last year profit */
1246 static bool VehicleProfitLastYearSorter(const Vehicle * const &a, const Vehicle * const &b)
1248 int r = ClampToI32(a->GetDisplayProfitLastYear() - b->GetDisplayProfitLastYear());
1249 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1252 /** Sort vehicles by their cargo */
1253 static bool VehicleCargoSorter(const Vehicle * const &a, const Vehicle * const &b)
1255 const Vehicle *v;
1256 CargoArray diff;
1258 /* Append the cargo of the connected waggons */
1259 for (v = a; v != nullptr; v = v->Next()) diff[v->cargo_type] += v->cargo_cap;
1260 for (v = b; v != nullptr; v = v->Next()) diff[v->cargo_type] -= v->cargo_cap;
1262 int r = 0;
1263 for (CargoID i = 0; i < NUM_CARGO; i++) {
1264 r = diff[i];
1265 if (r != 0) break;
1268 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1271 /** Sort vehicles by their reliability */
1272 static bool VehicleReliabilitySorter(const Vehicle * const &a, const Vehicle * const &b)
1274 int r = a->reliability - b->reliability;
1275 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1278 /** Sort vehicles by their max speed */
1279 static bool VehicleMaxSpeedSorter(const Vehicle * const &a, const Vehicle * const &b)
1281 int r = a->vcache.cached_max_speed - b->vcache.cached_max_speed;
1282 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1285 /** Sort vehicles by model */
1286 static bool VehicleModelSorter(const Vehicle * const &a, const Vehicle * const &b)
1288 int r = a->engine_type - b->engine_type;
1289 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1292 /** Sort vehicles by their value */
1293 static bool VehicleValueSorter(const Vehicle * const &a, const Vehicle * const &b)
1295 const Vehicle *u;
1296 Money diff = 0;
1298 for (u = a; u != nullptr; u = u->Next()) diff += u->value;
1299 for (u = b; u != nullptr; u = u->Next()) diff -= u->value;
1301 int r = ClampToI32(diff);
1302 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1305 /** Sort vehicles by their length */
1306 static bool VehicleLengthSorter(const Vehicle * const &a, const Vehicle * const &b)
1308 int r = a->GetGroundVehicleCache()->cached_total_length - b->GetGroundVehicleCache()->cached_total_length;
1309 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1312 /** Sort vehicles by the time they can still live */
1313 static bool VehicleTimeToLiveSorter(const Vehicle * const &a, const Vehicle * const &b)
1315 int r = ClampToI32((a->max_age - a->age) - (b->max_age - b->age));
1316 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1319 /** Sort vehicles by the timetable delay */
1320 static bool VehicleTimetableDelaySorter(const Vehicle * const &a, const Vehicle * const &b)
1322 int r = a->lateness_counter - b->lateness_counter;
1323 return (r != 0) ? r < 0 : VehicleNumberSorter(a, b);
1326 void InitializeGUI()
1328 MemSetT(&_grouping, 0);
1329 MemSetT(&_sorting, 0);
1333 * Assign a vehicle window a new vehicle
1334 * @param window_class WindowClass to search for
1335 * @param from_index the old vehicle ID
1336 * @param to_index the new vehicle ID
1338 static inline void ChangeVehicleWindow(WindowClass window_class, VehicleID from_index, VehicleID to_index)
1340 Window *w = FindWindowById(window_class, from_index);
1341 if (w != nullptr) {
1342 /* Update window_number */
1343 w->window_number = to_index;
1344 if (w->viewport != nullptr) w->viewport->follow_vehicle = to_index;
1346 /* Update vehicle drag data */
1347 if (_thd.window_class == window_class && _thd.window_number == (WindowNumber)from_index) {
1348 _thd.window_number = to_index;
1351 /* Notify the window. */
1352 w->InvalidateData(VIWD_AUTOREPLACE, false);
1357 * Report a change in vehicle IDs (due to autoreplace) to affected vehicle windows.
1358 * @param from_index the old vehicle ID
1359 * @param to_index the new vehicle ID
1361 void ChangeVehicleViewWindow(VehicleID from_index, VehicleID to_index)
1363 ChangeVehicleWindow(WC_VEHICLE_VIEW, from_index, to_index);
1364 ChangeVehicleWindow(WC_VEHICLE_ORDERS, from_index, to_index);
1365 ChangeVehicleWindow(WC_VEHICLE_REFIT, from_index, to_index);
1366 ChangeVehicleWindow(WC_VEHICLE_DETAILS, from_index, to_index);
1367 ChangeVehicleWindow(WC_VEHICLE_TIMETABLE, from_index, to_index);
1370 static const NWidgetPart _nested_vehicle_list[] = {
1371 NWidget(NWID_HORIZONTAL),
1372 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1373 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VL_CAPTION_SELECTION),
1374 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VL_CAPTION),
1375 NWidget(NWID_HORIZONTAL),
1376 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VL_CAPTION_SHARED_ORDERS),
1377 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VL_ORDER_VIEW), SetMinimalSize(61, 14), SetDataTip(STR_GOTO_ORDER_VIEW, STR_GOTO_ORDER_VIEW_TOOLTIP),
1378 EndContainer(),
1379 EndContainer(),
1380 NWidget(WWT_SHADEBOX, COLOUR_GREY),
1381 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
1382 NWidget(WWT_STICKYBOX, COLOUR_GREY),
1383 EndContainer(),
1385 NWidget(NWID_HORIZONTAL),
1386 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_VL_GROUP_ORDER), SetMinimalSize(81, 12), SetFill(0, 1), SetDataTip(STR_STATION_VIEW_GROUP, STR_TOOLTIP_GROUP_ORDER),
1387 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_GROUP_BY_PULLDOWN), SetMinimalSize(167, 12), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_GROUP_ORDER),
1388 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(12, 12), SetFill(1, 1), SetResize(1, 0), EndContainer(),
1389 EndContainer(),
1391 NWidget(NWID_HORIZONTAL),
1392 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VL_SORT_ORDER), SetMinimalSize(81, 12), SetFill(0, 1), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
1393 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_SORT_BY_PULLDOWN), SetMinimalSize(167, 12), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
1394 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(12, 12), SetFill(1, 1), SetResize(1, 0), EndContainer(),
1395 EndContainer(),
1397 NWidget(NWID_HORIZONTAL),
1398 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),
1399 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VL_SCROLLBAR),
1400 EndContainer(),
1402 NWidget(NWID_HORIZONTAL),
1403 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VL_HIDE_BUTTONS),
1404 NWidget(NWID_HORIZONTAL),
1405 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VL_AVAILABLE_VEHICLES), SetMinimalSize(106, 12), SetFill(0, 1),
1406 SetDataTip(STR_BLACK_STRING, STR_VEHICLE_LIST_AVAILABLE_ENGINES_TOOLTIP),
1407 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(0, 12), SetResize(1, 0), SetFill(1, 1), EndContainer(),
1408 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VL_MANAGE_VEHICLES_DROPDOWN), SetMinimalSize(118, 12), SetFill(0, 1),
1409 SetDataTip(STR_VEHICLE_LIST_MANAGE_LIST, STR_VEHICLE_LIST_MANAGE_LIST_TOOLTIP),
1410 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VL_STOP_ALL), SetMinimalSize(12, 12), SetFill(0, 1),
1411 SetDataTip(SPR_FLAG_VEH_STOPPED, STR_VEHICLE_LIST_MASS_STOP_LIST_TOOLTIP),
1412 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VL_START_ALL), SetMinimalSize(12, 12), SetFill(0, 1),
1413 SetDataTip(SPR_FLAG_VEH_RUNNING, STR_VEHICLE_LIST_MASS_START_LIST_TOOLTIP),
1414 EndContainer(),
1415 /* Widget to be shown for other companies hiding the previous 5 widgets. */
1416 NWidget(WWT_PANEL, COLOUR_GREY), SetFill(1, 1), SetResize(1, 0), EndContainer(),
1417 EndContainer(),
1418 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
1419 EndContainer(),
1422 static void DrawSmallOrderList(const Vehicle *v, int left, int right, int y, uint order_arrow_width, VehicleOrderID start)
1424 const Order *order = v->GetOrder(start);
1425 if (order == nullptr) return;
1427 bool rtl = _current_text_dir == TD_RTL;
1428 int l_offset = rtl ? 0 : order_arrow_width;
1429 int r_offset = rtl ? order_arrow_width : 0;
1430 int i = 0;
1431 VehicleOrderID oid = start;
1433 do {
1434 if (oid == v->cur_real_order_index) DrawString(left, right, y, STR_TINY_RIGHT_ARROW, TC_BLACK);
1436 if (order->IsType(OT_GOTO_STATION)) {
1437 SetDParam(0, order->GetDestination());
1438 DrawString(left + l_offset, right - r_offset, y, STR_TINY_BLACK_STATION);
1440 y += FONT_HEIGHT_SMALL;
1441 if (++i == 4) break;
1444 oid++;
1445 order = order->next;
1446 if (order == nullptr) {
1447 order = v->orders->GetFirstOrder();
1448 oid = 0;
1450 } while (oid != start);
1453 /** Draw small order list in the vehicle GUI, but without the little black arrow. This is used for shared order groups. */
1454 static void DrawSmallOrderList(const Order *order, int left, int right, int y, uint order_arrow_width)
1456 bool rtl = _current_text_dir == TD_RTL;
1457 int l_offset = rtl ? 0 : order_arrow_width;
1458 int r_offset = rtl ? order_arrow_width : 0;
1459 int i = 0;
1460 while (order != nullptr) {
1461 if (order->IsType(OT_GOTO_STATION)) {
1462 SetDParam(0, order->GetDestination());
1463 DrawString(left + l_offset, right - r_offset, y, STR_TINY_BLACK_STATION);
1465 y += FONT_HEIGHT_SMALL;
1466 if (++i == 4) break;
1468 order = order->next;
1473 * Draws an image of a vehicle chain
1474 * @param v Front vehicle
1475 * @param left The minimum horizontal position
1476 * @param right The maximum horizontal position
1477 * @param y Vertical position to draw at
1478 * @param selection Selected vehicle to draw a frame around
1479 * @param skip Number of pixels to skip at the front (for scrolling)
1481 void DrawVehicleImage(const Vehicle *v, int left, int right, int y, VehicleID selection, EngineImageType image_type, int skip)
1483 switch (v->type) {
1484 case VEH_TRAIN: DrawTrainImage(Train::From(v), left, right, y, selection, image_type, skip); break;
1485 case VEH_ROAD: DrawRoadVehImage(v, left, right, y, selection, image_type, skip); break;
1486 case VEH_SHIP: DrawShipImage(v, left, right, y, selection, image_type); break;
1487 case VEH_AIRCRAFT: DrawAircraftImage(v, left, right, y, selection, image_type); break;
1488 default: NOT_REACHED();
1493 * Get the height of a vehicle in the vehicle list GUIs.
1494 * @param type the vehicle type to look at
1495 * @param divisor the resulting height must be dividable by this
1496 * @return the height
1498 uint GetVehicleListHeight(VehicleType type, uint divisor)
1500 /* Name + vehicle + profit */
1501 uint base = ScaleGUITrad(GetVehicleHeight(type)) + 2 * FONT_HEIGHT_SMALL;
1502 /* Drawing of the 4 small orders + profit*/
1503 if (type >= VEH_SHIP) base = std::max(base, 5U * FONT_HEIGHT_SMALL);
1505 if (divisor == 1) return base;
1507 /* Make sure the height is dividable by divisor */
1508 uint rem = base % divisor;
1509 return base + (rem == 0 ? 0 : divisor - rem);
1513 * Draw all the vehicle list items.
1514 * @param selected_vehicle The vehicle that is to be highlighted.
1515 * @param line_height Height of a single item line.
1516 * @param r Rectangle with edge positions of the matrix widget.
1518 void BaseVehicleListWindow::DrawVehicleListItems(VehicleID selected_vehicle, int line_height, const Rect &r) const
1520 int left = r.left + WD_MATRIX_LEFT;
1521 int right = r.right - WD_MATRIX_RIGHT;
1522 int width = right - left;
1523 bool rtl = _current_text_dir == TD_RTL;
1525 int text_offset = std::max<int>(GetSpriteSize(SPR_PROFIT_LOT).width, GetDigitWidth() * this->unitnumber_digits) + WD_FRAMERECT_RIGHT;
1526 int text_left = left + (rtl ? 0 : text_offset);
1527 int text_right = right - (rtl ? text_offset : 0);
1529 bool show_orderlist = this->vli.vtype >= VEH_SHIP;
1530 int orderlist_left = left + (rtl ? 0 : std::max(ScaleGUITrad(100) + text_offset, width / 2));
1531 int orderlist_right = right - (rtl ? std::max(ScaleGUITrad(100) + text_offset, width / 2) : 0);
1533 int image_left = (rtl && show_orderlist) ? orderlist_right : text_left;
1534 int image_right = (!rtl && show_orderlist) ? orderlist_left : text_right;
1536 int vehicle_button_x = rtl ? right - GetSpriteSize(SPR_PROFIT_LOT).width : left;
1538 int y = r.top;
1539 uint max = static_cast<uint>(std::min<size_t>(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->vehgroups.size()));
1540 for (uint i = this->vscroll->GetPosition(); i < max; ++i) {
1542 const GUIVehicleGroup &vehgroup = this->vehgroups[i];
1544 SetDParam(0, vehgroup.GetDisplayProfitThisYear());
1545 SetDParam(1, vehgroup.GetDisplayProfitLastYear());
1546 DrawString(text_left, text_right, y + line_height - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1, STR_VEHICLE_LIST_PROFIT_THIS_YEAR_LAST_YEAR);
1548 DrawVehicleProfitButton(vehgroup.GetOldestVehicleAge(), vehgroup.GetDisplayProfitLastYear(), vehgroup.NumVehicles(), vehicle_button_x, y + FONT_HEIGHT_NORMAL + 3);
1550 switch (this->grouping) {
1551 case GB_NONE: {
1552 const Vehicle *v = vehgroup.GetSingleVehicle();
1554 if (HasBit(v->vehicle_flags, VF_PATHFINDER_LOST)) {
1555 DrawSprite(SPR_WARNING_SIGN, PAL_NONE, vehicle_button_x, y + FONT_HEIGHT_NORMAL + 3 + GetSpriteSize(SPR_PROFIT_LOT).height);
1558 DrawVehicleImage(v, image_left, image_right, y + FONT_HEIGHT_SMALL - 1, selected_vehicle, EIT_IN_LIST, 0);
1560 if (!v->name.empty()) {
1561 /* The vehicle got a name so we will print it */
1562 SetDParam(0, v->index);
1563 DrawString(text_left, text_right, y, STR_TINY_BLACK_VEHICLE);
1564 } else if (v->group_id != DEFAULT_GROUP) {
1565 /* The vehicle has no name, but is member of a group, so print group name */
1566 SetDParam(0, v->group_id);
1567 DrawString(text_left, text_right, y, STR_TINY_GROUP, TC_BLACK);
1570 if (show_orderlist) DrawSmallOrderList(v, orderlist_left, orderlist_right, y, this->order_arrow_width, v->cur_real_order_index);
1572 StringID str;
1573 if (v->IsChainInDepot()) {
1574 str = STR_BLUE_COMMA;
1575 } else {
1576 str = (v->age > v->max_age - DAYS_IN_LEAP_YEAR) ? STR_RED_COMMA : STR_BLACK_COMMA;
1579 SetDParam(0, v->unitnumber);
1580 DrawString(left, right, y + 2, str);
1581 break;
1584 case GB_SHARED_ORDERS:
1585 assert(vehgroup.NumVehicles() > 0);
1587 for (int i = 0; i < static_cast<int>(vehgroup.NumVehicles()); ++i) {
1588 if (image_left + 8 * i >= image_right) break; // Break if there is no more space to draw any more vehicles anyway.
1589 DrawVehicleImage(vehgroup.vehicles_begin[i], image_left + 8 * i, image_right, y + FONT_HEIGHT_SMALL - 1, selected_vehicle, EIT_IN_LIST, 0);
1592 if (show_orderlist) DrawSmallOrderList((vehgroup.vehicles_begin[0])->GetFirstOrder(), orderlist_left, orderlist_right, y, this->order_arrow_width);
1594 SetDParam(0, vehgroup.NumVehicles());
1595 DrawString(left, right, y + 2, STR_BLACK_COMMA);
1596 break;
1598 default:
1599 NOT_REACHED();
1602 y += line_height;
1606 void BaseVehicleListWindow::UpdateSortingFromGrouping()
1608 /* Set up sorting. Make the window-specific _sorting variable
1609 * point to the correct global _sorting struct so we are freed
1610 * from having conditionals during window operation */
1611 switch (this->vli.vtype) {
1612 case VEH_TRAIN: this->sorting = &_sorting[this->grouping].train; break;
1613 case VEH_ROAD: this->sorting = &_sorting[this->grouping].roadveh; break;
1614 case VEH_SHIP: this->sorting = &_sorting[this->grouping].ship; break;
1615 case VEH_AIRCRAFT: this->sorting = &_sorting[this->grouping].aircraft; break;
1616 default: NOT_REACHED();
1618 this->vehgroups.SetSortFuncs(this->GetVehicleSorterFuncs());
1619 this->vehgroups.SetListing(*this->sorting);
1620 this->vehgroups.ForceRebuild();
1621 this->vehgroups.NeedResort();
1624 void BaseVehicleListWindow::UpdateVehicleGroupBy(GroupBy group_by)
1626 if (this->grouping != group_by) {
1627 /* Save the old sorting option, so that if we change the grouping option back later on,
1628 * UpdateSortingFromGrouping() will automatically restore the saved sorting option. */
1629 *this->sorting = this->vehgroups.GetListing();
1631 this->grouping = group_by;
1632 _grouping[this->vli.type][this->vli.vtype] = group_by;
1633 this->UpdateSortingFromGrouping();
1638 * Window for the (old) vehicle listing.
1640 * bitmask for w->window_number
1641 * 0-7 CompanyID (owner)
1642 * 8-10 window type (use flags in vehicle_gui.h)
1643 * 11-15 vehicle type (using VEH_, but can be compressed to fewer bytes if needed)
1644 * 16-31 StationID or OrderID depending on window type (bit 8-10)
1646 struct VehicleListWindow : public BaseVehicleListWindow {
1647 private:
1648 /** Enumeration of planes of the button row at the bottom. */
1649 enum ButtonPlanes {
1650 BP_SHOW_BUTTONS, ///< Show the buttons.
1651 BP_HIDE_BUTTONS, ///< Show the empty panel.
1654 /** Enumeration of planes of the title row at the top. */
1655 enum CaptionPlanes {
1656 BP_NORMAL, ///< Show shared orders caption and buttons.
1657 BP_SHARED_ORDERS, ///< Show the normal caption.
1660 public:
1661 VehicleListWindow(WindowDesc *desc, WindowNumber window_number) : BaseVehicleListWindow(desc, window_number)
1663 this->CreateNestedTree();
1665 this->vscroll = this->GetScrollbar(WID_VL_SCROLLBAR);
1667 this->BuildVehicleList();
1668 this->SortVehicleList();
1670 /* Set up the window widgets */
1671 this->GetWidget<NWidgetCore>(WID_VL_LIST)->tool_tip = STR_VEHICLE_LIST_TRAIN_LIST_TOOLTIP + this->vli.vtype;
1673 NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VL_CAPTION_SELECTION);
1674 if (this->vli.type == VL_SHARED_ORDERS) {
1675 this->GetWidget<NWidgetCore>(WID_VL_CAPTION_SHARED_ORDERS)->widget_data = STR_VEHICLE_LIST_SHARED_ORDERS_LIST_CAPTION;
1676 /* If we are in the shared orders window, then disable the group-by dropdown menu.
1677 * Remove this when the group-by dropdown menu has another option apart from grouping by shared orders. */
1678 this->SetWidgetDisabledState(WID_VL_GROUP_ORDER, true);
1679 this->SetWidgetDisabledState(WID_VL_GROUP_BY_PULLDOWN, true);
1680 nwi->SetDisplayedPlane(BP_SHARED_ORDERS);
1681 } else {
1682 this->GetWidget<NWidgetCore>(WID_VL_CAPTION)->widget_data = STR_VEHICLE_LIST_TRAIN_CAPTION + this->vli.vtype;
1683 nwi->SetDisplayedPlane(BP_NORMAL);
1686 this->FinishInitNested(window_number);
1687 if (this->vli.company != OWNER_NONE) this->owner = this->vli.company;
1690 ~VehicleListWindow()
1692 *this->sorting = this->vehgroups.GetListing();
1695 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
1697 switch (widget) {
1698 case WID_VL_LIST:
1699 resize->height = GetVehicleListHeight(this->vli.vtype, 1);
1701 switch (this->vli.vtype) {
1702 case VEH_TRAIN:
1703 case VEH_ROAD:
1704 size->height = 6 * resize->height;
1705 break;
1706 case VEH_SHIP:
1707 case VEH_AIRCRAFT:
1708 size->height = 4 * resize->height;
1709 break;
1710 default: NOT_REACHED();
1712 break;
1714 case WID_VL_SORT_ORDER: {
1715 Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
1716 d.width += padding.width + Window::SortButtonWidth() * 2; // Doubled since the string is centred and it also looks better.
1717 d.height += padding.height;
1718 *size = maxdim(*size, d);
1719 break;
1722 case WID_VL_MANAGE_VEHICLES_DROPDOWN: {
1723 Dimension d = this->GetActionDropdownSize(this->vli.type == VL_STANDARD, false);
1724 d.height += padding.height;
1725 d.width += padding.width;
1726 *size = maxdim(*size, d);
1727 break;
1732 void SetStringParameters(int widget) const override
1734 switch (widget) {
1735 case WID_VL_AVAILABLE_VEHICLES:
1736 SetDParam(0, STR_VEHICLE_LIST_AVAILABLE_TRAINS + this->vli.vtype);
1737 break;
1739 case WID_VL_CAPTION:
1740 case WID_VL_CAPTION_SHARED_ORDERS: {
1741 switch (this->vli.type) {
1742 case VL_SHARED_ORDERS: // Shared Orders
1743 if (this->vehicles.size() == 0) {
1744 /* We can't open this window without vehicles using this order
1745 * and we should close the window when deleting the order. */
1746 NOT_REACHED();
1748 SetDParam(0, this->vehicles.size());
1749 break;
1751 case VL_STANDARD: // Company Name
1752 SetDParam(0, STR_COMPANY_NAME);
1753 SetDParam(1, this->vli.index);
1754 SetDParam(3, this->vehicles.size());
1755 break;
1757 case VL_STATION_LIST: // Station/Waypoint Name
1758 SetDParam(0, Station::IsExpected(BaseStation::Get(this->vli.index)) ? STR_STATION_NAME : STR_WAYPOINT_NAME);
1759 SetDParam(1, this->vli.index);
1760 SetDParam(3, this->vehicles.size());
1761 break;
1763 case VL_DEPOT_LIST:
1764 SetDParam(0, STR_DEPOT_CAPTION);
1765 SetDParam(1, this->vli.vtype);
1766 SetDParam(2, this->vli.index);
1767 SetDParam(3, this->vehicles.size());
1768 break;
1769 default: NOT_REACHED();
1771 break;
1776 void DrawWidget(const Rect &r, int widget) const override
1778 switch (widget) {
1779 case WID_VL_SORT_ORDER:
1780 /* draw arrow pointing up/down for ascending/descending sorting */
1781 this->DrawSortButtonState(widget, this->vehgroups.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
1782 break;
1784 case WID_VL_LIST:
1785 this->DrawVehicleListItems(INVALID_VEHICLE, this->resize.step_height, r);
1786 break;
1790 void OnPaint() override
1792 this->BuildVehicleList();
1793 this->SortVehicleList();
1795 if (this->vehicles.size() == 0 && this->IsWidgetLowered(WID_VL_MANAGE_VEHICLES_DROPDOWN)) {
1796 HideDropDownMenu(this);
1799 /* Hide the widgets that we will not use in this window
1800 * Some windows contains actions only fit for the owner */
1801 int plane_to_show = (this->owner == _local_company) ? BP_SHOW_BUTTONS : BP_HIDE_BUTTONS;
1802 NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VL_HIDE_BUTTONS);
1803 if (plane_to_show != nwi->shown_plane) {
1804 nwi->SetDisplayedPlane(plane_to_show);
1805 nwi->SetDirty(this);
1807 if (this->owner == _local_company) {
1808 this->SetWidgetDisabledState(WID_VL_AVAILABLE_VEHICLES, this->vli.type != VL_STANDARD);
1809 this->SetWidgetsDisabledState(this->vehicles.size() == 0,
1810 WID_VL_MANAGE_VEHICLES_DROPDOWN,
1811 WID_VL_STOP_ALL,
1812 WID_VL_START_ALL,
1813 WIDGET_LIST_END);
1816 /* Set text of group by dropdown widget. */
1817 this->GetWidget<NWidgetCore>(WID_VL_GROUP_BY_PULLDOWN)->widget_data = this->vehicle_group_by_names[this->grouping];
1819 /* Set text of sort by dropdown widget. */
1820 this->GetWidget<NWidgetCore>(WID_VL_SORT_BY_PULLDOWN)->widget_data = this->GetVehicleSorterNames()[this->vehgroups.SortType()];
1822 this->DrawWidgets();
1825 void OnClick(Point pt, int widget, int click_count) override
1827 switch (widget) {
1828 case WID_VL_ORDER_VIEW: // Open the shared orders window
1829 assert(this->vli.type == VL_SHARED_ORDERS);
1830 assert(!this->vehicles.empty());
1831 ShowOrdersWindow(this->vehicles[0]);
1832 break;
1834 case WID_VL_SORT_ORDER: // Flip sorting method ascending/descending
1835 this->vehgroups.ToggleSortOrder();
1836 this->SetDirty();
1837 break;
1839 case WID_VL_GROUP_BY_PULLDOWN: // Select sorting criteria dropdown menu
1840 ShowDropDownMenu(this, this->vehicle_group_by_names, this->grouping, WID_VL_GROUP_BY_PULLDOWN, 0, 0);
1841 return;
1843 case WID_VL_SORT_BY_PULLDOWN: // Select sorting criteria dropdown menu
1844 ShowDropDownMenu(this, this->GetVehicleSorterNames(), this->vehgroups.SortType(), WID_VL_SORT_BY_PULLDOWN, 0,
1845 (this->vli.vtype == VEH_TRAIN || this->vli.vtype == VEH_ROAD) ? 0 : (1 << 10));
1846 return;
1848 case WID_VL_LIST: { // Matrix to show vehicles
1849 uint id_v = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_VL_LIST);
1850 if (id_v >= this->vehgroups.size()) return; // click out of list bound
1852 const GUIVehicleGroup &vehgroup = this->vehgroups[id_v];
1853 switch (this->grouping) {
1854 case GB_NONE: {
1855 const Vehicle *v = vehgroup.GetSingleVehicle();
1856 if (!VehicleClicked(v)) {
1857 if (_ctrl_pressed) {
1858 ShowCompanyGroupForVehicle(v);
1859 } else {
1860 ShowVehicleViewWindow(v);
1863 break;
1866 case GB_SHARED_ORDERS: {
1867 assert(vehgroup.NumVehicles() > 0);
1868 const Vehicle *v = vehgroup.vehicles_begin[0];
1869 /* We do not support VehicleClicked() here since the contextual action may only make sense for individual vehicles */
1871 if (_ctrl_pressed) {
1872 ShowOrdersWindow(v);
1873 } else {
1874 if (vehgroup.NumVehicles() == 1) {
1875 ShowVehicleViewWindow(v);
1876 } else {
1877 ShowVehicleListWindow(v);
1880 break;
1883 default: NOT_REACHED();
1886 break;
1889 case WID_VL_AVAILABLE_VEHICLES:
1890 ShowBuildVehicleWindow(INVALID_TILE, this->vli.vtype);
1891 break;
1893 case WID_VL_MANAGE_VEHICLES_DROPDOWN: {
1894 ShowDropDownList(this, this->BuildActionDropdownList(VehicleListIdentifier::UnPack(this->window_number).type == VL_STANDARD, false), 0, WID_VL_MANAGE_VEHICLES_DROPDOWN);
1895 break;
1898 case WID_VL_STOP_ALL:
1899 case WID_VL_START_ALL:
1900 Command<CMD_MASS_START_STOP>::Post(0, widget == WID_VL_START_ALL, true, this->vli);
1901 break;
1905 void OnDropdownSelect(int widget, int index) override
1907 switch (widget) {
1908 case WID_VL_GROUP_BY_PULLDOWN:
1909 this->UpdateVehicleGroupBy(static_cast<GroupBy>(index));
1910 break;
1912 case WID_VL_SORT_BY_PULLDOWN:
1913 this->vehgroups.SetSortType(index);
1914 break;
1916 case WID_VL_MANAGE_VEHICLES_DROPDOWN:
1917 assert(this->vehicles.size() != 0);
1919 switch (index) {
1920 case ADI_REPLACE: // Replace window
1921 ShowReplaceGroupVehicleWindow(ALL_GROUP, this->vli.vtype);
1922 break;
1923 case ADI_SERVICE: // Send for servicing
1924 case ADI_DEPOT: // Send to Depots
1925 Command<CMD_SEND_VEHICLE_TO_DEPOT>::Post(GetCmdSendToDepotMsg(this->vli.vtype), 0, DepotCommand::MassSend | (index == ADI_SERVICE ? DepotCommand::Service : DepotCommand::None), this->vli);
1926 break;
1928 default: NOT_REACHED();
1930 break;
1932 default: NOT_REACHED();
1934 this->SetDirty();
1937 void OnGameTick() override
1939 if (this->vehgroups.NeedResort()) {
1940 StationID station = (this->vli.type == VL_STATION_LIST) ? this->vli.index : INVALID_STATION;
1942 Debug(misc, 3, "Periodic resort {} list company {} at station {}", this->vli.vtype, this->owner, station);
1943 this->SetDirty();
1947 void OnResize() override
1949 this->vscroll->SetCapacityFromWidget(this, WID_VL_LIST);
1953 * Some data on this window has become invalid.
1954 * @param data Information about the changed data.
1955 * @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.
1957 void OnInvalidateData(int data = 0, bool gui_scope = true) override
1959 if (!gui_scope && HasBit(data, 31) && this->vli.type == VL_SHARED_ORDERS) {
1960 /* Needs to be done in command-scope, so everything stays valid */
1961 this->vli.index = GB(data, 0, 20);
1962 this->window_number = this->vli.Pack();
1963 this->vehgroups.ForceRebuild();
1964 return;
1967 if (data == 0) {
1968 /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
1969 this->vehgroups.ForceRebuild();
1970 } else {
1971 this->vehgroups.ForceResort();
1976 static WindowDesc _vehicle_list_other_desc(
1977 WDP_AUTO, "list_vehicles", 260, 246,
1978 WC_INVALID, WC_NONE,
1980 _nested_vehicle_list, lengthof(_nested_vehicle_list)
1983 static WindowDesc _vehicle_list_train_desc(
1984 WDP_AUTO, "list_vehicles_train", 325, 246,
1985 WC_TRAINS_LIST, WC_NONE,
1987 _nested_vehicle_list, lengthof(_nested_vehicle_list)
1990 static void ShowVehicleListWindowLocal(CompanyID company, VehicleListType vlt, VehicleType vehicle_type, uint32 unique_number)
1992 if (!Company::IsValidID(company) && company != OWNER_NONE) return;
1994 WindowNumber num = VehicleListIdentifier(vlt, vehicle_type, company, unique_number).Pack();
1995 if (vehicle_type == VEH_TRAIN) {
1996 AllocateWindowDescFront<VehicleListWindow>(&_vehicle_list_train_desc, num);
1997 } else {
1998 _vehicle_list_other_desc.cls = GetWindowClassForVehicleType(vehicle_type);
1999 AllocateWindowDescFront<VehicleListWindow>(&_vehicle_list_other_desc, num);
2003 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type)
2005 /* If _settings_client.gui.advanced_vehicle_list > 1, display the Advanced list
2006 * if _settings_client.gui.advanced_vehicle_list == 1, display Advanced list only for local company
2007 * if _ctrl_pressed, do the opposite action (Advanced list x Normal list)
2010 if ((_settings_client.gui.advanced_vehicle_list > (uint)(company != _local_company)) != _ctrl_pressed) {
2011 ShowCompanyGroup(company, vehicle_type);
2012 } else {
2013 ShowVehicleListWindowLocal(company, VL_STANDARD, vehicle_type, company);
2017 void ShowVehicleListWindow(const Vehicle *v)
2019 ShowVehicleListWindowLocal(v->owner, VL_SHARED_ORDERS, v->type, v->FirstShared()->index);
2022 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, StationID station)
2024 ShowVehicleListWindowLocal(company, VL_STATION_LIST, vehicle_type, station);
2027 void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, TileIndex depot_tile)
2029 uint16 depot_airport_index;
2031 if (vehicle_type == VEH_AIRCRAFT) {
2032 depot_airport_index = GetStationIndex(depot_tile);
2033 } else {
2034 depot_airport_index = GetDepotIndex(depot_tile);
2036 ShowVehicleListWindowLocal(company, VL_DEPOT_LIST, vehicle_type, depot_airport_index);
2040 /* Unified vehicle GUI - Vehicle Details Window */
2042 static_assert(WID_VD_DETAILS_CARGO_CARRIED == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_CARGO );
2043 static_assert(WID_VD_DETAILS_TRAIN_VEHICLES == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_INFO );
2044 static_assert(WID_VD_DETAILS_CAPACITY_OF_EACH == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_CAPACITY);
2045 static_assert(WID_VD_DETAILS_TOTAL_CARGO == WID_VD_DETAILS_CARGO_CARRIED + TDW_TAB_TOTALS );
2047 /** Vehicle details widgets (other than train). */
2048 static const NWidgetPart _nested_nontrain_vehicle_details_widgets[] = {
2049 NWidget(NWID_HORIZONTAL),
2050 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
2051 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VD_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2052 NWidget(WWT_SHADEBOX, COLOUR_GREY),
2053 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
2054 NWidget(WWT_STICKYBOX, COLOUR_GREY),
2055 EndContainer(),
2056 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_TOP_DETAILS), SetMinimalSize(405, 42), SetResize(1, 0), EndContainer(),
2057 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_MIDDLE_DETAILS), SetMinimalSize(405, 45), SetResize(1, 0), EndContainer(),
2058 NWidget(NWID_HORIZONTAL),
2059 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_DECREASE_SERVICING_INTERVAL), SetFill(0, 1),
2060 SetDataTip(AWV_DECREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
2061 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_INCREASE_SERVICING_INTERVAL), SetFill(0, 1),
2062 SetDataTip(AWV_INCREASE, STR_VEHICLE_DETAILS_INCREASE_SERVICING_INTERVAL_TOOLTIP),
2063 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VD_SERVICE_INTERVAL_DROPDOWN), SetFill(0, 1),
2064 SetDataTip(STR_EMPTY, STR_SERVICE_INTERVAL_DROPDOWN_TOOLTIP),
2065 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_SERVICING_INTERVAL), SetFill(1, 1), SetResize(1, 0), EndContainer(),
2066 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
2067 EndContainer(),
2070 /** Train details widgets. */
2071 static const NWidgetPart _nested_train_vehicle_details_widgets[] = {
2072 NWidget(NWID_HORIZONTAL),
2073 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
2074 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VD_CAPTION), SetDataTip(STR_VEHICLE_DETAILS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2075 NWidget(WWT_SHADEBOX, COLOUR_GREY),
2076 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
2077 NWidget(WWT_STICKYBOX, COLOUR_GREY),
2078 EndContainer(),
2079 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_TOP_DETAILS), SetResize(1, 0), SetMinimalSize(405, 42), EndContainer(),
2080 NWidget(NWID_HORIZONTAL),
2081 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),
2082 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_VD_SCROLLBAR),
2083 EndContainer(),
2084 NWidget(NWID_HORIZONTAL),
2085 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_DECREASE_SERVICING_INTERVAL), SetFill(0, 1),
2086 SetDataTip(AWV_DECREASE, STR_VEHICLE_DETAILS_DECREASE_SERVICING_INTERVAL_TOOLTIP),
2087 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_VD_INCREASE_SERVICING_INTERVAL), SetFill(0, 1),
2088 SetDataTip(AWV_INCREASE, STR_VEHICLE_DETAILS_INCREASE_SERVICING_INTERVAL_TOOLTIP),
2089 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_VD_SERVICE_INTERVAL_DROPDOWN), SetFill(0, 1),
2090 SetDataTip(STR_EMPTY, STR_SERVICE_INTERVAL_DROPDOWN_TOOLTIP),
2091 NWidget(WWT_PANEL, COLOUR_GREY, WID_VD_SERVICING_INTERVAL), SetFill(1, 1), SetResize(1, 0), EndContainer(),
2092 EndContainer(),
2093 NWidget(NWID_HORIZONTAL),
2094 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_CARGO_CARRIED), SetMinimalSize(96, 12),
2095 SetDataTip(STR_VEHICLE_DETAIL_TAB_CARGO, STR_VEHICLE_DETAILS_TRAIN_CARGO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
2096 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_TRAIN_VEHICLES), SetMinimalSize(99, 12),
2097 SetDataTip(STR_VEHICLE_DETAIL_TAB_INFORMATION, STR_VEHICLE_DETAILS_TRAIN_INFORMATION_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
2098 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_CAPACITY_OF_EACH), SetMinimalSize(99, 12),
2099 SetDataTip(STR_VEHICLE_DETAIL_TAB_CAPACITIES, STR_VEHICLE_DETAILS_TRAIN_CAPACITIES_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
2100 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_VD_DETAILS_TOTAL_CARGO), SetMinimalSize(99, 12),
2101 SetDataTip(STR_VEHICLE_DETAIL_TAB_TOTAL_CARGO, STR_VEHICLE_DETAILS_TRAIN_TOTAL_CARGO_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
2102 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
2103 EndContainer(),
2107 extern int GetTrainDetailsWndVScroll(VehicleID veh_id, TrainDetailsWindowTabs det_tab);
2108 extern void DrawTrainDetails(const Train *v, int left, int right, int y, int vscroll_pos, uint16 vscroll_cap, TrainDetailsWindowTabs det_tab);
2109 extern void DrawRoadVehDetails(const Vehicle *v, int left, int right, int y);
2110 extern void DrawShipDetails(const Vehicle *v, int left, int right, int y);
2111 extern void DrawAircraftDetails(const Aircraft *v, int left, int right, int y);
2113 static StringID _service_interval_dropdown[] = {
2114 STR_VEHICLE_DETAILS_DEFAULT,
2115 STR_VEHICLE_DETAILS_DAYS,
2116 STR_VEHICLE_DETAILS_PERCENT,
2117 INVALID_STRING_ID,
2120 /** Class for managing the vehicle details window. */
2121 struct VehicleDetailsWindow : Window {
2122 TrainDetailsWindowTabs tab; ///< For train vehicles: which tab is displayed.
2123 Scrollbar *vscroll;
2125 /** Initialize a newly created vehicle details window */
2126 VehicleDetailsWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
2128 const Vehicle *v = Vehicle::Get(window_number);
2130 this->CreateNestedTree();
2131 this->vscroll = (v->type == VEH_TRAIN ? this->GetScrollbar(WID_VD_SCROLLBAR) : nullptr);
2132 this->FinishInitNested(window_number);
2134 this->owner = v->owner;
2135 this->tab = TDW_TAB_CARGO;
2139 * Some data on this window has become invalid.
2140 * @param data Information about the changed data.
2141 * @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.
2143 void OnInvalidateData(int data = 0, bool gui_scope = true) override
2145 if (data == VIWD_AUTOREPLACE) {
2146 /* Autoreplace replaced the vehicle.
2147 * Nothing to do for this window. */
2148 return;
2150 if (!gui_scope) return;
2151 const Vehicle *v = Vehicle::Get(this->window_number);
2152 if (v->type == VEH_ROAD) {
2153 const NWidgetBase *nwid_info = this->GetWidget<NWidgetBase>(WID_VD_MIDDLE_DETAILS);
2154 uint aimed_height = this->GetRoadVehDetailsHeight(v);
2155 /* If the number of articulated parts changes, the size of the window must change too. */
2156 if (aimed_height != nwid_info->current_y) {
2157 this->ReInit();
2163 * Gets the desired height for the road vehicle details panel.
2164 * @param v Road vehicle being shown.
2165 * @return Desired height in pixels.
2167 uint GetRoadVehDetailsHeight(const Vehicle *v)
2169 uint desired_height;
2170 if (v->HasArticulatedPart()) {
2171 /* An articulated RV has its text drawn under the sprite instead of after it, hence 15 pixels extra. */
2172 desired_height = WD_FRAMERECT_TOP + ScaleGUITrad(15) + 3 * FONT_HEIGHT_NORMAL + 2 + WD_FRAMERECT_BOTTOM;
2173 /* Add space for the cargo amount for each part. */
2174 for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
2175 if (u->cargo_cap != 0) desired_height += FONT_HEIGHT_NORMAL + 1;
2177 } else {
2178 desired_height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + 3 + WD_FRAMERECT_BOTTOM;
2180 return desired_height;
2183 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
2185 switch (widget) {
2186 case WID_VD_TOP_DETAILS: {
2187 Dimension dim = { 0, 0 };
2188 size->height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
2190 for (uint i = 0; i < 4; i++) SetDParamMaxValue(i, INT16_MAX);
2191 static const StringID info_strings[] = {
2192 STR_VEHICLE_INFO_MAX_SPEED,
2193 STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED,
2194 STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE,
2195 STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR,
2196 STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS
2198 for (uint i = 0; i < lengthof(info_strings); i++) {
2199 dim = maxdim(dim, GetStringBoundingBox(info_strings[i]));
2201 SetDParam(0, STR_VEHICLE_INFO_AGE);
2202 dim = maxdim(dim, GetStringBoundingBox(STR_VEHICLE_INFO_AGE_RUNNING_COST_YR));
2203 size->width = dim.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
2204 break;
2207 case WID_VD_MIDDLE_DETAILS: {
2208 const Vehicle *v = Vehicle::Get(this->window_number);
2209 switch (v->type) {
2210 case VEH_ROAD:
2211 size->height = this->GetRoadVehDetailsHeight(v);
2212 break;
2214 case VEH_SHIP:
2215 size->height = WD_FRAMERECT_TOP + 4 * FONT_HEIGHT_NORMAL + 3 + WD_FRAMERECT_BOTTOM;
2216 break;
2218 case VEH_AIRCRAFT:
2219 size->height = WD_FRAMERECT_TOP + 5 * FONT_HEIGHT_NORMAL + 4 + WD_FRAMERECT_BOTTOM;
2220 break;
2222 default:
2223 NOT_REACHED(); // Train uses WID_VD_MATRIX instead.
2225 break;
2228 case WID_VD_MATRIX:
2229 resize->height = std::max(ScaleGUITrad(14), WD_MATRIX_TOP + FONT_HEIGHT_NORMAL + WD_MATRIX_BOTTOM);
2230 size->height = 4 * resize->height;
2231 break;
2233 case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
2234 StringID *strs = _service_interval_dropdown;
2235 while (*strs != INVALID_STRING_ID) {
2236 *size = maxdim(*size, GetStringBoundingBox(*strs++));
2238 size->width += padding.width;
2239 size->height = FONT_HEIGHT_NORMAL + WD_DROPDOWNTEXT_TOP + WD_DROPDOWNTEXT_BOTTOM;
2240 break;
2243 case WID_VD_SERVICING_INTERVAL:
2244 SetDParamMaxValue(0, MAX_SERVINT_DAYS); // Roughly the maximum interval
2245 SetDParamMaxValue(1, MAX_YEAR * DAYS_IN_YEAR); // Roughly the maximum year
2246 size->width = std::max(
2247 GetStringBoundingBox(STR_VEHICLE_DETAILS_SERVICING_INTERVAL_PERCENT).width,
2248 GetStringBoundingBox(STR_VEHICLE_DETAILS_SERVICING_INTERVAL_DAYS).width
2249 ) + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
2250 size->height = WD_FRAMERECT_TOP + FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
2251 break;
2255 /** Checks whether service interval is enabled for the vehicle. */
2256 static bool IsVehicleServiceIntervalEnabled(const VehicleType vehicle_type, CompanyID company_id)
2258 const VehicleDefaultSettings *vds = &Company::Get(company_id)->settings.vehicle;
2259 switch (vehicle_type) {
2260 default: NOT_REACHED();
2261 case VEH_TRAIN: return vds->servint_trains != 0;
2262 case VEH_ROAD: return vds->servint_roadveh != 0;
2263 case VEH_SHIP: return vds->servint_ships != 0;
2264 case VEH_AIRCRAFT: return vds->servint_aircraft != 0;
2269 * Draw the details for the given vehicle at the position of the Details windows
2271 * @param v current vehicle
2272 * @param left The left most coordinate to draw
2273 * @param right The right most coordinate to draw
2274 * @param y The y coordinate
2275 * @param vscroll_pos Position of scrollbar (train only)
2276 * @param vscroll_cap Number of lines currently displayed (train only)
2277 * @param det_tab Selected details tab (train only)
2279 static void DrawVehicleDetails(const Vehicle *v, int left, int right, int y, int vscroll_pos, uint vscroll_cap, TrainDetailsWindowTabs det_tab)
2281 switch (v->type) {
2282 case VEH_TRAIN: DrawTrainDetails(Train::From(v), left, right, y, vscroll_pos, vscroll_cap, det_tab); break;
2283 case VEH_ROAD: DrawRoadVehDetails(v, left, right, y); break;
2284 case VEH_SHIP: DrawShipDetails(v, left, right, y); break;
2285 case VEH_AIRCRAFT: DrawAircraftDetails(Aircraft::From(v), left, right, y); break;
2286 default: NOT_REACHED();
2290 void SetStringParameters(int widget) const override
2292 if (widget == WID_VD_CAPTION) SetDParam(0, Vehicle::Get(this->window_number)->index);
2295 void DrawWidget(const Rect &r, int widget) const override
2297 const Vehicle *v = Vehicle::Get(this->window_number);
2299 switch (widget) {
2300 case WID_VD_TOP_DETAILS: {
2301 int y = r.top + WD_FRAMERECT_TOP;
2303 /* Draw running cost */
2304 SetDParam(1, v->age / DAYS_IN_LEAP_YEAR);
2305 SetDParam(0, (v->age + DAYS_IN_YEAR < v->max_age) ? STR_VEHICLE_INFO_AGE : STR_VEHICLE_INFO_AGE_RED);
2306 SetDParam(2, v->max_age / DAYS_IN_LEAP_YEAR);
2307 SetDParam(3, v->GetDisplayRunningCost());
2308 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_AGE_RUNNING_COST_YR);
2309 y += FONT_HEIGHT_NORMAL;
2311 /* Draw max speed */
2312 StringID string;
2313 if (v->type == VEH_TRAIN ||
2314 (v->type == VEH_ROAD && _settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL)) {
2315 const GroundVehicleCache *gcache = v->GetGroundVehicleCache();
2316 SetDParam(2, v->GetDisplayMaxSpeed());
2317 SetDParam(1, gcache->cached_power);
2318 SetDParam(0, gcache->cached_weight);
2319 SetDParam(3, gcache->cached_max_te / 1000);
2320 if (v->type == VEH_TRAIN && (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ||
2321 GetRailTypeInfo(Train::From(v)->railtype)->acceleration_type == 2)) {
2322 string = STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED;
2323 } else {
2324 string = STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE;
2326 } else {
2327 SetDParam(0, v->GetDisplayMaxSpeed());
2328 if (v->type == VEH_AIRCRAFT) {
2329 SetDParam(1, v->GetEngine()->GetAircraftTypeText());
2330 if (Aircraft::From(v)->GetRange() > 0) {
2331 SetDParam(2, Aircraft::From(v)->GetRange());
2332 string = STR_VEHICLE_INFO_MAX_SPEED_TYPE_RANGE;
2333 } else {
2334 string = STR_VEHICLE_INFO_MAX_SPEED_TYPE;
2336 } else {
2337 string = STR_VEHICLE_INFO_MAX_SPEED;
2340 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, string);
2341 y += FONT_HEIGHT_NORMAL;
2343 /* Draw profit */
2344 SetDParam(0, v->GetDisplayProfitThisYear());
2345 SetDParam(1, v->GetDisplayProfitLastYear());
2346 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_PROFIT_THIS_YEAR_LAST_YEAR);
2347 y += FONT_HEIGHT_NORMAL;
2349 /* Draw breakdown & reliability */
2350 SetDParam(0, ToPercent16(v->reliability));
2351 SetDParam(1, v->breakdowns_since_last_service);
2352 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_VEHICLE_INFO_RELIABILITY_BREAKDOWNS);
2353 break;
2356 case WID_VD_MATRIX:
2357 /* For trains only. */
2358 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);
2359 break;
2361 case WID_VD_MIDDLE_DETAILS: {
2362 /* For other vehicles, at the place of the matrix. */
2363 bool rtl = _current_text_dir == TD_RTL;
2364 uint sprite_width = GetSingleVehicleWidth(v, EIT_IN_DETAILS) + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
2366 uint text_left = r.left + (rtl ? 0 : sprite_width);
2367 uint text_right = r.right - (rtl ? sprite_width : 0);
2369 /* Articulated road vehicles use a complete line. */
2370 if (v->type == VEH_ROAD && v->HasArticulatedPart()) {
2371 DrawVehicleImage(v, r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, 0);
2372 } else {
2373 uint sprite_left = rtl ? text_right : r.left;
2374 uint sprite_right = rtl ? r.right : text_left;
2376 DrawVehicleImage(v, sprite_left + WD_FRAMERECT_LEFT, sprite_right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, INVALID_VEHICLE, EIT_IN_DETAILS, 0);
2378 DrawVehicleDetails(v, text_left + WD_FRAMERECT_LEFT, text_right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, 0, 0, this->tab);
2379 break;
2382 case WID_VD_SERVICING_INTERVAL:
2383 /* Draw service interval text */
2384 SetDParam(0, v->GetServiceInterval());
2385 SetDParam(1, v->date_of_last_service);
2386 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + (r.bottom - r.top + 1 - FONT_HEIGHT_NORMAL) / 2,
2387 v->ServiceIntervalIsPercent() ? STR_VEHICLE_DETAILS_SERVICING_INTERVAL_PERCENT : STR_VEHICLE_DETAILS_SERVICING_INTERVAL_DAYS);
2388 break;
2392 /** Repaint vehicle details window. */
2393 void OnPaint() override
2395 const Vehicle *v = Vehicle::Get(this->window_number);
2397 if (v->type == VEH_TRAIN) {
2398 this->DisableWidget(this->tab + WID_VD_DETAILS_CARGO_CARRIED);
2399 this->vscroll->SetCount(GetTrainDetailsWndVScroll(v->index, this->tab));
2402 /* Disable service-scroller when interval is set to disabled */
2403 this->SetWidgetsDisabledState(!IsVehicleServiceIntervalEnabled(v->type, v->owner),
2404 WID_VD_INCREASE_SERVICING_INTERVAL,
2405 WID_VD_DECREASE_SERVICING_INTERVAL,
2406 WIDGET_LIST_END);
2408 StringID str = v->ServiceIntervalIsCustom() ?
2409 (v->ServiceIntervalIsPercent() ? STR_VEHICLE_DETAILS_PERCENT : STR_VEHICLE_DETAILS_DAYS) :
2410 STR_VEHICLE_DETAILS_DEFAULT;
2411 this->GetWidget<NWidgetCore>(WID_VD_SERVICE_INTERVAL_DROPDOWN)->widget_data = str;
2413 this->DrawWidgets();
2416 void OnClick(Point pt, int widget, int click_count) override
2418 switch (widget) {
2419 case WID_VD_INCREASE_SERVICING_INTERVAL: // increase int
2420 case WID_VD_DECREASE_SERVICING_INTERVAL: { // decrease int
2421 int mod = _ctrl_pressed ? 5 : 10;
2422 const Vehicle *v = Vehicle::Get(this->window_number);
2424 mod = (widget == WID_VD_DECREASE_SERVICING_INTERVAL) ? -mod : mod;
2425 mod = GetServiceIntervalClamped(mod + v->GetServiceInterval(), v->ServiceIntervalIsPercent());
2426 if (mod == v->GetServiceInterval()) return;
2428 Command<CMD_CHANGE_SERVICE_INT>::Post(STR_ERROR_CAN_T_CHANGE_SERVICING, v->index, mod, true, v->ServiceIntervalIsPercent());
2429 break;
2432 case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
2433 const Vehicle *v = Vehicle::Get(this->window_number);
2434 ShowDropDownMenu(this, _service_interval_dropdown, v->ServiceIntervalIsCustom() ? (v->ServiceIntervalIsPercent() ? 2 : 1) : 0, widget, 0, 0);
2435 break;
2438 case WID_VD_DETAILS_CARGO_CARRIED:
2439 case WID_VD_DETAILS_TRAIN_VEHICLES:
2440 case WID_VD_DETAILS_CAPACITY_OF_EACH:
2441 case WID_VD_DETAILS_TOTAL_CARGO:
2442 this->SetWidgetsDisabledState(false,
2443 WID_VD_DETAILS_CARGO_CARRIED,
2444 WID_VD_DETAILS_TRAIN_VEHICLES,
2445 WID_VD_DETAILS_CAPACITY_OF_EACH,
2446 WID_VD_DETAILS_TOTAL_CARGO,
2447 widget,
2448 WIDGET_LIST_END);
2450 this->tab = (TrainDetailsWindowTabs)(widget - WID_VD_DETAILS_CARGO_CARRIED);
2451 this->SetDirty();
2452 break;
2456 void OnDropdownSelect(int widget, int index) override
2458 switch (widget) {
2459 case WID_VD_SERVICE_INTERVAL_DROPDOWN: {
2460 const Vehicle *v = Vehicle::Get(this->window_number);
2461 bool iscustom = index != 0;
2462 bool ispercent = iscustom ? (index == 2) : Company::Get(v->owner)->settings.vehicle.servint_ispercent;
2463 uint16 interval = GetServiceIntervalClamped(v->GetServiceInterval(), ispercent);
2464 Command<CMD_CHANGE_SERVICE_INT>::Post(STR_ERROR_CAN_T_CHANGE_SERVICING, v->index, interval, iscustom, ispercent);
2465 break;
2470 void OnResize() override
2472 NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_VD_MATRIX);
2473 if (nwi != nullptr) {
2474 this->vscroll->SetCapacityFromWidget(this, WID_VD_MATRIX);
2479 /** Vehicle details window descriptor. */
2480 static WindowDesc _train_vehicle_details_desc(
2481 WDP_AUTO, "view_vehicle_details_train", 405, 178,
2482 WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
2484 _nested_train_vehicle_details_widgets, lengthof(_nested_train_vehicle_details_widgets)
2487 /** Vehicle details window descriptor for other vehicles than a train. */
2488 static WindowDesc _nontrain_vehicle_details_desc(
2489 WDP_AUTO, "view_vehicle_details", 405, 113,
2490 WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
2492 _nested_nontrain_vehicle_details_widgets, lengthof(_nested_nontrain_vehicle_details_widgets)
2495 /** Shows the vehicle details window of the given vehicle. */
2496 static void ShowVehicleDetailsWindow(const Vehicle *v)
2498 CloseWindowById(WC_VEHICLE_ORDERS, v->index, false);
2499 CloseWindowById(WC_VEHICLE_TIMETABLE, v->index, false);
2500 AllocateWindowDescFront<VehicleDetailsWindow>((v->type == VEH_TRAIN) ? &_train_vehicle_details_desc : &_nontrain_vehicle_details_desc, v->index);
2504 /* Unified vehicle GUI - Vehicle View Window */
2506 /** Vehicle view widgets. */
2507 static const NWidgetPart _nested_vehicle_view_widgets[] = {
2508 NWidget(NWID_HORIZONTAL),
2509 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
2510 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_RENAME), SetMinimalSize(12, 14), SetDataTip(SPR_RENAME, STR_NULL /* filled in later */),
2511 NWidget(WWT_CAPTION, COLOUR_GREY, WID_VV_CAPTION), SetDataTip(STR_VEHICLE_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2512 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_LOCATION), SetMinimalSize(12, 14), SetDataTip(SPR_GOTO_LOCATION, STR_NULL /* filled in later */),
2513 NWidget(WWT_DEBUGBOX, COLOUR_GREY),
2514 NWidget(WWT_SHADEBOX, COLOUR_GREY),
2515 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
2516 NWidget(WWT_STICKYBOX, COLOUR_GREY),
2517 EndContainer(),
2518 NWidget(NWID_HORIZONTAL),
2519 NWidget(WWT_PANEL, COLOUR_GREY),
2520 NWidget(WWT_INSET, COLOUR_GREY), SetPadding(2, 2, 2, 2),
2521 NWidget(NWID_VIEWPORT, INVALID_COLOUR, WID_VV_VIEWPORT), SetMinimalSize(226, 84), SetResize(1, 1),
2522 EndContainer(),
2523 EndContainer(),
2524 NWidget(NWID_VERTICAL),
2525 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VV_SELECT_DEPOT_CLONE),
2526 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_GOTO_DEPOT), SetMinimalSize(18, 18), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
2527 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_CLONE), SetMinimalSize(18, 18), SetDataTip(0x0 /* filled later */, 0x0 /* filled later */),
2528 EndContainer(),
2529 /* For trains only, 'ignore signal' button. */
2530 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_FORCE_PROCEED), SetMinimalSize(18, 18),
2531 SetDataTip(SPR_IGNORE_SIGNALS, STR_VEHICLE_VIEW_TRAIN_IGNORE_SIGNAL_TOOLTIP),
2532 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_VV_SELECT_REFIT_TURN),
2533 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_REFIT), SetMinimalSize(18, 18), SetDataTip(SPR_REFIT_VEHICLE, 0x0 /* filled later */),
2534 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_TURN_AROUND), SetMinimalSize(18, 18),
2535 SetDataTip(SPR_FORCE_VEHICLE_TURN, STR_VEHICLE_VIEW_ROAD_VEHICLE_REVERSE_TOOLTIP),
2536 EndContainer(),
2537 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_SHOW_ORDERS), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_ORDERS, 0x0 /* filled later */),
2538 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_SHOW_DETAILS), SetMinimalSize(18, 18), SetDataTip(SPR_SHOW_VEHICLE_DETAILS, 0x0 /* filled later */),
2539 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(18, 0), SetResize(0, 1), EndContainer(),
2540 EndContainer(),
2541 EndContainer(),
2542 NWidget(NWID_HORIZONTAL),
2543 NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_VV_START_STOP), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetResize(1, 0), SetFill(1, 0),
2544 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_VV_ORDER_LOCATION), SetMinimalSize(12, 14), SetDataTip(SPR_GOTO_LOCATION, STR_VEHICLE_VIEW_ORDER_LOCATION_TOOLTIP),
2545 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
2546 EndContainer(),
2549 /** Vehicle view window descriptor for all vehicles but trains. */
2550 static WindowDesc _vehicle_view_desc(
2551 WDP_AUTO, "view_vehicle", 250, 116,
2552 WC_VEHICLE_VIEW, WC_NONE,
2554 _nested_vehicle_view_widgets, lengthof(_nested_vehicle_view_widgets)
2558 * Vehicle view window descriptor for trains. Only minimum_height and
2559 * default_height are different for train view.
2561 static WindowDesc _train_view_desc(
2562 WDP_AUTO, "view_vehicle_train", 250, 134,
2563 WC_VEHICLE_VIEW, WC_NONE,
2565 _nested_vehicle_view_widgets, lengthof(_nested_vehicle_view_widgets)
2569 /* Just to make sure, nobody has changed the vehicle type constants, as we are
2570 using them for array indexing in a number of places here. */
2571 static_assert(VEH_TRAIN == 0);
2572 static_assert(VEH_ROAD == 1);
2573 static_assert(VEH_SHIP == 2);
2574 static_assert(VEH_AIRCRAFT == 3);
2576 /** Zoom levels for vehicle views indexed by vehicle type. */
2577 static const ZoomLevel _vehicle_view_zoom_levels[] = {
2578 ZOOM_LVL_TRAIN,
2579 ZOOM_LVL_ROADVEH,
2580 ZOOM_LVL_SHIP,
2581 ZOOM_LVL_AIRCRAFT,
2584 /* Constants for geometry of vehicle view viewport */
2585 static const int VV_INITIAL_VIEWPORT_WIDTH = 226;
2586 static const int VV_INITIAL_VIEWPORT_HEIGHT = 84;
2587 static const int VV_INITIAL_VIEWPORT_HEIGHT_TRAIN = 102;
2589 /** Command indices for the _vehicle_command_translation_table. */
2590 enum VehicleCommandTranslation {
2591 VCT_CMD_START_STOP = 0,
2592 VCT_CMD_CLONE_VEH,
2593 VCT_CMD_TURN_AROUND,
2596 /** Command codes for the shared buttons indexed by VehicleCommandTranslation and vehicle type. */
2597 static const StringID _vehicle_msg_translation_table[][4] = {
2598 { // VCT_CMD_START_STOP
2599 STR_ERROR_CAN_T_STOP_START_TRAIN,
2600 STR_ERROR_CAN_T_STOP_START_ROAD_VEHICLE,
2601 STR_ERROR_CAN_T_STOP_START_SHIP,
2602 STR_ERROR_CAN_T_STOP_START_AIRCRAFT
2604 { // VCT_CMD_CLONE_VEH
2605 STR_ERROR_CAN_T_BUY_TRAIN,
2606 STR_ERROR_CAN_T_BUY_ROAD_VEHICLE,
2607 STR_ERROR_CAN_T_BUY_SHIP,
2608 STR_ERROR_CAN_T_BUY_AIRCRAFT
2610 { // VCT_CMD_TURN_AROUND
2611 STR_ERROR_CAN_T_REVERSE_DIRECTION_TRAIN,
2612 STR_ERROR_CAN_T_MAKE_ROAD_VEHICLE_TURN,
2613 INVALID_STRING_ID, // invalid for ships
2614 INVALID_STRING_ID // invalid for aircraft
2619 * This is the Callback method after attempting to start/stop a vehicle
2620 * @param cmd unused
2621 * @param result the result of the start/stop command
2622 * @param veh_id Vehicle ID.
2624 void CcStartStopVehicle(Commands cmd, const CommandCost &result, VehicleID veh_id, bool)
2626 if (result.Failed()) return;
2628 const Vehicle *v = Vehicle::GetIfValid(veh_id);
2629 if (v == nullptr || !v->IsPrimaryVehicle() || v->owner != _local_company) return;
2631 StringID msg = (v->vehstatus & VS_STOPPED) ? STR_VEHICLE_COMMAND_STOPPED : STR_VEHICLE_COMMAND_STARTED;
2632 Point pt = RemapCoords(v->x_pos, v->y_pos, v->z_pos);
2633 AddTextEffect(msg, pt.x, pt.y, DAY_TICKS, TE_RISING);
2637 * Executes #CMD_START_STOP_VEHICLE for given vehicle.
2638 * @param v Vehicle to start/stop
2639 * @param texteffect Should a texteffect be shown?
2641 void StartStopVehicle(const Vehicle *v, bool texteffect)
2643 assert(v->IsPrimaryVehicle());
2644 Command<CMD_START_STOP_VEHICLE>::Post(_vehicle_msg_translation_table[VCT_CMD_START_STOP][v->type], texteffect ? CcStartStopVehicle : nullptr, v->tile, v->index, false);
2647 /** Checks whether the vehicle may be refitted at the moment.*/
2648 static bool IsVehicleRefitable(const Vehicle *v)
2650 if (!v->IsStoppedInDepot()) return false;
2652 do {
2653 if (IsEngineRefittable(v->engine_type)) return true;
2654 } while (v->IsGroundVehicle() && (v = v->Next()) != nullptr);
2656 return false;
2659 /** Window manager class for viewing a vehicle. */
2660 struct VehicleViewWindow : Window {
2661 private:
2662 /** Display planes available in the vehicle view window. */
2663 enum PlaneSelections {
2664 SEL_DC_GOTO_DEPOT, ///< Display 'goto depot' button in #WID_VV_SELECT_DEPOT_CLONE stacked widget.
2665 SEL_DC_CLONE, ///< Display 'clone vehicle' button in #WID_VV_SELECT_DEPOT_CLONE stacked widget.
2667 SEL_RT_REFIT, ///< Display 'refit' button in #WID_VV_SELECT_REFIT_TURN stacked widget.
2668 SEL_RT_TURN_AROUND, ///< Display 'turn around' button in #WID_VV_SELECT_REFIT_TURN stacked widget.
2670 SEL_DC_BASEPLANE = SEL_DC_GOTO_DEPOT, ///< First plane of the #WID_VV_SELECT_DEPOT_CLONE stacked widget.
2671 SEL_RT_BASEPLANE = SEL_RT_REFIT, ///< First plane of the #WID_VV_SELECT_REFIT_TURN stacked widget.
2673 bool mouse_over_start_stop = false;
2676 * Display a plane in the window.
2677 * @param plane Plane to show.
2679 void SelectPlane(PlaneSelections plane)
2681 switch (plane) {
2682 case SEL_DC_GOTO_DEPOT:
2683 case SEL_DC_CLONE:
2684 this->GetWidget<NWidgetStacked>(WID_VV_SELECT_DEPOT_CLONE)->SetDisplayedPlane(plane - SEL_DC_BASEPLANE);
2685 break;
2687 case SEL_RT_REFIT:
2688 case SEL_RT_TURN_AROUND:
2689 this->GetWidget<NWidgetStacked>(WID_VV_SELECT_REFIT_TURN)->SetDisplayedPlane(plane - SEL_RT_BASEPLANE);
2690 break;
2692 default:
2693 NOT_REACHED();
2697 public:
2698 VehicleViewWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
2700 this->flags |= WF_DISABLE_VP_SCROLL;
2701 this->CreateNestedTree();
2703 /* Sprites for the 'send to depot' button indexed by vehicle type. */
2704 static const SpriteID vehicle_view_goto_depot_sprites[] = {
2705 SPR_SEND_TRAIN_TODEPOT,
2706 SPR_SEND_ROADVEH_TODEPOT,
2707 SPR_SEND_SHIP_TODEPOT,
2708 SPR_SEND_AIRCRAFT_TODEPOT,
2710 const Vehicle *v = Vehicle::Get(window_number);
2711 this->GetWidget<NWidgetCore>(WID_VV_GOTO_DEPOT)->widget_data = vehicle_view_goto_depot_sprites[v->type];
2713 /* Sprites for the 'clone vehicle' button indexed by vehicle type. */
2714 static const SpriteID vehicle_view_clone_sprites[] = {
2715 SPR_CLONE_TRAIN,
2716 SPR_CLONE_ROADVEH,
2717 SPR_CLONE_SHIP,
2718 SPR_CLONE_AIRCRAFT,
2720 this->GetWidget<NWidgetCore>(WID_VV_CLONE)->widget_data = vehicle_view_clone_sprites[v->type];
2722 switch (v->type) {
2723 case VEH_TRAIN:
2724 this->GetWidget<NWidgetCore>(WID_VV_TURN_AROUND)->tool_tip = STR_VEHICLE_VIEW_TRAIN_REVERSE_TOOLTIP;
2725 break;
2727 case VEH_ROAD:
2728 break;
2730 case VEH_SHIP:
2731 case VEH_AIRCRAFT:
2732 this->SelectPlane(SEL_RT_REFIT);
2733 break;
2735 default: NOT_REACHED();
2737 this->FinishInitNested(window_number);
2738 this->owner = v->owner;
2739 this->GetWidget<NWidgetViewport>(WID_VV_VIEWPORT)->InitializeViewport(this, this->window_number | (1 << 31), _vehicle_view_zoom_levels[v->type]);
2741 this->GetWidget<NWidgetCore>(WID_VV_START_STOP)->tool_tip = STR_VEHICLE_VIEW_TRAIN_STATUS_START_STOP_TOOLTIP + v->type;
2742 this->GetWidget<NWidgetCore>(WID_VV_RENAME)->tool_tip = STR_VEHICLE_DETAILS_TRAIN_RENAME + v->type;
2743 this->GetWidget<NWidgetCore>(WID_VV_LOCATION)->tool_tip = STR_VEHICLE_VIEW_TRAIN_CENTER_TOOLTIP + v->type;
2744 this->GetWidget<NWidgetCore>(WID_VV_REFIT)->tool_tip = STR_VEHICLE_VIEW_TRAIN_REFIT_TOOLTIP + v->type;
2745 this->GetWidget<NWidgetCore>(WID_VV_GOTO_DEPOT)->tool_tip = STR_VEHICLE_VIEW_TRAIN_SEND_TO_DEPOT_TOOLTIP + v->type;
2746 this->GetWidget<NWidgetCore>(WID_VV_SHOW_ORDERS)->tool_tip = STR_VEHICLE_VIEW_TRAIN_ORDERS_TOOLTIP + v->type;
2747 this->GetWidget<NWidgetCore>(WID_VV_SHOW_DETAILS)->tool_tip = STR_VEHICLE_VIEW_TRAIN_SHOW_DETAILS_TOOLTIP + v->type;
2748 this->GetWidget<NWidgetCore>(WID_VV_CLONE)->tool_tip = STR_VEHICLE_VIEW_CLONE_TRAIN_INFO + v->type;
2750 this->UpdateButtonStatus();
2753 void Close() override
2755 CloseWindowById(WC_VEHICLE_ORDERS, this->window_number, false);
2756 CloseWindowById(WC_VEHICLE_REFIT, this->window_number, false);
2757 CloseWindowById(WC_VEHICLE_DETAILS, this->window_number, false);
2758 CloseWindowById(WC_VEHICLE_TIMETABLE, this->window_number, false);
2759 this->Window::Close();
2762 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
2764 const Vehicle *v = Vehicle::Get(this->window_number);
2765 switch (widget) {
2766 case WID_VV_START_STOP:
2767 size->height = std::max({size->height, GetSpriteSize(SPR_WARNING_SIGN).height, GetSpriteSize(SPR_FLAG_VEH_STOPPED).height, GetSpriteSize(SPR_FLAG_VEH_RUNNING).height}) + WD_IMGBTN_TOP + WD_IMGBTN_BOTTOM;
2768 break;
2770 case WID_VV_FORCE_PROCEED:
2771 if (v->type != VEH_TRAIN) {
2772 size->height = 0;
2773 size->width = 0;
2775 break;
2777 case WID_VV_VIEWPORT:
2778 size->width = VV_INITIAL_VIEWPORT_WIDTH;
2779 size->height = (v->type == VEH_TRAIN) ? VV_INITIAL_VIEWPORT_HEIGHT_TRAIN : VV_INITIAL_VIEWPORT_HEIGHT;
2780 break;
2784 void OnPaint() override
2786 const Vehicle *v = Vehicle::Get(this->window_number);
2787 bool is_localcompany = v->owner == _local_company;
2788 bool refitable_and_stopped_in_depot = IsVehicleRefitable(v);
2790 this->SetWidgetDisabledState(WID_VV_RENAME, !is_localcompany);
2791 this->SetWidgetDisabledState(WID_VV_GOTO_DEPOT, !is_localcompany);
2792 this->SetWidgetDisabledState(WID_VV_REFIT, !refitable_and_stopped_in_depot || !is_localcompany);
2793 this->SetWidgetDisabledState(WID_VV_CLONE, !is_localcompany);
2795 if (v->type == VEH_TRAIN) {
2796 this->SetWidgetLoweredState(WID_VV_FORCE_PROCEED, Train::From(v)->force_proceed == TFP_SIGNAL);
2797 this->SetWidgetDisabledState(WID_VV_FORCE_PROCEED, !is_localcompany);
2798 this->SetWidgetDisabledState(WID_VV_TURN_AROUND, !is_localcompany);
2801 this->SetWidgetDisabledState(WID_VV_ORDER_LOCATION, v->current_order.GetLocation(v) == INVALID_TILE);
2803 this->DrawWidgets();
2806 void SetStringParameters(int widget) const override
2808 if (widget != WID_VV_CAPTION) return;
2810 const Vehicle *v = Vehicle::Get(this->window_number);
2811 SetDParam(0, v->index);
2814 void DrawWidget(const Rect &r, int widget) const override
2816 if (widget != WID_VV_START_STOP) return;
2818 const Vehicle *v = Vehicle::Get(this->window_number);
2819 StringID str;
2820 TextColour text_colour = TC_FROMSTRING;
2821 if (v->vehstatus & VS_CRASHED) {
2822 str = STR_VEHICLE_STATUS_CRASHED;
2823 } else if (v->type != VEH_AIRCRAFT && v->breakdown_ctr == 1) { // check for aircraft necessary?
2824 str = STR_VEHICLE_STATUS_BROKEN_DOWN;
2825 } else if (v->vehstatus & VS_STOPPED && (!mouse_over_start_stop || v->IsStoppedInDepot())) {
2826 if (v->type == VEH_TRAIN) {
2827 if (v->cur_speed == 0) {
2828 if (Train::From(v)->gcache.cached_power == 0) {
2829 str = STR_VEHICLE_STATUS_TRAIN_NO_POWER;
2830 } else {
2831 str = STR_VEHICLE_STATUS_STOPPED;
2833 } else {
2834 SetDParam(0, v->GetDisplaySpeed());
2835 str = STR_VEHICLE_STATUS_TRAIN_STOPPING_VEL;
2837 } else { // no train
2838 str = STR_VEHICLE_STATUS_STOPPED;
2840 } else if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_TRAIN_STUCK) && !v->current_order.IsType(OT_LOADING)) {
2841 str = STR_VEHICLE_STATUS_TRAIN_STUCK;
2842 } else if (v->type == VEH_AIRCRAFT && HasBit(Aircraft::From(v)->flags, VAF_DEST_TOO_FAR) && !v->current_order.IsType(OT_LOADING)) {
2843 str = STR_VEHICLE_STATUS_AIRCRAFT_TOO_FAR;
2844 } else { // vehicle is in a "normal" state, show current order
2845 if (mouse_over_start_stop) {
2846 if (v->vehstatus & VS_STOPPED) {
2847 text_colour = TC_RED | TC_FORCED;
2848 } else if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_TRAIN_STUCK) && !v->current_order.IsType(OT_LOADING)) {
2849 text_colour = TC_ORANGE | TC_FORCED;
2852 switch (v->current_order.GetType()) {
2853 case OT_GOTO_STATION: {
2854 SetDParam(0, v->current_order.GetDestination());
2855 SetDParam(1, v->GetDisplaySpeed());
2856 str = HasBit(v->vehicle_flags, VF_PATHFINDER_LOST) ? STR_VEHICLE_STATUS_CANNOT_REACH_STATION_VEL : STR_VEHICLE_STATUS_HEADING_FOR_STATION_VEL;
2857 break;
2860 case OT_GOTO_DEPOT: {
2861 SetDParam(0, v->type);
2862 SetDParam(1, v->current_order.GetDestination());
2863 SetDParam(2, v->GetDisplaySpeed());
2864 if (v->current_order.GetDepotActionType() & ODATFB_NEAREST_DEPOT) {
2865 /* This case *only* happens when multiple nearest depot orders
2866 * follow each other (including an order list only one order: a
2867 * nearest depot order) and there are no reachable depots.
2868 * It is primarily to guard for the case that there is no
2869 * depot with index 0, which would be used as fallback for
2870 * evaluating the string in the status bar. */
2871 str = STR_EMPTY;
2872 } else if (v->current_order.GetDepotActionType() & ODATFB_HALT) {
2873 str = HasBit(v->vehicle_flags, VF_PATHFINDER_LOST) ? STR_VEHICLE_STATUS_CANNOT_REACH_DEPOT_VEL : STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_VEL;
2874 } else {
2875 str = HasBit(v->vehicle_flags, VF_PATHFINDER_LOST) ? STR_VEHICLE_STATUS_CANNOT_REACH_DEPOT_SERVICE_VEL : STR_VEHICLE_STATUS_HEADING_FOR_DEPOT_SERVICE_VEL;
2877 break;
2880 case OT_LOADING:
2881 str = STR_VEHICLE_STATUS_LOADING_UNLOADING;
2882 break;
2884 case OT_GOTO_WAYPOINT: {
2885 assert(v->type == VEH_TRAIN || v->type == VEH_SHIP);
2886 SetDParam(0, v->current_order.GetDestination());
2887 str = HasBit(v->vehicle_flags, VF_PATHFINDER_LOST) ? STR_VEHICLE_STATUS_CANNOT_REACH_WAYPOINT_VEL : STR_VEHICLE_STATUS_HEADING_FOR_WAYPOINT_VEL;
2888 SetDParam(1, v->GetDisplaySpeed());
2889 break;
2892 case OT_LEAVESTATION:
2893 if (v->type != VEH_AIRCRAFT) {
2894 str = STR_VEHICLE_STATUS_LEAVING;
2895 break;
2897 FALLTHROUGH;
2898 default:
2899 if (v->GetNumManualOrders() == 0) {
2900 str = STR_VEHICLE_STATUS_NO_ORDERS_VEL;
2901 SetDParam(0, v->GetDisplaySpeed());
2902 } else {
2903 str = STR_EMPTY;
2905 break;
2909 /* Draw the flag plus orders. */
2910 bool rtl = (_current_text_dir == TD_RTL);
2911 uint text_offset = std::max({GetSpriteSize(SPR_WARNING_SIGN).width, GetSpriteSize(SPR_FLAG_VEH_STOPPED).width, GetSpriteSize(SPR_FLAG_VEH_RUNNING).width}) + WD_IMGBTN_LEFT + WD_IMGBTN_RIGHT;
2912 int height = r.bottom - r.top;
2913 int text_left = r.left + (rtl ? (uint)WD_FRAMERECT_LEFT : text_offset);
2914 int text_right = r.right - (rtl ? text_offset : (uint)WD_FRAMERECT_RIGHT);
2915 int text_top = r.top + WD_FRAMERECT_TOP + (height - WD_FRAMERECT_TOP - WD_FRAMERECT_BOTTOM - FONT_HEIGHT_NORMAL) / 2;
2916 int image = ((v->vehstatus & VS_STOPPED) != 0) ? SPR_FLAG_VEH_STOPPED : (HasBit(v->vehicle_flags, VF_PATHFINDER_LOST)) ? SPR_WARNING_SIGN : SPR_FLAG_VEH_RUNNING;
2917 int image_left = (rtl ? text_right + 1 : r.left) + WD_IMGBTN_LEFT;
2918 int image_top = r.top + WD_IMGBTN_TOP + (height - WD_IMGBTN_TOP + WD_IMGBTN_BOTTOM - GetSpriteSize(image).height) / 2;
2919 int lowered = this->IsWidgetLowered(WID_VV_START_STOP) ? 1 : 0;
2920 DrawSprite(image, PAL_NONE, image_left + lowered, image_top + lowered);
2921 DrawString(text_left + lowered, text_right + lowered, text_top + lowered, str, text_colour, SA_HOR_CENTER);
2924 void OnClick(Point pt, int widget, int click_count) override
2926 const Vehicle *v = Vehicle::Get(this->window_number);
2928 switch (widget) {
2929 case WID_VV_RENAME: { // rename
2930 SetDParam(0, v->index);
2931 ShowQueryString(STR_VEHICLE_NAME, STR_QUERY_RENAME_TRAIN_CAPTION + v->type,
2932 MAX_LENGTH_VEHICLE_NAME_CHARS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
2933 break;
2936 case WID_VV_START_STOP: // start stop
2937 StartStopVehicle(v, false);
2938 break;
2940 case WID_VV_ORDER_LOCATION: {
2941 /* Scroll to current order destination */
2942 TileIndex tile = v->current_order.GetLocation(v);
2943 if (tile == INVALID_TILE) break;
2945 if (_ctrl_pressed) {
2946 ShowExtraViewportWindow(tile);
2947 } else {
2948 ScrollMainWindowToTile(tile);
2950 break;
2953 case WID_VV_LOCATION: // center main view
2954 if (_ctrl_pressed) {
2955 ShowExtraViewportWindow(TileVirtXY(v->x_pos, v->y_pos));
2956 } else {
2957 const Window *mainwindow = FindWindowById(WC_MAIN_WINDOW, 0);
2958 if (click_count > 1 && mainwindow->viewport->zoom <= ZOOM_LVL_OUT_4X) {
2959 /* main window 'follows' vehicle */
2960 mainwindow->viewport->follow_vehicle = v->index;
2961 } else {
2962 ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos);
2965 break;
2967 case WID_VV_GOTO_DEPOT: // goto hangar
2968 Command<CMD_SEND_VEHICLE_TO_DEPOT>::Post(GetCmdSendToDepotMsg(v), v->index, _ctrl_pressed ? DepotCommand::Service : DepotCommand::None, {});
2969 break;
2970 case WID_VV_REFIT: // refit
2971 ShowVehicleRefitWindow(v, INVALID_VEH_ORDER_ID, this);
2972 break;
2973 case WID_VV_SHOW_ORDERS: // show orders
2974 if (_ctrl_pressed) {
2975 ShowTimetableWindow(v);
2976 } else {
2977 ShowOrdersWindow(v);
2979 break;
2980 case WID_VV_SHOW_DETAILS: // show details
2981 if (_ctrl_pressed) {
2982 ShowCompanyGroupForVehicle(v);
2983 } else {
2984 ShowVehicleDetailsWindow(v);
2986 break;
2987 case WID_VV_CLONE: // clone vehicle
2988 /* Suppress the vehicle GUI when share-cloning.
2989 * There is no point to it except for starting the vehicle.
2990 * For starting the vehicle the player has to open the depot GUI, which is
2991 * most likely already open, but is also visible in the vehicle viewport. */
2992 Command<CMD_CLONE_VEHICLE>::Post(_vehicle_msg_translation_table[VCT_CMD_CLONE_VEH][v->type],
2993 _ctrl_pressed ? nullptr : CcCloneVehicle,
2994 v->tile, v->index, _ctrl_pressed);
2995 break;
2996 case WID_VV_TURN_AROUND: // turn around
2997 assert(v->IsGroundVehicle());
2998 if (v->type == VEH_ROAD) {
2999 Command<CMD_TURN_ROADVEH>::Post(_vehicle_msg_translation_table[VCT_CMD_TURN_AROUND][v->type], v->tile, v->index);
3000 } else {
3001 Command<CMD_REVERSE_TRAIN_DIRECTION>::Post(_vehicle_msg_translation_table[VCT_CMD_TURN_AROUND][v->type], v->tile, v->index, false);
3003 break;
3004 case WID_VV_FORCE_PROCEED: // force proceed
3005 assert(v->type == VEH_TRAIN);
3006 Command<CMD_FORCE_TRAIN_PROCEED>::Post(STR_ERROR_CAN_T_MAKE_TRAIN_PASS_SIGNAL, v->tile, v->index);
3007 break;
3011 void OnQueryTextFinished(char *str) override
3013 if (str == nullptr) return;
3015 Command<CMD_RENAME_VEHICLE>::Post(STR_ERROR_CAN_T_RENAME_TRAIN + Vehicle::Get(this->window_number)->type, this->window_number, str);
3018 void OnMouseOver(Point pt, int widget) override
3020 bool start_stop = widget == WID_VV_START_STOP;
3021 if (start_stop != mouse_over_start_stop) {
3022 mouse_over_start_stop = start_stop;
3023 this->SetWidgetDirty(WID_VV_START_STOP);
3027 void OnResize() override
3029 if (this->viewport != nullptr) {
3030 NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_VV_VIEWPORT);
3031 nvp->UpdateViewportCoordinates(this);
3035 void UpdateButtonStatus()
3037 const Vehicle *v = Vehicle::Get(this->window_number);
3038 bool veh_stopped = v->IsStoppedInDepot();
3040 /* Widget WID_VV_GOTO_DEPOT must be hidden if the vehicle is already stopped in depot.
3041 * Widget WID_VV_CLONE_VEH should then be shown, since cloning is allowed only while in depot and stopped.
3043 PlaneSelections plane = veh_stopped ? SEL_DC_CLONE : SEL_DC_GOTO_DEPOT;
3044 NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VV_SELECT_DEPOT_CLONE); // Selection widget 'send to depot' / 'clone'.
3045 if (nwi->shown_plane + SEL_DC_BASEPLANE != plane) {
3046 this->SelectPlane(plane);
3047 this->SetWidgetDirty(WID_VV_SELECT_DEPOT_CLONE);
3049 /* The same system applies to widget WID_VV_REFIT_VEH and VVW_WIDGET_TURN_AROUND.*/
3050 if (v->IsGroundVehicle()) {
3051 PlaneSelections plane = veh_stopped ? SEL_RT_REFIT : SEL_RT_TURN_AROUND;
3052 NWidgetStacked *nwi = this->GetWidget<NWidgetStacked>(WID_VV_SELECT_REFIT_TURN);
3053 if (nwi->shown_plane + SEL_RT_BASEPLANE != plane) {
3054 this->SelectPlane(plane);
3055 this->SetWidgetDirty(WID_VV_SELECT_REFIT_TURN);
3061 * Some data on this window has become invalid.
3062 * @param data Information about the changed data.
3063 * @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.
3065 void OnInvalidateData(int data = 0, bool gui_scope = true) override
3067 if (data == VIWD_AUTOREPLACE) {
3068 /* Autoreplace replaced the vehicle.
3069 * Nothing to do for this window. */
3070 return;
3073 this->UpdateButtonStatus();
3076 bool IsNewGRFInspectable() const override
3078 return ::IsNewGRFInspectable(GetGrfSpecFeature(Vehicle::Get(this->window_number)->type), this->window_number);
3081 void ShowNewGRFInspectWindow() const override
3083 ::ShowNewGRFInspectWindow(GetGrfSpecFeature(Vehicle::Get(this->window_number)->type), this->window_number);
3088 /** Shows the vehicle view window of the given vehicle. */
3089 void ShowVehicleViewWindow(const Vehicle *v)
3091 AllocateWindowDescFront<VehicleViewWindow>((v->type == VEH_TRAIN) ? &_train_view_desc : &_vehicle_view_desc, v->index);
3095 * Dispatch a "vehicle selected" event if any window waits for it.
3096 * @param v selected vehicle;
3097 * @return did any window accept vehicle selection?
3099 bool VehicleClicked(const Vehicle *v)
3101 assert(v != nullptr);
3102 if (!(_thd.place_mode & HT_VEHICLE)) return false;
3104 v = v->First();
3105 if (!v->IsPrimaryVehicle()) return false;
3107 return _thd.GetCallbackWnd()->OnVehicleSelect(v);
3110 void StopGlobalFollowVehicle(const Vehicle *v)
3112 Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
3113 if (w != nullptr && w->viewport->follow_vehicle == v->index) {
3114 ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos, true); // lock the main view on the vehicle's last position
3115 w->viewport->follow_vehicle = INVALID_VEHICLE;
3121 * This is the Callback method after the construction attempt of a primary vehicle
3122 * @param cmd unused
3123 * @param result indicates completion (or not) of the operation
3124 * @param new_veh_id ID of the new vehicle.
3126 void CcBuildPrimaryVehicle(Commands cmd, const CommandCost &result, VehicleID new_veh_id, uint, uint16)
3128 if (result.Failed()) return;
3130 const Vehicle *v = Vehicle::Get(new_veh_id);
3131 ShowVehicleViewWindow(v);
3135 * Get the width of a vehicle (part) in pixels.
3136 * @param v Vehicle to get the width for.
3137 * @return Width of the vehicle.
3139 int GetSingleVehicleWidth(const Vehicle *v, EngineImageType image_type)
3141 switch (v->type) {
3142 case VEH_TRAIN:
3143 return Train::From(v)->GetDisplayImageWidth();
3145 case VEH_ROAD:
3146 return RoadVehicle::From(v)->GetDisplayImageWidth();
3148 default:
3149 bool rtl = _current_text_dir == TD_RTL;
3150 VehicleSpriteSeq seq;
3151 v->GetImage(rtl ? DIR_E : DIR_W, image_type, &seq);
3152 Rect rec;
3153 seq.GetBounds(&rec);
3154 return UnScaleGUI(rec.right - rec.left + 1);
3159 * Get the width of a vehicle (including all parts of the consist) in pixels.
3160 * @param v Vehicle to get the width for.
3161 * @return Width of the vehicle.
3163 int GetVehicleWidth(const Vehicle *v, EngineImageType image_type)
3165 if (v->type == VEH_TRAIN || v->type == VEH_ROAD) {
3166 int vehicle_width = 0;
3167 for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
3168 vehicle_width += GetSingleVehicleWidth(u, image_type);
3170 return vehicle_width;
3171 } else {
3172 return GetSingleVehicleWidth(v, image_type);
3177 * Set the mouse cursor to look like a vehicle.
3178 * @param v Vehicle
3179 * @param image_type Type of vehicle image to use.
3181 void SetMouseCursorVehicle(const Vehicle *v, EngineImageType image_type)
3183 bool rtl = _current_text_dir == TD_RTL;
3185 _cursor.sprite_count = 0;
3186 int total_width = 0;
3187 int y_offset = 0;
3188 bool rotor_seq = false; // Whether to draw the rotor of the vehicle in this step.
3189 bool is_ground_vehicle = v->IsGroundVehicle();
3191 while (v != nullptr) {
3192 if (total_width >= ScaleGUITrad(2 * (int)VEHICLEINFO_FULL_VEHICLE_WIDTH)) break;
3194 PaletteID pal = (v->vehstatus & VS_CRASHED) ? PALETTE_CRASH : GetVehiclePalette(v);
3195 VehicleSpriteSeq seq;
3197 if (rotor_seq) {
3198 GetCustomRotorSprite(Aircraft::From(v), image_type, &seq);
3199 if (!seq.IsValid()) seq.Set(SPR_ROTOR_STOPPED);
3200 y_offset = - ScaleGUITrad(5);
3201 } else {
3202 v->GetImage(rtl ? DIR_E : DIR_W, image_type, &seq);
3205 if (_cursor.sprite_count + seq.count > lengthof(_cursor.sprite_seq)) break;
3207 for (uint i = 0; i < seq.count; ++i) {
3208 PaletteID pal2 = (v->vehstatus & VS_CRASHED) || !seq.seq[i].pal ? pal : seq.seq[i].pal;
3209 _cursor.sprite_seq[_cursor.sprite_count].sprite = seq.seq[i].sprite;
3210 _cursor.sprite_seq[_cursor.sprite_count].pal = pal2;
3211 _cursor.sprite_pos[_cursor.sprite_count].x = rtl ? -total_width : total_width;
3212 _cursor.sprite_pos[_cursor.sprite_count].y = y_offset;
3213 _cursor.sprite_count++;
3216 if (v->type == VEH_AIRCRAFT && v->subtype == AIR_HELICOPTER && !rotor_seq) {
3217 /* Draw rotor part in the next step. */
3218 rotor_seq = true;
3219 } else {
3220 total_width += GetSingleVehicleWidth(v, image_type);
3221 v = v->HasArticulatedPart() ? v->GetNextArticulatedPart() : nullptr;
3225 if (is_ground_vehicle) {
3226 /* Center trains and road vehicles on the front vehicle */
3227 int offs = (ScaleGUITrad(VEHICLEINFO_FULL_VEHICLE_WIDTH) - total_width) / 2;
3228 if (rtl) offs = -offs;
3229 for (uint i = 0; i < _cursor.sprite_count; ++i) {
3230 _cursor.sprite_pos[i].x += offs;
3234 UpdateCursorSize();