REM Demonstration Application using Toolbar.opo
REM original code from the Demo OPL32 source file
REM from the Series 5 ROM ver 1.00(113) July 97

REM Additional comments,minor fixes and routines added
REM by Leigh Edwards August 1997

REM Fixed minor ONERR handling bug in File name dialog procedure CmdF%
REM New time edit flags in dialogs
REM Use of an INI file
REM Program help file and how to call it etc.

INCLUDE "const.oph"
INCLUDE "date.oxh"
REM INCLUDE "xxxxx.oxh"
REM need new OPX for system Language code
REM OPX for resource file stuff and calling Data for help
INCLUDE "system.oxh"

REM toolbar CONSTs etc
INCLUDE "toolbar.oph"

REM application specific CONSTs etc
INCLUDE "ppcopl32.oph"

                                   REM Do NOT use this UID for your Apps it is an
                                   REM official Uid reserved for EMCC = &100002A5 see PPCOPL32.OPH
APP PPCOPL32,KUidEmcc00&           REM the APP name is overridden if other CAPTION statements are included below
  ICON "ppcopl32.mbm"              REM use a new icon - all six parts for 3 zoom sizes supplied in sub dir
  CAPTION KAppEng$,KLangEnglish%   REM the App name in English see CONST.OPH and appendix for the country codes
  CAPTION KAppFr$,KLangFrench%     REM the App name for a French variant
  CAPTION KAppGdr$,KLangGerman%    REM the App name for a German variant etc.
                                   REM etc. for any other language variants
  FLAGS 1                          REM 1= creates files, this is the usual default - minimum is an ini file
ENDA                               REM don't use FLAGS 2 or App will not appear on extras bar

PROC main:
                      REM app specific variables
  GLOBAL Appname$(10) REM name of Application - depends on Country but keep short
  GLOBAL RSCname$(12) REM name of Resource file depends on Country
  GLOBAL Lang%        REM language code of machine
  GLOBAL snd%         REM flag for the state of program sound
  GLOBAL HelpThrdID&  REM A ID for tracking the Data app for program help
  GLOBAL HStatus&     REM a status word to keep track of the help thread

  GLOBAL ScrWid%      REM pixel width initially
  GLOBAL ScrHght%     REM pixel height initially
  GLOBAL MenuPos%     REM last menu position
  GLOBAL bitmapId%,mainMbm$(255) REM 'EPOC' bitmap ID and file name string
  GLOBAL offs%(6)                REM for PARSE$ offsets
  GLOBAL id%(12)                 REM twelve 'drawable' IDs for the 'EPOC' windows

  REM get height and width of the whole screen
  REM this must be done before TbLink:
  ScrWid%  = gWIDTH
  ScrHght% = gHEIGHT

  SETFLAGS &10000 REM enable the receipt of machine switch on events

  ESCAPE OFF REM disable Ctrl+Esc to quit from Application
             REM 'REM' this out when testing any modifications

  Getlang:   REM get machine language code and set up any language specific stuff

  LOADM "z:\system\opl\Toolbar" REM load the ROM based OPO module for Toolbars
  TBarLink:("AppCont1")         REM call TBarLink in Toolbar.opo which 'links' toolbar GLOBALs
                                REM TBarlink then calls AppCont1: using the @ operator e.g. @("AppCont1"):
                                REM NOTE! control never actually returns to here
ENDP

PROC AppCont1:       REM program continues from here by being
                     REM called from the toolbar.opo link procedure TBarLink:
  GLOBAL wIdMain%    REM main window ID
  LOCAL justEntered% REM next drawing not relative to prev point

                     REM For portability with SIBO
  GLOBAL HotKMod%    REM modifier for hot-key
                     REM Psion-key on SIBO
                     REM Control-key on Era - i.e. Series 5

  GLOBAL event&(16),evType& REM declare event data array and a flag for type of event
  GLOBAL command$(255)      REM note the size of the commands$ string for long file names

  myInit:                       REM also initialises TBar + draws it
  FONT KFontCourierNormal13&,16 REM set font to courier, mono-spaced style

  DO                                        REM main loop
    nextEv%:                                REM go and wait for the next event
    evType&=event&(KEvaType%)               REM get the event type
    gUSE wIdMain%                           REM use the main window
    IF event&(KEvAPtrOplWindowId%)=widMain% REM pen events return Window ID in event&(3)
      IF (evType&=KEvPtrEnter&)             REM Pen now in contact with screen
        justEntered%=KTrue%                 REM next drawing is not relative to prev point
        CONTINUE                            REM goto top of loop again
      ENDIF
    ENDIF
    IF evType&=KEvPtr&                      REM if Pen event
      IF event&(KEvAPtrType%)=KEvPtrDrag&   REM and if Pen drag
        IF justEntered%                     REM and if just touched screen
          gAT event&(KEvAPtrScreenPosX%),event&(KEvAPtrScreenPosY%)   REM put 'cursor' where pen touched
          justEntered%=KFalse%                                        REM set flag
        ENDIF
        gLINETO event&(KEvAPtrScreenPosX%),event&(KEvAPtrScreenPosY%) REM draw line to new position at x,y
      ELSEIF event&(KEvAPtrType%)=KEvPtrPenDown&                      REM event Pen down - LE was(KEvPtrButton1Down&)
        justEntered%=KFalse%                                          REM set flag
        gAT event&(KEvAPtrScreenPosX%),event&(KEvAPtrScreenPosY%)     REM put 'cursor' where pen touched
        gLINEBY 0,0                                                   REM draw a single point
      ENDIF
    ELSE                                    REM else check other non-pen events recieved
      IF event&(KEvaType%) AND &400                          REM If non event
        IF (evType&<>KEvKeyUp&) AND (evType&<>KEvKeyDown&)   REM if NOT key up and NOT key down
          PRINT "Ev(&"+hex$(event&(KEvaType%));")",          REM print the hex value of the event inside ()
        ENDIF                                                REM
      ELSEIF (event&(KEvaType%)<32 OR event&(KEvaType%)>255) REM if key is not a printable character
        PRINT "<";event&(KEvaType%);">",                     REM print the decimal value of the event inside <>
      ELSE                                                   REM else just key so
        PRINT chr$(event&(KEvaType%));                       REM print ASCII key code character
      ENDIF
    ENDIF
  UNTIL 0  REM loop forever, told to shutdown or user quits
