/*------------------------------------------------------------------------
    File        : signature_demo.p
    Purpose     : FWD User Meeting demo (#12087, topic 15): drive a signature
                  pad with an LCD screen, attached to the user's PC, from 4GL
                  code running in the FWD web client.

    Notes       : The pad is reached through the browser: 4GL code -> FWD
                  server -> web client (JavaScript) -> local SigWeb service
                  -> USB pad.  With webClient/signaturePadInSimMode = TRUE
                  the FWD server simulates the whole pad (r16820): the LCD,
                  its hot spots and the ink; the mouse is the pen.

                  The pad screens are drawn by the 4GL code with
                  LCDWriteString (text and pseudo-graphic boxes) and react
                  through KeyPadAddHotSpot / KeyPadQueryHotSpot:
                  1. Review: the delivery details, Cancel and OK.
                  2. Sign:   a framed signing box, Clear, Cancel and OK.
                  3. Result: "Thank you" (the signature is saved as a BMP
                     and shown in the window) or "Cancelled".
                  The simulated LCD is shown 1:1 in the widget, so the LCD
                  coordinates below are widget pixels (400 x 300).
  ----------------------------------------------------------------------*/

/* hot spot key codes */
&SCOPED-DEFINE HS-OK     1
&SCOPED-DEFINE HS-CANCEL 2
&SCOPED-DEFINE HS-CLEAR  3

/* pad screens */
&SCOPED-DEFINE SCR-IDLE   0
&SCOPED-DEFINE SCR-REVIEW 1
&SCOPED-DEFINE SCR-SIGN   2
&SCOPED-DEFINE SCR-DONE   3

DEFINE VARIABLE hSig      AS HANDLE    NO-UNDO.
DEFINE VARIABLE hImg      AS HANDLE    NO-UNDO.
DEFINE VARIABLE cTitle    AS CHARACTER NO-UNDO INITIAL "Arial, size=14, bold".
DEFINE VARIABLE cBody     AS CHARACTER NO-UNDO INITIAL "Arial, size=11".
DEFINE VARIABLE cBold     AS CHARACTER NO-UNDO INITIAL "Arial, size=11, bold".
DEFINE VARIABLE cBox      AS CHARACTER NO-UNDO INITIAL "Courier New, size=12, bold".
DEFINE VARIABLE dCharW    AS DECIMAL   NO-UNDO INITIAL 9.6.  /* Courier New 12 pt cell width */
DEFINE VARIABLE iLineH    AS INTEGER   NO-UNDO INITIAL 15.   /* pseudo-graphic line pitch */
DEFINE VARIABLE cSigFile  AS CHARACTER NO-UNDO.
DEFINE VARIABLE lLcd      AS LOGICAL   NO-UNDO.
DEFINE VARIABLE iScreen   AS INTEGER   NO-UNDO.
DEFINE VARIABLE iPoints   AS INTEGER   NO-UNDO.

DEFINE VARIABLE cOrder    AS CHARACTER NO-UNDO FORMAT "x(12)"  LABEL "Order"
   INITIAL "SO-104522".
DEFINE VARIABLE cCustomer AS CHARACTER NO-UNDO FORMAT "x(30)"  LABEL "Customer"
   INITIAL "Northwind Garden Supplies".
DEFINE VARIABLE cItems    AS CHARACTER NO-UNDO FORMAT "x(30)"  LABEL "Items"
   INITIAL "3 pallets, 42 cartons".
DEFINE VARIABLE cStatus   AS CHARACTER NO-UNDO FORMAT "x(70)"  LABEL "Status"
   INITIAL "Press Start Signing to send the delivery to the pad".
DEFINE VARIABLE cLog      AS CHARACTER NO-UNDO
   VIEW-AS EDITOR SCROLLBAR-VERTICAL SIZE-PIXELS 336 BY 152.

DEFINE BUTTON btnStart  LABEL "Start Signing" SIZE-PIXELS 100 BY 26.
DEFINE BUTTON btnClear  LABEL "Clear"         SIZE-PIXELS 80 BY 26.
DEFINE BUTTON btnAccept LABEL "Accept"        SIZE-PIXELS 80 BY 26.
DEFINE BUTTON btnCancel LABEL "Cancel"        SIZE-PIXELS 80 BY 26.
DEFINE BUTTON btnExit   LABEL "Exit"          SIZE-PIXELS 80 BY 26.

