(svn r27770) -Fix [FS#6540]: Initialize variables in station_sl.cpp (JGR)
[openttd.git] / src / news_gui.cpp
blob3800af8b5723f49792cf5f9a97d644cd160e5608
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 news_gui.cpp GUI functions related to news messages. */
12 #include "stdafx.h"
13 #include "gui.h"
14 #include "viewport_func.h"
15 #include "strings_func.h"
16 #include "window_func.h"
17 #include "date_func.h"
18 #include "vehicle_base.h"
19 #include "vehicle_func.h"
20 #include "vehicle_gui.h"
21 #include "station_base.h"
22 #include "industry.h"
23 #include "town.h"
24 #include "sound_func.h"
25 #include "string_func.h"
26 #include "widgets/dropdown_func.h"
27 #include "statusbar_gui.h"
28 #include "company_manager_face.h"
29 #include "company_func.h"
30 #include "engine_base.h"
31 #include "engine_gui.h"
32 #include "core/geometry_func.hpp"
33 #include "command_func.h"
34 #include "company_base.h"
35 #include "settings_internal.h"
37 #include "widgets/news_widget.h"
39 #include "table/strings.h"
41 #include "safeguards.h"
43 const NewsItem *_statusbar_news_item = NULL;
45 static uint MIN_NEWS_AMOUNT = 30; ///< preferred minimum amount of news messages
46 static uint _total_news = 0; ///< current number of news items
47 static NewsItem *_oldest_news = NULL; ///< head of news items queue
48 static NewsItem *_latest_news = NULL; ///< tail of news items queue
50 /**
51 * Forced news item.
52 * Users can force an item by accessing the history or "last message".
53 * If the message being shown was forced by the user, a pointer is stored
54 * in _forced_news. Otherwise, \a _forced_news variable is NULL.
56 static const NewsItem *_forced_news = NULL; ///< item the user has asked for
58 /** Current news item (last item shown regularly). */
59 static const NewsItem *_current_news = NULL;
62 /**
63 * Get the position a news-reference is referencing.
64 * @param reftype The type of reference.
65 * @param ref The reference.
66 * @return A tile for the referenced object, or INVALID_TILE if none.
68 static TileIndex GetReferenceTile(NewsReferenceType reftype, uint32 ref)
70 switch (reftype) {
71 case NR_TILE: return (TileIndex)ref;
72 case NR_STATION: return Station::Get((StationID)ref)->xy;
73 case NR_INDUSTRY: return Industry::Get((IndustryID)ref)->location.tile + TileDiffXY(1, 1);
74 case NR_TOWN: return Town::Get((TownID)ref)->xy;
75 default: return INVALID_TILE;
79 /* Normal news items. */
80 static const NWidgetPart _nested_normal_news_widgets[] = {
81 NWidget(WWT_PANEL, COLOUR_WHITE, WID_N_PANEL),
82 NWidget(NWID_HORIZONTAL), SetPadding(1, 1, 0, 1),
83 NWidget(WWT_CLOSEBOX, COLOUR_WHITE, WID_N_CLOSEBOX), SetPadding(0, 0, 0, 1),
84 NWidget(NWID_SPACER), SetFill(1, 0),
85 NWidget(NWID_VERTICAL),
86 NWidget(WWT_LABEL, COLOUR_WHITE, WID_N_DATE), SetDataTip(STR_DATE_LONG_SMALL, STR_NULL),
87 NWidget(NWID_SPACER), SetFill(0, 1),
88 EndContainer(),
89 EndContainer(),
90 NWidget(WWT_EMPTY, COLOUR_WHITE, WID_N_MESSAGE), SetMinimalSize(428, 154), SetPadding(0, 5, 1, 5),
91 EndContainer(),
94 static WindowDesc _normal_news_desc(
95 WDP_MANUAL, NULL, 0, 0,
96 WC_NEWS_WINDOW, WC_NONE,
98 _nested_normal_news_widgets, lengthof(_nested_normal_news_widgets)
101 /* New vehicles news items. */
102 static const NWidgetPart _nested_vehicle_news_widgets[] = {
103 NWidget(WWT_PANEL, COLOUR_WHITE, WID_N_PANEL),
104 NWidget(NWID_HORIZONTAL), SetPadding(1, 1, 0, 1),
105 NWidget(NWID_VERTICAL),
106 NWidget(WWT_CLOSEBOX, COLOUR_WHITE, WID_N_CLOSEBOX), SetPadding(0, 0, 0, 1),
107 NWidget(NWID_SPACER), SetFill(0, 1),
108 EndContainer(),
109 NWidget(WWT_LABEL, COLOUR_WHITE, WID_N_VEH_TITLE), SetFill(1, 1), SetMinimalSize(419, 55), SetDataTip(STR_EMPTY, STR_NULL),
110 EndContainer(),
111 NWidget(WWT_PANEL, COLOUR_WHITE, WID_N_VEH_BKGND), SetPadding(0, 25, 1, 25),
112 NWidget(NWID_VERTICAL),
113 NWidget(WWT_EMPTY, INVALID_COLOUR, WID_N_VEH_NAME), SetMinimalSize(369, 33), SetFill(1, 0),
114 NWidget(WWT_EMPTY, INVALID_COLOUR, WID_N_VEH_SPR), SetMinimalSize(369, 32), SetFill(1, 0),
115 NWidget(WWT_EMPTY, INVALID_COLOUR, WID_N_VEH_INFO), SetMinimalSize(369, 46), SetFill(1, 0),
116 EndContainer(),
117 EndContainer(),
118 EndContainer(),
121 static WindowDesc _vehicle_news_desc(
122 WDP_MANUAL, NULL, 0, 0,
123 WC_NEWS_WINDOW, WC_NONE,
125 _nested_vehicle_news_widgets, lengthof(_nested_vehicle_news_widgets)
128 /* Company news items. */
129 static const NWidgetPart _nested_company_news_widgets[] = {
130 NWidget(WWT_PANEL, COLOUR_WHITE, WID_N_PANEL),
131 NWidget(NWID_HORIZONTAL), SetPadding(1, 1, 0, 1),
132 NWidget(NWID_VERTICAL),
133 NWidget(WWT_CLOSEBOX, COLOUR_WHITE, WID_N_CLOSEBOX), SetPadding(0, 0, 0, 1),
134 NWidget(NWID_SPACER), SetFill(0, 1),
135 EndContainer(),
136 NWidget(WWT_LABEL, COLOUR_WHITE, WID_N_TITLE), SetFill(1, 1), SetMinimalSize(410, 20), SetDataTip(STR_EMPTY, STR_NULL),
137 EndContainer(),
138 NWidget(NWID_HORIZONTAL), SetPadding(0, 1, 1, 1),
139 NWidget(NWID_VERTICAL),
140 NWidget(WWT_EMPTY, COLOUR_WHITE, WID_N_MGR_FACE), SetMinimalSize(93, 119), SetPadding(2, 6, 2, 1),
141 NWidget(WWT_EMPTY, COLOUR_WHITE, WID_N_MGR_NAME), SetMinimalSize(93, 24), SetPadding(0, 0, 0, 1),
142 NWidget(NWID_SPACER), SetFill(0, 1),
143 EndContainer(),
144 NWidget(WWT_EMPTY, COLOUR_WHITE, WID_N_COMPANY_MSG), SetFill(1, 1), SetMinimalSize(328, 150),
145 EndContainer(),
146 EndContainer(),
149 static WindowDesc _company_news_desc(
150 WDP_MANUAL, NULL, 0, 0,
151 WC_NEWS_WINDOW, WC_NONE,
153 _nested_company_news_widgets, lengthof(_nested_company_news_widgets)
156 /* Thin news items. */
157 static const NWidgetPart _nested_thin_news_widgets[] = {
158 NWidget(WWT_PANEL, COLOUR_WHITE, WID_N_PANEL),
159 NWidget(NWID_HORIZONTAL), SetPadding(1, 1, 0, 1),
160 NWidget(WWT_CLOSEBOX, COLOUR_WHITE, WID_N_CLOSEBOX), SetPadding(0, 0, 0, 1),
161 NWidget(NWID_SPACER), SetFill(1, 0),
162 NWidget(NWID_VERTICAL),
163 NWidget(WWT_LABEL, COLOUR_WHITE, WID_N_DATE), SetDataTip(STR_DATE_LONG_SMALL, STR_NULL),
164 NWidget(NWID_SPACER), SetFill(0, 1),
165 EndContainer(),
166 EndContainer(),
167 NWidget(WWT_EMPTY, COLOUR_WHITE, WID_N_MESSAGE), SetMinimalSize(428, 48), SetFill(1, 0), SetPadding(0, 5, 0, 5),
168 NWidget(NWID_VIEWPORT, INVALID_COLOUR, WID_N_VIEWPORT), SetMinimalSize(426, 70), SetPadding(1, 2, 2, 2),
169 EndContainer(),
172 static WindowDesc _thin_news_desc(
173 WDP_MANUAL, NULL, 0, 0,
174 WC_NEWS_WINDOW, WC_NONE,
176 _nested_thin_news_widgets, lengthof(_nested_thin_news_widgets)
179 /* Small news items. */
180 static const NWidgetPart _nested_small_news_widgets[] = {
181 /* Caption + close box. The caption is no WWT_CAPTION as the window shall not be moveable and so on. */
182 NWidget(NWID_HORIZONTAL),
183 NWidget(WWT_CLOSEBOX, COLOUR_LIGHT_BLUE, WID_N_CLOSEBOX),
184 NWidget(WWT_EMPTY, COLOUR_LIGHT_BLUE, WID_N_CAPTION), SetFill(1, 0),
185 EndContainer(),
187 /* Main part */
188 NWidget(WWT_PANEL, COLOUR_LIGHT_BLUE, WID_N_HEADLINE),
189 NWidget(WWT_INSET, COLOUR_LIGHT_BLUE, WID_N_INSET), SetPadding(2, 2, 2, 2),
190 NWidget(NWID_VIEWPORT, INVALID_COLOUR, WID_N_VIEWPORT), SetPadding(1, 1, 1, 1), SetMinimalSize(274, 47), SetFill(1, 0),
191 EndContainer(),
192 NWidget(WWT_EMPTY, COLOUR_WHITE, WID_N_MESSAGE), SetMinimalSize(275, 20), SetFill(1, 0), SetPadding(0, 5, 0, 5),
193 EndContainer(),
196 static WindowDesc _small_news_desc(
197 WDP_MANUAL, NULL, 0, 0,
198 WC_NEWS_WINDOW, WC_NONE,
200 _nested_small_news_widgets, lengthof(_nested_small_news_widgets)
204 * Window layouts for news items.
206 static WindowDesc* _news_window_layout[] = {
207 &_thin_news_desc, ///< NF_THIN
208 &_small_news_desc, ///< NF_SMALL
209 &_normal_news_desc, ///< NF_NORMAL
210 &_vehicle_news_desc, ///< NF_VEHICLE
211 &_company_news_desc, ///< NF_COMPANY
214 WindowDesc* GetNewsWindowLayout(NewsFlag flags)
216 uint layout = GB(flags, NFB_WINDOW_LAYOUT, NFB_WINDOW_LAYOUT_COUNT);
217 assert(layout < lengthof(_news_window_layout));
218 return _news_window_layout[layout];
222 * Per-NewsType data
224 static NewsTypeData _news_type_data[] = {
225 /* name, age, sound, */
226 NewsTypeData("news_display.arrival_player", 60, SND_1D_APPLAUSE ), ///< NT_ARRIVAL_COMPANY
227 NewsTypeData("news_display.arrival_other", 60, SND_1D_APPLAUSE ), ///< NT_ARRIVAL_OTHER
228 NewsTypeData("news_display.accident", 90, SND_BEGIN ), ///< NT_ACCIDENT
229 NewsTypeData("news_display.company_info", 60, SND_BEGIN ), ///< NT_COMPANY_INFO
230 NewsTypeData("news_display.open", 90, SND_BEGIN ), ///< NT_INDUSTRY_OPEN
231 NewsTypeData("news_display.close", 90, SND_BEGIN ), ///< NT_INDUSTRY_CLOSE
232 NewsTypeData("news_display.economy", 30, SND_BEGIN ), ///< NT_ECONOMY
233 NewsTypeData("news_display.production_player", 30, SND_BEGIN ), ///< NT_INDUSTRY_COMPANY
234 NewsTypeData("news_display.production_other", 30, SND_BEGIN ), ///< NT_INDUSTRY_OTHER
235 NewsTypeData("news_display.production_nobody", 30, SND_BEGIN ), ///< NT_INDUSTRY_NOBODY
236 NewsTypeData("news_display.advice", 150, SND_BEGIN ), ///< NT_ADVICE
237 NewsTypeData("news_display.new_vehicles", 30, SND_1E_OOOOH ), ///< NT_NEW_VEHICLES
238 NewsTypeData("news_display.acceptance", 90, SND_BEGIN ), ///< NT_ACCEPTANCE
239 NewsTypeData("news_display.subsidies", 180, SND_BEGIN ), ///< NT_SUBSIDIES
240 NewsTypeData("news_display.general", 60, SND_BEGIN ), ///< NT_GENERAL
243 assert_compile(lengthof(_news_type_data) == NT_END);
246 * Return the news display option.
247 * @return display options
249 NewsDisplay NewsTypeData::GetDisplay() const
251 uint index;
252 const SettingDesc *sd = GetSettingFromName(this->name, &index);
253 assert(sd != NULL);
254 void *ptr = GetVariableAddress(NULL, &sd->save);
255 return (NewsDisplay)ReadValue(ptr, sd->save.conv);
258 /** Window class displaying a news item. */
259 struct NewsWindow : Window {
260 uint16 chat_height; ///< Height of the chat window.
261 uint16 status_height; ///< Height of the status bar window
262 const NewsItem *ni; ///< News item to display.
263 static uint duration; ///< Remaining time for showing current news message (may only be accessed while a news item is displayed).
265 NewsWindow(WindowDesc *desc, const NewsItem *ni) : Window(desc), ni(ni)
267 NewsWindow::duration = 555;
268 const Window *w = FindWindowByClass(WC_SEND_NETWORK_MSG);
269 this->chat_height = (w != NULL) ? w->height : 0;
270 this->status_height = FindWindowById(WC_STATUS_BAR, 0)->height;
272 this->flags |= WF_DISABLE_VP_SCROLL;
274 this->CreateNestedTree();
276 /* For company news with a face we have a separate headline in param[0] */
277 if (desc == &_company_news_desc) this->GetWidget<NWidgetCore>(WID_N_TITLE)->widget_data = this->ni->params[0];
279 this->FinishInitNested(0);
281 /* Initialize viewport if it exists. */
282 NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_N_VIEWPORT);
283 if (nvp != NULL) {
284 nvp->InitializeViewport(this, ni->reftype1 == NR_VEHICLE ? 0x80000000 | ni->ref1 : GetReferenceTile(ni->reftype1, ni->ref1), ZOOM_LVL_NEWS);
285 if (this->ni->flags & NF_NO_TRANSPARENT) nvp->disp_flags |= ND_NO_TRANSPARENCY;
286 if ((this->ni->flags & NF_INCOLOUR) == 0) {
287 nvp->disp_flags |= ND_SHADE_GREY;
288 } else if (this->ni->flags & NF_SHADE) {
289 nvp->disp_flags |= ND_SHADE_DIMMED;
293 PositionNewsMessage(this);
296 void DrawNewsBorder(const Rect &r) const
298 GfxFillRect(r.left, r.top, r.right, r.bottom, PC_WHITE);
300 GfxFillRect(r.left, r.top, r.left, r.bottom, PC_BLACK);
301 GfxFillRect(r.right, r.top, r.right, r.bottom, PC_BLACK);
302 GfxFillRect(r.left, r.top, r.right, r.top, PC_BLACK);
303 GfxFillRect(r.left, r.bottom, r.right, r.bottom, PC_BLACK);
306 virtual Point OnInitialPosition(int16 sm_width, int16 sm_height, int window_number)
308 Point pt = { 0, _screen.height };
309 return pt;
312 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
314 StringID str = STR_NULL;
315 switch (widget) {
316 case WID_N_MGR_FACE:
317 *size = maxdim(*size, GetSpriteSize(SPR_GRADIENT));
318 break;
320 case WID_N_MESSAGE:
321 CopyInDParam(0, this->ni->params, lengthof(this->ni->params));
322 str = this->ni->string_id;
323 break;
325 case WID_N_COMPANY_MSG:
326 str = this->GetCompanyMessageString();
327 break;
329 case WID_N_VEH_NAME:
330 case WID_N_VEH_TITLE:
331 str = this->GetNewVehicleMessageString(widget);
332 break;
334 case WID_N_VEH_INFO: {
335 assert(this->ni->reftype1 == NR_ENGINE);
336 EngineID engine = this->ni->ref1;
337 str = GetEngineInfoString(engine);
338 break;
340 default:
341 return; // Do nothing
344 /* Update minimal size with length of the multi-line string. */
345 Dimension d = *size;
346 d.width = (d.width >= padding.width) ? d.width - padding.width : 0;
347 d.height = (d.height >= padding.height) ? d.height - padding.height : 0;
348 d = GetStringMultiLineBoundingBox(str, d);
349 d.width += padding.width;
350 d.height += padding.height;
351 *size = maxdim(*size, d);
354 virtual void SetStringParameters(int widget) const
356 if (widget == WID_N_DATE) SetDParam(0, this->ni->date);
359 virtual void DrawWidget(const Rect &r, int widget) const
361 switch (widget) {
362 case WID_N_CAPTION:
363 DrawCaption(r, COLOUR_LIGHT_BLUE, this->owner, STR_NEWS_MESSAGE_CAPTION);
364 break;
366 case WID_N_PANEL:
367 this->DrawNewsBorder(r);
368 break;
370 case WID_N_MESSAGE:
371 CopyInDParam(0, this->ni->params, lengthof(this->ni->params));
372 DrawStringMultiLine(r.left, r.right, r.top, r.bottom, this->ni->string_id, TC_FROMSTRING, SA_CENTER);
373 break;
375 case WID_N_MGR_FACE: {
376 const CompanyNewsInformation *cni = (const CompanyNewsInformation*)this->ni->free_data;
377 DrawCompanyManagerFace(cni->face, cni->colour, r.left, r.top);
378 GfxFillRect(r.left, r.top, r.right, r.bottom, PALETTE_NEWSPAPER, FILLRECT_RECOLOUR);
379 break;
381 case WID_N_MGR_NAME: {
382 const CompanyNewsInformation *cni = (const CompanyNewsInformation*)this->ni->free_data;
383 SetDParamStr(0, cni->president_name);
384 DrawStringMultiLine(r.left, r.right, r.top, r.bottom, STR_JUST_RAW_STRING, TC_FROMSTRING, SA_CENTER);
385 break;
387 case WID_N_COMPANY_MSG:
388 DrawStringMultiLine(r.left, r.right, r.top, r.bottom, this->GetCompanyMessageString(), TC_FROMSTRING, SA_CENTER);
389 break;
391 case WID_N_VEH_BKGND:
392 GfxFillRect(r.left, r.top, r.right, r.bottom, PC_GREY);
393 break;
395 case WID_N_VEH_NAME:
396 case WID_N_VEH_TITLE:
397 DrawStringMultiLine(r.left, r.right, r.top, r.bottom, this->GetNewVehicleMessageString(widget), TC_FROMSTRING, SA_CENTER);
398 break;
400 case WID_N_VEH_SPR: {
401 assert(this->ni->reftype1 == NR_ENGINE);
402 EngineID engine = this->ni->ref1;
403 DrawVehicleEngine(r.left, r.right, (r.left + r.right) / 2, (r.top + r.bottom) / 2, engine, GetEnginePalette(engine, _local_company), EIT_PREVIEW);
404 GfxFillRect(r.left, r.top, r.right, r.bottom, PALETTE_NEWSPAPER, FILLRECT_RECOLOUR);
405 break;
407 case WID_N_VEH_INFO: {
408 assert(this->ni->reftype1 == NR_ENGINE);
409 EngineID engine = this->ni->ref1;
410 DrawStringMultiLine(r.left, r.right, r.top, r.bottom, GetEngineInfoString(engine), TC_FROMSTRING, SA_CENTER);
411 break;
416 virtual void OnClick(Point pt, int widget, int click_count)
418 switch (widget) {
419 case WID_N_CLOSEBOX:
420 NewsWindow::duration = 0;
421 delete this;
422 _forced_news = NULL;
423 break;
425 case WID_N_CAPTION:
426 if (this->ni->reftype1 == NR_VEHICLE) {
427 const Vehicle *v = Vehicle::Get(this->ni->ref1);
428 ShowVehicleViewWindow(v);
430 break;
432 case WID_N_VIEWPORT:
433 break; // Ignore clicks
435 default:
436 if (this->ni->reftype1 == NR_VEHICLE) {
437 const Vehicle *v = Vehicle::Get(this->ni->ref1);
438 ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos);
439 } else {
440 TileIndex tile1 = GetReferenceTile(this->ni->reftype1, this->ni->ref1);
441 TileIndex tile2 = GetReferenceTile(this->ni->reftype2, this->ni->ref2);
442 if (_ctrl_pressed) {
443 if (tile1 != INVALID_TILE) ShowExtraViewPortWindow(tile1);
444 if (tile2 != INVALID_TILE) ShowExtraViewPortWindow(tile2);
445 } else {
446 if ((tile1 == INVALID_TILE || !ScrollMainWindowToTile(tile1)) && tile2 != INVALID_TILE) {
447 ScrollMainWindowToTile(tile2);
451 break;
455 virtual EventState OnKeyPress(WChar key, uint16 keycode)
457 if (keycode == WKC_SPACE) {
458 /* Don't continue. */
459 delete this;
460 return ES_HANDLED;
462 return ES_NOT_HANDLED;
466 * Some data on this window has become invalid.
467 * @param data Information about the changed data.
468 * @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.
470 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
472 if (!gui_scope) return;
473 /* The chatbar has notified us that is was either created or closed */
474 int newtop = this->top + this->chat_height - data;
475 this->chat_height = data;
476 this->SetWindowTop(newtop);
479 virtual void OnTick()
481 /* Scroll up newsmessages from the bottom in steps of 4 pixels */
482 int newtop = max(this->top - 4, _screen.height - this->height - this->status_height - this->chat_height);
483 this->SetWindowTop(newtop);
486 private:
488 * Moves the window so #newtop is new 'top' coordinate. Makes screen dirty where needed.
489 * @param newtop new top coordinate
491 void SetWindowTop(int newtop)
493 if (this->top == newtop) return;
495 int mintop = min(newtop, this->top);
496 int maxtop = max(newtop, this->top);
497 if (this->viewport != NULL) this->viewport->top += newtop - this->top;
498 this->top = newtop;
500 SetDirtyBlocks(this->left, mintop, this->left + this->width, maxtop + this->height);
503 StringID GetCompanyMessageString() const
505 /* Company news with a face have a separate headline, so the normal message is shifted by two params */
506 CopyInDParam(0, this->ni->params + 2, lengthof(this->ni->params) - 2);
507 return this->ni->params[1];
510 StringID GetNewVehicleMessageString(int widget) const
512 assert(this->ni->reftype1 == NR_ENGINE);
513 EngineID engine = this->ni->ref1;
515 switch (widget) {
516 case WID_N_VEH_TITLE:
517 SetDParam(0, GetEngineCategoryName(engine));
518 return STR_NEWS_NEW_VEHICLE_NOW_AVAILABLE;
520 case WID_N_VEH_NAME:
521 SetDParam(0, engine);
522 return STR_NEWS_NEW_VEHICLE_TYPE;
524 default:
525 NOT_REACHED();
530 /* static */ uint NewsWindow::duration = 0; // Instance creation.
533 /** Open up an own newspaper window for the news item */
534 static void ShowNewspaper(const NewsItem *ni)
536 SoundFx sound = _news_type_data[ni->type].sound;
537 if (sound != 0 && _settings_client.sound.news_full) SndPlayFx(sound);
539 new NewsWindow(GetNewsWindowLayout(ni->flags), ni);
542 /** Show news item in the ticker */
543 static void ShowTicker(const NewsItem *ni)
545 if (_settings_client.sound.news_ticker) SndPlayFx(SND_16_MORSE);
547 _statusbar_news_item = ni;
548 InvalidateWindowData(WC_STATUS_BAR, 0, SBI_SHOW_TICKER);
551 /** Initialize the news-items data structures */
552 void InitNewsItemStructs()
554 for (NewsItem *ni = _oldest_news; ni != NULL; ) {
555 NewsItem *next = ni->next;
556 delete ni;
557 ni = next;
560 _total_news = 0;
561 _oldest_news = NULL;
562 _latest_news = NULL;
563 _forced_news = NULL;
564 _current_news = NULL;
565 _statusbar_news_item = NULL;
566 NewsWindow::duration = 0;
570 * Are we ready to show another news item?
571 * Only if nothing is in the newsticker and no newspaper is displayed
573 static bool ReadyForNextItem()
575 const NewsItem *ni = _forced_news == NULL ? _current_news : _forced_news;
576 if (ni == NULL) return true;
578 /* Ticker message
579 * Check if the status bar message is still being displayed? */
580 if (IsNewsTickerShown()) return false;
582 /* Newspaper message, decrement duration counter */
583 if (NewsWindow::duration != 0) NewsWindow::duration--;
585 /* neither newsticker nor newspaper are running */
586 return (NewsWindow::duration == 0 || FindWindowById(WC_NEWS_WINDOW, 0) == NULL);
589 /** Move to the next news item */
590 static void MoveToNextItem()
592 InvalidateWindowData(WC_STATUS_BAR, 0, SBI_NEWS_DELETED); // invalidate the statusbar
593 DeleteWindowById(WC_NEWS_WINDOW, 0); // close the newspapers window if shown
594 _forced_news = NULL;
595 _statusbar_news_item = NULL;
597 /* if we're not at the last item, then move on */
598 if (_current_news != _latest_news) {
599 _current_news = (_current_news == NULL) ? _oldest_news : _current_news->next;
600 const NewsItem *ni = _current_news;
601 const NewsType type = ni->type;
603 /* check the date, don't show too old items */
604 if (_date - _news_type_data[type].age > ni->date) return;
606 switch (_news_type_data[type].GetDisplay()) {
607 default: NOT_REACHED();
608 case ND_OFF: // Off - show nothing only a small reminder in the status bar
609 InvalidateWindowData(WC_STATUS_BAR, 0, SBI_SHOW_REMINDER);
610 break;
612 case ND_SUMMARY: // Summary - show ticker
613 ShowTicker(ni);
614 break;
616 case ND_FULL: // Full - show newspaper
617 ShowNewspaper(ni);
618 break;
624 * Add a new newsitem to be shown.
625 * @param string String to display
626 * @param type news category
627 * @param flags display flags for the news
628 * @param reftype1 Type of ref1
629 * @param ref1 Reference 1 to some object: Used for a possible viewport, scrolling after clicking on the news, and for deleteing the news when the object is deleted.
630 * @param reftype2 Type of ref2
631 * @param ref2 Reference 2 to some object: Used for scrolling after clicking on the news, and for deleteing the news when the object is deleted.
632 * @param free_data Pointer to data that must be freed once the news message is cleared
634 * @see NewsSubtype
636 void AddNewsItem(StringID string, NewsType type, NewsFlag flags, NewsReferenceType reftype1, uint32 ref1, NewsReferenceType reftype2, uint32 ref2, void *free_data)
638 if (_game_mode == GM_MENU) return;
640 /* Create new news item node */
641 NewsItem *ni = new NewsItem;
643 ni->string_id = string;
644 ni->type = type;
645 ni->flags = flags;
647 /* show this news message in colour? */
648 if (_cur_year >= _settings_client.gui.coloured_news_year) ni->flags |= NF_INCOLOUR;
650 ni->reftype1 = reftype1;
651 ni->reftype2 = reftype2;
652 ni->ref1 = ref1;
653 ni->ref2 = ref2;
654 ni->free_data = free_data;
655 ni->date = _date;
656 CopyOutDParam(ni->params, 0, lengthof(ni->params));
658 if (_total_news++ == 0) {
659 assert(_oldest_news == NULL);
660 _oldest_news = ni;
661 ni->prev = NULL;
662 } else {
663 assert(_latest_news->next == NULL);
664 _latest_news->next = ni;
665 ni->prev = _latest_news;
668 ni->next = NULL;
669 _latest_news = ni;
671 SetWindowDirty(WC_MESSAGE_HISTORY, 0);
675 * Create a new custom news item.
676 * @param tile unused
677 * @param flags type of operation
678 * @param p1 various bitstuffed elements
679 * - p1 = (bit 0 - 7) - NewsType of the message.
680 * - p1 = (bit 8 - 15) - NewsReferenceType of first reference.
681 * - p1 = (bit 16 - 23) - Company this news message is for.
682 * @param p2 First reference of the news message.
683 * @param text The text of the news message.
684 * @return the cost of this operation or an error
686 CommandCost CmdCustomNewsItem(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
688 if (_current_company != OWNER_DEITY) return CMD_ERROR;
690 NewsType type = (NewsType)GB(p1, 0, 8);
691 NewsReferenceType reftype1 = (NewsReferenceType)GB(p1, 8, 8);
692 CompanyID company = (CompanyID)GB(p1, 16, 8);
694 if (company != INVALID_OWNER && !Company::IsValidID(company)) return CMD_ERROR;
695 if (type >= NT_END) return CMD_ERROR;
696 if (StrEmpty(text)) return CMD_ERROR;
698 switch (reftype1) {
699 case NR_NONE: break;
700 case NR_TILE:
701 if (!IsValidTile(p2)) return CMD_ERROR;
702 break;
704 case NR_VEHICLE:
705 if (!Vehicle::IsValidID(p2)) return CMD_ERROR;
706 break;
708 case NR_STATION:
709 if (!Station::IsValidID(p2)) return CMD_ERROR;
710 break;
712 case NR_INDUSTRY:
713 if (!Industry::IsValidID(p2)) return CMD_ERROR;
714 break;
716 case NR_TOWN:
717 if (!Town::IsValidID(p2)) return CMD_ERROR;
718 break;
720 case NR_ENGINE:
721 if (!Engine::IsValidID(p2)) return CMD_ERROR;
722 break;
724 default: return CMD_ERROR;
727 if (company != INVALID_OWNER && company != _local_company) return CommandCost();
729 if (flags & DC_EXEC) {
730 char *news = stredup(text);
731 SetDParamStr(0, news);
732 AddNewsItem(STR_NEWS_CUSTOM_ITEM, type, NF_NORMAL, reftype1, p2, NR_NONE, UINT32_MAX, news);
735 return CommandCost();
738 /** Delete a news item from the queue */
739 static void DeleteNewsItem(NewsItem *ni)
741 /* Delete the news from the news queue. */
742 if (ni->prev != NULL) {
743 ni->prev->next = ni->next;
744 } else {
745 assert(_oldest_news == ni);
746 _oldest_news = ni->next;
749 if (ni->next != NULL) {
750 ni->next->prev = ni->prev;
751 } else {
752 assert(_latest_news == ni);
753 _latest_news = ni->prev;
756 _total_news--;
758 if (_forced_news == ni || _current_news == ni || _statusbar_news_item == ni) {
759 /* When we're the current news, go to the previous item first;
760 * we just possibly made that the last news item. */
761 if (_current_news == ni) _current_news = ni->prev;
763 /* About to remove the currently forced item (shown as newspapers) ||
764 * about to remove the currently displayed item (newspapers, ticker, or just a reminder) */
765 MoveToNextItem();
768 delete ni;
770 SetWindowDirty(WC_MESSAGE_HISTORY, 0);
774 * Delete a news item type about a vehicle.
775 * When the news item type is INVALID_STRING_ID all news about the vehicle gets deleted.
776 * @param vid The vehicle to remove the news for.
777 * @param news The news type to remove.
779 void DeleteVehicleNews(VehicleID vid, StringID news)
781 NewsItem *ni = _oldest_news;
783 while (ni != NULL) {
784 NewsItem *next = ni->next;
785 if (((ni->reftype1 == NR_VEHICLE && ni->ref1 == vid) || (ni->reftype2 == NR_VEHICLE && ni->ref2 == vid)) &&
786 (news == INVALID_STRING_ID || ni->string_id == news)) {
787 DeleteNewsItem(ni);
789 ni = next;
794 * Remove news regarding given station so there are no 'unknown station now accepts Mail'
795 * or 'First train arrived at unknown station' news items.
796 * @param sid station to remove news about
798 void DeleteStationNews(StationID sid)
800 NewsItem *ni = _oldest_news;
802 while (ni != NULL) {
803 NewsItem *next = ni->next;
804 if ((ni->reftype1 == NR_STATION && ni->ref1 == sid) || (ni->reftype2 == NR_STATION && ni->ref2 == sid)) {
805 DeleteNewsItem(ni);
807 ni = next;
812 * Remove news regarding given industry
813 * @param iid industry to remove news about
815 void DeleteIndustryNews(IndustryID iid)
817 NewsItem *ni = _oldest_news;
819 while (ni != NULL) {
820 NewsItem *next = ni->next;
821 if ((ni->reftype1 == NR_INDUSTRY && ni->ref1 == iid) || (ni->reftype2 == NR_INDUSTRY && ni->ref2 == iid)) {
822 DeleteNewsItem(ni);
824 ni = next;
829 * Remove engine announcements for invalid engines.
831 void DeleteInvalidEngineNews()
833 NewsItem *ni = _oldest_news;
835 while (ni != NULL) {
836 NewsItem *next = ni->next;
837 if ((ni->reftype1 == NR_ENGINE && (!Engine::IsValidID(ni->ref1) || !Engine::Get(ni->ref1)->IsEnabled())) ||
838 (ni->reftype2 == NR_ENGINE && (!Engine::IsValidID(ni->ref2) || !Engine::Get(ni->ref2)->IsEnabled()))) {
839 DeleteNewsItem(ni);
841 ni = next;
845 static void RemoveOldNewsItems()
847 NewsItem *next;
848 for (NewsItem *cur = _oldest_news; _total_news > MIN_NEWS_AMOUNT && cur != NULL; cur = next) {
849 next = cur->next;
850 if (_date - _news_type_data[cur->type].age * _settings_client.gui.news_message_timeout > cur->date) DeleteNewsItem(cur);
855 * Report a change in vehicle IDs (due to autoreplace) to affected vehicle news.
856 * @note Viewports of currently displayed news is changed via #ChangeVehicleViewports
857 * @param from_index the old vehicle ID
858 * @param to_index the new vehicle ID
860 void ChangeVehicleNews(VehicleID from_index, VehicleID to_index)
862 for (NewsItem *ni = _oldest_news; ni != NULL; ni = ni->next) {
863 if (ni->reftype1 == NR_VEHICLE && ni->ref1 == from_index) ni->ref1 = to_index;
864 if (ni->reftype2 == NR_VEHICLE && ni->ref2 == from_index) ni->ref2 = to_index;
865 if (ni->flags & NF_VEHICLE_PARAM0 && ni->params[0] == from_index) ni->params[0] = to_index;
869 void NewsLoop()
871 /* no news item yet */
872 if (_total_news == 0) return;
874 /* There is no status bar, so no reason to show news;
875 * especially important with the end game screen when
876 * there is no status bar but possible news. */
877 if (FindWindowById(WC_STATUS_BAR, 0) == NULL) return;
879 static byte _last_clean_month = 0;
881 if (_last_clean_month != _cur_month) {
882 RemoveOldNewsItems();
883 _last_clean_month = _cur_month;
886 if (ReadyForNextItem()) MoveToNextItem();
889 /** Do a forced show of a specific message */
890 static void ShowNewsMessage(const NewsItem *ni)
892 assert(_total_news != 0);
894 /* Delete the news window */
895 DeleteWindowById(WC_NEWS_WINDOW, 0);
897 /* setup forced news item */
898 _forced_news = ni;
900 if (_forced_news != NULL) {
901 DeleteWindowById(WC_NEWS_WINDOW, 0);
902 ShowNewspaper(ni);
906 /** Show previous news item */
907 void ShowLastNewsMessage()
909 const NewsItem *ni = NULL;
910 if (_total_news == 0) {
911 return;
912 } else if (_forced_news == NULL) {
913 /* Not forced any news yet, show the current one, unless a news window is
914 * open (which can only be the current one), then show the previous item */
915 if (_current_news == NULL) {
916 /* No news were shown yet resp. the last shown one was already deleted.
917 * Threat this as if _forced_news reached _oldest_news; so, wrap around and start anew with the latest. */
918 ni = _latest_news;
919 } else {
920 const Window *w = FindWindowById(WC_NEWS_WINDOW, 0);
921 ni = (w == NULL || (_current_news == _oldest_news)) ? _current_news : _current_news->prev;
923 } else if (_forced_news == _oldest_news) {
924 /* We have reached the oldest news, start anew with the latest */
925 ni = _latest_news;
926 } else {
927 /* 'Scrolling' through news history show each one in turn */
928 ni = _forced_news->prev;
930 bool wrap = false;
931 for (;;) {
932 if (_news_type_data[ni->type].GetDisplay() != ND_OFF) {
933 ShowNewsMessage(ni);
934 break;
937 ni = ni->prev;
938 if (ni == NULL) {
939 if (wrap) break;
940 /* We have reached the oldest news, start anew with the latest */
941 ni = _latest_news;
942 wrap = true;
949 * Draw an unformatted news message truncated to a maximum length. If
950 * length exceeds maximum length it will be postfixed by '...'
951 * @param left the left most location for the string
952 * @param right the right most location for the string
953 * @param y position of the string
954 * @param colour the colour the string will be shown in
955 * @param *ni NewsItem being printed
956 * @param maxw maximum width of string in pixels
958 static void DrawNewsString(uint left, uint right, int y, TextColour colour, const NewsItem *ni)
960 char buffer[512], buffer2[512];
961 StringID str;
963 CopyInDParam(0, ni->params, lengthof(ni->params));
964 str = ni->string_id;
966 GetString(buffer, str, lastof(buffer));
967 /* Copy the just gotten string to another buffer to remove any formatting
968 * from it such as big fonts, etc. */
969 const char *ptr = buffer;
970 char *dest = buffer2;
971 WChar c_last = '\0';
972 for (;;) {
973 WChar c = Utf8Consume(&ptr);
974 if (c == 0) break;
975 /* Make a space from a newline, but ignore multiple newlines */
976 if (c == '\n' && c_last != '\n') {
977 dest[0] = ' ';
978 dest++;
979 } else if (c == '\r') {
980 dest[0] = dest[1] = dest[2] = dest[3] = ' ';
981 dest += 4;
982 } else if (IsPrintable(c)) {
983 dest += Utf8Encode(dest, c);
985 c_last = c;
988 *dest = '\0';
989 /* Truncate and show string; postfixed by '...' if necessary */
990 DrawString(left, right, y, buffer2, colour);
993 struct MessageHistoryWindow : Window {
994 static const int top_spacing; ///< Additional spacing at the top of the #WID_MH_BACKGROUND widget.
995 static const int bottom_spacing; ///< Additional spacing at the bottom of the #WID_MH_BACKGROUND widget.
997 int line_height; /// < Height of a single line in the news history window including spacing.
998 int date_width; /// < Width needed for the date part.
1000 Scrollbar *vscroll;
1002 MessageHistoryWindow(WindowDesc *desc) : Window(desc)
1004 this->CreateNestedTree();
1005 this->vscroll = this->GetScrollbar(WID_MH_SCROLLBAR);
1006 this->FinishInitNested(); // Initializes 'this->line_height' and 'this->date_width'.
1007 this->OnInvalidateData(0);
1010 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
1012 if (widget == WID_MH_BACKGROUND) {
1013 this->line_height = FONT_HEIGHT_NORMAL + 2;
1014 resize->height = this->line_height;
1016 /* Months are off-by-one, so it's actually 8. Not using
1017 * month 12 because the 1 is usually less wide. */
1018 SetDParam(0, ConvertYMDToDate(ORIGINAL_MAX_YEAR, 7, 30));
1019 this->date_width = GetStringBoundingBox(STR_SHORT_DATE).width;
1021 size->height = 4 * resize->height + this->top_spacing + this->bottom_spacing; // At least 4 lines are visible.
1022 size->width = max(200u, size->width); // At least 200 pixels wide.
1026 virtual void OnPaint()
1028 this->OnInvalidateData(0);
1029 this->DrawWidgets();
1032 virtual void DrawWidget(const Rect &r, int widget) const
1034 if (widget != WID_MH_BACKGROUND || _total_news == 0) return;
1036 /* Find the first news item to display. */
1037 NewsItem *ni = _latest_news;
1038 for (int n = this->vscroll->GetPosition(); n > 0; n--) {
1039 ni = ni->prev;
1040 if (ni == NULL) return;
1043 /* Fill the widget with news items. */
1044 int y = r.top + this->top_spacing;
1045 bool rtl = _current_text_dir == TD_RTL;
1046 uint date_left = rtl ? r.right - WD_FRAMERECT_RIGHT - this->date_width : r.left + WD_FRAMERECT_LEFT;
1047 uint date_right = rtl ? r.right - WD_FRAMERECT_RIGHT : r.left + WD_FRAMERECT_LEFT + this->date_width;
1048 uint news_left = rtl ? r.left + WD_FRAMERECT_LEFT : r.left + WD_FRAMERECT_LEFT + this->date_width + WD_FRAMERECT_RIGHT;
1049 uint news_right = rtl ? r.right - WD_FRAMERECT_RIGHT - this->date_width - WD_FRAMERECT_RIGHT : r.right - WD_FRAMERECT_RIGHT;
1050 for (int n = this->vscroll->GetCapacity(); n > 0; n--) {
1051 SetDParam(0, ni->date);
1052 DrawString(date_left, date_right, y, STR_SHORT_DATE);
1054 DrawNewsString(news_left, news_right, y, TC_WHITE, ni);
1055 y += this->line_height;
1057 ni = ni->prev;
1058 if (ni == NULL) return;
1063 * Some data on this window has become invalid.
1064 * @param data Information about the changed data.
1065 * @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.
1067 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
1069 if (!gui_scope) return;
1070 this->vscroll->SetCount(_total_news);
1073 virtual void OnClick(Point pt, int widget, int click_count)
1075 if (widget == WID_MH_BACKGROUND) {
1076 NewsItem *ni = _latest_news;
1077 if (ni == NULL) return;
1079 for (int n = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_MH_BACKGROUND, WD_FRAMERECT_TOP, this->line_height); n > 0; n--) {
1080 ni = ni->prev;
1081 if (ni == NULL) return;
1084 ShowNewsMessage(ni);
1088 virtual void OnResize()
1090 this->vscroll->SetCapacityFromWidget(this, WID_MH_BACKGROUND);
1094 const int MessageHistoryWindow::top_spacing = WD_FRAMERECT_TOP + 4;
1095 const int MessageHistoryWindow::bottom_spacing = WD_FRAMERECT_BOTTOM;
1097 static const NWidgetPart _nested_message_history[] = {
1098 NWidget(NWID_HORIZONTAL),
1099 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
1100 NWidget(WWT_CAPTION, COLOUR_BROWN), SetDataTip(STR_MESSAGE_HISTORY, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1101 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
1102 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
1103 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
1104 EndContainer(),
1106 NWidget(NWID_HORIZONTAL),
1107 NWidget(WWT_PANEL, COLOUR_BROWN, WID_MH_BACKGROUND), SetMinimalSize(200, 125), SetDataTip(0x0, STR_MESSAGE_HISTORY_TOOLTIP), SetResize(1, 12), SetScrollbar(WID_MH_SCROLLBAR),
1108 EndContainer(),
1109 NWidget(NWID_VERTICAL),
1110 NWidget(NWID_VSCROLLBAR, COLOUR_BROWN, WID_MH_SCROLLBAR),
1111 NWidget(WWT_RESIZEBOX, COLOUR_BROWN),
1112 EndContainer(),
1113 EndContainer(),
1116 static WindowDesc _message_history_desc(
1117 WDP_AUTO, "list_news", 400, 140,
1118 WC_MESSAGE_HISTORY, WC_NONE,
1120 _nested_message_history, lengthof(_nested_message_history)
1123 /** Display window with news messages history */
1124 void ShowMessageHistory()
1126 DeleteWindowById(WC_MESSAGE_HISTORY, 0);
1127 new MessageHistoryWindow(&_message_history_desc);