ENDP

PROC myInit:      REM Initialise display
  Read_ini:       REM Open Program .ini file or use default settings
  wIdMain%=1      REM Just use console for now
  gUPDATE off     REM turn of updates for now, until command buffer is full or gUPDATE ON
  gSETPENWIDTH 2  REM set pen to two pixels wide - try changing this
  gCOLOR 0,0,0    REM set drawing colour to solid black - try changing this
  HotKMod%=4      REM Control-key for Era i.e. Series 5
  initTBar:       REM call Toolbar.opo procedure to create toolbar and show it
  makeWins:       REM Create and draw the 'EPOC' windows
  gORDER 1,255    REM Main window into background i.e. behind the 'EPOC' windows
ENDP

REM Coerce floating point arguments to integers
EXTERNAL makeWin%:(x%,y%)

REM create and draw all the 'EPOC' windows
REM only called at start-up
PROC makeWins:
  LOCAL angle,i%

  MainMbm$="\system\apps\ppcopl32\epoc.mbm" REM 41 x 43 pixel four colour image
  MainMbm$=PARSE$(MainMbm$,LEFT$(CMD$(1),LEN(CMD$(1))-4),offs%()) REM PARSE file name to get a full path
  bitmapId%=gLoadBit(MainMbm$,0,0)          REM load the bitmap and keep its ID

  WHILE angle<2.0*pi      REM this will loop 12 times
     angle=angle+pi/6.0   REM the x,y positions of the 12 windows
     i%=i%+1              REM will approximate to a circle on the screen
     id%(i%)=makeWin%:(225.0+70.0*SIN(angle),80.0-70.0*COS(angle)) REM create next image
  ENDWH
ENDP

PROC makeWin%:(x%,y%) REM called to create and draw each 'EPOC' window
  LOCAL id%

  REM Create a 4 colour mode window, shadow l pixel above the window behind - starts
  REM with 2 pixel shadow, but the shadow will increase as each new window is drawn
  REM window is bigger than the bitmap to allow for the shadow

  id%=gCreate(x%,y%,70,70,1,$111)      REM each picture drawn in new 70x70 window!
  gMOVE 15,15                          REM move 15 pixels right and 15 down inside new window
  gCOPY bitmapId%,0,0,gWIDTH,gHEIGHT,3 REM copy the EPOC bitmap into window in replace mode
  gXBORDER 2,3                         REM S5 type border, with a double pixel shadow - on the whole window
  RETURN id%                           REM return each window id for Anti / Clock wise options later
ENDP

REM set up the Toolbar buttons and actions
PROC initTBar:
  LOCAL mbmTbar$(255),bitmapid1&,bitmapid2&

  mbmTbar$="\system\apps\ppcopl32\buttons.mbm" REM location of button bitmaps
  mbmTbar$=PARSE$(mbmTbar$,LEFT$(CMD$(1),LEN(CMD$(1))-4),offs%()) REM PARSE file name to get a full path
  bitmapId1&=gLoadBit(mbmTbar$,0,0)            REM load 'Clock' button bitmap
  bitmapId2&=gLoadBit(mbmTbar$,0,1)            REM load 'Anti'  button bitmap

  TBarInit:(Appname$,ScrWid%,ScrHght%)             REM Set title above Toolbar
  TBarButt:("c",1,"Clock",0,bitmapid1&,bitmapid1&,0) REM Initialise the top button with a bitmap
  TBarButt:("a",2,"Anti",0,bitmapid2&,bitmapid2&,0)  REM                2nd button with a bitmap
  TBarButt:("p",3,"Popup"+chr$(10)+"demo",0,&0,&0,1) REM Popup buttin Chr$(10) inserts a new line character, action on pointer down
  TBarButt:("e",4,"Exit",0,&0,&0,0)                  REM Exit button

  IF TbVis%   REM if the Toolbar setting is true turn it on
    TBarShow:
  ELSE        REM else turn it off
    TBarHide:
  ENDIF
ENDP

