Advertisement
Pirnogion

OC/Button

Sep 6th, 2015
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.94 KB | None | 0 0
  1. local rect = require "rectangle"
  2. local unicode = require "unicode"
  3.  
  4. --CONST--
  5. local STATUS_ENABLED = 0
  6. local STATUS_DISABLED = 5
  7. local STATUS_BLINK = 10
  8.  
  9. --UTILS--
  10. local function alignTextToCenterRect(rectangle, text)
  11.     local x = rectangle.sx + rectangle.width/2 - unicode.len(text)/2
  12.     local y = rectangle.sy + rectangle.height/2
  13.  
  14.     return x, y
  15. end
  16.  
  17. --Default settings
  18. local default_design = {
  19.     blink_time = 0.2,
  20.  
  21.     [STATUS_ENABLED] = {
  22.         bg = 0x00ff00,
  23.         fg = 0xffffff,
  24.         char = ' '
  25.     },
  26.  
  27.     [STATUS_DISABLED] = {
  28.         bg = 0xffffff,
  29.         fg = 0,
  30.         char = ' '
  31.     },
  32.  
  33.     [STATUS_BLINK] = {
  34.         bg = 0xff0000,
  35.         fg = 0,
  36.         char = ' '
  37.     }
  38. }
  39.  
  40. local default_text = ' '
  41.  
  42. local default_action = function()
  43.     --nothing
  44. end
  45.  
  46. --BUTTON API--
  47. local buttonAPI = {}
  48.  
  49. function buttonAPI.create(gpu, rectangle, text, action, design, status)
  50.     button = {}
  51.  
  52.     button.gpu       = gpu
  53.     button.rectangle = rectangle
  54.     button.design    = design or default_design
  55.     button.text      = text or default_text
  56.     button.action    = action or default_action
  57.     button.status    = status or STATUS_ENABLED
  58.  
  59.     function button:redraw()
  60.         self.gpu.setBackground( self.design[self.status].bg )
  61.         self.gpu.setForeground( self.design[self.status].fg )
  62.         self.gpu.fill( self.rectangle.sx, self.rectangle.sy, self.rectangle.width, self.rectangle.height, self.design[self.status].char )
  63.  
  64.         local textX, textY = alignTextToCenterRect(self.rectangle, self.text)
  65.         self.gpu.set( textX, textY, self.text )
  66.     end
  67.  
  68.     function button:handler(event)
  69.         if ( event[1] == "touch" and event[5] == 0 ) then
  70.             if ( self.status == STATUS_ENABLED ) then
  71.                 if ( rect.PointInRect(event[3], event[4], self.rectangle) ) then
  72.                     self.action()
  73.  
  74.                     self.status = STATUS_BLINK
  75.                     self:redraw()
  76.                     os.sleep(self.design.blink_time)
  77.                     self.status = STATUS_ENABLED
  78.                     self:redraw()
  79.                 end
  80.             end
  81.         end
  82.     end
  83.  
  84.     return button
  85. end
  86.  
  87. return buttonAPI
  88. --pastebin -f get J5jHxja6 lib/button.lua
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement