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
11 Version
, Major_version
= App
.love_version()
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 function App
.love_version()
89 local major_version
, minor_version
= love
.getVersion()
90 local version
= major_version
..'.'..minor_version
91 return version
, major_version
94 -- save/restore various framework globals we care about -- only on very first load
95 function App
.snapshot_love()
96 if Love_snapshot
then return end
98 -- save the entire initial font; it doesn't seem reliably recreated using newFont
99 Love_snapshot
.initial_font
= love
.graphics
.getFont()
102 function App
.undo_initialize()
103 love
.graphics
.setFont(Love_snapshot
.initial_font
)
106 function App
.run_tests_and_initialize()
110 if #Test_errors
> 0 then
111 local error_message
= ''
112 if Warning_before_tests
then
113 error_message
= Warning_before_tests
..'\n\n'
115 error_message
= error_message
.. ('There were %d test failures:\n%s'):format(#Test_errors
, table.concat(Test_errors
))
119 App
.initialize_globals()
120 App
.initialize(love
.arg
.parseGameArguments(arg
), arg
)
123 function App
.run_tests()
124 local sorted_names
= {}
125 for name
,binding
in pairs(_G
) do
126 if name
:find('test_') == 1 then
127 table.insert(sorted_names
, name
)
130 table.sort(sorted_names
)
131 for _
,name
in ipairs(sorted_names
) do
132 App
.initialize_for_test()
133 --? print('=== '..name)
135 xpcall(_G
[name
], function(err
) prepend_debug_info_to_test_failure(name
, err
) end)
137 -- clean up all test methods
138 for _
,name
in ipairs(sorted_names
) do
143 function App
.initialize_for_test()
144 App
.screen
.init
{width
=100, height
=50}
145 App
.screen
.contents
= {} -- clear screen
150 App
.fake_keys_pressed
= {}
151 App
.fake_mouse_state
= {x
=-1, y
=-1}
152 App
.initialize_globals()
155 -- App.screen.resize and App.screen.move seem like better names than
156 -- love.window.setMode and love.window.setPosition respectively. They'll
157 -- be side-effect-free during tests, and they'll save their results in
158 -- attributes of App.screen for easy access.
162 -- Use App.screen.init in tests to initialize the fake screen.
163 function App
.screen
.init(dims
)
164 App
.screen
.width
= dims
.width
165 App
.screen
.height
= dims
.height
168 function App
.screen
.resize(width
, height
, flags
)
169 App
.screen
.width
= width
170 App
.screen
.height
= height
171 App
.screen
.flags
= flags
174 function App
.screen
.size()
175 return App
.screen
.width
, App
.screen
.height
, App
.screen
.flags
178 function App
.screen
.move(x
,y
, displayindex
)
181 App
.screen
.displayindex
= displayindex
184 function App
.screen
.position()
185 return App
.screen
.x
, App
.screen
.y
, App
.screen
.displayindex
188 -- If you use App.screen.print instead of love.graphics.print,
189 -- tests will be able to check what was printed using App.screen.check below.
191 -- One drawback of this approach: the y coordinate used depends on font size,
192 -- which feels brittle.
194 function App
.screen
.print(msg
, x
,y
)
195 local screen_row
= 'y'..tostring(y
)
196 --? print('drawing "'..msg..'" at y '..tostring(y))
197 local screen
= App
.screen
198 if screen
.contents
[screen_row
] == nil then
199 screen
.contents
[screen_row
] = {}
200 for i
=0,screen
.width
-1 do
201 screen
.contents
[screen_row
][i
] = ''
204 if x
< screen
.width
then
205 screen
.contents
[screen_row
][x
] = msg
209 function App
.screen
.check(y
, expected_contents
, msg
)
210 --? print('checking for "'..expected_contents..'" at y '..tostring(y))
211 local screen_row
= 'y'..tostring(y
)
213 if App
.screen
.contents
[screen_row
] == nil then
214 error('no text at y '..tostring(y
))
216 for i
,s
in ipairs(App
.screen
.contents
[screen_row
]) do
217 contents
= contents
..s
219 check_eq(contents
, expected_contents
, msg
)
222 -- If you access the time using App.get_time instead of love.timer.getTime,
223 -- tests will be able to move the time back and forwards as needed using
224 -- App.wait_fake_time below.
227 function App
.get_time()
230 function App
.wait_fake_time(t
)
231 App
.time
= App
.time
+ t
234 function App
.width(text
)
235 return love
.graphics
.getFont():getWidth(text
)
238 -- If you access the clipboard using App.get_clipboard and App.set_clipboard
239 -- instead of love.system.getClipboardText and love.system.setClipboardText
240 -- respectively, tests will be able to manipulate the clipboard by
241 -- reading/writing App.clipboard.
244 function App
.get_clipboard()
247 function App
.set_clipboard(s
)
251 -- In tests I mostly send chords all at once to the keyboard handlers.
252 -- However, you'll occasionally need to check if a key is down outside a handler.
253 -- If you use App.key_down instead of love.keyboard.isDown, tests will be able to
254 -- simulate keypresses using App.fake_key_press and App.fake_key_release
255 -- below. This isn't very realistic, though, and it's up to tests to
256 -- orchestrate key presses that correspond to the handlers they invoke.
258 App
.fake_keys_pressed
= {}
259 function App
.key_down(key
)
260 return App
.fake_keys_pressed
[key
]
263 function App
.fake_key_press(key
)
264 App
.fake_keys_pressed
[key
] = true
266 function App
.fake_key_release(key
)
267 App
.fake_keys_pressed
[key
] = nil
270 -- Tests mostly will invoke mouse handlers directly. However, you'll
271 -- occasionally need to check if a mouse button is down outside a handler.
272 -- If you use App.mouse_down instead of love.mouse.isDown, tests will be able to
273 -- simulate mouse clicks using App.fake_mouse_press and App.fake_mouse_release
274 -- below. This isn't very realistic, though, and it's up to tests to
275 -- orchestrate presses that correspond to the handlers they invoke.
277 App
.fake_mouse_state
= {x
=-1, y
=-1} -- x,y always set
279 function App
.mouse_move(x
,y
)
280 App
.fake_mouse_state
.x
= x
281 App
.fake_mouse_state
.y
= y
283 function App
.mouse_down(mouse_button
)
284 return App
.fake_mouse_state
[mouse_button
]
286 function App
.mouse_x()
287 return App
.fake_mouse_state
.x
289 function App
.mouse_y()
290 return App
.fake_mouse_state
.y
293 function App
.fake_mouse_press(x
,y
, mouse_button
)
294 App
.fake_mouse_state
.x
= x
295 App
.fake_mouse_state
.y
= y
296 App
.fake_mouse_state
[mouse_button
] = true
298 function App
.fake_mouse_release(x
,y
, mouse_button
)
299 App
.fake_mouse_state
.x
= x
300 App
.fake_mouse_state
.y
= y
301 App
.fake_mouse_state
[mouse_button
] = nil
304 -- If you use App.open_for_reading and App.open_for_writing instead of other
305 -- various Lua and LÖVE helpers, tests will be able to check the results of
306 -- file operations inside the App.filesystem table.
308 function App
.open_for_reading(filename
)
309 if App
.filesystem
[filename
] then
311 lines
= function(self
)
312 return App
.filesystem
[filename
]:gmatch('[^\n]+')
314 read = function(self
)
315 return App
.filesystem
[filename
]
317 close
= function(self
)
323 function App
.read_file(filename
)
324 return App
.filesystem
[filename
]
327 function App
.open_for_writing(filename
)
328 App
.filesystem
[filename
] = ''
330 write = function(self
, s
)
331 App
.filesystem
[filename
] = App
.filesystem
[filename
]..s
333 close
= function(self
)
338 function App
.write_file(filename
, contents
)
339 App
.filesystem
[filename
] = contents
340 return --[[status]] true
343 function App
.mkdir(dirname
)
344 -- nothing in test mode
347 function App
.remove(filename
)
348 App
.filesystem
[filename
] = nil
351 -- Some helpers to trigger an event and then refresh the screen. Akin to one
352 -- iteration of the event loop.
354 -- all textinput events are also keypresses
355 -- TODO: handle chords of multiple keys
356 function App
.run_after_textinput(t
)
360 App
.screen
.contents
= {}
364 -- not all keys are textinput
365 -- TODO: handle chords of multiple keys
366 function App
.run_after_keychord(chord
)
367 App
.keychord_press(chord
)
368 App
.keyreleased(chord
)
369 App
.screen
.contents
= {}
373 function App
.run_after_mouse_click(x
,y
, mouse_button
)
374 App
.fake_mouse_press(x
,y
, mouse_button
)
375 App
.mousepressed(x
,y
, mouse_button
)
376 App
.fake_mouse_release(x
,y
, mouse_button
)
377 App
.mousereleased(x
,y
, mouse_button
)
378 App
.screen
.contents
= {}
382 function App
.run_after_mouse_press(x
,y
, mouse_button
)
383 App
.fake_mouse_press(x
,y
, mouse_button
)
384 App
.mousepressed(x
,y
, mouse_button
)
385 App
.screen
.contents
= {}
389 function App
.run_after_mouse_release(x
,y
, mouse_button
)
390 App
.fake_mouse_release(x
,y
, mouse_button
)
391 App
.mousereleased(x
,y
, mouse_button
)
392 App
.screen
.contents
= {}
396 -- miscellaneous internal helpers
398 function App
.color(color
)
399 love
.graphics
.setColor(color
.r
, color
.g
, color
.b
, color
.a
)
402 -- prepend file/line/test
403 function prepend_debug_info_to_test_failure(test_name
, err
)
404 local err_without_line_number
= err
:gsub('^[^:]*:[^:]*: ', '')
405 local stack_trace
= debug
.traceback('', --[[stack frame]]5)
406 local file_and_line_number
= stack_trace
:gsub('stack traceback:\n', ''):gsub(': .*', '')
407 local full_error
= file_and_line_number
..':'..test_name
..' -- '..err_without_line_number
408 --? local full_error = file_and_line_number..':'..test_name..' -- '..err_without_line_number..'\t\t'..stack_trace:gsub('\n', '\n\t\t')
409 table.insert(Test_errors
, full_error
)
412 nativefs
= require
'nativefs'
416 -- call this once all tests are run
417 -- can't run any tests after this
418 function App
.disable_tests()
419 -- have LÖVE delegate all handlers to App if they exist
420 -- make sure to late-bind handlers like LÖVE's defaults do
421 for name
in pairs(love
.handlers
) do
423 -- love.keyboard.isDown doesn't work on Android, so emulate it using
424 -- keypressed and keyreleased events
425 if name
== 'keypressed' then
426 love
.handlers
[name
] = function(key
, scancode
, isrepeat
)
427 Keys_down
[key
] = true
428 return App
.keypressed(key
, scancode
, isrepeat
)
430 elseif name
== 'keyreleased' then
431 love
.handlers
[name
] = function(key
, scancode
)
433 return App
.keyreleased(key
, scancode
)
436 love
.handlers
[name
] = function(...) App
[name
](...) end
441 -- test methods are disallowed outside tests
443 App
.disable_tests
= nil
444 App
.screen
.init
= nil
447 App
.run_after_textinput
= nil
448 App
.run_after_keychord
= nil
451 App
.run_after_mouse_click
= nil
452 App
.run_after_mouse_press
= nil
453 App
.run_after_mouse_release
= nil
454 App
.fake_keys_pressed
= nil
455 App
.fake_key_press
= nil
456 App
.fake_key_release
= nil
457 App
.fake_mouse_state
= nil
458 App
.fake_mouse_press
= nil
459 App
.fake_mouse_release
= nil
460 -- other methods dispatch to real hardware
461 App
.screen
.resize
= love
.window
.setMode
462 App
.screen
.size
= love
.window
.getMode
463 App
.screen
.move
= love
.window
.setPosition
464 App
.screen
.position
= love
.window
.getPosition
465 App
.screen
.print = love
.graphics
.print
466 App
.open_for_reading
=
468 local result
= nativefs
.newFile(filename
)
469 local ok
, err
= result
:open('r')
478 if not is_absolute_path(path
) then
479 return --[[status]] false, 'Please use an unambiguous absolute path.'
481 local f
, err
= App
.open_for_reading(path
)
483 return --[[status]] false, err
485 local contents
= f
:read()
489 App
.open_for_writing
=
491 local result
= nativefs
.newFile(filename
)
492 local ok
, err
= result
:open('w')
500 function(path
, contents
)
501 if not is_absolute_path(path
) then
502 return --[[status]] false, 'Please use an unambiguous absolute path.'
504 local f
, err
= App
.open_for_writing(path
)
506 return --[[status]] false, err
510 return --[[status]] true
512 App
.files
= nativefs
.getDirectoryItems
513 App
.mkdir
= nativefs
.createDirectory
514 App
.remove = nativefs
.remove
515 App
.source_dir
= love
.filesystem
.getSource()..'/' -- '/' should work even on Windows
516 App
.current_dir
= nativefs
.getWorkingDirectory()..'/'
517 App
.save_dir
= love
.filesystem
.getSaveDirectory()..'/'
518 App
.get_time
= love
.timer
.getTime
519 App
.get_clipboard
= love
.system
.getClipboardText
520 App
.set_clipboard
= love
.system
.setClipboardText
521 App
.key_down
= function(key
) return Keys_down
[key
] end
522 App
.mouse_move
= love
.mouse
.setPosition
523 App
.mouse_down
= love
.mouse
.isDown
524 App
.mouse_x
= love
.mouse
.getX
525 App
.mouse_y
= love
.mouse
.getY