前回 で作成したプログラムに、ポップアップメニューから「コピー」「切り取り」「貼り付け」の機能を追加する。
ポップアップメニューの作成は、「逆引き Ruby/Tk」の「ポップアップメニューを作る」で実装方法を発見した。
「コピー」「切り取り」「貼り付け」の実装方法がわからず、ソースコードを見ることに。
tk/text.rbを見ると、「text_cut」「text_copy」「text_paste」という、まさにそのままのメソッドを発見して、無事に完成。
ちなみに環境は、Windows + [One-Click Installer 1.8.2-15][4]
#!/usr/bin/env ruby
$KCODE = 'SJIS'
require 'tk'
require 'bluecloth'
class MarkdownEditor
TITLE = 'Markdown Editor'
def initialize
Tk.root.title(TITLE)
f = TkFrame.new.pack(:fill => :x)
@button = TkButton.new(f,
'text'=>'Change Mode',
'command' => proc{swich_mode()}
).pack('side' => 'left')
@label = TkLabel.new(f).pack(:side => :left)
scr_x = TkScrollbar.new.pack(:fill=>:x, :side=>:bottom)
scr_y = TkScrollbar.new.pack(:fill=>:y, :side=>:right)
@editor = TkText.new {
xscrollbar(scr_x)
yscrollbar(scr_y)
}.pack(:fill => :both, :expand => true)
menu = TkMenu.new { tearoff 'off' }
menu.add('command', :label => 'Cut', :command => proc{ @editor.text_cut })
menu.add('command', :label => 'Copy', :command => proc{ @editor.text_copy })
menu.add('command', :label => 'Paste', :command => proc{ @editor.text_paste })
@editor.bind('ButtonPress-3', proc { |x, y| menu.popup(x, y) }, "%X %Y")
to_text()
Tk.mainloop
end
def to_html
return if @state == :html
begin
Tk.root.cursor "watch"
Tk.root.update
@state = :html
@label.text('HTML Mode')
@source = @editor.value
@editor.value = BlueCloth::new(@source).to_html
ensure
Tk.root.cursor ""
Tk.root.update
end
end
def to_text
return if @state == :text
@state = :text
@label.text('Text Mode')
@editor.value = @source
end
# モードを切り替える
def swich_mode
case @state
when :text
to_html()
when :html
to_text()
end
end
end
if __FILE__ == $0
MarkdownEditor.new
end
[4]; http://rubyforge.org/frs/?groupid=167&releaseid=2049