graph_gui.cpp

Go to the documentation of this file.
00001 /* $Id: graph_gui.cpp 21048 2010-10-27 20:17:45Z rubidium $ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 #include "openttd.h"
00014 #include "graph_gui.h"
00015 #include "window_gui.h"
00016 #include "company_base.h"
00017 #include "company_gui.h"
00018 #include "economy_func.h"
00019 #include "cargotype.h"
00020 #include "strings_func.h"
00021 #include "window_func.h"
00022 #include "date_func.h"
00023 #include "gfx_func.h"
00024 #include "sortlist_type.h"
00025 #include "core/geometry_func.hpp"
00026 #include "currency.h"
00027 
00028 #include "table/strings.h"
00029 #include "table/sprites.h"
00030 
00031 /* Bitmasks of company and cargo indices that shouldn't be drawn. */
00032 static uint _legend_excluded_companies;
00033 static uint _legend_excluded_cargo;
00034 
00035 /* Apparently these don't play well with enums. */
00036 static const OverflowSafeInt64 INVALID_DATAPOINT(INT64_MAX); // Value used for a datapoint that shouldn't be drawn.
00037 static const uint INVALID_DATAPOINT_POS = UINT_MAX;  // Used to determine if the previous point was drawn.
00038 
00039 /****************/
00040 /* GRAPH LEGEND */
00041 /****************/
00042 
00044 enum GraphLegendWidgetNumbers {
00045   GLW_BACKGROUND,
00046 
00047   GLW_FIRST_COMPANY,
00048   GLW_LAST_COMPANY = GLW_FIRST_COMPANY + MAX_COMPANIES - 1,
00049 };
00050 
00051 struct GraphLegendWindow : Window {
00052   GraphLegendWindow(const WindowDesc *desc, WindowNumber window_number) : Window()
00053   {
00054     this->InitNested(desc, window_number);
00055 
00056     for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
00057       if (!HasBit(_legend_excluded_companies, c)) this->LowerWidget(c + GLW_FIRST_COMPANY);
00058 
00059       this->OnInvalidateData(c);
00060     }
00061   }
00062 
00063   virtual void OnPaint()
00064   {
00065     this->DrawWidgets();
00066   }
00067 
00068   virtual void DrawWidget(const Rect &r, int widget) const
00069   {
00070     if (!IsInsideMM(widget, GLW_FIRST_COMPANY, MAX_COMPANIES + GLW_FIRST_COMPANY)) return;
00071 
00072     CompanyID cid = (CompanyID)(widget - GLW_FIRST_COMPANY);
00073 
00074     if (!Company::IsValidID(cid)) return;
00075 
00076     bool rtl = _dynlang.text_dir == TD_RTL;
00077 
00078     DrawCompanyIcon(cid, rtl ? r.right - 16 : r.left + 2, r.top + 2 + (FONT_HEIGHT_NORMAL - 10) / 2);
00079 
00080     SetDParam(0, cid);
00081     SetDParam(1, cid);
00082     DrawString(r.left + (rtl ? WD_FRAMERECT_LEFT : 19), r.right - (rtl ? 19 : WD_FRAMERECT_RIGHT), r.top + WD_FRAMERECT_TOP, STR_COMPANY_NAME_COMPANY_NUM, HasBit(_legend_excluded_companies, cid) ? TC_BLACK : TC_WHITE);
00083   }
00084 
00085   virtual void OnClick(Point pt, int widget, int click_count)
00086   {
00087     if (!IsInsideMM(widget, GLW_FIRST_COMPANY, MAX_COMPANIES + GLW_FIRST_COMPANY)) return;
00088 
00089     ToggleBit(_legend_excluded_companies, widget - GLW_FIRST_COMPANY);
00090     this->ToggleWidgetLoweredState(widget);
00091     this->SetDirty();
00092     InvalidateWindowData(WC_INCOME_GRAPH, 0);
00093     InvalidateWindowData(WC_OPERATING_PROFIT, 0);
00094     InvalidateWindowData(WC_DELIVERED_CARGO, 0);
00095     InvalidateWindowData(WC_PERFORMANCE_HISTORY, 0);
00096     InvalidateWindowData(WC_COMPANY_VALUE, 0);
00097   }
00098 
00099   virtual void OnInvalidateData(int data)
00100   {
00101     if (Company::IsValidID(data)) return;
00102 
00103     SetBit(_legend_excluded_companies, data);
00104     this->RaiseWidget(data + GLW_FIRST_COMPANY);
00105   }
00106 };
00107 
00114 static NWidgetBase *MakeNWidgetCompanyLines(int *biggest_index)
00115 {
00116   NWidgetVertical *vert = new NWidgetVertical();
00117 
00118   for (int widnum = GLW_FIRST_COMPANY; widnum <= GLW_LAST_COMPANY; widnum++) {
00119     NWidgetBackground *panel = new NWidgetBackground(WWT_PANEL, COLOUR_GREY, widnum);
00120     panel->SetMinimalSize(246, FONT_HEIGHT_NORMAL + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
00121     panel->SetFill(1, 0);
00122     panel->SetDataTip(0x0, STR_GRAPH_KEY_COMPANY_SELECTION_TOOLTIP);
00123     vert->Add(panel);
00124   }
00125   *biggest_index = GLW_LAST_COMPANY;
00126   return vert;
00127 }
00128 
00129 static const NWidgetPart _nested_graph_legend_widgets[] = {
00130   NWidget(NWID_HORIZONTAL),
00131     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
00132     NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_GRAPH_KEY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00133     NWidget(WWT_SHADEBOX, COLOUR_GREY),
00134     NWidget(WWT_STICKYBOX, COLOUR_GREY),
00135   EndContainer(),
00136   NWidget(WWT_PANEL, COLOUR_GREY, GLW_BACKGROUND),
00137     NWidget(NWID_SPACER), SetMinimalSize(0, 2),
00138     NWidget(NWID_HORIZONTAL),
00139       NWidget(NWID_SPACER), SetMinimalSize(2, 0),
00140       NWidgetFunction(MakeNWidgetCompanyLines),
00141       NWidget(NWID_SPACER), SetMinimalSize(2, 0),
00142     EndContainer(),
00143   EndContainer(),
00144 };
00145 
00146 static const WindowDesc _graph_legend_desc(
00147   WDP_AUTO, 0, 0,
00148   WC_GRAPH_LEGEND, WC_NONE,
00149   0,
00150   _nested_graph_legend_widgets, lengthof(_nested_graph_legend_widgets)
00151 );
00152 
00153 static void ShowGraphLegend()
00154 {
00155   AllocateWindowDescFront<GraphLegendWindow>(&_graph_legend_desc, 0);
00156 }
00157 
00158 /******************/
00159 /* BASE OF GRAPHS */
00160 /*****************/
00161 
00163 enum CompanyValueWidgets {
00164   BGW_KEY_BUTTON,
00165   BGW_BACKGROUND,
00166 };
00167 
00168 struct BaseGraphWindow : Window {
00169 protected:
00170   enum {
00171     GRAPH_MAX_DATASETS = 32,
00172     GRAPH_AXIS_LINE_COLOUR  = 215,
00173     GRAPH_NUM_MONTHS = 24, 
00174 
00175     GRAPH_NUM_LINES_Y = 9, 
00176     /* 9 is convenient as that means the distance between them is the gd_height of the graph / 8,
00177      * which is the same
00178      * as height >> 3. */
00179   };
00180 
00181   uint excluded_data; 
00182   byte num_dataset;
00183   byte num_on_x_axis;
00184   bool has_negative_values;
00185   byte num_vert_lines;
00186   static const TextColour graph_axis_label_colour = TC_BLACK; 
00187 
00188   /* The starting month and year that values are plotted against. If month is
00189    * 0xFF, use x_values_start and x_values_increment below instead. */
00190   byte month;
00191   Year year;
00192 
00193   /* These values are used if the graph is being plotted against values
00194    * rather than the dates specified by month and year. */
00195   uint16 x_values_start;
00196   uint16 x_values_increment;
00197 
00198   int graph_widget;
00199   StringID format_str_y_axis;
00200   byte colours[GRAPH_MAX_DATASETS];
00201   OverflowSafeInt64 cost[GRAPH_MAX_DATASETS][GRAPH_NUM_MONTHS]; 
00202 
00208   int64 GetHighestValue() const
00209   {
00210     OverflowSafeInt64 highest_value = 0;
00211 
00212     for (int i = 0; i < this->num_dataset; i++) {
00213       if (HasBit(this->excluded_data, i)) continue;
00214       for (int j = 0; j < this->num_on_x_axis; j++) {
00215         OverflowSafeInt64 datapoint = this->cost[i][j];
00216 
00217         if (datapoint != INVALID_DATAPOINT) {
00218           /* For now, if the graph has negative values the scaling is
00219            * symmetrical about the x axis, so take the absolute value
00220            * of each data point. */
00221           highest_value = max(highest_value, abs(datapoint));
00222         }
00223       }
00224     }
00225 
00226     /* Prevent showing the highest value too close to the graph upper limit. */
00227     highest_value = (11 * highest_value) / 10;
00228     /* Avoid using zero as the highest value. */
00229     if (highest_value == 0) highest_value = GRAPH_NUM_LINES_Y - 1;
00230     /* Round up highest_value so that it will divide cleanly into the number of
00231      * axis labels used. */
00232     int round_val = highest_value % (GRAPH_NUM_LINES_Y - 1);
00233     if (round_val != 0) highest_value += (GRAPH_NUM_LINES_Y - 1 - round_val);
00234 
00235     return highest_value;
00236   }
00237 
00238   uint GetYLabelWidth(int64 highest_value) const
00239   {
00240     /* draw text strings on the y axis */
00241     int64 y_label = highest_value;
00242     int64 y_label_separation = highest_value / (GRAPH_NUM_LINES_Y - 1);
00243 
00244     /* If there are negative values, the graph goes from highest_value to
00245      * -highest_value, not highest_value to 0. */
00246     if (this->has_negative_values) y_label_separation *= 2;
00247 
00248     uint max_width = 0;
00249 
00250     for (int i = 0; i < GRAPH_NUM_LINES_Y; i++) {
00251       SetDParam(0, this->format_str_y_axis);
00252       SetDParam(1, y_label);
00253       Dimension d = GetStringBoundingBox(STR_GRAPH_Y_LABEL);
00254       if (d.width > max_width) max_width = d.width;
00255 
00256       y_label -= y_label_separation;
00257     }
00258 
00259     return max_width;
00260   }
00261 
00266   void DrawGraph(Rect r) const
00267   {
00268     uint x, y;                       
00269     OverflowSafeInt64 highest_value; 
00270     int x_axis_offset;               
00271 
00272     /* the colours and cost array of GraphDrawer must accomodate
00273      * both values for cargo and companies. So if any are higher, quit */
00274     assert_compile(GRAPH_MAX_DATASETS >= (int)NUM_CARGO && GRAPH_MAX_DATASETS >= (int)MAX_COMPANIES);
00275     assert(this->num_vert_lines > 0);
00276 
00277     byte grid_colour = _colour_gradient[COLOUR_GREY][4];
00278 
00279     /* Rect r will be adjusted to contain just the graph, with labels being
00280      * placed outside the area. */
00281     r.top    += 5 + GetCharacterHeight(FS_SMALL) / 2;
00282     r.bottom -= (this->month == 0xFF ? 1 : 3) * GetCharacterHeight(FS_SMALL) + 4;
00283     r.left   += 9;
00284     r.right  -= 5;
00285 
00286     highest_value = GetHighestValue();
00287 
00288     /* Get width for Y labels */
00289     int label_width = GetYLabelWidth(highest_value);
00290 
00291     r.left += label_width;
00292 
00293     int x_sep = (r.right - r.left) / this->num_vert_lines;
00294     int y_sep = (r.bottom - r.top) / (GRAPH_NUM_LINES_Y - 1);
00295 
00296     /* Redetermine right and bottom edge of graph to fit with the integer
00297      * separation values. */
00298     r.right = r.left + x_sep * this->num_vert_lines;
00299     r.bottom = r.top + y_sep * (GRAPH_NUM_LINES_Y - 1);
00300 
00301     /* Where to draw the X axis */
00302     x_axis_offset = r.bottom - r.top;
00303     if (this->has_negative_values) x_axis_offset /= 2;
00304 
00305     /* Draw the vertical grid lines. */
00306 
00307     /* Don't draw the first line, as that's where the axis will be. */
00308     x = r.left + x_sep;
00309 
00310     for (int i = 0; i < this->num_vert_lines; i++) {
00311       GfxFillRect(x, r.top, x, r.bottom, grid_colour);
00312       x += x_sep;
00313     }
00314 
00315     /* Draw the horizontal grid lines. */
00316     y = r.bottom;
00317 
00318     for (int i = 0; i < GRAPH_NUM_LINES_Y; i++) {
00319       GfxFillRect(r.left - 3, y, r.left - 1, y, GRAPH_AXIS_LINE_COLOUR);
00320       GfxFillRect(r.left, y, r.right, y, grid_colour);
00321       y -= y_sep;
00322     }
00323 
00324     /* Draw the y axis. */
00325     GfxFillRect(r.left, r.top, r.left, r.bottom, GRAPH_AXIS_LINE_COLOUR);
00326 
00327     /* Draw the x axis. */
00328     y = x_axis_offset + r.top;
00329     GfxFillRect(r.left, y, r.right, y, GRAPH_AXIS_LINE_COLOUR);
00330 
00331     /* Find the largest value that will be drawn. */
00332     if (this->num_on_x_axis == 0)
00333       return;
00334 
00335     assert(this->num_on_x_axis > 0);
00336     assert(this->num_dataset > 0);
00337 
00338     /* draw text strings on the y axis */
00339     int64 y_label = highest_value;
00340     int64 y_label_separation = highest_value / (GRAPH_NUM_LINES_Y - 1);
00341 
00342     /* If there are negative values, the graph goes from highest_value to
00343      * -highest_value, not highest_value to 0. */
00344     if (this->has_negative_values) y_label_separation *= 2;
00345 
00346     y = r.top - GetCharacterHeight(FS_SMALL) / 2;
00347 
00348     for (int i = 0; i < GRAPH_NUM_LINES_Y; i++) {
00349       SetDParam(0, this->format_str_y_axis);
00350       SetDParam(1, y_label);
00351       DrawString(r.left - label_width - 4, r.left - 4, y, STR_GRAPH_Y_LABEL, graph_axis_label_colour, SA_RIGHT);
00352 
00353       y_label -= y_label_separation;
00354       y += y_sep;
00355     }
00356 
00357     /* draw strings on the x axis */
00358     if (this->month != 0xFF) {
00359       x = r.left;
00360       y = r.bottom + 2;
00361       byte month = this->month;
00362       Year year  = this->year;
00363       for (int i = 0; i < this->num_on_x_axis; i++) {
00364         SetDParam(0, month + STR_MONTH_ABBREV_JAN);
00365         SetDParam(1, month + STR_MONTH_ABBREV_JAN + 2);
00366         SetDParam(2, year);
00367         DrawStringMultiLine(x, x + x_sep, y, this->height, month == 0 ? STR_GRAPH_X_LABEL_MONTH_YEAR : STR_GRAPH_X_LABEL_MONTH, graph_axis_label_colour);
00368 
00369         month += 3;
00370         if (month >= 12) {
00371           month = 0;
00372           year++;
00373         }
00374         x += x_sep;
00375       }
00376     } else {
00377       /* Draw the label under the data point rather than on the grid line. */
00378       x = r.left;
00379       y = r.bottom + 2;
00380       uint16 label = this->x_values_start;
00381 
00382       for (int i = 0; i < this->num_on_x_axis; i++) {
00383         SetDParam(0, label);
00384         DrawString(x + 1, x + x_sep - 1, y, STR_GRAPH_Y_LABEL_NUMBER, graph_axis_label_colour, SA_CENTER);
00385 
00386         label += this->x_values_increment;
00387         x += x_sep;
00388       }
00389     }
00390 
00391     /* draw lines and dots */
00392     for (int i = 0; i < this->num_dataset; i++) {
00393       if (!HasBit(this->excluded_data, i)) {
00394         /* Centre the dot between the grid lines. */
00395         x = r.left + (x_sep / 2);
00396 
00397         byte colour  = this->colours[i];
00398         uint prev_x = INVALID_DATAPOINT_POS;
00399         uint prev_y = INVALID_DATAPOINT_POS;
00400 
00401         for (int j = 0; j < this->num_on_x_axis; j++) {
00402           OverflowSafeInt64 datapoint = this->cost[i][j];
00403 
00404           if (datapoint != INVALID_DATAPOINT) {
00405             /*
00406              * Check whether we need to reduce the 'accuracy' of the
00407              * datapoint value and the highest value to splut overflows.
00408              * And when 'drawing' 'one million' or 'one million and one'
00409              * there is no significant difference, so the least
00410              * significant bits can just be removed.
00411              *
00412              * If there are more bits needed than would fit in a 32 bits
00413              * integer, so at about 31 bits because of the sign bit, the
00414              * least significant bits are removed.
00415              */
00416             int mult_range = FindLastBit(x_axis_offset) + FindLastBit(abs(datapoint));
00417             int reduce_range = max(mult_range - 31, 0);
00418 
00419             /* Handle negative values differently (don't shift sign) */
00420             if (datapoint < 0) {
00421               datapoint = -(abs(datapoint) >> reduce_range);
00422             } else {
00423               datapoint >>= reduce_range;
00424             }
00425 
00426             y = r.top + x_axis_offset - (x_axis_offset * datapoint) / (highest_value >> reduce_range);
00427 
00428             /* Draw the point. */
00429             GfxFillRect(x - 1, y - 1, x + 1, y + 1, colour);
00430 
00431             /* Draw the line connected to the previous point. */
00432             if (prev_x != INVALID_DATAPOINT_POS) GfxDrawLine(prev_x, prev_y, x, y, colour);
00433 
00434             prev_x = x;
00435             prev_y = y;
00436           } else {
00437             prev_x = INVALID_DATAPOINT_POS;
00438             prev_y = INVALID_DATAPOINT_POS;
00439           }
00440 
00441           x += x_sep;
00442         }
00443       }
00444     }
00445   }
00446 
00447 
00448   BaseGraphWindow(int widget, bool has_negative_values, StringID format_str_y_axis) :
00449       Window(), has_negative_values(has_negative_values),
00450       format_str_y_axis(format_str_y_axis)
00451   {
00452     SetWindowDirty(WC_GRAPH_LEGEND, 0);
00453     this->num_vert_lines = 24;
00454     this->graph_widget = widget;
00455   }
00456 
00457   void InitializeWindow(const WindowDesc *desc, WindowNumber number)
00458   {
00459     /* Initialise the dataset */
00460     this->UpdateStatistics(true);
00461 
00462     this->InitNested(desc, number);
00463   }
00464 
00465 public:
00466   virtual void OnPaint()
00467   {
00468     this->DrawWidgets();
00469   }
00470 
00471   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00472   {
00473     if (widget != this->graph_widget) return;
00474 
00475     uint x_label_width = 0;
00476 
00477     if (this->month != 0xFF) {
00478       byte month = this->month;
00479       Year year  = this->year;
00480       for (int i = 0; i < this->num_on_x_axis; i++) {
00481         SetDParam(0, month + STR_MONTH_ABBREV_JAN);
00482         SetDParam(1, month + STR_MONTH_ABBREV_JAN + 2);
00483         SetDParam(2, year);
00484         x_label_width = max(x_label_width, GetStringBoundingBox(month == 0 ? STR_GRAPH_X_LABEL_MONTH_YEAR : STR_GRAPH_X_LABEL_MONTH).width);
00485 
00486         month += 3;
00487         if (month >= 12) {
00488           month = 0;
00489           year++;
00490         }
00491       }
00492     } else {
00493       /* Draw the label under the data point rather than on the grid line. */
00494       SetDParam(0, this->x_values_start + this->num_on_x_axis * this->x_values_increment);
00495       x_label_width = GetStringBoundingBox(STR_GRAPH_Y_LABEL_NUMBER).width;
00496     }
00497 
00498     SetDParam(0, this->format_str_y_axis);
00499     SetDParam(1, INT64_MAX);
00500     uint y_label_width = GetStringBoundingBox(STR_GRAPH_Y_LABEL).width;
00501 
00502     size->width  = max<uint>(size->width,  5 + y_label_width + this->num_on_x_axis * (x_label_width + 5) + 9);
00503     size->height = max<uint>(size->height, 5 + (1 + GRAPH_NUM_LINES_Y * 2 + (this->month != 0xFF ? 3 : 1)) * FONT_HEIGHT_SMALL + 4);
00504     size->height = max<uint>(size->height, size->width / 3);
00505   }
00506 
00507   virtual void DrawWidget(const Rect &r, int widget) const
00508   {
00509     if (widget != this->graph_widget) return;
00510 
00511     DrawGraph(r);
00512   }
00513 
00514   virtual OverflowSafeInt64 GetGraphData(const Company *c, int j)
00515   {
00516     return INVALID_DATAPOINT;
00517   }
00518 
00519   virtual void OnClick(Point pt, int widget, int click_count)
00520   {
00521     /* Clicked on legend? */
00522     if (widget == BGW_KEY_BUTTON) ShowGraphLegend();
00523   }
00524 
00525   virtual void OnTick()
00526   {
00527     this->UpdateStatistics(false);
00528   }
00529 
00530   virtual void OnInvalidateData(int data)
00531   {
00532     this->UpdateStatistics(true);
00533   }
00534 
00539   void UpdateStatistics(bool initialize)
00540   {
00541     uint excluded_companies = _legend_excluded_companies;
00542 
00543     /* Exclude the companies which aren't valid */
00544     for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
00545       if (!Company::IsValidID(c)) SetBit(excluded_companies, c);
00546     }
00547 
00548     byte nums = 0;
00549     const Company *c;
00550     FOR_ALL_COMPANIES(c) {
00551       nums = min(this->num_vert_lines, max(nums, c->num_valid_stat_ent));
00552     }
00553 
00554     int mo = (_cur_month / 3 - nums) * 3;
00555     int yr = _cur_year;
00556     while (mo < 0) {
00557       yr--;
00558       mo += 12;
00559     }
00560 
00561     if (!initialize && this->excluded_data == excluded_companies && this->num_on_x_axis == nums &&
00562         this->year == yr && this->month == mo) {
00563       /* There's no reason to get new stats */
00564       return;
00565     }
00566 
00567     this->excluded_data = excluded_companies;
00568     this->num_on_x_axis = nums;
00569     this->year = yr;
00570     this->month = mo;
00571 
00572     int numd = 0;
00573     for (CompanyID k = COMPANY_FIRST; k < MAX_COMPANIES; k++) {
00574       c = Company::GetIfValid(k);
00575       if (c != NULL) {
00576         this->colours[numd] = _colour_gradient[c->colour][6];
00577         for (int j = this->num_on_x_axis, i = 0; --j >= 0;) {
00578           this->cost[numd][i] = (j >= c->num_valid_stat_ent) ? INVALID_DATAPOINT : GetGraphData(c, j);
00579           i++;
00580         }
00581       }
00582       numd++;
00583     }
00584 
00585     this->num_dataset = numd;
00586   }
00587 };
00588 
00589 
00590 /********************/
00591 /* OPERATING PROFIT */
00592 /********************/
00593 
00594 struct OperatingProfitGraphWindow : BaseGraphWindow {
00595   OperatingProfitGraphWindow(const WindowDesc *desc, WindowNumber window_number) :
00596       BaseGraphWindow(BGW_BACKGROUND, true, STR_JUST_CURRCOMPACT)
00597   {
00598     this->InitializeWindow(desc, window_number);
00599   }
00600 
00601   virtual OverflowSafeInt64 GetGraphData(const Company *c, int j)
00602   {
00603     return c->old_economy[j].income + c->old_economy[j].expenses;
00604   }
00605 };
00606 
00607 static const NWidgetPart _nested_operating_profit_widgets[] = {
00608   NWidget(NWID_HORIZONTAL),
00609     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
00610     NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_GRAPH_OPERATING_PROFIT_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00611     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, BGW_KEY_BUTTON), SetMinimalSize(50, 0), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetDataTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
00612     NWidget(WWT_SHADEBOX, COLOUR_GREY),
00613     NWidget(WWT_STICKYBOX, COLOUR_GREY),
00614   EndContainer(),
00615   NWidget(WWT_PANEL, COLOUR_GREY, BGW_BACKGROUND), SetMinimalSize(576, 160), EndContainer(),
00616 };
00617 
00618 static const WindowDesc _operating_profit_desc(
00619   WDP_AUTO, 0, 0,
00620   WC_OPERATING_PROFIT, WC_NONE,
00621   WDF_UNCLICK_BUTTONS,
00622   _nested_operating_profit_widgets, lengthof(_nested_operating_profit_widgets)
00623 );
00624 
00625 
00626 void ShowOperatingProfitGraph()
00627 {
00628   AllocateWindowDescFront<OperatingProfitGraphWindow>(&_operating_profit_desc, 0);
00629 }
00630 
00631 
00632 /****************/
00633 /* INCOME GRAPH */
00634 /****************/
00635 
00636 struct IncomeGraphWindow : BaseGraphWindow {
00637   IncomeGraphWindow(const WindowDesc *desc, WindowNumber window_number) :
00638       BaseGraphWindow(BGW_BACKGROUND, false, STR_JUST_CURRCOMPACT)
00639   {
00640     this->InitializeWindow(desc, window_number);
00641   }
00642 
00643   virtual OverflowSafeInt64 GetGraphData(const Company *c, int j)
00644   {
00645     return c->old_economy[j].income;
00646   }
00647 };
00648 
00649 static const NWidgetPart _nested_income_graph_widgets[] = {
00650   NWidget(NWID_HORIZONTAL),
00651     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
00652     NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_GRAPH_INCOME_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00653     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, BGW_KEY_BUTTON), SetMinimalSize(50, 0), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetDataTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
00654     NWidget(WWT_SHADEBOX, COLOUR_GREY),
00655     NWidget(WWT_STICKYBOX, COLOUR_GREY),
00656   EndContainer(),
00657   NWidget(WWT_PANEL, COLOUR_GREY, BGW_BACKGROUND), SetMinimalSize(576, 128), EndContainer(),
00658 };
00659 
00660 
00661 static const WindowDesc _income_graph_desc(
00662   WDP_AUTO, 0, 0,
00663   WC_INCOME_GRAPH, WC_NONE,
00664   WDF_UNCLICK_BUTTONS,
00665   _nested_income_graph_widgets, lengthof(_nested_income_graph_widgets)
00666 );
00667 
00668 void ShowIncomeGraph()
00669 {
00670   AllocateWindowDescFront<IncomeGraphWindow>(&_income_graph_desc, 0);
00671 }
00672 
00673 /*******************/
00674 /* DELIVERED CARGO */
00675 /*******************/
00676 
00677 struct DeliveredCargoGraphWindow : BaseGraphWindow {
00678   DeliveredCargoGraphWindow(const WindowDesc *desc, WindowNumber window_number) :
00679       BaseGraphWindow(BGW_BACKGROUND, false, STR_JUST_COMMA)
00680   {
00681     this->InitializeWindow(desc, window_number);
00682   }
00683 
00684   virtual OverflowSafeInt64 GetGraphData(const Company *c, int j)
00685   {
00686     return c->old_economy[j].delivered_cargo;
00687   }
00688 };
00689 
00690 static const NWidgetPart _nested_delivered_cargo_graph_widgets[] = {
00691   NWidget(NWID_HORIZONTAL),
00692     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
00693     NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_GRAPH_CARGO_DELIVERED_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00694     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, BGW_KEY_BUTTON), SetMinimalSize(50, 0), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetDataTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
00695     NWidget(WWT_SHADEBOX, COLOUR_GREY),
00696     NWidget(WWT_STICKYBOX, COLOUR_GREY),
00697   EndContainer(),
00698   NWidget(WWT_PANEL, COLOUR_GREY, BGW_BACKGROUND), SetMinimalSize(576, 128), EndContainer(),
00699 };
00700 
00701 static const WindowDesc _delivered_cargo_graph_desc(
00702   WDP_AUTO, 0, 0,
00703   WC_DELIVERED_CARGO, WC_NONE,
00704   WDF_UNCLICK_BUTTONS,
00705   _nested_delivered_cargo_graph_widgets, lengthof(_nested_delivered_cargo_graph_widgets)
00706 );
00707 
00708 void ShowDeliveredCargoGraph()
00709 {
00710   AllocateWindowDescFront<DeliveredCargoGraphWindow>(&_delivered_cargo_graph_desc, 0);
00711 }
00712 
00713 /***********************/
00714 /* PERFORMANCE HISTORY */
00715 /***********************/
00716 
00718 enum PerformanceHistoryGraphWidgets {
00719   PHW_KEY,
00720   PHW_DETAILED_PERFORMANCE,
00721   PHW_BACKGROUND,
00722 };
00723 
00724 struct PerformanceHistoryGraphWindow : BaseGraphWindow {
00725   PerformanceHistoryGraphWindow(const WindowDesc *desc, WindowNumber window_number) :
00726       BaseGraphWindow(PHW_BACKGROUND, false, STR_JUST_COMMA)
00727   {
00728     this->InitializeWindow(desc, window_number);
00729   }
00730 
00731   virtual OverflowSafeInt64 GetGraphData(const Company *c, int j)
00732   {
00733     return c->old_economy[j].performance_history;
00734   }
00735 
00736   virtual void OnClick(Point pt, int widget, int click_count)
00737   {
00738     if (widget == PHW_DETAILED_PERFORMANCE) ShowPerformanceRatingDetail();
00739     this->BaseGraphWindow::OnClick(pt, widget, click_count);
00740   }
00741 };
00742 
00743 static const NWidgetPart _nested_performance_history_widgets[] = {
00744   NWidget(NWID_HORIZONTAL),
00745     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
00746     NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_GRAPH_COMPANY_PERFORMANCE_RATINGS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00747     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, PHW_DETAILED_PERFORMANCE), SetMinimalSize(50, 0), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetDataTip(STR_PERFORMANCE_DETAIL_KEY, STR_GRAPH_PERFORMANCE_DETAIL_TOOLTIP),
00748     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, PHW_KEY), SetMinimalSize(50, 0), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetDataTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
00749     NWidget(WWT_SHADEBOX, COLOUR_GREY),
00750     NWidget(WWT_STICKYBOX, COLOUR_GREY),
00751   EndContainer(),
00752   NWidget(WWT_PANEL, COLOUR_GREY, PHW_BACKGROUND), SetMinimalSize(576, 224), EndContainer(),
00753 };
00754 
00755 static const WindowDesc _performance_history_desc(
00756   WDP_AUTO, 0, 0,
00757   WC_PERFORMANCE_HISTORY, WC_NONE,
00758   WDF_UNCLICK_BUTTONS,
00759   _nested_performance_history_widgets, lengthof(_nested_performance_history_widgets)
00760 );
00761 
00762 void ShowPerformanceHistoryGraph()
00763 {
00764   AllocateWindowDescFront<PerformanceHistoryGraphWindow>(&_performance_history_desc, 0);
00765 }
00766 
00767 /*****************/
00768 /* COMPANY VALUE */
00769 /*****************/
00770 
00771 struct CompanyValueGraphWindow : BaseGraphWindow {
00772   CompanyValueGraphWindow(const WindowDesc *desc, WindowNumber window_number) :
00773       BaseGraphWindow(BGW_BACKGROUND, false, STR_JUST_CURRCOMPACT)
00774   {
00775     this->InitializeWindow(desc, window_number);
00776   }
00777 
00778   virtual OverflowSafeInt64 GetGraphData(const Company *c, int j)
00779   {
00780     return c->old_economy[j].company_value;
00781   }
00782 };
00783 
00784 static const NWidgetPart _nested_company_value_graph_widgets[] = {
00785   NWidget(NWID_HORIZONTAL),
00786     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
00787     NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_GRAPH_COMPANY_VALUES_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00788     NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, BGW_KEY_BUTTON), SetMinimalSize(50, 0), SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM + 2), SetDataTip(STR_GRAPH_KEY_BUTTON, STR_GRAPH_KEY_TOOLTIP),
00789     NWidget(WWT_SHADEBOX, COLOUR_GREY),
00790     NWidget(WWT_STICKYBOX, COLOUR_GREY),
00791   EndContainer(),
00792   NWidget(WWT_PANEL, COLOUR_GREY, BGW_BACKGROUND), SetMinimalSize(576, 224), EndContainer(),
00793 };
00794 
00795 static const WindowDesc _company_value_graph_desc(
00796   WDP_AUTO, 0, 0,
00797   WC_COMPANY_VALUE, WC_NONE,
00798   WDF_UNCLICK_BUTTONS,
00799   _nested_company_value_graph_widgets, lengthof(_nested_company_value_graph_widgets)
00800 );
00801 
00802 void ShowCompanyValueGraph()
00803 {
00804   AllocateWindowDescFront<CompanyValueGraphWindow>(&_company_value_graph_desc, 0);
00805 }
00806 
00807 /*****************/
00808 /* PAYMENT RATES */
00809 /*****************/
00810 
00812 enum CargoPaymentRatesWidgets {
00813   CPW_BACKGROUND,
00814   CPW_HEADER,
00815   CPW_GRAPH,
00816   CPW_FOOTER,
00817   CPW_CARGO_FIRST,
00818 };
00819 
00820 struct PaymentRatesGraphWindow : BaseGraphWindow {
00821   PaymentRatesGraphWindow(const WindowDesc *desc, WindowNumber window_number) :
00822       BaseGraphWindow(CPW_GRAPH, false, STR_JUST_CURRCOMPACT)
00823   {
00824     this->num_on_x_axis = 20;
00825     this->num_vert_lines = 20;
00826     this->month = 0xFF;
00827     this->x_values_start     = 10;
00828     this->x_values_increment = 10;
00829 
00830     /* Initialise the dataset */
00831     this->OnHundredthTick();
00832 
00833     this->InitNested(desc, window_number);
00834 
00835     int i = 0;
00836     const CargoSpec *cs;
00837     FOR_ALL_CARGOSPECS(cs) {
00838       this->SetWidgetLoweredState(CPW_CARGO_FIRST + cs->Index(), !HasBit(_legend_excluded_cargo, i));
00839       i++;
00840     }
00841   }
00842 
00843   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00844   {
00845     if (widget < CPW_CARGO_FIRST) {
00846       BaseGraphWindow::UpdateWidgetSize(widget, size, padding, fill, resize);
00847       return;
00848     }
00849 
00850     const CargoSpec *cs = CargoSpec::Get(widget - CPW_CARGO_FIRST);
00851     SetDParam(0, cs->name);
00852     Dimension d = GetStringBoundingBox(STR_GRAPH_CARGO_PAYMENT_CARGO);
00853     d.width += 14; // colour field
00854     d.width += WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
00855     d.height += WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
00856     *size = maxdim(d, *size);
00857   }
00858 
00859   virtual void DrawWidget(const Rect &r, int widget) const
00860   {
00861     if (widget < CPW_CARGO_FIRST) {
00862       BaseGraphWindow::DrawWidget(r, widget);
00863       return;
00864     }
00865 
00866     const CargoSpec *cs = CargoSpec::Get(widget - CPW_CARGO_FIRST);
00867     bool rtl = _dynlang.text_dir == TD_RTL;
00868 
00869     /* Since the buttons have no text, no images,
00870      * both the text and the coloured box have to be manually painted.
00871      * clk_dif will move one pixel down and one pixel to the right
00872      * when the button is clicked */
00873     byte clk_dif = this->IsWidgetLowered(widget) ? 1 : 0;
00874     int x = r.left + WD_FRAMERECT_LEFT;
00875     int y = r.top;
00876 
00877     int rect_x = clk_dif + (rtl ? r.right - 12 : r.left + WD_FRAMERECT_LEFT);
00878 
00879     GfxFillRect(rect_x, y + clk_dif, rect_x + 8, y + 5 + clk_dif, 0);
00880     GfxFillRect(rect_x + 1, y + 1 + clk_dif, rect_x + 7, y + 4 + clk_dif, cs->legend_colour);
00881     SetDParam(0, cs->name);
00882     DrawString(rtl ? r.left : x + 14 + clk_dif, (rtl ? r.right - 14 + clk_dif : r.right), y + clk_dif, STR_GRAPH_CARGO_PAYMENT_CARGO);
00883   }
00884 
00885   virtual void OnClick(Point pt, int widget, int click_count)
00886   {
00887     if (widget >= CPW_CARGO_FIRST) {
00888       int i = 0;
00889       const CargoSpec *cs;
00890       FOR_ALL_CARGOSPECS(cs) {
00891         if (cs->Index() + CPW_CARGO_FIRST == widget) break;
00892         i++;
00893       }
00894 
00895       ToggleBit(_legend_excluded_cargo, i);
00896       this->ToggleWidgetLoweredState(widget);
00897       this->excluded_data = _legend_excluded_cargo;
00898       this->SetDirty();
00899     }
00900   }
00901 
00902   virtual void OnTick()
00903   {
00904     /* Override default OnTick */
00905   }
00906 
00907   virtual void OnInvalidateData(int data)
00908   {
00909     this->OnHundredthTick();
00910   }
00911 
00912   virtual void OnHundredthTick()
00913   {
00914     this->excluded_data = _legend_excluded_cargo;
00915 
00916     int i = 0;
00917     const CargoSpec *cs;
00918     FOR_ALL_CARGOSPECS(cs) {
00919       this->colours[i] = cs->legend_colour;
00920       for (uint j = 0; j != 20; j++) {
00921         this->cost[i][j] = GetTransportedGoodsIncome(10, 20, j * 4 + 4, cs->Index());
00922       }
00923 
00924       i++;
00925     }
00926     this->num_dataset = i;
00927   }
00928 };
00929 
00931 static NWidgetBase *MakeCargoButtons(int *biggest_index)
00932 {
00933   NWidgetVertical *ver = new NWidgetVertical;
00934 
00935   const CargoSpec *cs;
00936   FOR_ALL_CARGOSPECS(cs) {
00937     *biggest_index = CPW_CARGO_FIRST + cs->Index();
00938     NWidgetBackground *leaf = new NWidgetBackground(WWT_PANEL, COLOUR_ORANGE, *biggest_index, NULL);
00939     leaf->tool_tip = STR_GRAPH_CARGO_PAYMENT_TOGGLE_CARGO;
00940     leaf->SetFill(1, 0);
00941     leaf->SetLowered(true);
00942     ver->Add(leaf);
00943   }
00944   return ver;
00945 }
00946 
00947 
00948 static const NWidgetPart _nested_cargo_payment_rates_widgets[] = {
00949   NWidget(NWID_HORIZONTAL),
00950     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
00951     NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_GRAPH_CARGO_PAYMENT_RATES_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00952     NWidget(WWT_SHADEBOX, COLOUR_GREY),
00953     NWidget(WWT_STICKYBOX, COLOUR_GREY),
00954   EndContainer(),
00955   NWidget(WWT_PANEL, COLOUR_GREY, CPW_BACKGROUND), SetMinimalSize(568, 128), SetResize(0, 1),
00956     NWidget(NWID_VERTICAL),
00957       NWidget(NWID_HORIZONTAL),
00958         NWidget(NWID_SPACER), SetFill(1, 0),
00959         NWidget(WWT_TEXT, COLOUR_GREY, CPW_HEADER), SetMinimalSize(0, 6), SetPadding(2, 0, 2, 0), SetDataTip(STR_GRAPH_CARGO_PAYMENT_RATES_TITLE, STR_NULL),
00960         NWidget(NWID_SPACER), SetFill(1, 0),
00961       EndContainer(),
00962       NWidget(NWID_HORIZONTAL),
00963         NWidget(WWT_EMPTY, COLOUR_GREY, CPW_GRAPH), SetMinimalSize(495, 0), SetFill(1, 1),
00964         NWidget(NWID_VERTICAL),
00965           NWidget(NWID_SPACER), SetMinimalSize(0, 24), SetFill(0, 0),
00966             NWidgetFunction(MakeCargoButtons),
00967           NWidget(NWID_SPACER), SetMinimalSize(0, 24), SetFill(0, 1),
00968         EndContainer(),
00969         NWidget(NWID_SPACER), SetMinimalSize(5, 0), SetFill(0, 1),
00970       EndContainer(),
00971       NWidget(NWID_HORIZONTAL),
00972         NWidget(NWID_SPACER), SetFill(1, 0),
00973         NWidget(WWT_TEXT, COLOUR_GREY, CPW_FOOTER), SetMinimalSize(0, 6), SetPadding(2, 0, 2, 0), SetDataTip(STR_GRAPH_CARGO_PAYMENT_RATES_X_LABEL, STR_NULL),
00974         NWidget(NWID_SPACER), SetFill(1, 0),
00975       EndContainer(),
00976     EndContainer(),
00977   EndContainer(),
00978 };
00979 
00980 static const WindowDesc _cargo_payment_rates_desc(
00981   WDP_AUTO, 0, 0,
00982   WC_PAYMENT_RATES, WC_NONE,
00983   0,
00984   _nested_cargo_payment_rates_widgets, lengthof(_nested_cargo_payment_rates_widgets)
00985 );
00986 
00987 
00988 void ShowCargoPaymentRates()
00989 {
00990   AllocateWindowDescFront<PaymentRatesGraphWindow>(&_cargo_payment_rates_desc, 0);
00991 }
00992 
00993 /************************/
00994 /* COMPANY LEAGUE TABLE */
00995 /************************/
00996 
00998 enum CompanyLeagueWidgets {
00999   CLW_BACKGROUND,
01000 };
01001 
01002 static const StringID _performance_titles[] = {
01003   STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_ENGINEER,
01004   STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_ENGINEER,
01005   STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_TRAFFIC_MANAGER,
01006   STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_TRAFFIC_MANAGER,
01007   STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_TRANSPORT_COORDINATOR,
01008   STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_TRANSPORT_COORDINATOR,
01009   STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_ROUTE_SUPERVISOR,
01010   STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_ROUTE_SUPERVISOR,
01011   STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_DIRECTOR,
01012   STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_DIRECTOR,
01013   STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_CHIEF_EXECUTIVE,
01014   STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_CHIEF_EXECUTIVE,
01015   STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_CHAIRMAN,
01016   STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_CHAIRMAN,
01017   STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_PRESIDENT,
01018   STR_COMPANY_LEAGUE_PERFORMANCE_TITLE_TYCOON,
01019 };
01020 
01021 static inline StringID GetPerformanceTitleFromValue(uint value)
01022 {
01023   return _performance_titles[minu(value, 1000) >> 6];
01024 }
01025 
01026 class CompanyLeagueWindow : public Window {
01027 private:
01028   GUIList<const Company*> companies;
01029   uint ordinal_width; 
01030   uint text_width;    
01031 
01035   void BuildCompanyList()
01036   {
01037     if (!this->companies.NeedRebuild()) return;
01038 
01039     this->companies.Clear();
01040 
01041     const Company *c;
01042     FOR_ALL_COMPANIES(c) {
01043       *this->companies.Append() = c;
01044     }
01045 
01046     this->companies.Compact();
01047     this->companies.RebuildDone();
01048   }
01049 
01051   static int CDECL PerformanceSorter(const Company * const *c1, const Company * const *c2)
01052   {
01053     return (*c2)->old_economy[1].performance_history - (*c1)->old_economy[1].performance_history;
01054   }
01055 
01056 public:
01057   CompanyLeagueWindow(const WindowDesc *desc, WindowNumber window_number) : Window()
01058   {
01059     this->InitNested(desc, window_number);
01060     this->companies.ForceRebuild();
01061     this->companies.NeedResort();
01062   }
01063 
01064   virtual void OnPaint()
01065   {
01066     this->BuildCompanyList();
01067     this->companies.Sort(&PerformanceSorter);
01068 
01069     this->DrawWidgets();
01070   }
01071 
01072   virtual void DrawWidget(const Rect &r, int widget) const
01073   {
01074     if (widget != CLW_BACKGROUND) return;
01075 
01076     uint y = r.top + WD_FRAMERECT_TOP;
01077     int icon_y_offset = 1 + (FONT_HEIGHT_NORMAL - 10) / 2;
01078 
01079     bool rtl = _dynlang.text_dir == TD_RTL;
01080     uint ordinal_left  = rtl ? r.right - WD_FRAMERECT_LEFT - this->ordinal_width : r.left + WD_FRAMERECT_LEFT;
01081     uint ordinal_right = rtl ? r.right - WD_FRAMERECT_LEFT : r.left + WD_FRAMERECT_LEFT + this->ordinal_width;
01082     uint icon_left     = r.left + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT + (rtl ? this->text_width : this->ordinal_width);
01083     uint text_left     = rtl ? r.left + WD_FRAMERECT_LEFT : r.right - WD_FRAMERECT_LEFT - this->text_width;
01084     uint text_right    = rtl ? r.left + WD_FRAMERECT_LEFT + this->text_width : r.right - WD_FRAMERECT_LEFT;
01085 
01086     for (uint i = 0; i != this->companies.Length(); i++) {
01087       const Company *c = this->companies[i];
01088       DrawString(ordinal_left, ordinal_right, y, i + STR_ORDINAL_NUMBER_1ST, i == 0 ? TC_WHITE : TC_YELLOW);
01089 
01090       DrawCompanyIcon(c->index, icon_left, y + icon_y_offset);
01091 
01092       SetDParam(0, c->index);
01093       SetDParam(1, c->index);
01094       SetDParam(2, GetPerformanceTitleFromValue(c->old_economy[1].performance_history));
01095       DrawString(text_left, text_right, y, STR_COMPANY_LEAGUE_COMPANY_NAME);
01096       y += FONT_HEIGHT_NORMAL;
01097     }
01098   }
01099 
01100   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01101   {
01102     if (widget != CLW_BACKGROUND) return;
01103 
01104     this->ordinal_width = 0;
01105     for (uint i = 0; i < MAX_COMPANIES; i++) {
01106       this->ordinal_width = max(this->ordinal_width, GetStringBoundingBox(STR_ORDINAL_NUMBER_1ST + i).width);
01107     }
01108     this->ordinal_width += 5; // Keep some extra spacing
01109 
01110     uint widest_width = 0;
01111     uint widest_title = 0;
01112     for (uint i = 0; i < lengthof(_performance_titles); i++) {
01113       uint width = GetStringBoundingBox(_performance_titles[i]).width;
01114       if (width > widest_width) {
01115         widest_title = i;
01116         widest_width = width;
01117       }
01118     }
01119 
01120     const Company *c;
01121     FOR_ALL_COMPANIES(c) {
01122       SetDParam(0, c->index);
01123       SetDParam(1, c->index);
01124       SetDParam(2, _performance_titles[widest_title]);
01125       widest_width = max(widest_width, GetStringBoundingBox(STR_COMPANY_LEAGUE_COMPANY_NAME).width);
01126     }
01127 
01128     this->text_width = widest_width + 30; // Keep some extra spacing
01129 
01130     size->width = WD_FRAMERECT_LEFT + this->ordinal_width + WD_FRAMERECT_RIGHT + 16 + WD_FRAMERECT_LEFT + this->text_width + WD_FRAMERECT_RIGHT;
01131   }
01132 
01133 
01134   virtual void OnTick()
01135   {
01136     if (this->companies.NeedResort()) {
01137       this->SetDirty();
01138     }
01139   }
01140 
01141   virtual void OnInvalidateData(int data)
01142   {
01143     if (data == 0) {
01144       this->companies.ForceRebuild();
01145     } else {
01146       this->companies.ForceResort();
01147     }
01148   }
01149 };
01150 
01151 static const NWidgetPart _nested_company_league_widgets[] = {
01152   NWidget(NWID_HORIZONTAL),
01153     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
01154     NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_COMPANY_LEAGUE_TABLE_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
01155     NWidget(WWT_SHADEBOX, COLOUR_GREY),
01156     NWidget(WWT_STICKYBOX, COLOUR_GREY),
01157   EndContainer(),
01158   NWidget(WWT_PANEL, COLOUR_GREY, CLW_BACKGROUND), SetMinimalSize(400, 0), SetMinimalTextLines(15, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM),
01159 };
01160 
01161 static const WindowDesc _company_league_desc(
01162   WDP_AUTO, 0, 0,
01163   WC_COMPANY_LEAGUE, WC_NONE,
01164   0,
01165   _nested_company_league_widgets, lengthof(_nested_company_league_widgets)
01166 );
01167 
01168 void ShowCompanyLeagueTable()
01169 {
01170   AllocateWindowDescFront<CompanyLeagueWindow>(&_company_league_desc, 0);
01171 }
01172 
01173 /*****************************/
01174 /* PERFORMANCE RATING DETAIL */
01175 /*****************************/
01176 
01178 enum PerformanceRatingDetailsWidgets {
01179   PRW_SCORE_FIRST,
01180   PRW_SCORE_LAST = PRW_SCORE_FIRST + (SCORE_END - SCORE_BEGIN) - 1,
01181 
01182   PRW_COMPANY_FIRST,
01183   PRW_COMPANY_LAST  = PRW_COMPANY_FIRST + MAX_COMPANIES - 1,
01184 };
01185 
01186 struct PerformanceRatingDetailWindow : Window {
01187   static CompanyID company;
01188   int timeout;
01189 
01190   PerformanceRatingDetailWindow(const WindowDesc *desc, WindowNumber window_number) : Window()
01191   {
01192     this->UpdateCompanyStats();
01193 
01194     this->InitNested(desc, window_number);
01195     this->OnInvalidateData(INVALID_COMPANY);
01196   }
01197 
01198   void UpdateCompanyStats()
01199   {
01200     /* Update all company stats with the current data
01201      * (this is because _score_info is not saved to a savegame) */
01202     Company *c;
01203     FOR_ALL_COMPANIES(c) {
01204       UpdateCompanyRatingAndValue(c, false);
01205     }
01206 
01207     this->timeout = DAY_TICKS * 5;
01208   }
01209 
01210   uint score_info_left;
01211   uint score_info_right;
01212   uint bar_left;
01213   uint bar_right;
01214   uint bar_width;
01215   uint bar_height;
01216   uint score_detail_left;
01217   uint score_detail_right;
01218 
01219   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01220   {
01221     switch (widget) {
01222       case PRW_SCORE_FIRST:
01223         this->bar_height = FONT_HEIGHT_NORMAL + 4;
01224         size->height = this->bar_height + 2 * WD_MATRIX_TOP;
01225 
01226         uint score_info_width = 0;
01227         for (uint i = SCORE_BEGIN; i < SCORE_END; i++) {
01228           score_info_width = max(score_info_width, GetStringBoundingBox(STR_PERFORMANCE_DETAIL_VEHICLES + i).width);
01229         }
01230         SetDParam(0, 1000);
01231         score_info_width += GetStringBoundingBox(STR_BLACK_COMMA).width + WD_FRAMERECT_LEFT;
01232 
01233         SetDParam(0, 100);
01234         this->bar_width = GetStringBoundingBox(STR_PERFORMANCE_DETAIL_PERCENT).width + 20; // Wide bars!
01235 
01236         /* At this number we are roughly at the max; it can become wider,
01237          * but then you need at 1000 times more money. At that time you're
01238          * not that interested anymore in the last few digits anyway.
01239          * The 500 is because 999 999 500 to 999 999 999 are rounded to
01240          * 1 000 M, and not 999 999 k. Use negative numbers to account for
01241          * the negative income/amount of money etc. as well. */
01242         int max = -(999999999 - 500);
01243 
01244         /* Scale max for the display currency. Prior to rendering the value
01245          * is converted into the display currency, which may cause it to
01246          * raise significantly. We need to compensate for that since {{CURRCOMPACT}}
01247          * is used, which can produce quite short renderings of very large
01248          * values. Otherwise the calculated width could be too narrow.
01249          * Note that it doesn't work if there was a currency with an exchange
01250          * rate greater than max.
01251          * When the currency rate is more than 1000, the 999 999 k becomes at
01252          * least 999 999 M which roughly is equally long. Furthermore if the
01253          * exchange rate is that high, 999 999 k is usually not enough anymore
01254          * to show the different currency numbers. */
01255         if (_currency->rate < 1000) max /= _currency->rate;
01256         SetDParam(0, max);
01257         SetDParam(1, max);
01258         uint score_detail_width = GetStringBoundingBox(STR_PERFORMANCE_DETAIL_AMOUNT_CURRENCY).width;
01259 
01260         size->width = 7 + score_info_width + 5 + this->bar_width + 5 + score_detail_width + 7;
01261         uint left  = 7;
01262         uint right = size->width - 7;
01263 
01264         bool rtl = _dynlang.text_dir == TD_RTL;
01265         this->score_info_left  = rtl ? right - score_info_width : left;
01266         this->score_info_right = rtl ? right : left + score_info_width;
01267 
01268         this->score_detail_left  = rtl ? left : right - score_detail_width;
01269         this->score_detail_right = rtl ? left + score_detail_width : right;
01270 
01271         this->bar_left  = left + (rtl ? score_detail_width : score_info_width) + 5;
01272         this->bar_right = this->bar_left + this->bar_width;
01273         break;
01274     }
01275   }
01276 
01277   virtual void OnPaint()
01278   {
01279     /* Draw standard stuff */
01280     this->DrawWidgets();
01281   }
01282 
01283   virtual void DrawWidget(const Rect &r, int widget) const
01284   {
01285     /* No need to draw when there's nothing to draw */
01286     if (this->company == INVALID_COMPANY) return;
01287 
01288     if (IsInsideMM(widget, PRW_COMPANY_FIRST, PRW_COMPANY_LAST + 1)) {
01289       if (this->IsWidgetDisabled(widget)) return;
01290       CompanyID cid = (CompanyID)(widget - PRW_COMPANY_FIRST);
01291       int offset = (cid == this->company) ? 1 : 0;
01292       Dimension sprite_size = GetSpriteSize(SPR_COMPANY_ICON);
01293       DrawCompanyIcon(cid, (r.left + r.right - sprite_size.width) / 2 + offset, (r.top + r.bottom - sprite_size.height) / 2 + offset);
01294       return;
01295     }
01296 
01297     if (!IsInsideMM(widget, PRW_SCORE_FIRST, PRW_SCORE_LAST + 1)) return;
01298 
01299     ScoreID score_type = (ScoreID)(widget - PRW_SCORE_FIRST);
01300 
01301       /* The colours used to show how the progress is going */
01302     int colour_done = _colour_gradient[COLOUR_GREEN][4];
01303     int colour_notdone = _colour_gradient[COLOUR_RED][4];
01304 
01305     /* Draw all the score parts */
01306     int val    = _score_part[company][score_type];
01307     int needed = _score_info[score_type].needed;
01308     int score  = _score_info[score_type].score;
01309 
01310     /* SCORE_TOTAL has his own rules ;) */
01311     if (score_type == SCORE_TOTAL) {
01312       for (ScoreID i = SCORE_BEGIN; i < SCORE_END; i++) score += _score_info[i].score;
01313       needed = SCORE_MAX;
01314     }
01315 
01316     uint bar_top  = r.top + WD_MATRIX_TOP;
01317     uint text_top = bar_top + 2;
01318 
01319     DrawString(this->score_info_left, this->score_info_right, text_top, STR_PERFORMANCE_DETAIL_VEHICLES + score_type);
01320 
01321     /* Draw the score */
01322     SetDParam(0, score);
01323     DrawString(this->score_info_left, this->score_info_right, text_top, STR_BLACK_COMMA, TC_FROMSTRING, SA_RIGHT);
01324 
01325     /* Calculate the %-bar */
01326     uint x = Clamp(val, 0, needed) * this->bar_width / needed;
01327     bool rtl = _dynlang.text_dir == TD_RTL;
01328     if (rtl) {
01329       x = this->bar_right - x;
01330     } else {
01331       x = this->bar_left + x;
01332     }
01333 
01334     /* Draw the bar */
01335     if (x != this->bar_left)  GfxFillRect(this->bar_left, bar_top, x, bar_top + this->bar_height, rtl ? colour_notdone : colour_done);
01336     if (x != this->bar_right) GfxFillRect(x, bar_top, this->bar_right, bar_top + this->bar_height, rtl ? colour_done : colour_notdone);
01337 
01338     /* Draw it */
01339     SetDParam(0, Clamp(val, 0, needed) * 100 / needed);
01340     DrawString(this->bar_left, this->bar_right, text_top, STR_PERFORMANCE_DETAIL_PERCENT, TC_FROMSTRING, SA_CENTER);
01341 
01342     /* SCORE_LOAN is inversed */
01343     if (score_type == SCORE_LOAN) val = needed - val;
01344 
01345     /* Draw the amount we have against what is needed
01346      * For some of them it is in currency format */
01347     SetDParam(0, val);
01348     SetDParam(1, needed);
01349     switch (score_type) {
01350       case SCORE_MIN_PROFIT:
01351       case SCORE_MIN_INCOME:
01352       case SCORE_MAX_INCOME:
01353       case SCORE_MONEY:
01354       case SCORE_LOAN:
01355         DrawString(this->score_detail_left, this->score_detail_right, text_top, STR_PERFORMANCE_DETAIL_AMOUNT_CURRENCY);
01356         break;
01357       default:
01358         DrawString(this->score_detail_left, this->score_detail_right, text_top, STR_PERFORMANCE_DETAIL_AMOUNT_INT);
01359     }
01360   }
01361 
01362   virtual void OnClick(Point pt, int widget, int click_count)
01363   {
01364     /* Check which button is clicked */
01365     if (IsInsideMM(widget, PRW_COMPANY_FIRST, PRW_COMPANY_LAST + 1)) {
01366       /* Is it no on disable? */
01367       if (!this->IsWidgetDisabled(widget)) {
01368         this->RaiseWidget(this->company + PRW_COMPANY_FIRST);
01369         this->company = (CompanyID)(widget - PRW_COMPANY_FIRST);
01370         this->LowerWidget(this->company + PRW_COMPANY_FIRST);
01371         this->SetDirty();
01372       }
01373     }
01374   }
01375 
01376   virtual void OnTick()
01377   {
01378     if (_pause_mode != PM_UNPAUSED) return;
01379 
01380     /* Update the company score every 5 days */
01381     if (--this->timeout == 0) {
01382       this->UpdateCompanyStats();
01383       this->SetDirty();
01384     }
01385   }
01386 
01391   virtual void OnInvalidateData(int data)
01392   {
01393     /* Disable the companies who are not active */
01394     for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) {
01395       this->SetWidgetDisabledState(i + PRW_COMPANY_FIRST, !Company::IsValidID(i));
01396     }
01397 
01398     /* Check if the currently selected company is still active. */
01399     if (this->company != INVALID_COMPANY && !Company::IsValidID(this->company)) {
01400       /* Raise the widget for the previous selection. */
01401       this->RaiseWidget(this->company + PRW_COMPANY_FIRST);
01402       this->company = INVALID_COMPANY;
01403     }
01404 
01405     if (this->company == INVALID_COMPANY) {
01406       const Company *c;
01407       FOR_ALL_COMPANIES(c) {
01408         this->company = c->index;
01409         break;
01410       }
01411     }
01412 
01413     /* Make sure the widget is lowered */
01414     this->LowerWidget(this->company + PRW_COMPANY_FIRST);
01415   }
01416 };
01417 
01418 CompanyID PerformanceRatingDetailWindow::company = INVALID_COMPANY;
01419 
01425 static NWidgetBase *MakePerformanceDetailPanels(int *biggest_index)
01426 {
01427   const StringID performance_tips[] = {
01428     STR_PERFORMANCE_DETAIL_VEHICLES_TOOLTIP,
01429     STR_PERFORMANCE_DETAIL_STATIONS_TOOLTIP,
01430     STR_PERFORMANCE_DETAIL_MIN_PROFIT_TOOLTIP,
01431     STR_PERFORMANCE_DETAIL_MIN_INCOME_TOOLTIP,
01432     STR_PERFORMANCE_DETAIL_MAX_INCOME_TOOLTIP,
01433     STR_PERFORMANCE_DETAIL_DELIVERED_TOOLTIP,
01434     STR_PERFORMANCE_DETAIL_CARGO_TOOLTIP,
01435     STR_PERFORMANCE_DETAIL_MONEY_TOOLTIP,
01436     STR_PERFORMANCE_DETAIL_LOAN_TOOLTIP,
01437     STR_PERFORMANCE_DETAIL_TOTAL_TOOLTIP,
01438   };
01439 
01440   assert_compile(lengthof(performance_tips) == SCORE_END - SCORE_BEGIN);
01441 
01442   NWidgetVertical *vert = new NWidgetVertical(NC_EQUALSIZE);
01443   for (int widnum = PRW_SCORE_FIRST; widnum <= PRW_SCORE_LAST; widnum++) {
01444     NWidgetBackground *panel = new NWidgetBackground(WWT_PANEL, COLOUR_GREY, widnum);
01445     panel->SetFill(1, 1);
01446     panel->SetDataTip(0x0, performance_tips[widnum - PRW_SCORE_FIRST]);
01447     vert->Add(panel);
01448   }
01449   *biggest_index = PRW_SCORE_LAST;
01450   return vert;
01451 }
01452 
01459 static NWidgetBase *MakeCompanyButtonRows(int *biggest_index)
01460 {
01461   static const int MAX_LENGTH = 8; // Maximal number of company buttons in one row.
01462   NWidgetVertical *vert = NULL; // Storage for all rows.
01463   NWidgetHorizontal *hor = NULL; // Storage for buttons in one row.
01464   int hor_length = 0;
01465 
01466   Dimension sprite_size = GetSpriteSize(SPR_COMPANY_ICON);
01467   sprite_size.width  += WD_MATRIX_LEFT + WD_MATRIX_RIGHT;
01468   sprite_size.height += WD_MATRIX_TOP + WD_MATRIX_BOTTOM + 1; // 1 for the 'offset' of being pressed
01469 
01470   for (int widnum = PRW_COMPANY_FIRST; widnum <= PRW_COMPANY_LAST; widnum++) {
01471     /* Ensure there is room in 'hor' for another button. */
01472     if (hor_length == MAX_LENGTH) {
01473       if (vert == NULL) vert = new NWidgetVertical();
01474       vert->Add(hor);
01475       hor = NULL;
01476       hor_length = 0;
01477     }
01478     if (hor == NULL) {
01479       hor = new NWidgetHorizontal();
01480       hor_length = 0;
01481     }
01482 
01483     NWidgetBackground *panel = new NWidgetBackground(WWT_PANEL, COLOUR_GREY, widnum);
01484     panel->SetMinimalSize(sprite_size.width, sprite_size.height);
01485     panel->SetFill(1, 0);
01486     panel->SetDataTip(0x0, STR_PERFORMANCE_DETAIL_SELECT_COMPANY_TOOLTIP);
01487     hor->Add(panel);
01488     hor_length++;
01489   }
01490   *biggest_index = PRW_COMPANY_LAST;
01491   if (vert == NULL) return hor; // All buttons fit in a single row.
01492 
01493   if (hor_length > 0 && hor_length < MAX_LENGTH) {
01494     /* Last row is partial, add a spacer at the end to force all buttons to the left. */
01495     NWidgetSpacer *spc = new NWidgetSpacer(0, 0);
01496     spc->SetMinimalSize(sprite_size.width, sprite_size.height);
01497     spc->SetFill(1, 0);
01498     hor->Add(spc);
01499   }
01500   if (hor != NULL) vert->Add(hor);
01501   return vert;
01502 }
01503 
01504 static const NWidgetPart _nested_performance_rating_detail_widgets[] = {
01505   NWidget(NWID_HORIZONTAL),
01506     NWidget(WWT_CLOSEBOX, COLOUR_GREY),
01507     NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_PERFORMANCE_DETAIL, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
01508     NWidget(WWT_SHADEBOX, COLOUR_GREY),
01509     NWidget(WWT_STICKYBOX, COLOUR_GREY),
01510   EndContainer(),
01511   NWidget(WWT_PANEL, COLOUR_GREY),
01512     NWidgetFunction(MakeCompanyButtonRows), SetPadding(0, 1, 1, 2),
01513   EndContainer(),
01514   NWidgetFunction(MakePerformanceDetailPanels),
01515 };
01516 
01517 static const WindowDesc _performance_rating_detail_desc(
01518   WDP_AUTO, 0, 0,
01519   WC_PERFORMANCE_DETAIL, WC_NONE,
01520   0,
01521   _nested_performance_rating_detail_widgets, lengthof(_nested_performance_rating_detail_widgets)
01522 );
01523 
01524 void ShowPerformanceRatingDetail()
01525 {
01526   AllocateWindowDescFront<PerformanceRatingDetailWindow>(&_performance_rating_detail_desc, 0);
01527 }

Generated on Sun Nov 14 14:41:51 2010 for OpenTTD by  doxygen 1.6.1