Fix crash when setting separation mode for vehicles with no orders list.
[openttd-joker.git] / src / graph_gui.cpp
blob5d3090a414c5ff900531817048aaeabc22e7d76a
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 graph_gui.cpp GUI that shows performance graphs. */
12 #include "stdafx.h"
13 #include "graph_gui.h"
14 #include "window_gui.h"
15 #include "company_base.h"
16 #include "company_gui.h"
17 #include "economy_func.h"
18 #include "cargotype.h"
19 #include "strings_func.h"
20 #include "window_func.h"
21 #include "date_func.h"
22 #include "gfx_func.h"
23 #include "sortlist_type.h"
24 #include "core/geometry_func.hpp"
25 #include "currency.h"
27 #include "widgets/graph_widget.h"
29 #include "table/strings.h"
30 #include "table/sprites.h"
31 #include <math.h>
33 #include "safeguards.h"
35 /* Bitmasks of company and cargo indices that shouldn't be drawn. */
36 static uint _legend_excluded_companies;
37 static uint _legend_excluded_cargo;
39 /* Apparently these don't play well with enums. */
40 static const OverflowSafeInt64 INVALID_DATAPOINT(INT64_MAX); // Value used for a datapoint that shouldn't be drawn.
41 static const uint INVALID_DATAPOINT_POS = UINT_MAX; // Used to determine if the previous point was drawn.
43 /****************/
44 /* GRAPH LEGEND */
45 /****************/
47 struct GraphLegendWindow : Window {
48 GraphLegendWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
50 this->InitNested(window_number);
52 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
53 if (!HasBit(_legend_excluded_companies, c)) this->LowerWidget(c + WID_GL_FIRST_COMPANY);
55 this->OnInvalidateData(c);
59 virtual void DrawWidget(const Rect &r, int widget) const
61 if (!IsInsideMM(widget, WID_GL_FIRST_COMPANY, MAX_COMPANIES + WID_GL_FIRST_COMPANY)) return;
63 CompanyID cid = (CompanyID)(widget - WID_GL_FIRST_COMPANY);
65 if (!Company::IsValidID(cid)) return;
67 bool rtl = _current_text_dir == TD_RTL;
69 Dimension d = GetSpriteSize(SPR_COMPANY_ICON);
70 DrawCompanyIcon(cid, rtl ? r.right - d.width - 2 : r.left + 2, r.top + (r.bottom - r.top - d.height) / 2);
72 SetDParam(0, cid);
73 SetDParam(1, cid);
74 DrawString(r.left + (rtl ? (uint)WD_FRAMERECT_LEFT : (d.width + 4)), r.right - (rtl ? (d.width + 4) : (uint)WD_FRAMERECT_RIGHT), r.top + (r.bottom - r.top + 1 - FONT_HEIGHT_NORMAL) / 2, STR_COMPANY_NAME_COMPANY_NUM, HasBit(_legend_excluded_companies, cid) ? TC_BLACK : TC_WHITE);
77 virtual void OnClick(Point pt, int widget, int click_count)
79 if (!IsInsideMM(widget, WID_GL_FIRST_COMPANY, MAX_COMPANIES + WID_GL_FIRST_COMPANY)) return;
81 ToggleBit(_legend_excluded_companies, widget - WID_GL_FIRST_COMPANY);
82 this->ToggleWidgetLoweredState(widget);
83 this->SetDirty();
84 InvalidateWindowData(WC_INCOME_GRAPH, 0);
85 InvalidateWindowData(WC_OPERATING_PROFIT, 0);
86 InvalidateWindowData(WC_DELIVERED_CARGO, 0);
87 InvalidateWindowData(WC_PERFORMANCE_HISTORY, 0);
88 InvalidateWindowData(WC_COMPANY_VALUE, 0);
91 /**
92 * Some data on this window has become invalid.
93 * @param data Information about the changed data.
94 * @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.
96 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
98 if (!gui_scope) return;
99 if (Company::IsValidID(data)) return;
101 SetBit(_legend_excluded_companies, data);
102 this->RaiseWidget(data + WID_GL_FIRST_COMPANY);
107 * Construct a vertical list of buttons, one for each company.
108 * @param biggest_index Storage for collecting the biggest index used in the returned tree.
109 * @return Panel with company buttons.
110 * @post \c *biggest_index contains the largest used index in the tree.
112 static NWidgetBase *MakeNWidgetCompanyLines(int *biggest_index)
114 NWidgetVertical *vert = new NWidgetVertical();
115 uint line_height = max<uint>(GetSpriteSize(SPR_COMPANY_ICON).height, FONT_HEIGHT_NORMAL) + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
117 for (int widnum = WID_GL_FIRST_COMPANY; widnum <= WID_GL_LAST_COMPANY; widnum++) {
118 NWidgetBackground *panel = new NWidgetBackground(WWT_PANEL, COLOUR_GREY, widnum);
119 panel->SetMinimalSize(246, line_height);
120 panel->SetFill(1, 0);
121 panel->SetDataTip(0x0, STR_GRAPH_KEY_COMPANY_SELECTION_TOOLTIP);
122 vert->Add(panel);
124 *biggest_index = WID_GL_LAST_COMPANY;
125 return vert;
128 static const NWidgetPart _nested_graph_legend_widgets[] = {
129 NWidget(NWID_HORIZONTAL),
130 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
131 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_GRAPH_KEY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
132 NWidget(WWT_SHADEBOX, COLOUR_GREY),
133 NWidget(WWT_STICKYBOX, COLOUR_GREY),
134 EndContainer(),
135 NWidget(WWT_PANEL, COLOUR_GREY, WID_GL_BACKGROUND),
136 NWidget(NWID_SPACER), SetMinimalSize(0, 2),
137 NWidget(NWID_HORIZONTAL),
138 NWidget(NWID_SPACER), SetMinimalSize(2, 0),
139 NWidgetFunction(MakeNWidgetCompanyLines),
140 NWidget(NWID_SPACER), SetMinimalSize(2, 0),
141 EndContainer(),
142 EndContainer(),
145 static WindowDesc _graph_legend_desc(
146 WDP_AUTO, "graph_legend", 0, 0,
147 WC_GRAPH_LEGEND, WC_NONE,
149 _nested_graph_legend_widgets, lengthof(_nested_graph_legend_widgets)
152 static void ShowGraphLegend()
154 AllocateWindowDescFront<GraphLegendWindow>(&_graph_legend_desc, 0);
157 /** Contains the interval of a graph's data. */
158 struct ValuesInterval {
159 OverflowSafeInt64 highest; ///< Highest value of this interval. Must be zero or greater.
160 OverflowSafeInt64 lowest; ///< Lowest value of this interval. Must be zero or less.
163 /******************/
164 /* BASE OF GRAPHS */
165 /*****************/
167 struct BaseGraphWindow : Window {
168 protected:
169 static const int GRAPH_MAX_DATASETS = 32;
170 static const int GRAPH_AXIS_LINE_COLOUR = PC_BLACK;
171 static const int GRAPH_NUM_MONTHS = 24; ///< Number of months displayed in the graph.
173 static const int MIN_GRAPH_NUM_LINES_Y = 9; ///< Minimal number of horizontal lines to draw.
174 static const int MIN_GRID_PIXEL_SIZE = 20; ///< Minimum distance between graph lines.
176 uint excluded_data; ///< bitmask of the datasets that shouldn't be displayed.
177 byte num_dataset;
178 byte num_on_x_axis;
179 byte num_vert_lines;
180 static const TextColour graph_axis_label_colour = TC_BLACK; ///< colour of the graph axis label.
182 /* The starting month and year that values are plotted against. If month is
183 * 0xFF, use x_values_start and x_values_increment below instead. */
184 byte month;
185 Year year;
187 /* These values are used if the graph is being plotted against values
188 * rather than the dates specified by month and year. */
189 uint16 x_values_start;
190 uint16 x_values_increment;
192 int graph_widget;
193 StringID format_str_y_axis;
194 byte colours[GRAPH_MAX_DATASETS];
195 OverflowSafeInt64 cost[GRAPH_MAX_DATASETS][GRAPH_NUM_MONTHS]; ///< Stored costs for the last #GRAPH_NUM_MONTHS months
198 * Get the interval that contains the graph's data. Excluded data is ignored to show smaller values in
199 * better detail when disabling higher ones.
200 * @param num_hori_lines Number of horizontal lines to be drawn.
201 * @return Highest and lowest values of the graph (ignoring disabled data).
203 ValuesInterval GetValuesInterval(int num_hori_lines) const
205 assert(num_hori_lines > 0);
207 ValuesInterval current_interval;
208 current_interval.highest = INT64_MIN;
209 current_interval.lowest = INT64_MAX;
211 for (int i = 0; i < this->num_dataset; i++) {
212 if (HasBit(this->excluded_data, i)) continue;
213 for (int j = 0; j < this->num_on_x_axis; j++) {
214 OverflowSafeInt64 datapoint = this->cost[i][j];
216 if (datapoint != INVALID_DATAPOINT) {
217 current_interval.highest = max(current_interval.highest, datapoint);
218 current_interval.lowest = min(current_interval.lowest, datapoint);
223 /* Prevent showing values too close to the graph limits. */
224 current_interval.highest = (11 * current_interval.highest) / 10;
225 current_interval.lowest = (11 * current_interval.lowest) / 10;
227 /* Always include zero in the shown range. */
228 double abs_lower = (current_interval.lowest > 0) ? 0 : (double)abs(current_interval.lowest);
229 double abs_higher = (current_interval.highest < 0) ? 0 : (double)current_interval.highest;
231 int num_pos_grids;
232 int64 grid_size;
234 if (abs_lower != 0 || abs_higher != 0) {
235 /* The number of grids to reserve for the positive part is: */
236 num_pos_grids = (int)floor(0.5 + num_hori_lines * abs_higher / (abs_higher + abs_lower));
238 /* If there are any positive or negative values, force that they have at least one grid. */
239 if (num_pos_grids == 0 && abs_higher != 0) num_pos_grids++;
240 if (num_pos_grids == num_hori_lines && abs_lower != 0) num_pos_grids--;
242 /* Get the required grid size for each side and use the maximum one. */
243 int64 grid_size_higher = (abs_higher > 0) ? ((int64)abs_higher + num_pos_grids - 1) / num_pos_grids : 0;
244 int64 grid_size_lower = (abs_lower > 0) ? ((int64)abs_lower + num_hori_lines - num_pos_grids - 1) / (num_hori_lines - num_pos_grids) : 0;
245 grid_size = max(grid_size_higher, grid_size_lower);
246 } else {
247 /* If both values are zero, show an empty graph. */
248 num_pos_grids = num_hori_lines / 2;
249 grid_size = 1;
252 current_interval.highest = num_pos_grids * grid_size;
253 current_interval.lowest = -(num_hori_lines - num_pos_grids) * grid_size;
254 return current_interval;
258 * Get width for Y labels.
259 * @param current_interval Interval that contains all of the graph data.
260 * @param num_hori_lines Number of horizontal lines to be drawn.
262 uint GetYLabelWidth(ValuesInterval current_interval, int num_hori_lines) const
264 /* draw text strings on the y axis */
265 int64 y_label = current_interval.highest;
266 int64 y_label_separation = (current_interval.highest - current_interval.lowest) / num_hori_lines;
268 uint max_width = 0;
270 for (int i = 0; i < (num_hori_lines + 1); i++) {
271 SetDParam(0, this->format_str_y_axis);
272 SetDParam(1, y_label);
273 Dimension d = GetStringBoundingBox(STR_GRAPH_Y_LABEL);
274 if (d.width > max_width) max_width = d.width;
276 y_label -= y_label_separation;
279 return max_width;
283 * Actually draw the graph.
284 * @param r the rectangle of the data field of the graph
286 void DrawGraph(Rect r) const
288 uint x, y; ///< Reused whenever x and y coordinates are needed.
289 ValuesInterval interval; ///< Interval that contains all of the graph data.
290 int x_axis_offset; ///< Distance from the top of the graph to the x axis.
292 /* the colours and cost array of GraphDrawer must accommodate
293 * both values for cargo and companies. So if any are higher, quit */
294 assert_compile(GRAPH_MAX_DATASETS >= (int)NUM_CARGO && GRAPH_MAX_DATASETS >= (int)MAX_COMPANIES);
295 assert(this->num_vert_lines > 0);
297 byte grid_colour = _colour_gradient[COLOUR_GREY][4];
299 /* Rect r will be adjusted to contain just the graph, with labels being
300 * placed outside the area. */
301 r.top += 5 + GetCharacterHeight(FS_SMALL) / 2;
302 r.bottom -= (this->month == 0xFF ? 1 : 3) * GetCharacterHeight(FS_SMALL) + 4;
303 r.left += 9;
304 r.right -= 5;
306 /* Initial number of horizontal lines. */
307 int num_hori_lines = 160 / MIN_GRID_PIXEL_SIZE;
308 /* For the rest of the height, the number of horizontal lines will increase more slowly. */
309 int resize = (r.bottom - r.top - 160) / (2 * MIN_GRID_PIXEL_SIZE);
310 if (resize > 0) num_hori_lines += resize;
312 interval = GetValuesInterval(num_hori_lines);
314 int label_width = GetYLabelWidth(interval, num_hori_lines);
316 r.left += label_width;
318 int x_sep = (r.right - r.left) / this->num_vert_lines;
319 int y_sep = (r.bottom - r.top) / num_hori_lines;
321 /* Redetermine right and bottom edge of graph to fit with the integer
322 * separation values. */
323 r.right = r.left + x_sep * this->num_vert_lines;
324 r.bottom = r.top + y_sep * num_hori_lines;
326 OverflowSafeInt64 interval_size = interval.highest + abs(interval.lowest);
327 /* Where to draw the X axis. Use floating point to avoid overflowing and results of zero. */
328 x_axis_offset = (int)((r.bottom - r.top) * (double)interval.highest / (double)interval_size);
330 /* Draw the vertical grid lines. */
332 /* Don't draw the first line, as that's where the axis will be. */
333 x = r.left + x_sep;
335 for (int i = 0; i < this->num_vert_lines; i++) {
336 GfxFillRect(x, r.top, x, r.bottom, grid_colour);
337 x += x_sep;
340 /* Draw the horizontal grid lines. */
341 y = r.bottom;
343 for (int i = 0; i < (num_hori_lines + 1); i++) {
344 GfxFillRect(r.left - 3, y, r.left - 1, y, GRAPH_AXIS_LINE_COLOUR);
345 GfxFillRect(r.left, y, r.right, y, grid_colour);
346 y -= y_sep;
349 /* Draw the y axis. */
350 GfxFillRect(r.left, r.top, r.left, r.bottom, GRAPH_AXIS_LINE_COLOUR);
352 /* Draw the x axis. */
353 y = x_axis_offset + r.top;
354 GfxFillRect(r.left, y, r.right, y, GRAPH_AXIS_LINE_COLOUR);
356 /* Find the largest value that will be drawn. */
357 if (this->num_on_x_axis == 0) return;
359 assert(this->num_on_x_axis > 0);
360 assert(this->num_dataset > 0);
362 /* draw text strings on the y axis */
363 int64 y_label = interval.highest;
364 int64 y_label_separation = abs(interval.highest - interval.lowest) / num_hori_lines;
366 y = r.top - GetCharacterHeight(FS_SMALL) / 2;
368 for (int i = 0; i < (num_hori_lines + 1); i++) {
369 SetDParam(0, this->format_str_y_axis);
370 SetDParam(1, y_label);
371 DrawString(r.left - label_width - 4, r.left - 4, y, STR_GRAPH_Y_LABEL, graph_axis_label_colour, SA_RIGHT);
373 y_label -= y_label_separation;
374 y += y_sep;
377 /* draw strings on the x axis */
378 if (this->month != 0xFF) {
379 x = r.left;
380 y = r.bottom + 2;
381 byte month = this->month;
382 Year year = this->year;
383 for (int i = 0; i < this->num_on_x_axis; i++) {
384 SetDParam(0, month + STR_MONTH_ABBREV_JAN);
385 SetDParam(1, month + STR_MONTH_ABBREV_JAN + 2);
386 SetDParam(2, year);
387 DrawStringMultiLine(x, x + x_sep, y, this->height, month == 0 ? STR_GRAPH_X_LABEL_MONTH_YEAR : STR_GRAPH_X_LABEL_MONTH, graph_axis_label_colour);
389 month += 3;
390 if (month >= 12) {
391 month = 0;
392 year++;
394 x += x_sep;
396 } else {
397 /* Draw the label under the data point rather than on the grid line. */
398 x = r.left;
399 y = r.bottom + 2;
400 uint16 label = this->x_values_start;
402 for (int i = 0; i < this->num_on_x_axis; i++) {
403 SetDParam(0, label);
404 DrawString(x + 1, x + x_sep - 1, y, STR_GRAPH_Y_LABEL_NUMBER, graph_axis_label_colour, SA_HOR_CENTER);
406 label += this->x_values_increment;
407 x += x_sep;
411 /* draw lines and dots */
412 uint linewidth = _settings_client.gui.graph_line_thickness;
413 uint pointoffs1 = (linewidth + 1) / 2;
414 uint pointoffs2 = linewidth + 1 - pointoffs1;
415 for (int i = 0; i < this->num_dataset; i++) {
416 if (!HasBit(this->excluded_data, i)) {
417 /* Centre the dot between the grid lines. */
418 x = r.left + (x_sep / 2);
420 byte colour = this->colours[i];
421 uint prev_x = INVALID_DATAPOINT_POS;
422 uint prev_y = INVALID_DATAPOINT_POS;
424 for (int j = 0; j < this->num_on_x_axis; j++) {
425 OverflowSafeInt64 datapoint = this->cost[i][j];
427 if (datapoint != INVALID_DATAPOINT) {
429 * Check whether we need to reduce the 'accuracy' of the
430 * datapoint value and the highest value to split overflows.
431 * And when 'drawing' 'one million' or 'one million and one'
432 * there is no significant difference, so the least
433 * significant bits can just be removed.
435 * If there are more bits needed than would fit in a 32 bits
436 * integer, so at about 31 bits because of the sign bit, the
437 * least significant bits are removed.
439 int mult_range = FindLastBit(x_axis_offset) + FindLastBit(abs(datapoint));
440 int reduce_range = max(mult_range - 31, 0);
442 /* Handle negative values differently (don't shift sign) */
443 if (datapoint < 0) {
444 datapoint = -(abs(datapoint) >> reduce_range);
445 } else {
446 datapoint >>= reduce_range;
448 y = r.top + x_axis_offset - ((r.bottom - r.top) * datapoint) / (interval_size >> reduce_range);
450 /* Draw the point. */
451 GfxFillRect(x - pointoffs1, y - pointoffs1, x + pointoffs2, y + pointoffs2, colour);
453 /* Draw the line connected to the previous point. */
454 if (prev_x != INVALID_DATAPOINT_POS) GfxDrawLine(prev_x, prev_y, x, y, colour, linewidth);
456 prev_x = x;
457 prev_y = y;
458 } else {
459 prev_x = INVALID_DATAPOINT_POS;
460 prev_y = INVALID_DATAPOINT_POS;
463 x += x_sep;
470 BaseGraphWindow(WindowDesc *desc, int widget, StringID format_str_y_axis) :
471 Window(desc),
472 format_str_y_axis(format_str_y_axis)
474 SetWindowDirty(WC_GRAPH_LEGEND, 0);
475 this->num_vert_lines = 24;
476 this->graph_widget = widget;
479 void InitializeWindow(WindowNumber number)
481 /* Initialise the dataset */
482 this->UpdateStatistics(true);
484 this->InitNested(number);
487 public:
488 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
490 if (widget != this->graph_widget) return;
492 uint x_label_width = 0;
494 if (this->month != 0xFF) {
495 byte month = this->month;
496 Year year = this->year;
497 for (int i = 0; i < this->num_on_x_axis; i++) {
498 SetDParam(0, month + STR_MONTH_ABBREV_JAN);
499 SetDParam(1, month + STR_MONTH_ABBREV_JAN + 2);
500 SetDParam(2, year);
501 x_label_width = max(x_label_width, GetStringBoundingBox(month == 0 ? STR_GRAPH_X_LABEL_MONTH_YEAR : STR_GRAPH_X_LABEL_MONTH).width);
503 month += 3;
504 if (month >= 12) {
505 month = 0;
506 year++;
509 } else {
510 /* Draw the label under the data point rather than on the grid line. */
511 SetDParamMaxValue(0, this->x_values_start + this->num_on_x_axis * this->x_values_increment, 0, FS_SMALL);
512 x_label_width = GetStringBoundingBox(STR_GRAPH_Y_LABEL_NUMBER).width;
515 SetDParam(0, this->format_str_y_axis);
516 SetDParam(1, INT64_MAX);
517 uint y_label_width = GetStringBoundingBox(STR_GRAPH_Y_LABEL).width;
519 size->width = max<uint>(size->width, 5 + y_label_width + this->num_on_x_axis * (x_label_width + 5) + 9);
520 size->height = max<uint>(size->height, 5 + (1 + MIN_GRAPH_NUM_LINES_Y * 2 + (this->month != 0xFF ? 3 : 1)) * FONT_HEIGHT_SMALL + 4);
521 size->height = max<uint>(size->height, size->width / 3);
524 virtual void DrawWidget(const Rect &r, int widget) const
526 if (widget != this->graph_widget) return;
528 DrawGraph(r);
531 virtual OverflowSafeInt64 GetGraphData(const Company *c, int j)
533 return INVALID_DATAPOINT;
536 virtual void OnClick(Point pt, int widget, int click_count)
538 /* Clicked on legend? */
539 if (widget == WID_CV_KEY_BUTTON) ShowGraphLegend();
542 virtual void OnTick()
544 this->UpdateStatistics(false);
548 * Some data on this window has become invalid.
549 * @param data Information about the changed data.
550 * @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.
552 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
554 if (!gui_scope) return;
555 this->UpdateStatistics(true);
559 * Update the statistics.
560 * @param initialize Initialize the data structure.
562 void UpdateStatistics(bool initialize)
564 uint excluded_companies = _legend_excluded_companies;
566 /* Exclude the companies which aren't valid */
567 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
568 if (!Company::IsValidID(c)) SetBit(excluded_companies, c);
571 byte nums = 0;
572 const Company *c;
573 FOR_ALL_COMPANIES(c) {
574 nums = min(this->num_vert_lines, max(nums, c->num_valid_stat_ent));
577 int mo = (_cur_month / 3 - nums) * 3;
578 int yr = _cur_year;
579 while (mo < 0) {
580 yr--;
581 mo += 12;
584 if (!initialize && this->excluded_data == excluded_companies && this->num_on_x_axis == nums &&
585 this->year == yr && this->month == mo) {
586 /* There's no reason to get new stats */
587 return;
590 this->excluded_data = excluded_companies;
591 this->num_on_x_axis = nums;
592 this->year = yr;
593 this->month = mo;
595 int numd = 0;
596 for (CompanyID k = COMPANY_FIRST; k < MAX_COMPANIES; k++) {
597 c = Company::GetIfValid(k);
598 if (c != nullptr) {
599 this->colours[numd] = _colour_gradient[c->colour][6];
600 for (int j = this->num_on_x_axis, i = 0; --j >= 0;) {
601 this->cost[numd][i] = (j >= c->num_valid_stat_ent) ? INVALID_DATAPOINT : GetGraphData(c, j);
602 i++;
605 numd++;
608 this->num_dataset = numd;
613 /********************/
614 /* OPERATING PROFIT */
615 /********************/
617 struct OperatingProfitGraphWindow : BaseGraphWindow {
618 OperatingProfitGraphWindow(WindowDesc *desc, WindowNumber window_number) :
619 BaseGraphWindow(desc, WID_CV_GRAPH, STR_JUST_CURRENCY_SHORT)
621 this->InitializeWindow(window_number);
624 virtual OverflowSafeInt64 GetGraphData(const Company *c, int j)
626 return c->old_economy[j].income + c->old_economy[j].expenses;
630 static const NWidgetPart _nested_operating_profit_widgets[] = {
631 NWidget(NWID_HORIZONTAL),
632 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
633 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_GRAPH_OPERATING_PROFIT_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
634 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_CV_KEY_BUTTON), SetMinimalSize(50, 0), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetDataTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
635 NWidget(WWT_SHADEBOX, COLOUR_GREY),
636 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
637 NWidget(WWT_STICKYBOX, COLOUR_GREY),
638 EndContainer(),
639 NWidget(WWT_PANEL, COLOUR_GREY, WID_CV_BACKGROUND),
640 NWidget(NWID_HORIZONTAL),
641 NWidget(WWT_EMPTY, COLOUR_GREY, WID_CV_GRAPH), SetMinimalSize(576, 160), SetFill(1, 1), SetResize(1, 1),
642 NWidget(NWID_VERTICAL),
643 NWidget(NWID_SPACER), SetFill(0, 1), SetResize(0, 1),
644 NWidget(WWT_RESIZEBOX, COLOUR_GREY, WID_CV_RESIZE),
645 EndContainer(),
646 EndContainer(),
647 EndContainer(),
650 static WindowDesc _operating_profit_desc(
651 WDP_AUTO, "graph_operating_profit", 0, 0,
652 WC_OPERATING_PROFIT, WC_NONE,
654 _nested_operating_profit_widgets, lengthof(_nested_operating_profit_widgets)
658 void ShowOperatingProfitGraph()
660 AllocateWindowDescFront<OperatingProfitGraphWindow>(&_operating_profit_desc, 0);
664 /****************/
665 /* INCOME GRAPH */
666 /****************/
668 struct IncomeGraphWindow : BaseGraphWindow {
669 IncomeGraphWindow(WindowDesc *desc, WindowNumber window_number) :
670 BaseGraphWindow(desc, WID_CV_GRAPH, STR_JUST_CURRENCY_SHORT)
672 this->InitializeWindow(window_number);
675 virtual OverflowSafeInt64 GetGraphData(const Company *c, int j)
677 return c->old_economy[j].income;
681 static const NWidgetPart _nested_income_graph_widgets[] = {
682 NWidget(NWID_HORIZONTAL),
683 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
684 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_GRAPH_INCOME_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
685 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_CV_KEY_BUTTON), SetMinimalSize(50, 0), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetDataTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
686 NWidget(WWT_SHADEBOX, COLOUR_GREY),
687 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
688 NWidget(WWT_STICKYBOX, COLOUR_GREY),
689 EndContainer(),
690 NWidget(WWT_PANEL, COLOUR_GREY, WID_CV_BACKGROUND),
691 NWidget(NWID_HORIZONTAL),
692 NWidget(WWT_EMPTY, COLOUR_GREY, WID_CV_GRAPH), SetMinimalSize(576, 128), SetFill(1, 1), SetResize(1, 1),
693 NWidget(NWID_VERTICAL),
694 NWidget(NWID_SPACER), SetFill(0, 1), SetResize(0, 1),
695 NWidget(WWT_RESIZEBOX, COLOUR_GREY, WID_CV_RESIZE),
696 EndContainer(),
697 EndContainer(),
698 EndContainer(),
701 static WindowDesc _income_graph_desc(
702 WDP_AUTO, "graph_income", 0, 0,
703 WC_INCOME_GRAPH, WC_NONE,
705 _nested_income_graph_widgets, lengthof(_nested_income_graph_widgets)
708 void ShowIncomeGraph()
710 AllocateWindowDescFront<IncomeGraphWindow>(&_income_graph_desc, 0);
713 /*******************/
714 /* DELIVERED CARGO */
715 /*******************/
717 struct DeliveredCargoGraphWindow : BaseGraphWindow {
718 DeliveredCargoGraphWindow(WindowDesc *desc, WindowNumber window_number) :
719 BaseGraphWindow(desc, WID_CV_GRAPH, STR_JUST_COMMA)
721 this->InitializeWindow(window_number);
724 virtual OverflowSafeInt64 GetGraphData(const Company *c, int j)
726 return c->old_economy[j].delivered_cargo.GetSum<OverflowSafeInt64>();
730 static const NWidgetPart _nested_delivered_cargo_graph_widgets[] = {
731 NWidget(NWID_HORIZONTAL),
732 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
733 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_GRAPH_CARGO_DELIVERED_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
734 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_CV_KEY_BUTTON), SetMinimalSize(50, 0), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetDataTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
735 NWidget(WWT_SHADEBOX, COLOUR_GREY),
736 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
737 NWidget(WWT_STICKYBOX, COLOUR_GREY),
738 EndContainer(),
739 NWidget(WWT_PANEL, COLOUR_GREY, WID_CV_BACKGROUND),
740 NWidget(NWID_HORIZONTAL),
741 NWidget(WWT_EMPTY, COLOUR_GREY, WID_CV_GRAPH), SetMinimalSize(576, 128), SetFill(1, 1), SetResize(1, 1),
742 NWidget(NWID_VERTICAL),
743 NWidget(NWID_SPACER), SetFill(0, 1), SetResize(0, 1),
744 NWidget(WWT_RESIZEBOX, COLOUR_GREY, WID_CV_RESIZE),
745 EndContainer(),
746 EndContainer(),
747 EndContainer(),
750 static WindowDesc _delivered_cargo_graph_desc(
751 WDP_AUTO, "graph_delivered_cargo", 0, 0,
752 WC_DELIVERED_CARGO, WC_NONE,
754 _nested_delivered_cargo_graph_widgets, lengthof(_nested_delivered_cargo_graph_widgets)
757 void ShowDeliveredCargoGraph()
759 AllocateWindowDescFront<DeliveredCargoGraphWindow>(&_delivered_cargo_graph_desc, 0);
762 /***********************/
763 /* PERFORMANCE HISTORY */
764 /***********************/
766 struct PerformanceHistoryGraphWindow : BaseGraphWindow {
767 PerformanceHistoryGraphWindow(WindowDesc *desc, WindowNumber window_number) :
768 BaseGraphWindow(desc, WID_PHG_GRAPH, STR_JUST_COMMA)
770 this->InitializeWindow(window_number);
773 virtual OverflowSafeInt64 GetGraphData(const Company *c, int j)
775 return c->old_economy[j].performance_history;
778 virtual void OnClick(Point pt, int widget, int click_count)
780 if (widget == WID_PHG_DETAILED_PERFORMANCE) ShowPerformanceRatingDetail();
781 this->BaseGraphWindow::OnClick(pt, widget, click_count);
785 static const NWidgetPart _nested_performance_history_widgets[] = {
786 NWidget(NWID_HORIZONTAL),
787 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
788 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_GRAPH_COMPANY_PERFORMANCE_RATINGS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
789 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_PHG_DETAILED_PERFORMANCE), SetMinimalSize(50, 0), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetDataTip(STR_PERFORMANCE_DETAIL_KEY, STR_GRAPH_PERFORMANCE_DETAIL_TOOLTIP),
790 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_PHG_KEY), SetMinimalSize(50, 0), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetDataTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
791 NWidget(WWT_SHADEBOX, COLOUR_GREY),
792 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
793 NWidget(WWT_STICKYBOX, COLOUR_GREY),
794 EndContainer(),
795 NWidget(WWT_PANEL, COLOUR_GREY, WID_PHG_BACKGROUND),
796 NWidget(NWID_HORIZONTAL),
797 NWidget(WWT_EMPTY, COLOUR_GREY, WID_PHG_GRAPH), SetMinimalSize(576, 224), SetFill(1, 1), SetResize(1, 1),
798 NWidget(NWID_VERTICAL),
799 NWidget(NWID_SPACER), SetFill(0, 1), SetResize(0, 1),
800 NWidget(WWT_RESIZEBOX, COLOUR_GREY, WID_PHG_RESIZE),
801 EndContainer(),
802 EndContainer(),
803 EndContainer(),
806 static WindowDesc _performance_history_desc(
807 WDP_AUTO, "graph_performance", 0, 0,
808 WC_PERFORMANCE_HISTORY, WC_NONE,
810 _nested_performance_history_widgets, lengthof(_nested_performance_history_widgets)
813 void ShowPerformanceHistoryGraph()
815 AllocateWindowDescFront<PerformanceHistoryGraphWindow>(&_performance_history_desc, 0);
818 /*****************/
819 /* COMPANY VALUE */
820 /*****************/
822 struct CompanyValueGraphWindow : BaseGraphWindow {
823 CompanyValueGraphWindow(WindowDesc *desc, WindowNumber window_number) :
824 BaseGraphWindow(desc, WID_CV_GRAPH, STR_JUST_CURRENCY_SHORT)
826 this->InitializeWindow(window_number);
829 virtual OverflowSafeInt64 GetGraphData(const Company *c, int j)
831 return c->old_economy[j].company_value;
835 static const NWidgetPart _nested_company_value_graph_widgets[] = {
836 NWidget(NWID_HORIZONTAL),
837 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
838 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_GRAPH_COMPANY_VALUES_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
839 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_CV_KEY_BUTTON), SetMinimalSize(50, 0), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetDataTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
840 NWidget(WWT_SHADEBOX, COLOUR_GREY),
841 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
842 NWidget(WWT_STICKYBOX, COLOUR_GREY),
843 EndContainer(),
844 NWidget(WWT_PANEL, COLOUR_GREY, WID_CV_BACKGROUND),
845 NWidget(NWID_HORIZONTAL),
846 NWidget(WWT_EMPTY, COLOUR_GREY, WID_CV_GRAPH), SetMinimalSize(576, 224), SetFill(1, 1), SetResize(1, 1),
847 NWidget(NWID_VERTICAL),
848 NWidget(NWID_SPACER), SetFill(0, 1), SetResize(0, 1),
849 NWidget(WWT_RESIZEBOX, COLOUR_GREY, WID_CV_RESIZE),
850 EndContainer(),
851 EndContainer(),
852 EndContainer(),
855 static WindowDesc _company_value_graph_desc(
856 WDP_AUTO, "graph_company_value", 0, 0,
857 WC_COMPANY_VALUE, WC_NONE,
859 _nested_company_value_graph_widgets, lengthof(_nested_company_value_graph_widgets)
862 void ShowCompanyValueGraph()
864 AllocateWindowDescFront<CompanyValueGraphWindow>(&_company_value_graph_desc, 0);
867 /*****************/
868 /* PAYMENT RATES */
869 /*****************/
871 struct PaymentRatesGraphWindow : BaseGraphWindow {
872 bool first_init; ///< This value is true until the first initialization of the window has finished.
873 PaymentRatesGraphWindow(WindowDesc *desc, WindowNumber window_number) :
874 BaseGraphWindow(desc, WID_CPR_GRAPH, STR_JUST_CURRENCY_SHORT)
876 this->first_init = true;
877 this->num_on_x_axis = 20;
878 this->num_vert_lines = 20;
879 this->month = 0xFF;
880 this->x_values_start = 10;
881 this->x_values_increment = 10;
883 /* Initialise the dataset */
884 this->OnHundredthTick();
886 this->InitNested(window_number);
888 this->UpdateLoweredWidgets();
891 virtual void OnInit()
893 /* UpdateLoweredWidgets needs to be called after a language or NewGRF change, but it can't be called before
894 * InitNested is done. On the first init these functions are called in the correct order by the constructor. */
895 if (!this->first_init) {
896 /* Initialise the dataset */
897 this->OnHundredthTick();
898 this->UpdateLoweredWidgets();
900 this->first_init = false;
903 void UpdateExcludedData()
905 this->excluded_data = 0;
907 int i = 0;
908 const CargoSpec *cs;
909 FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
910 if (HasBit(_legend_excluded_cargo, cs->Index())) SetBit(this->excluded_data, i);
911 i++;
915 void UpdateLoweredWidgets()
917 for (int i = 0; i < _sorted_standard_cargo_specs_size; i++) {
918 this->SetWidgetLoweredState(WID_CPR_CARGO_FIRST + i, !HasBit(this->excluded_data, i));
922 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
924 if (widget < WID_CPR_CARGO_FIRST) {
925 BaseGraphWindow::UpdateWidgetSize(widget, size, padding, fill, resize);
926 return;
929 const CargoSpec *cs = _sorted_cargo_specs[widget - WID_CPR_CARGO_FIRST];
930 SetDParam(0, cs->name);
931 Dimension d = GetStringBoundingBox(STR_GRAPH_CARGO_PAYMENT_CARGO);
932 d.width += 14; // colour field
933 d.width += WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
934 d.height += WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
935 *size = maxdim(d, *size);
938 virtual void DrawWidget(const Rect &r, int widget) const
940 if (widget < WID_CPR_CARGO_FIRST) {
941 BaseGraphWindow::DrawWidget(r, widget);
942 return;
945 const CargoSpec *cs = _sorted_cargo_specs[widget - WID_CPR_CARGO_FIRST];
946 bool rtl = _current_text_dir == TD_RTL;
948 /* Since the buttons have no text, no images,
949 * both the text and the coloured box have to be manually painted.
950 * clk_dif will move one pixel down and one pixel to the right
951 * when the button is clicked */
952 byte clk_dif = this->IsWidgetLowered(widget) ? 1 : 0;
953 int x = r.left + WD_FRAMERECT_LEFT;
954 int y = r.top;
956 int rect_x = clk_dif + (rtl ? r.right - 12 : r.left + WD_FRAMERECT_LEFT);
958 GfxFillRect(rect_x, y + clk_dif, rect_x + 8, y + 5 + clk_dif, PC_BLACK);
959 GfxFillRect(rect_x + 1, y + 1 + clk_dif, rect_x + 7, y + 4 + clk_dif, cs->legend_colour);
960 SetDParam(0, cs->name);
961 DrawString(rtl ? r.left : x + 14 + clk_dif, (rtl ? r.right - 14 + clk_dif : r.right), y + clk_dif, STR_GRAPH_CARGO_PAYMENT_CARGO);
964 virtual void OnClick(Point pt, int widget, int click_count)
966 switch (widget) {
967 case WID_CPR_ENABLE_CARGOES:
968 /* Remove all cargoes from the excluded lists. */
969 _legend_excluded_cargo = 0;
970 this->excluded_data = 0;
971 this->UpdateLoweredWidgets();
972 this->SetDirty();
973 break;
975 case WID_CPR_DISABLE_CARGOES: {
976 /* Add all cargoes to the excluded lists. */
977 int i = 0;
978 const CargoSpec *cs;
979 FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
980 SetBit(_legend_excluded_cargo, cs->Index());
981 SetBit(this->excluded_data, i);
982 i++;
984 this->UpdateLoweredWidgets();
985 this->SetDirty();
986 break;
989 default:
990 if (widget >= WID_CPR_CARGO_FIRST) {
991 int i = widget - WID_CPR_CARGO_FIRST;
992 ToggleBit(_legend_excluded_cargo, _sorted_cargo_specs[i]->Index());
993 this->ToggleWidgetLoweredState(widget);
994 this->UpdateExcludedData();
995 this->SetDirty();
997 break;
1001 virtual void OnTick()
1003 /* Override default OnTick */
1007 * Some data on this window has become invalid.
1008 * @param data Information about the changed data.
1009 * @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.
1011 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
1013 if (!gui_scope) return;
1014 this->OnHundredthTick();
1017 virtual void OnHundredthTick()
1019 this->UpdateExcludedData();
1021 int i = 0;
1022 const CargoSpec *cs;
1023 byte ctt = 0; //cargo transfer time a 200 tile
1024 const float factor = 200.0f * 28.57f * 0.4f;
1025 FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
1026 this->colours[i] = cs->legend_colour;
1027 // velocity instead of time
1028 for (uint j = 0; j != 20; j++) {
1029 ctt = (byte)(factor / ((j + 1)*10.0f)); //200*28.57*0.4/V, V=10*j
1030 this->cost[i][j] = GetTransportedGoodsIncome(1, 200, ctt, cs->Index());
1032 i++;
1034 this->num_dataset = i;
1038 /** Construct the row containing the digit keys. */
1039 static NWidgetBase *MakeCargoButtons(int *biggest_index)
1041 NWidgetVertical *ver = new NWidgetVertical;
1043 for (int i = 0; i < _sorted_standard_cargo_specs_size; i++) {
1044 NWidgetBackground *leaf = new NWidgetBackground(WWT_PANEL, COLOUR_ORANGE, WID_CPR_CARGO_FIRST + i, nullptr);
1045 leaf->tool_tip = STR_GRAPH_CARGO_PAYMENT_TOGGLE_CARGO;
1046 leaf->SetFill(1, 0);
1047 leaf->SetLowered(true);
1048 ver->Add(leaf);
1050 *biggest_index = WID_CPR_CARGO_FIRST + _sorted_standard_cargo_specs_size - 1;
1051 return ver;
1055 static const NWidgetPart _nested_cargo_payment_rates_widgets[] = {
1056 NWidget(NWID_HORIZONTAL),
1057 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1058 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_GRAPH_CARGO_PAYMENT_RATES_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1059 NWidget(WWT_SHADEBOX, COLOUR_GREY),
1060 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
1061 NWidget(WWT_STICKYBOX, COLOUR_GREY),
1062 EndContainer(),
1063 NWidget(WWT_PANEL, COLOUR_GREY, WID_CPR_BACKGROUND), SetMinimalSize(568, 128),
1064 NWidget(NWID_HORIZONTAL),
1065 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
1066 NWidget(WWT_TEXT, COLOUR_GREY, WID_CPR_HEADER), SetMinimalSize(0, 6), SetPadding(2, 0, 2, 0), SetDataTip(STR_GRAPH_CARGO_PAYMENT_RATES_TITLE, STR_NULL),
1067 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
1068 EndContainer(),
1069 NWidget(NWID_HORIZONTAL),
1070 NWidget(WWT_EMPTY, COLOUR_GREY, WID_CPR_GRAPH), SetMinimalSize(495, 0), SetFill(1, 1), SetResize(1, 1),
1071 NWidget(NWID_VERTICAL),
1072 NWidget(NWID_SPACER), SetMinimalSize(0, 24), SetFill(0, 0), SetResize(0, 1),
1073 NWidget(WWT_PUSHTXTBTN, COLOUR_ORANGE, WID_CPR_ENABLE_CARGOES), SetDataTip(STR_GRAPH_CARGO_ENABLE_ALL, STR_GRAPH_CARGO_TOOLTIP_ENABLE_ALL), SetFill(1, 0),
1074 NWidget(WWT_PUSHTXTBTN, COLOUR_ORANGE, WID_CPR_DISABLE_CARGOES), SetDataTip(STR_GRAPH_CARGO_DISABLE_ALL, STR_GRAPH_CARGO_TOOLTIP_DISABLE_ALL), SetFill(1, 0),
1075 NWidget(NWID_SPACER), SetMinimalSize(0, 4),
1076 NWidgetFunction(MakeCargoButtons),
1077 NWidget(NWID_SPACER), SetMinimalSize(0, 24), SetFill(0, 1), SetResize(0, 1),
1078 EndContainer(),
1079 NWidget(NWID_SPACER), SetMinimalSize(5, 0), SetFill(0, 1), SetResize(0, 1),
1080 EndContainer(),
1081 NWidget(NWID_HORIZONTAL),
1082 NWidget(NWID_SPACER), SetMinimalSize(WD_RESIZEBOX_WIDTH, 0), SetFill(1, 0), SetResize(1, 0),
1083 NWidget(WWT_TEXT, COLOUR_GREY, WID_CPR_FOOTER), SetMinimalSize(0, 6), SetPadding(2, 0, 2, 0), SetDataTip(STR_GRAPH_CARGO_PAYMENT_RATES_X_LABEL, STR_NULL),
1084 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
1085 NWidget(WWT_RESIZEBOX, COLOUR_GREY, WID_CPR_RESIZE),
1086 EndContainer(),
1087 EndContainer(),
1090 static WindowDesc _cargo_payment_rates_desc(
1091 WDP_AUTO, "graph_cargo_payment_rates", 0, 0,
1092 WC_PAYMENT_RATES, WC_NONE,
1094 _nested_cargo_payment_rates_widgets, lengthof(_nested_cargo_payment_rates_widgets)
1098 void ShowCargoPaymentRates()
1100 AllocateWindowDescFront<PaymentRatesGraphWindow>(&_cargo_payment_rates_desc, 0);
1103 /************************/
1104 /* COMPANY LEAGUE TABLE */
1105 /************************/
1107 static const StringID _performance_titles[] = {
1108 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_ENGINEER,
1109 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_ENGINEER,
1110 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_TRAFFIC_MANAGER,
1111 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_TRAFFIC_MANAGER,
1112 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_TRANSPORT_COORDINATOR,
1113 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_TRANSPORT_COORDINATOR,
1114 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_ROUTE_SUPERVISOR,
1115 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_ROUTE_SUPERVISOR,
1116 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_DIRECTOR,
1117 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_DIRECTOR,
1118 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_CHIEF_EXECUTIVE,
1119 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_CHIEF_EXECUTIVE,
1120 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_CHAIRMAN,
1121 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_CHAIRMAN,
1122 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_PRESIDENT,
1123 STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_TYCOON,
1126 static inline StringID GetPerformanceTitleFromValue(uint value)
1128 return _performance_titles[minu(value, 1000) >> 6];
1131 class CompanyLeagueWindow : public Window {
1132 private:
1133 GUIList<const Company*> companies;
1134 uint ordinal_width; ///< The width of the ordinal number
1135 uint text_width; ///< The width of the actual text
1136 uint icon_width; ///< The width of the company icon
1137 int line_height; ///< Height of the text lines
1140 * (Re)Build the company league list
1142 void BuildCompanyList()
1144 if (!this->companies.NeedRebuild()) return;
1146 this->companies.Clear();
1148 const Company *c;
1149 FOR_ALL_COMPANIES(c) {
1150 *this->companies.Append() = c;
1153 this->companies.Compact();
1154 this->companies.RebuildDone();
1157 /** Sort the company league by performance history */
1158 static int CDECL PerformanceSorter(const Company * const *c1, const Company * const *c2)
1160 return (*c2)->old_economy[0].performance_history - (*c1)->old_economy[0].performance_history;
1163 public:
1164 CompanyLeagueWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
1166 this->InitNested(window_number);
1167 this->companies.ForceRebuild();
1168 this->companies.NeedResort();
1171 virtual void OnPaint()
1173 this->BuildCompanyList();
1174 this->companies.Sort(&PerformanceSorter);
1176 this->DrawWidgets();
1179 virtual void DrawWidget(const Rect &r, int widget) const
1181 if (widget != WID_CL_BACKGROUND) return;
1183 int icon_y_offset = 1 + (FONT_HEIGHT_NORMAL - this->line_height) / 2;
1184 uint y = r.top + WD_FRAMERECT_TOP - icon_y_offset;
1186 bool rtl = _current_text_dir == TD_RTL;
1187 uint ordinal_left = rtl ? r.right - WD_FRAMERECT_LEFT - this->ordinal_width : r.left + WD_FRAMERECT_LEFT;
1188 uint ordinal_right = rtl ? r.right - WD_FRAMERECT_LEFT : r.left + WD_FRAMERECT_LEFT + this->ordinal_width;
1189 uint icon_left = r.left + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT + (rtl ? this->text_width : this->ordinal_width);
1190 uint text_left = rtl ? r.left + WD_FRAMERECT_LEFT : r.right - WD_FRAMERECT_LEFT - this->text_width;
1191 uint text_right = rtl ? r.left + WD_FRAMERECT_LEFT + this->text_width : r.right - WD_FRAMERECT_LEFT;
1193 for (uint i = 0; i != this->companies.Length(); i++) {
1194 const Company *c = this->companies[i];
1195 DrawString(ordinal_left, ordinal_right, y, i + STR_ORDINAL_NUMBER_1ST, i == 0 ? TC_WHITE : TC_YELLOW);
1197 DrawCompanyIcon(c->index, icon_left, y + icon_y_offset);
1199 SetDParam(0, c->index);
1200 SetDParam(1, c->index);
1201 SetDParam(2, GetPerformanceTitleFromValue(c->old_economy[0].performance_history));
1202 DrawString(text_left, text_right, y, STR_COMPANY_LEAGUE_COMPANY_NAME);
1203 y += this->line_height;
1207 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
1209 if (widget != WID_CL_BACKGROUND) return;
1211 this->ordinal_width = 0;
1212 for (uint i = 0; i < MAX_COMPANIES; i++) {
1213 this->ordinal_width = max(this->ordinal_width, GetStringBoundingBox(STR_ORDINAL_NUMBER_1ST + i).width);
1215 this->ordinal_width += 5; // Keep some extra spacing
1217 uint widest_width = 0;
1218 uint widest_title = 0;
1219 for (uint i = 0; i < lengthof(_performance_titles); i++) {
1220 uint width = GetStringBoundingBox(_performance_titles[i]).width;
1221 if (width > widest_width) {
1222 widest_title = i;
1223 widest_width = width;
1227 Dimension d = GetSpriteSize(SPR_COMPANY_ICON);
1228 this->icon_width = d.width + 2;
1229 this->line_height = max<int>(d.height + 2, FONT_HEIGHT_NORMAL);
1231 const Company *c;
1232 FOR_ALL_COMPANIES(c) {
1233 SetDParam(0, c->index);
1234 SetDParam(1, c->index);
1235 SetDParam(2, _performance_titles[widest_title]);
1236 widest_width = max(widest_width, GetStringBoundingBox(STR_COMPANY_LEAGUE_COMPANY_NAME).width);
1239 this->text_width = widest_width + 30; // Keep some extra spacing
1241 size->width = WD_FRAMERECT_LEFT + this->ordinal_width + WD_FRAMERECT_RIGHT + this->icon_width + WD_FRAMERECT_LEFT + this->text_width + WD_FRAMERECT_RIGHT;
1242 size->height = WD_FRAMERECT_TOP + this->line_height * MAX_COMPANIES + WD_FRAMERECT_BOTTOM;
1246 virtual void OnTick()
1248 if (this->companies.NeedResort()) {
1249 this->SetDirty();
1254 * Some data on this window has become invalid.
1255 * @param data Information about the changed data.
1256 * @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.
1258 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
1260 if (data == 0) {
1261 /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
1262 this->companies.ForceRebuild();
1263 } else {
1264 this->companies.ForceResort();
1269 static const NWidgetPart _nested_company_league_widgets[] = {
1270 NWidget(NWID_HORIZONTAL),
1271 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1272 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_COMPANY_LEAGUE_TABLE_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1273 NWidget(WWT_SHADEBOX, COLOUR_GREY),
1274 NWidget(WWT_STICKYBOX, COLOUR_GREY),
1275 EndContainer(),
1276 NWidget(WWT_PANEL, COLOUR_GREY, WID_CL_BACKGROUND), SetMinimalSize(400, 0), SetMinimalTextLines(15, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM),
1279 static WindowDesc _company_league_desc(
1280 WDP_AUTO, "league", 0, 0,
1281 WC_COMPANY_LEAGUE, WC_NONE,
1283 _nested_company_league_widgets, lengthof(_nested_company_league_widgets)
1286 void ShowCompanyLeagueTable()
1288 AllocateWindowDescFront<CompanyLeagueWindow>(&_company_league_desc, 0);
1291 /*****************************/
1292 /* PERFORMANCE RATING DETAIL */
1293 /*****************************/
1295 struct PerformanceRatingDetailWindow : Window {
1296 static CompanyID company;
1297 int timeout;
1299 PerformanceRatingDetailWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
1301 this->UpdateCompanyStats();
1303 this->InitNested(window_number);
1304 this->OnInvalidateData(INVALID_COMPANY);
1307 void UpdateCompanyStats()
1309 /* Update all company stats with the current data
1310 * (this is because _score_info is not saved to a savegame) */
1311 Company *c;
1312 FOR_ALL_COMPANIES(c) {
1313 UpdateCompanyRatingAndValue(c, false);
1316 this->timeout = DAY_TICKS * 5;
1319 uint score_info_left;
1320 uint score_info_right;
1321 uint bar_left;
1322 uint bar_right;
1323 uint bar_width;
1324 uint bar_height;
1325 uint score_detail_left;
1326 uint score_detail_right;
1328 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
1330 switch (widget) {
1331 case WID_PRD_SCORE_FIRST:
1332 this->bar_height = FONT_HEIGHT_NORMAL + 4;
1333 size->height = this->bar_height + 2 * WD_MATRIX_TOP;
1335 uint score_info_width = 0;
1336 for (uint i = SCORE_BEGIN; i < SCORE_END; i++) {
1337 score_info_width = max(score_info_width, GetStringBoundingBox(STR_PERFORMANCE_DETAIL_VEHICLES + i).width);
1339 SetDParamMaxValue(0, 1000);
1340 score_info_width += GetStringBoundingBox(STR_BLACK_COMMA).width + WD_FRAMERECT_LEFT;
1342 SetDParamMaxValue(0, 100);
1343 this->bar_width = GetStringBoundingBox(STR_PERFORMANCE_DETAIL_PERCENT).width + 20; // Wide bars!
1345 /* At this number we are roughly at the max; it can become wider,
1346 * but then you need at 1000 times more money. At that time you're
1347 * not that interested anymore in the last few digits anyway.
1348 * The 500 is because 999 999 500 to 999 999 999 are rounded to
1349 * 1 000 M, and not 999 999 k. Use negative numbers to account for
1350 * the negative income/amount of money etc. as well. */
1351 int max = -(999999999 - 500);
1353 /* Scale max for the display currency. Prior to rendering the value
1354 * is converted into the display currency, which may cause it to
1355 * raise significantly. We need to compensate for that since {{CURRCOMPACT}}
1356 * is used, which can produce quite short renderings of very large
1357 * values. Otherwise the calculated width could be too narrow.
1358 * Note that it doesn't work if there was a currency with an exchange
1359 * rate greater than max.
1360 * When the currency rate is more than 1000, the 999 999 k becomes at
1361 * least 999 999 M which roughly is equally long. Furthermore if the
1362 * exchange rate is that high, 999 999 k is usually not enough anymore
1363 * to show the different currency numbers. */
1364 if (_currency->rate < 1000) max /= _currency->rate;
1365 SetDParam(0, max);
1366 SetDParam(1, max);
1367 uint score_detail_width = GetStringBoundingBox(STR_PERFORMANCE_DETAIL_AMOUNT_CURRENCY).width;
1369 size->width = 7 + score_info_width + 5 + this->bar_width + 5 + score_detail_width + 7;
1370 uint left = 7;
1371 uint right = size->width - 7;
1373 bool rtl = _current_text_dir == TD_RTL;
1374 this->score_info_left = rtl ? right - score_info_width : left;
1375 this->score_info_right = rtl ? right : left + score_info_width;
1377 this->score_detail_left = rtl ? left : right - score_detail_width;
1378 this->score_detail_right = rtl ? left + score_detail_width : right;
1380 this->bar_left = left + (rtl ? score_detail_width : score_info_width) + 5;
1381 this->bar_right = this->bar_left + this->bar_width;
1382 break;
1386 virtual void DrawWidget(const Rect &r, int widget) const
1388 /* No need to draw when there's nothing to draw */
1389 if (this->company == INVALID_COMPANY) return;
1391 if (IsInsideMM(widget, WID_PRD_COMPANY_FIRST, WID_PRD_COMPANY_LAST + 1)) {
1392 if (this->IsWidgetDisabled(widget)) return;
1393 CompanyID cid = (CompanyID)(widget - WID_PRD_COMPANY_FIRST);
1394 int offset = (cid == this->company) ? 1 : 0;
1395 Dimension sprite_size = GetSpriteSize(SPR_COMPANY_ICON);
1396 DrawCompanyIcon(cid, (r.left + r.right - sprite_size.width) / 2 + offset, (r.top + r.bottom - sprite_size.height) / 2 + offset);
1397 return;
1400 if (!IsInsideMM(widget, WID_PRD_SCORE_FIRST, WID_PRD_SCORE_LAST + 1)) return;
1402 ScoreID score_type = (ScoreID)(widget - WID_PRD_SCORE_FIRST);
1404 /* The colours used to show how the progress is going */
1405 int colour_done = _colour_gradient[COLOUR_GREEN][4];
1406 int colour_notdone = _colour_gradient[COLOUR_RED][4];
1408 /* Draw all the score parts */
1409 int val = _score_part[company][score_type];
1410 int needed = _score_info[score_type].needed;
1411 int score = _score_info[score_type].score;
1413 /* SCORE_TOTAL has his own rules ;) */
1414 if (score_type == SCORE_TOTAL) {
1415 for (ScoreID i = SCORE_BEGIN; i < SCORE_END; i++) score += _score_info[i].score;
1416 needed = SCORE_MAX;
1419 uint bar_top = r.top + WD_MATRIX_TOP;
1420 uint text_top = bar_top + 2;
1422 DrawString(this->score_info_left, this->score_info_right, text_top, STR_PERFORMANCE_DETAIL_VEHICLES + score_type);
1424 /* Draw the score */
1425 SetDParam(0, score);
1426 DrawString(this->score_info_left, this->score_info_right, text_top, STR_BLACK_COMMA, TC_FROMSTRING, SA_RIGHT);
1428 /* Calculate the %-bar */
1429 uint x = Clamp(val, 0, needed) * this->bar_width / needed;
1430 bool rtl = _current_text_dir == TD_RTL;
1431 if (rtl) {
1432 x = this->bar_right - x;
1433 } else {
1434 x = this->bar_left + x;
1437 /* Draw the bar */
1438 if (x != this->bar_left) GfxFillRect(this->bar_left, bar_top, x, bar_top + this->bar_height, rtl ? colour_notdone : colour_done);
1439 if (x != this->bar_right) GfxFillRect(x, bar_top, this->bar_right, bar_top + this->bar_height, rtl ? colour_done : colour_notdone);
1441 /* Draw it */
1442 SetDParam(0, Clamp(val, 0, needed) * 100 / needed);
1443 DrawString(this->bar_left, this->bar_right, text_top, STR_PERFORMANCE_DETAIL_PERCENT, TC_FROMSTRING, SA_HOR_CENTER);
1445 /* SCORE_LOAN is inversed */
1446 if (score_type == SCORE_LOAN) val = needed - val;
1448 /* Draw the amount we have against what is needed
1449 * For some of them it is in currency format */
1450 SetDParam(0, val);
1451 SetDParam(1, needed);
1452 switch (score_type) {
1453 case SCORE_MIN_PROFIT:
1454 case SCORE_MIN_INCOME:
1455 case SCORE_MAX_INCOME:
1456 case SCORE_MONEY:
1457 case SCORE_LOAN:
1458 DrawString(this->score_detail_left, this->score_detail_right, text_top, STR_PERFORMANCE_DETAIL_AMOUNT_CURRENCY);
1459 break;
1460 default:
1461 DrawString(this->score_detail_left, this->score_detail_right, text_top, STR_PERFORMANCE_DETAIL_AMOUNT_INT);
1465 virtual void OnClick(Point pt, int widget, int click_count)
1467 /* Check which button is clicked */
1468 if (IsInsideMM(widget, WID_PRD_COMPANY_FIRST, WID_PRD_COMPANY_LAST + 1)) {
1469 /* Is it no on disable? */
1470 if (!this->IsWidgetDisabled(widget)) {
1471 this->RaiseWidget(this->company + WID_PRD_COMPANY_FIRST);
1472 this->company = (CompanyID)(widget - WID_PRD_COMPANY_FIRST);
1473 this->LowerWidget(this->company + WID_PRD_COMPANY_FIRST);
1474 this->SetDirty();
1479 virtual void OnTick()
1481 if (_pause_mode != PM_UNPAUSED) return;
1483 /* Update the company score every 5 days */
1484 if (--this->timeout == 0) {
1485 this->UpdateCompanyStats();
1486 this->SetDirty();
1491 * Some data on this window has become invalid.
1492 * @param data the company ID of the company that is going to be removed
1493 * @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.
1495 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
1497 if (!gui_scope) return;
1498 /* Disable the companies who are not active */
1499 for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) {
1500 this->SetWidgetDisabledState(i + WID_PRD_COMPANY_FIRST, !Company::IsValidID(i));
1503 /* Check if the currently selected company is still active. */
1504 if (this->company != INVALID_COMPANY && !Company::IsValidID(this->company)) {
1505 /* Raise the widget for the previous selection. */
1506 this->RaiseWidget(this->company + WID_PRD_COMPANY_FIRST);
1507 this->company = INVALID_COMPANY;
1510 if (this->company == INVALID_COMPANY) {
1511 const Company *c;
1512 FOR_ALL_COMPANIES(c) {
1513 this->company = c->index;
1514 break;
1518 /* Make sure the widget is lowered */
1519 this->LowerWidget(this->company + WID_PRD_COMPANY_FIRST);
1523 CompanyID PerformanceRatingDetailWindow::company = INVALID_COMPANY;
1526 * Make a vertical list of panels for outputting score details.
1527 * @param biggest_index Storage for collecting the biggest index used in the returned tree.
1528 * @return Panel with performance details.
1529 * @post \c *biggest_index contains the largest used index in the tree.
1531 static NWidgetBase *MakePerformanceDetailPanels(int *biggest_index)
1533 const StringID performance_tips[] = {
1534 STR_PERFORMANCE_DETAIL_VEHICLES_TOOLTIP,
1535 STR_PERFORMANCE_DETAIL_STATIONS_TOOLTIP,
1536 STR_PERFORMANCE_DETAIL_MIN_PROFIT_TOOLTIP,
1537 STR_PERFORMANCE_DETAIL_MIN_INCOME_TOOLTIP,
1538 STR_PERFORMANCE_DETAIL_MAX_INCOME_TOOLTIP,
1539 STR_PERFORMANCE_DETAIL_DELIVERED_TOOLTIP,
1540 STR_PERFORMANCE_DETAIL_CARGO_TOOLTIP,
1541 STR_PERFORMANCE_DETAIL_MONEY_TOOLTIP,
1542 STR_PERFORMANCE_DETAIL_LOAN_TOOLTIP,
1543 STR_PERFORMANCE_DETAIL_TOTAL_TOOLTIP,
1546 assert_compile(lengthof(performance_tips) == SCORE_END - SCORE_BEGIN);
1548 NWidgetVertical *vert = new NWidgetVertical(NC_EQUALSIZE);
1549 for (int widnum = WID_PRD_SCORE_FIRST; widnum <= WID_PRD_SCORE_LAST; widnum++) {
1550 NWidgetBackground *panel = new NWidgetBackground(WWT_PANEL, COLOUR_GREY, widnum);
1551 panel->SetFill(1, 1);
1552 panel->SetDataTip(0x0, performance_tips[widnum - WID_PRD_SCORE_FIRST]);
1553 vert->Add(panel);
1555 *biggest_index = WID_PRD_SCORE_LAST;
1556 return vert;
1559 /** Make a number of rows with buttons for each company for the performance rating detail window. */
1560 NWidgetBase *MakeCompanyButtonRowsGraphGUI(int *biggest_index)
1562 return MakeCompanyButtonRows(biggest_index, WID_PRD_COMPANY_FIRST, WID_PRD_COMPANY_LAST, 8, STR_PERFORMANCE_DETAIL_SELECT_COMPANY_TOOLTIP);
1565 static const NWidgetPart _nested_performance_rating_detail_widgets[] = {
1566 NWidget(NWID_HORIZONTAL),
1567 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1568 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_PERFORMANCE_DETAIL, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1569 NWidget(WWT_SHADEBOX, COLOUR_GREY),
1570 NWidget(WWT_STICKYBOX, COLOUR_GREY),
1571 EndContainer(),
1572 NWidget(WWT_PANEL, COLOUR_GREY),
1573 NWidgetFunction(MakeCompanyButtonRowsGraphGUI), SetPadding(0, 1, 1, 2),
1574 EndContainer(),
1575 NWidgetFunction(MakePerformanceDetailPanels),
1578 static WindowDesc _performance_rating_detail_desc(
1579 WDP_AUTO, "league_details", 0, 0,
1580 WC_PERFORMANCE_DETAIL, WC_NONE,
1582 _nested_performance_rating_detail_widgets, lengthof(_nested_performance_rating_detail_widgets)
1585 void ShowPerformanceRatingDetail()
1587 AllocateWindowDescFront<PerformanceRatingDetailWindow>(&_performance_rating_detail_desc, 0);
1590 /*****************/
1591 /* STATION CARGO */
1592 /*****************/
1594 struct StationCargoGraphWindow : BaseGraphWindow {
1595 StationID station_id;
1597 bool first_init; ///< This value is true until the first initialization of the window has finished.
1598 StationCargoGraphWindow(WindowDesc *desc, WindowNumber window_number) :
1599 BaseGraphWindow(desc, WID_SCG_GRAPH, STR_JUST_COMMA)
1601 station_id = window_number;
1603 this->first_init = true;
1604 this->num_on_x_axis = MAX_STATION_CARGO_HISTORY_DAYS; // Four weeks
1605 this->num_vert_lines = MAX_STATION_CARGO_HISTORY_DAYS;
1606 this->month = 0xFF;
1607 this->x_values_start = 2;
1608 this->x_values_increment = 2;
1610 /* Initialise the dataset */
1611 this->OnHundredthTick();
1613 this->InitNested(window_number);
1615 this->UpdateLoweredWidgets();
1618 virtual void OnInit()
1620 /* UpdateLoweredWidgets needs to be called after a language or NewGRF change, but it can't be called before
1621 * InitNested is done. On the first init these functions are called in the correct order by the constructor. */
1622 if (!this->first_init) {
1623 /* Initialise the dataset */
1624 this->OnHundredthTick();
1625 this->UpdateLoweredWidgets();
1627 this->first_init = false;
1630 virtual void SetStringParameters(int widget) const
1632 if (widget == WID_SCG_CAPTION) {
1633 SetDParam(0, this->station_id);
1637 void UpdateExcludedData()
1639 this->excluded_data = 0;
1641 int i = 0;
1642 const CargoSpec *cs;
1643 FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
1644 if (HasBit(_legend_excluded_cargo, cs->Index())) SetBit(this->excluded_data, i);
1645 i++;
1649 void UpdateLoweredWidgets()
1651 for (int i = 0; i < _sorted_standard_cargo_specs_size; i++) {
1652 this->SetWidgetLoweredState(WID_SCG_CARGO_FIRST + i, !HasBit(this->excluded_data, i));
1656 virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
1658 if (widget < WID_SCG_CARGO_FIRST) {
1659 BaseGraphWindow::UpdateWidgetSize(widget, size, padding, fill, resize);
1660 return;
1663 const CargoSpec *cs = _sorted_cargo_specs[widget - WID_SCG_CARGO_FIRST];
1664 SetDParam(0, cs->name);
1665 Dimension d = GetStringBoundingBox(STR_GRAPH_CARGO_PAYMENT_CARGO);
1666 d.width += 14; // colour field
1667 d.width += WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
1668 d.height += WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
1669 *size = maxdim(d, *size);
1672 virtual void DrawWidget(const Rect &r, int widget) const
1674 if (widget < WID_SCG_CARGO_FIRST) {
1675 BaseGraphWindow::DrawWidget(r, widget);
1676 return;
1679 const CargoSpec *cs = _sorted_cargo_specs[widget - WID_SCG_CARGO_FIRST];
1680 bool rtl = _current_text_dir == TD_RTL;
1682 /* Since the buttons have no text, no images,
1683 * both the text and the coloured box have to be manually painted.
1684 * clk_dif will move one pixel down and one pixel to the right
1685 * when the button is clicked */
1686 byte clk_dif = this->IsWidgetLowered(widget) ? 1 : 0;
1687 int x = r.left + WD_FRAMERECT_LEFT;
1688 int y = r.top;
1690 int rect_x = clk_dif + (rtl ? r.right - 12 : r.left + WD_FRAMERECT_LEFT);
1692 GfxFillRect(rect_x, y + clk_dif, rect_x + 8, y + 5 + clk_dif, PC_BLACK);
1693 GfxFillRect(rect_x + 1, y + 1 + clk_dif, rect_x + 7, y + 4 + clk_dif, cs->legend_colour);
1694 SetDParam(0, cs->name);
1695 DrawString(rtl ? r.left : x + 14 + clk_dif, (rtl ? r.right - 14 + clk_dif : r.right), y + clk_dif, STR_GRAPH_CARGO_PAYMENT_CARGO);
1698 virtual void OnClick(Point pt, int widget, int click_count)
1700 switch (widget) {
1701 case WID_SCG_ENABLE_CARGOES:
1702 /* Remove all cargoes from the excluded lists. */
1703 _legend_excluded_cargo = 0;
1704 this->excluded_data = 0;
1705 this->UpdateLoweredWidgets();
1706 this->SetDirty();
1707 break;
1709 case WID_SCG_DISABLE_CARGOES: {
1710 /* Add all cargoes to the excluded lists. */
1711 int i = 0;
1712 const CargoSpec *cs;
1713 FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
1714 SetBit(_legend_excluded_cargo, cs->Index());
1715 SetBit(this->excluded_data, i);
1716 i++;
1718 this->UpdateLoweredWidgets();
1719 this->SetDirty();
1720 break;
1723 default:
1724 if (widget >= WID_SCG_CARGO_FIRST) {
1725 int i = widget - WID_SCG_CARGO_FIRST;
1726 ToggleBit(_legend_excluded_cargo, _sorted_cargo_specs[i]->Index());
1727 this->ToggleWidgetLoweredState(widget);
1728 this->UpdateExcludedData();
1729 this->SetDirty();
1731 break;
1735 virtual void OnTick()
1737 /* Override default OnTick */
1741 * Some data on this window has become invalid.
1742 * @param data Information about the changed data.
1743 * @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.
1745 virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
1747 if (!gui_scope) return;
1748 this->OnHundredthTick();
1751 virtual void OnHundredthTick()
1753 this->UpdateExcludedData();
1755 const Station* station = Station::GetIfValid(this->station_id);
1757 if (station == nullptr) return;
1759 int i = 0;
1760 const CargoSpec *cs;
1761 FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
1762 this->colours[i] = cs->legend_colour;
1764 for (uint j = 0; j < MAX_STATION_CARGO_HISTORY_DAYS; j++) {
1766 this->cost[i][j] = station->station_cargo_history[cs->Index() * MAX_STATION_CARGO_HISTORY_DAYS + j] * STATION_CARGO_HISTORY_FACTOR;
1768 i++;
1771 this->num_dataset = i;
1773 this->SetDirty();
1777 /** Construct the row containing the digit keys. */
1778 static NWidgetBase *MakeStationCargoButtons(int *biggest_index)
1780 NWidgetVertical *ver = new NWidgetVertical;
1782 for (int i = 0; i < _sorted_standard_cargo_specs_size; i++) {
1783 NWidgetBackground *leaf = new NWidgetBackground(WWT_PANEL, COLOUR_ORANGE, WID_SCG_CARGO_FIRST + i, nullptr);
1784 leaf->tool_tip = STR_GRAPH_CARGO_PAYMENT_TOGGLE_CARGO;
1785 leaf->SetFill(1, 0);
1786 leaf->SetLowered(true);
1787 ver->Add(leaf);
1789 *biggest_index = WID_SCG_CARGO_FIRST + _sorted_standard_cargo_specs_size - 1;
1790 return ver;
1794 static const NWidgetPart _nested_station_cargo_widgets[] = {
1795 NWidget(NWID_HORIZONTAL),
1796 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1797 NWidget(WWT_CAPTION, COLOUR_GREY, WID_SCG_CAPTION), SetDataTip(STR_GRAPH_STATION_CARGO_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1798 NWidget(WWT_SHADEBOX, COLOUR_GREY),
1799 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
1800 NWidget(WWT_STICKYBOX, COLOUR_GREY),
1801 EndContainer(),
1802 NWidget(WWT_PANEL, COLOUR_GREY, WID_SCG_BACKGROUND), SetMinimalSize(568, 128),
1803 NWidget(NWID_HORIZONTAL),
1804 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
1805 NWidget(WWT_TEXT, COLOUR_GREY, WID_SCG_HEADER), SetMinimalSize(0, 6), SetPadding(2, 0, 2, 0), SetDataTip(STR_GRAPH_STATION_CARGO_TITLE, STR_NULL),
1806 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
1807 EndContainer(),
1808 NWidget(NWID_HORIZONTAL),
1809 NWidget(WWT_EMPTY, COLOUR_GREY, WID_SCG_GRAPH), SetMinimalSize(495, 0), SetFill(1, 1), SetResize(1, 1),
1810 NWidget(NWID_VERTICAL),
1811 NWidget(NWID_SPACER), SetMinimalSize(0, 24), SetFill(0, 0), SetResize(0, 1),
1812 NWidget(WWT_PUSHTXTBTN, COLOUR_ORANGE, WID_SCG_ENABLE_CARGOES), SetDataTip(STR_GRAPH_CARGO_ENABLE_ALL, STR_GRAPH_CARGO_TOOLTIP_ENABLE_ALL), SetFill(1, 0),
1813 NWidget(WWT_PUSHTXTBTN, COLOUR_ORANGE, WID_SCG_DISABLE_CARGOES), SetDataTip(STR_GRAPH_CARGO_DISABLE_ALL, STR_GRAPH_CARGO_TOOLTIP_DISABLE_ALL), SetFill(1, 0),
1814 NWidget(NWID_SPACER), SetMinimalSize(0, 4),
1815 NWidgetFunction(MakeStationCargoButtons),
1816 NWidget(NWID_SPACER), SetMinimalSize(0, 24), SetFill(0, 1), SetResize(0, 1),
1817 EndContainer(),
1818 NWidget(NWID_SPACER), SetMinimalSize(5, 0), SetFill(0, 1), SetResize(0, 1),
1819 EndContainer(),
1820 NWidget(NWID_HORIZONTAL),
1821 NWidget(NWID_SPACER), SetMinimalSize(WD_RESIZEBOX_WIDTH, 0), SetFill(1, 0), SetResize(1, 0),
1822 NWidget(WWT_TEXT, COLOUR_GREY, WID_SCG_FOOTER), SetMinimalSize(0, 6), SetPadding(2, 0, 2, 0), SetDataTip(STR_GRAPH_STATION_CARGO_X_LABEL, STR_NULL),
1823 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
1824 NWidget(WWT_RESIZEBOX, COLOUR_GREY, WID_SCG_RESIZE),
1825 EndContainer(),
1826 EndContainer(),
1829 static WindowDesc _station_cargo_desc(
1830 WDP_AUTO, "graph_station_cargo", 0, 0,
1831 WC_STATION_CARGO, WC_NONE,
1833 _nested_station_cargo_widgets, lengthof(_nested_station_cargo_widgets)
1837 void ShowStationCargo(StationID station_id)
1839 AllocateWindowDescFront<StationCargoGraphWindow>(&_station_cargo_desc, station_id);