# credit to aspel from the rxvt-unicode list # vim:ft=perl ts=4 sts=4 sw=4 noet: sub _pop_overlay { my ($self, $text) = @_; my $timer = 'timer-'.time; my $ov = $self->overlay_simple(0, 0, $text); $self->{$timer} = urxvt::timer ->new ->after(5) ->cb(sub { delete $self->{$timer}; undef $ov }); } { my $loaded; my $error; my %exceptions = ( '' => 'auto', iw => 'Hebrew', 'zh-CN' => 'Chinese (Simplified)', 'zh-TW' => 'Chinese (Traditional)', ); sub code2lang { my $code = shift; if (not $loaded++) { eval "use Locale::Language"; $error = $@; } $exceptions{$code} || ($error ? '' : code2language($code)) || $code; } } sub google_translate { my ($self, $src, $dst, $set_selection) = @_; my $goog = 'WebService::Google::Language'; for ($goog, 'Encode') { eval "use $_"; if ($@) { _pop_overlay $self, "Requires $_: $@"; return; } } my $service = $goog->new( 'referer' => 'http://translator.local/', 'src' => $src, 'dest' => $dst, ); my $result = $service->translate($self->selection); my $text; if ($result->error) { $text = sprintf "Error code: %s\nMessage: %s", $result->code, $result->message; } else { my $translation; eval { $translation = Encode::decode('utf8', $result->translation); }; if ($@) { $text = "Error decoding text from UTF-8"; } else { $text = $translation; $self->selection($text) if $set_selection; } } _pop_overlay $self, $text; } sub on_start { my ($self) = @_; my @default_dst = ( qw/en/, # English qw/fr it de es/, # FIGS - France, Italy, Germany, Spain qw/pt ru hi zh-CN/, # BRIC - Brazil, Russia, India, China qw/zh-TW ja ko/, # CJK - Chinese, Japanese, Korean qw/el ar iw/, # etc. - Greek, Arabic, Hebrew ); my %lang = ( src => [''], dst => [ @default_dst ], pairs => [], ); for (keys %lang) { my $val = $self->x_resource("gt_lang.$_"); next unless defined $val; my @vals = split /,/, $val, -1; $lang{$_} = [ @vals ? @vals : '' ]; } for my $src (@{$lang{src}}) { for my $dst (@{$lang{dst}}) { push @{$lang{pairs}}, join ':', $src, $dst; } } my $base_label = $self->x_resource('gt_lang.label') || 'Google translate'; my $no_names = $self->x_resource('gt_lang.codes') ? 1 : 0; for (@{$lang{pairs}}) { my ($src, $dst) = split /:/, $_, -1; my $label = $base_label; $label .= ' ' if $label; $label .= join '->', map $no_names ? $_ : code2lang($_), $src, $dst; push @{ $self->{term}{selection_popup_hook} }, sub { ($label => sub { $self->google_translate($src, $dst, 1) }) }; } () } sub on_user_command { my ($self, $cmd) = @_; $self->google_translate($1, $2, length $3) if $cmd =~ /^google-translate:([^:]*):([^:]*)((?::1)?)$/; () }