2011年12月25日日曜日

[Ruby]Ruby+cursesで文字化け



Ubuntu11.10の環境で、ruby1.9.3+cursesを使いコンソールアプリを作ろうとしたが、日本語が文字化けし、正しく表示できず。
ncursesを試そうとしたが、gem install ncursesを実行すると、

compiling form_wrap.c
form_wrap.c: 関数 ‘rbncurs_m_new_form’ 内:
form_wrap.c:395:34: エラー: ‘struct RArray’ は ‘len’ という名前のメンバを持っていません

とエラーが表示されて、インストールできず。
ruby.hには、RArray構造体にlenは定義されているのに何でだろう?

原因不明なので、今度はffi-ncursesを試した。
https://github.com/seanohalpin/ffi-ncurses
このページのサンプルを試してみたが、
require 'ffi-ncurses'
で、次のエラーが発生。

/home/satoshi/.rvm/gems/ruby-1.9.3-p0/gems/ffi-1.0.11/lib/ffi/library.rb:121:in `block in ffi_lib': Could not open library 'ncursesw': ncursesw: cannot open shared object file: No such file or directory. (LoadError)
Could not open library 'libncursesw.so': /usr/lib/libncursesw.so: file too short.
Could not open library 'libncursesw': libncursesw: cannot open shared object file: No such file or directory.
Could not open library 'ncurses': ncurses: cannot open shared object file: No such file or directory.
Could not open library 'libncurses.so': /usr/lib/libncurses.so: file too short.
Could not open library 'libcurses': libcurses: cannot open shared object file: No such file or directory.
Could not open library 'libcurses.so': /usr/lib/libcurses.so: file too short
以下略

/usr/lib配下を調べてみる。
$ ls -l /usr/lib/libncursesw*
-rw-r--r-- 1 root root 302466 2011-09-17 04:29 /usr/lib/libncursesw.a
-rw-r--r-- 1 root root     32 2011-09-17 04:29 /usr/lib/libncursesw.so
あれ?libncuresw.soがシンボリックリンクになっていない。
$ cd /usr/lib/
/usr/lib配下を直接修正したくないが、シンボリックリンクを貼り直すか。
バックアップしてから
$ sudo mv libncursesw.so libncursesw.so.orig
シンボリックリンクを貼り直す。
$ sudo ln -s /lib/libncursesw.so.5.9 libncursesw.so
以上で次のコードが正しく動き、日本語も表示された。

# -*- coding: utf-8 -*-
require 'ffi-ncurses'

begin
  FFI::NCurses.initscr
  FFI::NCurses.clear
  FFI::NCurses.addstr("こんにちは、世界!")
  FFI::NCurses.refresh
  FFI::NCurses.getch
ensure
  FFI::NCurses.endwin
end

シンボリックリンクを貼り直したくない場合は、
$ RUBY_FFI_NCURSES_LIB=/lib/libncursesw.so.5.9 ruby プログラム名
でも可。
Ubuntuのパッケージ管理を考えると、.bashrcに
export RUBY_FFI_NCURSES_LIB=/lib/libncursesw.so.5.9
を追加しておく方が良いのかも。

==参考URL==
https://github.com/seanohalpin/ffi-ncurses/issues/7
https://github.com/ffi/ffi/issues/168