bugfix: safety against breaking the AI if you press undo while it's thinking
[kaya.git] / lib / constrained_text_item.rb
blob3d06ebcc7a21507c3b3bbb0558f2a154bad9e300
1 # Copyright (c) 2009 Paolo Capriotti <p.capriotti@gmail.com>
2
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 2 of the License, or
6 # (at your option) any later version.
8 require 'toolkit'
10 class ConstrainedTextItem < Qt::GraphicsItem
11   attr_reader :text
13   def initialize(text, parent, constraint = Qt::RectF.new, opts = {})
14     super(parent)
15     @text = text.to_s
16     @parent = parent
17     @constraint = constraint
18     
19     @font = opts[:font] || Qt::Font.new
20     @fm = Qt::FontMetrics.new(@font)
21     @color = opts[:color] || Qt::Color.new(Qt::black)
22     
23     update_metrics
24   end
25   
26   def paint(p, opts, widget)
27     p.pen = @color
28     p.font = @font
29     p.saving do
30       p.translate(@constraint.center)
31       p.scale(@factor, @factor)
32       p.translate(-@brect_max.center)
33       p.draw_text((@brect_max.width - @brect.width) / 2, 0, @text)
34     end
35   end
36   
37   def boundingRect
38     @constraint
39   end
41   def text=(value)
42     @text = value.to_s
43     update_metrics
44     update @constraint
45   end
46   
47   def constraint=(value)
48     @constraint = value
49     update_metrics
50     update @constraint
51   end
52   
53   def color=(value)
54     @color = value
55     update @constraint
56   end
57   
58   def update_metrics
59     if @text.empty?
60       @brect = @constraint
61       @brect_max = @constraint
62       @factor = 1.0
63     else
64       @brect = @fm.bounding_rect(@text)
65       @brect_max = @fm.bounding_rect('H' * @text.size)
66       @factor = [
67         @constraint.width / @brect_max.width,
68         @constraint.height / @brect_max.height].min
69     end
70   end
71   
72   alias :name :text  
73 end