Add ScriptStoryPageElementList to get the contents of a page
[openttd/fttd.git] / src / station_gui.cpp
blob67746a2c527c7d71bae96426fcdce255b0e8633a
1 /* $Id$ */
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 "window_func.h"
23 #include "viewport_func.h"
24 #include "widgets/dropdown_func.h"
25 #include "station_base.h"
26 #include "waypoint_base.h"
27 #include "tilehighlight_func.h"
28 #include "company_base.h"
29 #include "sortlist_type.h"
30 #include "core/geometry_func.hpp"
31 #include "vehiclelist.h"
32 #include "town.h"
33 #include "linkgraph/linkgraph.h"
34 #include "station_func.h"
36 #include "widgets/station_widget.h"
38 #include "table/strings.h"
40 #include <set>
41 #include <vector>
43 /**
44 * Calculates and draws the accepted or supplied cargo around the selected tile(s)
45 * @param left x position where the string is to be drawn
46 * @param right the right most position to draw on
47 * @param top y position where the string is to be drawn
48 * @param sct which type of cargo is to be displayed (passengers/non-passengers)
49 * @param rad radius around selected tile(s) to be searched
50 * @param supplies if supplied cargoes should be drawn, else accepted cargoes
51 * @return Returns the y value below the string that was drawn
53 int DrawStationCoverageAreaText(int left, int right, int top, StationCoverageType sct, int rad, bool supplies)
55 TileIndex tile = TileVirtXY(_thd.pos.x, _thd.pos.y);
56 uint32 cargo_mask = 0;
57 if (_thd.drawstyle == HT_RECT && tile < MapSize()) {
58 CargoArray cargoes;
59 if (supplies) {
60 cargoes = GetProductionAroundTiles(tile, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE, rad);
61 } else {
62 cargoes = GetAcceptanceAroundTiles(tile, _thd.size.x / TILE_SIZE, _thd.size.y / TILE_SIZE, rad);
65 /* Convert cargo counts to a set of cargo bits, and draw the result. */
66 for (CargoID i = 0; i < NUM_CARGO; i++) {
67 switch (sct) {
68 case SCT_PASSENGERS_ONLY: if (!IsCargoInClass(i, CC_PASSENGERS)) continue; break;
69 case SCT_NON_PASSENGERS_ONLY: if (IsCargoInClass(i, CC_PASSENGERS)) continue; break;
70 case SCT_ALL: break;
71 default: NOT_REACHED();
73 if (cargoes[i] >= (supplies ? 1U : 8U)) SetBit(cargo_mask, i);
76 SetDParam(0, cargo_mask);
77 return DrawStringMultiLine(left, right, top, INT32_MAX, supplies ? STR_STATION_BUILD_SUPPLIES_CARGO : STR_STATION_BUILD_ACCEPTS_CARGO);
80 /**
81 * Check whether we need to redraw the station coverage text.
82 * If it is needed actually make the window for redrawing.
83 * @param w the window to check.
85 void CheckRedrawStationCoverage(const Window *w)
87 if (_thd.dirty & 1) {
88 _thd.dirty &= ~1;
89 w->SetDirty();
93 /**
94 * Draw small boxes of cargo amount and ratings data at the given
95 * coordinates. If amount exceeds 576 units, it is shown 'full', same
96 * goes for the rating: at above 90% orso (224) it is also 'full'
98 * @param left left most coordinate to draw the box at
99 * @param right right most coordinate to draw the box at
100 * @param y coordinate to draw the box at
101 * @param type Cargo type
102 * @param amount Cargo amount
103 * @param rating ratings data for that particular cargo
105 * @note Each cargo-bar is 16 pixels wide and 6 pixels high
106 * @note Each rating 14 pixels wide and 1 pixel high and is 1 pixel below the cargo-bar
108 static void StationsWndShowStationRating(int left, int right, int y, CargoID type, uint amount, byte rating)
110 static const uint units_full = 576; ///< number of units to show station as 'full'
111 static const uint rating_full = 224; ///< rating needed so it is shown as 'full'
113 const CargoSpec *cs = CargoSpec::Get(type);
114 if (!cs->IsValid()) return;
116 int colour = cs->rating_colour;
117 TextColour tc = GetContrastColour(colour);
118 uint w = (minu(amount, units_full) + 5) / 36;
120 int height = GetCharacterHeight(FS_SMALL);
122 /* Draw total cargo (limited) on station (fits into 16 pixels) */
123 if (w != 0) GfxFillRect(left, y, left + w - 1, y + height, colour);
125 /* Draw a one pixel-wide bar of additional cargo meter, useful
126 * for stations with only a small amount (<=30) */
127 if (w == 0) {
128 uint rest = amount / 5;
129 if (rest != 0) {
130 w += left;
131 GfxFillRect(w, y + height - rest, w, y + height, colour);
135 DrawString(left + 1, right, y, cs->abbrev, tc);
137 /* Draw green/red ratings bar (fits into 14 pixels) */
138 y += height + 2;
139 GfxFillRect(left + 1, y, left + 14, y, PC_RED);
140 rating = minu(rating, rating_full) / 16;
141 if (rating != 0) GfxFillRect(left + 1, y, left + rating, y, PC_GREEN);
144 typedef GUIList<const Station*> GUIStationList;
147 * The list of stations per company.
149 class CompanyStationsWindow : public Window
151 protected:
152 /* Runtime saved values */
153 static Listing last_sorting;
154 static byte facilities; // types of stations of interest
155 static bool include_empty; // whether we should include stations without waiting cargo
156 static const uint32 cargo_filter_max;
157 static uint32 cargo_filter; // bitmap of cargo types to include
158 static const Station *last_station;
160 /* Constants for sorting stations */
161 static const StringID sorter_names[];
162 static GUIStationList::SortFunction * const sorter_funcs[];
164 GUIStationList stations;
165 Scrollbar *vscroll;
168 * (Re)Build station list
170 * @param owner company whose stations are to be in list
172 void BuildStationsList(const Owner owner)
174 if (!this->stations.NeedRebuild()) return;
176 DEBUG(misc, 3, "Building station list for company %d", owner);
178 this->stations.Clear();
180 const Station *st;
181 FOR_ALL_STATIONS(st) {
182 if (st->owner == owner || (st->owner == OWNER_NONE && HasStationInUse(st->index, true, owner))) {
183 if (this->facilities & st->facilities) { // only stations with selected facilities
184 int num_waiting_cargo = 0;
185 for (CargoID j = 0; j < NUM_CARGO; j++) {
186 if (st->goods[j].HasRating()) {
187 num_waiting_cargo++; // count number of waiting cargo
188 if (HasBit(this->cargo_filter, j)) {
189 *this->stations.Append() = st;
190 break;
194 /* stations without waiting cargo */
195 if (num_waiting_cargo == 0 && this->include_empty) {
196 *this->stations.Append() = st;
202 this->stations.Compact();
203 this->stations.RebuildDone();
205 this->vscroll->SetCount(this->stations.Length()); // Update the scrollbar
208 /** Sort stations by their name */
209 static int CDECL StationNameSorter(const Station * const *a, const Station * const *b)
211 static char buf_cache[64];
212 char buf[64];
214 SetDParam(0, (*a)->index);
215 GetString(buf, STR_STATION_NAME, lastof(buf));
217 if (*b != last_station) {
218 last_station = *b;
219 SetDParam(0, (*b)->index);
220 GetString(buf_cache, STR_STATION_NAME, lastof(buf_cache));
223 return strcmp(buf, buf_cache);
226 /** Sort stations by their type */
227 static int CDECL StationTypeSorter(const Station * const *a, const Station * const *b)
229 return (*a)->facilities - (*b)->facilities;
232 /** Sort stations by their waiting cargo */
233 static int CDECL StationWaitingTotalSorter(const Station * const *a, const Station * const *b)
235 int diff = 0;
237 CargoID j;
238 FOR_EACH_SET_CARGO_ID(j, cargo_filter) {
239 diff += (*a)->goods[j].cargo.TotalCount() - (*b)->goods[j].cargo.TotalCount();
242 return diff;
245 /** Sort stations by their available waiting cargo */
246 static int CDECL StationWaitingAvailableSorter(const Station * const *a, const Station * const *b)
248 int diff = 0;
250 CargoID j;
251 FOR_EACH_SET_CARGO_ID(j, cargo_filter) {
252 diff += (*a)->goods[j].cargo.AvailableCount() - (*b)->goods[j].cargo.AvailableCount();
255 return diff;
258 /** Sort stations by their rating */
259 static int CDECL StationRatingMaxSorter(const Station * const *a, const Station * const *b)
261 byte maxr1 = 0;
262 byte maxr2 = 0;
264 CargoID j;
265 FOR_EACH_SET_CARGO_ID(j, cargo_filter) {
266 if ((*a)->goods[j].HasRating()) maxr1 = max(maxr1, (*a)->goods[j].rating);
267 if ((*b)->goods[j].HasRating()) maxr2 = max(maxr2, (*b)->goods[j].rating);
270 return maxr1 - maxr2;
273 /** Sort stations by their rating */
274 static int CDECL StationRatingMinSorter(const Station * const *a, const Station * const *b)
276 byte minr1 = 255;
277 byte minr2 = 255;
279 for (CargoID j = 0; j < NUM_CARGO; j++) {
280 if (!HasBit(cargo_filter, j)) continue;
281 if ((*a)->goods[j].HasRating()) minr1 = min(minr1, (*a)->goods[j].rating);
282 if ((*b)->goods[j].HasRating()) minr2 = min(minr2, (*b)->goods[j].rating);
285 return -(minr1 - minr2);
288 /** Sort the stations list */
289 void SortStationsList()
291 if (!this->stations.Sort()) return;
293 /* Reset name sorter sort cache */
294 this->last_station = NULL;
296 /* Set the modified widget dirty */
297 this->SetWidgetDirty(WID_STL_LIST);
300 public:
301 CompanyStationsWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
303 this->stations.SetListing(this->last_sorting);
304 this->stations.SetSortFuncs(this->sorter_funcs);
305 this->stations.ForceRebuild();
306 this->stations.NeedResort();
307 this->SortStationsList();
309 this->CreateNestedTree();
310 this->vscroll = this->GetScrollbar(WID_STL_SCROLLBAR);
311 this->FinishInitNested(window_number);
312 this->owner = (Owner)this->window_number;
314 const CargoSpec *cs;
315 FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
316 if (!HasBit(this->cargo_filter, cs->Index())) continue;
317 this->LowerWidget(WID_STL_CARGOSTART + index);
320 if (this->cargo_filter == this->cargo_filter_max) this->cargo_filter = _cargo_mask;
322 for (uint i = 0; i < 5; i++) {
323 if (HasBit(this->facilities, i)) this->LowerWidget(i + WID_STL_TRAIN);
325 this->SetWidgetLoweredState(WID_STL_NOCARGOWAITING, this->include_empty);
327 this->GetWidget<NWidgetCore>(WID_STL_SORTDROPBTN)->widget_data = this->sorter_names[this->stations.SortType()];
330 ~CompanyStationsWindow()
332 this->last_sorting = this->stations.GetListing();
335 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
337 switch (widget) {
338 case WID_STL_SORTBY: {
339 Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
340 d.width += padding.width + WD_SORTBUTTON_ARROW_WIDTH * 2; // Doubled since the string is centred and it also looks better.
341 d.height += padding.height;
342 *size = maxdim(*size, d);
343 break;
346 case WID_STL_SORTDROPBTN: {
347 Dimension d = {0, 0};
348 for (int i = 0; this->sorter_names[i] != INVALID_STRING_ID; i++) {
349 d = maxdim(d, GetStringBoundingBox(this->sorter_names[i]));
351 d.width += padding.width;
352 d.height += padding.height;
353 *size = maxdim(*size, d);
354 break;
357 case WID_STL_LIST:
358 resize->height = FONT_HEIGHT_NORMAL;
359 size->height = WD_FRAMERECT_TOP + 5 * resize->height + WD_FRAMERECT_BOTTOM;
360 break;
362 case WID_STL_TRAIN:
363 case WID_STL_TRUCK:
364 case WID_STL_BUS:
365 case WID_STL_AIRPLANE:
366 case WID_STL_SHIP:
367 size->height = max<uint>(FONT_HEIGHT_SMALL, 10) + padding.height;
368 break;
370 case WID_STL_CARGOALL:
371 case WID_STL_FACILALL:
372 case WID_STL_NOCARGOWAITING: {
373 Dimension d = GetStringBoundingBox(widget == WID_STL_NOCARGOWAITING ? STR_ABBREV_NONE : STR_ABBREV_ALL);
374 d.width += padding.width + 2;
375 d.height += padding.height;
376 *size = maxdim(*size, d);
377 break;
380 default:
381 if (widget >= WID_STL_CARGOSTART) {
382 Dimension d = GetStringBoundingBox(_sorted_cargo_specs[widget - WID_STL_CARGOSTART]->abbrev);
383 d.width += padding.width + 2;
384 d.height += padding.height;
385 *size = maxdim(*size, d);
387 break;
391 virtual void OnPaint()
393 this->BuildStationsList((Owner)this->window_number);
394 this->SortStationsList();
396 this->DrawWidgets();
399 virtual void DrawWidget(const Rect &r, int widget) const
401 switch (widget) {
402 case WID_STL_SORTBY:
403 /* draw arrow pointing up/down for ascending/descending sorting */
404 this->DrawSortButtonState(WID_STL_SORTBY, this->stations.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
405 break;
407 case WID_STL_LIST: {
408 bool rtl = _current_text_dir == TD_RTL;
409 int max = min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->stations.Length());
410 int y = r.top + WD_FRAMERECT_TOP;
411 for (int i = this->vscroll->GetPosition(); i < max; ++i) { // do until max number of stations of owner
412 const Station *st = this->stations[i];
413 assert(st->xy != INVALID_TILE);
415 /* Do not do the complex check HasStationInUse here, it may be even false
416 * when the order had been removed and the station list hasn't been removed yet */
417 assert(st->owner == owner || st->owner == OWNER_NONE);
419 SetDParam(0, st->index);
420 SetDParam(1, st->facilities);
421 int x = DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_LIST_STATION);
422 x += rtl ? -5 : 5;
424 /* show cargo waiting and station ratings */
425 for (uint j = 0; j < _sorted_standard_cargo_specs_size; j++) {
426 CargoID cid = _sorted_cargo_specs[j]->Index();
427 if (st->goods[cid].cargo.TotalCount() > 0) {
428 /* For RTL we work in exactly the opposite direction. So
429 * decrement the space needed first, then draw to the left
430 * instead of drawing to the left and then incrementing
431 * the space. */
432 if (rtl) {
433 x -= 20;
434 if (x < r.left + WD_FRAMERECT_LEFT) break;
436 StationsWndShowStationRating(x, x + 16, y, cid, st->goods[cid].cargo.TotalCount(), st->goods[cid].rating);
437 if (!rtl) {
438 x += 20;
439 if (x > r.right - WD_FRAMERECT_RIGHT) break;
443 y += FONT_HEIGHT_NORMAL;
446 if (this->vscroll->GetCount() == 0) { // company has no stations
447 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_LIST_NONE);
448 return;
450 break;
453 case WID_STL_NOCARGOWAITING: {
454 int cg_ofst = this->IsWidgetLowered(widget) ? 2 : 1;
455 DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, STR_ABBREV_NONE, TC_BLACK, SA_HOR_CENTER);
456 break;
459 case WID_STL_CARGOALL: {
460 int cg_ofst = this->IsWidgetLowered(widget) ? 2 : 1;
461 DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, STR_ABBREV_ALL, TC_BLACK, SA_HOR_CENTER);
462 break;
465 case WID_STL_FACILALL: {
466 int cg_ofst = this->IsWidgetLowered(widget) ? 2 : 1;
467 DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, STR_ABBREV_ALL, TC_BLACK, SA_HOR_CENTER);
468 break;
471 default:
472 if (widget >= WID_STL_CARGOSTART) {
473 const CargoSpec *cs = _sorted_cargo_specs[widget - WID_STL_CARGOSTART];
474 int cg_ofst = HasBit(this->cargo_filter, cs->Index()) ? 2 : 1;
475 GfxFillRect(r.left + cg_ofst, r.top + cg_ofst, r.right - 2 + cg_ofst, r.bottom - 2 + cg_ofst, cs->rating_colour);
476 TextColour tc = GetContrastColour(cs->rating_colour);
477 DrawString(r.left + cg_ofst, r.right + cg_ofst, r.top + cg_ofst, cs->abbrev, tc, SA_HOR_CENTER);
479 break;
483 virtual void SetStringParameters(int widget) const
485 if (widget == WID_STL_CAPTION) {
486 SetDParam(0, this->window_number);
487 SetDParam(1, this->vscroll->GetCount());
491 virtual void OnClick(Point pt, int widget, int click_count)
493 switch (widget) {
494 case WID_STL_LIST: {
495 uint id_v = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_STL_LIST, 0, FONT_HEIGHT_NORMAL);
496 if (id_v >= this->stations.Length()) return; // click out of list bound
498 const Station *st = this->stations[id_v];
499 /* do not check HasStationInUse - it is slow and may be invalid */
500 assert(st->owner == (Owner)this->window_number || st->owner == OWNER_NONE);
502 if (_ctrl_pressed) {
503 ShowExtraViewPortWindow(st->xy);
504 } else {
505 ScrollMainWindowToTile(st->xy);
507 break;
510 case WID_STL_TRAIN:
511 case WID_STL_TRUCK:
512 case WID_STL_BUS:
513 case WID_STL_AIRPLANE:
514 case WID_STL_SHIP:
515 if (_ctrl_pressed) {
516 ToggleBit(this->facilities, widget - WID_STL_TRAIN);
517 this->ToggleWidgetLoweredState(widget);
518 } else {
519 uint i;
520 FOR_EACH_SET_BIT(i, this->facilities) {
521 this->RaiseWidget(i + WID_STL_TRAIN);
523 this->facilities = 1 << (widget - WID_STL_TRAIN);
524 this->LowerWidget(widget);
526 this->stations.ForceRebuild();
527 this->SetDirty();
528 break;
530 case WID_STL_FACILALL:
531 for (uint i = WID_STL_TRAIN; i <= WID_STL_SHIP; i++) {
532 this->LowerWidget(i);
535 this->facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK;
536 this->stations.ForceRebuild();
537 this->SetDirty();
538 break;
540 case WID_STL_CARGOALL: {
541 for (uint i = 0; i < _sorted_standard_cargo_specs_size; i++) {
542 this->LowerWidget(WID_STL_CARGOSTART + i);
544 this->LowerWidget(WID_STL_NOCARGOWAITING);
546 this->cargo_filter = _cargo_mask;
547 this->include_empty = true;
548 this->stations.ForceRebuild();
549 this->SetDirty();
550 break;
553 case WID_STL_SORTBY: // flip sorting method asc/desc
554 this->stations.ToggleSortOrder();
555 this->SetDirty();
556 break;
558 case WID_STL_SORTDROPBTN: // select sorting criteria dropdown menu
559 ShowDropDownMenu(this, this->sorter_names, this->stations.SortType(), WID_STL_SORTDROPBTN, 0, 0);
560 break;
562 case WID_STL_NOCARGOWAITING:
563 if (_ctrl_pressed) {
564 this->include_empty = !this->include_empty;
565 this->ToggleWidgetLoweredState(WID_STL_NOCARGOWAITING);
566 } else {
567 for (uint i = 0; i < _sorted_standard_cargo_specs_size; i++) {
568 this->RaiseWidget(WID_STL_CARGOSTART + i);
571 this->cargo_filter = 0;
572 this->include_empty = true;
574 this->LowerWidget(WID_STL_NOCARGOWAITING);
576 this->stations.ForceRebuild();
577 this->SetDirty();
578 break;
580 default:
581 if (widget >= WID_STL_CARGOSTART) { // change cargo_filter
582 /* Determine the selected cargo type */
583 const CargoSpec *cs = _sorted_cargo_specs[widget - WID_STL_CARGOSTART];
585 if (_ctrl_pressed) {
586 ToggleBit(this->cargo_filter, cs->Index());
587 this->ToggleWidgetLoweredState(widget);
588 } else {
589 for (uint i = 0; i < _sorted_standard_cargo_specs_size; i++) {
590 this->RaiseWidget(WID_STL_CARGOSTART + i);
592 this->RaiseWidget(WID_STL_NOCARGOWAITING);
594 this->cargo_filter = 0;
595 this->include_empty = false;
597 SetBit(this->cargo_filter, cs->Index());
598 this->LowerWidget(widget);
600 this->stations.ForceRebuild();
601 this->SetDirty();
603 break;
607 virtual void OnDropdownSelect(int widget, int index)
609 if (this->stations.SortType() != index) {
610 this->stations.SetSortType(index);
612 /* Display the current sort variant */
613 this->GetWidget<NWidgetCore>(WID_STL_SORTDROPBTN)->widget_data = this->sorter_names[this->stations.SortType()];
615 this->SetDirty();
619 virtual void OnTick()
621 if (_pause_mode != PM_UNPAUSED) return;
622 if (this->stations.NeedResort()) {
623 DEBUG(misc, 3, "Periodic rebuild station list company %d", this->window_number);
624 this->SetDirty();
628 virtual void OnResize()
630 this->vscroll->SetCapacityFromWidget(this, WID_STL_LIST, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
634 * Some data on this window has become invalid.
635 * @param data Information about the changed data.
636 * @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.
638 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
640 if (data == 0) {
641 /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
642 this->stations.ForceRebuild();
643 } else {
644 this->stations.ForceResort();
649 Listing CompanyStationsWindow::last_sorting = {false, 0};
650 byte CompanyStationsWindow::facilities = FACIL_TRAIN | FACIL_TRUCK_STOP | FACIL_BUS_STOP | FACIL_AIRPORT | FACIL_DOCK;
651 bool CompanyStationsWindow::include_empty = true;
652 const uint32 CompanyStationsWindow::cargo_filter_max = UINT32_MAX;
653 uint32 CompanyStationsWindow::cargo_filter = UINT32_MAX;
654 const Station *CompanyStationsWindow::last_station = NULL;
656 /* Availible station sorting functions */
657 GUIStationList::SortFunction * const CompanyStationsWindow::sorter_funcs[] = {
658 &StationNameSorter,
659 &StationTypeSorter,
660 &StationWaitingTotalSorter,
661 &StationWaitingAvailableSorter,
662 &StationRatingMaxSorter,
663 &StationRatingMinSorter
666 /* Names of the sorting functions */
667 const StringID CompanyStationsWindow::sorter_names[] = {
668 STR_SORT_BY_NAME,
669 STR_SORT_BY_FACILITY,
670 STR_SORT_BY_WAITING_TOTAL,
671 STR_SORT_BY_WAITING_AVAILABLE,
672 STR_SORT_BY_RATING_MAX,
673 STR_SORT_BY_RATING_MIN,
674 INVALID_STRING_ID
678 * Make a horizontal row of cargo buttons, starting at widget #WID_STL_CARGOSTART.
679 * @param biggest_index Pointer to store biggest used widget number of the buttons.
680 * @return Horizontal row.
682 static NWidgetBase *CargoWidgets(int *biggest_index)
684 NWidgetHorizontal *container = new NWidgetHorizontal();
686 for (uint i = 0; i < _sorted_standard_cargo_specs_size; i++) {
687 NWidgetBackground *panel = new NWidgetBackground(WWT_PANEL, COLOUR_GREY, WID_STL_CARGOSTART + i);
688 panel->SetMinimalSize(14, 11);
689 panel->SetResize(0, 0);
690 panel->SetFill(0, 1);
691 panel->SetDataTip(0, STR_STATION_LIST_USE_CTRL_TO_SELECT_MORE);
692 container->Add(panel);
694 *biggest_index = WID_STL_CARGOSTART + _sorted_standard_cargo_specs_size;
695 return container;
698 static const NWidgetPart _nested_company_stations_widgets[] = {
699 NWidget(NWID_HORIZONTAL),
700 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
701 NWidget(WWT_CAPTION, COLOUR_GREY, WID_STL_CAPTION), SetDataTip(STR_STATION_LIST_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
702 NWidget(WWT_SHADEBOX, COLOUR_GREY),
703 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
704 NWidget(WWT_STICKYBOX, COLOUR_GREY),
705 EndContainer(),
706 NWidget(NWID_HORIZONTAL),
707 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),
708 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),
709 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),
710 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),
711 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),
712 NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_STL_FACILALL), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_SELECT_ALL_FACILITIES), SetFill(0, 1),
713 NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(5, 11), SetFill(0, 1), EndContainer(),
714 NWidgetFunction(CargoWidgets),
715 NWidget(WWT_PANEL, COLOUR_GREY, WID_STL_NOCARGOWAITING), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_NO_WAITING_CARGO), SetFill(0, 1), EndContainer(),
716 NWidget(WWT_PUSHBTN, COLOUR_GREY, WID_STL_CARGOALL), SetMinimalSize(14, 11), SetDataTip(0x0, STR_STATION_LIST_SELECT_ALL_TYPES), SetFill(0, 1),
717 NWidget(WWT_PANEL, COLOUR_GREY), SetDataTip(0x0, STR_NULL), SetResize(1, 0), SetFill(1, 1), EndContainer(),
718 EndContainer(),
719 NWidget(NWID_HORIZONTAL),
720 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_STL_SORTBY), SetMinimalSize(81, 12), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
721 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_STL_SORTDROPBTN), SetMinimalSize(163, 12), SetDataTip(STR_SORT_BY_NAME, STR_TOOLTIP_SORT_CRITERIA), // widget_data gets overwritten.
722 NWidget(WWT_PANEL, COLOUR_GREY), SetDataTip(0x0, STR_NULL), SetResize(1, 0), SetFill(1, 1), EndContainer(),
723 EndContainer(),
724 NWidget(NWID_HORIZONTAL),
725 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(),
726 NWidget(NWID_VERTICAL),
727 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_STL_SCROLLBAR),
728 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
729 EndContainer(),
730 EndContainer(),
733 static WindowDesc _company_stations_desc(
734 WDP_AUTO, "list_stations", 358, 162,
735 WC_STATION_LIST, WC_NONE,
737 _nested_company_stations_widgets, lengthof(_nested_company_stations_widgets)
741 * Opens window with list of company's stations
743 * @param company whose stations' list show
745 void ShowCompanyStations(CompanyID company)
747 if (!Company::IsValidID(company)) return;
749 AllocateWindowDescFront<CompanyStationsWindow>(&_company_stations_desc, company);
752 static const NWidgetPart _nested_station_view_widgets[] = {
753 NWidget(NWID_HORIZONTAL),
754 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
755 NWidget(WWT_CAPTION, COLOUR_GREY, WID_SV_CAPTION), SetDataTip(STR_STATION_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
756 NWidget(WWT_SHADEBOX, COLOUR_GREY),
757 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
758 NWidget(WWT_STICKYBOX, COLOUR_GREY),
759 EndContainer(),
760 NWidget(NWID_HORIZONTAL),
761 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_SORT_ORDER), SetMinimalSize(81, 12), SetFill(1, 1), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
762 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_SV_SORT_BY), SetMinimalSize(168, 12), SetResize(1, 0), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_SORT_CRITERIA),
763 EndContainer(),
764 NWidget(NWID_HORIZONTAL),
765 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_SV_GROUP), SetMinimalSize(81, 12), SetFill(1, 1), SetDataTip(STR_STATION_VIEW_GROUP, 0x0),
766 NWidget(WWT_DROPDOWN, COLOUR_GREY, WID_SV_GROUP_BY), SetMinimalSize(168, 12), SetResize(1, 0), SetFill(0, 1), SetDataTip(0x0, STR_TOOLTIP_GROUP_ORDER),
767 EndContainer(),
768 NWidget(NWID_HORIZONTAL),
769 NWidget(WWT_PANEL, COLOUR_GREY, WID_SV_WAITING), SetMinimalSize(237, 44), SetResize(1, 10), SetScrollbar(WID_SV_SCROLLBAR), EndContainer(),
770 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_SV_SCROLLBAR),
771 EndContainer(),
772 NWidget(WWT_PANEL, COLOUR_GREY, WID_SV_ACCEPT_RATING_LIST), SetMinimalSize(249, 23), SetResize(1, 0), EndContainer(),
773 NWidget(NWID_HORIZONTAL),
774 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
775 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_LOCATION), SetMinimalSize(45, 12), SetResize(1, 0), SetFill(1, 1),
776 SetDataTip(STR_BUTTON_LOCATION, STR_STATION_VIEW_CENTER_TOOLTIP),
777 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_ACCEPTS_RATINGS), SetMinimalSize(46, 12), SetResize(1, 0), SetFill(1, 1),
778 SetDataTip(STR_STATION_VIEW_RATINGS_BUTTON, STR_STATION_VIEW_RATINGS_TOOLTIP),
779 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_RENAME), SetMinimalSize(45, 12), SetResize(1, 0), SetFill(1, 1),
780 SetDataTip(STR_BUTTON_RENAME, STR_STATION_VIEW_RENAME_TOOLTIP),
781 EndContainer(),
782 NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_SV_CLOSE_AIRPORT), SetMinimalSize(45, 12), SetResize(1, 0), SetFill(1, 1),
783 SetDataTip(STR_STATION_VIEW_CLOSE_AIRPORT, STR_STATION_VIEW_CLOSE_AIRPORT_TOOLTIP),
784 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_TRAINS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_TRAIN, STR_STATION_VIEW_SCHEDULED_TRAINS_TOOLTIP),
785 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_ROADVEHS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_LORRY, STR_STATION_VIEW_SCHEDULED_ROAD_VEHICLES_TOOLTIP),
786 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_SHIPS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_SHIP, STR_STATION_VIEW_SCHEDULED_SHIPS_TOOLTIP),
787 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SV_PLANES), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_PLANE, STR_STATION_VIEW_SCHEDULED_AIRCRAFT_TOOLTIP),
788 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
789 EndContainer(),
793 * Draws icons of waiting cargo in the StationView window
795 * @param i type of cargo
796 * @param waiting number of waiting units
797 * @param left left most coordinate to draw on
798 * @param right right most coordinate to draw on
799 * @param y y coordinate
800 * @param width the width of the view
802 static void DrawCargoIcons(CargoID i, uint waiting, int left, int right, int y)
804 uint num = min((waiting + 5) / 10, (right - left) / 10); // maximum is width / 10 icons so it won't overflow
805 if (num == 0) return;
807 SpriteID sprite = CargoSpec::Get(i)->GetCargoIcon();
809 int x = _current_text_dir == TD_RTL ? left : right - num * 10;
810 do {
811 DrawSprite(sprite, PAL_NONE, x, y);
812 x += 10;
813 } while (--num);
816 enum SortOrder {
817 SO_DESCENDING,
818 SO_ASCENDING
821 class CargoDataEntry;
823 enum CargoSortType {
824 ST_AS_GROUPING, ///< by the same principle the entries are being grouped
825 ST_COUNT, ///< by amount of cargo
826 ST_STATION_STRING, ///< by station name
827 ST_STATION_ID, ///< by station id
828 ST_CARGO_ID, ///< by cargo id
831 class CargoSorter {
832 public:
833 CargoSorter(CargoSortType t = ST_STATION_ID, SortOrder o = SO_ASCENDING) : type(t), order(o) {}
834 CargoSortType GetSortType() {return this->type;}
835 bool operator()(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const;
837 private:
838 CargoSortType type;
839 SortOrder order;
841 template<class Tid>
842 bool SortId(Tid st1, Tid st2) const;
843 bool SortCount(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const;
844 bool SortStation (StationID st1, StationID st2) const;
847 typedef std::set<CargoDataEntry *, CargoSorter> CargoDataSet;
850 * A cargo data entry representing one possible row in the station view window's
851 * top part. Cargo data entries form a tree where each entry can have several
852 * children. Parents keep track of the sums of their childrens' cargo counts.
854 class CargoDataEntry {
855 public:
856 CargoDataEntry();
857 ~CargoDataEntry();
860 * Insert a new child or retrieve an existing child using a station ID as ID.
861 * @param station ID of the station for which an entry shall be created or retrieved
862 * @return a child entry associated with the given station.
864 CargoDataEntry *InsertOrRetrieve(StationID station)
866 return this->InsertOrRetrieve<StationID>(station);
870 * Insert a new child or retrieve an existing child using a cargo ID as ID.
871 * @param cargo ID of the cargo for which an entry shall be created or retrieved
872 * @return a child entry associated with the given cargo.
874 CargoDataEntry *InsertOrRetrieve(CargoID cargo)
876 return this->InsertOrRetrieve<CargoID>(cargo);
879 void Update(uint count);
882 * Remove a child associated with the given station.
883 * @param station ID of the station for which the child should be removed.
885 void Remove(StationID station)
887 CargoDataEntry t(station);
888 this->Remove(&t);
892 * Remove a child associated with the given cargo.
893 * @param cargo ID of the cargo for which the child should be removed.
895 void Remove(CargoID cargo)
897 CargoDataEntry t(cargo);
898 this->Remove(&t);
902 * Retrieve a child for the given station. Return NULL if it doesn't exist.
903 * @param station ID of the station the child we're looking for is associated with.
904 * @return a child entry for the given station or NULL.
906 CargoDataEntry *Retrieve(StationID station) const
908 CargoDataEntry t(station);
909 return this->Retrieve(this->children->find(&t));
913 * Retrieve a child for the given cargo. Return NULL if it doesn't exist.
914 * @param cargo ID of the cargo the child we're looking for is associated with.
915 * @return a child entry for the given cargo or NULL.
917 CargoDataEntry *Retrieve(CargoID cargo) const
919 CargoDataEntry t(cargo);
920 return this->Retrieve(this->children->find(&t));
923 void Resort(CargoSortType type, SortOrder order);
926 * Get the station ID for this entry.
928 StationID GetStation() const { return this->station; }
931 * Get the cargo ID for this entry.
933 CargoID GetCargo() const { return this->cargo; }
936 * Get the cargo count for this entry.
938 uint GetCount() const { return this->count; }
941 * Get the parent entry for this entry.
943 CargoDataEntry *GetParent() const { return this->parent; }
946 * Get the number of children for this entry.
948 uint GetNumChildren() const { return this->num_children; }
951 * Get an iterator pointing to the begin of the set of children.
953 CargoDataSet::iterator Begin() const { return this->children->begin(); }
956 * Get an iterator pointing to the end of the set of children.
958 CargoDataSet::iterator End() const { return this->children->end(); }
961 * Has this entry transfers.
963 bool HasTransfers() const { return this->transfers; }
966 * Set the transfers state.
968 void SetTransfers(bool value) { this->transfers = value; }
970 void Clear();
971 private:
973 CargoDataEntry(StationID st, uint c, CargoDataEntry *p);
974 CargoDataEntry(CargoID car, uint c, CargoDataEntry *p);
975 CargoDataEntry(StationID st);
976 CargoDataEntry(CargoID car);
978 CargoDataEntry *Retrieve(CargoDataSet::iterator i) const;
980 template<class Tid>
981 CargoDataEntry *InsertOrRetrieve(Tid s);
983 void Remove(CargoDataEntry *comp);
984 void IncrementSize();
986 CargoDataEntry *parent; ///< the parent of this entry.
987 const union {
988 StationID station; ///< ID of the station this entry is associated with.
989 struct {
990 CargoID cargo; ///< ID of the cargo this entry is associated with.
991 bool transfers; ///< If there are transfers for this cargo.
994 uint num_children; ///< the number of subentries belonging to this entry.
995 uint count; ///< sum of counts of all children or amount of cargo for this entry.
996 CargoDataSet *children; ///< the children of this entry.
999 CargoDataEntry::CargoDataEntry() :
1000 parent(NULL),
1001 station(INVALID_STATION),
1002 num_children(0),
1003 count(0),
1004 children(new CargoDataSet(CargoSorter(ST_CARGO_ID)))
1007 CargoDataEntry::CargoDataEntry(CargoID cargo, uint count, CargoDataEntry *parent) :
1008 parent(parent),
1009 cargo(cargo),
1010 num_children(0),
1011 count(count),
1012 children(new CargoDataSet)
1015 CargoDataEntry::CargoDataEntry(StationID station, uint count, CargoDataEntry *parent) :
1016 parent(parent),
1017 station(station),
1018 num_children(0),
1019 count(count),
1020 children(new CargoDataSet)
1023 CargoDataEntry::CargoDataEntry(StationID station) :
1024 parent(NULL),
1025 station(station),
1026 num_children(0),
1027 count(0),
1028 children(NULL)
1031 CargoDataEntry::CargoDataEntry(CargoID cargo) :
1032 parent(NULL),
1033 cargo(cargo),
1034 num_children(0),
1035 count(0),
1036 children(NULL)
1039 CargoDataEntry::~CargoDataEntry()
1041 this->Clear();
1042 delete this->children;
1046 * Delete all subentries, reset count and num_children and adapt parent's count.
1048 void CargoDataEntry::Clear()
1050 if (this->children != NULL) {
1051 for (CargoDataSet::iterator i = this->children->begin(); i != this->children->end(); ++i) {
1052 assert(*i != this);
1053 delete *i;
1055 this->children->clear();
1057 if (this->parent != NULL) this->parent->count -= this->count;
1058 this->count = 0;
1059 this->num_children = 0;
1063 * Remove a subentry from this one and delete it.
1064 * @param child the entry to be removed. This may also be a synthetic entry
1065 * which only contains the ID of the entry to be removed. In this case child is
1066 * not deleted.
1068 void CargoDataEntry::Remove(CargoDataEntry *child)
1070 CargoDataSet::iterator i = this->children->find(child);
1071 if (i != this->children->end()) {
1072 delete *i;
1073 this->children->erase(i);
1078 * Retrieve a subentry or insert it if it doesn't exist, yet.
1079 * @tparam ID type of ID: either StationID or CargoID
1080 * @param child_id ID of the child to be inserted or retrieved.
1081 * @return the new or retrieved subentry
1083 template<class Tid>
1084 CargoDataEntry *CargoDataEntry::InsertOrRetrieve(Tid child_id)
1086 CargoDataEntry tmp(child_id);
1087 CargoDataSet::iterator i = this->children->find(&tmp);
1088 if (i == this->children->end()) {
1089 IncrementSize();
1090 return *(this->children->insert(new CargoDataEntry(child_id, 0, this)).first);
1091 } else {
1092 CargoDataEntry *ret = *i;
1093 assert(this->children->value_comp().GetSortType() != ST_COUNT);
1094 return ret;
1099 * Update the count for this entry and propagate the change to the parent entry
1100 * if there is one.
1101 * @param count the amount to be added to this entry
1103 void CargoDataEntry::Update(uint count)
1105 this->count += count;
1106 if (this->parent != NULL) this->parent->Update(count);
1110 * Increment
1112 void CargoDataEntry::IncrementSize()
1114 ++this->num_children;
1115 if (this->parent != NULL) this->parent->IncrementSize();
1118 void CargoDataEntry::Resort(CargoSortType type, SortOrder order)
1120 CargoDataSet *new_subs = new CargoDataSet(this->children->begin(), this->children->end(), CargoSorter(type, order));
1121 delete this->children;
1122 this->children = new_subs;
1125 CargoDataEntry *CargoDataEntry::Retrieve(CargoDataSet::iterator i) const
1127 if (i == this->children->end()) {
1128 return NULL;
1129 } else {
1130 assert(this->children->value_comp().GetSortType() != ST_COUNT);
1131 return *i;
1135 bool CargoSorter::operator()(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const
1137 switch (this->type) {
1138 case ST_STATION_ID:
1139 return this->SortId<StationID>(cd1->GetStation(), cd2->GetStation());
1140 case ST_CARGO_ID:
1141 return this->SortId<CargoID>(cd1->GetCargo(), cd2->GetCargo());
1142 case ST_COUNT:
1143 return this->SortCount(cd1, cd2);
1144 case ST_STATION_STRING:
1145 return this->SortStation(cd1->GetStation(), cd2->GetStation());
1146 default:
1147 NOT_REACHED();
1151 template<class Tid>
1152 bool CargoSorter::SortId(Tid st1, Tid st2) const
1154 return (this->order == SO_ASCENDING) ? st1 < st2 : st2 < st1;
1157 bool CargoSorter::SortCount(const CargoDataEntry *cd1, const CargoDataEntry *cd2) const
1159 uint c1 = cd1->GetCount();
1160 uint c2 = cd2->GetCount();
1161 if (c1 == c2) {
1162 return this->SortStation(cd1->GetStation(), cd2->GetStation());
1163 } else if (this->order == SO_ASCENDING) {
1164 return c1 < c2;
1165 } else {
1166 return c2 < c1;
1170 bool CargoSorter::SortStation(StationID st1, StationID st2) const
1172 static char buf1[MAX_LENGTH_STATION_NAME_CHARS];
1173 static char buf2[MAX_LENGTH_STATION_NAME_CHARS];
1175 if (!Station::IsValidID(st1)) {
1176 return Station::IsValidID(st2) ? this->order == SO_ASCENDING : this->SortId(st1, st2);
1177 } else if (!Station::IsValidID(st2)) {
1178 return order == SO_DESCENDING;
1181 SetDParam(0, st1);
1182 GetString(buf1, STR_STATION_NAME, lastof(buf1));
1183 SetDParam(0, st2);
1184 GetString(buf2, STR_STATION_NAME, lastof(buf2));
1186 int res = strcmp(buf1, buf2);
1187 if (res == 0) {
1188 return this->SortId(st1, st2);
1189 } else {
1190 return (this->order == SO_ASCENDING) ? res < 0 : res > 0;
1195 * The StationView window
1197 struct StationViewWindow : public Window {
1199 * A row being displayed in the cargo view (as opposed to being "hidden" behind a plus sign).
1201 struct RowDisplay {
1202 RowDisplay(CargoDataEntry *f, StationID n) : filter(f), next_station(n) {}
1203 RowDisplay(CargoDataEntry *f, CargoID n) : filter(f), next_cargo(n) {}
1206 * Parent of the cargo entry belonging to the row.
1208 CargoDataEntry *filter;
1209 union {
1211 * ID of the station belonging to the entry actually displayed if it's to/from/via.
1213 StationID next_station;
1216 * ID of the cargo belonging to the entry actually displayed if it's cargo.
1218 CargoID next_cargo;
1222 typedef std::vector<RowDisplay> CargoDataVector;
1224 static const int NUM_COLUMNS = 4; ///< Number of "columns" in the cargo view: cargo, from, via, to
1227 * Type of data invalidation.
1229 enum Invalidation {
1230 INV_FLOWS = 0x100, ///< The planned flows have been recalculated and everything has to be updated.
1231 INV_CARGO = 0x200 ///< Some cargo has been added or removed.
1235 * Type of grouping used in each of the "columns".
1237 enum Grouping {
1238 GR_SOURCE, ///< Group by source of cargo ("from").
1239 GR_NEXT, ///< Group by next station ("via").
1240 GR_DESTINATION, ///< Group by estimated final destination ("to").
1241 GR_CARGO, ///< Group by cargo type.
1245 * Display mode of the cargo view.
1247 enum Mode {
1248 MODE_WAITING, ///< Show cargo waiting at the station.
1249 MODE_PLANNED ///< Show cargo planned to pass through the station.
1252 uint expand_shrink_width; ///< The width allocated to the expand/shrink 'button'
1253 int rating_lines; ///< Number of lines in the cargo ratings view.
1254 int accepts_lines; ///< Number of lines in the accepted cargo view.
1255 Scrollbar *vscroll;
1257 /** Height of the #WID_SV_ACCEPT_RATING_LIST widget for different views. */
1258 enum AcceptListHeight {
1259 ALH_RATING = 13, ///< Height of the cargo ratings view.
1260 ALH_ACCEPTS = 3, ///< Height of the accepted cargo view.
1263 static const StringID _sort_names[]; ///< Names of the sorting options in the dropdown.
1264 static const StringID _group_names[]; ///< Names of the grouping options in the dropdown.
1267 * Sort types of the different 'columns'.
1268 * In fact only ST_COUNT and ST_AS_GROUPING are active and you can only
1269 * sort all the columns in the same way. The other options haven't been
1270 * included in the GUI due to lack of space.
1272 CargoSortType sortings[NUM_COLUMNS];
1274 /** Sort order (ascending/descending) for the 'columns'. */
1275 SortOrder sort_orders[NUM_COLUMNS];
1277 int scroll_to_row; ///< If set, scroll the main viewport to the station pointed to by this row.
1278 int grouping_index; ///< Currently selected entry in the grouping drop down.
1279 Mode current_mode; ///< Currently selected display mode of cargo view.
1280 Grouping groupings[NUM_COLUMNS]; ///< Grouping modes for the different columns.
1282 CargoDataEntry expanded_rows; ///< Parent entry of currently expanded rows.
1283 CargoDataEntry cached_destinations; ///< Cache for the flows passing through this station.
1284 CargoDataVector displayed_rows; ///< Parent entry of currently displayed rows (including collapsed ones).
1286 StationViewWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc),
1287 scroll_to_row(INT_MAX), grouping_index(0)
1289 this->rating_lines = ALH_RATING;
1290 this->accepts_lines = ALH_ACCEPTS;
1292 this->CreateNestedTree();
1293 this->vscroll = this->GetScrollbar(WID_SV_SCROLLBAR);
1294 /* Nested widget tree creation is done in two steps to ensure that this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS) exists in UpdateWidgetSize(). */
1295 this->FinishInitNested(window_number);
1297 this->groupings[0] = GR_CARGO;
1298 this->sortings[0] = ST_AS_GROUPING;
1299 this->SelectGroupBy(_settings_client.gui.station_gui_group_order);
1300 this->SelectSortBy(_settings_client.gui.station_gui_sort_by);
1301 this->sort_orders[0] = SO_ASCENDING;
1302 this->SelectSortOrder((SortOrder)_settings_client.gui.station_gui_sort_order);
1303 Owner owner = Station::Get(window_number)->owner;
1304 if (owner != OWNER_NONE) this->owner = owner;
1307 ~StationViewWindow()
1309 Owner owner = Station::Get(this->window_number)->owner;
1310 DeleteWindowById(WC_TRAINS_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_TRAIN, owner, this->window_number).Pack(), false);
1311 DeleteWindowById(WC_ROADVEH_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_ROAD, owner, this->window_number).Pack(), false);
1312 DeleteWindowById(WC_SHIPS_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_SHIP, owner, this->window_number).Pack(), false);
1313 DeleteWindowById(WC_AIRCRAFT_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_AIRCRAFT, owner, this->window_number).Pack(), false);
1317 * Show a certain cargo entry characterized by source/next/dest station, cargo ID and amount of cargo at the
1318 * right place in the cargo view. I.e. update as many rows as are expanded following that characterization.
1319 * @param data Root entry of the tree.
1320 * @param cargo Cargo ID of the entry to be shown.
1321 * @param source Source station of the entry to be shown.
1322 * @param next Next station the cargo to be shown will visit.
1323 * @param dest Final destination of the cargo to be shown.
1324 * @param count Amount of cargo to be shown.
1326 void ShowCargo(CargoDataEntry *data, CargoID cargo, StationID source, StationID next, StationID dest, uint count)
1328 if (count == 0) return;
1329 bool auto_distributed = _settings_game.linkgraph.GetDistributionType(cargo) != DT_MANUAL;
1330 const CargoDataEntry *expand = &this->expanded_rows;
1331 for (int i = 0; i < NUM_COLUMNS && expand != NULL; ++i) {
1332 switch (groupings[i]) {
1333 case GR_CARGO:
1334 assert(i == 0);
1335 data = data->InsertOrRetrieve(cargo);
1336 data->SetTransfers(source != this->window_number);
1337 expand = expand->Retrieve(cargo);
1338 break;
1339 case GR_SOURCE:
1340 if (auto_distributed || source != this->window_number) {
1341 data = data->InsertOrRetrieve(source);
1342 expand = expand->Retrieve(source);
1344 break;
1345 case GR_NEXT:
1346 if (auto_distributed) {
1347 data = data->InsertOrRetrieve(next);
1348 expand = expand->Retrieve(next);
1350 break;
1351 case GR_DESTINATION:
1352 if (auto_distributed) {
1353 data = data->InsertOrRetrieve(dest);
1354 expand = expand->Retrieve(dest);
1356 break;
1359 data->Update(count);
1362 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
1364 switch (widget) {
1365 case WID_SV_WAITING:
1366 resize->height = FONT_HEIGHT_NORMAL;
1367 size->height = WD_FRAMERECT_TOP + 4 * resize->height + WD_FRAMERECT_BOTTOM;
1368 this->expand_shrink_width = max(GetStringBoundingBox("-").width, GetStringBoundingBox("+").width) + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
1369 break;
1371 case WID_SV_ACCEPT_RATING_LIST:
1372 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;
1373 break;
1375 case WID_SV_CLOSE_AIRPORT:
1376 if (!(Station::Get(this->window_number)->facilities & FACIL_AIRPORT)) {
1377 /* Hide 'Close Airport' button if no airport present. */
1378 size->width = 0;
1379 resize->width = 0;
1380 fill->width = 0;
1382 break;
1386 virtual void OnPaint()
1388 const Station *st = Station::Get(this->window_number);
1389 CargoDataEntry cargo;
1390 BuildCargoList(&cargo, st);
1392 this->vscroll->SetCount(cargo.GetNumChildren()); // update scrollbar
1394 /* disable some buttons */
1395 this->SetWidgetDisabledState(WID_SV_RENAME, st->owner != _local_company);
1396 this->SetWidgetDisabledState(WID_SV_TRAINS, !(st->facilities & FACIL_TRAIN));
1397 this->SetWidgetDisabledState(WID_SV_ROADVEHS, !(st->facilities & FACIL_TRUCK_STOP) && !(st->facilities & FACIL_BUS_STOP));
1398 this->SetWidgetDisabledState(WID_SV_SHIPS, !(st->facilities & FACIL_DOCK));
1399 this->SetWidgetDisabledState(WID_SV_PLANES, !(st->facilities & FACIL_AIRPORT));
1400 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
1401 this->SetWidgetLoweredState(WID_SV_CLOSE_AIRPORT, (st->facilities & FACIL_AIRPORT) && (st->airport.flags & AIRPORT_CLOSED_block) != 0);
1403 this->DrawWidgets();
1405 if (!this->IsShaded()) {
1406 /* Draw 'accepted cargo' or 'cargo ratings'. */
1407 const NWidgetBase *wid = this->GetWidget<NWidgetBase>(WID_SV_ACCEPT_RATING_LIST);
1408 const Rect r = {wid->pos_x, wid->pos_y, wid->pos_x + wid->current_x - 1, wid->pos_y + wid->current_y - 1};
1409 if (this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) {
1410 int lines = this->DrawAcceptedCargo(r);
1411 if (lines > this->accepts_lines) { // Resize the widget, and perform re-initialization of the window.
1412 this->accepts_lines = lines;
1413 this->ReInit();
1414 return;
1416 } else {
1417 int lines = this->DrawCargoRatings(r);
1418 if (lines > this->rating_lines) { // Resize the widget, and perform re-initialization of the window.
1419 this->rating_lines = lines;
1420 this->ReInit();
1421 return;
1425 /* Draw arrow pointing up/down for ascending/descending sorting */
1426 this->DrawSortButtonState(WID_SV_SORT_ORDER, sort_orders[1] == SO_ASCENDING ? SBS_UP : SBS_DOWN);
1428 int pos = this->vscroll->GetPosition();
1430 int maxrows = this->vscroll->GetCapacity();
1432 displayed_rows.clear();
1434 /* Draw waiting cargo. */
1435 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_SV_WAITING);
1436 Rect waiting_rect = {nwi->pos_x, nwi->pos_y, nwi->pos_x + nwi->current_x - 1, nwi->pos_y + nwi->current_y - 1};
1437 this->DrawEntries(&cargo, waiting_rect, pos, maxrows, 0);
1438 scroll_to_row = INT_MAX;
1442 virtual void SetStringParameters(int widget) const
1444 const Station *st = Station::Get(this->window_number);
1445 SetDParam(0, st->index);
1446 SetDParam(1, st->facilities);
1450 * Rebuild the cache for estimated destinations which is used to quickly show the "destination" entries
1451 * even if we actually don't know the destination of a certain packet from just looking at it.
1452 * @param i Cargo to recalculate the cache for.
1454 void RecalcDestinations(CargoID i)
1456 const Station *st = Station::Get(this->window_number);
1457 CargoDataEntry *cargo_entry = cached_destinations.InsertOrRetrieve(i);
1458 cargo_entry->Clear();
1460 const FlowStatMap &flows = st->goods[i].flows;
1461 for (FlowStatMap::const_iterator it = flows.begin(); it != flows.end(); ++it) {
1462 StationID from = it->first;
1463 CargoDataEntry *source_entry = cargo_entry->InsertOrRetrieve(from);
1464 const FlowStat::SharesMap *shares = it->second.GetShares();
1465 uint32 prev_count = 0;
1466 for (FlowStat::SharesMap::const_iterator flow_it = shares->begin(); flow_it != shares->end(); ++flow_it) {
1467 StationID via = flow_it->second;
1468 CargoDataEntry *via_entry = source_entry->InsertOrRetrieve(via);
1469 if (via == this->window_number) {
1470 via_entry->InsertOrRetrieve(via)->Update(flow_it->first - prev_count);
1471 } else {
1472 EstimateDestinations(i, from, via, flow_it->first - prev_count, via_entry);
1474 prev_count = flow_it->first;
1480 * Estimate the amounts of cargo per final destination for a given cargo, source station and next hop and
1481 * save the result as children of the given CargoDataEntry.
1482 * @param cargo ID of the cargo to estimate destinations for.
1483 * @param source Source station of the given batch of cargo.
1484 * @param next Intermediate hop to start the calculation at ("next hop").
1485 * @param count Size of the batch of cargo.
1486 * @param dest CargoDataEntry to save the results in.
1488 void EstimateDestinations(CargoID cargo, StationID source, StationID next, uint count, CargoDataEntry *dest)
1490 if (Station::IsValidID(next) && Station::IsValidID(source)) {
1491 CargoDataEntry tmp;
1492 const FlowStatMap &flowmap = Station::Get(next)->goods[cargo].flows;
1493 FlowStatMap::const_iterator map_it = flowmap.find(source);
1494 if (map_it != flowmap.end()) {
1495 const FlowStat::SharesMap *shares = map_it->second.GetShares();
1496 uint32 prev_count = 0;
1497 for (FlowStat::SharesMap::const_iterator i = shares->begin(); i != shares->end(); ++i) {
1498 tmp.InsertOrRetrieve(i->second)->Update(i->first - prev_count);
1499 prev_count = i->first;
1503 if (tmp.GetCount() == 0) {
1504 dest->InsertOrRetrieve(INVALID_STATION)->Update(count);
1505 } else {
1506 uint sum_estimated = 0;
1507 while (sum_estimated < count) {
1508 for (CargoDataSet::iterator i = tmp.Begin(); i != tmp.End() && sum_estimated < count; ++i) {
1509 CargoDataEntry *child = *i;
1510 uint estimate = DivideApprox(child->GetCount() * count, tmp.GetCount());
1511 if (estimate == 0) estimate = 1;
1513 sum_estimated += estimate;
1514 if (sum_estimated > count) {
1515 estimate -= sum_estimated - count;
1516 sum_estimated = count;
1519 if (estimate > 0) {
1520 if (child->GetStation() == next) {
1521 dest->InsertOrRetrieve(next)->Update(estimate);
1522 } else {
1523 EstimateDestinations(cargo, source, child->GetStation(), estimate, dest);
1530 } else {
1531 dest->InsertOrRetrieve(INVALID_STATION)->Update(count);
1536 * Build up the cargo view for PLANNED mode and a specific cargo.
1537 * @param i Cargo to show.
1538 * @param flows The current station's flows for that cargo.
1539 * @param cargo The CargoDataEntry to save the results in.
1541 void BuildFlowList(CargoID i, const FlowStatMap &flows, CargoDataEntry *cargo)
1543 const CargoDataEntry *source_dest = this->cached_destinations.Retrieve(i);
1544 for (FlowStatMap::const_iterator it = flows.begin(); it != flows.end(); ++it) {
1545 StationID from = it->first;
1546 const CargoDataEntry *source_entry = source_dest->Retrieve(from);
1547 const FlowStat::SharesMap *shares = it->second.GetShares();
1548 for (FlowStat::SharesMap::const_iterator flow_it = shares->begin(); flow_it != shares->end(); ++flow_it) {
1549 const CargoDataEntry *via_entry = source_entry->Retrieve(flow_it->second);
1550 for (CargoDataSet::iterator dest_it = via_entry->Begin(); dest_it != via_entry->End(); ++dest_it) {
1551 CargoDataEntry *dest_entry = *dest_it;
1552 ShowCargo(cargo, i, from, flow_it->second, dest_entry->GetStation(), dest_entry->GetCount());
1559 * Build up the cargo view for WAITING mode and a specific cargo.
1560 * @param i Cargo to show.
1561 * @param packets The current station's cargo list for that cargo.
1562 * @param cargo The CargoDataEntry to save the result in.
1564 void BuildCargoList(CargoID i, const StationCargoList &packets, CargoDataEntry *cargo)
1566 const CargoDataEntry *source_dest = this->cached_destinations.Retrieve(i);
1567 for (StationCargoList::ConstIterator it = packets.Packets()->begin(); it != packets.Packets()->end(); it++) {
1568 const CargoPacket *cp = *it;
1569 StationID next = it.GetKey();
1571 const CargoDataEntry *source_entry = source_dest->Retrieve(cp->SourceStation());
1572 if (source_entry == NULL) {
1573 this->ShowCargo(cargo, i, cp->SourceStation(), next, INVALID_STATION, cp->Count());
1574 continue;
1577 const CargoDataEntry *via_entry = source_entry->Retrieve(next);
1578 if (via_entry == NULL) {
1579 this->ShowCargo(cargo, i, cp->SourceStation(), next, INVALID_STATION, cp->Count());
1580 continue;
1583 for (CargoDataSet::iterator dest_it = via_entry->Begin(); dest_it != via_entry->End(); ++dest_it) {
1584 CargoDataEntry *dest_entry = *dest_it;
1585 uint val = DivideApprox(cp->Count() * dest_entry->GetCount(), via_entry->GetCount());
1586 this->ShowCargo(cargo, i, cp->SourceStation(), next, dest_entry->GetStation(), val);
1589 this->ShowCargo(cargo, i, NEW_STATION, NEW_STATION, NEW_STATION, packets.ReservedCount());
1593 * Build up the cargo view for all cargoes.
1594 * @param cargo The root cargo entry to save all results in.
1595 * @param st The station to calculate the cargo view from.
1597 void BuildCargoList(CargoDataEntry *cargo, const Station *st)
1599 for (CargoID i = 0; i < NUM_CARGO; i++) {
1601 if (this->cached_destinations.Retrieve(i) == NULL) {
1602 this->RecalcDestinations(i);
1605 if (this->current_mode == MODE_WAITING) {
1606 this->BuildCargoList(i, st->goods[i].cargo, cargo);
1607 } else {
1608 this->BuildFlowList(i, st->goods[i].flows, cargo);
1614 * Mark a specific row, characterized by its CargoDataEntry, as expanded.
1615 * @param data The row to be marked as expanded.
1617 void SetDisplayedRow(const CargoDataEntry *data)
1619 std::list<StationID> stations;
1620 const CargoDataEntry *parent = data->GetParent();
1621 if (parent->GetParent() == NULL) {
1622 this->displayed_rows.push_back(RowDisplay(&this->expanded_rows, data->GetCargo()));
1623 return;
1626 StationID next = data->GetStation();
1627 while (parent->GetParent()->GetParent() != NULL) {
1628 stations.push_back(parent->GetStation());
1629 parent = parent->GetParent();
1632 CargoID cargo = parent->GetCargo();
1633 CargoDataEntry *filter = this->expanded_rows.Retrieve(cargo);
1634 while (!stations.empty()) {
1635 filter = filter->Retrieve(stations.back());
1636 stations.pop_back();
1639 this->displayed_rows.push_back(RowDisplay(filter, next));
1643 * Select the correct string for an entry referring to the specified station.
1644 * @param station Station the entry is showing cargo for.
1645 * @param here String to be shown if the entry refers to the same station as this station GUI belongs to.
1646 * @param other_station String to be shown if the entry refers to a specific other station.
1647 * @param any String to be shown if the entry refers to "any station".
1648 * @return One of the three given strings or STR_STATION_VIEW_RESERVED, depending on what station the entry refers to.
1650 StringID GetEntryString(StationID station, StringID here, StringID other_station, StringID any)
1652 if (station == this->window_number) {
1653 return here;
1654 } else if (station == INVALID_STATION) {
1655 return any;
1656 } else if (station == NEW_STATION) {
1657 return STR_STATION_VIEW_RESERVED;
1658 } else {
1659 SetDParam(2, station);
1660 return other_station;
1665 * Determine if we need to show the special "non-stop" string.
1666 * @param cd Entry we are going to show.
1667 * @param station Station the entry refers to.
1668 * @param column The "column" the entry will be shown in.
1669 * @return either STR_STATION_VIEW_VIA or STR_STATION_VIEW_NONSTOP.
1671 StringID SearchNonStop(CargoDataEntry *cd, StationID station, int column)
1673 CargoDataEntry *parent = cd->GetParent();
1674 for (int i = column - 1; i > 0; --i) {
1675 if (this->groupings[i] == GR_DESTINATION) {
1676 if (parent->GetStation() == station) {
1677 return STR_STATION_VIEW_NONSTOP;
1678 } else {
1679 return STR_STATION_VIEW_VIA;
1682 parent = parent->GetParent();
1685 if (this->groupings[column + 1] == GR_DESTINATION) {
1686 CargoDataSet::iterator begin = cd->Begin();
1687 CargoDataSet::iterator end = cd->End();
1688 if (begin != end && ++(cd->Begin()) == end && (*(begin))->GetStation() == station) {
1689 return STR_STATION_VIEW_NONSTOP;
1690 } else {
1691 return STR_STATION_VIEW_VIA;
1695 return STR_STATION_VIEW_VIA;
1699 * Draw the given cargo entries in the station GUI.
1700 * @param entry Root entry for all cargo to be drawn.
1701 * @param r Screen rectangle to draw into.
1702 * @param pos Current row to be drawn to (counted down from 0 to -maxrows, same as vscroll->GetPosition()).
1703 * @param maxrows Maximum row to be drawn.
1704 * @param column Current "column" being drawn.
1705 * @param cargo Current cargo being drawn (if cargo column has been passed).
1706 * @return row (in "pos" counting) after the one we have last drawn to.
1708 int DrawEntries(CargoDataEntry *entry, Rect &r, int pos, int maxrows, int column, CargoID cargo = CT_INVALID)
1710 if (this->sortings[column] == ST_AS_GROUPING) {
1711 if (this->groupings[column] != GR_CARGO) {
1712 entry->Resort(ST_STATION_STRING, this->sort_orders[column]);
1714 } else {
1715 entry->Resort(ST_COUNT, this->sort_orders[column]);
1717 for (CargoDataSet::iterator i = entry->Begin(); i != entry->End(); ++i) {
1718 CargoDataEntry *cd = *i;
1720 Grouping grouping = this->groupings[column];
1721 if (grouping == GR_CARGO) cargo = cd->GetCargo();
1722 bool auto_distributed = _settings_game.linkgraph.GetDistributionType(cargo) != DT_MANUAL;
1724 if (pos > -maxrows && pos <= 0) {
1725 StringID str = STR_EMPTY;
1726 int y = r.top + WD_FRAMERECT_TOP - pos * FONT_HEIGHT_NORMAL;
1727 SetDParam(0, cargo);
1728 SetDParam(1, cd->GetCount());
1730 if (this->groupings[column] == GR_CARGO) {
1731 str = STR_STATION_VIEW_WAITING_CARGO;
1732 DrawCargoIcons(cd->GetCargo(), cd->GetCount(), r.left + WD_FRAMERECT_LEFT + this->expand_shrink_width, r.right - WD_FRAMERECT_RIGHT - this->expand_shrink_width, y);
1733 } else {
1734 if (!auto_distributed) grouping = GR_SOURCE;
1735 StationID station = cd->GetStation();
1737 switch (grouping) {
1738 case GR_SOURCE:
1739 str = this->GetEntryString(station, STR_STATION_VIEW_FROM_HERE, STR_STATION_VIEW_FROM, STR_STATION_VIEW_FROM_ANY);
1740 break;
1741 case GR_NEXT:
1742 str = this->GetEntryString(station, STR_STATION_VIEW_VIA_HERE, STR_STATION_VIEW_VIA, STR_STATION_VIEW_VIA_ANY);
1743 if (str == STR_STATION_VIEW_VIA) str = this->SearchNonStop(cd, station, column);
1744 break;
1745 case GR_DESTINATION:
1746 str = this->GetEntryString(station, STR_STATION_VIEW_TO_HERE, STR_STATION_VIEW_TO, STR_STATION_VIEW_TO_ANY);
1747 break;
1748 default:
1749 NOT_REACHED();
1751 if (pos == -this->scroll_to_row && Station::IsValidID(station)) {
1752 ScrollMainWindowToTile(Station::Get(station)->xy);
1756 bool rtl = _current_text_dir == TD_RTL;
1757 int text_left = rtl ? r.left + this->expand_shrink_width : r.left + WD_FRAMERECT_LEFT + column * this->expand_shrink_width;
1758 int text_right = rtl ? r.right - WD_FRAMERECT_LEFT - column * this->expand_shrink_width : r.right - this->expand_shrink_width;
1759 int shrink_left = rtl ? r.left + WD_FRAMERECT_LEFT : r.right - this->expand_shrink_width + WD_FRAMERECT_LEFT;
1760 int shrink_right = rtl ? r.left + this->expand_shrink_width - WD_FRAMERECT_RIGHT : r.right - WD_FRAMERECT_RIGHT;
1762 DrawString(text_left, text_right, y, str);
1764 if (column < NUM_COLUMNS - 1) {
1765 const char *sym = NULL;
1766 if (cd->GetNumChildren() > 0) {
1767 sym = "-";
1768 } else if (auto_distributed && str != STR_STATION_VIEW_RESERVED) {
1769 sym = "+";
1770 } else {
1771 /* Only draw '+' if there is something to be shown. */
1772 const StationCargoList &list = Station::Get(this->window_number)->goods[cargo].cargo;
1773 if (grouping == GR_CARGO && (list.ReservedCount() > 0 || cd->HasTransfers())) {
1774 sym = "+";
1777 if (sym) DrawString(shrink_left, shrink_right, y, sym, TC_YELLOW);
1779 this->SetDisplayedRow(cd);
1781 --pos;
1782 if (auto_distributed || column == 0) {
1783 pos = this->DrawEntries(cd, r, pos, maxrows, column + 1, cargo);
1786 return pos;
1790 * Draw accepted cargo in the #WID_SV_ACCEPT_RATING_LIST widget.
1791 * @param r Rectangle of the widget.
1792 * @return Number of lines needed for drawing the accepted cargo.
1794 int DrawAcceptedCargo(const Rect &r) const
1796 const Station *st = Station::Get(this->window_number);
1798 uint32 cargo_mask = 0;
1799 for (CargoID i = 0; i < NUM_CARGO; i++) {
1800 if (HasBit(st->goods[i].acceptance_pickup, GoodsEntry::GES_ACCEPTANCE)) SetBit(cargo_mask, i);
1802 SetDParam(0, cargo_mask);
1803 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);
1804 return CeilDiv(bottom - r.top - WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL);
1808 * Draw cargo ratings in the #WID_SV_ACCEPT_RATING_LIST widget.
1809 * @param r Rectangle of the widget.
1810 * @return Number of lines needed for drawing the cargo ratings.
1812 int DrawCargoRatings(const Rect &r) const
1814 const Station *st = Station::Get(this->window_number);
1815 int y = r.top + WD_FRAMERECT_TOP;
1817 if (st->town->exclusive_counter > 0) {
1818 SetDParam(0, st->town->exclusivity);
1819 y = DrawStringMultiLine(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, r.bottom, st->town->exclusivity == st->owner ? STR_STATIOV_VIEW_EXCLUSIVE_RIGHTS_SELF : STR_STATIOV_VIEW_EXCLUSIVE_RIGHTS_COMPANY);
1820 y += WD_PAR_VSEP_WIDE;
1823 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_STATION_VIEW_SUPPLY_RATINGS_TITLE);
1824 y += FONT_HEIGHT_NORMAL;
1826 const CargoSpec *cs;
1827 FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
1828 const GoodsEntry *ge = &st->goods[cs->Index()];
1829 if (!ge->HasRating()) continue;
1831 const LinkGraph *lg = LinkGraph::GetIfValid(ge->link_graph);
1832 SetDParam(0, cs->name);
1833 SetDParam(1, lg != NULL ? lg->Monthly((*lg)[ge->node].Supply()) : 0);
1834 SetDParam(2, STR_CARGO_RATING_APPALLING + (ge->rating >> 5));
1835 SetDParam(3, ToPercent8(ge->rating));
1836 DrawString(r.left + WD_FRAMERECT_LEFT + 6, r.right - WD_FRAMERECT_RIGHT - 6, y, STR_STATION_VIEW_CARGO_SUPPLY_RATING);
1837 y += FONT_HEIGHT_NORMAL;
1839 return CeilDiv(y - r.top - WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL);
1843 * Expand or collapse a specific row.
1844 * @param filter Parent of the row.
1845 * @param next ID pointing to the row.
1847 template<class Tid>
1848 void HandleCargoWaitingClick(CargoDataEntry *filter, Tid next)
1850 if (filter->Retrieve(next) != NULL) {
1851 filter->Remove(next);
1852 } else {
1853 filter->InsertOrRetrieve(next);
1858 * Handle a click on a specific row in the cargo view.
1859 * @param row Row being clicked.
1861 void HandleCargoWaitingClick(int row)
1863 if (row < 0 || (uint)row >= this->displayed_rows.size()) return;
1864 if (_ctrl_pressed) {
1865 this->scroll_to_row = row;
1866 } else {
1867 RowDisplay &display = this->displayed_rows[row];
1868 if (display.filter == &this->expanded_rows) {
1869 this->HandleCargoWaitingClick<CargoID>(display.filter, display.next_cargo);
1870 } else {
1871 this->HandleCargoWaitingClick<StationID>(display.filter, display.next_station);
1874 this->SetWidgetDirty(WID_SV_WAITING);
1877 virtual void OnClick(Point pt, int widget, int click_count)
1879 switch (widget) {
1880 case WID_SV_WAITING:
1881 this->HandleCargoWaitingClick(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_SV_WAITING, WD_FRAMERECT_TOP, FONT_HEIGHT_NORMAL) - this->vscroll->GetPosition());
1882 break;
1884 case WID_SV_LOCATION:
1885 if (_ctrl_pressed) {
1886 ShowExtraViewPortWindow(Station::Get(this->window_number)->xy);
1887 } else {
1888 ScrollMainWindowToTile(Station::Get(this->window_number)->xy);
1890 break;
1892 case WID_SV_ACCEPTS_RATINGS: {
1893 /* Swap between 'accepts' and 'ratings' view. */
1894 int height_change;
1895 NWidgetCore *nwi = this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS);
1896 if (this->GetWidget<NWidgetCore>(WID_SV_ACCEPTS_RATINGS)->widget_data == STR_STATION_VIEW_RATINGS_BUTTON) {
1897 nwi->SetDataTip(STR_STATION_VIEW_ACCEPTS_BUTTON, STR_STATION_VIEW_ACCEPTS_TOOLTIP); // Switch to accepts view.
1898 height_change = this->rating_lines - this->accepts_lines;
1899 } else {
1900 nwi->SetDataTip(STR_STATION_VIEW_RATINGS_BUTTON, STR_STATION_VIEW_RATINGS_TOOLTIP); // Switch to ratings view.
1901 height_change = this->accepts_lines - this->rating_lines;
1903 this->ReInit(0, height_change * FONT_HEIGHT_NORMAL);
1904 break;
1907 case WID_SV_RENAME:
1908 SetDParam(0, this->window_number);
1909 ShowQueryString(STR_STATION_NAME, STR_STATION_VIEW_RENAME_STATION_CAPTION, MAX_LENGTH_STATION_NAME_CHARS,
1910 this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
1911 break;
1913 case WID_SV_CLOSE_AIRPORT:
1914 DoCommandP(0, this->window_number, 0, CMD_OPEN_CLOSE_AIRPORT);
1915 break;
1917 case WID_SV_TRAINS: // Show list of scheduled trains to this station
1918 case WID_SV_ROADVEHS: // Show list of scheduled road-vehicles to this station
1919 case WID_SV_SHIPS: // Show list of scheduled ships to this station
1920 case WID_SV_PLANES: { // Show list of scheduled aircraft to this station
1921 Owner owner = Station::Get(this->window_number)->owner;
1922 ShowVehicleListWindow(owner, (VehicleType)(widget - WID_SV_TRAINS), (StationID)this->window_number);
1923 break;
1926 case WID_SV_SORT_BY: {
1927 /* The initial selection is composed of current mode and
1928 * sorting criteria for columns 1, 2, and 3. Column 0 is always
1929 * sorted by cargo ID. The others can theoretically be sorted
1930 * by different things but there is no UI for that. */
1931 ShowDropDownMenu(this, _sort_names,
1932 this->current_mode * 2 + (this->sortings[1] == ST_COUNT ? 1 : 0),
1933 WID_SV_SORT_BY, 0, 0);
1934 break;
1937 case WID_SV_GROUP_BY: {
1938 ShowDropDownMenu(this, _group_names, this->grouping_index, WID_SV_GROUP_BY, 0, 0);
1939 break;
1942 case WID_SV_SORT_ORDER: { // flip sorting method asc/desc
1943 this->SelectSortOrder(this->sort_orders[1] == SO_ASCENDING ? SO_DESCENDING : SO_ASCENDING);
1944 this->SetTimeout();
1945 this->LowerWidget(WID_SV_SORT_ORDER);
1946 break;
1952 * Select a new sort order for the cargo view.
1953 * @param order New sort order.
1955 void SelectSortOrder(SortOrder order)
1957 this->sort_orders[1] = this->sort_orders[2] = this->sort_orders[3] = order;
1958 _settings_client.gui.station_gui_sort_order = this->sort_orders[1];
1959 this->SetDirty();
1963 * Select a new sort criterium for the cargo view.
1964 * @param index Row being selected in the sort criteria drop down.
1966 void SelectSortBy(int index)
1968 _settings_client.gui.station_gui_sort_by = index;
1969 switch (_sort_names[index]) {
1970 case STR_STATION_VIEW_WAITING_STATION:
1971 this->current_mode = MODE_WAITING;
1972 this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_AS_GROUPING;
1973 break;
1974 case STR_STATION_VIEW_WAITING_AMOUNT:
1975 this->current_mode = MODE_WAITING;
1976 this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_COUNT;
1977 break;
1978 case STR_STATION_VIEW_PLANNED_STATION:
1979 this->current_mode = MODE_PLANNED;
1980 this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_AS_GROUPING;
1981 break;
1982 case STR_STATION_VIEW_PLANNED_AMOUNT:
1983 this->current_mode = MODE_PLANNED;
1984 this->sortings[1] = this->sortings[2] = this->sortings[3] = ST_COUNT;
1985 break;
1986 default:
1987 NOT_REACHED();
1989 /* Display the current sort variant */
1990 this->GetWidget<NWidgetCore>(WID_SV_SORT_BY)->widget_data = _sort_names[index];
1991 this->SetDirty();
1995 * Select a new grouping mode for the cargo view.
1996 * @param index Row being selected in the grouping drop down.
1998 void SelectGroupBy(int index)
2000 this->grouping_index = index;
2001 _settings_client.gui.station_gui_group_order = index;
2002 this->GetWidget<NWidgetCore>(WID_SV_GROUP_BY)->widget_data = _group_names[index];
2003 switch (_group_names[index]) {
2004 case STR_STATION_VIEW_GROUP_S_V_D:
2005 this->groupings[1] = GR_SOURCE;
2006 this->groupings[2] = GR_NEXT;
2007 this->groupings[3] = GR_DESTINATION;
2008 break;
2009 case STR_STATION_VIEW_GROUP_S_D_V:
2010 this->groupings[1] = GR_SOURCE;
2011 this->groupings[2] = GR_DESTINATION;
2012 this->groupings[3] = GR_NEXT;
2013 break;
2014 case STR_STATION_VIEW_GROUP_V_S_D:
2015 this->groupings[1] = GR_NEXT;
2016 this->groupings[2] = GR_SOURCE;
2017 this->groupings[3] = GR_DESTINATION;
2018 break;
2019 case STR_STATION_VIEW_GROUP_V_D_S:
2020 this->groupings[1] = GR_NEXT;
2021 this->groupings[2] = GR_DESTINATION;
2022 this->groupings[3] = GR_SOURCE;
2023 break;
2024 case STR_STATION_VIEW_GROUP_D_S_V:
2025 this->groupings[1] = GR_DESTINATION;
2026 this->groupings[2] = GR_SOURCE;
2027 this->groupings[3] = GR_NEXT;
2028 break;
2029 case STR_STATION_VIEW_GROUP_D_V_S:
2030 this->groupings[1] = GR_DESTINATION;
2031 this->groupings[2] = GR_NEXT;
2032 this->groupings[3] = GR_SOURCE;
2033 break;
2035 this->SetDirty();
2038 virtual void OnDropdownSelect(int widget, int index)
2040 if (widget == WID_SV_SORT_BY) {
2041 this->SelectSortBy(index);
2042 } else {
2043 this->SelectGroupBy(index);
2047 virtual void OnQueryTextFinished(char *str)
2049 if (str == NULL) return;
2051 DoCommandP(0, this->window_number, 0, CMD_RENAME_STATION | CMD_MSG(STR_ERROR_CAN_T_RENAME_STATION), NULL, str);
2054 virtual void OnResize()
2056 this->vscroll->SetCapacityFromWidget(this, WID_SV_WAITING, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
2060 * Some data on this window has become invalid. Invalidate the cache for the given cargo if necessary.
2061 * @param data Information about the changed data. If it's a valid cargo ID, invalidate the cargo data.
2062 * @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.
2064 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
2066 if (gui_scope) {
2067 if (data >= 0 && data < NUM_CARGO) {
2068 this->cached_destinations.Remove((CargoID)data);
2069 } else {
2070 this->ReInit();
2076 const StringID StationViewWindow::_sort_names[] = {
2077 STR_STATION_VIEW_WAITING_STATION,
2078 STR_STATION_VIEW_WAITING_AMOUNT,
2079 STR_STATION_VIEW_PLANNED_STATION,
2080 STR_STATION_VIEW_PLANNED_AMOUNT,
2081 INVALID_STRING_ID
2084 const StringID StationViewWindow::_group_names[] = {
2085 STR_STATION_VIEW_GROUP_S_V_D,
2086 STR_STATION_VIEW_GROUP_S_D_V,
2087 STR_STATION_VIEW_GROUP_V_S_D,
2088 STR_STATION_VIEW_GROUP_V_D_S,
2089 STR_STATION_VIEW_GROUP_D_S_V,
2090 STR_STATION_VIEW_GROUP_D_V_S,
2091 INVALID_STRING_ID
2094 static WindowDesc _station_view_desc(
2095 WDP_AUTO, "view_station", 249, 117,
2096 WC_STATION_VIEW, WC_NONE,
2098 _nested_station_view_widgets, lengthof(_nested_station_view_widgets)
2102 * Opens StationViewWindow for given station
2104 * @param station station which window should be opened
2106 void ShowStationViewWindow(StationID station)
2108 AllocateWindowDescFront<StationViewWindow>(&_station_view_desc, station);
2111 /** Struct containing TileIndex and StationID */
2112 struct TileAndStation {
2113 TileIndex tile; ///< TileIndex
2114 StationID station; ///< StationID
2117 static SmallVector<TileAndStation, 8> _deleted_stations_nearby;
2118 static SmallVector<StationID, 8> _stations_nearby_list;
2121 * Add station on this tile to _stations_nearby_list if it's fully within the
2122 * station spread.
2123 * @param tile Tile just being checked
2124 * @param user_data Pointer to TileArea context
2125 * @tparam T the type of station to look for
2127 template <class T>
2128 static bool AddNearbyStation(TileIndex tile, void *user_data)
2130 TileArea *ctx = (TileArea *)user_data;
2132 /* First check if there were deleted stations here */
2133 for (uint i = 0; i < _deleted_stations_nearby.Length(); i++) {
2134 TileAndStation *ts = _deleted_stations_nearby.Get(i);
2135 if (ts->tile == tile) {
2136 *_stations_nearby_list.Append() = _deleted_stations_nearby[i].station;
2137 _deleted_stations_nearby.Erase(ts);
2138 i--;
2142 /* Check if own station and if we stay within station spread */
2143 if (!IsStationTile(tile)) return false;
2145 StationID sid = GetStationIndex(tile);
2147 /* This station is (likely) a waypoint */
2148 if (!T::IsValidID(sid)) return false;
2150 T *st = T::Get(sid);
2151 if (st->owner != _local_company || _stations_nearby_list.Contains(sid)) return false;
2153 if (st->rect.BeforeAddRect(ctx->tile, ctx->w, ctx->h, StationRect::ADD_TEST).Succeeded()) {
2154 *_stations_nearby_list.Append() = sid;
2157 return false; // We want to include *all* nearby stations
2161 * Circulate around the to-be-built station to find stations we could join.
2162 * Make sure that only stations are returned where joining wouldn't exceed
2163 * station spread and are our own station.
2164 * @param ta Base tile area of the to-be-built station
2165 * @param distant_join Search for adjacent stations (false) or stations fully
2166 * within station spread
2167 * @tparam T the type of station to look for
2169 template <class T>
2170 static const T *FindStationsNearby(TileArea ta, bool distant_join)
2172 TileArea ctx = ta;
2174 _stations_nearby_list.Clear();
2175 _deleted_stations_nearby.Clear();
2177 /* Check the inside, to return, if we sit on another station */
2178 TILE_AREA_LOOP(t, ta) {
2179 if (t < MapSize() && IsStationTile(t) && T::IsValidID(GetStationIndex(t))) return T::GetByTile(t);
2182 /* Look for deleted stations */
2183 const BaseStation *st;
2184 FOR_ALL_BASE_STATIONS(st) {
2185 if (T::IsExpected(st) && !st->IsInUse() && st->owner == _local_company) {
2186 /* Include only within station spread (yes, it is strictly less than) */
2187 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) {
2188 TileAndStation *ts = _deleted_stations_nearby.Append();
2189 ts->tile = st->xy;
2190 ts->station = st->index;
2192 /* Add the station when it's within where we're going to build */
2193 if (IsInsideBS(TileX(st->xy), TileX(ctx.tile), ctx.w) &&
2194 IsInsideBS(TileY(st->xy), TileY(ctx.tile), ctx.h)) {
2195 AddNearbyStation<T>(st->xy, &ctx);
2201 /* Only search tiles where we have a chance to stay within the station spread.
2202 * The complete check needs to be done in the callback as we don't know the
2203 * extent of the found station, yet. */
2204 if (distant_join && min(ta.w, ta.h) >= _settings_game.station.station_spread) return NULL;
2205 uint max_dist = distant_join ? _settings_game.station.station_spread - min(ta.w, ta.h) : 1;
2207 TileIndex tile = TILE_ADD(ctx.tile, TileOffsByDir(DIR_N));
2208 CircularTileSearch(&tile, max_dist, ta.w, ta.h, AddNearbyStation<T>, &ctx);
2210 return NULL;
2213 static const NWidgetPart _nested_select_station_widgets[] = {
2214 NWidget(NWID_HORIZONTAL),
2215 NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
2216 NWidget(WWT_CAPTION, COLOUR_DARK_GREEN, WID_JS_CAPTION), SetDataTip(STR_JOIN_STATION_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2217 NWidget(WWT_DEFSIZEBOX, COLOUR_DARK_GREEN),
2218 EndContainer(),
2219 NWidget(NWID_HORIZONTAL),
2220 NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_JS_PANEL), SetResize(1, 0), SetScrollbar(WID_JS_SCROLLBAR), EndContainer(),
2221 NWidget(NWID_VERTICAL),
2222 NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, WID_JS_SCROLLBAR),
2223 NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
2224 EndContainer(),
2225 EndContainer(),
2229 * Window for selecting stations/waypoints to (distant) join to.
2230 * @tparam T The type of station to join with
2232 template <class T>
2233 struct SelectStationWindow : Window {
2234 CommandContainer select_station_cmd; ///< Command to build new station
2235 TileArea area; ///< Location of new station
2236 Scrollbar *vscroll;
2238 SelectStationWindow(WindowDesc *desc, const CommandContainer &cmd, TileArea ta) :
2239 Window(desc),
2240 select_station_cmd(cmd),
2241 area(ta)
2243 this->CreateNestedTree();
2244 this->vscroll = this->GetScrollbar(WID_JS_SCROLLBAR);
2245 this->GetWidget<NWidgetCore>(WID_JS_CAPTION)->widget_data = T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_JOIN_WAYPOINT_CAPTION : STR_JOIN_STATION_CAPTION;
2246 this->FinishInitNested(0);
2247 this->OnInvalidateData(0);
2250 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
2252 if (widget != WID_JS_PANEL) return;
2254 /* Determine the widest string */
2255 Dimension d = GetStringBoundingBox(T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_JOIN_WAYPOINT_CREATE_SPLITTED_WAYPOINT : STR_JOIN_STATION_CREATE_SPLITTED_STATION);
2256 for (uint i = 0; i < _stations_nearby_list.Length(); i++) {
2257 const T *st = T::Get(_stations_nearby_list[i]);
2258 SetDParam(0, st->index);
2259 SetDParam(1, st->facilities);
2260 d = maxdim(d, GetStringBoundingBox(T::EXPECTED_FACIL == FACIL_WAYPOINT ? STR_STATION_LIST_WAYPOINT : STR_STATION_LIST_STATION));
2263 resize->height = d.height;
2264 d.height *= 5;
2265 d.width += WD_FRAMERECT_RIGHT + WD_FRAMERECT_LEFT;
2266 d.height += WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
2267 *size = d;
2270 virtual void DrawWidget(const Rect &r, int widget) const
2272 if (widget != WID_JS_PANEL) return;
2274 uint y = r.top + WD_FRAMERECT_TOP;
2275 if (this->vscroll->GetPosition() == 0) {
2276 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);
2277 y += this->resize.step_height;
2280 for (uint i = max<uint>(1, this->vscroll->GetPosition()); i <= _stations_nearby_list.Length(); ++i, y += this->resize.step_height) {
2281 /* Don't draw anything if it extends past the end of the window. */
2282 if (i - this->vscroll->GetPosition() >= this->vscroll->GetCapacity()) break;
2284 const T *st = T::Get(_stations_nearby_list[i - 1]);
2285 SetDParam(0, st->index);
2286 SetDParam(1, st->facilities);
2287 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);
2291 virtual void OnClick(Point pt, int widget, int click_count)
2293 if (widget != WID_JS_PANEL) return;
2295 uint st_index = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_JS_PANEL, WD_FRAMERECT_TOP);
2296 bool distant_join = (st_index > 0);
2297 if (distant_join) st_index--;
2299 if (distant_join && st_index >= _stations_nearby_list.Length()) return;
2301 /* Insert station to be joined into stored command */
2302 SB(this->select_station_cmd.p2, 16, 16,
2303 (distant_join ? _stations_nearby_list[st_index] : NEW_STATION));
2305 /* Execute stored Command */
2306 DoCommandP(&this->select_station_cmd);
2308 /* Close Window; this might cause double frees! */
2309 DeleteWindowById(WC_SELECT_STATION, 0);
2312 virtual void OnTick()
2314 if (_thd.dirty & 2) {
2315 _thd.dirty &= ~2;
2316 this->SetDirty();
2320 virtual void OnResize()
2322 this->vscroll->SetCapacityFromWidget(this, WID_JS_PANEL, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
2326 * Some data on this window has become invalid.
2327 * @param data Information about the changed data.
2328 * @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.
2330 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
2332 if (!gui_scope) return;
2333 FindStationsNearby<T>(this->area, true);
2334 this->vscroll->SetCount(_stations_nearby_list.Length() + 1);
2335 this->SetDirty();
2339 static WindowDesc _select_station_desc(
2340 WDP_AUTO, "build_station_join", 200, 180,
2341 WC_SELECT_STATION, WC_NONE,
2342 WDF_CONSTRUCTION,
2343 _nested_select_station_widgets, lengthof(_nested_select_station_widgets)
2348 * Check whether we need to show the station selection window.
2349 * @param cmd Command to build the station.
2350 * @param ta Tile area of the to-be-built station
2351 * @tparam T the type of station
2352 * @return whether we need to show the station selection window.
2354 template <class T>
2355 static bool StationJoinerNeeded(const CommandContainer &cmd, TileArea ta)
2357 /* Only show selection if distant join is enabled in the settings */
2358 if (!_settings_game.station.distant_join_stations) return false;
2360 /* If a window is already opened and we didn't ctrl-click,
2361 * return true (i.e. just flash the old window) */
2362 Window *selection_window = FindWindowById(WC_SELECT_STATION, 0);
2363 if (selection_window != NULL) {
2364 /* Abort current distant-join and start new one */
2365 delete selection_window;
2366 UpdateTileSelection();
2369 /* only show the popup, if we press ctrl */
2370 if (!_ctrl_pressed) return false;
2372 /* Now check if we could build there */
2373 if (DoCommand(&cmd, CommandFlagsToDCFlags(GetCommandFlags(cmd.cmd))).Failed()) return false;
2375 /* Test for adjacent station or station below selection.
2376 * If adjacent-stations is disabled and we are building next to a station, do not show the selection window.
2377 * but join the other station immediately. */
2378 const T *st = FindStationsNearby<T>(ta, false);
2379 return st == NULL && (_settings_game.station.adjacent_stations || _stations_nearby_list.Length() == 0);
2383 * Show the station selection window when needed. If not, build the station.
2384 * @param cmd Command to build the station.
2385 * @param ta Area to build the station in
2386 * @tparam the class to find stations for
2388 template <class T>
2389 void ShowSelectBaseStationIfNeeded(const CommandContainer &cmd, TileArea ta)
2391 if (StationJoinerNeeded<T>(cmd, ta)) {
2392 if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
2393 new SelectStationWindow<T>(&_select_station_desc, cmd, ta);
2394 } else {
2395 DoCommandP(&cmd);
2400 * Show the station selection window when needed. If not, build the station.
2401 * @param cmd Command to build the station.
2402 * @param ta Area to build the station in
2404 void ShowSelectStationIfNeeded(const CommandContainer &cmd, TileArea ta)
2406 ShowSelectBaseStationIfNeeded<Station>(cmd, ta);
2410 * Show the waypoint selection window when needed. If not, build the waypoint.
2411 * @param cmd Command to build the waypoint.
2412 * @param ta Area to build the waypoint in
2414 void ShowSelectWaypointIfNeeded(const CommandContainer &cmd, TileArea ta)
2416 ShowSelectBaseStationIfNeeded<Waypoint>(cmd, ta);