summaryrefslogtreecommitdiff
path: root/FS.lua (plain)
blob: 04822d775743f34ee0e2682b3b41a03926f1cbe7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246

require 'buf'   -- TODO: move buf out of 'string' namespace
local zlib = require 'zlib'
local lfs = require 'lfs'

local assert, pairs, ipairs, notice = assert, pairs, ipairs, notice
local io, table, string, coroutine = io, table, string, coroutine
local loadstring, pcall, setfenv, setmetatable, error, rawget, require =
  loadstring, pcall, setfenv, setmetatable, error, rawget, require
local _WIN32 = _WIN32

local RWFromFile, RWFromNewMem, sethook, loaders =
  SDL.RWFromFile, SDL.RWFromNewMem, debug.sethook, package.loaders
local IMG_Load_RW, LoadWAV_RW = SDL.IMG_Load_RW, SDL.LoadWAV_RW

local _rwfromfile, _mkdir, _rmdir, _remove = nil

module(...)


-- co vsetko vlastne ta nova architektura *potrebuje*?
-- - loader implementujuci _open a _list ako citace priamo z fs
-- - loader implementujuci _open a _list ako citace zo zipu
-- - startovaci postup:
--   - najdeme user dir a vyrobime handle
--   - spustime userrc ak existuje
--   - najdeme data dir (musi tam byt manifest) a vyrobime handle
--   - spustime manifest ak existuje
-- - defaultny manifest potom najde standardne paky a vyrobi handly
-- co ak niekto bude chciet vyrobit mod?
-- - vyrobi upraveny manifest, co spravi to co povodny, a potom vyrobi handly
-- co ak niekto bude chciet vyrobit mod system?
-- - spravi specialnu modovu utilitu.
-- - tato modova utilita vyrobi v userdire specialny manifest, co spravi to
--   co povodny (ledaze by nie), potom nacita "runtime linker" modovej
--   utility, a potom povie, ktore mody by to chcelo
-- - runtime linker hned po nacitani prezrie data aj user adresar, ci tam
--   nie su nejake dalsie mody (ci uz su v .pak suboroch alebo v adresaroch
--   alebo ako). ked uzivatel povie, ze chce nejaky mod, zisti sa, ci uz je
--   taky mod registrovany, a mozno sa nacita.
-- - runtime linker je benevolentny a umoznuje nacitavajucim sa modom, aby
--   spustili lubovolny kod. takze mod moze registrovat dalsie mody. bud ma
--   v sebe hardcodnuty zoznam submodov, alebo zrecykluje rutiny runtime
--   linkera na prehladavanie adresara.
-- co poradie loaderov?
-- - aj ak nepouzijeme modovu utilitu, je v tom strasny neporiadok.
-- - vlastne je to presne opacne, ako by malo. tato vlastnost sa zachova?
-- - potom problem solved, proste miesto setAsMainLoader bude
--   appendToActiveList.


mainLoader = nil


Loader = {}

function Loader:new(o)
  self.__index = self
  return setmetatable(o or {}, self)
end

function Loader:_open(filename)
  return nil, "not implemented"
end

function Loader:_list(dirname)
  return nil, "not implemented"
end

function Loader:_tryNext(op, filename, errors, msg)
  errors = (errors or '')..'\n\t'..self.id..': '..msg
  if not self.nextLoader then return nil, errors:gsub('^\n\t', '') end
  return self.nextLoader[op](self.nextLoader, filename, errors)
end

function Loader:_failed(errors, msg)
  -- return an error without trying any more loaders.
  errors = (errors or '')..'\n\t'..self.id..': '..msg
  return nil, errors:gsub('^\n\t', '')
end

function Loader:appendToActiveList()
  if not mainLoader then mainLoader = self; return end
  local h = mainLoader
  while h.nextLoader do h = h.nextLoader end
  h.nextLoader = self
end

function Loader:listFiles(directory)
  local result = self.nextLoader and
    self.nextLoader:listFiles(directory) or {}
  for k,v in pairs(self:_list(directory) or {}) do result[k] = v end
  return result
end

function Loader:loadRW(filename, errors)
  local result, msg = self:_open(filename)
  if result then return result end
  return self:_tryNext('loadRW', filename, errors, msg)
end

function Loader:loadText(filename, errors)
  local result, msg = self:_open(filename)
  if result then result, msg = result:read() end
  if result then return result end
  return self:_tryNext('loadText', filename, errors, msg)
end

function Loader:loadCode(filename, errors)
  local result, msg = self:_open(filename)
  if result then result, msg = result:read() end
  if result then result, msg = loadstring(result, '@'..filename)
    if not result then return self:_failed(errors, msg) end end
  if result then return result end
  return self:_tryNext('loadCode', filename, errors, msg)
