Rework the way the ReinitSeparation command is called. The old way was way too danger...
[openttd-joker.git] / src / station_gui.cpp
blob36d23a76adb7268cfb413a98f01bfa5bfdfd4a4a
1 /* $Id: station_gui.cpp 26083 2013-11-24 14:29:32Z rubidium $ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
10 /** @file station_gui.cpp The GUI for stations. */
12 #include "stdafx.h"
13 #include "debug.h"
14 #include "gui.h"
15 #include "textbuf_gui.h"
16 #include "company_func.h"
17 #include "command_func.h"
18 #include "vehicle_gui.h"
19 #include "cargotype.h"
20 #include "station_gui.h"
21 #include "strings_func.h"
22 #include "string_func.h"
23 #include "window_func.h"
24 #include "viewport_func.h"
25 #include "widgets/dropdown_func.h"
26 #include "station_base.h"
27 #include "waypoint_base.h"
28 #include "tilehighlight_func.h"
29 #include "company_base.h"
30 #include "sortlist_type.h"
31 #include "core/geometry_func.hpp"
32 #include "vehiclelist.h"
33 #include "core/math_func.hpp"
34 #include "overlay_cmd.h"
35 #include "town.h"
36 #include "linkgraph/linkgraph.h"
37 #include "zoom_func.h"
38 #include "newgrf_cargo.h"
39 #include "departures_gui.h"
40 #include "graph_gui.h"
42 #include "widgets/station_widget.h"
44 #include "table/strings.h"
46 #include <set>
47 #include <vector>
48 #include <cmath>
50 #include "safeguards.h"
52 /**
53 * Calculates and draws the accepted or supplied cargo around the selected tile(s)
54 * @param left x position where the string is to be drawn
55 * @param right the right most position to draw on
56 * @param top y position where the string is to be drawn
57 * @param sct which type of cargo is to be displayed (passengers/non-passengers)
58 * @param rad radius around selected tile(s) to be searched
59 * @param supplies if supplied cargoes should be drawn, else accepted cargoes
60 * @return Returns the y value below the string that was drawn
62 int DrawStationCoverageAreaText(int left, int right, int top, StationCoverageType sct, int rad, bool supplies)
64 TileIndex tile = TileVirtXY(_thd.pos.x, _thd.pos.y);
65 uint32 cargo_mask = 0;
66 if (_thd.drawstyle == HT_RECT && tile < MapSize()) {
67 CargoArray cargoes;
68 if (supplies) {
69 cargoes = GetProductionAroundTiles(tile, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE, rad);
70 } else {
71 cargoes = GetAcceptanceAroundTiles(tile, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE, rad);
74 /* Convert cargo counts to a set of cargo bits, and draw the result. */
75 for (CargoID i = 0; i < NUM_CARGO; i++) {
76 switch (sct) {
77 case SCT_PASSENGERS_ONLY: if (!IsCargoInClass(i, CC_PASSENGERS)) continue; break;
78 case SCT_NON_PASSENGERS_ONLY: if (IsCargoInClass(i, CC_PASSENGERS)) continue; break;
79 case SCT_ALL: break;
80 default: NOT_REACHED();
82 if (cargoes[i] >= (supplies ? 1U : 8U)) SetBit(cargo_mask, i);
85 SetDParam(0, cargo_mask);
86 return DrawStringMultiLine(left, right, top, INT32_MAX, supplies ? STR_STATION_BUILD_SUPPLIES_CARGO : STR_STATION_BUILD_ACCEPTS_CARGO);
89 /**
90 * Check whether we need to redraw the station coverage text.
91 * If it is needed actually make the window for redrawing.
92 * @param w the window to check.
94 void CheckRedrawStationCoverage(const Window *w)
96 if (_thd.dirty & 1) {
97 _thd.dirty &= ~1;
98 w->SetDirty();
103 * Draw small boxes of cargo amount and ratings data at the given
104 * coordinates. If amount exceeds 576 units, it is shown 'full', same
105 * goes for the rating: at above 90% orso (224) it is also 'full'
107 * @param left left most coordinate to draw the box at
108 * @param right right most coordinate to draw the box at
109 * @param y coordinate to draw the box at
110 * @param type Cargo type
111 * @param amount Cargo amount
112 * @param rating ratings data for that particular cargo
114 * @note Each cargo-bar is 16 pixels wide and 6 pixels high
115 * @note Each rating 14 pixels wide and 1 pixel high and is 1 pixel below the cargo-bar
117 static void StationsWndShowStationRating(int left, int right, int y, CargoID type, uint amount, byte rating)
119 static const uint units_full = 576; ///< number of units to show station as 'full'
120 static const uint rating_full = 224; ///< rating needed so it is shown as 'full'
122 const CargoSpec *cs = CargoSpec::Get(type);
123 if (!cs->IsValid()) return;
125 int colour = cs->rating_colour;
126 TextColour tc = GetContrastColour(colour);
127 uint w = (minu(amount, units_full) + 5) / 36;
129 int height = GetCharacterHeight(FS_SMALL);
131 /* Draw total cargo (limited) on station (fits into 16 pixels) */
132 if (w != 0) GfxFillRect(left, y, left + w - 1, y + height, colour);
134 /* Draw a one pixel-wide bar of additional cargo meter, useful
135 * for stations with only a small amount (<=30) */
136 if (w == 0) {
137 uint rest = amount / 5;
138 if (rest != 0) {
139 w += left;
140 GfxFillRect(w, y + height - rest, w, y + height, colour);
144 DrawString(left + 1, right, y, cs->abbrev, tc);
146 /* Draw green/red ratings bar (fits into 14 pixels) */
147 y += height + 2;
148 GfxFillRect(left + 1, y, left + 14, y, PC_RED);
149 rating = minu(rating, rating_full) / 16;
150 if (rating != 0) GfxFillRect(left + 1, y, left + rating, y, PC_GREEN);
153 typedef GUIList<const Station*> GUIStationList;
156 * The list of stations per company.
158 class CompanyStationsWindow : public Window
160 protected:
161 /* Runtime saved values */
162 static Listing last_sorting;
163 static byte facilities; // types of stations of interest
164 static bool include_empty; // whether we should include stations without waiting cargo
165 static const uint32 cargo_filter_max;
166 static uint32 cargo_filter; // bitmap of cargo types to include
167 static const Station *last_station;
169 /* Constants for sorting stations */
170 static const StringID sorter_names[];
171 static GUIStationList::SortFunction * const sorter_funcs[];
173 GUIStationList stations;
174 Scrollbar *vscroll;
177 * (Re)Build station list
179 * @param owner company whose stations are to be in list
181 void BuildStationsList(const Owner owner)
183 if (!this->stations.NeedRebuild()) return;
185 DEBUG(misc, 3, "Building station list for company %d", owner);
187 this->stations.Clear();
189 const Station *st;
190 FOR_ALL_STATIONS(st) {
191 if (st->owner == owner || (st->owner == OWNER_NONE && HasStationInUse(st->index, true, owner))) {
192 if (this->facilities & st->facilities) { // only stations with selected facilities
193 int num_waiting_cargo = 0;
194 for (CargoID j = 0; j < NUM_CARGO; j++) {
195 if (st->goods[j].HasRating()) {
196 num_waiting_cargo++; // count number of waiting cargo
197 if (HasBit(this->cargo_filter, j)) {
198 *this->stations.Append() = st;
199 break;
203 /* stations without waiting cargo */
204 if (num_waiting_cargo == 0 && this->include_empty) {
205 *this->stations.Append() = st;
211 this->stations.Compact();
212 this->stations.RebuildDone();
214 this->vscroll->SetCount(this->stations.Length()); // Update the scrollbar
217 /** Sort stations by their name */
218 static int CDECL StationNameSorter(const Station * const *a, const Station * const *b)
220 static char buf_cache[64];
221 char buf[64];
223 SetDParam(0, (*a)->index);
224 GetString(buf, STR_STATION_NAME, lastof(buf));
226 if (*b != last_station) {
227 last_station = *b;
228 SetDParam(0, (*b)->index);
229 GetString(buf_cache, STR_STATION_NAME, lastof(buf_cache));
232 int r = strnatcmp(buf, buf_cache); // Sort by name (natural sorting).
233 if (r == 0) return (*a)->index - (*b)->index;
234 return r;
237 /** Sort stations by their type */
238 static int CDECL StationTypeSorter(const Station * const *a, const Station * const *b)
240 return (*a)->facilities - (*b)->facilities;
243 /** Sort stations by their waiting cargo */
244 static int CDECL StationWaitingTotalSorter(const Station * const *a, const Station * const *b)
246 int diff = 0;
248 CargoID j;
249 FOR_EACH_SET_CARGO_ID(j, cargo_filter) {
250 diff += (*a)->goods[j].cargo.TotalCount() - (*b)->goods[j].cargo.TotalCount();
253 return diff;
256 /** Sort stations by their available waiting cargo */
257 static int CDECL StationWaitingAvailableSorter(const Station * const *a, const Station * const *b)
259 int diff = 0;
261 CargoID j;
262 FOR_EACH_SET_CARGO_ID(j, cargo_filter) {
263 diff += (*a)->goods[j].cargo.AvailableCount() - (*b)->goods[j].cargo.AvailableCount();
266 return diff;
269 /** Sort stations by their rating */
270 static int CDECL StationRatingMaxSorter(const Station * const *a, const Station * const *b)
272 byte maxr1 = 0;
273 byte maxr2 = 0;
275 CargoID j;
276 FOR_EACH_SET_CARGO_ID(j, cargo_filter) {
277 if ((*a)->goods[j].HasRating()) maxr1 = max(maxr1, (*a)->goods[j].rating);
278 if ((*b)->goods[j].HasRating()) maxr2 = max(maxr2, (*b)->goods[j].rating);
281 return maxr1 - maxr2;
284 /** Sort stations by their rating */
285 static int CDECL StationRatingMinSorter(const Station * const *a, const Station * const *b)
287 byte minr1 = 255;
288 byte minr2 = 255;
290 for (CargoID j = 0; j < NUM_CARGO; j++) {
291 if (!HasBit(cargo_filter, j)) continue;
292 if ((*a)->goods[j].HasRating()) minr1 = min(minr1, (*a)->goods[j].rating);
293 if ((*b)->goods[j].HasRating()) minr2 = min(minr2, (*b)->goods[j].rating);
296 return -(minr1 - minr2);
299 /** Sort the stations list */
300 void SortStationsList()
302 if (!this->stations.Sort()) return;
304 /* Reset name sorter sort cache */
305 this->last_station = nullptr;
307 /* Set the modified widget dirty */
308 this->SetWidgetDirty(WID_STL_LIST);
311 public:
312 CompanyStationsWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
314 this->stations.SetListing(this->last_sorting);
315 this->stations.SetSortFuncs(this->sorter_funcs);
316 this->stations.ForceRebuild();
317 this->stations.NeedResort();
318 this->SortStationsList();
320 this->CreateNestedTree();
321 this->vscroll = this->GetScrollbar(WID_STL_SCROLLBAR);
322 this->FinishInitNested(window_number);
323 this->owner = (Owner)this->window_number;
325 const CargoSpec *cs;
326 FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
327 if (!HasBit(this->cargo_filter, cs->Index())) continue;
328 this->LowerWidget(WID_STL_CARGOSTART + index);
331 if (this->cargo_filter == this->cargo_filter_max) this->cargo_filter = _cargo_mask;
333 for (uint i = 0; i < 5; i++) {
334 if (HasBit(this->facilities, i)) this->LowerWidget(i + WID_STL_TRAIN);
336 this->SetWidgetLoweredState(WID_STL_NOCARGOWAITING, this->include_empty);
338 this->GetWidget<NWidgetCore>(WID_STL_SORTDROPBTN)->widget_data = this->sorter_names[this->stations.SortType()];
341 ~CompanyStationsWindow()
343 this->last_sorting = this->stations.GetListing();
346 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
348 switch (widget) {
349 case WID_STL_SORTBY: {
350 Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
351 d.width += padding.width + Window::SortButtonWidth() * 2; // Doubled since the string is centred and it also looks better.
352 d.height += padding.height;
353 *size = maxdim(*size, d);
354 break;
357 case WID_STL_SORTDROPBTN: {
358 Dimension d = {0, 0};
359 for (int i = 0; this->sorter_names[i] != INVALID_STRING_ID; i++) {
360 d = maxdim(d, GetStringBoundingBox(this->sorter_names[i]));
362 d.width += padding.width;
363 d.height += padding.height;
364 *size = maxdim(*size, d);
365 break;
368 case WID_STL_LIST:
369 resize->height = FONT_HEIGHT_NORMAL;
370 size->height = WD_FRAMERECT_TOP + 5 * resize->height + WD_FRAMERECT_BOTTOM;
371 break;
373 case WID_STL_TRAIN:
374 case WID_STL_TRUCK:
375 case WID_STL_BUS:
376 case WID_STL_AIRPLANE:
377 case WID_STL_SHIP:
378 size->height = max<uint>(FONT_HEIGHT_SMALL, 10) + padding.height;
379 break;
381 case WID_STL_CARGOALL:
382 case WID_STL_FACILALL:
383 case WID_STL_NOCARGOWAITING: {
384 Dimension d = GetStringBoundingBox(widget == WID_STL_NOCARGOWAITING ? STR_ABBREV_NONE : STR_ABBREV_ALL);
385 d.width += padding.width + 2;
386 d.height += padding.height;
387 *size = maxdim(*size, d);
388 break;
391 default:
392 if (widget >= WID_STL_CARGOSTART) {
393 Dimension d = GetStringBoundingBox(_sorted_cargo_specs[widget - WID_STL_CARGOSTART]->abbrev);
394 d.width += padding.width + 2;
395 d.height += padding.height;
396 *size = maxdim(*size, d);
398 break;
402 virtual void OnPaint()
404 this->BuildStationsList((Owner)this->window_number);
405 this->SortStationsList();
407 this->DrawWidgets();
410 virtual void DrawWidget(const Rect &r, int widget) const
412 switch (widget) {
413 case WID_STL_SORTBY:
414 /* draw arrow pointing up/down for ascending/descending sorting */
415 this->DrawSortButtonState(WID_STL_SORTBY, this->stations.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
416 break;
418 case WID_STL_LIST: {
419 bool rtl = _current_text_dir == TD_RTL;
420 int max = min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->stations.Length());
421 int y = r.top + WD_FRAMERECT_TOP;
422 for (int i = this->vscroll->GetPosition(); i < max; ++i) { // do until max number of stations of owner
423 const Station *st = this->stations[i];
424 assert(st->xy != INVALID_TILE);
426 /* Do not do the complex check HasStationInUse here, it may be even false
427 * when the order had been removed and the station list hasn't been removed yet */
428 assert(st->owner == owner || st->owner == OWNER_NONE);
430 SetDParam(0, st->index);
431 SetDParam(1, st->facilities);
432 int x = DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_LIST_STATION);
433 x += rtl ? -5 : 5;
435 /* show cargo waiting and station ratings */
436 for (uint j = 0; j < _sorted_standard_cargo_specs_size; j++) {
437 CargoID cid = _sorted_cargo_specs[j]->Index();
438 if (st->goods[cid].cargo.TotalCount() > 0) {
439 /* For RTL we work in exactly the opposite direction. So
440 * decrement the space needed first, then draw to the left
441 * instead of drawing to the left and then incrementing
442 * the space. */
443 if (rtl) {
444 x -= 20;
445 if (x < r.left + WD_FRAMERECT_LEFT) break;
447 StationsWndShowStationRating(x, x + 16, y, cid, st->goods[cid].cargo.TotalCount(), st->goods[cid].rating);
448 if (!rtl) {
449 x += 20;
450 if (x > r.right - WD_FRAMERECT_RIGHT) break;
454 y += FONT_HEIGHT_NORMAL;
457 if (this->vscroll->GetCount() == 0) { // company has no stations
458 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_LIST_NONE);
459 return;
461 break;
464 case WID_STL_NOCARGOWAITING: {
465 int cg_ofst = this->IsWidgetLowered(widget) ? 2 : 1;
466 DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, STR_ABBREV_NONE, TC_BLACK, SA_HOR_CENTER);
467 break;
470 case WID_STL_CARGOALL: {
471 int cg_ofst = this->IsWidgetLowered(widget) ? 2 : 1;
472 DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, STR_ABBREV_ALL, TC_BLACK, SA_HOR_CENTER);
473 break;
476 case WID_STL_FACILALL: {
477 int cg_ofst = this->IsWidgetLowered(widget) ? 2 : 1;
478 DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, STR_ABBREV_ALL, TC_BLACK, SA_HOR_CENTER);
479 break;
482 default:
483 if (widget >= WID_STL_CARGOSTART) {
484 const CargoSpec *cs = _sorted_cargo_specs[widget - WID_STL_CARGOSTART];
485 int cg_ofst = HasBit(this->cargo_filter, cs->Index()) ? 2 : 1;
486 GfxFillRect(r.left + cg_ofst, r.top + cg_ofst, r.right - 2 + cg_ofst, r.bottom - 2 + cg_ofst, cs->rating_colour);
487 TextColour tc = GetContrastColour(cs->rating_colour);
488 DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, cs->abbrev, tc, SA_HOR_CENTER);
490 break;
494 virtual void SetStringParameters(int widget) const
496 if (widget == WID_STL_CAPTION) {
497 SetDParam(0, this->window_number);
498 SetDParam(1, this->vscroll->GetCount());
502 virtual void OnClick(Point pt, int widget, int click_count)
504 switch (widget) {
505 case WID_STL_LIST: {
506 uint id_v = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_STL_LIST, 0, FONT_HEIGHT_NORMAL);
507 if (id_v >= this->stations.Length()) return; // click out of list bound
509 const Station *st = this->stations[id_v];
510 /* do not check HasStationInUse - it is slow and may be invalid */
511 assert(st->owner == (Owner)this->window_number || st->owner == OWNER_NONE);
513 if (_ctrl_pressed) {
514 ShowExtraViewPortWindow(st->xy);
515 } else {
516 ScrollMainWindowToTile(st->xy);
518 break;
521 case WID_STL_TRAIN:
522 case WID_STL_TRUCK:
523 case WID_STL_BUS:
524 case WID_STL_AIRPLANE:
525 case WID_STL_SHIP:
526 if (_ctrl_pressed) {
527 ToggleBit(this->facilities, widget - WID_STL_TRAIN);
528 this->ToggleWidgetLoweredState(widget);
529 } else {
530 uint i;
531 FOR_EACH_SET_BIT(i, this->facilities) {
532 this->RaiseWidget(i + WID_STL_TRAIN);
534 this->facilities = 1 << (widget - WID_STL_TRAIN);
535 this->LowerWidget(widget);
537 this->stations.ForceRebuild();
538 this->SetDirty();
539 break;
541 case WID_STL_FACILALL:
542 for (uint i = WID_STL_TRAIN; i <= WID_STL_SHIP; i++) {
543 this->LowerWidget(i);
546 this->facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK;
547 this->stations.ForceRebuild();
548 this->SetDirty();
549 break;
551 case WID_STL_CARGOALL: {
552 for (uint i = 0; i < _sorted_standard_cargo_specs_size; i++) {
553 this->LowerWidget(WID_STL_CARGOSTART + i);
555 this->LowerWidget(WID_STL_NOCARGOWAITING);
557 this->cargo_filter = _cargo_mask;
558 this->include_empty = true;
559 this->stations.ForceRebuild();
560 this->SetDirty();
561 break;
564 case WID_STL_SORTBY: // flip sorting method asc/desc
565 this->stations.ToggleSortOrder();
566 this->SetDirty();
567 break;
569 case WID_STL_SORTDROPBTN: // select sorting criteria dropdown menu
570 ShowDropDownMenu(this, this->sorter_names, this->stations.SortType(), WID_STL_SORTDROPBTN, 0, 0);
571 break;
573 case WID_STL_NOCARGOWAITING:
574 if (_ctrl_pressed) {
575 this->include_empty = !this->include_empty;
576 this->ToggleWidgetLoweredState(WID_STL_NOCARGOWAITING);
577 } else {
578 for (uint i = 0; i < _sorted_standard_cargo_specs_size; i++) {
579 this->RaiseWidget(WID_STL_CARGOSTART + i);
582 this->cargo_filter = 0;
583 this->include_empty = true;
585 this->LowerWidget(WID_STL_NOCARGOWAITING);
587 this->stations.ForceRebuild();
588 this->SetDirty();
589 break;
591 default:
592 if (widget >= WID_STL_CARGOSTART) { // change cargo_filter
593 /* Determine the selected cargo type */
594 const CargoSpec *cs = _sorted_cargo_specs[widget - WID_STL_CARGOSTART];
596 if (_ctrl_pressed) {
597 ToggleBit(this->cargo_filter, cs->Index());
598 this->ToggleWidgetLoweredState(widget);
599 } else {
600 for (uint i = 0; i < _sorted_standard_cargo_specs_size; i++) {
601 this->RaiseWidget(WID_STL_CARGOSTART + i);
603 this->RaiseWidget(WID_STL_NOCARGOWAITING);
605 this->cargo_filter = 0;
606 this->include_empty = false;
608 SetBit(this->cargo_filter, cs->Index());
609 this->LowerWidget(widget);
611 this->stations.ForceRebuild();
612 this->SetDirty();
614 break;
618 virtual void OnDropdownSelect(int widget, int index)
620 if (this->stations.SortType() != index) {
621 this->stations.SetSortType(index);
623 /* Display the current sort variant */
624 this->GetWidget<NWidgetCore>(WID_STL_SORTDROPBTN)->widget_data = this->sorter_names[this->stations.SortType()];
626 this->SetDirty();
630 virtual void OnTick()
632 if (_pause_mode != PM_UNPAUSED) return;
633 if (this->stations.NeedResort()) {
634 DEBUG(misc, 3, "Periodic rebuild station list company %d", this->window_number);
635 this->SetDirty();
639 virtual void OnResize()
641 this->vscroll->SetCapacityFromWidget(this, WID_STL_LIST, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
645 * Some data on this window has become invalid.
646 * @param data Information about the changed data.
647 * @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.
649 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
651 if (data == 0) {
652 /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
653 this->stations.ForceRebuild();
654 } else {
655 this->stations.ForceResort();
660 Listing CompanyStationsWindow::last_sorting = {false, 0};
661 byte CompanyStationsWindow::facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK;
662 bool CompanyStationsWindow::include_empty = true;
663 const uint32 CompanyStationsWindow::cargo_filter_max = UINT32_MAX;
664 uint32 CompanyStationsWindow::cargo_filter = UINT32_MAX;
665 const Station *CompanyStationsWindow::last_station = nullptr;
667 /* Availible station sorting functions */
668 GUIStationList::SortFunction * const CompanyStationsWindow::sorter_funcs[] = {
669 &StationNameSorter,
670 &StationTypeSorter,
671 &StationWaitingTotalSorter,
672 &StationWaitingAvailableSorter,
673 &StationRatingMaxSorter,
674 &StationRatingMinSorter
677 /* Names of the sorting functions */
678 const StringID CompanyStationsWindow::sorter_names[] = {
679 STR_SORT_BY_NAME,
680 STR_SORT_BY_FACILITY,
681 STR_SORT_BY_WAITING_TOTAL,
682 STR_SORT_BY_WAITING_AVAILABLE,
683 STR_SORT_BY_RATING_MAX,
684 STR_SORT_BY_RATING_MIN,
685 INVALID_STRING_ID
689 * Make a horizontal row of cargo buttons, starting at widget #WID_STL_CARGOSTART.
690 * @param biggest_index Pointer to store biggest used widget number of the buttons.
691 * @return Horizontal row.
693 static NWidgetBase *CargoWidgets(int *biggest_index)
695 NWidgetHorizontal *container = new NWidgetHorizontal();
697 for (uint i = 0; i < _sorted_standard_cargo_specs_size; i++) {
698 NWidgetBackground *panel = new NWidgetBackground(WWT_PANEL, COLOUR_GREY, WID_STL_CARGOSTART + i);
699 panel->SetMinimalSize(14, 11);
700 panel->SetResize(0, 0);
701 panel->SetFill(0, 1);
702 panel->SetDataTip(0, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE);
703 container->Add(panel);
705 *biggest_index = WID_STL_CARGOSTART + _sorted_standard_cargo_specs_size;
706 return container;
709 static const NWidgetPart _nested_company_stations_widgets[] = {
710 NWidget(NWID_HORIZONTAL),
711 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
712 NWidget(WWT_CAPTION, COLOUR_GREY, WID_STL_CAPTION), SetDataTip(STR_STATION_LIST_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
713 NWidget(WWT_SHADEBOX, COLOUR_GREY),
714 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
715 NWidget(WWT_STICKYBOX, COLOUR_GREY),
716 EndContainer(),
717 NWidget(NWID_HORIZONTAL),
718 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),
719 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),
720 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),
721 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),
722 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),
723 NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_STL_FACILALL), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_SELECT_ALL_FACILITIES), SetFill(0, 1),
724 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(5, 11), SetFill(0, 1), EndContainer(),
725 NWidgetFunction(CargoWidgets),
726 NWidget(WWT_PANEL, COLOUR_GREY, WID_STL_NOCARGOWAITING), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_NO_WAITING_CARGO), SetFill(0, 1), EndContainer(),
727 NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_STL_CARGOALL), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_SELECT_ALL_TYPES), SetFill(0, 1),
728 NWidget(WWT_PANEL, COLOUR_GREY), SetDataTip(0x0, STR_NULL), SetResize(1, 0), SetFill(1, 1), EndContainer(),
729 EndContainer(),
730 NWidget(NWID_HORIZONTAL),
731 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_STL_SORTBY), SetMinimalSize(81, 12), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
732 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_STL_SORTDROPBTN), SetMinimalSize(163, 12), SetDataTip(STR_SORT_BY_NAME, STR_TOOLTIP_SORT_CRITERIA), // widget_data gets overwritten.
733 NWidget(WWT_PANEL, COLOUR_GREY), SetDataTip(0x0, STR_NULL), SetResize(1, 0), SetFill(1, 1), EndContainer(),
734 EndContainer(),
735 NWidget(NWID_HORIZONTAL),
736 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(),
737 NWidget(NWID_VERTICAL),
738 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_STL_SCROLLBAR),
739 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
740 EndContainer(),
741 EndContainer(),
744 static WindowDesc _company_stations_desc(
745 WDP_AUTO, "list_stations", 358, 162,
746 WC_STATION_LIST, WC_NONE,
748 _nested_company_stations_widgets, lengthof(_nested_company_stations_widgets)
752 * Opens window with list of company's stations
754 * @param company whose stations' list show
756 void ShowCompanyStations(CompanyID company)
758 if (!Company::IsValidID(company)) return;
760 AllocateWindowDescFront<CompanyStationsWindow>(&_company_stations_desc, company);
763 static const NWidgetPart _nested_station_view_widgets[] = {
764 NWidget(NWID_HORIZONTAL),
765 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
766 NWidget(WWT_CAPTION, COLOUR_GREY, WID_SV_CAPTION), SetDataTip(STR_STATION_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
767 NWidget(WWT_SHADEBOX, COLOUR_GREY),
768 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
769 NWidget(WWT_STICKYBOX, COLOUR_GREY),
770 EndContainer(),
771 NWidget(NWID_HORIZONTAL),
772 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_SORT_ORDER), SetMinimalSize(81, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
773 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_SV_SORT_BY), SetMinimalSize(168, 12), SetResize(1, 0), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
774 EndContainer(),
775 NWidget(NWID_HORIZONTAL),
776 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_SV_GROUP), SetMinimalSize(81, 12), SetFill(1, 1), SetDataTip(STR_STATION_VIEW_GROUP, 0x0),
777 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_SV_GROUP_BY), SetMinimalSize(168, 12), SetResize(1, 0), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_GROUP_ORDER),
778 EndContainer(),
779 NWidget(NWID_HORIZONTAL),
780 NWidget(WWT_PANEL, COLOUR_GREY, WID_SV_WAITING), SetMinimalSize(237, 44), SetResize(1, 10), SetScrollbar(WID_SV_SCROLLBAR), EndContainer(),
781 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_SV_SCROLLBAR),
782 EndContainer(),
783 NWidget(WWT_PANEL, COLOUR_GREY, WID_SV_ACCEPT_RATING_LIST), SetMinimalSize(249, 23), SetResize(1, 0), EndContainer(),
784 NWidget(NWID_HORIZONTAL),
785 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
786 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_COVERAGE), SetMinimalSize(60, 12), SetResize(1, 0), SetFill(1, 1),
787 SetDataTip(STR_BUTTON_COVERAGE, STR_STATION_VIEW_COVERAGE_TIP),
788 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_LOCATION), SetMinimalSize(45, 12), SetResize(1, 0), SetFill(1, 1),
789 SetDataTip(STR_BUTTON_LOCATION, STR_STATION_VIEW_CENTER_TOOLTIP),
790 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_ACCEPTS_RATINGS), SetMinimalSize(46, 12), SetResize(1, 0), SetFill(1, 1),
791 SetDataTip(STR_STATION_VIEW_RATINGS_BUTTON, STR_STATION_VIEW_RATINGS_TOOLTIP),
792 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_RENAME), SetMinimalSize(45, 12), SetResize(1, 0), SetFill(1, 1),
793 SetDataTip(STR_BUTTON_RENAME, STR_STATION_VIEW_RENAME_TOOLTIP),
794 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_HISTORY), SetMinimalSize(60, 12), SetResize(1, 0), SetFill(1, 1),
795 SetDataTip(STR_STATION_VIEW_HISTORY_BUTTON, STR_STATION_VIEW_HISTORY_TOOLTIP),
796 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_DEPARTURES), SetMinimalSize(80, 12), SetResize(1, 0), SetFill(1, 1),
797 SetDataTip(STR_STATION_VIEW_DEPARTURES_BUTTON, STR_STATION_VIEW_DEPARTURES_TOOLTIP),
798 EndContainer(),
799 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_SV_CLOSE_AIRPORT), SetMinimalSize(45, 12), SetResize(1, 0), SetFill(1, 1),
800 SetDataTip(STR_STATION_VIEW_CLOSE_AIRPORT, STR_STATION_VIEW_CLOSE_AIRPORT_TOOLTIP),
801 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_TRAINS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_TRAIN, STR_STATION_VIEW_SCHEDULED_TRAINS_TOOLTIP),
802 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_ROADVEHS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_LORRY, STR_STATION_VIEW_SCHEDULED_ROAD_VEHICLES_TOOLTIP),
803 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_SHIPS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_SHIP, STR_STATION_VIEW_SCHEDULED_SHIPS_TOOLTIP),
804 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_PLANES), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_PLANE, STR_STATION_VIEW_SCHEDULED_AIRCRAFT_TOOLTIP),
805 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
806 EndContainer(),
810 * Draws icons of waiting cargo in the StationView window
812 * @param i type of cargo
813 * @param waiting number of waiting units
814 * @param left left most coordinate to draw on
815 * @param right right most coordinate to draw on
816 * @param y y coordinate
817 * @param width the width of the view
819 static void DrawCargoIcons(CargoID i, uint waiting, int left, int right, int y)
821 int width = ScaleGUITrad(10);
822 uint num = min((waiting + (width / 2)) / width, (right - left) / width); // maximum is width / 10 icons so it won't overflow
823 if (num == 0) return;
825 SpriteID sprite = CargoSpec::Get(i)->GetCargoIcon();
827 int x = _current_text_dir == TD_RTL ? left : right - num * width;
828 do {
829 DrawSprite(sprite, PAL_NONE, x, y);
830 x += width;
831 } while (--num);
834 enum SortOrder {
835 SO_DESCENDING,
836 SO_ASCENDING
839 class CargoDataEntry;
841 enum CargoSortType {
842 ST_AS_GROUPING, ///< by the same principle the entries are being grouped
843 ST_COUNT, ///< by amount of cargo
844 ST_STATION_STRING, ///< by station name
845 ST_STATION_ID, ///< by station id
846 ST_CARGO_ID, ///< by cargo id
849 class CargoSorter {
850 public:
851 CargoSorter(CargoSortType t = ST_STATION_ID, SortOrder o = SO_ASCENDING) : type(t), order(o) {}
852 CargoSortType GetSortType() {return this->type;}
853 bool operator()(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const;
855 private:
856 CargoSortType type;
857 SortOrder order;
859 template<class Tid>
860 bool SortId(Tid st1, Tid st2) const;
861 bool SortCount(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const;
862 bool SortStation (StationID st1, StationID st2) const;
865 typedef std::set<CargoDataEntry *, CargoSorter> CargoDataSet;
868 * A cargo data entry representing one possible row in the station view window's
869 * top part. Cargo data entries form a tree where each entry can have several
870 * children. Parents keep track of the sums of their childrens' cargo counts.
872 class CargoDataEntry {
873 public:
874 CargoDataEntry();
875 ~CargoDataEntry();
878 * Insert a new child or retrieve an existing child using a station ID as ID.
879 * @param station ID of the station for which an entry shall be created or retrieved
880 * @return a child entry associated with the given station.
882 CargoDataEntry *InsertOrRetrieve(StationID station)
884 return this->InsertOrRetrieve<StationID>(station);
888 * Insert a new child or retrieve an existing child using a cargo ID as ID.
889 * @param cargo ID of the cargo for which an entry shall be created or retrieved
890 * @return a child entry associated with the given cargo.
892 CargoDataEntry *InsertOrRetrieve(CargoID cargo)
894 return this->InsertOrRetrieve<CargoID>(cargo);
897 void Update(uint count);
900 * Remove a child associated with the given station.
901 * @param station ID of the station for which the child should be removed.
903 void Remove(StationID station)
905 CargoDataEntry t(station);
906 this->Remove(&t);
910 * Remove a child associated with the given cargo.
911 * @param cargo ID of the cargo for which the child should be removed.
913 void Remove(CargoID cargo)
915 CargoDataEntry t(cargo);
916 this->Remove(&t);
920 * Retrieve a child for the given station. Return nullptr if it doesn't exist.
921 * @param station ID of the station the child we're looking for is associated with.
922 * @return a child entry for the given station or nullptr.
924 CargoDataEntry *Retrieve(StationID station) const
926 CargoDataEntry t(station);
927 return this->Retrieve(this->children->find(&t));
931 * Retrieve a child for the given cargo. Return nullptr if it doesn't exist.
932 * @param cargo ID of the cargo the child we're looking for is associated with.
933 * @return a child entry for the given cargo or nullptr.
935 CargoDataEntry *Retrieve(CargoID cargo) const
937 CargoDataEntry t(cargo);
938 return this->Retrieve(this->children->find(&t));
941 void Resort(CargoSortType type, SortOrder order);
944 * Get the station ID for this entry.
946 StationID GetStation() const { return this->station; }
949 * Get the cargo ID for this entry.
951 CargoID GetCargo() const { return this->cargo; }
954 * Get the cargo count for this entry.
956 uint GetCount() const { return this->count; }
959 * Get the parent entry for this entry.
961 CargoDataEntry *GetParent() const { return this->parent; }
964 * Get the number of children for this entry.
966 uint GetNumChildren() const { return this->num_children; }
969 * Get an iterator pointing to the begin of the set of children.
971 CargoDataSet::iterator Begin() const { return this->children->begin(); }
974 * Get an iterator pointing to the end of the set of children.
976 CargoDataSet::iterator End() const { return this->children->end(); }
979 * Has this entry transfers.
981 bool HasTransfers() const { return this->transfers; }
984 * Set the transfers state.
986 void SetTransfers(bool value) { this->transfers = value; }
988 void Clear();
989 private:
991 CargoDataEntry(StationID st, uint c, CargoDataEntry *p);
992 CargoDataEntry(CargoID car, uint c, CargoDataEntry *p);
993 CargoDataEntry(StationID st);
994 CargoDataEntry(CargoID car);
996 CargoDataEntry *Retrieve(CargoDataSet::iterator i) const;
998 template<class Tid>
999 CargoDataEntry *InsertOrRetrieve(Tid s);
1001 void Remove(CargoDataEntry *comp);
1002 void IncrementSize();
1004 CargoDataEntry *parent; ///< the parent of this entry.
1005 const union {
1006 StationID station; ///< ID of the station this entry is associated with.
1007 struct {
1008 CargoID cargo; ///< ID of the cargo this entry is associated with.
1009 bool transfers; ///< If there are transfers for this cargo.
1012 uint num_children; ///< the number of subentries belonging to this entry.
1013 uint count; ///< sum of counts of all children or amount of cargo for this entry.
1014 CargoDataSet *children; ///< the children of this entry.
1017 CargoDataEntry::CargoDataEntry() :
1018 parent(nullptr),
1019 station(INVALID_STATION),
1020 num_children(0),
1021 count(0),
1022 children(new CargoDataSet(CargoSorter(ST_CARGO_ID)))
1025 CargoDataEntry::CargoDataEntry(CargoID cargo, uint count, CargoDataEntry *parent) :
1026 parent(parent),
1027 cargo(cargo),
1028 num_children(0),
1029 count(count),
1030 children(new CargoDataSet)
1033 CargoDataEntry::CargoDataEntry(StationID station, uint count, CargoDataEntry *parent) :
1034 parent(parent),
1035 station(station),
1036 num_children(0),
1037 count(count),
1038 children(new CargoDataSet)
1041 CargoDataEntry::CargoDataEntry(StationID station) :
1042 parent(nullptr),
1043 station(station),
1044 num_children(0),
1045 count(0),
1046 children(nullptr)
1049 CargoDataEntry::CargoDataEntry(CargoID cargo) :
1050 parent(nullptr),
1051 cargo(cargo),
1052 num_children(0),
1053 count(0),
1054 children(nullptr)
1057 CargoDataEntry::~CargoDataEntry()
1059 this->Clear();
1060 delete this->children;
1064 * Delete all subentries, reset count and num_children and adapt parent's count.
1066 void CargoDataEntry::Clear()
1068 if (this->children != nullptr) {
1069 for (CargoDataSet::iterator i = this->children->begin(); i != this->children->end(); ++i) {
1070 assert(*i != this);
1071 delete *i;
1073 this->children->clear();
1075 if (this->parent != nullptr) this->parent->count -= this->count;
1076 this->count = 0;
1077 this->num_children = 0;
1081 * Remove a subentry from this one and delete it.
1082 * @param child the entry to be removed. This may also be a synthetic entry
1083 * which only contains the ID of the entry to be removed. In this case child is
1084 * not deleted.
1086 void CargoDataEntry::Remove(CargoDataEntry *child)
1088 CargoDataSet::iterator i = this->children->find(child);
1089 if (i != this->children->end()) {
1090 delete *i;
1091 this->children->erase(i);
1096 * Retrieve a subentry or insert it if it doesn't exist, yet.
1097 * @tparam ID type of ID: either StationID or CargoID
1098 * @param child_id ID of the child to be inserted or retrieved.
1099 * @return the new or retrieved subentry
1101 template<class Tid>
1102 CargoDataEntry *CargoDataEntry::InsertOrRetrieve(Tid child_id)
1104 CargoDataEntry tmp(child_id);
1105 CargoDataSet::iterator i = this->children->find(&tmp);
1106 if (i == this->children->end()) {
1107 IncrementSize();
1108 return *(this->children->insert(new CargoDataEntry(child_id, 0, this)).first);
1109 } else {
1110 CargoDataEntry *ret = *i;
1111 assert(this->children->value_comp().GetSortType() != ST_COUNT);
1112 return ret;
1117 * Update the count for this entry and propagate the change to the parent entry
1118 * if there is one.
1119 * @param count the amount to be added to this entry
1121 void CargoDataEntry::Update(uint count)
1123 this->count += count;
1124 if (this->parent != nullptr) this->parent->Update(count);
1128 * Increment
1130 void CargoDataEntry::IncrementSize()
1132 ++this->num_children;
1133 if (this->parent != nullptr) this->parent->IncrementSize();
1136 void CargoDataEntry::Resort(CargoSortType type, SortOrder order)
1138 CargoDataSet *new_subs = new CargoDataSet(this->children->begin(), this->children->end(), CargoSorter(type, order));
1139 delete this->children;
1140 this->children = new_subs;
1143 CargoDataEntry *CargoDataEntry::Retrieve(CargoDataSet::iterator i) const
1145 if (i == this->children->end()) {
1146 return nullptr;
1147 } else {
1148 assert(this->children->value_comp().GetSortType() != ST_COUNT);
1149 return *i;
1153 bool CargoSorter::operator()(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const
1155 switch (this->type) {
1156 case ST_STATION_ID:
1157 return this->SortId<StationID>(cd1->GetStation(), cd2->GetStation());
1158 case ST_CARGO_ID:
1159 return this->SortId<CargoID>(cd1->GetCargo(), cd2->GetCargo());
1160 case ST_COUNT:
1161 return this->SortCount(cd1, cd2);
1162 case ST_STATION_STRING:
1163 return this->SortStation(cd1->GetStation(), cd2->GetStation());
1164 default:
1165 NOT_REACHED();
1169 template<class Tid>
1170 bool CargoSorter::SortId(Tid st1, Tid st2) const
1172 return (this->order == SO_ASCENDING) ? st1 < st2 : st2 < st1;
1175 bool CargoSorter::SortCount(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const
1177 uint c1 = cd1->GetCount();
1178 uint c2 = cd2->GetCount();
1179 if (c1 == c2) {
1180 return this->SortStation(cd1->GetStation(), cd2->GetStation());
1181 } else if (this->order == SO_ASCENDING) {
1182 return c1 < c2;
1183 } else {
1184 return c2 < c1;
1188 bool CargoSorter::SortStation(StationID st1, StationID st2) const
1190 static char buf1[MAX_LENGTH_STATION_NAME_CHARS];
1191 static char buf2[MAX_LENGTH_STATION_NAME_CHARS];
1193 if (!Station::IsValidID(st1)) {
1194 return Station::IsValidID(st2) ? this->order == SO_ASCENDING : this->SortId(st1, st2);
1195 } else if (!Station::IsValidID(st2)) {
1196 return order == SO_DESCENDING;
1199 SetDParam(0, st1);
1200 GetString(buf1, STR_STATION_NAME, lastof(buf1));
1201 SetDParam(0, st2);
1202 GetString(buf2, STR_STATION_NAME, lastof(buf2));
1204 int res = strnatcmp(buf1, buf2); // Sort by name (natural sorting).
1205 if (res == 0) {
1206 return this->SortId(st1, st2);
1207 } else {
1208 return (this->order == SO_ASCENDING) ? res < 0 : res > 0;
1213 * The StationView window
1215 struct StationViewWindow : public Window {
1217 * A row being displayed in the cargo view (as opposed to being "hidden" behind a plus sign).
1219 struct RowDisplay {
1220 RowDisplay(CargoDataEntry *f, StationID n) : filter(f), next_station(n) {}
1221 RowDisplay(CargoDataEntry *f, CargoID n) : filter(f), next_cargo(n) {}
1224 * Parent of the cargo entry belonging to the row.
1226 CargoDataEntry *filter;
1227 union {
1229 * ID of the station belonging to the entry actually displayed if it's to/from/via.
1231 StationID next_station;
1234 * ID of the cargo belonging to the entry actually displayed if it's cargo.
1236 CargoID next_cargo;
1240 typedef std::vector<RowDisplay> CargoDataVector;
1242 static const int NUM_COLUMNS = 4; ///< Number of "columns" in the cargo view: cargo, from, via, to
1245 * Type of data invalidation.
1247 enum Invalidation {
1248 INV_FLOWS = 0x100, ///< The planned flows have been recalculated and everything has to be updated.
1249 INV_CARGO = 0x200 ///< Some cargo has been added or removed.
1253 * Type of grouping used in each of the "columns".
1255 enum Grouping {
1256 GR_SOURCE, ///< Group by source of cargo ("from").
1257 GR_NEXT, ///< Group by next station ("via").
1258 GR_DESTINATION, ///< Group by estimated final destination ("to").
1259 GR_CARGO, ///< Group by cargo type.
1263 * Display mode of the cargo view.
1265 enum Mode {
1266 MODE_WAITING, ///< Show cargo waiting at the station.
1267 MODE_PLANNED ///< Show cargo planned to pass through the station.
1270 uint expand_shrink_width; ///< The width allocated to the expand/shrink 'button'
1271 int rating_lines; ///< Number of lines in the cargo ratings view.
1272 int accepts_lines; ///< Number of lines in the accepted cargo view.
1273 Scrollbar *vscroll;
1275 /** Height of the #WID_SV_ACCEPT_RATING_LIST widget for different views. */
1276 enum AcceptListHeight {
1277 ALH_RATING = 13, ///< Height of the cargo ratings view.
1278 ALH_ACCEPTS = 3, ///< Height of the accepted cargo view.
1281 static const StringID _sort_names[]; ///< Names of the sorting options in the dropdown.
1282 static const StringID _group_names[]; ///< Names of the grouping options in the dropdown.
1285 * Sort types of the different 'columns'.
1286 * In fact only ST_COUNT and ST_AS_GROUPING are active and you can only
1287 * sort all the columns in the same way. The other options haven't been
1288 * included in the GUI due to lack of space.
1290 CargoSortType sortings[NUM_COLUMNS];
1292 /** Sort order (ascending/descending) for the 'columns'. */
1293 SortOrder sort_orders[NUM_COLUMNS];
1295 int scroll_to_row; ///< If set, scroll the main viewport to the station pointed to by this row.
1296 int grouping_index; ///< Currently selected entry in the grouping drop down.
1297 int ratings_list_y = 0; ///< Y coordinate of first line in station ratings panel.
1298 Mode current_mode; ///< Currently selected display mode of cargo view.
1299 Grouping groupings[NUM_COLUMNS]; ///< Grouping modes for the different columns.
1301 CargoDataEntry expanded_rows; ///< Parent entry of currently expanded rows.
1302 CargoDataEntry cached_destinations; ///< Cache for the flows passing through this station.
1303 CargoDataVector displayed_rows; ///< Parent entry of currently displayed rows (including collapsed ones).
1305 StationViewWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc),
1306 scroll_to_row(INT_MAX), grouping_index(0)
1308 this->rating_lines = ALH_RATING;
1309 this->accepts_lines = ALH_ACCEPTS;
1311 this->CreateNestedTree();
1312 this->vscroll = this->GetScrollbar(WID_SV_SCROLLBAR);
1313 /* Nested widget tree creation is done in two steps to ensure that this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS) exists in UpdateWidgetSize(). */
1314 this->FinishInitNested(window_number);
1316 this->groupings[0] = GR_CARGO;
1317 this->sortings[0] = ST_AS_GROUPING;
1318 this->SelectGroupBy(_settings_client.gui.station_gui_group_order);
1319 this->SelectSortBy(_settings_client.gui.station_gui_sort_by);
1320 this->sort_orders[0] = SO_ASCENDING;
1321 this->SelectSortOrder((SortOrder)_settings_client.gui.station_gui_sort_order);
1322 this->owner = Station::Get(window_number)->owner;
1325 ~StationViewWindow()
1327 Overlays::Instance()->RemoveStation(Station::Get(this->window_number));
1328 MarkWholeScreenDirty();
1329 Owner owner = Station::Get(this->window_number)->owner;
1330 DeleteWindowById(WC_TRAINS_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_TRAIN, this->owner, this->window_number).Pack(), false);
1331 DeleteWindowById(WC_ROADVEH_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_ROAD, this->owner, this->window_number).Pack(), false);
1332 DeleteWindowById(WC_SHIPS_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_SHIP, this->owner, this->window_number).Pack(), false);
1333 DeleteWindowById(WC_AIRCRAFT_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_AIRCRAFT, this->owner, this->window_number).Pack(), false);
1337 * Show a certain cargo entry characterized by source/next/dest station, cargo ID and amount of cargo at the
1338 * right place in the cargo view. I.e. update as many rows as are expanded following that characterization.
1339 * @param data Root entry of the tree.
1340 * @param cargo Cargo ID of the entry to be shown.
1341 * @param source Source station of the entry to be shown.
1342 * @param next Next station the cargo to be shown will visit.
1343 * @param dest Final destination of the cargo to be shown.
1344 * @param count Amount of cargo to be shown.
1346 void ShowCargo(CargoDataEntry *data, CargoID cargo, StationID source, StationID next, StationID dest, uint count)
1348 if (count == 0) return;
1349 bool auto_distributed = _settings_game.linkgraph.GetDistributionType(cargo) != DT_MANUAL;
1350 const CargoDataEntry *expand = &this->expanded_rows;
1351 for (int i = 0; i < NUM_COLUMNS && expand != nullptr; ++i) {
1352 switch (groupings[i]) {
1353 case GR_CARGO:
1354 assert(i == 0);
1355 data = data->InsertOrRetrieve(cargo);
1356 data->SetTransfers(source != this->window_number);
1357 expand = expand->Retrieve(cargo);
1358 break;
1359 case GR_SOURCE:
1360 if (auto_distributed || source != this->window_number) {
1361 data = data->InsertOrRetrieve(source);
1362 expand = expand->Retrieve(source);
1364 break;
1365 case GR_NEXT:
1366 if (auto_distributed) {
1367 data = data->InsertOrRetrieve(next);
1368 expand = expand->Retrieve(next);
1370 break;
1371 case GR_DESTINATION:
1372 if (auto_distributed) {
1373 data = data->InsertOrRetrieve(dest);
1374 expand = expand->Retrieve(dest);
1376 break;
1379 data->Update(count);
1382 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
1384 switch (widget) {
1385 case WID_SV_WAITING:
1386 resize->height = FONT_HEIGHT_NORMAL;
1387 size->height = WD_FRAMERECT_TOP + 4 * resize->height + WD_FRAMERECT_BOTTOM;
1388 this->expand_shrink_width = max(GetStringBoundingBox("-").width, GetStringBoundingBox("+").width) + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
1389 break;
1391 case WID_SV_ACCEPT_RATING_LIST:
1392 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;
1393 break;
1395 case WID_SV_CLOSE_AIRPORT:
1396 if (!(Station::Get(this->window_number)->facilities & FACIL_AIRPORT)) {
1397 /* Hide 'Close Airport' button if no airport present. */
1398 size->width = 0;
1399 resize->width = 0;
1400 fill->width = 0;
1402 break;
1406 virtual void OnToolTip(Point pt, int widget, TooltipCloseCondition close_cond)
1408 if (widget != WID_SV_ACCEPT_RATING_LIST || this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) {
1409 Window::OnToolTip(pt, widget, close_cond);
1410 return;
1413 int ofs_y = pt.y - this->ratings_list_y;
1414 if (ofs_y < 0) return;
1416 const Station *st = Station::Get(this->window_number);
1417 const CargoSpec *cs;
1418 FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
1419 const GoodsEntry *ge = &st->goods[cs->Index()];
1420 if (!ge->HasRating()) continue;
1421 ofs_y -= FONT_HEIGHT_NORMAL;
1422 if (ofs_y < 0) {
1423 GuiShowStationRatingTooltip(this, st, cs);
1424 break;
1429 virtual void OnPaint()
1431 const Station *st = Station::Get(this->window_number);
1432 CargoDataEntry cargo;
1433 BuildCargoList(&cargo, st);
1435 this->vscroll->SetCount(cargo.GetNumChildren()); // update scrollbar
1437 /* disable some buttons */
1438 this->SetWidgetDisabledState(WID_SV_RENAME, st->owner != _local_company);
1439 this->SetWidgetDisabledState(WID_SV_TRAINS, !(st->facilities & FACIL_TRAIN));
1440 this->SetWidgetDisabledState(WID_SV_ROADVEHS, !(st->facilities & FACIL_TRUCK_STOP) && !(st->facilities & FACIL_BUS_STOP));
1441 this->SetWidgetDisabledState(WID_SV_SHIPS, !(st->facilities & FACIL_DOCK));
1442 this->SetWidgetDisabledState(WID_SV_PLANES, !(st->facilities & FACIL_AIRPORT));
1443 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
1444 this->SetWidgetLoweredState(WID_SV_CLOSE_AIRPORT, (st->facilities & FACIL_AIRPORT) && (st->airport.flags & AIRPORT_CLOSED_block) != 0);
1446 /* check lowered stated for some buttons */
1447 this->SetWidgetLoweredState(WID_SV_COVERAGE, Overlays::Instance()->HasStation(st));
1449 this->DrawWidgets();
1451 if (!this->IsShaded()) {
1452 /* Draw 'accepted cargo' or 'cargo ratings'. */
1453 const NWidgetBase *wid = this->GetWidget<NWidgetBase>(WID_SV_ACCEPT_RATING_LIST);
1454 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)};
1455 if (this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) {
1456 int lines = this->DrawAcceptedCargo(r);
1457 if (lines > this->accepts_lines) { // Resize the widget, and perform re-initialization of the window.
1458 this->accepts_lines = lines;
1459 this->ReInit();
1460 return;
1463 else {
1464 int lines = this->DrawCargoRatings(r);
1465 if (lines > this->rating_lines) { // Resize the widget, and perform re-initialization of the window.
1466 this->rating_lines = lines;
1467 this->ReInit();
1468 return;
1472 /* Draw arrow pointing up/down for ascending/descending sorting */
1473 this->DrawSortButtonState(WID_SV_SORT_ORDER, sort_orders[1] == SO_ASCENDING ? SBS_UP : SBS_DOWN);
1475 int pos = this->vscroll->GetPosition();
1477 int maxrows = this->vscroll->GetCapacity();
1479 displayed_rows.clear();
1481 /* Draw waiting cargo. */
1482 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_SV_WAITING);
1483 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)};
1484 this->DrawEntries(&cargo, waiting_rect, pos, maxrows, 0);
1485 scroll_to_row = INT_MAX;
1489 virtual void SetStringParameters(int widget) const
1491 const Station *st = Station::Get(this->window_number);
1492 SetDParam(0, st->index);
1493 SetDParam(1, st->facilities);
1497 * Rebuild the cache for estimated destinations which is used to quickly show the "destination" entries
1498 * even if we actually don't know the destination of a certain packet from just looking at it.
1499 * @param i Cargo to recalculate the cache for.
1501 void RecalcDestinations(CargoID i)
1503 const Station *st = Station::Get(this->window_number);
1504 CargoDataEntry *cargo_entry = cached_destinations.InsertOrRetrieve(i);
1505 cargo_entry->Clear();
1507 const FlowStatMap &flows = st->goods[i].flows;
1508 for (FlowStatMap::const_iterator it = flows.begin(); it != flows.end(); ++it) {
1509 StationID from = it->first;
1510 CargoDataEntry *source_entry = cargo_entry->InsertOrRetrieve(from);
1511 const FlowStat::SharesMap *shares = it->second.GetShares();
1512 uint32 prev_count = 0;
1513 for (FlowStat::SharesMap::const_iterator flow_it = shares->begin(); flow_it != shares->end(); ++flow_it) {
1514 StationID via = flow_it->second;
1515 CargoDataEntry *via_entry = source_entry->InsertOrRetrieve(via);
1516 if (via == this->window_number) {
1517 via_entry->InsertOrRetrieve(via)->Update(flow_it->first - prev_count);
1518 } else {
1519 EstimateDestinations(i, from, via, flow_it->first - prev_count, via_entry);
1521 prev_count = flow_it->first;
1527 * Estimate the amounts of cargo per final destination for a given cargo, source station and next hop and
1528 * save the result as children of the given CargoDataEntry.
1529 * @param cargo ID of the cargo to estimate destinations for.
1530 * @param source Source station of the given batch of cargo.
1531 * @param next Intermediate hop to start the calculation at ("next hop").
1532 * @param count Size of the batch of cargo.
1533 * @param dest CargoDataEntry to save the results in.
1535 void EstimateDestinations(CargoID cargo, StationID source, StationID next, uint count, CargoDataEntry *dest)
1537 if (Station::IsValidID(next) && Station::IsValidID(source)) {
1538 CargoDataEntry tmp;
1539 const FlowStatMap &flowmap = Station::Get(next)->goods[cargo].flows;
1540 FlowStatMap::const_iterator map_it = flowmap.find(source);
1541 if (map_it != flowmap.end()) {
1542 const FlowStat::SharesMap *shares = map_it->second.GetShares();
1543 uint32 prev_count = 0;
1544 for (FlowStat::SharesMap::const_iterator i = shares->begin(); i != shares->end(); ++i) {
1545 tmp.InsertOrRetrieve(i->second)->Update(i->first - prev_count);
1546 prev_count = i->first;
1550 if (tmp.GetCount() == 0) {
1551 dest->InsertOrRetrieve(INVALID_STATION)->Update(count);
1552 } else {
1553 uint sum_estimated = 0;
1554 while (sum_estimated < count) {
1555 for (CargoDataSet::iterator i = tmp.Begin(); i != tmp.End() && sum_estimated < count; ++i) {
1556 CargoDataEntry *child = *i;
1557 uint estimate = DivideApprox(child->GetCount() * count, tmp.GetCount());
1558 if (estimate == 0) estimate = 1;
1560 sum_estimated += estimate;
1561 if (sum_estimated > count) {
1562 estimate -= sum_estimated - count;
1563 sum_estimated = count;
1566 if (estimate > 0) {
1567 if (child->GetStation() == next) {
1568 dest->InsertOrRetrieve(next)->Update(estimate);
1569 } else {
1570 EstimateDestinations(cargo, source, child->GetStation(), estimate, dest);
1577 } else {
1578 dest->InsertOrRetrieve(INVALID_STATION)->Update(count);
1583 * Build up the cargo view for PLANNED mode and a specific cargo.
1584 * @param i Cargo to show.
1585 * @param flows The current station's flows for that cargo.
1586 * @param cargo The CargoDataEntry to save the results in.
1588 void BuildFlowList(CargoID i, const FlowStatMap &flows, CargoDataEntry *cargo)
1590 const CargoDataEntry *source_dest = this->cached_destinations.Retrieve(i);
1591 for (FlowStatMap::const_iterator it = flows.begin(); it != flows.end(); ++it) {
1592 StationID from = it->first;
1593 const CargoDataEntry *source_entry = source_dest->Retrieve(from);
1594 const FlowStat::SharesMap *shares = it->second.GetShares();
1595 for (FlowStat::SharesMap::const_iterator flow_it = shares->begin(); flow_it != shares->end(); ++flow_it) {
1596 const CargoDataEntry *via_entry = source_entry->Retrieve(flow_it->second);
1597 for (CargoDataSet::iterator dest_it = via_entry->Begin(); dest_it != via_entry->End(); ++dest_it) {
1598 CargoDataEntry *dest_entry = *dest_it;
1599 ShowCargo(cargo, i, from, flow_it->second, dest_entry->GetStation(), dest_entry->GetCount());
1606 * Build up the cargo view for WAITING mode and a specific cargo.
1607 * @param i Cargo to show.
1608 * @param packets The current station's cargo list for that cargo.
1609 * @param cargo The CargoDataEntry to save the result in.
1611 void BuildCargoList(CargoID i, const StationCargoList &packets, CargoDataEntry *cargo)
1613 const CargoDataEntry *source_dest = this->cached_destinations.Retrieve(i);
1614 for (StationCargoList::ConstIterator it = packets.Packets()->begin(); it != packets.Packets()->end(); it++) {
1615 const CargoPacket *cp = *it;
1616 StationID next = it.GetKey();
1618 const CargoDataEntry *source_entry = source_dest->Retrieve(cp->SourceStation());
1619 if (source_entry == nullptr) {
1620 this->ShowCargo(cargo, i, cp->SourceStation(), next, INVALID_STATION, cp->Count());
1621 continue;
1624 const CargoDataEntry *via_entry = source_entry->Retrieve(next);
1625 if (via_entry == nullptr) {
1626 this->ShowCargo(cargo, i, cp->SourceStation(), next, INVALID_STATION, cp->Count());
1627 continue;
1630 for (CargoDataSet::iterator dest_it = via_entry->Begin(); dest_it != via_entry->End(); ++dest_it) {
1631 CargoDataEntry *dest_entry = *dest_it;
1632 uint val = DivideApprox(cp->Count() * dest_entry->GetCount(), via_entry->GetCount());
1633 this->ShowCargo(cargo, i, cp->SourceStation(), next, dest_entry->GetStation(), val);
1636 this->ShowCargo(cargo, i, NEW_STATION, NEW_STATION, NEW_STATION, packets.ReservedCount());
1640 * Build up the cargo view for all cargoes.
1641 * @param cargo The root cargo entry to save all results in.
1642 * @param st The station to calculate the cargo view from.
1644 void BuildCargoList(CargoDataEntry *cargo, const Station *st)
1646 for (CargoID i = 0; i < NUM_CARGO; i++) {
1648 if (this->cached_destinations.Retrieve(i) == nullptr) {
1649 this->RecalcDestinations(i);
1652 if (this->current_mode == MODE_WAITING) {
1653 this->BuildCargoList(i, st->goods[i].cargo, cargo);
1654 } else {
1655 this->BuildFlowList(i, st->goods[i].flows, cargo);
1661 * Mark a specific row, characterized by its CargoDataEntry, as expanded.
1662 * @param data The row to be marked as expanded.
1664 void SetDisplayedRow(const CargoDataEntry *data)
1666 std::vector<StationID> stations;
1667 const CargoDataEntry *parent = data->GetParent();
1668 if (parent->GetParent() == nullptr) {
1669 this->displayed_rows.push_back(RowDisplay(&this->expanded_rows, data->GetCargo()));
1670 return;
1673 StationID next = data->GetStation();
1674 while (parent->GetParent()->GetParent() != nullptr) {
1675 stations.push_back(parent->GetStation());
1676 parent = parent->GetParent();
1679 CargoID cargo = parent->GetCargo();
1680 CargoDataEntry *filter = this->expanded_rows.Retrieve(cargo);
1681 while (!stations.empty()) {
1682 filter = filter->Retrieve(stations.back());
1683 stations.pop_back();
1686 this->displayed_rows.push_back(RowDisplay(filter, next));
1690 * Select the correct string for an entry referring to the specified station.
1691 * @param station Station the entry is showing cargo for.
1692 * @param here String to be shown if the entry refers to the same station as this station GUI belongs to.
1693 * @param other_station String to be shown if the entry refers to a specific other station.
1694 * @param any String to be shown if the entry refers to "any station".
1695 * @return One of the three given strings or STR_STATION_VIEW_RESERVED, depending on what station the entry refers to.
1697 StringID GetEntryString(StationID station, StringID here, StringID other_station, StringID any)
1699 if (station == this->window_number) {
1700 return here;
1701 } else if (station == INVALID_STATION) {
1702 return any;
1703 } else if (station == NEW_STATION) {
1704 return STR_STATION_VIEW_RESERVED;
1705 } else {
1706 SetDParam(2, station);
1707 return other_station;
1712 * Determine if we need to show the special "non-stop" string.
1713 * @param cd Entry we are going to show.
1714 * @param station Station the entry refers to.
1715 * @param column The "column" the entry will be shown in.
1716 * @return either STR_STATION_VIEW_VIA or STR_STATION_VIEW_NONSTOP.
1718 StringID SearchNonStop(CargoDataEntry *cd, StationID station, int column)
1720 CargoDataEntry *parent = cd->GetParent();
1721 for (int i = column - 1; i > 0; --i) {
1722 if (this->groupings[i] == GR_DESTINATION) {
1723 if (parent->GetStation() == station) {
1724 return STR_STATION_VIEW_NONSTOP;
1725 } else {
1726 return STR_STATION_VIEW_VIA;
1729 parent = parent->GetParent();
1732 if (this->groupings[column + 1] == GR_DESTINATION) {
1733 CargoDataSet::iterator begin = cd->Begin();
1734 CargoDataSet::iterator end = cd->End();
1735 if (begin != end && ++(cd->Begin()) == end && (*(begin))->GetStation() == station) {
1736 return STR_STATION_VIEW_NONSTOP;
1737 } else {
1738 return STR_STATION_VIEW_VIA;
1742 return STR_STATION_VIEW_VIA;
1746 * Draw the given cargo entries in the station GUI.
1747 * @param entry Root entry for all cargo to be drawn.
1748 * @param r Screen rectangle to draw into.
1749 * @param pos Current row to be drawn to (counted down from 0 to -maxrows, same as vscroll->GetPosition()).
1750 * @param maxrows Maximum row to be drawn.
1751 * @param column Current "column" being drawn.
1752 * @param cargo Current cargo being drawn (if cargo column has been passed).
1753 * @return row (in "pos" counting) after the one we have last drawn to.
1755 int DrawEntries(CargoDataEntry *entry, Rect &r, int pos, int maxrows, int column, CargoID cargo = CT_INVALID)
1757 if (this->sortings[column] == ST_AS_GROUPING) {
1758 if (this->groupings[column] != GR_CARGO) {
1759 entry->Resort(ST_STATION_STRING, this->sort_orders[column]);
1761 } else {
1762 entry->Resort(ST_COUNT, this->sort_orders[column]);
1764 for (CargoDataSet::iterator i = entry->Begin(); i != entry->End(); ++i) {
1765 CargoDataEntry *cd = *i;
1767 Grouping grouping = this->groupings[column];
1768 if (grouping == GR_CARGO) cargo = cd->GetCargo();
1769 bool auto_distributed = _settings_game.linkgraph.GetDistributionType(cargo) != DT_MANUAL;
1771 if (pos > -maxrows && pos <= 0) {
1772 StringID str = STR_EMPTY;
1773 int y = r.top + WD_FRAMERECT_TOP - pos * FONT_HEIGHT_NORMAL;
1774 SetDParam(0, cargo);
1775 SetDParam(1, cd->GetCount());
1777 if (this->groupings[column] == GR_CARGO) {
1778 str = STR_STATION_VIEW_WAITING_CARGO;
1779 DrawCargoIcons(cd->GetCargo(), cd->GetCount(), r.left + WD_FRAMERECT_LEFT + this->expand_shrink_width, r.right - WD_FRAMERECT_RIGHT - this->expand_shrink_width, y);
1780 } else {
1781 if (!auto_distributed) grouping = GR_SOURCE;
1782 StationID station = cd->GetStation();
1784 switch (grouping) {
1785 case GR_SOURCE:
1786 str = this->GetEntryString(station, STR_STATION_VIEW_FROM_HERE, STR_STATION_VIEW_FROM, STR_STATION_VIEW_FROM_ANY);
1787 break;
1788 case GR_NEXT:
1789 str = this->GetEntryString(station, STR_STATION_VIEW_VIA_HERE, STR_STATION_VIEW_VIA, STR_STATION_VIEW_VIA_ANY);
1790 if (str == STR_STATION_VIEW_VIA) str = this->SearchNonStop(cd, station, column);
1791 break;
1792 case GR_DESTINATION:
1793 str = this->GetEntryString(station, STR_STATION_VIEW_TO_HERE, STR_STATION_VIEW_TO, STR_STATION_VIEW_TO_ANY);
1794 break;
1795 default:
1796 NOT_REACHED();
1798 if (pos == -this->scroll_to_row && Station::IsValidID(station)) {
1799 ScrollMainWindowToTile(Station::Get(station)->xy);
1803 bool rtl = _current_text_dir == TD_RTL;
1804 int text_left = rtl ? r.left + this->expand_shrink_width : r.left + WD_FRAMERECT_LEFT + column * this->expand_shrink_width;
1805 int text_right = rtl ? r.right - WD_FRAMERECT_LEFT - column * this->expand_shrink_width : r.right - this->expand_shrink_width;
1806 int shrink_left = rtl ? r.left + WD_FRAMERECT_LEFT : r.right - this->expand_shrink_width + WD_FRAMERECT_LEFT;
1807 int shrink_right = rtl ? r.left + this->expand_shrink_width - WD_FRAMERECT_RIGHT : r.right - WD_FRAMERECT_RIGHT;
1809 DrawString(text_left, text_right, y, str);
1811 if (column < NUM_COLUMNS - 1) {
1812 const char *sym = nullptr;
1813 if (cd->GetNumChildren() > 0) {
1814 sym = "-";
1815 } else if (auto_distributed && str != STR_STATION_VIEW_RESERVED) {
1816 sym = "+";
1817 } else {
1818 /* Only draw '+' if there is something to be shown. */
1819 const StationCargoList &list = Station::Get(this->window_number)->goods[cargo].cargo;
1820 if (grouping == GR_CARGO && (list.ReservedCount() > 0 || cd->HasTransfers())) {
1821 sym = "+";
1824 if (sym) DrawString(shrink_left, shrink_right, y, sym, TC_YELLOW);
1826 this->SetDisplayedRow(cd);
1828 --pos;
1829 if (auto_distributed || column == 0) {
1830 pos = this->DrawEntries(cd, r, pos, maxrows, column + 1, cargo);
1833 return pos;
1837 * Draw accepted cargo in the #WID_SV_ACCEPT_RATING_LIST widget.
1838 * @param r Rectangle of the widget.
1839 * @return Number of lines needed for drawing the accepted cargo.
1841 int DrawAcceptedCargo(const Rect &r) const
1843 const Station *st = Station::Get(this->window_number);
1845 uint32 cargo_mask = 0;
1846 for (CargoID i = 0; i < NUM_CARGO; i++) {
1847 if (HasBit(st->goods[i].status, GoodsEntry::GES_ACCEPTANCE)) SetBit(cargo_mask, i);
1849 SetDParam(0, cargo_mask);
1850 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);
1851 return CeilDiv(bottom - r.top - WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL);
1855 * Draw cargo ratings in the #WID_SV_ACCEPT_RATING_LIST widget.
1856 * @param r Rectangle of the widget.
1857 * @return Number of lines needed for drawing the cargo ratings.
1859 int DrawCargoRatings(const Rect &r)
1861 const Station *st = Station::Get(this->window_number);
1862 int y = r.top + WD_FRAMERECT_TOP;
1864 if (st->town->exclusive_counter > 0) {
1865 SetDParam(0, st->town->exclusivity);
1866 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);
1867 y += WD_PAR_VSEP_WIDE;
1870 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_VIEW_SUPPLY_RATINGS_TITLE);
1871 y += FONT_HEIGHT_NORMAL;
1873 this->ratings_list_y = y;
1875 const CargoSpec *cs;
1876 FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
1877 const GoodsEntry *ge = &st->goods[cs->Index()];
1878 if (!ge->HasRating()) continue;
1880 const LinkGraph *lg = LinkGraph::GetIfValid(ge->link_graph);
1881 SetDParam(0, cs->name);
1882 SetDParam(1, lg != nullptr ? lg->Monthly((*lg)[ge->node].Supply()) : 0);
1883 SetDParam(2, STR_CARGO_RATING_APPALLING + (ge->rating >> 5));
1884 SetDParam(3, ToPercent8(ge->rating));
1885 DrawString(r.left + WD_FRAMERECT_LEFT + 6, r.right - WD_FRAMERECT_RIGHT - 6, y, STR_STATION_VIEW_CARGO_SUPPLY_RATING);
1886 y += FONT_HEIGHT_NORMAL;
1888 return CeilDiv(y - r.top - WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL);
1892 * Expand or collapse a specific row.
1893 * @param filter Parent of the row.
1894 * @param next ID pointing to the row.
1896 template<class Tid>
1897 void HandleCargoWaitingClick(CargoDataEntry *filter, Tid next)
1899 if (filter->Retrieve(next) != nullptr) {
1900 filter->Remove(next);
1901 } else {
1902 filter->InsertOrRetrieve(next);
1907 * Handle a click on a specific row in the cargo view.
1908 * @param row Row being clicked.
1910 void HandleCargoWaitingClick(int row)
1912 if (row < 0 || (uint)row >= this->displayed_rows.size()) return;
1913 if (_ctrl_pressed) {
1914 this->scroll_to_row = row;
1915 } else {
1916 RowDisplay &display = this->displayed_rows[row];
1917 if (display.filter == &this->expanded_rows) {
1918 this->HandleCargoWaitingClick<CargoID>(display.filter, display.next_cargo);
1919 } else {
1920 this->HandleCargoWaitingClick<StationID>(display.filter, display.next_station);
1923 this->SetWidgetDirty(WID_SV_WAITING);
1926 virtual void OnClick(Point pt, int widget, int click_count)
1928 switch (widget) {
1929 case WID_SV_WAITING:
1930 this->HandleCargoWaitingClick(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_SV_WAITING, WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL) - this->vscroll->GetPosition());
1931 break;
1933 case WID_SV_LOCATION:
1934 if (_ctrl_pressed) {
1935 ShowExtraViewPortWindow(Station::Get(this->window_number)->xy);
1936 } else {
1937 ScrollMainWindowToTile(Station::Get(this->window_number)->xy);
1939 break;
1941 case WID_SV_COVERAGE:
1942 Overlays::Instance()->ToggleStation(Station::Get(this->window_number));
1943 MarkWholeScreenDirty();
1944 break;
1946 case WID_SV_ACCEPTS_RATINGS: {
1947 /* Swap between 'accepts' and 'ratings' view. */
1948 int height_change;
1949 NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS);
1950 if (this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) {
1951 nwi->SetDataTip(STR_STATION_VIEW_ACCEPTS_BUTTON, STR_STATION_VIEW_ACCEPTS_TOOLTIP); // Switch to accepts view.
1952 height_change = this->rating_lines - this->accepts_lines;
1953 } else {
1954 nwi->SetDataTip(STR_STATION_VIEW_RATINGS_BUTTON, STR_STATION_VIEW_RATINGS_TOOLTIP); // Switch to ratings view.
1955 height_change = this->accepts_lines - this->rating_lines;
1957 this->ReInit(0, height_change * FONT_HEIGHT_NORMAL);
1958 break;
1961 case WID_SV_RENAME:
1962 SetDParam(0, this->window_number);
1963 ShowQueryString(STR_STATION_NAME, STR_STATION_VIEW_RENAME_STATION_CAPTION, MAX_LENGTH_STATION_NAME_CHARS,
1964 this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
1965 break;
1967 case WID_SV_CLOSE_AIRPORT:
1968 DoCommandP(0, this->window_number, 0, CMD_OPEN_CLOSE_AIRPORT);
1969 break;
1971 case WID_SV_TRAINS: // Show list of scheduled trains to this station
1972 case WID_SV_ROADVEHS: // Show list of scheduled road-vehicles to this station
1973 case WID_SV_SHIPS: // Show list of scheduled ships to this station
1974 case WID_SV_PLANES: { // Show list of scheduled aircraft to this station
1975 Owner owner = Station::Get(this->window_number)->owner;
1976 ShowVehicleListWindow(owner, (VehicleType)(widget - WID_SV_TRAINS), (StationID)this->window_number);
1977 break;
1980 case WID_SV_SORT_BY: {
1981 /* The initial selection is composed of current mode and
1982 * sorting criteria for columns 1, 2, and 3. Column 0 is always
1983 * sorted by cargo ID. The others can theoretically be sorted
1984 * by different things but there is no UI for that. */
1985 ShowDropDownMenu(this, _sort_names,
1986 this->current_mode * 2 + (this->sortings[1] == ST_COUNT ? 1 : 0),
1987 WID_SV_SORT_BY, 0, 0);
1988 break;
1991 case WID_SV_GROUP_BY: {
1992 ShowDropDownMenu(this, _group_names, this->grouping_index, WID_SV_GROUP_BY, 0, 0);
1993 break;
1996 case WID_SV_SORT_ORDER: { // flip sorting method asc/desc
1997 this->SelectSortOrder(this->sort_orders[1] == SO_ASCENDING ? SO_DESCENDING : SO_ASCENDING);
1998 this->SetTimeout();
1999 this->LowerWidget(WID_SV_SORT_ORDER);
2000 break;
2003 case WID_SV_HISTORY: {
2004 ShowStationCargo((StationID)this->window_number);
2005 break;
2008 case WID_SV_DEPARTURES: {
2009 ShowStationDepartures((StationID)this->window_number);
2010 break;
2016 * Select a new sort order for the cargo view.
2017 * @param order New sort order.
2019 void SelectSortOrder(SortOrder order)
2021 this->sort_orders[1] = this->sort_orders[2] = this->sort_orders[3] = order;
2022 _settings_client.gui.station_gui_sort_order = this->sort_orders[1];
2023 this->SetDirty();
2027 * Select a new sort criterium for the cargo view.
2028 * @param index Row being selected in the sort criteria drop down.
2030 void SelectSortBy(int index)
2032 _settings_client.gui.station_gui_sort_by = index;
2033 switch (_sort_names[index]) {
2034 case STR_STATION_VIEW_WAITING_STATION:
2035 this->current_mode = MODE_WAITING;
2036 this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_AS_GROUPING;
2037 break;
2038 case STR_STATION_VIEW_WAITING_AMOUNT:
2039 this->current_mode = MODE_WAITING;
2040 this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_COUNT;
2041 break;
2042 case STR_STATION_VIEW_PLANNED_STATION:
2043 this->current_mode = MODE_PLANNED;
2044 this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_AS_GROUPING;
2045 break;
2046 case STR_STATION_VIEW_PLANNED_AMOUNT:
2047 this->current_mode = MODE_PLANNED;
2048 this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_COUNT;
2049 break;
2050 default:
2051 NOT_REACHED();
2053 /* Display the current sort variant */
2054 this->GetWidget<NWidgetCore>(WID_SV_SORT_BY)->widget_data = _sort_names[index];
2055 this->SetDirty();
2059 * Select a new grouping mode for the cargo view.
2060 * @param index Row being selected in the grouping drop down.
2062 void SelectGroupBy(int index)
2064 this->grouping_index = index;
2065 _settings_client.gui.station_gui_group_order = index;
2066 this->GetWidget<NWidgetCore>(WID_SV_GROUP_BY)->widget_data = _group_names[index];
2067 switch (_group_names[index]) {
2068 case STR_STATION_VIEW_GROUP_S_V_D:
2069 this->groupings[1] = GR_SOURCE;
2070 this->groupings[2] = GR_NEXT;
2071 this->groupings[3] = GR_DESTINATION;
2072 break;
2073 case STR_STATION_VIEW_GROUP_S_D_V:
2074 this->groupings[1] = GR_SOURCE;
2075 this->groupings[2] = GR_DESTINATION;
2076 this->groupings[3] = GR_NEXT;
2077 break;
2078 case STR_STATION_VIEW_GROUP_V_S_D:
2079 this->groupings[1] = GR_NEXT;
2080 this->groupings[2] = GR_SOURCE;
2081 this->groupings[3] = GR_DESTINATION;
2082 break;
2083 case STR_STATION_VIEW_GROUP_V_D_S:
2084 this->groupings[1] = GR_NEXT;
2085 this->groupings[2] = GR_DESTINATION;
2086 this->groupings[3] = GR_SOURCE;
2087 break;
2088 case STR_STATION_VIEW_GROUP_D_S_V:
2089 this->groupings[1] = GR_DESTINATION;
2090 this->groupings[2] = GR_SOURCE;
2091 this->groupings[3] = GR_NEXT;
2092 break;
2093 case STR_STATION_VIEW_GROUP_D_V_S:
2094 this->groupings[1] = GR_DESTINATION;
2095 this->groupings[2] = GR_NEXT;
2096 this->groupings[3] = GR_SOURCE;
2097 break;
2099 this->SetDirty();
2102 virtual void OnDropdownSelect(int widget, int index)
2104 if (widget == WID_SV_SORT_BY) {
2105 this->SelectSortBy(index);
2106 } else {
2107 this->SelectGroupBy(index);
2111 virtual void OnQueryTextFinished(char *str)
2113 if (str == nullptr) return;
2115 DoCommandP(0, this->window_number, 0, CMD_RENAME_STATION | CMD_MSG(STR_ERROR_CAN_T_RENAME_STATION), nullptr, str);
2118 virtual void OnResize()
2120 this->vscroll->SetCapacityFromWidget(this, WID_SV_WAITING, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
2124 * Some data on this window has become invalid. Invalidate the cache for the given cargo if necessary.
2125 * @param data Information about the changed data. If it's a valid cargo ID, invalidate the cargo data.
2126 * @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.
2128 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
2130 if (gui_scope) {
2131 if (data >= 0 && data < NUM_CARGO) {
2132 this->cached_destinations.Remove((CargoID)data);
2133 } else {
2134 this->ReInit();
2139 protected:
2141 void Get(WindowNumber window_number);
2144 const StringID StationViewWindow::_sort_names[] = {
2145 STR_STATION_VIEW_WAITING_STATION,
2146 STR_STATION_VIEW_WAITING_AMOUNT,
2147 STR_STATION_VIEW_PLANNED_STATION,
2148 STR_STATION_VIEW_PLANNED_AMOUNT,
2149 INVALID_STRING_ID
2152 const StringID StationViewWindow::_group_names[] = {
2153 STR_STATION_VIEW_GROUP_S_V_D,
2154 STR_STATION_VIEW_GROUP_S_D_V,
2155 STR_STATION_VIEW_GROUP_V_S_D,
2156 STR_STATION_VIEW_GROUP_V_D_S,
2157 STR_STATION_VIEW_GROUP_D_S_V,
2158 STR_STATION_VIEW_GROUP_D_V_S,
2159 INVALID_STRING_ID
2162 static WindowDesc _station_view_desc(
2163 WDP_AUTO, "view_station", 249, 117,
2164 WC_STATION_VIEW, WC_NONE,
2166 _nested_station_view_widgets, lengthof(_nested_station_view_widgets)
2170 * Opens StationViewWindow for given station
2172 * @param station station which window should be opened
2174 void ShowStationViewWindow(StationID station)
2176 if (_ctrl_pressed) {
2177 Overlays::Instance()->ToggleStation(Station::Get(station));
2178 MarkWholeScreenDirty();
2179 } else {
2180 AllocateWindowDescFront<StationViewWindow>(&_station_view_desc, station);
2184 /** Struct containing TileIndex and StationID */
2185 struct TileAndStation {
2186 TileIndex tile; ///< TileIndex
2187 StationID station; ///< StationID
2190 static SmallVector<TileAndStation, 8> _deleted_stations_nearby;
2191 static SmallVector<StationID, 8> _stations_nearby_list;
2194 * Add station on this tile to _stations_nearby_list if it's fully within the
2195 * station spread.
2196 * @param tile Tile just being checked
2197 * @param user_data Pointer to TileArea context
2198 * @tparam T the type of station to look for
2200 template <class T>
2201 static bool AddNearbyStation(TileIndex tile, void *user_data)
2203 TileArea *ctx = (TileArea *)user_data;
2205 /* First check if there were deleted stations here */
2206 for (uint i = 0; i < _deleted_stations_nearby.Length(); i++) {
2207 TileAndStation *ts = _deleted_stations_nearby.Get(i);
2208 if (ts->tile == tile) {
2209 *_stations_nearby_list.Append() = _deleted_stations_nearby[i].station;
2210 _deleted_stations_nearby.Erase(ts);
2211 i--;
2215 /* Check if own station and if we stay within station spread */
2216 if (!IsTileType(tile, MP_STATION)) return false;
2218 StationID sid = GetStationIndex(tile);
2220 /* This station is (likely) a waypoint */
2221 if (!T::IsValidID(sid)) return false;
2223 T *st = T::Get(sid);
2224 if (st->owner != _local_company || _stations_nearby_list.Contains(sid)) return false;
2226 if (st->rect.BeforeAddRect(ctx->tile, ctx->w, ctx->h, StationRect::ADD_TEST).Succeeded()) {
2227 *_stations_nearby_list.Append() = sid;
2230 return false; // We want to include *all* nearby stations
2234 * Circulate around the to-be-built station to find stations we could join.
2235 * Make sure that only stations are returned where joining wouldn't exceed
2236 * station spread and are our own station.
2237 * @param ta Base tile area of the to-be-built station
2238 * @param distant_join Search for adjacent stations (false) or stations fully
2239 * within station spread
2240 * @tparam T the type of station to look for
2242 template <class T>
2243 static const T *FindStationsNearby(TileArea ta, bool distant_join)
2245 TileArea ctx = ta;
2247 _stations_nearby_list.Clear();
2248 _deleted_stations_nearby.Clear();
2250 /* Check the inside, to return, if we sit on another station */
2251 TILE_AREA_LOOP(t, ta) {
2252 if (t < MapSize() && IsTileType(t, MP_STATION) && T::IsValidID(GetStationIndex(t))) return T::GetByTile(t);
2255 /* Look for deleted stations */
2256 const BaseStation *st;
2257 FOR_ALL_BASE_STATIONS(st) {
2258 if (T::IsExpected(st) && !st->IsInUse() && st->owner == _local_company) {
2259 /* Include only within station spread (yes, it is strictly less than) */
2260 if (max(DistanceMax(ta.tile, st->xy), DistanceMax(TILE_ADDXY(ta.tile, ta.w - 1, ta.h - 1), st->xy)) < _settings_game.station.station_spread) {
2261 TileAndStation *ts = _deleted_stations_nearby.Append();
2262 ts->tile = st->xy;
2263 ts->station = st->index;
2265 /* Add the station when it's within where we're going to build */
2266 if (IsInsideBS(TileX(st->xy), TileX(ctx.tile), ctx.w) &&
2267 IsInsideBS(TileY(st->xy), TileY(ctx.tile), ctx.h)) {
2268 AddNearbyStation<T>(st->xy, &ctx);
2274 /* Only search tiles where we have a chance to stay within the station spread.
2275 * The complete check needs to be done in the callback as we don't know the
2276 * extent of the found station, yet. */
2277 if (distant_join && min(ta.w, ta.h) >= _settings_game.station.station_spread) return nullptr;
2278 uint max_dist = distant_join ? _settings_game.station.station_spread - min(ta.w, ta.h) : 1;
2280 CircularTileSearch(TileX(ctx.tile) - 1, TileY(ctx.tile) - 1, max_dist, ta.w, ta.h, AddNearbyStation<T>, &ctx);
2282 return nullptr;
2285 static const NWidgetPart _nested_select_station_widgets[] = {
2286 NWidget(NWID_HORIZONTAL),
2287 NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
2288 NWidget(WWT_CAPTION, COLOUR_DARK_GREEN, WID_JS_CAPTION), SetDataTip(STR_JOIN_STATION_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2289 NWidget(WWT_DEFSIZEBOX, COLOUR_DARK_GREEN),
2290 EndContainer(),
2291 NWidget(NWID_HORIZONTAL),
2292 NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_JS_PANEL), SetResize(1, 0), SetScrollbar(WID_JS_SCROLLBAR), EndContainer(),
2293 NWidget(NWID_VERTICAL),
2294 NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, WID_JS_SCROLLBAR),
2295 NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
2296 EndContainer(),
2297 EndContainer(),
2301 * Window for selecting stations/waypoints to (distant) join to.
2302 * @tparam T The type of station to join with
2304 template <class T>
2305 struct SelectStationWindow : Window {
2306 CommandContainer select_station_cmd; ///< Command to build new station
2307 TileArea area; ///< Location of new station
2308 Scrollbar *vscroll;
2310 SelectStationWindow(WindowDesc *desc, const CommandContainer &cmd, TileArea ta) :
2311 Window(desc),
2312 select_station_cmd(cmd),
2313 area(ta)
2315 this->CreateNestedTree();
2316 this->vscroll = this->GetScrollbar(WID_JS_SCROLLBAR);
2317 this->GetWidget<NWidgetCore>(WID_JS_CAPTION)->widget_data = T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_JOIN_WAYPOINT_CAPTION : STR_JOIN_STATION_CAPTION;
2318 this->FinishInitNested(0);
2319 this->OnInvalidateData(0);
2322 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
2324 if (widget != WID_JS_PANEL) return;
2326 /* Determine the widest string */
2327 Dimension d = GetStringBoundingBox(T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_JOIN_WAYPOINT_CREATE_SPLITTED_WAYPOINT : STR_JOIN_STATION_CREATE_SPLITTED_STATION);
2328 for (uint i = 0; i < _stations_nearby_list.Length(); i++) {
2329 const T *st = T::Get(_stations_nearby_list[i]);
2330 SetDParam(0, st->index);
2331 SetDParam(1, st->facilities);
2332 d = maxdim(d, GetStringBoundingBox(T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_STATION_LIST_WAYPOINT : STR_STATION_LIST_STATION));
2335 resize->height = d.height;
2336 d.height *= 5;
2337 d.width += WD_FRAMERECT_RIGHT + WD_FRAMERECT_LEFT;
2338 d.height += WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
2339 *size = d;
2342 virtual void DrawWidget(const Rect &r, int widget) const
2344 if (widget != WID_JS_PANEL) return;
2346 uint y = r.top + WD_FRAMERECT_TOP;
2347 if (this->vscroll->GetPosition() == 0) {
2348 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);
2349 y += this->resize.step_height;
2352 for (uint i = max<uint>(1, this->vscroll->GetPosition()); i <= _stations_nearby_list.Length(); ++i, y += this->resize.step_height) {
2353 /* Don't draw anything if it extends past the end of the window. */
2354 if (i - this->vscroll->GetPosition() >= this->vscroll->GetCapacity()) break;
2356 const T *st = T::Get(_stations_nearby_list[i - 1]);
2357 SetDParam(0, st->index);
2358 SetDParam(1, st->facilities);
2359 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);
2363 virtual void OnClick(Point pt, int widget, int click_count)
2365 if (widget != WID_JS_PANEL) return;
2367 uint st_index = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_JS_PANEL, WD_FRAMERECT_TOP);
2368 bool distant_join = (st_index > 0);
2369 if (distant_join) st_index--;
2371 if (distant_join && st_index >= _stations_nearby_list.Length()) return;
2373 /* Insert station to be joined into stored command */
2374 SB(this->select_station_cmd.p2, 16, 16,
2375 (distant_join ? _stations_nearby_list[st_index] : NEW_STATION));
2377 /* Execute stored Command */
2378 DoCommandP(&this->select_station_cmd);
2380 /* Close Window; this might cause double frees! */
2381 DeleteWindowById(WC_SELECT_STATION, 0);
2384 virtual void OnTick()
2386 if (_thd.dirty & 2) {
2387 _thd.dirty &= ~2;
2388 this->SetDirty();
2392 virtual void OnResize()
2394 this->vscroll->SetCapacityFromWidget(this, WID_JS_PANEL, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
2398 * Some data on this window has become invalid.
2399 * @param data Information about the changed data.
2400 * @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.
2402 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
2404 if (!gui_scope) return;
2405 FindStationsNearby<T>(this->area, true);
2406 this->vscroll->SetCount(_stations_nearby_list.Length() + 1);
2407 this->SetDirty();
2411 static WindowDesc _select_station_desc(
2412 WDP_AUTO, "build_station_join", 200, 180,
2413 WC_SELECT_STATION, WC_NONE,
2414 WDF_CONSTRUCTION,
2415 _nested_select_station_widgets, lengthof(_nested_select_station_widgets)
2420 * Check whether we need to show the station selection window.
2421 * @param cmd Command to build the station.
2422 * @param ta Tile area of the to-be-built station
2423 * @tparam T the type of station
2424 * @return whether we need to show the station selection window.
2426 template <class T>
2427 static bool StationJoinerNeeded(const CommandContainer &cmd, TileArea ta)
2429 /* Only show selection if distant join is enabled in the settings */
2430 if (!_settings_game.station.distant_join_stations) return false;
2432 /* If a window is already opened and we didn't ctrl-click,
2433 * return true (i.e. just flash the old window) */
2434 Window *selection_window = FindWindowById(WC_SELECT_STATION, 0);
2435 if (selection_window != nullptr) {
2436 /* Abort current distant-join and start new one */
2437 delete selection_window;
2438 UpdateTileSelection();
2441 /* only show the popup, if we press ctrl */
2442 if (!_ctrl_pressed) return false;
2444 /* Now check if we could build there */
2445 if (DoCommand(&cmd, CommandFlagsToDCFlags(GetCommandFlags(cmd.cmd))).Failed()) return false;
2447 /* Test for adjacent station or station below selection.
2448 * If adjacent-stations is disabled and we are building next to a station, do not show the selection window.
2449 * but join the other station immediately. */
2450 const T *st = FindStationsNearby<T>(ta, false);
2451 return st == nullptr && (_settings_game.station.adjacent_stations || _stations_nearby_list.Length() == 0);
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
2458 * @tparam the class to find stations for
2460 template <class T>
2461 void ShowSelectBaseStationIfNeeded(const CommandContainer &cmd, TileArea ta)
2463 if (StationJoinerNeeded<T>(cmd, ta)) {
2464 if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
2465 new SelectStationWindow<T>(&_select_station_desc, cmd, ta);
2466 } else {
2467 DoCommandP(&cmd);
2472 * Show the station selection window when needed. If not, build the station.
2473 * @param cmd Command to build the station.
2474 * @param ta Area to build the station in
2476 void ShowSelectStationIfNeeded(const CommandContainer &cmd, TileArea ta)
2478 ShowSelectBaseStationIfNeeded<Station>(cmd, ta);
2482 * Show the waypoint selection window when needed. If not, build the waypoint.
2483 * @param cmd Command to build the waypoint.
2484 * @param ta Area to build the waypoint in
2486 void ShowSelectWaypointIfNeeded(const CommandContainer &cmd, TileArea ta)
2488 ShowSelectBaseStationIfNeeded<Waypoint>(cmd, ta);