DEFINE FRAME fMain
   cOrder    AT X 70  Y 6
   cCustomer AT X 70  Y 26
   cItems    AT X 70  Y 46
   "Signature pad screen:" AT X 12  Y 76
   "Saved image:"          AT X 430 Y 76
   "Pad events:"           AT X 430 Y 220
   cLog      AT X 430 Y 240 NO-LABEL
   btnStart  AT X 12  Y 410
   btnClear  AT X 120 Y 410
   btnAccept AT X 208 Y 410
   btnCancel AT X 296 Y 410
   btnExit   AT X 686 Y 410
   cStatus   AT X 60  Y 446
   WITH SIDE-LABELS SIZE-PIXELS 780 BY 476 THREE-D NO-BOX.

ASSIGN
   CURRENT-WINDOW:TITLE         = "Delivery Confirmation"
   CURRENT-WINDOW:WIDTH-PIXELS  = 780
   CURRENT-WINDOW:HEIGHT-PIXELS = 476.

CREATE SIGNATURE hSig
   ASSIGN NAME          = "sigPad"
          FRAME         = FRAME fMain:HANDLE
          X             = 12
          Y             = 96
          WIDTH-PIXELS  = 400
          HEIGHT-PIXELS = 300
          BGCOLOR-RGB   = 0xFFFFFF
          FGCOLOR-RGB   = 0x000000
          SENSITIVE     = TRUE
          VISIBLE       = TRUE.

CREATE IMAGE hImg
   ASSIGN FRAME          = FRAME fMain:HANDLE
          X              = 430
          Y              = 96
          WIDTH-PIXELS   = 336
          HEIGHT-PIXELS  = 118
          STRETCH-TO-FIT = TRUE
          RETAIN-SHAPE   = TRUE
          VISIBLE        = TRUE.

/* every pen-up is the moment to look at the pad: hot spot taps and ink */
ON "PEN-UP" OF hSig DO:
   RUN checkPad.
END.

ON CHOOSE OF btnStart IN FRAME fMain DO:
   RUN startSigning.
END.

/* the window buttons do what the pad buttons do; setButtons enables each one only when it applies */
ON CHOOSE OF btnClear IN FRAME fMain DO:
   RUN logEvent("Window: Clear").
   RUN clearInk.
END.

ON CHOOSE OF btnAccept IN FRAME fMain DO:
   RUN logEvent("Window: Accept").
   RUN acceptSignature.
END.

ON CHOOSE OF btnCancel IN FRAME fMain DO:
   RUN logEvent("Window: Cancel").
   RUN cancelSigning.
END.

ON CHOOSE OF btnExit IN FRAME fMain
   APPLY "CLOSE" TO THIS-PROCEDURE.

ON CLOSE OF THIS-PROCEDURE DO:
   IF iScreen <> {&SCR-IDLE} THEN
      hSig:SetTabletState(0).
   APPLY "CLOSE" TO CURRENT-WINDOW.
END.

DISPLAY cOrder cCustomer cItems cStatus WITH FRAME fMain.
ENABLE cLog btnStart btnClear btnAccept btnCancel btnExit WITH FRAME fMain.
cLog:READ-ONLY IN FRAME fMain = TRUE.
RUN setButtons.

WAIT-FOR CLOSE OF THIS-PROCEDURE OR CLOSE OF CURRENT-WINDOW.

/* ----------------------------------------------------------------------
   window helpers
   ---------------------------------------------------------------------- */
PROCEDURE setStatus:
   DEFINE INPUT PARAMETER pcText AS CHARACTER NO-UNDO.

   cStatus = pcText.
   DISPLAY cStatus WITH FRAME fMain.
END PROCEDURE.

/* Enable the window buttons that apply to the current pad screen. */
PROCEDURE setButtons:
   DO WITH FRAME fMain:
      ASSIGN
         /* a new signing starts when none is in progress */
         btnStart:SENSITIVE  = (iScreen = {&SCR-IDLE} OR iScreen = {&SCR-DONE})
         /* Clear and Accept act on the ink, so only while the signing box is shown */
         btnClear:SENSITIVE  = (iScreen = {&SCR-SIGN})
         btnAccept:SENSITIVE = (iScreen = {&SCR-SIGN})
         btnCancel:SENSITIVE = (iScreen = {&SCR-REVIEW} OR iScreen = {&SCR-SIGN}).
   END.
END PROCEDURE.

