use color alpha in button backgrounds
[lines.love.git] / app.lua
blobcf89a37374c7c194b9cf203313b589f91dfe63a8
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 Error_message = debug.traceback('Error: ' .. tostring(err), --[[stack frame]]2):gsub('\n[^\n]+$', '')
47 print(Error_message)
48 if Current_app == 'run' then
49 Settings.current_app = 'source'
50 love.filesystem.write('config', json.encode(Settings))
51 load_file_from_source_or_save_directory('main.lua')
52 App.undo_initialize()
53 App.run_tests_and_initialize()
54 else
55 love.event.quit()
56 end
57 end
59 -- The rest of this file wraps around various LÖVE primitives to support
60 -- automated tests. Often tests will run with a fake version of a primitive
61 -- that redirects to the real love.* version once we're done with tests.
63 -- Not everything is so wrapped yet. Sometimes you still have to use love.*
64 -- primitives directly.
66 App = {}
68 -- save/restore various framework globals we care about -- only on very first load
69 function App.snapshot_love()
70 if Love_snapshot then return end
71 Love_snapshot = {}
72 -- save the entire initial font; it doesn't seem reliably recreated using newFont
73 Love_snapshot.initial_font = love.graphics.getFont()
74 end
76 function App.undo_initialize()
77 love.graphics.setFont(Love_snapshot.initial_font)
78 end
80 function App.run_tests_and_initialize()
81 App.load()
82 Test_errors = {}
83 App.run_tests()
84 if #Test_errors > 0 then
85 error(('There were %d test failures:\n\n%s'):format(#Test_errors, table.concat(Test_errors)))
86 end
87 App.disable_tests()
88 App.initialize_globals()
89 App.initialize(love.arg.parseGameArguments(arg), arg)
90 end
92 function App.run_tests()
93 local sorted_names = {}
94 for name,binding in pairs(_G) do
95 if name:find('test_') == 1 then
96 table.insert(sorted_names, name)
97 end
98 end
99 table.sort(sorted_names)
100 for _,name in ipairs(sorted_names) do
101 App.initialize_for_test()
102 --? print('=== '..name)
103 --? _G[name]()
104 xpcall(_G[name], function(err) prepend_debug_info_to_test_failure(name, err) end)
106 -- clean up all test methods
107 for _,name in ipairs(sorted_names) do
108 _G[name] = nil
112 function App.initialize_for_test()
113 App.screen.init{width=100, height=50}
114 App.screen.contents = {} -- clear screen
115 App.filesystem = {}
116 App.source_dir = ''
117 App.current_dir = ''
118 App.save_dir = ''
119 App.fake_keys_pressed = {}
120 App.fake_mouse_state = {x=-1, y=-1}
121 App.initialize_globals()
124 -- App.screen.resize and App.screen.move seem like better names than
125 -- love.window.setMode and love.window.setPosition respectively. They'll
126 -- be side-effect-free during tests, and they'll save their results in
127 -- attributes of App.screen for easy access.
129 App.screen={}
131 -- Use App.screen.init in tests to initialize the fake screen.
132 function App.screen.init(dims)
133 App.screen.width = dims.width
134 App.screen.height = dims.height
137 function App.screen.resize(width, height, flags)
138 App.screen.width = width
139 App.screen.height = height
140 App.screen.flags = flags
143 function App.screen.size()
144 return App.screen.width, App.screen.height, App.screen.flags
147 function App.screen.move(x,y, displayindex)
148 App.screen.x = x
149 App.screen.y = y
150 App.screen.displayindex = displayindex
153 function App.screen.position()
154 return App.screen.x, App.screen.y, App.screen.displayindex
157 -- If you use App.screen.print instead of love.graphics.print,
158 -- tests will be able to check what was printed using App.screen.check below.
160 -- One drawback of this approach: the y coordinate used depends on font size,
161 -- which feels brittle.
163 function App.screen.print(msg, x,y)
164 local screen_row = 'y'..tostring(y)
165 --? print('drawing "'..msg..'" at y '..tostring(y))
166 local screen = App.screen
167 if screen.contents[screen_row] == nil then
168 screen.contents[screen_row] = {}
169 for i=0,screen.width-1 do
170 screen.contents[screen_row][i] = ''
173 if x < screen.width then
174 screen.contents[screen_row][x] = msg
178 function App.screen.check(y, expected_contents, msg)
179 --? print('checking for "'..expected_contents..'" at y '..tostring(y))
180 local screen_row = 'y'..tostring(y)
181 local contents = ''
182 if App.screen.contents[screen_row] == nil then
183 error('no text at y '..tostring(y))
185 for i,s in ipairs(App.screen.contents[screen_row]) do
186 contents = contents..s
188 check_eq(contents, expected_contents, msg)
191 -- If you access the time using App.get_time instead of love.timer.getTime,
192 -- tests will be able to move the time back and forwards as needed using
193 -- App.wait_fake_time below.
195 App.time = 1
196 function App.get_time()
197 return App.time
199 function App.wait_fake_time(t)
200 App.time = App.time + t
203 function App.width(text)
204 return love.graphics.getFont():getWidth(text)
207 -- If you access the clipboard using App.get_clipboard and App.set_clipboard
208 -- instead of love.system.getClipboardText and love.system.setClipboardText
209 -- respectively, tests will be able to manipulate the clipboard by
210 -- reading/writing App.clipboard.
212 App.clipboard = ''
213 function App.get_clipboard()
214 return App.clipboard
216 function App.set_clipboard(s)
217 App.clipboard = s
220 -- In tests I mostly send chords all at once to the keyboard handlers.
221 -- However, you'll occasionally need to check if a key is down outside a handler.
222 -- If you use App.key_down instead of love.keyboard.isDown, tests will be able to
223 -- simulate keypresses using App.fake_key_press and App.fake_key_release
224 -- below. This isn't very realistic, though, and it's up to tests to
225 -- orchestrate key presses that correspond to the handlers they invoke.
227 App.fake_keys_pressed = {}
228 function App.key_down(key)
229 return App.fake_keys_pressed[key]
232 function App.fake_key_press(key)
233 App.fake_keys_pressed[key] = true
235 function App.fake_key_release(key)
236 App.fake_keys_pressed[key] = nil
239 -- Tests mostly will invoke mouse handlers directly. However, you'll
240 -- occasionally need to check if a mouse button is down outside a handler.
241 -- If you use App.mouse_down instead of love.mouse.isDown, tests will be able to
242 -- simulate mouse clicks using App.fake_mouse_press and App.fake_mouse_release
243 -- below. This isn't very realistic, though, and it's up to tests to
244 -- orchestrate presses that correspond to the handlers they invoke.
246 App.fake_mouse_state = {x=-1, y=-1} -- x,y always set
248 function App.mouse_move(x,y)
249 App.fake_mouse_state.x = x
250 App.fake_mouse_state.y = y
252 function App.mouse_down(mouse_button)
253 return App.fake_mouse_state[mouse_button]
255 function App.mouse_x()
256 return App.fake_mouse_state.x
258 function App.mouse_y()
259 return App.fake_mouse_state.y
262 function App.fake_mouse_press(x,y, mouse_button)
263 App.fake_mouse_state.x = x
264 App.fake_mouse_state.y = y
265 App.fake_mouse_state[mouse_button] = true
267 function App.fake_mouse_release(x,y, mouse_button)
268 App.fake_mouse_state.x = x
269 App.fake_mouse_state.y = y
270 App.fake_mouse_state[mouse_button] = nil
273 -- If you use App.open_for_reading and App.open_for_writing instead of other
274 -- various Lua and LÖVE helpers, tests will be able to check the results of
275 -- file operations inside the App.filesystem table.
277 function App.open_for_reading(filename)
278 if App.filesystem[filename] then
279 return {
280 lines = function(self)
281 return App.filesystem[filename]:gmatch('[^\n]+')
282 end,
283 read = function(self)
284 return App.filesystem[filename]
285 end,
286 close = function(self)
287 end,
292 function App.read_file(filename)
293 return App.filesystem[filename]
296 function App.open_for_writing(filename)
297 App.filesystem[filename] = ''
298 return {
299 write = function(self, s)
300 App.filesystem[filename] = App.filesystem[filename]..s
301 end,
302 close = function(self)
303 end,
307 function App.write_file(filename, contents)
308 App.filesystem[filename] = contents
309 return --[[status]] true
312 function App.mkdir(dirname)
313 -- nothing in test mode
316 function App.remove(filename)
317 App.filesystem[filename] = nil
320 -- Some helpers to trigger an event and then refresh the screen. Akin to one
321 -- iteration of the event loop.
323 -- all textinput events are also keypresses
324 -- TODO: handle chords of multiple keys
325 function App.run_after_textinput(t)
326 App.keypressed(t)
327 App.textinput(t)
328 App.keyreleased(t)
329 App.screen.contents = {}
330 App.draw()
333 -- not all keys are textinput
334 -- TODO: handle chords of multiple keys
335 function App.run_after_keychord(chord)
336 App.keychord_press(chord)
337 App.keyreleased(chord)
338 App.screen.contents = {}
339 App.draw()
342 function App.run_after_mouse_click(x,y, mouse_button)
343 App.fake_mouse_press(x,y, mouse_button)
344 App.mousepressed(x,y, mouse_button)
345 App.fake_mouse_release(x,y, mouse_button)
346 App.mousereleased(x,y, mouse_button)
347 App.screen.contents = {}
348 App.draw()
351 function App.run_after_mouse_press(x,y, mouse_button)
352 App.fake_mouse_press(x,y, mouse_button)
353 App.mousepressed(x,y, mouse_button)
354 App.screen.contents = {}
355 App.draw()
358 function App.run_after_mouse_release(x,y, mouse_button)
359 App.fake_mouse_release(x,y, mouse_button)
360 App.mousereleased(x,y, mouse_button)
361 App.screen.contents = {}
362 App.draw()
365 -- miscellaneous internal helpers
367 function App.color(color)
368 love.graphics.setColor(color.r, color.g, color.b, color.a)
371 -- prepend file/line/test
372 function prepend_debug_info_to_test_failure(test_name, err)
373 local err_without_line_number = err:gsub('^[^:]*:[^:]*: ', '')
374 local stack_trace = debug.traceback('', --[[stack frame]]5)
375 local file_and_line_number = stack_trace:gsub('stack traceback:\n', ''):gsub(': .*', '')
376 local full_error = file_and_line_number..':'..test_name..' -- '..err_without_line_number
377 --? local full_error = file_and_line_number..':'..test_name..' -- '..err_without_line_number..'\t\t'..stack_trace:gsub('\n', '\n\t\t')
378 table.insert(Test_errors, full_error)
381 nativefs = require 'nativefs'
383 local Keys_down = {}
385 -- call this once all tests are run
386 -- can't run any tests after this
387 function App.disable_tests()
388 -- have LÖVE delegate all handlers to App if they exist
389 for name in pairs(love.handlers) do
390 if App[name] then
391 -- love.keyboard.isDown doesn't work on Android, so emulate it using
392 -- keypressed and keyreleased events
393 if name == 'keypressed' then
394 love.handlers[name] = function(key, scancode, isrepeat)
395 Keys_down[key] = true
396 return App.keypressed(key, scancode, isrepeat)
398 elseif name == 'keyreleased' then
399 love.handlers[name] = function(key, scancode)
400 Keys_down[key] = nil
401 return App.keyreleased(key, scancode)
403 else
404 love.handlers[name] = App[name]
409 -- test methods are disallowed outside tests
410 App.run_tests = nil
411 App.disable_tests = nil
412 App.screen.init = nil
413 App.filesystem = nil
414 App.time = nil
415 App.run_after_textinput = nil
416 App.run_after_keychord = nil
417 App.keypress = nil
418 App.keyrelease = nil
419 App.run_after_mouse_click = nil
420 App.run_after_mouse_press = nil
421 App.run_after_mouse_release = nil
422 App.fake_keys_pressed = nil
423 App.fake_key_press = nil
424 App.fake_key_release = nil
425 App.fake_mouse_state = nil
426 App.fake_mouse_press = nil
427 App.fake_mouse_release = nil
428 -- other methods dispatch to real hardware
429 App.screen.resize = love.window.setMode
430 App.screen.size = love.window.getMode
431 App.screen.move = love.window.setPosition
432 App.screen.position = love.window.getPosition
433 App.screen.print = love.graphics.print
434 App.open_for_reading =
435 function(filename)
436 local result = nativefs.newFile(filename)
437 local ok, err = result:open('r')
438 if ok then
439 return result
440 else
441 return ok, err
444 App.read_file =
445 function(path)
446 if not is_absolute_path(path) then
447 return --[[status]] false, 'Please use an unambiguous absolute path.'
449 local f, err = App.open_for_reading(path)
450 if err then
451 return --[[status]] false, err
453 local contents = f:read()
454 f:close()
455 return contents
457 App.open_for_writing =
458 function(filename)
459 local result = nativefs.newFile(filename)
460 local ok, err = result:open('w')
461 if ok then
462 return result
463 else
464 return ok, err
467 App.write_file =
468 function(path, contents)
469 if not is_absolute_path(path) then
470 return --[[status]] false, 'Please use an unambiguous absolute path.'
472 local f, err = App.open_for_writing(path)
473 if err then
474 return --[[status]] false, err
476 f:write(contents)
477 f:close()
478 return --[[status]] true
480 App.files = nativefs.getDirectoryItems
481 App.mkdir = nativefs.createDirectory
482 App.remove = nativefs.remove
483 App.source_dir = love.filesystem.getSource()..'/'
484 App.current_dir = nativefs.getWorkingDirectory()..'/'
485 App.save_dir = love.filesystem.getSaveDirectory()..'/'
486 App.get_time = love.timer.getTime
487 App.get_clipboard = love.system.getClipboardText
488 App.set_clipboard = love.system.setClipboardText
489 App.key_down = function(key) return Keys_down[key] end
490 App.mouse_move = love.mouse.setPosition
491 App.mouse_down = love.mouse.isDown
492 App.mouse_x = love.mouse.getX
493 App.mouse_y = love.mouse.getY