OXT Community Stacks

The scripts of Barcode Studio

Version 1.0. These are the scripts exactly as they are in the stack that plays here. Each line has its number, and a link to a line keeps it.

the stack script

Barcode Studio.oxtstack, stack "Barcode Studio", 1262 lines

-- Barcode Studio: barcodes made and read by barcodext, in motion.
--
-- The stack opens straight into its first scene and plays the scenes
-- one after another until "Play all" is turned off:
--   1. Type a code   a QR code made again at every letter typed, then
--                    drawn in other inks and read back
--   2. Every kind    each kind barcodext makes, made and read back
--   3. Scan a sheet  six barcodes of six kinds found in one picture by
--                    one call, outlined as a scanning beam passes
--   4. Damage it     two QR codes with the same words, stained
--                    together: the stronger repair level reads on
--   5. Your turn     type your own and pick a kind, save it as a PNG
--                    picture or an SVG drawing, or read a picture
--
-- Every scene is played by a timer one frame at a time, with the screen
-- locked while a frame is drawn: nothing here waits, so the stack
-- answers a click at any moment. Every control is named "of me" (this
-- stack): a message sent in time resolves a bare name against whichever
-- stack is the defaultStack when it arrives.
--
-- The stack keeps working without the library: it says so on its stage,
-- and every button still answers.

constant kTick = 40
constant kMarks = 12
constant kMidX = 358
constant kMidY = 350
constant kGood = "#34D399"
constant kBad = "#F87171"
constant kOrange = "#FF8A3D"
constant kButton = "#2A3146"
constant kText = "#E6E9F0"
constant kDim = "#9199AC"
constant kFaint = "#6B7385"
constant kTyped = "https://openxtalk.org/ - every letter typed makes a new QR code, and it grows as the words do."
constant kCommon = "QR Code,EAN-13,Code 128,Data Matrix,Aztec,PDF417,UPC-A,Code 39,ITF"
constant kAliases = "EAN/UPC,QR Code Model 2,Aztec Code"
constant kInks = "29,78,216|4,120,87|109,40,217|154,52,18|0,0,0"
constant kInkCount = 5
constant kInkNames = "Blue ink|Green ink|Violet ink|Brown ink|Black ink"
constant kDamageText = "https://openxtalk.org/"

local sHasLibrary
local sScene
local sLast
local sStep
local sTimer
local sNext
local sPending
local sTour
local sData
local sKind

on preOpenStack
   bsStart
end preOpenStack

-- Straight into motion: the first letter is typed as the stack opens.
on openStack
   bsPlay 1
end openStack

on closeStack
   bsStopAll
   pass closeStack
end closeStack

-- Asks the library who it is. A stack must never fail because a library
-- is missing, so the first call is inside a try.
command bsStart
   local tVersion, tError
   put false into sHasLibrary
   put true into sTour
   put empty into sScene
   put 1 into sLast
   put "QR Code" into sKind
   put empty into sData
   try
      put bcLibraryVersion() into tVersion
      put true into sHasLibrary
   catch tError
      put empty into tVersion
   end try
   lock screen
   bsClearStage
   if sHasLibrary then
      put tVersion into field "Version" of me
      set the textColor of field "Version" of me to kFaint
      put "Makes and reads " & the number of lines in bsKinds() & " kinds of barcode, live, with barcodext and zxing-cpp." into field "Tagline" of me
      set the label of button "Scene 2" of me to "2. Every kind (" & the number of lines in bsKinds() & ")"
      set the text of button "Kinds menu" of me to bsKinds()
   else
      put "barcodext is not installed here" into field "Version" of me
      set the textColor of field "Version" of me to kBad
   end if
   set the label of button "Kind" of me to sKind
   bsShowTour
   unlock screen
end bsStart

function bsHasLibrary
   return sHasLibrary is true
end bsHasLibrary

-- The number of the scene playing, empty when none is (the tests and
-- Play all read it).
function bsPlaying
   return sScene
end bsPlaying

-- The kinds to show, one to a line: the ones most people know first, and
-- no second name for a kind already listed.
function bsKinds
   local tKind, tOut, tAll
   put bcWritableFormats() into tAll
   repeat for each item tKind in kCommon
      if tKind is among the items of tAll then
         put tKind & return after tOut
      end if
   end repeat
   repeat for each item tKind in tAll
      if tKind is not among the items of kCommon and tKind is not among the items of kAliases then
         put tKind & return after tOut
      end if
   end repeat
   delete the last char of tOut
   return tOut
end bsKinds

------------------------------------------------------------------------
-- Scenes: one timer, one frame at a time
------------------------------------------------------------------------

command bsStopAll
   if sTimer is not empty then
      cancel sTimer
   end if
   if sNext is not empty then
      cancel sNext
   end if
   if sPending is not empty then
      cancel sPending
   end if
   put empty into sTimer
   put empty into sNext
   put empty into sPending
end bsStopAll

-- Starts a scene from its first frame. pPicture is for scene 3 only: a
-- picture to scan instead of the sample sheet.
command bsPlay pScene, pPicture
   local tError
   bsStopAll
   put pScene into sScene
   put pScene into sLast
   put 0 into sStep
   put empty into sData
   lock screen
   bsClearStage
   bsMarkScene pScene
   put bsAbout(pScene) into field "About" of me
   if not bsHasLibrary() then
      bsNotice
      put empty into sScene
      unlock screen
      exit bsPlay
   end if
   try
      switch pScene
         case 1
            bsBeginType
            break
         case 2
            bsBeginKinds
            break
         case 3
            bsBeginScan pPicture
            break
         case 4
            bsBeginDamage
            break
         case 5
            bsBeginTurn
            break
      end switch
   catch tError
      bsFail
   end try
   unlock screen
   -- Your turn waits for typing: it has no frames
   if sScene is not empty and sScene is not 5 then
      bsSchedule
   end if
end bsPlay

