\ VP-clock
\ Time-related definitions
\ 
\ $Id: VP-clock.txt,v 1.1 2000/10/25 00:17:42 kris_johnson Exp $

\ Copyright 2000
\ Kristopher D. Johnson
\ 
\ See LICENSE-JacksOrBetter for the
\ conditions under which you may
\ use, redistribute, or modify this 
\ code, or create derived works.

\ Palm OS DateTime structure
struct
  1 cells field >second
  1 cells field >minute
  1 cells field >hour
  1 cells field >day
  1 cells field >month
  1 cells field >year
  1 cells field >weekday
end-struct DateTime

: .DateTime ( &DateTime -- )
  >r
  r@ >year @ .
  r@ >month @ .
  r@ >day @ .
  r@ >hour @ .
  r@ >minute @ .
  r@ >second @ .
  r>
;

\ Fill members of DateTime
\ structure from given
\ TimGetSeconds result
: secs>DateTime ( ud. &DateTime -- )
  >abs 2swap ( &DateTime. ud. )
  TimSecondsToDateTime
;

: DateTime>clock ( &DateTime -- minutes hours )
  dup >minute @ swap >hour @ ;

\ Buffer used by sec>clock
DateTime secs>clock-buf

: secs>clock ( ud. -- minute hour )
  secs>clock-buf secs>DateTime
  secs>clock-buf DateTime>clock
;

\ SystemPreferencesChoice
\ code for TimeFormatType
5 constant prefTimeFormat

\ Return system time format
: time-format ( -- TimeFormatType )
  prefTimeFormat >byte
  PrefGetPreference
  d>s
;

\ Buffer used by >hh:mm
\ (should be at least 9 chars)
create hh:mm-buf  16 chars allot
 
\ Given hour and minute, return
\ string of the form "HH:MM pm"
\ (or whatever the system time
\ format is)
: >hh:mm ( mm hh -- zadr u )
  >r >r
  hh:mm-buf >abs
  time-format >byte
  r> >byte r> >byte
  TimeToAscii
  hh:mm-buf zcount
;

\ Time when clock was last refreshed
2variable LastClockRefresh
variable LastClockHour
variable LastClockMinute

: set-clock ( mm hh -- )
  2dup LastClockHour !
  LastClockMinute !
  >hh:mm txtClock set-label ;

\ Display current time
: refresh-clock ( -- )
  TimGetSeconds
  2dup LastClockRefresh 2!
  secs>clock ( mm hh )
  set-clock
;

: refresh-clock-if-time-changed ( -- )
  \ Check whether second has changed
  \ and exit if not
  TimGetSeconds ( ud. )
  2dup LastClockRefresh 2@ d= if
    2drop exit
  then
  2dup LastClockRefresh 2!

  \ Check whether hour or minute
  \ have changed; exit if not
  secs>clock ( mm hh )
  2dup
  LastClockHour @ = ( mm f )
  swap LastClockMinute @ = ( f f )
  and if
    2drop exit
  then
  set-clock
;

