industry_gui.cpp

Go to the documentation of this file.
00001 /* $Id$ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * 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.
00006  * 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.
00007  * 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/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 #include "error.h"
00014 #include "gui.h"
00015 #include "settings_gui.h"
00016 #include "sound_func.h"
00017 #include "window_func.h"
00018 #include "textbuf_gui.h"
00019 #include "command_func.h"
00020 #include "viewport_func.h"
00021 #include "industry.h"
00022 #include "town.h"
00023 #include "cheat_type.h"
00024 #include "newgrf_industries.h"
00025 #include "newgrf_text.h"
00026 #include "newgrf_debug.h"
00027 #include "strings_func.h"
00028 #include "company_func.h"
00029 #include "tilehighlight_func.h"
00030 #include "string_func.h"
00031 #include "sortlist_type.h"
00032 #include "widgets/dropdown_func.h"
00033 #include "company_base.h"
00034 #include "core/geometry_func.hpp"
00035 #include "core/random_func.hpp"
00036 #include "core/backup_type.hpp"
00037 #include "genworld.h"
00038 #include "smallmap_gui.h"
00039 #include "widgets/dropdown_type.h"
00040 #include "widgets/industry_widget.h"
00041 
00042 #include "table/strings.h"
00043 
00044 bool _ignore_restrictions;
00045 uint64 _displayed_industries; 
00046 
00047 assert_compile(NUM_INDUSTRYTYPES <= 64); // Make sure all industry types fit in _displayed_industries.
00048 
00050 enum CargoSuffixType {
00051   CST_FUND,  
00052   CST_VIEW,  
00053   CST_DIR,   
00054 };
00055 
00056 static void ShowIndustryCargoesWindow(IndustryType id);
00057 
00073 static void GetCargoSuffix(uint cargo, CargoSuffixType cst, const Industry *ind, IndustryType ind_type, const IndustrySpec *indspec, char *suffix, const char *suffix_last)
00074 {
00075   suffix[0] = '\0';
00076   if (HasBit(indspec->callback_mask, CBM_IND_CARGO_SUFFIX)) {
00077     uint16 callback = GetIndustryCallback(CBID_INDUSTRY_CARGO_SUFFIX, 0, (cst << 8) | cargo, const_cast<Industry *>(ind), ind_type, (cst != CST_FUND) ? ind->location.tile : INVALID_TILE);
00078     if (callback == CALLBACK_FAILED || callback == 0x400) return;
00079     if (callback > 0x400) {
00080       ErrorUnknownCallbackResult(indspec->grf_prop.grffile->grfid, CBID_INDUSTRY_CARGO_SUFFIX, callback);
00081     } else if (indspec->grf_prop.grffile->grf_version >= 8 || GB(callback, 0, 8) != 0xFF) {
00082       StartTextRefStackUsage(6);
00083       GetString(suffix, GetGRFStringID(indspec->grf_prop.grffile->grfid, 0xD000 + callback), suffix_last);
00084       StopTextRefStackUsage();
00085     }
00086   }
00087 }
00088 
00099 template <typename TC, typename TS>
00100 static inline void GetAllCargoSuffixes(uint cb_offset, CargoSuffixType cst, const Industry *ind, IndustryType ind_type, const IndustrySpec *indspec, const TC &cargoes, TS &suffixes)
00101 {
00102   assert_compile(lengthof(cargoes) <= lengthof(suffixes));
00103   for (uint j = 0; j < lengthof(cargoes); j++) {
00104     if (cargoes[j] != CT_INVALID) {
00105       GetCargoSuffix(cb_offset + j, cst, ind, ind_type, indspec, suffixes[j], lastof(suffixes[j]));
00106     } else {
00107       suffixes[j][0] = '\0';
00108     }
00109   }
00110 }
00111 
00112 IndustryType _sorted_industry_types[NUM_INDUSTRYTYPES]; 
00113 
00115 static int CDECL IndustryTypeNameSorter(const IndustryType *a, const IndustryType *b)
00116 {
00117   static char industry_name[2][64];
00118 
00119   const IndustrySpec *indsp1 = GetIndustrySpec(*a);
00120   SetDParam(0, indsp1->name);
00121   GetString(industry_name[0], STR_JUST_STRING, lastof(industry_name[0]));
00122 
00123   const IndustrySpec *indsp2 = GetIndustrySpec(*b);
00124   SetDParam(0, indsp2->name);
00125   GetString(industry_name[1], STR_JUST_STRING, lastof(industry_name[1]));
00126 
00127   int r = strnatcmp(industry_name[0], industry_name[1]); // Sort by name (natural sorting).
00128 
00129   /* If the names are equal, sort by industry type. */
00130   return (r != 0) ? r : (*a - *b);
00131 }
00132 
00136 void SortIndustryTypes()
00137 {
00138   /* Add each industry type to the list. */
00139   for (IndustryType i = 0; i < NUM_INDUSTRYTYPES; i++) {
00140     _sorted_industry_types[i] = i;
00141   }
00142 
00143   /* Sort industry types by name. */
00144   QSortT(_sorted_industry_types, NUM_INDUSTRYTYPES, &IndustryTypeNameSorter);
00145 }
00146 
00154 void CcBuildIndustry(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
00155 {
00156   if (result.Succeeded()) return;
00157 
00158   uint8 indtype = GB(p1, 0, 8);
00159   if (indtype < NUM_INDUSTRYTYPES) {
00160     const IndustrySpec *indsp = GetIndustrySpec(indtype);
00161     if (indsp->enabled) {
00162       SetDParam(0, indsp->name);
00163       ShowErrorMessage(STR_ERROR_CAN_T_BUILD_HERE, result.GetErrorMessage(), WL_INFO, TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE);
00164     }
00165   }
00166 }
00167 
00168 static const NWidgetPart _nested_build_industry_widgets[] = {
00169   NWidget(NWID_HORIZONTAL),
00170     NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
00171     NWidget(WWT_CAPTION, COLOUR_DARK_GREEN), SetDataTip(STR_FUND_INDUSTRY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00172     NWidget(WWT_SHADEBOX, COLOUR_DARK_GREEN),
00173     NWidget(WWT_STICKYBOX, COLOUR_DARK_GREEN),
00174   EndContainer(),
00175   NWidget(NWID_HORIZONTAL),
00176     NWidget(WWT_MATRIX, COLOUR_DARK_GREEN, WID_DPI_MATRIX_WIDGET), SetDataTip(0x801, STR_FUND_INDUSTRY_SELECTION_TOOLTIP), SetFill(1, 0), SetResize(1, 1), SetScrollbar(WID_DPI_SCROLLBAR),
00177     NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, WID_DPI_SCROLLBAR),
00178   EndContainer(),
00179   NWidget(WWT_PANEL, COLOUR_DARK_GREEN, WID_DPI_INFOPANEL), SetResize(1, 0),
00180   EndContainer(),
00181   NWidget(NWID_HORIZONTAL),
00182     NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, WID_DPI_DISPLAY_WIDGET), SetFill(1, 0), SetResize(1, 0),
00183         SetDataTip(STR_INDUSTRY_DISPLAY_CHAIN, STR_INDUSTRY_DISPLAY_CHAIN_TOOLTIP),
00184     NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, WID_DPI_FUND_WIDGET), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_JUST_STRING, STR_NULL),
00185     NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
00186   EndContainer(),
00187 };
00188 
00190 static const WindowDesc _build_industry_desc(
00191   WDP_AUTO, 170, 212,
00192   WC_BUILD_INDUSTRY, WC_NONE,
00193   WDF_CONSTRUCTION,
00194   _nested_build_industry_widgets, lengthof(_nested_build_industry_widgets)
00195 );
00196 
00198 class BuildIndustryWindow : public Window {
00199   int selected_index;                         
00200   IndustryType selected_type;                 
00201   uint16 callback_timer;                      
00202   bool timer_enabled;                         
00203   uint16 count;                               
00204   IndustryType index[NUM_INDUSTRYTYPES + 1];  
00205   bool enabled[NUM_INDUSTRYTYPES + 1];        
00206   Scrollbar *vscroll;
00207 
00209   static const int MATRIX_TEXT_OFFSET = 17;
00210 
00211   void SetupArrays()
00212   {
00213     this->count = 0;
00214 
00215     for (uint i = 0; i < lengthof(this->index); i++) {
00216       this->index[i]   = INVALID_INDUSTRYTYPE;
00217       this->enabled[i] = false;
00218     }
00219 
00220     if (_game_mode == GM_EDITOR) { // give room for the Many Random "button"
00221       this->index[this->count] = INVALID_INDUSTRYTYPE;
00222       this->enabled[this->count] = true;
00223       this->count++;
00224       this->timer_enabled = false;
00225     }
00226     /* Fill the arrays with industries.
00227      * The tests performed after the enabled allow to load the industries
00228      * In the same way they are inserted by grf (if any)
00229      */
00230     for (uint8 i = 0; i < NUM_INDUSTRYTYPES; i++) {
00231       IndustryType ind = _sorted_industry_types[i];
00232       const IndustrySpec *indsp = GetIndustrySpec(ind);
00233       if (indsp->enabled) {
00234         /* Rule is that editor mode loads all industries.
00235          * In game mode, all non raw industries are loaded too
00236          * and raw ones are loaded only when setting allows it */
00237         if (_game_mode != GM_EDITOR && indsp->IsRawIndustry() && _settings_game.construction.raw_industry_construction == 0) {
00238           /* Unselect if the industry is no longer in the list */
00239           if (this->selected_type == ind) this->selected_index = -1;
00240           continue;
00241         }
00242         this->index[this->count] = ind;
00243         this->enabled[this->count] = (_game_mode == GM_EDITOR) || GetIndustryProbabilityCallback(ind, IACT_USERCREATION, 1) > 0;
00244         /* Keep the selection to the correct line */
00245         if (this->selected_type == ind) this->selected_index = this->count;
00246         this->count++;
00247       }
00248     }
00249 
00250     /* first industry type is selected if the current selection is invalid.
00251      * I'll be damned if there are none available ;) */
00252     if (this->selected_index == -1) {
00253       this->selected_index = 0;
00254       this->selected_type = this->index[0];
00255     }
00256 
00257     this->vscroll->SetCount(this->count);
00258   }
00259 
00261   void SetButtons()
00262   {
00263     this->SetWidgetDisabledState(WID_DPI_FUND_WIDGET, this->selected_type != INVALID_INDUSTRYTYPE && !this->enabled[this->selected_index]);
00264     this->SetWidgetDisabledState(WID_DPI_DISPLAY_WIDGET, this->selected_type == INVALID_INDUSTRYTYPE && this->enabled[this->selected_index]);
00265   }
00266 
00267 public:
00268   BuildIndustryWindow() : Window()
00269   {
00270     this->timer_enabled = _loaded_newgrf_features.has_newindustries;
00271 
00272     this->selected_index = -1;
00273     this->selected_type = INVALID_INDUSTRYTYPE;
00274 
00275     this->callback_timer = DAY_TICKS;
00276 
00277     this->CreateNestedTree(&_build_industry_desc);
00278     this->vscroll = this->GetScrollbar(WID_DPI_SCROLLBAR);
00279     this->FinishInitNested(&_build_industry_desc, 0);
00280 
00281     this->SetButtons();
00282   }
00283 
00284   virtual void OnInit()
00285   {
00286     this->SetupArrays();
00287   }
00288 
00289   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00290   {
00291     switch (widget) {
00292       case WID_DPI_MATRIX_WIDGET: {
00293         Dimension d = GetStringBoundingBox(STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES);
00294         for (byte i = 0; i < this->count; i++) {
00295           if (this->index[i] == INVALID_INDUSTRYTYPE) continue;
00296           d = maxdim(d, GetStringBoundingBox(GetIndustrySpec(this->index[i])->name));
00297         }
00298         resize->height = FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;
00299         d.width += MATRIX_TEXT_OFFSET + padding.width;
00300         d.height = 5 * resize->height;
00301         *size = maxdim(*size, d);
00302         break;
00303       }
00304 
00305       case WID_DPI_INFOPANEL: {
00306         /* Extra line for cost outside of editor + extra lines for 'extra' information for NewGRFs. */
00307         int height = 2 + (_game_mode == GM_EDITOR ? 0 : 1) + (_loaded_newgrf_features.has_newindustries ? 4 : 0);
00308         Dimension d = {0, 0};
00309         for (byte i = 0; i < this->count; i++) {
00310           if (this->index[i] == INVALID_INDUSTRYTYPE) continue;
00311 
00312           const IndustrySpec *indsp = GetIndustrySpec(this->index[i]);
00313 
00314           char cargo_suffix[3][512];
00315           GetAllCargoSuffixes(0, CST_FUND, NULL, this->index[i], indsp, indsp->accepts_cargo, cargo_suffix);
00316           StringID str = STR_INDUSTRY_VIEW_REQUIRES_CARGO;
00317           byte p = 0;
00318           SetDParam(0, STR_JUST_NOTHING);
00319           SetDParamStr(1, "");
00320           for (byte j = 0; j < lengthof(indsp->accepts_cargo); j++) {
00321             if (indsp->accepts_cargo[j] == CT_INVALID) continue;
00322             if (p > 0) str++;
00323             SetDParam(p++, CargoSpec::Get(indsp->accepts_cargo[j])->name);
00324             SetDParamStr(p++, cargo_suffix[j]);
00325           }
00326           d = maxdim(d, GetStringBoundingBox(str));
00327 
00328           /* Draw the produced cargoes, if any. Otherwise, will print "Nothing". */
00329           GetAllCargoSuffixes(3, CST_FUND, NULL, this->index[i], indsp, indsp->produced_cargo, cargo_suffix);
00330           str = STR_INDUSTRY_VIEW_PRODUCES_CARGO;
00331           p = 0;
00332           SetDParam(0, STR_JUST_NOTHING);
00333           SetDParamStr(1, "");
00334           for (byte j = 0; j < lengthof(indsp->produced_cargo); j++) {
00335             if (indsp->produced_cargo[j] == CT_INVALID) continue;
00336             if (p > 0) str++;
00337             SetDParam(p++, CargoSpec::Get(indsp->produced_cargo[j])->name);
00338             SetDParamStr(p++, cargo_suffix[j]);
00339           }
00340           d = maxdim(d, GetStringBoundingBox(str));
00341         }
00342 
00343         /* Set it to something more sane :) */
00344         size->height = height * FONT_HEIGHT_NORMAL + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
00345         size->width  = d.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
00346         break;
00347       }
00348 
00349       case WID_DPI_FUND_WIDGET: {
00350         Dimension d = GetStringBoundingBox(STR_FUND_INDUSTRY_BUILD_NEW_INDUSTRY);
00351         d = maxdim(d, GetStringBoundingBox(STR_FUND_INDUSTRY_PROSPECT_NEW_INDUSTRY));
00352         d = maxdim(d, GetStringBoundingBox(STR_FUND_INDUSTRY_FUND_NEW_INDUSTRY));
00353         d.width += padding.width;
00354         d.height += padding.height;
00355         *size = maxdim(*size, d);
00356         break;
00357       }
00358     }
00359   }
00360 
00361   virtual void SetStringParameters(int widget) const
00362   {
00363     switch (widget) {
00364       case WID_DPI_FUND_WIDGET:
00365         /* Raw industries might be prospected. Show this fact by changing the string
00366          * In Editor, you just build, while ingame, or you fund or you prospect */
00367         if (_game_mode == GM_EDITOR) {
00368           /* We've chosen many random industries but no industries have been specified */
00369           SetDParam(0, STR_FUND_INDUSTRY_BUILD_NEW_INDUSTRY);
00370         } else {
00371           const IndustrySpec *indsp = GetIndustrySpec(this->index[this->selected_index]);
00372           SetDParam(0, (_settings_game.construction.raw_industry_construction == 2 && indsp->IsRawIndustry()) ? STR_FUND_INDUSTRY_PROSPECT_NEW_INDUSTRY : STR_FUND_INDUSTRY_FUND_NEW_INDUSTRY);
00373         }
00374         break;
00375     }
00376   }
00377 
00378   virtual void DrawWidget(const Rect &r, int widget) const
00379   {
00380     switch (widget) {
00381       case WID_DPI_MATRIX_WIDGET:
00382         for (byte i = 0; i < this->vscroll->GetCapacity() && i + this->vscroll->GetPosition() < this->count; i++) {
00383           int x = r.left + WD_MATRIX_LEFT;
00384           int y = r.top + WD_MATRIX_TOP + i * this->resize.step_height;
00385           bool selected = this->selected_index == i + this->vscroll->GetPosition();
00386 
00387           if (this->index[i + this->vscroll->GetPosition()] == INVALID_INDUSTRYTYPE) {
00388             DrawString(x + MATRIX_TEXT_OFFSET, r.right - WD_MATRIX_RIGHT, y, STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES, selected ? TC_WHITE : TC_ORANGE);
00389             continue;
00390           }
00391           const IndustrySpec *indsp = GetIndustrySpec(this->index[i + this->vscroll->GetPosition()]);
00392 
00393           /* Draw the name of the industry in white is selected, otherwise, in orange */
00394           DrawString(x + MATRIX_TEXT_OFFSET, r.right - WD_MATRIX_RIGHT, y, indsp->name, selected ? TC_WHITE : TC_ORANGE);
00395           GfxFillRect(x,     y + 1,  x + 10, y + 7, selected ? PC_WHITE : PC_BLACK);
00396           GfxFillRect(x + 1, y + 2,  x +  9, y + 6, indsp->map_colour);
00397         }
00398         break;
00399 
00400       case WID_DPI_INFOPANEL: {
00401         int y      = r.top    + WD_FRAMERECT_TOP;
00402         int bottom = r.bottom - WD_FRAMERECT_BOTTOM;
00403         int left   = r.left   + WD_FRAMERECT_LEFT;
00404         int right  = r.right  - WD_FRAMERECT_RIGHT;
00405 
00406         if (this->selected_type == INVALID_INDUSTRYTYPE) {
00407           DrawStringMultiLine(left, right, y,  bottom, STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES_TOOLTIP);
00408           break;
00409         }
00410 
00411         const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
00412 
00413         if (_game_mode != GM_EDITOR) {
00414           SetDParam(0, indsp->GetConstructionCost());
00415           DrawString(left, right, y, STR_FUND_INDUSTRY_INDUSTRY_BUILD_COST);
00416           y += FONT_HEIGHT_NORMAL;
00417         }
00418 
00419         /* Draw the accepted cargoes, if any. Otherwise, will print "Nothing". */
00420         char cargo_suffix[3][512];
00421         GetAllCargoSuffixes(0, CST_FUND, NULL, this->selected_type, indsp, indsp->accepts_cargo, cargo_suffix);
00422         StringID str = STR_INDUSTRY_VIEW_REQUIRES_CARGO;
00423         byte p = 0;
00424         SetDParam(0, STR_JUST_NOTHING);
00425         SetDParamStr(1, "");
00426         for (byte j = 0; j < lengthof(indsp->accepts_cargo); j++) {
00427           if (indsp->accepts_cargo[j] == CT_INVALID) continue;
00428           if (p > 0) str++;
00429           SetDParam(p++, CargoSpec::Get(indsp->accepts_cargo[j])->name);
00430           SetDParamStr(p++, cargo_suffix[j]);
00431         }
00432         DrawString(left, right, y, str);
00433         y += FONT_HEIGHT_NORMAL;
00434 
00435         /* Draw the produced cargoes, if any. Otherwise, will print "Nothing". */
00436         GetAllCargoSuffixes(3, CST_FUND, NULL, this->selected_type, indsp, indsp->produced_cargo, cargo_suffix);
00437         str = STR_INDUSTRY_VIEW_PRODUCES_CARGO;
00438         p = 0;
00439         SetDParam(0, STR_JUST_NOTHING);
00440         SetDParamStr(1, "");
00441         for (byte j = 0; j < lengthof(indsp->produced_cargo); j++) {
00442           if (indsp->produced_cargo[j] == CT_INVALID) continue;
00443           if (p > 0) str++;
00444           SetDParam(p++, CargoSpec::Get(indsp->produced_cargo[j])->name);
00445           SetDParamStr(p++, cargo_suffix[j]);
00446         }
00447         DrawString(left, right, y, str);
00448         y += FONT_HEIGHT_NORMAL;
00449 
00450         /* Get the additional purchase info text, if it has not already been queried. */
00451         str = STR_NULL;
00452         if (HasBit(indsp->callback_mask, CBM_IND_FUND_MORE_TEXT)) {
00453           uint16 callback_res = GetIndustryCallback(CBID_INDUSTRY_FUND_MORE_TEXT, 0, 0, NULL, this->selected_type, INVALID_TILE);
00454           if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
00455             if (callback_res > 0x400) {
00456               ErrorUnknownCallbackResult(indsp->grf_prop.grffile->grfid, CBID_INDUSTRY_FUND_MORE_TEXT, callback_res);
00457             } else {
00458               str = GetGRFStringID(indsp->grf_prop.grffile->grfid, 0xD000 + callback_res);  // No. here's the new string
00459               if (str != STR_UNDEFINED) {
00460                 StartTextRefStackUsage(6);
00461                 DrawStringMultiLine(left, right, y, bottom, str, TC_YELLOW);
00462                 StopTextRefStackUsage();
00463               }
00464             }
00465           }
00466         }
00467         break;
00468       }
00469     }
00470   }
00471 
00472   virtual void OnClick(Point pt, int widget, int click_count)
00473   {
00474     switch (widget) {
00475       case WID_DPI_MATRIX_WIDGET: {
00476         int y = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_DPI_MATRIX_WIDGET);
00477         if (y < this->count) { // Is it within the boundaries of available data?
00478           this->selected_index = y;
00479           this->selected_type = this->index[y];
00480           const IndustrySpec *indsp = (this->selected_type == INVALID_INDUSTRYTYPE) ? NULL : GetIndustrySpec(this->selected_type);
00481 
00482           this->SetDirty();
00483 
00484           if (_thd.GetCallbackWnd() == this &&
00485               ((_game_mode != GM_EDITOR && _settings_game.construction.raw_industry_construction == 2 && indsp != NULL && indsp->IsRawIndustry()) ||
00486               this->selected_type == INVALID_INDUSTRYTYPE ||
00487               !this->enabled[this->selected_index])) {
00488             /* Reset the button state if going to prospecting or "build many industries" */
00489             this->RaiseButtons();
00490             ResetObjectToPlace();
00491           }
00492 
00493           this->SetButtons();
00494           if (this->enabled[this->selected_index] && click_count > 1) this->OnClick(pt, WID_DPI_FUND_WIDGET, 1);
00495         }
00496         break;
00497       }
00498 
00499       case WID_DPI_DISPLAY_WIDGET:
00500         if (this->selected_type != INVALID_INDUSTRYTYPE) ShowIndustryCargoesWindow(this->selected_type);
00501         break;
00502 
00503       case WID_DPI_FUND_WIDGET: {
00504         if (this->selected_type == INVALID_INDUSTRYTYPE) {
00505           this->HandleButtonClick(WID_DPI_FUND_WIDGET);
00506 
00507           if (Town::GetNumItems() == 0) {
00508             ShowErrorMessage(STR_ERROR_CAN_T_GENERATE_INDUSTRIES, STR_ERROR_MUST_FOUND_TOWN_FIRST, WL_INFO);
00509           } else {
00510             extern void GenerateIndustries();
00511             _generating_world = true;
00512             GenerateIndustries();
00513             _generating_world = false;
00514           }
00515         } else if (_game_mode != GM_EDITOR && _settings_game.construction.raw_industry_construction == 2 && GetIndustrySpec(this->selected_type)->IsRawIndustry()) {
00516           DoCommandP(0, this->selected_type, InteractiveRandom(), CMD_BUILD_INDUSTRY | CMD_MSG(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY));
00517           this->HandleButtonClick(WID_DPI_FUND_WIDGET);
00518         } else {
00519           HandlePlacePushButton(this, WID_DPI_FUND_WIDGET, SPR_CURSOR_INDUSTRY, HT_RECT);
00520         }
00521         break;
00522       }
00523     }
00524   }
00525 
00526   virtual void OnResize()
00527   {
00528     /* Adjust the number of items in the matrix depending of the resize */
00529     this->vscroll->SetCapacityFromWidget(this, WID_DPI_MATRIX_WIDGET);
00530     this->GetWidget<NWidgetCore>(WID_DPI_MATRIX_WIDGET)->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
00531   }
00532 
00533   virtual void OnPlaceObject(Point pt, TileIndex tile)
00534   {
00535     bool success = true;
00536     /* We do not need to protect ourselves against "Random Many Industries" in this mode */
00537     const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
00538     uint32 seed = InteractiveRandom();
00539 
00540     if (_game_mode == GM_EDITOR) {
00541       /* Show error if no town exists at all */
00542       if (Town::GetNumItems() == 0) {
00543         SetDParam(0, indsp->name);
00544         ShowErrorMessage(STR_ERROR_CAN_T_BUILD_HERE, STR_ERROR_MUST_FOUND_TOWN_FIRST, WL_INFO, pt.x, pt.y);
00545         return;
00546       }
00547 
00548       Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
00549       _generating_world = true;
00550       _ignore_restrictions = true;
00551 
00552       DoCommandP(tile, (InteractiveRandomRange(indsp->num_table) << 8) | this->selected_type, seed,
00553           CMD_BUILD_INDUSTRY | CMD_MSG(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY), &CcBuildIndustry);
00554 
00555       cur_company.Restore();
00556       _ignore_restrictions = false;
00557       _generating_world = false;
00558     } else {
00559       success = DoCommandP(tile, (InteractiveRandomRange(indsp->num_table) << 8) | this->selected_type, seed, CMD_BUILD_INDUSTRY | CMD_MSG(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY));
00560     }
00561 
00562     /* If an industry has been built, just reset the cursor and the system */
00563     if (success && !_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
00564   }
00565 
00566   virtual void OnTick()
00567   {
00568     if (_pause_mode != PM_UNPAUSED) return;
00569     if (!this->timer_enabled) return;
00570     if (--this->callback_timer == 0) {
00571       /* We have just passed another day.
00572        * See if we need to update availability of currently selected industry */
00573       this->callback_timer = DAY_TICKS; // restart counter
00574 
00575       const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
00576 
00577       if (indsp->enabled) {
00578         bool call_back_result = GetIndustryProbabilityCallback(this->selected_type, IACT_USERCREATION, 1) > 0;
00579 
00580         /* Only if result does match the previous state would it require a redraw. */
00581         if (call_back_result != this->enabled[this->selected_index]) {
00582           this->enabled[this->selected_index] = call_back_result;
00583           this->SetButtons();
00584           this->SetDirty();
00585         }
00586       }
00587     }
00588   }
00589 
00590   virtual void OnTimeout()
00591   {
00592     this->RaiseButtons();
00593   }
00594 
00595   virtual void OnPlaceObjectAbort()
00596   {
00597     this->RaiseButtons();
00598   }
00599 
00605   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
00606   {
00607     if (!gui_scope) return;
00608     this->SetupArrays();
00609 
00610     const IndustrySpec *indsp = (this->selected_type == INVALID_INDUSTRYTYPE) ? NULL : GetIndustrySpec(this->selected_type);
00611     if (indsp == NULL) this->enabled[this->selected_index] = _settings_game.difficulty.industry_density != ID_FUND_ONLY;
00612     this->SetButtons();
00613   }
00614 };
00615 
00616 void ShowBuildIndustryWindow()
00617 {
00618   if (_game_mode != GM_EDITOR && !Company::IsValidID(_local_company)) return;
00619   if (BringWindowToFrontById(WC_BUILD_INDUSTRY, 0)) return;
00620   new BuildIndustryWindow();
00621 }
00622 
00623 static void UpdateIndustryProduction(Industry *i);
00624 
00625 static inline bool IsProductionAlterable(const Industry *i)
00626 {
00627   const IndustrySpec *is = GetIndustrySpec(i->type);
00628   return ((_game_mode == GM_EDITOR || _cheats.setup_prod.value) &&
00629       (is->production_rate[0] != 0 || is->production_rate[1] != 0 || is->IsRawIndustry()));
00630 }
00631 
00632 class IndustryViewWindow : public Window
00633 {
00635   enum Editability {
00636     EA_NONE,              
00637     EA_MULTIPLIER,        
00638     EA_RATE,              
00639   };
00640 
00642   enum InfoLine {
00643     IL_NONE,              
00644     IL_MULTIPLIER,        
00645     IL_RATE1,             
00646     IL_RATE2,             
00647   };
00648 
00649   Editability editable;     
00650   InfoLine editbox_line;    
00651   InfoLine clicked_line;    
00652   byte clicked_button;      
00653   int production_offset_y;  
00654   int info_height;          
00655 
00656 public:
00657   IndustryViewWindow(const WindowDesc *desc, WindowNumber window_number) : Window()
00658   {
00659     this->flags |= WF_DISABLE_VP_SCROLL;
00660     this->editbox_line = IL_NONE;
00661     this->clicked_line = IL_NONE;
00662     this->clicked_button = 0;
00663     this->info_height = WD_FRAMERECT_TOP + 2 * FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM + 1; // Info panel has at least two lines text.
00664 
00665     this->InitNested(desc, window_number);
00666     NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_IV_VIEWPORT);
00667     nvp->InitializeViewport(this, Industry::Get(window_number)->location.GetCenterTile(), ZOOM_LVL_INDUSTRY);
00668 
00669     this->InvalidateData();
00670   }
00671 
00672   virtual void OnPaint()
00673   {
00674     this->DrawWidgets();
00675 
00676     if (this->IsShaded()) return; // Don't draw anything when the window is shaded.
00677 
00678     NWidgetBase *nwi = this->GetWidget<NWidgetBase>(WID_IV_INFO);
00679     uint expected = this->DrawInfo(nwi->pos_x, nwi->pos_x + nwi->current_x - 1, nwi->pos_y) - nwi->pos_y;
00680     if (expected > nwi->current_y - 1) {
00681       this->info_height = expected + 1;
00682       this->ReInit();
00683       return;
00684     }
00685   }
00686 
00694   int DrawInfo(uint left, uint right, uint top)
00695   {
00696     Industry *i = Industry::Get(this->window_number);
00697     const IndustrySpec *ind = GetIndustrySpec(i->type);
00698     int y = top + WD_FRAMERECT_TOP;
00699     bool first = true;
00700     bool has_accept = false;
00701     char cargo_suffix[3][512];
00702 
00703     if (i->prod_level == PRODLEVEL_CLOSURE) {
00704       DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_INDUSTRY_ANNOUNCED_CLOSURE);
00705       y += 2 * FONT_HEIGHT_NORMAL;
00706     }
00707 
00708     if (HasBit(ind->callback_mask, CBM_IND_PRODUCTION_CARGO_ARRIVAL) || HasBit(ind->callback_mask, CBM_IND_PRODUCTION_256_TICKS)) {
00709       GetAllCargoSuffixes(0, CST_VIEW, i, i->type, ind, i->accepts_cargo, cargo_suffix);
00710       for (byte j = 0; j < lengthof(i->accepts_cargo); j++) {
00711         if (i->accepts_cargo[j] == CT_INVALID) continue;
00712         has_accept = true;
00713         if (first) {
00714           DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_WAITING_FOR_PROCESSING);
00715           y += FONT_HEIGHT_NORMAL;
00716           first = false;
00717         }
00718         SetDParam(0, i->accepts_cargo[j]);
00719         SetDParam(1, i->incoming_cargo_waiting[j]);
00720         SetDParamStr(2, cargo_suffix[j]);
00721         DrawString(left + WD_FRAMETEXT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_WAITING_STOCKPILE_CARGO);
00722         y += FONT_HEIGHT_NORMAL;
00723       }
00724     } else {
00725       GetAllCargoSuffixes(0, CST_VIEW, i, i->type, ind, i->accepts_cargo, cargo_suffix);
00726       StringID str = STR_INDUSTRY_VIEW_REQUIRES_CARGO;
00727       byte p = 0;
00728       for (byte j = 0; j < lengthof(i->accepts_cargo); j++) {
00729         if (i->accepts_cargo[j] == CT_INVALID) continue;
00730         has_accept = true;
00731         if (p > 0) str++;
00732         SetDParam(p++, CargoSpec::Get(i->accepts_cargo[j])->name);
00733         SetDParamStr(p++, cargo_suffix[j]);
00734       }
00735       if (has_accept) {
00736         DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, str);
00737         y += FONT_HEIGHT_NORMAL;
00738       }
00739     }
00740 
00741     GetAllCargoSuffixes(3, CST_VIEW, i, i->type, ind, i->produced_cargo, cargo_suffix);
00742     first = true;
00743     for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
00744       if (i->produced_cargo[j] == CT_INVALID) continue;
00745       if (first) {
00746         if (has_accept) y += WD_PAR_VSEP_WIDE;
00747         DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_PRODUCTION_LAST_MONTH_TITLE);
00748         y += FONT_HEIGHT_NORMAL;
00749         if (this->editable == EA_RATE) this->production_offset_y = y;
00750         first = false;
00751       }
00752 
00753       SetDParam(0, i->produced_cargo[j]);
00754       SetDParam(1, i->last_month_production[j]);
00755       SetDParamStr(2, cargo_suffix[j]);
00756       SetDParam(3, ToPercent8(i->last_month_pct_transported[j]));
00757       uint x = left + WD_FRAMETEXT_LEFT + (this->editable == EA_RATE ? SETTING_BUTTON_WIDTH + 10 : 0);
00758       DrawString(x, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_TRANSPORTED);
00759       /* Let's put out those buttons.. */
00760       if (this->editable == EA_RATE) {
00761         DrawArrowButtons(left + WD_FRAMETEXT_LEFT, y, COLOUR_YELLOW, (this->clicked_line == IL_RATE1 + j) ? this->clicked_button : 0,
00762             i->production_rate[j] > 0, i->production_rate[j] < 255);
00763       }
00764       y += FONT_HEIGHT_NORMAL;
00765     }
00766 
00767     /* Display production multiplier if editable */
00768     if (this->editable == EA_MULTIPLIER) {
00769       y += WD_PAR_VSEP_WIDE;
00770       this->production_offset_y = y;
00771       SetDParam(0, RoundDivSU(i->prod_level * 100, PRODLEVEL_DEFAULT));
00772       uint x = left + WD_FRAMETEXT_LEFT + SETTING_BUTTON_WIDTH + 10;
00773       DrawString(x, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_PRODUCTION_LEVEL);
00774       DrawArrowButtons(left + WD_FRAMETEXT_LEFT, y, COLOUR_YELLOW, (this->clicked_line == IL_MULTIPLIER) ? this->clicked_button : 0,
00775           i->prod_level > PRODLEVEL_MINIMUM, i->prod_level < PRODLEVEL_MAXIMUM);
00776       y += FONT_HEIGHT_NORMAL;
00777     }
00778 
00779     /* Get the extra message for the GUI */
00780     if (HasBit(ind->callback_mask, CBM_IND_WINDOW_MORE_TEXT)) {
00781       uint16 callback_res = GetIndustryCallback(CBID_INDUSTRY_WINDOW_MORE_TEXT, 0, 0, i, i->type, i->location.tile);
00782       if (callback_res != CALLBACK_FAILED && callback_res != 0x400) {
00783         if (callback_res > 0x400) {
00784           ErrorUnknownCallbackResult(ind->grf_prop.grffile->grfid, CBID_INDUSTRY_WINDOW_MORE_TEXT, callback_res);
00785         } else {
00786           StringID message = GetGRFStringID(ind->grf_prop.grffile->grfid, 0xD000 + callback_res);
00787           if (message != STR_NULL && message != STR_UNDEFINED) {
00788             y += WD_PAR_VSEP_WIDE;
00789 
00790             StartTextRefStackUsage(6);
00791             /* Use all the available space left from where we stand up to the
00792              * end of the window. We ALSO enlarge the window if needed, so we
00793              * can 'go' wild with the bottom of the window. */
00794             y = DrawStringMultiLine(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, UINT16_MAX, message, TC_BLACK);
00795             StopTextRefStackUsage();
00796           }
00797         }
00798       }
00799     }
00800     return y + WD_FRAMERECT_BOTTOM;
00801   }
00802 
00803   virtual void SetStringParameters(int widget) const
00804   {
00805     if (widget == WID_IV_CAPTION) SetDParam(0, this->window_number);
00806   }
00807 
00808   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00809   {
00810     if (widget == WID_IV_INFO) size->height = this->info_height;
00811   }
00812 
00813   virtual void OnClick(Point pt, int widget, int click_count)
00814   {
00815     switch (widget) {
00816       case WID_IV_INFO: {
00817         Industry *i = Industry::Get(this->window_number);
00818         InfoLine line = IL_NONE;
00819 
00820         switch (this->editable) {
00821           case EA_NONE: break;
00822 
00823           case EA_MULTIPLIER:
00824             if (IsInsideBS(pt.y, this->production_offset_y, FONT_HEIGHT_NORMAL)) line = IL_MULTIPLIER;
00825             break;
00826 
00827           case EA_RATE:
00828             if (pt.y >= this->production_offset_y) {
00829               int row = (pt.y - this->production_offset_y) / FONT_HEIGHT_NORMAL;
00830               for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
00831                 if (i->produced_cargo[j] == CT_INVALID) continue;
00832                 row--;
00833                 if (row < 0) {
00834                   line = (InfoLine)(IL_RATE1 + j);
00835                   break;
00836                 }
00837               }
00838             }
00839             break;
00840         }
00841         if (line == IL_NONE) return;
00842 
00843         NWidgetBase *nwi = this->GetWidget<NWidgetBase>(widget);
00844         int left = nwi->pos_x + WD_FRAMETEXT_LEFT;
00845         int right = nwi->pos_x + nwi->current_x - 1 - WD_FRAMERECT_RIGHT;
00846         if (IsInsideMM(pt.x, left, left + SETTING_BUTTON_WIDTH)) {
00847           /* Clicked buttons, decrease or increase production */
00848           byte button = (pt.x < left + SETTING_BUTTON_WIDTH / 2) ? 1 : 2;
00849           switch (this->editable) {
00850             case EA_MULTIPLIER:
00851               if (button == 1) {
00852                 if (i->prod_level <= PRODLEVEL_MINIMUM) return;
00853                 i->prod_level = max<uint>(i->prod_level / 2, PRODLEVEL_MINIMUM);
00854               } else {
00855                 if (i->prod_level >= PRODLEVEL_MAXIMUM) return;
00856                 i->prod_level = minu(i->prod_level * 2, PRODLEVEL_MAXIMUM);
00857               }
00858               break;
00859 
00860             case EA_RATE:
00861               if (button == 1) {
00862                 if (i->production_rate[line - IL_RATE1] <= 0) return;
00863                 i->production_rate[line - IL_RATE1] = max(i->production_rate[line - IL_RATE1] / 2, 0);
00864               } else {
00865                 if (i->production_rate[line - IL_RATE1] >= 255) return;
00866                 /* a zero production industry is unlikely to give anything but zero, so push it a little bit */
00867                 int new_prod = i->production_rate[line - IL_RATE1] == 0 ? 1 : i->production_rate[line - IL_RATE1] * 2;
00868                 i->production_rate[line - IL_RATE1] = minu(new_prod, 255);
00869               }
00870               break;
00871 
00872             default: NOT_REACHED();
00873           }
00874 
00875           UpdateIndustryProduction(i);
00876           this->SetDirty();
00877           this->SetTimeout();
00878           this->clicked_line = line;
00879           this->clicked_button = button;
00880         } else if (IsInsideMM(pt.x, left + SETTING_BUTTON_WIDTH + 10, right)) {
00881           /* clicked the text */
00882           this->editbox_line = line;
00883           switch (this->editable) {
00884             case EA_MULTIPLIER:
00885               SetDParam(0, RoundDivSU(i->prod_level * 100, PRODLEVEL_DEFAULT));
00886               ShowQueryString(STR_JUST_INT, STR_CONFIG_GAME_PRODUCTION_LEVEL, 10, this, CS_ALPHANUMERAL, QSF_NONE);
00887               break;
00888 
00889             case EA_RATE:
00890               SetDParam(0, i->production_rate[line - IL_RATE1] * 8);
00891               ShowQueryString(STR_JUST_INT, STR_CONFIG_GAME_PRODUCTION, 10, this, CS_ALPHANUMERAL, QSF_NONE);
00892               break;
00893 
00894             default: NOT_REACHED();
00895           }
00896         }
00897         break;
00898       }
00899 
00900       case WID_IV_GOTO: {
00901         Industry *i = Industry::Get(this->window_number);
00902         if (_ctrl_pressed) {
00903           ShowExtraViewPortWindow(i->location.GetCenterTile());
00904         } else {
00905           ScrollMainWindowToTile(i->location.GetCenterTile());
00906         }
00907         break;
00908       }
00909 
00910       case WID_IV_DISPLAY: {
00911         Industry *i = Industry::Get(this->window_number);
00912         ShowIndustryCargoesWindow(i->type);
00913         break;
00914       }
00915     }
00916   }
00917 
00918   virtual void OnTimeout()
00919   {
00920     this->clicked_line = IL_NONE;
00921     this->clicked_button = 0;
00922     this->SetDirty();
00923   }
00924 
00925   virtual void OnResize()
00926   {
00927     if (this->viewport != NULL) {
00928       NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(WID_IV_VIEWPORT);
00929       nvp->UpdateViewportCoordinates(this);
00930 
00931       ScrollWindowToTile(Industry::Get(this->window_number)->location.GetCenterTile(), this, true); // Re-center viewport.
00932     }
00933   }
00934 
00935   virtual void OnQueryTextFinished(char *str)
00936   {
00937     if (StrEmpty(str)) return;
00938 
00939     Industry *i = Industry::Get(this->window_number);
00940     uint value = atoi(str);
00941     switch (this->editbox_line) {
00942       case IL_NONE: NOT_REACHED();
00943 
00944       case IL_MULTIPLIER:
00945         i->prod_level = ClampU(RoundDivSU(value * PRODLEVEL_DEFAULT, 100), PRODLEVEL_MINIMUM, PRODLEVEL_MAXIMUM);
00946         break;
00947 
00948       default:
00949         i->production_rate[this->editbox_line - IL_RATE1] = ClampU(RoundDivSU(value, 8), 0, 255);
00950         break;
00951     }
00952     UpdateIndustryProduction(i);
00953     this->SetDirty();
00954   }
00955 
00961   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
00962   {
00963     if (!gui_scope) return;
00964     const Industry *i = Industry::Get(this->window_number);
00965     if (IsProductionAlterable(i)) {
00966       const IndustrySpec *ind = GetIndustrySpec(i->type);
00967       this->editable = ind->UsesSmoothEconomy() ? EA_RATE : EA_MULTIPLIER;
00968     } else {
00969       this->editable = EA_NONE;
00970     }
00971   }
00972 
00973   virtual bool IsNewGRFInspectable() const
00974   {
00975     return ::IsNewGRFInspectable(GSF_INDUSTRIES, this->window_number);
00976   }
00977 
00978   virtual void ShowNewGRFInspectWindow() const
00979   {
00980 		::ShowNewGRFInspectWindow(GSF_INDUSTRIES, this->window_number);
00981   }
00982 };
00983 
00984 static void UpdateIndustryProduction(Industry *i)
00985 {
00986   const IndustrySpec *indspec = GetIndustrySpec(i->type);
00987   if (!indspec->UsesSmoothEconomy()) i->RecomputeProductionMultipliers();
00988 
00989   for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
00990     if (i->produced_cargo[j] != CT_INVALID) {
00991       i->last_month_production[j] = 8 * i->production_rate[j];
00992     }
00993   }
00994 }
00995 
00997 static const NWidgetPart _nested_industry_view_widgets[] = {
00998   NWidget(NWID_HORIZONTAL),
00999     NWidget(WWT_CLOSEBOX, COLOUR_CREAM),
01000     NWidget(WWT_CAPTION, COLOUR_CREAM, WID_IV_CAPTION), SetDataTip(STR_INDUSTRY_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
01001     NWidget(WWT_DEBUGBOX, COLOUR_CREAM),
01002     NWidget(WWT_SHADEBOX, COLOUR_CREAM),
01003     NWidget(WWT_STICKYBOX, COLOUR_CREAM),
01004   EndContainer(),
01005   NWidget(WWT_PANEL, COLOUR_CREAM),
01006     NWidget(WWT_INSET, COLOUR_CREAM), SetPadding(2, 2, 2, 2),
01007       NWidget(NWID_VIEWPORT, INVALID_COLOUR, WID_IV_VIEWPORT), SetMinimalSize(254, 86), SetFill(1, 0), SetPadding(1, 1, 1, 1), SetResize(1, 1),
01008     EndContainer(),
01009   EndContainer(),
01010   NWidget(WWT_PANEL, COLOUR_CREAM, WID_IV_INFO), SetMinimalSize(260, 2), SetResize(1, 0),
01011   EndContainer(),
01012   NWidget(NWID_HORIZONTAL),
01013     NWidget(WWT_PUSHTXTBTN, COLOUR_CREAM, WID_IV_GOTO), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_BUTTON_LOCATION, STR_INDUSTRY_VIEW_LOCATION_TOOLTIP),
01014     NWidget(WWT_PUSHTXTBTN, COLOUR_CREAM, WID_IV_DISPLAY), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_INDUSTRY_DISPLAY_CHAIN, STR_INDUSTRY_DISPLAY_CHAIN_TOOLTIP),
01015     NWidget(WWT_RESIZEBOX, COLOUR_CREAM),
01016   EndContainer(),
01017 };
01018 
01020 static const WindowDesc _industry_view_desc(
01021   WDP_AUTO, 260, 120,
01022   WC_INDUSTRY_VIEW, WC_NONE,
01023   0,
01024   _nested_industry_view_widgets, lengthof(_nested_industry_view_widgets)
01025 );
01026 
01027 void ShowIndustryViewWindow(int industry)
01028 {
01029   AllocateWindowDescFront<IndustryViewWindow>(&_industry_view_desc, industry);
01030 }
01031 
01033 static const NWidgetPart _nested_industry_directory_widgets[] = {
01034   NWidget(NWID_HORIZONTAL),
01035     NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
01036     NWidget(WWT_CAPTION, COLOUR_BROWN), SetDataTip(STR_INDUSTRY_DIRECTORY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
01037     NWidget(WWT_SHADEBOX, COLOUR_BROWN),
01038     NWidget(WWT_STICKYBOX, COLOUR_BROWN),
01039   EndContainer(),
01040   NWidget(NWID_HORIZONTAL),
01041     NWidget(NWID_VERTICAL),
01042       NWidget(NWID_HORIZONTAL),
01043         NWidget(WWT_TEXTBTN, COLOUR_BROWN, WID_ID_DROPDOWN_ORDER), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
01044         NWidget(WWT_DROPDOWN, COLOUR_BROWN, WID_ID_DROPDOWN_CRITERIA), SetDataTip(STR_JUST_STRING, STR_TOOLTIP_SORT_CRITERIA),
01045         NWidget(WWT_PANEL, COLOUR_BROWN), SetResize(1, 0), EndContainer(),
01046       EndContainer(),
01047       NWidget(WWT_PANEL, COLOUR_BROWN, WID_ID_INDUSTRY_LIST), SetDataTip(0x0, STR_INDUSTRY_DIRECTORY_LIST_CAPTION), SetResize(1, 1), SetScrollbar(WID_ID_SCROLLBAR), EndContainer(),
01048     EndContainer(),
01049     NWidget(NWID_VERTICAL),
01050       NWidget(NWID_VSCROLLBAR, COLOUR_BROWN, WID_ID_SCROLLBAR),
01051       NWidget(WWT_RESIZEBOX, COLOUR_BROWN),
01052     EndContainer(),
01053   EndContainer(),
01054 };
01055 
01056 typedef GUIList<const Industry*> GUIIndustryList;
01057 
01058 
01062 class IndustryDirectoryWindow : public Window {
01063 protected:
01064   /* Runtime saved values */
01065   static Listing last_sorting;
01066   static const Industry *last_industry;
01067 
01068   /* Constants for sorting stations */
01069   static const StringID sorter_names[];
01070   static GUIIndustryList::SortFunction * const sorter_funcs[];
01071 
01072   GUIIndustryList industries;
01073   Scrollbar *vscroll;
01074 
01076   void BuildSortIndustriesList()
01077   {
01078     if (this->industries.NeedRebuild()) {
01079       this->industries.Clear();
01080 
01081       const Industry *i;
01082       FOR_ALL_INDUSTRIES(i) {
01083         *this->industries.Append() = i;
01084       }
01085 
01086       this->industries.Compact();
01087       this->industries.RebuildDone();
01088       this->vscroll->SetCount(this->industries.Length()); // Update scrollbar as well.
01089     }
01090 
01091     if (!this->industries.Sort()) return;
01092     IndustryDirectoryWindow::last_industry = NULL; // Reset name sorter sort cache
01093     this->SetWidgetDirty(WID_ID_INDUSTRY_LIST); // Set the modified widget dirty
01094   }
01095 
01103   static inline int GetCargoTransportedPercentsIfValid(const Industry *i, uint id)
01104   {
01105     assert(id < lengthof(i->produced_cargo));
01106 
01107     if (i->produced_cargo[id] == CT_INVALID) return 101;
01108     return ToPercent8(i->last_month_pct_transported[id]);
01109   }
01110 
01118   static int GetCargoTransportedSortValue(const Industry *i)
01119   {
01120     int p1 = GetCargoTransportedPercentsIfValid(i, 0);
01121     int p2 = GetCargoTransportedPercentsIfValid(i, 1);
01122 
01123     if (p1 > p2) Swap(p1, p2); // lower value has higher priority
01124 
01125     return (p1 << 8) + p2;
01126   }
01127 
01129   static int CDECL IndustryNameSorter(const Industry * const *a, const Industry * const *b)
01130   {
01131     static char buf_cache[96];
01132     static char buf[96];
01133 
01134     SetDParam(0, (*a)->index);
01135     GetString(buf, STR_INDUSTRY_NAME, lastof(buf));
01136 
01137     if (*b != last_industry) {
01138       last_industry = *b;
01139       SetDParam(0, (*b)->index);
01140       GetString(buf_cache, STR_INDUSTRY_NAME, lastof(buf_cache));
01141     }
01142 
01143     return strnatcmp(buf, buf_cache); // Sort by name (natural sorting).
01144   }
01145 
01147   static int CDECL IndustryTypeSorter(const Industry * const *a, const Industry * const *b)
01148   {
01149     int it_a = 0;
01150     while (it_a != NUM_INDUSTRYTYPES && (*a)->type != _sorted_industry_types[it_a]) it_a++;
01151     int it_b = 0;
01152     while (it_b != NUM_INDUSTRYTYPES && (*b)->type != _sorted_industry_types[it_b]) it_b++;
01153     int r = it_a - it_b;
01154     return (r == 0) ? IndustryNameSorter(a, b) : r;
01155   }
01156 
01158   static int CDECL IndustryProductionSorter(const Industry * const *a, const Industry * const *b)
01159   {
01160     uint prod_a = 0, prod_b = 0;
01161     for (uint i = 0; i < lengthof((*a)->produced_cargo); i++) {
01162       if ((*a)->produced_cargo[i] != CT_INVALID) prod_a += (*a)->last_month_production[i];
01163       if ((*b)->produced_cargo[i] != CT_INVALID) prod_b += (*b)->last_month_production[i];
01164     }
01165     int r = prod_a - prod_b;
01166 
01167     return (r == 0) ? IndustryTypeSorter(a, b) : r;
01168   }
01169 
01171   static int CDECL IndustryTransportedCargoSorter(const Industry * const *a, const Industry * const *b)
01172   {
01173     int r = GetCargoTransportedSortValue(*a) - GetCargoTransportedSortValue(*b);
01174     return (r == 0) ? IndustryNameSorter(a, b) : r;
01175   }
01176 
01182   StringID GetIndustryString(const Industry *i) const
01183   {
01184     const IndustrySpec *indsp = GetIndustrySpec(i->type);
01185     byte p = 0;
01186 
01187     /* Industry name */
01188     SetDParam(p++, i->index);
01189 
01190     static char cargo_suffix[lengthof(i->produced_cargo)][512];
01191     GetAllCargoSuffixes(3, CST_DIR, i, i->type, indsp, i->produced_cargo, cargo_suffix);
01192 
01193     /* Industry productions */
01194     for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
01195       if (i->produced_cargo[j] == CT_INVALID) continue;
01196       SetDParam(p++, i->produced_cargo[j]);
01197       SetDParam(p++, i->last_month_production[j]);
01198       SetDParamStr(p++, cargo_suffix[j]);
01199     }
01200 
01201     /* Transported productions */
01202     for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
01203       if (i->produced_cargo[j] == CT_INVALID) continue;
01204       SetDParam(p++, ToPercent8(i->last_month_pct_transported[j]));
01205     }
01206 
01207     /* Drawing the right string */
01208     switch (p) {
01209       case 1:  return STR_INDUSTRY_DIRECTORY_ITEM_NOPROD;
01210       case 5:  return STR_INDUSTRY_DIRECTORY_ITEM;
01211       default: return STR_INDUSTRY_DIRECTORY_ITEM_TWO;
01212     }
01213   }
01214 
01215 public:
01216   IndustryDirectoryWindow(const WindowDesc *desc, WindowNumber number) : Window()
01217   {
01218     this->CreateNestedTree(desc);
01219     this->vscroll = this->GetScrollbar(WID_ID_SCROLLBAR);
01220 
01221     this->industries.SetListing(this->last_sorting);
01222     this->industries.SetSortFuncs(IndustryDirectoryWindow::sorter_funcs);
01223     this->industries.ForceRebuild();
01224     this->BuildSortIndustriesList();
01225 
01226     this->FinishInitNested(desc, 0);
01227   }
01228 
01229   ~IndustryDirectoryWindow()
01230   {
01231     this->last_sorting = this->industries.GetListing();
01232   }
01233 
01234   virtual void SetStringParameters(int widget) const
01235   {
01236     if (widget == WID_ID_DROPDOWN_CRITERIA) SetDParam(0, IndustryDirectoryWindow::sorter_names[this->industries.SortType()]);
01237   }
01238 
01239   virtual void DrawWidget(const Rect &r, int widget) const
01240   {
01241     switch (widget) {
01242       case WID_ID_DROPDOWN_ORDER:
01243         this->DrawSortButtonState(widget, this->industries.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
01244         break;
01245 
01246       case WID_ID_INDUSTRY_LIST: {
01247         int n = 0;
01248         int y = r.top + WD_FRAMERECT_TOP;
01249         if (this->industries.Length() == 0) {
01250           DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_DIRECTORY_NONE);
01251           break;
01252         }
01253         for (uint i = this->vscroll->GetPosition(); i < this->industries.Length(); i++) {
01254           DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, this->GetIndustryString(this->industries[i]));
01255 
01256           y += this->resize.step_height;
01257           if (++n == this->vscroll->GetCapacity()) break; // max number of industries in 1 window
01258         }
01259         break;
01260       }
01261     }
01262   }
01263 
01264   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01265   {
01266     switch (widget) {
01267       case WID_ID_DROPDOWN_ORDER: {
01268         Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
01269         d.width += padding.width + WD_SORTBUTTON_ARROW_WIDTH * 2; // Doubled since the string is centred and it also looks better.
01270         d.height += padding.height;
01271         *size = maxdim(*size, d);
01272         break;
01273       }
01274 
01275       case WID_ID_DROPDOWN_CRITERIA: {
01276         Dimension d = {0, 0};
01277         for (uint i = 0; IndustryDirectoryWindow::sorter_names[i] != INVALID_STRING_ID; i++) {
01278           d = maxdim(d, GetStringBoundingBox(IndustryDirectoryWindow::sorter_names[i]));
01279         }
01280         d.width += padding.width;
01281         d.height += padding.height;
01282         *size = maxdim(*size, d);
01283         break;
01284       }
01285 
01286       case WID_ID_INDUSTRY_LIST: {
01287         Dimension d = GetStringBoundingBox(STR_INDUSTRY_DIRECTORY_NONE);
01288         for (uint i = 0; i < this->industries.Length(); i++) {
01289           d = maxdim(d, GetStringBoundingBox(this->GetIndustryString(this->industries[i])));
01290         }
01291         resize->height = d.height;
01292         d.height *= 5;
01293         d.width += padding.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
01294         d.height += padding.height + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
01295         *size = maxdim(*size, d);
01296         break;
01297       }
01298     }
01299   }
01300 
01301 
01302   virtual void OnClick(Point pt, int widget, int click_count)
01303   {
01304     switch (widget) {
01305       case WID_ID_DROPDOWN_ORDER:
01306         this->industries.ToggleSortOrder();
01307         this->SetDirty();
01308         break;
01309 
01310       case WID_ID_DROPDOWN_CRITERIA:
01311         ShowDropDownMenu(this, IndustryDirectoryWindow::sorter_names, this->industries.SortType(), WID_ID_DROPDOWN_CRITERIA, 0, 0);
01312         break;
01313 
01314       case WID_ID_INDUSTRY_LIST: {
01315         uint p = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_ID_INDUSTRY_LIST, WD_FRAMERECT_TOP);
01316         if (p < this->industries.Length()) {
01317           if (_ctrl_pressed) {
01318             ShowExtraViewPortWindow(this->industries[p]->location.tile);
01319           } else {
01320             ScrollMainWindowToTile(this->industries[p]->location.tile);
01321           }
01322         }
01323         break;
01324       }
01325     }
01326   }
01327 
01328   virtual void OnDropdownSelect(int widget, int index)
01329   {
01330     if (this->industries.SortType() != index) {
01331       this->industries.SetSortType(index);
01332       this->BuildSortIndustriesList();
01333     }
01334   }
01335 
01336   virtual void OnResize()
01337   {
01338     this->vscroll->SetCapacityFromWidget(this, WID_ID_INDUSTRY_LIST);
01339   }
01340 
01341   virtual void OnPaint()
01342   {
01343     if (this->industries.NeedRebuild()) this->BuildSortIndustriesList();
01344     this->DrawWidgets();
01345   }
01346 
01347   virtual void OnHundredthTick()
01348   {
01349     this->industries.ForceResort();
01350     this->BuildSortIndustriesList();
01351   }
01352 
01358   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
01359   {
01360     if (data == 0) {
01361       /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
01362       this->industries.ForceRebuild();
01363     } else {
01364       this->industries.ForceResort();
01365     }
01366   }
01367 };
01368 
01369 Listing IndustryDirectoryWindow::last_sorting = {false, 0};
01370 const Industry *IndustryDirectoryWindow::last_industry = NULL;
01371 
01372 /* Available station sorting functions. */
01373 GUIIndustryList::SortFunction * const IndustryDirectoryWindow::sorter_funcs[] = {
01374   &IndustryNameSorter,
01375   &IndustryTypeSorter,
01376   &IndustryProductionSorter,
01377   &IndustryTransportedCargoSorter
01378 };
01379 
01380 /* Names of the sorting functions */
01381 const StringID IndustryDirectoryWindow::sorter_names[] = {
01382   STR_SORT_BY_NAME,
01383   STR_SORT_BY_TYPE,
01384   STR_SORT_BY_PRODUCTION,
01385   STR_SORT_BY_TRANSPORTED,
01386   INVALID_STRING_ID
01387 };
01388 
01389 
01391 static const WindowDesc _industry_directory_desc(
01392   WDP_AUTO, 428, 190,
01393   WC_INDUSTRY_DIRECTORY, WC_NONE,
01394   0,
01395   _nested_industry_directory_widgets, lengthof(_nested_industry_directory_widgets)
01396 );
01397 
01398 void ShowIndustryDirectory()
01399 {
01400   AllocateWindowDescFront<IndustryDirectoryWindow>(&_industry_directory_desc, 0);
01401 }
01402 
01404 static const NWidgetPart _nested_industry_cargoes_widgets[] = {
01405   NWidget(NWID_HORIZONTAL),
01406     NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
01407     NWidget(WWT_CAPTION, COLOUR_BROWN, WID_IC_CAPTION), SetDataTip(STR_INDUSTRY_CARGOES_INDUSTRY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
01408     NWidget(WWT_SHADEBOX, COLOUR_BROWN),
01409     NWidget(WWT_STICKYBOX, COLOUR_BROWN),
01410   EndContainer(),
01411   NWidget(NWID_HORIZONTAL),
01412     NWidget(NWID_VERTICAL),
01413       NWidget(WWT_PANEL, COLOUR_BROWN, WID_IC_PANEL), SetResize(1, 10), SetMinimalSize(200, 90), SetScrollbar(WID_IC_SCROLLBAR), EndContainer(),
01414       NWidget(NWID_HORIZONTAL),
01415         NWidget(WWT_TEXTBTN, COLOUR_BROWN, WID_IC_NOTIFY),
01416           SetDataTip(STR_INDUSTRY_CARGOES_NOTIFY_SMALLMAP, STR_INDUSTRY_CARGOES_NOTIFY_SMALLMAP_TOOLTIP),
01417         NWidget(WWT_PANEL, COLOUR_BROWN), SetFill(1, 0), SetResize(0, 0), EndContainer(),
01418         NWidget(WWT_DROPDOWN, COLOUR_BROWN, WID_IC_IND_DROPDOWN), SetFill(0, 0), SetResize(0, 0),
01419             SetDataTip(STR_INDUSTRY_CARGOES_SELECT_INDUSTRY, STR_INDUSTRY_CARGOES_SELECT_INDUSTRY_TOOLTIP),
01420         NWidget(WWT_DROPDOWN, COLOUR_BROWN, WID_IC_CARGO_DROPDOWN), SetFill(0, 0), SetResize(0, 0),
01421             SetDataTip(STR_INDUSTRY_CARGOES_SELECT_CARGO, STR_INDUSTRY_CARGOES_SELECT_CARGO_TOOLTIP),
01422       EndContainer(),
01423     EndContainer(),
01424     NWidget(NWID_VERTICAL),
01425       NWidget(NWID_VSCROLLBAR, COLOUR_BROWN, WID_IC_SCROLLBAR),
01426       NWidget(WWT_RESIZEBOX, COLOUR_BROWN),
01427     EndContainer(),
01428   EndContainer(),
01429 };
01430 
01432 static const WindowDesc _industry_cargoes_desc(
01433   WDP_AUTO, 300, 210,
01434   WC_INDUSTRY_CARGOES, WC_NONE,
01435   0,
01436   _nested_industry_cargoes_widgets, lengthof(_nested_industry_cargoes_widgets)
01437 );
01438 
01440 enum CargoesFieldType {
01441   CFT_EMPTY,       
01442   CFT_SMALL_EMPTY, 
01443   CFT_INDUSTRY,    
01444   CFT_CARGO,       
01445   CFT_CARGO_LABEL, 
01446   CFT_HEADER,      
01447 };
01448 
01449 static const uint MAX_CARGOES = 3; 
01450 
01452 struct CargoesField {
01453   static const int VERT_INTER_INDUSTRY_SPACE;
01454   static const int HOR_CARGO_BORDER_SPACE;
01455   static const int CARGO_STUB_WIDTH;
01456   static const int HOR_CARGO_WIDTH, HOR_CARGO_SPACE;
01457   static const int CARGO_FIELD_WIDTH;
01458   static const int VERT_CARGO_SPACE, VERT_CARGO_EDGE;
01459   static const int BLOB_DISTANCE, BLOB_WIDTH, BLOB_HEIGHT;
01460 
01461   static const int INDUSTRY_LINE_COLOUR;
01462   static const int CARGO_LINE_COLOUR;
01463 
01464   static int small_height, normal_height;
01465   static int industry_width;
01466 
01467   CargoesFieldType type; 
01468   union {
01469     struct {
01470       IndustryType ind_type;                 
01471       CargoID other_produced[MAX_CARGOES];   
01472       CargoID other_accepted[MAX_CARGOES];   
01473     } industry; 
01474     struct {
01475       CargoID vertical_cargoes[MAX_CARGOES]; 
01476       byte num_cargoes;                      
01477       CargoID supp_cargoes[MAX_CARGOES];     
01478       byte top_end;                          
01479       CargoID cust_cargoes[MAX_CARGOES];     
01480       byte bottom_end;                       
01481     } cargo; 
01482     struct {
01483       CargoID cargoes[MAX_CARGOES];          
01484       bool left_align;                       
01485     } cargo_label;   
01486     StringID header; 
01487   } u; // Data for each type.
01488 
01493   void MakeEmpty(CargoesFieldType type)
01494   {
01495     this->type = type;
01496   }
01497 
01503   void MakeIndustry(IndustryType ind_type)
01504   {
01505     this->type = CFT_INDUSTRY;
01506     this->u.industry.ind_type = ind_type;
01507     MemSetT(this->u.industry.other_accepted, INVALID_CARGO, MAX_CARGOES);
01508     MemSetT(this->u.industry.other_produced, INVALID_CARGO, MAX_CARGOES);
01509   }
01510 
01517   int ConnectCargo(CargoID cargo, bool producer)
01518   {
01519     assert(this->type == CFT_CARGO);
01520     if (cargo == INVALID_CARGO) return -1;
01521 
01522     /* Find the vertical cargo column carrying the cargo. */
01523     int column = -1;
01524     for (int i = 0; i < this->u.cargo.num_cargoes; i++) {
01525       if (cargo == this->u.cargo.vertical_cargoes[i]) {
01526         column = i;
01527         break;
01528       }
01529     }
01530     if (column < 0) return -1;
01531 
01532     if (producer) {
01533       assert(this->u.cargo.supp_cargoes[column] == INVALID_CARGO);
01534       this->u.cargo.supp_cargoes[column]  = column;
01535     } else {
01536       assert(this->u.cargo.cust_cargoes[column] == INVALID_CARGO);
01537       this->u.cargo.cust_cargoes[column] = column;
01538     }
01539     return column;
01540   }
01541 
01546   bool HasConnection()
01547   {
01548     assert(this->type == CFT_CARGO);
01549 
01550     for (uint i = 0; i < MAX_CARGOES; i++) {
01551       if (this->u.cargo.supp_cargoes[i] != INVALID_CARGO) return true;
01552       if (this->u.cargo.cust_cargoes[i] != INVALID_CARGO) return true;
01553     }
01554     return false;
01555   }
01556 
01566   void MakeCargo(const CargoID *cargoes, uint length, int count = -1, bool top_end = false, bool bottom_end = false)
01567   {
01568     this->type = CFT_CARGO;
01569     uint i;
01570     uint num = 0;
01571     for (i = 0; i < MAX_CARGOES && i < length; i++) {
01572       if (cargoes[i] != INVALID_CARGO) {
01573         this->u.cargo.vertical_cargoes[num] = cargoes[i];
01574         num++;
01575       }
01576     }
01577     this->u.cargo.num_cargoes = (count < 0) ? num : count;
01578     for (; num < MAX_CARGOES; num++) this->u.cargo.vertical_cargoes[num] = INVALID_CARGO;
01579     this->u.cargo.top_end = top_end;
01580     this->u.cargo.bottom_end = bottom_end;
01581     MemSetT(this->u.cargo.supp_cargoes, INVALID_CARGO, MAX_CARGOES);
01582     MemSetT(this->u.cargo.cust_cargoes, INVALID_CARGO, MAX_CARGOES);
01583   }
01584 
01591   void MakeCargoLabel(const CargoID *cargoes, uint length, bool left_align)
01592   {
01593     this->type = CFT_CARGO_LABEL;
01594     uint i;
01595     for (i = 0; i < MAX_CARGOES && i < length; i++) this->u.cargo_label.cargoes[i] = cargoes[i];
01596     for (; i < MAX_CARGOES; i++) this->u.cargo_label.cargoes[i] = INVALID_CARGO;
01597     this->u.cargo_label.left_align = left_align;
01598   }
01599 
01604   void MakeHeader(StringID textid)
01605   {
01606     this->type = CFT_HEADER;
01607     this->u.header = textid;
01608   }
01609 
01615   int GetCargoBase(int xpos) const
01616   {
01617     assert(this->type == CFT_CARGO);
01618 
01619     switch (this->u.cargo.num_cargoes) {
01620       case 0: return xpos + CARGO_FIELD_WIDTH / 2;
01621       case 1: return xpos + CARGO_FIELD_WIDTH / 2 - HOR_CARGO_WIDTH / 2;
01622       case 2: return xpos + CARGO_FIELD_WIDTH / 2 - HOR_CARGO_WIDTH - HOR_CARGO_SPACE / 2;
01623       case 3: return xpos + CARGO_FIELD_WIDTH / 2 - HOR_CARGO_WIDTH - HOR_CARGO_SPACE - HOR_CARGO_WIDTH / 2;
01624       default: NOT_REACHED();
01625     }
01626   }
01627 
01633   void Draw(int xpos, int ypos) const
01634   {
01635     switch (this->type) {
01636       case CFT_EMPTY:
01637       case CFT_SMALL_EMPTY:
01638         break;
01639 
01640       case CFT_HEADER:
01641         ypos += (small_height - FONT_HEIGHT_NORMAL) / 2;
01642         DrawString(xpos, xpos + industry_width, ypos, this->u.header, TC_WHITE, SA_HOR_CENTER);
01643         break;
01644 
01645       case CFT_INDUSTRY: {
01646         int ypos1 = ypos + VERT_INTER_INDUSTRY_SPACE / 2;
01647         int ypos2 = ypos + normal_height - 1 - VERT_INTER_INDUSTRY_SPACE / 2;
01648         int xpos2 = xpos + industry_width - 1;
01649         GfxDrawLine(xpos,  ypos1, xpos2, ypos1, INDUSTRY_LINE_COLOUR);
01650         GfxDrawLine(xpos,  ypos1, xpos,  ypos2, INDUSTRY_LINE_COLOUR);
01651         GfxDrawLine(xpos,  ypos2, xpos2, ypos2, INDUSTRY_LINE_COLOUR);
01652         GfxDrawLine(xpos2, ypos1, xpos2, ypos2, INDUSTRY_LINE_COLOUR);
01653         ypos += (normal_height - FONT_HEIGHT_NORMAL) / 2;
01654         if (this->u.industry.ind_type < NUM_INDUSTRYTYPES) {
01655           const IndustrySpec *indsp = GetIndustrySpec(this->u.industry.ind_type);
01656           SetDParam(0, indsp->name);
01657           DrawString(xpos, xpos2, ypos, STR_JUST_STRING, TC_WHITE, SA_HOR_CENTER);
01658 
01659           /* Draw the industry legend. */
01660           int blob_left, blob_right;
01661           if (_current_text_dir == TD_RTL) {
01662             blob_right = xpos2 - BLOB_DISTANCE;
01663             blob_left  = blob_right - BLOB_WIDTH;
01664           } else {
01665             blob_left  = xpos + BLOB_DISTANCE;
01666             blob_right = blob_left + BLOB_WIDTH;
01667           }
01668           GfxFillRect(blob_left,     ypos2 - BLOB_DISTANCE - BLOB_HEIGHT,     blob_right,     ypos2 - BLOB_DISTANCE,     PC_BLACK); // Border
01669           GfxFillRect(blob_left + 1, ypos2 - BLOB_DISTANCE - BLOB_HEIGHT + 1, blob_right - 1, ypos2 - BLOB_DISTANCE - 1, indsp->map_colour);
01670         } else {
01671           DrawString(xpos, xpos2, ypos, STR_INDUSTRY_CARGOES_HOUSES, TC_FROMSTRING, SA_HOR_CENTER);
01672         }
01673 
01674         /* Draw the other_produced/other_accepted cargoes. */
01675         const CargoID *other_right, *other_left;
01676         if (_current_text_dir == TD_RTL) {
01677           other_right = this->u.industry.other_accepted;
01678           other_left  = this->u.industry.other_produced;
01679         } else {
01680           other_right = this->u.industry.other_produced;
01681           other_left  = this->u.industry.other_accepted;
01682         }
01683         ypos1 += VERT_CARGO_EDGE;
01684         for (uint i = 0; i < MAX_CARGOES; i++) {
01685           if (other_right[i] != INVALID_CARGO) {
01686             const CargoSpec *csp = CargoSpec::Get(other_right[i]);
01687             int xp = xpos + industry_width + CARGO_STUB_WIDTH;
01688             DrawHorConnection(xpos + industry_width, xp - 1, ypos1, csp);
01689             GfxDrawLine(xp, ypos1, xp, ypos1 + FONT_HEIGHT_NORMAL - 1, CARGO_LINE_COLOUR);
01690           }
01691           if (other_left[i] != INVALID_CARGO) {
01692             const CargoSpec *csp = CargoSpec::Get(other_left[i]);
01693             int xp = xpos - CARGO_STUB_WIDTH;
01694             DrawHorConnection(xp + 1, xpos - 1, ypos1, csp);
01695             GfxDrawLine(xp, ypos1, xp, ypos1 + FONT_HEIGHT_NORMAL - 1, CARGO_LINE_COLOUR);
01696           }
01697           ypos1 += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
01698         }
01699         break;
01700       }
01701 
01702       case CFT_CARGO: {
01703         int cargo_base = this->GetCargoBase(xpos);
01704         int top = ypos + (this->u.cargo.top_end ? VERT_INTER_INDUSTRY_SPACE / 2 + 1 : 0);
01705         int bot = ypos - (this->u.cargo.bottom_end ? VERT_INTER_INDUSTRY_SPACE / 2 + 1 : 0) + normal_height - 1;
01706         int colpos = cargo_base;
01707         for (int i = 0; i < this->u.cargo.num_cargoes; i++) {
01708           if (this->u.cargo.top_end) GfxDrawLine(colpos, top - 1, colpos + HOR_CARGO_WIDTH - 1, top - 1, CARGO_LINE_COLOUR);
01709           if (this->u.cargo.bottom_end) GfxDrawLine(colpos, bot + 1, colpos + HOR_CARGO_WIDTH - 1, bot + 1, CARGO_LINE_COLOUR);
01710           GfxDrawLine(colpos, top, colpos, bot, CARGO_LINE_COLOUR);
01711           colpos++;
01712           const CargoSpec *csp = CargoSpec::Get(this->u.cargo.vertical_cargoes[i]);
01713           GfxFillRect(colpos, top, colpos + HOR_CARGO_WIDTH - 2, bot, csp->legend_colour, FILLRECT_OPAQUE);
01714           colpos += HOR_CARGO_WIDTH - 2;
01715           GfxDrawLine(colpos, top, colpos, bot, CARGO_LINE_COLOUR);
01716           colpos += 1 + HOR_CARGO_SPACE;
01717         }
01718 
01719         const CargoID *hor_left, *hor_right;
01720         if (_current_text_dir == TD_RTL) {
01721           hor_left  = this->u.cargo.cust_cargoes;
01722           hor_right = this->u.cargo.supp_cargoes;
01723         } else {
01724           hor_left  = this->u.cargo.supp_cargoes;
01725           hor_right = this->u.cargo.cust_cargoes;
01726         }
01727         ypos += VERT_CARGO_EDGE + VERT_INTER_INDUSTRY_SPACE / 2;
01728         for (uint i = 0; i < MAX_CARGOES; i++) {
01729           if (hor_left[i] != INVALID_CARGO) {
01730             int col = hor_left[i];
01731             int dx = 0;
01732             const CargoSpec *csp = CargoSpec::Get(this->u.cargo.vertical_cargoes[col]);
01733             for (; col > 0; col--) {
01734               int lf = cargo_base + col * HOR_CARGO_WIDTH + (col - 1) * HOR_CARGO_SPACE;
01735               DrawHorConnection(lf, lf + HOR_CARGO_SPACE - dx, ypos, csp);
01736               dx = 1;
01737             }
01738             DrawHorConnection(xpos, cargo_base - dx, ypos, csp);
01739           }
01740           if (hor_right[i] != INVALID_CARGO) {
01741             int col = hor_right[i];
01742             int dx = 0;
01743             const CargoSpec *csp = CargoSpec::Get(this->u.cargo.vertical_cargoes[col]);
01744             for (; col < this->u.cargo.num_cargoes - 1; col++) {
01745               int lf = cargo_base + (col + 1) * HOR_CARGO_WIDTH + col * HOR_CARGO_SPACE;
01746               DrawHorConnection(lf + dx - 1, lf + HOR_CARGO_SPACE - 1, ypos, csp);
01747               dx = 1;
01748             }
01749             DrawHorConnection(cargo_base + col * HOR_CARGO_SPACE + (col + 1) * HOR_CARGO_WIDTH - 1 + dx, xpos + CARGO_FIELD_WIDTH - 1, ypos, csp);
01750           }
01751           ypos += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
01752         }
01753         break;
01754       }
01755 
01756       case CFT_CARGO_LABEL:
01757         ypos += VERT_CARGO_EDGE + VERT_INTER_INDUSTRY_SPACE / 2;
01758         for (uint i = 0; i < MAX_CARGOES; i++) {
01759           if (this->u.cargo_label.cargoes[i] != INVALID_CARGO) {
01760             const CargoSpec *csp = CargoSpec::Get(this->u.cargo_label.cargoes[i]);
01761             DrawString(xpos + WD_FRAMERECT_LEFT, xpos + industry_width - 1 - WD_FRAMERECT_RIGHT, ypos, csp->name, TC_WHITE,
01762                 (this->u.cargo_label.left_align) ? SA_LEFT : SA_RIGHT);
01763           }
01764           ypos += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
01765         }
01766         break;
01767 
01768       default:
01769         NOT_REACHED();
01770     }
01771   }
01772 
01780   CargoID CargoClickedAt(const CargoesField *left, const CargoesField *right, Point pt) const
01781   {
01782     assert(this->type == CFT_CARGO);
01783 
01784     /* Vertical matching. */
01785     int cpos = this->GetCargoBase(0);
01786     uint col;
01787     for (col = 0; col < this->u.cargo.num_cargoes; col++) {
01788       if (pt.x < cpos) break;
01789       if (pt.x < cpos + CargoesField::HOR_CARGO_WIDTH) return this->u.cargo.vertical_cargoes[col];
01790       cpos += CargoesField::HOR_CARGO_WIDTH + CargoesField::HOR_CARGO_SPACE;
01791     }
01792     /* col = 0 -> left of first col, 1 -> left of 2nd col, ... this->u.cargo.num_cargoes right of last-col. */
01793 
01794     int vpos = VERT_INTER_INDUSTRY_SPACE / 2 + VERT_CARGO_EDGE;
01795     uint row;
01796     for (row = 0; row < MAX_CARGOES; row++) {
01797       if (pt.y < vpos) return INVALID_CARGO;
01798       if (pt.y < vpos + FONT_HEIGHT_NORMAL) break;
01799       vpos += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
01800     }
01801     if (row == MAX_CARGOES) return INVALID_CARGO;
01802 
01803     /* row = 0 -> at first horizontal row, row = 1 -> second horizontal row, 2 = 3rd horizontal row. */
01804     if (col == 0) {
01805       if (this->u.cargo.supp_cargoes[row] != INVALID_CARGO) return this->u.cargo.vertical_cargoes[this->u.cargo.supp_cargoes[row]];
01806       if (left != NULL) {
01807         if (left->type == CFT_INDUSTRY) return left->u.industry.other_produced[row];
01808         if (left->type == CFT_CARGO_LABEL && !left->u.cargo_label.left_align) return left->u.cargo_label.cargoes[row];
01809       }
01810       return INVALID_CARGO;
01811     }
01812     if (col == this->u.cargo.num_cargoes) {
01813       if (this->u.cargo.cust_cargoes[row] != INVALID_CARGO) return this->u.cargo.vertical_cargoes[this->u.cargo.cust_cargoes[row]];
01814       if (right != NULL) {
01815         if (right->type == CFT_INDUSTRY) return right->u.industry.other_accepted[row];
01816         if (right->type == CFT_CARGO_LABEL && right->u.cargo_label.left_align) return right->u.cargo_label.cargoes[row];
01817       }
01818       return INVALID_CARGO;
01819     }
01820     if (row >= col) {
01821       /* Clicked somewhere in-between vertical cargo connection.
01822        * Since the horizontal connection is made in the same order as the vertical list, the above condition
01823        * ensures we are left-below the main diagonal, thus at the supplying side.
01824        */
01825       return (this->u.cargo.supp_cargoes[row] != INVALID_CARGO) ? this->u.cargo.vertical_cargoes[this->u.cargo.supp_cargoes[row]] : INVALID_CARGO;
01826     } else {
01827       /* Clicked at a customer connection. */
01828       return (this->u.cargo.cust_cargoes[row] != INVALID_CARGO) ? this->u.cargo.vertical_cargoes[this->u.cargo.cust_cargoes[row]] : INVALID_CARGO;
01829     }
01830   }
01831 
01837   CargoID CargoLabelClickedAt(Point pt) const
01838   {
01839     assert(this->type == CFT_CARGO_LABEL);
01840 
01841     int vpos = VERT_INTER_INDUSTRY_SPACE / 2 + VERT_CARGO_EDGE;
01842     uint row;
01843     for (row = 0; row < MAX_CARGOES; row++) {
01844       if (pt.y < vpos) return INVALID_CARGO;
01845       if (pt.y < vpos + FONT_HEIGHT_NORMAL) break;
01846       vpos += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
01847     }
01848     if (row == MAX_CARGOES) return INVALID_CARGO;
01849     return this->u.cargo_label.cargoes[row];
01850   }
01851 
01852 private:
01860   static void DrawHorConnection(int left, int right, int top, const CargoSpec *csp)
01861   {
01862     GfxDrawLine(left, top, right, top, CARGO_LINE_COLOUR);
01863     GfxFillRect(left, top + 1, right, top + FONT_HEIGHT_NORMAL - 2, csp->legend_colour, FILLRECT_OPAQUE);
01864     GfxDrawLine(left, top + FONT_HEIGHT_NORMAL - 1, right, top + FONT_HEIGHT_NORMAL - 1, CARGO_LINE_COLOUR);
01865   }
01866 };
01867 
01868 assert_compile(MAX_CARGOES >= cpp_lengthof(IndustrySpec, produced_cargo));
01869 assert_compile(MAX_CARGOES >= cpp_lengthof(IndustrySpec, accepts_cargo));
01870 
01871 int CargoesField::small_height;   
01872 int CargoesField::normal_height;  
01873 int CargoesField::industry_width; 
01874 const int CargoesField::VERT_INTER_INDUSTRY_SPACE = 6; 
01875 
01876 const int CargoesField::HOR_CARGO_BORDER_SPACE = 15; 
01877 const int CargoesField::CARGO_STUB_WIDTH       = 10; 
01878 const int CargoesField::HOR_CARGO_WIDTH        = 15; 
01879 const int CargoesField::HOR_CARGO_SPACE        =  5; 
01880 const int CargoesField::VERT_CARGO_EDGE        =  4; 
01881 const int CargoesField::VERT_CARGO_SPACE       =  4; 
01882 
01883 const int CargoesField::BLOB_DISTANCE =  5; 
01884 const int CargoesField::BLOB_WIDTH    = 12; 
01885 const int CargoesField::BLOB_HEIGHT   =  9; 
01886 
01888 const int CargoesField::CARGO_FIELD_WIDTH = HOR_CARGO_BORDER_SPACE * 2 + HOR_CARGO_WIDTH * MAX_CARGOES + HOR_CARGO_SPACE * (MAX_CARGOES - 1);
01889 
01890 const int CargoesField::INDUSTRY_LINE_COLOUR = PC_YELLOW; 
01891 const int CargoesField::CARGO_LINE_COLOUR    = PC_YELLOW; 
01892 
01894 struct CargoesRow {
01895   CargoesField columns[5]; 
01896 
01901   void ConnectIndustryProduced(int column)
01902   {
01903     CargoesField *ind_fld   = this->columns + column;
01904     CargoesField *cargo_fld = this->columns + column + 1;
01905     assert(ind_fld->type == CFT_INDUSTRY && cargo_fld->type == CFT_CARGO);
01906 
01907     MemSetT(ind_fld->u.industry.other_produced, INVALID_CARGO, MAX_CARGOES);
01908 
01909     if (ind_fld->u.industry.ind_type < NUM_INDUSTRYTYPES) {
01910       CargoID others[MAX_CARGOES]; // Produced cargoes not carried in the cargo column.
01911       int other_count = 0;
01912 
01913       const IndustrySpec *indsp = GetIndustrySpec(ind_fld->u.industry.ind_type);
01914       for (uint i = 0; i < lengthof(indsp->produced_cargo); i++) {
01915         int col = cargo_fld->ConnectCargo(indsp->produced_cargo[i], true);
01916         if (col < 0) others[other_count++] = indsp->produced_cargo[i];
01917       }
01918 
01919       /* Allocate other cargoes in the empty holes of the horizontal cargo connections. */
01920       for (uint i = 0; i < MAX_CARGOES && other_count > 0; i++) {
01921         if (cargo_fld->u.cargo.supp_cargoes[i] == INVALID_CARGO) ind_fld->u.industry.other_produced[i] = others[--other_count];
01922       }
01923     } else {
01924       /* Houses only display what is demanded. */
01925       for (uint i = 0; i < cargo_fld->u.cargo.num_cargoes; i++) {
01926         CargoID cid = cargo_fld->u.cargo.vertical_cargoes[i];
01927         if (cid == CT_PASSENGERS || cid == CT_MAIL) cargo_fld->ConnectCargo(cid, true);
01928       }
01929     }
01930   }
01931 
01937   void MakeCargoLabel(int column, bool accepting)
01938   {
01939     CargoID cargoes[MAX_CARGOES];
01940     MemSetT(cargoes, INVALID_CARGO, lengthof(cargoes));
01941 
01942     CargoesField *label_fld = this->columns + column;
01943     CargoesField *cargo_fld = this->columns + (accepting ? column - 1 : column + 1);
01944 
01945     assert(cargo_fld->type == CFT_CARGO && label_fld->type == CFT_EMPTY);
01946     for (uint i = 0; i < cargo_fld->u.cargo.num_cargoes; i++) {
01947       int col = cargo_fld->ConnectCargo(cargo_fld->u.cargo.vertical_cargoes[i], !accepting);
01948       cargoes[col] = cargo_fld->u.cargo.vertical_cargoes[i];
01949     }
01950     label_fld->MakeCargoLabel(cargoes, lengthof(cargoes), accepting);
01951   }
01952 
01953 
01958   void ConnectIndustryAccepted(int column)
01959   {
01960     CargoesField *ind_fld   = this->columns + column;
01961     CargoesField *cargo_fld = this->columns + column - 1;
01962     assert(ind_fld->type == CFT_INDUSTRY && cargo_fld->type == CFT_CARGO);
01963 
01964     MemSetT(ind_fld->u.industry.other_accepted, INVALID_CARGO, MAX_CARGOES);
01965 
01966     if (ind_fld->u.industry.ind_type < NUM_INDUSTRYTYPES) {
01967       CargoID others[MAX_CARGOES]; // Accepted cargoes not carried in the cargo column.
01968       int other_count = 0;
01969 
01970       const IndustrySpec *indsp = GetIndustrySpec(ind_fld->u.industry.ind_type);
01971       for (uint i = 0; i < lengthof(indsp->accepts_cargo); i++) {
01972         int col = cargo_fld->ConnectCargo(indsp->accepts_cargo[i], false);
01973         if (col < 0) others[other_count++] = indsp->accepts_cargo[i];
01974       }
01975 
01976       /* Allocate other cargoes in the empty holes of the horizontal cargo connections. */
01977       for (uint i = 0; i < MAX_CARGOES && other_count > 0; i++) {
01978         if (cargo_fld->u.cargo.cust_cargoes[i] == INVALID_CARGO) ind_fld->u.industry.other_accepted[i] = others[--other_count];
01979       }
01980     } else {
01981       /* Houses only display what is demanded. */
01982       for (uint i = 0; i < cargo_fld->u.cargo.num_cargoes; i++) {
01983         for (uint h = 0; h < HOUSE_MAX; h++) {
01984           HouseSpec *hs = HouseSpec::Get(h);
01985           if (!hs->enabled) continue;
01986 
01987           for (uint j = 0; j < lengthof(hs->accepts_cargo); j++) {
01988             if (cargo_fld->u.cargo.vertical_cargoes[i] == hs->accepts_cargo[j]) {
01989               cargo_fld->ConnectCargo(cargo_fld->u.cargo.vertical_cargoes[i], false);
01990               goto next_cargo;
01991             }
01992           }
01993         }
01994 next_cargo: ;
01995       }
01996     }
01997   }
01998 };
01999 
02000 
02028 struct IndustryCargoesWindow : public Window {
02029   static const int HOR_TEXT_PADDING, VERT_TEXT_PADDING;
02030 
02031   typedef SmallVector<CargoesRow, 4> Fields;
02032 
02033   Fields fields;  
02034   uint ind_cargo; 
02035   Dimension cargo_textsize; 
02036   Dimension ind_textsize;   
02037   Scrollbar *vscroll;
02038 
02039   IndustryCargoesWindow(int id) : Window()
02040   {
02041     this->OnInit();
02042     this->CreateNestedTree(&_industry_cargoes_desc);
02043     this->vscroll = this->GetScrollbar(WID_IC_SCROLLBAR);
02044     this->FinishInitNested(&_industry_cargoes_desc, 0);
02045     this->OnInvalidateData(id);
02046   }
02047 
02048   virtual void OnInit()
02049   {
02050     /* Initialize static CargoesField size variables. */
02051     Dimension d = GetStringBoundingBox(STR_INDUSTRY_CARGOES_PRODUCERS);
02052     d = maxdim(d, GetStringBoundingBox(STR_INDUSTRY_CARGOES_CUSTOMERS));
02053     d.width  += WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT;
02054     d.height += WD_FRAMETEXT_TOP + WD_FRAMETEXT_BOTTOM;
02055     CargoesField::small_height = d.height;
02056 
02057     /* Decide about the size of the box holding the text of an industry type. */
02058     this->ind_textsize.width = 0;
02059     this->ind_textsize.height = 0;
02060     for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
02061       const IndustrySpec *indsp = GetIndustrySpec(it);
02062       if (!indsp->enabled) continue;
02063       this->ind_textsize = maxdim(this->ind_textsize, GetStringBoundingBox(indsp->name));
02064     }
02065     d.width = max(d.width, this->ind_textsize.width);
02066     d.height = this->ind_textsize.height;
02067     this->ind_textsize = maxdim(this->ind_textsize, GetStringBoundingBox(STR_INDUSTRY_CARGOES_SELECT_INDUSTRY));
02068 
02069     /* Compute max size of the cargo texts. */
02070     this->cargo_textsize.width = 0;
02071     this->cargo_textsize.height = 0;
02072     for (uint i = 0; i < NUM_CARGO; i++) {
02073       const CargoSpec *csp = CargoSpec::Get(i);
02074       if (!csp->IsValid()) continue;
02075       this->cargo_textsize = maxdim(this->cargo_textsize, GetStringBoundingBox(csp->name));
02076     }
02077     d = maxdim(d, this->cargo_textsize); // Box must also be wide enough to hold any cargo label.
02078     this->cargo_textsize = maxdim(this->cargo_textsize, GetStringBoundingBox(STR_INDUSTRY_CARGOES_SELECT_CARGO));
02079 
02080     d.width  += 2 * HOR_TEXT_PADDING;
02081     /* Ensure the height is enough for the industry type text, for the horizontal connections, and for the cargo labels. */
02082     uint min_ind_height = CargoesField::VERT_CARGO_EDGE * 2 + MAX_CARGOES * FONT_HEIGHT_NORMAL + (MAX_CARGOES - 1) *  CargoesField::VERT_CARGO_SPACE;
02083     d.height = max(d.height + 2 * VERT_TEXT_PADDING, min_ind_height);
02084 
02085     CargoesField::industry_width = d.width;
02086     CargoesField::normal_height = d.height + CargoesField::VERT_INTER_INDUSTRY_SPACE;
02087   }
02088 
02089   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
02090   {
02091     switch (widget) {
02092       case WID_IC_PANEL:
02093         size->width = WD_FRAMETEXT_LEFT + CargoesField::industry_width * 3 + CargoesField::CARGO_FIELD_WIDTH * 2 + WD_FRAMETEXT_RIGHT;
02094         break;
02095 
02096       case WID_IC_IND_DROPDOWN:
02097         size->width = max(size->width, this->ind_textsize.width + padding.width);
02098         break;
02099 
02100       case WID_IC_CARGO_DROPDOWN:
02101         size->width = max(size->width, this->cargo_textsize.width + padding.width);
02102         break;
02103     }
02104   }
02105 
02106 
02107   CargoesFieldType type; 
02108   virtual void SetStringParameters  (int widget) const
02109   {
02110     if (widget != WID_IC_CAPTION) return;
02111 
02112     if (this->ind_cargo < NUM_INDUSTRYTYPES) {
02113       const IndustrySpec *indsp = GetIndustrySpec(this->ind_cargo);
02114       SetDParam(0, indsp->name);
02115     } else {
02116       const CargoSpec *csp = CargoSpec::Get(this->ind_cargo - NUM_INDUSTRYTYPES);
02117       SetDParam(0, csp->name);
02118     }
02119   }
02120 
02129   static bool HasCommonValidCargo(const CargoID *cargoes1, uint length1, const CargoID *cargoes2, uint length2)
02130   {
02131     while (length1 > 0) {
02132       if (*cargoes1 != INVALID_CARGO) {
02133         for (uint i = 0; i < length2; i++) if (*cargoes1 == cargoes2[i]) return true;
02134       }
02135       cargoes1++;
02136       length1--;
02137     }
02138     return false;
02139   }
02140 
02147   static bool HousesCanSupply(const CargoID *cargoes, uint length)
02148   {
02149     for (uint i = 0; i < length; i++) {
02150       if (cargoes[i] == INVALID_CARGO) continue;
02151       if (cargoes[i] == CT_PASSENGERS || cargoes[i] == CT_MAIL) return true;
02152     }
02153     return false;
02154   }
02155 
02162   static bool HousesCanAccept(const CargoID *cargoes, uint length)
02163   {
02164     HouseZones climate_mask;
02165     switch (_settings_game.game_creation.landscape) {
02166       case LT_TEMPERATE: climate_mask = HZ_TEMP; break;
02167       case LT_ARCTIC:    climate_mask = HZ_SUBARTC_ABOVE | HZ_SUBARTC_BELOW; break;
02168       case LT_TROPIC:    climate_mask = HZ_SUBTROPIC; break;
02169       case LT_TOYLAND:   climate_mask = HZ_TOYLND; break;
02170       default: NOT_REACHED();
02171     }
02172     for (uint i = 0; i < length; i++) {
02173       if (cargoes[i] == INVALID_CARGO) continue;
02174 
02175       for (uint h = 0; h < HOUSE_MAX; h++) {
02176         HouseSpec *hs = HouseSpec::Get(h);
02177         if (!hs->enabled || !(hs->building_availability & climate_mask)) continue;
02178 
02179         for (uint j = 0; j < lengthof(hs->accepts_cargo); j++) {
02180           if (cargoes[i] == hs->accepts_cargo[j]) return true;
02181         }
02182       }
02183     }
02184     return false;
02185   }
02186 
02193   static int CountMatchingAcceptingIndustries(const CargoID *cargoes, uint length)
02194   {
02195     int count = 0;
02196     for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
02197       const IndustrySpec *indsp = GetIndustrySpec(it);
02198       if (!indsp->enabled) continue;
02199 
02200       if (HasCommonValidCargo(cargoes, length, indsp->accepts_cargo, lengthof(indsp->accepts_cargo))) count++;
02201     }
02202     return count;
02203   }
02204 
02211   static int CountMatchingProducingIndustries(const CargoID *cargoes, uint length)
02212   {
02213     int count = 0;
02214     for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
02215       const IndustrySpec *indsp = GetIndustrySpec(it);
02216       if (!indsp->enabled) continue;
02217 
02218       if (HasCommonValidCargo(cargoes, length, indsp->produced_cargo, lengthof(indsp->produced_cargo))) count++;
02219     }
02220     return count;
02221   }
02222 
02229   void ShortenCargoColumn(int column, int top, int bottom)
02230   {
02231     while (top < bottom && !this->fields[top].columns[column].HasConnection()) {
02232       this->fields[top].columns[column].MakeEmpty(CFT_EMPTY);
02233       top++;
02234     }
02235     this->fields[top].columns[column].u.cargo.top_end = true;
02236 
02237     while (bottom > top && !this->fields[bottom].columns[column].HasConnection()) {
02238       this->fields[bottom].columns[column].MakeEmpty(CFT_EMPTY);
02239       bottom--;
02240     }
02241     this->fields[bottom].columns[column].u.cargo.bottom_end = true;
02242   }
02243 
02250   void PlaceIndustry(int row, int col, IndustryType it)
02251   {
02252     assert(this->fields[row].columns[col].type == CFT_EMPTY);
02253     this->fields[row].columns[col].MakeIndustry(it);
02254     if (col == 0) {
02255       this->fields[row].ConnectIndustryProduced(col);
02256     } else {
02257       this->fields[row].ConnectIndustryAccepted(col);
02258     }
02259   }
02260 
02264   void NotifySmallmap()
02265   {
02266     if (!this->IsWidgetLowered(WID_IC_NOTIFY)) return;
02267 
02268     /* Only notify the smallmap window if it exists. In particular, do not
02269      * bring it to the front to prevent messing up any nice layout of the user. */
02270     InvalidateWindowClassesData(WC_SMALLMAP, 0);
02271   }
02272 
02277   void ComputeIndustryDisplay(IndustryType it)
02278   {
02279     this->GetWidget<NWidgetCore>(WID_IC_CAPTION)->widget_data = STR_INDUSTRY_CARGOES_INDUSTRY_CAPTION;
02280     this->ind_cargo = it;
02281     _displayed_industries = 1ULL << it;
02282 
02283     this->fields.Clear();
02284     CargoesRow *row = this->fields.Append();
02285     row->columns[0].MakeHeader(STR_INDUSTRY_CARGOES_PRODUCERS);
02286     row->columns[1].MakeEmpty(CFT_SMALL_EMPTY);
02287     row->columns[2].MakeEmpty(CFT_SMALL_EMPTY);
02288     row->columns[3].MakeEmpty(CFT_SMALL_EMPTY);
02289     row->columns[4].MakeHeader(STR_INDUSTRY_CARGOES_CUSTOMERS);
02290 
02291     const IndustrySpec *central_sp = GetIndustrySpec(it);
02292     bool houses_supply = HousesCanSupply(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo));
02293     bool houses_accept = HousesCanAccept(central_sp->produced_cargo, lengthof(central_sp->produced_cargo));
02294     /* Make a field consisting of two cargo columns. */
02295     int num_supp = CountMatchingProducingIndustries(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo)) + houses_supply;
02296     int num_cust = CountMatchingAcceptingIndustries(central_sp->produced_cargo, lengthof(central_sp->produced_cargo)) + houses_accept;
02297     int num_indrows = max(3, max(num_supp, num_cust)); // One is needed for the 'it' industry, and 2 for the cargo labels.
02298     for (int i = 0; i < num_indrows; i++) {
02299       CargoesRow *row = this->fields.Append();
02300       row->columns[0].MakeEmpty(CFT_EMPTY);
02301       row->columns[1].MakeCargo(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo));
02302       row->columns[2].MakeEmpty(CFT_EMPTY);
02303       row->columns[3].MakeCargo(central_sp->produced_cargo, lengthof(central_sp->produced_cargo));
02304       row->columns[4].MakeEmpty(CFT_EMPTY);
02305     }
02306     /* Add central industry. */
02307     int central_row = 1 + num_indrows / 2;
02308     this->fields[central_row].columns[2].MakeIndustry(it);
02309     this->fields[central_row].ConnectIndustryProduced(2);
02310     this->fields[central_row].ConnectIndustryAccepted(2);
02311 
02312     /* Add cargo labels. */
02313     this->fields[central_row - 1].MakeCargoLabel(2, true);
02314     this->fields[central_row + 1].MakeCargoLabel(2, false);
02315 
02316     /* Add suppliers and customers of the 'it' industry. */
02317     int supp_count = 0;
02318     int cust_count = 0;
02319     for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
02320       const IndustrySpec *indsp = GetIndustrySpec(it);
02321       if (!indsp->enabled) continue;
02322 
02323       if (HasCommonValidCargo(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo), indsp->produced_cargo, lengthof(indsp->produced_cargo))) {
02324         this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, it);
02325         SetBit(_displayed_industries, it);
02326         supp_count++;
02327       }
02328       if (HasCommonValidCargo(central_sp->produced_cargo, lengthof(central_sp->produced_cargo), indsp->accepts_cargo, lengthof(indsp->accepts_cargo))) {
02329         this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 4, it);
02330         SetBit(_displayed_industries, it);
02331         cust_count++;
02332       }
02333     }
02334     if (houses_supply) {
02335       this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, NUM_INDUSTRYTYPES);
02336       supp_count++;
02337     }
02338     if (houses_accept) {
02339       this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 4, NUM_INDUSTRYTYPES);
02340       cust_count++;
02341     }
02342 
02343     this->ShortenCargoColumn(1, 1, num_indrows);
02344     this->ShortenCargoColumn(3, 1, num_indrows);
02345     const NWidgetBase *nwp = this->GetWidget<NWidgetBase>(WID_IC_PANEL);
02346     this->vscroll->SetCount(CeilDiv(WD_FRAMETEXT_TOP + WD_FRAMETEXT_BOTTOM + CargoesField::small_height + num_indrows * CargoesField::normal_height, nwp->resize_y));
02347     this->SetDirty();
02348     this->NotifySmallmap();
02349   }
02350 
02355   void ComputeCargoDisplay(CargoID cid)
02356   {
02357     this->GetWidget<NWidgetCore>(WID_IC_CAPTION)->widget_data = STR_INDUSTRY_CARGOES_CARGO_CAPTION;
02358     this->ind_cargo = cid + NUM_INDUSTRYTYPES;
02359     _displayed_industries = 0;
02360 
02361     this->fields.Clear();
02362     CargoesRow *row = this->fields.Append();
02363     row->columns[0].MakeHeader(STR_INDUSTRY_CARGOES_PRODUCERS);
02364     row->columns[1].MakeEmpty(CFT_SMALL_EMPTY);
02365     row->columns[2].MakeHeader(STR_INDUSTRY_CARGOES_CUSTOMERS);
02366     row->columns[3].MakeEmpty(CFT_SMALL_EMPTY);
02367     row->columns[4].MakeEmpty(CFT_SMALL_EMPTY);
02368 
02369     bool houses_supply = HousesCanSupply(&cid, 1);
02370     bool houses_accept = HousesCanAccept(&cid, 1);
02371     int num_supp = CountMatchingProducingIndustries(&cid, 1) + houses_supply + 1; // Ensure room for the cargo label.
02372     int num_cust = CountMatchingAcceptingIndustries(&cid, 1) + houses_accept;
02373     int num_indrows = max(num_supp, num_cust);
02374     for (int i = 0; i < num_indrows; i++) {
02375       CargoesRow *row = this->fields.Append();
02376       row->columns[0].MakeEmpty(CFT_EMPTY);
02377       row->columns[1].MakeCargo(&cid, 1);
02378       row->columns[2].MakeEmpty(CFT_EMPTY);
02379       row->columns[3].MakeEmpty(CFT_EMPTY);
02380       row->columns[4].MakeEmpty(CFT_EMPTY);
02381     }
02382 
02383     this->fields[num_indrows].MakeCargoLabel(0, false); // Add cargo labels at the left bottom.
02384 
02385     /* Add suppliers and customers of the cargo. */
02386     int supp_count = 0;
02387     int cust_count = 0;
02388     for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
02389       const IndustrySpec *indsp = GetIndustrySpec(it);
02390       if (!indsp->enabled) continue;
02391 
02392       if (HasCommonValidCargo(&cid, 1, indsp->produced_cargo, lengthof(indsp->produced_cargo))) {
02393         this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, it);
02394         SetBit(_displayed_industries, it);
02395         supp_count++;
02396       }
02397       if (HasCommonValidCargo(&cid, 1, indsp->accepts_cargo, lengthof(indsp->accepts_cargo))) {
02398         this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 2, it);
02399         SetBit(_displayed_industries, it);
02400         cust_count++;
02401       }
02402     }
02403     if (houses_supply) {
02404       this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, NUM_INDUSTRYTYPES);
02405       supp_count++;
02406     }
02407     if (houses_accept) {
02408       this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 2, NUM_INDUSTRYTYPES);
02409       cust_count++;
02410     }
02411 
02412     this->ShortenCargoColumn(1, 1, num_indrows);
02413     const NWidgetBase *nwp = this->GetWidget<NWidgetBase>(WID_IC_PANEL);
02414     this->vscroll->SetCount(CeilDiv(WD_FRAMETEXT_TOP + WD_FRAMETEXT_BOTTOM + CargoesField::small_height + num_indrows * CargoesField::normal_height, nwp->resize_y));
02415     this->SetDirty();
02416     this->NotifySmallmap();
02417   }
02418 
02426   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
02427   {
02428     if (!gui_scope) return;
02429     if (data == NUM_INDUSTRYTYPES) {
02430       if (this->IsWidgetLowered(WID_IC_NOTIFY)) {
02431         this->RaiseWidget(WID_IC_NOTIFY);
02432         this->SetWidgetDirty(WID_IC_NOTIFY);
02433       }
02434       return;
02435     }
02436 
02437     assert(data >= 0 && data < NUM_INDUSTRYTYPES);
02438     this->ComputeIndustryDisplay(data);
02439   }
02440 
02441   virtual void DrawWidget(const Rect &r, int widget) const
02442   {
02443     if (widget != WID_IC_PANEL) return;
02444 
02445     DrawPixelInfo tmp_dpi, *old_dpi;
02446     int width = r.right - r.left + 1;
02447     int height = r.bottom - r.top + 1 - WD_FRAMERECT_TOP - WD_FRAMERECT_BOTTOM;
02448     if (!FillDrawPixelInfo(&tmp_dpi, r.left + WD_FRAMERECT_LEFT, r.top + WD_FRAMERECT_TOP, width, height)) return;
02449     old_dpi = _cur_dpi;
02450     _cur_dpi = &tmp_dpi;
02451 
02452     int left_pos = WD_FRAMERECT_LEFT;
02453     if (this->ind_cargo >= NUM_INDUSTRYTYPES) left_pos += (CargoesField::industry_width + CargoesField::CARGO_FIELD_WIDTH) / 2;
02454     int last_column = (this->ind_cargo < NUM_INDUSTRYTYPES) ? 4 : 2;
02455 
02456     const NWidgetBase *nwp = this->GetWidget<NWidgetBase>(WID_IC_PANEL);
02457     int vpos = -this->vscroll->GetPosition() * nwp->resize_y;
02458     for (uint i = 0; i < this->fields.Length(); i++) {
02459       int row_height = (i == 0) ? CargoesField::small_height : CargoesField::normal_height;
02460       if (vpos + row_height >= 0) {
02461         int xpos = left_pos;
02462         int col, dir;
02463         if (_current_text_dir == TD_RTL) {
02464           col = last_column;
02465           dir = -1;
02466         } else {
02467           col = 0;
02468           dir = 1;
02469         }
02470         while (col >= 0 && col <= last_column) {
02471           this->fields[i].columns[col].Draw(xpos, vpos);
02472           xpos += (col & 1) ? CargoesField::CARGO_FIELD_WIDTH : CargoesField::industry_width;
02473           col += dir;
02474         }
02475       }
02476       vpos += row_height;
02477       if (vpos >= height) break;
02478     }
02479 
02480     _cur_dpi = old_dpi;
02481   }
02482 
02490   bool CalculatePositionInWidget(Point pt, Point *fieldxy, Point *xy)
02491   {
02492     const NWidgetBase *nw = this->GetWidget<NWidgetBase>(WID_IC_PANEL);
02493     pt.x -= nw->pos_x;
02494     pt.y -= nw->pos_y;
02495 
02496     int vpos = WD_FRAMERECT_TOP + CargoesField::small_height - this->vscroll->GetPosition() * nw->resize_y;
02497     if (pt.y < vpos) return false;
02498 
02499     int row = (pt.y - vpos) / CargoesField::normal_height; // row is relative to row 1.
02500     if (row + 1 >= (int)this->fields.Length()) return false;
02501     vpos = pt.y - vpos - row * CargoesField::normal_height; // Position in the row + 1 field
02502     row++; // rebase row to match index of this->fields.
02503 
02504     int xpos = 2 * WD_FRAMERECT_LEFT + ((this->ind_cargo < NUM_INDUSTRYTYPES) ? 0 :  (CargoesField::industry_width + CargoesField::CARGO_FIELD_WIDTH) / 2);
02505     if (pt.x < xpos) return false;
02506     int column;
02507     for (column = 0; column <= 5; column++) {
02508       int width = (column & 1) ? CargoesField::CARGO_FIELD_WIDTH : CargoesField::industry_width;
02509       if (pt.x < xpos + width) break;
02510       xpos += width;
02511     }
02512     int num_columns = (this->ind_cargo < NUM_INDUSTRYTYPES) ? 4 : 2;
02513     if (column > num_columns) return false;
02514     xpos = pt.x - xpos;
02515 
02516     /* Return both positions, compensating for RTL languages (which works due to the equal symmetry in both displays). */
02517     fieldxy->y = row;
02518     xy->y = vpos;
02519     if (_current_text_dir == TD_RTL) {
02520       fieldxy->x = num_columns - column;
02521       xy->x = ((column & 1) ? CargoesField::CARGO_FIELD_WIDTH : CargoesField::industry_width) - xpos;
02522     } else {
02523       fieldxy->x = column;
02524       xy->x = xpos;
02525     }
02526     return true;
02527   }
02528 
02529   virtual void OnClick(Point pt, int widget, int click_count)
02530   {
02531     switch (widget) {
02532       case WID_IC_PANEL: {
02533         Point fieldxy, xy;
02534         if (!CalculatePositionInWidget(pt, &fieldxy, &xy)) return;
02535 
02536         const CargoesField *fld = this->fields[fieldxy.y].columns + fieldxy.x;
02537         switch (fld->type) {
02538           case CFT_INDUSTRY:
02539             if (fld->u.industry.ind_type < NUM_INDUSTRYTYPES) this->ComputeIndustryDisplay(fld->u.industry.ind_type);
02540             break;
02541 
02542           case CFT_CARGO: {
02543             CargoesField *lft = (fieldxy.x > 0) ? this->fields[fieldxy.y].columns + fieldxy.x - 1 : NULL;
02544             CargoesField *rgt = (fieldxy.x < 4) ? this->fields[fieldxy.y].columns + fieldxy.x + 1 : NULL;
02545             CargoID cid = fld->CargoClickedAt(lft, rgt, xy);
02546             if (cid != INVALID_CARGO) this->ComputeCargoDisplay(cid);
02547             break;
02548           }
02549 
02550           case CFT_CARGO_LABEL: {
02551             CargoID cid = fld->CargoLabelClickedAt(xy);
02552             if (cid != INVALID_CARGO) this->ComputeCargoDisplay(cid);
02553             break;
02554           }
02555 
02556           default:
02557             break;
02558         }
02559         break;
02560       }
02561 
02562       case WID_IC_NOTIFY:
02563         this->ToggleWidgetLoweredState(WID_IC_NOTIFY);
02564         this->SetWidgetDirty(WID_IC_NOTIFY);
02565         if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP);
02566 
02567         if (this->IsWidgetLowered(WID_IC_NOTIFY)) {
02568           if (FindWindowByClass(WC_SMALLMAP) == NULL) ShowSmallMap();
02569           this->NotifySmallmap();
02570         }
02571         break;
02572 
02573       case WID_IC_CARGO_DROPDOWN: {
02574         DropDownList *lst = new DropDownList;
02575         const CargoSpec *cs;
02576         FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
02577           lst->push_back(new DropDownListStringItem(cs->name, cs->Index(), false));
02578         }
02579         if (lst->size() == 0) {
02580           delete lst;
02581           break;
02582         }
02583         int selected = (this->ind_cargo >= NUM_INDUSTRYTYPES) ? this->ind_cargo - NUM_INDUSTRYTYPES : -1;
02584         ShowDropDownList(this, lst, selected, WID_IC_CARGO_DROPDOWN, 0, true);
02585         break;
02586       }
02587 
02588       case WID_IC_IND_DROPDOWN: {
02589         DropDownList *lst = new DropDownList;
02590         for (uint8 i = 0; i < NUM_INDUSTRYTYPES; i++) {
02591           IndustryType ind = _sorted_industry_types[i];
02592           const IndustrySpec *indsp = GetIndustrySpec(ind);
02593           if (!indsp->enabled) continue;
02594           lst->push_back(new DropDownListStringItem(indsp->name, ind, false));
02595         }
02596         if (lst->size() == 0) {
02597           delete lst;
02598           break;
02599         }
02600         int selected = (this->ind_cargo < NUM_INDUSTRYTYPES) ? this->ind_cargo : -1;
02601         ShowDropDownList(this, lst, selected, WID_IC_IND_DROPDOWN, 0, true);
02602         break;
02603       }
02604     }
02605   }
02606 
02607   virtual void OnDropdownSelect(int widget, int index)
02608   {
02609     if (index < 0) return;
02610 
02611     switch (widget) {
02612       case WID_IC_CARGO_DROPDOWN:
02613         this->ComputeCargoDisplay(index);
02614         break;
02615 
02616       case WID_IC_IND_DROPDOWN:
02617         this->ComputeIndustryDisplay(index);
02618         break;
02619     }
02620   }
02621 
02622   virtual void OnHover(Point pt, int widget)
02623   {
02624     if (widget != WID_IC_PANEL) return;
02625 
02626     Point fieldxy, xy;
02627     if (!CalculatePositionInWidget(pt, &fieldxy, &xy)) return;
02628 
02629     const CargoesField *fld = this->fields[fieldxy.y].columns + fieldxy.x;
02630     CargoID cid = INVALID_CARGO;
02631     switch (fld->type) {
02632       case CFT_CARGO: {
02633         CargoesField *lft = (fieldxy.x > 0) ? this->fields[fieldxy.y].columns + fieldxy.x - 1 : NULL;
02634         CargoesField *rgt = (fieldxy.x < 4) ? this->fields[fieldxy.y].columns + fieldxy.x + 1 : NULL;
02635         cid = fld->CargoClickedAt(lft, rgt, xy);
02636         break;
02637       }
02638 
02639       case CFT_CARGO_LABEL: {
02640         cid = fld->CargoLabelClickedAt(xy);
02641         break;
02642       }
02643 
02644       case CFT_INDUSTRY:
02645         if (fld->u.industry.ind_type < NUM_INDUSTRYTYPES && (this->ind_cargo >= NUM_INDUSTRYTYPES || fieldxy.x != 2)) {
02646           GuiShowTooltips(this, STR_INDUSTRY_CARGOES_INDUSTRY_TOOLTIP, 0, NULL, TCC_HOVER);
02647         }
02648         return;
02649 
02650       default:
02651         break;
02652     }
02653     if (cid != INVALID_CARGO && (this->ind_cargo < NUM_INDUSTRYTYPES || cid != this->ind_cargo - NUM_INDUSTRYTYPES)) {
02654       const CargoSpec *csp = CargoSpec::Get(cid);
02655       uint64 params[5];
02656       params[0] = csp->name;
02657       GuiShowTooltips(this, STR_INDUSTRY_CARGOES_CARGO_TOOLTIP, 1, params, TCC_HOVER);
02658     }
02659   }
02660 
02661   virtual void OnResize()
02662   {
02663     this->vscroll->SetCapacityFromWidget(this, WID_IC_PANEL);
02664   }
02665 };
02666 
02667 const int IndustryCargoesWindow::HOR_TEXT_PADDING  = 5; 
02668 const int IndustryCargoesWindow::VERT_TEXT_PADDING = 5; 
02669 
02674 static void ShowIndustryCargoesWindow(IndustryType id)
02675 {
02676   if (id >= NUM_INDUSTRYTYPES) {
02677     for (uint8 i = 0; i < NUM_INDUSTRYTYPES; i++) {
02678       const IndustrySpec *indsp = GetIndustrySpec(_sorted_industry_types[i]);
02679       if (indsp->enabled) {
02680         id = _sorted_industry_types[i];
02681         break;
02682       }
02683     }
02684     if (id >= NUM_INDUSTRYTYPES) return;
02685   }
02686 
02687   Window *w = BringWindowToFrontById(WC_INDUSTRY_CARGOES, 0);
02688   if (w != NULL) {
02689     w->InvalidateData(id);
02690     return;
02691   }
02692   new IndustryCargoesWindow(id);
02693 }
02694 
02696 void ShowIndustryCargoesWindow()
02697 {
02698   ShowIndustryCargoesWindow(NUM_INDUSTRYTYPES);
02699 }