command bsSchedule
   if sScene is not empty and sTimer is empty then
      send "bsTick" to me in kTick milliseconds
      put the result into sTimer
   end if
end bsSchedule

-- One frame of the scene that is playing.
command bsTick
   local tDone, tError
   put empty into sTimer
   if sScene is empty or sScene is 5 then
      exit bsTick
   end if
   add 1 to sStep
   lock screen
   try
      switch sScene
         case 1
            put bsFrameType(sStep) into tDone
            break
         case 2
            put bsFrameKinds(sStep) into tDone
            break
         case 3
            put bsFrameScan(sStep) into tDone
            break
         case 4
            put bsFrameDamage(sStep) into tDone
            break
      end switch
   catch tError
      put "failed" into tDone
      bsFail
   end try
   unlock screen
   if tDone is "done" then
      bsSceneDone
   else if tDone is not "failed" then
      bsSchedule
   end if
end bsTick

-- The last frame stays on the stage. With Play all on, the next scene
-- starts a moment later.
command bsSceneDone
   put empty into sScene
   if sTour then
      send "bsPlayNext" to me in 1600 milliseconds
      put the result into sNext
   end if
end bsSceneDone

-- Play all: the scene after the one that ended (5, Your turn, is never
-- played by Play all).
command bsPlayNext
   put empty into sNext
   bsPlay (sLast mod 4) + 1
end bsPlayNext

-- A scene that stops says so plainly, and the stack goes on answering.
command bsFail
   local tWhy
   put empty into sScene
   put bcLastError() into tWhy
   if tWhy is empty then
      put "This scene stopped on an error." into tWhy
   else
      put "This scene stopped: " & tWhy into tWhy
   end if
   bsHud tWhy, kBad
end bsFail

command bsMarkScene pScene
   local tN
   repeat with tN = 1 to 5
      if tN is pScene then
         set the backgroundColor of button ("Scene" && tN) of me to kOrange
      else
         set the backgroundColor of button ("Scene" && tN) of me to kButton
      end if
   end repeat
end bsMarkScene

command bsShowTour
   if sTour then
      set the backgroundColor of button "Tour" of me to kOrange
      set the label of button "Tour" of me to "Play all: on"
   else
      set the backgroundColor of button "Tour" of me to kButton
      set the label of button "Tour" of me to "Play all: off"
   end if
end bsShowTour

function bsAbout pScene
   switch pScene
      case 1
         return "Every letter typed makes a new QR code, in well under a millisecond. It grows from 21 to 37 squares a side as the words get longer. Then the ink changes: a barcode is only squares, so any dark colour reads, and each one is read back to prove it."
      case 2
         return "Each kind of barcode this library makes, one after another: made from a sample that suits it, then read back by the same library to prove it says what it should. Some are for shops, some for parcels, some for tickets, film and medicine."
      case 3
         return "A sheet with six barcodes of six kinds, one of them light on dark. One call reads the whole picture and says where each barcode is, so each can be outlined as the beam passes."
      case 4
         return "Two QR codes with the same words, stained in the same places. A QR code carries spare squares to repair itself, and level H carries about four times as many as level L. After every stain both are read again: watch which one keeps reading."
      case 5
         return "Your turn. Type in the box below and the barcode is made as you type; pick another kind with the kind button. Save it as a PNG picture, or as an SVG drawing that prints sharp at any size. Or read a picture of your own."
   end switch
   return empty
end bsAbout

------------------------------------------------------------------------
-- The stage
------------------------------------------------------------------------

command bsClearStage
   local tN
   repeat with tN = 1 to 2
      hide image ("Code" && tN) of me
      hide graphic ("Label" && tN) of me
      put empty into field ("Caption" && tN) of me
   end repeat
   repeat with tN = 1 to kMarks
      hide graphic ("Mark" && tN) of me
      hide field ("Tag" && tN) of me
   end repeat
   hide graphic "Beam" of me
   hide graphic "Beam Glow" of me
   hide graphic "Meter" of me
   hide graphic "Meter Back" of me
   hide field "HUD" of me
   put empty into field "Big" of me
   put empty into field "Under" of me
   put empty into field "Notice" of me
   put empty into field "Readout" of me
end bsClearStage

command bsNotice
   put "This engine does not have barcodext, the barcode library, so nothing can be drawn here." & return & return & "Install barcodext from the xTalk Suite, or open this stack in the OXT-Beyond web gallery, where it is built in." into field "Notice" of me
   bsHud "barcodext is missing", kBad
end bsNotice

-- The small box at the top left of the stage, sized to its words.
command bsHud pText, pColor
   if pColor is empty then
      put kDim into pColor
   end if
   put pText into field "HUD" of me
   set the textColor of field "HUD" of me to pColor
   set the width of field "HUD" of me to min(640, the formattedWidth of field "HUD" of me + 8)
   set the left of field "HUD" of me to 34
   show field "HUD" of me
end bsHud

command bsReadout pText
   put pText into field "Readout" of me
end bsReadout

-- Puts a picture (an array with width, height and imageData) into image
-- "Code <pN>" with its middle at pX,pY, on a white label a little larger.
-- The size is set before the pixels: the engine reads imageData against
-- the image's size.
command bsShowCode pN, pPicture, pX, pY
   local tImage, tLeft, tTop
   put the long id of image ("Code" && pN) of me into tImage
   put pX - pPicture["width"] div 2 into tLeft
   put pY - pPicture["height"] div 2 into tTop
   set the lockLoc of tImage to true
   set the rect of tImage to tLeft, tTop, tLeft + pPicture["width"], tTop + pPicture["height"]
   set the imageData of tImage to pPicture["imageData"]
   set the blendLevel of tImage to 0
   show tImage
   set the rect of graphic ("Label" && pN) of me to tLeft - 14, tTop - 14, tLeft + pPicture["width"] + 14, tTop + pPicture["height"] + 14
   set the blendLevel of graphic ("Label" && pN) of me to 0
   show graphic ("Label" && pN) of me