REM Handles Menu and Toolbar events
PROC nextEv%:

  WHILE 1               REM loop forever or until the program exit message is received
                        REM or until the event is recognised and we BREAK out
    GETEVENT32 event&()     REM Call GETEVENT32 to wait for the next event

    evType&=event&(KEvaType%)  REM will only get here if something has happened
                               REM so look in array element 1 for the event type
                               REM KEvaType% = 1 is defined in CONST.OPH
    IF evType&=KEvCommand&     REM if KEvCommand& = &404 i.e. a system message
      command$=GETCMD$         REM so get new command line command byte
      IF left$(command$,1)="X" REM if it is "X" the system telling App to shutdown
        cmdE%:                 REM so goto program stop procedure
      ENDIF
    ELSEIF evType&=KEvPtr&   REM If pointer event i.e. Pen tap so call a Toolbar.opo procedure
                             REM it's Toolbar.opo that handles the clock and task list, it
                             REM handles button state drawing and calls the matching procedure

      IF NOT TBarOffer%:(event&(KEvAPtrOplWindowId%),event&(KEvAPtrType%),event&(KEvAPtrPositionX%),event&(KEvAPtrPositionY%))
        BREAK                REM leave loop and return if the pen tap was a valid toolbar action
      ENDIF                  REM since the toolbar.opo will have called the procedure

                             REM If Pen has touched the main window
    ELSEIF evType&=KEvPtrEnter& AND (event&(KEvAPtrOplWindowId%)=wIdMain%)
      BREAK

    ELSEIF evType&=0         REM Or null event so go back to top of loop and wait again
      CONTINUE

                             REM if pen touched Menu tab on side of screen or a key was pressed
    ELSEIF (evType&=KKeySidebarMenu%) OR ((evType& AND $400)=0)

                             REM if not menu tab, or menu key or hot key BREAK out
      IF (evType&<>KKeySidebarMenu%) AND (evType&<>KKeyMenu%) AND ((event&(KEvAKMod%) AND HotKMod%)=0)
        BREAK
      ENDIF

                             REM so call offrCmd%: to check for menu or hot key press
                             REM and BREAK out if not
      IF NOT offrCmd%:(event&(KEvaType%),event&(KEvAKMod%)) REM ret -1 if command, else 0
        BREAK
      ENDIF

                             REM added by LE to see other events e.g. as machine switch on
    ELSEIF evType& AND &400
      BREAK

    ENDIF
  ENDWH
ENDP


REM Command handlers follow

REM Program Exit selected
PROC cmdE%:
  LOCAL previous&
  Save_ini:                            REM Save / replace the Program's .ini file
  IF HelpThrdID& <> 0                  REM If a program help thread is running
    IOYIELD                            REM allow status word to be updated
    IF HStatus& = KStatusPending32&    REM is 'pending' so still running
      ENDTASK&:(HelpThrdID&,previous&) REM end the task using its thread ID
    ENDIF
  ENDIF
  STOP REM end the program
ENDP

REM Text editor
PROC cmdSE%:
  LOCAL buffer&(101) REM 101=1+(399+3)/4 integer arithmetic
  LOCAL pLen&,pText&
  LOCAL i%,c%
  pLen&=ADDR(buffer&(1))  REM address of length of data
  pText&=ADDR(buffer&(2)) REM address of data in buffer
  LOCK ON                 REM tell the system we're busy
  WHILE 1                 REM loop until dialog completed with
                          REM button press or Esc
    dINIT "Editor with dEDITMULTI, Esc to quit"
    dEDITMULTI pLen&,"Edit long text",20,6,399 REM new dialog field need a button
    dBUTTONS "Done editing",%d                 REM to complete, Enter is a valid character
    IF DIALOG=0  REM if Esc pressed
      LOCK OFF   REM remove lock
      CLS        REM clear screen
      BREAK      REM leave the loop
    ENDIF
    LOCK OFF
    CLS
    PRINT "Text length ";buffer&(1)
    PRINT "Characters entered:"
    i%=0
    WHILE i%<buffer&(1)   REM print all buffer
      c%=PEEKB(pText&+i%) REM PEEK out each byte character
      IF c%>=32           REM if is an alpha character
        PRINT CHR$(c%);   REM print each character
      ELSE
        PRINT ".";      REM for non printable characters
      ENDIF
      i%=i%+1
    ENDWH
    PRINT
    PRINT "Press a key or tap the screen:"
    waitkeypen:
  ENDWH
ENDP

REM Date/time editors
PROC cmdD%:
  LOCAL d1&,d2&,t1&,t2&
  LOCK ON REM tell the system we're busy
  dINIT "Date and time editors"
    dDATE d1&,"Date",0,&10000
    dTIME t1&,"Time",1,0,&10000
    dTIME t1&,"Time (no seconds)",0,0,&7fff
    dTIME t1&,"Time (no hours)",4,0,&7fff     REM new flag in OPL32
    dTIME t1&,"Time (24 hours)",8,0,&7fff     REM new flag in OPL32
  DIALOG
  LOCK OFF
ENDP

