OXT Community Stacks

The scripts of Beat Box

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.

25 scripts in this stack
  1. card id 1002 (card 1) Beat Box, 385 lines
  2. button "View script" (card 1) Beat Box, 9 lines
  3. button "Play" (card 1) Beat Box, 5 lines
  4. button "Slower" (card 1) Beat Box, 5 lines
  5. button "Faster" (card 1) Beat Box, 5 lines
  6. button "beat House" (card 1) Beat Box, 5 lines
  7. button "beat Hip hop" (card 1) Beat Box, 5 lines
  8. button "beat Breakbeat" (card 1) Beat Box, 5 lines
  9. button "beat Random" (card 1) Beat Box, 5 lines
  10. button "beat Clear" (card 1) Beat Box, 5 lines
  11. field "row 1" (card 1) Beat Box, 2 lines
  12. field "row 2" (card 1) Beat Box, 2 lines
  13. field "row 3" (card 1) Beat Box, 2 lines
  14. field "row 4" (card 1) Beat Box, 2 lines
  15. field "row 5" (card 1) Beat Box, 2 lines
  16. field "row 6" (card 1) Beat Box, 2 lines
  17. the stack script Beat Box Script Viewer, 28 lines
  18. card "Viewer" (card 1) Beat Box Script Viewer, 369 lines
  19. field "svObjects" (card 1) Beat Box Script Viewer, 5 lines
  20. button "svOnly" (card 1) Beat Box Script Viewer, 5 lines
  21. field "svCode" (card 1) Beat Box Script Viewer, 5 lines
  22. button "svCopy" (card 1) Beat Box Script Viewer, 4 lines
  23. button "svShowMe" (card 1) Beat Box Script Viewer, 4 lines
  24. button "svEdit" (card 1) Beat Box Script Viewer, 5 lines
  25. button "svClose" (card 1) Beat Box Script Viewer, 4 lines

card id 1002 (card 1)

Beat Box.oxtstack, stack "Beat Box", 385 lines

-- Beat Box: a 16-step drum machine.
--
-- The pads are graphics; the drums are made by the browser's Web Audio
-- from oscillators and noise, with no samples at all. Timing is the
-- browser's job: a small JavaScript sequencer plays each step a moment
-- ahead on the audio clock, so the beat stays steady. The script tells it
-- the pattern and the tempo with do ... as "JavaScript", and asks it many
-- times a second which step is playing, to move the playhead.
-- Your beat and tempo are saved to a file: in a browser, that file is kept
-- in the page's own storage, so the beat is still there next time.

constant kRows = "Kick,Snare,Clap,Hat,Open hat,Tom"
constant kColours = "236,72,153|251,191,36|163,230,53|34,211,238|96,165,250|167,139,250"
constant kOff = "38,34,68"
constant kOffBeat = "50,45,88"
constant kSaveFile = "beat-box.txt"

local sPattern, sMutes, sBpm, sPlaying, sStep, sTimer, sFallbackAt, sAudio

on preOpenCard
   if sBpm is empty then
      put 0 into sStep
      put false into sPlaying
      if not bbLoad() then bbPreset "House"
      bbDrawAll
   end if
end preOpenCard

on closeCard
   bbStop
end closeCard

-- A pad: click turns it on or off. A row's name: click mutes the row.
on mouseUp
   local tName, tRow, tStep
   put the short name of the target into tName
   if tName begins with "pad " then
      -- "pad 2,7" is row 2, step 7
      put word 2 of tName into tStep
      put item 1 of tStep into tRow
      put item 2 of tStep into tStep
      if char tStep of sPattern[tRow] is "1" then
         put "0" into char tStep of sPattern[tRow]
      else
         put "1" into char tStep of sPattern[tRow]
         if not sPlaying then bbHit tRow
      end if
      bbDrawPad tRow, tStep
      bbSend
      bbSave
   else if tName begins with "row " then
      put word 2 of tName into tRow
      put not sMutes[tRow] into sMutes[tRow]
      bbDrawRow tRow
      bbSend
      bbSave
   else
      pass mouseUp
   end if
end mouseUp

on keyDown pKey
   if pKey is space then
      bbPlayStop
   else
      pass keyDown
   end if
end keyDown