PROCEDURE logEvent:
   DEFINE INPUT PARAMETER pcText AS CHARACTER NO-UNDO.

   DO WITH FRAME fMain:
      cLog:SCREEN-VALUE = cLog:SCREEN-VALUE
                          + (IF cLog:SCREEN-VALUE = "" THEN "" ELSE CHR(10))
                          + STRING(TIME, "HH:MM:SS") + "  " + pcText.
      cLog:CURSOR-OFFSET = LENGTH(cLog:SCREEN-VALUE) + 1.
   END.
END PROCEDURE.

/* ----------------------------------------------------------------------
   pad drawing helpers (LCD coordinates)
   ---------------------------------------------------------------------- */
PROCEDURE lcdText:
   DEFINE INPUT PARAMETER piDest AS INTEGER   NO-UNDO.
   DEFINE INPUT PARAMETER piX    AS INTEGER   NO-UNDO.
   DEFINE INPUT PARAMETER piY    AS INTEGER   NO-UNDO.
   DEFINE INPUT PARAMETER pcFont AS CHARACTER NO-UNDO.
   DEFINE INPUT PARAMETER pcText AS CHARACTER NO-UNDO.

   /* mode 2: write opaque */
   hSig:LCDWriteString(piDest, 2, piX, piY, pcFont, pcText).
END PROCEDURE.

/* A pseudo-graphic button: +------+ / |  OK  | / +------+, and its hot spot. */
PROCEDURE lcdButton:
   DEFINE INPUT PARAMETER piDest  AS INTEGER   NO-UNDO.
   DEFINE INPUT PARAMETER piX     AS INTEGER   NO-UNDO.
   DEFINE INPUT PARAMETER piY     AS INTEGER   NO-UNDO.
   DEFINE INPUT PARAMETER piCells AS INTEGER   NO-UNDO.
   DEFINE INPUT PARAMETER pcLabel AS CHARACTER NO-UNDO.
   DEFINE INPUT PARAMETER piKey   AS INTEGER   NO-UNDO.

   DEFINE VARIABLE cEdge AS CHARACTER NO-UNDO.
   DEFINE VARIABLE iPad  AS INTEGER   NO-UNDO.
   DEFINE VARIABLE iW    AS INTEGER   NO-UNDO.
   DEFINE VARIABLE iH    AS INTEGER   NO-UNDO.

   cEdge = "+" + FILL("-", piCells - 2) + "+".
   iPad  = TRUNCATE((piCells - 2 - LENGTH(pcLabel)) / 2, 0).

   RUN lcdText(piDest, piX, piY, cBox, cEdge).
   RUN lcdText(piDest, piX, piY + iLineH, cBox,
               "|" + FILL(" ", iPad) + pcLabel
                   + FILL(" ", piCells - 2 - iPad - LENGTH(pcLabel)) + "|").
   RUN lcdText(piDest, piX, piY + 2 * iLineH, cBox, cEdge).

   /* coordinate system 1: LCD pixels; sizes in variables, the method takes INTEGER arguments */
   ASSIGN
      iW = INTEGER(piCells * dCharW)
      iH = 3 * iLineH + 2.
   hSig:KeyPadAddHotSpot(piKey, 1, piX, piY, iW, iH).
END PROCEDURE.

/* Invert a button on the LCD for a moment, so the user sees the tap. */
PROCEDURE flashButton:
   DEFINE INPUT PARAMETER piX     AS INTEGER NO-UNDO.
   DEFINE INPUT PARAMETER piY     AS INTEGER NO-UNDO.
   DEFINE INPUT PARAMETER piCells AS INTEGER NO-UNDO.

   DEFINE VARIABLE iW AS INTEGER NO-UNDO.
   DEFINE VARIABLE iH AS INTEGER NO-UNDO.

   ASSIGN
      iW = INTEGER(piCells * dCharW)
      iH = 3 * iLineH + 2.
   /* mode 1: complement */
   hSig:LCDRefresh(1, piX, piY, iW, iH).
   PAUSE 1 NO-MESSAGE.
END PROCEDURE.

PROCEDURE noInk:
   /* a 1 x 1 signature window: taps on the buttons leave no ink */
   hSig:LCDSetWindow(0, 0, 1, 1).
   hSig:SetSigWindow(1, 0, 0, 1, 1).
END PROCEDURE.

/* ----------------------------------------------------------------------
   pad screens
   ---------------------------------------------------------------------- */
