Feature: Ctrl-click to remove fully autoreplaced vehicles from list (#9639)
[openttd-github.git] / src / station_gui.cpp
blobecc7ea77c32fae1267b47094981bab5c62854e2c
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"
35 #include "widgets/station_widget.h"
37 #include "table/strings.h"
39 #include <set>
40 #include <vector>
42 #include "safeguards.h"
44 /**
45 * Calculates and draws the accepted or supplied cargo around the selected tile(s)
46 * @param left x position where the string is to be drawn
47 * @param right the right most position to draw on
48 * @param top y position where the string is to be drawn
49 * @param sct which type of cargo is to be displayed (passengers/non-passengers)
50 * @param rad radius around selected tile(s) to be searched
51 * @param supplies if supplied cargoes should be drawn, else accepted cargoes
52 * @return Returns the y value below the string that was drawn
54 int DrawStationCoverageAreaText(int left, int right, int top, StationCoverageType sct, int rad, bool supplies)
56 TileIndex tile = TileVirtXY(_thd.pos.x, _thd.pos.y);
57 CargoTypes cargo_mask = 0;
58 if (_thd.drawstyle == HT_RECT && tile < MapSize()) {
59 CargoArray cargoes;
60 if (supplies) {
61 cargoes = GetProductionAroundTiles(tile, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE, rad);
62 } else {
63 cargoes = GetAcceptanceAroundTiles(tile, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE, rad);
66 /* Convert cargo counts to a set of cargo bits, and draw the result. */
67 for (CargoID i = 0; i < NUM_CARGO; i++) {
68 switch (sct) {
69 case SCT_PASSENGERS_ONLY: if (!IsCargoInClass(i, CC_PASSENGERS)) continue; break;
70 case SCT_NON_PASSENGERS_ONLY: if (IsCargoInClass(i, CC_PASSENGERS)) continue; break;
71 case SCT_ALL: break;
72 default: NOT_REACHED();
74 if (cargoes[i] >= (supplies ? 1U : 8U)) SetBit(cargo_mask, i);
77 SetDParam(0, cargo_mask);
78 return DrawStringMultiLine(left, right, top, INT32_MAX, supplies ? STR_STATION_BUILD_SUPPLIES_CARGO : STR_STATION_BUILD_ACCEPTS_CARGO);
81 /**
82 * Find stations adjacent to the current tile highlight area, so that existing coverage
83 * area can be drawn.
85 static void FindStationsAroundSelection()
87 /* With distant join we don't know which station will be selected, so don't show any */
88 if (_ctrl_pressed) {
89 SetViewportCatchmentStation(nullptr, true);
90 return;
93 /* Tile area for TileHighlightData */
94 TileArea location(TileVirtXY(_thd.pos.x, _thd.pos.y), _thd.size.x / TILE_SIZE - 1, _thd.size.y / TILE_SIZE - 1);
96 /* Extended area by one tile */
97 uint x = TileX(location.tile);
98 uint y = TileY(location.tile);
100 int max_c = 1;
101 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)));
103 Station *adjacent = nullptr;
105 /* Direct loop instead of ForAllStationsAroundTiles as we are not interested in catchment area */
106 for (TileIndex tile : ta) {
107 if (IsTileType(tile, MP_STATION) && GetTileOwner(tile) == _local_company) {
108 Station *st = Station::GetByTile(tile);
109 if (st == nullptr) continue;
110 if (adjacent != nullptr && st != adjacent) {
111 /* Multiple nearby, distant join is required. */
112 adjacent = nullptr;
113 break;
115 adjacent = st;
118 SetViewportCatchmentStation(adjacent, true);
122 * Check whether we need to redraw the station coverage text.
123 * If it is needed actually make the window for redrawing.
124 * @param w the window to check.
126 void CheckRedrawStationCoverage(const Window *w)
128 /* Test if ctrl state changed */
129 static bool _last_ctrl_pressed;
130 if (_ctrl_pressed != _last_ctrl_pressed) {
131 _thd.dirty = 0xff;
132 _last_ctrl_pressed = _ctrl_pressed;
135 if (_thd.dirty & 1) {
136 _thd.dirty &= ~1;
137 w->SetDirty();
139 if (_settings_client.gui.station_show_coverage && _thd.drawstyle == HT_RECT) {
140 FindStationsAroundSelection();
146 * Draw small boxes of cargo amount and ratings data at the given
147 * coordinates. If amount exceeds 576 units, it is shown 'full', same
148 * goes for the rating: at above 90% orso (224) it is also 'full'
150 * @param left left most coordinate to draw the box at
151 * @param right right most coordinate to draw the box at
152 * @param y coordinate to draw the box at
153 * @param type Cargo type
154 * @param amount Cargo amount
155 * @param rating ratings data for that particular cargo
157 static void StationsWndShowStationRating(int left, int right, int y, CargoID type, uint amount, byte rating)
159 static const uint units_full = 576; ///< number of units to show station as 'full'
160 static const uint rating_full = 224; ///< rating needed so it is shown as 'full'
162 const CargoSpec *cs = CargoSpec::Get(type);
163 if (!cs->IsValid()) return;
165 int padding = ScaleFontTrad(1);
166 int width = right - left;
167 int colour = cs->rating_colour;
168 TextColour tc = GetContrastColour(colour);
169 uint w = std::min(amount + 5, units_full) * width / units_full;
171 int height = GetCharacterHeight(FS_SMALL) + padding - 1;
173 if (amount > 30) {
174 /* Draw total cargo (limited) on station */
175 GfxFillRect(left, y, left + w - 1, y + height, colour);
176 } else {
177 /* Draw a (scaled) one pixel-wide bar of additional cargo meter, useful
178 * for stations with only a small amount (<=30) */
179 uint rest = ScaleFontTrad(amount) / 5;
180 if (rest != 0) {
181 GfxFillRect(left, y + height - rest, left + padding - 1, y + height, colour);
185 DrawString(left + padding, right, y, cs->abbrev, tc);
187 /* Draw green/red ratings bar (fits under the waiting bar) */
188 y += height + padding + 1;
189 GfxFillRect(left + padding, y, right - padding - 1, y + padding - 1, PC_RED);
190 w = std::min<uint>(rating, rating_full) * (width - padding - padding) / rating_full;
191 if (w != 0) GfxFillRect(left + padding, y, left + w - 1, y + padding - 1, PC_GREEN);
194 typedef GUIList<const Station*> GUIStationList;
197 * The list of stations per company.
199 class CompanyStationsWindow : public Window
201 protected:
202 /* Runtime saved values */
203 static Listing last_sorting;
204 static byte facilities; // types of stations of interest
205 static bool include_empty; // whether we should include stations without waiting cargo
206 static const CargoTypes cargo_filter_max;
207 static CargoTypes cargo_filter; // bitmap of cargo types to include
209 /* Constants for sorting stations */
210 static const StringID sorter_names[];
211 static GUIStationList::SortFunction * const sorter_funcs[];
213 GUIStationList stations;
214 Scrollbar *vscroll;
215 uint rating_width;
218 * (Re)Build station list
220 * @param owner company whose stations are to be in list
222 void BuildStationsList(const Owner owner)
224 if (!this->stations.NeedRebuild()) return;
226 Debug(misc, 3, "Building station list for company {}", owner);
228 this->stations.clear();
230 for (const Station *st : Station::Iterate()) {
231 if (st->owner == owner || (st->owner == OWNER_NONE && HasStationInUse(st->index, true, owner))) {
232 if (this->facilities & st->facilities) { // only stations with selected facilities
233 int num_waiting_cargo = 0;
234 for (CargoID j = 0; j < NUM_CARGO; j++) {
235 if (st->goods[j].HasRating()) {
236 num_waiting_cargo++; // count number of waiting cargo
237 if (HasBit(this->cargo_filter, j)) {
238 this->stations.push_back(st);
239 break;
243 /* stations without waiting cargo */
244 if (num_waiting_cargo == 0 && this->include_empty) {
245 this->stations.push_back(st);
251 this->stations.shrink_to_fit();
252 this->stations.RebuildDone();
254 this->vscroll->SetCount((uint)this->stations.size()); // Update the scrollbar
257 /** Sort stations by their name */
258 static bool StationNameSorter(const Station * const &a, const Station * const &b)
260 int r = strnatcmp(a->GetCachedName(), b->GetCachedName()); // Sort by name (natural sorting).
261 if (r == 0) return a->index < b->index;
262 return r < 0;
265 /** Sort stations by their type */
266 static bool StationTypeSorter(const Station * const &a, const Station * const &b)
268 return a->facilities < b->facilities;
271 /** Sort stations by their waiting cargo */
272 static bool StationWaitingTotalSorter(const Station * const &a, const Station * const &b)
274 int diff = 0;
276 for (CargoID j : SetCargoBitIterator(cargo_filter)) {
277 diff += a->goods[j].cargo.TotalCount() - b->goods[j].cargo.TotalCount();
280 return diff < 0;
283 /** Sort stations by their available waiting cargo */
284 static bool StationWaitingAvailableSorter(const Station * const &a, const Station * const &b)
286 int diff = 0;
288 for (CargoID j : SetCargoBitIterator(cargo_filter)) {
289 diff += a->goods[j].cargo.AvailableCount() - b->goods[j].cargo.AvailableCount();
292 return diff < 0;
295 /** Sort stations by their rating */
296 static bool StationRatingMaxSorter(const Station * const &a, const Station * const &b)
298 byte maxr1 = 0;
299 byte maxr2 = 0;
301 for (CargoID j : SetCargoBitIterator(cargo_filter)) {
302 if (a->goods[j].HasRating()) maxr1 = std::max(maxr1, a->goods[j].rating);
303 if (b->goods[j].HasRating()) maxr2 = std::max(maxr2, b->goods[j].rating);
306 return maxr1 < maxr2;
309 /** Sort stations by their rating */
310 static bool StationRatingMinSorter(const Station * const &a, const Station * const &b)
312 byte minr1 = 255;
313 byte minr2 = 255;
315 for (CargoID j = 0; j < NUM_CARGO; j++) {
316 if (!HasBit(cargo_filter, j)) continue;
317 if (a->goods[j].HasRating()) minr1 = std::min(minr1, a->goods[j].rating);
318 if (b->goods[j].HasRating()) minr2 = std::min(minr2, b->goods[j].rating);
321 return minr1 > minr2;
324 /** Sort the stations list */
325 void SortStationsList()
327 if (!this->stations.Sort()) return;
329 /* Set the modified widget dirty */
330 this->SetWidgetDirty(WID_STL_LIST);
333 public:
334 CompanyStationsWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
336 this->stations.SetListing(this->last_sorting);
337 this->stations.SetSortFuncs(this->sorter_funcs);
338 this->stations.ForceRebuild();
339 this->stations.NeedResort();
340 this->SortStationsList();
342 this->CreateNestedTree();
343 this->vscroll = this->GetScrollbar(WID_STL_SCROLLBAR);
344 this->FinishInitNested(window_number);
345 this->owner = (Owner)this->window_number;
347 uint8 index = 0;
348 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
349 if (HasBit(this->cargo_filter, cs->Index())) {
350 this->LowerWidget(WID_STL_CARGOSTART + index);
352 index++;
355 if (this->cargo_filter == this->cargo_filter_max) this->cargo_filter = _cargo_mask;
357 for (uint i = 0; i < 5; i++) {
358 if (HasBit(this->facilities, i)) this->LowerWidget(i + WID_STL_TRAIN);
360 this->SetWidgetLoweredState(WID_STL_NOCARGOWAITING, this->include_empty);
362 this->GetWidget<NWidgetCore>(WID_STL_SORTDROPBTN)->widget_data = this->sorter_names[this->stations.SortType()];
365 ~CompanyStationsWindow()
367 this->last_sorting = this->stations.GetListing();
370 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
372 switch (widget) {
373 case WID_STL_SORTBY: {
374 Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
375 d.width += padding.width + Window::SortButtonWidth() * 2; // Doubled since the string is centred and it also looks better.
376 d.height += padding.height;
377 *size = maxdim(*size, d);
378 break;
381 case WID_STL_SORTDROPBTN: {
382 Dimension d = {0, 0};
383 for (int i = 0; this->sorter_names[i] != INVALID_STRING_ID; i++) {
384 d = maxdim(d, GetStringBoundingBox(this->sorter_names[i]));
386 d.width += padding.width;
387 d.height += padding.height;
388 *size = maxdim(*size, d);
389 break;
392 case WID_STL_LIST:
393 resize->height = std::max(FONT_HEIGHT_NORMAL, FONT_HEIGHT_SMALL + ScaleFontTrad(3));
394 size->height = WD_FRAMERECT_TOP + 5 * resize->height + WD_FRAMERECT_BOTTOM;
396 /* Determine appropriate width for mini station rating graph */
397 this->rating_width = 0;
398 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
399 this->rating_width = std::max(this->rating_width, GetStringBoundingBox(cs->abbrev).width);
401 /* Approximately match original 16 pixel wide rating bars by multiplying string width by 1.6 */
402 this->rating_width = this->rating_width * 16 / 10;
403 break;
405 case WID_STL_CARGOALL:
406 case WID_STL_FACILALL:
407 case WID_STL_NOCARGOWAITING: {
408 Dimension d = GetStringBoundingBox(widget == WID_STL_NOCARGOWAITING ? STR_ABBREV_NONE : STR_ABBREV_ALL);
409 d.width += padding.width + 2;
410 d.height += padding.height;
411 *size = maxdim(*size, d);
412 break;
415 default:
416 if (widget >= WID_STL_CARGOSTART) {
417 Dimension d = GetStringBoundingBox(_sorted_cargo_specs[widget - WID_STL_CARGOSTART]->abbrev);
418 d.width += padding.width + 2;
419 d.height += padding.height;
420 *size = maxdim(*size, d);
422 break;
426 void OnPaint() override
428 this->BuildStationsList((Owner)this->window_number);
429 this->SortStationsList();
431 this->DrawWidgets();
434 void DrawWidget(const Rect &r, int widget) const override
436 switch (widget) {
437 case WID_STL_SORTBY:
438 /* draw arrow pointing up/down for ascending/descending sorting */
439 this->DrawSortButtonState(WID_STL_SORTBY, this->stations.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
440 break;
442 case WID_STL_LIST: {
443 bool rtl = _current_text_dir == TD_RTL;
444 int max = std::min<size_t>(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->stations.size());
445 int y = r.top + WD_FRAMERECT_TOP;
446 uint line_height = this->GetWidget<NWidgetBase>(widget)->resize_y;
447 /* Spacing between station name and first rating graph. */
448 int text_spacing = ScaleFontTrad(5);
449 /* Spacing between additional rating graphs. */
450 int rating_spacing = ScaleFontTrad(4);
452 for (int i = this->vscroll->GetPosition(); i < max; ++i) { // do until max number of stations of owner
453 const Station *st = this->stations[i];
454 assert(st->xy != INVALID_TILE);
456 /* Do not do the complex check HasStationInUse here, it may be even false
457 * when the order had been removed and the station list hasn't been removed yet */
458 assert(st->owner == owner || st->owner == OWNER_NONE);
460 SetDParam(0, st->index);
461 SetDParam(1, st->facilities);
462 int x = DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y + (line_height - FONT_HEIGHT_NORMAL) / 2, STR_STATION_LIST_STATION);
463 x += rtl ? -text_spacing : text_spacing;
465 /* show cargo waiting and station ratings */
466 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
467 CargoID cid = cs->Index();
468 if (st->goods[cid].cargo.TotalCount() > 0) {
469 /* For RTL we work in exactly the opposite direction. So
470 * decrement the space needed first, then draw to the left
471 * instead of drawing to the left and then incrementing
472 * the space. */
473 if (rtl) {
474 x -= rating_width + rating_spacing;
475 if (x < r.left + WD_FRAMERECT_LEFT) break;
477 StationsWndShowStationRating(x, x + rating_width, y, cid, st->goods[cid].cargo.TotalCount(), st->goods[cid].rating);
478 if (!rtl) {
479 x += rating_width + rating_spacing;
480 if (x > r.right - WD_FRAMERECT_RIGHT) break;
484 y += line_height;
487 if (this->vscroll->GetCount() == 0) { // company has no stations
488 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_LIST_NONE);
489 return;
491 break;
494 case WID_STL_NOCARGOWAITING: {
495 int cg_ofst = this->IsWidgetLowered(widget) ? 1 : 0;
496 DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + (r.bottom - r.top - FONT_HEIGHT_SMALL) / 2 + cg_ofst, STR_ABBREV_NONE, TC_BLACK, SA_HOR_CENTER);
497 break;
500 case WID_STL_CARGOALL: {
501 int cg_ofst = this->IsWidgetLowered(widget) ? 1 : 0;
502 DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + (r.bottom - r.top - FONT_HEIGHT_SMALL) / 2 + cg_ofst, STR_ABBREV_ALL, TC_BLACK, SA_HOR_CENTER);
503 break;
506 case WID_STL_FACILALL: {
507 int cg_ofst = this->IsWidgetLowered(widget) ? 1 : 0;
508 DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + (r.bottom - r.top - FONT_HEIGHT_SMALL) / 2 + cg_ofst, STR_ABBREV_ALL, TC_BLACK, SA_HOR_CENTER);
509 break;
512 default:
513 if (widget >= WID_STL_CARGOSTART) {
514 const CargoSpec *cs = _sorted_cargo_specs[widget - WID_STL_CARGOSTART];
515 int cg_ofst = HasBit(this->cargo_filter, cs->Index()) ? 1 : 0;
516 GfxFillRect(r.left + cg_ofst + 1, r.top + cg_ofst + 1, r.right - 1 + cg_ofst, r.bottom - 1 + cg_ofst, cs->rating_colour);
517 TextColour tc = GetContrastColour(cs->rating_colour);
518 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);
520 break;
524 void SetStringParameters(int widget) const override
526 if (widget == WID_STL_CAPTION) {
527 SetDParam(0, this->window_number);
528 SetDParam(1, this->vscroll->GetCount());
532 void OnClick(Point pt, int widget, int click_count) override
534 switch (widget) {
535 case WID_STL_LIST: {
536 uint id_v = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_STL_LIST);
537 if (id_v >= this->stations.size()) return; // click out of list bound
539 const Station *st = this->stations[id_v];
540 /* do not check HasStationInUse - it is slow and may be invalid */
541 assert(st->owner == (Owner)this->window_number || st->owner == OWNER_NONE);
543 if (_ctrl_pressed) {
544 ShowExtraViewportWindow(st->xy);
545 } else {
546 ScrollMainWindowToTile(st->xy);
548 break;
551 case WID_STL_TRAIN:
552 case WID_STL_TRUCK:
553 case WID_STL_BUS:
554 case WID_STL_AIRPLANE:
555 case WID_STL_SHIP:
556 if (_ctrl_pressed) {
557 ToggleBit(this->facilities, widget - WID_STL_TRAIN);
558 this->ToggleWidgetLoweredState(widget);
559 } else {
560 for (uint i : SetBitIterator(this->facilities)) {
561 this->RaiseWidget(i + WID_STL_TRAIN);
563 this->facilities = 1 << (widget - WID_STL_TRAIN);
564 this->LowerWidget(widget);
566 this->stations.ForceRebuild();
567 this->SetDirty();
568 break;
570 case WID_STL_FACILALL:
571 for (uint i = WID_STL_TRAIN; i <= WID_STL_SHIP; i++) {
572 this->LowerWidget(i);
575 this->facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK;
576 this->stations.ForceRebuild();
577 this->SetDirty();
578 break;
580 case WID_STL_CARGOALL: {
581 for (uint i = 0; i < _sorted_standard_cargo_specs.size(); i++) {
582 this->LowerWidget(WID_STL_CARGOSTART + i);
584 this->LowerWidget(WID_STL_NOCARGOWAITING);
586 this->cargo_filter = _cargo_mask;
587 this->include_empty = true;
588 this->stations.ForceRebuild();
589 this->SetDirty();
590 break;
593 case WID_STL_SORTBY: // flip sorting method asc/desc
594 this->stations.ToggleSortOrder();
595 this->SetDirty();
596 break;
598 case WID_STL_SORTDROPBTN: // select sorting criteria dropdown menu
599 ShowDropDownMenu(this, this->sorter_names, this->stations.SortType(), WID_STL_SORTDROPBTN, 0, 0);
600 break;
602 case WID_STL_NOCARGOWAITING:
603 if (_ctrl_pressed) {
604 this->include_empty = !this->include_empty;
605 this->ToggleWidgetLoweredState(WID_STL_NOCARGOWAITING);
606 } else {
607 for (uint i = 0; i < _sorted_standard_cargo_specs.size(); i++) {
608 this->RaiseWidget(WID_STL_CARGOSTART + i);
611 this->cargo_filter = 0;
612 this->include_empty = true;
614 this->LowerWidget(WID_STL_NOCARGOWAITING);
616 this->stations.ForceRebuild();
617 this->SetDirty();
618 break;
620 default:
621 if (widget >= WID_STL_CARGOSTART) { // change cargo_filter
622 /* Determine the selected cargo type */
623 const CargoSpec *cs = _sorted_cargo_specs[widget - WID_STL_CARGOSTART];
625 if (_ctrl_pressed) {
626 ToggleBit(this->cargo_filter, cs->Index());
627 this->ToggleWidgetLoweredState(widget);
628 } else {
629 for (uint i = 0; i < _sorted_standard_cargo_specs.size(); i++) {
630 this->RaiseWidget(WID_STL_CARGOSTART + i);
632 this->RaiseWidget(WID_STL_NOCARGOWAITING);
634 this->cargo_filter = 0;
635 this->include_empty = false;
637 SetBit(this->cargo_filter, cs->Index());
638 this->LowerWidget(widget);
640 this->stations.ForceRebuild();
641 this->SetDirty();
643 break;
647 void OnDropdownSelect(int widget, int index) override
649 if (this->stations.SortType() != index) {
650 this->stations.SetSortType(index);
652 /* Display the current sort variant */
653 this->GetWidget<NWidgetCore>(WID_STL_SORTDROPBTN)->widget_data = this->sorter_names[this->stations.SortType()];
655 this->SetDirty();
659 void OnGameTick() override
661 if (this->stations.NeedResort()) {
662 Debug(misc, 3, "Periodic rebuild station list company {}", this->window_number);
663 this->SetDirty();
667 void OnResize() override
669 this->vscroll->SetCapacityFromWidget(this, WID_STL_LIST, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
673 * Some data on this window has become invalid.
674 * @param data Information about the changed data.
675 * @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.
677 void OnInvalidateData(int data = 0, bool gui_scope = true) override
679 if (data == 0) {
680 /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
681 this->stations.ForceRebuild();
682 } else {
683 this->stations.ForceResort();
688 Listing CompanyStationsWindow::last_sorting = {false, 0};
689 byte CompanyStationsWindow::facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK;
690 bool CompanyStationsWindow::include_empty = true;
691 const CargoTypes CompanyStationsWindow::cargo_filter_max = ALL_CARGOTYPES;
692 CargoTypes CompanyStationsWindow::cargo_filter = ALL_CARGOTYPES;
694 /* Available station sorting functions */
695 GUIStationList::SortFunction * const CompanyStationsWindow::sorter_funcs[] = {
696 &StationNameSorter,
697 &StationTypeSorter,
698 &StationWaitingTotalSorter,
699 &StationWaitingAvailableSorter,
700 &StationRatingMaxSorter,
701 &StationRatingMinSorter
704 /* Names of the sorting functions */
705 const StringID CompanyStationsWindow::sorter_names[] = {
706 STR_SORT_BY_NAME,
707 STR_SORT_BY_FACILITY,
708 STR_SORT_BY_WAITING_TOTAL,
709 STR_SORT_BY_WAITING_AVAILABLE,
710 STR_SORT_BY_RATING_MAX,
711 STR_SORT_BY_RATING_MIN,
712 INVALID_STRING_ID
716 * Make a horizontal row of cargo buttons, starting at widget #WID_STL_CARGOSTART.
717 * @param biggest_index Pointer to store biggest used widget number of the buttons.
718 * @return Horizontal row.
720 static NWidgetBase *CargoWidgets(int *biggest_index)
722 NWidgetHorizontal *container = new NWidgetHorizontal();
724 for (uint i = 0; i < _sorted_standard_cargo_specs.size(); i++) {
725 NWidgetBackground *panel = new NWidgetBackground(WWT_PANEL, COLOUR_GREY, WID_STL_CARGOSTART + i);
726 panel->SetMinimalSize(14, 0);
727 panel->SetMinimalTextLines(1, 0, FS_NORMAL);
728 panel->SetResize(0, 0);
729 panel->SetFill(0, 1);
730 panel->SetDataTip(0, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE);
731 container->Add(panel);
733 *biggest_index = WID_STL_CARGOSTART + static_cast<int>(_sorted_standard_cargo_specs.size());
734 return container;
737 static const NWidgetPart _nested_company_stations_widgets[] = {
738 NWidget(NWID_HORIZONTAL),
739 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
740 NWidget(WWT_CAPTION, COLOUR_GREY, WID_STL_CAPTION), SetDataTip(STR_STATION_LIST_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
741 NWidget(WWT_SHADEBOX, COLOUR_GREY),
742 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
743 NWidget(WWT_STICKYBOX, COLOUR_GREY),
744 EndContainer(),
745 NWidget(NWID_HORIZONTAL),
746 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),
747 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),
748 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),
749 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),
750 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),
751 NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_STL_FACILALL), SetMinimalSize(14, 0), SetMinimalTextLines(1, 0), SetDataTip(0x0, STR_STATION_LIST_SELECT_ALL_FACILITIES), SetFill(0, 1),
752 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(5, 0), SetFill(0, 1), EndContainer(),
753 NWidgetFunction(CargoWidgets),
754 NWidget(WWT_PANEL, COLOUR_GREY, WID_STL_NOCARGOWAITING), SetMinimalSize(14, 0), SetMinimalTextLines(1, 0), SetDataTip(0x0, STR_STATION_LIST_NO_WAITING_CARGO), SetFill(0, 1), EndContainer(),
755 NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_STL_CARGOALL), SetMinimalSize(14, 0), SetMinimalTextLines(1, 0), SetDataTip(0x0, STR_STATION_LIST_SELECT_ALL_TYPES), SetFill(0, 1),
756 NWidget(WWT_PANEL, COLOUR_GREY), SetDataTip(0x0, STR_NULL), SetResize(1, 0), SetFill(1, 1), EndContainer(),
757 EndContainer(),
758 NWidget(NWID_HORIZONTAL),
759 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_STL_SORTBY), SetMinimalSize(81, 12), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
760 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_STL_SORTDROPBTN), SetMinimalSize(163, 12), SetDataTip(STR_SORT_BY_NAME, STR_TOOLTIP_SORT_CRITERIA), // widget_data gets overwritten.
761 NWidget(WWT_PANEL, COLOUR_GREY), SetDataTip(0x0, STR_NULL), SetResize(1, 0), SetFill(1, 1), EndContainer(),
762 EndContainer(),
763 NWidget(NWID_HORIZONTAL),
764 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(),
765 NWidget(NWID_VERTICAL),
766 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_STL_SCROLLBAR),
767 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
768 EndContainer(),
769 EndContainer(),
772 static WindowDesc _company_stations_desc(
773 WDP_AUTO, "list_stations", 358, 162,
774 WC_STATION_LIST, WC_NONE,
776 _nested_company_stations_widgets, lengthof(_nested_company_stations_widgets)
780 * Opens window with list of company's stations
782 * @param company whose stations' list show
784 void ShowCompanyStations(CompanyID company)
786 if (!Company::IsValidID(company)) return;
788 AllocateWindowDescFront<CompanyStationsWindow>(&_company_stations_desc, company);
791 static const NWidgetPart _nested_station_view_widgets[] = {
792 NWidget(NWID_HORIZONTAL),
793 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
794 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_SV_RENAME), SetMinimalSize(12, 14), SetDataTip(SPR_RENAME, STR_STATION_VIEW_RENAME_TOOLTIP),
795 NWidget(WWT_CAPTION, COLOUR_GREY, WID_SV_CAPTION), SetDataTip(STR_STATION_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
796 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_SV_LOCATION), SetMinimalSize(12, 14), SetDataTip(SPR_GOTO_LOCATION, STR_STATION_VIEW_CENTER_TOOLTIP),
797 NWidget(WWT_SHADEBOX, COLOUR_GREY),
798 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
799 NWidget(WWT_STICKYBOX, COLOUR_GREY),
800 EndContainer(),
801 NWidget(NWID_HORIZONTAL),
802 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_SV_GROUP), SetMinimalSize(81, 12), SetFill(1, 1), SetDataTip(STR_STATION_VIEW_GROUP, 0x0),
803 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_SV_GROUP_BY), SetMinimalSize(168, 12), SetResize(1, 0), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_GROUP_ORDER),
804 EndContainer(),
805 NWidget(NWID_HORIZONTAL),
806 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_SORT_ORDER), SetMinimalSize(81, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
807 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_SV_SORT_BY), SetMinimalSize(168, 12), SetResize(1, 0), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
808 EndContainer(),
809 NWidget(NWID_HORIZONTAL),
810 NWidget(WWT_PANEL, COLOUR_GREY, WID_SV_WAITING), SetMinimalSize(237, 44), SetResize(1, 10), SetScrollbar(WID_SV_SCROLLBAR), EndContainer(),
811 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_SV_SCROLLBAR),
812 EndContainer(),
813 NWidget(WWT_PANEL, COLOUR_GREY, WID_SV_ACCEPT_RATING_LIST), SetMinimalSize(249, 23), SetResize(1, 0), EndContainer(),
814 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
815 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_ACCEPTS_RATINGS), SetMinimalSize(46, 12), SetResize(1, 0), SetFill(1, 1),
816 SetDataTip(STR_STATION_VIEW_RATINGS_BUTTON, STR_STATION_VIEW_RATINGS_TOOLTIP),
817 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_SV_CLOSE_AIRPORT), SetMinimalSize(45, 12), SetResize(1, 0), SetFill(1, 1),
818 SetDataTip(STR_STATION_VIEW_CLOSE_AIRPORT, STR_STATION_VIEW_CLOSE_AIRPORT_TOOLTIP),
819 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_SV_CATCHMENT), SetMinimalSize(45, 12), SetResize(1, 0), SetFill(1, 1), SetDataTip(STR_BUTTON_CATCHMENT, STR_TOOLTIP_CATCHMENT),
820 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_TRAINS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_TRAIN, STR_STATION_VIEW_SCHEDULED_TRAINS_TOOLTIP),
821 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_ROADVEHS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_LORRY, STR_STATION_VIEW_SCHEDULED_ROAD_VEHICLES_TOOLTIP),
822 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_SHIPS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_SHIP, STR_STATION_VIEW_SCHEDULED_SHIPS_TOOLTIP),
823 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_PLANES), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_PLANE, STR_STATION_VIEW_SCHEDULED_AIRCRAFT_TOOLTIP),
824 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
825 EndContainer(),
829 * Draws icons of waiting cargo in the StationView window
831 * @param i type of cargo
832 * @param waiting number of waiting units
833 * @param left left most coordinate to draw on
834 * @param right right most coordinate to draw on
835 * @param y y coordinate
837 static void DrawCargoIcons(CargoID i, uint waiting, int left, int right, int y)
839 int width = ScaleGUITrad(10);
840 uint num = std::min<uint>((waiting + (width / 2)) / width, (right - left) / width); // maximum is width / 10 icons so it won't overflow
841 if (num == 0) return;
843 SpriteID sprite = CargoSpec::Get(i)->GetCargoIcon();
845 int x = _current_text_dir == TD_RTL ? left : right - num * width;
846 do {
847 DrawSprite(sprite, PAL_NONE, x, y);
848 x += width;
849 } while (--num);
852 enum SortOrder {
853 SO_DESCENDING,
854 SO_ASCENDING
857 class CargoDataEntry;
859 enum CargoSortType {
860 ST_AS_GROUPING, ///< by the same principle the entries are being grouped
861 ST_COUNT, ///< by amount of cargo
862 ST_STATION_STRING, ///< by station name
863 ST_STATION_ID, ///< by station id
864 ST_CARGO_ID, ///< by cargo id
867 class CargoSorter {
868 public:
869 CargoSorter(CargoSortType t = ST_STATION_ID, SortOrder o = SO_ASCENDING) : type(t), order(o) {}
870 CargoSortType GetSortType() {return this->type;}
871 bool operator()(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const;
873 private:
874 CargoSortType type;
875 SortOrder order;
877 template<class Tid>
878 bool SortId(Tid st1, Tid st2) const;
879 bool SortCount(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const;
880 bool SortStation (StationID st1, StationID st2) const;
883 typedef std::set<CargoDataEntry *, CargoSorter> CargoDataSet;
886 * A cargo data entry representing one possible row in the station view window's
887 * top part. Cargo data entries form a tree where each entry can have several
888 * children. Parents keep track of the sums of their childrens' cargo counts.
890 class CargoDataEntry {
891 public:
892 CargoDataEntry();
893 ~CargoDataEntry();
896 * Insert a new child or retrieve an existing child using a station ID as ID.
897 * @param station ID of the station for which an entry shall be created or retrieved
898 * @return a child entry associated with the given station.
900 CargoDataEntry *InsertOrRetrieve(StationID station)
902 return this->InsertOrRetrieve<StationID>(station);
906 * Insert a new child or retrieve an existing child using a cargo ID as ID.
907 * @param cargo ID of the cargo for which an entry shall be created or retrieved
908 * @return a child entry associated with the given cargo.
910 CargoDataEntry *InsertOrRetrieve(CargoID cargo)
912 return this->InsertOrRetrieve<CargoID>(cargo);
915 void Update(uint count);
918 * Remove a child associated with the given station.
919 * @param station ID of the station for which the child should be removed.
921 void Remove(StationID station)
923 CargoDataEntry t(station);
924 this->Remove(&t);
928 * Remove a child associated with the given cargo.
929 * @param cargo ID of the cargo for which the child should be removed.
931 void Remove(CargoID cargo)
933 CargoDataEntry t(cargo);
934 this->Remove(&t);
938 * Retrieve a child for the given station. Return nullptr if it doesn't exist.
939 * @param station ID of the station the child we're looking for is associated with.
940 * @return a child entry for the given station or nullptr.
942 CargoDataEntry *Retrieve(StationID station) const
944 CargoDataEntry t(station);
945 return this->Retrieve(this->children->find(&t));
949 * Retrieve a child for the given cargo. Return nullptr if it doesn't exist.
950 * @param cargo ID of the cargo the child we're looking for is associated with.
951 * @return a child entry for the given cargo or nullptr.
953 CargoDataEntry *Retrieve(CargoID cargo) const
955 CargoDataEntry t(cargo);
956 return this->Retrieve(this->children->find(&t));
959 void Resort(CargoSortType type, SortOrder order);
962 * Get the station ID for this entry.
964 StationID GetStation() const { return this->station; }
967 * Get the cargo ID for this entry.
969 CargoID GetCargo() const { return this->cargo; }
972 * Get the cargo count for this entry.
974 uint GetCount() const { return this->count; }
977 * Get the parent entry for this entry.
979 CargoDataEntry *GetParent() const { return this->parent; }
982 * Get the number of children for this entry.
984 uint GetNumChildren() const { return this->num_children; }
987 * Get an iterator pointing to the begin of the set of children.
989 CargoDataSet::iterator Begin() const { return this->children->begin(); }
992 * Get an iterator pointing to the end of the set of children.
994 CargoDataSet::iterator End() const { return this->children->end(); }
997 * Has this entry transfers.
999 bool HasTransfers() const { return this->transfers; }
1002 * Set the transfers state.
1004 void SetTransfers(bool value) { this->transfers = value; }
1006 void Clear();
1007 private:
1009 CargoDataEntry(StationID st, uint c, CargoDataEntry *p);
1010 CargoDataEntry(CargoID car, uint c, CargoDataEntry *p);
1011 CargoDataEntry(StationID st);
1012 CargoDataEntry(CargoID car);
1014 CargoDataEntry *Retrieve(CargoDataSet::iterator i) const;
1016 template<class Tid>
1017 CargoDataEntry *InsertOrRetrieve(Tid s);
1019 void Remove(CargoDataEntry *comp);
1020 void IncrementSize();
1022 CargoDataEntry *parent; ///< the parent of this entry.
1023 const union {
1024 StationID station; ///< ID of the station this entry is associated with.
1025 struct {
1026 CargoID cargo; ///< ID of the cargo this entry is associated with.
1027 bool transfers; ///< If there are transfers for this cargo.
1030 uint num_children; ///< the number of subentries belonging to this entry.
1031 uint count; ///< sum of counts of all children or amount of cargo for this entry.
1032 CargoDataSet *children; ///< the children of this entry.
1035 CargoDataEntry::CargoDataEntry() :
1036 parent(nullptr),
1037 station(INVALID_STATION),
1038 num_children(0),
1039 count(0),
1040 children(new CargoDataSet(CargoSorter(ST_CARGO_ID)))
1043 CargoDataEntry::CargoDataEntry(CargoID cargo, uint count, CargoDataEntry *parent) :
1044 parent(parent),
1045 cargo(cargo),
1046 num_children(0),
1047 count(count),
1048 children(new CargoDataSet)
1051 CargoDataEntry::CargoDataEntry(StationID station, uint count, CargoDataEntry *parent) :
1052 parent(parent),
1053 station(station),
1054 num_children(0),
1055 count(count),
1056 children(new CargoDataSet)
1059 CargoDataEntry::CargoDataEntry(StationID station) :
1060 parent(nullptr),
1061 station(station),
1062 num_children(0),
1063 count(0),
1064 children(nullptr)
1067 CargoDataEntry::CargoDataEntry(CargoID cargo) :
1068 parent(nullptr),
1069 cargo(cargo),
1070 num_children(0),
1071 count(0),
1072 children(nullptr)
1075 CargoDataEntry::~CargoDataEntry()
1077 this->Clear();
1078 delete this->children;
1082 * Delete all subentries, reset count and num_children and adapt parent's count.
1084 void CargoDataEntry::Clear()
1086 if (this->children != nullptr) {
1087 for (CargoDataSet::iterator i = this->children->begin(); i != this->children->end(); ++i) {
1088 assert(*i != this);
1089 delete *i;
1091 this->children->clear();
1093 if (this->parent != nullptr) this->parent->count -= this->count;
1094 this->count = 0;
1095 this->num_children = 0;
1099 * Remove a subentry from this one and delete it.
1100 * @param child the entry to be removed. This may also be a synthetic entry
1101 * which only contains the ID of the entry to be removed. In this case child is
1102 * not deleted.
1104 void CargoDataEntry::Remove(CargoDataEntry *child)
1106 CargoDataSet::iterator i = this->children->find(child);
1107 if (i != this->children->end()) {
1108 delete *i;
1109 this->children->erase(i);
1114 * Retrieve a subentry or insert it if it doesn't exist, yet.
1115 * @tparam ID type of ID: either StationID or CargoID
1116 * @param child_id ID of the child to be inserted or retrieved.
1117 * @return the new or retrieved subentry
1119 template<class Tid>
1120 CargoDataEntry *CargoDataEntry::InsertOrRetrieve(Tid child_id)
1122 CargoDataEntry tmp(child_id);
1123 CargoDataSet::iterator i = this->children->find(&tmp);
1124 if (i == this->children->end()) {
1125 IncrementSize();
1126 return *(this->children->insert(new CargoDataEntry(child_id, 0, this)).first);
1127 } else {
1128 CargoDataEntry *ret = *i;
1129 assert(this->children->value_comp().GetSortType() != ST_COUNT);
1130 return ret;
1135 * Update the count for this entry and propagate the change to the parent entry
1136 * if there is one.
1137 * @param count the amount to be added to this entry
1139 void CargoDataEntry::Update(uint count)
1141 this->count += count;
1142 if (this->parent != nullptr) this->parent->Update(count);
1146 * Increment
1148 void CargoDataEntry::IncrementSize()
1150 ++this->num_children;
1151 if (this->parent != nullptr) this->parent->IncrementSize();
1154 void CargoDataEntry::Resort(CargoSortType type, SortOrder order)
1156 CargoDataSet *new_subs = new CargoDataSet(this->children->begin(), this->children->end(), CargoSorter(type, order));
1157 delete this->children;
1158 this->children = new_subs;
1161 CargoDataEntry *CargoDataEntry::Retrieve(CargoDataSet::iterator i) const
1163 if (i == this->children->end()) {
1164 return nullptr;
1165 } else {
1166 assert(this->children->value_comp().GetSortType() != ST_COUNT);
1167 return *i;
1171 bool CargoSorter::operator()(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const
1173 switch (this->type) {
1174 case ST_STATION_ID:
1175 return this->SortId<StationID>(cd1->GetStation(), cd2->GetStation());
1176 case ST_CARGO_ID:
1177 return this->SortId<CargoID>(cd1->GetCargo(), cd2->GetCargo());
1178 case ST_COUNT:
1179 return this->SortCount(cd1, cd2);
1180 case ST_STATION_STRING:
1181 return this->SortStation(cd1->GetStation(), cd2->GetStation());
1182 default:
1183 NOT_REACHED();
1187 template<class Tid>
1188 bool CargoSorter::SortId(Tid st1, Tid st2) const
1190 return (this->order == SO_ASCENDING) ? st1 < st2 : st2 < st1;
1193 bool CargoSorter::SortCount(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const
1195 uint c1 = cd1->GetCount();
1196 uint c2 = cd2->GetCount();
1197 if (c1 == c2) {
1198 return this->SortStation(cd1->GetStation(), cd2->GetStation());
1199 } else if (this->order == SO_ASCENDING) {
1200 return c1 < c2;
1201 } else {
1202 return c2 < c1;
1206 bool CargoSorter::SortStation(StationID st1, StationID st2) const
1208 if (!Station::IsValidID(st1)) {
1209 return Station::IsValidID(st2) ? this->order == SO_ASCENDING : this->SortId(st1, st2);
1210 } else if (!Station::IsValidID(st2)) {
1211 return order == SO_DESCENDING;
1214 int res = strnatcmp(Station::Get(st1)->GetCachedName(), Station::Get(st2)->GetCachedName()); // Sort by name (natural sorting).
1215 if (res == 0) {
1216 return this->SortId(st1, st2);
1217 } else {
1218 return (this->order == SO_ASCENDING) ? res < 0 : res > 0;
1223 * The StationView window
1225 struct StationViewWindow : public Window {
1227 * A row being displayed in the cargo view (as opposed to being "hidden" behind a plus sign).
1229 struct RowDisplay {
1230 RowDisplay(CargoDataEntry *f, StationID n) : filter(f), next_station(n) {}
1231 RowDisplay(CargoDataEntry *f, CargoID n) : filter(f), next_cargo(n) {}
1234 * Parent of the cargo entry belonging to the row.
1236 CargoDataEntry *filter;
1237 union {
1239 * ID of the station belonging to the entry actually displayed if it's to/from/via.
1241 StationID next_station;
1244 * ID of the cargo belonging to the entry actually displayed if it's cargo.
1246 CargoID next_cargo;
1250 typedef std::vector<RowDisplay> CargoDataVector;
1252 static const int NUM_COLUMNS = 4; ///< Number of "columns" in the cargo view: cargo, from, via, to
1255 * Type of data invalidation.
1257 enum Invalidation {
1258 INV_FLOWS = 0x100, ///< The planned flows have been recalculated and everything has to be updated.
1259 INV_CARGO = 0x200 ///< Some cargo has been added or removed.
1263 * Type of grouping used in each of the "columns".
1265 enum Grouping {
1266 GR_SOURCE, ///< Group by source of cargo ("from").
1267 GR_NEXT, ///< Group by next station ("via").
1268 GR_DESTINATION, ///< Group by estimated final destination ("to").
1269 GR_CARGO, ///< Group by cargo type.
1273 * Display mode of the cargo view.
1275 enum Mode {
1276 MODE_WAITING, ///< Show cargo waiting at the station.
1277 MODE_PLANNED ///< Show cargo planned to pass through the station.
1280 uint expand_shrink_width; ///< The width allocated to the expand/shrink 'button'
1281 int rating_lines; ///< Number of lines in the cargo ratings view.
1282 int accepts_lines; ///< Number of lines in the accepted cargo view.
1283 Scrollbar *vscroll;
1285 /** Height of the #WID_SV_ACCEPT_RATING_LIST widget for different views. */
1286 enum AcceptListHeight {
1287 ALH_RATING = 13, ///< Height of the cargo ratings view.
1288 ALH_ACCEPTS = 3, ///< Height of the accepted cargo view.
1291 static const StringID _sort_names[]; ///< Names of the sorting options in the dropdown.
1292 static const StringID _group_names[]; ///< Names of the grouping options in the dropdown.
1295 * Sort types of the different 'columns'.
1296 * In fact only ST_COUNT and ST_AS_GROUPING are active and you can only
1297 * sort all the columns in the same way. The other options haven't been
1298 * included in the GUI due to lack of space.
1300 CargoSortType sortings[NUM_COLUMNS];
1302 /** Sort order (ascending/descending) for the 'columns'. */
1303 SortOrder sort_orders[NUM_COLUMNS];
1305 int scroll_to_row; ///< If set, scroll the main viewport to the station pointed to by this row.
1306 int grouping_index; ///< Currently selected entry in the grouping drop down.
1307 Mode current_mode; ///< Currently selected display mode of cargo view.
1308 Grouping groupings[NUM_COLUMNS]; ///< Grouping modes for the different columns.
1310 CargoDataEntry expanded_rows; ///< Parent entry of currently expanded rows.
1311 CargoDataEntry cached_destinations; ///< Cache for the flows passing through this station.
1312 CargoDataVector displayed_rows; ///< Parent entry of currently displayed rows (including collapsed ones).
1314 StationViewWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc),
1315 scroll_to_row(INT_MAX), grouping_index(0)
1317 this->rating_lines = ALH_RATING;
1318 this->accepts_lines = ALH_ACCEPTS;
1320 this->CreateNestedTree();
1321 this->vscroll = this->GetScrollbar(WID_SV_SCROLLBAR);
1322 /* Nested widget tree creation is done in two steps to ensure that this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS) exists in UpdateWidgetSize(). */
1323 this->FinishInitNested(window_number);
1325 this->groupings[0] = GR_CARGO;
1326 this->sortings[0] = ST_AS_GROUPING;
1327 this->SelectGroupBy(_settings_client.gui.station_gui_group_order);
1328 this->SelectSortBy(_settings_client.gui.station_gui_sort_by);
1329 this->sort_orders[0] = SO_ASCENDING;
1330 this->SelectSortOrder((SortOrder)_settings_client.gui.station_gui_sort_order);
1331 this->owner = Station::Get(window_number)->owner;
1334 void Close() override
1336 CloseWindowById(WC_TRAINS_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_TRAIN, this->owner, this->window_number).Pack(), false);
1337 CloseWindowById(WC_ROADVEH_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_ROAD, this->owner, this->window_number).Pack(), false);
1338 CloseWindowById(WC_SHIPS_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_SHIP, this->owner, this->window_number).Pack(), false);
1339 CloseWindowById(WC_AIRCRAFT_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_AIRCRAFT, this->owner, this->window_number).Pack(), false);
1341 SetViewportCatchmentStation(Station::Get(this->window_number), false);
1342 this->Window::Close();
1346 * Show a certain cargo entry characterized by source/next/dest station, cargo ID and amount of cargo at the
1347 * right place in the cargo view. I.e. update as many rows as are expanded following that characterization.
1348 * @param data Root entry of the tree.
1349 * @param cargo Cargo ID of the entry to be shown.
1350 * @param source Source station of the entry to be shown.
1351 * @param next Next station the cargo to be shown will visit.
1352 * @param dest Final destination of the cargo to be shown.
1353 * @param count Amount of cargo to be shown.
1355 void ShowCargo(CargoDataEntry *data, CargoID cargo, StationID source, StationID next, StationID dest, uint count)
1357 if (count == 0) return;
1358 bool auto_distributed = _settings_game.linkgraph.GetDistributionType(cargo) != DT_MANUAL;
1359 const CargoDataEntry *expand = &this->expanded_rows;
1360 for (int i = 0; i < NUM_COLUMNS && expand != nullptr; ++i) {
1361 switch (groupings[i]) {
1362 case GR_CARGO:
1363 assert(i == 0);
1364 data = data->InsertOrRetrieve(cargo);
1365 data->SetTransfers(source != this->window_number);
1366 expand = expand->Retrieve(cargo);
1367 break;
1368 case GR_SOURCE:
1369 if (auto_distributed || source != this->window_number) {
1370 data = data->InsertOrRetrieve(source);
1371 expand = expand->Retrieve(source);
1373 break;
1374 case GR_NEXT:
1375 if (auto_distributed) {
1376 data = data->InsertOrRetrieve(next);
1377 expand = expand->Retrieve(next);
1379 break;
1380 case GR_DESTINATION:
1381 if (auto_distributed) {
1382 data = data->InsertOrRetrieve(dest);
1383 expand = expand->Retrieve(dest);
1385 break;
1388 data->Update(count);
1391 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
1393 switch (widget) {
1394 case WID_SV_WAITING:
1395 resize->height = FONT_HEIGHT_NORMAL;
1396 size->height = WD_FRAMERECT_TOP + 4 * resize->height + WD_FRAMERECT_BOTTOM;
1397 this->expand_shrink_width = std::max(GetStringBoundingBox("-").width, GetStringBoundingBox("+").width) + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
1398 break;
1400 case WID_SV_ACCEPT_RATING_LIST:
1401 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;
1402 break;
1404 case WID_SV_CLOSE_AIRPORT:
1405 if (!(Station::Get(this->window_number)->facilities & FACIL_AIRPORT)) {
1406 /* Hide 'Close Airport' button if no airport present. */
1407 size->width = 0;
1408 resize->width = 0;
1409 fill->width = 0;
1411 break;
1415 void OnPaint() override
1417 const Station *st = Station::Get(this->window_number);
1418 CargoDataEntry cargo;
1419 BuildCargoList(&cargo, st);
1421 this->vscroll->SetCount(cargo.GetNumChildren()); // update scrollbar
1423 /* disable some buttons */
1424 this->SetWidgetDisabledState(WID_SV_RENAME, st->owner != _local_company);
1425 this->SetWidgetDisabledState(WID_SV_TRAINS, !(st->facilities & FACIL_TRAIN));
1426 this->SetWidgetDisabledState(WID_SV_ROADVEHS, !(st->facilities & FACIL_TRUCK_STOP) && !(st->facilities & FACIL_BUS_STOP));
1427 this->SetWidgetDisabledState(WID_SV_SHIPS, !(st->facilities & FACIL_DOCK));
1428 this->SetWidgetDisabledState(WID_SV_PLANES, !(st->facilities & FACIL_AIRPORT));
1429 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
1430 this->SetWidgetLoweredState(WID_SV_CLOSE_AIRPORT, (st->facilities & FACIL_AIRPORT) && (st->airport.flags & AIRPORT_CLOSED_block) != 0);
1432 extern const Station *_viewport_highlight_station;
1433 this->SetWidgetDisabledState(WID_SV_CATCHMENT, st->facilities == FACIL_NONE);
1434 this->SetWidgetLoweredState(WID_SV_CATCHMENT, _viewport_highlight_station == st);
1436 this->DrawWidgets();
1438 if (!this->IsShaded()) {
1439 /* Draw 'accepted cargo' or 'cargo ratings'. */
1440 const NWidgetBase *wid = this->GetWidget<NWidgetBase>(WID_SV_ACCEPT_RATING_LIST);
1441 const Rect r = wid->GetCurrentRect();
1442 if (this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) {
1443 int lines = this->DrawAcceptedCargo(r);
1444 if (lines > this->accepts_lines) { // Resize the widget, and perform re-initialization of the window.
1445 this->accepts_lines = lines;
1446 this->ReInit();
1447 return;
1449 } else {
1450 int lines = this->DrawCargoRatings(r);
1451 if (lines > this->rating_lines) { // Resize the widget, and perform re-initialization of the window.
1452 this->rating_lines = lines;
1453 this->ReInit();
1454 return;
1458 /* Draw arrow pointing up/down for ascending/descending sorting */
1459 this->DrawSortButtonState(WID_SV_SORT_ORDER, sort_orders[1] == SO_ASCENDING ? SBS_UP : SBS_DOWN);
1461 int pos = this->vscroll->GetPosition();
1463 int maxrows = this->vscroll->GetCapacity();
1465 displayed_rows.clear();
1467 /* Draw waiting cargo. */
1468 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_SV_WAITING);
1469 Rect waiting_rect = nwi->GetCurrentRect();
1470 this->DrawEntries(&cargo, waiting_rect, pos, maxrows, 0);
1471 scroll_to_row = INT_MAX;
1475 void SetStringParameters(int widget) const override
1477 const Station *st = Station::Get(this->window_number);
1478 SetDParam(0, st->index);
1479 SetDParam(1, st->facilities);
1483 * Rebuild the cache for estimated destinations which is used to quickly show the "destination" entries
1484 * even if we actually don't know the destination of a certain packet from just looking at it.
1485 * @param i Cargo to recalculate the cache for.
1487 void RecalcDestinations(CargoID i)
1489 const Station *st = Station::Get(this->window_number);
1490 CargoDataEntry *cargo_entry = cached_destinations.InsertOrRetrieve(i);
1491 cargo_entry->Clear();
1493 const FlowStatMap &flows = st->goods[i].flows;
1494 for (FlowStatMap::const_iterator it = flows.begin(); it != flows.end(); ++it) {
1495 StationID from = it->first;
1496 CargoDataEntry *source_entry = cargo_entry->InsertOrRetrieve(from);
1497 const FlowStat::SharesMap *shares = it->second.GetShares();
1498 uint32 prev_count = 0;
1499 for (FlowStat::SharesMap::const_iterator flow_it = shares->begin(); flow_it != shares->end(); ++flow_it) {
1500 StationID via = flow_it->second;
1501 CargoDataEntry *via_entry = source_entry->InsertOrRetrieve(via);
1502 if (via == this->window_number) {
1503 via_entry->InsertOrRetrieve(via)->Update(flow_it->first - prev_count);
1504 } else {
1505 EstimateDestinations(i, from, via, flow_it->first - prev_count, via_entry);
1507 prev_count = flow_it->first;
1513 * Estimate the amounts of cargo per final destination for a given cargo, source station and next hop and
1514 * save the result as children of the given CargoDataEntry.
1515 * @param cargo ID of the cargo to estimate destinations for.
1516 * @param source Source station of the given batch of cargo.
1517 * @param next Intermediate hop to start the calculation at ("next hop").
1518 * @param count Size of the batch of cargo.
1519 * @param dest CargoDataEntry to save the results in.
1521 void EstimateDestinations(CargoID cargo, StationID source, StationID next, uint count, CargoDataEntry *dest)
1523 if (Station::IsValidID(next) && Station::IsValidID(source)) {
1524 CargoDataEntry tmp;
1525 const FlowStatMap &flowmap = Station::Get(next)->goods[cargo].flows;
1526 FlowStatMap::const_iterator map_it = flowmap.find(source);
1527 if (map_it != flowmap.end()) {
1528 const FlowStat::SharesMap *shares = map_it->second.GetShares();
1529 uint32 prev_count = 0;
1530 for (FlowStat::SharesMap::const_iterator i = shares->begin(); i != shares->end(); ++i) {
1531 tmp.InsertOrRetrieve(i->second)->Update(i->first - prev_count);
1532 prev_count = i->first;
1536 if (tmp.GetCount() == 0) {
1537 dest->InsertOrRetrieve(INVALID_STATION)->Update(count);
1538 } else {
1539 uint sum_estimated = 0;
1540 while (sum_estimated < count) {
1541 for (CargoDataSet::iterator i = tmp.Begin(); i != tmp.End() && sum_estimated < count; ++i) {
1542 CargoDataEntry *child = *i;
1543 uint estimate = DivideApprox(child->GetCount() * count, tmp.GetCount());
1544 if (estimate == 0) estimate = 1;
1546 sum_estimated += estimate;
1547 if (sum_estimated > count) {
1548 estimate -= sum_estimated - count;
1549 sum_estimated = count;
1552 if (estimate > 0) {
1553 if (child->GetStation() == next) {
1554 dest->InsertOrRetrieve(next)->Update(estimate);
1555 } else {
1556 EstimateDestinations(cargo, source, child->GetStation(), estimate, dest);
1563 } else {
1564 dest->InsertOrRetrieve(INVALID_STATION)->Update(count);
1569 * Build up the cargo view for PLANNED mode and a specific cargo.
1570 * @param i Cargo to show.
1571 * @param flows The current station's flows for that cargo.
1572 * @param cargo The CargoDataEntry to save the results in.
1574 void BuildFlowList(CargoID i, const FlowStatMap &flows, CargoDataEntry *cargo)
1576 const CargoDataEntry *source_dest = this->cached_destinations.Retrieve(i);
1577 for (FlowStatMap::const_iterator it = flows.begin(); it != flows.end(); ++it) {
1578 StationID from = it->first;
1579 const CargoDataEntry *source_entry = source_dest->Retrieve(from);
1580 const FlowStat::SharesMap *shares = it->second.GetShares();
1581 for (FlowStat::SharesMap::const_iterator flow_it = shares->begin(); flow_it != shares->end(); ++flow_it) {
1582 const CargoDataEntry *via_entry = source_entry->Retrieve(flow_it->second);
1583 for (CargoDataSet::iterator dest_it = via_entry->Begin(); dest_it != via_entry->End(); ++dest_it) {
1584 CargoDataEntry *dest_entry = *dest_it;
1585 ShowCargo(cargo, i, from, flow_it->second, dest_entry->GetStation(), dest_entry->GetCount());
1592 * Build up the cargo view for WAITING mode and a specific cargo.
1593 * @param i Cargo to show.
1594 * @param packets The current station's cargo list for that cargo.
1595 * @param cargo The CargoDataEntry to save the result in.
1597 void BuildCargoList(CargoID i, const StationCargoList &packets, CargoDataEntry *cargo)
1599 const CargoDataEntry *source_dest = this->cached_destinations.Retrieve(i);
1600 for (StationCargoList::ConstIterator it = packets.Packets()->begin(); it != packets.Packets()->end(); it++) {
1601 const CargoPacket *cp = *it;
1602 StationID next = it.GetKey();
1604 const CargoDataEntry *source_entry = source_dest->Retrieve(cp->SourceStation());
1605 if (source_entry == nullptr) {
1606 this->ShowCargo(cargo, i, cp->SourceStation(), next, INVALID_STATION, cp->Count());
1607 continue;
1610 const CargoDataEntry *via_entry = source_entry->Retrieve(next);
1611 if (via_entry == nullptr) {
1612 this->ShowCargo(cargo, i, cp->SourceStation(), next, INVALID_STATION, cp->Count());
1613 continue;
1616 for (CargoDataSet::iterator dest_it = via_entry->Begin(); dest_it != via_entry->End(); ++dest_it) {
1617 CargoDataEntry *dest_entry = *dest_it;
1618 uint val = DivideApprox(cp->Count() * dest_entry->GetCount(), via_entry->GetCount());
1619 this->ShowCargo(cargo, i, cp->SourceStation(), next, dest_entry->GetStation(), val);
1622 this->ShowCargo(cargo, i, NEW_STATION, NEW_STATION, NEW_STATION, packets.ReservedCount());
1626 * Build up the cargo view for all cargoes.
1627 * @param cargo The root cargo entry to save all results in.
1628 * @param st The station to calculate the cargo view from.
1630 void BuildCargoList(CargoDataEntry *cargo, const Station *st)
1632 for (CargoID i = 0; i < NUM_CARGO; i++) {
1634 if (this->cached_destinations.Retrieve(i) == nullptr) {
1635 this->RecalcDestinations(i);
1638 if (this->current_mode == MODE_WAITING) {
1639 this->BuildCargoList(i, st->goods[i].cargo, cargo);
1640 } else {
1641 this->BuildFlowList(i, st->goods[i].flows, cargo);
1647 * Mark a specific row, characterized by its CargoDataEntry, as expanded.
1648 * @param data The row to be marked as expanded.
1650 void SetDisplayedRow(const CargoDataEntry *data)
1652 std::list<StationID> stations;
1653 const CargoDataEntry *parent = data->GetParent();
1654 if (parent->GetParent() == nullptr) {
1655 this->displayed_rows.push_back(RowDisplay(&this->expanded_rows, data->GetCargo()));
1656 return;
1659 StationID next = data->GetStation();
1660 while (parent->GetParent()->GetParent() != nullptr) {
1661 stations.push_back(parent->GetStation());
1662 parent = parent->GetParent();
1665 CargoID cargo = parent->GetCargo();
1666 CargoDataEntry *filter = this->expanded_rows.Retrieve(cargo);
1667 while (!stations.empty()) {
1668 filter = filter->Retrieve(stations.back());
1669 stations.pop_back();
1672 this->displayed_rows.push_back(RowDisplay(filter, next));
1676 * Select the correct string for an entry referring to the specified station.
1677 * @param station Station the entry is showing cargo for.
1678 * @param here String to be shown if the entry refers to the same station as this station GUI belongs to.
1679 * @param other_station String to be shown if the entry refers to a specific other station.
1680 * @param any String to be shown if the entry refers to "any station".
1681 * @return One of the three given strings or STR_STATION_VIEW_RESERVED, depending on what station the entry refers to.
1683 StringID GetEntryString(StationID station, StringID here, StringID other_station, StringID any)
1685 if (station == this->window_number) {
1686 return here;
1687 } else if (station == INVALID_STATION) {
1688 return any;
1689 } else if (station == NEW_STATION) {
1690 return STR_STATION_VIEW_RESERVED;
1691 } else {
1692 SetDParam(2, station);
1693 return other_station;
1698 * Determine if we need to show the special "non-stop" string.
1699 * @param cd Entry we are going to show.
1700 * @param station Station the entry refers to.
1701 * @param column The "column" the entry will be shown in.
1702 * @return either STR_STATION_VIEW_VIA or STR_STATION_VIEW_NONSTOP.
1704 StringID SearchNonStop(CargoDataEntry *cd, StationID station, int column)
1706 CargoDataEntry *parent = cd->GetParent();
1707 for (int i = column - 1; i > 0; --i) {
1708 if (this->groupings[i] == GR_DESTINATION) {
1709 if (parent->GetStation() == station) {
1710 return STR_STATION_VIEW_NONSTOP;
1711 } else {
1712 return STR_STATION_VIEW_VIA;
1715 parent = parent->GetParent();
1718 if (this->groupings[column + 1] == GR_DESTINATION) {
1719 CargoDataSet::iterator begin = cd->Begin();
1720 CargoDataSet::iterator end = cd->End();
1721 if (begin != end && ++(cd->Begin()) == end && (*(begin))->GetStation() == station) {
1722 return STR_STATION_VIEW_NONSTOP;
1723 } else {
1724 return STR_STATION_VIEW_VIA;
1728 return STR_STATION_VIEW_VIA;
1732 * Draw the given cargo entries in the station GUI.
1733 * @param entry Root entry for all cargo to be drawn.
1734 * @param r Screen rectangle to draw into.
1735 * @param pos Current row to be drawn to (counted down from 0 to -maxrows, same as vscroll->GetPosition()).
1736 * @param maxrows Maximum row to be drawn.
1737 * @param column Current "column" being drawn.
1738 * @param cargo Current cargo being drawn (if cargo column has been passed).
1739 * @return row (in "pos" counting) after the one we have last drawn to.
1741 int DrawEntries(CargoDataEntry *entry, Rect &r, int pos, int maxrows, int column, CargoID cargo = CT_INVALID)
1743 if (this->sortings[column] == ST_AS_GROUPING) {
1744 if (this->groupings[column] != GR_CARGO) {
1745 entry->Resort(ST_STATION_STRING, this->sort_orders[column]);
1747 } else {
1748 entry->Resort(ST_COUNT, this->sort_orders[column]);
1750 for (CargoDataSet::iterator i = entry->Begin(); i != entry->End(); ++i) {
1751 CargoDataEntry *cd = *i;
1753 Grouping grouping = this->groupings[column];
1754 if (grouping == GR_CARGO) cargo = cd->GetCargo();
1755 bool auto_distributed = _settings_game.linkgraph.GetDistributionType(cargo) != DT_MANUAL;
1757 if (pos > -maxrows && pos <= 0) {
1758 StringID str = STR_EMPTY;
1759 int y = r.top + WD_FRAMERECT_TOP - pos * FONT_HEIGHT_NORMAL;
1760 SetDParam(0, cargo);
1761 SetDParam(1, cd->GetCount());
1763 if (this->groupings[column] == GR_CARGO) {
1764 str = STR_STATION_VIEW_WAITING_CARGO;
1765 DrawCargoIcons(cd->GetCargo(), cd->GetCount(), r.left + WD_FRAMERECT_LEFT + this->expand_shrink_width, r.right - WD_FRAMERECT_RIGHT - this->expand_shrink_width, y);
1766 } else {
1767 if (!auto_distributed) grouping = GR_SOURCE;
1768 StationID station = cd->GetStation();
1770 switch (grouping) {
1771 case GR_SOURCE:
1772 str = this->GetEntryString(station, STR_STATION_VIEW_FROM_HERE, STR_STATION_VIEW_FROM, STR_STATION_VIEW_FROM_ANY);
1773 break;
1774 case GR_NEXT:
1775 str = this->GetEntryString(station, STR_STATION_VIEW_VIA_HERE, STR_STATION_VIEW_VIA, STR_STATION_VIEW_VIA_ANY);
1776 if (str == STR_STATION_VIEW_VIA) str = this->SearchNonStop(cd, station, column);
1777 break;
1778 case GR_DESTINATION:
1779 str = this->GetEntryString(station, STR_STATION_VIEW_TO_HERE, STR_STATION_VIEW_TO, STR_STATION_VIEW_TO_ANY);
1780 break;
1781 default:
1782 NOT_REACHED();
1784 if (pos == -this->scroll_to_row && Station::IsValidID(station)) {
1785 ScrollMainWindowToTile(Station::Get(station)->xy);
1789 bool rtl = _current_text_dir == TD_RTL;
1790 int text_left = rtl ? r.left + this->expand_shrink_width : r.left + WD_FRAMERECT_LEFT + column * this->expand_shrink_width;
1791 int text_right = rtl ? r.right - WD_FRAMERECT_LEFT - column * this->expand_shrink_width : r.right - this->expand_shrink_width;
1792 int shrink_left = rtl ? r.left + WD_FRAMERECT_LEFT : r.right - this->expand_shrink_width + WD_FRAMERECT_LEFT;
1793 int shrink_right = rtl ? r.left + this->expand_shrink_width - WD_FRAMERECT_RIGHT : r.right - WD_FRAMERECT_RIGHT;
1795 DrawString(text_left, text_right, y, str);
1797 if (column < NUM_COLUMNS - 1) {
1798 const char *sym = nullptr;
1799 if (cd->GetNumChildren() > 0) {
1800 sym = "-";
1801 } else if (auto_distributed && str != STR_STATION_VIEW_RESERVED) {
1802 sym = "+";
1803 } else {
1804 /* Only draw '+' if there is something to be shown. */
1805 const StationCargoList &list = Station::Get(this->window_number)->goods[cargo].cargo;
1806 if (grouping == GR_CARGO && (list.ReservedCount() > 0 || cd->HasTransfers())) {
1807 sym = "+";
1810 if (sym) DrawString(shrink_left, shrink_right, y, sym, TC_YELLOW);
1812 this->SetDisplayedRow(cd);
1814 --pos;
1815 if (auto_distributed || column == 0) {
1816 pos = this->DrawEntries(cd, r, pos, maxrows, column + 1, cargo);
1819 return pos;
1823 * Draw accepted cargo in the #WID_SV_ACCEPT_RATING_LIST widget.
1824 * @param r Rectangle of the widget.
1825 * @return Number of lines needed for drawing the accepted cargo.
1827 int DrawAcceptedCargo(const Rect &r) const
1829 const Station *st = Station::Get(this->window_number);
1831 CargoTypes cargo_mask = 0;
1832 for (CargoID i = 0; i < NUM_CARGO; i++) {
1833 if (HasBit(st->goods[i].status, GoodsEntry::GES_ACCEPTANCE)) SetBit(cargo_mask, i);
1835 SetDParam(0, cargo_mask);
1836 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);
1837 return CeilDiv(bottom - r.top - WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL);
1841 * Draw cargo ratings in the #WID_SV_ACCEPT_RATING_LIST widget.
1842 * @param r Rectangle of the widget.
1843 * @return Number of lines needed for drawing the cargo ratings.
1845 int DrawCargoRatings(const Rect &r) const
1847 const Station *st = Station::Get(this->window_number);
1848 int y = r.top + WD_FRAMERECT_TOP;
1850 if (st->town->exclusive_counter > 0) {
1851 SetDParam(0, st->town->exclusivity);
1852 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);
1853 y += WD_PAR_VSEP_WIDE;
1856 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_VIEW_SUPPLY_RATINGS_TITLE);
1857 y += FONT_HEIGHT_NORMAL;
1859 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
1860 const GoodsEntry *ge = &st->goods[cs->Index()];
1861 if (!ge->HasRating()) continue;
1863 const LinkGraph *lg = LinkGraph::GetIfValid(ge->link_graph);
1864 SetDParam(0, cs->name);
1865 SetDParam(1, lg != nullptr ? lg->Monthly((*lg)[ge->node].Supply()) : 0);
1866 SetDParam(2, STR_CARGO_RATING_APPALLING + (ge->rating >> 5));
1867 SetDParam(3, ToPercent8(ge->rating));
1868 DrawString(r.left + WD_FRAMERECT_LEFT + 6, r.right - WD_FRAMERECT_RIGHT - 6, y, STR_STATION_VIEW_CARGO_SUPPLY_RATING);
1869 y += FONT_HEIGHT_NORMAL;
1871 return CeilDiv(y - r.top - WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL);
1875 * Expand or collapse a specific row.
1876 * @param filter Parent of the row.
1877 * @param next ID pointing to the row.
1879 template<class Tid>
1880 void HandleCargoWaitingClick(CargoDataEntry *filter, Tid next)
1882 if (filter->Retrieve(next) != nullptr) {
1883 filter->Remove(next);
1884 } else {
1885 filter->InsertOrRetrieve(next);
1890 * Handle a click on a specific row in the cargo view.
1891 * @param row Row being clicked.
1893 void HandleCargoWaitingClick(int row)
1895 if (row < 0 || (uint)row >= this->displayed_rows.size()) return;
1896 if (_ctrl_pressed) {
1897 this->scroll_to_row = row;
1898 } else {
1899 RowDisplay &display = this->displayed_rows[row];
1900 if (display.filter == &this->expanded_rows) {
1901 this->HandleCargoWaitingClick<CargoID>(display.filter, display.next_cargo);
1902 } else {
1903 this->HandleCargoWaitingClick<StationID>(display.filter, display.next_station);
1906 this->SetWidgetDirty(WID_SV_WAITING);
1909 void OnClick(Point pt, int widget, int click_count) override
1911 switch (widget) {
1912 case WID_SV_WAITING:
1913 this->HandleCargoWaitingClick(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_SV_WAITING, WD_FRAMERECT_TOP) - this->vscroll->GetPosition());
1914 break;
1916 case WID_SV_CATCHMENT:
1917 SetViewportCatchmentStation(Station::Get(this->window_number), !this->IsWidgetLowered(WID_SV_CATCHMENT));
1918 break;
1920 case WID_SV_LOCATION:
1921 if (_ctrl_pressed) {
1922 ShowExtraViewportWindow(Station::Get(this->window_number)->xy);
1923 } else {
1924 ScrollMainWindowToTile(Station::Get(this->window_number)->xy);
1926 break;
1928 case WID_SV_ACCEPTS_RATINGS: {
1929 /* Swap between 'accepts' and 'ratings' view. */
1930 int height_change;
1931 NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS);
1932 if (this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) {
1933 nwi->SetDataTip(STR_STATION_VIEW_ACCEPTS_BUTTON, STR_STATION_VIEW_ACCEPTS_TOOLTIP); // Switch to accepts view.
1934 height_change = this->rating_lines - this->accepts_lines;
1935 } else {
1936 nwi->SetDataTip(STR_STATION_VIEW_RATINGS_BUTTON, STR_STATION_VIEW_RATINGS_TOOLTIP); // Switch to ratings view.
1937 height_change = this->accepts_lines - this->rating_lines;
1939 this->ReInit(0, height_change * FONT_HEIGHT_NORMAL);
1940 break;
1943 case WID_SV_RENAME:
1944 SetDParam(0, this->window_number);
1945 ShowQueryString(STR_STATION_NAME, STR_STATION_VIEW_RENAME_STATION_CAPTION, MAX_LENGTH_STATION_NAME_CHARS,
1946 this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
1947 break;
1949 case WID_SV_CLOSE_AIRPORT:
1950 DoCommandP(0, this->window_number, 0, CMD_OPEN_CLOSE_AIRPORT);
1951 break;
1953 case WID_SV_TRAINS: // Show list of scheduled trains to this station
1954 case WID_SV_ROADVEHS: // Show list of scheduled road-vehicles to this station
1955 case WID_SV_SHIPS: // Show list of scheduled ships to this station
1956 case WID_SV_PLANES: { // Show list of scheduled aircraft to this station
1957 Owner owner = Station::Get(this->window_number)->owner;
1958 ShowVehicleListWindow(owner, (VehicleType)(widget - WID_SV_TRAINS), (StationID)this->window_number);
1959 break;
1962 case WID_SV_SORT_BY: {
1963 /* The initial selection is composed of current mode and
1964 * sorting criteria for columns 1, 2, and 3. Column 0 is always
1965 * sorted by cargo ID. The others can theoretically be sorted
1966 * by different things but there is no UI for that. */
1967 ShowDropDownMenu(this, _sort_names,
1968 this->current_mode * 2 + (this->sortings[1] == ST_COUNT ? 1 : 0),
1969 WID_SV_SORT_BY, 0, 0);
1970 break;
1973 case WID_SV_GROUP_BY: {
1974 ShowDropDownMenu(this, _group_names, this->grouping_index, WID_SV_GROUP_BY, 0, 0);
1975 break;
1978 case WID_SV_SORT_ORDER: { // flip sorting method asc/desc
1979 this->SelectSortOrder(this->sort_orders[1] == SO_ASCENDING ? SO_DESCENDING : SO_ASCENDING);
1980 this->SetTimeout();
1981 this->LowerWidget(WID_SV_SORT_ORDER);
1982 break;
1988 * Select a new sort order for the cargo view.
1989 * @param order New sort order.
1991 void SelectSortOrder(SortOrder order)
1993 this->sort_orders[1] = this->sort_orders[2] = this->sort_orders[3] = order;
1994 _settings_client.gui.station_gui_sort_order = this->sort_orders[1];
1995 this->SetDirty();
1999 * Select a new sort criterium for the cargo view.
2000 * @param index Row being selected in the sort criteria drop down.
2002 void SelectSortBy(int index)
2004 _settings_client.gui.station_gui_sort_by = index;
2005 switch (_sort_names[index]) {
2006 case STR_STATION_VIEW_WAITING_STATION:
2007 this->current_mode = MODE_WAITING;
2008 this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_AS_GROUPING;
2009 break;
2010 case STR_STATION_VIEW_WAITING_AMOUNT:
2011 this->current_mode = MODE_WAITING;
2012 this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_COUNT;
2013 break;
2014 case STR_STATION_VIEW_PLANNED_STATION:
2015 this->current_mode = MODE_PLANNED;
2016 this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_AS_GROUPING;
2017 break;
2018 case STR_STATION_VIEW_PLANNED_AMOUNT:
2019 this->current_mode = MODE_PLANNED;
2020 this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_COUNT;
2021 break;
2022 default:
2023 NOT_REACHED();
2025 /* Display the current sort variant */
2026 this->GetWidget<NWidgetCore>(WID_SV_SORT_BY)->widget_data = _sort_names[index];
2027 this->SetDirty();
2031 * Select a new grouping mode for the cargo view.
2032 * @param index Row being selected in the grouping drop down.
2034 void SelectGroupBy(int index)
2036 this->grouping_index = index;
2037 _settings_client.gui.station_gui_group_order = index;
2038 this->GetWidget<NWidgetCore>(WID_SV_GROUP_BY)->widget_data = _group_names[index];
2039 switch (_group_names[index]) {
2040 case STR_STATION_VIEW_GROUP_S_V_D:
2041 this->groupings[1] = GR_SOURCE;
2042 this->groupings[2] = GR_NEXT;
2043 this->groupings[3] = GR_DESTINATION;
2044 break;
2045 case STR_STATION_VIEW_GROUP_S_D_V:
2046 this->groupings[1] = GR_SOURCE;
2047 this->groupings[2] = GR_DESTINATION;
2048 this->groupings[3] = GR_NEXT;
2049 break;
2050 case STR_STATION_VIEW_GROUP_V_S_D:
2051 this->groupings[1] = GR_NEXT;
2052 this->groupings[2] = GR_SOURCE;
2053 this->groupings[3] = GR_DESTINATION;
2054 break;
2055 case STR_STATION_VIEW_GROUP_V_D_S:
2056 this->groupings[1] = GR_NEXT;
2057 this->groupings[2] = GR_DESTINATION;
2058 this->groupings[3] = GR_SOURCE;
2059 break;
2060 case STR_STATION_VIEW_GROUP_D_S_V:
2061 this->groupings[1] = GR_DESTINATION;
2062 this->groupings[2] = GR_SOURCE;
2063 this->groupings[3] = GR_NEXT;
2064 break;
2065 case STR_STATION_VIEW_GROUP_D_V_S:
2066 this->groupings[1] = GR_DESTINATION;
2067 this->groupings[2] = GR_NEXT;
2068 this->groupings[3] = GR_SOURCE;
2069 break;
2071 this->SetDirty();
2074 void OnDropdownSelect(int widget, int index) override
2076 if (widget == WID_SV_SORT_BY) {
2077 this->SelectSortBy(index);
2078 } else {
2079 this->SelectGroupBy(index);
2083 void OnQueryTextFinished(char *str) override
2085 if (str == nullptr) return;
2087 DoCommandP(0, this->window_number, 0, CMD_RENAME_STATION | CMD_MSG(STR_ERROR_CAN_T_RENAME_STATION), nullptr, str);
2090 void OnResize() override
2092 this->vscroll->SetCapacityFromWidget(this, WID_SV_WAITING, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
2096 * Some data on this window has become invalid. Invalidate the cache for the given cargo if necessary.
2097 * @param data Information about the changed data. If it's a valid cargo ID, invalidate the cargo data.
2098 * @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.
2100 void OnInvalidateData(int data = 0, bool gui_scope = true) override
2102 if (gui_scope) {
2103 if (data >= 0 && data < NUM_CARGO) {
2104 this->cached_destinations.Remove((CargoID)data);
2105 } else {
2106 this->ReInit();
2112 const StringID StationViewWindow::_sort_names[] = {
2113 STR_STATION_VIEW_WAITING_STATION,
2114 STR_STATION_VIEW_WAITING_AMOUNT,
2115 STR_STATION_VIEW_PLANNED_STATION,
2116 STR_STATION_VIEW_PLANNED_AMOUNT,
2117 INVALID_STRING_ID
2120 const StringID StationViewWindow::_group_names[] = {
2121 STR_STATION_VIEW_GROUP_S_V_D,
2122 STR_STATION_VIEW_GROUP_S_D_V,
2123 STR_STATION_VIEW_GROUP_V_S_D,
2124 STR_STATION_VIEW_GROUP_V_D_S,
2125 STR_STATION_VIEW_GROUP_D_S_V,
2126 STR_STATION_VIEW_GROUP_D_V_S,
2127 INVALID_STRING_ID
2130 static WindowDesc _station_view_desc(
2131 WDP_AUTO, "view_station", 249, 117,
2132 WC_STATION_VIEW, WC_NONE,
2134 _nested_station_view_widgets, lengthof(_nested_station_view_widgets)
2138 * Opens StationViewWindow for given station
2140 * @param station station which window should be opened
2142 void ShowStationViewWindow(StationID station)
2144 AllocateWindowDescFront<StationViewWindow>(&_station_view_desc, station);
2147 /** Struct containing TileIndex and StationID */
2148 struct TileAndStation {
2149 TileIndex tile; ///< TileIndex
2150 StationID station; ///< StationID
2153 static std::vector<TileAndStation> _deleted_stations_nearby;
2154 static std::vector<StationID> _stations_nearby_list;
2157 * Add station on this tile to _stations_nearby_list if it's fully within the
2158 * station spread.
2159 * @param tile Tile just being checked
2160 * @param user_data Pointer to TileArea context
2161 * @tparam T the type of station to look for
2163 template <class T>
2164 static bool AddNearbyStation(TileIndex tile, void *user_data)
2166 TileArea *ctx = (TileArea *)user_data;
2168 /* First check if there were deleted stations here */
2169 for (uint i = 0; i < _deleted_stations_nearby.size(); i++) {
2170 auto ts = _deleted_stations_nearby.begin() + i;
2171 if (ts->tile == tile) {
2172 _stations_nearby_list.push_back(_deleted_stations_nearby[i].station);
2173 _deleted_stations_nearby.erase(ts);
2174 i--;
2178 /* Check if own station and if we stay within station spread */
2179 if (!IsTileType(tile, MP_STATION)) return false;
2181 StationID sid = GetStationIndex(tile);
2183 /* This station is (likely) a waypoint */
2184 if (!T::IsValidID(sid)) return false;
2186 T *st = T::Get(sid);
2187 if (st->owner != _local_company || std::find(_stations_nearby_list.begin(), _stations_nearby_list.end(), sid) != _stations_nearby_list.end()) return false;
2189 if (st->rect.BeforeAddRect(ctx->tile, ctx->w, ctx->h, StationRect::ADD_TEST).Succeeded()) {
2190 _stations_nearby_list.push_back(sid);
2193 return false; // We want to include *all* nearby stations
2197 * Circulate around the to-be-built station to find stations we could join.
2198 * Make sure that only stations are returned where joining wouldn't exceed
2199 * station spread and are our own station.
2200 * @param ta Base tile area of the to-be-built station
2201 * @param distant_join Search for adjacent stations (false) or stations fully
2202 * within station spread
2203 * @tparam T the type of station to look for
2205 template <class T>
2206 static const T *FindStationsNearby(TileArea ta, bool distant_join)
2208 TileArea ctx = ta;
2210 _stations_nearby_list.clear();
2211 _deleted_stations_nearby.clear();
2213 /* Check the inside, to return, if we sit on another station */
2214 for (TileIndex t : ta) {
2215 if (t < MapSize() && IsTileType(t, MP_STATION) && T::IsValidID(GetStationIndex(t))) return T::GetByTile(t);
2218 /* Look for deleted stations */
2219 for (const BaseStation *st : BaseStation::Iterate()) {
2220 if (T::IsExpected(st) && !st->IsInUse() && st->owner == _local_company) {
2221 /* Include only within station spread (yes, it is strictly less than) */
2222 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) {
2223 _deleted_stations_nearby.push_back({st->xy, st->index});
2225 /* Add the station when it's within where we're going to build */
2226 if (IsInsideBS(TileX(st->xy), TileX(ctx.tile), ctx.w) &&
2227 IsInsideBS(TileY(st->xy), TileY(ctx.tile), ctx.h)) {
2228 AddNearbyStation<T>(st->xy, &ctx);
2234 /* Only search tiles where we have a chance to stay within the station spread.
2235 * The complete check needs to be done in the callback as we don't know the
2236 * extent of the found station, yet. */
2237 if (distant_join && std::min(ta.w, ta.h) >= _settings_game.station.station_spread) return nullptr;
2238 uint max_dist = distant_join ? _settings_game.station.station_spread - std::min(ta.w, ta.h) : 1;
2240 TileIndex tile = TileAddByDir(ctx.tile, DIR_N);
2241 CircularTileSearch(&tile, max_dist, ta.w, ta.h, AddNearbyStation<T>, &ctx);
2243 return nullptr;
2246 static const NWidgetPart _nested_select_station_widgets[] = {
2247 NWidget(NWID_HORIZONTAL),
2248 NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
2249 NWidget(WWT_CAPTION, COLOUR_DARK_GREEN, WID_JS_CAPTION), SetDataTip(STR_JOIN_STATION_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2250 NWidget(WWT_DEFSIZEBOX, COLOUR_DARK_GREEN),
2251 EndContainer(),
2252 NWidget(NWID_HORIZONTAL),
2253 NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_JS_PANEL), SetResize(1, 0), SetScrollbar(WID_JS_SCROLLBAR), EndContainer(),
2254 NWidget(NWID_VERTICAL),
2255 NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, WID_JS_SCROLLBAR),
2256 NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
2257 EndContainer(),
2258 EndContainer(),
2262 * Window for selecting stations/waypoints to (distant) join to.
2263 * @tparam T The type of station to join with
2265 template <class T>
2266 struct SelectStationWindow : Window {
2267 CommandContainer select_station_cmd; ///< Command to build new station
2268 TileArea area; ///< Location of new station
2269 Scrollbar *vscroll;
2271 SelectStationWindow(WindowDesc *desc, const CommandContainer &cmd, TileArea ta) :
2272 Window(desc),
2273 select_station_cmd(cmd),
2274 area(ta)
2276 this->CreateNestedTree();
2277 this->vscroll = this->GetScrollbar(WID_JS_SCROLLBAR);
2278 this->GetWidget<NWidgetCore>(WID_JS_CAPTION)->widget_data = T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_JOIN_WAYPOINT_CAPTION : STR_JOIN_STATION_CAPTION;
2279 this->FinishInitNested(0);
2280 this->OnInvalidateData(0);
2282 _thd.freeze = true;
2285 void Close() override
2287 if (_settings_client.gui.station_show_coverage) SetViewportCatchmentStation(nullptr, true);
2289 _thd.freeze = false;
2290 this->Window::Close();
2293 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
2295 if (widget != WID_JS_PANEL) return;
2297 /* Determine the widest string */
2298 Dimension d = GetStringBoundingBox(T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_JOIN_WAYPOINT_CREATE_SPLITTED_WAYPOINT : STR_JOIN_STATION_CREATE_SPLITTED_STATION);
2299 for (uint i = 0; i < _stations_nearby_list.size(); i++) {
2300 const T *st = T::Get(_stations_nearby_list[i]);
2301 SetDParam(0, st->index);
2302 SetDParam(1, st->facilities);
2303 d = maxdim(d, GetStringBoundingBox(T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_STATION_LIST_WAYPOINT : STR_STATION_LIST_STATION));
2306 resize->height = d.height;
2307 d.height *= 5;
2308 d.width += WD_FRAMERECT_RIGHT + WD_FRAMERECT_LEFT;
2309 d.height += WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
2310 *size = d;
2313 void DrawWidget(const Rect &r, int widget) const override
2315 if (widget != WID_JS_PANEL) return;
2317 uint y = r.top + WD_FRAMERECT_TOP;
2318 if (this->vscroll->GetPosition() == 0) {
2319 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);
2320 y += this->resize.step_height;
2323 for (uint i = std::max<uint>(1, this->vscroll->GetPosition()); i <= _stations_nearby_list.size(); ++i, y += this->resize.step_height) {
2324 /* Don't draw anything if it extends past the end of the window. */
2325 if (i - this->vscroll->GetPosition() >= this->vscroll->GetCapacity()) break;
2327 const T *st = T::Get(_stations_nearby_list[i - 1]);
2328 SetDParam(0, st->index);
2329 SetDParam(1, st->facilities);
2330 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);
2334 void OnClick(Point pt, int widget, int click_count) override
2336 if (widget != WID_JS_PANEL) return;
2338 uint st_index = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_JS_PANEL, WD_FRAMERECT_TOP);
2339 bool distant_join = (st_index > 0);
2340 if (distant_join) st_index--;
2342 if (distant_join && st_index >= _stations_nearby_list.size()) return;
2344 /* Insert station to be joined into stored command */
2345 SB(this->select_station_cmd.p2, 16, 16,
2346 (distant_join ? _stations_nearby_list[st_index] : NEW_STATION));
2348 /* Execute stored Command */
2349 DoCommandP(&this->select_station_cmd);
2351 /* Close Window; this might cause double frees! */
2352 CloseWindowById(WC_SELECT_STATION, 0);
2355 void OnRealtimeTick(uint delta_ms) override
2357 if (_thd.dirty & 2) {
2358 _thd.dirty &= ~2;
2359 this->SetDirty();
2363 void OnResize() override
2365 this->vscroll->SetCapacityFromWidget(this, WID_JS_PANEL, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
2369 * Some data on this window has become invalid.
2370 * @param data Information about the changed data.
2371 * @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.
2373 void OnInvalidateData(int data = 0, bool gui_scope = true) override
2375 if (!gui_scope) return;
2376 FindStationsNearby<T>(this->area, true);
2377 this->vscroll->SetCount((uint)_stations_nearby_list.size() + 1);
2378 this->SetDirty();
2381 void OnMouseOver(Point pt, int widget) override
2383 if (widget != WID_JS_PANEL || T::EXPECTED_FACIL == FACIL_WAYPOINT) {
2384 SetViewportCatchmentStation(nullptr, true);
2385 return;
2388 /* Show coverage area of station under cursor */
2389 uint st_index = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_JS_PANEL, WD_FRAMERECT_TOP);
2390 if (st_index == 0 || st_index > _stations_nearby_list.size()) {
2391 SetViewportCatchmentStation(nullptr, true);
2392 } else {
2393 st_index--;
2394 SetViewportCatchmentStation(Station::Get(_stations_nearby_list[st_index]), true);
2399 static WindowDesc _select_station_desc(
2400 WDP_AUTO, "build_station_join", 200, 180,
2401 WC_SELECT_STATION, WC_NONE,
2402 WDF_CONSTRUCTION,
2403 _nested_select_station_widgets, lengthof(_nested_select_station_widgets)
2408 * Check whether we need to show the station selection window.
2409 * @param cmd Command to build the station.
2410 * @param ta Tile area of the to-be-built station
2411 * @tparam T the type of station
2412 * @return whether we need to show the station selection window.
2414 template <class T>
2415 static bool StationJoinerNeeded(const CommandContainer &cmd, TileArea ta)
2417 /* Only show selection if distant join is enabled in the settings */
2418 if (!_settings_game.station.distant_join_stations) return false;
2420 /* If a window is already opened and we didn't ctrl-click,
2421 * return true (i.e. just flash the old window) */
2422 Window *selection_window = FindWindowById(WC_SELECT_STATION, 0);
2423 if (selection_window != nullptr) {
2424 /* Abort current distant-join and start new one */
2425 selection_window->Close();
2426 UpdateTileSelection();
2429 /* only show the popup, if we press ctrl */
2430 if (!_ctrl_pressed) return false;
2432 /* Now check if we could build there */
2433 if (DoCommand(&cmd, CommandFlagsToDCFlags(GetCommandFlags(cmd.cmd))).Failed()) return false;
2435 /* Test for adjacent station or station below selection.
2436 * If adjacent-stations is disabled and we are building next to a station, do not show the selection window.
2437 * but join the other station immediately. */
2438 const T *st = FindStationsNearby<T>(ta, false);
2439 return st == nullptr && (_settings_game.station.adjacent_stations || _stations_nearby_list.size() == 0);
2443 * Show the station selection window when needed. If not, build the station.
2444 * @param cmd Command to build the station.
2445 * @param ta Area to build the station in
2446 * @tparam the class to find stations for
2448 template <class T>
2449 void ShowSelectBaseStationIfNeeded(const CommandContainer &cmd, TileArea ta)
2451 if (StationJoinerNeeded<T>(cmd, ta)) {
2452 if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
2453 new SelectStationWindow<T>(&_select_station_desc, cmd, ta);
2454 } else {
2455 DoCommandP(&cmd);
2460 * Show the station selection window when needed. If not, build the station.
2461 * @param cmd Command to build the station.
2462 * @param ta Area to build the station in
2464 void ShowSelectStationIfNeeded(const CommandContainer &cmd, TileArea ta)
2466 ShowSelectBaseStationIfNeeded<Station>(cmd, ta);
2470 * Show the waypoint selection window when needed. If not, build the waypoint.
2471 * @param cmd Command to build the waypoint.
2472 * @param ta Area to build the waypoint in
2474 void ShowSelectWaypointIfNeeded(const CommandContainer &cmd, TileArea ta)
2476 ShowSelectBaseStationIfNeeded<Waypoint>(cmd, ta);