-- The patterns: one string of sixteen 0s and 1s for each instrument.
command bbPreset pName
   local tRows, i
   switch pName
      case "Hip hop"
         put "1000000010100000,0000100000001000,0000000000000000,1010101010101010,0000000000000010,0000000000000000" into tRows
         put 92 into sBpm
         break
      case "Breakbeat"
         put "1010000000110000,0000100101001001,0000000000000000,1010101010101010,0000000000000000,0000000000000110" into tRows
         put 136 into sBpm
         break
      case "Clear"
         put "0000000000000000,0000000000000000,0000000000000000,0000000000000000,0000000000000000,0000000000000000" into tRows
         if sBpm is empty then put 120 into sBpm
         break
      case "Random"
         put empty into tRows
         repeat with i = 1 to 6
            put bbRandomRow(i) & comma after tRows
         end repeat
         delete the last char of tRows
         if sBpm is empty then put 120 into sBpm
         break
      default
         put "1000100010001000,0000000000000000,0000100000001000,1101110111011101,0010001000100010,0000000000000000" into tRows
         put 124 into sBpm
   end switch
   repeat with i = 1 to 6
      put item i of tRows into sPattern[i]
      put false into sMutes[i]
   end repeat
   bbDrawAll
   bbSend
   bbSave
end bbPreset

-- A random row that still sounds like a beat: kicks lean to the down
-- beats, snares and claps to the back beats, hats are busy.
function bbRandomRow pRow
   local tRow, tChance, s
   repeat with s = 1 to 16
      switch pRow
         case 1
            if s mod 4 is 1 then
               put 80 into tChance
            else
               put 12 into tChance
            end if
            break
         case 2
            if s is 5 or s is 13 then
               put 90 into tChance
            else
               put 8 into tChance
            end if
            break
         case 3
            put 10 into tChance
            break
         case 4
            put 60 into tChance
            break
         case 5
            put 10 into tChance
            break
         default
            put 6 into tChance
      end switch
      if random(100) <= tChance then
         put "1" after tRow
      else
         put "0" after tRow
      end if
   end repeat
   return tRow
end bbRandomRow

command bbTempo pChange
   put max(60, min(180, sBpm + pChange)) into sBpm
   bbDrawTempo
   bbSend
   bbSave
end bbTempo

-- Drawing: every pad, a row, one pad.
command bbDrawAll
   local r
   lock screen
   repeat with r = 1 to 6
      bbDrawRow r
   end repeat
   bbDrawTempo
   unlock screen
end bbDrawAll

command bbDrawRow pRow
   local s
   repeat with s = 1 to 16
      bbDrawPad pRow, s
   end repeat
   if sMutes[pRow] then
      set the blendLevel of field ("row" && pRow) to 60
      set the blendLevel of graphic ("led" & pRow) to 80
   else
      set the blendLevel of field ("row" && pRow) to 0
      set the blendLevel of graphic ("led" & pRow) to 0
   end if
end bbDrawRow

command bbDrawPad pRow, pStep
   local tColour
   if char pStep of sPattern[pRow] is "1" then
      set the itemDelimiter to "|"
      put item pRow of kColours into tColour
      set the itemDelimiter to comma
      if sMutes[pRow] then
         set the blendLevel of graphic ("pad" && pRow & comma & pStep) to 65
      else
         set the blendLevel of graphic ("pad" && pRow & comma & pStep) to 0
      end if
   else if pStep mod 4 is 1 then
      put kOffBeat into tColour
      set the blendLevel of graphic ("pad" && pRow & comma & pStep) to 0
   else
      put kOff into tColour
      set the blendLevel of graphic ("pad" && pRow & comma & pStep) to 0
   end if
   set the backgroundColor of graphic ("pad" && pRow & comma & pStep) to tColour
end bbDrawPad

command bbDrawTempo
   set the text of field "Bpm" to sBpm
end bbDrawTempo