end bsShowCode

-- The picture in image "Code <pN>", as an array.
function bsPictureOf pN
   local tPicture
   put the width of image ("Code" && pN) of me into tPicture["width"]
   put the height of image ("Code" && pN) of me into tPicture["height"]
   put the imageData of image ("Code" && pN) of me into tPicture["imageData"]
   return tPicture
end bsPictureOf

-- A barcode as large as fits pMaxW x pMaxH: made once at scale 1 to
-- learn its size, then at the largest scale that fits.
function bsFit pText, pKind, pOptions, pMaxW, pMaxH, pShowText
   local tOne, tScale, tPicture
   put bcCreateAdvanced(pText, pKind, pOptions, 1, true, pShowText) into tOne
   if tOne["width"] is empty then
      return empty
   end if
   put max(1, min(10, pMaxW div tOne["width"], pMaxH div tOne["height"])) into tScale
   repeat while tScale > 1
      put bcCreateAdvanced(pText, pKind, pOptions, tScale, true, pShowText) into tPicture
      if tPicture["width"] is not empty and tPicture["width"] <= pMaxW and tPicture["height"] <= pMaxH then
         return tPicture
      end if
      subtract 1 from tScale
   end repeat
   return tOne
end bsFit

-- A barcode painted by this script from the rows of 1 and 0 that
-- bcCreateMatrix returns: pOn is the colour of the 1 squares and pOff of
-- the 0 squares (red,green,blue), with pPad squares of margin.
function bsPaint pRows, pScale, pPad, pOn, pOff
   local tOn, tOff, tOnRun, tOffRun, tLine, tRow, tData, tChar, tPadRow, tWidth, tHeight, tPicture, tBand
   if pRows is empty then
      return empty
   end if
   put numToByte(0) & numToByte(item 1 of pOn) & numToByte(item 2 of pOn) & numToByte(item 3 of pOn) into tOn
   put numToByte(0) & numToByte(item 1 of pOff) & numToByte(item 2 of pOff) & numToByte(item 3 of pOff) into tOff
   repeat pScale times
      put tOn after tOnRun
      put tOff after tOffRun
   end repeat
   -- a linear barcode comes back as one row: give it some height
   if the number of lines in pRows is 1 then
      put pRows into tBand
      repeat 23 times
         put return & tBand after pRows
      end repeat
   end if
   put the number of chars in line 1 of pRows + 2 * pPad into tWidth
   put the number of lines in pRows + 2 * pPad into tHeight
   repeat tWidth times
      put tOffRun after tPadRow
   end repeat
   repeat pPad * pScale times
      put tPadRow after tData
   end repeat
   repeat for each line tLine in pRows
      put empty into tRow
      repeat pPad times
         put tOffRun after tRow
      end repeat
      repeat for each char tChar in tLine
         if tChar is "1" then
            put tOnRun after tRow
         else
            put tOffRun after tRow
         end if
      end repeat
      repeat pPad times
         put tOffRun after tRow
      end repeat
      repeat pScale times
         put tRow after tData
      end repeat
   end repeat
   repeat pPad * pScale times
      put tPadRow after tData
   end repeat
   put tWidth * pScale into tPicture["width"]
   put tHeight * pScale into tPicture["height"]
   put tData into tPicture["imageData"]
   return tPicture
end bsPaint

-- An example of content that suits a kind: each kind has rules (an
-- EAN-13 is 12 or 13 digits, a Code 39 is capitals and digits, ...).
function bsSampleFor pKind
   if pKind is among the items of "EAN-13,EAN/UPC" then
      return "5901234123457"
   end if
   if pKind is among the items of "Code 32,Pharmazentralnummer,Code 39 Standard" then
      return "12345"
   end if
   if pKind begins with "DataBar Expanded" then
      return "(01)09501101530003"
   end if
   if pKind begins with "DataBar" then
      return "0950110153000"
   end if
   switch pKind
      case "EAN-8"
         return "96385074"
      case "EAN-5"
         return "52495"
      case "EAN-2"
         return "12"
      case "ISBN"
         return "9780306406157"
      case "UPC-A"
         return "036000291452"
      case "UPC-E"
         return "01234565"
      case "Code 39"
         return "XTALK-39"
      case "Code 128"
         return "PARCEL-0417"
      case "Telepen Numeric"
         return "123456"
      case "Codabar"
         return "A12345B"
      case "ITF"
         return "1234567890"
      case "ITF-14"
         return "12345678901231"
      case "DX Film Edge"
         return "127-15"
      case "Aztec Rune"
         return "123"
      case "MaxiCode"
         return "OXT-BEYOND PARCEL"
      case "QR Code"
         return "https://openxtalk.org/"
   end switch
   return "Hello, xTalk"
end bsSampleFor

------------------------------------------------------------------------
-- 1. Type a code
------------------------------------------------------------------------

command bsBeginType
   put 0 into sData["typed"]
   put 0 into sData["ink"]
   bsTypeTo 1
end bsBeginType

function bsFrameType pStep
   if sData["typed"] < the number of chars in kTyped then
      if pStep mod 2 is 0 then
         bsTypeTo sData["typed"] + 1
      end if
      bsCaret pStep
      return empty
   end if
   -- every word is typed: now the inks
   if pStep mod 16 is 0 then
      add 1 to sData["ink"]
      if sData["ink"] > kInkCount then
         return "done"
      end if
      bsInk sData["ink"]
   end if
   bsCaret pStep
   return empty
end bsFrameType