PROCEDURE startSigning:
   hSig:SetTabletState(1).

   /* 11/12: T-LBK462 (240 x 64 LCD); 58: the FWD pad simulator, which emulates an LCD */
   lLcd = LOOKUP(STRING(hSig:TabletModelNumber()), "11,12,58") > 0.
   RUN logEvent("Pad connected, model " + STRING(hSig:TabletModelNumber())
                + (IF lLcd THEN " (LCD)" ELSE "")).

   hSig:ClearTablet().
   hImg:LOAD-IMAGE("").

   IF lLcd THEN
      RUN showReview.
   ELSE
   DO:
      iScreen = {&SCR-SIGN}.
      RUN setButtons.
      RUN setStatus("Waiting for the signature").
   END.
END PROCEDURE.

/* Screen 1: the customer checks the delivery and taps OK or Cancel. */
PROCEDURE showReview:
   hSig:KeyPadClearHotSpotList().
   hSig:LCDRefresh(0, 0, 0, 400, 300).
   RUN noInk.

   RUN lcdText(0, 16, 12,  cTitle, "Delivery " + cOrder).
   RUN lcdText(0, 16, 38,  cBox,   FILL("=", 38)).
   RUN lcdText(0, 16, 62,  cBold,  "Customer").
   RUN lcdText(0, 110, 62, cBody,  cCustomer).
   RUN lcdText(0, 16, 86,  cBold,  "Items").
   RUN lcdText(0, 110, 86, cBody,  cItems).
   RUN lcdText(0, 16, 124, cBody,  "Please check the delivery, then tap OK.").

   RUN lcdButton(0, 30,  222, 12, "Cancel", {&HS-CANCEL}).
   RUN lcdButton(0, 254, 222, 12, "OK",     {&HS-OK}).
   hSig:SetLCDCaptureMode(2).

   iScreen = {&SCR-REVIEW}.
   RUN setButtons.
   RUN logEvent("Pad screen 1: review the delivery").
   RUN setStatus("The customer reviews the delivery on the pad").
END PROCEDURE.

/* Screen 2: a framed signing box; built in the pad's background memory, so Clear can restore it. */
PROCEDURE showSign:
   DEFINE VARIABLE iRow AS INTEGER NO-UNDO.

   hSig:KeyPadClearHotSpotList().
   hSig:ClearTablet().
   hSig:LCDRefresh(0, 0, 0, 400, 300).

   RUN lcdText(1, 16, 8, cBold, "Please sign inside the box").
   RUN lcdText(1, 16, 34, cBox, "+" + FILL("-", 36) + "+").
   DO iRow = 0 TO 8:
      IF iRow = 7 THEN
         RUN lcdText(1, 16, 49 + iRow * iLineH, cBox, "| X " + FILL("_", 32) + " |").
      ELSE
         RUN lcdText(1, 16, 49 + iRow * iLineH, cBox, "|" + FILL(" ", 36) + "|").
   END.
   RUN lcdText(1, 16, 49 + 9 * iLineH, cBox, "+" + FILL("-", 36) + "+").

   RUN lcdButton(1, 16,  222, 11, "Clear",  {&HS-CLEAR}).
   RUN lcdButton(1, 139, 222, 11, "Cancel", {&HS-CANCEL}).
   RUN lcdButton(1, 262, 222, 11, "OK",     {&HS-OK}).

   /* mode 2: copy the background memory to the display */
   hSig:LCDRefresh(2, 0, 0, 400, 300).

   /* ink only inside the box, and it stays on the LCD */
   hSig:LCDSetWindow(28, 52, 342, 128).
   hSig:SetSigWindow(1, 28, 52, 342, 128).
   hSig:SetLCDCaptureMode(2).

   iScreen = {&SCR-SIGN}.
   RUN setButtons.
   RUN logEvent("Pad screen 2: sign").
   RUN setStatus("Waiting for the signature").
END PROCEDURE.

/* Screen 3: a closing message, the pad is done. */
PROCEDURE showResult:
   DEFINE INPUT PARAMETER pcLine1 AS CHARACTER NO-UNDO.
   DEFINE INPUT PARAMETER pcLine2 AS CHARACTER NO-UNDO.

   hSig:KeyPadClearHotSpotList().
   RUN noInk.
   hSig:LCDRefresh(0, 0, 0, 400, 300).
   RUN lcdText(0, 16,  90,  cBox,   FILL("=", 38)).
   RUN lcdText(0, 120, 116, cTitle, pcLine1).
   RUN lcdText(0, 60,  150, cBody,  pcLine2).
   RUN lcdText(0, 16,  180, cBox,   FILL("=", 38)).
   iScreen = {&SCR-DONE}.
   RUN setButtons.