REM Filename editor allows user to try out the new flag
REM values to restrict the options for file name
REM editing or selection restrictions
REM ONERR handling in this procedure fixed by LE
PROC cmdF%:
  LOCAL f1$(255)
  LOCAL flags&,flags$(30),label$(8)

  flags$="$1 OR $80"  REM set up initial flags string
  ONERR e1            REM set up error handler

  LOCK ON REM tell the system we're busy
  WHILE 1             REM loop until user presses Escape
    dINIT "Filename editor/selector(flags=$"+hex$(flags&)+"): Esc quits",KDlgDensePack%
      IF flags& AND 1    REM bit 1 set for editor
        label$="Edit"    REM change the prompt string
      ELSE
        label$="Select"  REM depending on flags set
      ENDIF

      dFILE f1$,label$+" file:",flags& REM get new flags from user
      dEDIT flags$,"Set next flags",20
      dTEXT "Flag values:","$1->editor,$2->allow dirs"
      dTEXT "and:","$4->dirs only,$8-> disallow existing (e)"
      dTEXT "and:","$10->query existing (e),$20->allow null string"
      dTEXT "and:","$40->no extension (s),$80->allow wildcards"
      dTEXT "and:","$100->allow ROM files,$200->allow System folder files"
    IF DIALOG=0         REM if Esc pressed
      ONERR OFF         REM turn error handler off
      LOCK OFF
      BREAK             REM BREAK out of loop and return
    ENDIF
    flags&=eval(flags$) REM convert flags$ string into a number in flags&
    GIPRINT f1$         REM briefly display the new flags set
    CONTINUE            REM back to top of loop
  e1::                              REM error are handled here
                                    REM if we have got here things must have
    ONERR OFF                       REM turn off error handling
    GIPRINT "Bad flags:"+err$(err)  REM gone wrong so display the error
  ENDWH
ENDP

REM Show new DIALOG flags used in dINIT
PROC cmdSF%:
  LOCAL curFlags%,d%
  LOCAL f%     REM new flag setting

  LOCK ON      REM tell the system we're busy
  WHILE 1      REM loop forever or until the user presses Escape
    dINIT "Dialog flags",curFlags%
    IF curFlags%=0                                 REM change text message according to flags
      dTEXT "The default setting","No flags set"
    ELSE
      IF curFlags% AND KDlgButRight%
        dTEXT "Buttons right","KDlgButRight%"
      ENDIF
      IF curFlags% AND KDlgNoTitle%
        dTEXT "No title","KDlgNoTitle%"
      ENDIF
      IF curFlags% AND KDlgFillScreen%
        dTEXT "Full screen dialog","KDlgFillScreen%"
      ENDIF
      IF curFlags% AND KDlgNoDrag%
        dTEXT "Dragging disabled","KDlgNoDrag%"
      ENDIF
      IF curFlags% AND KDlgDensePack%
        dTEXT "Densely packed","KDlgDensePack% set"
      ELSE
        dTEXT "Loosely packed","KDlgDensePack% clear"
      ENDIF
    ENDIF
    dButtons "Buttons",%b,"Title",%t,"Screen",%s,"Packing",%p,"Dragging",%d
    d%=DIALOG
    IF d%=0   REM user pressed Escape
      LOCK OFF
      BREAK   REM so BREAK out and return
    ENDIF
    IF d%=%b             REM detect which button was used via hot key or pen tap
      f%=KDlgButRight%
    ELSEIF d%=%t
      f%=KDlgNoTitle%
    ELSEIF d%=%s
      f%=KDlgFillScreen%
    ELSEIF d%=%d
      f%=KDlgNoDrag%
    ELSEIF d%=%p
      f%=KDlgDensePack%
    ENDIF
    IF curFlags% AND f%                 REM test any flag has changed
      curFlags%=curFlags% AND (NOT f%)  REM remove flag if set
    ELSE
      curFlags%=curFlags% OR f%         REM add flag if not set
    ENDIF
  ENDWH
ENDP

REM Get all events
PROC cmdV%:
  GLOBAL event&(16)

  LOCK ON                                          REM tell the system we're busy
  BUSY "Modal demo (toolbar inactive) Esc quits",2 REM tell user how to quit events display
  gUSE 1                                 REM use main window
  gCLS                                   REM clear graphics screen
  AT 1,5                                 REM position text insertion point
  WHILE 1                                REM loop forever, until Esc key
    clrEv:                               REM clear the events array
    GETEVENT32 event&()                  REM wait for an event
    IF (event&(1)=27) AND (event&(4)=0)  REM test for Esc key with no modifier key such as Shift Esc
      BREAK                              REM BREAK out
    ENDIF
    showEv:                              REM call procedure to show the event details
  ENDWH
  gUSE 1
  gCLS          REM get rid of any events on screen
  AT 1,1
  BUSY OFF      REM turn off the Escape message
  LOCK OFF      REM Application is no longer busy
ENDP

