Fix: Stopped ships shouldn't block depots (#8578)
[openttd-github.git] / src / station_gui.cpp
blobb4156261bcc9766223422cab312fa32cd4686dfa
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 TILE_AREA_LOOP(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 * @note Each cargo-bar is 16 pixels wide and 6 pixels high
158 * @note Each rating 14 pixels wide and 1 pixel high and is 1 pixel below the cargo-bar
160 static void StationsWndShowStationRating(int left, int right, int y, CargoID type, uint amount, byte rating)
162 static const uint units_full = 576; ///< number of units to show station as 'full'
163 static const uint rating_full = 224; ///< rating needed so it is shown as 'full'
165 const CargoSpec *cs = CargoSpec::Get(type);
166 if (!cs->IsValid()) return;
168 int colour = cs->rating_colour;
169 TextColour tc = GetContrastColour(colour);
170 uint w = (std::min(amount, units_full) + 5) / 36;
172 int height = GetCharacterHeight(FS_SMALL);
174 /* Draw total cargo (limited) on station (fits into 16 pixels) */
175 if (w != 0) GfxFillRect(left, y, left + w - 1, y + height, colour);
177 /* Draw a one pixel-wide bar of additional cargo meter, useful
178 * for stations with only a small amount (<=30) */
179 if (w == 0) {
180 uint rest = amount / 5;
181 if (rest != 0) {
182 w += left;
183 GfxFillRect(w, y + height - rest, w, y + height, colour);
187 DrawString(left + 1, right, y, cs->abbrev, tc);
189 /* Draw green/red ratings bar (fits into 14 pixels) */
190 y += height + 2;
191 GfxFillRect(left + 1, y, left + 14, y, PC_RED);
192 rating = std::min<uint>(rating, rating_full) / 16;
193 if (rating != 0) GfxFillRect(left + 1, y, left + rating, y, PC_GREEN);
196 typedef GUIList<const Station*> GUIStationList;
199 * The list of stations per company.
201 class CompanyStationsWindow : public Window
203 protected:
204 /* Runtime saved values */
205 static Listing last_sorting;
206 static byte facilities; // types of stations of interest
207 static bool include_empty; // whether we should include stations without waiting cargo
208 static const CargoTypes cargo_filter_max;
209 static CargoTypes cargo_filter; // bitmap of cargo types to include
211 /* Constants for sorting stations */
212 static const StringID sorter_names[];
213 static GUIStationList::SortFunction * const sorter_funcs[];
215 GUIStationList stations;
216 Scrollbar *vscroll;
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 %d", 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 CargoID j;
278 FOR_EACH_SET_CARGO_ID(j, cargo_filter) {
279 diff += a->goods[j].cargo.TotalCount() - b->goods[j].cargo.TotalCount();
282 return diff < 0;
285 /** Sort stations by their available waiting cargo */
286 static bool StationWaitingAvailableSorter(const Station * const &a, const Station * const &b)
288 int diff = 0;
290 CargoID j;
291 FOR_EACH_SET_CARGO_ID(j, cargo_filter) {
292 diff += a->goods[j].cargo.AvailableCount() - b->goods[j].cargo.AvailableCount();
295 return diff < 0;
298 /** Sort stations by their rating */
299 static bool StationRatingMaxSorter(const Station * const &a, const Station * const &b)
301 byte maxr1 = 0;
302 byte maxr2 = 0;
304 CargoID j;
305 FOR_EACH_SET_CARGO_ID(j, cargo_filter) {
306 if (a->goods[j].HasRating()) maxr1 = std::max(maxr1, a->goods[j].rating);
307 if (b->goods[j].HasRating()) maxr2 = std::max(maxr2, b->goods[j].rating);
310 return maxr1 < maxr2;
313 /** Sort stations by their rating */
314 static bool StationRatingMinSorter(const Station * const &a, const Station * const &b)
316 byte minr1 = 255;
317 byte minr2 = 255;
319 for (CargoID j = 0; j < NUM_CARGO; j++) {
320 if (!HasBit(cargo_filter, j)) continue;
321 if (a->goods[j].HasRating()) minr1 = std::min(minr1, a->goods[j].rating);
322 if (b->goods[j].HasRating()) minr2 = std::min(minr2, b->goods[j].rating);
325 return minr1 > minr2;
328 /** Sort the stations list */
329 void SortStationsList()
331 if (!this->stations.Sort()) return;
333 /* Set the modified widget dirty */
334 this->SetWidgetDirty(WID_STL_LIST);
337 public:
338 CompanyStationsWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
340 this->stations.SetListing(this->last_sorting);
341 this->stations.SetSortFuncs(this->sorter_funcs);
342 this->stations.ForceRebuild();
343 this->stations.NeedResort();
344 this->SortStationsList();
346 this->CreateNestedTree();
347 this->vscroll = this->GetScrollbar(WID_STL_SCROLLBAR);
348 this->FinishInitNested(window_number);
349 this->owner = (Owner)this->window_number;
351 const CargoSpec *cs;
352 FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
353 if (!HasBit(this->cargo_filter, cs->Index())) continue;
354 this->LowerWidget(WID_STL_CARGOSTART + index);
357 if (this->cargo_filter == this->cargo_filter_max) this->cargo_filter = _cargo_mask;
359 for (uint i = 0; i < 5; i++) {
360 if (HasBit(this->facilities, i)) this->LowerWidget(i + WID_STL_TRAIN);
362 this->SetWidgetLoweredState(WID_STL_NOCARGOWAITING, this->include_empty);
364 this->GetWidget<NWidgetCore>(WID_STL_SORTDROPBTN)->widget_data = this->sorter_names[this->stations.SortType()];
367 ~CompanyStationsWindow()
369 this->last_sorting = this->stations.GetListing();
372 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
374 switch (widget) {
375 case WID_STL_SORTBY: {
376 Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
377 d.width += padding.width + Window::SortButtonWidth() * 2; // Doubled since the string is centred and it also looks better.
378 d.height += padding.height;
379 *size = maxdim(*size, d);
380 break;
383 case WID_STL_SORTDROPBTN: {
384 Dimension d = {0, 0};
385 for (int i = 0; this->sorter_names[i] != INVALID_STRING_ID; i++) {
386 d = maxdim(d, GetStringBoundingBox(this->sorter_names[i]));
388 d.width += padding.width;
389 d.height += padding.height;
390 *size = maxdim(*size, d);
391 break;
394 case WID_STL_LIST:
395 resize->height = FONT_HEIGHT_NORMAL;
396 size->height = WD_FRAMERECT_TOP + 5 * resize->height + WD_FRAMERECT_BOTTOM;
397 break;
399 case WID_STL_TRAIN:
400 case WID_STL_TRUCK:
401 case WID_STL_BUS:
402 case WID_STL_AIRPLANE:
403 case WID_STL_SHIP:
404 size->height = std::max<uint>(FONT_HEIGHT_SMALL, 10) + padding.height;
405 break;
407 case WID_STL_CARGOALL:
408 case WID_STL_FACILALL:
409 case WID_STL_NOCARGOWAITING: {
410 Dimension d = GetStringBoundingBox(widget == WID_STL_NOCARGOWAITING ? STR_ABBREV_NONE : STR_ABBREV_ALL);
411 d.width += padding.width + 2;
412 d.height += padding.height;
413 *size = maxdim(*size, d);
414 break;
417 default:
418 if (widget >= WID_STL_CARGOSTART) {
419 Dimension d = GetStringBoundingBox(_sorted_cargo_specs[widget - WID_STL_CARGOSTART]->abbrev);
420 d.width += padding.width + 2;
421 d.height += padding.height;
422 *size = maxdim(*size, d);
424 break;
428 void OnPaint() override
430 this->BuildStationsList((Owner)this->window_number);
431 this->SortStationsList();
433 this->DrawWidgets();
436 void DrawWidget(const Rect &r, int widget) const override
438 switch (widget) {
439 case WID_STL_SORTBY:
440 /* draw arrow pointing up/down for ascending/descending sorting */
441 this->DrawSortButtonState(WID_STL_SORTBY, this->stations.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
442 break;
444 case WID_STL_LIST: {
445 bool rtl = _current_text_dir == TD_RTL;
446 int max = std::min<size_t>(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->stations.size());
447 int y = r.top + WD_FRAMERECT_TOP;
448 for (int i = this->vscroll->GetPosition(); i < max; ++i) { // do until max number of stations of owner
449 const Station *st = this->stations[i];
450 assert(st->xy != INVALID_TILE);
452 /* Do not do the complex check HasStationInUse here, it may be even false
453 * when the order had been removed and the station list hasn't been removed yet */
454 assert(st->owner == owner || st->owner == OWNER_NONE);
456 SetDParam(0, st->index);
457 SetDParam(1, st->facilities);
458 int x = DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_LIST_STATION);
459 x += rtl ? -5 : 5;
461 /* show cargo waiting and station ratings */
462 for (uint j = 0; j < _sorted_standard_cargo_specs_size; j++) {
463 CargoID cid = _sorted_cargo_specs[j]->Index();
464 if (st->goods[cid].cargo.TotalCount() > 0) {
465 /* For RTL we work in exactly the opposite direction. So
466 * decrement the space needed first, then draw to the left
467 * instead of drawing to the left and then incrementing
468 * the space. */
469 if (rtl) {
470 x -= 20;
471 if (x < r.left + WD_FRAMERECT_LEFT) break;
473 StationsWndShowStationRating(x, x + 16, y, cid, st->goods[cid].cargo.TotalCount(), st->goods[cid].rating);
474 if (!rtl) {
475 x += 20;
476 if (x > r.right - WD_FRAMERECT_RIGHT) break;
480 y += FONT_HEIGHT_NORMAL;
483 if (this->vscroll->GetCount() == 0) { // company has no stations
484 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_LIST_NONE);
485 return;
487 break;
490 case WID_STL_NOCARGOWAITING: {
491 int cg_ofst = this->IsWidgetLowered(widget) ? 2 : 1;
492 DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, STR_ABBREV_NONE, TC_BLACK, SA_HOR_CENTER);
493 break;
496 case WID_STL_CARGOALL: {
497 int cg_ofst = this->IsWidgetLowered(widget) ? 2 : 1;
498 DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, STR_ABBREV_ALL, TC_BLACK, SA_HOR_CENTER);
499 break;
502 case WID_STL_FACILALL: {
503 int cg_ofst = this->IsWidgetLowered(widget) ? 2 : 1;
504 DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, STR_ABBREV_ALL, TC_BLACK, SA_HOR_CENTER);
505 break;
508 default:
509 if (widget >= WID_STL_CARGOSTART) {
510 const CargoSpec *cs = _sorted_cargo_specs[widget - WID_STL_CARGOSTART];
511 int cg_ofst = HasBit(this->cargo_filter, cs->Index()) ? 2 : 1;
512 GfxFillRect(r.left + cg_ofst, r.top + cg_ofst, r.right - 2 + cg_ofst, r.bottom - 2 + cg_ofst, cs->rating_colour);
513 TextColour tc = GetContrastColour(cs->rating_colour);
514 DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, cs->abbrev, tc, SA_HOR_CENTER);
516 break;
520 void SetStringParameters(int widget) const override
522 if (widget == WID_STL_CAPTION) {
523 SetDParam(0, this->window_number);
524 SetDParam(1, this->vscroll->GetCount());
528 void OnClick(Point pt, int widget, int click_count) override
530 switch (widget) {
531 case WID_STL_LIST: {
532 uint id_v = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_STL_LIST, 0, FONT_HEIGHT_NORMAL);
533 if (id_v >= this->stations.size()) return; // click out of list bound
535 const Station *st = this->stations[id_v];
536 /* do not check HasStationInUse - it is slow and may be invalid */
537 assert(st->owner == (Owner)this->window_number || st->owner == OWNER_NONE);
539 if (_ctrl_pressed) {
540 ShowExtraViewportWindow(st->xy);
541 } else {
542 ScrollMainWindowToTile(st->xy);
544 break;
547 case WID_STL_TRAIN:
548 case WID_STL_TRUCK:
549 case WID_STL_BUS:
550 case WID_STL_AIRPLANE:
551 case WID_STL_SHIP:
552 if (_ctrl_pressed) {
553 ToggleBit(this->facilities, widget - WID_STL_TRAIN);
554 this->ToggleWidgetLoweredState(widget);
555 } else {
556 uint i;
557 FOR_EACH_SET_BIT(i, this->facilities) {
558 this->RaiseWidget(i + WID_STL_TRAIN);
560 this->facilities = 1 << (widget - WID_STL_TRAIN);
561 this->LowerWidget(widget);
563 this->stations.ForceRebuild();
564 this->SetDirty();
565 break;
567 case WID_STL_FACILALL:
568 for (uint i = WID_STL_TRAIN; i <= WID_STL_SHIP; i++) {
569 this->LowerWidget(i);
572 this->facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK;
573 this->stations.ForceRebuild();
574 this->SetDirty();
575 break;
577 case WID_STL_CARGOALL: {
578 for (uint i = 0; i < _sorted_standard_cargo_specs_size; i++) {
579 this->LowerWidget(WID_STL_CARGOSTART + i);
581 this->LowerWidget(WID_STL_NOCARGOWAITING);
583 this->cargo_filter = _cargo_mask;
584 this->include_empty = true;
585 this->stations.ForceRebuild();
586 this->SetDirty();
587 break;
590 case WID_STL_SORTBY: // flip sorting method asc/desc
591 this->stations.ToggleSortOrder();
592 this->SetDirty();
593 break;
595 case WID_STL_SORTDROPBTN: // select sorting criteria dropdown menu
596 ShowDropDownMenu(this, this->sorter_names, this->stations.SortType(), WID_STL_SORTDROPBTN, 0, 0);
597 break;
599 case WID_STL_NOCARGOWAITING:
600 if (_ctrl_pressed) {
601 this->include_empty = !this->include_empty;
602 this->ToggleWidgetLoweredState(WID_STL_NOCARGOWAITING);
603 } else {
604 for (uint i = 0; i < _sorted_standard_cargo_specs_size; i++) {
605 this->RaiseWidget(WID_STL_CARGOSTART + i);
608 this->cargo_filter = 0;
609 this->include_empty = true;
611 this->LowerWidget(WID_STL_NOCARGOWAITING);
613 this->stations.ForceRebuild();
614 this->SetDirty();
615 break;
617 default:
618 if (widget >= WID_STL_CARGOSTART) { // change cargo_filter
619 /* Determine the selected cargo type */
620 const CargoSpec *cs = _sorted_cargo_specs[widget - WID_STL_CARGOSTART];
622 if (_ctrl_pressed) {
623 ToggleBit(this->cargo_filter, cs->Index());
624 this->ToggleWidgetLoweredState(widget);
625 } else {
626 for (uint i = 0; i < _sorted_standard_cargo_specs_size; i++) {
627 this->RaiseWidget(WID_STL_CARGOSTART + i);
629 this->RaiseWidget(WID_STL_NOCARGOWAITING);
631 this->cargo_filter = 0;
632 this->include_empty = false;
634 SetBit(this->cargo_filter, cs->Index());
635 this->LowerWidget(widget);
637 this->stations.ForceRebuild();
638 this->SetDirty();
640 break;
644 void OnDropdownSelect(int widget, int index) override
646 if (this->stations.SortType() != index) {
647 this->stations.SetSortType(index);
649 /* Display the current sort variant */
650 this->GetWidget<NWidgetCore>(WID_STL_SORTDROPBTN)->widget_data = this->sorter_names[this->stations.SortType()];
652 this->SetDirty();
656 void OnGameTick() override
658 if (this->stations.NeedResort()) {
659 DEBUG(misc, 3, "Periodic rebuild station list company %d", this->window_number);
660 this->SetDirty();
664 void OnResize() override
666 this->vscroll->SetCapacityFromWidget(this, WID_STL_LIST, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
670 * Some data on this window has become invalid.
671 * @param data Information about the changed data.
672 * @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.
674 void OnInvalidateData(int data = 0, bool gui_scope = true) override
676 if (data == 0) {
677 /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
678 this->stations.ForceRebuild();
679 } else {
680 this->stations.ForceResort();
685 Listing CompanyStationsWindow::last_sorting = {false, 0};
686 byte CompanyStationsWindow::facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK;
687 bool CompanyStationsWindow::include_empty = true;
688 const CargoTypes CompanyStationsWindow::cargo_filter_max = ALL_CARGOTYPES;
689 CargoTypes CompanyStationsWindow::cargo_filter = ALL_CARGOTYPES;
691 /* Available station sorting functions */
692 GUIStationList::SortFunction * const CompanyStationsWindow::sorter_funcs[] = {
693 &StationNameSorter,
694 &StationTypeSorter,
695 &StationWaitingTotalSorter,
696 &StationWaitingAvailableSorter,
697 &StationRatingMaxSorter,
698 &StationRatingMinSorter
701 /* Names of the sorting functions */
702 const StringID CompanyStationsWindow::sorter_names[] = {
703 STR_SORT_BY_NAME,
704 STR_SORT_BY_FACILITY,
705 STR_SORT_BY_WAITING_TOTAL,
706 STR_SORT_BY_WAITING_AVAILABLE,
707 STR_SORT_BY_RATING_MAX,
708 STR_SORT_BY_RATING_MIN,
709 INVALID_STRING_ID
713 * Make a horizontal row of cargo buttons, starting at widget #WID_STL_CARGOSTART.
714 * @param biggest_index Pointer to store biggest used widget number of the buttons.
715 * @return Horizontal row.
717 static NWidgetBase *CargoWidgets(int *biggest_index)
719 NWidgetHorizontal *container = new NWidgetHorizontal();
721 for (uint i = 0; i < _sorted_standard_cargo_specs_size; i++) {
722 NWidgetBackground *panel = new NWidgetBackground(WWT_PANEL, COLOUR_GREY, WID_STL_CARGOSTART + i);
723 panel->SetMinimalSize(14, 11);
724 panel->SetResize(0, 0);
725 panel->SetFill(0, 1);
726 panel->SetDataTip(0, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE);
727 container->Add(panel);
729 *biggest_index = WID_STL_CARGOSTART + _sorted_standard_cargo_specs_size;
730 return container;
733 static const NWidgetPart _nested_company_stations_widgets[] = {
734 NWidget(NWID_HORIZONTAL),
735 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
736 NWidget(WWT_CAPTION, COLOUR_GREY, WID_STL_CAPTION), SetDataTip(STR_STATION_LIST_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
737 NWidget(WWT_SHADEBOX, COLOUR_GREY),
738 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
739 NWidget(WWT_STICKYBOX, COLOUR_GREY),
740 EndContainer(),
741 NWidget(NWID_HORIZONTAL),
742 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_STL_TRAIN), SetMinimalSize(14, 11), SetDataTip(STR_TRAIN, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
743 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_STL_TRUCK), SetMinimalSize(14, 11), SetDataTip(STR_LORRY, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
744 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_STL_BUS), SetMinimalSize(14, 11), SetDataTip(STR_BUS, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
745 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_STL_SHIP), SetMinimalSize(14, 11), SetDataTip(STR_SHIP, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
746 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_STL_AIRPLANE), SetMinimalSize(14, 11), SetDataTip(STR_PLANE, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE), SetFill(0, 1),
747 NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_STL_FACILALL), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_SELECT_ALL_FACILITIES), SetFill(0, 1),
748 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(5, 11), SetFill(0, 1), EndContainer(),
749 NWidgetFunction(CargoWidgets),
750 NWidget(WWT_PANEL, COLOUR_GREY, WID_STL_NOCARGOWAITING), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_NO_WAITING_CARGO), SetFill(0, 1), EndContainer(),
751 NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_STL_CARGOALL), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_SELECT_ALL_TYPES), SetFill(0, 1),
752 NWidget(WWT_PANEL, COLOUR_GREY), SetDataTip(0x0, STR_NULL), SetResize(1, 0), SetFill(1, 1), EndContainer(),
753 EndContainer(),
754 NWidget(NWID_HORIZONTAL),
755 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_STL_SORTBY), SetMinimalSize(81, 12), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
756 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_STL_SORTDROPBTN), SetMinimalSize(163, 12), SetDataTip(STR_SORT_BY_NAME, STR_TOOLTIP_SORT_CRITERIA), // widget_data gets overwritten.
757 NWidget(WWT_PANEL, COLOUR_GREY), SetDataTip(0x0, STR_NULL), SetResize(1, 0), SetFill(1, 1), EndContainer(),
758 EndContainer(),
759 NWidget(NWID_HORIZONTAL),
760 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(),
761 NWidget(NWID_VERTICAL),
762 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_STL_SCROLLBAR),
763 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
764 EndContainer(),
765 EndContainer(),
768 static WindowDesc _company_stations_desc(
769 WDP_AUTO, "list_stations", 358, 162,
770 WC_STATION_LIST, WC_NONE,
772 _nested_company_stations_widgets, lengthof(_nested_company_stations_widgets)
776 * Opens window with list of company's stations
778 * @param company whose stations' list show
780 void ShowCompanyStations(CompanyID company)
782 if (!Company::IsValidID(company)) return;
784 AllocateWindowDescFront<CompanyStationsWindow>(&_company_stations_desc, company);
787 static const NWidgetPart _nested_station_view_widgets[] = {
788 NWidget(NWID_HORIZONTAL),
789 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
790 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_SV_RENAME), SetMinimalSize(12, 14), SetDataTip(SPR_RENAME, STR_STATION_VIEW_RENAME_TOOLTIP),
791 NWidget(WWT_CAPTION, COLOUR_GREY, WID_SV_CAPTION), SetDataTip(STR_STATION_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
792 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_SV_LOCATION), SetMinimalSize(12, 14), SetDataTip(SPR_GOTO_LOCATION, STR_STATION_VIEW_CENTER_TOOLTIP),
793 NWidget(WWT_SHADEBOX, COLOUR_GREY),
794 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
795 NWidget(WWT_STICKYBOX, COLOUR_GREY),
796 EndContainer(),
797 NWidget(NWID_HORIZONTAL),
798 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_SV_GROUP), SetMinimalSize(81, 12), SetFill(1, 1), SetDataTip(STR_STATION_VIEW_GROUP, 0x0),
799 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_SV_GROUP_BY), SetMinimalSize(168, 12), SetResize(1, 0), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_GROUP_ORDER),
800 EndContainer(),
801 NWidget(NWID_HORIZONTAL),
802 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_SORT_ORDER), SetMinimalSize(81, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
803 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_SV_SORT_BY), SetMinimalSize(168, 12), SetResize(1, 0), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
804 EndContainer(),
805 NWidget(NWID_HORIZONTAL),
806 NWidget(WWT_PANEL, COLOUR_GREY, WID_SV_WAITING), SetMinimalSize(237, 44), SetResize(1, 10), SetScrollbar(WID_SV_SCROLLBAR), EndContainer(),
807 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_SV_SCROLLBAR),
808 EndContainer(),
809 NWidget(WWT_PANEL, COLOUR_GREY, WID_SV_ACCEPT_RATING_LIST), SetMinimalSize(249, 23), SetResize(1, 0), EndContainer(),
810 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
811 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_ACCEPTS_RATINGS), SetMinimalSize(46, 12), SetResize(1, 0), SetFill(1, 1),
812 SetDataTip(STR_STATION_VIEW_RATINGS_BUTTON, STR_STATION_VIEW_RATINGS_TOOLTIP),
813 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_SV_CLOSE_AIRPORT), SetMinimalSize(45, 12), SetResize(1, 0), SetFill(1, 1),
814 SetDataTip(STR_STATION_VIEW_CLOSE_AIRPORT, STR_STATION_VIEW_CLOSE_AIRPORT_TOOLTIP),
815 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_SV_CATCHMENT), SetMinimalSize(45, 12), SetResize(1, 0), SetFill(1, 1), SetDataTip(STR_BUTTON_CATCHMENT, STR_TOOLTIP_CATCHMENT),
816 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_TRAINS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_TRAIN, STR_STATION_VIEW_SCHEDULED_TRAINS_TOOLTIP),
817 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_ROADVEHS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_LORRY, STR_STATION_VIEW_SCHEDULED_ROAD_VEHICLES_TOOLTIP),
818 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_SHIPS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_SHIP, STR_STATION_VIEW_SCHEDULED_SHIPS_TOOLTIP),
819 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_PLANES), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_PLANE, STR_STATION_VIEW_SCHEDULED_AIRCRAFT_TOOLTIP),
820 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
821 EndContainer(),
825 * Draws icons of waiting cargo in the StationView window
827 * @param i type of cargo
828 * @param waiting number of waiting units
829 * @param left left most coordinate to draw on
830 * @param right right most coordinate to draw on
831 * @param y y coordinate
833 static void DrawCargoIcons(CargoID i, uint waiting, int left, int right, int y)
835 int width = ScaleGUITrad(10);
836 uint num = std::min<uint>((waiting + (width / 2)) / width, (right - left) / width); // maximum is width / 10 icons so it won't overflow
837 if (num == 0) return;
839 SpriteID sprite = CargoSpec::Get(i)->GetCargoIcon();
841 int x = _current_text_dir == TD_RTL ? left : right - num * width;
842 do {
843 DrawSprite(sprite, PAL_NONE, x, y);
844 x += width;
845 } while (--num);
848 enum SortOrder {
849 SO_DESCENDING,
850 SO_ASCENDING
853 class CargoDataEntry;
855 enum CargoSortType {
856 ST_AS_GROUPING, ///< by the same principle the entries are being grouped
857 ST_COUNT, ///< by amount of cargo
858 ST_STATION_STRING, ///< by station name
859 ST_STATION_ID, ///< by station id
860 ST_CARGO_ID, ///< by cargo id
863 class CargoSorter {
864 public:
865 CargoSorter(CargoSortType t = ST_STATION_ID, SortOrder o = SO_ASCENDING) : type(t), order(o) {}
866 CargoSortType GetSortType() {return this->type;}
867 bool operator()(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const;
869 private:
870 CargoSortType type;
871 SortOrder order;
873 template<class Tid>
874 bool SortId(Tid st1, Tid st2) const;
875 bool SortCount(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const;
876 bool SortStation (StationID st1, StationID st2) const;
879 typedef std::set<CargoDataEntry *, CargoSorter> CargoDataSet;
882 * A cargo data entry representing one possible row in the station view window's
883 * top part. Cargo data entries form a tree where each entry can have several
884 * children. Parents keep track of the sums of their childrens' cargo counts.
886 class CargoDataEntry {
887 public:
888 CargoDataEntry();
889 ~CargoDataEntry();
892 * Insert a new child or retrieve an existing child using a station ID as ID.
893 * @param station ID of the station for which an entry shall be created or retrieved
894 * @return a child entry associated with the given station.
896 CargoDataEntry *InsertOrRetrieve(StationID station)
898 return this->InsertOrRetrieve<StationID>(station);
902 * Insert a new child or retrieve an existing child using a cargo ID as ID.
903 * @param cargo ID of the cargo for which an entry shall be created or retrieved
904 * @return a child entry associated with the given cargo.
906 CargoDataEntry *InsertOrRetrieve(CargoID cargo)
908 return this->InsertOrRetrieve<CargoID>(cargo);
911 void Update(uint count);
914 * Remove a child associated with the given station.
915 * @param station ID of the station for which the child should be removed.
917 void Remove(StationID station)
919 CargoDataEntry t(station);
920 this->Remove(&t);
924 * Remove a child associated with the given cargo.
925 * @param cargo ID of the cargo for which the child should be removed.
927 void Remove(CargoID cargo)
929 CargoDataEntry t(cargo);
930 this->Remove(&t);
934 * Retrieve a child for the given station. Return nullptr if it doesn't exist.
935 * @param station ID of the station the child we're looking for is associated with.
936 * @return a child entry for the given station or nullptr.
938 CargoDataEntry *Retrieve(StationID station) const
940 CargoDataEntry t(station);
941 return this->Retrieve(this->children->find(&t));
945 * Retrieve a child for the given cargo. Return nullptr if it doesn't exist.
946 * @param cargo ID of the cargo the child we're looking for is associated with.
947 * @return a child entry for the given cargo or nullptr.
949 CargoDataEntry *Retrieve(CargoID cargo) const
951 CargoDataEntry t(cargo);
952 return this->Retrieve(this->children->find(&t));
955 void Resort(CargoSortType type, SortOrder order);
958 * Get the station ID for this entry.
960 StationID GetStation() const { return this->station; }
963 * Get the cargo ID for this entry.
965 CargoID GetCargo() const { return this->cargo; }
968 * Get the cargo count for this entry.
970 uint GetCount() const { return this->count; }
973 * Get the parent entry for this entry.
975 CargoDataEntry *GetParent() const { return this->parent; }
978 * Get the number of children for this entry.
980 uint GetNumChildren() const { return this->num_children; }
983 * Get an iterator pointing to the begin of the set of children.
985 CargoDataSet::iterator Begin() const { return this->children->begin(); }
988 * Get an iterator pointing to the end of the set of children.
990 CargoDataSet::iterator End() const { return this->children->end(); }
993 * Has this entry transfers.
995 bool HasTransfers() const { return this->transfers; }
998 * Set the transfers state.
1000 void SetTransfers(bool value) { this->transfers = value; }
1002 void Clear();
1003 private:
1005 CargoDataEntry(StationID st, uint c, CargoDataEntry *p);
1006 CargoDataEntry(CargoID car, uint c, CargoDataEntry *p);
1007 CargoDataEntry(StationID st);
1008 CargoDataEntry(CargoID car);
1010 CargoDataEntry *Retrieve(CargoDataSet::iterator i) const;
1012 template<class Tid>
1013 CargoDataEntry *InsertOrRetrieve(Tid s);
1015 void Remove(CargoDataEntry *comp);
1016 void IncrementSize();
1018 CargoDataEntry *parent; ///< the parent of this entry.
1019 const union {
1020 StationID station; ///< ID of the station this entry is associated with.
1021 struct {
1022 CargoID cargo; ///< ID of the cargo this entry is associated with.
1023 bool transfers; ///< If there are transfers for this cargo.
1026 uint num_children; ///< the number of subentries belonging to this entry.
1027 uint count; ///< sum of counts of all children or amount of cargo for this entry.
1028 CargoDataSet *children; ///< the children of this entry.
1031 CargoDataEntry::CargoDataEntry() :
1032 parent(nullptr),
1033 station(INVALID_STATION),
1034 num_children(0),
1035 count(0),
1036 children(new CargoDataSet(CargoSorter(ST_CARGO_ID)))
1039 CargoDataEntry::CargoDataEntry(CargoID cargo, uint count, CargoDataEntry *parent) :
1040 parent(parent),
1041 cargo(cargo),
1042 num_children(0),
1043 count(count),
1044 children(new CargoDataSet)
1047 CargoDataEntry::CargoDataEntry(StationID station, uint count, CargoDataEntry *parent) :
1048 parent(parent),
1049 station(station),
1050 num_children(0),
1051 count(count),
1052 children(new CargoDataSet)
1055 CargoDataEntry::CargoDataEntry(StationID station) :
1056 parent(nullptr),
1057 station(station),
1058 num_children(0),
1059 count(0),
1060 children(nullptr)
1063 CargoDataEntry::CargoDataEntry(CargoID cargo) :
1064 parent(nullptr),
1065 cargo(cargo),
1066 num_children(0),
1067 count(0),
1068 children(nullptr)
1071 CargoDataEntry::~CargoDataEntry()
1073 this->Clear();
1074 delete this->children;
1078 * Delete all subentries, reset count and num_children and adapt parent's count.
1080 void CargoDataEntry::Clear()
1082 if (this->children != nullptr) {
1083 for (CargoDataSet::iterator i = this->children->begin(); i != this->children->end(); ++i) {
1084 assert(*i != this);
1085 delete *i;
1087 this->children->clear();
1089 if (this->parent != nullptr) this->parent->count -= this->count;
1090 this->count = 0;
1091 this->num_children = 0;
1095 * Remove a subentry from this one and delete it.
1096 * @param child the entry to be removed. This may also be a synthetic entry
1097 * which only contains the ID of the entry to be removed. In this case child is
1098 * not deleted.
1100 void CargoDataEntry::Remove(CargoDataEntry *child)
1102 CargoDataSet::iterator i = this->children->find(child);
1103 if (i != this->children->end()) {
1104 delete *i;
1105 this->children->erase(i);
1110 * Retrieve a subentry or insert it if it doesn't exist, yet.
1111 * @tparam ID type of ID: either StationID or CargoID
1112 * @param child_id ID of the child to be inserted or retrieved.
1113 * @return the new or retrieved subentry
1115 template<class Tid>
1116 CargoDataEntry *CargoDataEntry::InsertOrRetrieve(Tid child_id)
1118 CargoDataEntry tmp(child_id);
1119 CargoDataSet::iterator i = this->children->find(&tmp);
1120 if (i == this->children->end()) {
1121 IncrementSize();
1122 return *(this->children->insert(new CargoDataEntry(child_id, 0, this)).first);
1123 } else {
1124 CargoDataEntry *ret = *i;
1125 assert(this->children->value_comp().GetSortType() != ST_COUNT);
1126 return ret;
1131 * Update the count for this entry and propagate the change to the parent entry
1132 * if there is one.
1133 * @param count the amount to be added to this entry
1135 void CargoDataEntry::Update(uint count)
1137 this->count += count;
1138 if (this->parent != nullptr) this->parent->Update(count);
1142 * Increment
1144 void CargoDataEntry::IncrementSize()
1146 ++this->num_children;
1147 if (this->parent != nullptr) this->parent->IncrementSize();
1150 void CargoDataEntry::Resort(CargoSortType type, SortOrder order)
1152 CargoDataSet *new_subs = new CargoDataSet(this->children->begin(), this->children->end(), CargoSorter(type, order));
1153 delete this->children;
1154 this->children = new_subs;
1157 CargoDataEntry *CargoDataEntry::Retrieve(CargoDataSet::iterator i) const
1159 if (i == this->children->end()) {
1160 return nullptr;
1161 } else {
1162 assert(this->children->value_comp().GetSortType() != ST_COUNT);
1163 return *i;
1167 bool CargoSorter::operator()(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const
1169 switch (this->type) {
1170 case ST_STATION_ID:
1171 return this->SortId<StationID>(cd1->GetStation(), cd2->GetStation());
1172 case ST_CARGO_ID:
1173 return this->SortId<CargoID>(cd1->GetCargo(), cd2->GetCargo());
1174 case ST_COUNT:
1175 return this->SortCount(cd1, cd2);
1176 case ST_STATION_STRING:
1177 return this->SortStation(cd1->GetStation(), cd2->GetStation());
1178 default:
1179 NOT_REACHED();
1183 template<class Tid>
1184 bool CargoSorter::SortId(Tid st1, Tid st2) const
1186 return (this->order == SO_ASCENDING) ? st1 < st2 : st2 < st1;
1189 bool CargoSorter::SortCount(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const
1191 uint c1 = cd1->GetCount();
1192 uint c2 = cd2->GetCount();
1193 if (c1 == c2) {
1194 return this->SortStation(cd1->GetStation(), cd2->GetStation());
1195 } else if (this->order == SO_ASCENDING) {
1196 return c1 < c2;
1197 } else {
1198 return c2 < c1;
1202 bool CargoSorter::SortStation(StationID st1, StationID st2) const
1204 if (!Station::IsValidID(st1)) {
1205 return Station::IsValidID(st2) ? this->order == SO_ASCENDING : this->SortId(st1, st2);
1206 } else if (!Station::IsValidID(st2)) {
1207 return order == SO_DESCENDING;
1210 int res = strnatcmp(Station::Get(st1)->GetCachedName(), Station::Get(st2)->GetCachedName()); // Sort by name (natural sorting).
1211 if (res == 0) {
1212 return this->SortId(st1, st2);
1213 } else {
1214 return (this->order == SO_ASCENDING) ? res < 0 : res > 0;
1219 * The StationView window
1221 struct StationViewWindow : public Window {
1223 * A row being displayed in the cargo view (as opposed to being "hidden" behind a plus sign).
1225 struct RowDisplay {
1226 RowDisplay(CargoDataEntry *f, StationID n) : filter(f), next_station(n) {}
1227 RowDisplay(CargoDataEntry *f, CargoID n) : filter(f), next_cargo(n) {}
1230 * Parent of the cargo entry belonging to the row.
1232 CargoDataEntry *filter;
1233 union {
1235 * ID of the station belonging to the entry actually displayed if it's to/from/via.
1237 StationID next_station;
1240 * ID of the cargo belonging to the entry actually displayed if it's cargo.
1242 CargoID next_cargo;
1246 typedef std::vector<RowDisplay> CargoDataVector;
1248 static const int NUM_COLUMNS = 4; ///< Number of "columns" in the cargo view: cargo, from, via, to
1251 * Type of data invalidation.
1253 enum Invalidation {
1254 INV_FLOWS = 0x100, ///< The planned flows have been recalculated and everything has to be updated.
1255 INV_CARGO = 0x200 ///< Some cargo has been added or removed.
1259 * Type of grouping used in each of the "columns".
1261 enum Grouping {
1262 GR_SOURCE, ///< Group by source of cargo ("from").
1263 GR_NEXT, ///< Group by next station ("via").
1264 GR_DESTINATION, ///< Group by estimated final destination ("to").
1265 GR_CARGO, ///< Group by cargo type.
1269 * Display mode of the cargo view.
1271 enum Mode {
1272 MODE_WAITING, ///< Show cargo waiting at the station.
1273 MODE_PLANNED ///< Show cargo planned to pass through the station.
1276 uint expand_shrink_width; ///< The width allocated to the expand/shrink 'button'
1277 int rating_lines; ///< Number of lines in the cargo ratings view.
1278 int accepts_lines; ///< Number of lines in the accepted cargo view.
1279 Scrollbar *vscroll;
1281 /** Height of the #WID_SV_ACCEPT_RATING_LIST widget for different views. */
1282 enum AcceptListHeight {
1283 ALH_RATING = 13, ///< Height of the cargo ratings view.
1284 ALH_ACCEPTS = 3, ///< Height of the accepted cargo view.
1287 static const StringID _sort_names[]; ///< Names of the sorting options in the dropdown.
1288 static const StringID _group_names[]; ///< Names of the grouping options in the dropdown.
1291 * Sort types of the different 'columns'.
1292 * In fact only ST_COUNT and ST_AS_GROUPING are active and you can only
1293 * sort all the columns in the same way. The other options haven't been
1294 * included in the GUI due to lack of space.
1296 CargoSortType sortings[NUM_COLUMNS];
1298 /** Sort order (ascending/descending) for the 'columns'. */
1299 SortOrder sort_orders[NUM_COLUMNS];
1301 int scroll_to_row; ///< If set, scroll the main viewport to the station pointed to by this row.
1302 int grouping_index; ///< Currently selected entry in the grouping drop down.
1303 Mode current_mode; ///< Currently selected display mode of cargo view.
1304 Grouping groupings[NUM_COLUMNS]; ///< Grouping modes for the different columns.
1306 CargoDataEntry expanded_rows; ///< Parent entry of currently expanded rows.
1307 CargoDataEntry cached_destinations; ///< Cache for the flows passing through this station.
1308 CargoDataVector displayed_rows; ///< Parent entry of currently displayed rows (including collapsed ones).
1310 StationViewWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc),
1311 scroll_to_row(INT_MAX), grouping_index(0)
1313 this->rating_lines = ALH_RATING;
1314 this->accepts_lines = ALH_ACCEPTS;
1316 this->CreateNestedTree();
1317 this->vscroll = this->GetScrollbar(WID_SV_SCROLLBAR);
1318 /* Nested widget tree creation is done in two steps to ensure that this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS) exists in UpdateWidgetSize(). */
1319 this->FinishInitNested(window_number);
1321 this->groupings[0] = GR_CARGO;
1322 this->sortings[0] = ST_AS_GROUPING;
1323 this->SelectGroupBy(_settings_client.gui.station_gui_group_order);
1324 this->SelectSortBy(_settings_client.gui.station_gui_sort_by);
1325 this->sort_orders[0] = SO_ASCENDING;
1326 this->SelectSortOrder((SortOrder)_settings_client.gui.station_gui_sort_order);
1327 this->owner = Station::Get(window_number)->owner;
1330 ~StationViewWindow()
1332 DeleteWindowById(WC_TRAINS_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_TRAIN, this->owner, this->window_number).Pack(), false);
1333 DeleteWindowById(WC_ROADVEH_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_ROAD, this->owner, this->window_number).Pack(), false);
1334 DeleteWindowById(WC_SHIPS_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_SHIP, this->owner, this->window_number).Pack(), false);
1335 DeleteWindowById(WC_AIRCRAFT_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_AIRCRAFT, this->owner, this->window_number).Pack(), false);
1337 SetViewportCatchmentStation(Station::Get(this->window_number), false);
1341 * Show a certain cargo entry characterized by source/next/dest station, cargo ID and amount of cargo at the
1342 * right place in the cargo view. I.e. update as many rows as are expanded following that characterization.
1343 * @param data Root entry of the tree.
1344 * @param cargo Cargo ID of the entry to be shown.
1345 * @param source Source station of the entry to be shown.
1346 * @param next Next station the cargo to be shown will visit.
1347 * @param dest Final destination of the cargo to be shown.
1348 * @param count Amount of cargo to be shown.
1350 void ShowCargo(CargoDataEntry *data, CargoID cargo, StationID source, StationID next, StationID dest, uint count)
1352 if (count == 0) return;
1353 bool auto_distributed = _settings_game.linkgraph.GetDistributionType(cargo) != DT_MANUAL;
1354 const CargoDataEntry *expand = &this->expanded_rows;
1355 for (int i = 0; i < NUM_COLUMNS && expand != nullptr; ++i) {
1356 switch (groupings[i]) {
1357 case GR_CARGO:
1358 assert(i == 0);
1359 data = data->InsertOrRetrieve(cargo);
1360 data->SetTransfers(source != this->window_number);
1361 expand = expand->Retrieve(cargo);
1362 break;
1363 case GR_SOURCE:
1364 if (auto_distributed || source != this->window_number) {
1365 data = data->InsertOrRetrieve(source);
1366 expand = expand->Retrieve(source);
1368 break;
1369 case GR_NEXT:
1370 if (auto_distributed) {
1371 data = data->InsertOrRetrieve(next);
1372 expand = expand->Retrieve(next);
1374 break;
1375 case GR_DESTINATION:
1376 if (auto_distributed) {
1377 data = data->InsertOrRetrieve(dest);
1378 expand = expand->Retrieve(dest);
1380 break;
1383 data->Update(count);
1386 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
1388 switch (widget) {
1389 case WID_SV_WAITING:
1390 resize->height = FONT_HEIGHT_NORMAL;
1391 size->height = WD_FRAMERECT_TOP + 4 * resize->height + WD_FRAMERECT_BOTTOM;
1392 this->expand_shrink_width = std::max(GetStringBoundingBox("-").width, GetStringBoundingBox("+").width) + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
1393 break;
1395 case WID_SV_ACCEPT_RATING_LIST:
1396 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;
1397 break;
1399 case WID_SV_CLOSE_AIRPORT:
1400 if (!(Station::Get(this->window_number)->facilities & FACIL_AIRPORT)) {
1401 /* Hide 'Close Airport' button if no airport present. */
1402 size->width = 0;
1403 resize->width = 0;
1404 fill->width = 0;
1406 break;
1410 void OnPaint() override
1412 const Station *st = Station::Get(this->window_number);
1413 CargoDataEntry cargo;
1414 BuildCargoList(&cargo, st);
1416 this->vscroll->SetCount(cargo.GetNumChildren()); // update scrollbar
1418 /* disable some buttons */
1419 this->SetWidgetDisabledState(WID_SV_RENAME, st->owner != _local_company);
1420 this->SetWidgetDisabledState(WID_SV_TRAINS, !(st->facilities & FACIL_TRAIN));
1421 this->SetWidgetDisabledState(WID_SV_ROADVEHS, !(st->facilities & FACIL_TRUCK_STOP) && !(st->facilities & FACIL_BUS_STOP));
1422 this->SetWidgetDisabledState(WID_SV_SHIPS, !(st->facilities & FACIL_DOCK));
1423 this->SetWidgetDisabledState(WID_SV_PLANES, !(st->facilities & FACIL_AIRPORT));
1424 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
1425 this->SetWidgetLoweredState(WID_SV_CLOSE_AIRPORT, (st->facilities & FACIL_AIRPORT) && (st->airport.flags & AIRPORT_CLOSED_block) != 0);
1427 extern const Station *_viewport_highlight_station;
1428 this->SetWidgetDisabledState(WID_SV_CATCHMENT, st->facilities == FACIL_NONE);
1429 this->SetWidgetLoweredState(WID_SV_CATCHMENT, _viewport_highlight_station == st);
1431 this->DrawWidgets();
1433 if (!this->IsShaded()) {
1434 /* Draw 'accepted cargo' or 'cargo ratings'. */
1435 const NWidgetBase *wid = this->GetWidget<NWidgetBase>(WID_SV_ACCEPT_RATING_LIST);
1436 const Rect r = {(int)wid->pos_x, (int)wid->pos_y, (int)(wid->pos_x + wid->current_x - 1), (int)(wid->pos_y + wid->current_y - 1)};
1437 if (this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) {
1438 int lines = this->DrawAcceptedCargo(r);
1439 if (lines > this->accepts_lines) { // Resize the widget, and perform re-initialization of the window.
1440 this->accepts_lines = lines;
1441 this->ReInit();
1442 return;
1444 } else {
1445 int lines = this->DrawCargoRatings(r);
1446 if (lines > this->rating_lines) { // Resize the widget, and perform re-initialization of the window.
1447 this->rating_lines = lines;
1448 this->ReInit();
1449 return;
1453 /* Draw arrow pointing up/down for ascending/descending sorting */
1454 this->DrawSortButtonState(WID_SV_SORT_ORDER, sort_orders[1] == SO_ASCENDING ? SBS_UP : SBS_DOWN);
1456 int pos = this->vscroll->GetPosition();
1458 int maxrows = this->vscroll->GetCapacity();
1460 displayed_rows.clear();
1462 /* Draw waiting cargo. */
1463 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_SV_WAITING);
1464 Rect waiting_rect = { (int)nwi->pos_x, (int)nwi->pos_y, (int)(nwi->pos_x + nwi->current_x - 1), (int)(nwi->pos_y + nwi->current_y - 1)};
1465 this->DrawEntries(&cargo, waiting_rect, pos, maxrows, 0);
1466 scroll_to_row = INT_MAX;
1470 void SetStringParameters(int widget) const override
1472 const Station *st = Station::Get(this->window_number);
1473 SetDParam(0, st->index);
1474 SetDParam(1, st->facilities);
1478 * Rebuild the cache for estimated destinations which is used to quickly show the "destination" entries
1479 * even if we actually don't know the destination of a certain packet from just looking at it.
1480 * @param i Cargo to recalculate the cache for.
1482 void RecalcDestinations(CargoID i)
1484 const Station *st = Station::Get(this->window_number);
1485 CargoDataEntry *cargo_entry = cached_destinations.InsertOrRetrieve(i);
1486 cargo_entry->Clear();
1488 const FlowStatMap &flows = st->goods[i].flows;
1489 for (FlowStatMap::const_iterator it = flows.begin(); it != flows.end(); ++it) {
1490 StationID from = it->first;
1491 CargoDataEntry *source_entry = cargo_entry->InsertOrRetrieve(from);
1492 const FlowStat::SharesMap *shares = it->second.GetShares();
1493 uint32 prev_count = 0;
1494 for (FlowStat::SharesMap::const_iterator flow_it = shares->begin(); flow_it != shares->end(); ++flow_it) {
1495 StationID via = flow_it->second;
1496 CargoDataEntry *via_entry = source_entry->InsertOrRetrieve(via);
1497 if (via == this->window_number) {
1498 via_entry->InsertOrRetrieve(via)->Update(flow_it->first - prev_count);
1499 } else {
1500 EstimateDestinations(i, from, via, flow_it->first - prev_count, via_entry);
1502 prev_count = flow_it->first;
1508 * Estimate the amounts of cargo per final destination for a given cargo, source station and next hop and
1509 * save the result as children of the given CargoDataEntry.
1510 * @param cargo ID of the cargo to estimate destinations for.
1511 * @param source Source station of the given batch of cargo.
1512 * @param next Intermediate hop to start the calculation at ("next hop").
1513 * @param count Size of the batch of cargo.
1514 * @param dest CargoDataEntry to save the results in.
1516 void EstimateDestinations(CargoID cargo, StationID source, StationID next, uint count, CargoDataEntry *dest)
1518 if (Station::IsValidID(next) && Station::IsValidID(source)) {
1519 CargoDataEntry tmp;
1520 const FlowStatMap &flowmap = Station::Get(next)->goods[cargo].flows;
1521 FlowStatMap::const_iterator map_it = flowmap.find(source);
1522 if (map_it != flowmap.end()) {
1523 const FlowStat::SharesMap *shares = map_it->second.GetShares();
1524 uint32 prev_count = 0;
1525 for (FlowStat::SharesMap::const_iterator i = shares->begin(); i != shares->end(); ++i) {
1526 tmp.InsertOrRetrieve(i->second)->Update(i->first - prev_count);
1527 prev_count = i->first;
1531 if (tmp.GetCount() == 0) {
1532 dest->InsertOrRetrieve(INVALID_STATION)->Update(count);
1533 } else {
1534 uint sum_estimated = 0;
1535 while (sum_estimated < count) {
1536 for (CargoDataSet::iterator i = tmp.Begin(); i != tmp.End() && sum_estimated < count; ++i) {
1537 CargoDataEntry *child = *i;
1538 uint estimate = DivideApprox(child->GetCount() * count, tmp.GetCount());
1539 if (estimate == 0) estimate = 1;
1541 sum_estimated += estimate;
1542 if (sum_estimated > count) {
1543 estimate -= sum_estimated - count;
1544 sum_estimated = count;
1547 if (estimate > 0) {
1548 if (child->GetStation() == next) {
1549 dest->InsertOrRetrieve(next)->Update(estimate);
1550 } else {
1551 EstimateDestinations(cargo, source, child->GetStation(), estimate, dest);
1558 } else {
1559 dest->InsertOrRetrieve(INVALID_STATION)->Update(count);
1564 * Build up the cargo view for PLANNED mode and a specific cargo.
1565 * @param i Cargo to show.
1566 * @param flows The current station's flows for that cargo.
1567 * @param cargo The CargoDataEntry to save the results in.
1569 void BuildFlowList(CargoID i, const FlowStatMap &flows, CargoDataEntry *cargo)
1571 const CargoDataEntry *source_dest = this->cached_destinations.Retrieve(i);
1572 for (FlowStatMap::const_iterator it = flows.begin(); it != flows.end(); ++it) {
1573 StationID from = it->first;
1574 const CargoDataEntry *source_entry = source_dest->Retrieve(from);
1575 const FlowStat::SharesMap *shares = it->second.GetShares();
1576 for (FlowStat::SharesMap::const_iterator flow_it = shares->begin(); flow_it != shares->end(); ++flow_it) {
1577 const CargoDataEntry *via_entry = source_entry->Retrieve(flow_it->second);
1578 for (CargoDataSet::iterator dest_it = via_entry->Begin(); dest_it != via_entry->End(); ++dest_it) {
1579 CargoDataEntry *dest_entry = *dest_it;
1580 ShowCargo(cargo, i, from, flow_it->second, dest_entry->GetStation(), dest_entry->GetCount());
1587 * Build up the cargo view for WAITING mode and a specific cargo.
1588 * @param i Cargo to show.
1589 * @param packets The current station's cargo list for that cargo.
1590 * @param cargo The CargoDataEntry to save the result in.
1592 void BuildCargoList(CargoID i, const StationCargoList &packets, CargoDataEntry *cargo)
1594 const CargoDataEntry *source_dest = this->cached_destinations.Retrieve(i);
1595 for (StationCargoList::ConstIterator it = packets.Packets()->begin(); it != packets.Packets()->end(); it++) {
1596 const CargoPacket *cp = *it;
1597 StationID next = it.GetKey();
1599 const CargoDataEntry *source_entry = source_dest->Retrieve(cp->SourceStation());
1600 if (source_entry == nullptr) {
1601 this->ShowCargo(cargo, i, cp->SourceStation(), next, INVALID_STATION, cp->Count());
1602 continue;
1605 const CargoDataEntry *via_entry = source_entry->Retrieve(next);
1606 if (via_entry == nullptr) {
1607 this->ShowCargo(cargo, i, cp->SourceStation(), next, INVALID_STATION, cp->Count());
1608 continue;
1611 for (CargoDataSet::iterator dest_it = via_entry->Begin(); dest_it != via_entry->End(); ++dest_it) {
1612 CargoDataEntry *dest_entry = *dest_it;
1613 uint val = DivideApprox(cp->Count() * dest_entry->GetCount(), via_entry->GetCount());
1614 this->ShowCargo(cargo, i, cp->SourceStation(), next, dest_entry->GetStation(), val);
1617 this->ShowCargo(cargo, i, NEW_STATION, NEW_STATION, NEW_STATION, packets.ReservedCount());
1621 * Build up the cargo view for all cargoes.
1622 * @param cargo The root cargo entry to save all results in.
1623 * @param st The station to calculate the cargo view from.
1625 void BuildCargoList(CargoDataEntry *cargo, const Station *st)
1627 for (CargoID i = 0; i < NUM_CARGO; i++) {
1629 if (this->cached_destinations.Retrieve(i) == nullptr) {
1630 this->RecalcDestinations(i);
1633 if (this->current_mode == MODE_WAITING) {
1634 this->BuildCargoList(i, st->goods[i].cargo, cargo);
1635 } else {
1636 this->BuildFlowList(i, st->goods[i].flows, cargo);
1642 * Mark a specific row, characterized by its CargoDataEntry, as expanded.
1643 * @param data The row to be marked as expanded.
1645 void SetDisplayedRow(const CargoDataEntry *data)
1647 std::list<StationID> stations;
1648 const CargoDataEntry *parent = data->GetParent();
1649 if (parent->GetParent() == nullptr) {
1650 this->displayed_rows.push_back(RowDisplay(&this->expanded_rows, data->GetCargo()));
1651 return;
1654 StationID next = data->GetStation();
1655 while (parent->GetParent()->GetParent() != nullptr) {
1656 stations.push_back(parent->GetStation());
1657 parent = parent->GetParent();
1660 CargoID cargo = parent->GetCargo();
1661 CargoDataEntry *filter = this->expanded_rows.Retrieve(cargo);
1662 while (!stations.empty()) {
1663 filter = filter->Retrieve(stations.back());
1664 stations.pop_back();
1667 this->displayed_rows.push_back(RowDisplay(filter, next));
1671 * Select the correct string for an entry referring to the specified station.
1672 * @param station Station the entry is showing cargo for.
1673 * @param here String to be shown if the entry refers to the same station as this station GUI belongs to.
1674 * @param other_station String to be shown if the entry refers to a specific other station.
1675 * @param any String to be shown if the entry refers to "any station".
1676 * @return One of the three given strings or STR_STATION_VIEW_RESERVED, depending on what station the entry refers to.
1678 StringID GetEntryString(StationID station, StringID here, StringID other_station, StringID any)
1680 if (station == this->window_number) {
1681 return here;
1682 } else if (station == INVALID_STATION) {
1683 return any;
1684 } else if (station == NEW_STATION) {
1685 return STR_STATION_VIEW_RESERVED;
1686 } else {
1687 SetDParam(2, station);
1688 return other_station;
1693 * Determine if we need to show the special "non-stop" string.
1694 * @param cd Entry we are going to show.
1695 * @param station Station the entry refers to.
1696 * @param column The "column" the entry will be shown in.
1697 * @return either STR_STATION_VIEW_VIA or STR_STATION_VIEW_NONSTOP.
1699 StringID SearchNonStop(CargoDataEntry *cd, StationID station, int column)
1701 CargoDataEntry *parent = cd->GetParent();
1702 for (int i = column - 1; i > 0; --i) {
1703 if (this->groupings[i] == GR_DESTINATION) {
1704 if (parent->GetStation() == station) {
1705 return STR_STATION_VIEW_NONSTOP;
1706 } else {
1707 return STR_STATION_VIEW_VIA;
1710 parent = parent->GetParent();
1713 if (this->groupings[column + 1] == GR_DESTINATION) {
1714 CargoDataSet::iterator begin = cd->Begin();
1715 CargoDataSet::iterator end = cd->End();
1716 if (begin != end && ++(cd->Begin()) == end && (*(begin))->GetStation() == station) {
1717 return STR_STATION_VIEW_NONSTOP;
1718 } else {
1719 return STR_STATION_VIEW_VIA;
1723 return STR_STATION_VIEW_VIA;
1727 * Draw the given cargo entries in the station GUI.
1728 * @param entry Root entry for all cargo to be drawn.
1729 * @param r Screen rectangle to draw into.
1730 * @param pos Current row to be drawn to (counted down from 0 to -maxrows, same as vscroll->GetPosition()).
1731 * @param maxrows Maximum row to be drawn.
1732 * @param column Current "column" being drawn.
1733 * @param cargo Current cargo being drawn (if cargo column has been passed).
1734 * @return row (in "pos" counting) after the one we have last drawn to.
1736 int DrawEntries(CargoDataEntry *entry, Rect &r, int pos, int maxrows, int column, CargoID cargo = CT_INVALID)
1738 if (this->sortings[column] == ST_AS_GROUPING) {
1739 if (this->groupings[column] != GR_CARGO) {
1740 entry->Resort(ST_STATION_STRING, this->sort_orders[column]);
1742 } else {
1743 entry->Resort(ST_COUNT, this->sort_orders[column]);
1745 for (CargoDataSet::iterator i = entry->Begin(); i != entry->End(); ++i) {
1746 CargoDataEntry *cd = *i;
1748 Grouping grouping = this->groupings[column];
1749 if (grouping == GR_CARGO) cargo = cd->GetCargo();
1750 bool auto_distributed = _settings_game.linkgraph.GetDistributionType(cargo) != DT_MANUAL;
1752 if (pos > -maxrows && pos <= 0) {
1753 StringID str = STR_EMPTY;
1754 int y = r.top + WD_FRAMERECT_TOP - pos * FONT_HEIGHT_NORMAL;
1755 SetDParam(0, cargo);
1756 SetDParam(1, cd->GetCount());
1758 if (this->groupings[column] == GR_CARGO) {
1759 str = STR_STATION_VIEW_WAITING_CARGO;
1760 DrawCargoIcons(cd->GetCargo(), cd->GetCount(), r.left + WD_FRAMERECT_LEFT + this->expand_shrink_width, r.right - WD_FRAMERECT_RIGHT - this->expand_shrink_width, y);
1761 } else {
1762 if (!auto_distributed) grouping = GR_SOURCE;
1763 StationID station = cd->GetStation();
1765 switch (grouping) {
1766 case GR_SOURCE:
1767 str = this->GetEntryString(station, STR_STATION_VIEW_FROM_HERE, STR_STATION_VIEW_FROM, STR_STATION_VIEW_FROM_ANY);
1768 break;
1769 case GR_NEXT:
1770 str = this->GetEntryString(station, STR_STATION_VIEW_VIA_HERE, STR_STATION_VIEW_VIA, STR_STATION_VIEW_VIA_ANY);
1771 if (str == STR_STATION_VIEW_VIA) str = this->SearchNonStop(cd, station, column);
1772 break;
1773 case GR_DESTINATION:
1774 str = this->GetEntryString(station, STR_STATION_VIEW_TO_HERE, STR_STATION_VIEW_TO, STR_STATION_VIEW_TO_ANY);
1775 break;
1776 default:
1777 NOT_REACHED();
1779 if (pos == -this->scroll_to_row && Station::IsValidID(station)) {
1780 ScrollMainWindowToTile(Station::Get(station)->xy);
1784 bool rtl = _current_text_dir == TD_RTL;
1785 int text_left = rtl ? r.left + this->expand_shrink_width : r.left + WD_FRAMERECT_LEFT + column * this->expand_shrink_width;
1786 int text_right = rtl ? r.right - WD_FRAMERECT_LEFT - column * this->expand_shrink_width : r.right - this->expand_shrink_width;
1787 int shrink_left = rtl ? r.left + WD_FRAMERECT_LEFT : r.right - this->expand_shrink_width + WD_FRAMERECT_LEFT;
1788 int shrink_right = rtl ? r.left + this->expand_shrink_width - WD_FRAMERECT_RIGHT : r.right - WD_FRAMERECT_RIGHT;
1790 DrawString(text_left, text_right, y, str);
1792 if (column < NUM_COLUMNS - 1) {
1793 const char *sym = nullptr;
1794 if (cd->GetNumChildren() > 0) {
1795 sym = "-";
1796 } else if (auto_distributed && str != STR_STATION_VIEW_RESERVED) {
1797 sym = "+";
1798 } else {
1799 /* Only draw '+' if there is something to be shown. */
1800 const StationCargoList &list = Station::Get(this->window_number)->goods[cargo].cargo;
1801 if (grouping == GR_CARGO && (list.ReservedCount() > 0 || cd->HasTransfers())) {
1802 sym = "+";
1805 if (sym) DrawString(shrink_left, shrink_right, y, sym, TC_YELLOW);
1807 this->SetDisplayedRow(cd);
1809 --pos;
1810 if (auto_distributed || column == 0) {
1811 pos = this->DrawEntries(cd, r, pos, maxrows, column + 1, cargo);
1814 return pos;
1818 * Draw accepted cargo in the #WID_SV_ACCEPT_RATING_LIST widget.
1819 * @param r Rectangle of the widget.
1820 * @return Number of lines needed for drawing the accepted cargo.
1822 int DrawAcceptedCargo(const Rect &r) const
1824 const Station *st = Station::Get(this->window_number);
1826 CargoTypes cargo_mask = 0;
1827 for (CargoID i = 0; i < NUM_CARGO; i++) {
1828 if (HasBit(st->goods[i].status, GoodsEntry::GES_ACCEPTANCE)) SetBit(cargo_mask, i);
1830 SetDParam(0, cargo_mask);
1831 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);
1832 return CeilDiv(bottom - r.top - WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL);
1836 * Draw cargo ratings in the #WID_SV_ACCEPT_RATING_LIST widget.
1837 * @param r Rectangle of the widget.
1838 * @return Number of lines needed for drawing the cargo ratings.
1840 int DrawCargoRatings(const Rect &r) const
1842 const Station *st = Station::Get(this->window_number);
1843 int y = r.top + WD_FRAMERECT_TOP;
1845 if (st->town->exclusive_counter > 0) {
1846 SetDParam(0, st->town->exclusivity);
1847 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);
1848 y += WD_PAR_VSEP_WIDE;
1851 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_VIEW_SUPPLY_RATINGS_TITLE);
1852 y += FONT_HEIGHT_NORMAL;
1854 const CargoSpec *cs;
1855 FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
1856 const GoodsEntry *ge = &st->goods[cs->Index()];
1857 if (!ge->HasRating()) continue;
1859 const LinkGraph *lg = LinkGraph::GetIfValid(ge->link_graph);
1860 SetDParam(0, cs->name);
1861 SetDParam(1, lg != nullptr ? lg->Monthly((*lg)[ge->node].Supply()) : 0);
1862 SetDParam(2, STR_CARGO_RATING_APPALLING + (ge->rating >> 5));
1863 SetDParam(3, ToPercent8(ge->rating));
1864 DrawString(r.left + WD_FRAMERECT_LEFT + 6, r.right - WD_FRAMERECT_RIGHT - 6, y, STR_STATION_VIEW_CARGO_SUPPLY_RATING);
1865 y += FONT_HEIGHT_NORMAL;
1867 return CeilDiv(y - r.top - WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL);
1871 * Expand or collapse a specific row.
1872 * @param filter Parent of the row.
1873 * @param next ID pointing to the row.
1875 template<class Tid>
1876 void HandleCargoWaitingClick(CargoDataEntry *filter, Tid next)
1878 if (filter->Retrieve(next) != nullptr) {
1879 filter->Remove(next);
1880 } else {
1881 filter->InsertOrRetrieve(next);
1886 * Handle a click on a specific row in the cargo view.
1887 * @param row Row being clicked.
1889 void HandleCargoWaitingClick(int row)
1891 if (row < 0 || (uint)row >= this->displayed_rows.size()) return;
1892 if (_ctrl_pressed) {
1893 this->scroll_to_row = row;
1894 } else {
1895 RowDisplay &display = this->displayed_rows[row];
1896 if (display.filter == &this->expanded_rows) {
1897 this->HandleCargoWaitingClick<CargoID>(display.filter, display.next_cargo);
1898 } else {
1899 this->HandleCargoWaitingClick<StationID>(display.filter, display.next_station);
1902 this->SetWidgetDirty(WID_SV_WAITING);
1905 void OnClick(Point pt, int widget, int click_count) override
1907 switch (widget) {
1908 case WID_SV_WAITING:
1909 this->HandleCargoWaitingClick(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_SV_WAITING, WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL) - this->vscroll->GetPosition());
1910 break;
1912 case WID_SV_CATCHMENT:
1913 SetViewportCatchmentStation(Station::Get(this->window_number), !this->IsWidgetLowered(WID_SV_CATCHMENT));
1914 break;
1916 case WID_SV_LOCATION:
1917 if (_ctrl_pressed) {
1918 ShowExtraViewportWindow(Station::Get(this->window_number)->xy);
1919 } else {
1920 ScrollMainWindowToTile(Station::Get(this->window_number)->xy);
1922 break;
1924 case WID_SV_ACCEPTS_RATINGS: {
1925 /* Swap between 'accepts' and 'ratings' view. */
1926 int height_change;
1927 NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS);
1928 if (this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) {
1929 nwi->SetDataTip(STR_STATION_VIEW_ACCEPTS_BUTTON, STR_STATION_VIEW_ACCEPTS_TOOLTIP); // Switch to accepts view.
1930 height_change = this->rating_lines - this->accepts_lines;
1931 } else {
1932 nwi->SetDataTip(STR_STATION_VIEW_RATINGS_BUTTON, STR_STATION_VIEW_RATINGS_TOOLTIP); // Switch to ratings view.
1933 height_change = this->accepts_lines - this->rating_lines;
1935 this->ReInit(0, height_change * FONT_HEIGHT_NORMAL);
1936 break;
1939 case WID_SV_RENAME:
1940 SetDParam(0, this->window_number);
1941 ShowQueryString(STR_STATION_NAME, STR_STATION_VIEW_RENAME_STATION_CAPTION, MAX_LENGTH_STATION_NAME_CHARS,
1942 this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
1943 break;
1945 case WID_SV_CLOSE_AIRPORT:
1946 DoCommandP(0, this->window_number, 0, CMD_OPEN_CLOSE_AIRPORT);
1947 break;
1949 case WID_SV_TRAINS: // Show list of scheduled trains to this station
1950 case WID_SV_ROADVEHS: // Show list of scheduled road-vehicles to this station
1951 case WID_SV_SHIPS: // Show list of scheduled ships to this station
1952 case WID_SV_PLANES: { // Show list of scheduled aircraft to this station
1953 Owner owner = Station::Get(this->window_number)->owner;
1954 ShowVehicleListWindow(owner, (VehicleType)(widget - WID_SV_TRAINS), (StationID)this->window_number);
1955 break;
1958 case WID_SV_SORT_BY: {
1959 /* The initial selection is composed of current mode and
1960 * sorting criteria for columns 1, 2, and 3. Column 0 is always
1961 * sorted by cargo ID. The others can theoretically be sorted
1962 * by different things but there is no UI for that. */
1963 ShowDropDownMenu(this, _sort_names,
1964 this->current_mode * 2 + (this->sortings[1] == ST_COUNT ? 1 : 0),
1965 WID_SV_SORT_BY, 0, 0);
1966 break;
1969 case WID_SV_GROUP_BY: {
1970 ShowDropDownMenu(this, _group_names, this->grouping_index, WID_SV_GROUP_BY, 0, 0);
1971 break;
1974 case WID_SV_SORT_ORDER: { // flip sorting method asc/desc
1975 this->SelectSortOrder(this->sort_orders[1] == SO_ASCENDING ? SO_DESCENDING : SO_ASCENDING);
1976 this->SetTimeout();
1977 this->LowerWidget(WID_SV_SORT_ORDER);
1978 break;
1984 * Select a new sort order for the cargo view.
1985 * @param order New sort order.
1987 void SelectSortOrder(SortOrder order)
1989 this->sort_orders[1] = this->sort_orders[2] = this->sort_orders[3] = order;
1990 _settings_client.gui.station_gui_sort_order = this->sort_orders[1];
1991 this->SetDirty();
1995 * Select a new sort criterium for the cargo view.
1996 * @param index Row being selected in the sort criteria drop down.
1998 void SelectSortBy(int index)
2000 _settings_client.gui.station_gui_sort_by = index;
2001 switch (_sort_names[index]) {
2002 case STR_STATION_VIEW_WAITING_STATION:
2003 this->current_mode = MODE_WAITING;
2004 this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_AS_GROUPING;
2005 break;
2006 case STR_STATION_VIEW_WAITING_AMOUNT:
2007 this->current_mode = MODE_WAITING;
2008 this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_COUNT;
2009 break;
2010 case STR_STATION_VIEW_PLANNED_STATION:
2011 this->current_mode = MODE_PLANNED;
2012 this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_AS_GROUPING;
2013 break;
2014 case STR_STATION_VIEW_PLANNED_AMOUNT:
2015 this->current_mode = MODE_PLANNED;
2016 this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_COUNT;
2017 break;
2018 default:
2019 NOT_REACHED();
2021 /* Display the current sort variant */
2022 this->GetWidget<NWidgetCore>(WID_SV_SORT_BY)->widget_data = _sort_names[index];
2023 this->SetDirty();
2027 * Select a new grouping mode for the cargo view.
2028 * @param index Row being selected in the grouping drop down.
2030 void SelectGroupBy(int index)
2032 this->grouping_index = index;
2033 _settings_client.gui.station_gui_group_order = index;
2034 this->GetWidget<NWidgetCore>(WID_SV_GROUP_BY)->widget_data = _group_names[index];
2035 switch (_group_names[index]) {
2036 case STR_STATION_VIEW_GROUP_S_V_D:
2037 this->groupings[1] = GR_SOURCE;
2038 this->groupings[2] = GR_NEXT;
2039 this->groupings[3] = GR_DESTINATION;
2040 break;
2041 case STR_STATION_VIEW_GROUP_S_D_V:
2042 this->groupings[1] = GR_SOURCE;
2043 this->groupings[2] = GR_DESTINATION;
2044 this->groupings[3] = GR_NEXT;
2045 break;
2046 case STR_STATION_VIEW_GROUP_V_S_D:
2047 this->groupings[1] = GR_NEXT;
2048 this->groupings[2] = GR_SOURCE;
2049 this->groupings[3] = GR_DESTINATION;
2050 break;
2051 case STR_STATION_VIEW_GROUP_V_D_S:
2052 this->groupings[1] = GR_NEXT;
2053 this->groupings[2] = GR_DESTINATION;
2054 this->groupings[3] = GR_SOURCE;
2055 break;
2056 case STR_STATION_VIEW_GROUP_D_S_V:
2057 this->groupings[1] = GR_DESTINATION;
2058 this->groupings[2] = GR_SOURCE;
2059 this->groupings[3] = GR_NEXT;
2060 break;
2061 case STR_STATION_VIEW_GROUP_D_V_S:
2062 this->groupings[1] = GR_DESTINATION;
2063 this->groupings[2] = GR_NEXT;
2064 this->groupings[3] = GR_SOURCE;
2065 break;
2067 this->SetDirty();
2070 void OnDropdownSelect(int widget, int index) override
2072 if (widget == WID_SV_SORT_BY) {
2073 this->SelectSortBy(index);
2074 } else {
2075 this->SelectGroupBy(index);
2079 void OnQueryTextFinished(char *str) override
2081 if (str == nullptr) return;
2083 DoCommandP(0, this->window_number, 0, CMD_RENAME_STATION | CMD_MSG(STR_ERROR_CAN_T_RENAME_STATION), nullptr, str);
2086 void OnResize() override
2088 this->vscroll->SetCapacityFromWidget(this, WID_SV_WAITING, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
2092 * Some data on this window has become invalid. Invalidate the cache for the given cargo if necessary.
2093 * @param data Information about the changed data. If it's a valid cargo ID, invalidate the cargo data.
2094 * @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.
2096 void OnInvalidateData(int data = 0, bool gui_scope = true) override
2098 if (gui_scope) {
2099 if (data >= 0 && data < NUM_CARGO) {
2100 this->cached_destinations.Remove((CargoID)data);
2101 } else {
2102 this->ReInit();
2108 const StringID StationViewWindow::_sort_names[] = {
2109 STR_STATION_VIEW_WAITING_STATION,
2110 STR_STATION_VIEW_WAITING_AMOUNT,
2111 STR_STATION_VIEW_PLANNED_STATION,
2112 STR_STATION_VIEW_PLANNED_AMOUNT,
2113 INVALID_STRING_ID
2116 const StringID StationViewWindow::_group_names[] = {
2117 STR_STATION_VIEW_GROUP_S_V_D,
2118 STR_STATION_VIEW_GROUP_S_D_V,
2119 STR_STATION_VIEW_GROUP_V_S_D,
2120 STR_STATION_VIEW_GROUP_V_D_S,
2121 STR_STATION_VIEW_GROUP_D_S_V,
2122 STR_STATION_VIEW_GROUP_D_V_S,
2123 INVALID_STRING_ID
2126 static WindowDesc _station_view_desc(
2127 WDP_AUTO, "view_station", 249, 117,
2128 WC_STATION_VIEW, WC_NONE,
2130 _nested_station_view_widgets, lengthof(_nested_station_view_widgets)
2134 * Opens StationViewWindow for given station
2136 * @param station station which window should be opened
2138 void ShowStationViewWindow(StationID station)
2140 AllocateWindowDescFront<StationViewWindow>(&_station_view_desc, station);
2143 /** Struct containing TileIndex and StationID */
2144 struct TileAndStation {
2145 TileIndex tile; ///< TileIndex
2146 StationID station; ///< StationID
2149 static std::vector<TileAndStation> _deleted_stations_nearby;
2150 static std::vector<StationID> _stations_nearby_list;
2153 * Add station on this tile to _stations_nearby_list if it's fully within the
2154 * station spread.
2155 * @param tile Tile just being checked
2156 * @param user_data Pointer to TileArea context
2157 * @tparam T the type of station to look for
2159 template <class T>
2160 static bool AddNearbyStation(TileIndex tile, void *user_data)
2162 TileArea *ctx = (TileArea *)user_data;
2164 /* First check if there were deleted stations here */
2165 for (uint i = 0; i < _deleted_stations_nearby.size(); i++) {
2166 auto ts = _deleted_stations_nearby.begin() + i;
2167 if (ts->tile == tile) {
2168 _stations_nearby_list.push_back(_deleted_stations_nearby[i].station);
2169 _deleted_stations_nearby.erase(ts);
2170 i--;
2174 /* Check if own station and if we stay within station spread */
2175 if (!IsTileType(tile, MP_STATION)) return false;
2177 StationID sid = GetStationIndex(tile);
2179 /* This station is (likely) a waypoint */
2180 if (!T::IsValidID(sid)) return false;
2182 T *st = T::Get(sid);
2183 if (st->owner != _local_company || std::find(_stations_nearby_list.begin(), _stations_nearby_list.end(), sid) != _stations_nearby_list.end()) return false;
2185 if (st->rect.BeforeAddRect(ctx->tile, ctx->w, ctx->h, StationRect::ADD_TEST).Succeeded()) {
2186 _stations_nearby_list.push_back(sid);
2189 return false; // We want to include *all* nearby stations
2193 * Circulate around the to-be-built station to find stations we could join.
2194 * Make sure that only stations are returned where joining wouldn't exceed
2195 * station spread and are our own station.
2196 * @param ta Base tile area of the to-be-built station
2197 * @param distant_join Search for adjacent stations (false) or stations fully
2198 * within station spread
2199 * @tparam T the type of station to look for
2201 template <class T>
2202 static const T *FindStationsNearby(TileArea ta, bool distant_join)
2204 TileArea ctx = ta;
2206 _stations_nearby_list.clear();
2207 _deleted_stations_nearby.clear();
2209 /* Check the inside, to return, if we sit on another station */
2210 TILE_AREA_LOOP(t, ta) {
2211 if (t < MapSize() && IsTileType(t, MP_STATION) && T::IsValidID(GetStationIndex(t))) return T::GetByTile(t);
2214 /* Look for deleted stations */
2215 for (const BaseStation *st : BaseStation::Iterate()) {
2216 if (T::IsExpected(st) && !st->IsInUse() && st->owner == _local_company) {
2217 /* Include only within station spread (yes, it is strictly less than) */
2218 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) {
2219 _deleted_stations_nearby.push_back({st->xy, st->index});
2221 /* Add the station when it's within where we're going to build */
2222 if (IsInsideBS(TileX(st->xy), TileX(ctx.tile), ctx.w) &&
2223 IsInsideBS(TileY(st->xy), TileY(ctx.tile), ctx.h)) {
2224 AddNearbyStation<T>(st->xy, &ctx);
2230 /* Only search tiles where we have a chance to stay within the station spread.
2231 * The complete check needs to be done in the callback as we don't know the
2232 * extent of the found station, yet. */
2233 if (distant_join && std::min(ta.w, ta.h) >= _settings_game.station.station_spread) return nullptr;
2234 uint max_dist = distant_join ? _settings_game.station.station_spread - std::min(ta.w, ta.h) : 1;
2236 TileIndex tile = TileAddByDir(ctx.tile, DIR_N);
2237 CircularTileSearch(&tile, max_dist, ta.w, ta.h, AddNearbyStation<T>, &ctx);
2239 return nullptr;
2242 static const NWidgetPart _nested_select_station_widgets[] = {
2243 NWidget(NWID_HORIZONTAL),
2244 NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
2245 NWidget(WWT_CAPTION, COLOUR_DARK_GREEN, WID_JS_CAPTION), SetDataTip(STR_JOIN_STATION_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2246 NWidget(WWT_DEFSIZEBOX, COLOUR_DARK_GREEN),
2247 EndContainer(),
2248 NWidget(NWID_HORIZONTAL),
2249 NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_JS_PANEL), SetResize(1, 0), SetScrollbar(WID_JS_SCROLLBAR), EndContainer(),
2250 NWidget(NWID_VERTICAL),
2251 NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, WID_JS_SCROLLBAR),
2252 NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
2253 EndContainer(),
2254 EndContainer(),
2258 * Window for selecting stations/waypoints to (distant) join to.
2259 * @tparam T The type of station to join with
2261 template <class T>
2262 struct SelectStationWindow : Window {
2263 CommandContainer select_station_cmd; ///< Command to build new station
2264 TileArea area; ///< Location of new station
2265 Scrollbar *vscroll;
2267 SelectStationWindow(WindowDesc *desc, const CommandContainer &cmd, TileArea ta) :
2268 Window(desc),
2269 select_station_cmd(cmd),
2270 area(ta)
2272 this->CreateNestedTree();
2273 this->vscroll = this->GetScrollbar(WID_JS_SCROLLBAR);
2274 this->GetWidget<NWidgetCore>(WID_JS_CAPTION)->widget_data = T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_JOIN_WAYPOINT_CAPTION : STR_JOIN_STATION_CAPTION;
2275 this->FinishInitNested(0);
2276 this->OnInvalidateData(0);
2278 _thd.freeze = true;
2281 ~SelectStationWindow()
2283 if (_settings_client.gui.station_show_coverage) SetViewportCatchmentStation(nullptr, true);
2285 _thd.freeze = false;
2288 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
2290 if (widget != WID_JS_PANEL) return;
2292 /* Determine the widest string */
2293 Dimension d = GetStringBoundingBox(T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_JOIN_WAYPOINT_CREATE_SPLITTED_WAYPOINT : STR_JOIN_STATION_CREATE_SPLITTED_STATION);
2294 for (uint i = 0; i < _stations_nearby_list.size(); i++) {
2295 const T *st = T::Get(_stations_nearby_list[i]);
2296 SetDParam(0, st->index);
2297 SetDParam(1, st->facilities);
2298 d = maxdim(d, GetStringBoundingBox(T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_STATION_LIST_WAYPOINT : STR_STATION_LIST_STATION));
2301 resize->height = d.height;
2302 d.height *= 5;
2303 d.width += WD_FRAMERECT_RIGHT + WD_FRAMERECT_LEFT;
2304 d.height += WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
2305 *size = d;
2308 void DrawWidget(const Rect &r, int widget) const override
2310 if (widget != WID_JS_PANEL) return;
2312 uint y = r.top + WD_FRAMERECT_TOP;
2313 if (this->vscroll->GetPosition() == 0) {
2314 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);
2315 y += this->resize.step_height;
2318 for (uint i = std::max<uint>(1, this->vscroll->GetPosition()); i <= _stations_nearby_list.size(); ++i, y += this->resize.step_height) {
2319 /* Don't draw anything if it extends past the end of the window. */
2320 if (i - this->vscroll->GetPosition() >= this->vscroll->GetCapacity()) break;
2322 const T *st = T::Get(_stations_nearby_list[i - 1]);
2323 SetDParam(0, st->index);
2324 SetDParam(1, st->facilities);
2325 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);
2329 void OnClick(Point pt, int widget, int click_count) override
2331 if (widget != WID_JS_PANEL) return;
2333 uint st_index = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_JS_PANEL, WD_FRAMERECT_TOP);
2334 bool distant_join = (st_index > 0);
2335 if (distant_join) st_index--;
2337 if (distant_join && st_index >= _stations_nearby_list.size()) return;
2339 /* Insert station to be joined into stored command */
2340 SB(this->select_station_cmd.p2, 16, 16,
2341 (distant_join ? _stations_nearby_list[st_index] : NEW_STATION));
2343 /* Execute stored Command */
2344 DoCommandP(&this->select_station_cmd);
2346 /* Close Window; this might cause double frees! */
2347 DeleteWindowById(WC_SELECT_STATION, 0);
2350 void OnRealtimeTick(uint delta_ms) override
2352 if (_thd.dirty & 2) {
2353 _thd.dirty &= ~2;
2354 this->SetDirty();
2358 void OnResize() override
2360 this->vscroll->SetCapacityFromWidget(this, WID_JS_PANEL, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
2364 * Some data on this window has become invalid.
2365 * @param data Information about the changed data.
2366 * @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.
2368 void OnInvalidateData(int data = 0, bool gui_scope = true) override
2370 if (!gui_scope) return;
2371 FindStationsNearby<T>(this->area, true);
2372 this->vscroll->SetCount((uint)_stations_nearby_list.size() + 1);
2373 this->SetDirty();
2376 void OnMouseOver(Point pt, int widget) override
2378 if (widget != WID_JS_PANEL || T::EXPECTED_FACIL == FACIL_WAYPOINT) {
2379 SetViewportCatchmentStation(nullptr, true);
2380 return;
2383 /* Show coverage area of station under cursor */
2384 uint st_index = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_JS_PANEL, WD_FRAMERECT_TOP);
2385 if (st_index == 0 || st_index > _stations_nearby_list.size()) {
2386 SetViewportCatchmentStation(nullptr, true);
2387 } else {
2388 st_index--;
2389 SetViewportCatchmentStation(Station::Get(_stations_nearby_list[st_index]), true);
2394 static WindowDesc _select_station_desc(
2395 WDP_AUTO, "build_station_join", 200, 180,
2396 WC_SELECT_STATION, WC_NONE,
2397 WDF_CONSTRUCTION,
2398 _nested_select_station_widgets, lengthof(_nested_select_station_widgets)
2403 * Check whether we need to show the station selection window.
2404 * @param cmd Command to build the station.
2405 * @param ta Tile area of the to-be-built station
2406 * @tparam T the type of station
2407 * @return whether we need to show the station selection window.
2409 template <class T>
2410 static bool StationJoinerNeeded(const CommandContainer &cmd, TileArea ta)
2412 /* Only show selection if distant join is enabled in the settings */
2413 if (!_settings_game.station.distant_join_stations) return false;
2415 /* If a window is already opened and we didn't ctrl-click,
2416 * return true (i.e. just flash the old window) */
2417 Window *selection_window = FindWindowById(WC_SELECT_STATION, 0);
2418 if (selection_window != nullptr) {
2419 /* Abort current distant-join and start new one */
2420 delete selection_window;
2421 UpdateTileSelection();
2424 /* only show the popup, if we press ctrl */
2425 if (!_ctrl_pressed) return false;
2427 /* Now check if we could build there */
2428 if (DoCommand(&cmd, CommandFlagsToDCFlags(GetCommandFlags(cmd.cmd))).Failed()) return false;
2430 /* Test for adjacent station or station below selection.
2431 * If adjacent-stations is disabled and we are building next to a station, do not show the selection window.
2432 * but join the other station immediately. */
2433 const T *st = FindStationsNearby<T>(ta, false);
2434 return st == nullptr && (_settings_game.station.adjacent_stations || _stations_nearby_list.size() == 0);
2438 * Show the station selection window when needed. If not, build the station.
2439 * @param cmd Command to build the station.
2440 * @param ta Area to build the station in
2441 * @tparam the class to find stations for
2443 template <class T>
2444 void ShowSelectBaseStationIfNeeded(const CommandContainer &cmd, TileArea ta)
2446 if (StationJoinerNeeded<T>(cmd, ta)) {
2447 if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
2448 new SelectStationWindow<T>(&_select_station_desc, cmd, ta);
2449 } else {
2450 DoCommandP(&cmd);
2455 * Show the station selection window when needed. If not, build the station.
2456 * @param cmd Command to build the station.
2457 * @param ta Area to build the station in
2459 void ShowSelectStationIfNeeded(const CommandContainer &cmd, TileArea ta)
2461 ShowSelectBaseStationIfNeeded<Station>(cmd, ta);
2465 * Show the waypoint selection window when needed. If not, build the waypoint.
2466 * @param cmd Command to build the waypoint.
2467 * @param ta Area to build the waypoint in
2469 void ShowSelectWaypointIfNeeded(const CommandContainer &cmd, TileArea ta)
2471 ShowSelectBaseStationIfNeeded<Waypoint>(cmd, ta);