industry_gui.cpp

Go to the documentation of this file.
00001 /* $Id: industry_gui.cpp 21665 2010-12-30 13:16:31Z alberth $ */
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 "openttd.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 "gfx_func.h"
00021 #include "industry.h"
00022 #include "town.h"
00023 #include "cheat_type.h"
00024 #include "newgrf_industries.h"
00025 #include "newgrf_text.h"
00026 #include "newgrf_debug.h"
00027 #include "strings_func.h"
00028 #include "company_func.h"
00029 #include "tilehighlight_func.h"
00030 #include "string_func.h"
00031 #include "sortlist_type.h"
00032 #include "widgets/dropdown_func.h"
00033 #include "company_base.h"
00034 #include "core/geometry_func.hpp"
00035 #include "core/random_func.hpp"
00036 #include "core/backup_type.hpp"
00037 #include "genworld.h"
00038 #include "smallmap_gui.h"
00039 
00040 #include "table/strings.h"
00041 #include "table/sprites.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 (GB(callback, 0, 8) != 0xFF) {
00078       PrepareTextRefStackUsage(6);
00079       GetString(suffix, GetGRFStringID(indspec->grf_prop.grffile->grfid, 0xD000 + callback), suffix_last);
00080       StopTextRefStackUsage();
00081     }
00082   }
00083 }
00084 
00095 template <typename TC, typename TS>
00096 static inline void GetAllCargoSuffixes(uint cb_offset, CargoSuffixType cst, const Industry *ind, IndustryType ind_type, const IndustrySpec *indspec, const TC &cargos, TS &suffixes)
00097 {
00098   assert_compile(lengthof(cargos) <= lengthof(suffixes));
00099   for (uint j = 0; j < lengthof(cargos); j++) {
00100     if (cargos[j] != CT_INVALID) {
00101       GetCargoSuffix(cb_offset + j, cst, ind, ind_type, indspec, suffixes[j], lastof(suffixes[j]));
00102     } else {
00103       suffixes[j][0] = '\0';
00104     }
00105   }
00106 }
00107 
00108 IndustryType _sorted_industry_types[NUM_INDUSTRYTYPES];
00109 
00111 static int CDECL IndustryTypeNameSorter(const IndustryType *a, const IndustryType *b)
00112 {
00113   static char industry_name[2][64];
00114 
00115   const IndustrySpec *indsp1 = GetIndustrySpec(*a);
00116   SetDParam(0, indsp1->name);
00117   GetString(industry_name[0], STR_JUST_STRING, lastof(industry_name[0]));
00118 
00119   const IndustrySpec *indsp2 = GetIndustrySpec(*b);
00120   SetDParam(0, indsp2->name);
00121   GetString(industry_name[1], STR_JUST_STRING, lastof(industry_name[1]));
00122 
00123   int r = strnatcmp(industry_name[0], industry_name[1]); // Sort by name (natural sorting).
00124 
00125   /* If the names are equal, sort by industry type. */
00126   return (r != 0) ? r : (*a - *b);
00127 }
00128 
00132 void SortIndustryTypes()
00133 {
00134   /* Add each industry type to the list. */
00135   for (IndustryType i = 0; i < NUM_INDUSTRYTYPES; i++) {
00136     _sorted_industry_types[i] = i;
00137   }
00138 
00139   /* Sort industry types by name. */
00140   QSortT(_sorted_industry_types, NUM_INDUSTRYTYPES, &IndustryTypeNameSorter);
00141 }
00142 
00150 void CcBuildIndustry(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
00151 {
00152   if (result.Succeeded()) return;
00153 
00154   uint8 indtype = GB(p1, 0, 8);
00155   if (indtype < NUM_INDUSTRYTYPES) {
00156     const IndustrySpec *indsp = GetIndustrySpec(indtype);
00157     if (indsp->enabled) {
00158       SetDParam(0, indsp->name);
00159       ShowErrorMessage(STR_ERROR_CAN_T_BUILD_HERE, result.GetErrorMessage(), WL_INFO, TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE);
00160     }
00161   }
00162 }
00163 
00165 enum DynamicPlaceIndustriesWidgets {
00166   DPIW_MATRIX_WIDGET,
00167   DPIW_SCROLLBAR,
00168   DPIW_INFOPANEL,
00169   DPIW_DISPLAY_WIDGET,
00170   DPIW_FUND_WIDGET,
00171 };
00172 
00173 static const NWidgetPart _nested_build_industry_widgets[] = {
00174   NWidget(NWID_HORIZONTAL),
00175     NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
00176     NWidget(WWT_CAPTION, COLOUR_DARK_GREEN), SetDataTip(STR_FUND_INDUSTRY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00177     NWidget(WWT_SHADEBOX, COLOUR_DARK_GREEN),
00178     NWidget(WWT_STICKYBOX, COLOUR_DARK_GREEN),
00179   EndContainer(),
00180   NWidget(NWID_HORIZONTAL),
00181     NWidget(WWT_MATRIX, COLOUR_DARK_GREEN, DPIW_MATRIX_WIDGET), SetDataTip(0x801, STR_FUND_INDUSTRY_SELECTION_TOOLTIP), SetFill(1, 0), SetResize(1, 1), SetScrollbar(DPIW_SCROLLBAR),
00182     NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, DPIW_SCROLLBAR),
00183   EndContainer(),
00184   NWidget(WWT_PANEL, COLOUR_DARK_GREEN, DPIW_INFOPANEL), SetResize(1, 0),
00185   EndContainer(),
00186   NWidget(NWID_HORIZONTAL),
00187     NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, DPIW_DISPLAY_WIDGET), SetFill(1, 0), SetResize(1, 0),
00188         SetDataTip(STR_INDUSTRY_DISPLAY_CHAIN, STR_INDUSTRY_DISPLAY_CHAIN_TOOLTIP),
00189     NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, DPIW_FUND_WIDGET), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_JUST_STRING, STR_NULL),
00190     NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
00191   EndContainer(),
00192 };
00193 
00195 static const WindowDesc _build_industry_desc(
00196   WDP_AUTO, 170, 212,
00197   WC_BUILD_INDUSTRY, WC_NONE,
00198   WDF_CONSTRUCTION,
00199   _nested_build_industry_widgets, lengthof(_nested_build_industry_widgets)
00200 );
00201 
00203 class BuildIndustryWindow : public Window {
00204   int selected_index;                         
00205   IndustryType selected_type;                 
00206   uint16 callback_timer;                      
00207   bool timer_enabled;                         
00208   uint16 count;                               
00209   IndustryType index[NUM_INDUSTRYTYPES + 1];  
00210   bool enabled[NUM_INDUSTRYTYPES + 1];        
00211   Scrollbar *vscroll;
00212 
00214   static const int MATRIX_TEXT_OFFSET = 17;
00215 
00216   void SetupArrays()
00217   {
00218     this->count = 0;
00219 
00220     for (uint i = 0; i < lengthof(this->index); i++) {
00221       this->index[i]   = INVALID_INDUSTRYTYPE;
00222       this->enabled[i] = false;
00223     }
00224 
00225     if (_game_mode == GM_EDITOR) { // give room for the Many Random "button"
00226       this->index[this->count] = INVALID_INDUSTRYTYPE;
00227       this->enabled[this->count] = true;
00228       this->count++;
00229       this->timer_enabled = false;
00230     }
00231     /* Fill the arrays with industries.
00232      * The tests performed after the enabled allow to load the industries
00233      * In the same way they are inserted by grf (if any)
00234      */
00235     for (uint8 i = 0; i < NUM_INDUSTRYTYPES; i++) {
00236       IndustryType ind = _sorted_industry_types[i];
00237       const IndustrySpec *indsp = GetIndustrySpec(ind);
00238       if (indsp->enabled) {
00239         /* Rule is that editor mode loads all industries.
00240          * In game mode, all non raw industries are loaded too
00241          * and raw ones are loaded only when setting allows it */
00242         if (_game_mode != GM_EDITOR && indsp->IsRawIndustry() && _settings_game.construction.raw_industry_construction == 0) {
00243           /* Unselect if the industry is no longer in the list */
00244           if (this->selected_type == ind) this->selected_index = -1;
00245           continue;
00246         }
00247         this->index[this->count] = ind;
00248         this->enabled[this->count] = (_game_mode == GM_EDITOR) || CheckIfCallBackAllowsAvailability(ind, IACT_USERCREATION);
00249         /* Keep the selection to the correct line */
00250         if (this->selected_type == ind) this->selected_index = this->count;
00251         this->count++;
00252       }
00253     }
00254 
00255     /* first indutry type is selected if the current selection is invalid.
00256      * I'll be damned if there are none available ;) */
00257     if (this->selected_index == -1) {
00258       this->selected_index = 0;
00259       this->selected_type = this->index[0];
00260     }
00261 
00262     this->vscroll->SetCount(this->count);
00263   }
00264 
00266   void SetButtons()
00267   {
00268     this->SetWidgetDisabledState(DPIW_FUND_WIDGET, this->selected_type != INVALID_INDUSTRYTYPE && !this->enabled[this->selected_index]);
00269     this->SetWidgetDisabledState(DPIW_DISPLAY_WIDGET, this->selected_type == INVALID_INDUSTRYTYPE && this->enabled[this->selected_index]);
00270   }
00271 
00272 public:
00273   BuildIndustryWindow() : Window()
00274   {
00275     this->timer_enabled = _loaded_newgrf_features.has_newindustries;
00276 
00277     this->selected_index = -1;
00278     this->selected_type = INVALID_INDUSTRYTYPE;
00279 
00280     this->callback_timer = DAY_TICKS;
00281 
00282     this->CreateNestedTree(&_build_industry_desc);
00283     this->vscroll = this->GetScrollbar(DPIW_SCROLLBAR);
00284     this->FinishInitNested(&_build_industry_desc, 0);
00285 
00286     this->SetButtons();
00287   }
00288 
00289   virtual void OnInit()
00290   {
00291     this->SetupArrays();
00292   }
00293 
00294   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00295   {
00296     switch (widget) {
00297       case DPIW_MATRIX_WIDGET: {
00298         Dimension d = GetStringBoundingBox(STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES);
00299         for (byte i = 0; i < this->count; i++) {
00300           if (this->index[i] == INVALID_INDUSTRYTYPE) continue;
00301           d = maxdim(d, GetStringBoundingBox(GetIndustrySpec(this->index[i])->name));
00302         }
00303         resize->height = FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;
00304         d.width += MATRIX_TEXT_OFFSET + padding.width;
00305         d.height = 5 * resize->height;
00306         *size = maxdim(*size, d);
00307         break;
00308       }
00309 
00310       case DPIW_INFOPANEL: {
00311         /* Extra line for cost outside of editor + extra lines for 'extra' information for NewGRFs. */
00312         int height = 2 + (_game_mode == GM_EDITOR ? 0 : 1) + (_loaded_newgrf_features.has_newindustries ? 4 : 0);
00313         Dimension d = {0, 0};
00314         for (byte i = 0; i < this->count; i++) {
00315           if (this->index[i] == INVALID_INDUSTRYTYPE) continue;
00316 
00317           const IndustrySpec *indsp = GetIndustrySpec(this->index[i]);
00318 
00319           char cargo_suffix[3][512];
00320           GetAllCargoSuffixes(0, CST_FUND, NULL, this->index[i], indsp, indsp->accepts_cargo, cargo_suffix);
00321           StringID str = STR_INDUSTRY_VIEW_REQUIRES_CARGO;
00322           byte p = 0;
00323           SetDParam(0, STR_JUST_NOTHING);
00324           SetDParamStr(1, "");
00325           for (byte j = 0; j < lengthof(indsp->accepts_cargo); j++) {
00326             if (indsp->accepts_cargo[j] == CT_INVALID) continue;
00327             if (p > 0) str++;
00328             SetDParam(p++, CargoSpec::Get(indsp->accepts_cargo[j])->name);
00329             SetDParamStr(p++, cargo_suffix[j]);
00330           }
00331           d = maxdim(d, GetStringBoundingBox(str));
00332 
00333           /* Draw the produced cargoes, if any. Otherwise, will print "Nothing". */
00334           GetAllCargoSuffixes(3, CST_FUND, NULL, this->index[i], indsp, indsp->produced_cargo, cargo_suffix);
00335           str = STR_INDUSTRY_VIEW_PRODUCES_CARGO;
00336           p = 0;
00337           SetDParam(0, STR_JUST_NOTHING);
00338           SetDParamStr(1, "");
00339           for (byte j = 0; j < lengthof(indsp->produced_cargo); j++) {
00340             if (indsp->produced_cargo[j] == CT_INVALID) continue;
00341             if (p > 0) str++;
00342             SetDParam(p++, CargoSpec::Get(indsp->produced_cargo[j])->name);
00343             SetDParamStr(p++, cargo_suffix[j]);
00344           }
00345           d = maxdim(d, GetStringBoundingBox(str));
00346         }
00347 
00348         /* Set it to something more sane :) */
00349         size->height = height * FONT_HEIGHT_NORMAL + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
00350         size->width  = d.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
00351         break;
00352       }
00353 
00354       case DPIW_FUND_WIDGET: {
00355         Dimension d = GetStringBoundingBox(STR_FUND_INDUSTRY_BUILD_NEW_INDUSTRY);
00356         d = maxdim(d, GetStringBoundingBox(STR_FUND_INDUSTRY_PROSPECT_NEW_INDUSTRY));
00357         d = maxdim(d, GetStringBoundingBox(STR_FUND_INDUSTRY_FUND_NEW_INDUSTRY));
00358         d.width += padding.width;
00359         d.height += padding.height;
00360         *size = maxdim(*size, d);
00361         break;
00362       }
00363     }
00364   }
00365 
00366   virtual void SetStringParameters(int widget) const
00367   {
00368     switch (widget) {
00369       case DPIW_FUND_WIDGET:
00370         /* Raw industries might be prospected. Show this fact by changing the string
00371          * In Editor, you just build, while ingame, or you fund or you prospect */
00372         if (_game_mode == GM_EDITOR) {
00373           /* We've chosen many random industries but no industries have been specified */
00374           SetDParam(0, STR_FUND_INDUSTRY_BUILD_NEW_INDUSTRY);
00375         } else {
00376           const IndustrySpec *indsp = GetIndustrySpec(this->index[this->selected_index]);
00377           SetDParam(0, (_settings_game.construction.raw_industry_construction == 2 && indsp->IsRawIndustry()) ? STR_FUND_INDUSTRY_PROSPECT_NEW_INDUSTRY : STR_FUND_INDUSTRY_FUND_NEW_INDUSTRY);
00378         }
00379         break;
00380     }
00381   }
00382 
00383   virtual void DrawWidget(const Rect &r, int widget) const
00384   {
00385     switch (widget) {
00386       case DPIW_MATRIX_WIDGET:
00387         for (byte i = 0; i < this->vscroll->GetCapacity() && i + this->vscroll->GetPosition() < this->count; i++) {
00388           int x = r.left + WD_MATRIX_LEFT;
00389           int y = r.top + WD_MATRIX_TOP + i * this->resize.step_height;
00390           bool selected = this->selected_index == i + this->vscroll->GetPosition();
00391 
00392           if (this->index[i + this->vscroll->GetPosition()] == INVALID_INDUSTRYTYPE) {
00393             DrawString(x + MATRIX_TEXT_OFFSET, r.right - WD_MATRIX_RIGHT, y, STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES, selected ? TC_WHITE : TC_ORANGE);
00394             continue;
00395           }
00396           const IndustrySpec *indsp = GetIndustrySpec(this->index[i + this->vscroll->GetPosition()]);
00397 
00398           /* Draw the name of the industry in white is selected, otherwise, in orange */
00399           DrawString(x + MATRIX_TEXT_OFFSET, r.right - WD_MATRIX_RIGHT, y, indsp->name, selected ? TC_WHITE : TC_ORANGE);
00400           GfxFillRect(x,     y + 1,  x + 10, y + 7, selected ? 15 : 0);
00401           GfxFillRect(x + 1, y + 2,  x +  9, y + 6, indsp->map_colour);
00402         }
00403         break;
00404 
00405       case DPIW_INFOPANEL: {
00406         int y      = r.top    + WD_FRAMERECT_TOP;
00407         int bottom = r.bottom - WD_FRAMERECT_BOTTOM;
00408         int left   = r.left   + WD_FRAMERECT_LEFT;
00409         int right  = r.right  - WD_FRAMERECT_RIGHT;
00410 
00411         if (this->selected_type == INVALID_INDUSTRYTYPE) {
00412           DrawStringMultiLine(left, right, y,  bottom, STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES_TOOLTIP);
00413           break;
00414         }
00415 
00416         const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
00417 
00418         if (_game_mode != GM_EDITOR) {
00419           SetDParam(0, indsp->GetConstructionCost());
00420           DrawString(left, right, y, STR_FUND_INDUSTRY_INDUSTRY_BUILD_COST);
00421           y += FONT_HEIGHT_NORMAL;
00422         }
00423 
00424         /* Draw the accepted cargoes, if any. Otherwise, will print "Nothing". */
00425         char cargo_suffix[3][512];
00426         GetAllCargoSuffixes(0, CST_FUND, NULL, this->selected_type, indsp, indsp->accepts_cargo, cargo_suffix);
00427         StringID str = STR_INDUSTRY_VIEW_REQUIRES_CARGO;
00428         byte p = 0;
00429         SetDParam(0, STR_JUST_NOTHING);
00430         SetDParamStr(1, "");
00431         for (byte j = 0; j < lengthof(indsp->accepts_cargo); j++) {
00432           if (indsp->accepts_cargo[j] == CT_INVALID) continue;
00433           if (p > 0) str++;
00434           SetDParam(p++, CargoSpec::Get(indsp->accepts_cargo[j])->name);
00435           SetDParamStr(p++, cargo_suffix[j]);
00436         }
00437         DrawString(left, right, y, str);
00438         y += FONT_HEIGHT_NORMAL;
00439 
00440         /* Draw the produced cargoes, if any. Otherwise, will print "Nothing". */
00441         GetAllCargoSuffixes(3, CST_FUND, NULL, this->selected_type, indsp, indsp->produced_cargo, cargo_suffix);
00442         str = STR_INDUSTRY_VIEW_PRODUCES_CARGO;
00443         p = 0;
00444         SetDParam(0, STR_JUST_NOTHING);
00445         SetDParamStr(1, "");
00446         for (byte j = 0; j < lengthof(indsp->produced_cargo); j++) {
00447           if (indsp->produced_cargo[j] == CT_INVALID) continue;
00448           if (p > 0) str++;
00449           SetDParam(p++, CargoSpec::Get(indsp->produced_cargo[j])->name);
00450           SetDParamStr(p++, cargo_suffix[j]);
00451         }
00452         DrawString(left, right, y, str);
00453         y += FONT_HEIGHT_NORMAL;
00454 
00455         /* Get the additional purchase info text, if it has not already been queried. */
00456         str = STR_NULL;
00457         if (HasBit(indsp->callback_mask, CBM_IND_FUND_MORE_TEXT)) {
00458           uint16 callback_res = GetIndustryCallback(CBID_INDUSTRY_FUND_MORE_TEXT, 0, 0, NULL, this->selected_type, INVALID_TILE);
00459           if (callback_res != CALLBACK_FAILED) {  // Did it fail?
00460             str = GetGRFStringID(indsp->grf_prop.grffile->grfid, 0xD000 + callback_res);  // No. here's the new string
00461             if (str != STR_UNDEFINED) {
00462               PrepareTextRefStackUsage(6);
00463               DrawStringMultiLine(left, right, y, bottom, str);
00464               StopTextRefStackUsage();
00465             }
00466           }
00467         }
00468         break;
00469       }
00470     }
00471   }
00472 
00473   virtual void OnClick(Point pt, int widget, int click_count)
00474   {
00475     switch (widget) {
00476       case DPIW_MATRIX_WIDGET: {
00477         int y = this->vscroll->GetScrolledRowFromWidget(pt.y, this, DPIW_MATRIX_WIDGET);
00478         if (y < this->count) { // Is it within the boundaries of available data?
00479           this->selected_index = y;
00480           this->selected_type = this->index[y];
00481           const IndustrySpec *indsp = (this->selected_type == INVALID_INDUSTRYTYPE) ? NULL : GetIndustrySpec(this->selected_type);
00482 
00483           this->SetDirty();
00484 
00485           if (_thd.GetCallbackWnd() == this &&
00486               ((_game_mode != GM_EDITOR && _settings_game.construction.raw_industry_construction == 2 && indsp != NULL && indsp->IsRawIndustry()) ||
00487               this->selected_type == INVALID_INDUSTRYTYPE ||
00488               !this->enabled[this->selected_index])) {
00489             /* Reset the button state if going to prospecting or "build many industries" */
00490             this->RaiseButtons();
00491             ResetObjectToPlace();
00492           }
00493 
00494           this->SetButtons();
00495           if (this->enabled[this->selected_index] && click_count > 1) this->OnClick(pt, DPIW_FUND_WIDGET, 1);
00496         }
00497         break;
00498       }
00499 
00500       case DPIW_DISPLAY_WIDGET:
00501         if (this->selected_type != INVALID_INDUSTRYTYPE) ShowIndustryCargoesWindow(this->selected_type);
00502         break;
00503 
00504       case DPIW_FUND_WIDGET: {
00505         if (this->selected_type == INVALID_INDUSTRYTYPE) {
00506           this->HandleButtonClick(DPIW_FUND_WIDGET);
00507 
00508           if (Town::GetNumItems() == 0) {
00509             ShowErrorMessage(STR_ERROR_CAN_T_GENERATE_INDUSTRIES, STR_ERROR_MUST_FOUND_TOWN_FIRST, WL_INFO);
00510           } else {
00511             extern void GenerateIndustries();
00512             _generating_world = true;
00513             GenerateIndustries();
00514             _generating_world = false;
00515           }
00516         } else if (_game_mode != GM_EDITOR && _settings_game.construction.raw_industry_construction == 2 && GetIndustrySpec(this->selected_type)->IsRawIndustry()) {
00517           DoCommandP(0, this->selected_type, InteractiveRandom(), CMD_BUILD_INDUSTRY | CMD_MSG(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY));
00518           this->HandleButtonClick(DPIW_FUND_WIDGET);
00519         } else {
00520           HandlePlacePushButton(this, DPIW_FUND_WIDGET, SPR_CURSOR_INDUSTRY, HT_RECT);
00521         }
00522         break;
00523       }
00524     }
00525   }
00526 
00527   virtual void OnResize()
00528   {
00529     /* Adjust the number of items in the matrix depending of the resize */
00530     this->vscroll->SetCapacityFromWidget(this, DPIW_MATRIX_WIDGET);
00531     this->GetWidget<NWidgetCore>(DPIW_MATRIX_WIDGET)->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
00532   }
00533 
00534   virtual void OnPlaceObject(Point pt, TileIndex tile)
00535   {
00536     bool success = true;
00537     /* We do not need to protect ourselves against "Random Many Industries" in this mode */
00538     const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
00539     uint32 seed = InteractiveRandom();
00540 
00541     if (_game_mode == GM_EDITOR) {
00542       /* Show error if no town exists at all */
00543       if (Town::GetNumItems() == 0) {
00544         SetDParam(0, indsp->name);
00545         ShowErrorMessage(STR_ERROR_CAN_T_BUILD_HERE, STR_ERROR_MUST_FOUND_TOWN_FIRST, WL_INFO, pt.x, pt.y);
00546         return;
00547       }
00548 
00549       Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
00550       _generating_world = true;
00551       _ignore_restrictions = true;
00552 
00553       DoCommandP(tile, (InteractiveRandomRange(indsp->num_table) << 8) | this->selected_type, seed,
00554           CMD_BUILD_INDUSTRY | CMD_MSG(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY), &CcBuildIndustry);
00555 
00556       cur_company.Restore();
00557       _ignore_restrictions = false;
00558       _generating_world = false;
00559     } else {
00560       success = DoCommandP(tile, (InteractiveRandomRange(indsp->num_table) << 8) | this->selected_type, seed, CMD_BUILD_INDUSTRY | CMD_MSG(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY));
00561     }
00562 
00563     /* If an industry has been built, just reset the cursor and the system */
00564     if (success && !_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
00565   }
00566 
00567   virtual void OnTick()
00568   {
00569     if (_pause_mode != PM_UNPAUSED) return;
00570     if (!this->timer_enabled) return;
00571     if (--this->callback_timer == 0) {
00572       /* We have just passed another day.
00573        * See if we need to update availability of currently selected industry */
00574       this->callback_timer = DAY_TICKS; // restart counter
00575 
00576       const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
00577 
00578       if (indsp->enabled) {
00579         bool call_back_result = CheckIfCallBackAllowsAvailability(this->selected_type, IACT_USERCREATION);
00580 
00581         /* Only if result does match the previous state would it require a redraw. */
00582         if (call_back_result != this->enabled[this->selected_index]) {
00583           this->enabled[this->selected_index] = call_back_result;
00584           this->SetButtons();
00585           this->SetDirty();
00586         }
00587       }
00588     }
00589   }
00590 
00591   virtual void OnTimeout()
00592   {
00593     this->RaiseButtons();
00594   }
00595 
00596   virtual void OnPlaceObjectAbort()
00597   {
00598     this->RaiseButtons();
00599   }
00600 
00601   virtual void OnInvalidateData(int data = 0)
00602   {
00603     this->SetupArrays();
00604 
00605     const IndustrySpec *indsp = (this->selected_type == INVALID_INDUSTRYTYPE) ? NULL : GetIndustrySpec(this->selected_type);
00606     if (indsp == NULL) this->enabled[this->selected_index] = _settings_game.difficulty.number_industries != 0;
00607     this->SetButtons();
00608   }
00609 };
00610 
00611 void ShowBuildIndustryWindow()
00612 {
00613   if (_game_mode != GM_EDITOR && !Company::IsValidID(_local_company)) return;
00614   if (BringWindowToFrontById(WC_BUILD_INDUSTRY, 0)) return;
00615   new BuildIndustryWindow();
00616 }
00617 
00618 static void UpdateIndustryProduction(Industry *i);
00619 
00620 static inline bool IsProductionAlterable(const Industry *i)
00621 {
00622   const IndustrySpec *is = GetIndustrySpec(i->type);
00623   return ((_game_mode == GM_EDITOR || _cheats.setup_prod.value) &&
00624       (is->production_rate[0] != 0 || is->production_rate[1] != 0 || is->IsRawIndustry()));
00625 }
00626 
00628 enum IndustryViewWidgets {
00629   IVW_CAPTION,
00630   IVW_VIEWPORT,
00631   IVW_INFO,
00632   IVW_GOTO,
00633   IVW_DISPLAY,
00634 };
00635 
00636 class IndustryViewWindow : public Window
00637 {
00639   enum Editability {
00640     EA_NONE,              
00641     EA_MULTIPLIER,        
00642     EA_RATE,              
00643   };
00644 
00646   enum InfoLine {
00647     IL_NONE,              
00648     IL_MULTIPLIER,        
00649     IL_RATE1,             
00650     IL_RATE2,             
00651   };
00652 
00653   Editability editable;     
00654   InfoLine editbox_line;    
00655   InfoLine clicked_line;    
00656   byte clicked_button;      
00657   int production_offset_y;  
00658   int info_height;          
00659 
00660 public:
00661   IndustryViewWindow(const WindowDesc *desc, WindowNumber window_number) : Window()
00662   {
00663     this->flags4 |= WF_DISABLE_VP_SCROLL;
00664     this->editbox_line = IL_NONE;
00665     this->clicked_line = IL_NONE;
00666     this->clicked_button = 0;
00667     this->info_height = WD_FRAMERECT_TOP + 2 * FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM + 1; // Info panel has at least two lines text.
00668 
00669     this->InitNested(desc, window_number);
00670     NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(IVW_VIEWPORT);
00671     nvp->InitializeViewport(this, Industry::Get(window_number)->location.GetCenterTile(), ZOOM_LVL_INDUSTRY);
00672 
00673     this->InvalidateData();
00674   }
00675 
00676   virtual void OnPaint()
00677   {
00678     this->DrawWidgets();
00679 
00680     if (this->IsShaded()) return; // Don't draw anything when the window is shaded.
00681 
00682     NWidgetBase *nwi = this->GetWidget<NWidgetBase>(IVW_INFO);
00683     uint expected = this->DrawInfo(nwi->pos_x, nwi->pos_x + nwi->current_x - 1, nwi->pos_y) - nwi->pos_y;
00684     if (expected > nwi->current_y - 1) {
00685       this->info_height = expected + 1;
00686       this->ReInit();
00687       return;
00688     }
00689   }
00690 
00698   int DrawInfo(uint left, uint right, uint top)
00699   {
00700     Industry *i = Industry::Get(this->window_number);
00701     const IndustrySpec *ind = GetIndustrySpec(i->type);
00702     int y = top + WD_FRAMERECT_TOP;
00703     bool first = true;
00704     bool has_accept = false;
00705     char cargo_suffix[3][512];
00706 
00707     if (HasBit(ind->callback_mask, CBM_IND_PRODUCTION_CARGO_ARRIVAL) || HasBit(ind->callback_mask, CBM_IND_PRODUCTION_256_TICKS)) {
00708       GetAllCargoSuffixes(0, CST_VIEW, i, i->type, ind, i->accepts_cargo, cargo_suffix);
00709       for (byte j = 0; j < lengthof(i->accepts_cargo); j++) {
00710         if (i->accepts_cargo[j] == CT_INVALID) continue;
00711         has_accept = true;
00712         if (first) {
00713           DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_WAITING_FOR_PROCESSING);
00714           y += FONT_HEIGHT_NORMAL;
00715           first = false;
00716         }
00717         SetDParam(0, i->accepts_cargo[j]);
00718         SetDParam(1, i->incoming_cargo_waiting[j]);
00719         SetDParamStr(2, cargo_suffix[j]);
00720         DrawString(left + WD_FRAMETEXT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_WAITING_STOCKPILE_CARGO);
00721         y += FONT_HEIGHT_NORMAL;
00722       }
00723     } else {
00724       GetAllCargoSuffixes(0, CST_VIEW, i, i->type, ind, i->accepts_cargo, cargo_suffix);
00725       StringID str = STR_INDUSTRY_VIEW_REQUIRES_CARGO;
00726       byte p = 0;
00727       for (byte j = 0; j < lengthof(i->accepts_cargo); j++) {
00728         if (i->accepts_cargo[j] == CT_INVALID) continue;
00729         has_accept = true;
00730         if (p > 0) str++;
00731         SetDParam(p++, CargoSpec::Get(i->accepts_cargo[j])->name);
00732         SetDParamStr(p++, cargo_suffix[j]);
00733       }
00734       if (has_accept) {
00735         DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, str);
00736         y += FONT_HEIGHT_NORMAL;
00737       }
00738     }
00739 
00740     GetAllCargoSuffixes(3, CST_VIEW, i, i->type, ind, i->produced_cargo, cargo_suffix);
00741     first = true;
00742     for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
00743       if (i->produced_cargo[j] == CT_INVALID) continue;
00744       if (first) {
00745         if (has_accept) y += WD_PAR_VSEP_WIDE;
00746         DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_PRODUCTION_LAST_MONTH_TITLE);
00747         y += FONT_HEIGHT_NORMAL;
00748         if (this->editable == EA_RATE) this->production_offset_y = y;
00749         first = false;
00750       }
00751 
00752       SetDParam(0, i->produced_cargo[j]);
00753       SetDParam(1, i->last_month_production[j]);
00754       SetDParamStr(2, cargo_suffix[j]);
00755       SetDParam(3, ToPercent8(i->last_month_pct_transported[j]));
00756       uint x = left + WD_FRAMETEXT_LEFT + (this->editable == EA_RATE ? 30 : 0);
00757       DrawString(x, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_TRANSPORTED);
00758       /* Let's put out those buttons.. */
00759       if (this->editable == EA_RATE) {
00760         DrawArrowButtons(left + WD_FRAMETEXT_LEFT, y, COLOUR_YELLOW, (this->clicked_line == IL_RATE1 + j) ? this->clicked_button : 0,
00761             i->production_rate[j] > 0, i->production_rate[j] < 255);
00762       }
00763       y += FONT_HEIGHT_NORMAL;
00764     }
00765 
00766     /* Display production multiplier if editable */
00767     if (this->editable == EA_MULTIPLIER) {
00768       y += WD_PAR_VSEP_WIDE;
00769       this->production_offset_y = y;
00770       SetDParam(0, RoundDivSU(i->prod_level * 100, PRODLEVEL_DEFAULT));
00771       uint x = left + WD_FRAMETEXT_LEFT + 30;
00772       DrawString(x, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_PRODUCTION_LEVEL);
00773       DrawArrowButtons(left + WD_FRAMETEXT_LEFT, y, COLOUR_YELLOW, (this->clicked_line == IL_MULTIPLIER) ? this->clicked_button : 0,
00774           i->prod_level > PRODLEVEL_MINIMUM, i->prod_level < PRODLEVEL_MAXIMUM);
00775       y += FONT_HEIGHT_NORMAL;
00776     }
00777 
00778     /* Get the extra message for the GUI */
00779     if (HasBit(ind->callback_mask, CBM_IND_WINDOW_MORE_TEXT)) {
00780       uint16 callback_res = GetIndustryCallback(CBID_INDUSTRY_WINDOW_MORE_TEXT, 0, 0, i, i->type, i->location.tile);
00781       if (callback_res != CALLBACK_FAILED) {
00782         StringID message = GetGRFStringID(ind->grf_prop.grffile->grfid, 0xD000 + callback_res);
00783         if (message != STR_NULL && message != STR_UNDEFINED) {
00784           y += WD_PAR_VSEP_WIDE;
00785 
00786           PrepareTextRefStackUsage(6);
00787           /* Use all the available space left from where we stand up to the
00788            * end of the window. We ALSO enlarge the window if needed, so we
00789            * can 'go' wild with the bottom of the window. */
00790           y = DrawStringMultiLine(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, UINT16_MAX, message);
00791           StopTextRefStackUsage();
00792         }
00793       }
00794     }
00795     return y + WD_FRAMERECT_BOTTOM;
00796   }
00797 
00798   virtual void SetStringParameters(int widget) const
00799   {
00800     if (widget== IVW_CAPTION) SetDParam(0, this->window_number);
00801   }
00802 
00803   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00804   {
00805     if (widget == IVW_INFO) size->height = this->info_height;
00806   }
00807 
00808   virtual void OnClick(Point pt, int widget, int click_count)
00809   {
00810     switch (widget) {
00811       case IVW_INFO: {
00812         Industry *i = Industry::Get(this->window_number);
00813         InfoLine line = IL_NONE;
00814 
00815         switch (this->editable) {
00816           case EA_NONE: break;
00817 
00818           case EA_MULTIPLIER:
00819             if (IsInsideBS(pt.y, this->production_offset_y, FONT_HEIGHT_NORMAL)) line = IL_MULTIPLIER;
00820             break;
00821 
00822           case EA_RATE:
00823             if (pt.y >= this->production_offset_y) {
00824               int row = (pt.y - this->production_offset_y) / FONT_HEIGHT_NORMAL;
00825               for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
00826                 if (i->produced_cargo[j] == CT_INVALID) continue;
00827                 row--;
00828                 if (row < 0) {
00829                   line = (InfoLine)(IL_RATE1 + j);
00830                   break;
00831                 }
00832               }
00833             }
00834             break;
00835         }
00836         if (line == IL_NONE) return;
00837 
00838         NWidgetBase *nwi = this->GetWidget<NWidgetBase>(widget);
00839         int left = nwi->pos_x + WD_FRAMETEXT_LEFT;
00840         int right = nwi->pos_x + nwi->current_x - 1 - WD_FRAMERECT_RIGHT;
00841         if (IsInsideMM(pt.x, left, left + 20)) {
00842           /* Clicked buttons, decrease or increase production */
00843           byte button = (pt.x < left + 10) ? 1 : 2;
00844           switch (this->editable) {
00845             case EA_MULTIPLIER:
00846               if (button == 1) {
00847                 if (i->prod_level <= PRODLEVEL_MINIMUM) return;
00848                 i->prod_level = max<uint>(i->prod_level / 2, PRODLEVEL_MINIMUM);
00849               } else {
00850                 if (i->prod_level >= PRODLEVEL_MAXIMUM) return;
00851                 i->prod_level = minu(i->prod_level * 2, PRODLEVEL_MAXIMUM);
00852               }
00853               break;
00854 
00855             case EA_RATE:
00856               if (button == 1) {
00857                 if (i->production_rate[line - IL_RATE1] <= 0) return;
00858                 i->production_rate[line - IL_RATE1] = max(i->production_rate[line - IL_RATE1] / 2, 0);
00859               } else {
00860                 if (i->production_rate[line - IL_RATE1] >= 255) return;
00861                 /* a zero production industry is unlikely to give anything but zero, so push it a little bit */
00862                 int new_prod = i->production_rate[line - IL_RATE1] == 0 ? 1 : i->production_rate[line - IL_RATE1] * 2;
00863                 i->production_rate[line - IL_RATE1] = minu(new_prod, 255);
00864               }
00865               break;
00866 
00867             default: NOT_REACHED();
00868           }
00869 
00870           UpdateIndustryProduction(i);
00871           this->SetDirty();
00872           this->flags4 |= WF_TIMEOUT_BEGIN;
00873           this->clicked_line = line;
00874           this->clicked_button = button;
00875         } else if (IsInsideMM(pt.x, left + 30, right)) {
00876           /* clicked the text */
00877           this->editbox_line = line;
00878           switch (this->editable) {
00879             case EA_MULTIPLIER:
00880               SetDParam(0, RoundDivSU(i->prod_level * 100, PRODLEVEL_DEFAULT));
00881               ShowQueryString(STR_JUST_INT, STR_CONFIG_GAME_PRODUCTION_LEVEL, 10, 100, this, CS_ALPHANUMERAL, QSF_NONE);
00882               break;
00883 
00884             case EA_RATE:
00885               SetDParam(0, i->production_rate[line - IL_RATE1] * 8);
00886               ShowQueryString(STR_JUST_INT, STR_CONFIG_GAME_PRODUCTION, 10, 100, this, CS_ALPHANUMERAL, QSF_NONE);
00887               break;
00888 
00889             default: NOT_REACHED();
00890           }
00891         }
00892         break;
00893       }
00894 
00895       case IVW_GOTO: {
00896         Industry *i = Industry::Get(this->window_number);
00897         if (_ctrl_pressed) {
00898           ShowExtraViewPortWindow(i->location.GetCenterTile());
00899         } else {
00900           ScrollMainWindowToTile(i->location.GetCenterTile());
00901         }
00902         break;
00903       }
00904 
00905       case IVW_DISPLAY: {
00906         Industry *i = Industry::Get(this->window_number);
00907         ShowIndustryCargoesWindow(i->type);
00908         break;
00909       }
00910     }
00911   }
00912 
00913   virtual void OnTimeout()
00914   {
00915     this->clicked_line = IL_NONE;
00916     this->clicked_button = 0;
00917     this->SetDirty();
00918   }
00919 
00920   virtual void OnResize()
00921   {
00922     if (this->viewport != NULL) {
00923       NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(IVW_VIEWPORT);
00924       nvp->UpdateViewportCoordinates(this);
00925 
00926       ScrollWindowToTile(Industry::Get(this->window_number)->location.GetCenterTile(), this, true); // Re-center viewport.
00927     }
00928   }
00929 
00930   virtual void OnQueryTextFinished(char *str)
00931   {
00932     if (StrEmpty(str)) return;
00933 
00934     Industry *i = Industry::Get(this->window_number);
00935     uint value = atoi(str);
00936     switch (this->editbox_line) {
00937       case IL_NONE: NOT_REACHED();
00938 
00939       case IL_MULTIPLIER:
00940         i->prod_level = ClampU(RoundDivSU(value * PRODLEVEL_DEFAULT, 100), PRODLEVEL_MINIMUM, PRODLEVEL_MAXIMUM);
00941         break;
00942 
00943       default:
00944         i->production_rate[this->editbox_line - IL_RATE1] = ClampU(RoundDivSU(value, 8), 0, 255);
00945         break;
00946     }
00947     UpdateIndustryProduction(i);
00948     this->SetDirty();
00949   }
00950 
00951   virtual void OnInvalidateData(int data)
00952   {
00953     const Industry *i = Industry::Get(this->window_number);
00954     if (IsProductionAlterable(i)) {
00955       const IndustrySpec *ind = GetIndustrySpec(i->type);
00956       this->editable = ind->UsesSmoothEconomy() ? EA_RATE : EA_MULTIPLIER;
00957     } else {
00958       this->editable = EA_NONE;
00959     }
00960   }
00961 
00962   virtual bool IsNewGRFInspectable() const
00963   {
00964     return ::IsNewGRFInspectable(GSF_INDUSTRIES, this->window_number);
00965   }
00966 
00967   virtual void ShowNewGRFInspectWindow() const
00968   {
00969 		::ShowNewGRFInspectWindow(GSF_INDUSTRIES, this->window_number);
00970   }
00971 };
00972 
00973 static void UpdateIndustryProduction(Industry *i)
00974 {
00975   const IndustrySpec *indspec = GetIndustrySpec(i->type);
00976   if (!indspec->UsesSmoothEconomy()) i->RecomputeProductionMultipliers();
00977 
00978   for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
00979     if (i->produced_cargo[j] != CT_INVALID) {
00980       i->last_month_production[j] = 8 * i->production_rate[j];
00981     }
00982   }
00983 }
00984 
00986 static const NWidgetPart _nested_industry_view_widgets[] = {
00987   NWidget(NWID_HORIZONTAL),
00988     NWidget(WWT_CLOSEBOX, COLOUR_CREAM),
00989     NWidget(WWT_CAPTION, COLOUR_CREAM, IVW_CAPTION), SetDataTip(STR_INDUSTRY_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00990     NWidget(WWT_DEBUGBOX, COLOUR_CREAM),
00991     NWidget(WWT_SHADEBOX, COLOUR_CREAM),
00992     NWidget(WWT_STICKYBOX, COLOUR_CREAM),
00993   EndContainer(),
00994   NWidget(WWT_PANEL, COLOUR_CREAM),
00995     NWidget(WWT_INSET, COLOUR_CREAM), SetPadding(2, 2, 2, 2),
00996       NWidget(NWID_VIEWPORT, INVALID_COLOUR, IVW_VIEWPORT), SetMinimalSize(254, 86), SetFill(1, 0), SetPadding(1, 1, 1, 1), SetResize(1, 1),
00997     EndContainer(),
00998   EndContainer(),
00999   NWidget(WWT_PANEL, COLOUR_CREAM, IVW_INFO), SetMinimalSize(260, 2), SetResize(1, 0),
01000   EndContainer(),
01001   NWidget(NWID_HORIZONTAL),
01002     NWidget(WWT_PUSHTXTBTN, COLOUR_CREAM, IVW_GOTO), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_BUTTON_LOCATION, STR_INDUSTRY_VIEW_LOCATION_TOOLTIP),
01003     NWidget(WWT_PUSHTXTBTN, COLOUR_CREAM, IVW_DISPLAY), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_INDUSTRY_DISPLAY_CHAIN, STR_INDUSTRY_DISPLAY_CHAIN_TOOLTIP),
01004     NWidget(WWT_RESIZEBOX, COLOUR_CREAM),
01005   EndContainer(),
01006 };
01007 
01009 static const WindowDesc _industry_view_desc(
01010   WDP_AUTO, 260, 120,
01011   WC_INDUSTRY_VIEW, WC_NONE,
01012   WDF_UNCLICK_BUTTONS,
01013   _nested_industry_view_widgets, lengthof(_nested_industry_view_widgets)
01014 );
01015 
01016 void ShowIndustryViewWindow(int industry)
01017 {
01018   AllocateWindowDescFront<IndustryViewWindow>(&_industry_view_desc, industry);
01019 }
01020 
01022 enum IndustryDirectoryWidgets {
01023   IDW_DROPDOWN_ORDER,
01024   IDW_DROPDOWN_CRITERIA,
01025   IDW_INDUSTRY_LIST,
01026   IDW_SCROLLBAR,
01027 };
01028 
01030 static const NWidgetPart _nested_industry_directory_widgets[] = {
01031   NWidget(NWID_HORIZONTAL),
01032     NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
01033     NWidget(WWT_CAPTION, COLOUR_BROWN), SetDataTip(STR_INDUSTRY_DIRECTORY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
01034     NWidget(WWT_SHADEBOX, COLOUR_BROWN),
01035     NWidget(WWT_STICKYBOX, COLOUR_BROWN),
01036   EndContainer(),
01037   NWidget(NWID_HORIZONTAL),
01038     NWidget(NWID_VERTICAL),
01039       NWidget(NWID_HORIZONTAL),
01040         NWidget(WWT_TEXTBTN, COLOUR_BROWN, IDW_DROPDOWN_ORDER), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
01041         NWidget(WWT_DROPDOWN, COLOUR_BROWN, IDW_DROPDOWN_CRITERIA), SetDataTip(STR_JUST_STRING, STR_TOOLTIP_SORT_CRITERIA),
01042         NWidget(WWT_PANEL, COLOUR_BROWN), SetResize(1, 0), EndContainer(),
01043       EndContainer(),
01044       NWidget(WWT_PANEL, COLOUR_BROWN, IDW_INDUSTRY_LIST), SetDataTip(0x0, STR_INDUSTRY_DIRECTORY_LIST_CAPTION), SetResize(1, 1), SetScrollbar(IDW_SCROLLBAR), EndContainer(),
01045     EndContainer(),
01046     NWidget(NWID_VERTICAL),
01047       NWidget(NWID_VSCROLLBAR, COLOUR_BROWN, IDW_SCROLLBAR),
01048       NWidget(WWT_RESIZEBOX, COLOUR_BROWN),
01049     EndContainer(),
01050   EndContainer(),
01051 };
01052 
01053 typedef GUIList<const Industry*> GUIIndustryList;
01054 
01055 
01059 class IndustryDirectoryWindow : public Window {
01060 protected:
01061   /* Runtime saved values */
01062   static Listing last_sorting;
01063   static const Industry *last_industry;
01064 
01065   /* Constants for sorting stations */
01066   static const StringID sorter_names[];
01067   static GUIIndustryList::SortFunction * const sorter_funcs[];
01068 
01069   GUIIndustryList industries;
01070   Scrollbar *vscroll;
01071 
01073   void BuildSortIndustriesList()
01074   {
01075     if (this->industries.NeedRebuild()) {
01076       this->industries.Clear();
01077 
01078       const Industry *i;
01079       FOR_ALL_INDUSTRIES(i) {
01080         *this->industries.Append() = i;
01081       }
01082 
01083       this->industries.Compact();
01084       this->industries.RebuildDone();
01085       this->vscroll->SetCount(this->industries.Length()); // Update scrollbar as well.
01086     }
01087 
01088     if (!this->industries.Sort()) return;
01089     IndustryDirectoryWindow::last_industry = NULL; // Reset name sorter sort cache
01090     this->SetWidgetDirty(IDW_INDUSTRY_LIST); // Set the modified widget dirty
01091   }
01092 
01100   static inline int GetCargoTransportedPercentsIfValid(const Industry *i, uint id)
01101   {
01102     assert(id < lengthof(i->produced_cargo));
01103 
01104     if (i->produced_cargo[id] == CT_INVALID) return 101;
01105     return ToPercent8(i->last_month_pct_transported[id]);
01106   }
01107 
01115   static int GetCargoTransportedSortValue(const Industry *i)
01116   {
01117     int p1 = GetCargoTransportedPercentsIfValid(i, 0);
01118     int p2 = GetCargoTransportedPercentsIfValid(i, 1);
01119 
01120     if (p1 > p2) Swap(p1, p2); // lower value has higher priority
01121 
01122     return (p1 << 8) + p2;
01123   }
01124 
01126   static int CDECL IndustryNameSorter(const Industry * const *a, const Industry * const *b)
01127   {
01128     static char buf_cache[96];
01129     static char buf[96];
01130 
01131     SetDParam(0, (*a)->index);
01132     GetString(buf, STR_INDUSTRY_NAME, lastof(buf));
01133 
01134     if (*b != last_industry) {
01135       last_industry = *b;
01136       SetDParam(0, (*b)->index);
01137       GetString(buf_cache, STR_INDUSTRY_NAME, lastof(buf_cache));
01138     }
01139 
01140     return strnatcmp(buf, buf_cache); // Sort by name (natural sorting).
01141   }
01142 
01144   static int CDECL IndustryTypeSorter(const Industry * const *a, const Industry * const *b)
01145   {
01146     int it_a = 0;
01147     while (it_a != NUM_INDUSTRYTYPES && (*a)->type != _sorted_industry_types[it_a]) it_a++;
01148     int it_b = 0;
01149     while (it_b != NUM_INDUSTRYTYPES && (*b)->type != _sorted_industry_types[it_b]) it_b++;
01150     int r = it_a - it_b;
01151     return (r == 0) ? IndustryNameSorter(a, b) : r;
01152   }
01153 
01155   static int CDECL IndustryProductionSorter(const Industry * const *a, const Industry * const *b)
01156   {
01157     uint prod_a = 0, prod_b = 0;
01158     for (uint i = 0; i < lengthof((*a)->produced_cargo); i++) {
01159       if ((*a)->produced_cargo[i] != CT_INVALID) prod_a += (*a)->last_month_production[i];
01160       if ((*b)->produced_cargo[i] != CT_INVALID) prod_b += (*b)->last_month_production[i];
01161     }
01162     int r = prod_a - prod_b;
01163 
01164     return (r == 0) ? IndustryTypeSorter(a, b) : r;
01165   }
01166 
01168   static int CDECL IndustryTransportedCargoSorter(const Industry * const *a, const Industry * const *b)
01169   {
01170     int r = GetCargoTransportedSortValue(*a) - GetCargoTransportedSortValue(*b);
01171     return (r == 0) ? IndustryNameSorter(a, b) : r;
01172   }
01173 
01179   StringID GetIndustryString(const Industry *i) const
01180   {
01181     const IndustrySpec *indsp = GetIndustrySpec(i->type);
01182     byte p = 0;
01183 
01184     /* Industry name */
01185     SetDParam(p++, i->index);
01186 
01187     static char cargo_suffix[lengthof(i->produced_cargo)][512];
01188     GetAllCargoSuffixes(3, CST_DIR, i, i->type, indsp, i->produced_cargo, cargo_suffix);
01189 
01190     /* Industry productions */
01191     for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
01192       if (i->produced_cargo[j] == CT_INVALID) continue;
01193       SetDParam(p++, i->produced_cargo[j]);
01194       SetDParam(p++, i->last_month_production[j]);
01195       SetDParamStr(p++, cargo_suffix[j]);
01196     }
01197 
01198     /* Transported productions */
01199     for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
01200       if (i->produced_cargo[j] == CT_INVALID) continue;
01201       SetDParam(p++, ToPercent8(i->last_month_pct_transported[j]));
01202     }
01203 
01204     /* Drawing the right string */
01205     switch (p) {
01206       case 1:  return STR_INDUSTRY_DIRECTORY_ITEM_NOPROD;
01207       case 5:  return STR_INDUSTRY_DIRECTORY_ITEM;
01208       default: return STR_INDUSTRY_DIRECTORY_ITEM_TWO;
01209     }
01210   }
01211 
01212 public:
01213   IndustryDirectoryWindow(const WindowDesc *desc, WindowNumber number) : Window()
01214   {
01215     this->CreateNestedTree(desc);
01216     this->vscroll = this->GetScrollbar(IDW_SCROLLBAR);
01217 
01218     this->industries.SetListing(this->last_sorting);
01219     this->industries.SetSortFuncs(IndustryDirectoryWindow::sorter_funcs);
01220     this->industries.ForceRebuild();
01221     this->BuildSortIndustriesList();
01222 
01223     this->FinishInitNested(desc, 0);
01224   }
01225 
01226   ~IndustryDirectoryWindow()
01227   {
01228     this->last_sorting = this->industries.GetListing();
01229   }
01230 
01231   virtual void SetStringParameters(int widget) const
01232   {
01233     if (widget == IDW_DROPDOWN_CRITERIA) SetDParam(0, IndustryDirectoryWindow::sorter_names[this->industries.SortType()]);
01234   }
01235 
01236   virtual void DrawWidget(const Rect &r, int widget) const
01237   {
01238     switch (widget) {
01239       case IDW_DROPDOWN_ORDER:
01240         this->DrawSortButtonState(widget, this->industries.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
01241         break;
01242 
01243       case IDW_INDUSTRY_LIST: {
01244         int n = 0;
01245         int y = r.top + WD_FRAMERECT_TOP;
01246         if (this->industries.Length() == 0) {
01247           DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_DIRECTORY_NONE);
01248           break;
01249         }
01250         for (uint i = this->vscroll->GetPosition(); i < this->industries.Length(); i++) {
01251           DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, this->GetIndustryString(this->industries[i]));
01252 
01253           y += this->resize.step_height;
01254           if (++n == this->vscroll->GetCapacity()) break; // max number of industries in 1 window
01255         }
01256         break;
01257       }
01258     }
01259   }
01260 
01261   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01262   {
01263     switch (widget) {
01264       case IDW_DROPDOWN_ORDER: {
01265         Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
01266         d.width += padding.width + WD_SORTBUTTON_ARROW_WIDTH * 2; // Doubled since the string is centred and it also looks better.
01267         d.height += padding.height;
01268         *size = maxdim(*size, d);
01269         break;
01270       }
01271 
01272       case IDW_DROPDOWN_CRITERIA: {
01273         Dimension d = {0, 0};
01274         for (uint i = 0; IndustryDirectoryWindow::sorter_names[i] != INVALID_STRING_ID; i++) {
01275           d = maxdim(d, GetStringBoundingBox(IndustryDirectoryWindow::sorter_names[i]));
01276         }
01277         d.width += padding.width;
01278         d.height += padding.height;
01279         *size = maxdim(*size, d);
01280         break;
01281       }
01282 
01283       case IDW_INDUSTRY_LIST: {
01284         Dimension d = GetStringBoundingBox(STR_INDUSTRY_DIRECTORY_NONE);
01285         for (uint i = 0; i < this->industries.Length(); i++) {
01286           d = maxdim(d, GetStringBoundingBox(this->GetIndustryString(this->industries[i])));
01287         }
01288         resize->height = d.height;
01289         d.height *= 5;
01290         d.width += padding.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
01291         d.height += padding.height + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
01292         *size = maxdim(*size, d);
01293         break;
01294       }
01295     }
01296   }
01297 
01298 
01299   virtual void OnClick(Point pt, int widget, int click_count)
01300   {
01301     switch (widget) {
01302       case IDW_DROPDOWN_ORDER:
01303         this->industries.ToggleSortOrder();
01304         this->SetDirty();
01305         break;
01306 
01307       case IDW_DROPDOWN_CRITERIA:
01308         ShowDropDownMenu(this, IndustryDirectoryWindow::sorter_names, this->industries.SortType(), IDW_DROPDOWN_CRITERIA, 0, 0);
01309         break;
01310 
01311       case IDW_INDUSTRY_LIST: {
01312         uint p = this->vscroll->GetScrolledRowFromWidget(pt.y, this, IDW_INDUSTRY_LIST, WD_FRAMERECT_TOP);
01313         if (p < this->industries.Length()) {
01314           if (_ctrl_pressed) {
01315             ShowExtraViewPortWindow(this->industries[p]->location.tile);
01316           } else {
01317             ScrollMainWindowToTile(this->industries[p]->location.tile);
01318           }
01319         }
01320         break;
01321       }
01322     }
01323   }
01324 
01325   virtual void OnDropdownSelect(int widget, int index)
01326   {
01327     if (this->industries.SortType() != index) {
01328       this->industries.SetSortType(index);
01329       this->BuildSortIndustriesList();
01330     }
01331   }
01332 
01333   virtual void OnResize()
01334   {
01335     this->vscroll->SetCapacityFromWidget(this, IDW_INDUSTRY_LIST);
01336   }
01337 
01338   virtual void OnHundredthTick()
01339   {
01340     this->industries.ForceResort();
01341     this->BuildSortIndustriesList();
01342   }
01343 
01344   virtual void OnInvalidateData(int data)
01345   {
01346     if (data == 0) {
01347       this->industries.ForceRebuild();
01348     } else {
01349       this->industries.ForceResort();
01350     }
01351     this->BuildSortIndustriesList();
01352   }
01353 };
01354 
01355 Listing IndustryDirectoryWindow::last_sorting = {false, 0};
01356 const Industry *IndustryDirectoryWindow::last_industry = NULL;
01357 
01358 /* Available station sorting functions. */
01359 GUIIndustryList::SortFunction * const IndustryDirectoryWindow::sorter_funcs[] = {
01360   &IndustryNameSorter,
01361   &IndustryTypeSorter,
01362   &IndustryProductionSorter,
01363   &IndustryTransportedCargoSorter
01364 };
01365 
01366 /* Names of the sorting functions */
01367 const StringID IndustryDirectoryWindow::sorter_names[] = {
01368   STR_SORT_BY_NAME,
01369   STR_SORT_BY_TYPE,
01370   STR_SORT_BY_PRODUCTION,
01371   STR_SORT_BY_TRANSPORTED,
01372   INVALID_STRING_ID
01373 };
01374 
01375 
01377 static const WindowDesc _industry_directory_desc(
01378   WDP_AUTO, 428, 190,
01379   WC_INDUSTRY_DIRECTORY, WC_NONE,
01380   WDF_UNCLICK_BUTTONS,
01381   _nested_industry_directory_widgets, lengthof(_nested_industry_directory_widgets)
01382 );
01383 
01384 void ShowIndustryDirectory()
01385 {
01386   AllocateWindowDescFront<IndustryDirectoryWindow>(&_industry_directory_desc, 0);
01387 }
01388 
01390 enum IndustryCargoesWidgets {
01391   ICW_CAPTION,
01392   ICW_NOTIFY,
01393   ICW_PANEL,
01394   ICW_SCROLLBAR,
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, ICW_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, ICW_PANEL), SetResize(1, 10), SetMinimalSize(200, 90), SetScrollbar(ICW_SCROLLBAR), EndContainer(),
01408       NWidget(NWID_HORIZONTAL),
01409         NWidget(WWT_TEXTBTN, COLOUR_BROWN, ICW_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, ICW_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,     0); // 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 = 191; 
01881 const int CargoesField::CARGO_LINE_COLOUR    = 191; 
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(ICW_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 != ICW_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 != ICW_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(ICW_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>(ICW_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>(ICW_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>(ICW_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>(ICW_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 
02395   virtual void OnInvalidateData(int data)
02396   {
02397     if (data == NUM_INDUSTRYTYPES) {
02398       if (this->IsWidgetLowered(ICW_NOTIFY)) {
02399         this->RaiseWidget(ICW_NOTIFY);
02400         this->SetWidgetDirty(ICW_NOTIFY);
02401       }
02402       return;
02403     }
02404 
02405     assert(data >= 0 && data < NUM_INDUSTRYTYPES);
02406     this->ComputeIndustryDisplay(data);
02407   }
02408 
02409   virtual void DrawWidget(const Rect &r, int widget) const
02410   {
02411     if (widget != ICW_PANEL) return;
02412 
02413     DrawPixelInfo tmp_dpi, *old_dpi;
02414     int width = r.right - r.left + 1;
02415     int height = r.bottom - r.top + 1 - WD_FRAMERECT_TOP - WD_FRAMERECT_BOTTOM;
02416     if (!FillDrawPixelInfo(&tmp_dpi, r.left + WD_FRAMERECT_LEFT, r.top + WD_FRAMERECT_TOP, width, height)) return;
02417     old_dpi = _cur_dpi;
02418     _cur_dpi = &tmp_dpi;
02419 
02420     int left_pos = WD_FRAMERECT_LEFT;
02421     if (this->ind_cargo >= NUM_INDUSTRYTYPES) left_pos += (CargoesField::industry_width + CargoesField::CARGO_FIELD_WIDTH) / 2;
02422     int last_column = (this->ind_cargo < NUM_INDUSTRYTYPES) ? 4 : 2;
02423 
02424     const NWidgetBase *nwp = this->GetWidget<NWidgetBase>(ICW_PANEL);
02425     int vpos = -this->vscroll->GetPosition() * nwp->resize_y;
02426     for (uint i = 0; i < this->fields.Length(); i++) {
02427       int row_height = (i == 0) ? CargoesField::small_height : CargoesField::normal_height;
02428       if (vpos + row_height >= 0) {
02429         int xpos = left_pos;
02430         int col, dir;
02431         if (_current_text_dir == TD_RTL) {
02432           col = last_column;
02433           dir = -1;
02434         } else {
02435           col = 0;
02436           dir = 1;
02437         }
02438         while (col >= 0 && col <= last_column) {
02439           this->fields[i].columns[col].Draw(xpos, vpos);
02440           xpos += (col & 1) ? CargoesField::CARGO_FIELD_WIDTH : CargoesField::industry_width;
02441           col += dir;
02442         }
02443       }
02444       vpos += row_height;
02445       if (vpos >= height) break;
02446     }
02447 
02448     _cur_dpi = old_dpi;
02449   }
02450 
02458   bool CalculatePositionInWidget(Point pt, Point *fieldxy, Point *xy)
02459   {
02460     const NWidgetBase *nw = this->GetWidget<NWidgetBase>(ICW_PANEL);
02461     pt.x -= nw->pos_x;
02462     pt.y -= nw->pos_y;
02463 
02464     int vpos = WD_FRAMERECT_TOP + CargoesField::small_height - this->vscroll->GetPosition() * nw->resize_y;
02465     if (pt.y < vpos) return false;
02466 
02467     int row = (pt.y - vpos) / CargoesField::normal_height; // row is relative to row 1.
02468     if (row + 1 >= (int)this->fields.Length()) return false;
02469     vpos = pt.y - vpos - row * CargoesField::normal_height; // Position in the row + 1 field
02470     row++; // rebase row to match index of this->fields.
02471 
02472     int xpos = 2 * WD_FRAMERECT_LEFT + ((this->ind_cargo < NUM_INDUSTRYTYPES) ? 0 :  (CargoesField::industry_width + CargoesField::CARGO_FIELD_WIDTH) / 2);
02473     if (pt.x < xpos) return false;
02474     int column;
02475     for (column = 0; column <= 5; column++) {
02476       int width = (column & 1) ? CargoesField::CARGO_FIELD_WIDTH : CargoesField::industry_width;
02477       if (pt.x < xpos + width) break;
02478       xpos += width;
02479     }
02480     int num_columns = (this->ind_cargo < NUM_INDUSTRYTYPES) ? 4 : 2;
02481     if (column > num_columns) return false;
02482     xpos = pt.x - xpos;
02483 
02484     /* Return both positions, compensating for RTL languages (which works due to the equal symmetry in both displays). */
02485     fieldxy->y = row;
02486     xy->y = vpos;
02487     if (_current_text_dir == TD_RTL) {
02488       fieldxy->x = num_columns - column;
02489       xy->x = ((column & 1) ? CargoesField::CARGO_FIELD_WIDTH : CargoesField::industry_width) - xpos;
02490     } else {
02491       fieldxy->x = column;
02492       xy->x = xpos;
02493     }
02494     return true;
02495   }
02496 
02497   virtual void OnClick(Point pt, int widget, int click_count)
02498   {
02499     switch (widget) {
02500       case ICW_PANEL: {
02501         Point fieldxy, xy;
02502         if (!CalculatePositionInWidget(pt, &fieldxy, &xy)) return;
02503 
02504         const CargoesField *fld = this->fields[fieldxy.y].columns + fieldxy.x;
02505         switch (fld->type) {
02506           case CFT_INDUSTRY:
02507             if (fld->u.industry.ind_type < NUM_INDUSTRYTYPES) this->ComputeIndustryDisplay(fld->u.industry.ind_type);
02508             break;
02509 
02510           case CFT_CARGO: {
02511             CargoesField *lft = (fieldxy.x > 0) ? this->fields[fieldxy.y].columns + fieldxy.x - 1 : NULL;
02512             CargoesField *rgt = (fieldxy.x < 4) ? this->fields[fieldxy.y].columns + fieldxy.x + 1 : NULL;
02513             CargoID cid = fld->CargoClickedAt(lft, rgt, xy);
02514             if (cid != INVALID_CARGO) this->ComputeCargoDisplay(cid);
02515             break;
02516           }
02517 
02518           case CFT_CARGO_LABEL: {
02519             CargoID cid = fld->CargoLabelClickedAt(xy);
02520             if (cid != INVALID_CARGO) this->ComputeCargoDisplay(cid);
02521             break;
02522           }
02523 
02524           default:
02525             break;
02526         }
02527         break;
02528       }
02529 
02530       case ICW_NOTIFY:
02531         this->ToggleWidgetLoweredState(ICW_NOTIFY);
02532         this->SetWidgetDirty(ICW_NOTIFY);
02533         SndPlayFx(SND_15_BEEP);
02534 
02535         if (this->IsWidgetLowered(ICW_NOTIFY)) {
02536           if (FindWindowByClass(WC_SMALLMAP) == NULL) ShowSmallMap();
02537           this->NotifySmallmap();
02538         }
02539         break;
02540     }
02541   }
02542 
02543   virtual void OnHover(Point pt, int widget)
02544   {
02545     if (widget != ICW_PANEL) return;
02546 
02547     Point fieldxy, xy;
02548     if (!CalculatePositionInWidget(pt, &fieldxy, &xy)) return;
02549 
02550     const CargoesField *fld = this->fields[fieldxy.y].columns + fieldxy.x;
02551     CargoID cid = INVALID_CARGO;
02552     switch (fld->type) {
02553       case CFT_CARGO: {
02554         CargoesField *lft = (fieldxy.x > 0) ? this->fields[fieldxy.y].columns + fieldxy.x - 1 : NULL;
02555         CargoesField *rgt = (fieldxy.x < 4) ? this->fields[fieldxy.y].columns + fieldxy.x + 1 : NULL;
02556         cid = fld->CargoClickedAt(lft, rgt, xy);
02557         break;
02558       }
02559 
02560       case CFT_CARGO_LABEL: {
02561         cid = fld->CargoLabelClickedAt(xy);
02562         break;
02563       }
02564 
02565       case CFT_INDUSTRY:
02566         if (fld->u.industry.ind_type < NUM_INDUSTRYTYPES && (this->ind_cargo >= NUM_INDUSTRYTYPES || fieldxy.x != 2)) {
02567           GuiShowTooltips(this, STR_INDUSTRY_CARGOES_INDUSTRY_TOOLTIP, 0, NULL, TCC_HOVER);
02568         }
02569         return;
02570 
02571       default:
02572         break;
02573     }
02574     if (cid != INVALID_CARGO && (this->ind_cargo < NUM_INDUSTRYTYPES || cid != this->ind_cargo - NUM_INDUSTRYTYPES)) {
02575       const CargoSpec *csp = CargoSpec::Get(cid);
02576       uint64 params[5];
02577       params[0] = csp->name;
02578       GuiShowTooltips(this, STR_INDUSTRY_CARGOES_CARGO_TOOLTIP, 1, params, TCC_HOVER);
02579     }
02580   }
02581 
02582   virtual void OnResize()
02583   {
02584     this->vscroll->SetCapacityFromWidget(this, ICW_PANEL);
02585   }
02586 };
02587 
02588 const int IndustryCargoesWindow::HOR_TEXT_PADDING  = 5; 
02589 const int IndustryCargoesWindow::VERT_TEXT_PADDING = 5; 
02590 
02595 static void ShowIndustryCargoesWindow(IndustryType id)
02596 {
02597   assert(id < NUM_INDUSTRYTYPES);
02598 
02599   Window *w = BringWindowToFrontById(WC_INDUSTRY_CARGOES, 0);
02600   if (w != NULL) {
02601     w->InvalidateData(id);
02602     return;
02603   }
02604   new IndustryCargoesWindow(id);
02605 }

Generated on Sun Jan 9 16:01:55 2011 for OpenTTD by  doxygen 1.6.1