REM display the events on screen
PROC showEv:
  LOCAL ev1&,mod%,rep%
  LOCAL i%
  LOCAL t&

  ev1&=event&(1)                 REM get the event type
  IF (ev1& AND $400)=0           REM was it a key press event
    mod%=event&(4)               REM get any key modifier e.g. Shift or Ctrl
    rep%=event&(5)               REM get number of key repeats if any
    PRINT "Key:  ";              REM Display the word 'Key'
    PRINT num$(ev1&,-4),         REM display the numeric key value
    IF ev1&<$1000                REM Normal key press not special
      PRINT " ";                 REM key such as Cursor key etc.
      IF ev1&<$100               REM printable character
        PRINT " ";
        IF ev1&<$10              REM Ctr+key pressed
          PRINT " ";
        ENDIF
      ENDIF
    ENDIF
    PRINT "(0x";hex$(ev1&);")",   REM hex value of key
    IF ev1&>=32                   REM printable character so
      PRINT "= '";chr$(ev1&);"'", REM print ASCII character
    ELSE
      PRINT "    ",               REM else skip the character
    ENDIF
    PRINT "  Modif=0x";hex$(mod%), REM show the hex value of any modifier
        PRINT "Repeats=";rep%;"  " REM print number of key repeats

  ELSE                           REM for non key event
    PRINT "Event:",hex$(ev1&),   REM print the word 'Event'
    i%=2
    PRINT "  ";
    VECTOR ev1&-&400             REM jump to a suitable descriptive message display
                                 REM routine for the event type that occurred
      l401,l402,l403,l404,l405,l406,l407,l408,l409,l410
    ENDV
    IF ev1&<>&400                REM not null event
      PRINT "Unknown",hex$(ev1&) REM catch any unknowns
      RETURN
    ENDIF
    WHILE 0
l401::
      PRINT "Focus gained"
      BREAK
l402::
      PRINT "Focus lost"
      BREAK
l403::
      PRINT "Switched on"
      BREAK
l404::
      PRINT "Exit command received"  REM Not yet implemented
      BREAK
l405::
      PRINT "Date changed"
      BREAK
l406::
      PRINT "Key down, scan code=";event&(3);"                    "
      BREAK
l407::
      PRINT "Key up,   scan code=";event&(3);"                      "
      BREAK
l408::
      t&=event&(KEvAPtrType%)                   REM for pen events
      PRINT "Pointer event ";t&,                REM describe what type it was
      vector t&+1                               REM jump to correct description
        lp0,lp1,lp2,lp3,lp4,lp5,lp6,lp7,lp8,lp9
      endv
      PRINT "Unknown type ",
      WHILE 0
  lp0::           REM All of these are for pointer device buttons 1 - 3
  lp1::           REM pen up or pen down, but as yet we only have a pen,
  lp2::           REM but pens don't have buttons unlike mice
  lp3::           REM so treat them all the same
  lp4::                                         REM lp4 & 5 are button 3 up and down
  lp5::           PRINT "Button";t&/2+1,        REM if screen buttons touched
        IF t& AND 1
          PRINT "up  ",
        ELSE
          PRINT "down",
        ENDIF
        BREAK
  lp6::           PRINT "Drag",
        BREAK
  lp7::           PRINT "Move",
        BREAK
  lp8::           PRINT "Button repeat",
        BREAK
  lp9::           PRINT "Switch on",
        BREAK
      ENDWH

            REM show the x,y coordinates touched
      PRINT "at (";event&(KEvAPtrPositionX%);",";event&(KEvAPtrPositionY%);")",

            REM show which window was touched
      PRINT "WinId=";event&(KEvAPtrOplWindowId%)
      BREAK
l409::      REM when pen goes down show the ID of Window entered
      PRINT "Pointer entered window",event&(KEvAPtrOplWindowId%)
      BREAK
l410::      REM when pen comes up again, show the ID of Window left
      PRINT "Pointer exited window",event&(KEvAPtrOplWindowId%)
      BREAK
    ENDWH
  ENDIF
ENDP

REM Fill GLOBAL event array event&(16) with zeros
REM to avoid reporting spurious information
PROC clrEv:
  LOCAL i%

  WHILE i%<16
    i%=i%+1
    event&(i%)=0
  ENDWH
ENDP

REM clear screen procedure, just hides the 'EPOC' windows
PROC cmdSC%:
  gORDER TbWinId%,1 REM make toolbar window first position window i.e. foreground
  gORDER 1,2        REM make main (default) window second position window
  gUSE 1            REM make main (default) window the current drawable
  gCLS              REM clear the main window - the 'EPOC' windows are hidden behind the main window
  AT 1,1            REM position the 'cursor'
ENDP

REM Stopwatch demo using microsecond timing in DATE.OPX
PROC cmdS%:
  LOCAL s&,e&,d&,a%(2),micro$(6),k%
  LOCAL y&,mo&,day&,h&,mi&,se&,m&
  LOCAL savedTbVis%

  savedTbVis%=TbVis%   REM save current state of Toolbar - visible or not
  IF savedTbVis%       REM if it is on
    TBarHide:          REM  turn it off
  ENDIF
  CLS                  REM clear the text screen
  PRINT
  PRINT " The Opl32 DateTime OPX gives extended access to E32's time functions"
  PRINT
  PRINT " Allows OPL programmers to achieve microsecond timing resolution"
  PRINT " in their programs, as demonstrated below. "
  PRINT
  PRINT
  PRINT " Press any key to start / 'lap time' the clock  :  Esc to quit"
  IF get<>27      REM check for any key by Esc
    s&=DTNOW&:    REM create a new date/time object containing all the date/time
    WHILE 1       REM components of the current time s& is the objects ID
      e&=DTNOW&:  REM create another data/time object e& is the objects ID

      REM now calculate exact difference between the two date/time objects
      REM i.e. s& and e& - m& will hold the difference in microseconds
      DTDateTimeDiff:(s&,e&,y&,mo&,day&,h&,mi&,se&,m&)

      AT 30,15
      micro$=num$(m&/1000,-3)               REM convert to milliseconds
      PRINT h&;":";mi&;":";se&;":"; micro$; REM show new time
      PRINT "                     "
      k%=key                                REM get a key
      IF k%=27
        BREAK                               REM BREAK out if Esc
      ENDIF

      IF k%                                 REM if any other key show lap time
        AT 1,17
        PRINT"LAP TIME      ";day&;"/";mo&;"/";y&,h&;":";mi&;":";se&;" and ";m&;" microseconds          "
      ENDIF
    ENDWH
  ENDIF
  IF savedTbVis%                            REM restore the Toolbar
    TBarShow:
  ENDIF
  CLS
ENDP

REM Clockwise demo
PROC cmdC%:
  LOCAL i%

  gUPDATE ON           REM enable immediate display updating
  WHILE i%<12          REM loop for all 12 'EPOC' windows
    i%=i%+1
    gORDER id%(i%),1   REM bring each window to the front
  ENDWH
  gUPDATE OFF          REM restrict the frequency of display updates
ENDP

REM Anti-clockwise demo
PROC cmdA%:
  LOCAL i%

  gUPDATE ON           REM enable display updating
  i%=11
  WHILE i%>0           REM loop for 11 'EPOC' windows
    gORDER id%(i%),1   REM bring each window to the front
    i%=i%-1
  ENDWH
  gORDER id%(12),1     REM bring last window to the front
  gUPDATE OFF          REM restrict the frequency of display updates
ENDP

REM Grey scales
PROC cmdG%:
  LOCAL win1%,win2%
  LOCAL width&,rgb&

  width&=40   REM default width for bands
  rgb&=255    REM default initial colour

  LOCK ON     REM tell the system we're busy
  dINIT " Enter width of each band"
    dLONG width&,"Width",1,ScrWid%
    dLONG rgb&,"Initial colours",0,255
    dBUTTONS "Cancel",-(27 OR $100),"OK",13 OR $100  REM buttons without shortcut labels
  IF DIALOG=0  REM user pressed Esc
    LOCK OFF
    RETURN     REM so return
  ENDIF
  LOCK OFF
  win1%=gCREATE(0,0,ScrWid%,ScrHght%/2,1,1)           REM create a 4 colour mode window
                                                      REM on top half of screen
  gUSE 1                                              REM switch to default window

  win2%=gCREATE(0,ScrHght%/2,ScrWid%,ScrHght%/2,1,2)  REM 16 colour mode window
                                                      REM on bottom half of screen
  gUSE win1%                                          REM switch to upper window
  bands:(width&,rgb&)  REM draw grey colour bands
  gUSE win2%           REM switch to lower window
  bands:(width&,rgb&)  REM draw grey colour bands
  waitkeypen:          REM wait for a key or pen event
  gCLOSE win2%         REM close lower window
  gCLOSE win1%         REM close upper window
ENDP

REM draw grey bands
PROC bands:(width&,initColor&)
  LOCAL col%,ii%,dif%
  REM screen has max of 16 grey scales, so 256/16 = 16 increments from white to black
  dif%=16
  col%=initColor&              REM starting point on grey scale
  ii%=(gWIDTH+width&-1)/width& REM loop to fill full screen width
  gAT 0,0
  WHILE ii%>0
    gCOLOR col%,col%,col%   REM set pen colour - all 3 values equal gives pure greys
    gFILL width&,gHEIGHT,0  REM fill band with current grey scale
    gMOVE width&,0          REM move over by band width
    col%=col%+dif%          REM adjust colour
    IF col%>255             REM if gone over range
      col%=col%-32          REM take it back to a valid range
      dif%=-16              REM start count down now
    ELSEIF col%<0           REM gone under range
      col%=col%+32          REM take it back to a valid range
      dif%=16               REM start counting up now
    ENDIF
    ii%=ii%-1
  ENDWH
ENDP

REM Toolbar visibility toggle on/off
PROC cmdT%:
  IF TbVis%   REM if on turn it off
    TBarHide:
  ELSE        REM else turn it on
    TBarShow:
  ENDIF
ENDP

REM Sound toggle on/off
PROC cmdSS%:
  IF snd%=KTrue%
    snd%=KFalse%             REM turn sound off
  ELSEIF snd%=KFalse%
    snd%=KTrue%              REM turn sound on
  ENDIF
  sound:(1)                  REM beep if on
ENDP

REM Program help
PROC cmdSH%:
  LOCAL full$(255),previous&,ret&
  full$=PARSE$(KAppdir$+KApproot$+KApphlp$,LEFT$(CMD$(1),LEN(CMD$(1))-4),offs%()) REM PARSE file name to get a full path
  IF HelpThrdID& = 0                                  REM help not already running
    HelpThrdID&=RUNAPP&:("Data",full$,"",0)           REM so run Data app with our help file
    LOGONTOTHREAD:(HelpThrdID&,HStatus&)              REM get status of help thread - still running?
  ELSE                                                REM else already running
    IOYIELD                                           REM allow status word to be updated
    IF HStatus& = KStatusPending32&                       REM is 'pending' so still running
      ret&=SETFOREGROUNDBYTHREAD&:(HelpThrdID&,previous&) REM bring help to the foregound
    ELSEIF HStatus& = 0
      HelpThrdID& = 0      REM reset thread ID
      cmdSH%:              REM call ourself to re-establish help
    ENDIF
  ENDIF
  RETURN
