OpenTTD Source 20261129-master-g72a8bdc861
station_gui.cpp
Go to the documentation of this file.
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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
11#include "debug.h"
12#include "gui.h"
13#include "graph_gui.h"
14#include "querystring_gui.h"
15#include "textbuf_gui.h"
16#include "company_func.h"
17#include "command_func.h"
18#include "tilearea_spiral.h"
19#include "vehicle_gui.h"
20#include "cargotype.h"
21#include "station_func.h"
22#include "station_gui.h"
23#include "strings_func.h"
24#include "string_func.h"
25#include "window_func.h"
26#include "viewport_func.h"
27#include "dropdown_type.h"
28#include "dropdown_func.h"
29#include "station_base.h"
30#include "waypoint_base.h"
31#include "tilehighlight_func.h"
32#include "company_base.h"
33#include "sortlist_type.h"
35#include "vehiclelist.h"
36#include "sound_func.h"
37#include "town.h"
38#include "linkgraph/linkgraph.h"
39#include "zoom_func.h"
40#include "station_cmd.h"
41
43#include "widgets/misc_widget.h"
44
45#include "table/strings.h"
46
48
49#include "safeguards.h"
50
52{
53 using StationType = Station;
54
55 static bool IsValidID(StationID id) { return Station::IsValidID(id); }
56 static bool IsValidBaseStation(const BaseStation *st) { return Station::IsExpected(st); }
57 static bool IsAcceptableWaypointTile(TileIndex) { return false; }
58 static constexpr bool IsWaypoint() { return false; }
59};
60
61template <bool ROAD, TileType TILE_TYPE>
63{
64 using StationType = Waypoint;
65
66 static bool IsValidID(StationID id) { return Waypoint::IsValidID(id) && HasBit(Waypoint::Get(id)->waypoint_flags, WPF_ROAD) == ROAD; }
67 static bool IsValidBaseStation(const BaseStation *st) { return Waypoint::IsExpected(st) && HasBit(Waypoint::From(st)->waypoint_flags, WPF_ROAD) == ROAD; }
68 static bool IsAcceptableWaypointTile(TileIndex tile) { return IsTileType(tile, TILE_TYPE); }
69 static constexpr bool IsWaypoint() { return true; }
70};
71using RailWaypointTypeFilter = GenericWaypointTypeFilter<false, TileType::Railway>;
72using RoadWaypointTypeFilter = GenericWaypointTypeFilter<true, TileType::Road>;
73
82int DrawStationCoverageAreaText(const Rect &r, StationCoverageType sct, int rad, bool supplies)
83{
84 TileIndex tile = TileVirtXY(_thd.pos.x, _thd.pos.y);
85 CargoTypes cargo_mask{};
86 if (_thd.drawstyle == HT_RECT && tile < Map::Size()) {
87 CargoArray cargoes;
88 if (supplies) {
89 cargoes = GetProductionAroundTiles(tile, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE, rad);
90 } else {
91 cargoes = GetAcceptanceAroundTiles(tile, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE, rad).first;
92 }
93
94 /* Convert cargo counts to a set of cargo bits, and draw the result. */
95 for (CargoType cargo : EnumRange(NUM_CARGO)) {
96 switch (sct) {
97 case SCT_PASSENGERS_ONLY: if (!IsCargoInClass(cargo, CargoClass::Passengers)) continue; break;
98 case SCT_NON_PASSENGERS_ONLY: if (IsCargoInClass(cargo, CargoClass::Passengers)) continue; break;
99 case SCT_ALL: break;
100 default: NOT_REACHED();
101 }
102 if (cargoes[cargo] >= (supplies ? 1U : 8U)) cargo_mask.Set(cargo);
103 }
104 }
105 return DrawStringMultiLine(r, GetString(supplies ? STR_STATION_BUILD_SUPPLIES_CARGO : STR_STATION_BUILD_ACCEPTS_CARGO, cargo_mask));
106}
107
112template <typename T>
114{
115 /* With distant join we don't know which station will be selected, so don't show any */
116 if (IsCtrlPressed()) {
117 SetViewportCatchmentSpecializedStation<typename T::StationType>(nullptr, true);
118 return;
119 }
120
121 /* Tile area for TileHighlightData */
122 TileArea location(TileVirtXY(_thd.pos.x, _thd.pos.y), _thd.size.x / TILE_SIZE - 1, _thd.size.y / TILE_SIZE - 1);
123
124 /* If the current tile is already a station, then it must be the nearest station. */
125 if (IsTileType(location.tile, TileType::Station) && GetTileOwner(location.tile) == _local_company) {
126 typename T::StationType *st = T::StationType::GetByTile(location.tile);
127 if (st != nullptr && T::IsValidBaseStation(st)) {
128 SetViewportCatchmentSpecializedStation<typename T::StationType>(st, true);
129 return;
130 }
131 }
132
133 /* Extended area by one tile */
134 uint x = TileX(location.tile);
135 uint y = TileY(location.tile);
136
137 /* Waypoints can only be built on existing rail/road tiles, so don't extend area if not highlighting a rail tile. */
138 int max_c = T::IsWaypoint() && !T::IsAcceptableWaypointTile(location.tile) ? 0 : 1;
139 TileArea ta(TileXY(std::max<int>(0, x - max_c), std::max<int>(0, y - max_c)), TileXY(std::min<int>(Map::MaxX(), x + location.w + max_c), std::min<int>(Map::MaxY(), y + location.h + max_c)));
140
141 typename T::StationType *adjacent = nullptr;
142
143 /* Direct loop instead of ForAllStationsAroundTiles as we are not interested in catchment area */
144 for (TileIndex tile : ta) {
146 typename T::StationType *st = T::StationType::GetByTile(tile);
147 if (st == nullptr || !T::IsValidBaseStation(st)) continue;
148 if (adjacent != nullptr && st != adjacent) {
149 /* Multiple nearby, distant join is required. */
150 adjacent = nullptr;
151 break;
152 }
153 adjacent = st;
154 }
155 }
156 SetViewportCatchmentSpecializedStation<typename T::StationType>(adjacent, true);
157}
158
165{
166 /* Test if ctrl state changed */
167 static bool _last_ctrl_pressed;
168 if (IsCtrlPressed() != _last_ctrl_pressed) {
169 _thd.dirty = 0xff;
170 _last_ctrl_pressed = IsCtrlPressed();
171 }
172
173 if (_thd.dirty & 1) {
174 _thd.dirty &= ~1;
175 w->SetDirty();
176
177 if (_settings_client.gui.station_show_coverage && _thd.drawstyle == HT_RECT) {
179 }
180 }
181}
182
183template <typename T>
184void CheckRedrawWaypointCoverage()
185{
186 /* Test if ctrl state changed */
187 static bool _last_ctrl_pressed;
188 if (IsCtrlPressed() != _last_ctrl_pressed) {
189 _thd.dirty = 0xff;
190 _last_ctrl_pressed = IsCtrlPressed();
191 }
192
193 if (_thd.dirty & 1) {
194 _thd.dirty &= ~1;
195
196 if (_thd.drawstyle == HT_RECT) {
198 }
199 }
200}
201
202void CheckRedrawRailWaypointCoverage(const Window *)
203{
204 CheckRedrawWaypointCoverage<RailWaypointTypeFilter>();
205}
206
207void CheckRedrawRoadWaypointCoverage(const Window *)
208{
209 CheckRedrawWaypointCoverage<RoadWaypointTypeFilter>();
210}
211
224static void StationsWndShowStationRating(int left, int right, int y, CargoType cargo, uint amount, uint8_t rating)
225{
226 static const uint units_full = 576;
227 static const uint rating_full = 224;
228
229 const CargoSpec *cs = CargoSpec::Get(cargo);
230 if (!cs->IsValid()) return;
231
232 int padding = ScaleGUITrad(1);
233 int width = right - left;
234 PixelColour colour = cs->rating_colour;
235 TextColour tc = GetContrastColour(colour);
236 uint w = std::min(amount + 5, units_full) * width / units_full;
237
238 int height = GetCharacterHeight(FontSize::Small) + padding - 1;
239
240 if (amount > 30) {
241 /* Draw total cargo (limited) on station */
242 GfxFillRect(left, y, left + w - 1, y + height, colour);
243 } else {
244 /* Draw a (scaled) one pixel-wide bar of additional cargo meter, useful
245 * for stations with only a small amount (<=30) */
246 uint rest = ScaleGUITrad(amount) / 5;
247 if (rest != 0) {
248 GfxFillRect(left, y + height - rest, left + padding - 1, y + height, colour);
249 }
250 }
251
252 DrawString(left + padding, right, y, cs->abbrev, tc, {AlignmentH::Centre, AlignmentV::Middle}, false, FontSize::Small);
253
254 /* Draw green/red ratings bar (fits under the waiting bar) */
255 y += height + padding + 1;
256 GfxFillRect(left + padding, y, right - padding - 1, y + padding - 1, PC_RED);
257 w = std::min<uint>(rating, rating_full) * (width - padding - padding) / rating_full;
258 if (w != 0) GfxFillRect(left + padding, y, left + w - 1, y + padding - 1, PC_GREEN);
259}
260
262
266class CompanyStationsWindow : public Window {
267protected:
275
276 static inline FilterState initial_state = {
277 {false, 0},
279 true,
280 ALL_CARGOTYPES,
281 };
282
284 static inline const StringID sorter_names[] = {
285 STR_SORT_BY_NAME,
286 STR_SORT_BY_FACILITY,
287 STR_SORT_BY_WAITING_TOTAL,
288 STR_SORT_BY_WAITING_AVAILABLE,
289 STR_SORT_BY_RATING_MAX,
290 STR_SORT_BY_RATING_MIN,
291 };
292 static const std::initializer_list<GUIStationList::SortFunction * const> sorter_funcs;
293
296
297 FilterState filter{};
298 GUIStationList stations{filter.cargoes};
299 Scrollbar *vscroll = nullptr;
300 uint rating_width = 0;
301 bool filter_expanded = false;
302 std::array<uint16_t, NUM_CARGO> stations_per_cargo_type{};
304
310 void BuildStationsList(const Owner owner)
311 {
312 if (!this->stations.NeedRebuild()) return;
313
314 Debug(Facility::Misc, Severity::Notice, "Building station list for company {}", owner);
315
316 this->stations.clear();
317 this->stations_per_cargo_type.fill(0);
318 this->stations_per_cargo_type_no_rating = 0;
319
320 for (const Station *st : Station::Iterate()) {
321 if (this->filter.facilities.Any(st->facilities)) { // only stations with selected facilities
322 if (st->owner == owner || (st->owner == OWNER_NONE && HasStationInUse(st->index, true, owner))) {
323 this->string_filter.ResetState();
324 this->string_filter.AddLine(st->GetCachedName());
325 if (!this->string_filter.GetState()) continue;
326
327 bool has_rating = false;
328 /* Add to the station/cargo counts. */
329 for (CargoType cargo : EnumRange(NUM_CARGO)) {
330 if (st->goods[cargo].HasRating()) this->stations_per_cargo_type[cargo]++;
331 }
332 for (CargoType cargo : EnumRange(NUM_CARGO)) {
333 if (st->goods[cargo].HasRating()) {
334 has_rating = true;
335 if (this->filter.cargoes.Test(cargo)) {
336 this->stations.push_back(st);
337 break;
338 }
339 }
340 }
341 /* Stations with no cargo rating. */
342 if (!has_rating) {
343 if (this->filter.include_no_rating) this->stations.push_back(st);
344 this->stations_per_cargo_type_no_rating++;
345 }
346 }
347 }
348 }
349
350 this->stations.RebuildDone();
351
352 this->vscroll->SetCount(this->stations.size()); // Update the scrollbar
353 }
354
356 static bool StationNameSorter(const Station * const &a, const Station * const &b, [[maybe_unused]] const CargoTypes &filter)
357 {
358 int r = StrNaturalCompare(a->GetCachedName(), b->GetCachedName()); // Sort by name (natural sorting).
359 if (r == 0) return a->index < b->index;
360 return r < 0;
361 }
362
364 static bool StationTypeSorter(const Station * const &a, const Station * const &b, [[maybe_unused]] const CargoTypes &filter)
365 {
366 return a->facilities < b->facilities;
367 }
368
370 static bool StationWaitingTotalSorter(const Station * const &a, const Station * const &b, const CargoTypes &filter)
371 {
372 int diff = 0;
373
374 for (CargoType cargo : filter) {
375 diff += a->goods[cargo].TotalCount() - b->goods[cargo].TotalCount();
376 }
377
378 return diff < 0;
379 }
380
382 static bool StationWaitingAvailableSorter(const Station * const &a, const Station * const &b, const CargoTypes &filter)
383 {
384 int diff = 0;
385
386 for (CargoType cargo : filter) {
387 diff += a->goods[cargo].AvailableCount() - b->goods[cargo].AvailableCount();
388 }
389
390 return diff < 0;
391 }
392
394 static bool StationRatingMaxSorter(const Station * const &a, const Station * const &b, const CargoTypes &filter)
395 {
396 uint8_t maxr1 = 0;
397 uint8_t maxr2 = 0;
398
399 for (CargoType cargo : filter) {
400 if (a->goods[cargo].HasRating()) maxr1 = std::max(maxr1, a->goods[cargo].rating);
401 if (b->goods[cargo].HasRating()) maxr2 = std::max(maxr2, b->goods[cargo].rating);
402 }
403
404 return maxr1 < maxr2;
405 }
406
408 static bool StationRatingMinSorter(const Station * const &a, const Station * const &b, const CargoTypes &filter)
409 {
410 uint8_t minr1 = 255;
411 uint8_t minr2 = 255;
412
413 for (CargoType cargo : filter) {
414 if (a->goods[cargo].HasRating()) minr1 = std::min(minr1, a->goods[cargo].rating);
415 if (b->goods[cargo].HasRating()) minr2 = std::min(minr2, b->goods[cargo].rating);
416 }
417
418 return minr1 > minr2;
419 }
420
423 {
424 if (!this->stations.Sort()) return;
425
426 /* Set the modified widget dirty */
428 }
429
430public:
432 {
433 /* Load initial filter state. */
434 this->filter = CompanyStationsWindow::initial_state;
435 if (this->filter.cargoes == ALL_CARGOTYPES) this->filter.cargoes = _cargo_mask;
436
437 this->stations.SetListing(this->filter.last_sorting);
438 this->stations.SetSortFuncs(CompanyStationsWindow::sorter_funcs);
439 this->stations.ForceRebuild();
440 this->stations.NeedResort();
441 this->SortStationsList();
442
443 this->CreateNestedTree();
444 this->vscroll = this->GetScrollbar(WID_STL_SCROLLBAR);
445 this->FinishInitNested(window_number);
446 this->owner = this->window_number;
447
448 this->querystrings[WID_STL_FILTER] = &this->name_editbox;
449 this->name_editbox.cancel_button = QueryString::ACTION_CLEAR;
450
451 if (this->filter.cargoes == ALL_CARGOTYPES) this->filter.cargoes = _cargo_mask;
452
453 for (StationFacility facil : this->filter.facilities) {
454 this->LowerWidget(WID_STL_TRAIN + to_underlying(facil));
455 }
456
457 this->GetWidget<NWidgetCore>(WID_STL_SORTDROPBTN)->SetString(CompanyStationsWindow::sorter_names[this->stations.SortType()]);
458 }
459
462 {
463 /* Save filter state. */
464 this->filter.last_sorting = this->stations.GetListing();
465 CompanyStationsWindow::initial_state = this->filter;
466 }
467
468 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
469 {
470 switch (widget) {
471 case WID_STL_SORTBY: {
473 d.width += padding.width + Window::SortButtonWidth() * 2; // Doubled since the string is centred and it also looks better.
474 d.height += padding.height;
475 size = maxdim(size, d);
476 break;
477 }
478
479 case WID_STL_SORTDROPBTN: {
481 d.width += padding.width;
482 d.height += padding.height;
483 size = maxdim(size, d);
484 break;
485 }
486
487 case WID_STL_LIST:
489 size.height = padding.height + 5 * resize.height;
490
491 /* Determine appropriate width for mini station rating graph */
492 this->rating_width = 0;
493 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
494 this->rating_width = std::max(this->rating_width, GetStringBoundingBox(cs->abbrev, FontSize::Small).width);
495 }
496 /* Approximately match original 16 pixel wide rating bars by multiplying string width by 1.6 */
497 this->rating_width = this->rating_width * 16 / 10;
498 break;
499 }
500 }
501
502 void OnPaint() override
503 {
504 this->BuildStationsList(this->window_number);
505 this->SortStationsList();
506
507 this->DrawWidgets();
508 }
509
510 void DrawWidget(const Rect &r, WidgetID widget) const override
511 {
512 switch (widget) {
513 case WID_STL_SORTBY:
514 /* draw arrow pointing up/down for ascending/descending sorting */
515 this->DrawSortButton(WID_STL_SORTBY, this->stations.IsDescSortOrder());
516 break;
517
518 case WID_STL_LIST: {
519 bool rtl = _current_text_dir == TD_RTL;
520 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
521 uint line_height = this->GetWidget<NWidgetBase>(widget)->resize_y;
522 /* Spacing between station name and first rating graph. */
523 int text_spacing = WidgetDimensions::scaled.hsep_wide;
524 /* Spacing between additional rating graphs. */
525 int rating_spacing = WidgetDimensions::scaled.hsep_normal;
526
527 auto [first, last] = this->vscroll->GetVisibleRangeIterators(this->stations);
528 for (auto it = first; it != last; ++it) {
529 const Station *st = *it;
530 assert(st->xy != INVALID_TILE);
531
532 /* Do not do the complex check HasStationInUse here, it may be even false
533 * when the order had been removed and the station list hasn't been removed yet */
534 assert(st->owner == owner || st->owner == OWNER_NONE);
535
536 int x = DrawString(tr.left, tr.right, tr.top + (line_height - GetCharacterHeight(FontSize::Normal)) / 2, GetString(STR_STATION_LIST_STATION, st->index, st->facilities));
537 x += rtl ? -text_spacing : text_spacing;
538
539 /* show cargo waiting and station ratings */
540 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
541 CargoType cargo_type = cs->Index();
542 if (st->goods[cargo_type].HasRating()) {
543 /* For RTL we work in exactly the opposite direction. So
544 * decrement the space needed first, then draw to the left
545 * instead of drawing to the left and then incrementing
546 * the space. */
547 if (rtl) {
548 x -= rating_width + rating_spacing;
549 if (x < tr.left) break;
550 }
551 StationsWndShowStationRating(x, x + rating_width, tr.top, cargo_type, st->goods[cargo_type].TotalCount(), st->goods[cargo_type].rating);
552 if (!rtl) {
553 x += rating_width + rating_spacing;
554 if (x > tr.right) break;
555 }
556 }
557 }
558 tr.top += line_height;
559 }
560
561 if (this->vscroll->GetCount() == 0) { // company has no stations
562 DrawString(tr.left, tr.right, tr.top + (line_height - GetCharacterHeight(FontSize::Normal)) / 2, STR_STATION_LIST_NONE);
563 return;
564 }
565 break;
566 }
567 }
568 }
569
570 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
571 {
572 if (widget == WID_STL_CAPTION) {
573 return GetString(STR_STATION_LIST_CAPTION, this->window_number, this->vscroll->GetCount());
574 }
575
576 if (widget == WID_STL_CARGODROPDOWN) {
577 if (this->filter.cargoes.None()) return GetString(this->filter.include_no_rating ? STR_STATION_LIST_CARGO_FILTER_ONLY_NO_RATING : STR_STATION_LIST_CARGO_FILTER_NO_CARGO_TYPES);
578 if (this->filter.cargoes == _cargo_mask) return GetString(this->filter.include_no_rating ? STR_STATION_LIST_CARGO_FILTER_ALL_AND_NO_RATING : STR_CARGO_TYPE_FILTER_ALL);
579 if (this->filter.cargoes.Count() == 1 && !this->filter.include_no_rating) return GetString(CargoSpec::Get(*this->filter.cargoes.begin())->name);
580 return GetString(STR_STATION_LIST_CARGO_FILTER_MULTIPLE);
581 }
582
583 return this->Window::GetWidgetString(widget, stringid);
584 }
585
586 DropDownList BuildCargoDropDownList(bool expanded) const
587 {
588 /* Define a custom item consisting of check mark, count string, icon and name string. */
590
591 DropDownList list;
592 list.push_back(MakeDropDownListStringItem(STR_STATION_LIST_CARGO_FILTER_SELECT_ALL, CargoFilterCriteria::CF_SELECT_ALL));
593 list.push_back(MakeDropDownListDividerItem());
594
595 bool any_hidden = false;
596
597 uint16_t count = this->stations_per_cargo_type_no_rating;
598 if (count == 0 && !expanded) {
599 any_hidden = true;
600 } else {
601 list.push_back(std::make_unique<DropDownString<DropDownListCheckedItem, FontSize::Small, true>>(fmt::format("{}", count), 0, this->filter.include_no_rating, GetString(STR_STATION_LIST_CARGO_FILTER_NO_RATING), CargoFilterCriteria::CF_NO_RATING, false, count == 0));
602 }
603
604 Dimension d = GetLargestCargoIconSize();
605 for (const CargoSpec *cs : _sorted_cargo_specs) {
606 count = this->stations_per_cargo_type[cs->Index()];
607 if (count == 0 && !expanded) {
608 any_hidden = true;
609 } else {
610 list.push_back(std::make_unique<DropDownListCargoItem>(this->filter.cargoes.Test(cs->Index()), fmt::format("{}", count), d, cs->GetCargoIcon(), PAL_NONE, GetString(cs->name), cs->Index(), false, count == 0));
611 }
612 }
613
614 if (!expanded && any_hidden) {
615 if (list.size() > 2) list.push_back(MakeDropDownListDividerItem());
616 list.push_back(MakeDropDownListStringItem(STR_STATION_LIST_CARGO_FILTER_EXPAND, CargoFilterCriteria::CF_EXPAND_LIST));
617 }
618
619 return list;
620 }
621
622 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
623 {
624 switch (widget) {
625 case WID_STL_LIST: {
626 auto it = this->vscroll->GetScrolledItemFromWidget(this->stations, pt.y, this, WID_STL_LIST, WidgetDimensions::scaled.framerect.top);
627 if (it == this->stations.end()) return; // click out of list bound
628
629 const Station *st = *it;
630 /* do not check HasStationInUse - it is slow and may be invalid */
631 assert(st->owner == this->window_number || st->owner == OWNER_NONE);
632
633 if (IsCtrlPressed()) {
635 } else {
637 }
638 break;
639 }
640
641 case WID_STL_TRAIN:
642 case WID_STL_TRUCK:
643 case WID_STL_BUS:
644 case WID_STL_AIRPLANE:
645 case WID_STL_SHIP:
646 if (IsCtrlPressed()) {
647 this->filter.facilities.Flip(static_cast<StationFacility>(widget - WID_STL_TRAIN));
648 this->ToggleWidgetLoweredState(widget);
649 } else {
650 for (StationFacility facil : this->filter.facilities) {
652 }
653 this->filter.facilities = static_cast<StationFacility>(widget - WID_STL_TRAIN);
654 this->LowerWidget(widget);
655 }
656 this->stations.ForceRebuild();
657 this->SetDirty();
658 SndClickBeep();
659 break;
660
661 case WID_STL_FACILALL:
662 for (WidgetID i = WID_STL_TRAIN; i <= WID_STL_SHIP; i++) {
663 this->LowerWidget(i);
664 }
665
667 this->stations.ForceRebuild();
668 this->SetDirty();
669 break;
670
671 case WID_STL_SORTBY: // flip sorting method asc/desc
672 this->stations.ToggleSortOrder();
673 this->SetDirty();
674 break;
675
676 case WID_STL_SORTDROPBTN: // select sorting criteria dropdown menu
678 break;
679
681 static std::string cargo_filter;
682 this->filter_expanded = false;
683 ShowDropDownList(this, this->BuildCargoDropDownList(this->filter_expanded), -1, widget, 0, {DropDownOption::Persist, DropDownOption::Filterable}, &cargo_filter);
684 break;
685 }
686 }
687 }
688
689 void OnDropdownSelect(WidgetID widget, int index, int) override
690 {
691 if (widget == WID_STL_SORTDROPBTN) {
692 if (this->stations.SortType() != index) {
693 this->stations.SetSortType(index);
694
695 /* Display the current sort variant */
697
698 this->SetDirty();
699 }
700 }
701
702 if (widget == WID_STL_CARGODROPDOWN) {
703 FilterState oldstate = this->filter;
704
705 if (index >= 0 && index < NUM_CARGO) {
706 if (IsCtrlPressed()) {
707 this->filter.cargoes.Flip(static_cast<CargoType>(index));
708 } else {
709 this->filter.cargoes = static_cast<CargoType>(index);
710 this->filter.include_no_rating = false;
711 }
712 } else if (index == CargoFilterCriteria::CF_NO_RATING) {
713 if (IsCtrlPressed()) {
714 this->filter.include_no_rating = !this->filter.include_no_rating;
715 } else {
716 this->filter.include_no_rating = true;
717 this->filter.cargoes.Reset();
718 }
719 } else if (index == CargoFilterCriteria::CF_SELECT_ALL) {
720 this->filter.cargoes = _cargo_mask;
721 this->filter.include_no_rating = true;
722 } else if (index == CargoFilterCriteria::CF_EXPAND_LIST) {
723 this->filter_expanded = true;
724 ReplaceDropDownList(this, this->BuildCargoDropDownList(this->filter_expanded));
725 return;
726 }
727
728 if (oldstate.cargoes != this->filter.cargoes || oldstate.include_no_rating != this->filter.include_no_rating) {
729 this->stations.ForceRebuild();
730 this->SetDirty();
731
732 /* Only refresh the list if it's changed. */
733 if (IsCtrlPressed()) ReplaceDropDownList(this, this->BuildCargoDropDownList(this->filter_expanded));
734 }
735
736 /* Always close the list if ctrl is not pressed. */
737 if (!IsCtrlPressed()) this->CloseChildWindows(WindowClass::DropdownMenu);
738 }
739 }
740
741 void OnGameTick() override
742 {
743 if (this->stations.NeedResort()) {
744 Debug(Facility::Misc, Severity::Notice, "Periodic rebuild station list company {}", static_cast<int>(this->window_number));
745 this->SetDirty();
746 }
747 }
748
749 void OnResize() override
750 {
751 this->vscroll->SetCapacityFromWidget(this, WID_STL_LIST, WidgetDimensions::scaled.framerect.Vertical());
752 }
753
754 void OnEditboxChanged(WidgetID wid) override
755 {
756 if (wid == WID_STL_FILTER) {
757 this->string_filter.SetFilterTerm(this->name_editbox.text.GetText());
758 this->InvalidateData(TDIWD_FORCE_REBUILD);
759 }
760 }
761
767 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
768 {
769 if (data == 0) {
770 /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
771 this->stations.ForceRebuild();
772 } else {
773 this->stations.ForceResort();
774 }
775 }
776};
777
778/* Available station sorting functions */
779const std::initializer_list<GUIStationList::SortFunction * const> CompanyStationsWindow::sorter_funcs = {
786};
787
788static constexpr std::initializer_list<NWidgetPart> _nested_company_stations_widgets = {
795 EndContainer(),
797 NWidget(WWT_TEXTBTN, Colours::Grey, WID_STL_TRAIN), SetAspect(WidgetDimensions::ASPECT_VEHICLE_ICON), SetStringTip(STR_TRAIN, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE_TOOLTIP), SetFill(0, 1),
798 NWidget(WWT_TEXTBTN, Colours::Grey, WID_STL_TRUCK), SetAspect(WidgetDimensions::ASPECT_VEHICLE_ICON), SetStringTip(STR_LORRY, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE_TOOLTIP), SetFill(0, 1),
799 NWidget(WWT_TEXTBTN, Colours::Grey, WID_STL_BUS), SetAspect(WidgetDimensions::ASPECT_VEHICLE_ICON), SetStringTip(STR_BUS, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE_TOOLTIP), SetFill(0, 1),
800 NWidget(WWT_TEXTBTN, Colours::Grey, WID_STL_SHIP), SetAspect(WidgetDimensions::ASPECT_VEHICLE_ICON), SetStringTip(STR_SHIP, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE_TOOLTIP), SetFill(0, 1),
801 NWidget(WWT_TEXTBTN, Colours::Grey, WID_STL_AIRPLANE), SetAspect(WidgetDimensions::ASPECT_VEHICLE_ICON), SetStringTip(STR_PLANE, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE_TOOLTIP), SetFill(0, 1),
802 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_STL_FACILALL), SetAspect(WidgetDimensions::ASPECT_VEHICLE_ICON), SetStringTip(STR_ABBREV_ALL, STR_STATION_LIST_SELECT_ALL_FACILITIES_TOOLTIP), SetTextStyle(TextColour::Black, FontSize::Small), SetFill(0, 1),
804 NWidget(WWT_DROPDOWN, Colours::Grey, WID_STL_CARGODROPDOWN), SetFill(1, 0), SetToolTip(STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE_TOOLTIP),
806 EndContainer(),
808 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_STL_SORTBY), SetMinimalSize(0, 12), SetStringTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
809 NWidget(WWT_DROPDOWN, Colours::Grey, WID_STL_SORTDROPBTN), SetMinimalSize(0, 12), SetStringTip(STR_SORT_BY_NAME, STR_TOOLTIP_SORT_CRITERIA), // widget_data gets overwritten.
810 NWidget(WWT_EDITBOX, Colours::Grey, WID_STL_FILTER), SetFill(1, 0), SetResize(1, 0), SetStringTip(STR_LIST_FILTER_OSKTITLE, STR_LIST_FILTER_TOOLTIP),
811 EndContainer(),
817 EndContainer(),
818 EndContainer(),
819};
820
823 WindowPosition::Automatic, "list_stations", 358, 162,
824 WindowClass::StationList, WindowClass::None,
825 {},
826 _nested_company_stations_widgets
827);
828
834void ShowCompanyStations(CompanyID company)
835{
836 if (!Company::IsValidID(company)) return;
837
839}
840
841static constexpr std::initializer_list<NWidgetPart> _nested_station_view_widgets = {
844 NWidget(WWT_PUSHIMGBTN, Colours::Grey, WID_SV_RENAME), SetAspect(WidgetDimensions::ASPECT_RENAME), SetSpriteTip(SPR_RENAME, STR_STATION_VIEW_EDIT_TOOLTIP),
846 NWidget(WWT_PUSHIMGBTN, Colours::Grey, WID_SV_LOCATION), SetAspect(WidgetDimensions::ASPECT_LOCATION), SetSpriteTip(SPR_GOTO_LOCATION, STR_STATION_VIEW_CENTER_TOOLTIP),
850 EndContainer(),
852 NWidget(WWT_TEXTBTN, Colours::Grey, WID_SV_GROUP), SetMinimalSize(81, 12), SetFill(1, 1), SetStringTip(STR_STATION_VIEW_GROUP),
853 NWidget(WWT_DROPDOWN, Colours::Grey, WID_SV_GROUP_BY), SetMinimalSize(168, 12), SetResize(1, 0), SetFill(0, 1), SetToolTip(STR_TOOLTIP_GROUP_ORDER),
854 EndContainer(),
856 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_SV_SORT_ORDER), SetMinimalSize(81, 12), SetFill(1, 1), SetStringTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
857 NWidget(WWT_DROPDOWN, Colours::Grey, WID_SV_SORT_BY), SetMinimalSize(168, 12), SetResize(1, 0), SetFill(0, 1), SetToolTip(STR_TOOLTIP_SORT_CRITERIA),
858 EndContainer(),
862 EndContainer(),
866 SetStringTip(STR_STATION_VIEW_RATINGS_BUTTON, STR_STATION_VIEW_RATINGS_TOOLTIP),
869 SetStringTip(STR_STATION_VIEW_CLOSE_AIRPORT, STR_STATION_VIEW_CLOSE_AIRPORT_TOOLTIP),
870 EndContainer(),
871 NWidget(WWT_TEXTBTN, Colours::Grey, WID_SV_CATCHMENT), SetMinimalSize(45, 12), SetResize(1, 0), SetFill(1, 1), SetStringTip(STR_BUTTON_CATCHMENT, STR_TOOLTIP_CATCHMENT),
872 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_SV_GRAPH), SetResize(1, 0), SetFill(1, 0), SetStringTip(STR_STATION_VIEW_GRAPH, STR_STATION_VIEW_GRAPH_TOOLTIP),
873 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_SV_TRAINS), SetAspect(WidgetDimensions::ASPECT_VEHICLE_ICON), SetFill(0, 1), SetStringTip(STR_TRAIN, STR_STATION_VIEW_SCHEDULED_TRAINS_TOOLTIP),
874 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_SV_ROADVEHS), SetAspect(WidgetDimensions::ASPECT_VEHICLE_ICON), SetFill(0, 1), SetStringTip(STR_LORRY, STR_STATION_VIEW_SCHEDULED_ROAD_VEHICLES_TOOLTIP),
875 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_SV_SHIPS), SetAspect(WidgetDimensions::ASPECT_VEHICLE_ICON), SetFill(0, 1), SetStringTip(STR_SHIP, STR_STATION_VIEW_SCHEDULED_SHIPS_TOOLTIP),
876 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_SV_PLANES), SetAspect(WidgetDimensions::ASPECT_VEHICLE_ICON), SetFill(0, 1), SetStringTip(STR_PLANE, STR_STATION_VIEW_SCHEDULED_AIRCRAFT_TOOLTIP),
878 EndContainer(),
879};
880
881enum SortOrder : uint8_t {
882 SO_DESCENDING,
883 SO_ASCENDING
884};
885
886class CargoDataEntry;
887
896
897class CargoSorter {
898public:
899 using is_transparent = void;
900 CargoSorter(CargoSortType t = CargoSortType::StationID, SortOrder o = SO_ASCENDING) : type(t), order(o) {}
901 CargoSortType GetSortType() {return this->type;}
902 bool operator()(const CargoDataEntry &cd1, const CargoDataEntry &cd2) const;
903 bool operator()(const CargoDataEntry &cd1, const std::unique_ptr<CargoDataEntry> &cd2) const { return this->operator()(cd1, *cd2); }
904 bool operator()(const std::unique_ptr<CargoDataEntry> &cd1, const CargoDataEntry &cd2) const { return this->operator()(*cd1, cd2); }
905 bool operator()(const std::unique_ptr<CargoDataEntry> &cd1, const std::unique_ptr<CargoDataEntry> &cd2) const { return this->operator()(*cd1, *cd2); }
906
907private:
908 CargoSortType type;
909 SortOrder order;
910
911 template <class Tid>
912 bool SortId(Tid st1, Tid st2) const;
913 bool SortCount(const CargoDataEntry &cd1, const CargoDataEntry &cd2) const;
914 bool SortStation(StationID st1, StationID st2) const;
915};
916
917typedef std::set<std::unique_ptr<CargoDataEntry>, CargoSorter> CargoDataSet;
918
924class CargoDataEntry {
925public:
926 CargoDataEntry();
928
934 CargoDataEntry &InsertOrRetrieve(StationID station)
935 {
936 return this->InsertOrRetrieve<StationID>(station);
937 }
938
945 {
946 return this->InsertOrRetrieve<CargoType>(cargo);
947 }
948
949 void Update(uint count);
950
955 void Remove(StationID station)
956 {
957 CargoDataEntry t(station);
958 this->Remove(t);
959 }
960
966 {
967 CargoDataEntry t(cargo);
968 this->Remove(t);
969 }
970
976 CargoDataEntry *Retrieve(StationID station) const
977 {
978 CargoDataEntry t(station);
979 return this->Retrieve(this->children->find(t));
980 }
981
987 CargoDataEntry *Retrieve(CargoType cargo) const
988 {
989 CargoDataEntry t(cargo);
990 return this->Retrieve(this->children->find(t));
991 }
992
993 void Resort(CargoSortType type, SortOrder order);
994
999 StationID GetStation() const { return this->station; }
1000
1005 CargoType GetCargo() const { return this->cargo; }
1006
1011 uint GetCount() const { return this->count; }
1012
1017 CargoDataEntry *GetParent() const { return this->parent; }
1018
1023 uint GetNumChildren() const { return this->num_children; }
1024
1029 CargoDataSet::iterator Begin() const { return this->children->begin(); }
1030
1035 CargoDataSet::iterator End() const { return this->children->end(); }
1036
1041 bool HasTransfers() const { return this->transfers; }
1042
1047 void SetTransfers(bool value) { this->transfers = value; }
1048
1049 void Clear();
1050
1053 CargoDataEntry(StationID station);
1055
1056private:
1057 CargoDataEntry *Retrieve(CargoDataSet::iterator i) const;
1058
1059 template <class Tid>
1061
1062 void Remove(CargoDataEntry &entry);
1063 void IncrementSize();
1064
1065 CargoDataEntry *parent;
1066 const union {
1067 StationID station;
1068 struct {
1071 };
1072 };
1074 uint count;
1075 std::unique_ptr<CargoDataSet> children;
1076};
1077
1078CargoDataEntry::CargoDataEntry() :
1079 parent(nullptr),
1080 station(StationID::Invalid()),
1081 num_children(0),
1082 count(0),
1083 children(std::make_unique<CargoDataSet>(CargoSorter(CargoSortType::CargoType)))
1084{}
1085
1086CargoDataEntry::CargoDataEntry(CargoType cargo, uint count, CargoDataEntry *parent) :
1087 parent(parent),
1088 cargo(cargo),
1089 num_children(0),
1090 count(count),
1091 children(std::make_unique<CargoDataSet>())
1092{}
1093
1094CargoDataEntry::CargoDataEntry(StationID station, uint count, CargoDataEntry *parent) :
1095 parent(parent),
1096 station(station),
1097 num_children(0),
1098 count(count),
1099 children(std::make_unique<CargoDataSet>())
1100{}
1101
1102CargoDataEntry::CargoDataEntry(StationID station) :
1103 parent(nullptr),
1104 station(station),
1105 num_children(0),
1106 count(0),
1107 children(nullptr)
1108{}
1109
1110CargoDataEntry::CargoDataEntry(CargoType cargo) :
1111 parent(nullptr),
1112 cargo(cargo),
1113 num_children(0),
1114 count(0),
1115 children(nullptr)
1116{}
1117
1120{
1121 this->Clear();
1122}
1123
1128{
1129 if (this->children != nullptr) this->children->clear();
1130 if (this->parent != nullptr) this->parent->count -= this->count;
1131 this->count = 0;
1132 this->num_children = 0;
1133}
1134
1141void CargoDataEntry::Remove(CargoDataEntry &entry)
1142{
1143 CargoDataSet::iterator i = this->children->find(entry);
1144 if (i != this->children->end()) this->children->erase(i);
1145}
1146
1153template <class Tid>
1154CargoDataEntry &CargoDataEntry::InsertOrRetrieve(Tid child_id)
1155{
1156 CargoDataEntry tmp(child_id);
1157 CargoDataSet::iterator i = this->children->find(tmp);
1158 if (i == this->children->end()) {
1159 IncrementSize();
1160 return **(this->children->insert(std::make_unique<CargoDataEntry>(child_id, 0, this)).first);
1161 } else {
1162 assert(this->children->value_comp().GetSortType() != CargoSortType::Count);
1163 return **i;
1164 }
1165}
1166
1173{
1174 this->count += count;
1175 if (this->parent != nullptr) this->parent->Update(count);
1176}
1177
1182{
1183 ++this->num_children;
1184 if (this->parent != nullptr) this->parent->IncrementSize();
1185}
1186
1187void CargoDataEntry::Resort(CargoSortType type, SortOrder order)
1188{
1189 auto new_children = std::make_unique<CargoDataSet>(CargoSorter(type, order));
1190 new_children->merge(*this->children);
1191 this->children = std::move(new_children);
1192}
1193
1194CargoDataEntry *CargoDataEntry::Retrieve(CargoDataSet::iterator i) const
1195{
1196 if (i == this->children->end()) {
1197 return nullptr;
1198 } else {
1199 assert(this->children->value_comp().GetSortType() != CargoSortType::Count);
1200 return i->get();
1201 }
1202}
1203
1204bool CargoSorter::operator()(const CargoDataEntry &cd1, const CargoDataEntry &cd2) const
1205{
1206 switch (this->type) {
1208 return this->SortId<StationID>(cd1.GetStation(), cd2.GetStation());
1210 return this->SortId<CargoType>(cd1.GetCargo(), cd2.GetCargo());
1212 return this->SortCount(cd1, cd2);
1214 return this->SortStation(cd1.GetStation(), cd2.GetStation());
1215 default:
1216 NOT_REACHED();
1217 }
1218}
1219
1220template <class Tid>
1221bool CargoSorter::SortId(Tid st1, Tid st2) const
1222{
1223 return (this->order == SO_ASCENDING) ? st1 < st2 : st2 < st1;
1224}
1225
1226bool CargoSorter::SortCount(const CargoDataEntry &cd1, const CargoDataEntry &cd2) const
1227{
1228 uint c1 = cd1.GetCount();
1229 uint c2 = cd2.GetCount();
1230 if (c1 == c2) {
1231 return this->SortStation(cd1.GetStation(), cd2.GetStation());
1232 } else if (this->order == SO_ASCENDING) {
1233 return c1 < c2;
1234 } else {
1235 return c2 < c1;
1236 }
1237}
1238
1239bool CargoSorter::SortStation(StationID st1, StationID st2) const
1240{
1241 if (!Station::IsValidID(st1)) {
1242 return Station::IsValidID(st2) ? this->order == SO_ASCENDING : this->SortId(st1, st2);
1243 } else if (!Station::IsValidID(st2)) {
1244 return order == SO_DESCENDING;
1245 }
1246
1247 int res = StrNaturalCompare(Station::Get(st1)->GetCachedName(), Station::Get(st2)->GetCachedName()); // Sort by name (natural sorting).
1248 if (res == 0) {
1249 return this->SortId(st1, st2);
1250 } else {
1251 return (this->order == SO_ASCENDING) ? res < 0 : res > 0;
1252 }
1253}
1254
1258struct StationViewWindow : public Window {
1262 struct RowDisplay {
1263 RowDisplay(CargoDataEntry *f, StationID n) : filter(f), next_station(n) {}
1264 RowDisplay(CargoDataEntry *f, CargoType n) : filter(f), next_cargo(n) {}
1265
1270 union {
1274 StationID next_station;
1275
1280 };
1281 };
1282
1283 typedef std::vector<RowDisplay> CargoDataVector;
1284
1285 static const int NUM_COLUMNS = 4;
1286
1290 enum Invalidation : uint16_t {
1291 INV_FLOWS = 0x100,
1292 INV_CARGO = 0x200
1293 };
1294
1304
1308 enum Mode : uint8_t {
1311 };
1312
1316 int line_height = 0;
1318 Scrollbar *vscroll = nullptr;
1319
1320 /* Height of the #WID_SV_ACCEPT_RATING_LIST widget for different views. */
1321 static constexpr uint RATING_LINES = 13;
1322 static constexpr uint ACCEPTS_LINES = 3;
1323
1325 static inline const StringID sort_names[] = {
1326 STR_STATION_VIEW_WAITING_STATION,
1327 STR_STATION_VIEW_WAITING_AMOUNT,
1328 STR_STATION_VIEW_PLANNED_STATION,
1329 STR_STATION_VIEW_PLANNED_AMOUNT,
1330 };
1331
1332 static inline const StringID group_names[] = {
1333 STR_STATION_VIEW_GROUP_S_V_D,
1334 STR_STATION_VIEW_GROUP_S_D_V,
1335 STR_STATION_VIEW_GROUP_V_S_D,
1336 STR_STATION_VIEW_GROUP_V_D_S,
1337 STR_STATION_VIEW_GROUP_D_S_V,
1338 STR_STATION_VIEW_GROUP_D_V_S,
1339 };
1340
1347 std::array<CargoSortType, NUM_COLUMNS> sortings{};
1348
1350 std::array<SortOrder, NUM_COLUMNS> sort_orders{};
1351
1352 int scroll_to_row = INT_MAX;
1355 std::array<Grouping, NUM_COLUMNS> groupings;
1356
1359 CargoDataVector displayed_rows{};
1360
1362 {
1363 this->CreateNestedTree();
1365 this->vscroll = this->GetScrollbar(WID_SV_SCROLLBAR);
1366 /* Nested widget tree creation is done in two steps to ensure that this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS) exists in UpdateWidgetSize(). */
1367 this->FinishInitNested(window_number);
1368
1369 this->groupings[0] = GR_CARGO;
1370 this->sortings[0] = CargoSortType::AsGrouping;
1371 this->SelectGroupBy(_settings_client.gui.station_gui_group_order);
1372 this->SelectSortBy(_settings_client.gui.station_gui_sort_by);
1373 this->sort_orders[0] = SO_ASCENDING;
1374 this->SelectSortOrder((SortOrder)_settings_client.gui.station_gui_sort_order);
1375 this->owner = Station::Get(window_number)->owner;
1376 }
1377
1378 void OnInit() override
1379 {
1380 this->cargo_icon_size = GetLargestCargoIconSize();
1381 this->line_height = std::max<int>(GetCharacterHeight(FontSize::Normal), this->cargo_icon_size.height);
1382 this->expand_shrink_width = std::max(GetCharacterWidth(FontSize::Normal, '-'), GetCharacterWidth(FontSize::Normal, '+'));
1383 }
1384
1385 void Close([[maybe_unused]] int data = 0) override
1386 {
1387 CloseWindowById(WindowClass::TrainList, VehicleListIdentifier(VehicleListType::Station, VehicleType::Train, this->owner, this->window_number).ToWindowNumber(), false);
1388 CloseWindowById(WindowClass::RoadVehicleList, VehicleListIdentifier(VehicleListType::Station, VehicleType::Road, this->owner, this->window_number).ToWindowNumber(), false);
1389 CloseWindowById(WindowClass::ShipList, VehicleListIdentifier(VehicleListType::Station, VehicleType::Ship, this->owner, this->window_number).ToWindowNumber(), false);
1390 CloseWindowById(WindowClass::AircraftList, VehicleListIdentifier(VehicleListType::Station, VehicleType::Aircraft, this->owner, this->window_number).ToWindowNumber(), false);
1391
1392 SetViewportCatchmentStation(Station::Get(this->window_number), false);
1393 this->Window::Close();
1394 }
1395
1406 void ShowCargo(CargoDataEntry *data, CargoType cargo, StationID source, StationID next, StationID dest, uint count)
1407 {
1408 if (count == 0) return;
1409 bool auto_distributed = _settings_game.linkgraph.GetDistributionType(cargo) != DistributionType::Manual;
1410 const CargoDataEntry *expand = &this->expanded_rows;
1411 for (int i = 0; i < NUM_COLUMNS && expand != nullptr; ++i) {
1412 switch (groupings[i]) {
1413 case GR_CARGO:
1414 assert(i == 0);
1415 data = &data->InsertOrRetrieve(cargo);
1416 data->SetTransfers(source != this->window_number);
1417 expand = expand->Retrieve(cargo);
1418 break;
1419 case GR_SOURCE:
1420 if (auto_distributed || source != this->window_number) {
1421 data = &data->InsertOrRetrieve(source);
1422 expand = expand->Retrieve(source);
1423 }
1424 break;
1425 case GR_NEXT:
1426 if (auto_distributed) {
1427 data = &data->InsertOrRetrieve(next);
1428 expand = expand->Retrieve(next);
1429 }
1430 break;
1431 case GR_DESTINATION:
1432 if (auto_distributed) {
1433 data = &data->InsertOrRetrieve(dest);
1434 expand = expand->Retrieve(dest);
1435 }
1436 break;
1437 }
1438 }
1439 data->Update(count);
1440 }
1441
1442 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
1443 {
1444 switch (widget) {
1445 case WID_SV_WAITING:
1446 fill.height = resize.height = this->line_height;
1447 size.height = 4 * resize.height + padding.height;
1448 break;
1449
1451 size.height = ((this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS)->GetString() == STR_STATION_VIEW_RATINGS_BUTTON) ? this->accepts_lines : this->rating_lines) * GetCharacterHeight(FontSize::Normal) + padding.height;
1452 break;
1453 }
1454 }
1455
1456 void OnPaint() override
1457 {
1458 const Station *st = Station::Get(this->window_number);
1459 CargoDataEntry cargo;
1460 BuildCargoList(&cargo, st);
1461
1462 this->vscroll->SetCount(cargo.GetNumChildren()); // update scrollbar
1463
1464 /* disable some buttons */
1470 this->SetWidgetDisabledState(WID_SV_CLOSE_AIRPORT, !st->facilities.Test(StationFacility::Airport) || st->owner != _local_company || st->owner == OWNER_NONE); // Also consider SE, where _local_company == OWNER_NONE
1472
1476
1477 this->DrawWidgets();
1478
1479 if (!this->IsShaded()) {
1480 /* Draw 'accepted cargo' or 'cargo ratings'. */
1482 const Rect r = wid->GetCurrentRect();
1483 if (this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS)->GetString() == STR_STATION_VIEW_RATINGS_BUTTON) {
1484 int lines = this->DrawAcceptedCargo(r);
1485 if (lines > this->accepts_lines) { // Resize the widget, and perform re-initialization of the window.
1486 this->accepts_lines = lines;
1487 this->ReInit();
1488 return;
1489 }
1490 } else {
1491 int lines = this->DrawCargoRatings(r);
1492 if (lines > this->rating_lines) { // Resize the widget, and perform re-initialization of the window.
1493 this->rating_lines = lines;
1494 this->ReInit();
1495 return;
1496 }
1497 }
1498
1499 /* Draw arrow pointing up/down for ascending/descending sorting */
1500 this->DrawSortButton(WID_SV_SORT_ORDER, sort_orders[1] != SO_ASCENDING);
1501
1502 int pos = this->vscroll->GetPosition();
1503
1504 int maxrows = this->vscroll->GetCapacity();
1505
1506 displayed_rows.clear();
1507
1508 /* Draw waiting cargo. */
1510 Rect waiting_rect = nwi->GetCurrentRect().Shrink(WidgetDimensions::scaled.framerect);
1511 this->DrawEntries(cargo, waiting_rect, pos, maxrows, 0);
1512 scroll_to_row = INT_MAX;
1513 }
1514 }
1515
1516 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
1517 {
1518 if (widget == WID_SV_CAPTION) {
1519 const Station *st = Station::Get(this->window_number);
1520 return GetString(STR_STATION_VIEW_CAPTION, st->index, st->facilities);
1521 }
1522
1523 return this->Window::GetWidgetString(widget, stringid);
1524 }
1525
1532 {
1533 const Station *st = Station::Get(this->window_number);
1534 CargoDataEntry &entry = cached_destinations.InsertOrRetrieve(cargo);
1535 entry.Clear();
1536
1537 if (!st->goods[cargo].HasData()) return;
1538
1539 for (const auto &it : st->goods[cargo].GetData().flows) {
1540 StationID from = it.first;
1541 CargoDataEntry &source_entry = entry.InsertOrRetrieve(from);
1542 uint32_t prev_count = 0;
1543 for (const auto &flow_it : *it.second.GetShares()) {
1544 StationID via = flow_it.second;
1545 CargoDataEntry &via_entry = source_entry.InsertOrRetrieve(via);
1546 if (via == this->window_number) {
1547 via_entry.InsertOrRetrieve(via).Update(flow_it.first - prev_count);
1548 } else {
1549 EstimateDestinations(cargo, from, via, flow_it.first - prev_count, via_entry);
1550 }
1551 prev_count = flow_it.first;
1552 }
1553 }
1554 }
1555
1565 void EstimateDestinations(CargoType cargo, StationID source, StationID next, uint count, CargoDataEntry &dest)
1566 {
1567 if (Station::IsValidID(next) && Station::IsValidID(source)) {
1568 GoodsEntry &ge = Station::Get(next)->goods[cargo];
1569 if (!ge.HasData()) return;
1570
1571 CargoDataEntry tmp;
1572 const FlowStatMap &flowmap = ge.GetData().flows;
1573 FlowStatMap::const_iterator map_it = flowmap.find(source);
1574 if (map_it != flowmap.end()) {
1575 const FlowStat::SharesMap *shares = map_it->second.GetShares();
1576 uint32_t prev_count = 0;
1577 for (FlowStat::SharesMap::const_iterator i = shares->begin(); i != shares->end(); ++i) {
1578 tmp.InsertOrRetrieve(i->second).Update(i->first - prev_count);
1579 prev_count = i->first;
1580 }
1581 }
1582
1583 if (tmp.GetCount() == 0) {
1584 dest.InsertOrRetrieve(StationID::Invalid()).Update(count);
1585 } else {
1586 uint sum_estimated = 0;
1587 while (sum_estimated < count) {
1588 for (CargoDataSet::iterator i = tmp.Begin(); i != tmp.End() && sum_estimated < count; ++i) {
1589 CargoDataEntry &child = **i;
1590 uint estimate = DivideApprox(child.GetCount() * count, tmp.GetCount());
1591 if (estimate == 0) estimate = 1;
1592
1593 sum_estimated += estimate;
1594 if (sum_estimated > count) {
1595 estimate -= sum_estimated - count;
1596 sum_estimated = count;
1597 }
1598
1599 if (estimate > 0) {
1600 if (child.GetStation() == next) {
1601 dest.InsertOrRetrieve(next).Update(estimate);
1602 } else {
1603 EstimateDestinations(cargo, source, child.GetStation(), estimate, dest);
1604 }
1605 }
1606 }
1607
1608 }
1609 }
1610 } else {
1611 dest.InsertOrRetrieve(StationID::Invalid()).Update(count);
1612 }
1613 }
1614
1621 void BuildFlowList(CargoType cargo, const FlowStatMap &flows, CargoDataEntry *entry)
1622 {
1623 const CargoDataEntry *source_dest = this->cached_destinations.Retrieve(cargo);
1624 for (FlowStatMap::const_iterator it = flows.begin(); it != flows.end(); ++it) {
1625 StationID from = it->first;
1626 const CargoDataEntry *source_entry = source_dest->Retrieve(from);
1627 const FlowStat::SharesMap *shares = it->second.GetShares();
1628 for (FlowStat::SharesMap::const_iterator flow_it = shares->begin(); flow_it != shares->end(); ++flow_it) {
1629 const CargoDataEntry *via_entry = source_entry->Retrieve(flow_it->second);
1630 for (CargoDataSet::iterator dest_it = via_entry->Begin(); dest_it != via_entry->End(); ++dest_it) {
1631 CargoDataEntry &dest_entry = **dest_it;
1632 ShowCargo(entry, cargo, from, flow_it->second, dest_entry.GetStation(), dest_entry.GetCount());
1633 }
1634 }
1635 }
1636 }
1637
1644 void BuildCargoList(CargoType cargo, const StationCargoList &packets, CargoDataEntry *entry)
1645 {
1646 const CargoDataEntry *source_dest = this->cached_destinations.Retrieve(cargo);
1647 for (StationCargoList::ConstIterator it = packets.Packets()->begin(); it != packets.Packets()->end(); it++) {
1648 const CargoPacket *cp = *it;
1649 StationID next = it.GetKey();
1650
1651 const CargoDataEntry *source_entry = source_dest->Retrieve(cp->GetFirstStation());
1652 if (source_entry == nullptr) {
1653 this->ShowCargo(entry, cargo, cp->GetFirstStation(), next, StationID::Invalid(), cp->Count());
1654 continue;
1655 }
1656
1657 const CargoDataEntry *via_entry = source_entry->Retrieve(next);
1658 if (via_entry == nullptr) {
1659 this->ShowCargo(entry, cargo, cp->GetFirstStation(), next, StationID::Invalid(), cp->Count());
1660 continue;
1661 }
1662
1663 uint remaining = cp->Count();
1664 for (CargoDataSet::iterator dest_it = via_entry->Begin(); dest_it != via_entry->End();) {
1665 CargoDataEntry &dest_entry = **dest_it;
1666
1667 /* Advance iterator here instead of in the for statement to test whether this is the last entry */
1668 ++dest_it;
1669
1670 uint val;
1671 if (dest_it == via_entry->End()) {
1672 /* Allocate all remaining waiting cargo to the last destination to avoid
1673 * waiting cargo being "lost", and the displayed total waiting cargo
1674 * not matching GoodsEntry::TotalCount() */
1675 val = remaining;
1676 } else {
1677 val = std::min<uint>(remaining, DivideApprox(cp->Count() * dest_entry.GetCount(), via_entry->GetCount()));
1678 remaining -= val;
1679 }
1680 this->ShowCargo(entry, cargo, cp->GetFirstStation(), next, dest_entry.GetStation(), val);
1681 }
1682 }
1683 this->ShowCargo(entry, cargo, NEW_STATION, NEW_STATION, NEW_STATION, packets.ReservedCount());
1684 }
1685
1691 void BuildCargoList(CargoDataEntry *entry, const Station *st)
1692 {
1693 for (CargoType cargo : EnumRange(NUM_CARGO)) {
1694
1695 if (this->cached_destinations.Retrieve(cargo) == nullptr) {
1696 this->RecalcDestinations(cargo);
1697 }
1698
1699 const GoodsEntry &ge = st->goods[cargo];
1700 if (!ge.HasData()) continue;
1701
1702 if (this->current_mode == MODE_WAITING) {
1703 this->BuildCargoList(cargo, ge.GetData().cargo, entry);
1704 } else {
1705 this->BuildFlowList(cargo, ge.GetData().flows, entry);
1706 }
1707 }
1708 }
1709
1715 {
1716 std::list<StationID> stations;
1717 const CargoDataEntry *parent = entry.GetParent();
1718 if (parent->GetParent() == nullptr) {
1719 this->displayed_rows.push_back(RowDisplay(&this->expanded_rows, entry.GetCargo()));
1720 return;
1721 }
1722
1723 StationID next = entry.GetStation();
1724 while (parent->GetParent()->GetParent() != nullptr) {
1725 stations.push_back(parent->GetStation());
1726 parent = parent->GetParent();
1727 }
1728
1729 CargoType cargo = parent->GetCargo();
1730 CargoDataEntry *filter = this->expanded_rows.Retrieve(cargo);
1731 while (!stations.empty()) {
1732 filter = filter->Retrieve(stations.back());
1733 stations.pop_back();
1734 }
1735
1736 this->displayed_rows.push_back(RowDisplay(filter, next));
1737 }
1738
1747 StringID GetEntryString(StationID station, StringID here, StringID other_station, StringID any) const
1748 {
1749 if (station == this->window_number) {
1750 return here;
1751 } else if (station == StationID::Invalid()) {
1752 return any;
1753 } else if (station == NEW_STATION) {
1754 return STR_STATION_VIEW_RESERVED;
1755 } else {
1756 return other_station;
1757 }
1758 }
1759
1760 StringID GetGroupingString(Grouping grouping, StationID station) const
1761 {
1762 switch (grouping) {
1763 case GR_SOURCE: return this->GetEntryString(station, STR_STATION_VIEW_FROM_HERE, STR_STATION_VIEW_FROM, STR_STATION_VIEW_FROM_ANY);
1764 case GR_NEXT: return this->GetEntryString(station, STR_STATION_VIEW_VIA_HERE, STR_STATION_VIEW_VIA, STR_STATION_VIEW_VIA_ANY);
1765 case GR_DESTINATION: return this->GetEntryString(station, STR_STATION_VIEW_TO_HERE, STR_STATION_VIEW_TO, STR_STATION_VIEW_TO_ANY);
1766 default: NOT_REACHED();
1767 }
1768 }
1769
1777 StringID SearchNonStop(CargoDataEntry &cd, StationID station, int column)
1778 {
1779 assert(column < NUM_COLUMNS);
1781 for (int i = column - 1; i > 0; --i) {
1782 if (this->groupings[i] == GR_DESTINATION) {
1783 if (parent->GetStation() == station) {
1784 return STR_STATION_VIEW_NONSTOP;
1785 } else {
1786 return STR_STATION_VIEW_VIA;
1787 }
1788 }
1789 parent = parent->GetParent();
1790 }
1791
1792 if (column < NUM_COLUMNS - 1 && this->groupings[column + 1] == GR_DESTINATION) {
1793 CargoDataSet::iterator begin = cd.Begin();
1794 CargoDataSet::iterator end = cd.End();
1795 if (begin != end && ++(cd.Begin()) == end && (*(begin))->GetStation() == station) {
1796 return STR_STATION_VIEW_NONSTOP;
1797 } else {
1798 return STR_STATION_VIEW_VIA;
1799 }
1800 }
1801
1802 return STR_STATION_VIEW_VIA;
1803 }
1804
1811 void DrawCargoIcons(CargoType cargo, uint waiting, const Rect &r) const
1812 {
1813 int width = ScaleSpriteTrad(10);
1814 uint num = std::min<uint>((waiting + (width / 2)) / width, r.Width() / width); // maximum is width / 10 icons so it won't overflow
1815 if (num == 0) return;
1816
1817 SpriteID sprite = CargoSpec::Get(cargo)->GetCargoIcon();
1818
1819 int x = _current_text_dir == TD_RTL ? r.left : r.right - num * width;
1820 int y = CentreBounds(r.top, r.bottom, this->cargo_icon_size.height);
1821 do {
1822 DrawSprite(sprite, PAL_NONE, x, y);
1823 x += width;
1824 } while (--num);
1825 }
1826
1837 int DrawEntries(CargoDataEntry &entry, const Rect &r, int pos, int maxrows, int column, CargoType cargo = INVALID_CARGO)
1838 {
1839 assert(column < NUM_COLUMNS);
1840 if (this->sortings[column] == CargoSortType::AsGrouping) {
1841 if (this->groupings[column] != GR_CARGO) {
1842 entry.Resort(CargoSortType::StationString, this->sort_orders[column]);
1843 }
1844 } else {
1845 entry.Resort(CargoSortType::Count, this->sort_orders[column]);
1846 }
1847 int text_y_offset = (this->line_height - GetCharacterHeight(FontSize::Normal)) / 2;
1848 for (CargoDataSet::iterator i = entry.Begin(); i != entry.End(); ++i) {
1849 CargoDataEntry &cd = **i;
1850
1851 Grouping grouping = this->groupings[column];
1852 if (grouping == GR_CARGO) cargo = cd.GetCargo();
1853 bool auto_distributed = _settings_game.linkgraph.GetDistributionType(cargo) != DistributionType::Manual;
1854
1855 if (pos > -maxrows && pos <= 0) {
1856 StringID str = STR_EMPTY;
1857 StationID station = StationID::Invalid();
1858 int y = r.top - pos * this->line_height;
1859 if (this->groupings[column] == GR_CARGO) {
1860 str = STR_STATION_VIEW_WAITING_CARGO;
1861 this->DrawCargoIcons(cd.GetCargo(), cd.GetCount(), Rect(r.left + this->expand_shrink_width, y, r.right - this->expand_shrink_width, y + this->line_height - 1));
1862 } else {
1863 if (!auto_distributed) grouping = GR_SOURCE;
1864 station = cd.GetStation();
1865 str = this->GetGroupingString(grouping, station);
1866 if (grouping == GR_NEXT && str == STR_STATION_VIEW_VIA) str = this->SearchNonStop(cd, station, column);
1867
1868 if (pos == -this->scroll_to_row && Station::IsValidID(station)) {
1870 }
1871 }
1872
1873 bool rtl = _current_text_dir == TD_RTL;
1874 Rect text = r.Indent(column * WidgetDimensions::scaled.hsep_indent, rtl).Indent(this->expand_shrink_width, !rtl);
1875 Rect shrink = r.WithWidth(this->expand_shrink_width, !rtl);
1876
1877 DrawString(text.left, text.right, y + text_y_offset, GetString(str, cargo, cd.GetCount(), station));
1878
1879 if (column < NUM_COLUMNS - 1) {
1880 std::string_view sym;
1881 if (cd.GetNumChildren() > 0) {
1882 sym = "-";
1883 } else if (auto_distributed && str != STR_STATION_VIEW_RESERVED) {
1884 sym = "+";
1885 } else {
1886 /* Only draw '+' if there is something to be shown. */
1887 const GoodsEntry &ge = Station::Get(this->window_number)->goods[cargo];
1888 if (ge.HasData()) {
1889 const StationCargoList &cargo_list = ge.GetData().cargo;
1890 if (grouping == GR_CARGO && (cargo_list.ReservedCount() > 0 || cd.HasTransfers())) {
1891 sym = "+";
1892 }
1893 }
1894 }
1895 if (!sym.empty()) DrawString(shrink.left, shrink.right, y + text_y_offset, sym, TextColour::Yellow);
1896 }
1897 this->SetDisplayedRow(cd);
1898 }
1899 --pos;
1900 if ((auto_distributed || column == 0) && column < NUM_COLUMNS - 1) {
1901 pos = this->DrawEntries(cd, r, pos, maxrows, column + 1, cargo);
1902 }
1903 }
1904 return pos;
1905 }
1906
1912 int DrawAcceptedCargo(const Rect &r) const
1913 {
1914 const Station *st = Station::Get(this->window_number);
1915 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
1916
1917 int bottom = DrawStringMultiLine(tr.left, tr.right, tr.top, INT32_MAX, GetString(STR_STATION_VIEW_ACCEPTS_CARGO, GetAcceptanceMask(st)));
1918 return CeilDiv(bottom - r.top - WidgetDimensions::scaled.framerect.top, GetCharacterHeight(FontSize::Normal));
1919 }
1920
1926 int DrawCargoRatings(const Rect &r) const
1927 {
1928 const Station *st = Station::Get(this->window_number);
1929 bool rtl = _current_text_dir == TD_RTL;
1930 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
1931
1932 if (st->town->exclusive_counter > 0) {
1933 tr.top = DrawStringMultiLine(tr, GetString(st->town->exclusivity == st->owner ? STR_STATION_VIEW_EXCLUSIVE_RIGHTS_SELF : STR_STATION_VIEW_EXCLUSIVE_RIGHTS_COMPANY, st->town->exclusivity));
1934 tr.top += WidgetDimensions::scaled.vsep_wide;
1935 }
1936
1937 DrawString(tr, TimerGameEconomy::UsingWallclockUnits() ? STR_STATION_VIEW_SUPPLY_RATINGS_TITLE_MINUTE : STR_STATION_VIEW_SUPPLY_RATINGS_TITLE_MONTH);
1939
1940 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
1941 const GoodsEntry *ge = &st->goods[cs->Index()];
1942 if (!ge->HasRating()) continue;
1943
1945 DrawString(tr.Indent(WidgetDimensions::scaled.hsep_indent, rtl),
1946 GetString(STR_STATION_VIEW_CARGO_SUPPLY_RATING,
1947 cs->name,
1948 lg != nullptr ? lg->Monthly((*lg)[ge->node].supply) : 0,
1949 STR_CARGO_RATING_APPALLING + (ge->rating >> 5),
1950 ToPercent8(ge->rating)));
1952 }
1953 return CeilDiv(tr.top - r.top - WidgetDimensions::scaled.framerect.top, GetCharacterHeight(FontSize::Normal));
1954 }
1955
1961 template <class Tid>
1963 {
1964 if (filter->Retrieve(next) != nullptr) {
1965 filter->Remove(next);
1966 } else {
1967 filter->InsertOrRetrieve(next);
1968 }
1969 }
1970
1976 {
1977 if (row < 0 || (uint)row >= this->displayed_rows.size()) return;
1978 if (IsCtrlPressed()) {
1979 this->scroll_to_row = row;
1980 } else {
1981 RowDisplay &display = this->displayed_rows[row];
1982 if (display.filter == &this->expanded_rows) {
1984 } else {
1986 }
1987 }
1990 }
1991
1992 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
1993 {
1994 Window *w = FindWindowByClass(WindowClass::QueryString);
1995
1996 switch (widget) {
1997 case WID_SV_WAITING:
1998 this->HandleCargoWaitingClick(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_SV_WAITING, WidgetDimensions::scaled.framerect.top) - this->vscroll->GetPosition());
1999 break;
2000
2001 case WID_SV_CATCHMENT:
2003 SndClickBeep();
2004
2005 if (w != nullptr && this->IsWidgetLowered(WID_SV_CATCHMENT)) {
2006 if (w->parent->window_class == WindowClass::StationView && w->IsWidgetLowered(WID_QS_MOVE)) SetViewportStationRect(Station::Get(w->parent->window_number), true);
2007 if (w->parent->window_class == WindowClass::WaypointView && w->IsWidgetLowered(WID_QS_MOVE)) SetViewportWaypointRect(Waypoint::Get(w->parent->window_number), true);
2008 }
2009 break;
2010
2011 case WID_SV_LOCATION:
2012 if (IsCtrlPressed()) {
2013 ShowExtraViewportWindow(Station::Get(this->window_number)->xy);
2014 } else {
2015 ScrollMainWindowToTile(Station::Get(this->window_number)->xy);
2016 }
2017 break;
2018
2020 /* Swap between 'accepts' and 'ratings' view. */
2021 int height_change;
2023 if (this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS)->GetString() == STR_STATION_VIEW_RATINGS_BUTTON) {
2024 nwi->SetStringTip(STR_STATION_VIEW_ACCEPTS_BUTTON, STR_STATION_VIEW_ACCEPTS_TOOLTIP); // Switch to accepts view.
2025 height_change = this->rating_lines - this->accepts_lines;
2026 } else {
2027 nwi->SetStringTip(STR_STATION_VIEW_RATINGS_BUTTON, STR_STATION_VIEW_RATINGS_TOOLTIP); // Switch to ratings view.
2028 height_change = this->accepts_lines - this->rating_lines;
2029 }
2030 this->ReInit(0, height_change * GetCharacterHeight(FontSize::Normal));
2031 break;
2032 }
2033
2034 case WID_SV_RENAME:
2035 ShowQueryString(GetString(STR_STATION_NAME, this->window_number), STR_STATION_VIEW_EDIT_STATION_SIGN, MAX_LENGTH_STATION_NAME_CHARS,
2037 break;
2038
2040 Command<Commands::OpenCloseAirport>::Post(this->window_number);
2041 break;
2042
2043 case WID_SV_TRAINS: // Show list of scheduled trains to this station
2044 case WID_SV_ROADVEHS: // Show list of scheduled road-vehicles to this station
2045 case WID_SV_SHIPS: // Show list of scheduled ships to this station
2046 case WID_SV_PLANES: { // Show list of scheduled aircraft to this station
2047 Owner owner = Station::Get(this->window_number)->owner;
2048 ShowVehicleListWindow(owner, (VehicleType)(widget - WID_SV_TRAINS), static_cast<StationID>(this->window_number));
2049 break;
2050 }
2051
2052 case WID_SV_SORT_BY: {
2053 /* The initial selection is composed of current mode and
2054 * sorting criteria for columns 1, 2, and 3. Column 0 is always
2055 * sorted by cargo type. The others can theoretically be sorted
2056 * by different things but there is no UI for that. */
2058 this->current_mode * 2 + (this->sortings[1] == CargoSortType::Count ? 1 : 0),
2059 WID_SV_SORT_BY, 0, 0);
2060 break;
2061 }
2062
2063 case WID_SV_GROUP_BY: {
2064 ShowDropDownMenu(this, StationViewWindow::group_names, this->grouping_index, WID_SV_GROUP_BY, 0, 0);
2065 break;
2066 }
2067
2068 case WID_SV_SORT_ORDER: { // flip sorting method asc/desc
2069 this->SelectSortOrder(this->sort_orders[1] == SO_ASCENDING ? SO_DESCENDING : SO_ASCENDING);
2070 this->SetTimeout();
2072 break;
2073 }
2074
2075 case WID_SV_GRAPH: {
2076 ShowStationGraph(this->window_number);
2077 break;
2078 }
2079 }
2080 }
2081
2086 void SelectSortOrder(SortOrder order)
2087 {
2088 this->sort_orders[1] = this->sort_orders[2] = this->sort_orders[3] = order;
2089 _settings_client.gui.station_gui_sort_order = this->sort_orders[1];
2090 this->SetDirty();
2091 }
2092
2097 void SelectSortBy(int index)
2098 {
2099 _settings_client.gui.station_gui_sort_by = index;
2100 switch (StationViewWindow::sort_names[index].base()) {
2101 case STR_STATION_VIEW_WAITING_STATION.base():
2102 this->current_mode = MODE_WAITING;
2103 this->sortings[1] = this->sortings[2] = this->sortings[3] = CargoSortType::AsGrouping;
2104 break;
2105 case STR_STATION_VIEW_WAITING_AMOUNT.base():
2106 this->current_mode = MODE_WAITING;
2107 this->sortings[1] = this->sortings[2] = this->sortings[3] = CargoSortType::Count;
2108 break;
2109 case STR_STATION_VIEW_PLANNED_STATION.base():
2110 this->current_mode = MODE_PLANNED;
2111 this->sortings[1] = this->sortings[2] = this->sortings[3] = CargoSortType::AsGrouping;
2112 break;
2113 case STR_STATION_VIEW_PLANNED_AMOUNT.base():
2114 this->current_mode = MODE_PLANNED;
2115 this->sortings[1] = this->sortings[2] = this->sortings[3] = CargoSortType::Count;
2116 break;
2117 default:
2118 NOT_REACHED();
2119 }
2120 /* Display the current sort variant */
2122 this->SetDirty();
2123 }
2124
2129 void SelectGroupBy(int index)
2130 {
2131 this->grouping_index = index;
2132 _settings_client.gui.station_gui_group_order = index;
2134 switch (StationViewWindow::group_names[index].base()) {
2135 case STR_STATION_VIEW_GROUP_S_V_D.base():
2136 this->groupings[1] = GR_SOURCE;
2137 this->groupings[2] = GR_NEXT;
2138 this->groupings[3] = GR_DESTINATION;
2139 break;
2140 case STR_STATION_VIEW_GROUP_S_D_V.base():
2141 this->groupings[1] = GR_SOURCE;
2142 this->groupings[2] = GR_DESTINATION;
2143 this->groupings[3] = GR_NEXT;
2144 break;
2145 case STR_STATION_VIEW_GROUP_V_S_D.base():
2146 this->groupings[1] = GR_NEXT;
2147 this->groupings[2] = GR_SOURCE;
2148 this->groupings[3] = GR_DESTINATION;
2149 break;
2150 case STR_STATION_VIEW_GROUP_V_D_S.base():
2151 this->groupings[1] = GR_NEXT;
2152 this->groupings[2] = GR_DESTINATION;
2153 this->groupings[3] = GR_SOURCE;
2154 break;
2155 case STR_STATION_VIEW_GROUP_D_S_V.base():
2156 this->groupings[1] = GR_DESTINATION;
2157 this->groupings[2] = GR_SOURCE;
2158 this->groupings[3] = GR_NEXT;
2159 break;
2160 case STR_STATION_VIEW_GROUP_D_V_S.base():
2161 this->groupings[1] = GR_DESTINATION;
2162 this->groupings[2] = GR_NEXT;
2163 this->groupings[3] = GR_SOURCE;
2164 break;
2165 }
2166 this->SetDirty();
2167 }
2168
2169 void OnDropdownSelect(WidgetID widget, int index, int) override
2170 {
2171 if (widget == WID_SV_SORT_BY) {
2172 this->SelectSortBy(index);
2173 } else {
2174 this->SelectGroupBy(index);
2175 }
2176 }
2177
2178 void OnQueryTextFinished(std::optional<std::string> str) override
2179 {
2180 if (!str.has_value()) return;
2181
2182 Command<Commands::RenameStation>::Post(STR_ERROR_CAN_T_RENAME_STATION, this->window_number, *str);
2183 }
2184
2185 void OnResize() override
2186 {
2187 this->vscroll->SetCapacityFromWidget(this, WID_SV_WAITING, WidgetDimensions::scaled.framerect.Vertical());
2188 }
2189
2195 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
2196 {
2197 if (gui_scope) {
2198 if (data >= 0 && data < NUM_CARGO) {
2199 this->cached_destinations.Remove((CargoType)data);
2200 } else {
2201 this->ReInit();
2202 }
2203 }
2204 }
2205};
2206
2209 WindowPosition::Automatic, "view_station", 249, 117,
2210 WindowClass::StationView, WindowClass::None,
2211 {},
2212 _nested_station_view_widgets
2213);
2214
2224
2230
2231static std::vector<TileAndStation> _deleted_stations_nearby;
2232static std::vector<StationID> _stations_nearby_list;
2233
2241template <class T>
2242static void AddNearbyStation(TileIndex tile, TileArea *ctx)
2243{
2244 /* First check if there were deleted stations here */
2245 for (auto it = _deleted_stations_nearby.begin(); it != _deleted_stations_nearby.end(); /* nothing */) {
2246 if (it->tile == tile) {
2247 _stations_nearby_list.push_back(it->station);
2248 it = _deleted_stations_nearby.erase(it);
2249 } else {
2250 ++it;
2251 }
2252 }
2253
2254 /* Check if own station and if we stay within station spread */
2255 if (!IsTileType(tile, TileType::Station)) return;
2256
2257 StationID sid = GetStationIndex(tile);
2258
2259 /* This station is (likely) a waypoint */
2260 if (!T::IsValidID(sid)) return;
2261
2262 const BaseStation *st = BaseStation::Get(sid);
2263 if (st->owner != _local_company || std::ranges::find(_stations_nearby_list, sid) != _stations_nearby_list.end()) return;
2264
2265 if (CheckStationSpread(st->spread, *ctx).Succeeded()) {
2266 _stations_nearby_list.push_back(sid);
2267 }
2268}
2269
2279template <class T>
2280static void FindStationsNearby(TileArea ta, bool distant_join)
2281{
2282 TileArea ctx = ta;
2283
2284 _stations_nearby_list.clear();
2285 _stations_nearby_list.push_back(NEW_STATION);
2286 _deleted_stations_nearby.clear();
2287
2288 /* Look for deleted stations */
2289 for (const BaseStation *st : BaseStation::Iterate()) {
2290 if (T::IsValidBaseStation(st) && !st->IsInUse() && st->owner == _local_company) {
2291 /* Include only within station spread (yes, it is strictly less than) */
2292 if (std::max(DistanceMax(ta.tile, st->xy), DistanceMax(TileAddXY(ta.tile, ta.w - 1, ta.h - 1), st->xy)) < _settings_game.station.station_spread) {
2293 _deleted_stations_nearby.emplace_back(st->xy, st->index);
2294
2295 /* Add the station when it's within where we're going to build */
2296 if (IsInsideBS(TileX(st->xy), TileX(ctx.tile), ctx.w) &&
2297 IsInsideBS(TileY(st->xy), TileY(ctx.tile), ctx.h)) {
2298 AddNearbyStation<T>(st->xy, &ctx);
2299 }
2300 }
2301 }
2302 }
2303
2304 /* Add stations that are within station tile area. Stations do not have to occupy all tiles */
2305 for (auto t : ta) {
2306 AddNearbyStation<T>(t, &ctx);
2307 }
2308
2309 /* Only search tiles where we have a chance to stay within the station spread.
2310 * The complete check needs to be done in the callback as we don't know the
2311 * extent of the found station, yet. */
2312 if (distant_join && std::min(ta.w, ta.h) >= _settings_game.station.station_spread) return;
2313 uint max_dist = distant_join ? _settings_game.station.station_spread - std::min(ta.w, ta.h) : 1;
2314
2315 for (auto tile : SpiralTileSequence(TileAddByDir(ctx.tile, Direction::N), max_dist, ta.w, ta.h)) {
2316 AddNearbyStation<T>(tile, &ctx);
2317 }
2318}
2319
2320static constexpr std::initializer_list<NWidgetPart> _nested_select_station_widgets = {
2323 NWidget(WWT_CAPTION, Colours::DarkGreen, WID_JS_CAPTION), SetStringTip(STR_JOIN_STATION_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2325 EndContainer(),
2331 EndContainer(),
2332 EndContainer(),
2333};
2334
2339template <class T>
2340struct SelectStationWindow : Window {
2341 StationPickerCmdProc select_station_proc{};
2343 Scrollbar *vscroll = nullptr;
2344
2345 SelectStationWindow(WindowDesc &desc, TileArea ta, StationPickerCmdProc&& proc) :
2346 Window(desc),
2347 select_station_proc(std::move(proc)),
2348 area(ta)
2349 {
2350 this->CreateNestedTree();
2351 this->vscroll = this->GetScrollbar(WID_JS_SCROLLBAR);
2352 this->GetWidget<NWidgetCore>(WID_JS_CAPTION)->SetString(T::IsWaypoint() ? STR_JOIN_WAYPOINT_CAPTION : STR_JOIN_STATION_CAPTION);
2353 this->FinishInitNested(0);
2354 this->OnInvalidateData(0);
2355
2356 _thd.freeze = true;
2357 }
2358
2359 void Close([[maybe_unused]] int data = 0) override
2360 {
2361 SetViewportCatchmentSpecializedStation<typename T::StationType>(nullptr, true);
2362
2363 _thd.freeze = false;
2364 this->Window::Close();
2365 }
2366
2367 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
2368 {
2369 if (widget != WID_JS_PANEL) return;
2370
2371 /* Determine the widest string */
2372 Dimension d = GetStringBoundingBox(T::IsWaypoint() ? STR_JOIN_WAYPOINT_CREATE_SPLIT_WAYPOINT : STR_JOIN_STATION_CREATE_SPLIT_STATION);
2373 for (const auto &station : _stations_nearby_list) {
2374 if (station == NEW_STATION) continue;
2375 const BaseStation *st = BaseStation::Get(station);
2376 d = maxdim(d, GetStringBoundingBox(T::IsWaypoint()
2377 ? GetString(STR_STATION_LIST_WAYPOINT, st->index)
2378 : GetString(STR_STATION_LIST_STATION, st->index, st->facilities)));
2379 }
2380
2381 fill.height = resize.height = d.height;
2382 d.height *= 5;
2383 d.width += padding.width;
2384 d.height += padding.height;
2385 size = d;
2386 }
2387
2388 void DrawWidget(const Rect &r, WidgetID widget) const override
2389 {
2390 if (widget != WID_JS_PANEL) return;
2391
2392 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
2393 auto [first, last] = this->vscroll->GetVisibleRangeIterators(_stations_nearby_list);
2394 for (auto it = first; it != last; ++it, tr.top += this->resize.step_height) {
2395 if (*it == NEW_STATION) {
2396 DrawString(tr, T::IsWaypoint() ? STR_JOIN_WAYPOINT_CREATE_SPLIT_WAYPOINT : STR_JOIN_STATION_CREATE_SPLIT_STATION);
2397 } else {
2398 const BaseStation *st = BaseStation::Get(*it);
2399 DrawString(tr, T::IsWaypoint()
2400 ? GetString(STR_STATION_LIST_WAYPOINT, st->index)
2401 : GetString(STR_STATION_LIST_STATION, st->index, st->facilities));
2402 }
2403 }
2404
2405 }
2406
2407 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
2408 {
2409 if (widget != WID_JS_PANEL) return;
2410
2411 auto it = this->vscroll->GetScrolledItemFromWidget(_stations_nearby_list, pt.y, this, WID_JS_PANEL, WidgetDimensions::scaled.framerect.top);
2412 if (it == _stations_nearby_list.end()) return;
2413
2414 /* Execute stored Command */
2415 this->select_station_proc(false, *it);
2416
2417 /* Close Window; this might cause double frees! */
2418 CloseWindowById(WindowClass::JoinStation, 0);
2419 }
2420
2421 void OnRealtimeTick([[maybe_unused]] uint delta_ms) override
2422 {
2423 if (_thd.dirty & 2) {
2424 _thd.dirty &= ~2;
2425 this->SetDirty();
2426 }
2427 }
2428
2429 void OnResize() override
2430 {
2431 this->vscroll->SetCapacityFromWidget(this, WID_JS_PANEL, WidgetDimensions::scaled.framerect.Vertical());
2432 }
2433
2439 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
2440 {
2441 if (!gui_scope) return;
2442 FindStationsNearby<T>(this->area, true);
2443 this->vscroll->SetCount(_stations_nearby_list.size());
2444 this->SetDirty();
2445 }
2446
2447 void OnMouseOver([[maybe_unused]] Point pt, WidgetID widget) override
2448 {
2449 if (widget != WID_JS_PANEL) {
2450 SetViewportCatchmentSpecializedStation<typename T::StationType>(nullptr, true);
2451 return;
2452 }
2453
2454 /* Show coverage area of station under cursor */
2455 auto it = this->vscroll->GetScrolledItemFromWidget(_stations_nearby_list, pt.y, this, WID_JS_PANEL, WidgetDimensions::scaled.framerect.top);
2456 const typename T::StationType *st = it == _stations_nearby_list.end() || *it == NEW_STATION ? nullptr : T::StationType::Get(*it);
2457 SetViewportCatchmentSpecializedStation<typename T::StationType>(st, true);
2458 }
2459};
2460
2463 WindowPosition::Automatic, "build_station_join", 200, 180,
2464 WindowClass::JoinStation, WindowClass::None,
2466 _nested_select_station_widgets
2467);
2468
2469
2475static bool StationJoinerNeeded(const StationPickerCmdProc &proc)
2476{
2477 /* Only show selection if distant join is enabled in the settings */
2478 if (!_settings_game.station.distant_join_stations) return false;
2479
2480 /* If a window is already opened and we didn't ctrl-click,
2481 * return true (i.e. just flash the old window) */
2482 Window *selection_window = FindWindowById(WindowClass::JoinStation, 0);
2483 if (selection_window != nullptr) {
2484 /* Abort current distant-join and start new one */
2485 selection_window->Close();
2487 }
2488
2489 /* only show the popup, if we press ctrl */
2490 if (!IsCtrlPressed()) return false;
2491
2492 /* Now check if we could build there */
2493 return proc(true, StationID::Invalid());
2494}
2495
2502template <class T>
2503void ShowSelectBaseStationIfNeeded(TileArea ta, StationPickerCmdProc&& proc)
2504{
2505 if (StationJoinerNeeded(proc)) {
2506 if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
2507 FindStationsNearby<T>(ta, false);
2508 new SelectStationWindow<T>(_select_station_desc, ta, std::move(proc));
2509 } else {
2510 proc(false, StationID::Invalid());
2511 }
2512}
2513
2519void ShowSelectStationIfNeeded(TileArea ta, StationPickerCmdProc proc)
2520{
2522}
2523
2529void ShowSelectRailWaypointIfNeeded(TileArea ta, StationPickerCmdProc proc)
2530{
2532}
2533
2539void ShowSelectRoadWaypointIfNeeded(TileArea ta, StationPickerCmdProc proc)
2540{
2542}
@ AirportClosed
Dummy block for indicating a closed airport.
Definition airport.h:131
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
static constexpr CargoType INVALID_CARGO
Invalid marker for cargoes.
Definition cargo_type.h:83
EnumBitSet< CargoType, uint64_t > CargoTypes
Bitset of CargoType elements.
Definition cargo_type.h:115
static constexpr CargoType NUM_CARGO
Maximum number of cargo types in a game.
Definition cargo_type.h:77
CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:22
Dimension GetLargestCargoIconSize()
Get dimensions of largest cargo icon.
std::span< const CargoSpec * > _sorted_standard_cargo_specs
Standard cargo specifications sorted alphabetically by name.
std::vector< const CargoSpec * > _sorted_cargo_specs
Cargo specifications sorted alphabetically by name.
CargoTypes _cargo_mask
Bitmask of cargo types available.
Definition cargotype.cpp:30
Types/functions related to cargoes.
@ Passengers
Passengers.
Definition cargotype.h:50
bool IsCargoInClass(CargoType cargo, CargoClasses cc)
Does a given cargo have any cargo class from cc.
Definition cargotype.h:288
uint Count() const
Count the number of set bits.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr bool None() const
Test if none of the values are set.
constexpr Timpl & Flip()
Flip all bits.
constexpr Timpl & Reset()
Reset all bits.
constexpr Timpl & Set()
Set all bits.
auto begin() const
Returns an iterator to begin of the set bits.
constexpr bool Any(const Timpl &other) const
Test if any of the given values are set.
A cargo data entry representing one possible row in the station view window's top part.
uint count
sum of counts of all children or amount of cargo for this entry.
void Clear()
Delete all subentries, reset count and num_children and adapt parent's count.
StationID GetStation() const
Get the station ID for this entry.
void IncrementSize()
Increment.
void SetTransfers(bool value)
Set the transfers state.
~CargoDataEntry()
Remove ourselves from our parent.
CargoType GetCargo() const
Get the cargo type for this entry.
uint num_children
the number of subentries belonging to this entry.
void Remove(CargoType cargo)
Remove a child associated with the given cargo.
CargoDataEntry * Retrieve(StationID station) const
Retrieve a child for the given station.
uint GetCount() const
Get the cargo count for this entry.
CargoDataEntry * GetParent() const
Get the parent entry for this entry.
StationID station
ID of the station this entry is associated with.
CargoType cargo
ID of the cargo this entry is associated with.
CargoDataEntry & InsertOrRetrieve(StationID station)
Insert a new child or retrieve an existing child using a station ID as ID.
CargoDataEntry & InsertOrRetrieve(CargoType cargo)
Insert a new child or retrieve an existing child using a cargo type as ID.
CargoDataSet::iterator End() const
Get an iterator pointing to the end of the set of children.
void Update(uint count)
Update the count for this entry and propagate the change to the parent entry if there is one.
std::unique_ptr< CargoDataSet > children
the children of this entry.
bool transfers
If there are transfers for this cargo.
CargoDataSet::iterator Begin() const
Get an iterator pointing to the begin of the set of children.
bool HasTransfers() const
Has this entry transfers.
CargoDataEntry * Retrieve(CargoType cargo) const
Retrieve a child for the given cargo.
CargoDataEntry * parent
the parent of this entry.
void Remove(StationID station)
Remove a child associated with the given station.
uint GetNumChildren() const
Get the number of children for this entry.
const Tcont * Packets() const
Returns a pointer to the cargo packet list (so you can iterate over it etc).
StationCargoPacketMap::const_iterator ConstIterator
bool Succeeded() const
Did this command succeed?
The list of stations per company.
std::array< uint16_t, NUM_CARGO > stations_per_cargo_type
Number of stations with a rating for each cargo type.
static bool StationNameSorter(const Station *const &a, const Station *const &b, const CargoTypes &filter)
Sort stations by their name.
void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
Update size and resize step of a widget in the window.
void OnEditboxChanged(WidgetID wid) override
The text in an editbox has been edited.
void OnResize() override
Called after the window got resized.
static bool StationWaitingAvailableSorter(const Station *const &a, const Station *const &b, const CargoTypes &filter)
Sort stations by their available waiting cargo.
void SortStationsList()
Sort the stations list.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
StringFilter string_filter
Filter for name.
static const StringID sorter_names[]
Strings describing how stations are sorted.
void OnDropdownSelect(WidgetID widget, int index, int) override
A dropdown option associated to this window has been selected.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
static bool StationRatingMaxSorter(const Station *const &a, const Station *const &b, const CargoTypes &filter)
Sort stations by their rating.
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
void OnPaint() override
The window must be repainted.
static bool StationWaitingTotalSorter(const Station *const &a, const Station *const &b, const CargoTypes &filter)
Sort stations by their waiting cargo.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
QueryString name_editbox
Filter editbox.
static bool StationTypeSorter(const Station *const &a, const Station *const &b, const CargoTypes &filter)
Sort stations by their type.
void OnGameTick() override
Called once per (game) tick.
~CompanyStationsWindow() override
Save the last sorting state.
void BuildStationsList(const Owner owner)
(Re)Build station list
static const std::initializer_list< GUIStationList::SortFunction *const > sorter_funcs
Functions to sort stations.
uint16_t stations_per_cargo_type_no_rating
Number of stations without a rating.
static bool StationRatingMinSorter(const Station *const &a, const Station *const &b, const CargoTypes &filter)
Sort stations by their rating.
Drop down checkmark component.
Iterate a range of enum values.
Flow descriptions by origin stations.
List template of 'things' T to sort in a GUI.
void RebuildDone()
Notify the sortlist that the rebuild is done.
bool IsDescSortOrder() const
Check if the sort order is descending.
void ToggleSortOrder()
Toggle the sort order Since that is the worst condition for the sort function reverse the list here.
bool NeedRebuild() const
Check if a rebuild is needed.
void ForceRebuild()
Force that a rebuild is needed.
bool Sort(Comp compare)
Sort the list.
void ForceResort()
Force a resort next Sort call Reset the resort timer if used too.
uint8_t SortType() const
Get the sorttype of the list.
Listing GetListing() const
Export current sort conditions.
bool NeedResort()
Check if a resort is needed next loop If used the resort timer will decrease every call till 0.
void SetSortType(uint8_t n_type)
Set the sorttype of the list.
A connected component of a link graph.
Definition linkgraph.h:35
uint Monthly(uint base) const
Scale a value to its monthly equivalent, based on last compression.
Definition linkgraph.h:262
Baseclass for nested widgets.
Base class for a 'real' widget.
void SetString(StringID string)
Set string of the nested widget.
Definition widget.cpp:1190
void SetStringTip(StringID string, StringID tool_tip)
Set string and tool tip of the nested widget.
Definition widget.cpp:1200
uint16_t w
The width of the area.
TileIndex tile
The base tile of the area.
uint16_t h
The height of the area.
Scrollbar data structure.
size_type GetCapacity() const
Gets the number of visible elements of the scrollbar.
void SetCount(size_t num)
Sets the number of elements in the list.
auto GetScrolledItemFromWidget(Tcontainer &container, int clickpos, const Window *const w, WidgetID widget, int padding=0, int line_height=-1) const
Return an iterator pointing to the element of a scrolled widget that a user clicked in.
size_type GetScrolledRowFromWidget(int clickpos, const Window *const w, WidgetID widget, int padding=0, int line_height=-1) const
Compute the row of a scrolled widget that a user clicked in.
Definition widget.cpp:2474
void SetCapacityFromWidget(Window *w, WidgetID widget, int padding=0)
Set capacity of visible elements from the size and resize properties of a widget.
Definition widget.cpp:2548
size_type GetCount() const
Gets the number of elements in the list.
auto GetVisibleRangeIterators(Tcontainer &container) const
Get a pair of iterators for the range of visible elements in a container.
size_type GetPosition() const
Gets the position of the first visible element in the list.
Generate TileIndices around a center tile or tile area, with increasing distance.
CargoList that is used for stations.
uint ReservedCount() const
Returns sum of cargo reserved for loading onto vehicles.
static bool UsingWallclockUnits(bool newgame=false)
Check if we are using wallclock units.
static WidgetDimensions scaled
Widget dimensions scaled for current zoom level.
Definition window_gui.h:30
Functions related to commands.
Definition of stuff that is very close to a company, like the company struct itself.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Functions related to companies.
static constexpr Owner OWNER_NONE
The tile has no ownership.
Functions related to debugging.
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
Definition debug.h:36
@ Misc
Misc message facility.
Definition debug_type.h:32
@ Notice
Notice.
Definition debug_type.h:18
void ShowDropDownMenu(Window *w, std::span< const StringID > strings, int selected, WidgetID button, uint32_t disabled_mask, uint32_t hidden_mask, uint width, DropDownOptions options, std::string *const persistent_filter_text)
Show a dropdown menu window near a widget of the parent window.
Definition dropdown.cpp:633
std::unique_ptr< DropDownListItem > MakeDropDownListDividerItem()
Creates new DropDownListDividerItem.
Definition dropdown.cpp:36
std::unique_ptr< DropDownListItem > MakeDropDownListStringItem(StringID str, int value, bool masked, bool shaded)
Creates new DropDownListStringItem.
Definition dropdown.cpp:49
void ShowDropDownList(Window *w, DropDownList &&list, int selected, WidgetID button, uint width, DropDownOptions options, std::string *const persistent_filter_text)
Show a drop down list.
Definition dropdown.cpp:591
Common drop down list components.
Functions related to the drop down widget.
Types related to the drop down widget.
std::vector< std::unique_ptr< const DropDownListItem > > DropDownList
A drop down list is a collection of drop down list items.
@ Persist
Set if this dropdown should stay open after an option is selected.
@ Filterable
Set if the dropdown is filterable.
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
Definition enum_type.hpp:21
int GetCharacterHeight(FontSize size)
Get height of a character for a given font size.
Definition fontcache.cpp:88
Dimension maxdim(const Dimension &d1, const Dimension &d2)
Compute bounding box of both dimensions.
Geometry functions.
int CentreBounds(int min, int max, int size)
Determine where to position a centred object.
Dimension GetStringBoundingBox(std::string_view str, FontSize start_fontsize)
Return the string dimension in pixels.
Definition gfx.cpp:894
Dimension GetStringListBoundingBox(std::span< const StringID > list, FontSize fontsize)
Get maximum dimension of a list of strings.
Definition gfx.cpp:933
void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub, ZoomLevel zoom)
Draw a sprite, not in a viewport.
Definition gfx.cpp:1032
uint8_t GetCharacterWidth(FontSize size, char32_t key)
Return width of character glyph.
Definition gfx.cpp:1272
void GfxFillRect(int left, int top, int right, int bottom, const std::variant< PixelColour, PaletteID > &colour, FillRectMode mode)
Applies a certain FillRectMode-operation to a rectangle [left, right] x [top, bottom] on the screen.
Definition gfx.cpp:111
int DrawStringMultiLine(int left, int right, int top, int bottom, std::string_view str, ExtendedTextColour colour, Alignment align, bool underline, FontSize fontsize)
Draw string, possibly over multiple lines.
Definition gfx.cpp:782
int DrawString(int left, int right, int top, std::string_view str, ExtendedTextColour colour, Alignment align, bool underline, FontSize fontsize)
Draw string, possibly truncated to make it fit in its allocated space.
Definition gfx.cpp:663
bool IsCtrlPressed()
Test if the ctrl key is pressed.
Definition gfx_func.h:82
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition gfx_type.h:17
@ Small
Index of the small font in the font tables.
Definition gfx_type.h:250
@ Normal
Index of the normal font in the font tables.
Definition gfx_type.h:249
@ Invalid
Invalid marker.
Definition gfx_type.h:302
@ Grey
Grey.
Definition gfx_type.h:299
@ DarkGreen
Dark green.
Definition gfx_type.h:292
TextColour
Colour of the strings, see _string_colourmap in table/string_colours.h or docs/ottd-colourtext-palett...
Definition gfx_type.h:315
@ Yellow
Yellow colour.
Definition gfx_type.h:326
@ Black
Black colour.
Definition gfx_type.h:334
void ShowStationGraph(WindowNumber window_number)
Create a station graph window for a station.
Graph GUI functions.
constexpr NWidgetPart SetFill(uint16_t fill_x, uint16_t fill_y)
Widget part function for setting filling.
constexpr NWidgetPart SetSpriteTip(SpriteID sprite, StringID tip={})
Widget part function for setting the sprite and tooltip.
constexpr NWidgetPart SetScrollbar(WidgetID index)
Attach a scrollbar to a widget.
constexpr NWidgetPart SetStringTip(StringID string, StringID tip={})
Widget part function for setting the string and tooltip.
constexpr NWidgetPart SetAspect(float ratio, AspectFlags flags=AspectFlag::ResizeX)
Widget part function for setting the aspect ratio.
constexpr NWidgetPart SetMinimalSize(int16_t x, int16_t y)
Widget part function for setting the minimal size.
constexpr NWidgetPart SetToolTip(StringID tip)
Widget part function for setting tooltip and clearing the widget data.
constexpr NWidgetPart EndContainer()
Widget part function for denoting the end of a container (horizontal, vertical, WWT_FRAME,...
constexpr NWidgetPart SetTextStyle(TextColour colour, FontSize size=FontSize::Normal)
Widget part function for setting the text style.
constexpr NWidgetPart NWidget(WidgetType tp, Colours col, WidgetID idx=INVALID_WIDGET)
Widget part function for starting a new 'real' widget.
constexpr NWidgetPart SetResize(int16_t dx, int16_t dy)
Widget part function for setting the resize step.
void SetDirty() const
Mark entire window as dirty (in need of re-paint).
Definition window.cpp:1013
GUI functions that shouldn't be here.
void ShowExtraViewportWindow(TileIndex tile=INVALID_TILE)
Show a new Extra Viewport window.
Declaration of link graph classes used for cargo distribution.
@ Manual
Manual distribution. No link graph calculations are run.
#define Rect
Macro that prevents name conflicts between included headers.
#define Point
Macro that prevents name conflicts between included headers.
uint DistanceMax(TileIndex t0, TileIndex t1)
Gets the biggest distance component (x or y) between the two given tiles.
Definition map.cpp:200
TileIndex TileAddXY(TileIndex tile, int x, int y)
Adds a given offset to a tile.
Definition map_func.h:474
static TileIndex TileVirtXY(uint x, uint y)
Get a tile from the virtual XY-coordinate.
Definition map_func.h:407
TileIndex TileAddByDir(TileIndex tile, Direction dir)
Adds a Direction to a tile.
Definition map_func.h:603
static TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
Definition map_func.h:376
static uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition map_func.h:429
static uint TileX(TileIndex tile)
Get the X component of a tile.
Definition map_func.h:419
int DivideApprox(int a, int b)
Deterministic approximate division.
Definition math_func.cpp:22
constexpr bool IsInsideBS(const T x, const size_t base, const size_t size)
Checks if a value is between a window started at some base point.
constexpr uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
constexpr uint ToPercent8(uint i)
Converts a "fract" value 0..255 to "percent" value 0..100.
void ShowQueryString(std::string_view str, StringID caption, uint maxsize, Window *parent, CharSetFilter afilter, QueryStringFlags flags)
Show a query popup window with a textbox in it.
Types related to the misc widgets.
@ WID_QS_MOVE
Move button.
Definition misc_widget.h:39
static constexpr CargoType CF_EXPAND_LIST
Expand list to show all items (station list).
Definition cargo_type.h:104
static constexpr CargoType CF_NO_RATING
Show items with no rating (station list).
Definition cargo_type.h:102
static constexpr CargoType CF_SELECT_ALL
Select all items (station list).
Definition cargo_type.h:103
TextColour GetContrastColour(PixelColour background, uint8_t threshold)
Determine a contrasty text colour for a coloured background.
Definition palette.cpp:366
static constexpr PixelColour PC_GREEN
Green palette colour.
static constexpr PixelColour PC_RED
Red palette colour.
Base for the GUIs that have an edit box in them.
A number of safeguards to prevent using unsafe methods.
@ Invalid
broken savegame (used internally)
Definition saveload.h:438
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
Base types for having sorted lists in GUIs.
void SndClickBeep()
Play a beep sound for a click event if enabled in settings.
Definition sound.cpp:252
Functions related to sound.
CommandCost CheckStationSpread(TileArea area, const TileArea &new_area)
Check if adding a new area to a station will exceed the maximum station spread.
Definition station.cpp:526
Base classes/functions for stations.
std::pair< CargoArray, CargoTypes > GetAcceptanceAroundTiles(TileIndex center_tile, int w, int h, int rad)
Get the acceptance of cargoes around the tile in 1/8.
bool HasStationInUse(StationID station, bool include_company, CompanyID company)
Tests whether the company's vehicles have this station in orders.
CargoTypes GetAcceptanceMask(const Station *st)
Get a mask of the cargo types that the station accepts.
CargoArray GetProductionAroundTiles(TileIndex north_tile, int w, int h, int rad)
Get the cargo types being produced around the tile (in a rectangle).
Command definitions related to stations.
Functions related to stations.
static void StationsWndShowStationRating(int left, int right, int y, CargoType cargo, uint amount, uint8_t rating)
Draw small boxes of cargo amount and ratings data at the given coordinates.
void ShowSelectStationIfNeeded(TileArea ta, StationPickerCmdProc proc)
Show the station selection window when needed.
CargoSortType
Ways of sorting cargo in the UI.
@ StationID
by station id
@ CargoType
by cargo type
@ AsGrouping
by the same principle the entries are being grouped
@ StationString
by station name
@ Count
by amount of cargo
void ShowSelectRailWaypointIfNeeded(TileArea ta, StationPickerCmdProc proc)
Show the rail waypoint selection window when needed.
void FindStationsAroundSelection()
Find stations adjacent to the current tile highlight area, so that existing coverage area can be draw...
static bool StationJoinerNeeded(const StationPickerCmdProc &proc)
Check whether we need to show the station selection window.
int DrawStationCoverageAreaText(const Rect &r, StationCoverageType sct, int rad, bool supplies)
Calculates and draws the accepted or supplied cargo around the selected tile(s).
void ShowStationViewWindow(StationID station)
Opens StationViewWindow for given station.
void CheckRedrawStationCoverage(const Window *w)
Check whether we need to redraw the station coverage text.
static WindowDesc _select_station_desc(WindowPosition::Automatic, "build_station_join", 200, 180, WindowClass::JoinStation, WindowClass::None, WindowDefaultFlag::Construction, _nested_select_station_widgets)
Window definition for the station selection window for (distant) joining.
void ShowCompanyStations(CompanyID company)
Opens window with list of company's stations.
void ShowSelectBaseStationIfNeeded(TileArea ta, StationPickerCmdProc &&proc)
Show the station selection window when needed.
static WindowDesc _station_view_desc(WindowPosition::Automatic, "view_station", 249, 117, WindowClass::StationView, WindowClass::None, {}, _nested_station_view_widgets)
Window definition for the station view window.
static void FindStationsNearby(TileArea ta, bool distant_join)
Circulate around the to-be-built station to find stations we could join.
static WindowDesc _company_stations_desc(WindowPosition::Automatic, "list_stations", 358, 162, WindowClass::StationList, WindowClass::None, {}, _nested_company_stations_widgets)
Window definition for the company stations window.
static void AddNearbyStation(TileIndex tile, TileArea *ctx)
Add station on this tile to _stations_nearby_list if it's fully within the station spread.
void ShowSelectRoadWaypointIfNeeded(TileArea ta, StationPickerCmdProc proc)
Show the road waypoint selection window when needed.
Contains enums and function declarations connected with stations GUI.
StationCoverageType
Types of cargo to display for station coverage.
Definition station_gui.h:20
@ SCT_NON_PASSENGERS_ONLY
Draw all non-passenger class cargoes.
Definition station_gui.h:22
@ SCT_PASSENGERS_ONLY
Draw only passenger class cargoes.
Definition station_gui.h:21
@ SCT_ALL
Draw all cargoes.
Definition station_gui.h:23
StationID GetStationIndex(Tile t)
Get StationID from a tile.
Definition station_map.h:26
StationFacility
The facilities a station might be having.
@ Dock
Station with a dock.
@ TruckStop
Station with truck stops.
@ Train
Station with train station.
@ Airport
Station with an airport.
@ BusStop
Station with bus stops.
EnumBitSet< StationFacility, uint8_t > StationFacilities
Bitset of StationFacility elements.
static const uint MAX_LENGTH_STATION_NAME_CHARS
The maximum length of a station name in characters including '\0'.
Types related to the station widgets.
@ WID_JS_CAPTION
Caption of the window.
@ WID_JS_PANEL
Main panel.
@ WID_JS_SCROLLBAR
Scrollbar of the panel.
@ WID_SV_CLOSE_AIRPORT
'Close airport' button.
@ WID_SV_GRAPH
Button to open cargo history window.
@ WID_SV_SORT_ORDER
'Sort order' button
@ WID_SV_CATCHMENT
Toggle catchment area highlight.
@ WID_SV_ROADVEHS
List of scheduled road vehs button.
@ WID_SV_SCROLLBAR
Scrollbar.
@ WID_SV_CAPTION
Caption of the window.
@ WID_SV_GROUP
label for "group by"
@ WID_SV_RENAME
'Rename' button.
@ WID_SV_SORT_BY
'Sort by' button
@ WID_SV_GROUP_BY
'Group by' button
@ WID_SV_PLANES
List of scheduled planes button.
@ WID_SV_ACCEPT_RATING_LIST
List of accepted cargoes / rating of cargoes.
@ WID_SV_WAITING
List of waiting cargo.
@ WID_SV_SHIPS
List of scheduled ships button.
@ WID_SV_LOCATION
'Location' button.
@ WID_SV_TRAINS
List of scheduled trains button.
@ WID_SV_ACCEPTS_RATINGS
'Accepts' / 'Ratings' button.
@ WID_SV_CLOSE_AIRPORT_SEL
Container for 'close airport' button, which can be hidden.
@ WID_STL_CAPTION
Caption of the window.
@ WID_STL_TRUCK
'TRUCK' button - list only facilities where is a truck stop.
@ WID_STL_SCROLLBAR
Scrollbar next to the main panel.
@ WID_STL_SORTDROPBTN
Dropdown button.
@ WID_STL_SORTBY
'Sort by' button - reverse sort direction.
@ WID_STL_TRAIN
'TRAIN' button - list only facilities where is a railroad station.
@ WID_STL_BUS
'BUS' button - list only facilities where is a bus stop.
@ WID_STL_FACILALL
'ALL' button - list all facilities.
@ WID_STL_LIST
The main panel, list of stations.
@ WID_STL_SHIP
'SHIP' button - list only facilities where is a dock.
@ WID_STL_FILTER
Filter of name.
@ WID_STL_CARGODROPDOWN
Cargo type dropdown list.
@ WID_STL_AIRPLANE
'AIRPLANE' button - list only facilities where is an airport.
Definition of base types and functions in a cross-platform compatible way.
int StrNaturalCompare(std::string_view s1, std::string_view s2, bool ignore_garbage_at_front)
Compares two strings using case insensitive natural sort.
Definition string.cpp:428
Functions related to low-level strings.
@ CS_ALPHANUMERAL
Both numeric and alphabetic and spaces and stuff.
Definition string_type.h:25
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:423
TextDirection _current_text_dir
Text direction of the currently selected language.
Definition strings.cpp:55
Functions related to OTTD's strings.
StrongType::Typedef< uint32_t, struct StringIDTag, StrongType::Compare, StrongType::Integer > StringID
Numeric value that represents a string, independent of the selected language.
@ TD_RTL
Text is written right-to-left by default.
static const int MAX_CHAR_LENGTH
Max. length of UTF-8 encoded unicode character.
AirportBlocks blocks
stores which blocks on the airport are taken. was 16 bit earlier on, then 32
Base class for all station-ish types.
TileIndex xy
Base tile of the station.
StationFacilities facilities
The facilities that this station has.
Owner owner
The owner of this station.
Town * town
The town this station is associated with.
TileArea spread
NOSAVE: Station spread tile area.
Class for storing amounts of cargo.
Definition cargo_type.h:120
Container for cargo from the same location and time.
Definition cargopacket.h:40
uint16_t Count() const
Gets the number of 'items' in this packet.
StationID GetFirstStation() const
Gets the ID of the station where the cargo was loaded for the first time.
Specification of a cargo type.
Definition cargotype.h:76
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo type.
Definition cargotype.h:140
StringID abbrev
Two letter abbreviation for this cargo type.
Definition cargotype.h:97
SpriteID GetCargoIcon() const
Get sprite for showing cargo of this type.
PixelColour rating_colour
Colour used for box representing the amount of cargo waiting at the station in the station rating vie...
Definition cargotype.h:80
bool IsValid() const
Tests for validity of this cargospec.
Definition cargotype.h:120
CargoTypes cargoes
bitmap of cargo types to include
StationFacilities facilities
types of stations of interest
bool include_no_rating
Whether we should include stations with no cargo rating.
Dimensions (a width and height) of a rectangle in 2D.
value_type height
The height of the rectangle.
value_type width
The width of the rectangle.
FlowStatMap flows
Planned flows through this station.
StationCargoList cargo
The cargo packets of cargo waiting in this station.
Stores station stats for a single cargo.
bool HasRating() const
Does this cargo have a rating at this station?
NodeID node
ID of node in link graph referring to this goods entry.
const GoodsEntryData & GetData() const
Get optional cargo packet/flow data.
LinkGraphID link_graph
Link graph this station belongs to.
uint8_t rating
Station rating for this cargo.
bool HasData() const
Test if this goods entry has optional cargo packet/flow data.
Data structure describing how to show the list (what sort direction and criteria).
static uint MaxY()
Gets the maximum Y coordinate within the map, including TileType::Void.
Definition map_func.h:298
static uint MaxX()
Gets the maximum X coordinate within the map, including TileType::Void.
Definition map_func.h:289
static uint Size()
Get the size of the map.
Definition map_func.h:280
Colour for pixel/line drawing.
Definition gfx_type.h:307
static Pool::IterateWrapper< BaseStation > Iterate(size_t from=0)
static BaseStation * Get(auto index)
static LinkGraph * GetIfValid(auto index)
Data stored about a string that can be modified in the GUI.
static const int ACTION_CLEAR
Clear editbox.
Specification of a rectangle with absolute coordinates of all edges.
Rect WithWidth(int width, bool end) const
Copy Rect and set its width.
int Width() const
Get width of Rect.
Rect Shrink(int s) const
Copy and shrink Rect by s pixels.
Rect Indent(int indent, bool end) const
Copy Rect and indent it from its position.
Window for selecting stations/waypoints to (distant) join to.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
void OnRealtimeTick(uint delta_ms) override
Called periodically.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
void OnResize() override
Called after the window got resized.
void Close(int data=0) override
Hide the window and all its child windows, and mark them for a later deletion.
void OnMouseOver(Point pt, WidgetID widget) override
The mouse is currently moving over the window or has just moved outside of the window.
TileArea area
Location of new station.
void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
Update size and resize step of a widget in the window.
static bool IsExpected(const BaseStation *st)
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
static Waypoint * Get(auto index)
static Waypoint * From(BaseStation *st)
A row being displayed in the cargo view (as opposed to being "hidden" behind a plus sign).
StationID next_station
ID of the station belonging to the entry actually displayed if it's to/from/via.
CargoDataEntry * filter
Parent of the cargo entry belonging to the row.
CargoType next_cargo
ID of the cargo belonging to the entry actually displayed if it's cargo.
The StationView window.
void HandleCargoWaitingClick(int row)
Handle a click on a specific row in the cargo view.
int DrawEntries(CargoDataEntry &entry, const Rect &r, int pos, int maxrows, int column, CargoType cargo=INVALID_CARGO)
Draw the given cargo entries in the station GUI.
void OnQueryTextFinished(std::optional< std::string > str) override
The query window opened from this window has closed.
void OnDropdownSelect(WidgetID widget, int index, int) override
A dropdown option associated to this window has been selected.
Mode
Display mode of the cargo view.
@ MODE_PLANNED
Show cargo planned to pass through the station.
@ MODE_WAITING
Show cargo waiting at the station.
std::array< Grouping, NUM_COLUMNS > groupings
Grouping modes for the different columns.
void EstimateDestinations(CargoType cargo, StationID source, StationID next, uint count, CargoDataEntry &dest)
Estimate the amounts of cargo per final destination for a given cargo, source station and next hop an...
void SelectSortBy(int index)
Select a new sort criterium for the cargo view.
void OnResize() override
Called after the window got resized.
StringID SearchNonStop(CargoDataEntry &cd, StationID station, int column)
Determine if we need to show the special "non-stop" string.
void Close(int data=0) override
Hide the window and all its child windows, and mark them for a later deletion.
Grouping
Type of grouping used in each of the "columns".
@ GR_SOURCE
Group by source of cargo ("from").
@ GR_NEXT
Group by next station ("via").
@ GR_CARGO
Group by cargo type.
@ GR_DESTINATION
Group by estimated final destination ("to").
void BuildCargoList(CargoType cargo, const StationCargoList &packets, CargoDataEntry *entry)
Build up the cargo view for WAITING mode and a specific cargo.
int DrawCargoRatings(const Rect &r) const
Draw cargo ratings in the WID_SV_ACCEPT_RATING_LIST widget.
static const int NUM_COLUMNS
Number of "columns" in the cargo view: cargo, from, via, to.
void OnInit() override
Notification that the nested widget tree gets initialized.
void RecalcDestinations(CargoType cargo)
Rebuild the cache for estimated destinations which is used to quickly show the "destination" entries ...
int line_height
Height of a cargo line.
Dimension cargo_icon_size
Size of largest cargo icon.
Invalidation
Type of data invalidation.
@ INV_FLOWS
The planned flows have been recalculated and everything has to be updated.
@ INV_CARGO
Some cargo has been added or removed.
void BuildCargoList(CargoDataEntry *entry, const Station *st)
Build up the cargo view for all cargoes.
void SelectSortOrder(SortOrder order)
Select a new sort order for the cargo view.
CargoDataEntry expanded_rows
Parent entry of currently expanded rows.
void OnPaint() override
The window must be repainted.
static constexpr uint RATING_LINES
Height in lines of the cargo ratings view.
CargoDataVector displayed_rows
Parent entry of currently displayed rows (including collapsed ones).
static const StringID group_names[]
Names of the grouping options in the dropdown.
int grouping_index
Currently selected entry in the grouping drop down.
void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
Update size and resize step of a widget in the window.
static constexpr uint ACCEPTS_LINES
Height in lines of the accepted cargo view.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
StringID GetEntryString(StationID station, StringID here, StringID other_station, StringID any) const
Select the correct string for an entry referring to the specified station.
std::array< CargoSortType, NUM_COLUMNS > sortings
Sort types of the different 'columns'.
void SetDisplayedRow(const CargoDataEntry &entry)
Mark a specific row, characterized by its CargoDataEntry, as expanded.
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
std::array< SortOrder, NUM_COLUMNS > sort_orders
Sort order (ascending/descending) for the 'columns'.
uint expand_shrink_width
The width allocated to the expand/shrink 'button'.
void HandleCargoWaitingClick(CargoDataEntry *filter, Tid next)
Expand or collapse a specific row.
int rating_lines
Number of lines in the cargo ratings view.
static const StringID sort_names[]
Names of the sorting options in the dropdown.
void DrawCargoIcons(CargoType cargo, uint waiting, const Rect &r) const
Draw icons of waiting cargo.
CargoDataEntry cached_destinations
Cache for the flows passing through this station.
int scroll_to_row
If set, scroll the main viewport to the station pointed to by this row.
Mode current_mode
Currently selected display mode of cargo view.
int accepts_lines
Number of lines in the accepted cargo view.
void BuildFlowList(CargoType cargo, const FlowStatMap &flows, CargoDataEntry *entry)
Build up the cargo view for PLANNED mode and a specific cargo.
void SelectGroupBy(int index)
Select a new grouping mode for the cargo view.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
int DrawAcceptedCargo(const Rect &r) const
Draw accepted cargo in the WID_SV_ACCEPT_RATING_LIST widget.
void ShowCargo(CargoDataEntry *data, CargoType cargo, StationID source, StationID next, StationID dest, uint count)
Show a certain cargo entry characterized by source/next/dest station, cargo type and amount of cargo ...
Station data structure.
std::array< GoodsEntry, NUM_CARGO > goods
Goods at this station.
Airport airport
Tile area the airport covers.
String filter and state.
void SetFilterTerm(std::string_view str)
Set the term to filter on.
void ResetState()
Reset the matching state to process a new item.
bool GetState() const
Get the matching state of the current item.
std::string_view GetText() const
Get the current text.
Definition textbuf.cpp:283
Struct containing TileIndex and StationID.
TileIndex tile
TileIndex.
StationID station
StationID.
CompanyID exclusivity
which company has exclusivity
Definition town.h:87
uint8_t exclusive_counter
months till the exclusivity expires
Definition town.h:88
The information about a vehicle list.
Definition vehiclelist.h:32
Representation of a waypoint.
High level window description.
Definition window_gui.h:171
Number to differentiate different windows of the same class.
Data structure for an opened window.
Definition window_gui.h:272
void ReInit(int rx=0, int ry=0, bool reposition=false)
Re-initialize a window, and optionally change its size.
Definition window.cpp:1025
void CloseChildWindows(WindowClass wc=WindowClass::Invalid) const
Close all children a window might have in a head-recursive manner.
Definition window.cpp:1122
virtual void Close(int data=0)
Hide the window and all its child windows, and mark them for a later deletion.
Definition window.cpp:1150
static int SortButtonWidth()
Get width of up/down arrow of sort button state.
Definition widget.cpp:839
void FinishInitNested(WindowNumber window_number=0)
Perform the second part of the initialization of a nested widget tree.
Definition window.cpp:1855
void DrawWidgets() const
Paint all widgets of a window.
Definition widget.cpp:792
void InvalidateData(int data=0, bool gui_scope=true)
Mark this window's data as invalid (in need of re-computing).
Definition window.cpp:3317
Window * parent
Parent window.
Definition window_gui.h:327
void RaiseWidget(WidgetID widget_index)
Marks a widget as raised.
Definition window_gui.h:468
void SetWidgetDirty(WidgetID widget_index) const
Invalidate a widget, i.e.
Definition window.cpp:565
virtual std::string GetWidgetString(WidgetID widget, StringID stringid) const
Get the raw string for a widget.
Definition window.cpp:513
ResizeInfo resize
Resize information.
Definition window_gui.h:313
void DrawSortButton(WidgetID widget, bool descending) const
Draw a sort button's up or down arrow symbol.
Definition widget.cpp:824
void CreateNestedTree()
Perform the first part of the initialization of a nested widget tree.
Definition window.cpp:1845
WindowClass window_class
Window class.
Definition window_gui.h:300
bool IsWidgetLowered(WidgetID widget_index) const
Gets the lowered state of a widget.
Definition window_gui.h:490
Owner owner
The owner of the content shown in this window. Company colour is acquired from this variable.
Definition window_gui.h:315
void SetWidgetLoweredState(WidgetID widget_index, bool lowered_stat)
Sets the lowered/raised status of a widget.
Definition window_gui.h:440
bool IsShaded() const
Is window shaded currently?
Definition window_gui.h:561
void SetTimeout()
Set the timeout flag of the window and initiate the timer.
Definition window_gui.h:354
Window(WindowDesc &desc)
Empty constructor, initialization has been moved to InitNested() called from the constructor of the d...
Definition window.cpp:1879
const NWID * GetWidget(WidgetID widnum) const
Get the nested widget with number widnum from the nested widget tree.
void LowerWidget(WidgetID widget_index)
Marks a widget as lowered.
Definition window_gui.h:459
const Scrollbar * GetScrollbar(WidgetID widnum) const
Return the Scrollbar to a widget index.
Definition window.cpp:322
void SetWidgetDisabledState(WidgetID widget_index, bool disab_stat)
Sets the enabled/disabled status of a widget.
Definition window_gui.h:380
int width
width of the window (number of pixels to the right in x direction)
Definition window_gui.h:310
void ToggleWidgetLoweredState(WidgetID widget_index)
Invert the lowered/raised status of a widget.
Definition window_gui.h:449
WindowNumber window_number
Window number within the window class.
Definition window_gui.h:301
Stuff related to the text buffer GUI.
@ EnableMove
enable the 'Move' button
Definition textbuf_gui.h:22
@ EnableDefault
enable the 'Default' button ("\0" is returned)
Definition textbuf_gui.h:20
@ LengthIsInChars
the length of the string is counted in characters
Definition textbuf_gui.h:21
static bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition tile_map.h:150
Owner GetTileOwner(Tile tile)
Returns the owner of a tile.
Definition tile_map.h:178
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
Definition tile_type.h:92
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition tile_type.h:100
static constexpr uint TILE_SIZE
Tile size in world coordinates.
Definition tile_type.h:15
@ Station
A tile of a station or airport.
Definition tile_type.h:54
OrthogonalTileArea TileArea
Shorthand for the much more common orthogonal tile area.
Type for iterating a sprial tile area.
Functions related to tile highlights.
void ResetObjectToPlace()
Reset the cursor and mouse mode handling back to default (normal cursor, only clicking in windows).
void UpdateTileSelection()
Updates tile highlighting for all cases.
@ HT_RECT
rectangle (stations, depots, ...)
Base of the town class.
Functions related to the vehicle's GUIs.
VehicleType
Available vehicle types.
@ Ship
Ship vehicle type.
@ Aircraft
Aircraft vehicle type.
@ Road
Road vehicle type.
@ Train
Train vehicle type.
Functions and type for generating vehicle lists.
@ Station
Index is the station.
Definition vehiclelist.h:25
bool ScrollMainWindowToTile(TileIndex tile, bool instant)
Scrolls the viewport of the main window to a given location.
void SetViewportStationRect(const Station *st, bool sel)
Select or deselect station for rectangle area highlight.
void SetViewportCatchmentStation(const Station *st, bool sel)
Select or deselect station for coverage area highlight.
void SetViewportWaypointRect(const Waypoint *wp, bool sel)
Select or deselect waypoint for rectangle area highlight.
const Station * _viewport_highlight_station
Currently selected station for coverage area highlight.
Functions related to (drawing on) viewports.
Base of waypoints.
@ WPF_ROAD
This is a road waypoint.
static RectPadding ScaleGUITrad(const RectPadding &r)
Scale a RectPadding to GUI zoom level.
Definition widget.cpp:49
@ WWT_PUSHTXTBTN
Normal push-button (no toggle button) with text caption.
@ WWT_PUSHIMGBTN
Normal push-button (no toggle button) with image caption.
@ WWT_EDITBOX
a textbox for typing
Definition widget_type.h:62
@ NWID_HORIZONTAL
Horizontal container.
Definition widget_type.h:66
@ WWT_TEXTBTN
(Toggle) Button with text
Definition widget_type.h:44
@ WWT_PANEL
Simple depressed panel.
Definition widget_type.h:39
@ WWT_STICKYBOX
Sticky box (at top-right of a window, after WWT_DEFSIZEBOX).
Definition widget_type.h:57
@ WWT_SHADEBOX
Shade box (at top-right of a window, between WWT_DEBUGBOX and WWT_DEFSIZEBOX).
Definition widget_type.h:55
@ WWT_CAPTION
Window caption (window title between closebox and stickybox).
Definition widget_type.h:52
@ NWID_VSCROLLBAR
Vertical scrollbar.
Definition widget_type.h:76
@ NWID_VERTICAL
Vertical container.
Definition widget_type.h:68
@ WWT_CLOSEBOX
Close box (at top-left of a window).
Definition widget_type.h:60
@ WWT_RESIZEBOX
Resize box (normally at bottom-right of a window).
Definition widget_type.h:59
@ WWT_DEFSIZEBOX
Default window size box (at top-right of a window, between WWT_SHADEBOX and WWT_STICKYBOX).
Definition widget_type.h:56
@ WWT_DROPDOWN
Drop down list.
Definition widget_type.h:61
@ NWID_SELECTION
Stacked widgets, only one visible at a time (eg in a panel with tabs).
Definition widget_type.h:71
@ SZSP_NONE
Display plane with zero size in both directions (none filling and resizing).
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
Definition window.cpp:1242
Window * FindWindowByClass(WindowClass cls)
Find any window by its class.
Definition window.cpp:1214
Window * FindWindowById(WindowClass cls, WindowNumber number)
Find a window by its class and window number.
Definition window.cpp:1199
Window functions not directly related to making/drawing windows.
@ Construction
This window is used for construction; close it whenever changing company.
Definition window_gui.h:154
Twindow * AllocateWindowDescFront(WindowDesc &desc, WindowNumber window_number, Targs... extra_arguments)
Open a new window.
@ Automatic
Find a place automatically.
Definition window_gui.h:145
int WidgetID
Widget ID.
Definition window_type.h:21
Functions related to zooming.
int ScaleSpriteTrad(int value)
Scale traditional pixel dimensions to GUI zoom level, for drawing sprites.
Definition zoom_func.h:107