speculatively recommend new LÖVE v11.5 in all forks
[lines.love.git] / app.lua
blob4142380f0009b4cac71a15fe8f3fd2a92b11259a
1 -- love.run: main entrypoint function for LÖVE
2 --
3 -- Most apps can just use the default shown in https://love2d.org/wiki/love.run,
4 -- but we need to override it to:
5 -- * recover from errors (by switching to the source editor)
6 -- * run all tests (functions starting with 'test_') on startup, and
7 -- * save some state that makes it possible to switch between the main app
8 -- and a source editor, while giving each the illusion of complete
9 -- control.
10 function love.run()
11 App.version_check()
12 App.snapshot_love()
13 -- Tests always run at the start.
14 App.run_tests_and_initialize()
15 --? print('==')
17 love.timer.step()
18 local dt = 0
20 return function()
21 if love.event then
22 love.event.pump()
23 for name, a,b,c,d,e,f in love.event.poll() do
24 if name == "quit" then
25 if not love.quit or not love.quit() then
26 return a or 0
27 end
28 end
29 xpcall(function() love.handlers[name](a,b,c,d,e,f) end, handle_error)
30 end
31 end
33 dt = love.timer.step()
34 xpcall(function() App.update(dt) end, handle_error)
36 love.graphics.origin()
37 love.graphics.clear(love.graphics.getBackgroundColor())
38 xpcall(App.draw, handle_error)
39 love.graphics.present()
41 love.timer.sleep(0.001)
42 end
43 end
45 function handle_error(err)
46 local callstack = debug.traceback('', --[[stack frame]]2)
47 Error_message = 'Error: ' .. tostring(err)..'\n'..cleaned_up_callstack(callstack)
48 print(Error_message)
49 if Current_app == 'run' then
50 Settings.current_app = 'source'
51 love.filesystem.write('config', json.encode(Settings))
52 load_file_from_source_or_save_directory('main.lua')
53 App.undo_initialize()
54 App.run_tests_and_initialize()
55 else
56 love.event.quit()
57 end
58 end
60 -- I tend to read code from files myself (say using love.filesystem calls)
61 -- rather than offload that to load().
62 -- Functions compiled in this manner have ugly filenames of the form [string "filename"]
63 -- This function cleans out this cruft from error callstacks.
64 function cleaned_up_callstack(callstack)
65 local frames = {}
66 for frame in string.gmatch(callstack, '[^\n]+\n*') do
67 local line = frame:gsub('^%s*(.-)\n?$', '%1')
68 local filename, rest = line:match('([^:]*):(.*)')
69 local core_filename = filename:match('^%[string "(.*)"%]$')
70 -- pass through frames that don't match this format
71 -- this includes the initial line "stack traceback:"
72 local new_frame = (core_filename or filename)..':'..rest
73 table.insert(frames, new_frame)
74 end
75 -- the initial "stack traceback:" line was unindented and remains so
76 return table.concat(frames, '\n\t')
77 end
79 -- The rest of this file wraps around various LÖVE primitives to support
80 -- automated tests. Often tests will run with a fake version of a primitive
81 -- that redirects to the real love.* version once we're done with tests.
83 -- Not everything is so wrapped yet. Sometimes you still have to use love.*
84 -- primitives directly.
86 App = {}
88 -- save/restore various framework globals we care about -- only on very first load
89 function App.snapshot_love()
90 if Love_snapshot then return end
91 Love_snapshot = {}
92 -- save the entire initial font; it doesn't seem reliably recreated using newFont
93 Love_snapshot.initial_font = love.graphics.getFont()
94 end
96 function App.undo_initialize()
97 love.graphics.setFont(Love_snapshot.initial_font)
98 end
100 function App.run_tests_and_initialize()
101 App.load()
102 Test_errors = {}
103 App.run_tests()
104 if #Test_errors > 0 then
105 error(('There were %d test failures:\n\n%s'):format(#Test_errors, table.concat(Test_errors)))
107 App.disable_tests()
108 App.initialize_globals()
109 App.initialize(love.arg.parseGameArguments(arg), arg)
110 App.version_check()
113 function App.run_tests()
114 local sorted_names = {}
115 for name,binding in pairs(_G) do
116 if name:find('test_') == 1 then
117 table.insert(sorted_names, name)
120 table.sort(sorted_names)
121 for _,name in ipairs(sorted_names) do
122 App.initialize_for_test()
123 --? print('=== '..name)
124 --? _G[name]()
125 xpcall(_G[name], function(err) prepend_debug_info_to_test_failure(name, err) end)
127 -- clean up all test methods
128 for _,name in ipairs(sorted_names) do
129 _G[name] = nil
133 function App.initialize_for_test()
134 App.screen.init{width=100, height=50}
135 App.screen.contents = {} -- clear screen
136 App.filesystem = {}
137 App.source_dir = ''
138 App.current_dir = ''
139 App.save_dir = ''
140 App.fake_keys_pressed = {}
141 App.fake_mouse_state = {x=-1, y=-1}
142 App.initialize_globals()
145 -- App.screen.resize and App.screen.move seem like better names than
146 -- love.window.setMode and love.window.setPosition respectively. They'll
147 -- be side-effect-free during tests, and they'll save their results in
148 -- attributes of App.screen for easy access.
150 App.screen={}
152 -- Use App.screen.init in tests to initialize the fake screen.
153 function App.screen.init(dims)
154 App.screen.width = dims.width
155 App.screen.height = dims.height
158 function App.screen.resize(width, height, flags)
159 App.screen.width = width
160 App.screen.height = height
161 App.screen.flags = flags
164 function App.screen.size()
165 return App.screen.width, App.screen.height, App.screen.flags
168 function App.screen.move(x,y, displayindex)
169 App.screen.x = x
170 App.screen.y = y
171 App.screen.displayindex = displayindex
174 function App.screen.position()
175 return App.screen.x, App.screen.y, App.screen.displayindex
178 -- If you use App.screen.print instead of love.graphics.print,
179 -- tests will be able to check what was printed using App.screen.check below.
181 -- One drawback of this approach: the y coordinate used depends on font size,
182 -- which feels brittle.
184 function App.screen.print(msg, x,y)
185 local screen_row = 'y'..tostring(y)
186 --? print('drawing "'..msg..'" at y '..tostring(y))
187 local screen = App.screen
188 if screen.contents[screen_row] == nil then
189 screen.contents[screen_row] = {}
190 for i=0,screen.width-1 do
191 screen.contents[screen_row][i] = ''
194 if x < screen.width then
195 screen.contents[screen_row][x] = msg
199 function App.screen.check(y, expected_contents, msg)
200 --? print('checking for "'..expected_contents..'" at y '..tostring(y))
201 local screen_row = 'y'..tostring(y)
202 local contents = ''
203 if App.screen.contents[screen_row] == nil then
204 error('no text at y '..tostring(y))
206 for i,s in ipairs(App.screen.contents[screen_row]) do
207 contents = contents..s
209 check_eq(contents, expected_contents, msg)
212 -- If you access the time using App.get_time instead of love.timer.getTime,
213 -- tests will be able to move the time back and forwards as needed using
214 -- App.wait_fake_time below.
216 App.time = 1
217 function App.get_time()
218 return App.time
220 function App.wait_fake_time(t)
221 App.time = App.time + t
224 function App.width(text)
225 return love.graphics.getFont():getWidth(text)
228 -- If you access the clipboard using App.get_clipboard and App.set_clipboard
229 -- instead of love.system.getClipboardText and love.system.setClipboardText
230 -- respectively, tests will be able to manipulate the clipboard by
231 -- reading/writing App.clipboard.
233 App.clipboard = ''
234 function App.get_clipboard()
235 return App.clipboard
237 function App.set_clipboard(s)
238 App.clipboard = s
241 -- In tests I mostly send chords all at once to the keyboard handlers.
242 -- However, you'll occasionally need to check if a key is down outside a handler.
243 -- If you use App.key_down instead of love.keyboard.isDown, tests will be able to
244 -- simulate keypresses using App.fake_key_press and App.fake_key_release
245 -- below. This isn't very realistic, though, and it's up to tests to
246 -- orchestrate key presses that correspond to the handlers they invoke.
248 App.fake_keys_pressed = {}
249 function App.key_down(key)
250 return App.fake_keys_pressed[key]
253 function App.fake_key_press(key)
254 App.fake_keys_pressed[key] = true
256 function App.fake_key_release(key)
257 App.fake_keys_pressed[key] = nil
260 -- Tests mostly will invoke mouse handlers directly. However, you'll
261 -- occasionally need to check if a mouse button is down outside a handler.
262 -- If you use App.mouse_down instead of love.mouse.isDown, tests will be able to
263 -- simulate mouse clicks using App.fake_mouse_press and App.fake_mouse_release
264 -- below. This isn't very realistic, though, and it's up to tests to
265 -- orchestrate presses that correspond to the handlers they invoke.
267 App.fake_mouse_state = {x=-1, y=-1} -- x,y always set
269 function App.mouse_move(x,y)
270 App.fake_mouse_state.x = x
271 App.fake_mouse_state.y = y
273 function App.mouse_down(mouse_button)
274 return App.fake_mouse_state[mouse_button]
276 function App.mouse_x()
277 return App.fake_mouse_state.x
279 function App.mouse_y()
280 return App.fake_mouse_state.y
283 function App.fake_mouse_press(x,y, mouse_button)
284 App.fake_mouse_state.x = x
285 App.fake_mouse_state.y = y
286 App.fake_mouse_state[mouse_button] = true
288 function App.fake_mouse_release(x,y, mouse_button)
289 App.fake_mouse_state.x = x
290 App.fake_mouse_state.y = y
291 App.fake_mouse_state[mouse_button] = nil
294 -- If you use App.open_for_reading and App.open_for_writing instead of other
295 -- various Lua and LÖVE helpers, tests will be able to check the results of
296 -- file operations inside the App.filesystem table.
298 function App.open_for_reading(filename)
299 if App.filesystem[filename] then
300 return {
301 lines = function(self)
302 return App.filesystem[filename]:gmatch('[^\n]+')
303 end,
304 read = function(self)
305 return App.filesystem[filename]
306 end,
307 close = function(self)
308 end,
313 function App.read_file(filename)
314 return App.filesystem[filename]
317 function App.open_for_writing(filename)
318 App.filesystem[filename] = ''
319 return {
320 write = function(self, s)
321 App.filesystem[filename] = App.filesystem[filename]..s
322 end,
323 close = function(self)
324 end,
328 function App.write_file(filename, contents)
329 App.filesystem[filename] = contents
330 return --[[status]] true
333 function App.mkdir(dirname)
334 -- nothing in test mode
337 function App.remove(filename)
338 App.filesystem[filename] = nil
341 -- Some helpers to trigger an event and then refresh the screen. Akin to one
342 -- iteration of the event loop.
344 -- all textinput events are also keypresses
345 -- TODO: handle chords of multiple keys
346 function App.run_after_textinput(t)
347 App.keypressed(t)
348 App.textinput(t)
349 App.keyreleased(t)
350 App.screen.contents = {}
351 App.draw()
354 -- not all keys are textinput
355 -- TODO: handle chords of multiple keys
356 function App.run_after_keychord(chord)
357 App.keychord_press(chord)
358 App.keyreleased(chord)
359 App.screen.contents = {}
360 App.draw()
363 function App.run_after_mouse_click(x,y, mouse_button)
364 App.fake_mouse_press(x,y, mouse_button)
365 App.mousepressed(x,y, mouse_button)
366 App.fake_mouse_release(x,y, mouse_button)
367 App.mousereleased(x,y, mouse_button)
368 App.screen.contents = {}
369 App.draw()
372 function App.run_after_mouse_press(x,y, mouse_button)
373 App.fake_mouse_press(x,y, mouse_button)
374 App.mousepressed(x,y, mouse_button)
375 App.screen.contents = {}
376 App.draw()
379 function App.run_after_mouse_release(x,y, mouse_button)
380 App.fake_mouse_release(x,y, mouse_button)
381 App.mousereleased(x,y, mouse_button)
382 App.screen.contents = {}
383 App.draw()
386 -- miscellaneous internal helpers
388 function App.color(color)
389 love.graphics.setColor(color.r, color.g, color.b, color.a)
392 -- prepend file/line/test
393 function prepend_debug_info_to_test_failure(test_name, err)
394 local err_without_line_number = err:gsub('^[^:]*:[^:]*: ', '')
395 local stack_trace = debug.traceback('', --[[stack frame]]5)
396 local file_and_line_number = stack_trace:gsub('stack traceback:\n', ''):gsub(': .*', '')
397 local full_error = file_and_line_number..':'..test_name..' -- '..err_without_line_number
398 --? local full_error = file_and_line_number..':'..test_name..' -- '..err_without_line_number..'\t\t'..stack_trace:gsub('\n', '\n\t\t')
399 table.insert(Test_errors, full_error)
402 nativefs = require 'nativefs'
404 local Keys_down = {}
406 -- call this once all tests are run
407 -- can't run any tests after this
408 function App.disable_tests()
409 -- have LÖVE delegate all handlers to App if they exist
410 -- make sure to late-bind handlers like LÖVE's defaults do
411 for name in pairs(love.handlers) do
412 if App[name] then
413 -- love.keyboard.isDown doesn't work on Android, so emulate it using
414 -- keypressed and keyreleased events
415 if name == 'keypressed' then
416 love.handlers[name] = function(key, scancode, isrepeat)
417 Keys_down[key] = true
418 return App.keypressed(key, scancode, isrepeat)
420 elseif name == 'keyreleased' then
421 love.handlers[name] = function(key, scancode)
422 Keys_down[key] = nil
423 return App.keyreleased(key, scancode)
425 else
426 love.handlers[name] = function(...) App[name](...) end
431 -- test methods are disallowed outside tests
432 App.run_tests = nil
433 App.disable_tests = nil
434 App.screen.init = nil
435 App.filesystem = nil
436 App.time = nil
437 App.run_after_textinput = nil
438 App.run_after_keychord = nil
439 App.keypress = nil
440 App.keyrelease = nil
441 App.run_after_mouse_click = nil
442 App.run_after_mouse_press = nil
443 App.run_after_mouse_release = nil
444 App.fake_keys_pressed = nil
445 App.fake_key_press = nil
446 App.fake_key_release = nil
447 App.fake_mouse_state = nil
448 App.fake_mouse_press = nil
449 App.fake_mouse_release = nil
450 -- other methods dispatch to real hardware
451 App.screen.resize = love.window.setMode
452 App.screen.size = love.window.getMode
453 App.screen.move = love.window.setPosition
454 App.screen.position = love.window.getPosition
455 App.screen.print = love.graphics.print
456 App.open_for_reading =
457 function(filename)
458 local result = nativefs.newFile(filename)
459 local ok, err = result:open('r')
460 if ok then
461 return result
462 else
463 return ok, err
466 App.read_file =
467 function(path)
468 if not is_absolute_path(path) then
469 return --[[status]] false, 'Please use an unambiguous absolute path.'
471 local f, err = App.open_for_reading(path)
472 if err then
473 return --[[status]] false, err
475 local contents = f:read()
476 f:close()
477 return contents
479 App.open_for_writing =
480 function(filename)
481 local result = nativefs.newFile(filename)
482 local ok, err = result:open('w')
483 if ok then
484 return result
485 else
486 return ok, err
489 App.write_file =
490 function(path, contents)
491 if not is_absolute_path(path) then
492 return --[[status]] false, 'Please use an unambiguous absolute path.'
494 local f, err = App.open_for_writing(path)
495 if err then
496 return --[[status]] false, err
498 f:write(contents)
499 f:close()
500 return --[[status]] true
502 App.files = nativefs.getDirectoryItems
503 App.mkdir = nativefs.createDirectory
504 App.remove = nativefs.remove
505 App.source_dir = love.filesystem.getSource()..'/' -- '/' should work even on Windows
506 App.current_dir = nativefs.getWorkingDirectory()..'/'
507 App.save_dir = love.filesystem.getSaveDirectory()..'/'
508 App.get_time = love.timer.getTime
509 App.get_clipboard = love.system.getClipboardText
510 App.set_clipboard = love.system.setClipboardText
511 App.key_down = function(key) return Keys_down[key] end
512 App.mouse_move = love.mouse.setPosition
513 App.mouse_down = love.mouse.isDown
514 App.mouse_x = love.mouse.getX
515 App.mouse_y = love.mouse.getY