-- The QR code of the first pCount letters, as large as fits a 330 pixel
-- square: the squares get smaller as there are more of them.
command bsTypeTo pCount
   local tText, tRows, tSquares, tScale, tPicture, tStart, tTime
   put pCount into sData["typed"]
   put char 1 to pCount of kTyped into tText
   put the milliseconds into tStart
   put bcCreateMatrix(tText, "QR Code", "") into tRows
   put the number of lines in tRows into tSquares
   put max(1, min(12, 330 div (tSquares + 8))) into tScale
   put bcCreateAdvanced(tText, "QR Code", "", tScale, true, false) into tPicture
   put the milliseconds - tStart into tTime
   if tPicture["width"] is empty then
      bsHud "QR Code: " & bcLastError(), kBad
      exit bsTypeTo
   end if
   put tRows into sData["rows"]
   put tScale into sData["scale"]
   bsShowCode 1, tPicture, kMidX, kMidY - 20
   put "Version " & (tSquares - 17) div 4 & ": " & tSquares & " x " & tSquares & " squares" into sData["size"]
   bsHud "QR Code  |  " & pCount & " letters  |  " & sData["size"] & "  |  made in " & bsMs(tTime), kDim
   bsReadout "bcCreateMatrix: " & tSquares & " rows of " & tSquares & " squares" & return & "bcCreateAdvanced at scale " & tScale & ": a picture of " & tPicture["width"] & " x " & tPicture["height"] & " pixels"
end bsTypeTo

-- The words typed so far, with a caret that blinks.
command bsCaret pStep
   local tCaret
   put space into tCaret
   if pStep mod 12 < 6 then
      put "_" into tCaret
   end if
   put char 1 to sData["typed"] of kTyped & tCaret into field "Under" of me
end bsCaret

-- The finished code in ink number pInk, painted from its squares, and
-- read back to prove that a reader still sees it.
command bsInk pInk
   local tInk, tPicture, tFound, tStart, tTime, tSays
   set the itemDelimiter to "|"
   put item pInk of kInks into tInk
   put item pInk of kInkNames into tSays
   set the itemDelimiter to comma
   put bsPaint(sData["rows"], sData["scale"], 4, tInk, "255,255,255") into tPicture
   bsShowCode 1, tPicture, kMidX, kMidY - 20
   put the milliseconds into tStart
   put bcRead(tPicture["imageData"], tPicture["width"], tPicture["height"]) into tFound
   put the milliseconds - tStart into tTime
   -- every letter as typed: a comparison that ignored case would pass a
   -- code read back in the wrong case
   set the caseSensitive to true
   if the number of elements in tFound > 0 and tFound[1]["text"] is kTyped then
      bsHud tSays & "  |  read back in " & bsMs(tTime) & ": every letter as it was typed", kGood
   else
      bsHud tSays & "  |  not read back", kBad
   end if
   bsReadout "bcCreateMatrix gave the squares; this script painted them in " & tolower(word 1 of tSays) & "." & return & "bcRead found it again in " & bsMs(tTime) & "."
end bsInk

-- A time in milliseconds, said plainly.
function bsMs pTime
   if pTime < 1 then
      return "under 1 ms"
   end if
   return pTime && "ms"
end bsMs

------------------------------------------------------------------------
-- 2. Every kind
------------------------------------------------------------------------

command bsBeginKinds
   put bsKinds() into sData["kinds"]
   put the number of lines in sData["kinds"] into sData["count"]
   put 0 into sData["index"]
   put 0 into sData["made"]
   put 0 into sData["read"]
   set the rect of graphic "Meter Back" of me to 60, 578, 656, 582
   set the rect of graphic "Meter" of me to 60, 578, 61, 582
   show graphic "Meter Back" of me
   show graphic "Meter" of me
   bsNextKind
end bsBeginKinds

-- A kind every ten frames; the first four of the ten slide it in.
function bsFrameKinds pStep
   local tPhase
   put pStep mod 10 into tPhase
   if tPhase is 0 then
      if sData["index"] >= sData["count"] then
         bsKindsSummary
         return "done"
      end if
      bsNextKind
   else if tPhase <= 4 then
      bsSlideKind tPhase
   end if
   return empty
end bsFrameKinds

command bsNextKind
   local tKind, tSample, tPicture, tFound, tAddOn
   add 1 to sData["index"]
   put line sData["index"] of sData["kinds"] into tKind
   put bsSampleFor(tKind) into tSample
   put tKind into field "Big" of me
   set the width of graphic "Meter" of me to max(1, round(596 * sData["index"] / sData["count"]))
   set the left of graphic "Meter" of me to 60
   put bsFit(tSample, tKind, "", 520, 280, true) into tPicture
   if tPicture["width"] is empty then
      hide image "Code 1" of me
      hide graphic "Label 1" of me
      put empty into field "Under" of me
      bsHud sData["index"] & " of " & sData["count"] & "  |  not made: " & bcLastError(), kBad
      exit bsNextKind
   end if
   add 1 to sData["made"]
   bsShowCode 1, tPicture, kMidX + 48, kMidY
   set the blendLevel of image "Code 1" of me to 60
   set the blendLevel of graphic "Label 1" of me to 60
   put tSample into field "Under" of me
   put bcRead(tPicture["imageData"], tPicture["width"], tPicture["height"]) into tFound
   put tKind is among the items of "EAN-2,EAN-5" into tAddOn
   if the number of elements in tFound > 0 then
      add 1 to sData["read"]
      bsHud sData["index"] & " of " & sData["count"] & "  |  made and read back as " & tFound[1]["format"], kGood
      bsReadout "bcCreateAdvanced(" & quote & tSample & quote & ", " & quote & tKind & quote & ")" & return & "bcRead: " & tFound[1]["format"] & ", " & quote & tFound[1]["text"] & quote
   else if tAddOn then
      bsHud sData["index"] & " of " & sData["count"] & "  |  made: an add-on, read beside a product code", kDim
      bsReadout "bcCreateAdvanced(" & quote & tSample & quote & ", " & quote & tKind & quote & ")" & return & "An add-on is read only beside the code it adds to."
   else
      bsHud sData["index"] & " of " & sData["count"] & "  |  made, not read back on its own", kDim
      bsReadout "bcCreateAdvanced(" & quote & tSample & quote & ", " & quote & tKind & quote & ")" & return & "bcRead did not find it alone."
   end if
