use editor state font for width calculations
[view.love.git] / app.lua
blobf59897c438cc219d738ef395ede16dfcc31a6226
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 Version, Major_version = App.love_version()
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 -- abort without running love.quit handler
57 Disable_all_quit_handlers = true
58 love.event.quit()
59 end
60 end
62 -- I tend to read code from files myself (say using love.filesystem calls)
63 -- rather than offload that to load().
64 -- Functions compiled in this manner have ugly filenames of the form [string "filename"]
65 -- This function cleans out this cruft from error callstacks.
66 function cleaned_up_callstack(callstack)
67 local frames = {}
68 for frame in string.gmatch(callstack, '[^\n]+\n*') do
69 local line = frame:gsub('^%s*(.-)\n?$', '%1')
70 local filename, rest = line:match('([^:]*):(.*)')
71 local core_filename = filename:match('^%[string "(.*)"%]$')
72 -- pass through frames that don't match this format
73 -- this includes the initial line "stack traceback:"
74 local new_frame = (core_filename or filename)..':'..rest
75 table.insert(frames, new_frame)
76 end
77 -- the initial "stack traceback:" line was unindented and remains so
78 return table.concat(frames, '\n\t')
79 end
81 -- The rest of this file wraps around various LÖVE primitives to support
82 -- automated tests. Often tests will run with a fake version of a primitive
83 -- that redirects to the real love.* version once we're done with tests.
85 -- Not everything is so wrapped yet. Sometimes you still have to use love.*
86 -- primitives directly.
88 App = {}
90 function App.love_version()
91 local major_version, minor_version = love.getVersion()
92 local version = major_version..'.'..minor_version
93 return version, major_version
94 end
96 -- save/restore various framework globals we care about -- only on very first load
97 function App.snapshot_love()
98 if Love_snapshot then return end
99 Love_snapshot = {}
100 -- save the entire initial font; it doesn't seem reliably recreated using newFont
101 Love_snapshot.initial_font = love.graphics.getFont()
104 function App.undo_initialize()
105 love.graphics.setFont(Love_snapshot.initial_font)
108 function App.run_tests_and_initialize()
109 App.load()
110 Test_errors = {}
111 App.run_tests()
112 if #Test_errors > 0 then
113 local error_message = ''
114 if Warning_before_tests then
115 error_message = Warning_before_tests..'\n\n'
117 error_message = error_message .. ('There were %d test failures:\n%s'):format(#Test_errors, table.concat(Test_errors))
118 error(error_message)
120 App.disable_tests()
121 App.initialize_globals()
122 App.initialize(love.arg.parseGameArguments(arg), arg)
125 function App.run_tests()
126 local sorted_names = {}
127 for name,binding in pairs(_G) do
128 if name:find('test_') == 1 then
129 table.insert(sorted_names, name)
132 table.sort(sorted_names)
133 for _,name in ipairs(sorted_names) do
134 App.initialize_for_test()
135 --? print('=== '..name)
136 --? _G[name]()
137 xpcall(_G[name], function(err) prepend_debug_info_to_test_failure(name, err) end)
139 -- clean up all test methods
140 for _,name in ipairs(sorted_names) do
141 _G[name] = nil
145 function App.initialize_for_test()
146 App.screen.init{width=100, height=50}
147 App.screen.contents = {} -- clear screen
148 App.filesystem = {}
149 App.source_dir = ''
150 App.current_dir = ''
151 App.save_dir = ''
152 App.fake_keys_pressed = {}
153 App.fake_mouse_state = {x=-1, y=-1}
154 App.initialize_globals()
157 -- App.screen.resize and App.screen.move seem like better names than
158 -- love.window.setMode and love.window.setPosition respectively. They'll
159 -- be side-effect-free during tests, and they'll save their results in
160 -- attributes of App.screen for easy access.
162 App.screen={}
164 -- Use App.screen.init in tests to initialize the fake screen.
165 function App.screen.init(dims)
166 App.screen.width = dims.width
167 App.screen.height = dims.height
170 function App.screen.resize(width, height, flags)
171 App.screen.width = width
172 App.screen.height = height
173 App.screen.flags = flags
176 function App.screen.size()
177 return App.screen.width, App.screen.height, App.screen.flags
180 function App.screen.move(x,y, displayindex)
181 App.screen.x = x
182 App.screen.y = y
183 App.screen.displayindex = displayindex
186 function App.screen.position()
187 return App.screen.x, App.screen.y, App.screen.displayindex
190 -- If you use App.screen.print instead of love.graphics.print,
191 -- tests will be able to check what was printed using App.screen.check below.
193 -- One drawback of this approach: the y coordinate used depends on font size,
194 -- which feels brittle.
196 function App.screen.print(msg, x,y)
197 local screen_row = 'y'..tostring(y)
198 --? print('drawing "'..msg..'" at y '..tostring(y))
199 local screen = App.screen
200 if screen.contents[screen_row] == nil then
201 screen.contents[screen_row] = {}
202 for i=0,screen.width-1 do
203 screen.contents[screen_row][i] = ''
206 if x < screen.width then
207 screen.contents[screen_row][x] = msg
211 function App.screen.check(y, expected_contents, msg)
212 --? print('checking for "'..expected_contents..'" at y '..tostring(y))
213 local screen_row = 'y'..tostring(y)
214 local contents = ''
215 if App.screen.contents[screen_row] == nil then
216 error('no text at y '..tostring(y))
218 for i,s in ipairs(App.screen.contents[screen_row]) do
219 contents = contents..s
221 check_eq(contents, expected_contents, msg)
224 -- If you access the time using App.get_time instead of love.timer.getTime,
225 -- tests will be able to move the time back and forwards as needed using
226 -- App.wait_fake_time below.
228 App.time = 1
229 function App.get_time()
230 return App.time
232 function App.wait_fake_time(t)
233 App.time = App.time + t
236 function App.width(text)
237 return love.graphics.getFont():getWidth(text)
240 -- If you access the clipboard using App.get_clipboard and App.set_clipboard
241 -- instead of love.system.getClipboardText and love.system.setClipboardText
242 -- respectively, tests will be able to manipulate the clipboard by
243 -- reading/writing App.clipboard.
245 App.clipboard = ''
246 function App.get_clipboard()
247 return App.clipboard
249 function App.set_clipboard(s)
250 App.clipboard = s
253 -- In tests I mostly send chords all at once to the keyboard handlers.
254 -- However, you'll occasionally need to check if a key is down outside a handler.
255 -- If you use App.key_down instead of love.keyboard.isDown, tests will be able to
256 -- simulate keypresses using App.fake_key_press and App.fake_key_release
257 -- below. This isn't very realistic, though, and it's up to tests to
258 -- orchestrate key presses that correspond to the handlers they invoke.
260 App.fake_keys_pressed = {}
261 function App.key_down(key)
262 return App.fake_keys_pressed[key]
265 function App.fake_key_press(key)
266 App.fake_keys_pressed[key] = true
268 function App.fake_key_release(key)
269 App.fake_keys_pressed[key] = nil
272 -- Tests mostly will invoke mouse handlers directly. However, you'll
273 -- occasionally need to check if a mouse button is down outside a handler.
274 -- If you use App.mouse_down instead of love.mouse.isDown, tests will be able to
275 -- simulate mouse clicks using App.fake_mouse_press and App.fake_mouse_release
276 -- below. This isn't very realistic, though, and it's up to tests to
277 -- orchestrate presses that correspond to the handlers they invoke.
279 App.fake_mouse_state = {x=-1, y=-1} -- x,y always set
281 function App.mouse_move(x,y)
282 App.fake_mouse_state.x = x
283 App.fake_mouse_state.y = y
285 function App.mouse_down(mouse_button)
286 return App.fake_mouse_state[mouse_button]
288 function App.mouse_x()
289 return App.fake_mouse_state.x
291 function App.mouse_y()
292 return App.fake_mouse_state.y
295 function App.fake_mouse_press(x,y, mouse_button)
296 App.fake_mouse_state.x = x
297 App.fake_mouse_state.y = y
298 App.fake_mouse_state[mouse_button] = true
300 function App.fake_mouse_release(x,y, mouse_button)
301 App.fake_mouse_state.x = x
302 App.fake_mouse_state.y = y
303 App.fake_mouse_state[mouse_button] = nil
306 -- If you use App.open_for_reading and App.open_for_writing instead of other
307 -- various Lua and LÖVE helpers, tests will be able to check the results of
308 -- file operations inside the App.filesystem table.
310 function App.open_for_reading(filename)
311 if App.filesystem[filename] then
312 return {
313 lines = function(self)
314 return App.filesystem[filename]:gmatch('[^\n]+')
315 end,
316 read = function(self)
317 return App.filesystem[filename]
318 end,
319 close = function(self)
320 end,
325 function App.read_file(filename)
326 return App.filesystem[filename]
329 function App.open_for_writing(filename)
330 App.filesystem[filename] = ''
331 return {
332 write = function(self, s)
333 App.filesystem[filename] = App.filesystem[filename]..s
334 end,
335 close = function(self)
336 end,
340 function App.write_file(filename, contents)
341 App.filesystem[filename] = contents
342 return --[[status]] true
345 function App.mkdir(dirname)
346 -- nothing in test mode
349 function App.remove(filename)
350 App.filesystem[filename] = nil
353 -- Some helpers to trigger an event and then refresh the screen. Akin to one
354 -- iteration of the event loop.
356 -- all textinput events are also keypresses
357 -- TODO: handle chords of multiple keys
358 function App.run_after_textinput(t)
359 App.keypressed(t)
360 App.textinput(t)
361 App.keyreleased(t)
362 App.screen.contents = {}
363 App.draw()
366 -- not all keys are textinput
367 -- TODO: handle chords of multiple keys
368 function App.run_after_keychord(chord)
369 App.keychord_press(chord)
370 App.keyreleased(chord)
371 App.screen.contents = {}
372 App.draw()
375 function App.run_after_mouse_click(x,y, mouse_button)
376 App.fake_mouse_press(x,y, mouse_button)
377 App.mousepressed(x,y, mouse_button)
378 App.fake_mouse_release(x,y, mouse_button)
379 App.mousereleased(x,y, mouse_button)
380 App.screen.contents = {}
381 App.draw()
384 function App.run_after_mouse_press(x,y, mouse_button)
385 App.fake_mouse_press(x,y, mouse_button)
386 App.mousepressed(x,y, mouse_button)
387 App.screen.contents = {}
388 App.draw()
391 function App.run_after_mouse_release(x,y, mouse_button)
392 App.fake_mouse_release(x,y, mouse_button)
393 App.mousereleased(x,y, mouse_button)
394 App.screen.contents = {}
395 App.draw()
398 -- miscellaneous internal helpers
400 function App.color(color)
401 love.graphics.setColor(color.r, color.g, color.b, color.a)
404 -- prepend file/line/test
405 function prepend_debug_info_to_test_failure(test_name, err)
406 local err_without_line_number = err:gsub('^[^:]*:[^:]*: ', '')
407 local stack_trace = debug.traceback('', --[[stack frame]]5)
408 local file_and_line_number = stack_trace:gsub('stack traceback:\n', ''):gsub(': .*', '')
409 local full_error = file_and_line_number..':'..test_name..' -- '..err_without_line_number
410 --? local full_error = file_and_line_number..':'..test_name..' -- '..err_without_line_number..'\t\t'..stack_trace:gsub('\n', '\n\t\t')
411 table.insert(Test_errors, full_error)
414 nativefs = require 'nativefs'
416 local Keys_down = {}
418 -- call this once all tests are run
419 -- can't run any tests after this
420 function App.disable_tests()
421 -- have LÖVE delegate all handlers to App if they exist
422 -- make sure to late-bind handlers like LÖVE's defaults do
423 for name in pairs(love.handlers) do
424 if App[name] then
425 -- love.keyboard.isDown doesn't work on Android, so emulate it using
426 -- keypressed and keyreleased events
427 if name == 'keypressed' then
428 love.handlers[name] = function(key, scancode, isrepeat)
429 Keys_down[key] = true
430 return App.keypressed(key, scancode, isrepeat)
432 elseif name == 'keyreleased' then
433 love.handlers[name] = function(key, scancode)
434 Keys_down[key] = nil
435 return App.keyreleased(key, scancode)
437 else
438 love.handlers[name] = function(...) App[name](...) end
443 -- test methods are disallowed outside tests
444 App.run_tests = nil
445 App.disable_tests = nil
446 App.screen.init = nil
447 App.filesystem = nil
448 App.time = nil
449 App.run_after_textinput = nil
450 App.run_after_keychord = nil
451 App.keypress = nil
452 App.keyrelease = nil
453 App.run_after_mouse_click = nil
454 App.run_after_mouse_press = nil
455 App.run_after_mouse_release = nil
456 App.fake_keys_pressed = nil
457 App.fake_key_press = nil
458 App.fake_key_release = nil
459 App.fake_mouse_state = nil
460 App.fake_mouse_press = nil
461 App.fake_mouse_release = nil
462 -- other methods dispatch to real hardware
463 App.screen.resize = love.window.setMode
464 App.screen.size = love.window.getMode
465 App.screen.move = love.window.setPosition
466 App.screen.position = love.window.getPosition
467 App.screen.print = love.graphics.print
468 App.open_for_reading =
469 function(filename)
470 local result = nativefs.newFile(filename)
471 local ok, err = result:open('r')
472 if ok then
473 return result
474 else
475 return ok, err
478 App.read_file =
479 function(path)
480 if not is_absolute_path(path) then
481 return --[[status]] false, 'Please use an unambiguous absolute path.'
483 local f, err = App.open_for_reading(path)
484 if err then
485 return --[[status]] false, err
487 local contents = f:read()
488 f:close()
489 return contents
491 App.open_for_writing =
492 function(filename)
493 local result = nativefs.newFile(filename)
494 local ok, err = result:open('w')
495 if ok then
496 return result
497 else
498 return ok, err
501 App.write_file =
502 function(path, contents)
503 if not is_absolute_path(path) then
504 return --[[status]] false, 'Please use an unambiguous absolute path.'
506 local f, err = App.open_for_writing(path)
507 if err then
508 return --[[status]] false, err
510 f:write(contents)
511 f:close()
512 return --[[status]] true
514 App.files = nativefs.getDirectoryItems
515 App.file_info = nativefs.getInfo
516 App.mkdir = nativefs.createDirectory
517 App.remove = nativefs.remove
518 App.source_dir = love.filesystem.getSource()..'/' -- '/' should work even on Windows
519 App.current_dir = nativefs.getWorkingDirectory()..'/'
520 App.save_dir = love.filesystem.getSaveDirectory()..'/'
521 App.get_time = love.timer.getTime
522 App.get_clipboard = love.system.getClipboardText
523 App.set_clipboard = love.system.setClipboardText
524 App.key_down = function(key) return Keys_down[key] end
525 App.mouse_move = love.mouse.setPosition
526 App.mouse_down = love.mouse.isDown
527 App.mouse_x = love.mouse.getX
528 App.mouse_y = love.mouse.getY