clearing starty is redundant in mutations
[view.love.git] / app.lua
blob35350d465560c2afef9ae4e73397c9c29501ac3e
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)
112 function App.run_tests()
113 local sorted_names = {}
114 for name,binding in pairs(_G) do
115 if name:find('test_') == 1 then
116 table.insert(sorted_names, name)
119 table.sort(sorted_names)
120 for _,name in ipairs(sorted_names) do
121 App.initialize_for_test()
122 --? print('=== '..name)
123 --? _G[name]()
124 xpcall(_G[name], function(err) prepend_debug_info_to_test_failure(name, err) end)
126 -- clean up all test methods
127 for _,name in ipairs(sorted_names) do
128 _G[name] = nil
132 function App.initialize_for_test()
133 App.screen.init{width=100, height=50}
134 App.screen.contents = {} -- clear screen
135 App.filesystem = {}
136 App.source_dir = ''
137 App.current_dir = ''
138 App.save_dir = ''
139 App.fake_keys_pressed = {}
140 App.fake_mouse_state = {x=-1, y=-1}
141 App.initialize_globals()
144 -- App.screen.resize and App.screen.move seem like better names than
145 -- love.window.setMode and love.window.setPosition respectively. They'll
146 -- be side-effect-free during tests, and they'll save their results in
147 -- attributes of App.screen for easy access.
149 App.screen={}
151 -- Use App.screen.init in tests to initialize the fake screen.
152 function App.screen.init(dims)
153 App.screen.width = dims.width
154 App.screen.height = dims.height
157 function App.screen.resize(width, height, flags)
158 App.screen.width = width
159 App.screen.height = height
160 App.screen.flags = flags
163 function App.screen.size()
164 return App.screen.width, App.screen.height, App.screen.flags
167 function App.screen.move(x,y, displayindex)
168 App.screen.x = x
169 App.screen.y = y
170 App.screen.displayindex = displayindex
173 function App.screen.position()
174 return App.screen.x, App.screen.y, App.screen.displayindex
177 -- If you use App.screen.print instead of love.graphics.print,
178 -- tests will be able to check what was printed using App.screen.check below.
180 -- One drawback of this approach: the y coordinate used depends on font size,
181 -- which feels brittle.
183 function App.screen.print(msg, x,y)
184 local screen_row = 'y'..tostring(y)
185 --? print('drawing "'..msg..'" at y '..tostring(y))
186 local screen = App.screen
187 if screen.contents[screen_row] == nil then
188 screen.contents[screen_row] = {}
189 for i=0,screen.width-1 do
190 screen.contents[screen_row][i] = ''
193 if x < screen.width then
194 screen.contents[screen_row][x] = msg
198 function App.screen.check(y, expected_contents, msg)
199 --? print('checking for "'..expected_contents..'" at y '..tostring(y))
200 local screen_row = 'y'..tostring(y)
201 local contents = ''
202 if App.screen.contents[screen_row] == nil then
203 error('no text at y '..tostring(y))
205 for i,s in ipairs(App.screen.contents[screen_row]) do
206 contents = contents..s
208 check_eq(contents, expected_contents, msg)
211 -- If you access the time using App.get_time instead of love.timer.getTime,
212 -- tests will be able to move the time back and forwards as needed using
213 -- App.wait_fake_time below.
215 App.time = 1
216 function App.get_time()
217 return App.time
219 function App.wait_fake_time(t)
220 App.time = App.time + t
223 function App.width(text)
224 return love.graphics.getFont():getWidth(text)
227 -- If you access the clipboard using App.get_clipboard and App.set_clipboard
228 -- instead of love.system.getClipboardText and love.system.setClipboardText
229 -- respectively, tests will be able to manipulate the clipboard by
230 -- reading/writing App.clipboard.
232 App.clipboard = ''
233 function App.get_clipboard()
234 return App.clipboard
236 function App.set_clipboard(s)
237 App.clipboard = s
240 -- In tests I mostly send chords all at once to the keyboard handlers.
241 -- However, you'll occasionally need to check if a key is down outside a handler.
242 -- If you use App.key_down instead of love.keyboard.isDown, tests will be able to
243 -- simulate keypresses using App.fake_key_press and App.fake_key_release
244 -- below. This isn't very realistic, though, and it's up to tests to
245 -- orchestrate key presses that correspond to the handlers they invoke.
247 App.fake_keys_pressed = {}
248 function App.key_down(key)
249 return App.fake_keys_pressed[key]
252 function App.fake_key_press(key)
253 App.fake_keys_pressed[key] = true
255 function App.fake_key_release(key)
256 App.fake_keys_pressed[key] = nil
259 -- Tests mostly will invoke mouse handlers directly. However, you'll
260 -- occasionally need to check if a mouse button is down outside a handler.
261 -- If you use App.mouse_down instead of love.mouse.isDown, tests will be able to
262 -- simulate mouse clicks using App.fake_mouse_press and App.fake_mouse_release
263 -- below. This isn't very realistic, though, and it's up to tests to
264 -- orchestrate presses that correspond to the handlers they invoke.
266 App.fake_mouse_state = {x=-1, y=-1} -- x,y always set
268 function App.mouse_move(x,y)
269 App.fake_mouse_state.x = x
270 App.fake_mouse_state.y = y
272 function App.mouse_down(mouse_button)
273 return App.fake_mouse_state[mouse_button]
275 function App.mouse_x()
276 return App.fake_mouse_state.x
278 function App.mouse_y()
279 return App.fake_mouse_state.y
282 function App.fake_mouse_press(x,y, mouse_button)
283 App.fake_mouse_state.x = x
284 App.fake_mouse_state.y = y
285 App.fake_mouse_state[mouse_button] = true
287 function App.fake_mouse_release(x,y, mouse_button)
288 App.fake_mouse_state.x = x
289 App.fake_mouse_state.y = y
290 App.fake_mouse_state[mouse_button] = nil
293 -- If you use App.open_for_reading and App.open_for_writing instead of other
294 -- various Lua and LÖVE helpers, tests will be able to check the results of
295 -- file operations inside the App.filesystem table.
297 function App.open_for_reading(filename)
298 if App.filesystem[filename] then
299 return {
300 lines = function(self)
301 return App.filesystem[filename]:gmatch('[^\n]+')
302 end,
303 read = function(self)
304 return App.filesystem[filename]
305 end,
306 close = function(self)
307 end,
312 function App.read_file(filename)
313 return App.filesystem[filename]
316 function App.open_for_writing(filename)
317 App.filesystem[filename] = ''
318 return {
319 write = function(self, s)
320 App.filesystem[filename] = App.filesystem[filename]..s
321 end,
322 close = function(self)
323 end,
327 function App.write_file(filename, contents)
328 App.filesystem[filename] = contents
329 return --[[status]] true
332 function App.mkdir(dirname)
333 -- nothing in test mode
336 function App.remove(filename)
337 App.filesystem[filename] = nil
340 -- Some helpers to trigger an event and then refresh the screen. Akin to one
341 -- iteration of the event loop.
343 -- all textinput events are also keypresses
344 -- TODO: handle chords of multiple keys
345 function App.run_after_textinput(t)
346 App.keypressed(t)
347 App.textinput(t)
348 App.keyreleased(t)
349 App.screen.contents = {}
350 App.draw()
353 -- not all keys are textinput
354 -- TODO: handle chords of multiple keys
355 function App.run_after_keychord(chord)
356 App.keychord_press(chord)
357 App.keyreleased(chord)
358 App.screen.contents = {}
359 App.draw()
362 function App.run_after_mouse_click(x,y, mouse_button)
363 App.fake_mouse_press(x,y, mouse_button)
364 App.mousepressed(x,y, mouse_button)
365 App.fake_mouse_release(x,y, mouse_button)
366 App.mousereleased(x,y, mouse_button)
367 App.screen.contents = {}
368 App.draw()
371 function App.run_after_mouse_press(x,y, mouse_button)
372 App.fake_mouse_press(x,y, mouse_button)
373 App.mousepressed(x,y, mouse_button)
374 App.screen.contents = {}
375 App.draw()
378 function App.run_after_mouse_release(x,y, mouse_button)
379 App.fake_mouse_release(x,y, mouse_button)
380 App.mousereleased(x,y, mouse_button)
381 App.screen.contents = {}
382 App.draw()
385 -- miscellaneous internal helpers
387 function App.color(color)
388 love.graphics.setColor(color.r, color.g, color.b, color.a)
391 -- prepend file/line/test
392 function prepend_debug_info_to_test_failure(test_name, err)
393 local err_without_line_number = err:gsub('^[^:]*:[^:]*: ', '')
394 local stack_trace = debug.traceback('', --[[stack frame]]5)
395 local file_and_line_number = stack_trace:gsub('stack traceback:\n', ''):gsub(': .*', '')
396 local full_error = file_and_line_number..':'..test_name..' -- '..err_without_line_number
397 --? local full_error = file_and_line_number..':'..test_name..' -- '..err_without_line_number..'\t\t'..stack_trace:gsub('\n', '\n\t\t')
398 table.insert(Test_errors, full_error)
401 nativefs = require 'nativefs'
403 local Keys_down = {}
405 -- call this once all tests are run
406 -- can't run any tests after this
407 function App.disable_tests()
408 -- have LÖVE delegate all handlers to App if they exist
409 -- make sure to late-bind handlers like LÖVE's defaults do
410 for name in pairs(love.handlers) do
411 if App[name] then
412 -- love.keyboard.isDown doesn't work on Android, so emulate it using
413 -- keypressed and keyreleased events
414 if name == 'keypressed' then
415 love.handlers[name] = function(key, scancode, isrepeat)
416 Keys_down[key] = true
417 return App.keypressed(key, scancode, isrepeat)
419 elseif name == 'keyreleased' then
420 love.handlers[name] = function(key, scancode)
421 Keys_down[key] = nil
422 return App.keyreleased(key, scancode)
424 else
425 love.handlers[name] = function(...) App[name](...) end
430 -- test methods are disallowed outside tests
431 App.run_tests = nil
432 App.disable_tests = nil
433 App.screen.init = nil
434 App.filesystem = nil
435 App.time = nil
436 App.run_after_textinput = nil
437 App.run_after_keychord = nil
438 App.keypress = nil
439 App.keyrelease = nil
440 App.run_after_mouse_click = nil
441 App.run_after_mouse_press = nil
442 App.run_after_mouse_release = nil
443 App.fake_keys_pressed = nil
444 App.fake_key_press = nil
445 App.fake_key_release = nil
446 App.fake_mouse_state = nil
447 App.fake_mouse_press = nil
448 App.fake_mouse_release = nil
449 -- other methods dispatch to real hardware
450 App.screen.resize = love.window.setMode
451 App.screen.size = love.window.getMode
452 App.screen.move = love.window.setPosition
453 App.screen.position = love.window.getPosition
454 App.screen.print = love.graphics.print
455 App.open_for_reading =
456 function(filename)
457 local result = nativefs.newFile(filename)
458 local ok, err = result:open('r')
459 if ok then
460 return result
461 else
462 return ok, err
465 App.read_file =
466 function(path)
467 if not is_absolute_path(path) then
468 return --[[status]] false, 'Please use an unambiguous absolute path.'
470 local f, err = App.open_for_reading(path)
471 if err then
472 return --[[status]] false, err
474 local contents = f:read()
475 f:close()
476 return contents
478 App.open_for_writing =
479 function(filename)
480 local result = nativefs.newFile(filename)
481 local ok, err = result:open('w')
482 if ok then
483 return result
484 else
485 return ok, err
488 App.write_file =
489 function(path, contents)
490 if not is_absolute_path(path) then
491 return --[[status]] false, 'Please use an unambiguous absolute path.'
493 local f, err = App.open_for_writing(path)
494 if err then
495 return --[[status]] false, err
497 f:write(contents)
498 f:close()
499 return --[[status]] true
501 App.files = nativefs.getDirectoryItems
502 App.mkdir = nativefs.createDirectory
503 App.remove = nativefs.remove
504 App.source_dir = love.filesystem.getSource()..'/' -- '/' should work even on Windows
505 App.current_dir = nativefs.getWorkingDirectory()..'/'
506 App.save_dir = love.filesystem.getSaveDirectory()..'/'
507 App.get_time = love.timer.getTime
508 App.get_clipboard = love.system.getClipboardText
509 App.set_clipboard = love.system.setClipboardText
510 App.key_down = function(key) return Keys_down[key] end
511 App.mouse_move = love.mouse.setPosition
512 App.mouse_down = love.mouse.isDown
513 App.mouse_x = love.mouse.getX
514 App.mouse_y = love.mouse.getY