Change: Let AI developers edit non-editable AI/Game Script Parameters (#8895)
[openttd-github.git] / src / station_gui.cpp
blob965b7e04f28d37a9be225f96c63e434a08ac7e4d
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /** @file station_gui.cpp The GUI for stations. */
10 #include "stdafx.h"
11 #include "debug.h"
12 #include "gui.h"
13 #include "textbuf_gui.h"
14 #include "company_func.h"
15 #include "command_func.h"
16 #include "vehicle_gui.h"
17 #include "cargotype.h"
18 #include "station_gui.h"
19 #include "strings_func.h"
20 #include "string_func.h"
21 #include "window_func.h"
22 #include "viewport_func.h"
23 #include "widgets/dropdown_func.h"
24 #include "station_base.h"
25 #include "waypoint_base.h"
26 #include "tilehighlight_func.h"
27 #include "company_base.h"
28 #include "sortlist_type.h"
29 #include "core/geometry_func.hpp"
30 #include "vehiclelist.h"
31 #include "town.h"
32 #include "linkgraph/linkgraph.h"
33 #include "zoom_func.h"
34 #include "station_cmd.h"
36 #include "widgets/station_widget.h"
38 #include "table/strings.h"
40 #include <set>
41 #include <vector>
43 #include "safeguards.h"
45 /**
46 * Calculates and draws the accepted or supplied cargo around the selected tile(s)
47 * @param left x position where the string is to be drawn
48 * @param right the right most position to draw on
49 * @param top y position where the string is to be drawn
50 * @param sct which type of cargo is to be displayed (passengers/non-passengers)
51 * @param rad radius around selected tile(s) to be searched
52 * @param supplies if supplied cargoes should be drawn, else accepted cargoes
53 * @return Returns the y value below the string that was drawn
55 int DrawStationCoverageAreaText(int left, int right, int top, StationCoverageType sct, int rad, bool supplies)
57 TileIndex tile = TileVirtXY(_thd.pos.x, _thd.pos.y);
58 CargoTypes cargo_mask = 0;
59 if (_thd.drawstyle == HT_RECT && tile < MapSize()) {
60 CargoArray cargoes;
61 if (supplies) {
62 cargoes = GetProductionAroundTiles(tile, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE, rad);
63 } else {
64 cargoes = GetAcceptanceAroundTiles(tile, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE, rad);
67 /* Convert cargo counts to a set of cargo bits, and draw the result. */
68 for (CargoID i = 0; i < NUM_CARGO; i++) {
69 switch (sct) {
70 case SCT_PASSENGERS_ONLY: if (!IsCargoInClass(i, CC_PASSENGERS)) continue; break;
71 case SCT_NON_PASSENGERS_ONLY: if (IsCargoInClass(i, CC_PASSENGERS)) continue; break;
72 case SCT_ALL: break;
73 default: NOT_REACHED();
75 if (cargoes[i] >= (supplies ? 1U : 8U)) SetBit(cargo_mask, i);
78 SetDParam(0, cargo_mask);
79 return DrawStringMultiLine(left, right, top, INT32_MAX, supplies ? STR_STATION_BUILD_SUPPLIES_CARGO : STR_STATION_BUILD_ACCEPTS_CARGO);
82 /**
83 * Find stations adjacent to the current tile highlight area, so that existing coverage
84 * area can be drawn.
86 static void FindStationsAroundSelection()
88 /* With distant join we don't know which station will be selected, so don't show any */
89 if (_ctrl_pressed) {
90 SetViewportCatchmentStation(nullptr, true);
91 return;
94 /* Tile area for TileHighlightData */
95 TileArea location(TileVirtXY(_thd.pos.x, _thd.pos.y), _thd.size.x / TILE_SIZE - 1, _thd.size.y / TILE_SIZE - 1);
97 /* Extended area by one tile */
98 uint x = TileX(location.tile);
99 uint y = TileY(location.tile);
101 int max_c = 1;
102 TileArea ta(TileXY(std::max<int>(0, x - max_c), std::max<int>(0, y - max_c)), TileXY(std::min<int>(MapMaxX(), x + location.w + max_c), std::min<int>(MapMaxY(), y + location.h + max_c)));
104 Station *adjacent = nullptr;
106 /* Direct loop instead of ForAllStationsAroundTiles as we are not interested in catchment area */
107 for (TileIndex tile : ta) {
108 if (IsTileType(tile, MP_STATION) && GetTileOwner(tile) == _local_company) {
109 Station *st = Station::GetByTile(tile);
110 if (st == nullptr) continue;
111 if (adjacent != nullptr && st != adjacent) {
112 /* Multiple nearby, distant join is required. */
113 adjacent = nullptr;
114 break;
116 adjacent = st;
119 SetViewportCatchmentStation(adjacent, true);
123 * Check whether we need to redraw the station coverage text.
124 * If it is needed actually make the window for redrawing.
125 * @param w the window to check.
127 void CheckRedrawStationCoverage(const Window *w)
129 /* Test if ctrl state changed */
130 static bool _last_ctrl_pressed;
131 if (_ctrl_pressed != _last_ctrl_pressed) {
132 _thd.dirty = 0xff;
133 _last_ctrl_pressed = _ctrl_pressed;
136 if (_thd.dirty & 1) {
137 _thd.dirty &= ~1;
138 w->SetDirty();
140 if (_settings_client.gui.station_show_coverage && _thd.drawstyle == HT_RECT) {
141 FindStationsAroundSelection();
147 * Draw small boxes of cargo amount and ratings data at the given
148 * coordinates. If amount exceeds 576 units, it is shown 'full', same
149 * goes for the rating: at above 90% orso (224) it is also 'full'
151 * @param left left most coordinate to draw the box at
152 * @param right right most coordinate to draw the box at
153 * @param y coordinate to draw the box at
154 * @param type Cargo type
155 * @param amount Cargo amount
156 * @param rating ratings data for that particular cargo
158 static void StationsWndShowStationRating(int left, int right, int y, CargoID type, uint amount, byte rating)
160 static const uint units_full = 576; ///< number of units to show station as 'full'
161 static const uint rating_full = 224; ///< rating needed so it is shown as 'full'
163 const CargoSpec *cs = CargoSpec::Get(type);
164 if (!cs->IsValid()) return;
166 int padding = ScaleFontTrad(1);
167 int width = right - left;
168 int colour = cs->rating_colour;
169 TextColour tc = GetContrastColour(colour);
170 uint w = std::min(amount + 5, units_full) * width / units_full;
172 int height = GetCharacterHeight(FS_SMALL) + padding - 1;
174 if (amount > 30) {
175 /* Draw total cargo (limited) on station */
176 GfxFillRect(left, y, left + w - 1, y + height, colour);
177 } else {
178 /* Draw a (scaled) one pixel-wide bar of additional cargo meter, useful
179 * for stations with only a small amount (<=30) */
180 uint rest = ScaleFontTrad(amount) / 5;
181 if (rest != 0) {
182 GfxFillRect(left, y + height - rest, left + padding - 1, y + height, colour);
186 DrawString(left + padding, right, y, cs->abbrev, tc);
188 /* Draw green/red ratings bar (fits under the waiting bar) */
189 y += height + padding + 1;
190 GfxFillRect(left + padding, y, right - padding - 1, y + padding - 1, PC_RED);
191 w = std::min<uint>(rating, rating_full) * (width - padding - padding) / rating_full;
192 if (w != 0) GfxFillRect(left + padding, y, left + w - 1, y + padding - 1, PC_GREEN);
195 typedef GUIList<const Station*> GUIStationList;
198 * The list of stations per company.
200 class CompanyStationsWindow : public Window
202 protected:
203 /* Runtime saved values */
204 static Listing last_sorting;
205 static byte facilities; // types of stations of interest
206 static bool include_empty; // whether we should include stations without waiting cargo
207 static const CargoTypes cargo_filter_max;
208 static CargoTypes cargo_filter; // bitmap of cargo types to include
210 /* Constants for sorting stations */
211 static const StringID sorter_names[];
212 static GUIStationList::SortFunction * const sorter_funcs[];
214 GUIStationList stations;
215 Scrollbar *vscroll;
216 uint rating_width;
219 * (Re)Build station list
221 * @param owner company whose stations are to be in list
223 void BuildStationsList(const Owner owner)
225 if (!this->stations.NeedRebuild()) return;
227 Debug(misc, 3, "Building station list for company {}", owner);
229 this->stations.clear();
231 for (const Station *st : Station::Iterate()) {
232 if (st->owner == owner || (st->owner == OWNER_NONE && HasStationInUse(st->index, true, owner))) {
233 if (this->facilities & st->facilities) { // only stations with selected facilities
234 int num_waiting_cargo = 0;
235 for (CargoID j = 0; j < NUM_CARGO; j++) {
236 if (st->goods[j].HasRating()) {
237 num_waiting_cargo++; // count number of waiting cargo
238 if (HasBit(this->cargo_filter, j)) {
239 this->stations.push_back(st);
240 break;
244 /* stations without waiting cargo */
245 if (num_waiting_cargo == 0 && this->include_empty) {
246 this->stations.push_back(st);
252 this->stations.shrink_to_fit();
253 this->stations.RebuildDone();
255 this->vscroll->SetCount((uint)this->stations.size()); // Update the scrollbar
258 /** Sort stations by their name */
259 static bool StationNameSorter(const Station * const &a, const Station * const &b)
261 int r = strnatcmp(a->GetCachedName(), b->GetCachedName()); // Sort by name (natural sorting).
262 if (r == 0) return a->index < b->index;
263 return r < 0;
266 /** Sort stations by their type */
267 static bool StationTypeSorter(const Station * const &a, const Station * const &b)
269 return a->facilities < b->facilities;
272 /** Sort stations by their waiting cargo */
273 static bool StationWaitingTotalSorter(const Station * const &a, const Station * const &b)
275 int diff = 0;
277 for (CargoID j : SetCargoBitIterator(cargo_filter)) {
278 diff += a->goods[j].cargo.TotalCount() - b->goods[j].cargo.TotalCount();
281 return diff < 0;
284 /** Sort stations by their available waiting cargo */
285 static bool StationWaitingAvailableSorter(const Station * const &a, const Station * const &b)
287 int diff = 0;
289 for (CargoID j : SetCargoBitIterator(cargo_filter)) {
290 diff += a->goods[j].cargo.AvailableCount() - b->goods[j].cargo.AvailableCount();
293 return diff < 0;
296 /** Sort stations by their rating */
297 static bool StationRatingMaxSorter(const Station * const &a, const Station * const &b)
299 byte maxr1 = 0;
300 byte maxr2 = 0;
302 for (CargoID j : SetCargoBitIterator(cargo_filter)) {
303 if (a->goods[j].HasRating()) maxr1 = std::max(maxr1, a->goods[j].rating);
304 if (b->goods[j].HasRating()) maxr2 = std::max(maxr2, b->goods[j].rating);
307 return maxr1 < maxr2;
310 /** Sort stations by their rating */
311 static bool StationRatingMinSorter(const Station * const &a, const Station * const &b)
313 byte minr1 = 255;
314 byte minr2 = 255;
316 for (CargoID j = 0; j < NUM_CARGO; j++) {
317 if (!HasBit(cargo_filter, j)) continue;
318 if (a->goods[j].HasRating()) minr1 = std::min(minr1, a->goods[j].rating);
319 if (b->goods[j].HasRating()) minr2 = std::min(minr2, b->goods[j].rating);
322 return minr1 > minr2;
325 /** Sort the stations list */
326 void SortStationsList()
328 if (!this->stations.Sort()) return;
330 /* Set the modified widget dirty */
331 this->SetWidgetDirty(WID_STL_LIST);
334 public:
335 CompanyStationsWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
337 this->stations.SetListing(this->last_sorting);
338 this->stations.SetSortFuncs(this->sorter_funcs);
339 this->stations.ForceRebuild();
340 this->stations.NeedResort();
341 this->SortStationsList();
343 this->CreateNestedTree();
344 this->vscroll = this->GetScrollbar(WID_STL_SCROLLBAR);
345 this->FinishInitNested(window_number);
346 this->owner = (Owner)this->window_number;
348 uint8 index = 0;
349 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
350 if (HasBit(this->cargo_filter, cs->Index())) {
351 this->LowerWidget(WID_STL_CARGOSTART + index);
353 index++;
356 if (this->cargo_filter == this->cargo_filter_max) this->cargo_filter = _cargo_mask;
358 for (uint i = 0; i < 5; i++) {
359 if (HasBit(this->facilities, i)) this->LowerWidget(i + WID_STL_TRAIN);
361 this->SetWidgetLoweredState(WID_STL_NOCARGOWAITING, this->include_empty);
363 this->GetWidget<NWidgetCore>(WID_STL_SORTDROPBTN)->widget_data = this->sorter_names[this->stations.SortType()];
366 ~CompanyStationsWindow()
368 this->last_sorting = this->stations.GetListing();
371 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
373 switch (widget) {
374 case WID_STL_SORTBY: {
375 Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
376 d.width += padding.width + Window::SortButtonWidth() * 2; // Doubled since the string is centred and it also looks better.
377 d.height += padding.height;
378 *size = maxdim(*size, d);
379 break;
382 case WID_STL_SORTDROPBTN: {
383 Dimension d = {0, 0};
384 for (int i = 0; this->sorter_names[i] != INVALID_STRING_ID; i++) {
385 d = maxdim(d, GetStringBoundingBox(this->sorter_names[i]));
387 d.width += padding.width;
388 d.height += padding.height;
389 *size = maxdim(*size, d);
390 break;
393 case WID_STL_LIST:
394 resize->height = std::max(FONT_HEIGHT_NORMAL, FONT_HEIGHT_SMALL + ScaleFontTrad(3));
395 size->height = WD_FRAMERECT_TOP + 5 * resize->height + WD_FRAMERECT_BOTTOM;
397 /* Determine appropriate width for mini station rating graph */
398 this->rating_width = 0;
399 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
400 this->rating_width = std::max(this->rating_width, GetStringBoundingBox(cs->abbrev).width);
402 /* Approximately match original 16 pixel wide rating bars by multiplying string width by 1.6 */
403 this->rating_width = this->rating_width * 16 / 10;
404 break;
406 default:
407 if (widget >= WID_STL_CARGOSTART) {
408 Dimension d = GetStringBoundingBox(_sorted_cargo_specs[widget - WID_STL_CARGOSTART]->abbrev);
409 d.width += padding.width + 2;
410 d.height += padding.height;
411 *size = maxdim(*size, d);
413 break;
417 void OnPaint() override
419 this->BuildStationsList((Owner)this->window_number);
420 this->SortStationsList();
422 this->DrawWidgets();
425 void DrawWidget(const Rect &r, int widget) const override
427 switch (widget) {
428 case WID_STL_SORTBY:
429 /* draw arrow pointing up/down for ascending/descending sorting */
430 this->DrawSortButtonState(WID_STL_SORTBY, this->stations.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
431 break;
433 case WID_STL_LIST: {
434 bool rtl = _current_text_dir == TD_RTL;
435 int max = std::min<size_t>(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->stations.size());
436 int y = r.top + WD_FRAMERECT_TOP;
437 uint line_height = this->GetWidget<NWidgetBase>(widget)->resize_y;
438 /* Spacing between station name and first rating graph. */
439 int text_spacing = ScaleFontTrad(5);
440 /* Spacing between additional rating graphs. */
441 int rating_spacing = ScaleFontTrad(4);
443 for (int i = this->vscroll->GetPosition(); i < max; ++i) { // do until max number of stations of owner
444 const Station *st = this->stations[i];
445 assert(st->xy != INVALID_TILE);
447 /* Do not do the complex check HasStationInUse here, it may be even false
448 * when the order had been removed and the station list hasn't been removed yet */
449 assert(st->owner == owner || st->owner == OWNER_NONE);
451 SetDParam(0, st->index);
452 SetDParam(1, st->facilities);
453 int x = DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y + (line_height - FONT_HEIGHT_NORMAL) / 2, STR_STATION_LIST_STATION);
454 x += rtl ? -text_spacing : text_spacing;
456 /* show cargo waiting and station ratings */
457 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
458 CargoID cid = cs->Index();
459 if (st->goods[cid].cargo.TotalCount() > 0) {
460 /* For RTL we work in exactly the opposite direction. So
461 * decrement the space needed first, then draw to the left
462 * instead of drawing to the left and then incrementing
463 * the space. */
464 if (rtl) {
465 x -= rating_width + rating_spacing;
466 if (x < r.left + WD_FRAMERECT_LEFT) break;
468 StationsWndShowStationRating(x, x + rating_width, y, cid, st->goods[cid].cargo.TotalCount(), st->goods[cid].rating);
469 if (!rtl) {
470 x += rating_width + rating_spacing;
471 if (x > r.right - WD_FRAMERECT_RIGHT) break;
475 y += line_height;
478 if (this->vscroll->GetCount() == 0) { // company has no stations
479 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_LIST_NONE);
480 return;
482 break;
485 default:
486 if (widget >= WID_STL_CARGOSTART) {
487 const CargoSpec *cs = _sorted_cargo_specs[widget - WID_STL_CARGOSTART];
488 int cg_ofst = HasBit(this->cargo_filter, cs->Index()) ? 1 : 0;
489 GfxFillRect(r.left + cg_ofst + 1, r.top + cg_ofst + 1, r.right - 1 + cg_ofst, r.bottom - 1 + cg_ofst, cs->rating_colour);
490 TextColour tc = GetContrastColour(cs->rating_colour);
491 DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + (r.bottom - r.top - FONT_HEIGHT_SMALL) / 2 + cg_ofst, cs->abbrev, tc, SA_HOR_CENTER);
493 break;
497 void SetStringParameters(int widget) const override
499 if (widget == WID_STL_CAPTION) {
500 SetDParam(0, this->window_number);
501 SetDParam(1, this->vscroll->GetCount());
505 void OnClick(Point pt, int widget, int click_count) override
507 switch (widget) {
508 case WID_STL_LIST: {
509 uint id_v = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_STL_LIST);
510 if (id_v >= this->stations.size()) return; // click out of list bound
512 const Station *st = this->stations[id_v];
513 /* do not check HasStationInUse - it is slow and may be invalid */
514 assert(st->owner == (Owner)this->window_number || st->owner == OWNER_NONE);
516 if (_ctrl_pressed) {
517 ShowExtraViewportWindow(st->xy);
518 } else {
519 ScrollMainWindowToTile(st->xy);
521 break;
524 case WID_STL_TRAIN:
525 case WID_STL_TRUCK:
526 case WID_STL_BUS:
527 case WID_STL_AIRPLANE:
528 case WID_STL_SHIP:
529 if (_ctrl_pressed) {
530 ToggleBit(this->facilities, widget - WID_STL_TRAIN);
531 this->ToggleWidgetLoweredState(widget);
532 } else {
533 for (uint i : SetBitIterator(this->facilities)) {
534 this->RaiseWidget(i + WID_STL_TRAIN);
536 this->facilities = 1 << (widget - WID_STL_TRAIN);
537 this->LowerWidget(widget);
539 this->stations.ForceRebuild();
540 this->SetDirty();
541 break;
543 case WID_STL_FACILALL:
544 for (uint i = WID_STL_TRAIN; i <= WID_STL_SHIP; i++) {
545 this->LowerWidget(i);
548 this->facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK;
549 this->stations.ForceRebuild();
550 this->SetDirty();
551 break;
553 case WID_STL_CARGOALL: {
554 for (uint i = 0; i < _sorted_standard_cargo_specs.size(); i++) {
555 this->LowerWidget(WID_STL_CARGOSTART + i);
557 this->LowerWidget(WID_STL_NOCARGOWAITING);
559 this->cargo_filter = _cargo_mask;
560 this->include_empty = true;
561 this->stations.ForceRebuild();
562 this->SetDirty();
563 break;
566 case WID_STL_SORTBY: // flip sorting method asc/desc
567 this->stations.ToggleSortOrder();
568 this->SetDirty();
569 break;
571 case WID_STL_SORTDROPBTN: // select sorting criteria dropdown menu
572 ShowDropDownMenu(this, this->sorter_names, this->stations.SortType(), WID_STL_SORTDROPBTN, 0, 0);
573 break;
575 case WID_STL_NOCARGOWAITING:
576 if (_ctrl_pressed) {
577 this->include_empty = !this->include_empty;
578 this->ToggleWidgetLoweredState(WID_STL_NOCARGOWAITING);
579 } else {
580 for (uint i = 0; i < _sorted_standard_cargo_specs.size(); i++) {
581 this->RaiseWidget(WID_STL_CARGOSTART + i);
584 this->cargo_filter = 0;
585 this->include_empty = true;
587 this->LowerWidget(WID_STL_NOCARGOWAITING);
589 this->stations.ForceRebuild();
590 this->SetDirty();
591 break;
593 default:
594 if (widget >= WID_STL_CARGOSTART) { // change cargo_filter
595 /* Determine the selected cargo type */
596 const CargoSpec *cs = _sorted_cargo_specs[widget - WID_STL_CARGOSTART];
598 if (_ctrl_pressed) {
599 ToggleBit(this->cargo_filter, cs->Index());
600 this->ToggleWidgetLoweredState(widget);
601 } else {
602 for (uint i = 0; i < _sorted_standard_cargo_specs.size(); i++) {
603 this->RaiseWidget(WID_STL_CARGOSTART + i);
605 this->RaiseWidget(WID_STL_NOCARGOWAITING);
607 this->cargo_filter = 0;
608 this->include_empty = false;
610 SetBit(this->cargo_filter, cs->Index());
611 this->LowerWidget(widget);
613 this->stations.ForceRebuild();
614 this->SetDirty();
616 break;
620 void OnDropdownSelect(int widget, int index) override
622 if (this->stations.SortType() != index) {
623 this->stations.SetSortType(index);
625 /* Display the current sort variant */
626 this->GetWidget<NWidgetCore>(WID_STL_SORTDROPBTN)->widget_data = this->sorter_names[this->stations.SortType()];
628 this->SetDirty();
632 void OnGameTick() override
634 if (this->stations.NeedResort()) {
635 Debug(misc, 3, "Periodic rebuild station list company {}", this->window_number);
636 this->SetDirty();
640 void OnResize() override
642 this->vscroll->SetCapacityFromWidget(this, WID_STL_LIST, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
646 * Some data on this window has become invalid.
647 * @param data Information about the changed data.
648 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
650 void OnInvalidateData(int data = 0, bool gui_scope = true) override
652 if (data == 0) {
653 /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
654 this->stations.ForceRebuild();
655 } else {
656 this->stations.ForceResort();
661 Listing CompanyStationsWindow::last_sorting = {false, 0};
662 byte CompanyStationsWindow::facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK;
663 bool CompanyStationsWindow::include_empty = true;
664 const CargoTypes CompanyStationsWindow::cargo_filter_max = ALL_CARGOTYPES;
665 CargoTypes CompanyStationsWindow::cargo_filter = ALL_CARGOTYPES;
667 /* Available station sorting functions */
668 GUIStationList::SortFunction * const CompanyStationsWindow::sorter_funcs[] = {
669 &StationNameSorter,
670 &StationTypeSorter,
671 &StationWaitingTotalSorter,
672 &StationWaitingAvailableSorter,
673 &StationRatingMaxSorter,
674 &StationRatingMinSorter
677 /* Names of the sorting functions */
678 const StringID CompanyStationsWindow::sorter_names[] = {
679 STR_SORT_BY_NAME,
680 STR_SORT_BY_FACILITY,
681 STR_SORT_BY_WAITING_TOTAL,
682 STR_SORT_BY_WAITING_AVAILABLE,
683 STR_SORT_BY_RATING_MAX,
684 STR_SORT_BY_RATING_MIN,
685 INVALID_STRING_ID
689 * Make a horizontal row of cargo buttons, starting at widget #WID_STL_CARGOSTART.
690 * @param biggest_index Pointer to store biggest used widget number of the buttons.
691 * @return Horizontal row.
693 static NWidgetBase *CargoWidgets(int *biggest_index)
695 NWidgetHorizontal *container = new NWidgetHorizontal();
697 for (uint i = 0; i < _sorted_standard_cargo_specs.size(); i++) {
698 NWidgetBackground *panel = new NWidgetBackground(WWT_PANEL, COLOUR_GREY, WID_STL_CARGOSTART + i);
699 panel->SetMinimalSize(14, 0);
700 panel->SetMinimalTextLines(1, 0, FS_NORMAL);
701 panel->SetResize(0, 0);
702 panel->SetFill(0, 1);
703 panel->SetDataTip(0, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE);
704 container->Add(panel);
706 *biggest_index = WID_STL_CARGOSTART + static_cast<int>(_sorted_standard_cargo_specs.size());
707 return container;
710 static const NWidgetPart _nested_company_stations_widgets[] = {
711 NWidget(NWID_HORIZONTAL),
712 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
713 NWidget(WWT_CAPTION, COLOUR_GREY, WID_STL_CAPTION), SetDataTip(STR_STATION_LIST_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
714 NWidget(WWT_SHADEBOX, COLOUR_GREY),
715 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
716 NWidget(WWT_STICKYBOX, COLOUR_GREY),
717 EndContainer(),
718 NWidget(NWID_HORIZONTAL),
719 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_STL_TRAIN), SetMinimalSize(14, 0), SetMinimalTextLines(1, 0), SetDataTip(STR_TRAIN, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
720 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_STL_TRUCK), SetMinimalSize(14, 0), SetMinimalTextLines(1, 0), SetDataTip(STR_LORRY, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
721 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_STL_BUS), SetMinimalSize(14, 0), SetMinimalTextLines(1, 0), SetDataTip(STR_BUS, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
722 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_STL_SHIP), SetMinimalSize(14, 0), SetMinimalTextLines(1, 0), SetDataTip(STR_SHIP, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
723 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_STL_AIRPLANE), SetMinimalSize(14, 0), SetMinimalTextLines(1, 0), SetDataTip(STR_PLANE, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
724 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_STL_FACILALL), SetMinimalSize(14, 0), SetMinimalTextLines(1, 0), SetDataTip(STR_ABBREV_ALL, STR_STATION_LIST_SELECT_ALL_FACILITIES), SetFill(0, 1),
725 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(5, 0), SetFill(0, 1), EndContainer(),
726 NWidgetFunction(CargoWidgets),
727 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_STL_NOCARGOWAITING), SetMinimalSize(14, 0), SetMinimalTextLines(1, 0), SetDataTip(STR_ABBREV_NONE, STR_STATION_LIST_NO_WAITING_CARGO), SetFill(0, 1),
728 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_STL_CARGOALL), SetMinimalSize(14, 0), SetMinimalTextLines(1, 0), SetDataTip(STR_ABBREV_ALL, STR_STATION_LIST_SELECT_ALL_TYPES), SetFill(0, 1),
729 NWidget(WWT_PANEL, COLOUR_GREY), SetResize(1, 0), SetFill(1, 1), EndContainer(),
730 EndContainer(),
731 NWidget(NWID_HORIZONTAL),
732 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_STL_SORTBY), SetMinimalSize(81, 12), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
733 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_STL_SORTDROPBTN), SetMinimalSize(163, 12), SetDataTip(STR_SORT_BY_NAME, STR_TOOLTIP_SORT_CRITERIA), // widget_data gets overwritten.
734 NWidget(WWT_PANEL, COLOUR_GREY), SetResize(1, 0), SetFill(1, 1), EndContainer(),
735 EndContainer(),
736 NWidget(NWID_HORIZONTAL),
737 NWidget(WWT_PANEL, COLOUR_GREY, WID_STL_LIST), SetMinimalSize(346, 125), SetResize(1, 10), SetDataTip(0x0, STR_STATION_LIST_TOOLTIP), SetScrollbar(WID_STL_SCROLLBAR), EndContainer(),
738 NWidget(NWID_VERTICAL),
739 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_STL_SCROLLBAR),
740 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
741 EndContainer(),
742 EndContainer(),
745 static WindowDesc _company_stations_desc(
746 WDP_AUTO, "list_stations", 358, 162,
747 WC_STATION_LIST, WC_NONE,
749 _nested_company_stations_widgets, lengthof(_nested_company_stations_widgets)
753 * Opens window with list of company's stations
755 * @param company whose stations' list show
757 void ShowCompanyStations(CompanyID company)
759 if (!Company::IsValidID(company)) return;
761 AllocateWindowDescFront<CompanyStationsWindow>(&_company_stations_desc, company);
764 static const NWidgetPart _nested_station_view_widgets[] = {
765 NWidget(NWID_HORIZONTAL),
766 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
767 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_SV_RENAME), SetMinimalSize(12, 14), SetDataTip(SPR_RENAME, STR_STATION_VIEW_RENAME_TOOLTIP),
768 NWidget(WWT_CAPTION, COLOUR_GREY, WID_SV_CAPTION), SetDataTip(STR_STATION_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
769 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_SV_LOCATION), SetMinimalSize(12, 14), SetDataTip(SPR_GOTO_LOCATION, STR_STATION_VIEW_CENTER_TOOLTIP),
770 NWidget(WWT_SHADEBOX, COLOUR_GREY),
771 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
772 NWidget(WWT_STICKYBOX, COLOUR_GREY),
773 EndContainer(),
774 NWidget(NWID_HORIZONTAL),
775 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_SV_GROUP), SetMinimalSize(81, 12), SetFill(1, 1), SetDataTip(STR_STATION_VIEW_GROUP, 0x0),
776 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_SV_GROUP_BY), SetMinimalSize(168, 12), SetResize(1, 0), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_GROUP_ORDER),
777 EndContainer(),
778 NWidget(NWID_HORIZONTAL),
779 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_SORT_ORDER), SetMinimalSize(81, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
780 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_SV_SORT_BY), SetMinimalSize(168, 12), SetResize(1, 0), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
781 EndContainer(),
782 NWidget(NWID_HORIZONTAL),
783 NWidget(WWT_PANEL, COLOUR_GREY, WID_SV_WAITING), SetMinimalSize(237, 44), SetResize(1, 10), SetScrollbar(WID_SV_SCROLLBAR), EndContainer(),
784 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_SV_SCROLLBAR),
785 EndContainer(),
786 NWidget(WWT_PANEL, COLOUR_GREY, WID_SV_ACCEPT_RATING_LIST), SetMinimalSize(249, 23), SetResize(1, 0), EndContainer(),
787 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
788 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_ACCEPTS_RATINGS), SetMinimalSize(46, 12), SetResize(1, 0), SetFill(1, 1),
789 SetDataTip(STR_STATION_VIEW_RATINGS_BUTTON, STR_STATION_VIEW_RATINGS_TOOLTIP),
790 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_SV_CLOSE_AIRPORT), SetMinimalSize(45, 12), SetResize(1, 0), SetFill(1, 1),
791 SetDataTip(STR_STATION_VIEW_CLOSE_AIRPORT, STR_STATION_VIEW_CLOSE_AIRPORT_TOOLTIP),
792 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_SV_CATCHMENT), SetMinimalSize(45, 12), SetResize(1, 0), SetFill(1, 1), SetDataTip(STR_BUTTON_CATCHMENT, STR_TOOLTIP_CATCHMENT),
793 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_TRAINS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_TRAIN, STR_STATION_VIEW_SCHEDULED_TRAINS_TOOLTIP),
794 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_ROADVEHS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_LORRY, STR_STATION_VIEW_SCHEDULED_ROAD_VEHICLES_TOOLTIP),
795 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_SHIPS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_SHIP, STR_STATION_VIEW_SCHEDULED_SHIPS_TOOLTIP),
796 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_PLANES), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_PLANE, STR_STATION_VIEW_SCHEDULED_AIRCRAFT_TOOLTIP),
797 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
798 EndContainer(),
802 * Draws icons of waiting cargo in the StationView window
804 * @param i type of cargo
805 * @param waiting number of waiting units
806 * @param left left most coordinate to draw on
807 * @param right right most coordinate to draw on
808 * @param y y coordinate
810 static void DrawCargoIcons(CargoID i, uint waiting, int left, int right, int y)
812 int width = ScaleGUITrad(10);
813 uint num = std::min<uint>((waiting + (width / 2)) / width, (right - left) / width); // maximum is width / 10 icons so it won't overflow
814 if (num == 0) return;
816 SpriteID sprite = CargoSpec::Get(i)->GetCargoIcon();
818 int x = _current_text_dir == TD_RTL ? left : right - num * width;
819 do {
820 DrawSprite(sprite, PAL_NONE, x, y);
821 x += width;
822 } while (--num);
825 enum SortOrder {
826 SO_DESCENDING,
827 SO_ASCENDING
830 class CargoDataEntry;
832 enum CargoSortType {
833 ST_AS_GROUPING, ///< by the same principle the entries are being grouped
834 ST_COUNT, ///< by amount of cargo
835 ST_STATION_STRING, ///< by station name
836 ST_STATION_ID, ///< by station id
837 ST_CARGO_ID, ///< by cargo id
840 class CargoSorter {
841 public:
842 CargoSorter(CargoSortType t = ST_STATION_ID, SortOrder o = SO_ASCENDING) : type(t), order(o) {}
843 CargoSortType GetSortType() {return this->type;}
844 bool operator()(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const;
846 private:
847 CargoSortType type;
848 SortOrder order;
850 template<class Tid>
851 bool SortId(Tid st1, Tid st2) const;
852 bool SortCount(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const;
853 bool SortStation (StationID st1, StationID st2) const;
856 typedef std::set<CargoDataEntry *, CargoSorter> CargoDataSet;
859 * A cargo data entry representing one possible row in the station view window's
860 * top part. Cargo data entries form a tree where each entry can have several
861 * children. Parents keep track of the sums of their childrens' cargo counts.
863 class CargoDataEntry {
864 public:
865 CargoDataEntry();
866 ~CargoDataEntry();
869 * Insert a new child or retrieve an existing child using a station ID as ID.
870 * @param station ID of the station for which an entry shall be created or retrieved
871 * @return a child entry associated with the given station.
873 CargoDataEntry *InsertOrRetrieve(StationID station)
875 return this->InsertOrRetrieve<StationID>(station);
879 * Insert a new child or retrieve an existing child using a cargo ID as ID.
880 * @param cargo ID of the cargo for which an entry shall be created or retrieved
881 * @return a child entry associated with the given cargo.
883 CargoDataEntry *InsertOrRetrieve(CargoID cargo)
885 return this->InsertOrRetrieve<CargoID>(cargo);
888 void Update(uint count);
891 * Remove a child associated with the given station.
892 * @param station ID of the station for which the child should be removed.
894 void Remove(StationID station)
896 CargoDataEntry t(station);
897 this->Remove(&t);
901 * Remove a child associated with the given cargo.
902 * @param cargo ID of the cargo for which the child should be removed.
904 void Remove(CargoID cargo)
906 CargoDataEntry t(cargo);
907 this->Remove(&t);
911 * Retrieve a child for the given station. Return nullptr if it doesn't exist.
912 * @param station ID of the station the child we're looking for is associated with.
913 * @return a child entry for the given station or nullptr.
915 CargoDataEntry *Retrieve(StationID station) const
917 CargoDataEntry t(station);
918 return this->Retrieve(this->children->find(&t));
922 * Retrieve a child for the given cargo. Return nullptr if it doesn't exist.
923 * @param cargo ID of the cargo the child we're looking for is associated with.
924 * @return a child entry for the given cargo or nullptr.
926 CargoDataEntry *Retrieve(CargoID cargo) const
928 CargoDataEntry t(cargo);
929 return this->Retrieve(this->children->find(&t));
932 void Resort(CargoSortType type, SortOrder order);
935 * Get the station ID for this entry.
937 StationID GetStation() const { return this->station; }
940 * Get the cargo ID for this entry.
942 CargoID GetCargo() const { return this->cargo; }
945 * Get the cargo count for this entry.
947 uint GetCount() const { return this->count; }
950 * Get the parent entry for this entry.
952 CargoDataEntry *GetParent() const { return this->parent; }
955 * Get the number of children for this entry.
957 uint GetNumChildren() const { return this->num_children; }
960 * Get an iterator pointing to the begin of the set of children.
962 CargoDataSet::iterator Begin() const { return this->children->begin(); }
965 * Get an iterator pointing to the end of the set of children.
967 CargoDataSet::iterator End() const { return this->children->end(); }
970 * Has this entry transfers.
972 bool HasTransfers() const { return this->transfers; }
975 * Set the transfers state.
977 void SetTransfers(bool value) { this->transfers = value; }
979 void Clear();
980 private:
982 CargoDataEntry(StationID st, uint c, CargoDataEntry *p);
983 CargoDataEntry(CargoID car, uint c, CargoDataEntry *p);
984 CargoDataEntry(StationID st);
985 CargoDataEntry(CargoID car);
987 CargoDataEntry *Retrieve(CargoDataSet::iterator i) const;
989 template<class Tid>
990 CargoDataEntry *InsertOrRetrieve(Tid s);
992 void Remove(CargoDataEntry *comp);
993 void IncrementSize();
995 CargoDataEntry *parent; ///< the parent of this entry.
996 const union {
997 StationID station; ///< ID of the station this entry is associated with.
998 struct {
999 CargoID cargo; ///< ID of the cargo this entry is associated with.
1000 bool transfers; ///< If there are transfers for this cargo.
1003 uint num_children; ///< the number of subentries belonging to this entry.
1004 uint count; ///< sum of counts of all children or amount of cargo for this entry.
1005 CargoDataSet *children; ///< the children of this entry.
1008 CargoDataEntry::CargoDataEntry() :
1009 parent(nullptr),
1010 station(INVALID_STATION),
1011 num_children(0),
1012 count(0),
1013 children(new CargoDataSet(CargoSorter(ST_CARGO_ID)))
1016 CargoDataEntry::CargoDataEntry(CargoID cargo, uint count, CargoDataEntry *parent) :
1017 parent(parent),
1018 cargo(cargo),
1019 num_children(0),
1020 count(count),
1021 children(new CargoDataSet)
1024 CargoDataEntry::CargoDataEntry(StationID station, uint count, CargoDataEntry *parent) :
1025 parent(parent),
1026 station(station),
1027 num_children(0),
1028 count(count),
1029 children(new CargoDataSet)
1032 CargoDataEntry::CargoDataEntry(StationID station) :
1033 parent(nullptr),
1034 station(station),
1035 num_children(0),
1036 count(0),
1037 children(nullptr)
1040 CargoDataEntry::CargoDataEntry(CargoID cargo) :
1041 parent(nullptr),
1042 cargo(cargo),
1043 num_children(0),
1044 count(0),
1045 children(nullptr)
1048 CargoDataEntry::~CargoDataEntry()
1050 this->Clear();
1051 delete this->children;
1055 * Delete all subentries, reset count and num_children and adapt parent's count.
1057 void CargoDataEntry::Clear()
1059 if (this->children != nullptr) {
1060 for (CargoDataSet::iterator i = this->children->begin(); i != this->children->end(); ++i) {
1061 assert(*i != this);
1062 delete *i;
1064 this->children->clear();
1066 if (this->parent != nullptr) this->parent->count -= this->count;
1067 this->count = 0;
1068 this->num_children = 0;
1072 * Remove a subentry from this one and delete it.
1073 * @param child the entry to be removed. This may also be a synthetic entry
1074 * which only contains the ID of the entry to be removed. In this case child is
1075 * not deleted.
1077 void CargoDataEntry::Remove(CargoDataEntry *child)
1079 CargoDataSet::iterator i = this->children->find(child);
1080 if (i != this->children->end()) {
1081 delete *i;
1082 this->children->erase(i);
1087 * Retrieve a subentry or insert it if it doesn't exist, yet.
1088 * @tparam ID type of ID: either StationID or CargoID
1089 * @param child_id ID of the child to be inserted or retrieved.
1090 * @return the new or retrieved subentry
1092 template<class Tid>
1093 CargoDataEntry *CargoDataEntry::InsertOrRetrieve(Tid child_id)
1095 CargoDataEntry tmp(child_id);
1096 CargoDataSet::iterator i = this->children->find(&tmp);
1097 if (i == this->children->end()) {
1098 IncrementSize();
1099 return *(this->children->insert(new CargoDataEntry(child_id, 0, this)).first);
1100 } else {
1101 CargoDataEntry *ret = *i;
1102 assert(this->children->value_comp().GetSortType() != ST_COUNT);
1103 return ret;
1108 * Update the count for this entry and propagate the change to the parent entry
1109 * if there is one.
1110 * @param count the amount to be added to this entry
1112 void CargoDataEntry::Update(uint count)
1114 this->count += count;
1115 if (this->parent != nullptr) this->parent->Update(count);
1119 * Increment
1121 void CargoDataEntry::IncrementSize()
1123 ++this->num_children;
1124 if (this->parent != nullptr) this->parent->IncrementSize();
1127 void CargoDataEntry::Resort(CargoSortType type, SortOrder order)
1129 CargoDataSet *new_subs = new CargoDataSet(this->children->begin(), this->children->end(), CargoSorter(type, order));
1130 delete this->children;
1131 this->children = new_subs;
1134 CargoDataEntry *CargoDataEntry::Retrieve(CargoDataSet::iterator i) const
1136 if (i == this->children->end()) {
1137 return nullptr;
1138 } else {
1139 assert(this->children->value_comp().GetSortType() != ST_COUNT);
1140 return *i;
1144 bool CargoSorter::operator()(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const
1146 switch (this->type) {
1147 case ST_STATION_ID:
1148 return this->SortId<StationID>(cd1->GetStation(), cd2->GetStation());
1149 case ST_CARGO_ID:
1150 return this->SortId<CargoID>(cd1->GetCargo(), cd2->GetCargo());
1151 case ST_COUNT:
1152 return this->SortCount(cd1, cd2);
1153 case ST_STATION_STRING:
1154 return this->SortStation(cd1->GetStation(), cd2->GetStation());
1155 default:
1156 NOT_REACHED();
1160 template<class Tid>
1161 bool CargoSorter::SortId(Tid st1, Tid st2) const
1163 return (this->order == SO_ASCENDING) ? st1 < st2 : st2 < st1;
1166 bool CargoSorter::SortCount(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const
1168 uint c1 = cd1->GetCount();
1169 uint c2 = cd2->GetCount();
1170 if (c1 == c2) {
1171 return this->SortStation(cd1->GetStation(), cd2->GetStation());
1172 } else if (this->order == SO_ASCENDING) {
1173 return c1 < c2;
1174 } else {
1175 return c2 < c1;
1179 bool CargoSorter::SortStation(StationID st1, StationID st2) const
1181 if (!Station::IsValidID(st1)) {
1182 return Station::IsValidID(st2) ? this->order == SO_ASCENDING : this->SortId(st1, st2);
1183 } else if (!Station::IsValidID(st2)) {
1184 return order == SO_DESCENDING;
1187 int res = strnatcmp(Station::Get(st1)->GetCachedName(), Station::Get(st2)->GetCachedName()); // Sort by name (natural sorting).
1188 if (res == 0) {
1189 return this->SortId(st1, st2);
1190 } else {
1191 return (this->order == SO_ASCENDING) ? res < 0 : res > 0;
1196 * The StationView window
1198 struct StationViewWindow : public Window {
1200 * A row being displayed in the cargo view (as opposed to being "hidden" behind a plus sign).
1202 struct RowDisplay {
1203 RowDisplay(CargoDataEntry *f, StationID n) : filter(f), next_station(n) {}
1204 RowDisplay(CargoDataEntry *f, CargoID n) : filter(f), next_cargo(n) {}
1207 * Parent of the cargo entry belonging to the row.
1209 CargoDataEntry *filter;
1210 union {
1212 * ID of the station belonging to the entry actually displayed if it's to/from/via.
1214 StationID next_station;
1217 * ID of the cargo belonging to the entry actually displayed if it's cargo.
1219 CargoID next_cargo;
1223 typedef std::vector<RowDisplay> CargoDataVector;
1225 static const int NUM_COLUMNS = 4; ///< Number of "columns" in the cargo view: cargo, from, via, to
1228 * Type of data invalidation.
1230 enum Invalidation {
1231 INV_FLOWS = 0x100, ///< The planned flows have been recalculated and everything has to be updated.
1232 INV_CARGO = 0x200 ///< Some cargo has been added or removed.
1236 * Type of grouping used in each of the "columns".
1238 enum Grouping {
1239 GR_SOURCE, ///< Group by source of cargo ("from").
1240 GR_NEXT, ///< Group by next station ("via").
1241 GR_DESTINATION, ///< Group by estimated final destination ("to").
1242 GR_CARGO, ///< Group by cargo type.
1246 * Display mode of the cargo view.
1248 enum Mode {
1249 MODE_WAITING, ///< Show cargo waiting at the station.
1250 MODE_PLANNED ///< Show cargo planned to pass through the station.
1253 uint expand_shrink_width; ///< The width allocated to the expand/shrink 'button'
1254 int rating_lines; ///< Number of lines in the cargo ratings view.
1255 int accepts_lines; ///< Number of lines in the accepted cargo view.
1256 Scrollbar *vscroll;
1258 /** Height of the #WID_SV_ACCEPT_RATING_LIST widget for different views. */
1259 enum AcceptListHeight {
1260 ALH_RATING = 13, ///< Height of the cargo ratings view.
1261 ALH_ACCEPTS = 3, ///< Height of the accepted cargo view.
1264 static const StringID _sort_names[]; ///< Names of the sorting options in the dropdown.
1265 static const StringID _group_names[]; ///< Names of the grouping options in the dropdown.
1268 * Sort types of the different 'columns'.
1269 * In fact only ST_COUNT and ST_AS_GROUPING are active and you can only
1270 * sort all the columns in the same way. The other options haven't been
1271 * included in the GUI due to lack of space.
1273 CargoSortType sortings[NUM_COLUMNS];
1275 /** Sort order (ascending/descending) for the 'columns'. */
1276 SortOrder sort_orders[NUM_COLUMNS];
1278 int scroll_to_row; ///< If set, scroll the main viewport to the station pointed to by this row.
1279 int grouping_index; ///< Currently selected entry in the grouping drop down.
1280 Mode current_mode; ///< Currently selected display mode of cargo view.
1281 Grouping groupings[NUM_COLUMNS]; ///< Grouping modes for the different columns.
1283 CargoDataEntry expanded_rows; ///< Parent entry of currently expanded rows.
1284 CargoDataEntry cached_destinations; ///< Cache for the flows passing through this station.
1285 CargoDataVector displayed_rows; ///< Parent entry of currently displayed rows (including collapsed ones).
1287 StationViewWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc),
1288 scroll_to_row(INT_MAX), grouping_index(0)
1290 this->rating_lines = ALH_RATING;
1291 this->accepts_lines = ALH_ACCEPTS;
1293 this->CreateNestedTree();
1294 this->vscroll = this->GetScrollbar(WID_SV_SCROLLBAR);
1295 /* Nested widget tree creation is done in two steps to ensure that this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS) exists in UpdateWidgetSize(). */
1296 this->FinishInitNested(window_number);
1298 this->groupings[0] = GR_CARGO;
1299 this->sortings[0] = ST_AS_GROUPING;
1300 this->SelectGroupBy(_settings_client.gui.station_gui_group_order);
1301 this->SelectSortBy(_settings_client.gui.station_gui_sort_by);
1302 this->sort_orders[0] = SO_ASCENDING;
1303 this->SelectSortOrder((SortOrder)_settings_client.gui.station_gui_sort_order);
1304 this->owner = Station::Get(window_number)->owner;
1307 void Close() override
1309 CloseWindowById(WC_TRAINS_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_TRAIN, this->owner, this->window_number).Pack(), false);
1310 CloseWindowById(WC_ROADVEH_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_ROAD, this->owner, this->window_number).Pack(), false);
1311 CloseWindowById(WC_SHIPS_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_SHIP, this->owner, this->window_number).Pack(), false);
1312 CloseWindowById(WC_AIRCRAFT_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_AIRCRAFT, this->owner, this->window_number).Pack(), false);
1314 SetViewportCatchmentStation(Station::Get(this->window_number), false);
1315 this->Window::Close();
1319 * Show a certain cargo entry characterized by source/next/dest station, cargo ID and amount of cargo at the
1320 * right place in the cargo view. I.e. update as many rows as are expanded following that characterization.
1321 * @param data Root entry of the tree.
1322 * @param cargo Cargo ID of the entry to be shown.
1323 * @param source Source station of the entry to be shown.
1324 * @param next Next station the cargo to be shown will visit.
1325 * @param dest Final destination of the cargo to be shown.
1326 * @param count Amount of cargo to be shown.
1328 void ShowCargo(CargoDataEntry *data, CargoID cargo, StationID source, StationID next, StationID dest, uint count)
1330 if (count == 0) return;
1331 bool auto_distributed = _settings_game.linkgraph.GetDistributionType(cargo) != DT_MANUAL;
1332 const CargoDataEntry *expand = &this->expanded_rows;
1333 for (int i = 0; i < NUM_COLUMNS && expand != nullptr; ++i) {
1334 switch (groupings[i]) {
1335 case GR_CARGO:
1336 assert(i == 0);
1337 data = data->InsertOrRetrieve(cargo);
1338 data->SetTransfers(source != this->window_number);
1339 expand = expand->Retrieve(cargo);
1340 break;
1341 case GR_SOURCE:
1342 if (auto_distributed || source != this->window_number) {
1343 data = data->InsertOrRetrieve(source);
1344 expand = expand->Retrieve(source);
1346 break;
1347 case GR_NEXT:
1348 if (auto_distributed) {
1349 data = data->InsertOrRetrieve(next);
1350 expand = expand->Retrieve(next);
1352 break;
1353 case GR_DESTINATION:
1354 if (auto_distributed) {
1355 data = data->InsertOrRetrieve(dest);
1356 expand = expand->Retrieve(dest);
1358 break;
1361 data->Update(count);
1364 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
1366 switch (widget) {
1367 case WID_SV_WAITING:
1368 resize->height = FONT_HEIGHT_NORMAL;
1369 size->height = WD_FRAMERECT_TOP + 4 * resize->height + WD_FRAMERECT_BOTTOM;
1370 this->expand_shrink_width = std::max(GetStringBoundingBox("-").width, GetStringBoundingBox("+").width) + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
1371 break;
1373 case WID_SV_ACCEPT_RATING_LIST:
1374 size->height = WD_FRAMERECT_TOP + ((this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) ? this->accepts_lines : this->rating_lines) * FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM;
1375 break;
1377 case WID_SV_CLOSE_AIRPORT:
1378 if (!(Station::Get(this->window_number)->facilities & FACIL_AIRPORT)) {
1379 /* Hide 'Close Airport' button if no airport present. */
1380 size->width = 0;
1381 resize->width = 0;
1382 fill->width = 0;
1384 break;
1388 void OnPaint() override
1390 const Station *st = Station::Get(this->window_number);
1391 CargoDataEntry cargo;
1392 BuildCargoList(&cargo, st);
1394 this->vscroll->SetCount(cargo.GetNumChildren()); // update scrollbar
1396 /* disable some buttons */
1397 this->SetWidgetDisabledState(WID_SV_RENAME, st->owner != _local_company);
1398 this->SetWidgetDisabledState(WID_SV_TRAINS, !(st->facilities & FACIL_TRAIN));
1399 this->SetWidgetDisabledState(WID_SV_ROADVEHS, !(st->facilities & FACIL_TRUCK_STOP) && !(st->facilities & FACIL_BUS_STOP));
1400 this->SetWidgetDisabledState(WID_SV_SHIPS, !(st->facilities & FACIL_DOCK));
1401 this->SetWidgetDisabledState(WID_SV_PLANES, !(st->facilities & FACIL_AIRPORT));
1402 this->SetWidgetDisabledState(WID_SV_CLOSE_AIRPORT, !(st->facilities & FACIL_AIRPORT) || st->owner != _local_company || st->owner == OWNER_NONE); // Also consider SE, where _local_company == OWNER_NONE
1403 this->SetWidgetLoweredState(WID_SV_CLOSE_AIRPORT, (st->facilities & FACIL_AIRPORT) && (st->airport.flags & AIRPORT_CLOSED_block) != 0);
1405 extern const Station *_viewport_highlight_station;
1406 this->SetWidgetDisabledState(WID_SV_CATCHMENT, st->facilities == FACIL_NONE);
1407 this->SetWidgetLoweredState(WID_SV_CATCHMENT, _viewport_highlight_station == st);
1409 this->DrawWidgets();
1411 if (!this->IsShaded()) {
1412 /* Draw 'accepted cargo' or 'cargo ratings'. */
1413 const NWidgetBase *wid = this->GetWidget<NWidgetBase>(WID_SV_ACCEPT_RATING_LIST);
1414 const Rect r = wid->GetCurrentRect();
1415 if (this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) {
1416 int lines = this->DrawAcceptedCargo(r);
1417 if (lines > this->accepts_lines) { // Resize the widget, and perform re-initialization of the window.
1418 this->accepts_lines = lines;
1419 this->ReInit();
1420 return;
1422 } else {
1423 int lines = this->DrawCargoRatings(r);
1424 if (lines > this->rating_lines) { // Resize the widget, and perform re-initialization of the window.
1425 this->rating_lines = lines;
1426 this->ReInit();
1427 return;
1431 /* Draw arrow pointing up/down for ascending/descending sorting */
1432 this->DrawSortButtonState(WID_SV_SORT_ORDER, sort_orders[1] == SO_ASCENDING ? SBS_UP : SBS_DOWN);
1434 int pos = this->vscroll->GetPosition();
1436 int maxrows = this->vscroll->GetCapacity();
1438 displayed_rows.clear();
1440 /* Draw waiting cargo. */
1441 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_SV_WAITING);
1442 Rect waiting_rect = nwi->GetCurrentRect();
1443 this->DrawEntries(&cargo, waiting_rect, pos, maxrows, 0);
1444 scroll_to_row = INT_MAX;
1448 void SetStringParameters(int widget) const override
1450 const Station *st = Station::Get(this->window_number);
1451 SetDParam(0, st->index);
1452 SetDParam(1, st->facilities);
1456 * Rebuild the cache for estimated destinations which is used to quickly show the "destination" entries
1457 * even if we actually don't know the destination of a certain packet from just looking at it.
1458 * @param i Cargo to recalculate the cache for.
1460 void RecalcDestinations(CargoID i)
1462 const Station *st = Station::Get(this->window_number);
1463 CargoDataEntry *cargo_entry = cached_destinations.InsertOrRetrieve(i);
1464 cargo_entry->Clear();
1466 const FlowStatMap &flows = st->goods[i].flows;
1467 for (FlowStatMap::const_iterator it = flows.begin(); it != flows.end(); ++it) {
1468 StationID from = it->first;
1469 CargoDataEntry *source_entry = cargo_entry->InsertOrRetrieve(from);
1470 const FlowStat::SharesMap *shares = it->second.GetShares();
1471 uint32 prev_count = 0;
1472 for (FlowStat::SharesMap::const_iterator flow_it = shares->begin(); flow_it != shares->end(); ++flow_it) {
1473 StationID via = flow_it->second;
1474 CargoDataEntry *via_entry = source_entry->InsertOrRetrieve(via);
1475 if (via == this->window_number) {
1476 via_entry->InsertOrRetrieve(via)->Update(flow_it->first - prev_count);
1477 } else {
1478 EstimateDestinations(i, from, via, flow_it->first - prev_count, via_entry);
1480 prev_count = flow_it->first;
1486 * Estimate the amounts of cargo per final destination for a given cargo, source station and next hop and
1487 * save the result as children of the given CargoDataEntry.
1488 * @param cargo ID of the cargo to estimate destinations for.
1489 * @param source Source station of the given batch of cargo.
1490 * @param next Intermediate hop to start the calculation at ("next hop").
1491 * @param count Size of the batch of cargo.
1492 * @param dest CargoDataEntry to save the results in.
1494 void EstimateDestinations(CargoID cargo, StationID source, StationID next, uint count, CargoDataEntry *dest)
1496 if (Station::IsValidID(next) && Station::IsValidID(source)) {
1497 CargoDataEntry tmp;
1498 const FlowStatMap &flowmap = Station::Get(next)->goods[cargo].flows;
1499 FlowStatMap::const_iterator map_it = flowmap.find(source);
1500 if (map_it != flowmap.end()) {
1501 const FlowStat::SharesMap *shares = map_it->second.GetShares();
1502 uint32 prev_count = 0;
1503 for (FlowStat::SharesMap::const_iterator i = shares->begin(); i != shares->end(); ++i) {
1504 tmp.InsertOrRetrieve(i->second)->Update(i->first - prev_count);
1505 prev_count = i->first;
1509 if (tmp.GetCount() == 0) {
1510 dest->InsertOrRetrieve(INVALID_STATION)->Update(count);
1511 } else {
1512 uint sum_estimated = 0;
1513 while (sum_estimated < count) {
1514 for (CargoDataSet::iterator i = tmp.Begin(); i != tmp.End() && sum_estimated < count; ++i) {
1515 CargoDataEntry *child = *i;
1516 uint estimate = DivideApprox(child->GetCount() * count, tmp.GetCount());
1517 if (estimate == 0) estimate = 1;
1519 sum_estimated += estimate;
1520 if (sum_estimated > count) {
1521 estimate -= sum_estimated - count;
1522 sum_estimated = count;
1525 if (estimate > 0) {
1526 if (child->GetStation() == next) {
1527 dest->InsertOrRetrieve(next)->Update(estimate);
1528 } else {
1529 EstimateDestinations(cargo, source, child->GetStation(), estimate, dest);
1536 } else {
1537 dest->InsertOrRetrieve(INVALID_STATION)->Update(count);
1542 * Build up the cargo view for PLANNED mode and a specific cargo.
1543 * @param i Cargo to show.
1544 * @param flows The current station's flows for that cargo.
1545 * @param cargo The CargoDataEntry to save the results in.
1547 void BuildFlowList(CargoID i, const FlowStatMap &flows, CargoDataEntry *cargo)
1549 const CargoDataEntry *source_dest = this->cached_destinations.Retrieve(i);
1550 for (FlowStatMap::const_iterator it = flows.begin(); it != flows.end(); ++it) {
1551 StationID from = it->first;
1552 const CargoDataEntry *source_entry = source_dest->Retrieve(from);
1553 const FlowStat::SharesMap *shares = it->second.GetShares();
1554 for (FlowStat::SharesMap::const_iterator flow_it = shares->begin(); flow_it != shares->end(); ++flow_it) {
1555 const CargoDataEntry *via_entry = source_entry->Retrieve(flow_it->second);
1556 for (CargoDataSet::iterator dest_it = via_entry->Begin(); dest_it != via_entry->End(); ++dest_it) {
1557 CargoDataEntry *dest_entry = *dest_it;
1558 ShowCargo(cargo, i, from, flow_it->second, dest_entry->GetStation(), dest_entry->GetCount());
1565 * Build up the cargo view for WAITING mode and a specific cargo.
1566 * @param i Cargo to show.
1567 * @param packets The current station's cargo list for that cargo.
1568 * @param cargo The CargoDataEntry to save the result in.
1570 void BuildCargoList(CargoID i, const StationCargoList &packets, CargoDataEntry *cargo)
1572 const CargoDataEntry *source_dest = this->cached_destinations.Retrieve(i);
1573 for (StationCargoList::ConstIterator it = packets.Packets()->begin(); it != packets.Packets()->end(); it++) {
1574 const CargoPacket *cp = *it;
1575 StationID next = it.GetKey();
1577 const CargoDataEntry *source_entry = source_dest->Retrieve(cp->SourceStation());
1578 if (source_entry == nullptr) {
1579 this->ShowCargo(cargo, i, cp->SourceStation(), next, INVALID_STATION, cp->Count());
1580 continue;
1583 const CargoDataEntry *via_entry = source_entry->Retrieve(next);
1584 if (via_entry == nullptr) {
1585 this->ShowCargo(cargo, i, cp->SourceStation(), next, INVALID_STATION, cp->Count());
1586 continue;
1589 for (CargoDataSet::iterator dest_it = via_entry->Begin(); dest_it != via_entry->End(); ++dest_it) {
1590 CargoDataEntry *dest_entry = *dest_it;
1591 uint val = DivideApprox(cp->Count() * dest_entry->GetCount(), via_entry->GetCount());
1592 this->ShowCargo(cargo, i, cp->SourceStation(), next, dest_entry->GetStation(), val);
1595 this->ShowCargo(cargo, i, NEW_STATION, NEW_STATION, NEW_STATION, packets.ReservedCount());
1599 * Build up the cargo view for all cargoes.
1600 * @param cargo The root cargo entry to save all results in.
1601 * @param st The station to calculate the cargo view from.
1603 void BuildCargoList(CargoDataEntry *cargo, const Station *st)
1605 for (CargoID i = 0; i < NUM_CARGO; i++) {
1607 if (this->cached_destinations.Retrieve(i) == nullptr) {
1608 this->RecalcDestinations(i);
1611 if (this->current_mode == MODE_WAITING) {
1612 this->BuildCargoList(i, st->goods[i].cargo, cargo);
1613 } else {
1614 this->BuildFlowList(i, st->goods[i].flows, cargo);
1620 * Mark a specific row, characterized by its CargoDataEntry, as expanded.
1621 * @param data The row to be marked as expanded.
1623 void SetDisplayedRow(const CargoDataEntry *data)
1625 std::list<StationID> stations;
1626 const CargoDataEntry *parent = data->GetParent();
1627 if (parent->GetParent() == nullptr) {
1628 this->displayed_rows.push_back(RowDisplay(&this->expanded_rows, data->GetCargo()));
1629 return;
1632 StationID next = data->GetStation();
1633 while (parent->GetParent()->GetParent() != nullptr) {
1634 stations.push_back(parent->GetStation());
1635 parent = parent->GetParent();
1638 CargoID cargo = parent->GetCargo();
1639 CargoDataEntry *filter = this->expanded_rows.Retrieve(cargo);
1640 while (!stations.empty()) {
1641 filter = filter->Retrieve(stations.back());
1642 stations.pop_back();
1645 this->displayed_rows.push_back(RowDisplay(filter, next));
1649 * Select the correct string for an entry referring to the specified station.
1650 * @param station Station the entry is showing cargo for.
1651 * @param here String to be shown if the entry refers to the same station as this station GUI belongs to.
1652 * @param other_station String to be shown if the entry refers to a specific other station.
1653 * @param any String to be shown if the entry refers to "any station".
1654 * @return One of the three given strings or STR_STATION_VIEW_RESERVED, depending on what station the entry refers to.
1656 StringID GetEntryString(StationID station, StringID here, StringID other_station, StringID any)
1658 if (station == this->window_number) {
1659 return here;
1660 } else if (station == INVALID_STATION) {
1661 return any;
1662 } else if (station == NEW_STATION) {
1663 return STR_STATION_VIEW_RESERVED;
1664 } else {
1665 SetDParam(2, station);
1666 return other_station;
1671 * Determine if we need to show the special "non-stop" string.
1672 * @param cd Entry we are going to show.
1673 * @param station Station the entry refers to.
1674 * @param column The "column" the entry will be shown in.
1675 * @return either STR_STATION_VIEW_VIA or STR_STATION_VIEW_NONSTOP.
1677 StringID SearchNonStop(CargoDataEntry *cd, StationID station, int column)
1679 CargoDataEntry *parent = cd->GetParent();
1680 for (int i = column - 1; i > 0; --i) {
1681 if (this->groupings[i] == GR_DESTINATION) {
1682 if (parent->GetStation() == station) {
1683 return STR_STATION_VIEW_NONSTOP;
1684 } else {
1685 return STR_STATION_VIEW_VIA;
1688 parent = parent->GetParent();
1691 if (this->groupings[column + 1] == GR_DESTINATION) {
1692 CargoDataSet::iterator begin = cd->Begin();
1693 CargoDataSet::iterator end = cd->End();
1694 if (begin != end && ++(cd->Begin()) == end && (*(begin))->GetStation() == station) {
1695 return STR_STATION_VIEW_NONSTOP;
1696 } else {
1697 return STR_STATION_VIEW_VIA;
1701 return STR_STATION_VIEW_VIA;
1705 * Draw the given cargo entries in the station GUI.
1706 * @param entry Root entry for all cargo to be drawn.
1707 * @param r Screen rectangle to draw into.
1708 * @param pos Current row to be drawn to (counted down from 0 to -maxrows, same as vscroll->GetPosition()).
1709 * @param maxrows Maximum row to be drawn.
1710 * @param column Current "column" being drawn.
1711 * @param cargo Current cargo being drawn (if cargo column has been passed).
1712 * @return row (in "pos" counting) after the one we have last drawn to.
1714 int DrawEntries(CargoDataEntry *entry, Rect &r, int pos, int maxrows, int column, CargoID cargo = CT_INVALID)
1716 if (this->sortings[column] == ST_AS_GROUPING) {
1717 if (this->groupings[column] != GR_CARGO) {
1718 entry->Resort(ST_STATION_STRING, this->sort_orders[column]);
1720 } else {
1721 entry->Resort(ST_COUNT, this->sort_orders[column]);
1723 for (CargoDataSet::iterator i = entry->Begin(); i != entry->End(); ++i) {
1724 CargoDataEntry *cd = *i;
1726 Grouping grouping = this->groupings[column];
1727 if (grouping == GR_CARGO) cargo = cd->GetCargo();
1728 bool auto_distributed = _settings_game.linkgraph.GetDistributionType(cargo) != DT_MANUAL;
1730 if (pos > -maxrows && pos <= 0) {
1731 StringID str = STR_EMPTY;
1732 int y = r.top + WD_FRAMERECT_TOP - pos * FONT_HEIGHT_NORMAL;
1733 SetDParam(0, cargo);
1734 SetDParam(1, cd->GetCount());
1736 if (this->groupings[column] == GR_CARGO) {
1737 str = STR_STATION_VIEW_WAITING_CARGO;
1738 DrawCargoIcons(cd->GetCargo(), cd->GetCount(), r.left + WD_FRAMERECT_LEFT + this->expand_shrink_width, r.right - WD_FRAMERECT_RIGHT - this->expand_shrink_width, y);
1739 } else {
1740 if (!auto_distributed) grouping = GR_SOURCE;
1741 StationID station = cd->GetStation();
1743 switch (grouping) {
1744 case GR_SOURCE:
1745 str = this->GetEntryString(station, STR_STATION_VIEW_FROM_HERE, STR_STATION_VIEW_FROM, STR_STATION_VIEW_FROM_ANY);
1746 break;
1747 case GR_NEXT:
1748 str = this->GetEntryString(station, STR_STATION_VIEW_VIA_HERE, STR_STATION_VIEW_VIA, STR_STATION_VIEW_VIA_ANY);
1749 if (str == STR_STATION_VIEW_VIA) str = this->SearchNonStop(cd, station, column);
1750 break;
1751 case GR_DESTINATION:
1752 str = this->GetEntryString(station, STR_STATION_VIEW_TO_HERE, STR_STATION_VIEW_TO, STR_STATION_VIEW_TO_ANY);
1753 break;
1754 default:
1755 NOT_REACHED();
1757 if (pos == -this->scroll_to_row && Station::IsValidID(station)) {
1758 ScrollMainWindowToTile(Station::Get(station)->xy);
1762 bool rtl = _current_text_dir == TD_RTL;
1763 int text_left = rtl ? r.left + this->expand_shrink_width : r.left + WD_FRAMERECT_LEFT + column * this->expand_shrink_width;
1764 int text_right = rtl ? r.right - WD_FRAMERECT_LEFT - column * this->expand_shrink_width : r.right - this->expand_shrink_width;
1765 int shrink_left = rtl ? r.left + WD_FRAMERECT_LEFT : r.right - this->expand_shrink_width + WD_FRAMERECT_LEFT;
1766 int shrink_right = rtl ? r.left + this->expand_shrink_width - WD_FRAMERECT_RIGHT : r.right - WD_FRAMERECT_RIGHT;
1768 DrawString(text_left, text_right, y, str);
1770 if (column < NUM_COLUMNS - 1) {
1771 const char *sym = nullptr;
1772 if (cd->GetNumChildren() > 0) {
1773 sym = "-";
1774 } else if (auto_distributed && str != STR_STATION_VIEW_RESERVED) {
1775 sym = "+";
1776 } else {
1777 /* Only draw '+' if there is something to be shown. */
1778 const StationCargoList &list = Station::Get(this->window_number)->goods[cargo].cargo;
1779 if (grouping == GR_CARGO && (list.ReservedCount() > 0 || cd->HasTransfers())) {
1780 sym = "+";
1783 if (sym) DrawString(shrink_left, shrink_right, y, sym, TC_YELLOW);
1785 this->SetDisplayedRow(cd);
1787 --pos;
1788 if (auto_distributed || column == 0) {
1789 pos = this->DrawEntries(cd, r, pos, maxrows, column + 1, cargo);
1792 return pos;
1796 * Draw accepted cargo in the #WID_SV_ACCEPT_RATING_LIST widget.
1797 * @param r Rectangle of the widget.
1798 * @return Number of lines needed for drawing the accepted cargo.
1800 int DrawAcceptedCargo(const Rect &r) const
1802 const Station *st = Station::Get(this->window_number);
1804 CargoTypes cargo_mask = 0;
1805 for (CargoID i = 0; i < NUM_CARGO; i++) {
1806 if (HasBit(st->goods[i].status, GoodsEntry::GES_ACCEPTANCE)) SetBit(cargo_mask, i);
1808 SetDParam(0, cargo_mask);
1809 int bottom = DrawStringMultiLine(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, INT32_MAX, STR_STATION_VIEW_ACCEPTS_CARGO);
1810 return CeilDiv(bottom - r.top - WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL);
1814 * Draw cargo ratings in the #WID_SV_ACCEPT_RATING_LIST widget.
1815 * @param r Rectangle of the widget.
1816 * @return Number of lines needed for drawing the cargo ratings.
1818 int DrawCargoRatings(const Rect &r) const
1820 const Station *st = Station::Get(this->window_number);
1821 int y = r.top + WD_FRAMERECT_TOP;
1823 if (st->town->exclusive_counter > 0) {
1824 SetDParam(0, st->town->exclusivity);
1825 y = DrawStringMultiLine(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, r.bottom, st->town->exclusivity == st->owner ? STR_STATION_VIEW_EXCLUSIVE_RIGHTS_SELF : STR_STATION_VIEW_EXCLUSIVE_RIGHTS_COMPANY);
1826 y += WD_PAR_VSEP_WIDE;
1829 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_VIEW_SUPPLY_RATINGS_TITLE);
1830 y += FONT_HEIGHT_NORMAL;
1832 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
1833 const GoodsEntry *ge = &st->goods[cs->Index()];
1834 if (!ge->HasRating()) continue;
1836 const LinkGraph *lg = LinkGraph::GetIfValid(ge->link_graph);
1837 SetDParam(0, cs->name);
1838 SetDParam(1, lg != nullptr ? lg->Monthly((*lg)[ge->node].Supply()) : 0);
1839 SetDParam(2, STR_CARGO_RATING_APPALLING + (ge->rating >> 5));
1840 SetDParam(3, ToPercent8(ge->rating));
1841 DrawString(r.left + WD_FRAMERECT_LEFT + 6, r.right - WD_FRAMERECT_RIGHT - 6, y, STR_STATION_VIEW_CARGO_SUPPLY_RATING);
1842 y += FONT_HEIGHT_NORMAL;
1844 return CeilDiv(y - r.top - WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL);
1848 * Expand or collapse a specific row.
1849 * @param filter Parent of the row.
1850 * @param next ID pointing to the row.
1852 template<class Tid>
1853 void HandleCargoWaitingClick(CargoDataEntry *filter, Tid next)
1855 if (filter->Retrieve(next) != nullptr) {
1856 filter->Remove(next);
1857 } else {
1858 filter->InsertOrRetrieve(next);
1863 * Handle a click on a specific row in the cargo view.
1864 * @param row Row being clicked.
1866 void HandleCargoWaitingClick(int row)
1868 if (row < 0 || (uint)row >= this->displayed_rows.size()) return;
1869 if (_ctrl_pressed) {
1870 this->scroll_to_row = row;
1871 } else {
1872 RowDisplay &display = this->displayed_rows[row];
1873 if (display.filter == &this->expanded_rows) {
1874 this->HandleCargoWaitingClick<CargoID>(display.filter, display.next_cargo);
1875 } else {
1876 this->HandleCargoWaitingClick<StationID>(display.filter, display.next_station);
1879 this->SetWidgetDirty(WID_SV_WAITING);
1882 void OnClick(Point pt, int widget, int click_count) override
1884 switch (widget) {
1885 case WID_SV_WAITING:
1886 this->HandleCargoWaitingClick(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_SV_WAITING, WD_FRAMERECT_TOP) - this->vscroll->GetPosition());
1887 break;
1889 case WID_SV_CATCHMENT:
1890 SetViewportCatchmentStation(Station::Get(this->window_number), !this->IsWidgetLowered(WID_SV_CATCHMENT));
1891 break;
1893 case WID_SV_LOCATION:
1894 if (_ctrl_pressed) {
1895 ShowExtraViewportWindow(Station::Get(this->window_number)->xy);
1896 } else {
1897 ScrollMainWindowToTile(Station::Get(this->window_number)->xy);
1899 break;
1901 case WID_SV_ACCEPTS_RATINGS: {
1902 /* Swap between 'accepts' and 'ratings' view. */
1903 int height_change;
1904 NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS);
1905 if (this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) {
1906 nwi->SetDataTip(STR_STATION_VIEW_ACCEPTS_BUTTON, STR_STATION_VIEW_ACCEPTS_TOOLTIP); // Switch to accepts view.
1907 height_change = this->rating_lines - this->accepts_lines;
1908 } else {
1909 nwi->SetDataTip(STR_STATION_VIEW_RATINGS_BUTTON, STR_STATION_VIEW_RATINGS_TOOLTIP); // Switch to ratings view.
1910 height_change = this->accepts_lines - this->rating_lines;
1912 this->ReInit(0, height_change * FONT_HEIGHT_NORMAL);
1913 break;
1916 case WID_SV_RENAME:
1917 SetDParam(0, this->window_number);
1918 ShowQueryString(STR_STATION_NAME, STR_STATION_VIEW_RENAME_STATION_CAPTION, MAX_LENGTH_STATION_NAME_CHARS,
1919 this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
1920 break;
1922 case WID_SV_CLOSE_AIRPORT:
1923 Command<CMD_OPEN_CLOSE_AIRPORT>::Post(this->window_number);
1924 break;
1926 case WID_SV_TRAINS: // Show list of scheduled trains to this station
1927 case WID_SV_ROADVEHS: // Show list of scheduled road-vehicles to this station
1928 case WID_SV_SHIPS: // Show list of scheduled ships to this station
1929 case WID_SV_PLANES: { // Show list of scheduled aircraft to this station
1930 Owner owner = Station::Get(this->window_number)->owner;
1931 ShowVehicleListWindow(owner, (VehicleType)(widget - WID_SV_TRAINS), (StationID)this->window_number);
1932 break;
1935 case WID_SV_SORT_BY: {
1936 /* The initial selection is composed of current mode and
1937 * sorting criteria for columns 1, 2, and 3. Column 0 is always
1938 * sorted by cargo ID. The others can theoretically be sorted
1939 * by different things but there is no UI for that. */
1940 ShowDropDownMenu(this, _sort_names,
1941 this->current_mode * 2 + (this->sortings[1] == ST_COUNT ? 1 : 0),
1942 WID_SV_SORT_BY, 0, 0);
1943 break;
1946 case WID_SV_GROUP_BY: {
1947 ShowDropDownMenu(this, _group_names, this->grouping_index, WID_SV_GROUP_BY, 0, 0);
1948 break;
1951 case WID_SV_SORT_ORDER: { // flip sorting method asc/desc
1952 this->SelectSortOrder(this->sort_orders[1] == SO_ASCENDING ? SO_DESCENDING : SO_ASCENDING);
1953 this->SetTimeout();
1954 this->LowerWidget(WID_SV_SORT_ORDER);
1955 break;
1961 * Select a new sort order for the cargo view.
1962 * @param order New sort order.
1964 void SelectSortOrder(SortOrder order)
1966 this->sort_orders[1] = this->sort_orders[2] = this->sort_orders[3] = order;
1967 _settings_client.gui.station_gui_sort_order = this->sort_orders[1];
1968 this->SetDirty();
1972 * Select a new sort criterium for the cargo view.
1973 * @param index Row being selected in the sort criteria drop down.
1975 void SelectSortBy(int index)
1977 _settings_client.gui.station_gui_sort_by = index;
1978 switch (_sort_names[index]) {
1979 case STR_STATION_VIEW_WAITING_STATION:
1980 this->current_mode = MODE_WAITING;
1981 this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_AS_GROUPING;
1982 break;
1983 case STR_STATION_VIEW_WAITING_AMOUNT:
1984 this->current_mode = MODE_WAITING;
1985 this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_COUNT;
1986 break;
1987 case STR_STATION_VIEW_PLANNED_STATION:
1988 this->current_mode = MODE_PLANNED;
1989 this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_AS_GROUPING;
1990 break;
1991 case STR_STATION_VIEW_PLANNED_AMOUNT:
1992 this->current_mode = MODE_PLANNED;
1993 this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_COUNT;
1994 break;
1995 default:
1996 NOT_REACHED();
1998 /* Display the current sort variant */
1999 this->GetWidget<NWidgetCore>(WID_SV_SORT_BY)->widget_data = _sort_names[index];
2000 this->SetDirty();
2004 * Select a new grouping mode for the cargo view.
2005 * @param index Row being selected in the grouping drop down.
2007 void SelectGroupBy(int index)
2009 this->grouping_index = index;
2010 _settings_client.gui.station_gui_group_order = index;
2011 this->GetWidget<NWidgetCore>(WID_SV_GROUP_BY)->widget_data = _group_names[index];
2012 switch (_group_names[index]) {
2013 case STR_STATION_VIEW_GROUP_S_V_D:
2014 this->groupings[1] = GR_SOURCE;
2015 this->groupings[2] = GR_NEXT;
2016 this->groupings[3] = GR_DESTINATION;
2017 break;
2018 case STR_STATION_VIEW_GROUP_S_D_V:
2019 this->groupings[1] = GR_SOURCE;
2020 this->groupings[2] = GR_DESTINATION;
2021 this->groupings[3] = GR_NEXT;
2022 break;
2023 case STR_STATION_VIEW_GROUP_V_S_D:
2024 this->groupings[1] = GR_NEXT;
2025 this->groupings[2] = GR_SOURCE;
2026 this->groupings[3] = GR_DESTINATION;
2027 break;
2028 case STR_STATION_VIEW_GROUP_V_D_S:
2029 this->groupings[1] = GR_NEXT;
2030 this->groupings[2] = GR_DESTINATION;
2031 this->groupings[3] = GR_SOURCE;
2032 break;
2033 case STR_STATION_VIEW_GROUP_D_S_V:
2034 this->groupings[1] = GR_DESTINATION;
2035 this->groupings[2] = GR_SOURCE;
2036 this->groupings[3] = GR_NEXT;
2037 break;
2038 case STR_STATION_VIEW_GROUP_D_V_S:
2039 this->groupings[1] = GR_DESTINATION;
2040 this->groupings[2] = GR_NEXT;
2041 this->groupings[3] = GR_SOURCE;
2042 break;
2044 this->SetDirty();
2047 void OnDropdownSelect(int widget, int index) override
2049 if (widget == WID_SV_SORT_BY) {
2050 this->SelectSortBy(index);
2051 } else {
2052 this->SelectGroupBy(index);
2056 void OnQueryTextFinished(char *str) override
2058 if (str == nullptr) return;
2060 Command<CMD_RENAME_STATION>::Post(STR_ERROR_CAN_T_RENAME_STATION, this->window_number, str);
2063 void OnResize() override
2065 this->vscroll->SetCapacityFromWidget(this, WID_SV_WAITING, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
2069 * Some data on this window has become invalid. Invalidate the cache for the given cargo if necessary.
2070 * @param data Information about the changed data. If it's a valid cargo ID, invalidate the cargo data.
2071 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
2073 void OnInvalidateData(int data = 0, bool gui_scope = true) override
2075 if (gui_scope) {
2076 if (data >= 0 && data < NUM_CARGO) {
2077 this->cached_destinations.Remove((CargoID)data);
2078 } else {
2079 this->ReInit();
2085 const StringID StationViewWindow::_sort_names[] = {
2086 STR_STATION_VIEW_WAITING_STATION,
2087 STR_STATION_VIEW_WAITING_AMOUNT,
2088 STR_STATION_VIEW_PLANNED_STATION,
2089 STR_STATION_VIEW_PLANNED_AMOUNT,
2090 INVALID_STRING_ID
2093 const StringID StationViewWindow::_group_names[] = {
2094 STR_STATION_VIEW_GROUP_S_V_D,
2095 STR_STATION_VIEW_GROUP_S_D_V,
2096 STR_STATION_VIEW_GROUP_V_S_D,
2097 STR_STATION_VIEW_GROUP_V_D_S,
2098 STR_STATION_VIEW_GROUP_D_S_V,
2099 STR_STATION_VIEW_GROUP_D_V_S,
2100 INVALID_STRING_ID
2103 static WindowDesc _station_view_desc(
2104 WDP_AUTO, "view_station", 249, 117,
2105 WC_STATION_VIEW, WC_NONE,
2107 _nested_station_view_widgets, lengthof(_nested_station_view_widgets)
2111 * Opens StationViewWindow for given station
2113 * @param station station which window should be opened
2115 void ShowStationViewWindow(StationID station)
2117 AllocateWindowDescFront<StationViewWindow>(&_station_view_desc, station);
2120 /** Struct containing TileIndex and StationID */
2121 struct TileAndStation {
2122 TileIndex tile; ///< TileIndex
2123 StationID station; ///< StationID
2126 static std::vector<TileAndStation> _deleted_stations_nearby;
2127 static std::vector<StationID> _stations_nearby_list;
2130 * Add station on this tile to _stations_nearby_list if it's fully within the
2131 * station spread.
2132 * @param tile Tile just being checked
2133 * @param user_data Pointer to TileArea context
2134 * @tparam T the type of station to look for
2136 template <class T>
2137 static bool AddNearbyStation(TileIndex tile, void *user_data)
2139 TileArea *ctx = (TileArea *)user_data;
2141 /* First check if there were deleted stations here */
2142 for (uint i = 0; i < _deleted_stations_nearby.size(); i++) {
2143 auto ts = _deleted_stations_nearby.begin() + i;
2144 if (ts->tile == tile) {
2145 _stations_nearby_list.push_back(_deleted_stations_nearby[i].station);
2146 _deleted_stations_nearby.erase(ts);
2147 i--;
2151 /* Check if own station and if we stay within station spread */
2152 if (!IsTileType(tile, MP_STATION)) return false;
2154 StationID sid = GetStationIndex(tile);
2156 /* This station is (likely) a waypoint */
2157 if (!T::IsValidID(sid)) return false;
2159 T *st = T::Get(sid);
2160 if (st->owner != _local_company || std::find(_stations_nearby_list.begin(), _stations_nearby_list.end(), sid) != _stations_nearby_list.end()) return false;
2162 if (st->rect.BeforeAddRect(ctx->tile, ctx->w, ctx->h, StationRect::ADD_TEST).Succeeded()) {
2163 _stations_nearby_list.push_back(sid);
2166 return false; // We want to include *all* nearby stations
2170 * Circulate around the to-be-built station to find stations we could join.
2171 * Make sure that only stations are returned where joining wouldn't exceed
2172 * station spread and are our own station.
2173 * @param ta Base tile area of the to-be-built station
2174 * @param distant_join Search for adjacent stations (false) or stations fully
2175 * within station spread
2176 * @tparam T the type of station to look for
2178 template <class T>
2179 static const T *FindStationsNearby(TileArea ta, bool distant_join)
2181 TileArea ctx = ta;
2183 _stations_nearby_list.clear();
2184 _deleted_stations_nearby.clear();
2186 /* Check the inside, to return, if we sit on another station */
2187 for (TileIndex t : ta) {
2188 if (t < MapSize() && IsTileType(t, MP_STATION) && T::IsValidID(GetStationIndex(t))) return T::GetByTile(t);
2191 /* Look for deleted stations */
2192 for (const BaseStation *st : BaseStation::Iterate()) {
2193 if (T::IsExpected(st) && !st->IsInUse() && st->owner == _local_company) {
2194 /* Include only within station spread (yes, it is strictly less than) */
2195 if (std::max(DistanceMax(ta.tile, st->xy), DistanceMax(TILE_ADDXY(ta.tile, ta.w - 1, ta.h - 1), st->xy)) < _settings_game.station.station_spread) {
2196 _deleted_stations_nearby.push_back({st->xy, st->index});
2198 /* Add the station when it's within where we're going to build */
2199 if (IsInsideBS(TileX(st->xy), TileX(ctx.tile), ctx.w) &&
2200 IsInsideBS(TileY(st->xy), TileY(ctx.tile), ctx.h)) {
2201 AddNearbyStation<T>(st->xy, &ctx);
2207 /* Only search tiles where we have a chance to stay within the station spread.
2208 * The complete check needs to be done in the callback as we don't know the
2209 * extent of the found station, yet. */
2210 if (distant_join && std::min(ta.w, ta.h) >= _settings_game.station.station_spread) return nullptr;
2211 uint max_dist = distant_join ? _settings_game.station.station_spread - std::min(ta.w, ta.h) : 1;
2213 TileIndex tile = TileAddByDir(ctx.tile, DIR_N);
2214 CircularTileSearch(&tile, max_dist, ta.w, ta.h, AddNearbyStation<T>, &ctx);
2216 return nullptr;
2219 static const NWidgetPart _nested_select_station_widgets[] = {
2220 NWidget(NWID_HORIZONTAL),
2221 NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
2222 NWidget(WWT_CAPTION, COLOUR_DARK_GREEN, WID_JS_CAPTION), SetDataTip(STR_JOIN_STATION_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2223 NWidget(WWT_DEFSIZEBOX, COLOUR_DARK_GREEN),
2224 EndContainer(),
2225 NWidget(NWID_HORIZONTAL),
2226 NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_JS_PANEL), SetResize(1, 0), SetScrollbar(WID_JS_SCROLLBAR), EndContainer(),
2227 NWidget(NWID_VERTICAL),
2228 NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, WID_JS_SCROLLBAR),
2229 NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
2230 EndContainer(),
2231 EndContainer(),
2235 * Window for selecting stations/waypoints to (distant) join to.
2236 * @tparam T The type of station to join with
2238 template <class T>
2239 struct SelectStationWindow : Window {
2240 StationPickerCmdProc select_station_proc;
2241 TileArea area; ///< Location of new station
2242 Scrollbar *vscroll;
2244 SelectStationWindow(WindowDesc *desc, TileArea ta, StationPickerCmdProc&& proc) :
2245 Window(desc),
2246 select_station_proc(std::move(proc)),
2247 area(ta)
2249 this->CreateNestedTree();
2250 this->vscroll = this->GetScrollbar(WID_JS_SCROLLBAR);
2251 this->GetWidget<NWidgetCore>(WID_JS_CAPTION)->widget_data = T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_JOIN_WAYPOINT_CAPTION : STR_JOIN_STATION_CAPTION;
2252 this->FinishInitNested(0);
2253 this->OnInvalidateData(0);
2255 _thd.freeze = true;
2258 void Close() override
2260 if (_settings_client.gui.station_show_coverage) SetViewportCatchmentStation(nullptr, true);
2262 _thd.freeze = false;
2263 this->Window::Close();
2266 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
2268 if (widget != WID_JS_PANEL) return;
2270 /* Determine the widest string */
2271 Dimension d = GetStringBoundingBox(T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_JOIN_WAYPOINT_CREATE_SPLITTED_WAYPOINT : STR_JOIN_STATION_CREATE_SPLITTED_STATION);
2272 for (uint i = 0; i < _stations_nearby_list.size(); i++) {
2273 const T *st = T::Get(_stations_nearby_list[i]);
2274 SetDParam(0, st->index);
2275 SetDParam(1, st->facilities);
2276 d = maxdim(d, GetStringBoundingBox(T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_STATION_LIST_WAYPOINT : STR_STATION_LIST_STATION));
2279 resize->height = d.height;
2280 d.height *= 5;
2281 d.width += WD_FRAMERECT_RIGHT + WD_FRAMERECT_LEFT;
2282 d.height += WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
2283 *size = d;
2286 void DrawWidget(const Rect &r, int widget) const override
2288 if (widget != WID_JS_PANEL) return;
2290 uint y = r.top + WD_FRAMERECT_TOP;
2291 if (this->vscroll->GetPosition() == 0) {
2292 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_JOIN_WAYPOINT_CREATE_SPLITTED_WAYPOINT : STR_JOIN_STATION_CREATE_SPLITTED_STATION);
2293 y += this->resize.step_height;
2296 for (uint i = std::max<uint>(1, this->vscroll->GetPosition()); i <= _stations_nearby_list.size(); ++i, y += this->resize.step_height) {
2297 /* Don't draw anything if it extends past the end of the window. */
2298 if (i - this->vscroll->GetPosition() >= this->vscroll->GetCapacity()) break;
2300 const T *st = T::Get(_stations_nearby_list[i - 1]);
2301 SetDParam(0, st->index);
2302 SetDParam(1, st->facilities);
2303 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_STATION_LIST_WAYPOINT : STR_STATION_LIST_STATION);
2307 void OnClick(Point pt, int widget, int click_count) override
2309 if (widget != WID_JS_PANEL) return;
2311 uint st_index = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_JS_PANEL, WD_FRAMERECT_TOP);
2312 bool distant_join = (st_index > 0);
2313 if (distant_join) st_index--;
2315 if (distant_join && st_index >= _stations_nearby_list.size()) return;
2317 /* Execute stored Command */
2318 this->select_station_proc(false, distant_join ? _stations_nearby_list[st_index] : NEW_STATION);
2320 /* Close Window; this might cause double frees! */
2321 CloseWindowById(WC_SELECT_STATION, 0);
2324 void OnRealtimeTick(uint delta_ms) override
2326 if (_thd.dirty & 2) {
2327 _thd.dirty &= ~2;
2328 this->SetDirty();
2332 void OnResize() override
2334 this->vscroll->SetCapacityFromWidget(this, WID_JS_PANEL, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
2338 * Some data on this window has become invalid.
2339 * @param data Information about the changed data.
2340 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
2342 void OnInvalidateData(int data = 0, bool gui_scope = true) override
2344 if (!gui_scope) return;
2345 FindStationsNearby<T>(this->area, true);
2346 this->vscroll->SetCount((uint)_stations_nearby_list.size() + 1);
2347 this->SetDirty();
2350 void OnMouseOver(Point pt, int widget) override
2352 if (widget != WID_JS_PANEL || T::EXPECTED_FACIL == FACIL_WAYPOINT) {
2353 SetViewportCatchmentStation(nullptr, true);
2354 return;
2357 /* Show coverage area of station under cursor */
2358 uint st_index = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_JS_PANEL, WD_FRAMERECT_TOP);
2359 if (st_index == 0 || st_index > _stations_nearby_list.size()) {
2360 SetViewportCatchmentStation(nullptr, true);
2361 } else {
2362 st_index--;
2363 SetViewportCatchmentStation(Station::Get(_stations_nearby_list[st_index]), true);
2368 static WindowDesc _select_station_desc(
2369 WDP_AUTO, "build_station_join", 200, 180,
2370 WC_SELECT_STATION, WC_NONE,
2371 WDF_CONSTRUCTION,
2372 _nested_select_station_widgets, lengthof(_nested_select_station_widgets)
2377 * Check whether we need to show the station selection window.
2378 * @param cmd Command to build the station.
2379 * @param ta Tile area of the to-be-built station
2380 * @tparam T the type of station
2381 * @return whether we need to show the station selection window.
2383 template <class T>
2384 static bool StationJoinerNeeded(TileArea ta, const StationPickerCmdProc &proc)
2386 /* Only show selection if distant join is enabled in the settings */
2387 if (!_settings_game.station.distant_join_stations) return false;
2389 /* If a window is already opened and we didn't ctrl-click,
2390 * return true (i.e. just flash the old window) */
2391 Window *selection_window = FindWindowById(WC_SELECT_STATION, 0);
2392 if (selection_window != nullptr) {
2393 /* Abort current distant-join and start new one */
2394 selection_window->Close();
2395 UpdateTileSelection();
2398 /* only show the popup, if we press ctrl */
2399 if (!_ctrl_pressed) return false;
2401 /* Now check if we could build there */
2402 if (!proc(true, INVALID_STATION)) return false;
2404 /* Test for adjacent station or station below selection.
2405 * If adjacent-stations is disabled and we are building next to a station, do not show the selection window.
2406 * but join the other station immediately. */
2407 const T *st = FindStationsNearby<T>(ta, false);
2408 return st == nullptr && (_settings_game.station.adjacent_stations || _stations_nearby_list.size() == 0);
2412 * Show the station selection window when needed. If not, build the station.
2413 * @param cmd Command to build the station.
2414 * @param ta Area to build the station in
2415 * @tparam the class to find stations for
2417 template <class T>
2418 void ShowSelectBaseStationIfNeeded(TileArea ta, StationPickerCmdProc&& proc)
2420 if (StationJoinerNeeded<T>(ta, proc)) {
2421 if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
2422 new SelectStationWindow<T>(&_select_station_desc, ta, std::move(proc));
2423 } else {
2424 proc(false, INVALID_STATION);
2429 * Show the station selection window when needed. If not, build the station.
2430 * @param ta Area to build the station in
2431 * @param proc Function called to execute the build command.
2433 void ShowSelectStationIfNeeded(TileArea ta, StationPickerCmdProc proc)
2435 ShowSelectBaseStationIfNeeded<Station>(ta, std::move(proc));
2439 * Show the waypoint selection window when needed. If not, build the waypoint.
2440 * @param ta Area to build the waypoint in
2441 * @param proc Function called to execute the build command.
2443 void ShowSelectWaypointIfNeeded(TileArea ta, StationPickerCmdProc proc)
2445 ShowSelectBaseStationIfNeeded<Waypoint>(ta, std::move(proc));