Fix 03cc0d6: Mark level crossings dirty when removing road from them, not from bridge...
[openttd-github.git] / src / industry_gui.cpp
blobcf78f4db9026e55c59de38e75a291623351c5f19
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"
42 #include "industry_cmd.h"
44 #include "table/strings.h"
46 #include <bitset>
48 #include "safeguards.h"
50 bool _ignore_restrictions;
51 std::bitset<NUM_INDUSTRYTYPES> _displayed_industries; ///< Communication from the industry chain window to the smallmap window about what industries to display.
53 /** Cargo suffix type (for which window is it requested) */
54 enum CargoSuffixType {
55 CST_FUND, ///< Fund-industry window
56 CST_VIEW, ///< View-industry window
57 CST_DIR, ///< Industry-directory window
60 /** Ways of displaying the cargo. */
61 enum CargoSuffixDisplay {
62 CSD_CARGO, ///< Display the cargo without sub-type (cb37 result 401).
63 CSD_CARGO_AMOUNT, ///< Display the cargo and amount (if useful), but no sub-type (cb37 result 400 or fail).
64 CSD_CARGO_TEXT, ///< Display then cargo and supplied string (cb37 result 800-BFF).
65 CSD_CARGO_AMOUNT_TEXT, ///< Display then cargo, amount, and string (cb37 result 000-3FF).
68 /** Transfer storage of cargo suffix information. */
69 struct CargoSuffix {
70 CargoSuffixDisplay display; ///< How to display the cargo and text.
71 char text[512]; ///< Cargo suffix text.
74 static void ShowIndustryCargoesWindow(IndustryType id);
76 /**
77 * Gets the string to display after the cargo name (using callback 37)
78 * @param cargo the cargo for which the suffix is requested, meaning depends on presence of flag 18 in prop 1A
79 * @param cst the cargo suffix type (for which window is it requested). @see CargoSuffixType
80 * @param ind the industry (nullptr if in fund window)
81 * @param ind_type the industry type
82 * @param indspec the industry spec
83 * @param suffix is filled with the string to display
85 static void GetCargoSuffix(uint cargo, CargoSuffixType cst, const Industry *ind, IndustryType ind_type, const IndustrySpec *indspec, CargoSuffix &suffix)
87 suffix.text[0] = '\0';
88 suffix.display = CSD_CARGO_AMOUNT;
90 if (HasBit(indspec->callback_mask, CBM_IND_CARGO_SUFFIX)) {
91 TileIndex t = (cst != CST_FUND) ? ind->location.tile : INVALID_TILE;
92 uint16 callback = GetIndustryCallback(CBID_INDUSTRY_CARGO_SUFFIX, 0, (cst << 8) | cargo, const_cast<Industry *>(ind), ind_type, t);
93 if (callback == CALLBACK_FAILED) return;
95 if (indspec->grf_prop.grffile->grf_version < 8) {
96 if (GB(callback, 0, 8) == 0xFF) return;
97 if (callback < 0x400) {
98 StartTextRefStackUsage(indspec->grf_prop.grffile, 6);
99 GetString(suffix.text, GetGRFStringID(indspec->grf_prop.grffile->grfid, 0xD000 + callback), lastof(suffix.text));
100 StopTextRefStackUsage();
101 suffix.display = CSD_CARGO_AMOUNT_TEXT;
102 return;
104 ErrorUnknownCallbackResult(indspec->grf_prop.grffile->grfid, CBID_INDUSTRY_CARGO_SUFFIX, callback);
105 return;
107 } else { // GRF version 8 or higher.
108 if (callback == 0x400) return;
109 if (callback == 0x401) {
110 suffix.display = CSD_CARGO;
111 return;
113 if (callback < 0x400) {
114 StartTextRefStackUsage(indspec->grf_prop.grffile, 6);
115 GetString(suffix.text, GetGRFStringID(indspec->grf_prop.grffile->grfid, 0xD000 + callback), lastof(suffix.text));
116 StopTextRefStackUsage();
117 suffix.display = CSD_CARGO_AMOUNT_TEXT;
118 return;
120 if (callback >= 0x800 && callback < 0xC00) {
121 StartTextRefStackUsage(indspec->grf_prop.grffile, 6);
122 GetString(suffix.text, GetGRFStringID(indspec->grf_prop.grffile->grfid, 0xD000 - 0x800 + callback), lastof(suffix.text));
123 StopTextRefStackUsage();
124 suffix.display = CSD_CARGO_TEXT;
125 return;
127 ErrorUnknownCallbackResult(indspec->grf_prop.grffile->grfid, CBID_INDUSTRY_CARGO_SUFFIX, callback);
128 return;
133 enum CargoSuffixInOut {
134 CARGOSUFFIX_OUT = 0,
135 CARGOSUFFIX_IN = 1,
139 * Gets all strings to display after the cargoes of industries (using callback 37)
140 * @param use_input get suffixes for output cargoes or input cargoes?
141 * @param cst the cargo suffix type (for which window is it requested). @see CargoSuffixType
142 * @param ind the industry (nullptr if in fund window)
143 * @param ind_type the industry type
144 * @param indspec the industry spec
145 * @param cargoes array with cargotypes. for CT_INVALID no suffix will be determined
146 * @param suffixes is filled with the suffixes
148 template <typename TC, typename TS>
149 static inline void GetAllCargoSuffixes(CargoSuffixInOut use_input, CargoSuffixType cst, const Industry *ind, IndustryType ind_type, const IndustrySpec *indspec, const TC &cargoes, TS &suffixes)
151 static_assert(lengthof(cargoes) <= lengthof(suffixes));
153 if (indspec->behaviour & INDUSTRYBEH_CARGOTYPES_UNLIMITED) {
154 /* Reworked behaviour with new many-in-many-out scheme */
155 for (uint j = 0; j < lengthof(suffixes); j++) {
156 if (cargoes[j] != CT_INVALID) {
157 byte local_id = indspec->grf_prop.grffile->cargo_map[cargoes[j]]; // should we check the value for valid?
158 uint cargotype = local_id << 16 | use_input;
159 GetCargoSuffix(cargotype, cst, ind, ind_type, indspec, suffixes[j]);
160 } else {
161 suffixes[j].text[0] = '\0';
162 suffixes[j].display = CSD_CARGO;
165 } else {
166 /* Compatible behaviour with old 3-in-2-out scheme */
167 for (uint j = 0; j < lengthof(suffixes); j++) {
168 suffixes[j].text[0] = '\0';
169 suffixes[j].display = CSD_CARGO;
171 switch (use_input) {
172 case CARGOSUFFIX_OUT:
173 if (cargoes[0] != CT_INVALID) GetCargoSuffix(3, cst, ind, ind_type, indspec, suffixes[0]);
174 if (cargoes[1] != CT_INVALID) GetCargoSuffix(4, cst, ind, ind_type, indspec, suffixes[1]);
175 break;
176 case CARGOSUFFIX_IN:
177 if (cargoes[0] != CT_INVALID) GetCargoSuffix(0, cst, ind, ind_type, indspec, suffixes[0]);
178 if (cargoes[1] != CT_INVALID) GetCargoSuffix(1, cst, ind, ind_type, indspec, suffixes[1]);
179 if (cargoes[2] != CT_INVALID) GetCargoSuffix(2, cst, ind, ind_type, indspec, suffixes[2]);
180 break;
181 default:
182 NOT_REACHED();
187 std::array<IndustryType, NUM_INDUSTRYTYPES> _sorted_industry_types; ///< Industry types sorted by name.
189 /** Sort industry types by their name. */
190 static bool IndustryTypeNameSorter(const IndustryType &a, const IndustryType &b)
192 static char industry_name[2][64];
194 const IndustrySpec *indsp1 = GetIndustrySpec(a);
195 GetString(industry_name[0], indsp1->name, lastof(industry_name[0]));
197 const IndustrySpec *indsp2 = GetIndustrySpec(b);
198 GetString(industry_name[1], indsp2->name, lastof(industry_name[1]));
200 int r = strnatcmp(industry_name[0], industry_name[1]); // Sort by name (natural sorting).
202 /* If the names are equal, sort by industry type. */
203 return (r != 0) ? r < 0 : (a < b);
207 * Initialize the list of sorted industry types.
209 void SortIndustryTypes()
211 /* Add each industry type to the list. */
212 for (IndustryType i = 0; i < NUM_INDUSTRYTYPES; i++) {
213 _sorted_industry_types[i] = i;
216 /* Sort industry types by name. */
217 std::sort(_sorted_industry_types.begin(), _sorted_industry_types.end(), IndustryTypeNameSorter);
221 * Command callback. In case of failure to build an industry, show an error message.
222 * @param cmd Unused.
223 * @param result Result of the command.
224 * @param tile Tile where the industry is placed.
225 * @param indtype Industry type.
227 void CcBuildIndustry(Commands cmd, const CommandCost &result, TileIndex tile, IndustryType indtype, uint32, bool, uint32)
229 if (result.Succeeded()) return;
231 if (indtype < NUM_INDUSTRYTYPES) {
232 const IndustrySpec *indsp = GetIndustrySpec(indtype);
233 if (indsp->enabled) {
234 SetDParam(0, indsp->name);
235 ShowErrorMessage(STR_ERROR_CAN_T_BUILD_HERE, result.GetErrorMessage(), WL_INFO, TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE);
240 static const NWidgetPart _nested_build_industry_widgets[] = {
241 NWidget(NWID_HORIZONTAL),
242 NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
243 NWidget(WWT_CAPTION, COLOUR_DARK_GREEN), SetDataTip(STR_FUND_INDUSTRY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
244 NWidget(WWT_SHADEBOX, COLOUR_DARK_GREEN),
245 NWidget(WWT_DEFSIZEBOX, COLOUR_DARK_GREEN),
246 NWidget(WWT_STICKYBOX, COLOUR_DARK_GREEN),
247 EndContainer(),
248 NWidget(NWID_SELECTION, COLOUR_DARK_GREEN, WID_DPI_SCENARIO_EDITOR_PANE),
249 NWidget(NWID_VERTICAL),
250 NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, WID_DPI_CREATE_RANDOM_INDUSTRIES_WIDGET), SetMinimalSize(0, 12), SetFill(1, 0), SetResize(1, 0),
251 SetDataTip(STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES, STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES_TOOLTIP),
252 NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, WID_DPI_REMOVE_ALL_INDUSTRIES_WIDGET), SetMinimalSize(0, 12), SetFill(1, 0), SetResize(1, 0),
253 SetDataTip(STR_FUND_INDUSTRY_REMOVE_ALL_INDUSTRIES, STR_FUND_INDUSTRY_REMOVE_ALL_INDUSTRIES_TOOLTIP),
254 EndContainer(),
255 EndContainer(),
256 NWidget(NWID_HORIZONTAL),
257 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),
258 NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, WID_DPI_SCROLLBAR),
259 EndContainer(),
260 NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_DPI_INFOPANEL), SetResize(1, 0),
261 EndContainer(),
262 NWidget(NWID_HORIZONTAL),
263 NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, WID_DPI_DISPLAY_WIDGET), SetFill(1, 0), SetResize(1, 0),
264 SetDataTip(STR_INDUSTRY_DISPLAY_CHAIN, STR_INDUSTRY_DISPLAY_CHAIN_TOOLTIP),
265 NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, WID_DPI_FUND_WIDGET), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_JUST_STRING, STR_NULL),
266 NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
267 EndContainer(),
270 /** Window definition of the dynamic place industries gui */
271 static WindowDesc _build_industry_desc(
272 WDP_AUTO, "build_industry", 170, 212,
273 WC_BUILD_INDUSTRY, WC_NONE,
274 WDF_CONSTRUCTION,
275 _nested_build_industry_widgets, lengthof(_nested_build_industry_widgets)
278 /** Build (fund or prospect) a new industry, */
279 class BuildIndustryWindow : public Window {
280 int selected_index; ///< index of the element in the matrix
281 IndustryType selected_type; ///< industry corresponding to the above index
282 uint16 count; ///< How many industries are loaded
283 IndustryType index[NUM_INDUSTRYTYPES + 1]; ///< Type of industry, in the order it was loaded
284 bool enabled[NUM_INDUSTRYTYPES + 1]; ///< availability state, coming from CBID_INDUSTRY_PROBABILITY (if ever)
285 Scrollbar *vscroll;
286 Dimension legend; ///< Dimension of the legend 'blob'.
288 /** The largest allowed minimum-width of the window, given in line heights */
289 static const int MAX_MINWIDTH_LINEHEIGHTS = 20;
291 void SetupArrays()
293 this->count = 0;
295 for (uint i = 0; i < lengthof(this->index); i++) {
296 this->index[i] = INVALID_INDUSTRYTYPE;
297 this->enabled[i] = false;
300 /* Fill the arrays with industries.
301 * The tests performed after the enabled allow to load the industries
302 * In the same way they are inserted by grf (if any)
304 for (IndustryType ind : _sorted_industry_types) {
305 const IndustrySpec *indsp = GetIndustrySpec(ind);
306 if (indsp->enabled) {
307 /* Rule is that editor mode loads all industries.
308 * In game mode, all non raw industries are loaded too
309 * and raw ones are loaded only when setting allows it */
310 if (_game_mode != GM_EDITOR && indsp->IsRawIndustry() && _settings_game.construction.raw_industry_construction == 0) {
311 /* Unselect if the industry is no longer in the list */
312 if (this->selected_type == ind) this->selected_index = -1;
313 continue;
315 this->index[this->count] = ind;
316 this->enabled[this->count] = (_game_mode == GM_EDITOR) || GetIndustryProbabilityCallback(ind, IACT_USERCREATION, 1) > 0;
317 /* Keep the selection to the correct line */
318 if (this->selected_type == ind) this->selected_index = this->count;
319 this->count++;
323 /* first industry type is selected if the current selection is invalid.
324 * I'll be damned if there are none available ;) */
325 if (this->selected_index == -1) {
326 this->selected_index = 0;
327 this->selected_type = this->index[0];
330 this->vscroll->SetCount(this->count);
333 /** Update status of the fund and display-chain widgets. */
334 void SetButtons()
336 this->SetWidgetDisabledState(WID_DPI_FUND_WIDGET, this->selected_type != INVALID_INDUSTRYTYPE && !this->enabled[this->selected_index]);
337 this->SetWidgetDisabledState(WID_DPI_DISPLAY_WIDGET, this->selected_type == INVALID_INDUSTRYTYPE && this->enabled[this->selected_index]);
341 * Build a string of cargo names with suffixes attached.
342 * This is distinct from the CARGO_LIST string formatting code in two ways:
343 * - This cargo list uses the order defined by the industry, rather than alphabetic.
344 * - NewGRF-supplied suffix strings can be attached to each cargo.
346 * @param cargolist Array of CargoID to display
347 * @param cargo_suffix Array of suffixes to attach to each cargo
348 * @param cargolistlen Length of arrays
349 * @param prefixstr String to use for the first item
350 * @return A formatted raw string
352 std::string MakeCargoListString(const CargoID *cargolist, const CargoSuffix *cargo_suffix, int cargolistlen, StringID prefixstr) const
354 std::string cargostring;
355 char buf[1024];
356 int numcargo = 0;
357 int firstcargo = -1;
359 for (int j = 0; j < cargolistlen; j++) {
360 if (cargolist[j] == CT_INVALID) continue;
361 numcargo++;
362 if (firstcargo < 0) {
363 firstcargo = j;
364 continue;
366 SetDParam(0, CargoSpec::Get(cargolist[j])->name);
367 SetDParamStr(1, cargo_suffix[j].text);
368 GetString(buf, STR_INDUSTRY_VIEW_CARGO_LIST_EXTENSION, lastof(buf));
369 cargostring += buf;
372 if (numcargo > 0) {
373 SetDParam(0, CargoSpec::Get(cargolist[firstcargo])->name);
374 SetDParamStr(1, cargo_suffix[firstcargo].text);
375 GetString(buf, prefixstr, lastof(buf));
376 cargostring = std::string(buf) + cargostring;
377 } else {
378 SetDParam(0, STR_JUST_NOTHING);
379 SetDParamStr(1, "");
380 GetString(buf, prefixstr, lastof(buf));
381 cargostring = std::string(buf);
384 return cargostring;
387 public:
388 BuildIndustryWindow() : Window(&_build_industry_desc)
390 this->selected_index = -1;
391 this->selected_type = INVALID_INDUSTRYTYPE;
393 this->CreateNestedTree();
394 this->vscroll = this->GetScrollbar(WID_DPI_SCROLLBAR);
395 this->FinishInitNested(0);
397 this->SetButtons();
399 /* Show scenario editor tools in editor. */
400 if (_game_mode != GM_EDITOR) {
401 auto *se_tools = this->GetWidget<NWidgetStacked>(WID_DPI_SCENARIO_EDITOR_PANE);
402 se_tools->SetDisplayedPlane(SZSP_HORIZONTAL);
403 this->ReInit();
407 void OnInit() override
409 /* Width of the legend blob -- slightly larger than the smallmap legend blob. */
410 this->legend.height = FONT_HEIGHT_SMALL;
411 this->legend.width = this->legend.height * 8 / 5;
413 this->SetupArrays();
416 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
418 switch (widget) {
419 case WID_DPI_MATRIX_WIDGET: {
420 Dimension d = GetStringBoundingBox(STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES);
421 for (uint16 i = 0; i < this->count; i++) {
422 if (this->index[i] == INVALID_INDUSTRYTYPE) continue;
423 d = maxdim(d, GetStringBoundingBox(GetIndustrySpec(this->index[i])->name));
425 resize->height = std::max<uint>(this->legend.height, FONT_HEIGHT_NORMAL) + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;
426 d.width += this->legend.width + ScaleFontTrad(7) + padding.width;
427 d.height = 5 * resize->height;
428 *size = maxdim(*size, d);
429 break;
432 case WID_DPI_INFOPANEL: {
433 /* Extra line for cost outside of editor. */
434 int height = 2 + (_game_mode == GM_EDITOR ? 0 : 1);
435 uint extra_lines_req = 0;
436 uint extra_lines_prd = 0;
437 uint extra_lines_newgrf = 0;
438 uint max_minwidth = FONT_HEIGHT_NORMAL * MAX_MINWIDTH_LINEHEIGHTS;
439 Dimension d = {0, 0};
440 for (uint16 i = 0; i < this->count; i++) {
441 if (this->index[i] == INVALID_INDUSTRYTYPE) continue;
443 const IndustrySpec *indsp = GetIndustrySpec(this->index[i]);
444 CargoSuffix cargo_suffix[lengthof(indsp->accepts_cargo)];
446 /* Measure the accepted cargoes, if any. */
447 GetAllCargoSuffixes(CARGOSUFFIX_IN, CST_FUND, nullptr, this->index[i], indsp, indsp->accepts_cargo, cargo_suffix);
448 std::string cargostring = this->MakeCargoListString(indsp->accepts_cargo, cargo_suffix, lengthof(indsp->accepts_cargo), STR_INDUSTRY_VIEW_REQUIRES_N_CARGO);
449 Dimension strdim = GetStringBoundingBox(cargostring.c_str());
450 if (strdim.width > max_minwidth) {
451 extra_lines_req = std::max(extra_lines_req, strdim.width / max_minwidth + 1);
452 strdim.width = max_minwidth;
454 d = maxdim(d, strdim);
456 /* Measure the produced cargoes, if any. */
457 GetAllCargoSuffixes(CARGOSUFFIX_OUT, CST_FUND, nullptr, this->index[i], indsp, indsp->produced_cargo, cargo_suffix);
458 cargostring = this->MakeCargoListString(indsp->produced_cargo, cargo_suffix, lengthof(indsp->produced_cargo), STR_INDUSTRY_VIEW_PRODUCES_N_CARGO);
459 strdim = GetStringBoundingBox(cargostring.c_str());
460 if (strdim.width > max_minwidth) {
461 extra_lines_prd = std::max(extra_lines_prd, strdim.width / max_minwidth + 1);
462 strdim.width = max_minwidth;
464 d = maxdim(d, strdim);
466 if (indsp->grf_prop.grffile != nullptr) {
467 /* Reserve a few extra lines for text from an industry NewGRF. */
468 extra_lines_newgrf = 4;
472 /* Set it to something more sane :) */
473 height += extra_lines_prd + extra_lines_req + extra_lines_newgrf;
474 size->height = height * FONT_HEIGHT_NORMAL + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
475 size->width = d.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
476 break;
479 case WID_DPI_FUND_WIDGET: {
480 Dimension d = GetStringBoundingBox(STR_FUND_INDUSTRY_BUILD_NEW_INDUSTRY);
481 d = maxdim(d, GetStringBoundingBox(STR_FUND_INDUSTRY_PROSPECT_NEW_INDUSTRY));
482 d = maxdim(d, GetStringBoundingBox(STR_FUND_INDUSTRY_FUND_NEW_INDUSTRY));
483 d.width += padding.width;
484 d.height += padding.height;
485 *size = maxdim(*size, d);
486 break;
491 void SetStringParameters(int widget) const override
493 switch (widget) {
494 case WID_DPI_FUND_WIDGET:
495 /* Raw industries might be prospected. Show this fact by changing the string
496 * In Editor, you just build, while ingame, or you fund or you prospect */
497 if (_game_mode == GM_EDITOR) {
498 /* We've chosen many random industries but no industries have been specified */
499 SetDParam(0, STR_FUND_INDUSTRY_BUILD_NEW_INDUSTRY);
500 } else {
501 if (count > 0) {
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);
504 } else {
505 SetDParam(0, STR_FUND_INDUSTRY_FUND_NEW_INDUSTRY);
508 break;
512 void DrawWidget(const Rect &r, int widget) const override
514 switch (widget) {
515 case WID_DPI_MATRIX_WIDGET: {
516 uint text_left, text_right, icon_left, icon_right;
517 if (_current_text_dir == TD_RTL) {
518 icon_right = r.right - WD_MATRIX_RIGHT;
519 icon_left = icon_right - this->legend.width;
520 text_right = icon_left - ScaleFontTrad(7);
521 text_left = r.left + WD_MATRIX_LEFT;
522 } else {
523 icon_left = r.left + WD_MATRIX_LEFT;
524 icon_right = icon_left + this->legend.width;
525 text_left = icon_right + ScaleFontTrad(7);
526 text_right = r.right - WD_MATRIX_RIGHT;
529 /* Vertical offset for legend icon. */
530 int icon_top = (this->resize.step_height - this->legend.height + 1) / 2;
531 int icon_bottom = icon_top + this->legend.height;
533 int y = r.top;
534 for (uint16 i = 0; i < this->vscroll->GetCapacity() && i + this->vscroll->GetPosition() < this->count; i++) {
535 bool selected = this->selected_index == i + this->vscroll->GetPosition();
537 if (this->index[i + this->vscroll->GetPosition()] == INVALID_INDUSTRYTYPE) {
538 DrawString(text_left, text_right, y + WD_MATRIX_TOP, STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES, selected ? TC_WHITE : TC_ORANGE);
539 y += this->resize.step_height;
540 continue;
542 const IndustrySpec *indsp = GetIndustrySpec(this->index[i + this->vscroll->GetPosition()]);
544 /* Draw the name of the industry in white is selected, otherwise, in orange */
545 DrawString(text_left, text_right, y + WD_MATRIX_TOP, indsp->name, selected ? TC_WHITE : TC_ORANGE);
546 GfxFillRect(icon_left, y + icon_top, icon_right, y + icon_bottom, selected ? PC_WHITE : PC_BLACK);
547 GfxFillRect(icon_left + 1, y + icon_top + 1, icon_right - 1, y + icon_bottom - 1, indsp->map_colour);
549 y += this->resize.step_height;
551 break;
554 case WID_DPI_INFOPANEL: {
555 int y = r.top + WD_FRAMERECT_TOP;
556 int bottom = r.bottom - WD_FRAMERECT_BOTTOM;
557 int left = r.left + WD_FRAMERECT_LEFT;
558 int right = r.right - WD_FRAMERECT_RIGHT;
560 if (this->selected_type == INVALID_INDUSTRYTYPE) {
561 DrawStringMultiLine(left, right, y, bottom, STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES_TOOLTIP);
562 break;
565 const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
567 if (_game_mode != GM_EDITOR) {
568 SetDParam(0, indsp->GetConstructionCost());
569 DrawString(left, right, y, STR_FUND_INDUSTRY_INDUSTRY_BUILD_COST);
570 y += FONT_HEIGHT_NORMAL;
573 CargoSuffix cargo_suffix[lengthof(indsp->accepts_cargo)];
575 /* Draw the accepted cargoes, if any. Otherwise, will print "Nothing". */
576 GetAllCargoSuffixes(CARGOSUFFIX_IN, CST_FUND, nullptr, this->selected_type, indsp, indsp->accepts_cargo, cargo_suffix);
577 std::string cargostring = this->MakeCargoListString(indsp->accepts_cargo, cargo_suffix, lengthof(indsp->accepts_cargo), STR_INDUSTRY_VIEW_REQUIRES_N_CARGO);
578 y = DrawStringMultiLine(left, right, y, bottom, cargostring);
580 /* Draw the produced cargoes, if any. Otherwise, will print "Nothing". */
581 GetAllCargoSuffixes(CARGOSUFFIX_OUT, CST_FUND, nullptr, this->selected_type, indsp, indsp->produced_cargo, cargo_suffix);
582 cargostring = this->MakeCargoListString(indsp->produced_cargo, cargo_suffix, lengthof(indsp->produced_cargo), STR_INDUSTRY_VIEW_PRODUCES_N_CARGO);
583 y = DrawStringMultiLine(left, right, y, bottom, cargostring);
585 /* Get the additional purchase info text, if it has not already been queried. */
586 if (HasBit(indsp->callback_mask, CBM_IND_FUND_MORE_TEXT)) {
587 uint16 callback_res = GetIndustryCallback(CBID_INDUSTRY_FUND_MORE_TEXT, 0, 0, nullptr, this->selected_type, INVALID_TILE);
588 if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
589 if (callback_res > 0x400) {
590 ErrorUnknownCallbackResult(indsp->grf_prop.grffile->grfid, CBID_INDUSTRY_FUND_MORE_TEXT, callback_res);
591 } else {
592 StringID str = GetGRFStringID(indsp->grf_prop.grffile->grfid, 0xD000 + callback_res); // No. here's the new string
593 if (str != STR_UNDEFINED) {
594 StartTextRefStackUsage(indsp->grf_prop.grffile, 6);
595 DrawStringMultiLine(left, right, y, bottom, str, TC_YELLOW);
596 StopTextRefStackUsage();
601 break;
606 static void AskManyRandomIndustriesCallback(Window *w, bool confirmed)
608 if (!confirmed) return;
610 if (Town::GetNumItems() == 0) {
611 ShowErrorMessage(STR_ERROR_CAN_T_GENERATE_INDUSTRIES, STR_ERROR_MUST_FOUND_TOWN_FIRST, WL_INFO);
612 } else {
613 extern void GenerateIndustries();
614 Backup<bool> old_generating_world(_generating_world, true, FILE_LINE);
615 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP);
616 GenerateIndustries();
617 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP);
618 old_generating_world.Restore();
622 static void AskRemoveAllIndustriesCallback(Window *w, bool confirmed)
624 if (!confirmed) return;
626 for (Industry *industry : Industry::Iterate()) delete industry;
628 /* Clear farmland. */
629 for (TileIndex tile = 0; tile < MapSize(); tile++) {
630 if (IsTileType(tile, MP_CLEAR) && GetRawClearGround(tile) == CLEAR_FIELDS) {
631 MakeClear(tile, CLEAR_GRASS, 3);
635 MarkWholeScreenDirty();
638 void OnClick(Point pt, int widget, int click_count) override
640 switch (widget) {
641 case WID_DPI_CREATE_RANDOM_INDUSTRIES_WIDGET: {
642 assert(_game_mode == GM_EDITOR);
643 this->HandleButtonClick(WID_DPI_CREATE_RANDOM_INDUSTRIES_WIDGET);
644 ShowQuery(STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES_CAPTION, STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES_QUERY, nullptr, AskManyRandomIndustriesCallback);
645 break;
648 case WID_DPI_REMOVE_ALL_INDUSTRIES_WIDGET: {
649 assert(_game_mode == GM_EDITOR);
650 this->HandleButtonClick(WID_DPI_REMOVE_ALL_INDUSTRIES_WIDGET);
651 ShowQuery(STR_FUND_INDUSTRY_REMOVE_ALL_INDUSTRIES_CAPTION, STR_FUND_INDUSTRY_REMOVE_ALL_INDUSTRIES_QUERY, nullptr, AskRemoveAllIndustriesCallback);
652 break;
655 case WID_DPI_MATRIX_WIDGET: {
656 int y = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_DPI_MATRIX_WIDGET);
657 if (y < this->count) { // Is it within the boundaries of available data?
658 this->selected_index = y;
659 this->selected_type = this->index[y];
660 const IndustrySpec *indsp = (this->selected_type == INVALID_INDUSTRYTYPE) ? nullptr : GetIndustrySpec(this->selected_type);
662 this->SetDirty();
664 if (_thd.GetCallbackWnd() == this &&
665 ((_game_mode != GM_EDITOR && _settings_game.construction.raw_industry_construction == 2 && indsp != nullptr && indsp->IsRawIndustry()) ||
666 this->selected_type == INVALID_INDUSTRYTYPE ||
667 !this->enabled[this->selected_index])) {
668 /* Reset the button state if going to prospecting or "build many industries" */
669 this->RaiseButtons();
670 ResetObjectToPlace();
673 this->SetButtons();
674 if (this->enabled[this->selected_index] && click_count > 1) this->OnClick(pt, WID_DPI_FUND_WIDGET, 1);
676 break;
679 case WID_DPI_DISPLAY_WIDGET:
680 if (this->selected_type != INVALID_INDUSTRYTYPE) ShowIndustryCargoesWindow(this->selected_type);
681 break;
683 case WID_DPI_FUND_WIDGET: {
684 if (this->selected_type != INVALID_INDUSTRYTYPE) {
685 if (_game_mode != GM_EDITOR && _settings_game.construction.raw_industry_construction == 2 && GetIndustrySpec(this->selected_type)->IsRawIndustry()) {
686 Command<CMD_BUILD_INDUSTRY>::Post(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY, 0, this->selected_type, 0, false, InteractiveRandom());
687 this->HandleButtonClick(WID_DPI_FUND_WIDGET);
688 } else {
689 HandlePlacePushButton(this, WID_DPI_FUND_WIDGET, SPR_CURSOR_INDUSTRY, HT_RECT);
692 break;
697 void OnResize() override
699 /* Adjust the number of items in the matrix depending of the resize */
700 this->vscroll->SetCapacityFromWidget(this, WID_DPI_MATRIX_WIDGET);
703 void OnPlaceObject(Point pt, TileIndex tile) override
705 bool success = true;
706 /* We do not need to protect ourselves against "Random Many Industries" in this mode */
707 const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
708 uint32 seed = InteractiveRandom();
709 uint32 layout_index = InteractiveRandomRange((uint32)indsp->layouts.size());
711 if (_game_mode == GM_EDITOR) {
712 /* Show error if no town exists at all */
713 if (Town::GetNumItems() == 0) {
714 SetDParam(0, indsp->name);
715 ShowErrorMessage(STR_ERROR_CAN_T_BUILD_HERE, STR_ERROR_MUST_FOUND_TOWN_FIRST, WL_INFO, pt.x, pt.y);
716 return;
719 Backup<CompanyID> cur_company(_current_company, OWNER_NONE, FILE_LINE);
720 Backup<bool> old_generating_world(_generating_world, true, FILE_LINE);
721 _ignore_restrictions = true;
723 Command<CMD_BUILD_INDUSTRY>::Post(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY, &CcBuildIndustry, tile, this->selected_type, layout_index, false, seed);
725 cur_company.Restore();
726 old_generating_world.Restore();
727 _ignore_restrictions = false;
728 } else {
729 success = Command<CMD_BUILD_INDUSTRY>::Post(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY, tile, this->selected_type, layout_index, false, seed);
732 /* If an industry has been built, just reset the cursor and the system */
733 if (success && !_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
736 void OnHundredthTick() override
738 if (_game_mode == GM_EDITOR) return;
739 if (this->count == 0) return;
740 const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
742 if (indsp->enabled) {
743 bool call_back_result = GetIndustryProbabilityCallback(this->selected_type, IACT_USERCREATION, 1) > 0;
745 /* Only if result does match the previous state would it require a redraw. */
746 if (call_back_result != this->enabled[this->selected_index]) {
747 this->enabled[this->selected_index] = call_back_result;
748 this->SetButtons();
749 this->SetDirty();
754 void OnTimeout() override
756 this->RaiseButtons();
759 void OnPlaceObjectAbort() override
761 this->RaiseButtons();
765 * Some data on this window has become invalid.
766 * @param data Information about the changed data.
767 * @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.
769 void OnInvalidateData(int data = 0, bool gui_scope = true) override
771 if (!gui_scope) return;
772 this->SetupArrays();
774 const IndustrySpec *indsp = (this->selected_type == INVALID_INDUSTRYTYPE) ? nullptr : GetIndustrySpec(this->selected_type);
775 if (indsp == nullptr) this->enabled[this->selected_index] = _settings_game.difficulty.industry_density != ID_FUND_ONLY;
776 this->SetButtons();
777 this->SetDirty();
781 void ShowBuildIndustryWindow()
783 if (_game_mode != GM_EDITOR && !Company::IsValidID(_local_company)) return;
784 if (BringWindowToFrontById(WC_BUILD_INDUSTRY, 0)) return;
785 new BuildIndustryWindow();
788 static void UpdateIndustryProduction(Industry *i);
790 static inline bool IsProductionAlterable(const Industry *i)
792 const IndustrySpec *is = GetIndustrySpec(i->type);
793 bool has_prod = false;
794 for (size_t j = 0; j < lengthof(is->production_rate); j++) {
795 if (is->production_rate[j] != 0) {
796 has_prod = true;
797 break;
800 return ((_game_mode == GM_EDITOR || _cheats.setup_prod.value) &&
801 (has_prod || is->IsRawIndustry()) &&
802 !_networking);
805 class IndustryViewWindow : public Window
807 /** Modes for changing production */
808 enum Editability {
809 EA_NONE, ///< Not alterable
810 EA_MULTIPLIER, ///< Allow changing the production multiplier
811 EA_RATE, ///< Allow changing the production rates
814 /** Specific lines in the info panel */
815 enum InfoLine {
816 IL_NONE, ///< No line
817 IL_MULTIPLIER, ///< Production multiplier
818 IL_RATE1, ///< Production rate of cargo 1
819 IL_RATE2, ///< Production rate of cargo 2
822 Editability editable; ///< Mode for changing production
823 InfoLine editbox_line; ///< The line clicked to open the edit box
824 InfoLine clicked_line; ///< The line of the button that has been clicked
825 byte clicked_button; ///< The button that has been clicked (to raise)
826 int production_offset_y; ///< The offset of the production texts/buttons
827 int info_height; ///< Height needed for the #WID_IV_INFO panel
829 public:
830 IndustryViewWindow(WindowDesc *desc, WindowNumber window_number) : Window(desc)
832 this->flags |= WF_DISABLE_VP_SCROLL;
833 this->editbox_line = IL_NONE;
834 this->clicked_line = IL_NONE;
835 this->clicked_button = 0;
836 this->info_height = WD_FRAMERECT_TOP + 2 * FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM + 1; // Info panel has at least two lines text.
838 this->InitNested(window_number);
839 NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_IV_VIEWPORT);
840 nvp->InitializeViewport(this, Industry::Get(window_number)->location.GetCenterTile(), ScaleZoomGUI(ZOOM_LVL_INDUSTRY));
842 this->InvalidateData();
845 void OnPaint() override
847 this->DrawWidgets();
849 if (this->IsShaded()) return; // Don't draw anything when the window is shaded.
851 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_IV_INFO);
852 uint expected = this->DrawInfo(nwi->pos_x, nwi->pos_x + nwi->current_x - 1, nwi->pos_y) - nwi->pos_y;
853 if (expected > nwi->current_y - 1) {
854 this->info_height = expected + 1;
855 this->ReInit();
856 return;
861 * Draw the text in the #WID_IV_INFO panel.
862 * @param left Left edge of the panel.
863 * @param right Right edge of the panel.
864 * @param top Top edge of the panel.
865 * @return Expected position of the bottom edge of the panel.
867 int DrawInfo(uint left, uint right, uint top)
869 Industry *i = Industry::Get(this->window_number);
870 const IndustrySpec *ind = GetIndustrySpec(i->type);
871 int y = top + WD_FRAMERECT_TOP;
872 bool first = true;
873 bool has_accept = false;
875 if (i->prod_level == PRODLEVEL_CLOSURE) {
876 DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_INDUSTRY_ANNOUNCED_CLOSURE);
877 y += 2 * FONT_HEIGHT_NORMAL;
880 CargoSuffix cargo_suffix[lengthof(i->accepts_cargo)];
881 GetAllCargoSuffixes(CARGOSUFFIX_IN, CST_VIEW, i, i->type, ind, i->accepts_cargo, cargo_suffix);
882 bool stockpiling = HasBit(ind->callback_mask, CBM_IND_PRODUCTION_CARGO_ARRIVAL) || HasBit(ind->callback_mask, CBM_IND_PRODUCTION_256_TICKS);
884 uint left_side = left + WD_FRAMERECT_LEFT * 4; // Indent accepted cargoes.
885 for (byte j = 0; j < lengthof(i->accepts_cargo); j++) {
886 if (i->accepts_cargo[j] == CT_INVALID) continue;
887 has_accept = true;
888 if (first) {
889 DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_REQUIRES);
890 y += FONT_HEIGHT_NORMAL;
891 first = false;
893 SetDParam(0, CargoSpec::Get(i->accepts_cargo[j])->name);
894 SetDParam(1, i->accepts_cargo[j]);
895 SetDParam(2, i->incoming_cargo_waiting[j]);
896 SetDParamStr(3, "");
897 StringID str = STR_NULL;
898 switch (cargo_suffix[j].display) {
899 case CSD_CARGO_AMOUNT_TEXT:
900 SetDParamStr(3, cargo_suffix[j].text);
901 FALLTHROUGH;
902 case CSD_CARGO_AMOUNT:
903 str = stockpiling ? STR_INDUSTRY_VIEW_ACCEPT_CARGO_AMOUNT : STR_INDUSTRY_VIEW_ACCEPT_CARGO;
904 break;
906 case CSD_CARGO_TEXT:
907 SetDParamStr(3, cargo_suffix[j].text);
908 FALLTHROUGH;
909 case CSD_CARGO:
910 str = STR_INDUSTRY_VIEW_ACCEPT_CARGO;
911 break;
913 default:
914 NOT_REACHED();
916 DrawString(left_side, right - WD_FRAMERECT_RIGHT, y, str);
917 y += FONT_HEIGHT_NORMAL;
920 GetAllCargoSuffixes(CARGOSUFFIX_OUT, CST_VIEW, i, i->type, ind, i->produced_cargo, cargo_suffix);
921 first = true;
922 for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
923 if (i->produced_cargo[j] == CT_INVALID) continue;
924 if (first) {
925 if (has_accept) y += WD_PAR_VSEP_WIDE;
926 DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_PRODUCTION_LAST_MONTH_TITLE);
927 y += FONT_HEIGHT_NORMAL;
928 if (this->editable == EA_RATE) this->production_offset_y = y;
929 first = false;
932 SetDParam(0, i->produced_cargo[j]);
933 SetDParam(1, i->last_month_production[j]);
934 SetDParamStr(2, cargo_suffix[j].text);
935 SetDParam(3, ToPercent8(i->last_month_pct_transported[j]));
936 uint x = left + WD_FRAMETEXT_LEFT + (this->editable == EA_RATE ? SETTING_BUTTON_WIDTH + 10 : 0);
937 DrawString(x, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_TRANSPORTED);
938 /* Let's put out those buttons.. */
939 if (this->editable == EA_RATE) {
940 DrawArrowButtons(left + WD_FRAMETEXT_LEFT, y, COLOUR_YELLOW, (this->clicked_line == IL_RATE1 + j) ? this->clicked_button : 0,
941 i->production_rate[j] > 0, i->production_rate[j] < 255);
943 y += FONT_HEIGHT_NORMAL;
946 /* Display production multiplier if editable */
947 if (this->editable == EA_MULTIPLIER) {
948 y += WD_PAR_VSEP_WIDE;
949 this->production_offset_y = y;
950 SetDParam(0, RoundDivSU(i->prod_level * 100, PRODLEVEL_DEFAULT));
951 uint x = left + WD_FRAMETEXT_LEFT + SETTING_BUTTON_WIDTH + 10;
952 DrawString(x, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_PRODUCTION_LEVEL);
953 DrawArrowButtons(left + WD_FRAMETEXT_LEFT, y, COLOUR_YELLOW, (this->clicked_line == IL_MULTIPLIER) ? this->clicked_button : 0,
954 i->prod_level > PRODLEVEL_MINIMUM, i->prod_level < PRODLEVEL_MAXIMUM);
955 y += FONT_HEIGHT_NORMAL;
958 /* Get the extra message for the GUI */
959 if (HasBit(ind->callback_mask, CBM_IND_WINDOW_MORE_TEXT)) {
960 uint16 callback_res = GetIndustryCallback(CBID_INDUSTRY_WINDOW_MORE_TEXT, 0, 0, i, i->type, i->location.tile);
961 if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
962 if (callback_res > 0x400) {
963 ErrorUnknownCallbackResult(ind->grf_prop.grffile->grfid, CBID_INDUSTRY_WINDOW_MORE_TEXT, callback_res);
964 } else {
965 StringID message = GetGRFStringID(ind->grf_prop.grffile->grfid, 0xD000 + callback_res);
966 if (message != STR_NULL && message != STR_UNDEFINED) {
967 y += WD_PAR_VSEP_WIDE;
969 StartTextRefStackUsage(ind->grf_prop.grffile, 6);
970 /* Use all the available space left from where we stand up to the
971 * end of the window. We ALSO enlarge the window if needed, so we
972 * can 'go' wild with the bottom of the window. */
973 y = DrawStringMultiLine(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, UINT16_MAX, message, TC_BLACK);
974 StopTextRefStackUsage();
980 if (!i->text.empty()) {
981 SetDParamStr(0, i->text);
982 y += WD_PAR_VSEP_WIDE;
983 y = DrawStringMultiLine(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, UINT16_MAX, STR_JUST_RAW_STRING, TC_BLACK);
986 return y + WD_FRAMERECT_BOTTOM;
989 void SetStringParameters(int widget) const override
991 if (widget == WID_IV_CAPTION) SetDParam(0, this->window_number);
994 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
996 if (widget == WID_IV_INFO) size->height = this->info_height;
999 void OnClick(Point pt, int widget, int click_count) override
1001 switch (widget) {
1002 case WID_IV_INFO: {
1003 Industry *i = Industry::Get(this->window_number);
1004 InfoLine line = IL_NONE;
1006 switch (this->editable) {
1007 case EA_NONE: break;
1009 case EA_MULTIPLIER:
1010 if (IsInsideBS(pt.y, this->production_offset_y, FONT_HEIGHT_NORMAL)) line = IL_MULTIPLIER;
1011 break;
1013 case EA_RATE:
1014 if (pt.y >= this->production_offset_y) {
1015 int row = (pt.y - this->production_offset_y) / FONT_HEIGHT_NORMAL;
1016 for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
1017 if (i->produced_cargo[j] == CT_INVALID) continue;
1018 row--;
1019 if (row < 0) {
1020 line = (InfoLine)(IL_RATE1 + j);
1021 break;
1025 break;
1027 if (line == IL_NONE) return;
1029 NWidgetBase *nwi = this->GetWidget<NWidgetBase>(widget);
1030 int left = nwi->pos_x + WD_FRAMETEXT_LEFT;
1031 int right = nwi->pos_x + nwi->current_x - 1 - WD_FRAMERECT_RIGHT;
1032 if (IsInsideMM(pt.x, left, left + SETTING_BUTTON_WIDTH)) {
1033 /* Clicked buttons, decrease or increase production */
1034 byte button = (pt.x < left + SETTING_BUTTON_WIDTH / 2) ? 1 : 2;
1035 switch (this->editable) {
1036 case EA_MULTIPLIER:
1037 if (button == 1) {
1038 if (i->prod_level <= PRODLEVEL_MINIMUM) return;
1039 i->prod_level = std::max<uint>(i->prod_level / 2, PRODLEVEL_MINIMUM);
1040 } else {
1041 if (i->prod_level >= PRODLEVEL_MAXIMUM) return;
1042 i->prod_level = std::min<uint>(i->prod_level * 2, PRODLEVEL_MAXIMUM);
1044 break;
1046 case EA_RATE:
1047 if (button == 1) {
1048 if (i->production_rate[line - IL_RATE1] <= 0) return;
1049 i->production_rate[line - IL_RATE1] = std::max(i->production_rate[line - IL_RATE1] / 2, 0);
1050 } else {
1051 if (i->production_rate[line - IL_RATE1] >= 255) return;
1052 /* a zero production industry is unlikely to give anything but zero, so push it a little bit */
1053 int new_prod = i->production_rate[line - IL_RATE1] == 0 ? 1 : i->production_rate[line - IL_RATE1] * 2;
1054 i->production_rate[line - IL_RATE1] = std::min<uint>(new_prod, 255);
1056 break;
1058 default: NOT_REACHED();
1061 UpdateIndustryProduction(i);
1062 this->SetDirty();
1063 this->SetTimeout();
1064 this->clicked_line = line;
1065 this->clicked_button = button;
1066 } else if (IsInsideMM(pt.x, left + SETTING_BUTTON_WIDTH + 10, right)) {
1067 /* clicked the text */
1068 this->editbox_line = line;
1069 switch (this->editable) {
1070 case EA_MULTIPLIER:
1071 SetDParam(0, RoundDivSU(i->prod_level * 100, PRODLEVEL_DEFAULT));
1072 ShowQueryString(STR_JUST_INT, STR_CONFIG_GAME_PRODUCTION_LEVEL, 10, this, CS_ALPHANUMERAL, QSF_NONE);
1073 break;
1075 case EA_RATE:
1076 SetDParam(0, i->production_rate[line - IL_RATE1] * 8);
1077 ShowQueryString(STR_JUST_INT, STR_CONFIG_GAME_PRODUCTION, 10, this, CS_ALPHANUMERAL, QSF_NONE);
1078 break;
1080 default: NOT_REACHED();
1083 break;
1086 case WID_IV_GOTO: {
1087 Industry *i = Industry::Get(this->window_number);
1088 if (_ctrl_pressed) {
1089 ShowExtraViewportWindow(i->location.GetCenterTile());
1090 } else {
1091 ScrollMainWindowToTile(i->location.GetCenterTile());
1093 break;
1096 case WID_IV_DISPLAY: {
1097 Industry *i = Industry::Get(this->window_number);
1098 ShowIndustryCargoesWindow(i->type);
1099 break;
1104 void OnTimeout() override
1106 this->clicked_line = IL_NONE;
1107 this->clicked_button = 0;
1108 this->SetDirty();
1111 void OnResize() override
1113 if (this->viewport != nullptr) {
1114 NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_IV_VIEWPORT);
1115 nvp->UpdateViewportCoordinates(this);
1117 ScrollWindowToTile(Industry::Get(this->window_number)->location.GetCenterTile(), this, true); // Re-center viewport.
1121 void OnQueryTextFinished(char *str) override
1123 if (StrEmpty(str)) return;
1125 Industry *i = Industry::Get(this->window_number);
1126 uint value = atoi(str);
1127 switch (this->editbox_line) {
1128 case IL_NONE: NOT_REACHED();
1130 case IL_MULTIPLIER:
1131 i->prod_level = ClampU(RoundDivSU(value * PRODLEVEL_DEFAULT, 100), PRODLEVEL_MINIMUM, PRODLEVEL_MAXIMUM);
1132 break;
1134 default:
1135 i->production_rate[this->editbox_line - IL_RATE1] = ClampU(RoundDivSU(value, 8), 0, 255);
1136 break;
1138 UpdateIndustryProduction(i);
1139 this->SetDirty();
1143 * Some data on this window has become invalid.
1144 * @param data Information about the changed data.
1145 * @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.
1147 void OnInvalidateData(int data = 0, bool gui_scope = true) override
1149 if (!gui_scope) return;
1150 const Industry *i = Industry::Get(this->window_number);
1151 if (IsProductionAlterable(i)) {
1152 const IndustrySpec *ind = GetIndustrySpec(i->type);
1153 this->editable = ind->UsesOriginalEconomy() ? EA_MULTIPLIER : EA_RATE;
1154 } else {
1155 this->editable = EA_NONE;
1159 bool IsNewGRFInspectable() const override
1161 return ::IsNewGRFInspectable(GSF_INDUSTRIES, this->window_number);
1164 void ShowNewGRFInspectWindow() const override
1166 ::ShowNewGRFInspectWindow(GSF_INDUSTRIES, this->window_number);
1170 static void UpdateIndustryProduction(Industry *i)
1172 const IndustrySpec *indspec = GetIndustrySpec(i->type);
1173 if (indspec->UsesOriginalEconomy()) i->RecomputeProductionMultipliers();
1175 for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
1176 if (i->produced_cargo[j] != CT_INVALID) {
1177 i->last_month_production[j] = 8 * i->production_rate[j];
1182 /** Widget definition of the view industry gui */
1183 static const NWidgetPart _nested_industry_view_widgets[] = {
1184 NWidget(NWID_HORIZONTAL),
1185 NWidget(WWT_CLOSEBOX, COLOUR_CREAM),
1186 NWidget(WWT_CAPTION, COLOUR_CREAM, WID_IV_CAPTION), SetDataTip(STR_INDUSTRY_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1187 NWidget(WWT_PUSHIMGBTN, COLOUR_CREAM, WID_IV_GOTO), SetMinimalSize(12, 14), SetDataTip(SPR_GOTO_LOCATION, STR_INDUSTRY_VIEW_LOCATION_TOOLTIP),
1188 NWidget(WWT_DEBUGBOX, COLOUR_CREAM),
1189 NWidget(WWT_SHADEBOX, COLOUR_CREAM),
1190 NWidget(WWT_DEFSIZEBOX, COLOUR_CREAM),
1191 NWidget(WWT_STICKYBOX, COLOUR_CREAM),
1192 EndContainer(),
1193 NWidget(WWT_PANEL, COLOUR_CREAM),
1194 NWidget(WWT_INSET, COLOUR_CREAM), SetPadding(2, 2, 2, 2),
1195 NWidget(NWID_VIEWPORT, INVALID_COLOUR, WID_IV_VIEWPORT), SetMinimalSize(254, 86), SetFill(1, 0), SetResize(1, 1),
1196 EndContainer(),
1197 EndContainer(),
1198 NWidget(WWT_PANEL, COLOUR_CREAM, WID_IV_INFO), SetMinimalSize(260, 2), SetResize(1, 0),
1199 EndContainer(),
1200 NWidget(NWID_HORIZONTAL),
1201 NWidget(WWT_PUSHTXTBTN, COLOUR_CREAM, WID_IV_DISPLAY), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_INDUSTRY_DISPLAY_CHAIN, STR_INDUSTRY_DISPLAY_CHAIN_TOOLTIP),
1202 NWidget(WWT_RESIZEBOX, COLOUR_CREAM),
1203 EndContainer(),
1206 /** Window definition of the view industry gui */
1207 static WindowDesc _industry_view_desc(
1208 WDP_AUTO, "view_industry", 260, 120,
1209 WC_INDUSTRY_VIEW, WC_NONE,
1211 _nested_industry_view_widgets, lengthof(_nested_industry_view_widgets)
1214 void ShowIndustryViewWindow(int industry)
1216 AllocateWindowDescFront<IndustryViewWindow>(&_industry_view_desc, industry);
1219 /** Widget definition of the industry directory gui */
1220 static const NWidgetPart _nested_industry_directory_widgets[] = {
1221 NWidget(NWID_HORIZONTAL),
1222 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
1223 NWidget(WWT_CAPTION, COLOUR_BROWN), SetDataTip(STR_INDUSTRY_DIRECTORY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1224 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
1225 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
1226 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
1227 EndContainer(),
1228 NWidget(NWID_HORIZONTAL),
1229 NWidget(NWID_VERTICAL),
1230 NWidget(NWID_HORIZONTAL),
1231 NWidget(WWT_TEXTBTN, COLOUR_BROWN, WID_ID_DROPDOWN_ORDER), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
1232 NWidget(WWT_DROPDOWN, COLOUR_BROWN, WID_ID_DROPDOWN_CRITERIA), SetDataTip(STR_JUST_STRING, STR_TOOLTIP_SORT_CRITERIA),
1233 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),
1234 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),
1235 NWidget(WWT_PANEL, COLOUR_BROWN), SetResize(1, 0), EndContainer(),
1236 EndContainer(),
1237 NWidget(WWT_PANEL, COLOUR_BROWN, WID_ID_INDUSTRY_LIST), SetDataTip(0x0, STR_INDUSTRY_DIRECTORY_LIST_CAPTION), SetResize(1, 1), SetScrollbar(WID_ID_SCROLLBAR), EndContainer(),
1238 EndContainer(),
1239 NWidget(NWID_VERTICAL),
1240 NWidget(NWID_VSCROLLBAR, COLOUR_BROWN, WID_ID_SCROLLBAR),
1241 NWidget(WWT_RESIZEBOX, COLOUR_BROWN),
1242 EndContainer(),
1243 EndContainer(),
1246 typedef GUIList<const Industry *, const std::pair<CargoID, CargoID> &> GUIIndustryList;
1248 /** Special cargo filter criteria */
1249 enum CargoFilterSpecialType {
1250 CF_ANY = CT_NO_REFIT, ///< Show all industries (i.e. no filtering)
1251 CF_NONE = CT_INVALID, ///< Show only industries which do not produce/accept cargo
1254 /** Cargo filter functions */
1256 * Check whether an industry accepts and produces a certain cargo pair.
1257 * @param industry The industry whose cargoes will being checked.
1258 * @param cargoes The accepted and produced cargo pair to look for.
1259 * @return bool Whether the given cargoes accepted and produced by the industry.
1261 static bool CDECL CargoFilter(const Industry * const *industry, const std::pair<CargoID, CargoID> &cargoes)
1263 auto accepted_cargo = cargoes.first;
1264 auto produced_cargo = cargoes.second;
1266 bool accepted_cargo_matches;
1268 switch (accepted_cargo) {
1269 case CF_ANY:
1270 accepted_cargo_matches = true;
1271 break;
1273 case CF_NONE:
1274 accepted_cargo_matches = std::all_of(std::begin((*industry)->accepts_cargo), std::end((*industry)->accepts_cargo), [](CargoID cargo) {
1275 return cargo == CT_INVALID;
1277 break;
1279 default:
1280 const auto &ac = (*industry)->accepts_cargo;
1281 accepted_cargo_matches = std::find(std::begin(ac), std::end(ac), accepted_cargo) != std::end(ac);
1282 break;
1285 bool produced_cargo_matches;
1287 switch (produced_cargo) {
1288 case CF_ANY:
1289 produced_cargo_matches = true;
1290 break;
1292 case CF_NONE:
1293 produced_cargo_matches = std::all_of(std::begin((*industry)->produced_cargo), std::end((*industry)->produced_cargo), [](CargoID cargo) {
1294 return cargo == CT_INVALID;
1296 break;
1298 default:
1299 const auto &pc = (*industry)->produced_cargo;
1300 produced_cargo_matches = std::find(std::begin(pc), std::end(pc), produced_cargo) != std::end(pc);
1301 break;
1304 return accepted_cargo_matches && produced_cargo_matches;
1307 static GUIIndustryList::FilterFunction * const _filter_funcs[] = { &CargoFilter };
1311 * The list of industries.
1313 class IndustryDirectoryWindow : public Window {
1314 protected:
1315 /* Runtime saved values */
1316 static Listing last_sorting;
1318 /* Constants for sorting industries */
1319 static const StringID sorter_names[];
1320 static GUIIndustryList::SortFunction * const sorter_funcs[];
1322 GUIIndustryList industries;
1323 Scrollbar *vscroll;
1325 CargoID cargo_filter[NUM_CARGO + 2]; ///< Available cargo filters; CargoID or CF_ANY or CF_NONE
1326 StringID cargo_filter_texts[NUM_CARGO + 3]; ///< Texts for filter_cargo, terminated by INVALID_STRING_ID
1327 byte produced_cargo_filter_criteria; ///< Selected produced cargo filter index
1328 byte accepted_cargo_filter_criteria; ///< Selected accepted cargo filter index
1329 static CargoID produced_cargo_filter;
1331 enum class SorterType : uint8 {
1332 ByName, ///< Sorter type to sort by name
1333 ByType, ///< Sorter type to sort by type
1334 ByProduction, ///< Sorter type to sort by production amount
1335 ByTransported, ///< Sorter type to sort by transported percentage
1339 * Set cargo filter list item index.
1340 * @param index The index of the cargo to be set
1342 void SetProducedCargoFilterIndex(byte index)
1344 if (this->produced_cargo_filter_criteria != index) {
1345 this->produced_cargo_filter_criteria = index;
1346 /* deactivate filter if criteria is 'Show All', activate it otherwise */
1347 bool is_filtering_necessary = this->cargo_filter[this->produced_cargo_filter_criteria] != CF_ANY || this->cargo_filter[this->accepted_cargo_filter_criteria] != CF_ANY;
1349 this->industries.SetFilterState(is_filtering_necessary);
1350 this->industries.SetFilterType(0);
1351 this->industries.ForceRebuild();
1356 * Set cargo filter list item index.
1357 * @param index The index of the cargo to be set
1359 void SetAcceptedCargoFilterIndex(byte index)
1361 if (this->accepted_cargo_filter_criteria != index) {
1362 this->accepted_cargo_filter_criteria = index;
1363 /* deactivate filter if criteria is 'Show All', activate it otherwise */
1364 bool is_filtering_necessary = this->cargo_filter[this->produced_cargo_filter_criteria] != CF_ANY || this->cargo_filter[this->accepted_cargo_filter_criteria] != CF_ANY;
1366 this->industries.SetFilterState(is_filtering_necessary);
1367 this->industries.SetFilterType(0);
1368 this->industries.ForceRebuild();
1373 * Populate the filter list and set the cargo filter criteria.
1375 void SetCargoFilterArray()
1377 byte filter_items = 0;
1379 /* Add item for disabling filtering. */
1380 this->cargo_filter[filter_items] = CF_ANY;
1381 this->cargo_filter_texts[filter_items] = STR_INDUSTRY_DIRECTORY_FILTER_ALL_TYPES;
1382 this->produced_cargo_filter_criteria = filter_items;
1383 this->accepted_cargo_filter_criteria = filter_items;
1384 filter_items++;
1386 /* Add item for industries not producing anything, e.g. power plants */
1387 this->cargo_filter[filter_items] = CF_NONE;
1388 this->cargo_filter_texts[filter_items] = STR_INDUSTRY_DIRECTORY_FILTER_NONE;
1389 filter_items++;
1391 /* Collect available cargo types for filtering. */
1392 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
1393 this->cargo_filter[filter_items] = cs->Index();
1394 this->cargo_filter_texts[filter_items] = cs->name;
1395 filter_items++;
1398 /* Terminate the filter list. */
1399 this->cargo_filter_texts[filter_items] = INVALID_STRING_ID;
1401 this->industries.SetFilterFuncs(_filter_funcs);
1403 bool is_filtering_necessary = this->cargo_filter[this->produced_cargo_filter_criteria] != CF_ANY || this->cargo_filter[this->accepted_cargo_filter_criteria] != CF_ANY;
1405 this->industries.SetFilterState(is_filtering_necessary);
1408 /** (Re)Build industries list */
1409 void BuildSortIndustriesList()
1411 if (this->industries.NeedRebuild()) {
1412 this->industries.clear();
1414 for (const Industry *i : Industry::Iterate()) {
1415 this->industries.push_back(i);
1418 this->industries.shrink_to_fit();
1419 this->industries.RebuildDone();
1422 auto filter = std::make_pair(this->cargo_filter[this->accepted_cargo_filter_criteria],
1423 this->cargo_filter[this->produced_cargo_filter_criteria]);
1425 this->industries.Filter(filter);
1427 IndustryDirectoryWindow::produced_cargo_filter = this->cargo_filter[this->produced_cargo_filter_criteria];
1428 this->industries.Sort();
1430 this->vscroll->SetCount((uint)this->industries.size()); // Update scrollbar as well.
1432 this->SetDirty();
1436 * Returns percents of cargo transported if industry produces this cargo, else -1
1438 * @param i industry to check
1439 * @param id cargo slot
1440 * @return percents of cargo transported, or -1 if industry doesn't use this cargo slot
1442 static inline int GetCargoTransportedPercentsIfValid(const Industry *i, uint id)
1444 assert(id < lengthof(i->produced_cargo));
1446 if (i->produced_cargo[id] == CT_INVALID) return -1;
1447 return ToPercent8(i->last_month_pct_transported[id]);
1451 * Returns value representing industry's transported cargo
1452 * percentage for industry sorting
1454 * @param i industry to check
1455 * @return value used for sorting
1457 static int GetCargoTransportedSortValue(const Industry *i)
1459 CargoID filter = IndustryDirectoryWindow::produced_cargo_filter;
1460 if (filter == CF_NONE) return 0;
1462 int percentage = 0, produced_cargo_count = 0;
1463 for (uint id = 0; id < lengthof(i->produced_cargo); id++) {
1464 if (filter == CF_ANY) {
1465 int transported = GetCargoTransportedPercentsIfValid(i, id);
1466 if (transported != -1) {
1467 produced_cargo_count++;
1468 percentage += transported;
1470 if (produced_cargo_count == 0 && id == lengthof(i->produced_cargo) - 1 && percentage == 0) {
1471 return transported;
1473 } else if (filter == i->produced_cargo[id]) {
1474 return GetCargoTransportedPercentsIfValid(i, id);
1478 if (produced_cargo_count == 0) return percentage;
1479 return percentage / produced_cargo_count;
1482 /** Sort industries by name */
1483 static bool IndustryNameSorter(const Industry * const &a, const Industry * const &b)
1485 int r = strnatcmp(a->GetCachedName(), b->GetCachedName()); // Sort by name (natural sorting).
1486 if (r == 0) return a->index < b->index;
1487 return r < 0;
1490 /** Sort industries by type and name */
1491 static bool IndustryTypeSorter(const Industry * const &a, const Industry * const &b)
1493 int it_a = 0;
1494 while (it_a != NUM_INDUSTRYTYPES && a->type != _sorted_industry_types[it_a]) it_a++;
1495 int it_b = 0;
1496 while (it_b != NUM_INDUSTRYTYPES && b->type != _sorted_industry_types[it_b]) it_b++;
1497 int r = it_a - it_b;
1498 return (r == 0) ? IndustryNameSorter(a, b) : r < 0;
1501 /** Sort industries by production and name */
1502 static bool IndustryProductionSorter(const Industry * const &a, const Industry * const &b)
1504 CargoID filter = IndustryDirectoryWindow::produced_cargo_filter;
1505 if (filter == CF_NONE) return IndustryTypeSorter(a, b);
1507 uint prod_a = 0, prod_b = 0;
1508 for (uint i = 0; i < lengthof(a->produced_cargo); i++) {
1509 if (filter == CF_ANY) {
1510 if (a->produced_cargo[i] != CT_INVALID) prod_a += a->last_month_production[i];
1511 if (b->produced_cargo[i] != CT_INVALID) prod_b += b->last_month_production[i];
1512 } else {
1513 if (a->produced_cargo[i] == filter) prod_a += a->last_month_production[i];
1514 if (b->produced_cargo[i] == filter) prod_b += b->last_month_production[i];
1517 int r = prod_a - prod_b;
1519 return (r == 0) ? IndustryTypeSorter(a, b) : r < 0;
1522 /** Sort industries by transported cargo and name */
1523 static bool IndustryTransportedCargoSorter(const Industry * const &a, const Industry * const &b)
1525 int r = GetCargoTransportedSortValue(a) - GetCargoTransportedSortValue(b);
1526 return (r == 0) ? IndustryNameSorter(a, b) : r < 0;
1530 * Get the StringID to draw and set the appropriate DParams.
1531 * @param i the industry to get the StringID of.
1532 * @return the StringID.
1534 StringID GetIndustryString(const Industry *i) const
1536 const IndustrySpec *indsp = GetIndustrySpec(i->type);
1537 byte p = 0;
1539 /* Industry name */
1540 SetDParam(p++, i->index);
1542 static CargoSuffix cargo_suffix[lengthof(i->produced_cargo)];
1543 GetAllCargoSuffixes(CARGOSUFFIX_OUT, CST_DIR, i, i->type, indsp, i->produced_cargo, cargo_suffix);
1545 /* Get industry productions (CargoID, production, suffix, transported) */
1546 struct CargoInfo {
1547 CargoID cargo_id;
1548 uint16 production;
1549 const char *suffix;
1550 uint transported;
1552 std::vector<CargoInfo> cargos;
1554 for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
1555 if (i->produced_cargo[j] == CT_INVALID) continue;
1556 cargos.push_back({ i->produced_cargo[j], i->last_month_production[j], cargo_suffix[j].text, ToPercent8(i->last_month_pct_transported[j]) });
1559 switch (static_cast<IndustryDirectoryWindow::SorterType>(this->industries.SortType())) {
1560 case IndustryDirectoryWindow::SorterType::ByName:
1561 case IndustryDirectoryWindow::SorterType::ByType:
1562 case IndustryDirectoryWindow::SorterType::ByProduction:
1563 /* Sort by descending production, then descending transported */
1564 std::sort(cargos.begin(), cargos.end(), [](const CargoInfo &a, const CargoInfo &b) {
1565 if (a.production != b.production) return a.production > b.production;
1566 return a.transported > b.transported;
1568 break;
1570 case IndustryDirectoryWindow::SorterType::ByTransported:
1571 /* Sort by descending transported, then descending production */
1572 std::sort(cargos.begin(), cargos.end(), [](const CargoInfo &a, const CargoInfo &b) {
1573 if (a.transported != b.transported) return a.transported > b.transported;
1574 return a.production > b.production;
1576 break;
1579 /* If the produced cargo filter is active then move the filtered cargo to the beginning of the list,
1580 * because this is the one the player interested in, and that way it is not hidden in the 'n' more cargos */
1581 const CargoID cid = this->cargo_filter[this->produced_cargo_filter_criteria];
1582 if (cid != CF_ANY && cid != CF_NONE) {
1583 auto filtered_ci = std::find_if(cargos.begin(), cargos.end(), [cid](const CargoInfo &ci) -> bool {
1584 return ci.cargo_id == cid;
1586 if (filtered_ci != cargos.end()) {
1587 std::rotate(cargos.begin(), filtered_ci, filtered_ci + 1);
1591 /* Display first 3 cargos */
1592 for (size_t j = 0; j < std::min<size_t>(3, cargos.size()); j++) {
1593 CargoInfo ci = cargos[j];
1594 SetDParam(p++, STR_INDUSTRY_DIRECTORY_ITEM_INFO);
1595 SetDParam(p++, ci.cargo_id);
1596 SetDParam(p++, ci.production);
1597 SetDParamStr(p++, ci.suffix);
1598 SetDParam(p++, ci.transported);
1601 /* Undisplayed cargos if any */
1602 SetDParam(p++, cargos.size() - 3);
1604 /* Drawing the right string */
1605 switch (cargos.size()) {
1606 case 0: return STR_INDUSTRY_DIRECTORY_ITEM_NOPROD;
1607 case 1: return STR_INDUSTRY_DIRECTORY_ITEM_PROD1;
1608 case 2: return STR_INDUSTRY_DIRECTORY_ITEM_PROD2;
1609 case 3: return STR_INDUSTRY_DIRECTORY_ITEM_PROD3;
1610 default: return STR_INDUSTRY_DIRECTORY_ITEM_PRODMORE;
1614 public:
1615 IndustryDirectoryWindow(WindowDesc *desc, WindowNumber number) : Window(desc)
1617 this->CreateNestedTree();
1618 this->vscroll = this->GetScrollbar(WID_ID_SCROLLBAR);
1620 this->industries.SetListing(this->last_sorting);
1621 this->industries.SetSortFuncs(IndustryDirectoryWindow::sorter_funcs);
1622 this->industries.ForceRebuild();
1623 this->BuildSortIndustriesList();
1625 this->FinishInitNested(0);
1628 ~IndustryDirectoryWindow()
1630 this->last_sorting = this->industries.GetListing();
1633 void OnInit() override
1635 this->SetCargoFilterArray();
1638 void SetStringParameters(int widget) const override
1640 switch (widget) {
1641 case WID_ID_DROPDOWN_CRITERIA:
1642 SetDParam(0, IndustryDirectoryWindow::sorter_names[this->industries.SortType()]);
1643 break;
1645 case WID_ID_FILTER_BY_ACC_CARGO:
1646 SetDParam(0, this->cargo_filter_texts[this->accepted_cargo_filter_criteria]);
1647 break;
1649 case WID_ID_FILTER_BY_PROD_CARGO:
1650 SetDParam(0, this->cargo_filter_texts[this->produced_cargo_filter_criteria]);
1651 break;
1655 void DrawWidget(const Rect &r, int widget) const override
1657 switch (widget) {
1658 case WID_ID_DROPDOWN_ORDER:
1659 this->DrawSortButtonState(widget, this->industries.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
1660 break;
1662 case WID_ID_INDUSTRY_LIST: {
1663 int n = 0;
1664 int y = r.top + WD_FRAMERECT_TOP;
1665 if (this->industries.size() == 0) {
1666 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_DIRECTORY_NONE);
1667 break;
1669 TextColour tc;
1670 const CargoID acf_cid = this->cargo_filter[this->accepted_cargo_filter_criteria];
1671 for (uint i = this->vscroll->GetPosition(); i < this->industries.size(); i++) {
1672 tc = TC_FROMSTRING;
1673 if (acf_cid != CF_ANY && acf_cid != CF_NONE) {
1674 Industry *ind = const_cast<Industry *>(this->industries[i]);
1675 if (IndustryTemporarilyRefusesCargo(ind, acf_cid)) {
1676 tc = TC_GREY | TC_FORCED;
1679 DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, this->GetIndustryString(this->industries[i]), tc);
1681 y += this->resize.step_height;
1682 if (++n == this->vscroll->GetCapacity()) break; // max number of industries in 1 window
1684 break;
1689 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
1691 switch (widget) {
1692 case WID_ID_DROPDOWN_ORDER: {
1693 Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
1694 d.width += padding.width + Window::SortButtonWidth() * 2; // Doubled since the string is centred and it also looks better.
1695 d.height += padding.height;
1696 *size = maxdim(*size, d);
1697 break;
1700 case WID_ID_DROPDOWN_CRITERIA: {
1701 Dimension d = {0, 0};
1702 for (uint i = 0; IndustryDirectoryWindow::sorter_names[i] != INVALID_STRING_ID; i++) {
1703 d = maxdim(d, GetStringBoundingBox(IndustryDirectoryWindow::sorter_names[i]));
1705 d.width += padding.width;
1706 d.height += padding.height;
1707 *size = maxdim(*size, d);
1708 break;
1711 case WID_ID_INDUSTRY_LIST: {
1712 Dimension d = GetStringBoundingBox(STR_INDUSTRY_DIRECTORY_NONE);
1713 for (uint i = 0; i < this->industries.size(); i++) {
1714 d = maxdim(d, GetStringBoundingBox(this->GetIndustryString(this->industries[i])));
1716 resize->height = d.height;
1717 d.height *= 5;
1718 d.width += padding.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
1719 d.height += padding.height + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
1720 *size = maxdim(*size, d);
1721 break;
1727 void OnClick(Point pt, int widget, int click_count) override
1729 switch (widget) {
1730 case WID_ID_DROPDOWN_ORDER:
1731 this->industries.ToggleSortOrder();
1732 this->SetDirty();
1733 break;
1735 case WID_ID_DROPDOWN_CRITERIA:
1736 ShowDropDownMenu(this, IndustryDirectoryWindow::sorter_names, this->industries.SortType(), WID_ID_DROPDOWN_CRITERIA, 0, 0);
1737 break;
1739 case WID_ID_FILTER_BY_ACC_CARGO: // Cargo filter dropdown
1740 ShowDropDownMenu(this, this->cargo_filter_texts, this->accepted_cargo_filter_criteria, WID_ID_FILTER_BY_ACC_CARGO, 0, 0);
1741 break;
1743 case WID_ID_FILTER_BY_PROD_CARGO: // Cargo filter dropdown
1744 ShowDropDownMenu(this, this->cargo_filter_texts, this->produced_cargo_filter_criteria, WID_ID_FILTER_BY_PROD_CARGO, 0, 0);
1745 break;
1747 case WID_ID_INDUSTRY_LIST: {
1748 uint p = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_ID_INDUSTRY_LIST, WD_FRAMERECT_TOP);
1749 if (p < this->industries.size()) {
1750 if (_ctrl_pressed) {
1751 ShowExtraViewportWindow(this->industries[p]->location.tile);
1752 } else {
1753 ScrollMainWindowToTile(this->industries[p]->location.tile);
1756 break;
1761 void OnDropdownSelect(int widget, int index) override
1763 switch (widget) {
1764 case WID_ID_DROPDOWN_CRITERIA: {
1765 if (this->industries.SortType() != index) {
1766 this->industries.SetSortType(index);
1767 this->BuildSortIndustriesList();
1769 break;
1772 case WID_ID_FILTER_BY_ACC_CARGO: {
1773 this->SetAcceptedCargoFilterIndex(index);
1774 this->BuildSortIndustriesList();
1775 break;
1778 case WID_ID_FILTER_BY_PROD_CARGO: {
1779 this->SetProducedCargoFilterIndex(index);
1780 this->BuildSortIndustriesList();
1781 break;
1786 void OnResize() override
1788 this->vscroll->SetCapacityFromWidget(this, WID_ID_INDUSTRY_LIST);
1791 void OnPaint() override
1793 if (this->industries.NeedRebuild()) this->BuildSortIndustriesList();
1794 this->DrawWidgets();
1797 void OnHundredthTick() override
1799 this->industries.ForceResort();
1800 this->BuildSortIndustriesList();
1804 * Some data on this window has become invalid.
1805 * @param data Information about the changed data.
1806 * @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.
1808 void OnInvalidateData(int data = 0, bool gui_scope = true) override
1810 switch (data) {
1811 case IDIWD_FORCE_REBUILD:
1812 /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
1813 this->industries.ForceRebuild();
1814 break;
1816 case IDIWD_PRODUCTION_CHANGE:
1817 if (this->industries.SortType() == 2) this->industries.ForceResort();
1818 break;
1820 default:
1821 this->industries.ForceResort();
1822 break;
1827 Listing IndustryDirectoryWindow::last_sorting = {false, 0};
1829 /* Available station sorting functions. */
1830 GUIIndustryList::SortFunction * const IndustryDirectoryWindow::sorter_funcs[] = {
1831 &IndustryNameSorter,
1832 &IndustryTypeSorter,
1833 &IndustryProductionSorter,
1834 &IndustryTransportedCargoSorter
1837 /* Names of the sorting functions */
1838 const StringID IndustryDirectoryWindow::sorter_names[] = {
1839 STR_SORT_BY_NAME,
1840 STR_SORT_BY_TYPE,
1841 STR_SORT_BY_PRODUCTION,
1842 STR_SORT_BY_TRANSPORTED,
1843 INVALID_STRING_ID
1846 CargoID IndustryDirectoryWindow::produced_cargo_filter = CF_ANY;
1849 /** Window definition of the industry directory gui */
1850 static WindowDesc _industry_directory_desc(
1851 WDP_AUTO, "list_industries", 428, 190,
1852 WC_INDUSTRY_DIRECTORY, WC_NONE,
1854 _nested_industry_directory_widgets, lengthof(_nested_industry_directory_widgets)
1857 void ShowIndustryDirectory()
1859 AllocateWindowDescFront<IndustryDirectoryWindow>(&_industry_directory_desc, 0);
1862 /** Widgets of the industry cargoes window. */
1863 static const NWidgetPart _nested_industry_cargoes_widgets[] = {
1864 NWidget(NWID_HORIZONTAL),
1865 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
1866 NWidget(WWT_CAPTION, COLOUR_BROWN, WID_IC_CAPTION), SetDataTip(STR_INDUSTRY_CARGOES_INDUSTRY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1867 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
1868 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
1869 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
1870 EndContainer(),
1871 NWidget(NWID_HORIZONTAL),
1872 NWidget(WWT_PANEL, COLOUR_BROWN, WID_IC_PANEL), SetResize(1, 10), SetMinimalSize(200, 90), SetScrollbar(WID_IC_SCROLLBAR), EndContainer(),
1873 NWidget(NWID_VSCROLLBAR, COLOUR_BROWN, WID_IC_SCROLLBAR),
1874 EndContainer(),
1875 NWidget(NWID_HORIZONTAL),
1876 NWidget(WWT_TEXTBTN, COLOUR_BROWN, WID_IC_NOTIFY),
1877 SetDataTip(STR_INDUSTRY_CARGOES_NOTIFY_SMALLMAP, STR_INDUSTRY_CARGOES_NOTIFY_SMALLMAP_TOOLTIP),
1878 NWidget(WWT_PANEL, COLOUR_BROWN), SetFill(1, 0), SetResize(0, 0), EndContainer(),
1879 NWidget(WWT_DROPDOWN, COLOUR_BROWN, WID_IC_IND_DROPDOWN), SetFill(0, 0), SetResize(0, 0),
1880 SetDataTip(STR_INDUSTRY_CARGOES_SELECT_INDUSTRY, STR_INDUSTRY_CARGOES_SELECT_INDUSTRY_TOOLTIP),
1881 NWidget(WWT_DROPDOWN, COLOUR_BROWN, WID_IC_CARGO_DROPDOWN), SetFill(0, 0), SetResize(0, 0),
1882 SetDataTip(STR_INDUSTRY_CARGOES_SELECT_CARGO, STR_INDUSTRY_CARGOES_SELECT_CARGO_TOOLTIP),
1883 NWidget(WWT_RESIZEBOX, COLOUR_BROWN),
1884 EndContainer(),
1887 /** Window description for the industry cargoes window. */
1888 static WindowDesc _industry_cargoes_desc(
1889 WDP_AUTO, "industry_cargoes", 300, 210,
1890 WC_INDUSTRY_CARGOES, WC_NONE,
1892 _nested_industry_cargoes_widgets, lengthof(_nested_industry_cargoes_widgets)
1895 /** Available types of field. */
1896 enum CargoesFieldType {
1897 CFT_EMPTY, ///< Empty field.
1898 CFT_SMALL_EMPTY, ///< Empty small field (for the header).
1899 CFT_INDUSTRY, ///< Display industry.
1900 CFT_CARGO, ///< Display cargo connections.
1901 CFT_CARGO_LABEL, ///< Display cargo labels.
1902 CFT_HEADER, ///< Header text.
1905 static const uint MAX_CARGOES = 16; ///< Maximum number of cargoes carried in a #CFT_CARGO field in #CargoesField.
1907 /** Data about a single field in the #IndustryCargoesWindow panel. */
1908 struct CargoesField {
1909 static const int VERT_INTER_INDUSTRY_SPACE;
1910 static const int BLOB_DISTANCE;
1912 static Dimension legend;
1913 static Dimension cargo_border;
1914 static Dimension cargo_line;
1915 static Dimension cargo_space;
1916 static Dimension cargo_stub;
1918 static const int INDUSTRY_LINE_COLOUR;
1919 static const int CARGO_LINE_COLOUR;
1921 static int small_height, normal_height;
1922 static int cargo_field_width;
1923 static int industry_width;
1924 static uint max_cargoes;
1926 CargoesFieldType type; ///< Type of field.
1927 union {
1928 struct {
1929 IndustryType ind_type; ///< Industry type (#NUM_INDUSTRYTYPES means 'houses').
1930 CargoID other_produced[MAX_CARGOES]; ///< Cargoes produced but not used in this figure.
1931 CargoID other_accepted[MAX_CARGOES]; ///< Cargoes accepted but not used in this figure.
1932 } industry; ///< Industry data (for #CFT_INDUSTRY).
1933 struct {
1934 CargoID vertical_cargoes[MAX_CARGOES]; ///< Cargoes running from top to bottom (cargo ID or #INVALID_CARGO).
1935 byte num_cargoes; ///< Number of cargoes.
1936 CargoID supp_cargoes[MAX_CARGOES]; ///< Cargoes entering from the left (index in #vertical_cargoes, or #INVALID_CARGO).
1937 byte top_end; ///< Stop at the top of the vertical cargoes.
1938 CargoID cust_cargoes[MAX_CARGOES]; ///< Cargoes leaving to the right (index in #vertical_cargoes, or #INVALID_CARGO).
1939 byte bottom_end; ///< Stop at the bottom of the vertical cargoes.
1940 } cargo; ///< Cargo data (for #CFT_CARGO).
1941 struct {
1942 CargoID cargoes[MAX_CARGOES]; ///< Cargoes to display (or #INVALID_CARGO).
1943 bool left_align; ///< Align all cargo texts to the left (else align to the right).
1944 } cargo_label; ///< Label data (for #CFT_CARGO_LABEL).
1945 StringID header; ///< Header text (for #CFT_HEADER).
1946 } u; // Data for each type.
1949 * Make one of the empty fields (#CFT_EMPTY or #CFT_SMALL_EMPTY).
1950 * @param type Type of empty field.
1952 void MakeEmpty(CargoesFieldType type)
1954 this->type = type;
1958 * Make an industry type field.
1959 * @param ind_type Industry type (#NUM_INDUSTRYTYPES means 'houses').
1960 * @note #other_accepted and #other_produced should be filled later.
1962 void MakeIndustry(IndustryType ind_type)
1964 this->type = CFT_INDUSTRY;
1965 this->u.industry.ind_type = ind_type;
1966 MemSetT(this->u.industry.other_accepted, INVALID_CARGO, MAX_CARGOES);
1967 MemSetT(this->u.industry.other_produced, INVALID_CARGO, MAX_CARGOES);
1971 * Connect a cargo from an industry to the #CFT_CARGO column.
1972 * @param cargo Cargo to connect.
1973 * @param producer Cargo is produced (if \c false, cargo is assumed to be accepted).
1974 * @return Horizontal connection index, or \c -1 if not accepted at all.
1976 int ConnectCargo(CargoID cargo, bool producer)
1978 assert(this->type == CFT_CARGO);
1979 if (cargo == INVALID_CARGO) return -1;
1981 /* Find the vertical cargo column carrying the cargo. */
1982 int column = -1;
1983 for (int i = 0; i < this->u.cargo.num_cargoes; i++) {
1984 if (cargo == this->u.cargo.vertical_cargoes[i]) {
1985 column = i;
1986 break;
1989 if (column < 0) return -1;
1991 if (producer) {
1992 assert(this->u.cargo.supp_cargoes[column] == INVALID_CARGO);
1993 this->u.cargo.supp_cargoes[column] = column;
1994 } else {
1995 assert(this->u.cargo.cust_cargoes[column] == INVALID_CARGO);
1996 this->u.cargo.cust_cargoes[column] = column;
1998 return column;
2002 * Does this #CFT_CARGO field have a horizontal connection?
2003 * @return \c true if a horizontal connection exists, \c false otherwise.
2005 bool HasConnection()
2007 assert(this->type == CFT_CARGO);
2009 for (uint i = 0; i < MAX_CARGOES; i++) {
2010 if (this->u.cargo.supp_cargoes[i] != INVALID_CARGO) return true;
2011 if (this->u.cargo.cust_cargoes[i] != INVALID_CARGO) return true;
2013 return false;
2017 * Make a piece of cargo column.
2018 * @param cargoes Array of #CargoID (may contain #INVALID_CARGO).
2019 * @param length Number of cargoes in \a cargoes.
2020 * @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).
2021 * @param top_end This is the first cargo field of this column.
2022 * @param bottom_end This is the last cargo field of this column.
2023 * @note #supp_cargoes and #cust_cargoes should be filled in later.
2025 void MakeCargo(const CargoID *cargoes, uint length, int count = -1, bool top_end = false, bool bottom_end = false)
2027 this->type = CFT_CARGO;
2028 uint i;
2029 uint num = 0;
2030 for (i = 0; i < MAX_CARGOES && i < length; i++) {
2031 if (cargoes[i] != INVALID_CARGO) {
2032 this->u.cargo.vertical_cargoes[num] = cargoes[i];
2033 num++;
2036 this->u.cargo.num_cargoes = (count < 0) ? num : count;
2037 for (; num < MAX_CARGOES; num++) this->u.cargo.vertical_cargoes[num] = INVALID_CARGO;
2038 this->u.cargo.top_end = top_end;
2039 this->u.cargo.bottom_end = bottom_end;
2040 MemSetT(this->u.cargo.supp_cargoes, INVALID_CARGO, MAX_CARGOES);
2041 MemSetT(this->u.cargo.cust_cargoes, INVALID_CARGO, MAX_CARGOES);
2045 * Make a field displaying cargo type names.
2046 * @param cargoes Array of #CargoID (may contain #INVALID_CARGO).
2047 * @param length Number of cargoes in \a cargoes.
2048 * @param left_align ALign texts to the left (else to the right).
2050 void MakeCargoLabel(const CargoID *cargoes, uint length, bool left_align)
2052 this->type = CFT_CARGO_LABEL;
2053 uint i;
2054 for (i = 0; i < MAX_CARGOES && i < length; i++) this->u.cargo_label.cargoes[i] = cargoes[i];
2055 for (; i < MAX_CARGOES; i++) this->u.cargo_label.cargoes[i] = INVALID_CARGO;
2056 this->u.cargo_label.left_align = left_align;
2060 * Make a header above an industry column.
2061 * @param textid Text to display.
2063 void MakeHeader(StringID textid)
2065 this->type = CFT_HEADER;
2066 this->u.header = textid;
2070 * For a #CFT_CARGO, compute the left position of the left-most vertical cargo connection.
2071 * @param xpos Left position of the field.
2072 * @return Left position of the left-most vertical cargo column.
2074 int GetCargoBase(int xpos) const
2076 assert(this->type == CFT_CARGO);
2077 int n = this->u.cargo.num_cargoes;
2079 return xpos + cargo_field_width / 2 - (CargoesField::cargo_line.width * n + CargoesField::cargo_space.width * (n - 1)) / 2;
2083 * Draw the field.
2084 * @param xpos Position of the left edge.
2085 * @param ypos Position of the top edge.
2087 void Draw(int xpos, int ypos) const
2089 switch (this->type) {
2090 case CFT_EMPTY:
2091 case CFT_SMALL_EMPTY:
2092 break;
2094 case CFT_HEADER:
2095 ypos += (small_height - FONT_HEIGHT_NORMAL) / 2;
2096 DrawString(xpos, xpos + industry_width, ypos, this->u.header, TC_WHITE, SA_HOR_CENTER);
2097 break;
2099 case CFT_INDUSTRY: {
2100 int ypos1 = ypos + VERT_INTER_INDUSTRY_SPACE / 2;
2101 int ypos2 = ypos + normal_height - 1 - VERT_INTER_INDUSTRY_SPACE / 2;
2102 int xpos2 = xpos + industry_width - 1;
2103 GfxDrawLine(xpos, ypos1, xpos2, ypos1, INDUSTRY_LINE_COLOUR);
2104 GfxDrawLine(xpos, ypos1, xpos, ypos2, INDUSTRY_LINE_COLOUR);
2105 GfxDrawLine(xpos, ypos2, xpos2, ypos2, INDUSTRY_LINE_COLOUR);
2106 GfxDrawLine(xpos2, ypos1, xpos2, ypos2, INDUSTRY_LINE_COLOUR);
2107 ypos += (normal_height - FONT_HEIGHT_NORMAL) / 2;
2108 if (this->u.industry.ind_type < NUM_INDUSTRYTYPES) {
2109 const IndustrySpec *indsp = GetIndustrySpec(this->u.industry.ind_type);
2110 DrawString(xpos, xpos2, ypos, indsp->name, TC_WHITE, SA_HOR_CENTER);
2112 /* Draw the industry legend. */
2113 int blob_left, blob_right;
2114 if (_current_text_dir == TD_RTL) {
2115 blob_right = xpos2 - BLOB_DISTANCE;
2116 blob_left = blob_right - CargoesField::legend.width;
2117 } else {
2118 blob_left = xpos + BLOB_DISTANCE;
2119 blob_right = blob_left + CargoesField::legend.width;
2121 GfxFillRect(blob_left, ypos2 - BLOB_DISTANCE - CargoesField::legend.height, blob_right, ypos2 - BLOB_DISTANCE, PC_BLACK); // Border
2122 GfxFillRect(blob_left + 1, ypos2 - BLOB_DISTANCE - CargoesField::legend.height + 1, blob_right - 1, ypos2 - BLOB_DISTANCE - 1, indsp->map_colour);
2123 } else {
2124 DrawString(xpos, xpos2, ypos, STR_INDUSTRY_CARGOES_HOUSES, TC_FROMSTRING, SA_HOR_CENTER);
2127 /* Draw the other_produced/other_accepted cargoes. */
2128 const CargoID *other_right, *other_left;
2129 if (_current_text_dir == TD_RTL) {
2130 other_right = this->u.industry.other_accepted;
2131 other_left = this->u.industry.other_produced;
2132 } else {
2133 other_right = this->u.industry.other_produced;
2134 other_left = this->u.industry.other_accepted;
2136 ypos1 += CargoesField::cargo_border.height + (FONT_HEIGHT_NORMAL - CargoesField::cargo_line.height) / 2;
2137 for (uint i = 0; i < CargoesField::max_cargoes; i++) {
2138 if (other_right[i] != INVALID_CARGO) {
2139 const CargoSpec *csp = CargoSpec::Get(other_right[i]);
2140 int xp = xpos + industry_width + CargoesField::cargo_stub.width;
2141 DrawHorConnection(xpos + industry_width, xp - 1, ypos1, csp);
2142 GfxDrawLine(xp, ypos1, xp, ypos1 + CargoesField::cargo_line.height - 1, CARGO_LINE_COLOUR);
2144 if (other_left[i] != INVALID_CARGO) {
2145 const CargoSpec *csp = CargoSpec::Get(other_left[i]);
2146 int xp = xpos - CargoesField::cargo_stub.width;
2147 DrawHorConnection(xp + 1, xpos - 1, ypos1, csp);
2148 GfxDrawLine(xp, ypos1, xp, ypos1 + CargoesField::cargo_line.height - 1, CARGO_LINE_COLOUR);
2150 ypos1 += FONT_HEIGHT_NORMAL + CargoesField::cargo_space.height;
2152 break;
2155 case CFT_CARGO: {
2156 int cargo_base = this->GetCargoBase(xpos);
2157 int top = ypos + (this->u.cargo.top_end ? VERT_INTER_INDUSTRY_SPACE / 2 + 1 : 0);
2158 int bot = ypos - (this->u.cargo.bottom_end ? VERT_INTER_INDUSTRY_SPACE / 2 + 1 : 0) + normal_height - 1;
2159 int colpos = cargo_base;
2160 for (int i = 0; i < this->u.cargo.num_cargoes; i++) {
2161 if (this->u.cargo.top_end) GfxDrawLine(colpos, top - 1, colpos + CargoesField::cargo_line.width - 1, top - 1, CARGO_LINE_COLOUR);
2162 if (this->u.cargo.bottom_end) GfxDrawLine(colpos, bot + 1, colpos + CargoesField::cargo_line.width - 1, bot + 1, CARGO_LINE_COLOUR);
2163 GfxDrawLine(colpos, top, colpos, bot, CARGO_LINE_COLOUR);
2164 colpos++;
2165 const CargoSpec *csp = CargoSpec::Get(this->u.cargo.vertical_cargoes[i]);
2166 GfxFillRect(colpos, top, colpos + CargoesField::cargo_line.width - 2, bot, csp->legend_colour, FILLRECT_OPAQUE);
2167 colpos += CargoesField::cargo_line.width - 2;
2168 GfxDrawLine(colpos, top, colpos, bot, CARGO_LINE_COLOUR);
2169 colpos += 1 + CargoesField::cargo_space.width;
2172 const CargoID *hor_left, *hor_right;
2173 if (_current_text_dir == TD_RTL) {
2174 hor_left = this->u.cargo.cust_cargoes;
2175 hor_right = this->u.cargo.supp_cargoes;
2176 } else {
2177 hor_left = this->u.cargo.supp_cargoes;
2178 hor_right = this->u.cargo.cust_cargoes;
2180 ypos += CargoesField::cargo_border.height + VERT_INTER_INDUSTRY_SPACE / 2 + (FONT_HEIGHT_NORMAL - CargoesField::cargo_line.height) / 2;
2181 for (uint i = 0; i < MAX_CARGOES; i++) {
2182 if (hor_left[i] != INVALID_CARGO) {
2183 int col = hor_left[i];
2184 int dx = 0;
2185 const CargoSpec *csp = CargoSpec::Get(this->u.cargo.vertical_cargoes[col]);
2186 for (; col > 0; col--) {
2187 int lf = cargo_base + col * CargoesField::cargo_line.width + (col - 1) * CargoesField::cargo_space.width;
2188 DrawHorConnection(lf, lf + CargoesField::cargo_space.width - dx, ypos, csp);
2189 dx = 1;
2191 DrawHorConnection(xpos, cargo_base - dx, ypos, csp);
2193 if (hor_right[i] != INVALID_CARGO) {
2194 int col = hor_right[i];
2195 int dx = 0;
2196 const CargoSpec *csp = CargoSpec::Get(this->u.cargo.vertical_cargoes[col]);
2197 for (; col < this->u.cargo.num_cargoes - 1; col++) {
2198 int lf = cargo_base + (col + 1) * CargoesField::cargo_line.width + col * CargoesField::cargo_space.width;
2199 DrawHorConnection(lf + dx - 1, lf + CargoesField::cargo_space.width - 1, ypos, csp);
2200 dx = 1;
2202 DrawHorConnection(cargo_base + col * CargoesField::cargo_space.width + (col + 1) * CargoesField::cargo_line.width - 1 + dx, xpos + CargoesField::cargo_field_width - 1, ypos, csp);
2204 ypos += FONT_HEIGHT_NORMAL + CargoesField::cargo_space.height;
2206 break;
2209 case CFT_CARGO_LABEL:
2210 ypos += CargoesField::cargo_border.height + VERT_INTER_INDUSTRY_SPACE / 2;
2211 for (uint i = 0; i < MAX_CARGOES; i++) {
2212 if (this->u.cargo_label.cargoes[i] != INVALID_CARGO) {
2213 const CargoSpec *csp = CargoSpec::Get(this->u.cargo_label.cargoes[i]);
2214 DrawString(xpos + WD_FRAMERECT_LEFT, xpos + industry_width - 1 - WD_FRAMERECT_RIGHT, ypos, csp->name, TC_WHITE,
2215 (this->u.cargo_label.left_align) ? SA_LEFT : SA_RIGHT);
2217 ypos += FONT_HEIGHT_NORMAL + CargoesField::cargo_space.height;
2219 break;
2221 default:
2222 NOT_REACHED();
2227 * Decide which cargo was clicked at in a #CFT_CARGO field.
2228 * @param left Left industry neighbour if available (else \c nullptr should be supplied).
2229 * @param right Right industry neighbour if available (else \c nullptr should be supplied).
2230 * @param pt Click position in the cargo field.
2231 * @return Cargo clicked at, or #INVALID_CARGO if none.
2233 CargoID CargoClickedAt(const CargoesField *left, const CargoesField *right, Point pt) const
2235 assert(this->type == CFT_CARGO);
2237 /* Vertical matching. */
2238 int cpos = this->GetCargoBase(0);
2239 uint col;
2240 for (col = 0; col < this->u.cargo.num_cargoes; col++) {
2241 if (pt.x < cpos) break;
2242 if (pt.x < cpos + (int)CargoesField::cargo_line.width) return this->u.cargo.vertical_cargoes[col];
2243 cpos += CargoesField::cargo_line.width + CargoesField::cargo_space.width;
2245 /* col = 0 -> left of first col, 1 -> left of 2nd col, ... this->u.cargo.num_cargoes right of last-col. */
2247 int vpos = VERT_INTER_INDUSTRY_SPACE / 2 + CargoesField::cargo_border.width;
2248 uint row;
2249 for (row = 0; row < MAX_CARGOES; row++) {
2250 if (pt.y < vpos) return INVALID_CARGO;
2251 if (pt.y < vpos + FONT_HEIGHT_NORMAL) break;
2252 vpos += FONT_HEIGHT_NORMAL + CargoesField::cargo_space.width;
2254 if (row == MAX_CARGOES) return INVALID_CARGO;
2256 /* row = 0 -> at first horizontal row, row = 1 -> second horizontal row, 2 = 3rd horizontal row. */
2257 if (col == 0) {
2258 if (this->u.cargo.supp_cargoes[row] != INVALID_CARGO) return this->u.cargo.vertical_cargoes[this->u.cargo.supp_cargoes[row]];
2259 if (left != nullptr) {
2260 if (left->type == CFT_INDUSTRY) return left->u.industry.other_produced[row];
2261 if (left->type == CFT_CARGO_LABEL && !left->u.cargo_label.left_align) return left->u.cargo_label.cargoes[row];
2263 return INVALID_CARGO;
2265 if (col == this->u.cargo.num_cargoes) {
2266 if (this->u.cargo.cust_cargoes[row] != INVALID_CARGO) return this->u.cargo.vertical_cargoes[this->u.cargo.cust_cargoes[row]];
2267 if (right != nullptr) {
2268 if (right->type == CFT_INDUSTRY) return right->u.industry.other_accepted[row];
2269 if (right->type == CFT_CARGO_LABEL && right->u.cargo_label.left_align) return right->u.cargo_label.cargoes[row];
2271 return INVALID_CARGO;
2273 if (row >= col) {
2274 /* Clicked somewhere in-between vertical cargo connection.
2275 * Since the horizontal connection is made in the same order as the vertical list, the above condition
2276 * ensures we are left-below the main diagonal, thus at the supplying side.
2278 return (this->u.cargo.supp_cargoes[row] != INVALID_CARGO) ? this->u.cargo.vertical_cargoes[this->u.cargo.supp_cargoes[row]] : INVALID_CARGO;
2279 } else {
2280 /* Clicked at a customer connection. */
2281 return (this->u.cargo.cust_cargoes[row] != INVALID_CARGO) ? this->u.cargo.vertical_cargoes[this->u.cargo.cust_cargoes[row]] : INVALID_CARGO;
2286 * Decide what cargo the user clicked in the cargo label field.
2287 * @param pt Click position in the cargo label field.
2288 * @return Cargo clicked at, or #INVALID_CARGO if none.
2290 CargoID CargoLabelClickedAt(Point pt) const
2292 assert(this->type == CFT_CARGO_LABEL);
2294 int vpos = VERT_INTER_INDUSTRY_SPACE / 2 + CargoesField::cargo_border.height;
2295 uint row;
2296 for (row = 0; row < MAX_CARGOES; row++) {
2297 if (pt.y < vpos) return INVALID_CARGO;
2298 if (pt.y < vpos + FONT_HEIGHT_NORMAL) break;
2299 vpos += FONT_HEIGHT_NORMAL + CargoesField::cargo_space.height;
2301 if (row == MAX_CARGOES) return INVALID_CARGO;
2302 return this->u.cargo_label.cargoes[row];
2305 private:
2307 * Draw a horizontal cargo connection.
2308 * @param left Left-most coordinate to draw.
2309 * @param right Right-most coordinate to draw.
2310 * @param top Top coordinate of the cargo connection.
2311 * @param csp Cargo to draw.
2313 static void DrawHorConnection(int left, int right, int top, const CargoSpec *csp)
2315 GfxDrawLine(left, top, right, top, CARGO_LINE_COLOUR);
2316 GfxFillRect(left, top + 1, right, top + CargoesField::cargo_line.height - 2, csp->legend_colour, FILLRECT_OPAQUE);
2317 GfxDrawLine(left, top + CargoesField::cargo_line.height - 1, right, top + CargoesField::cargo_line.height - 1, CARGO_LINE_COLOUR);
2321 static_assert(MAX_CARGOES >= cpp_lengthof(IndustrySpec, produced_cargo));
2322 static_assert(MAX_CARGOES >= cpp_lengthof(IndustrySpec, accepts_cargo));
2324 Dimension CargoesField::legend; ///< Dimension of the legend blob.
2325 Dimension CargoesField::cargo_border; ///< Dimensions of border between cargo lines and industry boxes.
2326 Dimension CargoesField::cargo_line; ///< Dimensions of cargo lines.
2327 Dimension CargoesField::cargo_space; ///< Dimensions of space between cargo lines.
2328 Dimension CargoesField::cargo_stub; ///< Dimensions of cargo stub (unconnected cargo line.)
2330 int CargoesField::small_height; ///< Height of the header row.
2331 int CargoesField::normal_height; ///< Height of the non-header rows.
2332 int CargoesField::industry_width; ///< Width of an industry field.
2333 int CargoesField::cargo_field_width; ///< Width of a cargo field.
2334 uint CargoesField::max_cargoes; ///< Largest number of cargoes actually on any industry.
2335 const int CargoesField::VERT_INTER_INDUSTRY_SPACE = 6; ///< Amount of space between two industries in a column.
2337 const int CargoesField::BLOB_DISTANCE = 5; ///< Distance of the industry legend colour from the edge of the industry box.
2339 const int CargoesField::INDUSTRY_LINE_COLOUR = PC_YELLOW; ///< Line colour of the industry type box.
2340 const int CargoesField::CARGO_LINE_COLOUR = PC_YELLOW; ///< Line colour around the cargo.
2342 /** A single row of #CargoesField. */
2343 struct CargoesRow {
2344 CargoesField columns[5]; ///< One row of fields.
2347 * Connect industry production cargoes to the cargo column after it.
2348 * @param column Column of the industry.
2350 void ConnectIndustryProduced(int column)
2352 CargoesField *ind_fld = this->columns + column;
2353 CargoesField *cargo_fld = this->columns + column + 1;
2354 assert(ind_fld->type == CFT_INDUSTRY && cargo_fld->type == CFT_CARGO);
2356 MemSetT(ind_fld->u.industry.other_produced, INVALID_CARGO, MAX_CARGOES);
2358 if (ind_fld->u.industry.ind_type < NUM_INDUSTRYTYPES) {
2359 CargoID others[MAX_CARGOES]; // Produced cargoes not carried in the cargo column.
2360 int other_count = 0;
2362 const IndustrySpec *indsp = GetIndustrySpec(ind_fld->u.industry.ind_type);
2363 assert(CargoesField::max_cargoes <= lengthof(indsp->produced_cargo));
2364 for (uint i = 0; i < CargoesField::max_cargoes; i++) {
2365 int col = cargo_fld->ConnectCargo(indsp->produced_cargo[i], true);
2366 if (col < 0) others[other_count++] = indsp->produced_cargo[i];
2369 /* Allocate other cargoes in the empty holes of the horizontal cargo connections. */
2370 for (uint i = 0; i < CargoesField::max_cargoes && other_count > 0; i++) {
2371 if (cargo_fld->u.cargo.supp_cargoes[i] == INVALID_CARGO) ind_fld->u.industry.other_produced[i] = others[--other_count];
2373 } else {
2374 /* Houses only display what is demanded. */
2375 for (uint i = 0; i < cargo_fld->u.cargo.num_cargoes; i++) {
2376 CargoID cid = cargo_fld->u.cargo.vertical_cargoes[i];
2377 if (cid == CT_PASSENGERS || cid == CT_MAIL) cargo_fld->ConnectCargo(cid, true);
2383 * Construct a #CFT_CARGO_LABEL field.
2384 * @param column Column to create the new field.
2385 * @param accepting Display accepted cargo (if \c false, display produced cargo).
2387 void MakeCargoLabel(int column, bool accepting)
2389 CargoID cargoes[MAX_CARGOES];
2390 MemSetT(cargoes, INVALID_CARGO, lengthof(cargoes));
2392 CargoesField *label_fld = this->columns + column;
2393 CargoesField *cargo_fld = this->columns + (accepting ? column - 1 : column + 1);
2395 assert(cargo_fld->type == CFT_CARGO && label_fld->type == CFT_EMPTY);
2396 for (uint i = 0; i < cargo_fld->u.cargo.num_cargoes; i++) {
2397 int col = cargo_fld->ConnectCargo(cargo_fld->u.cargo.vertical_cargoes[i], !accepting);
2398 if (col >= 0) cargoes[col] = cargo_fld->u.cargo.vertical_cargoes[i];
2400 label_fld->MakeCargoLabel(cargoes, lengthof(cargoes), accepting);
2405 * Connect industry accepted cargoes to the cargo column before it.
2406 * @param column Column of the industry.
2408 void ConnectIndustryAccepted(int column)
2410 CargoesField *ind_fld = this->columns + column;
2411 CargoesField *cargo_fld = this->columns + column - 1;
2412 assert(ind_fld->type == CFT_INDUSTRY && cargo_fld->type == CFT_CARGO);
2414 MemSetT(ind_fld->u.industry.other_accepted, INVALID_CARGO, MAX_CARGOES);
2416 if (ind_fld->u.industry.ind_type < NUM_INDUSTRYTYPES) {
2417 CargoID others[MAX_CARGOES]; // Accepted cargoes not carried in the cargo column.
2418 int other_count = 0;
2420 const IndustrySpec *indsp = GetIndustrySpec(ind_fld->u.industry.ind_type);
2421 assert(CargoesField::max_cargoes <= lengthof(indsp->accepts_cargo));
2422 for (uint i = 0; i < CargoesField::max_cargoes; i++) {
2423 int col = cargo_fld->ConnectCargo(indsp->accepts_cargo[i], false);
2424 if (col < 0) others[other_count++] = indsp->accepts_cargo[i];
2427 /* Allocate other cargoes in the empty holes of the horizontal cargo connections. */
2428 for (uint i = 0; i < CargoesField::max_cargoes && other_count > 0; i++) {
2429 if (cargo_fld->u.cargo.cust_cargoes[i] == INVALID_CARGO) ind_fld->u.industry.other_accepted[i] = others[--other_count];
2431 } else {
2432 /* Houses only display what is demanded. */
2433 for (uint i = 0; i < cargo_fld->u.cargo.num_cargoes; i++) {
2434 for (uint h = 0; h < NUM_HOUSES; h++) {
2435 HouseSpec *hs = HouseSpec::Get(h);
2436 if (!hs->enabled) continue;
2438 for (uint j = 0; j < lengthof(hs->accepts_cargo); j++) {
2439 if (hs->cargo_acceptance[j] > 0 && cargo_fld->u.cargo.vertical_cargoes[i] == hs->accepts_cargo[j]) {
2440 cargo_fld->ConnectCargo(cargo_fld->u.cargo.vertical_cargoes[i], false);
2441 goto next_cargo;
2445 next_cargo: ;
2453 * Window displaying the cargo connections around an industry (or cargo).
2455 * The main display is constructed from 'fields', rectangles that contain an industry, piece of the cargo connection, cargo labels, or headers.
2456 * For a nice display, the following should be kept in mind:
2457 * - A #CFT_HEADER is always at the top of an column of #CFT_INDUSTRY fields.
2458 * - A #CFT_CARGO_LABEL field is also always put in a column of #CFT_INDUSTRY fields.
2459 * - The top row contains #CFT_HEADER and #CFT_SMALL_EMPTY fields.
2460 * - Cargo connections have a column of their own (#CFT_CARGO fields).
2461 * - 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.
2462 * The information however is part of the industry.
2464 * This results in the following invariants:
2465 * - Width of a #CFT_INDUSTRY column is large enough to hold all industry type labels, all cargo labels, and all header texts.
2466 * - Height of a #CFT_INDUSTRY is large enough to hold a header line, or a industry type line, \c N cargo labels
2467 * (where \c N is the maximum number of cargoes connected between industries), \c N connections of cargo types, and space
2468 * between two industry types (1/2 above it, and 1/2 underneath it).
2469 * - Width of a cargo field (#CFT_CARGO) is large enough to hold \c N vertical columns (one for each type of cargo).
2470 * Also, space is needed between an industry and the leftmost/rightmost column to draw the non-carried cargoes.
2471 * - Height of a #CFT_CARGO field is equally high as the height of the #CFT_INDUSTRY.
2472 * - A field at the top (#CFT_HEADER or #CFT_SMALL_EMPTY) match the width of the fields below them (#CFT_INDUSTRY respectively
2473 * #CFT_CARGO), the height should be sufficient to display the header text.
2475 * When displaying the cargoes around an industry type, five columns are needed (supplying industries, accepted cargoes, the industry,
2476 * produced cargoes, customer industries). Displaying the industries around a cargo needs three columns (supplying industries, the cargo,
2477 * 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.
2479 struct IndustryCargoesWindow : public Window {
2480 static const int HOR_TEXT_PADDING, VERT_TEXT_PADDING;
2482 typedef std::vector<CargoesRow> Fields;
2484 Fields fields; ///< Fields to display in the #WID_IC_PANEL.
2485 uint ind_cargo; ///< If less than #NUM_INDUSTRYTYPES, an industry type, else a cargo id + NUM_INDUSTRYTYPES.
2486 Dimension cargo_textsize; ///< Size to hold any cargo text, as well as STR_INDUSTRY_CARGOES_SELECT_CARGO.
2487 Dimension ind_textsize; ///< Size to hold any industry type text, as well as STR_INDUSTRY_CARGOES_SELECT_INDUSTRY.
2488 Scrollbar *vscroll;
2490 IndustryCargoesWindow(int id) : Window(&_industry_cargoes_desc)
2492 this->OnInit();
2493 this->CreateNestedTree();
2494 this->vscroll = this->GetScrollbar(WID_IC_SCROLLBAR);
2495 this->FinishInitNested(0);
2496 this->OnInvalidateData(id);
2499 void OnInit() override
2501 /* Initialize static CargoesField size variables. */
2502 Dimension d = GetStringBoundingBox(STR_INDUSTRY_CARGOES_PRODUCERS);
2503 d = maxdim(d, GetStringBoundingBox(STR_INDUSTRY_CARGOES_CUSTOMERS));
2504 d.width += WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT;
2505 d.height += WD_FRAMETEXT_TOP + WD_FRAMETEXT_BOTTOM;
2506 CargoesField::small_height = d.height;
2508 /* Size of the legend blob -- slightly larger than the smallmap legend blob. */
2509 CargoesField::legend.height = FONT_HEIGHT_SMALL;
2510 CargoesField::legend.width = CargoesField::legend.height * 8 / 5;
2512 /* Size of cargo lines. */
2513 CargoesField::cargo_line.width = FONT_HEIGHT_NORMAL;
2514 CargoesField::cargo_line.height = CargoesField::cargo_line.width;
2516 /* Size of border between cargo lines and industry boxes. */
2517 CargoesField::cargo_border.width = CargoesField::cargo_line.width * 3 / 2;
2518 CargoesField::cargo_border.height = CargoesField::cargo_line.width / 2;
2520 /* Size of space between cargo lines. */
2521 CargoesField::cargo_space.width = CargoesField::cargo_line.width / 2;
2522 CargoesField::cargo_space.height = CargoesField::cargo_line.height / 2;
2524 /* Size of cargo stub (unconnected cargo line.) */
2525 CargoesField::cargo_stub.width = CargoesField::cargo_line.width / 2;
2526 CargoesField::cargo_stub.height = CargoesField::cargo_line.height; /* Unused */
2528 /* Decide about the size of the box holding the text of an industry type. */
2529 this->ind_textsize.width = 0;
2530 this->ind_textsize.height = 0;
2531 CargoesField::max_cargoes = 0;
2532 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2533 const IndustrySpec *indsp = GetIndustrySpec(it);
2534 if (!indsp->enabled) continue;
2535 this->ind_textsize = maxdim(this->ind_textsize, GetStringBoundingBox(indsp->name));
2536 CargoesField::max_cargoes = std::max<uint>(CargoesField::max_cargoes, std::count_if(indsp->accepts_cargo, endof(indsp->accepts_cargo), IsCargoIDValid));
2537 CargoesField::max_cargoes = std::max<uint>(CargoesField::max_cargoes, std::count_if(indsp->produced_cargo, endof(indsp->produced_cargo), IsCargoIDValid));
2539 d.width = std::max(d.width, this->ind_textsize.width);
2540 d.height = this->ind_textsize.height;
2541 this->ind_textsize = maxdim(this->ind_textsize, GetStringBoundingBox(STR_INDUSTRY_CARGOES_SELECT_INDUSTRY));
2543 /* Compute max size of the cargo texts. */
2544 this->cargo_textsize.width = 0;
2545 this->cargo_textsize.height = 0;
2546 for (uint i = 0; i < NUM_CARGO; i++) {
2547 const CargoSpec *csp = CargoSpec::Get(i);
2548 if (!csp->IsValid()) continue;
2549 this->cargo_textsize = maxdim(this->cargo_textsize, GetStringBoundingBox(csp->name));
2551 d = maxdim(d, this->cargo_textsize); // Box must also be wide enough to hold any cargo label.
2552 this->cargo_textsize = maxdim(this->cargo_textsize, GetStringBoundingBox(STR_INDUSTRY_CARGOES_SELECT_CARGO));
2554 d.width += 2 * HOR_TEXT_PADDING;
2555 /* Ensure the height is enough for the industry type text, for the horizontal connections, and for the cargo labels. */
2556 uint min_ind_height = CargoesField::cargo_border.height * 2 + CargoesField::max_cargoes * FONT_HEIGHT_NORMAL + (CargoesField::max_cargoes - 1) * CargoesField::cargo_space.height;
2557 d.height = std::max(d.height + 2 * VERT_TEXT_PADDING, min_ind_height);
2559 CargoesField::industry_width = d.width;
2560 CargoesField::normal_height = d.height + CargoesField::VERT_INTER_INDUSTRY_SPACE;
2562 /* Width of a #CFT_CARGO field. */
2563 CargoesField::cargo_field_width = CargoesField::cargo_border.width * 2 + CargoesField::cargo_line.width * CargoesField::max_cargoes + CargoesField::cargo_space.width * (CargoesField::max_cargoes - 1);
2566 void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
2568 switch (widget) {
2569 case WID_IC_PANEL:
2570 resize->height = CargoesField::normal_height;
2571 size->width = WD_FRAMETEXT_LEFT + CargoesField::industry_width * 3 + CargoesField::cargo_field_width * 2 + WD_FRAMETEXT_RIGHT;
2572 size->height = WD_FRAMETEXT_TOP + CargoesField::small_height + 2 * resize->height + WD_FRAMETEXT_BOTTOM;
2573 break;
2575 case WID_IC_IND_DROPDOWN:
2576 size->width = std::max(size->width, this->ind_textsize.width + padding.width);
2577 break;
2579 case WID_IC_CARGO_DROPDOWN:
2580 size->width = std::max(size->width, this->cargo_textsize.width + padding.width);
2581 break;
2586 CargoesFieldType type; ///< Type of field.
2587 void SetStringParameters (int widget) const override
2589 if (widget != WID_IC_CAPTION) return;
2591 if (this->ind_cargo < NUM_INDUSTRYTYPES) {
2592 const IndustrySpec *indsp = GetIndustrySpec(this->ind_cargo);
2593 SetDParam(0, indsp->name);
2594 } else {
2595 const CargoSpec *csp = CargoSpec::Get(this->ind_cargo - NUM_INDUSTRYTYPES);
2596 SetDParam(0, csp->name);
2601 * Do the two sets of cargoes have a valid cargo in common?
2602 * @param cargoes1 Base address of the first cargo array.
2603 * @param length1 Number of cargoes in the first cargo array.
2604 * @param cargoes2 Base address of the second cargo array.
2605 * @param length2 Number of cargoes in the second cargo array.
2606 * @return Arrays have at least one valid cargo in common.
2608 static bool HasCommonValidCargo(const CargoID *cargoes1, uint length1, const CargoID *cargoes2, uint length2)
2610 while (length1 > 0) {
2611 if (*cargoes1 != INVALID_CARGO) {
2612 for (uint i = 0; i < length2; i++) if (*cargoes1 == cargoes2[i]) return true;
2614 cargoes1++;
2615 length1--;
2617 return false;
2621 * Can houses be used to supply one of the cargoes?
2622 * @param cargoes Base address of the cargo array.
2623 * @param length Number of cargoes in the array.
2624 * @return Houses can supply at least one of the cargoes.
2626 static bool HousesCanSupply(const CargoID *cargoes, uint length)
2628 for (uint i = 0; i < length; i++) {
2629 if (cargoes[i] == INVALID_CARGO) continue;
2630 if (cargoes[i] == CT_PASSENGERS || cargoes[i] == CT_MAIL) return true;
2632 return false;
2636 * Can houses be used as customers of the produced cargoes?
2637 * @param cargoes Base address of the cargo array.
2638 * @param length Number of cargoes in the array.
2639 * @return Houses can accept at least one of the cargoes.
2641 static bool HousesCanAccept(const CargoID *cargoes, uint length)
2643 HouseZones climate_mask;
2644 switch (_settings_game.game_creation.landscape) {
2645 case LT_TEMPERATE: climate_mask = HZ_TEMP; break;
2646 case LT_ARCTIC: climate_mask = HZ_SUBARTC_ABOVE | HZ_SUBARTC_BELOW; break;
2647 case LT_TROPIC: climate_mask = HZ_SUBTROPIC; break;
2648 case LT_TOYLAND: climate_mask = HZ_TOYLND; break;
2649 default: NOT_REACHED();
2651 for (uint i = 0; i < length; i++) {
2652 if (cargoes[i] == INVALID_CARGO) continue;
2654 for (uint h = 0; h < NUM_HOUSES; h++) {
2655 HouseSpec *hs = HouseSpec::Get(h);
2656 if (!hs->enabled || !(hs->building_availability & climate_mask)) continue;
2658 for (uint j = 0; j < lengthof(hs->accepts_cargo); j++) {
2659 if (hs->cargo_acceptance[j] > 0 && cargoes[i] == hs->accepts_cargo[j]) return true;
2663 return false;
2667 * Count how many industries have accepted cargoes in common with one of the supplied set.
2668 * @param cargoes Cargoes to search.
2669 * @param length Number of cargoes in \a cargoes.
2670 * @return Number of industries that have an accepted cargo in common with the supplied set.
2672 static int CountMatchingAcceptingIndustries(const CargoID *cargoes, uint length)
2674 int count = 0;
2675 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2676 const IndustrySpec *indsp = GetIndustrySpec(it);
2677 if (!indsp->enabled) continue;
2679 if (HasCommonValidCargo(cargoes, length, indsp->accepts_cargo, lengthof(indsp->accepts_cargo))) count++;
2681 return count;
2685 * Count how many industries have produced cargoes in common with one of the supplied set.
2686 * @param cargoes Cargoes to search.
2687 * @param length Number of cargoes in \a cargoes.
2688 * @return Number of industries that have a produced cargo in common with the supplied set.
2690 static int CountMatchingProducingIndustries(const CargoID *cargoes, uint length)
2692 int count = 0;
2693 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2694 const IndustrySpec *indsp = GetIndustrySpec(it);
2695 if (!indsp->enabled) continue;
2697 if (HasCommonValidCargo(cargoes, length, indsp->produced_cargo, lengthof(indsp->produced_cargo))) count++;
2699 return count;
2703 * Shorten the cargo column to just the part between industries.
2704 * @param column Column number of the cargo column.
2705 * @param top Current top row.
2706 * @param bottom Current bottom row.
2708 void ShortenCargoColumn(int column, int top, int bottom)
2710 while (top < bottom && !this->fields[top].columns[column].HasConnection()) {
2711 this->fields[top].columns[column].MakeEmpty(CFT_EMPTY);
2712 top++;
2714 this->fields[top].columns[column].u.cargo.top_end = true;
2716 while (bottom > top && !this->fields[bottom].columns[column].HasConnection()) {
2717 this->fields[bottom].columns[column].MakeEmpty(CFT_EMPTY);
2718 bottom--;
2720 this->fields[bottom].columns[column].u.cargo.bottom_end = true;
2724 * Place an industry in the fields.
2725 * @param row Row of the new industry.
2726 * @param col Column of the new industry.
2727 * @param it Industry to place.
2729 void PlaceIndustry(int row, int col, IndustryType it)
2731 assert(this->fields[row].columns[col].type == CFT_EMPTY);
2732 this->fields[row].columns[col].MakeIndustry(it);
2733 if (col == 0) {
2734 this->fields[row].ConnectIndustryProduced(col);
2735 } else {
2736 this->fields[row].ConnectIndustryAccepted(col);
2741 * Notify smallmap that new displayed industries have been selected (in #_displayed_industries).
2743 void NotifySmallmap()
2745 if (!this->IsWidgetLowered(WID_IC_NOTIFY)) return;
2747 /* Only notify the smallmap window if it exists. In particular, do not
2748 * bring it to the front to prevent messing up any nice layout of the user. */
2749 InvalidateWindowClassesData(WC_SMALLMAP, 0);
2753 * Compute what and where to display for industry type \a it.
2754 * @param displayed_it Industry type to display.
2756 void ComputeIndustryDisplay(IndustryType displayed_it)
2758 this->GetWidget<NWidgetCore>(WID_IC_CAPTION)->widget_data = STR_INDUSTRY_CARGOES_INDUSTRY_CAPTION;
2759 this->ind_cargo = displayed_it;
2760 _displayed_industries.reset();
2761 _displayed_industries.set(displayed_it);
2763 this->fields.clear();
2764 CargoesRow &row = this->fields.emplace_back();
2765 row.columns[0].MakeHeader(STR_INDUSTRY_CARGOES_PRODUCERS);
2766 row.columns[1].MakeEmpty(CFT_SMALL_EMPTY);
2767 row.columns[2].MakeEmpty(CFT_SMALL_EMPTY);
2768 row.columns[3].MakeEmpty(CFT_SMALL_EMPTY);
2769 row.columns[4].MakeHeader(STR_INDUSTRY_CARGOES_CUSTOMERS);
2771 const IndustrySpec *central_sp = GetIndustrySpec(displayed_it);
2772 bool houses_supply = HousesCanSupply(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo));
2773 bool houses_accept = HousesCanAccept(central_sp->produced_cargo, lengthof(central_sp->produced_cargo));
2774 /* Make a field consisting of two cargo columns. */
2775 int num_supp = CountMatchingProducingIndustries(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo)) + houses_supply;
2776 int num_cust = CountMatchingAcceptingIndustries(central_sp->produced_cargo, lengthof(central_sp->produced_cargo)) + houses_accept;
2777 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.
2778 for (int i = 0; i < num_indrows; i++) {
2779 CargoesRow &row = this->fields.emplace_back();
2780 row.columns[0].MakeEmpty(CFT_EMPTY);
2781 row.columns[1].MakeCargo(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo));
2782 row.columns[2].MakeEmpty(CFT_EMPTY);
2783 row.columns[3].MakeCargo(central_sp->produced_cargo, lengthof(central_sp->produced_cargo));
2784 row.columns[4].MakeEmpty(CFT_EMPTY);
2786 /* Add central industry. */
2787 int central_row = 1 + num_indrows / 2;
2788 this->fields[central_row].columns[2].MakeIndustry(displayed_it);
2789 this->fields[central_row].ConnectIndustryProduced(2);
2790 this->fields[central_row].ConnectIndustryAccepted(2);
2792 /* Add cargo labels. */
2793 this->fields[central_row - 1].MakeCargoLabel(2, true);
2794 this->fields[central_row + 1].MakeCargoLabel(2, false);
2796 /* Add suppliers and customers of the 'it' industry. */
2797 int supp_count = 0;
2798 int cust_count = 0;
2799 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2800 const IndustrySpec *indsp = GetIndustrySpec(it);
2801 if (!indsp->enabled) continue;
2803 if (HasCommonValidCargo(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo), indsp->produced_cargo, lengthof(indsp->produced_cargo))) {
2804 this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, it);
2805 _displayed_industries.set(it);
2806 supp_count++;
2808 if (HasCommonValidCargo(central_sp->produced_cargo, lengthof(central_sp->produced_cargo), indsp->accepts_cargo, lengthof(indsp->accepts_cargo))) {
2809 this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 4, it);
2810 _displayed_industries.set(it);
2811 cust_count++;
2814 if (houses_supply) {
2815 this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, NUM_INDUSTRYTYPES);
2816 supp_count++;
2818 if (houses_accept) {
2819 this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 4, NUM_INDUSTRYTYPES);
2820 cust_count++;
2823 this->ShortenCargoColumn(1, 1, num_indrows);
2824 this->ShortenCargoColumn(3, 1, num_indrows);
2825 this->vscroll->SetCount(num_indrows);
2826 this->SetDirty();
2827 this->NotifySmallmap();
2831 * Compute what and where to display for cargo id \a cid.
2832 * @param cid Cargo id to display.
2834 void ComputeCargoDisplay(CargoID cid)
2836 this->GetWidget<NWidgetCore>(WID_IC_CAPTION)->widget_data = STR_INDUSTRY_CARGOES_CARGO_CAPTION;
2837 this->ind_cargo = cid + NUM_INDUSTRYTYPES;
2838 _displayed_industries.reset();
2840 this->fields.clear();
2841 CargoesRow &row = this->fields.emplace_back();
2842 row.columns[0].MakeHeader(STR_INDUSTRY_CARGOES_PRODUCERS);
2843 row.columns[1].MakeEmpty(CFT_SMALL_EMPTY);
2844 row.columns[2].MakeHeader(STR_INDUSTRY_CARGOES_CUSTOMERS);
2845 row.columns[3].MakeEmpty(CFT_SMALL_EMPTY);
2846 row.columns[4].MakeEmpty(CFT_SMALL_EMPTY);
2848 bool houses_supply = HousesCanSupply(&cid, 1);
2849 bool houses_accept = HousesCanAccept(&cid, 1);
2850 int num_supp = CountMatchingProducingIndustries(&cid, 1) + houses_supply + 1; // Ensure room for the cargo label.
2851 int num_cust = CountMatchingAcceptingIndustries(&cid, 1) + houses_accept;
2852 int num_indrows = std::max(num_supp, num_cust);
2853 for (int i = 0; i < num_indrows; i++) {
2854 CargoesRow &row = this->fields.emplace_back();
2855 row.columns[0].MakeEmpty(CFT_EMPTY);
2856 row.columns[1].MakeCargo(&cid, 1);
2857 row.columns[2].MakeEmpty(CFT_EMPTY);
2858 row.columns[3].MakeEmpty(CFT_EMPTY);
2859 row.columns[4].MakeEmpty(CFT_EMPTY);
2862 this->fields[num_indrows].MakeCargoLabel(0, false); // Add cargo labels at the left bottom.
2864 /* Add suppliers and customers of the cargo. */
2865 int supp_count = 0;
2866 int cust_count = 0;
2867 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
2868 const IndustrySpec *indsp = GetIndustrySpec(it);
2869 if (!indsp->enabled) continue;
2871 if (HasCommonValidCargo(&cid, 1, indsp->produced_cargo, lengthof(indsp->produced_cargo))) {
2872 this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, it);
2873 _displayed_industries.set(it);
2874 supp_count++;
2876 if (HasCommonValidCargo(&cid, 1, indsp->accepts_cargo, lengthof(indsp->accepts_cargo))) {
2877 this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 2, it);
2878 _displayed_industries.set(it);
2879 cust_count++;
2882 if (houses_supply) {
2883 this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, NUM_INDUSTRYTYPES);
2884 supp_count++;
2886 if (houses_accept) {
2887 this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 2, NUM_INDUSTRYTYPES);
2888 cust_count++;
2891 this->ShortenCargoColumn(1, 1, num_indrows);
2892 this->vscroll->SetCount(num_indrows);
2893 this->SetDirty();
2894 this->NotifySmallmap();
2898 * Some data on this window has become invalid.
2899 * @param data Information about the changed data.
2900 * - data = 0 .. NUM_INDUSTRYTYPES - 1: Display the chain around the given industry.
2901 * - data = NUM_INDUSTRYTYPES: Stop sending updates to the smallmap window.
2902 * @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.
2904 void OnInvalidateData(int data = 0, bool gui_scope = true) override
2906 if (!gui_scope) return;
2907 if (data == NUM_INDUSTRYTYPES) {
2908 if (this->IsWidgetLowered(WID_IC_NOTIFY)) {
2909 this->RaiseWidget(WID_IC_NOTIFY);
2910 this->SetWidgetDirty(WID_IC_NOTIFY);
2912 return;
2915 assert(data >= 0 && data < NUM_INDUSTRYTYPES);
2916 this->ComputeIndustryDisplay(data);
2919 void DrawWidget(const Rect &r, int widget) const override
2921 if (widget != WID_IC_PANEL) return;
2923 DrawPixelInfo tmp_dpi, *old_dpi;
2924 int width = r.right - r.left + 1;
2925 int height = r.bottom - r.top + 1 - WD_FRAMERECT_TOP - WD_FRAMERECT_BOTTOM;
2926 if (!FillDrawPixelInfo(&tmp_dpi, r.left + WD_FRAMERECT_LEFT, r.top + WD_FRAMERECT_TOP, width, height)) return;
2927 old_dpi = _cur_dpi;
2928 _cur_dpi = &tmp_dpi;
2930 int left_pos = WD_FRAMERECT_LEFT;
2931 if (this->ind_cargo >= NUM_INDUSTRYTYPES) left_pos += (CargoesField::industry_width + CargoesField::cargo_field_width) / 2;
2932 int last_column = (this->ind_cargo < NUM_INDUSTRYTYPES) ? 4 : 2;
2934 const NWidgetBase *nwp = this->GetWidget<NWidgetBase>(WID_IC_PANEL);
2935 int vpos = -this->vscroll->GetPosition() * nwp->resize_y;
2936 for (uint i = 0; i < this->fields.size(); i++) {
2937 int row_height = (i == 0) ? CargoesField::small_height : CargoesField::normal_height;
2938 if (vpos + row_height >= 0) {
2939 int xpos = left_pos;
2940 int col, dir;
2941 if (_current_text_dir == TD_RTL) {
2942 col = last_column;
2943 dir = -1;
2944 } else {
2945 col = 0;
2946 dir = 1;
2948 while (col >= 0 && col <= last_column) {
2949 this->fields[i].columns[col].Draw(xpos, vpos);
2950 xpos += (col & 1) ? CargoesField::cargo_field_width : CargoesField::industry_width;
2951 col += dir;
2954 vpos += row_height;
2955 if (vpos >= height) break;
2958 _cur_dpi = old_dpi;
2962 * Calculate in which field was clicked, and within the field, at what position.
2963 * @param pt Clicked position in the #WID_IC_PANEL widget.
2964 * @param fieldxy If \c true is returned, field x/y coordinate of \a pt.
2965 * @param xy If \c true is returned, x/y coordinate with in the field.
2966 * @return Clicked at a valid position.
2968 bool CalculatePositionInWidget(Point pt, Point *fieldxy, Point *xy)
2970 const NWidgetBase *nw = this->GetWidget<NWidgetBase>(WID_IC_PANEL);
2971 pt.x -= nw->pos_x;
2972 pt.y -= nw->pos_y;
2974 int vpos = WD_FRAMERECT_TOP + CargoesField::small_height - this->vscroll->GetPosition() * nw->resize_y;
2975 if (pt.y < vpos) return false;
2977 int row = (pt.y - vpos) / CargoesField::normal_height; // row is relative to row 1.
2978 if (row + 1 >= (int)this->fields.size()) return false;
2979 vpos = pt.y - vpos - row * CargoesField::normal_height; // Position in the row + 1 field
2980 row++; // rebase row to match index of this->fields.
2982 int xpos = 2 * WD_FRAMERECT_LEFT + ((this->ind_cargo < NUM_INDUSTRYTYPES) ? 0 : (CargoesField::industry_width + CargoesField::cargo_field_width) / 2);
2983 if (pt.x < xpos) return false;
2984 int column;
2985 for (column = 0; column <= 5; column++) {
2986 int width = (column & 1) ? CargoesField::cargo_field_width : CargoesField::industry_width;
2987 if (pt.x < xpos + width) break;
2988 xpos += width;
2990 int num_columns = (this->ind_cargo < NUM_INDUSTRYTYPES) ? 4 : 2;
2991 if (column > num_columns) return false;
2992 xpos = pt.x - xpos;
2994 /* Return both positions, compensating for RTL languages (which works due to the equal symmetry in both displays). */
2995 fieldxy->y = row;
2996 xy->y = vpos;
2997 if (_current_text_dir == TD_RTL) {
2998 fieldxy->x = num_columns - column;
2999 xy->x = ((column & 1) ? CargoesField::cargo_field_width : CargoesField::industry_width) - xpos;
3000 } else {
3001 fieldxy->x = column;
3002 xy->x = xpos;
3004 return true;
3007 void OnClick(Point pt, int widget, int click_count) override
3009 switch (widget) {
3010 case WID_IC_PANEL: {
3011 Point fieldxy, xy;
3012 if (!CalculatePositionInWidget(pt, &fieldxy, &xy)) return;
3014 const CargoesField *fld = this->fields[fieldxy.y].columns + fieldxy.x;
3015 switch (fld->type) {
3016 case CFT_INDUSTRY:
3017 if (fld->u.industry.ind_type < NUM_INDUSTRYTYPES) this->ComputeIndustryDisplay(fld->u.industry.ind_type);
3018 break;
3020 case CFT_CARGO: {
3021 CargoesField *lft = (fieldxy.x > 0) ? this->fields[fieldxy.y].columns + fieldxy.x - 1 : nullptr;
3022 CargoesField *rgt = (fieldxy.x < 4) ? this->fields[fieldxy.y].columns + fieldxy.x + 1 : nullptr;
3023 CargoID cid = fld->CargoClickedAt(lft, rgt, xy);
3024 if (cid != INVALID_CARGO) this->ComputeCargoDisplay(cid);
3025 break;
3028 case CFT_CARGO_LABEL: {
3029 CargoID cid = fld->CargoLabelClickedAt(xy);
3030 if (cid != INVALID_CARGO) this->ComputeCargoDisplay(cid);
3031 break;
3034 default:
3035 break;
3037 break;
3040 case WID_IC_NOTIFY:
3041 this->ToggleWidgetLoweredState(WID_IC_NOTIFY);
3042 this->SetWidgetDirty(WID_IC_NOTIFY);
3043 if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
3045 if (this->IsWidgetLowered(WID_IC_NOTIFY)) {
3046 if (FindWindowByClass(WC_SMALLMAP) == nullptr) ShowSmallMap();
3047 this->NotifySmallmap();
3049 break;
3051 case WID_IC_CARGO_DROPDOWN: {
3052 DropDownList lst;
3053 for (const CargoSpec *cs : _sorted_standard_cargo_specs) {
3054 lst.emplace_back(new DropDownListStringItem(cs->name, cs->Index(), false));
3056 if (!lst.empty()) {
3057 int selected = (this->ind_cargo >= NUM_INDUSTRYTYPES) ? (int)(this->ind_cargo - NUM_INDUSTRYTYPES) : -1;
3058 ShowDropDownList(this, std::move(lst), selected, WID_IC_CARGO_DROPDOWN, 0, true);
3060 break;
3063 case WID_IC_IND_DROPDOWN: {
3064 DropDownList lst;
3065 for (IndustryType ind : _sorted_industry_types) {
3066 const IndustrySpec *indsp = GetIndustrySpec(ind);
3067 if (!indsp->enabled) continue;
3068 lst.emplace_back(new DropDownListStringItem(indsp->name, ind, false));
3070 if (!lst.empty()) {
3071 int selected = (this->ind_cargo < NUM_INDUSTRYTYPES) ? (int)this->ind_cargo : -1;
3072 ShowDropDownList(this, std::move(lst), selected, WID_IC_IND_DROPDOWN, 0, true);
3074 break;
3079 void OnDropdownSelect(int widget, int index) override
3081 if (index < 0) return;
3083 switch (widget) {
3084 case WID_IC_CARGO_DROPDOWN:
3085 this->ComputeCargoDisplay(index);
3086 break;
3088 case WID_IC_IND_DROPDOWN:
3089 this->ComputeIndustryDisplay(index);
3090 break;
3094 bool OnTooltip(Point pt, int widget, TooltipCloseCondition close_cond) override
3096 if (widget != WID_IC_PANEL) return false;
3098 Point fieldxy, xy;
3099 if (!CalculatePositionInWidget(pt, &fieldxy, &xy)) return false;
3101 const CargoesField *fld = this->fields[fieldxy.y].columns + fieldxy.x;
3102 CargoID cid = INVALID_CARGO;
3103 switch (fld->type) {
3104 case CFT_CARGO: {
3105 CargoesField *lft = (fieldxy.x > 0) ? this->fields[fieldxy.y].columns + fieldxy.x - 1 : nullptr;
3106 CargoesField *rgt = (fieldxy.x < 4) ? this->fields[fieldxy.y].columns + fieldxy.x + 1 : nullptr;
3107 cid = fld->CargoClickedAt(lft, rgt, xy);
3108 break;
3111 case CFT_CARGO_LABEL: {
3112 cid = fld->CargoLabelClickedAt(xy);
3113 break;
3116 case CFT_INDUSTRY:
3117 if (fld->u.industry.ind_type < NUM_INDUSTRYTYPES && (this->ind_cargo >= NUM_INDUSTRYTYPES || fieldxy.x != 2)) {
3118 GuiShowTooltips(this, STR_INDUSTRY_CARGOES_INDUSTRY_TOOLTIP, 0, nullptr, close_cond);
3120 return true;
3122 default:
3123 break;
3125 if (cid != INVALID_CARGO && (this->ind_cargo < NUM_INDUSTRYTYPES || cid != this->ind_cargo - NUM_INDUSTRYTYPES)) {
3126 const CargoSpec *csp = CargoSpec::Get(cid);
3127 uint64 params[5];
3128 params[0] = csp->name;
3129 GuiShowTooltips(this, STR_INDUSTRY_CARGOES_CARGO_TOOLTIP, 1, params, close_cond);
3130 return true;
3133 return false;
3136 void OnResize() override
3138 this->vscroll->SetCapacityFromWidget(this, WID_IC_PANEL, WD_FRAMERECT_TOP + CargoesField::small_height);
3142 const int IndustryCargoesWindow::HOR_TEXT_PADDING = 5; ///< Horizontal padding around the industry type text.
3143 const int IndustryCargoesWindow::VERT_TEXT_PADDING = 5; ///< Vertical padding around the industry type text.
3146 * Open the industry and cargoes window.
3147 * @param id Industry type to display, \c NUM_INDUSTRYTYPES selects a default industry type.
3149 static void ShowIndustryCargoesWindow(IndustryType id)
3151 if (id >= NUM_INDUSTRYTYPES) {
3152 for (IndustryType ind : _sorted_industry_types) {
3153 const IndustrySpec *indsp = GetIndustrySpec(ind);
3154 if (indsp->enabled) {
3155 id = ind;
3156 break;
3159 if (id >= NUM_INDUSTRYTYPES) return;
3162 Window *w = BringWindowToFrontById(WC_INDUSTRY_CARGOES, 0);
3163 if (w != nullptr) {
3164 w->InvalidateData(id);
3165 return;
3167 new IndustryCargoesWindow(id);
3170 /** Open the industry and cargoes window with an industry. */
3171 void ShowIndustryCargoesWindow()
3173 ShowIndustryCargoesWindow(NUM_INDUSTRYTYPES);