ENDP

REM popup menu next to button, with KMPopupPosTopRight% specifying that
REM the x,y coordinates apply to the top right corner of the popup menu
REM other values are KMPopupPosTopLeft%, KMPopupPosBottomLeft%, KMPopupPosBottomRight%
PROC cmdTbDownP%:
  LOCAL pop%
  REM           x    ,    y       ,   corner
  pop%=mPOPUP(ScrWid%-TbWidth%,97,KMPopupPosTopRight%,"Item a",%a,"Item b",%b)
  IF pop%=0                                REM if Esc pressed
    GIPRINT "Popup cancelled"
  ELSE
    GIPRINT "Item "+chr$(pop%)+" selected" REM pop% is number of item selected by user
  ENDIF
ENDP

REM Checks if key a press was the menu key or a hot-key
REM Returns -1 if command (menu or hot-key)
REM also -1 if menu-key pressed but cancelled
PROC offrCmd%:(key&,modif&)
  LOCAL isMenuK%
  LOCAL m%,k%,cmdRoot$(4)
  LOCAL mod%
  LOCAL hotK%
  LOCAL tbOn%,SOn%

  mod%=modif&  REM save the key press modifier
  k%=key&      REM and the key press as integers

  IF (k%=KKeyMenu%) OR (k%=KKeySidebarMenu%) REM if menu key or menu tab on LHS of screen
    isMenuK%=-1                              REM set flag for menu
    IF TbVis%           REM if the Toolbar is visible
      TbOn%=$2000       REM ensure the Show Toolbar menu checkbox is ticked
    ENDIF
    IF snd%             REM if program sound is On
      SOn%=$2000        REM ensure the Sound menu checkbox is ticked
    ENDIF
    mINIT   REM set up and display the menu
      mCARD "File","Close",%e              REM no files yet, just exit
      mCARD "Edit","Clear screen",%C
      mCASC "Edit boxes","Text editor",%E,"Date/time",%d ,"Filename",%f
      mCARD "Dialogs","New flags",%F,"Edit boxes>",16
      mCARD "View","Show toolbar",%t OR KMenuCheckBox% OR TbOn%     REM this item has a checkbox
      mCARD "Graphics","Clockwise",%c,"Anti-clockwise",-%a,"Grey scales",%g
      mCARD "Events","Display events",%v
      mCARD "OPX","Stopwatch demo",%s
      mCARD "Tools","Help",%H,"Sound",%S OR KMenuCheckBox% OR SOn% REM Sound item has a checkbox

    LOCK ON             REM tell the system we're busy
    m%=MENU(MenuPos%)   REM show the menu with last item selected
    LOCK OFF            REM not busy now menu has been cleared

    IF m%               REM get the menu item key
      hotK%=m%          REM save it as a hot-key
      mod%=HotKMod%     REM set key modifer flag to value for an accelerator i.e. Ctrl
      IF hotK%<=%Z      REM if key was uppercase
        mod%=mod% OR 2  REM set key modifier flag to Shift
      ENDIF
    ELSE
      RETURN -1         REM menu cancelled e.g. by Esc key
    ENDIF
  ELSE                  REM not menu key
    hotK%=k%-1+%a       REM make Ctrl+Key the same as Shift+Ctrl+Key
  ENDIF
  IF mod% AND HotKMod%  REM Hotkey modif, so maybe accelerator
    cmdRoot$="cmd"      REM set the procedure name root for lower case hot keys
    IF mod% AND 2       REM If modifier was shift key
      cmdRoot$="cmds"   REM set the procedure name root for upper case hot keys
    ENDIF

REM PRINT "call ";cmdRoot$+chr$(hotK%),hotK% REM remove REM at start to see hotkeys etc

    ONERR eNotCmd                     REM set up error handler

    REM not shifted key and Ctrl+c or Ctrl+a
    IF ((mod% AND 2)=0) AND ((hotK%=%c) OR (hotK%=%a))
      gORDER 1,255                    REM Text window to back to hide it
    ELSE
      gORDER TbWinId%,1               REM Toolbar to front
      gORDER 1,2                      REM Text window behind toolbar
    ENDIF
    @%(cmdRoot$+chr$(hotK%)):         REM add hot-key letter onto procedure name root
                                      REM and call the procedure named in the resulting string
    gUSE 1
    ONERR OFF                         REM turn off the specific error handling
    RETURN -1                         REM else other non specific errors will come here
  ENDIF

REM error handling code for illegal commands
eNotCmd::                 REM error has occurred
  IF isMenuK% OR err<>-99 REM if menu was pressed or error was not 'procedure not found'
    ONERR OFF             REM stop an infinite loop if another error occurs
    GIPRINT "Bug: Proc "+cmdRoot$+chr$(hotK%)+"%:,"+err$(err) REM tell user what error was

    IF err=-98            REM Undefined externals error
      ALERT("ERRX$: "+ErrX$,err$(err)) REM put up an alert dialog box with
    ENDIF                              REM the corresponding system error message
    RETURN -1
  ENDIF
  RETURN 0
