OpenTTD Source 20261129-master-g72a8bdc861
statusbar_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 "core/backup_type.hpp"
12#include "gfx_func.h"
13#include "news_func.h"
14#include "company_func.h"
15#include "string_func.h"
16#include "strings_func.h"
17#include "company_base.h"
18#include "tilehighlight_func.h"
19#include "news_gui.h"
20#include "company_gui.h"
21#include "window_gui.h"
23#include "window_func.h"
24#include "statusbar_gui.h"
25#include "toolbar_gui.h"
27#include "zoom_func.h"
28#include "timer/timer.h"
30#include "timer/timer_window.h"
31
33
34#include "table/strings.h"
35#include "table/sprites.h"
36
37#include "safeguards.h"
38
39static bool DrawScrollingStatusText(const NewsItem &ni, int scroll_pos, int left, int right, int top, int bottom)
40{
41 /* Replace newlines and the likes with spaces. */
42 std::string message = StrMakeValid(ni.GetStatusText(), StringValidationSetting::ReplaceTabCrNlWithSpace);
43
44 DrawPixelInfo tmp_dpi;
45 if (!FillDrawPixelInfo(&tmp_dpi, left, top, right - left, bottom)) return true;
46
47 int width = GetStringBoundingBox(message).width;
48 int pos = (_current_text_dir == TD_RTL) ? (scroll_pos - width) : (right - scroll_pos - left);
49
50 AutoRestoreBackup dpi_backup(_cur_dpi, &tmp_dpi);
51 DrawString(pos, INT16_MAX, 0, message, TextColour::LightBlue, AlignmentH::ForceLeft);
52
53 return (_current_text_dir == TD_RTL) ? (pos < right - left) : (pos + width > 0);
54}
55
56struct StatusBarWindow : Window {
57 bool saving = false;
58 int ticker_scroll = TICKER_STOP;
59
60 static const int TICKER_STOP = 1640;
61 static const int COUNTER_STEP = 2;
62 static constexpr auto REMINDER_START = std::chrono::milliseconds(1350);
63
64 StatusBarWindow(WindowDesc &desc) : Window(desc)
65 {
66 this->InitNested();
67 this->flags.Reset(WindowFlag::WhiteBorder);
69 }
70
71 Point OnInitialPosition([[maybe_unused]] int16_t sm_width, [[maybe_unused]] int16_t sm_height, [[maybe_unused]] int window_number) override
72 {
73 Point pt = { 0, _screen.height - sm_height };
74 return pt;
75 }
76
77 void FindWindowPlacementAndResize(int, int def_height, bool allow_resize) override
78 {
80 }
81
82 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
83 {
84 Dimension d;
85 switch (widget) {
86 case WID_S_LEFT:
88 break;
89
90 case WID_S_RIGHT: {
91 Money max_money = UINT32_MAX;
92 for (const Company *c : Company::Iterate()) max_money = std::max(abs(c->money), max_money);
93 d = GetStringBoundingBox(GetString(STR_JUST_CURRENCY_LONG, max_money));
94 d.width += WidgetDimensions::scaled.hsep_wide;
95 break;
96 }
97
98 default:
99 return;
100 }
101
102 d.width += padding.width;
103 d.height += padding.height;
104 size = maxdim(d, size);
105 }
106
107 void DrawWidget(const Rect &r, WidgetID widget) const override
108 {
109 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect, RectPadding::zero);
110 tr.top = CentreBounds(r.top, r.bottom, GetCharacterHeight(FontSize::Normal));
111 switch (widget) {
112 case WID_S_LEFT:
113 /* Draw the date */
115 break;
116
117 case WID_S_RIGHT: {
119 DrawString(tr, STR_STATUSBAR_SPECTATOR, TextColour::FromString, AlignmentH::Centre);
120 } else if (_settings_game.difficulty.infinite_money) {
121 DrawString(tr, STR_STATUSBAR_INFINITE_MONEY, TextColour::FromString, AlignmentH::Centre);
122 } else {
123 /* Draw company money, if any */
125 if (c != nullptr) {
126 DrawString(tr, GetString(STR_JUST_CURRENCY_LONG, c->money), TextColour::White, AlignmentH::Centre);
127 }
128 }
129 break;
130 }
131
132 case WID_S_MIDDLE:
133 /* Draw status bar */
134 if (this->saving) { // true when saving is active
136 } else if (_do_autosave) {
137 DrawString(tr, STR_STATUSBAR_AUTOSAVE, TextColour::FromString, AlignmentH::Centre);
138 } else if (_pause_mode.Any()) {
139 StringID msg = _pause_mode.Test(PauseMode::LinkGraph) ? STR_STATUSBAR_PAUSED_LINK_GRAPH : STR_STATUSBAR_PAUSED;
141 } else if (this->ticker_scroll < TICKER_STOP && GetStatusbarNews() != nullptr && !GetStatusbarNews()->headline.empty()) {
142 /* Draw the scrolling news text */
143 if (!DrawScrollingStatusText(*GetStatusbarNews(), ScaleGUITrad(this->ticker_scroll), tr.left, tr.right, tr.top, tr.bottom)) {
144 InvalidateWindowData(WindowClass::Statusbar, 0, SBI_NEWS_DELETED);
146 /* This is the default text */
148 }
149 }
150 } else {
152 /* This is the default text */
154 }
155 }
156
157 if (!this->reminder_timeout.HasFired()) {
158 Dimension icon_size = GetSpriteSize(SPR_UNREAD_NEWS);
159 DrawSprite(SPR_UNREAD_NEWS, PAL_NONE, tr.right - icon_size.width, CentreBounds(r.top, r.bottom, icon_size.height));
160 }
161 break;
162 }
163 }
164
170 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
171 {
172 if (!gui_scope) return;
173 switch (data) {
174 default: NOT_REACHED();
175 case SBI_SAVELOAD_START: this->saving = true; break;
176 case SBI_SAVELOAD_FINISH: this->saving = false; break;
177 case SBI_SHOW_TICKER: this->ticker_scroll = 0; break;
178 case SBI_SHOW_REMINDER: this->reminder_timeout.Reset(); break;
179 case SBI_NEWS_DELETED:
180 this->ticker_scroll = TICKER_STOP; // reset ticker ...
181 this->reminder_timeout.Abort(); // ... and reminder
182 break;
183 }
184 }
185
186 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
187 {
188 switch (widget) {
189 case WID_S_MIDDLE: ShowLastNewsMessage(); break;
191 default: ResetObjectToPlace();
192 }
193 }
194
196 const IntervalTimer<TimerWindow> ticker_scroll_interval = {std::chrono::milliseconds(15), [this](uint count) {
197 if (_pause_mode.Any()) return;
198
199 if (this->ticker_scroll < TICKER_STOP) {
200 this->ticker_scroll += count;
202 }
203 }};
204
205 TimeoutTimer<TimerWindow> reminder_timeout = {REMINDER_START, [this]() {
207 }};
208
209 const IntervalTimer<TimerGameCalendar> daily_interval = {{TimerGameCalendar::Trigger::Day, TimerGameCalendar::Priority::None}, [this](auto) {
211 }};
212};
213
214static constexpr std::initializer_list<NWidgetPart> _nested_main_status_widgets = {
217 NWidget(WWT_PUSHBTN, Colours::Grey, WID_S_MIDDLE), SetMinimalSize(40, 12), SetToolTip(STR_STATUSBAR_TOOLTIP_SHOW_LAST_NEWS), SetResize(1, 0),
219 EndContainer(),
220};
221
224 WindowPosition::Manual, {}, 0, 0,
225 WindowClass::Statusbar, WindowClass::None,
227 _nested_main_status_widgets
228);
229
235{
236 const StatusBarWindow *w = dynamic_cast<StatusBarWindow*>(FindWindowById(WindowClass::Statusbar, 0));
237 return w != nullptr && w->ticker_scroll < StatusBarWindow::TICKER_STOP;
238}
239
Class for backupping variables and making sure they are restored later.
An interval timer will fire every interval, and will continue to fire until it is deleted.
Definition timer.h:76
A timeout timer will fire once after the interval.
Definition timer.h:116
static Date date
Current date in days (day counter).
static constexpr TimerGame< struct Calendar >::Year MAX_YEAR
static constexpr Date DateAtStartOfYear(Year year)
static WidgetDimensions scaled
Widget dimensions scaled for current zoom level.
Definition window_gui.h:30
Definition of stuff that is very close to a company, like the company struct itself.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Functions related to companies.
void ShowCompanyFinances(CompanyID company)
Open the finances window of a company.
GUI Functions related to companies.
static constexpr CompanyID COMPANY_SPECTATOR
The client is spectating.
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.
@ Centre
Align to the centre.
@ ForceLeft
Force align to the left.
int CentreBounds(int min, int max, int size)
Determine where to position a centred object.
@ Middle
Align to the middle.
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
PauseModes _pause_mode
The current pause mode.
Definition gfx.cpp:46
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 FillDrawPixelInfo(DrawPixelInfo *n, int left, int top, int width, int height)
Set up a clipping area for only drawing into a certain area.
Definition gfx.cpp:1567
Functions related to the gfx engine.
@ Normal
Index of the normal font in the font tables.
Definition gfx_type.h:249
@ Grey
Grey.
Definition gfx_type.h:299
@ White
White colour.
Definition gfx_type.h:330
@ LightBlue
Light blue colour.
Definition gfx_type.h:331
@ FromString
Marker for telling to use the colour from the string.
Definition gfx_type.h:317
constexpr NWidgetPart SetMinimalSize(int16_t x, int16_t y)
Widget part function for setting the minimal size.
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.
#define Point
Macro that prevents name conflicts between included headers.
constexpr T abs(const T a)
Returns the absolute value of (scalar) variable.
Definition math_func.hpp:23
Functions related to news.
const NewsItem * GetStatusbarNews()
Get pointer to the current status bar news item.
Definition news_gui.cpp:70
void ShowLastNewsMessage()
Show previous news item.
GUI functions related to the news.
@ LinkGraph
A game paused due to the link graph schedule lagging.
Definition openttd.h:78
A number of safeguards to prevent using unsafe methods.
bool _do_autosave
are we doing an autosave at the moment?
Definition saveload.cpp:86
Functions related to saving and loading games.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
This file contains all sprite-related enums and defines.
void ShowStatusBar()
Show our status bar.
bool IsNewsTickerShown()
Checks whether the news ticker is currently being used.
static WindowDesc _main_status_desc(WindowPosition::Manual, {}, 0, 0, WindowClass::Statusbar, WindowClass::None, {WindowDefaultFlag::NoFocus, WindowDefaultFlag::NoClose}, _nested_main_status_widgets)
Window definition for the main status bar.
Functions, definitions and such used only by the GUI.
@ SBI_SHOW_REMINDER
show a reminder (dot on the right side of the statusbar)
@ SBI_SAVELOAD_FINISH
finished saving
@ SBI_SHOW_TICKER
start scrolling news
@ SBI_SAVELOAD_START
started saving
@ SBI_NEWS_DELETED
abort current news display (active news were deleted)
Types related to the statusbar widgets.
@ WID_S_LEFT
Left part of the statusbar; date is shown there.
@ WID_S_MIDDLE
Middle part; current news or company name or *** SAVING *** or *** PAUSED ***.
@ WID_S_RIGHT
Right part; bank balance.
Definition of base types and functions in a cross-platform compatible way.
static void StrMakeValid(Builder &builder, StringConsumer &consumer, StringValidationSettings settings)
Copies the valid (UTF-8) characters from consumer to the builder.
Definition string.cpp:118
Functions related to low-level strings.
@ ReplaceTabCrNlWithSpace
Replace tabs ('\t'), carriage returns ('\r') and newlines (' ') with spaces.
Definition string_type.h:53
uint64_t GetParamMaxValue(uint64_t max_value, uint min_count, FontSize size)
Get some number that is suitable for string size computations.
Definition strings.cpp:235
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.
StrongType::Typedef< uint32_t, struct StringIDTag, StrongType::Compare, StrongType::Integer > StringID
Numeric value that represents a string, independent of the selected language.
@ TD_RTL
Text is written right-to-left by default.
Class to backup a specific variable and restore it upon destruction of this object to prevent stack v...
Money money
Money owned by the company.
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.
Data about how and where to blit pixels.
Definition gfx_type.h:157
Information about a single item of news.
Definition news_type.h:134
static Pool::IterateWrapper< Company > Iterate(size_t from=0)
static Company * GetIfValid(auto index)
Specification of a rectangle with absolute coordinates of all edges.
Rect Shrink(int s) const
Copy and shrink Rect by s pixels.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
void FindWindowPlacementAndResize(int, int def_height, bool allow_resize) override
Resize window towards the default size.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
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.
const IntervalTimer< TimerWindow > ticker_scroll_interval
Move information on the ticker slowly from one side to the other.
static const int TICKER_STOP
scrolling is finished when counter reaches this value
Point OnInitialPosition(int16_t sm_width, int16_t sm_height, int window_number) override
Compute the initial position of the window.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
static const int COUNTER_STEP
this is subtracted from active counters every tick
static constexpr auto REMINDER_START
time in ms for reminder notification (red dot on the right) to stay
High level window description.
Definition window_gui.h:171
void SetWidgetDirty(WidgetID widget_index) const
Invalidate a widget, i.e.
Definition window.cpp:565
ResizeInfo resize
Resize information.
Definition window_gui.h:313
virtual void FindWindowPlacementAndResize(int def_width, int def_height, bool allow_resize)
Resize window towards the default size.
Definition window.cpp:1523
Window(WindowDesc &desc)
Empty constructor, initialization has been moved to InitNested() called from the constructor of the d...
Definition window.cpp:1879
void InitNested(WindowNumber number=0)
Perform complete initialization of the Window with nested widgets, to allow use.
Definition window.cpp:1869
WindowFlags flags
Window flags.
Definition window_gui.h:299
WindowNumber window_number
Window number within the window class.
Definition window_gui.h:301
Functions related to tile highlights.
void ResetObjectToPlace()
Reset the cursor and mouse mode handling back to default (normal cursor, only clicking in windows).
Definition of Interval and OneShot timers.
Definition of the game-calendar-timer.
Definition of the Window system.
uint _toolbar_width
Width of the toolbar, shared by statusbar.
Stuff related to the (main) toolbar.
static RectPadding ScaleGUITrad(const RectPadding &r)
Scale a RectPadding to GUI zoom level.
Definition widget.cpp:49
@ WWT_PUSHBTN
Normal push-button (no toggle button) with custom drawing.
@ NWID_HORIZONTAL
Horizontal container.
Definition widget_type.h:66
@ WWT_PANEL
Simple depressed panel.
Definition widget_type.h:39
int PositionStatusbar(Window *w)
(Re)position statusbar window at the screen.
Definition window.cpp:3560
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition window.cpp:3377
Window * FindWindowById(WindowClass cls, WindowNumber number)
Find a window by its class and window number.
Definition window.cpp:1199
Window functions not directly related to making/drawing windows.
Functions, definitions and such used only by the GUI.
@ NoClose
This window can't be interactively closed.
Definition window_gui.h:157
@ NoFocus
This window won't get focus/make any other window lose focus when click.
Definition window_gui.h:156
@ WhiteBorder
Window white border counter bit mask.
Definition window_gui.h:231
@ Manual
Manually align the window (so no automatic location finding).
Definition window_gui.h:144
int WidgetID
Widget ID.
Definition window_type.h:21
Functions related to zooming.