Added the Gruff library to the lib/ directory of the the rails folder, and the
[selectricity] / lib / gruff-0.2.8 / lib / gruff / base.rb
1 #
2 # = Gruff. Graphs.
3 #
4 # Author:: Geoffrey Grosenbach boss@topfunky.com
5 #
6 # Originally Created:: October 23, 2005
7 #
8 # Extra thanks to Tim Hunter for writing RMagick, 
9 # and also contributions by
10 # Jarkko Laine, Mike Perham, Andreas Schwarz, 
11 # Alun Eyre, Guillaume Theoret, David Stokar, 
12 # Paul Rogers, Dave Woodward, Frank Oxener,
13 # Kevin Clark, Cies Breijs, Richard Cowin,
14 # and a cast of thousands.
15 #
16
17 require 'rubygems'
18 require 'RMagick'
19 require File.dirname(__FILE__) + '/deprecated'
20
21 module Gruff
22   
23   VERSION = '0.2.8'
24   
25   class Base
26     
27     include Magick
28     include Deprecated
29
30     # Draw extra lines showing where the margins and text centers are
31     DEBUG = false
32
33     # Used for navigating the array of data to plot
34     DATA_LABEL_INDEX = 0
35     DATA_VALUES_INDEX = 1
36     DATA_COLOR_INDEX = 2
37
38     # Blank space around the edges of the graph
39     TOP_MARGIN = BOTTOM_MARGIN = RIGHT_MARGIN = LEFT_MARGIN = 20.0
40     
41     # Space around text elements. Mostly used for vertical spacing
42     LEGEND_MARGIN = TITLE_MARGIN = LABEL_MARGIN = 10.0
43     
44     # A hash of names for the individual columns, where the key is the array index for the column this label represents.
45     #
46     # Not all columns need to be named.
47     #
48     # Example: 0 => 2005, 3 => 2006, 5 => 2007, 7 => 2008
49     attr_accessor :labels
50
51     # Used internally for spacing.
52     #
53     # By default, labels are centered over the point they represent.
54     attr_accessor :center_labels_over_point
55
56     # Used internally for horizontal graph types.
57     attr_accessor :has_left_labels
58
59     # A label for the bottom of the graph
60     attr_accessor :x_axis_label
61     
62     # A label for the left side of the graph
63     attr_accessor :y_axis_label
64
65     # attr_accessor :x_axis_increment
66     
67     # Manually set increment of the horizontal marking lines
68     attr_accessor :y_axis_increment
69
70     # Get or set the list of colors that will be used to draw the bars or lines.
71     attr_accessor :colors
72
73     # The large title of the graph displayed at the top
74     attr_accessor :title
75
76     # Font used for titles, labels, etc. Works best if you provide the full path to the TTF font file.
77     # RMagick must be built with the Freetype libraries for this to work properly.
78     #
79     # Tries to find Bitstream Vera (Vera.ttf) in the location specified by
80     # ENV['MAGICK_FONT_PATH']. Uses default RMagick font otherwise.
81     attr_reader :font
82
83     attr_accessor :font_color
84
85     # Hide various elements
86     attr_accessor :hide_line_markers, :hide_legend, :hide_title, :hide_line_numbers
87
88     # Message shown when there is no data. Fits up to 20 characters. Defaults to "No Data."
89     attr_accessor :no_data_message
90
91     # The font size of the large title at the top of the graph
92     attr_accessor :title_font_size
93
94     # Optionally set the size of the font. Based on an 800x600px graph. Default is 20.
95     #
96     # Will be scaled down if graph is smaller than 800px wide.
97     attr_accessor :legend_font_size
98
99     # The font size of the labels around the graph
100     attr_accessor :marker_font_size
101     
102     # The color of the auxiliary lines
103     attr_accessor :marker_color
104
105     # The number of horizontal lines shown for reference
106     attr_accessor :marker_count
107     
108
109     # You can manually set a minimum value instead of having the values guessed for you.
110     #
111     # Set it after you have given all your data to the graph object.
112     attr_accessor :minimum_value
113
114     # You can manually set a maximum value, such as a percentage-based graph that always goes to 100.
115     #
116     # If you use this, you must set it after you have given all your data to the graph object.
117     attr_accessor :maximum_value
118     
119     # Set to false if you don't want the data to be sorted with largest avg values at the back.
120     attr_accessor :sort
121     
122     # Experimental
123     attr_accessor :additional_line_values
124     
125     # Experimental
126     attr_accessor :stacked
127     
128     
129     # Optionally set the size of the colored box by each item in the legend. Default is 20.0
130     #
131     # Will be scaled down if graph is smaller than 800px wide.
132     attr_accessor :legend_box_size
133
134
135     # If one numerical argument is given, the graph is drawn at 4/3 ratio according to the given width (800 results in 800x600, 400 gives 400x300, etc.).
136     #
137     # Or, send a geometry string for other ratios ('800x400', '400x225'). 
138     #
139     # Looks for Bitstream Vera as the default font. Expects an environment var of MAGICK_FONT_PATH to be set. (Uses RMagick's default font otherwise.)
140     def initialize(target_width=800)
141
142       if not Numeric === target_width
143         geometric_width, geometric_height = target_width.split('x')
144         @columns = geometric_width.to_f
145         @rows = geometric_height.to_f
146       else
147         @columns = target_width.to_f
148         @rows = target_width.to_f * 0.75        
149       end
150       
151       initialize_ivars
152
153       reset_themes
154       theme_keynote
155     end
156
157     ##
158     # Set instance variables for this object.
159     #
160     # Subclasses can override this, call super, then set values separately.
161     #
162     # This makes it possible to set defaults in a subclass but still allow
163     # developers to change this values in their program.
164     
165     def initialize_ivars
166       # Internal for calculations
167       @raw_columns = 800.0
168       @raw_rows = 800.0 * (@rows/@columns)
169       @column_count = 0
170       @marker_count = nil
171       @maximum_value = @minimum_value = nil
172       @has_data = false
173       @data = Array.new
174       @labels = Hash.new
175       @labels_seen = Hash.new
176       @sort = true
177       @title = nil
178
179       @scale = @columns / @raw_columns
180
181       vera_font_path = File.expand_path('Vera.ttf', ENV['MAGICK_FONT_PATH'])
182       @font = File.exists?(vera_font_path) ? vera_font_path : nil
183
184       @marker_font_size = 21.0
185       @legend_font_size = 20.0
186       @title_font_size = 36.0
187       
188       @legend_box_size = 20.0
189
190       @no_data_message = "No Data"
191
192       @hide_line_markers = @hide_legend = @hide_title = @hide_line_numbers = false
193       @center_labels_over_point = true
194       @has_left_labels = false
195
196       @additional_line_values = []      
197       @additional_line_colors = []
198       @theme_options = {}
199       
200       @x_axis_label = @y_axis_label = nil
201       @y_axis_increment = nil
202       @stacked = nil
203       @norm_data = nil
204     end
205     
206     def font=(font_path)
207       @font = font_path
208       @d.font = @font
209     end
210
211     # Add a color to the list of available colors for lines.
212     #
213     # Example: 
214     #  add_color('#c0e9d3')
215     def add_color(colorname)
216       @colors << colorname
217     end
218
219
220     # Replace the entire color list with a new array of colors. You need to have one more color
221     # than the number of datasets you intend to draw. Also aliased as the colors= setter method.
222     #
223     # Example: 
224     #  replace_colors('#cc99cc', '#d9e043', '#34d8a2')
225     def replace_colors(color_list=[])
226       @colors = color_list
227     end
228
229
230     # You can set a theme manually. Assign a hash to this method before you send your data.
231     #
232     #  graph.theme = {
233     #    :colors => %w(orange purple green white red),
234     #    :marker_color => 'blue',
235     #    :background_colors => %w(black grey)
236     #  }
237     #
238     # :background_image => 'squirrel.png' is also possible.
239     #
240     # (Or hopefully something better looking than that.)
241     #
242     def theme=(options)
243       reset_themes()
244       
245       defaults = {
246         :colors => ['black', 'white'],
247         :additional_line_colors => [],
248         :marker_color => 'white',
249         :font_color => 'black',
250         :background_colors => nil,
251         :background_image => nil
252       }
253       @theme_options = defaults.merge options
254
255       @colors = @theme_options[:colors]
256       @marker_color = @theme_options[:marker_color]
257       @font_color = @theme_options[:font_color] || @marker_color
258       @additional_line_colors = @theme_options[:additional_line_colors]
259       
260       render_background
261     end
262     
263     # A color scheme similar to the popular presentation software.
264     def theme_keynote
265       # Colors
266       @blue = '#6886B4'
267       @yellow = '#FDD84E'
268       @green = '#72AE6E'
269       @red = '#D1695E'
270       @purple = '#8A6EAF'
271       @orange = '#EFAA43'
272       @white = 'white'
273       @colors = [@yellow, @blue, @green, @red, @purple, @orange, @white]
274
275       self.theme = {
276         :colors => @colors,
277         :marker_color => 'white',
278         :font_color => 'white',
279         :background_colors => ['black', '#4a465a']
280       }
281     end
282     
283     # A color scheme plucked from the colors on the popular usability blog.
284     def theme_37signals
285       # Colors
286       @green = '#339933'
287       @purple = '#cc99cc'
288       @blue = '#336699'
289       @yellow = '#FFF804'
290       @red = '#ff0000'
291       @orange = '#cf5910'
292       @black = 'black'
293       @colors = [@yellow, @blue, @green, @red, @purple, @orange, @black]
294
295       self.theme = {
296         :colors => @colors,
297         :marker_color => 'black',
298         :font_color => 'black',
299         :background_colors => ['#d1edf5', 'white']
300       }
301     end
302
303     # A color scheme from the colors used on the 2005 Rails keynote presentation at RubyConf.
304     def theme_rails_keynote
305       # Colors
306       @green = '#00ff00'
307       @grey = '#333333'
308       @orange = '#ff5d00'
309       @red = '#f61100'
310       @white = 'white'
311       @light_grey = '#999999'
312       @black = 'black'
313       @colors = [@green, @grey, @orange, @red, @white, @light_grey, @black]
314       
315       self.theme = {
316         :colors => @colors,
317         :marker_color => 'white',
318         :font_color => 'white',
319         :background_colors => ['#0083a3', '#0083a3']
320       }
321     end
322
323     # A color scheme similar to that used on the popular podcast site.
324     def theme_odeo
325       # Colors
326       @grey = '#202020'
327       @white = 'white'
328       @dark_pink = '#a21764'
329       @green = '#8ab438'
330       @light_grey = '#999999'
331       @dark_blue = '#3a5b87'
332       @black = 'black'
333       @colors = [@grey, @white, @dark_blue, @dark_pink, @green, @light_grey, @black]
334       
335       self.theme = {
336         :colors => @colors,
337         :marker_color => 'white',
338         :font_color => 'white',
339         :background_colors => ['#ff47a4', '#ff1f81']
340       }
341     end
342
343     # Parameters are an array where the first element is the name of the dataset
344     # and the value is an array of values to plot.
345     #
346     # Can be called multiple times with different datasets for a multi-valued graph.
347     #
348     # If the color argument is nil, the next color from the default theme will be used.
349     #
350     # NOTE: If you want to use a preset theme, you must set it before calling data().
351     #
352     # Example:
353     #
354     #  data("Bart S.", [95, 45, 78, 89, 88, 76], '#ffcc00')
355     #
356     def data(name, data_points=[], color=nil)
357       data_points = Array(data_points) # make sure it's an array
358       @data << [name, data_points, (color || increment_color)]
359       # Set column count if this is larger than previous counts
360       @column_count = (data_points.length > @column_count) ? data_points.length : @column_count
361
362       # Pre-normalize
363       data_points.each_with_index do |data_point, index|
364         next if data_point.nil?
365         
366         # Setup max/min so spread starts at the low end of the data points
367         if @maximum_value.nil? && @minimum_value.nil?
368           @maximum_value = @minimum_value = data_point
369         end
370
371         # TODO Doesn't work with stacked bar graphs
372         # Original: @maximum_value = larger_than_max?(data_point, index) ? max(data_point, index) : @maximum_value
373         @maximum_value = larger_than_max?(data_point) ? data_point : @maximum_value
374         @has_data = true if @maximum_value > 0
375         
376         @minimum_value = less_than_min?(data_point) ? data_point : @minimum_value
377           @has_data = true if @minimum_value < 0
378       end
379     end
380
381     # Writes the graph to a file. Defaults to 'graph.png'
382     #
383     # Example: write('graphs/my_pretty_graph.png')
384     def write(filename="graph.png")
385       draw()
386       @base_image.write(filename)
387     end
388
389     # Return the graph as a rendered binary blob.
390     def to_blob(fileformat='PNG')
391       draw()
392       return @base_image.to_blob do
393          self.format = fileformat
394       end
395     end
396
397 protected
398
399     # Overridden by subclasses to do the actual plotting of the graph.
400     #
401     # Subclasses should start by calling super() for this method.
402     def draw
403       make_stacked if @stacked
404       setup_drawing
405       
406       debug {
407         # Outer margin
408         @d.rectangle( LEFT_MARGIN, TOP_MARGIN, 
409                             @raw_columns - RIGHT_MARGIN, @raw_rows - BOTTOM_MARGIN)
410         # Graph area box
411         @d.rectangle( @graph_left, @graph_top, @graph_right, @graph_bottom)
412       }
413     end
414
415     ##
416     # Calculates size of drawable area and draws the decorations.
417     #
418     # * line markers
419     # * legend
420     # * title
421     
422     def setup_drawing
423       # Maybe should be done in one of the following functions for more granularity.
424       unless @has_data
425         draw_no_data()
426         return
427       end
428       
429       normalize()
430       setup_graph_measurements()
431       sort_norm_data() if @sort # Sort norm_data with avg largest values set first (for display)
432       
433       draw_legend()
434       draw_line_markers()
435       draw_axis_labels()
436       draw_title
437     end
438
439     # Make copy of data with values scaled between 0-100
440     def normalize(force=false)
441       if @norm_data.nil? || force
442         @norm_data = []
443         return unless @has_data
444                 
445         calculate_spread
446         
447         @data.each do |data_row|
448           norm_data_points = []
449           data_row[DATA_VALUES_INDEX].each do |data_point|
450             if data_point.nil?
451               norm_data_points << nil
452             else
453               norm_data_points << ((data_point.to_f - @minimum_value.to_f ) / @spread)
454             end
455           end
456           @norm_data << [data_row[DATA_LABEL_INDEX], norm_data_points, data_row[DATA_COLOR_INDEX]]
457         end
458       end
459     end
460
461     def calculate_spread
462       @spread = @maximum_value.to_f - @minimum_value.to_f
463       @spread = @spread > 0 ? @spread : 1
464     end
465
466     ##
467     # Calculates size of drawable area, general font dimensions, etc.
468     
469     def setup_graph_measurements
470       @marker_caps_height = calculate_caps_height(@marker_font_size)
471       @title_caps_height = calculate_caps_height(@title_font_size)
472       @legend_caps_height = calculate_caps_height(@legend_font_size)
473       
474       if @hide_line_markers
475         (@graph_left, 
476          @graph_right_margin, 
477          @graph_bottom_margin) = [LEFT_MARGIN, RIGHT_MARGIN, BOTTOM_MARGIN]
478       else
479         longest_left_label_width = 0
480         if @has_left_labels
481           longest_left_label_width =  calculate_width(@marker_font_size,
482                                       labels.values.inject('') { |value, memo| (value.to_s.length > memo.to_s.length) ? value : memo }) * 1.25
483         else
484           longest_left_label_width = calculate_width(@marker_font_size, 
485                           label(@maximum_value.to_f))
486         end
487       
488         # Shift graph if left line numbers are hidden
489         line_number_width = @hide_line_numbers && !@has_left_labels ? 
490                               0.0 : 
491                               (longest_left_label_width + LABEL_MARGIN * 2)
492
493         @graph_left = LEFT_MARGIN + 
494                       line_number_width + 
495                       (@y_axis_label.nil? ? 0.0 : @marker_caps_height + LABEL_MARGIN * 2)
496         # Make space for half the width of the rightmost column label.
497         # Might be greater than the number of columns if between-style bar markers are used.
498         last_label = @labels.keys.sort.last.to_i
499         extra_room_for_long_label = (last_label >= (@column_count-1) && @center_labels_over_point) ?
500           calculate_width(@marker_font_size, @labels[last_label])/2.0 :
501           0
502         @graph_right_margin =   RIGHT_MARGIN + extra_room_for_long_label
503                                 
504         @graph_bottom_margin =  BOTTOM_MARGIN + 
505                                 @marker_caps_height + LABEL_MARGIN
506       end
507
508       @graph_right = @raw_columns - @graph_right_margin
509       @graph_width = @raw_columns - @graph_left - @graph_right_margin
510
511       # When @hide title, leave a TITLE_MARGIN space for aesthetics.
512       # Same with @hide_legend
513       @graph_top = TOP_MARGIN + 
514                     (@hide_title ? TITLE_MARGIN : @title_caps_height + TITLE_MARGIN * 2) +
515                     (@hide_legend ? LEGEND_MARGIN : @legend_caps_height + LEGEND_MARGIN * 2)
516
517       @graph_bottom = @raw_rows - @graph_bottom_margin -
518                       (@x_axis_label.nil? ? 0.0 : @marker_caps_height + LABEL_MARGIN)
519       
520       @graph_height = @graph_bottom - @graph_top
521     end
522
523     # Draw the optional labels for the x axis and y axis.
524     def draw_axis_labels
525       unless @x_axis_label.nil?
526         # X Axis
527         # Centered vertically and horizontally by setting the
528         # height to 1.0 and the width to the width of the graph.
529         x_axis_label_y_coordinate = @graph_bottom + LABEL_MARGIN * 2 + @marker_caps_height
530
531         # TODO Center between graph area
532         @d.fill = @font_color
533         @d.font = @font if @font
534         @d.stroke('transparent')
535         @d.pointsize = scale_fontsize(@marker_font_size)
536         @d.gravity = NorthGravity
537         @d = @d.annotate_scaled( @base_image, 
538                           @raw_columns, 1.0, 
539                           0.0, x_axis_label_y_coordinate, 
540                           @x_axis_label, @scale)
541         debug { @d.line 0.0, x_axis_label_y_coordinate, @raw_columns, x_axis_label_y_coordinate }
542       end
543
544       unless @y_axis_label.nil?
545         # Y Axis, rotated vertically
546         @d.rotation = 90.0
547         @d.gravity = CenterGravity
548         @d = @d.annotate_scaled( @base_image, 
549                           1.0, @raw_rows,
550                           LEFT_MARGIN + @marker_caps_height / 2.0, 0.0, 
551                           @y_axis_label, @scale)
552         @d.rotation = -90.0
553       end
554     end
555
556     # Draws horizontal background lines and labels
557     def draw_line_markers
558       return if @hide_line_markers
559       
560       @d = @d.stroke_antialias false
561             
562       if @y_axis_increment.nil?
563         # Try to use a number of horizontal lines that will come out even.
564         #
565         # TODO Do the same for larger numbers...100, 75, 50, 25
566         if @marker_count.nil?
567           (3..7).each do |lines|
568             if @spread % lines == 0.0
569               @marker_count = lines
570               break
571             end
572           end
573           @marker_count ||= 4
574         end
575         @increment = (@spread > 0) ? significant(@spread / @marker_count) : 1
576       else
577         # TODO Make this work for negative values
578         @maximum_value = [@maximum_value.ceil, @y_axis_increment].max
579         @minimum_value = @minimum_value.floor
580         calculate_spread
581         normalize(true)
582         
583         @marker_count = (@spread / @y_axis_increment).to_i
584         @increment = @y_axis_increment
585       end
586       @increment_scaled = @graph_height.to_f / (@spread / @increment)
587
588       # Draw horizontal line markers and annotate with numbers
589       (0..@marker_count).each do |index|
590         y = @graph_top + @graph_height - index.to_f * @increment_scaled
591         
592         @d = @d.stroke(@marker_color)
593         @d = @d.stroke_width 1
594         @d = @d.line(@graph_left, y, @graph_right, y)
595
596         marker_label = index * @increment + @minimum_value.to_f
597
598         unless @hide_line_numbers
599           @d.fill = @font_color
600           @d.font = @font if @font
601           @d.stroke('transparent')
602           @d.pointsize = scale_fontsize(@marker_font_size)
603           @d.gravity = EastGravity
604         
605           # Vertically center with 1.0 for the height
606           @d = @d.annotate_scaled( @base_image, 
607                             @graph_left - LABEL_MARGIN, 1.0,
608                             0.0, y,
609                             label(marker_label), @scale)
610         end
611       end
612       
613       # # Submitted by a contibutor...the utility escapes me
614       # i = 0
615       # @additional_line_values.each do |value|
616       #   @increment_scaled = @graph_height.to_f / (@maximum_value.to_f / value)
617       # 
618       #   y = @graph_top + @graph_height - @increment_scaled
619       # 
620       #   @d = @d.stroke(@additional_line_colors[i])
621       #   @d = @d.line(@graph_left, y, @graph_right, y)
622       # 
623       # 
624       #   @d.fill = @additional_line_colors[i]
625       #   @d.font = @font if @font
626       #   @d.stroke('transparent')
627       #   @d.pointsize = scale_fontsize(@marker_font_size)
628       #   @d.gravity = EastGravity
629       #   @d = @d.annotate_scaled( @base_image, 
630       #                     100, 20,
631       #                     -10, y - (@marker_font_size/2.0), 
632       #                     "", @scale)
633       #   i += 1   
634       # end
635       
636       @d = @d.stroke_antialias true
637     end
638
639     # Draws a legend with the names of the datasets 
640     # matched to the colors used to draw them.
641     def draw_legend
642       return if @hide_legend
643
644       @legend_labels = @data.collect {|item| item[DATA_LABEL_INDEX] }
645
646       legend_square_width = @legend_box_size # small square with color of this item
647
648       # May fix legend drawing problem at small sizes
649       @d.font = @font if @font
650       @d.pointsize = @legend_font_size
651
652       metrics = @d.get_type_metrics(@base_image, @legend_labels.join(''))
653       legend_text_width = metrics.width
654       legend_width = legend_text_width + 
655                     (@legend_labels.length * legend_square_width * 2.7)
656       legend_left = (@raw_columns - legend_width) / 2
657       legend_increment = legend_width / @legend_labels.length.to_f
658
659       current_x_offset = legend_left
660       current_y_offset =  @hide_title ? 
661                           TOP_MARGIN + LEGEND_MARGIN : 
662                           TOP_MARGIN + 
663                           TITLE_MARGIN + @title_caps_height +
664                           LEGEND_MARGIN
665
666       debug { @d.line 0.0, current_y_offset, @raw_columns, current_y_offset }
667                                                     
668       @legend_labels.each_with_index do |legend_label, index|        
669
670         # Draw label
671         @d.fill = @font_color
672         @d.font = @font if @font
673         @d.pointsize = scale_fontsize(@legend_font_size)
674         @d.stroke('transparent')
675         @d.font_weight = NormalWeight
676         @d.gravity = WestGravity
677         @d = @d.annotate_scaled( @base_image, 
678                           @raw_columns, 1.0,
679                           current_x_offset + (legend_square_width * 1.7), current_y_offset, 
680                           legend_label.to_s, @scale)
681         
682         # Now draw box with color of this dataset
683         @d = @d.stroke('transparent')
684         @d = @d.fill @data[index][DATA_COLOR_INDEX]
685         @d = @d.rectangle(current_x_offset, 
686                           current_y_offset - legend_square_width / 2.0, 
687                           current_x_offset + legend_square_width, 
688                           current_y_offset + legend_square_width / 2.0)
689
690         @d.pointsize = @legend_font_size
691         metrics = @d.get_type_metrics(@base_image, legend_label.to_s)
692         current_string_offset = metrics.width + (legend_square_width * 2.7)
693         current_x_offset += current_string_offset
694       end
695       @color_index = 0
696     end
697
698     def draw_title
699       return if (@hide_title || @title.nil?)
700       
701       @d.fill = @font_color
702       @d.font = @font if @font
703       @d.stroke('transparent')
704       @d.pointsize = scale_fontsize(@title_font_size)
705       @d.font_weight = BoldWeight
706       @d.gravity = NorthGravity
707       @d = @d.annotate_scaled( @base_image, 
708                         @raw_columns, 1.0,
709                         0, TOP_MARGIN, 
710                         @title, @scale)
711     end
712
713     ##
714     # Draws column labels below graph, centered over x_offset
715     #
716     # TODO Allow WestGravity as an option
717     
718     def draw_label(x_offset, index, count=nil)
719       return if @hide_line_markers
720
721       if !@labels[index].nil? && @labels_seen[index].nil?
722         y_offset = @graph_bottom + LABEL_MARGIN
723         
724         if count && (count % 2) == 1
725           y_offset += 1.5 * LABEL_MARGIN
726         end
727         
728         @d.fill = @font_color
729         @d.font = @font if @font
730         @d.stroke('transparent')
731         @d.font_weight = NormalWeight
732         @d.pointsize = scale_fontsize(@marker_font_size)
733         @d.gravity = NorthGravity
734         @d = @d.annotate_scaled(@base_image,
735                                 1.0, 1.0,
736                                 x_offset, y_offset,
737                                 @labels[index], @scale)
738         @labels_seen[index] = 1
739         debug { @d.line 0.0, y_offset, @raw_columns, y_offset }
740       end
741     end
742
743     def draw_no_data
744         @d.fill = @font_color
745         @d.font = @font if @font
746         @d.stroke('transparent')
747         @d.font_weight = NormalWeight
748         @d.pointsize = scale_fontsize(80)
749         @d.gravity = CenterGravity
750         @d = @d.annotate_scaled( @base_image, 
751                         @raw_columns, @raw_rows/2.0,
752                         0, 10, 
753                         @no_data_message, @scale)
754     end
755
756     ##
757     # Finds the best background to render based on the provided theme options.
758     #
759     # Creates a @base_image to draw on.
760     #
761     def render_background
762       case @theme_options[:background_colors]
763       when Array
764         @base_image = render_gradiated_background(*@theme_options[:background_colors])
765       when String
766         @base_image = render_solid_background(@theme_options[:background_colors])
767       else
768         @base_image = render_image_background(*@theme_options[:background_image])
769       end
770     end
771
772     ##
773     # Make a new image at the current size with a solid +color+.
774     
775     def render_solid_background(color)
776       Image.new(@columns, @rows) {
777         self.background_color = color
778       }
779     end
780
781     # Use with a theme definition method to draw a gradiated background.
782     def render_gradiated_background(top_color, bottom_color)
783       Image.new(@columns, @rows, 
784           GradientFill.new(0, 0, 100, 0, top_color, bottom_color))
785     end
786
787     # Use with a theme to use an image (800x600 original) background.
788     def render_image_background(image_path)
789       image = Image.read(image_path)
790       if @scale != 1.0
791         image[0].resize!(@scale) # TODO Resize with new scale (crop if necessary for wide graph)
792       end
793       image[0]
794     end
795     
796     # Use with a theme to make a transparent background
797     def render_transparent_background
798       Image.new(@columns, @rows) do
799         self.background_color = 'transparent'
800       end
801     end
802
803     def reset_themes
804       @color_index = 0
805       @labels_seen = {}
806       @theme_options = {}
807       
808       @d = Draw.new
809       # Scale down from 800x600 used to calculate drawing.
810       @d = @d.scale(@scale, @scale)
811     end
812
813     def scale(value)
814       value * @scale
815     end
816     
817     # Return a comparable fontsize for the current graph.
818     def scale_fontsize(value)
819       new_fontsize = value * @scale
820       # return new_fontsize < 10.0 ? 10.0 : new_fontsize
821       return new_fontsize
822     end
823
824     def clip_value_if_greater_than(value, max_value)
825       (value > max_value) ? max_value : value
826     end
827
828     # Overridden by subclasses such as stacked bar.
829     def larger_than_max?(data_point, index=0)
830       data_point > @maximum_value
831     end
832
833           def less_than_min?(data_point, index=0)
834       data_point < @minimum_value
835     end
836
837     ##
838     # Overridden by subclasses that need it.
839     def max(data_point, index)
840       data_point
841     end
842
843     ##
844     # Overridden by subclasses that need it.
845           def min(data_point, index)
846       data_point
847     end
848    
849     def significant(inc)
850       return 1.0 if inc == 0 # Keep from going into infinite loop
851       factor = 1.0
852       while (inc < 10)
853         inc *= 10
854         factor /= 10
855       end
856
857       while (inc > 100)
858         inc /= 10
859         factor *= 10
860       end
861
862       res = inc.floor * factor
863       if (res.to_i.to_f == res)
864         res.to_i
865       else
866         res
867       end
868     end
869
870     # Sort with largest overall summed value at front of array 
871     # so it shows up correctly in the drawn graph.
872     def sort_norm_data
873       @norm_data.sort! { |a,b| sums(b[1]) <=> sums(a[1]) }
874     end
875
876     def sums(data_set)
877       total_sum = 0
878       data_set.collect {|num| total_sum += num.to_f }
879       total_sum
880     end
881
882     ##
883     # Used by StackedBar and child classes.
884     #
885     # May need to be moved to the StackedBar class.
886     
887     def get_maximum_by_stack
888       # Get sum of each stack
889       max_hash = {}
890       @data.each do |data_set|
891         data_set[DATA_VALUES_INDEX].each_with_index do |data_point, i|
892           max_hash[i] = 0.0 unless max_hash[i]
893           max_hash[i] += data_point.to_f
894         end
895       end
896
897       # @maximum_value = 0
898       max_hash.keys.each do |key|
899         @maximum_value = max_hash[key] if max_hash[key] > @maximum_value
900       end
901       @minimum_value = 0
902     end
903
904     def make_stacked
905       stacked_values = Array.new(@column_count, 0)
906       @data.each do |value_set|
907         value_set[1].each_with_index do |value, index|
908           stacked_values[index] += value
909         end
910         value_set[1] = stacked_values.dup
911       end
912     end
913
914 private
915     
916     # Takes a block and draws it if DEBUG is true.
917     #
918     #   debug { @d.rectangle x1, y1, x2, y2 }
919     #
920     def debug
921       if DEBUG
922         @d = @d.fill 'transparent'
923         @d = @d.stroke 'turquoise'
924         @d = yield
925       end
926     end
927     
928     def increment_color
929       if @color_index == 0
930         @color_index += 1
931         return @colors[0]
932       else
933         if @color_index < @colors.length
934           @color_index += 1
935           return @colors[@color_index - 1]
936         else
937           # Start over
938           @color_index = 0
939           return @colors[-1]
940         end
941       end
942     end
943
944     ##
945     # Return a formatted string representing a number value that should be printed as a label.   
946
947     def label(value)      
948       if (@spread.to_f % @marker_count.to_f == 0) || !@y_axis_increment.nil?
949         return value.to_i.to_s
950       end
951       
952       if @spread > 10.0
953         sprintf("%0i", value)
954       elsif @spread >= 3.0
955         sprintf("%0.2f", value)
956       else
957         value.to_s
958       end
959     end
960
961     ##
962     # Returns the height of the capital letter 'X' for the current font and size.
963     #
964     # Not scaled since it deals with dimensions that the regular 
965     # scaling will handle.
966     #
967     def calculate_caps_height(font_size)
968       @d.pointsize = font_size
969       @d.get_type_metrics(@base_image, 'X').height
970     end
971
972     ##
973     # Returns the width of a string at this pointsize.
974     #
975     # Not scaled since it deals with dimensions that the regular 
976     # scaling will handle.
977     #    
978     def calculate_width(font_size, text)
979       @d.pointsize = font_size
980       @d.get_type_metrics(@base_image, text.to_s).width
981     end
982
983   end # Gruff::Base
984   
985   class IncorrectNumberOfDatasetsException < StandardError; end
986           
987 end # Gruff
988
989
990 module Magick
991   
992   class Draw
993     
994     # Additional method since Draw.scale doesn't affect annotations.
995     def annotate_scaled(img, width, height, x, y, text, scale)
996       scaled_width = (width * scale) >= 1 ? (width * scale) : 1
997       scaled_height = (height * scale) >= 1 ? (height * scale) : 1
998       
999       self.annotate( img, 
1000                       scaled_width, scaled_height,
1001                       x * scale, y * scale,
1002                       text)
1003     end
1004     
1005   end
1006   
1007 end # Magick
1008

Benjamin Mako Hill || Want to submit a patch?