]> git.cworth.org Git - sup/blob - lib/sup/util.rb
fix garbaged text in textfield when using ncursesw
[sup] / lib / sup / util.rb
1 require 'thread'
2 require 'lockfile'
3 require 'mime/types'
4 require 'pathname'
5
6 ## time for some monkeypatching!
7 class Lockfile
8   def gen_lock_id
9     Hash[
10          'host' => "#{ Socket.gethostname }",
11          'pid' => "#{ Process.pid }",
12          'ppid' => "#{ Process.ppid }",
13          'time' => timestamp,
14          'pname' => $0,
15          'user' => ENV["USER"]
16         ]
17   end
18
19   def dump_lock_id lock_id = @lock_id
20       "host: %s\npid: %s\nppid: %s\ntime: %s\nuser: %s\npname: %s\n" %
21         lock_id.values_at('host','pid','ppid','time','user', 'pname')
22     end
23
24   def lockinfo_on_disk
25     h = load_lock_id IO.read(path)
26     h['mtime'] = File.mtime path
27     h
28   end
29
30   def touch_yourself; touch path end
31 end
32
33 class Pathname
34   def human_size
35     s =
36       begin
37         size
38       rescue SystemCallError
39         return "?"
40       end
41     s.to_human_size
42   end
43
44   def human_time
45     begin
46       ctime.strftime("%Y-%m-%d %H:%M")
47     rescue SystemCallError
48       "?"
49     end
50   end
51 end
52
53 ## more monkeypatching!
54 module RMail
55   class EncodingUnsupportedError < StandardError; end
56
57   class Message
58     def self.make_file_attachment fn
59       bfn = File.basename fn
60       t = MIME::Types.type_for(bfn).first || MIME::Types.type_for("exe").first
61       make_attachment IO.read(fn), t.content_type, t.encoding, bfn.to_s
62     end
63
64     def charset
65       if header.field?("content-type") && header.fetch("content-type") =~ /charset="?(.*?)"?(;|$)/i
66         $1
67       end
68     end
69
70     def self.make_attachment payload, mime_type, encoding, filename
71       a = Message.new
72       a.header.add "Content-Disposition", "attachment; filename=#{filename.inspect}"
73       a.header.add "Content-Type", "#{mime_type}; name=#{filename.inspect}"
74       a.header.add "Content-Transfer-Encoding", encoding if encoding
75       a.body =
76         case encoding
77         when "base64"
78           [payload].pack "m"
79         when "quoted-printable"
80           [payload].pack "M"
81         when "7bit", "8bit", nil
82           payload
83         else
84           raise EncodingUnsupportedError, encoding.inspect
85         end
86       a
87     end
88   end
89 end
90
91 class Range
92   ## only valid for integer ranges (unless I guess it's exclusive)
93   def size 
94     last - first + (exclude_end? ? 0 : 1)
95   end
96 end
97
98 class Module
99   def bool_reader *args
100     args.each { |sym| class_eval %{ def #{sym}?; @#{sym}; end } }
101   end
102   def bool_writer *args; attr_writer(*args); end
103   def bool_accessor *args
104     bool_reader(*args)
105     bool_writer(*args)
106   end
107
108   def defer_all_other_method_calls_to obj
109     class_eval %{
110       def method_missing meth, *a, &b; @#{obj}.send meth, *a, &b; end
111       def respond_to?(m, include_private = false)
112         @#{obj}.respond_to?(m, include_private)
113       end
114     }
115   end
116 end
117
118 class Object
119   def ancestors
120     ret = []
121     klass = self.class
122
123     until klass == Object
124       ret << klass
125       klass = klass.superclass
126     end
127     ret
128   end
129
130   ## "k combinator"
131   def returning x; yield x; x; end
132
133   ## clone of java-style whole-method synchronization
134   ## assumes a @mutex variable
135   ## TODO: clean up, try harder to avoid namespace collisions
136   def synchronized *methods
137     methods.each do |meth|
138       class_eval <<-EOF
139         alias unsynchronized_#{meth} #{meth}
140         def #{meth}(*a, &b)
141           @mutex.synchronize { unsynchronized_#{meth}(*a, &b) }
142         end
143       EOF
144     end
145   end
146
147   def ignore_concurrent_calls *methods
148     methods.each do |meth|
149       mutex = "@__concurrent_protector_#{meth}"
150       flag = "@__concurrent_flag_#{meth}"
151       oldmeth = "__unprotected_#{meth}"
152       class_eval <<-EOF
153         alias #{oldmeth} #{meth}
154         def #{meth}(*a, &b)
155           #{mutex} = Mutex.new unless defined? #{mutex}
156           #{flag} = true unless defined? #{flag}
157           run = #{mutex}.synchronize do
158             if #{flag}
159               #{flag} = false
160               true
161             end
162           end
163           if run
164             ret = #{oldmeth}(*a, &b)
165             #{mutex}.synchronize { #{flag} = true }
166             ret
167           end
168         end
169       EOF
170     end
171   end
172 end
173
174 class String
175   ## nasty multibyte hack for ruby 1.8. if it's utf-8, split into chars using
176   ## the utf8 regex and count those. otherwise, use the byte length.
177   def display_length
178     if $encoding == "UTF-8"
179       scan(/./u).size
180     else
181       size
182     end
183   end
184
185   def camel_to_hyphy
186     self.gsub(/([a-z])([A-Z0-9])/, '\1-\2').downcase
187   end
188
189   def find_all_positions x
190     ret = []
191     start = 0
192     while start < length
193       pos = index x, start
194       break if pos.nil?
195       ret << pos
196       start = pos + 1
197     end
198     ret
199   end
200
201   ## a very complicated regex found on teh internets to split on
202   ## commas, unless they occurr within double quotes.
203   def split_on_commas
204     split(/,\s*(?=(?:[^"]*"[^"]*")*(?![^"]*"))/)
205   end
206
207   ## ok, here we do it the hard way. got to have a remainder for purposes of
208   ## tab-completing full email addresses
209   def split_on_commas_with_remainder
210     ret = []
211     state = :outstring
212     pos = 0
213     region_start = 0
214     while pos <= length
215       newpos = case state
216         when :escaped_instring, :escaped_outstring then pos
217         else index(/[,"\\]/, pos)
218       end 
219       
220       if newpos
221         char = self[newpos]
222       else
223         char = nil
224         newpos = length
225       end
226
227       case char
228       when ?"
229         state = case state
230           when :outstring then :instring
231           when :instring then :outstring
232           when :escaped_instring then :instring
233           when :escaped_outstring then :outstring
234         end
235       when ?,, nil
236         state = case state
237           when :outstring, :escaped_outstring then
238             ret << self[region_start ... newpos].gsub(/^\s+|\s+$/, "")
239             region_start = newpos + 1
240             :outstring
241           when :instring then :instring
242           when :escaped_instring then :instring
243         end
244       when ?\\
245         state = case state
246           when :instring then :escaped_instring
247           when :outstring then :escaped_outstring
248           when :escaped_instring then :instring
249           when :escaped_outstring then :outstring
250         end
251       end
252       pos = newpos + 1
253     end
254
255     remainder = case state
256       when :instring
257         self[region_start .. -1].gsub(/^\s+/, "")
258       else
259         nil
260       end
261
262     [ret, remainder]
263   end
264
265   def wrap len
266     ret = []
267     s = self
268     while s.length > len
269       cut = s[0 ... len].rindex(/\s/)
270       if cut
271         ret << s[0 ... cut]
272         s = s[(cut + 1) .. -1]
273       else
274         ret << s[0 ... len]
275         s = s[len .. -1]
276       end
277     end
278     ret << s
279   end
280
281   def normalize_whitespace
282     gsub(/\t/, "    ").gsub(/\r/, "")
283   end
284
285   unless method_defined? :ord
286     def ord
287       self[0]
288     end
289   end
290
291   ## takes a space-separated list of words, and returns an array of symbols.
292   ## typically used in Sup for translating Ferret's representation of a list
293   ## of labels (a string) to an array of label symbols.
294   def symbolistize; split.map { |x| x.intern } end
295 end
296
297 class Numeric
298   def clamp min, max
299     if self < min
300       min
301     elsif self > max
302       max
303     else
304       self
305     end
306   end
307
308   def in? range; range.member? self; end
309
310   def to_human_size
311     if self < 1024
312       to_s + "b"
313     elsif self < (1024 * 1024)
314       (self / 1024).to_s + "k"
315     elsif self < (1024 * 1024 * 1024)
316       (self / 1024 / 1024).to_s + "m"
317     else
318       (self / 1024 / 1024 / 1024).to_s + "g"
319     end
320   end
321 end
322
323 class Fixnum
324   def to_character
325     if self < 128 && self >= 0
326       chr
327     else
328       "<#{self}>"
329     end
330   end
331
332   ## hacking the english language
333   def pluralize s
334     to_s + " " +
335       if self == 1
336         s
337       else
338         if s =~ /(.*)y$/
339           $1 + "ies"
340         else
341           s + "s"
342         end
343       end
344   end
345 end
346
347 class Hash
348   def - o
349     Hash[*self.map { |k, v| [k, v] unless o.include? k }.compact.flatten_one_level]
350   end
351
352   def select_by_value v=true
353     select { |k, vv| vv == v }.map { |x| x.first }
354   end
355 end
356
357 module Enumerable
358   def map_with_index
359     ret = []
360     each_with_index { |x, i| ret << yield(x, i) }
361     ret
362   end
363
364   def sum; inject(0) { |x, y| x + y }; end
365   
366   def map_to_hash
367     ret = {}
368     each { |x| ret[x] = yield(x) }
369     ret
370   end
371
372   # like find, except returns the value of the block rather than the
373   # element itself.
374   def argfind
375     ret = nil
376     find { |e| ret ||= yield(e) }
377     ret || nil # force
378   end
379
380   def argmin
381     best, bestval = nil, nil
382     each do |e|
383       val = yield e
384       if bestval.nil? || val < bestval
385         best, bestval = e, val
386       end
387     end
388     best
389   end
390
391   ## returns the maximum shared prefix of an array of strings
392   ## optinally excluding a prefix
393   def shared_prefix caseless=false, exclude=""
394     return "" if empty?
395     prefix = ""
396     (0 ... first.length).each do |i|
397       c = (caseless ? first.downcase : first)[i]
398       break unless all? { |s| (caseless ? s.downcase : s)[i] == c }
399       next if exclude[i] == c
400       prefix += first[i].chr
401     end
402     prefix
403   end
404
405   def max_of
406     map { |e| yield e }.max
407   end
408 end
409
410 class Array
411   def flatten_one_level
412     inject([]) { |a, e| a + e }
413   end
414
415   def to_h; Hash[*flatten]; end
416   def rest; self[1..-1]; end
417
418   def to_boolean_h; Hash[*map { |x| [x, true] }.flatten]; end
419
420   def last= e; self[-1] = e end
421   def nonempty?; !empty? end
422
423   def to_set_of_symbols
424     map { |x| x.is_a?(Symbol) ? x : x.intern }.uniq
425   end
426 end
427
428 class Time
429   def to_indexable_s
430     sprintf "%012d", self
431   end
432
433   def nearest_hour
434     if min < 30
435       self
436     else
437       self + (60 - min) * 60
438     end
439   end
440
441   def midnight # within a second
442     self - (hour * 60 * 60) - (min * 60) - sec
443   end
444
445   def is_the_same_day? other
446     (midnight - other.midnight).abs < 1
447   end
448
449   def is_the_day_before? other
450     other.midnight - midnight <=  24 * 60 * 60 + 1
451   end
452
453   def to_nice_distance_s from=Time.now
454     later_than = (self < from)
455     diff = (self.to_i - from.to_i).abs.to_f
456     text = 
457       [ ["second", 60],
458         ["minute", 60],
459         ["hour", 24],
460         ["day", 7],
461         ["week", 4.345], # heh heh
462         ["month", 12],
463         ["year", nil],
464       ].argfind do |unit, size|
465         if diff.round <= 1
466           "one #{unit}"
467         elsif size.nil? || diff.round < size
468           "#{diff.round} #{unit}s"
469         else
470           diff /= size.to_f
471           false
472         end
473       end
474     if later_than
475       text + " ago"
476     else
477       "in " + text
478     end  
479   end
480
481   TO_NICE_S_MAX_LEN = 9 # e.g. "Yest.10am"
482   def to_nice_s from=Time.now
483     if year != from.year
484       strftime "%b %Y"
485     elsif month != from.month
486       strftime "%b %e"
487     else
488       if is_the_same_day? from
489         strftime("%l:%M%P")
490       elsif is_the_day_before? from
491         "Yest."  + nearest_hour.strftime("%l%P")
492       else
493         strftime "%b %e"
494       end
495     end
496   end
497 end
498
499 ## simple singleton module. far less complete and insane than the ruby
500 ## standard library one, but automatically forwards methods calls and
501 ## allows for constructors that take arguments.
502 ##
503 ## You must have #initialize call "self.class.i_am_the_instance self"
504 ## at some point or everything will fail horribly.
505 module Singleton
506   module ClassMethods
507     def instance; @instance; end
508     def instantiated?; defined?(@instance) && !@instance.nil?; end
509     def deinstantiate!; @instance = nil; end
510     def method_missing meth, *a, &b
511       raise "no instance defined!" unless defined? @instance
512
513       ## if we've been deinstantiated, just drop all calls. this is
514       ## useful because threads that might be active during the
515       ## cleanup process (e.g. polling) would otherwise have to
516       ## special-case every call to a Singleton object
517       return nil if @instance.nil?
518
519       @instance.send meth, *a, &b
520     end
521     def i_am_the_instance o
522       raise "there can be only one! (instance)" if defined? @instance
523       @instance = o
524     end
525   end
526
527   def self.included klass
528     klass.extend ClassMethods
529   end
530 end
531
532 ## wraps an object. if it throws an exception, keeps a copy.
533 class Recoverable
534   def initialize o
535     @o = o
536     @error = nil
537     @mutex = Mutex.new
538   end
539
540   attr_accessor :error
541
542   def clear_error!; @error = nil; end
543   def has_errors?; !@error.nil?; end
544
545   def method_missing m, *a, &b; __pass m, *a, &b end
546   
547   def id; __pass :id; end
548   def to_s; __pass :to_s; end
549   def to_yaml x; __pass :to_yaml, x; end
550   def is_a? c; @o.is_a? c; end
551
552   def respond_to?(m, include_private=false)
553     @o.respond_to?(m, include_private)
554   end
555
556   def __pass m, *a, &b
557     begin
558       @o.send(m, *a, &b)
559     rescue Exception => e
560       @error ||= e
561       raise
562     end
563   end
564 end
565
566 ## acts like a hash with an initialization block, but saves any
567 ## newly-created value even upon lookup.
568 ##
569 ## for example:
570 ##
571 ## class C
572 ##   attr_accessor :val
573 ##   def initialize; @val = 0 end
574 ## end
575 ## 
576 ## h = Hash.new { C.new }
577 ## h[:a].val # => 0
578 ## h[:a].val = 1
579 ## h[:a].val # => 0
580 ##
581 ## h2 = SavingHash.new { C.new }
582 ## h2[:a].val # => 0
583 ## h2[:a].val = 1
584 ## h2[:a].val # => 1
585 ##
586 ## important note: you REALLY want to use #member? to test existence,
587 ## because just checking h[anything] will always evaluate to true
588 ## (except for degenerate constructor blocks that return nil or false)
589 class SavingHash
590   def initialize &b
591     @constructor = b
592     @hash = Hash.new
593   end
594
595   def [] k
596     @hash[k] ||= @constructor.call(k)
597   end
598
599   defer_all_other_method_calls_to :hash
600 end
601
602 class OrderedHash < Hash
603   alias_method :store, :[]=
604   alias_method :each_pair, :each
605   attr_reader :keys
606
607   def initialize *a
608     @keys = []
609     a.each { |k, v| self[k] = v }
610   end
611
612   def []= key, val
613     @keys << key unless member?(key)
614     super
615   end
616
617   def values; keys.map { |k| self[k] } end
618   def index key; @keys.index key end
619
620   def delete key
621     @keys.delete key
622     super
623   end
624
625   def each; @keys.each { |k| yield k, self[k] } end
626 end
627
628 ## easy thread-safe class for determining who's the "winner" in a race (i.e.
629 ## first person to hit the finish line
630 class FinishLine
631   def initialize
632     @m = Mutex.new
633     @over = false
634   end
635
636   def winner?
637     @m.synchronize { !@over && @over = true }
638   end
639 end
640
641 class Iconv
642   def self.easy_decode target, charset, text
643     return text if charset =~ /^(x-unknown|unknown[-_ ]?8bit|ascii[-_ ]?7[-_ ]?bit)$/i
644     charset = case charset
645       when /UTF[-_ ]?8/i then "utf-8"
646       when /(iso[-_ ])?latin[-_ ]?1$/i then "ISO-8859-1"
647       when /iso[-_ ]?8859[-_ ]?15/i then 'ISO-8859-15'
648       when /unicode[-_ ]1[-_ ]1[-_ ]utf[-_]7/i then "utf-7"
649       else charset
650     end
651
652     begin
653       Iconv.iconv(target + "//IGNORE", charset, text + " ").join[0 .. -2]
654     rescue Errno::EINVAL, Iconv::InvalidEncoding, Iconv::InvalidCharacter, Iconv::IllegalSequence => e
655       Redwood::log "warning: error (#{e.class.name}) decoding text from #{charset} to #{target}: #{text[0 ... 20]}"
656       text
657     end
658   end
659 end