Advertisement
kaibochan

Text.lua

Feb 22nd, 2025
280
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.08 KB | None | 0 0
  1. local Element = require("gui.Element")
  2. local Cell = require("gui.Cell")
  3.  
  4. local Text = Element:new {
  5.     __name = "Text",
  6.     text = "",
  7.     text_color = colors.white,
  8.  
  9.     text_lines = {""},
  10.     scroll_offset = 0,
  11.     auto_scroll = false,
  12. }
  13.  
  14. function Text:new(o)
  15.     o = o or {}
  16.     o = Element:new(o)
  17.  
  18.     setmetatable(o, self)
  19.     self.__index = self
  20.  
  21.     o:updateTextBuffer()
  22.  
  23.     return o
  24. end
  25.  
  26. -- write text to an intermediate text buffer
  27. -- breaking it up into lines to be drawn onto the cell buffer
  28. function Text:updateTextBuffer()
  29.     self.text_lines = {}
  30.     local sub_text = self.text
  31.  
  32.     while #sub_text > 0 do
  33.         local new_line_index = sub_text:find("\n")
  34.         if not new_line_index or new_line_index > self.width then
  35.             table.insert(self.text_lines, sub_text:sub(1, self.width))
  36.             sub_text = sub_text:sub(self.width + 1)
  37.         else
  38.             table.insert(self.text_lines, sub_text:sub(1, new_line_index))
  39.             sub_text = sub_text:sub(new_line_index + 1)
  40.         end
  41.     end
  42.  
  43.     if self.auto_scroll then
  44.         self.scroll_offset = math.max(0, #self.text_lines - self.height)
  45.     end
  46. end
  47.  
  48. function Text:setText(new_text)
  49.     self.text = new_text
  50.     self:updateTextBuffer()
  51. end
  52.  
  53. function Text:getText()
  54.     return self.text
  55. end
  56.  
  57. function Text:write(to_write)
  58.     self.text = self.text .. to_write
  59.     self:updateTextBuffer()
  60. end
  61.  
  62. function Text:updateBuffer()
  63.     local default_cell = Cell:new {
  64.         bg_color = self.bg_color,
  65.         fg_color = self.text_color,
  66.     }
  67.     self.buffer:fill(default_cell)
  68.  
  69.     -- self:updateTextBuffer()
  70.     for x = 0, self.width - 1 do
  71.         for y = 0, self.height - 1 do
  72.             local line_index = y + self.scroll_offset + 1
  73.             if line_index > 0 and line_index <= #self.text_lines then
  74.                 local character = self.text_lines[line_index]:sub(x + 1, x + 1)
  75.                 if #character ~= 0 then
  76.                     self.buffer.cells[x][y].character = character
  77.                 end
  78.             end
  79.         end
  80.     end
  81. end
  82.  
  83. return Text
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement