t8rt0t

edit_nbt.lua

Jul 23rd, 2024 (edited)
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 29.13 KB | None | 0 0
  1. -- SPDX-FileCopyrightText: 2017 Daniel Ratcliffe
  2. --
  3. -- SPDX-License-Identifier: LicenseRef-CCPL
  4. shell.setCompletionFunction(shell.getRunningProgram(),shell.getCompletionInfo()["rom/programs/edit.lua"].fnComplete)
  5. -- Get file to edit
  6. local tArgs = { ... }
  7. if #tArgs == 0 then
  8.     local programName = arg[0] or fs.getName(shell.getRunningProgram())
  9.     print("Usage: " .. programName .. " <path>")
  10.     return
  11. end
  12.  
  13. local nbt = require("nbt")
  14. local zip = require("LibDeflate")
  15.  
  16. -- Error checking
  17. local sPath = shell.resolve(tArgs[1])
  18. local bReadOnly = fs.isReadOnly(sPath)
  19. if fs.exists(sPath) and fs.isDir(sPath) then
  20.     print("Cannot edit a directory.")
  21.     return
  22. end
  23.  
  24. -- Create .nbt files by default
  25. if not fs.exists(sPath) and not string.find(sPath, "%.") then
  26.     local sExtension = settings.get("edit.nbt_extension")
  27.     if sExtension ~= "" and type(sExtension) == "string" then
  28.         sPath = sPath .. "." .. sExtension
  29.     end
  30. end
  31.  
  32. local x, y = 1, 1
  33. local w, h = term.getSize()
  34. local scrollX, scrollY = 0, 0
  35.  
  36. local tLines = {}
  37. local bRunning = true
  38.  
  39. -- Colours
  40. local highlightColour, keywordColour, commentColour, textColour, bgColour, stringColour, errorColour
  41. if term.isColour() then
  42.     bgColour = colours.black
  43.     textColour = colours.white
  44.     highlightColour = colors.yellow
  45.  
  46.     keyColor = colors.lightGray
  47.     stringColor = colors.gray
  48.     byteColor = colors.pink
  49.     byteArrColor = colors.purple
  50.     shortColor = colors.cyan
  51.     intColor = colors.lightBlue
  52.     intArrColor = colors.blue
  53.     longColor = colors.lime
  54.     longArrColor = colors.green
  55.     floatColor = colors.yellow
  56.     doubleColor = colors.orange
  57.    
  58.     --highlightColour = colours.yellow
  59.     --keywordColour = colours.yellow
  60.     --commentColour = colours.green
  61.     --stringColour = colours.red
  62.     errorColour = colours.red
  63. else
  64.     bgColour = colours.black
  65.     textColour = colours.white
  66.     highlightColour = colors.white
  67.  
  68.     keyColor = colors.white
  69.     stringColor = colors.gray
  70.     byteColor = colors.lightGray
  71.     byteArrColor = colors.lightGray
  72.     shortColor = colors.lightGray
  73.     intColor = colors.lightGray
  74.     intArrColor = colors.lightGray
  75.     longColor = colors.lightGray
  76.     longArrColor = colors.lightGray
  77.     floatColor = colors.lightGray
  78.     doubleColor = colors.lightGray
  79.     errorColour = colours.white
  80. end
  81.  
  82. local runHandler = [[multishell.setTitle(multishell.getCurrent(), %q)
  83. local current = term.current()
  84. local contents, name = %q, %q
  85. local fn, err = load(contents, name, nil, _ENV)
  86. if fn then
  87.     local exception = require "cc.internal.exception"
  88.     local ok, err, co = exception.try(fn, ...)
  89.  
  90.     term.redirect(current)
  91.     term.setTextColor(term.isColour() and colours.yellow or colours.white)
  92.     term.setBackgroundColor(colours.black)
  93.     term.setCursorBlink(false)
  94.  
  95.     if not ok then
  96.         printError(err)
  97.         exception.report(err, co, { [name] = contents })
  98.     end
  99. else
  100.     local parser = require "cc.internal.syntax"
  101.     if parser.parse_program(contents) then printError(err) end
  102. end
  103.  
  104. local message = "Press any key to continue."
  105. if ok then message = "Program finished. " .. message end
  106. local _, y = term.getCursorPos()
  107. local w, h = term.getSize()
  108. local wrapped = require("cc.strings").wrap(message, w)
  109.  
  110. local start_y = h - #wrapped + 1
  111. if y >= start_y then term.scroll(y - start_y + 1) end
  112. for i = 1, #wrapped do
  113.     term.setCursorPos(1, start_y + i - 1)
  114.     term.write(wrapped[i])
  115. end
  116. os.pullEvent('key')
  117. require "cc.internal.event".discard_char()
  118. ]]
  119.  
  120. -- Menus
  121. local bMenu = false
  122. local nMenuItem = 1
  123. local tMenuItems = {}
  124. if not bReadOnly and shell.openTab then
  125.     table.insert(tMenuItems, "Save")
  126. end
  127. -- if shell.openTab then
  128. --     table.insert(tMenuItems, "Run")
  129. -- end
  130. -- if peripheral.find("printer") then
  131. --     table.insert(tMenuItems, "Print")
  132. -- end
  133. table.insert(tMenuItems, "Exit")
  134.  
  135. local status_ok, status_text
  136. local function set_status(text, ok)
  137.     status_ok = ok ~= false
  138.     status_text = text
  139. end
  140.  
  141. if bReadOnly then
  142.     set_status("File is read only", false)
  143. elseif fs.getFreeSpace(sPath) < 1024 then
  144.     set_status("Disk is low on space", false)
  145. else
  146.     local message
  147.     if term.isColour() then
  148.         message = "Press Ctrl or click here to access menu"
  149.     else
  150.         message = "Press Ctrl to access menu"
  151.     end
  152.  
  153.     if #message > w - 5 then
  154.         message = "Press Ctrl for menu"
  155.     end
  156.  
  157.     set_status(message)
  158. end
  159.  
  160. local function load(_sPath)
  161.     tLines = {}
  162.     if fs.exists(_sPath) then
  163.         local file = fs.open(_sPath, "r")
  164.         local data = file.readAll()
  165.         file.close()
  166.         local uncompressed_data,errCode = zip:DecompressGzip(data)
  167.         if uncompressed_data then
  168.             local _,compoundTag = pcall(nbt.frombinary,uncompressed_data)
  169.             if _ and compoundTag then
  170.                 local _,serialized = pcall(nbt.serialize,compoundTag)
  171.                 if _ and serialized then
  172.                     for sLine in serialized:gmatch('[^\n]+') do
  173.                         table.insert(tLines,sLine)
  174.                     end
  175.                     return
  176.                 else
  177.                     set_status("Error serializing nbt "..tostring(serialized),false)
  178.                 end
  179.             else
  180.                 set_status("Error converting nbt from binary "..tostring(compoundTag),false)
  181.             end
  182.         else
  183.             set_status("Error unzipping data, error code ["..tostring(errCode).."]",false)
  184.         end
  185.     end
  186.     if #tLines == 0 then
  187.         tLines = {"{","}"}
  188.     end
  189. end
  190.  
  191. local function save(_sPath, fWrite)
  192.     -- Create intervening folder
  193.     local sDir = _sPath:sub(1, _sPath:len() - fs.getName(_sPath):len())
  194.     if not fs.exists(sDir) then
  195.         fs.makeDir(sDir)
  196.     end
  197.  
  198.     -- Save
  199.     local file, fileerr
  200.     local function innerSave()
  201.         file, fileerr = fs.open(_sPath, "w")
  202.         if file then
  203.             if file then
  204.                 fWrite(file)
  205.             end
  206.         else
  207.             error("Failed to open " .. _sPath)
  208.         end
  209.     end
  210.  
  211.     local ok, err = pcall(innerSave)
  212.     if file then
  213.         file.close()
  214.     end
  215.     return ok, err, fileerr
  216. end
  217.  
  218. local function tryWrite(sLine, regex, colour)
  219.     local match = string.match(sLine, regex)
  220.     if match then
  221.         if type(colour) == "number" then
  222.             term.setTextColour(colour)
  223.         else
  224.             term.setTextColour(colour(match,sLine))
  225.         end
  226.         term.write(match)
  227.         term.setTextColour(textColour)
  228.         return string.sub(sLine, #match + 1)
  229.     end
  230.     return nil
  231. end
  232.  
  233. local function writeHighlighted(sLine)
  234.     while #sLine > 0 do
  235.         sLine =
  236.             tryWrite(sLine, "^\"\"", function(match,str)
  237.                 str = str:sub(#match + 1)
  238.                 if str:match("^%s*:") then return keyColor else return stringColor end
  239.             end
  240.             ) or
  241.             tryWrite(sLine, "^\".-[^\\]\"", function(match,str)
  242.                 str = str:sub(#match + 1)
  243.                 if str:match("^%s*:") then return keyColor else return stringColor end
  244.             end) or
  245.             tryWrite(sLine, "^''", function(match,str)
  246.                 str = str:sub(#match + 1)
  247.                 if str:match("^%s*:") then return keyColor else return stringColor end
  248.             end) or
  249.             tryWrite(sLine, "^'.-[^\\]'", function(match,str)
  250.                 str = str:sub(#match + 1)
  251.                 if str:match("^%s*:") then return keyColor else return stringColor end
  252.             end) or
  253.        
  254.             -- tryWrite(sLine, "^\"\"", stringColor) or
  255.             -- tryWrite(sLine, "^\".-[^\\]\"", stringColor) or
  256.             -- tryWrite(sLine, "^''", stringColor) or
  257.             -- tryWrite(sLine, "^'.-[^\\]'", stringColor) or
  258.  
  259.             tryWrite(sLine,"^true",byteColor) or
  260.             tryWrite(sLine,"^false",byteColor) or
  261.             tryWrite(sLine,"^I;",intArrColor) or
  262.             tryWrite(sLine,"^B;",byteArrColor) or
  263.             tryWrite(sLine,"^L;",longArrColor) or
  264.             tryWrite(sLine, "^%a[%w_]*", function(match,str)
  265.                 local temp = str:sub(#match + 1)
  266.                 if temp:match("^%s*:") then return keyColor elseif str == "true" or str == "false" then return byteColor else return textColour end
  267.             end) or
  268.             tryWrite(sLine,"^%-?%d+%.%d*[fF]",floatColor) or
  269.             tryWrite(sLine,"^%-?%d+%.%d*",doubleColor) or
  270.             tryWrite(sLine,"^%-?%d+[bB]",byteColor) or
  271.             tryWrite(sLine,"^%-?%d+[sS]",shortColor) or
  272.             tryWrite(sLine,"^%-?%d+[lL]",longColor) or
  273.             tryWrite(sLine,"^%-?%d+",intColor) or
  274.            
  275.        
  276.             -- tryWrite(sLine, "^%-%-%[%[.-%]%]", commentColour) or
  277.             -- tryWrite(sLine, "^%-%-.*", commentColour) or
  278.             -- tryWrite(sLine, "^\"\"", stringColour) or
  279.             -- tryWrite(sLine, "^\".-[^\\]\"", stringColour) or
  280.             -- tryWrite(sLine, "^\'\'", stringColour) or
  281.             -- tryWrite(sLine, "^\'.-[^\\]\'", stringColour) or
  282.             -- tryWrite(sLine, "^%[%[.-%]%]", stringColour) or
  283.             -- tryWrite(sLine, "^[%w_]+", function(match)
  284.             --     if tKeywords[match] then
  285.             --         return keywordColour
  286.             --     end
  287.             --     return textColour
  288.             -- end) or
  289.             tryWrite(sLine, "^.", textColour)
  290.     end
  291. end
  292.  
  293. -- local tCompletions
  294. -- local nCompletion
  295.  
  296. -- local tCompleteEnv = _ENV
  297. -- local function complete(sLine)
  298. --     if settings.get("edit.autocomplete") then
  299. --         local nStartPos = string.find(sLine, "[a-zA-Z0-9_%.:]+$")
  300. --         if nStartPos then
  301. --             sLine = string.sub(sLine, nStartPos)
  302. --         end
  303. --         if #sLine > 0 then
  304. --             return textutils.complete(sLine, tCompleteEnv)
  305. --         end
  306. --     end
  307. --     return nil
  308. -- end
  309.  
  310. -- local function recomplete()
  311. --     local sLine = tLines[y]
  312. --     if not bMenu and not bReadOnly and x == #sLine + 1 then
  313. --         tCompletions = complete(sLine)
  314. --         if tCompletions and #tCompletions > 0 then
  315. --             nCompletion = 1
  316. --         else
  317. --             nCompletion = nil
  318. --         end
  319. --     else
  320. --         tCompletions = nil
  321. --         nCompletion = nil
  322. --     end
  323. -- end
  324.  
  325. -- local function writeCompletion(sLine)
  326. --     if nCompletion then
  327. --         local sCompletion = tCompletions[nCompletion]
  328. --         term.setTextColor(colours.white)
  329. --         term.setBackgroundColor(colours.grey)
  330. --         term.write(sCompletion)
  331. --         term.setTextColor(textColour)
  332. --         term.setBackgroundColor(bgColour)
  333. --     end
  334. -- end
  335.  
  336. local function redrawText()
  337.     local cursorX, cursorY = x, y
  338.     for y = 1, h - 1 do
  339.         term.setCursorPos(1 - scrollX, y)
  340.         term.clearLine()
  341.  
  342.         local sLine = tLines[y + scrollY]
  343.         if sLine ~= nil then
  344.             writeHighlighted(sLine)
  345.             -- if cursorY == y and cursorX == #sLine + 1 then
  346.             --     writeCompletion()
  347.             -- end
  348.         end
  349.     end
  350.     term.setCursorPos(x - scrollX, y - scrollY)
  351. end
  352.  
  353. local function redrawLine(_nY)
  354.     local sLine = tLines[_nY]
  355.     if sLine then
  356.         term.setCursorPos(1 - scrollX, _nY - scrollY)
  357.         term.clearLine()
  358.         writeHighlighted(sLine)
  359.         -- if _nY == y and x == #sLine + 1 then
  360.         --     writeCompletion()
  361.         -- end
  362.         term.setCursorPos(x - scrollX, _nY - scrollY)
  363.     end
  364. end
  365.  
  366. local function redrawMenu()
  367.     -- Clear line
  368.     term.setCursorPos(1, h)
  369.     term.clearLine()
  370.  
  371.     -- Draw line numbers
  372.     term.setCursorPos(w - #("Ln " .. y) + 1, h)
  373.     term.setTextColour(highlightColour)
  374.     term.write("Ln ")
  375.     term.setTextColour(textColour)
  376.     term.write(y)
  377.  
  378.     term.setCursorPos(1, h)
  379.     if bMenu then
  380.         -- Draw menu
  381.         term.setTextColour(textColour)
  382.         for nItem, sItem in pairs(tMenuItems) do
  383.             if nItem == nMenuItem then
  384.                 term.setTextColour(highlightColour)
  385.                 term.write("[")
  386.                 term.setTextColour(textColour)
  387.                 term.write(sItem)
  388.                 term.setTextColour(highlightColour)
  389.                 term.write("]")
  390.                 term.setTextColour(textColour)
  391.             else
  392.                 term.write(" " .. sItem .. " ")
  393.             end
  394.         end
  395.     else
  396.         -- Draw status
  397.         term.setTextColour(status_ok and highlightColour or errorColour)
  398.         term.write(status_text)
  399.         term.setTextColour(textColour)
  400.     end
  401.  
  402.     -- Reset cursor
  403.     term.setCursorPos(x - scrollX, y - scrollY)
  404. end
  405.  
  406. local tMenuFuncs = {
  407.     Save = function()
  408.         if bReadOnly then
  409.             set_status("Access denied", false)
  410.         else
  411.             local ok, _, fileerr  = save(sPath, function(file)
  412.                 local str = ""
  413.                 for k,v in ipairs(tLines) do
  414.                     str = str .. v .. "\n"
  415.                 end
  416.                 local tag = nbt.fromstring(str)
  417.                 local binarystr = nbt.tobinary(tag)
  418.                 local zippedstr = assert(zip:CompressGzip(binarystr),"Could not zip file!")
  419.                 file.write(zippedstr)
  420.             end)
  421.             if ok then
  422.                 set_status("Saved to " .. sPath)
  423.             else
  424.                 if fileerr then
  425.                     set_status("Error saving: " .. fileerr, false)
  426.                 else
  427.                     set_status("Error saving to " .. sPath, false)
  428.                 end
  429.             end
  430.         end
  431.         redrawMenu()
  432.     end,
  433.     Print = function()
  434.         local printer = peripheral.find("printer")
  435.         if not printer then
  436.             set_status("No printer attached", false)
  437.             return
  438.         end
  439.  
  440.         local nPage = 0
  441.         local sName = fs.getName(sPath)
  442.         if printer.getInkLevel() < 1 then
  443.             set_status("Printer out of ink", false)
  444.             return
  445.         elseif printer.getPaperLevel() < 1 then
  446.             set_status("Printer out of paper", false)
  447.             return
  448.         end
  449.  
  450.         local screenTerminal = term.current()
  451.         local printerTerminal = {
  452.             getCursorPos = printer.getCursorPos,
  453.             setCursorPos = printer.setCursorPos,
  454.             getSize = printer.getPageSize,
  455.             write = printer.write,
  456.         }
  457.         printerTerminal.scroll = function()
  458.             if nPage == 1 then
  459.                 printer.setPageTitle(sName .. " (page " .. nPage .. ")")
  460.             end
  461.  
  462.             while not printer.newPage() do
  463.                 if printer.getInkLevel() < 1 then
  464.                     set_status("Printer out of ink, please refill", false)
  465.                 elseif printer.getPaperLevel() < 1 then
  466.                     set_status("Printer out of paper, please refill", false)
  467.                 else
  468.                     set_status("Printer output tray full, please empty", false)
  469.                 end
  470.  
  471.                 term.redirect(screenTerminal)
  472.                 redrawMenu()
  473.                 term.redirect(printerTerminal)
  474.  
  475.                 sleep(0.5)
  476.             end
  477.  
  478.             nPage = nPage + 1
  479.             if nPage == 1 then
  480.                 printer.setPageTitle(sName)
  481.             else
  482.                 printer.setPageTitle(sName .. " (page " .. nPage .. ")")
  483.             end
  484.         end
  485.  
  486.         bMenu = false
  487.         term.redirect(printerTerminal)
  488.         local ok, error = pcall(function()
  489.             term.scroll()
  490.             for _, sLine in ipairs(tLines) do
  491.                 print(sLine)
  492.             end
  493.         end)
  494.         term.redirect(screenTerminal)
  495.         if not ok then
  496.             print(error)
  497.         end
  498.  
  499.         while not printer.endPage() do
  500.             set_status("Printer output tray full, please empty")
  501.             redrawMenu()
  502.             sleep(0.5)
  503.         end
  504.         bMenu = true
  505.  
  506.         if nPage > 1 then
  507.             set_status("Printed " .. nPage .. " Pages")
  508.         else
  509.             set_status("Printed 1 Page")
  510.         end
  511.         redrawMenu()
  512.     end,
  513.     Exit = function()
  514.         bRunning = false
  515.     end,
  516.     Run = function()
  517.         local sTitle = fs.getName(sPath)
  518.         if sTitle:sub(-4) == ".lua" then
  519.             sTitle = sTitle:sub(1, -5)
  520.         end
  521.         local sTempPath = bReadOnly and ".temp." .. sTitle or fs.combine(fs.getDir(sPath), ".temp." .. sTitle)
  522.         if fs.exists(sTempPath) then
  523.             set_status("Error saving to " .. sTempPath, false)
  524.             return
  525.         end
  526.         local ok = save(sTempPath, function(file)
  527.             file.write(runHandler:format(sTitle, table.concat(tLines, "\n"), "@/" .. sPath))
  528.         end)
  529.         if ok then
  530.             local nTask = shell.openTab("/" .. sTempPath)
  531.             if nTask then
  532.                 shell.switchTab(nTask)
  533.             else
  534.                 set_status("Error starting Task", false)
  535.             end
  536.             fs.delete(sTempPath)
  537.         else
  538.             set_status("Error saving to " .. sTempPath, false)
  539.         end
  540.         redrawMenu()
  541.     end,
  542. }
  543.  
  544. local function doMenuItem(_n)
  545.     tMenuFuncs[tMenuItems[_n]]()
  546.     if bMenu then
  547.         bMenu = false
  548.         term.setCursorBlink(true)
  549.     end
  550.     redrawMenu()
  551. end
  552.  
  553. local function setCursor(newX, newY)
  554.     local _, oldY = x, y
  555.     x, y = newX, newY
  556.     local screenX = x - scrollX
  557.     local screenY = y - scrollY
  558.  
  559.     local bRedraw = false
  560.     if screenX < 1 then
  561.         scrollX = x - 1
  562.         screenX = 1
  563.         bRedraw = true
  564.     elseif screenX > w then
  565.         scrollX = x - w
  566.         screenX = w
  567.         bRedraw = true
  568.     end
  569.  
  570.     if screenY < 1 then
  571.         scrollY = y - 1
  572.         screenY = 1
  573.         bRedraw = true
  574.     elseif screenY > h - 1 then
  575.         scrollY = y - (h - 1)
  576.         screenY = h - 1
  577.         bRedraw = true
  578.     end
  579.  
  580.     -- recomplete()
  581.     if bRedraw then
  582.         redrawText()
  583.     elseif y ~= oldY then
  584.         redrawLine(oldY)
  585.         redrawLine(y)
  586.     else
  587.         redrawLine(y)
  588.     end
  589.     term.setCursorPos(screenX, screenY)
  590.  
  591.     redrawMenu()
  592. end
  593.  
  594. -- Actual program functionality begins
  595. load(sPath)
  596.  
  597. term.setBackgroundColour(bgColour)
  598. term.clear()
  599. term.setCursorPos(x, y)
  600. term.setCursorBlink(true)
  601.  
  602. -- recomplete()
  603. redrawText()
  604. redrawMenu()
  605.  
  606. -- local function acceptCompletion()
  607. --     if nCompletion then
  608. --         -- Append the completion
  609. --         local sCompletion = tCompletions[nCompletion]
  610. --         tLines[y] = tLines[y] .. sCompletion
  611. --         setCursor(x + #sCompletion , y)
  612. --     end
  613. --end
  614.  
  615. -- Handle input
  616. while bRunning do
  617.     local sEvent, param, param2, param3 = os.pullEvent()
  618.     if sEvent == "key" then
  619.         if param == keys.up then
  620.             -- Up
  621.             if not bMenu then
  622.                 if false and nCompletion then
  623.                     -- Cycle completions
  624.                     -- nCompletion = nCompletion - 1
  625.                     -- if nCompletion < 1 then
  626.                     --     nCompletion = #tCompletions
  627.                     -- end
  628.                     -- redrawLine(y)
  629.  
  630.                 elseif y > 1 then
  631.                     -- Move cursor up
  632.                     setCursor(
  633.                         math.min(x, #tLines[y - 1] + 1),
  634.                         y - 1
  635.                     )
  636.                 end
  637.             end
  638.  
  639.         elseif param == keys.down then
  640.             -- Down
  641.             if not bMenu then
  642.                 -- Move cursor down
  643.                 if false and nCompletion then
  644.                     -- -- Cycle completions
  645.                     -- nCompletion = nCompletion + 1
  646.                     -- if nCompletion > #tCompletions then
  647.                     --     nCompletion = 1
  648.                     -- end
  649.                     -- redrawLine(y)
  650.  
  651.                 elseif y < #tLines then
  652.                     -- Move cursor down
  653.                     setCursor(
  654.                         math.min(x, #tLines[y + 1] + 1),
  655.                         y + 1
  656.                     )
  657.                 end
  658.             end
  659.  
  660.         elseif param == keys.tab then
  661.             -- Tab
  662.             if not bMenu and not bReadOnly then
  663.                 if false and nCompletion and x == #tLines[y] + 1 then
  664.                     -- Accept autocomplete
  665.                     -- acceptCompletion()
  666.                 else
  667.                     -- Indent line
  668.                     local sLine = tLines[y]
  669.                     tLines[y] = string.sub(sLine, 1, x - 1) .. "    " .. string.sub(sLine, x)
  670.                     setCursor(x + 4, y)
  671.                 end
  672.             end
  673.  
  674.         elseif param == keys.pageUp then
  675.             -- Page Up
  676.             if not bMenu then
  677.                 -- Move up a page
  678.                 local newY
  679.                 if y - (h - 1) >= 1 then
  680.                     newY = y - (h - 1)
  681.                 else
  682.                     newY = 1
  683.                 end
  684.                 setCursor(
  685.                     math.min(x, #tLines[newY] + 1),
  686.                     newY
  687.                 )
  688.             end
  689.  
  690.         elseif param == keys.pageDown then
  691.             -- Page Down
  692.             if not bMenu then
  693.                 -- Move down a page
  694.                 local newY
  695.                 if y + (h - 1) <= #tLines then
  696.                     newY = y + (h - 1)
  697.                 else
  698.                     newY = #tLines
  699.                 end
  700.                 local newX = math.min(x, #tLines[newY] + 1)
  701.                 setCursor(newX, newY)
  702.             end
  703.  
  704.         elseif param == keys.home then
  705.             -- Home
  706.             if not bMenu then
  707.                 -- Move cursor to the beginning
  708.                 if x > 1 then
  709.                     setCursor(1, y)
  710.                 end
  711.             end
  712.  
  713.         elseif param == keys["end"] then
  714.             -- End
  715.             if not bMenu then
  716.                 -- Move cursor to the end
  717.                 local nLimit = #tLines[y] + 1
  718.                 if x < nLimit then
  719.                     setCursor(nLimit, y)
  720.                 end
  721.             end
  722.  
  723.         elseif param == keys.left then
  724.             -- Left
  725.             if not bMenu then
  726.                 if x > 1 then
  727.                     -- Move cursor left
  728.                     setCursor(x - 1, y)
  729.                 elseif x == 1 and y > 1 then
  730.                     setCursor(#tLines[y - 1] + 1, y - 1)
  731.                 end
  732.             else
  733.                 -- Move menu left
  734.                 nMenuItem = nMenuItem - 1
  735.                 if nMenuItem < 1 then
  736.                     nMenuItem = #tMenuItems
  737.                 end
  738.                 redrawMenu()
  739.             end
  740.  
  741.         elseif param == keys.right then
  742.             -- Right
  743.             if not bMenu then
  744.                 local nLimit = #tLines[y] + 1
  745.                 if x < nLimit then
  746.                     -- Move cursor right
  747.                     setCursor(x + 1, y)
  748.                 elseif false and nCompletion and x == #tLines[y] + 1 then
  749.                     -- Accept autocomplete
  750.                     -- acceptCompletion()
  751.                 elseif x == nLimit and y < #tLines then
  752.                     -- Go to next line
  753.                     setCursor(1, y + 1)
  754.                 end
  755.             else
  756.                 -- Move menu right
  757.                 nMenuItem = nMenuItem + 1
  758.                 if nMenuItem > #tMenuItems then
  759.                     nMenuItem = 1
  760.                 end
  761.                 redrawMenu()
  762.             end
  763.  
  764.         elseif param == keys.delete then
  765.             -- Delete
  766.             if not bMenu and not bReadOnly then
  767.                 local nLimit = #tLines[y] + 1
  768.                 if x < nLimit then
  769.                     local sLine = tLines[y]
  770.                     tLines[y] = string.sub(sLine, 1, x - 1) .. string.sub(sLine, x + 1)
  771.                     -- recomplete()
  772.                     redrawLine(y)
  773.                 elseif y < #tLines then
  774.                     tLines[y] = tLines[y] .. tLines[y + 1]
  775.                     table.remove(tLines, y + 1)
  776.                     -- recomplete()
  777.                     redrawText()
  778.                 end
  779.             end
  780.  
  781.         elseif param == keys.backspace then
  782.             -- Backspace
  783.             if not bMenu and not bReadOnly then
  784.                 if x > 1 then
  785.                     -- Remove character
  786.                     local sLine = tLines[y]
  787.                     if x > 4 and string.sub(sLine, x - 4, x - 1) == "    " and not string.sub(sLine, 1, x - 1):find("%S") then
  788.                         tLines[y] = string.sub(sLine, 1, x - 5) .. string.sub(sLine, x)
  789.                         setCursor(x - 4, y)
  790.                     else
  791.                         tLines[y] = string.sub(sLine, 1, x - 2) .. string.sub(sLine, x)
  792.                         setCursor(x - 1, y)
  793.                     end
  794.                 elseif y > 1 then
  795.                     -- Remove newline
  796.                     local sPrevLen = #tLines[y - 1]
  797.                     tLines[y - 1] = tLines[y - 1] .. tLines[y]
  798.                     table.remove(tLines, y)
  799.                     setCursor(sPrevLen + 1, y - 1)
  800.                     redrawText()
  801.                 end
  802.             end
  803.  
  804.         elseif param == keys.enter or param == keys.numPadEnter then
  805.             -- Enter/Numpad Enter
  806.             if not bMenu and not bReadOnly then
  807.                 -- Newline
  808.                 local sLine = tLines[y]
  809.                 local _, spaces = string.find(sLine, "^[ ]+")
  810.                 if not spaces then
  811.                     spaces = 0
  812.                 end
  813.                 tLines[y] = string.sub(sLine, 1, x - 1)
  814.                 table.insert(tLines, y + 1, string.rep(' ', spaces) .. string.sub(sLine, x))
  815.                 setCursor(spaces + 1, y + 1)
  816.                 redrawText()
  817.  
  818.             elseif bMenu then
  819.                 -- Menu selection
  820.                 doMenuItem(nMenuItem)
  821.  
  822.             end
  823.  
  824.         elseif param == keys.leftCtrl or param == keys.rightCtrl then
  825.             -- Menu toggle
  826.             bMenu = not bMenu
  827.             if bMenu then
  828.                 term.setCursorBlink(false)
  829.             else
  830.                 term.setCursorBlink(true)
  831.             end
  832.             redrawMenu()
  833.         elseif param == keys.rightAlt then
  834.             if bMenu then
  835.                 bMenu = false
  836.                 term.setCursorBlink(true)
  837.                 redrawMenu()
  838.             end
  839.         end
  840.  
  841.     elseif sEvent == "char" then
  842.         if not bMenu and not bReadOnly then
  843.             -- Input text
  844.             local sLine = tLines[y]
  845.             tLines[y] = string.sub(sLine, 1, x - 1) .. param .. string.sub(sLine, x)
  846.             setCursor(x + 1, y)
  847.  
  848.         elseif bMenu then
  849.             -- Select menu items
  850.             for n, sMenuItem in ipairs(tMenuItems) do
  851.                 if string.lower(string.sub(sMenuItem, 1, 1)) == string.lower(param) then
  852.                     doMenuItem(n)
  853.                     break
  854.                 end
  855.             end
  856.         end
  857.  
  858.     elseif sEvent == "paste" then
  859.         if not bReadOnly then
  860.             -- Close menu if open
  861.             if bMenu then
  862.                 bMenu = false
  863.                 term.setCursorBlink(true)
  864.                 redrawMenu()
  865.             end
  866.             -- Input text
  867.             local sLine = tLines[y]
  868.             tLines[y] = string.sub(sLine, 1, x - 1) .. param .. string.sub(sLine, x)
  869.             setCursor(x + #param , y)
  870.         end
  871.  
  872.     elseif sEvent == "mouse_click" then
  873.         local cx, cy = param2, param3
  874.         if not bMenu then
  875.             if param == 1 then
  876.                 -- Left click
  877.                 if cy < h then
  878.                     local newY = math.min(math.max(scrollY + cy, 1), #tLines)
  879.                     local newX = math.min(math.max(scrollX + cx, 1), #tLines[newY] + 1)
  880.                     setCursor(newX, newY)
  881.                 else
  882.                     bMenu = true
  883.                     redrawMenu()
  884.                 end
  885.             end
  886.         else
  887.             if cy == h then
  888.                 local nMenuPosEnd = 1
  889.                 local nMenuPosStart = 1
  890.                 for n, sMenuItem in ipairs(tMenuItems) do
  891.                     nMenuPosEnd = nMenuPosEnd + #sMenuItem + 1
  892.                     if cx > nMenuPosStart and cx < nMenuPosEnd then
  893.                         doMenuItem(n)
  894.                     end
  895.                     nMenuPosEnd = nMenuPosEnd + 1
  896.                     nMenuPosStart = nMenuPosEnd
  897.                 end
  898.             else
  899.                 bMenu = false
  900.                 term.setCursorBlink(true)
  901.                 redrawMenu()
  902.             end
  903.         end
  904.  
  905.     elseif sEvent == "mouse_scroll" then
  906.         if not bMenu then
  907.             if param == -1 then
  908.                 -- Scroll up
  909.                 if scrollY > 0 then
  910.                     -- Move cursor up
  911.                     scrollY = scrollY - 1
  912.                     redrawText()
  913.                 end
  914.  
  915.             elseif param == 1 then
  916.                 -- Scroll down
  917.                 local nMaxScroll = #tLines - (h - 1)
  918.                 if scrollY < nMaxScroll then
  919.                     -- Move cursor down
  920.                     scrollY = scrollY + 1
  921.                     redrawText()
  922.                 end
  923.  
  924.             end
  925.         end
  926.  
  927.     elseif sEvent == "term_resize" then
  928.         w, h = term.getSize()
  929.         setCursor(x, y)
  930.         redrawMenu()
  931.         redrawText()
  932.  
  933.     end
  934. end
  935.  
  936. -- Cleanup
  937. term.clear()
  938. term.setCursorBlink(false)
  939. term.setCursorPos(1, 1)
Advertisement
Add Comment
Please, Sign In to add comment