Skip to content

Instantly share code, notes, and snippets.

@track8
Last active December 14, 2015 01:29
Show Gist options
  • Save track8/5006542 to your computer and use it in GitHub Desktop.
Save track8/5006542 to your computer and use it in GitHub Desktop.
タイマ習作
# -*- coding: utf-8 -*-
require 'gtk2'
class CountdownTimer
def initialize(minutes, &block)
@default_block = block
reset(minutes, &block)
end
def expected_time
@initial_time + (@initial_seconds - @remain_seconds)
end
def diff(expected, actual)
h_diff = actual.hour - expected.hour
m_diff = actual.min - expected.min
s_diff = actual.sec - expected.sec
h_diff * 3600 + m_diff * 60 + s_diff
end
def adjust(diff)
@remain_seconds -= diff unless diff == 0
end
def start
@initial_time = Time.now
@th.run
end
def reset(minutes, &block)
@initial_time = Time.now
@remain_seconds = minutes * 60
@initial_seconds = @remain_seconds
block = @default_block unless block_given?
block.call(@remain_seconds)
@th = Thread.new do
Thread.stop
loop do
d = diff(expected_time, Time.now)
adjust(d)
sleep(1)
@remain_seconds -= 1
block.call(@remain_seconds)
break if @remain_seconds < 0
end
end
end
def join; @th.join; end
def kill; @th.kill; end
def self.to_minutes_string(seconds)
min, sec = seconds.divmod(60)
"#{sprintf('%02d', min)}:#{sprintf('%02d', sec)}"
end
end
# window
window = Gtk::Window.new
# layout
vbox = Gtk::VBox.new(false, 5)
vbox.border_width = 10
window.add(vbox)
align = Gtk::Alignment.new(0.5, 0.5, 1, 1)
vbox.pack_start(align, false, false, 5)
# separator
separator = Gtk::HSeparator.new
vbox.pack_start(separator, false, false, 0)
# countdown_label
style = Gtk::Style.new
style.font_desc = Pango::FontDescription.new("Avenir Heavy 256")
style.set_fg(Gtk::STATE_NORMAL, 0, 0, 0)
#style.set_bg(Gtk::STATE_NORMAL, 0xff, 0xff, 0)
countdown_label = Gtk::Label.new
countdown_label.style = style
eventbox = Gtk::EventBox.new.add(countdown_label)
eventbox.style = style
align.add(eventbox)
# table
table = Gtk::Table.new(2, 3, false)
table.row_spacings = 5
table.border_width = 5
vbox.pack_start(table, false, true, 0)
# timer
timer = CountdownTimer.new(0.25) do |seconds|
if seconds <= 0
countdown_label.text = "ラジオッス!"
else
countdown_label.text = CountdownTimer.to_minutes_string(seconds)
end
end
# start_button
start_button = Gtk::Button.new("Start")
start_button.signal_connect("clicked") { timer.start }
vbox.pack_start(start_button, false, false, 0)
start_button.can_default = true
start_button.grab_default
# clear_buton
clear_button = Gtk::Button.new("Clear")
clear_button.signal_connect("clicked") { timer.reset(0.1) }
vbox.pack_start(clear_button, false, false, 0)
# # close_button
# button = Gtk::Button.new("Close")
# button.signal_connect("clicked") {window.destroy}
# vbox.pack_start(button, false, false, 0)
window.show_all
window.signal_connect("destroy") do
timer.kill
Gtk.main_quit
end
Gtk.main
timer.join
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment