4 # :title: Language module for rbot
6 # This module takes care of language handling for rbot:
7 # setting the core.language value, loading the appropriate
13 # This constant hash holds the mapping
14 # from long language names to the usual POSIX
15 # locale specifications
18 :british_english => 'en_GB',
19 :american_english => 'en_US',
26 :traditional_chinese => 'zh_TW',
27 :simplified_chinese => 'zh_CN'
30 # Return the shortest language for the current
32 def Language.from_locale
33 lang = locale.language
35 str = lang + "_#{locale.country}"
36 if Lang2Locale.value?(str)
37 # Get the shortest key in Lang2Locale which maps to the given lang_country
38 return Lang2Locale.select { |k, v| v == str }.transpose.first.map { |v| v.to_s }.sort { |a, b| a.length <=> b.length }.first
41 # lang_country didn't work, let's try lan
42 if Lang2Locale.value?(lang)
43 # Get the shortest key in Lang2Locale which maps to the given lang
44 return Lang2Locale.select { |k, v| v == lang }.transpose.first.map { |v| v.to_s }.sort { |a, b| a.length <=> b.length }.first
46 # all else fail, return 'english'
51 BotConfig.register BotConfigEnumValue.new('core.language',
52 :default => Irc::Language.from_locale, :wizard => true,
53 :values => Proc.new{|bot|
54 Dir.new(Config::datadir + "/languages").collect {|f|
55 f =~ /\.lang$/ ? f.gsub(/\.lang$/, "") : nil
58 :on_change => Proc.new {|bot, v| bot.lang.set_language v},
59 :desc => "Which language file the bot should use")
61 def initialize(bot, language)
67 def set_language(language)
68 lang_str = language.to_s.downcase.gsub(/\s+/,'_')
69 lang_sym = lang_str.intern
70 if Lang2Locale.key?(lang_sym)
71 setlocale(Lang2Locale[lang_sym])
72 debug "locale set to #{locale}"
75 warn "Unable to set locale, unknown language #{language} (#{lang_str})"
78 file = Config::datadir + "/languages/#{lang_str}.lang"
79 unless(FileTest.exist?(file))
80 raise "no such language: #{lang_str} (no such file #{file})"
85 return if @bot.plugins.nil?
86 @bot.plugins.core_modules.each { |p|
87 if p.respond_to?('set_language')
88 p.set_language(@language)
91 @bot.plugins.plugins.each { |p|
92 if p.respond_to?('set_language')
93 p.set_language(@language)
101 IO.foreach(@file) {|l|
105 @strings[$1] = Array.new
107 elsif(l =~ /^\s*(.*)$/)
108 @strings[current_key] << $1
118 if(@strings.has_key?(key))
119 return @strings[key][rand(@strings[key].length)]
121 raise "undefined language key"
126 File.open(@file, "w") {|file|
127 @strings.each {|key,val|