END PROCEDURE.

/* ----------------------------------------------------------------------
   pad events
   ---------------------------------------------------------------------- */
PROCEDURE checkPad:
   CASE iScreen:
      WHEN {&SCR-REVIEW} THEN
      DO:
         IF hSig:KeyPadQueryHotSpot({&HS-OK}) > 0 THEN
         DO:
            RUN logEvent("Pad: OK tapped").
            RUN flashButton(254, 222, 12).
            RUN showSign.
         END.
         ELSE IF hSig:KeyPadQueryHotSpot({&HS-CANCEL}) > 0 THEN
         DO:
            RUN logEvent("Pad: Cancel tapped").
            RUN flashButton(30, 222, 12).
            RUN cancelSigning.
         END.
      END.

      WHEN {&SCR-SIGN} THEN
      DO:
         IF lLcd AND hSig:KeyPadQueryHotSpot({&HS-OK}) > 0 THEN
         DO:
            RUN logEvent("Pad: OK tapped").
            RUN flashButton(262, 222, 11).
            RUN acceptSignature.
         END.
         ELSE IF lLcd AND hSig:KeyPadQueryHotSpot({&HS-CANCEL}) > 0 THEN
         DO:
            RUN logEvent("Pad: Cancel tapped").
            RUN flashButton(139, 222, 11).
            RUN cancelSigning.
         END.
         ELSE IF lLcd AND hSig:KeyPadQueryHotSpot({&HS-CLEAR}) > 0 THEN
         DO:
            RUN logEvent("Pad: Clear tapped").
            RUN flashButton(16, 222, 11).
            RUN clearInk.
         END.
         ELSE
         DO:
            iPoints = hSig:NumberOfTabletPoints().
            RUN logEvent("Pen up: " + STRING(iPoints) + " points").
            RUN setStatus(STRING(iPoints) + " points captured, tap OK on the pad").
         END.
      END.
   END CASE.
END PROCEDURE.

PROCEDURE clearInk:
   hSig:ClearSigWindow(1).
   hSig:ClearTablet().
   IF lLcd THEN
   DO:
      /* restore the screen without ink; re-adding the hot spots resets their tap counters */
      RUN showSign.
   END.
   RUN setStatus("Signature cleared, please sign again").
END PROCEDURE.

PROCEDURE cancelSigning:
   hSig:ClearTablet().
   RUN showResult("Cancelled", "The delivery was not signed.").
   RUN logEvent("Signing cancelled").
   RUN setStatus("Signing cancelled by the customer").
END PROCEDURE.

/* Save the signature as a monochrome BMP and show it in the window. */
PROCEDURE acceptSignature:
   DEFINE VARIABLE mImg AS MEMPTR NO-UNDO.

   iPoints = hSig:NumberOfTabletPoints().
   IF iPoints = 0 THEN
   DO:
      IF lLcd THEN
      DO:
         /* re-adding the hot spots resets their tap counters; the hint goes over the title */
         RUN showSign.
         RUN lcdText(0, 16, 8, cBold, "Please sign first, then tap OK").
      END.
      RUN logEvent("No signature yet").
      RUN setStatus("No signature yet: the customer must sign first").
      RETURN.
   END.

   hSig:ClearSigWindow(1).

   /* the image settings of the production screen: 571 x 200, centered and zoomed */
   hSig:SetImageFileFormat(2).
   hSig:SetImageXSize(571).
   hSig:SetImageYSize(200).
   hSig:SetImagePenWidth(11).
   hSig:SetJustifyMode(5).
   hSig:SetJustifyX(10).
   hSig:SetJustifyY(10).

   mImg = hSig:getSignatureImage("bmp", "Format1bppIndexed").
   cSigFile = SESSION:TEMP-DIRECTORY + "signature_" + cOrder + ".bmp".
   COPY-LOB FROM mImg TO FILE cSigFile NO-CONVERT.
   SET-SIZE(mImg) = 0.

   hImg:LOAD-IMAGE(cSigFile).

   /* the pad keeps showing the result; it is switched off when the program closes */
   IF lLcd THEN
      RUN showResult("Thank you!", "Your signature was received.").
   ELSE
   DO:
      iScreen = {&SCR-DONE}.
      RUN setButtons.
   END.

   RUN logEvent("Signature saved: " + STRING(iPoints) + " points").
   RUN setStatus("Signature saved as signature_" + cOrder + ".bmp ("
                 + STRING(iPoints) + " points)").
END PROCEDURE.
