summaryrefslogtreecommitdiff
path: root/ext/tk/sample/demos-jp/timer
blob: 232f4ae5cab13db3ab0f107b7656ab5586b36768 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#!/usr/local/bin/ruby
#
# timer --
# This script generates a counter with start,stop and reset buttons.
#
# Copyright (C) 1998 Takaaki Tateishi (ttate@jaist.ac.jp)
# last update: Sat Jun 27 12:24:14 JST 1998
#

require "tk"
require "thread"
require "tkafter"

$time = "0.00"
$m = Mutex.new
$loop = false

def timer_stop
  $loop = false
  $m.lock
end

def timer_start
  $loop = true
  $m.unlock
end

def timer_reset
  $time = "0.00"
  $root.countframe.counter['text'] = $time
end

def timer_loop
  if $loop
    $time = $time.succ
    $root.countframe.counter['text'] = $time
  end
  Tk.after(10,proc{timer_loop})
end


#
# thread version
#
def timer_loop2
  while true
    $m.lock
    $time = $time.succ
    $root.countframe.counter['text'] = $time
    sleep(0.01)
    $m.unlock
  end
end

#
# TkAfter
#
def timer_loop3
  if $loop
    $time = $time.succ
    $root.countframe.counter['text'] = $time
  end
end


class CountFrame < TkFrame
  attr_reader :counter

  def initialize(parent=nil,keys=nil)
    super(parent,keys)
    @counter = TkLabel.new(self,
			   'text'=>$time, 
			   'relief'=>'raised')
    @counter.pack('fill'=>'both')
    self
  end
end


class ButtonFrame < TkFrame
  def initialize(parent=nil,keys=nil)
    super(parent,keys)
    @stop = TkButton.new(self,
			 'text'=>'Stop',
			 'command'=>proc{timer_stop})
    @start = TkButton.new(self,
			  'text'=>'Start',
			  'command'=>proc{timer_start})
    @reset = TkButton.new(self,
			  'text'=>'Reset',
			  'command'=>proc{timer_reset})
    for b in [@stop,@start,@reset]
      b.pack('side'=>'left', 'fill'=>'both', 'expand'=>'yes')
    end
  end
end


class Timer < TkRoot
  attr_reader :countframe

  def initialize
    super
    @countframe = CountFrame.new(self)
    @buttonframe = ButtonFrame.new(self)
    for f in [@buttonframe,@countframe]
      f.pack('side'=>'top', 'fill'=>'both')
    end
    self
  end
end


$root = Timer.new

#$thread = Thread.start{timer_loop2}
#timer_loop
TkAfter.new(10,-1,proc{timer_loop3}).start

Tk.mainloop