end bsNextKind

command bsSlideKind pPhase
   local tShift
   if not the visible of image "Code 1" of me then
      exit bsSlideKind
   end if
   put 12 into tShift
   set the left of image "Code 1" of me to the left of image "Code 1" of me - tShift
   set the left of graphic "Label 1" of me to the left of graphic "Label 1" of me - tShift
   set the blendLevel of image "Code 1" of me to 60 - 15 * pPhase
   set the blendLevel of graphic "Label 1" of me to 60 - 15 * pPhase
end bsSlideKind

command bsKindsSummary
   put sData["made"] && "kinds made," && sData["read"] && "read back" into field "Big" of me
   bsHud "Every kind this library makes, made and read back by the same library", kGood
end bsKindsSummary

------------------------------------------------------------------------
-- 3. Scan a sheet
------------------------------------------------------------------------

-- Reads the whole picture once, at the start, and keeps what was found
-- in the order the beam will meet it: left to right.
command bsBeginScan pPicture
   local tFound, tStart, tN, tOrder, tLine, tPosition, tLeft, tRight, tItem
   if pPicture["width"] is empty then
      put bsSampleSheet() into pPicture
      put "Six barcodes on one sheet, read by one call" into field "Big" of me
   else
      put "Your picture" into field "Big" of me
   end if
   bsShowCode 1, pPicture, kMidX, kMidY + 10
   put the milliseconds into tStart
   put bcRead(pPicture["imageData"], pPicture["width"], pPicture["height"]) into tFound
   put the milliseconds - tStart into sData["ms"]
   put the left of image "Code 1" of me into sData["left"]
   put the top of image "Code 1" of me into sData["top"]
   put pPicture["width"] into sData["width"]
   put pPicture["height"] into sData["height"]
   -- the middle of each barcode, across: the beam meets them in that order
   repeat with tN = 1 to the number of elements in tFound
      put tFound[tN]["position"] into tPosition
      put 100000 into tLeft
      put -1 into tRight
      -- the x of each of the four corners (items 1, 3, 5 and 7): a
      -- "step" in a repeat is not honoured on every engine
      repeat with tItem = 0 to 3
         put min(tLeft, item (2 * tItem + 1) of tPosition) into tLeft
         put max(tRight, item (2 * tItem + 1) of tPosition) into tRight
      end repeat
      put (tLeft + tRight) div 2 & tab & tN & return after tOrder
   end repeat
   set the itemDelimiter to tab
   sort lines of tOrder numeric by item 1 of each
   put 0 into tN
   repeat for each line tLine in tOrder
      if tLine is empty then
         next repeat
      end if
      add 1 to tN
      put tFound[item 2 of tLine] into sData["found"][tN]
      put sData["left"] + item 1 of tLine into sData["middle"][tN]
   end repeat
   set the itemDelimiter to comma
   put tN into sData["count"]
   put 0 into sData["shown"]
   bsHud "Scanning...", kDim
   set the rect of graphic "Beam" of me to sData["left"] - 2, sData["top"] - 10, sData["left"] + 1, sData["top"] + sData["height"] + 10
   set the rect of graphic "Beam Glow" of me to sData["left"] - 40, sData["top"] - 10, sData["left"], sData["top"] + sData["height"] + 10
   show graphic "Beam Glow" of me
   show graphic "Beam" of me
end bsBeginScan

function bsFrameScan pStep
   local tSweep, tX
   put 64 into tSweep
   if pStep <= tSweep then
      put sData["left"] - 10 + round((sData["width"] + 20) * pStep / tSweep) into tX
      set the left of graphic "Beam" of me to tX - 1
      set the right of graphic "Beam Glow" of me to tX
      repeat while sData["shown"] < sData["count"] and sData["middle"][sData["shown"] + 1] <= tX
         add 1 to sData["shown"]
         bsReveal sData["shown"]
      end repeat
      return empty
   end if
   if pStep is tSweep + 1 then
      hide graphic "Beam" of me
      hide graphic "Beam Glow" of me
      if sData["count"] is 0 then
         if bcLastError() is not empty then
            bsHud bcLastError(), kBad
         else
            bsHud "No barcode found in this picture (" & bsMs(sData["ms"]) & ")", kDim
         end if
      else
         bsHud "Found " & sData["count"] & " in " & bsMs(sData["ms"]) & ", with one call to bcRead", kGood
      end if
   end if
   if pStep >= tSweep + 60 then
      return "done"
   end if
   return empty
end bsFrameScan

-- Outlines barcode pN where the picture is on the stage, tags it with
-- its kind and words, and adds it to the list.
command bsReveal pN
   local tBarcode, tPosition, tPoints, tN, tText, tTag, tTop, tLeft
   if pN > kMarks then
      exit bsReveal
   end if
   put sData["found"][pN] into tBarcode
   put tBarcode["position"] into tPosition
   if the number of items in tPosition is 8 then
      put 100000 into tTop
      put 100000 into tLeft
      repeat with tN = 1 to 4
         put (sData["left"] + item (2 * tN - 1) of tPosition) & comma & (sData["top"] + item (2 * tN) of tPosition) & return after tPoints
         put min(tTop, sData["top"] + item (2 * tN) of tPosition) into tTop
         put min(tLeft, sData["left"] + item (2 * tN - 1) of tPosition) into tLeft
      end repeat
      put line 1 of tPoints after tPoints
      set the points of graphic ("Mark" && pN) of me to tPoints
      if tBarcode["valid"] is true then
         set the foregroundColor of graphic ("Mark" && pN) of me to kGood
      else
         set the foregroundColor of graphic ("Mark" && pN) of me to kBad
      end if
      show graphic ("Mark" && pN) of me
   end if
   put tBarcode["text"] into tText
   replace return with space in tText
   if the number of chars in tText > 28 then
      put char 1 to 28 of tText & "..." into tText
   end if
   put the long id of field ("Tag" && pN) of me into tTag
   put tBarcode["format"] & ": " & tText into field ("Tag" && pN) of me
   set the width of tTag to the formattedWidth of tTag + 8
   if tTop is not empty then
      set the topLeft of tTag to max(30, min(tLeft, 686 - the width of tTag)), max(160, tTop - the height of tTag - 4)
   end if
   show tTag
   put tBarcode["format"] & ": " & tText & return after field "Readout" of me
end bsReveal

-- Six barcodes of six kinds on one white sheet, one of them light on
-- dark: what a parcel label or a ticket looks like to a reader.
function bsSampleSheet
   local tSheet, tWide, tHigh, tPicture, tRow, tWhite, tCell, tN, tCode, tKind, tText, tLeft, tTop
   put 570 into tWide
   put 360 into tHigh
   put numToByte(0) & numToByte(255) & numToByte(255) & numToByte(255) into tWhite
   repeat tWide times
      put tWhite after tRow
   end repeat
   repeat tHigh times
      put tRow after tSheet
   end repeat
   put 0 into tN
   repeat for each item tKind in "QR Code,EAN-13,Aztec,Data Matrix,Code 128,PDF417"
      add 1 to tN
      put item tN of "https://openxtalk.org/,5901234123457,Seat 14C gate B7,Part 4711 shelf C,PARCEL-0417,OXT-BEYOND BOARDING PASS" into tText
      if tKind is "Data Matrix" then
         -- light squares on a dark label
         put bcCreateMatrix(tText, tKind, "") into tCode
         put bsPaint(tCode, 6, 2, "255,255,255", "16,24,40") into tCode
      else
         put bsFit(tText, tKind, "", 170, 156, true) into tCode
      end if
      if tCode["width"] is empty then
         next repeat
      end if
      put ((tN - 1) mod 3) * 190 + (190 - tCode["width"]) div 2 into tLeft
      put ((tN - 1) div 3) * 180 + (180 - tCode["height"]) div 2 into tTop
      put bsPaste(tSheet, tWide, tCode, tLeft, tTop) into tSheet
   end repeat
   put tWide into tPicture["width"]
   put tHigh into tPicture["height"]
   put tSheet into tPicture["imageData"]
   return tPicture
end bsSampleSheet

-- Draws one picture onto another, both as imageData.
function bsPaste pSheet, pSheetWidth, pPicture, pLeft, pTop
   local tY, tRow, tStart
   put pPicture["width"] * 4 into tRow
   repeat with tY = 0 to pPicture["height"] - 1
      put ((pTop + tY) * pSheetWidth + pLeft) * 4 + 1 into tStart
      put byte (tY * tRow + 1) to (tY * tRow + tRow) of pPicture["imageData"] into byte tStart to (tStart + tRow - 1) of pSheet
   end repeat
   return pSheet
end bsPaste

------------------------------------------------------------------------
-- 4. Damage it
------------------------------------------------------------------------

-- Two QR codes of the same words, at repair levels L and H, side by side.
-- The stains fall at the same places on both, as fractions of the code,
-- and never on the squares a reader finds a code by: the three corner
-- squares with the strips beside them, and the two timing lines.
command bsBeginDamage
   local tN, tLevel, tRows, tSquares, tScale, tPicture, tX, tY, tTries
   put "Same words, two repair levels" into field "Big" of me
   repeat with tN = 1 to 2
      put item tN of "L,H" into tLevel
      put bcCreateMatrix(kDamageText, "QR Code", "ecLevel=" & tLevel) into tRows
      put the number of lines in tRows into tSquares
      put max(1, min(9, 250 div (tSquares + 8))) into tScale
      put bcCreateAdvanced(kDamageText, "QR Code", "ecLevel=" & tLevel, tScale, true, false) into tPicture
      if tPicture["width"] is empty then
         bsHud "QR Code: " & bcLastError(), kBad
         exit bsBeginDamage
      end if
      put tRows into sData[tN]["rows"]
      put tSquares into sData[tN]["squares"]
      put tScale into sData[tN]["scale"]
      put (tPicture["width"] div tScale - tSquares) div 2 into sData[tN]["pad"]
      put tPicture["width"] into sData[tN]["width"]
      put tPicture["imageData"] into sData[tN]["data"]
      put 0 into sData[tN]["covered"]
      put empty into sData[tN]["lost"]
      put tLevel into sData[tN]["level"]
      bsShowCode tN, tPicture, kMidX - 170 + 340 * (tN - 1), kMidY - 6
      set the rect of field ("Caption" && tN) of me to kMidX - 330 + 340 * (tN - 1), kMidY + 136, kMidX - 10 + 340 * (tN - 1), kMidY + 186
      set the textColor of field ("Caption" && tN) of me to kText
   end repeat
   -- where the stains fall, decided once for both codes
   repeat with tN = 1 to 60
      put 0 into tTries
      repeat
         add 1 to tTries
         put random(1000) / 1000 into tX
         put random(1000) / 1000 into tY
         if bsStainFits(1, tX, tY) and bsStainFits(2, tX, tY) then
            exit repeat
         end if
         if tTries > 200 then
            exit repeat
         end if
      end repeat
      put tX into sData["x"][tN]
      put tY into sData["y"][tN]
   end repeat
   put 0 into sData["stains"]
   bsDamageRead
end bsBeginDamage

-- The top left square of a stain of two by two squares, on code pN.
function bsStainAt pN, pX, pY
   local tLast
   put sData[pN]["squares"] - 2 into tLast
   return round(pY * tLast) & comma & round(pX * tLast)
end bsStainAt

