]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/core/utils/extends.rb
Color codes and Irc.color(fg, bg) methods to ease color display
[user/henk/code/ruby/rbot.git] / lib / rbot / core / utils / extends.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: Standard classes extensions
5 #
6 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
7 # Copyright:: (C) 2006,2007 Giuseppe Bilotta
8 # License:: GPL v2
9 #
10 # This file collects extensions to standard Ruby classes and to some core rbot
11 # classes to be used by the various plugins
12 #
13 # Please note that global symbols have to be prefixed by :: because this plugin
14 # will be read into an anonymous module
15
16 # Extensions to the Module class
17 #
18 class ::Module
19
20   # Many plugins define Struct objects to hold their data. On rescans, lots of
21   # warnings are echoed because of the redefinitions. Using this method solves
22   # the problem, by checking if the Struct already exists, and if it has the
23   # same attributes
24   #
25   def define_structure(name, *members)
26     sym = name.to_sym
27     if Struct.const_defined?(sym)
28       kl = Struct.const_get(sym)
29       if kl.new.members.map { |member| member.intern } == members.map
30         debug "Struct #{sym} previously defined, skipping"
31         const_set(sym, kl)
32         return
33       end
34     end
35     debug "Defining struct #{sym} with members #{members.inspect}"
36     const_set(sym, Struct.new(name.to_s, *members))
37   end
38 end
39
40
41 # Extensions to the Array class
42 #
43 class ::Array
44
45   # This method returns a random element from the array, or nil if the array is
46   # empty
47   #
48   def pick_one
49     return nil if self.empty?
50     self[rand(self.length)]
51   end
52 end
53
54 # Extensions to the Range class
55 #
56 class ::Range
57
58   # This method returns a random number between the lower and upper bound
59   #
60   def pick_one
61     len = self.last - self.first
62     len += 1 unless self.exclude_end?
63     self.first + Kernel::rand(len)
64   end
65   alias :rand :pick_one
66 end
67
68 # Extensions for the Numeric classes
69 #
70 class ::Numeric
71
72   # This method forces a real number to be not more than a given positive
73   # number or not less than a given positive number, or between two any given
74   # numbers
75   #
76   def clip(left,right=0)
77     raise ArgumentError unless left.kind_of?(Numeric) and right.kind_of?(Numeric)
78     l = [left,right].min
79     u = [left,right].max
80     return l if self < l
81     return u if self > u
82     return self
83   end
84 end
85
86 # Extensions to the String class
87 #
88 # TODO make riphtml() just call ircify_html() with stronger purify options.
89 #
90 class ::String
91
92   # This method will return a purified version of the receiver, with all HTML
93   # stripped off and some of it converted to IRC formatting
94   #
95   def ircify_html(opts={})
96     txt = self.dup
97
98     # remove scripts
99     txt.gsub!(/<script(?:\s+[^>]*)?>.*?<\/script>/im, "")
100
101     # remove styles
102     txt.gsub!(/<style(?:\s+[^>]*)?>.*?<\/style>/im, "")
103
104     # bold and strong -> bold
105     txt.gsub!(/<\/?(?:b|strong)(?:\s+[^>]*)?>/im, "#{Bold}")
106
107     # italic, emphasis and underline -> underline
108     txt.gsub!(/<\/?(?:i|em|u)(?:\s+[^>]*)?>/im, "#{Underline}")
109
110     ## This would be a nice addition, but the results are horrible
111     ## Maybe make it configurable?
112     # txt.gsub!(/<\/?a( [^>]*)?>/, "#{Reverse}")
113     case val = opts[:a_href]
114     when Reverse, Bold, Underline
115       txt.gsub!(/<(?:\/a\s*|a (?:[^>]*\s+)?href\s*=\s*(?:[^>]*\s*)?)>/, val)
116     when :link_out
117       # Not good for nested links, but the best we can do without something like hpricot
118       txt.gsub!(/<a (?:[^>]*\s+)?href\s*=\s*(?:([^"'>][^\s>]*)\s+|"((?:[^"]|\\")*)"|'((?:[^']|\\')*)')(?:[^>]*\s+)?>(.*?)<\/a>/) { |match|
119         debug match
120         debug [$1, $2, $3, $4].inspect
121         link = $1 || $2 || $3
122         str = $4
123         str + ": " + link
124       }
125     else
126       warning "unknown :a_href option #{val} passed to ircify_html" if val
127     end
128
129     # Paragraph and br tags are converted to whitespace
130     txt.gsub!(/<\/?(p|br)(?:\s+[^>]*)?\s*\/?\s*>/i, ' ')
131     txt.gsub!("\n", ' ')
132     txt.gsub!("\r", ' ')
133
134     # Superscripts and subscripts are turned into ^{...} and _{...}
135     # where the {} are omitted for single characters
136     txt.gsub!(/<sup>(.*?)<\/sup>/, '^{\1}')
137     txt.gsub!(/<sub>(.*?)<\/sub>/, '_{\1}')
138     txt.gsub!(/(^|_)\{(.)\}/, '\1\2')
139
140     # All other tags are just removed
141     txt.gsub!(/<[^>]+>/, '')
142
143     # Convert HTML entities. We do it now to be able to handle stuff
144     # such as &nbsp;
145     txt = Utils.decode_html_entities(txt)
146
147     # Remove double formatting options, since they only waste bytes
148     txt.gsub!(/#{Bold}(\s*)#{Bold}/, '\1')
149     txt.gsub!(/#{Underline}(\s*)#{Underline}/, '\1')
150
151     # Simplify whitespace that appears on both sides of a formatting option
152     txt.gsub!(/\s+(#{Bold}|#{Underline})\s+/, ' \1')
153     txt.sub!(/\s+(#{Bold}|#{Underline})\z/, '\1')
154     txt.sub!(/\A(#{Bold}|#{Underline})\s+/, '\1')
155
156     # And finally whitespace is squeezed
157     txt.gsub!(/\s+/, ' ')
158     txt.strip!
159
160     if opts[:limit] && txt.size > opts[:limit]
161       txt = txt.slice(0, opts[:limit]) + "#{Reverse}...#{Reverse}"
162     end
163
164     # Decode entities and strip whitespace
165     return txt
166   end
167
168   # As above, but modify the receiver
169   #
170   def ircify_html!(opts={})
171     old_hash = self.hash
172     replace self.ircify_html(opts)
173     return self unless self.hash == old_hash
174   end
175
176   # This method will strip all HTML crud from the receiver
177   #
178   def riphtml
179     self.gsub(/<[^>]+>/, '').gsub(/&amp;/,'&').gsub(/&quot;/,'"').gsub(/&lt;/,'<').gsub(/&gt;/,'>').gsub(/&ellip;/,'...').gsub(/&apos;/, "'").gsub("\n",'')
180   end
181 end
182
183
184 # Extensions to the Regexp class, with some common and/or complex regular
185 # expressions.
186 #
187 class ::Regexp
188
189   # A method to build a regexp that matches a list of something separated by
190   # optional commas and/or the word "and", an optionally repeated prefix,
191   # and whitespace.
192   def Regexp.new_list(reg, pfx = "")
193     if pfx.kind_of?(String) and pfx.empty?
194       return %r(#{reg}(?:,?(?:\s+and)?\s+#{reg})*)
195     else
196       return %r(#{reg}(?:,?(?:\s+and)?(?:\s+#{pfx})?\s+#{reg})*)
197     end
198   end
199
200   IN_ON = /in|on/
201
202   module Irc
203     # Match a list of channel anmes separated by optional commas, whitespace
204     # and optionally the word "and"
205     CHAN_LIST = Regexp.new_list(GEN_CHAN)
206
207     # Match "in #channel" or "on #channel" and/or "in private" (optionally
208     # shortened to "in pvt"), returning the channel name or the word 'private'
209     # or 'pvt' as capture
210     IN_CHAN = /#{IN_ON}\s+(#{GEN_CHAN})|(here)|/
211     IN_CHAN_PVT = /#{IN_CHAN}|in\s+(private|pvt)/
212
213     # As above, but with channel lists
214     IN_CHAN_LIST_SFX = Regexp.new_list(/#{GEN_CHAN}|here/, IN_ON)
215     IN_CHAN_LIST = /#{IN_ON}\s+#{IN_CHAN_LIST_SFX}|anywhere|everywhere/
216     IN_CHAN_LIST_PVT_SFX = Regexp.new_list(/#{GEN_CHAN}|here|private|pvt/, IN_ON)
217     IN_CHAN_LIST_PVT = /#{IN_ON}\s+#{IN_CHAN_LIST_PVT_SFX}|anywhere|everywhere/
218
219     # Match a list of nicknames separated by optional commas, whitespace and
220     # optionally the word "and"
221     NICK_LIST = Regexp.new_list(GEN_NICK)
222
223   end
224
225 end
226
227
228 module ::Irc
229
230   # Define standard IRC attriubtes (not so standard actually,
231   # but the closest thing we have ...)
232   Bold = "\002"
233   Underline = "\037"
234   Reverse = "\026"
235   Italic = "\011"
236   NormalText = "\017"
237
238   # Color is prefixed by \003 and followed by optional
239   # foreground and background specifications, two-digits-max
240   # numbers separated by a comma. One of the two parts
241   # must be present.
242   Color = "\003"
243   ColorRx = /#{Color}\d?\d?(?:,\d\d?)?/
244
245   # Standard color codes
246   ColorCode = {
247     :black      => 1,
248     :blue       => 2,
249     :navyblue   => 2,
250     :navy_blue  => 2,
251     :green      => 3,
252     :red        => 4,
253     :brown      => 5,
254     :purple     => 6,
255     :olive      => 7,
256     :yellow     => 8,
257     :limegreen  => 9,
258     :lime_green => 9,
259     :teal       => 10,
260     :aqualight  => 11,
261     :aqua_light => 11,
262     :royal_blue => 12,
263     :hotpink    => 13,
264     :hot_pink   => 13,
265     :darkgray   => 14,
266     :dark_gray  => 14,
267     :lightgray  => 15,
268     :light_gray => 15,
269     :white      => 16
270   }
271
272   # Convert a String or Symbol into a color number
273   def Irc.find_color(data)
274     if Integer === data
275       data
276     else
277       f = if String === data
278             data.intern
279           else
280             data
281           end
282       if ColorCode.key?(f)
283         ColorCode[f] 
284       else
285         0
286       end
287     end
288   end
289
290   # Insert the full color code for a given
291   # foreground/background combination.
292   def Irc.color(fg=nil,bg=nil)
293     str = Color.dup
294     if fg
295      str << Irc.find_color(fg).to_s
296     end
297     if bg
298       str << "," << Irc.find_color(bg).to_s
299     end
300     return str
301   end
302
303
304   class BasicUserMessage
305
306     # We extend the BasicUserMessage class with a method that parses a string
307     # which is a channel list as matched by IN_CHAN(_LIST) and co. The method
308     # returns an array of channel names, where 'private' or 'pvt' is replaced
309     # by the Symbol :"?", 'here' is replaced by the channel of the message or
310     # by :"?" (depending on whether the message target is the bot or a
311     # Channel), and 'anywhere' and 'everywhere' are replaced by Symbol :*
312     #
313     def parse_channel_list(string)
314       return [:*] if [:anywhere, :everywhere].include? string.to_sym
315       string.scan(
316       /(?:^|,?(?:\s+and)?\s+)(?:in|on\s+)?(#{Regexp::Irc::GEN_CHAN}|here|private|pvt)/
317                  ).map { |chan_ar|
318         chan = chan_ar.first
319         case chan.to_sym
320         when :private, :pvt
321           :"?"
322         when :here
323           case self.target
324           when Channel
325             self.target.name
326           else
327             :"?"
328           end
329         else
330           chan
331         end
332       }.uniq
333     end
334   end
335 end