1
0
mirror of https://github.com/20kdc/OC-KittenOS.git synced 2024-11-27 12:58:05 +11:00
OC-KittenOS/code/libs/lineedit.lua

78 lines
2.4 KiB
Lua
Raw Permalink Normal View History

-- Copyright (C) 2018-2021 by KittenOS NEO contributors
--
-- Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
-- THIS SOFTWARE.
2020-03-30 22:08:12 +11:00
return {
-- note: everything must already be unicode.safeTextFormat'd
2020-03-31 00:36:33 +11:00
draw = function (sW, line, cursorX, rX)
2020-03-30 22:08:12 +11:00
-- if no camera, provide a default
2020-03-31 00:36:33 +11:00
rX = rX or math.max(1, (cursorX or 1) - math.floor(sW * 2 / 3))
2020-03-30 22:08:12 +11:00
-- transform into area-relative
local tl = unicode.sub(line, rX, rX + sW - 1)
-- inject cursor
2020-03-31 00:36:33 +11:00
if cursorX then
2020-03-30 22:08:12 +11:00
cursorX = (cursorX - rX) + 1
if cursorX >= 1 then
if cursorX <= sW then
tl = unicode.sub(tl, 1, cursorX - 1) .. "_" .. unicode.sub(tl, cursorX + 1)
end
end
end
return tl .. (" "):rep(sW - unicode.len(tl))
end,
clamp = function (tl, cursorX)
tl = unicode.len(tl)
if tl < cursorX - 1 then
return tl + 1
end
return cursorX
end,
-- returns line, cursorX, special
-- return values may be nil if irrelevant
key = function (ks, kc, line, cursorX)
local cS = unicode.sub(line, 1, cursorX - 1)
local cE = unicode.sub(line, cursorX)
local ll = unicode.len(line)
2020-03-30 22:08:12 +11:00
if kc == 203 then -- navi <
if cursorX > 1 then
return nil, cursorX - 1
else
-- cline underflow
return nil, nil, "l<"
end
elseif kc == 205 then -- navi >
if cursorX > ll then
-- cline overflow
return nil, nil, "l>"
end
return nil, cursorX + 1
elseif kc == 199 then -- home
return nil, 1
elseif kc == 207 then -- end
return nil, unicode.len(line) + 1
elseif ks == "\8" then -- del
2020-03-30 22:08:12 +11:00
if cursorX == 1 then
2020-03-31 00:36:33 +11:00
-- weld prev
return nil, nil, "w<"
2020-03-30 22:08:12 +11:00
else
return unicode.sub(cS, 1, unicode.len(cS) - 1) .. cE, cursorX - 1
2020-03-30 22:08:12 +11:00
end
elseif kc == 211 then -- del
if cursorX > ll then
return nil, nil, "w>"
end
return cS .. unicode.sub(cE, 2)
2020-03-30 22:08:12 +11:00
elseif ks then -- standard letters
if ks == "\r" then
-- new line
return nil, nil, "nl"
end
return cS .. ks .. cE, cursorX + unicode.len(ks)
end
-- :(
end
}