-- True when a stain at pX,pY misses what a reader finds code pN by.
function bsStainFits pN, pX, pY
   local tAt, tSquares, tR, tC
   put sData[pN]["squares"] into tSquares
   put bsStainAt(pN, pX, pY) into tAt
   repeat with tR = item 1 of tAt to item 1 of tAt + 1
      repeat with tC = item 2 of tAt to item 2 of tAt + 1
         if tR is 6 or tC is 6 then
            return false
         end if
         if tR <= 8 and (tC <= 8 or tC >= tSquares - 8) then
            return false
         end if
         if tC <= 8 and tR >= tSquares - 8 then
            return false
         end if
      end repeat
   end repeat
   return true
end bsStainFits

-- A stain every five frames, until neither code reads or the stains run
-- out.
function bsFrameDamage pStep
   if sData[1]["lost"] is not empty and sData[2]["lost"] is not empty then
      if pStep >= sData["end"] + 50 then
         return "done"
      end if
      return empty
   end if
   if pStep mod 5 is not 0 then
      return empty
   end if
   if sData["stains"] >= 60 then
      return "done"
   end if
   add 1 to sData["stains"]
   bsStain 1, sData["stains"]
   bsStain 2, sData["stains"]
   bsDamageRead
   if sData[1]["lost"] is not empty and sData[2]["lost"] is not empty then
      put pStep into sData["end"]
   end if
   return empty
end bsFrameDamage

-- Stain pStain on code pN: two by two squares, dark brown or pale yellow
-- in turn, so a reader sees some squares the other way round.
command bsStain pN, pStain
   local tAt, tR, tC, tDark, tPixel, tRun, tScale, tPad, tWidth, tY, tStart, tData, tKey
   put sData[pN]["scale"] into tScale
   put sData[pN]["pad"] into tPad
   put sData[pN]["width"] into tWidth
   put sData[pN]["data"] into tData
   put bsStainAt(pN, sData["x"][pStain], sData["y"][pStain]) into tAt
   put pStain mod 2 is 1 into tDark
   if tDark then
      put numToByte(0) & numToByte(124) & numToByte(45) & numToByte(18) into tPixel
   else
      put numToByte(0) & numToByte(253) & numToByte(230) & numToByte(138) into tPixel
   end if
   put empty into tRun
   repeat tScale times
      put tPixel after tRun
   end repeat
   repeat with tR = item 1 of tAt to item 1 of tAt + 1
      repeat with tC = item 2 of tAt to item 2 of tAt + 1
         put tR & comma & tC into tKey
         if sData[pN]["stained"][tKey] is not true then
            put true into sData[pN]["stained"][tKey]
            add 1 to sData[pN]["covered"]
         end if
         repeat with tY = (tPad + tR) * tScale to (tPad + tR) * tScale + tScale - 1
            put (tY * tWidth + (tPad + tC) * tScale) * 4 + 1 into tStart
            put tRun into byte tStart to (tStart + tScale * 4 - 1) of tData
         end repeat
      end repeat
   end repeat
   put tData into sData[pN]["data"]
   set the imageData of image ("Code" && pN) of me to tData
end bsStain

-- Reads both codes as they are now and says how each is doing.
command bsDamageRead
   local tN, tFound, tPercent, tPoints, tPosition, tK, tLeft, tTop, tCaption, tStains
   put sData["stains"] into tStains
   set the caseSensitive to true
   repeat with tN = 1 to 2
      put round(100 * sData[tN]["covered"] / (sData[tN]["squares"] * sData[tN]["squares"])) into tPercent
      put the left of image ("Code" && tN) of me into tLeft
      put the top of image ("Code" && tN) of me into tTop
      if sData[tN]["lost"] is not empty then
         next repeat
      end if
      put bcRead(sData[tN]["data"], sData[tN]["width"], sData[tN]["width"]) into tFound
      if the number of elements in tFound > 0 and tFound[1]["text"] is kDamageText then
         if tStains is 0 then
            put "Level " & sData[tN]["level"] & ": reads" & return & item tN of "the least spare,the most spare" into tCaption
         else
            put "Level " & sData[tN]["level"] & ": still reads" & return & tStains && "stains," && tPercent & "% of it covered" into tCaption
         end if
         set the textColor of field ("Caption" && tN) of me to kGood
         put tFound[1]["position"] into tPosition
         put empty into tPoints
         repeat with tK = 1 to 4
            put (tLeft + item (2 * tK - 1) of tPosition) & comma & (tTop + item (2 * tK) of tPosition) & return after tPoints
         end repeat
         put line 1 of tPoints after tPoints
         set the points of graphic ("Mark" && tN) of me to tPoints
         set the foregroundColor of graphic ("Mark" && tN) of me to kGood
         show graphic ("Mark" && tN) of me
      else
         put tStains into sData[tN]["lost"]
         put "Level " & sData[tN]["level"] & ": lost after " & tStains & " stains" & return & tPercent & "% of it covered" into tCaption
         set the textColor of field ("Caption" && tN) of me to kBad
         hide graphic ("Mark" && tN) of me
         set the blendLevel of image ("Code" && tN) of me to 35
      end if
      put tCaption into field ("Caption" && tN) of me
   end repeat
   if tStains is 0 then
      bsHud "Both read  |  stains next, and bcRead on both codes after each one", kDim
   else
      bsHud "Stain " & tStains & "  |  bcRead on both codes after each one", kDim
   end if
   bsReadout "Level L: " & sData[1]["squares"] & " x " & sData[1]["squares"] & " squares, " & sData[1]["covered"] && "stained" & return & "Level H: " & sData[2]["squares"] & " x " & sData[2]["squares"] & " squares, " & sData[2]["covered"] && "stained"
end bsDamageRead

------------------------------------------------------------------------
-- 5. Your turn
------------------------------------------------------------------------

command bsBeginTurn
   put false into sTour
   bsShowTour
   bsMakeTurn
end bsBeginTurn

-- Typing makes the barcode a moment after the last key, not at each.
command bsMakeSoon
   if sPending is not empty then
      cancel sPending
   end if
   send "bsMakeTurn" to me in 150 milliseconds
   put the result into sPending
end bsMakeSoon

command bsMakeTurn
   local tText, tPicture, tStart, tTime, tNote
   put empty into sPending
   if not bsHasLibrary() then
      exit bsMakeTurn
   end if
   lock screen
   bsClearStage
   put the text of field "Input" of me into tText
   if tText is empty then
      bsHud "Type something in the box to put in the barcode", kDim
      unlock screen
      exit bsMakeTurn
   end if
   put the milliseconds into tStart
   put bsFit(tText, sKind, "", 600, 380, true) into tPicture
   put the milliseconds - tStart into tTime
   if tPicture["width"] is empty then
      put bcLastError() into tNote
      if tNote is empty then
         put "that cannot be made into this kind of barcode" into tNote
      end if
      bsHud sKind & ": " & tNote, kBad
      bsReadout "A " & sKind & " takes, for example: " & bsSampleFor(sKind)
      unlock screen
      exit bsMakeTurn
   end if
   bsShowCode 1, tPicture, kMidX, kMidY
   bsHud sKind & "  |  " & tPicture["width"] & " x " & tPicture["height"] & " pixels  |  made in " & bsMs(tTime), kGood
   bsReadout "bcCreateAdvanced(" & quote & char 1 to 40 of tText & quote & ", " & quote & sKind & quote & ")"
   unlock screen
end bsMakeTurn

command bsPickKind pKind
   put pKind into sKind
   set the label of button "Kind" of me to pKind
   if sScene is not 5 then
      bsPlay 5
   else
      bsMakeTurn
   end if
end bsPickKind

command bsSavePNG
   local tData, tPath
   if sScene is not 5 or not the visible of image "Code 1" of me then
      bsPlay 5
   end if
   if not the visible of image "Code 1" of me then
      exit bsSavePNG
   end if
   ask file "Save the barcode as:" with "barcode.png"
   put it into tPath
   if tPath is empty then
      exit bsSavePNG
   end if
   export image "Code 1" of me to tData as PNG
   put tData into url ("binfile:" & tPath)
   bsReadout "Saved the picture: " & the number of bytes in tData & " bytes of PNG."
end bsSavePNG

-- SVG is a drawing, not pixels: it prints sharp at any size.
command bsSaveSVG
   local tSVG, tPath
   if not bsHasLibrary() then
      bsNotice
      exit bsSaveSVG
   end if
   put bcCreateSVG(the text of field "Input" of me, sKind, "", true) into tSVG
   if tSVG is empty then
      bsHud sKind & ": " & bcLastError(), kBad
      exit bsSaveSVG
   end if
   ask file "Save the drawing as:" with "barcode.svg"
   put it into tPath
   if tPath is empty then
      exit bsSaveSVG
   end if
   put textEncode(tSVG, "UTF-8") into url ("binfile:" & tPath)
   bsReadout "Saved the drawing: " & the number of chars in tSVG & " characters of SVG."
end bsSaveSVG

-- A picture of your own: shown scaled down to the stage if it is larger,
-- then scanned as the sample sheet is. What is read is what is shown.
command bsReadAPicture
   local tPath, tData
   if not bsHasLibrary() then
      bsPlay 3
      exit bsReadAPicture
   end if
   answer file "Choose a picture with a barcode in it:"
   put it into tPath
   if tPath is empty then
      exit bsReadAPicture
   end if
   put url ("binfile:" & tPath) into tData
   bsReadPictureData tData
end bsReadAPicture

command bsReadPictureData pData
   local tImage, tWide, tHigh, tScale, tPicture
   put false into sTour
   bsShowTour
   if not (byte 2 to 4 of pData is "PNG" or byte 1 to 4 of pData is "GIF8" or (byteToNum(byte 1 of pData) is 255 and byteToNum(byte 2 of pData) is 216)) then
      bsPlay 5
      bsHud "That file is not a picture this stack can open. Try a PNG, a JPEG or a GIF.", kBad
      exit bsReadPictureData
   end if
   put the long id of image "Loader" of me into tImage
   lock screen
   set the lockLoc of tImage to false
   set the text of tImage to pData
   put the formattedWidth of tImage into tWide
   put the formattedHeight of tImage into tHigh
   if tWide < 1 or tHigh < 1 then
      unlock screen
      bsPlay 5
      bsHud "That picture could not be opened.", kBad
      exit bsReadPictureData
   end if
   put min(1, 600 / tWide, 380 / tHigh) into tScale
   set the lockLoc of tImage to true
   set the width of tImage to max(1, round(tWide * tScale))
   set the height of tImage to max(1, round(tHigh * tScale))
   put the width of tImage into tPicture["width"]
   put the height of tImage into tPicture["height"]
   put the imageData of tImage into tPicture["imageData"]
   set the text of tImage to empty
   unlock screen
   bsPlay 3, tPicture
end bsReadPictureData

------------------------------------------------------------------------
-- Clicks, picks and typing
------------------------------------------------------------------------

on mouseUp
   local tName
   put the short name of the target into tName
   if word 1 of tName is "Scene" and the number of words in tName is 2 then
      if word 2 of tName is 5 then
         put false into sTour
      end if
      bsPlay word 2 of tName
      exit mouseUp
   end if
   switch tName
      case "Tour"
         put not sTour into sTour
         bsShowTour
         if sTour and sScene is empty then
            bsPlay (sLast mod 4) + 1
         end if
         break
      case "Kind"
         popup button "Kinds menu" of me
         break
      case "Read a picture"
         bsReadAPicture
         break
      case "Save PNG"
         bsSavePNG
         break
      case "Save SVG"
         bsSaveSVG
         break
   end switch
end mouseUp

on menuPick pItem
   if the short name of the target is "Kinds menu" then
      bsPickKind pItem
   end if
end menuPick

on textChanged
   if the short name of the target is "Input" then
      if sScene is not 5 then
         put false into sTour
         bsPlay 5
      else
         bsMakeSoon
      end if
   end if
end textChanged