end

function Loader:loadData(filename, errors)
  local result, msg = self:_open(filename)
  if result then result, msg = result:read() end
  if result then result, msg = loadstring(result, '@'..filename)
    if not result then return self:_failed(errors, msg) end end
  if result then
    local env = {}
    local status, returned = pcall(setfenv(result, env))
    if status then env._data = returned or env._data; return env end
    return self:_failed(errors, returned)
  end
  return self:_tryNext('loadData', filename, errors, msg)
end

function Loader:loadXML(filename, errors)
  local result, XMLParser = pcall(require, 'XMLParser')
  if not result then return self:_failed(errors, XMLParser) end
  local result, msg = self:_open(filename)
  if result then result, msg = result:read() end
  if result then result, msg = pcall(XMLParser.parse, result)
    if not result then self:_failed(errors, msg) end end
  if result then return msg end
  return self:_tryNext('loadXML', filename, errors, msg)
end

function Loader:loadImage(filename, errors)
  local result; local rw, msg = self:_open(filename)
  if rw then result, msg = pcall(IMG_Load_RW, rw, true) end
  if result then rw:disown(); return msg end
  return self:_tryNext('loadImage', filename, errors, msg)
end

function Loader:loadMusic(filename, errors)
  local result; local rw, msg = self:_open(filename)
  if rw then result, msg = pcall(LoadWAV_RW, rw, true) end
  if result then rw:disown(); return msg end
  return self:_tryNext('loadMusic', filename, errors, msg)
end


function normalizePath(path)
  -- "aaa/bbb/../../../ccc/" -> "/ccc"
  path = ('/'..path..'/'):gsub('\\', '/'):gsub('/+', '/')
  while path:match('/%.%./') do
    path = path:gsub('^/+%.%./+', '/'):gsub('[^/]+/+%.%./', '', 1) end
  return (path:gsub('/+', '/'):gsub('/$', ''))   -- only one result
end


-- make FS.loadFoo(x) an alias for FS.mainLoader:loadFoo(normalizePath(x))
setmetatable(_M, { __index = function (t, k)
  if rawget(t, 'mainLoader') and mainLoader[k] then
    return function (x) return mainLoader[k](mainLoader, normalizePath(x)) end
  end
end })


DataDirectory = Loader:new()

DataDirectory.path = nil

function DataDirectory:_open(filename)
  local status, result = pcall(RWFromFile, self.path..'/'..filename, 'r')
  if status then return result end
  return nil, result
end

function DataDirectory:_list(path)
  path = self.path..'/'..path..'/'
  local result = {}
  local status, iter = pcall(lfs.dir, path)
  if not status then return nil, iter end
  for file in iter do if file ~= '.' and file ~= '..' then
    local mode, err = lfs.attributes(path..file, 'mode')
    if err then return nil, err end
    result[file] = mode
  end end
  return result
end


-- execute a "SFX stub" of a file without loading all of it.
function loadSFX(rw, ...)
  local payload
  local header = assert(rw:read(4))
  if header == 'ULPK' then
    local destLen, sourceLen = assert(rw:read(8)):unpack('<CC')
    local sourceBuf = RWFromNewMem(sourceLen)
    sourceLen = zlib.uncompress(sourceBuf:baseptr(), sourceLen,
      assert(rw:read(destLen)), destLen)
    payload = assert(sourceBuf:read(sourceLen))
  elseif header == '--SF' then
    local sourceLen = assert(tonumber(assert(rw:read(8)):unpack('8s')),
      "malformed header")
    payload = assert(rw:read(sourceLen))
  else
    error("not a SFX")
  end
  return assert(loadstring(payload, '=sfx'))(rw, ...)
end

function makeSFXStub(stub, compress)
  if not compress then return '--SF'..('%08d'):format(#stub)..stub end
  local destLen = zlib.compressBound(#stub)
  local destBuf = RWFromNewMem(#stub)
  destLen = zlib.compress(destBuf:baseptr(), destLen, stub, #stub)
  return 'ULPK'..('<CC'):pack(destLen, #stub)..assert(destBuf:read(destLen))
end


-- these are implemented in launcher.lua:

function write(filename, body)
  error"user directory not initialized."
end

function remove(filename)
  error"user directory not initialized."
end


function moduleLoader(moduleName)
  local filename = moduleName:gsub('%.', '/')..'.lua'
  local fn, err = loadCode(filename)
  return fn or (err and '\n\t'..err or '')
end

if loaders then loaders[#loaders+1] = moduleLoader end