-- The sequencer in the page. It is made once and kept on window.oxtBeat;
-- after that the script only changes its pattern, tempo and state.
function bbEngineJs
   return "(function(){var w=window;if(w.oxtBeat)return 'ok';" & \
         "var C=w.AudioContext||w.webkitAudioContext;if(!C)return 'none';" & \
         "var c=new C(),out=c.createDynamicsCompressor(),m=c.createGain();m.gain.value=0.8;m.connect(out);out.connect(c.destination);" & \
         "var n=c.createBuffer(1,c.sampleRate,c.sampleRate),d=n.getChannelData(0);for(var i=0;i<d.length;i++)d[i]=Math.random()*2-1;" & \
         "function env(g,t,a,len){g.gain.setValueAtTime(a,t);g.gain.exponentialRampToValueAtTime(0.001,t+len);}" & \
         "function tone(type,f1,f2,len,a,t){var o=c.createOscillator(),g=c.createGain();o.type=type;" & \
         "o.frequency.setValueAtTime(f1,t);o.frequency.exponentialRampToValueAtTime(f2,t+len);env(g,t,a,len);" & \
         "o.connect(g);g.connect(m);o.start(t);o.stop(t+len+0.02);}" & \
         "function noise(kind,f,len,a,t){var s=c.createBufferSource(),b=c.createBiquadFilter(),g=c.createGain();" & \
         "s.buffer=n;b.type=kind;b.frequency.value=f;env(g,t,a,len);s.connect(b);b.connect(g);g.connect(m);s.start(t);s.stop(t+len+0.02);}" & \
         "var drums=[function(t){tone('sine',150,40,0.45,1,t);}," & \
         "function(t){noise('highpass',1200,0.18,0.7,t);tone('triangle',190,150,0.1,0.5,t);}," & \
         "function(t){noise('bandpass',1500,0.02,0.8,t);noise('bandpass',1500,0.02,0.8,t+0.012);noise('bandpass',1400,0.22,0.8,t+0.024);}," & \
         "function(t){noise('highpass',7500,0.05,0.35,t);}," & \
         "function(t){noise('highpass',7000,0.32,0.3,t);}," & \
         "function(t){tone('sine',240,110,0.32,0.8,t);}];" & \
         "var B=w.oxtBeat={c:c,rows:['','','','','',''],mutes:[0,0,0,0,0,0],bpm:120,playing:false,next:0,step:0,shown:-1,queue:[]," & \
         "hit:function(r){if(c.state==='suspended')c.resume();drums[r](c.currentTime+0.01);}," & \
         "start:function(){if(c.state==='suspended')c.resume();B.playing=true;B.step=0;B.next=c.currentTime+0.06;B.queue=[];}," & \
         "stop:function(){B.playing=false;B.queue=[];B.shown=-1;}," & \
         "now:function(){var t=c.currentTime;while(B.queue.length&&B.queue[0][1]<=t){B.shown=B.queue.shift()[0];}return B.playing?B.shown:-1;}};" & \
         "setInterval(function(){if(!B.playing)return;var ahead=c.currentTime+0.12;" & \
         "while(B.next<ahead){for(var r=0;r<6;r++)if(!B.mutes[r]&&B.rows[r].charAt(B.step)==='1')drums[r](B.next);" & \
         "B.queue.push([B.step,B.next]);B.next+=60/B.bpm/4;B.step=(B.step+1)%16;}},25);" & \
         "return 'ok';})()"
end bbEngineJs

-- Makes the sequencer if need be; true when the page can play.
function bbReady
   local tResult
   if the platform is not "HTML5" then return false
   if sAudio is "ok" then return true
   try
      do bbEngineJs() as "JavaScript"
      put the result into tResult
   catch tError
      put "none" into tResult
   end try
   put tResult into sAudio
   return (tResult is "ok")
end bbReady

-- The pattern, mutes and tempo, sent to the page.
command bbSend
   local tRows, tMutes, r
   if not bbReady() then exit bbSend
   repeat with r = 1 to 6
      put "'" & sPattern[r] & "'," after tRows
      if sMutes[r] then
         put "1," after tMutes
      else
         put "0," after tMutes
      end if
   end repeat
   delete the last char of tRows
   delete the last char of tMutes
   do "oxtBeat.rows=[" & tRows & "];oxtBeat.mutes=[" & tMutes & "];oxtBeat.bpm=" & sBpm & ";" as "JavaScript"
end bbSend

command bbHit pRow
   if bbReady() then do "oxtBeat.hit(" & pRow - 1 & ")" as "JavaScript"
end bbHit

command bbPlayStop
   if sPlaying then
      bbStop
   else
      bbPlay
   end if
end bbPlayStop

command bbPlay
   put true into sPlaying
   put 0 into sStep
   set the label of button "Play" to "Stop"
   if bbReady() then
      bbSend
      do "oxtBeat.start()" as "JavaScript"
      set the text of field "Status" to "Playing. Change pads as it plays: you hear it at once. Space starts and stops."
   else
      put the milliseconds into sFallbackAt
      set the text of field "Status" to "Open this stack in a browser to hear it: the drums are made by the page. The playhead runs anyway."
   end if
   bbFollow
end bbPlay

command bbStop
   put false into sPlaying
   if sTimer is not empty then cancel sTimer
   put empty into sTimer
   if sAudio is "ok" then do "oxtBeat.stop()" as "JavaScript"
   if there is a button "Play" then
      set the label of button "Play" to "Play"
      bbShowStep 0
   end if
end bbStop

-- Many times a second: which step is the page playing? Move the playhead
-- there and light the pads that sound.
on bbFollow
   local tStep
   set the defaultStack to the short name of the owner of me
   put empty into sTimer
   if not sPlaying then exit bbFollow
   if sAudio is "ok" then
      do "oxtBeat.now()" as "JavaScript"
      put the result + 1 into tStep
   else
      put (round((the milliseconds - sFallbackAt) / (15000 / sBpm)) mod 16) + 1 into tStep
   end if
   if tStep is not sStep and tStep >= 1 then bbShowStep tStep
   send "bbFollow" to me in 16 milliseconds
   put the result into sTimer
end bbFollow

command bbShowStep pStep
   local r, tOld
   lock screen
   put sStep into tOld
   put pStep into sStep
   if tOld >= 1 then
      repeat with r = 1 to 6
         bbDrawPad r, tOld
      end repeat
      set the backgroundColor of graphic ("dot" & tOld) to kOff
   end if
   if pStep >= 1 then
      set the left of graphic "Head" to the left of graphic ("pad 1," & pStep) - 4
      set the visible of graphic "Head" to true
      set the backgroundColor of graphic ("dot" & pStep) to "255,255,255"
      -- the pads that sound now flash white
      repeat with r = 1 to 6
         if char pStep of sPattern[r] is "1" and not sMutes[r] then
            set the backgroundColor of graphic ("pad" && r & comma & pStep) to "255,255,255"
         end if
      end repeat
   else
      set the visible of graphic "Head" to false
   end if
   unlock screen
end bbShowStep

-- The beat's file. In a browser, the documents folder is the page's own
-- storage, kept between visits; elsewhere a folder for this sample.
function bbSavePath
   local tFolder
   if the platform is "HTML5" then
      put specialFolderPath("documents") into tFolder
   else
      put specialFolderPath("temporary") & "/oxt-beat-box" into tFolder
   end if
   if there is not a folder tFolder then create folder tFolder
   return tFolder & "/" & kSaveFile
end bbSavePath

-- Line 1 the tempo, then one line a row: its pattern, and 1 if muted.
command bbSave
   local tText, r
   put sBpm & return into tText
   repeat with r = 1 to 6
      put sPattern[r] & comma & (sMutes[r] is true) & return after tText
   end repeat
   put tText into url ("file:" & bbSavePath())
end bbSave

function bbLoad
   local tText, r
   put url ("file:" & bbSavePath()) into tText
   if line 1 of tText is not an integer or the number of lines of tText < 7 then return false
   put line 1 of tText into sBpm
   repeat with r = 1 to 6
      put item 1 of line r + 1 of tText into sPattern[r]
      if length(sPattern[r]) is not 16 then return false
      put (item 2 of line r + 1 of tText is "true") into sMutes[r]
   end repeat
   return true
end bbLoad

button "View script" (card 1)

Beat Box.oxtstack, stack "Beat Box", 9 lines

-- Opens the Script Viewer: the scripts of this stack, in colour.
on mouseUp
   if the mode of stack "Beat Box Script Viewer" is not 0 then
      close stack "Beat Box Script Viewer"
   else
      dispatch "svOpen" to card "Viewer" of stack "Beat Box Script Viewer" with the short name of this stack
   end if
end mouseUp

button "Play" (card 1)

Beat Box.oxtstack, stack "Beat Box", 5 lines

-- Starts and stops the beat. Space does the same.
on mouseUp
   bbPlayStop
end mouseUp

button "Slower" (card 1)

Beat Box.oxtstack, stack "Beat Box", 5 lines

-- Four beats a minute slower.
on mouseUp
   bbTempo -4
end mouseUp

button "Faster" (card 1)

Beat Box.oxtstack, stack "Beat Box", 5 lines

-- Four beats a minute faster.
on mouseUp
   bbTempo 4
end mouseUp

button "beat House" (card 1)

Beat Box.oxtstack, stack "Beat Box", 5 lines

-- Puts a pattern on the pads.
on mouseUp
   bbPreset the label of me
end mouseUp

button "beat Hip hop" (card 1)

Beat Box.oxtstack, stack "Beat Box", 5 lines

-- Puts a pattern on the pads.
on mouseUp
   bbPreset the label of me
end mouseUp

button "beat Breakbeat" (card 1)

Beat Box.oxtstack, stack "Beat Box", 5 lines

-- Puts a pattern on the pads.
on mouseUp
   bbPreset the label of me
end mouseUp

