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