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
14 # This constant hash holds the mapping
15 # from long language names to the usual POSIX
16 # locale specifications
19 :british_english => 'en_GB',
20 :american_english => 'en_US',
27 :traditional_chinese => 'zh_TW',
28 :simplified_chinese => 'zh_CN'
30 # On WIN32 it appears necessary to have ".UTF-8" explicitly for gettext to use UTF-8
31 Lang2Locale.each_value {|v| v.replace(v + '.UTF-8')}
33 # Return the shortest language for the current
35 def Language.from_locale
36 return 'english' unless defined?(GetText)
37 lang = locale.language
39 str = lang + "_#{locale.country}"
40 if Lang2Locale.value?(str)
41 # Get the shortest key in Lang2Locale which maps to the given lang_country
42 lang_str = Lang2Locale.select { |k, v| v == str }.transpose.first.map { |v| v.to_s }.sort { |a, b| a.length <=> b.length }.first
43 if File.exist?(File.join(Config::datadir, "languages/#{lang_str}.lang"))
48 # lang_country didn't work, let's try lan
49 if Lang2Locale.value?(lang)
50 # Get the shortest key in Lang2Locale which maps to the given lang
51 lang_str = Lang2Locale.select { |k, v| v == lang }.transpose.first.map { |v| v.to_s }.sort { |a, b| a.length <=> b.length }.first
52 if File.exist?(File.join(Config::datadir, "/languages/#{lang_str}.lang"))
56 # all else fail, return 'english'
60 Config.register Config::EnumValue.new('core.language',
61 :default => Irc::Bot::Language.from_locale, :wizard => true,
62 :values => Proc.new{|bot|
63 Dir.new(Config::datadir + "/languages").collect {|f|
64 f =~ /\.lang$/ ? f.gsub(/\.lang$/, "") : nil
67 :on_change => Proc.new {|bot, v| bot.lang.set_language v},
68 :desc => "Which language file the bot should use")
70 def initialize(bot, language)
76 def set_language(language)
77 lang_str = language.to_s.downcase.gsub(/\s+/,'_')
78 lang_sym = lang_str.intern
79 if defined?(GetText) and Lang2Locale.key?(lang_sym)
80 setlocale(Lang2Locale[lang_sym])
81 debug "locale set to #{locale}"
84 warning "Unable to set locale, unknown language #{language} (#{lang_str})"
87 file = Config::datadir + "/languages/#{lang_str}.lang"
88 unless(FileTest.exist?(file))
89 raise "no such language: #{lang_str} (no such file #{file})"
94 return if @bot.plugins.nil?
95 @bot.plugins.core_modules.each { |p|
96 if p.respond_to?('set_language')
97 p.set_language(@language)
100 @bot.plugins.plugins.each { |p|
101 if p.respond_to?('set_language')
102 p.set_language(@language)
110 IO.foreach(@file) {|l|
114 @strings[$1] = Array.new
116 elsif(l =~ /^\s*(.*)$/)
117 @strings[current_key] << $1
127 if(@strings.has_key?(key))
128 return @strings[key][rand(@strings[key].length)]
130 raise "undefined language key"
135 File.open(@file, "w") {|file|
136 @strings.each {|key,val|