filelist.lua 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. return function(BOXUI)
  2. local utils = BOXUI.utils
  3. local List = BOXUI.list
  4. local M = utils.newclass("filelist", List)
  5. local isAllowedFile = function(filename, allowedExts)
  6. if not allowedExts then return true end
  7. local ext = filename:match(".([^.]+)$")
  8. return ext and allowedExts[ext:lower()]
  9. end
  10. local itemComperator = function(item1, item2)
  11. local type1, type2 = item1.context.type, item2.context.type
  12. if type1 == type2 then return item1.text < item2.text end
  13. return type1 < type2
  14. end
  15. local createItemsFromDir = function(fl, path)
  16. local toplevel = fl.toplevel
  17. local exts = fl.extensions
  18. if not path or (toplevel and string.find(path, toplevel, 1, true) ~= 1) then
  19. path = toplevel or ""
  20. end
  21. local diritems = love.filesystem.getDirectoryItems(path)
  22. local listitems = {}
  23. local prefix = (path == "" and "" or path .. "/")
  24. local ctx
  25. local info, infotype, filepath
  26. for i, f in ipairs(diritems) do
  27. filepath = prefix .. f
  28. info = love.filesystem.getInfo(filepath)
  29. if info ~= nil then
  30. infotype = info.type
  31. ctx = {type = infotype, name = filepath}
  32. if infotype == "directory" then
  33. table.insert(listitems, {text = f, context = ctx, icon = fl.diricon})
  34. elseif infotype == "file" and isAllowedFile(f, exts) then
  35. table.insert(listitems, {text = f, context = ctx, icon = fl.fileicon})
  36. end
  37. end
  38. end
  39. table.sort(listitems, itemComperator)
  40. if path ~= "" and path ~= toplevel then
  41. ctx = {type = "directory", name = path:gsub("/?[^/]+$","")}
  42. table.insert(listitems, 1, {text = "..", context = ctx, icon = fl.diricon})
  43. end
  44. --table.insert(listitems, 1, {back = fl.headerBack, text = prefix})
  45. fl.title = (prefix == "" and "[ROOT]" or prefix)
  46. return listitems, path
  47. end
  48. M.init = function(self, x, y, width, height)
  49. List.init(self, x, y, width, height)
  50. self.toplevel = nil
  51. self.extensions = nil
  52. self.diricon = nil
  53. self.fileicon = nil
  54. --self.headerBack = {0.7, 0.7, 0.7}
  55. self.path = nil
  56. end
  57. M.setPath = function(self, path)
  58. local items, usedpath = createItemsFromDir(self, path)
  59. self:setItems(items, true)
  60. self.path = usedpath
  61. return path == nil or path == usedpath
  62. end
  63. BOXUI.add(M)
  64. end