Fix: Don't try to rename OWNER_DEITY signs in-game (#9716)
[openttd-github.git] / src / industry_gui.cpp
blob1b63191f3973182024dbf81786c04fc5865ee608
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /** @file industry_gui.cpp GUIs related to industries. */
10 #include "stdafx.h"
11 #include "error.h"
12 #include "gui.h"
13 #include "settings_gui.h"
14 #include "sound_func.h"
15 #include "window_func.h"
16 #include "textbuf_gui.h"
17 #include "command_func.h"
18 #include "viewport_func.h"
19 #include "industry.h"
20 #include "town.h"
21 #include "cheat_type.h"
22 #include "newgrf_industries.h"
23 #include "newgrf_text.h"
24 #include "newgrf_debug.h"
25 #include "network/network.h"
26 #include "strings_func.h"
27 #include "company_func.h"
28 #include "tilehighlight_func.h"
29 #include "string_func.h"
30 #include "sortlist_type.h"
31 #include "widgets/dropdown_func.h"
32 #include "company_base.h"
33 #include "core/geometry_func.hpp"
34 #include "core/random_func.hpp"
35 #include "core/backup_type.hpp"
36 #include "genworld.h"
37 #include "smallmap_gui.h"
38 #include "widgets/dropdown_type.h"
39 #include "widgets/industry_widget.h"
40 #include "clear_map.h"
41 #include "zoom_func.h"
43 #include "table/strings.h"
45 #include <bitset>
47 #include "safeguards.h"
49 bool _ignore_restrictions;
50 std::bitset<NUM_INDUSTRYTYPES> _displayed_industries; ///< Communication from the industry chain window to the smallmap window about what industries to display.
52 /** Cargo suffix type (for which window is it requested) */
53 enum CargoSuffixType {
54 CST_FUND, ///< Fund-industry window
55 CST_VIEW, ///< View-industry window
56 CST_DIR, ///< Industry-directory window
59 /** Ways of displaying the cargo. */
60 enum CargoSuffixDisplay {
61 CSD_CARGO, ///< Display the cargo without sub-type (cb37 result 401).
62 CSD_CARGO_AMOUNT, ///< Display the cargo and amount (if useful), but no sub-type (cb37 result 400 or fail).
63 CSD_CARGO_TEXT, ///< Display then cargo and supplied string (cb37 result 800-BFF).
64 CSD_CARGO_AMOUNT_TEXT, ///< Display then cargo, amount, and string (cb37 result 000-3FF).
67 /** Transfer storage of cargo suffix information. */
68 struct CargoSuffix {
69 CargoSuffixDisplay display; ///< How to display the cargo and text.
70 char text[512]; ///< Cargo suffix text.
73 static void ShowIndustryCargoesWindow(IndustryType id);
75 /**
76 * Gets the string to display after the cargo name (using callback 37)
77 * @param cargo the cargo for which the suffix is requested, meaning depends on presence of flag 18 in prop 1A
78 * @param cst the cargo suffix type (for which window is it requested). @see CargoSuffixType
79 * @param ind the industry (nullptr if in fund window)
80 * @param ind_type the industry type
81 * @param indspec the industry spec
82 * @param suffix is filled with the string to display
84 static void GetCargoSuffix(uint cargo, CargoSuffixType cst, const Industry *ind, IndustryType ind_type, const IndustrySpec *indspec, CargoSuffix &suffix)
86 suffix.text[0] = '\0';
87 suffix.display = CSD_CARGO_AMOUNT;
89 if (HasBit(indspec->callback_mask, CBM_IND_CARGO_SUFFIX)) {
90 TileIndex t = (cst != CST_FUND) ? ind->location.tile : INVALID_TILE;
91 uint16 callback = GetIndustryCallback(CBID_INDUSTRY_CARGO_SUFFIX, 0, (cst << 8) | cargo, const_cast<Industry *>(ind), ind_type, t);
92 if (callback == CALLBACK_FAILED) return;
94 if (indspec->grf_prop.grffile->grf_version < 8) {
95 if (GB(callback, 0, 8) == 0xFF) return;
96 if (callback < 0x400) {
97 StartTextRefStackUsage(indspec->grf_prop.grffile, 6);
98 GetString(suffix.text, GetGRFStringID(indspec->grf_prop.grffile->grfid, 0xD000 + callback), lastof(suffix.text));
99 StopTextRefStackUsage();
100 suffix.display = CSD_CARGO_AMOUNT_TEXT;
101 return;
103 ErrorUnknownCallbackResult(indspec->grf_prop.grffile->grfid, CBID_INDUSTRY_CARGO_SUFFIX, callback);
104 return;
106 } else { // GRF version 8 or higher.
107 if (callback == 0x400) return;
108 if (callback == 0x401) {
109 suffix.display = CSD_CARGO;
110 return;
112 if (callback < 0x400) {
113 StartTextRefStackUsage(indspec->grf_prop.grffile, 6);
114 GetString(suffix.text, GetGRFStringID(indspec->grf_prop.grffile->grfid, 0xD000 + callback), lastof(suffix.text));
115 StopTextRefStackUsage();
116 suffix.display = CSD_CARGO_AMOUNT_TEXT;
117 return;
119 if (callback >= 0x800 && callback < 0xC00) {
120 StartTextRefStackUsage(indspec->grf_prop.grffile, 6);
121 GetString(suffix.text, GetGRFStringID(indspec->grf_prop.grffile->grfid, 0xD000 - 0x800 + callback), lastof(suffix.text));
122 StopTextRefStackUsage();
123 suffix.display = CSD_CARGO_TEXT;
124 return;
126 ErrorUnknownCallbackResult(indspec->grf_prop.grffile->grfid, CBID_INDUSTRY_CARGO_SUFFIX, callback);
127 return;
132 enum CargoSuffixInOut {
133 CARGOSUFFIX_OUT = 0,
134 CARGOSUFFIX_IN = 1,
138 * Gets all strings to display after the cargoes of industries (using callback 37)
139 * @param use_input get suffixes for output cargoes or input cargoes?
140 * @param cst the cargo suffix type (for which window is it requested). @see CargoSuffixType
141 * @param ind the industry (nullptr if in fund window)
142 * @param ind_type the industry type
143 * @param indspec the industry spec
144 * @param cargoes array with cargotypes. for CT_INVALID no suffix will be determined
145 * @param suffixes is filled with the suffixes
147 template <typename TC, typename TS>
148 static inline void GetAllCargoSuffixes(CargoSuffixInOut use_input, CargoSuffixType cst, const Industry *ind, IndustryType ind_type, const IndustrySpec *indspec, const TC &cargoes, TS &suffixes)
150 static_assert(lengthof(cargoes) <= lengthof(suffixes));
152 if (indspec->behaviour & INDUSTRYBEH_CARGOTYPES_UNLIMITED) {
153 /* Reworked behaviour with new many-in-many-out scheme */
154 for (uint j = 0; j < lengthof(suffixes); j++) {
155 if (cargoes[j] != CT_INVALID) {
156 byte local_id = indspec->grf_prop.grffile->cargo_map[cargoes[j]]; // should we check the value for valid?
157 uint cargotype = local_id << 16 | use_input;
158 GetCargoSuffix(cargotype, cst, ind, ind_type, indspec, suffixes[j]);
159 } else {
160 suffixes[j].text[0] = '\0';
161 suffixes[j].display = CSD_CARGO;
164 } else {
165 /* Compatible behaviour with old 3-in-2-out scheme */
166 for (uint j = 0; j < lengthof(suffixes); j++) {
167 suffixes[j].text[0] = '\0';
168 suffixes[j].display = CSD_CARGO;
170 switch (use_input) {
171 case CARGOSUFFIX_OUT:
172 if (cargoes[0] != CT_INVALID) GetCargoSuffix(3, cst, ind, ind_type, indspec, suffixes[0]);
173 if (cargoes[1] != CT_INVALID) GetCargoSuffix(4, cst, ind, ind_type, indspec, suffixes[1]);
174 break;
175 case CARGOSUFFIX_IN:
176 if (cargoes[0] != CT_INVALID) GetCargoSuffix(0, cst, ind, ind_type, indspec, suffixes[0]);
177 if (cargoes[1] != CT_INVALID) GetCargoSuffix(1, cst, ind, ind_type, indspec, suffixes[1]);
178 if (cargoes[2] != CT_INVALID) GetCargoSuffix(2, cst, ind, ind_type, indspec, suffixes[2]);
179 break;
180 default:
181 NOT_REACHED();
186 std::array<IndustryType, NUM_INDUSTRYTYPES> _sorted_industry_types; ///< Industry types sorted by name.
188 /** Sort industry types by their name. */
189 static bool IndustryTypeNameSorter(const IndustryType &a, const IndustryType &b)
191 static char industry_name[2][64];
193 const IndustrySpec *indsp1 = GetIndustrySpec(a);
194 GetString(industry_name[0], indsp1->name, lastof(industry_name[0]));
196 const IndustrySpec *indsp2 = GetIndustrySpec(b);
197 GetString(industry_name[1], indsp2->name, lastof(industry_name[1]));
199 int r = strnatcmp(industry_name[0], industry_name[1]); // Sort by name (natural sorting).
201 /* If the names are equal, sort by industry type. */
202 return (r != 0) ? r < 0 : (a < b);
206 * Initialize the list of sorted industry types.
208 void SortIndustryTypes()
210 /* Add each industry type to the list. */
211 for (IndustryType i = 0; i < NUM_INDUSTRYTYPES; i++) {
212 _sorted_industry_types[i] = i;
215 /* Sort industry types by name. */
216 std::sort(_sorted_industry_types.begin(), _sorted_industry_types.end(), IndustryTypeNameSorter);
220 * Command callback. In case of failure to build an industry, show an error message.
221 * @param result Result of the command.
222 * @param tile Tile where the industry is placed.
223 * @param p1 Additional data of the #CMD_BUILD_INDUSTRY command.
224 * @param p2 Additional data of the #CMD_BUILD_INDUSTRY command.
225 * @param cmd Unused.
227 void CcBuildIndustry(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2, uint32 cmd)
229 if (result.Succeeded()) return;
231 uint8 indtype = GB(p1, 0, 8);
232 if (indtype < NUM_INDUSTRYTYPES) {
233 const IndustrySpec *indsp = GetIndustrySpec(indtype);
234 if (indsp->enabled) {
235 SetDParam(0, indsp->name);
236 ShowErrorMessage(STR_ERROR_CAN_T_BUILD_HERE, result.GetErrorMessage(), WL_INFO, TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE);
241 static const NWidgetPart _nested_build_industry_widgets[] = {
242 NWidget(NWID_HORIZONTAL),
243 NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
244 NWidget(WWT_CAPTION, COLOUR_DARK_GREEN), SetDataTip(STR_FUND_INDUSTRY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
245 NWidget(WWT_SHADEBOX, COLOUR_DARK_GREEN),
246 NWidget(WWT_DEFSIZEBOX, COLOUR_DARK_GREEN),
247 NWidget(WWT_STICKYBOX, COLOUR_DARK_GREEN),
248 EndContainer(),
249 NWidget(NWID_SELECTION, COLOUR_DARK_GREEN, WID_DPI_SCENARIO_EDITOR_PANE),
250 NWidget(NWID_VERTICAL),
251 NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, WID_DPI_CREATE_RANDOM_INDUSTRIES_WIDGET), SetMinimalSize(0, 12), SetFill(1, 0), SetResize(1, 0),
252 SetDataTip(STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES, STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES_TOOLTIP),
253 NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, WID_DPI_REMOVE_ALL_INDUSTRIES_WIDGET), SetMinimalSize(0, 12), SetFill(1, 0), SetResize(1, 0),
254 SetDataTip(STR_FUND_INDUSTRY_REMOVE_ALL_INDUSTRIES, STR_FUND_INDUSTRY_REMOVE_ALL_INDUSTRIES_TOOLTIP),
255 EndContainer(),
256 EndContainer(),
257 NWidget(NWID_HORIZONTAL),
258 NWidget(WWT_MATRIX, COLOUR_DARK_GREEN, WID_DPI_MATRIX_WIDGET), SetMatrixDataTip(1, 0, STR_FUND_INDUSTRY_SELECTION_TOOLTIP), SetFill(1, 0), SetResize(1, 1), SetScrollbar(WID_DPI_SCROLLBAR),
259 NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, WID_DPI_SCROLLBAR),
260 EndContainer(),
261 NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_DPI_INFOPANEL), SetResize(1, 0),
262 EndContainer(),
263 NWidget(NWID_HORIZONTAL),
264 NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, WID_DPI_DISPLAY_WIDGET), SetFill(1, 0), SetResize(1, 0),
265 SetDataTip(STR_INDUSTRY_DISPLAY_CHAIN, STR_INDUSTRY_DISPLAY_CHAIN_TOOLTIP),
266 NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, WID_DPI_FUND_WIDGET), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_JUST_STRING, STR_NULL),
267 NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
268 EndContainer(),
271 /** Window definition of the dynamic place industries gui */
272 static WindowDesc _build_industry_desc(
273 WDP_AUTO, "build_industry", 170, 212,
274 WC_BUILD_INDUSTRY, WC_NONE,
275 WDF_CONSTRUCTION,
276 _nested_build_industry_widgets, lengthof(_nested_build_industry_widgets)
279 /** Build (fund or prospect) a new industry, */
280 class BuildIndustryWindow : public Window {
281 int selected_index; ///< index of the element in the matrix
282 IndustryType selected_type; ///< industry corresponding to the above index
283 uint16 count; ///< How many industries are loaded
284 IndustryType index[NUM_INDUSTRYTYPES + 1]; ///< Type of industry, in the order it was loaded
285 bool enabled[NUM_INDUSTRYTYPES + 1]; ///< availability state, coming from CBID_INDUSTRY_PROBABILITY (if ever)
286 Scrollbar *vscroll;
287 Dimension legend; ///< Dimension of the legend 'blob'.
289 /** The largest allowed minimum-width of the window, given in line heights */
290 static const int MAX_MINWIDTH_LINEHEIGHTS = 20;
292 void SetupArrays()
294 this->count = 0;
296 for (uint i = 0; i < lengthof(this->index); i++) {
297 this->index[i] = INVALID_INDUSTRYTYPE;
298 this->enabled[i] = false;
301 /* Fill the arrays with industries.
302 * The tests performed after the enabled allow to load the industries
303 * In the same way they are inserted by grf (if any)
305 for (IndustryType ind : _sorted_industry_types) {
306 const IndustrySpec *indsp = GetIndustrySpec(ind);
307 if (indsp->enabled) {
308 /* Rule is that editor mode loads all industries.
309 * In game mode, all non raw industries are loaded too
310 * and raw ones are loaded only when setting allows it */
311 if (_game_mode != GM_EDITOR && indsp->IsRawIndustry() && _settings_game.construction.raw_industry_construction == 0) {
312 /* Unselect if the industry is no longer in the list */
313 if (this->selected_type == ind) this->selected_index = -1;
314 continue;
316 this->index[this->count] = ind;
317 this->enabled[this->count] = (_game_mode == GM_EDITOR) || GetIndustryProbabilityCallback(ind, IACT_USERCREATION, 1) > 0;
318 /* Keep the selection to the correct line */
319 if (this->selected_type == ind) this->selected_index = this->count;
320 this->count++;
324 /* first industry type is selected if the current selection is invalid.
325 * I'll be damned if there are none available ;) */
326 if (this->selected_index == -1) {
327 this->selected_index = 0;
328 this->selected_type = this->index[0];
331 this->vscroll->SetCount(this->count);
334 /** Update status of the fund and display-chain widgets. */
335 void SetButtons()
337 this->SetWidgetDisabledState(WID_DPI_FUND_WIDGET, this->selected_type != INVALID_INDUSTRYTYPE && !this->enabled[this->selected_index]);
338 this->SetWidgetDisabledState(WID_DPI_DISPLAY_WIDGET, this->selected_type == INVALID_INDUSTRYTYPE && this->enabled[this->selected_index]);
342 * Build a string of cargo names with suffixes attached.
343 * This is distinct from the CARGO_LIST string formatting code in two ways:
344 * - This cargo list uses the order defined by the industry, rather than alphabetic.
345 * - NewGRF-supplied suffix strings can be attached to each cargo.
347 * @param cargolist Array of CargoID to display
348 * @param cargo_suffix Array of suffixes to attach to each cargo
349 * @param cargolistlen Length of arrays
350 * @param prefixstr String to use for the first item
351 * @return A formatted raw string
353 std::string MakeCargoListString(const CargoID *cargolist, const CargoSuffix *cargo_suffix, int cargolistlen, StringID prefixstr) const
355 std::string cargostring;
356 char buf[1024];
357 int numcargo = 0;
358 int firstcargo = -1;
360 for (int j = 0; j < cargolistlen; j++) {
361 if (cargolist[j] == CT_INVALID) continue;
362 numcargo++;
363 if (firstcargo < 0) {
364 firstcargo = j;
365 continue;
367 SetDParam(0, CargoSpec::Get(cargolist[j])->name);
368 SetDParamStr(1, cargo_suffix[j].text);
369 GetString(buf, STR_INDUSTRY_VIEW_CARGO_LIST_EXTENSION, lastof(buf));
370 cargostring += buf;
373 if (numcargo > 0) {
374 SetDParam(0, CargoSpec::Get(cargolist[firstcargo])->name);
375 SetDParamStr(1, cargo_suffix[firstcargo].text);
376 GetString(buf, prefixstr, lastof(buf));
377 cargostring = std::string(buf) + cargostring;
378 } else {
379 SetDParam(0, STR_JUST_NOTHING);
380 SetDParamStr(1, "");
381 GetString(buf, prefixstr, lastof(buf));
382 cargostring = std::string(buf);
385 return cargostring;
388 public:
389 BuildIndustryWindow() : Window(&_build_industry_desc)
391 this->selected_index = -1;
392 this->selected_type = INVALID_INDUSTRYTYPE;
394 this->CreateNestedTree();
395 this->vscroll = this->GetScrollbar(WID_DPI_SCROLLBAR);
396 this->FinishInitNested(0);
398 this->SetButtons();
400 /* Show scenario editor tools in editor. */
401 if (_game_mode != GM_EDITOR) {
402 auto *se_tools = this->GetWidget<NWidgetStacked>(WID_DPI_SCENARIO_EDITOR_PANE);
403 se_tools->SetDisplayedPlane(SZSP_HORIZONTAL);
404 this->ReInit();
408 void OnInit() override
410 /* Width of the legend blob -- slightly larger than the smallmap legend blob. */
411 this->legend.height = FONT_HEIGHT_SMALL;
412 this->legend.width = this->legend.height * 8 / 5;
414 this->SetupArrays();
417 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
419 switch (widget) {
420 case WID_DPI_MATRIX_WIDGET: {
421 Dimension d = GetStringBoundingBox(STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES);
422 for (uint16 i = 0; i < this->count; i++) {
423 if (this->index[i] == INVALID_INDUSTRYTYPE) continue;
424 d = maxdim(d, GetStringBoundingBox(GetIndustrySpec(this->index[i])->name));
426 resize->height = std::max<uint>(this->legend.height, FONT_HEIGHT_NORMAL) + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;
427 d.width += this->legend.width + ScaleFontTrad(7) + padding.width;
428 d.height = 5 * resize->height;
429 *size = maxdim(*size, d);
430 break;
433 case WID_DPI_INFOPANEL: {
434 /* Extra line for cost outside of editor. */
435 int height = 2 + (_game_mode == GM_EDITOR ? 0 : 1);
436 uint extra_lines_req = 0;
437 uint extra_lines_prd = 0;
438 uint extra_lines_newgrf = 0;
439 uint max_minwidth = FONT_HEIGHT_NORMAL * MAX_MINWIDTH_LINEHEIGHTS;
440 Dimension d = {0, 0};
441 for (uint16 i = 0; i < this->count; i++) {
442 if (this->index[i] == INVALID_INDUSTRYTYPE) continue;
444 const IndustrySpec *indsp = GetIndustrySpec(this->index[i]);
445 CargoSuffix cargo_suffix[lengthof(indsp->accepts_cargo)];
447 /* Measure the accepted cargoes, if any. */
448 GetAllCargoSuffixes(CARGOSUFFIX_IN, CST_FUND, nullptr, this->index[i], indsp, indsp->accepts_cargo, cargo_suffix);
449 std::string cargostring = this->MakeCargoListString(indsp->accepts_cargo, cargo_suffix, lengthof(indsp->accepts_cargo), STR_INDUSTRY_VIEW_REQUIRES_N_CARGO);
450 Dimension strdim = GetStringBoundingBox(cargostring.c_str());
451 if (strdim.width > max_minwidth) {
452 extra_lines_req = std::max(extra_lines_req, strdim.width / max_minwidth + 1);
453 strdim.width = max_minwidth;
455 d = maxdim(d, strdim);
457 /* Measure the produced cargoes, if any. */
458 GetAllCargoSuffixes(CARGOSUFFIX_OUT, CST_FUND, nullptr, this->index[i], indsp, indsp->produced_cargo, cargo_suffix);
459 cargostring = this->MakeCargoListString(indsp->produced_cargo, cargo_suffix, lengthof(indsp->produced_cargo), STR_INDUSTRY_VIEW_PRODUCES_N_CARGO);
460 strdim = GetStringBoundingBox(cargostring.c_str());
461 if (strdim.width > max_minwidth) {
462 extra_lines_prd = std::max(extra_lines_prd, strdim.width / max_minwidth + 1);
463 strdim.width = max_minwidth;
465 d = maxdim(d, strdim);
467 if (indsp->grf_prop.grffile != nullptr) {
468 /* Reserve a few extra lines for text from an industry NewGRF. */
469 extra_lines_newgrf = 4;
473 /* Set it to something more sane :) */
474 height += extra_lines_prd + extra_lines_req + extra_lines_newgrf;
475 size->height = height * FONT_HEIGHT_NORMAL + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
476 size->width = d.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
477 break;
480 case WID_DPI_FUND_WIDGET: {
481 Dimension d = GetStringBoundingBox(STR_FUND_INDUSTRY_BUILD_NEW_INDUSTRY);
482 d = maxdim(d, GetStringBoundingBox(STR_FUND_INDUSTRY_PROSPECT_NEW_INDUSTRY));
483 d = maxdim(d, GetStringBoundingBox(STR_FUND_INDUSTRY_FUND_NEW_INDUSTRY));
484 d.width += padding.width;
485 d.height += padding.height;
486 *size = maxdim(*size, d);
487 break;
492 void SetStringParameters(int widget) const override
494 switch (widget) {
495 case WID_DPI_FUND_WIDGET:
496 /* Raw industries might be prospected. Show this fact by changing the string
497 * In Editor, you just build, while ingame, or you fund or you prospect */
498 if (_game_mode == GM_EDITOR) {
499 /* We've chosen many random industries but no industries have been specified */
500 SetDParam(0, STR_FUND_INDUSTRY_BUILD_NEW_INDUSTRY);
501 } else {
502 const IndustrySpec *indsp = GetIndustrySpec(this->index[this->selected_index]);
503 SetDParam(0, (_settings_game.construction.raw_industry_construction == 2 && indsp->IsRawIndustry()) ? STR_FUND_INDUSTRY_PROSPECT_NEW_INDUSTRY : STR_FUND_INDUSTRY_FUND_NEW_INDUSTRY);
505 break;
509 void DrawWidget(const Rect &r, int widget) const override
511 switch (widget) {
512 case WID_DPI_MATRIX_WIDGET: {
513 uint text_left, text_right, icon_left, icon_right;
514 if (_current_text_dir == TD_RTL) {
515 icon_right = r.right - WD_MATRIX_RIGHT;
516 icon_left = icon_right - this->legend.width;
517 text_right = icon_left - ScaleFontTrad(7);
518 text_left = r.left + WD_MATRIX_LEFT;
519 } else {
520 icon_left = r.left + WD_MATRIX_LEFT;
521 icon_right = icon_left + this->legend.width;
522 text_left = icon_right + ScaleFontTrad(7);
523 text_right = r.right - WD_MATRIX_RIGHT;
526 /* Vertical offset for legend icon. */
527 int icon_top = (this->resize.step_height - this->legend.height + 1) / 2;
528 int icon_bottom = icon_top + this->legend.height;
530 int y = r.top;
531 for (uint16 i = 0; i < this->vscroll->GetCapacity() && i + this->vscroll->GetPosition() < this->count; i++) {
532 bool selected = this->selected_index == i + this->vscroll->GetPosition();
534 if (this->index[i + this->vscroll->GetPosition()] == INVALID_INDUSTRYTYPE) {
535 DrawString(text_left, text_right, y + WD_MATRIX_TOP, STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES, selected ? TC_WHITE : TC_ORANGE);
536 y += this->resize.step_height;
537 continue;
539 const IndustrySpec *indsp = GetIndustrySpec(this->index[i + this->vscroll->GetPosition()]);
541 /* Draw the name of the industry in white is selected, otherwise, in orange */
542 DrawString(text_left, text_right, y + WD_MATRIX_TOP, indsp->name, selected ? TC_WHITE : TC_ORANGE);
543 GfxFillRect(icon_left, y + icon_top, icon_right, y + icon_bottom, selected ? PC_WHITE : PC_BLACK);
544 GfxFillRect(icon_left + 1, y + icon_top + 1, icon_right - 1, y + icon_bottom - 1, indsp->map_colour);
546 y += this->resize.step_height;
548 break;
551 case WID_DPI_INFOPANEL: {
552 int y = r.top + WD_FRAMERECT_TOP;
553 int bottom = r.bottom - WD_FRAMERECT_BOTTOM;
554 int left = r.left + WD_FRAMERECT_LEFT;
555 int right = r.right - WD_FRAMERECT_RIGHT;
557 if (this->selected_type == INVALID_INDUSTRYTYPE) {
558 DrawStringMultiLine(left, right, y, bottom, STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES_TOOLTIP);
559 break;
562 const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
564 if (_game_mode != GM_EDITOR) {
565 SetDParam(0, indsp->GetConstructionCost());
566 DrawString(left, right, y, STR_FUND_INDUSTRY_INDUSTRY_BUILD_COST);
567 y += FONT_HEIGHT_NORMAL;
570 CargoSuffix cargo_suffix[lengthof(indsp->accepts_cargo)];
572 /* Draw the accepted cargoes, if any. Otherwise, will print "Nothing". */
573 GetAllCargoSuffixes(CARGOSUFFIX_IN, CST_FUND, nullptr, this->selected_type, indsp, indsp->accepts_cargo, cargo_suffix);
574 std::string cargostring = this->MakeCargoListString(indsp->accepts_cargo, cargo_suffix, lengthof(indsp->accepts_cargo), STR_INDUSTRY_VIEW_REQUIRES_N_CARGO);
575 y = DrawStringMultiLine(left, right, y, bottom, cargostring);
577 /* Draw the produced cargoes, if any. Otherwise, will print "Nothing". */
578 GetAllCargoSuffixes(CARGOSUFFIX_OUT, CST_FUND, nullptr, this->selected_type, indsp, indsp->produced_cargo, cargo_suffix);
579 cargostring = this->MakeCargoListString(indsp->produced_cargo, cargo_suffix, lengthof(indsp->produced_cargo), STR_INDUSTRY_VIEW_PRODUCES_N_CARGO);
580 y = DrawStringMultiLine(left, right, y, bottom, cargostring);
582 /* Get the additional purchase info text, if it has not already been queried. */
583 if (HasBit(indsp->callback_mask, CBM_IND_FUND_MORE_TEXT)) {
584 uint16 callback_res = GetIndustryCallback(CBID_INDUSTRY_FUND_MORE_TEXT, 0, 0, nullptr, this->selected_type, INVALID_TILE);
585 if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
586 if (callback_res > 0x400) {
587 ErrorUnknownCallbackResult(indsp->grf_prop.grffile->grfid, CBID_INDUSTRY_FUND_MORE_TEXT, callback_res);
588 } else {
589 StringID str = GetGRFStringID(indsp->grf_prop.grffile->grfid, 0xD000 + callback_res); // No. here's the new string
590 if (str != STR_UNDEFINED) {
591 StartTextRefStackUsage(indsp->grf_prop.grffile, 6);
592 DrawStringMultiLine(left, right, y, bottom, str, TC_YELLOW);
593 StopTextRefStackUsage();
598 break;
603 static void AskManyRandomIndustriesCallback(Window *w, bool confirmed)
605 if (!confirmed) return;
607 if (Town::GetNumItems() == 0) {
608 ShowErrorMessage(STR_ERROR_CAN_T_GENERATE_INDUSTRIES, STR_ERROR_MUST_FOUND_TOWN_FIRST, WL_INFO);
609 } else {
610 extern void GenerateIndustries();
611 Backup<bool> old_generating_world(_generating_world, true, FILE_LINE);
612 GenerateIndustries();
613 old_generating_world.Restore();
617 static void AskRemoveAllIndustriesCallback(Window *w, bool confirmed)
619 if (!confirmed) return;
621 for (Industry *industry : Industry::Iterate()) delete industry;
623 /* Clear farmland. */
624 for (TileIndex tile = 0; tile < MapSize(); tile++) {
625 if (IsTileType(tile, MP_CLEAR) && GetRawClearGround(tile) == CLEAR_FIELDS) {
626 MakeClear(tile, CLEAR_GRASS, 3);
630 MarkWholeScreenDirty();
633 void OnClick(Point pt, int widget, int click_count) override
635 switch (widget) {
636 case WID_DPI_CREATE_RANDOM_INDUSTRIES_WIDGET: {
637 assert(_game_mode == GM_EDITOR);
638 this->HandleButtonClick(WID_DPI_CREATE_RANDOM_INDUSTRIES_WIDGET);
639 ShowQuery(STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES_CAPTION, STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES_QUERY, nullptr, AskManyRandomIndustriesCallback);
640 break;
643 case WID_DPI_REMOVE_ALL_INDUSTRIES_WIDGET: {
644 assert(_game_mode == GM_EDITOR);
645 this->HandleButtonClick(WID_DPI_REMOVE_ALL_INDUSTRIES_WIDGET);
646 ShowQuery(STR_FUND_INDUSTRY_REMOVE_ALL_INDUSTRIES_CAPTION, STR_FUND_INDUSTRY_REMOVE_ALL_INDUSTRIES_QUERY, nullptr, AskRemoveAllIndustriesCallback);
647 break;
650 case WID_DPI_MATRIX_WIDGET: {
651 int y = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_DPI_MATRIX_WIDGET);
652 if (y < this->count) { // Is it within the boundaries of available data?
653 this->selected_index = y;
654 this->selected_type = this->index[y];
655 const IndustrySpec *indsp = (this->selected_type == INVALID_INDUSTRYTYPE) ? nullptr : GetIndustrySpec(this->selected_type);
657 this->SetDirty();
659 if (_thd.GetCallbackWnd() == this &&
660 ((_game_mode != GM_EDITOR && _settings_game.construction.raw_industry_construction == 2 && indsp != nullptr && indsp->IsRawIndustry()) ||
661 this->selected_type == INVALID_INDUSTRYTYPE ||
662 !this->enabled[this->selected_index])) {
663 /* Reset the button state if going to prospecting or "build many industries" */
664 this->RaiseButtons();
665 ResetObjectToPlace();
668 this->SetButtons();
669 if (this->enabled[this->selected_index] && click_count > 1) this->OnClick(pt, WID_DPI_FUND_WIDGET, 1);
671 break;
674 case WID_DPI_DISPLAY_WIDGET:
675 if (this->selected_type != INVALID_INDUSTRYTYPE) ShowIndustryCargoesWindow(this->selected_type);
676 break;
678 case WID_DPI_FUND_WIDGET: {
679 if (this->selected_type != INVALID_INDUSTRYTYPE) {
680 if (_game_mode != GM_EDITOR && _settings_game.construction.raw_industry_construction == 2 && GetIndustrySpec(this->selected_type)->IsRawIndustry()) {
681 DoCommandP(0, this->selected_type, InteractiveRandom(), CMD_BUILD_INDUSTRY | CMD_MSG(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY));
682 this->HandleButtonClick(WID_DPI_FUND_WIDGET);
683 } else {
684 HandlePlacePushButton(this, WID_DPI_FUND_WIDGET, SPR_CURSOR_INDUSTRY, HT_RECT);
687 break;
692 void OnResize() override
694 /* Adjust the number of items in the matrix depending of the resize */
695 this->vscroll->SetCapacityFromWidget(this, WID_DPI_MATRIX_WIDGET);
698 void OnPlaceObject(Point pt, TileIndex tile) override
700 bool success = true;
701 /* We do not need to protect ourselves against "Random Many Industries" in this mode */
702 const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
703 uint32 seed = InteractiveRandom();
704 uint32 layout_index = InteractiveRandomRange((uint32)indsp->layouts.size());
706 if (_game_mode == GM_EDITOR) {
707 /* Show error if no town exists at all */
708 if (Town::GetNumItems() == 0) {
709 SetDParam(0, indsp->name);
710 ShowErrorMessage(STR_ERROR_CAN_T_BUILD_HERE, STR_ERROR_MUST_FOUND_TOWN_FIRST, WL_INFO, pt.x, pt.y);
711 return;
714 Backup<CompanyID> cur_company(_current_company, OWNER_NONE, FILE_LINE);
715 Backup<bool> old_generating_world(_generating_world, true, FILE_LINE);
716 _ignore_restrictions = true;
718 DoCommandP(tile, (layout_index << 8) | this->selected_type, seed,
719 CMD_BUILD_INDUSTRY | CMD_MSG(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY), &CcBuildIndustry);
721 cur_company.Restore();
722 old_generating_world.Restore();
723 _ignore_restrictions = false;
724 } else {
725 success = DoCommandP(tile, (layout_index << 8) | this->selected_type, seed, CMD_BUILD_INDUSTRY | CMD_MSG(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY));
728 /* If an industry has been built, just reset the cursor and the system */
729 if (success && !_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
732 void OnHundredthTick() override
734 if (_game_mode == GM_EDITOR) return;
735 const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
737 if (indsp->enabled) {
738 bool call_back_result = GetIndustryProbabilityCallback(this->selected_type, IACT_USERCREATION, 1) > 0;
740 /* Only if result does match the previous state would it require a redraw. */
741 if (call_back_result != this->enabled[this->selected_index]) {
742 this->enabled[this->selected_index] = call_back_result;
743 this->SetButtons();
744 this->SetDirty();
749 void OnTimeout() override
751 this->RaiseButtons();
754 void OnPlaceObjectAbort() override
756 this->RaiseButtons();
760 * Some data on this window has become invalid.
761 * @param data Information about the changed data.
762 * @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.
764 void OnInvalidateData(int data = 0, bool gui_scope = true) override
766 if (!gui_scope) return;
767 this->SetupArrays();
769 const IndustrySpec *indsp = (this->selected_type == INVALID_INDUSTRYTYPE) ? nullptr : GetIndustrySpec(this->selected_type);
770 if (indsp == nullptr) this->enabled[this->selected_index] = _settings_game.difficulty.industry_density != ID_FUND_ONLY;
771 this->SetButtons();
772 this->SetDirty();
776 void ShowBuildIndustryWindow()
778 if (_game_mode != GM_EDITOR && !Company::IsValidID(_local_company)) return;
779 if (BringWindowToFrontById(WC_BUILD_INDUSTRY, 0)) return;
780 new BuildIndustryWindow();
783 static void UpdateIndustryProduction(Industry *i);
785 static inline bool IsProductionAlterable(const Industry *i)
787 const IndustrySpec *is = GetIndustrySpec(i->type);
788 bool has_prod = false;
789 for (size_t j = 0; j < lengthof(is->production_rate); j++) {
790 if (is->production_rate[j] != 0) {
791 has_prod = true;
792 break;
795 return ((_game_mode == GM_EDITOR || _cheats.setup_prod.value) &&
796 (has_prod || is->IsRawIndustry()) &&
797 !_networking);
800 class IndustryViewWindow : public Window
802 /** Modes for changing production */
803 enum Editability {
804 EA_NONE, ///< Not alterable
805 EA_MULTIPLIER, ///< Allow changing the production multiplier
806 EA_RATE, ///< Allow changing the production rates
809 /** Specific lines in the info panel */
810 enum InfoLine {
811 IL_NONE, ///< No line
812 IL_MULTIPLIER, ///< Production multiplier
813 IL_RATE1, ///< Production rate of cargo 1
814 IL_RATE2, ///< Production rate of cargo 2
817 Editability editable; ///< Mode for changing production
818 InfoLine editbox_line; ///< The line clicked to open the edit box
819 InfoLine clicked_line; ///< The line of the button that has been clicked
820 byte clicked_button; ///< The button that has been clicked (to raise)
821 int production_offset_y; ///< The offset of the production texts/buttons
822 int info_height; ///< Height needed for the #WID_IV_INFO panel
824 public:
825 IndustryViewWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
827 this->flags |= WF_DISABLE_VP_SCROLL;
828 this->editbox_line = IL_NONE;
829 this->clicked_line = IL_NONE;
830 this->clicked_button = 0;
831 this->info_height = WD_FRAMERECT_TOP + 2 * FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM + 1; // Info panel has at least two lines text.
833 this->InitNested(window_number);
834 NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_IV_VIEWPORT);
835 nvp->InitializeViewport(this, Industry::Get(window_number)->location.GetCenterTile(), ZOOM_LVL_INDUSTRY);
837 this->InvalidateData();
840 void OnPaint() override
842 this->DrawWidgets();
844 if (this->IsShaded()) return; // Don't draw anything when the window is shaded.
846 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_IV_INFO);
847 uint expected = this->DrawInfo(nwi->pos_x, nwi->pos_x + nwi->current_x - 1, nwi->pos_y) - nwi->pos_y;
848 if (expected > nwi->current_y - 1) {
849 this->info_height = expected + 1;
850 this->ReInit();
851 return;
856 * Draw the text in the #WID_IV_INFO panel.
857 * @param left Left edge of the panel.
858 * @param right Right edge of the panel.
859 * @param top Top edge of the panel.
860 * @return Expected position of the bottom edge of the panel.
862 int DrawInfo(uint left, uint right, uint top)
864 Industry *i = Industry::Get(this->window_number);
865 const IndustrySpec *ind = GetIndustrySpec(i->type);
866 int y = top + WD_FRAMERECT_TOP;
867 bool first = true;
868 bool has_accept = false;
870 if (i->prod_level == PRODLEVEL_CLOSURE) {
871 DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_INDUSTRY_ANNOUNCED_CLOSURE);
872 y += 2 * FONT_HEIGHT_NORMAL;
875 CargoSuffix cargo_suffix[lengthof(i->accepts_cargo)];
876 GetAllCargoSuffixes(CARGOSUFFIX_IN, CST_VIEW, i, i->type, ind, i->accepts_cargo, cargo_suffix);
877 bool stockpiling = HasBit(ind->callback_mask, CBM_IND_PRODUCTION_CARGO_ARRIVAL) || HasBit(ind->callback_mask, CBM_IND_PRODUCTION_256_TICKS);
879 uint left_side = left + WD_FRAMERECT_LEFT * 4; // Indent accepted cargoes.
880 for (byte j = 0; j < lengthof(i->accepts_cargo); j++) {
881 if (i->accepts_cargo[j] == CT_INVALID) continue;
882 has_accept = true;
883 if (first) {
884 DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_REQUIRES);
885 y += FONT_HEIGHT_NORMAL;
886 first = false;
888 SetDParam(0, CargoSpec::Get(i->accepts_cargo[j])->name);
889 SetDParam(1, i->accepts_cargo[j]);
890 SetDParam(2, i->incoming_cargo_waiting[j]);
891 SetDParamStr(3, "");
892 StringID str = STR_NULL;
893 switch (cargo_suffix[j].display) {
894 case CSD_CARGO_AMOUNT_TEXT:
895 SetDParamStr(3, cargo_suffix[j].text);
896 FALLTHROUGH;
897 case CSD_CARGO_AMOUNT:
898 str = stockpiling ? STR_INDUSTRY_VIEW_ACCEPT_CARGO_AMOUNT : STR_INDUSTRY_VIEW_ACCEPT_CARGO;
899 break;
901 case CSD_CARGO_TEXT:
902 SetDParamStr(3, cargo_suffix[j].text);
903 FALLTHROUGH;
904 case CSD_CARGO:
905 str = STR_INDUSTRY_VIEW_ACCEPT_CARGO;
906 break;
908 default:
909 NOT_REACHED();
911 DrawString(left_side, right - WD_FRAMERECT_RIGHT, y, str);
912 y += FONT_HEIGHT_NORMAL;
915 GetAllCargoSuffixes(CARGOSUFFIX_OUT, CST_VIEW, i, i->type, ind, i->produced_cargo, cargo_suffix);
916 first = true;
917 for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
918 if (i->produced_cargo[j] == CT_INVALID) continue;
919 if (first) {
920 if (has_accept) y += WD_PAR_VSEP_WIDE;
921 DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_PRODUCTION_LAST_MONTH_TITLE);
922 y += FONT_HEIGHT_NORMAL;
923 if (this->editable == EA_RATE) this->production_offset_y = y;
924 first = false;
927 SetDParam(0, i->produced_cargo[j]);
928 SetDParam(1, i->last_month_production[j]);
929 SetDParamStr(2, cargo_suffix[j].text);
930 SetDParam(3, ToPercent8(i->last_month_pct_transported[j]));
931 uint x = left + WD_FRAMETEXT_LEFT + (this->editable == EA_RATE ? SETTING_BUTTON_WIDTH + 10 : 0);
932 DrawString(x, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_TRANSPORTED);
933 /* Let's put out those buttons.. */
934 if (this->editable == EA_RATE) {
935 DrawArrowButtons(left + WD_FRAMETEXT_LEFT, y, COLOUR_YELLOW, (this->clicked_line == IL_RATE1 + j) ? this->clicked_button : 0,
936 i->production_rate[j] > 0, i->production_rate[j] < 255);
938 y += FONT_HEIGHT_NORMAL;
941 /* Display production multiplier if editable */
942 if (this->editable == EA_MULTIPLIER) {
943 y += WD_PAR_VSEP_WIDE;
944 this->production_offset_y = y;
945 SetDParam(0, RoundDivSU(i->prod_level * 100, PRODLEVEL_DEFAULT));
946 uint x = left + WD_FRAMETEXT_LEFT + SETTING_BUTTON_WIDTH + 10;
947 DrawString(x, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_PRODUCTION_LEVEL);
948 DrawArrowButtons(left + WD_FRAMETEXT_LEFT, y, COLOUR_YELLOW, (this->clicked_line == IL_MULTIPLIER) ? this->clicked_button : 0,
949 i->prod_level > PRODLEVEL_MINIMUM, i->prod_level < PRODLEVEL_MAXIMUM);
950 y += FONT_HEIGHT_NORMAL;
953 /* Get the extra message for the GUI */
954 if (HasBit(ind->callback_mask, CBM_IND_WINDOW_MORE_TEXT)) {
955 uint16 callback_res = GetIndustryCallback(CBID_INDUSTRY_WINDOW_MORE_TEXT, 0, 0, i, i->type, i->location.tile);
956 if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
957 if (callback_res > 0x400) {
958 ErrorUnknownCallbackResult(ind->grf_prop.grffile->grfid, CBID_INDUSTRY_WINDOW_MORE_TEXT, callback_res);
959 } else {
960 StringID message = GetGRFStringID(ind->grf_prop.grffile->grfid, 0xD000 + callback_res);
961 if (message != STR_NULL && message != STR_UNDEFINED) {
962 y += WD_PAR_VSEP_WIDE;
964 StartTextRefStackUsage(ind->grf_prop.grffile, 6);
965 /* Use all the available space left from where we stand up to the
966 * end of the window. We ALSO enlarge the window if needed, so we
967 * can 'go' wild with the bottom of the window. */
968 y = DrawStringMultiLine(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, UINT16_MAX, message, TC_BLACK);
969 StopTextRefStackUsage();
975 if (!i->text.empty()) {
976 SetDParamStr(0, i->text);
977 y += WD_PAR_VSEP_WIDE;
978 y = DrawStringMultiLine(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, UINT16_MAX, STR_JUST_RAW_STRING, TC_BLACK);
981 return y + WD_FRAMERECT_BOTTOM;
984 void SetStringParameters(int widget) const override
986 if (widget == WID_IV_CAPTION) SetDParam(0, this->window_number);
989 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
991 if (widget == WID_IV_INFO) size->height = this->info_height;
994 void OnClick(Point pt, int widget, int click_count) override
996 switch (widget) {
997 case WID_IV_INFO: {
998 Industry *i = Industry::Get(this->window_number);
999 InfoLine line = IL_NONE;
1001 switch (this->editable) {
1002 case EA_NONE: break;
1004 case EA_MULTIPLIER:
1005 if (IsInsideBS(pt.y, this->production_offset_y, FONT_HEIGHT_NORMAL)) line = IL_MULTIPLIER;
1006 break;
1008 case EA_RATE:
1009 if (pt.y >= this->production_offset_y) {
1010 int row = (pt.y - this->production_offset_y) / FONT_HEIGHT_NORMAL;
1011 for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
1012 if (i->produced_cargo[j] == CT_INVALID) continue;
1013 row--;
1014 if (row < 0) {
1015 line = (InfoLine)(IL_RATE1 + j);
1016 break;
1020 break;
1022 if (line == IL_NONE) return;
1024 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(widget);
1025 int left = nwi->pos_x + WD_FRAMETEXT_LEFT;
1026 int right = nwi->pos_x + nwi->current_x - 1 - WD_FRAMERECT_RIGHT;
1027 if (IsInsideMM(pt.x, left, left + SETTING_BUTTON_WIDTH)) {
1028 /* Clicked buttons, decrease or increase production */
1029 byte button = (pt.x < left + SETTING_BUTTON_WIDTH / 2) ? 1 : 2;
1030 switch (this->editable) {
1031 case EA_MULTIPLIER:
1032 if (button == 1) {
1033 if (i->prod_level <= PRODLEVEL_MINIMUM) return;
1034 i->prod_level = std::max<uint>(i->prod_level / 2, PRODLEVEL_MINIMUM);
1035 } else {
1036 if (i->prod_level >= PRODLEVEL_MAXIMUM) return;
1037 i->prod_level = std::min<uint>(i->prod_level * 2, PRODLEVEL_MAXIMUM);
1039 break;
1041 case EA_RATE:
1042 if (button == 1) {
1043 if (i->production_rate[line - IL_RATE1] <= 0) return;
1044 i->production_rate[line - IL_RATE1] = std::max(i->production_rate[line - IL_RATE1] / 2, 0);
1045 } else {
1046 if (i->production_rate[line - IL_RATE1] >= 255) return;
1047 /* a zero production industry is unlikely to give anything but zero, so push it a little bit */
1048 int new_prod = i->production_rate[line - IL_RATE1] == 0 ? 1 : i->production_rate[line - IL_RATE1] * 2;
1049 i->production_rate[line - IL_RATE1] = std::min<uint>(new_prod, 255);
1051 break;
1053 default: NOT_REACHED();
1056 UpdateIndustryProduction(i);
1057 this->SetDirty();
1058 this->SetTimeout();
1059 this->clicked_line = line;
1060 this->clicked_button = button;
1061 } else if (IsInsideMM(pt.x, left + SETTING_BUTTON_WIDTH + 10, right)) {
1062 /* clicked the text */
1063 this->editbox_line = line;
1064 switch (this->editable) {
1065 case EA_MULTIPLIER:
1066 SetDParam(0, RoundDivSU(i->prod_level * 100, PRODLEVEL_DEFAULT));
1067 ShowQueryString(STR_JUST_INT, STR_CONFIG_GAME_PRODUCTION_LEVEL, 10, this, CS_ALPHANUMERAL, QSF_NONE);
1068 break;
1070 case EA_RATE:
1071 SetDParam(0, i->production_rate[line - IL_RATE1] * 8);
1072 ShowQueryString(STR_JUST_INT, STR_CONFIG_GAME_PRODUCTION, 10, this, CS_ALPHANUMERAL, QSF_NONE);
1073 break;
1075 default: NOT_REACHED();
1078 break;
1081 case WID_IV_GOTO: {
1082 Industry *i = Industry::Get(this->window_number);
1083 if (_ctrl_pressed) {
1084 ShowExtraViewportWindow(i->location.GetCenterTile());
1085 } else {
1086 ScrollMainWindowToTile(i->location.GetCenterTile());
1088 break;
1091 case WID_IV_DISPLAY: {
1092 Industry *i = Industry::Get(this->window_number);
1093 ShowIndustryCargoesWindow(i->type);
1094 break;
1099 void OnTimeout() override
1101 this->clicked_line = IL_NONE;
1102 this->clicked_button = 0;
1103 this->SetDirty();
1106 void OnResize() override
1108 if (this->viewport != nullptr) {
1109 NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_IV_VIEWPORT);
1110 nvp->UpdateViewportCoordinates(this);
1112 ScrollWindowToTile(Industry::Get(this->window_number)->location.GetCenterTile(), this, true); // Re-center viewport.
1116 void OnQueryTextFinished(char *str) override
1118 if (StrEmpty(str)) return;
1120 Industry *i = Industry::Get(this->window_number);
1121 uint value = atoi(str);
1122 switch (this->editbox_line) {
1123 case IL_NONE: NOT_REACHED();
1125 case IL_MULTIPLIER:
1126 i->prod_level = ClampU(RoundDivSU(value * PRODLEVEL_DEFAULT, 100), PRODLEVEL_MINIMUM, PRODLEVEL_MAXIMUM);
1127 break;
1129 default:
1130 i->production_rate[this->editbox_line - IL_RATE1] = ClampU(RoundDivSU(value, 8), 0, 255);
1131 break;
1133 UpdateIndustryProduction(i);
1134 this->SetDirty();
1138 * Some data on this window has become invalid.
1139 * @param data Information about the changed data.
1140 * @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.
1142 void OnInvalidateData(int data = 0, bool gui_scope = true) override
1144 if (!gui_scope) return;
1145 const Industry *i = Industry::Get(this->window_number);
1146 if (IsProductionAlterable(i)) {
1147 const IndustrySpec *ind = GetIndustrySpec(i->type);
1148 this->editable = ind->UsesOriginalEconomy() ? EA_MULTIPLIER : EA_RATE;
1149 } else {
1150 this->editable = EA_NONE;
1154 bool IsNewGRFInspectable() const override
1156 return ::IsNewGRFInspectable(GSF_INDUSTRIES, this->window_number);
1159 void ShowNewGRFInspectWindow() const override
1161 ::ShowNewGRFInspectWindow(GSF_INDUSTRIES, this->window_number);
1165 static void UpdateIndustryProduction(Industry *i)
1167 const IndustrySpec *indspec = GetIndustrySpec(i->type);
1168 if (indspec->UsesOriginalEconomy()) i->RecomputeProductionMultipliers();
1170 for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
1171 if (i->produced_cargo[j] != CT_INVALID) {
1172 i->last_month_production[j] = 8 * i->production_rate[j];
1177 /** Widget definition of the view industry gui */
1178 static const NWidgetPart _nested_industry_view_widgets[] = {
1179 NWidget(NWID_HORIZONTAL),
1180 NWidget(WWT_CLOSEBOX, COLOUR_CREAM),
1181 NWidget(WWT_CAPTION, COLOUR_CREAM, WID_IV_CAPTION), SetDataTip(STR_INDUSTRY_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1182 NWidget(WWT_PUSHIMGBTN, COLOUR_CREAM, WID_IV_GOTO), SetMinimalSize(12, 14), SetDataTip(SPR_GOTO_LOCATION, STR_INDUSTRY_VIEW_LOCATION_TOOLTIP),
1183 NWidget(WWT_DEBUGBOX, COLOUR_CREAM),
1184 NWidget(WWT_SHADEBOX, COLOUR_CREAM),
1185 NWidget(WWT_DEFSIZEBOX, COLOUR_CREAM),
1186 NWidget(WWT_STICKYBOX, COLOUR_CREAM),
1187 EndContainer(),
1188 NWidget(WWT_PANEL, COLOUR_CREAM),
1189 NWidget(WWT_INSET, COLOUR_CREAM), SetPadding(2, 2, 2, 2),
1190 NWidget(NWID_VIEWPORT, INVALID_COLOUR, WID_IV_VIEWPORT), SetMinimalSize(254, 86), SetFill(1, 0), SetResize(1, 1),
1191 EndContainer(),
1192 EndContainer(),
1193 NWidget(WWT_PANEL, COLOUR_CREAM, WID_IV_INFO), SetMinimalSize(260, 2), SetResize(1, 0),
1194 EndContainer(),
1195 NWidget(NWID_HORIZONTAL),
1196 NWidget(WWT_PUSHTXTBTN, COLOUR_CREAM, WID_IV_DISPLAY), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_INDUSTRY_DISPLAY_CHAIN, STR_INDUSTRY_DISPLAY_CHAIN_TOOLTIP),
1197 NWidget(WWT_RESIZEBOX, COLOUR_CREAM),
1198 EndContainer(),
1201 /** Window definition of the view industry gui */
1202 static WindowDesc _industry_view_desc(
1203 WDP_AUTO, "view_industry", 260, 120,
1204 WC_INDUSTRY_VIEW, WC_NONE,
1206 _nested_industry_view_widgets, lengthof(_nested_industry_view_widgets)
1209 void ShowIndustryViewWindow(int industry)
1211 AllocateWindowDescFront<IndustryViewWindow>(&_industry_view_desc, industry);
1214 /** Widget definition of the industry directory gui */
1215 static const NWidgetPart _nested_industry_directory_widgets[] = {
1216 NWidget(NWID_HORIZONTAL),
1217 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
1218 NWidget(WWT_CAPTION, COLOUR_BROWN), SetDataTip(STR_INDUSTRY_DIRECTORY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1219 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
1220 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
1221 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
1222 EndContainer(),
1223 NWidget(NWID_HORIZONTAL),
1224 NWidget(NWID_VERTICAL),
1225 NWidget(NWID_HORIZONTAL),
1226 NWidget(WWT_TEXTBTN, COLOUR_BROWN, WID_ID_DROPDOWN_ORDER), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
1227 NWidget(WWT_DROPDOWN, COLOUR_BROWN, WID_ID_DROPDOWN_CRITERIA), SetDataTip(STR_JUST_STRING, STR_TOOLTIP_SORT_CRITERIA),
1228 NWidget(WWT_DROPDOWN, COLOUR_BROWN, WID_ID_FILTER_BY_ACC_CARGO), SetMinimalSize(225, 12), SetFill(0, 1), SetDataTip(STR_INDUSTRY_DIRECTORY_ACCEPTED_CARGO_FILTER, STR_TOOLTIP_FILTER_CRITERIA),
1229 NWidget(WWT_DROPDOWN, COLOUR_BROWN, WID_ID_FILTER_BY_PROD_CARGO), SetMinimalSize(225, 12), SetFill(0, 1), SetDataTip(STR_INDUSTRY_DIRECTORY_PRODUCED_CARGO_FILTER, STR_TOOLTIP_FILTER_CRITERIA),
1230 NWidget(WWT_PANEL, COLOUR_BROWN), SetResize(1, 0), EndContainer(),
1231 EndContainer(),
1232 NWidget(WWT_PANEL, COLOUR_BROWN, WID_ID_INDUSTRY_LIST), SetDataTip(0x0, STR_INDUSTRY_DIRECTORY_LIST_CAPTION), SetResize(1, 1), SetScrollbar(WID_ID_SCROLLBAR), EndContainer(),
1233 EndContainer(),
1234 NWidget(NWID_VERTICAL),
1235 NWidget(NWID_VSCROLLBAR, COLOUR_BROWN, WID_ID_SCROLLBAR),
1236 NWidget(WWT_RESIZEBOX, COLOUR_BROWN),
1237 EndContainer(),
1238 EndContainer(),
1241 typedef GUIList<const Industry *, const std::pair<CargoID, CargoID> &> GUIIndustryList;
1243 /** Special cargo filter criteria */
1244 enum CargoFilterSpecialType {
1245 CF_ANY = CT_NO_REFIT, ///< Show all industries (i.e. no filtering)
1246 CF_NONE = CT_INVALID, ///< Show only industries which do not produce/accept cargo
1249 /** Cargo filter functions */
1251 * Check whether an industry accepts and produces a certain cargo pair.
1252 * @param industry The industry whose cargoes will being checked.
1253 * @param cargoes The accepted and produced cargo pair to look for.
1254 * @return bool Whether the given cargoes accepted and produced by the industry.
1256 static bool CDECL CargoFilter(const Industry * const *industry, const std::pair<CargoID, CargoID> &cargoes)
1258 auto accepted_cargo = cargoes.first;
1259 auto produced_cargo = cargoes.second;
1261 bool accepted_cargo_matches;
1263 switch (accepted_cargo) {
1264 case CF_ANY:
1265 accepted_cargo_matches = true;
1266 break;
1268 case CF_NONE:
1269 accepted_cargo_matches = std::all_of(std::begin((*industry)->accepts_cargo), std::end((*industry)->accepts_cargo), [](CargoID cargo) {
1270 return cargo == CT_INVALID;
1272 break;
1274 default:
1275 const auto &ac = (*industry)->accepts_cargo;
1276 accepted_cargo_matches = std::find(std::begin(ac), std::end(ac), accepted_cargo) != std::end(ac);
1277 break;
1280 bool produced_cargo_matches;
1282 switch (produced_cargo) {
1283 case CF_ANY:
1284 produced_cargo_matches = true;
1285 break;
1287 case CF_NONE:
1288 produced_cargo_matches = std::all_of(std::begin((*industry)->produced_cargo), std::end((*industry)->produced_cargo), [](CargoID cargo) {
1289 return cargo == CT_INVALID;
1291 break;
1293 default:
1294 const auto &pc = (*industry)->produced_cargo;
1295 produced_cargo_matches = std::find(std::begin(pc), std::end(pc), produced_cargo) != std::end(pc);
1296 break;
1299 return accepted_cargo_matches && produced_cargo_matches;
1302 static GUIIndustryList::FilterFunction * const _filter_funcs[] = { &CargoFilter };
1306 * The list of industries.
1308 class IndustryDirectoryWindow : public Window {
1309 protected:
1310 /* Runtime saved values */
1311 static Listing last_sorting;
1313 /* Constants for sorting industries */
1314 static const StringID sorter_names[];
1315 static GUIIndustryList::SortFunction * const sorter_funcs[];
1317 GUIIndustryList industries;
1318 Scrollbar *vscroll;
1320 CargoID cargo_filter[NUM_CARGO + 2]; ///< Available cargo filters; CargoID or CF_ANY or CF_NONE
1321 StringID cargo_filter_texts[NUM_CARGO + 3]; ///< Texts for filter_cargo, terminated by INVALID_STRING_ID
1322 byte produced_cargo_filter_criteria; ///< Selected produced cargo filter index
1323 byte accepted_cargo_filter_criteria; ///< Selected accepted cargo filter index
1324 static CargoID produced_cargo_filter;
1326 enum class SorterType : uint8 {
1327 IDW_SORT_BY_NAME, ///< Sorter type to sort by name
1328 IDW_SORT_BY_TYPE, ///< Sorter type to sort by type
1329 IDW_SORT_BY_PRODUCTION, ///< Sorter type to sort by production amount
1330 IDW_SORT_BY_TRANSPORTED, ///< Sorter type to sort by transported percentage
1334 * Set cargo filter list item index.
1335 * @param index The index of the cargo to be set
1337 void SetProducedCargoFilterIndex(byte index)
1339 if (this->produced_cargo_filter_criteria != index) {
1340 this->produced_cargo_filter_criteria = index;
1341 /* deactivate filter if criteria is 'Show All', activate it otherwise */
1342 bool is_filtering_necessary = this->cargo_filter[this->produced_cargo_filter_criteria] != CF_ANY || this->cargo_filter[this->accepted_cargo_filter_criteria] != CF_ANY;
1344 this->industries.SetFilterState(is_filtering_necessary);
1345 this->industries.SetFilterType(0);
1346 this->industries.ForceRebuild();
1351 * Set cargo filter list item index.
1352 * @param index The index of the cargo to be set
1354 void SetAcceptedCargoFilterIndex(byte index)
1356 if (this->accepted_cargo_filter_criteria != index) {
1357 this->accepted_cargo_filter_criteria = index;
1358 /* deactivate filter if criteria is 'Show All', activate it otherwise */
1359 bool is_filtering_necessary = this->cargo_filter[this->produced_cargo_filter_criteria] != CF_ANY || this->cargo_filter[this->accepted_cargo_filter_criteria] != CF_ANY;
1361 this->industries.SetFilterState(is_filtering_necessary);
1362 this->industries.SetFilterType(0);
1363 this->industries.ForceRebuild();
1368 * Populate the filter list and set the cargo filter criteria.
1370 void SetCargoFilterArray()
1372 byte filter_items = 0;
1374 /* Add item for disabling filtering. */
1375 this->cargo_filter[filter_items] = CF_ANY;
1376 this->cargo_filter_texts[filter_items] = STR_INDUSTRY_DIRECTORY_FILTER_ALL_TYPES;
1377 this->produced_cargo_filter_criteria = filter_items;
1378 this->accepted_cargo_filter_criteria = filter_items;
1379 filter_items++;
1381 /* Add item for industries not producing anything, e.g. power plants */
1382 this->cargo_filter[filter_items] = CF_NONE;
1383 this->cargo_filter_texts[filter_items] = STR_INDUSTRY_DIRECTORY_FILTER_NONE;
1384 filter_items++;
1386 /* Collect available cargo types for filtering. */
1387 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
1388 this->cargo_filter[filter_items] = cs->Index();
1389 this->cargo_filter_texts[filter_items] = cs->name;
1390 filter_items++;
1393 /* Terminate the filter list. */
1394 this->cargo_filter_texts[filter_items] = INVALID_STRING_ID;
1396 this->industries.SetFilterFuncs(_filter_funcs);
1398 bool is_filtering_necessary = this->cargo_filter[this->produced_cargo_filter_criteria] != CF_ANY || this->cargo_filter[this->accepted_cargo_filter_criteria] != CF_ANY;
1400 this->industries.SetFilterState(is_filtering_necessary);
1403 /** (Re)Build industries list */
1404 void BuildSortIndustriesList()
1406 if (this->industries.NeedRebuild()) {
1407 this->industries.clear();
1409 for (const Industry *i : Industry::Iterate()) {
1410 this->industries.push_back(i);
1413 this->industries.shrink_to_fit();
1414 this->industries.RebuildDone();
1417 auto filter = std::make_pair(this->cargo_filter[this->accepted_cargo_filter_criteria],
1418 this->cargo_filter[this->produced_cargo_filter_criteria]);
1420 this->industries.Filter(filter);
1422 IndustryDirectoryWindow::produced_cargo_filter = this->cargo_filter[this->produced_cargo_filter_criteria];
1423 this->industries.Sort();
1425 this->vscroll->SetCount((uint)this->industries.size()); // Update scrollbar as well.
1427 this->SetDirty();
1431 * Returns percents of cargo transported if industry produces this cargo, else -1
1433 * @param i industry to check
1434 * @param id cargo slot
1435 * @return percents of cargo transported, or -1 if industry doesn't use this cargo slot
1437 static inline int GetCargoTransportedPercentsIfValid(const Industry *i, uint id)
1439 assert(id < lengthof(i->produced_cargo));
1441 if (i->produced_cargo[id] == CT_INVALID) return -1;
1442 return ToPercent8(i->last_month_pct_transported[id]);
1446 * Returns value representing industry's transported cargo
1447 * percentage for industry sorting
1449 * @param i industry to check
1450 * @return value used for sorting
1452 static int GetCargoTransportedSortValue(const Industry *i)
1454 CargoID filter = IndustryDirectoryWindow::produced_cargo_filter;
1455 if (filter == CF_NONE) return 0;
1457 int percentage = 0, produced_cargo_count = 0;
1458 for (uint id = 0; id < lengthof(i->produced_cargo); id++) {
1459 if (filter == CF_ANY) {
1460 int transported = GetCargoTransportedPercentsIfValid(i, id);
1461 if (transported != -1) {
1462 produced_cargo_count++;
1463 percentage += transported;
1465 if (produced_cargo_count == 0 && id == lengthof(i->produced_cargo) - 1 && percentage == 0) {
1466 return transported;
1468 } else if (filter == i->produced_cargo[id]) {
1469 return GetCargoTransportedPercentsIfValid(i, id);
1473 if (produced_cargo_count == 0) return percentage;
1474 return percentage / produced_cargo_count;
1477 /** Sort industries by name */
1478 static bool IndustryNameSorter(const Industry * const &a, const Industry * const &b)
1480 int r = strnatcmp(a->GetCachedName(), b->GetCachedName()); // Sort by name (natural sorting).
1481 if (r == 0) return a->index < b->index;
1482 return r < 0;
1485 /** Sort industries by type and name */
1486 static bool IndustryTypeSorter(const Industry * const &a, const Industry * const &b)
1488 int it_a = 0;
1489 while (it_a != NUM_INDUSTRYTYPES && a->type != _sorted_industry_types[it_a]) it_a++;
1490 int it_b = 0;
1491 while (it_b != NUM_INDUSTRYTYPES && b->type != _sorted_industry_types[it_b]) it_b++;
1492 int r = it_a - it_b;
1493 return (r == 0) ? IndustryNameSorter(a, b) : r < 0;
1496 /** Sort industries by production and name */
1497 static bool IndustryProductionSorter(const Industry * const &a, const Industry * const &b)
1499 CargoID filter = IndustryDirectoryWindow::produced_cargo_filter;
1500 if (filter == CF_NONE) return IndustryTypeSorter(a, b);
1502 uint prod_a = 0, prod_b = 0;
1503 for (uint i = 0; i < lengthof(a->produced_cargo); i++) {
1504 if (filter == CF_ANY) {
1505 if (a->produced_cargo[i] != CT_INVALID) prod_a += a->last_month_production[i];
1506 if (b->produced_cargo[i] != CT_INVALID) prod_b += b->last_month_production[i];
1507 } else {
1508 if (a->produced_cargo[i] == filter) prod_a += a->last_month_production[i];
1509 if (b->produced_cargo[i] == filter) prod_b += b->last_month_production[i];
1512 int r = prod_a - prod_b;
1514 return (r == 0) ? IndustryTypeSorter(a, b) : r < 0;
1517 /** Sort industries by transported cargo and name */
1518 static bool IndustryTransportedCargoSorter(const Industry * const &a, const Industry * const &b)
1520 int r = GetCargoTransportedSortValue(a) - GetCargoTransportedSortValue(b);
1521 return (r == 0) ? IndustryNameSorter(a, b) : r < 0;
1525 * Get the StringID to draw and set the appropriate DParams.
1526 * @param i the industry to get the StringID of.
1527 * @return the StringID.
1529 StringID GetIndustryString(const Industry *i) const
1531 const IndustrySpec *indsp = GetIndustrySpec(i->type);
1532 byte p = 0;
1534 /* Industry name */
1535 SetDParam(p++, i->index);
1537 static CargoSuffix cargo_suffix[lengthof(i->produced_cargo)];
1538 GetAllCargoSuffixes(CARGOSUFFIX_OUT, CST_DIR, i, i->type, indsp, i->produced_cargo, cargo_suffix);
1540 /* Get industry productions (CargoID, production, suffix, transported) */
1541 struct CargoInfo {
1542 CargoID cargo_id;
1543 uint16 production;
1544 const char *suffix;
1545 uint transported;
1547 std::vector<CargoInfo> cargos;
1549 for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
1550 if (i->produced_cargo[j] == CT_INVALID) continue;
1551 cargos.push_back({ i->produced_cargo[j], i->last_month_production[j], cargo_suffix[j].text, ToPercent8(i->last_month_pct_transported[j]) });
1554 switch (static_cast<IndustryDirectoryWindow::SorterType>(this->industries.SortType())) {
1555 case IndustryDirectoryWindow::SorterType::IDW_SORT_BY_NAME:
1556 case IndustryDirectoryWindow::SorterType::IDW_SORT_BY_TYPE:
1557 case IndustryDirectoryWindow::SorterType::IDW_SORT_BY_PRODUCTION:
1558 /* Sort by descending production, then descending transported */
1559 std::sort(cargos.begin(), cargos.end(), [](const CargoInfo &a, const CargoInfo &b) {
1560 if (a.production != b.production) return a.production > b.production;
1561 return a.transported > b.transported;
1563 break;
1565 case IndustryDirectoryWindow::SorterType::IDW_SORT_BY_TRANSPORTED:
1566 /* Sort by descending transported, then descending production */
1567 std::sort(cargos.begin(), cargos.end(), [](const CargoInfo &a, const CargoInfo &b) {
1568 if (a.transported != b.transported) return a.transported > b.transported;
1569 return a.production > b.production;
1571 break;
1574 /* If the produced cargo filter is active then move the filtered cargo to the beginning of the list,
1575 * because this is the one the player interested in, and that way it is not hidden in the 'n' more cargos */
1576 const CargoID cid = this->cargo_filter[this->produced_cargo_filter_criteria];
1577 if (cid != CF_ANY && cid != CF_NONE) {
1578 auto filtered_ci = std::find_if(cargos.begin(), cargos.end(), [cid](const CargoInfo &ci) -> bool {
1579 return ci.cargo_id == cid;
1581 if (filtered_ci != cargos.end()) {
1582 std::rotate(cargos.begin(), filtered_ci, filtered_ci + 1);
1586 /* Display first 3 cargos */
1587 for (size_t j = 0; j < std::min<size_t>(3, cargos.size()); j++) {
1588 CargoInfo ci = cargos[j];
1589 SetDParam(p++, STR_INDUSTRY_DIRECTORY_ITEM_INFO);
1590 SetDParam(p++, ci.cargo_id);
1591 SetDParam(p++, ci.production);
1592 SetDParamStr(p++, ci.suffix);
1593 SetDParam(p++, ci.transported);
1596 /* Undisplayed cargos if any */
1597 SetDParam(p++, cargos.size() - 3);
1599 /* Drawing the right string */
1600 switch (cargos.size()) {
1601 case 0: return STR_INDUSTRY_DIRECTORY_ITEM_NOPROD;
1602 case 1: return STR_INDUSTRY_DIRECTORY_ITEM_PROD1;
1603 case 2: return STR_INDUSTRY_DIRECTORY_ITEM_PROD2;
1604 case 3: return STR_INDUSTRY_DIRECTORY_ITEM_PROD3;
1605 default: return STR_INDUSTRY_DIRECTORY_ITEM_PRODMORE;
1609 public:
1610 IndustryDirectoryWindow(WindowDesc *desc, WindowNumber number) : Window(desc)
1612 this->CreateNestedTree();
1613 this->vscroll = this->GetScrollbar(WID_ID_SCROLLBAR);
1615 this->industries.SetListing(this->last_sorting);
1616 this->industries.SetSortFuncs(IndustryDirectoryWindow::sorter_funcs);
1617 this->industries.ForceRebuild();
1618 this->BuildSortIndustriesList();
1620 this->FinishInitNested(0);
1623 ~IndustryDirectoryWindow()
1625 this->last_sorting = this->industries.GetListing();
1628 void OnInit() override
1630 this->SetCargoFilterArray();
1633 void SetStringParameters(int widget) const override
1635 switch (widget) {
1636 case WID_ID_DROPDOWN_CRITERIA:
1637 SetDParam(0, IndustryDirectoryWindow::sorter_names[this->industries.SortType()]);
1638 break;
1640 case WID_ID_FILTER_BY_ACC_CARGO:
1641 SetDParam(0, this->cargo_filter_texts[this->accepted_cargo_filter_criteria]);
1642 break;
1644 case WID_ID_FILTER_BY_PROD_CARGO:
1645 SetDParam(0, this->cargo_filter_texts[this->produced_cargo_filter_criteria]);
1646 break;
1650 void DrawWidget(const Rect &r, int widget) const override
1652 switch (widget) {
1653 case WID_ID_DROPDOWN_ORDER:
1654 this->DrawSortButtonState(widget, this->industries.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
1655 break;
1657 case WID_ID_INDUSTRY_LIST: {
1658 int n = 0;
1659 int y = r.top + WD_FRAMERECT_TOP;
1660 if (this->industries.size() == 0) {
1661 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_DIRECTORY_NONE);
1662 break;
1664 TextColour tc;
1665 const CargoID acf_cid = this->cargo_filter[this->accepted_cargo_filter_criteria];
1666 for (uint i = this->vscroll->GetPosition(); i < this->industries.size(); i++) {
1667 tc = TC_FROMSTRING;
1668 if (acf_cid != CF_ANY && acf_cid != CF_NONE) {
1669 Industry *ind = const_cast<Industry *>(this->industries[i]);
1670 if (IndustryTemporarilyRefusesCargo(ind, acf_cid)) {
1671 tc = TC_GREY | TC_FORCED;
1674 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, this->GetIndustryString(this->industries[i]), tc);
1676 y += this->resize.step_height;
1677 if (++n == this->vscroll->GetCapacity()) break; // max number of industries in 1 window
1679 break;
1684 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
1686 switch (widget) {
1687 case WID_ID_DROPDOWN_ORDER: {
1688 Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
1689 d.width += padding.width + Window::SortButtonWidth() * 2; // Doubled since the string is centred and it also looks better.
1690 d.height += padding.height;
1691 *size = maxdim(*size, d);
1692 break;
1695 case WID_ID_DROPDOWN_CRITERIA: {
1696 Dimension d = {0, 0};
1697 for (uint i = 0; IndustryDirectoryWindow::sorter_names[i] != INVALID_STRING_ID; i++) {
1698 d = maxdim(d, GetStringBoundingBox(IndustryDirectoryWindow::sorter_names[i]));
1700 d.width += padding.width;
1701 d.height += padding.height;
1702 *size = maxdim(*size, d);
1703 break;
1706 case WID_ID_INDUSTRY_LIST: {
1707 Dimension d = GetStringBoundingBox(STR_INDUSTRY_DIRECTORY_NONE);
1708 for (uint i = 0; i < this->industries.size(); i++) {
1709 d = maxdim(d, GetStringBoundingBox(this->GetIndustryString(this->industries[i])));
1711 resize->height = d.height;
1712 d.height *= 5;
1713 d.width += padding.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
1714 d.height += padding.height + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
1715 *size = maxdim(*size, d);
1716 break;
1722 void OnClick(Point pt, int widget, int click_count) override
1724 switch (widget) {
1725 case WID_ID_DROPDOWN_ORDER:
1726 this->industries.ToggleSortOrder();
1727 this->SetDirty();
1728 break;
1730 case WID_ID_DROPDOWN_CRITERIA:
1731 ShowDropDownMenu(this, IndustryDirectoryWindow::sorter_names, this->industries.SortType(), WID_ID_DROPDOWN_CRITERIA, 0, 0);
1732 break;
1734 case WID_ID_FILTER_BY_ACC_CARGO: // Cargo filter dropdown
1735 ShowDropDownMenu(this, this->cargo_filter_texts, this->accepted_cargo_filter_criteria, WID_ID_FILTER_BY_ACC_CARGO, 0, 0);
1736 break;
1738 case WID_ID_FILTER_BY_PROD_CARGO: // Cargo filter dropdown
1739 ShowDropDownMenu(this, this->cargo_filter_texts, this->produced_cargo_filter_criteria, WID_ID_FILTER_BY_PROD_CARGO, 0, 0);
1740 break;
1742 case WID_ID_INDUSTRY_LIST: {
1743 uint p = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_ID_INDUSTRY_LIST, WD_FRAMERECT_TOP);
1744 if (p < this->industries.size()) {
1745 if (_ctrl_pressed) {
1746 ShowExtraViewportWindow(this->industries[p]->location.tile);
1747 } else {
1748 ScrollMainWindowToTile(this->industries[p]->location.tile);
1751 break;
1756 void OnDropdownSelect(int widget, int index) override
1758 switch (widget) {
1759 case WID_ID_DROPDOWN_CRITERIA: {
1760 if (this->industries.SortType() != index) {
1761 this->industries.SetSortType(index);
1762 this->BuildSortIndustriesList();
1764 break;
1767 case WID_ID_FILTER_BY_ACC_CARGO: {
1768 this->SetAcceptedCargoFilterIndex(index);
1769 this->BuildSortIndustriesList();
1770 break;
1773 case WID_ID_FILTER_BY_PROD_CARGO: {
1774 this->SetProducedCargoFilterIndex(index);
1775 this->BuildSortIndustriesList();
1776 break;
1781 void OnResize() override
1783 this->vscroll->SetCapacityFromWidget(this, WID_ID_INDUSTRY_LIST);
1786 void OnPaint() override
1788 if (this->industries.NeedRebuild()) this->BuildSortIndustriesList();
1789 this->DrawWidgets();
1792 void OnHundredthTick() override
1794 this->industries.ForceResort();
1795 this->BuildSortIndustriesList();
1799 * Some data on this window has become invalid.
1800 * @param data Information about the changed data.
1801 * @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.
1803 void OnInvalidateData(int data = 0, bool gui_scope = true) override
1805 switch (data) {
1806 case IDIWD_FORCE_REBUILD:
1807 /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
1808 this->industries.ForceRebuild();
1809 break;
1811 case IDIWD_PRODUCTION_CHANGE:
1812 if (this->industries.SortType() == 2) this->industries.ForceResort();
1813 break;
1815 default:
1816 this->industries.ForceResort();
1817 break;
1822 Listing IndustryDirectoryWindow::last_sorting = {false, 0};
1824 /* Available station sorting functions. */
1825 GUIIndustryList::SortFunction * const IndustryDirectoryWindow::sorter_funcs[] = {
1826 &IndustryNameSorter,
1827 &IndustryTypeSorter,
1828 &IndustryProductionSorter,
1829 &IndustryTransportedCargoSorter
1832 /* Names of the sorting functions */
1833 const StringID IndustryDirectoryWindow::sorter_names[] = {
1834 STR_SORT_BY_NAME,
1835 STR_SORT_BY_TYPE,
1836 STR_SORT_BY_PRODUCTION,
1837 STR_SORT_BY_TRANSPORTED,
1838 INVALID_STRING_ID
1841 CargoID IndustryDirectoryWindow::produced_cargo_filter = CF_ANY;
1844 /** Window definition of the industry directory gui */
1845 static WindowDesc _industry_directory_desc(
1846 WDP_AUTO, "list_industries", 428, 190,
1847 WC_INDUSTRY_DIRECTORY, WC_NONE,
1849 _nested_industry_directory_widgets, lengthof(_nested_industry_directory_widgets)
1852 void ShowIndustryDirectory()
1854 AllocateWindowDescFront<IndustryDirectoryWindow>(&_industry_directory_desc, 0);
1857 /** Widgets of the industry cargoes window. */
1858 static const NWidgetPart _nested_industry_cargoes_widgets[] = {
1859 NWidget(NWID_HORIZONTAL),
1860 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
1861 NWidget(WWT_CAPTION, COLOUR_BROWN, WID_IC_CAPTION), SetDataTip(STR_INDUSTRY_CARGOES_INDUSTRY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1862 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
1863 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
1864 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
1865 EndContainer(),
1866 NWidget(NWID_HORIZONTAL),
1867 NWidget(NWID_VERTICAL),
1868 NWidget(WWT_PANEL, COLOUR_BROWN, WID_IC_PANEL), SetResize(1, 10), SetMinimalSize(200, 90), SetScrollbar(WID_IC_SCROLLBAR), EndContainer(),
1869 NWidget(NWID_HORIZONTAL),
1870 NWidget(WWT_TEXTBTN, COLOUR_BROWN, WID_IC_NOTIFY),
1871 SetDataTip(STR_INDUSTRY_CARGOES_NOTIFY_SMALLMAP, STR_INDUSTRY_CARGOES_NOTIFY_SMALLMAP_TOOLTIP),
1872 NWidget(WWT_PANEL, COLOUR_BROWN), SetFill(1, 0), SetResize(0, 0), EndContainer(),
1873 NWidget(WWT_DROPDOWN, COLOUR_BROWN, WID_IC_IND_DROPDOWN), SetFill(0, 0), SetResize(0, 0),
1874 SetDataTip(STR_INDUSTRY_CARGOES_SELECT_INDUSTRY, STR_INDUSTRY_CARGOES_SELECT_INDUSTRY_TOOLTIP),
1875 NWidget(WWT_DROPDOWN, COLOUR_BROWN, WID_IC_CARGO_DROPDOWN), SetFill(0, 0), SetResize(0, 0),
1876 SetDataTip(STR_INDUSTRY_CARGOES_SELECT_CARGO, STR_INDUSTRY_CARGOES_SELECT_CARGO_TOOLTIP),
1877 EndContainer(),
1878 EndContainer(),
1879 NWidget(NWID_VERTICAL),
1880 NWidget(NWID_VSCROLLBAR, COLOUR_BROWN, WID_IC_SCROLLBAR),
1881 NWidget(WWT_RESIZEBOX, COLOUR_BROWN),
1882 EndContainer(),
1883 EndContainer(),
1886 /** Window description for the industry cargoes window. */
1887 static WindowDesc _industry_cargoes_desc(
1888 WDP_AUTO, "industry_cargoes", 300, 210,
1889 WC_INDUSTRY_CARGOES, WC_NONE,
1891 _nested_industry_cargoes_widgets, lengthof(_nested_industry_cargoes_widgets)
1894 /** Available types of field. */
1895 enum CargoesFieldType {
1896 CFT_EMPTY, ///< Empty field.
1897 CFT_SMALL_EMPTY, ///< Empty small field (for the header).
1898 CFT_INDUSTRY, ///< Display industry.
1899 CFT_CARGO, ///< Display cargo connections.
1900 CFT_CARGO_LABEL, ///< Display cargo labels.
1901 CFT_HEADER, ///< Header text.
1904 static const uint MAX_CARGOES = 16; ///< Maximum number of cargoes carried in a #CFT_CARGO field in #CargoesField.
1906 /** Data about a single field in the #IndustryCargoesWindow panel. */
1907 struct CargoesField {
1908 static const int VERT_INTER_INDUSTRY_SPACE;
1909 static const int BLOB_DISTANCE;
1911 static Dimension legend;
1912 static Dimension cargo_border;
1913 static Dimension cargo_line;
1914 static Dimension cargo_space;
1915 static Dimension cargo_stub;
1917 static const int INDUSTRY_LINE_COLOUR;
1918 static const int CARGO_LINE_COLOUR;
1920 static int small_height, normal_height;
1921 static int cargo_field_width;
1922 static int industry_width;
1923 static uint max_cargoes;
1925 CargoesFieldType type; ///< Type of field.
1926 union {
1927 struct {
1928 IndustryType ind_type; ///< Industry type (#NUM_INDUSTRYTYPES means 'houses').
1929 CargoID other_produced[MAX_CARGOES]; ///< Cargoes produced but not used in this figure.
1930 CargoID other_accepted[MAX_CARGOES]; ///< Cargoes accepted but not used in this figure.
1931 } industry; ///< Industry data (for #CFT_INDUSTRY).
1932 struct {
1933 CargoID vertical_cargoes[MAX_CARGOES]; ///< Cargoes running from top to bottom (cargo ID or #INVALID_CARGO).
1934 byte num_cargoes; ///< Number of cargoes.
1935 CargoID supp_cargoes[MAX_CARGOES]; ///< Cargoes entering from the left (index in #vertical_cargoes, or #INVALID_CARGO).
1936 byte top_end; ///< Stop at the top of the vertical cargoes.
1937 CargoID cust_cargoes[MAX_CARGOES]; ///< Cargoes leaving to the right (index in #vertical_cargoes, or #INVALID_CARGO).
1938 byte bottom_end; ///< Stop at the bottom of the vertical cargoes.
1939 } cargo; ///< Cargo data (for #CFT_CARGO).
1940 struct {
1941 CargoID cargoes[MAX_CARGOES]; ///< Cargoes to display (or #INVALID_CARGO).
1942 bool left_align; ///< Align all cargo texts to the left (else align to the right).
1943 } cargo_label; ///< Label data (for #CFT_CARGO_LABEL).
1944 StringID header; ///< Header text (for #CFT_HEADER).
1945 } u; // Data for each type.
1948 * Make one of the empty fields (#CFT_EMPTY or #CFT_SMALL_EMPTY).
1949 * @param type Type of empty field.
1951 void MakeEmpty(CargoesFieldType type)
1953 this->type = type;
1957 * Make an industry type field.
1958 * @param ind_type Industry type (#NUM_INDUSTRYTYPES means 'houses').
1959 * @note #other_accepted and #other_produced should be filled later.
1961 void MakeIndustry(IndustryType ind_type)
1963 this->type = CFT_INDUSTRY;
1964 this->u.industry.ind_type = ind_type;
1965 MemSetT(this->u.industry.other_accepted, INVALID_CARGO, MAX_CARGOES);
1966 MemSetT(this->u.industry.other_produced, INVALID_CARGO, MAX_CARGOES);
1970 * Connect a cargo from an industry to the #CFT_CARGO column.
1971 * @param cargo Cargo to connect.
1972 * @param producer Cargo is produced (if \c false, cargo is assumed to be accepted).
1973 * @return Horizontal connection index, or \c -1 if not accepted at all.
1975 int ConnectCargo(CargoID cargo, bool producer)
1977 assert(this->type == CFT_CARGO);
1978 if (cargo == INVALID_CARGO) return -1;
1980 /* Find the vertical cargo column carrying the cargo. */
1981 int column = -1;
1982 for (int i = 0; i < this->u.cargo.num_cargoes; i++) {
1983 if (cargo == this->u.cargo.vertical_cargoes[i]) {
1984 column = i;
1985 break;
1988 if (column < 0) return -1;
1990 if (producer) {
1991 assert(this->u.cargo.supp_cargoes[column] == INVALID_CARGO);
1992 this->u.cargo.supp_cargoes[column] = column;
1993 } else {
1994 assert(this->u.cargo.cust_cargoes[column] == INVALID_CARGO);
1995 this->u.cargo.cust_cargoes[column] = column;
1997 return column;
2001 * Does this #CFT_CARGO field have a horizontal connection?
2002 * @return \c true if a horizontal connection exists, \c false otherwise.
2004 bool HasConnection()
2006 assert(this->type == CFT_CARGO);
2008 for (uint i = 0; i < MAX_CARGOES; i++) {
2009 if (this->u.cargo.supp_cargoes[i] != INVALID_CARGO) return true;
2010 if (this->u.cargo.cust_cargoes[i] != INVALID_CARGO) return true;
2012 return false;
2016 * Make a piece of cargo column.
2017 * @param cargoes Array of #CargoID (may contain #INVALID_CARGO).
2018 * @param length Number of cargoes in \a cargoes.
2019 * @param count Number of cargoes to display (should be at least the number of valid cargoes, or \c -1 to let the method compute it).
2020 * @param top_end This is the first cargo field of this column.
2021 * @param bottom_end This is the last cargo field of this column.
2022 * @note #supp_cargoes and #cust_cargoes should be filled in later.
2024 void MakeCargo(const CargoID *cargoes, uint length, int count = -1, bool top_end = false, bool bottom_end = false)
2026 this->type = CFT_CARGO;
2027 uint i;
2028 uint num = 0;
2029 for (i = 0; i < MAX_CARGOES && i < length; i++) {
2030 if (cargoes[i] != INVALID_CARGO) {
2031 this->u.cargo.vertical_cargoes[num] = cargoes[i];
2032 num++;
2035 this->u.cargo.num_cargoes = (count < 0) ? num : count;
2036 for (; num < MAX_CARGOES; num++) this->u.cargo.vertical_cargoes[num] = INVALID_CARGO;
2037 this->u.cargo.top_end = top_end;
2038 this->u.cargo.bottom_end = bottom_end;
2039 MemSetT(this->u.cargo.supp_cargoes, INVALID_CARGO, MAX_CARGOES);
2040 MemSetT(this->u.cargo.cust_cargoes, INVALID_CARGO, MAX_CARGOES);
2044 * Make a field displaying cargo type names.
2045 * @param cargoes Array of #CargoID (may contain #INVALID_CARGO).
2046 * @param length Number of cargoes in \a cargoes.
2047 * @param left_align ALign texts to the left (else to the right).
2049 void MakeCargoLabel(const CargoID *cargoes, uint length, bool left_align)
2051 this->type = CFT_CARGO_LABEL;
2052 uint i;
2053 for (i = 0; i < MAX_CARGOES && i < length; i++) this->u.cargo_label.cargoes[i] = cargoes[i];
2054 for (; i < MAX_CARGOES; i++) this->u.cargo_label.cargoes[i] = INVALID_CARGO;
2055 this->u.cargo_label.left_align = left_align;
2059 * Make a header above an industry column.
2060 * @param textid Text to display.
2062 void MakeHeader(StringID textid)
2064 this->type = CFT_HEADER;
2065 this->u.header = textid;
2069 * For a #CFT_CARGO, compute the left position of the left-most vertical cargo connection.
2070 * @param xpos Left position of the field.
2071 * @return Left position of the left-most vertical cargo column.
2073 int GetCargoBase(int xpos) const
2075 assert(this->type == CFT_CARGO);
2076 int n = this->u.cargo.num_cargoes;
2078 return xpos + cargo_field_width / 2 - (CargoesField::cargo_line.width * n + CargoesField::cargo_space.width * (n - 1)) / 2;
2082 * Draw the field.
2083 * @param xpos Position of the left edge.
2084 * @param ypos Position of the top edge.
2086 void Draw(int xpos, int ypos) const
2088 switch (this->type) {
2089 case CFT_EMPTY:
2090 case CFT_SMALL_EMPTY:
2091 break;
2093 case CFT_HEADER:
2094 ypos += (small_height - FONT_HEIGHT_NORMAL) / 2;
2095 DrawString(xpos, xpos + industry_width, ypos, this->u.header, TC_WHITE, SA_HOR_CENTER);
2096 break;
2098 case CFT_INDUSTRY: {
2099 int ypos1 = ypos + VERT_INTER_INDUSTRY_SPACE / 2;
2100 int ypos2 = ypos + normal_height - 1 - VERT_INTER_INDUSTRY_SPACE / 2;
2101 int xpos2 = xpos + industry_width - 1;
2102 GfxDrawLine(xpos, ypos1, xpos2, ypos1, INDUSTRY_LINE_COLOUR);
2103 GfxDrawLine(xpos, ypos1, xpos, ypos2, INDUSTRY_LINE_COLOUR);
2104 GfxDrawLine(xpos, ypos2, xpos2, ypos2, INDUSTRY_LINE_COLOUR);
2105 GfxDrawLine(xpos2, ypos1, xpos2, ypos2, INDUSTRY_LINE_COLOUR);
2106 ypos += (normal_height - FONT_HEIGHT_NORMAL) / 2;
2107 if (this->u.industry.ind_type < NUM_INDUSTRYTYPES) {
2108 const IndustrySpec *indsp = GetIndustrySpec(this->u.industry.ind_type);
2109 DrawString(xpos, xpos2, ypos, indsp->name, TC_WHITE, SA_HOR_CENTER);
2111 /* Draw the industry legend. */
2112 int blob_left, blob_right;
2113 if (_current_text_dir == TD_RTL) {
2114 blob_right = xpos2 - BLOB_DISTANCE;
2115 blob_left = blob_right - CargoesField::legend.width;
2116 } else {
2117 blob_left = xpos + BLOB_DISTANCE;
2118 blob_right = blob_left + CargoesField::legend.width;
2120 GfxFillRect(blob_left, ypos2 - BLOB_DISTANCE - CargoesField::legend.height, blob_right, ypos2 - BLOB_DISTANCE, PC_BLACK); // Border
2121 GfxFillRect(blob_left + 1, ypos2 - BLOB_DISTANCE - CargoesField::legend.height + 1, blob_right - 1, ypos2 - BLOB_DISTANCE - 1, indsp->map_colour);
2122 } else {
2123 DrawString(xpos, xpos2, ypos, STR_INDUSTRY_CARGOES_HOUSES, TC_FROMSTRING, SA_HOR_CENTER);
2126 /* Draw the other_produced/other_accepted cargoes. */
2127 const CargoID *other_right, *other_left;
2128 if (_current_text_dir == TD_RTL) {
2129 other_right = this->u.industry.other_accepted;
2130 other_left = this->u.industry.other_produced;
2131 } else {
2132 other_right = this->u.industry.other_produced;
2133 other_left = this->u.industry.other_accepted;
2135 ypos1 += CargoesField::cargo_border.height + (FONT_HEIGHT_NORMAL - CargoesField::cargo_line.height) / 2;
2136 for (uint i = 0; i < CargoesField::max_cargoes; i++) {
2137 if (other_right[i] != INVALID_CARGO) {
2138 const CargoSpec *csp = CargoSpec::Get(other_right[i]);
2139 int xp = xpos + industry_width + CargoesField::cargo_stub.width;
2140 DrawHorConnection(xpos + industry_width, xp - 1, ypos1, csp);
2141 GfxDrawLine(xp, ypos1, xp, ypos1 + CargoesField::cargo_line.height - 1, CARGO_LINE_COLOUR);
2143 if (other_left[i] != INVALID_CARGO) {
2144 const CargoSpec *csp = CargoSpec::Get(other_left[i]);
2145 int xp = xpos - CargoesField::cargo_stub.width;
2146 DrawHorConnection(xp + 1, xpos - 1, ypos1, csp);
2147 GfxDrawLine(xp, ypos1, xp, ypos1 + CargoesField::cargo_line.height - 1, CARGO_LINE_COLOUR);
2149 ypos1 += FONT_HEIGHT_NORMAL + CargoesField::cargo_space.height;
2151 break;
2154 case CFT_CARGO: {
2155 int cargo_base = this->GetCargoBase(xpos);
2156 int top = ypos + (this->u.cargo.top_end ? VERT_INTER_INDUSTRY_SPACE / 2 + 1 : 0);
2157 int bot = ypos - (this->u.cargo.bottom_end ? VERT_INTER_INDUSTRY_SPACE / 2 + 1 : 0) + normal_height - 1;
2158 int colpos = cargo_base;
2159 for (int i = 0; i < this->u.cargo.num_cargoes; i++) {
2160 if (this->u.cargo.top_end) GfxDrawLine(colpos, top - 1, colpos + CargoesField::cargo_line.width - 1, top - 1, CARGO_LINE_COLOUR);
2161 if (this->u.cargo.bottom_end) GfxDrawLine(colpos, bot + 1, colpos + CargoesField::cargo_line.width - 1, bot + 1, CARGO_LINE_COLOUR);
2162 GfxDrawLine(colpos, top, colpos, bot, CARGO_LINE_COLOUR);
2163 colpos++;
2164 const CargoSpec *csp = CargoSpec::Get(this->u.cargo.vertical_cargoes[i]);
2165 GfxFillRect(colpos, top, colpos + CargoesField::cargo_line.width - 2, bot, csp->legend_colour, FILLRECT_OPAQUE);
2166 colpos += CargoesField::cargo_line.width - 2;
2167 GfxDrawLine(colpos, top, colpos, bot, CARGO_LINE_COLOUR);
2168 colpos += 1 + CargoesField::cargo_space.width;
2171 const CargoID *hor_left, *hor_right;
2172 if (_current_text_dir == TD_RTL) {
2173 hor_left = this->u.cargo.cust_cargoes;
2174 hor_right = this->u.cargo.supp_cargoes;
2175 } else {
2176 hor_left = this->u.cargo.supp_cargoes;
2177 hor_right = this->u.cargo.cust_cargoes;
2179 ypos += CargoesField::cargo_border.height + VERT_INTER_INDUSTRY_SPACE / 2 + (FONT_HEIGHT_NORMAL - CargoesField::cargo_line.height) / 2;
2180 for (uint i = 0; i < MAX_CARGOES; i++) {
2181 if (hor_left[i] != INVALID_CARGO) {
2182 int col = hor_left[i];
2183 int dx = 0;
2184 const CargoSpec *csp = CargoSpec::Get(this->u.cargo.vertical_cargoes[col]);
2185 for (; col > 0; col--) {
2186 int lf = cargo_base + col * CargoesField::cargo_line.width + (col - 1) * CargoesField::cargo_space.width;
2187 DrawHorConnection(lf, lf + CargoesField::cargo_space.width - dx, ypos, csp);
2188 dx = 1;
2190 DrawHorConnection(xpos, cargo_base - dx, ypos, csp);
2192 if (hor_right[i] != INVALID_CARGO) {
2193 int col = hor_right[i];
2194 int dx = 0;
2195 const CargoSpec *csp = CargoSpec::Get(this->u.cargo.vertical_cargoes[col]);
2196 for (; col < this->u.cargo.num_cargoes - 1; col++) {
2197 int lf = cargo_base + (col + 1) * CargoesField::cargo_line.width + col * CargoesField::cargo_space.width;
2198 DrawHorConnection(lf + dx - 1, lf + CargoesField::cargo_space.width - 1, ypos, csp);
2199 dx = 1;
2201 DrawHorConnection(cargo_base + col * CargoesField::cargo_space.width + (col + 1) * CargoesField::cargo_line.width - 1 + dx, xpos + CargoesField::cargo_field_width - 1, ypos, csp);
2203 ypos += FONT_HEIGHT_NORMAL + CargoesField::cargo_space.height;
2205 break;
2208 case CFT_CARGO_LABEL:
2209 ypos += CargoesField::cargo_border.height + VERT_INTER_INDUSTRY_SPACE / 2;
2210 for (uint i = 0; i < MAX_CARGOES; i++) {
2211 if (this->u.cargo_label.cargoes[i] != INVALID_CARGO) {
2212 const CargoSpec *csp = CargoSpec::Get(this->u.cargo_label.cargoes[i]);
2213 DrawString(xpos + WD_FRAMERECT_LEFT, xpos + industry_width - 1 - WD_FRAMERECT_RIGHT, ypos, csp->name, TC_WHITE,
2214 (this->u.cargo_label.left_align) ? SA_LEFT : SA_RIGHT);
2216 ypos += FONT_HEIGHT_NORMAL + CargoesField::cargo_space.height;
2218 break;
2220 default:
2221 NOT_REACHED();
2226 * Decide which cargo was clicked at in a #CFT_CARGO field.
2227 * @param left Left industry neighbour if available (else \c nullptr should be supplied).
2228 * @param right Right industry neighbour if available (else \c nullptr should be supplied).
2229 * @param pt Click position in the cargo field.
2230 * @return Cargo clicked at, or #INVALID_CARGO if none.
2232 CargoID CargoClickedAt(const CargoesField *left, const CargoesField *right, Point pt) const
2234 assert(this->type == CFT_CARGO);
2236 /* Vertical matching. */
2237 int cpos = this->GetCargoBase(0);
2238 uint col;
2239 for (col = 0; col < this->u.cargo.num_cargoes; col++) {
2240 if (pt.x < cpos) break;
2241 if (pt.x < cpos + (int)CargoesField::cargo_line.width) return this->u.cargo.vertical_cargoes[col];
2242 cpos += CargoesField::cargo_line.width + CargoesField::cargo_space.width;
2244 /* col = 0 -> left of first col, 1 -> left of 2nd col, ... this->u.cargo.num_cargoes right of last-col. */
2246 int vpos = VERT_INTER_INDUSTRY_SPACE / 2 + CargoesField::cargo_border.width;
2247 uint row;
2248 for (row = 0; row < MAX_CARGOES; row++) {
2249 if (pt.y < vpos) return INVALID_CARGO;
2250 if (pt.y < vpos + FONT_HEIGHT_NORMAL) break;
2251 vpos += FONT_HEIGHT_NORMAL + CargoesField::cargo_space.width;
2253 if (row == MAX_CARGOES) return INVALID_CARGO;
2255 /* row = 0 -> at first horizontal row, row = 1 -> second horizontal row, 2 = 3rd horizontal row. */
2256 if (col == 0) {
2257 if (this->u.cargo.supp_cargoes[row] != INVALID_CARGO) return this->u.cargo.vertical_cargoes[this->u.cargo.supp_cargoes[row]];
2258 if (left != nullptr) {
2259 if (left->type == CFT_INDUSTRY) return left->u.industry.other_produced[row];
2260 if (left->type == CFT_CARGO_LABEL && !left->u.cargo_label.left_align) return left->u.cargo_label.cargoes[row];
2262 return INVALID_CARGO;
2264 if (col == this->u.cargo.num_cargoes) {
2265 if (this->u.cargo.cust_cargoes[row] != INVALID_CARGO) return this->u.cargo.vertical_cargoes[this->u.cargo.cust_cargoes[row]];
2266 if (right != nullptr) {
2267 if (right->type == CFT_INDUSTRY) return right->u.industry.other_accepted[row];
2268 if (right->type == CFT_CARGO_LABEL && right->u.cargo_label.left_align) return right->u.cargo_label.cargoes[row];
2270 return INVALID_CARGO;
2272 if (row >= col) {
2273 /* Clicked somewhere in-between vertical cargo connection.
2274 * Since the horizontal connection is made in the same order as the vertical list, the above condition
2275 * ensures we are left-below the main diagonal, thus at the supplying side.
2277 return (this->u.cargo.supp_cargoes[row] != INVALID_CARGO) ? this->u.cargo.vertical_cargoes[this->u.cargo.supp_cargoes[row]] : INVALID_CARGO;
2278 } else {
2279 /* Clicked at a customer connection. */
2280 return (this->u.cargo.cust_cargoes[row] != INVALID_CARGO) ? this->u.cargo.vertical_cargoes[this->u.cargo.cust_cargoes[row]] : INVALID_CARGO;
2285 * Decide what cargo the user clicked in the cargo label field.
2286 * @param pt Click position in the cargo label field.
2287 * @return Cargo clicked at, or #INVALID_CARGO if none.
2289 CargoID CargoLabelClickedAt(Point pt) const
2291 assert(this->type == CFT_CARGO_LABEL);
2293 int vpos = VERT_INTER_INDUSTRY_SPACE / 2 + CargoesField::cargo_border.height;
2294 uint row;
2295 for (row = 0; row < MAX_CARGOES; row++) {
2296 if (pt.y < vpos) return INVALID_CARGO;
2297 if (pt.y < vpos + FONT_HEIGHT_NORMAL) break;
2298 vpos += FONT_HEIGHT_NORMAL + CargoesField::cargo_space.height;
2300 if (row == MAX_CARGOES) return INVALID_CARGO;
2301 return this->u.cargo_label.cargoes[row];
2304 private:
2306 * Draw a horizontal cargo connection.
2307 * @param left Left-most coordinate to draw.
2308 * @param right Right-most coordinate to draw.
2309 * @param top Top coordinate of the cargo connection.
2310 * @param csp Cargo to draw.
2312 static void DrawHorConnection(int left, int right, int top, const CargoSpec *csp)
2314 GfxDrawLine(left, top, right, top, CARGO_LINE_COLOUR);
2315 GfxFillRect(left, top + 1, right, top + CargoesField::cargo_line.height - 2, csp->legend_colour, FILLRECT_OPAQUE);
2316 GfxDrawLine(left, top + CargoesField::cargo_line.height - 1, right, top + CargoesField::cargo_line.height - 1, CARGO_LINE_COLOUR);
2320 static_assert(MAX_CARGOES >= cpp_lengthof(IndustrySpec, produced_cargo));
2321 static_assert(MAX_CARGOES >= cpp_lengthof(IndustrySpec, accepts_cargo));
2323 Dimension CargoesField::legend; ///< Dimension of the legend blob.
2324 Dimension CargoesField::cargo_border; ///< Dimensions of border between cargo lines and industry boxes.
2325 Dimension CargoesField::cargo_line; ///< Dimensions of cargo lines.
2326 Dimension CargoesField::cargo_space; ///< Dimensions of space between cargo lines.
2327 Dimension CargoesField::cargo_stub; ///< Dimensions of cargo stub (unconnected cargo line.)
2329 int CargoesField::small_height; ///< Height of the header row.
2330 int CargoesField::normal_height; ///< Height of the non-header rows.
2331 int CargoesField::industry_width; ///< Width of an industry field.
2332 int CargoesField::cargo_field_width; ///< Width of a cargo field.
2333 uint CargoesField::max_cargoes; ///< Largest number of cargoes actually on any industry.
2334 const int CargoesField::VERT_INTER_INDUSTRY_SPACE = 6; ///< Amount of space between two industries in a column.
2336 const int CargoesField::BLOB_DISTANCE = 5; ///< Distance of the industry legend colour from the edge of the industry box.
2338 const int CargoesField::INDUSTRY_LINE_COLOUR = PC_YELLOW; ///< Line colour of the industry type box.
2339 const int CargoesField::CARGO_LINE_COLOUR = PC_YELLOW; ///< Line colour around the cargo.
2341 /** A single row of #CargoesField. */
2342 struct CargoesRow {
2343 CargoesField columns[5]; ///< One row of fields.
2346 * Connect industry production cargoes to the cargo column after it.
2347 * @param column Column of the industry.
2349 void ConnectIndustryProduced(int column)
2351 CargoesField *ind_fld = this->columns + column;
2352 CargoesField *cargo_fld = this->columns + column + 1;
2353 assert(ind_fld->type == CFT_INDUSTRY && cargo_fld->type == CFT_CARGO);
2355 MemSetT(ind_fld->u.industry.other_produced, INVALID_CARGO, MAX_CARGOES);
2357 if (ind_fld->u.industry.ind_type < NUM_INDUSTRYTYPES) {
2358 CargoID others[MAX_CARGOES]; // Produced cargoes not carried in the cargo column.
2359 int other_count = 0;
2361 const IndustrySpec *indsp = GetIndustrySpec(ind_fld->u.industry.ind_type);
2362 assert(CargoesField::max_cargoes <= lengthof(indsp->produced_cargo));
2363 for (uint i = 0; i < CargoesField::max_cargoes; i++) {
2364 int col = cargo_fld->ConnectCargo(indsp->produced_cargo[i], true);
2365 if (col < 0) others[other_count++] = indsp->produced_cargo[i];
2368 /* Allocate other cargoes in the empty holes of the horizontal cargo connections. */
2369 for (uint i = 0; i < CargoesField::max_cargoes && other_count > 0; i++) {
2370 if (cargo_fld->u.cargo.supp_cargoes[i] == INVALID_CARGO) ind_fld->u.industry.other_produced[i] = others[--other_count];
2372 } else {
2373 /* Houses only display what is demanded. */
2374 for (uint i = 0; i < cargo_fld->u.cargo.num_cargoes; i++) {
2375 CargoID cid = cargo_fld->u.cargo.vertical_cargoes[i];
2376 if (cid == CT_PASSENGERS || cid == CT_MAIL) cargo_fld->ConnectCargo(cid, true);
2382 * Construct a #CFT_CARGO_LABEL field.
2383 * @param column Column to create the new field.
2384 * @param accepting Display accepted cargo (if \c false, display produced cargo).
2386 void MakeCargoLabel(int column, bool accepting)
2388 CargoID cargoes[MAX_CARGOES];
2389 MemSetT(cargoes, INVALID_CARGO, lengthof(cargoes));
2391 CargoesField *label_fld = this->columns + column;
2392 CargoesField *cargo_fld = this->columns + (accepting ? column - 1 : column + 1);
2394 assert(cargo_fld->type == CFT_CARGO && label_fld->type == CFT_EMPTY);
2395 for (uint i = 0; i < cargo_fld->u.cargo.num_cargoes; i++) {
2396 int col = cargo_fld->ConnectCargo(cargo_fld->u.cargo.vertical_cargoes[i], !accepting);
2397 if (col >= 0) cargoes[col] = cargo_fld->u.cargo.vertical_cargoes[i];
2399 label_fld->MakeCargoLabel(cargoes, lengthof(cargoes), accepting);
2404 * Connect industry accepted cargoes to the cargo column before it.
2405 * @param column Column of the industry.
2407 void ConnectIndustryAccepted(int column)
2409 CargoesField *ind_fld = this->columns + column;
2410 CargoesField *cargo_fld = this->columns + column - 1;
2411 assert(ind_fld->type == CFT_INDUSTRY && cargo_fld->type == CFT_CARGO);
2413 MemSetT(ind_fld->u.industry.other_accepted, INVALID_CARGO, MAX_CARGOES);
2415 if (ind_fld->u.industry.ind_type < NUM_INDUSTRYTYPES) {
2416 CargoID others[MAX_CARGOES]; // Accepted cargoes not carried in the cargo column.
2417 int other_count = 0;
2419 const IndustrySpec *indsp = GetIndustrySpec(ind_fld->u.industry.ind_type);
2420 assert(CargoesField::max_cargoes <= lengthof(indsp->accepts_cargo));
2421 for (uint i = 0; i < CargoesField::max_cargoes; i++) {
2422 int col = cargo_fld->ConnectCargo(indsp->accepts_cargo[i], false);
2423 if (col < 0) others[other_count++] = indsp->accepts_cargo[i];
2426 /* Allocate other cargoes in the empty holes of the horizontal cargo connections. */
2427 for (uint i = 0; i < CargoesField::max_cargoes && other_count > 0; i++) {
2428 if (cargo_fld->u.cargo.cust_cargoes[i] == INVALID_CARGO) ind_fld->u.industry.other_accepted[i] = others[--other_count];
2430 } else {
2431 /* Houses only display what is demanded. */
2432 for (uint i = 0; i < cargo_fld->u.cargo.num_cargoes; i++) {
2433 for (uint h = 0; h < NUM_HOUSES; h++) {
2434 HouseSpec *hs = HouseSpec::Get(h);
2435 if (!hs->enabled) continue;
2437 for (uint j = 0; j < lengthof(hs->accepts_cargo); j++) {
2438 if (hs->cargo_acceptance[j] > 0 && cargo_fld->u.cargo.vertical_cargoes[i] == hs->accepts_cargo[j]) {
2439 cargo_fld->ConnectCargo(cargo_fld->u.cargo.vertical_cargoes[i], false);
2440 goto next_cargo;
2444 next_cargo: ;
2452 * Window displaying the cargo connections around an industry (or cargo).
2454 * The main display is constructed from 'fields', rectangles that contain an industry, piece of the cargo connection, cargo labels, or headers.
2455 * For a nice display, the following should be kept in mind:
2456 * - A #CFT_HEADER is always at the top of an column of #CFT_INDUSTRY fields.
2457 * - A #CFT_CARGO_LABEL field is also always put in a column of #CFT_INDUSTRY fields.
2458 * - The top row contains #CFT_HEADER and #CFT_SMALL_EMPTY fields.
2459 * - Cargo connections have a column of their own (#CFT_CARGO fields).
2460 * - Cargo accepted or produced by an industry, but not carried in a cargo connection, is drawn in the space of a cargo column attached to the industry.
2461 * The information however is part of the industry.
2463 * This results in the following invariants:
2464 * - Width of a #CFT_INDUSTRY column is large enough to hold all industry type labels, all cargo labels, and all header texts.
2465 * - Height of a #CFT_INDUSTRY is large enough to hold a header line, or a industry type line, \c N cargo labels
2466 * (where \c N is the maximum number of cargoes connected between industries), \c N connections of cargo types, and space
2467 * between two industry types (1/2 above it, and 1/2 underneath it).
2468 * - Width of a cargo field (#CFT_CARGO) is large enough to hold \c N vertical columns (one for each type of cargo).
2469 * Also, space is needed between an industry and the leftmost/rightmost column to draw the non-carried cargoes.
2470 * - Height of a #CFT_CARGO field is equally high as the height of the #CFT_INDUSTRY.
2471 * - A field at the top (#CFT_HEADER or #CFT_SMALL_EMPTY) match the width of the fields below them (#CFT_INDUSTRY respectively
2472 * #CFT_CARGO), the height should be sufficient to display the header text.
2474 * When displaying the cargoes around an industry type, five columns are needed (supplying industries, accepted cargoes, the industry,
2475 * produced cargoes, customer industries). Displaying the industries around a cargo needs three columns (supplying industries, the cargo,
2476 * customer industries). The remaining two columns are set to #CFT_EMPTY with a width equal to the average of a cargo and an industry column.
2478 struct IndustryCargoesWindow : public Window {
2479 static const int HOR_TEXT_PADDING, VERT_TEXT_PADDING;
2481 typedef std::vector<CargoesRow> Fields;
2483 Fields fields; ///< Fields to display in the #WID_IC_PANEL.
2484 uint ind_cargo; ///< If less than #NUM_INDUSTRYTYPES, an industry type, else a cargo id + NUM_INDUSTRYTYPES.
2485 Dimension cargo_textsize; ///< Size to hold any cargo text, as well as STR_INDUSTRY_CARGOES_SELECT_CARGO.
2486 Dimension ind_textsize; ///< Size to hold any industry type text, as well as STR_INDUSTRY_CARGOES_SELECT_INDUSTRY.
2487 Scrollbar *vscroll;
2489 IndustryCargoesWindow(int id) : Window(&_industry_cargoes_desc)
2491 this->OnInit();
2492 this->CreateNestedTree();
2493 this->vscroll = this->GetScrollbar(WID_IC_SCROLLBAR);
2494 this->FinishInitNested(0);
2495 this->OnInvalidateData(id);
2498 void OnInit() override
2500 /* Initialize static CargoesField size variables. */
2501 Dimension d = GetStringBoundingBox(STR_INDUSTRY_CARGOES_PRODUCERS);
2502 d = maxdim(d, GetStringBoundingBox(STR_INDUSTRY_CARGOES_CUSTOMERS));
2503 d.width += WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT;
2504 d.height += WD_FRAMETEXT_TOP + WD_FRAMETEXT_BOTTOM;
2505 CargoesField::small_height = d.height;
2507 /* Size of the legend blob -- slightly larger than the smallmap legend blob. */
2508 CargoesField::legend.height = FONT_HEIGHT_SMALL;
2509 CargoesField::legend.width = CargoesField::legend.height * 8 / 5;
2511 /* Size of cargo lines. */
2512 CargoesField::cargo_line.width = FONT_HEIGHT_NORMAL;
2513 CargoesField::cargo_line.height = CargoesField::cargo_line.width;
2515 /* Size of border between cargo lines and industry boxes. */
2516 CargoesField::cargo_border.width = CargoesField::cargo_line.width * 3 / 2;
2517 CargoesField::cargo_border.height = CargoesField::cargo_line.width / 2;
2519 /* Size of space between cargo lines. */
2520 CargoesField::cargo_space.width = CargoesField::cargo_line.width / 2;
2521 CargoesField::cargo_space.height = CargoesField::cargo_line.height / 2;
2523 /* Size of cargo stub (unconnected cargo line.) */
2524 CargoesField::cargo_stub.width = CargoesField::cargo_line.width / 2;
2525 CargoesField::cargo_stub.height = CargoesField::cargo_line.height; /* Unused */
2527 /* Decide about the size of the box holding the text of an industry type. */
2528 this->ind_textsize.width = 0;
2529 this->ind_textsize.height = 0;
2530 CargoesField::max_cargoes = 0;
2531 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2532 const IndustrySpec *indsp = GetIndustrySpec(it);
2533 if (!indsp->enabled) continue;
2534 this->ind_textsize = maxdim(this->ind_textsize, GetStringBoundingBox(indsp->name));
2535 CargoesField::max_cargoes = std::max<uint>(CargoesField::max_cargoes, std::count_if(indsp->accepts_cargo, endof(indsp->accepts_cargo), IsCargoIDValid));
2536 CargoesField::max_cargoes = std::max<uint>(CargoesField::max_cargoes, std::count_if(indsp->produced_cargo, endof(indsp->produced_cargo), IsCargoIDValid));
2538 d.width = std::max(d.width, this->ind_textsize.width);
2539 d.height = this->ind_textsize.height;
2540 this->ind_textsize = maxdim(this->ind_textsize, GetStringBoundingBox(STR_INDUSTRY_CARGOES_SELECT_INDUSTRY));
2542 /* Compute max size of the cargo texts. */
2543 this->cargo_textsize.width = 0;
2544 this->cargo_textsize.height = 0;
2545 for (uint i = 0; i < NUM_CARGO; i++) {
2546 const CargoSpec *csp = CargoSpec::Get(i);
2547 if (!csp->IsValid()) continue;
2548 this->cargo_textsize = maxdim(this->cargo_textsize, GetStringBoundingBox(csp->name));
2550 d = maxdim(d, this->cargo_textsize); // Box must also be wide enough to hold any cargo label.
2551 this->cargo_textsize = maxdim(this->cargo_textsize, GetStringBoundingBox(STR_INDUSTRY_CARGOES_SELECT_CARGO));
2553 d.width += 2 * HOR_TEXT_PADDING;
2554 /* Ensure the height is enough for the industry type text, for the horizontal connections, and for the cargo labels. */
2555 uint min_ind_height = CargoesField::cargo_border.height * 2 + CargoesField::max_cargoes * FONT_HEIGHT_NORMAL + (CargoesField::max_cargoes - 1) * CargoesField::cargo_space.height;
2556 d.height = std::max(d.height + 2 * VERT_TEXT_PADDING, min_ind_height);
2558 CargoesField::industry_width = d.width;
2559 CargoesField::normal_height = d.height + CargoesField::VERT_INTER_INDUSTRY_SPACE;
2561 /* Width of a #CFT_CARGO field. */
2562 CargoesField::cargo_field_width = CargoesField::cargo_border.width * 2 + CargoesField::cargo_line.width * CargoesField::max_cargoes + CargoesField::cargo_space.width * (CargoesField::max_cargoes - 1);
2565 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
2567 switch (widget) {
2568 case WID_IC_PANEL:
2569 resize->height = CargoesField::normal_height;
2570 size->width = WD_FRAMETEXT_LEFT + CargoesField::industry_width * 3 + CargoesField::cargo_field_width * 2 + WD_FRAMETEXT_RIGHT;
2571 size->height = WD_FRAMETEXT_TOP + CargoesField::small_height + 2 * resize->height + WD_FRAMETEXT_BOTTOM;
2572 break;
2574 case WID_IC_IND_DROPDOWN:
2575 size->width = std::max(size->width, this->ind_textsize.width + padding.width);
2576 break;
2578 case WID_IC_CARGO_DROPDOWN:
2579 size->width = std::max(size->width, this->cargo_textsize.width + padding.width);
2580 break;
2585 CargoesFieldType type; ///< Type of field.
2586 void SetStringParameters (int widget) const override
2588 if (widget != WID_IC_CAPTION) return;
2590 if (this->ind_cargo < NUM_INDUSTRYTYPES) {
2591 const IndustrySpec *indsp = GetIndustrySpec(this->ind_cargo);
2592 SetDParam(0, indsp->name);
2593 } else {
2594 const CargoSpec *csp = CargoSpec::Get(this->ind_cargo - NUM_INDUSTRYTYPES);
2595 SetDParam(0, csp->name);
2600 * Do the two sets of cargoes have a valid cargo in common?
2601 * @param cargoes1 Base address of the first cargo array.
2602 * @param length1 Number of cargoes in the first cargo array.
2603 * @param cargoes2 Base address of the second cargo array.
2604 * @param length2 Number of cargoes in the second cargo array.
2605 * @return Arrays have at least one valid cargo in common.
2607 static bool HasCommonValidCargo(const CargoID *cargoes1, uint length1, const CargoID *cargoes2, uint length2)
2609 while (length1 > 0) {
2610 if (*cargoes1 != INVALID_CARGO) {
2611 for (uint i = 0; i < length2; i++) if (*cargoes1 == cargoes2[i]) return true;
2613 cargoes1++;
2614 length1--;
2616 return false;
2620 * Can houses be used to supply one of the cargoes?
2621 * @param cargoes Base address of the cargo array.
2622 * @param length Number of cargoes in the array.
2623 * @return Houses can supply at least one of the cargoes.
2625 static bool HousesCanSupply(const CargoID *cargoes, uint length)
2627 for (uint i = 0; i < length; i++) {
2628 if (cargoes[i] == INVALID_CARGO) continue;
2629 if (cargoes[i] == CT_PASSENGERS || cargoes[i] == CT_MAIL) return true;
2631 return false;
2635 * Can houses be used as customers of the produced cargoes?
2636 * @param cargoes Base address of the cargo array.
2637 * @param length Number of cargoes in the array.
2638 * @return Houses can accept at least one of the cargoes.
2640 static bool HousesCanAccept(const CargoID *cargoes, uint length)
2642 HouseZones climate_mask;
2643 switch (_settings_game.game_creation.landscape) {
2644 case LT_TEMPERATE: climate_mask = HZ_TEMP; break;
2645 case LT_ARCTIC: climate_mask = HZ_SUBARTC_ABOVE | HZ_SUBARTC_BELOW; break;
2646 case LT_TROPIC: climate_mask = HZ_SUBTROPIC; break;
2647 case LT_TOYLAND: climate_mask = HZ_TOYLND; break;
2648 default: NOT_REACHED();
2650 for (uint i = 0; i < length; i++) {
2651 if (cargoes[i] == INVALID_CARGO) continue;
2653 for (uint h = 0; h < NUM_HOUSES; h++) {
2654 HouseSpec *hs = HouseSpec::Get(h);
2655 if (!hs->enabled || !(hs->building_availability & climate_mask)) continue;
2657 for (uint j = 0; j < lengthof(hs->accepts_cargo); j++) {
2658 if (hs->cargo_acceptance[j] > 0 && cargoes[i] == hs->accepts_cargo[j]) return true;
2662 return false;
2666 * Count how many industries have accepted cargoes in common with one of the supplied set.
2667 * @param cargoes Cargoes to search.
2668 * @param length Number of cargoes in \a cargoes.
2669 * @return Number of industries that have an accepted cargo in common with the supplied set.
2671 static int CountMatchingAcceptingIndustries(const CargoID *cargoes, uint length)
2673 int count = 0;
2674 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2675 const IndustrySpec *indsp = GetIndustrySpec(it);
2676 if (!indsp->enabled) continue;
2678 if (HasCommonValidCargo(cargoes, length, indsp->accepts_cargo, lengthof(indsp->accepts_cargo))) count++;
2680 return count;
2684 * Count how many industries have produced cargoes in common with one of the supplied set.
2685 * @param cargoes Cargoes to search.
2686 * @param length Number of cargoes in \a cargoes.
2687 * @return Number of industries that have a produced cargo in common with the supplied set.
2689 static int CountMatchingProducingIndustries(const CargoID *cargoes, uint length)
2691 int count = 0;
2692 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2693 const IndustrySpec *indsp = GetIndustrySpec(it);
2694 if (!indsp->enabled) continue;
2696 if (HasCommonValidCargo(cargoes, length, indsp->produced_cargo, lengthof(indsp->produced_cargo))) count++;
2698 return count;
2702 * Shorten the cargo column to just the part between industries.
2703 * @param column Column number of the cargo column.
2704 * @param top Current top row.
2705 * @param bottom Current bottom row.
2707 void ShortenCargoColumn(int column, int top, int bottom)
2709 while (top < bottom && !this->fields[top].columns[column].HasConnection()) {
2710 this->fields[top].columns[column].MakeEmpty(CFT_EMPTY);
2711 top++;
2713 this->fields[top].columns[column].u.cargo.top_end = true;
2715 while (bottom > top && !this->fields[bottom].columns[column].HasConnection()) {
2716 this->fields[bottom].columns[column].MakeEmpty(CFT_EMPTY);
2717 bottom--;
2719 this->fields[bottom].columns[column].u.cargo.bottom_end = true;
2723 * Place an industry in the fields.
2724 * @param row Row of the new industry.
2725 * @param col Column of the new industry.
2726 * @param it Industry to place.
2728 void PlaceIndustry(int row, int col, IndustryType it)
2730 assert(this->fields[row].columns[col].type == CFT_EMPTY);
2731 this->fields[row].columns[col].MakeIndustry(it);
2732 if (col == 0) {
2733 this->fields[row].ConnectIndustryProduced(col);
2734 } else {
2735 this->fields[row].ConnectIndustryAccepted(col);
2740 * Notify smallmap that new displayed industries have been selected (in #_displayed_industries).
2742 void NotifySmallmap()
2744 if (!this->IsWidgetLowered(WID_IC_NOTIFY)) return;
2746 /* Only notify the smallmap window if it exists. In particular, do not
2747 * bring it to the front to prevent messing up any nice layout of the user. */
2748 InvalidateWindowClassesData(WC_SMALLMAP, 0);
2752 * Compute what and where to display for industry type \a it.
2753 * @param displayed_it Industry type to display.
2755 void ComputeIndustryDisplay(IndustryType displayed_it)
2757 this->GetWidget<NWidgetCore>(WID_IC_CAPTION)->widget_data = STR_INDUSTRY_CARGOES_INDUSTRY_CAPTION;
2758 this->ind_cargo = displayed_it;
2759 _displayed_industries.reset();
2760 _displayed_industries.set(displayed_it);
2762 this->fields.clear();
2763 CargoesRow &row = this->fields.emplace_back();
2764 row.columns[0].MakeHeader(STR_INDUSTRY_CARGOES_PRODUCERS);
2765 row.columns[1].MakeEmpty(CFT_SMALL_EMPTY);
2766 row.columns[2].MakeEmpty(CFT_SMALL_EMPTY);
2767 row.columns[3].MakeEmpty(CFT_SMALL_EMPTY);
2768 row.columns[4].MakeHeader(STR_INDUSTRY_CARGOES_CUSTOMERS);
2770 const IndustrySpec *central_sp = GetIndustrySpec(displayed_it);
2771 bool houses_supply = HousesCanSupply(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo));
2772 bool houses_accept = HousesCanAccept(central_sp->produced_cargo, lengthof(central_sp->produced_cargo));
2773 /* Make a field consisting of two cargo columns. */
2774 int num_supp = CountMatchingProducingIndustries(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo)) + houses_supply;
2775 int num_cust = CountMatchingAcceptingIndustries(central_sp->produced_cargo, lengthof(central_sp->produced_cargo)) + houses_accept;
2776 int num_indrows = std::max(3, std::max(num_supp, num_cust)); // One is needed for the 'it' industry, and 2 for the cargo labels.
2777 for (int i = 0; i < num_indrows; i++) {
2778 CargoesRow &row = this->fields.emplace_back();
2779 row.columns[0].MakeEmpty(CFT_EMPTY);
2780 row.columns[1].MakeCargo(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo));
2781 row.columns[2].MakeEmpty(CFT_EMPTY);
2782 row.columns[3].MakeCargo(central_sp->produced_cargo, lengthof(central_sp->produced_cargo));
2783 row.columns[4].MakeEmpty(CFT_EMPTY);
2785 /* Add central industry. */
2786 int central_row = 1 + num_indrows / 2;
2787 this->fields[central_row].columns[2].MakeIndustry(displayed_it);
2788 this->fields[central_row].ConnectIndustryProduced(2);
2789 this->fields[central_row].ConnectIndustryAccepted(2);
2791 /* Add cargo labels. */
2792 this->fields[central_row - 1].MakeCargoLabel(2, true);
2793 this->fields[central_row + 1].MakeCargoLabel(2, false);
2795 /* Add suppliers and customers of the 'it' industry. */
2796 int supp_count = 0;
2797 int cust_count = 0;
2798 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2799 const IndustrySpec *indsp = GetIndustrySpec(it);
2800 if (!indsp->enabled) continue;
2802 if (HasCommonValidCargo(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo), indsp->produced_cargo, lengthof(indsp->produced_cargo))) {
2803 this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, it);
2804 _displayed_industries.set(it);
2805 supp_count++;
2807 if (HasCommonValidCargo(central_sp->produced_cargo, lengthof(central_sp->produced_cargo), indsp->accepts_cargo, lengthof(indsp->accepts_cargo))) {
2808 this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 4, it);
2809 _displayed_industries.set(it);
2810 cust_count++;
2813 if (houses_supply) {
2814 this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, NUM_INDUSTRYTYPES);
2815 supp_count++;
2817 if (houses_accept) {
2818 this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 4, NUM_INDUSTRYTYPES);
2819 cust_count++;
2822 this->ShortenCargoColumn(1, 1, num_indrows);
2823 this->ShortenCargoColumn(3, 1, num_indrows);
2824 this->vscroll->SetCount(num_indrows);
2825 this->SetDirty();
2826 this->NotifySmallmap();
2830 * Compute what and where to display for cargo id \a cid.
2831 * @param cid Cargo id to display.
2833 void ComputeCargoDisplay(CargoID cid)
2835 this->GetWidget<NWidgetCore>(WID_IC_CAPTION)->widget_data = STR_INDUSTRY_CARGOES_CARGO_CAPTION;
2836 this->ind_cargo = cid + NUM_INDUSTRYTYPES;
2837 _displayed_industries.reset();
2839 this->fields.clear();
2840 CargoesRow &row = this->fields.emplace_back();
2841 row.columns[0].MakeHeader(STR_INDUSTRY_CARGOES_PRODUCERS);
2842 row.columns[1].MakeEmpty(CFT_SMALL_EMPTY);
2843 row.columns[2].MakeHeader(STR_INDUSTRY_CARGOES_CUSTOMERS);
2844 row.columns[3].MakeEmpty(CFT_SMALL_EMPTY);
2845 row.columns[4].MakeEmpty(CFT_SMALL_EMPTY);
2847 bool houses_supply = HousesCanSupply(&cid, 1);
2848 bool houses_accept = HousesCanAccept(&cid, 1);
2849 int num_supp = CountMatchingProducingIndustries(&cid, 1) + houses_supply + 1; // Ensure room for the cargo label.
2850 int num_cust = CountMatchingAcceptingIndustries(&cid, 1) + houses_accept;
2851 int num_indrows = std::max(num_supp, num_cust);
2852 for (int i = 0; i < num_indrows; i++) {
2853 CargoesRow &row = this->fields.emplace_back();
2854 row.columns[0].MakeEmpty(CFT_EMPTY);
2855 row.columns[1].MakeCargo(&cid, 1);
2856 row.columns[2].MakeEmpty(CFT_EMPTY);
2857 row.columns[3].MakeEmpty(CFT_EMPTY);
2858 row.columns[4].MakeEmpty(CFT_EMPTY);
2861 this->fields[num_indrows].MakeCargoLabel(0, false); // Add cargo labels at the left bottom.
2863 /* Add suppliers and customers of the cargo. */
2864 int supp_count = 0;
2865 int cust_count = 0;
2866 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2867 const IndustrySpec *indsp = GetIndustrySpec(it);
2868 if (!indsp->enabled) continue;
2870 if (HasCommonValidCargo(&cid, 1, indsp->produced_cargo, lengthof(indsp->produced_cargo))) {
2871 this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, it);
2872 _displayed_industries.set(it);
2873 supp_count++;
2875 if (HasCommonValidCargo(&cid, 1, indsp->accepts_cargo, lengthof(indsp->accepts_cargo))) {
2876 this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 2, it);
2877 _displayed_industries.set(it);
2878 cust_count++;
2881 if (houses_supply) {
2882 this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, NUM_INDUSTRYTYPES);
2883 supp_count++;
2885 if (houses_accept) {
2886 this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 2, NUM_INDUSTRYTYPES);
2887 cust_count++;
2890 this->ShortenCargoColumn(1, 1, num_indrows);
2891 this->vscroll->SetCount(num_indrows);
2892 this->SetDirty();
2893 this->NotifySmallmap();
2897 * Some data on this window has become invalid.
2898 * @param data Information about the changed data.
2899 * - data = 0 .. NUM_INDUSTRYTYPES - 1: Display the chain around the given industry.
2900 * - data = NUM_INDUSTRYTYPES: Stop sending updates to the smallmap window.
2901 * @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.
2903 void OnInvalidateData(int data = 0, bool gui_scope = true) override
2905 if (!gui_scope) return;
2906 if (data == NUM_INDUSTRYTYPES) {
2907 if (this->IsWidgetLowered(WID_IC_NOTIFY)) {
2908 this->RaiseWidget(WID_IC_NOTIFY);
2909 this->SetWidgetDirty(WID_IC_NOTIFY);
2911 return;
2914 assert(data >= 0 && data < NUM_INDUSTRYTYPES);
2915 this->ComputeIndustryDisplay(data);
2918 void DrawWidget(const Rect &r, int widget) const override
2920 if (widget != WID_IC_PANEL) return;
2922 DrawPixelInfo tmp_dpi, *old_dpi;
2923 int width = r.right - r.left + 1;
2924 int height = r.bottom - r.top + 1 - WD_FRAMERECT_TOP - WD_FRAMERECT_BOTTOM;
2925 if (!FillDrawPixelInfo(&tmp_dpi, r.left + WD_FRAMERECT_LEFT, r.top + WD_FRAMERECT_TOP, width, height)) return;
2926 old_dpi = _cur_dpi;
2927 _cur_dpi = &tmp_dpi;
2929 int left_pos = WD_FRAMERECT_LEFT;
2930 if (this->ind_cargo >= NUM_INDUSTRYTYPES) left_pos += (CargoesField::industry_width + CargoesField::cargo_field_width) / 2;
2931 int last_column = (this->ind_cargo < NUM_INDUSTRYTYPES) ? 4 : 2;
2933 const NWidgetBase *nwp = this->GetWidget<NWidgetBase>(WID_IC_PANEL);
2934 int vpos = -this->vscroll->GetPosition() * nwp->resize_y;
2935 for (uint i = 0; i < this->fields.size(); i++) {
2936 int row_height = (i == 0) ? CargoesField::small_height : CargoesField::normal_height;
2937 if (vpos + row_height >= 0) {
2938 int xpos = left_pos;
2939 int col, dir;
2940 if (_current_text_dir == TD_RTL) {
2941 col = last_column;
2942 dir = -1;
2943 } else {
2944 col = 0;
2945 dir = 1;
2947 while (col >= 0 && col <= last_column) {
2948 this->fields[i].columns[col].Draw(xpos, vpos);
2949 xpos += (col & 1) ? CargoesField::cargo_field_width : CargoesField::industry_width;
2950 col += dir;
2953 vpos += row_height;
2954 if (vpos >= height) break;
2957 _cur_dpi = old_dpi;
2961 * Calculate in which field was clicked, and within the field, at what position.
2962 * @param pt Clicked position in the #WID_IC_PANEL widget.
2963 * @param fieldxy If \c true is returned, field x/y coordinate of \a pt.
2964 * @param xy If \c true is returned, x/y coordinate with in the field.
2965 * @return Clicked at a valid position.
2967 bool CalculatePositionInWidget(Point pt, Point *fieldxy, Point *xy)
2969 const NWidgetBase *nw = this->GetWidget<NWidgetBase>(WID_IC_PANEL);
2970 pt.x -= nw->pos_x;
2971 pt.y -= nw->pos_y;
2973 int vpos = WD_FRAMERECT_TOP + CargoesField::small_height - this->vscroll->GetPosition() * nw->resize_y;
2974 if (pt.y < vpos) return false;
2976 int row = (pt.y - vpos) / CargoesField::normal_height; // row is relative to row 1.
2977 if (row + 1 >= (int)this->fields.size()) return false;
2978 vpos = pt.y - vpos - row * CargoesField::normal_height; // Position in the row + 1 field
2979 row++; // rebase row to match index of this->fields.
2981 int xpos = 2 * WD_FRAMERECT_LEFT + ((this->ind_cargo < NUM_INDUSTRYTYPES) ? 0 : (CargoesField::industry_width + CargoesField::cargo_field_width) / 2);
2982 if (pt.x < xpos) return false;
2983 int column;
2984 for (column = 0; column <= 5; column++) {
2985 int width = (column & 1) ? CargoesField::cargo_field_width : CargoesField::industry_width;
2986 if (pt.x < xpos + width) break;
2987 xpos += width;
2989 int num_columns = (this->ind_cargo < NUM_INDUSTRYTYPES) ? 4 : 2;
2990 if (column > num_columns) return false;
2991 xpos = pt.x - xpos;
2993 /* Return both positions, compensating for RTL languages (which works due to the equal symmetry in both displays). */
2994 fieldxy->y = row;
2995 xy->y = vpos;
2996 if (_current_text_dir == TD_RTL) {
2997 fieldxy->x = num_columns - column;
2998 xy->x = ((column & 1) ? CargoesField::cargo_field_width : CargoesField::industry_width) - xpos;
2999 } else {
3000 fieldxy->x = column;
3001 xy->x = xpos;
3003 return true;
3006 void OnClick(Point pt, int widget, int click_count) override
3008 switch (widget) {
3009 case WID_IC_PANEL: {
3010 Point fieldxy, xy;
3011 if (!CalculatePositionInWidget(pt, &fieldxy, &xy)) return;
3013 const CargoesField *fld = this->fields[fieldxy.y].columns + fieldxy.x;
3014 switch (fld->type) {
3015 case CFT_INDUSTRY:
3016 if (fld->u.industry.ind_type < NUM_INDUSTRYTYPES) this->ComputeIndustryDisplay(fld->u.industry.ind_type);
3017 break;
3019 case CFT_CARGO: {
3020 CargoesField *lft = (fieldxy.x > 0) ? this->fields[fieldxy.y].columns + fieldxy.x - 1 : nullptr;
3021 CargoesField *rgt = (fieldxy.x < 4) ? this->fields[fieldxy.y].columns + fieldxy.x + 1 : nullptr;
3022 CargoID cid = fld->CargoClickedAt(lft, rgt, xy);
3023 if (cid != INVALID_CARGO) this->ComputeCargoDisplay(cid);
3024 break;
3027 case CFT_CARGO_LABEL: {
3028 CargoID cid = fld->CargoLabelClickedAt(xy);
3029 if (cid != INVALID_CARGO) this->ComputeCargoDisplay(cid);
3030 break;
3033 default:
3034 break;
3036 break;
3039 case WID_IC_NOTIFY:
3040 this->ToggleWidgetLoweredState(WID_IC_NOTIFY);
3041 this->SetWidgetDirty(WID_IC_NOTIFY);
3042 if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
3044 if (this->IsWidgetLowered(WID_IC_NOTIFY)) {
3045 if (FindWindowByClass(WC_SMALLMAP) == nullptr) ShowSmallMap();
3046 this->NotifySmallmap();
3048 break;
3050 case WID_IC_CARGO_DROPDOWN: {
3051 DropDownList lst;
3052 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
3053 lst.emplace_back(new DropDownListStringItem(cs->name, cs->Index(), false));
3055 if (!lst.empty()) {
3056 int selected = (this->ind_cargo >= NUM_INDUSTRYTYPES) ? (int)(this->ind_cargo - NUM_INDUSTRYTYPES) : -1;
3057 ShowDropDownList(this, std::move(lst), selected, WID_IC_CARGO_DROPDOWN, 0, true);
3059 break;
3062 case WID_IC_IND_DROPDOWN: {
3063 DropDownList lst;
3064 for (IndustryType ind : _sorted_industry_types) {
3065 const IndustrySpec *indsp = GetIndustrySpec(ind);
3066 if (!indsp->enabled) continue;
3067 lst.emplace_back(new DropDownListStringItem(indsp->name, ind, false));
3069 if (!lst.empty()) {
3070 int selected = (this->ind_cargo < NUM_INDUSTRYTYPES) ? (int)this->ind_cargo : -1;
3071 ShowDropDownList(this, std::move(lst), selected, WID_IC_IND_DROPDOWN, 0, true);
3073 break;
3078 void OnDropdownSelect(int widget, int index) override
3080 if (index < 0) return;
3082 switch (widget) {
3083 case WID_IC_CARGO_DROPDOWN:
3084 this->ComputeCargoDisplay(index);
3085 break;
3087 case WID_IC_IND_DROPDOWN:
3088 this->ComputeIndustryDisplay(index);
3089 break;
3093 bool OnTooltip(Point pt, int widget, TooltipCloseCondition close_cond) override
3095 if (widget != WID_IC_PANEL) return false;
3097 Point fieldxy, xy;
3098 if (!CalculatePositionInWidget(pt, &fieldxy, &xy)) return false;
3100 const CargoesField *fld = this->fields[fieldxy.y].columns + fieldxy.x;
3101 CargoID cid = INVALID_CARGO;
3102 switch (fld->type) {
3103 case CFT_CARGO: {
3104 CargoesField *lft = (fieldxy.x > 0) ? this->fields[fieldxy.y].columns + fieldxy.x - 1 : nullptr;
3105 CargoesField *rgt = (fieldxy.x < 4) ? this->fields[fieldxy.y].columns + fieldxy.x + 1 : nullptr;
3106 cid = fld->CargoClickedAt(lft, rgt, xy);
3107 break;
3110 case CFT_CARGO_LABEL: {
3111 cid = fld->CargoLabelClickedAt(xy);
3112 break;
3115 case CFT_INDUSTRY:
3116 if (fld->u.industry.ind_type < NUM_INDUSTRYTYPES && (this->ind_cargo >= NUM_INDUSTRYTYPES || fieldxy.x != 2)) {
3117 GuiShowTooltips(this, STR_INDUSTRY_CARGOES_INDUSTRY_TOOLTIP, 0, nullptr, close_cond);
3119 return true;
3121 default:
3122 break;
3124 if (cid != INVALID_CARGO && (this->ind_cargo < NUM_INDUSTRYTYPES || cid != this->ind_cargo - NUM_INDUSTRYTYPES)) {
3125 const CargoSpec *csp = CargoSpec::Get(cid);
3126 uint64 params[5];
3127 params[0] = csp->name;
3128 GuiShowTooltips(this, STR_INDUSTRY_CARGOES_CARGO_TOOLTIP, 1, params, close_cond);
3129 return true;
3132 return false;
3135 void OnResize() override
3137 this->vscroll->SetCapacityFromWidget(this, WID_IC_PANEL, WD_FRAMERECT_TOP + CargoesField::small_height);
3141 const int IndustryCargoesWindow::HOR_TEXT_PADDING = 5; ///< Horizontal padding around the industry type text.
3142 const int IndustryCargoesWindow::VERT_TEXT_PADDING = 5; ///< Vertical padding around the industry type text.
3145 * Open the industry and cargoes window.
3146 * @param id Industry type to display, \c NUM_INDUSTRYTYPES selects a default industry type.
3148 static void ShowIndustryCargoesWindow(IndustryType id)
3150 if (id >= NUM_INDUSTRYTYPES) {
3151 for (IndustryType ind : _sorted_industry_types) {
3152 const IndustrySpec *indsp = GetIndustrySpec(ind);
3153 if (indsp->enabled) {
3154 id = ind;
3155 break;
3158 if (id >= NUM_INDUSTRYTYPES) return;
3161 Window *w = BringWindowToFrontById(WC_INDUSTRY_CARGOES, 0);
3162 if (w != nullptr) {
3163 w->InvalidateData(id);
3164 return;
3166 new IndustryCargoesWindow(id);
3169 /** Open the industry and cargoes window with an industry. */
3170 void ShowIndustryCargoesWindow()
3172 ShowIndustryCargoesWindow(NUM_INDUSTRYTYPES);