button "beat Random" (card 1)

Beat Box.oxtstack, stack "Beat Box", 5 lines

-- Puts a pattern on the pads.
on mouseUp
   bbPreset the label of me
end mouseUp

button "beat Clear" (card 1)

Beat Box.oxtstack, stack "Beat Box", 5 lines

-- Puts a pattern on the pads.
on mouseUp
   bbPreset the label of me
end mouseUp

field "row 1" (card 1)

Beat Box.oxtstack, stack "Beat Box", 2 lines

-- Click to mute or unmute this drum: the card script does it.

field "row 2" (card 1)

Beat Box.oxtstack, stack "Beat Box", 2 lines

-- Click to mute or unmute this drum: the card script does it.

field "row 3" (card 1)

Beat Box.oxtstack, stack "Beat Box", 2 lines

-- Click to mute or unmute this drum: the card script does it.

field "row 4" (card 1)

Beat Box.oxtstack, stack "Beat Box", 2 lines

-- Click to mute or unmute this drum: the card script does it.

field "row 5" (card 1)

Beat Box.oxtstack, stack "Beat Box", 2 lines

-- Click to mute or unmute this drum: the card script does it.

field "row 6" (card 1)

Beat Box.oxtstack, stack "Beat Box", 2 lines

-- Click to mute or unmute this drum: the card script does it.

the stack script

Beat Box.oxtstack, stack "Beat Box Script Viewer", 28 lines

-- The Script Viewer's own messages stop here, so they never reach the
-- stack it belongs to: that stack's openCard, mouseUp and arrowKey
-- handlers are for its own cards.
on preOpenStack
end preOpenStack
on openStack
end openStack
on preOpenCard
end preOpenCard
on openCard
end openCard
on closeCard
end closeCard
on closeStack
end closeStack
on mouseUp
end mouseUp
on mouseDown
end mouseDown
on arrowKey pKey
   -- up and down move through the list
   if pKey is "up" then svMove -1
   if pKey is "down" then svMove 1
end arrowKey
on escapeKey
   close this stack
end escapeKey

card "Viewer" (card 1)

Beat Box.oxtstack, stack "Beat Box Script Viewer", 369 lines

-- ===== The Script Viewer =====
-- Lists the scripts of the card in front of the stack that opened it,
-- and shows the one chosen in colour: comments, strings, numbers,
-- keywords, commands and the names of handlers each in their own
-- colour, with line numbers. Any stack opens it with svOpen:
--
--    dispatch "svOpen" to card 1 of stack "Beat Box Script Viewer" with "My Stack"
--
-- Controls are named "of me" (this card), so these handlers work even
-- while another stack is the default stack.

-- The colours of the code, on its dark background.
constant kInk = "#E0DEF4"
constant kComment = "#7F8FA6"
constant kString = "#F6C177"
constant kNumber = "#F8A978"
constant kKeyword = "#C4A7E7"
constant kCommand = "#9CCFD8"
constant kDeclare = "#EB6F92"
constant kName = "#82AAFF"
constant kSoft = "#A6A3C4"

-- Words of each kind. A word may be in only one list.
constant kKeywords = "if,then,else,end,repeat,for,each,while,until,forever,times,switch,case,default,break,exit,next,pass,return,try,catch,finally,throw,do,send,dispatch,call,with,in"
constant kCommands = "put,set,get,go,answer,ask,create,delete,show,hide,lock,unlock,wait,add,subtract,multiply,divide,sort,replace,open,close,palette,move,play,beep,select,copy,paste,start,stop,save,write,read,launch,click,type,focus,choose,cancel,import,export,print,filter,split,combine,load,post"
constant kSoftWords = "the,of,into,after,before,and,or,not,is,a,an,to,me,it,empty,true,false,quote,space,tab,comma,cr,return,line,lines,word,words,char,chars,item,items,field,button,card,stack,graphic,group,this,target,among,contains,there"
constant kDeclares = "on,command,function,private,getprop,setprop,local,global,constant"

local sTarget    -- the name of the stack whose scripts are listed
local sIDs       -- the long id of the object on each line of the list
local sInBlock   -- true inside a /* ... */ comment while colouring

-- Open the viewer for a stack, beside its window, listing the scripts
-- of its card in front. pChoose "stack" chooses the stack script.
command svOpen pStack, pChoose
   local tR, tScreen, tHeight, tLeft, tTop
   put pStack into sTarget
   put the rect of stack pStack into tR
   put the working screenRect into tScreen
   -- As tall as the screen allows, keeping room above for the title bar,
   -- so that the window can always be dragged.
   put min(640, item 4 of tScreen - item 2 of tScreen - 44) into tHeight
   put max(440, tHeight) into tHeight
   if the height of this stack is not tHeight then
      set the height of this stack to tHeight
   end if
   svLayout
   -- To the right of the stack's window, or to its left, or over it.
   put item 3 of tR + 12 into tLeft
   if tLeft + the width of this stack > item 3 of tScreen then
      put item 1 of tR - 12 - the width of this stack into tLeft
   end if
   if tLeft < item 1 of tScreen then
      put item 3 of tR - the width of this stack - 12 into tLeft
   end if
   put max(item 1 of tScreen, tLeft) into tLeft
   -- Level with the stack, but never above the screen or off its bottom.
   put max(item 2 of tR, item 2 of tScreen + 32) into tTop
   if tTop + tHeight > item 4 of tScreen - 8 then
      put item 4 of tScreen - 8 - tHeight into tTop
   end if
   put max(tTop, item 2 of tScreen + 32) into tTop
   set the topLeft of this stack to tLeft, tTop
   -- Open first: a list field keeps its chosen line only while open.
   if the mode of this stack is 0 then
      palette this stack
   end if
   svRefresh pChoose
end svOpen

-- The window can be made shorter or taller: the list and the code share
-- the height, and the buttons stay at the bottom.
on resizeStack
   svLayout
end resizeStack

command svLayout
   local tH, tList, tY, tButton
   put the height of this stack into tH
   put max(70, 140 - max(0, 600 - tH)) into tList
   lock screen
   set the rect of field "svObjects" of me to 16, 78, 524, 78 + tList
   put 78 + tList + 4 into tY
   set the rect of button "svOnly" of me to 16, tY, 330, tY + 22
   add 28 to tY
   set the rect of field "svAbout" of me to 16, tY, 524, tY + 54
   add 62 to tY
   set the rect of field "svGutter" of me to 16, tY, 58, tH - 52
   set the rect of field "svCode" of me to 58, tY, 524, tH - 52
   repeat for each item tButton in "svCopy,svShowMe,svEdit,svClose"
      set the bottom of button tButton of me to tH - 12
   end repeat
   unlock screen
end svLayout

-- Rebuild the list for the target's card in front.
command svRefresh pChoose
   local tCard, tMain, tList, tObj, i, tOnly, tPrevious, tLine
   if sTarget is empty or there is not a stack sTarget then exit svRefresh
   -- Remember which object was chosen, to choose it again.
   put line (the hilitedLine of field "svObjects" of me) of sIDs into tPrevious
   put the long id of stack sTarget into tMain
   put the long id of this card of stack sTarget into tCard
   put sTarget & ": the card" && quote & the short name of tCard & quote into field "svSub" of me
   put the hilite of button "svOnly" of me into tOnly
   -- The stack and the card come first: they are always listed.
   put "Stack script" & tab & svCount(tMain) into tList
   put tMain into sIDs
   put return & "Card script" & tab & svCount(tCard) after tList
   put return & tCard after sIDs
   -- Then each control of the card, from the back to the front.
   repeat with i = 1 to the number of controls of tCard
      put the long id of control i of tCard into tObj
      if tOnly and the script of tObj is empty then next repeat
      put return after tList
      -- Controls in a group are indented under it.
      if word 1 of the owner of tObj is "group" then put "    " after tList
      put the name of tObj & tab & svCount(tObj) after tList
      put return & tObj after sIDs
   end repeat
   put tList into field "svObjects" of me
   -- Choose as asked, or the same object again, or else the card script.
   put 2 into tLine
   if pChoose is "stack" then
      put 1 into tLine
   else if tPrevious is not empty then
      set the wholeMatches to true
      if lineOffset(tPrevious, sIDs) > 0 then put lineOffset(tPrevious, sIDs) into tLine
   end if
   set the hilitedLine of field "svObjects" of me to tLine
   svShow
end svRefresh

-- "12 lines", or "no script".
function svCount pObj
   local tCount
   put the number of lines of the script of pObj into tCount
   if tCount is 0 then return "no script"
   if tCount is 1 then return "1 line"
   return tCount && "lines"
end svCount

-- The long id of the object chosen in the list (empty when none).
function svCurrent
   local tLine
   put the hilitedLine of field "svObjects" of me into tLine
   if tLine is empty then return empty
   return line tLine of sIDs
end svCurrent

-- Show the chosen object's script, and a word on what it is for.
command svShow
   local tObj, tScript, tNumbers, i
   put svCurrent() into tObj
   if tObj is empty then exit svShow
   if not exists(tObj) then
      -- It was deleted since the list was made.
      svRefresh
      exit svShow
   end if
   lock screen
   put svAbout(tObj) into field "svAbout" of me
   put the script of tObj into tScript
   if tScript is empty then put "-- This object has no script." into tScript
   -- htmlText sets the text and its colours in one go.
   set the htmlText of field "svCode" of me to svColoured(tScript)
   repeat with i = 1 to the number of lines of tScript
      put i & return after tNumbers
   end repeat
   put char 1 to -2 of tNumbers into field "svGutter" of me
   set the vScroll of field "svCode" of me to 0
   set the hScroll of field "svCode" of me to 0
   set the vScroll of field "svGutter" of me to 0
   unlock screen
end svShow

-- The script as htmlText, one coloured paragraph per line.
function svColoured pScript
   local tLine, tHtml
   put false into sInBlock
   repeat for each line tLine in pScript
      put "<p>" & svColourLine(tLine) & "</p>" after tHtml
   end repeat
   return tHtml
end svColoured

-- One line, coloured word by word. Walks the line a character at a
-- time: a quote starts a string, -- or # a comment to the end of the
-- line, /* a comment to */, a letter a word.
function svColourLine pLine
   local tOut, tLen, i, tChar, tStart, tWord, tPrev, tEnd
   put the number of chars of pLine into tLen
   put 1 into i
   if sInBlock then
      put offset("*/", pLine) into tEnd
      if tEnd is 0 then return svSpan(pLine, kComment)
      put svSpan(char 1 to tEnd + 1 of pLine, kComment) into tOut
      put false into sInBlock
      put tEnd + 2 into i
   end if
   repeat while i <= tLen
      put char i of pLine into tChar
      if tChar is quote then
         put i into tStart
         add 1 to i
         repeat while i <= tLen and char i of pLine is not quote
            add 1 to i
         end repeat
         put svSpan(char tStart to i of pLine, kString) after tOut
         add 1 to i
      else if char i to i + 1 of pLine is "--" or tChar is "#" then
         put svSpan(char i to tLen of pLine, kComment) after tOut
         exit repeat
      else if char i to i + 1 of pLine is "/*" then
         put offset("*/", char i + 2 to tLen of pLine) into tEnd
         if tEnd is 0 then
            put svSpan(char i to tLen of pLine, kComment) after tOut
            put true into sInBlock
            exit repeat
         end if
         put svSpan(char i to i + tEnd + 2 of pLine, kComment) after tOut
         add tEnd + 3 to i
      else if svIsWordChar(tChar) then
         put i into tStart
         repeat while i <= tLen and svIsWordChar(char i of pLine)
            add 1 to i
         end repeat
         put char tStart to i - 1 of pLine into tWord
         put svSpan(tWord, svWordColour(tWord, tPrev)) after tOut
         put tWord into tPrev
      else
         put svEscape(tChar) after tOut
         add 1 to i
      end if
   end repeat
   return tOut
end svColourLine

-- The colour of a word, which can depend on the word before it: the
-- word after on, command or function is the name of a handler.
function svWordColour pWord, pPrevious
   if pPrevious is among the items of "on,command,function,getProp,setProp" then return kName
   if pWord is a number then return kNumber
   if pWord is among the items of kDeclares then return kDeclare
   if pWord is among the items of kKeywords then return kKeyword
   if pWord is among the items of kCommands then return kCommand
   if pWord is among the items of kSoftWords then return kSoft
   return kInk
end svWordColour

function svIsWordChar pChar
   return pChar is in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"
end svIsWordChar

function svSpan pText, pColour
   return "<font color=" & quote & pColour & quote & ">" & svEscape(pText) & "</font>"
end svSpan

-- < > and & mean something in HTML: write them as entities.
function svEscape pText
   replace "&" with "&amp;" in pText
   replace "<" with "&lt;" in pText
   replace ">" with "&gt;" in pText
   return pText
end svEscape

