はじめてのRuby/GTK

Ruby/GTKやりました。Swingと似てますね。業務連絡になっちゃうけどこういうのは動くんですよ。

require 'gtk2'

class SampleEntry1

  def initialize
    init_window
  end

  def show
    send_focus_change(true)
    @window.show
  end

  def hide
    send_focus_change(false)
    @window.hide
  end

  def forward=(forward)
    @direction.active = forward
  end

  def forward?
    @direction.active?
  end

  def init_window
    #@window = Gtk::Window.new(Gtk::Window::POPUP)
    @window = Gtk::Window.new
    @window.decorated = false
    # modalだと閉じれないので
    #@window.modal = true
    init_frame
    init_box
    init_entry
    init_direction
  end

  def init_frame
    @frame = Gtk::Frame.new
    @frame.shadow_type = Gtk::ShadowType::ETCHED_IN
    @frame.show
    @window.add(@frame)
  end

  def init_box
    @box = Gtk::HBox.new
    @box.border_width = 3
    @box.show
    @frame.add(@box)
  end

  def init_entry
    @entry = Gtk::Entry.new
    @entry.show
    @box.add(@entry)
  end

  def init_direction
    @direction = Gtk::ToggleButton.new
    @arrow = Gtk::Arrow.new(Gtk::Arrow::LEFT, Gtk::SHADOW_NONE)
    @arrow.show
    @direction.add(@arrow)
    @direction.can_focus = false
    @direction.show
    @box.add(@direction)
    @direction.signal_connect("toggled") do |button|
      if forward?
        type = Gtk::Arrow::RIGHT
      else
        type = Gtk::Arrow::LEFT
      end
      @arrow.set(type, Gtk::SHADOW_NONE)
    end
    #@direction.active = true
  end

  def send_focus_change(focus_in)
    @entry.has_focus = focus_in
    event = Gdk::EventFocus.new(Gdk::EventFocus::FOCUS_CHANGE)
    event.window = @entry.window
    event.in = focus_in
    @entry.event(event)
    @entry.notify("has-focus")
  end
end

class SampleEntry2

  def initialize(entry1 = nil)
    @entry1 = entry1
    init_window
  end

  def init_window
    @window = Gtk::Window.new
    @window.set_size_request(200, 100)
    @window.title = "GTK Entry"
    @window.signal_connect("destroy") {Gtk.main_quit}

    vbox = Gtk::VBox.new(false, 0)
    @window.add(vbox)

    b1 = Gtk::Button.new("Show")
    b1.signal_connect("clicked") {@entry1.show}
    vbox.pack_start(b1, true, true, 0)
    b1.can_default = true

    b2 = Gtk::Button.new("Hide")
    b2.signal_connect("clicked") {@entry1.hide}
    vbox.pack_start(b2, true, true, 0)
    b2.can_default = true

    b3 = Gtk::Button.new("Quit")
    b3.signal_connect("clicked") {Gtk.main_quit}
    vbox.pack_start(b3, true, true, 0)
    b3.can_default = true

    @window.show_all
  end
end

Gtk.init

SampleEntry2.new(SampleEntry1.new)

Gtk.main

うーん。うーん。