ENDP

PROC Getlang:   REM get system language code and set up any language specific stuff
  LOCAL cn$(2),full$(255)

  Lang%=1           REM force to English until we have an OPX
                    REM to return the machine language code
  IF Lang%=3             REM does it speak German
    Appname$=KAppGdr$
  ELSEIF Lang%=2         REM does it speak French
    Appname$=KAppFr$
  ELSE                   REM default is English
    Appname$=KAppEng$
  ENDIF

  cn$=GEN$(lang%,2)                         REM convert number to string
  IF lang% < 10 : cn$="0"+cn$ :ENDIF        REM put on leading 0 if needed
  RSCname$=KRSCroot$+cn$+KApprsc$             REM assemble the file name
  full$=PARSE$(KAppdir$+RSCname$,LEFT$(CMD$(1),LEN(CMD$(1))-4),offs%())   REM PARSE it to get a full path
  IF (NOT EXIST(full$))                       REM test that it exists
    RSCname$=KRSCroot$+"01"+KApprsc$          REM if not build a default English file name
    full$=PARSE$(KAppdir$+RSCname$,LEFT$(CMD$(1),LEN(CMD$(1))-4),offs%()) REM PARSE it to get a full path
    IF (NOT EXIST(full$))                     REM Quit if the default English file not found
      GIPRINT full$                           REM just display the name then abandon program
      REM pferr:(1,"No resource file")
    ELSE
      GIPRINT full$                    REM just display it for now
      REM id&=LOADRSC&:(full$)         REM open resource file
      REM string$=READRSC$:(strid&)    REM read a string with identifier strid&
      REM long&=READRSCLONG&:(longid&) REM read a long value with identifier longid&
      REM UNLOADRSC:(id&)              REM close resource file
    ENDIF
  ENDIF
ENDP

REM wait for a key or pen event
PROC waitkeypen:
  WHILE 1
    clrEv:                     REM clear global event array
    GETEVENT32 event&()        REM wait for any event
    evType&=event&(KEvaType%)  REM get the type
    IF evType&=KEvCommand&     REM but if KEvCommand& = &404
      command$=GETCMD$         REM get new command line command byte
      IF left$(command$,1)="X" REM if it is "X" the system telling App to shutdown
        cmdE%:                 REM so goto program stop procedure
      ENDIF
    ELSEIF ((evType& AND $400)=0) OR (evType&=KEvPtr& AND event&(KEvAPtrType%)=KEvPtrPenDown&)
      BREAK
    ENDIF
  ENDWH
ENDP

REM make a beep, but only if program sound on
PROC sound:(s%)
  IF snd%=KTrue%
    IF s%<>0
      BEEP 5,300
    ENDIF
  ENDIF
ENDP

REM Open Program .ini file
PROC Read_ini:
  LOCAL full$(255)
  snd%   =  KFalse%        REM default to sound off
  TbVis% =  KTrue%         REM default to Toolbar visibility on
  full$=PARSE$("C:"+KAppdir$+KApproot$+KAppini$,"",offs%()) REM PARSE file name to get a full path
  IF EXIST(full$)          REM but if ini exist use stored values
    TRAP OPEN full$,A,TbVis%,snd%
    IF NOT ERR             REM mananged to open it OK
      snd%   =  A.snd%     REM restore sound flag
      TbVis% =  A.TbVis%   REM restore Toolbar visibility flag
      TRAP CLOSE           REM got setting so close file
    ENDIF
  ENDIF
ENDP

REM Save / Create Program .ini file
REM this is the easiest way to create an .ini file
REM Data files automatically have headers with the UIDs in them
PROC Save_ini:
  LOCAL full$(255)
  full$=PARSE$("C:"+KAppdir$+KApproot$+KAppini$,"",offs%()) REM PARSE file name to get a full path
  TRAP DELETE full$                  REM delete old ini file
  IF NOT ERR                         REM if no error
    TRAP CREATE full$,A,TbVis%,snd%  REM create a new one
    IF NOT ERR             REM If no error on create
      A.snd%   =  snd%     REM save sound flag
      A.TbVis% =  TbVis%   REM save Toolbar visibility flag
      TRAP APPEND          REM save data
      TRAP CLOSE           REM close file
    ENDIF
  ENDIF
ENDP

REM check & process terminal file & other errors
PROC pferr:(e%,m$)
  IF e%<>0          REM just return if e%=0
    LOCK ON
    sound:(1)       REM beep if program sound is enabled
    dINIT Appname$+GEN$(e%,-4)
    dTEXT "Information: ",m$
    IF e%<0
      dTEXT "","ERRX$: "+ERRX$           REM any extended erro message
      dTEXT "Err= "+GEN$(e%,-4),ERR$(e%)  REM normal error message
    ENDIF
    DIALOG
    LOCK OFF

    REM possibly recoverable file errors ??
    IF e%=-32 OR e%=-37 OR e%=-38 OR e%=-40 OR e%=-41 OR e%=-42
      REM insert some error recovery code here ??
      RETURN

    ELSE        REM unrecoverable errors
      sound:(1) REM beep if program sound is enabled
      cmdE%:    REM exit the program
    ENDIF
  ENDIF
ENDP REM pferr:(e%,m$)