-- A sentence or two on what this kind of script does, and its handlers.
function svAbout pObj
   local tKind, tText, tHandlers
   put word 1 of the name of pObj into tKind
   switch tKind
      case "stack"
         put "The stack script is the last stop on the message path for every card, so its handlers can be called from anywhere in the stack." into tText
         break
      case "card"
         put "A card script gets the card's own messages (openCard, closeCard) and the messages of its controls that they do not handle." into tText
         break
      case "group"
         put "A group script gets the messages of the controls inside the group that they do not handle themselves." into tText
         break
      default
         if the script of pObj is not empty then
            put "This" && tKind & "'s handlers run when it gets the messages they are named after: mouseUp for a click." into tText
         else if the cGoTo of pObj is not empty then
            put "No script: its click goes up the message path to the stack script, which reads its cGoTo property (" & quote & the cGoTo of pObj & quote & ")." into tText
         else if word 1 of the owner of pObj is "group" then
            put "No script: its messages go on to its group," && the short name of the owner of pObj & "." into tText
         else
            put "No script: this" && tKind && "only shows something, and other scripts change it." into tText
         end if
   end switch
   put svHandlers(the script of pObj) into tHandlers
   if tHandlers is not empty then put return & "Handlers: " & tHandlers after tText
   return tText
end svAbout

-- The names of the handlers in a script, joined with commas.
function svHandlers pScript
   local tLine, tDecl, tList
   repeat for each line tLine in pScript
      put tLine into tDecl
      if word 1 of tDecl is "private" then delete word 1 of tDecl
      if word 1 of tDecl is among the items of "on,command,function,getProp,setProp" then
         put word 2 of tDecl & ", " after tList
      end if
   end repeat
   if tList is not empty then delete char -2 to -1 of tList
   return tList
end svHandlers

-- Copy the chosen script, and say so on the button for a moment.
command svCopy
   local tObj
   put svCurrent() into tObj
   if tObj is empty then exit svCopy
   set the clipboardData["text"] to the script of tObj
   set the label of button "svCopy" of me to "Copied!"
   send "svCopyDone" to me in 1200 milliseconds
end svCopy

on svCopyDone
   set the label of button "svCopy" of me to "Copy"
end svCopyDone

-- Open the chosen script in the Script Editor (only in the IDE).
command svEdit
   local tObj
   put svCurrent() into tObj
   if tObj is empty then exit svEdit
   edit the script of tObj
end svEdit

-- Make the chosen control blink, to show where it is.
command svShowMe
   local tObj
   put svCurrent() into tObj
   if tObj is empty then exit svShowMe
   if word 1 of the name of tObj is among the items of "stack,card" then
      put "Show me works on a control: choose one in the list." into field "svAbout" of me
      exit svShowMe
   end if
   if not the visible of tObj then
      put "This control is hidden right now, so it cannot blink." into field "svAbout" of me
      exit svShowMe
   end if
   repeat 3 times
      set the visible of tObj to false
      wait 150 milliseconds with messages
      set the visible of tObj to true
      wait 150 milliseconds with messages
   end repeat
end svShowMe

-- The arrow keys move the choice in the list.
command svMove pStep
   local tLine
   put the hilitedLine of field "svObjects" of me into tLine
   if tLine is empty then put 0 into tLine
   put max(1, min(the number of lines of field "svObjects" of me, tLine + pStep)) into tLine
   set the hilitedLine of field "svObjects" of me to tLine
   svShow
end svMove


-- Edit script is shown only in the IDE, where the Script Editor is.
on preOpenCard
   set the visible of button "svEdit" of me to (the environment is "development")
end preOpenCard

field "svObjects" (card 1)

Beat Box.oxtstack, stack "Beat Box Script Viewer", 5 lines

-- Show the script of the object clicked. svShow is in the card script.
on mouseUp
   svShow
end mouseUp

button "svOnly" (card 1)

Beat Box.oxtstack, stack "Beat Box Script Viewer", 5 lines

-- List every control, or only those with a script.
on mouseUp
   svRefresh
end mouseUp

field "svCode" (card 1)

Beat Box.oxtstack, stack "Beat Box Script Viewer", 5 lines

-- The line numbers scroll with the code.
on scrollbarDrag
   set the vScroll of field "svGutter" of me to the vScroll of me
end scrollbarDrag

button "svCopy" (card 1)

Beat Box.oxtstack, stack "Beat Box Script Viewer", 4 lines

on mouseUp
   svCopy
end mouseUp

button "svShowMe" (card 1)

Beat Box.oxtstack, stack "Beat Box Script Viewer", 4 lines

on mouseUp
   svShowMe
end mouseUp

button "svEdit" (card 1)

Beat Box.oxtstack, stack "Beat Box Script Viewer", 5 lines

-- edit opens the Script Editor, which only the IDE has.
on mouseUp
   svEdit
end mouseUp

button "svClose" (card 1)

Beat Box.oxtstack, stack "Beat Box Script Viewer", 4 lines

on mouseUp
   close this stack
end mouseUp