From 62b31ac719e7631b4f6b2a2d22f1b8997118f525 Mon Sep 17 00:00:00 2001 From: Matthias Richter Date: Sat, 16 Jan 2016 02:16:52 +0100 Subject: [PATCH] Move computation of text offset from theme to input widget --- input.lua | 25 ++++++++++++++++++++++++- theme.lua | 26 ++------------------------ 2 files changed, 26 insertions(+), 25 deletions(-) diff --git a/input.lua b/input.lua index cc8b921..ff2d842 100644 --- a/input.lua +++ b/input.lua @@ -14,7 +14,8 @@ return function(core, input, ...) opt.id = opt.id or input opt.font = opt.font or love.graphics.getFont() - w = w or opt.font:getWidth(text) + 4 + local text_width = opt.font:getWidth(input.text) + w = w or text_width + 4 h = h or opt.font:getHeight() + 4 input.text = input.text or "" @@ -63,6 +64,28 @@ return function(core, input, ...) -- TODO end + -- get size of text and cursor position + opt.cursor_pos = 0 + if input.cursor > 1 then + local s = input.text:sub(0, utf8.offset(input.text, input.cursor)-1) + opt.cursor_pos = opt.font:getWidth(s) + end + + -- compute drawing offset + input.drawoffset = input.drawoffset or 0 + if opt.cursor_pos - input.drawoffset < 0 then + -- cursor left of input box + input.drawoffset = opt.cursor_pos + end + if opt.cursor_pos - input.drawoffset > w then + -- cursor right of input box + input.drawoffset = opt.cursor_pos - w + end + if text_width - input.drawoffset < w and text_width > w then + -- text bigger than input box, but does not fill it + input.drawoffset = text_width - w + end + core:registerDraw(core.theme.Input, input, opt, x,y,w,h) return { diff --git a/theme.lua b/theme.lua index 5cf46c3..4930002 100644 --- a/theme.lua +++ b/theme.lua @@ -104,29 +104,7 @@ function theme.Input(input, opt, x,y,w,h) x = x + 3 w = w - 6 - -- get size of text and cursor position local th = opt.font:getHeight() - local tw = opt.font:getWidth(input.text) - local cursor_pos = 0 - if input.cursor > 1 then - local s = input.text:sub(0, utf8.offset(input.text, input.cursor)-1) - cursor_pos = opt.font:getWidth(s) - end - - -- compute drawing offset - input.drawoffset = input.drawoffset or 0 - if cursor_pos - input.drawoffset < 0 then - -- cursor left of input box - input.drawoffset = cursor_pos - end - if cursor_pos - input.drawoffset > w then - -- cursor right of input box - input.drawoffset = cursor_pos - w - end - if tw - input.drawoffset < w and tw > w then - -- text bigger than input box, but does not fill it - input.drawoffset = tw - w - end -- set scissors local sx, sy, sw, sh = love.graphics.getScissor() @@ -142,8 +120,8 @@ function theme.Input(input, opt, x,y,w,h) if opt.hasKeyboardFocus and (love.timer.getTime() % 1) > .5 then love.graphics.setLineWidth(1) love.graphics.setLineStyle('rough') - love.graphics.line(x + cursor_pos, y + (h-th)/2, - x + cursor_pos, y + (h+th)/2) + love.graphics.line(x + opt.cursor_pos, y + (h-th)/2, + x + opt.cursor_pos, y + (h+th)/2) end -- reset scissor