OpenTTD Source 20261112-master-gbcbec5e63f
subsidy_gui.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
11#include "industry.h"
12#include "town.h"
13#include "window_gui.h"
14#include "strings_func.h"
15#include "viewport_func.h"
16#include "gui.h"
17#include "subsidy_base.h"
19
21
22#include "table/strings.h"
23
24#include "safeguards.h"
25
26struct SubsidyListWindow : Window {
27 Scrollbar *vscroll = nullptr;
28 Dimension cargo_icon_size{};
29
30 SubsidyListWindow(WindowDesc &desc, WindowNumber window_number) : Window(desc)
31 {
32 this->CreateNestedTree();
33 this->vscroll = this->GetScrollbar(WID_SUL_SCROLLBAR);
34 this->FinishInitNested(window_number);
35 this->OnInvalidateData(0);
36 }
37
38 void OnInit() override
39 {
40 this->cargo_icon_size = GetLargestCargoIconSize();
41 }
42
43 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
44 {
45 if (widget != WID_SUL_PANEL) return;
46
47 int y = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_SUL_PANEL, WidgetDimensions::scaled.framerect.top);
48 int num = 0;
49 for (const Subsidy *s : Subsidy::Iterate()) {
50 if (!s->IsAwarded()) {
51 y--;
52 if (y == 0) {
53 this->HandleClick(s);
54 return;
55 }
56 num++;
57 }
58 }
59
60 if (num == 0) {
61 y--; // "None"
62 if (y < 0) return;
63 }
64
65 y -= 2; // "Services already subsidised:"
66 if (y < 0) return;
67
68 for (const Subsidy *s : Subsidy::Iterate()) {
69 if (s->IsAwarded()) {
70 y--;
71 if (y == 0) {
72 this->HandleClick(s);
73 return;
74 }
75 }
76 }
77 }
78
79 void HandleClick(const Subsidy *s)
80 {
81 /* determine src coordinate for subsidy and try to scroll to it */
82 TileIndex xy;
83 switch (s->src.type) {
84 case SourceType::Industry: xy = Industry::Get(s->src.ToIndustryID())->location.tile; break;
85 case SourceType::Town: xy = Town::Get(s->src.ToTownID())->xy; break;
86 default: NOT_REACHED();
87 }
88
91
92 /* otherwise determine dst coordinate for subsidy and scroll to it */
93 switch (s->dst.type) {
94 case SourceType::Industry: xy = Industry::Get(s->dst.ToIndustryID())->location.tile; break;
95 case SourceType::Town: xy = Town::Get(s->dst.ToTownID())->xy; break;
96 default: NOT_REACHED();
97 }
98
99 if (IsCtrlPressed()) {
101 } else {
103 }
104 }
105 }
106
112 {
113 /* Count number of (non) awarded subsidies */
114 uint num_awarded = 0;
115 uint num_not_awarded = 0;
116 for (const Subsidy *s : Subsidy::Iterate()) {
117 if (!s->IsAwarded()) {
118 num_not_awarded++;
119 } else {
120 num_awarded++;
121 }
122 }
123
124 /* Count the 'none' lines */
125 if (num_awarded == 0) num_awarded = 1;
126 if (num_not_awarded == 0) num_not_awarded = 1;
127
128 /* Offered, accepted and an empty line before the accepted ones. */
129 return 3 + num_awarded + num_not_awarded;
130 }
131
132 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
133 {
134 if (widget != WID_SUL_PANEL) return;
135 Dimension d = maxdim(GetStringBoundingBox(STR_SUBSIDIES_OFFERED_TITLE), GetStringBoundingBox(STR_SUBSIDIES_SUBSIDISED_TITLE));
136
137 fill.height = resize.height = GetCharacterHeight(FontSize::Normal);
138
139 d.height *= 5;
140 d.width += WidgetDimensions::scaled.framerect.Horizontal();
141 d.height += WidgetDimensions::scaled.framerect.Vertical();
142 size = maxdim(size, d);
143 }
144
145 void DrawCargoIcon(const Rect &r, int y_offset, CargoType cargo_type) const
146 {
147 bool rtl = _current_text_dir == TD_RTL;
148 SpriteID icon = CargoSpec::Get(cargo_type)->GetCargoIcon();
149 Dimension d = GetSpriteSize(icon);
150 Rect ir = r.WithWidth(this->cargo_icon_size.width, rtl).WithHeight(GetCharacterHeight(FontSize::Normal));
151 DrawSprite(icon, PAL_NONE, CentreBounds(ir.left, ir.right, d.width), CentreBounds(ir.top, ir.bottom, this->cargo_icon_size.height) + y_offset);
152 }
153
154 void DrawWidget(const Rect &r, WidgetID widget) const override
155 {
156 if (widget != WID_SUL_PANEL) return;
157
158 TimerGameEconomy::YearMonthDay ymd = TimerGameEconomy::ConvertDateToYMD(TimerGameEconomy::date);
159
160 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
161 Rect sr = tr.Indent(this->cargo_icon_size.width + WidgetDimensions::scaled.hsep_normal, _current_text_dir == TD_RTL);
162
163 int pos = -this->vscroll->GetPosition();
164 const int cap = this->vscroll->GetCapacity();
165
166 /* Section for drawing the offered subsidies */
167 if (IsInsideMM(pos, 0, cap)) DrawString(tr.left, tr.right, tr.top + pos * GetCharacterHeight(FontSize::Normal), STR_SUBSIDIES_OFFERED_TITLE);
168 pos++;
169
170 uint num = 0;
171 for (const Subsidy *s : Subsidy::Iterate()) {
172 if (!s->IsAwarded()) {
173 if (IsInsideMM(pos, 0, cap)) {
174 /* Displays the two offered towns */
175 const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
176 std::string text;
177
178 /* If using wallclock units, show minutes remaining. Otherwise show the date when the subsidy ends. */
180 text = GetString(STR_SUBSIDIES_OFFERED_FROM_TO,
181 cs->name, s->src.GetFormat(), s->src.id, s->dst.GetFormat(), s->dst.id,
182 STR_SUBSIDIES_OFFERED_EXPIRY_TIME,
183 s->remaining + 1); // We get the rest of the current economy month for free, since the expiration is checked on each new month.
184 } else {
185 text = GetString(STR_SUBSIDIES_OFFERED_FROM_TO,
186 cs->name, s->src.GetFormat(), s->src.id, s->dst.GetFormat(), s->dst.id,
187 STR_SUBSIDIES_OFFERED_EXPIRY_DATE,
188 TimerGameEconomy::date.base() - ymd.day + s->remaining * 32);
189 }
190
191 DrawCargoIcon(tr, pos * GetCharacterHeight(FontSize::Normal), s->cargo_type);
192 DrawString(sr.left, sr.right, sr.top + pos * GetCharacterHeight(FontSize::Normal), text);
193 }
194 pos++;
195 num++;
196 }
197 }
198
199 if (num == 0) {
200 if (IsInsideMM(pos, 0, cap)) DrawString(tr.left, tr.right, tr.top + pos * GetCharacterHeight(FontSize::Normal), STR_SUBSIDIES_NONE);
201 pos++;
202 }
203
204 /* Section for drawing the already granted subsidies */
205 pos++;
206 if (IsInsideMM(pos, 0, cap)) DrawString(tr.left, tr.right, tr.top + pos * GetCharacterHeight(FontSize::Normal), STR_SUBSIDIES_SUBSIDISED_TITLE);
207 pos++;
208 num = 0;
209
210 for (const Subsidy *s : Subsidy::Iterate()) {
211 if (s->IsAwarded()) {
212 if (IsInsideMM(pos, 0, cap)) {
213 const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
214 std::string text;
215
216 /* If using wallclock units, show minutes remaining. Otherwise show the date when the subsidy ends. */
218 text = GetString(STR_SUBSIDIES_SUBSIDISED_FROM_TO,
219 cs->name, s->src.GetFormat(), s->src.id, s->dst.GetFormat(), s->dst.id,
220 s->awarded,
221 STR_SUBSIDIES_SUBSIDISED_EXPIRY_TIME,
222 s->remaining + 1); // We get the rest of the current economy month for free, since the expiration is checked on each new month.
223 } else {
224 text = GetString(STR_SUBSIDIES_SUBSIDISED_FROM_TO,
225 cs->name, s->src.GetFormat(), s->src.id, s->dst.GetFormat(), s->dst.id,
226 s->awarded,
227 STR_SUBSIDIES_SUBSIDISED_EXPIRY_DATE,
228 TimerGameEconomy::date.base() - ymd.day + s->remaining * 32);
229 }
230
231 /* Displays the two connected stations */
232 DrawCargoIcon(tr, pos * GetCharacterHeight(FontSize::Normal), s->cargo_type);
233 DrawString(sr.left, sr.right, sr.top + pos * GetCharacterHeight(FontSize::Normal), text);
234 }
235 pos++;
236 num++;
237 }
238 }
239
240 if (num == 0) {
241 if (IsInsideMM(pos, 0, cap)) DrawString(tr.left, tr.right, tr.top + pos * GetCharacterHeight(FontSize::Normal), STR_SUBSIDIES_NONE);
242 pos++;
243 }
244 }
245
246 void OnResize() override
247 {
248 this->vscroll->SetCapacityFromWidget(this, WID_SUL_PANEL, WidgetDimensions::scaled.framerect.Vertical());
249 }
250
256 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
257 {
258 if (!gui_scope) return;
259 this->vscroll->SetCount(this->CountLines());
260 }
261};
262
263static constexpr std::initializer_list<NWidgetPart> _nested_subsidies_list_widgets = {
266 NWidget(WWT_CAPTION, Colours::Brown), SetStringTip(STR_SUBSIDIES_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
270 EndContainer(),
272 NWidget(WWT_PANEL, Colours::Brown, WID_SUL_PANEL), SetToolTip(STR_SUBSIDIES_TOOLTIP_CLICK_ON_SERVICE_TO_CENTER), SetResize(1, 1), SetScrollbar(WID_SUL_SCROLLBAR), EndContainer(),
276 EndContainer(),
277 EndContainer(),
278};
279
282 WindowPosition::Automatic, "list_subsidies", 500, 127,
283 WindowClass::SubsidyList, WindowClass::None,
284 {},
285 _nested_subsidies_list_widgets
286);
287
288
289void ShowSubsidiesList()
290{
292}
CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:22
Dimension GetLargestCargoIconSize()
Get dimensions of largest cargo icon.
TileIndex tile
The base tile of the area.
Scrollbar data structure.
size_type GetCapacity() const
Gets the number of visible elements of the scrollbar.
void SetCount(size_t num)
Sets the number of elements in the list.
size_type GetScrolledRowFromWidget(int clickpos, const Window *const w, WidgetID widget, int padding=0, int line_height=-1) const
Compute the row of a scrolled widget that a user clicked in.
Definition widget.cpp:2474
void SetCapacityFromWidget(Window *w, WidgetID widget, int padding=0)
Set capacity of visible elements from the size and resize properties of a widget.
Definition widget.cpp:2548
size_type GetPosition() const
Gets the position of the first visible element in the list.
static Date date
Current date in days (day counter).
static bool UsingWallclockUnits(bool newgame=false)
Check if we are using wallclock units.
static YearMonthDay ConvertDateToYMD(Date date)
Converts a Date to a Year, Month & Day.
static WidgetDimensions scaled
Widget dimensions scaled for current zoom level.
Definition window_gui.h:30
int GetCharacterHeight(FontSize size)
Get height of a character for a given font size.
Definition fontcache.cpp:88
Dimension maxdim(const Dimension &d1, const Dimension &d2)
Compute bounding box of both dimensions.
Geometry functions.
int CentreBounds(int min, int max, int size)
Determine where to position a centred object.
Dimension GetSpriteSize(SpriteID sprid, Point *offset, ZoomLevel zoom)
Get the size of a sprite.
Definition gfx.cpp:966
Dimension GetStringBoundingBox(std::string_view str, FontSize start_fontsize)
Return the string dimension in pixels.
Definition gfx.cpp:894
void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub, ZoomLevel zoom)
Draw a sprite, not in a viewport.
Definition gfx.cpp:1032
int DrawString(int left, int right, int top, std::string_view str, ExtendedTextColour colour, Alignment align, bool underline, FontSize fontsize)
Draw string, possibly truncated to make it fit in its allocated space.
Definition gfx.cpp:663
bool IsCtrlPressed()
Test if the ctrl key is pressed.
Definition gfx_func.h:82
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition gfx_type.h:17
@ Normal
Index of the normal font in the font tables.
Definition gfx_type.h:249
@ Brown
Brown.
Definition gfx_type.h:298
constexpr NWidgetPart SetScrollbar(WidgetID index)
Attach a scrollbar to a widget.
constexpr NWidgetPart SetStringTip(StringID string, StringID tip={})
Widget part function for setting the string and tooltip.
constexpr NWidgetPart SetToolTip(StringID tip)
Widget part function for setting tooltip and clearing the widget data.
constexpr NWidgetPart EndContainer()
Widget part function for denoting the end of a container (horizontal, vertical, WWT_FRAME,...
constexpr NWidgetPart NWidget(WidgetType tp, Colours col, WidgetID idx=INVALID_WIDGET)
Widget part function for starting a new 'real' widget.
constexpr NWidgetPart SetResize(int16_t dx, int16_t dy)
Widget part function for setting the resize step.
GUI functions that shouldn't be here.
void ShowExtraViewportWindow(TileIndex tile=INVALID_TILE)
Show a new Extra Viewport window.
Base of all industries.
#define Rect
Macro that prevents name conflicts between included headers.
#define Point
Macro that prevents name conflicts between included headers.
constexpr bool IsInsideMM(const size_t x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
A number of safeguards to prevent using unsafe methods.
@ Industry
Source/destination is an industry.
Definition source_type.h:21
@ Town
Source/destination is a town.
Definition source_type.h:22
Definition of base types and functions in a cross-platform compatible way.
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:423
TextDirection _current_text_dir
Text direction of the currently selected language.
Definition strings.cpp:55
Functions related to OTTD's strings.
@ TD_RTL
Text is written right-to-left by default.
Specification of a cargo type.
Definition cargotype.h:76
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo type.
Definition cargotype.h:140
SpriteID GetCargoIcon() const
Get sprite for showing cargo of this type.
StringID name
Name of this type of cargo.
Definition cargotype.h:93
Dimensions (a width and height) of a rectangle in 2D.
value_type height
The height of the rectangle.
value_type width
The width of the rectangle.
TileArea location
Location of the industry.
Definition industry.h:108
static Pool::IterateWrapper< Subsidy > Iterate(size_t from=0)
static Industry * Get(auto index)
Specification of a rectangle with absolute coordinates of all edges.
Rect WithWidth(int width, bool end) const
Copy Rect and set its width.
Rect Shrink(int s) const
Copy and shrink Rect by s pixels.
Rect WithHeight(int height, bool end=false) const
Copy Rect and set its height.
Rect Indent(int indent, bool end) const
Copy Rect and indent it from its position.
SourceID id
Index of industry/town/HQ, Source::Invalid if unknown/invalid.
Definition source_type.h:36
StringID GetFormat() const
Get the format string for a subsidy Source.
Definition subsidy.cpp:56
SourceType type
Type of source_id.
Definition source_type.h:37
uint CountLines()
Count the number of lines in this window.
void OnInit() override
Notification that the nested widget tree gets initialized.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
Update size and resize step of a widget in the window.
void OnResize() override
Called after the window got resized.
Struct about subsidies, offered and awarded.
bool IsAwarded() const
Tests whether this subsidy has been awarded to someone.
CargoType cargo_type
Cargo type involved in this subsidy, INVALID_CARGO for invalid subsidy.
CompanyID awarded
Subsidy is awarded to this company; CompanyID::Invalid() if it's not awarded to anyone.
Source dst
Destination of subsidised path.
Source src
Source of subsidised path.
uint16_t remaining
Remaining months when this subsidy is valid.
TileIndex xy
town center tile
Definition town.h:65
High level window description.
Definition window_gui.h:171
Number to differentiate different windows of the same class.
void FinishInitNested(WindowNumber window_number=0)
Perform the second part of the initialization of a nested widget tree.
Definition window.cpp:1855
ResizeInfo resize
Resize information.
Definition window_gui.h:313
void CreateNestedTree()
Perform the first part of the initialization of a nested widget tree.
Definition window.cpp:1845
Window(WindowDesc &desc)
Empty constructor, initialization has been moved to InitNested() called from the constructor of the d...
Definition window.cpp:1879
const Scrollbar * GetScrollbar(WidgetID widnum) const
Return the Scrollbar to a widget index.
Definition window.cpp:322
WindowNumber window_number
Window number within the window class.
Definition window_gui.h:301
Subsidy base class.
static WindowDesc _subsidies_list_desc(WindowPosition::Automatic, "list_subsidies", 500, 127, WindowClass::SubsidyList, WindowClass::None, {}, _nested_subsidies_list_widgets)
Window definition for the subsidies window.
Types related to the subsidy widgets.
@ WID_SUL_PANEL
Main panel of window.
@ WID_SUL_SCROLLBAR
Scrollbar of panel.
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
Definition tile_type.h:92
Base of the town class.
bool ScrollMainWindowToTile(TileIndex tile, bool instant)
Scrolls the viewport of the main window to a given location.
Functions related to (drawing on) viewports.
@ NWID_HORIZONTAL
Horizontal container.
Definition widget_type.h:66
@ WWT_PANEL
Simple depressed panel.
Definition widget_type.h:39
@ WWT_STICKYBOX
Sticky box (at top-right of a window, after WWT_DEFSIZEBOX).
Definition widget_type.h:57
@ WWT_SHADEBOX
Shade box (at top-right of a window, between WWT_DEBUGBOX and WWT_DEFSIZEBOX).
Definition widget_type.h:55
@ WWT_CAPTION
Window caption (window title between closebox and stickybox).
Definition widget_type.h:52
@ NWID_VSCROLLBAR
Vertical scrollbar.
Definition widget_type.h:76
@ NWID_VERTICAL
Vertical container.
Definition widget_type.h:68
@ WWT_CLOSEBOX
Close box (at top-left of a window).
Definition widget_type.h:60
@ WWT_RESIZEBOX
Resize box (normally at bottom-right of a window).
Definition widget_type.h:59
@ WWT_DEFSIZEBOX
Default window size box (at top-right of a window, between WWT_SHADEBOX and WWT_STICKYBOX).
Definition widget_type.h:56
Functions, definitions and such used only by the GUI.
Twindow * AllocateWindowDescFront(WindowDesc &desc, WindowNumber window_number, Targs... extra_arguments)
Open a new window.
@ Automatic
Find a place automatically.
Definition window_gui.h:145
int WidgetID
Widget ID.
Definition window_type.h:21