industry_gui.cpp

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

Generated on Fri Mar 4 21:36:59 2011 for OpenTTD by  doxygen 1.6.1