1 -- love.run: main entrypoint function for LÖVE
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
13 -- Tests always run at the start.
14 App
.run_tests_and_initialize()
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
29 xpcall(function() love
.handlers
[name
](a
,b
,c
,d
,e
,f
) end, handle_error
)
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)
45 function handle_error(err
)
46 local callstack
= debug
.traceback('', --[[stack frame]]2)
47 Error_message
= 'Error: ' .. tostring(err
)..'\n'..cleaned_up_callstack(callstack
)
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')
54 App
.run_tests_and_initialize()
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
)
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
)
75 -- the initial "stack traceback:" line was unindented and remains so
76 return table.concat(frames
, '\n\t')
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.
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
92 -- save the entire initial font; it doesn't seem reliably recreated using newFont
93 Love_snapshot
.initial_font
= love
.graphics
.getFont()
96 function App
.undo_initialize()
97 love
.graphics
.setFont(Love_snapshot
.initial_font
)
100 function App
.run_tests_and_initialize()
104 if #Test_errors
> 0 then
105 error(('There were %d test failures:\n\n%s'):format(#Test_errors
, table.concat(Test_errors
)))
108 App
.initialize_globals()
109 App
.initialize(love
.arg
.parseGameArguments(arg
), arg
)
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)
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
133 function App
.initialize_for_test()
134 App
.screen
.init
{width
=100, height
=50}
135 App
.screen
.contents
= {} -- clear screen
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.
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
)
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
)
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.
217 function App
.get_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.
234 function App
.get_clipboard()
237 function App
.set_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
301 lines
= function(self
)
302 return App
.filesystem
[filename
]:gmatch('[^\n]+')
304 read = function(self
)
305 return App
.filesystem
[filename
]
307 close
= function(self
)
313 function App
.read_file(filename
)
314 return App
.filesystem
[filename
]
317 function App
.open_for_writing(filename
)
318 App
.filesystem
[filename
] = ''
320 write = function(self
, s
)
321 App
.filesystem
[filename
] = App
.filesystem
[filename
]..s
323 close
= function(self
)
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
)
350 App
.screen
.contents
= {}
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
= {}
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
= {}
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
= {}
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
= {}
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'
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
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
)
423 return App
.keyreleased(key
, scancode
)
426 love
.handlers
[name
] = function(...) App
[name
](...) end
431 -- test methods are disallowed outside tests
433 App
.disable_tests
= nil
434 App
.screen
.init
= nil
437 App
.run_after_textinput
= nil
438 App
.run_after_keychord
= 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
=
458 local result
= nativefs
.newFile(filename
)
459 local ok
, err
= result
:open('r')
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
)
473 return --[[status]] false, err
475 local contents
= f
:read()
479 App
.open_for_writing
=
481 local result
= nativefs
.newFile(filename
)
482 local ok
, err
= result
:open('w')
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
)
496 return --[[status]] false, err
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