#! lua
local sys, !, $, dim in require "riscos"
@ = require "wimp.toolbox"
-------------- drawfile stuff ---------------
local Drawfile_Load = \ (fpath)
  local r0,r1,r2,r3,r4 = sys (8, 17, fpath)
  if r0 ~= 1 then => nil,fpath.." not a file" end -- if
  local buf = dim (r4)
  sys (8, 16, fpath, buf, 0) -- load file into b
  => buf, r4
  end

local Drawfile_Render = \ (buf, buf_size)
       => \ (@, x, y)
   local b in @
   local u, v = 1<<16, 1<<8
   ![b + 256] = u
   ![b + 260] = 0
   ![b + 264] = 0
   ![b + 268] = u
   ![b + 272] = v*x
   ![b + 276] = v*y
   sys (0x45540, 0, buf, buf_size, b + 256, b + 28)     -- DrawFile_Render
   end end
-----------------------------------------------
local page = dofile "codex:index"
local cache = { } -- storing loaded Drawfile data
local where = "codex:%s"
local getfile = \ (n) => where:format (page[n]) end
local getpage = \ (n)
      local data = cache[n]
      if data then => data.buf, data.bufsize end -- if
      local b, bs = Drawfile_Load (getfile (n))
      cache[n] = { buf = b, bufsize = bs }
      => b, bs
      end

_ENV = @
handler[1] = \ (@)          -- Wimp_RedrawWindow
      local Drawfile_Redraw = Drawfile_Render (getpage (@.pageno))
      => @:user_redraw (Drawfile_Redraw) end

handler.tbox[0xa0] = \ (@)   -- Select clicked on iconbar
  local self_id, parent_id, parent_comp in @.obj.codex
  if 1 & (@:GetObjectState (0, self_id)) == 1 then
    if pageno < #page then pageno + = 1 end -- if
    @:winredraw (self_id)
  else
    pageno = 1
    @:Show_Object (0, self_id, 0, 0, parent_id, parent_comp)
  end -- if
  end

handler.tbox[0xa1] = \ (@)   -- Adjust clicked on iconbar
  local self_id, parent_id, parent_comp in @.obj.codex
  if 1 & (@:GetObjectState (0, self_id)) == 1 then
    if pageno > 1 then pageno - = 1 end -- if
    @:winredraw (self_id)
  else
    pageno = #page
    @:Show_Object (0, self_id, 0, 0, parent_id, parent_comp)
  end -- if
  end

handler.tbox[0xa2] = \ (@)   -- Help on iconbar menu
        local b in @
        $[b] = "filer_run codex:!Help\0"
        sys (0x400de, b)  -- Wimp_StartTask
        end

handler.tbox[0xb0] = handler.tbox[0xa0] -- >
handler.tbox[0xb1] = handler.tbox[0xa1] -- <
handler.tbox[0xb2] = \ (@)              -- >>
  local self_id in @.obj.codex
  pageno = #page
  @:winredraw (self_id)
  end
handler.tbox[0xb3] = \ (@)              -- >>
  local self_id in @.obj.codex
  pageno = 1
  @:winredraw (self_id)
  end

$[resdir] = arg[1]    -- Tell the toolbox where to find res.
init (@, { }, { })    -- All wimp, all toolbox events signify.
mask = 257            -- No null or kbd events.
run (@)               -- This has to be the last statement.
