
---------------------------------------------------------------------------------
--# GTimeout and GtkSwitch = a simple sports timer.
---------------------------------------------------------------------------------

include GtkEngine.e
include std/stats.e

-- Run from an x-term if you want to see the lap times!

-- Exercise for the reader: 
-- Add a graph to show the increase/decrease in lap times
-- as the race progresses...

atom ct = 0, n = 1, last = 0
sequence fmt = "<span color='red'>%2.2f</span>"
sequence laps = {}

constant win = create(GtkWindow,
    "title=Stopwatch,border_width=10,background=black,position=1,keep above=1,$destroy=Quit")

constant panel = create(GtkBox,"orientation=VERTICAL")
    add(win,panel)
    
constant btn1 = create(GtkSwitch,
    "tooltip text=click to start/pause,$activate=StartStop")

constant btn2 = create(GtkButton,
    "label=Lap,color=red,tooltip text=click to record lap time,$clicked=RecordLapTime")

constant reset_img = create(GtkImage,"thumbnails/icon-reset.png")

constant btn3 = create(GtkButton,
    "image=./thumbnails/icon-reset.png,tooltip text=click to reset,$clicked=Reset")

constant lbl = create(GtkLabel,"alignment=.5,font=36")
    add(panel,lbl)

constant btnbox = create(GtkButtonBox)
    set(btnbox,"spacing",5)
    pack(panel,btnbox)
    add(btnbox,{btn1,btn2,btn3})

object tick = create(GTimeout,10,_("Count"))

show_all(win)

Info(,,"Run from an x-term","if you want to see lap times")

main()

--------------------------------------
global function StartStop(atom ctl) -- toggle timer
--------------------------------------
return 0
end function

--------------------------------
global function RecordLapTime()
--------------------------------
laps = append(laps,{ct-last,0})
atom avg = stats:average(vslice(laps,1))
laps[$][2] = avg
last = ct

ifdef WINDOWS then
    system("cls")
elsedef
    system("clear")
end ifdef

for i = 1 to length(laps) do
    display("Lap: [:3>] Time: [.2] Avg: [3.3]",{i,laps[i][1],laps[i][2]})
end for

return 1
end function

--------------------------
global function Reset() -- zero time
--------------------------
    ct = 0
    laps = {} 
    last = 0
    set(lbl,"markup",sprintf(fmt,ct))
return 0 
end function 

-------------------
function Count() -- called by tick
-------------------
    if get(btn1,"active") then
        ct += .01
        set(lbl,"markup",sprintf(fmt,ct))
    end if
return 1
end function

